@xuda.io/runtime-bundle
Version:
The Xuda Runtime Bundle refers to a collection of scripts and libraries packaged together to provide the necessary runtime environment for executing plugins or components in the Xuda platform.
52,971 lines • 1.98 MB
JavaScript
/*! css.js 27-02-2018 */
!(function (e) {
"use strict";
var t = function () {
(this.cssImportStatements = []),
(this.cssKeyframeStatements = []),
(this.cssRegex = new RegExp("([\\s\\S]*?){([\\s\\S]*?)}", "gi")),
(this.cssMediaQueryRegex = "((@media [\\s\\S]*?){([\\s\\S]*?}\\s*?)})"),
(this.cssKeyframeRegex =
"((@.*?keyframes [\\s\\S]*?){([\\s\\S]*?}\\s*?)})"),
(this.combinedCSSRegex =
"((\\s*?(?:\\/\\*[\\s\\S]*?\\*\\/)?\\s*?@media[\\s\\S]*?){([\\s\\S]*?)}\\s*?})|(([\\s\\S]*?){([\\s\\S]*?)})"),
(this.cssCommentsRegex = "(\\/\\*[\\s\\S]*?\\*\\/)"),
(this.cssImportStatementRegex = new RegExp("@import .*?;", "gi"));
};
(t.prototype.stripComments = function (e) {
var t = new RegExp(this.cssCommentsRegex, "gi");
return e.replace(t, "");
}),
(t.prototype.parseCSS = function (e) {
if (void 0 === e) return [];
for (var t = []; ; ) {
var s = this.cssImportStatementRegex.exec(e);
if (null === s) break;
this.cssImportStatements.push(s[0]),
t.push({ selector: "@imports", type: "imports", styles: s[0] });
}
e = e.replace(this.cssImportStatementRegex, "");
for (
var r, i = new RegExp(this.cssKeyframeRegex, "gi");
null !== (r = i.exec(e));
)
t.push({ selector: "@keyframes", type: "keyframes", styles: r[0] });
e = e.replace(i, "");
for (
var n = new RegExp(this.combinedCSSRegex, "gi");
null !== (r = n.exec(e));
) {
var o = "";
o =
void 0 === r[2]
? r[5].split("\r\n").join("\n").trim()
: r[2].split("\r\n").join("\n").trim();
var l = new RegExp(this.cssCommentsRegex, "gi"),
p = l.exec(o);
if (
(null !== p && (o = o.replace(l, "").trim()),
-1 !== (o = o.replace(/\n+/, "\n")).indexOf("@media"))
) {
var a = {
selector: o,
type: "media",
subStyles: this.parseCSS(r[3] + "\n}"),
};
null !== p && (a.comments = p[0]), t.push(a);
} else {
var c = { selector: o, rules: this.parseRules(r[6]) };
"@font-face" === o && (c.type = "font-face"),
null !== p && (c.comments = p[0]),
t.push(c);
}
}
return t;
}),
(t.prototype.parseRules = function (e) {
var t = [];
e = (e = e.split("\r\n").join("\n")).split(";");
for (var s = 0; s < e.length; s++) {
var r = e[s];
if (-1 !== (r = r.trim()).indexOf(":")) {
var i = (r = r.split(":"))[0].trim(),
n = r.slice(1).join(":").trim();
if (i.length < 1 || n.length < 1) continue;
t.push({ directive: i, value: n });
} else
"base64," === r.trim().substr(0, 7)
? (t[t.length - 1].value += r.trim())
: r.length > 0 &&
t.push({ directive: "", value: r, defective: !0 });
}
return t;
}),
(t.prototype.findCorrespondingRule = function (e, t, s) {
void 0 === s && (s = !1);
for (
var r = !1, i = 0;
i < e.length &&
(e[i].directive !== t || ((r = e[i]), s !== e[i].value));
i++
);
return r;
}),
(t.prototype.findBySelector = function (e, t, s) {
void 0 === s && (s = !1);
for (var r = [], i = 0; i < e.length; i++)
!1 === s
? e[i].selector === t && r.push(e[i])
: -1 !== e[i].selector.indexOf(t) && r.push(e[i]);
if ("@imports" === t || r.length < 2) return r;
var n = r[0];
for (i = 1; i < r.length; i++) this.intelligentCSSPush([n], r[i]);
return [n];
}),
(t.prototype.deleteBySelector = function (e, t) {
for (var s = [], r = 0; r < e.length; r++)
e[r].selector !== t && s.push(e[r]);
return s;
}),
(t.prototype.compressCSS = function (e) {
for (var t = [], s = {}, r = 0; r < e.length; r++) {
var i = e[r];
if (!0 !== s[i.selector]) {
var n = this.findBySelector(e, i.selector);
0 !== n.length && ((t = t.concat(n)), (s[i.selector] = !0));
}
}
return t;
}),
(t.prototype.cssDiff = function (e, t) {
if (e.selector !== t.selector) return !1;
if ("media" === e.type || "media" === t.type) return !1;
for (
var s, r, i = { selector: e.selector, rules: [] }, n = 0;
n < e.rules.length;
n++
)
(s = e.rules[n]),
!1 === (r = this.findCorrespondingRule(t.rules, s.directive, s.value))
? i.rules.push(s)
: s.value !== r.value && i.rules.push(s);
for (var o = 0; o < t.rules.length; o++)
(r = t.rules[o]),
!1 === (s = this.findCorrespondingRule(e.rules, r.directive)) &&
((r.type = "DELETED"), i.rules.push(r));
return 0 !== i.rules.length && i;
}),
(t.prototype.intelligentMerge = function (e, t, s) {
void 0 === s && (s = !1);
for (var r = 0; r < t.length; r++) this.intelligentCSSPush(e, t[r], s);
for (r = 0; r < e.length; r++) {
var i = e[r];
"media" !== i.type &&
"keyframes" !== i.type &&
(i.rules = this.compactRules(i.rules));
}
}),
(t.prototype.intelligentCSSPush = function (e, t, s) {
var r = t.selector,
i = !1;
if ((void 0 === s && (s = !1), !1 === s)) {
for (var n = 0; n < e.length; n++)
if (e[n].selector === r) {
i = e[n];
break;
}
} else
for (var o = e.length - 1; o > -1; o--)
if (e[o].selector === r) {
i = e[o];
break;
}
if (!1 === i) e.push(t);
else if ("media" !== t.type)
for (var l = 0; l < t.rules.length; l++) {
var p = t.rules[l],
a = this.findCorrespondingRule(i.rules, p.directive);
!1 === a
? i.rules.push(p)
: "DELETED" === p.type
? (a.type = "DELETED")
: (a.value = p.value);
}
else i.subStyles = i.subStyles.concat(t.subStyles);
}),
(t.prototype.compactRules = function (e) {
for (var t = [], s = 0; s < e.length; s++)
"DELETED" !== e[s].type && t.push(e[s]);
return t;
}),
(t.prototype.getCSSForEditor = function (e, t) {
void 0 === t && (t = 0);
var s = "";
void 0 === e && (e = this.css);
for (var r = 0; r < e.length; r++)
"imports" === e[r].type && (s += e[r].styles + "\n\n");
for (r = 0; r < e.length; r++) {
var i = e[r];
if (void 0 !== i.selector) {
var n = "";
void 0 !== i.comments && (n = i.comments + "\n"),
"media" === i.type
? ((s += n + i.selector + "{\n"),
(s += this.getCSSForEditor(i.subStyles, t + 1)),
(s += "}\n\n"))
: "keyframes" !== i.type &&
"imports" !== i.type &&
((s += this.getSpaces(t) + n + i.selector + " {\n"),
(s += this.getCSSOfRules(i.rules, t + 1)),
(s += this.getSpaces(t) + "}\n\n"));
}
}
for (r = 0; r < e.length; r++)
"keyframes" === e[r].type && (s += e[r].styles + "\n\n");
return s;
}),
(t.prototype.getImports = function (e) {
for (var t = [], s = 0; s < e.length; s++)
"imports" === e[s].type && t.push(e[s].styles);
return t;
}),
(t.prototype.getCSSOfRules = function (e, t) {
for (var s = "", r = 0; r < e.length; r++)
void 0 !== e[r] &&
(void 0 === e[r].defective
? (s +=
this.getSpaces(t) + e[r].directive + ": " + e[r].value + ";\n")
: (s += this.getSpaces(t) + e[r].value + ";\n"));
return s || "\n";
}),
(t.prototype.getSpaces = function (e) {
for (var t = "", s = 0; s < 4 * e; s++) t += " ";
return t;
}),
(t.prototype.applyNamespacing = function (e, t) {
var s = e,
r = "." + this.cssPreviewNamespace;
void 0 !== t && (r = t), "string" == typeof e && (s = this.parseCSS(e));
for (var i = 0; i < s.length; i++) {
var n = s[i];
if (
!(
n.selector.indexOf("@font-face") > -1 ||
n.selector.indexOf("keyframes") > -1 ||
n.selector.indexOf("@import") > -1 ||
n.selector.indexOf(".form-all") > -1 ||
n.selector.indexOf("#stage") > -1
)
)
if ("media" !== n.type) {
for (
var o = n.selector.split(","), l = [], p = 0;
p < o.length;
p++
)
-1 === o[p].indexOf(".supernova")
? l.push(r + " " + o[p])
: l.push(o[p]);
n.selector = l.join(",");
} else n.subStyles = this.applyNamespacing(n.subStyles, t);
}
return s;
}),
(t.prototype.clearNamespacing = function (e, t) {
void 0 === t && (t = !1);
var s = e,
r = "." + this.cssPreviewNamespace;
"string" == typeof e && (s = this.parseCSS(e));
for (var i = 0; i < s.length; i++) {
var n = s[i];
if ("media" !== n.type) {
for (var o = n.selector.split(","), l = [], p = 0; p < o.length; p++)
l.push(o[p].split(r + " ").join(""));
n.selector = l.join(",");
} else n.subStyles = this.clearNamespacing(n.subStyles, !0);
}
return !1 === t ? this.getCSSForEditor(s) : s;
}),
(t.prototype.createStyleElement = function (e, t, s) {
if (
(void 0 === s && (s = !1),
!1 === this.testMode &&
"nonamespace" !== s &&
(t = this.applyNamespacing(t)),
"string" != typeof t && (t = this.getCSSForEditor(t)),
!0 === s && (t = this.getCSSForEditor(this.parseCSS(t))),
!1 !== this.testMode)
)
return this.testMode("create style #" + e, t);
var r = document.getElementById(e);
r && r.parentNode.removeChild(r);
var i = document.head || document.getElementsByTagName("head")[0],
n = document.createElement("style");
(n.id = e),
(n.type = "text/css"),
i.appendChild(n),
n.styleSheet && !n.sheet
? (n.styleSheet.cssText = t)
: n.appendChild(document.createTextNode(t));
}),
(e.cssjs = t);
})(this);
// PouchDB 9.0.0
//
// (c) 2012-2024 Dale Harvey and the PouchDB team
// PouchDB may be freely distributed under the Apache license, version 2.0.
// For all details and documentation:
// http://pouchdb.com
!(function (e) {
if ("object" == typeof exports && "undefined" != typeof module)
module.exports = e();
else if ("function" == typeof define && define.amd) define([], e);
else {
("undefined" != typeof window
? window
: "undefined" != typeof global
? global
: "undefined" != typeof self
? self
: this
).PouchDB = e();
}
})(function () {
return (function e(t, n, r) {
function i(s, a) {
if (!n[s]) {
if (!t[s]) {
var c = "function" == typeof require && require;
if (!a && c) return c(s, !0);
if (o) return o(s, !0);
var u = new Error("Cannot find module '" + s + "'");
throw ((u.code = "MODULE_NOT_FOUND"), u);
}
var f = (n[s] = { exports: {} });
t[s][0].call(
f.exports,
function (e) {
return i(t[s][1][e] || e);
},
f,
f.exports,
e,
t,
n,
r
);
}
return n[s].exports;
}
for (
var o = "function" == typeof require && require, s = 0;
s < r.length;
s++
)
i(r[s]);
return i;
})(
{
1: [
function (e, t, n) {
var r =
Object.create ||
function (e) {
var t = function () {};
return (t.prototype = e), new t();
},
i =
Object.keys ||
function (e) {
var t = [];
for (var n in e)
Object.prototype.hasOwnProperty.call(e, n) && t.push(n);
return n;
},
o =
Function.prototype.bind ||
function (e) {
var t = this;
return function () {
return t.apply(e, arguments);
};
};
function s() {
(this._events &&
Object.prototype.hasOwnProperty.call(this, "_events")) ||
((this._events = r(null)), (this._eventsCount = 0)),
(this._maxListeners = this._maxListeners || void 0);
}
(t.exports = s),
(s.EventEmitter = s),
(s.prototype._events = void 0),
(s.prototype._maxListeners = void 0);
var a,
c = 10;
try {
var u = {};
Object.defineProperty &&
Object.defineProperty(u, "x", { value: 0 }),
(a = 0 === u.x);
} catch (e) {
a = !1;
}
function f(e) {
return void 0 === e._maxListeners
? s.defaultMaxListeners
: e._maxListeners;
}
function l(e, t, n) {
if (t) e.call(n);
else
for (var r = e.length, i = w(e, r), o = 0; o < r; ++o)
i[o].call(n);
}
function d(e, t, n, r) {
if (t) e.call(n, r);
else
for (var i = e.length, o = w(e, i), s = 0; s < i; ++s)
o[s].call(n, r);
}
function h(e, t, n, r, i) {
if (t) e.call(n, r, i);
else
for (var o = e.length, s = w(e, o), a = 0; a < o; ++a)
s[a].call(n, r, i);
}
function p(e, t, n, r, i, o) {
if (t) e.call(n, r, i, o);
else
for (var s = e.length, a = w(e, s), c = 0; c < s; ++c)
a[c].call(n, r, i, o);
}
function v(e, t, n, r) {
if (t) e.apply(n, r);
else
for (var i = e.length, o = w(e, i), s = 0; s < i; ++s)
o[s].apply(n, r);
}
function _(e, t, n, i) {
var o, s, a;
if ("function" != typeof n)
throw new TypeError('"listener" argument must be a function');
if (
((s = e._events)
? (s.newListener &&
(e.emit("newListener", t, n.listener ? n.listener : n),
(s = e._events)),
(a = s[t]))
: ((s = e._events = r(null)), (e._eventsCount = 0)),
a)
) {
if (
("function" == typeof a
? (a = s[t] = i ? [n, a] : [a, n])
: i
? a.unshift(n)
: a.push(n),
!a.warned && (o = f(e)) && o > 0 && a.length > o)
) {
a.warned = !0;
var c = new Error(
"Possible EventEmitter memory leak detected. " +
a.length +
' "' +
String(t) +
'" listeners added. Use emitter.setMaxListeners() to increase limit.'
);
(c.name = "MaxListenersExceededWarning"),
(c.emitter = e),
(c.type = t),
(c.count = a.length),
"object" == typeof console &&
console.warn &&
console.warn("%s: %s", c.name, c.message);
}
} else (a = s[t] = n), ++e._eventsCount;
return e;
}
function y() {
if (!this.fired)
switch (
(this.target.removeListener(this.type, this.wrapFn),
(this.fired = !0),
arguments.length)
) {
case 0:
return this.listener.call(this.target);
case 1:
return this.listener.call(this.target, arguments[0]);
case 2:
return this.listener.call(
this.target,
arguments[0],
arguments[1]
);
case 3:
return this.listener.call(
this.target,
arguments[0],
arguments[1],
arguments[2]
);
default:
for (
var e = new Array(arguments.length), t = 0;
t < e.length;
++t
)
e[t] = arguments[t];
this.listener.apply(this.target, e);
}
}
function g(e, t, n) {
var r = {
fired: !1,
wrapFn: void 0,
target: e,
type: t,
listener: n,
},
i = o.call(y, r);
return (i.listener = n), (r.wrapFn = i), i;
}
function m(e, t, n) {
var r = e._events;
if (!r) return [];
var i = r[t];
return i
? "function" == typeof i
? n
? [i.listener || i]
: [i]
: n
? (function (e) {
for (var t = new Array(e.length), n = 0; n < t.length; ++n)
t[n] = e[n].listener || e[n];
return t;
})(i)
: w(i, i.length)
: [];
}
function b(e) {
var t = this._events;
if (t) {
var n = t[e];
if ("function" == typeof n) return 1;
if (n) return n.length;
}
return 0;
}
function w(e, t) {
for (var n = new Array(t), r = 0; r < t; ++r) n[r] = e[r];
return n;
}
a
? Object.defineProperty(s, "defaultMaxListeners", {
enumerable: !0,
get: function () {
return c;
},
set: function (e) {
if ("number" != typeof e || e < 0 || e != e)
throw new TypeError(
'"defaultMaxListeners" must be a positive number'
);
c = e;
},
})
: (s.defaultMaxListeners = c),
(s.prototype.setMaxListeners = function (e) {
if ("number" != typeof e || e < 0 || isNaN(e))
throw new TypeError('"n" argument must be a positive number');
return (this._maxListeners = e), this;
}),
(s.prototype.getMaxListeners = function () {
return f(this);
}),
(s.prototype.emit = function (e) {
var t,
n,
r,
i,
o,
s,
a = "error" === e;
if ((s = this._events)) a = a && null == s.error;
else if (!a) return !1;
if (a) {
if (
(arguments.length > 1 && (t = arguments[1]),
t instanceof Error)
)
throw t;
var c = new Error('Unhandled "error" event. (' + t + ")");
throw ((c.context = t), c);
}
if (!(n = s[e])) return !1;
var u = "function" == typeof n;
switch ((r = arguments.length)) {
case 1:
l(n, u, this);
break;
case 2:
d(n, u, this, arguments[1]);
break;
case 3:
h(n, u, this, arguments[1], arguments[2]);
break;
case 4:
p(n, u, this, arguments[1], arguments[2], arguments[3]);
break;
default:
for (i = new Array(r - 1), o = 1; o < r; o++)
i[o - 1] = arguments[o];
v(n, u, this, i);
}
return !0;
}),
(s.prototype.addListener = function (e, t) {
return _(this, e, t, !1);
}),
(s.prototype.on = s.prototype.addListener),
(s.prototype.prependListener = function (e, t) {
return _(this, e, t, !0);
}),
(s.prototype.once = function (e, t) {
if ("function" != typeof t)
throw new TypeError('"listener" argument must be a function');
return this.on(e, g(this, e, t)), this;
}),
(s.prototype.prependOnceListener = function (e, t) {
if ("function" != typeof t)
throw new TypeError('"listener" argument must be a function');
return this.prependListener(e, g(this, e, t)), this;
}),
(s.prototype.removeListener = function (e, t) {
var n, i, o, s, a;
if ("function" != typeof t)
throw new TypeError('"listener" argument must be a function');
if (!(i = this._events)) return this;
if (!(n = i[e])) return this;
if (n === t || n.listener === t)
0 == --this._eventsCount
? (this._events = r(null))
: (delete i[e],
i.removeListener &&
this.emit("removeListener", e, n.listener || t));
else if ("function" != typeof n) {
for (o = -1, s = n.length - 1; s >= 0; s--)
if (n[s] === t || n[s].listener === t) {
(a = n[s].listener), (o = s);
break;
}
if (o < 0) return this;
0 === o
? n.shift()
: (function (e, t) {
for (
var n = t, r = n + 1, i = e.length;
r < i;
n += 1, r += 1
)
e[n] = e[r];
e.pop();
})(n, o),
1 === n.length && (i[e] = n[0]),
i.removeListener && this.emit("removeListener", e, a || t);
}
return this;
}),
(s.prototype.removeAllListeners = function (e) {
var t, n, o;
if (!(n = this._events)) return this;
if (!n.removeListener)
return (
0 === arguments.length
? ((this._events = r(null)), (this._eventsCount = 0))
: n[e] &&
(0 == --this._eventsCount
? (this._events = r(null))
: delete n[e]),
this
);
if (0 === arguments.length) {
var s,
a = i(n);
for (o = 0; o < a.length; ++o)
"removeListener" !== (s = a[o]) && this.removeAllListeners(s);
return (
this.removeAllListeners("removeListener"),
(this._events = r(null)),
(this._eventsCount = 0),
this
);
}
if ("function" == typeof (t = n[e])) this.removeListener(e, t);
else if (t)
for (o = t.length - 1; o >= 0; o--)
this.removeListener(e, t[o]);
return this;
}),
(s.prototype.listeners = function (e) {
return m(this, e, !0);
}),
(s.prototype.rawListeners = function (e) {
return m(this, e, !1);
}),
(s.listenerCount = function (e, t) {
return "function" == typeof e.listenerCount
? e.listenerCount(t)
: b.call(e, t);
}),
(s.prototype.listenerCount = b),
(s.prototype.eventNames = function () {
return this._eventsCount > 0 ? Reflect.ownKeys(this._events) : [];
});
},
{},
],
2: [
function (e, t, n) {
var r,
i,
o = (t.exports = {});
function s() {
throw new Error("setTimeout has not been defined");
}
function a() {
throw new Error("clearTimeout has not been defined");
}
function c(e) {
if (r === setTimeout) return setTimeout(e, 0);
if ((r === s || !r) && setTimeout)
return (r = setTimeout), setTimeout(e, 0);
try {
return r(e, 0);
} catch (t) {
try {
return r.call(null, e, 0);
} catch (t) {
return r.call(this, e, 0);
}
}
}
!(function () {
try {
r = "function" == typeof setTimeout ? setTimeout : s;
} catch (e) {
r = s;
}
try {
i = "function" == typeof clearTimeout ? clearTimeout : a;
} catch (e) {
i = a;
}
})();
var u,
f = [],
l = !1,
d = -1;
function h() {
l &&
u &&
((l = !1),
u.length ? (f = u.concat(f)) : (d = -1),
f.length && p());
}
function p() {
if (!l) {
var e = c(h);
l = !0;
for (var t = f.length; t; ) {
for (u = f, f = []; ++d < t; ) u && u[d].run();
(d = -1), (t = f.length);
}
(u = null),
(l = !1),
(function (e) {
if (i === clearTimeout) return clearTimeout(e);
if ((i === a || !i) && clearTimeout)
return (i = clearTimeout), clearTimeout(e);
try {
i(e);
} catch (t) {
try {
return i.call(null, e);
} catch (t) {
return i.call(this, e);
}
}
})(e);
}
}
function v(e, t) {
(this.fun = e), (this.array = t);
}
function _() {}
(o.nextTick = function (e) {
var t = new Array(arguments.length - 1);
if (arguments.length > 1)
for (var n = 1; n < arguments.length; n++)
t[n - 1] = arguments[n];
f.push(new v(e, t)), 1 !== f.length || l || c(p);
}),
(v.prototype.run = function () {
this.fun.apply(null, this.array);
}),
(o.title = "browser"),
(o.browser = !0),
(o.env = {}),
(o.argv = []),
(o.version = ""),
(o.versions = {}),
(o.on = _),
(o.addListener = _),
(o.once = _),
(o.off = _),
(o.removeListener = _),
(o.removeAllListeners = _),
(o.emit = _),
(o.prependListener = _),
(o.prependOnceListener = _),
(o.listeners = function (e) {
return [];
}),
(o.binding = function (e) {
throw new Error("process.binding is not supported");
}),
(o.cwd = function () {
return "/";
}),
(o.chdir = function (e) {
throw new Error("process.chdir is not supported");
}),
(o.umask = function () {
return 0;
});
},
{},
],
3: [
function (e, t, n) {
!(function (e) {
if ("object" == typeof n) t.exports = e();
else {
var r;
try {
r = window;
} catch (e) {
r = self;
}
r.SparkMD5 = e();
}
})(function (e) {
"use strict";
var t = [
"0",
"1",
"2",
"3",
"4",
"5",
"6",
"7",
"8",
"9",
"a",
"b",
"c",
"d",
"e",
"f",
];
function n(e, t) {
var n = e[0],
r = e[1],
i = e[2],
o = e[3];
(r =
((((r +=
((((i =
((((i +=
((((o =
((((o +=
((((n =
((((n +=
(((r & i) | (~r & o)) + t[0] - 680876936) | 0) <<
7) |
(n >>> 25)) +
r) |
0) &
r) |
(~n & i)) +
t[1] -
389564586) |
0) <<
12) |
(o >>> 20)) +
n) |
0) &
n) |
(~o & r)) +
t[2] +
606105819) |
0) <<
17) |
(i >>> 15)) +
o) |
0) &
o) |
(~i & n)) +
t[3] -
1044525330) |
0) <<
22) |
(r >>> 10)) +
i) |
0),
(r =
((((r +=
((((i =
((((i +=
((((o =
((((o +=
((((n =
((((n +=
(((r & i) | (~r & o)) + t[4] - 176418897) |
0) <<
7) |
(n >>> 25)) +
r) |
0) &
r) |
(~n & i)) +
t[5] +
1200080426) |
0) <<
12) |
(o >>> 20)) +
n) |
0) &
n) |
(~o & r)) +
t[6] -
1473231341) |
0) <<
17) |
(i >>> 15)) +
o) |
0) &
o) |
(~i & n)) +
t[7] -
45705983) |
0) <<
22) |
(r >>> 10)) +
i) |
0),
(r =
((((r +=
((((i =
((((i +=
((((o =
((((o +=
((((n =
((((n +=
(((r & i) | (~r & o)) + t[8] + 1770035416) |
0) <<
7) |
(n >>> 25)) +
r) |
0) &
r) |
(~n & i)) +
t[9] -
1958414417) |
0) <<
12) |
(o >>> 20)) +
n) |
0) &
n) |
(~o & r)) +
t[10] -
42063) |
0) <<
17) |
(i >>> 15)) +
o) |
0) &
o) |
(~i & n)) +
t[11] -
1990404162) |
0) <<
22) |
(r >>> 10)) +
i) |
0),
(r =
((((r +=
((((i =
((((i +=
((((o =
((((o +=
((((n =
((((n +=
(((r & i) | (~r & o)) + t[12] + 1804603682) |
0) <<
7) |
(n >>> 25)) +
r) |
0) &
r) |
(~n & i)) +
t[13] -
40341101) |
0) <<
12) |
(o >>> 20)) +
n) |
0) &
n) |
(~o & r)) +
t[14] -
1502002290) |
0) <<
17) |
(i >>> 15)) +
o) |
0) &
o) |
(~i & n)) +
t[15] +
1236535329) |
0) <<
22) |
(r >>> 10)) +
i) |
0),
(r =
((((r +=
((((i =
((((i +=
((((o =
((((o +=
((((n =
((((n +=
(((r & o) | (i & ~o)) + t[1] - 165796510) |
0) <<
5) |
(n >>> 27)) +
r) |
0) &
i) |
(r & ~i)) +
t[6] -
1069501632) |
0) <<
9) |
(o >>> 23)) +
n) |
0) &
r) |
(n & ~r)) +
t[11] +
643717713) |
0) <<
14) |
(i >>> 18)) +
o) |
0) &
n) |
(o & ~n)) +
t[0] -
373897302) |
0) <<
20) |
(r >>> 12)) +
i) |
0),
(r =
((((r +=
((((i =
((((i +=
((((o =
((((o +=
((((n =
((((n +=
(((r & o) | (i & ~o)) + t[5] - 701558691) |
0) <<
5) |
(n >>> 27)) +
r) |
0) &
i) |
(r & ~i)) +
t[10] +
38016083) |
0) <<
9) |
(o >>> 23)) +
n) |
0) &
r) |
(n & ~r)) +
t[15] -
660478335) |
0) <<
14) |
(i >>> 18)) +
o) |
0) &
n) |
(o & ~n)) +
t[4] -
405537848) |
0) <<
20) |
(r >>> 12)) +
i) |
0),
(r =
((((r +=
((((i =
((((i +=
((((o =
((((o +=
((((n =
((((n +=
(((r & o) | (i & ~o)) + t[9] + 568446438) |
0) <<
5) |
(n >>> 27)) +
r) |
0) &
i) |
(r & ~i)) +
t[14] -
1019803690) |
0) <<
9) |
(o >>> 23)) +
n) |
0) &
r) |
(n & ~r)) +
t[3] -
187363961) |
0) <<
14) |
(i >>> 18)) +
o) |
0) &
n) |
(o & ~n)) +
t[8] +
1163531501) |
0) <<
20) |
(r >>> 12)) +
i) |
0),
(r =
((((r +=
((((i =
((((i +=
((((o =
((((o +=
((((n =
((((n +=
(((r & o) | (i & ~o)) + t[13] - 1444681467) |
0) <<
5) |
(n >>> 27)) +
r) |
0) &
i) |
(r & ~i)) +
t[2] -
51403784) |
0) <<
9) |
(o >>> 23)) +
n) |
0) &
r) |
(n & ~r)) +
t[7] +
1735328473) |
0) <<
14) |
(i >>> 18)) +
o) |
0) &
n) |
(o & ~n)) +
t[12] -
1926607734) |
0) <<
20) |
(r >>> 12)) +
i) |
0),
(r =
((((r +=
(((i =
((((i +=
(((o =
((((o +=
(((n =
((((n += ((r ^ i ^ o) + t[5] - 378558) | 0) <<
4) |
(n >>> 28)) +
r) |
0) ^
r ^
i) +
t[8] -
2022574463) |
0) <<
11) |
(o >>> 21)) +
n) |
0) ^
n ^
r) +
t[11] +
1839030562) |
0) <<
16) |
(i >>> 16)) +
o) |
0) ^
o ^
n) +
t[14] -
35309556) |
0) <<
23) |
(r >>> 9)) +
i) |
0),
(r =
((((r +=
(((i =
((((i +=
(((o =
((((o +=
(((n =
((((n += ((r ^ i ^ o) + t[1] - 1530992060) | 0) <<
4) |
(n >>> 28)) +
r) |
0) ^
r ^
i) +
t[4] +
1272893353) |
0) <<
11) |
(o >>> 21)) +
n) |
0) ^
n ^
r) +
t[7] -
155497632) |
0) <<
16) |
(i >>> 16)) +
o) |
0) ^
o ^
n) +
t[10] -
1094730640) |
0) <<
23) |
(r >>> 9)) +
i) |
0),
(r =
((((r +=
(((i =
((((i +=
(((o =
((((o +=
(((n =
((((n += ((r ^ i ^ o) + t[13] + 681279174) | 0) <<
4) |
(n >>> 28)) +
r) |
0) ^
r ^
i) +
t[0] -
358537222) |
0) <<
11) |
(o >>> 21)) +
n) |
0) ^
n ^
r) +
t[3] -
722521979) |
0) <<
16) |
(i >>> 16)) +
o) |
0) ^
o ^
n) +
t[6] +
76029189) |
0) <<
23) |
(r >>> 9)) +
i) |
0),
(r =
((((r +=
(((i =
((((i +=
(((o =
((((o +=
(((n =
((((n += ((r ^ i ^ o) + t[9] - 640364487) | 0) <<
4) |
(n >>> 28)) +
r) |
0) ^
r ^
i) +
t[12] -
421815835) |
0) <<
11) |
(o >>> 21)) +
n) |
0) ^
n ^
r) +
t[15] +
530742520) |
0) <<
16) |
(i >>> 16)) +
o) |
0) ^
o ^
n) +
t[2] -
995338651) |
0) <<
23) |
(r >>> 9)) +
i) |
0),
(r =
((((r +=
(((o =
((((o +=
((r ^
((n =
((((n += ((i ^ (r | ~o)) + t[0] - 198630844) | 0) <<
6) |
(n >>> 26)) +
r) |
0) |
~i)) +
t[7] +
1126891415) |
0) <<
10) |
(o >>> 22)) +
n) |
0) ^
((i =
((((i += ((n ^ (o | ~r)) + t[14] - 1416354905) | 0) <<
15) |
(i >>> 17)) +
o) |
0) |
~n)) +
t[5] -
57434055) |
0) <<
21) |
(r >>> 11)) +
i) |
0),
(r =
((((r +=
(((o =
((((o +=
((r ^
((n =
((((n +=
((i ^ (r | ~o)) + t[12] + 1700485571) | 0) <<
6) |
(n >>> 26)) +
r) |
0) |
~i)) +
t[3] -
1894986606) |
0) <<
10) |
(o >>> 22)) +
n) |
0) ^
((i =
((((i += ((n ^ (o | ~r)) + t[10] - 1051523) | 0) <<
15) |
(i >>> 17)) +
o) |
0) |
~n)) +
t[1] -
2054922799) |
0) <<
21) |
(r >>> 11)) +
i) |
0),
(r =
((((r +=
(((o =
((((o +=
((r ^
((n =
((((n +=
((i ^ (r | ~o)) + t[8] + 1873313359) | 0) <<
6) |
(n >>> 26)) +
r) |
0) |
~i)) +
t[15] -
30611744) |
0) <<
10) |
(o >>> 22)) +
n) |
0) ^
((i =
((((i += ((n ^ (o | ~r)) + t[6] - 1560198380) | 0) <<
15) |
(i >>> 17)) +
o) |
0) |
~n)) +
t[13] +
1309151649) |
0) <<
21) |
(r >>> 11)) +
i) |
0),
(r =
((((r +=
(((o =
((((o +=
((r ^
((n =
((((n += ((i ^ (r | ~o)) + t[4] - 145523070) | 0) <<
6) |
(n >>> 26)) +
r) |
0) |
~i)) +
t[11] -
1120210379) |
0) <<
10) |
(o >>> 22)) +
n) |
0) ^
((i =
((((i += ((n ^ (o | ~r)) + t[2] + 718787259) | 0) <<
15) |
(i >>> 17)) +
o) |
0) |
~n)) +
t[9] -
343485551) |
0) <<
21) |
(r >>> 11)) +
i) |
0),
(e[0] = (n + e[0]) | 0),
(e[1] = (r + e[1]) | 0),
(e[2] = (i + e[2]) | 0),
(e[3] = (o + e[3]) | 0);
}
function r(e) {
var t,
n = [];
for (t = 0; t < 64; t += 4)
n[t >> 2] =
e.charCodeAt(t) +
(e.charCodeAt(t + 1) << 8) +
(e.charCodeAt(t + 2) << 16) +
(e.charCodeAt(t + 3) << 24);
return n;
}
function i(e) {
var t,
n = [];
for (t = 0; t < 64; t += 4)
n[t >> 2] =
e[t] + (e[t + 1] << 8) + (e[t + 2] << 16) + (e[t + 3] << 24);
return n;
}
function o(e) {
var t,
i,
o,
s,
a,
c,
u = e.length,
f = [1732584193, -271733879, -1732584194, 271733878];
for (t = 64; t <= u; t += 64) n(f, r(e.substring(t - 64, t)));
for (
i = (e = e.substring(t - 64)).length,
o = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
t = 0;
t < i;
t += 1
)
o[t >> 2] |= e.charCodeAt(t) << (t % 4 << 3);
if (((o[t >> 2] |= 128 << (t % 4 << 3)), t > 55))
for (n(f, o), t = 0; t < 16; t += 1) o[t] = 0;
return (
(s = (s = 8 * u).toString(16).match(/(.*?)(.{0,8})$/)),
(a = parseInt(s[2], 16)),
(c = parseInt(s[1], 16) || 0),
(o[14] = a),
(o[15] = c),
n(f, o),
f
);
}
function s(e) {
var n,
r = "";
for (n = 0; n < 4; n += 1)
r += t[(e >> (8 * n + 4)) & 15] + t[(e >> (8 * n)) & 15];
return r;
}
function a(e) {
var t;
for (t = 0; t < e.length; t += 1) e[t] = s(e[t]);
return e.join("");
}
function c(e) {
return (
/[\u0080-\uFFFF]/.test(e) &&
(e = unescape(encodeURIComponent(e))),
e
);
}
function u(e) {
var t,
n = [],
r = e.length;
for (t = 0; t < r - 1; t += 2)
n.push(parseInt(e.substr(t, 2), 16));
return String.fromCharCode.apply(String, n);
}
function f() {
this.reset();
}
return (
"5d41402abc4b2a76b9719d911017c592" !== a(o("hello")) &&
function (e, t) {
var n = (65535 & e) + (65535 & t);
return (
(((e >> 16) + (t >> 16) + (n >> 16)) << 16) | (65535 & n)
);
},
"undefined" == typeof ArrayBuffer ||
ArrayBuffer.prototype.slice ||
(function () {
function t(e, t) {
return (e = 0 | e || 0) < 0
? Math.max(e + t, 0)
: Math.min(e, t);
}
ArrayBuffer.prototype.slice = function (n, r) {
var i,
o,
s,
a,
c = this.byteLength,
u = t(n, c),
f = c;
return (
r !== e && (f = t(r, c)),
u > f
? new ArrayBuffer(0)
: ((i = f - u),
(o = new ArrayBuffer(i)),
(s = new Uint8Array(o)),
(a = new Uint8Array(this, u, i)),
s.set(a),
o)
);
};
})(),
(f.prototype.append = function (e) {
return this.appendBinary(c(e)), this;
}),
(f.prototype.appendBinary = function (e) {
(this._buff += e), (this._length += e.length);
var t,
i = this._buff.length;
for (t = 64; t <= i; t += 64)
n(this._hash, r(this._buff.substring(t - 64, t)));
return (this._buff = this._buff.substring(t - 64)), this;
}),
(f.prototype.end = function (e) {
var t,
n,
r = this._buff,
i = r.length,
o = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0];
for (t = 0; t < i; t += 1)
o[t >> 2] |= r.charCodeAt(t) << (t % 4 << 3);
return (
this._finish(o, i),
(n = a(this._hash)),
e && (n = u(n)),
this.reset(),
n
);
}),
(f.prototype.reset = function () {
return (
(this._buff = ""),
(this._length = 0),
(this._hash = [
1732584193, -271733879, -1732584194, 271733878,
]),
this
);
}),
(f.prototype.getState = function () {
return {
buff: this._buff,
length: this._length,
hash: this._hash.slice(),
};
}),
(f.prototype.setState = function (e) {
return (
(this._buff = e.buff),
(this._length = e.length),
(this._hash = e.hash),
this
);
}),
(f.prototype.destroy = function () {
delete this._hash, delete this._buff, delete this._length;
}),
(f.prototype._finish = function (e, t) {
var r,
i,
o,
s = t;
if (((e[s >> 2] |= 128 << (s % 4 << 3)), s > 55))
for (n(this._hash, e), s = 0; s < 16; s += 1) e[s] = 0;
(r = (r = 8 * this._length)
.toString(16)
.match(/(.*?)(.{0,8})$/)),
(i = parseInt(r[2], 16)),
(o = parseInt(r[1], 16) || 0),
(e[14] = i),
(e[15] = o),
n(this._hash, e);
}),
(f.hash = function (e, t) {
return f.hashBinary(c(e), t);
}),
(f.hashBinary = function (e, t) {
var n = a(o(e));
return t ? u(n) : n;
}),
(f.ArrayBuffer = function () {
this.reset();
}),
(f.ArrayBuffer.prototype.append = function (e) {
var t,
r,
o,
s,
a,
c =
((r = this._buff.buffer),
(o = e),
(s = !0),
(a = new Uint8Array(r.byteLength + o.byteLength)).set(
new Uint8Array(r)
),
a.set(new Uint8Array(o), r.byteLength),
s ? a : a.buffer),
u = c.length;
for (this._length += e.byteLength, t = 64; t <= u; t += 64)
n(this._hash, i(c.subarray(t - 64, t)));
return (
(this._buff =
t - 64 < u
? new Uint8Array(c.buffer.slice(t - 64))
: new Uint8Array(0)),
this
);
}),
(f.ArrayBuffer.prototype.end = function (e) {
var t,
n,
r = this._buff,
i = r.length,
o = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0];
for (t = 0; t < i; t += 1) o[t >> 2] |= r[t] << (t % 4 << 3);
return (
this._finish(o, i),
(n = a(this._hash)),
e && (n = u(n)),
this.reset(),
n
);
}),
(f.ArrayBuffer.prototype.reset = function () {
return (
(this._buff = new Uint8Array(0)),
(this._length = 0),
(this._hash = [
1732584193, -271733879, -1732584194, 271733878,
]),
this
);
}),
(f.ArrayBuffer.prototype.getState = function () {
var e,
t = f.prototype.getState.call(this);
return (
(t.buff =
((e = t.buff),
String.fromCharCode.apply(null, new Uint8Array(e)))),
t
);
}),
(f.ArrayBuffer.prototype.setState = function (e) {
return (
(e.buff = (function (e, t) {
var n,
r = e.length,
i = new ArrayBuffer(r),
o = new Uint8Array(i);
for (n = 0; n < r; n += 1) o[n] = e.charCodeAt(n);
return t ? o : i;
})(e.buff, !0)),
f.prototype.setState.call(this, e)
);
}),
(f.ArrayBuffer.prototype.destroy = f.prototype.destroy),
(f.ArrayBuffer.prototype._finish = f.prototype._finish),
(f.ArrayBuffer.hash = function (e, t) {
var r = a(
(function (e) {
var t,
r,
o,
s,
a,
c,
u = e.length,
f = [1732584193, -271733879, -1732584194, 271733878];
for (t = 64; t <= u; t += 64)
n(f, i(e.subarray(t - 64, t)));
for (
r = (e =
t - 64 < u ? e.subarray(t - 64) : new Uint8Array(0))
.length,
o = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
t = 0;
t < r;
t += 1
)
o[t >> 2] |= e[t] << (t % 4 << 3);
if (((o[t >> 2] |= 128 << (t % 4 << 3)), t > 55))
for (n(f, o), t = 0; t < 16; t += 1) o[t] = 0;
return (
(s = (s = 8 * u).toString(16).match(/(.*?)(.{0,8})$/)),
(a = parseInt(s[2], 16)),
(c = parseInt(s[1], 16) || 0),
(o[14] = a),
(o[15] = c),
n(f, o),
f
);
})(new Uint8Array(e))
);
return t ? u(r) : r;
}),
f
);
});
},
{},
],
4: [
function (e, t, n) {
"use strict";
Object.defineProperty(n, "__esModule", { value: !0 }),
Object.defineProperty(n, "v1", {
enumerable: !0,
get: function () {
return r.default;
},
}),
Object.defineProperty(n, "v3", {
enumerable: !0,
get: function () {
return i.default;
},
}),
Object.defineProperty(n, "v4", {
enumerable: !0,
get: function () {
return o.default;
},
}),
Object.defineProperty(n, "v5", {
enumerable: !0,
get: function () {
return s.default;
},
}),
Object.defineProperty(n, "NIL", {
enumerable: !0,
get: function () {
return a.default;
},
}),
Object.defineProperty(n, "version", {
enumerable: !0,
get: function () {
return c.default;
},
}),
Object.defineProperty(n, "validate", {
enumerable: !0,
get: function () {
return u.default;
},
}),
Object.defineProperty(n, "stringify", {
enumerable: !0,
get: function () {
return f.default;
},
}),
Object.defineProperty(n, "parse", {
enumerable: !0,
get: function () {
return l.default;
},
});
var r = d(e("./v1.js")),
i = d(e("./v3.js")),
o = d(e("./v4.js")),
s = d(e("./v5.js")),
a = d(e("./nil.js")),
c = d(e("./version.js")),
u = d(e("./validate.js")),
f = d(e("./stringify.js")),
l = d(e("./parse.js"));
function d(e) {
return e && e.__esModule ? e : { default: e };
}
},
{
"./nil.js": 6,
"./parse.js": 7,
"./stringify.js": 11,
"./v1.js": 12,
"./v3.js": 13,
"./v4.js": 15,
"./v5.js": 16,
"./validate.js": 17,
"./version.js": 18,
},
],
5: [
function (e, t, n) {
"use strict";
function r(e) {
return 14 + (((e + 64) >>> 9) << 4) + 1;
}
function i(e, t) {
const n = (65535 & e) + (65535 & t);
return (((e >> 16) + (t >> 16) + (n >> 16)) << 16) | (65535 & n);
}
function o(e, t, n, r, o, s) {
return i(
((a = i(i(t, e), i(r, s))) << (c = o)) | (a >>> (32 - c)),
n
);
var a, c;
}
function s(e, t, n, r, i, s, a) {
return o((t & n) | (~t & r), e, t, i, s, a);
}
function a(e, t, n, r, i, s, a) {
return o((t & r) | (n & ~r), e, t, i, s, a);
}
function c(e, t, n, r, i, s, a) {
return o(t ^ n ^ r, e, t, i, s, a);
}
function u(e, t, n, r, i, s, a) {
return o(n ^ (t | ~r), e, t, i, s, a);
}
Object.defineProperty(n, "__esModule", { value: !0 }),
(n.default = void 0);
var f = function (e) {
if ("string" == typeof e) {
const t = unescape(encodeURIComponent(e));
e = new Uint8Array(t.length);
for (let n = 0; n < t.length; ++n) e[n] = t.charCodeAt(n);
}
return (function (e) {
const t = [],
n = 32 * e.length;
for (let r = 0; r < n; r += 8) {
const n = (e[r >> 5] >>> r % 32) & 255,
i = parseInt(
"0123456789abcdef".charAt((n >>> 4) & 15) +
"0123456789abcdef".charAt(15 & n),
16
);
t.push(i);
}
return t;
})(
(function (e, t) {
(e[t >> 5] |= 128 << t % 32), (e[r(t) - 1] = t);
let n = 1732584193,
o = -271733879,
f = -1732584194,
l = 271733878;
for (let t = 0; t < e.length; t += 16) {
const r = n,
d = o,
h = f,
p = l;
(n = s(n, o, f, l, e[t], 7, -680876936)),
(l = s(l, n, o, f, e[t + 1], 12, -389564586)),
(f = s(f, l, n, o, e[t + 2], 17, 606105819)),
(o = s(o, f, l, n, e[t + 3], 22, -1044525330)),
(n = s(n, o, f, l, e[t + 4], 7, -176418897)),
(l = s(l, n, o, f, e[t + 5], 12, 1200080426)),
(f = s(f, l, n, o, e[t + 6], 17, -1473231341)),
(o = s(o, f, l, n, e[t + 7], 22, -45705983)),
(n = s(n, o, f, l, e[t + 8], 7, 1770035416)),
(l = s(l, n, o, f, e[t + 9], 12, -1958414417)),
(f = s(f, l, n, o, e[t + 10], 17, -42063)),
(o = s(o, f, l, n, e[t + 11], 22, -1990404162)),
(n = s(n, o, f, l, e[t + 12], 7, 1804603682)),
(l = s(l, n, o, f, e[t + 13], 12, -40341101)),
(f = s(f, l, n, o, e[t + 14], 17, -1502002290)),
(o = s(o, f, l, n, e[t + 15], 22, 1236535329)),
(n = a(n, o, f, l, e[t + 1], 5, -165796510)),
(l = a(l, n, o, f, e[t + 6], 9, -1069501632)),
(f = a(f, l, n, o, e[t + 11], 14, 643717713)),
(o = a(o, f, l, n, e[t], 20, -373897302)),
(n = a(n, o, f, l, e[t + 5], 5, -701558691)),
(l = a(l, n, o, f, e[t + 10], 9, 38016083)),
(f = a(f, l, n, o, e[t + 15], 14, -660478335)),
(o = a(o, f, l, n, e[t + 4], 20, -405537848)),
(n = a(n, o, f, l, e[t + 9], 5, 568446438)),
(l = a(l, n, o, f, e[t + 14], 9, -1019803690)),
(f = a(f, l, n, o, e[t + 3], 14, -187363961)),
(o = a(o, f, l, n, e[t + 8], 20, 1163531501)),
(n = a(n, o, f, l, e[t + 13], 5, -1444681467)),
(l = a(l, n, o, f, e[t + 2], 9, -51403784)),
(f = a(f, l, n, o, e[t + 7], 14, 1735328473)),
(o = a(o, f, l, n, e[t + 12], 20, -1926607734)),
(n = c(n, o, f, l, e[t + 5], 4, -378558)),
(l = c(l, n, o, f, e[t + 8], 11, -2022574463)),
(f = c(f, l, n, o, e[t + 11], 16, 1839030562)),
(o = c(o, f, l, n, e[t + 14], 23, -35309556)),
(n = c(n, o, f, l, e[t + 1], 4, -1530992060)),
(l = c(l, n, o, f, e[t + 4], 11, 1272893353)),
(f = c(f, l, n, o, e[t + 7], 16, -155497632)),
(o = c(o, f, l, n, e[t + 10], 23, -1094730640)),
(n = c(n, o, f, l, e[t + 13], 4, 681279174)),
(l = c(l, n, o, f, e[t], 11, -358537222)),
(f = c(f, l, n, o, e[t + 3], 16, -722521979)),
(o = c(o, f, l, n, e[t + 6], 23, 76029189)),
(n = c(n, o, f, l, e[t + 9], 4, -640364487)),
(l = c(l, n, o, f, e[t + 12], 11, -421815835)),
(f = c(f, l, n, o, e[t + 15], 16, 530742520)),
(o = c(o, f, l, n, e[t + 2], 23, -995338651)),
(n = u(n, o, f, l, e[t], 6, -198630844)),
(l = u(l, n, o, f, e[t + 7], 10, 1126891415)),
(f = u(f, l, n, o, e[t + 14], 15, -1416354905)),
(o = u(o, f, l, n, e[t + 5], 21, -57434055)),
(n = u(n, o, f, l, e[t + 12], 6, 1700485571)),
(l = u(l, n, o, f, e[t + 3], 10, -1894986606)),
(f = u(f, l, n, o, e[t + 10], 15, -1051523)),
(o = u(o, f, l, n, e[t + 1], 21, -2054922799)),
(n = u(n, o, f, l, e[t + 8], 6, 1873313359)),
(l = u(l, n, o, f, e[t + 15], 10, -30611744)),
(f = u(f, l, n, o, e[t + 6], 15, -1560198380)),
(o = u(o, f, l, n, e[t + 13], 21, 1309151649)),
(n = u(n, o, f, l, e[t + 4], 6, -145523070)),
(l = u(l, n, o, f, e[t + 11], 10, -1120210379)),
(f = u(f, l, n, o, e[t + 2], 15, 718787259)),
(o = u(o, f, l, n, e[t + 9], 21, -343485551)),
(n = i(n, r)),
(o = i(o, d)),
(f = i(f, h)),
(l = i(l, p));
}
return [n, o, f, l];
})(
(function (e) {
if (0 === e.length) return [];
const t = 8 * e.length,
n = new Uint32Array(r(t));
for (let r = 0; r < t; r += 8)
n[r >> 5] |= (255 & e[r / 8]) << r % 32;
return n;
})(e),
8 * e.length
)
);
};
n.default = f;
},
{},
],
6: [
function (e, t, n) {
"use strict";
Object.defineProperty(n, "__esModule", { value: !0 }),
(n.default = void 0);
n.default = "00000000-0000-0000-0000-000000000000";
},
{},
],
7: [
function (e, t, n) {
"use strict";
Object.defineProperty(n, "__esModule", { value: !0 }),
(n.default = void 0);
var r,
i = (r = e("./validate.js")) && r.__esModule ? r : { default: r };
var o = function (e) {
if (!(0, i.default)(e)) throw TypeError("Invalid UUID");
let t;
const n = new Uint8Array(16);
return (
(n[0] = (t = parseInt(e.slice(0, 8), 16)) >>> 24),
(n[1] = (t >>> 16) & 255),
(n[2] = (t >>> 8) & 255),
(n[3] = 255 & t),
(n[4] = (t = parseInt(e.slice(9, 13), 16)) >>> 8),
(n[5] = 255 & t),
(n[6] = (t = parseInt(e.slice(14, 18), 16)) >>> 8),
(n[7] = 255 & t),
(n[8] = (t = parseInt(e.slice(19, 23), 16)) >>> 8),
(n[9] = 255 & t),
(n[10] =
((t = parseInt(e.slice(24, 36), 16)) / 1099511627776) & 255),
(n[11] = (t / 4294967296) & 255),
(n[12] = (t >>> 24) & 255),
(n[13] = (t >>> 16) & 255),
(n[14] = (t >>> 8) & 255),
(n[15] = 255 & t),
n
);
};
n.default = o;
},
{ "./validate.js": 17 },
],
8: [
function (e, t, n) {
"use strict";
Object.defineProperty(n, "__esModule", { value: !0 }),
(n.default = void 0);
n.default =
/^(?:[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|00000000-0000-0000-0000-000000000000)$/i;
},
{},
],
9: [
function (e, t, n) {
"use strict";
let r;
Object.defineProperty(n, "__esModule", { value: !0 }),
(n.default = function () {
if (
!r &&
((r =
("undefined" != typeof crypto &&
crypto.getRandomValues &&
crypto.getRandomValues.bind(crypto)) ||
("undefined" != typeof msCrypto &&
"function" == typeof msCrypto.getRandomValues &&
msCrypto.getRandomValues.bind(msCrypto))),
!r)
)
throw new Error(
"crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported"
);
return r(i);
});
const i = new Uint8Array(16);
},
{},
],
10: [
function (e, t, n) {
"use strict";
function r(e, t, n, r) {
switch (e) {
case 0:
return (t & n) ^ (~t & r);
case 1:
return t ^ n ^ r;
case 2:
return (t & n) ^ (t & r) ^ (n & r);
case 3:
return t ^ n ^ r;
}
}
function i(e, t) {
return (e << t) | (e >>> (32 - t));
}
Object.defineProperty(n, "__esModule", { value: !0 }),
(n.default = void 0);
var o = function (e) {
const t = [1518500249, 1859775393, 2400959708, 3395469782],
n = [1732584193, 4023233417, 2562383102, 271733878, 3285377520];
if ("string" == typeof e) {
const t = unescape(encodeURIComponent(e));
e = [];
for (let n = 0; n < t.length; ++n) e.push(t.charCodeAt(n));
} else Array.isArray(e) || (e = Array.prototype.slice.call(e));
e.push(128);
const o = e.length / 4 + 2,
s = Math.ceil(o / 16),
a = new Array(s);
for (let t = 0; t < s; ++t) {
const n = new Uint32Array(16);
for (let r = 0; r < 16; ++r)
n[r] =
(e[64 * t + 4 * r] << 24) |
(e[64 * t + 4 * r + 1] << 16) |
(e[64 * t + 4 * r + 2] << 8) |
e[64 * t + 4 * r + 3];
a[t] = n;
}
(a[s - 1][14] = (8 * (e.length - 1)) / Math.pow(2, 32)),
(a[s - 1][14] = Math.floor(a[s - 1][14])),
(a[s - 1][15] = (8 * (e.length - 1)) & 4294967295);
for (let e = 0; e < s; ++e) {
const o = new Uint32Array(80);
for (let t = 0; t < 16; ++t) o[t] = a[e][t];
for (let e = 16; e < 80; ++e)
o[e] = i(o[e - 3] ^ o[e - 8] ^ o[e - 14] ^ o[e - 16], 1);
let s = n[0],
c = n[1],
u = n[2],
f = n[3],
l = n[4];
for (let e = 0; e < 80; ++e) {
const n = Math.floor(e / 20),
a = (i(s, 5) + r(n, c, u, f) + l + t[n] + o[e]) >>> 0;
(l = f), (f = u), (u = i(c, 30) >>> 0), (c = s), (s = a);
}
(n[0] = (n[0] + s) >>> 0),
(n[1] = (n[1] + c) >>> 0),
(n[2] = (n[2] + u) >>> 0),
(n[3] = (n[3] + f) >>> 0),
(n[4] = (n[4] + l) >>> 0);
}
return [
(n[0] >> 24) & 255,
(n[0] >> 16) & 255,
(n[0] >> 8) & 255,
255 & n[0],
(n[1] >> 24) & 255,
(n[1] >> 16) & 255,
(n[1] >> 8) & 255,
255 & n[1],
(n[2] >> 24) & 255,
(n[2] >> 16) & 255,
(n[2] >> 8) & 255,
255 & n[2],
(n[3] >> 24) & 255,
(n[3] >> 16) & 255,
(n[3] >> 8) & 255,
255 & n[3],
(n[4] >> 24) & 255,
(n[4] >> 16) & 255,
(n[4] >> 8) & 255,
255 & n[4],
];
};
n.default = o;
},
{},
],
11: [
function (e, t, n) {
"use strict";
Object.defineProperty(n, "__esModule", { value: !0 }),
(n.default = void 0);
var r,
i = (r = e("./validate.js")) && r.__esModule ? r : { default: r };
const o = [];
for (let e = 0; e < 256; ++e)
o.push((e + 256).toString(16).substr(1));
var s = function (e, t = 0) {
const n = (
o[e[t + 0]] +
o[e[t + 1]] +
o[e[t + 2]] +
o[e[t + 3]] +
"-" +
o[e[t + 4]] +
o[e[t + 5]] +
"-" +
o[e[t + 6]] +
o[e[t + 7]] +
"-" +
o[e[t + 8]] +
o[e[t + 9]] +
"-" +
o[e[t + 10]] +
o[e[t + 11]] +
o[e[t + 12]] +
o[e[t + 13]] +
o[e[t + 14]] +
o[e[t + 15]]
).toLowerCase();
if (!(0, i.default)(n))
throw TypeError("Stringified UUID is invalid");
return n;
};
n.default = s;
},
{ "./validate.js": 17 },
],
12: [
function (e, t, n) {
"use strict";
Object.defineProperty(n, "__esModule", { value: !0 }),
(n.default = void 0);
var r = o(e("./rng.js")),
i = o(e("./stringify.js"));
function o(e) {
return e && e.__esModule ? e : { default: e };
}
let s,
a,
c = 0,
u = 0;
var f = function (e, t, n) {
let o = (t && n) || 0;
const f = t || new Array(16);
let l = (e = e || {}).node || s,
d = void 0 !== e.clockseq ? e.clockseq : a;
if (null == l || null == d) {
const t = e.random || (e.rng || r.default)();
null == l && (l = s = [1 | t[0], t[1], t[2], t[3], t[4], t[5]]),
null == d && (d = a = 16383 & ((t[6] << 8) | t[7]));
}
let h = void 0 !== e.msecs ? e.msecs : Date.now(),
p = void 0 !== e.nsecs ? e.nsecs : u + 1;
const v = h - c + (p - u) / 1e4;
if (
(v < 0 && void 0 === e.clockseq && (d = (d + 1) & 16383),
(v < 0 || h > c) && void 0 === e.nsecs && (p = 0),
p >= 1e4)
)
throw new Error(
"uuid.v1(): Can't create more than 10M uuids/sec"
);
(c = h), (u = p), (a = d), (h += 122192928e5);
const _ = (1e4 * (268435455 & h) + p) % 4294967296;
(f[o++] = (_ >>> 24) & 255),
(f[o++] = (_ >>> 16) & 255),
(f[o++] = (_ >>> 8) & 255),
(f[o++] = 255 & _);
const y = ((h / 4294967296) * 1e4) & 268435455;
(f[o++] = (y >>> 8) & 255),
(f[o++] = 255 & y),
(f[o++] = ((y >>> 24) & 15) | 16),
(f[o++] = (y >>> 16) & 255),
(f[o++] = (d >>> 8) | 128),
(f[o++] = 255 & d);
for (let e = 0; e < 6; ++e) f[o + e] = l[e];
return t || (0, i.default)(f);
};
n.default = f;
},
{ "./rng.js": 9, "./stringify.js": 11 },
],
13: [
function (e, t, n) {
"use strict";
Object.defineProperty(n, "__esModule", { value: !0 }),
(n.default = void 0);
var r = o(e("./v35.js")),
i = o(e("./md5.js"));
function o(e) {
return e && e.__esModule ? e : { default: e };
}
var s = (0, r.default)("v3", 48, i.default);
n.default = s;
},
{ "./md5.js": 5, "./v35.js": 14 },
],
14: [
function (e, t, n) {
"use strict";
Object.defineProperty(n, "__esModule", { value: !0 }),
(n.default = function (e, t, n) {
function o(e, o, s, a) {
if (
("string" == typeof e &&
(e = (function (e) {
e = unescape(encodeURIComponent(e));
const t = [];
for (let n = 0; n < e.length; ++n)
t.push(e.charCodeAt(n));
return t;
})(e)),
"string" == typeof o && (o = (0, i.default)(o)),
16 !== o.length)
)
throw TypeError(
"Namespace must be array-like (16 iterable integer values, 0-255)"
);
let c = new Uint8Array(16 + e.length);
if (
(c.set(o),
c.set(e, o.length),
(c = n(c)),
(c[6] = (15 & c[6]) | t),
(c[8] = (63 & c[8]) | 128),
s)
) {
a = a || 0;
for (let e = 0; e < 16; ++e) s[a + e] = c[e];
return s;
}
return (0, r.default)(c);
}
try {
o.name = e;
} catch (e) {}
return (o.DNS = s), (o.URL = a), o;
}),
(n.URL = n.DNS = void 0);
var r = o(e("./stringify.js")),
i = o(e("./parse.js"));
function o(e) {
return e && e.__esModule ? e : { default: e };
}
const s = "6ba7b810-9dad-11d1-80b4-00c04fd430c8";
n.DNS = s;
const a = "6ba7b811-9dad-11d1-80b4-00c04fd430c8";
n.URL = a;
},
{ "./parse.js": 7, "./stringify.js": 11 },
],
15: [
function (e, t, n) {
"use strict";
Object.defineProperty(n, "__esModule", { value: !0 }),
(n.default = void 0);
var r = o(e("./rng.js")),
i = o(e("./stringify.js"));
function o(e) {
return e && e.__esModule ? e : { default: e };
}
var s = function (e, t, n) {
const o = (e = e || {}).random || (e.rng || r.default)();
if (((o[6] = (15 & o[6]) | 64), (o[8] = (63 & o[8]) | 128), t)) {
n = n || 0;
for (let e = 0; e < 16; ++e) t[n + e] = o[e];
return t;
}
return (0, i.default)(o);
};
n.default = s;
},
{ "./rng.js": 9, "./stringify.js": 11 },
],
16: [
function (e, t, n) {
"use strict";
Object.defineProperty(n, "__esModule", { value: !0 }),
(n.default = void 0);
var r = o(e("./v35.js")),
i = o(e("./sha1.js"));
function o(e) {
return e && e.__esModule ? e : { default: e };
}
var s = (0, r.default)("v5", 80, i.default);
n.default = s;
},
{ "./sha1.js": 10, "./v35.js": 14 },
],
17: [
function (e, t, n) {
"use strict";
Object.defineProperty(n, "__esModule", { value: !0 }),
(n.default = void 0);
var r,
i = (r = e("./regex.js")) && r.__esModule ? r : { default: r };
var o = function (e) {
return "string" == typeof e && i.default.test(e);
};
n.default = o;
},
{ "./regex.js": 8 },
],
18: [
function (e, t, n) {
"use strict";
Object.defineProperty(n, "__esModule", { value: !0 }),
(n.default = void 0);
var r,
i = (r = e("./validate.js")) && r.__esModule ? r : { default: r };
var o = function (e) {
if (!(0, i.default)(e)) throw TypeError("Invalid UUID");
return parseInt(e.substr(14, 1), 16);
};
n.default = o;
},
{ "./validate.js": 17 },
],
19: [
function (e, t, n) {
"use strict";
function r(e, t, n) {
var r = n[n.length - 1];
e === r.element && (n.pop(), (r = n[n.length - 1]));
var i = r.element,
o = r.index;
if (Array.isArray(i)) i.push(e);
else if (o === t.length - 2) {
i[t.pop()] = e;
} else t.push(e);
}
(n.stringify = function (e) {
var t = [];
t.push({ obj: e });
for (var n, r, i, o, s, a, c, u, f, l, d = ""; (n = t.pop()); )
if (((r = n.obj), (d += n.prefix || ""), (i = n.val || "")))
d += i;
else if ("object" != typeof r)
d += void 0 === r ? null : JSON.stringify(r);
else if (null === r) d += "null";
else if (Array.isArray(r)) {
for (t.push({ val: "]" }), o = r.length - 1; o >= 0; o--)
(s = 0 === o ? "" : ","), t.push({ obj: r[o], prefix: s });
t.push({ val: "[" });
} else {
for (c in ((a = []), r)) r.hasOwnProperty(c) && a.push(c);
for (t.push({ val: "}" }), o = a.length - 1; o >= 0; o--)
(f = r[(u = a[o])]),
(l = o > 0 ? "," : ""),
(l += JSON.stringify(u) + ":"),
t.push({ obj: f, prefix: l });
t.push({ val: "{" });
}
return d;
}),
(n.parse = function (e) {
for (var t, n, i, o, s, a, c, u, f, l = [], d = [], h = 0; ; )
if ("}" !== (t = e[h++]) && "]" !== t && void 0 !== t)
switch (t) {
case " ":
case "\t":
case "\n":
case ":":
case ",":
break;
case "n":
(h += 3), r(null, l, d);
break;
case "t":
(h += 3), r(!0, l, d);
break;
case "f":
(h += 4), r(!1, l, d);
break;
case "0":
case "1":
case "2":
case "3":
case "4":
case "5":
case "6":
case "7":
case "8":
case "9":
case "-":
for (n = "", h--; ; ) {
if (((i = e[h++]), !/[\d\.\-e\+]/.test(i))) {
h--;
break;
}
n += i;
}
r(parseFloat(n), l, d);
break;
case '"':
for (
o = "", s = void 0, a = 0;
'"' !== (c = e[h++]) || ("\\" === s && a % 2 == 1);
)
(o += c), "\\" === (s = c) ? a++ : (a = 0);
r(JSON.parse('"' + o + '"'), l, d);
break;
case "[":
(u = { element: [], index: l.length }),
l.push(u.element),
d.push(u);
break;
case "{":
(f = { element: {}, index: l.length }),
l.push(f.element),
d.push(f);
break;
default:
throw new Error(
"unexpectedly reached end of input: " + t
);
}
else {
if (1 === l.length) return l.pop();
r(l.pop(), l, d);
}
});
},
{},
],
20: [
function (e, t, n) {
(function (n) {
(function () {
"use strict";
function r(e) {
return e && "object" == typeof e && "default" in e
? e.default
: e;
}
var i = r(e("spark-md5")),
o = e("uuid"),
s = r(e("vuvuzela")),
a = r(e("events"));
var c = Function.prototype.toString,
u = c.call(Object);
function f(e) {
var t, n, r;
if (!e || "object" != typeof e) return e;
if (Array.isArray(e)) {
for (t = [], n = 0, r = e.length; n < r; n++) t[n] = f(e[n]);
return t;
}
if (e instanceof Date && isFinite(e)) return e.toISOString();
if (
(function (e) {
return (
("undefined" != typeof ArrayBuffer &&
e instanceof ArrayBuffer) ||
("undefined" != typeof Blob && e instanceof Blob)
);
})(e)
)
return (function (e) {
return e instanceof ArrayBuffer
? e.slice(0)
: e.slice(0, e.size, e.type);
})(e);
if (
!(function (e) {
var t = Object.getPrototypeOf(e);
if (null === t) return !0;
var n = t.constructor;
return (
"function" == typeof n && n instanceof n && c.call(n) == u
);
})(e)
)
return e;
for (n in ((t = {}), e))
if (Object.prototype.hasOwnProperty.call(e, n)) {
var i = f(e[n]);
void 0 !== i && (t[n] = i);
}
return t;
}
function l(e) {
var t = !1;
return function (...n) {
if (t) throw new Error("once called more than once");
(t = !0), e.apply(this, n);
};
}
function d(e) {
return function (...t) {
t = f(t);
var n = this,
r = "function" == typeof t[t.length - 1] && t.pop(),
i = new Promise(function (r, i) {
var o;
try {
var s = l(function (e, t) {
e ? i(e) : r(t);
});
t.push(s),
(o = e.apply(n, t)) &&
"function" == typeof o.then &&
r(o);
} catch (e) {
i(e);
}
});
return (
r &&
i.then(function (e) {
r(null, e);
}, r),
i
);
};
}
function h(e, t) {
return d(function (...n) {
if (this._closed)
return Promise.reject(new Error("database is closed"));
if (this._destroyed)
return Promise.reject(new Error("database is destroyed"));
var r = this;
return (
(function (e, t, n) {
if (e.constructor.listeners("debug").length) {
for (
var r = ["api", e.name, t], i = 0;
i < n.length - 1;
i++
)
r.push(n[i]);
e.constructor.emit("debug", r);
var o = n[n.length - 1];
n[n.length - 1] = function (n, r) {
var i = ["api", e.name, t];
(i = i.concat(n ? ["error", n] : ["success", r])),
e.constructor.emit("debug", i),
o(n, r);
};
}
})(r, e, n),
this.taskqueue.isReady
? t.apply(this, n)
: new Promise(function (t, i) {
r.taskqueue.addTask(function (o) {
o ? i(o) : t(r[e].apply(r, n));
});
})
);
});
}
function p(e, t) {
for (var n = {}, r = 0, i = t.length; r < i; r++) {
var o = t[r];
o in e && (n[o] = e[o]);
}
return n;
}
var v;
function _(e) {
return e;
}
function y(e) {
return [{ ok: e }];
}
function g(e, t, n) {
var r = t.docs,
i = new Map();
r.forEach(function (e) {
i.has(e.id) ? i.get(e.id).push(e) : i.set(e.id, [e]);
});
var o = i.size,
s = 0,
a = new Array(o);
function c() {
var e;
++s === o &&
((e = []),
a.forEach(function (t) {
t.docs.forEach(function (n) {
e.push({ id: t.id, docs: [n] });
});
}),
n(null, { results: e }));
}
var u = [];
i.forEach(function (e, t) {
u.push(t);
});
var f = 0;
function l() {
if (!(f >= u.length)) {
var n = Math.min(f + 6, u.length),
r = u.slice(f, n);
!(function (n, r) {
n.forEach(function (n, o) {
var s = r + o,
u = i.get(n),
f = p(u[0], ["atts_since", "attachments"]);
(f.open_revs = u.map(function (e) {
return e.rev;
})),
(f.open_revs = f.open_revs.filter(_));
var d = _;
0 === f.open_revs.length &&
(delete f.open_revs, (d = y)),
[
"revs",
"attachments",
"binary",
"ajax",
"latest",
].forEach(function (e) {
e in t && (f[e] = t[e]);
}),
e.get(n, f, function (e, t) {
var r, i, o;
(r = e ? [{ error: e }] : d(t)),
(i = n),
(o = r),
(a[s] = { id: i, docs: o }),
c(),
l();
});
});
})(r, f),
(f += r.length);
}
}
l();
}
try {
localStorage.setItem("_pouch_check_localstorage", 1),
(v = !!localStorage.getItem("_pouch_check_localstorage"));
} catch (e) {
v = !1;
}
function m() {
return v;
}
const b =
"function" == typeof queueMicrotask
? queueMicrotask
: function (e) {
Promise.resolve().then(e);
};
function w(e) {
if (
"undefined" != typeof console &&
"function" == typeof console[e]
) {
var t = Array.prototype.slice.call(arguments, 1);
console[e].apply(console, t);
}
}
function k(e) {
var t = 0;
return (
e || (t = 2e3),
(function (e, t) {
return (
(e = parseInt(e, 10) || 0),
(t = parseInt(t, 10)) != t || t <= e
? (t = (e || 1) << 1)
: (t += 1),
t > 6e5 && ((e = 3e5), (t = 6e5)),
~~((t - e) * Math.random() + e)
);
})(e, t)
);
}
function j(e, t) {
w("info", "The above " + e + " is totally normal. " + t);
}
class q extends Error {
constructor(e, t, n) {
super(),
(this.status = e),
(this.name = t),
(this.message = n),
(this.error = !0);
}
toString() {
return JSON.stringify({
status: this.status,
name: this.name,
message: this.message,
reason: this.reason,
});
}
}
new q(401, "unauthorized", "Name or password is incorrect.");
var O = new q(400, "bad_request", "Missing JSON list of 'docs'"),
A = new q(404, "not_found", "missing"),
S = new q(409, "conflict", "Document update conflict"),
x = new q(
400,
"bad_request",
"_id field must contain a string"
),
P = new q(412, "missing_id", "_id is required for puts"),
C = new q(
400,
"bad_request",
"Only reserved document ids may start with underscore."
),
E =
(new q(412, "precondition_failed", "Database not open"),
new q(
500,
"unknown_error",
"Database encountered an unknown error"
)),
$ = new q(500, "badarg", "Some query argument is invalid"),
I =
(new q(400, "invalid_request", "Request was invalid"),
new q(
400,
"query_parse_error",
"Some query parameter is invalid"
)),
L = new q(500, "doc_validation", "Bad special document member"),
D = new q(
400,
"bad_request",
"Something wrong with the request"
),
T = new q(400, "bad_request", "Document must be a JSON object"),
B =
(new q(404, "not_found", "Database not found"),
new q(500, "indexed_db_went_bad", "unknown")),
M =
(new q(500, "web_sql_went_bad", "unknown"),
new q(500, "levelDB_went_went_bad", "unknown"),
new q(
403,
"forbidden",
"Forbidden by design doc validate_doc_update function"
),
new q(400, "bad_request", "Invalid rev format")),
R =
(new q(
412,
"file_exists",
"The database could not be created, the file already exists."
),
new q(
412,
"missing_stub",
"A pre-existing attachment stub wasn't found"
));
new q(413, "invalid_url", "Provided URL is invalid");
function N(e, t) {
function n(t) {
for (
var n = Object.getOwnPropertyNames(e), r = 0, i = n.length;
r < i;
r++
)
"function" != typeof e[n[r]] && (this[n[r]] = e[n[r]]);
void 0 === this.stack && (this.stack = new Error().stack),
void 0 !== t && (this.reason = t);
}
return (n.prototype = q.prototype), new n(t);
}
function U(e) {
if ("object" != typeof e) {
var t = e;
(e = E).data = t;
}
return (
"error" in e &&
"conflict" === e.error &&
((e.name = "conflict"), (e.status = 409)),
"name" in e || (e.name = e.error || "unknown"),
"status" in e || (e.status = 500),
"message" in e || (e.message = e.message || e.reason),
"stack" in e || (e.stack = new Error().stack),
e
);
}
function F(e) {
var t = {},
n = e.filter && "function" == typeof e.filter;
return (
(t.query = e.query_params),
function (r) {
r.doc || (r.doc = {});
var i =
n &&
(function (e, t, n) {
try {
return !e(t, n);
} catch (e) {
var r = "Filter function threw: " + e.toString();
return N(D, r);
}
})(e.filter, r.doc, t);
if ("object" == typeof i) return i;
if (i) return !1;
if (e.include_docs) {
if (!e.attachments)
for (var o in r.doc._attachments)
Object.prototype.hasOwnProperty.call(
r.doc._attachments,
o
) && (r.doc._attachments[o].stub = !0);
} else delete r.doc;
return !0;
}
);
}
function K(e) {
var t;
if (
(e
? "string" != typeof e
? (t = N(x))
: /^_/.test(e) &&
!/^_(design|local)/.test(e) &&
(t = N(C))
: (t = N(P)),
t)
)
throw t;
}
function J(e) {
return "boolean" == typeof e._remote
? e._remote
: "function" == typeof e.type &&
(w(
"warn",
"db.type() is deprecated and will be removed in a future version of PouchDB"
),
"http" === e.type());
}
function z(e) {
if (!e) return null;
var t = e.split("/");
return 2 === t.length ? t : 1 === t.length ? [e, e] : null;
}
function V(e) {
var t = z(e);
return t ? t.join("/") : null;
}
var G = [
"source",
"protocol",
"authority",
"userInfo",
"user",
"password",
"host",
"port",
"relative",
"path",
"directory",
"file",
"query",
"anchor",
],
Q = /(?:^|&)([^&=]*)=?([^&]*)/g,
W =
/^(?:(?![^:@]+:[^:@\/]*@)([^:\/?#.]+):)?(?:\/\/)?((?:(([^:@]*)(?::([^:@]*))?)?@)?([^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/;
function Y(e) {
for (var t = W.exec(e), n = {}, r = 14; r--; ) {
var i = G[r],
o = t[r] || "",
s = -1 !== ["user", "password"].indexOf(i);
n[i] = s ? decodeURIComponent(o) : o;
}
return (
(n.queryKey = {}),
n[G[12]].replace(Q, function (e, t, r) {
t && (n.queryKey[t] = r);
}),
n
);
}
function H(e, t) {
var n = [],
r = [];
for (var i in t)
Object.prototype.hasOwnProperty.call(t, i) &&
(n.push(i), r.push(t[i]));
return n.push(e), Function.apply(null, n).apply(null, r);
}
function X(e, t, n) {
return e
.get(t)
.catch(function (e) {
if (404 !== e.status) throw e;
return {};
})
.then(function (r) {
var i = r._rev,
o = n(r);
return o
? ((o._id = t),
(o._rev = i),
(function (e, t, n) {
return e.put(t).then(
function (e) {
return { updated: !0, rev: e.rev };
},
function (r) {
if (409 !== r.status) throw r;
return X(e, t._id, n);
}
);
})(e, o, n))
: { updated: !1, rev: i };
});
}
var Z = function (e) {
return atob(e);
},
ee = function (e) {
return btoa(e);
};
function te(e, t) {
(e = e || []), (t = t || {});
try {
return new Blob(e, t);
} catch (i) {
if ("TypeError" !== i.name) throw i;
for (
var n = new (
"undefined" != typeof BlobBuilder
? BlobBuilder
: "undefined" != typeof MSBlobBuilder
? MSBlobBuilder
: "undefined" != typeof MozBlobBuilder
? MozBlobBuilder
: WebKitBlobBuilder
)(),
r = 0;
r < e.length;
r += 1
)
n.append(e[r]);
return n.getBlob(t.type);
}
}
function ne(e) {
for (
var t = e.length,
n = new ArrayBuffer(t),
r = new Uint8Array(n),
i = 0;
i < t;
i++
)
r[i] = e.charCodeAt(i);
return n;
}
function re(e, t) {
return te([ne(e)], { type: t });
}
function ie(e, t) {
return re(Z(e), t);
}
function oe(e, t) {
var n = new FileReader(),
r = "function" == typeof n.readAsBinaryString;
(n.onloadend = function (e) {
var n = e.target.result || "";
if (r) return t(n);
t(
(function (e) {
for (
var t = "",
n = new Uint8Array(e),
r = n.byteLength,
i = 0;
i < r;
i++
)
t += String.fromCharCode(n[i]);
return t;
})(n)
);
}),
r ? n.readAsBinaryString(e) : n.readAsArrayBuffer(e);
}
function se(e, t) {
oe(e, function (e) {
t(e);
});
}
function ae(e, t) {
se(e, function (e) {
t(ee(e));
});
}
var ce = self.setImmediate || self.setTimeout;
function ue(e, t, n, r, i) {
(n > 0 || r < t.size) && (t = t.slice(n, r)),
(function (e, t) {
var n = new FileReader();
(n.onloadend = function (e) {
var n = e.target.result || new ArrayBuffer(0);
t(n);
}),
n.readAsArrayBuffer(e);
})(t, function (t) {
e.append(t), i();
});
}
function fe(e, t, n, r, i) {
(n > 0 || r < t.length) && (t = t.substring(n, r)),
e.appendBinary(t),
i();
}
function le(e, t) {
var n = "string" == typeof e,
r = n ? e.length : e.size,
o = Math.min(32768, r),
s = Math.ceil(r / o),
a = 0,
c = n ? new i() : new i.ArrayBuffer(),
u = n ? fe : ue;
function f() {
ce(d);
}
function l() {
var e = (function (e) {
return ee(e);
})(c.end(!0));
t(e), c.destroy();
}
function d() {
var t = a * o,
n = t + o;
a++, u(c, e, t, n, a < s ? f : l);
}
d();
}
function de(e) {
return i.hash(e);
}
function he(e, t) {
if (!t) return o.v4().replace(/-/g, "").toLowerCase();
var n = Object.assign({}, e);
return delete n._rev_tree, de(JSON.stringify(n));
}
var pe = o.v4;
function ve(e) {
for (var t, n, r, i, o = e.rev_tree.slice(); (i = o.pop()); ) {
var s = i.ids,
a = s[2],
c = i.pos;
if (a.length)
for (var u = 0, f = a.length; u < f; u++)
o.push({ pos: c + 1, ids: a[u] });
else {
var l = !!s[1].deleted,
d = s[0];
(t && !(r !== l ? r : n !== c ? n < c : t < d)) ||
((t = d), (n = c), (r = l));
}
}
return n + "-" + t;
}
function _e(e, t) {
for (var n, r = e.slice(); (n = r.pop()); )
for (
var i = n.pos,
o = n.ids,
s = o[2],
a = t(0 === s.length, i, o[0], n.ctx, o[1]),
c = 0,
u = s.length;
c < u;
c++
)
r.push({ pos: i + 1, ids: s[c], ctx: a });
}
function ye(e, t) {
return e.pos - t.pos;
}
function ge(e) {
var t = [];
_e(e, function (e, n, r, i, o) {
e && t.push({ rev: n + "-" + r, pos: n, opts: o });
}),
t.sort(ye).reverse();
for (var n = 0, r = t.length; n < r; n++) delete t[n].pos;
return t;
}
function me(e) {
for (
var t = ve(e),
n = ge(e.rev_tree),
r = [],
i = 0,
o = n.length;
i < o;
i++
) {
var s = n[i];
s.rev === t || s.opts.deleted || r.push(s.rev);
}
return r;
}
function be(e) {
for (var t, n = [], r = e.slice(); (t = r.pop()); ) {
var i = t.pos,
o = t.ids,
s = o[0],
a = o[1],
c = o[2],
u = 0 === c.length,
f = t.history ? t.history.slice() : [];
f.push({ id: s, opts: a }),
u && n.push({ pos: i + 1 - f.length, ids: f });
for (var l = 0, d = c.length; l < d; l++)
r.push({ pos: i + 1, ids: c[l], history: f });
}
return n.reverse();
}
function we(e, t) {
return e.pos - t.pos;
}
function ke(e, t, n) {
var r = (function (e, t, n) {
for (var r, i = 0, o = e.length; i < o; )
n(e[(r = (i + o) >>> 1)], t) < 0 ? (i = r + 1) : (o = r);
return i;
})(e, t, n);
e.splice(r, 0, t);
}
function je(e, t) {
for (var n, r, i = t, o = e.length; i < o; i++) {
var s = e[i],
a = [s.id, s.opts, []];
r ? (r[2].push(a), (r = a)) : (n = r = a);
}
return n;
}
function qe(e, t) {
return e[0] < t[0] ? -1 : 1;
}
function Oe(e, t) {
for (var n = [{ tree1: e, tree2: t }], r = !1; n.length > 0; ) {
var i = n.pop(),
o = i.tree1,
s = i.tree2;
(o[1].status || s[1].status) &&
(o[1].status =
"available" === o[1].status || "available" === s[1].status
? "available"
: "missing");
for (var a = 0; a < s[2].length; a++)
if (o[2][0]) {
for (var c = !1, u = 0; u < o[2].length; u++)
o[2][u][0] === s[2][a][0] &&
(n.push({ tree1: o[2][u], tree2: s[2][a] }),
(c = !0));
c || ((r = "new_branch"), ke(o[2], s[2][a], qe));
} else (r = "new_leaf"), (o[2][0] = s[2][a]);
}
return { conflicts: r, tree: e };
}
function Ae(e, t, n) {
var r,
i = [],
o = !1,
s = !1;
if (!e.length) return { tree: [t], conflicts: "new_leaf" };
for (var a = 0, c = e.length; a < c; a++) {
var u = e[a];
if (u.pos === t.pos && u.ids[0] === t.ids[0])
(r = Oe(u.ids, t.ids)),
i.push({ pos: u.pos, ids: r.tree }),
(o = o || r.conflicts),
(s = !0);
else if (!0 !== n) {
var f = u.pos < t.pos ? u : t,
l = u.pos < t.pos ? t : u,
d = l.pos - f.pos,
h = [],
p = [];
for (
p.push({
ids: f.ids,
diff: d,
parent: null,
parentIdx: null,
});
p.length > 0;
) {
var v = p.pop();
if (0 !== v.diff)
for (var _ = v.ids[2], y = 0, g = _.length; y < g; y++)
p.push({
ids: _[y],
diff: v.diff - 1,
parent: v.ids,
parentIdx: y,
});
else v.ids[0] === l.ids[0] && h.push(v);
}
var m = h[0];
m
? ((r = Oe(m.ids, l.ids)),
(m.parent[2][m.parentIdx] = r.tree),
i.push({ pos: f.pos, ids: f.ids }),
(o = o || r.conflicts),
(s = !0))
: i.push(u);
} else i.push(u);
}
return (
s || i.push(t),
i.sort(we),
{ tree: i, conflicts: o || "internal_node" }
);
}
function Se(e, t, n) {
var r = Ae(e, t),
i = (function (e, t) {
for (var n, r, i = be(e), o = 0, s = i.length; o < s; o++) {
var a,
c = i[o],
u = c.ids;
if (u.length > t) {
n || (n = {});
var f = u.length - t;
a = { pos: c.pos + f, ids: je(u, f) };
for (var l = 0; l < f; l++) {
var d = c.pos + l + "-" + u[l].id;
n[d] = !0;
}
} else a = { pos: c.pos, ids: je(u, 0) };
r = r ? Ae(r, a, !0).tree : [a];
}
return (
n &&
_e(r, function (e, t, r) {
delete n[t + "-" + r];
}),
{ tree: r, revs: n ? Object.keys(n) : [] }
);
})(r.tree, n);
return {
tree: i.tree,
stemmedRevs: i.revs,
conflicts: r.conflicts,
};
}
function xe(e) {
return e.ids;
}
function Pe(e, t) {
t || (t = ve(e));
for (
var n,
r = t.substring(t.indexOf("-") + 1),
i = e.rev_tree.map(xe);
(n = i.pop());
) {
if (n[0] === r) return !!n[1].deleted;
i = i.concat(n[2]);
}
}
function Ce(e) {
return "string" == typeof e && e.startsWith("_local/");
}
function Ee(e, t, n) {
var r = [{ rev: e._rev }];
"all_docs" === n.style &&
(r = ge(t.rev_tree).map(function (e) {
return { rev: e.rev };
}));
var i = { id: t.id, changes: r, doc: e };
return (
Pe(t, e._rev) && (i.deleted = !0),
n.conflicts &&
((i.doc._conflicts = me(t)),
i.doc._conflicts.length || delete i.doc._conflicts),
i
);
}
class $e extends a {
constructor(e, t, n) {
super(), (this.db = e);
var r = ((t = t ? f(t) : {}).complete = l((t, n) => {
var r, o;
t
? ((o = "error"),
("listenerCount" in (r = this)
? r.listenerCount(o)
: a.listenerCount(r, o)) > 0 && this.emit("error", t))
: this.emit("complete", n),
this.removeAllListeners(),
e.removeListener("destroyed", i);
}));
n &&
(this.on("complete", function (e) {
n(null, e);
}),
this.on("error", n));
const i = () => {
this.cancel();
};
e.once("destroyed", i),
(t.onChange = (e, t, n) => {
this.isCancelled ||
(function (e, t, n, r) {
try {
e.emit("change", t, n, r);
} catch (e) {
w("error", 'Error in .on("change", function):', e);
}
})(this, e, t, n);
});
var o = new Promise(function (e, n) {
t.complete = function (t, r) {
t ? n(t) : e(r);
};
});
this.once("cancel", function () {
e.removeListener("destroyed", i),
t.complete(null, { status: "cancelled" });
}),
(this.then = o.then.bind(o)),
(this.catch = o.catch.bind(o)),
this.then(function (e) {
r(null, e);
}, r),
e.taskqueue.isReady
? this.validateChanges(t)
: e.taskqueue.addTask((e) => {
e
? t.complete(e)
: this.isCancelled
? this.emit("cancel")
: this.validateChanges(t);
});
}
cancel() {
(this.isCancelled = !0),
this.db.taskqueue.isReady && this.emit("cancel");
}
validateChanges(e) {
var t = e.complete;
Ke._changesFilterPlugin
? Ke._changesFilterPlugin.validate(e, (n) => {
if (n) return t(n);
this.doChanges(e);
})
: this.doChanges(e);
}
doChanges(e) {
var t = e.complete;
if (
("live" in (e = f(e)) &&
!("continuous" in e) &&
(e.continuous = e.live),
(e.processChange = Ee),
"latest" === e.since && (e.since = "now"),
e.since || (e.since = 0),
"now" !== e.since)
) {
if (Ke._changesFilterPlugin) {
if (
(Ke._changesFilterPlugin.normalize(e),
Ke._changesFilterPlugin.shouldFilter(this, e))
)
return Ke._changesFilterPlugin.filter(this, e);
} else
["doc_ids", "filter", "selector", "view"].forEach(
function (t) {
t in e &&
w(
"warn",
'The "' +
t +
'" option was passed in to changes/replicate, but pouchdb-changes-filter plugin is not installed, so it was ignored. Please install the plugin to enable filtering.'
);
}
);
"descending" in e || (e.descending = !1),
(e.limit = 0 === e.limit ? 1 : e.limit),
(e.complete = t);
var n = this.db._changes(e);
if (n && "function" == typeof n.cancel) {
const e = this.cancel;
this.cancel = (...t) => {
n.cancel(), e.apply(this, t);
};
}
} else
this.db.info().then((n) => {
this.isCancelled
? t(null, { status: "cancelled" })
: ((e.since = n.update_seq), this.doChanges(e));
}, t);
}
}
function Ie(e, t) {
return function (n, r) {
n || (r[0] && r[0].error)
? (((n = n || r[0]).docId = t), e(n))
: e(null, r.length ? r[0] : r);
};
}
function Le(e, t) {
if (e._id === t._id) {
return (
(e._revisions ? e._revisions.start : 0) -
(t._revisions ? t._revisions.start : 0)
);
}
return e._id < t._id ? -1 : 1;
}
function De(e, t, n) {
return e
.get("_local/purges")
.then(function (e) {
const r = e.purgeSeq + 1;
return (
e.purges.push({ docId: t, rev: n, purgeSeq: r }),
e.purges.length > self.purged_infos_limit &&
e.purges.splice(
0,
e.purges.length - self.purged_infos_limit
),
(e.purgeSeq = r),
e
);
})
.catch(function (e) {
if (404 !== e.status) throw e;
return {
_id: "_local/purges",
purges: [{ docId: t, rev: n, purgeSeq: 0 }],
purgeSeq: 0,
};
})
.then(function (t) {
return e.put(t);
});
}
function Te(e) {
return null === e || "object" != typeof e || Array.isArray(e);
}
const Be = /^\d+-[^-]*$/;
function Me(e) {
return "string" == typeof e && Be.test(e);
}
class Re extends a {
_setup() {
(this.post = h("post", function (e, t, n) {
if (("function" == typeof t && ((n = t), (t = {})), Te(e)))
return n(N(T));
this.bulkDocs({ docs: [e] }, t, Ie(n, e._id));
}).bind(this)),
(this.put = h("put", function (e, t, n) {
if (
("function" == typeof t && ((n = t), (t = {})), Te(e))
)
return n(N(T));
if ((K(e._id), "_rev" in e && !Me(e._rev)))
return n(N(M));
if (Ce(e._id) && "function" == typeof this._putLocal)
return e._deleted
? this._removeLocal(e, n)
: this._putLocal(e, n);
const r = (n) => {
"function" == typeof this._put && !1 !== t.new_edits
? this._put(e, t, n)
: this.bulkDocs({ docs: [e] }, t, Ie(n, e._id));
};
var i, o, s, a;
t.force && e._rev
? ((i = e._rev.split("-")),
(o = i[1]),
(s = parseInt(i[0], 10) + 1),
(a = he()),
(e._revisions = { start: s, ids: [a, o] }),
(e._rev = s + "-" + a),
(t.new_edits = !1),
r(function (t) {
var r = t
? null
: { ok: !0, id: e._id, rev: e._rev };
n(t, r);
}))
: r(n);
}).bind(this)),
(this.putAttachment = h(
"putAttachment",
function (e, t, n, r, i) {
var o = this;
function s(e) {
var n = "_rev" in e ? parseInt(e._rev, 10) : 0;
return (
(e._attachments = e._attachments || {}),
(e._attachments[t] = {
content_type: i,
data: r,
revpos: ++n,
}),
o.put(e)
);
}
return (
"function" == typeof i &&
((i = r), (r = n), (n = null)),
void 0 === i && ((i = r), (r = n), (n = null)),
i ||
w(
"warn",
"Attachment",
t,
"on document",
e,
"is missing content_type"
),
o.get(e).then(
function (e) {
if (e._rev !== n) throw N(S);
return s(e);
},
function (t) {
if (t.reason === A.message) return s({ _id: e });
throw t;
}
)
);
}
).bind(this)),
(this.removeAttachment = h(
"removeAttachment",
function (e, t, n, r) {
this.get(e, (e, i) => {
if (e) r(e);
else if (i._rev === n) {
if (!i._attachments) return r();
delete i._attachments[t],
0 === Object.keys(i._attachments).length &&
delete i._attachments,
this.put(i, r);
} else r(N(S));
});
}
).bind(this)),
(this.remove = h("remove", function (e, t, n, r) {
var i;
"string" == typeof t
? ((i = { _id: e, _rev: t }),
"function" == typeof n && ((r = n), (n = {})))
: ((i = e),
"function" == typeof t
? ((r = t), (n = {}))
: ((r = n), (n = t))),
((n = n || {}).was_delete = !0);
var o = {
_id: i._id,
_rev: i._rev || n.rev,
_deleted: !0,
};
if (Ce(o._id) && "function" == typeof this._removeLocal)
return this._removeLocal(i, r);
this.bulkDocs({ docs: [o] }, n, Ie(r, o._id));
}).bind(this)),
(this.revsDiff = h("revsDiff", function (e, t, n) {
"function" == typeof t && ((n = t), (t = {}));
var r = Object.keys(e);
if (!r.length) return n(null, {});
var i = 0,
o = new Map();
function s(e, t) {
o.has(e) || o.set(e, { missing: [] }),
o.get(e).missing.push(t);
}
r.forEach(function (t) {
this._getRevisionTree(t, function (a, c) {
if (a && 404 === a.status && "missing" === a.message)
o.set(t, { missing: e[t] });
else {
if (a) return n(a);
!(function (t, n) {
var r = e[t].slice(0);
_e(n, function (e, n, i, o, a) {
var c = n + "-" + i,
u = r.indexOf(c);
-1 !== u &&
(r.splice(u, 1),
"available" !== a.status && s(t, c));
}),
r.forEach(function (e) {
s(t, e);
});
})(t, c);
}
if (++i === r.length) {
var u = {};
return (
o.forEach(function (e, t) {
u[t] = e;
}),
n(null, u)
);
}
});
}, this);
}).bind(this)),
(this.bulkGet = h("bulkGet", function (e, t) {
g(this, e, t);
}).bind(this)),
(this.compactDocument = h(
"compactDocument",
function (e, t, n) {
this._getRevisionTree(e, (r, i) => {
if (r) return n(r);
var o = (function (e) {
var t = {},
n = [];
return (
_e(e, function (e, r, i, o) {
var s = r + "-" + i;
return (
e && (t[s] = 0),
void 0 !== o && n.push({ from: o, to: s }),
s
);
}),
n.reverse(),
n.forEach(function (e) {
void 0 === t[e.from]
? (t[e.from] = 1 + t[e.to])
: (t[e.from] = Math.min(
t[e.from],
1 + t[e.to]
));
}),
t
);
})(i),
s = [],
a = [];
Object.keys(o).forEach(function (e) {
o[e] > t && s.push(e);
}),
_e(i, function (e, t, n, r, i) {
var o = t + "-" + n;
"available" === i.status &&
-1 !== s.indexOf(o) &&
a.push(o);
}),
this._doCompaction(e, a, n);
});
}
).bind(this)),
(this.compact = h("compact", function (e, t) {
"function" == typeof e && ((t = e), (e = {})),
(e = e || {}),
(this._compactionQueue = this._compactionQueue || []),
this._compactionQueue.push({ opts: e, callback: t }),
1 === this._compactionQueue.length &&
(function e(t) {
var n = t._compactionQueue[0],
r = n.opts,
i = n.callback;
t.get("_local/compaction")
.catch(function () {
return !1;
})
.then(function (n) {
n && n.last_seq && (r.last_seq = n.last_seq),
t._compact(r, function (n, r) {
n ? i(n) : i(null, r),
b(function () {
t._compactionQueue.shift(),
t._compactionQueue.length && e(t);
});
});
});
})(this);
}).bind(this)),
(this.get = h("get", function (e, t, n) {
if (
("function" == typeof t && ((n = t), (t = {})),
(t = t || {}),
"string" != typeof e)
)
return n(N(x));
if (Ce(e) && "function" == typeof this._getLocal)
return this._getLocal(e, n);
var r = [];
const i = () => {
var i = [],
o = r.length;
if (!o) return n(null, i);
r.forEach((r) => {
this.get(
e,
{
rev: r,
revs: t.revs,
latest: t.latest,
attachments: t.attachments,
binary: t.binary,
},
function (e, t) {
if (e) i.push({ missing: r });
else {
for (var s, a = 0, c = i.length; a < c; a++)
if (i[a].ok && i[a].ok._rev === t._rev) {
s = !0;
break;
}
s || i.push({ ok: t });
}
--o || n(null, i);
}
);
});
};
if (!t.open_revs)
return this._get(e, t, (r, i) => {
if (r) return (r.docId = e), n(r);
var o = i.doc,
s = i.metadata,
a = i.ctx;
if (t.conflicts) {
var c = me(s);
c.length && (o._conflicts = c);
}
if (
(Pe(s, o._rev) && (o._deleted = !0),
t.revs || t.revs_info)
) {
for (
var u = o._rev.split("-"),
f = parseInt(u[0], 10),
l = u[1],
d = be(s.rev_tree),
h = null,
p = 0;
p < d.length;
p++
) {
var v = d[p];
const e = v.ids.findIndex((e) => e.id === l);
(e === f - 1 || (!h && -1 !== e)) && (h = v);
}
if (!h)
return (
((r = new Error("invalid rev tree")).docId = e),
n(r)
);
const i = o._rev.split("-")[1],
a = h.ids.findIndex((e) => e.id === i) + 1;
var _ = h.ids.length - a;
if (
(h.ids.splice(a, _),
h.ids.reverse(),
t.revs &&
(o._revisions = {
start: h.pos + h.ids.length - 1,
ids: h.ids.map(function (e) {
return e.id;
}),
}),
t.revs_info)
) {
var y = h.pos + h.ids.length;
o._revs_info = h.ids.map(function (e) {
return {
rev: --y + "-" + e.id,
status: e.opts.status,
};
});
}
}
if (t.attachments && o._attachments) {
var g = o._attachments,
m = Object.keys(g).length;
if (0 === m) return n(null, o);
Object.keys(g).forEach((e) => {
this._getAttachment(
o._id,
e,
g[e],
{ binary: t.binary, metadata: s, ctx: a },
function (t, r) {
var i = o._attachments[e];
(i.data = r),
delete i.stub,
delete i.length,
--m || n(null, o);
}
);
});
} else {
if (o._attachments)
for (var b in o._attachments)
Object.prototype.hasOwnProperty.call(
o._attachments,
b
) && (o._attachments[b].stub = !0);
n(null, o);
}
});
if ("all" === t.open_revs)
this._getRevisionTree(e, function (e, t) {
if (e) return n(e);
(r = ge(t).map(function (e) {
return e.rev;
})),
i();
});
else {
if (!Array.isArray(t.open_revs))
return n(N(E, "function_clause"));
r = t.open_revs;
for (var o = 0; o < r.length; o++) {
if (!Me(r[o])) return n(N(M));
}
i();
}
}).bind(this)),
(this.getAttachment = h(
"getAttachment",
function (e, t, n, r) {
n instanceof Function && ((r = n), (n = {})),
this._get(e, n, (i, o) =>
i
? r(i)
: o.doc._attachments && o.doc._attachments[t]
? ((n.ctx = o.ctx),
(n.binary = !0),
(n.metadata = o.metadata),
void this._getAttachment(
e,
t,
o.doc._attachments[t],
n,
r
))
: r(N(A))
);
}
).bind(this)),
(this.allDocs = h("allDocs", function (e, t) {
if (
("function" == typeof e && ((t = e), (e = {})),
(e.skip = void 0 !== e.skip ? e.skip : 0),
e.start_key && (e.startkey = e.start_key),
e.end_key && (e.endkey = e.end_key),
"keys" in e)
) {
if (!Array.isArray(e.keys))
return t(
new TypeError("options.keys must be an array")
);
var n = ["startkey", "endkey", "key"].filter(function (
t
) {
return t in e;
})[0];
if (n)
return void t(
N(
I,
"Query parameter `" +
n +
"` is not compatible with multi-get"
)
);
if (
!J(this) &&
((function (e) {
var t =
"limit" in e
? e.keys.slice(e.skip, e.limit + e.skip)
: e.skip > 0
? e.keys.slice(e.skip)
: e.keys;
(e.keys = t),
(e.skip = 0),
delete e.limit,
e.descending &&
(t.reverse(), (e.descending = !1));
})(e),
0 === e.keys.length)
)
return this._allDocs({ limit: 0 }, t);
}
return this._allDocs(e, t);
}).bind(this)),
(this.close = h("close", function (e) {
return (
(this._closed = !0), this.emit("closed"), this._close(e)
);
}).bind(this)),
(this.info = h("info", function (e) {
this._info((t, n) => {
if (t) return e(t);
(n.db_name = n.db_name || this.name),
(n.auto_compaction = !(
!this.auto_compaction || J(this)
)),
(n.adapter = this.adapter),
e(null, n);
});
}).bind(this)),
(this.id = h("id", function (e) {
return this._id(e);
}).bind(this)),
(this.bulkDocs = h("bulkDocs", function (e, t, n) {
if (
("function" == typeof t && ((n = t), (t = {})),
(t = t || {}),
Array.isArray(e) && (e = { docs: e }),
!e || !e.docs || !Array.isArray(e.docs))
)
return n(N(O));
for (var r = 0; r < e.docs.length; ++r) {
const t = e.docs[r];
if (Te(t)) return n(N(T));
if ("_rev" in t && !Me(t._rev)) return n(N(M));
}
var i;
if (
(e.docs.forEach(function (e) {
e._attachments &&
Object.keys(e._attachments).forEach(function (t) {
(i =
i ||
(function (e) {
return (
"_" === e.charAt(0) &&
e +
" is not a valid attachment name, attachment names cannot start with '_'"
);
})(t)),
e._attachments[t].content_type ||
w(
"warn",
"Attachment",
t,
"on document",
e._id,
"is missing content_type"
);
});
}),
i)
)
return n(N(D, i));
"new_edits" in t ||
(t.new_edits = !("new_edits" in e) || e.new_edits);
var o = this;
t.new_edits || J(o) || e.docs.sort(Le),
(function (e) {
for (var t = 0; t < e.length; t++) {
var n = e[t];
if (n._deleted) delete n._attachments;
else if (n._attachments)
for (
var r = Object.keys(n._attachments), i = 0;
i < r.length;
i++
) {
var o = r[i];
n._attachments[o] = p(n._attachments[o], [
"data",
"digest",
"content_type",
"length",
"revpos",
"stub",
]);
}
}
})(e.docs);
var s = e.docs.map(function (e) {
return e._id;
});
this._bulkDocs(e, t, function (e, r) {
if (e) return n(e);
if (
(t.new_edits ||
(r = r.filter(function (e) {
return e.error;
})),
!J(o))
)
for (var i = 0, a = r.length; i < a; i++)
r[i].id = r[i].id || s[i];
n(null, r);
});
}).bind(this)),
(this.registerDependentDatabase = h(
"registerDependentDatabase",
function (e, t) {
var n = f(this.__opts);
this.__opts.view_adapter &&
(n.adapter = this.__opts.view_adapter);
var r = new this.constructor(e, n);
X(this, "_local/_pouch_dependentDbs", function (t) {
return (
(t.dependentDbs = t.dependentDbs || {}),
!t.dependentDbs[e] && ((t.dependentDbs[e] = !0), t)
);
})
.then(function () {
t(null, { db: r });
})
.catch(t);
}
).bind(this)),
(this.destroy = h("destroy", function (e, t) {
"function" == typeof e && ((t = e), (e = {}));
var n = !("use_prefix" in this) || this.use_prefix;
const r = () => {
this._destroy(e, (e, n) => {
if (e) return t(e);
(this._destroyed = !0),
this.emit("destroyed"),
t(null, n || { ok: !0 });
});
};
if (J(this)) return r();
this.get("_local/_pouch_dependentDbs", (e, i) => {
if (e) return 404 !== e.status ? t(e) : r();
var o = i.dependentDbs,
s = this.constructor,
a = Object.keys(o).map((e) => {
var t = n
? e.replace(new RegExp("^" + s.prefix), "")
: e;
return new s(t, this.__opts).destroy();
});
Promise.all(a).then(r, t);
});
}).bind(this));
}
_compact(e, t) {
var n,
r = {
return_docs: !1,
last_seq: e.last_seq || 0,
since: e.last_seq || 0,
},
i = [],
o = 0;
const s = (e) => {
this.activeTasks.update(n, { completed_items: ++o }),
i.push(this.compactDocument(e.id, 0));
},
a = (e) => {
this.activeTasks.remove(n, e), t(e);
},
c = (e) => {
var r = e.last_seq;
Promise.all(i)
.then(() =>
X(
this,
"_local/compaction",
(e) =>
(!e.last_seq || e.last_seq < r) &&
((e.last_seq = r), e)
)
)
.then(() => {
this.activeTasks.remove(n), t(null, { ok: !0 });
})
.catch(a);
};
this.info().then((e) => {
(n = this.activeTasks.add({
name: "database_compaction",
total_items: e.update_seq - r.last_seq,
})),
this.changes(r)
.on("change", s)
.on("complete", c)
.on("error", a);
});
}
changes(e, t) {
return (
"function" == typeof e && ((t = e), (e = {})),
((e = e || {}).return_docs =
"return_docs" in e ? e.return_docs : !e.live),
new $e(this, e, t)
);
}
type() {
return "function" == typeof this._type
? this._type()
: this.adapter;
}
}
Re.prototype.purge = h("_purge", function (e, t, n) {
if (void 0 === this._purge)
return n(
N(
E,
"Purge is not implemented in the " +
this.adapter +
" adapter."
)
);
var r = this;
r._getRevisionTree(e, (i, o) => {
if (i) return n(i);
if (!o) return n(N(A));
let s;
try {
s = (function (e, t) {
let n = [];
const r = e.slice();
let i;
for (; (i = r.pop()); ) {
const { pos: e, ids: o } = i,
s = `${e}-${o[0]}`,
a = o[2];
if ((n.push(s), s === t)) {
if (0 !== a.length)
throw new Error(
"The requested revision is not a leaf"
);
return n.reverse();
}
(0 === a.length || a.length > 1) && (n = []);
for (let t = 0, n = a.length; t < n; t++)
r.push({ pos: e + 1, ids: a[t] });
}
if (0 === n.length)
throw new Error(
"The requested revision does not exist"
);
return n.reverse();
})(o, t);
} catch (i) {
return n(i.message || i);
}
r._purge(e, s, (i, o) => {
if (i) return n(i);
De(r, e, t).then(function () {
return n(null, o);
});
});
});
});
class Ne {
constructor() {
(this.isReady = !1), (this.failed = !1), (this.queue = []);
}
execute() {
var e;
if (this.failed)
for (; (e = this.queue.shift()); ) e(this.failed);
else for (; (e = this.queue.shift()); ) e();
}
fail(e) {
(this.failed = e), this.execute();
}
ready(e) {
(this.isReady = !0), (this.db = e), this.execute();
}
addTask(e) {
this.queue.push(e), this.failed && this.execute();
}
}
function Ue(e, t) {
let n = function (...e) {
if (!(this instanceof n)) return new n(...e);
t.apply(this, e);
};
var r, i;
return (
(i = e),
((r = n).prototype = Object.create(i.prototype, {
constructor: { value: r },
})),
n
);
}
class Fe extends Re {
constructor(e, t) {
super(), this._setup(e, t);
}
_setup(e, t) {
if (
(super._setup(),
(t = t || {}),
e &&
"object" == typeof e &&
((e = (t = e).name), delete t.name),
void 0 === t.deterministic_revs &&
(t.deterministic_revs = !0),
(this.__opts = t = f(t)),
(this.auto_compaction = t.auto_compaction),
(this.purged_infos_limit = t.purged_infos_limit || 1e3),
(this.prefix = Ke.prefix),
"string" != typeof e)
)
throw new Error("Missing/invalid DB name");
var n = (function (e, t) {
var n = e.match(/([a-z-]*):\/\/(.*)/);
if (n)
return {
name: /https?/.test(n[1]) ? n[1] + "://" + n[2] : n[2],
adapter: n[1],
};
var r = Ke.adapters,
i = Ke.preferredAdapters,
o = Ke.prefix,
s = t.adapter;
if (!s)
for (
var a = 0;
a < i.length &&
"idb" === (s = i[a]) &&
"websql" in r &&
m() &&
localStorage["_pouch__websqldb_" + o + e];
++a
)
w(
"log",
'PouchDB is downgrading "' +
e +
'" to WebSQL to avoid data loss, because it was already opened with WebSQL.'
);
var c = r[s];
return {
name:
!c || !("use_prefix" in c) || c.use_prefix ? o + e : e,
adapter: s,
};
})((t.prefix || "") + e, t);
if (
((t.name = n.name),
(t.adapter = t.adapter || n.adapter),
(this.name = e),
(this._adapter = t.adapter),
Ke.emit("debug", [
"adapter",
"Picked adapter: ",
t.adapter,
]),
!Ke.adapters[t.adapter] || !Ke.adapters[t.adapter].valid())
)
throw new Error("Invalid Adapter: " + t.adapter);
if (
t.view_adapter &&
(!Ke.adapters[t.view_adapter] ||
!Ke.adapters[t.view_adapter].valid())
)
throw new Error("Invalid View Adapter: " + t.view_adapter);
(this.taskqueue = new Ne()),
(this.adapter = t.adapter),
Ke.adapters[t.adapter].call(this, t, (e) => {
if (e) return this.taskqueue.fail(e);
!(function (e) {
function t(t) {
e.removeListener("closed", n),
t || e.constructor.emit("destroyed", e.name);
}
function n() {
e.removeListener("destroyed", t),
e.constructor.emit("unref", e);
}
e.once("destroyed", t),
e.once("closed", n),
e.constructor.emit("ref", e);
})(this),
this.emit("created", this),
Ke.emit("created", this.name),
this.taskqueue.ready(this);
});
}
}
const Ke = Ue(Fe, function (e, t) {
Fe.prototype._setup.call(this, e, t);
});
var Je = fetch,
ze = Headers;
(Ke.adapters = {}),
(Ke.preferredAdapters = []),
(Ke.prefix = "_pouch_");
var Ve = new a();
!(function (e) {
Object.keys(a.prototype).forEach(function (t) {
"function" == typeof a.prototype[t] &&
(e[t] = Ve[t].bind(Ve));
});
var t = (e._destructionListeners = new Map());
e.on("ref", function (e) {
t.has(e.name) || t.set(e.name, []), t.get(e.name).push(e);
}),
e.on("unref", function (e) {
if (t.has(e.name)) {
var n = t.get(e.name),
r = n.indexOf(e);
r < 0 ||
(n.splice(r, 1),
n.length > 1 ? t.set(e.name, n) : t.delete(e.name));
}
}),
e.on("destroyed", function (e) {
if (t.has(e)) {
var n = t.get(e);
t.delete(e),
n.forEach(function (e) {
e.emit("destroyed", !0);
});
}
});
})(Ke),
(Ke.adapter = function (e, t, n) {
t.valid() &&
((Ke.adapters[e] = t), n && Ke.preferredAdapters.push(e));
}),
(Ke.plugin = function (e) {
if ("function" == typeof e) e(Ke);
else {
if ("object" != typeof e || 0 === Object.keys(e).length)
throw new Error(
'Invalid plugin: got "' +
e +
'", expected an object or a function'
);
Object.keys(e).forEach(function (t) {
Ke.prototype[t] = e[t];
});
}
return (
this.__defaults &&
(Ke.__defaults = Object.assign({}, this.__defaults)),
Ke
);
}),
(Ke.defaults = function (e) {
let t = Ue(Ke, function (e, n) {
(n = n || {}),
e &&
"object" == typeof e &&
((e = (n = e).name), delete n.name),
(n = Object.assign({}, t.__defaults, n)),
Ke.call(this, e, n);
});
return (
(t.preferredAdapters = Ke.preferredAdapters.slice()),
Object.keys(Ke).forEach(function (e) {
e in t || (t[e] = Ke[e]);
}),
(t.__defaults = Object.assign({}, this.__defaults, e)),
t
);
}),
(Ke.fetch = function (e, t) {
return Je(e, t);
}),
(Ke.prototype.activeTasks = Ke.activeTasks =
new (class {
constructor() {
this.tasks = {};
}
list() {
return Object.values(this.tasks);
}
add(e) {
const t = o.v4();
return (
(this.tasks[t] = {
id: t,
name: e.name,
total_items: e.total_items,
created_at: new Date().toJSON(),
}),
t
);
}
get(e) {
return this.tasks[e];
}
remove(e, t) {
return delete this.tasks[e], this.tasks;
}
update(e, t) {
const n = this.tasks[e];
if (void 0 !== n) {
const r = {
id: n.id,
name: n.name,
created_at: n.created_at,
total_items: t.total_items || n.total_items,
completed_items:
t.completed_items || n.completed_items,
updated_at: new Date().toJSON(),
};
this.tasks[e] = r;
}
return this.tasks;
}
})());
function Ge(e, t) {
for (var n = e, r = 0, i = t.length; r < i; r++) {
if (!(n = n[t[r]])) break;
}
return n;
}
function Qe(e) {
for (var t = [], n = "", r = 0, i = e.length; r < i; r++) {
var o = e[r];
r > 0 && "\\" === e[r - 1] && ("$" === o || "." === o)
? (n = n.substring(0, n.length - 1) + o)
: "." === o
? (t.push(n), (n = ""))
: (n += o);
}
return t.push(n), t;
}
var We = ["$or", "$nor", "$not"];
function Ye(e) {
return We.indexOf(e) > -1;
}
function He(e) {
return Object.keys(e)[0];
}
function Xe(e) {
var t = {},
n = { $or: !0, $nor: !0 };
return (
e.forEach(function (e) {
Object.keys(e).forEach(function (r) {
var i = e[r];
if (("object" != typeof i && (i = { $eq: i }), Ye(r)))
if (i instanceof Array) {
if (n[r]) return (n[r] = !1), void (t[r] = i);
var o = [];
t[r].forEach(function (e) {
Object.keys(i).forEach(function (t) {
var n = i[t],
r = Math.max(
Object.keys(e).length,
Object.keys(n).length
),
s = Xe([e, n]);
Object.keys(s).length <= r || o.push(s);
});
}),
(t[r] = o);
} else t[r] = Xe([i]);
else {
var s = (t[r] = t[r] || {});
Object.keys(i).forEach(function (e) {
var t = i[e];
return "$gt" === e || "$gte" === e
? (function (e, t, n) {
if (void 0 !== n.$eq) return;
void 0 !== n.$gte
? "$gte" === e
? t > n.$gte && (n.$gte = t)
: t >= n.$gte &&
(delete n.$gte, (n.$gt = t))
: void 0 !== n.$gt
? "$gte" === e
? t > n.$gt && (delete n.$gt, (n.$gte = t))
: t > n.$gt && (n.$gt = t)
: (n[e] = t);
})(e, t, s)
: "$lt" === e || "$lte" === e
? (function (e, t, n) {
if (void 0 !== n.$eq) return;
void 0 !== n.$lte
? "$lte" === e
? t < n.$lte && (n.$lte = t)
: t <= n.$lte &&
(delete n.$lte, (n.$lt = t))
: void 0 !== n.$lt
? "$lte" === e
? t < n.$lt && (delete n.$lt, (n.$lte = t))
: t < n.$lt && (n.$lt = t)
: (n[e] = t);
})(e, t, s)
: "$ne" === e
? (function (e, t) {
"$ne" in t ? t.$ne.push(e) : (t.$ne = [e]);
})(t, s)
: "$eq" === e
? (function (e, t) {
delete t.$gt,
delete t.$gte,
delete t.$lt,
delete t.$lte,
delete t.$ne,
(t.$eq = e);
})(t, s)
: "$regex" === e
? (function (e, t) {
"$regex" in t
? t.$regex.push(e)
: (t.$regex = [e]);
})(t, s)
: void (s[e] = t);
});
}
});
}),
t
);
}
function Ze(e) {
var t = f(e);
(function e(t, n) {
for (var r in t) {
"$and" === r && (n = !0);
var i = t[r];
"object" == typeof i && (n = e(i, n));
}
return n;
})(t, !1) &&
"$and" in
(t = (function e(t) {
for (var n in t) {
if (Array.isArray(t))
for (var r in t) t[r].$and && (t[r] = Xe(t[r].$and));
var i = t[n];
"object" == typeof i && e(i);
}
return t;
})(t)) &&
(t = Xe(t.$and)),
["$or", "$nor"].forEach(function (e) {
e in t &&
t[e].forEach(function (e) {
for (var t = Object.keys(e), n = 0; n < t.length; n++) {
var r = t[n],
i = e[r];
("object" == typeof i && null !== i) ||
(e[r] = { $eq: i });
}
});
}),
"$not" in t && (t.$not = Xe([t.$not]));
for (var n = Object.keys(t), r = 0; r < n.length; r++) {
var i = n[r],
o = t[i];
("object" == typeof o && null !== o) || (o = { $eq: o }),
(t[i] = o);
}
return (
(function e(t) {
Object.keys(t).forEach(function (n) {
var r = t[n];
Array.isArray(r)
? r.forEach(function (t) {
t && "object" == typeof t && e(t);
})
: "$ne" === n
? (t.$ne = [r])
: "$regex" === n
? (t.$regex = [r])
: r && "object" == typeof r && e(r);
});
})(t),
t
);
}
function et(e, t) {
if (e === t) return 0;
(e = tt(e)), (t = tt(t));
var n = st(e),
r = st(t);
if (n - r != 0) return n - r;
switch (typeof e) {
case "number":
return e - t;
case "boolean":
return e < t ? -1 : 1;
case "string":
return (function (e, t) {
return e === t ? 0 : e > t ? 1 : -1;
})(e, t);
}
return Array.isArray(e)
? (function (e, t) {
for (
var n = Math.min(e.length, t.length), r = 0;
r < n;
r++
) {
var i = et(e[r], t[r]);
if (0 !== i) return i;
}
return e.length === t.length
? 0
: e.length > t.length
? 1
: -1;
})(e, t)
: (function (e, t) {
for (
var n = Object.keys(e),
r = Object.keys(t),
i = Math.min(n.length, r.length),
o = 0;
o < i;
o++
) {
var s = et(n[o], r[o]);
if (0 !== s) return s;
if (0 !== (s = et(e[n[o]], t[r[o]]))) return s;
}
return n.length === r.length
? 0
: n.length > r.length
? 1
: -1;
})(e, t);
}
function tt(e) {
switch (typeof e) {
case "undefined":
return null;
case "number":
return e === 1 / 0 || e === -1 / 0 || isNaN(e) ? null : e;
case "object":
var t = e;
if (Array.isArray(e)) {
var n = e.length;
e = new Array(n);
for (var r = 0; r < n; r++) e[r] = tt(t[r]);
} else {
if (e instanceof Date) return e.toJSON();
if (null !== e)
for (var i in ((e = {}), t))
if (Object.prototype.hasOwnProperty.call(t, i)) {
var o = t[i];
void 0 !== o && (e[i] = tt(o));
}
}
}
return e;
}
function nt(e) {
if (null !== e)
switch (typeof e) {
case "boolean":
return e ? 1 : 0;
case "number":
return (function (e) {
if (0 === e) return "1";
var t = e.toExponential().split(/e\+?/),
n = parseInt(t[1], 10),
r = e < 0,
i = r ? "0" : "2",
o =
((s = ((r ? -n : n) - -324).toString()),
(a = "0"),
(c = 3),
(function (e, t, n) {
for (var r = "", i = n - e.length; r.length < i; )
r += t;
return r;
})(s, a, c) + s);
var s, a, c;
i += "" + o;
var u = Math.abs(parseFloat(t[0]));
r && (u = 10 - u);
var f = u.toFixed(20);
return (f = f.replace(/\.?0+$/, "")), (i += "" + f);
})(e);
case "string":
return e
.replace(/\u0002/g, "\x02\x02")
.replace(/\u0001/g, "\x01\x02")
.replace(/\u0000/g, "\x01\x01");
case "object":
var t = Array.isArray(e),
n = t ? e : Object.keys(e),
r = -1,
i = n.length,
o = "";
if (t) for (; ++r < i; ) o += rt(n[r]);
else
for (; ++r < i; ) {
var s = n[r];
o += rt(s) + rt(e[s]);
}
return o;
}
return "";
}
function rt(e) {
return st((e = tt(e))) + "" + nt(e) + "\0";
}
function it(e, t) {
var n,
r = t;
if ("1" === e[t]) (n = 0), t++;
else {
var i = "0" === e[t];
t++;
var o = "",
s = e.substring(t, t + 3),
a = parseInt(s, 10) + -324;
for (i && (a = -a), t += 3; ; ) {
var c = e[t];
if ("\0" === c) break;
(o += c), t++;
}
(n =
1 === (o = o.split(".")).length
? parseInt(o, 10)
: parseFloat(o[0] + "." + o[1])),
i && (n -= 10),
0 !== a && (n = parseFloat(n + "e" + a));
}
return { num: n, length: t - r };
}
function ot(e, t) {
var n = e.pop();
if (t.length) {
var r = t[t.length - 1];
n === r.element && (t.pop(), (r = t[t.length - 1]));
var i = r.element,
o = r.index;
if (Array.isArray(i)) i.push(n);
else if (o === e.length - 2) {
i[e.pop()] = n;
} else e.push(n);
}
}
function st(e) {
var t = ["boolean", "number", "string", "object"].indexOf(
typeof e
);
return ~t
? null === e
? 1
: Array.isArray(e)
? 5
: t < 3
? t + 2
: t + 3
: Array.isArray(e)
? 5
: void 0;
}
function at(e, t, n) {
if (
((e = e.filter(function (e) {
return ct(e.doc, t.selector, n);
})),
t.sort)
) {
var r = (function (e) {
function t(t) {
return e.map(function (e) {
var n = Qe(He(e));
return Ge(t, n);
});
}
return function (e, n) {
var r,
i,
o = et(t(e.doc), t(n.doc));
return 0 !== o
? o
: ((r = e.doc._id),
(i = n.doc._id),
r < i ? -1 : r > i ? 1 : 0);
};
})(t.sort);
(e = e.sort(r)),
"string" != typeof t.sort[0] &&
"desc" === (i = t.sort[0])[He(i)] &&
(e = e.reverse());
}
var i;
if ("limit" in t || "skip" in t) {
var o = t.skip || 0,
s = ("limit" in t ? t.limit : e.length) + o;
e = e.slice(o, s);
}
return e;
}
function ct(e, t, n) {
return n.every(function (n) {
var r = t[n],
i = Qe(n),
o = Ge(e, i);
return Ye(n)
? (function (e, t, n) {
if ("$or" === e)
return t.some(function (e) {
return ct(n, e, Object.keys(e));
});
if ("$not" === e) return !ct(n, t, Object.keys(t));
return !t.find(function (e) {
return ct(n, e, Object.keys(e));
});
})(n, r, e)
: ut(r, e, i, o);
});
}
function ut(e, t, n, r) {
return (
!e ||
("object" == typeof e
? Object.keys(e).every(function (i) {
var o = e[i];
if (0 === i.indexOf("$")) return ft(i, t, o, n, r);
var s = Qe(i);
if (
void 0 === r &&
"object" != typeof o &&
s.length > 0
)
return !1;
var a = Ge(r, s);
return "object" == typeof o
? ut(o, t, n, a)
: ft("$eq", t, o, s, a);
})
: e === r)
);
}
function ft(e, t, n, r, i) {
if (!pt[e])
throw new Error(
'unknown operator "' +
e +
'" - should be one of $eq, $lte, $lt, $gt, $gte, $exists, $ne, $in, $nin, $size, $mod, $regex, $elemMatch, $type, $allMatch or $all'
);
return pt[e](t, n, r, i);
}
function lt(e) {
return null != e;
}
function dt(e) {
return void 0 !== e;
}
function ht(e, t) {
return t.some(function (t) {
return e instanceof Array
? e.some(function (e) {
return 0 === et(t, e);
})
: 0 === et(t, e);
});
}
var pt = {
$elemMatch: function (e, t, n, r) {
return (
!!Array.isArray(r) &&
0 !== r.length &&
("object" == typeof r[0] && null !== r[0]
? r.some(function (e) {
return ct(e, t, Object.keys(t));
})
: r.some(function (r) {
return ut(t, e, n, r);
}))
);
},
$allMatch: function (e, t, n, r) {
return (
!!Array.isArray(r) &&
0 !== r.length &&
("object" == typeof r[0] && null !== r[0]
? r.every(function (e) {
return ct(e, t, Object.keys(t));
})
: r.every(function (r) {
return ut(t, e, n, r);
}))
);
},
$eq: function (e, t, n, r) {
return dt(r) && 0 === et(r, t);
},
$gte: function (e, t, n, r) {
return dt(r) && et(r, t) >= 0;
},
$gt: function (e, t, n, r) {
return dt(r) && et(r, t) > 0;
},
$lte: function (e, t, n, r) {
return dt(r) && et(r, t) <= 0;
},
$lt: function (e, t, n, r) {
return dt(r) && et(r, t) < 0;
},
$exists: function (e, t, n, r) {
return t ? dt(r) : !dt(r);
},
$mod: function (e, t, n, r) {
return (
lt(r) &&
(function (e, t) {
return (
"number" == typeof e &&
parseInt(e, 10) === e &&
e % t[0] === t[1]
);
})(r, t)
);
},
$ne: function (e, t, n, r) {
return t.every(function (e) {
return 0 !== et(r, e);
});
},
$in: function (e, t, n, r) {
return lt(r) && ht(r, t);
},
$nin: function (e, t, n, r) {
return lt(r) && !ht(r, t);
},
$size: function (e, t, n, r) {
return (
lt(r) &&
Array.isArray(r) &&
(function (e, t) {
return e.length === t;
})(r, t)
);
},
$all: function (e, t, n, r) {
return (
Array.isArray(r) &&
(function (e, t) {
return t.every(function (t) {
return e.some(function (e) {
return 0 === et(t, e);
});
});
})(r, t)
);
},
$regex: function (e, t, n, r) {
return (
lt(r) &&
"string" == typeof r &&
t.every(function (e) {
return (function (e, t) {
return new RegExp(t).test(e);
})(r, e);
})
);
},
$type: function (e, t, n, r) {
return (function (e, t) {
switch (t) {
case "null":
return null === e;
case "boolean":
return "boolean" == typeof e;
case "number":
return "number" == typeof e;
case "string":
return "string" == typeof e;
case "array":
return e instanceof Array;
case "object":
return "[object Object]" === {}.toString.call(e);
}
})(r, t);
},
};
function vt(e, t) {
if (e.selector && e.filter && "_selector" !== e.filter) {
var n = "string" == typeof e.filter ? e.filter : "function";
return t(
new Error('selector invalid for filter "' + n + '"')
);
}
t();
}
function _t(e) {
e.view && !e.filter && (e.filter = "_view"),
e.selector && !e.filter && (e.filter = "_selector"),
e.filter &&
"string" == typeof e.filter &&
("_view" === e.filter
? (e.view = V(e.view))
: (e.filter = V(e.filter)));
}
function yt(e, t) {
return (
t.filter &&
"string" == typeof t.filter &&
!t.doc_ids &&
!J(e.db)
);
}
function gt(e, t) {
var n = t.complete;
if ("_view" === t.filter) {
if (!t.view || "string" != typeof t.view) {
var r = N(
D,
"`view` filter parameter not found or invalid."
);
return n(r);
}
var i = z(t.view);
e.db.get("_design/" + i[0], function (r, o) {
if (e.isCancelled) return n(null, { status: "cancelled" });
if (r) return n(U(r));
var s = o && o.views && o.views[i[1]] && o.views[i[1]].map;
if (!s)
return n(
N(
A,
o.views
? "missing json key: " + i[1]
: "missing json key: views"
)
);
(t.filter = H(
[
"return function(doc) {",
' "use strict";',
" var emitted = false;",
" var emit = function (a, b) {",
" emitted = true;",
" };",
" var view = " + s + ";",
" view(doc);",
" if (emitted) {",
" return true;",
" }",
"};",
].join("\n"),
{}
)),
e.doChanges(t);
});
} else if (t.selector)
(t.filter = function (e) {
return (function (e, t) {
if ("object" != typeof t)
throw new Error(
"Selector error: expected a JSON object"
);
var n = at(
[{ doc: e }],
{ selector: (t = Ze(t)) },
Object.keys(t)
);
return n && 1 === n.length;
})(e, t.selector);
}),
e.doChanges(t);
else {
var o = z(t.filter);
e.db.get("_design/" + o[0], function (r, i) {
if (e.isCancelled) return n(null, { status: "cancelled" });
if (r) return n(U(r));
var s = i && i.filters && i.filters[o[1]];
if (!s)
return n(
N(
A,
i && i.filters
? "missing json key: " + o[1]
: "missing json key: filters"
)
);
(t.filter = H('"use strict";\nreturn ' + s + ";", {})),
e.doChanges(t);
});
}
}
function mt(e) {
return e.reduce(function (e, t) {
return (e[t] = !0), e;
}, {});
}
Ke.plugin(function (e) {
e._changesFilterPlugin = {
validate: vt,
normalize: _t,
shouldFilter: yt,
filter: gt,
};
}),
(Ke.version = "9.0.0");
var bt = mt([
"_id",
"_rev",
"_access",
"_attachments",
"_deleted",
"_revisions",
"_revs_info",
"_conflicts",
"_deleted_conflicts",
"_local_seq",
"_rev_tree",
"_replication_id",
"_replication_state",
"_replication_state_time",
"_replication_state_reason",
"_replication_stats",
"_removed",
]),
wt = mt([
"_access",
"_attachments",
"_replication_id",
"_replication_state",
"_replication_state_time",
"_replication_state_reason",
"_replication_stats",
]);
function kt(e) {
if (!/^\d+-/.test(e)) return N(M);
var t = e.indexOf("-"),
n = e.substring(0, t),
r = e.substring(t + 1);
return { prefix: parseInt(n, 10), id: r };
}
function jt(e, t, n) {
var r, i, o;
n || (n = { deterministic_revs: !0 });
var s = { status: "available" };
if ((e._deleted && (s.deleted = !0), t))
if (
(e._id || (e._id = pe()),
(i = he(e, n.deterministic_revs)),
e._rev)
) {
if ((o = kt(e._rev)).error) return o;
(e._rev_tree = [
{
pos: o.prefix,
ids: [o.id, { status: "missing" }, [[i, s, []]]],
},
]),
(r = o.prefix + 1);
} else (e._rev_tree = [{ pos: 1, ids: [i, s, []] }]), (r = 1);
else if (
(e._revisions &&
((e._rev_tree = (function (e, t) {
for (
var n = e.start - e.ids.length + 1,
r = e.ids,
i = [r[0], t, []],
o = 1,
s = r.length;
o < s;
o++
)
i = [r[o], { status: "missing" }, [i]];
return [{ pos: n, ids: i }];
})(e._revisions, s)),
(r = e._revisions.start),
(i = e._revisions.ids[0])),
!e._rev_tree)
) {
if ((o = kt(e._rev)).error) return o;
(r = o.prefix),
(i = o.id),
(e._rev_tree = [{ pos: r, ids: [i, s, []] }]);
}
K(e._id), (e._rev = r + "-" + i);
var a = { metadata: {}, data: {} };
for (var c in e)
if (Object.prototype.hasOwnProperty.call(e, c)) {
var u = "_" === c[0];
if (u && !bt[c]) {
var f = N(L, c);
throw ((f.message = L.message + ": " + c), f);
}
u && !wt[c]
? (a.metadata[c.slice(1)] = e[c])
: (a.data[c] = e[c]);
}
return a;
}
function qt(e, t, n) {
var r = (function (e) {
try {
return Z(e);
} catch (e) {
return {
error: N($, "Attachment is not a valid base64 string"),
};
}
})(e.data);
if (r.error) return n(r.error);
(e.length = r.length),
(e.data =
"blob" === t
? re(r, e.content_type)
: "base64" === t
? ee(r)
: r),
le(r, function (t) {
(e.digest = "md5-" + t), n();
});
}
function Ot(e, t, n) {
if (e.stub) return n();
"string" == typeof e.data
? qt(e, t, n)
: (function (e, t, n) {
le(e.data, function (r) {
(e.digest = "md5-" + r),
(e.length = e.data.size || e.data.length || 0),
"binary" === t
? se(e.data, function (t) {
(e.data = t), n();
})
: "base64" === t
? ae(e.data, function (t) {
(e.data = t), n();
})
: n();
});
})(e, t, n);
}
function At(e, t, n, r, i, o, s, a) {
if (
(function (e, t) {
for (
var n,
r = e.slice(),
i = t.split("-"),
o = parseInt(i[0], 10),
s = i[1];
(n = r.pop());
) {
if (n.pos === o && n.ids[0] === s) return !0;
for (var a = n.ids[2], c = 0, u = a.length; c < u; c++)
r.push({ pos: n.pos + 1, ids: a[c] });
}
return !1;
})(t.rev_tree, n.metadata.rev) &&
!a
)
return (r[i] = n), o();
var c = t.winningRev || ve(t),
u = "deleted" in t ? t.deleted : Pe(t, c),
f =
"deleted" in n.metadata
? n.metadata.deleted
: Pe(n.metadata),
l = /^1-/.test(n.metadata.rev);
if (u && !f && a && l) {
var d = n.data;
(d._rev = c), (d._id = n.metadata.id), (n = jt(d, a));
}
var h = Se(t.rev_tree, n.metadata.rev_tree[0], e);
if (
a &&
((u && f && "new_leaf" !== h.conflicts) ||
(!u && "new_leaf" !== h.conflicts) ||
(u && !f && "new_branch" === h.conflicts))
) {
var p = N(S);
return (r[i] = p), o();
}
var v = n.metadata.rev;
(n.metadata.rev_tree = h.tree),
(n.stemmedRevs = h.stemmedRevs || []),
t.rev_map && (n.metadata.rev_map = t.rev_map);
var _ = ve(n.metadata),
y = Pe(n.metadata, _),
g = u === y ? 0 : u < y ? -1 : 1;
s(n, _, y, v === _ ? y : Pe(n.metadata, v), !0, g, i, o);
}
function St(e, t, n, r, i, o, s, a, c) {
e = e || 1e3;
var u = a.new_edits,
f = new Map(),
l = 0,
d = t.length;
function h() {
++l === d && c && c();
}
t.forEach(function (e, t) {
if (e._id && Ce(e._id)) {
var r = e._deleted ? "_removeLocal" : "_putLocal";
n[r](e, { ctx: i }, function (e, n) {
(o[t] = e || n), h();
});
} else {
var s = e.metadata.id;
f.has(s)
? (d--, f.get(s).push([e, t]))
: f.set(s, [[e, t]]);
}
}),
f.forEach(function (t, n) {
var i = 0;
function c() {
++i < t.length ? f() : h();
}
function f() {
var f = t[i],
l = f[0],
d = f[1];
if (r.has(n)) At(e, r.get(n), l, o, d, c, s, u);
else {
var h = Se([], l.metadata.rev_tree[0], e);
(l.metadata.rev_tree = h.tree),
(l.stemmedRevs = h.stemmedRevs || []),
(function (e, t, n) {
var r = ve(e.metadata),
i = Pe(e.metadata, r);
if ("was_delete" in a && i)
return (o[t] = N(A, "deleted")), n();
if (
u &&
(function (e) {
return (
"missing" ===
e.metadata.rev_tree[0].ids[1].status
);
})(e)
) {
var c = N(S);
return (o[t] = c), n();
}
s(e, r, i, i, !1, i ? 0 : 1, t, n);
})(l, d, c);
}
}
f();
});
}
var xt = "document-store",
Pt = "meta-store";
function Ct(e) {
try {
return JSON.stringify(e);
} catch (t) {
return s.stringify(e);
}
}
function Et(e) {
return function (t) {
var n = "unknown_error";
t.target &&
t.target.error &&
(n = t.target.error.name || t.target.error.message),
e(N(B, n, t.type));
};
}
function $t(e, t, n) {
return {
data: Ct(e),
winningRev: t,
deletedOrLocal: n ? "1" : "0",
seq: e.seq,
id: e.id,
};
}
function It(e) {
if (!e) return null;
var t = (function (e) {
try {
return JSON.parse(e);
} catch (t) {
return s.parse(e);
}
})(e.data);
return (
(t.winningRev = e.winningRev),
(t.deleted = "1" === e.deletedOrLocal),
(t.seq = e.seq),
t
);
}
function Lt(e) {
if (!e) return e;
var t = e._doc_id_rev.lastIndexOf(":");
return (
(e._id = e._doc_id_rev.substring(0, t - 1)),
(e._rev = e._doc_id_rev.substring(t + 1)),
delete e._doc_id_rev,
e
);
}
function Dt(e, t, n, r) {
n
? r(
e
? "string" != typeof e
? e
: ie(e, t)
: te([""], { type: t })
)
: e
? "string" != typeof e
? oe(e, function (e) {
r(ee(e));
})
: r(e)
: r("");
}
function Tt(e, t, n, r) {
var i = Object.keys(e._attachments || {});
if (!i.length) return r && r();
var o = 0;
function s() {
++o === i.length && r && r();
}
i.forEach(function (r) {
t.attachments && t.include_docs
? (function (e, t) {
var r = e._attachments[t],
i = r.digest;
n.objectStore("attach-store").get(i).onsuccess =
function (e) {
(r.body = e.target.result.body), s();
};
})(e, r)
: ((e._attachments[r].stub = !0), s());
});
}
function Bt(e, t) {
return Promise.all(
e.map(function (e) {
if (e.doc && e.doc._attachments) {
var n = Object.keys(e.doc._attachments);
return Promise.all(
n.map(function (n) {
var r = e.doc._attachments[n];
if ("body" in r) {
var i = r.body,
o = r.content_type;
return new Promise(function (s) {
Dt(i, o, t, function (t) {
(e.doc._attachments[n] = Object.assign(
p(r, ["digest", "content_type"]),
{ data: t }
)),
s();
});
});
}
})
);
}
})
);
}
function Mt(e, t, n) {
var r = [],
i = n.objectStore("by-sequence"),
o = n.objectStore("attach-store"),
s = n.objectStore("attach-seq-store"),
a = e.length;
function c() {
--a ||
(function () {
if (!r.length) return;
r.forEach(function (e) {
s
.index("digestSeq")
.count(
IDBKeyRange.bound(e + "::", e + "::\uffff", !1, !1)
).onsuccess = function (t) {
t.target.result || o.delete(e);
};
});
})();
}
e.forEach(function (e) {
var n = i.index("_doc_id_rev"),
o = t + "::" + e;
n.getKey(o).onsuccess = function (e) {
var t = e.target.result;
if ("number" != typeof t) return c();
i.delete(t),
(s
.index("seq")
.openCursor(IDBKeyRange.only(t)).onsuccess = function (
e
) {
var t = e.target.result;
if (t) {
var n = t.value.digestSeq.split("::")[0];
r.push(n), s.delete(t.primaryKey), t.continue();
} else c();
});
};
});
}
function Rt(e, t, n) {
try {
return { txn: e.transaction(t, n) };
} catch (e) {
return { error: e };
}
}
var Nt = new (class extends a {
constructor() {
super(),
(this._listeners = {}),
m() &&
addEventListener("storage", (e) => {
this.emit(e.key);
});
}
addListener(e, t, n, r) {
if (!this._listeners[t]) {
var i = !1,
o = this;
(this._listeners[t] = s), this.on(e, s);
}
function s() {
if (o._listeners[t])
if (i) i = "waiting";
else {
i = !0;
var e = p(r, [
"style",
"include_docs",
"attachments",
"conflicts",
"filter",
"doc_ids",
"view",
"since",
"query_params",
"binary",
"return_docs",
]);
n.changes(e)
.on("change", function (e) {
e.seq > r.since &&
!r.cancelled &&
((r.since = e.seq), r.onChange(e));
})
.on("complete", function () {
"waiting" === i && b(s), (i = !1);
})
.on("error", function () {
i = !1;
});
}
}
}
removeListener(e, t) {
t in this._listeners &&
(super.removeListener(e, this._listeners[t]),
delete this._listeners[t]);
}
notifyLocalWindows(e) {
m() &&
(localStorage[e] = "a" === localStorage[e] ? "b" : "a");
}
notify(e) {
this.emit(e), this.notifyLocalWindows(e);
}
})();
function Ut(e, t, n, r, i, o) {
for (
var s, a, c, u, f, l, d, h, p = t.docs, v = 0, _ = p.length;
v < _;
v++
) {
var y = p[v];
(y._id && Ce(y._id)) ||
((y = p[v] = jt(y, n.new_edits, e)).error && !d && (d = y));
}
if (d) return o(d);
var g = !1,
m = 0,
b = new Array(p.length),
w = new Map(),
k = !1,
j = r._meta.blobSupport ? "blob" : "base64";
function q() {
(g = !0), O();
}
function O() {
h && g && ((h.docCount += m), l.put(h));
}
function A() {
k || (Nt.notify(r._meta.name), o(null, b));
}
function S(e, t, n, r, i, o, s, a) {
(e.metadata.winningRev = t), (e.metadata.deleted = n);
var c = e.data;
if (
((c._id = e.metadata.id),
(c._rev = e.metadata.rev),
r && (c._deleted = !0),
c._attachments && Object.keys(c._attachments).length)
)
return (function (e, t, n, r, i, o) {
var s = e.data,
a = 0,
c = Object.keys(s._attachments);
function f() {
a === c.length && x(e, t, n, r, i, o);
}
function l() {
a++, f();
}
c.forEach(function (n) {
var r = e.data._attachments[n];
if (r.stub) a++, f();
else {
var i = r.data;
delete r.data,
(r.revpos = parseInt(t, 10)),
(function (e, t, n) {
u.count(e).onsuccess = function (r) {
if (r.target.result) return n();
var i = { digest: e, body: t };
u.put(i).onsuccess = n;
};
})(r.digest, i, l);
}
});
})(e, t, n, i, s, a);
(m += o), O(), x(e, t, n, i, s, a);
}
function x(e, t, n, i, o, u) {
var l = e.data,
d = e.metadata;
function h(o) {
var c = e.stemmedRevs || [];
i &&
r.auto_compaction &&
(c = c.concat(
(function (e) {
var t = [];
return (
_e(e.rev_tree, function (e, n, r, i, o) {
"available" !== o.status ||
e ||
(t.push(n + "-" + r), (o.status = "missing"));
}),
t
);
})(e.metadata)
)),
c && c.length && Mt(c, e.metadata.id, s),
(d.seq = o.target.result);
var u = $t(d, t, n);
a.put(u).onsuccess = p;
}
function p() {
(b[o] = { ok: !0, id: d.id, rev: d.rev }),
w.set(e.metadata.id, e.metadata),
(function (e, t, n) {
var r = 0,
i = Object.keys(e.data._attachments || {});
if (!i.length) return n();
function o() {
++r === i.length && n();
}
function s(n) {
var r = e.data._attachments[n].digest,
i = f.put({ seq: t, digestSeq: r + "::" + t });
(i.onsuccess = o),
(i.onerror = function (e) {
e.preventDefault(), e.stopPropagation(), o();
});
}
for (var a = 0; a < i.length; a++) s(i[a]);
})(e, d.seq, u);
}
(l._doc_id_rev = d.id + "::" + d.rev),
delete l._id,
delete l._rev;
var v = c.put(l);
(v.onsuccess = h),
(v.onerror = function (e) {
e.preventDefault(),
e.stopPropagation(),
(c
.index("_doc_id_rev")
.getKey(l._doc_id_rev).onsuccess = function (e) {
c.put(l, e.target.result).onsuccess = h;
});
});
}
!(function (e, t, n) {
if (!e.length) return n();
var r,
i = 0;
function o() {
i++, e.length === i && (r ? n(r) : n());
}
e.forEach(function (e) {
var n =
e.data && e.data._attachments
? Object.keys(e.data._attachments)
: [],
i = 0;
if (!n.length) return o();
function s(e) {
(r = e), ++i === n.length && o();
}
for (var a in e.data._attachments)
Object.prototype.hasOwnProperty.call(
e.data._attachments,
a
) && Ot(e.data._attachments[a], t, s);
});
})(p, j, function (t) {
if (t) return o(t);
!(function () {
var t = Rt(
i,
[
xt,
"by-sequence",
"attach-store",
"local-store",
"attach-seq-store",
Pt,
],
"readwrite"
);
if (t.error) return o(t.error);
((s = t.txn).onabort = Et(o)),
(s.ontimeout = Et(o)),
(s.oncomplete = A),
(a = s.objectStore(xt)),
(c = s.objectStore("by-sequence")),
(u = s.objectStore("attach-store")),
(f = s.objectStore("attach-seq-store")),
((l = s.objectStore(Pt)).get(Pt).onsuccess = function (
e
) {
(h = e.target.result), O();
}),
(function (e) {
var t = [];
if (
(p.forEach(function (e) {
e.data &&
e.data._attachments &&
Object.keys(e.data._attachments).forEach(
function (n) {
var r = e.data._attachments[n];
r.stub && t.push(r.digest);
}
);
}),
!t.length)
)
return e();
var n,
r = 0;
t.forEach(function (i) {
!(function (e, t) {
u.get(e).onsuccess = function (n) {
if (n.target.result) t();
else {
var r = N(
R,
"unknown stub attachment with digest " + e
);
(r.status = 412), t(r);
}
};
})(i, function (i) {
i && !n && (n = i), ++r === t.length && e(n);
});
});
})(function (t) {
if (t) return (k = !0), o(t);
!(function () {
if (!p.length) return;
var t = 0;
function i() {
++t === p.length &&
St(e.revs_limit, p, r, w, s, b, S, n, q);
}
function o(e) {
var t = It(e.target.result);
t && w.set(t.id, t), i();
}
for (var c = 0, u = p.length; c < u; c++) {
var f = p[c];
if (f._id && Ce(f._id)) i();
else a.get(f.metadata.id).onsuccess = o;
}
})();
});
})();
});
}
function Ft(e, t, n, r, i) {
var o, s, a;
function c(e) {
(s = e.target.result), o && i(o, s, a);
}
function u(e) {
(o = e.target.result), s && i(o, s, a);
}
function f(e) {
var t = e.target.result;
if (!t) return i();
i([t.key], [t.value], t);
}
-1 === r && (r = 1e3),
"function" == typeof e.getAll &&
"function" == typeof e.getAllKeys &&
r > 1 &&
!n
? ((a = {
continue: function () {
if (!o.length) return i();
var n,
a = o[o.length - 1];
if (t && t.upper)
try {
n = IDBKeyRange.bound(
a,
t.upper,
!0,
t.upperOpen
);
} catch (e) {
if ("DataError" === e.name && 0 === e.code)
return i();
}
else n = IDBKeyRange.lowerBound(a, !0);
(t = n),
(o = null),
(s = null),
(e.getAll(t, r).onsuccess = c),
(e.getAllKeys(t, r).onsuccess = u);
},
}),
(e.getAll(t, r).onsuccess = c),
(e.getAllKeys(t, r).onsuccess = u))
: n
? (e.openCursor(t, "prev").onsuccess = f)
: (e.openCursor(t).onsuccess = f);
}
function Kt(e, t, n) {
var r,
i,
o = "startkey" in e && e.startkey,
s = "endkey" in e && e.endkey,
a = "key" in e && e.key,
c = "keys" in e && e.keys,
u = e.skip || 0,
f = "number" == typeof e.limit ? e.limit : -1,
l = !1 !== e.inclusive_end;
if (
!c &&
(i =
(r = (function (e, t, n, r, i) {
try {
if (e && t)
return i
? IDBKeyRange.bound(t, e, !n, !1)
: IDBKeyRange.bound(e, t, !1, !n);
if (e)
return i
? IDBKeyRange.upperBound(e)
: IDBKeyRange.lowerBound(e);
if (t)
return i
? IDBKeyRange.lowerBound(t, !n)
: IDBKeyRange.upperBound(t, !n);
if (r) return IDBKeyRange.only(r);
} catch (e) {
return { error: e };
}
return null;
})(o, s, l, a, e.descending)) && r.error) &&
("DataError" !== i.name || 0 !== i.code)
)
return n(N(B, i.name, i.message));
var d = [xt, "by-sequence", Pt];
e.attachments && d.push("attach-store");
var h = Rt(t, d, "readonly");
if (h.error) return n(h.error);
var p = h.txn;
(p.oncomplete = function () {
e.attachments ? Bt(w, e.binary).then(O) : O();
}),
(p.onabort = Et(n));
var v,
_,
y = p.objectStore(xt),
g = p.objectStore("by-sequence"),
m = p.objectStore(Pt),
b = g.index("_doc_id_rev"),
w = [];
function k(t, n) {
var r = { id: n.id, key: n.id, value: { rev: t } };
n.deleted
? c && (w.push(r), (r.value.deleted = !0), (r.doc = null))
: u-- <= 0 &&
(w.push(r),
e.include_docs &&
(function (t, n, r) {
var i = t.id + "::" + r;
b.get(i).onsuccess = function (r) {
if (
((n.doc = Lt(r.target.result) || {}), e.conflicts)
) {
var i = me(t);
i.length && (n.doc._conflicts = i);
}
Tt(n.doc, e, p);
};
})(n, r, t));
}
function j(e) {
for (var t = 0, n = e.length; t < n && w.length !== f; t++) {
var r = e[t];
if (r.error && c) w.push(r);
else {
var i = It(r);
k(i.winningRev, i);
}
}
}
function q(e, t, n) {
n && (j(t), w.length < f && n.continue());
}
function O() {
var t = { total_rows: v, offset: e.skip, rows: w };
e.update_seq && void 0 !== _ && (t.update_seq = _),
n(null, t);
}
return (
(m.get(Pt).onsuccess = function (e) {
v = e.target.result.docCount;
}),
e.update_seq &&
(g.openKeyCursor(null, "prev").onsuccess = (e) => {
var t = e.target.result;
t && t.key && (_ = t.key);
}),
i || 0 === f
? void 0
: c
? (function (e, t, n) {
var r = new Array(e.length),
i = 0;
e.forEach(function (o, s) {
t.get(o).onsuccess = function (t) {
t.target.result
? (r[s] = t.target.result)
: (r[s] = { key: o, error: "not_found" }),
++i === e.length && n(e, r, {});
};
});
})(c, y, q)
: -1 === f
? (function (e, t, n) {
if ("function" != typeof e.getAll) {
var r = [];
e.openCursor(t).onsuccess = function (e) {
var t = e.target.result;
t
? (r.push(t.value), t.continue())
: n({ target: { result: r } });
};
} else e.getAll(t).onsuccess = n;
})(y, r, function (t) {
var n = t.target.result;
e.descending && (n = n.reverse()), j(n);
})
: void Ft(y, r, e.descending, f + u, q)
);
}
var Jt = !1,
zt = [];
function Vt() {
!Jt && zt.length && ((Jt = !0), zt.shift()());
}
function Gt(e, t, n, r) {
if ((e = f(e)).continuous) {
var i = n + ":" + pe();
return (
Nt.addListener(n, i, t, e),
Nt.notify(n),
{
cancel: function () {
Nt.removeListener(n, i);
},
}
);
}
var o = e.doc_ids && new Set(e.doc_ids);
e.since = e.since || 0;
var s = e.since,
a = "limit" in e ? e.limit : -1;
0 === a && (a = 1);
var c,
u,
l,
d,
h = [],
p = 0,
v = F(e),
_ = new Map();
function y(e, t, n, r) {
if (n.seq !== t) return r();
if (n.winningRev === e._rev) return r(n, e);
var i = e._id + "::" + n.winningRev;
d.get(i).onsuccess = function (e) {
r(n, Lt(e.target.result));
};
}
function g() {
e.complete(null, { results: h, last_seq: s });
}
var m = [xt, "by-sequence"];
e.attachments && m.push("attach-store");
var b = Rt(r, m, "readonly");
if (b.error) return e.complete(b.error);
((c = b.txn).onabort = Et(e.complete)),
(c.oncomplete = function () {
!e.continuous && e.attachments ? Bt(h).then(g) : g();
}),
(u = c.objectStore("by-sequence")),
(l = c.objectStore(xt)),
(d = u.index("_doc_id_rev")),
Ft(
u,
e.since && !e.descending
? IDBKeyRange.lowerBound(e.since, !0)
: null,
e.descending,
a,
function (t, n, r) {
if (r && t.length) {
var i = new Array(t.length),
u = new Array(t.length),
f = 0;
n.forEach(function (n, s) {
!(function (e, t, n) {
if (o && !o.has(e._id)) return n();
var r = _.get(e._id);
if (r) return y(e, t, r, n);
l.get(e._id).onsuccess = function (i) {
(r = It(i.target.result)),
_.set(e._id, r),
y(e, t, r, n);
};
})(Lt(n), t[s], function (n, o) {
(u[s] = n),
(i[s] = o),
++f === t.length &&
(function () {
for (
var t = [], n = 0, o = i.length;
n < o && p !== a;
n++
) {
var s = i[n];
if (s) {
var c = u[n];
t.push(d(c, s));
}
}
Promise.all(t)
.then(function (t) {
for (var n = 0, r = t.length; n < r; n++)
t[n] && e.onChange(t[n]);
})
.catch(e.complete),
p !== a && r.continue();
})();
});
});
}
function d(t, n) {
var r = e.processChange(n, t, e);
s = r.seq = t.seq;
var i = v(r);
return "object" == typeof i
? Promise.reject(i)
: i
? (p++,
e.return_docs && h.push(r),
e.attachments && e.include_docs
? new Promise(function (t) {
Tt(n, e, c, function () {
Bt([r], e.binary).then(function () {
t(r);
});
});
})
: Promise.resolve(r))
: Promise.resolve();
}
}
);
}
var Qt,
Wt = new Map(),
Yt = new Map();
function Ht(e, t) {
var n = this;
!(function (e, t, n) {
zt.push(function () {
e(function (e, r) {
!(function (e, t, n, r) {
try {
e(t, n);
} catch (t) {
r.emit("error", t);
}
})(t, e, r, n),
(Jt = !1),
b(function () {
Vt();
});
});
}),
Vt();
})(
function (t) {
!(function (e, t, n) {
var r = t.name,
i = null,
o = null;
function s(e) {
return function (t, n) {
t &&
t instanceof Error &&
!t.reason &&
o &&
(t.reason = o),
e(t, n);
};
}
function a(e, t) {
var n = e.objectStore(xt);
n.createIndex("deletedOrLocal", "deletedOrLocal", {
unique: !1,
}),
(n.openCursor().onsuccess = function (e) {
var r = e.target.result;
if (r) {
var i = r.value,
o = Pe(i);
(i.deletedOrLocal = o ? "1" : "0"),
n.put(i),
r.continue();
} else t();
});
}
function c(e, t) {
var n = e.objectStore("local-store"),
r = e.objectStore(xt),
i = e.objectStore("by-sequence");
r.openCursor().onsuccess = function (e) {
var o = e.target.result;
if (o) {
var s = o.value,
a = s.id,
c = Ce(a),
u = ve(s);
if (c) {
var f = a + "::" + u,
l = a + "::",
d = a + "::~",
h = i.index("_doc_id_rev"),
p = IDBKeyRange.bound(l, d, !1, !1),
v = h.openCursor(p);
v.onsuccess = function (e) {
if ((v = e.target.result)) {
var t = v.value;
t._doc_id_rev === f && n.put(t),
i.delete(v.primaryKey),
v.continue();
} else r.delete(o.primaryKey), o.continue();
};
} else o.continue();
} else t && t();
};
}
function u(e, t) {
var n = e.objectStore("by-sequence"),
r = e.objectStore("attach-store"),
i = e.objectStore("attach-seq-store");
r.count().onsuccess = function (e) {
if (!e.target.result) return t();
n.openCursor().onsuccess = function (e) {
var n = e.target.result;
if (!n) return t();
for (
var r = n.value,
o = n.primaryKey,
s = Object.keys(r._attachments || {}),
a = {},
c = 0;
c < s.length;
c++
) {
a[r._attachments[s[c]].digest] = !0;
}
var u = Object.keys(a);
for (c = 0; c < u.length; c++) {
var f = u[c];
i.put({ seq: o, digestSeq: f + "::" + o });
}
n.continue();
};
};
}
function f(e) {
var t = e.objectStore("by-sequence"),
n = e.objectStore(xt);
n.openCursor().onsuccess = function (e) {
var r = e.target.result;
if (r) {
var i,
o = (i = r.value).data
? It(i)
: ((i.deleted = "1" === i.deletedOrLocal), i);
if (((o.winningRev = o.winningRev || ve(o)), o.seq))
return s();
!(function () {
var e = o.id + "::",
n = o.id + "::\uffff",
r = t
.index("_doc_id_rev")
.openCursor(IDBKeyRange.bound(e, n)),
i = 0;
r.onsuccess = function (e) {
var t = e.target.result;
if (!t) return (o.seq = i), s();
var n = t.primaryKey;
n > i && (i = n), t.continue();
};
})();
}
function s() {
var e = $t(o, o.winningRev, o.deleted);
n.put(e).onsuccess = function () {
r.continue();
};
}
};
}
(e._meta = null),
(e._remote = !1),
(e.type = function () {
return "idb";
}),
(e._id = d(function (t) {
t(null, e._meta.instanceId);
})),
(e._bulkDocs = function (n, r, o) {
Ut(t, n, r, e, i, s(o));
}),
(e._get = function (e, t, n) {
var r,
o,
s,
a = t.ctx;
if (!a) {
var c = Rt(
i,
[xt, "by-sequence", "attach-store"],
"readonly"
);
if (c.error) return n(c.error);
a = c.txn;
}
function u() {
n(s, { doc: r, metadata: o, ctx: a });
}
a.objectStore(xt).get(e).onsuccess = function (e) {
if (!(o = It(e.target.result)))
return (s = N(A, "missing")), u();
var n;
if (t.rev)
n = t.latest
? (function (e, t) {
for (
var n, r = t.rev_tree.slice();
(n = r.pop());
) {
var i = n.pos,
o = n.ids,
s = o[0],
a = o[1],
c = o[2],
u = 0 === c.length,
f = n.history ? n.history.slice() : [];
if (
(f.push({ id: s, pos: i, opts: a }), u)
)
for (
var l = 0, d = f.length;
l < d;
l++
) {
var h = f[l];
if (h.pos + "-" + h.id === e)
return i + "-" + s;
}
for (var p = 0, v = c.length; p < v; p++)
r.push({
pos: i + 1,
ids: c[p],
history: f,
});
}
throw new Error(
"Unable to resolve latest revision for id " +
t.id +
", rev " +
e
);
})(t.rev, o)
: t.rev;
else if (((n = o.winningRev), Pe(o)))
return (s = N(A, "deleted")), u();
var i = a.objectStore("by-sequence"),
c = o.id + "::" + n;
i.index("_doc_id_rev").get(c).onsuccess = function (
e
) {
if (((r = e.target.result) && (r = Lt(r)), !r))
return (s = N(A, "missing")), u();
u();
};
};
}),
(e._getAttachment = function (e, t, n, r, o) {
var s;
if (r.ctx) s = r.ctx;
else {
var a = Rt(
i,
[xt, "by-sequence", "attach-store"],
"readonly"
);
if (a.error) return o(a.error);
s = a.txn;
}
var c = n.digest,
u = n.content_type;
s.objectStore("attach-store").get(c).onsuccess =
function (e) {
Dt(
e.target.result.body,
u,
r.binary,
function (e) {
o(null, e);
}
);
};
}),
(e._info = function (t) {
var n,
r,
o = Rt(i, [Pt, "by-sequence"], "readonly");
if (o.error) return t(o.error);
var s = o.txn;
(s.objectStore(Pt).get(Pt).onsuccess = function (e) {
r = e.target.result.docCount;
}),
(s
.objectStore("by-sequence")
.openKeyCursor(null, "prev").onsuccess =
function (e) {
var t = e.target.result;
n = t ? t.key : 0;
}),
(s.oncomplete = function () {
t(null, {
doc_count: r,
update_seq: n,
idb_attachment_format: e._meta.blobSupport
? "binary"
: "base64",
});
});
}),
(e._allDocs = function (e, t) {
Kt(e, i, s(t));
}),
(e._changes = function (t) {
return Gt(t, e, r, i);
}),
(e._close = function (e) {
i.close(), Wt.delete(r), e();
}),
(e._getRevisionTree = function (e, t) {
var n = Rt(i, [xt], "readonly");
if (n.error) return t(n.error);
n.txn.objectStore(xt).get(e).onsuccess = function (
e
) {
var n = It(e.target.result);
n ? t(null, n.rev_tree) : t(N(A));
};
}),
(e._doCompaction = function (e, t, n) {
var r = Rt(
i,
[
xt,
"by-sequence",
"attach-store",
"attach-seq-store",
],
"readwrite"
);
if (r.error) return n(r.error);
var o = r.txn;
(o.objectStore(xt).get(e).onsuccess = function (n) {
var r = It(n.target.result);
_e(r.rev_tree, function (e, n, r, i, o) {
var s = n + "-" + r;
-1 !== t.indexOf(s) && (o.status = "missing");
}),
Mt(t, e, o);
var i = r.winningRev,
s = r.deleted;
o.objectStore(xt).put($t(r, i, s));
}),
(o.onabort = Et(n)),
(o.oncomplete = function () {
n();
});
}),
(e._getLocal = function (e, t) {
var n = Rt(i, ["local-store"], "readonly");
if (n.error) return t(n.error);
var r = n.txn.objectStore("local-store").get(e);
(r.onerror = Et(t)),
(r.onsuccess = function (e) {
var n = e.target.result;
n ? (delete n._doc_id_rev, t(null, n)) : t(N(A));
});
}),
(e._putLocal = function (e, t, n) {
"function" == typeof t && ((n = t), (t = {})),
delete e._revisions;
var r = e._rev,
o = e._id;
e._rev = r
? "0-" + (parseInt(r.split("-")[1], 10) + 1)
: "0-1";
var s,
a = t.ctx;
if (!a) {
var c = Rt(i, ["local-store"], "readwrite");
if (c.error) return n(c.error);
((a = c.txn).onerror = Et(n)),
(a.oncomplete = function () {
s && n(null, s);
});
}
var u,
f = a.objectStore("local-store");
r
? ((u = f.get(o)).onsuccess = function (i) {
var o = i.target.result;
o && o._rev === r
? (f.put(e).onsuccess = function () {
(s = { ok: !0, id: e._id, rev: e._rev }),
t.ctx && n(null, s);
})
: n(N(S));
})
: (((u = f.add(e)).onerror = function (e) {
n(N(S)),
e.preventDefault(),
e.stopPropagation();
}),
(u.onsuccess = function () {
(s = { ok: !0, id: e._id, rev: e._rev }),
t.ctx && n(null, s);
}));
}),
(e._removeLocal = function (e, t, n) {
"function" == typeof t && ((n = t), (t = {}));
var r,
o = t.ctx;
if (!o) {
var s = Rt(i, ["local-store"], "readwrite");
if (s.error) return n(s.error);
(o = s.txn).oncomplete = function () {
r && n(null, r);
};
}
var a = e._id,
c = o.objectStore("local-store"),
u = c.get(a);
(u.onerror = Et(n)),
(u.onsuccess = function (i) {
var o = i.target.result;
o && o._rev === e._rev
? (c.delete(a),
(r = { ok: !0, id: a, rev: "0-0" }),
t.ctx && n(null, r))
: n(N(A));
});
}),
(e._destroy = function (e, t) {
Nt.removeAllListeners(r);
var n = Yt.get(r);
n && n.result && (n.result.close(), Wt.delete(r));
var i = indexedDB.deleteDatabase(r);
(i.onsuccess = function () {
Yt.delete(r),
m() &&
r in localStorage &&
delete localStorage[r],
t(null, { ok: !0 });
}),
(i.onerror = Et(t));
});
var l = Wt.get(r);
if (l)
return (
(i = l.idb),
(e._meta = l.global),
b(function () {
n(null, e);
})
);
var h = indexedDB.open(r, 5);
Yt.set(r, h),
(h.onupgradeneeded = function (e) {
var t = e.target.result;
if (e.oldVersion < 1)
return (function (e) {
var t = e.createObjectStore(xt, {
keyPath: "id",
});
e
.createObjectStore("by-sequence", {
autoIncrement: !0,
})
.createIndex("_doc_id_rev", "_doc_id_rev", {
unique: !0,
}),
e.createObjectStore("attach-store", {
keyPath: "digest",
}),
e.createObjectStore(Pt, {
keyPath: "id",
autoIncrement: !1,
}),
e.createObjectStore("detect-blob-support"),
t.createIndex(
"deletedOrLocal",
"deletedOrLocal",
{ unique: !1 }
),
e.createObjectStore("local-store", {
keyPath: "_id",
});
var n = e.createObjectStore("attach-seq-store", {
autoIncrement: !0,
});
n.createIndex("seq", "seq"),
n.createIndex("digestSeq", "digestSeq", {
unique: !0,
});
})(t);
var n = e.currentTarget.transaction;
e.oldVersion < 3 &&
(function (e) {
e.createObjectStore("local-store", {
keyPath: "_id",
}).createIndex("_doc_id_rev", "_doc_id_rev", {
unique: !0,
});
})(t),
e.oldVersion < 4 &&
(function (e) {
var t = e.createObjectStore(
"attach-seq-store",
{ autoIncrement: !0 }
);
t.createIndex("seq", "seq"),
t.createIndex("digestSeq", "digestSeq", {
unique: !0,
});
})(t);
var r = [a, c, u, f],
i = e.oldVersion;
!(function e() {
var t = r[i - 1];
i++, t && t(n, e);
})();
}),
(h.onsuccess = function (t) {
((i = t.target.result).onversionchange = function () {
i.close(), Wt.delete(r);
}),
(i.onabort = function (e) {
w(
"error",
"Database has a global failure",
e.target.error
),
(o = e.target.error),
i.close(),
Wt.delete(r);
});
var s,
a,
c,
u,
f = i.transaction(
[Pt, "detect-blob-support", xt],
"readwrite"
),
l = !1;
function d() {
void 0 !== c &&
l &&
((e._meta = {
name: r,
instanceId: u,
blobSupport: c,
}),
Wt.set(r, { idb: i, global: e._meta }),
n(null, e));
}
function h() {
if (void 0 !== a && void 0 !== s) {
var e = r + "_id";
e in s ? (u = s[e]) : (s[e] = u = pe()),
(s.docCount = a),
f.objectStore(Pt).put(s);
}
}
(f.objectStore(Pt).get(Pt).onsuccess = function (e) {
(s = e.target.result || { id: Pt }), h();
}),
(function (e, t) {
e
.objectStore(xt)
.index("deletedOrLocal")
.count(IDBKeyRange.only("0")).onsuccess =
function (e) {
t(e.target.result);
};
})(f, function (e) {
(a = e), h();
}),
Qt ||
(Qt = (function (e, t, n) {
return new Promise(function (r) {
var i = te([""]);
let o;
if ("function" == typeof n) {
const r = n(i);
o = e.objectStore(t).put(r);
} else {
const r = n;
o = e.objectStore(t).put(i, r);
}
(o.onsuccess = function () {
var e =
navigator.userAgent.match(
/Chrome\/(\d+)/
),
t = navigator.userAgent.match(/Edge\//);
r(t || !e || parseInt(e[1], 10) >= 43);
}),
(o.onerror = e.onabort =
function (e) {
e.preventDefault(),
e.stopPropagation(),
r(!1);
});
}).catch(function () {
return !1;
});
})(f, "detect-blob-support", "key")),
Qt.then(function (e) {
(c = e), d();
}),
(f.oncomplete = function () {
(l = !0), d();
}),
(f.onabort = Et(n));
}),
(h.onerror = function (e) {
var t = e.target.error && e.target.error.message;
t
? -1 !==
t.indexOf(
"stored database is a higher version"
) &&
(t = new Error(
'This DB was created with the newer "indexeddb" adapter, but you are trying to open it with the older "idb" adapter'
))
: (t =
"Failed to open indexedDB, are you in private browsing mode?"),
w("error", t),
n(N(B, t));
});
})(n, e, t);
},
t,
n.constructor
);
}
Ht.valid = function () {
try {
return (
"undefined" != typeof indexedDB &&
"undefined" != typeof IDBKeyRange
);
} catch (e) {
return !1;
}
};
const Xt = {};
function Zt(e) {
const t = e.doc || e.ok,
n = t && t._attachments;
n &&
Object.keys(n).forEach(function (e) {
const t = n[e];
t.data = ie(t.data, t.content_type);
});
}
function en(e) {
return /^_design/.test(e)
? "_design/" + encodeURIComponent(e.slice(8))
: e.startsWith("_local/")
? "_local/" + encodeURIComponent(e.slice(7))
: encodeURIComponent(e);
}
function tn(e) {
return e._attachments && Object.keys(e._attachments)
? Promise.all(
Object.keys(e._attachments).map(function (t) {
const n = e._attachments[t];
if (n.data && "string" != typeof n.data)
return new Promise(function (e) {
ae(n.data, e);
}).then(function (e) {
n.data = e;
});
})
)
: Promise.resolve();
}
function nn(e, t) {
if (
(function (e) {
if (!e.prefix) return !1;
const t = Y(e.prefix).protocol;
return "http" === t || "https" === t;
})(t)
) {
const n = t.name.substr(t.prefix.length);
e = t.prefix.replace(/\/?$/, "/") + encodeURIComponent(n);
}
const n = Y(e);
(n.user || n.password) &&
(n.auth = { username: n.user, password: n.password });
const r = n.path.replace(/(^\/|\/$)/g, "").split("/");
return (
(n.db = r.pop()),
-1 === n.db.indexOf("%") && (n.db = encodeURIComponent(n.db)),
(n.path = r.join("/")),
n
);
}
function rn(e, t) {
return on(e, e.db + "/" + t);
}
function on(e, t) {
const n = e.path ? "/" : "";
return (
e.protocol +
"://" +
e.host +
(e.port ? ":" + e.port : "") +
"/" +
e.path +
n +
t
);
}
function sn(e) {
const t = Object.keys(e);
return 0 === t.length
? ""
: "?" +
t
.map((t) => t + "=" + encodeURIComponent(e[t]))
.join("&");
}
function an(e, t) {
const r = this,
i = nn(e.name, e),
o = rn(i, "");
e = f(e);
const s = async function (t, n) {
if (
(((n = n || {}).headers = n.headers || new ze()),
(n.credentials = "include"),
e.auth || i.auth)
) {
const t = e.auth || i.auth,
r = t.username + ":" + t.password,
o = ee(unescape(encodeURIComponent(r)));
n.headers.set("Authorization", "Basic " + o);
}
const r = e.headers || {};
Object.keys(r).forEach(function (e) {
n.headers.append(e, r[e]);
}),
(function (e) {
const t =
"undefined" != typeof navigator && navigator.userAgent
? navigator.userAgent.toLowerCase()
: "",
n = -1 !== t.indexOf("msie"),
r = -1 !== t.indexOf("trident"),
i = -1 !== t.indexOf("edge"),
o = !("method" in e) || "GET" === e.method;
return (n || r || i) && o;
})(n) &&
(t +=
(-1 === t.indexOf("?") ? "?" : "&") +
"_nonce=" +
Date.now());
const o = e.fetch || Je;
return await o(t, n);
};
function a(e, t) {
return h(e, function (...e) {
l()
.then(function () {
return t.apply(this, e);
})
.catch(function (t) {
e.pop()(t);
});
}).bind(r);
}
async function c(e, t) {
const n = {};
((t = t || {}).headers = t.headers || new ze()),
t.headers.get("Content-Type") ||
t.headers.set("Content-Type", "application/json"),
t.headers.get("Accept") ||
t.headers.set("Accept", "application/json");
const r = await s(e, t);
(n.ok = r.ok), (n.status = r.status);
const i = await r.json();
if (((n.data = i), !n.ok)) {
n.data.status = n.status;
throw U(n.data);
}
return (
Array.isArray(n.data) &&
(n.data = n.data.map(function (e) {
return e.error || e.missing ? U(e) : e;
})),
n
);
}
let u;
async function l() {
return e.skip_setup
? Promise.resolve()
: u ||
((u = c(o)
.catch(function (e) {
return e && e.status && 404 === e.status
? (j(
404,
"PouchDB is just detecting if the remote exists."
),
c(o, { method: "PUT" }))
: Promise.reject(e);
})
.catch(function (e) {
return (
!(!e || !e.status || 412 !== e.status) ||
Promise.reject(e)
);
})),
u.catch(function () {
u = null;
}),
u);
}
function d(e) {
return e.split("/").map(encodeURIComponent).join("/");
}
b(function () {
t(null, r);
}),
(r._remote = !0),
(r.type = function () {
return "http";
}),
(r.id = a("id", async function (e) {
let t;
try {
const e = await s(on(i, ""));
t = await e.json();
} catch (e) {
t = {};
}
e(null, t && t.uuid ? t.uuid + i.db : rn(i, ""));
})),
(r.compact = a("compact", async function (e, t) {
"function" == typeof e && ((t = e), (e = {})),
(e = f(e)),
await c(rn(i, "_compact"), { method: "POST" }),
(function n() {
r.info(function (r, i) {
i && !i.compact_running
? t(null, { ok: !0 })
: setTimeout(n, e.interval || 200);
});
})();
})),
(r.bulkGet = h("bulkGet", function (e, t) {
const n = this;
async function r(t) {
const n = {};
e.revs && (n.revs = !0),
e.attachments && (n.attachments = !0),
e.latest && (n.latest = !0);
try {
const r = await c(rn(i, "_bulk_get" + sn(n)), {
method: "POST",
body: JSON.stringify({ docs: e.docs }),
});
e.attachments &&
e.binary &&
r.data.results.forEach(function (e) {
e.docs.forEach(Zt);
}),
t(null, r.data);
} catch (e) {
t(e);
}
}
function o() {
const r = Math.ceil(e.docs.length / 50);
let i = 0;
const o = new Array(r);
function s(e) {
return function (n, s) {
(o[e] = s.results),
++i === r && t(null, { results: o.flat() });
};
}
for (let t = 0; t < r; t++) {
const r = p(e, [
"revs",
"attachments",
"binary",
"latest",
]);
(r.docs = e.docs.slice(
50 * t,
Math.min(e.docs.length, 50 * (t + 1))
)),
g(n, r, s(t));
}
}
const s = on(i, ""),
a = Xt[s];
"boolean" != typeof a
? r(function (e, n) {
e
? ((Xt[s] = !1),
j(
e.status,
"PouchDB is just detecting if the remote supports the _bulk_get API."
),
o())
: ((Xt[s] = !0), t(null, n));
})
: a
? r(t)
: o();
})),
(r._info = async function (e) {
try {
await l();
const t = await s(rn(i, "")),
n = await t.json();
(n.host = rn(i, "")), e(null, n);
} catch (t) {
e(t);
}
}),
(r.fetch = async function (e, t) {
await l();
const n =
"/" === e.substring(0, 1)
? on(i, e.substring(1))
: rn(i, e);
return s(n, t);
}),
(r.get = a("get", async function (e, t, n) {
"function" == typeof t && ((n = t), (t = {}));
const r = {};
function o(e) {
const n = e._attachments,
r = n && Object.keys(n);
if (!n || !r.length) return;
return (function (e, t) {
return new Promise(function (n, r) {
var i,
o = 0,
s = 0,
a = 0,
c = e.length;
function u() {
++a === c ? (i ? r(i) : n()) : d();
}
function f() {
o--, u();
}
function l(e) {
o--, (i = i || e), u();
}
function d() {
for (; o < t && s < c; ) o++, e[s++]().then(f, l);
}
d();
});
})(
r.map(function (r) {
return function () {
return (async function (r) {
const o = n[r],
a = en(e._id) + "/" + d(r) + "?rev=" + e._rev,
c = await s(rn(i, a));
let u, f;
if (
((u =
"buffer" in c
? await c.buffer()
: await c.blob()),
t.binary)
) {
const e = Object.getOwnPropertyDescriptor(
u.__proto__,
"type"
);
(e && !e.set) || (u.type = o.content_type),
(f = u);
} else
f = await new Promise(function (e) {
ae(u, e);
});
delete o.stub, delete o.length, (o.data = f);
})(r);
};
}),
5
);
}
(t = f(t)).revs && (r.revs = !0),
t.revs_info && (r.revs_info = !0),
t.latest && (r.latest = !0),
t.open_revs &&
("all" !== t.open_revs &&
(t.open_revs = JSON.stringify(t.open_revs)),
(r.open_revs = t.open_revs)),
t.rev && (r.rev = t.rev),
t.conflicts && (r.conflicts = t.conflicts),
t.update_seq && (r.update_seq = t.update_seq),
(e = en(e));
const a = rn(i, e + sn(r));
try {
const e = await c(a);
t.attachments &&
(await ((u = e.data),
Array.isArray(u)
? Promise.all(
u.map(function (e) {
if (e.ok) return o(e.ok);
})
)
: o(u))),
n(null, e.data);
} catch (t) {
(t.docId = e), n(t);
}
var u;
})),
(r.remove = a("remove", async function (e, t, n, r) {
let o;
"string" == typeof t
? ((o = { _id: e, _rev: t }),
"function" == typeof n && ((r = n), (n = {})))
: ((o = e),
"function" == typeof t
? ((r = t), (n = {}))
: ((r = n), (n = t)));
const s = o._rev || n.rev,
a = rn(i, en(o._id)) + "?rev=" + s;
try {
r(null, (await c(a, { method: "DELETE" })).data);
} catch (e) {
r(e);
}
})),
(r.getAttachment = a(
"getAttachment",
async function (e, t, r, o) {
"function" == typeof r && ((o = r), (r = {}));
const a = r.rev ? "?rev=" + r.rev : "",
c = rn(i, en(e)) + "/" + d(t) + a;
let u;
try {
const e = await s(c, { method: "GET" });
if (!e.ok) throw e;
let t;
if (
((u = e.headers.get("content-type")),
(t =
void 0 === n ||
n.browser ||
"function" != typeof e.buffer
? await e.blob()
: await e.buffer()),
void 0 !== n && !n.browser)
) {
const e = Object.getOwnPropertyDescriptor(
t.__proto__,
"type"
);
(e && !e.set) || (t.type = u);
}
o(null, t);
} catch (e) {
o(e);
}
}
)),
(r.removeAttachment = a(
"removeAttachment",
async function (e, t, n, r) {
const o = rn(i, en(e) + "/" + d(t)) + "?rev=" + n;
try {
r(null, (await c(o, { method: "DELETE" })).data);
} catch (e) {
r(e);
}
}
)),
(r.putAttachment = a(
"putAttachment",
async function (e, t, n, r, o, s) {
"function" == typeof o &&
((s = o), (o = r), (r = n), (n = null));
const a = en(e) + "/" + d(t);
let u = rn(i, a);
if ((n && (u += "?rev=" + n), "string" == typeof r)) {
let e;
try {
e = Z(r);
} catch (e) {
return s(
N($, "Attachment is not a valid base64 string")
);
}
r = e ? re(e, o) : "";
}
try {
s(
null,
(
await c(u, {
headers: new ze({ "Content-Type": o }),
method: "PUT",
body: r,
})
).data
);
} catch (e) {
s(e);
}
}
)),
(r._bulkDocs = async function (e, t, n) {
e.new_edits = t.new_edits;
try {
await l(), await Promise.all(e.docs.map(tn));
n(
null,
(
await c(rn(i, "_bulk_docs"), {
method: "POST",
body: JSON.stringify(e),
})
).data
);
} catch (e) {
n(e);
}
}),
(r._put = async function (e, t, n) {
try {
await l(), await tn(e);
n(
null,
(
await c(rn(i, en(e._id)), {
method: "PUT",
body: JSON.stringify(e),
})
).data
);
} catch (t) {
(t.docId = e && e._id), n(t);
}
}),
(r.allDocs = a("allDocs", async function (e, t) {
"function" == typeof e && ((t = e), (e = {}));
const n = {};
let r,
o = "GET";
(e = f(e)).conflicts && (n.conflicts = !0),
e.update_seq && (n.update_seq = !0),
e.descending && (n.descending = !0),
e.include_docs && (n.include_docs = !0),
e.attachments && (n.attachments = !0),
e.key && (n.key = JSON.stringify(e.key)),
e.start_key && (e.startkey = e.start_key),
e.startkey && (n.startkey = JSON.stringify(e.startkey)),
e.end_key && (e.endkey = e.end_key),
e.endkey && (n.endkey = JSON.stringify(e.endkey)),
void 0 !== e.inclusive_end &&
(n.inclusive_end = !!e.inclusive_end),
void 0 !== e.limit && (n.limit = e.limit),
void 0 !== e.skip && (n.skip = e.skip);
const s = sn(n);
void 0 !== e.keys && ((o = "POST"), (r = { keys: e.keys }));
try {
const n = await c(rn(i, "_all_docs" + s), {
method: o,
body: JSON.stringify(r),
});
e.include_docs &&
e.attachments &&
e.binary &&
n.data.rows.forEach(Zt),
t(null, n.data);
} catch (e) {
t(e);
}
})),
(r._changes = function (e) {
const t = "batch_size" in e ? e.batch_size : 25;
(e = f(e)).continuous &&
!("heartbeat" in e) &&
(e.heartbeat = 1e4);
let n = "timeout" in e ? e.timeout : 3e4;
"timeout" in e &&
e.timeout &&
n - e.timeout < 5e3 &&
(n = e.timeout + 5e3),
"heartbeat" in e &&
e.heartbeat &&
n - e.heartbeat < 5e3 &&
(n = e.heartbeat + 5e3);
const r = {};
"timeout" in e && e.timeout && (r.timeout = e.timeout);
const o = void 0 !== e.limit && e.limit;
let s = o;
if (
(e.style && (r.style = e.style),
(e.include_docs ||
(e.filter && "function" == typeof e.filter)) &&
(r.include_docs = !0),
e.attachments && (r.attachments = !0),
e.continuous && (r.feed = "longpoll"),
e.seq_interval && (r.seq_interval = e.seq_interval),
e.conflicts && (r.conflicts = !0),
e.descending && (r.descending = !0),
e.update_seq && (r.update_seq = !0),
"heartbeat" in e &&
e.heartbeat &&
(r.heartbeat = e.heartbeat),
e.filter &&
"string" == typeof e.filter &&
(r.filter = e.filter),
e.view &&
"string" == typeof e.view &&
((r.filter = "_view"), (r.view = e.view)),
e.query_params && "object" == typeof e.query_params)
)
for (const t in e.query_params)
Object.prototype.hasOwnProperty.call(
e.query_params,
t
) && (r[t] = e.query_params[t]);
let a,
u = "GET";
e.doc_ids
? ((r.filter = "_doc_ids"),
(u = "POST"),
(a = { doc_ids: e.doc_ids }))
: e.selector &&
((r.filter = "_selector"),
(u = "POST"),
(a = { selector: e.selector }));
const d = new AbortController();
let h;
const p = async function (n, f) {
if (e.aborted) return;
(r.since = n),
"object" == typeof r.since &&
(r.since = JSON.stringify(r.since)),
e.descending
? o && (r.limit = s)
: (r.limit = !o || s > t ? t : s);
const p = rn(i, "_changes" + sn(r)),
v = {
signal: d.signal,
method: u,
body: JSON.stringify(a),
};
if (((h = n), !e.aborted))
try {
await l();
f(null, (await c(p, v)).data);
} catch (e) {
f(e);
}
},
v = { results: [] },
_ = function (n, r) {
if (e.aborted) return;
let i = 0;
if (r && r.results) {
(i = r.results.length), (v.last_seq = r.last_seq);
let t = null,
n = null;
"number" == typeof r.pending && (t = r.pending),
("string" != typeof v.last_seq &&
"number" != typeof v.last_seq) ||
(n = v.last_seq);
(({}).query = e.query_params),
(r.results = r.results.filter(function (r) {
s--;
const i = F(e)(r);
return (
i &&
(e.include_docs &&
e.attachments &&
e.binary &&
Zt(r),
e.return_docs && v.results.push(r),
e.onChange(r, t, n)),
i
);
}));
} else if (n)
return (e.aborted = !0), void e.complete(n);
r && r.last_seq && (h = r.last_seq);
const a = (o && s <= 0) || (r && i < t) || e.descending;
(!e.continuous || (o && s <= 0)) && a
? e.complete(null, v)
: b(function () {
p(h, _);
});
};
return (
p(e.since || 0, _),
{
cancel: function () {
(e.aborted = !0), d.abort();
},
}
);
}),
(r.revsDiff = a("revsDiff", async function (e, t, n) {
"function" == typeof t && ((n = t), (t = {}));
try {
n(
null,
(
await c(rn(i, "_revs_diff"), {
method: "POST",
body: JSON.stringify(e),
})
).data
);
} catch (e) {
n(e);
}
})),
(r._close = function (e) {
e();
}),
(r._destroy = async function (e, t) {
try {
t(null, await c(rn(i, ""), { method: "DELETE" }));
} catch (e) {
404 === e.status ? t(null, { ok: !0 }) : t(e);
}
});
}
an.valid = function () {
return !0;
};
class cn extends Error {
constructor(e) {
super(),
(this.status = 400),
(this.name = "query_parse_error"),
(this.message = e),
(this.error = !0);
try {
Error.captureStackTrace(this, cn);
} catch (e) {}
}
}
class un extends Error {
constructor(e) {
super(),
(this.status = 404),
(this.name = "not_found"),
(this.message = e),
(this.error = !0);
try {
Error.captureStackTrace(this, un);
} catch (e) {}
}
}
class fn extends Error {
constructor(e) {
super(),
(this.status = 500),
(this.name = "invalid_value"),
(this.message = e),
(this.error = !0);
try {
Error.captureStackTrace(this, fn);
} catch (e) {}
}
}
function ln(e, t) {
return (
t &&
e.then(
function (e) {
b(function () {
t(null, e);
});
},
function (e) {
b(function () {
t(e);
});
}
),
e
);
}
function dn(e, t) {
return function () {
var n = arguments,
r = this;
return e.add(function () {
return t.apply(r, n);
});
};
}
function hn(e) {
var t = new Set(e),
n = new Array(t.size),
r = -1;
return (
t.forEach(function (e) {
n[++r] = e;
}),
n
);
}
function pn(e) {
var t = new Array(e.size),
n = -1;
return (
e.forEach(function (e, r) {
t[++n] = r;
}),
t
);
}
function vn(e) {
return new fn(
"builtin " +
e +
" function requires map values to be numbers or number arrays"
);
}
function _n(e) {
for (var t = 0, n = 0, r = e.length; n < r; n++) {
var i = e[n];
if ("number" != typeof i) {
if (!Array.isArray(i)) throw vn("_sum");
t = "number" == typeof t ? [t] : t;
for (var o = 0, s = i.length; o < s; o++) {
var a = i[o];
if ("number" != typeof a) throw vn("_sum");
void 0 === t[o] ? t.push(a) : (t[o] += a);
}
} else "number" == typeof t ? (t += i) : (t[0] += i);
}
return t;
}
var yn = w.bind(null, "log"),
gn = Array.isArray,
mn = JSON.parse;
function bn(e, t) {
return H("return (" + e.replace(/;\s*$/, "") + ");", {
emit: t,
sum: _n,
log: yn,
isArray: gn,
toJSON: mn,
});
}
class wn {
constructor() {
this.promise = Promise.resolve();
}
add(e) {
return (
(this.promise = this.promise
.catch(() => {})
.then(() => e())),
this.promise
);
}
finish() {
return this.promise;
}
}
function kn(e) {
if (!e) return "undefined";
switch (typeof e) {
case "function":
case "string":
return e.toString();
default:
return JSON.stringify(e);
}
}
async function jn(e, t, n, r, i, o) {
const s = (function (e, t) {
return kn(e) + kn(t) + "undefined";
})(n, r);
let a;
if (!i && ((a = e._cachedViews = e._cachedViews || {}), a[s]))
return a[s];
const c = e.info().then(async function (c) {
const u = c.db_name + "-mrview-" + (i ? "temp" : de(s));
await X(e, "_local/" + o, function (e) {
e.views = e.views || {};
let n = t;
-1 === n.indexOf("/") && (n = t + "/" + t);
const r = (e.views[n] = e.views[n] || {});
if (!r[u]) return (r[u] = !0), e;
});
const f = (await e.registerDependentDatabase(u)).db;
f.auto_compaction = !0;
const l = {
name: u,
db: f,
sourceDB: e,
adapter: e.adapter,
mapFun: n,
reduceFun: r,
};
let d;
try {
d = await l.db.get("_local/lastSeq");
} catch (e) {
if (404 !== e.status) throw e;
}
return (
(l.seq = d ? d.seq : 0),
a &&
l.db.once("destroyed", function () {
delete a[s];
}),
l
);
});
return a && (a[s] = c), c;
}
const qn = {},
On = new wn();
function An(e) {
return -1 === e.indexOf("/") ? [e, e] : e.split("/");
}
function Sn(e, t, n) {
try {
e.emit("error", t);
} catch (e) {
w(
"error",
"The user's map/reduce function threw an uncaught error.\nYou can debug this error by doing:\nmyDatabase.on('error', function (err) { debugger; });\nPlease double-check your map/reduce function."
),
w("error", t, n);
}
}
var xn = function (e, t) {
return _n(t);
},
Pn = function (e, t) {
return t.length;
},
Cn = function (e, t) {
return {
sum: _n(t),
min: Math.min.apply(null, t),
max: Math.max.apply(null, t),
count: t.length,
sumsqr: (function (e) {
for (var t = 0, n = 0, r = e.length; n < r; n++) {
var i = e[n];
t += i * i;
}
return t;
})(t),
};
};
var En = (function (e, t, n, r) {
function i(e, t, n) {
try {
t(n);
} catch (r) {
Sn(e, r, { fun: t, doc: n });
}
}
function o(e, t, n, r, i) {
try {
return { output: t(n, r, i) };
} catch (o) {
return (
Sn(e, o, { fun: t, keys: n, values: r, rereduce: i }),
{ error: o }
);
}
}
function s(e, t) {
const n = et(e.key, t.key);
return 0 !== n ? n : et(e.value, t.value);
}
function a(e, t, n) {
return (
(n = n || 0),
"number" == typeof t
? e.slice(n, t + n)
: n > 0
? e.slice(n)
: e
);
}
function c(e) {
const t = e.value;
return (t && "object" == typeof t && t._id) || e.id;
}
function u(e) {
return function (t) {
return (
e.include_docs &&
e.attachments &&
e.binary &&
(function (e) {
for (const t of e.rows) {
const e = t.doc && t.doc._attachments;
if (e)
for (const t of Object.keys(e)) {
const n = e[t];
e[t].data = ie(n.data, n.content_type);
}
}
})(t),
t
);
};
}
function f(e, t, n, r) {
let i = t[e];
void 0 !== i &&
(r && (i = encodeURIComponent(JSON.stringify(i))),
n.push(e + "=" + i));
}
function l(e) {
if (void 0 !== e) {
const t = Number(e);
return isNaN(t) || t !== parseInt(e, 10) ? e : t;
}
}
function d(e) {
if (e) {
if ("number" != typeof e)
return new cn(`Invalid value for integer: "${e}"`);
if (e < 0)
return new cn(
`Invalid value for positive integer: "${e}"`
);
}
}
function h(e, t) {
const n = e.descending ? "endkey" : "startkey",
r = e.descending ? "startkey" : "endkey";
if (void 0 !== e[n] && void 0 !== e[r] && et(e[n], e[r]) > 0)
throw new cn(
"No rows can match your key range, reverse your start_key and end_key or set {descending : true}"
);
if (t.reduce && !1 !== e.reduce) {
if (e.include_docs)
throw new cn("{include_docs:true} is invalid for reduce");
if (
e.keys &&
e.keys.length > 1 &&
!e.group &&
!e.group_level
)
throw new cn(
"Multi-key fetches for reduce views must use {group: true}"
);
}
for (const t of ["group_level", "limit", "skip"]) {
const n = d(e[t]);
if (n) throw n;
}
}
function p(e) {
return function (t) {
if (404 === t.status) return e;
throw t;
};
}
function v(e, t, n) {
return e.db
.get("_local/lastSeq")
.catch(p({ _id: "_local/lastSeq", seq: 0 }))
.then(function (r) {
var i = pn(t);
return Promise.all(
i.map(function (n) {
return (async function (e, t, n) {
const r = "_local/doc_" + e,
i = { _id: r, keys: [] },
o = n.get(e),
s = o[0],
a = o[1],
c = await ((function (e) {
return 1 === e.length && /^1-/.test(e[0].rev);
})(a)
? Promise.resolve(i)
: t.db.get(r).catch(p(i)));
return (function (e, t) {
const n = [],
r = new Set();
for (const e of t.rows) {
const t = e.doc;
if (
t &&
(n.push(t),
r.add(t._id),
(t._deleted = !s.has(t._id)),
!t._deleted)
) {
const e = s.get(t._id);
"value" in e && (t.value = e.value);
}
}
const i = pn(s);
for (const e of i)
if (!r.has(e)) {
const t = { _id: e },
r = s.get(e);
"value" in r && (t.value = r.value),
n.push(t);
}
return (
(e.keys = hn(i.concat(e.keys))), n.push(e), n
);
})(
c,
await (function (e) {
return e.keys.length
? t.db.allDocs({
keys: e.keys,
include_docs: !0,
})
: Promise.resolve({ rows: [] });
})(c)
);
})(n, e, t);
})
)
.then(function (t) {
var i = t.flat();
return (
(r.seq = n), i.push(r), e.db.bulkDocs({ docs: i })
);
})
.then(() =>
(function (e) {
return e.sourceDB
.get("_local/purges")
.then(function (t) {
const n = t.purgeSeq;
return e.db
.get("_local/purgeSeq")
.then(function (e) {
return e._rev;
})
.catch(p(void 0))
.then(function (t) {
return e.db.put({
_id: "_local/purgeSeq",
_rev: t,
purgeSeq: n,
});
});
})
.catch(function (e) {
if (404 !== e.status) throw e;
});
})(e)
);
});
}
function _(e) {
const t = "string" == typeof e ? e : e.name;
let n = qn[t];
return n || (n = qn[t] = new wn()), n;
}
async function y(e, n) {
return dn(_(e), function () {
return (async function (e, n) {
let r, o, a;
const c = t(e.mapFun, function (e, t) {
const n = { id: o._id, key: tt(e) };
null != t && (n.value = tt(t)), r.push(n);
});
let u = e.seq || 0;
let f = 0;
const l = { view: e.name, indexed_docs: f };
e.sourceDB.emit("indexing", l);
const d = new wn();
async function h() {
return (function (t, l) {
const p = t.results;
if (!p.length && !l.length) return;
for (const e of l) {
if (
p.findIndex(function (t) {
return t.id === e.docId;
}) < 0
) {
const t = {
_id: e.docId,
doc: { _id: e.docId, _deleted: 1 },
changes: [],
};
e.doc &&
((t.doc = e.doc),
t.changes.push({ rev: e.doc._rev })),
p.push(t);
}
}
const y = (function (t) {
const n = new Map();
for (const a of t) {
if ("_" !== a.doc._id[0]) {
(r = []),
(o = a.doc),
o._deleted || i(e.sourceDB, c, o),
r.sort(s);
const t = _(r);
n.set(a.doc._id, [t, a.changes]);
}
u = a.seq;
}
return n;
})(p);
d.add(
(function (t, n) {
return function () {
return v(e, t, n);
};
})(y, u)
),
(f += p.length);
const g = {
view: e.name,
last_seq: t.last_seq,
results_count: p.length,
indexed_docs: f,
};
if (
(e.sourceDB.emit("indexing", g),
e.sourceDB.activeTasks.update(a, {
completed_items: f,
}),
p.length < n.changes_batch_size)
)
return;
return h();
})(
await e.sourceDB.changes({
return_docs: !0,
conflicts: !0,
include_docs: !0,
style: "all_docs",
since: u,
limit: n.changes_batch_size,
}),
await e.db
.get("_local/purgeSeq")
.then(function (e) {
return e.purgeSeq;
})
.catch(p(-1))
.then(function (t) {
return e.sourceDB
.get("_local/purges")
.then(function (n) {
const r = n.purges
.filter(function (e, n) {
return n > t;
})
.map((e) => e.docId),
i = r.filter(function (e, t) {
return r.indexOf(e) === t;
});
return Promise.all(
i.map(function (t) {
return e.sourceDB
.get(t)
.then(function (e) {
return { docId: t, doc: e };
})
.catch(p({ docId: t }));
})
);
})
.catch(p([]));
})
);
}
function _(e) {
const t = new Map();
let n;
for (let r = 0, i = e.length; r < i; r++) {
const i = e[r],
o = [i.key, i.id];
r > 0 && 0 === et(i.key, n) && o.push(r),
t.set(rt(o), i),
(n = i.key);
}
return t;
}
try {
await e.sourceDB.info().then(function (t) {
a = e.sourceDB.activeTasks.add({
name: "view_indexing",
total_items: t.update_seq - u,
});
}),
await h(),
await d.finish(),
(e.seq = u),
e.sourceDB.activeTasks.remove(a);
} catch (t) {
e.sourceDB.activeTasks.remove(a, t);
}
})(e, n);
})();
}
function g(e, t) {
return dn(_(e), function () {
return (async function (e, t) {
let r;
const i = e.reduceFun && !1 !== t.reduce,
s = t.skip || 0;
void 0 === t.keys ||
t.keys.length ||
((t.limit = 0), delete t.keys);
async function u(t) {
t.include_docs = !0;
const n = await e.db.allDocs(t);
return (
(r = n.total_rows),
n.rows.map(function (e) {
if (
"value" in e.doc &&
"object" == typeof e.doc.value &&
null !== e.doc.value
) {
const t = Object.keys(e.doc.value).sort(),
n = ["id", "key", "value"];
if (!(t < n || t > n)) return e.doc.value;
}
const t = (function (e) {
for (var t = [], n = [], r = 0; ; ) {
var i = e[r++];
if ("\0" !== i)
switch (i) {
case "1":
t.push(null);
break;
case "2":
t.push("1" === e[r]), r++;
break;
case "3":
var o = it(e, r);
t.push(o.num), (r += o.length);
break;
case "4":
for (var s = ""; ; ) {
var a = e[r];
if ("\0" === a) break;
(s += a), r++;
}
(s = s
.replace(/\u0001\u0001/g, "\0")
.replace(/\u0001\u0002/g, "\x01")
.replace(/\u0002\u0002/g, "\x02")),
t.push(s);
break;
case "5":
var c = { element: [], index: t.length };
t.push(c.element), n.push(c);
break;
case "6":
var u = { element: {}, index: t.length };
t.push(u.element), n.push(u);
break;
default:
throw new Error(
"bad collationIndex or unexpectedly reached end of input: " +
i
);
}
else {
if (1 === t.length) return t.pop();
ot(t, n);
}
}
})(e.doc._id);
return {
key: t[0],
id: t[1],
value: "value" in e.doc ? e.doc.value : null,
};
})
);
}
async function f(u) {
let f;
if (
((f = i
? (function (e, t, r) {
0 === r.group_level && delete r.group_level;
const i = r.group || r.group_level,
s = n(e.reduceFun),
c = [],
u = isNaN(r.group_level)
? Number.POSITIVE_INFINITY
: r.group_level;
for (const e of t) {
const t = c[c.length - 1];
let n = i ? e.key : null;
i && Array.isArray(n) && (n = n.slice(0, u)),
t && 0 === et(t.groupKey, n)
? (t.keys.push([e.key, e.id]),
t.values.push(e.value))
: c.push({
keys: [[e.key, e.id]],
values: [e.value],
groupKey: n,
});
}
t = [];
for (const n of c) {
const r = o(
e.sourceDB,
s,
n.keys,
n.values,
!1
);
if (r.error && r.error instanceof fn)
throw r.error;
t.push({
value: r.error ? null : r.output,
key: n.groupKey,
});
}
return { rows: a(t, r.limit, r.skip) };
})(e, u, t)
: void 0 === t.keys
? { total_rows: r, offset: s, rows: u }
: {
total_rows: r,
offset: s,
rows: a(u, t.limit, t.skip),
}),
t.update_seq && (f.update_seq = e.seq),
t.include_docs)
) {
const n = hn(u.map(c)),
r = await e.sourceDB.allDocs({
keys: n,
include_docs: !0,
conflicts: t.conflicts,
attachments: t.attachments,
binary: t.binary,
}),
i = new Map();
for (const e of r.rows) i.set(e.id, e.doc);
for (const e of u) {
const t = c(e),
n = i.get(t);
n && (e.doc = n);
}
}
return f;
}
if (void 0 !== t.keys) {
const e = t.keys.map(function (e) {
const n = {
startkey: rt([e]),
endkey: rt([e, {}]),
};
return t.update_seq && (n.update_seq = !0), u(n);
}),
n = await Promise.all(e);
return f(n.flat());
}
{
const e = { descending: t.descending };
let n, r;
if (
(t.update_seq && (e.update_seq = !0),
"start_key" in t && (n = t.start_key),
"startkey" in t && (n = t.startkey),
"end_key" in t && (r = t.end_key),
"endkey" in t && (r = t.endkey),
void 0 !== n &&
(e.startkey = t.descending ? rt([n, {}]) : rt([n])),
void 0 !== r)
) {
let n = !1 !== t.inclusive_end;
t.descending && (n = !n),
(e.endkey = rt(n ? [r, {}] : [r]));
}
if (void 0 !== t.key) {
const n = rt([t.key]),
r = rt([t.key, {}]);
e.descending
? ((e.endkey = n), (e.startkey = r))
: ((e.startkey = n), (e.endkey = r));
}
i ||
("number" == typeof t.limit && (e.limit = t.limit),
(e.skip = s));
return f(await u(e));
}
})(e, t);
})();
}
async function m(t, n, i) {
if ("function" == typeof t._query)
return (function (e, t, n) {
return new Promise(function (r, i) {
e._query(t, n, function (e, t) {
if (e) return i(e);
r(t);
});
});
})(t, n, i);
if (J(t))
return (async function (e, t, n) {
let r,
i,
o = [],
s = "GET";
if (
(f("reduce", n, o),
f("include_docs", n, o),
f("attachments", n, o),
f("limit", n, o),
f("descending", n, o),
f("group", n, o),
f("group_level", n, o),
f("skip", n, o),
f("stale", n, o),
f("conflicts", n, o),
f("startkey", n, o, !0),
f("start_key", n, o, !0),
f("endkey", n, o, !0),
f("end_key", n, o, !0),
f("inclusive_end", n, o),
f("key", n, o, !0),
f("update_seq", n, o),
(o = o.join("&")),
(o = "" === o ? "" : "?" + o),
void 0 !== n.keys)
) {
const e = 2e3,
i =
"keys=" +
encodeURIComponent(JSON.stringify(n.keys));
i.length + o.length + 1 <= e
? (o += ("?" === o[0] ? "&" : "?") + i)
: ((s = "POST"),
"string" == typeof t
? (r = { keys: n.keys })
: (t.keys = n.keys));
}
if ("string" == typeof t) {
const a = An(t),
c = await e.fetch(
"_design/" + a[0] + "/_view/" + a[1] + o,
{
headers: new ze({
"Content-Type": "application/json",
}),
method: s,
body: JSON.stringify(r),
}
);
i = c.ok;
const f = await c.json();
if (!i) throw ((f.status = c.status), U(f));
for (const e of f.rows)
if (
e.value &&
e.value.error &&
"builtin_reduce_error" === e.value.error
)
throw new Error(e.reason);
return new Promise(function (e) {
e(f);
}).then(u(n));
}
r = r || {};
for (const e of Object.keys(t))
Array.isArray(t[e])
? (r[e] = t[e])
: (r[e] = t[e].toString());
const a = await e.fetch("_temp_view" + o, {
headers: new ze({ "Content-Type": "application/json" }),
method: "POST",
body: JSON.stringify(r),
});
i = a.ok;
const c = await a.json();
if (!i) throw ((c.status = a.status), U(c));
return new Promise(function (e) {
e(c);
}).then(u(n));
})(t, n, i);
const o = {
changes_batch_size:
t.__opts.view_update_changes_batch_size || 50,
};
if ("string" != typeof n)
return (
h(i, n),
On.add(async function () {
const r = await jn(
t,
"temp_view/temp_view",
n.map,
n.reduce,
!0,
e
);
return (
(s = y(r, o).then(function () {
return g(r, i);
})),
(a = function () {
return r.db.destroy();
}),
s.then(
function (e) {
return a().then(function () {
return e;
});
},
function (e) {
return a().then(function () {
throw e;
});
}
)
);
var s, a;
}),
On.finish()
);
{
const s = n,
a = An(s),
c = a[0],
u = a[1],
f = await t.get("_design/" + c);
if (!(n = f.views && f.views[u]))
throw new un(`ddoc ${f._id} has no view named ${u}`);
r(f, u), h(i, n);
const l = await jn(t, s, n.map, n.reduce, !1, e);
return "ok" === i.stale || "update_after" === i.stale
? ("update_after" === i.stale &&
b(function () {
y(l, o);
}),
g(l, i))
: (await y(l, o), g(l, i));
}
}
var w;
return {
query: function (e, t, n) {
const r = this;
"function" == typeof t && ((n = t), (t = {})),
(t = t
? (function (e) {
return (
(e.group_level = l(e.group_level)),
(e.limit = l(e.limit)),
(e.skip = l(e.skip)),
e
);
})(t)
: {}),
"function" == typeof e && (e = { map: e });
const i = Promise.resolve().then(function () {
return m(r, e, t);
});
return ln(i, n), i;
},
viewCleanup:
((w = function () {
const t = this;
return "function" == typeof t._viewCleanup
? (function (e) {
return new Promise(function (t, n) {
e._viewCleanup(function (e, r) {
if (e) return n(e);
t(r);
});
});
})(t)
: J(t)
? (async function (e) {
return (
await e.fetch("_view_cleanup", {
headers: new ze({
"Content-Type": "application/json",
}),
method: "POST",
})
).json();
})(t)
: (async function (t) {
try {
const n = await t.get("_local/" + e),
r = new Map();
for (const e of Object.keys(n.views)) {
const t = An(e),
n = "_design/" + t[0],
i = t[1];
let o = r.get(n);
o || ((o = new Set()), r.set(n, o)), o.add(i);
}
const i = { keys: pn(r), include_docs: !0 },
o = await t.allDocs(i),
s = {};
for (const e of o.rows) {
const t = e.key.substring(8);
for (const i of r.get(e.key)) {
let r = t + "/" + i;
n.views[r] || (r = i);
const o = Object.keys(n.views[r]),
a = e.doc && e.doc.views && e.doc.views[i];
for (const e of o) s[e] = s[e] || a;
}
}
const a = Object.keys(s)
.filter(function (e) {
return !s[e];
})
.map(function (e) {
return dn(_(e), function () {
return new t.constructor(
e,
t.__opts
).destroy();
})();
});
return Promise.all(a).then(function () {
return { ok: !0 };
});
} catch (e) {
if (404 === e.status) return { ok: !0 };
throw e;
}
})(t);
}),
function (...e) {
var t = e.pop(),
n = w.apply(this, e);
return "function" == typeof t && ln(n, t), n;
}),
};
})(
"mrviews",
function (e, t) {
if ("function" == typeof e && 2 === e.length) {
var n = e;
return function (e) {
return n(e, t);
};
}
return bn(e.toString(), t);
},
function (e) {
var t = e.toString(),
n = (function (e) {
if (/^_sum/.test(e)) return xn;
if (/^_count/.test(e)) return Pn;
if (/^_stats/.test(e)) return Cn;
if (/^_/.test(e))
throw new Error(
e + " is not a supported reduce function."
);
})(t);
return n || bn(t);
},
function (e, t) {
var n = e.views && e.views[t];
if ("string" != typeof n.map)
throw new un(
"ddoc " +
e._id +
" has no string view named " +
t +
", instead found object of type: " +
typeof n.map
);
}
);
var $n = {
query: function (e, t, n) {
return En.query.call(this, e, t, n);
},
viewCleanup: function (e) {
return En.viewCleanup.call(this, e);
},
};
function In(e, t) {
var n = Object.keys(t._attachments);
return Promise.all(
n.map(function (n) {
return e.getAttachment(t._id, n, { rev: t._rev });
})
);
}
function Ln(e, t, n, r) {
n = f(n);
var i = [],
o = !0;
return Promise.resolve()
.then(function () {
var s = (function (e) {
var t = [];
return (
Object.keys(e).forEach(function (n) {
e[n].missing.forEach(function (e) {
t.push({ id: n, rev: e });
});
}),
{ docs: t, revs: !0, latest: !0 }
);
})(n);
if (s.docs.length)
return e.bulkGet(s).then(function (n) {
if (r.cancelled) throw new Error("cancelled");
return Promise.all(
n.results.map(function (n) {
return Promise.all(
n.docs.map(function (n) {
var r = n.ok;
return (
n.error && (o = !1),
r && r._attachments
? (function (e, t, n) {
var r = J(t) && !J(e),
i = Object.keys(n._attachments);
return r
? e
.get(n._id)
.then(function (r) {
return Promise.all(
i.map(function (i) {
return (function (e, t, n) {
return (
!e._attachments ||
!e._attachments[n] ||
e._attachments[n]
.digest !==
t._attachments[n]
.digest
);
})(r, n, i)
? t.getAttachment(
n._id,
i
)
: e.getAttachment(
r._id,
i
);
})
);
})
.catch(function (e) {
if (404 !== e.status) throw e;
return In(t, n);
})
: In(t, n);
})(t, e, r).then((e) => {
var t = Object.keys(r._attachments);
return (
e.forEach(function (e, n) {
var i = r._attachments[t[n]];
delete i.stub,
delete i.length,
(i.data = e);
}),
r
);
})
: r
);
})
);
})
).then(function (e) {
i = i.concat(e.flat().filter(Boolean));
});
});
})
.then(function () {
return { ok: o, docs: i };
});
}
function Dn(e, t, n, r, i) {
return e
.get(t)
.catch(function (n) {
if (404 === n.status)
return (
("http" !== e.adapter && "https" !== e.adapter) ||
j(
404,
"PouchDB is just checking if a remote checkpoint exists."
),
{
session_id: r,
_id: t,
history: [],
replicator: "pouchdb",
version: 1,
}
);
throw n;
})
.then(function (o) {
if (!i.cancelled && o.last_seq !== n)
return (
(o.history = (o.history || []).filter(function (e) {
return e.session_id !== r;
})),
o.history.unshift({ last_seq: n, session_id: r }),
(o.history = o.history.slice(0, 5)),
(o.version = 1),
(o.replicator = "pouchdb"),
(o.session_id = r),
(o.last_seq = n),
e.put(o).catch(function (o) {
if (409 === o.status) return Dn(e, t, n, r, i);
throw o;
})
);
});
}
class Tn {
constructor(
e,
t,
n,
r,
i = { writeSourceCheckpoint: !0, writeTargetCheckpoint: !0 }
) {
(this.src = e),
(this.target = t),
(this.id = n),
(this.returnValue = r),
(this.opts = i),
void 0 === i.writeSourceCheckpoint &&
(i.writeSourceCheckpoint = !0),
void 0 === i.writeTargetCheckpoint &&
(i.writeTargetCheckpoint = !0);
}
writeCheckpoint(e, t) {
var n = this;
return this.updateTarget(e, t).then(function () {
return n.updateSource(e, t);
});
}
updateTarget(e, t) {
return this.opts.writeTargetCheckpoint
? Dn(this.target, this.id, e, t, this.returnValue)
: Promise.resolve(!0);
}
updateSource(e, t) {
if (this.opts.writeSourceCheckpoint) {
var n = this;
return Dn(this.src, this.id, e, t, this.returnValue).catch(
function (e) {
if (Rn(e))
return (n.opts.writeSourceCheckpoint = !1), !0;
throw e;
}
);
}
return Promise.resolve(!0);
}
getCheckpoint() {
var e = this;
return e.opts.writeSourceCheckpoint ||
e.opts.writeTargetCheckpoint
? e.opts &&
e.opts.writeSourceCheckpoint &&
!e.opts.writeTargetCheckpoint
? e.src
.get(e.id)
.then(function (e) {
return e.last_seq || 0;
})
.catch(function (e) {
if (404 !== e.status) throw e;
return 0;
})
: e.target
.get(e.id)
.then(function (t) {
return e.opts &&
e.opts.writeTargetCheckpoint &&
!e.opts.writeSourceCheckpoint
? t.last_seq || 0
: e.src.get(e.id).then(
function (e) {
return t.version !== e.version
? 0
: (n = t.version
? t.version.toString()
: "undefined") in Bn
? Bn[n](t, e)
: 0;
var n;
},
function (n) {
if (404 === n.status && t.last_seq)
return e.src
.put({ _id: e.id, last_seq: 0 })
.then(
function () {
return 0;
},
function (n) {
return Rn(n)
? ((e.opts.writeSourceCheckpoint =
!1),
t.last_seq)
: 0;
}
);
throw n;
}
);
})
.catch(function (e) {
if (404 !== e.status) throw e;
return 0;
})
: Promise.resolve(0);
}
}
var Bn = {
undefined: function (e, t) {
return 0 === et(e.last_seq, t.last_seq) ? t.last_seq : 0;
},
1: function (e, t) {
return (function (e, t) {
if (e.session_id === t.session_id)
return { last_seq: e.last_seq, history: e.history };
return (function e(t, n) {
var r = t[0],
i = t.slice(1),
o = n[0],
s = n.slice(1);
if (!r || 0 === n.length)
return { last_seq: 0, history: [] };
if (Mn(r.session_id, n))
return { last_seq: r.last_seq, history: t };
if (Mn(o.session_id, i))
return { last_seq: o.last_seq, history: s };
return e(i, s);
})(e.history, t.history);
})(t, e).last_seq;
},
};
function Mn(e, t) {
var n = t[0],
r = t.slice(1);
return (
!(!e || 0 === t.length) && (e === n.session_id || Mn(e, r))
);
}
function Rn(e) {
return (
"number" == typeof e.status &&
4 === Math.floor(e.status / 100)
);
}
function Nn(e, t, n, r, i) {
return this instanceof Tn ? Nn : new Tn(e, t, n, r, i);
}
function Un(e, t, n) {
var r = n.doc_ids ? n.doc_ids.sort(et) : "",
i = n.filter ? n.filter.toString() : "",
o = "",
s = "",
a = "";
return (
n.selector && (a = JSON.stringify(n.selector)),
n.filter &&
n.query_params &&
(o = JSON.stringify(
(function (e) {
return Object.keys(e)
.sort(et)
.reduce(function (t, n) {
return (t[n] = e[n]), t;
}, {});
})(n.query_params)
)),
n.filter && "_view" === n.filter && (s = n.view.toString()),
Promise.all([e.id(), t.id()])
.then(function (e) {
var t = e[0] + e[1] + i + s + o + r + a;
return new Promise(function (e) {
le(t, e);
});
})
.then(function (e) {
return (
"_local/" +
(e = e.replace(/\//g, ".").replace(/\+/g, "_"))
);
})
);
}
function Fn(e, t, n, r, i) {
var o,
s,
a,
c,
u = [],
l = { seq: 0, changes: [], docs: [] },
d = !1,
h = !1,
p = !1,
v = 0,
_ = 0,
y = n.continuous || n.live || !1,
g = n.batch_size || 100,
m = n.batches_limit || 10,
w = n.style || "all_docs",
j = !1,
q = n.doc_ids,
O = n.selector,
A = [],
S = pe();
i = i || {
ok: !0,
start_time: new Date().toISOString(),
docs_read: 0,
docs_written: 0,
doc_write_failures: 0,
errors: [],
};
var x = {};
function P() {
return a
? Promise.resolve()
: Un(e, t, n).then(function (i) {
s = i;
var o = {};
(o =
!1 === n.checkpoint
? {
writeSourceCheckpoint: !1,
writeTargetCheckpoint: !1,
}
: "source" === n.checkpoint
? {
writeSourceCheckpoint: !0,
writeTargetCheckpoint: !1,
}
: "target" === n.checkpoint
? {
writeSourceCheckpoint: !1,
writeTargetCheckpoint: !0,
}
: {
writeSourceCheckpoint: !0,
writeTargetCheckpoint: !0,
}),
(a = new Nn(e, t, s, r, o));
});
}
function C() {
if (((A = []), 0 !== o.docs.length)) {
var e = o.docs,
s = { timeout: n.timeout };
return t.bulkDocs({ docs: e, new_edits: !1 }, s).then(
function (t) {
if (r.cancelled) throw (T(), new Error("cancelled"));
var n = Object.create(null);
t.forEach(function (e) {
e.error && (n[e.id] = e);
});
var o = Object.keys(n).length;
(i.doc_write_failures += o),
(i.docs_written += e.length - o),
e.forEach(function (e) {
var t = n[e._id];
if (t) {
i.errors.push(t);
var o = (t.name || "").toLowerCase();
if ("unauthorized" !== o && "forbidden" !== o)
throw t;
r.emit("denied", f(t));
} else A.push(e);
});
},
function (t) {
throw ((i.doc_write_failures += e.length), t);
}
);
}
}
function E() {
if (o.error)
throw new Error("There was a problem getting docs.");
i.last_seq = _ = o.seq;
var t = f(i);
return (
A.length &&
((t.docs = A),
"number" == typeof o.pending &&
((t.pending = o.pending), delete o.pending),
r.emit("change", t)),
(d = !0),
e.info().then(function (t) {
var n = e.activeTasks.get(c);
if (o && n) {
var r = n.completed_items || 0,
i = parseInt(t.update_seq, 10) - parseInt(v, 10);
e.activeTasks.update(c, {
completed_items: r + o.changes.length,
total_items: i,
});
}
}),
a
.writeCheckpoint(o.seq, S)
.then(function () {
if (
(r.emit("checkpoint", { checkpoint: o.seq }),
(d = !1),
r.cancelled)
)
throw (T(), new Error("cancelled"));
(o = void 0), U();
})
.catch(function (e) {
throw (z(e), e);
})
);
}
function $() {
return Ln(e, t, o.diffs, r).then(function (e) {
(o.error = !e.ok),
e.docs.forEach(function (e) {
delete o.diffs[e._id], i.docs_read++, o.docs.push(e);
});
});
}
function I() {
var e;
r.cancelled ||
o ||
(0 !== u.length
? ((o = u.shift()),
r.emit("checkpoint", { start_next_batch: o.seq }),
((e = {}),
o.changes.forEach(function (t) {
r.emit("checkpoint", { revs_diff: t }),
"_user/" !== t.id &&
(e[t.id] = t.changes.map(function (e) {
return e.rev;
}));
}),
t.revsDiff(e).then(function (e) {
if (r.cancelled) throw (T(), new Error("cancelled"));
o.diffs = e;
}))
.then($)
.then(C)
.then(E)
.then(I)
.catch(function (e) {
D("batch processing terminated with error", e);
}))
: L(!0));
}
function L(e) {
0 !== l.changes.length
? (e || h || l.changes.length >= g) &&
(u.push(l),
(l = { seq: 0, changes: [], docs: [] }),
("pending" !== r.state && "stopped" !== r.state) ||
((r.state = "active"), r.emit("active")),
I())
: 0 !== u.length ||
o ||
(((y && x.live) || h) &&
((r.state = "pending"), r.emit("paused")),
h && T());
}
function D(e, t) {
p ||
(t.message || (t.message = e),
(i.ok = !1),
(i.status = "aborting"),
(u = []),
(l = { seq: 0, changes: [], docs: [] }),
T(t));
}
function T(o) {
if (!(p || (r.cancelled && ((i.status = "cancelled"), d))))
if (
((i.status = i.status || "complete"),
(i.end_time = new Date().toISOString()),
(i.last_seq = _),
(p = !0),
e.activeTasks.remove(c, o),
o)
) {
(o = N(o)).result = i;
var s = (o.name || "").toLowerCase();
"unauthorized" === s || "forbidden" === s
? (r.emit("error", o), r.removeAllListeners())
: (function (e, t, n, r) {
if (!1 === e.retry)
return (
t.emit("error", n), void t.removeAllListeners()
);
if (
("function" != typeof e.back_off_function &&
(e.back_off_function = k),
t.emit("requestError", n),
"active" === t.state || "pending" === t.state)
) {
t.emit("paused", n), (t.state = "stopped");
var i = function () {
e.current_back_off = 0;
};
t.once("paused", function () {
t.removeListener("active", i);
}),
t.once("active", i);
}
(e.current_back_off = e.current_back_off || 0),
(e.current_back_off = e.back_off_function(
e.current_back_off
)),
setTimeout(r, e.current_back_off);
})(n, r, o, function () {
Fn(e, t, n, r);
});
} else r.emit("complete", i), r.removeAllListeners();
}
function B(t, i, o) {
if (r.cancelled) return T();
if (("number" == typeof i && (l.pending = i), F(n)(t)))
(l.seq = t.seq || o),
l.changes.push(t),
r.emit("checkpoint", { pending_batch: l.seq }),
b(function () {
L(0 === u.length && x.live);
});
else {
var s = e.activeTasks.get(c);
if (s) {
var a = s.completed_items || 0;
e.activeTasks.update(c, { completed_items: ++a });
}
}
}
function M(e) {
if (((j = !1), r.cancelled)) return T();
if (e.results.length > 0)
(x.since = e.results[e.results.length - 1].seq), U(), L(!0);
else {
var t = function () {
y ? ((x.live = !0), U()) : (h = !0), L(!0);
};
o || 0 !== e.results.length
? t()
: ((d = !0),
a
.writeCheckpoint(e.last_seq, S)
.then(function () {
if (
((d = !1),
(i.last_seq = _ = e.last_seq),
r.cancelled)
)
throw (T(), new Error("cancelled"));
t();
})
.catch(z));
}
}
function R(e) {
if (((j = !1), r.cancelled)) return T();
D("changes rejected", e);
}
function U() {
if (!j && !h && u.length < m) {
(j = !0),
r._changes &&
(r.removeListener("cancel", r._abortChanges),
r._changes.cancel()),
r.once("cancel", i);
var t = e.changes(x).on("change", B);
t.then(o, o),
t.then(M).catch(R),
n.retry && ((r._changes = t), (r._abortChanges = i));
}
function i() {
t.cancel();
}
function o() {
r.removeListener("cancel", i);
}
}
function K(t) {
return e.info().then(function (r) {
var i =
void 0 === n.since
? parseInt(r.update_seq, 10) - parseInt(t, 10)
: parseInt(r.update_seq, 10);
return (
(c = e.activeTasks.add({
name: `${y ? "continuous " : ""}replication from ${
r.db_name
}`,
total_items: i,
})),
t
);
});
}
function J() {
P()
.then(function () {
if (!r.cancelled)
return a
.getCheckpoint()
.then(K)
.then(function (e) {
(v = e),
(x = {
since: (_ = e),
limit: g,
batch_size: g,
style: w,
doc_ids: q,
selector: O,
return_docs: !0,
}),
n.filter &&
("string" != typeof n.filter
? (x.include_docs = !0)
: (x.filter = n.filter)),
"heartbeat" in n && (x.heartbeat = n.heartbeat),
"timeout" in n && (x.timeout = n.timeout),
n.query_params &&
(x.query_params = n.query_params),
n.view && (x.view = n.view),
U();
});
T();
})
.catch(function (e) {
D("getCheckpoint rejected with ", e);
});
}
function z(e) {
(d = !1), D("writeCheckpoint completed with error", e);
}
r.ready(e, t),
r.cancelled
? T()
: (r._addedListeners ||
(r.once("cancel", T),
"function" == typeof n.complete &&
(r.once("error", n.complete),
r.once("complete", function (e) {
n.complete(null, e);
})),
(r._addedListeners = !0)),
void 0 === n.since
? J()
: P()
.then(function () {
return (d = !0), a.writeCheckpoint(n.since, S);
})
.then(function () {
(d = !1),
r.cancelled ? T() : ((_ = n.since), J());
})
.catch(z));
}
class Kn extends a {
constructor() {
super(), (this.cancelled = !1), (this.state = "pending");
const e = new Promise((e, t) => {
this.once("complete", e), this.once("error", t);
});
(this.then = function (t, n) {
return e.then(t, n);
}),
(this.catch = function (t) {
return e.catch(t);
}),
this.catch(function () {});
}
cancel() {
(this.cancelled = !0),
(this.state = "cancelled"),
this.emit("cancel");
}
ready(e, t) {
if (this._readyCalled) return;
this._readyCalled = !0;
const n = () => {
this.cancel();
};
function r() {
e.removeListener("destroyed", n),
t.removeListener("destroyed", n);
}
e.once("destroyed", n),
t.once("destroyed", n),
this.once("complete", r),
this.once("error", r);
}
}
function Jn(e, t) {
var n = t.PouchConstructor;
return "string" == typeof e ? new n(e, t) : e;
}
function zn(e, t, n, r) {
if (
("function" == typeof n && ((r = n), (n = {})),
void 0 === n && (n = {}),
n.doc_ids && !Array.isArray(n.doc_ids))
)
throw N(D, "`doc_ids` filter parameter is not a list.");
(n.complete = r),
((n = f(n)).continuous = n.continuous || n.live),
(n.retry = "retry" in n && n.retry),
(n.PouchConstructor = n.PouchConstructor || this);
var i = new Kn(n);
return Fn(Jn(e, n), Jn(t, n), n, i), i;
}
function Vn(e, t, n, r) {
return (
"function" == typeof n && ((r = n), (n = {})),
void 0 === n && (n = {}),
((n = f(n)).PouchConstructor = n.PouchConstructor || this),
(e = Jn(e, n)),
(t = Jn(t, n)),
new Gn(e, t, n, r)
);
}
class Gn extends a {
constructor(e, t, n, r) {
super(), (this.canceled = !1);
const i = n.push ? Object.assign({}, n, n.push) : n,
o = n.pull ? Object.assign({}, n, n.pull) : n;
(this.push = zn(e, t, i)),
(this.pull = zn(t, e, o)),
(this.pushPaused = !0),
(this.pullPaused = !0);
const s = (e) => {
this.emit("change", { direction: "pull", change: e });
},
a = (e) => {
this.emit("change", { direction: "push", change: e });
},
c = (e) => {
this.emit("denied", { direction: "push", doc: e });
},
u = (e) => {
this.emit("denied", { direction: "pull", doc: e });
},
f = () => {
(this.pushPaused = !0),
this.pullPaused && this.emit("paused");
},
l = () => {
(this.pullPaused = !0),
this.pushPaused && this.emit("paused");
},
d = () => {
(this.pushPaused = !1),
this.pullPaused &&
this.emit("active", { direction: "push" });
},
h = () => {
(this.pullPaused = !1),
this.pushPaused &&
this.emit("active", { direction: "pull" });
};
let p = {};
const v = (e) => (t, n) => {
(("change" === t && (n === s || n === a)) ||
("denied" === t && (n === u || n === c)) ||
("paused" === t && (n === l || n === f)) ||
("active" === t && (n === h || n === d))) &&
(t in p || (p[t] = {}),
(p[t][e] = !0),
2 === Object.keys(p[t]).length &&
this.removeAllListeners(t));
};
function _(e, t, n) {
-1 == e.listeners(t).indexOf(n) && e.on(t, n);
}
n.live &&
(this.push.on("complete", this.pull.cancel.bind(this.pull)),
this.pull.on("complete", this.push.cancel.bind(this.push))),
this.on("newListener", function (e) {
"change" === e
? (_(this.pull, "change", s), _(this.push, "change", a))
: "denied" === e
? (_(this.pull, "denied", u), _(this.push, "denied", c))
: "active" === e
? (_(this.pull, "active", h), _(this.push, "active", d))
: "paused" === e &&
(_(this.pull, "paused", l),
_(this.push, "paused", f));
}),
this.on("removeListener", function (e) {
"change" === e
? (this.pull.removeListener("change", s),
this.push.removeListener("change", a))
: "denied" === e
? (this.pull.removeListener("denied", u),
this.push.removeListener("denied", c))
: "active" === e
? (this.pull.removeListener("active", h),
this.push.removeListener("active", d))
: "paused" === e &&
(this.pull.removeListener("paused", l),
this.push.removeListener("paused", f));
}),
this.pull.on("removeListener", v("pull")),
this.push.on("removeListener", v("push"));
const y = Promise.all([this.push, this.pull]).then(
(e) => {
const t = { push: e[0], pull: e[1] };
return (
this.emit("complete", t),
r && r(null, t),
this.removeAllListeners(),
t
);
},
(e) => {
if (
(this.cancel(),
r ? r(e) : this.emit("error", e),
this.removeAllListeners(),
r)
)
throw e;
}
);
(this.then = function (e, t) {
return y.then(e, t);
}),
(this.catch = function (e) {
return y.catch(e);
});
}
cancel() {
this.canceled ||
((this.canceled = !0),
this.push.cancel(),
this.pull.cancel());
}
}
Ke.plugin(function (e) {
e.adapter("idb", Ht, !0);
})
.plugin(function (e) {
e.adapter("http", an, !1), e.adapter("https", an, !1);
})
.plugin($n)
.plugin(function (e) {
(e.replicate = zn),
(e.sync = Vn),
Object.defineProperty(e.prototype, "replicate", {
get: function () {
var e = this;
return (
void 0 === this.replicateMethods &&
(this.replicateMethods = {
from: function (t, n, r) {
return e.constructor.replicate(t, e, n, r);
},
to: function (t, n, r) {
return e.constructor.replicate(e, t, n, r);
},
}),
this.replicateMethods
);
},
}),
(e.prototype.sync = function (e, t, n) {
return this.constructor.sync(this, e, t, n);
});
}),
(t.exports = Ke);
}).call(this);
}).call(this, e("_process"));
},
{ _process: 2, events: 1, "spark-md5": 3, uuid: 4, vuvuzela: 19 },
],
},
{},
[20]
)(20);
});
// pouchdb-find plugin 9.0.0
// Based on Mango: https://github.com/cloudant/mango
//
// (c) 2012-2024 Dale Harvey and the PouchDB team
// PouchDB may be freely distributed under the Apache license, version 2.0.
// For all details and documentation:
// http://pouchdb.com
!(function e(t, n, r) {
function o(s, u) {
if (!n[s]) {
if (!t[s]) {
var c = "function" == typeof require && require;
if (!u && c) return c(s, !0);
if (i) return i(s, !0);
var a = new Error("Cannot find module '" + s + "'");
throw ((a.code = "MODULE_NOT_FOUND"), a);
}
var f = (n[s] = { exports: {} });
t[s][0].call(
f.exports,
function (e) {
return o(t[s][1][e] || e);
},
f,
f.exports,
e,
t,
n,
r
);
}
return n[s].exports;
}
for (
var i = "function" == typeof require && require, s = 0;
s < r.length;
s++
)
o(r[s]);
return o;
})(
{
1: [
function (e, t, n) {
var r =
Object.create ||
function (e) {
var t = function () {};
return (t.prototype = e), new t();
},
o =
Object.keys ||
function (e) {
var t = [];
for (var n in e)
Object.prototype.hasOwnProperty.call(e, n) && t.push(n);
return n;
},
i =
Function.prototype.bind ||
function (e) {
var t = this;
return function () {
return t.apply(e, arguments);
};
};
function s() {
(this._events &&
Object.prototype.hasOwnProperty.call(this, "_events")) ||
((this._events = r(null)), (this._eventsCount = 0)),
(this._maxListeners = this._maxListeners || void 0);
}
(t.exports = s),
(s.EventEmitter = s),
(s.prototype._events = void 0),
(s.prototype._maxListeners = void 0);
var u,
c = 10;
try {
var a = {};
Object.defineProperty && Object.defineProperty(a, "x", { value: 0 }),
(u = 0 === a.x);
} catch (e) {
u = !1;
}
function f(e) {
return void 0 === e._maxListeners
? s.defaultMaxListeners
: e._maxListeners;
}
function l(e, t, n) {
if (t) e.call(n);
else
for (var r = e.length, o = w(e, r), i = 0; i < r; ++i) o[i].call(n);
}
function d(e, t, n, r) {
if (t) e.call(n, r);
else
for (var o = e.length, i = w(e, o), s = 0; s < o; ++s)
i[s].call(n, r);
}
function y(e, t, n, r, o) {
if (t) e.call(n, r, o);
else
for (var i = e.length, s = w(e, i), u = 0; u < i; ++u)
s[u].call(n, r, o);
}
function p(e, t, n, r, o, i) {
if (t) e.call(n, r, o, i);
else
for (var s = e.length, u = w(e, s), c = 0; c < s; ++c)
u[c].call(n, r, o, i);
}
function h(e, t, n, r) {
if (t) e.apply(n, r);
else
for (var o = e.length, i = w(e, o), s = 0; s < o; ++s)
i[s].apply(n, r);
}
function v(e, t, n, o) {
var i, s, u;
if ("function" != typeof n)
throw new TypeError('"listener" argument must be a function');
if (
((s = e._events)
? (s.newListener &&
(e.emit("newListener", t, n.listener ? n.listener : n),
(s = e._events)),
(u = s[t]))
: ((s = e._events = r(null)), (e._eventsCount = 0)),
u)
) {
if (
("function" == typeof u
? (u = s[t] = o ? [n, u] : [u, n])
: o
? u.unshift(n)
: u.push(n),
!u.warned && (i = f(e)) && i > 0 && u.length > i)
) {
u.warned = !0;
var c = new Error(
"Possible EventEmitter memory leak detected. " +
u.length +
' "' +
String(t) +
'" listeners added. Use emitter.setMaxListeners() to increase limit.'
);
(c.name = "MaxListenersExceededWarning"),
(c.emitter = e),
(c.type = t),
(c.count = u.length),
"object" == typeof console &&
console.warn &&
console.warn("%s: %s", c.name, c.message);
}
} else (u = s[t] = n), ++e._eventsCount;
return e;
}
function g() {
if (!this.fired)
switch (
(this.target.removeListener(this.type, this.wrapFn),
(this.fired = !0),
arguments.length)
) {
case 0:
return this.listener.call(this.target);
case 1:
return this.listener.call(this.target, arguments[0]);
case 2:
return this.listener.call(
this.target,
arguments[0],
arguments[1]
);
case 3:
return this.listener.call(
this.target,
arguments[0],
arguments[1],
arguments[2]
);
default:
for (
var e = new Array(arguments.length), t = 0;
t < e.length;
++t
)
e[t] = arguments[t];
this.listener.apply(this.target, e);
}
}
function m(e, t, n) {
var r = {
fired: !1,
wrapFn: void 0,
target: e,
type: t,
listener: n,
},
o = i.call(g, r);
return (o.listener = n), (r.wrapFn = o), o;
}
function _(e, t, n) {
var r = e._events;
if (!r) return [];
var o = r[t];
return o
? "function" == typeof o
? n
? [o.listener || o]
: [o]
: n
? (function (e) {
for (var t = new Array(e.length), n = 0; n < t.length; ++n)
t[n] = e[n].listener || e[n];
return t;
})(o)
: w(o, o.length)
: [];
}
function b(e) {
var t = this._events;
if (t) {
var n = t[e];
if ("function" == typeof n) return 1;
if (n) return n.length;
}
return 0;
}
function w(e, t) {
for (var n = new Array(t), r = 0; r < t; ++r) n[r] = e[r];
return n;
}
u
? Object.defineProperty(s, "defaultMaxListeners", {
enumerable: !0,
get: function () {
return c;
},
set: function (e) {
if ("number" != typeof e || e < 0 || e != e)
throw new TypeError(
'"defaultMaxListeners" must be a positive number'
);
c = e;
},
})
: (s.defaultMaxListeners = c),
(s.prototype.setMaxListeners = function (e) {
if ("number" != typeof e || e < 0 || isNaN(e))
throw new TypeError('"n" argument must be a positive number');
return (this._maxListeners = e), this;
}),
(s.prototype.getMaxListeners = function () {
return f(this);
}),
(s.prototype.emit = function (e) {
var t,
n,
r,
o,
i,
s,
u = "error" === e;
if ((s = this._events)) u = u && null == s.error;
else if (!u) return !1;
if (u) {
if (
(arguments.length > 1 && (t = arguments[1]), t instanceof Error)
)
throw t;
var c = new Error('Unhandled "error" event. (' + t + ")");
throw ((c.context = t), c);
}
if (!(n = s[e])) return !1;
var a = "function" == typeof n;
switch ((r = arguments.length)) {
case 1:
l(n, a, this);
break;
case 2:
d(n, a, this, arguments[1]);
break;
case 3:
y(n, a, this, arguments[1], arguments[2]);
break;
case 4:
p(n, a, this, arguments[1], arguments[2], arguments[3]);
break;
default:
for (o = new Array(r - 1), i = 1; i < r; i++)
o[i - 1] = arguments[i];
h(n, a, this, o);
}
return !0;
}),
(s.prototype.addListener = function (e, t) {
return v(this, e, t, !1);
}),
(s.prototype.on = s.prototype.addListener),
(s.prototype.prependListener = function (e, t) {
return v(this, e, t, !0);
}),
(s.prototype.once = function (e, t) {
if ("function" != typeof t)
throw new TypeError('"listener" argument must be a function');
return this.on(e, m(this, e, t)), this;
}),
(s.prototype.prependOnceListener = function (e, t) {
if ("function" != typeof t)
throw new TypeError('"listener" argument must be a function');
return this.prependListener(e, m(this, e, t)), this;
}),
(s.prototype.removeListener = function (e, t) {
var n, o, i, s, u;
if ("function" != typeof t)
throw new TypeError('"listener" argument must be a function');
if (!(o = this._events)) return this;
if (!(n = o[e])) return this;
if (n === t || n.listener === t)
0 == --this._eventsCount
? (this._events = r(null))
: (delete o[e],
o.removeListener &&
this.emit("removeListener", e, n.listener || t));
else if ("function" != typeof n) {
for (i = -1, s = n.length - 1; s >= 0; s--)
if (n[s] === t || n[s].listener === t) {
(u = n[s].listener), (i = s);
break;
}
if (i < 0) return this;
0 === i
? n.shift()
: (function (e, t) {
for (
var n = t, r = n + 1, o = e.length;
r < o;
n += 1, r += 1
)
e[n] = e[r];
e.pop();
})(n, i),
1 === n.length && (o[e] = n[0]),
o.removeListener && this.emit("removeListener", e, u || t);
}
return this;
}),
(s.prototype.removeAllListeners = function (e) {
var t, n, i;
if (!(n = this._events)) return this;
if (!n.removeListener)
return (
0 === arguments.length
? ((this._events = r(null)), (this._eventsCount = 0))
: n[e] &&
(0 == --this._eventsCount
? (this._events = r(null))
: delete n[e]),
this
);
if (0 === arguments.length) {
var s,
u = o(n);
for (i = 0; i < u.length; ++i)
"removeListener" !== (s = u[i]) && this.removeAllListeners(s);
return (
this.removeAllListeners("removeListener"),
(this._events = r(null)),
(this._eventsCount = 0),
this
);
}
if ("function" == typeof (t = n[e])) this.removeListener(e, t);
else if (t)
for (i = t.length - 1; i >= 0; i--) this.removeListener(e, t[i]);
return this;
}),
(s.prototype.listeners = function (e) {
return _(this, e, !0);
}),
(s.prototype.rawListeners = function (e) {
return _(this, e, !1);
}),
(s.listenerCount = function (e, t) {
return "function" == typeof e.listenerCount
? e.listenerCount(t)
: b.call(e, t);
}),
(s.prototype.listenerCount = b),
(s.prototype.eventNames = function () {
return this._eventsCount > 0 ? Reflect.ownKeys(this._events) : [];
});
},
{},
],
2: [
function (e, t, n) {
!(function (e) {
if ("object" == typeof n) t.exports = e();
else if ("function" == typeof define && define.amd) define(e);
else {
var r;
try {
r = window;
} catch (e) {
r = self;
}
r.SparkMD5 = e();
}
})(function (e) {
"use strict";
var t = [
"0",
"1",
"2",
"3",
"4",
"5",
"6",
"7",
"8",
"9",
"a",
"b",
"c",
"d",
"e",
"f",
];
function n(e, t) {
var n = e[0],
r = e[1],
o = e[2],
i = e[3];
(r =
((((r +=
((((o =
((((o +=
((((i =
((((i +=
((((n =
((((n +=
(((r & o) | (~r & i)) + t[0] - 680876936) | 0) <<
7) |
(n >>> 25)) +
r) |
0) &
r) |
(~n & o)) +
t[1] -
389564586) |
0) <<
12) |
(i >>> 20)) +
n) |
0) &
n) |
(~i & r)) +
t[2] +
606105819) |
0) <<
17) |
(o >>> 15)) +
i) |
0) &
i) |
(~o & n)) +
t[3] -
1044525330) |
0) <<
22) |
(r >>> 10)) +
o) |
0),
(r =
((((r +=
((((o =
((((o +=
((((i =
((((i +=
((((n =
((((n +=
(((r & o) | (~r & i)) + t[4] - 176418897) | 0) <<
7) |
(n >>> 25)) +
r) |
0) &
r) |
(~n & o)) +
t[5] +
1200080426) |
0) <<
12) |
(i >>> 20)) +
n) |
0) &
n) |
(~i & r)) +
t[6] -
1473231341) |
0) <<
17) |
(o >>> 15)) +
i) |
0) &
i) |
(~o & n)) +
t[7] -
45705983) |
0) <<
22) |
(r >>> 10)) +
o) |
0),
(r =
((((r +=
((((o =
((((o +=
((((i =
((((i +=
((((n =
((((n +=
(((r & o) | (~r & i)) + t[8] + 1770035416) | 0) <<
7) |
(n >>> 25)) +
r) |
0) &
r) |
(~n & o)) +
t[9] -
1958414417) |
0) <<
12) |
(i >>> 20)) +
n) |
0) &
n) |
(~i & r)) +
t[10] -
42063) |
0) <<
17) |
(o >>> 15)) +
i) |
0) &
i) |
(~o & n)) +
t[11] -
1990404162) |
0) <<
22) |
(r >>> 10)) +
o) |
0),
(r =
((((r +=
((((o =
((((o +=
((((i =
((((i +=
((((n =
((((n +=
(((r & o) | (~r & i)) + t[12] + 1804603682) |
0) <<
7) |
(n >>> 25)) +
r) |
0) &
r) |
(~n & o)) +
t[13] -
40341101) |
0) <<
12) |
(i >>> 20)) +
n) |
0) &
n) |
(~i & r)) +
t[14] -
1502002290) |
0) <<
17) |
(o >>> 15)) +
i) |
0) &
i) |
(~o & n)) +
t[15] +
1236535329) |
0) <<
22) |
(r >>> 10)) +
o) |
0),
(r =
((((r +=
((((o =
((((o +=
((((i =
((((i +=
((((n =
((((n +=
(((r & i) | (o & ~i)) + t[1] - 165796510) | 0) <<
5) |
(n >>> 27)) +
r) |
0) &
o) |
(r & ~o)) +
t[6] -
1069501632) |
0) <<
9) |
(i >>> 23)) +
n) |
0) &
r) |
(n & ~r)) +
t[11] +
643717713) |
0) <<
14) |
(o >>> 18)) +
i) |
0) &
n) |
(i & ~n)) +
t[0] -
373897302) |
0) <<
20) |
(r >>> 12)) +
o) |
0),
(r =
((((r +=
((((o =
((((o +=
((((i =
((((i +=
((((n =
((((n +=
(((r & i) | (o & ~i)) + t[5] - 701558691) | 0) <<
5) |
(n >>> 27)) +
r) |
0) &
o) |
(r & ~o)) +
t[10] +
38016083) |
0) <<
9) |
(i >>> 23)) +
n) |
0) &
r) |
(n & ~r)) +
t[15] -
660478335) |
0) <<
14) |
(o >>> 18)) +
i) |
0) &
n) |
(i & ~n)) +
t[4] -
405537848) |
0) <<
20) |
(r >>> 12)) +
o) |
0),
(r =
((((r +=
((((o =
((((o +=
((((i =
((((i +=
((((n =
((((n +=
(((r & i) | (o & ~i)) + t[9] + 568446438) | 0) <<
5) |
(n >>> 27)) +
r) |
0) &
o) |
(r & ~o)) +
t[14] -
1019803690) |
0) <<
9) |
(i >>> 23)) +
n) |
0) &
r) |
(n & ~r)) +
t[3] -
187363961) |
0) <<
14) |
(o >>> 18)) +
i) |
0) &
n) |
(i & ~n)) +
t[8] +
1163531501) |
0) <<
20) |
(r >>> 12)) +
o) |
0),
(r =
((((r +=
((((o =
((((o +=
((((i =
((((i +=
((((n =
((((n +=
(((r & i) | (o & ~i)) + t[13] - 1444681467) |
0) <<
5) |
(n >>> 27)) +
r) |
0) &
o) |
(r & ~o)) +
t[2] -
51403784) |
0) <<
9) |
(i >>> 23)) +
n) |
0) &
r) |
(n & ~r)) +
t[7] +
1735328473) |
0) <<
14) |
(o >>> 18)) +
i) |
0) &
n) |
(i & ~n)) +
t[12] -
1926607734) |
0) <<
20) |
(r >>> 12)) +
o) |
0),
(r =
((((r +=
(((o =
((((o +=
(((i =
((((i +=
(((n =
((((n += ((r ^ o ^ i) + t[5] - 378558) | 0) << 4) |
(n >>> 28)) +
r) |
0) ^
r ^
o) +
t[8] -
2022574463) |
0) <<
11) |
(i >>> 21)) +
n) |
0) ^
n ^
r) +
t[11] +
1839030562) |
0) <<
16) |
(o >>> 16)) +
i) |
0) ^
i ^
n) +
t[14] -
35309556) |
0) <<
23) |
(r >>> 9)) +
o) |
0),
(r =
((((r +=
(((o =
((((o +=
(((i =
((((i +=
(((n =
((((n += ((r ^ o ^ i) + t[1] - 1530992060) | 0) <<
4) |
(n >>> 28)) +
r) |
0) ^
r ^
o) +
t[4] +
1272893353) |
0) <<
11) |
(i >>> 21)) +
n) |
0) ^
n ^
r) +
t[7] -
155497632) |
0) <<
16) |
(o >>> 16)) +
i) |
0) ^
i ^
n) +
t[10] -
1094730640) |
0) <<
23) |
(r >>> 9)) +
o) |
0),
(r =
((((r +=
(((o =
((((o +=
(((i =
((((i +=
(((n =
((((n += ((r ^ o ^ i) + t[13] + 681279174) | 0) <<
4) |
(n >>> 28)) +
r) |
0) ^
r ^
o) +
t[0] -
358537222) |
0) <<
11) |
(i >>> 21)) +
n) |
0) ^
n ^
r) +
t[3] -
722521979) |
0) <<
16) |
(o >>> 16)) +
i) |
0) ^
i ^
n) +
t[6] +
76029189) |
0) <<
23) |
(r >>> 9)) +
o) |
0),
(r =
((((r +=
(((o =
((((o +=
(((i =
((((i +=
(((n =
((((n += ((r ^ o ^ i) + t[9] - 640364487) | 0) <<
4) |
(n >>> 28)) +
r) |
0) ^
r ^
o) +
t[12] -
421815835) |
0) <<
11) |
(i >>> 21)) +
n) |
0) ^
n ^
r) +
t[15] +
530742520) |
0) <<
16) |
(o >>> 16)) +
i) |
0) ^
i ^
n) +
t[2] -
995338651) |
0) <<
23) |
(r >>> 9)) +
o) |
0),
(r =
((((r +=
(((i =
((((i +=
((r ^
((n =
((((n += ((o ^ (r | ~i)) + t[0] - 198630844) | 0) <<
6) |
(n >>> 26)) +
r) |
0) |
~o)) +
t[7] +
1126891415) |
0) <<
10) |
(i >>> 22)) +
n) |
0) ^
((o =
((((o += ((n ^ (i | ~r)) + t[14] - 1416354905) | 0) <<
15) |
(o >>> 17)) +
i) |
0) |
~n)) +
t[5] -
57434055) |
0) <<
21) |
(r >>> 11)) +
o) |
0),
(r =
((((r +=
(((i =
((((i +=
((r ^
((n =
((((n += ((o ^ (r | ~i)) + t[12] + 1700485571) | 0) <<
6) |
(n >>> 26)) +
r) |
0) |
~o)) +
t[3] -
1894986606) |
0) <<
10) |
(i >>> 22)) +
n) |
0) ^
((o =
((((o += ((n ^ (i | ~r)) + t[10] - 1051523) | 0) << 15) |
(o >>> 17)) +
i) |
0) |
~n)) +
t[1] -
2054922799) |
0) <<
21) |
(r >>> 11)) +
o) |
0),
(r =
((((r +=
(((i =
((((i +=
((r ^
((n =
((((n += ((o ^ (r | ~i)) + t[8] + 1873313359) | 0) <<
6) |
(n >>> 26)) +
r) |
0) |
~o)) +
t[15] -
30611744) |
0) <<
10) |
(i >>> 22)) +
n) |
0) ^
((o =
((((o += ((n ^ (i | ~r)) + t[6] - 1560198380) | 0) <<
15) |
(o >>> 17)) +
i) |
0) |
~n)) +
t[13] +
1309151649) |
0) <<
21) |
(r >>> 11)) +
o) |
0),
(r =
((((r +=
(((i =
((((i +=
((r ^
((n =
((((n += ((o ^ (r | ~i)) + t[4] - 145523070) | 0) <<
6) |
(n >>> 26)) +
r) |
0) |
~o)) +
t[11] -
1120210379) |
0) <<
10) |
(i >>> 22)) +
n) |
0) ^
((o =
((((o += ((n ^ (i | ~r)) + t[2] + 718787259) | 0) << 15) |
(o >>> 17)) +
i) |
0) |
~n)) +
t[9] -
343485551) |
0) <<
21) |
(r >>> 11)) +
o) |
0),
(e[0] = (n + e[0]) | 0),
(e[1] = (r + e[1]) | 0),
(e[2] = (o + e[2]) | 0),
(e[3] = (i + e[3]) | 0);
}
function r(e) {
var t,
n = [];
for (t = 0; t < 64; t += 4)
n[t >> 2] =
e.charCodeAt(t) +
(e.charCodeAt(t + 1) << 8) +
(e.charCodeAt(t + 2) << 16) +
(e.charCodeAt(t + 3) << 24);
return n;
}
function o(e) {
var t,
n = [];
for (t = 0; t < 64; t += 4)
n[t >> 2] =
e[t] + (e[t + 1] << 8) + (e[t + 2] << 16) + (e[t + 3] << 24);
return n;
}
function i(e) {
var t,
o,
i,
s,
u,
c,
a = e.length,
f = [1732584193, -271733879, -1732584194, 271733878];
for (t = 64; t <= a; t += 64) n(f, r(e.substring(t - 64, t)));
for (
o = (e = e.substring(t - 64)).length,
i = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
t = 0;
t < o;
t += 1
)
i[t >> 2] |= e.charCodeAt(t) << (t % 4 << 3);
if (((i[t >> 2] |= 128 << (t % 4 << 3)), t > 55))
for (n(f, i), t = 0; t < 16; t += 1) i[t] = 0;
return (
(s = (s = 8 * a).toString(16).match(/(.*?)(.{0,8})$/)),
(u = parseInt(s[2], 16)),
(c = parseInt(s[1], 16) || 0),
(i[14] = u),
(i[15] = c),
n(f, i),
f
);
}
function s(e) {
var n,
r = "";
for (n = 0; n < 4; n += 1)
r += t[(e >> (8 * n + 4)) & 15] + t[(e >> (8 * n)) & 15];
return r;
}
function u(e) {
var t;
for (t = 0; t < e.length; t += 1) e[t] = s(e[t]);
return e.join("");
}
function c(e) {
return (
/[\u0080-\uFFFF]/.test(e) &&
(e = unescape(encodeURIComponent(e))),
e
);
}
function a(e) {
var t,
n = [],
r = e.length;
for (t = 0; t < r - 1; t += 2) n.push(parseInt(e.substr(t, 2), 16));
return String.fromCharCode.apply(String, n);
}
function f() {
this.reset();
}
return (
"5d41402abc4b2a76b9719d911017c592" !== u(i("hello")) &&
function (e, t) {
var n = (65535 & e) + (65535 & t);
return (
(((e >> 16) + (t >> 16) + (n >> 16)) << 16) | (65535 & n)
);
},
"undefined" == typeof ArrayBuffer ||
ArrayBuffer.prototype.slice ||
(function () {
function t(e, t) {
return (e = 0 | e || 0) < 0
? Math.max(e + t, 0)
: Math.min(e, t);
}
ArrayBuffer.prototype.slice = function (n, r) {
var o,
i,
s,
u,
c = this.byteLength,
a = t(n, c),
f = c;
return (
r !== e && (f = t(r, c)),
a > f
? new ArrayBuffer(0)
: ((o = f - a),
(i = new ArrayBuffer(o)),
(s = new Uint8Array(i)),
(u = new Uint8Array(this, a, o)),
s.set(u),
i)
);
};
})(),
(f.prototype.append = function (e) {
return this.appendBinary(c(e)), this;
}),
(f.prototype.appendBinary = function (e) {
(this._buff += e), (this._length += e.length);
var t,
o = this._buff.length;
for (t = 64; t <= o; t += 64)
n(this._hash, r(this._buff.substring(t - 64, t)));
return (this._buff = this._buff.substring(t - 64)), this;
}),
(f.prototype.end = function (e) {
var t,
n,
r = this._buff,
o = r.length,
i = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0];
for (t = 0; t < o; t += 1)
i[t >> 2] |= r.charCodeAt(t) << (t % 4 << 3);
return (
this._finish(i, o),
(n = u(this._hash)),
e && (n = a(n)),
this.reset(),
n
);
}),
(f.prototype.reset = function () {
return (
(this._buff = ""),
(this._length = 0),
(this._hash = [1732584193, -271733879, -1732584194, 271733878]),
this
);
}),
(f.prototype.getState = function () {
return {
buff: this._buff,
length: this._length,
hash: this._hash.slice(),
};
}),
(f.prototype.setState = function (e) {
return (
(this._buff = e.buff),
(this._length = e.length),
(this._hash = e.hash),
this
);
}),
(f.prototype.destroy = function () {
delete this._hash, delete this._buff, delete this._length;
}),
(f.prototype._finish = function (e, t) {
var r,
o,
i,
s = t;
if (((e[s >> 2] |= 128 << (s % 4 << 3)), s > 55))
for (n(this._hash, e), s = 0; s < 16; s += 1) e[s] = 0;
(r = (r = 8 * this._length).toString(16).match(/(.*?)(.{0,8})$/)),
(o = parseInt(r[2], 16)),
(i = parseInt(r[1], 16) || 0),
(e[14] = o),
(e[15] = i),
n(this._hash, e);
}),
(f.hash = function (e, t) {
return f.hashBinary(c(e), t);
}),
(f.hashBinary = function (e, t) {
var n = u(i(e));
return t ? a(n) : n;
}),
(f.ArrayBuffer = function () {
this.reset();
}),
(f.ArrayBuffer.prototype.append = function (e) {
var t,
r,
i,
s,
u,
c =
((r = this._buff.buffer),
(i = e),
(s = !0),
(u = new Uint8Array(r.byteLength + i.byteLength)).set(
new Uint8Array(r)
),
u.set(new Uint8Array(i), r.byteLength),
s ? u : u.buffer),
a = c.length;
for (this._length += e.byteLength, t = 64; t <= a; t += 64)
n(this._hash, o(c.subarray(t - 64, t)));
return (
(this._buff =
t - 64 < a
? new Uint8Array(c.buffer.slice(t - 64))
: new Uint8Array(0)),
this
);
}),
(f.ArrayBuffer.prototype.end = function (e) {
var t,
n,
r = this._buff,
o = r.length,
i = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0];
for (t = 0; t < o; t += 1) i[t >> 2] |= r[t] << (t % 4 << 3);
return (
this._finish(i, o),
(n = u(this._hash)),
e && (n = a(n)),
this.reset(),
n
);
}),
(f.ArrayBuffer.prototype.reset = function () {
return (
(this._buff = new Uint8Array(0)),
(this._length = 0),
(this._hash = [1732584193, -271733879, -1732584194, 271733878]),
this
);
}),
(f.ArrayBuffer.prototype.getState = function () {
var e,
t = f.prototype.getState.call(this);
return (
(t.buff =
((e = t.buff),
String.fromCharCode.apply(null, new Uint8Array(e)))),
t
);
}),
(f.ArrayBuffer.prototype.setState = function (e) {
return (
(e.buff = (function (e, t) {
var n,
r = e.length,
o = new ArrayBuffer(r),
i = new Uint8Array(o);
for (n = 0; n < r; n += 1) i[n] = e.charCodeAt(n);
return t ? i : o;
})(e.buff, !0)),
f.prototype.setState.call(this, e)
);
}),
(f.ArrayBuffer.prototype.destroy = f.prototype.destroy),
(f.ArrayBuffer.prototype._finish = f.prototype._finish),
(f.ArrayBuffer.hash = function (e, t) {
var r = u(
(function (e) {
var t,
r,
i,
s,
u,
c,
a = e.length,
f = [1732584193, -271733879, -1732584194, 271733878];
for (t = 64; t <= a; t += 64) n(f, o(e.subarray(t - 64, t)));
for (
r = (e =
t - 64 < a ? e.subarray(t - 64) : new Uint8Array(0))
.length,
i = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
t = 0;
t < r;
t += 1
)
i[t >> 2] |= e[t] << (t % 4 << 3);
if (((i[t >> 2] |= 128 << (t % 4 << 3)), t > 55))
for (n(f, i), t = 0; t < 16; t += 1) i[t] = 0;
return (
(s = (s = 8 * a).toString(16).match(/(.*?)(.{0,8})$/)),
(u = parseInt(s[2], 16)),
(c = parseInt(s[1], 16) || 0),
(i[14] = u),
(i[15] = c),
n(f, i),
f
);
})(new Uint8Array(e))
);
return t ? a(r) : r;
}),
f
);
});
},
{},
],
3: [
function (e, t, n) {
"use strict";
Object.defineProperty(n, "__esModule", { value: !0 }),
Object.defineProperty(n, "v1", {
enumerable: !0,
get: function () {
return r.default;
},
}),
Object.defineProperty(n, "v3", {
enumerable: !0,
get: function () {
return o.default;
},
}),
Object.defineProperty(n, "v4", {
enumerable: !0,
get: function () {
return i.default;
},
}),
Object.defineProperty(n, "v5", {
enumerable: !0,
get: function () {
return s.default;
},
}),
Object.defineProperty(n, "NIL", {
enumerable: !0,
get: function () {
return u.default;
},
}),
Object.defineProperty(n, "version", {
enumerable: !0,
get: function () {
return c.default;
},
}),
Object.defineProperty(n, "validate", {
enumerable: !0,
get: function () {
return a.default;
},
}),
Object.defineProperty(n, "stringify", {
enumerable: !0,
get: function () {
return f.default;
},
}),
Object.defineProperty(n, "parse", {
enumerable: !0,
get: function () {
return l.default;
},
});
var r = d(e("./v1.js")),
o = d(e("./v3.js")),
i = d(e("./v4.js")),
s = d(e("./v5.js")),
u = d(e("./nil.js")),
c = d(e("./version.js")),
a = d(e("./validate.js")),
f = d(e("./stringify.js")),
l = d(e("./parse.js"));
function d(e) {
return e && e.__esModule ? e : { default: e };
}
},
{
"./nil.js": 5,
"./parse.js": 6,
"./stringify.js": 10,
"./v1.js": 11,
"./v3.js": 12,
"./v4.js": 14,
"./v5.js": 15,
"./validate.js": 16,
"./version.js": 17,
},
],
4: [
function (e, t, n) {
"use strict";
function r(e) {
return 14 + (((e + 64) >>> 9) << 4) + 1;
}
function o(e, t) {
const n = (65535 & e) + (65535 & t);
return (((e >> 16) + (t >> 16) + (n >> 16)) << 16) | (65535 & n);
}
function i(e, t, n, r, i, s) {
return o(
((u = o(o(t, e), o(r, s))) << (c = i)) | (u >>> (32 - c)),
n
);
var u, c;
}
function s(e, t, n, r, o, s, u) {
return i((t & n) | (~t & r), e, t, o, s, u);
}
function u(e, t, n, r, o, s, u) {
return i((t & r) | (n & ~r), e, t, o, s, u);
}
function c(e, t, n, r, o, s, u) {
return i(t ^ n ^ r, e, t, o, s, u);
}
function a(e, t, n, r, o, s, u) {
return i(n ^ (t | ~r), e, t, o, s, u);
}
Object.defineProperty(n, "__esModule", { value: !0 }),
(n.default = void 0);
var f = function (e) {
if ("string" == typeof e) {
const t = unescape(encodeURIComponent(e));
e = new Uint8Array(t.length);
for (let n = 0; n < t.length; ++n) e[n] = t.charCodeAt(n);
}
return (function (e) {
const t = [],
n = 32 * e.length;
for (let r = 0; r < n; r += 8) {
const n = (e[r >> 5] >>> r % 32) & 255,
o = parseInt(
"0123456789abcdef".charAt((n >>> 4) & 15) +
"0123456789abcdef".charAt(15 & n),
16
);
t.push(o);
}
return t;
})(
(function (e, t) {
(e[t >> 5] |= 128 << t % 32), (e[r(t) - 1] = t);
let n = 1732584193,
i = -271733879,
f = -1732584194,
l = 271733878;
for (let t = 0; t < e.length; t += 16) {
const r = n,
d = i,
y = f,
p = l;
(n = s(n, i, f, l, e[t], 7, -680876936)),
(l = s(l, n, i, f, e[t + 1], 12, -389564586)),
(f = s(f, l, n, i, e[t + 2], 17, 606105819)),
(i = s(i, f, l, n, e[t + 3], 22, -1044525330)),
(n = s(n, i, f, l, e[t + 4], 7, -176418897)),
(l = s(l, n, i, f, e[t + 5], 12, 1200080426)),
(f = s(f, l, n, i, e[t + 6], 17, -1473231341)),
(i = s(i, f, l, n, e[t + 7], 22, -45705983)),
(n = s(n, i, f, l, e[t + 8], 7, 1770035416)),
(l = s(l, n, i, f, e[t + 9], 12, -1958414417)),
(f = s(f, l, n, i, e[t + 10], 17, -42063)),
(i = s(i, f, l, n, e[t + 11], 22, -1990404162)),
(n = s(n, i, f, l, e[t + 12], 7, 1804603682)),
(l = s(l, n, i, f, e[t + 13], 12, -40341101)),
(f = s(f, l, n, i, e[t + 14], 17, -1502002290)),
(i = s(i, f, l, n, e[t + 15], 22, 1236535329)),
(n = u(n, i, f, l, e[t + 1], 5, -165796510)),
(l = u(l, n, i, f, e[t + 6], 9, -1069501632)),
(f = u(f, l, n, i, e[t + 11], 14, 643717713)),
(i = u(i, f, l, n, e[t], 20, -373897302)),
(n = u(n, i, f, l, e[t + 5], 5, -701558691)),
(l = u(l, n, i, f, e[t + 10], 9, 38016083)),
(f = u(f, l, n, i, e[t + 15], 14, -660478335)),
(i = u(i, f, l, n, e[t + 4], 20, -405537848)),
(n = u(n, i, f, l, e[t + 9], 5, 568446438)),
(l = u(l, n, i, f, e[t + 14], 9, -1019803690)),
(f = u(f, l, n, i, e[t + 3], 14, -187363961)),
(i = u(i, f, l, n, e[t + 8], 20, 1163531501)),
(n = u(n, i, f, l, e[t + 13], 5, -1444681467)),
(l = u(l, n, i, f, e[t + 2], 9, -51403784)),
(f = u(f, l, n, i, e[t + 7], 14, 1735328473)),
(i = u(i, f, l, n, e[t + 12], 20, -1926607734)),
(n = c(n, i, f, l, e[t + 5], 4, -378558)),
(l = c(l, n, i, f, e[t + 8], 11, -2022574463)),
(f = c(f, l, n, i, e[t + 11], 16, 1839030562)),
(i = c(i, f, l, n, e[t + 14], 23, -35309556)),
(n = c(n, i, f, l, e[t + 1], 4, -1530992060)),
(l = c(l, n, i, f, e[t + 4], 11, 1272893353)),
(f = c(f, l, n, i, e[t + 7], 16, -155497632)),
(i = c(i, f, l, n, e[t + 10], 23, -1094730640)),
(n = c(n, i, f, l, e[t + 13], 4, 681279174)),
(l = c(l, n, i, f, e[t], 11, -358537222)),
(f = c(f, l, n, i, e[t + 3], 16, -722521979)),
(i = c(i, f, l, n, e[t + 6], 23, 76029189)),
(n = c(n, i, f, l, e[t + 9], 4, -640364487)),
(l = c(l, n, i, f, e[t + 12], 11, -421815835)),
(f = c(f, l, n, i, e[t + 15], 16, 530742520)),
(i = c(i, f, l, n, e[t + 2], 23, -995338651)),
(n = a(n, i, f, l, e[t], 6, -198630844)),
(l = a(l, n, i, f, e[t + 7], 10, 1126891415)),
(f = a(f, l, n, i, e[t + 14], 15, -1416354905)),
(i = a(i, f, l, n, e[t + 5], 21, -57434055)),
(n = a(n, i, f, l, e[t + 12], 6, 1700485571)),
(l = a(l, n, i, f, e[t + 3], 10, -1894986606)),
(f = a(f, l, n, i, e[t + 10], 15, -1051523)),
(i = a(i, f, l, n, e[t + 1], 21, -2054922799)),
(n = a(n, i, f, l, e[t + 8], 6, 1873313359)),
(l = a(l, n, i, f, e[t + 15], 10, -30611744)),
(f = a(f, l, n, i, e[t + 6], 15, -1560198380)),
(i = a(i, f, l, n, e[t + 13], 21, 1309151649)),
(n = a(n, i, f, l, e[t + 4], 6, -145523070)),
(l = a(l, n, i, f, e[t + 11], 10, -1120210379)),
(f = a(f, l, n, i, e[t + 2], 15, 718787259)),
(i = a(i, f, l, n, e[t + 9], 21, -343485551)),
(n = o(n, r)),
(i = o(i, d)),
(f = o(f, y)),
(l = o(l, p));
}
return [n, i, f, l];
})(
(function (e) {
if (0 === e.length) return [];
const t = 8 * e.length,
n = new Uint32Array(r(t));
for (let r = 0; r < t; r += 8)
n[r >> 5] |= (255 & e[r / 8]) << r % 32;
return n;
})(e),
8 * e.length
)
);
};
n.default = f;
},
{},
],
5: [
function (e, t, n) {
"use strict";
Object.defineProperty(n, "__esModule", { value: !0 }),
(n.default = void 0);
n.default = "00000000-0000-0000-0000-000000000000";
},
{},
],
6: [
function (e, t, n) {
"use strict";
Object.defineProperty(n, "__esModule", { value: !0 }),
(n.default = void 0);
var r,
o = (r = e("./validate.js")) && r.__esModule ? r : { default: r };
var i = function (e) {
if (!(0, o.default)(e)) throw TypeError("Invalid UUID");
let t;
const n = new Uint8Array(16);
return (
(n[0] = (t = parseInt(e.slice(0, 8), 16)) >>> 24),
(n[1] = (t >>> 16) & 255),
(n[2] = (t >>> 8) & 255),
(n[3] = 255 & t),
(n[4] = (t = parseInt(e.slice(9, 13), 16)) >>> 8),
(n[5] = 255 & t),
(n[6] = (t = parseInt(e.slice(14, 18), 16)) >>> 8),
(n[7] = 255 & t),
(n[8] = (t = parseInt(e.slice(19, 23), 16)) >>> 8),
(n[9] = 255 & t),
(n[10] =
((t = parseInt(e.slice(24, 36), 16)) / 1099511627776) & 255),
(n[11] = (t / 4294967296) & 255),
(n[12] = (t >>> 24) & 255),
(n[13] = (t >>> 16) & 255),
(n[14] = (t >>> 8) & 255),
(n[15] = 255 & t),
n
);
};
n.default = i;
},
{ "./validate.js": 16 },
],
7: [
function (e, t, n) {
"use strict";
Object.defineProperty(n, "__esModule", { value: !0 }),
(n.default = void 0);
n.default =
/^(?:[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|00000000-0000-0000-0000-000000000000)$/i;
},
{},
],
8: [
function (e, t, n) {
"use strict";
let r;
Object.defineProperty(n, "__esModule", { value: !0 }),
(n.default = function () {
if (
!r &&
((r =
("undefined" != typeof crypto &&
crypto.getRandomValues &&
crypto.getRandomValues.bind(crypto)) ||
("undefined" != typeof msCrypto &&
"function" == typeof msCrypto.getRandomValues &&
msCrypto.getRandomValues.bind(msCrypto))),
!r)
)
throw new Error(
"crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported"
);
return r(o);
});
const o = new Uint8Array(16);
},
{},
],
9: [
function (e, t, n) {
"use strict";
function r(e, t, n, r) {
switch (e) {
case 0:
return (t & n) ^ (~t & r);
case 1:
return t ^ n ^ r;
case 2:
return (t & n) ^ (t & r) ^ (n & r);
case 3:
return t ^ n ^ r;
}
}
function o(e, t) {
return (e << t) | (e >>> (32 - t));
}
Object.defineProperty(n, "__esModule", { value: !0 }),
(n.default = void 0);
var i = function (e) {
const t = [1518500249, 1859775393, 2400959708, 3395469782],
n = [1732584193, 4023233417, 2562383102, 271733878, 3285377520];
if ("string" == typeof e) {
const t = unescape(encodeURIComponent(e));
e = [];
for (let n = 0; n < t.length; ++n) e.push(t.charCodeAt(n));
} else Array.isArray(e) || (e = Array.prototype.slice.call(e));
e.push(128);
const i = e.length / 4 + 2,
s = Math.ceil(i / 16),
u = new Array(s);
for (let t = 0; t < s; ++t) {
const n = new Uint32Array(16);
for (let r = 0; r < 16; ++r)
n[r] =
(e[64 * t + 4 * r] << 24) |
(e[64 * t + 4 * r + 1] << 16) |
(e[64 * t + 4 * r + 2] << 8) |
e[64 * t + 4 * r + 3];
u[t] = n;
}
(u[s - 1][14] = (8 * (e.length - 1)) / Math.pow(2, 32)),
(u[s - 1][14] = Math.floor(u[s - 1][14])),
(u[s - 1][15] = (8 * (e.length - 1)) & 4294967295);
for (let e = 0; e < s; ++e) {
const i = new Uint32Array(80);
for (let t = 0; t < 16; ++t) i[t] = u[e][t];
for (let e = 16; e < 80; ++e)
i[e] = o(i[e - 3] ^ i[e - 8] ^ i[e - 14] ^ i[e - 16], 1);
let s = n[0],
c = n[1],
a = n[2],
f = n[3],
l = n[4];
for (let e = 0; e < 80; ++e) {
const n = Math.floor(e / 20),
u = (o(s, 5) + r(n, c, a, f) + l + t[n] + i[e]) >>> 0;
(l = f), (f = a), (a = o(c, 30) >>> 0), (c = s), (s = u);
}
(n[0] = (n[0] + s) >>> 0),
(n[1] = (n[1] + c) >>> 0),
(n[2] = (n[2] + a) >>> 0),
(n[3] = (n[3] + f) >>> 0),
(n[4] = (n[4] + l) >>> 0);
}
return [
(n[0] >> 24) & 255,
(n[0] >> 16) & 255,
(n[0] >> 8) & 255,
255 & n[0],
(n[1] >> 24) & 255,
(n[1] >> 16) & 255,
(n[1] >> 8) & 255,
255 & n[1],
(n[2] >> 24) & 255,
(n[2] >> 16) & 255,
(n[2] >> 8) & 255,
255 & n[2],
(n[3] >> 24) & 255,
(n[3] >> 16) & 255,
(n[3] >> 8) & 255,
255 & n[3],
(n[4] >> 24) & 255,
(n[4] >> 16) & 255,
(n[4] >> 8) & 255,
255 & n[4],
];
};
n.default = i;
},
{},
],
10: [
function (e, t, n) {
"use strict";
Object.defineProperty(n, "__esModule", { value: !0 }),
(n.default = void 0);
var r,
o = (r = e("./validate.js")) && r.__esModule ? r : { default: r };
const i = [];
for (let e = 0; e < 256; ++e) i.push((e + 256).toString(16).substr(1));
var s = function (e, t = 0) {
const n = (
i[e[t + 0]] +
i[e[t + 1]] +
i[e[t + 2]] +
i[e[t + 3]] +
"-" +
i[e[t + 4]] +
i[e[t + 5]] +
"-" +
i[e[t + 6]] +
i[e[t + 7]] +
"-" +
i[e[t + 8]] +
i[e[t + 9]] +
"-" +
i[e[t + 10]] +
i[e[t + 11]] +
i[e[t + 12]] +
i[e[t + 13]] +
i[e[t + 14]] +
i[e[t + 15]]
).toLowerCase();
if (!(0, o.default)(n))
throw TypeError("Stringified UUID is invalid");
return n;
};
n.default = s;
},
{ "./validate.js": 16 },
],
11: [
function (e, t, n) {
"use strict";
Object.defineProperty(n, "__esModule", { value: !0 }),
(n.default = void 0);
var r = i(e("./rng.js")),
o = i(e("./stringify.js"));
function i(e) {
return e && e.__esModule ? e : { default: e };
}
let s,
u,
c = 0,
a = 0;
var f = function (e, t, n) {
let i = (t && n) || 0;
const f = t || new Array(16);
let l = (e = e || {}).node || s,
d = void 0 !== e.clockseq ? e.clockseq : u;
if (null == l || null == d) {
const t = e.random || (e.rng || r.default)();
null == l && (l = s = [1 | t[0], t[1], t[2], t[3], t[4], t[5]]),
null == d && (d = u = 16383 & ((t[6] << 8) | t[7]));
}
let y = void 0 !== e.msecs ? e.msecs : Date.now(),
p = void 0 !== e.nsecs ? e.nsecs : a + 1;
const h = y - c + (p - a) / 1e4;
if (
(h < 0 && void 0 === e.clockseq && (d = (d + 1) & 16383),
(h < 0 || y > c) && void 0 === e.nsecs && (p = 0),
p >= 1e4)
)
throw new Error("uuid.v1(): Can't create more than 10M uuids/sec");
(c = y), (a = p), (u = d), (y += 122192928e5);
const v = (1e4 * (268435455 & y) + p) % 4294967296;
(f[i++] = (v >>> 24) & 255),
(f[i++] = (v >>> 16) & 255),
(f[i++] = (v >>> 8) & 255),
(f[i++] = 255 & v);
const g = ((y / 4294967296) * 1e4) & 268435455;
(f[i++] = (g >>> 8) & 255),
(f[i++] = 255 & g),
(f[i++] = ((g >>> 24) & 15) | 16),
(f[i++] = (g >>> 16) & 255),
(f[i++] = (d >>> 8) | 128),
(f[i++] = 255 & d);
for (let e = 0; e < 6; ++e) f[i + e] = l[e];
return t || (0, o.default)(f);
};
n.default = f;
},
{ "./rng.js": 8, "./stringify.js": 10 },
],
12: [
function (e, t, n) {
"use strict";
Object.defineProperty(n, "__esModule", { value: !0 }),
(n.default = void 0);
var r = i(e("./v35.js")),
o = i(e("./md5.js"));
function i(e) {
return e && e.__esModule ? e : { default: e };
}
var s = (0, r.default)("v3", 48, o.default);
n.default = s;
},
{ "./md5.js": 4, "./v35.js": 13 },
],
13: [
function (e, t, n) {
"use strict";
Object.defineProperty(n, "__esModule", { value: !0 }),
(n.default = function (e, t, n) {
function i(e, i, s, u) {
if (
("string" == typeof e &&
(e = (function (e) {
e = unescape(encodeURIComponent(e));
const t = [];
for (let n = 0; n < e.length; ++n) t.push(e.charCodeAt(n));
return t;
})(e)),
"string" == typeof i && (i = (0, o.default)(i)),
16 !== i.length)
)
throw TypeError(
"Namespace must be array-like (16 iterable integer values, 0-255)"
);
let c = new Uint8Array(16 + e.length);
if (
(c.set(i),
c.set(e, i.length),
(c = n(c)),
(c[6] = (15 & c[6]) | t),
(c[8] = (63 & c[8]) | 128),
s)
) {
u = u || 0;
for (let e = 0; e < 16; ++e) s[u + e] = c[e];
return s;
}
return (0, r.default)(c);
}
try {
i.name = e;
} catch (e) {}
return (i.DNS = s), (i.URL = u), i;
}),
(n.URL = n.DNS = void 0);
var r = i(e("./stringify.js")),
o = i(e("./parse.js"));
function i(e) {
return e && e.__esModule ? e : { default: e };
}
const s = "6ba7b810-9dad-11d1-80b4-00c04fd430c8";
n.DNS = s;
const u = "6ba7b811-9dad-11d1-80b4-00c04fd430c8";
n.URL = u;
},
{ "./parse.js": 6, "./stringify.js": 10 },
],
14: [
function (e, t, n) {
"use strict";
Object.defineProperty(n, "__esModule", { value: !0 }),
(n.default = void 0);
var r = i(e("./rng.js")),
o = i(e("./stringify.js"));
function i(e) {
return e && e.__esModule ? e : { default: e };
}
var s = function (e, t, n) {
const i = (e = e || {}).random || (e.rng || r.default)();
if (((i[6] = (15 & i[6]) | 64), (i[8] = (63 & i[8]) | 128), t)) {
n = n || 0;
for (let e = 0; e < 16; ++e) t[n + e] = i[e];
return t;
}
return (0, o.default)(i);
};
n.default = s;
},
{ "./rng.js": 8, "./stringify.js": 10 },
],
15: [
function (e, t, n) {
"use strict";
Object.defineProperty(n, "__esModule", { value: !0 }),
(n.default = void 0);
var r = i(e("./v35.js")),
o = i(e("./sha1.js"));
function i(e) {
return e && e.__esModule ? e : { default: e };
}
var s = (0, r.default)("v5", 80, o.default);
n.default = s;
},
{ "./sha1.js": 9, "./v35.js": 13 },
],
16: [
function (e, t, n) {
"use strict";
Object.defineProperty(n, "__esModule", { value: !0 }),
(n.default = void 0);
var r,
o = (r = e("./regex.js")) && r.__esModule ? r : { default: r };
var i = function (e) {
return "string" == typeof e && o.default.test(e);
};
n.default = i;
},
{ "./regex.js": 7 },
],
17: [
function (e, t, n) {
"use strict";
Object.defineProperty(n, "__esModule", { value: !0 }),
(n.default = void 0);
var r,
o = (r = e("./validate.js")) && r.__esModule ? r : { default: r };
var i = function (e) {
if (!(0, o.default)(e)) throw TypeError("Invalid UUID");
return parseInt(e.substr(14, 1), 16);
};
n.default = i;
},
{ "./validate.js": 16 },
],
18: [
function (e, t, n) {
"use strict";
e("events"), e("uuid");
var r,
o =
(r = e("spark-md5")) && "object" == typeof r && "default" in r
? r.default
: r;
var i = Function.prototype.toString,
s = i.call(Object);
function u(e) {
var t, n, r;
if (!e || "object" != typeof e) return e;
if (Array.isArray(e)) {
for (t = [], n = 0, r = e.length; n < r; n++) t[n] = u(e[n]);
return t;
}
if (e instanceof Date && isFinite(e)) return e.toISOString();
if (
(function (e) {
return (
("undefined" != typeof ArrayBuffer &&
e instanceof ArrayBuffer) ||
("undefined" != typeof Blob && e instanceof Blob)
);
})(e)
)
return (function (e) {
return e instanceof ArrayBuffer
? e.slice(0)
: e.slice(0, e.size, e.type);
})(e);
if (
!(function (e) {
var t = Object.getPrototypeOf(e);
if (null === t) return !0;
var n = t.constructor;
return "function" == typeof n && n instanceof n && i.call(n) == s;
})(e)
)
return e;
for (n in ((t = {}), e))
if (Object.prototype.hasOwnProperty.call(e, n)) {
var o = u(e[n]);
void 0 !== o && (t[n] = o);
}
return t;
}
try {
localStorage.setItem("_pouch_check_localstorage", 1),
!!localStorage.getItem("_pouch_check_localstorage");
} catch (e) {
!1;
}
const c =
"function" == typeof queueMicrotask
? queueMicrotask
: function (e) {
Promise.resolve().then(e);
};
function a(e) {
if (
"undefined" != typeof console &&
"function" == typeof console[e]
) {
var t = Array.prototype.slice.call(arguments, 1);
console[e].apply(console, t);
}
}
class f extends Error {
constructor(e, t, n) {
super(),
(this.status = e),
(this.name = t),
(this.message = n),
(this.error = !0);
}
toString() {
return JSON.stringify({
status: this.status,
name: this.name,
message: this.message,
reason: this.reason,
});
}
}
new f(401, "unauthorized", "Name or password is incorrect."),
new f(400, "bad_request", "Missing JSON list of 'docs'"),
new f(404, "not_found", "missing"),
new f(409, "conflict", "Document update conflict"),
new f(400, "bad_request", "_id field must contain a string"),
new f(412, "missing_id", "_id is required for puts"),
new f(
400,
"bad_request",
"Only reserved document ids may start with underscore."
),
new f(412, "precondition_failed", "Database not open");
var l = new f(
500,
"unknown_error",
"Database encountered an unknown error"
);
new f(500, "badarg", "Some query argument is invalid"),
new f(400, "invalid_request", "Request was invalid"),
new f(400, "query_parse_error", "Some query parameter is invalid"),
new f(500, "doc_validation", "Bad special document member"),
new f(400, "bad_request", "Something wrong with the request"),
new f(400, "bad_request", "Document must be a JSON object"),
new f(404, "not_found", "Database not found"),
new f(500, "indexed_db_went_bad", "unknown"),
new f(500, "web_sql_went_bad", "unknown"),
new f(500, "levelDB_went_went_bad", "unknown"),
new f(
403,
"forbidden",
"Forbidden by design doc validate_doc_update function"
),
new f(400, "bad_request", "Invalid rev format"),
new f(
412,
"file_exists",
"The database could not be created, the file already exists."
),
new f(
412,
"missing_stub",
"A pre-existing attachment stub wasn't found"
),
new f(413, "invalid_url", "Provided URL is invalid");
function d(e) {
if ("object" != typeof e) {
var t = e;
(e = l).data = t;
}
return (
"error" in e &&
"conflict" === e.error &&
((e.name = "conflict"), (e.status = 409)),
"name" in e || (e.name = e.error || "unknown"),
"status" in e || (e.status = 500),
"message" in e || (e.message = e.message || e.reason),
"stack" in e || (e.stack = new Error().stack),
e
);
}
function y(e) {
return "boolean" == typeof e._remote
? e._remote
: "function" == typeof e.type &&
(a(
"warn",
"db.type() is deprecated and will be removed in a future version of PouchDB"
),
"http" === e.type());
}
function p(e, t, n) {
return e
.get(t)
.catch(function (e) {
if (404 !== e.status) throw e;
return {};
})
.then(function (r) {
var o = r._rev,
i = n(r);
return i
? ((i._id = t),
(i._rev = o),
(function (e, t, n) {
return e.put(t).then(
function (e) {
return { updated: !0, rev: e.rev };
},
function (r) {
if (409 !== r.status) throw r;
return p(e, t._id, n);
}
);
})(e, i, n))
: { updated: !1, rev: o };
});
}
function h(e) {
for (
var t = e.length,
n = new ArrayBuffer(t),
r = new Uint8Array(n),
o = 0;
o < t;
o++
)
r[o] = e.charCodeAt(o);
return n;
}
function v(e, t) {
return (function (e, t) {
(e = e || []), (t = t || {});
try {
return new Blob(e, t);
} catch (o) {
if ("TypeError" !== o.name) throw o;
for (
var n = new (
"undefined" != typeof BlobBuilder
? BlobBuilder
: "undefined" != typeof MSBlobBuilder
? MSBlobBuilder
: "undefined" != typeof MozBlobBuilder
? MozBlobBuilder
: WebKitBlobBuilder
)(),
r = 0;
r < e.length;
r += 1
)
n.append(e[r]);
return n.getBlob(t.type);
}
})([h(e)], { type: t });
}
function g(e, t) {
return v(atob(e), t);
}
self.setImmediate || self.setTimeout;
function m(e) {
return o.hash(e);
}
function _(e, t) {
for (var n = e, r = 0, o = t.length; r < o; r++) {
if (!(n = n[t[r]])) break;
}
return n;
}
function b(e, t, n) {
for (var r = 0, o = t.length; r < o - 1; r++) {
var i = t[r];
e = e[i] = e[i] || {};
}
e[t[o - 1]] = n;
}
function w(e, t) {
return e < t ? -1 : e > t ? 1 : 0;
}
function k(e) {
for (var t = [], n = "", r = 0, o = e.length; r < o; r++) {
var i = e[r];
r > 0 && "\\" === e[r - 1] && ("$" === i || "." === i)
? (n = n.substring(0, n.length - 1) + i)
: "." === i
? (t.push(n), (n = ""))
: (n += i);
}
return t.push(n), t;
}
var j = ["$or", "$nor", "$not"];
function $(e) {
return j.indexOf(e) > -1;
}
function x(e) {
return Object.keys(e)[0];
}
function O(e) {
return e[x(e)];
}
function A(e) {
var t = {},
n = { $or: !0, $nor: !0 };
return (
e.forEach(function (e) {
Object.keys(e).forEach(function (r) {
var o = e[r];
if (("object" != typeof o && (o = { $eq: o }), $(r)))
if (o instanceof Array) {
if (n[r]) return (n[r] = !1), void (t[r] = o);
var i = [];
t[r].forEach(function (e) {
Object.keys(o).forEach(function (t) {
var n = o[t],
r = Math.max(
Object.keys(e).length,
Object.keys(n).length
),
s = A([e, n]);
Object.keys(s).length <= r || i.push(s);
});
}),
(t[r] = i);
} else t[r] = A([o]);
else {
var s = (t[r] = t[r] || {});
Object.keys(o).forEach(function (e) {
var t = o[e];
return "$gt" === e || "$gte" === e
? (function (e, t, n) {
if (void 0 !== n.$eq) return;
void 0 !== n.$gte
? "$gte" === e
? t > n.$gte && (n.$gte = t)
: t >= n.$gte && (delete n.$gte, (n.$gt = t))
: void 0 !== n.$gt
? "$gte" === e
? t > n.$gt && (delete n.$gt, (n.$gte = t))
: t > n.$gt && (n.$gt = t)
: (n[e] = t);
})(e, t, s)
: "$lt" === e || "$lte" === e
? (function (e, t, n) {
if (void 0 !== n.$eq) return;
void 0 !== n.$lte
? "$lte" === e
? t < n.$lte && (n.$lte = t)
: t <= n.$lte && (delete n.$lte, (n.$lt = t))
: void 0 !== n.$lt
? "$lte" === e
? t < n.$lt && (delete n.$lt, (n.$lte = t))
: t < n.$lt && (n.$lt = t)
: (n[e] = t);
})(e, t, s)
: "$ne" === e
? (function (e, t) {
"$ne" in t ? t.$ne.push(e) : (t.$ne = [e]);
})(t, s)
: "$eq" === e
? (function (e, t) {
delete t.$gt,
delete t.$gte,
delete t.$lt,
delete t.$lte,
delete t.$ne,
(t.$eq = e);
})(t, s)
: "$regex" === e
? (function (e, t) {
"$regex" in t ? t.$regex.push(e) : (t.$regex = [e]);
})(t, s)
: void (s[e] = t);
});
}
});
}),
t
);
}
function q(e) {
var t = u(e);
(function e(t, n) {
for (var r in t) {
"$and" === r && (n = !0);
var o = t[r];
"object" == typeof o && (n = e(o, n));
}
return n;
})(t, !1) &&
"$and" in
(t = (function e(t) {
for (var n in t) {
if (Array.isArray(t))
for (var r in t) t[r].$and && (t[r] = A(t[r].$and));
var o = t[n];
"object" == typeof o && e(o);
}
return t;
})(t)) &&
(t = A(t.$and)),
["$or", "$nor"].forEach(function (e) {
e in t &&
t[e].forEach(function (e) {
for (var t = Object.keys(e), n = 0; n < t.length; n++) {
var r = t[n],
o = e[r];
("object" == typeof o && null !== o) || (e[r] = { $eq: o });
}
});
}),
"$not" in t && (t.$not = A([t.$not]));
for (var n = Object.keys(t), r = 0; r < n.length; r++) {
var o = n[r],
i = t[o];
("object" == typeof i && null !== i) || (i = { $eq: i }),
(t[o] = i);
}
return (
(function e(t) {
Object.keys(t).forEach(function (n) {
var r = t[n];
Array.isArray(r)
? r.forEach(function (t) {
t && "object" == typeof t && e(t);
})
: "$ne" === n
? (t.$ne = [r])
: "$regex" === n
? (t.$regex = [r])
: r && "object" == typeof r && e(r);
});
})(t),
t
);
}
function M(e, t) {
if (e === t) return 0;
(e = E(e)), (t = E(t));
var n = C(e),
r = C(t);
if (n - r != 0) return n - r;
switch (typeof e) {
case "number":
return e - t;
case "boolean":
return e < t ? -1 : 1;
case "string":
return (function (e, t) {
return e === t ? 0 : e > t ? 1 : -1;
})(e, t);
}
return Array.isArray(e)
? (function (e, t) {
for (var n = Math.min(e.length, t.length), r = 0; r < n; r++) {
var o = M(e[r], t[r]);
if (0 !== o) return o;
}
return e.length === t.length ? 0 : e.length > t.length ? 1 : -1;
})(e, t)
: (function (e, t) {
for (
var n = Object.keys(e),
r = Object.keys(t),
o = Math.min(n.length, r.length),
i = 0;
i < o;
i++
) {
var s = M(n[i], r[i]);
if (0 !== s) return s;
if (0 !== (s = M(e[n[i]], t[r[i]]))) return s;
}
return n.length === r.length ? 0 : n.length > r.length ? 1 : -1;
})(e, t);
}
function E(e) {
switch (typeof e) {
case "undefined":
return null;
case "number":
return e === 1 / 0 || e === -1 / 0 || isNaN(e) ? null : e;
case "object":
var t = e;
if (Array.isArray(e)) {
var n = e.length;
e = new Array(n);
for (var r = 0; r < n; r++) e[r] = E(t[r]);
} else {
if (e instanceof Date) return e.toJSON();
if (null !== e)
for (var o in ((e = {}), t))
if (Object.prototype.hasOwnProperty.call(t, o)) {
var i = t[o];
void 0 !== i && (e[o] = E(i));
}
}
}
return e;
}
function S(e) {
if (null !== e)
switch (typeof e) {
case "boolean":
return e ? 1 : 0;
case "number":
return (function (e) {
if (0 === e) return "1";
var t = e.toExponential().split(/e\+?/),
n = parseInt(t[1], 10),
r = e < 0,
o = r ? "0" : "2",
i =
((s = ((r ? -n : n) - -324).toString()),
(u = "0"),
(c = 3),
(function (e, t, n) {
for (var r = "", o = n - e.length; r.length < o; )
r += t;
return r;
})(s, u, c) + s);
var s, u, c;
o += "" + i;
var a = Math.abs(parseFloat(t[0]));
r && (a = 10 - a);
var f = a.toFixed(20);
return (f = f.replace(/\.?0+$/, "")), (o += "" + f);
})(e);
case "string":
return e
.replace(/\u0002/g, "\x02\x02")
.replace(/\u0001/g, "\x01\x02")
.replace(/\u0000/g, "\x01\x01");
case "object":
var t = Array.isArray(e),
n = t ? e : Object.keys(e),
r = -1,
o = n.length,
i = "";
if (t) for (; ++r < o; ) i += B(n[r]);
else
for (; ++r < o; ) {
var s = n[r];
i += B(s) + B(e[s]);
}
return i;
}
return "";
}
function B(e) {
return C((e = E(e))) + "" + S(e) + "\0";
}
function P(e, t) {
var n,
r = t;
if ("1" === e[t]) (n = 0), t++;
else {
var o = "0" === e[t];
t++;
var i = "",
s = e.substring(t, t + 3),
u = parseInt(s, 10) + -324;
for (o && (u = -u), t += 3; ; ) {
var c = e[t];
if ("\0" === c) break;
(i += c), t++;
}
(n =
1 === (i = i.split(".")).length
? parseInt(i, 10)
: parseFloat(i[0] + "." + i[1])),
o && (n -= 10),
0 !== u && (n = parseFloat(n + "e" + u));
}
return { num: n, length: t - r };
}
function I(e, t) {
var n = e.pop();
if (t.length) {
var r = t[t.length - 1];
n === r.element && (t.pop(), (r = t[t.length - 1]));
var o = r.element,
i = r.index;
if (Array.isArray(o)) o.push(n);
else if (i === e.length - 2) {
o[e.pop()] = n;
} else e.push(n);
}
}
function C(e) {
var t = ["boolean", "number", "string", "object"].indexOf(typeof e);
return ~t
? null === e
? 1
: Array.isArray(e)
? 5
: t < 3
? t + 2
: t + 3
: Array.isArray(e)
? 5
: void 0;
}
function L(e, t, n) {
if (
((e = e.filter(function (e) {
return U(e.doc, t.selector, n);
})),
t.sort)
) {
var r = (function (e) {
function t(t) {
return e.map(function (e) {
var n = k(x(e));
return _(t, n);
});
}
return function (e, n) {
var r = M(t(e.doc), t(n.doc));
return 0 !== r ? r : w(e.doc._id, n.doc._id);
};
})(t.sort);
(e = e.sort(r)),
"string" != typeof t.sort[0] &&
"desc" === O(t.sort[0]) &&
(e = e.reverse());
}
if ("limit" in t || "skip" in t) {
var o = t.skip || 0,
i = ("limit" in t ? t.limit : e.length) + o;
e = e.slice(o, i);
}
return e;
}
function U(e, t, n) {
return n.every(function (n) {
var r = t[n],
o = k(n),
i = _(e, o);
return $(n)
? (function (e, t, n) {
if ("$or" === e)
return t.some(function (e) {
return U(n, e, Object.keys(e));
});
if ("$not" === e) return !U(n, t, Object.keys(t));
return !t.find(function (e) {
return U(n, e, Object.keys(e));
});
})(n, r, e)
: D(r, e, o, i);
});
}
function D(e, t, n, r) {
return (
!e ||
("object" == typeof e
? Object.keys(e).every(function (o) {
var i = e[o];
if (0 === o.indexOf("$")) return N(o, t, i, n, r);
var s = k(o);
if (void 0 === r && "object" != typeof i && s.length > 0)
return !1;
var u = _(r, s);
return "object" == typeof i
? D(i, t, n, u)
: N("$eq", t, i, s, u);
})
: e === r)
);
}
function N(e, t, n, r, o) {
if (!z[e])
throw new Error(
'unknown operator "' +
e +
'" - should be one of $eq, $lte, $lt, $gt, $gte, $exists, $ne, $in, $nin, $size, $mod, $regex, $elemMatch, $type, $allMatch or $all'
);
return z[e](t, n, r, o);
}
function T(e) {
return null != e;
}
function F(e) {
return void 0 !== e;
}
function R(e, t) {
return t.some(function (t) {
return e instanceof Array
? e.some(function (e) {
return 0 === M(t, e);
})
: 0 === M(t, e);
});
}
var z = {
$elemMatch: function (e, t, n, r) {
return (
!!Array.isArray(r) &&
0 !== r.length &&
("object" == typeof r[0] && null !== r[0]
? r.some(function (e) {
return U(e, t, Object.keys(t));
})
: r.some(function (r) {
return D(t, e, n, r);
}))
);
},
$allMatch: function (e, t, n, r) {
return (
!!Array.isArray(r) &&
0 !== r.length &&
("object" == typeof r[0] && null !== r[0]
? r.every(function (e) {
return U(e, t, Object.keys(t));
})
: r.every(function (r) {
return D(t, e, n, r);
}))
);
},
$eq: function (e, t, n, r) {
return F(r) && 0 === M(r, t);
},
$gte: function (e, t, n, r) {
return F(r) && M(r, t) >= 0;
},
$gt: function (e, t, n, r) {
return F(r) && M(r, t) > 0;
},
$lte: function (e, t, n, r) {
return F(r) && M(r, t) <= 0;
},
$lt: function (e, t, n, r) {
return F(r) && M(r, t) < 0;
},
$exists: function (e, t, n, r) {
return t ? F(r) : !F(r);
},
$mod: function (e, t, n, r) {
return (
T(r) &&
(function (e, t) {
return (
"number" == typeof e &&
parseInt(e, 10) === e &&
e % t[0] === t[1]
);
})(r, t)
);
},
$ne: function (e, t, n, r) {
return t.every(function (e) {
return 0 !== M(r, e);
});
},
$in: function (e, t, n, r) {
return T(r) && R(r, t);
},
$nin: function (e, t, n, r) {
return T(r) && !R(r, t);
},
$size: function (e, t, n, r) {
return (
T(r) &&
Array.isArray(r) &&
(function (e, t) {
return e.length === t;
})(r, t)
);
},
$all: function (e, t, n, r) {
return (
Array.isArray(r) &&
(function (e, t) {
return t.every(function (t) {
return e.some(function (e) {
return 0 === M(t, e);
});
});
})(r, t)
);
},
$regex: function (e, t, n, r) {
return (
T(r) &&
"string" == typeof r &&
t.every(function (e) {
return (function (e, t) {
return new RegExp(t).test(e);
})(r, e);
})
);
},
$type: function (e, t, n, r) {
return (function (e, t) {
switch (t) {
case "null":
return null === e;
case "boolean":
return "boolean" == typeof e;
case "number":
return "number" == typeof e;
case "string":
return "string" == typeof e;
case "array":
return e instanceof Array;
case "object":
return "[object Object]" === {}.toString.call(e);
}
})(r, t);
},
};
function J(e, t) {
if ("object" != typeof t)
throw new Error("Selector error: expected a JSON object");
var n = L([{ doc: e }], { selector: (t = q(t)) }, Object.keys(t));
return n && 1 === n.length;
}
const V = (...e) => {
let t = [];
for (const n of e)
Array.isArray(n) ? (t = t.concat(V(...n))) : t.push(n);
return t;
},
Q =
"function" == typeof Array.prototype.flat
? (...e) => e.flat(1 / 0)
: V;
function K(e) {
const t = {};
for (const n of e) Object.assign(t, n);
return t;
}
function X(e, t) {
for (let n = 0, r = Math.min(e.length, t.length); n < r; n++)
if (e[n] !== t[n]) return !1;
return !0;
}
function G(e, t) {
if (e.length !== t.length) return !1;
for (let n = 0, r = e.length; n < r; n++)
if (e[n] !== t[n]) return !1;
return !0;
}
function W(e) {
return function (...t) {
const n = t[t.length - 1];
if ("function" != typeof n) return e.apply(this, t);
{
const r = n.bind(null, null),
o = n.bind(null);
e.apply(this, t.slice(0, -1)).then(r, o);
}
};
}
var Y = Headers;
function H(e) {
(e = u(e)).index || (e.index = {});
for (const t of ["type", "name", "ddoc"])
e.index[t] && ((e[t] = e.index[t]), delete e.index[t]);
return (
e.fields && ((e.index.fields = e.fields), delete e.fields),
e.type || (e.type = "json"),
e
);
}
function Z(e) {
return "object" == typeof e && null !== e;
}
function ee(e, t, n) {
let r = "",
o = t,
i = !0;
if (
(-1 !==
["$in", "$nin", "$or", "$and", "$mod", "$nor", "$all"].indexOf(
e
) &&
(Array.isArray(t) ||
(r = "Query operator " + e + " must be an array.")),
-1 !== ["$not", "$elemMatch", "$allMatch"].indexOf(e) &&
((!Array.isArray(t) && Z(t)) ||
(r = "Query operator " + e + " must be an object.")),
"$mod" === e && Array.isArray(t))
)
if (2 !== t.length)
r =
"Query operator $mod must be in the format [divisor, remainder], where divisor and remainder are both integers.";
else {
const e = t[0],
n = t[1];
0 === e &&
((r =
"Query operator $mod's divisor cannot be 0, cannot divide by zero."),
(i = !1)),
("number" == typeof e && parseInt(e, 10) === e) ||
((r = "Query operator $mod's divisor is not an integer."),
(o = e)),
parseInt(n, 10) !== n &&
((r = "Query operator $mod's remainder is not an integer."),
(o = n));
}
if (
("$exists" === e &&
"boolean" != typeof t &&
(r = "Query operator $exists must be a boolean."),
"$type" === e)
) {
const e = [
"null",
"boolean",
"number",
"string",
"array",
"object",
],
n =
'"' +
e.slice(0, e.length - 1).join('", "') +
'", or "' +
e[e.length - 1] +
'"';
("string" != typeof t || -1 == e.indexOf(t)) &&
(r =
"Query operator $type must be a string. Supported values: " +
n +
".");
}
if (
("$size" === e &&
parseInt(t, 10) !== t &&
(r = "Query operator $size must be a integer."),
"$regex" === e &&
"string" != typeof t &&
(n
? (r = "Query operator $regex must be a string.")
: t instanceof RegExp ||
(r =
"Query operator $regex must be a string or an instance of a javascript regular expression.")),
r)
) {
if (i) {
r +=
" Received" +
(null === o
? " "
: Array.isArray(o)
? " array"
: " " + typeof o) +
": " +
(Z(o) ? JSON.stringify(o, null, "\t") : o);
}
throw new Error(r);
}
}
const te = [
"$all",
"$allMatch",
"$and",
"$elemMatch",
"$exists",
"$in",
"$mod",
"$nin",
"$nor",
"$not",
"$or",
"$regex",
"$size",
"$type",
],
ne = ["$in", "$nin", "$mod", "$all"],
re = ["$eq", "$gt", "$gte", "$lt", "$lte"];
function oe(e, t) {
if (Array.isArray(e)) for (const n of e) Z(n) && oe(n, t);
else
for (const [n, r] of Object.entries(e))
-1 !== te.indexOf(n) && ee(n, r, t),
-1 === re.indexOf(n) &&
-1 === ne.indexOf(n) &&
Z(r) &&
oe(r, t);
}
async function ie(e, t, n) {
n.body &&
((n.body = JSON.stringify(n.body)),
(n.headers = new Y({ "Content-type": "application/json" })));
const r = await e.fetch(t, n),
o = await r.json();
if (!r.ok) {
o.status = r.status;
throw d(
(function (e, t) {
function n(t) {
for (
var n = Object.getOwnPropertyNames(e), r = 0, o = n.length;
r < o;
r++
)
"function" != typeof e[n[r]] && (this[n[r]] = e[n[r]]);
void 0 === this.stack && (this.stack = new Error().stack),
void 0 !== t && (this.reason = t);
}
return (n.prototype = f.prototype), new n(t);
})(o)
);
}
return o;
}
async function se(e, t) {
return await ie(e, "_index", { method: "POST", body: H(t) });
}
async function ue(e, t) {
return (
oe(t.selector, !0),
await ie(e, "_find", { method: "POST", body: t })
);
}
async function ce(e, t) {
return await ie(e, "_explain", { method: "POST", body: t });
}
async function ae(e) {
return await ie(e, "_index", { method: "GET" });
}
async function fe(e, t) {
const n = t.ddoc,
r = t.type || "json",
o = t.name;
if (!n) throw new Error("you must provide an index's ddoc");
if (!o) throw new Error("you must provide an index's name");
const i = "_index/" + [n, r, o].map(encodeURIComponent).join("/");
return await ie(e, i, { method: "DELETE" });
}
class le {
constructor() {
this.promise = Promise.resolve();
}
add(e) {
return (
(this.promise = this.promise.catch(() => {}).then(() => e())),
this.promise
);
}
finish() {
return this.promise;
}
}
function de(e) {
if (!e) return "undefined";
switch (typeof e) {
case "function":
case "string":
return e.toString();
default:
return JSON.stringify(e);
}
}
async function ye(e, t, n, r, o, i) {
const s = (function (e, t) {
return de(e) + de(t) + "undefined";
})(n, r);
let u;
if (!o && ((u = e._cachedViews = e._cachedViews || {}), u[s]))
return u[s];
const c = e.info().then(async function (c) {
const a = c.db_name + "-mrview-" + (o ? "temp" : m(s));
await p(e, "_local/" + i, function (e) {
e.views = e.views || {};
let n = t;
-1 === n.indexOf("/") && (n = t + "/" + t);
const r = (e.views[n] = e.views[n] || {});
if (!r[a]) return (r[a] = !0), e;
});
const f = (await e.registerDependentDatabase(a)).db;
f.auto_compaction = !0;
const l = {
name: a,
db: f,
sourceDB: e,
adapter: e.adapter,
mapFun: n,
reduceFun: r,
};
let d;
try {
d = await l.db.get("_local/lastSeq");
} catch (e) {
if (404 !== e.status) throw e;
}
return (
(l.seq = d ? d.seq : 0),
u &&
l.db.once("destroyed", function () {
delete u[s];
}),
l
);
});
return u && (u[s] = c), c;
}
class pe extends Error {
constructor(e) {
super(),
(this.status = 400),
(this.name = "query_parse_error"),
(this.message = e),
(this.error = !0);
try {
Error.captureStackTrace(this, pe);
} catch (e) {}
}
}
class he extends Error {
constructor(e) {
super(),
(this.status = 404),
(this.name = "not_found"),
(this.message = e),
(this.error = !0);
try {
Error.captureStackTrace(this, he);
} catch (e) {}
}
}
class ve extends Error {
constructor(e) {
super(),
(this.status = 500),
(this.name = "invalid_value"),
(this.message = e),
(this.error = !0);
try {
Error.captureStackTrace(this, ve);
} catch (e) {}
}
}
function ge(e, t) {
return (
t &&
e.then(
function (e) {
c(function () {
t(null, e);
});
},
function (e) {
c(function () {
t(e);
});
}
),
e
);
}
function me(e, t) {
return function () {
var n = arguments,
r = this;
return e.add(function () {
return t.apply(r, n);
});
};
}
function _e(e) {
var t = new Set(e),
n = new Array(t.size),
r = -1;
return (
t.forEach(function (e) {
n[++r] = e;
}),
n
);
}
function be(e) {
var t = new Array(e.size),
n = -1;
return (
e.forEach(function (e, r) {
t[++n] = r;
}),
t
);
}
const we = {},
ke = new le();
function je(e) {
return -1 === e.indexOf("/") ? [e, e] : e.split("/");
}
function $e(e, t, n) {
try {
e.emit("error", t);
} catch (e) {
a(
"error",
"The user's map/reduce function threw an uncaught error.\nYou can debug this error by doing:\nmyDatabase.on('error', function (err) { debugger; });\nPlease double-check your map/reduce function."
),
a("error", t, n);
}
}
function xe(e, t) {
for (const n of t) if (void 0 === (e = e[n])) return;
return e;
}
function Oe(e, t, n) {
const r = (function (e) {
return e.every((e) => -1 === e.indexOf("."));
})(e),
o = 1 === e.length;
return r
? o
? (function (e, t, n) {
return function (r) {
(n && !J(r, n)) || t(r[e]);
};
})(e[0], t, n)
: (function (e, t, n) {
return function (r) {
if (n && !J(r, n)) return;
const o = e.map((e) => r[e]);
t(o);
};
})(e, t, n)
: o
? (function (e, t, n) {
const r = k(e);
return function (e) {
if (n && !J(e, n)) return;
const o = xe(e, r);
void 0 !== o && t(o);
};
})(e[0], t, n)
: (function (e, t, n) {
return function (r) {
if (n && !J(r, n)) return;
const o = [];
for (const t of e) {
const e = xe(r, k(t));
if (void 0 === e) return;
o.push(e);
}
t(o);
};
})(e, t, n);
}
const Ae = (function (e, t, n, r) {
function o(e, t, n) {
try {
t(n);
} catch (r) {
$e(e, r, { fun: t, doc: n });
}
}
function i(e, t, n, r, o) {
try {
return { output: t(n, r, o) };
} catch (i) {
return (
$e(e, i, { fun: t, keys: n, values: r, rereduce: o }),
{ error: i }
);
}
}
function s(e, t) {
const n = M(e.key, t.key);
return 0 !== n ? n : M(e.value, t.value);
}
function u(e, t, n) {
return (
(n = n || 0),
"number" == typeof t ? e.slice(n, t + n) : n > 0 ? e.slice(n) : e
);
}
function a(e) {
const t = e.value;
return (t && "object" == typeof t && t._id) || e.id;
}
function f(e) {
return function (t) {
return (
e.include_docs &&
e.attachments &&
e.binary &&
(function (e) {
for (const t of e.rows) {
const e = t.doc && t.doc._attachments;
if (e)
for (const t of Object.keys(e)) {
const n = e[t];
e[t].data = g(n.data, n.content_type);
}
}
})(t),
t
);
};
}
function l(e, t, n, r) {
let o = t[e];
void 0 !== o &&
(r && (o = encodeURIComponent(JSON.stringify(o))),
n.push(e + "=" + o));
}
function p(e) {
if (void 0 !== e) {
const t = Number(e);
return isNaN(t) || t !== parseInt(e, 10) ? e : t;
}
}
function h(e) {
if (e) {
if ("number" != typeof e)
return new pe(`Invalid value for integer: "${e}"`);
if (e < 0)
return new pe(`Invalid value for positive integer: "${e}"`);
}
}
function v(e, t) {
const n = e.descending ? "endkey" : "startkey",
r = e.descending ? "startkey" : "endkey";
if (void 0 !== e[n] && void 0 !== e[r] && M(e[n], e[r]) > 0)
throw new pe(
"No rows can match your key range, reverse your start_key and end_key or set {descending : true}"
);
if (t.reduce && !1 !== e.reduce) {
if (e.include_docs)
throw new pe("{include_docs:true} is invalid for reduce");
if (e.keys && e.keys.length > 1 && !e.group && !e.group_level)
throw new pe(
"Multi-key fetches for reduce views must use {group: true}"
);
}
for (const t of ["group_level", "limit", "skip"]) {
const n = h(e[t]);
if (n) throw n;
}
}
function m(e) {
return function (t) {
if (404 === t.status) return e;
throw t;
};
}
function _(e, t, n) {
return e.db
.get("_local/lastSeq")
.catch(m({ _id: "_local/lastSeq", seq: 0 }))
.then(function (r) {
var o = be(t);
return Promise.all(
o.map(function (n) {
return (async function (e, t, n) {
const r = "_local/doc_" + e,
o = { _id: r, keys: [] },
i = n.get(e),
s = i[0],
u = i[1],
c = await ((function (e) {
return 1 === e.length && /^1-/.test(e[0].rev);
})(u)
? Promise.resolve(o)
: t.db.get(r).catch(m(o)));
return (function (e, t) {
const n = [],
r = new Set();
for (const e of t.rows) {
const t = e.doc;
if (
t &&
(n.push(t),
r.add(t._id),
(t._deleted = !s.has(t._id)),
!t._deleted)
) {
const e = s.get(t._id);
"value" in e && (t.value = e.value);
}
}
const o = be(s);
for (const e of o)
if (!r.has(e)) {
const t = { _id: e },
r = s.get(e);
"value" in r && (t.value = r.value), n.push(t);
}
return (e.keys = _e(o.concat(e.keys))), n.push(e), n;
})(
c,
await (function (e) {
return e.keys.length
? t.db.allDocs({ keys: e.keys, include_docs: !0 })
: Promise.resolve({ rows: [] });
})(c)
);
})(n, e, t);
})
)
.then(function (t) {
var o = t.flat();
return (r.seq = n), o.push(r), e.db.bulkDocs({ docs: o });
})
.then(() =>
(function (e) {
return e.sourceDB
.get("_local/purges")
.then(function (t) {
const n = t.purgeSeq;
return e.db
.get("_local/purgeSeq")
.then(function (e) {
return e._rev;
})
.catch(m(void 0))
.then(function (t) {
return e.db.put({
_id: "_local/purgeSeq",
_rev: t,
purgeSeq: n,
});
});
})
.catch(function (e) {
if (404 !== e.status) throw e;
});
})(e)
);
});
}
function b(e) {
const t = "string" == typeof e ? e : e.name;
let n = we[t];
return n || (n = we[t] = new le()), n;
}
async function w(e, n) {
return me(b(e), function () {
return (async function (e, n) {
let r, i, u;
const c = t(e.mapFun, function (e, t) {
const n = { id: i._id, key: E(e) };
null != t && (n.value = E(t)), r.push(n);
});
let a = e.seq || 0;
let f = 0;
const l = { view: e.name, indexed_docs: f };
e.sourceDB.emit("indexing", l);
const d = new le();
async function y() {
return (function (t, l) {
const h = t.results;
if (!h.length && !l.length) return;
for (const e of l) {
if (
h.findIndex(function (t) {
return t.id === e.docId;
}) < 0
) {
const t = {
_id: e.docId,
doc: { _id: e.docId, _deleted: 1 },
changes: [],
};
e.doc &&
((t.doc = e.doc),
t.changes.push({ rev: e.doc._rev })),
h.push(t);
}
}
const v = (function (t) {
const n = new Map();
for (const u of t) {
if ("_" !== u.doc._id[0]) {
(r = []),
(i = u.doc),
i._deleted || o(e.sourceDB, c, i),
r.sort(s);
const t = p(r);
n.set(u.doc._id, [t, u.changes]);
}
a = u.seq;
}
return n;
})(h);
d.add(
(function (t, n) {
return function () {
return _(e, t, n);
};
})(v, a)
),
(f += h.length);
const g = {
view: e.name,
last_seq: t.last_seq,
results_count: h.length,
indexed_docs: f,
};
if (
(e.sourceDB.emit("indexing", g),
e.sourceDB.activeTasks.update(u, { completed_items: f }),
h.length < n.changes_batch_size)
)
return;
return y();
})(
await e.sourceDB.changes({
return_docs: !0,
conflicts: !0,
include_docs: !0,
style: "all_docs",
since: a,
limit: n.changes_batch_size,
}),
await e.db
.get("_local/purgeSeq")
.then(function (e) {
return e.purgeSeq;
})
.catch(m(-1))
.then(function (t) {
return e.sourceDB
.get("_local/purges")
.then(function (n) {
const r = n.purges
.filter(function (e, n) {
return n > t;
})
.map((e) => e.docId),
o = r.filter(function (e, t) {
return r.indexOf(e) === t;
});
return Promise.all(
o.map(function (t) {
return e.sourceDB
.get(t)
.then(function (e) {
return { docId: t, doc: e };
})
.catch(m({ docId: t }));
})
);
})
.catch(m([]));
})
);
}
function p(e) {
const t = new Map();
let n;
for (let r = 0, o = e.length; r < o; r++) {
const o = e[r],
i = [o.key, o.id];
r > 0 && 0 === M(o.key, n) && i.push(r),
t.set(B(i), o),
(n = o.key);
}
return t;
}
try {
await e.sourceDB.info().then(function (t) {
u = e.sourceDB.activeTasks.add({
name: "view_indexing",
total_items: t.update_seq - a,
});
}),
await y(),
await d.finish(),
(e.seq = a),
e.sourceDB.activeTasks.remove(u);
} catch (t) {
e.sourceDB.activeTasks.remove(u, t);
}
})(e, n);
})();
}
function k(e, t) {
return me(b(e), function () {
return (async function (e, t) {
let r;
const o = e.reduceFun && !1 !== t.reduce,
s = t.skip || 0;
void 0 === t.keys ||
t.keys.length ||
((t.limit = 0), delete t.keys);
async function c(t) {
t.include_docs = !0;
const n = await e.db.allDocs(t);
return (
(r = n.total_rows),
n.rows.map(function (e) {
if (
"value" in e.doc &&
"object" == typeof e.doc.value &&
null !== e.doc.value
) {
const t = Object.keys(e.doc.value).sort(),
n = ["id", "key", "value"];
if (!(t < n || t > n)) return e.doc.value;
}
const t = (function (e) {
for (var t = [], n = [], r = 0; ; ) {
var o = e[r++];
if ("\0" !== o)
switch (o) {
case "1":
t.push(null);
break;
case "2":
t.push("1" === e[r]), r++;
break;
case "3":
var i = P(e, r);
t.push(i.num), (r += i.length);
break;
case "4":
for (var s = ""; ; ) {
var u = e[r];
if ("\0" === u) break;
(s += u), r++;
}
(s = s
.replace(/\u0001\u0001/g, "\0")
.replace(/\u0001\u0002/g, "\x01")
.replace(/\u0002\u0002/g, "\x02")),
t.push(s);
break;
case "5":
var c = { element: [], index: t.length };
t.push(c.element), n.push(c);
break;
case "6":
var a = { element: {}, index: t.length };
t.push(a.element), n.push(a);
break;
default:
throw new Error(
"bad collationIndex or unexpectedly reached end of input: " +
o
);
}
else {
if (1 === t.length) return t.pop();
I(t, n);
}
}
})(e.doc._id);
return {
key: t[0],
id: t[1],
value: "value" in e.doc ? e.doc.value : null,
};
})
);
}
async function f(c) {
let f;
if (
((f = o
? (function (e, t, r) {
0 === r.group_level && delete r.group_level;
const o = r.group || r.group_level,
s = n(e.reduceFun),
c = [],
a = isNaN(r.group_level)
? Number.POSITIVE_INFINITY
: r.group_level;
for (const e of t) {
const t = c[c.length - 1];
let n = o ? e.key : null;
o && Array.isArray(n) && (n = n.slice(0, a)),
t && 0 === M(t.groupKey, n)
? (t.keys.push([e.key, e.id]),
t.values.push(e.value))
: c.push({
keys: [[e.key, e.id]],
values: [e.value],
groupKey: n,
});
}
t = [];
for (const n of c) {
const r = i(e.sourceDB, s, n.keys, n.values, !1);
if (r.error && r.error instanceof ve) throw r.error;
t.push({
value: r.error ? null : r.output,
key: n.groupKey,
});
}
return { rows: u(t, r.limit, r.skip) };
})(e, c, t)
: void 0 === t.keys
? { total_rows: r, offset: s, rows: c }
: {
total_rows: r,
offset: s,
rows: u(c, t.limit, t.skip),
}),
t.update_seq && (f.update_seq = e.seq),
t.include_docs)
) {
const n = _e(c.map(a)),
r = await e.sourceDB.allDocs({
keys: n,
include_docs: !0,
conflicts: t.conflicts,
attachments: t.attachments,
binary: t.binary,
}),
o = new Map();
for (const e of r.rows) o.set(e.id, e.doc);
for (const e of c) {
const t = a(e),
n = o.get(t);
n && (e.doc = n);
}
}
return f;
}
if (void 0 !== t.keys) {
const e = t.keys.map(function (e) {
const n = { startkey: B([e]), endkey: B([e, {}]) };
return t.update_seq && (n.update_seq = !0), c(n);
}),
n = await Promise.all(e);
return f(n.flat());
}
{
const e = { descending: t.descending };
let n, r;
if (
(t.update_seq && (e.update_seq = !0),
"start_key" in t && (n = t.start_key),
"startkey" in t && (n = t.startkey),
"end_key" in t && (r = t.end_key),
"endkey" in t && (r = t.endkey),
void 0 !== n &&
(e.startkey = t.descending ? B([n, {}]) : B([n])),
void 0 !== r)
) {
let n = !1 !== t.inclusive_end;
t.descending && (n = !n), (e.endkey = B(n ? [r, {}] : [r]));
}
if (void 0 !== t.key) {
const n = B([t.key]),
r = B([t.key, {}]);
e.descending
? ((e.endkey = n), (e.startkey = r))
: ((e.startkey = n), (e.endkey = r));
}
o ||
("number" == typeof t.limit && (e.limit = t.limit),
(e.skip = s));
return f(await c(e));
}
})(e, t);
})();
}
async function j(t, n, o) {
if ("function" == typeof t._query)
return (function (e, t, n) {
return new Promise(function (r, o) {
e._query(t, n, function (e, t) {
if (e) return o(e);
r(t);
});
});
})(t, n, o);
if (y(t))
return (async function (e, t, n) {
let r,
o,
i = [],
s = "GET";
if (
(l("reduce", n, i),
l("include_docs", n, i),
l("attachments", n, i),
l("limit", n, i),
l("descending", n, i),
l("group", n, i),
l("group_level", n, i),
l("skip", n, i),
l("stale", n, i),
l("conflicts", n, i),
l("startkey", n, i, !0),
l("start_key", n, i, !0),
l("endkey", n, i, !0),
l("end_key", n, i, !0),
l("inclusive_end", n, i),
l("key", n, i, !0),
l("update_seq", n, i),
(i = i.join("&")),
(i = "" === i ? "" : "?" + i),
void 0 !== n.keys)
) {
const e = 2e3,
o = "keys=" + encodeURIComponent(JSON.stringify(n.keys));
o.length + i.length + 1 <= e
? (i += ("?" === i[0] ? "&" : "?") + o)
: ((s = "POST"),
"string" == typeof t
? (r = { keys: n.keys })
: (t.keys = n.keys));
}
if ("string" == typeof t) {
const u = je(t),
c = await e.fetch(
"_design/" + u[0] + "/_view/" + u[1] + i,
{
headers: new Y({ "Content-Type": "application/json" }),
method: s,
body: JSON.stringify(r),
}
);
o = c.ok;
const a = await c.json();
if (!o) throw ((a.status = c.status), d(a));
for (const e of a.rows)
if (
e.value &&
e.value.error &&
"builtin_reduce_error" === e.value.error
)
throw new Error(e.reason);
return new Promise(function (e) {
e(a);
}).then(f(n));
}
r = r || {};
for (const e of Object.keys(t))
Array.isArray(t[e])
? (r[e] = t[e])
: (r[e] = t[e].toString());
const u = await e.fetch("_temp_view" + i, {
headers: new Y({ "Content-Type": "application/json" }),
method: "POST",
body: JSON.stringify(r),
});
o = u.ok;
const c = await u.json();
if (!o) throw ((c.status = u.status), d(c));
return new Promise(function (e) {
e(c);
}).then(f(n));
})(t, n, o);
const i = {
changes_batch_size: t.__opts.view_update_changes_batch_size || 50,
};
if ("string" != typeof n)
return (
v(o, n),
ke.add(async function () {
const r = await ye(
t,
"temp_view/temp_view",
n.map,
n.reduce,
!0,
e
);
return (
(s = w(r, i).then(function () {
return k(r, o);
})),
(u = function () {
return r.db.destroy();
}),
s.then(
function (e) {
return u().then(function () {
return e;
});
},
function (e) {
return u().then(function () {
throw e;
});
}
)
);
var s, u;
}),
ke.finish()
);
{
const s = n,
u = je(s),
a = u[0],
f = u[1],
l = await t.get("_design/" + a);
if (!(n = l.views && l.views[f]))
throw new he(`ddoc ${l._id} has no view named ${f}`);
r(l, f), v(o, n);
const d = await ye(t, s, n.map, n.reduce, !1, e);
return "ok" === o.stale || "update_after" === o.stale
? ("update_after" === o.stale &&
c(function () {
w(d, i);
}),
k(d, o))
: (await w(d, i), k(d, o));
}
}
var $;
return {
query: function (e, t, n) {
const r = this;
"function" == typeof t && ((n = t), (t = {})),
(t = t
? (function (e) {
return (
(e.group_level = p(e.group_level)),
(e.limit = p(e.limit)),
(e.skip = p(e.skip)),
e
);
})(t)
: {}),
"function" == typeof e && (e = { map: e });
const o = Promise.resolve().then(function () {
return j(r, e, t);
});
return ge(o, n), o;
},
viewCleanup:
(($ = function () {
const t = this;
return "function" == typeof t._viewCleanup
? (function (e) {
return new Promise(function (t, n) {
e._viewCleanup(function (e, r) {
if (e) return n(e);
t(r);
});
});
})(t)
: y(t)
? (async function (e) {
return (
await e.fetch("_view_cleanup", {
headers: new Y({
"Content-Type": "application/json",
}),
method: "POST",
})
).json();
})(t)
: (async function (t) {
try {
const n = await t.get("_local/" + e),
r = new Map();
for (const e of Object.keys(n.views)) {
const t = je(e),
n = "_design/" + t[0],
o = t[1];
let i = r.get(n);
i || ((i = new Set()), r.set(n, i)), i.add(o);
}
const o = { keys: be(r), include_docs: !0 },
i = await t.allDocs(o),
s = {};
for (const e of i.rows) {
const t = e.key.substring(8);
for (const o of r.get(e.key)) {
let r = t + "/" + o;
n.views[r] || (r = o);
const i = Object.keys(n.views[r]),
u = e.doc && e.doc.views && e.doc.views[o];
for (const e of i) s[e] = s[e] || u;
}
}
const u = Object.keys(s)
.filter(function (e) {
return !s[e];
})
.map(function (e) {
return me(b(e), function () {
return new t.constructor(e, t.__opts).destroy();
})();
});
return Promise.all(u).then(function () {
return { ok: !0 };
});
} catch (e) {
if (404 === e.status) return { ok: !0 };
throw e;
}
})(t);
}),
function (...e) {
var t = e.pop(),
n = $.apply(this, e);
return "function" == typeof t && ge(n, t), n;
}),
};
})(
"indexes",
function (e, t) {
return Oe(Object.keys(e.fields), t, e.partial_filter_selector);
},
function () {
throw new Error("reduce not supported");
},
function (e, t) {
const n = e.views[t];
if (!n.map || !n.map.fields)
throw new Error(
"ddoc " +
e._id +
" with view " +
t +
" doesn't have map.fields defined. maybe it wasn't created by this plugin?"
);
}
);
function qe(e) {
return e._customFindAbstractMapper
? {
query: function (t, n) {
const r = Ae.query.bind(this);
return e._customFindAbstractMapper.query.call(this, t, n, r);
},
viewCleanup: function () {
const t = Ae.viewCleanup.bind(this);
return e._customFindAbstractMapper.viewCleanup.call(this, t);
},
}
: Ae;
}
const Me = /^_design\//;
function Ee(e) {
return (
(e.fields = e.fields.map(function (e) {
if ("string" == typeof e) {
const t = {};
return (t[e] = "asc"), t;
}
return e;
})),
e.partial_filter_selector &&
(e.partial_filter_selector = q(e.partial_filter_selector)),
e
);
}
function Se(e, t) {
return t.def.fields.map((t) => {
const n = x(t);
return _(e, k(n));
});
}
async function Be(e, t) {
const n = u((t = H(t)).index);
let r;
function o() {
return r || (r = m(JSON.stringify(t)));
}
(t.index = Ee(t.index)),
(function (e) {
const t = e.fields.filter(function (e) {
return "asc" === O(e);
});
if (0 !== t.length && t.length !== e.fields.length)
throw new Error("unsupported mixed sorting");
})(t.index);
const i = t.name || "idx-" + o(),
s = t.ddoc || "idx-" + o(),
c = "_design/" + s;
let a = !1,
f = !1;
if (
(e.constructor.emit("debug", ["find", "creating index", c]),
await p(e, c, function (e) {
return (
e._rev && "query" !== e.language && (a = !0),
(e.language = "query"),
(e.views = e.views || {}),
(f = !!e.views[i]),
!f &&
((e.views[i] = {
map: {
fields: K(t.index.fields),
partial_filter_selector: t.index.partial_filter_selector,
},
reduce: "_count",
options: { def: n },
}),
e)
);
}),
a)
)
throw new Error(
'invalid language for ddoc with id "' +
c +
'" (should be "query")'
);
const l = s + "/" + i;
return (
await qe(e).query.call(e, l, { limit: 0, reduce: !1 }),
{ id: c, name: i, result: f ? "exists" : "created" }
);
}
async function Pe(e) {
const t = await e.allDocs({
startkey: "_design/",
endkey: "_design/\uffff",
include_docs: !0,
}),
n = {
indexes: [
{
ddoc: null,
name: "_all_docs",
type: "special",
def: { fields: [{ _id: "asc" }] },
},
],
};
return (
(n.indexes = Q(
n.indexes,
t.rows
.filter(function (e) {
return "query" === e.doc.language;
})
.map(function (e) {
return (
void 0 !== e.doc.views ? Object.keys(e.doc.views) : []
).map(function (t) {
const n = e.doc.views[t];
return {
ddoc: e.id,
name: t,
type: "json",
def: Ee(n.options.def),
};
});
})
)),
n.indexes.sort(function (e, t) {
return w(e.name, t.name);
}),
(n.total_rows = n.indexes.length),
n
);
}
const Ie = { "\uffff": {} },
Ce = {
queryOpts: { limit: 0, startkey: Ie, endkey: null },
inMemoryFields: [],
};
function Le(e, t) {
return e.def.fields.some((e) => x(e) === t);
}
function Ue(e, t) {
return "$eq" !== x(e[t]);
}
function De(e, t) {
const n = t.def.fields.map(x);
return e.slice().sort(function (e, t) {
let r = n.indexOf(e),
o = n.indexOf(t);
return (
-1 === r && (r = Number.MAX_VALUE),
-1 === o && (o = Number.MAX_VALUE),
w(r, o)
);
});
}
function Ne(e, t, n, r) {
const o = Q(
e,
(function (e, t, n) {
let r = !1;
for (let o = 0, i = (n = De(n, e)).length; o < i; o++) {
const s = n[o];
if (r || !Le(e, s)) return n.slice(o);
o < i - 1 && Ue(t, s) && (r = !0);
}
return [];
})(t, n, r),
(function (e) {
const t = [];
for (const [n, r] of Object.entries(e))
for (const e of Object.keys(r)) "$ne" === e && t.push(n);
return t;
})(n)
);
return De(((i = o), Array.from(new Set(i))), t);
var i;
}
function Te(e, t, n) {
if (t) {
const i = ((o = e), !((r = t).length > o.length) && X(r, o)),
s = X(n, e);
return i && s;
}
var r, o;
return (function (e, t) {
e = e.slice();
for (const n of t) {
if (!e.length) break;
const t = e.indexOf(n);
if (-1 === t) return !1;
e.splice(t, 1);
}
return !0;
})(n, e);
}
const Fe = ["$eq", "$gt", "$gte", "$lt", "$lte"];
function Re(e) {
return -1 === Fe.indexOf(e);
}
function ze(e, t, n, r) {
const o = e.def.fields.map(x);
return (
!!Te(o, t, n) &&
(function (e, t) {
const n = t[e[0]];
return (
void 0 === n || !(1 === Object.keys(n).length && "$ne" === x(n))
);
})(o, r)
);
}
function Je(e, t, n, r, o) {
const i = (function (e, t, n, r) {
return r.filter(function (r) {
return ze(r, n, t, e);
});
})(e, t, n, r);
if (0 === i.length) {
if (o)
throw {
error: "no_usable_index",
message: "There is no index available for this selector.",
};
const e = r[0];
return (e.defaultUsed = !0), e;
}
if (1 === i.length && !o) return i[0];
const s = (function (e) {
const t = {};
for (const n of e) t[n] = !0;
return t;
})(t);
if (o) {
const e = "_design/" + o[0],
t = 2 === o.length && o[1],
n = i.find(function (n) {
return !(!t || n.ddoc !== e || t !== n.name) || n.ddoc === e;
});
if (!n)
throw {
error: "unknown_error",
message:
"Could not find that index or could not use that index for the query",
};
return n;
}
return (function (e, t) {
let n = null,
r = -1;
for (const o of e) {
const e = t(o);
e > r && ((r = e), (n = o));
}
return n;
})(i, function (e) {
const t = e.def.fields.map(x);
let n = 0;
for (const e of t) s[e] && n++;
return n;
});
}
function Ve(e, t) {
switch (e) {
case "$eq":
return { key: t };
case "$lte":
return { endkey: t };
case "$gte":
return { startkey: t };
case "$lt":
return { endkey: t, inclusive_end: !1 };
case "$gt":
return { startkey: t, inclusive_start: !1 };
}
return { startkey: null };
}
function Qe(e, t) {
switch (e) {
case "$eq":
return { startkey: t, endkey: t };
case "$lte":
return { endkey: t };
case "$gte":
return { startkey: t };
case "$lt":
return { endkey: t, inclusive_end: !1 };
case "$gt":
return { startkey: t, inclusive_start: !1 };
}
}
function Ke(e, t) {
return t.defaultUsed
? (function (e) {
return {
queryOpts: { startkey: null },
inMemoryFields: [Object.keys(e)],
};
})(e)
: 1 === t.def.fields.length
? (function (e, t) {
const n = x(t.def.fields[0]),
r = e[n] || {},
o = [],
i = Object.keys(r);
let s;
for (const e of i) {
Re(e) && o.push(n);
const t = Ve(e, r[e]);
s = s ? K([s, t]) : t;
}
return { queryOpts: s, inMemoryFields: o };
})(e, t)
: (function (e, t) {
const n = t.def.fields.map(x);
let r = [];
const o = [],
i = [];
let s, u;
function c(e) {
!1 !== s && o.push(null),
!1 !== u && i.push(Ie),
(r = n.slice(e));
}
for (let t = 0, r = n.length; t < r; t++) {
const r = e[n[t]];
if (!r || !Object.keys(r).length) {
c(t);
break;
}
if (Object.keys(r).some(Re)) {
c(t);
break;
}
if (t > 0) {
const o =
"$gt" in r || "$gte" in r || "$lt" in r || "$lte" in r,
i = Object.keys(e[n[t - 1]]),
s = G(i, ["$eq"]),
u = G(i, Object.keys(r));
if (o && !s && !u) {
c(t);
break;
}
}
const a = Object.keys(r);
let f = null;
for (const e of a) {
const t = Qe(e, r[e]);
f = f ? K([f, t]) : t;
}
o.push("startkey" in f ? f.startkey : null),
i.push("endkey" in f ? f.endkey : Ie),
"inclusive_start" in f && (s = f.inclusive_start),
"inclusive_end" in f && (u = f.inclusive_end);
}
const a = { startkey: o, endkey: i };
return (
void 0 !== s && (a.inclusive_start = s),
void 0 !== u && (a.inclusive_end = u),
{ queryOpts: a, inMemoryFields: r }
);
})(e, t);
}
function Xe(e, t) {
const n = e.selector,
r = e.sort;
if (
(function (e) {
return Object.keys(e)
.map(function (t) {
return e[t];
})
.some(function (e) {
return "object" == typeof e && 0 === Object.keys(e).length;
});
})(n)
)
return Object.assign({}, Ce, { index: t[0] });
const o = (function (e, t) {
const n = Object.keys(e),
r = t ? t.map(x) : [];
let o;
return (
(o = n.length >= r.length ? n : r),
0 === r.length
? { fields: o }
: ((o = o.sort(function (e, t) {
let n = r.indexOf(e);
-1 === n && (n = Number.MAX_VALUE);
let o = r.indexOf(t);
return (
-1 === o && (o = Number.MAX_VALUE),
n < o ? -1 : n > o ? 1 : 0
);
})),
{ fields: o, sortOrder: t.map(x) })
);
})(n, r),
i = o.fields,
s = Je(n, i, o.sortOrder, t, e.use_index),
u = Ke(n, s);
return {
queryOpts: u.queryOpts,
index: s,
inMemoryFields: Ne(u.inMemoryFields, s, n, i),
};
}
async function Ge(e, t, n) {
return "_all_docs" === n.name
? (async function (e, t) {
const n = u(t);
n.descending
? ("endkey" in n &&
"string" != typeof n.endkey &&
(n.endkey = ""),
"startkey" in n &&
"string" != typeof n.startkey &&
(n.limit = 0))
: ("startkey" in n &&
"string" != typeof n.startkey &&
(n.startkey = ""),
"endkey" in n &&
"string" != typeof n.endkey &&
(n.limit = 0)),
"key" in n && "string" != typeof n.key && (n.limit = 0),
n.limit > 0 &&
n.indexes_count &&
((n.original_limit = n.limit),
(n.limit += n.indexes_count));
const r = await e.allDocs(n);
return (
(r.rows = r.rows.filter(function (e) {
return !/^_design\//.test(e.id);
})),
n.original_limit && (n.limit = n.original_limit),
(r.rows = r.rows.slice(0, n.limit)),
r
);
})(e, t)
: qe(e).query.call(e, (r = n).ddoc.substring(8) + "/" + r.name, t);
var r;
}
async function We(e, t, n) {
t.selector && (oe(t.selector, !1), (t.selector = q(t.selector))),
t.sort &&
(t.sort = (function (e) {
if (!Array.isArray(e))
throw new Error("invalid sort json - should be an array");
return e.map(function (e) {
if ("string" == typeof e) {
const t = {};
return (t[e] = "asc"), t;
}
return e;
});
})(t.sort)),
t.use_index &&
(t.use_index = (function (e) {
let t = [];
return (
"string" == typeof e ? t.push(e) : (t = e),
t.map(function (e) {
return e.replace(Me, "");
})
);
})(t.use_index)),
"limit" in t || (t.limit = 25),
(function (e) {
if ("object" != typeof e.selector)
throw new Error("you must provide a selector when you find()");
})(t);
const r = await Pe(e);
e.constructor.emit("debug", ["find", "planning query", t]);
const o = Xe(t, r.indexes);
e.constructor.emit("debug", ["find", "query plan", o]);
const i = o.index;
!(function (e, t) {
if (t.defaultUsed && e.sort) {
const t = e.sort
.filter(function (e) {
return "_id" !== Object.keys(e)[0];
})
.map(function (e) {
return Object.keys(e)[0];
});
if (t.length > 0)
throw new Error(
'Cannot sort on field(s) "' +
t.join(",") +
'" when using the default index'
);
}
t.defaultUsed;
})(t, i);
let s = Object.assign(
{ include_docs: !0, reduce: !1, indexes_count: r.total_rows },
o.queryOpts
);
if ("startkey" in s && "endkey" in s && M(s.startkey, s.endkey) > 0)
return { docs: [] };
if (
(t.sort &&
"string" != typeof t.sort[0] &&
"desc" === O(t.sort[0]) &&
((s.descending = !0),
(s = (function (e) {
const t = u(e);
return (
delete t.startkey,
delete t.endkey,
delete t.inclusive_start,
delete t.inclusive_end,
"endkey" in e && (t.startkey = e.endkey),
"startkey" in e && (t.endkey = e.startkey),
"inclusive_start" in e &&
(t.inclusive_end = e.inclusive_start),
"inclusive_end" in e && (t.inclusive_start = e.inclusive_end),
t
);
})(s))),
o.inMemoryFields.length ||
((s.limit = t.limit), "skip" in t && (s.skip = t.skip)),
n)
)
return Promise.resolve(o, s);
const c = await Ge(e, s, i);
!1 === s.inclusive_start &&
(c.rows = (function (e, t, n) {
const r = n.def.fields;
let o = 0;
for (const i of e) {
let e = Se(i.doc, n);
if (1 === r.length) e = e[0];
else for (; e.length > t.length; ) e.pop();
if (Math.abs(M(e, t)) > 0) break;
++o;
}
return o > 0 ? e.slice(o) : e;
})(c.rows, s.startkey, i)),
o.inMemoryFields.length &&
(c.rows = L(c.rows, t, o.inMemoryFields));
const a = {
docs: c.rows.map(function (e) {
const n = e.doc;
return t.fields
? (function (e, t) {
const n = {};
for (const r of t) {
const t = k(r),
o = _(e, t);
void 0 !== o && b(n, t, o);
}
return n;
})(n, t.fields)
: n;
}),
};
return (
i.defaultUsed &&
(a.warning =
"No matching index found, create an index to optimize query time."),
a
);
}
async function Ye(e, t) {
const n = await We(e, t, !0);
return {
dbname: e.name,
index: n.index,
selector: t.selector,
range: {
start_key: n.queryOpts.startkey,
end_key: n.queryOpts.endkey,
},
opts: {
use_index: t.use_index || [],
bookmark: "nil",
limit: t.limit,
skip: t.skip,
sort: t.sort || {},
fields: t.fields,
conflicts: !1,
r: [49],
},
limit: t.limit,
skip: t.skip || 0,
fields: t.fields,
};
}
async function He(e, t) {
if (!t.ddoc)
throw new Error("you must supply an index.ddoc when deleting");
if (!t.name)
throw new Error("you must supply an index.name when deleting");
const n = t.ddoc,
r = t.name;
return (
await p(e, n, function (e) {
return 1 === Object.keys(e.views).length && e.views[r]
? { _id: n, _deleted: !0 }
: (delete e.views[r], e);
}),
await qe(e).viewCleanup.apply(e),
{ ok: !0 }
);
}
const Ze = {};
(Ze.createIndex = W(async function (e) {
if ("object" != typeof e)
throw new Error("you must provide an index to create");
return (y(this) ? se : Be)(this, e);
})),
(Ze.find = W(async function (e) {
if ("object" != typeof e)
throw new Error("you must provide search parameters to find()");
return (y(this) ? ue : We)(this, e);
})),
(Ze.explain = W(async function (e) {
if ("object" != typeof e)
throw new Error(
"you must provide search parameters to explain()"
);
return (y(this) ? ce : Ye)(this, e);
})),
(Ze.getIndexes = W(async function () {
return (y(this) ? ae : Pe)(this);
})),
(Ze.deleteIndex = W(async function (e) {
if ("object" != typeof e)
throw new Error("you must provide an index to delete");
return (y(this) ? fe : He)(this, e);
})),
"undefined" == typeof PouchDB
? a(
"error",
'pouchdb-find plugin error: Cannot find global "PouchDB" object! Did you remember to include pouchdb.js?'
)
: PouchDB.plugin(Ze);
},
{ events: 1, "spark-md5": 2, uuid: 3 },
],
},
{},
[18]
);
(function (f) {
var d,
e,
p = function () {
d = new (window.UAParser || exports.UAParser)().getResult();
e = new Detector();
return this;
};
p.prototype = {
getSoftwareVersion: function () {
return "0.1.11";
},
getBrowserData: function () {
return d;
},
getFingerprint: function () {
var b = d.ua,
c = this.getScreenPrint(),
a = this.getPlugins(),
g = this.getFonts(),
n = this.isLocalStorage(),
f = this.isSessionStorage(),
h = this.getTimeZone(),
u = this.getLanguage(),
m = this.getSystemLanguage(),
e = this.isCookie(),
C = this.getCanvasPrint();
return murmurhash3_32_gc(
b +
"|" +
c +
"|" +
a +
"|" +
g +
"|" +
n +
"|" +
f +
"|" +
h +
"|" +
u +
"|" +
m +
"|" +
e +
"|" +
C,
256
);
},
getCustomFingerprint: function () {
for (var b = "", c = 0; c < arguments.length; c++)
b += arguments[c] + "|";
return murmurhash3_32_gc(b, 256);
},
getUserAgent: function () {
return d.ua;
},
getUserAgentLowerCase: function () {
return d.ua.toLowerCase();
},
getBrowser: function () {
return d.browser.name;
},
getBrowserVersion: function () {
return d.browser.version;
},
getBrowserMajorVersion: function () {
return d.browser.major;
},
isIE: function () {
return /IE/i.test(d.browser.name);
},
isChrome: function () {
return /Chrome/i.test(d.browser.name);
},
isFirefox: function () {
return /Firefox/i.test(d.browser.name);
},
isSafari: function () {
return /Safari/i.test(d.browser.name);
},
isMobileSafari: function () {
return /Mobile\sSafari/i.test(d.browser.name);
},
isOpera: function () {
return /Opera/i.test(d.browser.name);
},
getEngine: function () {
return d.engine.name;
},
getEngineVersion: function () {
return d.engine.version;
},
getOS: function () {
return d.os.name;
},
getOSVersion: function () {
return d.os.version;
},
isWindows: function () {
return /Windows/i.test(d.os.name);
},
isMac: function () {
return /Mac/i.test(d.os.name);
},
isLinux: function () {
return /Linux/i.test(d.os.name);
},
isUbuntu: function () {
return /Ubuntu/i.test(d.os.name);
},
isSolaris: function () {
return /Solaris/i.test(d.os.name);
},
getDevice: function () {
return d.device.model;
},
getDeviceType: function () {
return d.device.type;
},
getDeviceVendor: function () {
return d.device.vendor;
},
getCPU: function () {
return d.cpu.architecture;
},
isMobile: function () {
var b = d.ua || navigator.vendor || window.opera;
return (
/(android|bb\d+|meego).+mobile|avantgo|bada\/|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|iris|kindle|lge |maemo|midp|mmp|mobile.+firefox|netfront|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)\/|plucker|pocket|psp|series(4|6)0|symbian|treo|up\.(browser|link)|vodafone|wap|windows (ce|phone)|xda|xiino/i.test(
b
) ||
/1207|6310|6590|3gso|4thp|50[1-6]i|770s|802s|a wa|abac|ac(er|oo|s\-)|ai(ko|rn)|al(av|ca|co)|amoi|an(ex|ny|yw)|aptu|ar(ch|go)|as(te|us)|attw|au(di|\-m|r |s )|avan|be(ck|ll|nq)|bi(lb|rd)|bl(ac|az)|br(e|v)w|bumb|bw\-(n|u)|c55\/|capi|ccwa|cdm\-|cell|chtm|cldc|cmd\-|co(mp|nd)|craw|da(it|ll|ng)|dbte|dc\-s|devi|dica|dmob|do(c|p)o|ds(12|\-d)|el(49|ai)|em(l2|ul)|er(ic|k0)|esl8|ez([4-7]0|os|wa|ze)|fetc|fly(\-|_)|g1 u|g560|gene|gf\-5|g\-mo|go(\.w|od)|gr(ad|un)|haie|hcit|hd\-(m|p|t)|hei\-|hi(pt|ta)|hp( i|ip)|hs\-c|ht(c(\-| |_|a|g|p|s|t)|tp)|hu(aw|tc)|i\-(20|go|ma)|i230|iac( |\-|\/)|ibro|idea|ig01|ikom|im1k|inno|ipaq|iris|ja(t|v)a|jbro|jemu|jigs|kddi|keji|kgt( |\/)|klon|kpt |kwc\-|kyo(c|k)|le(no|xi)|lg( g|\/(k|l|u)|50|54|\-[a-w])|libw|lynx|m1\-w|m3ga|m50\/|ma(te|ui|xo)|mc(01|21|ca)|m\-cr|me(rc|ri)|mi(o8|oa|ts)|mmef|mo(01|02|bi|de|do|t(\-| |o|v)|zz)|mt(50|p1|v )|mwbp|mywa|n10[0-2]|n20[2-3]|n30(0|2)|n50(0|2|5)|n7(0(0|1)|10)|ne((c|m)\-|on|tf|wf|wg|wt)|nok(6|i)|nzph|o2im|op(ti|wv)|oran|owg1|p800|pan(a|d|t)|pdxg|pg(13|\-([1-8]|c))|phil|pire|pl(ay|uc)|pn\-2|po(ck|rt|se)|prox|psio|pt\-g|qa\-a|qc(07|12|21|32|60|\-[2-7]|i\-)|qtek|r380|r600|raks|rim9|ro(ve|zo)|s55\/|sa(ge|ma|mm|ms|ny|va)|sc(01|h\-|oo|p\-)|sdk\/|se(c(\-|0|1)|47|mc|nd|ri)|sgh\-|shar|sie(\-|m)|sk\-0|sl(45|id)|sm(al|ar|b3|it|t5)|so(ft|ny)|sp(01|h\-|v\-|v )|sy(01|mb)|t2(18|50)|t6(00|10|18)|ta(gt|lk)|tcl\-|tdg\-|tel(i|m)|tim\-|t\-mo|to(pl|sh)|ts(70|m\-|m3|m5)|tx\-9|up(\.b|g1|si)|utst|v400|v750|veri|vi(rg|te)|vk(40|5[0-3]|\-v)|vm40|voda|vulc|vx(52|53|60|61|70|80|81|83|85|98)|w3c(\-| )|webc|whit|wi(g |nc|nw)|wmlb|wonu|x700|yas\-|your|zeto|zte\-/i.test(
b.substr(0, 4)
)
);
},
isMobileMajor: function () {
return (
this.isMobileAndroid() ||
this.isMobileBlackBerry() ||
this.isMobileIOS() ||
this.isMobileOpera() ||
this.isMobileWindows()
);
},
isMobileAndroid: function () {
return d.ua.match(/Android/i) ? !0 : !1;
},
isMobileOpera: function () {
return d.ua.match(/Opera Mini/i) ? !0 : !1;
},
isMobileWindows: function () {
return d.ua.match(/IEMobile/i) ? !0 : !1;
},
isMobileBlackBerry: function () {
return d.ua.match(/BlackBerry/i) ? !0 : !1;
},
isMobileIOS: function () {
return d.ua.match(/iPhone|iPad|iPod/i) ? !0 : !1;
},
isIphone: function () {
return d.ua.match(/iPhone/i) ? !0 : !1;
},
isIpad: function () {
return d.ua.match(/iPad/i) ? !0 : !1;
},
isIpod: function () {
return d.ua.match(/iPod/i) ? !0 : !1;
},
getScreenPrint: function () {
return (
"Current Resolution: " +
this.getCurrentResolution() +
", Available Resolution: " +
this.getAvailableResolution() +
", Color Depth: " +
this.getColorDepth() +
", Device XDPI: " +
this.getDeviceXDPI() +
", Device YDPI: " +
this.getDeviceYDPI()
);
},
getColorDepth: function () {
return screen.colorDepth;
},
getCurrentResolution: function () {
return screen.width + "x" + screen.height;
},
getAvailableResolution: function () {
return screen.availWidth + "x" + screen.availHeight;
},
getDeviceXDPI: function () {
return screen.deviceXDPI;
},
getDeviceYDPI: function () {
return screen.deviceYDPI;
},
getPlugins: function () {
for (var b = "", c = 0; c < navigator.plugins.length; c++)
b =
c == navigator.plugins.length - 1
? b + navigator.plugins[c].name
: b + (navigator.plugins[c].name + ", ");
return b;
},
isJava: function () {
return navigator.javaEnabled();
},
getJavaVersion: function () {
return deployJava.getJREs().toString();
},
isFlash: function () {
return navigator.plugins["Shockwave Flash"] ? !0 : !1;
},
getFlashVersion: function () {
return this.isFlash()
? ((objPlayerVersion = swfobject.getFlashPlayerVersion()),
objPlayerVersion.major +
"." +
objPlayerVersion.minor +
"." +
objPlayerVersion.release)
: "";
},
isSilverlight: function () {
return navigator.plugins["Silverlight Plug-In"] ? !0 : !1;
},
getSilverlightVersion: function () {
return this.isSilverlight()
? navigator.plugins["Silverlight Plug-In"].description
: "";
},
isMimeTypes: function () {
return navigator.mimeTypes.length ? !0 : !1;
},
getMimeTypes: function () {
for (var b = "", c = 0; c < navigator.mimeTypes.length; c++)
b =
c == navigator.mimeTypes.length - 1
? b + navigator.mimeTypes[c].description
: b + (navigator.mimeTypes[c].description + ", ");
return b;
},
isFont: function (b) {
return e.detect(b);
},
getFonts: function () {
for (
var b =
"Abadi MT Condensed Light;Adobe Fangsong Std;Adobe Hebrew;Adobe Ming Std;Agency FB;Aharoni;Andalus;Angsana New;AngsanaUPC;Aparajita;Arab;Arabic Transparent;Arabic Typesetting;Arial Baltic;Arial Black;Arial CE;Arial CYR;Arial Greek;Arial TUR;Arial;Batang;BatangChe;Bauhaus 93;Bell MT;Bitstream Vera Serif;Bodoni MT;Bookman Old Style;Braggadocio;Broadway;Browallia New;BrowalliaUPC;Calibri Light;Calibri;Californian FB;Cambria Math;Cambria;Candara;Castellar;Casual;Centaur;Century Gothic;Chalkduster;Colonna MT;Comic Sans MS;Consolas;Constantia;Copperplate Gothic Light;Corbel;Cordia New;CordiaUPC;Courier New Baltic;Courier New CE;Courier New CYR;Courier New Greek;Courier New TUR;Courier New;DFKai-SB;DaunPenh;David;DejaVu LGC Sans Mono;Desdemona;DilleniaUPC;DokChampa;Dotum;DotumChe;Ebrima;Engravers MT;Eras Bold ITC;Estrangelo Edessa;EucrosiaUPC;Euphemia;Eurostile;FangSong;Forte;FrankRuehl;Franklin Gothic Heavy;Franklin Gothic Medium;FreesiaUPC;French Script MT;Gabriola;Gautami;Georgia;Gigi;Gisha;Goudy Old Style;Gulim;GulimChe;GungSeo;Gungsuh;GungsuhChe;Haettenschweiler;Harrington;Hei S;HeiT;Heisei Kaku Gothic;Hiragino Sans GB;Impact;Informal Roman;IrisUPC;Iskoola Pota;JasmineUPC;KacstOne;KaiTi;Kalinga;Kartika;Khmer UI;Kino MT;KodchiangUPC;Kokila;Kozuka Gothic Pr6N;Lao UI;Latha;Leelawadee;Levenim MT;LilyUPC;Lohit Gujarati;Loma;Lucida Bright;Lucida Console;Lucida Fax;Lucida Sans Unicode;MS Gothic;MS Mincho;MS PGothic;MS PMincho;MS Reference Sans Serif;MS UI Gothic;MV Boli;Magneto;Malgun Gothic;Mangal;Marlett;Matura MT Script Capitals;Meiryo UI;Meiryo;Menlo;Microsoft Himalaya;Microsoft JhengHei;Microsoft New Tai Lue;Microsoft PhagsPa;Microsoft Sans Serif;Microsoft Tai Le;Microsoft Uighur;Microsoft YaHei;Microsoft Yi Baiti;MingLiU;MingLiU-ExtB;MingLiU_HKSCS;MingLiU_HKSCS-ExtB;Miriam Fixed;Miriam;Mongolian Baiti;MoolBoran;NSimSun;Narkisim;News Gothic MT;Niagara Solid;Nyala;PMingLiU;PMingLiU-ExtB;Palace Script MT;Palatino Linotype;Papyrus;Perpetua;Plantagenet Cherokee;Playbill;Prelude Bold;Prelude Condensed Bold;Prelude Condensed Medium;Prelude Medium;PreludeCompressedWGL Black;PreludeCompressedWGL Bold;PreludeCompressedWGL Light;PreludeCompressedWGL Medium;PreludeCondensedWGL Black;PreludeCondensedWGL Bold;PreludeCondensedWGL Light;PreludeCondensedWGL Medium;PreludeWGL Black;PreludeWGL Bold;PreludeWGL Light;PreludeWGL Medium;Raavi;Rachana;Rockwell;Rod;Sakkal Majalla;Sawasdee;Script MT Bold;Segoe Print;Segoe Script;Segoe UI Light;Segoe UI Semibold;Segoe UI Symbol;Segoe UI;Shonar Bangla;Showcard Gothic;Shruti;SimHei;SimSun;SimSun-ExtB;Simplified Arabic Fixed;Simplified Arabic;Snap ITC;Sylfaen;Symbol;Tahoma;Times New Roman Baltic;Times New Roman CE;Times New Roman CYR;Times New Roman Greek;Times New Roman TUR;Times New Roman;TlwgMono;Traditional Arabic;Trebuchet MS;Tunga;Tw Cen MT Condensed Extra Bold;Ubuntu;Umpush;Univers;Utopia;Utsaah;Vani;Verdana;Vijaya;Vladimir Script;Vrinda;Webdings;Wide Latin;Wingdings".split(
";"
),
c = "",
a = 0;
a < b.length;
a++
)
e.detect(b[a]) &&
(c = a == b.length - 1 ? c + b[a] : c + (b[a] + ", "));
return c;
},
isLocalStorage: function () {
try {
return !!f.localStorage;
} catch (b) {
return !0;
}
},
isSessionStorage: function () {
try {
return !!f.sessionStorage;
} catch (b) {
return !0;
}
},
isCookie: function () {
return navigator.cookieEnabled;
},
getTimeZone: function () {
return String(String(new Date()).split("(")[1]).split(")")[0];
},
getLanguage: function () {
return navigator.language;
},
getSystemLanguage: function () {
return navigator.systemLanguage;
},
isCanvas: function () {
var b = document.createElement("canvas");
try {
return !(!b.getContext || !b.getContext("2d"));
} catch (c) {
return !1;
}
},
getCanvasPrint: function () {
var b = document.createElement("canvas"),
c;
try {
c = b.getContext("2d");
} catch (a) {
return "";
}
c.textBaseline = "top";
c.font = "14px 'Arial'";
c.textBaseline = "alphabetic";
c.fillStyle = "#f60";
c.fillRect(125, 1, 62, 20);
c.fillStyle = "#069";
c.fillText("ClientJS,org <canvas> 1.0", 2, 15);
c.fillStyle = "rgba(102, 204, 0, 0.7)";
c.fillText("ClientJS,org <canvas> 1.0", 4, 17);
return b.toDataURL();
},
};
"object" === typeof module &&
"undefined" !== typeof exports &&
(module.exports = p);
f.ClientJS = p;
})(window);
var deployJava = (function () {
function f(a) {
c.debug && (console.log ? console.log(a) : alert(a));
}
function d(a) {
if (null == a || 0 == a.length) return "http://java.com/dt-redirect";
"&" == a.charAt(0) && (a = a.substring(1, a.length));
return "http://java.com/dt-redirect?" + a;
}
var e = ["id", "class", "title", "style"];
"classid codebase codetype data type archive declare standby height width usemap name tabindex align border hspace vspace"
.split(" ")
.concat(
e,
["lang", "dir"],
"onclick ondblclick onmousedown onmouseup onmouseover onmousemove onmouseout onkeypress onkeydown onkeyup".split(
" "
)
);
var p =
"codebase code name archive object width height alt align hspace vspace"
.split(" ")
.concat(e),
b;
try {
b =
-1 != document.location.protocol.indexOf("http")
? "//java.com/js/webstart.png"
: "http://java.com/js/webstart.png";
} catch (a) {
b = "http://java.com/js/webstart.png";
}
var c = {
debug: null,
version: "20120801",
firefoxJavaVersion: null,
myInterval: null,
preInstallJREList: null,
returnPage: null,
brand: null,
locale: null,
installType: null,
EAInstallEnabled: !1,
EarlyAccessURL: null,
oldMimeType: "application/npruntime-scriptable-plugin;DeploymentToolkit",
mimeType: "application/java-deployment-toolkit",
launchButtonPNG: b,
browserName: null,
browserName2: null,
getJREs: function () {
var a = [];
if (this.isPluginInstalled())
for (var g = this.getPlugin().jvms, b = 0; b < g.getLength(); b++)
a[b] = g.get(b).version;
else
(g = this.getBrowser()),
"MSIE" == g
? this.testUsingActiveX("1.7.0")
? (a[0] = "1.7.0")
: this.testUsingActiveX("1.6.0")
? (a[0] = "1.6.0")
: this.testUsingActiveX("1.5.0")
? (a[0] = "1.5.0")
: this.testUsingActiveX("1.4.2")
? (a[0] = "1.4.2")
: this.testForMSVM() && (a[0] = "1.1")
: "Netscape Family" == g &&
(this.getJPIVersionUsingMimeType(),
null != this.firefoxJavaVersion
? (a[0] = this.firefoxJavaVersion)
: this.testUsingMimeTypes("1.7")
? (a[0] = "1.7.0")
: this.testUsingMimeTypes("1.6")
? (a[0] = "1.6.0")
: this.testUsingMimeTypes("1.5")
? (a[0] = "1.5.0")
: this.testUsingMimeTypes("1.4.2")
? (a[0] = "1.4.2")
: "Safari" == this.browserName2 &&
(this.testUsingPluginsArray("1.7.0")
? (a[0] = "1.7.0")
: this.testUsingPluginsArray("1.6")
? (a[0] = "1.6.0")
: this.testUsingPluginsArray("1.5")
? (a[0] = "1.5.0")
: this.testUsingPluginsArray("1.4.2") && (a[0] = "1.4.2")));
if (this.debug)
for (b = 0; b < a.length; ++b)
f("[getJREs()] We claim to have detected Java SE " + a[b]);
return a;
},
installJRE: function (a, g) {
if (this.isPluginInstalled() && this.isAutoInstallEnabled(a)) {
var b = !1;
if (
(b = this.isCallbackSupported()
? this.getPlugin().installJRE(a, g)
: this.getPlugin().installJRE(a))
)
this.refresh(),
null != this.returnPage && (document.location = this.returnPage);
return b;
}
return this.installLatestJRE();
},
isAutoInstallEnabled: function (a) {
if (!this.isPluginInstalled()) return !1;
"undefined" == typeof a && (a = null);
if (
"MSIE" != deployJava.browserName ||
deployJava.compareVersionToPattern(
deployJava.getPlugin().version,
["10", "0", "0"],
!1,
!0
)
)
a = !0;
else if (null == a) a = !1;
else {
var g = "1.6.0_33+";
if (null == g || 0 == g.length) a = !0;
else {
var b = g.charAt(g.length - 1);
"+" != b &&
"*" != b &&
-1 != g.indexOf("_") &&
"_" != b &&
((g += "*"), (b = "*"));
g = g.substring(0, g.length - 1);
if (0 < g.length) {
var c = g.charAt(g.length - 1);
if ("." == c || "_" == c) g = g.substring(0, g.length - 1);
}
a = "*" == b ? 0 == a.indexOf(g) : "+" == b ? g <= a : !1;
}
a = !a;
}
return a;
},
isCallbackSupported: function () {
return (
this.isPluginInstalled() &&
this.compareVersionToPattern(
this.getPlugin().version,
["10", "2", "0"],
!1,
!0
)
);
},
installLatestJRE: function (a) {
if (this.isPluginInstalled() && this.isAutoInstallEnabled()) {
var g = !1;
if (
(g = this.isCallbackSupported()
? this.getPlugin().installLatestJRE(a)
: this.getPlugin().installLatestJRE())
)
this.refresh(),
null != this.returnPage && (document.location = this.returnPage);
return g;
}
a = this.getBrowser();
g = navigator.platform.toLowerCase();
if (
"true" == this.EAInstallEnabled &&
-1 != g.indexOf("win") &&
null != this.EarlyAccessURL
)
(this.preInstallJREList = this.getJREs()),
null != this.returnPage &&
(this.myInterval = setInterval("deployJava.poll()", 3e3)),
(location.href = this.EarlyAccessURL);
else {
if ("MSIE" == a) return this.IEInstall();
if ("Netscape Family" == a && -1 != g.indexOf("win32"))
return this.FFInstall();
location.href = d(
(null != this.returnPage ? "&returnPage=" + this.returnPage : "") +
(null != this.locale ? "&locale=" + this.locale : "") +
(null != this.brand ? "&brand=" + this.brand : "")
);
}
return !1;
},
runApplet: function (a, g, b) {
if ("undefined" == b || null == b) b = "1.1";
var c = b.match("^(\\d+)(?:\\.(\\d+)(?:\\.(\\d+)(?:_(\\d+))?)?)?$");
null == this.returnPage && (this.returnPage = document.location);
null != c
? "?" != this.getBrowser()
? this.versionCheck(b + "+")
? this.writeAppletTag(a, g)
: this.installJRE(b + "+") &&
(this.refresh(),
(location.href = document.location),
this.writeAppletTag(a, g))
: this.writeAppletTag(a, g)
: f(
"[runApplet()] Invalid minimumVersion argument to runApplet():" + b
);
},
writeAppletTag: function (a, g) {
var b = "<applet ",
c = "",
h = !0;
if (null == g || "object" != typeof g) g = {};
for (var d in a) {
var m;
a: {
m = d.toLowerCase();
for (var f = p.length, e = 0; e < f; e++)
if (p[e] === m) {
m = !0;
break a;
}
m = !1;
}
m
? ((b += " " + d + '="' + a[d] + '"'), "code" == d && (h = !1))
: (g[d] = a[d]);
}
d = !1;
for (var q in g) {
"codebase_lookup" == q && (d = !0);
if ("object" == q || "java_object" == q || "java_code" == q) h = !1;
c += '<param name="' + q + '" value="' + g[q] + '"/>';
}
d || (c += '<param name="codebase_lookup" value="false"/>');
h && (b += ' code="dummy"');
document.write(b + ">\n" + c + "\n</applet>");
},
versionCheck: function (a) {
var g = 0,
b = a.match(
"^(\\d+)(?:\\.(\\d+)(?:\\.(\\d+)(?:_(\\d+))?)?)?(\\*|\\+)?$"
);
if (null != b) {
for (var c = (a = !1), h = [], d = 1; d < b.length; ++d)
"string" == typeof b[d] && "" != b[d] && ((h[g] = b[d]), g++);
"+" == h[h.length - 1]
? ((c = !0), (a = !1), h.length--)
: "*" == h[h.length - 1]
? ((c = !1), (a = !0), h.length--)
: 4 > h.length && ((c = !1), (a = !0));
g = this.getJREs();
for (d = 0; d < g.length; ++d)
if (this.compareVersionToPattern(g[d], h, a, c)) return !0;
} else
(g = "Invalid versionPattern passed to versionCheck: " + a),
f("[versionCheck()] " + g),
alert(g);
return !1;
},
isWebStartInstalled: function (a) {
if ("?" == this.getBrowser()) return !0;
if ("undefined" == a || null == a) a = "1.4.2";
var b = !1;
null != a.match("^(\\d+)(?:\\.(\\d+)(?:\\.(\\d+)(?:_(\\d+))?)?)?$")
? (b = this.versionCheck(a + "+"))
: (f(
"[isWebStartInstaller()] Invalid minimumVersion argument to isWebStartInstalled(): " +
a
),
(b = this.versionCheck("1.4.2+")));
return b;
},
getJPIVersionUsingMimeType: function () {
for (var a = 0; a < navigator.mimeTypes.length; ++a) {
var b = navigator.mimeTypes[a].type.match(
/^application\/x-java-applet;jpi-version=(.*)$/
);
if (
null != b &&
((this.firefoxJavaVersion = b[1]), "Opera" != this.browserName2)
)
break;
}
},
launchWebStartApplication: function (a) {
navigator.userAgent.toLowerCase();
this.getJPIVersionUsingMimeType();
if (
0 == this.isWebStartInstalled("1.7.0") &&
(0 == this.installJRE("1.7.0+") ||
0 == this.isWebStartInstalled("1.7.0"))
)
return !1;
var b = null;
document.documentURI && (b = document.documentURI);
null == b && (b = document.URL);
var c = this.getBrowser(),
d;
"MSIE" == c
? (d =
'<object classid="clsid:8AD9C840-044E-11D1-B3E9-00805F499D93" width="0" height="0"><PARAM name="launchjnlp" value="' +
a +
'"><PARAM name="docbase" value="' +
b +
'"></object>')
: "Netscape Family" == c &&
(d =
'<embed type="application/x-java-applet;jpi-version=' +
this.firefoxJavaVersion +
'" width="0" height="0" launchjnlp="' +
a +
'"docbase="' +
b +
'" />');
"undefined" == document.body || null == document.body
? (document.write(d), (document.location = b))
: ((a = document.createElement("div")),
(a.id = "div1"),
(a.style.position = "relative"),
(a.style.left = "-10000px"),
(a.style.margin = "0px auto"),
(a.className = "dynamicDiv"),
(a.innerHTML = d),
document.body.appendChild(a));
},
createWebStartLaunchButtonEx: function (a, b) {
null == this.returnPage && (this.returnPage = a);
document.write(
'<a href="' +
("javascript:deployJava.launchWebStartApplication('" + a + "');") +
'" onMouseOver="window.status=\'\'; return true;"><img src="' +
this.launchButtonPNG +
'" border="0" /></a>'
);
},
createWebStartLaunchButton: function (a, b) {
null == this.returnPage && (this.returnPage = a);
document.write(
'<a href="' +
("javascript:if (!deployJava.isWebStartInstalled("" +
b +
"")) {if (deployJava.installLatestJRE()) {if (deployJava.launch("" +
a +
"")) {}}} else {if (deployJava.launch("" +
a +
"")) {}}") +
'" onMouseOver="window.status=\'\'; return true;"><img src="' +
this.launchButtonPNG +
'" border="0" /></a>'
);
},
launch: function (a) {
document.location = a;
return !0;
},
isPluginInstalled: function () {
var a = this.getPlugin();
return a && a.jvms ? !0 : !1;
},
isAutoUpdateEnabled: function () {
return this.isPluginInstalled()
? this.getPlugin().isAutoUpdateEnabled()
: !1;
},
setAutoUpdateEnabled: function () {
return this.isPluginInstalled()
? this.getPlugin().setAutoUpdateEnabled()
: !1;
},
setInstallerType: function (a) {
this.installType = a;
return this.isPluginInstalled()
? this.getPlugin().setInstallerType(a)
: !1;
},
setAdditionalPackages: function (a) {
return this.isPluginInstalled()
? this.getPlugin().setAdditionalPackages(a)
: !1;
},
setEarlyAccess: function (a) {
this.EAInstallEnabled = a;
},
isPlugin2: function () {
if (this.isPluginInstalled() && this.versionCheck("1.6.0_10+"))
try {
return this.getPlugin().isPlugin2();
} catch (a) {}
return !1;
},
allowPlugin: function () {
this.getBrowser();
return "Safari" != this.browserName2 && "Opera" != this.browserName2;
},
getPlugin: function () {
this.refresh();
var a = null;
this.allowPlugin() && (a = document.getElementById("deployJavaPlugin"));
return a;
},
compareVersionToPattern: function (a, b, c, d) {
if (void 0 == a || void 0 == b) return !1;
var h = a.match("^(\\d+)(?:\\.(\\d+)(?:\\.(\\d+)(?:_(\\d+))?)?)?$");
if (null != h) {
var f = 0;
a = [];
for (var m = 1; m < h.length; ++m)
"string" == typeof h[m] && "" != h[m] && ((a[f] = h[m]), f++);
h = Math.min(a.length, b.length);
if (d) {
for (m = 0; m < h; ++m) {
if (a[m] < b[m]) return !1;
if (a[m] > b[m]) break;
}
return !0;
}
for (m = 0; m < h; ++m) if (a[m] != b[m]) return !1;
return c ? !0 : a.length == b.length;
}
return !1;
},
getBrowser: function () {
if (null == this.browserName) {
var a = navigator.userAgent.toLowerCase();
f("[getBrowser()] navigator.userAgent.toLowerCase() -> " + a);
-1 != a.indexOf("msie") && -1 == a.indexOf("opera")
? (this.browserName2 = this.browserName = "MSIE")
: -1 != a.indexOf("iphone")
? ((this.browserName = "Netscape Family"),
(this.browserName2 = "iPhone"))
: -1 != a.indexOf("firefox") && -1 == a.indexOf("opera")
? ((this.browserName = "Netscape Family"),
(this.browserName2 = "Firefox"))
: -1 != a.indexOf("chrome")
? ((this.browserName = "Netscape Family"),
(this.browserName2 = "Chrome"))
: -1 != a.indexOf("safari")
? ((this.browserName = "Netscape Family"),
(this.browserName2 = "Safari"))
: -1 != a.indexOf("mozilla") && -1 == a.indexOf("opera")
? ((this.browserName = "Netscape Family"),
(this.browserName2 = "Other"))
: -1 != a.indexOf("opera")
? ((this.browserName = "Netscape Family"),
(this.browserName2 = "Opera"))
: ((this.browserName = "?"), (this.browserName2 = "unknown"));
f(
"[getBrowser()] Detected browser name:" +
this.browserName +
", " +
this.browserName2
);
}
return this.browserName;
},
testUsingActiveX: function (a) {
a = "JavaWebStart.isInstalled." + a + ".0";
if ("undefined" == typeof ActiveXObject || !ActiveXObject)
return (
f(
"[testUsingActiveX()] Browser claims to be IE, but no ActiveXObject object?"
),
!1
);
try {
return null != new ActiveXObject(a);
} catch (b) {
return !1;
}
},
testForMSVM: function () {
if ("undefined" != typeof oClientCaps) {
var a = oClientCaps.getComponentVersion(
"{08B0E5C0-4FCB-11CF-AAA5-00401C608500}",
"ComponentID"
);
return "" == a || "5,0,5000,0" == a ? !1 : !0;
}
return !1;
},
testUsingMimeTypes: function (a) {
if (!navigator.mimeTypes)
return (
f(
"[testUsingMimeTypes()] Browser claims to be Netscape family, but no mimeTypes[] array?"
),
!1
);
for (var b = 0; b < navigator.mimeTypes.length; ++b) {
s = navigator.mimeTypes[b].type;
var c = s.match(
/^application\/x-java-applet\x3Bversion=(1\.8|1\.7|1\.6|1\.5|1\.4\.2)$/
);
if (null != c && this.compareVersions(c[1], a)) return !0;
}
return !1;
},
testUsingPluginsArray: function (a) {
if (!navigator.plugins || !navigator.plugins.length) return !1;
for (
var b = navigator.platform.toLowerCase(), c = 0;
c < navigator.plugins.length;
++c
)
if (
((s = navigator.plugins[c].description),
-1 != s.search(/^Java Switchable Plug-in (Cocoa)/))
) {
if (this.compareVersions("1.5.0", a)) return !0;
} else if (
-1 != s.search(/^Java/) &&
-1 != b.indexOf("win") &&
(this.compareVersions("1.5.0", a) || this.compareVersions("1.6.0", a))
)
return !0;
return this.compareVersions("1.5.0", a) ? !0 : !1;
},
IEInstall: function () {
location.href = d(
(null != this.returnPage ? "&returnPage=" + this.returnPage : "") +
(null != this.locale ? "&locale=" + this.locale : "") +
(null != this.brand ? "&brand=" + this.brand : "")
);
return !1;
},
done: function (a, b) {},
FFInstall: function () {
location.href = d(
(null != this.returnPage ? "&returnPage=" + this.returnPage : "") +
(null != this.locale ? "&locale=" + this.locale : "") +
(null != this.brand ? "&brand=" + this.brand : "") +
(null != this.installType ? "&type=" + this.installType : "")
);
return !1;
},
compareVersions: function (a, b) {
for (var c = a.split("."), d = b.split("."), h = 0; h < c.length; ++h)
c[h] = Number(c[h]);
for (h = 0; h < d.length; ++h) d[h] = Number(d[h]);
2 == c.length && (c[2] = 0);
return c[0] > d[0]
? !0
: c[0] < d[0]
? !1
: c[1] > d[1]
? !0
: c[1] < d[1]
? !1
: c[2] > d[2]
? !0
: c[2] < d[2]
? !1
: !0;
},
enableAlerts: function () {
this.browserName = null;
this.debug = !0;
},
poll: function () {
this.refresh();
var a = this.getJREs();
0 == this.preInstallJREList.length &&
0 != a.length &&
(clearInterval(this.myInterval),
null != this.returnPage && (location.href = this.returnPage));
0 != this.preInstallJREList.length &&
0 != a.length &&
this.preInstallJREList[0] != a[0] &&
(clearInterval(this.myInterval),
null != this.returnPage && (location.href = this.returnPage));
},
writePluginTag: function () {
var a = this.getBrowser();
"MSIE" == a
? document.write(
'<object classid="clsid:CAFEEFAC-DEC7-0000-0001-ABCDEFFEDCBA" id="deployJavaPlugin" width="0" height="0"></object>'
)
: "Netscape Family" == a && this.allowPlugin() && this.writeEmbedTag();
},
refresh: function () {
navigator.plugins.refresh(!1);
"Netscape Family" == this.getBrowser() &&
this.allowPlugin() &&
null == document.getElementById("deployJavaPlugin") &&
this.writeEmbedTag();
},
writeEmbedTag: function () {
var a = !1;
if (null != navigator.mimeTypes) {
for (var b = 0; b < navigator.mimeTypes.length; b++)
navigator.mimeTypes[b].type == this.mimeType &&
navigator.mimeTypes[b].enabledPlugin &&
(document.write(
'<embed id="deployJavaPlugin" type="' +
this.mimeType +
'" hidden="true" />'
),
(a = !0));
if (!a)
for (b = 0; b < navigator.mimeTypes.length; b++)
navigator.mimeTypes[b].type == this.oldMimeType &&
navigator.mimeTypes[b].enabledPlugin &&
document.write(
'<embed id="deployJavaPlugin" type="' +
this.oldMimeType +
'" hidden="true" />'
);
}
},
};
c.writePluginTag();
if (null == c.locale) {
e = null;
if (null == e)
try {
e = navigator.userLanguage;
} catch (a) {}
if (null == e)
try {
e = navigator.systemLanguage;
} catch (a) {}
if (null == e)
try {
e = navigator.language;
} catch (a) {}
null != e && (e.replace("-", "_"), (c.locale = e));
}
return c;
})();
var Detector = function () {
var f = ["monospace", "sans-serif", "serif"],
d = document.getElementsByTagName("body")[0],
e = document.createElement("span");
e.style.fontSize = "72px";
e.innerHTML = "mmmmmmmmmmlli";
var p = {},
b = {},
c;
for (c in f)
(e.style.fontFamily = f[c]),
d.appendChild(e),
(p[f[c]] = e.offsetWidth),
(b[f[c]] = e.offsetHeight),
d.removeChild(e);
this.detect = function (a) {
var c = !1,
n;
for (n in f) {
e.style.fontFamily = a + "," + f[n];
d.appendChild(e);
var v = e.offsetWidth != p[f[n]] || e.offsetHeight != b[f[n]];
d.removeChild(e);
c = c || v;
}
return c;
};
};
function murmurhash3_32_gc(f, d) {
var e, p, b, c, a;
e = f.length & 3;
p = f.length - e;
b = d;
for (a = 0; a < p; )
(c =
(f.charCodeAt(a) & 255) |
((f.charCodeAt(++a) & 255) << 8) |
((f.charCodeAt(++a) & 255) << 16) |
((f.charCodeAt(++a) & 255) << 24)),
++a,
(c =
(3432918353 * (c & 65535) +
(((3432918353 * (c >>> 16)) & 65535) << 16)) &
4294967295),
(c = (c << 15) | (c >>> 17)),
(c =
(461845907 * (c & 65535) + (((461845907 * (c >>> 16)) & 65535) << 16)) &
4294967295),
(b ^= c),
(b = (b << 13) | (b >>> 19)),
(b = (5 * (b & 65535) + (((5 * (b >>> 16)) & 65535) << 16)) & 4294967295),
(b = (b & 65535) + 27492 + ((((b >>> 16) + 58964) & 65535) << 16));
c = 0;
switch (e) {
case 3:
c ^= (f.charCodeAt(a + 2) & 255) << 16;
case 2:
c ^= (f.charCodeAt(a + 1) & 255) << 8;
case 1:
(c ^= f.charCodeAt(a) & 255),
(c =
(3432918353 * (c & 65535) +
(((3432918353 * (c >>> 16)) & 65535) << 16)) &
4294967295),
(c = (c << 15) | (c >>> 17)),
(b ^=
(461845907 * (c & 65535) +
(((461845907 * (c >>> 16)) & 65535) << 16)) &
4294967295);
}
b ^= f.length;
b ^= b >>> 16;
b =
(2246822507 * (b & 65535) + (((2246822507 * (b >>> 16)) & 65535) << 16)) &
4294967295;
b ^= b >>> 13;
b =
(3266489909 * (b & 65535) + (((3266489909 * (b >>> 16)) & 65535) << 16)) &
4294967295;
return (b ^ (b >>> 16)) >>> 0;
}
var swfobject = (function () {
function f() {
if (!y) {
try {
var a = l
.getElementsByTagName("body")[0]
.appendChild(l.createElement("span"));
a.parentNode.removeChild(a);
} catch (b) {
return;
}
y = !0;
for (var a = F.length, c = 0; c < a; c++) F[c]();
}
}
function d(a) {
y ? a() : (F[F.length] = a);
}
function e(a) {
if ("undefined" != typeof r.addEventListener)
r.addEventListener("load", a, !1);
else if ("undefined" != typeof l.addEventListener)
l.addEventListener("load", a, !1);
else if ("undefined" != typeof r.attachEvent) B(r, "onload", a);
else if ("function" == typeof r.onload) {
var b = r.onload;
r.onload = function () {
b();
a();
};
} else r.onload = a;
}
function p() {
var a = l.getElementsByTagName("body")[0],
c = l.createElement("object");
c.setAttribute("type", "application/x-shockwave-flash");
var d = a.appendChild(c);
if (d) {
var g = 0;
(function () {
if ("undefined" != typeof d.GetVariable) {
var h = d.GetVariable("$version");
h &&
((h = h.split(" ")[1].split(",")),
(k.pv = [
parseInt(h[0], 10),
parseInt(h[1], 10),
parseInt(h[2], 10),
]));
} else if (10 > g) {
g++;
setTimeout(arguments.callee, 10);
return;
}
a.removeChild(c);
d = null;
b();
})();
} else b();
}
function b() {
var b = x.length;
if (0 < b)
for (var z = 0; z < b; z++) {
var d = x[z].id,
h = x[z].callbackFn,
f = { success: !1, id: d };
if (0 < k.pv[0]) {
var e = m(d);
if (e)
if (!C(x[z].swfVersion) || (k.wk && 312 > k.wk))
if (x[z].expressInstall && a()) {
f = {};
f.data = x[z].expressInstall;
f.width = e.getAttribute("width") || "0";
f.height = e.getAttribute("height") || "0";
e.getAttribute("class") &&
(f.styleclass = e.getAttribute("class"));
e.getAttribute("align") && (f.align = e.getAttribute("align"));
for (
var l = {},
e = e.getElementsByTagName("param"),
q = e.length,
u = 0;
u < q;
u++
)
"movie" != e[u].getAttribute("name").toLowerCase() &&
(l[e[u].getAttribute("name")] = e[u].getAttribute("value"));
g(f, l, d, h);
} else n(e), h && h(f);
else A(d, !0), h && ((f.success = !0), (f.ref = c(d)), h(f));
} else
A(d, !0),
h &&
((d = c(d)) &&
"undefined" != typeof d.SetVariable &&
((f.success = !0), (f.ref = d)),
h(f));
}
}
function c(a) {
var b = null;
(a = m(a)) &&
"OBJECT" == a.nodeName &&
("undefined" != typeof a.SetVariable
? (b = a)
: (a = a.getElementsByTagName("object")[0]) && (b = a));
return b;
}
function a() {
return !G && C("6.0.65") && (k.win || k.mac) && !(k.wk && 312 > k.wk);
}
function g(a, b, c, d) {
G = !0;
J = d || null;
L = { success: !1, id: c };
var g = m(c);
if (g) {
"OBJECT" == g.nodeName ? ((E = v(g)), (H = null)) : ((E = g), (H = c));
a.id = "SWFObjectExprInst";
if (
"undefined" == typeof a.width ||
(!/%$/.test(a.width) && 310 > parseInt(a.width, 10))
)
a.width = "310";
if (
"undefined" == typeof a.height ||
(!/%$/.test(a.height) && 137 > parseInt(a.height, 10))
)
a.height = "137";
l.title = l.title.slice(0, 47) + " - Flash Player Installation";
d = k.ie && k.win ? "ActiveX" : "PlugIn";
d =
"MMredirectURL=" +
r.location.toString().replace(/&/g, "%26") +
"&MMplayerType=" +
d +
"&MMdoctitle=" +
l.title;
b.flashvars =
"undefined" != typeof b.flashvars ? b.flashvars + ("&" + d) : d;
k.ie &&
k.win &&
4 != g.readyState &&
((d = l.createElement("div")),
(c += "SWFObjectNew"),
d.setAttribute("id", c),
g.parentNode.insertBefore(d, g),
(g.style.display = "none"),
(function () {
4 == g.readyState
? g.parentNode.removeChild(g)
: setTimeout(arguments.callee, 10);
})());
h(a, b, c);
}
}
function n(a) {
if (k.ie && k.win && 4 != a.readyState) {
var b = l.createElement("div");
a.parentNode.insertBefore(b, a);
b.parentNode.replaceChild(v(a), b);
a.style.display = "none";
(function () {
4 == a.readyState
? a.parentNode.removeChild(a)
: setTimeout(arguments.callee, 10);
})();
} else a.parentNode.replaceChild(v(a), a);
}
function v(a) {
var b = l.createElement("div");
if (k.win && k.ie) b.innerHTML = a.innerHTML;
else if ((a = a.getElementsByTagName("object")[0]))
if ((a = a.childNodes))
for (var c = a.length, d = 0; d < c; d++)
(1 == a[d].nodeType && "PARAM" == a[d].nodeName) ||
8 == a[d].nodeType ||
b.appendChild(a[d].cloneNode(!0));
return b;
}
function h(a, b, c) {
var d,
g = m(c);
if (k.wk && 312 > k.wk) return d;
if (g)
if (("undefined" == typeof a.id && (a.id = c), k.ie && k.win)) {
var h = "",
f;
for (f in a)
a[f] != Object.prototype[f] &&
("data" == f.toLowerCase()
? (b.movie = a[f])
: "styleclass" == f.toLowerCase()
? (h += ' class="' + a[f] + '"')
: "classid" != f.toLowerCase() &&
(h += " " + f + '="' + a[f] + '"'));
f = "";
for (var e in b)
b[e] != Object.prototype[e] &&
(f += '<param name="' + e + '" value="' + b[e] + '" />');
g.outerHTML =
'<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000"' +
h +
">" +
f +
"</object>";
I[I.length] = a.id;
d = m(a.id);
} else {
e = l.createElement("object");
e.setAttribute("type", "application/x-shockwave-flash");
for (var q in a)
a[q] != Object.prototype[q] &&
("styleclass" == q.toLowerCase()
? e.setAttribute("class", a[q])
: "classid" != q.toLowerCase() && e.setAttribute(q, a[q]));
for (h in b)
b[h] != Object.prototype[h] &&
"movie" != h.toLowerCase() &&
((a = e),
(f = h),
(q = b[h]),
(c = l.createElement("param")),
c.setAttribute("name", f),
c.setAttribute("value", q),
a.appendChild(c));
g.parentNode.replaceChild(e, g);
d = e;
}
return d;
}
function u(a) {
var b = m(a);
b &&
"OBJECT" == b.nodeName &&
(k.ie && k.win
? ((b.style.display = "none"),
(function () {
if (4 == b.readyState) {
var c = m(a);
if (c) {
for (var d in c) "function" == typeof c[d] && (c[d] = null);
c.parentNode.removeChild(c);
}
} else setTimeout(arguments.callee, 10);
})())
: b.parentNode.removeChild(b));
}
function m(a) {
var b = null;
try {
b = l.getElementById(a);
} catch (c) {}
return b;
}
function B(a, b, c) {
a.attachEvent(b, c);
D[D.length] = [a, b, c];
}
function C(a) {
var b = k.pv;
a = a.split(".");
a[0] = parseInt(a[0], 10);
a[1] = parseInt(a[1], 10) || 0;
a[2] = parseInt(a[2], 10) || 0;
return b[0] > a[0] ||
(b[0] == a[0] && b[1] > a[1]) ||
(b[0] == a[0] && b[1] == a[1] && b[2] >= a[2])
? !0
: !1;
}
function q(a, b, c, d) {
if (!k.ie || !k.mac) {
var h = l.getElementsByTagName("head")[0];
h &&
((c = c && "string" == typeof c ? c : "screen"),
d && (K = w = null),
(w && K == c) ||
((d = l.createElement("style")),
d.setAttribute("type", "text/css"),
d.setAttribute("media", c),
(w = h.appendChild(d)),
k.ie &&
k.win &&
"undefined" != typeof l.styleSheets &&
0 < l.styleSheets.length &&
(w = l.styleSheets[l.styleSheets.length - 1]),
(K = c)),
k.ie && k.win
? w && "object" == typeof w.addRule && w.addRule(a, b)
: w &&
"undefined" != typeof l.createTextNode &&
w.appendChild(l.createTextNode(a + " {" + b + "}")));
}
}
function A(a, b) {
if (M) {
var c = b ? "visible" : "hidden";
y && m(a) ? (m(a).style.visibility = c) : q("#" + a, "visibility:" + c);
}
}
function N(a) {
return null != /[\\\"<>\.;]/.exec(a) &&
"undefined" != typeof encodeURIComponent
? encodeURIComponent(a)
: a;
}
var r = window,
l = document,
t = navigator,
O = !1,
F = [
function () {
O ? p() : b();
},
],
x = [],
I = [],
D = [],
E,
H,
J,
L,
y = !1,
G = !1,
w,
K,
M = !0,
k = (function () {
var a =
"undefined" != typeof l.getElementById &&
"undefined" != typeof l.getElementsByTagName &&
"undefined" != typeof l.createElement,
b = t.userAgent.toLowerCase(),
c = t.platform.toLowerCase(),
d = c ? /win/.test(c) : /win/.test(b),
c = c ? /mac/.test(c) : /mac/.test(b),
b = /webkit/.test(b)
? parseFloat(b.replace(/^.*webkit\/(\d+(\.\d+)?).*$/, "$1"))
: !1,
h = !+"\v1",
g = [0, 0, 0],
f = null;
if (
"undefined" != typeof t.plugins &&
"object" == typeof t.plugins["Shockwave Flash"]
)
!(f = t.plugins["Shockwave Flash"].description) ||
("undefined" != typeof t.mimeTypes &&
t.mimeTypes["application/x-shockwave-flash"] &&
!t.mimeTypes["application/x-shockwave-flash"].enabledPlugin) ||
((O = !0),
(h = !1),
(f = f.replace(/^.*\s+(\S+\s+\S+$)/, "$1")),
(g[0] = parseInt(f.replace(/^(.*)\..*$/, "$1"), 10)),
(g[1] = parseInt(f.replace(/^.*\.(.*)\s.*$/, "$1"), 10)),
(g[2] = /[a-zA-Z]/.test(f)
? parseInt(f.replace(/^.*[a-zA-Z]+(.*)$/, "$1"), 10)
: 0));
else if ("undefined" != typeof r.ActiveXObject)
try {
var e = new ActiveXObject("ShockwaveFlash.ShockwaveFlash");
e &&
(f = e.GetVariable("$version")) &&
((h = !0),
(f = f.split(" ")[1].split(",")),
(g = [parseInt(f[0], 10), parseInt(f[1], 10), parseInt(f[2], 10)]));
} catch (m) {}
return { w3: a, pv: g, wk: b, ie: h, win: d, mac: c };
})();
(function () {
k.w3 &&
((("undefined" != typeof l.readyState && "complete" == l.readyState) ||
("undefined" == typeof l.readyState &&
(l.getElementsByTagName("body")[0] || l.body))) &&
f(),
y ||
("undefined" != typeof l.addEventListener &&
l.addEventListener("DOMContentLoaded", f, !1),
k.ie &&
k.win &&
(l.attachEvent("onreadystatechange", function () {
"complete" == l.readyState &&
(l.detachEvent("onreadystatechange", arguments.callee), f());
}),
r == top &&
(function () {
if (!y) {
try {
l.documentElement.doScroll("left");
} catch (a) {
setTimeout(arguments.callee, 0);
return;
}
f();
}
})()),
k.wk &&
(function () {
y ||
(/loaded|complete/.test(l.readyState)
? f()
: setTimeout(arguments.callee, 0));
})(),
e(f)));
})();
(function () {
k.ie &&
k.win &&
window.attachEvent("onunload", function () {
for (var a = D.length, b = 0; b < a; b++)
D[b][0].detachEvent(D[b][1], D[b][2]);
a = I.length;
for (b = 0; b < a; b++) u(I[b]);
for (var c in k) k[c] = null;
k = null;
for (var d in swfobject) swfobject[d] = null;
swfobject = null;
});
})();
return {
registerObject: function (a, b, c, d) {
if (k.w3 && a && b) {
var h = {};
h.id = a;
h.swfVersion = b;
h.expressInstall = c;
h.callbackFn = d;
x[x.length] = h;
A(a, !1);
} else d && d({ success: !1, id: a });
},
getObjectById: function (a) {
if (k.w3) return c(a);
},
embedSWF: function (b, c, f, e, m, q, l, u, p, r) {
var n = { success: !1, id: c };
k.w3 && !(k.wk && 312 > k.wk) && b && c && f && e && m
? (A(c, !1),
d(function () {
f += "";
e += "";
var d = {};
if (p && "object" === typeof p) for (var k in p) d[k] = p[k];
d.data = b;
d.width = f;
d.height = e;
k = {};
if (u && "object" === typeof u) for (var B in u) k[B] = u[B];
if (l && "object" === typeof l)
for (var t in l)
k.flashvars =
"undefined" != typeof k.flashvars
? k.flashvars + ("&" + t + "=" + l[t])
: t + "=" + l[t];
if (C(m))
(B = h(d, k, c)),
d.id == c && A(c, !0),
(n.success = !0),
(n.ref = B);
else {
if (q && a()) {
d.data = q;
g(d, k, c, r);
return;
}
A(c, !0);
}
r && r(n);
}))
: r && r(n);
},
switchOffAutoHideShow: function () {
M = !1;
},
ua: k,
getFlashPlayerVersion: function () {
return { major: k.pv[0], minor: k.pv[1], release: k.pv[2] };
},
hasFlashPlayerVersion: C,
createSWF: function (a, b, c) {
if (k.w3) return h(a, b, c);
},
showExpressInstall: function (b, c, d, h) {
k.w3 && a() && g(b, c, d, h);
},
removeSWF: function (a) {
k.w3 && u(a);
},
createCSS: function (a, b, c, d) {
k.w3 && q(a, b, c, d);
},
addDomLoadEvent: d,
addLoadEvent: e,
getQueryParamValue: function (a) {
var b = l.location.search || l.location.hash;
if (b) {
/\?/.test(b) && (b = b.split("?")[1]);
if (null == a) return N(b);
for (var b = b.split("&"), c = 0; c < b.length; c++)
if (b[c].substring(0, b[c].indexOf("=")) == a)
return N(b[c].substring(b[c].indexOf("=") + 1));
}
return "";
},
expressInstallCallback: function () {
if (G) {
var a = m("SWFObjectExprInst");
a &&
E &&
(a.parentNode.replaceChild(E, a),
H && (A(H, !0), k.ie && k.win && (E.style.display = "block")),
J && J(L));
G = !1;
}
},
};
})();
(function (f, d) {
var e = {
extend: function (a, b) {
for (var c in b)
-1 !== "browser cpu device engine os".indexOf(c) &&
0 === b[c].length % 2 &&
(a[c] = b[c].concat(a[c]));
return a;
},
has: function (a, b) {
return "string" === typeof a
? -1 !== b.toLowerCase().indexOf(a.toLowerCase())
: !1;
},
lowerize: function (a) {
return a.toLowerCase();
},
major: function (a) {
return "string" === typeof a ? a.split(".")[0] : d;
},
},
p = function () {
for (
var a, b = 0, c, f, g, e, p, n, r = arguments;
b < r.length && !p;
) {
var l = r[b],
t = r[b + 1];
if ("undefined" === typeof a)
for (g in ((a = {}), t))
t.hasOwnProperty(g) &&
((e = t[g]), "object" === typeof e ? (a[e[0]] = d) : (a[e] = d));
for (c = f = 0; c < l.length && !p; )
if ((p = l[c++].exec(this.getUA())))
for (g = 0; g < t.length; g++)
(n = p[++f]),
(e = t[g]),
"object" === typeof e && 0 < e.length
? 2 == e.length
? (a[e[0]] =
"function" == typeof e[1] ? e[1].call(this, n) : e[1])
: 3 == e.length
? (a[e[0]] =
"function" !== typeof e[1] || (e[1].exec && e[1].test)
? n
? n.replace(e[1], e[2])
: d
: n
? e[1].call(this, n, e[2])
: d)
: 4 == e.length &&
(a[e[0]] = n ? e[3].call(this, n.replace(e[1], e[2])) : d)
: (a[e] = n ? n : d);
b += 2;
}
return a;
},
b = function (a, b) {
for (var c in b)
if ("object" === typeof b[c] && 0 < b[c].length)
for (var f = 0; f < b[c].length; f++) {
if (e.has(b[c][f], a)) return "?" === c ? d : c;
}
else if (e.has(b[c], a)) return "?" === c ? d : c;
return a;
},
c = {
ME: "4.90",
"NT 3.11": "NT3.51",
"NT 4.0": "NT4.0",
2e3: "NT 5.0",
XP: ["NT 5.1", "NT 5.2"],
Vista: "NT 6.0",
7: "NT 6.1",
8: "NT 6.2",
8.1: "NT 6.3",
10: ["NT 6.4", "NT 10.0"],
RT: "ARM",
},
a = {
browser: [
[
/(opera\smini)\/([\w\.-]+)/i,
/(opera\s[mobiletab]+).+version\/([\w\.-]+)/i,
/(opera).+version\/([\w\.]+)/i,
/(opera)[\/\s]+([\w\.]+)/i,
],
["name", "version"],
[/\s(opr)\/([\w\.]+)/i],
[["name", "Opera"], "version"],
[
/(kindle)\/([\w\.]+)/i,
/(lunascape|maxthon|netfront|jasmine|blazer)[\/\s]?([\w\.]+)*/i,
/(avant\s|iemobile|slim|baidu)(?:browser)?[\/\s]?([\w\.]*)/i,
/(?:ms|\()(ie)\s([\w\.]+)/i,
/(rekonq)\/([\w\.]+)*/i,
/(chromium|flock|rockmelt|midori|epiphany|silk|skyfire|ovibrowser|bolt|iron|vivaldi|iridium|phantomjs)\/([\w\.-]+)/i,
],
["name", "version"],
[/(trident).+rv[:\s]([\w\.]+).+like\sgecko/i],
[["name", "IE"], "version"],
[/(edge)\/((\d+)?[\w\.]+)/i],
["name", "version"],
[/(yabrowser)\/([\w\.]+)/i],
[["name", "Yandex"], "version"],
[/(comodo_dragon)\/([\w\.]+)/i],
[["name", /_/g, " "], "version"],
[
/(chrome|omniweb|arora|[tizenoka]{5}\s?browser)\/v?([\w\.]+)/i,
/(qqbrowser)[\/\s]?([\w\.]+)/i,
],
["name", "version"],
[
/(uc\s?browser)[\/\s]?([\w\.]+)/i,
/ucweb.+(ucbrowser)[\/\s]?([\w\.]+)/i,
/JUC.+(ucweb)[\/\s]?([\w\.]+)/i,
],
[["name", "UCBrowser"], "version"],
[/(dolfin)\/([\w\.]+)/i],
[["name", "Dolphin"], "version"],
[/((?:android.+)crmo|crios)\/([\w\.]+)/i],
[["name", "Chrome"], "version"],
[/XiaoMi\/MiuiBrowser\/([\w\.]+)/i],
["version", ["name", "MIUI Browser"]],
[/android.+version\/([\w\.]+)\s+(?:mobile\s?safari|safari)/i],
["version", ["name", "Android Browser"]],
[/FBAV\/([\w\.]+);/i],
["version", ["name", "Facebook"]],
[/fxios\/([\w\.-]+)/i],
["version", ["name", "Firefox"]],
[/version\/([\w\.]+).+?mobile\/\w+\s(safari)/i],
["version", ["name", "Mobile Safari"]],
[/version\/([\w\.]+).+?(mobile\s?safari|safari)/i],
["version", "name"],
[/webkit.+?(mobile\s?safari|safari)(\/[\w\.]+)/i],
[
"name",
[
"version",
b,
{
"1.0": "/8",
1.2: "/1",
1.3: "/3",
"2.0": "/412",
"2.0.2": "/416",
"2.0.3": "/417",
"2.0.4": "/419",
"?": "/",
},
],
],
[/(konqueror)\/([\w\.]+)/i, /(webkit|khtml)\/([\w\.]+)/i],
["name", "version"],
[/(navigator|netscape)\/([\w\.-]+)/i],
[["name", "Netscape"], "version"],
[
/(swiftfox)/i,
/(icedragon|iceweasel|camino|chimera|fennec|maemo\sbrowser|minimo|conkeror)[\/\s]?([\w\.\+]+)/i,
/(firefox|seamonkey|k-meleon|icecat|iceape|firebird|phoenix)\/([\w\.-]+)/i,
/(mozilla)\/([\w\.]+).+rv\:.+gecko\/\d+/i,
/(polaris|lynx|dillo|icab|doris|amaya|w3m|netsurf|sleipnir)[\/\s]?([\w\.]+)/i,
/(links)\s\(([\w\.]+)/i,
/(gobrowser)\/?([\w\.]+)*/i,
/(ice\s?browser)\/v?([\w\._]+)/i,
/(mosaic)[\/\s]([\w\.]+)/i,
],
["name", "version"],
],
cpu: [
[/(?:(amd|x(?:(?:86|64)[_-])?|wow|win)64)[;\)]/i],
[["architecture", "amd64"]],
[/(ia32(?=;))/i],
[["architecture", e.lowerize]],
[/((?:i[346]|x)86)[;\)]/i],
[["architecture", "ia32"]],
[/windows\s(ce|mobile);\sppc;/i],
[["architecture", "arm"]],
[/((?:ppc|powerpc)(?:64)?)(?:\smac|;|\))/i],
[["architecture", /ower/, "", e.lowerize]],
[/(sun4\w)[;\)]/i],
[["architecture", "sparc"]],
[
/((?:avr32|ia64(?=;))|68k(?=\))|arm(?:64|(?=v\d+;))|(?=atmel\s)avr|(?:irix|mips|sparc)(?:64)?(?=;)|pa-risc)/i,
],
[["architecture", e.lowerize]],
],
device: [
[/\((ipad|playbook);[\w\s\);-]+(rim|apple)/i],
["model", "vendor", ["type", "tablet"]],
[/applecoremedia\/[\w\.]+ \((ipad)/],
["model", ["vendor", "Apple"], ["type", "tablet"]],
[/(apple\s{0,1}tv)/i],
[
["model", "Apple TV"],
["vendor", "Apple"],
],
[
/(archos)\s(gamepad2?)/i,
/(hp).+(touchpad)/i,
/(kindle)\/([\w\.]+)/i,
/\s(nook)[\w\s]+build\/(\w+)/i,
/(dell)\s(strea[kpr\s\d]*[\dko])/i,
],
["vendor", "model", ["type", "tablet"]],
[/(kf[A-z]+)\sbuild\/[\w\.]+.*silk\//i],
["model", ["vendor", "Amazon"], ["type", "tablet"]],
[/(sd|kf)[0349hijorstuw]+\sbuild\/[\w\.]+.*silk\//i],
[
["model", b, { "Fire Phone": ["SD", "KF"] }],
["vendor", "Amazon"],
["type", "mobile"],
],
[/\((ip[honed|\s\w*]+);.+(apple)/i],
["model", "vendor", ["type", "mobile"]],
[/\((ip[honed|\s\w*]+);/i],
["model", ["vendor", "Apple"], ["type", "mobile"]],
[
/(blackberry)[\s-]?(\w+)/i,
/(blackberry|benq|palm(?=\-)|sonyericsson|acer|asus|dell|huawei|meizu|motorola|polytron)[\s_-]?([\w-]+)*/i,
/(hp)\s([\w\s]+\w)/i,
/(asus)-?(\w+)/i,
],
["vendor", "model", ["type", "mobile"]],
[/\(bb10;\s(\w+)/i],
["model", ["vendor", "BlackBerry"], ["type", "mobile"]],
[/android.+(transfo[prime\s]{4,10}\s\w+|eeepc|slider\s\w+|nexus 7)/i],
["model", ["vendor", "Asus"], ["type", "tablet"]],
[/(sony)\s(tablet\s[ps])\sbuild\//i, /(sony)?(?:sgp.+)\sbuild\//i],
[
["vendor", "Sony"],
["model", "Xperia Tablet"],
["type", "tablet"],
],
[/(?:sony)?(?:(?:(?:c|d)\d{4})|(?:so[-l].+))\sbuild\//i],
[
["vendor", "Sony"],
["model", "Xperia Phone"],
["type", "mobile"],
],
[/\s(ouya)\s/i, /(nintendo)\s([wids3u]+)/i],
["vendor", "model", ["type", "console"]],
[/android.+;\s(shield)\sbuild/i],
["model", ["vendor", "Nvidia"], ["type", "console"]],
[/(playstation\s[34portablevi]+)/i],
["model", ["vendor", "Sony"], ["type", "console"]],
[/(sprint\s(\w+))/i],
[
["vendor", b, { HTC: "APA", Sprint: "Sprint" }],
["model", b, { "Evo Shift 4G": "7373KT" }],
["type", "mobile"],
],
[/(lenovo)\s?(S(?:5000|6000)+(?:[-][\w+]))/i],
["vendor", "model", ["type", "tablet"]],
[
/(htc)[;_\s-]+([\w\s]+(?=\))|\w+)*/i,
/(zte)-(\w+)*/i,
/(alcatel|geeksphone|huawei|lenovo|nexian|panasonic|(?=;\s)sony)[_\s-]?([\w-]+)*/i,
],
["vendor", ["model", /_/g, " "], ["type", "mobile"]],
[/(nexus\s9)/i],
["model", ["vendor", "HTC"], ["type", "tablet"]],
[/[\s\(;](xbox(?:\sone)?)[\s\);]/i],
["model", ["vendor", "Microsoft"], ["type", "console"]],
[/(kin\.[onetw]{3})/i],
[
["model", /\./g, " "],
["vendor", "Microsoft"],
["type", "mobile"],
],
[
/\s(milestone|droid(?:[2-4x]|\s(?:bionic|x2|pro|razr))?(:?\s4g)?)[\w\s]+build\//i,
/mot[\s-]?(\w+)*/i,
/(XT\d{3,4}) build\//i,
/(nexus\s[6])/i,
],
["model", ["vendor", "Motorola"], ["type", "mobile"]],
[/android.+\s(mz60\d|xoom[\s2]{0,2})\sbuild\//i],
["model", ["vendor", "Motorola"], ["type", "tablet"]],
[
/android.+((sch-i[89]0\d|shw-m380s|gt-p\d{4}|gt-n8000|sgh-t8[56]9|nexus 10))/i,
/((SM-T\w+))/i,
],
[["vendor", "Samsung"], "model", ["type", "tablet"]],
[
/((s[cgp]h-\w+|gt-\w+|galaxy\snexus|sm-n900))/i,
/(sam[sung]*)[\s-]*(\w+-?[\w-]*)*/i,
/sec-((sgh\w+))/i,
],
[["vendor", "Samsung"], "model", ["type", "mobile"]],
[/(samsung);smarttv/i],
["vendor", "model", ["type", "smarttv"]],
[/\(dtv[\);].+(aquos)/i],
["model", ["vendor", "Sharp"], ["type", "smarttv"]],
[/sie-(\w+)*/i],
["model", ["vendor", "Siemens"], ["type", "mobile"]],
[/(maemo|nokia).*(n900|lumia\s\d+)/i, /(nokia)[\s_-]?([\w-]+)*/i],
[["vendor", "Nokia"], "model", ["type", "mobile"]],
[/android\s3\.[\s\w;-]{10}(a\d{3})/i],
["model", ["vendor", "Acer"], ["type", "tablet"]],
[/android\s3\.[\s\w;-]{10}(lg?)-([06cv9]{3,4})/i],
[["vendor", "LG"], "model", ["type", "tablet"]],
[/(lg) netcast\.tv/i],
["vendor", "model", ["type", "smarttv"]],
[/(nexus\s[45])/i, /lg[e;\s\/-]+(\w+)*/i],
["model", ["vendor", "LG"], ["type", "mobile"]],
[/android.+(ideatab[a-z0-9\-\s]+)/i],
["model", ["vendor", "Lenovo"], ["type", "tablet"]],
[/linux;.+((jolla));/i],
["vendor", "model", ["type", "mobile"]],
[/((pebble))app\/[\d\.]+\s/i],
["vendor", "model", ["type", "wearable"]],
[/android.+;\s(glass)\s\d/i],
["model", ["vendor", "Google"], ["type", "wearable"]],
[
/android.+(\w+)\s+build\/hm\1/i,
/android.+(hm[\s\-_]*note?[\s_]*(?:\d\w)?)\s+build/i,
/android.+(mi[\s\-_]*(?:one|one[\s_]plus)?[\s_]*(?:\d\w)?)\s+build/i,
],
[
["model", /_/g, " "],
["vendor", "Xiaomi"],
["type", "mobile"],
],
[/\s(tablet)[;\/\s]/i, /\s(mobile)[;\/\s]/i],
[["type", e.lowerize], "vendor", "model"],
],
engine: [
[/windows.+\sedge\/([\w\.]+)/i],
["version", ["name", "EdgeHTML"]],
[
/(presto)\/([\w\.]+)/i,
/(webkit|trident|netfront|netsurf|amaya|lynx|w3m)\/([\w\.]+)/i,
/(khtml|tasman|links)[\/\s]\(?([\w\.]+)/i,
/(icab)[\/\s]([23]\.[\d\.]+)/i,
],
["name", "version"],
[/rv\:([\w\.]+).*(gecko)/i],
["version", "name"],
],
os: [
[/microsoft\s(windows)\s(vista|xp)/i],
["name", "version"],
[
/(windows)\snt\s6\.2;\s(arm)/i,
/(windows\sphone(?:\sos)*|windows\smobile|windows)[\s\/]?([ntce\d\.\s]+\w)/i,
],
["name", ["version", b, c]],
[/(win(?=3|9|n)|win\s9x\s)([nt\d\.]+)/i],
[
["name", "Windows"],
["version", b, c],
],
[/\((bb)(10);/i],
[["name", "BlackBerry"], "version"],
[
/(blackberry)\w*\/?([\w\.]+)*/i,
/(tizen)[\/\s]([\w\.]+)/i,
/(android|webos|palm\sos|qnx|bada|rim\stablet\sos|meego|contiki)[\/\s-]?([\w\.]+)*/i,
/linux;.+(sailfish);/i,
],
["name", "version"],
[/(symbian\s?os|symbos|s60(?=;))[\/\s-]?([\w\.]+)*/i],
[["name", "Symbian"], "version"],
[/\((series40);/i],
["name"],
[/mozilla.+\(mobile;.+gecko.+firefox/i],
[["name", "Firefox OS"], "version"],
[
/(nintendo|playstation)\s([wids34portablevu]+)/i,
/(mint)[\/\s\(]?(\w+)*/i,
/(mageia|vectorlinux)[;\s]/i,
/(joli|[kxln]?ubuntu|debian|[open]*suse|gentoo|(?=\s)arch|slackware|fedora|mandriva|centos|pclinuxos|redhat|zenwalk|linpus)[\/\s-]?([\w\.-]+)*/i,
/(hurd|linux)\s?([\w\.]+)*/i,
/(gnu)\s?([\w\.]+)*/i,
],
["name", "version"],
[/(cros)\s[\w]+\s([\w\.]+\w)/i],
[["name", "Chromium OS"], "version"],
[/(sunos)\s?([\w\.]+\d)*/i],
[["name", "Solaris"], "version"],
[/\s([frentopc-]{0,4}bsd|dragonfly)\s?([\w\.]+)*/i],
["name", "version"],
[/(ip[honead]+)(?:.*os\s([\w]+)*\slike\smac|;\sopera)/i],
[
["name", "iOS"],
["version", /_/g, "."],
],
[/(mac\sos\sx)\s?([\w\s\.]+\w)*/i, /(macintosh|mac(?=_powerpc)\s)/i],
[
["name", "Mac OS"],
["version", /_/g, "."],
],
[
/((?:open)?solaris)[\/\s-]?([\w\.]+)*/i,
/(haiku)\s(\w+)/i,
/(aix)\s((\d)(?=\.|\)|\s)[\w\.]*)*/i,
/(plan\s9|minix|beos|os\/2|amigaos|morphos|risc\sos|openvms)/i,
/(unix)\s?([\w\.]+)*/i,
],
["name", "version"],
],
},
g = function (b, c) {
if (!(this instanceof g)) return new g(b, c).getResult();
var d =
b ||
(f && f.navigator && f.navigator.userAgent
? f.navigator.userAgent
: ""),
n = c ? e.extend(a, c) : a;
this.getBrowser = function () {
var a = p.apply(this, n.browser);
a.major = e.major(a.version);
return a;
};
this.getCPU = function () {
return p.apply(this, n.cpu);
};
this.getDevice = function () {
return p.apply(this, n.device);
};
this.getEngine = function () {
return p.apply(this, n.engine);
};
this.getOS = function () {
return p.apply(this, n.os);
};
this.getResult = function () {
return {
ua: this.getUA(),
browser: this.getBrowser(),
engine: this.getEngine(),
os: this.getOS(),
device: this.getDevice(),
cpu: this.getCPU(),
};
};
this.getUA = function () {
return d;
};
this.setUA = function (a) {
d = a;
return this;
};
this.setUA(d);
return this;
};
g.VERSION = "0.7.10";
g.BROWSER = { NAME: "name", MAJOR: "major", VERSION: "version" };
g.CPU = { ARCHITECTURE: "architecture" };
g.DEVICE = {
MODEL: "model",
VENDOR: "vendor",
TYPE: "type",
CONSOLE: "console",
MOBILE: "mobile",
SMARTTV: "smarttv",
TABLET: "tablet",
WEARABLE: "wearable",
EMBEDDED: "embedded",
};
g.ENGINE = { NAME: "name", VERSION: "version" };
g.OS = { NAME: "name", VERSION: "version" };
"undefined" !== typeof exports
? ("undefined" !== typeof module &&
module.exports &&
(exports = module.exports = g),
(exports.UAParser = g))
: "function" === typeof define && define.amd
? define(function () {
return g;
})
: (f.UAParser = g);
var n = f.jQuery || f.Zepto;
if ("undefined" !== typeof n) {
var v = new g();
n.ua = v.getResult();
n.ua.get = function () {
return v.getUA();
};
n.ua.set = function (a) {
v.setUA(a);
a = v.getResult();
for (var b in a) n.ua[b] = a[b];
};
}
})("object" === typeof window ? window : this);
!(function (e, t) {
"use strict";
"undefined" != typeof window && "function" == typeof define && define.amd
? define(t)
: "undefined" != typeof module && module.exports
? (module.exports = t())
: e.exports
? (e.exports = t())
: (e.Fingerprint2 = t());
})(this, function () {
"use strict";
void 0 === Array.isArray &&
(Array.isArray = function (e) {
return "[object Array]" === Object.prototype.toString.call(e);
});
function d(e, t) {
(e = [e[0] >>> 16, 65535 & e[0], e[1] >>> 16, 65535 & e[1]]),
(t = [t[0] >>> 16, 65535 & t[0], t[1] >>> 16, 65535 & t[1]]);
var n = [0, 0, 0, 0];
return (
(n[3] += e[3] + t[3]),
(n[2] += n[3] >>> 16),
(n[3] &= 65535),
(n[2] += e[2] + t[2]),
(n[1] += n[2] >>> 16),
(n[2] &= 65535),
(n[1] += e[1] + t[1]),
(n[0] += n[1] >>> 16),
(n[1] &= 65535),
(n[0] += e[0] + t[0]),
(n[0] &= 65535),
[(n[0] << 16) | n[1], (n[2] << 16) | n[3]]
);
}
function f(e, t) {
(e = [e[0] >>> 16, 65535 & e[0], e[1] >>> 16, 65535 & e[1]]),
(t = [t[0] >>> 16, 65535 & t[0], t[1] >>> 16, 65535 & t[1]]);
var n = [0, 0, 0, 0];
return (
(n[3] += e[3] * t[3]),
(n[2] += n[3] >>> 16),
(n[3] &= 65535),
(n[2] += e[2] * t[3]),
(n[1] += n[2] >>> 16),
(n[2] &= 65535),
(n[2] += e[3] * t[2]),
(n[1] += n[2] >>> 16),
(n[2] &= 65535),
(n[1] += e[1] * t[3]),
(n[0] += n[1] >>> 16),
(n[1] &= 65535),
(n[1] += e[2] * t[2]),
(n[0] += n[1] >>> 16),
(n[1] &= 65535),
(n[1] += e[3] * t[1]),
(n[0] += n[1] >>> 16),
(n[1] &= 65535),
(n[0] += e[0] * t[3] + e[1] * t[2] + e[2] * t[1] + e[3] * t[0]),
(n[0] &= 65535),
[(n[0] << 16) | n[1], (n[2] << 16) | n[3]]
);
}
function g(e, t) {
return 32 === (t %= 64)
? [e[1], e[0]]
: t < 32
? [(e[0] << t) | (e[1] >>> (32 - t)), (e[1] << t) | (e[0] >>> (32 - t))]
: ((t -= 32),
[(e[1] << t) | (e[0] >>> (32 - t)), (e[0] << t) | (e[1] >>> (32 - t))]);
}
function h(e, t) {
return 0 === (t %= 64)
? e
: t < 32
? [(e[0] << t) | (e[1] >>> (32 - t)), e[1] << t]
: [e[1] << (t - 32), 0];
}
function m(e, t) {
return [e[0] ^ t[0], e[1] ^ t[1]];
}
function p(e) {
return (
(e = m(e, [0, e[0] >>> 1])),
(e = f(e, [4283543511, 3981806797])),
(e = m(e, [0, e[0] >>> 1])),
(e = f(e, [3301882366, 444984403])),
(e = m(e, [0, e[0] >>> 1]))
);
}
function l(e, t) {
t = t || 0;
for (
var n = (e = e || "").length % 16,
a = e.length - n,
r = [0, t],
i = [0, t],
o = [0, 0],
l = [0, 0],
s = [2277735313, 289559509],
c = [1291169091, 658871167],
u = 0;
u < a;
u += 16
)
(o = [
(255 & e.charCodeAt(u + 4)) |
((255 & e.charCodeAt(u + 5)) << 8) |
((255 & e.charCodeAt(u + 6)) << 16) |
((255 & e.charCodeAt(u + 7)) << 24),
(255 & e.charCodeAt(u)) |
((255 & e.charCodeAt(u + 1)) << 8) |
((255 & e.charCodeAt(u + 2)) << 16) |
((255 & e.charCodeAt(u + 3)) << 24),
]),
(l = [
(255 & e.charCodeAt(u + 12)) |
((255 & e.charCodeAt(u + 13)) << 8) |
((255 & e.charCodeAt(u + 14)) << 16) |
((255 & e.charCodeAt(u + 15)) << 24),
(255 & e.charCodeAt(u + 8)) |
((255 & e.charCodeAt(u + 9)) << 8) |
((255 & e.charCodeAt(u + 10)) << 16) |
((255 & e.charCodeAt(u + 11)) << 24),
]),
(o = f(o, s)),
(o = g(o, 31)),
(o = f(o, c)),
(r = m(r, o)),
(r = g(r, 27)),
(r = d(r, i)),
(r = d(f(r, [0, 5]), [0, 1390208809])),
(l = f(l, c)),
(l = g(l, 33)),
(l = f(l, s)),
(i = m(i, l)),
(i = g(i, 31)),
(i = d(i, r)),
(i = d(f(i, [0, 5]), [0, 944331445]));
switch (((o = [0, 0]), (l = [0, 0]), n)) {
case 15:
l = m(l, h([0, e.charCodeAt(u + 14)], 48));
case 14:
l = m(l, h([0, e.charCodeAt(u + 13)], 40));
case 13:
l = m(l, h([0, e.charCodeAt(u + 12)], 32));
case 12:
l = m(l, h([0, e.charCodeAt(u + 11)], 24));
case 11:
l = m(l, h([0, e.charCodeAt(u + 10)], 16));
case 10:
l = m(l, h([0, e.charCodeAt(u + 9)], 8));
case 9:
(l = m(l, [0, e.charCodeAt(u + 8)])),
(l = f(l, c)),
(l = g(l, 33)),
(l = f(l, s)),
(i = m(i, l));
case 8:
o = m(o, h([0, e.charCodeAt(u + 7)], 56));
case 7:
o = m(o, h([0, e.charCodeAt(u + 6)], 48));
case 6:
o = m(o, h([0, e.charCodeAt(u + 5)], 40));
case 5:
o = m(o, h([0, e.charCodeAt(u + 4)], 32));
case 4:
o = m(o, h([0, e.charCodeAt(u + 3)], 24));
case 3:
o = m(o, h([0, e.charCodeAt(u + 2)], 16));
case 2:
o = m(o, h([0, e.charCodeAt(u + 1)], 8));
case 1:
(o = m(o, [0, e.charCodeAt(u)])),
(o = f(o, s)),
(o = g(o, 31)),
(o = f(o, c)),
(r = m(r, o));
}
return (
(r = m(r, [0, e.length])),
(i = m(i, [0, e.length])),
(r = d(r, i)),
(i = d(i, r)),
(r = p(r)),
(i = p(i)),
(r = d(r, i)),
(i = d(i, r)),
("00000000" + (r[0] >>> 0).toString(16)).slice(-8) +
("00000000" + (r[1] >>> 0).toString(16)).slice(-8) +
("00000000" + (i[0] >>> 0).toString(16)).slice(-8) +
("00000000" + (i[1] >>> 0).toString(16)).slice(-8)
);
}
function c(e, t) {
if (Array.prototype.forEach && e.forEach === Array.prototype.forEach)
e.forEach(t);
else if (e.length === +e.length)
for (var n = 0, a = e.length; n < a; n++) t(e[n], n, e);
else for (var r in e) e.hasOwnProperty(r) && t(e[r], r, e);
}
function s(e, a) {
var r = [];
return null == e
? r
: Array.prototype.map && e.map === Array.prototype.map
? e.map(a)
: (c(e, function (e, t, n) {
r.push(a(e, t, n));
}),
r);
}
function a(e) {
throw new Error(
"'new Fingerprint()' is deprecated, see https://github.com/fingerprintjs/fingerprintjs#upgrade-guide-from-182-to-200"
);
}
var e = {
preprocessor: null,
audio: { timeout: 1e3, excludeIOS11: !0 },
fonts: {
swfContainerId: "fingerprintjs2",
swfPath: "flash/compiled/FontList.swf",
userDefinedFonts: [],
extendedJsFonts: !1,
},
screen: { detectScreenOrientation: !0 },
plugins: { sortPluginsFor: [/palemoon/i], excludeIE: !1 },
extraComponents: [],
excludes: {
enumerateDevices: !0,
pixelRatio: !0,
doNotTrack: !0,
fontsFlash: !0,
adBlock: !0,
},
NOT_AVAILABLE: "not available",
ERROR: "error",
EXCLUDED: "excluded",
},
n = function () {
return navigator.mediaDevices && navigator.mediaDevices.enumerateDevices;
},
r = function (e) {
var t = [window.screen.width, window.screen.height];
return e.screen.detectScreenOrientation && t.sort().reverse(), t;
},
i = function (e) {
if (window.screen.availWidth && window.screen.availHeight) {
var t = [window.screen.availHeight, window.screen.availWidth];
return e.screen.detectScreenOrientation && t.sort().reverse(), t;
}
return e.NOT_AVAILABLE;
},
o = function (e) {
if (null == navigator.plugins) return e.NOT_AVAILABLE;
for (var t = [], n = 0, a = navigator.plugins.length; n < a; n++)
navigator.plugins[n] && t.push(navigator.plugins[n]);
return (
T(e) &&
(t = t.sort(function (e, t) {
return e.name > t.name ? 1 : e.name < t.name ? -1 : 0;
})),
s(t, function (e) {
var t = s(e, function (e) {
return [e.type, e.suffixes];
});
return [e.name, e.description, t];
})
);
},
u = function (t) {
var e = [];
return (
(Object.getOwnPropertyDescriptor &&
Object.getOwnPropertyDescriptor(window, "ActiveXObject")) ||
"ActiveXObject" in window
? (e = s(
[
"AcroPDF.PDF",
"Adodb.Stream",
"AgControl.AgControl",
"DevalVRXCtrl.DevalVRXCtrl.1",
"MacromediaFlashPaper.MacromediaFlashPaper",
"Msxml2.DOMDocument",
"Msxml2.XMLHTTP",
"PDF.PdfCtrl",
"QuickTime.QuickTime",
"QuickTimeCheckObject.QuickTimeCheck.1",
"RealPlayer",
"RealPlayer.RealPlayer(tm) ActiveX Control (32-bit)",
"RealVideo.RealVideo(tm) ActiveX Control (32-bit)",
"Scripting.Dictionary",
"SWCtl.SWCtl",
"Shell.UIHelper",
"ShockwaveFlash.ShockwaveFlash",
"Skype.Detection",
"TDCCtl.TDCCtl",
"WMPlayer.OCX",
"rmocx.RealPlayer G2 Control",
"rmocx.RealPlayer G2 Control.1",
],
function (e) {
try {
return new window.ActiveXObject(e), e;
} catch (e) {
return t.ERROR;
}
}
))
: e.push(t.NOT_AVAILABLE),
navigator.plugins && (e = e.concat(o(t))),
e
);
},
T = function (e) {
for (var t = !1, n = 0, a = e.plugins.sortPluginsFor.length; n < a; n++) {
var r = e.plugins.sortPluginsFor[n];
if (navigator.userAgent.match(r)) {
t = !0;
break;
}
}
return t;
},
A = function (t) {
try {
return !!window.sessionStorage;
} catch (e) {
return t.ERROR;
}
},
v = function (t) {
try {
return !!window.localStorage;
} catch (e) {
return t.ERROR;
}
},
S = function (t) {
if (N()) return t.EXCLUDED;
try {
return !!window.indexedDB;
} catch (e) {
return t.ERROR;
}
},
C = function (e) {
return navigator.hardwareConcurrency
? navigator.hardwareConcurrency
: e.NOT_AVAILABLE;
},
w = function (e) {
return navigator.cpuClass || e.NOT_AVAILABLE;
},
B = function (e) {
return navigator.platform ? navigator.platform : e.NOT_AVAILABLE;
},
y = function (e) {
return navigator.doNotTrack
? navigator.doNotTrack
: navigator.msDoNotTrack
? navigator.msDoNotTrack
: window.doNotTrack
? window.doNotTrack
: e.NOT_AVAILABLE;
},
t = function () {
var t,
e = 0;
void 0 !== navigator.maxTouchPoints
? (e = navigator.maxTouchPoints)
: void 0 !== navigator.msMaxTouchPoints &&
(e = navigator.msMaxTouchPoints);
try {
document.createEvent("TouchEvent"), (t = !0);
} catch (e) {
t = !1;
}
return [e, t, "ontouchstart" in window];
},
E = function (e) {
var t = [],
n = document.createElement("canvas");
(n.width = 2e3), (n.height = 200), (n.style.display = "inline");
var a = n.getContext("2d");
return (
a.rect(0, 0, 10, 10),
a.rect(2, 2, 6, 6),
t.push(
"canvas winding:" +
(!1 === a.isPointInPath(5, 5, "evenodd") ? "yes" : "no")
),
(a.textBaseline = "alphabetic"),
(a.fillStyle = "#f60"),
a.fillRect(125, 1, 62, 20),
(a.fillStyle = "#069"),
e.dontUseFakeFontInCanvas
? (a.font = "11pt Arial")
: (a.font = "11pt no-real-font-123"),
a.fillText("Cwm fjordbank glyphs vext quiz, 😃", 2, 15),
(a.fillStyle = "rgba(102, 204, 0, 0.2)"),
(a.font = "18pt Arial"),
a.fillText("Cwm fjordbank glyphs vext quiz, 😃", 4, 45),
(a.globalCompositeOperation = "multiply"),
(a.fillStyle = "rgb(255,0,255)"),
a.beginPath(),
a.arc(50, 50, 50, 0, 2 * Math.PI, !0),
a.closePath(),
a.fill(),
(a.fillStyle = "rgb(0,255,255)"),
a.beginPath(),
a.arc(100, 50, 50, 0, 2 * Math.PI, !0),
a.closePath(),
a.fill(),
(a.fillStyle = "rgb(255,255,0)"),
a.beginPath(),
a.arc(75, 100, 50, 0, 2 * Math.PI, !0),
a.closePath(),
a.fill(),
(a.fillStyle = "rgb(255,0,255)"),
a.arc(75, 75, 75, 0, 2 * Math.PI, !0),
a.arc(75, 75, 25, 0, 2 * Math.PI, !0),
a.fill("evenodd"),
n.toDataURL && t.push("canvas fp:" + n.toDataURL()),
t
);
},
x = function () {
function e(e) {
return (
o.clearColor(0, 0, 0, 1),
o.enable(o.DEPTH_TEST),
o.depthFunc(o.LEQUAL),
o.clear(o.COLOR_BUFFER_BIT | o.DEPTH_BUFFER_BIT),
"[" + e[0] + ", " + e[1] + "]"
);
}
var o = U();
if (!o) return null;
var l = [],
t = o.createBuffer();
o.bindBuffer(o.ARRAY_BUFFER, t);
var n = new Float32Array([
-0.2, -0.9, 0, 0.4, -0.26, 0, 0, 0.732134444, 0,
]);
o.bufferData(o.ARRAY_BUFFER, n, o.STATIC_DRAW),
(t.itemSize = 3),
(t.numItems = 3);
var a = o.createProgram(),
r = o.createShader(o.VERTEX_SHADER);
o.shaderSource(
r,
"attribute vec2 attrVertex;varying vec2 varyinTexCoordinate;uniform vec2 uniformOffset;void main(){varyinTexCoordinate=attrVertex+uniformOffset;gl_Position=vec4(attrVertex,0,1);}"
),
o.compileShader(r);
var i = o.createShader(o.FRAGMENT_SHADER);
o.shaderSource(
i,
"precision mediump float;varying vec2 varyinTexCoordinate;void main() {gl_FragColor=vec4(varyinTexCoordinate,0,1);}"
),
o.compileShader(i),
o.attachShader(a, r),
o.attachShader(a, i),
o.linkProgram(a),
o.useProgram(a),
(a.vertexPosAttrib = o.getAttribLocation(a, "attrVertex")),
(a.offsetUniform = o.getUniformLocation(a, "uniformOffset")),
o.enableVertexAttribArray(a.vertexPosArray),
o.vertexAttribPointer(a.vertexPosAttrib, t.itemSize, o.FLOAT, !1, 0, 0),
o.uniform2f(a.offsetUniform, 1, 1),
o.drawArrays(o.TRIANGLE_STRIP, 0, t.numItems);
try {
l.push(o.canvas.toDataURL());
} catch (e) {}
l.push("extensions:" + (o.getSupportedExtensions() || []).join(";")),
l.push(
"webgl aliased line width range:" +
e(o.getParameter(o.ALIASED_LINE_WIDTH_RANGE))
),
l.push(
"webgl aliased point size range:" +
e(o.getParameter(o.ALIASED_POINT_SIZE_RANGE))
),
l.push("webgl alpha bits:" + o.getParameter(o.ALPHA_BITS)),
l.push(
"webgl antialiasing:" +
(o.getContextAttributes().antialias ? "yes" : "no")
),
l.push("webgl blue bits:" + o.getParameter(o.BLUE_BITS)),
l.push("webgl depth bits:" + o.getParameter(o.DEPTH_BITS)),
l.push("webgl green bits:" + o.getParameter(o.GREEN_BITS)),
l.push(
"webgl max anisotropy:" +
(function (e) {
var t =
e.getExtension("EXT_texture_filter_anisotropic") ||
e.getExtension("WEBKIT_EXT_texture_filter_anisotropic") ||
e.getExtension("MOZ_EXT_texture_filter_anisotropic");
if (t) {
var n = e.getParameter(t.MAX_TEXTURE_MAX_ANISOTROPY_EXT);
return 0 === n && (n = 2), n;
}
return null;
})(o)
),
l.push(
"webgl max combined texture image units:" +
o.getParameter(o.MAX_COMBINED_TEXTURE_IMAGE_UNITS)
),
l.push(
"webgl max cube map texture size:" +
o.getParameter(o.MAX_CUBE_MAP_TEXTURE_SIZE)
),
l.push(
"webgl max fragment uniform vectors:" +
o.getParameter(o.MAX_FRAGMENT_UNIFORM_VECTORS)
),
l.push(
"webgl max render buffer size:" +
o.getParameter(o.MAX_RENDERBUFFER_SIZE)
),
l.push(
"webgl max texture image units:" +
o.getParameter(o.MAX_TEXTURE_IMAGE_UNITS)
),
l.push("webgl max texture size:" + o.getParameter(o.MAX_TEXTURE_SIZE)),
l.push(
"webgl max varying vectors:" + o.getParameter(o.MAX_VARYING_VECTORS)
),
l.push(
"webgl max vertex attribs:" + o.getParameter(o.MAX_VERTEX_ATTRIBS)
),
l.push(
"webgl max vertex texture image units:" +
o.getParameter(o.MAX_VERTEX_TEXTURE_IMAGE_UNITS)
),
l.push(
"webgl max vertex uniform vectors:" +
o.getParameter(o.MAX_VERTEX_UNIFORM_VECTORS)
),
l.push(
"webgl max viewport dims:" + e(o.getParameter(o.MAX_VIEWPORT_DIMS))
),
l.push("webgl red bits:" + o.getParameter(o.RED_BITS)),
l.push("webgl renderer:" + o.getParameter(o.RENDERER)),
l.push(
"webgl shading language version:" +
o.getParameter(o.SHADING_LANGUAGE_VERSION)
),
l.push("webgl stencil bits:" + o.getParameter(o.STENCIL_BITS)),
l.push("webgl vendor:" + o.getParameter(o.VENDOR)),
l.push("webgl version:" + o.getParameter(o.VERSION));
try {
var s = o.getExtension("WEBGL_debug_renderer_info");
s &&
(l.push(
"webgl unmasked vendor:" + o.getParameter(s.UNMASKED_VENDOR_WEBGL)
),
l.push(
"webgl unmasked renderer:" +
o.getParameter(s.UNMASKED_RENDERER_WEBGL)
));
} catch (e) {}
return (
o.getShaderPrecisionFormat &&
c(["FLOAT", "INT"], function (i) {
c(["VERTEX", "FRAGMENT"], function (r) {
c(["HIGH", "MEDIUM", "LOW"], function (a) {
c(["precision", "rangeMin", "rangeMax"], function (e) {
var t = o.getShaderPrecisionFormat(
o[r + "_SHADER"],
o[a + "_" + i]
)[e];
"precision" !== e && (e = "precision " + e);
var n = [
"webgl ",
r.toLowerCase(),
" shader ",
a.toLowerCase(),
" ",
i.toLowerCase(),
" ",
e,
":",
t,
].join("");
l.push(n);
});
});
});
}),
V(o),
l
);
},
O = function () {
try {
var e = U(),
t = e.getExtension("WEBGL_debug_renderer_info"),
n =
e.getParameter(t.UNMASKED_VENDOR_WEBGL) +
"~" +
e.getParameter(t.UNMASKED_RENDERER_WEBGL);
return V(e), n;
} catch (e) {
return null;
}
},
M = function () {
var e = document.createElement("div");
e.innerHTML = " ";
var t = !(e.className = "adsbox");
try {
document.body.appendChild(e),
(t = 0 === document.getElementsByClassName("adsbox")[0].offsetHeight),
document.body.removeChild(e);
} catch (e) {
t = !1;
}
return t;
},
P = function () {
if (void 0 !== navigator.languages)
try {
if (
navigator.languages[0].substr(0, 2) !==
navigator.language.substr(0, 2)
)
return !0;
} catch (e) {
return !0;
}
return !1;
},
b = function () {
return (
window.screen.width < window.screen.availWidth ||
window.screen.height < window.screen.availHeight
);
},
L = function () {
var e = navigator.userAgent.toLowerCase(),
t = navigator.oscpu,
n = navigator.platform.toLowerCase(),
a =
0 <= e.indexOf("windows phone")
? "Windows Phone"
: 0 <= e.indexOf("windows") ||
0 <= e.indexOf("win16") ||
0 <= e.indexOf("win32") ||
0 <= e.indexOf("win64") ||
0 <= e.indexOf("win95") ||
0 <= e.indexOf("win98") ||
0 <= e.indexOf("winnt") ||
0 <= e.indexOf("wow64")
? "Windows"
: 0 <= e.indexOf("android")
? "Android"
: 0 <= e.indexOf("linux") ||
0 <= e.indexOf("cros") ||
0 <= e.indexOf("x11")
? "Linux"
: 0 <= e.indexOf("iphone") ||
0 <= e.indexOf("ipad") ||
0 <= e.indexOf("ipod") ||
0 <= e.indexOf("crios") ||
0 <= e.indexOf("fxios")
? "iOS"
: 0 <= e.indexOf("macintosh") || 0 <= e.indexOf("mac_powerpc)")
? "Mac"
: "Other";
if (
("ontouchstart" in window ||
0 < navigator.maxTouchPoints ||
0 < navigator.msMaxTouchPoints) &&
"Windows" !== a &&
"Windows Phone" !== a &&
"Android" !== a &&
"iOS" !== a &&
"Other" !== a &&
-1 === e.indexOf("cros")
)
return !0;
if (void 0 !== t) {
if (
0 <= (t = t.toLowerCase()).indexOf("win") &&
"Windows" !== a &&
"Windows Phone" !== a
)
return !0;
if (0 <= t.indexOf("linux") && "Linux" !== a && "Android" !== a)
return !0;
if (0 <= t.indexOf("mac") && "Mac" !== a && "iOS" !== a) return !0;
if (
(-1 === t.indexOf("win") &&
-1 === t.indexOf("linux") &&
-1 === t.indexOf("mac")) !=
("Other" === a)
)
return !0;
}
return (
(0 <= n.indexOf("win") && "Windows" !== a && "Windows Phone" !== a) ||
((0 <= n.indexOf("linux") ||
0 <= n.indexOf("android") ||
0 <= n.indexOf("pike")) &&
"Linux" !== a &&
"Android" !== a) ||
((0 <= n.indexOf("mac") ||
0 <= n.indexOf("ipad") ||
0 <= n.indexOf("ipod") ||
0 <= n.indexOf("iphone")) &&
"Mac" !== a &&
"iOS" !== a) ||
(!(0 <= n.indexOf("arm") && "Windows Phone" === a) &&
!(0 <= n.indexOf("pike") && 0 <= e.indexOf("opera mini")) &&
((n.indexOf("win") < 0 &&
n.indexOf("linux") < 0 &&
n.indexOf("mac") < 0 &&
n.indexOf("iphone") < 0 &&
n.indexOf("ipad") < 0 &&
n.indexOf("ipod") < 0) !=
("Other" === a) ||
(void 0 === navigator.plugins &&
"Windows" !== a &&
"Windows Phone" !== a)))
);
},
I = function () {
var e,
t = navigator.userAgent.toLowerCase(),
n = navigator.productSub;
if (0 <= t.indexOf("edge/") || 0 <= t.indexOf("iemobile/")) return !1;
if (0 <= t.indexOf("opera mini")) return !1;
if (
("Chrome" ===
(e =
0 <= t.indexOf("firefox/")
? "Firefox"
: 0 <= t.indexOf("opera/") || 0 <= t.indexOf(" opr/")
? "Opera"
: 0 <= t.indexOf("chrome/")
? "Chrome"
: 0 <= t.indexOf("safari/")
? 0 <= t.indexOf("android 1.") ||
0 <= t.indexOf("android 2.") ||
0 <= t.indexOf("android 3.") ||
0 <= t.indexOf("android 4.")
? "AOSP"
: "Safari"
: 0 <= t.indexOf("trident/")
? "Internet Explorer"
: "Other") ||
"Safari" === e ||
"Opera" === e) &&
"20030107" !== n
)
return !0;
var a,
r = eval.toString().length;
if (37 === r && "Safari" !== e && "Firefox" !== e && "Other" !== e)
return !0;
if (39 === r && "Internet Explorer" !== e && "Other" !== e) return !0;
if (
33 === r &&
"Chrome" !== e &&
"AOSP" !== e &&
"Opera" !== e &&
"Other" !== e
)
return !0;
try {
throw "a";
} catch (e) {
try {
e.toSource(), (a = !0);
} catch (e) {
a = !1;
}
}
return a && "Firefox" !== e && "Other" !== e;
},
k = function () {
var e = document.createElement("canvas");
return !(!e.getContext || !e.getContext("2d"));
},
D = function () {
if (!k()) return !1;
var e = U(),
t = !!window.WebGLRenderingContext && !!e;
return V(e), t;
},
R = function () {
return (
"Microsoft Internet Explorer" === navigator.appName ||
!(
"Netscape" !== navigator.appName ||
!/Trident/.test(navigator.userAgent)
)
);
},
N = function () {
return (
2 <=
("msWriteProfilerMark" in window) +
("msLaunchUri" in navigator) +
("msSaveBlob" in navigator)
);
},
_ = function () {
return void 0 !== window.swfobject;
},
F = function () {
return window.swfobject.hasFlashPlayerVersion("9.0.0");
},
G = function (t, e) {
var n = "___fp_swf_loaded";
window[n] = function (e) {
t(e);
};
var a,
r,
i = e.fonts.swfContainerId;
(r = document.createElement("div")).setAttribute(
"id",
a.fonts.swfContainerId
),
document.body.appendChild(r);
var o = { onReady: n };
window.swfobject.embedSWF(
e.fonts.swfPath,
i,
"1",
"1",
"9.0.0",
!1,
o,
{ allowScriptAccess: "always", menu: "false" },
{}
);
},
U = function () {
var e = document.createElement("canvas"),
t = null;
try {
t = e.getContext("webgl") || e.getContext("experimental-webgl");
} catch (e) {}
return (t = t || null);
},
V = function (e) {
var t = e.getExtension("WEBGL_lose_context");
null != t && t.loseContext();
},
H = [
{
key: "userAgent",
getData: function (e) {
e(navigator.userAgent);
},
},
{
key: "webdriver",
getData: function (e, t) {
e(
null == navigator.webdriver ? t.NOT_AVAILABLE : navigator.webdriver
);
},
},
{
key: "language",
getData: function (e, t) {
e(
navigator.language ||
navigator.userLanguage ||
navigator.browserLanguage ||
navigator.systemLanguage ||
t.NOT_AVAILABLE
);
},
},
{
key: "colorDepth",
getData: function (e, t) {
e(window.screen.colorDepth || t.NOT_AVAILABLE);
},
},
{
key: "deviceMemory",
getData: function (e, t) {
e(navigator.deviceMemory || t.NOT_AVAILABLE);
},
},
{
key: "pixelRatio",
getData: function (e, t) {
e(window.devicePixelRatio || t.NOT_AVAILABLE);
},
},
{
key: "hardwareConcurrency",
getData: function (e, t) {
e(C(t));
},
},
{
key: "screenResolution",
getData: function (e, t) {
e(r(t));
},
},
{
key: "availableScreenResolution",
getData: function (e, t) {
e(i(t));
},
},
{
key: "timezoneOffset",
getData: function (e) {
e(new Date().getTimezoneOffset());
},
},
{
key: "timezone",
getData: function (e, t) {
window.Intl && window.Intl.DateTimeFormat
? e(
new window.Intl.DateTimeFormat().resolvedOptions().timeZone ||
t.NOT_AVAILABLE
)
: e(t.NOT_AVAILABLE);
},
},
{
key: "sessionStorage",
getData: function (e, t) {
e(A(t));
},
},
{
key: "localStorage",
getData: function (e, t) {
e(v(t));
},
},
{
key: "indexedDb",
getData: function (e, t) {
e(S(t));
},
},
{
key: "addBehavior",
getData: function (e) {
e(!!window.HTMLElement.prototype.addBehavior);
},
},
{
key: "openDatabase",
getData: function (e) {
e(!!window.openDatabase);
},
},
{
key: "cpuClass",
getData: function (e, t) {
e(w(t));
},
},
{
key: "platform",
getData: function (e, t) {
e(B(t));
},
},
{
key: "doNotTrack",
getData: function (e, t) {
e(y(t));
},
},
{
key: "plugins",
getData: function (e, t) {
R() ? (t.plugins.excludeIE ? e(t.EXCLUDED) : e(u(t))) : e(o(t));
},
},
{
key: "canvas",
getData: function (e, t) {
k() ? e(E(t)) : e(t.NOT_AVAILABLE);
},
},
{
key: "webgl",
getData: function (e, t) {
D() ? e(x()) : e(t.NOT_AVAILABLE);
},
},
{
key: "webglVendorAndRenderer",
getData: function (e) {
D() ? e(O()) : e();
},
},
{
key: "adBlock",
getData: function (e) {
e(M());
},
},
{
key: "hasLiedLanguages",
getData: function (e) {
e(P());
},
},
{
key: "hasLiedResolution",
getData: function (e) {
e(b());
},
},
{
key: "hasLiedOs",
getData: function (e) {
e(L());
},
},
{
key: "hasLiedBrowser",
getData: function (e) {
e(I());
},
},
{
key: "touchSupport",
getData: function (e) {
e(t());
},
},
{
key: "fonts",
getData: function (e, t) {
var u = ["monospace", "sans-serif", "serif"],
d = [
"Andale Mono",
"Arial",
"Arial Black",
"Arial Hebrew",
"Arial MT",
"Arial Narrow",
"Arial Rounded MT Bold",
"Arial Unicode MS",
"Bitstream Vera Sans Mono",
"Book Antiqua",
"Bookman Old Style",
"Calibri",
"Cambria",
"Cambria Math",
"Century",
"Century Gothic",
"Century Schoolbook",
"Comic Sans",
"Comic Sans MS",
"Consolas",
"Courier",
"Courier New",
"Geneva",
"Georgia",
"Helvetica",
"Helvetica Neue",
"Impact",
"Lucida Bright",
"Lucida Calligraphy",
"Lucida Console",
"Lucida Fax",
"LUCIDA GRANDE",
"Lucida Handwriting",
"Lucida Sans",
"Lucida Sans Typewriter",
"Lucida Sans Unicode",
"Microsoft Sans Serif",
"Monaco",
"Monotype Corsiva",
"MS Gothic",
"MS Outlook",
"MS PGothic",
"MS Reference Sans Serif",
"MS Sans Serif",
"MS Serif",
"MYRIAD",
"MYRIAD PRO",
"Palatino",
"Palatino Linotype",
"Segoe Print",
"Segoe Script",
"Segoe UI",
"Segoe UI Light",
"Segoe UI Semibold",
"Segoe UI Symbol",
"Tahoma",
"Times",
"Times New Roman",
"Times New Roman PS",
"Trebuchet MS",
"Verdana",
"Wingdings",
"Wingdings 2",
"Wingdings 3",
];
t.fonts.extendedJsFonts &&
(d = d.concat([
"Abadi MT Condensed Light",
"Academy Engraved LET",
"ADOBE CASLON PRO",
"Adobe Garamond",
"ADOBE GARAMOND PRO",
"Agency FB",
"Aharoni",
"Albertus Extra Bold",
"Albertus Medium",
"Algerian",
"Amazone BT",
"American Typewriter",
"American Typewriter Condensed",
"AmerType Md BT",
"Andalus",
"Angsana New",
"AngsanaUPC",
"Antique Olive",
"Aparajita",
"Apple Chancery",
"Apple Color Emoji",
"Apple SD Gothic Neo",
"Arabic Typesetting",
"ARCHER",
"ARNO PRO",
"Arrus BT",
"Aurora Cn BT",
"AvantGarde Bk BT",
"AvantGarde Md BT",
"AVENIR",
"Ayuthaya",
"Bandy",
"Bangla Sangam MN",
"Bank Gothic",
"BankGothic Md BT",
"Baskerville",
"Baskerville Old Face",
"Batang",
"BatangChe",
"Bauer Bodoni",
"Bauhaus 93",
"Bazooka",
"Bell MT",
"Bembo",
"Benguiat Bk BT",
"Berlin Sans FB",
"Berlin Sans FB Demi",
"Bernard MT Condensed",
"BernhardFashion BT",
"BernhardMod BT",
"Big Caslon",
"BinnerD",
"Blackadder ITC",
"BlairMdITC TT",
"Bodoni 72",
"Bodoni 72 Oldstyle",
"Bodoni 72 Smallcaps",
"Bodoni MT",
"Bodoni MT Black",
"Bodoni MT Condensed",
"Bodoni MT Poster Compressed",
"Bookshelf Symbol 7",
"Boulder",
"Bradley Hand",
"Bradley Hand ITC",
"Bremen Bd BT",
"Britannic Bold",
"Broadway",
"Browallia New",
"BrowalliaUPC",
"Brush Script MT",
"Californian FB",
"Calisto MT",
"Calligrapher",
"Candara",
"CaslonOpnface BT",
"Castellar",
"Centaur",
"Cezanne",
"CG Omega",
"CG Times",
"Chalkboard",
"Chalkboard SE",
"Chalkduster",
"Charlesworth",
"Charter Bd BT",
"Charter BT",
"Chaucer",
"ChelthmITC Bk BT",
"Chiller",
"Clarendon",
"Clarendon Condensed",
"CloisterBlack BT",
"Cochin",
"Colonna MT",
"Constantia",
"Cooper Black",
"Copperplate",
"Copperplate Gothic",
"Copperplate Gothic Bold",
"Copperplate Gothic Light",
"CopperplGoth Bd BT",
"Corbel",
"Cordia New",
"CordiaUPC",
"Cornerstone",
"Coronet",
"Cuckoo",
"Curlz MT",
"DaunPenh",
"Dauphin",
"David",
"DB LCD Temp",
"DELICIOUS",
"Denmark",
"DFKai-SB",
"Didot",
"DilleniaUPC",
"DIN",
"DokChampa",
"Dotum",
"DotumChe",
"Ebrima",
"Edwardian Script ITC",
"Elephant",
"English 111 Vivace BT",
"Engravers MT",
"EngraversGothic BT",
"Eras Bold ITC",
"Eras Demi ITC",
"Eras Light ITC",
"Eras Medium ITC",
"EucrosiaUPC",
"Euphemia",
"Euphemia UCAS",
"EUROSTILE",
"Exotc350 Bd BT",
"FangSong",
"Felix Titling",
"Fixedsys",
"FONTIN",
"Footlight MT Light",
"Forte",
"FrankRuehl",
"Fransiscan",
"Freefrm721 Blk BT",
"FreesiaUPC",
"Freestyle Script",
"French Script MT",
"FrnkGothITC Bk BT",
"Fruitger",
"FRUTIGER",
"Futura",
"Futura Bk BT",
"Futura Lt BT",
"Futura Md BT",
"Futura ZBlk BT",
"FuturaBlack BT",
"Gabriola",
"Galliard BT",
"Gautami",
"Geeza Pro",
"Geometr231 BT",
"Geometr231 Hv BT",
"Geometr231 Lt BT",
"GeoSlab 703 Lt BT",
"GeoSlab 703 XBd BT",
"Gigi",
"Gill Sans",
"Gill Sans MT",
"Gill Sans MT Condensed",
"Gill Sans MT Ext Condensed Bold",
"Gill Sans Ultra Bold",
"Gill Sans Ultra Bold Condensed",
"Gisha",
"Gloucester MT Extra Condensed",
"GOTHAM",
"GOTHAM BOLD",
"Goudy Old Style",
"Goudy Stout",
"GoudyHandtooled BT",
"GoudyOLSt BT",
"Gujarati Sangam MN",
"Gulim",
"GulimChe",
"Gungsuh",
"GungsuhChe",
"Gurmukhi MN",
"Haettenschweiler",
"Harlow Solid Italic",
"Harrington",
"Heather",
"Heiti SC",
"Heiti TC",
"HELV",
"Herald",
"High Tower Text",
"Hiragino Kaku Gothic ProN",
"Hiragino Mincho ProN",
"Hoefler Text",
"Humanst 521 Cn BT",
"Humanst521 BT",
"Humanst521 Lt BT",
"Imprint MT Shadow",
"Incised901 Bd BT",
"Incised901 BT",
"Incised901 Lt BT",
"INCONSOLATA",
"Informal Roman",
"Informal011 BT",
"INTERSTATE",
"IrisUPC",
"Iskoola Pota",
"JasmineUPC",
"Jazz LET",
"Jenson",
"Jester",
"Jokerman",
"Juice ITC",
"Kabel Bk BT",
"Kabel Ult BT",
"Kailasa",
"KaiTi",
"Kalinga",
"Kannada Sangam MN",
"Kartika",
"Kaufmann Bd BT",
"Kaufmann BT",
"Khmer UI",
"KodchiangUPC",
"Kokila",
"Korinna BT",
"Kristen ITC",
"Krungthep",
"Kunstler Script",
"Lao UI",
"Latha",
"Leelawadee",
"Letter Gothic",
"Levenim MT",
"LilyUPC",
"Lithograph",
"Lithograph Light",
"Long Island",
"Lydian BT",
"Magneto",
"Maiandra GD",
"Malayalam Sangam MN",
"Malgun Gothic",
"Mangal",
"Marigold",
"Marion",
"Marker Felt",
"Market",
"Marlett",
"Matisse ITC",
"Matura MT Script Capitals",
"Meiryo",
"Meiryo UI",
"Microsoft Himalaya",
"Microsoft JhengHei",
"Microsoft New Tai Lue",
"Microsoft PhagsPa",
"Microsoft Tai Le",
"Microsoft Uighur",
"Microsoft YaHei",
"Microsoft Yi Baiti",
"MingLiU",
"MingLiU_HKSCS",
"MingLiU_HKSCS-ExtB",
"MingLiU-ExtB",
"Minion",
"Minion Pro",
"Miriam",
"Miriam Fixed",
"Mistral",
"Modern",
"Modern No. 20",
"Mona Lisa Solid ITC TT",
"Mongolian Baiti",
"MONO",
"MoolBoran",
"Mrs Eaves",
"MS LineDraw",
"MS Mincho",
"MS PMincho",
"MS Reference Specialty",
"MS UI Gothic",
"MT Extra",
"MUSEO",
"MV Boli",
"Nadeem",
"Narkisim",
"NEVIS",
"News Gothic",
"News GothicMT",
"NewsGoth BT",
"Niagara Engraved",
"Niagara Solid",
"Noteworthy",
"NSimSun",
"Nyala",
"OCR A Extended",
"Old Century",
"Old English Text MT",
"Onyx",
"Onyx BT",
"OPTIMA",
"Oriya Sangam MN",
"OSAKA",
"OzHandicraft BT",
"Palace Script MT",
"Papyrus",
"Parchment",
"Party LET",
"Pegasus",
"Perpetua",
"Perpetua Titling MT",
"PetitaBold",
"Pickwick",
"Plantagenet Cherokee",
"Playbill",
"PMingLiU",
"PMingLiU-ExtB",
"Poor Richard",
"Poster",
"PosterBodoni BT",
"PRINCETOWN LET",
"Pristina",
"PTBarnum BT",
"Pythagoras",
"Raavi",
"Rage Italic",
"Ravie",
"Ribbon131 Bd BT",
"Rockwell",
"Rockwell Condensed",
"Rockwell Extra Bold",
"Rod",
"Roman",
"Sakkal Majalla",
"Santa Fe LET",
"Savoye LET",
"Sceptre",
"Script",
"Script MT Bold",
"SCRIPTINA",
"Serifa",
"Serifa BT",
"Serifa Th BT",
"ShelleyVolante BT",
"Sherwood",
"Shonar Bangla",
"Showcard Gothic",
"Shruti",
"Signboard",
"SILKSCREEN",
"SimHei",
"Simplified Arabic",
"Simplified Arabic Fixed",
"SimSun",
"SimSun-ExtB",
"Sinhala Sangam MN",
"Sketch Rockwell",
"Skia",
"Small Fonts",
"Snap ITC",
"Snell Roundhand",
"Socket",
"Souvenir Lt BT",
"Staccato222 BT",
"Steamer",
"Stencil",
"Storybook",
"Styllo",
"Subway",
"Swis721 BlkEx BT",
"Swiss911 XCm BT",
"Sylfaen",
"Synchro LET",
"System",
"Tamil Sangam MN",
"Technical",
"Teletype",
"Telugu Sangam MN",
"Tempus Sans ITC",
"Terminal",
"Thonburi",
"Traditional Arabic",
"Trajan",
"TRAJAN PRO",
"Tristan",
"Tubular",
"Tunga",
"Tw Cen MT",
"Tw Cen MT Condensed",
"Tw Cen MT Condensed Extra Bold",
"TypoUpright BT",
"Unicorn",
"Univers",
"Univers CE 55 Medium",
"Univers Condensed",
"Utsaah",
"Vagabond",
"Vani",
"Vijaya",
"Viner Hand ITC",
"VisualUI",
"Vivaldi",
"Vladimir Script",
"Vrinda",
"Westminster",
"WHITNEY",
"Wide Latin",
"ZapfEllipt BT",
"ZapfHumnst BT",
"ZapfHumnst Dm BT",
"Zapfino",
"Zurich BlkEx BT",
"Zurich Ex BT",
"ZWAdobeF",
])),
(d = (d = d.concat(t.fonts.userDefinedFonts)).filter(function (
e,
t
) {
return d.indexOf(e) === t;
}));
function f() {
var e = document.createElement("span");
return (
(e.style.position = "absolute"),
(e.style.left = "-9999px"),
(e.style.fontSize = "72px"),
(e.style.fontStyle = "normal"),
(e.style.fontWeight = "normal"),
(e.style.letterSpacing = "normal"),
(e.style.lineBreak = "auto"),
(e.style.lineHeight = "normal"),
(e.style.textTransform = "none"),
(e.style.textAlign = "left"),
(e.style.textDecoration = "none"),
(e.style.textShadow = "none"),
(e.style.whiteSpace = "normal"),
(e.style.wordBreak = "normal"),
(e.style.wordSpacing = "normal"),
(e.innerHTML = "mmmmmmmmmmlli"),
e
);
}
function n(e) {
for (var t = !1, n = 0; n < u.length; n++)
if (
(t =
e[n].offsetWidth !== i[u[n]] || e[n].offsetHeight !== o[u[n]])
)
return t;
return t;
}
var a = document.getElementsByTagName("body")[0],
r = document.createElement("div"),
g = document.createElement("div"),
i = {},
o = {},
l = (function () {
for (var e = [], t = 0, n = u.length; t < n; t++) {
var a = f();
(a.style.fontFamily = u[t]), r.appendChild(a), e.push(a);
}
return e;
})();
a.appendChild(r);
for (var s = 0, c = u.length; s < c; s++)
(i[u[s]] = l[s].offsetWidth), (o[u[s]] = l[s].offsetHeight);
var h = (function () {
for (var e, t, n, a = {}, r = 0, i = d.length; r < i; r++) {
for (var o = [], l = 0, s = u.length; l < s; l++) {
var c =
((e = d[r]),
(t = u[l]),
(n = void 0),
((n = f()).style.fontFamily = "'" + e + "'," + t),
n);
g.appendChild(c), o.push(c);
}
a[d[r]] = o;
}
return a;
})();
a.appendChild(g);
for (var m = [], p = 0, T = d.length; p < T; p++)
n(h[d[p]]) && m.push(d[p]);
a.removeChild(g), a.removeChild(r), e(m);
},
pauseBefore: !0,
},
{
key: "fontsFlash",
getData: function (t, e) {
return _()
? F()
? e.fonts.swfPath
? void G(function (e) {
t(e);
}, e)
: t("missing options.fonts.swfPath")
: t("flash not installed")
: t("swf object not loaded");
},
pauseBefore: !0,
},
{
key: "audio",
getData: function (n, e) {
var t = e.audio;
if (
t.excludeIOS11 &&
navigator.userAgent.match(/OS 11.+Version\/11.+Safari/)
)
return n(e.EXCLUDED);
var a =
window.OfflineAudioContext || window.webkitOfflineAudioContext;
if (null == a) return n(e.NOT_AVAILABLE);
var r = new a(1, 44100, 44100),
i = r.createOscillator();
(i.type = "triangle"), i.frequency.setValueAtTime(1e4, r.currentTime);
var o = r.createDynamicsCompressor();
c(
[
["threshold", -50],
["knee", 40],
["ratio", 12],
["reduction", -20],
["attack", 0],
["release", 0.25],
],
function (e) {
void 0 !== o[e[0]] &&
"function" == typeof o[e[0]].setValueAtTime &&
o[e[0]].setValueAtTime(e[1], r.currentTime);
}
),
i.connect(o),
o.connect(r.destination),
i.start(0),
r.startRendering();
var l = setTimeout(function () {
return (
console.warn(
'Audio fingerprint timed out. Please report bug at https://github.com/fingerprintjs/fingerprintjs with your user agent: "' +
navigator.userAgent +
'".'
),
(r.oncomplete = function () {}),
(r = null),
n("audioTimeout")
);
}, t.timeout);
r.oncomplete = function (e) {
var t;
try {
clearTimeout(l),
(t = e.renderedBuffer
.getChannelData(0)
.slice(4500, 5e3)
.reduce(function (e, t) {
return e + Math.abs(t);
}, 0)
.toString()),
i.disconnect(),
o.disconnect();
} catch (e) {
return void n(e);
}
n(t);
};
},
},
{
key: "enumerateDevices",
getData: function (t, e) {
if (!n()) return t(e.NOT_AVAILABLE);
navigator.mediaDevices
.enumerateDevices()
.then(function (e) {
t(
e.map(function (e) {
return (
"id=" +
e.deviceId +
";gid=" +
e.groupId +
";" +
e.kind +
";" +
e.label
);
})
);
})
.catch(function (e) {
t(e);
});
},
},
];
return (
(a.get = function (n, a) {
(function (e, t) {
if (null == t) return;
var n, a;
for (a in t)
null == (n = t[a]) ||
Object.prototype.hasOwnProperty.call(e, a) ||
(e[a] = n);
})((n = a ? n || {} : ((a = n), {})), e),
(n.components = n.extraComponents.concat(H));
var r = {
data: [],
addPreprocessedComponent: function (e, t) {
"function" == typeof n.preprocessor && (t = n.preprocessor(e, t)),
r.data.push({ key: e, value: t });
},
},
i = -1,
o = function (e) {
if ((i += 1) >= n.components.length) a(r.data);
else {
var t = n.components[i];
if (n.excludes[t.key]) o(!1);
else {
if (!e && t.pauseBefore)
return (
--i,
void setTimeout(function () {
o(!0);
}, 1)
);
try {
t.getData(function (e) {
r.addPreprocessedComponent(t.key, e), o(!1);
}, n);
} catch (e) {
r.addPreprocessedComponent(t.key, String(e)), o(!1);
}
}
}
};
o(!1);
}),
(a.getPromise = function (n) {
return new Promise(function (e, t) {
a.get(n, e);
});
}),
(a.getV18 = function (i, o) {
return (
null == o && ((o = i), (i = {})),
a.get(i, function (e) {
for (var t = [], n = 0; n < e.length; n++) {
var a = e[n];
if (a.value === (i.NOT_AVAILABLE || "not available"))
t.push({ key: a.key, value: "unknown" });
else if ("plugins" === a.key)
t.push({
key: "plugins",
value: s(a.value, function (e) {
var t = s(e[2], function (e) {
return e.join ? e.join("~") : e;
}).join(",");
return [e[0], e[1], t].join("::");
}),
});
else if (
-1 !== ["canvas", "webgl"].indexOf(a.key) &&
Array.isArray(a.value)
)
t.push({ key: a.key, value: a.value.join("~") });
else if (
-1 !==
[
"sessionStorage",
"localStorage",
"indexedDb",
"addBehavior",
"openDatabase",
].indexOf(a.key)
) {
if (!a.value) continue;
t.push({ key: a.key, value: 1 });
} else
a.value
? t.push(
a.value.join ? { key: a.key, value: a.value.join(";") } : a
)
: t.push({ key: a.key, value: a.value });
}
var r = l(
s(t, function (e) {
return e.value;
}).join("~~~"),
31
);
o(r, t);
})
);
}),
(a.x64hash128 = l),
(a.VERSION = "2.1.4"),
a
);
});
/*!
* Socket.IO v3.0.5
* (c) 2014-2021 Guillermo Rauch
* Released under the MIT License.
*/
!function(t,e){"object"==typeof exports&&"object"==typeof module?module.exports=e():"function"==typeof define&&define.amd?define([],e):"object"==typeof exports?exports.io=e():t.io=e()}(window,(function(){return function(t){var e={};function n(r){if(e[r])return e[r].exports;var o=e[r]={i:r,l:!1,exports:{}};return t[r].call(o.exports,o,o.exports,n),o.l=!0,o.exports}return n.m=t,n.c=e,n.d=function(t,e,r){n.o(t,e)||Object.defineProperty(t,e,{enumerable:!0,get:r})},n.r=function(t){"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(t,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(t,"__esModule",{value:!0})},n.t=function(t,e){if(1&e&&(t=n(t)),8&e)return t;if(4&e&&"object"==typeof t&&t&&t.__esModule)return t;var r=Object.create(null);if(n.r(r),Object.defineProperty(r,"default",{enumerable:!0,value:t}),2&e&&"string"!=typeof t)for(var o in t)n.d(r,o,function(e){return t[e]}.bind(null,o));return r},n.n=function(t){var e=t&&t.__esModule?function(){return t.default}:function(){return t};return n.d(e,"a",e),e},n.o=function(t,e){return Object.prototype.hasOwnProperty.call(t,e)},n.p="",n(n.s=17)}([function(t,e,n){function r(t){if(t)return function(t){for(var e in r.prototype)t[e]=r.prototype[e];return t}(t)}t.exports=r,r.prototype.on=r.prototype.addEventListener=function(t,e){return this._callbacks=this._callbacks||{},(this._callbacks["$"+t]=this._callbacks["$"+t]||[]).push(e),this},r.prototype.once=function(t,e){function n(){this.off(t,n),e.apply(this,arguments)}return n.fn=e,this.on(t,n),this},r.prototype.off=r.prototype.removeListener=r.prototype.removeAllListeners=r.prototype.removeEventListener=function(t,e){if(this._callbacks=this._callbacks||{},0==arguments.length)return this._callbacks={},this;var n,r=this._callbacks["$"+t];if(!r)return this;if(1==arguments.length)return delete this._callbacks["$"+t],this;for(var o=0;o<r.length;o++)if((n=r[o])===e||n.fn===e){r.splice(o,1);break}return 0===r.length&&delete this._callbacks["$"+t],this},r.prototype.emit=function(t){this._callbacks=this._callbacks||{};for(var e=new Array(arguments.length-1),n=this._callbacks["$"+t],r=1;r<arguments.length;r++)e[r-1]=arguments[r];if(n){r=0;for(var o=(n=n.slice(0)).length;r<o;++r)n[r].apply(this,e)}return this},r.prototype.listeners=function(t){return this._callbacks=this._callbacks||{},this._callbacks["$"+t]||[]},r.prototype.hasListeners=function(t){return!!this.listeners(t).length}},function(t,e,n){var r=n(23),o=n(24),i=String.fromCharCode(30);t.exports={protocol:4,encodePacket:r,encodePayload:function(t,e){var n=t.length,o=new Array(n),s=0;t.forEach((function(t,c){r(t,!1,(function(t){o[c]=t,++s===n&&e(o.join(i))}))}))},decodePacket:o,decodePayload:function(t,e){for(var n=t.split(i),r=[],s=0;s<n.length;s++){var c=o(n[s],e);if(r.push(c),"error"===c.type)break}return r}}},function(t,e){t.exports="undefined"!=typeof self?self:"undefined"!=typeof window?window:Function("return this")()},function(t,e,n){function r(t){return(r="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t})(t)}function o(t,e){for(var n=0;n<e.length;n++){var r=e[n];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(t,r.key,r)}}function i(t,e){return(i=Object.setPrototypeOf||function(t,e){return t.__proto__=e,t})(t,e)}function s(t){var e=function(){if("undefined"==typeof Reflect||!Reflect.construct)return!1;if(Reflect.construct.sham)return!1;if("function"==typeof Proxy)return!0;try{return Date.prototype.toString.call(Reflect.construct(Date,[],(function(){}))),!0}catch(t){return!1}}();return function(){var n,r=a(t);if(e){var o=a(this).constructor;n=Reflect.construct(r,arguments,o)}else n=r.apply(this,arguments);return c(this,n)}}function c(t,e){return!e||"object"!==r(e)&&"function"!=typeof e?function(t){if(void 0===t)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return t}(t):e}function a(t){return(a=Object.setPrototypeOf?Object.getPrototypeOf:function(t){return t.__proto__||Object.getPrototypeOf(t)})(t)}var u=n(1),f=function(t){!function(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Super expression must either be null or a function");t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,writable:!0,configurable:!0}}),e&&i(t,e)}(a,t);var e,n,r,c=s(a);function a(t){var e;return function(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}(this,a),(e=c.call(this)).opts=t,e.query=t.query,e.readyState="",e.socket=t.socket,e}return e=a,(n=[{key:"onError",value:function(t,e){var n=new Error(t);return n.type="TransportError",n.description=e,this.emit("error",n),this}},{key:"open",value:function(){return"closed"!==this.readyState&&""!==this.readyState||(this.readyState="opening",this.doOpen()),this}},{key:"close",value:function(){return"opening"!==this.readyState&&"open"!==this.readyState||(this.doClose(),this.onClose()),this}},{key:"send",value:function(t){if("open"!==this.readyState)throw new Error("Transport not open");this.write(t)}},{key:"onOpen",value:function(){this.readyState="open",this.writable=!0,this.emit("open")}},{key:"onData",value:function(t){var e=u.decodePacket(t,this.socket.binaryType);this.onPacket(e)}},{key:"onPacket",value:function(t){this.emit("packet",t)}},{key:"onClose",value:function(){this.readyState="closed",this.emit("close")}}])&&o(e.prototype,n),r&&o(e,r),a}(n(0));t.exports=f},function(t,e){e.encode=function(t){var e="";for(var n in t)t.hasOwnProperty(n)&&(e.length&&(e+="&"),e+=encodeURIComponent(n)+"="+encodeURIComponent(t[n]));return e},e.decode=function(t){for(var e={},n=t.split("&"),r=0,o=n.length;r<o;r++){var i=n[r].split("=");e[decodeURIComponent(i[0])]=decodeURIComponent(i[1])}return e}},function(t,e,n){"use strict";function r(t){return(r="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t})(t)}function o(t,e,n){return(o="undefined"!=typeof Reflect&&Reflect.get?Reflect.get:function(t,e,n){var r=function(t,e){for(;!Object.prototype.hasOwnProperty.call(t,e)&&null!==(t=a(t)););return t}(t,e);if(r){var o=Object.getOwnPropertyDescriptor(r,e);return o.get?o.get.call(n):o.value}})(t,e,n||t)}function i(t,e){return(i=Object.setPrototypeOf||function(t,e){return t.__proto__=e,t})(t,e)}function s(t){var e=function(){if("undefined"==typeof Reflect||!Reflect.construct)return!1;if(Reflect.construct.sham)return!1;if("function"==typeof Proxy)return!0;try{return Date.prototype.toString.call(Reflect.construct(Date,[],(function(){}))),!0}catch(t){return!1}}();return function(){var n,r=a(t);if(e){var o=a(this).constructor;n=Reflect.construct(r,arguments,o)}else n=r.apply(this,arguments);return c(this,n)}}function c(t,e){return!e||"object"!==r(e)&&"function"!=typeof e?function(t){if(void 0===t)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return t}(t):e}function a(t){return(a=Object.setPrototypeOf?Object.getPrototypeOf:function(t){return t.__proto__||Object.getPrototypeOf(t)})(t)}function u(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}function f(t,e){for(var n=0;n<e.length;n++){var r=e[n];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(t,r.key,r)}}function p(t,e,n){return e&&f(t.prototype,e),n&&f(t,n),t}Object.defineProperty(e,"__esModule",{value:!0}),e.Decoder=e.Encoder=e.PacketType=e.protocol=void 0;var l,h=n(0),y=n(29),d=n(15);e.protocol=5,function(t){t[t.CONNECT=0]="CONNECT",t[t.DISCONNECT=1]="DISCONNECT",t[t.EVENT=2]="EVENT",t[t.ACK=3]="ACK",t[t.CONNECT_ERROR=4]="CONNECT_ERROR",t[t.BINARY_EVENT=5]="BINARY_EVENT",t[t.BINARY_ACK=6]="BINARY_ACK"}(l=e.PacketType||(e.PacketType={}));var v=function(){function t(){u(this,t)}return p(t,[{key:"encode",value:function(t){return t.type!==l.EVENT&&t.type!==l.ACK||!d.hasBinary(t)?[this.encodeAsString(t)]:(t.type=t.type===l.EVENT?l.BINARY_EVENT:l.BINARY_ACK,this.encodeAsBinary(t))}},{key:"encodeAsString",value:function(t){var e=""+t.type;return t.type!==l.BINARY_EVENT&&t.type!==l.BINARY_ACK||(e+=t.attachments+"-"),t.nsp&&"/"!==t.nsp&&(e+=t.nsp+","),null!=t.id&&(e+=t.id),null!=t.data&&(e+=JSON.stringify(t.data)),e}},{key:"encodeAsBinary",value:function(t){var e=y.deconstructPacket(t),n=this.encodeAsString(e.packet),r=e.buffers;return r.unshift(n),r}}]),t}();e.Encoder=v;var b=function(t){!function(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Super expression must either be null or a function");t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,writable:!0,configurable:!0}}),e&&i(t,e)}(n,t);var e=s(n);function n(){return u(this,n),e.call(this)}return p(n,[{key:"add",value:function(t){var e;if("string"==typeof t)(e=this.decodeString(t)).type===l.BINARY_EVENT||e.type===l.BINARY_ACK?(this.reconstructor=new m(e),0===e.attachments&&o(a(n.prototype),"emit",this).call(this,"decoded",e)):o(a(n.prototype),"emit",this).call(this,"decoded",e);else{if(!d.isBinary(t)&&!t.base64)throw new Error("Unknown type: "+t);if(!this.reconstructor)throw new Error("got binary data when not reconstructing a packet");(e=this.reconstructor.takeBinaryData(t))&&(this.reconstructor=null,o(a(n.prototype),"emit",this).call(this,"decoded",e))}}},{key:"decodeString",value:function(t){var e=0,r={type:Number(t.charAt(0))};if(void 0===l[r.type])throw new Error("unknown packet type "+r.type);if(r.type===l.BINARY_EVENT||r.type===l.BINARY_ACK){for(var o=e+1;"-"!==t.charAt(++e)&&e!=t.length;);var i=t.substring(o,e);if(i!=Number(i)||"-"!==t.charAt(e))throw new Error("Illegal attachments");r.attachments=Number(i)}if("/"===t.charAt(e+1)){for(var s=e+1;++e;){if(","===t.charAt(e))break;if(e===t.length)break}r.nsp=t.substring(s,e)}else r.nsp="/";var c=t.charAt(e+1);if(""!==c&&Number(c)==c){for(var a=e+1;++e;){var u=t.charAt(e);if(null==u||Number(u)!=u){--e;break}if(e===t.length)break}r.id=Number(t.substring(a,e+1))}if(t.charAt(++e)){var f=function(t){try{return JSON.parse(t)}catch(t){return!1}}(t.substr(e));if(!n.isPayloadValid(r.type,f))throw new Error("invalid payload");r.data=f}return r}},{key:"destroy",value:function(){this.reconstructor&&this.reconstructor.finishedReconstruction()}}],[{key:"isPayloadValid",value:function(t,e){switch(t){case l.CONNECT:return"object"===r(e);case l.DISCONNECT:return void 0===e;case l.CONNECT_ERROR:return"string"==typeof e||"object"===r(e);case l.EVENT:case l.BINARY_EVENT:return Array.isArray(e)&&"string"==typeof e[0];case l.ACK:case l.BINARY_ACK:return Array.isArray(e)}}}]),n}(h);e.Decoder=b;var m=function(){function t(e){u(this,t),this.packet=e,this.buffers=[],this.reconPack=e}return p(t,[{key:"takeBinaryData",value:function(t){if(this.buffers.push(t),this.buffers.length===this.reconPack.attachments){var e=y.reconstructPacket(this.reconPack,this.buffers);return this.finishedReconstruction(),e}return null}},{key:"finishedReconstruction",value:function(){this.reconPack=null,this.buffers=[]}}]),t}()},function(t,e){var n=/^(?:(?![^:@]+:[^:@\/]*@)(http|https|ws|wss):\/\/)?((?:(([^:@]*)(?::([^:@]*))?)?@)?((?:[a-f0-9]{0,4}:){2,7}[a-f0-9]{0,4}|[^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/,r=["source","protocol","authority","userInfo","user","password","host","port","relative","path","directory","file","query","anchor"];t.exports=function(t){var e=t,o=t.indexOf("["),i=t.indexOf("]");-1!=o&&-1!=i&&(t=t.substring(0,o)+t.substring(o,i).replace(/:/g,";")+t.substring(i,t.length));for(var s,c,a=n.exec(t||""),u={},f=14;f--;)u[r[f]]=a[f]||"";return-1!=o&&-1!=i&&(u.source=e,u.host=u.host.substring(1,u.host.length-1).replace(/;/g,":"),u.authority=u.authority.replace("[","").replace("]","").replace(/;/g,":"),u.ipv6uri=!0),u.pathNames=function(t,e){var n=e.replace(/\/{2,9}/g,"/").split("/");"/"!=e.substr(0,1)&&0!==e.length||n.splice(0,1);"/"==e.substr(e.length-1,1)&&n.splice(n.length-1,1);return n}(0,u.path),u.queryKey=(s=u.query,c={},s.replace(/(?:^|&)([^&=]*)=?([^&]*)/g,(function(t,e,n){e&&(c[e]=n)})),c),u}},function(t,e,n){"use strict";function r(t){return(r="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t})(t)}function o(t,e){for(var n=0;n<e.length;n++){var r=e[n];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(t,r.key,r)}}function i(t,e,n){return(i="undefined"!=typeof Reflect&&Reflect.get?Reflect.get:function(t,e,n){var r=function(t,e){for(;!Object.prototype.hasOwnProperty.call(t,e)&&null!==(t=u(t)););return t}(t,e);if(r){var o=Object.getOwnPropertyDescriptor(r,e);return o.get?o.get.call(n):o.value}})(t,e,n||t)}function s(t,e){return(s=Object.setPrototypeOf||function(t,e){return t.__proto__=e,t})(t,e)}function c(t){var e=function(){if("undefined"==typeof Reflect||!Reflect.construct)return!1;if(Reflect.construct.sham)return!1;if("function"==typeof Proxy)return!0;try{return Date.prototype.toString.call(Reflect.construct(Date,[],(function(){}))),!0}catch(t){return!1}}();return function(){var n,r=u(t);if(e){var o=u(this).constructor;n=Reflect.construct(r,arguments,o)}else n=r.apply(this,arguments);return a(this,n)}}function a(t,e){return!e||"object"!==r(e)&&"function"!=typeof e?function(t){if(void 0===t)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return t}(t):e}function u(t){return(u=Object.setPrototypeOf?Object.getPrototypeOf:function(t){return t.__proto__||Object.getPrototypeOf(t)})(t)}Object.defineProperty(e,"__esModule",{value:!0}),e.Manager=void 0;var f=n(19),p=n(14),l=n(0),h=n(5),y=n(16),d=n(30),v=function(t){!function(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Super expression must either be null or a function");t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,writable:!0,configurable:!0}}),e&&s(t,e)}(v,t);var e,n,a,l=c(v);function v(t,e){var n;!function(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}(this,v),(n=l.call(this)).nsps={},n.subs=[],t&&"object"===r(t)&&(e=t,t=void 0),(e=e||{}).path=e.path||"/socket.io",n.opts=e,n.reconnection(!1!==e.reconnection),n.reconnectionAttempts(e.reconnectionAttempts||1/0),n.reconnectionDelay(e.reconnectionDelay||1e3),n.reconnectionDelayMax(e.reconnectionDelayMax||5e3),n.randomizationFactor(e.randomizationFactor||.5),n.backoff=new d({min:n.reconnectionDelay(),max:n.reconnectionDelayMax(),jitter:n.randomizationFactor()}),n.timeout(null==e.timeout?2e4:e.timeout),n._readyState="closed",n.uri=t;var o=e.parser||h;return n.encoder=new o.Encoder,n.decoder=new o.Decoder,n._autoConnect=!1!==e.autoConnect,n._autoConnect&&n.open(),n}return e=v,(n=[{key:"reconnection",value:function(t){return arguments.length?(this._reconnection=!!t,this):this._reconnection}},{key:"reconnectionAttempts",value:function(t){return void 0===t?this._reconnectionAttempts:(this._reconnectionAttempts=t,this)}},{key:"reconnectionDelay",value:function(t){var e;return void 0===t?this._reconnectionDelay:(this._reconnectionDelay=t,null===(e=this.backoff)||void 0===e||e.setMin(t),this)}},{key:"randomizationFactor",value:function(t){var e;return void 0===t?this._randomizationFactor:(this._randomizationFactor=t,null===(e=this.backoff)||void 0===e||e.setJitter(t),this)}},{key:"reconnectionDelayMax",value:function(t){var e;return void 0===t?this._reconnectionDelayMax:(this._reconnectionDelayMax=t,null===(e=this.backoff)||void 0===e||e.setMax(t),this)}},{key:"timeout",value:function(t){return arguments.length?(this._timeout=t,this):this._timeout}},{key:"maybeReconnectOnOpen",value:function(){!this._reconnecting&&this._reconnection&&0===this.backoff.attempts&&this.reconnect()}},{key:"open",value:function(t){var e=this;if(~this._readyState.indexOf("open"))return this;this.engine=f(this.uri,this.opts);var n=this.engine,r=this;this._readyState="opening",this.skipReconnect=!1;var o=y.on(n,"open",(function(){r.onopen(),t&&t()})),s=y.on(n,"error",(function(n){r.cleanup(),r._readyState="closed",i(u(v.prototype),"emit",e).call(e,"error",n),t?t(n):r.maybeReconnectOnOpen()}));if(!1!==this._timeout){var c=this._timeout;0===c&&o();var a=setTimeout((function(){o(),n.close(),n.emit("error",new Error("timeout"))}),c);this.subs.push((function(){clearTimeout(a)}))}return this.subs.push(o),this.subs.push(s),this}},{key:"connect",value:function(t){return this.open(t)}},{key:"onopen",value:function(){this.cleanup(),this._readyState="open",i(u(v.prototype),"emit",this).call(this,"open");var t=this.engine;this.subs.push(y.on(t,"ping",this.onping.bind(this)),y.on(t,"data",this.ondata.bind(this)),y.on(t,"error",this.onerror.bind(this)),y.on(t,"close",this.onclose.bind(this)),y.on(this.decoder,"decoded",this.ondecoded.bind(this)))}},{key:"onping",value:function(){i(u(v.prototype),"emit",this).call(this,"ping")}},{key:"ondata",value:function(t){this.decoder.add(t)}},{key:"ondecoded",value:function(t){i(u(v.prototype),"emit",this).call(this,"packet",t)}},{key:"onerror",value:function(t){i(u(v.prototype),"emit",this).call(this,"error",t)}},{key:"socket",value:function(t,e){var n=this.nsps[t];return n||(n=new p.Socket(this,t,e),this.nsps[t]=n),n}},{key:"_destroy",value:function(t){for(var e=0,n=Object.keys(this.nsps);e<n.length;e++){var r=n[e];if(this.nsps[r].active)return}this._close()}},{key:"_packet",value:function(t){t.query&&0===t.type&&(t.nsp+="?"+t.query);for(var e=this.encoder.encode(t),n=0;n<e.length;n++)this.engine.write(e[n],t.options)}},{key:"cleanup",value:function(){this.subs.forEach((function(t){return t()})),this.subs.length=0,this.decoder.destroy()}},{key:"_close",value:function(){this.skipReconnect=!0,this._reconnecting=!1,"opening"===this._readyState&&this.cleanup(),this.backoff.reset(),this._readyState="closed",this.engine&&this.engine.close()}},{key:"disconnect",value:function(){return this._close()}},{key:"onclose",value:function(t){this.cleanup(),this.backoff.reset(),this._readyState="closed",i(u(v.prototype),"emit",this).call(this,"close",t),this._reconnection&&!this.skipReconnect&&this.reconnect()}},{key:"reconnect",value:function(){var t=this;if(this._reconnecting||this.skipReconnect)return this;var e=this;if(this.backoff.attempts>=this._reconnectionAttempts)this.backoff.reset(),i(u(v.prototype),"emit",this).call(this,"reconnect_failed"),this._reconnecting=!1;else{var n=this.backoff.duration();this._reconnecting=!0;var r=setTimeout((function(){e.skipReconnect||(i(u(v.prototype),"emit",t).call(t,"reconnect_attempt",e.backoff.attempts),e.skipReconnect||e.open((function(n){n?(e._reconnecting=!1,e.reconnect(),i(u(v.prototype),"emit",t).call(t,"reconnect_error",n)):e.onreconnect()})))}),n);this.subs.push((function(){clearTimeout(r)}))}}},{key:"onreconnect",value:function(){var t=this.backoff.attempts;this._reconnecting=!1,this.backoff.reset(),i(u(v.prototype),"emit",this).call(this,"reconnect",t)}}])&&o(e.prototype,n),a&&o(e,a),v}(l);e.Manager=v},function(t,e,n){var r=n(9),o=n(22),i=n(26),s=n(27);e.polling=function(t){var e=!1,n=!1,s=!1!==t.jsonp;if("undefined"!=typeof location){var c="https:"===location.protocol,a=location.port;a||(a=c?443:80),e=t.hostname!==location.hostname||a!==t.port,n=t.secure!==c}if(t.xdomain=e,t.xscheme=n,"open"in new r(t)&&!t.forceJSONP)return new o(t);if(!s)throw new Error("JSONP disabled");return new i(t)},e.websocket=s},function(t,e,n){var r=n(21),o=n(2);t.exports=function(t){var e=t.xdomain,n=t.xscheme,i=t.enablesXDR;try{if("undefined"!=typeof XMLHttpRequest&&(!e||r))return new XMLHttpRequest}catch(t){}try{if("undefined"!=typeof XDomainRequest&&!n&&i)return new XDomainRequest}catch(t){}if(!e)try{return new(o[["Active"].concat("Object").join("X")])("Microsoft.XMLHTTP")}catch(t){}}},function(t,e,n){function r(t){return(r="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t})(t)}function o(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}function i(t,e){for(var n=0;n<e.length;n++){var r=e[n];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(t,r.key,r)}}function s(t,e){return(s=Object.setPrototypeOf||function(t,e){return t.__proto__=e,t})(t,e)}function c(t){var e=function(){if("undefined"==typeof Reflect||!Reflect.construct)return!1;if(Reflect.construct.sham)return!1;if("function"==typeof Proxy)return!0;try{return Date.prototype.toString.call(Reflect.construct(Date,[],(function(){}))),!0}catch(t){return!1}}();return function(){var n,r=u(t);if(e){var o=u(this).constructor;n=Reflect.construct(r,arguments,o)}else n=r.apply(this,arguments);return a(this,n)}}function a(t,e){return!e||"object"!==r(e)&&"function"!=typeof e?function(t){if(void 0===t)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return t}(t):e}function u(t){return(u=Object.setPrototypeOf?Object.getPrototypeOf:function(t){return t.__proto__||Object.getPrototypeOf(t)})(t)}var f=n(3),p=n(4),l=n(1),h=n(12),y=function(t){!function(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Super expression must either be null or a function");t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,writable:!0,configurable:!0}}),e&&s(t,e)}(u,t);var e,n,r,a=c(u);function u(){return o(this,u),a.apply(this,arguments)}return e=u,(n=[{key:"doOpen",value:function(){this.poll()}},{key:"pause",value:function(t){var e=this;function n(){e.readyState="paused",t()}if(this.readyState="pausing",this.polling||!this.writable){var r=0;this.polling&&(r++,this.once("pollComplete",(function(){--r||n()}))),this.writable||(r++,this.once("drain",(function(){--r||n()})))}else n()}},{key:"poll",value:function(){this.polling=!0,this.doPoll(),this.emit("poll")}},{key:"onData",value:function(t){var e=this;l.decodePayload(t,this.socket.binaryType).forEach((function(t,n,r){if("opening"===e.readyState&&"open"===t.type&&e.onOpen(),"close"===t.type)return e.onClose(),!1;e.onPacket(t)})),"closed"!==this.readyState&&(this.polling=!1,this.emit("pollComplete"),"open"===this.readyState&&this.poll())}},{key:"doClose",value:function(){var t=this;function e(){t.write([{type:"close"}])}"open"===this.readyState?e():this.once("open",e)}},{key:"write",value:function(t){var e=this;this.writable=!1,l.encodePayload(t,(function(t){e.doWrite(t,(function(){e.writable=!0,e.emit("drain")}))}))}},{key:"uri",value:function(){var t=this.query||{},e=this.opts.secure?"https":"http",n="";return!1!==this.opts.timestampRequests&&(t[this.opts.timestampParam]=h()),this.supportsBinary||t.sid||(t.b64=1),t=p.encode(t),this.opts.port&&("https"===e&&443!==Number(this.opts.port)||"http"===e&&80!==Number(this.opts.port))&&(n=":"+this.opts.port),t.length&&(t="?"+t),e+"://"+(-1!==this.opts.hostname.indexOf(":")?"["+this.opts.hostname+"]":this.opts.hostname)+n+this.opts.path+t}},{key:"name",get:function(){return"polling"}}])&&i(e.prototype,n),r&&i(e,r),u}(f);t.exports=y},function(t,e){var n=Object.create(null);n.open="0",n.close="1",n.ping="2",n.pong="3",n.message="4",n.upgrade="5",n.noop="6";var r=Object.create(null);Object.keys(n).forEach((function(t){r[n[t]]=t}));t.exports={PACKET_TYPES:n,PACKET_TYPES_REVERSE:r,ERROR_PACKET:{type:"error",data:"parser error"}}},function(t,e,n){"use strict";var r,o="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-_".split(""),i={},s=0,c=0;function a(t){var e="";do{e=o[t%64]+e,t=Math.floor(t/64)}while(t>0);return e}function u(){var t=a(+new Date);return t!==r?(s=0,r=t):t+"."+a(s++)}for(;c<64;c++)i[o[c]]=c;u.encode=a,u.decode=function(t){var e=0;for(c=0;c<t.length;c++)e=64*e+i[t.charAt(c)];return e},t.exports=u},function(t,e){t.exports.pick=function(t){for(var e=arguments.length,n=new Array(e>1?e-1:0),r=1;r<e;r++)n[r-1]=arguments[r];return n.reduce((function(e,n){return e[n]=t[n],e}),{})}},function(t,e,n){"use strict";function r(t){return(r="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t})(t)}function o(t,e){var n;if("undefined"==typeof Symbol||null==t[Symbol.iterator]){if(Array.isArray(t)||(n=function(t,e){if(!t)return;if("string"==typeof t)return i(t,e);var n=Object.prototype.toString.call(t).slice(8,-1);"Object"===n&&t.constructor&&(n=t.constructor.name);if("Map"===n||"Set"===n)return Array.from(t);if("Arguments"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n))return i(t,e)}(t))||e&&t&&"number"==typeof t.length){n&&(t=n);var r=0,o=function(){};return{s:o,n:function(){return r>=t.length?{done:!0}:{done:!1,value:t[r++]}},e:function(t){throw t},f:o}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}var s,c=!0,a=!1;return{s:function(){n=t[Symbol.iterator]()},n:function(){var t=n.next();return c=t.done,t},e:function(t){a=!0,s=t},f:function(){try{c||null==n.return||n.return()}finally{if(a)throw s}}}}function i(t,e){(null==e||e>t.length)&&(e=t.length);for(var n=0,r=new Array(e);n<e;n++)r[n]=t[n];return r}function s(t,e){for(var n=0;n<e.length;n++){var r=e[n];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(t,r.key,r)}}function c(t,e,n){return(c="undefined"!=typeof Reflect&&Reflect.get?Reflect.get:function(t,e,n){var r=function(t,e){for(;!Object.prototype.hasOwnProperty.call(t,e)&&null!==(t=p(t)););return t}(t,e);if(r){var o=Object.getOwnPropertyDescriptor(r,e);return o.get?o.get.call(n):o.value}})(t,e,n||t)}function a(t,e){return(a=Object.setPrototypeOf||function(t,e){return t.__proto__=e,t})(t,e)}function u(t){var e=function(){if("undefined"==typeof Reflect||!Reflect.construct)return!1;if(Reflect.construct.sham)return!1;if("function"==typeof Proxy)return!0;try{return Date.prototype.toString.call(Reflect.construct(Date,[],(function(){}))),!0}catch(t){return!1}}();return function(){var n,r=p(t);if(e){var o=p(this).constructor;n=Reflect.construct(r,arguments,o)}else n=r.apply(this,arguments);return f(this,n)}}function f(t,e){return!e||"object"!==r(e)&&"function"!=typeof e?function(t){if(void 0===t)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return t}(t):e}function p(t){return(p=Object.setPrototypeOf?Object.getPrototypeOf:function(t){return t.__proto__||Object.getPrototypeOf(t)})(t)}Object.defineProperty(e,"__esModule",{value:!0}),e.Socket=void 0;var l=n(5),h=n(0),y=n(16),d=Object.freeze({connect:1,connect_error:1,disconnect:1,disconnecting:1,newListener:1,removeListener:1}),v=function(t){!function(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Super expression must either be null or a function");t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,writable:!0,configurable:!0}}),e&&a(t,e)}(f,t);var e,n,r,i=u(f);function f(t,e,n){var r;return function(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}(this,f),(r=i.call(this)).receiveBuffer=[],r.sendBuffer=[],r.ids=0,r.acks={},r.flags={},r.io=t,r.nsp=e,r.ids=0,r.acks={},r.receiveBuffer=[],r.sendBuffer=[],r.connected=!1,r.disconnected=!0,r.flags={},n&&n.auth&&(r.auth=n.auth),r.io._autoConnect&&r.open(),r}return e=f,(n=[{key:"subEvents",value:function(){if(!this.subs){var t=this.io;this.subs=[y.on(t,"open",this.onopen.bind(this)),y.on(t,"packet",this.onpacket.bind(this)),y.on(t,"error",this.onerror.bind(this)),y.on(t,"close",this.onclose.bind(this))]}}},{key:"connect",value:function(){return this.connected||(this.subEvents(),this.io._reconnecting||this.io.open(),"open"===this.io._readyState&&this.onopen()),this}},{key:"open",value:function(){return this.connect()}},{key:"send",value:function(){for(var t=arguments.length,e=new Array(t),n=0;n<t;n++)e[n]=arguments[n];return e.unshift("message"),this.emit.apply(this,e),this}},{key:"emit",value:function(t){if(d.hasOwnProperty(t))throw new Error('"'+t+'" is a reserved event name');for(var e=arguments.length,n=new Array(e>1?e-1:0),r=1;r<e;r++)n[r-1]=arguments[r];n.unshift(t);var o={type:l.PacketType.EVENT,data:n,options:{}};o.options.compress=!1!==this.flags.compress,"function"==typeof n[n.length-1]&&(this.acks[this.ids]=n.pop(),o.id=this.ids++);var i=this.io.engine&&this.io.engine.transport&&this.io.engine.transport.writable,s=this.flags.volatile&&(!i||!this.connected);return s||(this.connected?this.packet(o):this.sendBuffer.push(o)),this.flags={},this}},{key:"packet",value:function(t){t.nsp=this.nsp,this.io._packet(t)}},{key:"onopen",value:function(){var t=this;"function"==typeof this.auth?this.auth((function(e){t.packet({type:l.PacketType.CONNECT,data:e})})):this.packet({type:l.PacketType.CONNECT,data:this.auth})}},{key:"onerror",value:function(t){this.connected||c(p(f.prototype),"emit",this).call(this,"connect_error",t)}},{key:"onclose",value:function(t){this.connected=!1,this.disconnected=!0,delete this.id,c(p(f.prototype),"emit",this).call(this,"disconnect",t)}},{key:"onpacket",value:function(t){if(t.nsp===this.nsp)switch(t.type){case l.PacketType.CONNECT:if(t.data&&t.data.sid){var e=t.data.sid;this.onconnect(e)}else c(p(f.prototype),"emit",this).call(this,"connect_error",new Error("It seems you are trying to reach a Socket.IO server in v2.x with a v3.x client, but they are not compatible (more information here: https://socket.io/docs/v3/migrating-from-2-x-to-3-0/)"));break;case l.PacketType.EVENT:case l.PacketType.BINARY_EVENT:this.onevent(t);break;case l.PacketType.ACK:case l.PacketType.BINARY_ACK:this.onack(t);break;case l.PacketType.DISCONNECT:this.ondisconnect();break;case l.PacketType.CONNECT_ERROR:var n=new Error(t.data.message);n.data=t.data.data,c(p(f.prototype),"emit",this).call(this,"connect_error",n)}}},{key:"onevent",value:function(t){var e=t.data||[];null!=t.id&&e.push(this.ack(t.id)),this.connected?this.emitEvent(e):this.receiveBuffer.push(Object.freeze(e))}},{key:"emitEvent",value:function(t){if(this._anyListeners&&this._anyListeners.length){var e,n=o(this._anyListeners.slice());try{for(n.s();!(e=n.n()).done;)e.value.apply(this,t)}catch(t){n.e(t)}finally{n.f()}}c(p(f.prototype),"emit",this).apply(this,t)}},{key:"ack",value:function(t){var e=this,n=!1;return function(){if(!n){n=!0;for(var r=arguments.length,o=new Array(r),i=0;i<r;i++)o[i]=arguments[i];e.packet({type:l.PacketType.ACK,id:t,data:o})}}}},{key:"onack",value:function(t){var e=this.acks[t.id];"function"==typeof e&&(e.apply(this,t.data),delete this.acks[t.id])}},{key:"onconnect",value:function(t){this.id=t,this.connected=!0,this.disconnected=!1,c(p(f.prototype),"emit",this).call(this,"connect"),this.emitBuffered()}},{key:"emitBuffered",value:function(){var t=this;this.receiveBuffer.forEach((function(e){return t.emitEvent(e)})),this.receiveBuffer=[],this.sendBuffer.forEach((function(e){return t.packet(e)})),this.sendBuffer=[]}},{key:"ondisconnect",value:function(){this.destroy(),this.onclose("io server disconnect")}},{key:"destroy",value:function(){this.subs&&(this.subs.forEach((function(t){return t()})),this.subs=void 0),this.io._destroy(this)}},{key:"disconnect",value:function(){return this.connected&&this.packet({type:l.PacketType.DISCONNECT}),this.destroy(),this.connected&&this.onclose("io client disconnect"),this}},{key:"close",value:function(){return this.disconnect()}},{key:"compress",value:function(t){return this.flags.compress=t,this}},{key:"onAny",value:function(t){return this._anyListeners=this._anyListeners||[],this._anyListeners.push(t),this}},{key:"prependAny",value:function(t){return this._anyListeners=this._anyListeners||[],this._anyListeners.unshift(t),this}},{key:"offAny",value:function(t){if(!this._anyListeners)return this;if(t){for(var e=this._anyListeners,n=0;n<e.length;n++)if(t===e[n])return e.splice(n,1),this}else this._anyListeners=[];return this}},{key:"listenersAny",value:function(){return this._anyListeners||[]}},{key:"active",get:function(){return!!this.subs}},{key:"volatile",get:function(){return this.flags.volatile=!0,this}}])&&s(e.prototype,n),r&&s(e,r),f}(h);e.Socket=v},function(t,e,n){"use strict";function r(t){return(r="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t})(t)}Object.defineProperty(e,"__esModule",{value:!0}),e.hasBinary=e.isBinary=void 0;var o="function"==typeof ArrayBuffer,i=Object.prototype.toString,s="function"==typeof Blob||"undefined"!=typeof Blob&&"[object BlobConstructor]"===i.call(Blob),c="function"==typeof File||"undefined"!=typeof File&&"[object FileConstructor]"===i.call(File);function a(t){return o&&(t instanceof ArrayBuffer||function(t){return"function"==typeof ArrayBuffer.isView?ArrayBuffer.isView(t):t.buffer instanceof ArrayBuffer}(t))||s&&t instanceof Blob||c&&t instanceof File}e.isBinary=a,e.hasBinary=function t(e,n){if(!e||"object"!==r(e))return!1;if(Array.isArray(e)){for(var o=0,i=e.length;o<i;o++)if(t(e[o]))return!0;return!1}if(a(e))return!0;if(e.toJSON&&"function"==typeof e.toJSON&&1===arguments.length)return t(e.toJSON(),!0);for(var s in e)if(Object.prototype.hasOwnProperty.call(e,s)&&t(e[s]))return!0;return!1}},function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.on=void 0,e.on=function(t,e,n){return t.on(e,n),function(){t.off(e,n)}}},function(t,e,n){"use strict";function r(t){return(r="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t})(t)}Object.defineProperty(e,"__esModule",{value:!0}),e.Socket=e.io=e.Manager=e.protocol=void 0;var o=n(18),i=n(7),s=n(14);Object.defineProperty(e,"Socket",{enumerable:!0,get:function(){return s.Socket}}),t.exports=e=a;var c=e.managers={};function a(t,e){"object"===r(t)&&(e=t,t=void 0),e=e||{};var n,s=o.url(t),a=s.source,u=s.id,f=s.path,p=c[u]&&f in c[u].nsps;return e.forceNew||e["force new connection"]||!1===e.multiplex||p?n=new i.Manager(a,e):(c[u]||(c[u]=new i.Manager(a,e)),n=c[u]),s.query&&!e.query&&(e.query=s.query),n.socket(s.path,e)}e.io=a;var u=n(5);Object.defineProperty(e,"protocol",{enumerable:!0,get:function(){return u.protocol}}),e.connect=a;var f=n(7);Object.defineProperty(e,"Manager",{enumerable:!0,get:function(){return f.Manager}})},function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.url=void 0;var r=n(6);e.url=function(t,e){var n=t;e=e||"undefined"!=typeof location&&location,null==t&&(t=e.protocol+"//"+e.host),"string"==typeof t&&("/"===t.charAt(0)&&(t="/"===t.charAt(1)?e.protocol+t:e.host+t),/^(https?|wss?):\/\//.test(t)||(t=void 0!==e?e.protocol+"//"+t:"https://"+t),n=r(t)),n.port||(/^(http|ws)$/.test(n.protocol)?n.port="80":/^(http|ws)s$/.test(n.protocol)&&(n.port="443")),n.path=n.path||"/";var o=-1!==n.host.indexOf(":")?"["+n.host+"]":n.host;return n.id=n.protocol+"://"+o+":"+n.port,n.href=n.protocol+"://"+o+(e&&e.port===n.port?"":":"+n.port),n}},function(t,e,n){var r=n(20);t.exports=function(t,e){return new r(t,e)},t.exports.Socket=r,t.exports.protocol=r.protocol,t.exports.Transport=n(3),t.exports.transports=n(8),t.exports.parser=n(1)},function(t,e,n){function r(){return(r=Object.assign||function(t){for(var e=1;e<arguments.length;e++){var n=arguments[e];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(t[r]=n[r])}return t}).apply(this,arguments)}function o(t){return(o="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t})(t)}function i(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}function s(t,e){for(var n=0;n<e.length;n++){var r=e[n];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(t,r.key,r)}}function c(t,e){return(c=Object.setPrototypeOf||function(t,e){return t.__proto__=e,t})(t,e)}function a(t){var e=function(){if("undefined"==typeof Reflect||!Reflect.construct)return!1;if(Reflect.construct.sham)return!1;if("function"==typeof Proxy)return!0;try{return Date.prototype.toString.call(Reflect.construct(Date,[],(function(){}))),!0}catch(t){return!1}}();return function(){var n,r=f(t);if(e){var o=f(this).constructor;n=Reflect.construct(r,arguments,o)}else n=r.apply(this,arguments);return u(this,n)}}function u(t,e){return!e||"object"!==o(e)&&"function"!=typeof e?function(t){if(void 0===t)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return t}(t):e}function f(t){return(f=Object.setPrototypeOf?Object.getPrototypeOf:function(t){return t.__proto__||Object.getPrototypeOf(t)})(t)}var p=n(8),l=n(0),h=n(1),y=n(6),d=n(4),v=function(t){!function(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Super expression must either be null or a function");t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,writable:!0,configurable:!0}}),e&&c(t,e)}(l,t);var e,n,u,f=a(l);function l(t){var e,n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return i(this,l),e=f.call(this),t&&"object"===o(t)&&(n=t,t=null),t?(t=y(t),n.hostname=t.host,n.secure="https"===t.protocol||"wss"===t.protocol,n.port=t.port,t.query&&(n.query=t.query)):n.host&&(n.hostname=y(n.host).host),e.secure=null!=n.secure?n.secure:"undefined"!=typeof location&&"https:"===location.protocol,n.hostname&&!n.port&&(n.port=e.secure?"443":"80"),e.hostname=n.hostname||("undefined"!=typeof location?location.hostname:"localhost"),e.port=n.port||("undefined"!=typeof location&&location.port?location.port:e.secure?443:80),e.transports=n.transports||["polling","websocket"],e.readyState="",e.writeBuffer=[],e.prevBufferLen=0,e.opts=r({path:"/engine.io",agent:!1,withCredentials:!1,upgrade:!0,jsonp:!0,timestampParam:"t",rememberUpgrade:!1,rejectUnauthorized:!0,perMessageDeflate:{threshold:1024},transportOptions:{}},n),e.opts.path=e.opts.path.replace(/\/$/,"")+"/","string"==typeof e.opts.query&&(e.opts.query=d.decode(e.opts.query)),e.id=null,e.upgrades=null,e.pingInterval=null,e.pingTimeout=null,e.pingTimeoutTimer=null,e.open(),e}return e=l,(n=[{key:"createTransport",value:function(t){var e=function(t){var e={};for(var n in t)t.hasOwnProperty(n)&&(e[n]=t[n]);return e}(this.opts.query);e.EIO=h.protocol,e.transport=t,this.id&&(e.sid=this.id);var n=r({},this.opts.transportOptions[t],this.opts,{query:e,socket:this,hostname:this.hostname,secure:this.secure,port:this.port});return new p[t](n)}},{key:"open",value:function(){var t;if(this.opts.rememberUpgrade&&l.priorWebsocketSuccess&&-1!==this.transports.indexOf("websocket"))t="websocket";else{if(0===this.transports.length){var e=this;return void setTimeout((function(){e.emit("error","No transports available")}),0)}t=this.transports[0]}this.readyState="opening";try{t=this.createTransport(t)}catch(t){return this.transports.shift(),void this.open()}t.open(),this.setTransport(t)}},{key:"setTransport",value:function(t){var e=this;this.transport&&this.transport.removeAllListeners(),this.transport=t,t.on("drain",(function(){e.onDrain()})).on("packet",(function(t){e.onPacket(t)})).on("error",(function(t){e.onError(t)})).on("close",(function(){e.onClose("transport close")}))}},{key:"probe",value:function(t){var e=this.createTransport(t,{probe:1}),n=!1,r=this;function o(){if(r.onlyBinaryUpgrades){var t=!this.supportsBinary&&r.transport.supportsBinary;n=n||t}n||(e.send([{type:"ping",data:"probe"}]),e.once("packet",(function(t){if(!n)if("pong"===t.type&&"probe"===t.data){if(r.upgrading=!0,r.emit("upgrading",e),!e)return;l.priorWebsocketSuccess="websocket"===e.name,r.transport.pause((function(){n||"closed"!==r.readyState&&(f(),r.setTransport(e),e.send([{type:"upgrade"}]),r.emit("upgrade",e),e=null,r.upgrading=!1,r.flush())}))}else{var o=new Error("probe error");o.transport=e.name,r.emit("upgradeError",o)}})))}function i(){n||(n=!0,f(),e.close(),e=null)}function s(t){var n=new Error("probe error: "+t);n.transport=e.name,i(),r.emit("upgradeError",n)}function c(){s("transport closed")}function a(){s("socket closed")}function u(t){e&&t.name!==e.name&&i()}function f(){e.removeListener("open",o),e.removeListener("error",s),e.removeListener("close",c),r.removeListener("close",a),r.removeListener("upgrading",u)}l.priorWebsocketSuccess=!1,e.once("open",o),e.once("error",s),e.once("close",c),this.once("close",a),this.once("upgrading",u),e.open()}},{key:"onOpen",value:function(){if(this.readyState="open",l.priorWebsocketSuccess="websocket"===this.transport.name,this.emit("open"),this.flush(),"open"===this.readyState&&this.opts.upgrade&&this.transport.pause)for(var t=0,e=this.upgrades.length;t<e;t++)this.probe(this.upgrades[t])}},{key:"onPacket",value:function(t){if("opening"===this.readyState||"open"===this.readyState||"closing"===this.readyState)switch(this.emit("packet",t),this.emit("heartbeat"),t.type){case"open":this.onHandshake(JSON.parse(t.data));break;case"ping":this.resetPingTimeout(),this.sendPacket("pong"),this.emit("pong");break;case"error":var e=new Error("server error");e.code=t.data,this.onError(e);break;case"message":this.emit("data",t.data),this.emit("message",t.data)}}},{key:"onHandshake",value:function(t){this.emit("handshake",t),this.id=t.sid,this.transport.query.sid=t.sid,this.upgrades=this.filterUpgrades(t.upgrades),this.pingInterval=t.pingInterval,this.pingTimeout=t.pingTimeout,this.onOpen(),"closed"!==this.readyState&&this.resetPingTimeout()}},{key:"resetPingTimeout",value:function(){var t=this;clearTimeout(this.pingTimeoutTimer),this.pingTimeoutTimer=setTimeout((function(){t.onClose("ping timeout")}),this.pingInterval+this.pingTimeout)}},{key:"onDrain",value:function(){this.writeBuffer.splice(0,this.prevBufferLen),this.prevBufferLen=0,0===this.writeBuffer.length?this.emit("drain"):this.flush()}},{key:"flush",value:function(){"closed"!==this.readyState&&this.transport.writable&&!this.upgrading&&this.writeBuffer.length&&(this.transport.send(this.writeBuffer),this.prevBufferLen=this.writeBuffer.length,this.emit("flush"))}},{key:"write",value:function(t,e,n){return this.sendPacket("message",t,e,n),this}},{key:"send",value:function(t,e,n){return this.sendPacket("message",t,e,n),this}},{key:"sendPacket",value:function(t,e,n,r){if("function"==typeof e&&(r=e,e=void 0),"function"==typeof n&&(r=n,n=null),"closing"!==this.readyState&&"closed"!==this.readyState){(n=n||{}).compress=!1!==n.compress;var o={type:t,data:e,options:n};this.emit("packetCreate",o),this.writeBuffer.push(o),r&&this.once("flush",r),this.flush()}}},{key:"close",value:function(){var t=this;function e(){t.onClose("forced close"),t.transport.close()}function n(){t.removeListener("upgrade",n),t.removeListener("upgradeError",n),e()}function r(){t.once("upgrade",n),t.once("upgradeError",n)}return"opening"!==this.readyState&&"open"!==this.readyState||(this.readyState="closing",this.writeBuffer.length?this.once("drain",(function(){this.upgrading?r():e()})):this.upgrading?r():e()),this}},{key:"onError",value:function(t){l.priorWebsocketSuccess=!1,this.emit("error",t),this.onClose("transport error",t)}},{key:"onClose",value:function(t,e){"opening"!==this.readyState&&"open"!==this.readyState&&"closing"!==this.readyState||(clearTimeout(this.pingIntervalTimer),clearTimeout(this.pingTimeoutTimer),this.transport.removeAllListeners("close"),this.transport.close(),this.transport.removeAllListeners(),this.readyState="closed",this.id=null,this.emit("close",t,e),this.writeBuffer=[],this.prevBufferLen=0)}},{key:"filterUpgrades",value:function(t){for(var e=[],n=0,r=t.length;n<r;n++)~this.transports.indexOf(t[n])&&e.push(t[n]);return e}}])&&s(e.prototype,n),u&&s(e,u),l}(l);v.priorWebsocketSuccess=!1,v.protocol=h.protocol,t.exports=v},function(t,e){try{t.exports="undefined"!=typeof XMLHttpRequest&&"withCredentials"in new XMLHttpRequest}catch(e){t.exports=!1}},function(t,e,n){function r(t){return(r="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t})(t)}function o(){return(o=Object.assign||function(t){for(var e=1;e<arguments.length;e++){var n=arguments[e];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(t[r]=n[r])}return t}).apply(this,arguments)}function i(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}function s(t,e){for(var n=0;n<e.length;n++){var r=e[n];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(t,r.key,r)}}function c(t,e,n){return e&&s(t.prototype,e),n&&s(t,n),t}function a(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Super expression must either be null or a function");t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,writable:!0,configurable:!0}}),e&&u(t,e)}function u(t,e){return(u=Object.setPrototypeOf||function(t,e){return t.__proto__=e,t})(t,e)}function f(t){var e=function(){if("undefined"==typeof Reflect||!Reflect.construct)return!1;if(Reflect.construct.sham)return!1;if("function"==typeof Proxy)return!0;try{return Date.prototype.toString.call(Reflect.construct(Date,[],(function(){}))),!0}catch(t){return!1}}();return function(){var n,r=l(t);if(e){var o=l(this).constructor;n=Reflect.construct(r,arguments,o)}else n=r.apply(this,arguments);return p(this,n)}}function p(t,e){return!e||"object"!==r(e)&&"function"!=typeof e?function(t){if(void 0===t)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return t}(t):e}function l(t){return(l=Object.setPrototypeOf?Object.getPrototypeOf:function(t){return t.__proto__||Object.getPrototypeOf(t)})(t)}var h=n(9),y=n(10),d=n(0),v=n(13).pick,b=n(2);function m(){}var g=null!=new h({xdomain:!1}).responseType,k=function(t){a(n,t);var e=f(n);function n(t){var r;if(i(this,n),r=e.call(this,t),"undefined"!=typeof location){var o="https:"===location.protocol,s=location.port;s||(s=o?443:80),r.xd="undefined"!=typeof location&&t.hostname!==location.hostname||s!==t.port,r.xs=t.secure!==o}var c=t&&t.forceBase64;return r.supportsBinary=g&&!c,r}return c(n,[{key:"request",value:function(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};return o(t,{xd:this.xd,xs:this.xs},this.opts),new w(this.uri(),t)}},{key:"doWrite",value:function(t,e){var n=this.request({method:"POST",data:t}),r=this;n.on("success",e),n.on("error",(function(t){r.onError("xhr post error",t)}))}},{key:"doPoll",value:function(){var t=this.request(),e=this;t.on("data",(function(t){e.onData(t)})),t.on("error",(function(t){e.onError("xhr poll error",t)})),this.pollXhr=t}}]),n}(y),w=function(t){a(n,t);var e=f(n);function n(t,r){var o;return i(this,n),(o=e.call(this)).opts=r,o.method=r.method||"GET",o.uri=t,o.async=!1!==r.async,o.data=void 0!==r.data?r.data:null,o.create(),o}return c(n,[{key:"create",value:function(){var t=v(this.opts,"agent","enablesXDR","pfx","key","passphrase","cert","ca","ciphers","rejectUnauthorized");t.xdomain=!!this.opts.xd,t.xscheme=!!this.opts.xs;var e=this.xhr=new h(t),r=this;try{e.open(this.method,this.uri,this.async);try{if(this.opts.extraHeaders)for(var o in e.setDisableHeaderCheck&&e.setDisableHeaderCheck(!0),this.opts.extraHeaders)this.opts.extraHeaders.hasOwnProperty(o)&&e.setRequestHeader(o,this.opts.extraHeaders[o])}catch(t){}if("POST"===this.method)try{e.setRequestHeader("Content-type","text/plain;charset=UTF-8")}catch(t){}try{e.setRequestHeader("Accept","*/*")}catch(t){}"withCredentials"in e&&(e.withCredentials=this.opts.withCredentials),this.opts.requestTimeout&&(e.timeout=this.opts.requestTimeout),this.hasXDR()?(e.onload=function(){r.onLoad()},e.onerror=function(){r.onError(e.responseText)}):e.onreadystatechange=function(){4===e.readyState&&(200===e.status||1223===e.status?r.onLoad():setTimeout((function(){r.onError("number"==typeof e.status?e.status:0)}),0))},e.send(this.data)}catch(t){return void setTimeout((function(){r.onError(t)}),0)}"undefined"!=typeof document&&(this.index=n.requestsCount++,n.requests[this.index]=this)}},{key:"onSuccess",value:function(){this.emit("success"),this.cleanup()}},{key:"onData",value:function(t){this.emit("data",t),this.onSuccess()}},{key:"onError",value:function(t){this.emit("error",t),this.cleanup(!0)}},{key:"cleanup",value:function(t){if(void 0!==this.xhr&&null!==this.xhr){if(this.hasXDR()?this.xhr.onload=this.xhr.onerror=m:this.xhr.onreadystatechange=m,t)try{this.xhr.abort()}catch(t){}"undefined"!=typeof document&&delete n.requests[this.index],this.xhr=null}}},{key:"onLoad",value:function(){var t=this.xhr.responseText;null!==t&&this.onData(t)}},{key:"hasXDR",value:function(){return"undefined"!=typeof XDomainRequest&&!this.xs&&this.enablesXDR}},{key:"abort",value:function(){this.cleanup()}}]),n}(d);if(w.requestsCount=0,w.requests={},"undefined"!=typeof document)if("function"==typeof attachEvent)attachEvent("onunload",_);else if("function"==typeof addEventListener){addEventListener("onpagehide"in b?"pagehide":"unload",_,!1)}function _(){for(var t in w.requests)w.requests.hasOwnProperty(t)&&w.requests[t].abort()}t.exports=k,t.exports.Request=w},function(t,e,n){var r=n(11).PACKET_TYPES,o="function"==typeof Blob||"undefined"!=typeof Blob&&"[object BlobConstructor]"===Object.prototype.toString.call(Blob),i="function"==typeof ArrayBuffer,s=function(t,e){var n=new FileReader;return n.onload=function(){var t=n.result.split(",")[1];e("b"+t)},n.readAsDataURL(t)};t.exports=function(t,e,n){var c,a=t.type,u=t.data;return o&&u instanceof Blob?e?n(u):s(u,n):i&&(u instanceof ArrayBuffer||(c=u,"function"==typeof ArrayBuffer.isView?ArrayBuffer.isView(c):c&&c.buffer instanceof ArrayBuffer))?e?n(u instanceof ArrayBuffer?u:u.buffer):s(new Blob([u]),n):n(r[a]+(u||""))}},function(t,e,n){var r,o=n(11),i=o.PACKET_TYPES_REVERSE,s=o.ERROR_PACKET;"function"==typeof ArrayBuffer&&(r=n(25));var c=function(t,e){if(r){var n=r.decode(t);return a(n,e)}return{base64:!0,data:t}},a=function(t,e){switch(e){case"blob":return t instanceof ArrayBuffer?new Blob([t]):t;case"arraybuffer":default:return t}};t.exports=function(t,e){if("string"!=typeof t)return{type:"message",data:a(t,e)};var n=t.charAt(0);return"b"===n?{type:"message",data:c(t.substring(1),e)}:i[n]?t.length>1?{type:i[n],data:t.substring(1)}:{type:i[n]}:s}},function(t,e){!function(t){"use strict";e.encode=function(e){var n,r=new Uint8Array(e),o=r.length,i="";for(n=0;n<o;n+=3)i+=t[r[n]>>2],i+=t[(3&r[n])<<4|r[n+1]>>4],i+=t[(15&r[n+1])<<2|r[n+2]>>6],i+=t[63&r[n+2]];return o%3==2?i=i.substring(0,i.length-1)+"=":o%3==1&&(i=i.substring(0,i.length-2)+"=="),i},e.decode=function(e){var n,r,o,i,s,c=.75*e.length,a=e.length,u=0;"="===e[e.length-1]&&(c--,"="===e[e.length-2]&&c--);var f=new ArrayBuffer(c),p=new Uint8Array(f);for(n=0;n<a;n+=4)r=t.indexOf(e[n]),o=t.indexOf(e[n+1]),i=t.indexOf(e[n+2]),s=t.indexOf(e[n+3]),p[u++]=r<<2|o>>4,p[u++]=(15&o)<<4|i>>2,p[u++]=(3&i)<<6|63&s;return f}}("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/")},function(t,e,n){function r(t){return(r="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t})(t)}function o(t,e){for(var n=0;n<e.length;n++){var r=e[n];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(t,r.key,r)}}function i(t,e,n){return(i="undefined"!=typeof Reflect&&Reflect.get?Reflect.get:function(t,e,n){var r=function(t,e){for(;!Object.prototype.hasOwnProperty.call(t,e)&&null!==(t=f(t)););return t}(t,e);if(r){var o=Object.getOwnPropertyDescriptor(r,e);return o.get?o.get.call(n):o.value}})(t,e,n||t)}function s(t,e){return(s=Object.setPrototypeOf||function(t,e){return t.__proto__=e,t})(t,e)}function c(t){var e=function(){if("undefined"==typeof Reflect||!Reflect.construct)return!1;if(Reflect.construct.sham)return!1;if("function"==typeof Proxy)return!0;try{return Date.prototype.toString.call(Reflect.construct(Date,[],(function(){}))),!0}catch(t){return!1}}();return function(){var n,r=f(t);if(e){var o=f(this).constructor;n=Reflect.construct(r,arguments,o)}else n=r.apply(this,arguments);return a(this,n)}}function a(t,e){return!e||"object"!==r(e)&&"function"!=typeof e?u(t):e}function u(t){if(void 0===t)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return t}function f(t){return(f=Object.setPrototypeOf?Object.getPrototypeOf:function(t){return t.__proto__||Object.getPrototypeOf(t)})(t)}var p,l=n(10),h=n(2),y=/\n/g,d=/\\n/g;function v(){}var b=function(t){!function(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Super expression must either be null or a function");t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,writable:!0,configurable:!0}}),e&&s(t,e)}(l,t);var e,n,r,a=c(l);function l(t){var e;!function(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}(this,l),(e=a.call(this,t)).query=e.query||{},p||(p=h.___eio=h.___eio||[]),e.index=p.length;var n=u(e);return p.push((function(t){n.onData(t)})),e.query.j=e.index,"function"==typeof addEventListener&&addEventListener("beforeunload",(function(){n.script&&(n.script.onerror=v)}),!1),e}return e=l,(n=[{key:"doClose",value:function(){this.script&&(this.script.parentNode.removeChild(this.script),this.script=null),this.form&&(this.form.parentNode.removeChild(this.form),this.form=null,this.iframe=null),i(f(l.prototype),"doClose",this).call(this)}},{key:"doPoll",value:function(){var t=this,e=document.createElement("script");this.script&&(this.script.parentNode.removeChild(this.script),this.script=null),e.async=!0,e.src=this.uri(),e.onerror=function(e){t.onError("jsonp poll error",e)};var n=document.getElementsByTagName("script")[0];n?n.parentNode.insertBefore(e,n):(document.head||document.body).appendChild(e),this.script=e,"undefined"!=typeof navigator&&/gecko/i.test(navigator.userAgent)&&setTimeout((function(){var t=document.createElement("iframe");document.body.appendChild(t),document.body.removeChild(t)}),100)}},{key:"doWrite",value:function(t,e){var n,r=this;if(!this.form){var o=document.createElement("form"),i=document.createElement("textarea"),s=this.iframeId="eio_iframe_"+this.index;o.className="socketio",o.style.position="absolute",o.style.top="-1000px",o.style.left="-1000px",o.target=s,o.method="POST",o.setAttribute("accept-charset","utf-8"),i.name="d",o.appendChild(i),document.body.appendChild(o),this.form=o,this.area=i}function c(){a(),e()}function a(){if(r.iframe)try{r.form.removeChild(r.iframe)}catch(t){r.onError("jsonp polling iframe removal error",t)}try{var t='<iframe src="javascript:0" name="'+r.iframeId+'">';n=document.createElement(t)}catch(t){(n=document.createElement("iframe")).name=r.iframeId,n.src="javascript:0"}n.id=r.iframeId,r.form.appendChild(n),r.iframe=n}this.form.action=this.uri(),a(),t=t.replace(d,"\\\n"),this.area.value=t.replace(y,"\\n");try{this.form.submit()}catch(t){}this.iframe.attachEvent?this.iframe.onreadystatechange=function(){"complete"===r.iframe.readyState&&c()}:this.iframe.onload=c}},{key:"supportsBinary",get:function(){return!1}}])&&o(e.prototype,n),r&&o(e,r),l}(l);t.exports=b},function(t,e,n){function r(t){return(r="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t})(t)}function o(t,e){for(var n=0;n<e.length;n++){var r=e[n];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(t,r.key,r)}}function i(t,e){return(i=Object.setPrototypeOf||function(t,e){return t.__proto__=e,t})(t,e)}function s(t){var e=function(){if("undefined"==typeof Reflect||!Reflect.construct)return!1;if(Reflect.construct.sham)return!1;if("function"==typeof Proxy)return!0;try{return Date.prototype.toString.call(Reflect.construct(Date,[],(function(){}))),!0}catch(t){return!1}}();return function(){var n,r=a(t);if(e){var o=a(this).constructor;n=Reflect.construct(r,arguments,o)}else n=r.apply(this,arguments);return c(this,n)}}function c(t,e){return!e||"object"!==r(e)&&"function"!=typeof e?function(t){if(void 0===t)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return t}(t):e}function a(t){return(a=Object.setPrototypeOf?Object.getPrototypeOf:function(t){return t.__proto__||Object.getPrototypeOf(t)})(t)}var u=n(3),f=n(1),p=n(4),l=n(12),h=n(13).pick,y=n(28),d=y.WebSocket,v=y.usingBrowserWebSocket,b=y.defaultBinaryType,m="undefined"!=typeof navigator&&"string"==typeof navigator.product&&"reactnative"===navigator.product.toLowerCase(),g=function(t){!function(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Super expression must either be null or a function");t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,writable:!0,configurable:!0}}),e&&i(t,e)}(a,t);var e,n,r,c=s(a);function a(t){var e;return function(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}(this,a),(e=c.call(this,t)).supportsBinary=!t.forceBase64,e}return e=a,(n=[{key:"doOpen",value:function(){if(this.check()){var t=this.uri(),e=this.opts.protocols,n=m?{}:h(this.opts,"agent","perMessageDeflate","pfx","key","passphrase","cert","ca","ciphers","rejectUnauthorized","localAddress");this.opts.extraHeaders&&(n.headers=this.opts.extraHeaders);try{this.ws=v&&!m?e?new d(t,e):new d(t):new d(t,e,n)}catch(t){return this.emit("error",t)}this.ws.binaryType=this.socket.binaryType||b,this.addEventListeners()}}},{key:"addEventListeners",value:function(){var t=this;this.ws.onopen=function(){t.onOpen()},this.ws.onclose=function(){t.onClose()},this.ws.onmessage=function(e){t.onData(e.data)},this.ws.onerror=function(e){t.onError("websocket error",e)}}},{key:"write",value:function(t){var e=this;this.writable=!1;for(var n=t.length,r=0,o=n;r<o;r++)!function(t){f.encodePacket(t,e.supportsBinary,(function(r){var o={};v||(t.options&&(o.compress=t.options.compress),e.opts.perMessageDeflate&&("string"==typeof r?Buffer.byteLength(r):r.length)<e.opts.perMessageDeflate.threshold&&(o.compress=!1));try{v?e.ws.send(r):e.ws.send(r,o)}catch(t){}--n||(e.emit("flush"),setTimeout((function(){e.writable=!0,e.emit("drain")}),0))}))}(t[r])}},{key:"onClose",value:function(){u.prototype.onClose.call(this)}},{key:"doClose",value:function(){void 0!==this.ws&&this.ws.close()}},{key:"uri",value:function(){var t=this.query||{},e=this.opts.secure?"wss":"ws",n="";return this.opts.port&&("wss"===e&&443!==Number(this.opts.port)||"ws"===e&&80!==Number(this.opts.port))&&(n=":"+this.opts.port),this.opts.timestampRequests&&(t[this.opts.timestampParam]=l()),this.supportsBinary||(t.b64=1),(t=p.encode(t)).length&&(t="?"+t),e+"://"+(-1!==this.opts.hostname.indexOf(":")?"["+this.opts.hostname+"]":this.opts.hostname)+n+this.opts.path+t}},{key:"check",value:function(){return!(!d||"__initialize"in d&&this.name===a.prototype.name)}},{key:"name",get:function(){return"websocket"}}])&&o(e.prototype,n),r&&o(e,r),a}(u);t.exports=g},function(t,e,n){var r=n(2);t.exports={WebSocket:r.WebSocket||r.MozWebSocket,usingBrowserWebSocket:!0,defaultBinaryType:"arraybuffer"}},function(t,e,n){"use strict";function r(t){return(r="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t})(t)}Object.defineProperty(e,"__esModule",{value:!0}),e.reconstructPacket=e.deconstructPacket=void 0;var o=n(15);e.deconstructPacket=function(t){var e=[],n=t.data,i=t;return i.data=function t(e,n){if(!e)return e;if(o.isBinary(e)){var i={_placeholder:!0,num:n.length};return n.push(e),i}if(Array.isArray(e)){for(var s=new Array(e.length),c=0;c<e.length;c++)s[c]=t(e[c],n);return s}if("object"===r(e)&&!(e instanceof Date)){var a={};for(var u in e)e.hasOwnProperty(u)&&(a[u]=t(e[u],n));return a}return e}(n,e),i.attachments=e.length,{packet:i,buffers:e}},e.reconstructPacket=function(t,e){return t.data=function t(e,n){if(!e)return e;if(e&&e._placeholder)return n[e.num];if(Array.isArray(e))for(var o=0;o<e.length;o++)e[o]=t(e[o],n);else if("object"===r(e))for(var i in e)e.hasOwnProperty(i)&&(e[i]=t(e[i],n));return e}(t.data,e),t.attachments=void 0,t}},function(t,e){function n(t){t=t||{},this.ms=t.min||100,this.max=t.max||1e4,this.factor=t.factor||2,this.jitter=t.jitter>0&&t.jitter<=1?t.jitter:0,this.attempts=0}t.exports=n,n.prototype.duration=function(){var t=this.ms*Math.pow(this.factor,this.attempts++);if(this.jitter){var e=Math.random(),n=Math.floor(e*this.jitter*t);t=0==(1&Math.floor(10*e))?t-n:t+n}return 0|Math.min(t,this.max)},n.prototype.reset=function(){this.attempts=0},n.prototype.setMin=function(t){this.ms=t},n.prototype.setMax=function(t){this.max=t},n.prototype.setJitter=function(t){this.jitter=t}}])}));
(() => {
function e(e, t, n, r) {
Object.defineProperty(e, t, {
get: n,
set: r,
enumerable: !0,
configurable: !0,
});
}
function t(e) {
return e && e.__esModule ? e.default : e;
}
class n {
constructor() {
(this.chunkedMTU = 16300),
(this._dataCount = 1),
(this.chunk = (e) => {
let t = [],
n = e.byteLength,
r = Math.ceil(n / this.chunkedMTU),
i = 0,
o = 0;
for (; o < n; ) {
let s = Math.min(n, o + this.chunkedMTU),
a = e.slice(o, s),
c = { __peerData: this._dataCount, n: i, data: a, total: r };
t.push(c), (o = s), i++;
}
return this._dataCount++, t;
});
}
}
class r {
append_buffer(e) {
this.flush(), this._parts.push(e);
}
append(e) {
this._pieces.push(e);
}
flush() {
if (this._pieces.length > 0) {
let e = new Uint8Array(this._pieces);
this._parts.push(e), (this._pieces = []);
}
}
toArrayBuffer() {
let e = [];
for (let t of this._parts) e.push(t);
return (function (e) {
let t = 0;
for (let n of e) t += n.byteLength;
let n = new Uint8Array(t),
r = 0;
for (let t of e) {
let e = new Uint8Array(t.buffer, t.byteOffset, t.byteLength);
n.set(e, r), (r += t.byteLength);
}
return n;
})(e).buffer;
}
constructor() {
(this.encoder = new TextEncoder()),
(this._pieces = []),
(this._parts = []);
}
}
function i(e) {
return new s(e).unpack();
}
function o(e) {
let t = new a(),
n = t.pack(e);
return n instanceof Promise ? n.then(() => t.getBuffer()) : t.getBuffer();
}
class s {
unpack() {
let e;
let t = this.unpack_uint8();
if (t < 128) return t;
if ((224 ^ t) < 32) return (224 ^ t) - 32;
if ((e = 160 ^ t) <= 15) return this.unpack_raw(e);
if ((e = 176 ^ t) <= 15) return this.unpack_string(e);
if ((e = 144 ^ t) <= 15) return this.unpack_array(e);
if ((e = 128 ^ t) <= 15) return this.unpack_map(e);
switch (t) {
case 192:
return null;
case 193:
case 212:
case 213:
case 214:
case 215:
return;
case 194:
return !1;
case 195:
return !0;
case 202:
return this.unpack_float();
case 203:
return this.unpack_double();
case 204:
return this.unpack_uint8();
case 205:
return this.unpack_uint16();
case 206:
return this.unpack_uint32();
case 207:
return this.unpack_uint64();
case 208:
return this.unpack_int8();
case 209:
return this.unpack_int16();
case 210:
return this.unpack_int32();
case 211:
return this.unpack_int64();
case 216:
return (e = this.unpack_uint16()), this.unpack_string(e);
case 217:
return (e = this.unpack_uint32()), this.unpack_string(e);
case 218:
return (e = this.unpack_uint16()), this.unpack_raw(e);
case 219:
return (e = this.unpack_uint32()), this.unpack_raw(e);
case 220:
return (e = this.unpack_uint16()), this.unpack_array(e);
case 221:
return (e = this.unpack_uint32()), this.unpack_array(e);
case 222:
return (e = this.unpack_uint16()), this.unpack_map(e);
case 223:
return (e = this.unpack_uint32()), this.unpack_map(e);
}
}
unpack_uint8() {
let e = 255 & this.dataView[this.index];
return this.index++, e;
}
unpack_uint16() {
let e = this.read(2),
t = (255 & e[0]) * 256 + (255 & e[1]);
return (this.index += 2), t;
}
unpack_uint32() {
let e = this.read(4),
t = ((256 * e[0] + e[1]) * 256 + e[2]) * 256 + e[3];
return (this.index += 4), t;
}
unpack_uint64() {
let e = this.read(8),
t =
((((((256 * e[0] + e[1]) * 256 + e[2]) * 256 + e[3]) * 256 + e[4]) *
256 +
e[5]) *
256 +
e[6]) *
256 +
e[7];
return (this.index += 8), t;
}
unpack_int8() {
let e = this.unpack_uint8();
return e < 128 ? e : e - 256;
}
unpack_int16() {
let e = this.unpack_uint16();
return e < 32768 ? e : e - 65536;
}
unpack_int32() {
let e = this.unpack_uint32();
return e < 2147483648 ? e : e - 4294967296;
}
unpack_int64() {
let e = this.unpack_uint64();
return e < 0x7fffffffffffffff ? e : e - 18446744073709552e3;
}
unpack_raw(e) {
if (this.length < this.index + e)
throw Error(
`BinaryPackFailure: index is out of range ${this.index} ${e} ${this.length}`
);
let t = this.dataBuffer.slice(this.index, this.index + e);
return (this.index += e), t;
}
unpack_string(e) {
let t, n;
let r = this.read(e),
i = 0,
o = "";
for (; i < e; )
(t = r[i]) < 160
? ((n = t), i++)
: (192 ^ t) < 32
? ((n = ((31 & t) << 6) | (63 & r[i + 1])), (i += 2))
: (224 ^ t) < 16
? ((n = ((15 & t) << 12) | ((63 & r[i + 1]) << 6) | (63 & r[i + 2])),
(i += 3))
: ((n =
((7 & t) << 18) |
((63 & r[i + 1]) << 12) |
((63 & r[i + 2]) << 6) |
(63 & r[i + 3])),
(i += 4)),
(o += String.fromCodePoint(n));
return (this.index += e), o;
}
unpack_array(e) {
let t = Array(e);
for (let n = 0; n < e; n++) t[n] = this.unpack();
return t;
}
unpack_map(e) {
let t = {};
for (let n = 0; n < e; n++) t[this.unpack()] = this.unpack();
return t;
}
unpack_float() {
let e = this.unpack_uint32();
return (
(0 == e >> 31 ? 1 : -1) *
((8388607 & e) | 8388608) *
2 ** (((e >> 23) & 255) - 127 - 23)
);
}
unpack_double() {
let e = this.unpack_uint32(),
t = this.unpack_uint32(),
n = ((e >> 20) & 2047) - 1023;
return (
(0 == e >> 31 ? 1 : -1) *
(((1048575 & e) | 1048576) * 2 ** (n - 20) + t * 2 ** (n - 52))
);
}
read(e) {
let t = this.index;
if (t + e <= this.length) return this.dataView.subarray(t, t + e);
throw Error("BinaryPackFailure: read index out of range");
}
constructor(e) {
(this.index = 0),
(this.dataBuffer = e),
(this.dataView = new Uint8Array(this.dataBuffer)),
(this.length = this.dataBuffer.byteLength);
}
}
class a {
getBuffer() {
return this._bufferBuilder.toArrayBuffer();
}
pack(e) {
if ("string" == typeof e) this.pack_string(e);
else if ("number" == typeof e)
Math.floor(e) === e ? this.pack_integer(e) : this.pack_double(e);
else if ("boolean" == typeof e)
!0 === e
? this._bufferBuilder.append(195)
: !1 === e && this._bufferBuilder.append(194);
else if (void 0 === e) this._bufferBuilder.append(192);
else if ("object" == typeof e) {
if (null === e) this._bufferBuilder.append(192);
else {
let t = e.constructor;
if (e instanceof Array) {
let t = this.pack_array(e);
if (t instanceof Promise)
return t.then(() => this._bufferBuilder.flush());
} else if (e instanceof ArrayBuffer) this.pack_bin(new Uint8Array(e));
else if ("BYTES_PER_ELEMENT" in e)
this.pack_bin(new Uint8Array(e.buffer, e.byteOffset, e.byteLength));
else if (e instanceof Date) this.pack_string(e.toString());
else if (e instanceof Blob)
return e.arrayBuffer().then((e) => {
this.pack_bin(new Uint8Array(e)), this._bufferBuilder.flush();
});
else if (t == Object || t.toString().startsWith("class")) {
let t = this.pack_object(e);
if (t instanceof Promise)
return t.then(() => this._bufferBuilder.flush());
} else throw Error(`Type "${t.toString()}" not yet supported`);
}
} else throw Error(`Type "${typeof e}" not yet supported`);
this._bufferBuilder.flush();
}
pack_bin(e) {
let t = e.length;
if (t <= 15) this.pack_uint8(160 + t);
else if (t <= 65535) this._bufferBuilder.append(218), this.pack_uint16(t);
else if (t <= 4294967295)
this._bufferBuilder.append(219), this.pack_uint32(t);
else throw Error("Invalid length");
this._bufferBuilder.append_buffer(e);
}
pack_string(e) {
let t = this._textEncoder.encode(e),
n = t.length;
if (n <= 15) this.pack_uint8(176 + n);
else if (n <= 65535) this._bufferBuilder.append(216), this.pack_uint16(n);
else if (n <= 4294967295)
this._bufferBuilder.append(217), this.pack_uint32(n);
else throw Error("Invalid length");
this._bufferBuilder.append_buffer(t);
}
pack_array(e) {
let t = e.length;
if (t <= 15) this.pack_uint8(144 + t);
else if (t <= 65535) this._bufferBuilder.append(220), this.pack_uint16(t);
else if (t <= 4294967295)
this._bufferBuilder.append(221), this.pack_uint32(t);
else throw Error("Invalid length");
let n = (r) => {
if (r < t) {
let t = this.pack(e[r]);
return t instanceof Promise ? t.then(() => n(r + 1)) : n(r + 1);
}
};
return n(0);
}
pack_integer(e) {
if (e >= -32 && e <= 127) this._bufferBuilder.append(255 & e);
else if (e >= 0 && e <= 255)
this._bufferBuilder.append(204), this.pack_uint8(e);
else if (e >= -128 && e <= 127)
this._bufferBuilder.append(208), this.pack_int8(e);
else if (e >= 0 && e <= 65535)
this._bufferBuilder.append(205), this.pack_uint16(e);
else if (e >= -32768 && e <= 32767)
this._bufferBuilder.append(209), this.pack_int16(e);
else if (e >= 0 && e <= 4294967295)
this._bufferBuilder.append(206), this.pack_uint32(e);
else if (e >= -2147483648 && e <= 2147483647)
this._bufferBuilder.append(210), this.pack_int32(e);
else if (e >= -0x8000000000000000 && e <= 0x7fffffffffffffff)
this._bufferBuilder.append(211), this.pack_int64(e);
else if (e >= 0 && e <= 18446744073709552e3)
this._bufferBuilder.append(207), this.pack_uint64(e);
else throw Error("Invalid integer");
}
pack_double(e) {
let t = 0;
e < 0 && ((t = 1), (e = -e));
let n = Math.floor(Math.log(e) / Math.LN2),
r = Math.floor((e / 2 ** n - 1) * 4503599627370496),
i = (t << 31) | ((n + 1023) << 20) | ((r / 4294967296) & 1048575);
this._bufferBuilder.append(203),
this.pack_int32(i),
this.pack_int32(r % 4294967296);
}
pack_object(e) {
let t = Object.keys(e),
n = t.length;
if (n <= 15) this.pack_uint8(128 + n);
else if (n <= 65535) this._bufferBuilder.append(222), this.pack_uint16(n);
else if (n <= 4294967295)
this._bufferBuilder.append(223), this.pack_uint32(n);
else throw Error("Invalid length");
let r = (n) => {
if (n < t.length) {
let i = t[n];
if (e.hasOwnProperty(i)) {
this.pack(i);
let t = this.pack(e[i]);
if (t instanceof Promise) return t.then(() => r(n + 1));
}
return r(n + 1);
}
};
return r(0);
}
pack_uint8(e) {
this._bufferBuilder.append(e);
}
pack_uint16(e) {
this._bufferBuilder.append(e >> 8), this._bufferBuilder.append(255 & e);
}
pack_uint32(e) {
let t = 4294967295 & e;
this._bufferBuilder.append((4278190080 & t) >>> 24),
this._bufferBuilder.append((16711680 & t) >>> 16),
this._bufferBuilder.append((65280 & t) >>> 8),
this._bufferBuilder.append(255 & t);
}
pack_uint64(e) {
let t = e / 4294967296,
n = e % 4294967296;
this._bufferBuilder.append((4278190080 & t) >>> 24),
this._bufferBuilder.append((16711680 & t) >>> 16),
this._bufferBuilder.append((65280 & t) >>> 8),
this._bufferBuilder.append(255 & t),
this._bufferBuilder.append((4278190080 & n) >>> 24),
this._bufferBuilder.append((16711680 & n) >>> 16),
this._bufferBuilder.append((65280 & n) >>> 8),
this._bufferBuilder.append(255 & n);
}
pack_int8(e) {
this._bufferBuilder.append(255 & e);
}
pack_int16(e) {
this._bufferBuilder.append((65280 & e) >> 8),
this._bufferBuilder.append(255 & e);
}
pack_int32(e) {
this._bufferBuilder.append((e >>> 24) & 255),
this._bufferBuilder.append((16711680 & e) >>> 16),
this._bufferBuilder.append((65280 & e) >>> 8),
this._bufferBuilder.append(255 & e);
}
pack_int64(e) {
let t = Math.floor(e / 4294967296),
n = e % 4294967296;
this._bufferBuilder.append((4278190080 & t) >>> 24),
this._bufferBuilder.append((16711680 & t) >>> 16),
this._bufferBuilder.append((65280 & t) >>> 8),
this._bufferBuilder.append(255 & t),
this._bufferBuilder.append((4278190080 & n) >>> 24),
this._bufferBuilder.append((16711680 & n) >>> 16),
this._bufferBuilder.append((65280 & n) >>> 8),
this._bufferBuilder.append(255 & n);
}
constructor() {
(this._bufferBuilder = new r()), (this._textEncoder = new TextEncoder());
}
}
let c = !0,
l = !0;
function p(e, t, n) {
let r = e.match(t);
return r && r.length >= n && parseInt(r[n], 10);
}
function d(e, t, n) {
if (!e.RTCPeerConnection) return;
let r = e.RTCPeerConnection.prototype,
i = r.addEventListener;
r.addEventListener = function (e, r) {
if (e !== t) return i.apply(this, arguments);
let o = (e) => {
let t = n(e);
t && (r.handleEvent ? r.handleEvent(t) : r(t));
};
return (
(this._eventMap = this._eventMap || {}),
this._eventMap[t] || (this._eventMap[t] = new Map()),
this._eventMap[t].set(r, o),
i.apply(this, [e, o])
);
};
let o = r.removeEventListener;
(r.removeEventListener = function (e, n) {
if (
e !== t ||
!this._eventMap ||
!this._eventMap[t] ||
!this._eventMap[t].has(n)
)
return o.apply(this, arguments);
let r = this._eventMap[t].get(n);
return (
this._eventMap[t].delete(n),
0 === this._eventMap[t].size && delete this._eventMap[t],
0 === Object.keys(this._eventMap).length && delete this._eventMap,
o.apply(this, [e, r])
);
}),
Object.defineProperty(r, "on" + t, {
get() {
return this["_on" + t];
},
set(e) {
this["_on" + t] &&
(this.removeEventListener(t, this["_on" + t]),
delete this["_on" + t]),
e && this.addEventListener(t, (this["_on" + t] = e));
},
enumerable: !0,
configurable: !0,
});
}
function h(e) {
return "boolean" != typeof e
? Error("Argument type: " + typeof e + ". Please use a boolean.")
: ((c = e),
e ? "adapter.js logging disabled" : "adapter.js logging enabled");
}
function u(e) {
return "boolean" != typeof e
? Error("Argument type: " + typeof e + ". Please use a boolean.")
: ((l = !e),
"adapter.js deprecation warnings " + (e ? "disabled" : "enabled"));
}
function f() {
"object" != typeof window ||
c ||
"undefined" == typeof console ||
"function" != typeof console.log ||
console.log.apply(console, arguments);
}
function m(e, t) {
l && console.warn(e + " is deprecated, please use " + t + " instead.");
}
function g(e) {
return "[object Object]" === Object.prototype.toString.call(e);
}
function y(e, t, n) {
let r = n ? "outbound-rtp" : "inbound-rtp",
i = new Map();
if (null === t) return i;
let o = [];
return (
e.forEach((e) => {
"track" === e.type && e.trackIdentifier === t.id && o.push(e);
}),
o.forEach((t) => {
e.forEach((n) => {
n.type === r &&
n.trackId === t.id &&
(function e(t, n, r) {
!n ||
r.has(n.id) ||
(r.set(n.id, n),
Object.keys(n).forEach((i) => {
i.endsWith("Id")
? e(t, t.get(n[i]), r)
: i.endsWith("Ids") &&
n[i].forEach((n) => {
e(t, t.get(n), r);
});
}));
})(e, n, i);
});
}),
i
);
}
var _,
C,
v,
b,
k,
S,
T,
R,
w,
P,
E,
D,
x,
I,
M,
O,
j = {};
function L(e, t) {
let n = e && e.navigator;
if (!n.mediaDevices) return;
let r = function (e) {
if ("object" != typeof e || e.mandatory || e.optional) return e;
let t = {};
return (
Object.keys(e).forEach((n) => {
if ("require" === n || "advanced" === n || "mediaSource" === n)
return;
let r = "object" == typeof e[n] ? e[n] : { ideal: e[n] };
void 0 !== r.exact &&
"number" == typeof r.exact &&
(r.min = r.max = r.exact);
let i = function (e, t) {
return e
? e + t.charAt(0).toUpperCase() + t.slice(1)
: "deviceId" === t
? "sourceId"
: t;
};
if (void 0 !== r.ideal) {
t.optional = t.optional || [];
let e = {};
"number" == typeof r.ideal
? ((e[i("min", n)] = r.ideal),
t.optional.push(e),
((e = {})[i("max", n)] = r.ideal))
: (e[i("", n)] = r.ideal),
t.optional.push(e);
}
void 0 !== r.exact && "number" != typeof r.exact
? ((t.mandatory = t.mandatory || {}),
(t.mandatory[i("", n)] = r.exact))
: ["min", "max"].forEach((e) => {
void 0 !== r[e] &&
((t.mandatory = t.mandatory || {}),
(t.mandatory[i(e, n)] = r[e]));
});
}),
e.advanced && (t.optional = (t.optional || []).concat(e.advanced)),
t
);
},
i = function (e, i) {
if (t.version >= 61) return i(e);
if ((e = JSON.parse(JSON.stringify(e))) && "object" == typeof e.audio) {
let t = function (e, t, n) {
t in e && !(n in e) && ((e[n] = e[t]), delete e[t]);
};
t(
(e = JSON.parse(JSON.stringify(e))).audio,
"autoGainControl",
"googAutoGainControl"
),
t(e.audio, "noiseSuppression", "googNoiseSuppression"),
(e.audio = r(e.audio));
}
if (e && "object" == typeof e.video) {
let o = e.video.facingMode;
o = o && ("object" == typeof o ? o : { ideal: o });
let s = t.version < 66;
if (
o &&
("user" === o.exact ||
"environment" === o.exact ||
"user" === o.ideal ||
"environment" === o.ideal) &&
!(
n.mediaDevices.getSupportedConstraints &&
n.mediaDevices.getSupportedConstraints().facingMode &&
!s
)
) {
let t;
if (
(delete e.video.facingMode,
"environment" === o.exact || "environment" === o.ideal
? (t = ["back", "rear"])
: ("user" === o.exact || "user" === o.ideal) && (t = ["front"]),
t)
)
return n.mediaDevices.enumerateDevices().then((n) => {
let s = (n = n.filter((e) => "videoinput" === e.kind)).find(
(e) => t.some((t) => e.label.toLowerCase().includes(t))
);
return (
!s && n.length && t.includes("back") && (s = n[n.length - 1]),
s &&
(e.video.deviceId = o.exact
? { exact: s.deviceId }
: { ideal: s.deviceId }),
(e.video = r(e.video)),
f("chrome: " + JSON.stringify(e)),
i(e)
);
});
}
e.video = r(e.video);
}
return f("chrome: " + JSON.stringify(e)), i(e);
},
o = function (e) {
return t.version >= 64
? e
: {
name:
{
PermissionDeniedError: "NotAllowedError",
PermissionDismissedError: "NotAllowedError",
InvalidStateError: "NotAllowedError",
DevicesNotFoundError: "NotFoundError",
ConstraintNotSatisfiedError: "OverconstrainedError",
TrackStartError: "NotReadableError",
MediaDeviceFailedDueToShutdown: "NotAllowedError",
MediaDeviceKillSwitchOn: "NotAllowedError",
TabCaptureError: "AbortError",
ScreenCaptureError: "AbortError",
DeviceCaptureError: "AbortError",
}[e.name] || e.name,
message: e.message,
constraint: e.constraint || e.constraintName,
toString() {
return this.name + (this.message && ": ") + this.message;
},
};
};
if (
((n.getUserMedia = function (e, t, r) {
i(e, (e) => {
n.webkitGetUserMedia(e, t, (e) => {
r && r(o(e));
});
});
}.bind(n)),
n.mediaDevices.getUserMedia)
) {
let e = n.mediaDevices.getUserMedia.bind(n.mediaDevices);
n.mediaDevices.getUserMedia = function (t) {
return i(t, (t) =>
e(t).then(
(e) => {
if (
(t.audio && !e.getAudioTracks().length) ||
(t.video && !e.getVideoTracks().length)
)
throw (
(e.getTracks().forEach((e) => {
e.stop();
}),
new DOMException("", "NotFoundError"))
);
return e;
},
(e) => Promise.reject(o(e))
)
);
};
}
}
function A(e, t) {
if (
(!e.navigator.mediaDevices ||
!("getDisplayMedia" in e.navigator.mediaDevices)) &&
e.navigator.mediaDevices
) {
if ("function" != typeof t) {
console.error(
"shimGetDisplayMedia: getSourceId argument is not a function"
);
return;
}
e.navigator.mediaDevices.getDisplayMedia = function (n) {
return t(n).then((t) => {
let r = n.video && n.video.width,
i = n.video && n.video.height,
o = n.video && n.video.frameRate;
return (
(n.video = {
mandatory: {
chromeMediaSource: "desktop",
chromeMediaSourceId: t,
maxFrameRate: o || 3,
},
}),
r && (n.video.mandatory.maxWidth = r),
i && (n.video.mandatory.maxHeight = i),
e.navigator.mediaDevices.getUserMedia(n)
);
});
};
}
}
function B(e) {
e.MediaStream = e.MediaStream || e.webkitMediaStream;
}
function F(e) {
if (
"object" != typeof e ||
!e.RTCPeerConnection ||
"ontrack" in e.RTCPeerConnection.prototype
)
d(
e,
"track",
(e) => (
e.transceiver ||
Object.defineProperty(e, "transceiver", {
value: { receiver: e.receiver },
}),
e
)
);
else {
Object.defineProperty(e.RTCPeerConnection.prototype, "ontrack", {
get() {
return this._ontrack;
},
set(e) {
this._ontrack && this.removeEventListener("track", this._ontrack),
this.addEventListener("track", (this._ontrack = e));
},
enumerable: !0,
configurable: !0,
});
let t = e.RTCPeerConnection.prototype.setRemoteDescription;
e.RTCPeerConnection.prototype.setRemoteDescription = function () {
return (
this._ontrackpoly ||
((this._ontrackpoly = (t) => {
t.stream.addEventListener("addtrack", (n) => {
let r;
r = e.RTCPeerConnection.prototype.getReceivers
? this.getReceivers().find(
(e) => e.track && e.track.id === n.track.id
)
: { track: n.track };
let i = new Event("track");
(i.track = n.track),
(i.receiver = r),
(i.transceiver = { receiver: r }),
(i.streams = [t.stream]),
this.dispatchEvent(i);
}),
t.stream.getTracks().forEach((n) => {
let r;
r = e.RTCPeerConnection.prototype.getReceivers
? this.getReceivers().find(
(e) => e.track && e.track.id === n.id
)
: { track: n };
let i = new Event("track");
(i.track = n),
(i.receiver = r),
(i.transceiver = { receiver: r }),
(i.streams = [t.stream]),
this.dispatchEvent(i);
});
}),
this.addEventListener("addstream", this._ontrackpoly)),
t.apply(this, arguments)
);
};
}
}
function U(e) {
if (
"object" == typeof e &&
e.RTCPeerConnection &&
!("getSenders" in e.RTCPeerConnection.prototype) &&
"createDTMFSender" in e.RTCPeerConnection.prototype
) {
let t = function (e, t) {
return {
track: t,
get dtmf() {
return (
void 0 === this._dtmf &&
("audio" === t.kind
? (this._dtmf = e.createDTMFSender(t))
: (this._dtmf = null)),
this._dtmf
);
},
_pc: e,
};
};
if (!e.RTCPeerConnection.prototype.getSenders) {
e.RTCPeerConnection.prototype.getSenders = function () {
return (this._senders = this._senders || []), this._senders.slice();
};
let n = e.RTCPeerConnection.prototype.addTrack;
e.RTCPeerConnection.prototype.addTrack = function (e, r) {
let i = n.apply(this, arguments);
return i || ((i = t(this, e)), this._senders.push(i)), i;
};
let r = e.RTCPeerConnection.prototype.removeTrack;
e.RTCPeerConnection.prototype.removeTrack = function (e) {
r.apply(this, arguments);
let t = this._senders.indexOf(e);
-1 !== t && this._senders.splice(t, 1);
};
}
let n = e.RTCPeerConnection.prototype.addStream;
e.RTCPeerConnection.prototype.addStream = function (e) {
(this._senders = this._senders || []),
n.apply(this, [e]),
e.getTracks().forEach((e) => {
this._senders.push(t(this, e));
});
};
let r = e.RTCPeerConnection.prototype.removeStream;
e.RTCPeerConnection.prototype.removeStream = function (e) {
(this._senders = this._senders || []),
r.apply(this, [e]),
e.getTracks().forEach((e) => {
let t = this._senders.find((t) => t.track === e);
t && this._senders.splice(this._senders.indexOf(t), 1);
});
};
} else if (
"object" == typeof e &&
e.RTCPeerConnection &&
"getSenders" in e.RTCPeerConnection.prototype &&
"createDTMFSender" in e.RTCPeerConnection.prototype &&
e.RTCRtpSender &&
!("dtmf" in e.RTCRtpSender.prototype)
) {
let t = e.RTCPeerConnection.prototype.getSenders;
(e.RTCPeerConnection.prototype.getSenders = function () {
let e = t.apply(this, []);
return e.forEach((e) => (e._pc = this)), e;
}),
Object.defineProperty(e.RTCRtpSender.prototype, "dtmf", {
get() {
return (
void 0 === this._dtmf &&
("audio" === this.track.kind
? (this._dtmf = this._pc.createDTMFSender(this.track))
: (this._dtmf = null)),
this._dtmf
);
},
});
}
}
function z(e) {
if (!e.RTCPeerConnection) return;
let t = e.RTCPeerConnection.prototype.getStats;
e.RTCPeerConnection.prototype.getStats = function () {
let [e, n, r] = arguments;
if (arguments.length > 0 && "function" == typeof e)
return t.apply(this, arguments);
if (0 === t.length && (0 == arguments.length || "function" != typeof e))
return t.apply(this, []);
let i = function (e) {
let t = {};
return (
e.result().forEach((e) => {
let n = {
id: e.id,
timestamp: e.timestamp,
type:
{
localcandidate: "local-candidate",
remotecandidate: "remote-candidate",
}[e.type] || e.type,
};
e.names().forEach((t) => {
n[t] = e.stat(t);
}),
(t[n.id] = n);
}),
t
);
},
o = function (e) {
return new Map(Object.keys(e).map((t) => [t, e[t]]));
};
return arguments.length >= 2
? t.apply(this, [
function (e) {
n(o(i(e)));
},
e,
])
: new Promise((e, n) => {
t.apply(this, [
function (t) {
e(o(i(t)));
},
n,
]);
}).then(n, r);
};
}
function N(e) {
if (
!(
"object" == typeof e &&
e.RTCPeerConnection &&
e.RTCRtpSender &&
e.RTCRtpReceiver
)
)
return;
if (!("getStats" in e.RTCRtpSender.prototype)) {
let t = e.RTCPeerConnection.prototype.getSenders;
t &&
(e.RTCPeerConnection.prototype.getSenders = function () {
let e = t.apply(this, []);
return e.forEach((e) => (e._pc = this)), e;
});
let n = e.RTCPeerConnection.prototype.addTrack;
n &&
(e.RTCPeerConnection.prototype.addTrack = function () {
let e = n.apply(this, arguments);
return (e._pc = this), e;
}),
(e.RTCRtpSender.prototype.getStats = function () {
let e = this;
return this._pc.getStats().then((t) => y(t, e.track, !0));
});
}
if (!("getStats" in e.RTCRtpReceiver.prototype)) {
let t = e.RTCPeerConnection.prototype.getReceivers;
t &&
(e.RTCPeerConnection.prototype.getReceivers = function () {
let e = t.apply(this, []);
return e.forEach((e) => (e._pc = this)), e;
}),
d(e, "track", (e) => ((e.receiver._pc = e.srcElement), e)),
(e.RTCRtpReceiver.prototype.getStats = function () {
let e = this;
return this._pc.getStats().then((t) => y(t, e.track, !1));
});
}
if (
!(
"getStats" in e.RTCRtpSender.prototype &&
"getStats" in e.RTCRtpReceiver.prototype
)
)
return;
let t = e.RTCPeerConnection.prototype.getStats;
e.RTCPeerConnection.prototype.getStats = function () {
if (arguments.length > 0 && arguments[0] instanceof e.MediaStreamTrack) {
let e, t, n;
let r = arguments[0];
return (this.getSenders().forEach((t) => {
t.track === r && (e ? (n = !0) : (e = t));
}),
this.getReceivers().forEach(
(e) => (e.track === r && (t ? (n = !0) : (t = e)), e.track === r)
),
n || (e && t))
? Promise.reject(
new DOMException(
"There are more than one sender or receiver for the track.",
"InvalidAccessError"
)
)
: e
? e.getStats()
: t
? t.getStats()
: Promise.reject(
new DOMException(
"There is no sender or receiver for the track.",
"InvalidAccessError"
)
);
}
return t.apply(this, arguments);
};
}
function $(e) {
e.RTCPeerConnection.prototype.getLocalStreams = function () {
return (
(this._shimmedLocalStreams = this._shimmedLocalStreams || {}),
Object.keys(this._shimmedLocalStreams).map(
(e) => this._shimmedLocalStreams[e][0]
)
);
};
let t = e.RTCPeerConnection.prototype.addTrack;
e.RTCPeerConnection.prototype.addTrack = function (e, n) {
if (!n) return t.apply(this, arguments);
this._shimmedLocalStreams = this._shimmedLocalStreams || {};
let r = t.apply(this, arguments);
return (
this._shimmedLocalStreams[n.id]
? -1 === this._shimmedLocalStreams[n.id].indexOf(r) &&
this._shimmedLocalStreams[n.id].push(r)
: (this._shimmedLocalStreams[n.id] = [n, r]),
r
);
};
let n = e.RTCPeerConnection.prototype.addStream;
e.RTCPeerConnection.prototype.addStream = function (e) {
(this._shimmedLocalStreams = this._shimmedLocalStreams || {}),
e.getTracks().forEach((e) => {
if (this.getSenders().find((t) => t.track === e))
throw new DOMException(
"Track already exists.",
"InvalidAccessError"
);
});
let t = this.getSenders();
n.apply(this, arguments);
let r = this.getSenders().filter((e) => -1 === t.indexOf(e));
this._shimmedLocalStreams[e.id] = [e].concat(r);
};
let r = e.RTCPeerConnection.prototype.removeStream;
e.RTCPeerConnection.prototype.removeStream = function (e) {
return (
(this._shimmedLocalStreams = this._shimmedLocalStreams || {}),
delete this._shimmedLocalStreams[e.id],
r.apply(this, arguments)
);
};
let i = e.RTCPeerConnection.prototype.removeTrack;
e.RTCPeerConnection.prototype.removeTrack = function (e) {
return (
(this._shimmedLocalStreams = this._shimmedLocalStreams || {}),
e &&
Object.keys(this._shimmedLocalStreams).forEach((t) => {
let n = this._shimmedLocalStreams[t].indexOf(e);
-1 !== n && this._shimmedLocalStreams[t].splice(n, 1),
1 === this._shimmedLocalStreams[t].length &&
delete this._shimmedLocalStreams[t];
}),
i.apply(this, arguments)
);
};
}
function J(e, t) {
if (!e.RTCPeerConnection) return;
if (e.RTCPeerConnection.prototype.addTrack && t.version >= 65) return $(e);
let n = e.RTCPeerConnection.prototype.getLocalStreams;
e.RTCPeerConnection.prototype.getLocalStreams = function () {
let e = n.apply(this);
return (
(this._reverseStreams = this._reverseStreams || {}),
e.map((e) => this._reverseStreams[e.id])
);
};
let r = e.RTCPeerConnection.prototype.addStream;
e.RTCPeerConnection.prototype.addStream = function (t) {
if (
((this._streams = this._streams || {}),
(this._reverseStreams = this._reverseStreams || {}),
t.getTracks().forEach((e) => {
if (this.getSenders().find((t) => t.track === e))
throw new DOMException(
"Track already exists.",
"InvalidAccessError"
);
}),
!this._reverseStreams[t.id])
) {
let n = new e.MediaStream(t.getTracks());
(this._streams[t.id] = n), (this._reverseStreams[n.id] = t), (t = n);
}
r.apply(this, [t]);
};
let i = e.RTCPeerConnection.prototype.removeStream;
function o(e, t) {
let n = t.sdp;
return (
Object.keys(e._reverseStreams || []).forEach((t) => {
let r = e._reverseStreams[t],
i = e._streams[r.id];
n = n.replace(RegExp(i.id, "g"), r.id);
}),
new RTCSessionDescription({ type: t.type, sdp: n })
);
}
(e.RTCPeerConnection.prototype.removeStream = function (e) {
(this._streams = this._streams || {}),
(this._reverseStreams = this._reverseStreams || {}),
i.apply(this, [this._streams[e.id] || e]),
delete this._reverseStreams[
this._streams[e.id] ? this._streams[e.id].id : e.id
],
delete this._streams[e.id];
}),
(e.RTCPeerConnection.prototype.addTrack = function (t, n) {
if ("closed" === this.signalingState)
throw new DOMException(
"The RTCPeerConnection's signalingState is 'closed'.",
"InvalidStateError"
);
let r = [].slice.call(arguments, 1);
if (1 !== r.length || !r[0].getTracks().find((e) => e === t))
throw new DOMException(
"The adapter.js addTrack polyfill only supports a single stream which is associated with the specified track.",
"NotSupportedError"
);
if (this.getSenders().find((e) => e.track === t))
throw new DOMException("Track already exists.", "InvalidAccessError");
(this._streams = this._streams || {}),
(this._reverseStreams = this._reverseStreams || {});
let i = this._streams[n.id];
if (i)
i.addTrack(t),
Promise.resolve().then(() => {
this.dispatchEvent(new Event("negotiationneeded"));
});
else {
let r = new e.MediaStream([t]);
(this._streams[n.id] = r),
(this._reverseStreams[r.id] = n),
this.addStream(r);
}
return this.getSenders().find((e) => e.track === t);
}),
["createOffer", "createAnswer"].forEach(function (t) {
let n = e.RTCPeerConnection.prototype[t];
e.RTCPeerConnection.prototype[t] = {
[t]() {
let e = arguments,
t = arguments.length && "function" == typeof arguments[0];
return t
? n.apply(this, [
(t) => {
let n = o(this, t);
e[0].apply(null, [n]);
},
(t) => {
e[1] && e[1].apply(null, t);
},
arguments[2],
])
: n.apply(this, arguments).then((e) => o(this, e));
},
}[t];
});
let s = e.RTCPeerConnection.prototype.setLocalDescription;
e.RTCPeerConnection.prototype.setLocalDescription = function () {
var e, t;
let n;
return (
arguments.length &&
arguments[0].type &&
(arguments[0] =
((e = this),
(t = arguments[0]),
(n = t.sdp),
Object.keys(e._reverseStreams || []).forEach((t) => {
let r = e._reverseStreams[t],
i = e._streams[r.id];
n = n.replace(RegExp(r.id, "g"), i.id);
}),
new RTCSessionDescription({ type: t.type, sdp: n }))),
s.apply(this, arguments)
);
};
let a = Object.getOwnPropertyDescriptor(
e.RTCPeerConnection.prototype,
"localDescription"
);
Object.defineProperty(e.RTCPeerConnection.prototype, "localDescription", {
get() {
let e = a.get.apply(this);
return "" === e.type ? e : o(this, e);
},
}),
(e.RTCPeerConnection.prototype.removeTrack = function (e) {
let t;
if ("closed" === this.signalingState)
throw new DOMException(
"The RTCPeerConnection's signalingState is 'closed'.",
"InvalidStateError"
);
if (!e._pc)
throw new DOMException(
"Argument 1 of RTCPeerConnection.removeTrack does not implement interface RTCRtpSender.",
"TypeError"
);
if (e._pc !== this)
throw new DOMException(
"Sender was not created by this connection.",
"InvalidAccessError"
);
(this._streams = this._streams || {}),
Object.keys(this._streams).forEach((n) => {
this._streams[n].getTracks().find((t) => e.track === t) &&
(t = this._streams[n]);
}),
t &&
(1 === t.getTracks().length
? this.removeStream(this._reverseStreams[t.id])
: t.removeTrack(e.track),
this.dispatchEvent(new Event("negotiationneeded")));
});
}
function V(e, t) {
!e.RTCPeerConnection &&
e.webkitRTCPeerConnection &&
(e.RTCPeerConnection = e.webkitRTCPeerConnection),
e.RTCPeerConnection &&
t.version < 53 &&
[
"setLocalDescription",
"setRemoteDescription",
"addIceCandidate",
].forEach(function (t) {
let n = e.RTCPeerConnection.prototype[t];
e.RTCPeerConnection.prototype[t] = {
[t]() {
return (
(arguments[0] = new (
"addIceCandidate" === t
? e.RTCIceCandidate
: e.RTCSessionDescription
)(arguments[0])),
n.apply(this, arguments)
);
},
}[t];
});
}
function G(e, t) {
d(e, "negotiationneeded", (e) => {
let n = e.target;
if (
(!(t.version < 72) &&
(!n.getConfiguration ||
"plan-b" !== n.getConfiguration().sdpSemantics)) ||
"stable" === n.signalingState
)
return e;
});
}
e(j, "shimMediaStream", () => B),
e(j, "shimOnTrack", () => F),
e(j, "shimGetSendersWithDtmf", () => U),
e(j, "shimGetStats", () => z),
e(j, "shimSenderReceiverGetStats", () => N),
e(j, "shimAddTrackRemoveTrackWithNative", () => $),
e(j, "shimAddTrackRemoveTrack", () => J),
e(j, "shimPeerConnection", () => V),
e(j, "fixNegotiationNeeded", () => G),
e(j, "shimGetUserMedia", () => L),
e(j, "shimGetDisplayMedia", () => A);
var W = {};
function H(e, t) {
let n = e && e.navigator,
r = e && e.MediaStreamTrack;
if (
((n.getUserMedia = function (e, t, r) {
m("navigator.getUserMedia", "navigator.mediaDevices.getUserMedia"),
n.mediaDevices.getUserMedia(e).then(t, r);
}),
!(
t.version > 55 &&
"autoGainControl" in n.mediaDevices.getSupportedConstraints()
))
) {
let e = function (e, t, n) {
t in e && !(n in e) && ((e[n] = e[t]), delete e[t]);
},
t = n.mediaDevices.getUserMedia.bind(n.mediaDevices);
if (
((n.mediaDevices.getUserMedia = function (n) {
return (
"object" == typeof n &&
"object" == typeof n.audio &&
(e(
(n = JSON.parse(JSON.stringify(n))).audio,
"autoGainControl",
"mozAutoGainControl"
),
e(n.audio, "noiseSuppression", "mozNoiseSuppression")),
t(n)
);
}),
r && r.prototype.getSettings)
) {
let t = r.prototype.getSettings;
r.prototype.getSettings = function () {
let n = t.apply(this, arguments);
return (
e(n, "mozAutoGainControl", "autoGainControl"),
e(n, "mozNoiseSuppression", "noiseSuppression"),
n
);
};
}
if (r && r.prototype.applyConstraints) {
let t = r.prototype.applyConstraints;
r.prototype.applyConstraints = function (n) {
return (
"audio" === this.kind &&
"object" == typeof n &&
(e(
(n = JSON.parse(JSON.stringify(n))),
"autoGainControl",
"mozAutoGainControl"
),
e(n, "noiseSuppression", "mozNoiseSuppression")),
t.apply(this, [n])
);
};
}
}
}
function Y(e, t) {
(e.navigator.mediaDevices &&
"getDisplayMedia" in e.navigator.mediaDevices) ||
!e.navigator.mediaDevices ||
(e.navigator.mediaDevices.getDisplayMedia = function (n) {
if (!(n && n.video)) {
let e = new DOMException(
"getDisplayMedia without video constraints is undefined"
);
return (e.name = "NotFoundError"), (e.code = 8), Promise.reject(e);
}
return (
!0 === n.video
? (n.video = { mediaSource: t })
: (n.video.mediaSource = t),
e.navigator.mediaDevices.getUserMedia(n)
);
});
}
function K(e) {
"object" == typeof e &&
e.RTCTrackEvent &&
"receiver" in e.RTCTrackEvent.prototype &&
!("transceiver" in e.RTCTrackEvent.prototype) &&
Object.defineProperty(e.RTCTrackEvent.prototype, "transceiver", {
get() {
return { receiver: this.receiver };
},
});
}
function X(e, t) {
if (
"object" != typeof e ||
!(e.RTCPeerConnection || e.mozRTCPeerConnection)
)
return;
!e.RTCPeerConnection &&
e.mozRTCPeerConnection &&
(e.RTCPeerConnection = e.mozRTCPeerConnection),
t.version < 53 &&
[
"setLocalDescription",
"setRemoteDescription",
"addIceCandidate",
].forEach(function (t) {
let n = e.RTCPeerConnection.prototype[t];
e.RTCPeerConnection.prototype[t] = {
[t]() {
return (
(arguments[0] = new (
"addIceCandidate" === t
? e.RTCIceCandidate
: e.RTCSessionDescription
)(arguments[0])),
n.apply(this, arguments)
);
},
}[t];
});
let n = {
inboundrtp: "inbound-rtp",
outboundrtp: "outbound-rtp",
candidatepair: "candidate-pair",
localcandidate: "local-candidate",
remotecandidate: "remote-candidate",
},
r = e.RTCPeerConnection.prototype.getStats;
e.RTCPeerConnection.prototype.getStats = function () {
let [e, i, o] = arguments;
return r
.apply(this, [e || null])
.then((e) => {
if (t.version < 53 && !i)
try {
e.forEach((e) => {
e.type = n[e.type] || e.type;
});
} catch (t) {
if ("TypeError" !== t.name) throw t;
e.forEach((t, r) => {
e.set(r, Object.assign({}, t, { type: n[t.type] || t.type }));
});
}
return e;
})
.then(i, o);
};
}
function q(e) {
if (
!("object" == typeof e && e.RTCPeerConnection && e.RTCRtpSender) ||
(e.RTCRtpSender && "getStats" in e.RTCRtpSender.prototype)
)
return;
let t = e.RTCPeerConnection.prototype.getSenders;
t &&
(e.RTCPeerConnection.prototype.getSenders = function () {
let e = t.apply(this, []);
return e.forEach((e) => (e._pc = this)), e;
});
let n = e.RTCPeerConnection.prototype.addTrack;
n &&
(e.RTCPeerConnection.prototype.addTrack = function () {
let e = n.apply(this, arguments);
return (e._pc = this), e;
}),
(e.RTCRtpSender.prototype.getStats = function () {
return this.track
? this._pc.getStats(this.track)
: Promise.resolve(new Map());
});
}
function Q(e) {
if (
!("object" == typeof e && e.RTCPeerConnection && e.RTCRtpSender) ||
(e.RTCRtpSender && "getStats" in e.RTCRtpReceiver.prototype)
)
return;
let t = e.RTCPeerConnection.prototype.getReceivers;
t &&
(e.RTCPeerConnection.prototype.getReceivers = function () {
let e = t.apply(this, []);
return e.forEach((e) => (e._pc = this)), e;
}),
d(e, "track", (e) => ((e.receiver._pc = e.srcElement), e)),
(e.RTCRtpReceiver.prototype.getStats = function () {
return this._pc.getStats(this.track);
});
}
function Z(e) {
!e.RTCPeerConnection ||
"removeStream" in e.RTCPeerConnection.prototype ||
(e.RTCPeerConnection.prototype.removeStream = function (e) {
m("removeStream", "removeTrack"),
this.getSenders().forEach((t) => {
t.track && e.getTracks().includes(t.track) && this.removeTrack(t);
});
});
}
function ee(e) {
e.DataChannel && !e.RTCDataChannel && (e.RTCDataChannel = e.DataChannel);
}
function et(e) {
if (!("object" == typeof e && e.RTCPeerConnection)) return;
let t = e.RTCPeerConnection.prototype.addTransceiver;
t &&
(e.RTCPeerConnection.prototype.addTransceiver = function () {
this.setParametersPromises = [];
let e = arguments[1] && arguments[1].sendEncodings;
void 0 === e && (e = []);
let n = (e = [...e]).length > 0;
n &&
e.forEach((e) => {
if ("rid" in e && !/^[a-z0-9]{0,16}$/i.test(e.rid))
throw TypeError("Invalid RID value provided.");
if (
"scaleResolutionDownBy" in e &&
!(parseFloat(e.scaleResolutionDownBy) >= 1)
)
throw RangeError("scale_resolution_down_by must be >= 1.0");
if ("maxFramerate" in e && !(parseFloat(e.maxFramerate) >= 0))
throw RangeError("max_framerate must be >= 0.0");
});
let r = t.apply(this, arguments);
if (n) {
let { sender: t } = r,
n = t.getParameters();
("encodings" in n &&
(1 !== n.encodings.length ||
0 !== Object.keys(n.encodings[0]).length)) ||
((n.encodings = e),
(t.sendEncodings = e),
this.setParametersPromises.push(
t
.setParameters(n)
.then(() => {
delete t.sendEncodings;
})
.catch(() => {
delete t.sendEncodings;
})
));
}
return r;
});
}
function en(e) {
if (!("object" == typeof e && e.RTCRtpSender)) return;
let t = e.RTCRtpSender.prototype.getParameters;
t &&
(e.RTCRtpSender.prototype.getParameters = function () {
let e = t.apply(this, arguments);
return (
"encodings" in e ||
(e.encodings = [].concat(this.sendEncodings || [{}])),
e
);
});
}
function er(e) {
if (!("object" == typeof e && e.RTCPeerConnection)) return;
let t = e.RTCPeerConnection.prototype.createOffer;
e.RTCPeerConnection.prototype.createOffer = function () {
return this.setParametersPromises && this.setParametersPromises.length
? Promise.all(this.setParametersPromises)
.then(() => t.apply(this, arguments))
.finally(() => {
this.setParametersPromises = [];
})
: t.apply(this, arguments);
};
}
function ei(e) {
if (!("object" == typeof e && e.RTCPeerConnection)) return;
let t = e.RTCPeerConnection.prototype.createAnswer;
e.RTCPeerConnection.prototype.createAnswer = function () {
return this.setParametersPromises && this.setParametersPromises.length
? Promise.all(this.setParametersPromises)
.then(() => t.apply(this, arguments))
.finally(() => {
this.setParametersPromises = [];
})
: t.apply(this, arguments);
};
}
e(W, "shimOnTrack", () => K),
e(W, "shimPeerConnection", () => X),
e(W, "shimSenderGetStats", () => q),
e(W, "shimReceiverGetStats", () => Q),
e(W, "shimRemoveStream", () => Z),
e(W, "shimRTCDataChannel", () => ee),
e(W, "shimAddTransceiver", () => et),
e(W, "shimGetParameters", () => en),
e(W, "shimCreateOffer", () => er),
e(W, "shimCreateAnswer", () => ei),
e(W, "shimGetUserMedia", () => H),
e(W, "shimGetDisplayMedia", () => Y);
var eo = {};
function es(e) {
if ("object" == typeof e && e.RTCPeerConnection) {
if (
("getLocalStreams" in e.RTCPeerConnection.prototype ||
(e.RTCPeerConnection.prototype.getLocalStreams = function () {
return (
this._localStreams || (this._localStreams = []),
this._localStreams
);
}),
!("addStream" in e.RTCPeerConnection.prototype))
) {
let t = e.RTCPeerConnection.prototype.addTrack;
(e.RTCPeerConnection.prototype.addStream = function (e) {
this._localStreams || (this._localStreams = []),
this._localStreams.includes(e) || this._localStreams.push(e),
e.getAudioTracks().forEach((n) => t.call(this, n, e)),
e.getVideoTracks().forEach((n) => t.call(this, n, e));
}),
(e.RTCPeerConnection.prototype.addTrack = function (e, ...n) {
return (
n &&
n.forEach((e) => {
this._localStreams
? this._localStreams.includes(e) ||
this._localStreams.push(e)
: (this._localStreams = [e]);
}),
t.apply(this, arguments)
);
});
}
"removeStream" in e.RTCPeerConnection.prototype ||
(e.RTCPeerConnection.prototype.removeStream = function (e) {
this._localStreams || (this._localStreams = []);
let t = this._localStreams.indexOf(e);
if (-1 === t) return;
this._localStreams.splice(t, 1);
let n = e.getTracks();
this.getSenders().forEach((e) => {
n.includes(e.track) && this.removeTrack(e);
});
});
}
}
function ea(e) {
if (
"object" == typeof e &&
e.RTCPeerConnection &&
("getRemoteStreams" in e.RTCPeerConnection.prototype ||
(e.RTCPeerConnection.prototype.getRemoteStreams = function () {
return this._remoteStreams ? this._remoteStreams : [];
}),
!("onaddstream" in e.RTCPeerConnection.prototype))
) {
Object.defineProperty(e.RTCPeerConnection.prototype, "onaddstream", {
get() {
return this._onaddstream;
},
set(e) {
this._onaddstream &&
(this.removeEventListener("addstream", this._onaddstream),
this.removeEventListener("track", this._onaddstreampoly)),
this.addEventListener("addstream", (this._onaddstream = e)),
this.addEventListener(
"track",
(this._onaddstreampoly = (e) => {
e.streams.forEach((e) => {
if (
(this._remoteStreams || (this._remoteStreams = []),
this._remoteStreams.includes(e))
)
return;
this._remoteStreams.push(e);
let t = new Event("addstream");
(t.stream = e), this.dispatchEvent(t);
});
})
);
},
});
let t = e.RTCPeerConnection.prototype.setRemoteDescription;
e.RTCPeerConnection.prototype.setRemoteDescription = function () {
let e = this;
return (
this._onaddstreampoly ||
this.addEventListener(
"track",
(this._onaddstreampoly = function (t) {
t.streams.forEach((t) => {
if (
(e._remoteStreams || (e._remoteStreams = []),
e._remoteStreams.indexOf(t) >= 0)
)
return;
e._remoteStreams.push(t);
let n = new Event("addstream");
(n.stream = t), e.dispatchEvent(n);
});
})
),
t.apply(e, arguments)
);
};
}
}
function ec(e) {
if ("object" != typeof e || !e.RTCPeerConnection) return;
let t = e.RTCPeerConnection.prototype,
n = t.createOffer,
r = t.createAnswer,
i = t.setLocalDescription,
o = t.setRemoteDescription,
s = t.addIceCandidate;
(t.createOffer = function (e, t) {
let r = arguments.length >= 2 ? arguments[2] : arguments[0],
i = n.apply(this, [r]);
return t ? (i.then(e, t), Promise.resolve()) : i;
}),
(t.createAnswer = function (e, t) {
let n = arguments.length >= 2 ? arguments[2] : arguments[0],
i = r.apply(this, [n]);
return t ? (i.then(e, t), Promise.resolve()) : i;
});
let a = function (e, t, n) {
let r = i.apply(this, [e]);
return n ? (r.then(t, n), Promise.resolve()) : r;
};
(t.setLocalDescription = a),
(a = function (e, t, n) {
let r = o.apply(this, [e]);
return n ? (r.then(t, n), Promise.resolve()) : r;
}),
(t.setRemoteDescription = a),
(a = function (e, t, n) {
let r = s.apply(this, [e]);
return n ? (r.then(t, n), Promise.resolve()) : r;
}),
(t.addIceCandidate = a);
}
function el(e) {
let t = e && e.navigator;
if (t.mediaDevices && t.mediaDevices.getUserMedia) {
let e = t.mediaDevices,
n = e.getUserMedia.bind(e);
t.mediaDevices.getUserMedia = (e) => n(ep(e));
}
!t.getUserMedia &&
t.mediaDevices &&
t.mediaDevices.getUserMedia &&
(t.getUserMedia = function (e, n, r) {
t.mediaDevices.getUserMedia(e).then(n, r);
}.bind(t));
}
function ep(e) {
return e && void 0 !== e.video
? Object.assign({}, e, {
video: (function e(t) {
return g(t)
? Object.keys(t).reduce(function (n, r) {
let i = g(t[r]),
o = i ? e(t[r]) : t[r],
s = i && !Object.keys(o).length;
return void 0 === o || s ? n : Object.assign(n, { [r]: o });
}, {})
: t;
})(e.video),
})
: e;
}
function ed(e) {
if (!e.RTCPeerConnection) return;
let t = e.RTCPeerConnection;
(e.RTCPeerConnection = function (e, n) {
if (e && e.iceServers) {
let t = [];
for (let n = 0; n < e.iceServers.length; n++) {
let r = e.iceServers[n];
void 0 === r.urls && r.url
? (m("RTCIceServer.url", "RTCIceServer.urls"),
((r = JSON.parse(JSON.stringify(r))).urls = r.url),
delete r.url,
t.push(r))
: t.push(e.iceServers[n]);
}
e.iceServers = t;
}
return new t(e, n);
}),
(e.RTCPeerConnection.prototype = t.prototype),
"generateCertificate" in t &&
Object.defineProperty(e.RTCPeerConnection, "generateCertificate", {
get: () => t.generateCertificate,
});
}
function eh(e) {
"object" == typeof e &&
e.RTCTrackEvent &&
"receiver" in e.RTCTrackEvent.prototype &&
!("transceiver" in e.RTCTrackEvent.prototype) &&
Object.defineProperty(e.RTCTrackEvent.prototype, "transceiver", {
get() {
return { receiver: this.receiver };
},
});
}
function eu(e) {
let t = e.RTCPeerConnection.prototype.createOffer;
e.RTCPeerConnection.prototype.createOffer = function (e) {
if (e) {
void 0 !== e.offerToReceiveAudio &&
(e.offerToReceiveAudio = !!e.offerToReceiveAudio);
let t = this.getTransceivers().find(
(e) => "audio" === e.receiver.track.kind
);
!1 === e.offerToReceiveAudio && t
? "sendrecv" === t.direction
? t.setDirection
? t.setDirection("sendonly")
: (t.direction = "sendonly")
: "recvonly" === t.direction &&
(t.setDirection
? t.setDirection("inactive")
: (t.direction = "inactive"))
: !0 !== e.offerToReceiveAudio ||
t ||
this.addTransceiver("audio", { direction: "recvonly" }),
void 0 !== e.offerToReceiveVideo &&
(e.offerToReceiveVideo = !!e.offerToReceiveVideo);
let n = this.getTransceivers().find(
(e) => "video" === e.receiver.track.kind
);
!1 === e.offerToReceiveVideo && n
? "sendrecv" === n.direction
? n.setDirection
? n.setDirection("sendonly")
: (n.direction = "sendonly")
: "recvonly" === n.direction &&
(n.setDirection
? n.setDirection("inactive")
: (n.direction = "inactive"))
: !0 !== e.offerToReceiveVideo ||
n ||
this.addTransceiver("video", { direction: "recvonly" });
}
return t.apply(this, arguments);
};
}
function ef(e) {
"object" != typeof e ||
e.AudioContext ||
(e.AudioContext = e.webkitAudioContext);
}
e(eo, "shimLocalStreamsAPI", () => es),
e(eo, "shimRemoteStreamsAPI", () => ea),
e(eo, "shimCallbacksAPI", () => ec),
e(eo, "shimGetUserMedia", () => el),
e(eo, "shimConstraints", () => ep),
e(eo, "shimRTCIceServerUrls", () => ed),
e(eo, "shimTrackEventTransceiver", () => eh),
e(eo, "shimCreateOfferLegacy", () => eu),
e(eo, "shimAudioContext", () => ef);
var em = {};
e(em, "shimRTCIceCandidate", () => e_),
e(em, "shimRTCIceCandidateRelayProtocol", () => eC),
e(em, "shimMaxMessageSize", () => ev),
e(em, "shimSendThrowTypeError", () => eb),
e(em, "shimConnectionState", () => ek),
e(em, "removeExtmapAllowMixed", () => eS),
e(em, "shimAddIceCandidateNullOrEmpty", () => eT),
e(em, "shimParameterlessSetLocalDescription", () => eR);
var eg = {};
let ey = {};
function e_(e) {
if (
!e.RTCIceCandidate ||
(e.RTCIceCandidate && "foundation" in e.RTCIceCandidate.prototype)
)
return;
let n = e.RTCIceCandidate;
(e.RTCIceCandidate = function (e) {
if (
("object" == typeof e &&
e.candidate &&
0 === e.candidate.indexOf("a=") &&
((e = JSON.parse(JSON.stringify(e))).candidate =
e.candidate.substring(2)),
e.candidate && e.candidate.length)
) {
let r = new n(e),
i = t(eg).parseCandidate(e.candidate);
for (let e in i) e in r || Object.defineProperty(r, e, { value: i[e] });
return (
(r.toJSON = function () {
return {
candidate: r.candidate,
sdpMid: r.sdpMid,
sdpMLineIndex: r.sdpMLineIndex,
usernameFragment: r.usernameFragment,
};
}),
r
);
}
return new n(e);
}),
(e.RTCIceCandidate.prototype = n.prototype),
d(
e,
"icecandidate",
(t) => (
t.candidate &&
Object.defineProperty(t, "candidate", {
value: new e.RTCIceCandidate(t.candidate),
writable: "false",
}),
t
)
);
}
function eC(e) {
!e.RTCIceCandidate ||
(e.RTCIceCandidate && "relayProtocol" in e.RTCIceCandidate.prototype) ||
d(e, "icecandidate", (e) => {
if (e.candidate) {
let n = t(eg).parseCandidate(e.candidate.candidate);
"relay" === n.type &&
(e.candidate.relayProtocol = { 0: "tls", 1: "tcp", 2: "udp" }[
n.priority >> 24
]);
}
return e;
});
}
function ev(e, n) {
if (!e.RTCPeerConnection) return;
"sctp" in e.RTCPeerConnection.prototype ||
Object.defineProperty(e.RTCPeerConnection.prototype, "sctp", {
get() {
return void 0 === this._sctp ? null : this._sctp;
},
});
let r = function (e) {
if (!e || !e.sdp) return !1;
let n = t(eg).splitSections(e.sdp);
return (
n.shift(),
n.some((e) => {
let n = t(eg).parseMLine(e);
return (
n && "application" === n.kind && -1 !== n.protocol.indexOf("SCTP")
);
})
);
},
i = function (e) {
let t = e.sdp.match(/mozilla...THIS_IS_SDPARTA-(\d+)/);
if (null === t || t.length < 2) return -1;
let n = parseInt(t[1], 10);
return n != n ? -1 : n;
},
o = function (e) {
let t = 65536;
return (
"firefox" === n.browser &&
(t =
n.version < 57
? -1 === e
? 16384
: 2147483637
: n.version < 60
? 57 === n.version
? 65535
: 65536
: 2147483637),
t
);
},
s = function (e, r) {
let i = 65536;
"firefox" === n.browser && 57 === n.version && (i = 65535);
let o = t(eg).matchPrefix(e.sdp, "a=max-message-size:");
return (
o.length > 0
? (i = parseInt(o[0].substring(19), 10))
: "firefox" === n.browser && -1 !== r && (i = 2147483637),
i
);
},
a = e.RTCPeerConnection.prototype.setRemoteDescription;
e.RTCPeerConnection.prototype.setRemoteDescription = function () {
if (((this._sctp = null), "chrome" === n.browser && n.version >= 76)) {
let { sdpSemantics: e } = this.getConfiguration();
"plan-b" === e &&
Object.defineProperty(this, "sctp", {
get() {
return void 0 === this._sctp ? null : this._sctp;
},
enumerable: !0,
configurable: !0,
});
}
if (r(arguments[0])) {
let e;
let t = i(arguments[0]),
n = o(t),
r = s(arguments[0], t);
e =
0 === n && 0 === r
? Number.POSITIVE_INFINITY
: 0 === n || 0 === r
? Math.max(n, r)
: Math.min(n, r);
let a = {};
Object.defineProperty(a, "maxMessageSize", { get: () => e }),
(this._sctp = a);
}
return a.apply(this, arguments);
};
}
function eb(e) {
if (
!(
e.RTCPeerConnection &&
"createDataChannel" in e.RTCPeerConnection.prototype
)
)
return;
function t(e, t) {
let n = e.send;
e.send = function () {
let r = arguments[0],
i = r.length || r.size || r.byteLength;
if ("open" === e.readyState && t.sctp && i > t.sctp.maxMessageSize)
throw TypeError(
"Message too large (can send a maximum of " +
t.sctp.maxMessageSize +
" bytes)"
);
return n.apply(e, arguments);
};
}
let n = e.RTCPeerConnection.prototype.createDataChannel;
(e.RTCPeerConnection.prototype.createDataChannel = function () {
let e = n.apply(this, arguments);
return t(e, this), e;
}),
d(e, "datachannel", (e) => (t(e.channel, e.target), e));
}
function ek(e) {
if (
!e.RTCPeerConnection ||
"connectionState" in e.RTCPeerConnection.prototype
)
return;
let t = e.RTCPeerConnection.prototype;
Object.defineProperty(t, "connectionState", {
get() {
return (
{ completed: "connected", checking: "connecting" }[
this.iceConnectionState
] || this.iceConnectionState
);
},
enumerable: !0,
configurable: !0,
}),
Object.defineProperty(t, "onconnectionstatechange", {
get() {
return this._onconnectionstatechange || null;
},
set(e) {
this._onconnectionstatechange &&
(this.removeEventListener(
"connectionstatechange",
this._onconnectionstatechange
),
delete this._onconnectionstatechange),
e &&
this.addEventListener(
"connectionstatechange",
(this._onconnectionstatechange = e)
);
},
enumerable: !0,
configurable: !0,
}),
["setLocalDescription", "setRemoteDescription"].forEach((e) => {
let n = t[e];
t[e] = function () {
return (
this._connectionstatechangepoly ||
((this._connectionstatechangepoly = (e) => {
let t = e.target;
if (t._lastConnectionState !== t.connectionState) {
t._lastConnectionState = t.connectionState;
let n = new Event("connectionstatechange", e);
t.dispatchEvent(n);
}
return e;
}),
this.addEventListener(
"iceconnectionstatechange",
this._connectionstatechangepoly
)),
n.apply(this, arguments)
);
};
});
}
function eS(e, t) {
if (
!e.RTCPeerConnection ||
("chrome" === t.browser && t.version >= 71) ||
("safari" === t.browser && t.version >= 605)
)
return;
let n = e.RTCPeerConnection.prototype.setRemoteDescription;
e.RTCPeerConnection.prototype.setRemoteDescription = function (t) {
if (t && t.sdp && -1 !== t.sdp.indexOf("\na=extmap-allow-mixed")) {
let n = t.sdp
.split("\n")
.filter((e) => "a=extmap-allow-mixed" !== e.trim())
.join("\n");
e.RTCSessionDescription && t instanceof e.RTCSessionDescription
? (arguments[0] = new e.RTCSessionDescription({
type: t.type,
sdp: n,
}))
: (t.sdp = n);
}
return n.apply(this, arguments);
};
}
function eT(e, t) {
if (!(e.RTCPeerConnection && e.RTCPeerConnection.prototype)) return;
let n = e.RTCPeerConnection.prototype.addIceCandidate;
n &&
0 !== n.length &&
(e.RTCPeerConnection.prototype.addIceCandidate = function () {
return arguments[0]
? (("chrome" === t.browser && t.version < 78) ||
("firefox" === t.browser && t.version < 68) ||
"safari" === t.browser) &&
arguments[0] &&
"" === arguments[0].candidate
? Promise.resolve()
: n.apply(this, arguments)
: (arguments[1] && arguments[1].apply(null), Promise.resolve());
});
}
function eR(e, t) {
if (!(e.RTCPeerConnection && e.RTCPeerConnection.prototype)) return;
let n = e.RTCPeerConnection.prototype.setLocalDescription;
n &&
0 !== n.length &&
(e.RTCPeerConnection.prototype.setLocalDescription = function () {
let e = arguments[0] || {};
if ("object" != typeof e || (e.type && e.sdp))
return n.apply(this, arguments);
if (!(e = { type: e.type, sdp: e.sdp }).type)
switch (this.signalingState) {
case "stable":
case "have-local-offer":
case "have-remote-pranswer":
e.type = "offer";
break;
default:
e.type = "answer";
}
return e.sdp || ("offer" !== e.type && "answer" !== e.type)
? n.apply(this, [e])
: ("offer" === e.type ? this.createOffer : this.createAnswer)
.apply(this)
.then((e) => n.apply(this, [e]));
});
}
(ey.generateIdentifier = function () {
return Math.random().toString(36).substring(2, 12);
}),
(ey.localCName = ey.generateIdentifier()),
(ey.splitLines = function (e) {
return e
.trim()
.split("\n")
.map((e) => e.trim());
}),
(ey.splitSections = function (e) {
return e
.split("\nm=")
.map((e, t) => (t > 0 ? "m=" + e : e).trim() + "\r\n");
}),
(ey.getDescription = function (e) {
let t = ey.splitSections(e);
return t && t[0];
}),
(ey.getMediaSections = function (e) {
let t = ey.splitSections(e);
return t.shift(), t;
}),
(ey.matchPrefix = function (e, t) {
return ey.splitLines(e).filter((e) => 0 === e.indexOf(t));
}),
(ey.parseCandidate = function (e) {
let t;
let n = {
foundation: (t =
0 === e.indexOf("a=candidate:")
? e.substring(12).split(" ")
: e.substring(10).split(" "))[0],
component: { 1: "rtp", 2: "rtcp" }[t[1]] || t[1],
protocol: t[2].toLowerCase(),
priority: parseInt(t[3], 10),
ip: t[4],
address: t[4],
port: parseInt(t[5], 10),
type: t[7],
};
for (let e = 8; e < t.length; e += 2)
switch (t[e]) {
case "raddr":
n.relatedAddress = t[e + 1];
break;
case "rport":
n.relatedPort = parseInt(t[e + 1], 10);
break;
case "tcptype":
n.tcpType = t[e + 1];
break;
case "ufrag":
(n.ufrag = t[e + 1]), (n.usernameFragment = t[e + 1]);
break;
default:
void 0 === n[t[e]] && (n[t[e]] = t[e + 1]);
}
return n;
}),
(ey.writeCandidate = function (e) {
let t = [];
t.push(e.foundation);
let n = e.component;
"rtp" === n ? t.push(1) : "rtcp" === n ? t.push(2) : t.push(n),
t.push(e.protocol.toUpperCase()),
t.push(e.priority),
t.push(e.address || e.ip),
t.push(e.port);
let r = e.type;
return (
t.push("typ"),
t.push(r),
"host" !== r &&
e.relatedAddress &&
e.relatedPort &&
(t.push("raddr"),
t.push(e.relatedAddress),
t.push("rport"),
t.push(e.relatedPort)),
e.tcpType &&
"tcp" === e.protocol.toLowerCase() &&
(t.push("tcptype"), t.push(e.tcpType)),
(e.usernameFragment || e.ufrag) &&
(t.push("ufrag"), t.push(e.usernameFragment || e.ufrag)),
"candidate:" + t.join(" ")
);
}),
(ey.parseIceOptions = function (e) {
return e.substring(14).split(" ");
}),
(ey.parseRtpMap = function (e) {
let t = e.substring(9).split(" "),
n = { payloadType: parseInt(t.shift(), 10) };
return (
(t = t[0].split("/")),
(n.name = t[0]),
(n.clockRate = parseInt(t[1], 10)),
(n.channels = 3 === t.length ? parseInt(t[2], 10) : 1),
(n.numChannels = n.channels),
n
);
}),
(ey.writeRtpMap = function (e) {
let t = e.payloadType;
void 0 !== e.preferredPayloadType && (t = e.preferredPayloadType);
let n = e.channels || e.numChannels || 1;
return (
"a=rtpmap:" +
t +
" " +
e.name +
"/" +
e.clockRate +
(1 !== n ? "/" + n : "") +
"\r\n"
);
}),
(ey.parseExtmap = function (e) {
let t = e.substring(9).split(" ");
return {
id: parseInt(t[0], 10),
direction: t[0].indexOf("/") > 0 ? t[0].split("/")[1] : "sendrecv",
uri: t[1],
attributes: t.slice(2).join(" "),
};
}),
(ey.writeExtmap = function (e) {
return (
"a=extmap:" +
(e.id || e.preferredId) +
(e.direction && "sendrecv" !== e.direction ? "/" + e.direction : "") +
" " +
e.uri +
(e.attributes ? " " + e.attributes : "") +
"\r\n"
);
}),
(ey.parseFmtp = function (e) {
let t;
let n = {},
r = e.substring(e.indexOf(" ") + 1).split(";");
for (let e = 0; e < r.length; e++)
n[(t = r[e].trim().split("="))[0].trim()] = t[1];
return n;
}),
(ey.writeFmtp = function (e) {
let t = "",
n = e.payloadType;
if (
(void 0 !== e.preferredPayloadType && (n = e.preferredPayloadType),
e.parameters && Object.keys(e.parameters).length)
) {
let r = [];
Object.keys(e.parameters).forEach((t) => {
void 0 !== e.parameters[t]
? r.push(t + "=" + e.parameters[t])
: r.push(t);
}),
(t += "a=fmtp:" + n + " " + r.join(";") + "\r\n");
}
return t;
}),
(ey.parseRtcpFb = function (e) {
let t = e.substring(e.indexOf(" ") + 1).split(" ");
return { type: t.shift(), parameter: t.join(" ") };
}),
(ey.writeRtcpFb = function (e) {
let t = "",
n = e.payloadType;
return (
void 0 !== e.preferredPayloadType && (n = e.preferredPayloadType),
e.rtcpFeedback &&
e.rtcpFeedback.length &&
e.rtcpFeedback.forEach((e) => {
t +=
"a=rtcp-fb:" +
n +
" " +
e.type +
(e.parameter && e.parameter.length ? " " + e.parameter : "") +
"\r\n";
}),
t
);
}),
(ey.parseSsrcMedia = function (e) {
let t = e.indexOf(" "),
n = { ssrc: parseInt(e.substring(7, t), 10) },
r = e.indexOf(":", t);
return (
r > -1
? ((n.attribute = e.substring(t + 1, r)),
(n.value = e.substring(r + 1)))
: (n.attribute = e.substring(t + 1)),
n
);
}),
(ey.parseSsrcGroup = function (e) {
let t = e.substring(13).split(" ");
return { semantics: t.shift(), ssrcs: t.map((e) => parseInt(e, 10)) };
}),
(ey.getMid = function (e) {
let t = ey.matchPrefix(e, "a=mid:")[0];
if (t) return t.substring(6);
}),
(ey.parseFingerprint = function (e) {
let t = e.substring(14).split(" ");
return { algorithm: t[0].toLowerCase(), value: t[1].toUpperCase() };
}),
(ey.getDtlsParameters = function (e, t) {
return {
role: "auto",
fingerprints: ey
.matchPrefix(e + t, "a=fingerprint:")
.map(ey.parseFingerprint),
};
}),
(ey.writeDtlsParameters = function (e, t) {
let n = "a=setup:" + t + "\r\n";
return (
e.fingerprints.forEach((e) => {
n += "a=fingerprint:" + e.algorithm + " " + e.value + "\r\n";
}),
n
);
}),
(ey.parseCryptoLine = function (e) {
let t = e.substring(9).split(" ");
return {
tag: parseInt(t[0], 10),
cryptoSuite: t[1],
keyParams: t[2],
sessionParams: t.slice(3),
};
}),
(ey.writeCryptoLine = function (e) {
return (
"a=crypto:" +
e.tag +
" " +
e.cryptoSuite +
" " +
("object" == typeof e.keyParams
? ey.writeCryptoKeyParams(e.keyParams)
: e.keyParams) +
(e.sessionParams ? " " + e.sessionParams.join(" ") : "") +
"\r\n"
);
}),
(ey.parseCryptoKeyParams = function (e) {
if (0 !== e.indexOf("inline:")) return null;
let t = e.substring(7).split("|");
return {
keyMethod: "inline",
keySalt: t[0],
lifeTime: t[1],
mkiValue: t[2] ? t[2].split(":")[0] : void 0,
mkiLength: t[2] ? t[2].split(":")[1] : void 0,
};
}),
(ey.writeCryptoKeyParams = function (e) {
return (
e.keyMethod +
":" +
e.keySalt +
(e.lifeTime ? "|" + e.lifeTime : "") +
(e.mkiValue && e.mkiLength ? "|" + e.mkiValue + ":" + e.mkiLength : "")
);
}),
(ey.getCryptoParameters = function (e, t) {
return ey.matchPrefix(e + t, "a=crypto:").map(ey.parseCryptoLine);
}),
(ey.getIceParameters = function (e, t) {
let n = ey.matchPrefix(e + t, "a=ice-ufrag:")[0],
r = ey.matchPrefix(e + t, "a=ice-pwd:")[0];
return n && r
? { usernameFragment: n.substring(12), password: r.substring(10) }
: null;
}),
(ey.writeIceParameters = function (e) {
let t =
"a=ice-ufrag:" +
e.usernameFragment +
"\r\na=ice-pwd:" +
e.password +
"\r\n";
return e.iceLite && (t += "a=ice-lite\r\n"), t;
}),
(ey.parseRtpParameters = function (e) {
let t = { codecs: [], headerExtensions: [], fecMechanisms: [], rtcp: [] },
n = ey.splitLines(e)[0].split(" ");
t.profile = n[2];
for (let r = 3; r < n.length; r++) {
let i = n[r],
o = ey.matchPrefix(e, "a=rtpmap:" + i + " ")[0];
if (o) {
let n = ey.parseRtpMap(o),
r = ey.matchPrefix(e, "a=fmtp:" + i + " ");
switch (
((n.parameters = r.length ? ey.parseFmtp(r[0]) : {}),
(n.rtcpFeedback = ey
.matchPrefix(e, "a=rtcp-fb:" + i + " ")
.map(ey.parseRtcpFb)),
t.codecs.push(n),
n.name.toUpperCase())
) {
case "RED":
case "ULPFEC":
t.fecMechanisms.push(n.name.toUpperCase());
}
}
}
ey.matchPrefix(e, "a=extmap:").forEach((e) => {
t.headerExtensions.push(ey.parseExtmap(e));
});
let r = ey.matchPrefix(e, "a=rtcp-fb:* ").map(ey.parseRtcpFb);
return (
t.codecs.forEach((e) => {
r.forEach((t) => {
e.rtcpFeedback.find(
(e) => e.type === t.type && e.parameter === t.parameter
) || e.rtcpFeedback.push(t);
});
}),
t
);
}),
(ey.writeRtpDescription = function (e, t) {
let n = "";
(n +=
"m=" +
e +
" " +
(t.codecs.length > 0 ? "9" : "0") +
" " +
(t.profile || "UDP/TLS/RTP/SAVPF") +
" " +
t.codecs
.map((e) =>
void 0 !== e.preferredPayloadType
? e.preferredPayloadType
: e.payloadType
)
.join(" ") +
"\r\nc=IN IP4 0.0.0.0\r\na=rtcp:9 IN IP4 0.0.0.0\r\n"),
t.codecs.forEach((e) => {
n += ey.writeRtpMap(e) + ey.writeFmtp(e) + ey.writeRtcpFb(e);
});
let r = 0;
return (
t.codecs.forEach((e) => {
e.maxptime > r && (r = e.maxptime);
}),
r > 0 && (n += "a=maxptime:" + r + "\r\n"),
t.headerExtensions &&
t.headerExtensions.forEach((e) => {
n += ey.writeExtmap(e);
}),
n
);
}),
(ey.parseRtpEncodingParameters = function (e) {
let t;
let n = [],
r = ey.parseRtpParameters(e),
i = -1 !== r.fecMechanisms.indexOf("RED"),
o = -1 !== r.fecMechanisms.indexOf("ULPFEC"),
s = ey
.matchPrefix(e, "a=ssrc:")
.map((e) => ey.parseSsrcMedia(e))
.filter((e) => "cname" === e.attribute),
a = s.length > 0 && s[0].ssrc,
c = ey.matchPrefix(e, "a=ssrc-group:FID").map((e) =>
e
.substring(17)
.split(" ")
.map((e) => parseInt(e, 10))
);
c.length > 0 && c[0].length > 1 && c[0][0] === a && (t = c[0][1]),
r.codecs.forEach((e) => {
if ("RTX" === e.name.toUpperCase() && e.parameters.apt) {
let r = {
ssrc: a,
codecPayloadType: parseInt(e.parameters.apt, 10),
};
a && t && (r.rtx = { ssrc: t }),
n.push(r),
i &&
(((r = JSON.parse(JSON.stringify(r))).fec = {
ssrc: a,
mechanism: o ? "red+ulpfec" : "red",
}),
n.push(r));
}
}),
0 === n.length && a && n.push({ ssrc: a });
let l = ey.matchPrefix(e, "b=");
return (
l.length &&
((l =
0 === l[0].indexOf("b=TIAS:")
? parseInt(l[0].substring(7), 10)
: 0 === l[0].indexOf("b=AS:")
? 950 * parseInt(l[0].substring(5), 10) - 16e3
: void 0),
n.forEach((e) => {
e.maxBitrate = l;
})),
n
);
}),
(ey.parseRtcpParameters = function (e) {
let t = {},
n = ey
.matchPrefix(e, "a=ssrc:")
.map((e) => ey.parseSsrcMedia(e))
.filter((e) => "cname" === e.attribute)[0];
n && ((t.cname = n.value), (t.ssrc = n.ssrc));
let r = ey.matchPrefix(e, "a=rtcp-rsize");
(t.reducedSize = r.length > 0), (t.compound = 0 === r.length);
let i = ey.matchPrefix(e, "a=rtcp-mux");
return (t.mux = i.length > 0), t;
}),
(ey.writeRtcpParameters = function (e) {
let t = "";
return (
e.reducedSize && (t += "a=rtcp-rsize\r\n"),
e.mux && (t += "a=rtcp-mux\r\n"),
void 0 !== e.ssrc &&
e.cname &&
(t += "a=ssrc:" + e.ssrc + " cname:" + e.cname + "\r\n"),
t
);
}),
(ey.parseMsid = function (e) {
let t;
let n = ey.matchPrefix(e, "a=msid:");
if (1 === n.length)
return { stream: (t = n[0].substring(7).split(" "))[0], track: t[1] };
let r = ey
.matchPrefix(e, "a=ssrc:")
.map((e) => ey.parseSsrcMedia(e))
.filter((e) => "msid" === e.attribute);
if (r.length > 0)
return { stream: (t = r[0].value.split(" "))[0], track: t[1] };
}),
(ey.parseSctpDescription = function (e) {
let t;
let n = ey.parseMLine(e),
r = ey.matchPrefix(e, "a=max-message-size:");
r.length > 0 && (t = parseInt(r[0].substring(19), 10)),
isNaN(t) && (t = 65536);
let i = ey.matchPrefix(e, "a=sctp-port:");
if (i.length > 0)
return {
port: parseInt(i[0].substring(12), 10),
protocol: n.fmt,
maxMessageSize: t,
};
let o = ey.matchPrefix(e, "a=sctpmap:");
if (o.length > 0) {
let e = o[0].substring(10).split(" ");
return { port: parseInt(e[0], 10), protocol: e[1], maxMessageSize: t };
}
}),
(ey.writeSctpDescription = function (e, t) {
let n = [];
return (
(n =
"DTLS/SCTP" !== e.protocol
? [
"m=" + e.kind + " 9 " + e.protocol + " " + t.protocol + "\r\n",
"c=IN IP4 0.0.0.0\r\n",
"a=sctp-port:" + t.port + "\r\n",
]
: [
"m=" + e.kind + " 9 " + e.protocol + " " + t.port + "\r\n",
"c=IN IP4 0.0.0.0\r\n",
"a=sctpmap:" + t.port + " " + t.protocol + " 65535\r\n",
]),
void 0 !== t.maxMessageSize &&
n.push("a=max-message-size:" + t.maxMessageSize + "\r\n"),
n.join("")
);
}),
(ey.generateSessionId = function () {
return Math.random().toString().substr(2, 22);
}),
(ey.writeSessionBoilerplate = function (e, t, n) {
return (
"v=0\r\no=" +
(n || "thisisadapterortc") +
" " +
(e || ey.generateSessionId()) +
" " +
(void 0 !== t ? t : 2) +
" IN IP4 127.0.0.1\r\ns=-\r\nt=0 0\r\n"
);
}),
(ey.getDirection = function (e, t) {
let n = ey.splitLines(e);
for (let e = 0; e < n.length; e++)
switch (n[e]) {
case "a=sendrecv":
case "a=sendonly":
case "a=recvonly":
case "a=inactive":
return n[e].substring(2);
}
return t ? ey.getDirection(t) : "sendrecv";
}),
(ey.getKind = function (e) {
return ey.splitLines(e)[0].split(" ")[0].substring(2);
}),
(ey.isRejected = function (e) {
return "0" === e.split(" ", 2)[1];
}),
(ey.parseMLine = function (e) {
let t = ey.splitLines(e)[0].substring(2).split(" ");
return {
kind: t[0],
port: parseInt(t[1], 10),
protocol: t[2],
fmt: t.slice(3).join(" "),
};
}),
(ey.parseOLine = function (e) {
let t = ey.matchPrefix(e, "o=")[0].substring(2).split(" ");
return {
username: t[0],
sessionId: t[1],
sessionVersion: parseInt(t[2], 10),
netType: t[3],
addressType: t[4],
address: t[5],
};
}),
(ey.isValidSDP = function (e) {
if ("string" != typeof e || 0 === e.length) return !1;
let t = ey.splitLines(e);
for (let e = 0; e < t.length; e++)
if (t[e].length < 2 || "=" !== t[e].charAt(1)) return !1;
return !0;
}),
(eg = ey);
let ew = (function (
{ window: e } = {},
t = { shimChrome: !0, shimFirefox: !0, shimSafari: !0 }
) {
let n = (function (e) {
let t = { browser: null, version: null };
if (void 0 === e || !e.navigator || !e.navigator.userAgent)
return (t.browser = "Not a browser."), t;
let { navigator: n } = e;
return (
n.mozGetUserMedia
? ((t.browser = "firefox"),
(t.version = p(n.userAgent, /Firefox\/(\d+)\./, 1)))
: n.webkitGetUserMedia ||
(!1 === e.isSecureContext && e.webkitRTCPeerConnection)
? ((t.browser = "chrome"),
(t.version = p(n.userAgent, /Chrom(e|ium)\/(\d+)\./, 2)))
: e.RTCPeerConnection && n.userAgent.match(/AppleWebKit\/(\d+)\./)
? ((t.browser = "safari"),
(t.version = p(n.userAgent, /AppleWebKit\/(\d+)\./, 1)),
(t.supportsUnifiedPlan =
e.RTCRtpTransceiver &&
"currentDirection" in e.RTCRtpTransceiver.prototype))
: (t.browser = "Not a supported browser."),
t
);
})(e),
r = {
browserDetails: n,
commonShim: em,
extractVersion: p,
disableLog: h,
disableWarnings: u,
sdp: eg,
};
switch (n.browser) {
case "chrome":
if (!j || !j.shimPeerConnection || !t.shimChrome) {
f("Chrome shim is not included in this adapter release.");
break;
}
if (null === n.version) {
f("Chrome shim can not determine version, not shimming.");
break;
}
f("adapter.js shimming chrome."),
(r.browserShim = j),
eT(e, n),
eR(e, n),
j.shimGetUserMedia(e, n),
j.shimMediaStream(e, n),
j.shimPeerConnection(e, n),
j.shimOnTrack(e, n),
j.shimAddTrackRemoveTrack(e, n),
j.shimGetSendersWithDtmf(e, n),
j.shimGetStats(e, n),
j.shimSenderReceiverGetStats(e, n),
j.fixNegotiationNeeded(e, n),
e_(e, n),
eC(e, n),
ek(e, n),
ev(e, n),
eb(e, n),
eS(e, n);
break;
case "firefox":
if (!W || !W.shimPeerConnection || !t.shimFirefox) {
f("Firefox shim is not included in this adapter release.");
break;
}
f("adapter.js shimming firefox."),
(r.browserShim = W),
eT(e, n),
eR(e, n),
W.shimGetUserMedia(e, n),
W.shimPeerConnection(e, n),
W.shimOnTrack(e, n),
W.shimRemoveStream(e, n),
W.shimSenderGetStats(e, n),
W.shimReceiverGetStats(e, n),
W.shimRTCDataChannel(e, n),
W.shimAddTransceiver(e, n),
W.shimGetParameters(e, n),
W.shimCreateOffer(e, n),
W.shimCreateAnswer(e, n),
e_(e, n),
ek(e, n),
ev(e, n),
eb(e, n);
break;
case "safari":
if (!eo || !t.shimSafari) {
f("Safari shim is not included in this adapter release.");
break;
}
f("adapter.js shimming safari."),
(r.browserShim = eo),
eT(e, n),
eR(e, n),
eo.shimRTCIceServerUrls(e, n),
eo.shimCreateOfferLegacy(e, n),
eo.shimCallbacksAPI(e, n),
eo.shimLocalStreamsAPI(e, n),
eo.shimRemoteStreamsAPI(e, n),
eo.shimTrackEventTransceiver(e, n),
eo.shimGetUserMedia(e, n),
eo.shimAudioContext(e, n),
e_(e, n),
eC(e, n),
ev(e, n),
eb(e, n),
eS(e, n);
break;
default:
f("Unsupported browser!");
}
return r;
})({ window: "undefined" == typeof window ? void 0 : window }),
eP = ew.default || ew,
eE = new (class {
isWebRTCSupported() {
return "undefined" != typeof RTCPeerConnection;
}
isBrowserSupported() {
let e = this.getBrowser(),
t = this.getVersion();
return (
!!this.supportedBrowsers.includes(e) &&
("chrome" === e
? t >= this.minChromeVersion
: "firefox" === e
? t >= this.minFirefoxVersion
: "safari" === e && !this.isIOS && t >= this.minSafariVersion)
);
}
getBrowser() {
return eP.browserDetails.browser;
}
getVersion() {
return eP.browserDetails.version || 0;
}
isUnifiedPlanSupported() {
let e;
let t = this.getBrowser(),
n = eP.browserDetails.version || 0;
if ("chrome" === t && n < this.minChromeVersion) return !1;
if ("firefox" === t && n >= this.minFirefoxVersion) return !0;
if (
!window.RTCRtpTransceiver ||
!("currentDirection" in RTCRtpTransceiver.prototype)
)
return !1;
let r = !1;
try {
(e = new RTCPeerConnection()).addTransceiver("audio"), (r = !0);
} catch (e) {
} finally {
e && e.close();
}
return r;
}
toString() {
return `Supports:
browser:${this.getBrowser()}
version:${this.getVersion()}
isIOS:${this.isIOS}
isWebRTCSupported:${this.isWebRTCSupported()}
isBrowserSupported:${this.isBrowserSupported()}
isUnifiedPlanSupported:${this.isUnifiedPlanSupported()}`;
}
constructor() {
(this.isIOS = ["iPad", "iPhone", "iPod"].includes(navigator.platform)),
(this.supportedBrowsers = ["firefox", "chrome", "safari"]),
(this.minFirefoxVersion = 59),
(this.minChromeVersion = 72),
(this.minSafariVersion = 605);
}
})(),
eD = (e) => !e || /^[A-Za-z0-9]+(?:[ _-][A-Za-z0-9]+)*$/.test(e),
ex = () => Math.random().toString(36).slice(2),
eI = {
iceServers: [
{ urls: "stun:stun.l.google.com:19302" },
{
urls: [
"turn:eu-0.turn.peerjs.com:3478",
"turn:us-0.turn.peerjs.com:3478",
],
username: "peerjs",
credential: "peerjsp",
},
],
sdpSemantics: "unified-plan",
},
eM = new (class extends n {
noop() {}
blobToArrayBuffer(e, t) {
let n = new FileReader();
return (
(n.onload = function (e) {
e.target && t(e.target.result);
}),
n.readAsArrayBuffer(e),
n
);
}
binaryStringToArrayBuffer(e) {
let t = new Uint8Array(e.length);
for (let n = 0; n < e.length; n++) t[n] = 255 & e.charCodeAt(n);
return t.buffer;
}
isSecure() {
return "https:" === location.protocol;
}
constructor(...e) {
super(...e),
(this.CLOUD_HOST = "0.peerjs.com"),
(this.CLOUD_PORT = 443),
(this.chunkedBrowsers = { Chrome: 1, chrome: 1 }),
(this.defaultConfig = eI),
(this.browser = eE.getBrowser()),
(this.browserVersion = eE.getVersion()),
(this.pack = o),
(this.unpack = i),
(this.supports = (function () {
let e;
let t = {
browser: eE.isBrowserSupported(),
webRTC: eE.isWebRTCSupported(),
audioVideo: !1,
data: !1,
binaryBlob: !1,
reliable: !1,
};
if (!t.webRTC) return t;
try {
let n;
(e = new RTCPeerConnection(eI)), (t.audioVideo = !0);
try {
(n = e.createDataChannel("_PEERJSTEST", { ordered: !0 })),
(t.data = !0),
(t.reliable = !!n.ordered);
try {
(n.binaryType = "blob"), (t.binaryBlob = !eE.isIOS);
} catch (e) {}
} catch (e) {
} finally {
n && n.close();
}
} catch (e) {
} finally {
e && e.close();
}
return t;
})()),
(this.validateId = eD),
(this.randomToken = ex);
}
})();
((_ = w || (w = {}))[(_.Disabled = 0)] = "Disabled"),
(_[(_.Errors = 1)] = "Errors"),
(_[(_.Warnings = 2)] = "Warnings"),
(_[(_.All = 3)] = "All");
var eO = new (class {
get logLevel() {
return this._logLevel;
}
set logLevel(e) {
this._logLevel = e;
}
log(...e) {
this._logLevel >= 3 && this._print(3, ...e);
}
warn(...e) {
this._logLevel >= 2 && this._print(2, ...e);
}
error(...e) {
this._logLevel >= 1 && this._print(1, ...e);
}
setLogFunction(e) {
this._print = e;
}
_print(e, ...t) {
let n = ["PeerJS: ", ...t];
for (let e in n)
n[e] instanceof Error &&
(n[e] = "(" + n[e].name + ") " + n[e].message);
e >= 3
? console.log(...n)
: e >= 2
? console.warn("WARNING", ...n)
: e >= 1 && console.error("ERROR", ...n);
}
constructor() {
this._logLevel = 0;
}
})(),
ej = {},
eL = Object.prototype.hasOwnProperty,
eA = "~";
function eB() {}
function eF(e, t, n) {
(this.fn = e), (this.context = t), (this.once = n || !1);
}
function eU(e, t, n, r, i) {
if ("function" != typeof n)
throw TypeError("The listener must be a function");
var o = new eF(n, r || e, i),
s = eA ? eA + t : t;
return (
e._events[s]
? e._events[s].fn
? (e._events[s] = [e._events[s], o])
: e._events[s].push(o)
: ((e._events[s] = o), e._eventsCount++),
e
);
}
function ez(e, t) {
0 == --e._eventsCount ? (e._events = new eB()) : delete e._events[t];
}
function eN() {
(this._events = new eB()), (this._eventsCount = 0);
}
Object.create &&
((eB.prototype = Object.create(null)), new eB().__proto__ || (eA = !1)),
(eN.prototype.eventNames = function () {
var e,
t,
n = [];
if (0 === this._eventsCount) return n;
for (t in (e = this._events))
eL.call(e, t) && n.push(eA ? t.slice(1) : t);
return Object.getOwnPropertySymbols
? n.concat(Object.getOwnPropertySymbols(e))
: n;
}),
(eN.prototype.listeners = function (e) {
var t = eA ? eA + e : e,
n = this._events[t];
if (!n) return [];
if (n.fn) return [n.fn];
for (var r = 0, i = n.length, o = Array(i); r < i; r++) o[r] = n[r].fn;
return o;
}),
(eN.prototype.listenerCount = function (e) {
var t = eA ? eA + e : e,
n = this._events[t];
return n ? (n.fn ? 1 : n.length) : 0;
}),
(eN.prototype.emit = function (e, t, n, r, i, o) {
var s = eA ? eA + e : e;
if (!this._events[s]) return !1;
var a,
c,
l = this._events[s],
p = arguments.length;
if (l.fn) {
switch ((l.once && this.removeListener(e, l.fn, void 0, !0), p)) {
case 1:
return l.fn.call(l.context), !0;
case 2:
return l.fn.call(l.context, t), !0;
case 3:
return l.fn.call(l.context, t, n), !0;
case 4:
return l.fn.call(l.context, t, n, r), !0;
case 5:
return l.fn.call(l.context, t, n, r, i), !0;
case 6:
return l.fn.call(l.context, t, n, r, i, o), !0;
}
for (c = 1, a = Array(p - 1); c < p; c++) a[c - 1] = arguments[c];
l.fn.apply(l.context, a);
} else {
var d,
h = l.length;
for (c = 0; c < h; c++)
switch (
(l[c].once && this.removeListener(e, l[c].fn, void 0, !0), p)
) {
case 1:
l[c].fn.call(l[c].context);
break;
case 2:
l[c].fn.call(l[c].context, t);
break;
case 3:
l[c].fn.call(l[c].context, t, n);
break;
case 4:
l[c].fn.call(l[c].context, t, n, r);
break;
default:
if (!a)
for (d = 1, a = Array(p - 1); d < p; d++)
a[d - 1] = arguments[d];
l[c].fn.apply(l[c].context, a);
}
}
return !0;
}),
(eN.prototype.on = function (e, t, n) {
return eU(this, e, t, n, !1);
}),
(eN.prototype.once = function (e, t, n) {
return eU(this, e, t, n, !0);
}),
(eN.prototype.removeListener = function (e, t, n, r) {
var i = eA ? eA + e : e;
if (!this._events[i]) return this;
if (!t) return ez(this, i), this;
var o = this._events[i];
if (o.fn)
o.fn !== t || (r && !o.once) || (n && o.context !== n) || ez(this, i);
else {
for (var s = 0, a = [], c = o.length; s < c; s++)
(o[s].fn !== t || (r && !o[s].once) || (n && o[s].context !== n)) &&
a.push(o[s]);
a.length ? (this._events[i] = 1 === a.length ? a[0] : a) : ez(this, i);
}
return this;
}),
(eN.prototype.removeAllListeners = function (e) {
var t;
return (
e
? ((t = eA ? eA + e : e), this._events[t] && ez(this, t))
: ((this._events = new eB()), (this._eventsCount = 0)),
this
);
}),
(eN.prototype.off = eN.prototype.removeListener),
(eN.prototype.addListener = eN.prototype.on),
(eN.prefixed = eA),
(eN.EventEmitter = eN),
(ej = eN),
((C = P || (P = {})).Data = "data"),
(C.Media = "media"),
((v = E || (E = {})).BrowserIncompatible = "browser-incompatible"),
(v.Disconnected = "disconnected"),
(v.InvalidID = "invalid-id"),
(v.InvalidKey = "invalid-key"),
(v.Network = "network"),
(v.PeerUnavailable = "peer-unavailable"),
(v.SslUnavailable = "ssl-unavailable"),
(v.ServerError = "server-error"),
(v.SocketError = "socket-error"),
(v.SocketClosed = "socket-closed"),
(v.UnavailableID = "unavailable-id"),
(v.WebRTC = "webrtc"),
((b = D || (D = {})).NegotiationFailed = "negotiation-failed"),
(b.ConnectionClosed = "connection-closed"),
((k = x || (x = {})).NotOpenYet = "not-open-yet"),
(k.MessageToBig = "message-too-big"),
((S = I || (I = {})).Binary = "binary"),
(S.BinaryUTF8 = "binary-utf8"),
(S.JSON = "json"),
(S.None = "raw"),
((T = M || (M = {})).Message = "message"),
(T.Disconnected = "disconnected"),
(T.Error = "error"),
(T.Close = "close"),
((R = O || (O = {})).Heartbeat = "HEARTBEAT"),
(R.Candidate = "CANDIDATE"),
(R.Offer = "OFFER"),
(R.Answer = "ANSWER"),
(R.Open = "OPEN"),
(R.Error = "ERROR"),
(R.IdTaken = "ID-TAKEN"),
(R.InvalidKey = "INVALID-KEY"),
(R.Leave = "LEAVE"),
(R.Expire = "EXPIRE");
var e$ = {};
e$ = JSON.parse(
'{"name":"peerjs","version":"1.5.2","keywords":["peerjs","webrtc","p2p","rtc"],"description":"PeerJS client","homepage":"https://peerjs.com","bugs":{"url":"https://github.com/peers/peerjs/issues"},"repository":{"type":"git","url":"https://github.com/peers/peerjs"},"license":"MIT","contributors":["Michelle Bu <michelle@michellebu.com>","afrokick <devbyru@gmail.com>","ericz <really.ez@gmail.com>","Jairo <kidandcat@gmail.com>","Jonas Gloning <34194370+jonasgloning@users.noreply.github.com>","Jairo Caro-Accino Viciana <jairo@galax.be>","Carlos Caballero <carlos.caballero.gonzalez@gmail.com>","hc <hheennrryy@gmail.com>","Muhammad Asif <capripio@gmail.com>","PrashoonB <prashoonbhattacharjee@gmail.com>","Harsh Bardhan Mishra <47351025+HarshCasper@users.noreply.github.com>","akotynski <aleksanderkotbury@gmail.com>","lmb <i@lmb.io>","Jairooo <jairocaro@msn.com>","Moritz Stückler <moritz.stueckler@gmail.com>","Simon <crydotsnakegithub@gmail.com>","Denis Lukov <denismassters@gmail.com>","Philipp Hancke <fippo@andyet.net>","Hans Oksendahl <hansoksendahl@gmail.com>","Jess <jessachandler@gmail.com>","khankuan <khankuan@gmail.com>","DUODVK <kurmanov.work@gmail.com>","XiZhao <kwang1imsa@gmail.com>","Matthias Lohr <matthias@lohr.me>","=frank tree <=frnktrb@googlemail.com>","Andre Eckardt <aeckardt@outlook.com>","Chris Cowan <agentme49@gmail.com>","Alex Chuev <alex@chuev.com>","alxnull <alxnull@e.mail.de>","Yemel Jardi <angel.jardi@gmail.com>","Ben Parnell <benjaminparnell.94@gmail.com>","Benny Lichtner <bennlich@gmail.com>","fresheneesz <bitetrudpublic@gmail.com>","bob.barstead@exaptive.com <bob.barstead@exaptive.com>","chandika <chandika@gmail.com>","emersion <contact@emersion.fr>","Christopher Van <cvan@users.noreply.github.com>","eddieherm <edhermoso@gmail.com>","Eduardo Pinho <enet4mikeenet@gmail.com>","Evandro Zanatta <ezanatta@tray.net.br>","Gardner Bickford <gardner@users.noreply.github.com>","Gian Luca <gianluca.cecchi@cynny.com>","PatrickJS <github@gdi2290.com>","jonnyf <github@jonathanfoss.co.uk>","Hizkia Felix <hizkifw@gmail.com>","Hristo Oskov <hristo.oskov@gmail.com>","Isaac Madwed <i.madwed@gmail.com>","Ilya Konanykhin <ilya.konanykhin@gmail.com>","jasonbarry <jasbarry@me.com>","Jonathan Burke <jonathan.burke.1311@googlemail.com>","Josh Hamit <josh.hamit@gmail.com>","Jordan Austin <jrax86@gmail.com>","Joel Wetzell <jwetzell@yahoo.com>","xizhao <kevin.wang@cloudera.com>","Alberto Torres <kungfoobar@gmail.com>","Jonathan Mayol <mayoljonathan@gmail.com>","Jefferson Felix <me@jsfelix.dev>","Rolf Erik Lekang <me@rolflekang.com>","Kevin Mai-Husan Chia <mhchia@users.noreply.github.com>","Pepijn de Vos <pepijndevos@gmail.com>","JooYoung <qkdlql@naver.com>","Tobias Speicher <rootcommander@gmail.com>","Steve Blaurock <sblaurock@gmail.com>","Kyrylo Shegeda <shegeda@ualberta.ca>","Diwank Singh Tomer <singh@diwank.name>","Sören Balko <Soeren.Balko@gmail.com>","Arpit Solanki <solankiarpit1997@gmail.com>","Yuki Ito <yuki@gnnk.net>","Artur Zayats <zag2art@gmail.com>"],"funding":{"type":"opencollective","url":"https://opencollective.com/peer"},"collective":{"type":"opencollective","url":"https://opencollective.com/peer"},"files":["dist/*"],"sideEffects":["lib/global.ts","lib/supports.ts"],"main":"dist/bundler.cjs","module":"dist/bundler.mjs","browser-minified":"dist/peerjs.min.js","browser-unminified":"dist/peerjs.js","browser-minified-cbor":"dist/serializer.cbor.mjs","browser-minified-msgpack":"dist/serializer.msgpack.mjs","types":"dist/types.d.ts","engines":{"node":">= 14"},"targets":{"types":{"source":"lib/exports.ts"},"main":{"source":"lib/exports.ts","sourceMap":{"inlineSources":true}},"module":{"source":"lib/exports.ts","includeNodeModules":["eventemitter3"],"sourceMap":{"inlineSources":true}},"browser-minified":{"context":"browser","outputFormat":"global","optimize":true,"engines":{"browsers":"chrome >= 83, edge >= 83, firefox >= 80, safari >= 15"},"source":"lib/global.ts"},"browser-unminified":{"context":"browser","outputFormat":"global","optimize":false,"engines":{"browsers":"chrome >= 83, edge >= 83, firefox >= 80, safari >= 15"},"source":"lib/global.ts"},"browser-minified-cbor":{"context":"browser","outputFormat":"esmodule","isLibrary":true,"optimize":true,"engines":{"browsers":"chrome >= 83, edge >= 83, firefox >= 102, safari >= 15"},"source":"lib/dataconnection/StreamConnection/Cbor.ts"},"browser-minified-msgpack":{"context":"browser","outputFormat":"esmodule","isLibrary":true,"optimize":true,"engines":{"browsers":"chrome >= 83, edge >= 83, firefox >= 102, safari >= 15"},"source":"lib/dataconnection/StreamConnection/MsgPack.ts"}},"scripts":{"contributors":"git-authors-cli --print=false && prettier --write package.json && git add package.json package-lock.json && git commit -m \\"chore(contributors): update and sort contributors list\\"","check":"tsc --noEmit && tsc -p e2e/tsconfig.json --noEmit","watch":"parcel watch","build":"rm -rf dist && parcel build","prepublishOnly":"npm run build","test":"jest","test:watch":"jest --watch","coverage":"jest --coverage --collectCoverageFrom=\\"./lib/**\\"","format":"prettier --write .","format:check":"prettier --check .","semantic-release":"semantic-release","e2e":"wdio run e2e/wdio.local.conf.ts","e2e:bstack":"wdio run e2e/wdio.bstack.conf.ts"},"devDependencies":{"@parcel/config-default":"^2.9.3","@parcel/packager-ts":"^2.9.3","@parcel/transformer-typescript-tsc":"^2.9.3","@parcel/transformer-typescript-types":"^2.9.3","@semantic-release/changelog":"^6.0.1","@semantic-release/git":"^10.0.1","@swc/core":"^1.3.27","@swc/jest":"^0.2.24","@types/jasmine":"^4.3.4","@wdio/browserstack-service":"^8.11.2","@wdio/cli":"^8.11.2","@wdio/globals":"^8.11.2","@wdio/jasmine-framework":"^8.11.2","@wdio/local-runner":"^8.11.2","@wdio/spec-reporter":"^8.11.2","@wdio/types":"^8.10.4","http-server":"^14.1.1","jest":"^29.3.1","jest-environment-jsdom":"^29.3.1","mock-socket":"^9.0.0","parcel":"^2.9.3","prettier":"^3.0.0","semantic-release":"^21.0.0","ts-node":"^10.9.1","typescript":"^5.0.0","wdio-geckodriver-service":"^5.0.1"},"dependencies":{"@msgpack/msgpack":"^2.8.0","cbor-x":"1.5.4","eventemitter3":"^4.0.7","peerjs-js-binarypack":"^2.1.0","webrtc-adapter":"^8.0.0"},"alias":{"process":false,"buffer":false}}'
);
class eJ extends ej.EventEmitter {
start(e, t) {
this._id = e;
let n = `${this._baseUrl}&id=${e}&token=${t}`;
!this._socket &&
this._disconnected &&
((this._socket = new WebSocket(n + "&version=" + e$.version)),
(this._disconnected = !1),
(this._socket.onmessage = (e) => {
let t;
try {
(t = JSON.parse(e.data)), eO.log("Server message received:", t);
} catch (t) {
eO.log("Invalid server message", e.data);
return;
}
this.emit(M.Message, t);
}),
(this._socket.onclose = (e) => {
this._disconnected ||
(eO.log("Socket closed.", e),
this._cleanup(),
(this._disconnected = !0),
this.emit(M.Disconnected));
}),
(this._socket.onopen = () => {
this._disconnected ||
(this._sendQueuedMessages(),
eO.log("Socket open"),
this._scheduleHeartbeat());
}));
}
_scheduleHeartbeat() {
this._wsPingTimer = setTimeout(() => {
this._sendHeartbeat();
}, this.pingInterval);
}
_sendHeartbeat() {
if (!this._wsOpen()) {
eO.log("Cannot send heartbeat, because socket closed");
return;
}
let e = JSON.stringify({ type: O.Heartbeat });
this._socket.send(e), this._scheduleHeartbeat();
}
_wsOpen() {
return !!this._socket && 1 === this._socket.readyState;
}
_sendQueuedMessages() {
let e = [...this._messagesQueue];
for (let t of ((this._messagesQueue = []), e)) this.send(t);
}
send(e) {
if (this._disconnected) return;
if (!this._id) {
this._messagesQueue.push(e);
return;
}
if (!e.type) {
this.emit(M.Error, "Invalid message");
return;
}
if (!this._wsOpen()) return;
let t = JSON.stringify(e);
this._socket.send(t);
}
close() {
this._disconnected || (this._cleanup(), (this._disconnected = !0));
}
_cleanup() {
this._socket &&
((this._socket.onopen =
this._socket.onmessage =
this._socket.onclose =
null),
this._socket.close(),
(this._socket = void 0)),
clearTimeout(this._wsPingTimer);
}
constructor(e, t, n, r, i, o = 5e3) {
super(),
(this.pingInterval = o),
(this._disconnected = !0),
(this._messagesQueue = []),
(this._baseUrl =
(e ? "wss://" : "ws://") + t + ":" + n + r + "peerjs?key=" + i);
}
}
class eV {
startConnection(e) {
let t = this._startPeerConnection();
if (
((this.connection.peerConnection = t),
this.connection.type === P.Media &&
e._stream &&
this._addTracksToConnection(e._stream, t),
e.originator)
) {
let n = this.connection,
r = { ordered: !!e.reliable },
i = t.createDataChannel(n.label, r);
n._initializeDataChannel(i), this._makeOffer();
} else this.handleSDP("OFFER", e.sdp);
}
_startPeerConnection() {
eO.log("Creating RTCPeerConnection.");
let e = new RTCPeerConnection(this.connection.provider.options.config);
return this._setupListeners(e), e;
}
_setupListeners(e) {
let t = this.connection.peer,
n = this.connection.connectionId,
r = this.connection.type,
i = this.connection.provider;
eO.log("Listening for ICE candidates."),
(e.onicecandidate = (e) => {
e.candidate &&
e.candidate.candidate &&
(eO.log(`Received ICE candidates for ${t}:`, e.candidate),
i.socket.send({
type: O.Candidate,
payload: { candidate: e.candidate, type: r, connectionId: n },
dst: t,
}));
}),
(e.oniceconnectionstatechange = () => {
switch (e.iceConnectionState) {
case "failed":
eO.log(
"iceConnectionState is failed, closing connections to " + t
),
this.connection.emitError(
D.NegotiationFailed,
"Negotiation of connection to " + t + " failed."
),
this.connection.close();
break;
case "closed":
eO.log(
"iceConnectionState is closed, closing connections to " + t
),
this.connection.emitError(
D.ConnectionClosed,
"Connection to " + t + " closed."
),
this.connection.close();
break;
case "disconnected":
eO.log(
"iceConnectionState changed to disconnected on the connection with " +
t
);
break;
case "completed":
e.onicecandidate = () => {};
}
this.connection.emit("iceStateChanged", e.iceConnectionState);
}),
eO.log("Listening for data channel"),
(e.ondatachannel = (e) => {
eO.log("Received data channel");
let r = e.channel;
i.getConnection(t, n)._initializeDataChannel(r);
}),
eO.log("Listening for remote stream"),
(e.ontrack = (e) => {
eO.log("Received remote stream");
let r = e.streams[0],
o = i.getConnection(t, n);
o.type === P.Media && this._addStreamToMediaConnection(r, o);
});
}
cleanup() {
eO.log("Cleaning up PeerConnection to " + this.connection.peer);
let e = this.connection.peerConnection;
if (!e) return;
(this.connection.peerConnection = null),
(e.onicecandidate =
e.oniceconnectionstatechange =
e.ondatachannel =
e.ontrack =
() => {});
let t = "closed" !== e.signalingState,
n = !1,
r = this.connection.dataChannel;
r && (n = !!r.readyState && "closed" !== r.readyState),
(t || n) && e.close();
}
async _makeOffer() {
let e = this.connection.peerConnection,
t = this.connection.provider;
try {
let n = await e.createOffer(this.connection.options.constraints);
eO.log("Created offer."),
this.connection.options.sdpTransform &&
"function" == typeof this.connection.options.sdpTransform &&
(n.sdp = this.connection.options.sdpTransform(n.sdp) || n.sdp);
try {
await e.setLocalDescription(n),
eO.log("Set localDescription:", n, `for:${this.connection.peer}`);
let r = {
sdp: n,
type: this.connection.type,
connectionId: this.connection.connectionId,
metadata: this.connection.metadata,
};
if (this.connection.type === P.Data) {
let e = this.connection;
r = {
...r,
label: e.label,
reliable: e.reliable,
serialization: e.serialization,
};
}
t.socket.send({
type: O.Offer,
payload: r,
dst: this.connection.peer,
});
} catch (e) {
"OperationError: Failed to set local offer sdp: Called in wrong state: kHaveRemoteOffer" !=
e &&
(t.emitError(E.WebRTC, e),
eO.log("Failed to setLocalDescription, ", e));
}
} catch (e) {
t.emitError(E.WebRTC, e), eO.log("Failed to createOffer, ", e);
}
}
async _makeAnswer() {
let e = this.connection.peerConnection,
t = this.connection.provider;
try {
let n = await e.createAnswer();
eO.log("Created answer."),
this.connection.options.sdpTransform &&
"function" == typeof this.connection.options.sdpTransform &&
(n.sdp = this.connection.options.sdpTransform(n.sdp) || n.sdp);
try {
await e.setLocalDescription(n),
eO.log("Set localDescription:", n, `for:${this.connection.peer}`),
t.socket.send({
type: O.Answer,
payload: {
sdp: n,
type: this.connection.type,
connectionId: this.connection.connectionId,
},
dst: this.connection.peer,
});
} catch (e) {
t.emitError(E.WebRTC, e),
eO.log("Failed to setLocalDescription, ", e);
}
} catch (e) {
t.emitError(E.WebRTC, e), eO.log("Failed to create answer, ", e);
}
}
async handleSDP(e, t) {
t = new RTCSessionDescription(t);
let n = this.connection.peerConnection,
r = this.connection.provider;
eO.log("Setting remote description", t);
try {
await n.setRemoteDescription(t),
eO.log(`Set remoteDescription:${e} for:${this.connection.peer}`),
"OFFER" === e && (await this._makeAnswer());
} catch (e) {
r.emitError(E.WebRTC, e), eO.log("Failed to setRemoteDescription, ", e);
}
}
async handleCandidate(e) {
eO.log("handleCandidate:", e);
try {
await this.connection.peerConnection.addIceCandidate(e),
eO.log(`Added ICE candidate for:${this.connection.peer}`);
} catch (e) {
this.connection.provider.emitError(E.WebRTC, e),
eO.log("Failed to handleCandidate, ", e);
}
}
_addTracksToConnection(e, t) {
if (
(eO.log(`add tracks from stream ${e.id} to peer connection`),
!t.addTrack)
)
return eO.error(
"Your browser does't support RTCPeerConnection#addTrack. Ignored."
);
e.getTracks().forEach((n) => {
t.addTrack(n, e);
});
}
_addStreamToMediaConnection(e, t) {
eO.log(`add stream ${e.id} to media connection ${t.connectionId}`),
t.addStream(e);
}
constructor(e) {
this.connection = e;
}
}
class eG extends ej.EventEmitter {
emitError(e, t) {
eO.error("Error:", t), this.emit("error", new eW(`${e}`, t));
}
}
class eW extends Error {
constructor(e, t) {
"string" == typeof t ? super(t) : (super(), Object.assign(this, t)),
(this.type = e);
}
}
class eH extends eG {
get open() {
return this._open;
}
constructor(e, t, n) {
super(),
(this.peer = e),
(this.provider = t),
(this.options = n),
(this._open = !1),
(this.metadata = n.metadata);
}
}
class eY extends eH {
get type() {
return P.Media;
}
get localStream() {
return this._localStream;
}
get remoteStream() {
return this._remoteStream;
}
_initializeDataChannel(e) {
(this.dataChannel = e),
(this.dataChannel.onopen = () => {
eO.log(`DC#${this.connectionId} dc connection success`),
this.emit("willCloseOnRemote");
}),
(this.dataChannel.onclose = () => {
eO.log(`DC#${this.connectionId} dc closed for:`, this.peer),
this.close();
});
}
addStream(e) {
eO.log("Receiving stream", e),
(this._remoteStream = e),
super.emit("stream", e);
}
handleMessage(e) {
let t = e.type,
n = e.payload;
switch (e.type) {
case O.Answer:
this._negotiator.handleSDP(t, n.sdp), (this._open = !0);
break;
case O.Candidate:
this._negotiator.handleCandidate(n.candidate);
break;
default:
eO.warn(`Unrecognized message type:${t} from peer:${this.peer}`);
}
}
answer(e, t = {}) {
if (this._localStream) {
eO.warn(
"Local stream already exists on this MediaConnection. Are you answering a call twice?"
);
return;
}
for (let n of ((this._localStream = e),
t && t.sdpTransform && (this.options.sdpTransform = t.sdpTransform),
this._negotiator.startConnection({
...this.options._payload,
_stream: e,
}),
this.provider._getMessages(this.connectionId)))
this.handleMessage(n);
this._open = !0;
}
close() {
this._negotiator &&
(this._negotiator.cleanup(), (this._negotiator = null)),
(this._localStream = null),
(this._remoteStream = null),
this.provider &&
(this.provider._removeConnection(this), (this.provider = null)),
this.options && this.options._stream && (this.options._stream = null),
this.open && ((this._open = !1), super.emit("close"));
}
constructor(e, t, n) {
super(e, t, n),
(this._localStream = this.options._stream),
(this.connectionId =
this.options.connectionId || eY.ID_PREFIX + eM.randomToken()),
(this._negotiator = new eV(this)),
this._localStream &&
this._negotiator.startConnection({
_stream: this._localStream,
originator: !0,
});
}
}
eY.ID_PREFIX = "mc_";
class eK {
_buildRequest(e) {
let t = this._options.secure ? "https" : "http",
{ host: n, port: r, path: i, key: o } = this._options,
s = new URL(`${t}://${n}:${r}${i}${o}/${e}`);
return (
s.searchParams.set("ts", `${Date.now()}${Math.random()}`),
s.searchParams.set("version", e$.version),
fetch(s.href, { referrerPolicy: this._options.referrerPolicy })
);
}
async retrieveId() {
try {
let e = await this._buildRequest("id");
if (200 !== e.status) throw Error(`Error. Status:${e.status}`);
return e.text();
} catch (t) {
eO.error("Error retrieving ID", t);
let e = "";
throw (
("/" === this._options.path &&
this._options.host !== eM.CLOUD_HOST &&
(e =
" If you passed in a `path` to your self-hosted PeerServer, you'll also need to pass in that same path when creating a new Peer."),
Error("Could not get an ID from the server." + e))
);
}
}
async listAllPeers() {
try {
let e = await this._buildRequest("peers");
if (200 !== e.status) {
if (401 === e.status) {
let e = "";
throw (
((e =
this._options.host === eM.CLOUD_HOST
? "It looks like you're using the cloud server. You can email team@peerjs.com to enable peer listing for your API key."
: "You need to enable `allow_discovery` on your self-hosted PeerServer to use this feature."),
Error(
"It doesn't look like you have permission to list peers IDs. " +
e
))
);
}
throw Error(`Error. Status:${e.status}`);
}
return e.json();
} catch (e) {
throw (
(eO.error("Error retrieving list peers", e),
Error("Could not get list peers from the server." + e))
);
}
}
constructor(e) {
this._options = e;
}
}
class eX extends eH {
get type() {
return P.Data;
}
_initializeDataChannel(e) {
(this.dataChannel = e),
(this.dataChannel.onopen = () => {
eO.log(`DC#${this.connectionId} dc connection success`),
(this._open = !0),
this.emit("open");
}),
(this.dataChannel.onmessage = (e) => {
eO.log(`DC#${this.connectionId} dc onmessage:`, e.data);
}),
(this.dataChannel.onclose = () => {
eO.log(`DC#${this.connectionId} dc closed for:`, this.peer),
this.close();
});
}
close(e) {
if (e?.flush) {
this.send({ __peerData: { type: "close" } });
return;
}
this._negotiator &&
(this._negotiator.cleanup(), (this._negotiator = null)),
this.provider &&
(this.provider._removeConnection(this), (this.provider = null)),
this.dataChannel &&
((this.dataChannel.onopen = null),
(this.dataChannel.onmessage = null),
(this.dataChannel.onclose = null),
(this.dataChannel = null)),
this.open && ((this._open = !1), super.emit("close"));
}
send(e, t = !1) {
if (!this.open) {
this.emitError(
x.NotOpenYet,
"Connection is not open. You should listen for the `open` event before sending messages."
);
return;
}
return this._send(e, t);
}
async handleMessage(e) {
let t = e.payload;
switch (e.type) {
case O.Answer:
await this._negotiator.handleSDP(e.type, t.sdp);
break;
case O.Candidate:
await this._negotiator.handleCandidate(t.candidate);
break;
default:
eO.warn(
"Unrecognized message type:",
e.type,
"from peer:",
this.peer
);
}
}
constructor(e, t, n) {
super(e, t, n),
(this.connectionId = this.options.connectionId || eX.ID_PREFIX + ex()),
(this.label = this.options.label || this.connectionId),
(this.reliable = !!this.options.reliable),
(this._negotiator = new eV(this)),
this._negotiator.startConnection(
this.options._payload || { originator: !0, reliable: this.reliable }
);
}
}
(eX.ID_PREFIX = "dc_"), (eX.MAX_BUFFERED_AMOUNT = 8388608);
class eq extends eX {
get bufferSize() {
return this._bufferSize;
}
_initializeDataChannel(e) {
super._initializeDataChannel(e),
(this.dataChannel.binaryType = "arraybuffer"),
this.dataChannel.addEventListener("message", (e) =>
this._handleDataMessage(e)
);
}
_bufferedSend(e) {
(this._buffering || !this._trySend(e)) &&
(this._buffer.push(e), (this._bufferSize = this._buffer.length));
}
_trySend(e) {
if (!this.open) return !1;
if (this.dataChannel.bufferedAmount > eX.MAX_BUFFERED_AMOUNT)
return (
(this._buffering = !0),
setTimeout(() => {
(this._buffering = !1), this._tryBuffer();
}, 50),
!1
);
try {
this.dataChannel.send(e);
} catch (e) {
return (
eO.error(`DC#:${this.connectionId} Error when sending:`, e),
(this._buffering = !0),
this.close(),
!1
);
}
return !0;
}
_tryBuffer() {
if (!this.open || 0 === this._buffer.length) return;
let e = this._buffer[0];
this._trySend(e) &&
(this._buffer.shift(),
(this._bufferSize = this._buffer.length),
this._tryBuffer());
}
close(e) {
if (e?.flush) {
this.send({ __peerData: { type: "close" } });
return;
}
(this._buffer = []), (this._bufferSize = 0), super.close();
}
constructor(...e) {
super(...e),
(this._buffer = []),
(this._bufferSize = 0),
(this._buffering = !1);
}
}
class eQ extends eq {
close(e) {
super.close(e), (this._chunkedData = {});
}
_handleDataMessage({ data: e }) {
let t = i(e),
n = t.__peerData;
if (n) {
if ("close" === n.type) {
this.close();
return;
}
this._handleChunk(t);
return;
}
this.emit("data", t);
}
_handleChunk(e) {
let t = e.__peerData,
n = this._chunkedData[t] || { data: [], count: 0, total: e.total };
if (
((n.data[e.n] = new Uint8Array(e.data)),
n.count++,
(this._chunkedData[t] = n),
n.total === n.count)
) {
delete this._chunkedData[t];
let e = (function (e) {
let t = 0;
for (let n of e) t += n.byteLength;
let n = new Uint8Array(t),
r = 0;
for (let t of e) n.set(t, r), (r += t.byteLength);
return n;
})(n.data);
this._handleDataMessage({ data: e });
}
}
_send(e, t) {
let n = o(e);
if (n instanceof Promise) return this._send_blob(n);
if (!t && n.byteLength > this.chunker.chunkedMTU) {
this._sendChunks(n);
return;
}
this._bufferedSend(n);
}
async _send_blob(e) {
let t = await e;
if (t.byteLength > this.chunker.chunkedMTU) {
this._sendChunks(t);
return;
}
this._bufferedSend(t);
}
_sendChunks(e) {
let t = this.chunker.chunk(e);
for (let e of (eO.log(
`DC#${this.connectionId} Try to send ${t.length} chunks...`
),
t))
this.send(e, !0);
}
constructor(e, t, r) {
super(e, t, r),
(this.chunker = new n()),
(this.serialization = I.Binary),
(this._chunkedData = {});
}
}
class eZ extends eq {
_handleDataMessage({ data: e }) {
super.emit("data", e);
}
_send(e, t) {
this._bufferedSend(e);
}
constructor(...e) {
super(...e), (this.serialization = I.None);
}
}
class e0 extends eq {
_handleDataMessage({ data: e }) {
let t = this.parse(this.decoder.decode(e)),
n = t.__peerData;
if (n && "close" === n.type) {
this.close();
return;
}
this.emit("data", t);
}
_send(e, t) {
let n = this.encoder.encode(this.stringify(e));
if (n.byteLength >= eM.chunkedMTU) {
this.emitError(x.MessageToBig, "Message too big for JSON channel");
return;
}
this._bufferedSend(n);
}
constructor(...e) {
super(...e),
(this.serialization = I.JSON),
(this.encoder = new TextEncoder()),
(this.decoder = new TextDecoder()),
(this.stringify = JSON.stringify),
(this.parse = JSON.parse);
}
}
class e1 extends eG {
get id() {
return this._id;
}
get options() {
return this._options;
}
get open() {
return this._open;
}
get socket() {
return this._socket;
}
get connections() {
let e = Object.create(null);
for (let [t, n] of this._connections) e[t] = n;
return e;
}
get destroyed() {
return this._destroyed;
}
get disconnected() {
return this._disconnected;
}
_createServerConnection() {
let e = new eJ(
this._options.secure,
this._options.host,
this._options.port,
this._options.path,
this._options.key,
this._options.pingInterval
);
return (
e.on(M.Message, (e) => {
this._handleMessage(e);
}),
e.on(M.Error, (e) => {
this._abort(E.SocketError, e);
}),
e.on(M.Disconnected, () => {
this.disconnected ||
(this.emitError(E.Network, "Lost connection to server."),
this.disconnect());
}),
e.on(M.Close, () => {
this.disconnected ||
this._abort(E.SocketClosed, "Underlying socket is already closed.");
}),
e
);
}
_initialize(e) {
(this._id = e), this.socket.start(e, this._options.token);
}
_handleMessage(e) {
let t = e.type,
n = e.payload,
r = e.src;
switch (t) {
case O.Open:
(this._lastServerId = this.id),
(this._open = !0),
this.emit("open", this.id);
break;
case O.Error:
this._abort(E.ServerError, n.msg);
break;
case O.IdTaken:
this._abort(E.UnavailableID, `ID "${this.id}" is taken`);
break;
case O.InvalidKey:
this._abort(
E.InvalidKey,
`API KEY "${this._options.key}" is invalid`
);
break;
case O.Leave:
eO.log(`Received leave message from ${r}`),
this._cleanupPeer(r),
this._connections.delete(r);
break;
case O.Expire:
this.emitError(E.PeerUnavailable, `Could not connect to peer ${r}`);
break;
case O.Offer: {
let e = n.connectionId,
t = this.getConnection(r, e);
if (
(t &&
(t.close(),
eO.warn(`Offer received for existing Connection ID:${e}`)),
n.type === P.Media)
) {
let i = new eY(r, this, {
connectionId: e,
_payload: n,
metadata: n.metadata,
});
(t = i), this._addConnection(r, t), this.emit("call", i);
} else if (n.type === P.Data) {
let i = new this._serializers[n.serialization](r, this, {
connectionId: e,
_payload: n,
metadata: n.metadata,
label: n.label,
serialization: n.serialization,
reliable: n.reliable,
});
(t = i), this._addConnection(r, t), this.emit("connection", i);
} else {
eO.warn(`Received malformed connection type:${n.type}`);
return;
}
for (let n of this._getMessages(e)) t.handleMessage(n);
break;
}
default: {
if (!n) {
eO.warn(`You received a malformed message from ${r} of type ${t}`);
return;
}
let i = n.connectionId,
o = this.getConnection(r, i);
o && o.peerConnection
? o.handleMessage(e)
: i
? this._storeMessage(i, e)
: eO.warn("You received an unrecognized message:", e);
}
}
}
_storeMessage(e, t) {
this._lostMessages.has(e) || this._lostMessages.set(e, []),
this._lostMessages.get(e).push(t);
}
_getMessages(e) {
let t = this._lostMessages.get(e);
return t ? (this._lostMessages.delete(e), t) : [];
}
connect(e, t = {}) {
if (((t = { serialization: "default", ...t }), this.disconnected)) {
eO.warn(
"You cannot connect to a new Peer because you called .disconnect() on this Peer and ended your connection with the server. You can create a new Peer to reconnect, or call reconnect on this peer if you believe its ID to still be available."
),
this.emitError(
E.Disconnected,
"Cannot connect to new Peer after disconnecting from server."
);
return;
}
let n = new this._serializers[t.serialization](e, this, t);
return this._addConnection(e, n), n;
}
call(e, t, n = {}) {
if (this.disconnected) {
eO.warn(
"You cannot connect to a new Peer because you called .disconnect() on this Peer and ended your connection with the server. You can create a new Peer to reconnect."
),
this.emitError(
E.Disconnected,
"Cannot connect to new Peer after disconnecting from server."
);
return;
}
if (!t) {
eO.error(
"To call a peer, you must provide a stream from your browser's `getUserMedia`."
);
return;
}
let r = new eY(e, this, { ...n, _stream: t });
return this._addConnection(e, r), r;
}
_addConnection(e, t) {
eO.log(`add connection ${t.type}:${t.connectionId} to peerId:${e}`),
this._connections.has(e) || this._connections.set(e, []),
this._connections.get(e).push(t);
}
_removeConnection(e) {
let t = this._connections.get(e.peer);
if (t) {
let n = t.indexOf(e);
-1 !== n && t.splice(n, 1);
}
this._lostMessages.delete(e.connectionId);
}
getConnection(e, t) {
let n = this._connections.get(e);
if (!n) return null;
for (let e of n) if (e.connectionId === t) return e;
return null;
}
_delayedAbort(e, t) {
setTimeout(() => {
this._abort(e, t);
}, 0);
}
_abort(e, t) {
eO.error("Aborting!"),
this.emitError(e, t),
this._lastServerId ? this.disconnect() : this.destroy();
}
destroy() {
this.destroyed ||
(eO.log(`Destroy peer with ID:${this.id}`),
this.disconnect(),
this._cleanup(),
(this._destroyed = !0),
this.emit("close"));
}
_cleanup() {
for (let e of this._connections.keys())
this._cleanupPeer(e), this._connections.delete(e);
this.socket.removeAllListeners();
}
_cleanupPeer(e) {
let t = this._connections.get(e);
if (t) for (let e of t) e.close();
}
disconnect() {
if (this.disconnected) return;
let e = this.id;
eO.log(`Disconnect peer with ID:${e}`),
(this._disconnected = !0),
(this._open = !1),
this.socket.close(),
(this._lastServerId = e),
(this._id = null),
this.emit("disconnected", e);
}
reconnect() {
if (this.disconnected && !this.destroyed)
eO.log(
`Attempting reconnection to server with ID ${this._lastServerId}`
),
(this._disconnected = !1),
this._initialize(this._lastServerId);
else if (this.destroyed)
throw Error(
"This peer cannot reconnect to the server. It has already been destroyed."
);
else if (this.disconnected || this.open)
throw Error(
`Peer ${this.id} cannot reconnect because it is not disconnected from the server!`
);
else
eO.error(
"In a hurry? We're still trying to make the initial connection!"
);
}
listAllPeers(e = (e) => {}) {
this._api
.listAllPeers()
.then((t) => e(t))
.catch((e) => this._abort(E.ServerError, e));
}
constructor(e, t) {
let n;
if (
(super(),
(this._serializers = {
raw: eZ,
json: e0,
binary: eQ,
"binary-utf8": eQ,
default: eQ,
}),
(this._id = null),
(this._lastServerId = null),
(this._destroyed = !1),
(this._disconnected = !1),
(this._open = !1),
(this._connections = new Map()),
(this._lostMessages = new Map()),
e && e.constructor == Object ? (t = e) : e && (n = e.toString()),
(t = {
debug: 0,
host: eM.CLOUD_HOST,
port: eM.CLOUD_PORT,
path: "/",
key: e1.DEFAULT_KEY,
token: eM.randomToken(),
config: eM.defaultConfig,
referrerPolicy: "strict-origin-when-cross-origin",
serializers: {},
...t,
}),
(this._options = t),
(this._serializers = {
...this._serializers,
...this.options.serializers,
}),
"/" === this._options.host &&
(this._options.host = window.location.hostname),
this._options.path &&
("/" !== this._options.path[0] &&
(this._options.path = "/" + this._options.path),
"/" !== this._options.path[this._options.path.length - 1] &&
(this._options.path += "/")),
void 0 === this._options.secure && this._options.host !== eM.CLOUD_HOST
? (this._options.secure = eM.isSecure())
: this._options.host == eM.CLOUD_HOST && (this._options.secure = !0),
this._options.logFunction &&
eO.setLogFunction(this._options.logFunction),
(eO.logLevel = this._options.debug || 0),
(this._api = new eK(t)),
(this._socket = this._createServerConnection()),
!eM.supports.audioVideo && !eM.supports.data)
) {
this._delayedAbort(
E.BrowserIncompatible,
"The current browser does not support WebRTC"
);
return;
}
if (n && !eM.validateId(n)) {
this._delayedAbort(E.InvalidID, `ID "${n}" is invalid`);
return;
}
n
? this._initialize(n)
: this._api
.retrieveId()
.then((e) => this._initialize(e))
.catch((e) => this._abort(E.ServerError, e));
}
}
(e1.DEFAULT_KEY = "peerjs"),
(window.peerjs = { Peer: e1, util: eM }),
(window.Peer = e1);
})();
!(function (u, D) {
"object" == typeof exports && "undefined" != typeof module
? (module.exports = D())
: "function" == typeof define && define.amd
? define(D)
: (u.JSON5 = D());
})(this, function () {
"use strict";
function u(u, D) {
return u((D = { exports: {} }), D.exports), D.exports;
}
var D = u(function (u) {
var D = (u.exports =
"undefined" != typeof window && window.Math == Math
? window
: "undefined" != typeof self && self.Math == Math
? self
: Function("return this")());
"number" == typeof __g && (__g = D);
}),
e = u(function (u) {
var D = (u.exports = { version: "2.6.5" });
"number" == typeof __e && (__e = D);
}),
r =
(e.version,
function (u) {
return "object" == typeof u ? null !== u : "function" == typeof u;
}),
t = function (u) {
if (!r(u)) throw TypeError(u + " is not an object!");
return u;
},
n = function (u) {
try {
return !!u();
} catch (u) {
return !0;
}
},
F = !n(function () {
return (
7 !=
Object.defineProperty({}, "a", {
get: function () {
return 7;
},
}).a
);
}),
C = D.document,
A = r(C) && r(C.createElement),
i =
!F &&
!n(function () {
return (
7 !=
Object.defineProperty(
((u = "div"), A ? C.createElement(u) : {}),
"a",
{
get: function () {
return 7;
},
}
).a
);
var u;
}),
E = Object.defineProperty,
o = {
f: F
? Object.defineProperty
: function (u, D, e) {
if (
(t(u),
(D = (function (u, D) {
if (!r(u)) return u;
var e, t;
if (
D &&
"function" == typeof (e = u.toString) &&
!r((t = e.call(u)))
)
return t;
if ("function" == typeof (e = u.valueOf) && !r((t = e.call(u))))
return t;
if (
!D &&
"function" == typeof (e = u.toString) &&
!r((t = e.call(u)))
)
return t;
throw TypeError("Can't convert object to primitive value");
})(D, !0)),
t(e),
i)
)
try {
return E(u, D, e);
} catch (u) {}
if ("get" in e || "set" in e)
throw TypeError("Accessors not supported!");
return "value" in e && (u[D] = e.value), u;
},
},
a = F
? function (u, D, e) {
return o.f(
u,
D,
(function (u, D) {
return {
enumerable: !(1 & u),
configurable: !(2 & u),
writable: !(4 & u),
value: D,
};
})(1, e)
);
}
: function (u, D, e) {
return (u[D] = e), u;
},
c = {}.hasOwnProperty,
B = function (u, D) {
return c.call(u, D);
},
s = 0,
f = Math.random(),
l = u(function (u) {
var r = D["__core-js_shared__"] || (D["__core-js_shared__"] = {});
(u.exports = function (u, D) {
return r[u] || (r[u] = void 0 !== D ? D : {});
})("versions", []).push({
version: e.version,
mode: "global",
copyright: "© 2019 Denis Pushkarev (zloirock.ru)",
});
})("native-function-to-string", Function.toString),
d = u(function (u) {
var r,
t = "Symbol(".concat(
void 0 === (r = "src") ? "" : r,
")_",
(++s + f).toString(36)
),
n = ("" + l).split("toString");
(e.inspectSource = function (u) {
return l.call(u);
}),
(u.exports = function (u, e, r, F) {
var C = "function" == typeof r;
C && (B(r, "name") || a(r, "name", e)),
u[e] !== r &&
(C && (B(r, t) || a(r, t, u[e] ? "" + u[e] : n.join(String(e)))),
u === D
? (u[e] = r)
: F
? u[e]
? (u[e] = r)
: a(u, e, r)
: (delete u[e], a(u, e, r)));
})(Function.prototype, "toString", function () {
return ("function" == typeof this && this[t]) || l.call(this);
});
}),
v = function (u, D, e) {
if (
((function (u) {
if ("function" != typeof u)
throw TypeError(u + " is not a function!");
})(u),
void 0 === D)
)
return u;
switch (e) {
case 1:
return function (e) {
return u.call(D, e);
};
case 2:
return function (e, r) {
return u.call(D, e, r);
};
case 3:
return function (e, r, t) {
return u.call(D, e, r, t);
};
}
return function () {
return u.apply(D, arguments);
};
},
p = function (u, r, t) {
var n,
F,
C,
A,
i = u & p.F,
E = u & p.G,
o = u & p.S,
c = u & p.P,
B = u & p.B,
s = E ? D : o ? D[r] || (D[r] = {}) : (D[r] || {}).prototype,
f = E ? e : e[r] || (e[r] = {}),
l = f.prototype || (f.prototype = {});
for (n in (E && (t = r), t))
(C = ((F = !i && s && void 0 !== s[n]) ? s : t)[n]),
(A =
B && F
? v(C, D)
: c && "function" == typeof C
? v(Function.call, C)
: C),
s && d(s, n, C, u & p.U),
f[n] != C && a(f, n, A),
c && l[n] != C && (l[n] = C);
};
(D.core = e),
(p.F = 1),
(p.G = 2),
(p.S = 4),
(p.P = 8),
(p.B = 16),
(p.W = 32),
(p.U = 64),
(p.R = 128);
var h,
m = p,
g = Math.ceil,
y = Math.floor,
w = function (u) {
return isNaN((u = +u)) ? 0 : (u > 0 ? y : g)(u);
},
b =
((h = !1),
function (u, D) {
var e,
r,
t = String(
(function (u) {
if (null == u) throw TypeError("Can't call method on " + u);
return u;
})(u)
),
n = w(D),
F = t.length;
return n < 0 || n >= F
? h
? ""
: void 0
: (e = t.charCodeAt(n)) < 55296 ||
e > 56319 ||
n + 1 === F ||
(r = t.charCodeAt(n + 1)) < 56320 ||
r > 57343
? h
? t.charAt(n)
: e
: h
? t.slice(n, n + 2)
: r - 56320 + ((e - 55296) << 10) + 65536;
});
m(m.P, "String", {
codePointAt: function (u) {
return b(this, u);
},
});
e.String.codePointAt;
var S = Math.max,
x = Math.min,
N = String.fromCharCode,
P = String.fromCodePoint;
m(m.S + m.F * (!!P && 1 != P.length), "String", {
fromCodePoint: function (u) {
for (
var D, e, r, t = arguments, n = [], F = arguments.length, C = 0;
F > C;
) {
if (
((D = +t[C++]),
(r = 1114111),
((e = w((e = D))) < 0 ? S(e + r, 0) : x(e, r)) !== D)
)
throw RangeError(D + " is not a valid code point");
n.push(
D < 65536 ? N(D) : N(55296 + ((D -= 65536) >> 10), (D % 1024) + 56320)
);
}
return n.join("");
},
});
e.String.fromCodePoint;
var _,
O,
j,
I,
V,
J,
M,
k,
L,
T,
z,
H,
$,
R,
G = {
Space_Separator: /[\u1680\u2000-\u200A\u202F\u205F\u3000]/,
ID_Start:
/[\xAA\xB5\xBA\xC0-\xD6\xD8-\xF6\xF8-\u02C1\u02C6-\u02D1\u02E0-\u02E4\u02EC\u02EE\u0370-\u0374\u0376\u0377\u037A-\u037D\u037F\u0386\u0388-\u038A\u038C\u038E-\u03A1\u03A3-\u03F5\u03F7-\u0481\u048A-\u052F\u0531-\u0556\u0559\u0561-\u0587\u05D0-\u05EA\u05F0-\u05F2\u0620-\u064A\u066E\u066F\u0671-\u06D3\u06D5\u06E5\u06E6\u06EE\u06EF\u06FA-\u06FC\u06FF\u0710\u0712-\u072F\u074D-\u07A5\u07B1\u07CA-\u07EA\u07F4\u07F5\u07FA\u0800-\u0815\u081A\u0824\u0828\u0840-\u0858\u0860-\u086A\u08A0-\u08B4\u08B6-\u08BD\u0904-\u0939\u093D\u0950\u0958-\u0961\u0971-\u0980\u0985-\u098C\u098F\u0990\u0993-\u09A8\u09AA-\u09B0\u09B2\u09B6-\u09B9\u09BD\u09CE\u09DC\u09DD\u09DF-\u09E1\u09F0\u09F1\u09FC\u0A05-\u0A0A\u0A0F\u0A10\u0A13-\u0A28\u0A2A-\u0A30\u0A32\u0A33\u0A35\u0A36\u0A38\u0A39\u0A59-\u0A5C\u0A5E\u0A72-\u0A74\u0A85-\u0A8D\u0A8F-\u0A91\u0A93-\u0AA8\u0AAA-\u0AB0\u0AB2\u0AB3\u0AB5-\u0AB9\u0ABD\u0AD0\u0AE0\u0AE1\u0AF9\u0B05-\u0B0C\u0B0F\u0B10\u0B13-\u0B28\u0B2A-\u0B30\u0B32\u0B33\u0B35-\u0B39\u0B3D\u0B5C\u0B5D\u0B5F-\u0B61\u0B71\u0B83\u0B85-\u0B8A\u0B8E-\u0B90\u0B92-\u0B95\u0B99\u0B9A\u0B9C\u0B9E\u0B9F\u0BA3\u0BA4\u0BA8-\u0BAA\u0BAE-\u0BB9\u0BD0\u0C05-\u0C0C\u0C0E-\u0C10\u0C12-\u0C28\u0C2A-\u0C39\u0C3D\u0C58-\u0C5A\u0C60\u0C61\u0C80\u0C85-\u0C8C\u0C8E-\u0C90\u0C92-\u0CA8\u0CAA-\u0CB3\u0CB5-\u0CB9\u0CBD\u0CDE\u0CE0\u0CE1\u0CF1\u0CF2\u0D05-\u0D0C\u0D0E-\u0D10\u0D12-\u0D3A\u0D3D\u0D4E\u0D54-\u0D56\u0D5F-\u0D61\u0D7A-\u0D7F\u0D85-\u0D96\u0D9A-\u0DB1\u0DB3-\u0DBB\u0DBD\u0DC0-\u0DC6\u0E01-\u0E30\u0E32\u0E33\u0E40-\u0E46\u0E81\u0E82\u0E84\u0E87\u0E88\u0E8A\u0E8D\u0E94-\u0E97\u0E99-\u0E9F\u0EA1-\u0EA3\u0EA5\u0EA7\u0EAA\u0EAB\u0EAD-\u0EB0\u0EB2\u0EB3\u0EBD\u0EC0-\u0EC4\u0EC6\u0EDC-\u0EDF\u0F00\u0F40-\u0F47\u0F49-\u0F6C\u0F88-\u0F8C\u1000-\u102A\u103F\u1050-\u1055\u105A-\u105D\u1061\u1065\u1066\u106E-\u1070\u1075-\u1081\u108E\u10A0-\u10C5\u10C7\u10CD\u10D0-\u10FA\u10FC-\u1248\u124A-\u124D\u1250-\u1256\u1258\u125A-\u125D\u1260-\u1288\u128A-\u128D\u1290-\u12B0\u12B2-\u12B5\u12B8-\u12BE\u12C0\u12C2-\u12C5\u12C8-\u12D6\u12D8-\u1310\u1312-\u1315\u1318-\u135A\u1380-\u138F\u13A0-\u13F5\u13F8-\u13FD\u1401-\u166C\u166F-\u167F\u1681-\u169A\u16A0-\u16EA\u16EE-\u16F8\u1700-\u170C\u170E-\u1711\u1720-\u1731\u1740-\u1751\u1760-\u176C\u176E-\u1770\u1780-\u17B3\u17D7\u17DC\u1820-\u1877\u1880-\u1884\u1887-\u18A8\u18AA\u18B0-\u18F5\u1900-\u191E\u1950-\u196D\u1970-\u1974\u1980-\u19AB\u19B0-\u19C9\u1A00-\u1A16\u1A20-\u1A54\u1AA7\u1B05-\u1B33\u1B45-\u1B4B\u1B83-\u1BA0\u1BAE\u1BAF\u1BBA-\u1BE5\u1C00-\u1C23\u1C4D-\u1C4F\u1C5A-\u1C7D\u1C80-\u1C88\u1CE9-\u1CEC\u1CEE-\u1CF1\u1CF5\u1CF6\u1D00-\u1DBF\u1E00-\u1F15\u1F18-\u1F1D\u1F20-\u1F45\u1F48-\u1F4D\u1F50-\u1F57\u1F59\u1F5B\u1F5D\u1F5F-\u1F7D\u1F80-\u1FB4\u1FB6-\u1FBC\u1FBE\u1FC2-\u1FC4\u1FC6-\u1FCC\u1FD0-\u1FD3\u1FD6-\u1FDB\u1FE0-\u1FEC\u1FF2-\u1FF4\u1FF6-\u1FFC\u2071\u207F\u2090-\u209C\u2102\u2107\u210A-\u2113\u2115\u2119-\u211D\u2124\u2126\u2128\u212A-\u212D\u212F-\u2139\u213C-\u213F\u2145-\u2149\u214E\u2160-\u2188\u2C00-\u2C2E\u2C30-\u2C5E\u2C60-\u2CE4\u2CEB-\u2CEE\u2CF2\u2CF3\u2D00-\u2D25\u2D27\u2D2D\u2D30-\u2D67\u2D6F\u2D80-\u2D96\u2DA0-\u2DA6\u2DA8-\u2DAE\u2DB0-\u2DB6\u2DB8-\u2DBE\u2DC0-\u2DC6\u2DC8-\u2DCE\u2DD0-\u2DD6\u2DD8-\u2DDE\u2E2F\u3005-\u3007\u3021-\u3029\u3031-\u3035\u3038-\u303C\u3041-\u3096\u309D-\u309F\u30A1-\u30FA\u30FC-\u30FF\u3105-\u312E\u3131-\u318E\u31A0-\u31BA\u31F0-\u31FF\u3400-\u4DB5\u4E00-\u9FEA\uA000-\uA48C\uA4D0-\uA4FD\uA500-\uA60C\uA610-\uA61F\uA62A\uA62B\uA640-\uA66E\uA67F-\uA69D\uA6A0-\uA6EF\uA717-\uA71F\uA722-\uA788\uA78B-\uA7AE\uA7B0-\uA7B7\uA7F7-\uA801\uA803-\uA805\uA807-\uA80A\uA80C-\uA822\uA840-\uA873\uA882-\uA8B3\uA8F2-\uA8F7\uA8FB\uA8FD\uA90A-\uA925\uA930-\uA946\uA960-\uA97C\uA984-\uA9B2\uA9CF\uA9E0-\uA9E4\uA9E6-\uA9EF\uA9FA-\uA9FE\uAA00-\uAA28\uAA40-\uAA42\uAA44-\uAA4B\uAA60-\uAA76\uAA7A\uAA7E-\uAAAF\uAAB1\uAAB5\uAAB6\uAAB9-\uAABD\uAAC0\uAAC2\uAADB-\uAADD\uAAE0-\uAAEA\uAAF2-\uAAF4\uAB01-\uAB06\uAB09-\uAB0E\uAB11-\uAB16\uAB20-\uAB26\uAB28-\uAB2E\uAB30-\uAB5A\uAB5C-\uAB65\uAB70-\uABE2\uAC00-\uD7A3\uD7B0-\uD7C6\uD7CB-\uD7FB\uF900-\uFA6D\uFA70-\uFAD9\uFB00-\uFB06\uFB13-\uFB17\uFB1D\uFB1F-\uFB28\uFB2A-\uFB36\uFB38-\uFB3C\uFB3E\uFB40\uFB41\uFB43\uFB44\uFB46-\uFBB1\uFBD3-\uFD3D\uFD50-\uFD8F\uFD92-\uFDC7\uFDF0-\uFDFB\uFE70-\uFE74\uFE76-\uFEFC\uFF21-\uFF3A\uFF41-\uFF5A\uFF66-\uFFBE\uFFC2-\uFFC7\uFFCA-\uFFCF\uFFD2-\uFFD7\uFFDA-\uFFDC]|\uD800[\uDC00-\uDC0B\uDC0D-\uDC26\uDC28-\uDC3A\uDC3C\uDC3D\uDC3F-\uDC4D\uDC50-\uDC5D\uDC80-\uDCFA\uDD40-\uDD74\uDE80-\uDE9C\uDEA0-\uDED0\uDF00-\uDF1F\uDF2D-\uDF4A\uDF50-\uDF75\uDF80-\uDF9D\uDFA0-\uDFC3\uDFC8-\uDFCF\uDFD1-\uDFD5]|\uD801[\uDC00-\uDC9D\uDCB0-\uDCD3\uDCD8-\uDCFB\uDD00-\uDD27\uDD30-\uDD63\uDE00-\uDF36\uDF40-\uDF55\uDF60-\uDF67]|\uD802[\uDC00-\uDC05\uDC08\uDC0A-\uDC35\uDC37\uDC38\uDC3C\uDC3F-\uDC55\uDC60-\uDC76\uDC80-\uDC9E\uDCE0-\uDCF2\uDCF4\uDCF5\uDD00-\uDD15\uDD20-\uDD39\uDD80-\uDDB7\uDDBE\uDDBF\uDE00\uDE10-\uDE13\uDE15-\uDE17\uDE19-\uDE33\uDE60-\uDE7C\uDE80-\uDE9C\uDEC0-\uDEC7\uDEC9-\uDEE4\uDF00-\uDF35\uDF40-\uDF55\uDF60-\uDF72\uDF80-\uDF91]|\uD803[\uDC00-\uDC48\uDC80-\uDCB2\uDCC0-\uDCF2]|\uD804[\uDC03-\uDC37\uDC83-\uDCAF\uDCD0-\uDCE8\uDD03-\uDD26\uDD50-\uDD72\uDD76\uDD83-\uDDB2\uDDC1-\uDDC4\uDDDA\uDDDC\uDE00-\uDE11\uDE13-\uDE2B\uDE80-\uDE86\uDE88\uDE8A-\uDE8D\uDE8F-\uDE9D\uDE9F-\uDEA8\uDEB0-\uDEDE\uDF05-\uDF0C\uDF0F\uDF10\uDF13-\uDF28\uDF2A-\uDF30\uDF32\uDF33\uDF35-\uDF39\uDF3D\uDF50\uDF5D-\uDF61]|\uD805[\uDC00-\uDC34\uDC47-\uDC4A\uDC80-\uDCAF\uDCC4\uDCC5\uDCC7\uDD80-\uDDAE\uDDD8-\uDDDB\uDE00-\uDE2F\uDE44\uDE80-\uDEAA\uDF00-\uDF19]|\uD806[\uDCA0-\uDCDF\uDCFF\uDE00\uDE0B-\uDE32\uDE3A\uDE50\uDE5C-\uDE83\uDE86-\uDE89\uDEC0-\uDEF8]|\uD807[\uDC00-\uDC08\uDC0A-\uDC2E\uDC40\uDC72-\uDC8F\uDD00-\uDD06\uDD08\uDD09\uDD0B-\uDD30\uDD46]|\uD808[\uDC00-\uDF99]|\uD809[\uDC00-\uDC6E\uDC80-\uDD43]|[\uD80C\uD81C-\uD820\uD840-\uD868\uD86A-\uD86C\uD86F-\uD872\uD874-\uD879][\uDC00-\uDFFF]|\uD80D[\uDC00-\uDC2E]|\uD811[\uDC00-\uDE46]|\uD81A[\uDC00-\uDE38\uDE40-\uDE5E\uDED0-\uDEED\uDF00-\uDF2F\uDF40-\uDF43\uDF63-\uDF77\uDF7D-\uDF8F]|\uD81B[\uDF00-\uDF44\uDF50\uDF93-\uDF9F\uDFE0\uDFE1]|\uD821[\uDC00-\uDFEC]|\uD822[\uDC00-\uDEF2]|\uD82C[\uDC00-\uDD1E\uDD70-\uDEFB]|\uD82F[\uDC00-\uDC6A\uDC70-\uDC7C\uDC80-\uDC88\uDC90-\uDC99]|\uD835[\uDC00-\uDC54\uDC56-\uDC9C\uDC9E\uDC9F\uDCA2\uDCA5\uDCA6\uDCA9-\uDCAC\uDCAE-\uDCB9\uDCBB\uDCBD-\uDCC3\uDCC5-\uDD05\uDD07-\uDD0A\uDD0D-\uDD14\uDD16-\uDD1C\uDD1E-\uDD39\uDD3B-\uDD3E\uDD40-\uDD44\uDD46\uDD4A-\uDD50\uDD52-\uDEA5\uDEA8-\uDEC0\uDEC2-\uDEDA\uDEDC-\uDEFA\uDEFC-\uDF14\uDF16-\uDF34\uDF36-\uDF4E\uDF50-\uDF6E\uDF70-\uDF88\uDF8A-\uDFA8\uDFAA-\uDFC2\uDFC4-\uDFCB]|\uD83A[\uDC00-\uDCC4\uDD00-\uDD43]|\uD83B[\uDE00-\uDE03\uDE05-\uDE1F\uDE21\uDE22\uDE24\uDE27\uDE29-\uDE32\uDE34-\uDE37\uDE39\uDE3B\uDE42\uDE47\uDE49\uDE4B\uDE4D-\uDE4F\uDE51\uDE52\uDE54\uDE57\uDE59\uDE5B\uDE5D\uDE5F\uDE61\uDE62\uDE64\uDE67-\uDE6A\uDE6C-\uDE72\uDE74-\uDE77\uDE79-\uDE7C\uDE7E\uDE80-\uDE89\uDE8B-\uDE9B\uDEA1-\uDEA3\uDEA5-\uDEA9\uDEAB-\uDEBB]|\uD869[\uDC00-\uDED6\uDF00-\uDFFF]|\uD86D[\uDC00-\uDF34\uDF40-\uDFFF]|\uD86E[\uDC00-\uDC1D\uDC20-\uDFFF]|\uD873[\uDC00-\uDEA1\uDEB0-\uDFFF]|\uD87A[\uDC00-\uDFE0]|\uD87E[\uDC00-\uDE1D]/,
ID_Continue:
/[\xAA\xB5\xBA\xC0-\xD6\xD8-\xF6\xF8-\u02C1\u02C6-\u02D1\u02E0-\u02E4\u02EC\u02EE\u0300-\u0374\u0376\u0377\u037A-\u037D\u037F\u0386\u0388-\u038A\u038C\u038E-\u03A1\u03A3-\u03F5\u03F7-\u0481\u0483-\u0487\u048A-\u052F\u0531-\u0556\u0559\u0561-\u0587\u0591-\u05BD\u05BF\u05C1\u05C2\u05C4\u05C5\u05C7\u05D0-\u05EA\u05F0-\u05F2\u0610-\u061A\u0620-\u0669\u066E-\u06D3\u06D5-\u06DC\u06DF-\u06E8\u06EA-\u06FC\u06FF\u0710-\u074A\u074D-\u07B1\u07C0-\u07F5\u07FA\u0800-\u082D\u0840-\u085B\u0860-\u086A\u08A0-\u08B4\u08B6-\u08BD\u08D4-\u08E1\u08E3-\u0963\u0966-\u096F\u0971-\u0983\u0985-\u098C\u098F\u0990\u0993-\u09A8\u09AA-\u09B0\u09B2\u09B6-\u09B9\u09BC-\u09C4\u09C7\u09C8\u09CB-\u09CE\u09D7\u09DC\u09DD\u09DF-\u09E3\u09E6-\u09F1\u09FC\u0A01-\u0A03\u0A05-\u0A0A\u0A0F\u0A10\u0A13-\u0A28\u0A2A-\u0A30\u0A32\u0A33\u0A35\u0A36\u0A38\u0A39\u0A3C\u0A3E-\u0A42\u0A47\u0A48\u0A4B-\u0A4D\u0A51\u0A59-\u0A5C\u0A5E\u0A66-\u0A75\u0A81-\u0A83\u0A85-\u0A8D\u0A8F-\u0A91\u0A93-\u0AA8\u0AAA-\u0AB0\u0AB2\u0AB3\u0AB5-\u0AB9\u0ABC-\u0AC5\u0AC7-\u0AC9\u0ACB-\u0ACD\u0AD0\u0AE0-\u0AE3\u0AE6-\u0AEF\u0AF9-\u0AFF\u0B01-\u0B03\u0B05-\u0B0C\u0B0F\u0B10\u0B13-\u0B28\u0B2A-\u0B30\u0B32\u0B33\u0B35-\u0B39\u0B3C-\u0B44\u0B47\u0B48\u0B4B-\u0B4D\u0B56\u0B57\u0B5C\u0B5D\u0B5F-\u0B63\u0B66-\u0B6F\u0B71\u0B82\u0B83\u0B85-\u0B8A\u0B8E-\u0B90\u0B92-\u0B95\u0B99\u0B9A\u0B9C\u0B9E\u0B9F\u0BA3\u0BA4\u0BA8-\u0BAA\u0BAE-\u0BB9\u0BBE-\u0BC2\u0BC6-\u0BC8\u0BCA-\u0BCD\u0BD0\u0BD7\u0BE6-\u0BEF\u0C00-\u0C03\u0C05-\u0C0C\u0C0E-\u0C10\u0C12-\u0C28\u0C2A-\u0C39\u0C3D-\u0C44\u0C46-\u0C48\u0C4A-\u0C4D\u0C55\u0C56\u0C58-\u0C5A\u0C60-\u0C63\u0C66-\u0C6F\u0C80-\u0C83\u0C85-\u0C8C\u0C8E-\u0C90\u0C92-\u0CA8\u0CAA-\u0CB3\u0CB5-\u0CB9\u0CBC-\u0CC4\u0CC6-\u0CC8\u0CCA-\u0CCD\u0CD5\u0CD6\u0CDE\u0CE0-\u0CE3\u0CE6-\u0CEF\u0CF1\u0CF2\u0D00-\u0D03\u0D05-\u0D0C\u0D0E-\u0D10\u0D12-\u0D44\u0D46-\u0D48\u0D4A-\u0D4E\u0D54-\u0D57\u0D5F-\u0D63\u0D66-\u0D6F\u0D7A-\u0D7F\u0D82\u0D83\u0D85-\u0D96\u0D9A-\u0DB1\u0DB3-\u0DBB\u0DBD\u0DC0-\u0DC6\u0DCA\u0DCF-\u0DD4\u0DD6\u0DD8-\u0DDF\u0DE6-\u0DEF\u0DF2\u0DF3\u0E01-\u0E3A\u0E40-\u0E4E\u0E50-\u0E59\u0E81\u0E82\u0E84\u0E87\u0E88\u0E8A\u0E8D\u0E94-\u0E97\u0E99-\u0E9F\u0EA1-\u0EA3\u0EA5\u0EA7\u0EAA\u0EAB\u0EAD-\u0EB9\u0EBB-\u0EBD\u0EC0-\u0EC4\u0EC6\u0EC8-\u0ECD\u0ED0-\u0ED9\u0EDC-\u0EDF\u0F00\u0F18\u0F19\u0F20-\u0F29\u0F35\u0F37\u0F39\u0F3E-\u0F47\u0F49-\u0F6C\u0F71-\u0F84\u0F86-\u0F97\u0F99-\u0FBC\u0FC6\u1000-\u1049\u1050-\u109D\u10A0-\u10C5\u10C7\u10CD\u10D0-\u10FA\u10FC-\u1248\u124A-\u124D\u1250-\u1256\u1258\u125A-\u125D\u1260-\u1288\u128A-\u128D\u1290-\u12B0\u12B2-\u12B5\u12B8-\u12BE\u12C0\u12C2-\u12C5\u12C8-\u12D6\u12D8-\u1310\u1312-\u1315\u1318-\u135A\u135D-\u135F\u1380-\u138F\u13A0-\u13F5\u13F8-\u13FD\u1401-\u166C\u166F-\u167F\u1681-\u169A\u16A0-\u16EA\u16EE-\u16F8\u1700-\u170C\u170E-\u1714\u1720-\u1734\u1740-\u1753\u1760-\u176C\u176E-\u1770\u1772\u1773\u1780-\u17D3\u17D7\u17DC\u17DD\u17E0-\u17E9\u180B-\u180D\u1810-\u1819\u1820-\u1877\u1880-\u18AA\u18B0-\u18F5\u1900-\u191E\u1920-\u192B\u1930-\u193B\u1946-\u196D\u1970-\u1974\u1980-\u19AB\u19B0-\u19C9\u19D0-\u19D9\u1A00-\u1A1B\u1A20-\u1A5E\u1A60-\u1A7C\u1A7F-\u1A89\u1A90-\u1A99\u1AA7\u1AB0-\u1ABD\u1B00-\u1B4B\u1B50-\u1B59\u1B6B-\u1B73\u1B80-\u1BF3\u1C00-\u1C37\u1C40-\u1C49\u1C4D-\u1C7D\u1C80-\u1C88\u1CD0-\u1CD2\u1CD4-\u1CF9\u1D00-\u1DF9\u1DFB-\u1F15\u1F18-\u1F1D\u1F20-\u1F45\u1F48-\u1F4D\u1F50-\u1F57\u1F59\u1F5B\u1F5D\u1F5F-\u1F7D\u1F80-\u1FB4\u1FB6-\u1FBC\u1FBE\u1FC2-\u1FC4\u1FC6-\u1FCC\u1FD0-\u1FD3\u1FD6-\u1FDB\u1FE0-\u1FEC\u1FF2-\u1FF4\u1FF6-\u1FFC\u203F\u2040\u2054\u2071\u207F\u2090-\u209C\u20D0-\u20DC\u20E1\u20E5-\u20F0\u2102\u2107\u210A-\u2113\u2115\u2119-\u211D\u2124\u2126\u2128\u212A-\u212D\u212F-\u2139\u213C-\u213F\u2145-\u2149\u214E\u2160-\u2188\u2C00-\u2C2E\u2C30-\u2C5E\u2C60-\u2CE4\u2CEB-\u2CF3\u2D00-\u2D25\u2D27\u2D2D\u2D30-\u2D67\u2D6F\u2D7F-\u2D96\u2DA0-\u2DA6\u2DA8-\u2DAE\u2DB0-\u2DB6\u2DB8-\u2DBE\u2DC0-\u2DC6\u2DC8-\u2DCE\u2DD0-\u2DD6\u2DD8-\u2DDE\u2DE0-\u2DFF\u2E2F\u3005-\u3007\u3021-\u302F\u3031-\u3035\u3038-\u303C\u3041-\u3096\u3099\u309A\u309D-\u309F\u30A1-\u30FA\u30FC-\u30FF\u3105-\u312E\u3131-\u318E\u31A0-\u31BA\u31F0-\u31FF\u3400-\u4DB5\u4E00-\u9FEA\uA000-\uA48C\uA4D0-\uA4FD\uA500-\uA60C\uA610-\uA62B\uA640-\uA66F\uA674-\uA67D\uA67F-\uA6F1\uA717-\uA71F\uA722-\uA788\uA78B-\uA7AE\uA7B0-\uA7B7\uA7F7-\uA827\uA840-\uA873\uA880-\uA8C5\uA8D0-\uA8D9\uA8E0-\uA8F7\uA8FB\uA8FD\uA900-\uA92D\uA930-\uA953\uA960-\uA97C\uA980-\uA9C0\uA9CF-\uA9D9\uA9E0-\uA9FE\uAA00-\uAA36\uAA40-\uAA4D\uAA50-\uAA59\uAA60-\uAA76\uAA7A-\uAAC2\uAADB-\uAADD\uAAE0-\uAAEF\uAAF2-\uAAF6\uAB01-\uAB06\uAB09-\uAB0E\uAB11-\uAB16\uAB20-\uAB26\uAB28-\uAB2E\uAB30-\uAB5A\uAB5C-\uAB65\uAB70-\uABEA\uABEC\uABED\uABF0-\uABF9\uAC00-\uD7A3\uD7B0-\uD7C6\uD7CB-\uD7FB\uF900-\uFA6D\uFA70-\uFAD9\uFB00-\uFB06\uFB13-\uFB17\uFB1D-\uFB28\uFB2A-\uFB36\uFB38-\uFB3C\uFB3E\uFB40\uFB41\uFB43\uFB44\uFB46-\uFBB1\uFBD3-\uFD3D\uFD50-\uFD8F\uFD92-\uFDC7\uFDF0-\uFDFB\uFE00-\uFE0F\uFE20-\uFE2F\uFE33\uFE34\uFE4D-\uFE4F\uFE70-\uFE74\uFE76-\uFEFC\uFF10-\uFF19\uFF21-\uFF3A\uFF3F\uFF41-\uFF5A\uFF66-\uFFBE\uFFC2-\uFFC7\uFFCA-\uFFCF\uFFD2-\uFFD7\uFFDA-\uFFDC]|\uD800[\uDC00-\uDC0B\uDC0D-\uDC26\uDC28-\uDC3A\uDC3C\uDC3D\uDC3F-\uDC4D\uDC50-\uDC5D\uDC80-\uDCFA\uDD40-\uDD74\uDDFD\uDE80-\uDE9C\uDEA0-\uDED0\uDEE0\uDF00-\uDF1F\uDF2D-\uDF4A\uDF50-\uDF7A\uDF80-\uDF9D\uDFA0-\uDFC3\uDFC8-\uDFCF\uDFD1-\uDFD5]|\uD801[\uDC00-\uDC9D\uDCA0-\uDCA9\uDCB0-\uDCD3\uDCD8-\uDCFB\uDD00-\uDD27\uDD30-\uDD63\uDE00-\uDF36\uDF40-\uDF55\uDF60-\uDF67]|\uD802[\uDC00-\uDC05\uDC08\uDC0A-\uDC35\uDC37\uDC38\uDC3C\uDC3F-\uDC55\uDC60-\uDC76\uDC80-\uDC9E\uDCE0-\uDCF2\uDCF4\uDCF5\uDD00-\uDD15\uDD20-\uDD39\uDD80-\uDDB7\uDDBE\uDDBF\uDE00-\uDE03\uDE05\uDE06\uDE0C-\uDE13\uDE15-\uDE17\uDE19-\uDE33\uDE38-\uDE3A\uDE3F\uDE60-\uDE7C\uDE80-\uDE9C\uDEC0-\uDEC7\uDEC9-\uDEE6\uDF00-\uDF35\uDF40-\uDF55\uDF60-\uDF72\uDF80-\uDF91]|\uD803[\uDC00-\uDC48\uDC80-\uDCB2\uDCC0-\uDCF2]|\uD804[\uDC00-\uDC46\uDC66-\uDC6F\uDC7F-\uDCBA\uDCD0-\uDCE8\uDCF0-\uDCF9\uDD00-\uDD34\uDD36-\uDD3F\uDD50-\uDD73\uDD76\uDD80-\uDDC4\uDDCA-\uDDCC\uDDD0-\uDDDA\uDDDC\uDE00-\uDE11\uDE13-\uDE37\uDE3E\uDE80-\uDE86\uDE88\uDE8A-\uDE8D\uDE8F-\uDE9D\uDE9F-\uDEA8\uDEB0-\uDEEA\uDEF0-\uDEF9\uDF00-\uDF03\uDF05-\uDF0C\uDF0F\uDF10\uDF13-\uDF28\uDF2A-\uDF30\uDF32\uDF33\uDF35-\uDF39\uDF3C-\uDF44\uDF47\uDF48\uDF4B-\uDF4D\uDF50\uDF57\uDF5D-\uDF63\uDF66-\uDF6C\uDF70-\uDF74]|\uD805[\uDC00-\uDC4A\uDC50-\uDC59\uDC80-\uDCC5\uDCC7\uDCD0-\uDCD9\uDD80-\uDDB5\uDDB8-\uDDC0\uDDD8-\uDDDD\uDE00-\uDE40\uDE44\uDE50-\uDE59\uDE80-\uDEB7\uDEC0-\uDEC9\uDF00-\uDF19\uDF1D-\uDF2B\uDF30-\uDF39]|\uD806[\uDCA0-\uDCE9\uDCFF\uDE00-\uDE3E\uDE47\uDE50-\uDE83\uDE86-\uDE99\uDEC0-\uDEF8]|\uD807[\uDC00-\uDC08\uDC0A-\uDC36\uDC38-\uDC40\uDC50-\uDC59\uDC72-\uDC8F\uDC92-\uDCA7\uDCA9-\uDCB6\uDD00-\uDD06\uDD08\uDD09\uDD0B-\uDD36\uDD3A\uDD3C\uDD3D\uDD3F-\uDD47\uDD50-\uDD59]|\uD808[\uDC00-\uDF99]|\uD809[\uDC00-\uDC6E\uDC80-\uDD43]|[\uD80C\uD81C-\uD820\uD840-\uD868\uD86A-\uD86C\uD86F-\uD872\uD874-\uD879][\uDC00-\uDFFF]|\uD80D[\uDC00-\uDC2E]|\uD811[\uDC00-\uDE46]|\uD81A[\uDC00-\uDE38\uDE40-\uDE5E\uDE60-\uDE69\uDED0-\uDEED\uDEF0-\uDEF4\uDF00-\uDF36\uDF40-\uDF43\uDF50-\uDF59\uDF63-\uDF77\uDF7D-\uDF8F]|\uD81B[\uDF00-\uDF44\uDF50-\uDF7E\uDF8F-\uDF9F\uDFE0\uDFE1]|\uD821[\uDC00-\uDFEC]|\uD822[\uDC00-\uDEF2]|\uD82C[\uDC00-\uDD1E\uDD70-\uDEFB]|\uD82F[\uDC00-\uDC6A\uDC70-\uDC7C\uDC80-\uDC88\uDC90-\uDC99\uDC9D\uDC9E]|\uD834[\uDD65-\uDD69\uDD6D-\uDD72\uDD7B-\uDD82\uDD85-\uDD8B\uDDAA-\uDDAD\uDE42-\uDE44]|\uD835[\uDC00-\uDC54\uDC56-\uDC9C\uDC9E\uDC9F\uDCA2\uDCA5\uDCA6\uDCA9-\uDCAC\uDCAE-\uDCB9\uDCBB\uDCBD-\uDCC3\uDCC5-\uDD05\uDD07-\uDD0A\uDD0D-\uDD14\uDD16-\uDD1C\uDD1E-\uDD39\uDD3B-\uDD3E\uDD40-\uDD44\uDD46\uDD4A-\uDD50\uDD52-\uDEA5\uDEA8-\uDEC0\uDEC2-\uDEDA\uDEDC-\uDEFA\uDEFC-\uDF14\uDF16-\uDF34\uDF36-\uDF4E\uDF50-\uDF6E\uDF70-\uDF88\uDF8A-\uDFA8\uDFAA-\uDFC2\uDFC4-\uDFCB\uDFCE-\uDFFF]|\uD836[\uDE00-\uDE36\uDE3B-\uDE6C\uDE75\uDE84\uDE9B-\uDE9F\uDEA1-\uDEAF]|\uD838[\uDC00-\uDC06\uDC08-\uDC18\uDC1B-\uDC21\uDC23\uDC24\uDC26-\uDC2A]|\uD83A[\uDC00-\uDCC4\uDCD0-\uDCD6\uDD00-\uDD4A\uDD50-\uDD59]|\uD83B[\uDE00-\uDE03\uDE05-\uDE1F\uDE21\uDE22\uDE24\uDE27\uDE29-\uDE32\uDE34-\uDE37\uDE39\uDE3B\uDE42\uDE47\uDE49\uDE4B\uDE4D-\uDE4F\uDE51\uDE52\uDE54\uDE57\uDE59\uDE5B\uDE5D\uDE5F\uDE61\uDE62\uDE64\uDE67-\uDE6A\uDE6C-\uDE72\uDE74-\uDE77\uDE79-\uDE7C\uDE7E\uDE80-\uDE89\uDE8B-\uDE9B\uDEA1-\uDEA3\uDEA5-\uDEA9\uDEAB-\uDEBB]|\uD869[\uDC00-\uDED6\uDF00-\uDFFF]|\uD86D[\uDC00-\uDF34\uDF40-\uDFFF]|\uD86E[\uDC00-\uDC1D\uDC20-\uDFFF]|\uD873[\uDC00-\uDEA1\uDEB0-\uDFFF]|\uD87A[\uDC00-\uDFE0]|\uD87E[\uDC00-\uDE1D]|\uDB40[\uDD00-\uDDEF]/,
},
U = {
isSpaceSeparator: function (u) {
return "string" == typeof u && G.Space_Separator.test(u);
},
isIdStartChar: function (u) {
return (
"string" == typeof u &&
((u >= "a" && u <= "z") ||
(u >= "A" && u <= "Z") ||
"$" === u ||
"_" === u ||
G.ID_Start.test(u))
);
},
isIdContinueChar: function (u) {
return (
"string" == typeof u &&
((u >= "a" && u <= "z") ||
(u >= "A" && u <= "Z") ||
(u >= "0" && u <= "9") ||
"$" === u ||
"_" === u ||
"" === u ||
"" === u ||
G.ID_Continue.test(u))
);
},
isDigit: function (u) {
return "string" == typeof u && /[0-9]/.test(u);
},
isHexDigit: function (u) {
return "string" == typeof u && /[0-9A-Fa-f]/.test(u);
},
};
function Z() {
for (T = "default", z = "", H = !1, $ = 1; ; ) {
R = q();
var u = X[T]();
if (u) return u;
}
}
function q() {
if (_[I]) return String.fromCodePoint(_.codePointAt(I));
}
function W() {
var u = q();
return (
"\n" === u ? (V++, (J = 0)) : u ? (J += u.length) : J++,
u && (I += u.length),
u
);
}
var X = {
default: function () {
switch (R) {
case "\t":
case "\v":
case "\f":
case " ":
case " ":
case "\ufeff":
case "\n":
case "\r":
case "\u2028":
case "\u2029":
return void W();
case "/":
return W(), void (T = "comment");
case void 0:
return W(), K("eof");
}
if (!U.isSpaceSeparator(R)) return X[O]();
W();
},
comment: function () {
switch (R) {
case "*":
return W(), void (T = "multiLineComment");
case "/":
return W(), void (T = "singleLineComment");
}
throw ru(W());
},
multiLineComment: function () {
switch (R) {
case "*":
return W(), void (T = "multiLineCommentAsterisk");
case void 0:
throw ru(W());
}
W();
},
multiLineCommentAsterisk: function () {
switch (R) {
case "*":
return void W();
case "/":
return W(), void (T = "default");
case void 0:
throw ru(W());
}
W(), (T = "multiLineComment");
},
singleLineComment: function () {
switch (R) {
case "\n":
case "\r":
case "\u2028":
case "\u2029":
return W(), void (T = "default");
case void 0:
return W(), K("eof");
}
W();
},
value: function () {
switch (R) {
case "{":
case "[":
return K("punctuator", W());
case "n":
return W(), Q("ull"), K("null", null);
case "t":
return W(), Q("rue"), K("boolean", !0);
case "f":
return W(), Q("alse"), K("boolean", !1);
case "-":
case "+":
return "-" === W() && ($ = -1), void (T = "sign");
case ".":
return (z = W()), void (T = "decimalPointLeading");
case "0":
return (z = W()), void (T = "zero");
case "1":
case "2":
case "3":
case "4":
case "5":
case "6":
case "7":
case "8":
case "9":
return (z = W()), void (T = "decimalInteger");
case "I":
return W(), Q("nfinity"), K("numeric", 1 / 0);
case "N":
return W(), Q("aN"), K("numeric", NaN);
case '"':
case "'":
return (H = '"' === W()), (z = ""), void (T = "string");
}
throw ru(W());
},
identifierNameStartEscape: function () {
if ("u" !== R) throw ru(W());
W();
var u = Y();
switch (u) {
case "$":
case "_":
break;
default:
if (!U.isIdStartChar(u)) throw nu();
}
(z += u), (T = "identifierName");
},
identifierName: function () {
switch (R) {
case "$":
case "_":
case "":
case "":
return void (z += W());
case "\\":
return W(), void (T = "identifierNameEscape");
}
if (!U.isIdContinueChar(R)) return K("identifier", z);
z += W();
},
identifierNameEscape: function () {
if ("u" !== R) throw ru(W());
W();
var u = Y();
switch (u) {
case "$":
case "_":
case "":
case "":
break;
default:
if (!U.isIdContinueChar(u)) throw nu();
}
(z += u), (T = "identifierName");
},
sign: function () {
switch (R) {
case ".":
return (z = W()), void (T = "decimalPointLeading");
case "0":
return (z = W()), void (T = "zero");
case "1":
case "2":
case "3":
case "4":
case "5":
case "6":
case "7":
case "8":
case "9":
return (z = W()), void (T = "decimalInteger");
case "I":
return W(), Q("nfinity"), K("numeric", $ * (1 / 0));
case "N":
return W(), Q("aN"), K("numeric", NaN);
}
throw ru(W());
},
zero: function () {
switch (R) {
case ".":
return (z += W()), void (T = "decimalPoint");
case "e":
case "E":
return (z += W()), void (T = "decimalExponent");
case "x":
case "X":
return (z += W()), void (T = "hexadecimal");
}
return K("numeric", 0 * $);
},
decimalInteger: function () {
switch (R) {
case ".":
return (z += W()), void (T = "decimalPoint");
case "e":
case "E":
return (z += W()), void (T = "decimalExponent");
}
if (!U.isDigit(R)) return K("numeric", $ * Number(z));
z += W();
},
decimalPointLeading: function () {
if (U.isDigit(R)) return (z += W()), void (T = "decimalFraction");
throw ru(W());
},
decimalPoint: function () {
switch (R) {
case "e":
case "E":
return (z += W()), void (T = "decimalExponent");
}
return U.isDigit(R)
? ((z += W()), void (T = "decimalFraction"))
: K("numeric", $ * Number(z));
},
decimalFraction: function () {
switch (R) {
case "e":
case "E":
return (z += W()), void (T = "decimalExponent");
}
if (!U.isDigit(R)) return K("numeric", $ * Number(z));
z += W();
},
decimalExponent: function () {
switch (R) {
case "+":
case "-":
return (z += W()), void (T = "decimalExponentSign");
}
if (U.isDigit(R)) return (z += W()), void (T = "decimalExponentInteger");
throw ru(W());
},
decimalExponentSign: function () {
if (U.isDigit(R)) return (z += W()), void (T = "decimalExponentInteger");
throw ru(W());
},
decimalExponentInteger: function () {
if (!U.isDigit(R)) return K("numeric", $ * Number(z));
z += W();
},
hexadecimal: function () {
if (U.isHexDigit(R)) return (z += W()), void (T = "hexadecimalInteger");
throw ru(W());
},
hexadecimalInteger: function () {
if (!U.isHexDigit(R)) return K("numeric", $ * Number(z));
z += W();
},
string: function () {
switch (R) {
case "\\":
return (
W(),
void (z += (function () {
switch (q()) {
case "b":
return W(), "\b";
case "f":
return W(), "\f";
case "n":
return W(), "\n";
case "r":
return W(), "\r";
case "t":
return W(), "\t";
case "v":
return W(), "\v";
case "0":
if ((W(), U.isDigit(q()))) throw ru(W());
return "\0";
case "x":
return (
W(),
(function () {
var u = "",
D = q();
if (!U.isHexDigit(D)) throw ru(W());
if (((u += W()), (D = q()), !U.isHexDigit(D)))
throw ru(W());
return (u += W()), String.fromCodePoint(parseInt(u, 16));
})()
);
case "u":
return W(), Y();
case "\n":
case "\u2028":
case "\u2029":
return W(), "";
case "\r":
return W(), "\n" === q() && W(), "";
case "1":
case "2":
case "3":
case "4":
case "5":
case "6":
case "7":
case "8":
case "9":
case void 0:
throw ru(W());
}
return W();
})())
);
case '"':
return H ? (W(), K("string", z)) : void (z += W());
case "'":
return H ? void (z += W()) : (W(), K("string", z));
case "\n":
case "\r":
throw ru(W());
case "\u2028":
case "\u2029":
!(function (u) {
console.warn(
"JSON5: '" +
Fu(u) +
"' in strings is not valid ECMAScript; consider escaping"
);
})(R);
break;
case void 0:
throw ru(W());
}
z += W();
},
start: function () {
switch (R) {
case "{":
case "[":
return K("punctuator", W());
}
T = "value";
},
beforePropertyName: function () {
switch (R) {
case "$":
case "_":
return (z = W()), void (T = "identifierName");
case "\\":
return W(), void (T = "identifierNameStartEscape");
case "}":
return K("punctuator", W());
case '"':
case "'":
return (H = '"' === W()), void (T = "string");
}
if (U.isIdStartChar(R)) return (z += W()), void (T = "identifierName");
throw ru(W());
},
afterPropertyName: function () {
if (":" === R) return K("punctuator", W());
throw ru(W());
},
beforePropertyValue: function () {
T = "value";
},
afterPropertyValue: function () {
switch (R) {
case ",":
case "}":
return K("punctuator", W());
}
throw ru(W());
},
beforeArrayValue: function () {
if ("]" === R) return K("punctuator", W());
T = "value";
},
afterArrayValue: function () {
switch (R) {
case ",":
case "]":
return K("punctuator", W());
}
throw ru(W());
},
end: function () {
throw ru(W());
},
};
function K(u, D) {
return { type: u, value: D, line: V, column: J };
}
function Q(u) {
for (var D = 0, e = u; D < e.length; D += 1) {
var r = e[D];
if (q() !== r) throw ru(W());
W();
}
}
function Y() {
for (var u = "", D = 4; D-- > 0; ) {
var e = q();
if (!U.isHexDigit(e)) throw ru(W());
u += W();
}
return String.fromCodePoint(parseInt(u, 16));
}
var uu = {
start: function () {
if ("eof" === M.type) throw tu();
Du();
},
beforePropertyName: function () {
switch (M.type) {
case "identifier":
case "string":
return (k = M.value), void (O = "afterPropertyName");
case "punctuator":
return void eu();
case "eof":
throw tu();
}
},
afterPropertyName: function () {
if ("eof" === M.type) throw tu();
O = "beforePropertyValue";
},
beforePropertyValue: function () {
if ("eof" === M.type) throw tu();
Du();
},
beforeArrayValue: function () {
if ("eof" === M.type) throw tu();
"punctuator" !== M.type || "]" !== M.value ? Du() : eu();
},
afterPropertyValue: function () {
if ("eof" === M.type) throw tu();
switch (M.value) {
case ",":
return void (O = "beforePropertyName");
case "}":
eu();
}
},
afterArrayValue: function () {
if ("eof" === M.type) throw tu();
switch (M.value) {
case ",":
return void (O = "beforeArrayValue");
case "]":
eu();
}
},
end: function () {},
};
function Du() {
var u;
switch (M.type) {
case "punctuator":
switch (M.value) {
case "{":
u = {};
break;
case "[":
u = [];
}
break;
case "null":
case "boolean":
case "numeric":
case "string":
u = M.value;
}
if (void 0 === L) L = u;
else {
var D = j[j.length - 1];
Array.isArray(D)
? D.push(u)
: Object.defineProperty(D, k, {
value: u,
writable: !0,
enumerable: !0,
configurable: !0,
});
}
if (null !== u && "object" == typeof u)
j.push(u),
(O = Array.isArray(u) ? "beforeArrayValue" : "beforePropertyName");
else {
var e = j[j.length - 1];
O =
null == e
? "end"
: Array.isArray(e)
? "afterArrayValue"
: "afterPropertyValue";
}
}
function eu() {
j.pop();
var u = j[j.length - 1];
O =
null == u
? "end"
: Array.isArray(u)
? "afterArrayValue"
: "afterPropertyValue";
}
function ru(u) {
return Cu(
void 0 === u
? "JSON5: invalid end of input at " + V + ":" + J
: "JSON5: invalid character '" + Fu(u) + "' at " + V + ":" + J
);
}
function tu() {
return Cu("JSON5: invalid end of input at " + V + ":" + J);
}
function nu() {
return Cu("JSON5: invalid identifier character at " + V + ":" + (J -= 5));
}
function Fu(u) {
var D = {
"'": "\\'",
'"': '\\"',
"\\": "\\\\",
"\b": "\\b",
"\f": "\\f",
"\n": "\\n",
"\r": "\\r",
"\t": "\\t",
"\v": "\\v",
"\0": "\\0",
"\u2028": "\\u2028",
"\u2029": "\\u2029",
};
if (D[u]) return D[u];
if (u < " ") {
var e = u.charCodeAt(0).toString(16);
return "\\x" + ("00" + e).substring(e.length);
}
return u;
}
function Cu(u) {
var D = new SyntaxError(u);
return (D.lineNumber = V), (D.columnNumber = J), D;
}
return {
parse: function (u, D) {
(_ = String(u)),
(O = "start"),
(j = []),
(I = 0),
(V = 1),
(J = 0),
(M = void 0),
(k = void 0),
(L = void 0);
do {
(M = Z()), uu[O]();
} while ("eof" !== M.type);
return "function" == typeof D
? (function u(D, e, r) {
var t = D[e];
if (null != t && "object" == typeof t)
if (Array.isArray(t))
for (var n = 0; n < t.length; n++) {
var F = String(n),
C = u(t, F, r);
void 0 === C
? delete t[F]
: Object.defineProperty(t, F, {
value: C,
writable: !0,
enumerable: !0,
configurable: !0,
});
}
else
for (var A in t) {
var i = u(t, A, r);
void 0 === i
? delete t[A]
: Object.defineProperty(t, A, {
value: i,
writable: !0,
enumerable: !0,
configurable: !0,
});
}
return r.call(D, e, t);
})({ "": L }, "", D)
: L;
},
stringify: function (u, D, e) {
var r,
t,
n,
F = [],
C = "",
A = "";
if (
(null == D ||
"object" != typeof D ||
Array.isArray(D) ||
((e = D.space), (n = D.quote), (D = D.replacer)),
"function" == typeof D)
)
t = D;
else if (Array.isArray(D)) {
r = [];
for (var i = 0, E = D; i < E.length; i += 1) {
var o = E[i],
a = void 0;
"string" == typeof o
? (a = o)
: ("number" == typeof o ||
o instanceof String ||
o instanceof Number) &&
(a = String(o)),
void 0 !== a && r.indexOf(a) < 0 && r.push(a);
}
}
return (
e instanceof Number
? (e = Number(e))
: e instanceof String && (e = String(e)),
"number" == typeof e
? e > 0 &&
((e = Math.min(10, Math.floor(e))), (A = " ".substr(0, e)))
: "string" == typeof e && (A = e.substr(0, 10)),
c("", { "": u })
);
function c(u, D) {
var e = D[u];
switch (
(null != e &&
("function" == typeof e.toJSON5
? (e = e.toJSON5(u))
: "function" == typeof e.toJSON && (e = e.toJSON(u))),
t && (e = t.call(D, u, e)),
e instanceof Number
? (e = Number(e))
: e instanceof String
? (e = String(e))
: e instanceof Boolean && (e = e.valueOf()),
e)
) {
case null:
return "null";
case !0:
return "true";
case !1:
return "false";
}
return "string" == typeof e
? B(e)
: "number" == typeof e
? String(e)
: "object" == typeof e
? Array.isArray(e)
? (function (u) {
if (F.indexOf(u) >= 0)
throw TypeError("Converting circular structure to JSON5");
F.push(u);
var D = C;
C += A;
for (var e, r = [], t = 0; t < u.length; t++) {
var n = c(String(t), u);
r.push(void 0 !== n ? n : "null");
}
if (0 === r.length) e = "[]";
else if ("" === A) {
var i = r.join(",");
e = "[" + i + "]";
} else {
var E = ",\n" + C,
o = r.join(E);
e = "[\n" + C + o + ",\n" + D + "]";
}
return F.pop(), (C = D), e;
})(e)
: (function (u) {
if (F.indexOf(u) >= 0)
throw TypeError("Converting circular structure to JSON5");
F.push(u);
var D = C;
C += A;
for (
var e, t, n = r || Object.keys(u), i = [], E = 0, o = n;
E < o.length;
E += 1
) {
var a = o[E],
B = c(a, u);
if (void 0 !== B) {
var f = s(a) + ":";
"" !== A && (f += " "), (f += B), i.push(f);
}
}
if (0 === i.length) e = "{}";
else if ("" === A) (t = i.join(",")), (e = "{" + t + "}");
else {
var l = ",\n" + C;
(t = i.join(l)), (e = "{\n" + C + t + ",\n" + D + "}");
}
return F.pop(), (C = D), e;
})(e)
: void 0;
}
function B(u) {
for (
var D = { "'": 0.1, '"': 0.2 },
e = {
"'": "\\'",
'"': '\\"',
"\\": "\\\\",
"\b": "\\b",
"\f": "\\f",
"\n": "\\n",
"\r": "\\r",
"\t": "\\t",
"\v": "\\v",
"\0": "\\0",
"\u2028": "\\u2028",
"\u2029": "\\u2029",
},
r = "",
t = 0;
t < u.length;
t++
) {
var F = u[t];
switch (F) {
case "'":
case '"':
D[F]++, (r += F);
continue;
case "\0":
if (U.isDigit(u[t + 1])) {
r += "\\x00";
continue;
}
}
if (e[F]) r += e[F];
else if (F < " ") {
var C = F.charCodeAt(0).toString(16);
r += "\\x" + ("00" + C).substring(C.length);
} else r += F;
}
var A =
n ||
Object.keys(D).reduce(function (u, e) {
return D[u] < D[e] ? u : e;
});
return A + (r = r.replace(new RegExp(A, "g"), e[A])) + A;
}
function s(u) {
if (0 === u.length) return B(u);
var D = String.fromCodePoint(u.codePointAt(0));
if (!U.isIdStartChar(D)) return B(u);
for (var e = D.length; e < u.length; e++)
if (!U.isIdContinueChar(String.fromCodePoint(u.codePointAt(e))))
return B(u);
return u;
}
},
};
});
!(function (e, t) {
'object' == typeof exports && 'undefined' != typeof module ? t(exports) : 'function' == typeof define && define.amd ? define(['exports'], t) : t((e.klona = {}));
})(this, function (e) {
e.klona = function e(t) {
if ('object' != typeof t) return t;
var o,
r,
n = Object.prototype.toString.call(t);
if ('[object Object]' === n) {
if (t.constructor !== Object && 'function' == typeof t.constructor) for (o in ((r = new t.constructor()), t)) t.hasOwnProperty(o) && r[o] !== t[o] && (r[o] = e(t[o]));
else for (o in ((r = {}), t)) '__proto__' === o ? Object.defineProperty(r, o, { value: e(t[o]), configurable: !0, enumerable: !0, writable: !0 }) : (r[o] = e(t[o]));
return r;
}
if ('[object Array]' === n) {
for (o = t.length, r = Array(o); o--; ) r[o] = e(t[o]);
return r;
}
return '[object Set]' === n
? ((r = new Set()),
t.forEach(function (t) {
r.add(e(t));
}),
r)
: '[object Map]' === n
? ((r = new Map()),
t.forEach(function (t, o) {
r.set(e(o), e(t));
}),
r)
: '[object Date]' === n
? new Date(+t)
: '[object RegExp]' === n
? (((r = new RegExp(t.source, t.flags)).lastIndex = t.lastIndex), r)
: '[object DataView]' === n
? new t.constructor(e(t.buffer))
: '[object ArrayBuffer]' === n
? t.slice(0)
: 'Array]' === n.slice(-6)
? new t.constructor(t)
: t;
};
});
'use strict';
if (typeof IS_DOCKER === 'undefined' || typeof IS_PROCESS_SERVER === 'undefined') {
var SESSION_OBJ = {};
var DOCS_OBJ = {};
}
var glb = {};
var func = {};
func.UI = {};
func.GLB = {};
func.mobile = {};
func.runtime = {};
func.runtime.bind = {};
func.runtime.program = {};
func.runtime.resources = {};
func.runtime.render = {};
func.runtime.session = {};
func.runtime.workers = {};
func.runtime.ui = {};
func.runtime.widgets = {};
glb.IS_STUDIO = null;
// Lodash replacement utilities
var xu_isEmpty = function (val) {
if (val == null) return true;
if (typeof val === 'boolean' || typeof val === 'number') return !val;
if (typeof val === 'string' || Array.isArray(val)) return val.length === 0;
if (val instanceof Map || val instanceof Set) return val.size === 0;
return Object.keys(val).length === 0;
};
var xu_isEqual = function (a, b) {
if (a === b) return true;
if (a == null || b == null) return a === b;
if (typeof a !== typeof b) return false;
if (a instanceof Date && b instanceof Date) return a.getTime() === b.getTime();
if (typeof a !== 'object') return false;
var keysA = Object.keys(a);
var keysB = Object.keys(b);
if (keysA.length !== keysB.length) return false;
for (var i = 0; i < keysA.length; i++) {
if (!Object.prototype.hasOwnProperty.call(b, keysA[i]) || !xu_isEqual(a[keysA[i]], b[keysA[i]])) return false;
}
return true;
};
var xu_get = function (obj, path, defaultVal) {
var keys = typeof path === 'string' ? path.split('.') : path;
var result = obj;
for (var i = 0; i < keys.length; i++) {
if (result == null) return defaultVal;
result = result[keys[i]];
}
return result === undefined ? defaultVal : result;
};
var xu_set = function (obj, path, value) {
var keys = typeof path === 'string' ? path.split('.') : path;
var current = obj;
for (var i = 0; i < keys.length - 1; i++) {
if (current[keys[i]] == null) current[keys[i]] = {};
current = current[keys[i]];
}
current[keys[keys.length - 1]] = value;
return obj;
};
var xu_clone = function (value) {
if (Array.isArray(value)) return value.slice();
if (value && typeof value === 'object') return { ...value };
return value;
};
var xu_cloneDeep = function (value) {
if (typeof structuredClone === 'function') {
try {
return structuredClone(value);
} catch (error) {}
}
if (Array.isArray(value)) {
return value.map(function (item) {
return xu_cloneDeep(item);
});
}
if (value && typeof value === 'object') {
var ret = {};
Object.keys(value).forEach(function (key) {
ret[key] = xu_cloneDeep(value[key]);
});
return ret;
}
return value;
};
var xu_map = function (collection, iteratee) {
if (!collection) return [];
if (Array.isArray(collection)) {
return collection.map(function (value, index) {
return iteratee ? iteratee(value, index) : value;
});
}
return Object.keys(collection).map(function (key) {
return iteratee ? iteratee(collection[key], key) : collection[key];
});
};
var xu_forEach = function (collection, iteratee) {
if (!collection || typeof iteratee !== 'function') return collection;
if (Array.isArray(collection)) {
collection.forEach(function (value, index) {
iteratee(value, index);
});
return collection;
}
Object.keys(collection).forEach(function (key) {
iteratee(collection[key], key);
});
return collection;
};
var xu_find = function (collection, predicate) {
if (!collection || typeof predicate !== 'function') return undefined;
var values = Array.isArray(collection)
? collection
: Object.keys(collection).map(function (key) {
return collection[key];
});
for (var i = 0; i < values.length; i++) {
if (predicate(values[i], i)) return values[i];
}
};
var xu_findIndex = function (collection, predicate) {
if (!Array.isArray(collection) || typeof predicate !== 'function') return -1;
for (var i = 0; i < collection.length; i++) {
if (predicate(collection[i], i)) return i;
}
return -1;
};
var xu_reduce = function (collection, iteratee, accumulator) {
if (!collection || typeof iteratee !== 'function') return accumulator;
var keys = Array.isArray(collection) ? collection.map(function (_value, index) { return index; }) : Object.keys(collection);
var has_accumulator = arguments.length > 2;
var result = accumulator;
for (var i = 0; i < keys.length; i++) {
var key = keys[i];
var value = Array.isArray(collection) ? collection[key] : collection[key];
if (!has_accumulator) {
result = value;
has_accumulator = true;
continue;
}
result = iteratee(result, value, key);
}
return result;
};
var xu_debounce = function (callback, wait) {
var timeout_id = null;
return function () {
var args = arguments;
var context = this;
clearTimeout(timeout_id);
timeout_id = setTimeout(function () {
callback.apply(context, args);
}, wait || 0);
};
};
var xu_toStringSafe = function (value) {
if (typeof value === 'string') return value;
if (value == null) return '';
return String(value);
};
var xu_some = function (collection, predicate) {
if (!collection || typeof predicate !== 'function') return false;
var values = Array.isArray(collection)
? collection
: Object.keys(collection).map(function (key) {
return collection[key];
});
for (var i = 0; i < values.length; i++) {
if (predicate(values[i], i)) return true;
}
return false;
};
var xu_has = function (obj, key) {
return !!obj && Object.prototype.hasOwnProperty.call(obj, key);
};
var xu_runtime_global = typeof globalThis !== 'undefined' ? globalThis : {};
if (typeof xu_runtime_global._ === 'undefined') {
xu_runtime_global._ = {
clone: xu_clone,
cloneDeep: xu_cloneDeep,
debounce: xu_debounce,
each: xu_forEach,
find: xu_find,
findIndex: xu_findIndex,
forEach: xu_forEach,
get: xu_get,
has: xu_has,
isArray: Array.isArray,
isEmpty: xu_isEmpty,
map: xu_map,
reduce: xu_reduce,
some: xu_some,
toString: xu_toStringSafe,
// lodash type-checks + common helpers (lodash was removed from the runtime;
// programs still call these on the global `_`).
isBoolean: function (v) { return typeof v === 'boolean'; },
isString: function (v) { return typeof v === 'string'; },
isNumber: function (v) { return typeof v === 'number'; },
isFunction: function (v) { return typeof v === 'function'; },
isObject: function (v) { return v !== null && (typeof v === 'object' || typeof v === 'function'); },
isPlainObject: function (v) { return v !== null && typeof v === 'object' && (Object.getPrototypeOf(v) === Object.prototype || Object.getPrototypeOf(v) === null); },
isNil: function (v) { return v == null; },
isUndefined: function (v) { return v === undefined; },
isNull: function (v) { return v === null; },
isInteger: Number.isInteger,
isNaN: function (v) { return typeof v === 'number' && v !== v; },
keys: function (o) { return o ? Object.keys(o) : []; },
values: function (o) { return o ? Object.values(o) : []; },
size: function (o) { return o == null ? 0 : (typeof o.length === 'number' ? o.length : Object.keys(o).length); },
includes: function (c, v) { return c == null ? false : (typeof c.includes === 'function' ? c.includes(v) : Object.values(c).indexOf(v) > -1); },
filter: function (c, fn) { return (c ? (Array.isArray(c) ? c : Object.values(c)) : []).filter(function (x, i) { return fn(x, i); }); },
last: function (a) { return a && a.length ? a[a.length - 1] : undefined; },
first: function (a) { return a && a.length ? a[0] : undefined; },
head: function (a) { return a && a.length ? a[0] : undefined; },
uniq: function (a) { return a ? Array.from(new Set(a)) : []; },
compact: function (a) { return a ? a.filter(Boolean) : []; },
assign: Object.assign,
merge: function (t) { for (var i = 1; i < arguments.length; i++) Object.assign(t || {}, arguments[i]); return t; },
capitalize: function (s) { s = String(s == null ? '' : s); return s.charAt(0).toUpperCase() + s.slice(1).toLowerCase(); },
noop: function () {},
};
}
if (typeof _ === 'undefined') {
var _ = xu_runtime_global._;
}
var PROJECT_OBJ = {};
var APP_OBJ = {};
var SESSION_ID = null;
var EXP_BUSY = false;
glb.PROTECTED_VARS = ['_NULL', '_THIS', '_FOR_KEY', '_FOR_VAL', '_ROWNO', '_ROWID', '_ROWDOC', '_KEY', '_VAL'];
// glb.newRecord = 999999;
func.common = {};
func.runtime.platform = {
get_global: function (name) {
try {
if (typeof globalThis === 'undefined') {
return null;
}
return globalThis?.[name] || null;
} catch (error) {
return null;
}
},
has_window: function () {
return !!func.runtime.platform.get_window();
},
has_document: function () {
return !!func.runtime.platform.get_document();
},
get_window: function () {
return func.runtime.platform.get_global('window');
},
get_document: function () {
return func.runtime.platform.get_global('document');
},
get_location: function () {
const win = func.runtime.platform.get_window();
return win?.location || null;
},
get_navigator: function () {
const win = func.runtime.platform.get_window();
if (win?.navigator) {
return win.navigator;
}
return func.runtime.platform.get_global('navi' + 'gator');
},
is_html_element: function (value) {
const html_element = func.runtime.platform.get_global('HTML' + 'Element');
if (typeof html_element !== 'function') {
return false;
}
return value instanceof html_element;
},
get_storage: function (type) {
const win = func.runtime.platform.get_window();
const storage_key = type === 'session' ? 'session' + 'Storage' : 'local' + 'Storage';
try {
if (!win) {
return null;
}
return win?.[storage_key] || null;
} catch (error) {
return null;
}
},
get_storage_item: function (key, type) {
const storage = func.runtime.platform.get_storage(type);
if (!storage) {
return null;
}
try {
return storage.getItem(key);
} catch (error) {
return null;
}
},
set_storage_item: function (key, value, type) {
const storage = func.runtime.platform.get_storage(type);
if (!storage) {
return false;
}
try {
storage.setItem(key, value);
return true;
} catch (error) {
return false;
}
},
get_cookie_item: function (key) {
if (!key) {
return null;
}
const doc = func.runtime.platform.get_document();
const cookie_string = doc?.cookie;
if (!cookie_string) {
return null;
}
const cookie_entry = cookie_string.split('; ').find(function (cookie) {
return cookie.startsWith(key + '=');
});
if (!cookie_entry) {
return null;
}
return cookie_entry.split('=').slice(1).join('=') || null;
},
get_url_href: function () {
return func.runtime.platform.get_location()?.href || '';
},
get_url_search: function () {
return func.runtime.platform.get_location()?.search || '';
},
get_url_hash: function () {
return func.runtime.platform.get_location()?.hash || '';
},
get_host: function () {
return func.runtime.platform.get_location()?.host || '';
},
get_hostname: function () {
return func.runtime.platform.get_location()?.hostname || '';
},
get_device_uuid: function () {
const win = func.runtime.platform.get_window();
return win?.device?.uuid || null;
},
get_device_name: function () {
const win = func.runtime.platform.get_window();
return win?.device?.name || null;
},
get_inner_size: function () {
const win = func.runtime.platform.get_window();
return {
width: win?.innerWidth || 0,
height: win?.innerHeight || 0,
};
},
add_window_listener: function (name, handler) {
const win = func.runtime.platform.get_window();
if (!win?.addEventListener) {
return false;
}
win.addEventListener(name, handler);
return true;
},
dispatch_body_event: function (event) {
const doc = func.runtime.platform.get_document();
if (!doc?.body?.dispatchEvent) {
return false;
}
doc.body.dispatchEvent(event);
return true;
},
reload_top_window: function () {
const win = func.runtime.platform.get_window();
if (!win?.top?.location?.reload) {
return false;
}
win.top.location.reload();
return true;
},
get_service_worker: function () {
const nav = func.runtime.platform.get_navigator();
return nav?.serviceWorker || null;
},
has_service_worker: function () {
return !!func.runtime.platform.get_service_worker();
},
register_service_worker: function (script_url) {
const service_worker = func.runtime.platform.get_service_worker();
if (!service_worker?.register) {
return Promise.reject(new Error('serviceWorker is not available'));
}
return service_worker.register(script_url);
},
add_service_worker_listener: function (name, handler) {
const service_worker = func.runtime.platform.get_service_worker();
if (!service_worker?.addEventListener) {
return false;
}
service_worker.addEventListener(name, handler);
return true;
},
};
// ── Platform-agnostic event bus ──
// Works in browser, worker, and Node environments.
// In browser, bridge DOM events into this bus so core code never touches $(document) directly.
func.runtime.platform._event_bus = {};
func.runtime.platform.on = function (name, handler) {
if (!func.runtime.platform._event_bus[name]) {
func.runtime.platform._event_bus[name] = [];
}
func.runtime.platform._event_bus[name].push(handler);
};
func.runtime.platform.off = function (name, handler) {
const handlers = func.runtime.platform._event_bus[name];
if (!handlers) return;
if (!handler) {
delete func.runtime.platform._event_bus[name];
return;
}
const index = handlers.indexOf(handler);
if (index !== -1) {
handlers.splice(index, 1);
}
};
func.runtime.platform._emitting = {};
func.runtime.platform.emit = function (name, data) {
// re-entrancy guard: prevent infinite loops when DOM bridge triggers the same event
if (func.runtime.platform._emitting[name]) return;
func.runtime.platform._emitting[name] = true;
try {
const handlers = func.runtime.platform._event_bus[name];
if (handlers) {
for (let i = 0; i < handlers.length; i++) {
handlers[i](data);
}
}
if (typeof func.runtime.platform.dispatch_document_event === 'function') {
func.runtime.platform.dispatch_document_event(name, data);
}
} finally {
func.runtime.platform._emitting[name] = false;
}
};
// ── Platform helpers for DOM-independent resource loading ──
func.runtime.platform.apply_element_attributes = function (node, attributes, excluded_keys = []) {
if (!node?.setAttribute || !attributes) {
return node;
}
const excluded = new Set(excluded_keys || []);
const attr_keys = Object.keys(attributes);
for (let index = 0; index < attr_keys.length; index++) {
const key = attr_keys[index];
if (!key || excluded.has(key)) {
continue;
}
const value = attributes[key];
if (value === false || typeof value === 'undefined') {
continue;
}
node.setAttribute(key, value === null ? '' : `${value}`);
}
return node;
};
func.runtime.platform.load_script = function (url, type, callback, attributes) {
const normalized_url = typeof url === 'string' ? url.trim() : '';
if (!normalized_url || normalized_url === 'undefined' || normalized_url === 'null') {
if (callback) {
callback();
}
return null;
}
const doc = func.runtime.platform.get_document();
if (!doc?.createElement || !doc?.head?.appendChild) {
if (callback) {
callback();
}
return;
}
const find_existing_script = function () {
const asset_key = attributes?.['data-xuda-asset-key'];
const scripts = doc.querySelectorAll ? Array.from(doc.querySelectorAll('script')) : [];
return scripts.find(function (script) {
if (asset_key && script.getAttribute('data-xuda-asset-key') === asset_key) {
return true;
}
return script.getAttribute('src') === normalized_url;
}) || null;
};
const existing_script = find_existing_script();
if (existing_script) {
if (callback) {
if (existing_script.getAttribute('data-xuda-loaded') === 'true' || !url) {
callback();
} else {
existing_script.addEventListener('load', callback, { once: true });
existing_script.addEventListener('error', callback, { once: true });
}
}
return existing_script;
}
const script = doc.createElement('script');
script.src = normalized_url;
if (type) script.type = type;
func.runtime.platform.apply_element_attributes(script, attributes, ['src', 'type']);
script.onload = function () {
script.setAttribute('data-xuda-loaded', 'true');
if (callback) {
callback();
}
};
script.onerror = function () {
if (callback) {
callback();
}
};
doc.head.appendChild(script);
return script;
};
func.runtime.platform.load_css = function (href, attributes) {
const normalized_href = typeof href === 'string' ? href.trim() : '';
if (!normalized_href || normalized_href === 'undefined' || normalized_href === 'null') {
return null;
}
const doc = func.runtime.platform.get_document();
if (!doc?.createElement || !doc?.head) {
return;
}
try {
const asset_key = attributes?.['data-xuda-asset-key'];
const existing_links = doc.querySelectorAll ? Array.from(doc.querySelectorAll('link')) : [];
const existing = existing_links.find(function (link) {
if (asset_key && link.getAttribute('data-xuda-asset-key') === asset_key) {
return true;
}
return link.getAttribute('href') === normalized_href;
});
if (existing) return existing;
} catch (err) {
return;
}
const link = doc.createElement('link');
link.rel = 'stylesheet';
link.type = 'text/css';
link.href = normalized_href;
func.runtime.platform.apply_element_attributes(link, attributes, ['href']);
doc.head.insertBefore(link, doc.head.firstChild);
return link;
};
func.runtime.platform.remove_js_css = function (filename, filetype) {
const doc = func.runtime.platform.get_document();
if (!doc?.getElementsByTagName) return;
const tagName = filetype === 'js' ? 'script' : filetype === 'css' ? 'link' : 'none';
const attr = filetype === 'js' ? 'src' : filetype === 'css' ? 'href' : 'none';
const elements = doc.getElementsByTagName(tagName);
for (let i = elements.length - 1; i >= 0; i--) {
if (elements[i] && elements[i].getAttribute(attr) != null && elements[i].getAttribute(attr).indexOf(filename) !== -1) {
elements[i].parentNode.removeChild(elements[i]);
}
}
};
func.runtime.platform.inject_css = function (cssText) {
const doc = func.runtime.platform.get_document();
if (!doc?.createElement || !doc?.head?.appendChild || !cssText) return;
const style = doc.createElement('style');
style.type = 'text/css';
style.textContent = cssText;
doc.head.appendChild(style);
};
func.runtime.platform.set_title = function (title) {
const doc = func.runtime.platform.get_document();
if (doc) {
doc.title = title;
}
};
func.runtime.platform.set_cursor = function (element, cursor) {
const node = func.runtime.ui?.get_first_node ? func.runtime.ui.get_first_node(element) : element;
if (node?.style) {
node.style.cursor = cursor;
}
};
func.runtime.program.normalize_doc_for_runtime = function (doc) {
if (!doc || doc.__xudaRuntimeNormalized || !Array.isArray(doc.progUi) || !doc.progUi.length) {
return doc;
}
const normalize_tag_name = function (tag_name) {
return `${tag_name || ''}`.trim().toLowerCase();
};
const merge_attributes = function (target, source) {
const merged = { ...(target || {}) };
const source_attributes = source || {};
const keys = Object.keys(source_attributes);
for (let index = 0; index < keys.length; index++) {
const key = keys[index];
const value = source_attributes[key];
if (typeof value === 'undefined') {
continue;
}
if (key === 'class' && merged.class && value) {
const next_value = `${merged.class} ${value}`.trim();
merged.class = Array.from(new Set(next_value.split(/\s+/).filter(Boolean))).join(' ');
continue;
}
if (key === 'style' && merged.style && value) {
merged.style = `${merged.style}; ${value}`.trim();
continue;
}
if (typeof merged[key] === 'undefined') {
merged[key] = value;
}
}
return merged;
};
const get_attribute_source = function (source) {
if (!source) {
return {};
}
if (typeof source === 'string') {
try {
const parsed = JSON.parse(source);
return parsed && typeof parsed === 'object' && !Array.isArray(parsed) ? parsed : {};
} catch (_) {
return {};
}
}
return typeof source === 'object' && !Array.isArray(source) ? source : {};
};
const normalize_node_attributes = function (node) {
let attributes = get_attribute_source(node?.attributes);
attributes = merge_attributes(attributes, get_attribute_source(node?.attributes_raw_obj));
attributes = merge_attributes(attributes, get_attribute_source(node?.attributes_raw));
return attributes;
};
const normalize_nodes = function (nodes, state) {
const normalized_nodes = [];
for (let index = 0; index < (nodes || []).length; index++) {
const node = nodes[index];
if (!node || typeof node !== 'object') {
continue;
}
const tag_name = normalize_tag_name(node.tagName);
if (tag_name === '!doctype') {
state.changed = true;
continue;
}
if (tag_name === 'html') {
state.changed = true;
state.root_attributes = merge_attributes(state.root_attributes, normalize_node_attributes(node));
normalized_nodes.push.apply(normalized_nodes, normalize_nodes(node.children, state));
continue;
}
if (tag_name === 'head') {
state.changed = true;
normalized_nodes.push.apply(normalized_nodes, normalize_nodes(node.children, state));
continue;
}
if (tag_name === 'body') {
state.changed = true;
state.root_attributes = merge_attributes(state.root_attributes, normalize_node_attributes(node));
normalized_nodes.push.apply(normalized_nodes, normalize_nodes(node.children, state));
continue;
}
let next_node = node;
const merged_node_attributes = normalize_node_attributes(node);
if (!xu_isEqual(merged_node_attributes, node.attributes || {})) {
next_node = {
...next_node,
attributes: merged_node_attributes,
};
state.changed = true;
}
if (Array.isArray(node.children) && node.children.length) {
const next_children = normalize_nodes(node.children, state);
if (next_children !== node.children) {
next_node = {
...next_node,
children: next_children,
};
state.changed = true;
}
}
normalized_nodes.push(next_node);
}
return normalized_nodes;
};
const [root_node, ...extra_nodes] = doc.progUi;
if (!root_node || typeof root_node !== 'object') {
return doc;
}
const state = {
changed: false,
root_attributes: {},
};
const root_node_attributes = normalize_node_attributes(root_node);
if (!xu_isEqual(root_node_attributes, root_node.attributes || {})) {
state.changed = true;
}
const normalized_children = normalize_nodes([...(root_node.children || []), ...extra_nodes], state);
const merged_attributes = merge_attributes(root_node_attributes, state.root_attributes);
if (!state.changed && !Object.keys(state.root_attributes).length) {
doc.__xudaRuntimeNormalized = true;
return doc;
}
return {
...doc,
__xudaRuntimeNormalized: true,
progUi: [
{
...root_node,
attributes: merged_attributes,
children: normalized_children,
},
],
};
};
func.runtime.env = {
get_url_params: function () {
const search = func.runtime.platform.get_url_search();
return new URLSearchParams(search);
},
get_url_parameters_object: function () {
const search_params = func.runtime.env.get_url_params();
const parameters = {};
for (const [key, value] of search_params.entries()) {
parameters[key] = value;
}
return parameters;
},
get_default_session_value: function (key) {
switch (key) {
case 'domain':
return func.runtime.platform.get_host();
case 'engine_mode':
return 'miniapp';
case 'app_id':
return 'unknown';
default:
return null;
}
},
};
func.runtime.session.create_tab_id = function () {
const session_storage = func.runtime.platform.get_storage('session');
const local_storage = func.runtime.platform.get_storage('local');
var page_tab_id = session_storage?.getItem('tabID');
if (page_tab_id == null) {
var local_tab_id = local_storage?.getItem('tabID');
page_tab_id = local_tab_id == null ? 1 : Number(local_tab_id) + 1;
func.runtime.platform.set_storage_item('tabID', page_tab_id, 'local');
func.runtime.platform.set_storage_item('tabID', page_tab_id, 'session');
}
return page_tab_id;
};
func.runtime.session.get_fingerprint = function (components, instance_id) {
const device_uuid = func.runtime.platform.get_device_uuid();
if (func.utils.get_device() && device_uuid) {
if (instance_id) {
return instance_id + device_uuid;
}
return device_uuid;
}
const fingerprint_id = Fingerprint2.x64hash128(
components
.map(function (pair) {
return pair.value;
})
.join(),
31,
);
if (instance_id) {
return instance_id + fingerprint_id + func.runtime.session.create_tab_id();
}
return fingerprint_id;
};
func.runtime.session.create_state = function (SESSION_ID, options) {
const runtime_host = func.runtime.platform.get_host();
SESSION_OBJ[SESSION_ID] = {
JOB_NO: 1000,
opt: options.opt,
root_element: options.root_element,
worker_type: options.worker_type,
api_callback: options.api_callback,
CODE_BUNDLE: options.code_bundle,
SLIM_BUNDLE: options.slim_bundle,
WORKER_OBJ: {
jobs: [],
num: 1000,
stat: null,
},
DS_GLB: {},
SYS_GLOBAL_OBJ_FIREBASE_AUTH_INFO: {
token: '',
first_name: '',
last_name: '',
email: '',
user_id: '',
picture: '',
verified_email: '',
locale: '',
error_code: '',
error_msg: '',
},
SYS_GLOBAL_OBJ_CLIENT_INFO: {
fingerprint: '',
device: '',
user_agent: '',
browser_version: '',
browser_name: '',
engine_version: '',
client_ip: '',
engine_name: '',
os_name: '',
os_version: '',
device_model: '',
device_vendor: '',
device_type: '',
screen_current_resolution_x: '',
screen_current_resolution_y: '',
screen_available_resolution_x: '',
screen_available_resolution_y: '',
language: '',
time_zone: '',
cpu_architecture: '',
uuid: '',
},
PUSH_NOTIFICATION_GRANTED: null,
FIREBASE_TOKEN_ID: null,
USR_OBJ: {},
debug_js: null,
DS_UI_EVENTS_GLB: {},
host: runtime_host,
req_id: 0,
build_info: {},
CACHE_REQ: {},
url_params: {
...func.common.getParametersFromUrl(),
...options.url_params,
},
};
func.runtime.workers.ensure_registry(SESSION_ID);
return SESSION_OBJ[SESSION_ID];
};
func.runtime.session.is_slim = function (SESSION_ID) {
const session = typeof SESSION_ID === 'undefined' || SESSION_ID === null ? null : SESSION_OBJ?.[SESSION_ID];
if (session && typeof session.SLIM_BUNDLE !== 'undefined') {
return !!session.SLIM_BUNDLE;
}
return !!glb.SLIM_BUNDLE;
};
func.runtime.session.set_default_value = function (_session, key, value) {
_session[key] = value || func.runtime.env.get_default_session_value(key);
return _session[key];
};
func.runtime.session.populate_client_info = function (_session, components) {
const _client_info = _session.SYS_GLOBAL_OBJ_CLIENT_INFO;
const platform = func.runtime.platform;
const { engine_mode } = _session;
_client_info.fingerprint = func.runtime.session.get_fingerprint(components);
if (engine_mode === 'live_preview') {
const inner_size = platform.get_inner_size();
_client_info.screen_current_resolution_x = inner_size.width;
_client_info.screen_current_resolution_y = inner_size.height;
_client_info.screen_available_resolution_x = inner_size.width;
_client_info.screen_available_resolution_y = inner_size.height;
} else {
_client_info.screen_current_resolution_x = components[6].value[0];
_client_info.screen_current_resolution_y = components[6].value[1];
_client_info.screen_available_resolution_x = components[7].value[0];
_client_info.screen_available_resolution_y = components[7].value[1];
}
const client = new ClientJS();
_client_info.device = func.utils.get_device();
const browser_data = client.getBrowserData();
_client_info.user_agent = browser_data.ua;
_client_info.browser_version = browser_data.browser.name;
_client_info.browser_name = browser_data.browser.version;
_client_info.engine_version = browser_data.engine.name;
_client_info.engine_name = browser_data.engine.version;
_client_info.os_name = browser_data.os.name;
_client_info.os_version = browser_data.os.version;
_client_info.device_model = browser_data.device.name;
_client_info.device_vendor = browser_data.device.name;
_client_info.device_type = browser_data.device.name;
_client_info.language = client.getLanguage();
_client_info.time_zone = client.getTimeZone();
_client_info.cpu_architecture = browser_data.cpu.architecture;
if (['android', 'ios', 'windows', 'macos', 'linux', 'live_preview'].includes(engine_mode) && func.utils.get_device()) {
_client_info.uuid = platform.get_device_uuid();
const device_name = platform.get_device_name();
if (device_name) {
_client_info.device_name = device_name;
}
}
return _client_info;
};
func.runtime.workers.ensure_registry = function (SESSION_ID) {
if (!WEB_WORKER[SESSION_ID]) {
WEB_WORKER[SESSION_ID] = {};
}
return WEB_WORKER[SESSION_ID];
};
func.runtime.workers.get_registry_entry = function (SESSION_ID, worker_id) {
return func.runtime.workers.ensure_registry(SESSION_ID)?.[worker_id] || null;
};
func.runtime.workers.set_registry_entry = function (SESSION_ID, worker_id, entry) {
const worker_registry = func.runtime.workers.ensure_registry(SESSION_ID);
worker_registry[worker_id] = entry;
return worker_registry[worker_id];
};
func.runtime.workers.build_worker_name = function (glb_worker_type, session, prog_obj, worker_id, build_id) {
return (
`${typeof session.SLIM_BUNDLE === 'undefined' || !session.SLIM_BUNDLE ? '' : 'Slim '}${prog_obj.menuName} worker` +
' ' +
glb_worker_type +
': #' +
worker_id.toString() +
' ' +
(build_id || '') +
' ' +
session.domain
);
};
func.runtime.workers.is_server_transport = function (session) {
return !!(RUNTIME_SERVER_WEBSOCKET && RUNTIME_SERVER_WEBSOCKET_CONNECTED && (!session.opt.app_computing_mode || session.opt.app_computing_mode === 'server'));
};
func.runtime.workers.send_message = function (SESSION_ID, worker_id, session, msg, process_pid) {
const registry_entry = func.runtime.workers.get_registry_entry(SESSION_ID, worker_id);
if (!registry_entry?.worker) {
return false;
}
if (func.runtime.workers.is_server_transport(session)) {
if (process_pid) {
msg.process_pid = process_pid;
}
registry_entry.worker.emit('message', msg);
return true;
}
registry_entry.worker.postMessage(msg);
return true;
};
func.runtime.workers.set_promise = function (SESSION_ID, worker_id, promise_queue_id, value) {
const registry_entry = func.runtime.workers.get_registry_entry(SESSION_ID, worker_id);
if (!registry_entry) {
return null;
}
registry_entry.promise_queue[promise_queue_id] = value;
return registry_entry.promise_queue[promise_queue_id];
};
func.runtime.workers.get_promise = function (SESSION_ID, worker_id, promise_queue_id) {
const registry_entry = func.runtime.workers.get_registry_entry(SESSION_ID, worker_id);
if (!registry_entry) {
return null;
}
return registry_entry.promise_queue[promise_queue_id];
};
func.runtime.workers.delete_promise = function (SESSION_ID, worker_id, promise_queue_id) {
const registry_entry = func.runtime.workers.get_registry_entry(SESSION_ID, worker_id);
if (!registry_entry?.promise_queue) {
return false;
}
delete registry_entry.promise_queue[promise_queue_id];
return true;
};
func.runtime.render.clone_runtime_options = function (value) {
if (typeof structuredClone === 'function') {
try {
return structuredClone(value);
} catch (_) {}
}
if (Array.isArray(value)) {
return value.map(function (item) {
return func.runtime.render.clone_runtime_options(item);
});
}
if (value && typeof value === 'object') {
const cloned = {};
const keys = Object.keys(value);
for (let index = 0; index < keys.length; index++) {
const key = keys[index];
cloned[key] = func.runtime.render.clone_runtime_options(value[key]);
}
return cloned;
}
return value;
};
func.runtime.render.normalize_runtime_bootstrap = function (raw_options = {}) {
const options = raw_options || {};
let app_computing_mode = options.app_computing_mode || '';
let app_render_mode = options.app_render_mode || '';
let app_client_activation = options.app_client_activation || '';
let ssr_payload = options.ssr_payload || null;
if (typeof ssr_payload === 'string') {
try {
ssr_payload = JSON.parse(ssr_payload);
} catch (_) {
ssr_payload = null;
}
}
if (ssr_payload && typeof ssr_payload === 'object') {
ssr_payload = func.runtime.render.clone_runtime_options(ssr_payload);
}
if (!app_computing_mode) {
if (app_render_mode === 'ssr_first_page' || app_render_mode === 'ssr_full') {
app_computing_mode = 'server';
} else {
app_computing_mode = 'main';
}
}
switch (app_computing_mode) {
case 'main':
app_render_mode = 'csr';
app_client_activation = 'none';
break;
case 'worker':
app_render_mode = 'csr';
app_client_activation = 'none';
break;
default:
app_computing_mode = 'server';
if (app_render_mode !== 'ssr_full') {
app_render_mode = 'ssr_first_page';
}
app_client_activation = app_render_mode === 'ssr_full' ? 'hydrate' : 'takeover';
break;
}
if (ssr_payload && typeof ssr_payload === 'object') {
if (!ssr_payload.app_render_mode) {
ssr_payload.app_render_mode = app_render_mode;
}
if (!ssr_payload.app_client_activation) {
ssr_payload.app_client_activation = app_client_activation;
}
if (!ssr_payload.app_computing_mode) {
ssr_payload.app_computing_mode = app_computing_mode;
}
}
return {
app_computing_mode,
app_render_mode,
app_client_activation,
ssr_payload,
};
};
func.runtime.render.apply_runtime_bootstrap_defaults = function (target = {}) {
const normalized = func.runtime.render.normalize_runtime_bootstrap(target);
target.app_computing_mode = normalized.app_computing_mode;
target.app_render_mode = normalized.app_render_mode;
target.app_client_activation = normalized.app_client_activation;
target.ssr_payload = normalized.ssr_payload;
return normalized;
};
func.runtime.render.is_server_render_mode = function (target = {}) {
const normalized = func.runtime.render.normalize_runtime_bootstrap(target?.opt || target);
return normalized.app_computing_mode === 'server' && normalized.app_render_mode !== 'csr';
};
func.runtime.render.is_takeover_mode = function (target = {}) {
const normalized = func.runtime.render.normalize_runtime_bootstrap(target?.opt || target);
return normalized.app_client_activation === 'takeover';
};
func.runtime.render.is_hydration_mode = function (target = {}) {
const normalized = func.runtime.render.normalize_runtime_bootstrap(target?.opt || target);
return normalized.app_client_activation === 'hydrate';
};
func.runtime.render.get_ssr_payload = function (target = {}) {
if (target?.opt?.ssr_payload) {
return target.opt.ssr_payload;
}
if (target?.ssr_payload) {
return target.ssr_payload;
}
const win = func.runtime.platform.get_window();
return win?.__XUDA_SSR__ || null;
};
func.runtime.render.should_use_ssr_payload = function (SESSION_ID, paramsP) {
const session = SESSION_OBJ?.[SESSION_ID];
const payload = func.runtime.render.get_ssr_payload(session);
if (!payload || payload._consumed) {
return false;
}
if (paramsP?.prog_id && payload.prog_id && payload.prog_id !== paramsP.prog_id) {
return false;
}
return true;
};
func.runtime.render.mark_ssr_payload_consumed = function (SESSION_ID) {
const session = SESSION_OBJ?.[SESSION_ID];
const payload = func.runtime.render.get_ssr_payload(session);
if (!payload || typeof payload !== 'object') {
return false;
}
payload._consumed = true;
return true;
};
func.runtime.render.get_root_data_system = function (SESSION_ID) {
return SESSION_OBJ[SESSION_ID]?.DS_GLB?.[0]?.data_system || null;
};
func.runtime.render.resolve_xu_for_source = async function (SESSION_ID, dsSessionP, value) {
let arr = value;
let reference_source_obj;
const normalized_reference = typeof value === 'string' && value.startsWith('@') ? value.substring(1) : value;
const _progFields = await func.datasource.get_progFields(SESSION_ID, dsSessionP);
let view_field_obj = func.common.find_item_by_key(_progFields, 'field_id', normalized_reference);
if (view_field_obj || normalized_reference !== value) {
reference_source_obj = await func.datasource.get_value(SESSION_ID, normalized_reference, dsSessionP);
arr = reference_source_obj?.ret?.value;
} else {
if (typeof value === 'string') {
arr = eval(value.replaceAll('\\', ''));
}
if (typeof arr === 'number') {
arr = Array.from(Array(arr).keys());
}
}
return {
arr,
reference_source_obj,
};
};
func.runtime.render.apply_iterate_value_to_ds = function (SESSION_ID, dsSessionP, currentRecordId, progFields, field_id, value, is_dynamic_field) {
if (is_dynamic_field) {
func.datasource.add_dynamic_field_to_ds(SESSION_ID, dsSessionP, field_id, value);
return true;
}
let view_field_obj = func.common.find_item_by_key(progFields || [], 'field_id', field_id);
if (!view_field_obj) {
console.error('field not exist in dataset for xu-for method');
return false;
}
let _ds = SESSION_OBJ[SESSION_ID].DS_GLB[dsSessionP];
try {
const row_idx = func.common.find_ROWID_idx(_ds, currentRecordId);
_ds.data_feed.rows[row_idx][field_id] = value;
return true;
} catch (err) {
console.error(err);
return false;
}
};
func.runtime.render.build_iterate_info = function (options) {
return {
_val: options._val,
_key: options._key,
iterator_key: options.iterator_key,
iterator_val: options.iterator_val,
is_key_dynamic_field: options.is_key_dynamic_field,
is_val_dynamic_field: options.is_val_dynamic_field,
reference_source_obj: options.reference_source_obj,
};
};
func.runtime.render.apply_iterate_info_to_current_record = function (SESSION_ID, dsSessionP, currentRecordId, progFields, iterate_info) {
if (!iterate_info) {
return false;
}
func.runtime.render.apply_iterate_value_to_ds(SESSION_ID, dsSessionP, currentRecordId, progFields, iterate_info.iterator_key, iterate_info._key, iterate_info.is_key_dynamic_field);
func.runtime.render.apply_iterate_value_to_ds(SESSION_ID, dsSessionP, currentRecordId, progFields, iterate_info.iterator_val, iterate_info._val, iterate_info.is_val_dynamic_field);
return true;
};
func.runtime.render.sync_iterate_info_to_dataset = function (_ds, iterate_info) {
if (!iterate_info) {
return false;
}
const sync_field = function (field_id, value, is_dynamic_field) {
if (is_dynamic_field) {
_ds.dynamic_fields[field_id].value = value;
return true;
}
try {
const row_idx = func.common.find_ROWID_idx(_ds, _ds.currentRecordId);
_ds.data_feed.rows[row_idx][field_id] = value;
return true;
} catch (err) {
console.error(err);
return false;
}
};
sync_field(iterate_info.iterator_key, iterate_info._key, iterate_info.is_key_dynamic_field);
sync_field(iterate_info.iterator_val, iterate_info._val, iterate_info.is_val_dynamic_field);
return true;
};
func.runtime.program.get_params_obj = async function (SESSION_ID, prog_id, nodeP, dsSession) {
const _prog = await func.utils.VIEWS_OBJ.get(SESSION_ID, prog_id);
if (!_prog) return;
let params_res = {},
params_raw = {};
if (_prog?.properties?.progParams) {
for await (const [key, val] of Object.entries(_prog.properties.progParams)) {
if (!['in', 'out'].includes(val.data.dir)) continue;
if (nodeP.attributes) {
if (Object.prototype.hasOwnProperty.call(nodeP.attributes, val.data.parameter)) {
params_res[val.data.parameter] = nodeP.attributes[val.data.parameter];
} else if (Object.prototype.hasOwnProperty.call(nodeP.attributes, `xu-exp:${val.data.parameter}`)) {
if (val.data.dir == 'out') {
params_res[val.data.parameter] = nodeP.attributes[`xu-exp:${val.data.parameter}`].replaceAll('@', '');
} else {
let ret = await func.expression.get(SESSION_ID, nodeP.attributes[`xu-exp:${val.data.parameter}`], dsSession, 'parameters');
params_res[val.data.parameter] = ret.result;
params_raw[val.data.parameter] = nodeP.attributes[`xu-exp:${val.data.parameter}`];
}
}
continue;
}
console.warn(`Warning: Program ${_prog.properties.menuName} expected In parameter: ${val.data.parameter} but received null instead`);
}
}
return { params_res, params_raw };
};
func.runtime.bind.build_datasource_changes = function (dsSessionP, currentRecordId, field_id, value) {
return {
[dsSessionP]: {
[currentRecordId]: {
[field_id]: value,
},
},
};
};
func.runtime.bind.get_bind_node = function (elm) {
if (!elm) {
return null;
}
if (elm.nodeType) {
return elm;
}
if (Array.isArray(elm) || typeof elm.length === 'number') {
return elm[0] || null;
}
return null;
};
func.runtime.bind.is_value_node = function (node) {
if (!node?.tagName) {
return false;
}
const tag_name = node.tagName.toLowerCase();
return ['input', 'select', 'textarea'].includes(tag_name) || typeof node.value !== 'undefined';
};
func.runtime.bind.get_bind_value_node = function (elm) {
const node = func.runtime.bind.get_bind_node(elm);
if (!node) {
return null;
}
if (func.runtime.bind.is_value_node(node)) {
return node;
}
return node.querySelector?.('input, select, textarea') || node;
};
func.runtime.bind.should_use_live_text_listener = function (elm) {
const node = func.runtime.bind.get_bind_value_node(elm);
if (!node?.tagName) {
return false;
}
const tag_name = node.tagName.toLowerCase();
const type = (node.type || node.getAttribute?.('type') || '').toLowerCase();
if (tag_name === 'textarea') {
return true;
}
if (tag_name !== 'input') {
return false;
}
return !['button', 'checkbox', 'file', 'hidden', 'image', 'radio', 'reset', 'submit'].includes(type);
};
func.runtime.bind.get_live_text_debounce_ms = function () {
return 200;
};
func.runtime.bind.to_finite_number = function (value) {
if (value === '' || value === null || typeof value === 'undefined') {
return null;
}
const numeric_value = Number(value);
return Number.isFinite(numeric_value) ? numeric_value : null;
};
func.runtime.bind.get_select_option_number = function (option) {
if (!option) {
return null;
}
const candidate_attributes = ['value', 'data-value', 'data-xuda-value', 'data-xu-value', 'xu-value'];
for (let index = 0; index < candidate_attributes.length; index++) {
const attr_value = option.getAttribute?.(candidate_attributes[index]);
const numeric_value = func.runtime.bind.to_finite_number(attr_value);
if (numeric_value !== null) {
return numeric_value;
}
}
return null;
};
func.runtime.bind.remember_select_numeric_context = function (elm, field_type, value) {
if (field_type !== 'number' || elm?.tagName?.toLowerCase?.() !== 'select') {
return false;
}
const numeric_value = func.runtime.bind.to_finite_number(value);
if (numeric_value === null || elm.selectedIndex < 0) {
return false;
}
elm.__xuda_select_numeric_bind_context = {
selectedIndex: elm.selectedIndex,
value: numeric_value,
};
return true;
};
func.runtime.bind.apply_select_value_once = function (elm, value, field_type) {
const options = Array.from(elm.options || []);
if (!options.length) {
return false;
}
const string_value = value === null || typeof value === 'undefined' ? '' : String(value);
const numeric_value = func.runtime.bind.to_finite_number(value);
let matched_index = -1;
if (field_type === 'number' && numeric_value !== null) {
matched_index = options.findIndex(function (option) {
return func.runtime.bind.get_select_option_number(option) === numeric_value;
});
if (matched_index < 0 && Number.isInteger(numeric_value)) {
if (options[numeric_value - 1]) {
matched_index = numeric_value - 1;
} else if (options[numeric_value]) {
matched_index = numeric_value;
}
}
} else {
matched_index = options.findIndex(function (option) {
return String(option.value) === string_value || String(option.getAttribute?.('value')) === string_value;
});
}
if (matched_index >= 0) {
elm.selectedIndex = matched_index;
func.runtime.bind.remember_select_numeric_context(elm, field_type, value);
return true;
}
return false;
};
func.runtime.bind.schedule_select_value_retry = function (elm, value, field_type, scheduled_at) {
if (elm.__xuda_select_set_retry_timer_ids) {
for (let index = 0; index < elm.__xuda_select_set_retry_timer_ids.length; index++) {
clearTimeout(elm.__xuda_select_set_retry_timer_ids[index]);
}
}
const retry_delays = [0, 50, 250, 500];
elm.__xuda_select_set_retry_timer_ids = retry_delays.map(function (delay) {
return setTimeout(function () {
if (!elm.isConnected) {
return;
}
if (elm.__xuda_select_last_user_change_ts && elm.__xuda_select_last_user_change_ts > scheduled_at) {
return;
}
func.runtime.bind.apply_select_value_once(elm, value, field_type);
}, delay);
});
};
func.runtime.bind.set_select_value = function (elm, value, field_type) {
if (elm?.tagName?.toLowerCase?.() !== 'select') {
return false;
}
const options = Array.from(elm.options || []);
const string_value = value === null || typeof value === 'undefined' ? '' : String(value);
if (elm.multiple) {
const selected_values = Array.isArray(value)
? value.map(function (item) {
return String(item);
})
: [string_value];
options.forEach(function (option) {
option.selected = selected_values.includes(String(option.value));
});
return true;
}
const scheduled_at = Date.now();
func.runtime.bind.apply_select_value_once(elm, value, field_type);
func.runtime.bind.schedule_select_value_retry(elm, value, field_type, scheduled_at);
return true;
};
func.runtime.bind.get_select_numeric_value = function (elm, raw_value) {
const raw_numeric_value = func.runtime.bind.to_finite_number(raw_value);
if (raw_numeric_value !== null) {
return raw_numeric_value;
}
if (elm?.tagName?.toLowerCase?.() !== 'select') {
return raw_value;
}
const selected_option = elm.options?.[elm.selectedIndex];
const selected_option_number = func.runtime.bind.get_select_option_number(selected_option);
if (selected_option_number !== null) {
return selected_option_number;
}
const context = elm.__xuda_select_numeric_bind_context;
if (context && Number.isFinite(context.value) && Number.isFinite(context.selectedIndex) && elm.selectedIndex >= 0) {
return context.value + (elm.selectedIndex - context.selectedIndex);
}
if (elm.selectedIndex >= 0) {
return elm.selectedIndex + 1;
}
return raw_value;
};
func.runtime.bind.normalize_raw_value = function (elm, field_prop, raw_value) {
const field_type = func.runtime.bind.get_field_type(field_prop);
if (field_type === 'number') {
return func.runtime.bind.get_select_numeric_value(elm, raw_value);
}
return raw_value;
};
func.runtime.bind.track_pending_update = function (SESSION_ID, promise) {
const session_obj = SESSION_OBJ?.[SESSION_ID];
if (!session_obj || !promise?.finally) {
return promise;
}
if (!session_obj.pending_bind_updates) {
session_obj.pending_bind_updates = new Set();
}
const tracked_promise = promise.finally(function () {
session_obj.pending_bind_updates.delete(tracked_promise);
});
session_obj.pending_bind_updates.add(tracked_promise);
return tracked_promise;
};
func.runtime.bind.wait_for_pending_updates = async function (SESSION_ID) {
const pending_bind_updates = SESSION_OBJ?.[SESSION_ID]?.pending_bind_updates;
if (!pending_bind_updates?.size) {
return;
}
await Promise.allSettled(Array.from(pending_bind_updates));
};
func.runtime.bind.attach_live_text_listener = function (adapter_name, adapter, elm, handler) {
const node = func.runtime.bind.get_bind_value_node(elm);
if (!node?.addEventListener || typeof handler !== 'function') {
return false;
}
const listener_key = `__xuda_${adapter_name}_live_text_bind_listeners`;
const listener_state_key = `${listener_key}_state`;
const previous_listeners = node[listener_key];
if (previous_listeners) {
for (let index = 0; index < previous_listeners.length; index++) {
node.removeEventListener(previous_listeners[index].event_name, previous_listeners[index].listener);
}
}
if (node[listener_state_key]?.debounce_timer) {
clearTimeout(node[listener_state_key].debounce_timer);
}
const debounce_ms = func.runtime.bind.get_live_text_debounce_ms();
const state = {
debounce_timer: null,
last_value: adapter.getter ? adapter.getter.call(adapter, node) : node.value,
pending_event: null,
pending_value: adapter.getter ? adapter.getter.call(adapter, node) : node.value,
};
node[listener_state_key] = state;
const listener = function (event) {
const current_value = adapter.getter ? adapter.getter.call(adapter, node) : node.value;
if (xu_isEqual(current_value, state.pending_value)) {
return;
}
state.pending_event = event;
state.pending_value = current_value;
clearTimeout(state.debounce_timer);
state.debounce_timer = setTimeout(function () {
const next_value = adapter.getter ? adapter.getter.call(adapter, node) : node.value;
state.debounce_timer = null;
state.pending_value = next_value;
if (xu_isEqual(next_value, state.last_value)) {
return;
}
state.last_value = next_value;
return handler(state.pending_event);
}, debounce_ms);
};
const listeners = [];
for (const event_name of ['input', 'keyup']) {
node.addEventListener(event_name, listener);
listeners.push({ event_name, listener });
}
node[listener_key] = listeners;
return true;
};
func.runtime.bind.normalize_adapter = function (adapter, adapter_name = 'adapter') {
if (!func.runtime.bind.is_valid_adapter(adapter)) {
return adapter;
}
return {
getter: function (elm) {
return adapter.getter.call(adapter, func.runtime.bind.get_bind_value_node(elm) || elm);
},
setter: function (elm, value) {
return adapter.setter.call(adapter, func.runtime.bind.get_bind_value_node(elm) || elm, value);
},
listener: function (elm, handler) {
const node = func.runtime.bind.get_bind_value_node(elm) || elm;
if (func.runtime.bind.should_use_live_text_listener(node)) {
return func.runtime.bind.attach_live_text_listener(adapter_name, adapter, node, handler);
}
return adapter.listener.call(adapter, node, handler);
},
};
};
func.runtime.bind.get_native_adapter = function () {
const has_explicit_value = function (elm) {
return !!elm?.hasAttribute?.('value');
};
const get_listener_event = function (elm) {
const tag_name = elm?.tagName?.toLowerCase?.();
const type = (elm?.type || '').toLowerCase();
if (tag_name === 'select' || ['checkbox', 'radio'].includes(type)) {
return 'change';
}
return 'input';
};
return {
getter: function (elm) {
if (!elm) {
return undefined;
}
const tag_name = elm?.tagName?.toLowerCase?.();
const type = (elm?.type || '').toLowerCase();
if (tag_name === 'select' && elm.multiple) {
return Array.from(elm.options || [])
.filter(function (option) {
return option.selected;
})
.map(function (option) {
return option.value;
});
}
if (type === 'checkbox') {
return has_explicit_value(elm) ? elm.value : !!elm.checked;
}
if (type === 'radio') {
return elm.value;
}
return typeof elm.value !== 'undefined' ? elm.value : undefined;
},
setter: function (elm, value) {
if (!elm) {
return false;
}
const tag_name = elm?.tagName?.toLowerCase?.();
const type = (elm?.type || '').toLowerCase();
if (tag_name === 'select' && elm.multiple) {
const selected_values = Array.isArray(value)
? value.map(function (item) {
return String(item);
})
: [String(value)];
Array.from(elm.options || []).forEach(function (option) {
option.selected = selected_values.includes(String(option.value));
});
return true;
}
if (type === 'checkbox' || type === 'radio') {
return true;
}
if (typeof elm.value !== 'undefined') {
elm.value = value === null || typeof value === 'undefined' ? '' : String(value);
}
return true;
},
listener: function (elm, handler) {
if (!elm?.addEventListener || typeof handler !== 'function') {
return false;
}
const event_name = get_listener_event(elm);
const listener_key = '__xuda_native_bind_listener_' + event_name;
if (elm[listener_key]) {
elm.removeEventListener(event_name, elm[listener_key]);
}
elm.addEventListener(event_name, handler);
elm[listener_key] = handler;
return true;
},
};
};
func.runtime.bind.is_valid_adapter = function (adapter) {
return !!(
adapter &&
typeof adapter.getter === 'function' &&
typeof adapter.setter === 'function' &&
typeof adapter.listener === 'function'
);
};
func.runtime.bind.get_adapter = function (SESSION_ID) {
const native_adapter = func.runtime.bind.get_native_adapter();
if (func.runtime.session.is_slim(SESSION_ID)) {
return func.runtime.bind.normalize_adapter(native_adapter, 'native');
}
const plugin_bind = UI_FRAMEWORK_PLUGIN?.bind;
if (!plugin_bind) {
return func.runtime.bind.normalize_adapter(native_adapter, 'native');
}
if (func.runtime.bind.is_valid_adapter(plugin_bind)) {
return func.runtime.bind.normalize_adapter(plugin_bind, 'plugin');
}
if (typeof plugin_bind === 'function') {
try {
const bind_instance = new plugin_bind();
if (func.runtime.bind.is_valid_adapter(bind_instance)) {
return func.runtime.bind.normalize_adapter(bind_instance, 'plugin');
}
} catch (error) {}
try {
const bind_factory = plugin_bind();
if (func.runtime.bind.is_valid_adapter(bind_factory)) {
return func.runtime.bind.normalize_adapter(bind_factory, 'plugin');
}
} catch (error) {}
}
return func.runtime.bind.normalize_adapter(native_adapter, 'native');
};
func.runtime.bind.resolve_field = async function (SESSION_ID, prog_id, dsSessionP, field_id, iterate_info) {
let _prog_id = prog_id;
let _dsP = dsSessionP;
let is_dynamic_field = false;
let field_prop;
const find_in_view = async function (field_id, prog_id) {
const view_ret = await func.utils.VIEWS_OBJ.get(SESSION_ID, prog_id);
if (!view_ret) {
return null;
}
return func.common.find_item_by_key(view_ret.progFields, 'field_id', field_id);
};
if (['_FOR_VAL', '_FOR_KEY'].includes(field_id)) {
is_dynamic_field = true;
if (iterate_info && (iterate_info.iterator_val === field_id || iterate_info.iterator_key === field_id)) {
const iter_value = iterate_info.iterator_val === field_id ? iterate_info._val : iterate_info._key;
const toType = function (obj) {
return {}.toString.call(obj).match(/\s([a-zA-Z]+)/)[1].toLowerCase();
};
field_prop = {
id: field_id,
data: { type: 'virtual', field_id },
props: { fieldType: typeof iter_value !== 'undefined' ? toType(iter_value) : 'string' },
value: iter_value,
};
} else {
field_prop = SESSION_OBJ[SESSION_ID]?.DS_GLB?.[_dsP]?.dynamic_fields?.[field_id];
}
} else {
field_prop = await find_in_view(field_id, _prog_id);
if (!field_prop) {
const ret_get_value = await func.datasource.get_value(SESSION_ID, field_id, _dsP);
if (ret_get_value.found) {
_dsP = ret_get_value.dsSessionP;
let _ds = SESSION_OBJ[SESSION_ID].DS_GLB[_dsP];
_prog_id = _ds?.prog_id;
field_prop = await find_in_view(field_id, _prog_id);
if (!field_prop) {
field_prop = _ds?.dynamic_fields?.[field_id];
if (field_prop) {
is_dynamic_field = true;
}
}
}
}
}
if (!field_prop) {
throw `field ${field_id} not found in the program scope`;
}
if (!is_dynamic_field) {
const _ds = SESSION_OBJ[SESSION_ID]?.DS_GLB?.[_dsP];
const table_id = _ds?._dataSourceTableId;
if (table_id) {
try {
const table_obj = await func.utils.FILES_OBJ.get(SESSION_ID, table_id);
const table_field_prop = func.common.find_item_by_key(table_obj?.tableFields || [], 'field_id', field_id);
const table_field_type = table_field_prop?.props?.fieldType;
if (table_field_type) {
field_prop = {
...field_prop,
props: {
...(field_prop.props || {}),
fieldType: table_field_type,
},
};
}
} catch (error) {}
}
}
return {
bind_field_id: field_id,
field_prop,
is_dynamic_field,
dsSessionP: _dsP,
prog_id: _prog_id,
};
};
func.runtime.bind.get_field_type = function (field_prop) {
return field_prop?.props?.fieldType;
};
func.runtime.bind.toggle_array_value = function (arr_value_before_cast, value_from_getter) {
if (arr_value_before_cast.includes(value_from_getter)) {
return arr_value_before_cast.filter((item) => !xu_isEqual(item, value_from_getter));
}
arr_value_before_cast.push(value_from_getter);
return arr_value_before_cast;
};
func.runtime.bind.get_cast_value = async function (SESSION_ID, field_prop, input_field_type, raw_value) {
const field_type = func.runtime.bind.get_field_type(field_prop);
if (field_type === 'object') {
return await func.common.get_cast_val(SESSION_ID, 'xu-bind', 'value', input_field_type, raw_value);
}
return await func.common.get_cast_val(SESSION_ID, 'xu-bind', 'value', field_type, raw_value);
};
func.runtime.bind.get_source_value = function (_ds, bind_field_id, is_dynamic_field) {
if (is_dynamic_field) {
return _ds.dynamic_fields[bind_field_id].value;
}
const row_idx = func.common.find_ROWID_idx(_ds, _ds.currentRecordId);
return _ds.data_feed.rows?.[row_idx]?.[bind_field_id];
};
func.runtime.bind.format_display_value = function ($elm, field_prop, bind_field_id, expression_value, value, input_field_type) {
const field_type = func.runtime.bind.get_field_type(field_prop);
const elm_value = func.runtime.ui.get_attr($elm, 'value');
if (field_type === 'array' && input_field_type === 'checkbox' && elm_value) {
return value.includes(elm_value);
}
if (field_type === 'array' && input_field_type === 'radio' && elm_value) {
if (value.includes(elm_value)) {
return elm_value;
}
return false;
}
if (field_type === 'object' && expression_value.split('.').length > 1) {
let str = expression_value.replace(bind_field_id, '(' + JSON.stringify(value) + ')');
return eval(str);
}
return value;
};
func.runtime.bind.update_reference_source_array = async function (options) {
const field_type = func.runtime.bind.get_field_type(options.field_prop);
const reference_source_obj = options.iterate_info?.reference_source_obj;
if (!reference_source_obj || reference_source_obj.ret.type !== 'array' || options.iterate_info?.iterator_val !== options.bind_field_id) {
return false;
}
const arr_idx = Number(options.iterate_info._key);
const dataset_arr = await func.datasource.get_value(options.SESSION_ID, reference_source_obj.fieldIdP, options.dsSessionP, reference_source_obj.currentRecordId);
let new_arr = structuredClone(dataset_arr.ret.value);
if (field_type === 'object' && options.val_is_reference_field) {
let obj_item = new_arr[arr_idx];
let e_exp = options.expression_value.replace(options.bind_field_id, 'obj_item');
eval(e_exp + `=${JSON.stringify(options.value)}`);
new_arr[arr_idx] = obj_item;
} else {
new_arr[arr_idx] = options.value;
}
let datasource_changes = func.runtime.bind.build_datasource_changes(options.dsSessionP, options.currentRecordId, reference_source_obj.fieldIdP, new_arr);
await func.datasource.update(options.SESSION_ID, datasource_changes);
return true;
};
func.runtime.resources.load_cdn = async function (SESSION_ID, resource) {
let normalized_resource = resource;
if (!(typeof normalized_resource === 'object' && normalized_resource !== null) && typeof normalized_resource === 'string') {
normalized_resource = { src: normalized_resource, type: 'js' };
}
if (!(typeof normalized_resource === 'object' && normalized_resource !== null)) {
throw new Error('cdn resource in wrong format');
}
return new Promise(async (resolve) => {
try {
switch (normalized_resource.type) {
case 'js':
await func.utils.load_js_on_demand(normalized_resource.src);
break;
case 'css':
func.runtime.platform.load_css(normalized_resource.src);
break;
case 'module':
await func.utils.load_js_on_demand(normalized_resource.src, 'module');
break;
default:
await func.utils.load_js_on_demand(normalized_resource.src);
break;
}
resolve();
} catch (error) {
func.utils.debug_report(SESSION_ID, 'xu-cdn', 'Fail to load: ' + normalized_resource, 'W');
resolve();
}
});
};
func.runtime.resources.get_plugin_manifest_entry = function (_session, plugin_name) {
return APP_OBJ[_session.app_id]?.app_plugins_purchased?.[plugin_name] || null;
};
func.runtime.resources.get_plugin_resource_candidates = function (_session, plugin, resource) {
const manifest_entry = plugin?.manifest?.[resource];
const default_path = `${manifest_entry?.dist ? 'dist/' : ''}${resource}`;
const candidates = [];
if (_session?.worker_type === 'Dev' && manifest_entry?.dist && /\.mjs$/.test(resource)) {
candidates.push(`src/${resource}`);
}
candidates.push(default_path);
return Array.from(new Set(candidates.filter(Boolean)));
};
func.runtime.resources.get_plugin_module_path = function (plugin, resource, _session) {
return func.runtime.resources.get_plugin_resource_candidates(_session, plugin, resource)[0] || resource;
};
func.runtime.resources.get_plugin_module_url = async function (SESSION_ID, plugin_name, plugin, resource) {
const _session = SESSION_OBJ[SESSION_ID];
return await func.utils.get_plugin_npm_cdn(SESSION_ID, plugin_name, func.runtime.resources.get_plugin_module_path(plugin, resource, _session));
};
func.runtime.resources.import_plugin_module = async function (SESSION_ID, plugin_name, plugin, resource) {
const _session = SESSION_OBJ[SESSION_ID];
const candidates = func.runtime.resources.get_plugin_resource_candidates(_session, plugin, resource);
let last_error = null;
for (let index = 0; index < candidates.length; index++) {
const candidate = candidates[index];
try {
return await func.utils.get_plugin_resource(SESSION_ID, plugin_name, candidate);
} catch (error) {
last_error = error;
}
}
throw last_error || new Error(`plugin resource not found: ${plugin_name}/${resource}`);
};
func.runtime.resources.load_plugin_runtime_css = async function (SESSION_ID, plugin_name, plugin) {
if (!plugin?.manifest?.['runtime.mjs']?.dist || !plugin?.manifest?.['runtime.mjs']?.css) {
return false;
}
const plugin_runtime_css_url = await func.utils.get_plugin_npm_cdn(SESSION_ID, plugin_name, 'dist/runtime.css');
func.utils.load_css_on_demand(plugin_runtime_css_url);
return true;
};
func.runtime.resources.resolve_plugin_properties = async function (SESSION_ID, dsSessionP, attributes, properties) {
// Plugin property schemas can carry function-valued defaults (e.g. tippy
// `placement: () => "top"`), which structuredClone cannot clone and throws on,
// breaking every element that uses the plugin. xu_cloneDeep tries
// structuredClone first and falls back to a recursive clone that preserves
// function references, so the schema clones cleanly either way.
let resolved_properties = xu_cloneDeep(properties);
for await (let [prop_name, prop_val] of Object.entries(resolved_properties || {})) {
prop_val.value = attributes?.[prop_name];
if (attributes?.[`xu-exp:${prop_name}`]) {
const res = await func.expression.get(SESSION_ID, attributes[`xu-exp:${prop_name}`], dsSessionP, 'UI Attr EXP');
prop_val.value = res.result;
}
}
return resolved_properties;
};
func.runtime.resources.run_ui_plugin = async function (SESSION_ID, paramsP, $elm, plugin_name, value) {
var _session = SESSION_OBJ[SESSION_ID];
const plugin = func.runtime.resources.get_plugin_manifest_entry(_session, plugin_name);
if (!plugin?.installed || !plugin?.manifest?.['runtime.mjs']?.exist || !plugin?.manifest?.['index.mjs']?.exist || !value?.enabled) {
return false;
}
await func.runtime.resources.load_plugin_runtime_css(SESSION_ID, plugin_name, plugin);
const plugin_index_resources = await func.runtime.resources.import_plugin_module(SESSION_ID, plugin_name, plugin, 'index.mjs');
const properties = await func.runtime.resources.resolve_plugin_properties(SESSION_ID, paramsP.dsSessionP, value?.attributes, plugin_index_resources.properties);
const plugin_runtime_resources = await func.runtime.resources.import_plugin_module(SESSION_ID, plugin_name, plugin, 'runtime.mjs');
if (plugin_runtime_resources.cdn && Array.isArray(plugin_runtime_resources.cdn)) {
for await (const resource of plugin_runtime_resources.cdn) {
await func.runtime.resources.load_cdn(SESSION_ID, resource);
}
}
if (plugin_runtime_resources.fn) {
const plugin_element = func.runtime.ui.get_first_node?.($elm) || $elm?.[0] || $elm;
if (!plugin_element) {
return false;
}
await plugin_runtime_resources.fn(plugin_name, plugin_element, properties);
}
return true;
};
func.runtime.widgets.create_context = function (SESSION_ID, paramsP, prop) {
const _session = SESSION_OBJ[SESSION_ID];
const plugin_name = prop['xu-widget'];
return {
SESSION_ID,
_session,
plugin_name,
method: prop['xu-method'] || '_default',
dsP: paramsP.dsSessionP,
propsP: prop,
sourceP: 'widgets',
plugin: APP_OBJ[_session.app_id]?.app_plugins_purchased?.[plugin_name] || null,
};
};
func.runtime.widgets.report_error = function (context, descP, warn) {
const program = context?._session?.DS_GLB?.[context.dsP];
if (!program) {
return null;
}
func.utils.debug.log(context.SESSION_ID, program.prog_id + '_' + program.callingMenuId, {
module: 'widgets',
action: 'Init',
source: context.sourceP,
prop: descP,
details: descP,
result: null,
error: warn ? false : true,
fields: null,
type: 'widgets',
prog_id: program.prog_id,
});
return null;
};
func.runtime.widgets.get_property_value = async function (context, fieldIdP, val, props) {
if (!val) return;
var value = fieldIdP in props ? props[fieldIdP] : typeof val.defaultValue === 'function' ? val?.defaultValue?.() : val?.defaultValue;
if (val.render === 'eventId') {
value = props?.[fieldIdP]?.event;
}
if (props[`xu-exp:${fieldIdP}`]) {
value = (await func.expression.get(context.SESSION_ID, props[`xu-exp:${fieldIdP}`], context.dsP, 'widget property')).result;
}
return func.common.get_cast_val(
context.SESSION_ID,
'widgets',
fieldIdP,
val.type,
value,
null,
);
};
func.runtime.widgets.get_fields_data = async function (context, fields, props) {
var data_obj = {};
var return_code = 1;
for await (const [key, val] of Object.entries(fields || {})) {
data_obj[key] = await func.runtime.widgets.get_property_value(context, key, val, props);
if (!data_obj[key] && val.mandatory) {
return_code = -1;
func.runtime.widgets.report_error(context, `${key} is a mandatory field.`);
break;
}
}
for await (const key of ['xu-bind']) {
data_obj[key] = await func.runtime.widgets.get_property_value(context, key, props?.[key], props);
}
return { code: return_code, data: data_obj };
};
func.runtime.widgets.get_resource_candidates = function (context, resource) {
return func.runtime.resources.get_plugin_resource_candidates(context._session, context.plugin, resource);
};
func.runtime.widgets.normalize_capabilities = function (definition) {
const capabilities = definition?.capabilities || {};
return {
browser: capabilities.browser !== false,
headless: capabilities.headless === true,
};
};
func.runtime.widgets.supports_current_environment = function (definition) {
const capabilities = func.runtime.widgets.normalize_capabilities(definition);
if (func.runtime.platform.has_document()) {
return capabilities.browser !== false;
}
return !!capabilities.headless;
};
func.runtime.widgets.get_resource_path = function (context, resource) {
const relative_path = func.runtime.widgets.get_resource_candidates(context, resource)[0] || resource;
const server_origin = typeof globalThis !== 'undefined' ? globalThis.__XU_SERVER_ORIGIN__ : '';
if (server_origin) {
return `${server_origin}/plugins/${context.plugin_name}/${relative_path}?gtp_token=${context._session.gtp_token}&app_id=${context._session.app_id}`;
}
if (context._session.worker_type === 'Dev') {
return `../../plugins/${context.plugin_name}/${relative_path}`;
}
return `https://${context._session.domain}/plugins/${context.plugin_name}/${relative_path}?gtp_token=${context._session.gtp_token}&app_id=${context._session.app_id}`;
};
func.runtime.widgets.load_css_style = function (context) {
func.utils.load_css_on_demand(func.runtime.widgets.get_resource_path(context, 'style.css'));
return true;
};
func.runtime.widgets.get_resource = async function (context, resource) {
const candidates = func.runtime.widgets.get_resource_candidates(context, resource);
let last_error = null;
for (let index = 0; index < candidates.length; index++) {
const candidate = candidates[index];
try {
return await func.utils.get_plugin_resource(context.SESSION_ID, context.plugin_name, candidate);
} catch (error) {
last_error = error;
}
}
throw last_error || new Error(`widget resource not found: ${context.plugin_name}/${resource}`);
};
func.runtime.widgets.get_definition = async function (context) {
return await func.runtime.widgets.get_resource(context, 'index.mjs');
};
func.runtime.widgets.get_methods = async function (context) {
const index = await func.runtime.widgets.get_definition(context);
return index?.methods || {};
};
func.runtime.widgets.load_runtime_css = async function (context) {
if (!context.plugin?.manifest?.['runtime.mjs']?.dist || !context.plugin?.manifest?.['runtime.mjs']?.css) {
return false;
}
const plugin_runtime_css_url = await func.utils.get_plugin_npm_cdn(context.SESSION_ID, context.plugin_name, 'dist/runtime.css');
func.utils.load_css_on_demand(plugin_runtime_css_url);
return true;
};
func.runtime.widgets.build_params = function (context, container_node, container_data, plugin_setup, api_utils, extra = {}) {
return {
SESSION_ID: context.SESSION_ID,
method: context.method,
_session: context._session,
dsP: context.dsP,
sourceP: context.sourceP,
propsP: context.propsP,
plugin_name: context.plugin_name,
container_node,
container_data,
plugin_setup,
report_error: function (descP, warn) {
return func.runtime.widgets.report_error(context, descP, warn);
},
log_error: function (descP, warn) {
return func.runtime.widgets.report_error(context, descP, warn);
},
call_plugin_api: async function (plugin_nameP, dataP) {
return await func.utils.call_plugin_api(context.SESSION_ID, plugin_nameP, dataP);
},
set_SYS_GLOBAL_OBJ_WIDGET_INFO: async function (docP) {
return await func.utils.set_SYS_GLOBAL_OBJ_WIDGET_INFO(context.SESSION_ID, docP);
},
run_widgetCallbackEvent: async function () {
const event_id = context.propsP?.widgetCallbackEvent;
if (!event_id || !api_utils?.invoke_event) {
return false;
}
return await api_utils.invoke_event(event_id);
},
api_utils,
...extra,
};
};
func.common.find_item_by_key = function (arr, key, val) {
return arr.find(function (e) {
return e.data[key] === val;
});
};
func.common.find_item_by_key_root = function (arr, key, val) {
return arr.find(function (e) {
return e[key] === val;
});
};
func.common.find_ROWID_idx = function (_ds, rowId) {
if (!_ds?.data_feed?.rows) {
throw new Error('data_feed not found');
}
// Find the index of the object with the given _ROWID
const index = _ds.data_feed.rows.findIndex((item) => item._ROWID === rowId);
// }
// If the index is -1, the ROWID was not found, so throw an error
if (index === -1) {
throw new Error(`ROWID "${rowId}" not found`);
}
// Return the found index
return index;
};
func.common.input_mask = async function (actionP, valP, typeP, maskP, elemP, grid_objP, grid_row_idP, grid_col_idP, dsSessionP) {
const module = await func.common.get_module(SESSION_ID, 'xuda-input-musk-utils-module.mjs');
module.input_mask(actionP, valP, typeP, maskP, elemP, grid_objP, grid_row_idP, grid_col_idP, dsSessionP);
};
glb.FUNCTION_NODES_ARR = ['batch', 'get_data', 'set_data', 'alert', 'javascript', 'api'];
glb.ALL_MENU_TYPE = ['globals', 'ai_agent', 'component', ...glb.FUNCTION_NODES_ARR];
glb.emailRegex = /^[\w\.-]+@[a-zA-Z\d\.-]+\.[a-zA-Z]{2,}$/;
const FIREBASE_AUTH_PROPERTIES_ARR = ['provider', 'token', 'first_name', 'last_name', 'email', 'user_id', 'picture', 'verified_email', 'locale', 'error_code', 'error_msg'];
const CLIENT_INFO_PROPERTIES_ARR = [
'fingerprint',
'device',
'user_agent',
'browser_version',
'browser_name',
'engine_version',
'engine_name',
'client_ip',
'os_name',
'os_version',
'device_model',
'device_vendor',
'device_type',
'screen_current_resolution_x',
'screen_current_resolution_y',
'screen_available_resolution_x',
'screen_available_resolution_y',
'language',
'time_zone',
'cpu_architecture',
'uuid',
'cursor_pos_x',
'cursor_pos_y',
];
const APP_PROPERTIES_ARR = ['build', 'author', 'date', 'name'];
const DATASOURCE_PROPERTIES_ARR = ['rows', 'type', 'first_row_id', 'last_row_id', 'query_from_segments_json', 'query_to_segments_json', 'locate_query_from_segments_json', 'locate_query_to_segments_json', 'first_row_segments_json', 'last_row_segments_json', 'rowid_snapshot', 'rowid'];
glb.MOBILE_ARR = ['component', 'web_app', 'ios_app', 'android_app', 'electron_app', 'osx_app', 'windows_app'];
glb.SYS_DATE_ARR = ['SYS_DATE', 'SYS_DATE_TIME', 'SYS_DATE_VALUE', 'SYS_DATE_WEEK_YEAR', 'SYS_DATE_MONTH_YEAR', 'SYS_TIME_SHORT', 'SYS_TIME'];
glb.API_OUTPUT_ARR = ['json', 'html', 'xml', 'text', 'css', 'javascript'];
const PROTECTED_NAMES_ARR = ['THIS', 'ROWID']; //tbd
func.common.db = async function (SESSION_ID, serviceP, dataP, opt = {}, dsSession) {
return new Promise(async function (resolve, reject) {
var _session = SESSION_OBJ[SESSION_ID];
const app_id = _session.app_id;
if (glb.DEBUG_MODE) {
console.info('request', dataP);
}
var data = {
app_id: app_id,
fingerprint: _session?.SYS_GLOBAL_OBJ_CLIENT_INFO?.fingerprint,
debug: glb.DEBUG_MODE,
session_id: SESSION_ID,
gtp_token: _session.gtp_token,
app_token: _session.app_token,
res_token: _session.res_token,
engine_mode: _session.engine_mode,
req_id: 'rt_req_' + crypto.randomUUID(),
app_replicate: APP_OBJ[app_id].app_replicate,
};
try {
if (typeof firebase !== 'undefined' && firebase?.auth()?.currentUser?.displayName) {
data.device_name = firebase.auth().currentUser.displayName;
}
} catch (error) {}
for (const [key, val] of Object.entries(dataP)) {
data[key] = val;
}
const success_callback = function (ret) {
if (dataP.table_id && DOCS_OBJ[app_id][dataP.table_id]) {
func.utils.debug.watch(SESSION_ID, dataP.table_id, 'table', DOCS_OBJ[app_id][dataP.table_id].properties.menuName, {
req: data,
res: ret,
});
}
if (glb.DEBUG_MODE) {
console.info('response', ret);
}
resolve(ret, true);
};
const error_callback = function (err) {
reject(err);
};
function cleanString(json) {
let str = JSON.stringify(json);
// Replace all non-alphanumeric characters with an empty string
return str.replace(/[^a-zA-Z0-9]/g, '');
}
const get_rep_id = function () {
let _data = {};
const fields_to_skip = ['fields', 'viewSourceDesc', 'skip', 'limit', 'count', 'reduce', 'prog_id', 'sortModel', 'filterModelMongo', 'filterModelSql', 'filterModelUserMongo', 'filterModelUserSql'];
for (let [key, val] of Object.entries(dataP)) {
if (typeof val !== 'undefined' && val !== null && !fields_to_skip.includes(key)) {
_data[key] = val;
}
}
return cleanString(_data);
};
const validate_existence_of_whole_table_request = async function (db) {
let table_req_id;
try {
table_req_id = cleanString({
key: data.table_id,
table_id: data.table_id,
});
const doc = await db.get(table_req_id);
let ret = await db.find({
selector: {
docType: 'rep_request',
table_id: data.table_id,
},
});
if (doc.stat < 3) {
throw 'not ready';
}
/// delete table refunded requests
for (let doc of ret.docs) {
if (doc.entire_table) continue;
func.db.pouch.remove_db_replication_from_server(SESSION_ID, doc._id);
}
return { code: 1, data: table_req_id };
} catch (err) {
return { code: -1, data: table_req_id };
}
};
const upsert_rep_request_from_remote_response = async function (db, rep_id, table_req_id, json) {
if (!json?.data?.opt) return;
try {
let existing_doc;
try {
existing_doc = await db.get(rep_id);
} catch (err) {}
const rep_doc = {
_id: rep_id,
selector: json.data.opt.selector,
stat: 1,
ts: Date.now(),
docType: 'rep_request',
table_id: dataP.table_id,
prog_id: dataP.prog_id,
entire_table: table_req_id === rep_id,
source: 'runtime',
e: data,
};
if (existing_doc?._rev) {
rep_doc._rev = existing_doc._rev;
}
await db.put(rep_doc);
func.db.pouch.set_db_replication_from_server(SESSION_ID);
} catch (err) {}
};
const read_remote_dbs = async function (db, rep_id, table_req_id) {
const json = await func.common.perform_rpi_request(SESSION_ID, serviceP, opt, data);
await upsert_rep_request_from_remote_response(db, rep_id, table_req_id, json);
return json;
};
const should_retry_live_preview_remote_read = function (json) {
return (
_session?.engine_mode === 'live_preview' &&
serviceP === 'dbs_read' &&
dataP.table_id &&
!dataP.count &&
!dataP.reduce &&
Array.isArray(json?.data?.rows) &&
!json.data.rows.length
);
};
const read_local_dbs_with_live_preview_fallback = async function (db, rep_id, table_req_id) {
const json = {
code: 1,
data: await func.db.pouch[serviceP](SESSION_ID, data),
};
if (should_retry_live_preview_remote_read(json)) {
return await read_remote_dbs(db, rep_id, table_req_id);
}
return json;
};
const read_dbs_pouch = async function (db) {
if (_session?.DS_GLB?.[dsSession]?.refreshed && (dataP.filterModelMongo || dataP.filterModelSql)) {
return await read_local_dbs_with_live_preview_fallback(db, get_rep_id(), null);
}
const rep_id = get_rep_id();
const { code: table_req_code, data: table_req_id } = await validate_existence_of_whole_table_request(db);
if (table_req_code > 0) {
return await read_local_dbs_with_live_preview_fallback(db, rep_id, table_req_id);
}
try {
const doc = await db.get(rep_id);
if (doc.stat < 3) throw 'replication not ready';
return await read_local_dbs_with_live_preview_fallback(db, rep_id, table_req_id);
} catch (err) {
return await read_remote_dbs(db, rep_id, table_req_id);
}
};
const update_dbs_pouch = async function (db) {
try {
// if (_session.DS_GLB[0].data_system.SYS_GLOBAL_BOL_ONLINE) {
// throw "online";
// }
const { code: table_req_code, data: table_req_id } = await validate_existence_of_whole_table_request(db);
if (table_req_code > 0) {
data.full_table_downloaded = true;
}
await db.get(dataP.row_id);
return await func.db.pouch[serviceP](SESSION_ID, data);
} catch (err) {
return await func.common.perform_rpi_request(SESSION_ID, serviceP, opt, data);
}
};
const create_dbs_pouch = async function (db) {
try {
const { code: table_req_code, data: table_req_id } = await validate_existence_of_whole_table_request(db);
if (table_req_code > 0) {
data.full_table_downloaded = true;
}
return await func.db.pouch[serviceP](SESSION_ID, data);
} catch (err) {
return await func.common.perform_rpi_request(SESSION_ID, serviceP, opt, data);
}
};
const delete_dbs_pouch = async function (db) {
for await (let row_id of dataP.ids || []) {
try {
const { code: table_req_code, data: table_req_id } = await validate_existence_of_whole_table_request(db);
if (table_req_code > 0) {
data.full_table_downloaded = true;
}
await db.get(row_id);
let _data = structuredClone(dataP);
_data.ids = [row_id];
return await func.db.pouch['dbs_delete'](SESSION_ID, _data);
} catch (err) {
return await func.common.perform_rpi_request(SESSION_ID, serviceP, opt, data);
}
}
};
if (typeof IS_DOCKER === 'undefined' && typeof IS_PROCESS_SERVER === 'undefined') {
try {
if (!SESSION_OBJ?.[SESSION_ID]?.rpi_http_methods?.includes(serviceP)) {
throw '';
}
const is_local_draft_pouch_runtime =
['miniapp', 'live_preview'].includes(_session?.engine_mode) &&
_session?.is_draft_runtime &&
Array.isArray(_session?.rpi_http_methods) &&
_session.rpi_http_methods.includes('dbs_read');
if (is_local_draft_pouch_runtime && ['dbs_read', 'dbs_update', 'dbs_create', 'dbs_delete'].includes(serviceP)) {
return success_callback({
code: 1,
data: await func.db.pouch[serviceP](SESSION_ID, data),
});
}
if (!(await func?.db?.pouch?.get_replication_stat(SESSION_ID))) throw '';
const db = await func.utils.connect_pouchdb(SESSION_ID);
if (_session?.engine_mode === 'live_preview' && !_session?.is_draft_runtime && ['dbs_update', 'dbs_create', 'dbs_delete'].includes(serviceP)) {
const json = await func.common.perform_rpi_request(SESSION_ID, serviceP, opt, data);
return success_callback(json, true);
}
switch (serviceP) {
case 'dbs_read': {
try {
return success_callback(await read_dbs_pouch(db));
} catch (err) {
if (err === 'creating index in progress') {
throw '';
}
return error_callback(err);
}
break;
}
case 'dbs_update': {
try {
const ret = {
code: 1,
data: await update_dbs_pouch(db),
};
return success_callback(ret);
} catch (err) {
return error_callback(err);
}
break;
}
case 'dbs_create': {
try {
const ret = {
code: 1,
data: await create_dbs_pouch(db),
};
return success_callback(ret);
} catch (err) {
return error_callback(err);
}
break;
}
case 'dbs_delete': {
try {
const ret = {
code: 1,
data: await delete_dbs_pouch(db),
};
return success_callback(ret);
} catch (err) {
return error_callback(err);
}
break;
}
default:
throw '';
break;
}
} catch (err) {
try {
const json = await func.common.perform_rpi_request(SESSION_ID, serviceP, opt, data);
return success_callback(json, true);
} catch (err) {
return error_callback(err);
}
}
}
// DOCKER // PROCESS_SERVER
const response = function (res, ret) {
if (ret.code < 0) {
return error_callback(ret);
}
success_callback(ret);
};
const get_white_spaced_data = function (data) {
var e = {};
for (const [key, val] of Object.entries(data)) {
if (!val) {
if (typeof val === 'boolean') {
e[key] = 'false';
} else {
e[key] = '';
}
} else {
if (typeof val === 'boolean') {
e[key] = 'true';
} else {
e[key] = val;
}
}
}
if (data.fields && !data.fields.length) {
e.fields = '';
}
return e;
};
if (dataP.table_id) {
await func.utils.FILES_OBJ.get(SESSION_ID, dataP.table_id);
await func.utils.TREE_OBJ.get(SESSION_ID, dataP.table_id);
}
data.db_driver = 'xuda';
__.rpi.http_calls(serviceP, { body: get_white_spaced_data(data) }, null, response);
});
};
func.common.getJsonFromUrl = function () {
return func.runtime.env.get_url_params();
};
func.common.getParametersFromUrl = function () {
return func.runtime.env.get_url_parameters_object();
};
func.common.getObjectFromUrl = function (url, element_attributes_obj, embed_params_obj) {
var result = {};
if (element_attributes_obj) {
for (let [key, val] of Object.entries(element_attributes_obj)) {
result[key] = val;
}
}
if (embed_params_obj) {
for (let [key, val] of Object.entries(embed_params_obj)) {
result[key] = val;
}
}
if (!url && typeof IS_DOCKER === 'undefined' && typeof IS_PROCESS_SERVER === 'undefined') {
url = location.href;
}
var question = url.indexOf('?');
var hash = url.indexOf('#');
if (hash == -1 && question == -1) return result;
if (hash == -1) hash = url.length;
var query = question == -1 || hash == question + 1 ? url.substring(hash) : url.substring(question + 1, hash);
// var result = {};
query.split('&').forEach(function (part) {
if (!part) return;
part = part.split('+').join(' '); // replace every + with space, regexp-free version
var eq = part.indexOf('=');
var key = eq > -1 ? part.substr(0, eq) : part;
var val = eq > -1 ? decodeURIComponent(part.substr(eq + 1)) : '';
var from = key.indexOf('[');
if (from == -1) {
result[decodeURIComponent(key)] = val;
} else {
var to = key.indexOf(']', from);
var index = decodeURIComponent(key.substring(from + 1, to));
key = decodeURIComponent(key.substring(0, from));
if (!result[key]) result[key] = [];
if (!index) result[key].push(val);
else result[key][index] = val;
}
});
return result;
};
func.common.getContrast_color = function (hexcolor) {
function colourNameToHex(colour) {
var colours = {
aliceblue: '#f0f8ff',
antiquewhite: '#faebd7',
aqua: '#00ffff',
aquamarine: '#7fffd4',
azure: '#f0ffff',
beige: '#f5f5dc',
bisque: '#ffe4c4',
black: '#000000',
blanchedalmond: '#ffebcd',
blue: '#0000ff',
blueviolet: '#8a2be2',
brown: '#a52a2a',
burlywood: '#deb887',
cadetblue: '#5f9ea0',
chartreuse: '#7fff00',
chocolate: '#d2691e',
coral: '#ff7f50',
cornflowerblue: '#6495ed',
cornsilk: '#fff8dc',
crimson: '#dc143c',
cyan: '#00ffff',
darkblue: '#00008b',
darkcyan: '#008b8b',
darkgoldenrod: '#b8860b',
darkgray: '#a9a9a9',
darkgreen: '#006400',
darkkhaki: '#bdb76b',
darkmagenta: '#8b008b',
darkolivegreen: '#556b2f',
darkorange: '#ff8c00',
darkorchid: '#9932cc',
darkred: '#8b0000',
darksalmon: '#e9967a',
darkseagreen: '#8fbc8f',
darkslateblue: '#483d8b',
darkslategray: '#2f4f4f',
darkturquoise: '#00ced1',
darkviolet: '#9400d3',
deeppink: '#ff1493',
deepskyblue: '#00bfff',
dimgray: '#696969',
dodgerblue: '#1e90ff',
firebrick: '#b22222',
floralwhite: '#fffaf0',
forestgreen: '#228b22',
fuchsia: '#ff00ff',
gainsboro: '#dcdcdc',
ghostwhite: '#f8f8ff',
gold: '#ffd700',
goldenrod: '#daa520',
gray: '#808080',
green: '#008000',
greenyellow: '#adff2f',
honeydew: '#f0fff0',
hotpink: '#ff69b4',
'indianred ': '#cd5c5c',
indigo: '#4b0082',
ivory: '#fffff0',
khaki: '#f0e68c',
lavender: '#e6e6fa',
lavenderblush: '#fff0f5',
lawngreen: '#7cfc00',
lemonchiffon: '#fffacd',
lightblue: '#add8e6',
lightcoral: '#f08080',
lightcyan: '#e0ffff',
lightgoldenrodyellow: '#fafad2',
lightgrey: '#d3d3d3',
lightgreen: '#90ee90',
lightpink: '#ffb6c1',
lightsalmon: '#ffa07a',
lightseagreen: '#20b2aa',
lightskyblue: '#87cefa',
lightslategray: '#778899',
lightsteelblue: '#b0c4de',
lightyellow: '#ffffe0',
lime: '#00ff00',
limegreen: '#32cd32',
linen: '#faf0e6',
magenta: '#ff00ff',
maroon: '#800000',
mediumaquamarine: '#66cdaa',
mediumblue: '#0000cd',
mediumorchid: '#ba55d3',
mediumpurple: '#9370d8',
mediumseagreen: '#3cb371',
mediumslateblue: '#7b68ee',
mediumspringgreen: '#00fa9a',
mediumturquoise: '#48d1cc',
mediumvioletred: '#c71585',
midnightblue: '#191970',
mintcream: '#f5fffa',
mistyrose: '#ffe4e1',
moccasin: '#ffe4b5',
navajowhite: '#ffdead',
navy: '#000080',
oldlace: '#fdf5e6',
olive: '#808000',
olivedrab: '#6b8e23',
orange: '#ffa500',
orangered: '#ff4500',
orchid: '#da70d6',
palegoldenrod: '#eee8aa',
palegreen: '#98fb98',
paleturquoise: '#afeeee',
palevioletred: '#d87093',
papayawhip: '#ffefd5',
peachpuff: '#ffdab9',
peru: '#cd853f',
pink: '#ffc0cb',
plum: '#dda0dd',
powderblue: '#b0e0e6',
purple: '#800080',
rebeccapurple: '#663399',
red: '#ff0000',
rosybrown: '#bc8f8f',
royalblue: '#4169e1',
saddlebrown: '#8b4513',
salmon: '#fa8072',
sandybrown: '#f4a460',
seagreen: '#2e8b57',
seashell: '#fff5ee',
sienna: '#a0522d',
silver: '#c0c0c0',
skyblue: '#87ceeb',
slateblue: '#6a5acd',
slategray: '#708090',
snow: '#fffafa',
springgreen: '#00ff7f',
steelblue: '#4682b4',
tan: '#d2b48c',
teal: '#008080',
thistle: '#d8bfd8',
tomato: '#ff6347',
turquoise: '#40e0d0',
violet: '#ee82ee',
wheat: '#f5deb3',
white: '#ffffff',
whitesmoke: '#f5f5f5',
yellow: '#ffff00',
yellowgreen: '#9acd32',
};
if (typeof colours[colour.toLowerCase()] != 'undefined') return colours[colour.toLowerCase()];
return false;
}
if (!hexcolor.includes('#')) {
hexcolor = colourNameToHex(hexcolor);
}
// If a leading # is provided, remove it
if (hexcolor.slice(0, 1) === '#') {
hexcolor = hexcolor.slice(1);
}
// Convert to RGB value
var r = Number(hexcolor.substr(0, 2), 16);
var g = Number(hexcolor.substr(2, 2), 16);
var b = Number(hexcolor.substr(4, 2), 16);
// Get YIQ ratio
var yiq = (r * 299 + g * 587 + b * 114) / 1000;
// Check contrast
return yiq >= 128 ? 'black' : 'white';
};
func.common.get_url = function (SESSION_ID, method, path) {
const _session = SESSION_OBJ[SESSION_ID] || {};
const origin =
((typeof globalThis !== 'undefined' && globalThis.__XU_SERVER_ORIGIN__)) ||
(_session.domain ? `https://${_session.domain}` : '');
if (!origin) {
return `/${method}${path ? '/' + path : '/'}`;
}
return `${origin}/${method}${path ? '/' + path : '/'}`;
};
var UI_FRAMEWORK_INSTALLED = null;
var UI_FRAMEWORK_PLUGIN = {};
func.common.get_cast_val = async function (SESSION_ID, source, attributeP, typeP, valP, errorP) {
const report_conversion_error = function (res) {
if (errorP) {
return func.utils.debug_report(SESSION_ID, source.charAt(0).toUpperCase() + source.slice(1).toLowerCase(), errorP, 'W');
}
var msg = `error converting ${attributeP} from ${valP} to ${typeP}`;
func.utils.debug_report(SESSION_ID, source.charAt(0).toUpperCase() + source.slice(1).toLowerCase(), msg, 'E');
};
const report_conversion_warn = function (msg) {
// number/boolean/bigint -> string is a lossless coercion (String(v) is always exact); don't surface
// it as a runtime warning — it routes through report_issue and shows as an "Unhandled Runtime Error".
if (typeP === 'string' && (typeof valP === 'number' || typeof valP === 'boolean' || typeof valP === 'bigint')) return;
var msg = `type mismatch auto conversion made to ${attributeP} from value ${valP} to ${typeP}`;
func.utils.debug_report(SESSION_ID, source.charAt(0).toUpperCase() + source.slice(1).toLowerCase(), msg, 'W');
};
const module = await func.common.get_module(SESSION_ID, `xuda-get-cast-util-module.mjs`);
return module.cast(typeP, valP, report_conversion_error, report_conversion_warn);
};
var WEB_WORKER = {};
var WEB_WORKER_CALLBACK_QUEUE = {};
glb.DEBUG_MODE = null;
var DS_UI_EVENTS_GLB = {};
var RUNTIME_SERVER_WEBSOCKET = null;
var RUNTIME_SERVER_WEBSOCKET_CONNECTED = null;
var WEBSOCKET_PROCESS_PID = null;
glb.worker_queue_num = 0;
glb.websocket_queue_num = 0;
func.common._import_cache = func.common._import_cache || {};
func.common.get_module = async function (SESSION_ID, module, paramsP = {}) {
let ret;
const get_ret = async function (src) {
// Cache the import() result to avoid repeated dynamic imports
if (!func.common._import_cache[src]) {
func.common._import_cache[src] = await import(src);
}
const module_ret = func.common._import_cache[src];
var params = get_params();
const ret = module_ret.XudaModule ? new module_ret.XudaModule(params) : await invoke_init_module(module_ret, params);
return ret;
};
const get_params = function () {
let params = {
glb,
func,
APP_OBJ,
SESSION_ID,
PROJECT_OBJ,
DOCS_OBJ,
SESSION_OBJ,
...paramsP,
};
if (typeof IS_PROCESS_SERVER !== 'undefined') params.IS_PROCESS_SERVER = IS_PROCESS_SERVER;
if (typeof IS_API_SERVER !== 'undefined') params.IS_API_SERVER = IS_API_SERVER;
if (typeof IS_DOCKER !== 'undefined') params.IS_DOCKER = IS_DOCKER;
return params;
};
const invoke_init_module = async function (module_ret, params) {
if (!module_ret.init_module) return module_ret;
await module_ret.init_module(params);
return module_ret;
};
const _session = SESSION_OBJ[SESSION_ID];
const append_ts = function (resource_path) {
const is_debug_live_runtime = ['Dev', 'Debug'].includes(_session?.worker_type) && ['live_preview', 'miniapp'].includes(_session?.engine_mode);
let local_runtime_cache_tag =
typeof globalThis !== 'undefined'
? globalThis.__XU_RUNTIME_MODULE_CACHE_TAG__ || globalThis.__XU_SERVER_BOOTSTRAP__?.version
: 0;
if (is_debug_live_runtime && typeof globalThis !== 'undefined') {
globalThis.__XU_RUNTIME_MODULE_CACHE_TAG__ = globalThis.__XU_RUNTIME_MODULE_CACHE_TAG__ || Date.now();
local_runtime_cache_tag = globalThis.__XU_RUNTIME_MODULE_CACHE_TAG__;
}
const cache_tag =
local_runtime_cache_tag ||
_session?.build_info?.runtime_ts ||
_session?.build_info?.last_changed_ts ||
_session?.build_info?.server_ts ||
_session?.opt?.app_build_id ||
0;
if (!cache_tag) {
return resource_path;
}
return `${resource_path}${resource_path.includes('?') ? '&' : '?'}ts=${cache_tag}`;
};
if (_session.worker_type === 'Dev') {
ret = await get_ret(append_ts('./modules/' + module));
return ret;
}
if (_session.worker_type === 'Debug') {
if (typeof IS_DOCKER !== 'undefined' || typeof IS_PROCESS_SERVER !== 'undefined') {
ret = await get_ret(func.utils.get_resource_filename(['live_preview', 'miniapp'].includes(_session.engine_mode) ? '' : _session?.opt?.app_build_id, `${_conf.xuda_home}root/dist/runtime/js/modules/` + module));
} else {
ret = await get_ret(
append_ts(
func.common.get_url(
SESSION_ID,
'dist',
func.utils.get_resource_filename(['live_preview', 'miniapp'].includes(_session.engine_mode) ? '' : _session?.opt?.app_build_id, 'runtime/js/modules/' + module),
),
),
);
}
return ret;
}
const rep = function () {
return module.endsWith('.js') ? module.replace('.js', '.min.js') : module.replace('.mjs', '.min.mjs');
};
if (typeof IS_DOCKER !== 'undefined' || typeof IS_PROCESS_SERVER !== 'undefined') {
ret = await get_ret(func.utils.get_resource_filename(['live_preview', 'miniapp'].includes(_session.engine_mode) ? '' : _session?.opt?.app_build_id, `${_conf.xuda_home}root/dist/runtime/js/modules/` + rep()));
} else {
ret = await get_ret(
append_ts(
func.common.get_url(
SESSION_ID,
'dist',
func.utils.get_resource_filename(['live_preview', 'miniapp'].includes(_session.engine_mode) ? '' : _session?.opt?.app_build_id, 'runtime/js/modules/' + rep()),
),
),
);
}
return ret;
};
func.api = {};
func.api.set_field_value = async function (field_id, value, avoid_refresh) {
const SESSION_ID = Object.keys(SESSION_OBJ)[0];
const api_utils = await func.common.get_module(SESSION_ID, 'xuda-api-library.mjs', {
func,
glb,
SESSION_OBJ,
SESSION_ID,
APP_OBJ,
dsSession: func.utils.get_last_datasource_no(SESSION_ID),
});
return await api_utils.set_field_value(field_id, value, avoid_refresh);
};
func.api.get_field_value = async function (field_id) {
const SESSION_ID = Object.keys(SESSION_OBJ)[0];
const api_utils = await func.common.get_module(SESSION_ID, 'xuda-api-library.mjs', {
func,
glb,
SESSION_OBJ,
SESSION_ID,
APP_OBJ,
dsSession: func.utils.get_last_datasource_no(SESSION_ID),
});
return await api_utils.get_field_value(field_id);
};
func.api.invoke_event = async function (event_id, options) {
const SESSION_ID = Object.keys(SESSION_OBJ)[0];
const api_utils = await func.common.get_module(SESSION_ID, 'xuda-api-library.mjs', {
func,
glb,
SESSION_OBJ,
SESSION_ID,
APP_OBJ,
dsSession: func.utils.get_last_datasource_no(SESSION_ID),
});
return await api_utils.invoke_event(event_id, options);
};
func.api.call_project_api = async function (prog_id, params) {
const SESSION_ID = Object.keys(SESSION_OBJ)[0];
const api_utils = await func.common.get_module(SESSION_ID, 'xuda-api-library.mjs', {
func,
glb,
SESSION_OBJ,
SESSION_ID,
APP_OBJ,
dsSession: func.utils.get_last_datasource_no(SESSION_ID),
});
return await api_utils.call_project_api(prog_id, params, null);
};
func.api.call_system_api = async function (api_method, payload) {
const SESSION_ID = Object.keys(SESSION_OBJ)[0];
const api_utils = await func.common.get_module(SESSION_ID, 'xuda-api-library.mjs', {
func,
glb,
SESSION_OBJ,
SESSION_ID,
APP_OBJ,
dsSession: func.utils.get_last_datasource_no(SESSION_ID),
});
return await api_utils.call_system_api(api_method, payload, null);
};
func.api.dbs_create = async function (table_id, data, cb) {
const SESSION_ID = Object.keys(SESSION_OBJ)[0];
const api_utils = await func.common.get_module(SESSION_ID, 'xuda-api-library.mjs', {
func,
glb,
SESSION_OBJ,
SESSION_ID,
APP_OBJ,
dsSession: func.utils.get_last_datasource_no(SESSION_ID),
});
return await api_utils.dbs_create(table_id, row_id, data, cb);
};
func.api.dbs_read = async function (table_id, selector, fields, sort, limit, skip, cb) {
const SESSION_ID = Object.keys(SESSION_OBJ)[0];
const api_utils = await func.common.get_module(SESSION_ID, 'xuda-api-library.mjs', {
func,
glb,
SESSION_OBJ,
SESSION_ID,
APP_OBJ,
dsSession: func.utils.get_last_datasource_no(SESSION_ID),
});
return await api_utils.dbs_read(table_id, selector, fields, sort, limit, skip, cb);
};
func.api.dbs_update = async function (table_id, row_id, data, cb) {
const SESSION_ID = Object.keys(SESSION_OBJ)[0];
const api_utils = await func.common.get_module(SESSION_ID, 'xuda-api-library.mjs', {
func,
glb,
SESSION_OBJ,
SESSION_ID,
APP_OBJ,
dsSession: func.utils.get_last_datasource_no(SESSION_ID),
});
return await api_utils.dbs_update(table_id, row_id, data, cb);
};
func.api.dbs_delete = async function (table_id, row_id, cb) {
const SESSION_ID = Object.keys(SESSION_OBJ)[0];
const api_utils = await func.common.get_module(SESSION_ID, 'xuda-api-library.mjs', {
func,
glb,
SESSION_OBJ,
SESSION_ID,
APP_OBJ,
dsSession: func.utils.get_last_datasource_no(SESSION_ID),
});
return await api_utils.dbs_delete(table_id, row_id, cb);
};
func.api.call_javascript = async function (prog_id, params, evaluate) {
const SESSION_ID = Object.keys(SESSION_OBJ)[0];
const api_utils = await func.common.get_module(SESSION_ID, 'xuda-api-library.mjs', {
func,
glb,
SESSION_OBJ,
SESSION_ID,
APP_OBJ,
dsSession: func.utils.get_last_datasource_no(SESSION_ID),
});
return await api_utils.call_javascript(prog_id, params, evaluate);
};
func.api.watch = function (path, cb, opt = {}) {
if (!path) return 'path is mandatory';
if (!cb) return 'cb (callback function) is mandatory';
const SESSION_ID = Object.keys(SESSION_OBJ)[0];
let _session = SESSION_OBJ[SESSION_ID];
if (!_session.watchers) {
_session.watchers = {};
}
_session.watchers[path] = { ...opt, handler: cb };
if (opt.immediate) {
const value = xu_get(SESSION_OBJ[SESSION_ID].DS_GLB[0], path);
cb({ path, newValue: value, oldValue: value, timestamp: Date.now(), opt });
if (opt.once) {
delete _session.watchers[path];
}
}
return 'ok';
};
// func.api.call_javascript = async function (prog_id, params, evaluate) {
// const SESSION_ID = Object.keys(SESSION_OBJ)[0];
// const api_utils = await func.common.get_module(SESSION_ID, 'xuda-api-library.mjs', {
// func,
// glb,
// SESSION_OBJ,
// SESSION_ID,
// APP_OBJ,
// dsSession: func.utils.get_last_datasource_no(SESSION_ID),
// });
// return await api_utils.call_javascript(prog_id, params, evaluate);
// };
glb.rpi_request_queue_num = 0;
func.common.perform_rpi_request = async function (SESSION_ID, serviceP, opt = {}, data) {
var _session = SESSION_OBJ[SESSION_ID];
var _data_system = _session?.DS_GLB?.[0]?.data_system;
const set_ajax = async function (stat) {
var datasource_changes = {
[0]: {
['data_system']: { SYS_GLOBAL_BOL_AJAX_BUSY: stat },
},
};
await func.datasource.update(SESSION_ID, datasource_changes);
};
if (_data_system) {
// _data_system.SYS_GLOBAL_BOL_AJAX_BUSY = 1;
await set_ajax(1);
if (!_data_system.SYS_GLOBAL_BOL_CONNECTED) {
func.utils.alerts.toast(SESSION_ID, 'Server connection error', 'You are not connected to the server, so your request cannot be processed.', 'error');
return { code: 88, data: {} };
}
}
const http = async function () {
const fetchWithTimeout = (url, options = {}, timeout = 600000) => {
// 100 seconds
const controller = new AbortController();
const { signal } = controller;
const timeoutPromise = new Promise((_, reject) =>
setTimeout(() => {
controller.abort();
reject(new Error('Request timed out'));
}, timeout),
);
const fetchPromise = fetch(url, { ...options, signal });
return Promise.race([fetchPromise, timeoutPromise]);
};
var url = func.common.get_url(SESSION_ID, 'rpi', '');
var _session = SESSION_OBJ[SESSION_ID];
const app_id = _session.app_id;
if (APP_OBJ[app_id].is_deployment && _session.rpi_http_methods?.includes(serviceP)) {
const origin =
((typeof globalThis !== 'undefined' && globalThis.__XU_SERVER_ORIGIN__)) ||
(_session.host ? 'https://' + _session.host : '');
url = origin ? origin + '/rpi/' : url;
}
url += serviceP;
try {
const response = await fetchWithTimeout(url, {
method: opt.type ? opt.type : 'POST',
headers: {
Accept: 'application/json',
'Content-Type': 'application/json',
'xu-gtp-token': _session.gtp_token,
'xu-app-token': _session.app_token,
},
body: JSON.stringify(data),
});
if (!response.ok) {
throw response.status;
}
const json = await response.json();
return json;
} catch (err) {
console.error(err);
if (err === 503) {
_this.func.UI.utils.progressScreen.show(SESSION_ID, `Error code ${err}, reloading in 5 sec`);
setTimeout(async () => {
await func.index.delete_pouch(SESSION_ID);
location.reload();
}, 5000);
}
return {};
}
};
try {
if (_session.engine_mode === 'live_preview') {
throw new Error('live_preview');
}
if (_session.engine_mode === 'miniapp') {
throw new Error('miniapp');
}
if (SESSION_OBJ?.[SESSION_ID]?.rpi_http_methods?.includes(serviceP)) {
const ret = await func.common.get_data_from_websocket(SESSION_ID, serviceP, data);
if (_data_system) {
// _data_system.SYS_GLOBAL_BOL_AJAX_BUSY = 0;
await set_ajax(0);
}
return ret;
} else {
throw new Error('method not found in rpi_http_methods');
}
} catch (err) {
const ret = await http();
if (_data_system) {
// _data_system.SYS_GLOBAL_BOL_AJAX_BUSY = 0;
await set_ajax(0);
}
return ret;
}
};
func.common.get_data_from_websocket = async function (SESSION_ID, serviceP, data) {
var _session = SESSION_OBJ[SESSION_ID];
return new Promise(function (resolve, reject) {
const dbs_calls = function () {
glb.websocket_queue_num++;
const obj = {
service: serviceP,
data,
websocket_queue_num: glb.websocket_queue_num,
};
if (glb.IS_WORKER) {
func.utils.post_back_to_client(SESSION_ID, 'get_dbs_data_from_websocket', _session.worker_id, obj);
self.addEventListener('get_ws_data_worker_' + glb.websocket_queue_num, (event) => {
resolve(event.detail.data);
});
// throw new Error("not ready yet");
} else {
if (RUNTIME_SERVER_WEBSOCKET && RUNTIME_SERVER_WEBSOCKET_CONNECTED) {
RUNTIME_SERVER_WEBSOCKET.emit('message', obj);
const _ws_event = 'get_ws_data_response_' + glb.websocket_queue_num;
const _ws_handler = function (data) {
resolve(data.data);
func.runtime.platform.off('get_ws_data_response_' + data.e.websocket_queue_num, _ws_handler);
};
func.runtime.platform.on(_ws_event, _ws_handler);
} else {
throw new Error('fail to fetch from ws websocket inactive');
}
}
};
const heartbeat = function () {
const obj = {
service: 'heartbeat',
data,
};
if (RUNTIME_SERVER_WEBSOCKET && RUNTIME_SERVER_WEBSOCKET_CONNECTED) {
RUNTIME_SERVER_WEBSOCKET.emit('message', obj);
const _hb_handler = function (data) {
resolve(data.data);
func.runtime.platform.off('heartbeat_response', _hb_handler);
};
func.runtime.platform.on('heartbeat_response', _hb_handler);
} else {
throw new Error('fail to fetch from ws websocket inactive');
}
};
if (serviceP === 'heartbeat') {
return heartbeat();
}
dbs_calls();
});
};
// func.common.sha256 = async function (inputString) {
// // 1. Create a hash buffer from the input string using SHA-256.
// // This part remains the same as it provides a strong, unique cryptographic starting point.
// const buffer = await crypto.subtle.digest('SHA-256', new TextEncoder().encode(inputString));
// // 2. Interpret the first 8 bytes (64 bits) of the hash as one big number.
// const view = new DataView(buffer);
// const bigInt = view.getBigUint64(0, false); // `false` for big-endian
// // 3. Convert the BigInt to a Base36 string.
// // The .toString(36) method handles the conversion to an alphanumeric representation (0-9, a-z).
// const base36Hash = bigInt.toString(36);
// // 4. Take the first 10 characters. If it's shorter, it will just return the whole string.
// // For a 64-bit integer, the Base36 representation will be about 13 characters long,
// // so slicing is a reliable way to get a fixed length.
// const shortHash = base36Hash.slice(0, 10);
// // 5. Pad the start in the unlikely case the hash is shorter than 10 characters.
// // This ensures the output is always exactly 10 characters long.
// return shortHash.padStart(10, '0');
// };
func.common.fastHash = function (inputString) {
let hash = 0x811c9dc5; // FNV offset basis
for (let i = 0; i < inputString.length; i++) {
hash ^= inputString.charCodeAt(i);
// FNV prime multiplication with 32-bit overflow
hash += (hash << 1) + (hash << 4) + (hash << 7) + (hash << 8) + (hash << 24);
}
// Convert to base36 and pad to 10 characters
return ((hash >>> 0).toString(36) + '0000000000').slice(0, 10);
};
glb.new_xu_render = false;
// XU_PERF: opt-in fast paths (shallow render-context copies, drive-ref
// pre-scan, keyed xu-for reuse). Default off = legacy behavior byte-for-byte.
glb.XU_PERF = glb.XU_PERF || false;
func.runtime = func.runtime || {};
func.runtime.ui = func.runtime.ui || {};
func.runtime.render = func.runtime.render || {};
func.runtime.widgets = func.runtime.widgets || {};
// Shared render-tree contract helpers live here so browser and headless runtimes can resolve the same UI structure.
func.runtime.render.TREE_CONTRACT_VERSION = func.runtime.render.TREE_CONTRACT_VERSION || 'xuda.render_tree.v1';
func.runtime.render._tree_widget_capability_cache = func.runtime.render._tree_widget_capability_cache || {};
func.runtime.render.safe_clone_tree_value = function (value) {
if (typeof structuredClone === 'function') {
try {
return structuredClone(value);
} catch (_) {
// Fall through to the recursive clone below.
}
}
if (Array.isArray(value)) {
return value.map(function (item) {
return func.runtime.render.safe_clone_tree_value(item);
});
}
if (value && typeof value === 'object') {
const cloned = {};
const keys = Object.keys(value);
for (let index = 0; index < keys.length; index++) {
const key = keys[index];
cloned[key] = func.runtime.render.safe_clone_tree_value(value[key]);
}
return cloned;
}
return value;
};
func.runtime.render.sort_tree_debug_value = function (value) {
if (Array.isArray(value)) {
return value.map(function (item) {
return func.runtime.render.sort_tree_debug_value(item);
});
}
if (value && typeof value === 'object') {
const sorted = {};
const keys = Object.keys(value).sort();
for (let index = 0; index < keys.length; index++) {
const key = keys[index];
sorted[key] = func.runtime.render.sort_tree_debug_value(value[key]);
}
return sorted;
}
return value;
};
func.runtime.render.is_tree_node = function (nodeP) {
return !!nodeP?.contract && nodeP.contract === func.runtime.render.TREE_CONTRACT_VERSION;
};
func.runtime.render.get_tree_source_node = function (nodeP) {
if (!func.runtime.render.is_tree_node(nodeP)) {
return nodeP || null;
}
return nodeP?.meta?.source_node || null;
};
func.runtime.render.get_tree_source_snapshot = function (nodeP) {
if (!func.runtime.render.is_tree_node(nodeP)) {
return func.runtime.render.safe_clone_tree_value(nodeP);
}
return nodeP?.meta?.source_snapshot || null;
};
func.runtime.render.get_tree_node_kind = function (nodeP) {
const tag_name = typeof nodeP?.tagName === 'string' ? nodeP.tagName.toLowerCase() : '';
const node_type = typeof nodeP?.type === 'string' ? nodeP.type.toLowerCase() : '';
if (tag_name === 'xu-widget') return 'widget';
if (tag_name === 'xu-single-view') return 'single_view';
if (tag_name === 'xu-multi-view') return 'multi_view';
if (tag_name === 'xu-panel') return 'panel';
if (tag_name === 'xu-teleport') return 'teleport';
if (tag_name === 'xurender') return 'placeholder';
if (tag_name === '#text' || node_type === 'text') return 'text';
if (!tag_name && typeof nodeP?.content === 'string' && !Array.isArray(nodeP?.children)) return 'text';
return 'element';
};
func.runtime.render.get_tree_node_id = function (nodeP, pathP) {
if (nodeP?.id) {
return nodeP.id;
}
if (nodeP?.id_org) {
return nodeP.id_org;
}
const normalized_path = Array.isArray(pathP) && pathP.length ? pathP.join('.') : 'root';
return `tree-node-${normalized_path}`;
};
func.runtime.render.get_tree_controls = function (attributes) {
const attrs = attributes || {};
const get_first_defined = function (keys) {
for (let index = 0; index < keys.length; index++) {
const key = keys[index];
if (Object.prototype.hasOwnProperty.call(attrs, key)) {
return attrs[key];
}
}
return null;
};
return {
xu_for: get_first_defined(['xu-for', 'xu-exp:xu-for']),
xu_if: get_first_defined(['xu-if', 'xu-exp:xu-if']),
xu_render: get_first_defined(['xu-render', 'xu-exp:xu-render']),
};
};
func.runtime.render.get_tree_node_capabilities = async function (options) {
const attributes = options?.attributes || {};
const plugin_name = attributes['xu-widget'];
if (!plugin_name) {
return null;
}
const cache = func.runtime.render._tree_widget_capability_cache;
if (cache[plugin_name]) {
return func.runtime.render.safe_clone_tree_value(cache[plugin_name]);
}
let capabilities = {
browser: true,
headless: false,
};
try {
if (options.SESSION_ID && options.paramsP && func.runtime.widgets?.create_context && func.runtime.widgets?.get_definition) {
const widget_context = func.runtime.widgets.create_context(options.SESSION_ID, options.paramsP, attributes);
const definition = await func.runtime.widgets.get_definition(widget_context);
capabilities = func.runtime.widgets.normalize_capabilities(definition);
}
} catch (_) {
// Keep the safe browser-only default when the widget definition is unavailable.
}
cache[plugin_name] = capabilities;
return func.runtime.render.safe_clone_tree_value(capabilities);
};
func.runtime.render.ensure_tree_node = async function (options) {
if (!options?.nodeP) {
return null;
}
if (func.runtime.render.is_tree_node(options.nodeP)) {
return options.nodeP;
}
return await func.runtime.render.build_tree(options);
};
func.runtime.render.build_tree = async function (options) {
if (Array.isArray(options?.nodeP)) {
return await func.runtime.render.build_tree_list({
...options,
nodesP: options.nodeP,
});
}
const nodeP = options?.nodeP;
if (!nodeP) {
return null;
}
if (func.runtime.render.is_tree_node(nodeP)) {
return nodeP;
}
const pathP = Array.isArray(options?.pathP) ? options.pathP.slice() : [];
const tree_path = pathP.length ? pathP.slice() : [0];
const attributes = func.runtime.render.safe_clone_tree_value(nodeP.attributes || {});
const has_child_nodes = Array.isArray(nodeP.children) && nodeP.children.length > 0;
if (typeof nodeP.content !== 'undefined' && typeof attributes['xu-content'] === 'undefined' && !has_child_nodes && nodeP.content !== '') {
attributes['xu-content'] = func.runtime.render.safe_clone_tree_value(nodeP.content);
}
const widget_capabilities = await func.runtime.render.get_tree_node_capabilities({
SESSION_ID: options?.SESSION_ID,
paramsP: options?.paramsP,
attributes,
});
const children = [];
const child_nodes = Array.isArray(nodeP.children) ? nodeP.children : [];
const parent_tree_id = tree_path.join('.');
for (let index = 0; index < child_nodes.length; index++) {
const child_tree = await func.runtime.render.build_tree({
...options,
nodeP: child_nodes[index],
pathP: tree_path.concat(index),
parent_tree_id: parent_tree_id,
keyP: index,
parent_nodeP: nodeP,
});
if (child_tree) {
children.push(child_tree);
}
}
const tree = {
contract: func.runtime.render.TREE_CONTRACT_VERSION,
id: func.runtime.render.get_tree_node_id(nodeP, tree_path),
xu_tree_id: `tree.${tree_path.join('.')}`,
kind: func.runtime.render.get_tree_node_kind(nodeP),
tagName: nodeP.tagName || null,
attributes,
text: typeof nodeP.text !== 'undefined' ? func.runtime.render.safe_clone_tree_value(nodeP.text) : null,
content: typeof nodeP.content !== 'undefined' ? func.runtime.render.safe_clone_tree_value(nodeP.content) : null,
children,
meta: {
tree_id: tree_path.join('.'),
path: tree_path,
parent_tree_id: options?.parent_tree_id || null,
key: typeof options?.keyP === 'undefined' ? null : options.keyP,
recordid: nodeP?.recordid || null,
dependency_fields: func.runtime.render.safe_clone_tree_value(nodeP?.dependency_fields || null),
iterate_info: func.runtime.render.safe_clone_tree_value(options?.parent_infoP?.iterate_info || nodeP?.iterate_info || null),
controls: func.runtime.render.get_tree_controls(attributes),
capabilities: widget_capabilities,
widget: attributes['xu-widget']
? {
plugin_name: attributes['xu-widget'],
method: attributes['xu-method'] || '_default',
capabilities: widget_capabilities,
}
: null,
source_node_id: nodeP?.id || nodeP?.id_org || null,
source_node: nodeP,
source_snapshot: func.runtime.ui?.get_node_snapshot
? func.runtime.ui.get_node_snapshot(nodeP)
: func.runtime.render.safe_clone_tree_value(nodeP),
},
};
return tree;
};
func.runtime.render.build_tree_list = async function (options) {
const nodes = Array.isArray(options?.nodesP) ? options.nodesP : [];
const trees = [];
for (let index = 0; index < nodes.length; index++) {
const tree = await func.runtime.render.build_tree({
...options,
nodeP: nodes[index],
pathP: Array.isArray(options?.pathP) && options.pathP.length ? options.pathP.concat(index) : [index],
keyP: index,
});
if (tree) {
trees.push(tree);
}
}
return trees;
};
func.runtime.render.sanitize_tree_for_debug = function (treeP) {
if (Array.isArray(treeP)) {
return treeP.map(function (child) {
return func.runtime.render.sanitize_tree_for_debug(child);
});
}
if (!func.runtime.render.is_tree_node(treeP)) {
return func.runtime.render.sort_tree_debug_value(func.runtime.render.safe_clone_tree_value(treeP));
}
return {
contract: treeP.contract,
id: treeP.id,
xu_tree_id: treeP.xu_tree_id || null,
kind: treeP.kind,
tagName: treeP.tagName,
attributes: func.runtime.render.sort_tree_debug_value(treeP.attributes || {}),
text: treeP.text,
content: treeP.content,
children: treeP.children.map(function (child) {
return func.runtime.render.sanitize_tree_for_debug(child);
}),
meta: {
tree_id: treeP.meta?.tree_id || null,
path: func.runtime.render.safe_clone_tree_value(treeP.meta?.path || []),
parent_tree_id: treeP.meta?.parent_tree_id || null,
key: typeof treeP.meta?.key === 'undefined' ? null : treeP.meta.key,
recordid: treeP.meta?.recordid || null,
dependency_fields: func.runtime.render.sort_tree_debug_value(treeP.meta?.dependency_fields || null),
iterate_info: func.runtime.render.sort_tree_debug_value(treeP.meta?.iterate_info || null),
controls: func.runtime.render.sort_tree_debug_value(treeP.meta?.controls || null),
capabilities: func.runtime.render.sort_tree_debug_value(treeP.meta?.capabilities || null),
widget: treeP.meta?.widget
? {
plugin_name: treeP.meta.widget.plugin_name,
method: treeP.meta.widget.method,
capabilities: func.runtime.render.sort_tree_debug_value(treeP.meta.widget.capabilities || null),
}
: null,
source_node_id: treeP.meta?.source_node_id || null,
},
};
};
func.runtime.render.serialize_tree = function (treeP, spacing = 2) {
return JSON.stringify(func.runtime.render.sanitize_tree_for_debug(treeP), null, spacing);
};
func.runtime = func.runtime || {};
func.runtime.ui = func.runtime.ui || {};
func.runtime.render = func.runtime.render || {};
func.runtime.widgets = func.runtime.widgets || {};
// Shared string-renderer helpers live here so headless/server runtimes can materialize the render tree without a DOM.
func.runtime.render.HTML_VOID_TAGS = func.runtime.render.HTML_VOID_TAGS || {
area: true,
base: true,
br: true,
col: true,
embed: true,
hr: true,
img: true,
input: true,
link: true,
meta: true,
param: true,
source: true,
track: true,
wbr: true,
};
func.runtime.render.escape_html = function (value) {
return `${value ?? ''}`
.replaceAll('&', '&')
.replaceAll('<', '<')
.replaceAll('>', '>')
.replaceAll('"', '"')
.replaceAll("'", ''');
};
func.runtime.render.escape_html_attribute = function (value) {
return func.runtime.render.escape_html(value);
};
func.runtime.render.is_html_void_tag = function (tag_name) {
return !!func.runtime.render.HTML_VOID_TAGS[(tag_name || '').toLowerCase()];
};
func.runtime.render.is_falsey_render_value = function (value) {
if (value === false || value === null || typeof value === 'undefined') {
return true;
}
if (typeof value === 'number') {
return value === 0;
}
if (typeof value === 'string') {
const normalized = value.trim().toLowerCase();
return normalized === '' || normalized === 'false' || normalized === '0' || normalized === 'null' || normalized === 'undefined' || normalized === 'off' || normalized === 'no';
}
return false;
};
func.runtime.render.should_render_tree_node = function (treeP) {
const controls = treeP?.meta?.controls || {};
if (controls.xu_if !== null && controls.xu_if !== undefined && func.runtime.render.is_falsey_render_value(controls.xu_if)) {
return false;
}
if (controls.xu_render !== null && controls.xu_render !== undefined && func.runtime.render.is_falsey_render_value(controls.xu_render)) {
return false;
}
return true;
};
func.runtime.render.is_tree_control_attribute = function (key) {
if (!key) {
return false;
}
return (
key.startsWith('xu-exp:') ||
key === 'xu-widget' ||
key === 'xu-method' ||
key === 'xu-for' ||
key === 'xu-for-key' ||
key === 'xu-for-val' ||
key === 'xu-if' ||
key === 'xu-render' ||
key === 'xu-bind' ||
key === 'xu-content' ||
key === 'xu-text' ||
key === 'xu-html' ||
key === 'xu-show' ||
key === 'xu-panel-program' ||
key === 'xu-teleport'
);
};
func.runtime.render.get_string_renderer_tag_name = function (treeP) {
switch (treeP?.kind) {
case 'widget':
case 'single_view':
case 'multi_view':
case 'panel':
case 'teleport':
return 'div';
case 'placeholder':
return null;
case 'text':
return null;
default:
return treeP?.tagName || 'div';
}
};
func.runtime.render.get_tree_terminal_content = function (treeP) {
const attributes = treeP?.attributes || {};
if (typeof attributes['xu-html'] !== 'undefined' && attributes['xu-html'] !== null) {
return {
value: `${attributes['xu-html']}`,
mode: 'html',
};
}
if (typeof attributes['xu-content'] !== 'undefined' && attributes['xu-content'] !== null) {
return {
value: `${attributes['xu-content']}`,
mode: 'html',
};
}
if (typeof attributes['xu-text'] !== 'undefined' && attributes['xu-text'] !== null) {
return {
value: `${attributes['xu-text']}`,
mode: 'text',
};
}
if (treeP?.kind === 'text') {
return {
value: typeof treeP?.text !== 'undefined' && treeP?.text !== null ? `${treeP.text}` : `${treeP?.content || ''}`,
mode: 'text',
};
}
return null;
};
func.runtime.render.render_tree_terminal_content = function (treeP) {
const terminal = func.runtime.render.get_tree_terminal_content(treeP);
if (!terminal) {
return null;
}
if (terminal.mode === 'html') {
return terminal.value;
}
return func.runtime.render.escape_html(terminal.value);
};
func.runtime.render.get_widget_fallback_markup = function (treeP) {
const widget_meta = treeP?.meta?.widget || {};
const capability_state = widget_meta?.capabilities?.headless ? 'headless-capable' : 'browser-only';
return `<!--xuda-widget:${func.runtime.render.escape_html(widget_meta.plugin_name || 'unknown')}:${capability_state}-->`;
};
func.runtime.render.get_tree_string_attributes = function (treeP, renderer_context) {
const attributes = func.runtime.render.safe_clone_tree_value(treeP?.attributes || {});
const attr_pairs = [];
const keys = Object.keys(attributes);
for (let index = 0; index < keys.length; index++) {
const key = keys[index];
if (func.runtime.render.is_tree_control_attribute(key)) {
continue;
}
const value = attributes[key];
if (value === false || value === null || typeof value === 'undefined') {
continue;
}
if (value === true) {
attr_pairs.push(key);
continue;
}
const normalized_value = typeof value === 'object' ? JSON.stringify(value) : `${value}`;
attr_pairs.push(`${key}="${func.runtime.render.escape_html_attribute(normalized_value)}"`);
}
attr_pairs.push(`data-xuda-kind="${func.runtime.render.escape_html_attribute(treeP?.kind || 'element')}"`);
attr_pairs.push(`data-xuda-node-id="${func.runtime.render.escape_html_attribute(treeP?.id || treeP?.meta?.source_node_id || '')}"`);
attr_pairs.push(`data-xuda-tree-id="${func.runtime.render.escape_html_attribute(treeP?.meta?.tree_id || '')}"`);
if (treeP?.kind === 'widget' && treeP?.meta?.widget) {
attr_pairs.push(`data-xuda-widget="${func.runtime.render.escape_html_attribute(treeP.meta.widget.plugin_name || '')}"`);
attr_pairs.push(`data-xuda-widget-method="${func.runtime.render.escape_html_attribute(treeP.meta.widget.method || '_default')}"`);
attr_pairs.push(`data-xuda-widget-capability="${func.runtime.render.escape_html_attribute(treeP.meta.widget.capabilities?.headless ? 'headless' : 'browser')}"`);
}
if (treeP?.kind === 'teleport' && treeP?.attributes?.['xu-teleport']) {
attr_pairs.push(`data-xuda-teleport-target="${func.runtime.render.escape_html_attribute(treeP.attributes['xu-teleport'])}"`);
}
if ((treeP?.meta?.controls?.xu_for !== null && treeP?.meta?.controls?.xu_for !== undefined) && !renderer_context?.strip_iteration_markers) {
attr_pairs.push('data-xuda-xu-for="pending"');
}
return attr_pairs.length ? ' ' + attr_pairs.join(' ') : '';
};
func.runtime.render.render_tree_children_to_string = async function (treeP, renderer_context) {
if (!Array.isArray(treeP?.children) || !treeP.children.length) {
return '';
}
let html = '';
for (let index = 0; index < treeP.children.length; index++) {
html += await func.runtime.render.render_tree_to_string(treeP.children[index], {
...renderer_context,
parent_tree: treeP,
});
}
return html;
};
func.runtime.render.render_tree_to_string = async function (treeP, renderer_context = {}) {
if (!treeP) {
return '';
}
if (Array.isArray(treeP)) {
let html = '';
for (let index = 0; index < treeP.length; index++) {
html += await func.runtime.render.render_tree_to_string(treeP[index], renderer_context);
}
return html;
}
const ensured_tree = await func.runtime.render.ensure_tree_node({
SESSION_ID: renderer_context?.SESSION_ID,
nodeP: treeP,
paramsP: renderer_context?.paramsP,
parent_infoP: renderer_context?.parent_infoP,
keyP: renderer_context?.keyP,
parent_nodeP: renderer_context?.parent_nodeP,
});
if (!ensured_tree || !func.runtime.render.should_render_tree_node(ensured_tree)) {
return '';
}
if (ensured_tree.kind === 'placeholder') {
if (renderer_context?.include_placeholders) {
return `<!--xuda-placeholder:${func.runtime.render.escape_html(ensured_tree.id || '')}-->`;
}
return '';
}
if (ensured_tree.kind === 'text') {
return func.runtime.render.render_tree_terminal_content(ensured_tree) || '';
}
const tag_name = func.runtime.render.get_string_renderer_tag_name(ensured_tree);
if (!tag_name || tag_name.toLowerCase() === 'script') {
return '';
}
const attributes = func.runtime.render.get_tree_string_attributes(ensured_tree, renderer_context);
const terminal_content = func.runtime.render.render_tree_terminal_content(ensured_tree);
let children_html = terminal_content !== null ? terminal_content : await func.runtime.render.render_tree_children_to_string(ensured_tree, renderer_context);
if (ensured_tree.kind === 'widget' && !children_html) {
children_html = func.runtime.render.get_widget_fallback_markup(ensured_tree);
}
if (func.runtime.render.is_html_void_tag(tag_name)) {
return `<${tag_name}${attributes}>`;
}
return `<${tag_name}${attributes}>${children_html}</${tag_name}>`;
};
func.runtime.render.render_to_string = async function (options = {}) {
const treeP = await func.runtime.render.ensure_tree_node({
SESSION_ID: options.SESSION_ID,
nodeP: options.treeP || options.nodeP,
paramsP: options.paramsP,
parent_infoP: options.parent_infoP,
keyP: options.keyP,
parent_nodeP: options.parent_nodeP,
});
return await func.runtime.render.render_tree_to_string(treeP, options);
};
func.runtime.render.get_server_render_mode = function (options = {}) {
const normalized = func.runtime.render.normalize_runtime_bootstrap({
app_computing_mode: options.app_computing_mode,
app_render_mode: options.app_render_mode,
app_client_activation: options.app_client_activation,
});
return normalized;
};
func.runtime.render.build_server_render_params = async function (options = {}) {
const SESSION_ID = options.SESSION_ID;
const prog_id = options.prog_id;
const dsSessionP = options.dsSessionP;
const _session = SESSION_OBJ?.[SESSION_ID] || {};
const _ds = _session?.DS_GLB?.[dsSessionP] || {};
const viewDoc = options.viewDoc || (await func.utils?.VIEWS_OBJ?.get?.(SESSION_ID, prog_id));
if (!viewDoc?.properties) {
throw new Error(`view document not found for ${prog_id}`);
}
const base_params = _ds?.screen_params ? func.runtime.render.safe_clone_tree_value(_ds.screen_params) : {};
const screenId = options.screenId || base_params.screenId || `ssr_${prog_id}_${dsSessionP || '0'}`;
const paramsP = {
...base_params,
prog_id,
sourceScreenP: null,
$callingContainerP: null,
triggerIdP: null,
callingDataSource_objP: _ds,
rowIdP: typeof options.rowIdP !== 'undefined' ? options.rowIdP : (_ds?.currentRecordId || null),
renderType: viewDoc.properties?.renderType,
parameters_obj_inP: options.parameters_obj_inP || base_params.parameters_obj_inP || options.parameters_raw_obj || {},
source_functionP: options.source_functionP || base_params.source_functionP || 'render_string',
is_panelP: false,
screen_type: options.screen_type || base_params.screen_type || 'render_string',
screenInfo: viewDoc,
call_screen_propertiesP: base_params.call_screen_propertiesP,
parentDataSourceNoP: typeof _ds?.parentDataSourceNo === 'undefined' || _ds?.parentDataSourceNo === null ? 0 : _ds.parentDataSourceNo,
parameters_raw_obj: options.parameters_raw_obj || base_params.parameters_raw_obj || {},
dsSessionP,
screenId,
containerIdP: base_params.containerIdP || `ssr_container_${screenId}`,
};
if (_ds) {
_ds.screen_params = paramsP;
}
return paramsP;
};
func.runtime.render.build_prog_tree = async function (options = {}) {
const SESSION_ID = options.SESSION_ID;
const prog_id = options.prog_id;
const viewDoc = options.viewDoc || (await func.utils?.VIEWS_OBJ?.get?.(SESSION_ID, prog_id));
if (!viewDoc?.progUi?.length) {
throw new Error(`progUi not found for ${prog_id}`);
}
const paramsP = options.paramsP || (await func.runtime.render.build_server_render_params({
...options,
SESSION_ID,
prog_id,
viewDoc,
}));
const root_index = typeof options.root_index === 'number' ? options.root_index : 0;
const root_node = func.runtime.render.safe_clone_tree_value(viewDoc.progUi[root_index]);
const tree = await func.runtime.render.build_tree({
SESSION_ID,
nodeP: root_node,
paramsP,
});
return {
tree,
paramsP,
viewDoc,
};
};
func.runtime.render.build_ssr_payload = function (render_program, options = {}) {
const runtime_profile = func.runtime.render.get_server_render_mode(options);
return {
contract: 'xuda.ssr.v1',
prog_id: options.prog_id,
screenId: render_program.paramsP.screenId,
containerId: render_program.paramsP.containerIdP,
app_computing_mode: runtime_profile.app_computing_mode,
app_render_mode: runtime_profile.app_render_mode,
app_client_activation: runtime_profile.app_client_activation,
tree_contract: func.runtime.render.TREE_CONTRACT_VERSION,
};
};
func.runtime.render.build_ssr_screen_html = function (html, render_program, options = {}) {
const payload = func.runtime.render.build_ssr_payload(render_program, options);
const screenId = func.runtime.render.escape_html_attribute(payload.screenId || '');
const containerId = func.runtime.render.escape_html_attribute(payload.containerId || '');
const activation = func.runtime.render.escape_html_attribute(payload.app_client_activation || 'takeover');
return `<div data-xuda-ssr-embed="true" class="xu_embed_div"><div id="${screenId}" class="xu_embed_container" data-xuda-ssr-screen="true" data-xuda-ssr-screen-id="${screenId}" data-xuda-activation="${activation}" style="display: contents;"><div id="${containerId}" data-xuda-ssr-root-frame="true" data-xuda-ssr-screen-id="${screenId}" data-xuda-activation="${activation}" style="display: contents;">${html}</div></div></div>`;
};
func.runtime.render.render_prog_to_string = async function (options = {}) {
const render_program = await func.runtime.render.build_prog_tree(options);
const html = await func.runtime.render.render_to_string({
...options,
SESSION_ID: options.SESSION_ID,
treeP: render_program.tree,
paramsP: render_program.paramsP,
});
const ssr_payload = func.runtime.render.build_ssr_payload(render_program, options);
const screen_html = func.runtime.render.build_ssr_screen_html(html, render_program, options);
return {
prog_id: options.prog_id,
dsSessionP: render_program.paramsP.dsSessionP,
screenId: render_program.paramsP.screenId,
html,
screen_html,
tree_json: func.runtime.render.serialize_tree(render_program.tree),
paramsP: render_program.paramsP,
ssr_payload,
};
};
func.runtime = func.runtime || {};
func.runtime.platform = func.runtime.platform || {};
func.runtime.platform.dispatch_document_event = function (name, data) {
if (typeof document === 'undefined' || typeof CustomEvent === 'undefined') {
return false;
}
document.dispatchEvent(new CustomEvent(name, {
detail: Array.isArray(data) ? data : [data],
}));
return true;
};
glb.DEBUG_INFO_OBJ = {};
// var CONNECTION_ATTEMPTS = 0;
glb.APP_INFO = {};
// var vars = {};
// var USERS_CACHE = {};
var SYSTEM_READY = null;
// var CPI_WEBSOCKET;
var GLB_JS_SCRIPTS_LOADED = [];
var STUDIO_WEBSOCKET = null;
var STUDIO_WEBSOCKET_CONNECTION_ID = null;
var STUDIO_PEER = null;
var STUDIO_PEER_CONN_SEND_METHOD = null;
var STUDIO_PEER_CONN_ID = null;
var SUPPORT_PEER = null;
var SUPPORT_PEER_CONN = null;
var STUDIO_PEER_CONN_MSG_QUEUE = [];
var CLIENT_ACTIVITY_TS;
var IS_ONLINE;
glb.REFERENCE_LESS_FUNCTIONS = ['update', 'raise_event', 'call_library', 'invoke_action', 'loader_on', 'loader_off', 'emit_event', 'delay', 'execute_evaluate_javascript', 'execute_native_javascript'];
var CACHE_PROG_UI = {};
var ALERT_IS_ACTIVE = false;
glb.WORKER_ATTEMPTS_NOT_RESPONDING = 200000;
glb.WORKER_TIMEOUT = 600000;
glb.WORKER_PAUSE = false;
// glb.EMAIL_SEND_RECEIVE_STATUS = {};
var DATASOURCE_INTERVALS = {};
var APP_MODAL_OBJ = {};
var CURRENT_APP_POPOVER = null;
var ELEMENT_CLICK_EVENT = null;
var posX = 0; //cursor x
var posY = 0; //cursor x
var LOADER_ACTIVE = false;
var LOADER_TEXT = '';
var REFRESHER_IN_PROGRESS = false;
glb.screen_num = 0;
var RESPONSE_FROM_STUDIO_QUEUE = {};
var SCREEN_BLOCKER_OBJ = {};
var IS_PROGRESS_SCREEN_OPEN = null;
// var UI_ENGINE_OBJ = null;
var UI_WORKER_OBJ = {
jobs: [],
num: 9000,
cache: {},
viewport_height_set_ids: [],
xu_render_cache: {},
// pending_for_viewport_render: {}
};
glb.html5_events_handler = [
'onabort',
'onafterprint',
'onautocomplete',
'onautocompleteerror',
'onbeforeprint',
'onbeforeunload',
'onblur',
'oncancel',
'oncanplay',
'oncanplaythrough',
'onchange',
'onclick',
'onclose',
'oncontextmenu',
'oncopy',
'oncuechange',
'oncut',
'ondblclick',
'ondrag',
'ondragend',
'ondragenter',
'ondragexit',
'ondragleave',
'ondragover',
'ondragstart',
'ondrop',
'ondurationchange',
'onemptied',
'onended',
'onerror',
'onfocus',
'onhashchange',
'oninput',
'oninvalid',
'onkeydown',
'onkeypress',
'onkeyup',
'onload',
'onloadeddata',
'onloadedmetadata',
'onloadstart',
'onmessage',
'onmousedown',
'onmouseenter',
'onmouseleave',
'onmousemove',
'onmouseout',
'onmouseover',
'onmouseup',
'onmousewheel',
'onoffline',
'ononline',
'onpagehide',
'onpageshow',
'onpaste',
'onpause',
'onplay',
'onplaying',
'onpopstate',
'onprogress',
'onratechange',
'onreset',
'onresize',
'onscroll',
'onsearch',
'onseeked',
'onseeking',
'onselect',
'onshow',
'onsort',
'onstalled',
'onstorage',
'onsubmit',
'onsuspend',
'ontimeupdate',
'ontoggle',
'onunload',
'onvolumechange',
'onwaiting',
];
glb.lifecycle = {
plugins: {},
// queue: [],
fn_arr: ['beforeInit', 'initialized', 'systemReady', 'beforeMounted', 'mounted'],
// add(type, fn, params) {
// this.queue.push({ type, fn, params });
// },
execute: async function (SESSION_ID, event) {
const _session = SESSION_OBJ[SESSION_ID];
const xu_api = await func.common.get_module(SESSION_ID, 'xuda-api-library.mjs', {
func,
glb,
SESSION_OBJ,
SESSION_ID,
APP_OBJ,
dsSession: func.utils.get_last_datasource_no(SESSION_ID),
});
var params = {
SESSION_ID,
session_data: _session,
app_obj: APP_OBJ[_session.app_id],
xu_api,
};
for await (const [plugin_name, val] of Object.entries(glb.lifecycle.plugins)) {
if (val?.plugin_script?.[event]) {
params.setup_data = val.setup_data;
await val.plugin_script[event](params);
}
}
},
};
glb.run_xu_before = [
'xu-cdn',
'xu-style',
'xu-render',
'xu-for-key',
'xu-for-val',
// "xu-ui-plugin",
// "programParameters",
];
glb.run_xu_after = ['xu-bind', 'xu-class', 'xu-script', 'xu-ui-plugin', 'xu-ref'];
glb.attr_abbreviations_arr = ['xu-click', 'xu-dblclick', 'xu-contextmenu', 'xu-focus', 'xu-keyup', 'xu-change', 'xu-blur', 'xu-init'];
glb.solid_attributes = ['disabled'];
func.utils = {};
func.utils.debug = {};
func.utils.debug.watch = async function (SESSION_ID, key, type, info, result, condition, not_executed) {
if (!glb.DEBUG_MODE) return;
const debug_utils = await func.common.get_module(SESSION_ID, 'xuda-debug-utils-module.mjs');
debug_utils.watch(SESSION_ID, key, type, info, result, condition, not_executed);
};
func.utils.debug.log = async function (SESSION_ID, node_idP, jsonP) {
if (typeof IS_PROCESS_SERVER !== 'undefined') return;
if (!glb.DEBUG_MODE && !glb.TRACE_ON) return;
const debug_utils = await func.common.get_module(SESSION_ID, 'xuda-debug-utils-module.mjs');
debug_utils.log(SESSION_ID, node_idP, jsonP);
// console.error(jsonP);
};
func.utils.debug.write = async function (SESSION_ID, logP, callbackP) {
if (!glb.DEBUG_MODE) return;
const debug_utils = await func.common.get_module(SESSION_ID, 'xuda-debug-utils-module.mjs');
debug_utils.write(SESSION_ID, logP, callbackP);
};
func.utils.debug.read_command = async function (data) {
if (!glb.DEBUG_MODE) return;
const debug_utils = await func.common.get_module(SESSION_ID, 'xuda-debug-utils-module.mjs');
debug_utils.read_command(data);
};
func.utils.DOCS_OBJ = {};
func.utils.DOCS_OBJ.get = async function (SESSION_ID, idP) {
if (!idP || idP === '0') return;
const normalize_runtime_doc = function (doc) {
if (!doc || !func.runtime.program?.normalize_doc_for_runtime) {
return doc;
}
return func.runtime.program.normalize_doc_for_runtime(doc);
};
var _session = SESSION_OBJ[SESSION_ID];
const _app_id = _session.app_id;
if (!DOCS_OBJ[_app_id]) {
DOCS_OBJ[_app_id] = {};
}
if (DOCS_OBJ[_app_id][idP]) {
return DOCS_OBJ[_app_id][idP];
}
if (_session.project_data) {
if (idP === 'system') {
if (_session.project_data.globals) {
DOCS_OBJ[_app_id][idP] = _session.project_data.globals;
} else {
DOCS_OBJ[_app_id][idP] = {};
}
return DOCS_OBJ[_app_id][idP];
}
let val = _session.project_data?.programs?.[idP];
if (val) {
DOCS_OBJ[_app_id][idP] = normalize_runtime_doc(val);
return DOCS_OBJ[_app_id][idP];
}
}
if (typeof _session.SLIM_BUNDLE === 'undefined' || !_session.SLIM_BUNDLE) {
const module = await func.common.get_module(SESSION_ID, `xuda-progs-loader-module.mjs`);
if (idP !== 'system') {
DOCS_OBJ[_app_id][idP] = normalize_runtime_doc(await module.DOCS_OBJ_get(SESSION_ID, idP));
if (DOCS_OBJ[_app_id][idP] && xu_isEmpty(DOCS_OBJ[_app_id][idP])) {
await func.utils.remove_cached_objects(SESSION_ID);
delete DOCS_OBJ[_app_id][idP];
}
return DOCS_OBJ[_app_id][idP];
}
DOCS_OBJ[_app_id][idP] = await module.DOCS_OBJ_get(SESSION_ID, 'global_' + (APP_OBJ[_app_id].app_replicate || _app_id));
if (APP_OBJ[_app_id].app_imported_projects) {
for await (const imported_app_id of APP_OBJ[_app_id].app_imported_projects) {
var view_ret = await module.DOCS_OBJ_get(SESSION_ID, 'global_' + imported_app_id);
DOCS_OBJ[_app_id][idP] = Object.assign(DOCS_OBJ[_app_id][idP], view_ret);
}
}
return DOCS_OBJ[_app_id][idP];
}
console.error(`${idP} not found`);
};
func.utils.FILES_OBJ = {};
func.utils.FILES_OBJ.get = async function (SESSION_ID, idP) {
if (!idP) return;
return await func.utils.DOCS_OBJ.get(SESSION_ID, idP);
};
func.utils.VIEWS_OBJ = {};
func.utils.VIEWS_OBJ.get = async function (SESSION_ID, idP) {
if (!idP) return;
return await func.utils.DOCS_OBJ.get(SESSION_ID, idP);
};
func.utils.TREE_OBJ = {};
func.utils.TREE_OBJ.get = async function (SESSION_ID, idP) {
if (!idP) return;
var ret = await func.utils.DOCS_OBJ.get(SESSION_ID, idP);
if (ret?.properties) {
ret.properties.id = idP;
}
return ret.properties;
};
func.utils.get_dateTime = async function (SESSION_ID, typeP, dateP) {
// const getUTC = function (ts) {
// var date = new Date(ts);
// var utc_date = new Date(
// date.getUTCFullYear(),
// date.getUTCMonth(),
// date.getUTCDate(),
// date.getUTCHours(),
// date.getUTCMinutes(),
// date.getUTCSeconds(),
// date.getUTCMilliseconds()
// );
// return utc_date;
// };
const get_server_ts = async function () {
var _session = SESSION_OBJ[SESSION_ID];
const response = await fetch(`https://${_session.domain}/cpi/get_utc_ts`, {
method: 'POST',
headers: {
Accept: 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify({}),
});
const json = await response.json();
return json.data;
// }
};
function getWeekNumber(d) {
// Copy date so don't modify original
d = new Date(+d);
d.setHours(0, 0, 0);
// Set to nearest Thursday: current date + 4 - current day number
// Make Sunday's day number 7
d.setDate(d.getDate() + 4 - (d.getDay() || 7));
// Get first day of year
var yearStart = new Date(d.getFullYear(), 0, 1);
// Calculate full weeks to nearest Thursday
var weekNo = Math.ceil(((d - yearStart) / 86400000 + 1) / 7);
// Return array of year and week number
return weekNo;
}
var sysDate = new Date(dateP); // getUTC(dateP); //new Date(dateP);
if (!dateP) {
let ts = await get_server_ts();
sysDate = new Date(ts);
}
var day = String(sysDate.getDate()).padStart(2, '0');
var month = String(sysDate.getMonth() + 1).padStart(2, '0');
var year = sysDate.getFullYear();
var week = String(getWeekNumber(sysDate)).padStart(2, '0');
var hour = String(sysDate.getHours()).padStart(2, '0');
var minute = String(sysDate.getMinutes()).padStart(2, '0');
var second = String(sysDate.getSeconds()).padStart(2, '0');
if (typeP === 'SYS_DATE') return year + '-' + month + '-' + day;
if (typeP === 'SYS_DATE_TIME') return year + '-' + month + '-' + day + 'T' + hour + ':' + minute;
if (typeP === 'SYS_DATE_VALUE') return sysDate.valueOf();
if (typeP === 'SYS_DATE_WEEK_YEAR') return year + 'W' + week;
if (typeP === 'SYS_DATE_MONTH_YEAR') return year + '-' + month;
if (typeP === 'SYS_TIME') return hour + ':' + minute + ':' + second;
if (typeP === 'SYS_TIME_SHORT') return hour + ':' + minute;
};
func.utils.is_onscreen_event = function (functionP) {
const arr = ['invoke_action', 'cache_refresh', 'call_popover', 'call_modal', 'call_page', 'loader_on', 'loader_off', 'emit_event'];
return arr.includes(functionP);
};
func.utils.get_screen_obj = async function (SESSION_ID, id) {
const prog_obj = await func.utils.VIEWS_OBJ.get(SESSION_ID, id);
if (!prog_obj) return console.error('prog not found: ' + id);
// if (prog_obj.properties.menuType === 'screen' || prog_obj.properties.menuType === 'api' || glb.FUNCTION_NODES_ARR.includes(prog_obj.properties.menuType) || glb.MOBILE_ARR.includes(prog_obj.properties.menuType)) {
if (['component', ...glb.FUNCTION_NODES_ARR].includes(prog_obj.properties.menuType)) {
return prog_obj;
}
return;
};
func.utils.clean_returned_datasource = function (SESSION_ID, DS) {
const clean_object_functions = function (obj) {
for (const [key, val] of Object.entries(obj)) {
if (typeof val === 'function') {
delete obj[key];
}
}
};
var _session = SESSION_OBJ[SESSION_ID];
if (!_session.DS_GLB[DS]) return;
var obj = { ..._session.DS_GLB[DS] };
delete obj.screen_params;
// try {
// clean_object_functions(obj);
// obj = JSON.parse(JSON.stringify(obj, func.utils.clean_stringify_null, '\t'));
// } catch (e) {
// console.error(e);
// }
delete obj.pre_init_fields;
delete obj.oninit_triggers_to_run;
// delete obj.raw_data;
delete obj.debug;
const clean_empty_objects = function () {
for (const [key, val] of Object.entries(obj)) {
if (typeof val === 'object' && !Array.isArray(val) && xu_isEmpty(val)) {
delete obj[key];
}
}
for (const [key, val] of Object.entries(obj)) {
if (typeof val === 'object' && Array.isArray(val) && !val.length) {
delete obj[key];
}
}
};
delete obj.screenInfo;
delete obj.viewEventsProp;
delete obj.viewSourceDesc;
delete obj.viewSourceProp;
delete obj.v;
clean_empty_objects();
try {
clean_object_functions(obj);
obj = JSON.parse(JSON.stringify(obj, func.utils.clean_stringify_null, '\t'));
} catch (e) {
console.error(e);
}
// clean_dataset();
return obj;
};
func.utils.post_back_to_client = function (SESSION_ID, service, id, data) {
if (typeof IS_PROCESS_SERVER !== 'undefined') return;
worker_post_message({
fx_to_execute: service,
params: data,
session_id: SESSION_ID,
worker_id: id,
});
};
func.utils.job_worker = {};
func.utils.job_worker = function (session_id) {
var SESSION_ID = session_id;
var _session = SESSION_OBJ[SESSION_ID];
var is_progressScreen_on;
var is_not_responding;
var attempt = 0;
const lock = function (dsP) {
if (!_session.WORKER_OBJ.jobs[_session.WORKER_OBJ.stat] || _session.WORKER_OBJ.jobs[_session.WORKER_OBJ.stat].typeP === 'system_interval' || _session.WORKER_OBJ.jobs[_session.WORKER_OBJ.stat].typeP === 'system event') {
return;
}
if (glb.IS_WORKER) {
func.utils.post_back_to_client(SESSION_ID, 'screen_blocker_on', _session.worker_id, null);
} else {
func.UI.utils.screen_blocker(true, 'Worker', dsP);
}
};
const unlock = function () {
if (glb.IS_WORKER) {
} else {
func.UI.utils.screen_blocker(false, 'Worker');
}
};
const not_responding = function () {
is_not_responding = true;
func.UI.utils.progressScreen.hide('Working, Please wait..');
setTimeout(function () {
if (!is_not_responding) return;
reset();
}, 500);
};
const idle = function () {
if (is_progressScreen_on) {
setTimeout(function () {
if (!attempt && is_progressScreen_on) {
is_progressScreen_on = false;
is_not_responding = false;
func.UI.utils.progressScreen.hide('Working, Please wait..');
} else if (attempt > 300 && is_not_responding) {
is_not_responding = false;
busy();
}
}, 310);
} else {
if (!glb.IS_WORKER) {
// func.UI.screen.garbage_collector(SESSION_ID);
}
}
};
const busy = function () {
if (glb.IS_WORKER) return;
func.utils.debug_report(SESSION_ID, 'utils.worker.busy', 'worker processing more then 10 second', 'W', '', _session.WORKER_OBJ.jobs);
is_progressScreen_on = true;
};
const reset = function () {
func.utils.debug_report(SESSION_ID, 'utils.worker.reset', 'worker not responding', 'E', '', _session.WORKER_OBJ.jobs);
_session.WORKER_OBJ.jobs = [];
_session.WORKER_OBJ.stat = null;
func.runtime.ui.clear_screen_blockers();
};
return {
_interval: null,
_was_busy: null,
init: async function () {
var _this = this;
this._interval = setInterval(async function () {
var _session = SESSION_OBJ[SESSION_ID];
if (!_session?.WORKER_OBJ) return;
if (typeof _session.WORKER_OBJ.stat === 'undefined' || _session.WORKER_OBJ.stat === 'undefined' || _session.WORKER_OBJ.stat === null) {
// idle
// if (_this._was_busy) {
// if (glb.IS_WORKER) {
// func.utils.post_back_to_client(
// SESSION_ID,
// "worker_busy_off",
// _session.worker_id,
// null
// );
// } else {
// func.UI.utils.indicator.worker.normal();
// }
// _this._was_busy = false;
// }
unlock();
if (_session.WORKER_OBJ.jobs.length) {
for await (const [key, val] of Object.entries(_session.WORKER_OBJ.jobs)) {
if (val.stat) {
break;
}
// if (!_session.WORKER_OBJ.stat) {
if (!_session.WORKER_OBJ.jobs[Number(key)] || val.job_num === 9999999) {
continue;
}
if (val.dsSessionP && !_session.DS_GLB[val.dsSessionP]) {
func.events.delete_job(SESSION_ID, val.job_num);
break;
}
await func.events.execute(
SESSION_ID,
val.job_num,
val.eventIdP,
val.triggerP,
val.functionP,
val.refIdP,
val.containerP,
val.elementP,
val.rowP,
val.evt,
val.descP,
val.rootScreenIdP,
val.dsSessionP,
null,
val.typeP,
null,
val.event_propertiesP,
val.calling_triggerP,
null,
val.paramsP,
val.target_frame_idP,
val.calling_trigger_prop,
val.calling_program,
val.argumentsP,
val.prog_id,
val.nodeId,
val.parentDataSourceNo,
val.$container,
val.event_optionsP,
);
}
_this._was_busy = true;
} else {
// idle
if (_this._was_busy) {
if (glb.IS_WORKER) {
func.utils.post_back_to_client(SESSION_ID, 'worker_busy_off', _session.worker_id, null);
} else {
func.UI.utils.indicator.worker.normal();
}
}
_this._was_busy = false;
}
attempt = 0;
is_not_responding = false;
idle();
} else {
//busy
_this._was_busy = true;
if (glb.IS_WORKER) {
func.utils.post_back_to_client(SESSION_ID, 'worker_busy_on', _session.worker_id, null);
} else {
func.UI.utils.indicator.worker.busy();
}
if (glb.WORKER_PAUSE) return;
attempt++;
if (!is_progressScreen_on && attempt > glb.WORKER_TIMEOUT) busy();
if (!is_not_responding && attempt >= glb.WORKER_ATTEMPTS_NOT_RESPONDING) {
not_responding();
}
var ds = null;
if (_session.WORKER_OBJ.jobs[0]) ds = _session.WORKER_OBJ.jobs[0].dsSessionP;
lock(ds);
}
}, 1);
},
stop: function () {
clearInterval(this._interval);
},
};
};
func.utils.base64MimeType = function (encoded) {
var result = null;
if (typeof encoded !== 'string') {
return result;
}
var mime = encoded.match(/data:([a-zA-Z0-9]+\/[a-zA-Z0-9-.+]+).*,.*/);
if (mime && mime.length) {
result = mime[1];
}
return result;
};
func.utils.makeid = function (length) {
var result = '';
var characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
var charactersLength = characters.length;
for (var i = 0; i < length; i++) {
result += characters.charAt(Math.floor(Math.random() * charactersLength));
}
return result;
};
func.utils.get_device = function () {
var device;
try {
const win = func.runtime.platform.get_window();
if (win?.cordova) {
device = win.cordova.platformId;
}
} catch (e) {
console.error('error using ui element in server side request');
}
return device;
};
func.utils.ws_worker = {};
func.utils.ws_worker.functions = {
init: async function (data) {
var SESSION_ID = data.SESSION_ID;
APP_OBJ[data.app_id] = data.APP_OBJ;
PROJECT_OBJ[data.app_id] = data.PROJECT_OBJ;
if (['live_preview', 'miniapp'].includes(data.SESSION_INFO.engine_mode)) {
DOCS_OBJ[data.app_id] = data.DOCS_OBJ;
} else if (typeof IS_DOCKER === 'undefined' && typeof IS_PROCESS_SERVER === 'undefined') {
if (!DOCS_OBJ[data.app_id]) {
DOCS_OBJ[data.app_id] = {};
}
}
glb.APP_INFO[data.app_id] = data.APP_INFO;
glb.DEBUG_MODE = data.DEBUG_MODE;
glb.DEBUG_INFO_OBJ = data.DEBUG_INFO_OBJ;
glb.WINDOW_LOCATION_SEARCH = data.WINDOW_LOCATION_SEARCH;
glb.ROOT_ELEMENT_ATTRIBUTES = data.ROOT_ELEMENT_ATTRIBUTES;
DATASOURCE_INTERVALS[SESSION_ID] = {};
SESSION_OBJ[SESSION_ID] = data.SESSION_INFO;
var _session = SESSION_OBJ[SESSION_ID];
glb.SESSION_INFO = data.SESSION_INFO;
_session.engine_mode = data.engine_mode;
STUDIO_WEBSOCKET_CONNECTION_ID = data.STUDIO_WEBSOCKET_CONNECTION_ID;
for (let [key, val] of Object.entries(_session.DS_GLB)) {
if (Number(key) > _session.dataSourceSessionGlobal) {
_session.dataSourceSessionGlobal = Number(key);
}
}
if (typeof _session.SLIM_BUNDLE === 'undefined' || !_session.SLIM_BUNDLE) {
const db_adapter = await func.common.get_module(SESSION_ID, 'xuda-db-adapter-module.mjs');
func.db = db_adapter._db;
}
_session.WORKER_OBJ.fx = new func.utils.job_worker(SESSION_ID);
_session.WORKER_OBJ.fx.init();
if (_session.app_id === 'unknown') {
worker_post_message({
fx_to_execute: 'init_done',
worker_id: ws_worker_id,
session_id: SESSION_ID,
});
} else {
const module = await func.common.get_module(SESSION_ID, `xuda-progs-loader-module.mjs`);
await module.load_objects_cache(SESSION_ID);
worker_post_message({
fx_to_execute: 'init_done',
worker_id: ws_worker_id,
session_id: SESSION_ID,
});
}
WEB_WORKER_CALLBACK_QUEUE[SESSION_ID] = {};
},
datasource_create: async function (params, promise_queue_id) {
var SESSION_ID = params.session_id;
var _session = SESSION_OBJ[SESSION_ID];
_session.ts = new Date().getTime();
var args = params;
args.SESSION_ID = SESSION_ID;
if (show_log) {
console.log('DATASOURCE EXECUTING SESSION_ID: ' + SESSION_ID, APP_OBJ[_session.app_id].app_name);
}
if (Number(params.dataSourceSessionGlobal) > _session.dataSourceSessionGlobal) {
_session.dataSourceSessionGlobal = Number(params.dataSourceSessionGlobal);
}
const ret = await func.datasource.prepare(
args.SESSION_ID,
args.prog_id,
args.dataSourceNoP,
args.parentDataSourceNoP,
args.containerIdP,
args.rowIdP,
args.jobNoP,
args.calling_trigger_prop,
args.parameters_raw_obj,
null,
args.callingSourceP,
args.calling_jobP,
args.screen_dsP,
args.is_panelP,
args.parameters_obj_inP,
args.static_refreshP,
args.run_atP,
args.worker_id,
);
try {
let _ds = _session.DS_GLB[ret.dsSessionP];
if (show_log) console.log('DATASOURCE EXECUTION DONE ' + ret.dsSessionP + ' ' + _ds?.tree_obj?.menuName || '' + ' SESSION_ID: ' + SESSION_ID, APP_OBJ[_session.app_id].app_name);
var obj = func.utils.clean_returned_datasource(SESSION_ID, ret?.dsSessionP);
obj.dataSourceSessionGlobal = _session.dataSourceSessionGlobal;
worker_post_message({
promise_queue_id,
params: obj,
worker_id: ws_worker_id,
session_id: SESSION_ID,
process_pid: params.process_pid,
service: params.service,
});
_ds.stat = 'idle';
} catch (error) {
console.error('[xuda-runtime] caught xuda_utils.js:606:', error);
}
},
datasource_delete: function (params, promise_queue_id) {
var SESSION_ID = params.session_id;
var _session = SESSION_OBJ[SESSION_ID];
if (DATASOURCE_INTERVALS[SESSION_ID] && DATASOURCE_INTERVALS[SESSION_ID][params.dssession]) {
DATASOURCE_INTERVALS[SESSION_ID][params.dssession].clear();
}
delete _session.DS_GLB[params.dssession];
if (show_log) console.log('DATASOURCE DELETE SESSION_ID: ' + SESSION_ID, APP_OBJ[_session.app_id].app_name, params.dssession);
console.error('[xuda-runtime] caught xuda_utils.js:617:', error);
worker_post_message({
promise_queue_id,
worker_id: ws_worker_id,
session_id: SESSION_ID,
process_pid: params.process_pid,
service: params.service,
});
},
update_datasource_changes_from_client: async function (params, promise_queue_id) {
if (xu_isEmpty(SESSION_OBJ)) return;
var SESSION_ID = params.session_id;
var _session = SESSION_OBJ[SESSION_ID];
if (!_session) {
_session = {};
_session.app_id = params.app_id;
_session.dataSourceSessionGlobal = -1;
_session.DS_GLB = {};
}
if (show_log) console.log('DATASOURCE UPDATE SESSION_ID: ' + SESSION_ID, APP_OBJ[_session.app_id].app_name, params.dssession);
await func.datasource.update(SESSION_ID, params.datasource_changes, true);
worker_post_message({
promise_queue_id,
params: params.dssession,
worker_id: ws_worker_id,
session_id: SESSION_ID,
process_pid: params.process_pid,
service: params.service,
});
},
return_to_data_source: function (params, promise_queue_id) {
var SESSION_ID = params.session_id;
var _session = SESSION_OBJ[SESSION_ID];
var ds = _session.DS_GLB[params.dssession];
var type = params.return_to_data_source_type;
var args = ds.args;
if (show_log) console.log('DATASOURCE RETURN TO DATASOURCE ' + params.dssession + ' SESSION_ID: ' + SESSION_ID, APP_OBJ[_session.app_id].app_name);
_session.DS_GLB[params.dssession].v.onscreen_events_active = params.onscreen_events_active;
if (params.viewEventExec_arr) _session.DS_GLB[params.dssession].viewEventExec_arr = JSON.parse(params.viewEventExec_arr);
var done = function (SESSION_ID, DS) {
if (show_log) console.log('DATASOURCE RETURN TO DATASOURCE DONE ' + DS + ' SESSION_ID: ' + SESSION_ID, APP_OBJ[_session.app_id].app_name);
var obj = func.utils.clean_returned_datasource(SESSION_ID, DS);
obj.dataSourceSessionGlobal = _session.dataSourceSessionGlobal;
worker_post_message({
fx_to_execute: 'post_datasource',
params: {
ds_obj: obj,
dsSessionP: params.dssession,
},
worker_id: ws_worker_id,
session_id: SESSION_ID,
process_pid: params.process_pid,
service: params.service,
});
};
done(SESSION_ID, params.dssession);
},
acknowledged_worker_with_eventChangesResults_done: function (params) {
var SESSION_ID = params.session_id;
var _session = SESSION_OBJ[SESSION_ID];
var ds = _session.DS_GLB[params.dssession];
if (show_log) console.log('UPDATE CHANGE EVENT DONE TO DATASOURCE ' + params.dssession + ' SESSION_ID: ' + SESSION_ID, APP_OBJ[_session.app_id].app_name);
ds.eventChangesResults_done = true;
},
return_from_db_query: function (params) {
var SESSION_ID = params.session_id;
var _session = SESSION_OBJ[SESSION_ID];
var id = params.id;
if (show_log) console.log('RETURN FROM DB_QUERY ' + params.dssession + ' SESSION_ID: ' + SESSION_ID, APP_OBJ[_session.app_id].app_name);
var callback = func.utils.get_callback_queue(SESSION_ID, params.callback_id);
if (callback) callback(params.data);
},
return_from_sava_data: function (params) {
var SESSION_ID = params.session_id;
var _session = SESSION_OBJ[SESSION_ID];
var id = params.id;
if (show_log) console.log('RETURN FROM SAVE_DATA ' + params.dssession + ' SESSION_ID: ' + SESSION_ID, APP_OBJ[_session.app_id].app_name);
func.utils.get_callback_queue(SESSION_ID, params.callback_id)();
},
update_debug_info: function (params) {
glb.DEBUG_INFO_OBJ = params;
},
// update_VIEWS_OBJ: function (params) {
// delete VIEWS_OBJ[APP_ID][params.id];
// },
// update_TREE_OBJ: function (params) {
// delete TREE_OBJ[APP_ID][params.id];
// },
// send_object_to_worker: function (params) {
// if (RESPONSE_FROM_STUDIO_QUEUE[params.req_id]) {
// RESPONSE_FROM_STUDIO_QUEUE[params.req_id].data = params;
// }
// },
get_dataSourceSessionGlobal: function (params) {
var SESSION_ID = params.session_id;
SESSION_OBJ[SESSION_ID].dataSourceSessionGlobal++;
let new_dataSourceSessionGlobal = SESSION_OBJ[SESSION_ID].dataSourceSessionGlobal;
return { new_dataSourceSessionGlobal };
},
create_webworker_globals: function (params) {
var SESSION_ID = params.session_id;
SESSION_OBJ[SESSION_ID].DS_GLB[0] = params.ds_data;
},
return_doc_from_studio: function (params) {
var SESSION_ID = params.session_id;
function emitCustomEvent(eventName, detail) {
const event = new CustomEvent(eventName, { detail });
self.dispatchEvent(event);
}
emitCustomEvent('live_preview_get_obj_response_worker_' + params._id, {
data: params,
});
},
return_doc_from_websocket: function (params) {
var SESSION_ID = params.session_id;
function emitCustomEvent(eventName, detail) {
const event = new CustomEvent(eventName, { detail });
self.dispatchEvent(event);
}
emitCustomEvent('get_doc_obj_from_build_worker_' + params._id, {
data: params,
});
},
return_dbs_data_from_websocket: function (params) {
var SESSION_ID = params.session_id;
function emitCustomEvent(eventName, detail) {
const event = new CustomEvent(eventName, { detail });
self.dispatchEvent(event);
}
emitCustomEvent('get_ws_data_worker_' + params.websocket_queue_num, {
data: params.data,
});
},
heartbeat: async function (params) {
var SESSION_ID = params.session_id;
try {
const do_heartbeat = async function (app_replicate, app_id, token_id, fingerprint, device_name, stat) {
try {
module.exports.close_expired_device_log_sessions(app_id);
return await update_device(app_replicate, app_id, token_id, fingerprint, device_name, stat);
} catch (err) {
return { code: -400, data: err.message };
}
};
let ret = await do_heartbeat(params.app_replicate, params.app_id, params.gtp_token || req.body.app_token, params.fingerprint, params.device_name, params.stat);
// session_status: ret_session.data.stat
if (params.token) {
try {
const couch = await __.rpi.get_app_couch(req.body.app_id);
const session_doc = await couch.get(req.body.app_token);
ret.session_stat = session_doc.stat;
} catch (error) {}
}
} catch (error) {
console.error('[xuda-runtime] caught xuda_utils.js:780:', error);
}
},
return_rpi_request_from_studio: function (params) {
var SESSION_ID = params.session_id;
function emitCustomEvent(eventName, detail) {
const event = new CustomEvent(eventName, { detail });
self.dispatchEvent(event);
}
emitCustomEvent('rpi_request_response_worker_' + params.table_id, {
data: params.data,
});
},
};
func.utils.set_callback_queue = function (SESSION_ID, func) {
var t = new Date().valueOf().toString() + Math.random().toString();
try {
WEB_WORKER_CALLBACK_QUEUE[SESSION_ID][t] = func;
} catch (e) {
console.error(id);
func.utils.remove_cached_objects(SESSION_ID);
}
return t;
};
func.utils.get_callback_queue = function (SESSION_ID, t) {
var func = WEB_WORKER_CALLBACK_QUEUE[SESSION_ID][t];
setTimeout(function () {
if (WEB_WORKER_CALLBACK_QUEUE[SESSION_ID][t]) delete WEB_WORKER_CALLBACK_QUEUE[SESSION_ID][t];
}, 1000);
return func;
};
func.utils.clean_stringify_null = function (key, value) {
// Filtering out properties
if (value === null) {
return undefined;
}
return value;
};
func.utils.load_js_on_demand = async function (js_src, type) {
const normalized_src = typeof js_src === 'string' ? js_src.trim() : '';
if (!normalized_src || normalized_src === 'undefined' || normalized_src === 'null') {
return false;
}
const get_script = function (callback) {
if (glb.IS_WORKER) {
callback();
return;
}
function isScriptLoaded(src) {
return GLB_JS_SCRIPTS_LOADED.includes(src);
}
if (isScriptLoaded(normalized_src)) {
callback(false);
} else {
func.runtime.platform.load_script(normalized_src, type, function () {
callback(true);
GLB_JS_SCRIPTS_LOADED.push(normalized_src);
});
}
};
return new Promise((resolve) => {
get_script(resolve);
});
};
func.utils.load_css_on_demand = function (css_href) {
const normalized_href = typeof css_href === 'string' ? css_href.trim() : '';
if (!normalized_href || normalized_href === 'undefined' || normalized_href === 'null') {
return null;
}
return func.runtime.platform.load_css(normalized_href);
};
func.utils.remove_js_css_file = function (filename, filetype) {
func.runtime.platform.remove_js_css(filename, filetype);
};
func.utils.replace_studio_drive_url = function (SESSION_ID, val) {
var _session = SESSION_OBJ[SESSION_ID];
if (!_session.is_deployment) return val;
try {
const rep = APP_OBJ[_session.app_id].app_replicate;
const dest = `https://${_session.domain}/studio-drive/${rep}`;
const rep_esc = rep.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
// Rewrite every legacy studio-drive host to the live domain: stale xuda.io hardcodings,
// and any xuda.ai host incl. subdomains (xuda.ai, master.xuda.ai, eu.xuda.ai, ...).
return val
.replaceAll(`https://xuda.io/studio-drive/${rep}`, dest)
.replace(new RegExp(`https://(?:[a-z0-9-]+\\.)*xuda\\.ai/studio-drive/${rep_esc}`, 'g'), dest);
} catch (err) {
return val;
}
};
func.utils.get_drive_url = function (SESSION_ID, val, wrap) {
// wrap = false; // tbd bypass
var _session = SESSION_OBJ[SESSION_ID];
function replaceFiletoURL(fileString) {
const _app = APP_OBJ[_session.app_id];
let url = `https://${_session.domain}/workspace-drive/${_app.is_deployment ? _app.app_datacenter_id : _app.app_id_reference}/`;
let FILE_REPLACE_URL = `${url}${val}`;
if (!_app.is_deployment) {
// the deployment server will handle the app_token
FILE_REPLACE_URL += `?app_token=${_session.app_token}&ts=${Date.now()}`;
} else {
FILE_REPLACE_URL += `?ts=${_session?.opt?.app_build_id || 0}`;
}
let match = `drv_${_app.app_replicate || _session.app_id}_[0-9a-f\\-]+\\.[a-zA-Z0-9]+`;
let pat = new RegExp(match, 'g');
let URLString = fileString.replace(pat, function (match, idx) {
const hasURLbefore = fileString.substring(idx - url.length, idx) === url;
if (hasURLbefore) {
return match;
}
return FILE_REPLACE_URL.replace('{val}', match);
});
return URLString;
}
if (typeof val === 'string' || typeof val === 'object') {
if (typeof val === 'string') {
if (val.includes('.') && val.includes('drv_') && val.length > 30) {
var ret = replaceFiletoURL(val);
if (wrap) {
return { value: '"' + ret + '"', changed: true };
} else {
return { value: ret, changed: true };
}
} else {
return { value: val, changed: false };
}
}
if (typeof val === 'object') {
// XU_PERF fast path: stringifying every bound object per evaluation just
// to look for 'drv_' is a hot-loop tax. Clean verdicts are memoized per
// object reference; datasource.update clears the cache, so a mutation can
// never outlive the refresh that would re-evaluate it. Only on a
// (possible) hit fall through to the exact legacy stringify path.
if (glb.XU_PERF) {
if (func.utils.drive_ref_clean_cache.has(val)) {
return { value: val, changed: false };
}
if (!func.utils.has_drive_ref(val, 0)) {
func.utils.drive_ref_clean_cache.add(val);
return { value: val, changed: false };
}
}
try {
let str = JSON.stringify(val);
if (str.includes('.') && str.includes('drv_') && str.length > 30) {
let new_val = replaceFiletoURL(str);
return { value: new_val, changed: true };
} else {
return { value: val, changed: false };
}
} catch (err) {
return { value: val, changed: false };
}
}
} else {
return { value: val, changed: false };
}
};
func.utils.drive_ref_clean_cache = new WeakSet();
// Early-exit scan for 'drv_' drive-file references in keys or string values.
// Returns true on any hit OR when traversal gives up (depth cap), so callers
// fall back to the exact legacy stringify detection in those cases.
func.utils.has_drive_ref = function (v, depth) {
if (typeof v === 'string') return v.includes('drv_');
if (v === null || typeof v !== 'object') return false;
if (depth > 8) return true; // too deep to be sure: let legacy path decide
if (Array.isArray(v)) {
for (let i = 0; i < v.length; i++) {
if (func.utils.has_drive_ref(v[i], depth + 1)) return true;
}
return false;
}
for (const k in v) {
if (k.includes('drv_')) return true;
if (func.utils.has_drive_ref(v[k], depth + 1)) return true;
}
return false;
};
func.utils._error_registry_module = func.utils._error_registry_module || null;
func.utils._error_registry_pending = func.utils._error_registry_pending || null;
func.utils.get_error_registry = async function (SESSION_ID) {
if (func.utils._error_registry_module) {
return func.utils._error_registry_module;
}
if (func.utils._error_registry_pending) {
return await func.utils._error_registry_pending;
}
if (!SESSION_ID || !SESSION_OBJ?.[SESSION_ID]) {
return null;
}
func.utils._error_registry_pending = func.common
.get_module(SESSION_ID, 'xuda-error-registry-module.mjs')
.then((module) => {
func.utils._error_registry_module = module;
return module;
})
.catch((err) => {
console.warn('XUDA WARNING RUN_MSG_NET_010', 'Failed to load error registry module', err);
return null;
})
.finally(() => {
func.utils._error_registry_pending = null;
});
return await func.utils._error_registry_pending;
};
func.utils._normalize_issue_severity = function (type, fallback = 'error') {
if (!type) return fallback;
const normalized = type.toString().toLowerCase();
if (['w', 'warn', 'warning'].includes(normalized)) return 'warning';
if (['i', 'info', 'log'].includes(normalized)) return 'info';
return 'error';
};
func.utils._serialize_issue_value = function (value, seen = new WeakSet()) {
if (value instanceof Error) {
return {
name: value.name,
message: value.message,
stack: value.stack,
cause: value.cause,
};
}
if (typeof value === 'undefined' || value === null) {
return value;
}
if (typeof value === 'function') {
return `[Function ${value.name || 'anonymous'}]`;
}
if (typeof value !== 'object') {
return value;
}
if (seen.has(value)) {
return '[Circular]';
}
seen.add(value);
if (Array.isArray(value)) {
return value.map((item) => func.utils._serialize_issue_value(item, seen));
}
const ret = {};
for (const [key, val] of Object.entries(value)) {
ret[key] = func.utils._serialize_issue_value(val, seen);
}
return ret;
};
func.utils._stringify_issue_message = function (value) {
if (typeof value === 'undefined' || value === null) {
return '';
}
if (typeof value === 'string') {
return value;
}
if (value instanceof Error) {
return value.message || value.toString();
}
try {
return JSON.stringify(func.utils._serialize_issue_value(value));
} catch (error) {
return value?.toString?.() || '';
}
};
func.utils._build_fallback_issue_definition = function (payload = {}) {
const code = payload.code || 'RUN_MSG_GEN_000';
const severity = func.utils._normalize_issue_severity(payload.type || payload.severity, code.startsWith('CHK_MSG_') ? 'warning' : 'error');
return {
code,
title: payload.title || (code.startsWith('CHK_MSG_') ? 'Studio Checker Validation Issue' : 'Runtime Error'),
severity,
domain: code.startsWith('CHK_MSG_') ? 'checker' : 'runtime',
category: payload.category || 'general',
summary: payload.message || 'The runtime reported an issue.',
help_slug: payload.help_slug || code.toLowerCase().replace(/_/g, '-'),
};
};
func.utils.report_issue = async function (SESSION_ID, payload = {}) {
const err = payload.err instanceof Error ? payload.err : payload.error instanceof Error ? payload.error : null;
const source = payload.source || payload.method || 'runtime';
const message = func.utils._stringify_issue_message(
typeof payload.message !== 'undefined' ? payload.message : typeof payload.msg !== 'undefined' ? payload.msg : err || payload.details || 'Unknown runtime issue',
);
try {
const registry = await func.utils.get_error_registry(SESSION_ID);
const registry_payload = {
code: payload.code,
source,
message,
type: payload.type || payload.severity,
err,
details: payload.details,
category: payload.category,
};
let definition = null;
if (registry?.get_error_definition && payload.code) {
definition = registry.get_error_definition(payload.code, registry_payload);
}
if (!definition && registry?.get_runtime_report_definition) {
definition = registry.get_runtime_report_definition(registry_payload);
}
if (!definition) {
definition = func.utils._build_fallback_issue_definition({
...payload,
source,
message,
});
}
const severity = func.utils._normalize_issue_severity(payload.type || payload.severity, definition.severity || 'error');
const error_code = definition.code || payload.code || 'RUN_MSG_GEN_000';
const error_title = definition.title || payload.title || 'Runtime Error';
const help_slug = definition.help_slug || error_code.toLowerCase().replace(/_/g, '-');
const console_method = severity === 'warning' ? 'warn' : severity === 'info' ? 'log' : 'error';
const _session = SESSION_OBJ?.[SESSION_ID];
const report = {
error_code,
error_title,
help_slug,
severity,
error_domain: definition.domain || 'runtime',
error_category: definition.category || payload.category || 'general',
source,
message,
stack: err?.stack || null,
app_id: _session?.app_id || payload.app_id || null,
session_id: SESSION_ID || null,
worker: !!glb?.IS_WORKER,
summary: definition.summary || message,
};
const details = {
report,
error: func.utils._serialize_issue_value(err),
context: func.utils._serialize_issue_value(payload.details),
extra: func.utils._serialize_issue_value(payload.extra),
};
const console_prefix = `XUDA ${console_method.toUpperCase()} ${error_code}`;
const console_summary = `${error_title}: ${source}${message ? ' | ' + message : ''}`;
if (glb?.debug_js && console.groupCollapsed) {
console.groupCollapsed(console_prefix, console_summary);
console[console_method](report);
if (details.context) console.log('context', details.context);
if (err) console.error(err);
console.groupEnd();
} else {
console[console_method](console_prefix, console_summary, {
help_slug,
});
}
if (!payload.skip_log && SESSION_ID && _session) {
await func.utils.write_log(SESSION_ID, source, message || error_title, console_method, payload.log_source || 'runtime', details, report);
}
return report;
} catch (report_err) {
console.error('XUDA ERROR RUN_MSG_GEN_000', 'Failed to report runtime issue', report_err, {
source,
message,
payload,
});
return null;
}
};
func.utils.debug_report = async function (SESSION_ID, sourceP, msgP, typeP, errP, objP) {
if (!typeP || typeP === 'E') {
setTimeout(() => {
// if (
// typeof IS_DOCKER === "undefined" &&
// typeof IS_API_SERVER === "undefined" &&
// typeof IS_PROCESS_SERVER === "undefined" &&
// !glb?.IS_WORKER
// ) {
// func.index.delete_pouch(SESSION_ID);
// }
}, 1000);
}
await func.utils.report_issue(SESSION_ID, {
source: sourceP,
message: msgP,
type: typeP,
err: errP,
details: objP,
});
};
func.utils.request_error = function (SESSION_ID, type, e) {
var _session = SESSION_OBJ[SESSION_ID];
console.error(type, e);
if (typeof IS_PROCESS_SERVER !== 'undefined') return;
if (!glb.IS_WORKER) {
func.utils.debug_report(SESSION_ID, type, e, 'E');
setTimeout(function () {
if (!glb.debug_js) {
// location.reload();
console.warn('** reload request');
}
}, 2000);
} else {
func.utils.post_back_to_client(SESSION_ID, 'ajax_error', _session.worker_id, null);
}
};
func.utils.alerts = {};
func.utils.alerts.invoke = async function (SESSION_ID, typeP, paramsP, sourceP, dsSessionP, msgP) {
try {
var _session = SESSION_OBJ[SESSION_ID];
if (ALERT_IS_ACTIVE) return;
ALERT_IS_ACTIVE = true;
var title;
var message = '';
var alert_type = 'console';
var alertDisplay;
var expRet = {};
var _ds = _session.DS_GLB[dsSessionP];
var type = '';
var createLog;
const get_alert_properties = async function (value, fx) {
var ret = value || '';
if (fx) {
const exp_ret = await func.expression.get(SESSION_ID, fx, dsSessionP, 'alert');
ret = exp_ret.result;
}
return ret;
};
switch (typeP) {
case 'alert':
type = 'User defined alert';
title = await get_alert_properties(paramsP.alertTitle, paramsP.alertTitleFx);
alert_type = await get_alert_properties(paramsP.alertType, paramsP.alertTypeFx);
message = await get_alert_properties(paramsP.alertBody, paramsP.alertBodyFx);
alertDisplay = await get_alert_properties(paramsP.alertDisplay, paramsP.alertDisplayFx);
createLog = paramsP.createLog;
break;
case 'call_alert':
type = 'User defined call alert';
let prop = await func.utils.TREE_OBJ.get(SESSION_ID, paramsP.prog);
if (!prop) {
console.log('events.execute', 'Missing details for alert message object: ' + paramsP.prog, 'W');
}
// user defined
let ret = await func.utils.VIEWS_OBJ.get(SESSION_ID, paramsP.prog);
if (ret?.alertData) {
title = await get_alert_properties(ret.alertData.alertTitle, ret.alertData.alertTitleFx);
alert_type = await get_alert_properties(ret.alertData.alertType, ret.alertData.alertTypeFx);
message = await get_alert_properties(ret.alertData.alertBody, ret.alertData.alertBodyFx);
alertDisplay = await get_alert_properties(ret.alertData.alertDisplay, ret.alertData.alertDisplayFx);
createLog = ret.alertData.createLog;
}
if (!title) {
title = prop.menuTitle;
}
if (!alert_type) {
alert_type = 'console';
}
if (!alertDisplay) {
alertDisplay = 'modal';
} //window alert by definition
break;
case 'system_msg': {
type = 'System alert';
const sys_alerts_obj = func.utils.get_system_error_msg();
if (sys_alerts_obj[paramsP]) {
title = sys_alerts_obj[paramsP].subject;
alert_type = sys_alerts_obj[paramsP].alert_type;
alertDisplay = sys_alerts_obj[paramsP].alertDisplay;
expRet = await func.expression.get(SESSION_ID, sys_alerts_obj[paramsP].msg, dsSessionP, 'alert');
message = func.expression.remove_quotes(expRet.result);
if (msgP) message = msgP;
if (alert_type === 'error') {
if (_ds) _ds.error = title + ' ' + sourceP;
func.utils.debug_report(SESSION_ID, sourceP, title + ' ' + sourceP, 'E', '', _ds);
}
}
break;
}
default:
message = msgP;
break;
}
} catch (err) {
console.error(err);
ALERT_IS_ACTIVE = false;
return;
}
if (glb.IS_WORKER) {
if (_session.IS_API) {
if (_ds) {
_ds.api_rendered_output = message;
} else {
console.error(message);
}
return;
}
// if (typeof IS_PROCESS_SERVER !== "undefined") return;
ALERT_IS_ACTIVE = false;
return func.utils.post_back_to_client(SESSION_ID, 'alert', _session.worker_id, [SESSION_ID, alert_type, alertDisplay, message, title]);
}
// const sys_alerts_obj = func.utils.get_system_error_msg();
// if (sys_alerts_obj[paramsP]) {
// var str = paramsP + " " + title + " " + message;
// if (sys_alerts_obj[paramsP].alert_type === "error") {
// console.error(str);
// } else if (sys_alerts_obj[paramsP].alert_type === "warning") {
// console.warn(str);
// } else {
// console.log(str);
// }
// } else {
// console.log(str);
// }
ALERT_IS_ACTIVE = false;
func.utils.alerts.execute(SESSION_ID, alert_type, alertDisplay, message, title, type);
if (createLog) {
func.utils.write_log(SESSION_ID, title, message, alert_type);
}
};
func.utils.alerts.execute = function (SESSION_ID, alert_type, alertDisplay, message, title, type) {
if (!UI_FRAMEWORK_INSTALLED) {
ALERT_IS_ACTIVE = false;
if (alertDisplay !== 'console') {
return alert(title + '\n \n' + message);
}
return console[alert_type === 'error' ? 'error' : 'log'](alert_type, title, message);
}
switch (alertDisplay) {
case 'console':
console[alert_type === 'success' ? 'log' : alert_type === 'warning' ? 'warn' : alert_type](alert_type, title, message);
ALERT_IS_ACTIVE = false;
break;
case 'modal':
func.utils.alerts.popup(title, message, alert_type);
break;
case 'toast':
func.utils.alerts.toast(SESSION_ID, title, message, alert_type);
ALERT_IS_ACTIVE = false;
break;
case 'browser':
alert(title + '\n \n' + message);
ALERT_IS_ACTIVE = false;
default:
console.log(alert_type, title, message);
ALERT_IS_ACTIVE = false;
}
};
func.utils.alerts.toast = function (SESSION_ID, title, message, alert_type) {
if (!UI_FRAMEWORK_PLUGIN.toast) return;
const toast = new UI_FRAMEWORK_PLUGIN.toast();
toast.create(alert_type, message, title, func.common.get_url(SESSION_ID, 'dist', `runtime/images/${alert_type}_alert_ico.svg`));
ALERT_IS_ACTIVE = false;
};
func.utils.alerts.popup = function (title, message, alert_type) {
const popup = new UI_FRAMEWORK_PLUGIN.popup();
var buttons = [
{
text: 'Ok',
role: 'cancel',
// cssClass: "primary",
handler: () => {
ALERT_IS_ACTIVE = false;
},
},
];
popup.create(alert_type.charAt(0).toUpperCase() + alert_type.slice(1), title, message, buttons);
};
func.utils.get_system_error_msg = function () {
var m = {};
m['SYS_MSG_0101'] = {
alert_type: 'success',
alertDisplay: 'toast',
subject: 'Save Success',
msg: 'Settings successfully saved',
};
m['SYS_MSG_0102'] = {
alert_type: 'error',
alertDisplay: 'toast',
subject: 'Save Failed CouchDB',
msg: 'Data fail save to database',
};
m['SYS_MSG_0103'] = {
alert_type: 'error',
alertDisplay: 'toast',
subject: 'Save Failed Table Empty',
msg: 'Table empty, no fields declared',
};
m['SYS_MSG_0104'] = {
alert_type: 'error',
alertDisplay: 'toast',
subject: 'Save Failed Missing Primary Index',
msg: 'Update failed, table missing Primary index',
};
m['SYS_MSG_0105'] = {
alert_type: 'error',
alertDisplay: 'toast',
subject: 'Save Failed Table Missing',
msg: 'Table repository missing',
};
m['SYS_MSG_0106'] = {
alert_type: 'error',
alertDisplay: 'toast',
subject: 'Save Failed Record Not Exist',
msg: 'Save update failed record not exist',
};
m['SYS_MSG_0107'] = {
alert_type: 'error',
alertDisplay: 'modal',
subject: 'Save Failed Unique Key',
msg: 'Save Failed, record already exist',
};
m['SYS_MSG_0108'] = {
alert_type: 'error',
alertDisplay: 'modal',
subject: 'Error reading document',
msg: 'Save Failed, record not found',
};
m['SYS_MSG_0110'] = {
alert_type: 'warning',
alertDisplay: 'toast',
subject: 'Record Changed',
msg: 'Record changed by other user, reload to get the latest changes',
};
m['SYS_MSG_0120'] = {
alert_type: 'error',
alertDisplay: 'modal',
subject: 'Create Mode Denied',
msg: 'Create mode not allowed for this program',
};
m['SYS_MSG_0122'] = {
alert_type: 'error',
alertDisplay: 'modal',
subject: 'Modify Mode Denied',
msg: 'Modify mode not allowed for this program',
};
m['SYS_MSG_0124'] = {
alert_type: 'error',
alertDisplay: 'modal',
subject: 'Delete Mode Denied',
msg: 'Delete mode not allowed for this program',
};
m['SYS_MSG_0126'] = {
alert_type: 'error',
alertDisplay: 'modal',
subject: 'Program Read Only',
msg: 'Program set to Read Only',
};
m['SYS_MSG_0130'] = {
alert_type: 'error',
alertDisplay: 'modal',
subject: 'Error Reduce',
msg: 'Select Index to Reduce',
};
m['SYS_MSG_0201'] = {
alert_type: 'error',
alertDisplay: 'toast',
subject: 'Failed to change GUI Property',
msg: 'Failed to change GUI element property, GUI element missing',
};
m['SYS_MSG_0310'] = {
alert_type: 'error',
alertDisplay: 'toast',
subject: 'Missing Reference Parameters Out',
msg: 'Parameter out not exist in dataset',
};
m['SYS_MSG_0400'] = {
alert_type: 'error',
alertDisplay: 'modal',
subject: 'Delete Widget Folder Denied',
msg: 'The selected folder contains data, Please clean or move content to another folder',
};
m['SYS_MSG_0410'] = {
alert_type: 'error',
alertDisplay: 'toast',
subject: 'Recipient Error',
msg: 'Check recipient data',
};
m['SYS_MSG_0412'] = {
alert_type: 'error',
alertDisplay: 'modal',
subject: 'Recipient Empty',
msg: 'No recipients entered or selected',
};
m['SYS_MSG_0414'] = {
alert_type: 'error',
alertDisplay: 'modal',
subject: 'Data Save Error',
msg: 'Widget has no content',
};
m['SYS_MSG_0416'] = {
alert_type: 'error',
alertDisplay: 'modal',
subject: 'Required Field',
msg: 'Edit url field is empty',
};
m['SYS_MSG_0418'] = {
alert_type: 'error',
alertDisplay: 'modal',
subject: 'Required Field',
msg: 'Publish url field is empty',
};
m['SYS_MSG_0420'] = {
alert_type: 'error',
alertDisplay: 'modal',
subject: 'Connection Error',
msg: 'Cannot connect to mailbox',
};
m['SYS_MSG_0422'] = {
alert_type: 'success',
alertDisplay: 'modal',
subject: 'Connection Ok',
msg: 'Connection Ok :)',
};
m['SYS_MSG_0424'] = {
alert_type: 'error',
alertDisplay: 'modal',
subject: 'Connection Failed',
msg: 'Connection to POP3 failed',
};
m['SYS_MSG_0426'] = {
alert_type: 'error',
alertDisplay: 'modal',
subject: 'Connection Failed',
msg: 'SMTP Connection error, Test Email was not sent',
};
m['SYS_MSG_0430'] = {
alert_type: 'error',
alertDisplay: 'toast',
subject: 'Email Account Error',
msg: 'No email account found, Right Click Tree -> Settings->Manage Accounts -> Right click for menu options',
};
m['SYS_MSG_0440'] = {
alert_type: 'error',
alertDisplay: 'modal',
subject: 'Widget Initiation Error',
msg: 'Missing information for Link Type or Link Name',
};
m['SYS_MSG_0442'] = {
alert_type: 'error',
alertDisplay: 'modal',
subject: 'Error Init Widget',
msg: 'Missing record Id on Create Mode',
};
m['SYS_MSG_0450'] = {
alert_type: 'error',
alertDisplay: 'modal',
subject: 'Validation Failed',
msg: 'Fix fields highlight in Red',
};
m['SYS_MSG_0501'] = {
alert_type: 'error',
alertDisplay: 'modal',
subject: 'Mandatory Alert Save',
msg: 'Save action failed, Mandatory fields missing',
};
m['SYS_MSG_0550'] = {
alert_type: 'error',
alertDisplay: 'toast',
subject: 'Illegal input number',
msg: "@SYS_GLOBAL_OBJ_ACTIVE_FIELD_INFO.nameform +' only allow numbers!'",
};
m['SYS_MSG_0610'] = {
alert_type: 'error',
alertDisplay: 'toast',
subject: 'Form Field Conflict',
msg: 'Field declared more than once for the form',
};
m['SYS_MSG_0612'] = {
alert_type: 'error',
alertDisplay: 'toast',
subject: 'Mask Error - Missing Definition',
msg: 'Missing mask definition',
};
m['SYS_MSG_0614'] = {
alert_type: 'error',
alertDisplay: 'toast',
subject: 'Mask Error - Wrong Definition',
msg: 'Wrong mask definition',
};
m['SYS_MSG_0616'] = {
alert_type: 'error',
alertDisplay: 'toast',
subject: 'Mask Error - Size Parser',
msg: 'Size parser error',
};
m['SYS_MSG_0618'] = {
alert_type: 'error',
alertDisplay: 'toast',
subject: 'Mask Error - Illegal Z switch',
msg: "Illegal 'Z' in string mask",
};
m['SYS_MSG_0620'] = {
alert_type: 'error',
alertDisplay: 'toast',
subject: 'Mask Error - Illegal N switch',
msg: "Illegal 'N' in string mask",
};
m['SYS_MSG_0622'] = {
alert_type: 'error',
alertDisplay: 'toast',
subject: 'Mask Error - Illegal + switch',
msg: "Illegal '+' in string mask",
};
m['SYS_MSG_0624'] = {
alert_type: 'error',
alertDisplay: 'toast',
subject: 'Mask Error - Illegal - switch',
msg: "Illegal '-' in string mask",
};
m['SYS_MSG_0626'] = {
alert_type: 'error',
alertDisplay: 'toast',
subject: 'Mask Error - Illegal C switch',
msg: "Illegal 'C' in string mask",
};
m['SYS_MSG_0628'] = {
alert_type: 'error',
alertDisplay: 'toast',
subject: 'Mask Error - Invalid switch',
msg: 'Invalid switch in string mask',
};
m['SYS_MSG_0630'] = {
alert_type: 'error',
alertDisplay: 'toast',
subject: 'Mask Error - Missing DOM Element',
msg: 'Missing DOM element',
};
m['SYS_MSG_0632'] = {
alert_type: 'error',
alertDisplay: 'toast',
subject: 'Mask Error - Too Big',
msg: 'Size to big, max: 15.5',
};
m['SYS_MSG_0700'] = {
alert_type: 'warning',
alertDisplay: 'console',
subject: 'Table Warning - Empty',
msg: 'Table has no content',
};
m['SYS_MSG_0702'] = {
alert_type: 'error',
alertDisplay: 'console',
subject: 'Table Error - No Fields',
msg: 'Table missing fields content',
};
m['SYS_MSG_0704'] = {
alert_type: 'warning',
alertDisplay: 'console',
subject: 'Table Warning - Not In Use',
msg: 'Table not in use by any object',
};
m['SYS_MSG_0706'] = {
alert_type: 'error',
alertDisplay: 'console',
subject: 'Table Error - No Primary Index',
msg: 'Table must have at least one index',
};
m['SYS_MSG_0708'] = {
alert_type: 'error',
alertDisplay: 'console',
subject: 'Table Error - Bad Index Name',
msg: 'Index name is invalid or cannot contain any of non word characters',
};
m['SYS_MSG_0710'] = {
alert_type: 'error',
alertDisplay: 'console',
subject: 'Table Error - Empty Index',
msg: 'Index has no keys',
};
m['SYS_MSG_0712'] = {
alert_type: 'error',
alertDisplay: 'console',
subject: 'Table Error - Key Not Exist',
msg: 'Key not exist in the table fields repository',
};
m['SYS_MSG_0714'] = {
alert_type: 'error',
alertDisplay: 'console',
subject: 'Table Error - Duplicate Fields',
msg: 'Duplicate fields in the table fields repository',
};
m['SYS_MSG_0716'] = {
alert_type: 'error',
alertDisplay: 'console',
subject: 'Table Error - Bad Field Name',
msg: 'Field name is invalid or cannot contain any of non word characters',
};
m['SYS_MSG_0718'] = {
alert_type: 'error',
alertDisplay: 'console',
subject: 'Table Error - Integrity Broken',
msg: 'Field broken from its properties, edit the field and save',
};
m['SYS_MSG_0720'] = {
alert_type: 'error',
alertDisplay: 'console',
subject: 'Table Error - Model Not Exist',
msg: 'Model assigned to the field not exist',
};
m['SYS_MSG_0722'] = {
alert_type: 'warning',
alertDisplay: 'console',
subject: 'Object Warning - Not In Use',
msg: 'Object not in use or not call by any object',
};
m['SYS_MSG_0724'] = {
alert_type: 'error',
alertDisplay: 'console',
subject: 'Object Error - Table Not Exist',
msg: 'Table assigned in object datasource not exist',
};
m['SYS_MSG_0726'] = {
alert_type: 'error',
alertDisplay: 'console',
subject: 'Object Error - Index Keys Mismatch',
msg: 'Table index has different structure',
};
m['SYS_MSG_0728'] = {
alert_type: 'error',
alertDisplay: 'console',
subject: 'Object Error - Index Key From Empty',
msg: 'Index key From must have a value',
};
m['SYS_MSG_0730'] = {
alert_type: 'error',
alertDisplay: 'console',
subject: 'Object Error - Index Key From Reference',
msg: 'Field reference not exist in any dataset or parameters',
};
m['SYS_MSG_0732'] = {
alert_type: 'error',
alertDisplay: 'console',
subject: 'Object Error - Index Key To Empty',
msg: 'Index key To must have a value',
};
m['SYS_MSG_0734'] = {
alert_type: 'error',
alertDisplay: 'console',
subject: 'Object Error - Index Key To Reference',
msg: 'Field reference not exist in any dataset or parameters',
};
m['SYS_MSG_0736'] = {
alert_type: 'error',
alertDisplay: 'console',
subject: 'Object Error - Index Locate From Reference',
msg: 'Field reference not exist in any dataset or parameters',
};
m['SYS_MSG_0738'] = {
alert_type: 'error',
alertDisplay: 'console',
subject: 'Object Error - Index Locate To Reference',
msg: 'Field reference not exist in any dataset or parameters',
};
m['SYS_MSG_0740'] = {
alert_type: 'error',
alertDisplay: 'console',
subject: 'Object Error - Index Empty',
msg: 'Index empty - no keys defined',
};
m['SYS_MSG_0742'] = {
alert_type: 'error',
alertDisplay: 'console',
subject: 'Object Error - Index Reference',
msg: 'Table index reference error',
};
m['SYS_MSG_0744'] = {
alert_type: 'error',
alertDisplay: 'console',
subject: 'Object Error - Duplicate Fields',
msg: 'Duplicate fields in the dataset fields repository',
};
m['SYS_MSG_0746'] = {
alert_type: 'error',
alertDisplay: 'console',
subject: 'Object Error - Field reference error',
msg: 'Field not exist in datasource table fields repository',
};
m['SYS_MSG_0748'] = {
alert_type: 'error',
alertDisplay: 'console',
subject: 'Object Error - Mismatch Reference Type',
msg: 'Mismatch in calling reference type',
};
m['SYS_MSG_0750'] = {
alert_type: 'error',
alertDisplay: 'console',
subject: 'Object Error - Reference Broken',
msg: 'Reference broken calling object not exist',
};
m['SYS_MSG_0752'] = {
alert_type: 'error',
alertDisplay: 'console',
subject: 'Object Error - Empty Reference',
msg: 'Reference empty',
};
m['SYS_MSG_0754'] = {
alert_type: 'error',
alertDisplay: 'console',
subject: 'Object Error - Action Not Exist',
msg: 'Action not exist',
};
m['SYS_MSG_0756'] = {
alert_type: 'error',
alertDisplay: 'console',
subject: 'Object Error - Empty Event Reference',
msg: 'Empty event reference',
};
m['SYS_MSG_0758'] = {
alert_type: 'error',
alertDisplay: 'console',
subject: 'Object Error - Bad Field Name',
msg: 'Field name is invalid or cannot contain any of non word characters',
};
m['SYS_MSG_0760'] = {
alert_type: 'error',
alertDisplay: 'console',
subject: 'Object Error - Integrity Broken',
msg: 'Field broken from its properties, edit the object and save',
};
m['SYS_MSG_0762'] = {
alert_type: 'error',
alertDisplay: 'console',
subject: 'Object Error - Model Not Exist',
msg: 'Model assigned to the field not exist',
};
m['SYS_MSG_0764'] = {
alert_type: 'error',
alertDisplay: 'console',
subject: 'Object Error - Empty Dataset',
msg: 'Dataset empty from fields',
};
m['SYS_MSG_0766'] = {
alert_type: 'error',
alertDisplay: 'console',
subject: 'Object Error - Field Type Mismatch',
msg: 'Field type not match to the underlined table field definition',
};
m['SYS_MSG_0768'] = {
alert_type: 'error',
alertDisplay: 'console',
subject: 'Object Error - Field Mask Mismatch',
msg: 'Field masks not match to the underlined table field definition',
};
m['SYS_MSG_0770'] = {
alert_type: 'error',
alertDisplay: 'console',
subject: 'Object Error - Bad Event Name',
msg: 'Event name is invalid or cannot contain any of non word characters',
};
m['SYS_MSG_0772'] = {
alert_type: 'error',
alertDisplay: 'console',
subject: 'Object Error - UI Field Not Exist',
msg: 'UI Field not exist in the dataset repository',
};
m['SYS_MSG_0774'] = {
alert_type: 'error',
alertDisplay: 'console',
subject: 'Object Error - UI Field Reference Broken',
msg: 'UI Field reference broken',
};
m['SYS_MSG_0780'] = {
alert_type: 'error',
alertDisplay: 'toast',
subject: 'UI element error',
msg: 'UI element not exist',
};
m['SYS_MSG_1210'] = {
alert_type: 'error',
alertDisplay: 'modal',
subject: 'Program error',
msg: 'Program not exist',
};
m['SYS_MSG_1220'] = {
alert_type: 'error',
alertDisplay: 'modal',
subject: 'Program error',
msg: 'Non grid output defined',
};
m['SYS_MSG_1240'] = {
alert_type: 'error',
alertDisplay: 'toast',
subject: 'Debug error',
msg: '',
};
m['SYS_MSG_1250'] = {
alert_type: 'error',
alertDisplay: 'toast',
subject: 'Debug log error',
msg: '',
};
m['SYS_MSG_1260'] = {
alert_type: 'error',
alertDisplay: 'toast',
subject: 'Session Expired',
msg: 'Renew token session in Studio',
};
return m;
};
func.utils.find_key_in_ViewUITreeObj = function (arr, key, val) {
return arr.reduce((a, item) => {
if (a) return a;
if (item[key] === val) return item;
if (item.children) return findId(val, item.children);
}, null);
};
func.utils.get_plugin_setup = function (SESSION_ID, plugin_name) {
const _session = SESSION_OBJ[SESSION_ID];
const normalize_setup_response = function (value) {
if (value && typeof value === 'object' && Object.prototype.hasOwnProperty.call(value, 'code')) {
return value;
}
return {
code: 1,
data: value && typeof value === 'object' ? value : {},
};
};
const report_error = function (descP, warn) {
func.utils.debug.log(SESSION_ID, plugin_name, {
module: 'plugin',
action: 'Init',
source: 'get_plugin_setup',
prop: descP,
details: descP,
result: null,
error: warn ? false : true,
fields: null,
type: 'plugin',
});
};
return new Promise(async (resolve, reject) => {
try {
const db = await func.utils.connect_pouchdb(SESSION_ID);
const should_bypass_cache =
_session?.worker_type === 'Dev' ||
(_session?.engine_mode === 'miniapp' && !_session?.app_token);
if (!should_bypass_cache) {
try {
let ret = await db.get(`cache_plugin_setup_${plugin_name}`);
return resolve(normalize_setup_response(ret.data));
} catch (err) {
// cache miss
}
}
const json = normalize_setup_response(await func.common.db(SESSION_ID, 'get_plugin_setup', {
plugin_name,
}));
if (json.code < 0) {
report_error('Error: ' + json.data, json.error_type === 'W' ? true : false);
}
resolve(json);
if (!should_bypass_cache) {
var doc = {
_id: `cache_plugin_setup_${plugin_name}`,
data: json,
docType: 'cache_plugin',
};
db.put(doc);
}
} catch (e) {
console.error(e);
const error_message = e?.message || e?.msg || String(e || 'Unknown plugin setup error');
report_error('Error: ' + error_message, e?.error_type === 'W' ? true : false);
resolve({
code: -1,
data: error_message,
error_type: e?.error_type,
});
}
});
};
func.utils.connect_studio_pouchdb = function (app_id, rt, custom) {
if (custom) {
return new PouchDB(custom, { auto_compaction: true });
}
var db_name = 'xuda_studio_db';
if (app_id) {
db_name += '_' + app_id;
}
if (rt) {
db_name = `xuda_rt_${app_id}`;
}
return new PouchDB(db_name, { auto_compaction: true });
};
func.utils.connect_pouchdb = async function (SESSION_ID) {
const app_id = SESSION_OBJ[SESSION_ID].app_id;
return func.utils.connect_studio_pouchdb(app_id, true);
};
func.utils.base64_encode_utf8 = function (value = '') {
if (typeof btoa === 'function') {
return btoa(unescape(encodeURIComponent(value)));
}
if (typeof Buffer !== 'undefined') {
return Buffer.from(value, 'utf8').toString('base64');
}
throw new Error('base64 encoder unavailable');
};
func.utils.should_use_local_studio_plugin_resources = function (SESSION_ID) {
const _session = SESSION_OBJ[SESSION_ID];
return typeof IS_PROCESS_SERVER === 'undefined' && (['live_preview'].includes(_session?.engine_mode) || _session?.is_draft_runtime);
};
func.utils.get_local_studio_plugin_doc = async function (SESSION_ID, plugin_name) {
if (!func.utils.should_use_local_studio_plugin_resources(SESSION_ID)) {
return null;
}
try {
const db = func.utils.connect_studio_pouchdb(null, false, 'xuda_studio_resources');
return await db.get(plugin_name);
} catch (error) {
return null;
}
};
func.utils.get_local_studio_plugin_file = async function (SESSION_ID, plugin_name, resource) {
const plugin_doc = await func.utils.get_local_studio_plugin_doc(SESSION_ID, plugin_name);
return plugin_doc?.files?.[`${plugin_name}/${resource}`] || null;
};
func.utils.get_local_studio_plugin_resource_url = async function (SESSION_ID, plugin_name, resource) {
const file_contents = await func.utils.get_local_studio_plugin_file(SESSION_ID, plugin_name, resource);
if (!file_contents) {
return null;
}
const content_type = resource.endsWith('.css') ? 'text/css' : 'text/javascript';
return `data:${content_type};base64,${func.utils.base64_encode_utf8(file_contents)}`;
};
// func.utils.validate_pouchdb = async function (SESSION_ID) {
// const app_id = SESSION_OBJ[SESSION_ID].app_id;
// const db = new PouchDB("xuda_rt_" + app_id);
// // db.info()
// // .then((info) => {
// // console.log("Database exists", info);
// // })
// // .catch((error) => {
// // if (error.status === 404) {
// // throw new Error("Database does not exist");
// // } else {
// // throw new Error("Error accessing database", error);
// // }
// // });
// try {
// let ret = await db.get(`cache_rt_info`);
// } catch (error) {
// throw new Error("new pouch detect");
// }
// };
func.utils.call_plugin_api = function (SESSION_ID, plugin_nameP, dataP) {
var _session = SESSION_OBJ[SESSION_ID];
const report_error = function (descP, warn) {
func.utils.debug.log(SESSION_ID, plugin_nameP, {
module: 'plugin',
action: 'Init',
source: 'call_plugin_api',
prop: descP,
details: descP,
result: null,
error: warn ? false : true,
fields: null,
type: 'plugin',
});
};
return new Promise(async (resolve) => {
var data = {
app_id: APP_OBJ[_session.app_id]._id,
debug: glb.DEBUG_MODE,
uid: _session.USR_OBJ._id,
gtp_token: _session.gtp_token,
app_token: _session.app_token,
};
data = Object.assign(data, dataP);
fetch(`https://xuda.ai/ppi/${plugin_nameP}`, {
method: 'POST',
headers: {
Accept: 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify(data),
})
.then((response) => {
if (!response.ok) {
return response.text().then((text) => {
throw new Error(text);
});
}
return response.json();
})
.then((json) => {
if (json.code < 0) {
report_error('Error: ' + json.data, json.error_type === 'W' ? true : false);
}
resolve(json.data);
// var doc = {
// _id: `cache_plugin_${plugin_nameP}`,
// data: json,
// docType: "cache_plugin",
// };
// db.put(doc);
})
.catch((err) => {
report_error('Error: ' + err.message);
resolve(err.message);
});
// }
});
};
func.utils.get_plugin_resource = function (SESSION_ID, plugin_name, plugin_resource) {
var _session = SESSION_OBJ[SESSION_ID];
const resource_ts =
(typeof globalThis !== 'undefined' ? globalThis.__XU_RUNTIME_MODULE_CACHE_TAG__ : '') ||
_session?.build_info?.runtime_ts ||
_session?.build_info?.last_changed_ts ||
_session?.build_info?.server_ts ||
_session?.opt?.app_build_id ||
(typeof globalThis !== 'undefined' ? globalThis.__XU_SERVER_BOOTSTRAP__?.version : 0) ||
0;
const plugin_resource_ts = `${resource_ts}-plugin-20260505-1`;
const get_path = function (resource) {
const server_origin = typeof globalThis !== 'undefined' ? globalThis.__XU_SERVER_ORIGIN__ : '';
if (server_origin) {
return `${server_origin}/plugins/${plugin_name}/${resource}?app_id=${_session.app_id}&ts=${plugin_resource_ts}`;
}
if (_session.worker_type === 'Dev') {
return `../../plugins/${plugin_name}/${resource}?ts=${plugin_resource_ts}`;
}
if (typeof IS_PROCESS_SERVER !== 'undefined') {
return `${_conf.plugins_drive_path}/${_session.app_id}/node_modules/${plugin_name}/${resource}`;
} else {
// return `./node_modules/${plugin_name}/${resource}?app_id=${_session.app_id}`;
return `https://${_session.domain}/plugins/${plugin_name}/${resource}?app_id=${_session.app_id}&ts=${plugin_resource_ts}`;
}
};
return new Promise(async (resolve, reject) => {
try {
const local_plugin_resource_url = await func.utils.get_local_studio_plugin_resource_url(SESSION_ID, plugin_name, plugin_resource);
if (local_plugin_resource_url) {
const plugin_resource_res = await import(/* @vite-ignore */ local_plugin_resource_url);
return resolve(plugin_resource_res);
}
} catch (err) {}
// const db = await func.utils.connect_pouchdb(SESSION_ID);
// try {
// if (_session.worker_type === "Dev") throw "bypass cache";
// let ret = await db.get(`cache_plugin_${plugin_name}_${plugin_resource}`);
// return resolve(ret.data);
// } catch (err) {
// try {
// const plugin_resource_res = await import(
// `${get_path(plugin_resource)}`
// );
// resolve(plugin_resource_res);
// // var doc = {
// // _id: `cache_plugin_${plugin_name}_${plugin_resource}`,
// // data: JSON.stringify(plugin_resource_res),
// // docType: "cache_plugin",
// // };
// // db.put(doc);
// } catch (err) {
// console.error(err);
// }
// }
try {
const plugin_resource_res = await import(`${get_path(plugin_resource)}`);
resolve(plugin_resource_res);
} catch (err) {
await func.utils.report_issue(SESSION_ID, {
code: 'RUN_MSG_GUI_020',
source: 'func.utils.get_plugin_resource',
message: 'plugin setup import failed',
err,
details: {
plugin_name,
plugin_resource,
plugin_path: get_path(plugin_resource),
},
});
reject(err);
}
});
};
func.utils.remove_cached_objects = async function (SESSION_ID) {
if (typeof IS_DOCKER !== 'undefined' || typeof IS_PROCESS_SERVER !== 'undefined') return;
try {
const db = await func.utils.connect_pouchdb(SESSION_ID);
let opt = {
$or: [
{
docType: 'cache_objects',
},
{
docType: 'cache_plugin',
},
{
docType: 'cache_app',
},
{
docType: 'cache_build_info',
},
],
};
const res = await db.find({ selector: opt });
for await (let val of res.docs) {
await db.remove(val);
}
} catch (err) {
return;
}
};
func.utils.get_plugin_npm_cdn = async function (SESSION_ID, plugin_name, resource) {
const _session = SESSION_OBJ[SESSION_ID];
const resource_ts =
(typeof globalThis !== 'undefined' ? globalThis.__XU_RUNTIME_MODULE_CACHE_TAG__ : '') ||
_session?.build_info?.runtime_ts ||
_session?.build_info?.last_changed_ts ||
_session?.build_info?.server_ts ||
_session?.opt?.app_build_id ||
(typeof globalThis !== 'undefined' ? globalThis.__XU_SERVER_BOOTSTRAP__?.version : 0) ||
0;
const plugin_resource_ts = `${resource_ts}-plugin-20260505-1`;
const local_plugin_resource_url = await func.utils.get_local_studio_plugin_resource_url(SESSION_ID, plugin_name, resource);
if (local_plugin_resource_url) {
return local_plugin_resource_url;
}
const get_path = function (resource) {
const server_origin = typeof globalThis !== 'undefined' ? globalThis.__XU_SERVER_ORIGIN__ : '';
if (server_origin) {
return `${server_origin}/plugins/${plugin_name}/${resource}?app_id=${_session.app_id}&ts=${plugin_resource_ts}`;
}
if (_session.worker_type === 'Dev') {
return `../../plugins/${plugin_name}/${resource}?ts=${plugin_resource_ts}`;
}
return `https://${_session.domain}/plugins/${plugin_name}/${resource}?app_id=${_session.app_id}&ts=${plugin_resource_ts}`;
};
return get_path(resource);
};
func.utils.write_log = async function (SESSION_ID, method = '', msg = '', log_type = 'error', source = 'runtime', details, meta = {}) {
const _session = SESSION_OBJ[SESSION_ID];
const body = {
msg,
log_type,
source,
details,
method,
...meta,
};
const is_offline =
(typeof IS_ONLINE !== 'undefined' && !IS_ONLINE) ||
(typeof navigator !== 'undefined' && navigator.onLine === false);
if (_session?.is_draft_runtime && is_offline) {
return null;
}
if (typeof IS_API_SERVER !== 'undefined' || typeof IS_DOCKER !== 'undefined' || typeof IS_PROCESS_SERVER !== 'undefined') {
return __.rpi.write_log(
_session?.app_id,
log_type,
source,
msg,
details,
null,
body,
method,
_session?.SYS_GLOBAL_OBJ_CLIENT_INFO?.fingerprint,
);
}
if (glb.IS_WORKER) {
let obj = {
service: 'write_log',
data: body,
log_type,
id: STUDIO_WEBSOCKET_CONNECTION_ID,
uid: _session?.USR_OBJ?._id,
source,
app_id: _session?.app_id,
gtp_token: _session?.gtp_token,
app_token: _session?.app_token,
};
return func.utils.post_back_to_client(SESSION_ID, 'write_log', _session.worker_id, obj);
}
await func.common.db(SESSION_ID, 'write_log', body);
};
func.utils.get_error_catalog_manifest = async function (SESSION_ID) {
const registry = await func.utils.get_error_registry(SESSION_ID);
return registry?.get_error_catalog_manifest?.() || null;
};
func.utils.get_resource_filename = function (build, filename) {
if (build) {
return filename.replace(/(\.\w+)$/, `.${build}$1`);
}
return filename;
};
func.utils.set_SYS_GLOBAL_OBJ_WIDGET_INFO = async function (SESSION_ID, docP) {
var obj = { ...docP };
obj.date = await func.utils.get_dateTime(SESSION_ID, 'SYS_DATE', docP.date);
obj.time = await func.utils.get_dateTime(SESSION_ID, 'SYS_TIME', docP.date);
var datasource_changes = {
[0]: {
['data_system']: {
['SYS_GLOBAL_OBJ_WIDGET_INFO']: obj,
},
},
};
await func.datasource.update(SESSION_ID, datasource_changes);
};
func.utils.get_last_datasource_no = function (SESSION_ID) {
if (typeof IS_PROCESS_SERVER !== 'undefined') {
return Object.keys(SESSION_OBJ[SESSION_ID].DS_GLB).at?.(-1);
} else {
const filtered = Object.values(SESSION_OBJ[SESSION_ID].DS_GLB).filter((e) => e.tree_obj.menuType !== 'api');
return filtered?.at?.(-1)?.dsSession;
}
};
func.runtime = func.runtime || {};
func.runtime.ui = func.runtime.ui || {};
func.runtime.render = func.runtime.render || {};
func.runtime.widgets = func.runtime.widgets || {};
// Browser-only host, root, and screen-container helpers live here so low-level DOM/container code can stay focused.
func.runtime.ui.get_root_element = function (SESSION_ID) {
const _session = SESSION_OBJ[SESSION_ID];
if (!_session) {
return func.runtime.ui._wrap_matches([]);
}
if (_session._root_wrapped?.[0] === _session.root_element) {
return _session._root_wrapped;
}
_session._root_wrapped = func.runtime.ui._wrap_matches(_session.root_element ? [_session.root_element] : []);
return _session._root_wrapped;
};
func.runtime.ui.get_root_node = function (SESSION_ID) {
return func.runtime.ui.get_root_element(SESSION_ID)?.[0] || null;
};
func.runtime.ui.show_root_element = function (SESSION_ID) {
return func.runtime.ui.show(func.runtime.ui.get_root_element(SESSION_ID));
};
func.runtime.ui.ensure_app_shell = function (SESSION_ID, domain) {
const $root_element = func.runtime.ui.get_root_element(SESSION_ID);
func.runtime.ui.set_style($root_element, 'position', 'relative');
if (!func.runtime.ui.has_selector($root_element, '.loader')) {
func.runtime.ui.append_html($root_element, `
<style>
.loader {
position: absolute;
background: rgb(0 0 0 / 30%);
z-index: 10;
overflow-y: auto;
top: 0;
right: 0;
bottom: 0;
left: 0;
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
}
.loader .loader_logo {
width: 43px;
height: 43px;
border-radius: 50%;
background-size: cover;
}
.loader .loader_msg {
padding-top: 10px;
text-align: center;
min-height: 20px;
font-family: ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, "Noto Sans", sans-serif, "Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol", "Noto Color Emoji";
}
.loader .loader_rotate {
padding: 20px;
border: 2px solid #fff;
border-right-color: #898989;
border-radius: 22px;
-webkit-animation: rotate 0.8s infinite linear;
position: absolute;
}
@-webkit-keyframes rotate {
100% {
-webkit-transform: rotate(360deg);
}
}
</style>
<div class="loader">
<div class="loader_logo">
<div class="loader_rotate"></div>
</div>
<div class="loader_msg"> </div>
</div>
<div class="progressLoader"></div>
`);
}
if (!func.runtime.ui.has_selector($root_element, '#tailwind_toast_controller')) {
func.runtime.ui.append_html(
$root_element,
`<div aria-live="assertive"
class="fixed inset-0 flex items-end px-4 py-6 pointer-events-none sm:p-6 sm:items-start z-[999]">
<div id="tailwind_toast_controller" class="w-full flex flex-col items-center space-y-4 sm:items-end">
</div>
</div>`,
);
}
if (!func.runtime.ui.has_selector($root_element, '#progressScreen2')) {
func.runtime.ui.append_html(
$root_element,
`
<div id="progressScreen2" style="display: none">
<div id="progressScreen2_text"></div>
</div>`,
);
}
const get_url = function (domain, method, path) {
return `https://${domain}/${method}${path ? '/' + path : '/'}`;
};
func.utils.load_css_on_demand(get_url(domain, 'dist', 'runtime/css/mobile.css'));
return $root_element;
};
func.runtime.ui.ensure_embed_container = function (SESSION_ID) {
const $root_element = func.runtime.ui.get_root_element(SESSION_ID);
let $embed_container = func.runtime.ui.find_by_selector($root_element, `#embed_${SESSION_ID}`, true);
if (!$embed_container.length) {
const $ssr_embed_container = func.runtime.ui.find_by_selector($root_element, `[data-xuda-ssr-embed="true"]`, true);
const ssr_embed_node = func.runtime.ui.get_first_node($ssr_embed_container);
if (ssr_embed_node) {
ssr_embed_node.id = 'embed_' + SESSION_ID;
$embed_container = func.runtime.ui._wrap_matches([ssr_embed_node]);
}
}
if (!$embed_container.length) {
const embed_node = document.createElement('div');
embed_node.id = 'embed_' + SESSION_ID;
embed_node.className = 'xu_embed_div';
func.runtime.ui.set_data(embed_node, 'xuData', {});
$embed_container = func.runtime.ui._wrap_matches([embed_node]);
func.runtime.ui.append_to($embed_container, $root_element);
}
return $embed_container;
};
func.runtime.ui.get_embed_container = function (SESSION_ID) {
return func.runtime.ui.find_by_selector(func.runtime.ui.get_root_element(SESSION_ID), `#embed_${SESSION_ID}`, true);
};
func.runtime.ui.get_embed_screen_containers = function () {
return func.runtime.ui.find_by_selector(document.body, '.xu_embed_container');
};
func.runtime.ui.append_to_body = function ($element) {
func.runtime.ui.append_to($element, document.body);
return $element;
};
func.runtime.ui.find_in_root = function (SESSION_ID, selector) {
return func.runtime.ui.find_by_selector(func.runtime.ui.get_root_element(SESSION_ID), selector);
};
func.runtime.ui.get_root_tag_name = function () {
let root_tag_name = 'div';
if (!func.runtime.session.is_slim()) {
if (typeof UI_FRAMEWORK_PLUGIN?.core !== 'function') {
return root_tag_name;
}
const ui_plugin_core = new UI_FRAMEWORK_PLUGIN.core();
root_tag_name = ui_plugin_core?.rootTagName() || root_tag_name;
}
return root_tag_name;
};
func.runtime.ui.find_ssr_screen_host = function ($container, screenId, containerId) {
const container_node = func.runtime.ui.get_first_node($container);
if (!container_node || !screenId) {
return null;
}
const dialog_node =
container_node.querySelector?.(`#${CSS?.escape ? CSS.escape(screenId) : screenId}`) ||
container_node.querySelector?.(`[data-xuda-ssr-screen-id="${screenId}"]`);
if (!dialog_node) {
return null;
}
const root_frame_node =
(containerId ? dialog_node.querySelector?.(`#${CSS?.escape ? CSS.escape(containerId) : containerId}`) : null) ||
dialog_node.querySelector?.('[data-xuda-ssr-root-frame="true"]');
if (!root_frame_node) {
return null;
}
return {
$dialogDiv: func.runtime.ui._wrap_matches([dialog_node]),
$rootFrame: func.runtime.ui._wrap_matches([root_frame_node]),
reused_ssr_host: true,
};
};
func.runtime.ui.create_screen_host = function (SESSION_ID, screen_type, params, $callingContainerP, screenId) {
var $dialogDiv;
var $rootFrame;
let reused_ssr_host = false;
switch (screen_type) {
case 'embed': {
const ssr_host = func.runtime.ui.find_ssr_screen_host($callingContainerP, screenId, params?.containerIdP);
if (ssr_host) {
return ssr_host;
}
const dialogNode = document.createElement('div');
dialogNode.id = screenId;
dialogNode.setAttribute('ui_engine', UI_FRAMEWORK_INSTALLED);
dialogNode.classList.add('xu_embed_container');
dialogNode.style.display = 'contents';
func.runtime.ui.set_data(dialogNode, 'xuData', {
paramsP: params,
screenInfo: params.screenInfo,
});
$dialogDiv = func.runtime.ui._wrap_matches([dialogNode]);
const root_tag_name = func.runtime.ui.get_root_tag_name();
const rootFrameNode = document.createElement(root_tag_name);
func.runtime.ui.set_data(rootFrameNode, 'xuData', {});
func.runtime.ui.set_data(rootFrameNode, 'xuAttributes', {});
dialogNode.appendChild(rootFrameNode);
$rootFrame = func.runtime.ui._wrap_matches([rootFrameNode]);
func.runtime.ui.append_to($dialogDiv, $callingContainerP);
break;
}
case 'panel':
$dialogDiv = $callingContainerP;
func.runtime.ui.set_data($dialogDiv, 'xuData', {
paramsP: params,
screenInfo: params.screenInfo,
});
$rootFrame = $dialogDiv;
break;
case 'page':
case 'modal':
case 'popover': {
const dialogNode = document.createElement('div');
const rootFrameNode = document.createElement('div');
dialogNode.appendChild(rootFrameNode);
$dialogDiv = func.runtime.ui._wrap_matches([dialogNode]);
$rootFrame = func.runtime.ui._wrap_matches([rootFrameNode]);
func.runtime.ui.append_to_body($dialogDiv);
break;
}
default:
break;
}
return {
$dialogDiv,
$rootFrame,
reused_ssr_host,
};
};
func.runtime.ui.find_xu_ui_in_root = function (SESSION_ID, xu_ui_id) {
if (!SESSION_ID || !xu_ui_id) {
return func.runtime.ui._wrap_matches([]);
}
if (func.runtime.ui.get_refresh_indexed_element_by_ui_id) {
const elm = func.runtime.ui.get_refresh_indexed_element_by_ui_id(SESSION_ID, xu_ui_id);
return func.runtime.ui._wrap_matches(elm ? [elm] : []);
}
return func.runtime.ui.find_in_root(SESSION_ID, `[xu-ui-id="${xu_ui_id}"]`);
};
func.runtime.ui.find_panel_wrapper_in_root = function (SESSION_ID, xu_ui_id) {
if (func.runtime.ui.get_refresh_indexed_panel_wrapper_by_id) {
const elm = func.runtime.ui.get_refresh_indexed_panel_wrapper_by_id(SESSION_ID, xu_ui_id);
return func.runtime.ui._wrap_matches(elm ? [elm] : []);
}
return func.runtime.ui.find_in_root(SESSION_ID, `[xu-panel-wrapper-id=${xu_ui_id}]`);
};
func.runtime.ui.find_element_data_in_root = function (SESSION_ID, dataKey, property, value) {
if (dataKey === 'xuData' && property === 'ui_id' && typeof value !== 'undefined' && func.runtime.ui.get_refresh_indexed_element_by_ui_id) {
const elm = func.runtime.ui.get_refresh_indexed_element_by_ui_id(SESSION_ID, value);
return func.runtime.ui._wrap_matches(elm ? [elm] : []);
}
if (dataKey === 'xuData' && property === 'nodeid' && typeof value !== 'undefined' && func.runtime.ui.get_refresh_indexed_elements_by_node_id) {
return func.runtime.ui.get_refresh_indexed_elements_by_node_id(SESSION_ID, value);
}
if (dataKey === 'xuPanelWrapper' && property === 'isWrapper' && typeof value === 'undefined') {
if (func.runtime.ui.get_refresh_indexed_panel_wrappers) {
return func.runtime.ui.get_refresh_indexed_panel_wrappers(SESSION_ID);
}
return func.runtime.ui.find_in_root(SESSION_ID, '[xu-panel-wrapper-id]');
}
return func.UI.utils.find_in_element_data(dataKey, func.runtime.ui.get_root_element(SESSION_ID), property, value);
};
func.runtime.ui.find_element_data_in_parent = function ($container, dataKey, property, value) {
const container_node = func.runtime.ui.get_first_node($container);
const parent_node = container_node?.parentElement;
if (!parent_node) {
return func.runtime.ui._wrap_matches([]);
}
if (dataKey === 'xuData' && property === 'ui_id' && typeof value !== 'undefined') {
if (func.runtime.ui.find_refresh_elements_by_attr) {
return func.runtime.ui.find_refresh_elements_by_attr(parent_node, 'xu-ui-id', value, true);
}
return func.runtime.ui.find_by_selector(parent_node, `[xu-ui-id="${value}"]`);
}
return func.UI.utils.find_in_element_data(dataKey, func.runtime.ui._wrap_matches([parent_node]), property, value);
};
func.runtime.ui.sync_child_parent_container = function ($div) {
const div_node = func.runtime.ui.get_first_node($div);
const parent_container = func.runtime.ui.get_data(div_node)?.xuData?.parent_container;
const children = div_node?.children ? Array.from(div_node.children) : [];
for (let index = 0; index < children.length; index++) {
const child_data = func.runtime.ui.get_data(children[index]);
if (!child_data?.xuData?.parent_container) {
continue;
}
child_data.xuData.parent_container = parent_container;
}
return $div;
};
func.runtime = func.runtime || {};
func.runtime.ui = func.runtime.ui || {};
func.runtime.render = func.runtime.render || {};
func.runtime.widgets = func.runtime.widgets || {};
func.runtime.ui.ui_id_hash_cache = func.runtime.ui.ui_id_hash_cache || new Map();
func.runtime.ui.node_snapshot_cache = func.runtime.ui.node_snapshot_cache || new WeakMap();
func.runtime.ui.node_child_items_cache = func.runtime.ui.node_child_items_cache || new WeakMap();
func.runtime.ui.node_children_by_id_cache = func.runtime.ui.node_children_by_id_cache || new WeakMap();
func.runtime.ui.is_invalid_asset_url_value = function (value) {
const normalized_value = typeof value === 'string' ? value.trim() : '';
return !normalized_value || /^(undefined|null)$/i.test(normalized_value) || /url\([^)]*(undefined|null)[^)]*\)/i.test(normalized_value);
};
if (typeof CSSStyleDeclaration !== 'undefined' && !CSSStyleDeclaration.prototype.__xuda_safe_asset_url_guard) {
const background_image_descriptor = Object.getOwnPropertyDescriptor(CSSStyleDeclaration.prototype, 'backgroundImage');
const original_set_property = CSSStyleDeclaration.prototype.setProperty;
Object.defineProperty(CSSStyleDeclaration.prototype, 'backgroundImage', {
configurable: true,
enumerable: background_image_descriptor?.enumerable ?? true,
get() {
if (background_image_descriptor?.get) {
return background_image_descriptor.get.call(this);
}
return this.getPropertyValue('background-image');
},
set(value) {
if (func.runtime.ui.is_invalid_asset_url_value(value)) {
return this.removeProperty('background-image');
}
if (background_image_descriptor?.set) {
return background_image_descriptor.set.call(this, value);
}
return original_set_property.call(this, 'background-image', value);
},
});
CSSStyleDeclaration.prototype.setProperty = function (name, value, priority) {
if (String(name).toLowerCase() === 'background-image' && func.runtime.ui.is_invalid_asset_url_value(value)) {
return this.removeProperty('background-image');
}
return original_set_property.call(this, name, value, priority);
};
Object.defineProperty(CSSStyleDeclaration.prototype, '__xuda_safe_asset_url_guard', { value: true });
}
// ── DOM-independent metadata store ──
// Keyed by xu-ui-id, decouples element metadata from jQuery .data().
// Enables headless/SSR execution where DOM elements don't exist.
func.runtime.ui._meta_store = func.runtime.ui._meta_store || {};
func.runtime.ui._element_id_to_xu_ui_id = func.runtime.ui._element_id_to_xu_ui_id || {};
func.runtime.ui.set_meta = function (xu_ui_id, key, value) {
if (!xu_ui_id) return;
if (!func.runtime.ui._meta_store[xu_ui_id]) {
func.runtime.ui._meta_store[xu_ui_id] = {};
}
func.runtime.ui._meta_store[xu_ui_id][key] = value;
};
func.runtime.ui.get_meta = function (xu_ui_id, key) {
const entry = func.runtime.ui._meta_store[xu_ui_id];
if (!entry) return undefined;
return key ? entry[key] : entry;
};
func.runtime.ui.delete_meta = function (xu_ui_id) {
delete func.runtime.ui._meta_store[xu_ui_id];
// clean reverse lookup
for (const id in func.runtime.ui._element_id_to_xu_ui_id) {
if (func.runtime.ui._element_id_to_xu_ui_id[id] === xu_ui_id) {
delete func.runtime.ui._element_id_to_xu_ui_id[id];
}
}
};
func.runtime.ui.register_element_id = function (element_id, xu_ui_id) {
if (element_id && xu_ui_id) {
func.runtime.ui._element_id_to_xu_ui_id[element_id] = xu_ui_id;
}
};
func.runtime.ui.get_meta_by_element_id = function (element_id) {
if (!element_id) return undefined;
const xu_ui_id = func.runtime.ui._element_id_to_xu_ui_id[element_id];
if (xu_ui_id) {
return func.runtime.ui._meta_store[xu_ui_id];
}
// fallback: try DOM lookup if in browser
if (typeof document !== 'undefined') {
const clean_id = element_id.startsWith('#') ? element_id.substring(1) : element_id;
const el = document.getElementById(clean_id);
if (el) {
const dom_xu_ui_id = el.getAttribute('xu-ui-id');
if (dom_xu_ui_id) {
func.runtime.ui.register_element_id(clean_id, dom_xu_ui_id);
return func.runtime.ui._meta_store[dom_xu_ui_id];
}
return func.runtime.ui.get_data(el);
}
}
return undefined;
};
func.runtime.ui.find_element_by_id = function (element_id) {
if (!element_id) return null;
if (typeof document !== 'undefined') {
return document.getElementById(element_id) || null;
}
return null;
};
func.runtime.ui.get_parent_element_id = function (element_id) {
if (!element_id) {
return null;
}
const clean_id = element_id.startsWith('#') ? element_id.substring(1) : element_id;
const element = func.runtime.ui.find_element_by_id(clean_id);
return element?.parentElement?.id || null;
};
func.runtime.ui.get_session_root = function (SESSION_ID) {
if (typeof document !== 'undefined') {
return document.getElementById('embed_' + SESSION_ID) || null;
}
return null;
};
func.runtime.ui.clear_screen_blockers = function () {
if (typeof document !== 'undefined') {
const blockers = document.querySelectorAll('.screen_blocker');
for (let i = 0; i < blockers.length; i++) {
blockers[i].remove();
}
}
};
func.runtime.ui.as_jquery = function (target) {
const node = func.runtime.ui.get_first_node(target);
return func.runtime.ui._wrap_matches(node ? [node] : []);
};
func.runtime.ui.get_first_node = function (target) {
if (!target) {
return null;
}
if (target?.nodeType) {
return target;
}
if (Array.isArray(target) || typeof target?.length === 'number') {
return target[0] || null;
}
return null;
};
func.runtime.ui.get_data = function (target) {
const target_node = func.runtime.ui.get_first_node(target);
if (target_node?.getAttribute) {
const xu_ui_id = target_node.getAttribute('xu-ui-id');
if (xu_ui_id) {
const meta = func.runtime.ui._meta_store[xu_ui_id];
if (meta) return meta;
}
}
if (target_node) {
if (!target_node.__xuData) {
target_node.__xuData = {};
}
return target_node.__xuData;
}
return {};
};
func.runtime.ui.get_parent = function (target) {
const target_node = func.runtime.ui.get_first_node(target);
return target_node?.parentElement || null;
};
func.runtime.ui.get_children = function (target) {
const target_node = func.runtime.ui.get_first_node(target);
return target_node?.children ? Array.from(target_node.children) : [];
};
// _wrap_matches — build a results object compatible with both jQuery-style
// access (.length, [0], [1], .toArray()) and native iteration (for...of).
func.runtime.ui._wrap_matches = function (matches) {
if (!matches) matches = [];
const result = {
length: matches.length,
toArray: function () { return matches.slice(); },
};
for (let i = 0; i < matches.length; i++) {
result[i] = matches[i];
}
// Make it iterable with for...of
result[Symbol.iterator] = function () {
let idx = 0;
return {
next: function () {
if (idx < matches.length) {
return { value: matches[idx++], done: false };
}
return { done: true };
},
};
};
return result;
};
func.runtime.ui.find_by_selector = function (target, selector, first_only = false) {
const target_node = func.runtime.ui.get_first_node(target);
const root_nodes = target_node ? [target_node] : (Array.isArray(target) ? target : (target?.length ? Array.from(target) : []));
const matches = [];
for (let root_index = 0; root_index < root_nodes.length; root_index++) {
const root_node = root_nodes[root_index];
if (root_node?.matches?.(selector)) {
matches.push(root_node);
if (first_only) {
break;
}
}
if (first_only && matches.length) {
break;
}
if (first_only) {
const first_match = root_node?.querySelector?.(selector);
if (first_match) {
matches.push(first_match);
break;
}
continue;
}
const descendants = root_node?.querySelectorAll?.(selector) || [];
for (let index = 0; index < descendants.length; index++) {
matches.push(descendants[index]);
}
}
return func.runtime.ui._wrap_matches(matches);
};
func.runtime.ui.insert_before = function ($element, $reference) {
const element_node = func.runtime.ui.get_first_node($element);
const reference_node = func.runtime.ui.get_first_node($reference);
if (reference_node?.before && element_node) {
reference_node.before(element_node);
}
if (func.runtime.ui.mark_refresh_index_dirty_from_target) {
func.runtime.ui.mark_refresh_index_dirty_from_target($reference, func.runtime.ui.get_data($element)?.xuData?.SESSION_ID);
}
return $element;
};
func.runtime.ui.insert_after = function ($element, $reference) {
const element_node = func.runtime.ui.get_first_node($element);
const reference_node = func.runtime.ui.get_first_node($reference);
if (reference_node?.after && element_node) {
reference_node.after(element_node);
}
if (func.runtime.ui.mark_refresh_index_dirty_from_target) {
func.runtime.ui.mark_refresh_index_dirty_from_target($reference, func.runtime.ui.get_data($element)?.xuData?.SESSION_ID);
}
return $element;
};
func.runtime.ui.has_selector = function (target, selector) {
return !!func.runtime.ui.get_first_node(func.runtime.ui.find_by_selector(target, selector, true));
};
func.runtime.ui.append_html = function (target, html) {
const target_node = func.runtime.ui.get_first_node(target);
if (!target_node || !html) {
return target_node || null;
}
target_node.insertAdjacentHTML('beforeend', html);
if (func.runtime.ui.mark_refresh_index_dirty_from_target) {
func.runtime.ui.mark_refresh_index_dirty_from_target(target_node);
}
return target_node;
};
func.runtime.ui.set_style = function (target, prop, value) {
const target_node = func.runtime.ui.get_first_node(target);
if (!target_node?.style || !prop) {
return target_node || null;
}
target_node.style[prop] = value;
return target_node;
};
func.runtime.ui.normalize_external_asset_url = function (value) {
if (typeof value !== 'string' || !value.trim()) {
return value;
}
const trimmed_value = value.trim();
try {
const url = new URL(trimmed_value, typeof document !== 'undefined' ? document.baseURI : 'https://xuda.ai');
if (url.hostname === 'via.placeholder.com') {
url.hostname = 'placehold.co';
return url.toString();
}
} catch (_) {
if (trimmed_value.startsWith('https://via.placeholder.com/') || trimmed_value.startsWith('http://via.placeholder.com/')) {
return trimmed_value.replace('via.placeholder.com', 'placehold.co');
}
}
return value;
};
func.runtime.ui.normalize_svg_path_value = function (value) {
if (typeof value !== 'string' || !value.trim()) {
return value;
}
let normalized_value = value.trim();
// Common AI-generated typo: path data ends with a dangling command after closepath, e.g. "...zzm".
normalized_value = normalized_value.replace(/([zZ])+\s*[mMlLhHvVcCsSqQtTaA]\s*$/g, '$1');
return normalized_value;
};
func.runtime.ui.normalize_attr_value = function (target_or_tag, key, value) {
if (typeof value !== 'string') {
return value;
}
const target_tag_name =
typeof target_or_tag === 'string'
? target_or_tag
: func.runtime.ui.get_first_node(target_or_tag)?.tagName || '';
const tag_name = `${target_tag_name || ''}`.trim().toLowerCase();
const attr_name = `${key || ''}`.trim().toLowerCase();
if ((tag_name === 'img' || tag_name === 'image') && ['src', 'href', 'xlink:href'].includes(attr_name)) {
return func.runtime.ui.normalize_external_asset_url(value);
}
if (tag_name === 'path' && attr_name === 'd') {
return func.runtime.ui.normalize_svg_path_value(value);
}
return value;
};
func.runtime.ui.get_attr = function (target, key) {
const target_node = func.runtime.ui.get_first_node(target);
return target_node?.getAttribute?.(key) ?? undefined;
};
func.runtime.ui.should_remove_attr = function (key, value) {
if (typeof value === 'undefined' || value === null) {
return true;
}
if (typeof value === 'string') {
const normalized_value = value.trim().toLowerCase();
if (normalized_value === 'undefined' || normalized_value === 'null') {
return true;
}
}
if (glb.solid_attributes?.includes?.(key)) {
return value === false || value === 'false' || value === 0 || value === '0';
}
return false;
};
func.runtime.ui.remove_attr = function (target, key) {
const target_node = func.runtime.ui.get_first_node(target);
target_node?.removeAttribute?.(key);
return target_node || target;
};
func.runtime.ui.set_attr = function (target, key, value) {
const target_node = func.runtime.ui.get_first_node(target);
if (target_node?.setAttribute) {
if (func.runtime.ui.should_remove_attr(key, value)) {
target_node.removeAttribute?.(key);
return target_node;
}
const normalized_value = glb.solid_attributes?.includes?.(key) && value === true
? ''
: func.runtime.ui.normalize_attr_value(target_node, key, value);
try {
target_node.setAttribute(key, normalized_value);
} catch (error) {
console.warn(`Failed to set attribute "${key}" on <${target_node.tagName?.toLowerCase?.() || 'unknown'}>`, error);
}
}
return target_node || target;
};
func.runtime.ui.set_data = function (target, key, value) {
const target_node = func.runtime.ui.get_first_node(target);
// write to meta store via xu-ui-id
if (target_node?.getAttribute) {
const xu_ui_id = target_node.getAttribute('xu-ui-id');
if (xu_ui_id) {
func.runtime.ui.set_meta(xu_ui_id, key, value);
return target;
}
}
// fallback: store on node directly
if (target_node) {
if (!target_node.__xuData) target_node.__xuData = {};
target_node.__xuData[key] = value;
}
return target;
};
func.runtime.ui.clear_data = function (target) {
const target_node = func.runtime.ui.get_first_node(target);
if (target_node?.getAttribute) {
const xu_ui_id = target_node.getAttribute('xu-ui-id');
if (xu_ui_id) {
func.runtime.ui.delete_meta(xu_ui_id);
}
}
if (target_node?.__xuData) {
delete target_node.__xuData;
}
return target;
};
func.runtime.ui.add_class = function (target, class_name) {
const target_node = func.runtime.ui.get_first_node(target);
if (target_node?.classList) {
target_node.classList.add(class_name);
return target_node;
}
return target_node || null;
};
func.runtime.ui.remove_class = function (target, class_name) {
const target_node = func.runtime.ui.get_first_node(target);
if (target_node?.classList) {
target_node.classList.remove(class_name);
return target_node;
}
return target_node || null;
};
func.runtime.ui.set_html = function (target, value) {
const target_node = func.runtime.ui.get_first_node(target);
if (typeof target_node?.innerHTML !== 'undefined') {
target_node.innerHTML = value;
return target_node;
}
return target_node || null;
};
func.runtime.ui.set_text = function (target, value) {
const target_node = func.runtime.ui.get_first_node(target);
if (typeof target_node?.textContent !== 'undefined') {
target_node.textContent = value;
return target_node;
}
return target_node || null;
};
func.runtime.ui.show = function (target) {
const target_node = func.runtime.ui.get_first_node(target);
if (target_node?.style) {
target_node.style.removeProperty('display');
return target_node;
}
return target_node || null;
};
func.runtime.ui.hide = function (target) {
const target_node = func.runtime.ui.get_first_node(target);
if (target_node?.style) {
target_node.style.display = 'none';
return target_node;
}
return target_node || null;
};
func.runtime.ui.append = function ($target, $element) {
const target_node = func.runtime.ui.get_first_node($target);
const element_node = func.runtime.ui.get_first_node($element);
if (target_node && element_node) {
target_node.appendChild(element_node);
}
if (func.runtime.ui.mark_refresh_index_dirty_from_target) {
func.runtime.ui.mark_refresh_index_dirty_from_target($target, func.runtime.ui.get_data($element)?.xuData?.SESSION_ID);
}
func.runtime?.perf?.increment?.(func.runtime.ui.get_data($element)?.xuData?.SESSION_ID, 'dom_appends');
return $element;
};
func.runtime.ui.append_to = function ($element, $target) {
const target_node = func.runtime.ui.get_first_node($target);
const element_node = func.runtime.ui.get_first_node($element);
if (target_node && element_node) {
target_node.appendChild(element_node);
}
if (func.runtime.ui.mark_refresh_index_dirty_from_target) {
func.runtime.ui.mark_refresh_index_dirty_from_target($target, func.runtime.ui.get_data($element)?.xuData?.SESSION_ID);
}
func.runtime?.perf?.increment?.(func.runtime.ui.get_data($element)?.xuData?.SESSION_ID, 'dom_appends');
return $element;
};
func.runtime.ui.empty = function (target) {
const target_node = func.runtime.ui.get_first_node(target);
if (target_node) {
target_node.replaceChildren();
}
if (func.runtime.ui.mark_refresh_index_dirty_from_target) {
func.runtime.ui.mark_refresh_index_dirty_from_target(target);
}
return target_node || null;
};
func.runtime.ui.remove = function (target) {
if (func.runtime.ui.mark_refresh_index_dirty_from_target) {
func.runtime.ui.mark_refresh_index_dirty_from_target(target);
}
// Normalise target into an array of DOM nodes
let target_nodes;
if (target?.nodeType) {
target_nodes = [target];
} else if (Array.isArray(target)) {
target_nodes = target;
} else if (target?.length) {
target_nodes = Array.from(target);
} else {
target_nodes = [];
}
const session_id = func.runtime.ui.get_data(target_nodes[0] || target)?.xuData?.SESSION_ID;
for (let index = 0; index < target_nodes.length; index++) {
const target_node = target_nodes[index];
// clean meta store for removed elements
const xu_ui_id = target_node?.getAttribute?.('xu-ui-id');
if (xu_ui_id) {
func.runtime.ui.delete_meta(xu_ui_id);
}
if (target_node?.remove) {
target_node.remove();
}
}
func.runtime?.perf?.increment?.(session_id, 'dom_removes', target_nodes.length || 1);
return true;
};
func.runtime.ui.set_display_contents = function ($element) {
return func.runtime.ui.set_style($element, 'display', 'contents');
};
func.runtime.ui.reconcile_xu_ui_id_duplicates = function (SESSION_ID, xu_ui_id, $keep) {
// Identity contract of the render layer: at most ONE live element may carry a given
// xu-ui-id. Re-render passes that miss their swap (stale $elm reference / refresh-index
// miss) used to leave both the old content and the new placeholder — or duplicate content
// copies — in the DOM (e.g. an un-closable modal whose gate flag was already false).
// Panels and teleports have their own reconcile (find_panel_wrapper_in_root /
// reconcile_teleports); this is the equivalent for xu-render swaps.
if (!xu_ui_id) return 0;
const keep_node = $keep ? func.runtime.ui.get_first_node($keep) : null;
const root_node = func.runtime.ui.get_first_node(func.runtime.ui.get_root_element?.(SESSION_ID)) || document.body;
if (!root_node?.querySelectorAll) return 0;
const escaped_ui_id = typeof CSS !== 'undefined' && CSS.escape ? CSS.escape(xu_ui_id) : xu_ui_id;
const matches = root_node.querySelectorAll(`[xu-ui-id="${escaped_ui_id}"]`);
// UI.remove deletes the meta-store entry of every element it removes — and the store is
// keyed by xu-ui-id, which the keeper SHARES with the duplicates being removed. Without
// restoring it, the surviving element becomes a lifecycle orphan: no ui_type/xuAttributes
// means the refresh index can't see it and its gate field can no longer reach it (an
// un-closable modal). Hold the entry reference and put it back after the removals.
const kept_meta = keep_node ? func.runtime.ui._meta_store?.[xu_ui_id] : null;
let removed = 0;
for (let match_index = 0; match_index < matches.length; match_index++) {
const match_node = matches[match_index];
if (keep_node && (match_node === keep_node || keep_node.contains(match_node) || match_node.contains(keep_node))) continue;
func.runtime.ui.remove(match_node);
removed++;
}
if (removed && keep_node && kept_meta && func.runtime.ui._meta_store && !func.runtime.ui._meta_store[xu_ui_id]) {
func.runtime.ui._meta_store[xu_ui_id] = kept_meta;
}
return removed;
};
func.runtime.ui.create_xurender = function (xu_ui_id, $target, hidden) {
const xurender = document.createElement('xurender');
xurender.setAttribute('xu-ui-id', xu_ui_id);
if (hidden) {
xurender.setAttribute('hidden', 'true');
}
return func.runtime.ui.append_to(xurender, $target);
};
func.runtime.ui.replace_with = function ($source, $target) {
if (func.runtime.ui.mark_refresh_index_dirty_from_target) {
func.runtime.ui.mark_refresh_index_dirty_from_target($source, func.runtime.ui.get_data($source)?.xuData?.SESSION_ID || func.runtime.ui.get_data($target)?.xuData?.SESSION_ID);
}
const source_node = func.runtime.ui.get_first_node($source);
const target_node = func.runtime.ui.get_first_node($target);
if (source_node?.replaceWith && target_node) {
source_node.replaceWith(target_node);
}
return $target;
};
func.runtime.ui.remove_xu_ui = function (xu_ui_id) {
const $targets = func.runtime.ui.find_by_selector(document.body, `[xu-ui-id="${xu_ui_id}"]`, false);
if (func.runtime.ui.mark_refresh_index_dirty_from_target) {
func.runtime.ui.mark_refresh_index_dirty_from_target($targets);
}
const targets = $targets.toArray();
for (let index = 0; index < targets.length; index++) {
targets[index].remove?.();
}
return true;
};
func.runtime.ui.build_debug_info = function (nodeP, $container, items) {
return {
id: nodeP.id,
parent_id: func.runtime.ui.get_data($container)?.xuData?.ui_id,
items: items,
};
};
func.runtime.ui.get_node_snapshot = function (nodeP) {
if (!nodeP) {
return nodeP;
}
if (func.runtime.ui.node_snapshot_cache.has(nodeP)) {
return func.runtime.ui.node_snapshot_cache.get(nodeP);
}
const snapshot = structuredClone(nodeP);
func.runtime.ui.node_snapshot_cache.set(nodeP, snapshot);
return snapshot;
};
func.runtime.ui.get_node_child_items = function (nodeP) {
if (!nodeP?.children?.length) {
return [];
}
if (func.runtime.ui.node_child_items_cache.has(nodeP)) {
return func.runtime.ui.node_child_items_cache.get(nodeP);
}
const items = nodeP.children.map(function (val) {
return val.xu_tree_id || val.id;
});
func.runtime.ui.node_child_items_cache.set(nodeP, items);
return items;
};
func.runtime.ui.get_node_children_by_id = function (nodeP) {
if (!nodeP?.children?.length) {
return {};
}
if (func.runtime.ui.node_children_by_id_cache.has(nodeP)) {
return func.runtime.ui.node_children_by_id_cache.get(nodeP);
}
const children_by_id = {};
for (let index = 0; index < nodeP.children.length; index++) {
const child_node = nodeP.children[index];
if (child_node?.id) {
children_by_id[child_node.id] = child_node;
}
}
func.runtime.ui.node_children_by_id_cache.set(nodeP, children_by_id);
return children_by_id;
};
func.runtime.ui.build_container_xu_data = function (options) {
return {
SESSION_ID: options.SESSION_ID,
prog_id: options.paramsP.prog_id,
nodeid: options.nodeP.id,
ui_type: options.nodeP.tagName,
recordid: options.currentRecordId,
paramsP: options.paramsP,
key: options.keyP,
key_path: options.key_path,
screenId: options.paramsP.screenId,
parent_container: func.runtime.ui.get_attr(options.$container, 'id'),
elem_key: options.elem_key,
properties: options.prop,
node: options.nodeP,
node_org: func.runtime.ui.get_node_snapshot(options.nodeP),
is_panelP: options.paramsP.is_panelP,
ui_id: options.ui_id,
elem_prop: options.elem_propP,
debug_info: func.runtime.ui.build_debug_info(options.nodeP, options.$container, options.items),
parent_node: options.parent_nodeP,
currentRecordId: options.currentRecordId,
$root_container: options.$root_container,
parent_element_ui_id: func.runtime.ui.get_data(options.$container)?.xuData?.ui_id,
is_placeholder: !!options.is_placeholder,
};
};
func.runtime.ui.apply_container_meta = function ($div, options) {
const div_node = func.runtime.ui.get_first_node($div);
func.runtime.ui.set_attr(div_node, 'xu-ui-id', options.ui_id);
func.runtime.ui.set_attr(div_node, 'data-xuda-kind', options.treeP?.kind || options.nodeP?.tagName || 'element');
func.runtime.ui.set_attr(div_node, 'data-xuda-node-id', options.nodeP?.id || options.nodeP?.id_org || '');
if (options.treeP?.meta?.tree_id !== null && typeof options.treeP?.meta?.tree_id !== 'undefined') {
func.runtime.ui.set_attr(div_node, 'data-xuda-tree-id', options.treeP.meta.tree_id);
}
const xuData = func.runtime.ui.build_container_xu_data(options);
if (options.parent_infoP?.iterate_info) {
xuData.iterate_info = options.parent_infoP.iterate_info;
}
func.runtime.ui.set_data(div_node, 'xuData', xuData);
func.runtime.ui.set_data(div_node, 'xuAttributes', {});
// dual-write to meta store
func.runtime.ui.set_meta(options.ui_id, 'xuData', xuData);
func.runtime.ui.set_meta(options.ui_id, 'xuAttributes', {});
// register element id mapping for lookups by container/screen id
const container_id = func.runtime.ui.get_attr(div_node, 'id');
if (container_id) {
func.runtime.ui.register_element_id(container_id, options.ui_id);
}
if (options.is_placeholder) {
func.runtime.ui.add_class(div_node, 'display_none');
}
if (options.classP) {
func.runtime.ui.add_class(div_node, options.classP);
}
return $div;
};
func.runtime.ui.get_append_target = function ($container, $appendToP) {
const $appendTo = $appendToP || $container;
if (!$appendTo) {
return null;
}
// Support both native elements (check nodeType) and jQuery/array-like (check length)
const node = func.runtime.ui.get_first_node($appendTo);
if (!node) {
return null;
}
return $appendTo;
};
func.runtime.ui.create_element = function (tag_name, attr_str) {
const el = document.createElement(tag_name);
if (attr_str) {
// Parse attribute string: key="value" or key='value' or bare key
const attr_regex = /([a-zA-Z_][\w\-.:]*)\s*(?:=\s*(?:"([^"]*)"|'([^']*)'|(\S+)))?/g;
let match;
while ((match = attr_regex.exec(attr_str)) !== null) {
const key = match[1];
const value = match[2] !== undefined ? match[2] : (match[3] !== undefined ? match[3] : (match[4] !== undefined ? match[4] : ''));
if (func.runtime.ui.should_remove_attr(key, value)) {
continue;
}
const normalized_value = func.runtime.ui.normalize_attr_value(tag_name, key, value);
try {
el.setAttribute(key, normalized_value);
} catch (error) {
console.warn(`Failed to set attribute "${key}" on <${tag_name}>`, error);
}
}
}
return el;
};
func.runtime.ui.create_svg_element = function (element, prop, nodeP, $appendTo) {
const get_tag_str = function (element, prop, val) {
let attr_str = '';
for (const [key, value] of Object.entries(prop)) {
if (key.substr(0, 2) !== 'xu') {
if (func.runtime.ui.should_remove_attr(key, value)) {
continue;
}
const normalized_value = func.runtime.ui.normalize_attr_value(element, key, value);
attr_str += ` ${key}="${normalized_value}" `;
}
}
if (element === 'svg') {
return `<${element} ${attr_str} > `;
}
let ret = '';
if (val?.children?.length) {
ret = iterate_svg(val);
}
return `<${element} ${attr_str} > ${ret} </${element}>`;
};
const iterate_svg = function (node) {
let ret = '';
if (node.children) {
for (let val of node.children) {
if (val.type === 'comment') continue;
ret += get_tag_str(val.tagName, val.attributes, val);
}
}
return ret;
};
const svg_str = get_tag_str(element, prop);
const inner_str = iterate_svg(nodeP);
const full_svg_str = svg_str + inner_str + '</svg>';
// Parse the SVG string into a DOM element via a temporary container
const tmp = document.createElement('div');
tmp.innerHTML = full_svg_str;
const svg_el = tmp.firstElementChild;
return func.runtime.ui.append_to(svg_el, $appendTo);
};
func.runtime.ui.create_container_element = function (div_typeP, attr_str, prop, nodeP, $appendTo) {
const div = div_typeP || 'div';
if (div === 'svg') {
return func.runtime.ui.create_svg_element(div_typeP, prop, nodeP, $appendTo);
}
return func.runtime.ui.create_element(div, attr_str);
};
func.runtime.ui.find_hydration_candidate = function (options) {
if (!func.runtime.render.is_hydration_mode(SESSION_OBJ?.[options.SESSION_ID])) {
return null;
}
if (!func.runtime.render.should_use_ssr_payload(options.SESSION_ID, options.paramsP)) {
return null;
}
if (options.is_placeholder || !options.treeP?.meta?.tree_id) {
return null;
}
const append_node = func.runtime.ui.get_first_node(options.$appendTo || options.$container);
if (!append_node) {
return null;
}
const children = func.runtime.ui.get_children(append_node);
for (let index = 0; index < children.length; index++) {
const child = children[index];
if (child?.__xuda_hydration_claimed) {
continue;
}
if (func.runtime.ui.get_attr(child, 'data-xuda-tree-id') !== `${options.treeP.meta.tree_id}`) {
continue;
}
child.__xuda_hydration_claimed = true;
func.runtime.ui.set_attr(child, 'data-xuda-client-activation', 'hydrate');
return child;
}
return null;
};
func.runtime.ui.build_xu_ui_id_seed = function (nodeP, dsSessionP, key_path, currentRecordId) {
const nodeId = nodeP.xu_tree_id || nodeP.id;
const elem_key = `${nodeId}-${key_path}-${currentRecordId}`;
return `${nodeP.id}-${elem_key}-${dsSessionP?.toString() || ''}`;
};
func.runtime.ui.build_container_key_path = function (container_xu_data, keyP, parent_infoP, nodeP, parent_nodeP) {
const key_segment = typeof keyP === 'undefined' || keyP === null ? '0' : `${keyP}`;
let key_path = `${container_xu_data?.key_path || '0'}-${key_segment}`;
const parent_identity = parent_nodeP?.xu_tree_id || parent_nodeP?.id;
const node_identity = nodeP?.xu_tree_id || nodeP?.id;
const is_iterated_clone = !!(parent_infoP?.iterate_info && parent_identity && node_identity && parent_identity === node_identity);
if (is_iterated_clone) {
key_path += '-iter';
}
return key_path;
};
func.runtime.ui.generate_xu_ui_id = async function (SESSION_ID, nodeP, $container, paramsP, keyP, precomputed = {}) {
const dsSessionP = paramsP.dsSessionP;
const _ds = SESSION_OBJ[SESSION_ID].DS_GLB[dsSessionP];
const containerXuData = precomputed.container_xu_data || func.runtime.ui.get_data($container)?.xuData;
let currentRecordId = typeof precomputed.currentRecordId !== 'undefined' ? precomputed.currentRecordId : containerXuData?.recordid || _ds?.currentRecordId || '';
// Same sentinel rule as create_container: an inherited 'newRecord' must not shadow the
// datasource's real positioned row (see create_container for the full failure mode).
if (currentRecordId === 'newRecord' && _ds?.currentRecordId && _ds.currentRecordId !== 'newRecord') {
const _live_rows = _ds.data_feed?.rows;
if (Array.isArray(_live_rows) && _live_rows.some((row) => row._ROWID === _ds.currentRecordId)) {
currentRecordId = _ds.currentRecordId;
}
}
const key_path = precomputed.key_path || func.runtime.ui.build_container_key_path(containerXuData, keyP, precomputed.parent_infoP, nodeP, precomputed.parent_nodeP);
const ui_id = func.runtime.ui.build_xu_ui_id_seed(nodeP, dsSessionP, key_path, currentRecordId);
if (func.runtime.ui.ui_id_hash_cache.has(ui_id)) {
return func.runtime.ui.ui_id_hash_cache.get(ui_id);
}
const hashed_ui_id = await func.common.fastHash(ui_id);
func.runtime.ui.ui_id_hash_cache.set(ui_id, hashed_ui_id);
return hashed_ui_id;
};
func.runtime.ui.create_container = async function (options) {
let _paramsP;
if (glb.XU_PERF) {
// paramsP carries callingDataSource_objP (full datasource) and screenInfo
// (full view doc); the JSON round-trip below serializes both per ELEMENT,
// which is quadratic on list size. The catch-path has always fallen back
// to this same shallow copy whenever paramsP is circular.
_paramsP = Object.assign({}, options.paramsP);
} else {
try {
_paramsP = JSON.parse(JSON.stringify(options.paramsP));
} catch (e) {
// paramsP may contain DOM element refs that create circular structures;
// fall back to a shallow copy which is sufficient for create_container.
_paramsP = Object.assign({}, options.paramsP);
}
}
const _ds = SESSION_OBJ[options.SESSION_ID].DS_GLB[_paramsP.dsSessionP];
const $appendTo = func.runtime.ui.get_append_target(options.$container, options.$appendToP);
if (!$appendTo) return null;
const container_data = func.runtime.ui.get_data(options.$container);
const container_xu_data = container_data?.xuData;
const items = func.runtime.ui.get_node_child_items(options.nodeP);
let currentRecordId = container_xu_data?.recordid || (_ds ? _ds.currentRecordId : '');
// A 'newRecord' inherited from the container must not shadow a real positioned row of the
// child's own datasource. An array/JSON-datasource multi-view stamps its grid while the ds
// rests on the create-mode sentinel, then renders each row with a real currentRecordId; if
// the sentinel wins, every child gets a dead record binding — its click adopts 'newRecord'
// as the ds current record, row lookups fail and all further updates abort (game pager:
// page numbers dead, then arrows and reopen wedged).
if (currentRecordId === 'newRecord' && _ds?.currentRecordId && _ds.currentRecordId !== 'newRecord') {
const _live_rows = _ds.data_feed?.rows;
if (Array.isArray(_live_rows) && _live_rows.some((row) => row._ROWID === _ds.currentRecordId)) {
currentRecordId = _ds.currentRecordId;
}
}
try {
const key_path = func.runtime.ui.build_container_key_path(container_xu_data, options.keyP, options.parent_infoP, options.nodeP, options.parent_nodeP);
const elem_key = `${options.nodeP.xu_tree_id || options.nodeP.id}-${key_path}-${currentRecordId}`;
const hydration_candidate = func.runtime.ui.find_hydration_candidate({
...options,
$appendTo,
});
const $div = hydration_candidate || func.runtime.ui.create_container_element(options.div_typeP, options.attr_str, options.prop, options.nodeP, $appendTo);
const new_ui_id = await func.runtime.ui.generate_xu_ui_id(options.SESSION_ID, options.nodeP, options.$container, options.paramsP, options.keyP, {
container_xu_data,
currentRecordId,
key_path,
parent_infoP: options.parent_infoP,
parent_nodeP: options.parent_nodeP,
});
func.runtime.ui.apply_container_meta($div, {
ui_id: new_ui_id,
paramsP: _paramsP,
nodeP: options.nodeP,
currentRecordId,
keyP: options.keyP,
key_path,
$container: options.$container,
prop: options.prop,
elem_key,
elem_propP: options.elem_propP,
items,
parent_nodeP: options.parent_nodeP,
$root_container: options.$root_container,
parent_infoP: options.parent_infoP,
is_placeholder: options.is_placeholder,
classP: options.classP,
treeP: options.treeP,
});
if (!hydration_candidate && options.div_typeP !== 'svg') {
func.runtime.ui.append_to($div, $appendTo);
}
return $div;
} catch (e) {
console.error(e);
}
return null;
};
func.UI.utils = {};
func.UI.utils.indicator = {};
func.UI.utils.indicator.worker = {};
func.UI.utils.indicator.worker.busy = function () {
document.querySelectorAll('.progressLoader').forEach(function (el) { el.classList.add('progress_busy'); });
};
func.UI.utils.indicator.worker.normal = function () {
document.querySelectorAll('.progressLoader').forEach(function (el) { el.classList.remove('progress_busy'); });
};
func.UI.utils.indicator.server = {};
func.UI.utils.indicator.server.busy = function () {
func.UI.utils.indicator.worker.busy();
};
func.UI.utils.indicator.server.normal = function () {
func.UI.utils.indicator.worker.normal();
};
func.UI.utils.indicator.screen = {};
func.UI.utils.indicator.screen.busy = function () {
document.querySelectorAll('.progressLoader').forEach(function (el) { el.classList.add('progress_busy2'); });
};
func.UI.utils.indicator.screen.normal = function () {
document.querySelectorAll('.progressLoader').forEach(function (el) { el.classList.remove('progress_busy2'); });
};
func.UI.utils.save = function (SESSION_ID, stateP) {
if (stateP) func.UI.utils.indicator.worker.busy();
else func.UI.utils.indicator.worker.normal();
};
func.UI.utils.screen_blocker = function (onP, idP, dsP) {
if (!idP) {
func.utils.debug_report('', 'Worker', 'Missing reference id', 'E');
return;
}
window.oncontextmenu = function () {
if (onP) return false;
else return true;
};
if (!onP) {
delete SCREEN_BLOCKER_OBJ[idP];
// Screen just settled: immediately reconcile teleports (drop orphans /
// mirror host visibility) instead of waiting for the 1s maintenance tick.
// Cheap no-op when there are no teleports.
if (xu_isEmpty(SCREEN_BLOCKER_OBJ) && func.UI?.reconcile_teleports) {
try {
func.UI.reconcile_teleports();
} catch (e) {}
}
return;
}
if (idP !== 'Worker') {
SCREEN_BLOCKER_OBJ[idP] = Date.now();
}
};
// Browser runtime helpers moved to xuda_runtime.browser.js.
func.UI.utils.get_node_elm = function (SESSION_ID, dsSessionP, ui_idP, $container, is_app_panel, ui_type, functionP) {
if (!$container) {
$container = func.runtime.ui._wrap_matches([document.body]);
}
var $elm;
if (!is_app_panel && func.runtime?.ui?.find_xu_ui_in_root) {
$elm = func.runtime.ui.find_xu_ui_in_root(SESSION_ID, ui_idP);
} else if (is_app_panel && func.runtime?.ui?.find_panel_wrapper_in_root) {
$elm = func.runtime.ui.find_panel_wrapper_in_root(SESSION_ID, ui_idP);
}
if (!$elm?.length) {
$elm = func.UI.utils.find_in_element_data(is_app_panel ? 'xuPanelData' : 'xuData', $container, 'ui_id', ui_idP);
}
const _session = SESSION_OBJ[SESSION_ID];
var _ds = _session.DS_GLB[dsSessionP];
if (_ds.tree_obj.renderType === 'form') {
return $elm;
}
var $grid_elm;
const grid_elements = $elm.toArray();
for (let index = 0; index < grid_elements.length; index++) {
const candidate = grid_elements[index];
if (func.runtime.ui.get_data(candidate)?.xuData?.recordid === _ds.currentRecordId) {
$grid_elm = func.runtime.ui._wrap_matches([candidate]);
break;
}
}
return $grid_elm;
return $elm;
};
func.UI.utils.get_nodeId = function (SESSION_ID, dsSessionP, ui_idP, $container, is_app_panel) {
var $elm = func.UI.utils.get_node_elm(SESSION_ID, dsSessionP, ui_idP, $container, is_app_panel, null, null);
if (is_app_panel) {
return func.runtime.ui.get_data($elm)?.xuData?.panel_info?.prop?.id;
} else {
return func.runtime.ui.get_attr($elm, 'nodeId');
}
};
// func.UI.utils.get_element_info = function (SESSION_ID, dsSessionP, ui_idP, $container, is_app_panel, ui_type, functionP) {
// var $elm = func.UI.utils.get_node_elm(SESSION_ID, dsSessionP, ui_idP, $container, is_app_panel, ui_type, functionP);
// var ret = {};
// if ($elm?.length) {
// //length added 20210209
// // if (is_app_panel) {
// // if ($elm?.data()?.xuData.panel_info) {
// // ret.nodeId = $elm.data().xuData.panel_info.prop.id;
// // } else {
// // ret.nodeId = $elm.data().xuData.properties.id;
// // }
// // } else {
// // ret.nodeId = $elm.data().xuData.nodeId;
// ret.nodeId = $elm.data().xuData.xu_id;
// // ret.nodeId = $elm.attr('xu-ui-id');
// // }
// }
// ret.$elm = $elm;
// return ret;
// };
func.UI.utils.get_ui_id_count = function (SESSION_ID, dsSessionP, ui_idP, $container) {
return func.UI.utils.get_node_elm(SESSION_ID, dsSessionP, ui_idP, $container, null, null).length;
};
// func.UI.utils.get_ui_info_tree_scope = function (SESSION_ID, dsP, ui_id, is_app_panel, ui_type, $container, functionP) {
// var drill_parent = function () {
// if (SESSION_OBJ[SESSION_ID].DS_GLB[dsP].parentDataSourceNo) {
// return func.UI.utils.get_ui_info_tree_scope(SESSION_ID, SESSION_OBJ[SESSION_ID].DS_GLB[dsP].parentDataSourceNo, ui_id, is_app_panel, ui_type);
// } else if (ui_type === 'xu-app-page') {
// if (elm_info.$elm.length) {
// return {
// ds: dsP,
// id: id,
// $elm: elm_info.$elm,
// };
// }
// }
// };
// if (!SESSION_OBJ[SESSION_ID].DS_GLB[dsP]) return;
// var elm_info = func.UI.utils.get_element_info(SESSION_ID, dsP, ui_id, $container, is_app_panel, ui_type, functionP);
// var id = elm_info.nodeId;
// if (!id) {
// return drill_parent();
// } else {
// if (is_app_panel) {
// return {
// ds: func.UI.utils.get_node_elm(SESSION_ID, dsP, ui_id, $container, is_app_panel).data().xuData.paramsP.dsSessionP,
// id: id,
// $elm: elm_info.$elm,
// };
// } else {
// return {
// ds: dsP,
// id: id,
// $elm: elm_info.$elm,
// };
// }
// }
// };
func.UI.utils.clean_node_busy = function (node) {
var run_node = function (node) {
node.busy = false;
for (var key in node.children) {
run_node(node.children[key]);
}
};
run_node(node);
return node;
};
// func.UI.utils.get_ui_info_tree_scope_sync = function (SESSION_ID, dsP, ui_id, ui_type, callback, $container, functionP) {
// var ret;
// var is_app_panel = false;
// if (ui_type === 'xu-panel') {
// is_app_panel = true;
// }
// ret = func.UI.utils.get_ui_info_tree_scope(SESSION_ID, dsP, ui_id, is_app_panel, ui_type, $container, functionP);
// if (!ret) {
// var attempts = 0;
// const run = function () {
// ret = func.UI.utils.get_ui_info_tree_scope(SESSION_ID, dsP, ui_id, is_app_panel, ui_type, $container, functionP);
// if (ret || attempts > 10) {
// callback(ret);
// } else {
// attempts++;
// console.log(attempts, dsP, ui_id, is_app_panel);
// setTimeout(function () {
// run();
// }, 100);
// }
// };
// run();
// } else {
// callback(ret);
// }
// };
func.UI.utils.live_preview_element_inspect_on = function (SESSION_ID, service) {
var elements = document.querySelectorAll('[xu-ui-id]');
elements.forEach(function (val) {
var _mouseenter_handler = function () {
document.querySelectorAll('.preview_mark').forEach(function (el) {
el.classList.remove('preview_mark');
el.removeEventListener('click', el._live_preview_click_handler);
});
val.classList.add('preview_mark');
var _click_handler = function (e) {
const _session = SESSION_OBJ[SESSION_ID];
console.log(func.runtime.ui.get_data(this));
const data = func.runtime.ui.get_data(this);
const obj = {
service: service + '_result',
id: STUDIO_WEBSOCKET_CONNECTION_ID,
uid: _session.USR_OBJ._id,
source: 'runtime',
app_id: _session.app_id,
gtp_token: _session.gtp_token,
session_id: SESSION_ID,
app_token: _session.app_token,
};
switch (service) {
case 'live_preview_element_reference':
obj.data = { prog_id: data.xuData.prog_id, node: data.xuData.node };
break;
case 'live_preview_element_info':
obj.data = {
element_info: data.debug_info,
datasource: _session.DS_GLB[data.paramsP.dsSessionP],
};
break;
case 'live_preview_element_dnd':
// code block
break;
default:
// code block
}
STUDIO_PEER_CONN_SEND_METHOD(obj);
// STUDIO_WEBSOCKET.emit("message", obj);
func.UI.utils.live_preview_element_inspect_off();
if (typeof LIVE_PREVIEW_APP_ACTIVE !== 'undefined') {
var refBtn = document.getElementById('live_preview_element_reference_btn');
if (refBtn) refBtn.style.color = 'unset';
var infoBtn = document.getElementById('live_preview_element_info_btn');
if (infoBtn) infoBtn.style.color = 'unset';
}
};
val._live_preview_click_handler = _click_handler;
val.addEventListener('click', _click_handler);
};
var _mouseleave_handler = function () {
val.classList.remove('preview_mark');
if (val._live_preview_click_handler) {
val.removeEventListener('click', val._live_preview_click_handler);
delete val._live_preview_click_handler;
}
};
val._live_preview_mouseenter_handler = _mouseenter_handler;
val._live_preview_mouseleave_handler = _mouseleave_handler;
val.addEventListener('mouseenter', _mouseenter_handler);
val.addEventListener('mouseleave', _mouseleave_handler);
});
};
func.UI.utils.live_preview_element_inspect_off = function () {
document.querySelectorAll('[xu-ui-id]').forEach(function (val) {
if (val._live_preview_mouseenter_handler) {
val.removeEventListener('mouseenter', val._live_preview_mouseenter_handler);
delete val._live_preview_mouseenter_handler;
}
if (val._live_preview_mouseleave_handler) {
val.removeEventListener('mouseleave', val._live_preview_mouseleave_handler);
delete val._live_preview_mouseleave_handler;
}
});
document.querySelectorAll('.preview_mark').forEach(function (el) {
el.classList.remove('preview_mark');
if (el._live_preview_click_handler) {
el.removeEventListener('click', el._live_preview_click_handler);
delete el._live_preview_click_handler;
}
});
};
func.UI.utils.live_preview_show_selected_element = function (nodeid) {
document.querySelectorAll('.preview_mark').forEach(function (el) { el.classList.remove('preview_mark'); });
document.querySelectorAll(`[nodeid="${nodeid}"]`).forEach(function (el) { el.classList.add('preview_mark'); });
};
func.UI.utils.get_url_attribute = function (SESSION_ID, key) {
const _session = SESSION_OBJ[SESSION_ID];
const platform = func.runtime.platform;
const url_param = glb.URL_PARAMS?.get?.(key) || (key === 'app_id' ? glb.URL_PARAMS?.get?.('id') : null);
const root_attribute = func.runtime.ui.get_attr(_session.root_element, key);
const option_param = _session.opt?.params?.[key];
const option_value = _session.opt?.[key];
const cookie_value = platform.get_cookie_item(key);
const storage_value = platform.get_storage_item(key, 'local');
return url_param || root_attribute || option_param || option_value || cookie_value || storage_value;
};
func.UI.utils.get_root_element_attributes = function (SESSION_ID) {
// test2345
var ret = {};
var root_el = func.runtime.ui.get_first_node(SESSION_OBJ[SESSION_ID].root_element);
if (root_el) {
var attrs = root_el.attributes;
for (var i = 0; i < attrs.length; i++) {
// attributes is not a plain object, but an array
// of attribute nodes, which contain both the name and value
if (attrs[i].specified) {
ret[attrs[i].name] = attrs[i].value;
}
}
}
return ret;
};
func.UI.utils.prompt_confirm_window = async function (SESSION_ID, messageP, picP, confirmYesFuncP, confirmNoFuncP, confirmCancelFuncP, title, colorP) {
if (confirmNoFuncP) {
buttons.push({
text: 'Disagree',
role: 'no',
cssClass: 'secondary',
handler: () => {
confirmNoFuncP();
},
});
}
if (confirmYesFuncP) {
buttons.push({
text: 'Agree',
role: 'yes',
cssClass: 'secondary',
handler: () => {
confirmYesFuncP();
},
});
}
if (confirmCancelFuncP) {
buttons.push({
text: 'Dismiss',
role: 'cancel',
cssClass: 'secondary',
handler: () => {
confirmCancelFuncP();
},
});
}
UI_FRAMEWORK_PLUGIN.modal(title, messageP, buttons);
};
func.UI.utils.alert = function (msg) {
console.error(msg);
};
func.UI.utils.progressScreen = {};
func.UI.utils.progressScreen.show = function (SESSION_ID, textP, show_bytesP, error, progress_off, logo_off) {
if (glb.IS_WORKER) {
return;
}
const app_obj = APP_OBJ?.[SESSION_OBJ?.[SESSION_ID]?.app_id];
var background_color = '';
var icon = app_obj?._conf?.logo_url || 'https://xuda.ai/dist/images/xuda_logo.png';
if (app_obj?.app_pic) {
icon = app_obj.app_pic;
}
if (app_obj && app_obj.app_icon_prop) {
if (app_obj.app_icon_prop.app_icon_background_color) {
background_color = app_obj.app_icon_prop.app_icon_background_color;
}
// if (app_obj.app_type === "master_team" && app_obj.app_pic) {
// let app_id = APP_OBJ[SESSION_OBJ[SESSION_ID].app_id];
// if (app_obj.app_replicate) {
// app_id = app_obj.app_replicate;
// }
// }
}
IS_PROGRESS_SCREEN_OPEN = true;
var progressScreen = document.getElementById('progressScreen2');
if (progressScreen) progressScreen.innerHTML = '';
document.querySelectorAll('.loader').forEach(function (el) { el.style.display = 'none'; });
if (background_color && progressScreen) {
progressScreen.style.color = func.common.getContrast_color(background_color);
progressScreen.style.backgroundColor = background_color;
}
setTimeout(function () {
if (IS_PROGRESS_SCREEN_OPEN) {
var error_msg = `<h4>${textP}</h4>`;
// $("#progressScreen2_text").fadeIn(500, function () {
// if (!logo_off) {
// $(this).prepend(`<img class='progressScreen_logo' src='${icon}'>`);
// }
// $(this).append(
// error
// ? error_msg
// : typeof textP === "object"
// ? textP
// : `<p>${textP}</p>`
// );
// });
var progressText = document.getElementById('progressScreen2_text');
if (progressText) {
progressText.style.display = '';
if (!logo_off) {
var img = document.createElement('img');
img.className = 'progressScreen_logo';
img.src = icon;
progressText.prepend(img);
}
if (error) {
progressText.insertAdjacentHTML('beforeend', error_msg);
} else if (typeof textP === 'object') {
progressText.appendChild(textP);
} else {
progressText.insertAdjacentHTML('beforeend', `<p>${textP}</p>`);
}
}
}
}, 500);
if (progressScreen) progressScreen.style.display = '';
var textDiv = document.createElement('div');
textDiv.id = 'progressScreen2_text';
textDiv.style.display = 'none';
if (progressScreen) progressScreen.appendChild(textDiv);
// .hide()
// .fadeIn("slow"); //.append(textP)
};
func.UI.utils.progressScreen.hide = function () {
if (glb.IS_WORKER) {
return;
}
IS_PROGRESS_SCREEN_OPEN = false;
// window.clearInterval(PROGRESS_INTERVAL);
// setTimeout(function () {
var ps2 = document.getElementById('progressScreen2');
if (ps2) ps2.style.display = 'none';
var ps2text = document.getElementById('progressScreen2_text');
if (ps2text) ps2text.innerHTML = '';
// $("#progressScreen2").css({
// height: "0px",
// top: "-100px",
// "background-image": "none"
// });
};
func.UI.utils.find_in_element_data = function (folder, $elm, key, val) {
if (!$elm?.length) {
return func.runtime.ui._wrap_matches([]);
}
if (folder === 'xuData' && key === 'ui_id' && typeof val !== 'undefined') {
return func.runtime.ui.find_by_selector($elm, `[xu-ui-id="${val}"]`);
}
if (folder === 'xuPanelWrapper' && key === 'isWrapper' && typeof val === 'undefined') {
return func.runtime.ui.find_by_selector($elm, '[xu-panel-wrapper-id]');
}
let candidate_selector;
if (folder === 'xuData' || folder === 'xuPanelData') {
candidate_selector = '[xu-ui-id]';
} else if (folder === 'xuPanelWrapper') {
candidate_selector = '[xu-panel-wrapper-id]';
} else {
candidate_selector = '*';
}
const matches = [];
const roots = $elm.toArray();
for (let root_index = 0; root_index < roots.length; root_index++) {
const root_node = roots[root_index];
const candidates = root_node?.querySelectorAll?.(candidate_selector) || [];
for (let candidate_index = 0; candidate_index < candidates.length; candidate_index++) {
const candidate = candidates[candidate_index];
const folder_data = func.runtime.ui.get_data(candidate)?.[folder];
if (!folder_data) {
continue;
}
if (typeof val === 'undefined') {
if (!folder_data[key]) {
continue;
}
} else if (folder_data[key] != val) {
continue;
}
matches.push(candidate);
}
}
return func.runtime.ui._wrap_matches(matches);
};
func.UI.utils.init_ui_framework = async function (SESSION_ID, prog_id) {
if (typeof glb.SLIM_BUNDLE !== 'undefined' || glb.SLIM_BUNDLE) return;
var _session = SESSION_OBJ[SESSION_ID];
var tree_obj = await func.utils.TREE_OBJ.get(SESSION_ID, prog_id);
if (xu_isEmpty(tree_obj)) {
return console.error('Error: prog ' + prog_id + ' not found.');
}
const report_error = function (descP, warn) {
func.utils.debug.log(SESSION_ID, prog_id, {
module: 'component',
action: 'Init',
source: 'install ui framework',
prop: descP,
details: descP,
result: null,
error: warn ? false : true,
fields: null,
type: 'component',
prog_id: prog_id,
});
};
const plugin_name = tree_obj.uiFramework;
if (!plugin_name) {
return report_error('no frameworks plugin defined', true);
}
if (plugin_name === UI_FRAMEWORK_INSTALLED) return;
const _plugin = APP_OBJ[_session.app_id]?.app_plugins_purchased?.[plugin_name];
if (!_plugin?.installed) {
return report_error(`plugin ${plugin_name} not installed`);
}
var _ui_framework_index;
try {
const runtime_mjs = `${_plugin.manifest['runtime.mjs'].dist ? 'dist/' : ''}runtime.mjs`;
_ui_framework_index = await func.utils.get_plugin_resource(SESSION_ID, plugin_name, runtime_mjs);
} catch (error) {
return report_error(`plugin ${plugin_name} not found`);
}
if (!_ui_framework_index) {
return report_error(`plugin ${plugin_name} is empty`);
}
if (!_ui_framework_index.core) {
return report_error(`plugin core not found in ${plugin_name} `);
}
// if (!_ui_framework_index.resources) {
// return report_error(`plugin resources not found in ${plugin_name} `);
// }
var _ui_framework_dashboard_setup;
var _ui_framework_dashboard_setup_data_ret;
const ui_framework_core = new _ui_framework_index.core();
if (ui_framework_core.init) {
try {
const setup_mjs = `${_plugin.manifest['index.mjs'].dist ? 'dist/' : ''}index.mjs`;
_ui_framework_dashboard_setup = await func.utils.get_plugin_resource(SESSION_ID, plugin_name, setup_mjs);
if (_ui_framework_dashboard_setup) {
_ui_framework_dashboard_setup_data_ret = await func.utils.get_plugin_setup(SESSION_ID, plugin_name);
}
} catch (error) {
await func.utils.report_issue(SESSION_ID, {
code: 'RUN_MSG_GUI_020',
source: 'get_plugin_setup',
message: `plugin setup import failed for ${plugin_name}`,
type: 'W',
err: error,
details: {
plugin_name,
},
});
}
}
if (plugin_name !== UI_FRAMEWORK_INSTALLED) {
UI_FRAMEWORK_INSTALLED = plugin_name;
const _plugin_INSTALLED = APP_OBJ[_session.app_id]?.app_plugins_purchased?.[UI_FRAMEWORK_INSTALLED];
UI_FRAMEWORK_PLUGIN = _ui_framework_index;
if (UI_FRAMEWORK_INSTALLED) {
var _current_ui_framework_runtime;
try {
const _runtime_mjs = `${_plugin_INSTALLED.manifest['runtime.mjs'].dist ? 'dist/' : ''}runtime.mjs`;
_current_ui_framework_runtime = await func.utils.get_plugin_resource(SESSION_ID, UI_FRAMEWORK_INSTALLED, _runtime_mjs);
} catch (error) {
return report_error(`plugin ${UI_FRAMEWORK_INSTALLED} not found`);
}
// remove
if (UI_FRAMEWORK_PLUGIN.core.discard && UI_FRAMEWORK_PLUGIN.init_id) {
UI_FRAMEWORK_PLUGIN.core.discard(UI_FRAMEWORK_PLUGIN.init_id);
}
if (_ui_framework_index.resources) {
for (var key in _current_ui_framework_runtime.resources) {
var val = _current_ui_framework_runtime.resources[key];
func.utils.remove_js_css_file(val.url, val.type);
}
}
}
// install
var init_id;
if (_ui_framework_index.resources) {
for await (var val of _ui_framework_index.resources) {
var ret = undefined;
var url = val.url;
switch (val.type) {
case 'module':
try {
// ret = await load_module(url);
ret = await func.utils.load_js_on_demand(url, 'module');
} catch (error) {
console.error('[xuda-runtime] caught xuda_UI.utils.js:630:', error);
}
break;
case 'css':
ret = func.utils.load_css_on_demand(url);
break;
case 'js':
ret = await func.utils.load_js_on_demand(url);
break;
default:
break;
}
if (val.callback) {
val.callback(ret);
}
}
}
if (ui_framework_core.init) {
init_id = await ui_framework_core.init(_ui_framework_dashboard_setup_data_ret?.code > -1 && _ui_framework_dashboard_setup_data_ret.data);
UI_FRAMEWORK_PLUGIN.init_id = init_id;
}
}
};
// old
// func.UI.utils.get_panels_from_dom = function (SESSION_ID, ignore_disableAutoRefresh) {
// const $elm = func.UI.utils.find_in_element_data('xuPanelData', $(SESSION_OBJ[SESSION_ID].root_element), 'parent_element_ui_id');
// var panels_obj = {};
// // set panels_obj
// for (const [elem_key, elem_val] of Object.entries($elm)) {
// if (elem_key === 'length') break;
// var $div = $(elem_val);
// let xuData = $div.data().xuData;
// if (!$div.data().xuPanelData) continue;
// let dsSession = xuData.paramsP.dsSessionP;
// var _session = SESSION_OBJ[SESSION_ID];
// let _ds = _session?.DS_GLB[dsSession];
// if (!_ds) continue;
// if (!ignore_disableAutoRefresh && _ds.tree_obj.disableAutoRefresh) {
// continue;
// }
// const parent_element_ui_id = $div.data().xuPanelData.parent_element_ui_id;
// if (!panels_obj[parent_element_ui_id]) {
// panels_obj[parent_element_ui_id] = {
// _ds,
// $div,
// ids: [],
// };
// }
// panels_obj[parent_element_ui_id].ids.push($div.attr('xu-ui-id'));
// }
// return panels_obj;
// };
func.UI.utils.get_panels_wrapper_from_dom = async function (SESSION_ID, $xu_embed_container, ignore_disableAutoRefresh) {
const get_refresh_state = function () {
return func.runtime?.ui?.ensure_refresh_dependency_state?.(SESSION_ID) || null;
};
const get_cached_panels_obj = function (refresh_state) {
const cached_panels = ignore_disableAutoRefresh ? refresh_state?.panel_wrappers_cache : refresh_state?.panel_wrappers_active_cache;
const panels_obj = cached_panels || {};
let requires_rebuild = false;
const panel_keys = Object.keys(refresh_state?.panel_wrappers_cache || {});
for (let index = 0; index < panel_keys.length; index++) {
const panel_entry = refresh_state.panel_wrappers_cache[panel_keys[index]];
if (!panel_entry?.$panel_div?.length || !panel_entry.$panel_div[0]?.isConnected) {
requires_rebuild = true;
break;
}
}
if (requires_rebuild) {
refresh_state.panel_wrappers_dirty = true;
refresh_state.panel_wrappers_cache = {};
refresh_state.panel_wrappers_active_cache = {};
return null;
}
return panels_obj;
};
const refresh_state = get_refresh_state();
if (refresh_state && !refresh_state.panel_wrappers_dirty && !xu_isEmpty(refresh_state.panel_wrappers_cache)) {
const cached_panels_obj = get_cached_panels_obj(refresh_state);
if (cached_panels_obj) {
return cached_panels_obj;
}
}
let $elm = func.runtime?.ui?.get_refresh_indexed_panel_wrappers?.(SESSION_ID);
if (!$elm?.length) {
const $root = func.runtime?.ui?.get_refresh_index_root?.(SESSION_ID) || func.runtime.ui._wrap_matches([func.runtime.ui.get_first_node(SESSION_OBJ[SESSION_ID].root_element)]);
if (func.runtime?.ui?.find_refresh_elements_by_attr) {
$elm = func.runtime.ui.find_refresh_elements_by_attr($root, 'xu-panel-wrapper-id');
} else {
var _root_node = func.runtime.ui.get_first_node($root);
var _panel_matches = [];
if (_root_node?.matches?.('[xu-panel-wrapper-id]')) _panel_matches.push(_root_node);
_root_node?.querySelectorAll?.('[xu-panel-wrapper-id]')?.forEach(function (el) { _panel_matches.push(el); });
$elm = func.runtime.ui._wrap_matches(_panel_matches);
}
}
const panels_obj = {};
const prog_doc_cache = {};
// set panels_obj
const panel_elements = Array.isArray($elm) ? $elm : ($elm.toArray ? $elm.toArray() : Array.from($elm));
for (let elem_index = 0; elem_index < panel_elements.length; elem_index++) {
const $panel_div = func.runtime.ui._wrap_matches([panel_elements[elem_index]]);
const panel_wrapper_data = func.runtime.ui.get_data($panel_div)?.xuPanelWrapper;
const panelXuAttributes = panel_wrapper_data?.panelXuAttributes;
const panelDivData = panel_wrapper_data?.panelDivData;
if (!panelXuAttributes) continue; // skip if no longer in dom
const xu_ui_id = func.runtime.ui.get_attr($panel_div, 'xu-ui-id');
if (!panels_obj[xu_ui_id]) {
var _session = SESSION_OBJ[SESSION_ID];
let _ds = _session?.DS_GLB[panelDivData.xuData.paramsP.dsSessionP];
if (!_ds) continue;
let prog_doc = prog_doc_cache[_ds.prog_id];
if (!prog_doc) {
prog_doc = await func.utils.DOCS_OBJ.get(SESSION_ID, _ds.prog_id);
prog_doc_cache[_ds.prog_id] = prog_doc;
}
if (!ignore_disableAutoRefresh && prog_doc.properties.disableAutoRefresh) {
continue;
}
const ids = [];
const child_nodes = $panel_div[0]?.children || [];
for (let child_index = 0; child_index < child_nodes.length; child_index++) {
const child_node = child_nodes[child_index];
if (func.runtime.ui.get_data(child_node)?.xuPanelData) {
ids.push(func.runtime.ui.get_attr(child_node, 'xu-ui-id'));
}
}
panels_obj[xu_ui_id] = {
panelXuAttributes,
progUi: prog_doc.progUi,
prog_doc,
$panel_div,
_ds,
ids,
};
}
}
if (refresh_state) {
refresh_state.panel_wrappers_cache = panels_obj;
refresh_state.panel_wrappers_active_cache = {};
const panel_keys = Object.keys(panels_obj);
for (let index = 0; index < panel_keys.length; index++) {
const xu_ui_id = panel_keys[index];
const panel_entry = panels_obj[xu_ui_id];
if (panel_entry?.prog_doc?.properties?.disableAutoRefresh) {
continue;
}
refresh_state.panel_wrappers_active_cache[xu_ui_id] = panel_entry;
}
refresh_state.panel_wrappers_dirty = false;
}
if (!ignore_disableAutoRefresh) {
return refresh_state?.panel_wrappers_active_cache || panels_obj;
}
return panels_obj;
};
func.UI.worker = {};
func.UI.worker.ID = null;
func.UI.worker.idle = 0;
func.UI.worker.ensure_runtime_indexes = function () {
if (!UI_WORKER_OBJ.job_index_by_num) {
UI_WORKER_OBJ.job_index_by_num = {};
}
if (!UI_WORKER_OBJ.jobs_by_queue_key) {
UI_WORKER_OBJ.jobs_by_queue_key = {};
}
if (!UI_WORKER_OBJ.viewport_height_set_ids_set) {
UI_WORKER_OBJ.viewport_height_set_ids_set = new Set(UI_WORKER_OBJ.viewport_height_set_ids || []);
}
if (!UI_WORKER_OBJ.pending_delete_sessions) {
UI_WORKER_OBJ.pending_delete_sessions = new Set();
}
if (!UI_WORKER_OBJ.pending_delete_elements_by_session) {
UI_WORKER_OBJ.pending_delete_elements_by_session = {};
}
if (typeof UI_WORKER_OBJ.run_timer === 'undefined') {
UI_WORKER_OBJ.run_timer = null;
}
if (typeof UI_WORKER_OBJ.run_in_progress === 'undefined') {
UI_WORKER_OBJ.run_in_progress = false;
}
if (typeof UI_WORKER_OBJ.run_again === 'undefined') {
UI_WORKER_OBJ.run_again = false;
}
if (typeof UI_WORKER_OBJ.run_schedule_type === 'undefined') {
UI_WORKER_OBJ.run_schedule_type = null;
}
if (typeof UI_WORKER_OBJ.dom_jobs_per_frame === 'undefined') {
UI_WORKER_OBJ.dom_jobs_per_frame = 8;
}
if (!UI_WORKER_OBJ.job_lane_counts) {
UI_WORKER_OBJ.job_lane_counts = { data: 0, dom: 0 };
(UI_WORKER_OBJ.jobs || []).forEach(function (job) {
if (!job) {
return;
}
const lane = job.lane || func.UI.worker.get_job_lane(job.functionP);
UI_WORKER_OBJ.job_lane_counts[lane] = (UI_WORKER_OBJ.job_lane_counts[lane] || 0) + 1;
});
}
if (typeof UI_WORKER_OBJ.active_jobs_count === 'undefined') {
UI_WORKER_OBJ.active_jobs_count = 0;
for (let index = 0; index < (UI_WORKER_OBJ.jobs || []).length; index++) {
if (UI_WORKER_OBJ.jobs[index]) {
UI_WORKER_OBJ.active_jobs_count++;
}
}
}
if (typeof UI_WORKER_OBJ.job_holes_count === 'undefined') {
UI_WORKER_OBJ.job_holes_count = Math.max(0, (UI_WORKER_OBJ.jobs || []).length - UI_WORKER_OBJ.active_jobs_count);
}
if (typeof UI_WORKER_OBJ.first_active_job_index === 'undefined') {
UI_WORKER_OBJ.first_active_job_index = null;
for (let index = 0; index < (UI_WORKER_OBJ.jobs || []).length; index++) {
if (UI_WORKER_OBJ.jobs[index]) {
UI_WORKER_OBJ.first_active_job_index = index;
break;
}
}
}
};
func.UI.worker.get_job_lane = function (functionP) {
if (functionP === 'update_datasource') {
return 'data';
}
return 'dom';
};
func.UI.worker.register_job = function (job, index = UI_WORKER_OBJ.jobs.length - 1) {
func.UI.worker.ensure_runtime_indexes();
if (!job) {
return false;
}
if (!job.lane) {
job.lane = func.UI.worker.get_job_lane(job.functionP);
}
UI_WORKER_OBJ.job_index_by_num[job.job_num] = index;
if (job.queue_key) {
UI_WORKER_OBJ.jobs_by_queue_key[job.queue_key] = job;
}
UI_WORKER_OBJ.job_lane_counts[job.lane] = (UI_WORKER_OBJ.job_lane_counts[job.lane] || 0) + 1;
UI_WORKER_OBJ.active_jobs_count++;
if (UI_WORKER_OBJ.first_active_job_index === null || index < UI_WORKER_OBJ.first_active_job_index) {
UI_WORKER_OBJ.first_active_job_index = index;
}
return true;
};
func.UI.worker.unregister_job = function (job) {
func.UI.worker.ensure_runtime_indexes();
if (!job) {
return false;
}
delete UI_WORKER_OBJ.job_index_by_num[job.job_num];
if (job.queue_key && UI_WORKER_OBJ.jobs_by_queue_key[job.queue_key]?.job_num === job.job_num) {
delete UI_WORKER_OBJ.jobs_by_queue_key[job.queue_key];
}
if (job.lane && UI_WORKER_OBJ.job_lane_counts[job.lane] > 0) {
UI_WORKER_OBJ.job_lane_counts[job.lane]--;
}
if (UI_WORKER_OBJ.active_jobs_count > 0) {
UI_WORKER_OBJ.active_jobs_count--;
}
return true;
};
func.UI.worker.advance_first_active_job_index = function (start_index = UI_WORKER_OBJ.first_active_job_index || 0) {
func.UI.worker.ensure_runtime_indexes();
if (!UI_WORKER_OBJ.active_jobs_count) {
UI_WORKER_OBJ.first_active_job_index = null;
return null;
}
for (let index = Math.max(0, start_index); index < UI_WORKER_OBJ.jobs.length; index++) {
if (UI_WORKER_OBJ.jobs[index]) {
UI_WORKER_OBJ.first_active_job_index = index;
return UI_WORKER_OBJ.jobs[index];
}
}
UI_WORKER_OBJ.first_active_job_index = null;
return null;
};
func.UI.worker.compact_jobs = function () {
func.UI.worker.ensure_runtime_indexes();
if (!UI_WORKER_OBJ.job_holes_count) {
return false;
}
const compacted_jobs = [];
UI_WORKER_OBJ.job_index_by_num = {};
UI_WORKER_OBJ.jobs_by_queue_key = {};
UI_WORKER_OBJ.job_lane_counts = { data: 0, dom: 0 };
UI_WORKER_OBJ.job_holes_count = 0;
UI_WORKER_OBJ.first_active_job_index = null;
for (let index = 0; index < UI_WORKER_OBJ.jobs.length; index++) {
const job = UI_WORKER_OBJ.jobs[index];
if (!job) {
continue;
}
const compacted_index = compacted_jobs.length;
compacted_jobs.push(job);
UI_WORKER_OBJ.job_index_by_num[job.job_num] = compacted_index;
if (job.queue_key) {
UI_WORKER_OBJ.jobs_by_queue_key[job.queue_key] = job;
}
UI_WORKER_OBJ.job_lane_counts[job.lane] = (UI_WORKER_OBJ.job_lane_counts[job.lane] || 0) + 1;
if (UI_WORKER_OBJ.first_active_job_index === null) {
UI_WORKER_OBJ.first_active_job_index = compacted_index;
}
}
UI_WORKER_OBJ.jobs = compacted_jobs;
return true;
};
func.UI.worker.maybe_compact_jobs = function (force = false) {
func.UI.worker.ensure_runtime_indexes();
if (!UI_WORKER_OBJ.job_holes_count) {
return false;
}
const jobs_length = UI_WORKER_OBJ.jobs.length;
// XU_PERF: compacting after every front deletion is O(queue²) on large
// refreshes; front holes are already skipped via first_active_job_index and
// the index maps are maintained incrementally, so "force" is only a hint
const should_compact = glb.XU_PERF
? UI_WORKER_OBJ.job_holes_count >= Math.max(1024, Math.ceil(jobs_length / 2))
: force ||
UI_WORKER_OBJ.job_holes_count >= 50 ||
UI_WORKER_OBJ.job_holes_count >= Math.ceil(jobs_length / 3) ||
(UI_WORKER_OBJ.first_active_job_index !== null && UI_WORKER_OBJ.first_active_job_index > 0);
if (!should_compact) {
return false;
}
return func.UI.worker.compact_jobs();
};
func.UI.worker.get_first_active_job = function () {
func.UI.worker.ensure_runtime_indexes();
if (!UI_WORKER_OBJ.active_jobs_count) {
UI_WORKER_OBJ.first_active_job_index = null;
return null;
}
if (UI_WORKER_OBJ.first_active_job_index !== null) {
const active_job = UI_WORKER_OBJ.jobs[UI_WORKER_OBJ.first_active_job_index];
if (active_job) {
return active_job;
}
}
const job = func.UI.worker.advance_first_active_job_index(0);
if (job) {
if (UI_WORKER_OBJ.first_active_job_index > 0) {
func.UI.worker.maybe_compact_jobs(true);
}
return job;
}
UI_WORKER_OBJ.active_jobs_count = 0;
UI_WORKER_OBJ.job_holes_count = UI_WORKER_OBJ.jobs.length;
UI_WORKER_OBJ.first_active_job_index = null;
func.UI.worker.maybe_compact_jobs(true);
return null;
};
func.UI.worker.get_pending_run_mode = function () {
func.UI.worker.ensure_runtime_indexes();
if (!UI_WORKER_OBJ.active_jobs_count) {
return null;
}
if (UI_WORKER_OBJ.job_lane_counts?.data > 0) {
return 'data';
}
return 'dom';
};
func.UI.worker.cancel_pending_run = function () {
func.UI.worker.ensure_runtime_indexes();
if (!UI_WORKER_OBJ.run_timer) {
return false;
}
if (UI_WORKER_OBJ.run_schedule_type === 'dom_frame') {
if (typeof window !== 'undefined' && typeof window.cancelAnimationFrame === 'function') {
window.cancelAnimationFrame(UI_WORKER_OBJ.run_timer);
} else if (typeof cancelAnimationFrame === 'function') {
cancelAnimationFrame(UI_WORKER_OBJ.run_timer);
} else {
clearTimeout(UI_WORKER_OBJ.run_timer);
}
} else {
clearTimeout(UI_WORKER_OBJ.run_timer);
}
UI_WORKER_OBJ.run_timer = null;
UI_WORKER_OBJ.run_schedule_type = null;
return true;
};
func.UI.worker.request_frame = function (callback) {
if (typeof window !== 'undefined' && typeof window.requestAnimationFrame === 'function') {
return window.requestAnimationFrame(callback);
}
if (typeof requestAnimationFrame === 'function') {
return requestAnimationFrame(callback);
}
return setTimeout(callback, 16);
};
func.UI.worker.reindex_jobs_from = function (start_index = 0) {
func.UI.worker.ensure_runtime_indexes();
for (let index = Math.max(0, start_index); index < UI_WORKER_OBJ.jobs.length; index++) {
const job = UI_WORKER_OBJ.jobs[index];
if (!job) {
continue;
}
UI_WORKER_OBJ.job_index_by_num[job.job_num] = index;
if (job.queue_key) {
UI_WORKER_OBJ.jobs_by_queue_key[job.queue_key] = job;
}
}
};
func.UI.worker.get_session_root = function (SESSION_ID) {
if (func.runtime?.ui?.get_root_element) {
const $root = func.runtime.ui.get_root_element(SESSION_ID);
if ($root?.length) {
return $root;
}
}
return func.runtime.ui._wrap_matches([document.body]);
};
func.UI.worker.get_session_runtime_elements = function (SESSION_ID) {
if (func.runtime?.ui?.get_refresh_indexed_runtime_elements) {
const $indexed = func.runtime.ui.get_refresh_indexed_runtime_elements(SESSION_ID);
if ($indexed?.length) {
return $indexed;
}
}
const $root = func.UI.worker.get_session_root(SESSION_ID);
if (func.runtime?.ui?.get_refresh_index_elements) {
return func.runtime.ui.get_refresh_index_elements(SESSION_ID, $root);
}
var _rt_root_node = func.runtime.ui.get_first_node($root);
var _rt_matches = [];
if (_rt_root_node?.matches?.('[xu-ui-id]')) _rt_matches.push(_rt_root_node);
_rt_root_node?.querySelectorAll?.('[xu-ui-id]')?.forEach(function (el) { _rt_matches.push(el); });
return func.runtime.ui._wrap_matches(_rt_matches);
};
func.UI.worker.mark_pending_delete_session = function (SESSION_ID) {
func.UI.worker.ensure_runtime_indexes();
if (SESSION_ID) {
UI_WORKER_OBJ.pending_delete_sessions.add(SESSION_ID);
}
};
func.UI.worker.mark_pending_delete_element = function (SESSION_ID, target) {
func.UI.worker.ensure_runtime_indexes();
if (!SESSION_ID || !target) {
return false;
}
if (!UI_WORKER_OBJ.pending_delete_elements_by_session[SESSION_ID]) {
UI_WORKER_OBJ.pending_delete_elements_by_session[SESSION_ID] = new Set();
}
const elements = Array.isArray(target) ? target : (target?.length !== undefined ? Array.from(target) : [func.runtime.ui.get_first_node(target)].filter(Boolean));
elements.forEach(function (element) {
UI_WORKER_OBJ.pending_delete_elements_by_session[SESSION_ID].add(element);
});
UI_WORKER_OBJ.pending_delete_sessions.add(SESSION_ID);
return true;
};
func.UI.worker.cleanup_pending_to_delete = function (SESSION_ID = Object.keys(SESSION_OBJ)[0]) {
func.UI.worker.ensure_runtime_indexes();
if (!UI_WORKER_OBJ.pending_delete_sessions.has(SESSION_ID)) {
return;
}
const pending_elements = UI_WORKER_OBJ.pending_delete_elements_by_session[SESSION_ID];
if (pending_elements?.size) {
pending_elements.forEach(function (element) {
const element_data = func.runtime.ui.get_data(element);
if (element_data?.xuData?.pending_to_delete) {
element_data.xuData.pending_to_delete = false;
}
});
pending_elements.clear();
} else {
const runtime_elements = func.UI.worker.get_session_runtime_elements(SESSION_ID);
for (let index = 0; index < runtime_elements.length; index++) {
const val = runtime_elements[index];
const element_data = func.runtime.ui.get_data(val);
if (element_data?.xuData?.pending_to_delete) {
element_data.xuData.pending_to_delete = false;
}
}
}
UI_WORKER_OBJ.pending_delete_sessions.delete(SESSION_ID);
};
func.UI.worker.init = async function (SESSION_ID) {
func.UI.worker.ensure_runtime_indexes();
func.UI.utils.isInViewport = function (el) {
var node = func.runtime.ui.get_first_node(el);
if (!node) return false;
var rect = node.getBoundingClientRect();
return rect.bottom > 0 && rect.top < (window.innerHeight || document.documentElement.clientHeight);
};
if (typeof $ !== 'undefined' && $.fn) {
$.fn.isInViewport = function () {
return func.UI.utils.isInViewport(this[0]);
};
}
if (!UI_WORKER_OBJ.in_flight_job_elements) {
UI_WORKER_OBJ.in_flight_job_elements = [];
}
const contains_job_element = function ($parent, $child) {
const parent_node = $parent?.[0];
const child_node = $child?.[0];
if (!parent_node || !child_node) {
return false;
}
return parent_node.contains(child_node);
};
// Cancel in-flight child jobs when a parent element is being removed/hidden.
// This prevents orphaned jobs whose DOM elements no longer exist.
func.UI.worker.cancel_child_in_flight_jobs = function ($parent_element) {
if (!$parent_element?.length || !UI_WORKER_OBJ.in_flight_job_elements.length) return;
const parent_node = $parent_element[0];
if (!parent_node) return;
for (let i = UI_WORKER_OBJ.in_flight_job_elements.length - 1; i >= 0; i--) {
const child_el = UI_WORKER_OBJ.in_flight_job_elements[i];
const child_node = child_el?.[0];
if (child_node && parent_node.contains(child_node)) {
UI_WORKER_OBJ.in_flight_job_elements.splice(i, 1);
}
}
};
const overlaps_any_in_flight = function (job) {
if (!job?.elementP) {
return false;
}
for (let index = 0; index < UI_WORKER_OBJ.in_flight_job_elements.length; index++) {
const active_el = UI_WORKER_OBJ.in_flight_job_elements[index];
if (!active_el) continue;
// Block only when the new job is a CHILD of an in-flight element.
// If the new job is a PARENT of an in-flight element, allow it to run
// (e.g. xu-render hiding a container while a child panel's on_load is still running).
if (contains_job_element(active_el, job.elementP)) {
return true;
}
}
return false;
};
const job_iterator = async function (run_mode = 'data') {
const mark_pending_delete_on_descendants = function ($element) {
if (!$element?.length) {
return;
}
const descendants = $element[0]?.querySelectorAll?.('[xu-ui-id]') || [];
for (let index = 0; index < descendants.length; index++) {
const val = descendants[index];
const elm_data = func.runtime.ui.get_data(val);
if (!elm_data?.xuData) {
continue;
}
elm_data.xuData.pending_to_delete = true;
func.UI.worker.mark_pending_delete_element(SESSION_ID, val);
}
};
// XU_PERF: 8 dom jobs/frame turns a 10k-element refresh into ~1,250 paced
// frames of mostly idle; a 512 dispatch budget drains it in a few passes
const dom_job_budget = run_mode === 'dom' ? (glb.XU_PERF ? 512 : UI_WORKER_OBJ.dom_jobs_per_frame) : Number.POSITIVE_INFINITY;
let dom_jobs_processed = 0;
const dispatched_jobs = [];
if (UI_WORKER_OBJ.active_jobs_count) {
func.UI.worker.idle = 0;
// XU_PERF: skip the hole prefix instead of rescanning it every pass
const scan_start = glb.XU_PERF && UI_WORKER_OBJ.first_active_job_index ? UI_WORKER_OBJ.first_active_job_index : 0;
for (let key = scan_start; key < UI_WORKER_OBJ.jobs.length; key++) {
const val = UI_WORKER_OBJ.jobs[key];
try {
if (!val) continue;
if (val.stat === 'busy') continue;
const job_lane = val.lane || func.UI.worker.get_job_lane(val.functionP);
val.lane = job_lane;
if (run_mode === 'data' && job_lane !== 'data') continue;
if (job_lane === 'dom' && dom_jobs_processed >= dom_job_budget) continue;
// skip jobs whose element overlaps with any currently in-flight job (parent/child)
// sibling containers can run in parallel
if (overlaps_any_in_flight(val)) continue;
if (!val.elementP) {
const job_promise = func.UI.worker.execute(val.SESSION_ID, val).catch(function (err) {
console.error(err);
});
dispatched_jobs.push(job_promise);
if (job_lane === 'dom') {
dom_jobs_processed++;
}
continue;
}
const active_xu_ui_id = func.runtime.ui.get_attr(val.elementP, 'xu-ui-id');
if (!active_xu_ui_id) continue;
const running_job_obj = func.UI.worker.get_first_active_job();
if (!running_job_obj) {
break;
}
if (running_job_obj.job_num !== val.job_num) {
// skip - if job element exist in the active job ui as child element
if (contains_job_element(running_job_obj.elementP, val.elementP)) {
continue;
}
// keep overlapping parent/child jobs serialized; siblings can run in-flight together
if (contains_job_element(val.elementP, running_job_obj.elementP)) {
continue;
}
}
// Track this element as in-flight so future schedule_run passes skip overlapping jobs
const in_flight_entry = val.elementP;
UI_WORKER_OBJ.in_flight_job_elements.push(in_flight_entry);
// execute siblings/non-overlapping jobs — fire and forget, re-trigger scheduler on completion
const job_promise = func.UI.worker.execute(val.SESSION_ID, val).catch(function (err) {
console.error(err);
}).finally(function () {
// remove this element from in-flight tracking
const idx = UI_WORKER_OBJ.in_flight_job_elements.indexOf(in_flight_entry);
if (idx !== -1) {
UI_WORKER_OBJ.in_flight_job_elements.splice(idx, 1);
}
// re-trigger scheduler so blocked sibling jobs can now run
func.UI.worker.schedule_run(0);
});
dispatched_jobs.push(job_promise);
if (job_lane === 'dom') {
dom_jobs_processed++;
}
continue;
} catch (err) {
console.error(err);
}
}
// Only await jobs that have no element (data jobs) — don't block on long-running UI jobs
// UI jobs with elements will re-trigger schedule_run when they complete
}
};
func.UI.worker.schedule_run = function (delay = 0, preferred_mode) {
func.UI.worker.ensure_runtime_indexes();
if (UI_WORKER_OBJ.run_in_progress) {
// Allow re-entry: even though a scan is in progress, mark run_again
// so the scheduler re-scans after the current pass. This lets sibling
// jobs that were queued after the scan started get picked up quickly.
UI_WORKER_OBJ.run_again = true;
return;
}
const run_mode = preferred_mode || func.UI.worker.get_pending_run_mode() || 'data';
if (UI_WORKER_OBJ.run_timer) {
const should_promote_data =
run_mode === 'data' &&
UI_WORKER_OBJ.run_schedule_type &&
UI_WORKER_OBJ.run_schedule_type !== 'data';
if (!should_promote_data) {
return;
}
func.UI.worker.cancel_pending_run();
}
const run_once = async function () {
UI_WORKER_OBJ.run_timer = null;
UI_WORKER_OBJ.run_schedule_type = null;
UI_WORKER_OBJ.run_in_progress = true;
try {
await job_iterator(run_mode);
} finally {
UI_WORKER_OBJ.run_in_progress = false;
func.UI.worker.maybe_compact_jobs();
const next_run_mode = func.UI.worker.get_pending_run_mode();
const should_continue = UI_WORKER_OBJ.run_again || !!next_run_mode;
UI_WORKER_OBJ.run_again = false;
if (should_continue) {
func.UI.worker.schedule_run(0, next_run_mode || undefined);
}
}
};
UI_WORKER_OBJ.run_schedule_type = run_mode;
if (run_mode === 'dom') {
if (delay > 0) {
UI_WORKER_OBJ.run_schedule_type = 'dom_delay';
UI_WORKER_OBJ.run_timer = setTimeout(function () {
UI_WORKER_OBJ.run_schedule_type = 'dom_frame';
UI_WORKER_OBJ.run_timer = func.UI.worker.request_frame(run_once);
}, delay);
} else {
UI_WORKER_OBJ.run_schedule_type = 'dom_frame';
UI_WORKER_OBJ.run_timer = func.UI.worker.request_frame(run_once);
}
} else {
UI_WORKER_OBJ.run_schedule_type = 'data';
UI_WORKER_OBJ.run_timer = setTimeout(run_once, delay);
}
this._interval = UI_WORKER_OBJ.run_timer;
};
if (!UI_WORKER_OBJ.maintenance_intervals_initialized) {
UI_WORKER_OBJ.maintenance_intervals_initialized = true;
setInterval(async function () {
func.UI.ds_garbage_collector();
}, 10000);
setInterval(async function () {
func.UI.worker.cleanup_pending_to_delete();
func.UI.refs_garbage_collector();
func.UI.teleport_garbage_collector();
}, 1000);
}
};
func.UI.worker.add_to_queue = async function (SESSION_ID, source, functionP, paramsP, calling_job, elementP, dsSession, calling_trigger_prop) {
func.UI.worker.ensure_runtime_indexes();
var obj = {
SESSION_ID,
source,
functionP,
paramsP,
calling_job,
elementP,
dsSession,
calling_trigger_prop,
job_num: UI_WORKER_OBJ.num,
};
obj.lane = func.UI.worker.get_job_lane(functionP);
const get_ui_id = function (target) {
return func.runtime?.ui?.get_attr ? func.runtime.ui.get_attr(target, 'xu-ui-id') : target?.attr?.('xu-ui-id');
};
const get_parent_ui_id = function (target) {
const parent_node = func.runtime.ui.get_first_node(target)?.parentElement;
if (!parent_node) {
return '';
}
return get_ui_id(parent_node);
};
const get_queue_key = function () {
if (functionP === 'update_datasource') {
return source + '_' + functionP + '_' + (dsSession || '') + '_' + (paramsP?.currentRecordId || '') + '_' + (paramsP?.field_id || '');
}
if (functionP === 'render_viewport') {
return source + '_' + functionP + '_' + (get_ui_id(paramsP?.$div) || '');
}
if (functionP === 'set_viewport_height') {
return source + '_' + functionP + '_' + (get_parent_ui_id(paramsP?.$div) || '');
}
if (functionP === 'execute_xu_all_attributes') {
return source + '_' + functionP + '_' + (get_ui_id(elementP) || '') + '_' + (paramsP?.fields_arr?.toString() || '');
}
if (functionP === 'execute_xu_render_attributes') {
return source + '_' + functionP + '_' + (get_ui_id(elementP) || '') + '_' + (paramsP?.attr_value?.toString?.() || paramsP?.attr_value || '') + '_' + (paramsP?.fields_arr?.toString() || '');
}
if (functionP === 'execute_xu_for') {
return source + '_' + functionP + '_' + (get_ui_id(elementP) || '') + '_' + (paramsP?.xu_for_item_id || '');
}
if (functionP === 'execute_xu_widget') {
return source + '_' + functionP + '_' + (get_ui_id(elementP) || '');
}
return null;
};
const queue_key = get_queue_key();
if (queue_key) {
obj.queue_key = queue_key;
let exist_job = UI_WORKER_OBJ.jobs_by_queue_key?.[queue_key];
if (exist_job) {
func.runtime?.perf?.increment?.(SESSION_ID, 'jobs_coalesced');
func.runtime?.perf?.increment_map?.(SESSION_ID, 'jobs_coalesced_by_function', functionP);
exist_job.paramsP = paramsP;
exist_job.calling_trigger_prop = calling_trigger_prop;
exist_job.elementP = elementP;
exist_job.dsSession = dsSession;
exist_job.lane = obj.lane;
return exist_job.job_num;
}
}
// if (calling_job) {
// var job_index = func.UI.worker.find_job_index(SESSION_ID, calling_job);
// if (job_index === null || typeof job_index === 'undefined') return;
// try {
// if (!UI_WORKER_OBJ.jobs[job_index].splice_count) {
// UI_WORKER_OBJ.jobs[job_index].splice_count = 0;
// }
// UI_WORKER_OBJ.jobs[job_index].splice_count++;
// UI_WORKER_OBJ.jobs.splice(job_index + UI_WORKER_OBJ.jobs[job_index].splice_count, 0, obj);
// // }
// } catch (e) {
// console.error('bug');
// // UI_WORKER_OBJ.jobs.splice(0, 0, obj);
// }
// } else {
// // check case of xu-render if queue has child node of the element then delete job
// // check case of execute attributes that queue not contain the element then add to parallel queue
// UI_WORKER_OBJ.jobs.push(obj);
// }
UI_WORKER_OBJ.jobs.push(obj);
func.UI.worker.register_job(obj, UI_WORKER_OBJ.jobs.length - 1);
func.runtime?.perf?.increment?.(SESSION_ID, 'jobs_queued');
func.runtime?.perf?.increment_map?.(SESSION_ID, 'jobs_queued_by_function', functionP);
if (func.UI.worker.schedule_run) {
func.UI.worker.schedule_run(0, obj.lane === 'data' ? 'data' : undefined);
}
UI_WORKER_OBJ.num++;
return UI_WORKER_OBJ.num - 1;
};
func.UI.worker.delete_job = async function (SESSION_ID, jobNoP) {
// func.UI.worker.ID.postMessage({
// method: "delete_job",
// params: {
// job_num: jobNoP,
// },
// });
// return;
var _session = SESSION_OBJ[SESSION_ID];
var job_index = func.UI.worker.find_job_index(SESSION_ID, jobNoP);
if (job_index === null || typeof job_index === 'undefined' || !UI_WORKER_OBJ.jobs[job_index]) {
// UI_WORKER_OBJ.stat = null;
return;
}
const removed_job = UI_WORKER_OBJ.jobs[job_index];
func.runtime?.perf?.increment?.(SESSION_ID, 'jobs_completed');
func.runtime?.perf?.increment_map?.(SESSION_ID, 'jobs_completed_by_function', removed_job.functionP);
var dsSession = removed_job.dsSession;
let ds_obj = _session?.DS_GLB[dsSession];
if (ds_obj) {
delete SCREEN_BLOCKER_OBJ[ds_obj.screenId + (ds_obj.callingScreenId ? '_' + ds_obj.callingScreenId : '')];
}
if (dsSession && ds_obj?.loops_limit && ds_obj?.loops_count < ds_obj?.loops_limit - 1) {
return;
}
// UI_WORKER_OBJ.stat = null;
func.UI.worker.unregister_job(removed_job);
UI_WORKER_OBJ.jobs[job_index] = null;
UI_WORKER_OBJ.job_holes_count++;
if (UI_WORKER_OBJ.first_active_job_index === job_index) {
func.UI.worker.advance_first_active_job_index(job_index + 1);
}
func.UI.worker.maybe_compact_jobs(job_index === 0);
};
func.UI.worker.execute = async function (SESSION_ID, queue_obj) {
var job_index = func.UI.worker.find_job_index(SESSION_ID, queue_obj.job_num);
// if (UI_WORKER_OBJ.jobs?.[job_index]?.stat === 'busy') {
// if (queue_obj.jobNoP) UI_WORKER_OBJ.stat = job_index;
// return;
// }
// if (queue_obj.jobNoP && !UI_WORKER_OBJ.jobs[job_index]) {
// UI_WORKER_OBJ.stat = null;
// return;
// }
if (queue_obj.jobNoP) UI_WORKER_OBJ.stat = job_index;
if (UI_WORKER_OBJ.jobs[job_index]) {
UI_WORKER_OBJ.jobs[job_index].stat = 'busy';
}
func.runtime?.perf?.increment?.(SESSION_ID, 'jobs_executed');
func.runtime?.perf?.increment_map?.(SESSION_ID, 'jobs_executed_by_function', queue_obj.functionP);
const fx = {
get_element_by_ui_id: function (xu_ui_id) {
if (!xu_ui_id) {
return func.runtime.ui._wrap_matches([]);
}
if (func.runtime?.ui?.get_refresh_indexed_element_by_ui_id) {
const _elm = func.runtime.ui.get_refresh_indexed_element_by_ui_id(SESSION_ID, xu_ui_id);
return func.runtime.ui._wrap_matches(_elm ? [_elm] : []);
}
const $root = func.UI.worker.get_session_root(SESSION_ID);
if (func.runtime?.ui?.find_refresh_elements_by_attr) {
return func.runtime.ui.find_refresh_elements_by_attr($root, 'xu-ui-id', xu_ui_id, true);
}
return func.runtime.ui.find_by_selector($root, `[xu-ui-id="${xu_ui_id}"]`);
},
get_live_element_context: function (elem_key, fallback_$elm, context = {}) {
let raw_$elm = elem_key ? fx.get_element_by_ui_id(elem_key) : fallback_$elm;
let $elm = func.runtime?.ui?.get_preferred_live_element ? func.runtime.ui.get_preferred_live_element(raw_$elm) : raw_$elm;
const matches_context = function (node_xu_data, allow_loose_match = false) {
if (!node_xu_data) {
return false;
}
if (context.node_id && node_xu_data.nodeid !== context.node_id) {
return false;
}
if (typeof context.key !== 'undefined' && context.key !== null && node_xu_data.key !== context.key) {
return false;
}
if (context.key_path && node_xu_data.key_path !== context.key_path) {
return false;
}
if (context.recordid && node_xu_data.recordid !== context.recordid) {
return false;
}
if (!allow_loose_match) {
if (context.prog_id && node_xu_data.paramsP?.prog_id !== context.prog_id) {
return false;
}
if (context.parent_element_ui_id && node_xu_data.parent_element_ui_id !== context.parent_element_ui_id) {
return false;
}
}
if (node_xu_data.pending_to_delete) {
return false;
}
return true;
};
const resolved_node = func.runtime.ui.get_first_node($elm);
const resolved_data = resolved_node ? func.runtime.ui.get_data(resolved_node)?.xuData : null;
const has_matching_resolved_node = matches_context(resolved_data);
if (context.node_id && !has_matching_resolved_node) {
const $root = func.UI.worker.get_session_root(SESSION_ID);
const runtime_nodes = func.runtime?.ui?.get_refresh_index_elements
? func.runtime.ui.get_refresh_index_elements(SESSION_ID, $root).toArray()
: Array.from(func.runtime.ui.get_first_node($root)?.querySelectorAll('[xu-ui-id]') || []);
let matching_nodes = [];
for (let index = 0; index < runtime_nodes.length; index++) {
const node = runtime_nodes[index];
const node_data = func.runtime.ui.get_data(node);
const node_xu_data = node_data?.xuData;
if (!matches_context(node_xu_data)) {
continue;
}
matching_nodes.push(node);
}
if (!matching_nodes.length) {
for (let index = 0; index < runtime_nodes.length; index++) {
const node = runtime_nodes[index];
const node_data = func.runtime.ui.get_data(node);
const node_xu_data = node_data?.xuData;
if (!matches_context(node_xu_data, true)) {
continue;
}
matching_nodes.push(node);
}
}
if (matching_nodes.length) {
raw_$elm = func.runtime.ui._wrap_matches(matching_nodes);
$elm = func.runtime?.ui?.get_preferred_live_element ? func.runtime.ui.get_preferred_live_element(raw_$elm) : raw_$elm;
}
}
const _resolved_node = func.runtime.ui.get_first_node($elm);
if (!_resolved_node) {
return {
$elm: func.runtime.ui._wrap_matches([]),
data: null,
};
}
if (!$elm?.length) {
$elm = func.runtime.ui._wrap_matches([_resolved_node]);
}
const data = func.runtime.ui.get_data($elm);
return {
$elm,
data,
};
},
get_child_node_by_id: function (xuData, node_id) {
if (!xuData?.node_org?.children?.length || !node_id) {
return null;
}
if (func.runtime?.ui?.get_node_children_by_id) {
const children_by_id = func.runtime.ui.get_node_children_by_id(xuData.node_org);
return children_by_id[node_id] || null;
}
if (!xuData.node_org_children_by_id) {
xuData.node_org_children_by_id = {};
for (let index = 0; index < xuData.node_org.children.length; index++) {
const child_node = xuData.node_org.children[index];
if (child_node?.id) {
xuData.node_org_children_by_id[child_node.id] = child_node;
}
}
}
return xuData.node_org_children_by_id[node_id] || null;
},
get_refresh_execution_plan: function (live_data, refresh_attributes) {
const xuData = live_data?.xuData;
if (!xuData) {
return [];
}
if (!xuData.refresh_execution_plan_cache) {
xuData.refresh_execution_plan_cache = {};
}
const cache_key = (refresh_attributes || []).join('|');
if (xuData.refresh_execution_plan_cache[cache_key]) {
return xuData.refresh_execution_plan_cache[cache_key];
}
const skip_attributes = {
'xu-exp:xu-render': true,
'xu-exp:xu-for': true,
'xu-for': true,
'xu-exp:xu-bind': true,
};
const raw_value_attributes = {
'xu-bind': true,
'xu-ref': true,
'xu-on': true,
'xu-for-key': true,
'xu-for-val': true,
'xu-click': true,
'xu-change': true,
'xu-blur': true,
'xu-focus': true,
'xu-init': true,
'xu-attrs': true,
'xu-cdn': true,
'xu-style': true,
'xu-style-global': true,
'xu-script': true,
'xu-viewport': true,
'xu-ui-plugin': true,
};
const execution_plan = [];
for (let index = 0; index < (refresh_attributes || []).length; index++) {
const attr = refresh_attributes[index];
if (!attr || skip_attributes[attr]) {
continue;
}
const attr_new = attr.split('xu-exp:')[1];
const xu_func = attr_new || attr;
const is_raw_value_attribute = !!raw_value_attributes[attr] || attr.substr(0, 6) === 'xu-on:';
execution_plan.push({
attr,
attr_new,
xu_func,
is_regular_attribute: !!(attr_new && attr_new.substr(0, 2) !== 'xu'),
requires_expression: !is_raw_value_attribute && attr !== 'xu-class' && attr !== 'xu-ui-plugin',
regular_attr_name: attr_new ? (attr_new !== 'viewBox' ? attr_new.toLowerCase() : attr_new) : null,
});
}
xuData.refresh_execution_plan_cache[cache_key] = execution_plan;
return execution_plan;
},
get_expression_cache_key: function (options) {
const iterate_info = options.iterate_info;
const iterate_key = iterate_info
? [
iterate_info.iterator_key ?? '',
iterate_info.iterator_val ?? '',
iterate_info._key ?? '',
iterate_info._val ?? '',
].join('::')
: '';
return [
options.expression_text,
options.dsSessionP,
options.recordid,
iterate_key,
].join('||');
},
get_expression_result: async function (cache, options) {
const cache_key = fx.get_expression_cache_key(options);
if (Object.prototype.hasOwnProperty.call(cache, cache_key)) {
return cache[cache_key];
}
const result = await func.expression.get(
options.SESSION_ID,
options.expression_text,
options.dsSessionP,
'UI Property EXP',
options.recordid,
null,
null,
null,
null,
null,
options.iterate_info,
);
cache[cache_key] = result;
return result;
},
update_datasource: async function (currentRecordId) {
if (queue_obj?.paramsP) {
var _ds = SESSION_OBJ[SESSION_ID].DS_GLB[queue_obj.dsSession];
_ds.currentRecordId = currentRecordId || queue_obj.paramsP.currentRecordId;
// console.info(queue_obj.dsSession, _ds.currentRecordId);
var datasource_changes = {
[_ds.dsSession]: { [_ds.currentRecordId]: 'set' },
};
await func.datasource.update(SESSION_ID, datasource_changes);
if (queue_obj.paramsP.field_id) {
datasource_changes = {
[_ds.dsSession]: {
[_ds.currentRecordId]: {
[queue_obj.paramsP.field_id]: queue_obj.paramsP.field_value,
},
},
};
await func.datasource.update(SESSION_ID, datasource_changes);
}
}
if (!currentRecordId) return await func.UI.worker.delete_job(SESSION_ID, queue_obj.job_num);
},
execute_xu_render_attributes: async function () {
const perf_end = func.runtime?.perf?.start?.(SESSION_ID, 'execute_xu_render_attributes');
const live_context = fx.get_live_element_context(queue_obj.paramsP?.elem_key, queue_obj.elementP || queue_obj.paramsP?.elem_val?.$elm, queue_obj.paramsP);
const _data = live_context.data;
try {
if (_data?.xuData?.paramsP) {
const live_xu_data = _data.xuData;
await func.runtime.render.execute_xu_function({
SESSION_ID,
is_skeleton: null,
$root_container: live_xu_data.$root_container,
nodeP: live_xu_data.node,
$container: fx.get_element_by_ui_id(live_xu_data.parent_element_ui_id) || live_xu_data.$container,
paramsP: live_xu_data.paramsP,
parent_infoP: live_xu_data.iterate_info ? { iterate_info: live_xu_data.iterate_info } : {},
jobNoP: queue_obj.jobNoP,
keyP: live_xu_data.key,
parent_nodeP: live_xu_data.parent_node,
xu_func: 'xu-render',
$elm: live_context.$elm,
$live_elm: live_context.$elm,
val: {
key: 'xu-render',
value: queue_obj.paramsP.attr_value,
fields_arr: queue_obj.paramsP.fields_arr,
jobNoP: queue_obj.jobNoP,
},
get_params_obj_new: func.runtime.program.get_params_obj,
});
}
return await func.UI.worker.delete_job(SESSION_ID, queue_obj.job_num);
} finally {
perf_end?.();
}
},
execute_xu_all_attributes: async function () {
const perf_end = func.runtime?.perf?.start?.(SESSION_ID, 'execute_xu_all_attributes');
const done = function () {
return func.UI.worker.delete_job(SESSION_ID, queue_obj.job_num);
};
try {
const live_context = fx.get_live_element_context(queue_obj.paramsP?.elem_key, queue_obj.elementP || queue_obj.paramsP?.elem_val?.$elm, queue_obj.paramsP);
const $elm = live_context.$elm;
const live_data = live_context.data;
const elm_node = $elm?.[0];
if (!$elm.length || !live_data?.xuData || !live_data?.xuAttributes) {
return done();
}
const live_xu_data = live_data.xuData;
const live_xu_attributes = live_data.xuAttributes;
const refresh_attributes = queue_obj.paramsP?.elem_val?.attributes || [];
const execution_plan = fx.get_refresh_execution_plan(live_data, refresh_attributes);
const expression_results_cache = {};
const live_parent_container = fx.get_element_by_ui_id(live_xu_data.parent_element_ui_id);
const xu_execution_context = {
SESSION_ID,
is_skeleton: null,
$root_container: live_xu_data.$root_container,
nodeP: live_xu_data.node,
$container: live_parent_container?.length ? live_parent_container : live_xu_data.$container,
paramsP: live_xu_data.paramsP,
parent_infoP: live_xu_data.iterate_info ? { iterate_info: live_xu_data.iterate_info } : {},
jobNoP: queue_obj.jobNoP,
keyP: live_xu_data.key,
parent_nodeP: live_xu_data.parent_node,
$elm,
$live_elm: $elm,
get_params_obj_new: func.runtime.program.get_params_obj,
};
const handler_bundle = func.runtime.render.build_xu_handlers(xu_execution_context, SESSION_OBJ[SESSION_ID].DS_GLB[live_xu_data.paramsP.dsSessionP]);
for (let index = 0; index < execution_plan.length; index++) {
const plan = execution_plan[index];
const attr = plan.attr;
const attr_value = live_xu_attributes[attr];
if (typeof attr_value === 'undefined') {
continue;
}
let result = attr_value;
if (plan.requires_expression) {
const expression_result = await fx.get_expression_result(expression_results_cache, {
SESSION_ID: queue_obj.paramsP.SESSION_ID,
expression_text: attr_value,
dsSessionP: live_xu_data.paramsP.dsSessionP,
recordid: live_xu_data.recordid,
iterate_info: live_xu_data.iterate_info,
});
result = expression_result.result;
}
if (plan.is_regular_attribute) {
if (plan.regular_attr_name === 'class') {
func.runtime.render.apply_expression_class($elm, result);
} else {
func.runtime.ui.set_attr($elm, plan.regular_attr_name, result);
}
} else {
try {
await func.runtime.render.execute_xu_function({
...xu_execution_context,
xu_func: plan.xu_func,
val: {
key: plan.xu_func,
value: result,
},
handler_bundle,
});
} catch (error) {
console.error('[xuda-runtime] caught xuda_UI.utils.js:1909:', error);
}
}
}
return done();
} finally {
perf_end?.();
}
},
execute_xu_for: async function () {
const perf_end = func.runtime?.perf?.start?.(SESSION_ID, 'execute_xu_for');
try {
const live_context = fx.get_live_element_context(queue_obj.paramsP?.elem_key, queue_obj.elementP || queue_obj?.paramsP?.elem_val?.$elm, queue_obj.paramsP);
var $elm = live_context.$elm; // $(SESSION_OBJ[SESSION_ID].root_element).find(`[xu-ui-id=${queue_obj.paramsP.elem_key}]`)
if (!$elm?.length) {
return await func.UI.worker.delete_job(SESSION_ID, queue_obj.job_num);
}
const existing_children_map = new Set();
if (func.runtime?.ui?.get_refresh_indexed_elements_by_node_id) {
const indexed_children = func.runtime.ui.get_refresh_indexed_elements_by_node_id(SESSION_ID, queue_obj?.paramsP?.xu_for_item_id).toArray();
for (let index = 0; index < indexed_children.length; index++) {
if (indexed_children[index].parentElement === func.runtime.ui.get_first_node($elm)) {
existing_children_map.add(indexed_children[index]);
}
}
}
const children = func.runtime.ui.get_children($elm);
for (let index = 0; index < children.length; index++) {
const child = children[index];
const child_data = func.runtime.ui.get_data(child);
if (child_data?.xuData?.nodeid === queue_obj?.paramsP?.xu_for_item_id) {
existing_children_map.add(child);
}
}
const _reuse_key = `${queue_obj.paramsP.elem_key}::${queue_obj?.paramsP?.xu_for_item_id}`;
if (existing_children_map.size) {
if (glb.XU_PERF) {
// hand the live rows to handle_xu_for for keyed reuse instead of
// tearing them down; whatever it does not consume is removed below
func.runtime.render.xu_for_reuse_stash = func.runtime.render.xu_for_reuse_stash || new Map();
func.runtime.render.xu_for_reuse_stash.set(_reuse_key, Array.from(existing_children_map));
} else {
func.runtime.ui.remove(func.runtime.ui._wrap_matches(Array.from(existing_children_map)));
}
}
let _data = live_context.data || func.runtime.ui.get_data($elm);
const node_to_render = fx.get_child_node_by_id(_data?.xuData, queue_obj?.paramsP?.xu_for_item_id);
await func.runtime.render.render_ui_tree(queue_obj.paramsP.SESSION_ID, $elm, node_to_render, null, _data.xuData.paramsP, queue_obj.jobNoP, null, _data.xuData.key, null, _data.xuData.parent_node, null, _data.xuData.$root_container);
if (glb.XU_PERF) {
// stash not consumed (id mismatch, non-array source, error): finish
// the legacy teardown so old rows can never linger next to new ones
const _leftover = func.runtime.render.xu_for_reuse_stash.get(_reuse_key);
if (_leftover) {
func.runtime.render.xu_for_reuse_stash.delete(_reuse_key);
const _still = _leftover.filter((el) => el && el.isConnected);
if (_still.length) func.runtime.ui.remove(func.runtime.ui._wrap_matches(_still));
}
}
} catch (error) {
} finally {
perf_end?.();
}
return await func.UI.worker.delete_job(SESSION_ID, queue_obj.job_num);
},
render_viewport: async function () {
const { nodeP, $div, parent_infoP, $root_container, jobNoP, is_skeleton, paramsP, $container } = queue_obj?.paramsP || {};
const _div_node = func.runtime.ui.get_first_node($div);
if (nodeP?.children?.length && !_div_node?.children?.length) {
await fx.update_datasource(func.runtime.ui.get_data($div)?.xuData?.currentRecordId);
func.runtime.ui.remove_class($div, 'skeleton');
for (let index = 0; index < nodeP.children.length; index++) {
await func.runtime.render.render_ui_tree(SESSION_ID, $div, nodeP.children[index], parent_infoP, paramsP, jobNoP, is_skeleton, index, null, nodeP, null, $root_container);
}
_div_node.style.removeProperty('height');
func.runtime.ui.get_data($div).xuData.viewport_height = _div_node?.offsetHeight || 0;
// set initial default height for all children
const parent_id = func.runtime.ui.get_attr(_div_node?.parentElement, 'xu-ui-id');
func.UI.worker.ensure_runtime_indexes();
if (!UI_WORKER_OBJ.viewport_height_set_ids_set.has(parent_id)) {
UI_WORKER_OBJ.viewport_height_set_ids_set.add(parent_id);
UI_WORKER_OBJ.viewport_height_set_ids.push(parent_id);
func.UI.worker.add_to_queue(SESSION_ID, 'gui event', 'set_viewport_height', { $div, height: func.runtime.ui.get_first_node($div)?.offsetHeight || 0 }, null, null, paramsP.dsSessionP);
}
}
return await func.UI.worker.delete_job(SESSION_ID, queue_obj.job_num);
},
set_viewport_height: async function () {
const { $div, height } = queue_obj?.paramsP || {};
const siblings = func.runtime.ui.get_first_node($div)?.parentElement?.children || [];
for (let index = 0; index < siblings.length; index++) {
const elm = siblings[index];
if (!elm.style.height && !elm.childElementCount) {
func.runtime.ui.set_style(elm, 'height', `${height}px`);
}
}
return await func.UI.worker.delete_job(SESSION_ID, queue_obj.job_num);
},
execute_xu_widget: async function () {
try {
const live_context = fx.get_live_element_context(queue_obj.paramsP?.elem_key, queue_obj.elementP || queue_obj?.paramsP?.elem_val?.$elm, queue_obj.paramsP);
var $elm = live_context.$elm; // $(SESSION_OBJ[SESSION_ID].root_element).find(`[xu-ui-id=${queue_obj.paramsP.elem_key}]`)
if (!$elm?.length) {
return await func.UI.worker.delete_job(SESSION_ID, queue_obj.job_num);
}
// $elm.empty();
// $.each($elm.children(), (key, val) => {
// if (!$(val)?.data()?.xuData) return true;
// if ($(val).data().xuData.nodeid === queue_obj?.paramsP?.xu_for_item_id) {
// $(val).remove();
// }
// });
const parent_id = func.runtime.ui.get_attr(func.runtime.ui.get_first_node($elm)?.parentElement, 'xu-ui-id');
let _data = live_context.data || func.runtime.ui.get_data($elm);
func.runtime.ui.remove($elm);
if (!_data?.xuData) {
return await func.UI.worker.delete_job(SESSION_ID, queue_obj.job_num);
}
const node_to_render = _data.xuData.node_org; //_data.xuData.node_org.children?.find((e) => e.id === queue_obj?.paramsP?.xu_for_item_id);
await func.runtime.render.render_ui_tree(queue_obj.paramsP.SESSION_ID, fx.get_element_by_ui_id(parent_id), node_to_render, null, _data.xuData.paramsP, queue_obj.jobNoP, null, _data.xuData.key, null, _data.xuData.parent_node, null, _data.xuData.$root_container);
} catch (error) {}
return await func.UI.worker.delete_job(SESSION_ID, queue_obj.job_num);
},
};
try {
return await fx[queue_obj.functionP]();
} catch (error) {
console.error(error);
const failed_job_index = func.UI.worker.find_job_index(SESSION_ID, queue_obj.job_num);
if (failed_job_index !== null && typeof failed_job_index !== 'undefined' && UI_WORKER_OBJ.jobs[failed_job_index]) {
await func.UI.worker.delete_job(SESSION_ID, queue_obj.job_num);
}
return null;
}
};
func.UI.worker.find_job_index = function (SESSION_ID, jobNoP) {
var ret = null;
if (!UI_WORKER_OBJ) return ret;
func.UI.worker.ensure_runtime_indexes();
if (Object.prototype.hasOwnProperty.call(UI_WORKER_OBJ.job_index_by_num, jobNoP)) {
const indexed_job = UI_WORKER_OBJ.job_index_by_num[jobNoP];
if (UI_WORKER_OBJ.jobs[indexed_job]) {
return indexed_job;
}
delete UI_WORKER_OBJ.job_index_by_num[jobNoP];
}
for (let key = 0; key < UI_WORKER_OBJ.jobs.length; key++) {
const val = UI_WORKER_OBJ.jobs[key];
if (val && val.job_num == jobNoP) {
ret = key;
UI_WORKER_OBJ.job_index_by_num[jobNoP] = ret;
break;
}
}
return ret;
};
func.UI.ds_garbage_collector = function (SESSION_ID = Object.keys(SESSION_OBJ)[0], re_check) {
let _session = SESSION_OBJ[SESSION_ID];
const _data_system = _session?.DS_GLB?.[0]?.data_system;
if (_data_system?.SYS_GLOBAL_BOL_AJAX_BUSY) return;
if (!_data_system?.SYS_GLOBAL_BOL_IDLE) return;
const ds_keys = Object.keys(_session.DS_GLB || {});
let abort = false;
for (let index = 0; index < ds_keys.length; index++) {
const _ds = _session.DS_GLB[ds_keys[index]];
if (_ds.stat === 'busy') {
abort = true;
break;
}
}
if (abort) {
return;
}
const ds_pending_to_delete = new Set();
const active_ds_sessions = new Set();
const runtime_elements = func.UI.worker.get_session_runtime_elements(SESSION_ID);
for (let index = 0; index < runtime_elements.length; index++) {
const val = runtime_elements[index];
const dsSessionP = func.runtime.ui.get_data(val)?.xuData?.paramsP?.dsSessionP;
if (typeof dsSessionP === 'undefined' || dsSessionP === null) continue;
active_ds_sessions.add(dsSessionP.toString());
}
for (let index = 0; index < ds_keys.length; index++) {
const dsP = ds_keys[index];
const _ds = _session.DS_GLB[dsP];
if (!_ds.screen_params) continue;
if (!active_ds_sessions.has(dsP.toString())) {
ds_pending_to_delete.add(dsP.toString());
}
}
// console.log(ds_pending_to_delete);
const sortedKeys = ds_keys.slice().sort((a, b) => b.localeCompare(a));
for (let index = 0; index < sortedKeys.length; index++) {
const key = sortedKeys[index];
const val = _session.DS_GLB[key];
const parent_ds = typeof val.parentDataSourceNo !== 'undefined' ? val.parentDataSourceNo.toString() : null;
if (!ds_pending_to_delete.has(key) && parent_ds && ds_pending_to_delete.has(parent_ds)) {
ds_pending_to_delete.delete(parent_ds);
}
}
// console.log(ds_pending_to_delete);
for (const val of ds_pending_to_delete) {
func.datasource.del(SESSION_ID, val);
}
};
func.UI.refs_garbage_collector = function (SESSION_ID = Object.keys(SESSION_OBJ)[0]) {
if (!xu_isEmpty(SCREEN_BLOCKER_OBJ)) {
// let dom to finish build
return;
}
let _session = SESSION_OBJ[SESSION_ID];
const _data_system = _session?.DS_GLB?.[0]?.data_system;
const refs_obj = _data_system?.SYS_GLOBAL_OBJ_REFS || {};
const ref_keys = Object.keys(refs_obj);
for (let ref_index = 0; ref_index < ref_keys.length; ref_index++) {
const key = ref_keys[ref_index];
const val = refs_obj[key];
const $root = func.UI.worker.get_session_root(SESSION_ID);
const _raw_el = func.runtime?.ui?.get_refresh_indexed_element_by_ui_id
? func.runtime.ui.get_refresh_indexed_element_by_ui_id(SESSION_ID, val.xu_ui_id)
: null;
const $element = _raw_el
? func.runtime.ui._wrap_matches([_raw_el])
: func.runtime?.ui?.find_refresh_elements_by_attr
? func.runtime.ui.find_refresh_elements_by_attr($root, 'xu-ui-id', val.xu_ui_id, true)
: func.runtime.ui.find_by_selector($root, `[xu-ui-id='${val.xu_ui_id}']`);
const $panel_wrapper = func.runtime?.ui?.find_panel_wrapper_in_root
? func.runtime.ui.find_panel_wrapper_in_root(SESSION_ID, val.xu_ui_id)
: func.runtime?.ui?.find_refresh_elements_by_attr
? func.runtime.ui.find_refresh_elements_by_attr($root, 'xu-panel-wrapper-id', val.xu_ui_id, true)
: func.runtime.ui.find_by_selector($root, `[xu-panel-wrapper-id='${val.xu_ui_id}']`);
if (!$element?.length && !$panel_wrapper?.length) {
delete _data_system.SYS_GLOBAL_OBJ_REFS[key];
}
}
};
// Reconcile teleported content with its host. A xu-teleport moves content OUT
// of the host's subtree to a target, so the content's lifecycle is no longer
// tied to the host by the DOM. This keeps them in sync:
// - host removed -> drop the orphaned teleport
// - host hidden -> hide the teleport (it lives at the target, outside the
// host, and would otherwise stay visible while the host is
// hidden), and restore it when the host is shown again.
// Driven by the 1s maintenance tick (backstop) AND immediately whenever a
// screen settles (see the screen-blocker unblock hook in this file), so there
// is no visible lag on panel open/close.
func.UI.reconcile_teleports = function (SESSION_ID = Object.keys(SESSION_OBJ)[0]) {
if (func.UI._reconciling_teleports) {
return;
}
if (!xu_isEmpty(SCREEN_BLOCKER_OBJ)) {
// let dom finish building
return;
}
const $root = func.UI.worker.get_session_root(SESSION_ID);
// Match ALL teleported elements. Every xu-teleport-parent-id holds a host's
// xu-ui-id, and xu-ui-id is a 10-char base36 hash from func.common.fastHash
// (e.g. "a3x9k2m1p0") — it NEVER starts with "node-". The old `^='node-'`
// filter therefore matched zero elements, so this whole function was a silent
// no-op and orphaned teleports (e.g. the ילקוט דיגיטלי nav) were never
// collected when their host/panel closed. See handles in
// xuda_runtime.browser.handlers.nodes.js (handle_xu_teleport).
const teleport_elements = $root[0]?.querySelectorAll?.(`[xu-teleport-parent-id]`) || [];
if (!teleport_elements.length) {
return;
}
func.UI._reconciling_teleports = true;
try {
for (let index = 0; index < teleport_elements.length; index++) {
const val = teleport_elements[index];
const xu_teleport_parent_id = val.getAttribute('xu-teleport-parent-id');
const _raw_parent = func.runtime?.ui?.get_refresh_indexed_element_by_ui_id
? func.runtime.ui.get_refresh_indexed_element_by_ui_id(SESSION_ID, xu_teleport_parent_id)
: null;
const $parent = _raw_parent
? func.runtime.ui._wrap_matches([_raw_parent])
: func.runtime?.ui?.find_refresh_elements_by_attr
? func.runtime.ui.find_refresh_elements_by_attr($root, 'xu-ui-id', xu_teleport_parent_id, true)
: func.runtime.ui.find_by_selector($root, `[xu-ui-id='${xu_teleport_parent_id}']`);
// Resolve a host node that is actually connected. The refresh-index lookup
// can hand back a DETACHED element (remove_xu_ui only marks the index
// dirty, and get_preferred_live_element returns a disconnected node when it
// is the only candidate), which used to make a removed panel look
// "present" and leak its teleport forever.
const parent_nodes = func.runtime.ui._to_node_array ? func.runtime.ui._to_node_array($parent) : [];
const host = parent_nodes.find((n) => n && n.isConnected);
if (!host) {
// Host removed -> the teleported content is orphaned; drop it.
func.runtime.ui.remove(val);
continue;
}
// Host present -> mirror its effective visibility onto the teleport, but
// ONLY when the host is a normal container (the "path A" host — a rendered
// parent DIV). In "path B" the host IS the <xu-teleport> source element,
// which handle_xu_teleport hides at its origin ON PURPOSE while the real
// content lives (visible) at the target; mirroring that intentional hidden
// state would wrongly hide legitimately-teleported content. The orphan
// removal above still applies to path B (source removed -> content drops).
const host_is_teleport_source = typeof host.tagName === 'string' && host.tagName.toLowerCase() === 'xu-teleport';
if (!host_is_teleport_source) {
// getClientRects().length === 0 catches display:none on the host or any
// ancestor; the hidden attribute is checked explicitly. Idempotent via
// the xu-teleport-hidden marker; original inline display saved/restored.
const host_hidden = host.hidden === true || (typeof host.getClientRects === 'function' && host.getClientRects().length === 0);
if (host_hidden) {
if (val.getAttribute('xu-teleport-hidden') !== '1') {
val.setAttribute('xu-teleport-hidden', '1');
val.setAttribute('xu-teleport-prev-display', val.style.display || '');
val.style.display = 'none';
}
} else if (val.getAttribute('xu-teleport-hidden') === '1') {
val.style.display = val.getAttribute('xu-teleport-prev-display') || '';
val.removeAttribute('xu-teleport-hidden');
val.removeAttribute('xu-teleport-prev-display');
}
}
}
} finally {
func.UI._reconciling_teleports = false;
}
};
// Back-compat alias: the 1s maintenance loop and any existing callers keep
// calling teleport_garbage_collector; it now also mirrors host visibility.
func.UI.teleport_garbage_collector = func.UI.reconcile_teleports;
func.UI.utils.prog_ui_attribute_index_cache = func.UI.utils.prog_ui_attribute_index_cache || new WeakMap();
func.UI.utils.get_prog_ui_attribute_index = function (progUi, prop, tag_name) {
if (!Array.isArray(progUi) || !prop) {
return {};
}
let prog_cache = func.UI.utils.prog_ui_attribute_index_cache.get(progUi);
if (!prog_cache) {
prog_cache = {};
func.UI.utils.prog_ui_attribute_index_cache.set(progUi, prog_cache);
}
const cache_key = `${prop || ''}::${tag_name || ''}`;
if (prog_cache[cache_key]) {
return prog_cache[cache_key];
}
const index = {};
const add_field = function (field_ref, item) {
if (!field_ref) {
return;
}
if (!index[field_ref]) {
index[field_ref] = [];
}
index[field_ref].push(item);
};
const iterate_progUi = function (node) {
for (let item of node) {
if ((!tag_name || item.tagName === tag_name) && !xu_isEmpty(item.attributes)) {
const attribute_keys = Object.keys(item.attributes);
for (let attr_index = 0; attr_index < attribute_keys.length; attr_index++) {
const attr = attribute_keys[attr_index];
const val = item.attributes[attr];
if (attr !== `xu-exp:${prop}` && attr !== prop) {
continue;
}
const attr_str = typeof val === 'string' ? val : JSON.stringify(val);
if (!attr_str) {
continue;
}
for (const match of attr_str.matchAll(/@([A-Za-z0-9_$.-]+)/g)) {
add_field(match[1], item);
}
}
}
if (item.children) {
iterate_progUi(item.children);
}
}
};
iterate_progUi(progUi);
prog_cache[cache_key] = index;
return index;
};
func.UI.find_field_in_progUi_attributes = function (progUi, field_id, prop, tag_name) {
if (prop) {
const index = func.UI.utils.get_prog_ui_attribute_index(progUi, prop, tag_name);
return index[field_id] || [];
}
let elm_nodes = [];
const iterate_progUi = function (node) {
for (let item of node) {
if (!tag_name || item.tagName === tag_name) {
if (tag_name) {
elm_nodes.push(item);
}
}
if (item.children) {
iterate_progUi(item.children);
}
}
};
iterate_progUi(progUi);
return elm_nodes;
};
func.UI.update_xu_ref = function (SESSION_ID, dsSessionP, ref_field_id, $elm) {
let ret;
const _session = SESSION_OBJ[SESSION_ID];
let _ds_0 = _session.DS_GLB[0];
const _ds = func.utils.clean_returned_datasource(SESSION_ID, dsSessionP);
// function createWatchedObject(obj, onChange) {
// const watchers = new WeakMap();
// function createProxy(target, path = []) {
// if (watchers.has(target)) {
// return watchers.get(target);
// }
// const proxy = new Proxy(target, {
// set(obj, prop, value) {
// const oldValue = obj[prop];
// let currentPath = [...path, prop];
// // Set the new value
// obj[prop] = value;
// // If the new value is an object, make it observable too
// if (typeof value === 'object' && value !== null) {
// obj[prop] = createProxy(value, currentPath);
// }
// // Notify of change
// if (oldValue !== value) {
// currentPath.shift();
// onChange({
// path: currentPath.join('.'),
// oldValue,
// newValue: value,
// type: 'set',
// timestamp: Date.now(),
// });
// }
// return true;
// },
// deleteProperty(obj, prop) {
// const oldValue = obj[prop];
// const currentPath = [...path, prop];
// delete obj[prop];
// onChange({
// path: currentPath.join('.'),
// oldValue,
// newValue: undefined,
// type: 'delete',
// timestamp: Date.now(),
// });
// return true;
// },
// });
// // Make nested objects observable
// for (const [key, value] of Object.entries(target)) {
// if (typeof value === 'object' && value !== null) {
// target[key] = createProxy(value, [...path, key]);
// }
// }
// watchers.set(target, proxy);
// return proxy;
// }
// return createProxy(obj);
// }
// const watchedDs = createWatchedObject({ _ref: _ds }, async (change) => {
// // console.log('Change detected:', change);
// const { path, newValue } = change;
// try {
// const datasource_changes = {
// [dsSessionP]: {
// ['datasource_main']: {
// watcher: { path, newValue },
// },
// },
// };
// await func.datasource.update(SESSION_ID, datasource_changes);
// } catch (error) {}
// });
//////////////
const clone_ref_value = function (value) {
if (typeof structuredClone === 'function') {
try {
return structuredClone(value);
} catch (error) {}
}
if (typeof _ !== 'undefined' && _.cloneDeep) {
return _.cloneDeep(value);
}
try {
return JSON.parse(JSON.stringify(value));
} catch (error) {
return value;
}
};
// Store snapshots instead of live object references so later datasource
// mutations are visible to xu-ref equality checks and UI refreshes.
let obj = { ds: clone_ref_value(_ds), data: {}, props: clone_ref_value(_ds.in_parameters || {}) };
// The xu-ref snapshot should track app-visible datasource state, not runtime bookkeeping.
// Exclude self-referential stores and refresh metadata so equality checks are driven by real
// data/parameter/UI changes rather than lifecycle ticks.
if (obj.ds) {
delete obj.ds.data_system;
delete obj.ds.refreshed;
delete obj.ds.stat;
delete obj.ds.stat_ts;
if (obj.ds.data_feed) delete obj.ds.data_feed.rows_changed;
if (obj.ds.v) delete obj.ds.v.old_dataSource;
}
try {
const row_idx = func.common.find_ROWID_idx(_ds, _ds.currentRecordId);
obj.data = clone_ref_value(_ds?.data_feed?.rows?.[row_idx]);
} catch (error) {
// error normal if find_ROWID_idx fail
}
let SYS_GLOBAL_OBJ_REFS = _ds_0.data_system['SYS_GLOBAL_OBJ_REFS'];
if ($elm) {
const elm_data = func.runtime.ui.get_data($elm);
const attributes = elm_data?.xuData?.xuPanelProps || elm_data?.xuData?.debug_info?.attribute_stat || {};
obj.attributes = clone_ref_value(attributes);
obj.xu_ui_id = func.runtime.ui.get_attr($elm, 'xu-ui-id');
}
// During datasource refresh, row data can be momentarily empty while the rows are being rebuilt.
// Do not replace a populated ref snapshot with that transient empty state.
const _stored_ref0 = SYS_GLOBAL_OBJ_REFS[ref_field_id];
const _new_data_empty = !obj.data || (typeof obj.data === 'object' && Object.keys(obj.data).length === 0);
const _stored_data_full =
_stored_ref0 && _stored_ref0.data && typeof _stored_ref0.data === 'object' && Object.keys(_stored_ref0.data).length > 0;
if (_new_data_empty && _stored_data_full) {
return ret;
}
// Compare only the parts the new snapshot actually carries. Datasource-path calls have no DOM
// element, so they cannot provide UI attributes or current panel parameter props; render-path calls
// do. Gate those DOM-derived pieces on $elm, while row data remains compared on every call.
const _stored_cmp = SYS_GLOBAL_OBJ_REFS[ref_field_id];
const _has_elm = $elm != null;
const _ref_changed =
!_stored_cmp ||
!xu_isEqual(_stored_cmp.data, obj.data) ||
(_has_elm && !xu_isEqual(_stored_cmp.props, obj.props)) ||
(_has_elm && !xu_isEqual(_stored_cmp.attributes, obj.attributes)) ||
(_has_elm && _stored_cmp.xu_ui_id !== obj.xu_ui_id);
// Temporary instrumentation: logs when a no-$elm props-only diff is ignored by the ref gate.
try {
if (typeof window !== 'undefined' && !_has_elm && _stored_cmp && !_ref_changed && !xu_isEqual(_stored_cmp.props, obj.props)) {
console.log('[xu-propsgate] suppressed no-$elm props-only diff, ref=' + ref_field_id + ' ds=' + (obj?.ds?.dsSession));
}
} catch (e) {}
if (_ref_changed) {
const _ref_was_absent = !SYS_GLOBAL_OBJ_REFS[ref_field_id];
if (_ref_was_absent) {
SYS_GLOBAL_OBJ_REFS[ref_field_id] = {};
}
// SYS_GLOBAL_OBJ_REFS[ref_field_id] = obj;
function deepUpdateObject(a, b) {
for (let key in b) {
if (b.hasOwnProperty(key)) {
if (typeof b[key] === 'object' && b[key] !== null && !Array.isArray(b[key]) && a[key] && typeof a[key] === 'object') {
deepUpdateObject(a[key], b[key]);
} else {
if (!xu_isEqual(a[key], b[key])) {
a[key] = b[key];
}
}
}
}
return a;
}
deepUpdateObject(SYS_GLOBAL_OBJ_REFS[ref_field_id], obj);
// SYS_GLOBAL_OBJ_REFS[ref_field_id] = obj;
ret = true;
}
return ret;
};
// func.UI.create_xu_ref = function (SESSION_ID, dsSessionP, ref_field_id, $elm) {
// let ret;
// const _session = SESSION_OBJ[SESSION_ID];
// let _ds_0 = _session.DS_GLB[0];
// function createWatchedObject(obj, onChange) {
// const watchers = new WeakMap();
// function createProxy(target, path = []) {
// if (watchers.has(target)) {
// return watchers.get(target);
// }
// const proxy = new Proxy(target, {
// set(obj, prop, value) {
// const oldValue = obj[prop];
// let currentPath = [...path, prop];
// // Set the new value
// obj[prop] = value;
// // If the new value is an object, make it observable too
// if (typeof value === 'object' && value !== null) {
// obj[prop] = createProxy(value, currentPath);
// }
// // Notify of change
// // if (oldValue !== value) {
// if (!_.isEqual(value, oldValue)) {
// currentPath.shift();
// onChange({
// path: currentPath.join('.'),
// oldValue,
// newValue: value,
// type: 'set',
// timestamp: Date.now(),
// });
// }
// return true;
// },
// deleteProperty(obj, prop) {
// const oldValue = obj[prop];
// const currentPath = [...path, prop];
// delete obj[prop];
// onChange({
// path: currentPath.join('.'),
// oldValue,
// newValue: undefined,
// type: 'delete',
// timestamp: Date.now(),
// });
// return true;
// },
// });
// // Make nested objects observable
// for (const [key, value] of Object.entries(target)) {
// if (typeof value === 'object' && value !== null) {
// target[key] = createProxy(value, [...path, key]);
// }
// }
// watchers.set(target, proxy);
// return proxy;
// }
// return createProxy(obj);
// }
// let _ds = _session.DS_GLB[dsSessionP];
// // const watchedDs = createWatchedObject({ _ref: _ds }, async (change) => {
// // // console.log('Change detected:', change);
// // const { path, newValue, oldValue } = change;
// // });
// const createBasicProxy = (target) => {
// return new Proxy(target, {
// // Intercept property access
// get(obj, prop) {
// console.log(`Getting property: ${String(prop)}`);
// return prop in obj ? obj[prop] : `Property ${String(prop)} not found`;
// },
// // Intercept property assignment
// set(obj, prop, value) {
// console.log(`Setting property: ${String(prop)} to ${value}`);
// obj[prop] = value;
// return true; // indicates success
// },
// // Intercept property deletion
// deleteProperty(obj, prop) {
// console.log(`Deleting property: ${String(prop)}`);
// if (prop in obj) {
// delete obj[prop];
// return true;
// }
// return false;
// },
// });
// };
// const p = createBasicProxy(_ds);
// // let obj = { ds: watchedDs._ref, data: {}, props: _ds.in_parameters || {} };
// let obj = { ds: {}, data: {}, props: _ds.in_parameters || {} };
// try {
// const row_idx = func.common.find_ROWID_idx(_ds, _ds.currentRecordId);
// obj.data = _ds?.data_feed?.rows?.[row_idx];
// } catch (error) {
// // error normal if find_ROWID_idx fail
// }
// let SYS_GLOBAL_OBJ_REFS = _ds_0.data_system['SYS_GLOBAL_OBJ_REFS'];
// if ($elm) {
// const attributes = $elm?.data()?.xuData?.xuPanelProps || $elm?.data()?.xuData?.debug_info?.attribute_stat || {};
// obj.attributes = attributes;
// obj.xu_ui_id = $elm.attr('xu-ui-id');
// }
// SYS_GLOBAL_OBJ_REFS[ref_field_id] = obj;
// return ret;
// };
func.runtime = func.runtime || {};
func.runtime.ui = func.runtime.ui || {};
func.runtime.render = func.runtime.render || {};
func.runtime.widgets = func.runtime.widgets || {};
func.runtime.perf = func.runtime.perf || {};
func.runtime.perf.global_stats = func.runtime.perf.global_stats || { sessions: {} };
func.runtime.perf.get_host = function () {
if (typeof window !== 'undefined') {
return window;
}
if (typeof globalThis !== 'undefined') {
return globalThis;
}
return {};
};
func.runtime.perf.sync_global_ref = function () {
const host = func.runtime.perf.get_host();
host.XUDA_RUNTIME_STATS = func.runtime.perf.global_stats;
return host.XUDA_RUNTIME_STATS;
};
func.runtime.perf.is_enabled = function () {
const host = func.runtime.perf.get_host();
const debug_mode = typeof glb !== 'undefined' && !!glb.DEBUG_MODE;
return !!(debug_mode || host.XUDA_RUNTIME_STATS_ENABLED);
};
func.runtime.perf.now = function () {
if (typeof performance !== 'undefined' && typeof performance.now === 'function') {
return performance.now();
}
return Date.now();
};
func.runtime.perf.ensure_session_stats = function (SESSION_ID) {
const global_stats = func.runtime.perf.global_stats;
if (!global_stats.sessions[SESSION_ID]) {
global_stats.sessions[SESSION_ID] = {
created_at: Date.now(),
counters: {},
durations: {},
maps: {},
};
}
if (SESSION_OBJ?.[SESSION_ID]) {
SESSION_OBJ[SESSION_ID].runtime_stats = global_stats.sessions[SESSION_ID];
}
func.runtime.perf.sync_global_ref();
return global_stats.sessions[SESSION_ID];
};
func.runtime.perf.reset_session = function (SESSION_ID) {
if (!SESSION_ID) {
return false;
}
delete func.runtime.perf.global_stats.sessions[SESSION_ID];
if (SESSION_OBJ?.[SESSION_ID]) {
delete SESSION_OBJ[SESSION_ID].runtime_stats;
}
func.runtime.perf.sync_global_ref();
return true;
};
func.runtime.perf.reset = function () {
func.runtime.perf.global_stats = { sessions: {} };
const session_ids = Object.keys(SESSION_OBJ || {});
for (let index = 0; index < session_ids.length; index++) {
delete SESSION_OBJ[session_ids[index]].runtime_stats;
}
func.runtime.perf.sync_global_ref();
return func.runtime.perf.global_stats;
};
func.runtime.perf.get_session_stats = function (SESSION_ID) {
if (!SESSION_ID) {
return null;
}
return func.runtime.perf.global_stats.sessions[SESSION_ID] || null;
};
func.runtime.perf.increment = function (SESSION_ID, key, amount = 1) {
if (!func.runtime.perf.is_enabled()) {
return 0;
}
const stats = func.runtime.perf.ensure_session_stats(SESSION_ID);
stats.counters[key] = (stats.counters[key] || 0) + amount;
return stats.counters[key];
};
func.runtime.perf.increment_map = function (SESSION_ID, bucket, key, amount = 1) {
if (!func.runtime.perf.is_enabled() || typeof key === 'undefined' || key === null) {
return 0;
}
const stats = func.runtime.perf.ensure_session_stats(SESSION_ID);
if (!stats.maps[bucket]) {
stats.maps[bucket] = {};
}
const map_key = key.toString();
stats.maps[bucket][map_key] = (stats.maps[bucket][map_key] || 0) + amount;
return stats.maps[bucket][map_key];
};
func.runtime.perf.record_duration = function (SESSION_ID, key, duration_ms) {
if (!func.runtime.perf.is_enabled()) {
return null;
}
const stats = func.runtime.perf.ensure_session_stats(SESSION_ID);
if (!stats.durations[key]) {
stats.durations[key] = {
count: 0,
total_ms: 0,
max_ms: 0,
last_ms: 0,
avg_ms: 0,
};
}
const metric = stats.durations[key];
metric.count++;
metric.total_ms += duration_ms;
metric.last_ms = duration_ms;
metric.max_ms = Math.max(metric.max_ms, duration_ms);
metric.avg_ms = metric.total_ms / metric.count;
return metric;
};
func.runtime.perf.start = function (SESSION_ID, key) {
if (!func.runtime.perf.is_enabled()) {
return null;
}
const started_at = func.runtime.perf.now();
return function () {
return func.runtime.perf.record_duration(SESSION_ID, key, func.runtime.perf.now() - started_at);
};
};
func.runtime.ui.init_screen = async function (options) {
const {
SESSION_ID,
prog_id,
sourceScreenP,
callingDataSource_objP,
$callingContainerP,
triggerIdP,
rowIdP,
jobNoP,
is_panelP,
parameters_obj_inP,
source_functionP,
call_screen_propertiesP,
refreshed_ds,
parameters_raw_obj,
} = options;
if (!prog_id) {
await func.utils.report_issue(SESSION_ID, {
code: 'RUN_MSG_RND_030',
source: 'func.runtime.ui.init_screen',
message: 'program is empty',
type: 'E',
});
return null;
}
const screen_ret = await func.utils.get_screen_obj(SESSION_ID, prog_id);
if (!screen_ret) {
await func.utils.report_issue(SESSION_ID, {
code: 'RUN_MSG_RND_030',
source: 'func.runtime.ui.init_screen',
message: 'program is not a screen object',
type: 'E',
details: {
prog_id,
},
});
return null;
}
await func.UI.utils.init_ui_framework(SESSION_ID, prog_id);
const _session = SESSION_OBJ[SESSION_ID];
const screenInfo = structuredClone(screen_ret);
const ssr_payload = func.runtime.render.should_use_ssr_payload(SESSION_ID, { prog_id }) ? func.runtime.render.get_ssr_payload(_session) : null;
const screen_type = source_functionP?.split('_')?.[1];
const screenId = ssr_payload?.screenId || (glb.screen_num++).toString();
if (SCREEN_BLOCKER_OBJ[prog_id + (sourceScreenP ? '_' + sourceScreenP : '')]) {
const wait_for_SCREEN_BLOCKER_release = function () {
return new Promise((resolve) => {
const interval = setInterval(function () {
if (!SCREEN_BLOCKER_OBJ[prog_id + (sourceScreenP ? '_' + sourceScreenP : '')]) {
clearInterval(interval);
resolve();
}
}, 5);
});
};
await wait_for_SCREEN_BLOCKER_release();
}
func.UI.utils.screen_blocker(true, prog_id + (sourceScreenP ? '_' + sourceScreenP : ''));
if ($callingContainerP && !xu_isEmpty($callingContainerP)) {
const calling_data = func.runtime.ui.get_data($callingContainerP);
if (calling_data?.xuData) calling_data.xuData.screenInfo = screenInfo;
}
let $dialogDiv;
let $rootFrame;
const params = {
prog_id,
sourceScreenP,
$callingContainerP,
triggerIdP,
callingDataSource_objP,
rowIdP,
renderType: screenInfo.properties?.renderType,
parameters_obj_inP,
source_functionP,
is_panelP,
screen_type,
screenInfo,
call_screen_propertiesP,
parentDataSourceNoP: _session.DS_GLB?.[callingDataSource_objP?.dsSession]?.dsSession || callingDataSource_objP?.parentDataSourceNo || 0,
parameters_raw_obj,
containerIdP: ssr_payload?.containerId || null,
ssr_payload,
};
const screen_host = func.runtime.ui.create_screen_host(SESSION_ID, screen_type, params, $callingContainerP, screenId);
$dialogDiv = screen_host.$dialogDiv;
$rootFrame = screen_host.$rootFrame;
params.containerIdP = func.runtime.ui.get_attr($rootFrame, 'id');
params.$container = $rootFrame;
const containerId = 'container_' + params.screenInfo.properties?.id + '_' + screenId;
const data = {
note: ' ROOT container',
root: true,
screenId,
is_panelP,
prog_id,
screen_type,
container: '#' + containerId,
};
if (is_panelP) {
func.runtime.ui.get_data($rootFrame).xuData.rootFrame = data;
} else {
const rf_data = func.runtime.ui.get_data($rootFrame);
if (!rf_data?.xuData) {
func.runtime.ui.set_data($rootFrame, 'xuData', {});
}
func.runtime.ui.set_attr($rootFrame, 'id', containerId);
func.runtime.ui.get_data($rootFrame).xuData.rootFrame = data;
func.runtime.ui.set_style($rootFrame, 'display', 'contents');
}
if (screen_host.reused_ssr_host && func.runtime.render.is_takeover_mode(_session)) {
func.runtime.ui.empty($rootFrame);
}
if (!is_panelP) func.UI.utils.indicator.screen.busy();
const ret = await func.datasource.create(
SESSION_ID,
prog_id,
refreshed_ds,
params.parentDataSourceNoP,
func.runtime.ui.get_attr($rootFrame, 'id'),
rowIdP,
jobNoP,
null,
parameters_raw_obj,
null,
null,
null,
null,
is_panelP,
parameters_obj_inP,
);
const _ds = SESSION_OBJ[SESSION_ID].DS_GLB[ret.dsSessionP];
_ds.screen_params = params;
params.dsSessionP = ret.dsSessionP;
func.runtime.ui.update_sys_obj_win_info(SESSION_ID, params.dsSessionP);
if (ret.dsSessionP < 0) {
return;
}
let viewDoc;
const view_ret = await func.utils.VIEWS_OBJ.get(SESSION_ID, SESSION_OBJ[SESSION_ID].DS_GLB[ret.dsSessionP].prog_id);
if (view_ret) {
viewDoc = view_ret;
}
if (!viewDoc?.progUi) {
return func.utils.alerts.invoke(SESSION_ID, 'system_msg', 'SYS_MSG_0780', params.renderType, ret.dsSessionP);
}
let node = structuredClone(viewDoc.progUi);
if (!node.length) {
await func.utils.report_issue(SESSION_ID, {
code: 'RUN_MSG_RND_040',
source: 'func.runtime.ui.render_single_view_node',
message: 'ui node empty',
type: 'W',
details: {
prog_id: SESSION_OBJ[SESSION_ID].DS_GLB[ret.dsSessionP].prog_id,
},
});
return null;
}
const ret_render_$container = await func.runtime.render.render_ui_tree(
SESSION_ID,
$rootFrame,
node[0],
null,
params,
jobNoP,
null,
null,
null,
null,
null,
$rootFrame,
);
if (!is_panelP) func.UI.utils.indicator.screen.normal();
return await func.runtime.ui.screen_loading_done({
SESSION_ID,
paramsP: params,
$div: ret_render_$container,
jobNoP,
});
};
func.runtime.ui.update_sys_obj_win_info = function (SESSION_ID, dsNoP) {
const _ds = SESSION_OBJ[SESSION_ID].DS_GLB[dsNoP];
if (!_ds) return;
if (!_ds.data_system) {
_ds.data_system = {};
}
_ds.data_system['SYS_STR_WIN_ID'] = _ds.tree_obj?.id;
_ds.data_system['SYS_STR_WIN_NAME'] = _ds.tree_obj?.menuName;
if (SESSION_OBJ[SESSION_ID].DS_GLB[dsNoP].mode) {
_ds.data_system['SYS_STR_WIN_MODE'] = SESSION_OBJ[SESSION_ID].DS_GLB[dsNoP].mode;
}
};
func.runtime.ui.validate_exit_events = async function (SESSION_ID, div_data_paramsP, forceP) {
return new Promise(async (resolve) => {
await func.events.validate(SESSION_ID, 'on_exit', div_data_paramsP.dsSessionP, null, 'screen');
const interval = setInterval(function () {
if (!SESSION_OBJ[SESSION_ID].WORKER_OBJ.jobs.length || forceP) {
clearInterval(interval);
resolve();
}
}, 5);
});
};
func.runtime.ui.call_embed = function (SESSION_ID, prog) {
const $embed = func.runtime.ui.get_embed_container(SESSION_ID);
func.runtime.ui.empty($embed);
const embed_data = func.runtime.ui.get_data($embed);
if (embed_data?.xuData) {
embed_data.xuData.screenInfo = null;
}
for (const [key, val] of Object.entries(SESSION_OBJ[SESSION_ID].DS_GLB)) {
if (key) func.datasource.del(SESSION_ID, key);
}
func.UI.main.embed_prog_execute(SESSION_ID, prog);
};
// Browser UI/screen boot helpers remain here. DOM/host helpers moved to xuda_runtime.browser.dom.js,
// presentation helpers moved to xuda_runtime.browser.presentation.js,
// refresh/realtime helpers moved to xuda_runtime.browser.refresh.js, and render/widget helpers moved to xuda_runtime.browser.render.js.
func.runtime = func.runtime || {};
func.runtime.ui = func.runtime.ui || {};
func.runtime.render = func.runtime.render || {};
func.runtime.widgets = func.runtime.widgets || {};
// Browser-only nav, modal, and page controller helpers live here so host/container wiring can stay focused.
func.runtime.ui.ensure_modal_controller = function (SESSION_ID, modal_id) {
var modal_controller = document.querySelector('xu-modal-controller');
if (!modal_controller) {
func.UI.component.create_app_modal_component(SESSION_ID, modal_id);
modal_controller = document.querySelector('xu-modal-controller');
}
return modal_controller;
};
func.runtime.ui.get_controller_params = function (controller_element) {
return func.runtime.ui.get_data(controller_element, 'xuControllerParams') || {};
};
func.runtime.ui.set_controller_params = function (controller_element, params) {
func.runtime.ui.set_data(controller_element, 'xuControllerParams', params);
return params;
};
func.runtime.ui.get_nav = function (SESSION_ID) {
return func.runtime.ui.find_in_root(SESSION_ID, 'xu-nav');
};
func.runtime.ui.ensure_nav = function (SESSION_ID, $container) {
let nav = func.runtime.ui.get_nav(SESSION_ID);
if (nav && nav.length) {
return nav;
}
var nav_el = document.createElement('xu-nav');
func.runtime.ui.append($container, nav_el);
var $nav = func.runtime.ui._wrap_matches([nav_el]);
func.UI.component.init_xu_nav($container, $nav);
return $nav;
};
func.runtime.ui.get_page_component_name = function (dsSessionP) {
return 'xu-page-component-' + dsSessionP;
};
func.runtime.ui.resolve_screen_property = async function (SESSION_ID, paramsP, property) {
var property_value = paramsP?.screenInfo?.properties?.[property] || paramsP?.screenInfo?.properties?.frameworkProperties?.[property];
if (paramsP?.call_screen_propertiesP) {
if (paramsP.call_screen_propertiesP?.[property]) {
property_value = paramsP.call_screen_propertiesP[property];
}
if (paramsP.call_screen_propertiesP[`xu-exp:${property}`]) {
property_value = (await func.expression.get(SESSION_ID, paramsP.call_screen_propertiesP[`xu-exp:${property}`], paramsP.dsSessionP, property)).result;
}
}
return property_value;
};
func.runtime.ui.apply_framework_properties = async function (SESSION_ID, paramsP, ui_framework, params) {
params.properties = {};
params.properties['name'] = await func.runtime.ui.resolve_screen_property(SESSION_ID, paramsP, 'menuTitle');
const properties = await ui_framework?.properties?.();
if (!properties) {
return params.properties;
}
for await (const [key, val] of Object.entries(properties)) {
params.properties[key] = await func.runtime.ui.resolve_screen_property(SESSION_ID, paramsP, key);
}
return params.properties;
};
func.runtime.ui.build_modal_params = function (paramsP, $div, $container, close_callback) {
return {
screenId: paramsP.screenId,
$dialogDiv: func.runtime.ui.get_children($div),
$container: $container,
dsSession: paramsP.dsSessionP,
modal_id: 'app_modal-' + paramsP.dsSessionP.toString(),
screenInfo: paramsP.screenInfo,
close_callback,
paramsP,
};
};
func.runtime.ui.set_modal_params = function (SESSION_ID, modal_id, params) {
var xu_modal_controller = func.runtime.ui.ensure_modal_controller(SESSION_ID, modal_id);
var controller_params = func.runtime.ui.get_controller_params(xu_modal_controller);
controller_params[modal_id] = params;
func.runtime.ui.set_controller_params(xu_modal_controller, controller_params);
return xu_modal_controller;
};
func.runtime.ui.get_modal_params = function (SESSION_ID, modal_id) {
const xu_modal_controller = func.runtime.ui.ensure_modal_controller(SESSION_ID, modal_id);
return func.runtime.ui.get_controller_params(xu_modal_controller)[modal_id];
};
func.runtime.ui.set_modal_instance = function (modal_id, modal) {
APP_MODAL_OBJ[modal_id] = modal;
return modal;
};
func.runtime.ui.has_modal_instance = function (modal_id) {
return !!APP_MODAL_OBJ[modal_id];
};
func.runtime.ui.delete_modal_instance = function (modal_id) {
delete APP_MODAL_OBJ[modal_id];
return true;
};
func.runtime.ui.close_all_modals = function () {
for (const [key, val] of Object.entries(APP_MODAL_OBJ)) {
if (val) {
UI_FRAMEWORK_PLUGIN.modal.close(key);
}
}
return true;
};
func.runtime.ui.build_popover_params = function (paramsP, $div, $container) {
return {
menuTitle: paramsP.screenInfo.properties?.menuTitle,
screenId: paramsP.screenId,
$dialogDiv: func.runtime.ui.get_children($div),
$container: $container,
};
};
func.runtime.ui.build_page_params = function (SESSION_ID, paramsP, $div_content, $container, nav) {
return {
div: $div_content,
name: paramsP.screenInfo.properties?.menuTitle,
screenId: paramsP.screenId,
$container: $container,
dsSession: paramsP.dsSessionP,
SESSION_ID,
nav,
paramsP,
};
};
func.runtime.ui.get_nav_data = function ($nav) {
return func.runtime.ui.get_data($nav)?.xuData || null;
};
func.runtime = func.runtime || {};
func.runtime.ui = func.runtime.ui || {};
func.runtime.render = func.runtime.render || {};
// Browser-only screen presentation helpers live here so the browser runtime can be split by concern.
func.runtime.ui.ensure_nav_params_registry = function ($nav) {
const nav_data = func.runtime.ui.get_nav_data($nav);
if (!nav_data) {
return null;
}
if (!nav_data.nav_params) {
nav_data.nav_params = {};
}
return nav_data.nav_params;
};
func.runtime.ui.restore_page_validate_state = function ($nav, dsSessionP, $container) {
const nav_data = func.runtime.ui.get_nav_data($nav);
const existing_params = nav_data?.params?.[dsSessionP];
if (func.runtime.ui.get_data(existing_params?.$container)?.xuData?.validate_screen_ready) {
func.runtime.ui.get_data($container).xuData.validate_screen_ready = func.runtime.ui.get_data(existing_params.$container).xuData.validate_screen_ready;
return true;
}
return false;
};
func.runtime.ui.register_page_params = function ($nav, dsSessionP, params) {
const nav_params = func.runtime.ui.ensure_nav_params_registry($nav);
if (!nav_params) {
return false;
}
nav_params[dsSessionP] = params;
return true;
};
func.runtime.ui.get_root_component_name = function (SESSION_ID) {
return 'xu-root-component-' + SESSION_ID;
};
func.runtime.ui.attach_nav_root_div = function ($nav, $div_content) {
const nav_data = func.runtime.ui.get_nav_data($nav);
if (!nav_data) {
return false;
}
nav_data.$div = $div_content;
return true;
};
func.runtime.ui.set_nav_root = async function ($nav, SESSION_ID) {
const nav_element = func.runtime.ui.get_first_node($nav);
if (!nav_element?.setRoot) {
return false;
}
await nav_element.setRoot(func.runtime.ui.get_root_component_name(SESSION_ID));
return true;
};
func.runtime.ui.release_screen_blocker = function (paramsP) {
func.UI.utils.screen_blocker(false, paramsP.prog_id + '_' + paramsP.sourceScreenP);
return true;
};
func.runtime.ui.close_modal_session = async function (SESSION_ID, modal_id) {
func.runtime.ui.delete_modal_instance(modal_id);
const params = func.runtime.ui.get_modal_params(SESSION_ID, modal_id);
if (params && params.$container) {
await func.runtime.ui.validate_exit_events(SESSION_ID, func.runtime.ui.get_data(params.$container)?.xuData?.paramsP, null);
func.datasource.clean_all(SESSION_ID, params.dsSession);
}
return true;
};
func.runtime.ui.render_screen_type = async function (options) {
const $div_content = func.runtime.ui.get_children(options.$div);
func.runtime.ui.sync_child_parent_container(options.$div);
const assert_framework_screen_supported = function (screen_type) {
if (!func.runtime.session.is_slim(options.SESSION_ID)) {
return;
}
throw new Error('Slim mode does not support "' + screen_type + '" screens without a UI framework plugin');
};
let $ret = options.$div;
let $nav = func.runtime.ui.get_nav(options.SESSION_ID);
let params;
switch (options.paramsP.screen_type) {
case 'modal': {
assert_framework_screen_supported('modal');
params = func.runtime.ui.build_modal_params(options.paramsP, options.$div, options.$container, options.close_modal);
const modal_id = params.modal_id;
func.runtime.ui.set_modal_params(options.SESSION_ID, modal_id, params);
const modalController = await new UI_FRAMEWORK_PLUGIN.modal();
await func.runtime.ui.apply_framework_properties(options.SESSION_ID, options.paramsP, modalController, params);
if (!func.runtime.ui.has_modal_instance(modal_id)) {
const modal = await modalController.create(params);
func.runtime.ui.set_modal_instance(modal_id, modal);
} else {
func.runtime.ui.empty(document.querySelector(modal_id));
}
await modalController.init(params);
break;
}
case 'popover': {
assert_framework_screen_supported('popover');
const xu_popover_controller = func.UI.component.create_app_popover_component(options.SESSION_ID);
params = func.runtime.ui.build_popover_params(options.paramsP, options.$div, options.$container);
func.runtime.ui.set_data(xu_popover_controller, 'xuControllerParams', params);
const popover = new UI_FRAMEWORK_PLUGIN.popover(options.SESSION_ID);
await func.runtime.ui.apply_framework_properties(options.SESSION_ID, options.paramsP, popover, params);
await popover.open(params);
CURRENT_APP_POPOVER = popover;
func.runtime.ui.release_screen_blocker(options.paramsP);
break;
}
case 'page': {
assert_framework_screen_supported('page');
const nav = func.runtime.ui.get_first_node($nav);
params = func.runtime.ui.build_page_params(options.SESSION_ID, options.paramsP, $div_content, options.$container, nav);
const component_name = func.runtime.ui.get_page_component_name(options.paramsP.dsSessionP);
func.runtime.ui.ensure_nav_params_registry($nav);
func.runtime.ui.restore_page_validate_state($nav, options.paramsP.dsSessionP, params.$container);
if (!func.runtime.ui.get_nav_data($nav)) return;
func.runtime.ui.register_page_params($nav, options.paramsP.dsSessionP, params);
if (!document.querySelector(component_name)) {
await func.UI.component.create_app_page_component(options.SESSION_ID, options.paramsP.dsSessionP);
const page = new UI_FRAMEWORK_PLUGIN.page();
await func.runtime.ui.apply_framework_properties(options.SESSION_ID, options.paramsP, page, params);
await page.create(params);
await page.init(params);
nav.push(component_name, { params });
} else {
console.error('[xuda-runtime] xuda_runtime.browser.presentation.js:134');
func.runtime.ui.empty(component_name);
await UI_FRAMEWORK_PLUGIN.page(options.SESSION_ID, options.paramsP.dsSessionP);
}
func.runtime.ui.get_data(options.$div).xuData.paramsP = func.runtime.ui.get_data(options.$container).xuData.paramsP;
break;
}
case 'panel':
func.runtime.ui.append(options.$container, $div_content);
$ret = options.$container;
break;
default:
$nav = func.runtime.ui.ensure_nav(options.SESSION_ID, options.$container);
func.runtime.ui.attach_nav_root_div($nav, $div_content);
await func.runtime.ui.set_nav_root($nav, options.SESSION_ID);
$ret = options.$container;
break;
}
return $ret;
};
func.runtime = func.runtime || {};
func.runtime.ui = func.runtime.ui || {};
func.runtime.render = func.runtime.render || {};
// Browser-only non-panel view renderers live here so screen presentation orchestration can stay focused.
func.runtime.ui.ensure_container_attributes = async function (options) {
const container_data = func.runtime.ui.get_data(options.$container);
if (!xu_isEmpty(container_data?.xuAttributes)) {
return options.$container;
}
await func.runtime.render.set_attributes_new({
SESSION_ID: options.SESSION_ID,
is_skeleton: options.is_skeleton,
$root_container: options.$root_container,
nodeP: options.nodeP,
$container: options.$container,
paramsP: options.paramsP,
parent_infoP: options.parent_infoP,
jobNoP: options.jobNoP,
keyP: options.keyP,
parent_nodeP: options.parent_nodeP,
$elm: options.$container,
is_init: true,
});
return options.$container;
};
func.runtime.ui.copy_runtime_state = function ($source, $target) {
const source_data = func.runtime.ui.get_data($source);
const target_data = func.runtime.ui.get_data($target);
if (!source_data?.xuData || !target_data?.xuData || !source_data?.xuAttributes || !target_data?.xuAttributes) {
return $target;
}
const xu_data_keys = Object.keys(source_data.xuData);
for (let index = 0; index < xu_data_keys.length; index++) {
const key = xu_data_keys[index];
const val = source_data.xuData[key];
try { target_data.xuData[key] = structuredClone(val); } catch (_) { target_data.xuData[key] = val; }
}
const xu_attribute_keys = Object.keys(source_data.xuAttributes);
for (let index = 0; index < xu_attribute_keys.length; index++) {
const key = xu_attribute_keys[index];
const val = source_data.xuAttributes[key];
try { target_data.xuAttributes[key] = structuredClone(val); } catch (_) { target_data.xuAttributes[key] = val; }
}
func.runtime.ui.mark_refresh_index_dirty_from_target?.($target, target_data.xuData.SESSION_ID || source_data.xuData.SESSION_ID);
return $target;
};
func.runtime.ui.ensure_multi_view_state = function ($div, nodeP, $container) {
const div_data = func.runtime.ui.get_data($div);
const container_data = func.runtime.ui.get_data($container);
if (!div_data?.xuData?.node || !div_data.xuData.node.children) {
div_data.xuData.node = nodeP;
}
if (!div_data?.xuData?.debug_info) {
div_data.xuData.debug_info = {
id: nodeP.id,
parent_id: container_data?.xuData?.ui_id,
};
}
return $div;
};
func.runtime.ui.should_close_mobile_overlays = function (paramsP) {
return !REFRESHER_IN_PROGRESS && (paramsP.is_mobile_popover || paramsP.is_mobile_page);
};
func.runtime.ui.render_single_view_node = async function (options) {
const exist_elm_obj = func.runtime.render.find_existing_element({
$container: options.$container,
nodeP: options.nodeP,
keyP: options.keyP,
render_context: options.render_context,
});
let $div = exist_elm_obj.div;
if (!$div) {
const $wrapper = document.createElement('div');
$div = await func.runtime.ui.create_container({
SESSION_ID: options.SESSION_ID,
$root_container: options.$root_container,
nodeP: options.nodeP,
$container: options.$container,
paramsP: options.paramsP,
parent_infoP: options.parent_infoP,
jobNoP: options.jobNoP,
keyP: options.keyP,
treeP: options.treeP,
parent_nodeP: options.parent_nodeP,
prop: options.prop,
div_typeP: 'div',
$appendToP: $wrapper,
attr_str: '',
});
if (!$div) return;
if (func.runtime.ui.should_close_mobile_overlays(options.paramsP)) {
func.runtime.ui.close_all_modals();
}
const div_el = func.runtime.ui.get_first_node($div);
if (div_el) {
div_el.addEventListener('mouseenter', function (e) {
options.hover_handlers.hover_in($div, e);
});
div_el.addEventListener('mouseleave', function () {
options.hover_handlers.hover_out();
});
}
}
await options.iterate_child($div, options.nodeP, null, $div);
await func.runtime.ui.ensure_container_attributes({
SESSION_ID: options.SESSION_ID,
is_skeleton: options.is_skeleton,
$root_container: options.$root_container,
nodeP: options.nodeP,
$container: options.$container,
paramsP: options.paramsP,
parent_infoP: options.parent_infoP,
jobNoP: options.jobNoP,
keyP: options.keyP,
parent_nodeP: options.parent_nodeP,
});
func.runtime.ui.copy_runtime_state($div, options.$container);
return await func.runtime.ui.render_screen_type({
SESSION_ID: options.SESSION_ID,
$div,
$container: options.$container,
paramsP: options.paramsP,
close_modal: options.close_modal,
});
};
func.runtime.ui.render_multi_view_node = async function (options) {
const $div = options.$container;
func.runtime.ui.ensure_multi_view_state($div, options.nodeP, options.$container);
const done = async function (continuous_idx) {
await func.runtime.ui.ensure_container_attributes({
SESSION_ID: options.SESSION_ID,
is_skeleton: options.is_skeleton,
$root_container: options.$root_container,
nodeP: options.nodeP,
$container: options.$container,
paramsP: options.paramsP,
parent_infoP: options.parent_infoP,
jobNoP: options.jobNoP,
keyP: options.keyP,
parent_nodeP: options.parent_nodeP,
});
return await func.runtime.ui.render_screen_type({
SESSION_ID: options.SESSION_ID,
$div,
$container: options.$container,
paramsP: options.paramsP,
close_modal: options.close_modal,
});
};
if (func.runtime.ui.should_close_mobile_overlays(options.paramsP)) {
func.runtime.ui.close_all_modals();
}
const _ds = SESSION_OBJ[options.SESSION_ID].DS_GLB[options.paramsP.dsSessionP];
if (!_ds.data_feed || xu_isEmpty(_ds.data_feed.rows)) {
await func.events.validate(options.SESSION_ID, 'record_not_found', options.paramsP.dsSessionP);
return await done(null);
}
// B1 — no-op refresh suppression: when a datasource refresh produced rows identical to the
// pre-refresh snapshot AND this container already holds rendered rows, keep the existing DOM.
// Rebuilding tears down and re-creates the entire list (visible flick, multi-second freeze,
// an abandoned child datasource session per refresh) for zero data change. Field-level
// changes still flow through the normal update/diff path; a genuinely-changed row set (any
// _ROWID or value difference, or a fresh/empty container) renders exactly as before.
try {
const _prev_rows = _ds.__refresh_prev_rows;
delete _ds.__refresh_prev_rows;
if (Array.isArray(_prev_rows)) {
const _cur_rows = _ds.data_feed.rows || [];
const _existing_children = func.runtime.ui.get_children(options.$container);
const _container_node = func.runtime.ui.get_first_node(options.$container);
const _rows_unchanged =
_container_node &&
_container_node.isConnected &&
_existing_children.length > 0 &&
_prev_rows.length === _cur_rows.length &&
_cur_rows.every(function (row, row_index) {
const prev = _prev_rows[row_index];
return prev && prev._ROWID === row._ROWID && xu_isEqual(prev, row);
});
if (_rows_unchanged) {
return await done(null);
}
}
} catch (e) {}
const rows = _ds.data_feed.rows || [];
for (let row_index = 0; row_index < rows.length; row_index++) {
const val = rows[row_index];
const node = JSON.parse(JSON.stringify(options.nodeP));
_ds.currentRecordId = val._ROWID;
await options.iterate_child($div, node, { continuous_idx: null }, options.$root_container);
await func.runtime.ui.ensure_container_attributes({
SESSION_ID: options.SESSION_ID,
is_skeleton: options.is_skeleton,
$root_container: options.$root_container,
nodeP: options.nodeP,
$container: options.$container,
paramsP: options.paramsP,
parent_infoP: options.parent_infoP,
jobNoP: options.jobNoP,
keyP: options.keyP,
parent_nodeP: options.parent_nodeP,
});
}
return await done(null);
};
func.runtime = func.runtime || {};
func.runtime.ui = func.runtime.ui || {};
func.runtime.render = func.runtime.render || {};
// Browser-only panel rendering helpers live here so generic view rendering can stay focused.
func.runtime.ui.render_panel_node = async function (options) {
const $wrapper = document.createElement('div');
const $div = await func.runtime.ui.create_container({
SESSION_ID: options.SESSION_ID,
$root_container: options.$root_container,
nodeP: options.nodeP,
$container: options.$container,
paramsP: options.paramsP,
parent_infoP: options.parent_infoP,
jobNoP: options.jobNoP,
keyP: options.keyP,
treeP: options.treeP,
parent_nodeP: options.parent_nodeP,
prop: options.prop,
$appendToP: $wrapper,
attr_str: '',
});
let ret = await func.runtime.render.set_attributes_new({
SESSION_ID: options.SESSION_ID,
is_skeleton: options.is_skeleton,
$root_container: options.$root_container,
nodeP: options.nodeP,
$container: options.$container,
paramsP: options.paramsP,
parent_infoP: options.parent_infoP,
jobNoP: options.jobNoP,
keyP: options.keyP,
parent_nodeP: options.parent_nodeP,
$elm: $div.cloneNode(true),
is_init: true,
refreshed_ds: options.refreshed_ds,
});
if (ret.abort) {
const _tpl = document.createElement('template');
_tpl.appendChild($div);
return (ret.$new_div = _tpl);
}
let $ret_panel_div = ret.$new_div;
if (!func.runtime.ui.get_first_node($ret_panel_div)?.childElementCount && options.nodeP.children.length) {
$ret_panel_div = await func.runtime.render.render_ui_tree(
options.SESSION_ID,
options.$container,
options.nodeP.children[0],
options.parent_infoP,
options.paramsP,
options.jobNoP,
null,
0,
null,
options.nodeP,
null,
options.$root_container,
);
}
const container_data = func.runtime.ui.get_data(options.$container);
if (!container_data?.xuData?.paramsP) {
return options.$container;
}
const $div_items = func.runtime.ui.get_data($div)?.xuData?.node?.children;
await func.runtime.ui.panel_post_render_handler({
SESSION_ID: options.SESSION_ID,
$container: options.$container,
$wrapper: $ret_panel_div,
nodeP: options.nodeP,
$panel_div: $div,
jobNoP: options.jobNoP,
});
if (container_data?.xuData?.node) {
container_data.xuData.node.children = $div_items;
}
return options.$container;
};
func.runtime.ui.panel_post_render_handler = async function (options) {
try {
const container_data = func.runtime.ui.get_data(options.$container);
const wrapper_data = func.runtime.ui.get_data(options.$wrapper);
const parent_container_data = func.runtime.ui.get_data(func.runtime.ui.get_parent(options.$container));
const _container_ds = SESSION_OBJ[options.SESSION_ID].DS_GLB[container_data?.xuData?.paramsP?.dsSessionP];
const _ds = SESSION_OBJ[options.SESSION_ID].DS_GLB[wrapper_data?.xuData?.paramsP?.dsSessionP];
const panel_wrapper_id = container_data?.xuSkipPanelReplacement ? null : container_data?.xuPanelData?.xu_panel_xu_ui_id;
const find_old_panels_elements = function () {
if (!panel_wrapper_id) {
return func.runtime.ui._wrap_matches([]);
}
return func.runtime.ui.find_panel_wrapper_in_root(options.SESSION_ID, panel_wrapper_id);
};
const $old_panel_div = find_old_panels_elements();
const wrapper_children = func.runtime.ui.get_children(options.$wrapper);
const set_xuPanelData_to_the_new_rendered_items = function () {
container_data.xuPanelWrapper = { isWrapper: true, panelXuAttributes: { ...wrapper_data?.xuAttributes }, panelDivData: { ...wrapper_data } };
func.runtime.ui.set_attr(options.$container, 'xu-panel-wrapper-id', func.runtime.ui.get_attr(options.$wrapper, 'xu-ui-id'));
for (let child_index = 0; child_index < wrapper_children.length; child_index++) {
const val = wrapper_children[child_index];
const val_data = func.runtime.ui.get_data(val);
if (!val_data.xuPanelData) {
val_data.xuPanelData = {};
}
val_data.xuPanelData.parent_element_ui_id = $old_panel_div?.length ? parent_container_data?.xuData?.ui_id : container_data?.xuData?.ui_id;
val_data.xuPanelData.xu_panel_xu_ui_id = (options.nodeP.xu_tree_id || options.nodeP.id) + '-' + _container_ds?.currentRecordId;
val_data.xuPanelData.node = options.nodeP;
val_data.xuPanelData.$panel_div = options.$panel_div.cloneNode(true);
}
};
set_xuPanelData_to_the_new_rendered_items();
if ($old_panel_div?.length) {
func.runtime.ui.get_first_node($old_panel_div).after(...wrapper_children);
} else {
const existing_children = func.runtime.ui.get_children(options.$container);
const existing_children_by_elem_key = {};
for (let existing_index = 0; existing_index < existing_children.length; existing_index++) {
const elm = existing_children[existing_index];
const elem_key = func.runtime.ui.get_data(elm)?.xuData?.elem_key;
if (elem_key) {
existing_children_by_elem_key[elem_key] = elm;
}
}
for (let child_index = 0; child_index < wrapper_children.length; child_index++) {
const child = wrapper_children[child_index];
const elem_key = func.runtime.ui.get_data(child)?.xuData?.elem_key;
const existing_child = elem_key ? existing_children_by_elem_key[elem_key] : null;
if (existing_child) {
// Positional replacement: the re-rendered child must take the OLD child's slot.
// remove(old)+append(new) pushed the replacement to the container END, so a
// datasource multi-view list (e.g. the daf pager) rendered its current record last —
// the record id decides WHICH element to replace, never WHERE it goes.
func.runtime.ui.insert_before(child, existing_child);
func.runtime.ui.remove(existing_child);
} else {
// Order-aware insertion: in a datasource multi-view, the CURRENT record's panel renders
// out-of-band (its panel identity nodeId-currentRecordId already exists), so its element
// arrives AFTER its siblings; a blind append parks it at the END of the list (current
// record rendered last — e.g. the daf pager). Derive the slot from the datasource row
// order instead: the record id decides WHICH element this is, row order decides WHERE.
const child_record_id = func.runtime.ui.get_data(child)?.xuData?.recordid;
const order_rows = (function () {
if (!child_record_id) return null;
const containing = function (rows) {
return Array.isArray(rows) && rows.length > 1 && rows.some((row) => row._ROWID === child_record_id) ? rows : null;
};
return containing(_container_ds?.data_feed?.rows) || containing(_ds?.data_feed?.rows);
})();
const row_idx_of = function (record_id) {
if (!record_id || !order_rows) return -1;
for (let row_index = 0; row_index < order_rows.length; row_index++) {
if (order_rows[row_index]._ROWID === record_id) return row_index;
}
return -1;
};
const child_row_idx = row_idx_of(child_record_id);
let $insert_before_sibling = null;
if (child_row_idx >= 0) {
const current_children = func.runtime.ui.get_children(options.$container);
for (let sibling_index = 0; sibling_index < current_children.length; sibling_index++) {
const sibling_row_idx = row_idx_of(func.runtime.ui.get_data(current_children[sibling_index])?.xuData?.recordid);
if (sibling_row_idx > child_row_idx) {
$insert_before_sibling = current_children[sibling_index];
break;
}
}
}
if ($insert_before_sibling) {
func.runtime.ui.insert_before(child, $insert_before_sibling);
} else {
func.runtime.ui.append(options.$container, child);
}
}
}
}
if (!wrapper_data?.xuData?.dsSession) {
return options.jobNoP;
}
if ($old_panel_div?.length) {
if (parent_container_data?.xuData?.paramsP) {
parent_container_data.xuData.paramsP.dsSessionP = _ds.parentDataSourceNo;
}
} else {
if (container_data?.xuData?.paramsP) {
container_data.xuData.paramsP.dsSessionP = _ds.parentDataSourceNo;
}
}
if ($old_panel_div?.length) {
func.runtime.ui.remove($old_panel_div);
}
return options.jobNoP;
} catch (error) {
return options.jobNoP;
}
};
func.runtime = func.runtime || {};
func.runtime.ui = func.runtime.ui || {};
func.runtime.render = func.runtime.render || {};
// Browser-only screen-ready event flow lives here so loading lifecycle can stay focused.
func.runtime.ui.refresh_screen_ready_fields = async function (options) {
const current_record_id = options._ds?.currentRecordId;
const changed_fields = options._ds?.data_feed?.form_fields_changed?.[current_record_id];
if (!changed_fields) {
return false;
}
const fields_to_refresh = Object.keys(changed_fields);
const containerId = options._ds.containerId;
const container = func.runtime.ui.find_element_by_id(containerId);
if (container) {
container.dispatchEvent(new CustomEvent(containerId + '.refresh', { detail: ['init', fields_to_refresh] }));
}
if (options.$div_objP) {
await func.runtime.ui.refresh_xu_attributes({
SESSION_ID: options.SESSION_ID,
fields_arr: fields_to_refresh,
$elm_to_search: options.$div_objP,
dsSession_changed: options.paramsP.dsSessionP,
});
}
return true;
};
func.runtime.ui.collect_screen_ready_events = async function (options) {
const _prog = await func.utils.VIEWS_OBJ.get(options.SESSION_ID, options._ds.prog_id);
const viewEventExec_arr = [];
if (!_prog?.progEvents || xu_isEmpty(_prog.progEvents)) {
return viewEventExec_arr;
}
for await (const event_obj of _prog.progEvents) {
if (event_obj.data.type !== 'screen_ready' || xu_isEmpty(event_obj.workflow)) {
continue;
}
if (event_obj.data.condition) {
const res = await func.expression.get(options.SESSION_ID, event_obj.data.condition, options.paramsP.dsSessionP, 'condition', options.paramsP.rowIdP, null, null, null, null, event_obj);
if (!res.result) {
continue;
}
}
for await (const trigger_obj of event_obj.workflow) {
if (!trigger_obj.data.enabled) {
continue;
}
const expression = trigger_obj.props.condition || undefined;
if (expression) {
const expCond = await func.expression.get(options.SESSION_ID, expression, options.paramsP.dsSessionP, 'condition', options.paramsP.rowIdP, trigger_obj.data.type);
if (!expCond.result) {
continue;
}
}
if (!trigger_obj.data.action) {
func.utils.debug_report(options.SESSION_ID, 'collect_screen_ready_events', `Error initiating screen_ready prog: ${options._ds.viewSourceDesc} reason: missing action`, 'E');
break;
}
if (!glb.REFERENCE_LESS_FUNCTIONS.includes(trigger_obj.data.action) && !trigger_obj.data.name?.prog) {
func.utils.debug_report(options.SESSION_ID, 'collect_screen_ready_events', `Error initiating screen_ready prog: ${options._ds.viewSourceDesc} reason: missing reference`, 'E');
break;
}
viewEventExec_arr.push({
eventInfo: trigger_obj,
eventId: event_obj.id,
triggerId: trigger_obj.id,
expression,
});
}
}
return viewEventExec_arr;
};
func.runtime.ui.execute_screen_ready_events = async function (options) {
const _ds = SESSION_OBJ[options.SESSION_ID]?.DS_GLB?.[options.paramsP.dsSessionP];
if (!_ds) {
return;
}
// screen_ready events fire ONCE per screen instance, never again on a re-render/refresh.
// A screen_ready event that triggers a refresh (e.g. an `update` action, or a
// `raise_event` whose handler writes a field) re-renders the screen, which would
// re-fire screen_ready -> refresh -> screen_ready -> ... an infinite render loop (the
// panel "flicker": styled UI paints, then the next cycle wipes it). A refresh reuses
// the same datasource session so this flag persists; navigating to a screen creates a
// new dsSession, so screen_ready fires again there as expected.
if (_ds.screen_ready_fired) {
return;
}
_ds.screen_ready_fired = true;
try {
const viewEventExec_arr = await func.runtime.ui.collect_screen_ready_events({
SESSION_ID: options.SESSION_ID,
paramsP: options.paramsP,
_ds,
});
if (!viewEventExec_arr.length) {
return;
}
for await (const val of viewEventExec_arr) {
let cond = val.eventInfo.data.enabled;
if (val.expression) {
const expCond = await func.expression.get(options.SESSION_ID, val.expression, options.paramsP.dsSessionP, 'condition', options.paramsP.rowIdP);
cond = expCond.result;
}
if (!cond) {
continue;
}
await func.events.execute(
options.SESSION_ID,
null,
val.eventId,
val.triggerId,
val.eventInfo.data.action,
val.eventInfo.data.name,
null,
null,
null,
null,
val.eventInfo.data.action,
null,
options.paramsP.dsSessionP,
val.eventId,
options.sourceP + ' event',
true,
null,
null,
options.paramsP.dsSessionP,
null,
null,
val.eventInfo,
null,
null,
_ds.prog_id,
_ds.nodeId,
_ds.parentDataSourceNo,
options.$div,
);
await func.runtime.ui.refresh_screen_ready_fields({
SESSION_ID: options.SESSION_ID,
paramsP: options.paramsP,
_ds,
$div_objP: options.$div_objP,
});
}
} catch (error) {
console.error('[xuda-runtime] caught xuda_runtime.browser.screenready.events.js:152:', error);
}
};
func.runtime = func.runtime || {};
func.runtime.ui = func.runtime.ui || {};
func.runtime.render = func.runtime.render || {};
// Browser-only screen loading lifecycle lives here so screen-ready event flow can stay focused.
func.runtime.ui.screen_loading_done = async function (options) {
let retries = 0;
const interval = setInterval(() => {
const xu_ui_id = func.runtime.ui.get_attr(options.$div, 'xu-ui-id');
if (!func.runtime.ui.find_xu_ui_in_root(options.SESSION_ID, xu_ui_id).length && !func.runtime.ui.find_panel_wrapper_in_root(options.SESSION_ID, xu_ui_id).length && !xu_ui_id && xu_ui_id) {
retries++;
if (retries > 100) {
func.utils.report_issue(options.SESSION_ID, {
code: 'RUN_MSG_RND_050',
source: 'screen_loading_done',
message: 'deadlock detected for screen ready',
type: 'W',
details: {
prog_id: options.paramsP.prog_id,
screen_id: options.paramsP.screenId,
},
});
} else {
return options.$div;
}
}
clearInterval(interval);
func.runtime.ui.execute_screen_ready_events({
SESSION_ID: options.SESSION_ID,
paramsP: options.paramsP,
sourceP: options.paramsP.screenInfo.properties?.renderType,
$div: options.$div,
jobNoP: options.jobNoP,
});
const _session = SESSION_OBJ[options.SESSION_ID];
if (func.runtime.render.should_use_ssr_payload(options.SESSION_ID, options.paramsP)) {
const root_node = func.runtime.ui.get_root_node(options.SESSION_ID);
if (root_node) {
func.runtime.ui.set_attr(root_node, 'data-xuda-client-activation', _session.opt.app_client_activation || 'none');
func.runtime.ui.set_attr(root_node, 'data-xuda-ssr-status', _session.opt.app_client_activation === 'hydrate' ? 'hydrated' : 'taken-over');
}
func.runtime.render.mark_ssr_payload_consumed(options.SESSION_ID);
}
func.events.delete_job(options.SESSION_ID, options.jobNoP);
func.UI.utils.screen_blocker(false, options.paramsP.prog_id + (options.paramsP.sourceScreenP ? '_' + options.paramsP.sourceScreenP : ''));
if (_session.prog_id === options.paramsP.prog_id) {
_session.system_ready = true;
if (_session.engine_mode === 'live_preview' && STUDIO_PEER_CONN_SEND_METHOD) {
STUDIO_PEER_CONN_SEND_METHOD({
service: 'system_ready',
data: {},
id: STUDIO_PEER.id,
source: 'runtime',
session_id: options.SESSION_ID,
app_id: _session.app_id,
gtp_token: _session.gtp_token,
app_token: _session.app_token,
});
}
}
}, 100);
return options.$div;
};
func.runtime = func.runtime || {};
func.runtime.ui = func.runtime.ui || {};
func.runtime.render = func.runtime.render || {};
// Browser-only generic refresh scan helpers live here so xu-attribute refresh orchestration can stay focused.
// Convert jQuery objects, arrays, NodeLists, or single DOM nodes into a plain array of DOM nodes.
func.runtime.ui._to_node_array = func.runtime.ui._to_node_array || function (input) {
if (!input) {
return [];
}
if (typeof input?.toArray === 'function' && typeof input?.length === 'number' && !input?.nodeType) {
return input.toArray();
}
if (Array.isArray(input)) {
return input;
}
if (input.nodeType) {
return [input];
}
if (typeof input.length === 'number') {
const arr = [];
for (let i = 0; i < input.length; i++) {
if (input[i]) {
arr.push(input[i]);
}
}
return arr;
}
return [];
};
func.runtime.ui.ensure_refresh_dependency_state = function (SESSION_ID) {
const _session = SESSION_OBJ?.[SESSION_ID];
if (!_session) {
return null;
}
if (!_session.refresh_dependency_state) {
_session.refresh_dependency_state = {
dirty: true,
index: {},
elements_by_ui_id: {},
elements_by_nodeid: {},
panel_wrappers_by_id: {},
xu_for_dirty: true,
xu_for_index: {},
panel_wrappers_dirty: true,
panel_wrappers_cache: {},
panel_wrappers_active_cache: {},
runtime_elements_cache: null,
panel_wrapper_elements_cache: null,
};
}
if (typeof _session.refresh_dependency_state.dirty !== 'boolean') {
_session.refresh_dependency_state.dirty = true;
}
if (!_session.refresh_dependency_state.index) {
_session.refresh_dependency_state.index = {};
}
if (!_session.refresh_dependency_state.elements_by_ui_id) {
_session.refresh_dependency_state.elements_by_ui_id = {};
}
if (!_session.refresh_dependency_state.elements_by_nodeid) {
_session.refresh_dependency_state.elements_by_nodeid = {};
}
if (!_session.refresh_dependency_state.panel_wrappers_by_id) {
_session.refresh_dependency_state.panel_wrappers_by_id = {};
}
if (typeof _session.refresh_dependency_state.xu_for_dirty !== 'boolean') {
_session.refresh_dependency_state.xu_for_dirty = true;
}
if (!_session.refresh_dependency_state.xu_for_index) {
_session.refresh_dependency_state.xu_for_index = {};
}
if (typeof _session.refresh_dependency_state.panel_wrappers_dirty !== 'boolean') {
_session.refresh_dependency_state.panel_wrappers_dirty = true;
}
if (!_session.refresh_dependency_state.panel_wrappers_cache) {
_session.refresh_dependency_state.panel_wrappers_cache = {};
}
if (!_session.refresh_dependency_state.panel_wrappers_active_cache) {
_session.refresh_dependency_state.panel_wrappers_active_cache = {};
}
if (typeof _session.refresh_dependency_state.runtime_elements_cache === 'undefined') {
_session.refresh_dependency_state.runtime_elements_cache = null;
}
if (typeof _session.refresh_dependency_state.panel_wrapper_elements_cache === 'undefined') {
_session.refresh_dependency_state.panel_wrapper_elements_cache = null;
}
return _session.refresh_dependency_state;
};
func.runtime.ui.resolve_refresh_index_session_id = function (target, explicit_session_id) {
if (explicit_session_id && SESSION_OBJ?.[explicit_session_id]) {
return explicit_session_id;
}
const target_node = func.runtime.ui.get_first_node(target);
const session_from_data = func.runtime.ui.get_data(target_node)?.xuData?.SESSION_ID;
if (session_from_data) {
return session_from_data;
}
const session_ids = Object.keys(SESSION_OBJ || {});
if (session_ids.length === 1) {
return session_ids[0];
}
return null;
};
func.runtime.ui.mark_refresh_index_dirty = function (SESSION_ID) {
const state = func.runtime.ui.ensure_refresh_dependency_state(SESSION_ID);
if (!state) {
return false;
}
state.dirty = true;
state.xu_for_dirty = true;
state.panel_wrappers_dirty = true;
state.runtime_elements_cache = null;
state.panel_wrapper_elements_cache = null;
return true;
};
func.runtime.ui.mark_refresh_index_dirty_from_target = function (target, explicit_session_id) {
const session_id = func.runtime.ui.resolve_refresh_index_session_id(target, explicit_session_id);
if (!session_id) {
return false;
}
return func.runtime.ui.mark_refresh_index_dirty(session_id);
};
func.runtime.ui.remove_refresh_dependency_entry = function ($elm, attr_key) {
const session_id = func.runtime.ui.resolve_refresh_index_session_id($elm);
const selector_id = func.runtime.ui.get_attr($elm, 'xu-ui-id');
const elm_data = func.runtime.ui.get_data($elm);
const dependency_store = elm_data?.xuData?.refresh_dependency_by_attr;
if (!session_id || !selector_id || !dependency_store?.[attr_key]) {
return false;
}
const state = func.runtime.ui.ensure_refresh_dependency_state(session_id);
const old_fields = dependency_store[attr_key] || [];
if (!state || state.dirty) {
delete dependency_store[attr_key];
return true;
}
for (const field_id of old_fields) {
const field_index = state.index?.[field_id];
const selector_entry = field_index?.[selector_id];
if (!selector_entry) {
continue;
}
selector_entry.attributes.delete(attr_key);
if (!selector_entry.attributes.size) {
delete field_index[selector_id];
}
if (xu_isEmpty(field_index)) {
delete state.index[field_id];
}
}
delete dependency_store[attr_key];
return true;
};
func.runtime.ui.update_refresh_dependency_entry = function ($elm, attr_key, attr_val) {
const session_id = func.runtime.ui.resolve_refresh_index_session_id($elm);
const selector_id = func.runtime.ui.get_attr($elm, 'xu-ui-id');
const elm_data = func.runtime.ui.get_data($elm);
if (!session_id || !selector_id || !elm_data?.xuData) {
return false;
}
if (!elm_data.xuData.refresh_dependency_by_attr) {
elm_data.xuData.refresh_dependency_by_attr = {};
}
func.runtime.ui.remove_refresh_dependency_entry($elm, attr_key);
const state = func.runtime.ui.ensure_refresh_dependency_state(session_id);
const fields = [...func.runtime.ui.collect_refresh_attribute_fields(elm_data, attr_key, attr_val)];
elm_data.xuData.refresh_dependency_by_attr[attr_key] = fields;
if (!state || state.dirty || !fields.length) {
return !!fields.length;
}
for (const field_id of fields) {
if (!state.index[field_id]) {
state.index[field_id] = {};
}
if (!state.index[field_id][selector_id]) {
state.index[field_id][selector_id] = {
attributes: new Set(),
$elm,
};
}
state.index[field_id][selector_id].attributes.add(attr_key);
state.index[field_id][selector_id].$elm = $elm;
}
return true;
};
func.runtime.ui.prune_stale_refresh_dependencies = function ($elm, node_attributes) {
const elm_data = func.runtime.ui.get_data($elm);
const stored_attributes = elm_data?.xuAttributes;
if (!stored_attributes) {
return false;
}
let changed = false;
for (const key of Object.keys(stored_attributes)) {
if (key.substr(0, 3) !== 'xu-') {
continue;
}
if (Object.prototype.hasOwnProperty.call(node_attributes || {}, key)) {
continue;
}
func.runtime.ui.remove_refresh_dependency_entry($elm, key);
delete stored_attributes[key];
changed = true;
}
return changed;
};
func.runtime.ui.normalize_refresh_field_reference = function (field_ref) {
if (!field_ref) {
return [];
}
const normalized = new Set();
normalized.add(field_ref);
const base_field = field_ref.split(/[.[(]/)[0];
if (base_field) {
normalized.add(base_field);
}
const clean_ref = field_ref.replace(/^\$+/, '');
const data_root_match = clean_ref.match(/^(data|record|row|props|params|parameters|fields|state|ctx|context|this)\.([A-Za-z0-9_$.-]+)/);
if (data_root_match?.[2]) {
normalized.add(data_root_match[2]);
const data_root_base_field = data_root_match[2].split(/[.[(]/)[0];
if (data_root_base_field) {
normalized.add(data_root_base_field);
}
}
return [...normalized].filter(Boolean);
};
func.runtime.ui.extract_expression_refresh_fields = function (elm_data, expression_text, without_var, _visited) {
const fields = new Set();
if (!expression_text) {
return fields;
}
const add_field = function (field_ref) {
for (const normalized of func.runtime.ui.normalize_refresh_field_reference(field_ref)) {
fields.add(normalized);
}
};
const text = typeof expression_text === 'string' ? expression_text : JSON.stringify(expression_text);
if (!text) {
return fields;
}
if (without_var) {
const trimmed = text.trim();
const root_match = trimmed.match(/^([A-Za-z0-9_$.-]+)/);
if (root_match?.[1]) {
add_field(root_match[1]);
}
}
for (const match of text.matchAll(/@([A-Za-z0-9_$.-]+)/g)) {
add_field(match[1]);
}
const data_root_refs = /(^|[^A-Za-z0-9_$])(\$?(?:data|record|row|props|params|parameters|fields|state|ctx|context|this)\.([A-Za-z0-9_$.-]+))/g;
for (const match of text.matchAll(data_root_refs)) {
if (match?.[2]) {
add_field(match[2]);
}
if (match?.[3]) {
add_field(match[3]);
}
}
const bracket_root_refs = /(^|[^A-Za-z0-9_$])(\$?(?:data|record|row|props|params|parameters|fields|state|ctx|context|this))\s*\[\s*['"]([A-Za-z0-9_$.-]+)['"]\s*\]/g;
for (const match of text.matchAll(bracket_root_refs)) {
if (match?.[3]) {
add_field(match[3]);
}
}
const parameters_raw_obj = elm_data?.xuData?.paramsP?.parameters_raw_obj || {};
const parameter_keys = Object.keys(parameters_raw_obj);
const visited = _visited || new Set();
for (let index = 0; index < parameter_keys.length; index++) {
const param_key = parameter_keys[index];
if (visited.has(param_key)) {
continue;
}
const param_val = parameters_raw_obj[param_key];
if (!param_val?.includes?.('@')) {
continue;
}
const param_token = `${without_var ? '' : '@'}${param_key}`;
if (!text.includes(param_token)) {
continue;
}
visited.add(param_key);
const nested_fields = func.runtime.ui.extract_expression_refresh_fields(elm_data, param_val, false, visited);
nested_fields.forEach(function (field_id) {
add_field(field_id);
});
}
return fields;
};
func.runtime.ui.validate_refresh_parameter_reference = function (elm_data, exp, field_id, without_var) {
let expression_text;
if (typeof exp === 'string') {
expression_text = exp;
} else if (typeof exp === 'object') {
expression_text = JSON.stringify(exp);
}
if (!expression_text || !expression_text.includes('@')) {
return false;
}
if (xu_isEmpty(elm_data?.xuData?.paramsP?.parameters_raw_obj)) {
return false;
}
const parameters_raw_obj = elm_data.xuData.paramsP.parameters_raw_obj;
const parameter_keys = Object.keys(parameters_raw_obj);
for (let index = 0; index < parameter_keys.length; index++) {
const param_key = parameter_keys[index];
const param_val = parameters_raw_obj[param_key];
if (!param_val?.includes?.('@')) {
continue;
}
expression_text = expression_text.replaceAll((without_var ? '' : '@') + param_key, param_val);
}
return expression_text.includes((without_var ? '' : '@') + field_id);
};
func.runtime.ui.collect_refresh_attribute_fields = function (elm_data, key, val) {
const fields = new Set();
const add_fields = function (values) {
values?.forEach?.(function (field_id) {
fields.add(field_id);
});
};
if (typeof val !== 'string' && typeof val !== 'object') {
return fields;
}
if (key === 'xu-bind' || key === 'xu-for') {
add_fields(func.runtime.ui.extract_expression_refresh_fields(elm_data, val, true));
add_fields(func.runtime.ui.extract_expression_refresh_fields(elm_data, val, false));
return fields;
}
if (key.substr(0, 6) === 'xu-exp' && key.substr(6, 1) === ':') {
add_fields(func.runtime.ui.extract_expression_refresh_fields(elm_data, val, false));
return fields;
}
if (key.substr(0, 8) === 'xu-class') {
try {
const classes_obj = typeof val === 'string' ? JSON.parse(val) : (val || {});
const class_keys = Object.keys(classes_obj || {});
for (let index = 0; index < class_keys.length; index++) {
add_fields(func.runtime.ui.extract_expression_refresh_fields(elm_data, classes_obj[class_keys[index]], false));
}
} catch (error) {
console.warn('parse error:' + val);
}
return fields;
}
if (key === 'xu-ui-plugin') {
add_fields(func.runtime.ui.extract_expression_refresh_fields(elm_data, JSON.stringify(val), false));
}
return fields;
};
func.runtime.ui.collect_element_refresh_dependencies = function (elm_data) {
const dependency_store = elm_data?.xuData?.refresh_dependency_by_attr;
if (!xu_isEmpty(dependency_store)) {
const stored_dependencies = {};
const attr_keys = Object.keys(dependency_store || {});
for (let attr_index = 0; attr_index < attr_keys.length; attr_index++) {
const attr_key = attr_keys[attr_index];
const fields_arr = dependency_store[attr_key] || [];
for (let field_index = 0; field_index < fields_arr.length; field_index++) {
const field_id = fields_arr[field_index];
if (!stored_dependencies[field_id]) {
stored_dependencies[field_id] = new Set();
}
stored_dependencies[field_id].add(attr_key);
}
}
return stored_dependencies;
}
const dependencies = {};
const xu_attributes = elm_data?.xuAttributes || {};
const attr_keys = Object.keys(xu_attributes);
for (let attr_index = 0; attr_index < attr_keys.length; attr_index++) {
const key = attr_keys[attr_index];
const val = xu_attributes[key];
if (key.substr(0, 3) !== 'xu-') {
continue;
}
const fields = func.runtime.ui.collect_refresh_attribute_fields(elm_data, key, val);
fields.forEach(function (field_id) {
if (!dependencies[field_id]) {
dependencies[field_id] = new Set();
}
dependencies[field_id].add(key);
});
}
return dependencies;
};
func.runtime.ui.matches_refresh_search_root = function (elm, search_roots) {
if (!search_roots?.length) {
return true;
}
const elm_node = func.runtime.ui.get_first_node(elm);
if (!elm_node) {
return false;
}
for (let index = 0; index < search_roots.length; index++) {
const root_node = func.runtime.ui.get_first_node(search_roots[index]);
if (elm_node === root_node || (root_node && root_node.contains(elm_node))) {
return true;
}
}
return false;
};
func.runtime.ui.collect_refresh_attributes = function (elm_data, field_id) {
const attributes = [];
const xu_attributes = elm_data?.xuAttributes || {};
const attr_keys = Object.keys(xu_attributes);
for (let attr_index = 0; attr_index < attr_keys.length; attr_index++) {
const key = attr_keys[attr_index];
const val = xu_attributes[key];
if (typeof val !== 'string' && typeof val !== 'object') {
continue;
}
if (typeof val === 'string' && !val?.includes('@') && key !== 'xu-bind' && key !== 'xu-for') {
continue;
}
if (key.substr(0, 3) !== 'xu-') {
continue;
}
if (key === 'xu-bind' || key === 'xu-for') {
if (val?.includes?.(field_id) || func.runtime.ui.validate_refresh_parameter_reference(elm_data, val, field_id, true)) {
attributes.push(key);
}
continue;
}
if (key.substr(0, 6) === 'xu-exp' && key.substr(6, 1) === ':') {
if (val?.includes?.('@' + field_id) || func.runtime.ui.validate_refresh_parameter_reference(elm_data, val, field_id)) {
attributes.push(key);
}
continue;
}
if (key.substr(0, 8) === 'xu-class') {
try {
const classes_obj = typeof val === 'string' ? JSON.parse(val) : (val || {});
const class_keys = Object.keys(classes_obj || {});
for (let class_index = 0; class_index < class_keys.length; class_index++) {
const cond = classes_obj[class_keys[class_index]];
if (cond?.includes?.('@' + field_id) || func.runtime.ui.validate_refresh_parameter_reference(elm_data, cond, field_id)) {
attributes.push('xu-class');
break;
}
}
if (attributes.length) {
break;
}
} catch (error) {
console.warn('parse error:' + val);
}
continue;
}
if (key === 'xu-ui-plugin') {
const plugin_str = JSON.stringify(val);
if (plugin_str.includes('@' + field_id) || func.runtime.ui.validate_refresh_parameter_reference(elm_data, plugin_str, field_id)) {
attributes.push(key);
break;
}
}
}
return attributes;
};
func.runtime.ui.normalize_refresh_fields = function (fields_arr) {
return new Set((fields_arr || []).map(function (field_id) {
return field_id?.toString?.() || field_id;
}));
};
func.runtime.ui.collect_refresh_attributes_for_fields = function (elm_data, fields_arr, requested_fields) {
const attributes = new Set();
requested_fields = requested_fields || func.runtime.ui.normalize_refresh_fields(fields_arr);
if (!requested_fields.size) {
return [];
}
let dependencies = {};
const dependency_store = elm_data?.xuData?.refresh_dependency_by_attr || {};
const dependency_attr_keys = Object.keys(dependency_store);
for (let attr_index = 0; attr_index < dependency_attr_keys.length; attr_index++) {
const attr_key = dependency_attr_keys[attr_index];
const attr_fields = dependency_store[attr_key] || [];
for (let field_index = 0; field_index < attr_fields.length; field_index++) {
const field_id = attr_fields[field_index];
const normalized_field_id = field_id?.toString?.() || field_id;
if (!requested_fields.has(normalized_field_id)) {
continue;
}
if (!dependencies[normalized_field_id]) {
dependencies[normalized_field_id] = new Set();
}
dependencies[normalized_field_id].add(attr_key);
}
}
if (xu_isEmpty(dependencies)) {
dependencies = func.runtime.ui.collect_element_refresh_dependencies(elm_data);
}
requested_fields.forEach(function (field_id) {
const attr_set = dependencies[field_id];
attr_set?.forEach?.(function (attr_key) {
attributes.add(attr_key);
});
});
return [...attributes];
};
func.runtime.ui.get_refresh_index_node_ids = function (elm_data, $elm) {
const ids = new Set();
const xuData = elm_data?.xuData || {};
const add_id = function (value) {
if (typeof value === 'string' && value) {
ids.add(value);
}
};
add_id(xuData.nodeid);
add_id(xuData.node?.id);
add_id(xuData.node_org?.id);
add_id(func.runtime.ui.get_attr($elm, 'data-xuda-node-id'));
return [...ids];
};
func.runtime.ui.register_refresh_index_element = function (elements_by_ui_id, elements_by_nodeid, panel_wrappers_by_id, selector_id, elm_data, $elm) {
if (!selector_id || !elm_data?.xuData) {
return false;
}
elements_by_ui_id[selector_id] = $elm;
const panel_wrapper_id = func.runtime.ui.get_attr($elm, 'xu-panel-wrapper-id');
if (panel_wrapper_id) {
panel_wrappers_by_id[panel_wrapper_id] = $elm;
}
const node_ids = func.runtime.ui.get_refresh_index_node_ids(elm_data, $elm);
if (!node_ids.length) {
return true;
}
for (let node_index = 0; node_index < node_ids.length; node_index++) {
const node_id = node_ids[node_index];
if (!elements_by_nodeid[node_id]) {
elements_by_nodeid[node_id] = {};
}
elements_by_nodeid[node_id][selector_id] = $elm;
}
return true;
};
func.runtime.ui.find_refresh_elements_by_attr = function (root_nodes_input, attr_name, attr_value, first_only = false) {
const root_nodes = func.runtime.ui._to_node_array(root_nodes_input);
if (!root_nodes.length || !attr_name) {
return func.runtime.ui._wrap_matches([]);
}
const selector = typeof attr_value === 'undefined' ? `[${attr_name}]` : `[${attr_name}="${attr_value}"]`;
const elements = [];
for (let root_index = 0; root_index < root_nodes.length; root_index++) {
const root_node = root_nodes[root_index];
if (root_node?.matches?.(selector)) {
elements.push(root_node);
if (first_only) {
break;
}
}
if (first_only && elements.length) {
break;
}
if (first_only) {
const first_match = root_node?.querySelector?.(selector);
if (first_match) {
elements.push(first_match);
break;
}
continue;
}
const descendants = root_node?.querySelectorAll?.(selector) || [];
for (let index = 0; index < descendants.length; index++) {
elements.push(descendants[index]);
}
}
return func.runtime.ui._wrap_matches(elements);
};
func.runtime.ui.get_preferred_live_element = function (target) {
const elements = func.runtime.ui._to_node_array(target);
if (!elements.length) {
return null;
}
let best_node = null;
let best_score = -Infinity;
for (let index = 0; index < elements.length; index++) {
const node = elements[index];
if (!node) {
continue;
}
const node_data = func.runtime.ui.get_data(node);
let score = 0;
if (node.isConnected) {
score += 100;
}
if (!node_data?.xuData?.pending_to_delete) {
score += 50;
}
if (node.getClientRects?.().length) {
score += 25;
}
if (!node.hidden) {
score += 10;
}
if (score >= best_score) {
best_score = score;
best_node = node;
}
}
return best_node || elements[elements.length - 1] || null;
};
func.runtime.ui.get_refresh_indexed_element_by_ui_id = function (SESSION_ID, selector_id) {
const state = func.runtime.ui.ensure_refresh_dependency_state(SESSION_ID);
if (!state) {
return null;
}
if (state.dirty) {
func.runtime.ui.rebuild_refresh_dependency_index(SESSION_ID);
}
let elm = state.elements_by_ui_id?.[selector_id];
elm = func.runtime.ui.get_preferred_live_element(elm);
if (elm?.isConnected) {
state.elements_by_ui_id[selector_id] = elm;
return elm;
}
const root_nodes = func.runtime.ui.get_refresh_index_root(SESSION_ID);
elm = func.runtime.ui.get_preferred_live_element(func.runtime.ui.find_refresh_elements_by_attr(root_nodes, 'xu-ui-id', selector_id));
if (elm) {
state.elements_by_ui_id[selector_id] = elm;
state.runtime_elements_cache = null;
} else if (state.elements_by_ui_id?.[selector_id]) {
delete state.elements_by_ui_id[selector_id];
state.runtime_elements_cache = null;
}
return elm;
};
func.runtime.ui.get_refresh_indexed_elements_by_node_id = function (SESSION_ID, node_id) {
const state = func.runtime.ui.ensure_refresh_dependency_state(SESSION_ID);
if (!state) {
return func.runtime.ui._wrap_matches([]);
}
if (state.dirty) {
func.runtime.ui.rebuild_refresh_dependency_index(SESSION_ID);
}
const indexed_elements = state.elements_by_nodeid?.[node_id] || {};
const elements = [];
const selector_ids = Object.keys(indexed_elements);
for (let index = 0; index < selector_ids.length; index++) {
const selector_id = selector_ids[index];
let candidate = indexed_elements[selector_id];
if (!candidate?.isConnected) {
candidate = func.runtime.ui.get_refresh_indexed_element_by_ui_id(SESSION_ID, selector_id);
if (!candidate) {
delete indexed_elements[selector_id];
continue;
}
indexed_elements[selector_id] = candidate;
}
if (candidate) {
elements.push(candidate);
}
}
return func.runtime.ui._wrap_matches(elements);
};
func.runtime.ui.get_refresh_index_root = function (SESSION_ID) {
const root = func.runtime.ui.get_first_node(func.runtime.ui.get_root_element?.(SESSION_ID));
if (root) {
return [root];
}
return [document.body];
};
func.runtime.ui.get_refresh_index_elements = function (SESSION_ID, search_root_input) {
const root_nodes = func.runtime.ui._to_node_array(search_root_input);
if (!root_nodes.length) {
const default_roots = func.runtime.ui.get_refresh_index_root(SESSION_ID);
root_nodes.push(...default_roots);
}
const elements = [];
for (let root_index = 0; root_index < root_nodes.length; root_index++) {
const root_node = root_nodes[root_index];
if (root_node?.matches?.('[xu-ui-id]')) {
elements.push(root_node);
}
const descendants = root_node?.querySelectorAll?.('[xu-ui-id]') || [];
for (let element_index = 0; element_index < descendants.length; element_index++) {
elements.push(descendants[element_index]);
}
}
return func.runtime.ui._wrap_matches(elements);
};
func.runtime.ui.get_refresh_indexed_runtime_elements = function (SESSION_ID) {
const state = func.runtime.ui.ensure_refresh_dependency_state(SESSION_ID);
if (!state) {
return [];
}
if (state.dirty) {
func.runtime.ui.rebuild_refresh_dependency_index(SESSION_ID);
}
if (state.runtime_elements_cache !== null) {
return state.runtime_elements_cache;
}
const elements = [];
const selector_ids = Object.keys(state.elements_by_ui_id || {});
for (let index = 0; index < selector_ids.length; index++) {
const selector_id = selector_ids[index];
let candidate = state.elements_by_ui_id[selector_id];
if (!candidate?.isConnected) {
candidate = func.runtime.ui.get_refresh_indexed_element_by_ui_id(SESSION_ID, selector_id);
}
if (candidate) {
elements.push(candidate);
}
}
state.runtime_elements_cache = elements;
return state.runtime_elements_cache;
};
func.runtime.ui.get_refresh_indexed_panel_wrapper_by_id = function (SESSION_ID, wrapper_id) {
const state = func.runtime.ui.ensure_refresh_dependency_state(SESSION_ID);
if (!state) {
return null;
}
if (state.dirty) {
func.runtime.ui.rebuild_refresh_dependency_index(SESSION_ID);
}
let elm = state.panel_wrappers_by_id?.[wrapper_id];
elm = func.runtime.ui.get_preferred_live_element(elm);
if (elm?.isConnected) {
state.panel_wrappers_by_id[wrapper_id] = elm;
return elm;
}
const root_nodes = func.runtime.ui.get_refresh_index_root(SESSION_ID);
elm = func.runtime.ui.get_preferred_live_element(func.runtime.ui.find_refresh_elements_by_attr(root_nodes, 'xu-panel-wrapper-id', wrapper_id));
if (elm) {
state.panel_wrappers_by_id[wrapper_id] = elm;
state.panel_wrapper_elements_cache = null;
} else if (state.panel_wrappers_by_id?.[wrapper_id]) {
delete state.panel_wrappers_by_id[wrapper_id];
state.panel_wrapper_elements_cache = null;
}
return elm;
};
func.runtime.ui.get_refresh_indexed_panel_wrappers = function (SESSION_ID) {
const state = func.runtime.ui.ensure_refresh_dependency_state(SESSION_ID);
if (!state) {
return [];
}
if (state.dirty) {
func.runtime.ui.rebuild_refresh_dependency_index(SESSION_ID);
}
if (state.panel_wrapper_elements_cache !== null) {
return state.panel_wrapper_elements_cache;
}
const elements = [];
const wrapper_ids = Object.keys(state.panel_wrappers_by_id || {});
for (let index = 0; index < wrapper_ids.length; index++) {
const wrapper_id = wrapper_ids[index];
let candidate = state.panel_wrappers_by_id[wrapper_id];
if (!candidate?.isConnected) {
candidate = func.runtime.ui.get_refresh_indexed_panel_wrapper_by_id(SESSION_ID, wrapper_id);
}
if (candidate) {
elements.push(candidate);
}
}
state.panel_wrapper_elements_cache = elements;
return state.panel_wrapper_elements_cache;
};
func.runtime.ui.rebuild_refresh_dependency_index = function (SESSION_ID) {
const state = func.runtime.ui.ensure_refresh_dependency_state(SESSION_ID);
if (!state) {
return {};
}
const index = {};
const elements_by_ui_id = {};
const elements_by_nodeid = {};
const panel_wrappers_by_id = {};
const refresh_elements = func.runtime.ui.get_refresh_index_elements(SESSION_ID);
for (let element_index = 0; element_index < refresh_elements.length; element_index++) {
const elm = refresh_elements[element_index];
const elm_data = func.runtime.ui.get_data(elm);
const selector_id = func.runtime.ui.get_attr(elm, 'xu-ui-id');
if (!selector_id || !elm_data?.xuData || !elm_data?.xuAttributes) {
continue;
}
func.runtime.ui.register_refresh_index_element(elements_by_ui_id, elements_by_nodeid, panel_wrappers_by_id, selector_id, elm_data, elm);
const dependencies = func.runtime.ui.collect_element_refresh_dependencies(elm_data);
const field_ids = Object.keys(dependencies);
for (let field_index = 0; field_index < field_ids.length; field_index++) {
const field_id = field_ids[field_index];
const attrs = dependencies[field_id];
if (!index[field_id]) {
index[field_id] = {};
}
if (!index[field_id][selector_id]) {
index[field_id][selector_id] = {
attributes: new Set(),
$elm: elm,
};
}
for (const attr_key of attrs || []) {
index[field_id][selector_id].attributes.add(attr_key);
}
}
}
state.index = index;
state.elements_by_ui_id = elements_by_ui_id;
state.elements_by_nodeid = elements_by_nodeid;
state.panel_wrappers_by_id = panel_wrappers_by_id;
const runtime_elements = [];
const runtime_selector_ids = Object.keys(elements_by_ui_id);
for (let index = 0; index < runtime_selector_ids.length; index++) {
const element = elements_by_ui_id[runtime_selector_ids[index]];
if (element) {
runtime_elements.push(element);
}
}
const panel_wrapper_elements = [];
const panel_wrapper_ids = Object.keys(panel_wrappers_by_id);
for (let index = 0; index < panel_wrapper_ids.length; index++) {
const element = panel_wrappers_by_id[panel_wrapper_ids[index]];
if (element) {
panel_wrapper_elements.push(element);
}
}
state.runtime_elements_cache = runtime_elements;
state.panel_wrapper_elements_cache = panel_wrapper_elements;
state.dirty = false;
return index;
};
func.runtime.ui.collect_refresh_selectors_from_index = function (options) {
const perf_end = func.runtime?.perf?.start?.(options.SESSION_ID, 'collect_refresh_selectors_from_index');
func.runtime?.perf?.increment?.(options.SESSION_ID, 'refresh_selector_index_calls');
const state = func.runtime.ui.ensure_refresh_dependency_state(options.SESSION_ID);
if (!state) {
perf_end?.();
return {};
}
if (state.dirty) {
func.runtime.ui.rebuild_refresh_dependency_index(options.SESSION_ID);
}
const selectors = {};
const index = state.index || {};
const search_roots = func.runtime.ui._to_node_array(options.$elm_to_search);
const search_root = search_roots.length ? search_roots : null;
const requested_fields = [...func.runtime.ui.normalize_refresh_fields(options.fields_arr)];
for (let field_index = 0; field_index < requested_fields.length; field_index++) {
const val_field = requested_fields[field_index];
const indexed_elements = index[val_field] || {};
const selector_ids = Object.keys(indexed_elements);
for (let selector_index = 0; selector_index < selector_ids.length; selector_index++) {
const selector_id = selector_ids[selector_index];
const entry = indexed_elements[selector_id];
let elm = entry.$elm;
if (!elm?.isConnected) {
elm = func.runtime.ui.get_refresh_indexed_element_by_ui_id(options.SESSION_ID, selector_id);
entry.$elm = elm;
}
if (!elm) {
delete indexed_elements[selector_id];
continue;
}
const elm_data = func.runtime.ui.get_data(elm);
if (!elm_data?.xuData) {
delete indexed_elements[selector_id];
continue;
}
if (!func.runtime.ui.matches_refresh_search_root(elm, search_root)) {
continue;
}
if (typeof options.dsSession_changed !== 'undefined' && elm_data.xuData.paramsP && elm_data.xuData.paramsP.dsSessionP < options.dsSession_changed) {
continue;
}
if (!selectors[selector_id]) {
selectors[selector_id] = { attributes: new Set(), $elm: elm };
}
const attr_values = [...entry.attributes];
for (let attr_index = 0; attr_index < attr_values.length; attr_index++) {
selectors[selector_id].attributes.add(attr_values[attr_index]);
}
}
}
const selector_result_ids = Object.keys(selectors);
for (let selector_index = 0; selector_index < selector_result_ids.length; selector_index++) {
const selector_id = selector_result_ids[selector_index];
selectors[selector_id].attributes = [...selectors[selector_id].attributes];
}
func.runtime?.perf?.increment?.(options.SESSION_ID, 'refresh_selector_index_found', selector_result_ids.length);
perf_end?.();
return selectors;
};
func.runtime.ui.collect_refresh_selectors_by_scan = function (options) {
const perf_end = func.runtime?.perf?.start?.(options.SESSION_ID, 'collect_refresh_selectors_by_scan');
func.runtime?.perf?.increment?.(options.SESSION_ID, 'refresh_selector_scan_calls');
const selectors = {};
const search_roots = func.runtime.ui._to_node_array(options.$elm_to_search);
const search_root = search_roots.length ? search_roots : func.runtime.ui.get_refresh_index_root(options.SESSION_ID);
const requested_fields = func.runtime.ui.normalize_refresh_fields(options.fields_arr);
const refresh_elements = func.runtime.ui.get_refresh_index_elements(options.SESSION_ID, search_root);
for (let element_index = 0; element_index < refresh_elements.length; element_index++) {
const elm = refresh_elements[element_index];
const elm_data = func.runtime.ui.get_data(elm);
if (!elm_data.xuData) {
continue;
}
if (typeof options.dsSession_changed !== 'undefined' && elm_data.xuData.paramsP && elm_data.xuData.paramsP.dsSessionP < options.dsSession_changed) {
continue;
}
const attributes = func.runtime.ui.collect_refresh_attributes_for_fields(elm_data, options.fields_arr, requested_fields);
const selector_id = func.runtime.ui.get_attr(elm, 'xu-ui-id');
if (!attributes.length || !selector_id) {
continue;
}
if (!selectors[selector_id]) {
selectors[selector_id] = { attributes: new Set(), $elm: elm };
}
for (let attr_index = 0; attr_index < attributes.length; attr_index++) {
selectors[selector_id].attributes.add(attributes[attr_index]);
}
}
const selector_ids = Object.keys(selectors);
for (let selector_index = 0; selector_index < selector_ids.length; selector_index++) {
const selector_id = selector_ids[selector_index];
selectors[selector_id].attributes = [...selectors[selector_id].attributes];
}
func.runtime?.perf?.increment?.(options.SESSION_ID, 'refresh_selector_scan_found', selector_ids.length);
perf_end?.();
return selectors;
};
func.runtime.ui.merge_refresh_selector_sets = function (target, source) {
if (xu_isEmpty(source)) {
return target || {};
}
target = target || {};
const selector_ids = Object.keys(source || {});
for (let selector_index = 0; selector_index < selector_ids.length; selector_index++) {
const selector_id = selector_ids[selector_index];
const source_entry = source[selector_id];
if (!source_entry) {
continue;
}
if (!target[selector_id]) {
target[selector_id] = {
attributes: [],
$elm: source_entry.$elm,
};
}
if (!target[selector_id].$elm && source_entry.$elm) {
target[selector_id].$elm = source_entry.$elm;
}
const attributes = new Set(target[selector_id].attributes || []);
for (const attr of source_entry.attributes || []) {
attributes.add(attr);
}
target[selector_id].attributes = [...attributes];
}
return target;
};
func.runtime.ui.prog_ui_xu_render_dependency_cache = func.runtime.ui.prog_ui_xu_render_dependency_cache || new WeakMap();
func.runtime.ui.get_prog_ui_node_attribute_sources = function (item) {
const sources = [];
if (!xu_isEmpty(item?.attributes)) {
sources.push(item.attributes);
}
if (!xu_isEmpty(item?.attributes_raw_obj)) {
sources.push(item.attributes_raw_obj);
}
if (!xu_isEmpty(item?.attributes_raw)) {
sources.push(item.attributes_raw);
}
return sources;
};
func.runtime.ui.get_prog_ui_node_attribute_value = function (item, attr) {
const sources = func.runtime.ui.get_prog_ui_node_attribute_sources(item);
for (let source_index = 0; source_index < sources.length; source_index++) {
const source = sources[source_index];
if (typeof source?.[attr] !== 'undefined') {
return source[attr];
}
}
return undefined;
};
func.runtime.ui.get_prog_ui_node_xu_render_attr = function (item) {
const sources = func.runtime.ui.get_prog_ui_node_attribute_sources(item);
for (let source_index = 0; source_index < sources.length; source_index++) {
const source = sources[source_index];
if (typeof source?.['xu-exp:xu-render'] !== 'undefined') {
return 'xu-exp:xu-render';
}
if (typeof source?.['xu-render'] !== 'undefined') {
return 'xu-render';
}
}
return null;
};
func.runtime.ui.get_live_render_gate_elements_for_entry = function (options, entry) {
if (!entry?.render_gate_parent_node_id) {
return [];
}
const gate_elements = func.runtime.ui.get_refresh_indexed_elements_by_node_id(options.SESSION_ID, entry.render_gate_parent_node_id).toArray();
const panel_wrapper = entry.panel_wrapper_ui_id
? func.runtime.ui.get_refresh_indexed_element_by_ui_id(options.SESSION_ID, entry.panel_wrapper_ui_id)
: null;
const panel_wrapper_node = func.runtime.ui.get_first_node(panel_wrapper);
const search_roots = func.runtime.ui._to_node_array(options.$elm_to_search);
const search_root = search_roots.length ? search_roots : null;
return gate_elements.filter(function (gate_element) {
const gate_data = func.runtime.ui.get_data(gate_element);
if (!gate_element?.isConnected || !gate_data?.xuData || gate_data.xuData.pending_to_delete) {
return false;
}
if (panel_wrapper_node && gate_element !== panel_wrapper_node && !panel_wrapper_node.contains(gate_element)) {
return false;
}
if (entry.panel_ds_session != null) {
const gate_ds_session = gate_data?.xuData?.paramsP?.dsSessionP;
if (gate_ds_session != null && gate_ds_session !== entry.panel_ds_session) {
return false;
}
}
return func.runtime.ui.matches_refresh_search_root(gate_element, search_root);
});
};
func.runtime.ui.collect_prog_ui_xu_render_dependencies = function (progUi, index = {}, parent_node = null, render_gate_parent_node = null) {
if (!Array.isArray(progUi)) {
return index;
}
for (let item_index = 0; item_index < progUi.length; item_index++) {
const item = progUi[item_index];
const attribute_sources = func.runtime.ui.get_prog_ui_node_attribute_sources(item);
for (let source_index = 0; source_index < attribute_sources.length; source_index++) {
const attributes = attribute_sources[source_index];
const attribute_keys = Object.keys(attributes || {});
for (let attr_index = 0; attr_index < attribute_keys.length; attr_index++) {
const attr = attribute_keys[attr_index];
if (attr !== 'xu-exp:xu-render' && attr !== 'xu-render') {
continue;
}
const val = attributes[attr];
const fields = new Set();
func.runtime.ui.extract_expression_refresh_fields({}, val, true).forEach(function (field_id) {
fields.add(field_id);
});
func.runtime.ui.extract_expression_refresh_fields({}, val, false).forEach(function (field_id) {
fields.add(field_id);
});
for (const field_id of fields) {
if (!index[field_id]) {
index[field_id] = {};
}
index[field_id][`${item.id || ''}::${attr}`] = {
node_id: item.id,
attr,
attr_value: val,
key: item_index,
node: item,
parent_node,
parent_node_id: parent_node?.id || null,
render_gate_parent_node,
render_gate_parent_node_id: render_gate_parent_node?.id || null,
};
}
}
}
if (item?.children) {
const next_render_gate_parent_node = func.runtime.ui.get_prog_ui_node_xu_render_attr(item) ? item : render_gate_parent_node;
func.runtime.ui.collect_prog_ui_xu_render_dependencies(item.children, index, item, next_render_gate_parent_node);
}
}
return index;
};
func.runtime.ui.get_prog_ui_xu_render_dependencies = function (progUi) {
if (!Array.isArray(progUi)) {
return {};
}
let cached_dependencies = func.runtime.ui.prog_ui_xu_render_dependency_cache.get(progUi);
if (cached_dependencies) {
return cached_dependencies;
}
cached_dependencies = func.runtime.ui.collect_prog_ui_xu_render_dependencies(progUi, {});
func.runtime.ui.prog_ui_xu_render_dependency_cache.set(progUi, cached_dependencies);
return cached_dependencies;
};
func.runtime.ui.merge_prog_ui_xu_render_dependencies = function (target_index, source_index, context = null) {
if (xu_isEmpty(source_index)) {
return target_index || {};
}
target_index = target_index || {};
const field_ids = Object.keys(source_index);
for (let field_index = 0; field_index < field_ids.length; field_index++) {
const field_id = field_ids[field_index];
const entry_obj = source_index[field_id];
if (!target_index[field_id]) {
target_index[field_id] = {};
}
const entry_keys = Object.keys(entry_obj || {});
for (let entry_index = 0; entry_index < entry_keys.length; entry_index++) {
const entry_key = entry_keys[entry_index];
const entry = entry_obj[entry_key];
const contextual_entry = context
? {
...entry,
panel_wrapper_ui_id: context.panel_wrapper_ui_id || null,
panel_ds_session: context.panel_ds_session || null,
panel_prog_id: context.panel_prog_id || null,
}
: entry;
const contextual_entry_key = context?.panel_wrapper_ui_id ? `${context.panel_wrapper_ui_id}::${entry_key}` : entry_key;
contextual_entry.dependency_key = contextual_entry_key;
target_index[field_id][contextual_entry_key] = contextual_entry;
}
}
return target_index;
};
func.runtime.ui.get_cached_refresh_panel_wrappers = function (SESSION_ID, include_disabled = true) {
const state = func.runtime.ui.ensure_refresh_dependency_state(SESSION_ID);
if (!state || state.panel_wrappers_dirty) {
return {};
}
return include_disabled ? state.panel_wrappers_cache || {} : state.panel_wrappers_active_cache || {};
};
func.runtime.ui.should_debug_xu_render_field = function (options, field_id) {
return (options?.fields_arr || []).includes(field_id);
};
func.runtime.ui.debug_xu_render_field = function (options, label, payload) {
if (!func.runtime.ui.should_debug_xu_render_field(options, 'open_modal_v')) {
return;
}
try {
globalThis.__XUDA_RT_TRACE && console.log('[xuda-runtime] xu_render_open_modal_probe ' +
JSON.stringify({
label,
fields: options?.fields_arr || [],
...payload,
}),
);
} catch (e) {}
};
func.runtime.ui.collect_all_prog_ui_xu_render_dependencies = function (options, panels_obj) {
const index = {};
const $embed_container = func.runtime.ui.get_embed_screen_containers();
const root_prog_ui = func.runtime.ui.get_data($embed_container)?.xuData?.screenInfo?.progUi;
if (root_prog_ui) {
func.runtime.ui.merge_prog_ui_xu_render_dependencies(index, func.runtime.ui.get_prog_ui_xu_render_dependencies(root_prog_ui));
}
const resolved_panels_obj = panels_obj || func.runtime.ui.get_cached_refresh_panel_wrappers(options.SESSION_ID, true);
const panel_ids = Object.keys(resolved_panels_obj || {});
func.runtime.ui.debug_xu_render_field(options, 'collect_all_start', {
root_prog_ui: !!root_prog_ui,
panel_count: panel_ids.length,
panels: panel_ids.slice(0, 20).map(function (panel_id) {
const panel_val = resolved_panels_obj[panel_id];
return {
panel_id,
prog_id: panel_val?._ds?.prog_id || null,
dsSession: panel_val?._ds?.dsSession || null,
progUi: Array.isArray(panel_val?.progUi) ? panel_val.progUi.length : null,
};
}),
});
for (let panel_index = 0; panel_index < panel_ids.length; panel_index++) {
const panel_val = resolved_panels_obj[panel_ids[panel_index]];
if (!panel_val?.progUi) {
continue;
}
func.runtime.ui.merge_prog_ui_xu_render_dependencies(index, func.runtime.ui.get_prog_ui_xu_render_dependencies(panel_val.progUi), {
panel_wrapper_ui_id: panel_ids[panel_index],
panel_ds_session: panel_val?._ds?.dsSession || null,
panel_prog_id: panel_val?._ds?.prog_id || null,
});
}
func.runtime.ui.collect_live_node_org_xu_render_dependencies(options, index);
func.runtime.ui.debug_xu_render_field(options, 'collect_all_done', {
open_modal_keys: Object.keys(index.open_modal_v || {}),
dependency_fields: Object.keys(index).filter(function (field_id) {
return field_id === 'open_modal_v' || field_id.includes('modal');
}),
});
return index;
};
func.runtime.ui.collect_live_node_org_xu_render_dependencies = function (options, index = {}) {
if (!options?.SESSION_ID) {
return index;
}
const $root = func.UI?.worker?.get_session_root ? func.UI.worker.get_session_root(options.SESSION_ID) : func.runtime.ui.get_embed_screen_containers();
const live_elements = func.runtime.ui.get_refresh_index_elements
? func.runtime.ui.get_refresh_index_elements(options.SESSION_ID, $root).toArray()
: Array.from(func.runtime.ui.get_first_node($root)?.querySelectorAll?.('[xu-ui-id]') || []);
const seen_parent_nodes = new Set();
for (let live_index = 0; live_index < live_elements.length; live_index++) {
const live_element = live_elements[live_index];
const live_xu_data = func.runtime.ui.get_data(live_element)?.xuData;
const parent_ui_id = func.runtime.ui.get_attr(live_element, 'xu-ui-id');
const parent_node = live_xu_data?.node_org || live_xu_data?.node;
if (!parent_ui_id || !parent_node?.id || !Array.isArray(parent_node.children) || !parent_node.children.length) {
continue;
}
const seen_key = `${parent_ui_id}::${parent_node.id}`;
if (seen_parent_nodes.has(seen_key)) {
continue;
}
seen_parent_nodes.add(seen_key);
const local_index = {};
func.runtime.ui.collect_prog_ui_xu_render_dependencies(parent_node.children, local_index, parent_node);
const field_ids = Object.keys(local_index);
for (let field_index = 0; field_index < field_ids.length; field_index++) {
const field_id = field_ids[field_index];
const entry_obj = local_index[field_id] || {};
if (!index[field_id]) {
index[field_id] = {};
}
const entry_keys = Object.keys(entry_obj);
for (let entry_index = 0; entry_index < entry_keys.length; entry_index++) {
const entry_key = entry_keys[entry_index];
const entry = entry_obj[entry_key];
if (entry?.parent_node_id !== parent_node.id) {
continue;
}
const live_entry_key = `${parent_ui_id}::${entry_key}`;
index[field_id][live_entry_key] = {
...entry,
dependency_key: live_entry_key,
parent_element_ui_id: parent_ui_id,
parent_ds_session: live_xu_data?.paramsP?.dsSessionP || null,
parent_prog_id: live_xu_data?.paramsP?.prog_id || null,
};
}
}
}
return index;
};
func.runtime.ui.collect_refresh_xu_render_selectors_from_prog_ui = function (options) {
const selectors = {};
const dependencies = func.runtime.ui.collect_all_prog_ui_xu_render_dependencies(options);
const requested_fields = [...func.runtime.ui.normalize_refresh_fields(options.fields_arr)];
const search_roots = func.runtime.ui._to_node_array(options.$elm_to_search);
const search_root = search_roots.length ? search_roots : null;
for (let field_index = 0; field_index < requested_fields.length; field_index++) {
const field_id = requested_fields[field_index];
const field_entries = dependencies?.[field_id] || {};
const entry_keys = Object.keys(field_entries);
for (let entry_index = 0; entry_index < entry_keys.length; entry_index++) {
const entry = field_entries[entry_keys[entry_index]];
if (!entry?.node_id) {
continue;
}
const $elements = func.runtime.ui.get_refresh_indexed_elements_by_node_id(options.SESSION_ID, entry.node_id);
const element_nodes = func.runtime.ui._to_node_array($elements);
for (let element_index = 0; element_index < element_nodes.length; element_index++) {
const elm = element_nodes[element_index];
const elm_data = func.runtime.ui.get_data(elm);
const selector_id = func.runtime.ui.get_attr(elm, 'xu-ui-id');
if (!selector_id || !elm_data?.xuData || elm_data.xuData.pending_to_delete) {
continue;
}
if (!func.runtime.ui.matches_refresh_search_root(elm, search_root)) {
continue;
}
if (!selectors[selector_id]) {
selectors[selector_id] = { attributes: new Set(), $elm: elm };
}
selectors[selector_id].attributes.add(entry.attr);
}
}
}
const selector_ids = Object.keys(selectors);
for (let selector_index = 0; selector_index < selector_ids.length; selector_index++) {
const selector_id = selector_ids[selector_index];
selectors[selector_id].attributes = [...selectors[selector_id].attributes];
}
if (!xu_isEmpty(selectors)) {
try {
globalThis.__XUDA_RT_TRACE && console.log('[xuda-runtime] refresh_selector_prog_ui_xu_render ' +
JSON.stringify({
fields: options.fields_arr || [],
selectors: selector_ids,
}),
);
} catch (e) {}
func.runtime?.perf?.increment?.(options.SESSION_ID, 'refresh_selector_prog_ui_xu_render_used');
}
return selectors;
};
func.runtime.ui.collect_prog_ui_xu_render_entries_for_fields = function (options, panels_obj) {
const dependencies = func.runtime.ui.collect_all_prog_ui_xu_render_dependencies(options, panels_obj);
const requested_fields = [...func.runtime.ui.normalize_refresh_fields(options.fields_arr)];
const entries = {};
for (let field_index = 0; field_index < requested_fields.length; field_index++) {
const field_id = requested_fields[field_index];
const field_entries = dependencies?.[field_id] || {};
const entry_keys = Object.keys(field_entries);
for (let entry_index = 0; entry_index < entry_keys.length; entry_index++) {
const entry_key = entry_keys[entry_index];
const entry = field_entries[entry_key];
if (!entry?.node_id || !entry?.node) {
continue;
}
entries[entry.dependency_key || `${entry.panel_wrapper_ui_id || ''}::${entry.parent_element_ui_id || ''}::${entry.node_id}::${entry.attr}`] = entry;
}
}
func.runtime.ui.debug_xu_render_field(options, 'entries_for_fields', {
count: Object.keys(entries).length,
entries: Object.values(entries)
.slice(0, 20)
.map(function (entry) {
return {
node_id: entry?.node_id || null,
attr: entry?.attr || null,
parent_node_id: entry?.parent_node_id || null,
render_gate_parent_node_id: entry?.render_gate_parent_node_id || null,
parent_element_ui_id: entry?.parent_element_ui_id || null,
panel_wrapper_ui_id: entry?.panel_wrapper_ui_id || null,
panel_prog_id: entry?.panel_prog_id || null,
parent_prog_id: entry?.parent_prog_id || null,
attr_value: entry?.attr_value || null,
};
}),
});
return Object.values(entries);
};
func.runtime.ui.is_prog_ui_xu_render_overlay_node = function (entry) {
const root_node = entry?.node;
if (!root_node) {
return false;
}
const stack = [root_node];
let inspected = 0;
while (stack.length && inspected < 40) {
const node = stack.shift();
inspected++;
const attrs = {};
const sources = func.runtime.ui.get_prog_ui_node_attribute_sources(node);
for (let source_index = 0; source_index < sources.length; source_index++) {
Object.assign(attrs, sources[source_index] || {});
}
const class_value = `${attrs.class || attrs['xu-class'] || attrs['xu-exp:class'] || ''}`;
const style_value = `${attrs.style || attrs['xu-style'] || attrs['xu-exp:style'] || ''}`;
if (
attrs.role === 'dialog' ||
attrs['aria-modal'] === true ||
attrs['aria-modal'] === 'true' ||
/\bfixed\b/.test(class_value) ||
/position\s*:\s*fixed/i.test(style_value)
) {
return true;
}
const children = Array.isArray(node?.children) ? node.children : [];
for (let child_index = 0; child_index < children.length; child_index++) {
stack.push(children[child_index]);
}
}
return false;
};
func.runtime.ui.find_live_xu_render_parent_by_node_data = function (options, entry, root_node) {
if (!entry?.parent_node_id || !root_node) {
return [];
}
const candidates = [];
if (root_node.matches?.('[xu-ui-id]')) {
candidates.push(root_node);
}
const descendants = root_node.querySelectorAll?.('[xu-ui-id]') || [];
for (let index = 0; index < descendants.length; index++) {
candidates.push(descendants[index]);
}
return candidates.filter(function (candidate) {
const candidate_data = func.runtime.ui.get_data(candidate);
const ids = func.runtime.ui.get_refresh_index_node_ids(candidate_data, candidate);
if (!ids.includes(entry.parent_node_id)) {
return false;
}
if (entry.panel_ds_session != null) {
const ds_session = candidate_data?.xuData?.paramsP?.dsSessionP;
if (ds_session != null && ds_session !== entry.panel_ds_session) {
return false;
}
}
return candidate?.isConnected && candidate_data?.xuData;
});
};
func.runtime.ui.should_mount_xu_render_entry_at_screen_root = function (entry) {
return (
func.runtime.ui.is_prog_ui_xu_render_overlay_node(entry) &&
(entry?._used_parent_fallback === 'panel_session_element' ||
entry?._used_parent_fallback === 'panel_virtual_parent' ||
entry?._used_parent_fallback === 'embed_screen')
);
};
func.runtime.ui.get_xu_render_screen_root_mount = function () {
const roots = func.runtime.ui._to_node_array(func.runtime.ui.get_embed_screen_containers());
for (let root_index = 0; root_index < roots.length; root_index++) {
const root = roots[root_index];
if (root?.isConnected) {
return root;
}
}
return roots[0] || null;
};
func.runtime.ui.get_prog_ui_xu_render_parent_elements = function (options, entry) {
let parent_elements = [];
if (entry.parent_element_ui_id) {
const parent_element = func.runtime.ui.get_refresh_indexed_element_by_ui_id(options.SESSION_ID, entry.parent_element_ui_id);
parent_elements = func.runtime.ui._to_node_array(parent_element);
} else if (entry.parent_node_id) {
parent_elements = func.runtime.ui.get_refresh_indexed_elements_by_node_id(options.SESSION_ID, entry.parent_node_id).toArray();
if (entry.panel_wrapper_ui_id) {
const panel_wrapper = func.runtime.ui.get_refresh_indexed_element_by_ui_id(options.SESSION_ID, entry.panel_wrapper_ui_id);
const panel_wrapper_node = func.runtime.ui.get_first_node(panel_wrapper);
if (panel_wrapper_node) {
parent_elements = parent_elements.filter(function (parent_element) {
return parent_element === panel_wrapper_node || panel_wrapper_node.contains(parent_element);
});
}
}
} else if (entry.panel_wrapper_ui_id) {
const panel_wrapper = func.runtime.ui.get_refresh_indexed_element_by_ui_id(options.SESSION_ID, entry.panel_wrapper_ui_id);
parent_elements = func.runtime.ui._to_node_array(panel_wrapper);
} else {
parent_elements = func.runtime.ui._to_node_array(func.runtime.ui.get_embed_screen_containers());
}
// Fallback: the declared parent (parent_element_ui_id / parent_node_id) may
// itself be an unrendered conditional node, so the lookup above yields zero
// live mount points and the missing-render (e.g. an open-modal xu-render)
// silently bails. Recover a mount point so the node can render.
let used_parent_fallback = null;
if (!parent_elements.length && (entry.parent_element_ui_id || entry.parent_node_id)) {
if (entry.render_gate_parent_node_id) {
const gate_elements = func.runtime.ui.get_live_render_gate_elements_for_entry(options, entry);
if (!gate_elements.length) {
entry._used_parent_fallback = 'blocked_by_render_gate_parent';
func.runtime.ui.debug_xu_render_field(options, 'parent_gate_blocked_child_render', {
node_id: entry?.node_id || null,
parent_node_id: entry?.parent_node_id || null,
render_gate_parent_node_id: entry?.render_gate_parent_node_id || null,
panel_wrapper_ui_id: entry?.panel_wrapper_ui_id || null,
panel_ds_session: entry?.panel_ds_session || null,
});
return [];
}
}
const fallback_panel_wrapper = entry.panel_wrapper_ui_id
? func.runtime.ui.get_refresh_indexed_element_by_ui_id(options.SESSION_ID, entry.panel_wrapper_ui_id)
: null;
const fallback_panel_wrapper_node = func.runtime.ui.get_first_node(fallback_panel_wrapper);
if (fallback_panel_wrapper_node && entry.parent_node_id) {
const virtual_parent_matches = func.runtime.ui.find_live_xu_render_parent_by_node_data(options, entry, fallback_panel_wrapper_node);
if (virtual_parent_matches.length) {
parent_elements = virtual_parent_matches;
used_parent_fallback = 'panel_virtual_parent';
}
}
// Prefer a live element INSIDE the panel that runs on the panel's own
// datasource session. The panel WRAPPER element carries the OUTER session,
// so evaluating/rendering against it resolves the render expression (e.g.
// @open_modal_v) on the wrong datasource. querySelectorAll is document
// order, so the first session match is the panel content root.
if (fallback_panel_wrapper_node && entry.panel_ds_session != null) {
const session_match = Array.from(fallback_panel_wrapper_node.querySelectorAll('[xu-ui-id]')).find(function (el) {
const el_data = func.runtime.ui.get_data(el);
return el?.isConnected && el_data?.xuData && el_data.xuData.paramsP && el_data.xuData.paramsP.dsSessionP === entry.panel_ds_session;
});
if (session_match) {
parent_elements = [session_match];
used_parent_fallback = 'panel_session_element';
}
}
// Last resorts: the panel wrapper itself (outer session - may evaluate
// false, but still a mount point), then the embed screen root.
if (!parent_elements.length && fallback_panel_wrapper_node) {
parent_elements = func.runtime.ui._to_node_array(fallback_panel_wrapper);
if (parent_elements.length) {
used_parent_fallback = 'panel_wrapper';
}
}
if (!parent_elements.length) {
parent_elements = func.runtime.ui._to_node_array(func.runtime.ui.get_embed_screen_containers());
if (parent_elements.length) {
used_parent_fallback = 'embed_screen';
}
}
}
entry._used_parent_fallback = used_parent_fallback;
const search_roots = func.runtime.ui._to_node_array(options.$elm_to_search);
const search_root = search_roots.length ? search_roots : null;
const filtered_parent_elements = parent_elements.filter(function (parent_element) {
const parent_data = func.runtime.ui.get_data(parent_element);
return parent_element?.isConnected && parent_data?.xuData && func.runtime.ui.matches_refresh_search_root(parent_element, search_root);
});
func.runtime.ui.debug_xu_render_field(options, 'parent_elements', {
node_id: entry?.node_id || null,
parent_node_id: entry?.parent_node_id || null,
parent_element_ui_id: entry?.parent_element_ui_id || null,
panel_wrapper_ui_id: entry?.panel_wrapper_ui_id || null,
candidate_count: parent_elements.length,
filtered_count: filtered_parent_elements.length,
used_parent_fallback,
mount: func.runtime.ui.should_mount_xu_render_entry_at_screen_root(entry) ? 'screen_root' : 'logical_parent',
candidates: parent_elements.slice(0, 10).map(function (parent_element) {
const parent_data = func.runtime.ui.get_data(parent_element);
return {
tag: parent_element?.tagName || null,
ui_id: func.runtime.ui.get_attr(parent_element, 'xu-ui-id') || null,
node_id: parent_data?.xuData?.nodeid || parent_data?.xuData?.node?.id || null,
dsSession: parent_data?.xuData?.paramsP?.dsSessionP || null,
};
}),
});
return filtered_parent_elements;
};
func.runtime.ui.is_prog_ui_xu_render_live_under_parent = function (options, entry, parent_element) {
const live_elements = func.runtime.ui.get_refresh_indexed_elements_by_node_id(options.SESSION_ID, entry.node_id).toArray();
const parent_data = func.runtime.ui.get_data(parent_element);
const parent_params = parent_data?.xuData?.paramsP;
const root_mounted_overlay = func.runtime.ui.should_mount_xu_render_entry_at_screen_root(entry);
const matches_entry_scope = function (candidate_element, candidate_data) {
if (root_mounted_overlay) {
const candidate_params = candidate_data?.xuData?.paramsP;
if (
candidate_params?.dsSessionP === parent_params?.dsSessionP &&
candidate_data?.xuData?.recordid === parent_data?.xuData?.recordid
) {
return true;
}
}
return candidate_element.parentElement === parent_element || parent_element?.contains?.(candidate_element);
};
for (let live_index = 0; live_index < live_elements.length; live_index++) {
const live_element = live_elements[live_index];
const live_data = func.runtime.ui.get_data(live_element);
// pending_to_delete is NOT a liveness veto: it marks an element whose xu-render pass is
// already queued — that pass owns the node. Treating it as "missing" here raced the queued
// job and mounted a duplicate subtree (a second full copy of an open modal, painted over
// the first — the visible re-render/flick on open). The flag is transient (a 1s maintenance
// sweep clears it), so deferring recovery for a pending element can never wedge the node.
if (!live_element?.isConnected) {
continue;
}
if (matches_entry_scope(live_element, live_data)) {
return true;
}
}
// The refresh index keeps a single sticky slot per xu-ui-id, so content that was mounted by a
// pass which bypassed index registration (e.g. an earlier recovery render) stands connected in
// the DOM while being invisible to the index. The DOM is the primary truth: a connected element
// of this prog node inside its mount root means the node is NOT missing — recovering over it
// stacks another copy of the subtree.
const mount_root = root_mounted_overlay
? func.runtime.ui.get_first_node(func.runtime.ui.get_xu_render_screen_root_mount?.() || parent_element)
: parent_element;
const mount_children = mount_root?.children || [];
for (let child_index = 0; child_index < mount_children.length; child_index++) {
const child_element = mount_children[child_index];
if (!child_element?.isConnected || child_element.tagName === 'XURENDER') {
continue;
}
const child_data = func.runtime.ui.get_data(child_element);
const child_xu_data = child_data?.xuData;
const child_node_id = child_xu_data?.node?.id || child_xu_data?.node_org?.id || child_xu_data?.original_data_obj?.nodeP?.id;
if (child_node_id !== entry.node_id) {
continue;
}
if (matches_entry_scope(child_element, child_data)) {
return true;
}
}
return false;
};
func.runtime.ui.evaluate_prog_ui_xu_render_entry = async function (options, entry, parent_element) {
const parent_data = func.runtime.ui.get_data(parent_element);
const parent_xu_data = parent_data?.xuData;
const paramsP = parent_xu_data?.paramsP;
const attr_value =
typeof entry.attr_value !== 'undefined' ? entry.attr_value : func.runtime.ui.get_prog_ui_node_attribute_value(entry.node, entry.attr);
if (!paramsP || typeof attr_value === 'undefined') {
return false;
}
if (entry.attr === 'xu-exp:xu-render') {
const res = await func.expression.get(options.SESSION_ID, attr_value, paramsP.dsSessionP, 'UI Property EXP', parent_xu_data.recordid);
return await func.common.get_cast_val(options.SESSION_ID, 'refresh missing progUi xu-render', 'xu-render', 'bool', res.result);
}
if (typeof attr_value === 'string' && attr_value.includes('@')) {
const res = await func.expression.get(options.SESSION_ID, attr_value, paramsP.dsSessionP, 'UI Property EXP', parent_xu_data.recordid);
return await func.common.get_cast_val(options.SESSION_ID, 'refresh missing progUi xu-render', 'xu-render', 'bool', res.result);
}
return await func.common.get_cast_val(options.SESSION_ID, 'refresh missing progUi xu-render', 'xu-render', 'bool', attr_value);
};
func.runtime.ui.render_missing_prog_ui_xu_render_entry = async function (options, entry, parent_element, current_job) {
const parent_data = func.runtime.ui.get_data(parent_element);
const parent_xu_data = parent_data?.xuData;
const paramsP = parent_xu_data?.paramsP;
if (!paramsP) {
return current_job;
}
const should_render = await func.runtime.ui.evaluate_prog_ui_xu_render_entry(options, entry, parent_element);
func.runtime.ui.debug_xu_render_field(options, 'render_missing_evaluated', {
node_id: entry?.node_id || null,
parent_node_id: entry?.parent_node_id || null,
parent_element_ui_id: entry?.parent_element_ui_id || null,
panel_wrapper_ui_id: entry?.panel_wrapper_ui_id || null,
used_parent_fallback: entry?._used_parent_fallback || null,
mount: func.runtime.ui.should_mount_xu_render_entry_at_screen_root(entry) ? 'screen_root' : 'logical_parent',
should_render,
});
if (!should_render) {
return current_job;
}
try {
globalThis.__XUDA_RT_TRACE && console.log('[xuda-runtime] refresh_missing_prog_ui_xu_render ' +
JSON.stringify({
fields: options.fields_arr || [],
node_id: entry.node_id,
parent_node_id: entry.parent_node_id || null,
key: entry.key,
mount: func.runtime.ui.should_mount_xu_render_entry_at_screen_root(entry) ? 'screen_root' : 'logical_parent',
}),
);
} catch (e) {}
const node_to_render = structuredClone(entry.node);
if (typeof entry.attr_value !== 'undefined' && typeof node_to_render?.attributes?.[entry.attr] === 'undefined') {
node_to_render.attributes = node_to_render.attributes || {};
node_to_render.attributes[entry.attr] = entry.attr_value;
}
let render_parent_element = parent_element;
if (func.runtime.ui.should_mount_xu_render_entry_at_screen_root(entry)) {
render_parent_element = func.runtime.ui.get_xu_render_screen_root_mount() || parent_element;
}
const new_$div = await func.runtime.render.render_ui_tree(
options.SESSION_ID,
func.runtime.ui._wrap_matches([render_parent_element]),
node_to_render,
parent_xu_data.iterate_info ? { iterate_info: parent_xu_data.iterate_info } : null,
paramsP,
current_job,
null,
entry.key,
null,
entry.parent_node || parent_xu_data.node_org || parent_xu_data.node || null,
null,
parent_xu_data.$root_container || func.runtime.ui.get_embed_screen_containers(),
);
// Recovery output must be lifecycle-equivalent to job-rendered content. The xu-render job
// path stamps the swapped-in content with the gate bookkeeping (xuAttributes carrying the
// xu-exp:xu-render expression, node identity, paramsP) — that stamping is what registers the
// element in the field-dependency index. Without it a recovered element is a lifecycle
// orphan: the gate field's next change reaches nobody (modal that can never close) and the
// index/liveness checks can't see the copy (another recovery stacks a duplicate over it).
const new_data = func.runtime.ui.get_data(new_$div);
if (new_data) {
new_data.xuData = new_data.xuData || {};
if (!new_data.xuData.node) {
new_data.xuData.node = node_to_render;
}
if (!new_data.xuData.node_org) {
new_data.xuData.node_org = node_to_render;
}
if (!new_data.xuData.ui_type) {
new_data.xuData.ui_type = node_to_render?.tagName || 'div';
}
if (!new_data.xuData.debug_info) {
new_data.xuData.debug_info = {};
}
if (!new_data.xuData.paramsP) {
new_data.xuData.paramsP = paramsP;
}
if (typeof new_data.xuData.recordid === 'undefined' && typeof parent_xu_data.recordid !== 'undefined') {
new_data.xuData.recordid = parent_xu_data.recordid;
}
if (xu_isEmpty(new_data.xuAttributes)) {
new_data.xuAttributes = { ...(node_to_render?.attributes || {}) };
}
}
// Identity contract at the recovery mount: the element just rendered is now the single owner
// of this node instance. Any copy an earlier race left behind (same xu-ui-id, connected)
// would otherwise stay stacked under the new one — one extra full copy per recovery pass.
const new_ui_id = func.runtime.ui.get_attr?.(new_$div, 'xu-ui-id');
if (new_ui_id && func.runtime.ui.reconcile_xu_ui_id_duplicates) {
func.runtime.ui.reconcile_xu_ui_id_duplicates(options.SESSION_ID, new_ui_id, new_$div);
}
func.runtime.ui.mark_refresh_index_dirty?.(options.SESSION_ID);
func.runtime?.perf?.increment?.(options.SESSION_ID, 'refresh_missing_prog_ui_xu_render_used');
return current_job;
};
func.runtime.ui.refresh_missing_prog_ui_xu_render_nodes = async function (options, current_job) {
let panels_obj = null;
try {
const $embed_container = func.runtime.ui.get_embed_screen_containers();
panels_obj = await func.UI.utils.get_panels_wrapper_from_dom(options.SESSION_ID, $embed_container, true);
} catch (error) {
func.runtime.ui.debug_xu_render_field(options, 'panel_collection_error', {
error: error?.message || String(error),
});
panels_obj = func.runtime.ui.get_cached_refresh_panel_wrappers(options.SESSION_ID, true);
}
func.runtime.ui.debug_xu_render_field(options, 'refresh_missing_start', {
panel_count: Object.keys(panels_obj || {}).length,
});
const entries = func.runtime.ui.collect_prog_ui_xu_render_entries_for_fields(options, panels_obj);
const rendered_keys = new Set();
for (let entry_index = 0; entry_index < entries.length; entry_index++) {
const entry = entries[entry_index];
const parent_elements = func.runtime.ui.get_prog_ui_xu_render_parent_elements(options, entry);
for (let parent_index = 0; parent_index < parent_elements.length; parent_index++) {
const parent_element = parent_elements[parent_index];
const parent_ui_id = func.runtime.ui.get_attr(parent_element, 'xu-ui-id') || 'root';
const render_key = `${parent_ui_id}::${entry.node_id}`;
if (rendered_keys.has(render_key)) {
continue;
}
if (func.runtime.ui.is_prog_ui_xu_render_live_under_parent(options, entry, parent_element)) {
continue;
}
current_job = await func.runtime.ui.render_missing_prog_ui_xu_render_entry(options, entry, parent_element, current_job);
rendered_keys.add(render_key);
}
}
return current_job;
};
func.runtime.ui.collect_refresh_selectors = function (options) {
let selectors = func.runtime.ui.collect_refresh_selectors_from_index(options);
if (!xu_isEmpty(selectors)) {
func.runtime?.perf?.increment?.(options.SESSION_ID, 'refresh_selector_index_used');
} else {
func.runtime?.perf?.increment?.(options.SESSION_ID, 'refresh_selector_scan_used');
selectors = func.runtime.ui.collect_refresh_selectors_by_scan(options);
}
if (xu_isEmpty(selectors) && typeof options.dsSession_changed !== 'undefined') {
const relaxed_selectors = func.runtime.ui.collect_refresh_selectors_by_scan({
...options,
dsSession_changed: undefined,
});
const render_selectors = {};
for (const [selector_id, selector_entry] of Object.entries(relaxed_selectors || {})) {
const render_attrs = (selector_entry.attributes || []).filter(function (attr) {
return attr === 'xu-exp:xu-render' || attr === 'xu-render';
});
if (!render_attrs.length) continue;
render_selectors[selector_id] = {
...selector_entry,
attributes: render_attrs,
};
}
if (!xu_isEmpty(render_selectors)) {
try {
globalThis.__XUDA_RT_TRACE && console.log('[xuda-runtime] refresh_selector_relaxed_xu_render ' +
JSON.stringify({
fields: options.fields_arr || [],
dsSession_changed: options.dsSession_changed,
selectors: Object.keys(render_selectors),
}),
);
} catch (e) {}
func.runtime?.perf?.increment?.(options.SESSION_ID, 'refresh_selector_relaxed_xu_render_used');
selectors = func.runtime.ui.merge_refresh_selector_sets(selectors, render_selectors);
}
}
const prog_ui_render_selectors = func.runtime.ui.collect_refresh_xu_render_selectors_from_prog_ui(options);
selectors = func.runtime.ui.merge_refresh_selector_sets(selectors, prog_ui_render_selectors);
return selectors;
};
func.runtime.ui.build_refresh_job_obj = function (options, elem_key, elem_val, extra = {}) {
const elm_data = func.runtime.ui.get_data(elem_val.$elm);
return {
ui_type: elm_data?.xuData?.ui_type,
SESSION_ID: options.SESSION_ID,
fields_arr: options.fields_arr,
elem_key,
node_id: elm_data?.xuData?.nodeid,
key: elm_data?.xuData?.key,
key_path: elm_data?.xuData?.key_path,
recordid: elm_data?.xuData?.recordid,
parent_element_ui_id: elm_data?.xuData?.parent_element_ui_id,
prog_id: elm_data?.xuData?.paramsP?.prog_id,
elem_val: {
attributes: [...(elem_val.attributes || [])],
},
...extra,
};
};
func.runtime.ui.queue_refresh_execute_job = async function (options, elem_key, elem_val, type, current_job) {
const elm_data = func.runtime.ui.get_data(elem_val.$elm);
if (!elm_data?.xuData) {
return current_job;
}
try {
const obj = func.runtime.ui.build_refresh_job_obj(options, elem_key, elem_val);
const next_job = await func.UI.worker.add_to_queue(options.SESSION_ID, 'gui event', type, obj, current_job, elem_val.$elm);
return next_job;
} catch (error) {
console.error('[xuda-runtime] caught xuda_runtime.browser.refresh.scan.js:1016:', error);
return current_job;
}
};
func.runtime.ui.queue_refresh_render_job = async function (options, elem_key, elem_val, attr_value, current_job) {
const elm_data = func.runtime.ui.get_data(elem_val?.$elm);
if (!elm_data?.xuData?.ui_type) {
return current_job;
}
const obj = func.runtime.ui.build_refresh_job_obj(options, elem_key, elem_val, { attr_value });
const next_job = await func.UI.worker.add_to_queue(
options.SESSION_ID,
'gui event',
'execute_xu_render_attributes',
obj,
current_job,
elem_val.$elm,
elm_data.xuData.paramsP.dsSessionP,
);
if (glb.DEBUG_MODE) {
console.info('execute_xu_render_attributes', obj);
}
return next_job;
};
func.runtime.ui.mark_refresh_pending_delete = function (elm_input) {
const elm = func.runtime.ui.get_first_node(elm_input);
const session_id = func.runtime.ui.resolve_refresh_index_session_id ? func.runtime.ui.resolve_refresh_index_session_id(elm) : func.runtime.ui.get_data(elm)?.xuData?.SESSION_ID;
const descendants = elm?.querySelectorAll?.('[xu-ui-id]') || [];
for (let index = 0; index < descendants.length; index++) {
const val = descendants[index];
const element_data = func.runtime.ui.get_data(val);
if (element_data?.xuData) {
element_data.xuData.pending_to_delete = true;
if (func.UI?.worker?.mark_pending_delete_element && session_id) {
func.UI.worker.mark_pending_delete_element(session_id, val);
}
}
}
if (func.UI?.worker?.mark_pending_delete_session && session_id) {
func.UI.worker.mark_pending_delete_session(session_id);
}
return elm_input;
};
func.runtime = func.runtime || {};
func.runtime.ui = func.runtime.ui || {};
func.runtime.render = func.runtime.render || {};
// Browser-only xu-for refresh helpers live here so generic refresh scanning can stay focused.
func.runtime.ui.prog_ui_xu_for_dependency_cache = func.runtime.ui.prog_ui_xu_for_dependency_cache || new WeakMap();
func.runtime.ui.prog_ui_xu_for_fields_cache = func.runtime.ui.prog_ui_xu_for_fields_cache || new Map();
func.runtime.ui.get_refresh_parent_element_ui_id = function ($elm) {
const elm_data = func.runtime.ui.get_data($elm);
if (elm_data?.xuPanelData) {
return elm_data.xuPanelData.parent_element_ui_id;
}
return elm_data?.xuData?.parent_element_ui_id;
};
func.runtime.ui.resolve_refresh_xu_for_item_id = function ($elm) {
const elm_data = func.runtime.ui.get_data($elm);
if (elm_data?.xuPanelData) {
return elm_data.xuPanelData.node.id;
}
return elm_data?.xuData?.nodeid;
};
func.runtime.ui.build_refresh_element_value = function ($elm) {
const elem_val = {
attributes: Object.keys(func.runtime.ui.get_data($elm)?.xuAttributes || {}),
$elm,
};
return elem_val;
};
func.runtime.ui.build_xu_for_refresh_job_obj = function (options, elem_key, $elm, xu_for_item_id) {
const elm_data = func.runtime.ui.get_data($elm);
return {
ui_type: elm_data.xuData.ui_type,
SESSION_ID: options.SESSION_ID,
fields_arr: options.fields_arr,
elem_key,
elem_val: {},
xu_for_item_id,
};
};
func.runtime.ui.queue_xu_for_refresh = async function (options, $elm, xu_for_item_id, current_job, debug_label, debug_context) {
const elm_data = func.runtime.ui.get_data($elm);
if (options.avoid_xu_for_refresh || !$elm?.length || !elm_data?.xuData) {
return current_job;
}
const elem_key = func.runtime.ui.get_attr($elm, 'xu-ui-id');
const obj = func.runtime.ui.build_xu_for_refresh_job_obj(options, elem_key, $elm, xu_for_item_id);
await func.UI.worker.add_to_queue(options.SESSION_ID, 'gui event', 'execute_xu_for', obj, current_job, $elm, elm_data.xuData.paramsP.dsSessionP);
if (glb.DEBUG_MODE) {
console.info(debug_label || 'execute_xu_for', obj, debug_context);
}
return current_job;
};
func.runtime.ui.collect_prog_ui_xu_for_fields = function (attr_val) {
const cache_key = typeof attr_val === 'string' ? `str:${attr_val}` : `obj:${JSON.stringify(attr_val || {})}`;
const cached_fields = func.runtime.ui.prog_ui_xu_for_fields_cache.get(cache_key);
if (cached_fields) {
return cached_fields;
}
const fields = new Set();
const add_fields = function (values) {
values?.forEach?.(function (field_id) {
fields.add(field_id);
});
};
add_fields(func.runtime.ui.extract_expression_refresh_fields({}, attr_val, true));
add_fields(func.runtime.ui.extract_expression_refresh_fields({}, attr_val, false));
const result = [...fields].filter(Boolean);
func.runtime.ui.prog_ui_xu_for_fields_cache.set(cache_key, result);
return result;
};
func.runtime.ui.add_prog_ui_xu_for_dependency = function (index, field_id, entry) {
if (!field_id) {
return;
}
if (!index[field_id]) {
index[field_id] = {};
}
const entry_key = `${entry.parent_node_id || ''}::${entry.xu_for_item_id}`;
index[field_id][entry_key] = entry;
};
func.runtime.ui.collect_prog_ui_xu_for_dependencies = function (progUi, index = {}, parent_node_id) {
if (!Array.isArray(progUi)) {
return index;
}
for (const item of progUi) {
if (!xu_isEmpty(item?.attributes)) {
const attribute_keys = Object.keys(item.attributes);
for (let attr_index = 0; attr_index < attribute_keys.length; attr_index++) {
const attr = attribute_keys[attr_index];
const val = item.attributes[attr];
if (attr !== 'xu-exp:xu-for' && attr !== 'xu-for') {
continue;
}
const fields = func.runtime.ui.collect_prog_ui_xu_for_fields(val);
for (const field_id of fields) {
func.runtime.ui.add_prog_ui_xu_for_dependency(index, field_id, {
parent_node_id,
xu_for_item_id: item.id,
});
}
}
}
if (item?.children) {
func.runtime.ui.collect_prog_ui_xu_for_dependencies(item.children, index, item.id);
}
}
return index;
};
func.runtime.ui.get_prog_ui_xu_for_dependencies = function (progUi) {
if (!Array.isArray(progUi)) {
return {};
}
let cached_dependencies = func.runtime.ui.prog_ui_xu_for_dependency_cache.get(progUi);
if (cached_dependencies) {
return cached_dependencies;
}
cached_dependencies = func.runtime.ui.collect_prog_ui_xu_for_dependencies(progUi, {});
func.runtime.ui.prog_ui_xu_for_dependency_cache.set(progUi, cached_dependencies);
return cached_dependencies;
};
func.runtime.ui.merge_prog_ui_xu_for_dependencies = function (target_index, source_index) {
if (xu_isEmpty(source_index)) {
return target_index;
}
const field_ids = Object.keys(source_index);
for (let field_index = 0; field_index < field_ids.length; field_index++) {
const field_id = field_ids[field_index];
const entry_obj = source_index[field_id];
if (!target_index[field_id]) {
target_index[field_id] = {};
}
const entry_keys = Object.keys(entry_obj || {});
for (let entry_index = 0; entry_index < entry_keys.length; entry_index++) {
const entry_key = entry_keys[entry_index];
const entry = entry_obj[entry_key];
target_index[field_id][entry_key] = entry;
}
}
return target_index;
};
func.runtime.ui.rebuild_refresh_xu_for_index = async function (SESSION_ID, panels_obj, $xu_embed_container) {
const state = func.runtime.ui.ensure_refresh_dependency_state(SESSION_ID);
if (!state) {
return {};
}
const index = {};
const $embed_container = $xu_embed_container?.length ? $xu_embed_container : func.runtime.ui.get_embed_screen_containers();
const root_prog_ui = func.runtime.ui.get_data($embed_container)?.xuData?.screenInfo?.progUi;
if (root_prog_ui) {
func.runtime.ui.merge_prog_ui_xu_for_dependencies(index, func.runtime.ui.get_prog_ui_xu_for_dependencies(root_prog_ui));
}
const resolved_panels_obj = panels_obj || (await func.UI.utils.get_panels_wrapper_from_dom(SESSION_ID, $embed_container, true));
for (const panel_val of Object.values(resolved_panels_obj || {})) {
func.runtime.ui.merge_prog_ui_xu_for_dependencies(index, func.runtime.ui.get_prog_ui_xu_for_dependencies(panel_val?.progUi));
}
state.xu_for_index = index;
state.xu_for_dirty = false;
return index;
};
func.runtime.ui.collect_refresh_xu_for_entries = async function (options, panels_obj, $xu_embed_container) {
const state = func.runtime.ui.ensure_refresh_dependency_state(options.SESSION_ID);
if (!state) {
return {
entries: [],
missing_fields: [...(options.fields_arr || [])],
panels_obj: panels_obj || {},
};
}
let resolved_panels_obj = panels_obj;
if (state.xu_for_dirty) {
if (!resolved_panels_obj) {
const $embed_container = $xu_embed_container?.length ? $xu_embed_container : func.runtime.ui.get_embed_screen_containers();
resolved_panels_obj = await func.UI.utils.get_panels_wrapper_from_dom(options.SESSION_ID, $embed_container, true);
}
await func.runtime.ui.rebuild_refresh_xu_for_index(options.SESSION_ID, resolved_panels_obj, $xu_embed_container);
}
const entries = {};
const missing_fields = [];
const fields_arr = options.fields_arr || [];
for (let field_index = 0; field_index < fields_arr.length; field_index++) {
const field_id = fields_arr[field_index];
const field_entries = state.xu_for_index?.[field_id];
if (xu_isEmpty(field_entries)) {
missing_fields.push(field_id);
continue;
}
const entry_keys = Object.keys(field_entries);
for (let entry_index = 0; entry_index < entry_keys.length; entry_index++) {
const entry_key = entry_keys[entry_index];
const entry = field_entries[entry_key];
entries[`${field_id}::${entry_key}`] = entry;
}
}
return {
entries: Object.values(entries),
missing_fields,
panels_obj: resolved_panels_obj || {},
};
};
func.runtime.ui.iterate_refresh_field_in_prog_ui = async function (options, progUi, field_id, refreshed_ids = [], panel_val, current_job) {
const dependencies = func.runtime.ui.get_prog_ui_xu_for_dependencies(progUi);
const field_entries = Object.values(dependencies?.[field_id] || {});
for (const entry of field_entries) {
const $elem = func.runtime.ui.get_refresh_indexed_elements_by_node_id(options.SESSION_ID, entry.parent_node_id);
if (!$elem?.length) {
continue;
}
const parent_element_ui_id = func.runtime.ui.get_attr($elem, 'xu-ui-id');
const refresh_key = parent_element_ui_id && entry.xu_for_item_id ? `${parent_element_ui_id}::${entry.xu_for_item_id}` : parent_element_ui_id;
const is_refreshed = refreshed_ids instanceof Set ? refreshed_ids.has(refresh_key) : refreshed_ids.includes(refresh_key);
if (is_refreshed) {
continue;
}
await func.runtime.ui.queue_xu_for_refresh(options, $elem, entry.xu_for_item_id, current_job, 'node execute_xu_for', panel_val);
if (refreshed_ids instanceof Set) {
refreshed_ids.add(refresh_key);
} else {
refreshed_ids.push(refresh_key);
}
}
return current_job;
};
func.runtime = func.runtime || {};
func.runtime.ui = func.runtime.ui || {};
func.runtime.render = func.runtime.render || {};
// Browser-only xu-attribute refresh helpers live here so screen refresh orchestration can stay focused.
func.runtime.ui.refresh_xu_attributes = async function (options) {
if (!options.ignore_screen_blocker && options.trigger !== 'click' && !xu_isEmpty(SCREEN_BLOCKER_OBJ)) {
setTimeout(() => {
func.runtime.ui.refresh_xu_attributes(options);
}, 100);
return;
}
const perf_end = func.runtime?.perf?.start?.(options.SESSION_ID, 'refresh_xu_attributes');
UI_WORKER_OBJ.cache = {};
try {
// if (glb.DEBUG_MODE) {
// console.info('========= xu-attributes refresh info ==============');
// console.info('fields_arr:', options.fields_arr);
// }
let new_job = options.jobNoP;
let selectors = func.runtime.ui.collect_refresh_selectors(options);
const xu_for_selectors = [];
const refreshed_ids = new Set();
const selector_keys = Object.keys(selectors);
func.runtime?.perf?.increment?.(options.SESSION_ID, 'refresh_selector_batches');
func.runtime?.perf?.increment?.(options.SESSION_ID, 'refresh_selector_total', selector_keys.length);
for (let selector_index = 0; selector_index < selector_keys.length; selector_index++) {
const elem_key = selector_keys[selector_index];
const elem_val = selectors[elem_key];
if (!elem_val) continue;
const $elm = elem_val.$elm;
const elm_data = func.runtime.ui.get_data($elm);
const xuData = elm_data?.xuData;
const xuAttributes = elm_data?.xuAttributes;
if (!xuData || xuData.pending_to_delete) continue;
const attr_list = elem_val.attributes || [];
const has_xu_exp_render = attr_list.includes('xu-exp:xu-render');
const has_xu_for = attr_list.includes('xu-exp:xu-for') || attr_list.includes('xu-for');
let performed_render;
if (!xuAttributes) continue;
if (has_xu_exp_render) {
const res = await func.expression.get(options.SESSION_ID, xuAttributes['xu-exp:xu-render'], xuData.paramsP.dsSessionP, 'UI Property EXP', xuData.recordid);
const attr_value = await func.common.get_cast_val(options.SESSION_ID, 'refresh xu-attributes', 'xu-render', 'bool', res.result);
const _elm_node = func.runtime.ui.get_first_node($elm);
if (!attr_value && _elm_node?.tagName === 'XURENDER') continue;
if (attr_value && _elm_node?.tagName !== 'XURENDER') {
new_job = await func.runtime.ui.queue_refresh_execute_job(options, elem_key, elem_val, 'execute_xu_all_attributes', new_job);
continue;
}
new_job = await func.runtime.ui.queue_refresh_render_job(options, elem_key, elem_val, attr_value, options.jobNoP);
performed_render = true;
func.runtime.ui.mark_refresh_pending_delete($elm);
}
const _elm_tag_node = func.runtime.ui.get_first_node($elm);
if (performed_render || _elm_tag_node?.tagName === 'XURENDER') continue;
if (has_xu_for) {
xu_for_selectors.push(elem_val);
continue;
}
if (xuData.ui_type === 'xu-widget') {
new_job = await func.runtime.ui.queue_refresh_execute_job(options, elem_key, elem_val, 'execute_xu_widget', new_job);
} else {
new_job = await func.runtime.ui.queue_refresh_execute_job(options, elem_key, elem_val, 'execute_xu_all_attributes', new_job);
}
}
if (func.runtime.ui.refresh_missing_prog_ui_xu_render_nodes) {
new_job = await func.runtime.ui.refresh_missing_prog_ui_xu_render_nodes(options, new_job);
}
for (let xu_for_index = 0; xu_for_index < xu_for_selectors.length; xu_for_index++) {
const elem_val = xu_for_selectors[xu_for_index];
const $elm = elem_val?.$elm;
const xuData = func.runtime.ui.get_data($elm)?.xuData;
if (!xuData || xuData.pending_to_delete) continue;
const parent_element_ui_id = func.runtime.ui.get_refresh_parent_element_ui_id($elm);
const xu_for_item_id = func.runtime.ui.resolve_refresh_xu_for_item_id($elm);
const refresh_key = parent_element_ui_id && xu_for_item_id ? `${parent_element_ui_id}::${xu_for_item_id}` : parent_element_ui_id;
if (!parent_element_ui_id || refreshed_ids.has(refresh_key)) {
continue;
}
let _$elem = func.runtime.ui.get_refresh_indexed_element_by_ui_id(options.SESSION_ID, parent_element_ui_id);
if (_$elem && !_$elem.length) _$elem = func.runtime.ui._wrap_matches([_$elem]);
await func.runtime.ui.queue_xu_for_refresh(options, _$elem, xu_for_item_id, new_job, 'execute_xu_for');
refreshed_ids.add(refresh_key);
}
const $xu_embed_container = func.runtime.ui.get_embed_screen_containers();
const refresh_state = func.runtime.ui.ensure_refresh_dependency_state(options.SESSION_ID);
const preload_panels_obj = refresh_state?.xu_for_dirty ? await func.UI.utils.get_panels_wrapper_from_dom(options.SESSION_ID, $xu_embed_container, true) : null;
let { entries: xu_for_entries, missing_fields, panels_obj } = await func.runtime.ui.collect_refresh_xu_for_entries(options, preload_panels_obj, $xu_embed_container);
if (missing_fields.length && xu_isEmpty(panels_obj)) {
panels_obj = await func.UI.utils.get_panels_wrapper_from_dom(options.SESSION_ID, $xu_embed_container, true);
}
for (let entry_index = 0; entry_index < xu_for_entries.length; entry_index++) {
const entry = xu_for_entries[entry_index];
const $elem = func.runtime.ui.get_refresh_indexed_elements_by_node_id(options.SESSION_ID, entry.parent_node_id);
if (!$elem?.length) {
continue;
}
const indexed_parent_element_ui_id = func.runtime.ui.get_attr($elem, 'xu-ui-id');
const indexed_refresh_key = indexed_parent_element_ui_id && entry.xu_for_item_id ? `${indexed_parent_element_ui_id}::${entry.xu_for_item_id}` : indexed_parent_element_ui_id;
if (!indexed_parent_element_ui_id || refreshed_ids.has(indexed_refresh_key)) {
continue;
}
await func.runtime.ui.queue_xu_for_refresh(options, $elem, entry.xu_for_item_id, new_job, 'indexed execute_xu_for', entry);
refreshed_ids.add(indexed_refresh_key);
}
func.runtime?.perf?.increment?.(options.SESSION_ID, 'refresh_xu_for_entries_total', xu_for_entries.length);
func.runtime?.perf?.increment?.(options.SESSION_ID, 'refresh_xu_for_missing_fields_total', missing_fields.length);
for (let missing_index = 0; missing_index < missing_fields.length; missing_index++) {
const field_id = missing_fields[missing_index];
if ($xu_embed_container.length) {
const progUi = func.runtime.ui.get_data($xu_embed_container)?.xuData?.screenInfo?.progUi;
if (progUi) {
await func.runtime.ui.iterate_refresh_field_in_prog_ui(options, progUi, field_id, refreshed_ids, null, new_job);
}
}
const panel_ids = Object.keys(panels_obj || {});
for (let panel_index = 0; panel_index < panel_ids.length; panel_index++) {
const panel_val = panels_obj[panel_ids[panel_index]];
await func.runtime.ui.iterate_refresh_field_in_prog_ui(options, panel_val.progUi, field_id, refreshed_ids, panel_val, new_job);
}
}
func.events.delete_job(options.SESSION_ID, options.jobNoP);
// if (glb.DEBUG_MODE) {
// console.info('===================================================');
// }
} finally {
perf_end?.();
}
};
func.runtime = func.runtime || {};
func.runtime.ui = func.runtime.ui || {};
func.runtime.render = func.runtime.render || {};
// [xu-preserve] one-time load marker — confirms THIS build (refresh-screen child-preserve + data-xu-preserve
// marker, build-400 parity) is the runtime actually running in the page. Temporary debug.
try {
const get_runtime_script_cache_tag = function () {
if (typeof document === 'undefined') {
return '';
}
const script_nodes = [];
if (document.currentScript?.src) {
script_nodes.push(document.currentScript);
}
if (document.scripts?.length) {
script_nodes.push(...Array.from(document.scripts).reverse());
}
for (let index = 0; index < script_nodes.length; index++) {
const src = script_nodes[index]?.src || '';
if (!src || !src.includes('xuda-runtime-bundle')) {
continue;
}
try {
const runtime_script_url = new URL(src, document.baseURI);
const runtime_cache_tag = runtime_script_url.searchParams.get('runtime_cache');
if (runtime_cache_tag) {
return runtime_cache_tag;
}
} catch (error) {}
}
return '';
};
if (typeof globalThis !== 'undefined') {
const runtime_cache_tag = get_runtime_script_cache_tag();
if (runtime_cache_tag) {
globalThis.__XU_RUNTIME_MODULE_CACHE_TAG__ = runtime_cache_tag;
}
}
if (typeof window !== 'undefined' && !window.__xu_preserve_build_logged) {
window.__xu_preserve_build_logged = true;
console.log(
'%c[xuda-runtime:refresh] ' +
JSON.stringify({
version: 'runtime-refresh-20260701-xu-render-parent-gate',
runtime_build: 484,
changes: [
'refresh-coalesce',
'status-tick-no-refresh',
'props-gate',
'child-preserve',
'xu-panel-param-expression-gate',
'native-js-import-cache-bust',
'datasource-refresh-log-restored',
'avoid-refresh-skips-refresh-screen',
'datasource-refresh-cause-logs',
'event-avoid-refresh-option',
'nested-event-avoid-refresh-option',
'out-param-avoid-refresh',
'output-field-avoid-refresh',
'output-param-attributes-only',
'api-set-field-value-attributes-only',
'api-set-field-value-deferred-refresh',
'synthetic-ref-field-no-panel-rerender',
'framework-root-preserve',
'preserved-reattach-lifecycle-event',
'xu-render-relaxed-selector',
'prog-ui-xu-render-selector',
'missing-prog-ui-xu-render-render',
'data-root-expression-fields',
'panel-prog-ui-xu-render-deps',
'panel-prog-ui-xu-render-context',
'live-node-org-xu-render-deps',
'open-modal-xu-render-probe',
'missing-render-parent-fallback',
'missing-render-panel-session-element',
'missing-render-logical-root-overlay',
'save-asset-event-trace',
'set-data-before-render-snapshot',
'pouch-replication-stat-off-without-replication',
'runtime-module-cache-tag-from-script-scan',
'custom-header-waits-inline-module-scripts',
'custom-header-recursive-executable-clone',
'tailwind-plugin-init-script-textcontent',
'tailwind-plugin-init-eval-fallback',
'tailwind-plugin-post-setup-refresh',
'custom-header-inline-module-blob-url',
'custom-header-inline-module-dynamic-import',
'custom-header-tailwind-refresh-retries',
'tailwind-component-theme-alpha-normalize',
'tailwind-theme-alpha-normalize-before-refresh',
'tailwind-addcomponents-captured-css',
'plugin-runtime-manifest-resource-path',
'plugin-runtime-import-failure-logged-continue',
'tailwind-refresh-coalesced',
'doc-ws-http-fallback',
'doc-ws-timeout',
'doc-ws-fallback-log-once',
'prog-ui-raw-attributes-initial-render',
'tagname-node-attribute-phases',
'ui-plugin-dom-element-target',
'xu-render-parent-gate',
],
}),
'color:#1d69db;font-weight:bold',
);
}
} catch (e) {}
// Browser-only screen refresh orchestration lives here so the browser runtime can be split by concern.
func.runtime.ui.prog_doc_refresh_dependency_cache = func.runtime.ui.prog_doc_refresh_dependency_cache || new WeakMap();
func.runtime.ui.panel_refresh_dependency_cache = func.runtime.ui.panel_refresh_dependency_cache || new WeakMap();
func.runtime.ui.extract_refresh_fields_from_text = function (text) {
const fields = new Set();
const str = typeof text === 'string' ? text : JSON.stringify(text || {});
if (!str) {
return fields;
}
for (const match of str.matchAll(/@([A-Za-z0-9_$.-]+)/g)) {
if (match?.[1]) {
fields.add(match[1]);
}
}
return fields;
};
func.runtime.ui.get_prog_doc_refresh_dependencies = function (prog_doc) {
if (!prog_doc || typeof prog_doc !== 'object') {
return {
prog_fields: new Set(),
xu_for_fields: new Set(),
};
}
let cache = func.runtime.ui.prog_doc_refresh_dependency_cache.get(prog_doc);
if (cache) {
return cache;
}
const prog_fields = new Set();
const prog_data_source_str = JSON.stringify(prog_doc.progDataSource || {});
for (const match of prog_data_source_str.matchAll(/@([A-Za-z0-9_$.-]+)/g)) {
if (match?.[1]) {
prog_fields.add(match[1]);
}
}
// NOTE: datasource "watch fields" are NOT handled here. Adding them to prog_fields
// only makes validate_change() take the shallow panel-rerender branch, which does
// NOT re-fire on_load/screen_ready (those are gated off on a refresh, see
// xuda_datasource.js run_on_load_events / schedule_panel_on_load_events). Watch
// fields must re-run the lifecycle so screen_ready-derived data (e.g. a virtual
// field) rebuilds — that is done in func.datasource.update (fire_watch_field_lifecycle).
const xu_for_index = func.UI.utils.get_prog_ui_attribute_index?.(prog_doc.progUi, 'xu-for') || {};
const xu_for_fields = new Set(Object.keys(xu_for_index));
cache = {
prog_fields,
xu_for_fields,
};
func.runtime.ui.prog_doc_refresh_dependency_cache.set(prog_doc, cache);
return cache;
};
func.runtime.ui.get_panel_refresh_dependencies = function (panelXuAttributes) {
if (!panelXuAttributes || typeof panelXuAttributes !== 'object') {
return {
program_fields: new Set(),
parameter_entries: [],
};
}
let cache = func.runtime.ui.panel_refresh_dependency_cache.get(panelXuAttributes);
if (cache) {
return cache;
}
const program_fields = func.runtime.ui.extract_refresh_fields_from_text(panelXuAttributes['xu-exp:program']);
const parameter_entries = [];
const panel_attr_keys = Object.keys(panelXuAttributes);
for (let attr_index = 0; attr_index < panel_attr_keys.length; attr_index++) {
const attr = panel_attr_keys[attr_index];
const value = panelXuAttributes[attr];
const match = attr.match(/xu-exp:(\w+)/);
if (!match || match[1] === 'program') {
continue;
}
parameter_entries.push({
parameter_in_field_id: match[1],
value_str: typeof value === 'string' ? value : JSON.stringify(value || {}),
});
}
cache = {
program_fields,
parameter_entries,
};
func.runtime.ui.panel_refresh_dependency_cache.set(panelXuAttributes, cache);
return cache;
};
// ---- build-400 parity: preserve app-injected content across a panel re-render ----
// Build 400 never blanket-removed a container's children, so DOM an app imperatively appended inside a
// runtime container survived a datasource refresh.
// The current runtime's empty()/remove() wipes regressed that and can destroy mounted native framework
// roots. Preserve explicit `data-xu-preserve` roots and known framework roots before a wipe, keyed by
// the nearest runtime ancestor's stable node id (data-xuda-node-id = template nodeP.id). The mounted
// framework app survives the DOM move (no unmount), so its state/reactivity is preserved.
func.runtime.ui.get_preservable_child_reason = function (el) {
try {
if (!el || el.nodeType !== 1) return '';
if (el.hasAttribute && el.hasAttribute('data-xu-preserve')) return 'data-xu-preserve';
if (el.__vue_app__ || el.__vueParentComponent || el._vnode) return 'vue-root';
if (el._reactRootContainer) return 'react-root';
const own_props = Object.getOwnPropertyNames(el);
for (let i = 0; i < own_props.length; i++) {
const prop = own_props[i];
if (
typeof prop === 'string' &&
(prop.indexOf('__reactContainer$') === 0 || prop.indexOf('__reactFiber$') === 0)
) {
return 'react-root';
}
}
} catch (e) {}
return '';
};
func.runtime.ui.detach_preserved_children = function ($container) {
const rescued = [];
try {
const root = func.runtime.ui.get_first_node($container);
if (!root || !root.querySelectorAll) return rescued;
const candidates = [];
const seen = new Set();
const add_candidate = function (el, reason) {
if (!el || el === root || seen.has(el)) return;
seen.add(el);
candidates.push({ node: el, reason: reason || func.runtime.ui.get_preservable_child_reason(el) || 'preserve' });
};
const marked = root.querySelectorAll('[data-xu-preserve]');
for (let i = 0; i < marked.length; i++) add_candidate(marked[i], 'data-xu-preserve');
const all_children = root.querySelectorAll('*');
for (let i = 0; i < all_children.length; i++) {
const el = all_children[i];
const reason = func.runtime.ui.get_preservable_child_reason(el);
if (reason) add_candidate(el, reason);
}
for (let i = 0; i < candidates.length; i++) {
const el = candidates[i].node;
// only the outermost preservable node when preserved roots nest
let parent = el.parentElement;
let nested = false;
while (parent && parent !== root) {
if (seen.has(parent)) {
nested = true;
break;
}
parent = parent.parentElement;
}
if (nested) continue;
// anchor = nearest runtime ancestor's stable node id
let anc = el.parentElement;
let anchor = null;
while (anc) {
const nid = (anc.getAttribute && anc.getAttribute('data-xuda-node-id')) || func.runtime.ui.get_data(anc)?.xuData?.nodeid;
if (nid) {
anchor = nid;
break;
}
if (anc === root) break;
anc = anc.parentElement;
}
rescued.push({ node: el, anchor, reason: candidates[i].reason });
}
if (rescued.length) {
// suppress the xu-ref observer for our own removeChild moves (cleared on the next macrotask,
// after the observer microtask has flushed)
func.runtime.ui.__xu_preserve_suppress = true;
setTimeout(function () {
func.runtime.ui.__xu_preserve_suppress = false;
}, 0);
}
for (let i = 0; i < rescued.length; i++) {
const n = rescued[i].node;
if (n.parentNode) n.parentNode.removeChild(n);
}
if (rescued.length) {
try {
globalThis.__XUDA_RT_TRACE && console.log('[xuda-runtime] preserve_detach ' +
JSON.stringify({
count: rescued.length,
nodes: rescued.map((r) => ({
id: (r.node && r.node.id) || '',
tag: r.node?.tagName || '',
anchor: r.anchor || null,
reason: r.reason || '',
})),
}),
);
} catch (e) {}
}
} catch (e) {
/* best-effort; never block the refresh */
}
return rescued;
};
func.runtime.ui.reattach_preserved_children = function ($container, rescued) {
if (!rescued || !rescued.length) return;
const attempt = function () {
let pending = 0;
// suppress the xu-ref observer for our own appendChild moves so re-attaching the preserved node does
// NOT re-enter refresh_screen (that would loop: reattach -> observer -> refresh -> re-render -> reattach).
// Cleared on the next macrotask, after the observer microtask has flushed.
func.runtime.ui.__xu_preserve_suppress = true;
setTimeout(function () {
func.runtime.ui.__xu_preserve_suppress = false;
}, 0);
try {
const root = func.runtime.ui.get_first_node($container);
if (!root) return rescued.length; // container not re-rendered yet — retry
let attached = 0;
for (let i = 0; i < rescued.length; i++) {
const r = rescued[i];
if (!r.node || r.node.isConnected) continue; // already re-attached
let target = null;
if (r.anchor && root.querySelector) {
target = root.querySelector(`[data-xuda-node-id="${r.anchor}"]`);
if (!target && func.runtime.ui.get_data(root)?.xuData?.nodeid === r.anchor) target = root;
}
if (!target) target = root; // fallback: the container root
if (!target.contains(r.node)) {
target.appendChild(r.node);
attached++;
try {
r.node.dispatchEvent(
new CustomEvent('xuda:preserved-reattach', {
bubbles: true,
detail: { anchor: r.anchor || null, reason: r.reason || '' },
}),
);
} catch (e) {}
}
}
try {
if (attached && root.dispatchEvent) {
root.dispatchEvent(new CustomEvent('xuda:preserved-children-reattached', { detail: { count: attached } }));
}
} catch (e) {}
} catch (e) {
/* best-effort */
}
try {
globalThis.__XUDA_RT_TRACE && console.log('[xuda-runtime] preserve_reattach ' +
JSON.stringify({
pending,
nodes: rescued.map((r) => ({
id: (r.node && r.node.id) || '',
connected: !!r.node?.isConnected,
anchor: r.anchor || null,
reason: r.reason || '',
})),
}),
);
} catch (e) {}
return pending;
};
// The panel may render synchronously or defer/background-render its children, so the target
// container can appear a tick later — retry on the next tick(s) for any still-pending node.
if (attempt() > 0) {
setTimeout(attempt, 0);
setTimeout(attempt, 60);
setTimeout(attempt, 250);
}
};
// ---- same-frame datasource refresh coalescing ----
// A single user gesture can update a chain of dependent fields on the same datasource, producing a
// burst of refresh_screen calls before the browser has painted. Coalesce those same-datasource calls
// into one render carrying the union of changed fields. Distinct datasources and later-frame
// refreshes are untouched, and non-data refreshes (watcher/full-screen, which carry no
// fields_changed_arr) bypass coalescing entirely.
func.runtime.ui._refresh_coalesce = func.runtime.ui._refresh_coalesce || { buckets: new Map(), scheduled: false };
func.runtime.ui.refresh_screen = function (options) {
const _state = func.runtime.ui._refresh_coalesce;
const _ds_key = options?.fields_changed_datasource;
const _can_coalesce = typeof requestAnimationFrame === 'function' && _ds_key != null && Array.isArray(options?.fields_changed_arr);
if (!_can_coalesce) {
return func.runtime.ui._refresh_screen_impl(options);
}
let _bucket = _state.buckets.get(_ds_key);
if (!_bucket) {
_bucket = { options: options, fields: new Set(), waiters: [] };
_state.buckets.set(_ds_key, _bucket);
}
_bucket.options = options; // latest options win for this datasource; fields are unioned below
for (const _f of options.fields_changed_arr) _bucket.fields.add(_f);
try {
globalThis.__XUDA_RT_TRACE && console.log('[xuda-runtime] refresh_screen_queue ' +
JSON.stringify({
datasource: _ds_key,
fields: Array.from(_bucket.fields),
waiters: _bucket.waiters.length + 1,
}),
);
} catch (e) {}
return new Promise(function (resolve) {
_bucket.waiters.push(resolve);
if (_state.scheduled) return;
_state.scheduled = true;
requestAnimationFrame(async function () {
_state.scheduled = false;
const _entries = Array.from(_state.buckets.entries());
_state.buckets.clear();
for (const [, _b] of _entries) {
const _merged = Object.assign({}, _b.options, { fields_changed_arr: Array.from(_b.fields) });
try {
globalThis.__XUDA_RT_TRACE && console.log('[xuda-runtime] refresh_screen_flush ' +
JSON.stringify({
datasource: _merged.fields_changed_datasource,
fields: _merged.fields_changed_arr,
waiters: _b.waiters.length,
}),
);
} catch (e) {}
let _result;
try {
_result = await func.runtime.ui._refresh_screen_impl(_merged);
} catch (error) {
console.error(error);
}
for (const _w of _b.waiters) {
try {
_w(_result);
} catch (e) {}
}
}
});
});
};
func.runtime.ui._refresh_screen_impl = async function (options) {
const perf_end = func.runtime?.perf?.start?.(options.SESSION_ID, 'refresh_screen');
let found;
let refresh_reason;
let refresh_details;
try {
const validate_change = function (prog_doc, panelXuAttributes, skip_ui_check) {
found = null;
refresh_reason = null;
refresh_details = null;
if (options.watcher?.path?.includes('progDataSource')) {
found = true;
refresh_reason = `progDataSource by watcher ${options.watcher.path}`;
refresh_details = options.watcher;
return;
}
const refresh_dependencies = func.runtime.ui.get_prog_doc_refresh_dependencies(prog_doc);
const _attributes = panelXuAttributes || {};
const panel_refresh_dependencies = func.runtime.ui.get_panel_refresh_dependencies(_attributes);
const fields_to_validate = (options.fields_changed_arr || []).filter(function (field_id) {
return field_id !== 'SYS_GLOBAL_OBJ_REFS' || options.fields_changed_arr.length === 1;
});
for (const field_id of fields_to_validate) {
found = panel_refresh_dependencies.program_fields.has(field_id);
if (found) {
refresh_reason = `program ${_attributes['xu-exp:program']} ${field_id} changed `;
refresh_details = _attributes;
break;
}
for (const parameter_entry of panel_refresh_dependencies.parameter_entries) {
const parameter_in_field_id = parameter_entry.parameter_in_field_id;
if (parameter_entry.value_str?.includes(field_id)) {
found = refresh_dependencies.prog_fields.has(parameter_in_field_id);
if (found) {
refresh_reason = `field ${field_id} in progDataSource parameter_in changed`;
refresh_details = prog_doc?.progDataSource;
break;
}
if (!skip_ui_check) {
found = refresh_dependencies.xu_for_fields.has(parameter_in_field_id);
if (found) {
refresh_reason = `field ${field_id} in progUi xu-for parameter_in changed`;
refresh_details = found;
break;
}
}
}
}
if (found) break;
found = refresh_dependencies.prog_fields.has(field_id);
if (found) {
refresh_reason = `field ${field_id} in progDataSource changed`;
refresh_details = prog_doc?.progDataSource;
break;
}
if (!skip_ui_check) {
found = refresh_dependencies.xu_for_fields.has(field_id);
if (found) {
refresh_reason = `field ${field_id} in progUi xu-for changed`;
refresh_details = found;
break;
}
}
if (found) {
break;
}
}
};
if (options.fields_changed_datasource) {
const _session = SESSION_OBJ[options.SESSION_ID];
const _ds = _session.DS_GLB[options.fields_changed_datasource];
const prog_doc = await func.utils.DOCS_OBJ.get(options.SESSION_ID, _ds.prog_id);
if (prog_doc.progUi) {
validate_change(prog_doc, null, true);
if (found) {
const $elm = func.runtime.ui.find_in_root(options.SESSION_ID, `#container_${_ds.prog_id}_0`);
if ($elm?.length) {
const elm_data = func.runtime.ui.get_data($elm);
const refreshed_ds = _ds.dsSession;
// build-400 parity: preserve program-injected content across the main-program wipe
const _rescued_main = func.runtime.ui.detach_preserved_children($elm);
func.runtime.ui.empty($elm);
if (func.runtime.ui.get_data($elm)) {
try {
globalThis.__XUDA_RT_TRACE && console.log('[xuda-runtime] refresh_screen_main_rerender ' +
JSON.stringify({
datasource: options.fields_changed_datasource || options.datasource_changed || null,
fields: options.fields_changed_arr || null,
reason: refresh_reason || null,
}),
);
} catch (e) {}
func.runtime?.perf?.increment?.(options.SESSION_ID, 'refresh_screen_main_rerenders');
await func.runtime.render.render_ui_tree(
options.SESSION_ID,
$elm,
structuredClone(elm_data.xuData.node),
{},
elm_data.xuData.paramsP,
null,
null,
elm_data.xuData.key,
refreshed_ds,
elm_data.xuData.parent_node,
null,
elm_data.xuData.$root_container,
);
func.runtime.ui.reattach_preserved_children($elm, _rescued_main);
if (glb.DEBUG_MODE) {
console.info('========= refresh main info ==============');
console.info('reason:', refresh_reason);
console.info('element:', $elm);
console.info('==========================================');
}
return;
}
}
}
}
}
const panels_obj = await func.UI.utils.get_panels_wrapper_from_dom(options.SESSION_ID, func.runtime.ui.get_root_element(options.SESSION_ID), false);
found = false;
const panel_ids = Object.keys(panels_obj || {});
for (let panel_index = 0; panel_index < panel_ids.length; panel_index++) {
found = false;
refresh_reason = null;
refresh_details = null;
const panel_val = panels_obj[panel_ids[panel_index]];
const panel_data = func.runtime.ui.get_data(panel_val.$panel_div);
const panel_xu_data = panel_data?.xuData;
if (!panel_xu_data) continue;
if (panel_xu_data.pending_to_delete) continue;
if (!options.watcher && options.fields_changed_arr) {
if (options.fields_changed_datasource && panel_val._ds.dsSession < Number(options.fields_changed_datasource)) {
continue;
}
validate_change(panel_val.prog_doc, panel_val?.panelXuAttributes);
}
if (options.datasource_changed && panel_val._ds.dsSession == options.datasource_changed) {
refresh_reason = `panel datasource ${options.datasource_changed} changed`;
refresh_details = '';
found = true;
}
if (found) {
// No-op refresh suppression (screen level): the changed datasource has ALREADY re-run
// by the time this notification arrives (its pre-refresh row snapshot is still attached).
// If the new rows are identical, skip this panel's teardown+re-render — that wipe/rebuild
// was the visible flick and multi-second freeze for zero data change. Genuinely changed
// rows leave the snapshot in place and re-render exactly as before.
try {
const _flick_ds = SESSION_OBJ[options.SESSION_ID]?.DS_GLB?.[panel_val._ds.dsSession];
const _flick_prev = _flick_ds && _flick_ds.__refresh_prev_rows;
if (options.datasource_changed && Array.isArray(_flick_prev)) {
const _flick_cur = (_flick_ds.data_feed && _flick_ds.data_feed.rows) || [];
const _flick_same =
_flick_prev.length === _flick_cur.length &&
_flick_cur.length > 0 &&
_flick_cur.every(function (row, row_index) {
const prev = _flick_prev[row_index];
return prev && prev._ROWID === row._ROWID && xu_isEqual(prev, row);
});
if (_flick_same) {
delete _flick_ds.__refresh_prev_rows;
console.log('%c[xuda-runtime] FLICK-SUPPRESSED — datasource ' + options.datasource_changed + ' re-ran with identical rows; panel re-render skipped', 'color:#16a34a;font-weight:bold');
continue;
}
}
} catch (e) {}
UI_WORKER_OBJ.cache = {};
const _session = SESSION_OBJ[options.SESSION_ID];
if (!_session) continue;
const $div_elm = panel_val.$panel_div;
const wrapper_data = panel_data;
const panel_node = func.runtime.ui.get_first_node($div_elm);
if (!panel_node?.isConnected) continue;
if (xu_isEmpty(wrapper_data)) continue;
const panel_refresh_key = [
options.datasource_changed || options.fields_changed_datasource || 'fields',
func.runtime.ui.get_attr($div_elm, 'xu-ui-id') || panel_ids[panel_index],
].join(':');
_session.panel_refresh_locks = _session.panel_refresh_locks || {};
const active_refresh = _session.panel_refresh_locks[panel_refresh_key];
if (active_refresh) {
active_refresh.pending = true;
continue;
}
const refresh_lock = { pending: false };
_session.panel_refresh_locks[panel_refresh_key] = refresh_lock;
let rerun_refresh = false;
if (glb.DEBUG_MODE) {
console.info('========= refresh info ==============');
console.info('reason:', refresh_reason);
console.info('details:', refresh_details);
console.info('panel:', panel_val);
console.info('=====================================');
}
try {
try {
try {
globalThis.__XUDA_RT_TRACE && console.log('[xuda-runtime] refresh_screen_panel_rerender ' +
JSON.stringify({
datasource: options.fields_changed_datasource || options.datasource_changed || null,
fields: options.fields_changed_arr || null,
panel_datasource: panel_val?._ds?.dsSession || null,
panel_prog_id: panel_val?._ds?.prog_id || null,
panel_ui_id: func.runtime.ui.get_attr($div_elm, 'xu-ui-id') || panel_ids[panel_index] || null,
reason: refresh_reason || null,
}),
);
} catch (e) {}
func.runtime?.perf?.increment?.(options.SESSION_ID, 'refresh_screen_panel_rerenders');
// build-400 parity: detach program-injected content so the rebuild below doesn't destroy it
const rescued_foreign = func.runtime.ui.detach_preserved_children($div_elm);
// Keep the current content painted through the rebuild. Wipe-then-async-render left the
// panel EMPTY for the entire rebuild — a multi-second blank flash on every datasource
// change (the screen/modal "flick"). The old children stay in place (marked so refresh
// scans skip them); the rebuild's panel reconcile replaces same-elem_key panels in
// their slots, and whatever old content the rebuild did not claim is swept afterwards.
const existing_children = func.runtime.ui.get_children($div_elm);
const stale_children_nodes = [];
for (let child_index = 0; child_index < existing_children.length; child_index++) {
func.runtime.ui.mark_refresh_pending_delete?.(existing_children[child_index]);
const stale_node = func.runtime.ui.get_first_node(existing_children[child_index]);
if (stale_node) {
stale_children_nodes.push(stale_node);
}
}
func.runtime.ui.mark_refresh_index_dirty?.(options.SESSION_ID);
const had_skip_panel_replacement = Object.prototype.hasOwnProperty.call(wrapper_data, 'xuSkipPanelReplacement');
const previous_skip_panel_replacement = wrapper_data.xuSkipPanelReplacement;
wrapper_data.xuSkipPanelReplacement = true;
let refreshed_ds;
if (_session.DS_GLB[panel_val._ds.dsSession]) {
refreshed_ds = panel_val._ds.dsSession;
}
try {
for (let child_index = 0; child_index < wrapper_data.xuData.node_org.children.length; child_index++) {
const item = wrapper_data.xuData.node_org.children[child_index];
if (item.tagName !== 'xu-panel') continue;
await func.runtime.render.render_ui_tree(
options.SESSION_ID,
$div_elm,
structuredClone(item),
{},
wrapper_data.xuData.paramsP,
null,
null,
wrapper_data.xuData.key,
refreshed_ds,
wrapper_data.xuData.parent_node,
null,
wrapper_data.xuData.$root_container,
);
}
} finally {
if (had_skip_panel_replacement) {
wrapper_data.xuSkipPanelReplacement = previous_skip_panel_replacement;
} else {
delete wrapper_data.xuSkipPanelReplacement;
}
}
// Sweep old content the rebuild did not replace in place (removed rows, key drift).
// Runs only after the new tree has landed, so the panel is never blank in between;
// if the rebuild threw, the sweep is skipped and the old content stays visible.
for (let stale_index = 0; stale_index < stale_children_nodes.length; stale_index++) {
const stale_node = stale_children_nodes[stale_index];
if (stale_node.isConnected) {
func.runtime.ui.remove(stale_node);
}
}
func.runtime.ui.mark_refresh_index_dirty?.(options.SESSION_ID);
// build-400 parity: re-attach the rescued program-injected content into the re-rendered panel
func.runtime.ui.reattach_preserved_children($div_elm, rescued_foreign);
} catch (error) {
console.error('[xuda-runtime] caught xuda_runtime.browser.refresh.js:314:', error);
}
} finally {
rerun_refresh = !!refresh_lock.pending;
if (_session.panel_refresh_locks?.[panel_refresh_key] === refresh_lock) {
delete _session.panel_refresh_locks[panel_refresh_key];
}
}
if (rerun_refresh) {
setTimeout(function () {
func.runtime.ui._refresh_screen_impl(options).catch(async function (error) {
if (func.utils?.report_issue) {
await func.utils.report_issue(options.SESSION_ID, {
code: 'RUN_MSG_RND_071',
source: 'refresh_screen',
message: 'queued panel refresh failed',
type: 'W',
err: error,
details: {
datasource_changed: options.datasource_changed,
fields_changed_datasource: options.fields_changed_datasource,
panel_refresh_key,
},
});
}
});
}, 0);
}
}
}
} finally {
perf_end?.();
}
};
func.runtime = func.runtime || {};
func.runtime.ui = func.runtime.ui || {};
func.runtime.render = func.runtime.render || {};
// Browser-only realtime refresh helpers live here so refresh orchestration can stay focused.
func.runtime.ui.refresh_document_changes_for_realtime_update = async function (SESSION_ID, doc_change) {
const _session = SESSION_OBJ[SESSION_ID];
for (const [key, _ds] of Object.entries(_session.DS_GLB)) {
const prog_obj = await func.utils.VIEWS_OBJ.get(SESSION_ID, _ds.prog_id);
if (prog_obj?.progDataSource?.dataSourceRealtime && prog_obj?.progDataSource?.dataSourceTableId === doc_change.table_id) {
try {
if (!_ds.screen_params) continue;
if (_ds.screen_params.is_panelP) {
await func.runtime.ui.refresh_screen({ SESSION_ID, fields_changed_arr: null, datasource_changed: key });
} else {
await func.action.execute(SESSION_ID, 'act_refresh', _ds, null, null);
}
} catch (err) {
await func.utils.report_issue(SESSION_ID, {
code: 'RUN_MSG_RND_070',
source: 'refresh_document_changes_for_realtime_update',
message: 'realtime refresh failed',
type: 'W',
err,
details: {
datasource: key,
table_id: doc_change.table_id,
prog_id: _ds.prog_id,
},
});
}
}
}
if (glb.new_xu_render) {
for (const [ui_cache_key, ui_cache_val] of Object.entries(UI_WORKER_OBJ.xu_render_cache)) {
const prog_obj = await func.utils.VIEWS_OBJ.get(SESSION_ID, ui_cache_val.paramsP.prog_id);
if (prog_obj?.progDataSource?.dataSourceTableId === doc_change.table_id) {
ui_cache_val.$div = null;
}
}
}
};
func.runtime = func.runtime || {};
func.runtime.ui = func.runtime.ui || {};
func.runtime.render = func.runtime.render || {};
func.runtime.widgets = func.runtime.widgets || {};
// Browser-only render draw helpers live here so the browser runtime can be split by concern.
func.runtime.render.get_screen_context = function (SESSION_ID, $container, paramsP, is_skeleton) {
const _session = SESSION_OBJ[SESSION_ID];
const _ds = is_skeleton ? null : _session?.DS_GLB?.[paramsP.dsSessionP];
const container_xu_data = func.runtime.ui.get_data($container)?.xuData;
let currentRecordId = container_xu_data?.recordid || _ds?.currentRecordId || '';
// Same sentinel rule as create_container — keeps element matching consistent with the
// upgraded record ids stamped on children (see xuda_runtime.browser.dom.js).
if (currentRecordId === 'newRecord' && _ds?.currentRecordId && _ds.currentRecordId !== 'newRecord') {
const _live_rows = _ds.data_feed?.rows;
if (Array.isArray(_live_rows) && _live_rows.some((row) => row._ROWID === _ds.currentRecordId)) {
currentRecordId = _ds.currentRecordId;
}
}
return {
_session,
_ds,
container_xu_data,
currentRecordId,
is_mobile: glb.MOBILE_ARR.includes(paramsP.screenInfo.properties?.menuType),
};
};
func.runtime.render.get_node_attributes = function (nodeP) {
try {
if (func.runtime.render.is_tree_node?.(nodeP)) {
return nodeP.attributes;
}
return nodeP?.attributes;
} catch (error) {
return undefined;
}
};
func.runtime.render.find_existing_element = function (options) {
const currentRecordId = options.currentRecordId || options.render_context?.currentRecordId;
const SESSION_ID = options.SESSION_ID || func.runtime.ui.get_data(options.$container)?.xuData?.SESSION_ID;
const is_matching_candidate = function (candidate) {
if (!candidate) return false;
const candidate_data = func.runtime.ui.get_data(candidate);
return (
!candidate_data?.xuData?.is_placeholder &&
!candidate_data?.xuData?.xu_for_placeholder &&
candidate_data?.xuData?.recordid === currentRecordId &&
candidate_data?.xuData?.key === options.keyP &&
candidate.tagName !== 'XURENDER'
);
};
const get_indexed_match = function () {
if (!SESSION_ID || !func.runtime.ui.get_refresh_indexed_elements_by_node_id) {
return null;
}
const indexed_candidates = func.runtime.ui.get_refresh_indexed_elements_by_node_id(SESSION_ID, options.nodeP.id).toArray();
for (let index = 0; index < indexed_candidates.length; index++) {
const candidate = indexed_candidates[index];
if (candidate.parentElement !== func.runtime.ui.get_first_node(options.$container)) {
continue;
}
if (is_matching_candidate(candidate)) {
return func.runtime.ui._wrap_matches([candidate]);
}
}
return null;
};
const indexed_match = get_indexed_match();
if (indexed_match?.length) {
return {
div: indexed_match,
candidates: indexed_match,
};
}
let $candidates = func.runtime.ui.find_element_data_in_parent(options.$container, 'xuData', 'nodeid', options.nodeP.id);
let $matched = null;
const fallback_candidates = $candidates?.toArray?.() || [];
for (let index = 0; index < fallback_candidates.length; index++) {
const candidate = fallback_candidates[index];
if (is_matching_candidate(candidate)) {
$matched = func.runtime.ui._wrap_matches([candidate]);
break;
}
}
return {
div: $matched,
candidates: $candidates,
};
};
func.runtime.render.log_tree_debug = function (options) {
return func.utils.debug.log(options.SESSION_ID, options.paramsP.prog_id + '_' + options.nodeP.id_org + '_ui_prop', {
module: 'gui',
action: 'init',
prop: options.nodeP.id,
details: options.error_descP,
result: null,
error: options.is_errorP,
source: options._ds?.tree_obj?.menuName || '',
fields: null,
type: null,
prog_id: options.paramsP.prog_id,
dsSession: null,
});
};
func.runtime.render.create_temp_render_container = function ($container) {
const tmp = document.createElement('tmp');
func.runtime.ui.set_data(tmp, 'xuData', func.runtime.ui.get_data($container)?.xuData);
return tmp;
};
func.runtime.render.insert_ordered_child = function ($container, $child, target_key) {
const children = func.runtime.ui.get_children($container);
if (!children.length) {
return func.runtime.ui.append_to($child, $container);
}
const normalized_target_key = Number.isFinite(Number(target_key)) ? Number(target_key) : `${target_key}`;
for (let index = 0; index < children.length; index++) {
const existing_child = children[index];
const existing_key = func.runtime.ui.get_data(existing_child)?.xuData?.key;
if (typeof existing_key === 'undefined' || existing_key === null) {
continue;
}
const normalized_existing_key = Number.isFinite(Number(existing_key)) ? Number(existing_key) : `${existing_key}`;
if (normalized_existing_key > normalized_target_key) {
return func.runtime.ui.insert_before($child, existing_child);
}
}
return func.runtime.ui.append_to($child, $container);
};
func.runtime.render.prepare_draw_context = async function (options) {
let temp_$div = null;
let render_container = options.$container;
let $div;
if (options.buffered) {
temp_$div = await func.runtime.ui.create_container({
SESSION_ID: options.SESSION_ID,
$root_container: options.$root_container,
nodeP: options.nodeP,
$container: options.$container,
paramsP: options.paramsP,
parent_infoP: options.parent_infoP,
jobNoP: options.jobNoP,
keyP: options.keyP,
treeP: options.treeP,
parent_nodeP: options.parent_nodeP,
prop: options.prop,
div_typeP: options.element,
attr_str: options.attr_str || '',
is_placeholder: true,
});
render_container = func.runtime.render.create_temp_render_container(options.$container);
$div = func.runtime.ui.get_first_node(temp_$div)?.cloneNode(true);
const cloned_data = func.runtime.ui.get_data($div);
if (cloned_data?.xuData) {
cloned_data.xuData.is_placeholder = false;
}
} else {
$div = await func.runtime.ui.create_container({
SESSION_ID: options.SESSION_ID,
$root_container: options.$root_container,
nodeP: options.nodeP,
$container: options.$container,
paramsP: options.paramsP,
parent_infoP: options.parent_infoP,
jobNoP: options.jobNoP,
keyP: options.keyP,
treeP: options.treeP,
parent_nodeP: options.parent_nodeP,
prop: options.prop,
div_typeP: options.element,
attr_str: options.attr_str || '',
});
}
return {
$div,
temp_$div,
$live_elm: temp_$div || $div,
render_container,
};
};
func.runtime.render.run_draw_pipeline = async function (options) {
if (!options.element || options.element === 'script') {
return {
$div: null,
temp_$div: null,
render_container: options.$container,
ret: {},
};
}
const draw_context = await func.runtime.render.prepare_draw_context(options);
const { $div, temp_$div, $live_elm, render_container } = draw_context;
func.runtime.render.bind_hover_handlers($div, options.hover_handlers, options.include_hover_click);
const ret = await func.runtime.render.set_attributes_new({
SESSION_ID: options.SESSION_ID,
is_skeleton: options.is_skeleton,
$root_container: options.$root_container,
nodeP: options.nodeP,
$container: render_container,
paramsP: options.paramsP,
parent_infoP: options.parent_infoP,
jobNoP: options.jobNoP,
keyP: options.keyP,
parent_nodeP: options.parent_nodeP,
$elm: $div,
$live_elm,
is_init: true,
});
if (!func.runtime.render.should_stop_after_attributes(options.nodeP, ret)) {
await func.runtime.render.process_post_attribute_children({
SESSION_ID: options.SESSION_ID,
$div,
nodeP: options.nodeP,
parent_infoP: options.parent_infoP,
$root_container: options.$root_container,
paramsP: options.paramsP,
jobNoP: options.jobNoP,
is_skeleton: options.is_skeleton,
keyP: options.keyP,
refreshed_ds: options.refreshed_ds,
parent_nodeP: options.parent_nodeP,
check_existP: options.check_existP,
render_container,
hover_in: options.hover_handlers.hover_in,
iterate_child: options.iterate_child,
await_children: !options.buffered,
defer_when_background: options.buffered,
ret,
});
}
return {
$div,
temp_$div,
$live_elm,
render_container,
ret,
};
};
// Browser render draw helpers remain here. Xu-render cache helpers moved to xuda_runtime.browser.render.cache.js.
func.runtime = func.runtime || {};
func.runtime.ui = func.runtime.ui || {};
func.runtime.render = func.runtime.render || {};
func.runtime.widgets = func.runtime.widgets || {};
func.runtime.render.parent_ds_fields_cache = func.runtime.render.parent_ds_fields_cache || new Map();
func.runtime.render.parent_ds_field_names_cache = func.runtime.render.parent_ds_field_names_cache || new Map();
func.runtime.render.xu_render_cache_str_cache = func.runtime.render.xu_render_cache_str_cache || new Map();
func.runtime.render.xu_render_exclude_fields_cache = func.runtime.render.xu_render_exclude_fields_cache || new WeakMap();
// Browser-only xu-render cache helpers live here so the draw pipeline can stay focused.
func.runtime.render.set_small_cache_entry = function (cache, key, value, max_entries = 1000) {
if (cache.size >= max_entries && !cache.has(key)) {
cache.clear();
}
cache.set(key, value);
return value;
};
func.runtime.render.get_runtime_descendants = function ($div) {
const _div_node = func.runtime.ui.get_first_node($div);
if (!_div_node) {
return [];
}
return _div_node.querySelectorAll?.('[xu-ui-id]') || [];
};
func.runtime.render.collect_dependency_fields_from_store = function (dependency_store, dependency_fields) {
const attr_keys = Object.keys(dependency_store || {});
for (let attr_index = 0; attr_index < attr_keys.length; attr_index++) {
const fields = dependency_store[attr_keys[attr_index]] || [];
for (let field_index = 0; field_index < fields.length; field_index++) {
dependency_fields.add(fields[field_index]);
}
}
return dependency_fields;
};
func.runtime.render.collect_dependency_fields_from_attributes = function (xu_attributes, dependency_fields) {
const attr_keys = Object.keys(xu_attributes || {});
for (let attr_index = 0; attr_index < attr_keys.length; attr_index++) {
const attr_val = xu_attributes[attr_keys[attr_index]];
if (typeof attr_val !== 'string') {
continue;
}
const matches = attr_val.match(/@([A-Za-z0-9_]+)/g) || [];
for (let match_index = 0; match_index < matches.length; match_index++) {
dependency_fields.add(matches[match_index].slice(1));
}
}
return dependency_fields;
};
func.runtime.render.build_xu_render_original_data = function (options) {
return {
$container: options.$container,
nodeP: func.runtime.ui.get_node_snapshot ? func.runtime.ui.get_node_snapshot(options.nodeP) : structuredClone(options.nodeP),
parent_infoP: options.parent_infoP,
paramsP: options.paramsP,
keyP: options.keyP,
parent_nodeP: options.parent_nodeP,
$root_container: options.$root_container,
};
};
func.runtime.render.attach_xu_render_state = function ($xurender, options) {
func.runtime.ui.set_data($xurender, 'xuData', options.xuData);
func.runtime.ui.get_data($xurender).xuData.original_data_obj = options.original_data_obj;
if (options.xurender_node) {
func.runtime.ui.get_data($xurender).xuData.xurender_node = options.xurender_node;
}
func.runtime.ui.get_data($xurender).xuAttributes = options.xuAttributes || {};
return $xurender;
};
func.runtime.render.create_xu_render_placeholder = function (xu_ui_id, $target, options = {}) {
const $xurender = func.runtime.ui.create_xurender(xu_ui_id, $target, options.hidden);
return func.runtime.render.attach_xu_render_state($xurender, options);
};
func.runtime.render.collect_dependency_fields = function ($div) {
if (!$div?.length) {
return [];
}
const dependency_fields = new Set();
const descendants = func.runtime.render.get_runtime_descendants($div);
for (let index = 0; index < descendants.length; index++) {
const elm_data = func.runtime.ui.get_data(descendants[index]);
const dependency_store = elm_data?.xuData?.refresh_dependency_by_attr;
if (dependency_store) {
func.runtime.render.collect_dependency_fields_from_store(dependency_store, dependency_fields);
continue;
}
const xu_attributes = elm_data?.xuAttributes;
if (!xu_attributes) {
continue;
}
func.runtime.render.collect_dependency_fields_from_attributes(xu_attributes, dependency_fields);
}
return [...dependency_fields];
};
func.runtime.render.cache_xu_render = function (cache_key, value) {
if (value?.$div && !value.dependency_fields) {
value.dependency_fields = func.runtime.render.collect_dependency_fields(value.$div);
}
UI_WORKER_OBJ.xu_render_cache[cache_key] = value;
return UI_WORKER_OBJ.xu_render_cache[cache_key];
};
func.runtime.render.get_parent_ds_cache_signature = function (SESSION_ID, dsSessionP) {
var _session = SESSION_OBJ[SESSION_ID];
var _ds = _session.DS_GLB[dsSessionP];
if (!_ds) {
return `${dsSessionP || ''}:`;
}
let signature = `${dsSessionP}:${_ds.currentRecordId || ''}`;
if (typeof _ds.parentDataSourceNo !== 'undefined') {
signature += `|${func.runtime.render.get_parent_ds_cache_signature(SESSION_ID, _ds.parentDataSourceNo)}`;
}
return signature;
};
func.runtime.render.build_parent_ds_fields = function (SESSION_ID, dsSessionP) {
var _session = SESSION_OBJ[SESSION_ID];
var _ds = _session.DS_GLB[dsSessionP];
if (!_ds) {
return {};
}
const idx = func.common.find_ROWID_idx(_ds, _ds.currentRecordId);
const data = _ds.data_feed.rows[idx] || {};
let obj = {};
if (typeof _ds.parentDataSourceNo !== 'undefined') {
obj = func.runtime.render.get_parent_ds_fields(SESSION_ID, _ds.parentDataSourceNo);
}
return { ...data, ...obj };
};
func.runtime.render.get_parent_ds_fields = function (SESSION_ID, dsSessionP) {
const signature = func.runtime.render.get_parent_ds_cache_signature(SESSION_ID, dsSessionP);
const cache_key = `${SESSION_ID}:${signature}`;
if (func.runtime.render.parent_ds_fields_cache.has(cache_key)) {
return func.runtime.render.parent_ds_fields_cache.get(cache_key);
}
const fields = func.runtime.render.build_parent_ds_fields(SESSION_ID, dsSessionP);
return func.runtime.render.set_small_cache_entry(func.runtime.render.parent_ds_fields_cache, cache_key, fields);
};
func.runtime.render.get_parent_ds_field_names = function (SESSION_ID, dsSessionP) {
const signature = func.runtime.render.get_parent_ds_cache_signature(SESSION_ID, dsSessionP);
const cache_key = `${SESSION_ID}:${signature}`;
if (func.runtime.render.parent_ds_field_names_cache.has(cache_key)) {
return func.runtime.render.parent_ds_field_names_cache.get(cache_key);
}
const fields = Object.keys(func.runtime.render.get_parent_ds_fields(SESSION_ID, dsSessionP));
return func.runtime.render.set_small_cache_entry(func.runtime.render.parent_ds_field_names_cache, cache_key, fields);
};
func.runtime.render.get_xu_render_exclude_fields = function ($elm) {
const fields_obj = func.runtime.ui.get_data($elm)?.xuData?.attr_exp_info?.['xu-render']?.fields;
if (!fields_obj) {
return [];
}
if (func.runtime.render.xu_render_exclude_fields_cache.has(fields_obj)) {
return func.runtime.render.xu_render_exclude_fields_cache.get(fields_obj);
}
const fields = Object.keys(fields_obj);
func.runtime.render.xu_render_exclude_fields_cache.set(fields_obj, fields);
return fields;
};
func.runtime.render.get_xu_render_cache_str = async function (SESSION_ID, dsSessionP, exclude_vars = []) {
const exclude_key = [...exclude_vars].sort().join('|');
const signature = func.runtime.render.get_parent_ds_cache_signature(SESSION_ID, dsSessionP);
const cache_key = `${SESSION_ID}:${signature}:${exclude_key}`;
if (func.runtime.render.xu_render_cache_str_cache.has(cache_key)) {
return func.runtime.render.xu_render_cache_str_cache.get(cache_key);
}
const fields_obj = func.runtime.render.get_parent_ds_fields(SESSION_ID, dsSessionP);
const exclude_vars_set = new Set(exclude_vars);
let str = '';
const field_keys = Object.keys(fields_obj);
for (let index = 0; index < field_keys.length; index++) {
const key = field_keys[index];
const val = fields_obj[key];
if (exclude_vars_set.has(key)) continue;
str += typeof val !== 'undefined' ? JSON.stringify(val) : '';
}
const cache_str = 'C-' + (await func.common.sha256(str));
return func.runtime.render.set_small_cache_entry(func.runtime.render.xu_render_cache_str_cache, cache_key, cache_str);
};
func.runtime.render.has_parent_field_dependency = function ($div, parent_fields = [], dependency_fields = null) {
if (!parent_fields?.length) {
return false;
}
const parent_field_set = new Set(parent_fields);
if (dependency_fields?.length) {
for (let index = 0; index < dependency_fields.length; index++) {
if (parent_field_set.has(dependency_fields[index])) {
return true;
}
}
return false;
}
if (!$div?.length) {
return false;
}
const descendants = func.runtime.render.get_runtime_descendants($div);
for (let index = 0; index < descendants.length; index++) {
const elm_data = func.runtime.ui.get_data(descendants[index]);
const dependency_store = elm_data?.xuData?.refresh_dependency_by_attr;
if (dependency_store) {
const attr_keys = Object.keys(dependency_store);
for (let attr_index = 0; attr_index < attr_keys.length; attr_index++) {
const fields = dependency_store[attr_keys[attr_index]] || [];
for (let field_index = 0; field_index < fields.length; field_index++) {
if (parent_field_set.has(fields[field_index])) {
return true;
}
}
}
continue;
}
const xu_attributes = elm_data?.xuAttributes;
if (!xu_attributes) {
continue;
}
const attr_keys = Object.keys(xu_attributes);
for (let attr_index = 0; attr_index < attr_keys.length; attr_index++) {
const attr_val = xu_attributes[attr_keys[attr_index]];
if (typeof attr_val !== 'string') {
continue;
}
for (let field_index = 0; field_index < parent_fields.length; field_index++) {
if (attr_val.includes('@' + parent_fields[field_index])) {
return true;
}
}
}
}
return false;
};
func.runtime.render.finalize_buffered_draw = async function (options) {
const xu_ui_id = func.runtime.ui.get_attr(options.$div, 'xu-ui-id');
if (options.ret.has_xu_exp_render_attribute) {
const exclude_fields = func.runtime.render.get_xu_render_exclude_fields(options.$div);
const xu_render_cache_id = await func.runtime.render.get_xu_render_cache_str(
options.SESSION_ID,
options.paramsP.dsSessionP,
exclude_fields,
);
const _$div = func.runtime.ui.get_first_node(options.$div)?.cloneNode(true);
func.runtime.render.cache_xu_render(xu_ui_id + xu_render_cache_id, { $div: _$div, paramsP: options.paramsP, data: func.runtime.ui.get_data(_$div) });
options.nodeP.xu_render_xu_ui_id = xu_ui_id;
options.nodeP.xu_render_cache_id = xu_render_cache_id;
}
return func.runtime.render.finalize_temp_draw(options.temp_$div, options.$div, options.ret);
};
func.runtime = func.runtime || {};
func.runtime.ui = func.runtime.ui || {};
func.runtime.render = func.runtime.render || {};
func.runtime.widgets = func.runtime.widgets || {};
func.runtime.render.viewport_observers = func.runtime.render.viewport_observers || null;
func.runtime.render.style_tag_cache = func.runtime.render.style_tag_cache || new Set();
// Browser-only post-render behavior helpers live here so the core render tree can stay focused.
func.runtime.render.finalize_temp_draw = function (temp_$div, $div, ret = {}) {
func.runtime.ui.remove_class($div, 'display_none');
if (ret.consume_placeholder) {
func.runtime.ui.remove(temp_$div);
return $div;
}
if (ret.xu_render_background_processing || ret.has_xu_render_attribute) {
func.runtime.ui.remove(temp_$div);
return $div;
}
func.runtime.ui.replace_with(temp_$div, $div);
return $div;
};
func.runtime.render.get_viewport_observers = function () {
if (func.runtime.render.viewport_observers) {
return func.runtime.render.viewport_observers;
}
const observer_inViewport = new IntersectionObserver(
function (entries) {
entries.forEach((entry) => {
if (entry.isIntersecting) {
entry.target.dispatchEvent(new CustomEvent('inViewport'));
observer_inViewport.unobserve(entry.target);
}
});
},
{
threshold: 0.1,
},
);
const observer_outViewport = new IntersectionObserver(
function (entries) {
entries.forEach((entry) => {
if (!entry.isIntersecting) {
entry.target.dispatchEvent(new CustomEvent('outViewport'));
}
});
},
{
threshold: 0,
},
);
func.runtime.render.viewport_observers = {
observer_inViewport,
observer_outViewport,
};
return func.runtime.render.viewport_observers;
};
func.runtime.render.bind_viewport_render = function ($div, handlers) {
const { observer_inViewport, observer_outViewport } = func.runtime.render.get_viewport_observers();
const div_node = func.runtime.ui.get_first_node($div);
let ui_job_id;
// Remove previous handlers if they exist, then attach new ones
if (div_node._xuda_inViewportHandler) {
div_node.removeEventListener('inViewport', div_node._xuda_inViewportHandler);
}
div_node._xuda_inViewportHandler = function () {
ui_job_id = handlers.onEnter({ observer_outViewport });
};
div_node.addEventListener('inViewport', div_node._xuda_inViewportHandler);
if (div_node._xuda_outViewportHandler) {
div_node.removeEventListener('outViewport', div_node._xuda_outViewportHandler);
}
div_node._xuda_outViewportHandler = function () {
handlers.onExit({ observer_inViewport, ui_job_id });
};
div_node.addEventListener('outViewport', div_node._xuda_outViewportHandler);
func.runtime.ui.add_class($div, 'skeleton');
observer_inViewport.observe(div_node);
return $div;
};
func.runtime.render.has_terminal_content_attributes = function (nodeP) {
return (
!xu_isEmpty(nodeP?.attributes?.['xu-text']) ||
!xu_isEmpty(nodeP?.attributes?.['xu-html']) ||
!xu_isEmpty(nodeP?.attributes?.['xu-exp:xu-text']) ||
!xu_isEmpty(nodeP?.attributes?.['xu-exp:xu-html'])
);
};
func.runtime.render.should_stop_after_attributes = function (nodeP, ret = {}) {
return !!(ret.abort || nodeP.tagName === 'svg' || func.runtime.render.has_terminal_content_attributes(nodeP));
};
func.runtime.render.should_use_viewport_render = function (nodeP) {
return nodeP?.attributes?.['xu-viewport'] == 'true';
};
func.runtime.render.bind_draw_viewport = function (options) {
const div_node = func.runtime.ui.get_first_node(options.$div);
func.runtime.render.bind_viewport_render(options.$div, {
onEnter: ({ observer_outViewport }) => {
if (div_node?.childElementCount) {
func.runtime.ui.remove_class(options.$div, 'skeleton');
return null;
}
options.hover_in(options.$div);
const ui_job_id = func.UI.worker.add_to_queue(
options.SESSION_ID,
'gui event',
'render_viewport',
{
$div: options.$div,
nodeP: options.nodeP,
parent_infoP: options.parent_infoP,
$root_container: options.$root_container,
paramsP: options.paramsP,
jobNoP: options.jobNoP,
is_skeleton: options.is_skeleton,
keyP: options.keyP,
refreshed_ds: options.refreshed_ds,
parent_nodeP: options.parent_nodeP,
check_existP: options.check_existP,
$container: options.render_container,
},
null,
null,
options.paramsP.dsSessionP,
);
observer_outViewport.observe(div_node);
return ui_job_id;
},
onExit: ({ observer_inViewport, ui_job_id }) => {
func.UI.worker.delete_job(options.SESSION_ID, ui_job_id);
if (div_node?.childElementCount) {
func.runtime.ui.empty(options.$div);
const height = func.runtime.ui.get_data(options.$div)?.xuData?.viewport_height || 10;
if (typeof height !== 'undefined') {
func.runtime.ui.set_style(options.$div, 'height', `${height}px`);
}
}
observer_inViewport.observe(div_node);
},
});
return options.$div;
};
func.runtime.render.process_post_attribute_children = async function (options) {
if (func.runtime.render.should_use_viewport_render(options.nodeP)) {
return func.runtime.render.bind_draw_viewport(options);
}
if (options.defer_when_background && options.ret?.xu_render_background_processing) {
return options.$div;
}
if (options.await_children) {
await options.iterate_child(options.$div, options.nodeP, options.parent_infoP, options.$root_container);
return options.$div;
}
options.iterate_child(options.$div, options.nodeP, options.parent_infoP, options.$root_container);
return options.$div;
};
func.runtime.render.append_style_tag = function (cssText) {
if (!cssText || func.runtime.render.style_tag_cache.has(cssText)) {
return false;
}
func.runtime.render.style_tag_cache.add(cssText);
const style_node = document.createElement('style');
style_node.textContent = cssText;
document.head.appendChild(style_node);
return true;
};
func.runtime.render.scope_css_to_xu_ui = function ($elm, cssText) {
var parser = new cssjs();
var parsed = parser.parseCSS(cssText);
var xuUiId = `[xu-ui-id="${func.runtime.ui.get_attr($elm, 'xu-ui-id')}"]`;
for (var key = 0; key < parsed.length; key++) {
var val = parsed[key];
var selectors_arr = val.selector.split(',');
for (var key2 = 0; key2 < selectors_arr.length; key2++) {
selectors_arr[key2] = `${xuUiId} ${selectors_arr[key2]}, ${xuUiId}${selectors_arr[key2]}`;
}
val.selector = selectors_arr.join(',');
}
return parser.getCSSForEditor(parsed);
};
func.runtime.render.bind_xu_event = function (options) {
const decode_html_entities = function (value) {
if (typeof value !== 'string' || value.indexOf('&') === -1) {
return value;
}
if (typeof document !== 'undefined') {
const textarea = document.createElement('textarea');
textarea.innerHTML = value;
return textarea.value;
}
return value
.replaceAll('"', '"')
.replaceAll('"', '"')
.replaceAll(''', "'")
.replaceAll(''', "'")
.replaceAll('<', '<')
.replaceAll('>', '>')
.replaceAll('&', '&');
};
const normalize_event_handlers = function (raw_handlers) {
if (typeof raw_handlers !== 'string') {
return raw_handlers;
}
const decoded_value = decode_html_entities(raw_handlers).trim();
if (!decoded_value) {
return [];
}
try {
return JSON5.parse(decoded_value);
} catch (error) {
func.utils.report_issue(options.SESSION_ID, {
code: 'RUN_MSG_RND_010',
source: 'xu-on',
message: `xu-on has invalid workflow syntax: ${decoded_value}`,
type: 'E',
err: error,
details: {
trigger: options.val.key,
value: decoded_value,
},
});
return [];
}
};
CLIENT_ACTIVITY_TS = Date.now();
const trigger = options.val.key.split('xu-on:')[1].toLowerCase();
const handler_key = `_xuda_xuOn_${trigger.replace(/[^a-z0-9_]/gi, '_')}`;
const elm_node = func.runtime.ui.get_first_node(options.$elm);
if (elm_node[handler_key]) {
elm_node.removeEventListener(trigger, elm_node[handler_key]);
}
elm_node[handler_key] = async function (evt) {
const _$elm = evt.currentTarget;
const elm_data = func.runtime.ui.get_data(_$elm);
const xuAttributes = elm_data?.xuAttributes;
const event_attr_key = 'xu-on:' + evt.type;
const event_handlers = normalize_event_handlers(xuAttributes?.[event_attr_key]);
if (xuAttributes && event_handlers !== xuAttributes?.[event_attr_key]) {
xuAttributes[event_attr_key] = event_handlers;
}
if (xu_isEmpty(xuAttributes) || xu_isEmpty(event_handlers)) return;
const handler_keys = Object.keys(event_handlers);
for (let handler_index = 0; handler_index < handler_keys.length; handler_index++) {
const val = event_handlers[handler_keys[handler_index]];
const handler_props = val?.props || {};
if (!xu_isEmpty(handler_props.condition)) {
const expCond = await func.expression.get(options.SESSION_ID, handler_props.condition, options.paramsP.dsSessionP, 'condition', options.paramsP.recordid);
if (!expCond.result) continue;
}
if (val?.event_modifiers && evt[val.event_modifiers]) {
evt[val.event_modifiers]();
}
const workflow = val?.workflow || val?.event;
if (workflow) {
const workflow_keys = Object.keys(workflow);
for (let workflow_index = 0; workflow_index < workflow_keys.length; workflow_index++) {
const val2 = workflow[workflow_keys[workflow_index]];
if (!val2?.data?.action) continue;
if (val2.data.enabled === false) continue;
func.events.add_to_queue(
options.SESSION_ID,
'element event',
val2.id,
evt.type,
val2.data.action,
val2.data.name,
null,
func.runtime.ui.get_attr(_$elm, 'xu-ui-id'),
null,
evt,
null,
null,
null,
options.paramsP.dsSessionP,
null,
null,
null,
evt.type,
val2.data.name,
null,
null,
val2,
null,
null,
null,
null,
null,
null,
);
}
}
}
};
elm_node.addEventListener(trigger, elm_node[handler_key]);
return options.$elm;
};
func.runtime = func.runtime || {};
func.runtime.ui = func.runtime.ui || {};
func.runtime.render = func.runtime.render || {};
func.runtime.widgets = func.runtime.widgets || {};
// Browser-only hover/debug state helpers live here so post-render behavior can stay focused on non-hover flow.
func.runtime.render.should_bind_hover_click = function (paramsP, parent_infoP) {
return paramsP.paramsP === 'grid' || !!parent_infoP?.iterate_info;
};
func.runtime.render.create_hover_handlers = function (options) {
return {
hover_in: function ($div, e) {
return func.runtime.render.handle_hover_in({
SESSION_ID: options.SESSION_ID,
is_skeleton: options.is_skeleton,
e,
$div,
$container: options.$container,
_ds: options._ds,
paramsP: options.paramsP,
});
},
hover_out: function () {
return func.runtime.render.handle_hover_out({
SESSION_ID: options.SESSION_ID,
is_skeleton: options.is_skeleton,
$container: options.$container,
_ds: options._ds,
});
},
};
};
func.runtime.render.bind_hover_handlers = function ($div, handlers, include_click) {
const el = func.runtime.ui.get_first_node($div);
if (!el) return $div;
el.addEventListener('mouseenter', function (e) {
handlers.hover_in($div, e);
});
el.addEventListener('mouseleave', function () {
handlers.hover_out();
});
if (include_click) {
el.addEventListener('click', function (e) {
handlers.hover_in($div, e);
});
el.addEventListener('contextmenu', function (e) {
handlers.hover_in($div, e);
});
}
return $div;
};
func.runtime.render.resolve_debug_element = function ($elm) {
try {
const el = func.runtime.ui.get_first_node($elm);
const id = el?.getAttribute?.('xu-ui-id');
if (!id || !glb.DEBUG_MODE) {
return $elm;
}
const matches = document.querySelectorAll(`[xu-ui-id="${id}"]`);
if (matches.length > 1) {
console.warn('Multiple elements for xu-ui-id: ' + id, matches);
}
return matches[0] || $elm;
} catch (e) {
console.error(e);
return $elm;
}
};
func.runtime.render.set_hover_item = function ($container, $target) {
const resolved_container = func.runtime.render.resolve_debug_element($container);
const resolved_data = func.runtime.ui.get_data(resolved_container);
if (!resolved_data?.xuData?.debug_info) {
return false;
}
const target_el = func.runtime.ui.get_first_node($target);
resolved_data.xuData.debug_info.hover_item = target_el?.getAttribute?.('xu-ui-id') || null;
return true;
};
func.runtime.render.get_element_attributes = function ($div) {
let attributes = {};
const el = func.runtime.ui.get_first_node($div);
const attrs = el?.attributes || [];
for (let index = 0; index < attrs.length; index++) {
const attr = attrs[index];
attributes[attr.name] = attr.value;
}
return attributes;
};
func.runtime.render.set_hovered_attributes = function (SESSION_ID, attributes) {
const root_data_system = func.runtime.render.get_root_data_system(SESSION_ID);
if (!root_data_system) {
return false;
}
root_data_system.SYS_OBJ_WIN_ELEMENT_HOVERED_ATTRIBUTES = attributes;
return true;
};
func.runtime.render.clear_hovered_attributes = function (SESSION_ID) {
return func.runtime.render.set_hovered_attributes(SESSION_ID, {});
};
func.runtime.render.queue_datasource_update = function (SESSION_ID, dsSessionP, currentRecordId, field_id, field_value) {
const payload = {
currentRecordId,
};
if (typeof field_id !== 'undefined') {
payload.field_id = field_id;
payload.field_value = field_value;
}
func.UI.worker.add_to_queue(SESSION_ID, 'gui event', 'update_datasource', payload, null, null, dsSessionP);
return payload;
};
func.runtime.render.queue_hover_updates = function (options) {
const resolved_div = func.runtime.render.resolve_debug_element(options.$div);
const resolved_data = func.runtime.ui.get_data(resolved_div);
const currentRecordId = resolved_data?.xuData?.currentRecordId;
if (options.$div && resolved_div && options._ds && options.paramsP.renderType === 'grid' && currentRecordId) {
func.runtime.render.queue_datasource_update(options.SESSION_ID, options.paramsP.dsSessionP, currentRecordId);
}
const div_data = func.runtime.ui.get_data(options.$div);
const iterate_info = div_data?.xuData?.iterate_info || div_data?.iterate_info;
if (!iterate_info || !currentRecordId) {
return false;
}
if (iterate_info.iterator_key) {
func.runtime.render.queue_datasource_update(options.SESSION_ID, options.paramsP.dsSessionP, currentRecordId, iterate_info.iterator_key, iterate_info._key);
}
if (iterate_info.iterator_val) {
func.runtime.render.queue_datasource_update(options.SESSION_ID, options.paramsP.dsSessionP, currentRecordId, iterate_info.iterator_val, iterate_info._val);
}
return true;
};
func.runtime.render.handle_hover_in = function (options) {
if (options.is_skeleton || (options.e && (EXP_BUSY || UI_WORKER_OBJ.active_jobs_count))) {
return false;
}
CLIENT_ACTIVITY_TS = Date.now();
const $target = options.$div || options.$container;
func.runtime.render.set_hover_item(options.$container, $target);
if (!options._ds) {
return true;
}
func.runtime.render.set_hovered_attributes(options.SESSION_ID, func.runtime.render.get_element_attributes($target));
const target_data = func.runtime.ui.get_data($target);
if (!target_data?.xuData) {
return true;
}
const iterate_info = target_data.xuData.iterate_info;
func.runtime.render.sync_iterate_info_to_dataset(options._ds, iterate_info);
func.runtime.render.queue_hover_updates({
SESSION_ID: options.SESSION_ID,
paramsP: options.paramsP,
$div: $target,
_ds: options._ds,
});
return true;
};
func.runtime.render.handle_hover_out = function (options) {
if (options.is_skeleton) {
return false;
}
CLIENT_ACTIVITY_TS = Date.now();
func.runtime.render.set_hover_item(options.$container, null);
if (options._ds?.data_system) {
func.runtime.render.clear_hovered_attributes(options.SESSION_ID);
return true;
}
return false;
};
func.runtime = func.runtime || {};
func.runtime.ui = func.runtime.ui || {};
func.runtime.render = func.runtime.render || {};
func.runtime.widgets = func.runtime.widgets || {};
// Browser-only widget rendering lives here so plugin runtime concerns stay separate from special-node routing.
func.runtime.widgets.render_node = async function (options) {
const exist_elm_obj = func.runtime.render.find_existing_element({
$container: options.$container,
nodeP: options.nodeP,
keyP: options.keyP,
render_context: options.render_context,
});
let $div = exist_elm_obj.div;
if (!$div) {
$div = await func.runtime.ui.create_container({
SESSION_ID: options.SESSION_ID,
$root_container: options.$root_container,
nodeP: options.nodeP,
$container: options.$container,
paramsP: options.paramsP,
parent_infoP: options.parent_infoP,
jobNoP: options.jobNoP,
keyP: options.keyP,
treeP: options.treeP,
parent_nodeP: options.parent_nodeP,
prop: options.prop,
classP: 'widget_wrapper',
});
if (func.runtime.render.is_hydration_mode(SESSION_OBJ?.[options.SESSION_ID]) && func.runtime.render.should_use_ssr_payload(options.SESSION_ID, options.paramsP)) {
func.runtime.ui.empty($div);
}
const widget_context = func.runtime.widgets.create_context(options.SESSION_ID, options.paramsP, options.prop);
const { plugin_name, method, propsP, plugin: _plugin } = widget_context;
const report_error = function (descP, warn) {
return func.runtime.widgets.report_error(widget_context, descP, warn);
};
const definition = await func.runtime.widgets.get_definition(widget_context);
if (!func.runtime.widgets.supports_current_environment(definition)) {
return report_error(`plugin ${plugin_name} is not available in the current environment`, true);
}
const methods = definition?.methods || {};
if (methods && !methods[method]) {
return report_error('method not found');
}
const fields_ret = await func.runtime.widgets.get_fields_data(widget_context, methods[method].fields, propsP);
if (fields_ret.code < 0) {
return report_error(fields_ret.data);
}
const fields = fields_ret.data;
let exclude_attributes = [];
const prop_keys = Object.keys(propsP || {});
for (let prop_index = 0; prop_index < prop_keys.length; prop_index++) {
const key = prop_keys[prop_index];
if (typeof fields[key] !== 'undefined' || typeof fields[`xu-exp:${key}`] !== 'undefined') {
exclude_attributes.push(key);
}
}
await func.runtime.render.set_attributes_new({
SESSION_ID: options.SESSION_ID,
is_skeleton: options.is_skeleton,
$root_container: options.$root_container,
nodeP: options.nodeP,
$container: options.$container,
paramsP: options.paramsP,
parent_infoP: options.parent_infoP,
jobNoP: options.jobNoP,
keyP: options.keyP,
parent_nodeP: options.parent_nodeP,
$elm: $div,
is_init: true,
execute_attributes: exclude_attributes,
});
func.runtime.ui.add_class($div, 'widget_wrapper');
if (!_plugin) {
return report_error(`plugin ${plugin_name} not found`);
}
if (_plugin.manifest['style.css'].exist) {
func.runtime.widgets.load_css_style(widget_context);
}
const plugin_setup_ret = await func.utils.get_plugin_setup(options.SESSION_ID, plugin_name);
if (plugin_setup_ret.code < 0) {
return report_error(plugin_setup_ret);
}
const api_utils = await func.common.get_module(options.SESSION_ID, 'xuda-api-library.mjs', {
func,
glb,
SESSION_OBJ,
SESSION_ID: options.SESSION_ID,
APP_OBJ,
dsSession: options.paramsP.dsSessionP,
job_id: options.jobNoP,
});
const params = func.runtime.widgets.build_params(
widget_context,
func.runtime.ui.get_first_node($div),
func.runtime.ui.get_data($div),
plugin_setup_ret.data,
api_utils,
);
const fx = await func.runtime.widgets.get_resource(widget_context, 'runtime.mjs');
await func.runtime.widgets.load_runtime_css(widget_context);
if (!fx[method]) {
throw `Method: ${method} does not exist`;
}
try {
await fx[method](fields, params);
} catch (err) {
func.utils.debug_report(options.SESSION_ID, `${plugin_name} widget`, err.message, 'E');
}
}
return $div;
};
func.runtime = func.runtime || {};
func.runtime.ui = func.runtime.ui || {};
func.runtime.render = func.runtime.render || {};
func.runtime.widgets = func.runtime.widgets || {};
// Browser-only special node renderers live here so the core render tree can stay focused.
const normalize_runtime_tag_name = function (tag_name) {
return `${tag_name || ''}`.trim().toLowerCase();
};
const get_runtime_node_attributes = function (nodeP) {
if (!nodeP?.attributes || typeof nodeP.attributes !== 'object') {
return {};
}
return nodeP.attributes;
};
const get_runtime_node_content = function (nodeP) {
if (typeof nodeP?.content === 'string') {
return nodeP.content;
}
if (typeof nodeP?.text === 'string') {
return nodeP.text;
}
if (!Array.isArray(nodeP?.children)) {
return '';
}
return nodeP.children
.map(function (child) {
if (typeof child === 'string') {
return child;
}
if (typeof child?.content === 'string') {
return child.content;
}
if (typeof child?.text === 'string') {
return child.text;
}
return '';
})
.join('');
};
const get_runtime_asset_key = function (options, tag_name) {
const source_node = options.treeP || options.nodeP || {};
const parts = [
'xuda-html-asset',
options.paramsP?.prog_id || '',
tag_name,
source_node.id || source_node.id_org || '',
typeof options.keyP === 'undefined' || options.keyP === null ? '' : `${options.keyP}`,
].filter(function (part) {
return `${part || ''}`.trim() !== '';
});
return parts.join(':');
};
const get_runtime_asset_signature = function (attributes, content) {
const normalized_attributes = {};
const attr_keys = Object.keys(attributes || {}).sort();
for (let index = 0; index < attr_keys.length; index++) {
const key = attr_keys[index];
normalized_attributes[key] = attributes[key];
}
return JSON.stringify({
attributes: normalized_attributes,
content: `${content || ''}`,
});
};
const escape_runtime_asset_selector_value = function (value) {
const win = func.runtime.platform.get_window?.();
if (win?.CSS?.escape) {
return win.CSS.escape(value);
}
return `${value || ''}`.replace(/\\/g, '\\\\').replace(/"/g, '\\"');
};
const find_runtime_head_asset = function (head, tag_name, asset_key) {
if (!head?.querySelector || !asset_key) {
return null;
}
return head.querySelector(`${tag_name}[data-xuda-asset-key="${escape_runtime_asset_selector_value(asset_key)}"]`);
};
const find_runtime_head_asset_by_attr = function (head, tag_name, attr_name, attr_value) {
if (!head?.querySelectorAll || !attr_name || !attr_value) {
return null;
}
const candidates = Array.from(head.querySelectorAll(tag_name));
return (
candidates.find(function (candidate) {
return candidate.getAttribute(attr_name) === attr_value || candidate[attr_name] === attr_value;
}) || null
);
};
const wait_for_runtime_asset_load = function (node) {
if (!node?.addEventListener) {
return Promise.resolve(node);
}
if (node.getAttribute?.('data-xuda-loaded') === 'true') {
return Promise.resolve(node);
}
if (!node.getAttribute?.('data-xuda-asset-key')) {
return Promise.resolve(node);
}
const tag_name = normalize_runtime_tag_name(node.tagName);
if (tag_name !== 'script' && !(tag_name === 'link' && normalize_runtime_tag_name(node.getAttribute?.('rel')) === 'stylesheet')) {
return Promise.resolve(node);
}
return new Promise(function (resolve) {
const done = function () {
node.setAttribute?.('data-xuda-loaded', 'true');
resolve(node);
};
node.addEventListener('load', done, { once: true });
node.addEventListener('error', done, { once: true });
});
};
const is_runtime_tailwind_script_src = function (src) {
const normalized_src = `${src || ''}`.trim().toLowerCase();
if (!normalized_src) {
return false;
}
return normalized_src.includes('cdn.tailwindcss.com') || /(?:^|\/)tailwind\.cdn\.js(?:[?#].*)?$/.test(normalized_src);
};
const is_runtime_tailwind_config_script = function (content) {
return /(?:^|[^\w.])tailwind\.config\s*=/.test(`${content || ''}`);
};
const has_runtime_tailwind = function () {
const win = func.runtime.platform.get_window?.();
return !!win?.tailwind;
};
const refresh_runtime_tailwind = async function () {
const win = func.runtime.platform.get_window?.();
const refresh = win?.tailwind?.refresh;
if (typeof refresh !== 'function') {
return false;
}
try {
await refresh();
return true;
} catch (error) {
console.error(error);
return false;
}
};
const remove_runtime_head_asset = function (node) {
if (node?.parentNode?.removeChild) {
node.parentNode.removeChild(node);
}
};
const apply_runtime_asset_metadata = function (node, asset_key, signature) {
if (!node?.setAttribute) {
return node;
}
if (asset_key) {
node.setAttribute('data-xuda-asset-key', asset_key);
}
node.setAttribute('data-xuda-asset-signature', signature);
return node;
};
const create_runtime_head_element = function (doc, tag_name, attributes, asset_key, signature) {
const node = doc.createElement(tag_name);
apply_runtime_asset_metadata(node, asset_key, signature);
func.runtime.platform.apply_element_attributes(node, attributes);
return node;
};
const get_runtime_html_script_queue = function () {
return (
func.runtime.render._html_script_queue ||
(func.runtime.render._html_script_queue = {
items: [],
running: false,
})
);
};
const queue_runtime_html_script_task = function (task) {
const queue = get_runtime_html_script_queue();
queue.items.push(task);
};
func.runtime.render.flush_html_script_queue = async function () {
const queue = get_runtime_html_script_queue();
if (queue.running || !queue.items.length) {
return;
}
queue.running = true;
try {
while (queue.items.length) {
const next_task = queue.items.shift();
await next_task();
}
} catch (error) {
console.error(error);
} finally {
queue.running = false;
}
};
const upsert_runtime_head_element = async function (options) {
const doc = func.runtime.platform.get_document?.();
const head = doc?.head;
const tag_name = normalize_runtime_tag_name(options.tag_name);
if (!doc?.createElement || !head?.appendChild || !tag_name) {
return null;
}
const asset_key = options.asset_key || '';
const signature = options.signature || '';
const attributes = options.attributes || {};
const content = typeof options.content === 'string' ? options.content : '';
const existing_by_key = find_runtime_head_asset(head, tag_name, asset_key);
if (existing_by_key && existing_by_key.getAttribute('data-xuda-asset-signature') === signature) {
return options.await_load ? await wait_for_runtime_asset_load(existing_by_key) : existing_by_key;
}
if (existing_by_key) {
remove_runtime_head_asset(existing_by_key);
}
if (options.find_existing_attr?.name && options.find_existing_attr?.value) {
const existing_by_attr = find_runtime_head_asset_by_attr(head, tag_name, options.find_existing_attr.name, options.find_existing_attr.value);
if (existing_by_attr) {
apply_runtime_asset_metadata(existing_by_attr, asset_key, signature);
existing_by_attr.setAttribute?.('data-xuda-loaded', 'true');
return existing_by_attr;
}
}
const node = create_runtime_head_element(doc, tag_name, attributes, asset_key, signature);
if (tag_name === 'script' && attributes.src && !Object.prototype.hasOwnProperty.call(attributes, 'async')) {
const script_type = normalize_runtime_tag_name(attributes.type);
if (script_type !== 'module') {
node.async = false;
}
}
if (tag_name === 'style' || (tag_name === 'script' && !attributes.src)) {
node.textContent = content;
}
head.appendChild(node);
if (tag_name !== 'script' && tag_name !== 'link') {
node.setAttribute('data-xuda-loaded', 'true');
}
return options.await_load ? await wait_for_runtime_asset_load(node) : node;
};
const render_runtime_html_asset = async function (options) {
if (options.is_skeleton) {
return options.$container;
}
const nodeP = options.treeP || options.nodeP || {};
const tag_name = normalize_runtime_tag_name(nodeP.tagName);
const attributes = { ...get_runtime_node_attributes(nodeP) };
const content = get_runtime_node_content(nodeP);
const asset_key = get_runtime_asset_key(options, tag_name);
const signature = get_runtime_asset_signature(attributes, content);
switch (tag_name) {
case 'title':
func.runtime.platform.set_title(content);
return options.$container;
case 'style':
await upsert_runtime_head_element({
tag_name,
attributes,
content,
asset_key,
signature,
});
return options.$container;
case 'meta':
if (!Object.keys(attributes).length) {
return options.$container;
}
await upsert_runtime_head_element({
tag_name,
attributes,
asset_key,
signature,
});
return options.$container;
case 'link': {
const href = `${attributes.href || ''}`.trim();
if (!href) {
return options.$container;
}
await upsert_runtime_head_element({
tag_name,
attributes,
asset_key,
signature,
find_existing_attr: {
name: 'href',
value: href,
},
await_load: normalize_runtime_tag_name(attributes.rel) === 'stylesheet',
});
return options.$container;
}
case 'script': {
const src = `${attributes.src || ''}`.trim();
const is_tailwind_script = is_runtime_tailwind_script_src(src);
const is_tailwind_config_script = is_runtime_tailwind_config_script(content);
if (!src && !content.trim()) {
return options.$container;
}
queue_runtime_html_script_task(async function () {
if (src && is_tailwind_script && has_runtime_tailwind()) {
return;
}
await upsert_runtime_head_element({
tag_name,
attributes,
content,
asset_key,
signature,
find_existing_attr: src
? {
name: 'src',
value: src,
}
: null,
await_load: !!src,
});
if (is_tailwind_config_script) {
await refresh_runtime_tailwind();
}
});
return options.$container;
}
default:
return null;
}
};
func.runtime.render.render_special_node = async function (options) {
const treeP = options.treeP || null;
const nodeP = options.nodeP || func.runtime.render.get_tree_source_node(treeP);
const render_tag_name = treeP?.tagName || nodeP?.tagName;
const normalized_render_tag_name = normalize_runtime_tag_name(render_tag_name);
const is_native_html_asset = ['title', 'style', 'meta', 'link', 'script'].includes(normalized_render_tag_name);
if (!is_native_html_asset && treeP?.content && nodeP?.attributes) {
nodeP.attributes['xu-content'] = treeP.content;
} else if (!is_native_html_asset && nodeP?.content && nodeP.attributes) {
nodeP.attributes['xu-content'] = nodeP.content;
}
const renderers = {
'xu-widget': async function () {
if (options.is_skeleton) return;
return await func.runtime.widgets.render_node({
SESSION_ID: options.SESSION_ID,
$container: options.$container,
$root_container: options.$root_container,
treeP,
nodeP: options.nodeP,
parent_infoP: options.parent_infoP,
paramsP: options.paramsP,
jobNoP: options.jobNoP,
is_skeleton: options.is_skeleton,
keyP: options.keyP,
parent_nodeP: options.parent_nodeP,
prop: options.prop,
render_context: options.render_context,
});
},
'xu-single-view': async function () {
const render_type = typeof options.paramsP?.renderType === 'string' ? options.paramsP.renderType.trim().toLowerCase() : '';
const view_renderer = ['grid', 'list'].includes(render_type) ? func.runtime.ui.render_multi_view_node : func.runtime.ui.render_single_view_node;
return await view_renderer({
SESSION_ID: options.SESSION_ID,
$container: options.$container,
$root_container: options.$root_container,
treeP,
nodeP: options.nodeP,
parent_infoP: options.parent_infoP,
paramsP: options.paramsP,
jobNoP: options.jobNoP,
is_skeleton: options.is_skeleton,
keyP: options.keyP,
parent_nodeP: options.parent_nodeP,
prop: options.prop,
render_context: options.render_context,
hover_handlers: options.hover_handlers,
iterate_child: options.iterate_child,
close_modal: options.close_modal,
});
},
'xu-multi-view': async function () {
return await func.runtime.ui.render_multi_view_node({
SESSION_ID: options.SESSION_ID,
$container: options.$container,
$root_container: options.$root_container,
treeP,
nodeP: options.nodeP,
parent_infoP: options.parent_infoP,
paramsP: options.paramsP,
jobNoP: options.jobNoP,
is_skeleton: options.is_skeleton,
keyP: options.keyP,
parent_nodeP: options.parent_nodeP,
iterate_child: options.iterate_child,
close_modal: options.close_modal,
});
},
'xu-panel': async function () {
return await func.runtime.ui.render_panel_node({
SESSION_ID: options.SESSION_ID,
$container: options.$container,
$root_container: options.$root_container,
treeP,
nodeP: options.nodeP,
parent_infoP: options.parent_infoP,
paramsP: options.paramsP,
jobNoP: options.jobNoP,
is_skeleton: options.is_skeleton,
keyP: options.keyP,
parent_nodeP: options.parent_nodeP,
prop: options.prop,
refreshed_ds: options.refreshed_ds,
});
},
title: async function () {
return await render_runtime_html_asset(options);
},
style: async function () {
return await render_runtime_html_asset(options);
},
meta: async function () {
return await render_runtime_html_asset(options);
},
link: async function () {
return await render_runtime_html_asset(options);
},
script: async function () {
return await render_runtime_html_asset(options);
},
};
const renderer = renderers[normalized_render_tag_name];
if (!renderer) {
return { handled: false };
}
return {
handled: true,
result: await renderer(),
};
};
func.runtime = func.runtime || {};
func.runtime.ui = func.runtime.ui || {};
func.runtime.render = func.runtime.render || {};
func.runtime.widgets = func.runtime.widgets || {};
// Browser-only child-iteration helpers live here so tree entrypoints can stay focused.
func.runtime.render.get_xu_for_iterators = function ($elm) {
const elm_data = func.runtime.ui.get_data($elm);
const custom_iterator_key = elm_data.xuData.iterator_key;
const custom_iterator_val = elm_data.xuData.iterator_val;
return {
iterator_key: custom_iterator_key || '_FOR_KEY',
iterator_val: custom_iterator_val || '_FOR_VAL',
is_key_dynamic_field: true,
is_val_dynamic_field: true,
};
};
func.runtime.render.attach_iterate_info_to_children = function ($divP, iterate_info) {
const el = func.runtime.ui.get_first_node($divP);
const children = el?.children ? Array.from(el.children) : [];
for (let index = 0; index < children.length; index++) {
const child_data = func.runtime.ui.get_data(children[index]);
if (child_data?.xuData) {
child_data.xuData.iterate_info = iterate_info;
}
}
return $divP;
};
func.runtime.render.can_iterate_children = function (nodeP, is_mobile) {
if (!nodeP) {
return false;
}
if (!is_mobile && nodeP.busy) {
return false;
}
return true;
};
func.runtime.render.mark_node_busy = function (nodeP) {
if (!nodeP) {
return false;
}
nodeP.busy = true;
return true;
};
func.runtime.render.release_node_busy = function (nodeP, delay = 1000) {
if (!nodeP) {
return false;
}
setTimeout(function () {
nodeP.busy = false;
}, delay);
return true;
};
func.runtime.render.render_child_nodes = async function (options) {
if (!options.nodeP?.children) {
return options.$divP;
}
if (options.before_record_function) {
await options.before_record_function();
}
if (options.nodeP.children.length) {
const render_tasks = new Array(options.nodeP.children.length);
for (let index = 0; index < options.nodeP.children.length; index++) {
const child = options.nodeP.children[index];
render_tasks[index] = options.render_child(index, child);
}
await Promise.all(render_tasks);
}
return options.$divP;
};
func.runtime.render.iterate_children = async function (options) {
if (!func.runtime.render.can_iterate_children(options.nodeP, options.is_mobile)) return;
func.runtime.render.mark_node_busy(options.nodeP);
const done = async function ($divP) {
func.runtime.render.release_node_busy(options.nodeP);
return $divP;
};
if (!options.nodeP || !options.nodeP.children) {
return await done(options.$divP);
}
await func.runtime.render.render_child_nodes({
$divP: options.$divP,
nodeP: options.nodeP,
before_record_function: options.before_record_function,
render_child: options.render_child,
});
return await done(options.$divP);
};
func.runtime = func.runtime || {};
func.runtime.ui = func.runtime.ui || {};
func.runtime.render = func.runtime.render || {};
func.runtime.widgets = func.runtime.widgets || {};
// Browser-only render tree entrypoints live here so draw/cache helpers can stay focused.
func.runtime.render.create_tree_runtime = function (options) {
const render_node = options.nodeP || func.runtime.render.get_tree_source_node(options.treeP);
const render_context = func.runtime.render.get_screen_context(options.SESSION_ID, options.$container, options.paramsP, options.is_skeleton);
const prop = func.runtime.render.get_node_attributes(options.treeP || render_node);
const is_mobile = render_context.is_mobile ? true : false;
const hover_handlers = func.runtime.render.create_hover_handlers({
SESSION_ID: options.SESSION_ID,
is_skeleton: options.is_skeleton,
$container: options.$container,
_ds: render_context._ds,
paramsP: options.paramsP,
});
const include_hover_click = func.runtime.render.should_bind_hover_click(options.paramsP, options.parent_infoP);
const close_modal = async function (modal_id) {
return await func.runtime.ui.close_modal_session(options.SESSION_ID, modal_id);
};
const iterate_child = async function ($divP, nodeP, parent_infoP, $root_container, before_record_function) {
const child_tree = await func.runtime.render.ensure_tree_node({
SESSION_ID: options.SESSION_ID,
nodeP: nodeP || options.treeP || render_node,
parent_infoP,
paramsP: options.paramsP,
keyP: options.keyP,
parent_nodeP: render_node,
pathP: options.treeP?.meta?.path || [],
});
return await func.runtime.render.iterate_children({
$divP,
nodeP: child_tree,
is_mobile,
before_record_function,
render_child: async function (key, child) {
await options.render_child($divP, child, parent_infoP, key, render_node, $root_container);
},
});
};
return {
render_context,
prop,
is_mobile,
hover_handlers,
include_hover_click,
close_modal,
iterate_child,
};
};
func.runtime.render.draw_node = async function (options) {
const draw_ret = await func.runtime.render.run_draw_pipeline({
SESSION_ID: options.SESSION_ID,
$container: options.$container,
nodeP: options.nodeP,
parent_infoP: options.parent_infoP,
paramsP: options.paramsP,
jobNoP: options.jobNoP,
is_skeleton: options.is_skeleton,
keyP: options.keyP,
refreshed_ds: options.refreshed_ds,
parent_nodeP: options.parent_nodeP,
check_existP: options.check_existP,
$root_container: options.$root_container,
prop: options.prop,
element: options.treeP?.tagName || options.nodeP.tagName,
hover_handlers: options.hover_handlers,
include_hover_click: options.include_hover_click,
iterate_child: options.iterate_child,
buffered: !!glb.new_xu_render,
});
if (!glb.new_xu_render) {
return draw_ret.$div;
}
if (!draw_ret.$div) {
return draw_ret.$div;
}
return await func.runtime.render.finalize_buffered_draw({
SESSION_ID: options.SESSION_ID,
$div: draw_ret.$div,
temp_$div: draw_ret.temp_$div,
ret: draw_ret.ret,
paramsP: options.paramsP,
nodeP: options.nodeP,
});
};
func.runtime.render.render_tree = async function (treeP, renderer_context) {
if (!treeP) return;
const nodeP = func.runtime.render.get_tree_source_node(treeP);
const perf_end = func.runtime?.perf?.start?.(renderer_context.SESSION_ID, 'render_ui_tree');
func.runtime?.perf?.increment_map?.(renderer_context.SESSION_ID, 'render_node_counts', treeP.id || nodeP?.id || nodeP?.id_org || treeP.tagName || 'unknown');
try {
const tree_runtime = func.runtime.render.create_tree_runtime({
SESSION_ID: renderer_context.SESSION_ID,
$container: renderer_context.$container,
treeP,
nodeP,
parent_infoP: renderer_context.parent_infoP,
paramsP: renderer_context.paramsP,
jobNoP: renderer_context.jobNoP,
is_skeleton: renderer_context.is_skeleton,
keyP: renderer_context.keyP,
render_child: async function ($divP, child, parent_infoP, key, parentNodeP, rootContainerP) {
await func.runtime.render.render_tree(child, {
...renderer_context,
$container: $divP,
parent_infoP,
keyP: key,
refreshed_ds: null,
parent_nodeP: parentNodeP,
check_existP: null,
$root_container: rootContainerP,
});
},
});
const render_context = tree_runtime.render_context;
const _ds = render_context._ds;
const prop = tree_runtime.prop;
const hover_handlers = tree_runtime.hover_handlers;
const include_hover_click = tree_runtime.include_hover_click;
const close_modal = tree_runtime.close_modal;
const iterate_child = tree_runtime.iterate_child;
func.runtime.render.log_tree_debug({
SESSION_ID: renderer_context.SESSION_ID,
paramsP: renderer_context.paramsP,
nodeP,
_ds,
});
const special_render = await func.runtime.render.render_special_node({
SESSION_ID: renderer_context.SESSION_ID,
$container: renderer_context.$container,
$root_container: renderer_context.$root_container,
treeP,
nodeP,
parent_infoP: renderer_context.parent_infoP,
paramsP: renderer_context.paramsP,
jobNoP: renderer_context.jobNoP,
is_skeleton: renderer_context.is_skeleton,
keyP: renderer_context.keyP,
refreshed_ds: renderer_context.refreshed_ds,
parent_nodeP: renderer_context.parent_nodeP,
prop,
render_context,
hover_handlers,
iterate_child,
close_modal,
});
if (special_render.handled) {
func.runtime?.perf?.increment?.(renderer_context.SESSION_ID, 'render_special_node_hits');
return special_render.result;
}
return await func.runtime.render.draw_node({
SESSION_ID: renderer_context.SESSION_ID,
$container: renderer_context.$container,
$root_container: renderer_context.$root_container,
treeP,
nodeP,
parent_infoP: renderer_context.parent_infoP,
paramsP: renderer_context.paramsP,
jobNoP: renderer_context.jobNoP,
is_skeleton: renderer_context.is_skeleton,
keyP: renderer_context.keyP,
refreshed_ds: renderer_context.refreshed_ds,
parent_nodeP: renderer_context.parent_nodeP,
check_existP: renderer_context.check_existP,
prop,
hover_handlers,
include_hover_click,
iterate_child,
});
} finally {
perf_end?.();
}
};
func.runtime.render.render_ui_tree = async function (SESSION_ID, $container, nodeP, parent_infoP, paramsP, jobNoP, is_skeleton, keyP, refreshed_ds, parent_nodeP, check_existP, $root_container) {
if (!nodeP) return;
const treeP = await func.runtime.render.ensure_tree_node({
SESSION_ID,
nodeP,
parent_infoP,
paramsP,
keyP,
parent_nodeP,
});
const render_depth = func.runtime.render._html_script_render_depth || (func.runtime.render._html_script_render_depth = {});
render_depth[SESSION_ID] = (render_depth[SESSION_ID] || 0) + 1;
try {
return await func.runtime.render.render_tree(treeP, {
SESSION_ID,
$container,
parent_infoP,
paramsP,
jobNoP,
is_skeleton,
keyP,
refreshed_ds,
parent_nodeP,
check_existP,
$root_container,
});
} finally {
render_depth[SESSION_ID] = Math.max((render_depth[SESSION_ID] || 1) - 1, 0);
if (render_depth[SESSION_ID] === 0) {
await func.runtime.render.flush_html_script_queue?.();
delete render_depth[SESSION_ID];
}
}
};
func.runtime = func.runtime || {};
func.runtime.ui = func.runtime.ui || {};
func.runtime.render = func.runtime.render || {};
func.runtime.widgets = func.runtime.widgets || {};
// Browser-only attribute policy helpers live here so the phase engine can stay focused on execution order.
func.runtime.render.is_attribute_element_node = function (nodeP) {
if (!nodeP || !nodeP.attributes) {
return false;
}
if (nodeP.type === 'element') {
return true;
}
if (func.runtime.render.is_tree_node?.(nodeP)) {
return nodeP.kind !== 'text' && nodeP.kind !== 'placeholder';
}
const tag_name = typeof nodeP.tagName === 'string' ? nodeP.tagName.trim().toLowerCase() : '';
return !!tag_name && tag_name !== '#text' && tag_name !== '!doctype';
};
func.runtime.render.normalize_node_attributes = function (nodeP) {
if (!func.runtime.render.is_attribute_element_node(nodeP)) {
return {};
}
const attributes = nodeP.attributes;
const attribute_keys = Object.keys(attributes);
for (let index = 0; index < attribute_keys.length; index++) {
const key = attribute_keys[index];
let val = attributes[key];
if (key.substring(0, 6) === 'xu-exp') {
if (xu_isEmpty(val)) {
delete attributes[key];
continue;
}
const clean_key = key.split(':')[1];
if (typeof attributes[clean_key] !== 'undefined') {
delete attributes[clean_key];
}
}
if (glb.attr_abbreviations_arr.includes(key)) {
attributes[`xu-on:${key.substring(3)}`] = [
{
handler: 'custom',
props: {},
workflow: [
{
id: Date.now(),
data: {
action: 'update',
name: { value: val },
enabled: true,
},
props: {},
},
],
},
];
delete attributes[key];
}
}
const normalized_keys = Object.keys(attributes);
for (let index = 0; index < normalized_keys.length; index++) {
const key = normalized_keys[index];
let val = attributes[key];
val = func.runtime.render.fix_val_defaults(key, val);
if (typeof val === 'undefined' || val === null) {
delete attributes[key];
continue;
}
if (glb.solid_attributes.includes(key) && !val) {
delete attributes[key];
continue;
}
attributes[key] = val;
}
return attributes;
};
func.runtime.render.get_attribute_base_key = function (key) {
return key.split(':')[0];
};
func.runtime.render.get_expression_attribute_target = function (key) {
return key.split('xu-exp:')[1] || '';
};
func.runtime.render.is_panel_parameter_expression = function (nodeP, attr) {
if (nodeP?.tagName !== 'xu-panel' || !attr) {
return false;
}
return !['program', 'xu-render', 'xu-ref', 'xu-show'].includes(attr);
};
func.runtime.render.is_native_attribute = function (nodeTag, key) {
const new_key = func.runtime.render.get_attribute_base_key(key);
if (nodeTag === 'xu-panel' || nodeTag === 'xu-teleport') {
return false;
}
return !(new_key.substr(0, 2) === 'xu' && new_key.substr(2, 1) === '-');
};
func.runtime.render.should_abort = function ($container, ret) {
return !!(ret?.abort || func.runtime.ui.get_data($container)?.xuData?.pending_to_delete);
};
func.runtime.render.should_skip_phase_attribute = function (attr, execute_attributes = []) {
return glb.html5_events_handler.includes(attr) || execute_attributes.includes(attr);
};
func.runtime.render.has_attribute_or_expression = function (nodeP, attr) {
return !!(nodeP?.attributes?.hasOwnProperty(attr) || nodeP?.attributes?.hasOwnProperty(`xu-exp:${attr}`));
};
func.runtime.render.should_run_before_attribute = function (nodeP, attr) {
if (!func.runtime.render.has_attribute_or_expression(nodeP, attr)) {
return false;
}
if (!nodeP.attributes[`xu-exp:${attr}`] && nodeP?.attributes?.hasOwnProperty(attr) && typeof func.runtime.render.fix_val_defaults(attr, nodeP.attributes[attr]) === 'undefined') {
return false;
}
return true;
};
func.runtime.render.should_defer_runtime_attribute = function (nodeP, new_key) {
return new_key === 'xu-exp' || nodeP.attributes['xu-exp:' + new_key] || glb.run_xu_before.includes(new_key) || glb.run_xu_after.includes(new_key);
};
func.runtime.render.should_run_expression_attribute = function (attr, execute_attributes = [], done_exp, key) {
if (!attr) {
return false;
}
if (func.runtime.render.should_skip_phase_attribute(attr, execute_attributes)) {
return false;
}
if (done_exp?.has && done_exp.has(key)) {
return false;
}
if (done_exp?.includes && done_exp.includes(key)) {
return false;
}
return true;
};
func.runtime.render.should_run_after_attribute = function (nodeP, attr, execute_attributes = []) {
if (func.runtime.render.should_skip_phase_attribute(attr, execute_attributes)) {
return false;
}
if (!nodeP.attributes) {
return false;
}
return !!(nodeP.attributes[attr] || nodeP.attributes[`xu-exp:${attr}`]);
};
func.runtime.render.is_xu_tag = function (tagName) {
return typeof tagName === 'string' && tagName.substr(0, 3) === 'xu-';
};
func.runtime.render.execute_attribute = async function (options) {
return await func.runtime.render.execute_xu_function({
SESSION_ID: options.SESSION_ID,
is_skeleton: options.is_skeleton,
$root_container: options.$root_container,
nodeP: options.nodeP,
$container: options.$container,
paramsP: options.paramsP,
parent_infoP: options.parent_infoP,
jobNoP: options.jobNoP,
keyP: options.keyP,
parent_nodeP: options.parent_nodeP,
xu_func: options.xu_func,
$elm: options.$elm,
$live_elm: options.$live_elm,
val: options.value_obj,
is_init: options.is_init,
refreshed_ds: options.refreshed_ds,
handler_bundle: options.handler_bundle,
get_params_obj_new: func.runtime.program.get_params_obj,
});
};
func.runtime.render.set_native_dom_attribute = function ($elm, key, val) {
try {
func.runtime.ui.set_attr($elm, key, val);
return true;
} catch (err) {
console.error(err.message);
return false;
}
};
func.runtime.render.store_xu_attribute = function ($elm, key, val) {
try {
const elm_data = func.runtime.ui.get_data($elm);
if (elm_data?.xuAttributes) {
elm_data.xuAttributes[key] = val;
if (func.runtime.ui.update_refresh_dependency_entry) {
func.runtime.ui.update_refresh_dependency_entry($elm, key, val);
}
return true;
}
} catch (error) {
console.error('[xuda-runtime] caught xuda_runtime.browser.attributes.policy.js:176:', error);
console.error(error);
}
return false;
};
func.runtime.render.record_attribute_stat = function ($elm, key, value) {
const elm_data = func.runtime.ui.get_data($elm);
if (!elm_data?.xuData) {
return false;
}
if (!elm_data.xuData.debug_info) {
elm_data.xuData.debug_info = {};
}
if (!elm_data.xuData.debug_info.attribute_stat) {
elm_data.xuData.debug_info.attribute_stat = {};
}
elm_data.xuData.debug_info.attribute_stat[key] = value;
return true;
};
func.runtime.render.fix_val_defaults = function (key, val) {
let ret = val;
if (key === 'xu-render' && (typeof val === 'undefined' || val === null || val === '')) {
ret = true;
}
if (key === 'xu-show' && (typeof val === 'undefined' || val === null || val === '')) {
ret = true;
}
return ret;
};
func.runtime.render.get_attribute_phase_plan = function (nodeP) {
if (!func.runtime.render.is_attribute_element_node(nodeP)) {
return {
has_xu_attrs: false,
before_attrs: [],
attribute_entries: [],
expression_entries: [],
after_attrs: [],
};
}
if (nodeP._runtime_attribute_phase_plan && nodeP._runtime_attribute_phase_plan_source === nodeP.attributes) {
return nodeP._runtime_attribute_phase_plan;
}
const attributes = nodeP.attributes || {};
const attribute_entries = [];
const expression_entries = [];
const html_event_entries = [];
const attribute_keys = Object.keys(attributes);
for (let index = 0; index < attribute_keys.length; index++) {
const key = attribute_keys[index];
const val = attributes[key];
const new_key = func.runtime.render.get_attribute_base_key(key);
attribute_entries.push({
key,
val,
new_key,
is_native: func.runtime.render.is_native_attribute(nodeP.tagName, key),
should_defer: func.runtime.render.should_defer_runtime_attribute(nodeP, new_key),
xu_func: new_key === 'xu-on' ? 'xu-on' : new_key,
});
if (glb.html5_events_handler.includes(key)) {
html_event_entries.push({
key,
});
}
const exp_attr = func.runtime.render.get_expression_attribute_target(key);
if (exp_attr) {
if (func.runtime.render.is_panel_parameter_expression(nodeP, exp_attr)) {
continue;
}
expression_entries.push({
key,
attr: exp_attr,
val,
});
}
}
const plan = {
has_xu_attrs: !!(attributes['xu-attrs'] || attributes['xu-exp:xu-attrs']),
before_attrs: glb.run_xu_before.filter(function (attr) {
return func.runtime.render.should_run_before_attribute(nodeP, attr);
}),
attribute_entries,
html_event_entries,
expression_entries,
after_attrs: glb.run_xu_after.filter(function (attr) {
return func.runtime.render.has_attribute_or_expression(nodeP, attr);
}),
};
nodeP._runtime_attribute_phase_plan_source = nodeP.attributes;
nodeP._runtime_attribute_phase_plan = plan;
return plan;
};
func.runtime = func.runtime || {};
func.runtime.ui = func.runtime.ui || {};
func.runtime.render = func.runtime.render || {};
func.runtime.widgets = func.runtime.widgets || {};
// Browser-only attribute reading helpers live here so phase execution can stay focused.
func.runtime.render.create_attribute_reader = function (options) {
const done_exp = new Set();
const attr_value_cache = {};
const xu_exp_cache = {};
const elm_data = func.runtime.ui.get_data(options.$elm);
const xuData = elm_data?.xuData;
const get_xuExp = async function (attrib) {
if (Object.prototype.hasOwnProperty.call(xu_exp_cache, attrib)) {
return xu_exp_cache[attrib];
}
if (options.is_skeleton) return;
if (glb.new_xu_render) {
if (xuData && !xuData.attr_exp_info) {
xuData.attr_exp_info = {};
}
}
const attr = `xu-exp:${attrib}`;
if (!options.nodeP?.attributes?.hasOwnProperty(attr)) return;
const exp = options.nodeP.attributes[attr];
const res = await func.expression.get(options.SESSION_ID, exp, options.paramsP.dsSessionP, 'UI Attr EXP', options._ds.currentRecordId);
if (glb.new_xu_render && xuData) {
xuData.attr_exp_info[attrib] = res;
}
done_exp.add(attr);
xu_exp_cache[attrib] = res.result;
return xu_exp_cache[attrib];
};
const get_attr_value = async function (key) {
if (Object.prototype.hasOwnProperty.call(attr_value_cache, key)) {
return attr_value_cache[key];
}
let ret = func.runtime.render.fix_val_defaults(key, options.nodeP.attributes[key]);
if (options.nodeP?.attributes?.hasOwnProperty(`xu-exp:${key}`)) {
ret = await get_xuExp(key);
}
attr_value_cache[key] = ret;
return attr_value_cache[key];
};
return {
done_exp,
get_attr_value,
};
};
func.runtime = func.runtime || {};
func.runtime.ui = func.runtime.ui || {};
func.runtime.render = func.runtime.render || {};
func.runtime.widgets = func.runtime.widgets || {};
// Browser-only attribute phase execution lives here so policy and entrypoint concerns can stay focused.
func.runtime.render.apply_attribute_phases = async function (options) {
let _ret = {};
if (!func.runtime.render.is_attribute_element_node(options.nodeP)) return _ret;
func.runtime.render.normalize_node_attributes(options.nodeP);
const phase_plan = func.runtime.render.get_attribute_phase_plan(options.nodeP);
if (phase_plan.has_xu_attrs) {
const attr = 'xu-attrs';
await func.runtime.render.execute_attribute({
SESSION_ID: options.SESSION_ID,
is_skeleton: options.is_skeleton,
$root_container: options.$root_container,
nodeP: options.nodeP,
$container: options.$container,
paramsP: options.paramsP,
parent_infoP: options.parent_infoP,
jobNoP: options.jobNoP,
keyP: options.keyP,
parent_nodeP: options.parent_nodeP,
xu_func: attr,
$elm: options.$elm,
$live_elm: options.$live_elm,
value_obj: {
key: attr,
value: await options.get_attr_value(attr),
},
is_init: options.is_init,
handler_bundle: options.handler_bundle,
});
}
if (!xu_isEmpty(options.nodeP.attributes)) {
for (let index = 0; index < phase_plan.before_attrs.length; index++) {
const attr = phase_plan.before_attrs[index];
if (func.runtime.render.should_abort(options.$container, _ret)) break;
if (func.runtime.render.should_skip_phase_attribute(attr, options.execute_attributes)) continue;
const ret = await func.runtime.render.execute_attribute({
SESSION_ID: options.SESSION_ID,
is_skeleton: options.is_skeleton,
$root_container: options.$root_container,
nodeP: options.nodeP,
$container: options.$container,
paramsP: options.paramsP,
parent_infoP: options.parent_infoP,
jobNoP: options.jobNoP,
keyP: options.keyP,
parent_nodeP: options.parent_nodeP,
xu_func: attr,
$elm: options.$elm,
$live_elm: options.$live_elm,
value_obj: {
key: attr,
value: await options.get_attr_value(attr),
},
is_init: options.is_init,
handler_bundle: options.handler_bundle,
});
_ret = Object.assign(_ret, ret);
}
}
for (let index = 0; index < phase_plan.attribute_entries.length; index++) {
const entry = phase_plan.attribute_entries[index];
const key = entry.key;
const val = entry.val;
if (func.runtime.render.should_abort(options.$container, _ret)) break;
if (func.runtime.render.should_skip_phase_attribute(key, options.execute_attributes)) continue;
if (entry.is_native) {
func.runtime.render.set_native_dom_attribute(options.$elm, key, val);
continue;
}
func.runtime.render.store_xu_attribute(options.$elm, key, val);
if (entry.should_defer) {
continue;
}
if (entry.new_key === 'xu-on') {
const ret = await func.runtime.render.execute_attribute({
SESSION_ID: options.SESSION_ID,
is_skeleton: options.is_skeleton,
$root_container: options.$root_container,
nodeP: options.nodeP,
$container: options.$container,
paramsP: options.paramsP,
parent_infoP: options.parent_infoP,
jobNoP: options.jobNoP,
keyP: options.keyP,
parent_nodeP: options.parent_nodeP,
xu_func: 'xu-on',
$elm: options.$elm,
$live_elm: options.$live_elm,
value_obj: {
key: key,
value: await options.get_attr_value(key),
},
is_init: options.is_init,
refreshed_ds: options.refreshed_ds,
handler_bundle: options.handler_bundle,
});
_ret = Object.assign(_ret, ret);
continue;
}
const ret = await func.runtime.render.execute_attribute({
SESSION_ID: options.SESSION_ID,
is_skeleton: options.is_skeleton,
$root_container: options.$root_container,
nodeP: options.nodeP,
$container: options.$container,
paramsP: options.paramsP,
parent_infoP: options.parent_infoP,
jobNoP: options.jobNoP,
keyP: options.keyP,
parent_nodeP: options.parent_nodeP,
xu_func: entry.xu_func,
$elm: options.$elm,
$live_elm: options.$live_elm,
value_obj: {
key: key,
value: await options.get_attr_value(key),
},
is_init: options.is_init,
refreshed_ds: options.refreshed_ds,
handler_bundle: options.handler_bundle,
});
_ret = Object.assign(_ret, ret);
}
for (let index = 0; index < phase_plan.expression_entries.length; index++) {
const entry = phase_plan.expression_entries[index];
const key = entry.key;
const val = entry.val;
if (func.runtime.render.should_abort(options.$container, _ret)) break;
const attr = entry.attr;
if (!func.runtime.render.should_run_expression_attribute(attr, options.execute_attributes, options.done_exp, key)) {
continue;
}
const ret = await func.runtime.render.execute_attribute({
SESSION_ID: options.SESSION_ID,
is_skeleton: options.is_skeleton,
$root_container: options.$root_container,
nodeP: options.nodeP,
$container: options.$container,
paramsP: options.paramsP,
parent_infoP: options.parent_infoP,
jobNoP: options.jobNoP,
keyP: options.keyP,
parent_nodeP: options.parent_nodeP,
xu_func: 'xu-exp',
$elm: options.$elm,
$live_elm: options.$live_elm,
value_obj: {
key: attr,
value: val,
},
is_init: true,
refreshed_ds: options.refreshed_ds,
handler_bundle: options.handler_bundle,
});
_ret = Object.assign(_ret, ret);
}
for (let index = 0; index < phase_plan.after_attrs.length; index++) {
const attr = phase_plan.after_attrs[index];
if (func.runtime.render.should_abort(options.$container, _ret)) break;
if (!func.runtime.render.should_run_after_attribute(options.nodeP, attr, options.execute_attributes)) continue;
const ret = await func.runtime.render.execute_attribute({
SESSION_ID: options.SESSION_ID,
is_skeleton: options.is_skeleton,
$root_container: options.$root_container,
nodeP: options.nodeP,
$container: options.$container,
paramsP: options.paramsP,
parent_infoP: options.parent_infoP,
jobNoP: options.jobNoP,
keyP: options.keyP,
parent_nodeP: options.parent_nodeP,
xu_func: attr,
$elm: options.$elm,
$live_elm: options.$live_elm,
value_obj: {
key: attr,
value: await options.get_attr_value(attr),
},
is_init: options.is_init,
refreshed_ds: options.refreshed_ds,
handler_bundle: options.handler_bundle,
});
_ret = Object.assign(_ret, ret);
}
return _ret;
};
func.runtime = func.runtime || {};
func.runtime.ui = func.runtime.ui || {};
func.runtime.render = func.runtime.render || {};
func.runtime.widgets = func.runtime.widgets || {};
// Browser-only attribute entrypoint lives here so reader and phase execution can evolve independently.
func.runtime.render.normalize_set_attributes_options = function (...args) {
if (typeof args[0] === 'object' && args[0] !== null && !Array.isArray(args[0])) {
return {
...args[0],
$live_elm: args[0].$live_elm || args[0].$elm,
};
}
const [SESSION_ID, is_skeleton, $root_container, nodeP, $container, paramsP, parent_infoP, jobNoP, keyP, parent_nodeP, $elm, is_init, execute_attributes = [], refreshed_ds] = args;
return {
SESSION_ID,
is_skeleton,
$root_container,
nodeP,
$container,
paramsP,
parent_infoP,
jobNoP,
keyP,
parent_nodeP,
$elm,
$live_elm: $elm,
is_init,
execute_attributes,
refreshed_ds,
};
};
func.runtime.render.set_attributes_new = async function (...args) {
const options = func.runtime.render.normalize_set_attributes_options(...args);
const _ds = SESSION_OBJ[options.SESSION_ID].DS_GLB[options.paramsP.dsSessionP];
if (!_ds) return { abort: true };
if (func.runtime.ui.prune_stale_refresh_dependencies) {
func.runtime.ui.prune_stale_refresh_dependencies(options.$elm, options.nodeP?.attributes || {});
}
const attr_reader = func.runtime.render.create_attribute_reader({
SESSION_ID: options.SESSION_ID,
is_skeleton: options.is_skeleton,
$elm: options.$elm,
nodeP: options.nodeP,
paramsP: options.paramsP,
_ds,
});
const handler_bundle = func.runtime.render.build_xu_handlers({
SESSION_ID: options.SESSION_ID,
is_skeleton: options.is_skeleton,
$root_container: options.$root_container,
nodeP: options.nodeP,
$container: options.$container,
paramsP: options.paramsP,
parent_infoP: options.parent_infoP,
jobNoP: options.jobNoP,
keyP: options.keyP,
parent_nodeP: options.parent_nodeP,
$elm: options.$elm,
$live_elm: options.$live_elm,
is_init: options.is_init,
refreshed_ds: options.refreshed_ds,
get_params_obj_new: func.runtime.program.get_params_obj,
}, _ds);
const _ret = await func.runtime.render.apply_attribute_phases({
SESSION_ID: options.SESSION_ID,
is_skeleton: options.is_skeleton,
$root_container: options.$root_container,
nodeP: options.nodeP,
$container: options.$container,
paramsP: options.paramsP,
parent_infoP: options.parent_infoP,
jobNoP: options.jobNoP,
keyP: options.keyP,
parent_nodeP: options.parent_nodeP,
$elm: options.$elm,
$live_elm: options.$live_elm,
is_init: options.is_init,
execute_attributes: options.execute_attributes || [],
refreshed_ds: options.refreshed_ds,
done_exp: attr_reader.done_exp,
get_attr_value: attr_reader.get_attr_value,
handler_bundle,
});
const phase_plan = func.runtime.render.get_attribute_phase_plan(options.nodeP);
for (let index = 0; index < phase_plan.html_event_entries.length; index++) {
const key = phase_plan.html_event_entries[index].key;
if (func.runtime.render.should_abort(options.$container, _ret)) break;
func.runtime.ui.set_attr(options.$elm, key, await attr_reader.get_attr_value(key));
}
return _ret;
};
func.runtime = func.runtime || {};
func.runtime.ui = func.runtime.ui || {};
func.runtime.render = func.runtime.render || {};
func.runtime.widgets = func.runtime.widgets || {};
// Browser-only data-bound xu handlers live here so the main handler dispatcher can stay focused.
func.runtime.render.handle_xu_ref = async function (options) {
if (!options.val.value) {
return {};
}
func.UI.update_xu_ref(options.SESSION_ID, options.dsSession || options.paramsP.dsSessionP, options.val.value, options.$elm);
const targetNode = func.runtime.ui.get_first_node(options.$elm);
if (!targetNode) {
return {};
}
const target_data = func.runtime.ui.get_data(options.$elm);
if (target_data?.xuData?.xu_ref_observer) {
target_data.xuData.xu_ref_observer.disconnect();
}
// Build-400 parity: refresh on ANY mutation. The xu-ref refresh loop is prevented upstream in
// update_xu_ref (clean snapshot, empty-transient guard, $elm-gated change detection), so cosmetic
// DOM-only mutations resolve to "no change" and never cascade.
// Filtering the mutations here was a redundant second mechanism and risked suppressing a real
// refresh; build 400's observer is unfiltered. The disconnect above (absent in build 400) still
// prevents observers accumulating across re-renders.
const observer = new MutationObserver(function () {
// Ignore the DOM moves the preserve mechanism makes itself (detach/reattach of a [data-xu-preserve]
// node across a panel re-render). They are internal bookkeeping, not a real data/user change, and
// reacting to them would re-enter refresh_screen -> re-render -> reattach -> ... an infinite loop.
if (func.runtime.ui.__xu_preserve_suppress) return;
func.runtime.ui.refresh_xu_attributes({
SESSION_ID: options.SESSION_ID,
fields_arr: [options.val.value],
});
});
observer.observe(targetNode, { attributes: true, childList: true, subtree: true });
if (target_data?.xuData) {
target_data.xuData.xu_ref_observer = observer;
}
return {};
};
func.runtime.render.handle_xu_bind = async function (options) {
if (options.is_skeleton) return {};
const $elm = func.runtime?.ui?.get_preferred_live_element ? func.runtime.ui.get_preferred_live_element(options.$elm) : options.$elm;
const elm_data = func.runtime.ui.get_data($elm);
const xuData = elm_data?.xuData;
const bind_expression =
typeof options?.val?.value === 'string'
? options.val.value
: elm_data?.xuAttributes?.['xu-bind'] || func.runtime.ui.get_attr($elm, 'xu-bind');
if (!xuData?.paramsP) {
return {};
}
if (!bind_expression) {
return {};
}
let val_is_reference_field = false;
let _prog_id = xuData.paramsP.prog_id;
let _dsP = xuData.paramsP.dsSessionP;
let is_dynamic_field = false;
let field_prop;
let bind_field_id;
const _bind_elm_node = func.runtime.ui.get_first_node($elm);
const input_field_type = _bind_elm_node?.type || func.runtime.ui.get_attr($elm, 'type');
const bind_ui_id = xuData.ui_id || func.runtime.ui.get_attr($elm, 'xu-ui-id');
const get_bind_targets = function () {
const $root = func.runtime.ui.get_refresh_index_root?.(options.SESSION_ID) || func.runtime.ui.get_root_element?.(options.SESSION_ID) || func.runtime.ui._wrap_matches([document.body]);
const live_targets = [];
const seen_nodes = new Set();
const add_candidate = function (node) {
if (!node || seen_nodes.has(node)) {
return;
}
const target_data = func.runtime.ui.get_data(node);
if (!node.isConnected || target_data?.xuData?.pending_to_delete) {
return;
}
seen_nodes.add(node);
live_targets.push(node);
};
if (bind_ui_id && options.SESSION_ID && func.runtime?.ui?.find_refresh_elements_by_attr) {
const ui_id_targets = func.runtime.ui.find_refresh_elements_by_attr($root, 'xu-ui-id', bind_ui_id).toArray();
for (let index = 0; index < ui_id_targets.length; index++) {
add_candidate(ui_id_targets[index]);
}
}
const runtime_nodes = func.runtime?.ui?.get_refresh_index_elements
? func.runtime.ui.get_refresh_index_elements(options.SESSION_ID, $root).toArray()
: func.runtime.ui.find_by_selector($root, '[xu-ui-id]').toArray();
const target_parent_ui_id = xuData.parent_element_ui_id;
const target_node_id = xuData.nodeid;
const target_recordid = xuData.recordid;
const target_prog_id = xuData.paramsP?.prog_id;
for (let index = 0; index < runtime_nodes.length; index++) {
const node = runtime_nodes[index];
const node_data = func.runtime.ui.get_data(node);
const node_xu_data = node_data?.xuData;
if (!node_xu_data) {
continue;
}
if (target_node_id && node_xu_data.nodeid !== target_node_id) {
continue;
}
if (target_parent_ui_id && node_xu_data.parent_element_ui_id !== target_parent_ui_id) {
continue;
}
if (target_prog_id && node_xu_data.paramsP?.prog_id !== target_prog_id) {
continue;
}
if (typeof target_recordid !== 'undefined' && target_recordid !== null && node_xu_data.recordid !== target_recordid) {
continue;
}
const node_bind_expression = node_data?.xuAttributes?.['xu-bind'] || func.runtime.ui.get_attr(node, 'xu-bind');
if (node_bind_expression !== bind_expression) {
continue;
}
add_candidate(node);
}
if (!live_targets.length) {
const _node = func.runtime.ui.get_first_node($elm);
return func.runtime.ui._wrap_matches(_node ? [_node] : []);
}
for (let index = 0; index < live_targets.length; index++) {
const node = live_targets[index];
const target_data = func.runtime.ui.get_data(node);
if (!node?.isConnected || target_data?.xuData?.pending_to_delete) {
continue;
}
add_candidate(node);
}
if (!live_targets.length) {
const _node = func.runtime.ui.get_first_node($elm);
return func.runtime.ui._wrap_matches(_node ? [_node] : []);
}
const target_nodes = live_targets;
const visible_targets = [];
for (let index = 0; index < target_nodes.length; index++) {
const node = target_nodes[index];
if (node.getClientRects?.().length && !node.hidden) {
visible_targets.push(node);
}
}
return func.runtime.ui._wrap_matches(visible_targets.length ? visible_targets : live_targets);
};
try {
const bind_field = await func.runtime.bind.resolve_field(options.SESSION_ID, _prog_id, _dsP, bind_expression.split('.')[0], xuData.iterate_info);
bind_field_id = bind_field.bind_field_id;
field_prop = bind_field.field_prop;
is_dynamic_field = bind_field.is_dynamic_field;
_dsP = bind_field.dsSessionP;
_prog_id = bind_field.prog_id;
val_is_reference_field = true;
} catch (err) {
console.error(err?.message || err);
return {};
}
const bind = func.runtime.bind.get_adapter(options.SESSION_ID);
const get_changed_node = function (event) {
const event_target = func.runtime.bind.get_bind_value_node(event?.target);
if (func.runtime.bind.is_value_node(event_target) && event_target.isConnected) {
return event_target;
}
const current_target = func.runtime.bind.get_bind_value_node(event?.currentTarget);
if (current_target?.nodeType && current_target.isConnected) {
return current_target;
}
return func.runtime.bind.get_bind_value_node(options.$elm);
};
const get_changed_input_type = function (node) {
return (node?.type || node?.getAttribute?.('type') || input_field_type || '').toLowerCase();
};
const field_changed = function (event) {
const pending_update = (async function () {
const changed_node = get_changed_node(event);
if (!changed_node) {
return;
}
if (changed_node.tagName?.toLowerCase?.() === 'select') {
changed_node.__xuda_select_last_user_change_ts = Date.now();
}
const changed_input_type = get_changed_input_type(changed_node);
const _ds = SESSION_OBJ[options.SESSION_ID].DS_GLB[_dsP];
const field_type = func.runtime.bind.get_field_type(field_prop);
if (field_type === 'array' && changed_input_type === 'checkbox' && val_is_reference_field) {
const arr_value_before_cast = [...(await func.datasource.get_value(options.SESSION_ID, bind_field_id, _dsP, _ds.currentRecordId)).ret.value];
const value_from_getter = bind.getter(changed_node);
const value = func.runtime.bind.toggle_array_value(arr_value_before_cast, value_from_getter);
const datasource_changes = func.runtime.bind.build_datasource_changes(_dsP, _ds.currentRecordId, bind_field_id, value);
return await func.datasource.update(options.SESSION_ID, datasource_changes);
}
if (field_type === 'array' && changed_input_type === 'radio' && val_is_reference_field) {
const value_from_getter = bind.getter(changed_node);
const datasource_changes = func.runtime.bind.build_datasource_changes(_dsP, _ds.currentRecordId, bind_field_id, [value_from_getter]);
return await func.datasource.update(options.SESSION_ID, datasource_changes);
}
const raw_value = func.runtime.bind.normalize_raw_value(changed_node, field_prop, bind.getter(changed_node));
const value = await func.runtime.bind.get_cast_value(options.SESSION_ID, field_prop, changed_input_type, raw_value);
func.runtime.bind.remember_select_numeric_context(changed_node, field_type, value);
if (!_ds.currentRecordId) return;
const iterate_info = xuData.iterate_info;
const is_iterate_field = is_dynamic_field && iterate_info && (iterate_info.iterator_val === bind_field_id || iterate_info.iterator_key === bind_field_id);
if (!is_iterate_field) {
const datasource_changes = func.runtime.bind.build_datasource_changes(_dsP, _ds.currentRecordId, bind_field_id, value);
await func.datasource.update(options.SESSION_ID, datasource_changes);
}
await func.runtime.bind.update_reference_source_array({
SESSION_ID: options.SESSION_ID,
dsSessionP: _dsP,
currentRecordId: _ds.currentRecordId,
iterate_info,
bind_field_id,
field_prop,
val_is_reference_field,
input_field_type: changed_input_type,
expression_value: bind_expression,
value,
});
await func.datasource.update_changes_for_out_parameter(options.SESSION_ID, _dsP, _ds.parentDataSourceNo);
})().catch(function (error) {
console.error(error);
});
return func.runtime.bind.track_pending_update(options.SESSION_ID, pending_update);
};
const bind_targets = get_bind_targets();
const target_nodes = bind_targets.toArray();
for (let index = 0; index < target_nodes.length; index++) {
const target = target_nodes[index];
const target_data = func.runtime.ui.get_data(target);
const listener_node = func.runtime.bind.get_bind_value_node(target) || target;
const bind_listener_mode = func.runtime.bind.should_use_live_text_listener(listener_node) ? 'live_text' : 'default';
if (
!target_data?.xuData ||
(
target_data.xuData.bind_listener_attached &&
target_data.xuData.bind_listener_mode === bind_listener_mode &&
target_data.xuData.bind_listener_node === listener_node
)
) {
continue;
}
bind.listener(listener_node, field_changed);
target_data.xuData.bind_listener_attached = true;
target_data.xuData.bind_listener_mode = bind_listener_mode;
target_data.xuData.bind_listener_node = listener_node;
}
const set_value = async function () {
const _ds = SESSION_OBJ[options.SESSION_ID].DS_GLB[_dsP];
if (!_ds) return;
const target_record_id = xuData.recordid || _ds.currentRecordId;
if (!target_record_id) return;
let value;
try {
if (val_is_reference_field) {
const iter = xuData.iterate_info;
if (iter && is_dynamic_field && (iter.iterator_val === bind_field_id || iter.iterator_key === bind_field_id)) {
value = iter.iterator_val === bind_field_id ? iter._val : iter._key;
} else {
const resolved_value = await func.datasource.get_value(options.SESSION_ID, bind_field_id, _dsP, target_record_id);
if (resolved_value?.found) {
value = resolved_value.ret.value;
} else {
value = func.runtime.bind.get_source_value(_ds, bind_field_id, is_dynamic_field);
}
}
value = func.runtime.bind.format_display_value($elm, field_prop, bind_field_id, bind_expression, value, input_field_type);
} else {
value = bind_expression;
}
if (typeof value === 'undefined') return;
const live_bind_targets = get_bind_targets().toArray();
for (let index = 0; index < live_bind_targets.length; index++) {
const elm = func.runtime.bind.get_bind_value_node(live_bind_targets[index]) || live_bind_targets[index];
if (!elm) {
continue;
}
const target_input_type = elm.type || input_field_type;
const is_focused_live_text_input = func.runtime.bind.should_use_live_text_listener(elm) && document.activeElement === elm;
if (is_focused_live_text_input && typeof elm.value !== 'undefined' && !xu_isEqual(elm.value, value === null ? '' : String(value))) {
continue;
}
switch (target_input_type) {
case 'radio':
bind.setter(elm, value);
elm.checked = elm.value === String(value);
break;
case 'checkbox':
bind.setter(elm, value);
elm.checked = !!value;
break;
default:
if (elm.tagName?.toLowerCase?.() === 'select' && func.runtime.bind.set_select_value(elm, value, func.runtime.bind.get_field_type(field_prop))) {
break;
}
bind.setter(elm, value);
if (typeof elm.value !== 'undefined') {
elm.value = value === null ? '' : String(value);
}
break;
}
}
} catch (err) {
console.error(err);
}
};
const bind_refresh_event = 'xu-bind-refresh.' + _dsP.toString();
const bind_handler_key = '_xuda_bind_' + (bind_ui_id || bind_field_id || 'bind');
if (document.body[bind_handler_key]) {
document.body.removeEventListener(bind_refresh_event, document.body[bind_handler_key]);
}
document.body[bind_handler_key] = async () => {
await set_value();
};
document.body.addEventListener(bind_refresh_event, document.body[bind_handler_key]);
await set_value();
return {};
};
func.runtime.render.apply_xu_class = async function (options) {
try {
const raw_value = options?.val?.value;
const xuData = func.runtime.ui.get_data(options.$elm)?.xuData;
if (typeof raw_value === 'string') {
const trimmed = raw_value.trim();
const looks_like_object = trimmed.startsWith('{') && trimmed.endsWith('}');
if (!looks_like_object) {
func.runtime.render.apply_expression_class(options.$elm, raw_value);
xuData.debug_info.attribute_stat['xu-class'] = func.runtime.ui.get_first_node(options.$elm)?.className || func.runtime.ui.get_attr(options.$elm, 'class');
return {};
}
}
const classes_obj = typeof raw_value === 'string' ? JSON5.parse(raw_value) : Object.assign({}, {}, raw_value);
if (typeof classes_obj !== 'object' || classes_obj === null || Array.isArray(classes_obj)) {
throw new Error('xu-class expects an object map or a class string');
}
const class_names = Object.keys(classes_obj);
for (let index = 0; index < class_names.length; index++) {
const cla = class_names[index];
const cond = classes_obj[cla];
const res = await func.expression.get(
options.SESSION_ID,
cond,
options.paramsP.dsSessionP,
'UI Attr EXP',
xuData.currentRecordId,
null,
null,
null,
null,
null,
xuData.iterate_info,
);
if (res.result) {
func.runtime.ui.add_class(options.$elm, cla);
} else {
func.runtime.ui.remove_class(options.$elm, cla);
}
}
xuData.debug_info.attribute_stat['xu-class'] = func.runtime.ui.get_first_node(options.$elm)?.className || func.runtime.ui.get_attr(options.$elm, 'class');
return {};
} catch (e) {
await func.runtime.render.report_xu_runtime_error(
{
...options,
xu_func: 'xu-class',
val: {
key: 'xu-class',
value: options?.val?.value,
},
},
e,
'xu-class has invalid syntax',
);
return { abort: true };
}
};
func.runtime = func.runtime || {};
func.runtime.ui = func.runtime.ui || {};
func.runtime.render = func.runtime.render || {};
func.runtime.widgets = func.runtime.widgets || {};
// Browser-only iteration handlers live here so xu-for flow can evolve separately from data binding.
// XU_PERF keyed reuse -------------------------------------------------------
// execute_xu_for stashes the existing row elements here (instead of tearing
// them down) so handle_xu_for can reuse unchanged rows. Any stash entry that
// is not consumed gets removed by execute_xu_for right after the re-render,
// so a mismatch degrades to the legacy full rebuild, never to duplicate or
// stale rows.
func.runtime.render.xu_for_reuse_stash = func.runtime.render.xu_for_reuse_stash || new Map();
// Stable identity for a row across renders: prefer the item's own id, fall
// back to the position for id-less objects, or the value itself for scalars.
func.runtime.render.get_xu_row_key = function (_val, idx) {
if (_val && typeof _val === 'object') {
const id = typeof _val.id !== 'undefined' ? _val.id : (typeof _val._id !== 'undefined' ? _val._id : _val.ROWID);
return typeof id === 'undefined' ? 'xidx:' + idx : 'xid:' + String(id);
}
return 'xval:' + String(_val);
};
// Value snapshot taken at render time; a row is reused only when its current
// item deep-equals the snapshot. Unsnapshottable values never compare equal,
// which forces a safe re-render.
func.runtime.render.snap_xu_row = function (_val) {
if (_val === null || typeof _val !== 'object') return _val;
try {
return structuredClone(_val);
} catch (e) {
return undefined;
}
};
// Resolve the LIVE container for an xu-for whose captured reference went stale.
// The row handler is asynchronous, so a concurrent panel refresh can replace its
// subtree while rows are rendering. The stable program node id is the only
// reliable link between the detached container and the visible replacement.
func.runtime.render.resolve_live_xu_for_container = function (SESSION_ID, $container, row_node_id) {
const container_data = func.runtime.ui.get_data($container)?.xuData || {};
const container_ui_id = func.runtime.ui.get_attr($container, 'xu-ui-id');
const root_node = document.body;
if (container_ui_id && root_node?.querySelector) {
const escaped_ui_id = typeof CSS !== 'undefined' && CSS.escape ? CSS.escape(container_ui_id) : container_ui_id;
const by_id = root_node.querySelector(`[xu-ui-id="${escaped_ui_id}"]`);
if (by_id && by_id.isConnected) return { node: by_id, via: 'xu-ui-id' };
}
if (container_data.nodeid && func.runtime.ui.get_refresh_indexed_elements_by_node_id) {
const indexed = func.runtime.ui.get_refresh_indexed_elements_by_node_id(SESSION_ID, container_data.nodeid).toArray();
for (let indexed_i = 0; indexed_i < indexed.length; indexed_i++) {
const candidate = indexed[indexed_i];
if (!candidate?.isConnected) continue;
const candidate_data = func.runtime.ui.get_data(func.runtime.ui._wrap_matches([candidate]))?.xuData || {};
if (typeof container_data.recordid === 'undefined' || candidate_data.recordid === container_data.recordid) {
return { node: candidate, via: 'refresh-index' };
}
}
}
if (root_node?.querySelectorAll) {
const all_ui_elements = root_node.querySelectorAll('[xu-ui-id]');
let any_record_fallback = null;
let row_parent_fallback = null;
for (let scan_i = 0; scan_i < all_ui_elements.length; scan_i++) {
const el = all_ui_elements[scan_i];
if (!el.isConnected) continue;
const el_data = func.runtime.ui.get_data(func.runtime.ui._wrap_matches([el]))?.xuData;
if (!el_data) continue;
if (container_data.nodeid && el_data.nodeid === container_data.nodeid) {
if (typeof container_data.recordid === 'undefined' || el_data.recordid === container_data.recordid) {
return { node: el, via: 'dom-scan' };
}
if (!any_record_fallback) any_record_fallback = el;
}
// A visible row rendered from this template identifies its live parent even
// when the container metadata disappeared with the stale subtree.
if (!row_parent_fallback && row_node_id && el_data.nodeid === row_node_id && el.parentElement) {
row_parent_fallback = el.parentElement;
}
}
if (any_record_fallback) return { node: any_record_fallback, via: 'dom-scan-anyrecord' };
if (row_parent_fallback) return { node: row_parent_fallback, via: 'row-parent' };
}
return { node: null, via: null };
};
// A later invocation for the same row template makes earlier deferred work stale.
func.runtime.render._xu_for_latest_run = func.runtime.render._xu_for_latest_run || new Map();
func.runtime.render.handle_xu_for = async function (options) {
if (options.parent_infoP?.iterate_info) return {};
if (!options.data.value) return {};
try {
const $live_elm = options.$live_elm || options.$elm;
const _run_token = (func.runtime.render._xu_for_latest_run.get(options.nodeP?.id) || 0) + 1;
func.runtime.render._xu_for_latest_run.set(options.nodeP?.id, _run_token);
const _is_latest_run = function () {
return func.runtime.render._xu_for_latest_run.get(options.nodeP?.id) === _run_token;
};
// Adopt a visible replacement before rendering. Without this, all rows land
// in a detached copy and the visible list remains frozen at its first row.
try {
const _container_node = func.runtime.ui.get_first_node(options.$container);
let _pending_attach_buffer = false;
if (_container_node && !_container_node.isConnected) {
let _detached_root = _container_node;
while (_detached_root.parentNode && _detached_root.parentNode.nodeType === 1) _detached_root = _detached_root.parentNode;
_pending_attach_buffer = _detached_root.tagName === 'TEMPLATE' || _detached_root.tagName === 'TMP';
}
if ((!_container_node || !_container_node.isConnected) && !_pending_attach_buffer) {
const _resolved = func.runtime.render.resolve_live_xu_for_container(options.SESSION_ID, options.$container, options.nodeP?.id);
if (_resolved.node && func.runtime.ui._wrap_matches) {
options.$container = func.runtime.ui._wrap_matches([_resolved.node]);
const _adopted_children = func.runtime.ui.get_children(options.$container);
let _cleared = 0;
for (let stale_index = 0; stale_index < _adopted_children.length; stale_index++) {
const _stale_child = _adopted_children[stale_index];
if (func.runtime.ui.get_data(_stale_child)?.xuData?.nodeid === options.nodeP?.id) {
func.runtime.ui.remove(_stale_child);
_cleared++;
}
}
console.log('[xufor-fix] adopted live container via ' + _resolved.via + ', cleared ' + _cleared + ' stale rows');
}
}
} catch (stale_resolution_error) {
console.log('[xufor-fix] resolution error', stale_resolution_error);
}
const { arr, reference_source_obj } = await func.runtime.render.resolve_xu_for_source(options.SESSION_ID, options.paramsP.dsSessionP, options.data.value);
const { iterator_key, iterator_val, is_key_dynamic_field, is_val_dynamic_field } = func.runtime.render.get_xu_for_iterators(options.$elm);
const _progFields = await func.datasource.get_progFields(options.SESSION_ID, options.paramsP.dsSessionP);
let i = 0;
const render_row = async function (_key, _val) {
const currentRecordId = SESSION_OBJ[options.SESSION_ID].DS_GLB[options.paramsP.dsSessionP].currentRecordId.toString();
const iterate_info = func.runtime.render.build_iterate_info({
_val,
_key,
iterator_key,
iterator_val,
is_key_dynamic_field,
is_val_dynamic_field,
reference_source_obj,
});
func.runtime.render.apply_iterate_info_to_current_record(options.SESSION_ID, options.paramsP.dsSessionP, currentRecordId, _progFields, iterate_info);
// XU_PERF: parent_infoP.iterate_info carries reference_source_obj (the
// whole source array); structuredClone per row is quadratic. iterate_info
// is replaced right below, so a shallow copy is sufficient.
const _parent_info = glb.XU_PERF ? Object.assign({}, options.parent_infoP) : (structuredClone(options.parent_infoP) || {});
_parent_info.iterate_info = iterate_info;
const $divP = await func.runtime.render.render_ui_tree(options.SESSION_ID, options.$container, options.nodeP, _parent_info, options.paramsP, options.jobNoP, null, i, null, options.nodeP, null, options.$root_container);
func.runtime.render.attach_iterate_info_to_children($divP, iterate_info);
i++;
return $divP;
};
if (Array.isArray(arr)) {
let reuse_pool = null;
let ordered = null;
if (glb.XU_PERF) {
ordered = [];
const parent_node = func.runtime.ui.get_first_node(options.$container);
const parent_ui_id = parent_node?.getAttribute?.('xu-ui-id');
const stash_key = parent_ui_id + '::' + options.nodeP.id;
const stashed = func.runtime.render.xu_for_reuse_stash.get(stash_key);
if (stashed) {
func.runtime.render.xu_for_reuse_stash.delete(stash_key);
// Rows reused as-is keep their rendered index bindings; when the
// template reads the key iterator, indexes shift on reorder, so
// fall back to the legacy rebuild for correctness.
const template_reads_index = func.runtime.render.xu_for_template_reads_key(options.nodeP, iterator_key);
if (template_reads_index) {
const _stale = stashed.filter(function (el) { return el && el.isConnected; });
if (_stale.length) func.runtime.ui.remove(func.runtime.ui._wrap_matches(_stale));
} else {
reuse_pool = new Map();
for (let s = 0; s < stashed.length; s++) {
const el = stashed[s];
if (el && el.isConnected && typeof el.__xu_row_key !== 'undefined' && !reuse_pool.has(el.__xu_row_key)) {
reuse_pool.set(el.__xu_row_key, el);
} else if (el && el.isConnected) {
func.runtime.ui.remove(func.runtime.ui._wrap_matches([el]));
}
}
}
}
}
for (let idx = 0; idx < arr.length; idx++) {
const _val = arr[idx];
if (glb.XU_PERF) {
const row_key = func.runtime.render.get_xu_row_key(_val, idx);
if (reuse_pool) {
const el = reuse_pool.get(row_key);
if (el) {
reuse_pool.delete(row_key);
if (xu_isEqual(el.__xu_row_snap, _val)) {
ordered.push(el);
i++;
continue; // unchanged row: keep its DOM untouched
}
// same key, changed value: rebuild the row, drop the old element
func.runtime.ui.remove(func.runtime.ui._wrap_matches([el]));
}
}
const $divP = await render_row(idx, _val);
const _row_node = func.runtime.ui.get_first_node($divP);
if (_row_node) {
_row_node.__xu_row_key = row_key;
_row_node.__xu_row_snap = func.runtime.render.snap_xu_row(_val);
ordered.push(_row_node);
}
} else {
await render_row(idx, _val);
}
}
if (reuse_pool) {
// rows whose keys vanished from the source
reuse_pool.forEach(function (el) {
if (el && el.isConnected) func.runtime.ui.remove(func.runtime.ui._wrap_matches([el]));
});
}
if (ordered && ordered.length > 1) {
// single forward pass: pull each row behind its predecessor
let prev = null;
for (let o = 0; o < ordered.length; o++) {
const el = ordered[o];
if (!el || !el.isConnected) continue;
if (prev && prev.nextSibling !== el) {
prev.parentElement.insertBefore(el, prev.nextSibling);
}
prev = el;
}
}
} else {
const iterate_keys = Object.keys(arr || {});
for (let idx = 0; idx < iterate_keys.length; idx++) {
const _key = iterate_keys[idx];
await render_row(_key, arr[_key]);
}
}
// The container can still be replaced during an awaited row render. Move the
// completed row nodes to the live replacement, then dedupe by iteration key;
// moving before deduping preserves the already-visible first row.
try {
const _post_container_node = func.runtime.ui.get_first_node(options.$container);
if (_post_container_node && !_post_container_node.isConnected) {
let _post_root = _post_container_node;
while (_post_root.parentNode && _post_root.parentNode.nodeType === 1) _post_root = _post_root.parentNode;
const _transplant_into = function ($target_node, via_label) {
const _dead_children = Array.prototype.slice.call(_post_container_node.children);
let _moved = 0;
for (let dead_i = 0; dead_i < _dead_children.length; dead_i++) {
const _dead_child = _dead_children[dead_i];
if (func.runtime.ui.get_data(func.runtime.ui._wrap_matches([_dead_child]))?.xuData?.nodeid === options.nodeP?.id) {
$target_node.appendChild(_dead_child);
_moved++;
}
}
const _seen_keys = new Set();
let _deduped = 0;
const _target_children = Array.prototype.slice.call($target_node.children);
for (let t_i = 0; t_i < _target_children.length; t_i++) {
const _t_child = _target_children[t_i];
const _t_data = func.runtime.ui.get_data(func.runtime.ui._wrap_matches([_t_child]))?.xuData;
if (!_t_data || _t_data.nodeid !== options.nodeP?.id) continue;
const _t_key = _t_data.iterate_info && typeof _t_data.iterate_info._key !== 'undefined' ? String(_t_data.iterate_info._key) : null;
if (_t_key === null) continue;
if (_seen_keys.has(_t_key)) {
func.runtime.ui.remove(_t_child);
_deduped++;
} else {
_seen_keys.add(_t_key);
}
}
console.log('[xufor-fix] transplant via ' + via_label + ': moved ' + _moved + ' rows, deduped ' + _deduped);
return _moved;
};
if (!_is_latest_run()) {
console.log('[xufor-fix] superseded run for node ' + String(options.nodeP?.id || '').slice(-10) + ' — deferred work dropped');
} else if (_post_root.tagName !== 'TEMPLATE' && _post_root.tagName !== 'TMP') {
const _post_resolved = func.runtime.render.resolve_live_xu_for_container(options.SESSION_ID, options.$container, options.nodeP?.id);
if (_post_resolved.node) {
_transplant_into(_post_resolved.node, 'post-loop/' + _post_resolved.via);
} else {
const _watch_started = Date.now();
let _last_scan = 0;
const _watcher = new MutationObserver(function () {
const _now = Date.now();
if (_now - _last_scan < 120) return;
_last_scan = _now;
try {
if (!_is_latest_run()) {
_watcher.disconnect();
console.log('[xufor-fix] watcher superseded by newer run — dropped');
return;
}
const _late = func.runtime.render.resolve_live_xu_for_container(options.SESSION_ID, options.$container, options.nodeP?.id);
if (_late.node && _late.node !== _post_container_node) {
_watcher.disconnect();
_transplant_into(_late.node, 'watcher/' + _late.via + '/+' + (_now - _watch_started) + 'ms');
}
} catch (watch_error) {
_watcher.disconnect();
console.log('[xufor-fix] watcher error', watch_error);
}
});
_watcher.observe(document.body, { childList: true, subtree: true });
setTimeout(function () {
_watcher.disconnect();
}, 12000);
}
}
}
} catch (post_loop_error) {
console.log('[xufor-fix] post-loop error', post_loop_error);
}
const _live_node = func.runtime.ui.get_first_node($live_elm);
if (_live_node) {
func.runtime.ui.remove($live_elm);
}
const _options_node = func.runtime.ui.get_first_node(options.$elm);
if (_options_node && _options_node !== _live_node) {
func.runtime.ui.remove(options.$elm);
}
return { abort: true, consume_placeholder: true };
} catch (e) {
console.error(' Iterator Arr parse error', e);
return { abort: true };
}
};
// Does the row template reference the key iterator (index)? Checked once per
// rebuild against the template node; cached per node object.
func.runtime.render.xu_for_template_reads_key = function (nodeP, iterator_key) {
if (!nodeP || !iterator_key) return false;
const cache = (func.runtime.render._xu_for_key_usage_cache = func.runtime.render._xu_for_key_usage_cache || new WeakMap());
const cached = cache.get(nodeP);
if (typeof cached !== 'undefined') return cached;
let uses = false;
try {
uses = JSON.stringify(nodeP).includes('@' + iterator_key);
} catch (e) {
uses = true; // cannot inspect: assume it does and stay on the safe path
}
cache.set(nodeP, uses);
return uses;
};
func.runtime.render.set_iterator_name = function ($elm, key, value) {
func.runtime.ui.get_data($elm).xuData[key] = value;
return {};
};
func.runtime = func.runtime || {};
func.runtime.ui = func.runtime.ui || {};
func.runtime.render = func.runtime.render || {};
func.runtime.widgets = func.runtime.widgets || {};
// Legacy xu-render flow stays isolated here so the feature-flag dispatch can stay small.
func.runtime.render.handle_legacy_xu_render = async function (options) {
const value = await func.common.get_cast_val(options.SESSION_ID, 'common fx', 'xu-render', 'bool', options.val.value);
const init_render = function () {
if (!value) {
const cloned_div = func.runtime.ui.get_first_node(options.$elm)?.cloneNode(true);
const original_data_obj = func.runtime.render.build_xu_render_original_data({
$container: cloned_div,
nodeP: options.nodeP,
parent_infoP: options.parent_infoP,
paramsP: options.paramsP,
keyP: options.keyP,
parent_nodeP: options.parent_nodeP,
$root_container: options.$root_container,
});
// Snapshot xuData while meta store still holds the entry
const snapshot_xuData = func.runtime.ui.get_data(cloned_div).xuData;
const snapshot_xuAttributes = options.nodeP.attributes || {};
const xu_ui_id = func.runtime.ui.get_attr(options.$elm, 'xu-ui-id');
// Remove original element from DOM WITHOUT deleting _meta_store.
const _elm_node = func.runtime.ui.get_first_node(options.$elm);
if (_elm_node?.remove) {
_elm_node.remove();
}
// Create XURENDER placeholder (overwrites meta store entry for this xu-ui-id)
func.runtime.render.create_xu_render_placeholder(xu_ui_id, options.$container, {
hidden: true,
xuData: snapshot_xuData,
original_data_obj,
xurender_node: cloned_div,
xuAttributes: snapshot_xuAttributes,
});
return { abort: true };
}
return {};
};
const replace_rendered_xu_node = async function (new_$div) {
const $parent = func.runtime.ui.get_parent(options.$elm);
func.runtime.ui.replace_with(options.$elm, new_$div);
if (options.from_panel) {
const xuPanelWrapper = { ...func.runtime.ui.get_data(new_$div).xuPanelWrapper };
if (func.runtime.ui.get_data($parent)) {
func.runtime.ui.get_data($parent).xuPanelWrapper = xuPanelWrapper;
}
func.runtime.ui.replace_with(options.$elm, func.runtime.ui.get_children(new_$div));
}
if (options.val.fields_arr) {
return await func.runtime.ui.refresh_xu_attributes({
SESSION_ID: options.SESSION_ID,
fields_arr: options.val.fields_arr,
jobNoP: options.val.jobNoP,
$elm_to_search: new_$div,
});
}
func.events.delete_job(options.SESSION_ID, options.jobNoP);
};
const post_render = async function () {
if (value) {
try {
const elm_node = func.runtime.ui.get_first_node(options.$elm);
if (elm_node?.tagName !== 'XURENDER' && elm_node) {
return func.events.delete_job(options.SESSION_ID, options.jobNoP);
}
const original_data_obj = func.runtime.ui.get_data(options.$elm).xuData.original_data_obj;
if (!original_data_obj) {
func.events.delete_job(options.SESSION_ID, options.jobNoP);
return { delete_job: options.jobNoP };
}
const new_$div = await func.runtime.render.render_ui_tree(
options.SESSION_ID,
options.$elm,
structuredClone(original_data_obj.nodeP),
original_data_obj.parent_infoP,
original_data_obj.paramsP,
options.jobNoP,
null,
original_data_obj.keyP,
null,
original_data_obj.parent_nodeP,
null,
original_data_obj.$root_container,
);
func.runtime.ui.get_data(new_$div).xuData.original_data_obj = original_data_obj;
func.runtime.ui.get_data(new_$div).xuData.xurender_node = func.runtime.ui.get_first_node(options.$elm)?.cloneNode(true);
func.runtime.ui.get_data(new_$div).xuAttributes = func.runtime.ui.get_data(options.$elm).xuAttributes || {};
const xu_ui_id = func.runtime.ui.get_attr(options.$elm, 'xu-ui-id');
// The placeholder→content swap must not be gated on a refresh-index lookup: when the
// (hidden) placeholder was missing from the index, the swap was silently skipped,
// leaving BOTH the freshly rendered content (appended at the container end) and the
// placeholder in the DOM — every truthy pass added another content copy, and the later
// falsy pass swapped the stale placeholder no-op, so the content never left the screen
// (un-closable create-assignment modal). Swap unconditionally, then enforce the
// one-live-element-per-xu-ui-id contract.
if (func.runtime.ui.get_data(new_$div).xuData.paramsP) {
await replace_rendered_xu_node(new_$div);
} else {
func.events.delete_job(options.SESSION_ID, options.jobNoP);
}
if (func.runtime.ui.reconcile_xu_ui_id_duplicates) {
func.runtime.ui.reconcile_xu_ui_id_duplicates(options.SESSION_ID, xu_ui_id, new_$div);
}
} catch (error) {
func.events.delete_job(options.SESSION_ID, options.jobNoP);
}
return;
}
if (func.runtime.ui.get_first_node(options.$elm)?.tagName === 'XURENDER') {
func.events.delete_job(options.SESSION_ID, options.jobNoP);
return;
}
// Resolve a stale reference before swapping in the placeholder: a prior truthy pass may
// have re-rendered the content into a different slot; replacing a detached node would
// leave the live content orphaned on screen.
{
const falsy_elm_node = func.runtime.ui.get_first_node(options.$elm);
const falsy_ui_id = func.runtime.ui.get_attr(options.$elm, 'xu-ui-id');
if (falsy_ui_id && (!falsy_elm_node || !falsy_elm_node.isConnected)) {
const $falsy_live = func.runtime?.ui?.find_xu_ui_in_root
? func.runtime.ui.find_xu_ui_in_root(options.SESSION_ID, falsy_ui_id)
: func.runtime.ui.find_by_selector(document.body, `[xu-ui-id="${falsy_ui_id}"]`);
if ($falsy_live?.length) {
options.$elm = $falsy_live;
}
}
}
const tmp_div = document.createElement('div');
const $xurender = func.runtime.ui.create_xurender(func.runtime.ui.get_attr(options.$elm, 'xu-ui-id'), tmp_div);
const elm_data = func.runtime.ui.get_data(options.$elm);
const elm_xu_data = elm_data?.xuData || {};
const elm_xu_attributes = elm_data?.xuAttributes || {};
const xurender_node_data = func.runtime.ui.get_data(elm_xu_data.xurender_node);
if (elm_xu_data.xurender_node) {
func.runtime.ui.set_data($xurender, 'xuAttributes', xurender_node_data?.xuAttributes || {});
func.runtime.ui.set_data($xurender, 'xuData', xurender_node_data?.xuData || {});
} else {
func.runtime.ui.set_data($xurender, 'xuAttributes', elm_xu_attributes);
func.runtime.ui.set_data($xurender, 'xuData', elm_xu_data);
const original_data_obj = func.runtime.render.build_xu_render_original_data({
nodeP: elm_xu_data.node_org,
paramsP: elm_xu_data.paramsP,
$container: func.runtime.ui.get_first_node(options.$elm)?.cloneNode(true),
parent_infoP: options.parent_infoP,
});
func.runtime.ui.get_data($xurender).xuData.original_data_obj = original_data_obj;
}
const elm_first_node = func.runtime.ui.get_first_node(options.$elm);
// Lifecycle: a closed screen owns nothing. Dispose datasource sessions of screens
// hosted inside the content being swapped out — leaked sessions (one set per open)
// kept their refresh listeners alive and re-rendered over every subsequent open.
const embed_hosts = elm_first_node?.querySelectorAll?.('.xu_embed_container') || [];
for (let embed_index = 0; embed_index < embed_hosts.length; embed_index++) {
const embed_screen_id = embed_hosts[embed_index].id;
if (embed_screen_id) {
try {
func.datasource.clean(options.SESSION_ID, embed_screen_id);
} catch (error) {}
}
}
const teleport_nodes = elm_first_node?.querySelectorAll?.('xu-teleport') || [];
for (let index = 0; index < teleport_nodes.length; index++) {
const val = teleport_nodes[index];
const xuTeleportData = func.runtime.ui.get_data(val).xuTeleportData || [];
for (const teleported_elm_id of xuTeleportData) {
func.runtime.ui.remove_xu_ui(teleported_elm_id);
}
}
func.runtime.ui.replace_with(options.$elm, func.runtime.ui.get_children(tmp_div));
if (func.runtime.ui.reconcile_xu_ui_id_duplicates) {
func.runtime.ui.reconcile_xu_ui_id_duplicates(options.SESSION_ID, func.runtime.ui.get_attr($xurender, 'xu-ui-id'), $xurender);
}
func.events.delete_job(options.SESSION_ID, options.jobNoP);
};
if (options.is_init) {
return init_render();
}
return await post_render();
};
func.runtime = func.runtime || {};
func.runtime.ui = func.runtime.ui || {};
func.runtime.render = func.runtime.render || {};
func.runtime.widgets = func.runtime.widgets || {};
// Modern xu-render flow stays isolated here so caching and tree reuse can evolve without the legacy path.
func.runtime.render.handle_modern_xu_render = async function (options) {
const value = await func.common.get_cast_val(options.SESSION_ID, 'common fx', 'xu-render', 'bool', options.val.value);
const has_xu_render_attribute = true;
const elm_data = func.runtime.ui.get_data(options.$elm);
const has_xu_exp_render_attribute = elm_data?.xuData?.attr_exp_info?.['xu-render'] ? true : false;
const init_render = async function () {
options.nodeP.xu_render_made = value;
if (!value) {
if (has_xu_exp_render_attribute) {
return { has_xu_exp_render_attribute, has_xu_render_attribute, xu_render_background_processing: true };
}
return { has_xu_render_attribute, abort: true };
}
return { has_xu_exp_render_attribute, has_xu_render_attribute };
};
const post_render = async function () {
const container_data = func.runtime.ui.get_data(options.$container);
if (!container_data?.xuData?.node?.children?.[options.keyP]) {
return;
}
const nodeP = container_data.xuData.node.children[options.keyP];
nodeP.xu_render_made = value;
if (value) {
try {
const exclude_fields = func.runtime.render.get_xu_render_exclude_fields(options.$elm);
const xu_render_cache_id = await func.runtime.render.get_xu_render_cache_str(
options.SESSION_ID,
options.paramsP.dsSessionP,
exclude_fields,
);
const xu_ui_id = func.runtime.ui.get_attr(options.$elm, 'xu-ui-id');
const cached_entry = UI_WORKER_OBJ?.xu_render_cache?.[xu_ui_id + xu_render_cache_id];
let found_parent_vars = false;
if (cached_entry?.$div) {
const parent_fields = func.runtime.render.get_parent_ds_field_names(options.SESSION_ID, options.paramsP.dsSessionP);
found_parent_vars = func.runtime.render.has_parent_field_dependency(cached_entry.$div, parent_fields, cached_entry?.dependency_fields);
}
let new_$div = !found_parent_vars && cached_entry?.$div ? func.runtime.ui.get_first_node(cached_entry.$div)?.cloneNode(true) : null;
if (!new_$div || found_parent_vars) {
func.runtime.render.cache_xu_render(xu_ui_id + xu_render_cache_id, { paramsP: options.paramsP });
nodeP.xu_render_xu_ui_id = xu_ui_id;
nodeP.xu_render_cache_id = xu_render_cache_id;
new_$div = await func.runtime.render.render_ui_tree(
options.SESSION_ID,
options.$container,
nodeP,
options.parent_infoP,
options.paramsP,
options.jobNoP,
null,
options.keyP,
null,
options.parent_nodeP,
null,
options.$root_container,
);
const _$div = func.runtime.ui.get_first_node(new_$div)?.cloneNode(true);
func.runtime.render.cache_xu_render(xu_ui_id + xu_render_cache_id, {
...UI_WORKER_OBJ.xu_render_cache[xu_ui_id + xu_render_cache_id],
$div: _$div,
data: func.runtime.ui.get_data(_$div),
});
}
func.runtime.render.insert_ordered_child(options.$container, new_$div, options.keyP);
// Remove the XURENDER placeholder now that the real content has been inserted.
if (func.runtime.ui.get_first_node(options.$elm)?.tagName === 'XURENDER') {
func.runtime.ui.remove(options.$elm);
}
// Enforce one live element per xu-ui-id: a stale options.$elm (placeholder replaced or
// moved since this job was queued) leaves the old copy behind — content duplicates.
if (func.runtime.ui.reconcile_xu_ui_id_duplicates) {
func.runtime.ui.reconcile_xu_ui_id_duplicates(options.SESSION_ID, xu_ui_id, new_$div);
}
} catch (error) {
func.events.delete_job(options.SESSION_ID, options.jobNoP);
}
return;
}
// Cancel any in-flight child jobs before removing the element.
// This prevents orphaned jobs (e.g. a child panel's long-running on_load delay)
// from blocking future scheduler passes after the parent element is gone.
if (func.UI?.worker?.cancel_child_in_flight_jobs) {
func.UI.worker.cancel_child_in_flight_jobs(options.$elm);
}
const xu_ui_id = func.runtime.ui.get_attr(options.$elm, 'xu-ui-id');
const exclude_fields = func.runtime.render.get_xu_render_exclude_fields(options.$elm);
const cache_str = await func.runtime.render.get_xu_render_cache_str(
options.SESSION_ID,
options.paramsP.dsSessionP,
exclude_fields,
);
const _$div = func.runtime.ui.get_first_node(options.$elm)?.cloneNode(true);
func.runtime.render.cache_xu_render(xu_ui_id + cache_str, { $div: _$div, data: func.runtime.ui.get_data(_$div), paramsP: options.paramsP });
// Lifecycle: dispose datasource sessions of screens hosted inside the removed content
// (same contract as the legacy falsy path — a closed screen owns nothing).
const closing_node = func.runtime.ui.get_first_node(options.$elm);
const embed_hosts = closing_node?.querySelectorAll?.('.xu_embed_container') || [];
for (let embed_index = 0; embed_index < embed_hosts.length; embed_index++) {
const embed_screen_id = embed_hosts[embed_index].id;
if (embed_screen_id) {
try {
func.datasource.clean(options.SESSION_ID, embed_screen_id);
} catch (error) {}
}
}
func.runtime.ui.remove(options.$elm);
// Enforce one live element per xu-ui-id: if options.$elm went stale (content re-rendered
// or moved since this job was queued), the live copy would survive the remove above and
// stay on screen even though its gate is now falsy (un-closable modal).
if (func.runtime.ui.reconcile_xu_ui_id_duplicates) {
func.runtime.ui.reconcile_xu_ui_id_duplicates(options.SESSION_ID, xu_ui_id, null);
}
func.events.delete_job(options.SESSION_ID, options.jobNoP);
};
if (options.is_init) {
return await init_render();
}
return await post_render();
};
func.runtime = func.runtime || {};
func.runtime.ui = func.runtime.ui || {};
func.runtime.render = func.runtime.render || {};
func.runtime.widgets = func.runtime.widgets || {};
// Browser-only xu-render dispatch lives here so legacy and modern render paths can stay isolated.
func.runtime.render.handle_xu_render = async function (options) {
if (glb.new_xu_render) {
return await func.runtime.render.handle_modern_xu_render(options);
}
return await func.runtime.render.handle_legacy_xu_render(options);
};
func.runtime = func.runtime || {};
func.runtime.ui = func.runtime.ui || {};
func.runtime.render = func.runtime.render || {};
func.runtime.widgets = func.runtime.widgets || {};
// Browser-only DOM-oriented xu handler helpers live here so handler dispatch can stay focused.
func.runtime.render.apply_expression_attribute = async function (options) {
const new_val = {
key: options.key,
value: func.runtime.render.fix_val_defaults(options.key, options.exp_ret.result),
};
if (func.runtime.render.is_xu_tag(options.nodeP.tagName)) {
if (options.tag_fx?.[options.nodeP.tagName]?.[new_val.key]) {
return await options.tag_fx[options.nodeP.tagName][new_val.key](options.$elm, new_val);
}
if (options.nodeP.tagName === 'xu-panel' && !new_val.key.startsWith('xu-')) {
return {};
}
console.warn(`attribute ${new_val.key} not found for ${options.nodeP.tagName}`);
return {};
}
if (!func.runtime.ui.get_data(options.$elm)?.xuData) {
return {};
}
func.runtime.render.record_attribute_stat(options.$elm, new_val.key, new_val.value);
if (typeof new_val.value === 'undefined' || new_val.value === null) {
func.runtime.ui.remove_attr(options.$elm, new_val.key);
return {};
}
if (glb.solid_attributes.includes(new_val.key) && !new_val.value) {
func.runtime.ui.remove_attr(options.$elm, new_val.key);
return {};
}
if (new_val.key.substr(0, 2) === 'xu') {
return await options.common_fx[new_val.key](options.$elm, new_val);
}
if (new_val.key === 'class') {
return func.runtime.render.apply_expression_class(options.$elm, new_val.value);
}
const existing_value = func.runtime.ui.get_attr(options.$elm, new_val.key) || '';
func.runtime.ui.set_attr(options.$elm, new_val.key, existing_value + new_val.value);
return {};
};
func.runtime.render.apply_expression_class = function ($elm, new_class_value) {
const xuData = func.runtime.ui.get_data($elm)?.xuData;
const old_exp_classes = xuData?._exp_class_cache || '';
if (old_exp_classes) {
const old_classes = old_exp_classes.split(/\s+/).filter(Boolean);
for (let i = 0; i < old_classes.length; i++) {
func.runtime.ui.remove_class($elm, old_classes[i]);
}
}
const new_value = (new_class_value || '').toString();
const new_classes = new_value.split(/\s+/).filter(Boolean);
for (let i = 0; i < new_classes.length; i++) {
func.runtime.ui.add_class($elm, new_classes[i]);
}
if (xuData) {
xuData._exp_class_cache = new_value;
}
return {};
};
func.runtime.render.apply_visibility = function ($elm, value) {
if (value) {
func.runtime.ui.show($elm);
return;
}
func.runtime.ui.hide($elm);
};
func.runtime.render.apply_dom_content = function ($elm, value, mode = 'html') {
if (mode === 'text') {
func.runtime.ui.set_text($elm, value);
return;
}
func.runtime.ui.set_html($elm, value);
};
func.runtime.render.run_inline_script = function ($elm, script_body) {
const checkExist = setInterval(async function () {
const node = func.runtime.ui.get_first_node($elm);
if (node && node.offsetParent !== null) {
try {
// A function-body inline script — "(elm) => {…}", "elm => {…}", "function(el){…}" — must be
// CALLED with the node, not merely defined; otherwise wrapping it as `async(el)=>{ (elm)=>{…} }`
// just declares the arrow and never runs it (e.g. the gallery's `new Swiper(elm,{…})`). Detect a
// function body, eval it as an expression, and invoke it with the node. Statement bodies keep the
// original wrap-and-run path unchanged.
const trimmed = `${script_body || ''}`.trim();
const is_function_body =
/^(async\s+)?(\([^)]*\)|[A-Za-z_$][\w$]*)\s*=>/.test(trimmed) || /^(async\s+)?function[\s*(]/.test(trimmed);
if (is_function_body) {
const f = eval(`(${script_body})`);
if (typeof f === 'function') await f(node);
} else {
const fn = `async (el)=>{${script_body} };`;
const res = eval(fn);
await res(node);
}
} catch (e) {
try {
eval(script_body);
} catch (e2) {
console.error('[xuda-runtime] inline script error', e2);
}
} finally {
clearInterval(checkExist);
}
}
}, 100);
};
// --- Legacy jQuery `$` global shim ------------------------------------------
// Some legacy apps call jQuery `$` from INLINE xu-script bodies, which
// run_inline_script eval's directly. Per-program shims are block
// scoped and invisible to that eval, so install the pure-JS `$` shim as a global
// once here (browser-only module, parsed before any inline script runs).
// Guarded: never clobber a real jQuery (a superset) or a per-program const $.
(function install_legacy_jq_shim() {
const host = typeof window !== 'undefined' ? window : typeof globalThis !== 'undefined' ? globalThis : null;
if (!host || host.$) return;
const $ = function() {
const proto = {};
const make = (els) => {
const col = Object.create(proto);
let n = 0;
for (const el of els) if (el != null) col[n++] = el;
col.length = n;
col.__col = true;
return col;
};
const sanitizeSel = (s) => s.replace(/\[\s*([-\w]+)\s*([~|^$*]?=)\s*([^\]'"]+?)\s*\]/g, (m, a, op, v) => `[${a}${op}"${v}"]`);
const qsa = (rootEl, sel) => {
try {
return Array.prototype.slice.call(rootEl.querySelectorAll(sel));
} catch (e) {
try {
return Array.prototype.slice.call(rootEl.querySelectorAll(sanitizeSel(sel)));
} catch (_) {
return [];
}
}
};
const toNodes = (arg) => {
if (arg == null) return [];
if (arg.__col) return Array.prototype.slice.call(arg, 0, arg.length);
if (arg instanceof Node || arg === window || arg === document) return [arg];
if (typeof arg === "string") {
const s = arg.trim();
if (s[0] === "<") {
const t = document.createElement("template");
t.innerHTML = s;
return Array.prototype.slice.call(t.content.childNodes);
}
return qsa(document, arg);
}
if (typeof arg.length === "number") return Array.prototype.slice.call(arg);
return [arg];
};
const root = (arg) => make(toNodes(arg));
const parseHTML = (html) => {
const t = document.createElement("template");
t.innerHTML = html;
return Array.prototype.slice.call(t.content.childNodes);
};
const contentNodes = (content) => {
if (content == null) return [];
if (content.__col) return Array.prototype.slice.call(content, 0, content.length);
if (content instanceof Node) return [content];
if (typeof content === "string") return parseHTML(content);
if (typeof content.length === "number") return Array.prototype.slice.call(content);
return [content];
};
const each = function(cb) {
for (let i = 0; i < this.length; i++) if (cb.call(this[i], i, this[i]) === false) break;
return this;
};
const eventStore = (el) => el.__jqEv || (el.__jqEv = {});
Object.assign(proto, {
each,
get(i) {
return i == null ? Array.prototype.slice.call(this, 0, this.length) : this[i < 0 ? this.length + i : i];
},
eq(i) {
return make([this.get(i)].filter(Boolean));
},
first() {
return this.eq(0);
},
last() {
return this.eq(-1);
},
add(other) {
return make(toNodes(this).concat(toNodes(other)));
},
filter(sel) {
const out = [];
each.call(this, function(i, el) {
if (typeof sel === "function") {
if (sel.call(el, i, el)) out.push(el);
} else if (el.matches && el.matches(sel)) out.push(el);
});
return make(out);
},
find(sel) {
const out = [];
each.call(this, (i, el) => {
if (el.querySelectorAll) out.push.apply(out, qsa(el, sel));
});
return make(out);
},
parent() {
const seen = /* @__PURE__ */ new Set(), out = [];
each.call(this, (i, el) => {
const p = el.parentNode;
if (p && !seen.has(p)) {
seen.add(p);
out.push(p);
}
});
return make(out);
},
children(sel) {
const out = [];
each.call(this, (i, el) => {
for (const c of el.children || []) if (!sel || c.matches && c.matches(sel)) out.push(c);
});
return make(out);
},
contents() {
const out = [];
each.call(this, (i, el) => {
for (const c of el.childNodes || []) out.push(c);
});
return make(out);
},
attr(name, val) {
if (val === void 0 && typeof name === "string") return this[0] ? this[0].getAttribute(name) : void 0;
return each.call(this, (i, el) => {
if (typeof name === "object") {
for (const k in name) el.setAttribute(k, name[k]);
} else el.setAttribute(name, val);
});
},
removeAttr(name) {
return each.call(this, (i, el) => el.removeAttribute(name));
},
addClass(c) {
const cs = String(c).split(/\s+/).filter(Boolean);
return each.call(this, (i, el) => el.classList.add(...cs));
},
removeClass(c) {
const cs = String(c).split(/\s+/).filter(Boolean);
return each.call(this, (i, el) => el.classList.remove(...cs));
},
hasClass(c) {
return this[0] ? this[0].classList.contains(c) : false;
},
css(name, val) {
if (typeof name === "object") return each.call(this, (i, el) => {
for (const k in name) setStyle(el, k, name[k]);
});
if (val === void 0) {
const el = this[0];
return el ? getComputedStyle(el).getPropertyValue(toKebab(name)) : void 0;
}
return each.call(this, (i, el) => setStyle(el, name, val));
},
html(v) {
if (v === void 0) return this[0] ? this[0].innerHTML : void 0;
return each.call(this, (i, el) => {
el.innerHTML = v;
});
},
text(v) {
if (v === void 0) return this[0] ? this[0].textContent : void 0;
return each.call(this, (i, el) => {
el.textContent = v;
});
},
append(content) {
const nodes = contentNodes(content);
return each.call(this, (i, el) => {
for (const n of nodes) el.appendChild(i === this.length - 1 ? n : n.cloneNode(true));
});
},
prepend(content) {
const nodes = contentNodes(content);
return each.call(this, (i, el) => {
const arr = i === this.length - 1 ? nodes : nodes.map((n) => n.cloneNode(true));
for (let k = arr.length - 1; k >= 0; k--) el.insertBefore(arr[k], el.firstChild);
});
},
after(content) {
const nodes = contentNodes(content);
return each.call(this, (i, el) => {
if (!el.parentNode) return;
const ref = el.nextSibling;
for (const n of nodes) el.parentNode.insertBefore(i === this.length - 1 ? n : n.cloneNode(true), ref);
});
},
before(content) {
const nodes = contentNodes(content);
return each.call(this, (i, el) => {
if (!el.parentNode) return;
for (const n of nodes) el.parentNode.insertBefore(i === this.length - 1 ? n : n.cloneNode(true), el);
});
},
insertBefore(target) {
const ref = toNodes(target)[0];
if (ref && ref.parentNode) each.call(this, (i, el) => ref.parentNode.insertBefore(el, ref));
return this;
},
has(sel) {
const out = [];
each.call(this, (i, el) => {
if (el.querySelector && el.querySelector(sel)) out.push(el);
});
return make(out);
},
slice(a, b) {
return make(Array.prototype.slice.call(this, 0, this.length).slice(a, b));
},
// jQuery .map(): returns a real array (so vue-grid etc. can use it directly),
// but also carries .toArray()/.get() so `$(...).map(...).toArray()` chains work.
map(cb) {
const out = [];
for (let i = 0; i < this.length; i++) {
const r = cb.call(this[i], i, this[i]);
if (r != null) {
if (Array.isArray(r)) out.push.apply(out, r);
else out.push(r);
}
}
Object.defineProperty(out, "toArray", { value: function() {
return this;
}, enumerable: false });
Object.defineProperty(out, "get", { value: function(i) {
return i == null ? this : this[i];
}, enumerable: false });
return out;
},
toArray() {
return Array.prototype.slice.call(this, 0, this.length);
},
not(sel) {
const out = [];
each.call(this, function(i, el) {
if (typeof sel === "function") {
if (!sel.call(el, i, el)) out.push(el);
} else if (!(el.matches && el.matches(sel))) out.push(el);
});
return make(out);
},
empty() {
return each.call(this, (i, el) => {
el.innerHTML = "";
});
},
remove() {
return each.call(this, (i, el) => {
if (el.parentNode) el.parentNode.removeChild(el);
});
},
replaceWith(content) {
return each.call(this, (i, el) => {
const nodes = contentNodes(content);
if (el.replaceWith) el.replaceWith(...nodes);
});
},
unwrap() {
const parents = /* @__PURE__ */ new Set();
each.call(this, (i, el) => {
if (el.parentNode) parents.add(el.parentNode);
});
parents.forEach((p) => {
if (p.parentNode) p.replaceWith(...Array.prototype.slice.call(p.childNodes));
});
return this;
},
hide() {
return each.call(this, (i, el) => {
el.style.display = "none";
});
},
show() {
return each.call(this, (i, el) => {
el.style.display = "";
});
},
width() {
const el = this[0];
return el ? el.getBoundingClientRect().width : 0;
},
position() {
const el = this[0];
return el ? { top: el.offsetTop, left: el.offsetLeft } : { top: 0, left: 0 };
},
// events: native add/removeEventListener; custom events via CustomEvent.detail
on(type, handler) {
return each.call(this, (i, el) => {
const wrap = (e) => handler.call(el, e, e.detail);
const store = eventStore(el);
(store[type] || (store[type] = [])).push({ handler, wrap });
el.addEventListener(type, wrap);
});
},
off(type, handler) {
return each.call(this, (i, el) => {
const store = el.__jqEv;
if (!store || !store[type]) return;
store[type] = store[type].filter((rec) => {
if (handler && rec.handler !== handler) return true;
el.removeEventListener(type, rec.wrap);
return false;
});
});
},
trigger(type, detail) {
return each.call(this, (i, el) => el.dispatchEvent(new CustomEvent(type, { detail, bubbles: true })));
}
});
proto.unbind = proto.off;
["click", "mouseup", "mousedown", "change", "keyup", "keydown", "blur", "focus"].forEach((ev) => {
proto[ev] = function(handler) {
return handler ? this.on(ev, handler) : this.trigger(ev);
};
});
function toKebab(s) {
return s.indexOf("-") > -1 ? s : s.replace(/[A-Z]/g, (m) => "-" + m.toLowerCase());
}
function setStyle(el, name, val) {
if (name.indexOf("-") > -1) el.style.setProperty(name, val);
else el.style[name] = val;
}
root.each = function(coll, cb) {
if (coll == null) return coll;
if (typeof coll.length === "number" && typeof coll !== "function" && coll.nodeType === void 0) {
for (let i = 0; i < coll.length; i++) if (cb.call(coll[i], i, coll[i]) === false) break;
} else {
for (const k in coll) if (cb.call(coll[k], k, coll[k]) === false) break;
}
return coll;
};
proto.data = function (key, val) {
if (arguments.length >= 2) {
for (let i = 0; i < this.length; i++) (this[i].__xuData || (this[i].__xuData = {}))[key] = val;
return this;
}
const el = this[0];
if (!el) return arguments.length === 1 ? undefined : {};
const store = el.__xuData || (el.__xuData = {});
if (arguments.length === 1) {
if (key in store) return store[key];
return el.dataset ? el.dataset[key] : undefined;
}
const out = {};
if (el.dataset) for (const k in el.dataset) out[k] = el.dataset[k];
for (const k in store) out[k] = store[k];
return out;
};
proto.siblings = function (sel) {
const out = [];
for (let i = 0; i < this.length; i++) {
const el = this[i];
if (!el || !el.parentNode) continue;
for (const sib of el.parentNode.children) {
if (sib !== el && (!sel || (sib.matches && sib.matches(sel))) && out.indexOf(sib) === -1) out.push(sib);
}
}
return make(out);
};
proto.draggabilly = function (opts) {
const Lib = (typeof window !== "undefined" && window.Draggabilly) || (typeof globalThis !== "undefined" && globalThis.Draggabilly);
for (let i = 0; i < this.length; i++) {
const el = this[i];
const store = el.__xuData || (el.__xuData = {});
if (opts === "destroy") {
if (store.draggabilly && store.draggabilly.destroy) store.draggabilly.destroy();
delete store.draggabilly;
continue;
}
if (!Lib) { if (!proto.__dbWarned) { proto.__dbWarned = true; console.warn("[xuda-runtime] Draggabilly not loaded; toolbar drag disabled"); } continue; }
store.draggabilly = new Lib(el, opts || {});
}
return this;
};
proto.draggable = function () {
if (!proto.__duiWarned) { proto.__duiWarned = true; console.warn("[xuda-runtime] jQuery-UI draggable not loaded; drag disabled"); }
return this;
};
return root;
}();
host.$ = $;
if (typeof globalThis !== 'undefined') globalThis.$ = $;
})();
func.runtime = func.runtime || {};
func.runtime.ui = func.runtime.ui || {};
func.runtime.render = func.runtime.render || {};
func.runtime.widgets = func.runtime.widgets || {};
// Browser-only node-related xu handlers live here so special-node rendering can stay focused.
func.runtime.render.handle_xu_panel_program = async function (options) {
let ret = {};
const _session = SESSION_OBJ[options.SESSION_ID];
const _ds = _session.DS_GLB[options.paramsP.dsSessionP];
const _refreshed_ds = _session.DS_GLB[options.refreshed_ds];
const render_panel_init = async function () {
const prog_id = options.val.value?.prog || options.val.value;
let create_new_ds = true;
if (options.refreshed_ds && _refreshed_ds?.prog_id === prog_id) {
create_new_ds = false;
}
const params_obj = await options.get_params_obj_new(options.SESSION_ID, prog_id, options.nodeP, options.paramsP.dsSessionP);
const ret_panel = await func.runtime.ui.init_screen({
SESSION_ID: options.SESSION_ID,
prog_id,
sourceScreenP: options.paramsP.screenId,
callingDataSource_objP: _ds,
$callingContainerP: options.$elm,
triggerIdP: null,
rowIdP: _ds.currentRecordId,
jobNoP: null,
is_panelP: true,
parameters_obj_inP: params_obj.params_res,
source_functionP: 'initXu_panel',
call_screen_propertiesP: undefined,
refreshed_ds: create_new_ds ? null : options.refreshed_ds,
parameters_raw_obj: params_obj.params_raw,
});
ret = { $new_div: ret_panel };
const container_data = func.runtime.ui.get_data(options.$container);
if (container_data?.xuData) {
container_data.xuData.xuPanelProps = func.runtime.ui.get_data(options.$elm)?.xuAttributes;
container_data.xuData.xuPanelData = func.runtime.ui.get_data(ret_panel);
}
return ret;
};
const render_panel_alter = async function () {
const program = options.val.value?.prog || options.val.value;
const $wrapper = document.createElement('div');
const $div = await func.runtime.ui.create_container({
SESSION_ID: options.SESSION_ID,
$root_container: options.$root_container,
nodeP: options.nodeP,
$container: options.$container,
paramsP: options.paramsP,
parent_infoP: options.parent_infoP,
jobNoP: options.jobNoP,
keyP: options.keyP,
treeP: options.treeP,
parent_nodeP: options.parent_nodeP,
prop: options.nodeP.attributes,
$appendToP: $wrapper,
attr_str: '',
});
const params_obj = await options.get_params_obj_new(options.SESSION_ID, program, options.nodeP, options.paramsP.dsSessionP);
const ret_init = await func.runtime.ui.init_screen({
SESSION_ID: options.SESSION_ID,
prog_id: program,
sourceScreenP: options.paramsP.screenId,
callingDataSource_objP: _ds,
$callingContainerP: $div,
triggerIdP: null,
rowIdP: _ds.currentRecordId,
jobNoP: options.jobNoP,
is_panelP: true,
parameters_obj_inP: params_obj.params_res,
source_functionP: 'alterXu_panel',
call_screen_propertiesP: undefined,
refreshed_ds: undefined,
parameters_raw_obj: params_obj.params_raw,
});
ret = {
$new_div: ret_init,
abort: true,
};
await func.runtime.ui.panel_post_render_handler({
SESSION_ID: options.SESSION_ID,
$container: options.$elm,
$wrapper: ret.$new_div,
nodeP: options.nodeP,
$panel_div: $div,
jobNoP: options.jobNoP,
});
return ret;
};
if (!options.val.value) {
if (options.is_init) {
options.val.value = '_empty_panel_program';
} else {
return { abort: true };
}
}
if (options.is_init) {
return await render_panel_init();
}
return await render_panel_alter();
};
func.runtime.render.handle_xu_teleport = async function (options) {
if (glb.new_xu_render) {
return {};
}
if (!options.val.value) {
return { abort: true };
}
const $parent = func.runtime.ui.get_parent(options.$elm);
const parent_data = func.runtime.ui.get_data($parent);
if (parent_data?.xuData) {
func.runtime.ui.set_data($parent, 'xuTeleportData', []);
const parent_xu_ui_id = func.runtime.ui.get_attr($parent, 'xu-ui-id');
for (let index = 0; index < options.nodeP.children.length; index++) {
const node = options.nodeP.children[index];
const $to_container = document.querySelector(options.val.value);
if (!$to_container) {
await func.utils.report_issue(options.SESSION_ID, {
code: 'RUN_MSG_GUI_010',
source: 'xu-teleport',
message: `container ${options.val.value} for xuTeleportData not found`,
type: 'E',
details: {
target: options.val.value,
},
});
return { abort: true };
}
const $teleport_elm = await func.runtime.render.render_ui_tree(
options.SESSION_ID,
$to_container,
node,
options.parent_infoP,
options.paramsP,
options.jobNoP,
options.is_skeleton,
index,
null,
node,
null,
options.$root_container,
);
parent_data.xuTeleportData.push(func.runtime.ui.get_attr($teleport_elm, 'xu-ui-id'));
func.runtime.ui.set_attr($teleport_elm, 'xu-teleport-parent-id', parent_xu_ui_id);
}
func.runtime.ui.remove(options.$elm);
return { abort: true };
}
func.runtime.ui.set_data(options.$elm, 'xuTeleportData', []);
func.runtime.ui.set_attr(options.$elm, 'hidden', true);
for (let index = 0; index < options.nodeP.children.length; index++) {
const node = options.nodeP.children[index];
const $to_container = document.querySelector(options.val.value);
if (!$to_container) {
await func.utils.report_issue(options.SESSION_ID, {
code: 'RUN_MSG_GUI_010',
source: 'xu-teleport',
message: `container ${options.val.value} for xuTeleportData not found`,
type: 'E',
details: {
target: options.val.value,
},
});
return { abort: true };
}
const $teleport_elm = await func.runtime.render.render_ui_tree(
options.SESSION_ID,
$to_container,
node,
options.parent_infoP,
options.paramsP,
options.jobNoP,
options.is_skeleton,
index,
null,
node,
null,
options.$root_container,
);
func.runtime.ui.get_data(options.$elm).xuTeleportData.push(func.runtime.ui.get_attr($teleport_elm, 'xu-ui-id'));
func.runtime.ui.set_attr($teleport_elm, 'xu-teleport-parent-id', func.runtime.ui.get_attr(options.$elm, 'xu-ui-id'));
}
return { abort: true };
};
func.runtime = func.runtime || {};
func.runtime.ui = func.runtime.ui || {};
func.runtime.render = func.runtime.render || {};
func.runtime.widgets = func.runtime.widgets || {};
// Browser-only common xu handler factories live here so registry composition can stay small.
func.runtime.render.build_base_xu_handlers = function (options, _ds) {
const decode_html_entities = function (value) {
if (typeof value !== 'string' || value.indexOf('&') === -1) {
return value;
}
if (typeof document !== 'undefined') {
const textarea = document.createElement('textarea');
textarea.innerHTML = value;
return textarea.value;
}
return value
.replaceAll('"', '"')
.replaceAll('"', '"')
.replaceAll(''', "'")
.replaceAll(''', "'")
.replaceAll('<', '<')
.replaceAll('>', '>')
.replaceAll('&', '&');
};
const parse_object_value = function (attr_name, val, shape = 'object') {
let parsed_value = val?.value;
if (typeof parsed_value === 'string') {
const decoded_value = decode_html_entities(parsed_value);
const trimmed_value = decoded_value.trim();
const wrapped_candidate =
trimmed_value.startsWith('(') && trimmed_value.endsWith(')')
? trimmed_value.slice(1, -1).trim()
: trimmed_value;
const looks_like_wrapped_shape =
(shape === 'object' && wrapped_candidate.startsWith('{') && wrapped_candidate.endsWith('}')) ||
(shape === 'array' && wrapped_candidate.startsWith('[') && wrapped_candidate.endsWith(']'));
try {
parsed_value = JSON5.parse(looks_like_wrapped_shape ? wrapped_candidate : trimmed_value);
} catch (error) {
throw func.runtime.render.build_xu_runtime_error(
{ ...options, xu_func: attr_name, val: { key: attr_name, value: val?.value } },
error,
`${attr_name} has invalid ${shape} syntax`,
);
}
}
const valid =
shape === 'array'
? Array.isArray(parsed_value)
: typeof parsed_value === 'object' && parsed_value !== null && !Array.isArray(parsed_value);
if (!valid) {
throw func.runtime.render.build_xu_runtime_error(
{ ...options, xu_func: attr_name, val: { key: attr_name, value: val?.value } },
null,
`${attr_name} expects a ${shape} value`,
);
}
return parsed_value;
};
return {
'xu-attrs': async function ($elm, val) {
if (!val.value) return {};
const attrs_obj = parse_object_value('xu-attrs', val, 'object');
const attr_keys = Object.keys(attrs_obj);
for (let index = 0; index < attr_keys.length; index++) {
const attr_key = attr_keys[index];
options.nodeP.attributes[attr_key] = attrs_obj[attr_key];
}
return {};
},
'xu-ref': async function ($elm, val, dsSession) {
return await func.runtime.render.handle_xu_ref({
SESSION_ID: options.SESSION_ID,
$elm,
paramsP: options.paramsP,
val,
dsSession,
});
},
'xu-bind': async function ($elm, val) {
return await func.runtime.render.handle_xu_bind({
SESSION_ID: options.SESSION_ID,
is_skeleton: options.is_skeleton,
$elm,
paramsP: options.paramsP,
val,
ds: _ds,
});
},
'xu-render': async function ($elm, val, from_panel) {
return await func.runtime.render.handle_xu_render({
SESSION_ID: options.SESSION_ID,
$elm,
$container: options.$container,
$root_container: options.$root_container,
nodeP: options.nodeP,
parent_infoP: options.parent_infoP,
paramsP: options.paramsP,
jobNoP: options.jobNoP,
keyP: options.keyP,
parent_nodeP: options.parent_nodeP,
val,
is_init: options.is_init,
from_panel,
});
},
'xu-show': async function ($elm, val) {
const value = await func.common.get_cast_val(options.SESSION_ID, 'common fx', 'xu-show', 'bool', val.value);
func.runtime.render.apply_visibility($elm, value);
return {};
},
'xu-content': async function ($elm, val) {
try {
func.runtime.render.apply_dom_content($elm, val.value, 'html');
} catch (error) {
console.warn(error);
}
return;
},
'xu-text': async function ($elm, val) {
try {
func.runtime.render.apply_dom_content($elm, val.value, 'text');
} catch (error) {
console.warn(error);
}
return;
},
'xu-html': async function ($elm, val) {
try {
func.runtime.render.apply_dom_content($elm, val.value, 'html');
} catch (error) {
console.warn(error);
}
return;
},
'xu-for': async function ($elm, data) {
return await func.runtime.render.handle_xu_for({
SESSION_ID: options.SESSION_ID,
$elm,
$live_elm: options.$live_elm || $elm,
$container: options.$container,
$root_container: options.$root_container,
nodeP: options.nodeP,
parent_infoP: options.parent_infoP,
paramsP: options.paramsP,
jobNoP: options.jobNoP,
data,
});
},
'xu-for-key': async function ($elm, val) {
return func.runtime.render.set_iterator_name($elm, 'iterator_key', val.value);
},
'xu-for-val': async function ($elm, val) {
return func.runtime.render.set_iterator_name($elm, 'iterator_val', val.value);
},
'xu-class': async function ($elm, val) {
return await func.runtime.render.apply_xu_class({
SESSION_ID: options.SESSION_ID,
$elm,
paramsP: options.paramsP,
val,
});
},
'xu-on': async function ($elm, val) {
func.runtime.render.bind_xu_event({
SESSION_ID: options.SESSION_ID,
paramsP: options.paramsP,
$elm,
val,
});
return {};
},
'xu-script': async function ($elm, val) {
func.runtime.render.run_inline_script($elm, val.value);
return {};
},
'xu-style-global': async function ($elm, val) {
func.runtime.render.append_style_tag(val.value);
return {};
},
'xu-style': async function ($elm, val) {
const newCSSString = func.runtime.render.scope_css_to_xu_ui($elm, val.value);
func.runtime.render.append_style_tag(newCSSString);
return {};
},
'xu-cdn': async function ($elm, val) {
// xu-cdn value can be an array [{src,type},...] or an object map; both
// iterate the same way via Object.keys. Accept either (was 'object' only,
// which threw "expects a object value" on the array form).
let resources_obj;
try {
resources_obj = parse_object_value('xu-cdn', val, 'array');
} catch (_) {
resources_obj = parse_object_value('xu-cdn', val, 'object');
}
const resource_keys = Object.keys(resources_obj || {});
for (let index = 0; index < resource_keys.length; index++) {
const resource = resources_obj[resource_keys[index]];
await func.runtime.resources.load_cdn(options.SESSION_ID, resource);
}
return {};
},
'xu-ui-plugin': async function ($elm, val) {
const plugins_obj = parse_object_value('xu-ui-plugin', val, 'object');
const plugin_names = Object.keys(plugins_obj);
for (let index = 0; index < plugin_names.length; index++) {
const plugin_name = plugin_names[index];
const value = plugins_obj[plugin_name];
await func.runtime.resources.run_ui_plugin(options.SESSION_ID, options.paramsP, $elm, plugin_name, value);
}
return {};
},
'xu-store': async function ($elm, val) {
try {
const fields_obj = parse_object_value('xu-store', val, 'object');
const field_ids = Object.keys(fields_obj);
for (let index = 0; index < field_ids.length; index++) {
const field_id = field_ids[index];
func.datasource.add_dynamic_field_to_ds(options.SESSION_ID, options.paramsP.dsSessionP, field_id, fields_obj[field_id]);
}
} catch (err) {
throw err;
}
return {};
},
'xu-viewport': async function () {
return {};
},
};
};
func.runtime.render.build_expression_xu_handler = function (options, common_fx, tag_fx) {
return async function ($elm, val) {
if (!SESSION_OBJ[options.SESSION_ID].DS_GLB[options.paramsP.dsSessionP]) return {};
const exp = val.value === null ? true : val.value;
const xuData = func.runtime.ui.get_data($elm)?.xuData;
const exp_ret = await func.expression.get(
options.SESSION_ID,
exp,
options.paramsP.dsSessionP,
'UI Attr EXP',
SESSION_OBJ[options.SESSION_ID].DS_GLB[options.paramsP.dsSessionP].currentRecordId,
null,
null,
null,
null,
null,
xuData?.iterate_info,
);
return await func.runtime.render.apply_expression_attribute({
$elm,
key: val.key,
exp_ret,
nodeP: options.nodeP,
tag_fx,
common_fx,
});
};
};
func.runtime = func.runtime || {};
func.runtime.ui = func.runtime.ui || {};
func.runtime.render = func.runtime.render || {};
func.runtime.widgets = func.runtime.widgets || {};
// Browser-only tag-specific xu handler factories live here so special-node policy stays isolated.
func.runtime.render.build_tag_xu_handlers = function (options, common_fx) {
return {
'xu-panel': {
program: async function ($elm, val) {
return await func.runtime.render.handle_xu_panel_program({
SESSION_ID: options.SESSION_ID,
$elm,
$container: options.$container,
$root_container: options.$root_container,
nodeP: options.nodeP,
parent_infoP: options.parent_infoP,
paramsP: options.paramsP,
jobNoP: options.jobNoP,
keyP: options.keyP,
parent_nodeP: options.parent_nodeP,
val,
is_init: options.is_init,
refreshed_ds: options.refreshed_ds,
get_params_obj_new: options.get_params_obj_new,
});
},
'xu-render': async function ($elm, val) {
return await common_fx['xu-render']($elm, val, true);
},
'xu-ref': async function ($elm, val) {
if (!val.value) return {};
return await common_fx['xu-ref'](options.$container, val, func.runtime.ui.get_data(options.$container)?.xuData?.xuPanelData?.xuData?.paramsP?.dsSessionP);
},
},
'xu-teleport': {
to: async function ($elm, val) {
return await func.runtime.render.handle_xu_teleport({
SESSION_ID: options.SESSION_ID,
$elm,
$root_container: options.$root_container,
nodeP: options.nodeP,
parent_infoP: options.parent_infoP,
paramsP: options.paramsP,
jobNoP: options.jobNoP,
is_skeleton: options.is_skeleton,
val,
});
},
'xu-render': async function ($elm, val) {
return await common_fx['xu-render']($elm, val, true);
},
'xu-show': async function ($elm, val) {
return await common_fx['xu-show']($elm, val, true);
},
},
};
};
func.runtime = func.runtime || {};
func.runtime.ui = func.runtime.ui || {};
func.runtime.render = func.runtime.render || {};
func.runtime.widgets = func.runtime.widgets || {};
// Browser-only xu handler registry composition lives here so execute_xu_function can ask for one ready object.
func.runtime.render.build_common_xu_handlers = function (options, _ds, tag_fx) {
const common_fx = func.runtime.render.build_base_xu_handlers(options, _ds);
common_fx['xu-exp'] = func.runtime.render.build_expression_xu_handler(options, common_fx, tag_fx);
return common_fx;
};
func.runtime.render.build_xu_handlers = function (options, _ds) {
const common_fx = func.runtime.render.build_base_xu_handlers(options, _ds);
const tag_fx = func.runtime.render.build_tag_xu_handlers(options, common_fx);
common_fx['xu-exp'] = func.runtime.render.build_expression_xu_handler(options, common_fx, tag_fx);
return { common_fx, tag_fx };
};
func.runtime = func.runtime || {};
func.runtime.ui = func.runtime.ui || {};
func.runtime.render = func.runtime.render || {};
func.runtime.widgets = func.runtime.widgets || {};
// Browser-only xu-attribute dispatch lives here so the attribute phase engine can stay focused.
func.runtime.render.build_xu_runtime_error = function (options, error, fallback_message) {
const raw_message = error?.message || error || fallback_message || 'Unknown runtime error';
const err = error instanceof Error ? error : new Error(raw_message);
err.xu_func = options?.xu_func;
err.node_tag = options?.nodeP?.tagName;
err.raw_value = options?.val?.value;
err.ui_id = func.runtime?.ui?.get_attr ? func.runtime.ui.get_attr(options?.$elm, 'xu-ui-id') : null;
return err;
};
func.runtime.render.report_xu_runtime_error = async function (options, error, fallback_message) {
const err = func.runtime.render.build_xu_runtime_error(options, error, fallback_message);
const attr_name = options?.val?.key || options?.xu_func || 'xu-*';
const tag_name = options?.nodeP?.tagName || 'unknown';
const raw_value = typeof err.raw_value === 'string' ? err.raw_value : JSON.stringify(err.raw_value);
const message = [`${attr_name} failed on <${tag_name}>`, err.message];
if (raw_value) {
message.push(`Value: ${raw_value}`);
}
if (err.ui_id) {
message.push(`xu-ui-id: ${err.ui_id}`);
}
if (func.utils?.report_issue) {
await func.utils.report_issue(options?.SESSION_ID, {
source: 'Slim runtime',
message: message.join(' | '),
type: 'E',
err,
details: {
xu_func: options?.xu_func,
attr_name,
tag_name,
raw_value: err.raw_value,
ui_id: err.ui_id,
},
});
}
return {};
};
func.runtime.render.execute_xu_function = async function (options) {
if (options.is_skeleton) return;
const _ds = SESSION_OBJ[options.SESSION_ID].DS_GLB[options.paramsP.dsSessionP];
const handler_bundle = options.handler_bundle || func.runtime.render.build_xu_handlers({
...options,
$live_elm: options.$live_elm || options.$elm,
}, _ds);
const { common_fx, tag_fx } = handler_bundle;
if (func.runtime.render.is_xu_tag(options.nodeP.tagName)) {
if (options.xu_func === 'xu-exp') {
return await common_fx[options.xu_func](options.$elm, options.val);
}
if (tag_fx?.[options.nodeP.tagName]?.[options.xu_func]) {
return await tag_fx[options.nodeP.tagName][options.xu_func](options.$elm, options.val);
}
if (options.nodeP.tagName === 'xu-panel' && !options.xu_func.startsWith('xu-')) {
if (!globalThis.__XUDA_PANEL_PARAM_GATE_LOGGED__) {
globalThis.__XUDA_PANEL_PARAM_GATE_LOGGED__ = true;
globalThis.__XUDA_RT_TRACE && console.log('[xuda-runtime] panel_parameter_attribute ' + JSON.stringify({
change: 'treat_xu_panel_non_runtime_attribute_as_parameter',
}));
}
return {};
}
console.warn(`attribute ${options.xu_func} not found for ${options.nodeP.tagName}`);
return {};
}
if (xu_isEmpty(func.runtime.ui.get_data(options.$elm))) {
return {};
}
if (options.xu_func !== 'xu-exp') {
func.runtime.render.record_attribute_stat(options.$elm, options.xu_func, options.val.value);
}
try {
if (!common_fx[options.xu_func]) {
await func.runtime.render.report_xu_runtime_error(options, null, `Unknown xu directive: ${options.xu_func}`);
return {};
}
return await common_fx[options.xu_func](options.$elm, options.val);
} catch (error) {
return await func.runtime.render.report_xu_runtime_error(options, error);
}
};
func.datasource = {};
// Preserve imperatively-set virtual fields without declarative expressions across the datasource refresh
// row-rebuild, so a refresh does not reset them to static defaults. Kept in a WeakMap off _ds so it never
// enters the update_xu_ref snapshot.
func.datasource.__vf_preserve = new WeakMap();
func.datasource._debug_summarize_set_data_feed = function (data_feed) {
const rows = data_feed?.rows;
const first_row = Array.isArray(rows) ? rows[0] : null;
const summarized_row = {};
if (first_row && typeof first_row === 'object') {
for (const key of Object.keys(first_row).slice(0, 12)) {
const value = first_row[key];
if (typeof value === 'string') {
summarized_row[key] = {
type: 'string',
length: value.length,
empty: value.length === 0,
};
} else if (Array.isArray(value)) {
summarized_row[key] = {
type: 'array',
length: value.length,
};
} else {
summarized_row[key] = {
type: typeof value,
value: value && typeof value === 'object' ? '[object]' : value,
};
}
}
}
return {
rows_length: Array.isArray(rows) ? rows.length : null,
rows_changed_length: Array.isArray(data_feed?.rows_changed) ? data_feed.rows_changed.length : null,
rows_added_length: Array.isArray(data_feed?.rows_added) ? data_feed.rows_added.length : null,
rows_deleted_length: Array.isArray(data_feed?.rows_deleted) ? data_feed.rows_deleted.length : null,
first_row: summarized_row,
};
};
func.datasource.create = async function (
SESSION_ID,
prog_id,
dataSourceNoP = null, // if exist then refresh
parentDataSourceNoP,
containerIdP,
rowIdP,
jobNoP,
calling_trigger_prop,
parameters_raw_obj,
NA_isInitP,
NA_callingSourceP,
calling_jobP,
NA_screen_dsP,
is_panelP,
parameters_obj_inP,
static_refreshP,
worker_id,
NA_eventChangesResults,
) {
// Coalesce concurrent refreshes of the same existing datasource onto the first in-flight create
// promise. Without this, a refresh-triggered render can synchronously re-enter create() for the
// same datasource while the previous pass is still rebuilding rows. Brand-new datasource creation
// is not coalesced, and the flag clears on settle so the next real refresh runs normally.
let _guard_ds = null;
if (dataSourceNoP != null) {
const _guard_session = SESSION_OBJ[SESSION_ID];
_guard_ds = _guard_session?.DS_GLB?.[dataSourceNoP];
if (_guard_ds && _guard_ds._create_in_flight) {
return _guard_ds._create_in_flight;
}
}
const _create_promise = new Promise(async function (resolve, reject) {
if (!prog_id) return reject('Program is empty');
var _session = SESSION_OBJ[SESSION_ID];
if (!_session.DS_GLB) return reject('DS_GLB not exist');
var _prog_obj = await func.utils.VIEWS_OBJ.get(SESSION_ID, prog_id);
if (!_prog_obj) return reject('Program not found');
var args = {
SESSION_ID,
prog_id,
dataSourceNoP,
parentDataSourceNoP,
containerIdP,
rowIdP,
jobNoP,
calling_trigger_prop,
calling_jobP,
is_panelP,
parameters_obj_inP,
static_refreshP,
worker_id,
parameters_raw_obj,
};
var IS_DATASOURCE_REFRESH = null;
var _ds = _session.DS_GLB[dataSourceNoP];
var old_dataSource_vars = {};
if (_ds) IS_DATASOURCE_REFRESH = true;
if (IS_DATASOURCE_REFRESH) {
old_dataSource_vars.sortOrder = _ds.sortOrder;
old_dataSource_vars.sortOrderTypeExp = _ds.sortOrderTypeExp;
if (_ds.data_system) {
old_dataSource_vars.SYS_OBJ_WIN_MODE = _ds.data_system.SYS_OBJ_WIN_MODE;
// old_dataSource_vars.SYS_OBJ_WIN_UI = _ds.data_system.SYS_OBJ_WIN_UI;
old_dataSource_vars.SYS_STR_WIN_ID = _ds.data_system.SYS_STR_WIN_ID;
old_dataSource_vars.SYS_STR_WIN_NAME = _ds.data_system.SYS_STR_WIN_NAME;
}
if (static_refreshP) old_dataSource_vars.in_parameters = _ds.in_parameters;
await func.datasource.update(SESSION_ID, {
[dataSourceNoP]: {
['datasource_main']: {
stat: 'busy',
stat_ts: Date.now(),
is_worker: glb.IS_WORKER,
},
},
});
}
const restore_old_dataSource_vars = function (dsSessionP) {
var _ds = SESSION_OBJ[SESSION_ID].DS_GLB[dsSessionP];
if (_ds.data_system) {
_ds.data_system.SYS_OBJ_WIN_MODE = old_dataSource_vars.SYS_OBJ_WIN_MODE;
// _ds.data_system.SYS_OBJ_WIN_UI = old_dataSource_vars.SYS_OBJ_WIN_UI;
_ds.data_system.SYS_STR_WIN_ID = old_dataSource_vars.SYS_STR_WIN_ID;
_ds.data_system.SYS_STR_WIN_NAME = old_dataSource_vars.SYS_STR_WIN_NAME;
}
if (static_refreshP) _ds.in_parameters = old_dataSource_vars.in_parameters;
};
var run_at = _prog_obj?.properties?.runAt;
if (_session.opt.app_computing_mode === 'main') {
run_at = 'client';
}
if (_prog_obj?.properties.menuType === 'globals') {
run_at = 'client';
}
if (!run_at && parentDataSourceNoP && _session.DS_GLB[parentDataSourceNoP]) {
if (_session.DS_GLB[parentDataSourceNoP]._run_at) run_at = _session.DS_GLB[parentDataSourceNoP].v.run_at;
}
const done = function (SESSION_ID, dsSessionP, response_returned_from_worker) {
var _ds = SESSION_OBJ[SESSION_ID].DS_GLB[dsSessionP];
if (IS_DATASOURCE_REFRESH) {
restore_old_dataSource_vars(dsSessionP);
}
if (!IS_DATASOURCE_REFRESH) {
if (!glb.IS_WORKER) {
DATASOURCE_INTERVALS[SESSION_ID][dsSessionP] = new func.datasource.interval(SESSION_ID, dsSessionP, 'client_interval');
DATASOURCE_INTERVALS[SESSION_ID][dsSessionP].init();
}
}
const set_stat_idle = async function () {
let ds_connected = [];
for (const [dsP, _ds] of Object.entries(_session.DS_GLB)) {
if (_ds.parentDataSourceNo == dsSessionP) {
ds_connected.push(dsP);
}
}
const datasource_changes = {
[dsSessionP]: {
['datasource_main']: {
stat: 'idle',
stat_ts: Date.now(),
is_worker: glb.IS_WORKER,
},
},
};
if (!ds_connected.length) {
return await func.datasource.update(SESSION_ID, datasource_changes);
}
let interval = setInterval(() => {
let idle_count = 0;
for (const dsSession of ds_connected) {
const _ds = _session.DS_GLB[dsSession];
// A connected child datasource that is missing/removed from DS_GLB can never become
// "idle"; reading _ds.stat would throw every tick, so the interval would never clear
// and this datasource would stay non-idle. Treat a missing child as idle so the wait can
// complete.
if (!_ds || _ds.stat == 'idle') {
idle_count++;
}
}
if (ds_connected.length === idle_count) {
clearInterval(interval);
func.datasource.update(SESSION_ID, datasource_changes);
}
}, 1000);
};
set_stat_idle();
resolve({
SESSION_ID,
dsSessionP,
rowIdP: _ds.args.rowIdP,
jobNoP: _ds.args.jobNoP,
callingLogId: _ds.callingLogId,
calling_jobP: _ds.calling_jobP,
});
};
var db_driver;
var is_system_client_vars = false;
if (jobNoP) {
}
if (glb.IS_WORKER || run_at === 'client' || is_system_client_vars || db_driver === 'pouchdb') {
const ret = await func.datasource.prepare(
args.SESSION_ID,
args.prog_id,
args.dataSourceNoP,
args.parentDataSourceNoP,
args.containerIdP,
args.rowIdP,
args.jobNoP,
args.calling_trigger_prop,
args.parameters_raw_obj,
null,
null,
args.calling_jobP,
null,
args.is_panelP,
args.parameters_obj_inP,
args.static_refreshP,
run_at,
worker_id,
);
return done(SESSION_ID, ret.dsSessionP);
}
// vvvv run at worker vvvv
if (_ds) IS_DATASOURCE_REFRESH = true;
var data = Object.assign(
{
session_id: SESSION_ID,
dataSourceSessionGlobal: SESSION_OBJ[SESSION_ID].dataSourceSessionGlobal,
parentDataSourceNo: IS_DATASOURCE_REFRESH ? _ds.parentDataSourceNo : null,
IS_DATASOURCE_REFRESH,
},
args,
);
delete data.SESSION_ID;
const jsonP = await func.index.call_worker(SESSION_ID, {
service: 'datasource_create',
data,
id: SESSION_OBJ[SESSION_ID].worker_id,
});
_session.DS_GLB[jsonP.dsSession] = jsonP;
if (jsonP.dataSourceSessionGlobal > _session.dataSourceSessionGlobal) {
_session.dataSourceSessionGlobal = jsonP.dataSourceSessionGlobal;
}
return done(SESSION_ID, jsonP.dsSession, true);
});
// Publish the in-flight promise on the existing _ds SYNCHRONOUSLY (no await between the
// top guard-check and here) so a synchronous burst of concurrent create(ds5) calls all
// coalesce onto this one promise. Then clear it once the create settles (resolve OR
// reject) so the next genuine refresh runs normally — only removing the flag if it still
// points at THIS promise, never clobbering a newer in-flight create.
if (_guard_ds) {
_guard_ds._create_in_flight = _create_promise;
_create_promise.finally(() => {
const _s = SESSION_OBJ[SESSION_ID];
const _d = _s?.DS_GLB?.[dataSourceNoP];
if (_d && _d._create_in_flight === _create_promise) {
delete _d._create_in_flight;
}
});
}
return _create_promise;
};
func.datasource.prepare = async function (SESSION_ID, prog_id, dataSourceNoP, parentDataSourceNoP, containerIdP, rowIdP, jobNoP, calling_trigger_prop, parameters_raw_obj, NA_isInitP, callingSourceP, calling_jobP, NA_screen_dsP, is_panelP, parameters_obj_inP, static_refreshP, run_atP, worker_id) {
const set_parameters = async function () {
var _session = SESSION_OBJ[SESSION_ID];
const get_Out_parameters = async function (fieldIdP, located_field_param_idxP, param_row_idP) {
var ret = parameters_obj_inP?.[fieldIdP] || fieldIdP;
PARAM_OUT_INFO[prog_id + '_' + param_row_idP] = {
module: _ds.viewModule,
action: 'parameters',
prop: 'out',
details: ret,
result: ret,
source: _ds.viewSourceDesc,
type: 'parameters',
prog_id: prog_id,
dsSession: dataSourceSession,
fieldId: fieldIdP,
parentDataSourceNo: parentDataSourceNoP,
};
return ret;
};
// set parameters list
const screenInfo = await func.utils.get_screen_obj(SESSION_ID, prog_id); // locate root receiving parameters screen id - get root screen info
if (
screenInfo?.properties?.progParams
// &&
// glb.PARAMETER_NODES_ARR.includes(screenInfo.properties.menuType)
) {
if (!xu_isEmpty(screenInfo.properties.progParams)) {
_ds.in_parameters = {};
_ds.out_parameters = {};
for await (let [key, val] of Object.entries(screenInfo.properties?.progParams)) {
// run on parameters arr
if (val.data.dir === 'in') {
_ds.in_parameters[val.data.parameter] = {
// value: parameters_obj_inP?.[val.data.parameter],
type: val.data.type,
};
if (typeof parameters_obj_inP?.[val.data.parameter] !== 'undefined') {
_ds.in_parameters[val.data.parameter].value = parameters_obj_inP[val.data.parameter];
} else if (['live_preview', 'miniapp'].includes(_session.engine_mode)) {
_ds.in_parameters[val.data.parameter].value = _session?.url_params?.[val.data.parameter];
}
continue;
}
if (val.data.dir === 'out' && val.data.parameter) {
_ds.out_parameters[val.data.parameter] = await get_Out_parameters(val.data.parameter, key, val.id);
}
}
_ds.PARAM_OUT_INFO = PARAM_OUT_INFO;
}
}
};
const build_GLOBAL_SYS_fields = function () {
if (!_ds.data_system) _ds.data_system = {};
_ds.data_system['SYS_GLOBAL_UTC'] = -new Date().getTimezoneOffset() / 60;
_ds.data_system['SYS_GLOBAL_STR_APP_ID'] = APP_OBJ[_session.app_id]._id;
_ds.data_system['SYS_GLOBAL_STR_SESSION_ID'] = SESSION_ID;
_ds.data_system['SYS_GLOBAL_STR_LOGIN_USER_ID'] = _session.USR_OBJ._id;
if (!['live_preview', 'miniapp'].includes(_session.engine_mode) && PROJECT_OBJ[_session.app_id].info) {
_ds.data_system['SYS_GLOBAL_OBJ_APP_INFO'] = {
build: PROJECT_OBJ[_session.app_id].info.build_id,
author: PROJECT_OBJ[_session.app_id].info.author,
date: PROJECT_OBJ[_session.app_id].info.build_date,
name: APP_OBJ[_session.app_id].app_name,
};
}
_ds.data_system['SYS_GLOBAL_OBJ_LOGIN_USER_INFO'] = {
id: _session.USR_OBJ._id,
user_name: _session.USR_OBJ.usr_name,
first_name: _session.USR_OBJ.usr_first_name,
last_name: _session.USR_OBJ.usr_last_name,
email: _session.USR_OBJ.usr_email,
profile_picture: _session.USR_OBJ.usr_profile_picture,
};
_ds.data_system['SYS_GLOBAL_STR_BROWSER_HASH_ID'] = _session.SYS_GLOBAL_STR_BROWSER_HASH_ID;
_ds.data_system['SYS_GLOBAL_STR_BROWSER_TITLE'] = _session.SYS_GLOBAL_STR_BROWSER_TITLE;
// }
_ds.data_system['SYS_GLOBAL_STR_SITE_CSS'] = {};
_ds.data_system['SYS_GLOBAL_BOL_SHIFT_KEY_STATE'] = 0;
_ds.data_system['SYS_GLOBAL_BOL_COMMAND_KEY_STATE'] = 0;
_ds.data_system['SYS_GLOBAL_BOL_CONTROL_KEY_STATE'] = 0;
_ds.data_system['SYS_GLOBAL_BOL_ALT_KEY_STATE'] = 0;
_ds.data_system['SYS_GLOBAL_BOL_ONLINE'] = 0;
_ds.data_system['SYS_GLOBAL_BOL_REPLICATION_STAT'] = 0;
_ds.data_system['SYS_GLOBAL_BOL_AJAX_BUSY'] = 0;
_ds.data_system['SYS_GLOBAL_BOL_CONNECTED'] = 1;
_ds.data_system['SYS_GLOBAL_BOL_IDLE'] = 0;
_ds.data_system['SYS_GLOBAL_STR_FIREBASE_TOKEN_ID'] = 0;
_ds.data_system['SYS_GLOBAL_BOL_PUSH_NOTIFICATION_GRANTED'] = _session.PUSH_NOTIFICATION_GRANTED;
_ds.data_system['SYS_GLOBAL_OBJ_FIREBASE_AUTH_INFO'] = _session.SYS_GLOBAL_OBJ_FIREBASE_AUTH_INFO;
_ds.data_system['SYS_GLOBAL_OBJ_CLIENT_INFO'] = _session.SYS_GLOBAL_OBJ_CLIENT_INFO;
_ds.data_system['SYS_GLOBAL_OBJ_REFS'] = {};
};
if (!SESSION_OBJ[SESSION_ID].DS_GLB) return;
if (dataSourceNoP && !SESSION_OBJ[SESSION_ID].DS_GLB[dataSourceNoP]) {
return func.utils.debug_report(SESSION_ID, 'Datasource', 'Datasource not exist: ' + dataSourceNoP, 'E');
}
if (!prog_id) {
return func.utils.debug_report(SESSION_ID, 'Datasource', 'Program is null', 'E');
}
const args = {
SESSION_ID,
prog_id,
dataSourceNoP,
parentDataSourceNoP,
containerIdP,
rowIdP,
jobNoP,
calling_trigger_prop,
calling_jobP,
is_panelP,
parameters_obj_inP,
static_refreshP,
run_atP,
worker_id,
parameters_raw_obj,
};
var dataSourceSession = null;
var IS_DATASOURCE_REFRESH = null;
var PARAM_OUT_INFO = {};
const init_dataSource = async function () {
const init_new_dataSource = async function () {
if (!['main'].includes(SESSION_OBJ[SESSION_ID].opt.app_computing_mode) && run_atP === 'client' && prog_id !== 'system') {
const ret = await func.index.call_worker(SESSION_ID, {
service: 'get_dataSourceSessionGlobal',
data: { session_id: SESSION_ID },
id: SESSION_OBJ[SESSION_ID].worker_id,
});
SESSION_OBJ[SESSION_ID].dataSourceSessionGlobal = ret?.new_dataSourceSessionGlobal || 1;
} else {
SESSION_OBJ[SESSION_ID].dataSourceSessionGlobal++;
}
dataSourceSession = SESSION_OBJ[SESSION_ID].dataSourceSessionGlobal;
SESSION_OBJ[SESSION_ID].DS_GLB[dataSourceSession] = {
data_feed: { rows: [] },
};
};
const init_existing_dataSource = function () {
let _ds = SESSION_OBJ[SESSION_ID].DS_GLB[dataSourceNoP];
console.log('DATASOURCE_REFRESH', dataSourceNoP);
if (!_ds) {
return;
}
IS_DATASOURCE_REFRESH = true;
dataSourceSession = dataSourceNoP;
_ds.refreshed = true;
if (_ds.watcher) {
xu_set(_ds, _ds.watcher.path, _ds.watcher.newValue);
}
try {
if (!_ds.v) _ds.v = {};
delete _ds.v.old_dataSource; // to eliminate parse error
delete _ds.rows_found;
try {
if (_ds.data_feed && _ds.data_feed.rows && _ds.data_feed.rows[0]) {
func.datasource.__vf_preserve.set(_ds, Object.assign({}, _ds.data_feed.rows[0]));
}
} catch (e) {}
// B1: keep the full pre-refresh row set so the render layer can detect a no-op
// refresh (identical rows) and skip rebuilding the list (see render_multi_view_node).
_ds.__refresh_prev_rows = _ds.data_feed && Array.isArray(_ds.data_feed.rows) ? _ds.data_feed.rows : null;
_ds.data_feed = {};
_ds.v.old_dataSource = {
currentRecordId: _ds.currentRecordId,
firstRecordId: _ds.firstRecordId,
finalRecordId: _ds.finalRecordId,
locatedRecordId: _ds.locatedRecordId,
sortOrder: _ds.sortOrder,
sortOrderTypeExp: _ds.sortOrderTypeExp,
};
} catch (err) {
console.error('function: init_existing_dataSource - error', err);
}
};
if (typeof dataSourceNoP === 'undefined' || dataSourceNoP === null) {
await init_new_dataSource();
} else {
init_existing_dataSource();
}
return SESSION_OBJ[SESSION_ID].DS_GLB[dataSourceSession];
};
var _ds = await init_dataSource();
if (!_ds) {
return func.utils.debug_report(SESSION_ID, 'Datasource', 'Datasource refresh failed: ' + dataSourceNoP, 'E');
}
_ds.stat = 'busy';
_ds._run_at = run_atP;
if (_ds.refreshed) {
await func.datasource.update(SESSION_ID, {
[_ds.dsSession]: {
['datasource_main']: {
stat: 'busy',
stat_ts: Date.now(),
is_worker: glb.IS_WORKER,
},
},
});
}
// init_v();
if (IS_DATASOURCE_REFRESH) {
if (!static_refreshP) await set_parameters(); // do only on new datasource or refresh
return func.datasource.execute(SESSION_ID, dataSourceSession, true);
}
_ds.tree_obj = await func.utils.TREE_OBJ.get(SESSION_ID, prog_id);
if (!_ds.tree_obj) {
return func.utils.debug_report(SESSION_ID, 'Datasource', 'Program not exist: ' + prog_id, 'E');
}
await func.datasource.set_VIEW_data(SESSION_ID, args, _ds);
if (
!_ds.v.viewSourceDesc // in case of event
) {
_ds.v.viewSourceDesc = callingSourceP;
}
if (dataSourceSession === 0) _ds.v.viewSourceDesc = 'system startup';
var _session = SESSION_OBJ[SESSION_ID];
const set_DS_GLB = async function () {
_ds.dataSource_init_arr = {};
_ds.containerId = containerIdP;
_ds.jobNoP = jobNoP;
_ds.viewSourceDesc = _ds.v.viewSourceDesc;
_ds.callingSource = callingSourceP;
_ds.calling_jobP = calling_jobP;
_ds.viewModule = _ds.v.viewModule;
_ds.viewSourceProp = _ds.v.viewSourceProp;
_ds.dsSession = dataSourceSession;
// _ds.v = v;
_ds.args = args;
_ds.worker_id = worker_id;
_ds.prog_id = prog_id;
// if (!IS_DATASOURCE_REFRESH) {
_ds.parentDataSourceNo = parentDataSourceNoP;
// }
};
await set_DS_GLB();
if (
prog_id === 'system' &&
!parentDataSourceNoP // do only on first time datasource 0 call
) {
build_GLOBAL_SYS_fields();
}
// ======================================
// PARAMETERS
//======================================
await set_parameters();
// ======================================
// INTERVALS
//======================================
_ds.client_interval = func.datasource.get_event_interval_arr(SESSION_ID, dataSourceSession, 'client_interval');
if (prog_id === 'system') {
_ds.server_interval = func.datasource.get_event_interval_arr(SESSION_ID, dataSourceSession, 'server_interval');
}
// if (static_refreshP) {
// delete _ds.raw_data;
// }
// if (!static_refreshP) await set_parameters(); // do only on new datasource or refresh
// try {
let ret_execute = await func.datasource.execute(SESSION_ID, dataSourceSession);
return ret_execute;
// } catch (e) {
// console.error(e);
// }
};
func.datasource.execute = async function (SESSION_ID, dataSourceSession, IS_DATASOURCE_REFRESH) {
var _session = SESSION_OBJ[SESSION_ID];
var _ds = _session.DS_GLB[dataSourceSession];
var args = _ds.args;
// var v = _ds.v;
let tree_obj = await func.utils.TREE_OBJ.get(SESSION_ID, _ds.prog_id);
let prog_obj = await func.utils.VIEWS_OBJ.get(SESSION_ID, _ds.prog_id);
const normalize_filter_model = function (value) {
if (value === null || typeof value === 'undefined') {
return undefined;
}
if (typeof value === 'string') {
const trimmed = value.trim();
if (!trimmed) {
return undefined;
}
if (trimmed.startsWith('{') || trimmed.startsWith('[')) {
try {
return JSON.parse(trimmed);
} catch (err) {
return value;
}
}
}
return value;
};
const callback_datasource = async function () {
const run_on_load_events = async function () {
if (!(await func.datasource.get_view_events_count(SESSION_ID, dataSourceSession, 'on_load'))) {
return false;
}
await func.datasource.execute_view_events(SESSION_ID, dataSourceSession, 'on_load');
return true;
};
const schedule_panel_on_load_events = function () {
setTimeout(async function () {
try {
await run_on_load_events();
} catch (error) {
console.error(error);
}
}, 0);
};
if (typeof IS_WORKER === 'undefined' && typeof IS_DOCKER === 'undefined' && typeof IS_PROCESS_SERVER === 'undefined' && _ds.viewSourceProp === 'globals') {
if (!['main'].includes(_session.opt.app_computing_mode)) {
await func.index.call_worker(SESSION_ID, {
service: 'create_webworker_globals',
data: { ds_data: _ds, session_id: SESSION_ID },
});
}
}
// on_load view events fire on INITIAL load only, never on a datasource REFRESH —
// the same once-per-screen rule as screen_ready. Re-firing on every refresh lets an
// on_load event that raises a render/fetch event (e.g. RENDER_PAGE_EVENT -> get_data +
// field update) re-render the screen, which refreshes the datasource, which re-fires
// on_load -> ... an infinite render loop (the panel "flicker"). A refresh reuses the
// same datasource session (IS_DATASOURCE_REFRESH); navigation creates a new one and
// fires on_load there as expected.
if (args.is_panelP) {
const callback_ret = await func.datasource.callback(SESSION_ID, dataSourceSession, args.rowIdP, args.jobNoP, _ds.prog_id);
if (!IS_DATASOURCE_REFRESH) schedule_panel_on_load_events();
return callback_ret;
}
if (!IS_DATASOURCE_REFRESH) await run_on_load_events();
return await func.datasource.callback(SESSION_ID, dataSourceSession, args.rowIdP, args.jobNoP, _ds.prog_id);
};
const get_limit = async function () {
var ret = 0;
let tree_ret = await func.utils.TREE_OBJ.get(SESSION_ID, _ds.prog_id);
if (tree_ret.menuType === 'get_data') {
return 1;
}
ret = _ds.progDataSource?.dataSourceLimit;
if (prog_obj.progDataSource?.dataSourceLoopExp) {
ret = (await func.expression.get(SESSION_ID, prog_obj.progDataSource.dataSourceLoopExp, dataSourceSession, 'view_loop', args.rowIdP)).result;
}
return ret;
};
const get_skip = async function () {
var ret = 0;
ret = _ds.progDataSource?.dataSourceSkip;
if (prog_obj.progDataSource?.dataSourceSkipExp) {
ret = (await func.expression.get(SESSION_ID, prog_obj.progDataSource.dataSourceSkipExp, dataSourceSession, 'view_loop', args.rowIdP)).result;
}
return ret;
};
const calc_batch_loops = async () => {
if (!prog_obj.progDataSource?.dataSourceType || _ds.progDataSource.dataSourceType === 'none') {
_ds.v.batch_loops = await get_limit();
return false;
}
_ds.v.batch_loops = (await get_limit()) <= _ds.v.raw_data?.rows?.length ? await get_limit() : _ds.v.raw_data?.rows?.length;
return true;
};
const render_api_output = async function () {
if (prog_obj?.scriptData?.value) {
var exp = await func.expression.get(SESSION_ID, prog_obj.scriptData.value, dataSourceSession, 'api_rendered_output', null, null, null, null, null, null, null, null, null, tree_obj.apiOutput);
let output_result = exp.result;
if (tree_obj.apiOutput === 'json') {
// iterate object to fix expressions
try {
// let output_result_obj = JSON5.parse(output_result)
let output_result_obj = await func.expression.secure_eval(SESSION_ID, 'api_rendered_output', '(' + output_result + ')', null, dataSourceSession);
// for await (let [key, val] of Object.entries(output_result_obj)) {
// output_result_obj[key] = (await func.expression.get(
// SESSION_ID,
// val,
// dataSourceSession, "object_property")).result
// }
output_result = JSON.stringify(output_result_obj);
} catch (err) {
console.error(err);
}
}
_ds.api_rendered_output += output_result + (tree_obj.apiOutput === 'json' ? ',' : '');
} else {
_ds.api_rendered_output = ''; //empty
}
};
// ======================================
// COMPUTE GLOBALS
// ======================================
if (_ds.prog_id === 'system') {
//TBD tree_obj.menuType === "globals"
_ds.currentRecordId = 'dataset';
await func.datasource.render_fields_dataset(SESSION_ID, dataSourceSession, {
id: 'dataset',
value: _session.url_params,
});
return await callback_datasource();
}
// ======================================
// BUILD DATA SOURCE
//======================================
let db_adapter_module;
if (prog_obj.progDataSource?.dataSourceType) {
db_adapter_module = await func.common.get_module(SESSION_ID, 'xuda-datasource-db-adapter-module.mjs');
}
const get_data_from_source = async function () {
switch (prog_obj.progDataSource.dataSourceSrcType) {
case 'input': {
const { result, error } = await func.expression.get(SESSION_ID, prog_obj.progDataSource.progDataSourceInput, dataSourceSession, 'datasource select');
if (error) {
func.utils.debug_report(SESSION_ID, 'Data source', `Datasource parse error using ${prog_obj.progDataSource?.dataSourceType} input`, 'E');
return null;
}
return result;
break;
}
case 'url': {
let opt = {
method: prog_obj.progDataSource.dataSourceMethod || 'POST',
headers: {
Accept: 'application/json',
'Content-Type': 'application/json',
},
};
let data = {};
if (prog_obj.progDataSource.dataSourceMethod == 'POST' && prog_obj.progDataSource.dataSourceParameters) {
for (let val of prog_obj.progDataSource.dataSourceParameters) {
data[val.key] = val.val;
}
opt.body = JSON.stringify(data);
}
try {
const response = await fetch('https://' + prog_obj.progDataSource.dataSourceDataUrl, opt);
const json = await response.json();
return json.data;
} catch (err) {
func.utils.debug_report(SESSION_ID, 'Data source', err.message + ' https://' + prog_obj.progDataSource.dataSourceDataUrl, 'E');
return null;
}
break;
}
default:
return null;
break;
}
};
if (!_ds.v.raw_data) {
_ds.v.raw_data = { rows: [] };
}
_ds.data_feed.rows = [];
switch (prog_obj.progDataSource?.dataSourceType) {
case 'table': {
_ds._dataSourceTableId = prog_obj.progDataSource?.dataSourceTableId; // get file id
if (prog_obj.progDataSource?.dataSourceTableIdExp) {
_ds.v.dataSourceTableIdExp = await func.expression.get(SESSION_ID, prog_obj.progDataSource?.dataSourceTableIdExp, dataSourceSession, 'dataSourceTableIdExp', args.rowIdP);
if (_ds.v.dataSourceTableIdExp.result) {
_ds._dataSourceTableId = _ds.v.dataSourceTableIdExp.result;
} else {
func.utils.debug_report(SESSION_ID, 'get_VIEW_data', 'Table Expression returned empty result', 'W');
}
}
if (!_ds._dataSourceTableId) {
return func.utils.debug_report(SESSION_ID, 'Data source', 'Table cannot be empty when Db Table selected', 'E');
}
let table_ret = await func.utils.TREE_OBJ.get(SESSION_ID, _ds._dataSourceTableId);
if (!table_ret) {
return func.utils.debug_report(SESSION_ID, 'Data source', 'Table not found: ' + _ds._dataSourceTableId, 'E');
}
await db_adapter_module.build_filter(SESSION_ID, dataSourceSession, _ds.v, _ds);
let filterModelMongo = _ds.progDataSource.filterModelMongo;
if (_ds.progDataSource.filterModelMongoFx) {
let ret = await func.expression.get(SESSION_ID, _ds.progDataSource.filterModelMongoFx, dataSourceSession, 'query', _ds.args.rowIdP);
filterModelMongo = ret.result;
}
filterModelMongo = normalize_filter_model(filterModelMongo);
let filterModelSql = _ds.progDataSource.filterModelSql;
if (_ds.progDataSource.filterModelSqlFx) {
let ret = await func.expression.get(SESSION_ID, _ds.progDataSource.filterModelSqlFx, dataSourceSession, 'query', _ds.args.rowIdP);
filterModelSql = ret.result;
}
filterModelSql = normalize_filter_model(filterModelSql);
const filterModel = {
filterModelNative: normalize_filter_model(_ds.progDataSource.filterModelNative),
filterModelMongo,
filterModelSql,
filterModelUserMongo: normalize_filter_model(_ds.progDataSource.filterModelUserMongo),
filterModelUserSql: normalize_filter_model(_ds.progDataSource.filterModelUserSql),
};
let _dataSourceFilterModelType = _ds?.progDataSource?.dataSourceFilterModelType;
if (_ds?.progDataSource?.dataSourceFilterModelTypeFx) {
const fx_ret = await func.expression.get(SESSION_ID, _ds.progDataSource.dataSourceFilterModelTypeFx, dataSourceSession, 'query', _ds.args.rowIdP);
_dataSourceFilterModelType = fx_ret.result;
}
// Infer 'index' from a configured index when no explicit type is set, so
// index datasources without an explicit dataSourceFilterModelType still
// apply their index filter. Prefer the value build_filter already resolved
// on _ds.v (it sees the full progDataSource incl. the index id), then fall
// back to inferring from the index id directly.
_dataSourceFilterModelType =
_dataSourceFilterModelType ||
_ds?.v?.dataSourceFilterModelType ||
(_ds?.progDataSource?.dataSourceIndexId || _ds?.progDataSource?.dataSourceIndexIdExp ? 'index' : 'query');
if (_dataSourceFilterModelType && !['query', 'index'].includes(_dataSourceFilterModelType)) {
return func.utils.debug_report(SESSION_ID, 'Data source', `Valid values for dataSourceFilterModelType are: "query" or "index" (${_dataSourceFilterModelType})`, 'E');
}
const sortModel = Array.isArray(_ds?.progDataSource?.sortModel) ? _ds.progDataSource.sortModel : [];
// An EMPTY sortModel must be sent as null, not []. get_query does
// `if (sortModel) data.sortModel = JSON.stringify(sortModel)` and [] is
// truthy, so it forwards sortModel:"[]" to the backend, which overrides the
// configured index's natural key order with an unsorted (_id) order. Index
// datasources that rely on their index ordering (no explicit sort model)
// were rendering unsorted. Only send a real, non-empty sort model.
const sortModelForDb = _dataSourceFilterModelType === 'query' || !sortModel.length ? null : sortModel;
_ds.v.raw_data = await func.db.get_query(
SESSION_ID,
_ds._dataSourceTableId,
_ds.v.couchView,
dataSourceSession,
_ds.viewSourceDesc,
'datasource table',
prog_obj.progDataSource.dataSourceReduce,
await get_skip(),
(await get_limit()) || 99999999,
null,
null,
sortModelForDb,
null,
filterModel,
_dataSourceFilterModelType,
);
if (sortModel.length && _ds?.v?.raw_data?.rows?.length) {
function sortByKeys(array, sortConfig) {
return array.sort((a, b) => {
for (let config of sortConfig) {
const key = config.field_id || config.colId;
const direction = (config.sort_dir || config.sort) === 'desc' ? -1 : 1;
const valA = a.value[key];
const valB = b.value[key];
if (typeof valA === 'undefined' && typeof valB === 'undefined') {
continue;
}
if (typeof valA === 'undefined') {
return 1;
}
if (typeof valB === 'undefined') {
return -1;
}
// Handle numeric comparison
if (typeof valA === 'number' && typeof valB === 'number') {
if (valA !== valB) {
return (valA - valB) * direction;
}
}
// Handle string comparison
else if (typeof valA === 'string' && typeof valB === 'string') {
if (valA !== valB) {
return valA.localeCompare(valB) * direction;
}
} else if (valA !== valB) {
return String(valA).localeCompare(String(valB)) * direction;
}
}
return 0;
});
}
const sorted = sortByKeys(_ds.v.raw_data.rows, _ds.progDataSource.sortModel);
_ds.v.raw_data.rows = sorted;
}
if (_ds?.progDataSource?.dataSourceLimit) {
const ret_rows_found = await func.db.get_query(SESSION_ID, _ds._dataSourceTableId, _ds.v.couchView, dataSourceSession, _ds.viewSourceDesc, 'datasource table', prog_obj.progDataSource.dataSourceReduce, null, null, true, null, null, null, filterModel, _dataSourceFilterModelType);
_ds.rows_found = ret_rows_found?.rows?.[0]?.value || 0;
_ds.rows_found_opt = ret_rows_found?.opt;
} else {
_ds.rows_found = _ds?.v?.raw_data?.rows?.length || 0;
_ds.rows_found_opt = _ds?.v?.raw_data?.opt;
}
break;
}
case 'array': {
let data = await get_data_from_source();
if (data === null) {
data = [];
}
_ds.rows_found = data?.length || 0;
let _KEY = 0;
for (const _VAL of data) {
_ds.v.raw_data.rows.push({ id: _KEY, value: { _KEY, _VAL } });
_KEY++;
}
break;
}
case 'json': {
let data = await get_data_from_source();
if (data === null) {
data = {};
}
_ds.rows_found = Object.keys(data)?.length || 0;
for (let [_KEY, _VAL] of Object.keys(data)) {
_ds.v.raw_data.rows.push({ id: _KEY, value: { _KEY, _VAL } });
}
break;
}
case 'csv': {
let data = await get_data_from_source();
if (data === null) {
data = '';
}
let _KEY = 0;
let arr = data.split(',');
for (const _VAL of arr) {
_ds.v.raw_data.rows.push({ id: _KEY, value: { _KEY, _VAL } });
_KEY++;
}
_ds.rows_found = arr?.length || 0;
break;
}
default:
break;
}
// ======================================
// EXECUTE
// ======================================
let ret;
const get_before_record_count = async () => {
return await func.datasource.get_view_events_count(SESSION_ID, dataSourceSession, 'before_record');
};
const get_after_record_count = async () => {
return await func.datasource.get_view_events_count(SESSION_ID, dataSourceSession, 'after_record');
};
let _raw_data_rows = [];
switch (tree_obj.menuType) {
case 'api': {
_ds.api_rendered_output = '';
let has_datasource = await calc_batch_loops();
_raw_data_rows = _ds.v.raw_data.rows || [];
if (!has_datasource) {
for (n = 0; n < _ds.v.batch_loops; n++) {
_raw_data_rows.push({ id: n, value: {} });
}
}
_ds.currentRecordId = 'dataset';
for await (let [key, raw_data_row] of Object.entries(_raw_data_rows)) {
if (has_datasource && Number(key) >= _ds.v.batch_loops) break;
if (!has_datasource) {
raw_data_row = _ds?.v.raw_data?.rows?.[key] || { id: key, value: {} };
}
if (await get_before_record_count()) {
await func.datasource.execute_view_events(SESSION_ID, dataSourceSession, 'before_record');
}
await func.datasource.render_fields_dataset(SESSION_ID, dataSourceSession, raw_data_row);
if (await get_after_record_count()) {
await func.datasource.execute_view_events(SESSION_ID, dataSourceSession, 'after_record');
}
await render_api_output();
}
if (tree_obj.apiOutput === 'json') {
var str = _ds.api_rendered_output.substring(0, _ds.api_rendered_output.length - 1);
if (Number(_ds.progDataSource?.dataSourceLimit) === 1) {
_ds.api_rendered_output = str;
} else {
_ds.api_rendered_output = '[' + str + ']';
}
}
break;
}
case 'batch': {
let has_datasource = await calc_batch_loops();
_raw_data_rows = _ds?.v.raw_data?.rows || [];
if (!has_datasource) {
for (n = 0; n < _ds.v.batch_loops; n++) {
_raw_data_rows.push({ id: n, value: {} });
}
}
_ds.currentRecordId = 'dataset';
for await (let [key, raw_data_row] of Object.entries(_raw_data_rows)) {
if (has_datasource && Number(key) >= _ds.v.batch_loops) break;
if (!has_datasource) {
raw_data_row = _ds?.v.raw_data?.rows?.[key] || { id: key, value: {} };
}
if (await get_before_record_count()) {
await func.datasource.execute_view_events(SESSION_ID, dataSourceSession, 'before_record');
}
await func.datasource.render_fields_dataset(SESSION_ID, dataSourceSession, raw_data_row);
if (await get_after_record_count()) {
await func.datasource.execute_view_events(SESSION_ID, dataSourceSession, 'after_record');
}
}
await func.datasource.set_outputField(SESSION_ID, dataSourceSession, _ds?.v?.raw_data?.rows, _ds.args);
break;
}
case 'get_data': {
if (await get_before_record_count()) {
await func.datasource.execute_view_events(SESSION_ID, dataSourceSession, 'before_record');
}
ret = await db_adapter_module.process_view_dataset(SESSION_ID, dataSourceSession, _ds);
if (await get_after_record_count()) {
await func.datasource.execute_view_events(SESSION_ID, dataSourceSession, 'after_record');
}
await func.datasource.set_outputField(SESSION_ID, dataSourceSession, _ds?.v?.raw_data?.rows, _ds.args);
break;
}
case 'set_data': {
if (!prog_obj.progDataSource?.dataSourceType || _ds.progDataSource.dataSourceType !== 'table' || !_ds._dataSourceTableId) {
return func.utils.debug_report(SESSION_ID, 'Data source', 'Datasource DB Table must be defined for Set Data operation', 'E');
}
const find_ROWID_idx_from_raw_data_arr = function (rowId) {
if (!_raw_data_rows) {
throw new Error('_raw_data_rows not found');
}
const index = _raw_data_rows.findIndex((item) => item.id === rowId);
if (index === -1) {
throw new Error(`ROWID "${rowId}" not found`);
}
return index;
};
if (tree_obj.crudMode === 'U') {
_ds.set_mode = 'U';
_raw_data_rows = _ds?.v.raw_data?.rows || [];
}
if (tree_obj.crudMode === 'D') {
_ds.set_mode = 'D';
_raw_data_rows = _ds?.v.raw_data?.rows || [];
}
// initiated with Update but no rows found
if (tree_obj.crudMode === 'U' && tree_obj.allowCreate && !_raw_data_rows?.length) {
_ds.set_mode = 'C';
try {
const row_idx = find_ROWID_idx_from_raw_data_arr('newRecord');
_raw_data_rows[row_idx] = { id: 'newRecord', value: {} };
} catch (error) {
_raw_data_rows.push({ id: 'newRecord', value: {} });
}
}
if (tree_obj.crudMode === 'C') {
_ds.set_mode = 'C';
try {
const row_idx = find_ROWID_idx_from_raw_data_arr('newRecord');
_raw_data_rows[row_idx] = [{ id: 'newRecord', value: {} }];
} catch (error) {
_raw_data_rows.push({ id: 'newRecord', value: {} });
}
}
const trace_set_data = function (label, payload) {
if (String(_ds?.prog_id || '') !== '1630849293262' && String(_ds?._dataSourceTableId || '') !== '1630542401398') return;
try {
globalThis.__XUDA_RT_TRACE && console.log('[xuda-runtime] set_data_trace ' +
JSON.stringify({
version: 'runtime-refresh-20260629-set-data-remote-save',
label,
dataSourceSession,
prog_id: _ds?.prog_id,
table_id: _ds?._dataSourceTableId,
set_mode: _ds?.set_mode,
currentRecordId: _ds?.currentRecordId,
...payload,
}),
);
} catch (err) {
console.warn('[xuda-runtime] set_data_trace_failed', err);
}
};
trace_set_data('start', {
crudMode: tree_obj.crudMode,
allowCreate: tree_obj.allowCreate,
raw_rows_length: _raw_data_rows?.length || 0,
data_feed: func.datasource._debug_summarize_set_data_feed(_ds.data_feed),
});
for await (let raw_data_row of _raw_data_rows) {
_ds.currentRecordId = raw_data_row.id;
let data_feed_str = JSON.stringify(_ds.data_feed);
trace_set_data('before_record', {
raw_row_id: raw_data_row.id,
data_feed: func.datasource._debug_summarize_set_data_feed(_ds.data_feed),
});
if (await get_before_record_count()) {
await func.datasource.execute_view_events(SESSION_ID, dataSourceSession, 'before_record');
}
await func.datasource.render_fields_dataset(SESSION_ID, dataSourceSession, raw_data_row);
if (await get_after_record_count()) {
await func.datasource.execute_view_events(SESSION_ID, dataSourceSession, 'after_record');
}
const data_feed_after_str = JSON.stringify(_ds.data_feed);
const should_save = _ds.set_mode === 'C' || data_feed_after_str !== data_feed_str;
trace_set_data('save_decision', {
should_save,
changed: data_feed_after_str !== data_feed_str,
data_feed: func.datasource._debug_summarize_set_data_feed(_ds.data_feed),
});
if (should_save) {
const dbMsgP = await func.db.save_data(SESSION_ID, dataSourceSession);
trace_set_data('save_result', {
result: dbMsgP
? {
code: dbMsgP.code,
id: dbMsgP.id || dbMsgP.data?.id,
data_id: dbMsgP.data?.id,
message: dbMsgP.message,
}
: null,
});
if (dbMsgP) _ds.currentRecordId = dbMsgP.id;
_ds.set_mode = 'U';
}
if (_ds.set_mode === 'D') {
const dbMsgP = await func.db.save_data(SESSION_ID, dataSourceSession);
if (dbMsgP) _ds.currentRecordId = dbMsgP.id;
}
}
await func.datasource.set_outputField(SESSION_ID, dataSourceSession, _ds?.v?.raw_data?.rows, _ds.args);
break;
}
case 'component': {
_raw_data_rows = _ds?.v.raw_data?.rows || [];
_ds.rows_processed = 0;
_ds.viewRangeExp_rows_deleted = 0;
let rows = _ds?.v.raw_data?.rows?.length;
_ds.data_feed.rows_changed = [];
_ds.data_feed.rows_deleted = [];
_ds.data_feed.rows_added = [];
if (tree_obj.rwMode === 'U') {
_ds.set_mode = 'U';
} else {
_ds.set_mode = 'R';
}
const row_not_found = async function () {
if (!prog_obj.progDataSource?.dataSourceType || prog_obj.properties.renderType === 'form' || (tree_obj.rwMode === 'U' && tree_obj.allowCreate)) {
_ds.currentRecordId = 'newRecord';
if (tree_obj.rwMode === 'U' && tree_obj.allowCreate) {
_ds.set_mode = 'C';
}
if (prog_obj.progDataSource?.dataSourceType) {
_ds.record_not_found = true;
}
try {
const row_idx = func.common.find_ROWID_idx(_ds, _ds.currentRecordId);
} catch (error) {
await func.datasource.render_fields_form(SESSION_ID, dataSourceSession, { id: 'newRecord', value: {} });
}
var count = await func.datasource.get_field_init_count(SESSION_ID, dataSourceSession, 'newRecord', false);
if (
count > 0 // was: && !args.dataSourceNoP
) {
await func.datasource.execute_field_init_events(SESSION_ID, dataSourceSession, 'form', 'newRecord');
}
} else {
_ds.record_not_found = true;
delete _ds.currentRecordId;
delete _ds.firstRecordId;
delete _ds.finalRecordId;
delete _ds.locatedRecordId;
}
await func.datasource.callback(SESSION_ID, dataSourceSession, args.rowIdP, args.jobNoP, _ds.prog_id);
};
if (!rows) {
await row_not_found();
break;
}
_ds.firstRecordId = _raw_data_rows[0].id;
const finish_form = async function () {
// check if locatedRecordId exist in SESSION_OBJ[SESSION_ID].DS_GLB
if (_ds.locatedRecordId) {
try {
const row_idx = func.common.find_ROWID_idx(_ds, _ds.locatedRecordId);
} catch (error) {
delete _ds.locatedRecordId;
}
}
_ds.finalRecordId = func.datasource.get_currentRecordId(SESSION_ID, dataSourceSession, true);
_ds.currentRecordId = _ds.finalRecordId;
};
for await (const [key, raw_data_row] of Object.entries(_raw_data_rows)) {
const idx = Number(key);
if (await get_before_record_count()) {
await func.datasource.execute_view_events(SESSION_ID, dataSourceSession, 'before_record');
}
_ds.currentRecordId = raw_data_row.id; // set temporary to allow expression decoder work
await func.datasource.render_fields_form(SESSION_ID, dataSourceSession, raw_data_row);
try {
const init_count = await func.datasource.get_field_init_count(SESSION_ID, dataSourceSession, raw_data_row.id, false, _ds.oninit_triggers_to_run);
if (init_count > 0) {
await func.datasource.execute_field_init_events(SESSION_ID, dataSourceSession, 'form', raw_data_row.id);
}
} catch (err) {
console.error(err);
}
if (await get_after_record_count()) {
await func.datasource.execute_view_events(SESSION_ID, dataSourceSession, 'after_record');
}
}
await finish_form();
break;
}
default:
return func.utils.debug_report(SESSION_ID, 'Data source', 'Program type not defined', 'E');
}
ret = await callback_datasource();
return ret;
};
func.datasource.render_fields_dataset = async function (SESSION_ID, dataSourceSession, raw_data_row) {
var _ds = SESSION_OBJ[SESSION_ID].DS_GLB[dataSourceSession];
var args = _ds.args;
const _progFields = await func.datasource.get_progFields(SESSION_ID, dataSourceSession);
if (!_progFields) {
return;
}
const get_value = async (field_id, value) => {
let view_field_obj = func.common.find_item_by_key(_progFields, 'field_id', field_id);
var fieldType = view_field_obj?.props?.fieldType;
let table_field_obj;
if (view_field_obj.data.type === 'table' && field_id !== 'REDUCE_VALUE') {
if (!_ds.progDataSource?.dataSourceTableId) {
return func.utils.debug_report(SESSION_ID, 'Datasource', `Table type defined without dataSourceTableId deceleration`, 'E');
}
let table_obj = await func.utils.FILES_OBJ.get(SESSION_ID, _ds._dataSourceTableId);
if (!table_obj) {
return func.utils.debug_report(SESSION_ID, 'Datasource', `dataSourceTableId reference error: ` + _ds._dataSourceTableId, 'E');
}
table_field_obj = func.common.find_item_by_key(table_obj.tableFields, 'field_id', field_id);
fieldType = table_field_obj.props?.fieldType;
}
return await func.common.get_cast_val(SESSION_ID, `render fields dataset ${_ds.viewSourceDesc}`, field_id, fieldType, value, null);
};
if (!_ds.data_feed) {
_ds.data_feed = { rows: [{ _ROWID: _ds.currentRecordId }] };
}
let row_idx;
try {
row_idx = func.common.find_ROWID_idx(_ds, _ds.currentRecordId);
} catch (err) {
_ds.data_feed.rows.push({ _ROWID: _ds.currentRecordId });
row_idx = func.common.find_ROWID_idx(_ds, _ds.currentRecordId);
// console.error(err);
}
_ds.dataset_alias = {};
for await (const val of _progFields) {
try {
var fieldId = val.data.field_id;
if (val.data.type === 'virtual' || _ds.set_mode === 'C') {
if (typeof raw_data_row?.value?.[fieldId] !== 'undefined') {
// supports x=x+1
_ds.data_feed.rows[row_idx][fieldId] = await get_value(fieldId, raw_data_row.value[fieldId]);
continue;
}
if (val.props?.propExpressions?.fieldValue) {
let ret = await func.expression.get(SESSION_ID, val.props?.propExpressions?.fieldValue, dataSourceSession, 'update', args.rowIdP);
_ds.data_feed.rows[row_idx][fieldId] = await get_value(fieldId, ret.result);
continue;
}
_ds.data_feed.rows[row_idx][fieldId] = await get_value(fieldId, val.props?.fieldValue);
continue;
}
if (val.data.type === 'table' || val.data.type === 'datasource') {
if (typeof raw_data_row.value[fieldId] === 'undefined') {
throw 'field do not exist in data: ' + fieldId;
}
_ds.data_feed.rows[row_idx][fieldId] = await get_value(fieldId, raw_data_row.value[fieldId]);
}
} catch (err) {
func.utils.debug_report(SESSION_ID, 'Datasource', err, 'E', null, _ds);
}
}
};
func.datasource.run_events_functions = async function (SESSION_ID, dataSourceSession, event_id, calling_job, async_event, event_parameters, event_optionsP) {
if (typeof dataSourceSession === 'undefined' || dataSourceSession === null) {
console.warn(`Event ${event_id} not exist or not found`);
return;
}
// return new Promise(async (resolve, reject) => {
var _ds = SESSION_OBJ[SESSION_ID].DS_GLB[dataSourceSession];
var args = _ds.args;
// var v = _ds.v;
const _view_obj = await func.utils.VIEWS_OBJ.get(SESSION_ID, _ds.prog_id);
let job_promises = [];
if (_view_obj.progEvents) {
for await (const [key, val] of Object.entries(_view_obj.progEvents)) {
if (val.data.type === 'user_defined' && val.data.event_name && val.data.event_name === event_id) {
const jobs = await func.events.validate(
SESSION_ID,
'user_defined',
dataSourceSession,
val.data.event_name,
args.callingSourceP,
event_parameters, // val.data.parameters
null,
event_optionsP,
);
if (calling_job || async_event) continue;
for (let job_num of jobs) {
job_promises.push(
new Promise((resolve, reject) => {
let i = 0;
const interval = setInterval(() => {
i++;
var job_index = func.events.find_job_index(SESSION_ID, job_num);
if (job_index == null) {
clearInterval(interval);
resolve(job_num);
}
if (i > 200) {
func.utils.report_issue(SESSION_ID, {
code: 'RUN_MSG_DSC_050',
source: 'func.datasource.run_events_functions',
message: 'deadlock detected',
type: 'E',
details: {
job_num,
event_id,
dsSessionP,
},
});
clearInterval(interval);
resolve(job_num);
}
}, 100);
}),
);
}
}
}
}
if (job_promises.length) {
await Promise.all(job_promises);
}
};
func.datasource.render_fields_form = async function (SESSION_ID, dataSourceSession, raw_data_row) {
var _ds = SESSION_OBJ[SESSION_ID].DS_GLB[dataSourceSession];
const _progFields = await func.datasource.get_progFields(SESSION_ID, dataSourceSession);
if (!_progFields) {
return;
}
const get_value = async (field_id, value) => {
let view_field_obj = func.common.find_item_by_key(_progFields, 'field_id', field_id);
var fieldType = view_field_obj.props?.fieldType;
let table_field_obj;
if (view_field_obj.data.type === 'table' && field_id !== 'REDUCE_VALUE') {
if (!_ds._dataSourceTableId) {
return func.utils.debug_report(SESSION_ID, 'Datasource', `Table type defined without dataSourceTableId deceleration`, 'E');
}
let table_obj = await func.utils.FILES_OBJ.get(SESSION_ID, _ds._dataSourceTableId);
if (!table_obj) {
return func.utils.debug_report(SESSION_ID, 'Datasource', `dataSourceTableId reference error: ` + _ds._dataSourceTableId, 'E');
}
table_field_obj = func.common.find_item_by_key(table_obj.tableFields, 'field_id', field_id);
if (!table_field_obj) {
return func.utils.debug_report(SESSION_ID, 'Datasource', `Field Id: ${field_id} not exist in table ${table_obj.properties.menuName}`, 'E');
}
fieldType = table_field_obj.props?.fieldType;
}
return await func.common.get_cast_val(SESSION_ID, `render fields datasource ${_ds.viewSourceDesc}`, field_id, fieldType, value, null);
};
let row_idx;
try {
row_idx = func.common.find_ROWID_idx(_ds, raw_data_row.id);
} catch (error) {
_ds.data_feed.rows.push({ _ROWID: raw_data_row.id });
row_idx = func.common.find_ROWID_idx(_ds, raw_data_row.id);
}
_ds.dataset_alias = {};
for await (const val of _progFields) {
try {
var fieldId = val.data.field_id;
if (val.data.type === 'virtual' || raw_data_row.id === 'newRecord') {
if (glb.PROTECTED_VARS.includes(fieldId)) {
switch (fieldId) {
case '_ROWNO': {
_ds.data_feed.rows[row_idx][fieldId] = await get_value(fieldId, row_idx);
continue;
}
case '_ROWID': {
_ds.data_feed.rows[row_idx][fieldId] = await get_value(fieldId, raw_data_row.id);
continue;
}
case '_ROWDOC': {
_ds.data_feed.rows[row_idx][fieldId] = await get_value(fieldId, raw_data_row.value);
continue;
}
}
}
if (val.props?.propExpressions?.fieldValue) {
// check init exp existence
let ret = await func.expression.get(SESSION_ID, val.props?.propExpressions?.fieldValue, dataSourceSession, 'update', raw_data_row.id);
_ds.data_feed.rows[row_idx][fieldId] = await get_value(fieldId, ret.result);
continue;
}
const _vfp = func.datasource.__vf_preserve.get(_ds);
const _vfPrev = _vfp ? _vfp[fieldId] : undefined;
_ds.data_feed.rows[row_idx][fieldId] =
_vfPrev !== undefined && _vfPrev !== null && _vfPrev !== ''
? _vfPrev
: await get_value(fieldId, val.props?.fieldValue);
continue;
}
if (val.data.type === 'table' || val.data.type === 'datasource') {
if (typeof raw_data_row.value[fieldId] === 'undefined') {
throw 'field do not exist in data: ' + fieldId;
}
_ds.data_feed.rows[row_idx][fieldId] = await get_value(fieldId, raw_data_row.value[fieldId]);
}
} catch (err) {
func.utils.debug_report(SESSION_ID, 'Datasource', err, 'E', null, _ds);
}
}
};
func.datasource.execute_field_init_events = async function (SESSION_ID, dataSourceSession, sourceP, rowIdP) {
var _ds = SESSION_OBJ[SESSION_ID].DS_GLB[dataSourceSession];
var args = _ds.args;
var arr = _ds.dataSource_init_arr[rowIdP];
// for await (const [key, val] of Object.entries(arr)) {
for await (const val of arr) {
if (!func.utils.is_onscreen_event(val.eventInfo.data.action)) {
var cond = val?.eventInfo?.data?.enabled;
var expression = undefined;
if (val.eventInfo.props.condition) expression = val.eventInfo.props.condition;
var expCond = {};
if (expression && !xu_isEmpty(expression)) {
// check if expression exist
expCond = await func.expression.get(SESSION_ID, expression, dataSourceSession, 'condition', rowIdP, null, null, val.fieldId); // execute expression
cond = expCond.result;
expCond.conditional = true;
val.DEBUG_INFO_OBJ.result = expCond.result;
val.DEBUG_INFO_OBJ.error = expCond.error;
val.DEBUG_INFO_OBJ.fields = expCond.fields;
val.DEBUG_INFO_OBJ.conditional = expCond.conditional;
val.DEBUG_INFO_OBJ.details = expression;
}
func.utils.debug.log(SESSION_ID, val.node_id, val.DEBUG_INFO_OBJ);
if (cond) {
// check condition again
if (!_ds) continue;
var ds = _ds.prog_id;
await func.events.execute(
SESSION_ID,
null,
val.triggerId,
val.eventInfo.data.name, //val.eventInfo.data.trigger,
val.eventInfo.data.action,
val.eventInfo.data.name, //eventInfo[5],
null,
val.fieldId,
val.rowId,
val.colId,
null,
null,
dataSourceSession,
val.eventInfo.id, //eventInfo[2],
sourceP,
true,
null,
null,
args.jobNoP,
null,
null,
val.eventInfo,
null,
null,
null,
null,
ds.parentDataSourceNo,
null,
);
}
}
}
};
func.datasource.get_field_init_count = async function (SESSION_ID, dataSourceSession, rowIdP, pre_initP, oninit_triggers_to_runP) {
var _ds = SESSION_OBJ[SESSION_ID].DS_GLB[dataSourceSession];
var args = _ds.args;
const _view_obj = await func.utils.VIEWS_OBJ.get(SESSION_ID, _ds.prog_id);
// _ds.dataSource_init_arr[rowIdP] = {};
var ret = 0;
// if (_ds.v.ViewFieldsObjs) {
for await (const field_obj of _view_obj.progFields) {
var fieldId = field_obj.data.field_id;
if (!field_obj?.workflow?.length) {
continue;
}
for await (const trigger_obj of field_obj.workflow) {
if (oninit_triggers_to_runP && !oninit_triggers_to_runP?.includes(trigger_obj.id)) {
continue;
}
if (
// trigger_obj.data.trigger === "oninit" &&
['get_data', 'set_data', 'batch', 'update', 'raise_event'].includes(trigger_obj.data.action)
) {
if (!trigger_obj.data.action) {
func.utils.debug_report(SESSION_ID, '_ds.get_field_init_count', `Error initiating event for field: ${fieldId} prog: ${_ds.v.viewSourceDesc} row: ${rowIdP} reason: missing action`, 'E');
break;
}
if (trigger_obj.data.enabled) {
if (!_ds.dataSource_init_arr[rowIdP]) {
_ds.dataSource_init_arr[rowIdP] = [];
}
// _ds.dataSource_init_arr[rowIdP][ret] = {
// eventInfo: trigger_obj,
// triggerId: trigger_obj.id,
// fieldId: fieldId,
// rowId: rowIdP,
// colId: field_obj.id,
// node_id: args.prog_id + "_" + trigger_obj.id + "_" + field_obj.id,
// fieldProp: field_obj,
// DEBUG_INFO_OBJ: {
// module: _ds.viewModule,
// action: "init field event",
// prop: fieldId,
// source: _ds.viewSourceDesc,
// type: "event",
// prog_id: args.prog_id,
// dsSession: dataSourceSession,
// },
// };
_ds.dataSource_init_arr[rowIdP].push({
eventInfo: trigger_obj,
triggerId: trigger_obj.id,
fieldId: fieldId,
rowId: rowIdP,
colId: field_obj.id,
node_id: args.prog_id + '_' + trigger_obj.id + '_' + field_obj.id,
fieldProp: field_obj,
DEBUG_INFO_OBJ: {
module: _ds.viewModule,
action: 'init field event',
prop: fieldId,
source: _ds.viewSourceDesc,
type: 'event',
prog_id: args.prog_id,
dsSession: dataSourceSession,
},
});
ret++;
}
}
}
}
// }
return ret;
};
func.datasource.get_view_events_count = async function (SESSION_ID, dataSourceSession, typeP, eventIdP) {
var _ds = SESSION_OBJ[SESSION_ID].DS_GLB[dataSourceSession];
const _prog = await func.utils.VIEWS_OBJ.get(SESSION_ID, _ds.prog_id);
if (!_ds) return 0;
var args = _ds.args;
var index = typeP;
if (eventIdP) index = typeP + '_' + eventIdP;
// client interval
if (!_ds.viewEventExec_arr) _ds.viewEventExec_arr = {};
_ds.viewEventExec_arr[index] = [];
if (!_prog.progEvents || xu_isEmpty(_prog.progEvents)) return 0;
for (const event_obj of _prog.progEvents) {
if (event_obj.data.type !== typeP) continue; // was false?? changed to true 020317
if (eventIdP && event_obj.id !== eventIdP) continue; // match w ID added 03312017
if (event_obj.data.condition) {
let res = await func.expression.get(SESSION_ID, event_obj.data.condition, dataSourceSession, 'condition', args.rowIdP, null, null, null, null, event_obj);
if (!res.result) {
continue;
}
}
if (xu_isEmpty(event_obj.workflow)) continue;
for (const trigger_obj of event_obj.workflow) {
if (trigger_obj.data.enabled) {
var expression;
if (trigger_obj.props.condition) expression = trigger_obj.props.condition;
var expCond = {};
if (expression) {
expCond.conditional = true;
}
func.utils.debug.log(SESSION_ID, args.prog_id + '_' + trigger_obj.id, {
module: _ds.viewModule,
action: trigger_obj.data.action,
prop: event_obj.data.type,
details: expression,
result: expCond.result,
error: expCond.error,
source: _ds.viewSourceDesc,
fields: expCond.fields,
type: 'event',
prog_id: args.prog_id,
dsSession: dataSourceSession,
conditional: expCond.conditional,
});
}
if (!trigger_obj.data.action) {
func.utils.debug_report(SESSION_ID, 'get_view_events_count', `Error initiating ${typeP} prog:${_ds.v.viewSourceDesc} reason: missing action`, 'E');
break;
}
if (!glb.REFERENCE_LESS_FUNCTIONS.includes(trigger_obj.data.action) && !trigger_obj.data.action) {
func.utils.debug_report(SESSION_ID, 'get_view_events_count', `Error initiating ${typeP} prog: ${_ds.v.viewSourceDesc} reason: missing reference`, 'E');
break;
}
if (trigger_obj.data.enabled) {
_ds.viewEventExec_arr[index].push({
eventInfo: trigger_obj,
eventId: event_obj.id,
triggerId: trigger_obj.id,
expression: expression,
});
// ret++;
}
}
}
return _ds.viewEventExec_arr[index].length;
};
func.datasource.execute_view_events = async function (SESSION_ID, dataSourceSession, typeP, eventIdP) {
var _ds = SESSION_OBJ[SESSION_ID].DS_GLB[dataSourceSession];
var args = _ds.args;
var i = -1;
var index = typeP;
if (eventIdP) index = typeP + '_' + eventIdP;
var arr = _ds.viewEventExec_arr[index];
if (xu_isEmpty(arr)) return;
for await (const val of arr) {
if (!glb.IS_WORKER || !func.utils.is_onscreen_event(val.eventInfo.data.action) || (glb.IS_WORKER && _ds.v.run_at === 'server' && !func.utils.is_onscreen_event(val.eventInfo.data.action))) {
// val.done = true;
var cond = true;
if (val.expression) {
var expCond = await func.expression.get(SESSION_ID, val.expression, dataSourceSession, 'condition', args.rowIdP, null, null, null, null, val.eventInfo); // execute expression
cond = expCond.result;
}
if (cond) {
var elem_params = undefined;
if (!glb.IS_WORKER) {
const container_meta = func.runtime.ui.get_meta_by_element_id(_ds.containerId);
elem_params = container_meta?.params;
}
const ret = await func.events.execute(
SESSION_ID,
null,
val.triggerId,
val.eventInfo.data.trigger,
val.eventInfo.data.action,
val.eventInfo.data.name,
null,
null,
null,
null,
val.eventInfo.data.action,
null,
dataSourceSession,
val.eventId,
_ds.tree_obj.menuType + ' event',
true,
null,
null,
args.jobNoP,
elem_params,
null,
val.eventInfo,
);
}
continue;
}
// on screen event
if (typeP == 'before_record' || typeP == 'after_record' || typeP == 'on_load' || typeP == 'on_exit') {
_ds.v.onscreen_events_active = {
i: i,
type: typeP,
};
var parent_ds_chain = func.datasource.get_parent_ds_chain(SESSION_ID, dataSourceSession);
var obj = {
ds_obj: func.utils.clean_returned_datasource(SESSION_ID, dataSourceSession),
dsSessionP: dataSourceSession,
};
obj.ds_obj.parent_ds_chain = parent_ds_chain;
}
}
};
func.datasource.get_parent_ds_chain = function (SESSION_ID, dataSourceSession) {
var arr = [];
var drill = function (ds) {
if (SESSION_OBJ[SESSION_ID].DS_GLB[ds]) {
if (typeof SESSION_OBJ[SESSION_ID].DS_GLB[ds].parentDataSourceNo !== 'undefined') {
arr.push(SESSION_OBJ[SESSION_ID].DS_GLB[ds].parentDataSourceNo);
drill(SESSION_OBJ[SESSION_ID].DS_GLB[ds].parentDataSourceNo);
}
}
};
drill(dataSourceSession);
return arr;
};
func.datasource.execute_onscreen_view_events = async function (SESSION_ID, dataSourceSession, sourceP) {
var _ds = SESSION_OBJ[SESSION_ID].DS_GLB[dataSourceSession];
var args = _ds.args;
var i = _ds.v.onscreen_events_active.i;
var type = _ds.v.onscreen_events_active.type;
var evnt;
if (_ds.viewEventExec_arr?.[type]?.[i]) {
evnt = _ds.viewEventExec_arr[type][i];
evnt.done = true;
var cond = true;
if (evnt.expression) {
var expCond = await func.expression.get(SESSION_ID, evnt.expression, dataSourceSession, 'condition', args.rowIdP); // execute expression
cond = expCond.result;
}
if (cond) {
let ret = await func.events.execute(
SESSION_ID,
null,
evnt.triggerId,
evnt.eventInfo.data.trigger,
evnt.eventInfo.data.action,
evnt.eventInfo.data.name, //eventInfo[5],
null,
null,
null,
null,
evnt.eventInfo.data.name, //eventInfo[4],
null,
dataSourceSession,
null,
sourceP + ' event',
true,
null,
null,
args.jobNoP,
);
}
} else console.error('*execute_onscreen_view_events error');
};
func.datasource.get_event_interval_arr = function (SESSION_ID, dataSourceSession, typeP) {
var _ds = SESSION_OBJ[SESSION_ID].DS_GLB[dataSourceSession];
// var v = _ds.v;
var arr = [];
var ret = 0;
if (!_ds.v.progEvents) return 0;
for (let val of _ds.v.progEvents) {
if (val.data.type !== typeP) continue;
arr.push([val.id, val.data.properties, val.data.condition]);
}
return arr;
};
func.datasource.clean_all = function (SESSION_ID, dsP) {
var arr = [dsP];
var get_child_ds = function (ds) {
var arr = [];
for (const [key, val] of Object.entries(SESSION_OBJ[SESSION_ID].DS_GLB)) {
if (val.parentDataSourceNo == ds) {
arr.push(key);
arr = arr.concat(get_child_ds(key));
}
}
return arr;
};
arr = arr.concat(get_child_ds(dsP));
for (let val of arr) {
func.datasource.del(SESSION_ID, val);
}
};
func.datasource.clean = function (SESSION_ID, screenIdP) {
var arr = [];
for (const [key, val] of Object.entries(SESSION_OBJ[SESSION_ID].DS_GLB)) {
try {
const screen_parent_id = val.screenId && func.runtime?.ui?.get_parent_element_id
? func.runtime.ui.get_parent_element_id(val.screenId)
: null;
if (
Number(key) > 0 &&
(val.screenId === screenIdP ||
val.rootScreenId === screenIdP ||
screen_parent_id === screenIdP ||
(val && val.parentDataSourceNo && arr.includes(val.parentDataSourceNo.toString())))
) {
arr.push(key);
if (val.screenId && func.UI?.utils?.screen_blocker) func.UI.utils.screen_blocker(false, val.screenId);
}
} catch (err) {
console.warn('func.datasource.clean failed');
func.datasource.reset_jobs(SESSION_ID, key, 'datasource.clean', err);
}
}
for (let val of arr) {
func.datasource.del(SESSION_ID, val);
}
};
func.datasource.del = function (SESSION_ID, dsP) {
if ((SESSION_OBJ[SESSION_ID].DS_GLB[dsP] && SESSION_OBJ[SESSION_ID].DS_GLB[dsP].keep_alive) || dsP == 0) return;
if (DATASOURCE_INTERVALS[SESSION_ID] && DATASOURCE_INTERVALS[SESSION_ID][dsP]) {
DATASOURCE_INTERVALS[SESSION_ID][dsP].clear();
}
const perform_delete = async function () {
var response = {
success: function (jsonP, ajaxP) {},
error: function (status) {
console.error('error datasource:' + status);
},
fail: function (status) {
console.error('error datasource:' + status);
},
};
var data = {
session_id: SESSION_ID,
dssession: dsP,
};
if (!SESSION_OBJ[SESSION_ID].DS_GLB[dsP]) return;
if (!glb.IS_WORKER) {
let _ds = SESSION_OBJ[SESSION_ID].DS_GLB[dsP];
if (_ds.worker_id) {
// if (_ds.data_xuda) console.log(dsP);
if (RUNTIME_SERVER_WEBSOCKET && RUNTIME_SERVER_WEBSOCKET_CONNECTED && (!_session.opt.app_computing_mode || _session.opt.app_computing_mode === 'server')) {
WEB_WORKER[SESSION_ID][_ds.worker_id].emit('message', {
service: 'close_websocket',
});
} else {
WEB_WORKER[SESSION_ID][_ds.worker_id].worker.terminate();
}
delete WEB_WORKER[SESSION_ID][_ds.worker_id];
} else {
const json = await func.index.call_worker(SESSION_ID, {
service: 'datasource_delete',
data: data,
id: _ds.worker_id,
});
response.success(json, true);
}
if (DS_UI_EVENTS_GLB) delete DS_UI_EVENTS_GLB[dsP];
}
delete SESSION_OBJ[SESSION_ID].DS_GLB[dsP];
};
var delete_pending_jobs = function () {
var arr = [];
for (const [key, val] of Object.entries(SESSION_OBJ[SESSION_ID].WORKER_OBJ.jobs)) {
if (val && val.dsSessionP == dsP) {
arr.push(key);
func.runtime.ui.clear_screen_blockers();
}
}
for (let val of arr.reverse()) {
SESSION_OBJ[SESSION_ID].WORKER_OBJ.jobs.splice(val, 1);
}
if (!SESSION_OBJ[SESSION_ID].WORKER_OBJ.jobs.length) SESSION_OBJ[SESSION_ID].WORKER_OBJ.stat = null;
};
if (!glb.IS_WORKER) {
if (SESSION_OBJ[SESSION_ID].DS_GLB[dsP]) {
delete SCREEN_BLOCKER_OBJ[SESSION_OBJ[SESSION_ID].DS_GLB[dsP].screenId + '_' + SESSION_OBJ[SESSION_ID].DS_GLB[dsP].callingScreenId];
// Refresh settled for this screen: once fully unblocked, reconcile
// teleports (drop orphans / mirror host visibility) on the next microtask
// (after this datasource completion unwinds) so there is no 1s lag on
// panel open/close. Gated so it is a no-op when there are no teleports.
if (func.UI?.reconcile_teleports) {
Promise.resolve().then(function () {
if (xu_isEmpty(SCREEN_BLOCKER_OBJ)) {
try {
func.UI.reconcile_teleports();
} catch (e) {}
}
});
}
delete_pending_jobs();
if (glb.new_xu_render) {
for (const [ui_cache_key, ui_cache_val] of Object.entries(UI_WORKER_OBJ.xu_render_cache)) {
if (ui_cache_val.paramsP.dsSessionP === dsP) {
delete UI_WORKER_OBJ.xu_render_cache[ui_cache_key];
}
}
}
}
const _nav_node = func.runtime.ui.get_first_node(SESSION_OBJ[SESSION_ID].root_element)?.querySelector?.('xu-nav');
if (_nav_node) {
var ds_obj = func.runtime.ui.get_data(_nav_node)?.xuData?.nav_params;
if (ds_obj) {
delete ds_obj[dsP];
}
}
}
perform_delete();
};
func.datasource.update = async function (SESSION_ID, datasource_changes, update_local_scope_only, avoid_xu_for_refresh, trigger) {
return new Promise(async (resolve, reject) => {
var _session = SESSION_OBJ[SESSION_ID];
if (glb.XU_PERF) {
// any state mutation invalidates memoized drive-ref clean verdicts and
// the per-epoch expression slot clones
func.utils.drive_ref_clean_cache = new WeakSet();
func.expression._slot_clone_cache = new WeakMap();
}
const refresh_control = avoid_xu_for_refresh && typeof avoid_xu_for_refresh === 'object' ? avoid_xu_for_refresh : {};
const avoid_refresh = avoid_xu_for_refresh === true || refresh_control.avoid_refresh === true;
const refresh_attributes_when_avoiding = refresh_control.refresh_attributes === true;
const skip_attribute_refresh = avoid_refresh && !refresh_attributes_when_avoiding;
const skip_screen_refresh = avoid_refresh || refresh_control.avoid_screen_refresh === true;
const defer_screen_refresh = !skip_screen_refresh && refresh_control.defer_refresh === true;
if (_session.IS_API || typeof IS_MASTER_WEBSOCKET !== 'undefined' || typeof IS_PROCESS_SERVER !== 'undefined') {
update_local_scope_only = true;
}
if (typeof glb.GLOBAL_VARS === 'undefined') {
glb.GLOBAL_VARS = (await func.common.get_module(SESSION_ID, 'xuda-system-globals-module.mjs')).system_globals;
}
const set_fieldComputed_dependencies = async function (dsNo, field_id, parent_ds) {
// iterate child ds
for (const [dsSession, _ds] of Object.entries(_session.DS_GLB)) {
if (parent_ds !== null) {
if (_ds.parentDataSourceNo != parent_ds) continue;
} else {
if (dsSession != dsNo) continue;
}
let tree_ret = await func.utils.TREE_OBJ.get(SESSION_ID, _ds.prog_id);
if (tree_ret.menuType === 'component' || tree_ret.menuType === 'globals') {
// check if field has fieldComputed property
const _progFields = await func.datasource.get_progFields(SESSION_ID, dsSession);
// find if field is computed
let fieldComputed_propExpressions, fieldComputed_id;
for await (const val of _progFields) {
const fieldId = val.data.field_id;
// if (fieldId !== field_id) continue
if (val.data.type !== 'virtual' || !val.props.fieldComputed) continue;
const _propExpressions = val.props?.propExpressions?.fieldValue;
if (_propExpressions && JSON.stringify(_propExpressions).includes(field_id)) {
fieldComputed_propExpressions = _propExpressions;
fieldComputed_id = fieldId;
}
}
if (!fieldComputed_id) return;
// iterate ds rows
for (const row of _ds.data_feed?.rows || []) {
// iterate row fields
for (const [key, val] of Object.entries(row)) {
if (key !== fieldComputed_id) continue;
try {
let ret = await func.expression.get(SESSION_ID, fieldComputed_propExpressions, dsNo, 'update', row._ROWID);
const row_idx = func.common.find_ROWID_idx(_ds, row._ROWID);
if (_ds.data_feed.rows[row_idx][fieldComputed_id] !== ret.result) {
_ds.data_feed.rows[row_idx][fieldComputed_id] = ret.result;
if (!fields_changed.includes(fieldComputed_id)) {
fields_changed.push(fieldComputed_id);
}
if (!datasource_changed.includes(dsSession)) {
datasource_changed.push(dsSession);
}
}
} catch (err) {
console.error(err);
}
}
}
}
await set_fieldComputed_dependencies(dsNo, field_id, dsSession);
}
};
var fields_changed = [];
var datasource_changed = [];
let client_datasource_changes = {};
let server_datasource_changes = {};
const mark_field_changed = async function (dataSource, field_id) {
if (!fields_changed.includes(field_id)) {
fields_changed.push(field_id);
// Refresh dependent in-parameters that reference this field.
for (const [_dsSession, _ds] of Object.entries(_session.DS_GLB)) {
if (_ds.args.parameters_raw_obj) {
for (const [key, exp] of Object.entries(_ds.args.parameters_raw_obj)) {
if (exp.includes(field_id)) {
let ret = await func.expression.get(SESSION_ID, exp, _dsSession, 'parameters');
_ds.in_parameters[key].value = ret.result;
}
}
}
}
}
if (!datasource_changed.includes(dataSource)) {
datasource_changed.push(dataSource);
}
};
const queue_remote_change = async function (dataSource, record_id, field_id, value, _ds) {
if (update_local_scope_only) {
return;
}
let tree_ret = await func.utils.TREE_OBJ.get(SESSION_ID, _ds.prog_id);
if (glb.IS_WORKER) {
if (tree_ret.menuType === 'globals' || tree_ret.menuType === 'component') {
const _progFields = await func.datasource.get_progFields(SESSION_ID, dataSource);
let view_field_obj = func.common.find_item_by_key(_progFields, 'field_id', field_id);
if (!view_field_obj?.data?.serverField && record_id !== 'data_system') {
if (!client_datasource_changes[dataSource]) {
client_datasource_changes[dataSource] = {};
}
if (!client_datasource_changes[dataSource][record_id]) {
client_datasource_changes[dataSource][record_id] = {};
}
client_datasource_changes[dataSource][record_id][field_id] = value;
}
}
} else {
if ((tree_ret.menuType === 'component' && _ds._run_at !== 'client') || tree_ret.menuType === 'globals') {
if (!server_datasource_changes[dataSource]) {
server_datasource_changes[dataSource] = {};
}
if (!server_datasource_changes[dataSource][record_id]) {
server_datasource_changes[dataSource][record_id] = {};
}
server_datasource_changes[dataSource][record_id][field_id] = value;
}
}
};
const update_xu_ref = function (dataSource) {
let ret;
let _ds_0 = _session.DS_GLB[0];
for ([ref_name, val] of Object.entries(_ds_0.data_system['SYS_GLOBAL_OBJ_REFS'])) {
if (val?.ds?.dsSession == dataSource) {
ret = func.UI.update_xu_ref(SESSION_ID, dataSource, ref_name);
}
}
return ret;
};
const mark_xu_refs_changed = function (dataSource) {
// Pushing the synthetic 'SYS_GLOBAL_OBJ_REFS' pseudo-field into fields_changed makes
// refresh_screen re-evaluate panel/modal visibility conditions that depend on @refs. This
// should only happen when update_xu_ref reports a real ref/data change.
if (!fields_changed.includes('SYS_GLOBAL_OBJ_REFS')) fields_changed.push('SYS_GLOBAL_OBJ_REFS');
};
// --- Watch fields (snapshot) -------------------------------------------------
// Before applying any change, snapshot the current value of every datasource's
// declared progDataSource.dataSourceWatchFields (Studio "Watch" popover). A watch
// field can be an in-parameter (e.g. pt_in) whose value is derived from another
// field, so we cannot detect it by matching fields_changed names — we compare its
// value before/after (see the fire-lifecycle block after the loop below).
const get_watch_field_value = function (watch_ds, watch_field_id) {
if (watch_ds?.in_parameters?.[watch_field_id] && typeof watch_ds.in_parameters[watch_field_id].value !== 'undefined') {
return watch_ds.in_parameters[watch_field_id].value;
}
const watch_rows = watch_ds?.data_feed?.rows || [];
const watch_row = watch_rows.find(function (row) { return row && row._ROWID === watch_ds.currentRecordId; }) || watch_rows[0] || {};
return watch_row[watch_field_id];
};
const watch_field_snapshot = {};
if (!glb.IS_WORKER) {
for (const [watch_dsSession, watch_ds] of Object.entries(_session.DS_GLB)) {
const watch_fields = watch_ds?.progDataSource?.dataSourceWatchFields;
if (!Array.isArray(watch_fields) || !watch_fields.length) {
continue;
}
watch_field_snapshot[watch_dsSession] = {};
for (let watch_index = 0; watch_index < watch_fields.length; watch_index++) {
const watch_field = watch_fields[watch_index];
const watch_field_id = typeof watch_field === 'string' ? watch_field.replace(/^@/, '') : (watch_field?.field_id ?? watch_field?.value ?? watch_field?.id);
if (watch_field_id) {
watch_field_snapshot[watch_dsSession][watch_field_id] = get_watch_field_value(watch_ds, watch_field_id);
}
}
}
}
// iterate changes datasource
for await (const [dataSource, row_data] of Object.entries(datasource_changes)) {
var _ds = _session.DS_GLB[dataSource];
if (!_ds) {
continue;
}
// iterate changes records
for (const [record_id, fields_data] of Object.entries(row_data)) {
// iterate changes fields
for (const [field_id, value] of Object.entries(fields_data)) {
// mechanism to make update directly on the datasource object
if (record_id === 'datasource_main') {
xu_set(_ds, field_id, value);
// stat/stat_ts/is_worker are datasource bookkeeping written on refresh lifecycle
// transitions. The value is still applied to _ds above; skip ref-change detection for
// these fields so lifecycle ticks do not schedule another screen refresh by themselves.
const _is_status_tick = field_id === 'stat' || field_id === 'stat_ts' || field_id === 'is_worker';
const ret = _is_status_tick ? false : update_xu_ref(dataSource);
if (ret) {
fields_changed.push(field_id);
datasource_changed.push(dataSource);
mark_xu_refs_changed(dataSource);
}
if (!glb.IS_WORKER && field_id === 'watcher') {
if (!server_datasource_changes[dataSource]) {
server_datasource_changes[dataSource] = {};
}
if (!server_datasource_changes[dataSource][record_id]) {
server_datasource_changes[dataSource][record_id] = {};
}
server_datasource_changes[dataSource][record_id][field_id] = value;
if (!update_local_scope_only) {
const ret = await func.index.call_worker(SESSION_ID, {
service: 'update_datasource_changes_from_client',
data: {
session_id: SESSION_ID,
datasource_changes: server_datasource_changes,
},
id: _ds.worker_id,
});
}
if (skip_screen_refresh) {
globalThis.__XUDA_RT_TRACE && console.log('[xuda-runtime] datasource_update_refresh_skipped ' +
JSON.stringify({
reason: 'avoid_refresh',
phase: 'watcher',
dataSource,
field_id,
fields_changed: structuredClone(fields_changed),
datasource_changed: structuredClone(datasource_changed),
}),
);
} else if (defer_screen_refresh) {
globalThis.__XUDA_RT_TRACE && console.log('[xuda-runtime] datasource_update_refresh_queued ' +
JSON.stringify({
phase: 'watcher',
dataSource,
field_id,
fields_changed: structuredClone(fields_changed),
datasource_changed: structuredClone(datasource_changed),
}),
);
func.runtime.ui.refresh_screen({
SESSION_ID,
fields_changed_arr: structuredClone(fields_changed),
datasource_changed: datasource_changed[0],
fields_changed_datasource: datasource_changed[0],
watcher: value,
})?.catch?.(function (error) {
console.error(error);
});
} else {
globalThis.__XUDA_RT_TRACE && console.log('[xuda-runtime] datasource_update_refresh ' +
JSON.stringify({
phase: 'watcher',
dataSource,
field_id,
fields_changed: structuredClone(fields_changed),
datasource_changed: structuredClone(datasource_changed),
}),
);
await func.runtime.ui.refresh_screen({
SESSION_ID,
fields_changed_arr: structuredClone(fields_changed),
datasource_changed: datasource_changed[0],
fields_changed_datasource: datasource_changed[0],
watcher: value,
});
}
}
continue;
}
if (typeof fields_data === 'object') {
if (glb.GLOBAL_VARS[field_id]) {
if (!_ds.data_system) {
_ds.data_system = {};
}
_ds.data_system[field_id] = value;
if (dataSource != 0 && _session.DS_GLB[0]) {
if (!_session.DS_GLB[0].data_system) {
_session.DS_GLB[0].data_system = {};
}
_session.DS_GLB[0].data_system[field_id] = value;
}
continue;
}
const dynamic_field = _ds?.dynamic_fields?.[field_id];
if (dynamic_field) {
if (!xu_isEqual(dynamic_field.value, value)) {
dynamic_field.value = value;
await set_fieldComputed_dependencies(dataSource, field_id, null);
if (update_xu_ref(dataSource)) {
mark_xu_refs_changed(dataSource);
}
await queue_remote_change(dataSource, record_id, field_id, value, _ds);
await mark_field_changed(dataSource, field_id);
}
continue;
}
try {
const row_idx = func.common.find_ROWID_idx(_ds, record_id);
// if (_ds.data_feed.rows[row_idx][field_id] !== value) {
if (!xu_isEqual(_ds.data_feed.rows[row_idx][field_id], value)) {
_ds.data_feed.rows[row_idx][field_id] = value;
await set_fieldComputed_dependencies(dataSource, field_id, null);
// search the field in refs
if (update_xu_ref(dataSource)) {
mark_xu_refs_changed(dataSource);
}
await queue_remote_change(dataSource, record_id, field_id, value, _ds);
await mark_field_changed(dataSource, field_id);
if (!_ds.data_feed.rows_changed) {
_ds.data_feed.rows_changed = [];
}
if (!_ds.data_feed.rows_changed.includes(record_id)) _ds.data_feed.rows_changed.push(record_id);
}
} catch (error) {
// normal
}
} else if (fields_data === 'set') {
_ds.currentRecordId = record_id;
}
}
}
}
// --- Watch fields (fire lifecycle) -------------------------------------------
// Re-fire the on_load/screen_ready lifecycle for any datasource whose watched VALUE
// changed vs the pre-change snapshot (captured above, before the change loop). We
// compare VALUES, not fields_changed names, because a watch field is typically an
// in-parameter (e.g. pt_in) whose value is DERIVED from another field (active_pt_id_v
// via xu-exp:pt_in) — so the changed field name never equals the watch name. on_load
// and screen_ready are gated to INITIAL load only (run_on_load_events /
// schedule_panel_on_load_events) to avoid render loops, so data a screen_ready derives
// (e.g. a virtual field) stays stale on refresh. A watch field is an explicit trigger,
// so re-running the lifecycle is intended. Coalesced (latest state wins) + throttled
// (<=15 fires/sec per datasource) so a mis-configured watch on a field the lifecycle
// itself writes is broken with a warning instead of looping forever.
if (!glb.IS_WORKER && !xu_isEmpty(watch_field_snapshot)) {
const watch_field_state = (_session.__watch_field_state = _session.__watch_field_state || { active: new Set(), pending: new Set(), fire_times: {} });
const fire_watch_field_lifecycle = function (watch_dsSession) {
if (watch_field_state.active.has(watch_dsSession)) {
watch_field_state.pending.add(watch_dsSession);
return;
}
const now = Date.now();
watch_field_state.fire_times[watch_dsSession] = (watch_field_state.fire_times[watch_dsSession] || []).filter(function (fired_at) {
return now - fired_at < 1000;
});
if (watch_field_state.fire_times[watch_dsSession].length >= 15) {
console.warn('[xuda-runtime] watch-field lifecycle throttled for datasource ' + watch_dsSession + ' — a watch field may be written by its own on_load/screen_ready (loop).');
return;
}
watch_field_state.fire_times[watch_dsSession].push(now);
watch_field_state.active.add(watch_dsSession);
setTimeout(async function () {
try {
for (const lifecycle_event of ['on_load', 'screen_ready']) {
if (await func.datasource.get_view_events_count(SESSION_ID, watch_dsSession, lifecycle_event)) {
await func.datasource.execute_view_events(SESSION_ID, watch_dsSession, lifecycle_event);
}
}
} catch (watch_error) {
console.error(watch_error);
} finally {
watch_field_state.active.delete(watch_dsSession);
if (watch_field_state.pending.has(watch_dsSession)) {
watch_field_state.pending.delete(watch_dsSession);
fire_watch_field_lifecycle(watch_dsSession);
}
}
}, 0);
};
for (const watch_dsSession of Object.keys(watch_field_snapshot)) {
const watch_ds = _session.DS_GLB[watch_dsSession];
if (!watch_ds) {
continue;
}
let watch_value_changed = false;
const watch_field_ids = Object.keys(watch_field_snapshot[watch_dsSession]);
for (let watch_index = 0; watch_index < watch_field_ids.length; watch_index++) {
const watch_field_id = watch_field_ids[watch_index];
if (!xu_isEqual(watch_field_snapshot[watch_dsSession][watch_field_id], get_watch_field_value(watch_ds, watch_field_id))) {
watch_value_changed = true;
break;
}
}
if (watch_value_changed) {
fire_watch_field_lifecycle(watch_dsSession);
}
}
}
if (glb.IS_WORKER) {
if (!update_local_scope_only && !xu_isEmpty(client_datasource_changes)) {
func.utils.post_back_to_client(SESSION_ID, 'update_client_eventChangesResults_from_worker', _session.worker_id, client_datasource_changes);
}
} else {
if (!update_local_scope_only && !xu_isEmpty(server_datasource_changes)) {
const ret = await func.index.call_worker(SESSION_ID, {
service: 'update_datasource_changes_from_client',
data: {
session_id: SESSION_ID,
datasource_changes: server_datasource_changes,
},
id: _ds.worker_id,
});
}
///// REFRESH SCREEN
if (fields_changed.length) {
function findMin(arr) {
return Math.min(...arr.map(Number));
}
if (!skip_attribute_refresh) {
if (skip_screen_refresh) {
globalThis.__XUDA_RT_TRACE && console.log('[xuda-runtime] datasource_update_attributes_only ' +
JSON.stringify({
reason: 'avoid_screen_refresh',
phase: 'fields',
fields_changed: structuredClone(fields_changed),
datasource_changed: structuredClone(datasource_changed),
trigger: trigger || null,
}),
);
} else if (defer_screen_refresh) {
globalThis.__XUDA_RT_TRACE && console.log('[xuda-runtime] datasource_update_refresh_queued ' +
JSON.stringify({
phase: 'fields',
fields_changed: structuredClone(fields_changed),
datasource_changed: structuredClone(datasource_changed),
trigger: trigger || null,
}),
);
} else {
globalThis.__XUDA_RT_TRACE && console.log('[xuda-runtime] datasource_update_refresh ' +
JSON.stringify({
phase: 'fields',
fields_changed: structuredClone(fields_changed),
datasource_changed: structuredClone(datasource_changed),
trigger: trigger || null,
}),
);
}
// await func.UI.screen.refresh_xu_attributes(SESSION_ID, _.cloneDeep(fields_changed), null, null, findMin(datasource_changed), avoid_xu_for_refresh, trigger);
await func.runtime.ui.refresh_xu_attributes({
SESSION_ID,
fields_arr: structuredClone(fields_changed),
jobNoP: null,
$elm_to_search: null,
dsSession_changed: findMin(datasource_changed),
avoid_xu_for_refresh: skip_screen_refresh,
trigger,
ignore_screen_blocker: true,
});
}
if (skip_screen_refresh) {
globalThis.__XUDA_RT_TRACE && console.log('[xuda-runtime] datasource_update_refresh_skipped ' +
JSON.stringify({
reason: refresh_attributes_when_avoiding ? 'avoid_screen_refresh' : 'avoid_refresh',
phase: 'fields',
attributes_refreshed: !skip_attribute_refresh,
fields_changed: structuredClone(fields_changed),
datasource_changed: structuredClone(datasource_changed),
}),
);
} else if (defer_screen_refresh) {
func.runtime.ui.refresh_screen({
SESSION_ID,
fields_changed_arr: structuredClone(fields_changed),
datasource_changed: null,
fields_changed_datasource: datasource_changed[0],
})?.catch?.(function (error) {
console.error(error);
});
} else {
// await removed from the below function cause to dead lock Mar 3 25
await func.runtime.ui.refresh_screen({
SESSION_ID,
fields_changed_arr: structuredClone(fields_changed),
datasource_changed: null,
fields_changed_datasource: datasource_changed[0],
});
}
}
// ///// REFRESH PARAMETERS IN
// if (fields_changed.length) {
// for (const [_dsSession, _ds] of Object.entries(_session.DS_GLB)) {
// if (_ds.args.parameters_raw_obj) {
// for (const [key, val] of Object.entries(_ds.args.parameters_raw_obj)) {
// if (fields_changed.includes(val)) {
// let ret = await func.expression.get(SESSION_ID, '@' + val, _dsSession, 'parameters');
// _ds.in_parameters[val].value = ret.result;
// }
// }
// }
// }
// }
}
resolve();
});
};
func.datasource.callback = async function (SESSION_ID, dsSessionP, rowIdP, jobNoP, nodeIdP) {
var _session = SESSION_OBJ[SESSION_ID];
var _ds = _session.DS_GLB[dsSessionP];
try {
const row_idx = func.common.find_ROWID_idx(_ds, 'dataset');
if (_ds.PARAM_OUT_INFO) {
// write log for out params
for (const [key, val] of Object.entries(_ds.PARAM_OUT_INFO)) {
if (typeof _ds?.data_feed?.rows?.[row_idx]?.[val.fieldId] === 'undefined') {
// func.utils.debug.log(SESSION_ID, key, val);
func.utils.alerts.invoke(SESSION_ID, 'system_msg', 'SYS_MSG_0310', val.fieldId, dsSessionP);
break;
}
val.result = _ds.data_feed.rows[row_idx][val.fieldId];
}
}
} catch (err) {
// console.error(err);
}
const datasetOutputField = _ds?.progDataSource?.datasetOutputField;
if (datasetOutputField) {
let ret_get_value = await func.datasource.get_value(SESSION_ID, datasetOutputField, _ds.dsSession);
if (ret_get_value.found) {
let datasource_changes = {};
if (!datasource_changes[ret_get_value.dsSessionP]) {
datasource_changes[ret_get_value.dsSessionP] = {};
}
if (!datasource_changes[ret_get_value.dsSessionP][ret_get_value.currentRecordId]) {
datasource_changes[ret_get_value.dsSessionP][ret_get_value.currentRecordId] = {};
datasource_changes[ret_get_value.dsSessionP][ret_get_value.currentRecordId][_ds?.progDataSource?.datasetOutputField] = _ds?.data_feed?.rows || [];
await func.datasource.update(SESSION_ID, datasource_changes);
}
}
}
func.utils.debug.log(SESSION_ID, nodeIdP, {
module: _ds.viewModule,
action: 'close',
source: _ds.viewSourceDesc,
type: 'adapter',
prog_id: _ds.prog_id,
dsSession: dsSessionP,
prop: _ds.log_prop + ' ' + 'adapter',
});
if (!glb.IS_WORKER) func.runtime.platform.set_cursor(_session.root_element, 'default');
if (_ds.prog_id) {
let _ds = _session.DS_GLB[dsSessionP];
func.utils.debug.watch(
SESSION_ID,
_ds.prog_id,
'program',
{
in_parameters: _ds.in_parameters,
out_parameters: _ds.out_parameters,
data_feed: _ds.data_feed,
},
_ds.tree_obj.menuType,
);
}
delete _ds.old_dataSource;
return {
SESSION_ID,
dsSessionP,
rowIdP,
jobNoP,
callingLogId: _ds.callingLogId,
calling_jobP: _ds.calling_jobP,
};
};
func.datasource.validate_viewRange = async function (SESSION_ID, viewRangeExpP, dsSessionP, rowIdP, sourceP) {
var _ds = SESSION_OBJ[SESSION_ID].DS_GLB[dsSessionP];
if (viewRangeExpP && _ds) {
var ret = func.expression.remove_quotes(await func.expression.get(SESSION_ID, viewRangeExpP, dsSessionP, 'range', rowIdP));
ret.result = func.expression.remove_quotes(ret.result);
func.utils.debug.log(SESSION_ID, _ds.prog_id, {
module: _ds.viewModule,
action: 'range Exp',
prop: sourceP,
details: viewRangeExpP,
result: ret.result,
error: ret.error,
source: _ds.viewSourceDesc,
json: ret.explain,
fields: ret.fields,
dsSession: dsSessionP,
});
_ds.viewRangeExpResults = ret.fields;
if (glb.DEBUG_MODE) {
if (!_ds.debug) {
_ds.debug = {};
}
if (!_ds.debug.viewRangeExp) {
_ds.debug.viewRangeExp = [];
}
_ds.debug.viewRangeExp.push(ret);
}
return ret.result;
} else return false;
};
func.datasource.validate_viewLocate = async function (SESSION_ID, viewLocateExpP, dsSessionP, rowIdP, sourceP) {
if (viewLocateExpP && _ds) {
var ret = func.expression.remove_quotes(await func.expression.get(SESSION_ID, viewLocateExpP, dsSessionP, 'locate', rowIdP));
ret.result = func.expression.remove_quotes(ret.result);
func.utils.debug.log(SESSION_ID, _ds.prog_id, {
module: _ds.viewModule,
action: 'locate Exp',
prop: sourceP,
details: viewLocateExpP,
result: ret.result,
error: ret.error,
source: _ds.viewSourceDesc,
json: ret.explain,
fields: ret.fields,
dsSession: dsSessionP,
});
_ds.viewLocateExpResults = ret.fields;
return ret.result;
} else return false;
};
func.datasource.get_viewFields_for_update_function = function (SESSION_ID, calling_trigger_prop, na, dsSessionP) {
var viewFields = [];
var exp = calling_trigger_prop?.data?.name?.value;
if (!exp) {
return viewFields;
}
const trim_wrapping_braces = function (value) {
const trimmed = value.trim();
if (trimmed.startsWith('{') && trimmed.endsWith('}')) {
return trimmed.substring(1, trimmed.length - 1);
}
return trimmed;
};
const strip_wrapping_quotes = function (value) {
const trimmed = value.trim();
const first = trimmed.substring(0, 1);
const last = trimmed.substring(trimmed.length - 1);
if ((first === "'" || first === '"' || first === '`') && last === first) {
return trimmed.substring(1, trimmed.length - 1);
}
return trimmed;
};
const split_top_level = function (value) {
const parts = [];
let current = '';
let quote = null;
let escape = false;
let paren_depth = 0;
let bracket_depth = 0;
let brace_depth = 0;
for (let index = 0; index < value.length; index++) {
const char = value[index];
if (escape) {
current += char;
escape = false;
continue;
}
if (quote) {
current += char;
if (char === '\\') {
escape = true;
} else if (char === quote) {
quote = null;
}
continue;
}
if (char === "'" || char === '"' || char === '`') {
quote = char;
current += char;
continue;
}
if (char === '(') paren_depth++;
if (char === ')') paren_depth = Math.max(0, paren_depth - 1);
if (char === '[') bracket_depth++;
if (char === ']') bracket_depth = Math.max(0, bracket_depth - 1);
if (char === '{') brace_depth++;
if (char === '}') brace_depth = Math.max(0, brace_depth - 1);
if ((char === ',' || char === ';') && !paren_depth && !bracket_depth && !brace_depth) {
if (current.trim()) {
parts.push(current.trim());
}
current = '';
continue;
}
current += char;
}
if (current.trim()) {
parts.push(current.trim());
}
return parts;
};
const find_top_level_colon = function (value) {
let quote = null;
let escape = false;
let paren_depth = 0;
let bracket_depth = 0;
let brace_depth = 0;
for (let index = 0; index < value.length; index++) {
const char = value[index];
if (escape) {
escape = false;
continue;
}
if (quote) {
if (char === '\\') {
escape = true;
} else if (char === quote) {
quote = null;
}
continue;
}
if (char === "'" || char === '"' || char === '`') {
quote = char;
continue;
}
if (char === '(') paren_depth++;
if (char === ')') paren_depth = Math.max(0, paren_depth - 1);
if (char === '[') bracket_depth++;
if (char === ']') bracket_depth = Math.max(0, bracket_depth - 1);
if (char === '{') brace_depth++;
if (char === '}') brace_depth = Math.max(0, brace_depth - 1);
if (char === ':' && !paren_depth && !bracket_depth && !brace_depth) {
return index;
}
}
return -1;
};
exp = trim_wrapping_braces(exp.replace(/\n/gi, ''));
const exp_arr = split_top_level(exp);
for (let index = 0; index < exp_arr.length; index++) {
const segment = exp_arr[index];
const pos = find_top_level_colon(segment);
if (pos === -1) {
continue;
}
let id = strip_wrapping_quotes(segment.substring(0, pos));
const val = segment.substring(pos + 1).trim();
if (id.substring(0, 1) === '@') {
id = id.substring(1);
}
if (!id || !val) {
continue;
}
viewFields.push({
id,
val,
});
}
return viewFields;
};
func.datasource.get_value = async function (SESSION_ID, fieldIdP, dsSessionP, rowIdP, org_dsSessionP) {
const normalize_field_id = function (field_id) {
if (typeof field_id === 'string') {
return field_id;
}
if (typeof field_id?.field_id === 'string') {
return field_id.field_id;
}
if (typeof field_id?.id === 'string') {
return field_id.id;
}
if (typeof field_id === 'number' || typeof field_id === 'boolean' || typeof field_id === 'bigint') {
return field_id.toString();
}
const coerced = field_id?.toString?.();
if (typeof coerced === 'string' && coerced && coerced !== '[object Object]') {
return coerced;
}
return null;
};
const return_missing_value = function (field_id, currentRecordId = null) {
return {
ret: {
value: undefined,
type: 'string',
prop: null,
},
dsSessionP,
fieldIdP: field_id,
currentRecordId,
found: false,
};
};
let row_lookup_issue = null;
const remember_row_lookup_issue = function (err, field_id, record_id) {
if (row_lookup_issue) return;
row_lookup_issue = {
err,
details: {
dsSessionP,
field_id,
record_id,
},
};
};
const report_row_lookup_issue = async function (lookup_ret) {
if (row_lookup_issue && !lookup_ret?.found) {
await func.utils.report_issue(SESSION_ID, {
code: 'RUN_MSG_DSC_060',
source: 'Datasource get value',
message: 'Datasource row lookup failed',
type: 'W',
err: row_lookup_issue.err,
details: row_lookup_issue.details,
skip_log: false,
});
}
return lookup_ret;
};
const return_value = async (field_id, value) => {
const _progFields = await func.datasource.get_progFields(SESSION_ID, dsSessionP);
let view_field_obj = func.common.find_item_by_key(_progFields, 'field_id', field_id);
var fieldType = view_field_obj?.props?.fieldType || 'string';
var fieldProp = view_field_obj?.props;
let table_field_obj;
if (view_field_obj?.data?.type === 'table') {
if (!_ds._dataSourceTableId) {
return func.utils.debug_report(SESSION_ID, 'Datasource', `Table type defined without dataSourceTableId deceleration`, 'E');
}
let table_obj = await func.utils.FILES_OBJ.get(SESSION_ID, _ds._dataSourceTableId);
if (!table_obj) {
return func.utils.debug_report(SESSION_ID, 'Datasource', `dataSourceTableId reference error: ` + _ds._dataSourceTableId, 'E');
}
table_field_obj = func.common.find_item_by_key(table_obj.tableFields, 'field_id', field_id);
fieldType = table_field_obj.props?.fieldType;
fieldProp = table_field_obj.props;
}
let ret = {
value: await func.common.get_cast_val(SESSION_ID, `datasource get value ${_ds.tree_obj.menuName}`, fieldIdP, fieldType, value, null),
type: fieldType,
prop: fieldProp,
};
if (ret.value && typeof ret.value === 'string' && ret.type !== 'exp') {
if (/"/.test(ret.value) && ret.value.indexOf('\\') === -1) ret.value = ret.value.replace(/"/g, '"');
}
return {
ret,
dsSessionP,
fieldIdP: field_id,
currentRecordId: _ds.currentRecordId,
found: typeof value !== 'undefined',
};
};
const return_dynamic_value = async (field_id, value) => {
let view_field_obj = _ds.dynamic_fields[field_id];
var fieldType = view_field_obj?.props?.fieldType || 'string';
var fieldProp = view_field_obj?.props;
let ret = {
value: view_field_obj.value,
type: fieldType,
prop: fieldProp,
};
if (ret.value && typeof ret.value === 'string' && ret.type !== 'exp') {
if (/"/.test(ret.value) && ret.value.indexOf('\\') === -1) ret.value = ret.value.replace(/"/g, '"');
}
return {
ret,
dsSessionP,
fieldIdP: field_id,
currentRecordId: _ds.currentRecordId,
found: typeof value !== 'undefined',
};
};
const return_value_parameters = async (field_id, value) => {
let ret = {
value: await func.common.get_cast_val(SESSION_ID, 'datasource get value', fieldIdP, value.type, value.value, null),
type: value.type,
prop: null,
};
if (ret.value && typeof ret.value === 'string' && ret.type !== 'exp') {
if (!ret.value.includes('<svg xmlns=') && /"/.test(ret.value) && ret.value.indexOf('\\') === -1) ret.value = ret.value.replace(/"/g, '"');
// if (/"/.test(ret.value) && ret.value.indexOf("\\") === -1)
// ret.value = ret.value.replace(/"/g, '\\"');
}
return {
ret,
dsSessionP,
fieldIdP: field_id,
currentRecordId: _ds.currentRecordId,
found: typeof value !== 'undefined',
};
};
const return_value_system = async (field_id, value) => {
let fieldType = glb.GLOBAL_VARS[field_id].type;
let fieldProp = null;
let ret = {
value: await func.common.get_cast_val(SESSION_ID, `datasource get value ${_ds.tree_obj.menuName}`, field_id, fieldType, value, null),
type: fieldType,
prop: fieldProp,
};
return {
ret,
dsSessionP,
fieldIdP: field_id,
currentRecordId: _ds.currentRecordId,
found: typeof value !== 'undefined',
};
};
const search_in_parameters = async (field_id) => {
if (typeof _ds?.in_parameters?.[field_id]?.value !== 'undefined') {
let ret = await return_value_parameters(field_id, _ds.in_parameters[field_id]);
return ret;
}
if (typeof _ds.parentDataSourceNo !== 'undefined') {
var org_dsSession = org_dsSessionP;
if (!org_dsSessionP) org_dsSession = dsSessionP;
let parent_record_id = recordId;
if (parent_record_id && parent_record_id !== 'newRecord') {
const parent_ds = SESSION_OBJ[SESSION_ID].DS_GLB[_ds.parentDataSourceNo];
const parent_has_record = !!parent_ds?.data_feed?.rows?.some((row) => row?._ROWID === parent_record_id);
if (parent_has_record) {
org_dsSession = null;
} else {
parent_record_id = null;
}
}
return await func.datasource.get_value(SESSION_ID, fieldIdP, _ds.parentDataSourceNo, parent_record_id, org_dsSession);
}
return await return_value(field_id);
};
if (typeof glb.GLOBAL_VARS === 'undefined') {
glb.GLOBAL_VARS = (await func.common.get_module(SESSION_ID, 'xuda-system-globals-module.mjs')).system_globals;
}
var _ds = SESSION_OBJ[SESSION_ID].DS_GLB[dsSessionP];
if (!_ds) {
if (dsSessionP > 0) {
// let prev_ds = dsSessionP - 1;
return await func.datasource.get_value(SESSION_ID, fieldIdP, dsSessionP - 1, rowIdP, org_dsSessionP);
}
const normalized_missing_field = normalize_field_id(fieldIdP);
if (normalized_missing_field === null) {
return return_missing_value(fieldIdP);
}
fieldIdP = normalized_missing_field;
return await return_value(fieldIdP);
} //console.error("error: datasource not exist: " + dsSessionP);
const normalized_field_id = normalize_field_id(fieldIdP);
if (normalized_field_id === null) {
func.utils.debug_report(SESSION_ID, 'Datasource get value', `Invalid field id type: ${typeof fieldIdP}`, 'W');
return return_missing_value(fieldIdP, _ds.currentRecordId);
}
fieldIdP = normalized_field_id;
let recordId = rowIdP;
if (!recordId) {
recordId = _ds.currentRecordId;
}
if (glb.GLOBAL_VARS[fieldIdP]) {
if (!_ds.data_system) {
_ds.data_system = {};
}
if (dsSessionP > 0) {
_ds.data_system['SYS_STR_ACTIVE_ROW_ID'] = _ds.currentRecordId;
_ds.data_system['SYS_STR_PROG_DS_SESSION'] = dsSessionP;
}
// set system time
if (glb.SYS_DATE_ARR.includes(fieldIdP)) {
var _ds_0 = SESSION_OBJ[SESSION_ID].DS_GLB[0];
if (_ds_0) {
if (!_ds_0.data_system) {
_ds_0.data_system = {};
}
const ts = await func.utils.get_dateTime(SESSION_ID, 'SYS_DATE_VALUE');
for (const val of glb.SYS_DATE_ARR) {
_ds_0.data_system[val] = await func.utils.get_dateTime(SESSION_ID, val, ts);
}
}
}
// await func.datasource.set_system_vars(SESSION_ID, dsSessionP);
if (typeof _ds?.data_system?.[fieldIdP] !== 'undefined') {
return await return_value_system(fieldIdP, _ds?.data_system?.[fieldIdP]);
}
return await search_in_parameters(fieldIdP);
}
// if (glb.PROTECTED_VARS[fieldIdP]) {
// switch (fieldIdP) {
// case "_ROW_NO": {
// let row_no = Object.keys(_ds?.data_feed?.rows).indexOf(recordId) || 0;
// return await return_value(fieldIdP, row_no);
// }
// default:
// break;
// }
// }
if (!_ds.data_feed) {
return await search_in_parameters(fieldIdP);
}
var _field_id = fieldIdP;
if (fieldIdP.substr(0, 1) === '_') {
if (_ds.alias) _field_id = _ds.alias[fieldIdP];
}
if (typeof _ds?.dynamic_fields?.[_field_id] !== 'undefined') {
return await return_dynamic_value(_field_id, _ds.dynamic_fields[_field_id]);
}
if (!org_dsSessionP && recordId) {
try {
const row_idx = func.common.find_ROWID_idx(_ds, recordId);
if (typeof _ds.data_feed?.rows?.[row_idx]?.[_field_id] !== 'undefined') {
if (Object.keys(_ds.data_feed?.rows?.[row_idx] || {})?.includes(_field_id)) {
return await return_value(_field_id, _ds.data_feed.rows[row_idx][_field_id]);
}
if (Object.keys(_ds?.dynamic_fields || {})?.includes(_field_id)) {
return await return_dynamic_value(_field_id, _ds.dynamic_fields[_field_id]);
}
}
} catch (err) {
remember_row_lookup_issue(err, _field_id, recordId);
}
}
if (_ds.currentRecordId) {
try {
const row_idx = func.common.find_ROWID_idx(_ds, _ds.currentRecordId);
if (typeof _ds.data_feed?.rows?.[row_idx]?.[_field_id] !== 'undefined') {
return await return_value(_field_id, _ds.data_feed.rows[row_idx][_field_id]);
}
} catch (error) {
remember_row_lookup_issue(error, _field_id, _ds.currentRecordId);
}
}
return await report_row_lookup_issue(await search_in_parameters(fieldIdP));
};
func.datasource.find_event_dataSource = async function (SESSION_ID, eventIdP, dsSessionP) {
const _ds = SESSION_OBJ[SESSION_ID].DS_GLB[dsSessionP];
var ret;
//============================
// Search in given datasource
//============================
if (_ds?.prog_id) {
let view_ret = await func.utils.VIEWS_OBJ.get(SESSION_ID, _ds.prog_id);
if (view_ret?.progEvents && func.common.find_item_by_key(view_ret.progEvents, 'event_name', eventIdP)) {
ret = dsSessionP;
if (_ds.callingSource === 'system') ret = 0;
if (_ds.callingSource === 'program' || !_ds.callingSource) ret = dsSessionP;
// >>> found value
return ret;
}
}
if (!ret && dsSessionP !== 0) {
//=======================================
// continue Search in parent datasource
//=======================================
if (_ds && _ds.parentDataSourceNo && Number(_ds.parentDataSourceNo) > 0 && Number(_ds.parentDataSourceNo) < dsSessionP) {
return await func.datasource.find_event_dataSource(SESSION_ID, eventIdP, _ds.parentDataSourceNo);
} else {
//========================================
// continue Search in global system
//=========================================
if (!ret) return await func.datasource.find_event_dataSource(SESSION_ID, eventIdP, 0);
}
}
};
func.datasource.reset_jobs = function (SESSION_ID, dsSessionP, sourceP, errP) {
for (const [key, val] of Object.entries(SESSION_OBJ[SESSION_ID].WORKER_OBJ.jobs)) {
if (val.dsSessionP === dsSessionP) {
func.events.delete_job(SESSION_ID, val.job_num);
break;
}
}
func.utils.debug_report(SESSION_ID, sourceP + 'Missing datasource: ' + dsSessionP, errP, 'W', null);
};
// func.datasource.set_system_vars = async function (SESSION_ID, dsSessionP) {
// var _ds = SESSION_OBJ[SESSION_ID].DS_GLB[dsSessionP];
// if (!_ds) return;
// if (!_ds.data_system) {
// _ds.data_system = {};
// }
// if (dsSessionP > 0) {
// _ds.data_system["SYS_STR_ACTIVE_ROW_ID"] = _ds.currentRecordId;
// _ds.data_system["SYS_GLOBAL_STR_PROG_DS_SESSION"] = dsSessionP;
// }
// // _ds.data_system["SYS_OBJ_DS_INFO"] = {
// // rows: _ds.rows_found,
// // first_row_id: _ds.firstRecordId,
// // last_row_id: _ds.lastRecordId,
// // query_from_segments_json: _ds.filter_from,
// // query_to_segments_json: _ds.filter_from,
// // locate_query_from_segments_json: _ds.locate_from,
// // locate_query_to_segments_json: _ds.locate_to,
// // first_row_segments_json: _ds.firstRecordKey_object,
// // last_row_segments_json: _ds.lastRecordKey_object,
// // rowid: _ds.currentRecordId,
// // };
// // if (!_ds.data_system["SYS_OBJ_DS_DATA"] && dsSessionP == 0) {
// // _ds.data_system["SYS_OBJ_DS_DATA"] = {
// // value: _.cloneDeep(_ds.data_system),
// // };
// // }
// var _ds_0 = SESSION_OBJ[SESSION_ID].DS_GLB[0];
// if (!_ds_0) return;
// if (!_ds_0.data_system) {
// _ds_0.data_system = {};
// }
// const ts = await func.utils.get_dateTime(SESSION_ID, "SYS_DATE_VALUE");
// for (const val of glb.SYS_DATE_ARR) {
// _ds_0.data_system[val] = await func.utils.get_dateTime(SESSION_ID, val, ts);
// }
// };
func.datasource.get_currentRecordId = function (SESSION_ID, dsSessionP, from_datasourceP) {
var _ds = SESSION_OBJ[SESSION_ID].DS_GLB[dsSessionP];
if (_ds._dataSourceTableId !== '') {
var firstRecordId = _ds.firstRecordId; // returns the value of the fist row
var currentRecordId = _ds.currentRecordId; // record id that exist on ds after entering the form
var locatedRecordId = _ds.locatedRecordId; // record id located by ds
if (!currentRecordId || from_datasourceP) {
// first time without locate
if (!locatedRecordId) currentRecordId = firstRecordId;
// set first row when no rec located
else currentRecordId = locatedRecordId; // set with located row
}
} else currentRecordId = 'newRecord'; // create mode
return currentRecordId;
};
func.datasource.interval = function (session_id, dsSessionP, typeP) {
var SESSION_ID = session_id;
var interval = [];
var _ds = SESSION_OBJ[SESSION_ID].DS_GLB[dsSessionP];
// var ds = _ds;
// var v = ds.v;
// var arr = func.datasource.get_event_interval_arr(
// SESSION_ID,
// dsSessionP,
// typeP
// );
var arr = _ds[typeP];
var fx = {
init: async function () {
if (arr?.length) {
for (let val of arr) {
var event_id = val[0];
var interval_rate = val[1];
var condition = val[2];
interval.push(
setInterval(async function () {
if (!SESSION_OBJ[SESSION_ID]) return;
var event_count = await func.datasource.get_view_events_count(SESSION_ID, dsSessionP, typeP, event_id);
if (!event_count) {
fx.clear();
return;
}
var event_condition = await func.expression.get(SESSION_ID, condition, dsSessionP, 'condition'); // execute condition;
if (condition && !event_condition.result) return;
const e = await func.datasource.execute_view_events(SESSION_ID, dsSessionP, typeP, event_id);
// for (const [key, val] of Object.entries(e)) {
// val.done = false;
// }
}, Number(interval_rate) * 1000),
);
}
} else {
await fx.clear();
return;
}
},
clear: function () {
if (DATASOURCE_INTERVALS[session_id]) delete DATASOURCE_INTERVALS[session_id][dsSessionP];
for (const [key, val] of Object.entries(interval)) {
clearInterval(val);
}
},
};
return fx;
};
// func.datasource.server_cron = function (session_id) {
// var SESSION_ID = session_id;
// var jobs = [];
// var arr = func.datasource.get_event_interval_arr(SESSION_ID, 0, 'server_cron');
// const schedule = require('node-schedule');
// if (!arr.length) {
// return jobs;
// }
// for (let val of arr) {
// var event_id = val[0];
// var cron_prop = val[1];
// var condition = val[2];
// jobs.push(
// schedule.scheduleJob(cron_prop, async function () {
// if (!SESSION_OBJ[SESSION_ID]) return;
// var event_count = await func.datasource.get_view_events_count(SESSION_ID, 0, 'server_cron', event_id);
// if (!event_count) {
// fx.clear();
// return;
// }
// var event_condition = await func.expression.get(SESSION_ID, condition, 0, 'condition'); // execute condition;
// if (condition && !event_condition.result) return;
// if (event_count) {
// const e = await func.datasource.execute_view_events(SESSION_ID, 0, 'server_cron', event_id);
// // for (const [key, val] of Object.entries(e)) {
// // val.done = false;
// // }
// }
// }),
// );
// }
// return jobs;
// };
func.datasource.get_viewLoops = async function (SESSION_ID, dataSourceSession, data, batch_source, default_limit) {
var _ds = SESSION_OBJ[SESSION_ID].DS_GLB[dataSourceSession];
var args = _ds.args;
// var v = _ds.v;
var ret = default_limit;
if (batch_source === 'db_data') ret = data.rows.length;
if (batch_source === 'array' || batch_source === 'csv') ret = data.length;
if (batch_source === 'json') ret = Object.keys(data).length;
if (_ds.progDataSource?.dataSourceLimit) {
if (batch_source !== 'no_data' && Number(_ds.progDataSource?.dataSourceLimit) < ret) {
ret = Number(_ds.progDataSource.dataSourceLimit);
}
if (!batch_source) ret = Number(_ds.progDataSource.dataSourceLimit);
}
if (prog_obj.progDataSource?.dataSourceLoopExp) {
var n = (await func.expression.get(SESSION_ID, _ds.v.viewLoopsExp, dataSourceSession, 'view_loop', args.rowIdP)).result;
if (batch_source !== 'no_data' && n < ret) ret = n;
if (!batch_source) ret = n;
}
return ret;
};
func.datasource.set_VIEW_data = async function (SESSION_ID, args, _ds) {
_ds.v = {
viewFieldsProp: {},
segFrom: [],
segTo: [],
segLocateFrom: [],
segLocateTo: [],
viewModule: 'adapter',
};
_ds.viewEventExec_arr = {};
var view = structuredClone(await func.utils.VIEWS_OBJ.get(SESSION_ID, args.prog_id));
// var view = klona.klona(await func.utils.VIEWS_OBJ.get(SESSION_ID, args.prog_id));
_ds.v.dataSourceSrcType = view.dataSourceSrcType;
if (view.progDataSource) _ds.progDataSource = view.progDataSource;
_ds.v.viewIndex = view?.progDataSource?.dataSourceIndexesObj;
let tree_ret = await func.utils.TREE_OBJ.get(SESSION_ID, args.prog_id);
_ds.v.viewSourceDesc = tree_ret.menuName;
if (!_ds.v.viewSourceDesc && tree_ret) {
_ds.v.viewSourceDesc = tree_ret.menuName;
}
if (glb.FUNCTION_NODES_ARR.includes(tree_ret.menuType)) {
_ds.v.viewModule = 'function';
}
_ds.v.viewSourceProp = tree_ret.menuType;
if (view.progEvents) _ds.v.progEvents = view.progEvents;
_ds._progDataSource_fields = [];
if (_ds.progDataSource) {
let ret = func.expression.parse(JSON.stringify(_ds.progDataSource));
_ds._progDataSource_fields = ret.map((e) => {
if (e.fieldId) return e.fieldId;
});
}
};
func.datasource.get_cast_val = async function (SESSION_ID, source, dsSession, valP, typeP, req, error) {
var prog_id, prog_name;
var _session = SESSION_OBJ[SESSION_ID];
var _ds = _session.DS_GLB[dsSession];
prog_id = _ds.prog_id;
prog_name = await func.utils.TREE_OBJ.get(SESSION_ID, _ds.prog_id).menuName;
const prog_info = prog_id ? ` (prog: ${prog_id} ${prog_name})` : '';
const report_conversion_error = function (res) {
var msg = `error converting from ${valP} to ${typeP}`;
if (error) {
return func.utils.debug_report(SESSION_ID, msg, '', 'W');
}
func.utils.debug_report(SESSION_ID, msg + ' ' + (source.charAt(0).toUpperCase() + source.slice(1).toLowerCase()) + prog_info, '', 'E');
};
const report_conversion_warn = function (res) {
// number/boolean/bigint -> string is lossless; skip the noise (it routes as an "Unhandled Runtime Error")
if (typeP === 'string' && (typeof valP === 'number' || typeof valP === 'boolean' || typeof valP === 'bigint')) return;
var msg = `type mismatch auto conversion from value ${valP} to ${typeP}`;
func.utils.debug_report(SESSION_ID, msg + ' ' + (source.charAt(0).toUpperCase() + source.slice(1).toLowerCase()) + prog_info, '', 'W');
};
// var ret = valP;
if (error) {
return report_conversion_error();
}
const module = await func.common.get_module(SESSION_ID, 'xuda-get-cast-util-module.mjs');
return module.cast(typeP, valP, report_conversion_error, report_conversion_warn);
};
func.datasource.get_field_init_triggers_to_run = function (SESSION_ID, dataSourceSession, pre_init_fieldsP) {
var _ds = SESSION_OBJ[SESSION_ID].DS_GLB[dataSourceSession];
if (!_ds) return;
return []; // inactive 021617
}; // inactive temporary, design to execute init workflow when querying large datasets
func.datasource.get_pre_init_fields = function (SESSION_ID, dsSessionP, viewRangeExpP, viewSortExpP, viewGroupByExpP, viewLocateExpP) {
var ret = [];
return; // inactive 021617
}; // temporary inactive, init preformed on the first round
func.datasource.add_dynamic_field_to_ds = function (SESSION_ID, dsSessionP, key, val) {
var _ds = SESSION_OBJ[SESSION_ID].DS_GLB[dsSessionP];
if (!_ds.dynamic_fields) {
_ds.dynamic_fields = {};
}
const toType = function (obj) {
return {}.toString
.call(obj)
.match(/\s([a-zA-Z]+)/)[1]
.toLowerCase();
};
_ds.dynamic_fields[key] = {
id: crypto.randomUUID(),
data: {
type: 'virtual',
field_id: key,
},
props: {
fieldType: typeof val !== 'undefined' ? toType(val) : 'string',
},
value: val,
};
};
func.datasource.get_progFields = async function (SESSION_ID, dsSessionP) {
var _ds = SESSION_OBJ[SESSION_ID].DS_GLB[dsSessionP];
const _view_obj = await func.utils.VIEWS_OBJ.get(SESSION_ID, _ds.prog_id);
return _view_obj.progFields;
};
func.datasource.update_changes_for_out_parameter = async function (SESSION_ID, dsSessionP, calling_dsP, avoid_refreshP) {
let _session = SESSION_OBJ[SESSION_ID];
let _ds = _session.DS_GLB[dsSessionP];
const _calling_ds = _session.DS_GLB[calling_dsP];
const avoid_refresh = avoid_refreshP === true || avoid_refreshP?.avoid_refresh === true;
const refresh_options = avoid_refresh ? { avoid_refresh: true, refresh_attributes: true } : false;
const get_row_idx_safe = function (target_ds, row_id) {
if (!target_ds || !row_id) {
return null;
}
try {
return func.common.find_ROWID_idx(target_ds, row_id);
} catch (_error) {
return null;
}
};
if (!_ds?.PARAM_OUT_INFO || !calling_dsP || !_calling_ds) {
return;
}
let data = {};
for await (const [key, val] of Object.entries(_ds.PARAM_OUT_INFO)) {
if (val.prop === 'out') {
try {
const current_row_idx = get_row_idx_safe(_ds, _ds.currentRecordId);
const dataset_row_idx = get_row_idx_safe(_ds, 'dataset');
let result;
if (
current_row_idx !== null &&
typeof _ds?.data_feed?.rows?.[current_row_idx]?.[val.fieldId] !== 'undefined'
) {
result = _ds.data_feed.rows[current_row_idx][val.fieldId];
} else if (
dataset_row_idx !== null &&
typeof _ds?.data_feed?.rows?.[dataset_row_idx]?.[val.fieldId] !== 'undefined'
) {
result = _ds.data_feed.rows[dataset_row_idx][val.fieldId];
}
if (typeof result !== 'undefined') {
data[val.details] = result;
}
} catch (err) {
console.error(err);
}
}
}
if (!xu_isEmpty(data)) {
let datasource_changes = {
[calling_dsP]: { [_calling_ds.currentRecordId]: data },
};
try {
if (avoid_refresh) {
globalThis.__XUDA_RT_TRACE && console.log('[xuda-runtime] out_parameter_update ' +
JSON.stringify({
avoidRefresh: true,
source_ds: dsSessionP,
target_ds: calling_dsP,
fields: Object.keys(data),
}),
);
}
} catch (e) {}
await func.datasource.update(SESSION_ID, datasource_changes, null, refresh_options);
}
};
func.datasource.set_outputField = async function (SESSION_ID, dsSessionP, result, args, avoid_refreshP) {
var _session = SESSION_OBJ[SESSION_ID];
// let _ds = _session.DS_GLB[dsSessionP];
const avoid_refresh = avoid_refreshP === true || avoid_refreshP?.avoid_refresh === true;
const refresh_options = avoid_refresh ? { avoid_refresh: true, refresh_attributes: true } : false;
const output_field = await func.datasource.get_args_property_value(SESSION_ID, dsSessionP, args, 'outputField');
if (output_field) {
let datasource_changes = {};
let ret_get_value = await func.datasource.get_value(SESSION_ID, output_field, dsSessionP);
if (ret_get_value.found) {
let _ds = _session.DS_GLB[ret_get_value.dsSessionP];
if (!datasource_changes[_ds.dsSession]) {
datasource_changes[_ds.dsSession] = {};
}
if (!datasource_changes[_ds.dsSession][ret_get_value.currentRecordId]) {
datasource_changes[_ds.dsSession][ret_get_value.currentRecordId] = {};
}
datasource_changes[_ds.dsSession][ret_get_value.currentRecordId][output_field] = result;
try {
if (avoid_refresh) {
globalThis.__XUDA_RT_TRACE && console.log('[xuda-runtime] output_field_update ' +
JSON.stringify({
avoidRefresh: true,
target_ds: _ds.dsSession,
field: output_field,
}),
);
}
} catch (e) {}
await func.datasource.update(SESSION_ID, datasource_changes, null, refresh_options);
}
}
};
func.datasource.get_args_property_value = async function (SESSION_ID, dsSession, args, prop_name) {
// Headless executions (cron/emitter workers) have no calling trigger — _prop is
// undefined there and the unguarded read crashed every server-side get_data run.
let _prop = args?.calling_trigger_prop?.data?.name;
let _value = _prop?.[prop_name];
if (_prop?.[`xu-exp:${prop_name}`]) {
_value = (await func.expression.get(SESSION_ID, _prop[`xu-exp:${prop_name}`], dsSession, `${prop_name} expression`)).result;
}
return _value;
};
func.UI.screen = {};
func.UI.screen.init = async function (SESSION_ID, prog_id, sourceScreenP, callingDataSource_objP, $callingContainerP, triggerIdP, rowIdP, jobNoP, is_panelP, parameters_obj_inP, source_functionP, call_screen_propertiesP, refreshed_ds, parameters_raw_obj) {
return await func.runtime.ui.init_screen({
SESSION_ID,
prog_id,
sourceScreenP,
callingDataSource_objP,
$callingContainerP,
triggerIdP,
rowIdP,
jobNoP,
is_panelP,
parameters_obj_inP,
source_functionP,
call_screen_propertiesP,
refreshed_ds,
parameters_raw_obj,
});
};
func.UI.screen.update_SYS_OBJ_WIN_INFO = function (SESSION_ID, dsNoP) {
return func.runtime.ui.update_sys_obj_win_info(SESSION_ID, dsNoP);
};
func.UI.screen.validate_exit_events = async function (SESSION_ID, div_data_paramsP, forceP) {
return await func.runtime.ui.validate_exit_events(SESSION_ID, div_data_paramsP, forceP);
};
func.UI.screen.call_embed = function (SESSION_ID, prog) {
return func.runtime.ui.call_embed(SESSION_ID, prog);
};
func.UI.screen.refresh_xu_attributes = async function (SESSION_ID, fields_arr, jobNoP, $elm_to_search, dsSession_changed, avoid_xu_for_refresh, trigger) {
return await func.runtime.ui.refresh_xu_attributes({
SESSION_ID,
fields_arr,
jobNoP,
$elm_to_search,
dsSession_changed,
avoid_xu_for_refresh,
trigger,
});
};
func.UI.screen.refresh_screen = async function (SESSION_ID, fields_changed_arr, datasource_changed, fields_changed_datasource, watcher) {
return await func.runtime.ui.refresh_screen({
SESSION_ID,
fields_changed_arr,
datasource_changed,
fields_changed_datasource,
watcher,
});
};
func.UI.screen.execute_xu_functions = async function (SESSION_ID, is_skeleton, $root_container, nodeP, $container, paramsP, parent_infoP, jobNoP, keyP, parent_nodeP, xu_func, $elm, val, is_init, refreshed_ds) {
if (is_skeleton) return;
return await func.runtime.render.execute_xu_function({
SESSION_ID,
is_skeleton,
$root_container,
nodeP,
$container,
paramsP,
parent_infoP,
jobNoP,
keyP,
parent_nodeP,
xu_func,
$elm,
val,
is_init,
refreshed_ds,
get_params_obj_new: func.runtime.program.get_params_obj,
});
};
func.UI.screen.fix_val_defaults = function (key, val) {
return func.runtime.render.fix_val_defaults(key, val);
};
func.UI.screen.set_attributes_new = async function (SESSION_ID, is_skeleton, $root_container, nodeP, $container, paramsP, parent_infoP, jobNoP, keyP, parent_nodeP, $elm, is_init, execute_attributes = [], refreshed_ds) {
return await func.runtime.render.set_attributes_new({
SESSION_ID,
is_skeleton,
$root_container,
nodeP,
$container,
paramsP,
parent_infoP,
jobNoP,
keyP,
parent_nodeP,
$elm,
is_init,
execute_attributes,
refreshed_ds,
});
};
func.UI.screen.panel_post_render_handler = async function (SESSION_ID, $container, $wrapper, nodeP, $panel_div, jobNoP) {
return await func.runtime.ui.panel_post_render_handler({
SESSION_ID,
$container,
$wrapper,
nodeP,
$panel_div,
jobNoP,
});
};
func.UI.screen.create_container = async function (SESSION_ID, $root_container, nodeP, $container, paramsP, parent_infoP, jobNoP, keyP, parent_nodeP, prop, classP, elem_propP, div_typeP, $appendToP, attr_str, is_placeholder) {
return await func.runtime.ui.create_container({
SESSION_ID,
$root_container,
nodeP,
$container,
paramsP,
parent_infoP,
jobNoP,
keyP,
parent_nodeP,
prop,
classP,
elem_propP,
div_typeP,
$appendToP,
attr_str,
is_placeholder,
});
};
func.UI.screen.execute_screen_ready_events = async function (SESSION_ID, paramsP, sourceP, $div, jobNoP, $div_objP) {
return await func.runtime.ui.execute_screen_ready_events({
SESSION_ID,
paramsP,
sourceP,
$div,
jobNoP,
$div_objP,
});
};
func.UI.screen.screen_loading_done = async function (SESSION_ID, paramsP, $div, jobNoP) {
return await func.runtime.ui.screen_loading_done({
SESSION_ID,
paramsP,
$div,
jobNoP,
});
};
func.UI.screen.render_ui_tree = async function (SESSION_ID, $container, nodeP, parent_infoP, paramsP, jobNoP, is_skeleton, keyP, refreshed_ds, parent_nodeP, check_existP, $root_container) {
return await func.runtime.render.render_ui_tree(SESSION_ID, $container, nodeP, parent_infoP, paramsP, jobNoP, is_skeleton, keyP, refreshed_ds, parent_nodeP, check_existP, $root_container);
};
func.UI.screen.refresh_document_changes_for_realtime_update = async function (SESSION_ID, doc_change) {
return await func.runtime.ui.refresh_document_changes_for_realtime_update(SESSION_ID, doc_change);
};
func.UI.screen.live_preview_hot_module_reload = async function (SESSION_ID, doc) {
return await func.runtime.ui.live_preview_hot_module_reload(SESSION_ID, doc);
};
func.UI.component = {};
func.UI.component.get_wrapped_nodes = function (target) {
if (!target) {
return [];
}
if (typeof target.toArray === "function") {
return target.toArray().filter(Boolean);
}
if (Array.isArray(target)) {
return target.filter(Boolean);
}
const first_node = func.runtime.ui.get_first_node(target);
return first_node ? [first_node] : [];
};
func.UI.component.move_wrapped_nodes = function (target, source) {
const target_node = func.runtime.ui.get_first_node(target);
if (!target_node) {
return false;
}
const nodes = func.UI.component.get_wrapped_nodes(source);
for (let index = 0; index < nodes.length; index++) {
target_node.appendChild(nodes[index]);
}
return true;
};
func.UI.component.create_app_modal_component = function (
SESSION_ID,
modal_content_name
) {
const root_element = SESSION_OBJ[SESSION_ID].root_element;
const xu_modal_controller_id = "xu-modal-controller";
var xu_modal_controller = root_element.querySelector(xu_modal_controller_id);
if (!xu_modal_controller) {
xu_modal_controller = document.createElement(xu_modal_controller_id);
root_element.prepend(xu_modal_controller);
}
customElements.define(
modal_content_name,
class extends HTMLElement {
constructor() {
super();
// console.log("modal_content_name", modal_content_name);
// let template = document.getElementById(
// "modal_template_" + modal_content_name
// );
// let templateContent = template.content;
// const shadowRoot = this.attachShadow({ mode: "open" });
// shadowRoot.appendChild(templateContent.cloneNode(true));
}
connectedCallback() {}
}
);
return xu_modal_controller_id;
};
// func.UI.component.create_in_app_modal_component = function (SESSION_ID) {
// customElements.define(
// "in-app-modal-content" + SESSION_ID,
// class ModalContent extends HTMLElement {
// connectedCallback() {
// func.UI.component.init_app_modal_component(
// SESSION_ID,
// "in-app-modal-content" + SESSION_ID
// );
// }
// }
// );
// };
// func.UI.component.create_qr_modal_component = function (SESSION_ID) {
// customElements.define(
// "qr-modal-content" + SESSION_ID,
// class ModalContent extends HTMLElement {
// connectedCallback() {
// func.UI.component.init_app_modal_component(
// SESSION_ID,
// "qr-modal-content" + SESSION_ID
// );
// }
// }
// );
// };
// func.UI.component.init_app_modal_component = async function (
// SESSION_ID,
// modal_content_name
// ) {
// const xu_modal_controller = document.querySelector("xu-modal-controller");
// var $modal = $(modal_content_name);
// var params =
// $(xu_modal_controller).data().xuControllerParams[modal_content_name];
// var icon;
// if (params.icon) {
// icon = await func.common.get_custom_icon(SESSION_ID, params.icon);
// }
// var dismiss = function () {
// APP_MODAL_OBJ[modal_content_name].dismiss().then(() => {
// APP_MODAL_OBJ[modal_content_name] = null;
// if (params.$container) {
// func.UI.screen.validate_exit_events(
// SESSION_ID,
// params.$container.data().xuData.paramsP,
// null,
// function () {
// func.datasource.clean_all(SESSION_ID, params.dsSession);
// }
// );
// }
// });
// };
// if (params.$container) {
// $modal.attr("id", params.$container.attr("id"));
// $.each(params.$container.data(), function (key, val) {
// $modal.data(key, val);
// });
// }
// var $header = $("<ion-header>");
// var $toolbar = $("<ion-toolbar>").appendTo($header);
// var $title = $("<ion-title>").text(params.menuTitle).appendTo($toolbar);
// if (icon) {
// var logo = `
// <img style="width: 45px; margin: 0 15px;" slot="start" src="${icon}" >
// `;
// $toolbar.append(logo);
// }
// if (
// !params.$container ||
// params.$container.data().xuData.paramsP.screenInfo.mCLS !== "false"
// ) {
// var $buttons = $('<ion-buttons slot="end">').appendTo($toolbar);
// $('<ion-button><ion-icon name="close"></ion-icon>')
// .click(dismiss)
// .appendTo($buttons);
// }
// if (
// !params.$container ||
// params.$container.data().xuData.paramsP.screenInfo.mHDR !== "false"
// ) {
// $header.appendTo($modal);
// }
// $modal.append(params.$dialogDiv);
// if (params.$modal_footer) {
// params.$modal_footer.appendTo($modal);
// }
// };
func.UI.component.create_app_page_component = async function (SESSION_ID, id) {
const component_id = "xu-page-component-" + id;
customElements.define(
component_id,
class extends HTMLElement {
constructor() {
super();
var xu_nav = SESSION_OBJ[SESSION_ID].root_element.querySelector("xu-nav");
var params = func.runtime.ui.get_data(xu_nav);
var container_data = func.runtime.ui.get_data(params.xuData.nav_params[id].$container);
for (const [key, val] of Object.entries(container_data)) {
func.runtime.ui.set_data(this, key, val);
}
}
connectedCallback() {
const page_back_callback = async () => {
await func.runtime.ui.validate_exit_events(
SESSION_ID,
func.runtime.ui.get_data(params.$container).xuData.paramsP,
null
);
nav.back();
func.datasource.clean_all(SESSION_ID, params.dsSession);
};
const nav = SESSION_OBJ[SESSION_ID].root_element.querySelector("xu-nav");
const params = func.runtime.ui.get_data(nav).xuData.nav_params[id];
params.callback(this, page_back_callback);
}
}
);
return component_id;
};
// func.UI.component.init_app_page_component = async function (SESSION_ID, id) {
// var params = $(SESSION_OBJ[SESSION_ID].root_element).find("xu-nav").data()
// .xuData.nav_params[id];
// var _this = this;
// var $page = $("xu-page-component-" + id).attr(
// "id",
// params.$container.attr("id")
// );
// $.each(params.$container.data(), function (key, val) {
// $page.data(key, val);
// });
// var icon;
// if (params.icon) {
// icon = await func.common.get_custom_icon(SESSION_ID, params.icon);
// }
// var $header = $("<ion-header>");
// var $toolbar = $("<ion-toolbar>").appendTo($header);
// $("<ion-title>").text(params.name).appendTo($toolbar);
// if (icon) {
// var logo = `
// <img style="width: 45px; margin: 0 15px;" slot="end" src="${icon}" >
// `;
// $toolbar.append(logo);
// }
// var $buttons = $('<ion-buttons slot="start">').appendTo($toolbar);
// if (params.$container.data().xuData.paramsP.screenInfo.mBCK !== "false") {
// var $button = $("<ion-back-button>");
// $button.off("click");
// $button
// .on("click", function () {
// func.UI.screen.validate_exit_events(
// SESSION_ID,
// params.$container.data().xuData.paramsP,
// null,
// function () {
// func.datasource.clean_all(SESSION_ID, params.dsSession);
// }
// );
// })
// .appendTo($buttons);
// }
// if (
// !params.$container ||
// params.$container.data().xuData.paramsP.screenInfo.mHDR !== "false"
// ) {
// if (
// params.icon ||
// params.name ||
// params.$container.data().xuData.paramsP.screenInfo.mBCK !== "false"
// ) {
// $header.appendTo($page);
// }
// }
// $page.append(params.div);
// };
func.UI.component.create_app_root_component = function (SESSION_ID) {
customElements.define(
"xu-root-component-" + SESSION_ID,
class ModalContent extends HTMLElement {
connectedCallback() {
const xu_nav = SESSION_OBJ[SESSION_ID].root_element.querySelector("xu-nav");
const xu_nav_data = func.runtime.ui.get_data(xu_nav);
func.UI.component.move_wrapped_nodes(this, xu_nav_data?.xuData?.$div);
const root_component_callback = xu_nav_data.xuData.root_component_callback;
if (root_component_callback) {
root_component_callback();
}
}
}
);
};
func.UI.component.create_app_popover_component = function (SESSION_ID) {
const root_element = SESSION_OBJ[SESSION_ID].root_element;
const xu_popover_controller_id = "xu-popover-controller-" + SESSION_ID;
var xu_popover_controller_el = root_element.querySelector(xu_popover_controller_id);
if (!xu_popover_controller_el) {
xu_popover_controller_el = document.createElement(xu_popover_controller_id);
root_element.prepend(xu_popover_controller_el);
}
customElements.define(
"xu-popover-content-" + SESSION_ID,
class ModalContent extends HTMLElement {
connectedCallback() {
const xu_popover_controller = document.querySelector(
"xu-popover-controller-" + SESSION_ID
);
var params = func.runtime.ui.get_data(xu_popover_controller, "xuControllerParams");
var popover_el = document.querySelector("xu-popover-content-" + SESSION_ID);
popover_el.setAttribute("id", func.runtime.ui.get_attr(params.$container, "id"));
var container_data = func.runtime.ui.get_data(params.$container);
for (const [key, val] of Object.entries(container_data)) {
func.runtime.ui.set_data(popover_el, key, val);
}
popover_el.innerHTML = '';
func.UI.component.move_wrapped_nodes(popover_el, params.$dialogDiv);
}
}
);
return xu_popover_controller_id;
};
func.UI.component.create_camera_select_popover_component = function (
SESSION_ID
) {
customElements.define(
"popover-camera-select-page" + SESSION_ID,
class ModalContent extends HTMLElement {
connectedCallback() {
const xu_popover_controller = document.querySelector(
"ion-popover-controller"
);
var params = func.runtime.ui.get_data(xu_popover_controller, "xuControllerParams");
func.UI.component.move_wrapped_nodes(this, params.$dialogDiv);
}
}
);
};
// func.UI.component.get_image_element = function (SESSION_ID, key, val, ds_id) {
// var $pallet_wrapper = $(`<div class="image_wrapper">`);
// var $modal_content = $(`<ion-content fullscreen scroll-x >`);
// var $modal_footer = $(`<ion-tab-bar slot="bottom">`);
// if (val.doc.dFWD) {
// $pallet_wrapper.css("width", val.doc.dFWD);
// }
// if (val.doc.dFHT) {
// $pallet_wrapper.css("height", val.doc.dFHT);
// }
// var $upload_wrapper = $(`<div class="upload_wrapper">`).appendTo(
// $pallet_wrapper
// );
// var $crop_wrapper = $(`<div>`).appendTo($modal_content);
// var $upload_image = $(
// `<img class="image_img" id="${key}" onerror="this.style.display='none'" src="data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHhtbG5zOnhsaW5rPSJodHRwOi8vd3d3LnczLm9yZy8xOTk5L3hsaW5rIiB3aWR0aD0iNTBweCIgdmVyc2lvbj0iMS4xIiBpZD0iQ2FwYV8xIiB4PSIwcHgiIHk9IjBweCIgdmlld0JveD0iMCAwIDYwIDYwIiBzdHlsZT0iIiB4bWw6c3BhY2U9InByZXNlcnZlIiBoZWlnaHQ9IjUwcHgiPgo8ZyBzdHlsZT0iJiMxMDsgICAgZmlsbDogcmdiYSgwLDAsMCwwLjEpOyYjMTA7Ij4KCTxwYXRoIGQ9Ik01NS4yMDEsMTUuNWgtOC41MjRsLTQtMTBIMTcuMzIzbC00LDEwSDEydi01SDZ2NUg0Ljc5OUMyLjE1MiwxNS41LDAsMTcuNjUyLDAsMjAuMjk5djI5LjM2OCAgIEMwLDUyLjMzMiwyLjE2OCw1NC41LDQuODMzLDU0LjVoNTAuMzM0YzIuNjY1LDAsNC44MzMtMi4xNjgsNC44MzMtNC44MzNWMjAuMjk5QzYwLDE3LjY1Miw1Ny44NDgsMTUuNSw1NS4yMDEsMTUuNXogTTgsMTIuNWgydjNIOCAgIFYxMi41eiBNNTgsNDkuNjY3YzAsMS41NjMtMS4yNzEsMi44MzMtMi44MzMsMi44MzNINC44MzNDMy4yNzEsNTIuNSwyLDUxLjIyOSwyLDQ5LjY2N1YyMC4yOTlDMiwxOC43NTYsMy4yNTYsMTcuNSw0Ljc5OSwxNy41SDZoNiAgIGgyLjY3N2w0LTEwaDIyLjY0Nmw0LDEwaDkuODc4YzEuNTQzLDAsMi43OTksMS4yNTYsMi43OTksMi43OTlWNDkuNjY3eiIvPgoJPHBhdGggZD0iTTMwLDE0LjVjLTkuOTI1LDAtMTgsOC4wNzUtMTgsMThzOC4wNzUsMTgsMTgsMThzMTgtOC4wNzUsMTgtMThTMzkuOTI1LDE0LjUsMzAsMTQuNXogTTMwLDQ4LjVjLTguODIyLDAtMTYtNy4xNzgtMTYtMTYgICBzNy4xNzgtMTYsMTYtMTZzMTYsNy4xNzgsMTYsMTZTMzguODIyLDQ4LjUsMzAsNDguNXoiLz4KCTxwYXRoIGQ9Ik0zMCwyMC41Yy02LjYxNywwLTEyLDUuMzgzLTEyLDEyczUuMzgzLDEyLDEyLDEyczEyLTUuMzgzLDEyLTEyUzM2LjYxNywyMC41LDMwLDIwLjV6IE0zMCw0Mi41Yy01LjUxNCwwLTEwLTQuNDg2LTEwLTEwICAgczQuNDg2LTEwLDEwLTEwczEwLDQuNDg2LDEwLDEwUzM1LjUxNCw0Mi41LDMwLDQyLjV6Ii8+Cgk8cGF0aCBkPSJNNTIsMTkuNWMtMi4yMDYsMC00LDEuNzk0LTQsNHMxLjc5NCw0LDQsNHM0LTEuNzk0LDQtNFM1NC4yMDYsMTkuNSw1MiwxOS41eiBNNTIsMjUuNWMtMS4xMDMsMC0yLTAuODk3LTItMnMwLjg5Ny0yLDItMiAgIHMyLDAuODk3LDIsMlM1My4xMDMsMjUuNSw1MiwyNS41eiIvPgo8L2c+CgogCgo8L3N2Zz4=" alt="" />`
// ).appendTo($upload_wrapper);
// var currentPopover = null;
// const open_select_camera_popup = async function () {
// const popoverController_div = document.querySelector(
// "ion-popover-controller"
// );
// const $list = $("<ion-list>");
// const $camera = $(
// `<ion-item>Take Photo <ion-icon name="camera-outline" slot="end"></ion-icon> </ion-icon></ion-item>`
// ).appendTo($list);
// const $photo = $(
// `<ion-item>Photo Library <ion-icon name="image-outline" slot="end"></ion-icon></ion-item>`
// ).appendTo($list);
// $camera.click(async function () {
// await popoverController.dismiss();
// navigator.camera.getPicture(
// function cameraSuccess(imageUri) {
// Doka.create()
// .edit(window.Ionic.WebView.convertFileSrc(imageUri))
// .then((output) => {
// // Called when the source image has been edited
// // Receives the output file and optionally, if `outputData`
// // is set to true, the editor state
// // console.log(output);
// var getBase64 = function (file) {
// var reader = new FileReader();
// reader.readAsDataURL(file);
// reader.onload = function () {
// $imgInp
// .data("filepond_base64", reader.result)
// .trigger("change");
// $upload_image.prop("src", reader.result);
// };
// reader.onerror = function (error) {
// console.log("Error: ", error);
// };
// };
// getBase64(output.file);
// });
// // You may choose to copy the picture, save it somewhere, or upload.
// },
// function cameraError(error) {
// console.debug("Unable to obtain picture: " + error, "app");
// },
// {
// quality: 100,
// correctOrientation: true,
// }
// );
// });
// $photo.click(async function () {
// await popoverController.dismiss();
// navigator.camera.getPicture(
// function cameraSuccess(imageUri) {
// Doka.create()
// .edit(window.Ionic.WebView.convertFileSrc(imageUri))
// .then((output) => {
// // Called when the source image has been edited
// // Receives the output file and optionally, if `outputData`
// // is set to true, the editor state
// var getBase64 = function (file) {
// var reader = new FileReader();
// reader.readAsDataURL(file);
// reader.onload = function () {
// $imgInp
// .data("filepond_base64", reader.result)
// .trigger("change");
// $upload_image.prop("src", reader.result);
// };
// reader.onerror = function (error) {
// console.log("Error: ", error);
// };
// };
// getBase64(output.file);
// });
// // You may choose to copy the picture, save it somewhere, or upload.
// },
// function cameraError(error) {
// console.debug("Unable to obtain picture: " + error, "app");
// },
// {
// quality: 100,
// correctOrientation: true,
// sourceType: Camera.MediaType.PICTURE,
// }
// );
// // }
// });
// $(popoverController_div).data({ params: { $dialogDiv: $list } });
// var popover = await popoverController.create({
// component: "popover-camera-select-page",
// // event: ev,
// translucent: true,
// });
// currentPopover = popover;
// return popover.present();
// };
// const croppie_integration = function () {
// function readURL(input) {
// if (input.files && input.files[0]) {
// var reader = new FileReader();
// reader.onload = function (e) {
// img_src = e.target.result;
// Doka.create()
// .edit(img_src)
// .then((output) => {
// // Called when the source image has been edited
// // Receives the output file and optionally, if `outputData`
// // is set to true, the editor state
// var getBase64 = function (file) {
// var reader = new FileReader();
// reader.readAsDataURL(file);
// reader.onload = function () {
// $imgInp.data("filepond_base64", reader.result);
// // .trigger("change");
// $upload_image.prop("src", reader.result);
// $upload_image.trigger("image_change");
// };
// reader.onerror = function (error) {
// console.log("Error: ", error);
// };
// };
// getBase64(output.file);
// });
// //////////////
// };
// reader.onloadend = function () {};
// reader.readAsDataURL(input.files[0]);
// }
// }
// $imgInp.change(function () {
// readURL(this);
// });
// };
// var $imgInp = $(
// `<input accept="file" type="file" class="imgInp" name="${key}" nodeid="${val.id}" recordid="${SESSION_OBJ[SESSION_ID].DS_GLB[ds_id].currentRecordId}"/>`
// )
// .attr("ui_id", key)
// .appendTo($upload_wrapper);
// if (func.utils.get_device()) {
// $imgInp.attr("hidden", true);
// $upload_image.click(function () {
// open_select_camera_popup();
// });
// } else {
// croppie_integration();
// }
// setTimeout(function () {
// $imgInp.css("height", $pallet_wrapper.height());
// }, 1000);
// return $pallet_wrapper;
// };
func.UI.component.init_xu_nav = function ($container, $nav) {
const container_el = func.runtime.ui.get_first_node($container);
const nav_el = func.runtime.ui.get_first_node($nav);
func.runtime.ui.set_data(nav_el, "xuData", { nav_stack: [] });
Object.defineProperty(nav_el, "setRoot", {
value: async function (component_id) {
return new Promise(async function (resolve, reject) {
func.runtime.ui.get_data(nav_el).xuData.nav_stack.unshift(component_id);
container_el.insertAdjacentHTML("beforeend", "<" + component_id + ">");
await customElements.whenDefined(component_id);
resolve();
});
},
configurable: true,
});
Object.defineProperty(nav_el, "push", {
value: async function (component_id) {
return new Promise(async function (resolve, reject) {
let last_component = func.runtime.ui.get_data(nav_el).xuData.nav_stack.at(-1);
var last_el = document.querySelector(last_component);
if (last_el) last_el.style.display = 'none';
func.runtime.ui.get_data(nav_el).xuData.nav_stack.push(component_id);
container_el.insertAdjacentHTML("beforeend", "<" + component_id + ">");
await customElements.whenDefined(component_id);
resolve();
});
},
configurable: true,
});
Object.defineProperty(nav_el, "popToRoot", {
value: async function () {
return new Promise(async function (resolve, reject) {
let last_component = func.runtime.ui.get_data(nav_el).xuData.nav_stack.at(-1);
var last_el = document.querySelector(last_component);
if (last_el) last_el.remove();
let root_component = func.runtime.ui.get_data(nav_el).xuData.nav_stack[0];
func.runtime.ui.get_data(nav_el).xuData.nav_stack[root_component];
var root_el = document.querySelector(root_component);
if (root_el) root_el.style.display = '';
await customElements.whenDefined(root_component);
resolve();
});
},
configurable: true,
});
Object.defineProperty(nav_el, "popTo", {
value: async function (index) {
return new Promise(async function (resolve, reject) {
let last_component = func.runtime.ui.get_data(nav_el).xuData.nav_stack.at(-1);
let last_component_index = func.runtime.ui.get_data(nav_el).xuData.nav_stack.length - 1;
var last_el = document.querySelector(last_component);
if (last_el) last_el.remove();
try {
var selected_component =
func.runtime.ui.get_data(nav_el).xuData.nav_stack[index || last_component_index - 1];
} catch (error) {
console.error(error);
return reject(error);
}
var selected_el = document.querySelector(selected_component);
if (selected_el) selected_el.style.display = '';
func.runtime.ui.get_data(nav_el).xuData.nav_stack.splice(last_component_index, 1);
await customElements.whenDefined(selected_component);
resolve();
});
},
configurable: true,
});
Object.defineProperty(nav_el, "back", {
value: async function (index) {
return new Promise(async function (resolve, reject) {
let last_component = func.runtime.ui.get_data(nav_el).xuData.nav_stack.at(-1);
let last_component_index = func.runtime.ui.get_data(nav_el).xuData.nav_stack.length - 1;
if (last_component_index === 0) return;
var last_el = document.querySelector(last_component);
if (last_el) last_el.remove();
try {
var selected_component =
func.runtime.ui.get_data(nav_el).xuData.nav_stack[last_component_index - 1];
} catch (error) {
console.error(error);
return reject(error);
}
var selected_el = document.querySelector(selected_component);
if (selected_el) selected_el.style.display = '';
func.runtime.ui.get_data(nav_el).xuData.nav_stack.splice(last_component_index, 1);
await customElements.whenDefined(selected_component);
resolve();
});
},
configurable: true,
});
};
func.expression = {};
func.expression.get = async function (SESSION_ID, valP, dsSessionP, sourceP, rowIdP, sourceActionP, secondPassP, calling_fieldIdP, fieldsP, debug_infoP, iterate_info, js_script_callback, jobNo, api_output_type) {
class xu_class {
async get() {
if (typeof EXP_BUSY !== 'undefined') {
EXP_BUSY = true;
}
var ret;
var fields = {};
var error;
var warning;
// XU_PERF: object token values are passed to the evaluator through this
// slot array instead of being JSON-embedded into the source text, so the
// source stays identical across rows and compiles once (see secure_eval)
var xu_slot_values = null;
var xu_slot_positions = null;
function evalJson(text) {
return eval('(' + text + ')');
}
if (valP === null) {
ret = '';
} else {
switch (typeof valP) {
case 'string':
ret = valP;
break;
case 'undefined':
ret = '';
break;
case 'boolean':
ret = valP ? 'Y' : 'N';
break;
default:
ret = valP.toString();
break;
}
}
if (ret.includes('&')) ret = ret.replace(/\&/g, '&');
ret = func.utils.replace_studio_drive_url(SESSION_ID, ret);
const end_results = function () {
const replace_quotes = function (ret) {
for (const [key, val] of Object.entries(fields)) {
if (typeof val === 'string') ret = ret.replace('"' + val + '"', val.replace(/"/gi, ''));
}
return ret;
};
if (['update', 'javascript'].includes(sourceP)) {
if (typeof ret === 'string') ret = replace_quotes(ret);
}
const log_error = function () {
if (SESSION_OBJ[SESSION_ID].DS_GLB[dsSessionP]) {
func.utils.debug.log(SESSION_ID, SESSION_OBJ[SESSION_ID].DS_GLB[dsSessionP].nodeId, {
module: 'expression',
action: sourceP,
source: calling_fieldIdP,
prop: ret,
details: ret,
result: ret,
error: error,
warning: warning,
fields: null,
type: 'exp',
prog_id: SESSION_OBJ[SESSION_ID].DS_GLB[dsSessionP].prog_id,
debug_info: debug_infoP,
});
}
};
if (error) log_error();
// if (error || warning) log_error();
if (typeof EXP_BUSY !== 'undefined') {
EXP_BUSY = false;
}
const results = {
result: ret,
fields,
res,
explain: result,
error,
warning,
req: valP,
var_error_found,
};
// console.log('EXP>>>', results);
return results;
// return {
// result: ret,
// fields: fields,
// res: res,
// explain: result,
// error: error,
// warning: warning,
// req: valP,
// var_error_found: var_error_found,
// };
};
const variable_not_exist = async function () {
try {
if (sourceP !== 'arguments') {
if (ret && ret.startsWith('_DATE_')) {
ret = ret.slice(6);
} else if (
ret === 'self' || // bypass eval for 'self'
(ret && ret.length === 10 && ret[4] === '-' && ret[7] === '-') // bypass eval for date 2017-03-22
) {
// date or 'self' — skip eval, return as-is
} else {
ret = await func.expression.secure_eval(SESSION_ID, sourceP, ret, jobNo, dsSessionP, js_script_callback, null, undefined, xu_slot_values);
}
// console.log("AFTER OK", ret)
return end_results();
} else {
// do eval for arithmetic vals
ret = ret.replace(/_NULL/gi, '');
return end_results();
}
} catch (err) {
// console.error(err);
return end_results();
}
};
if (!func.expression.validate_variables(valP)) {
return await variable_not_exist();
}
const validate_email = async function () {
const ret = await func.expression.secure_eval(SESSION_ID, sourceP, valP, jobNo, dsSessionP, js_script_callback, null, true);
return glb.emailRegex.test(ret);
};
if (await validate_email()) {
return await variable_not_exist();
}
// var split = [];
var var_Arr = [];
const get_iterate_value_ret = function (fieldIdP) {
if (!iterate_info || (iterate_info.iterator_key !== fieldIdP && iterate_info.iterator_val !== fieldIdP)) {
return null;
}
const iter_value = iterate_info.iterator_key === fieldIdP ? iterate_info._key : iterate_info._val;
const iter_type = typeof iter_value !== 'undefined' ? {}.toString.call(iter_value).match(/\s([a-zA-Z]+)/)[1].toLowerCase() : 'string';
return {
ret: {
value: iter_value,
type: iter_type,
prop: ['array', 'object'].includes(iter_type) ? iter_value : null,
},
fieldIdP,
currentRecordId: rowIdP,
found: typeof iter_value !== 'undefined',
};
};
const split = func.expression.parse(ret) || [];
// console.log(valP, split);
const split_entries = Object.entries(split);
for (let entry_i = 0; entry_i < split_entries.length; entry_i++) {
// run each field
const [arr_key, val] = split_entries[entry_i];
const key = Number(arr_key);
var_Arr[key] = {};
var_Arr[key].value = val.value;
//--------------
const replace_value_in_string = async function (retP, fieldIdP) {
if (iterate_info?.iterator_key === fieldIdP || iterate_info?.iterator_val === fieldIdP) {
if (iterate_info.iterator_key === fieldIdP) {
retP.value = iterate_info._key;
}
if (iterate_info.iterator_val === fieldIdP) {
retP.value = iterate_info._val;
}
}
const set_value = function (valP) {
if (typeof valP !== 'undefined') {
var_Arr[key].value = valP;
if (typeof valP === 'string') var_Arr[key].type = 'string';
} else {
if (retP.type === 'object') {
var_Arr[key].value = '';
var_Arr[key].type = 'string';
}
}
};
if (sourceP === 'exp' && retP.type !== 'exp') {
var_Arr[key].type = retP.type;
return;
}
if (typeof retP.value !== 'undefined') {
var_Arr[key].type = retP.type;
var_Arr[key].value = typeof retP.value === 'string' && !retP.value.includes('<svg xmlns=') && retP.value.indexOf('\\') === -1 && !['UI Attr EXP', 'update'].includes(sourceP) ? retP.value.replaceAll('"', '\\"') : retP.value; // new Apr 6 2025 fixing "\"how much?\"" // new Jul 29 25 to fix quil extra "\" " source!=="UI Attr EXP"
if ((val.value.indexOf('[') > -1) | (val.value.indexOf('.') > -1)) {
//get values from array '@var==="sss" && @var_B==="sss" && @obj.property===5 && @objA["value"]===123 | @objB["value"].property===1234'
var data = retP.prop;
if (retP.type === 'object') data = retP.value;
var property1, property2;
//check for split situation: @objB[@var].property 1: @objB[ 2:@var].property
if (val.value.indexOf('[') === -1 && val.value.indexOf(']') > -1 && val.value.substr(0, 1) === '@') {
//check situation 2
var prevData = var_Arr[key - 1].value;
var_Arr[key].value = prevData[data]; // @objB[@var]
if (val.value.indexOf('.') > -1) {
const props_split = await func.expression.get_property(val.value);
property2 = props_split.property2;
if (prevData[data]) set_value(prevData[data][property2]);
// var_Arr[key].value = prevData[data][property2]; //@objB[@var].property
}
delete var_Arr[key - 1];
} else {
const props = await func.expression.get_property(val.value);
property1 = props.property1;
property2 = props.property2;
if (property1) {
var_Arr[key].value = data[property1]; // @var["value"] or @var.property
if (property2) {
if (data[property1]) set_value(data[property1][property2]);
}
}
if (property2 && !property1) {
if (
data //data[property2]
) {
set_value(data[property2]);
}
}
}
fields[fieldIdP] = var_Arr[key].value; // added 051017 to allow @SYS_GLOBAL_OBJ_WIDGET_INFO.doc_id
var_Arr[key].fieldId = fieldIdP;
} else {
fields[fieldIdP] = var_Arr[key].value; // update flat no warpers
var_Arr[key].fieldId = fieldIdP;
}
}
};
//>>>>>>>>>>>>>>>>>>
//>>>> start here >>
//>>>>>>>>>>>>>>>>>>
if (val.fieldId) {
// @_THIS
if (val.fieldId && val.fieldId.substr(0, 5) === '_THIS' && calling_fieldIdP && (val.fieldId.length === 5 || (val.fieldId.length > 5 && val.fieldId.substr(5, 1) === '.'))) {
if (val.fieldId.length === 5) val.fieldId = calling_fieldIdP;
else val.fieldId = calling_fieldIdP + val.fieldId(5, val.fieldId.length - 1);
}
if (!sourceP === 'exp') {
var_Arr[key].value = '""';
} // put default
fields[val.fieldId] = var_Arr[key].value;
const ret = get_iterate_value_ret(val.fieldId) || (await func.datasource.get_value(SESSION_ID, val.fieldId, dsSessionP, rowIdP)); // find field in dataSources
await replace_value_in_string(ret.ret, ret.fieldIdP);
}
}
try {
// eval the expression
var res = [];
var exp_exist;
var var_error_found;
// merge arr values
var_Arr.forEach(function (val, key) {
if (sourceP === 'UI Property EXP') {
let ret = func.utils.get_drive_url(SESSION_ID, val.value, true);
if (ret.changed) {
res[key] = ret.value;
return true;
}
}
if (sourceP === 'UI Attr EXP') {
let ret = func.utils.get_drive_url(SESSION_ID, val.value, var_Arr.length == 1 ? false : true);
if (ret.changed) {
res[key] = ret.value;
return true;
}
}
if (val.type === 'exp') {
exp_exist = true;
}
res[key] = val.value;
if (var_Arr.length > 1) {
// complex input
if (!['DbQuery', 'alert', 'exp', 'api_rendered_output'].includes(sourceP) && ['string', 'date'].includes(val.type)) {
res[key] = '`' + val.value + '`';
}
// new Dec 18 2024 for Ishai // json,html,xml,text,css
if (['api_rendered_output'].includes(sourceP) && ['json'].includes(api_output_type) && ['string', 'date'].includes(val.type)) {
res[key] = `"` + val.value + `"`;
}
}
if (val.fieldId && val.value && typeof val.value === 'string') {
if (['query', 'condition', 'range', 'sort', 'locate'].includes(sourceP)) {
if (val.value.indexOf('↵') > -1) {
res[key] = val.value.split('↵').join('');
}
res[key] = res[key].replace(/(\r\n|\n|\r)/gm, ''); //.replace(/"/g,'\"');//.replace(/'/g,"");
}
if (['init', 'update', 'virtual'].includes(sourceP)) {
if (val.value.indexOf('↵') > -1) res[key] = val.value.split('↵').join('\n');
res[key] = res[key].replace(/(\r\n|\n|\r)/gm, '\\n');
}
if (typeof IS_PROCESS_SERVER !== 'undefined') {
res[key] = res[key].replace(/(\r\n|\n|\r)/gm, '<br>');
}
fields[val.fieldId] = res[key];
}
// extract object
if (typeof val.value === 'object' && var_Arr.length > 1) {
const _paren = !Array.isArray(val.value) && !var_Arr[key + 1].value?.includes('.');
let _slotted = false;
if (glb.XU_PERF && sourceP === 'UI Attr EXP') {
// slot-ify: clone preserves the legacy parse-of-stringify isolation
try {
const _snap = val.value === null ? null : func.expression.get_slot_clone(val.value);
xu_slot_values = xu_slot_values || [];
xu_slot_positions = xu_slot_positions || [];
const _slot = xu_slot_values.length;
xu_slot_values.push(_snap);
xu_slot_positions.push({ key: key, slot: _slot, paren: _paren });
res[key] = _paren ? '(__xu_v[' + _slot + '])' : '__xu_v[' + _slot + ']';
_slotted = true;
} catch (clone_err) {
_slotted = false;
}
}
if (!_slotted) {
if (_paren) {
// prevent cast on single value expression
res[key] = '(' + JSON.stringify(val.value) + ')';
} else {
res[key] = JSON.stringify(val.value);
}
}
}
if (!exp_exist && sourceP !== 'exp' && val.value && typeof val.value === 'string' && val.value.substr(0, 1) === '@') {
warning = 'Error encoding ' + val.value;
var_error_found = true;
res[key] = 0;
}
});
const join = function (arrP) {
return arrP.join('');
};
var exp = undefined;
if (exp_exist && sourceP !== 'exp') {
// the recursive pass has no access to this call's slot array, so
// materialize slots back into legacy JSON text before recursing
if (xu_slot_values && xu_slot_positions) {
for (let sp = 0; sp < xu_slot_positions.length; sp++) {
const p = xu_slot_positions[sp];
const txt = JSON.stringify(xu_slot_values[p.slot]);
res[p.key] = p.paren ? '(' + txt + ')' : txt;
}
xu_slot_values = null;
xu_slot_positions = null;
}
exp = await func.expression.get(SESSION_ID, join(res), dsSessionP, sourceP, rowIdP, sourceActionP, true, calling_fieldIdP, fields, debug_infoP);
if (exp.res) res = exp.res;
// do second pass when exp exist
else res = [exp.result];
fields = Object.assign(exp.fields, fieldsP);
}
var result = join(res);
if (res.length === 1) {
// bypass join for single value expression
result = res[0];
}
if (secondPassP) {
ret = result;
} else if (sourceP !== 'exp') {
// no eval for second pass
// return single value
if (res.length === 1 && typeof res[0] === 'string' && typeof res[0] !== 'object') {
// avoid eval when query leading zeros problem
ret = join(res);
if (ret && ret.substr(0, 1) === '@') {
error = 'Error encoding @ var';
var_error_found = true;
}
} else {
if (
![
'arguments',
// "alert",
'api_rendered_output',
'DbQuery',
].includes(sourceP)
) {
ret = await func.expression.secure_eval(SESSION_ID, sourceP, result, jobNo, dsSessionP, js_script_callback, null, undefined, xu_slot_values);
} else {
if (sourceP === 'DbQuery') {
ret = JSON.stringify(evalJson(result));
} else {
// try eval
ret = result;
}
}
}
}
// console.log("AAAA")
return end_results();
} catch (err) {
ret = result; // skip eval on error
error = err.message;
return end_results();
}
}
}
const new_class = new xu_class();
return new_class.get();
};
// func.expression.get_bad1 = async function (SESSION_ID, valP, dsSessionP, sourceP, rowIdP, sourceActionP, secondPassP, calling_fieldIdP, fieldsP = {}, debug_infoP, iterate_info, js_script_callback, jobNo, api_output_type) {
// const evalJson = (text) => eval(`(${text})`);
// const replaceQuotes = (str) => {
// for (const [key, val] of Object.entries(fields)) {
// if (typeof val === 'string') str = str.replace(`"${val}"`, val.replace(/"/g, ''));
// }
// return str;
// };
// let ret, error, warning, var_error_found;
// const fields = { ...fieldsP };
// // Initial value processing
// if (valP === null || typeof valP === 'undefined') ret = '';
// else if (typeof valP === 'boolean') ret = valP ? 'Y' : 'N';
// else ret = valP.toString();
// ret = ret.replace(/\&/g, '&');
// ret = func.utils.replace_studio_drive_url(SESSION_ID, ret);
// // End results helper
// const endResults = () => {
// if (['update', 'javascript'].includes(sourceP) && typeof ret === 'string') {
// ret = replaceQuotes(ret);
// }
// if ((error || warning) && SESSION_OBJ[SESSION_ID]?.DS_GLB[dsSessionP]) {
// func.utils.debug.log(SESSION_ID, SESSION_OBJ[SESSION_ID].DS_GLB[dsSessionP].nodeId, {
// module: 'expression',
// action: sourceP,
// source: calling_fieldIdP,
// prop: ret,
// details: ret,
// result: ret,
// error,
// warning,
// fields: null,
// type: 'exp',
// prog_id: SESSION_OBJ[SESSION_ID].DS_GLB[dsSessionP].prog_id,
// debug_info: debug_infoP,
// });
// }
// return { result: ret, fields, error, warning, req: valP, var_error_found };
// };
// // Handle non-variable cases
// const handleNonVariable = async () => {
// try {
// if (sourceP !== 'arguments') {
// if (ret.startsWith('_DATE_')) ret = ret.slice(6);
// else if (/^\d{4}-\d{2}-\d{2}$/.test(ret) || ret === 'self') return endResults();
// else ret = await func.expression.secure_eval(SESSION_ID, sourceP, ret, jobNo, dsSessionP, js_script_callback);
// } else {
// ret = ret.replace(/_NULL/gi, '');
// }
// return endResults();
// } catch (err) {
// error = err.message;
// return endResults();
// }
// };
// // Early return for simple cases
// if (!func.expression.validate_variables(valP)) return await handleNonVariable();
// if (glb.emailRegex.test(await func.expression.secure_eval(SESSION_ID, sourceP, valP, jobNo, dsSessionP, js_script_callback))) {
// return await handleNonVariable();
// }
// // Parse and process variables
// const split = func.expression.parse(ret) || [];
// const var_Arr = await Promise.all(
// split.map(async (val, key) => {
// const result = { value: val.value, fieldId: val.fieldId };
// if (!val.fieldId) return result;
// // Handle _THIS substitution
// if (val.fieldId.startsWith('_THIS') && calling_fieldIdP) {
// result.fieldId = val.fieldId.length === 5 ? calling_fieldIdP : calling_fieldIdP + val.fieldId.slice(5);
// }
// // Fetch value from datasource
// const { ret: fetchedValue, fieldIdP } = await func.datasource.get_value(SESSION_ID, result.fieldId, dsSessionP, rowIdP);
// result.value = fetchedValue?.value ?? (sourceP === 'exp' ? fetchedValue?.value : '""');
// result.type = fetchedValue?.type;
// // Handle iteration
// if (iterate_info) {
// if (iterate_info.iterator_key === fieldIdP) result.value = iterate_info._key;
// if (iterate_info.iterator_val === fieldIdP) result.value = iterate_info._val;
// }
// // Process nested properties
// if (val.value.includes('[') || val.value.includes('.')) {
// const { property1, property2 } = await func.expression.get_property(val.value);
// const data = fetchedValue?.type === 'object' ? fetchedValue.value : fetchedValue?.prop;
// if (key > 0 && val.value.includes(']') && !val.value.includes('[') && split[key - 1].value) {
// const prevData = split[key - 1].value;
// result.value = prevData[fieldIdP];
// if (val.value.includes('.') && prevData[fieldIdP]) {
// result.value = prevData[fieldIdP][property2] ?? '';
// }
// } else if (data) {
// if (property1) result.value = data[property1] ?? '';
// if (property2) result.value = (property1 ? data[property1]?.[property2] : data[property2]) ?? '';
// }
// }
// fields[fieldIdP] = result.value;
// return result;
// }),
// );
// // Final evaluation
// try {
// const res = var_Arr.map((val, key) => {
// if (sourceP === 'UI Property EXP' || sourceP === 'UI Attr EXP') {
// const { changed, value } = func.utils.get_drive_url(SESSION_ID, val.value, sourceP === 'UI Attr EXP' && var_Arr.length > 1);
// if (changed) return value;
// }
// let value = val.value;
// if (var_Arr.length > 1) {
// if (!['DbQuery', 'alert', 'exp', 'api_rendered_output'].includes(sourceP) && ['string', 'date'].includes(val.type)) {
// value = `\`${value}\``;
// } else if (sourceP === 'api_rendered_output' && api_output_type === 'json' && ['string', 'date'].includes(val.type)) {
// value = `"${value}"`;
// }
// }
// if (val.fieldId && typeof value === 'string') {
// if (['query', 'condition', 'range', 'sort', 'locate'].includes(sourceP)) value = value.replace(/↵|\r\n|\n|\r/g, '');
// if (['init', 'update', 'virtual'].includes(sourceP)) value = value.replace(/↵|\r\n|\n|\r/g, '\\n');
// if (typeof IS_PROCESS_SERVER !== 'undefined') value = value.replace(/↵|\r\n|\n|\r/g, '<br>');
// fields[val.fieldId] = value;
// }
// if (typeof value === 'object' && var_Arr.length > 1) {
// value = Array.isArray(value) || var_Arr[key + 1]?.value?.includes('.') ? JSON.stringify(value) : `(${JSON.stringify(value)})`;
// }
// if (!val.type === 'exp' && sourceP !== 'exp' && typeof value === 'string' && value.startsWith('@')) {
// warning = `Error encoding ${value}`;
// var_error_found = true;
// return '0';
// }
// return value;
// });
// ret = res.length === 1 ? res[0] : res.join('');
// if (var_Arr.some((v) => v.type === 'exp') && sourceP !== 'exp' && !secondPassP) {
// const exp = await func.expression.get(SESSION_ID, ret, dsSessionP, sourceP, rowIdP, sourceActionP, true, calling_fieldIdP, fields, debug_infoP);
// ret = exp.res?.[0] ?? exp.result;
// Object.assign(fields, exp.fields);
// } else if (!secondPassP && !['arguments', 'api_rendered_output', 'DbQuery'].includes(sourceP)) {
// ret = await func.expression.secure_eval(SESSION_ID, sourceP, ret, jobNo, dsSessionP, js_script_callback);
// } else if (sourceP === 'DbQuery') {
// ret = JSON.stringify(evalJson(ret));
// }
// if (typeof ret === 'string' && ret.startsWith('@')) {
// error = 'Error encoding @ var';
// var_error_found = true;
// }
// } catch (err) {
// error = err.message;
// }
// return endResults();
// };
// func.expression.parse_org = function (strP) {
// var extract_str = function (strP, posP) {
// if (!posP) posP = 0;
// var clean_split_str = function (arrP) {
// var arr = [];
// if (arrP && arrP.length > 1 && arrP[0] === '' && arrP[1].indexOf('@') > -1) {
// for (var i = 1; i <= arrP.length; i++) {
// arr.push(arrP[i]);
// }
// return arr;
// } else return arrP;
// };
// var nonLettersPatt = /\W/; // non letters
// var validSymbolsNoArray = /[^.@\[]/; //valid symbols no array /[^.@\[\]\]]/
// var validSymbolsWithArray = /[^.@"'\[\]]/; //valid symbols with array
// var validSymbols = validSymbolsNoArray;
// var splitTmp = strP.replace(/@/g, '^^@').split('^^');
// var split = clean_split_str(splitTmp);
// var obj = [];
// if (split) {
// for (let val of split) {
// // run on @ segments
// if (val) {
// var pos = strP.indexOf(val);
// if (val && val.substr(0, 1) === '@') {
// var tmpStr = '';
// var word_start_pos = undefined;
// var word_end_pos = undefined;
// // run on @ segment string
// for (var i = 0; i <= val.length; i++) {
// var key1 = i;
// var val1 = val.substr(i, 1);
// if (
// val1 === '.' &&
// !word_start_pos // find first dot
// )
// word_start_pos = key1;
// if (
// word_start_pos &&
// key1 > word_start_pos &&
// nonLettersPatt.test(val1) // find any sign character to mark the end of word
// )
// word_end_pos = key1;
// if (word_start_pos && word_start_pos >= 0 && word_end_pos && word_end_pos >= 0) {
// // find the word
// var word = val.substr(word_start_pos + 1, word_end_pos - word_start_pos - 1); // get the word
// // if (glb.ALL_PROPERTIES_ARR.indexOf(word) === -1) {
// // compare with internal properties
// tmpStr = tmpStr.substr(0, word_start_pos) + '^^' + tmpStr.substr(word_start_pos, word_end_pos);
// // }
// if (val.substr(word_end_pos, 1) === '.') word_start_pos = word_end_pos;
// else word_start_pos = null;
// word_end_pos = null;
// }
// if (val1 === '[') validSymbols = validSymbolsWithArray;
// if (nonLettersPatt.test(val1) && validSymbols.test(val1) && tmpStr.indexOf('^^') === -1) {
// tmpStr += '^^' + val1;
// } else tmpStr += val1;
// }
// // });
// if (tmpStr.indexOf('^^') > -1) {
// var obj1 = extract_str(tmpStr, pos);
// obj = obj.concat(obj1);
// } else {
// // push clean @var
// var fieldId = undefined;
// if (val) {
// fieldId = val.substr(1, val.length);
// if (val.indexOf('.') > -1) fieldId = val.substr(1, val.indexOf('.') - 1);
// if (val.indexOf('[') > -1) fieldId = val.substr(1, val.indexOf('[') - 1);
// //
// // if (val.indexOf("]") > -1)
// // fieldId = val.substr(1, val.indexOf("]") - 1);
// }
// obj.push({
// value: val,
// fieldId: fieldId,
// pos: pos + posP,
// });
// }
// } else {
// obj.push({
// value: val,
// pos: pos + posP,
// });
// }
// }
// }
// return obj;
// }
// };
// var res = extract_str(strP);
// return res;
// };
func.expression._parse_cache = new Map();
func.expression.parse = function (input) {
if (typeof input !== 'string') return [];
if (func.expression._parse_cache.has(input)) {
return func.expression._parse_cache.get(input).map(function (s) { return Object.assign({}, s); });
}
const segments = [];
let pos = 0;
const parts = input.split(/(@\w+)/).filter(Boolean);
for (const part of parts) {
if (part.startsWith('@')) {
const fieldId = part.slice(1);
segments.push({
value: part,
fieldId,
pos,
});
} else {
segments.push({
value: part,
pos,
});
}
pos += part.length;
}
// Evict oldest entry if cache exceeds limit
if (func.expression._parse_cache.size >= 500) {
const firstKey = func.expression._parse_cache.keys().next().value;
func.expression._parse_cache.delete(firstKey);
}
func.expression._parse_cache.set(input, segments);
return segments.map(function (s) { return Object.assign({}, s); });
};
func.expression.get_property = async function (valP) {
async function secure_eval(val) {
if (typeof IS_PROCESS_SERVER === 'undefined') {
try {
return eval(val);
} catch (err) {
console.error(err);
return;
}
}
try {
let vm = new VM({
sandbox: {
func: func,
SESSION_ID: SESSION_ID,
SESSION_OBJ: { [`${SESSION_ID}`]: SESSION_OBJ[SESSION_ID] },
},
timeout: 1000,
allowAsync: false,
});
return await vm.run(val);
} catch (err) {
throw err;
}
}
var property1, property2;
if (valP.indexOf('[') > -1 && valP.indexOf(']') > -1) {
property1 = valP.substr(valP.indexOf('[') + 1, valP.indexOf(']') - valP.indexOf('[') - 1); // get []
property1 = await secure_eval(property1);
}
if (valP.indexOf('.') > -1) property2 = valP.substr(valP.indexOf('.') + 1, valP.length); // get .
return {
property1: property1,
property2: property2,
};
};
// func.expression.get_property_bad = async function (valP) {
// if (typeof valP !== 'string') return { property1: undefined, property2: undefined };
// const secureEval = async (expr) => {
// if (typeof IS_PROCESS_SERVER === 'undefined') {
// try {
// return eval(expr);
// } catch (err) {
// console.error(err);
// return undefined;
// }
// }
// try {
// const vm = new VM.VM({
// sandbox: {
// func,
// SESSION_ID,
// SESSION_OBJ: { [SESSION_ID]: SESSION_OBJ[SESSION_ID] },
// },
// timeout: 1000,
// allowAsync: false,
// });
// return await vm.run(expr);
// } catch {
// return undefined; // Simplified error handling
// }
// };
// let property1, property2;
// const bracketStart = valP.indexOf('[');
// const bracketEnd = valP.indexOf(']');
// if (bracketStart > -1 && bracketEnd > bracketStart) {
// const expr = valP.slice(bracketStart + 1, bracketEnd);
// property1 = await secureEval(expr);
// }
// const dotIndex = valP.indexOf('.');
// if (dotIndex > -1) {
// property2 = valP.slice(dotIndex + 1);
// }
// return { property1, property2 };
// };
func.expression.validate_constant = function (valP) {
var patt = /["']/;
if (typeof valP === 'string' && patt.test(valP.substr(0, 1)) && patt.test(valP.substr(0, valP.length - 1))) return true;
else return false;
};
func.expression.validate_variables = function (valP) {
if (typeof valP === 'string' && valP.indexOf('@') > -1) return true;
else return false;
};
func.expression.remove_quotes = function (valP) {
if (func.expression.validate_constant(valP)) return valP.substr(1, valP.length - 2);
else return valP;
};
// func.expression.validate_constant = function (valP) {
// typeof valP === 'string' && /^["'].*["']$/.test(valP);
// };
// func.expression.validate_variables = function (valP) {
// typeof valP === 'string' && valP.includes('@');
// };
// func.expression.remove_quotes = function (valP) {
// func.expression.validate_constant(valP) && typeof valP === 'string' ? valP.slice(1, -1) : valP;
// };
// func.expression.secure_eval_org = async function (SESSION_ID, sourceP, val, job_id, dsSessionP, js_script_callback, evt) {
// const api_utils = await func.common.get_module(SESSION_ID, 'xuda-api-library.mjs', {
// func,
// glb,
// SESSION_OBJ,
// SESSION_ID,
// APP_OBJ,
// dsSession: dsSessionP,
// job_id,
// });
// const xu = api_utils;
// if (typeof IS_PROCESS_SERVER === 'undefined' && typeof IS_DOCKER === 'undefined') {
// try {
// return eval(val);
// } catch (err) {
// try {
// return JSON5.parse(val);
// } catch (err) {
// // console.error(err);
// return val;
// }
// }
// }
// // server side execution
// if (sourceP === 'javascript') {
// process.on('uncaughtException', (err) => {
// console.error('Asynchronous error caught.', err);
// func.events.delete_job(SESSION_ID, job_id);
// if (typeof IS_PROCESS_SERVER !== 'undefined' || typeof IS_DOCKER !== 'undefined') {
// if (SESSION_OBJ[SESSION_ID].crawler) return;
// return __.rpi.write_log(SESSION_OBJ[SESSION_ID].app_id, 'error', 'worker', 'vm error', err, null, val, 'func.expression.get.secure_eval');
// }
// });
// try {
// const dir = path.join(_conf.studio_drive_path, SESSION_OBJ[SESSION_ID].app_id, 'node_modules', '/');
// const script = new VM.VMScript(`try{${val}}catch(e){func.api.error(SESSION_ID, "nodejs error", e); console.error(e); func.events.delete_job(SESSION_ID, job_id);}`, { filename: dir, dirname: dir });
// let vm = new VM.NodeVM({
// require: {
// external: true,
// },
// sandbox: {
// func,
// xu,
// SESSION_ID,
// SESSION_OBJ: { [`${SESSION_ID}`]: SESSION_OBJ[SESSION_ID] },
// callback: js_script_callback,
// job_id,
// axios,
// got,
// FormData,
// },
// timeout: 60000,
// });
// return await vm.run(script, {
// filename: dir,
// dirname: dir,
// });
// } catch (err) {
// console.error('Failed to execute script.', err);
// if (typeof IS_PROCESS_SERVER !== 'undefined') {
// func.events.delete_job(SESSION_ID, jobNo);
// return __.db.add_error_log(SESSION_OBJ[SESSION_ID].app_id, 'api', err);
// }
// }
// } else {
// try {
// try {
// let vm = new VM.VM({
// sandbox: {
// xu,
// func,
// SESSION_ID,
// SESSION_OBJ: { [`${SESSION_ID}`]: SESSION_OBJ[SESSION_ID] },
// callback: js_script_callback,
// job_id,
// },
// timeout: 1000,
// allowAsync: false,
// });
// let ret = val;
// if (typeof val === 'string') {
// ret = await vm.run(val);
// }
// return ret;
// } catch (err) {
// throw '';
// }
// } catch (err) {
// try {
// return JSON5.parse(val);
// } catch (err) {
// // console.error(err);
// return val;
// }
// }
// }
// };
// One clone per object per update epoch: many attribute expressions binding
// the same large object (e.g. a whole tree field) would otherwise re-clone it
// per evaluation. datasource.update clears the cache, so expressions never see
// values from before the mutation that triggered their refresh.
func.expression.get_slot_clone = function (v) {
const cache = (func.expression._slot_clone_cache = func.expression._slot_clone_cache || new WeakMap());
let c = cache.get(v);
if (typeof c === 'undefined') {
c = structuredClone(v);
cache.set(v, c);
}
return c;
};
func.expression.secure_eval = async function (SESSION_ID, sourceP, val, job_id, dsSessionP, js_script_callback, evt, ignore_errors, xu_values) {
if (typeof val !== 'string') return val;
const xu = await func.common.get_module(SESSION_ID, 'xuda-api-library.mjs', {
func,
glb,
SESSION_OBJ,
SESSION_ID,
APP_OBJ,
dsSession: dsSessionP,
job_id,
});
const isServer = typeof IS_PROCESS_SERVER !== 'undefined' || typeof IS_DOCKER !== 'undefined';
// visible to both the compiled path and the direct eval below
const __xu_v = xu_values;
// Client-side execution
if (!isServer) {
// XU_PERF: compile once per distinct source instead of parsing on every
// eval. Non-expression sources (multi-statement javascript) and sources
// that fail to compile stay on the legacy eval; any runtime error falls
// through to the legacy path so error semantics are unchanged.
if (glb.XU_PERF && sourceP !== 'javascript') {
// compile on the SECOND sighting: repeated sources (row templates) get a
// compiled function, one-off sources (unique per-node paths) stay on
// plain eval and never pay Function-compile cost
const cache = (func.expression._compiled_exp_cache = func.expression._compiled_exp_cache || new Map());
const entry = cache.get(val);
if (typeof entry === 'function') {
try {
return entry(xu, func, glb, SESSION_ID, SESSION_OBJ, dsSessionP, job_id, js_script_callback, evt, __xu_v);
} catch (compiled_err) {
// fall through to the legacy eval below
}
} else if (entry === 1) {
let fn = null;
try {
fn = new Function('xu', 'func', 'glb', 'SESSION_ID', 'SESSION_OBJ', 'dsSessionP', 'job_id', 'js_script_callback', 'evt', '__xu_v', 'return (' + val + '\n);');
} catch (compile_err) {
fn = null; // uncompilable: stays null, legacy eval from here on
}
cache.set(val, fn);
if (fn) {
try {
return fn(xu, func, glb, SESSION_ID, SESSION_OBJ, dsSessionP, job_id, js_script_callback, evt, __xu_v);
} catch (compiled_err) {
// fall through to the legacy eval below
}
}
} else if (typeof entry === 'undefined') {
if (cache.size > 4000) cache.clear();
cache.set(val, 1);
}
}
try {
return eval(val);
} catch (err) {
if (sourceP === 'javascript' && !ignore_errors) {
await func.utils.report_issue(SESSION_ID, {
code: 'RUN_MSG_EXP_010',
source: 'func.expression.secure_eval',
message: 'Execution error',
type: 'E',
err,
details: {
sourceP,
dsSessionP,
job_id,
},
});
}
try {
return JSON5.parse(val);
} catch (json_error) {
return val;
}
}
}
// Server-side execution
const sandbox = {
func,
xu,
SESSION_ID,
SESSION_OBJ: { [SESSION_ID]: SESSION_OBJ[SESSION_ID] },
callback: js_script_callback,
job_id,
...(sourceP === 'javascript' ? { axios, got, FormData } : {}),
};
const handleError = async (err) => {
await func.utils.report_issue(SESSION_ID, {
code: 'RUN_MSG_EXP_010',
source: 'func.expression.secure_eval',
message: 'Execution error',
type: 'E',
err,
details: {
sourceP,
dsSessionP,
job_id,
},
});
func.events.delete_job(SESSION_ID, job_id);
if (isServer && !SESSION_OBJ[SESSION_ID].crawler) {
if (sourceP !== 'javascript') {
__.db.add_error_log(SESSION_OBJ[SESSION_ID].app_id, 'api', err);
}
}
return val; // Fallback to original value
};
if (sourceP === 'javascript') {
process.on('uncaughtException', function (uncaught_error) {
handleError(uncaught_error);
});
try {
const dir = path.join(_conf.studio_drive_path, SESSION_OBJ[SESSION_ID].app_id, 'node_modules');
const script = new VMScript(`try { ${val} } catch (e) { func.api.error(SESSION_ID, "nodejs error", e); throw e; }`, { filename: dir, dirname: dir });
const vm = new NodeVM({
require: { external: true },
sandbox,
timeout: 60000,
});
return await vm.run(script, { filename: dir, dirname: dir });
} catch (err) {
return await handleError(err);
}
}
try {
const vm = new VM({
sandbox,
timeout: 1000,
allowAsync: false,
});
return await vm.run(val);
} catch {
try {
return JSON5.parse(val);
} catch {
return val;
}
}
};
func.events = {};
func.events._debug_summarize_value = function (value) {
if (Array.isArray(value)) {
return {
type: 'array',
length: value.length,
first_keys: value[0] && typeof value[0] === 'object' ? Object.keys(value[0]).slice(0, 8) : [],
};
}
if (value && typeof value === 'object') {
return {
type: 'object',
keys: Object.keys(value).slice(0, 12),
};
}
if (typeof value === 'string') {
return {
type: 'string',
length: value.length,
empty: value.length === 0,
};
}
return {
type: typeof value,
value,
};
};
func.events._debug_summarize_object = function (obj) {
const ret = {};
if (!obj || typeof obj !== 'object') return ret;
for (const [key, value] of Object.entries(obj)) {
ret[key] = func.events._debug_summarize_value(value);
}
return ret;
};
func.events._debug_trace_save_asset = async function (SESSION_ID, label, payload, dsSessionP) {
try {
const fields = {};
for (const field_id of ['files_v', 'view_v', 'wysiwyg_v', 'open_modal_v']) {
try {
const field_ret = await func.datasource.get_value(SESSION_ID, field_id, dsSessionP);
fields[field_id] = {
found: !!field_ret?.found,
dsSessionP: field_ret?.dsSessionP,
currentRecordId: field_ret?.currentRecordId,
value: func.events._debug_summarize_value(field_ret?.ret?.value),
};
} catch (err) {
fields[field_id] = {
error: err?.message || String(err),
};
}
}
globalThis.__XUDA_RT_TRACE && console.log('[xuda-runtime] save_asset_trace ' +
JSON.stringify({
label,
dsSessionP,
...payload,
fields,
}),
);
} catch (err) {
console.warn('[xuda-runtime] save_asset_trace_failed', err);
}
};
func.events.validate = async function (SESSION_ID, triggerP, dsSessionP, eventIdP, sourceP, argumentsP, return_validation_onlyP, event_optionsP) {
var _session = SESSION_OBJ[SESSION_ID];
var _ds = _session.DS_GLB[dsSessionP];
const event_options = event_optionsP && typeof event_optionsP === 'object' ? event_optionsP : {};
var args = {
triggerP,
dsSessionP,
eventIdP,
sourceP,
argumentsP,
return_validation_onlyP,
event_options,
};
const search_event_in_parent_ds = async function () {
if (_ds && typeof _ds.parentDataSourceNo !== 'undefined') {
await func.events.validate(SESSION_ID, triggerP, _ds.parentDataSourceNo, eventIdP, sourceP, argumentsP, return_validation_onlyP, event_options);
}
};
var ret = false;
var jobs = [];
// var success;
if (_ds?.prog_id) {
const _view_obj = await func.utils.VIEWS_OBJ.get(SESSION_ID, _ds.prog_id);
// check view exist
if (!glb.IS_WORKER) _ds.event_stat_obj = {};
if (_view_obj.progEvents) {
if (_session.api_callback && eventIdP) {
_session.api_callback(eventIdP, SESSION_ID, SESSION_OBJ);
}
// check events has rows
for await (let val of _view_obj.progEvents) {
//run events rows
var eventProp = undefined;
if (val.data.type === triggerP) {
// compare event trigger
if ((triggerP !== 'user_defined') | (triggerP === 'user_defined' && eventIdP === val.data.event_name)) {
// compare user defined name
var expCond;
if (val.data.condition) expCond = await func.expression.get(SESSION_ID, val.data.condition, dsSessionP, 'condition');
if (!val.data.condition || expCond.result) {
func.utils.debug.watch(SESSION_ID, _ds.prog_id + '%' + val.id, 'view_event', val, triggerP + ' ' + eventIdP, expCond);
ret = true;
if (return_validation_onlyP) break;
const set_arguments = async function () {
var args = argumentsP || {};
// for await (let [key, fieldId] of Object.entries(
// val.data.parameters
// )) {
// const field_info = func.common.find_item_by_key(
// _view_obj.progFields,
// "field_id",
// fieldId
// );
// var value = await func.common.get_cast_val(
// SESSION_ID,
// "events",
// fieldId,
// field_info.props.fieldType,
// args[fieldId]
// );
// const ret = await func.datasource.get_value(
// SESSION_ID,
// fieldId,
// dsSessionP,
// _ds.currentRecordId
// );
// const datasource_changes = {
// [ret.dsSessionP]: {
// [ret.currentRecordId]: { [fieldId]: value },
// },
// };
// await func.datasource.update(SESSION_ID, datasource_changes);
// }
for await (let [key, fieldId] of Object.entries(val.data.parameters)) {
const field_info = func.common.find_item_by_key(_view_obj.progFields, 'field_id', fieldId);
if (field_info?.data?.type !== 'virtual') {
console.warn('parameter field must be virtual, update ignored');
continue;
}
if (!args[fieldId]) continue;
let value = await func.common.get_cast_val(SESSION_ID, 'events', fieldId, field_info.props.fieldType, args[fieldId].value);
if (!xu_isEmpty(args[fieldId].fx)) {
const fx_ret = await func.expression.get(SESSION_ID, args[fieldId].fx, dsSessionP, 'update');
value = fx_ret.result;
}
// find the target field in the program dataset
const ret = await func.datasource.get_value(SESSION_ID, fieldId, dsSessionP, _ds.currentRecordId);
const datasource_changes = {
[ret.dsSessionP]: {
[ret.currentRecordId]: { [fieldId]: value },
},
};
await func.datasource.update(SESSION_ID, datasource_changes, null, event_options.avoid_refresh === true);
}
await add_event();
};
const add_event = async function () {
const _event = func.common.find_item_by_key_root(_view_obj.progEvents, 'id', val.id);
if (_event.workflow) {
// check if event property exist
if (!_event.workflow || xu_isEmpty(_event.workflow)) return;
// check events has rows
for (const trigger_obj of _event.workflow) {
//run events rows
if (!trigger_obj.data.action) continue;
if (!trigger_obj.data.enabled) continue;
// condition ok
var callingEventId = val.data.event_name;
if (!callingEventId) callingEventId = val.id; // default event id when event name is missing
// eventProp = trigger_obj;
// success = true;
const ref_id = trigger_obj.data.name;
var container = undefined;
var screen_prop = undefined;
if (!glb.IS_WORKER) {
if (_ds.panel_div_id) {
try {
container = '#' + _ds.panel_div_id;
const panel_meta = func.runtime.ui.get_meta_by_element_id(_ds.panel_div_id);
if (panel_meta?.xuData?.panel_info) {
screen_prop = panel_meta.xuData.panel_info.paramsP;
} else {
///////////////
container = '#' + _session.DS_GLB[dsSessionP].screenId;
const screen_meta = func.runtime.ui.get_meta_by_element_id(_session.DS_GLB[dsSessionP].screenId);
if (screen_meta?.xuData) {
screen_prop = screen_meta.xuData.paramsP;
}
if (!screen_meta) {
container = '#' + _session.DS_GLB[dsSessionP].containerId;
}
//////////////
}
} catch (e) {
console.error(e);
}
} else {
container = '#' + _ds.screenId;
const screen_meta = func.runtime.ui.get_meta_by_element_id(_ds.screenId);
if (screen_meta?.xuData) {
screen_prop = screen_meta.xuData.paramsP;
}
if (!screen_meta) {
container = '#' + _ds.containerId;
}
}
} else {
screen_prop = {
callingContainerP: _ds.containerId,
};
}
jobs.push(
await func.events.add_to_queue(
SESSION_ID,
sourceP + ' event',
trigger_obj.id,
null, // was click
trigger_obj.data.action,
ref_id,
container,
null,
_ds.currentRecordId,
null,
trigger_obj.data.name,
null,
null,
dsSessionP,
null,
null,
trigger_obj,
triggerP,
screen_prop,
null, // was target frame id
null,
trigger_obj,
trigger_obj.data.parameter_source_data,
val.id,
null,
args,
null,
null,
event_options,
),
);
}
}
};
if (val.data.parameters) {
await set_arguments();
} else {
await add_event();
}
} else {
if (val.data.condition && !expCond.result) {
func.utils.debug.watch(SESSION_ID, _ds.prog_id + '%' + val.id, 'view_event', val, triggerP + ' ' + eventIdP, expCond, true);
}
}
}
}
}
}
}
if (return_validation_onlyP) return ret;
if (!ret) await search_event_in_parent_ds();
return jobs;
};
func.events.add_to_queue = async function (
SESSION_ID,
typeP,
eventIdP,
triggerP,
functionP,
refIdP,
containerP,
elementP,
rowP,
evt,
descP,
NA_rootScreenIdP,
NA_callingEventIdP,
dsSessionP,
NA_isInitP,
NA_calling_program,
event_propertiesP,
calling_triggerP,
paramsP,
NA_target_frame_idP,
_NA2,
calling_trigger_prop,
argumentsP,
source_event_idP,
calling_job,
args,
$div,
$container,
event_optionsP,
) {
var _session = SESSION_OBJ[SESSION_ID];
var obj = {
SESSION_ID,
typeP,
eventIdP,
triggerP,
functionP,
refIdP,
containerP,
elementP,
rowP,
descP,
dsSessionP,
event_propertiesP,
calling_triggerP,
paramsP,
calling_trigger_prop,
argumentsP,
source_event_idP,
calling_job,
args,
$div,
$container,
event_optionsP,
evt,
job_num: _session.WORKER_OBJ.num,
};
var _ds = _session.DS_GLB[dsSessionP];
if (!_ds) return;
if (typeof dsSessionP !== 'undefined' && dsSessionP !== null) {
obj.prog_id = _ds.prog_id;
obj.parentDataSourceNo = _ds.parentDataSourceNo;
obj.nodeId = _ds.nodeId;
}
///////
if (glb.IS_WORKER && func.utils.is_onscreen_event(functionP)) {
obj.client = true;
if (functionP === 'call_library') {
obj.client = false;
}
if (typeof dsSessionP !== 'undefined' && dsSessionP !== null) {
obj.ds_obj = func.utils.clean_returned_datasource(SESSION_ID, dsSessionP);
}
if (obj.client) {
_session.WORKER_OBJ.num++;
// if (!_session.IS_API)
func.utils.post_back_to_client(SESSION_ID, 'job', _session.worker_id, obj);
return;
}
}
////////
if (calling_job) {
var job_index = func.events.find_job_index(SESSION_ID, calling_job);
try {
if (!_session.WORKER_OBJ.jobs[job_index].splice_count) {
_session.WORKER_OBJ.jobs[job_index].splice_count = 0;
}
_session.WORKER_OBJ.jobs[job_index].splice_count++;
_session.WORKER_OBJ.jobs.splice(job_index + _session.WORKER_OBJ.jobs[job_index].splice_count, 0, obj);
// }
} catch (e) {
console.error('bug');
// _session.WORKER_OBJ.jobs.splice(0, 0, obj);
}
} else {
_session.WORKER_OBJ.jobs.push(obj);
}
_session.WORKER_OBJ.num++;
return _session.WORKER_OBJ.num - 1;
};
func.events.find_job_index = function (SESSION_ID, jobNoP) {
var _session = SESSION_OBJ[SESSION_ID];
var ret = null;
if (!_session.WORKER_OBJ) return ret;
for (const [key, val] of Object.entries(_session.WORKER_OBJ.jobs)) {
if (val && val.job_num == jobNoP) {
ret = key;
break;
}
}
return ret;
};
func.events.execute = async function (
SESSION_ID,
jobNoP,
eventIdP,
triggerP,
functionP,
refIdP,
containerP,
elementP,
rowP,
evt,
descP,
rootScreenIdP,
dsSessionP,
NA_callingEventIdP,
callingSourceP,
NA_isInitP,
event_propertiesP,
calling_triggerP,
calling_jobP,
paramsP,
NA_target_frame_idP,
calling_trigger_prop,
NA_calling_program,
argumentsP,
NA_viewIdP,
NA_nodeIdP,
NA_parentDataSourceNoP,
$div,
event_optionsP,
) {
var _session = SESSION_OBJ[SESSION_ID];
var _ds = _session.DS_GLB[dsSessionP];
const event_options = event_optionsP && typeof event_optionsP === 'object' ? event_optionsP : {};
const avoid_event_refresh = event_options.avoid_refresh === true;
if (functionP === 'update') refIdP = null; // in case of left over when program changing from call function to update
var job_index = func.events.find_job_index(SESSION_ID, jobNoP);
if (_session.WORKER_OBJ.jobs?.[job_index]?.stat === 'busy') {
if (jobNoP) _session.WORKER_OBJ.stat = job_index;
return;
}
if (jobNoP && !_session.WORKER_OBJ.jobs[job_index]) {
_session.WORKER_OBJ.stat = null;
return;
}
if (jobNoP) _session.WORKER_OBJ.stat = job_index;
if (jobNoP && calling_trigger_prop?.props?.async) {
func.events.delete_job(SESSION_ID, jobNoP);
_session.WORKER_OBJ.stat = null;
}
if (_session.WORKER_OBJ.jobs[job_index]) {
_session.WORKER_OBJ.jobs[job_index].stat = 'busy';
}
var dsSession = dsSessionP; // new 2020420
var field_elm = elementP;
var calling_field_id = field_elm;
if (field_elm && typeof field_elm === 'object') calling_field_id = func.runtime.ui.get_attr(field_elm, 'xu-ui-id');
var log_nodeId;
var log_prog_id;
var log_source;
if (_session.DS_GLB[dsSession]?.prog_id) log_prog_id = _session.DS_GLB[dsSession].prog_id;
log_nodeId = log_prog_id + '_' + eventIdP;
var log_prop = callingSourceP;
if (callingSourceP === 'system event') {
log_prop = 'global event';
}
if (calling_field_id) {
const _view_obj = await func.utils.VIEWS_OBJ.get(SESSION_ID, _ds.prog_id);
let _field_obj = func.common.find_item_by_key(_view_obj.progFields, 'field_id', calling_field_id);
log_nodeId = log_prog_id + '_' + eventIdP + '_' + _field_obj?.id;
log_source = calling_field_id;
}
if (elementP) {
log_prop = triggerP;
log_nodeId = log_nodeId + '_ui_prop'; //+"_"+eventIdP;
}
//check condition
var expCond;
if (event_propertiesP) {
// conditional event
if (event_propertiesP?.props?.condition) {
expCond = await func.expression.get(SESSION_ID, event_propertiesP.props.condition, dsSession, 'condition', null, null, null, calling_field_id ? calling_field_id : calling_triggerP, null, descP); // execute expression
if (
/files_v|wysiwyg_v|view_v|open_modal_v/.test(event_propertiesP.props.condition) ||
functionP === 'set_data' ||
String(refIdP?.prog || '') === '1630849293262'
) {
await func.events._debug_trace_save_asset(
SESSION_ID,
'condition_eval',
{
functionP,
ref_prog: refIdP?.prog,
eventIdP,
source_event_id: event_propertiesP?.id || calling_trigger_prop?.id,
condition: event_propertiesP.props.condition,
result: expCond?.result,
error: expCond?.error,
fields: expCond?.fields,
},
dsSession,
);
}
func.utils.debug.log(SESSION_ID, log_nodeId, {
module: 'event',
action: log_prop,
source: log_source,
prop: descP,
details: event_propertiesP.props.condition,
result: expCond.result,
error: expCond.error,
fields: expCond.fields,
type: 'event',
prog_id: log_prog_id,
conditional: true,
});
var cond = expCond.result;
if (!cond || expCond.error) {
// condition failed // === true 03/04/16
func.events.delete_job(SESSION_ID, jobNoP);
await func.events._debug_trace_save_asset(
SESSION_ID,
'condition_skip',
{
functionP,
ref_prog: refIdP?.prog,
eventIdP,
source_event_id: event_propertiesP?.id || calling_trigger_prop?.id,
condition: event_propertiesP.props.condition,
result: expCond?.result,
error: expCond?.error,
fields: expCond?.fields,
},
dsSession,
);
func.utils.debug.watch(SESSION_ID, calling_trigger_prop?.id, functionP, '', '', expCond, true);
return;
}
} // Non conditional event
else {
func.utils.debug.log(SESSION_ID, log_nodeId, {
module: 'event',
action: log_prop,
source: log_source,
prop: descP,
details: null,
result: null,
error: null,
fields: null,
type: 'event',
prog_id: log_prog_id,
});
}
}
// var log_error = function (descP, detailsP, warning) {
// func.utils.debug.log(SESSION_ID, log_nodeId, {
// module: "event",
// action: functionP,
// source: log_source,
// prop: descP,
// details: detailsP,
// result: null,
// error: !warning,
// warning: warning,
// fields: null,
// type: "event",
// prog_id: log_prog_id,
// });
// };
const get_params_obj = async function () {
const _prog_id = await get_prog_id();
const _prog = await func.utils.VIEWS_OBJ.get(SESSION_ID, _prog_id);
if (!_prog) {
func.events.delete_job(SESSION_ID, jobNoP);
return func.utils.debug_report(SESSION_ID, 'func.events.execute', 'Program not found: ' + refIdP.prog, 'E');
}
// get in parameters
var params_obj = {};
if (_prog?.properties?.progParams) {
for await (const [key, val] of Object.entries(_prog.properties.progParams)) {
// if (val.data.dir === 'in') continue;
if (typeof args.parameters_obj_inP?.[val.data.parameter] !== 'undefined') {
if (args.parameters_obj_inP?.[val.data.parameter].fx) {
let ret = await func.expression.get(SESSION_ID, args.parameters_obj_inP?.[val.data.parameter].fx, dsSession, 'parameters');
params_obj[val.data.parameter] = ret.result;
} else {
params_obj[val.data.parameter] = args.parameters_obj_inP?.[val.data.parameter].value;
}
continue;
}
if (
val.data.parameter === 'REDUCE_VALUE' &&
typeof args.parameters_obj_inP?.REDUCE_COUNTER !== 'undefined'
) {
const legacy_reduce_counter = args.parameters_obj_inP.REDUCE_COUNTER;
if (legacy_reduce_counter.fx) {
let ret = await func.expression.get(SESSION_ID, legacy_reduce_counter.fx, dsSession, 'parameters');
params_obj[val.data.parameter] = ret.result;
} else {
params_obj[val.data.parameter] = legacy_reduce_counter.value;
}
try {
globalThis.__XUDA_RT_TRACE && console.log('[xuda-runtime] legacy_reduce_counter_alias ' +
JSON.stringify({
program: _prog.properties.menuName,
parameter: val.data.parameter,
target: params_obj[val.data.parameter],
}),
);
} catch (e) {}
continue;
}
console.warn(`Warning: Program ${_prog.properties.menuName} expected In parameter: ${val.data.parameter} but received null instead`);
}
}
if (functionP === 'set_data' || String(_prog_id || '') === '1630849293262') {
await func.events._debug_trace_save_asset(
SESSION_ID,
'set_data_params',
{
functionP,
target_prog: _prog_id,
menuName: _prog?.properties?.menuName,
params: func.events._debug_summarize_object(params_obj),
},
dsSession,
);
}
return params_obj;
};
const get_prog_id = async function () {
let _prop = args?.calling_trigger_prop?.data?.name?.properties;
let _prog_id = args.prog_id;
if (_prop?.['xu-exp:prog']) {
_prog_id = (await func.expression.get(SESSION_ID, _prop['xu-exp:prog'], dsSession, 'prog_id expression')).result;
}
return _prog_id;
};
// const get_args_property_value = async function (prop_name) {
// let _prop = args?.calling_trigger_prop?.data?.name;
// let _value = _prop[prop_name];
// if (_prop?.[`xu-exp:${prop_name}`]) {
// _value = (
// await func.expression.get(
// SESSION_ID,
// _prop[`xu-exp:${prop_name}`],
// dsSession,
// `${prop_name} expression`
// )
// ).result;
// }
// return _value;
// };
var args = {
prog_id: refIdP?.prog,
screenIdP: refIdP?.prog,
callingFieldIdP: field_elm,
dataSourceNoP: null,
parentDataSourceNoP: dsSession,
triggerIdP: eventIdP,
containerIdP: null,
rowIdP: rowP, //sub_row_idP ? sub_row_idP : rowP,
jobNoP: jobNoP,
callingSourceP: callingSourceP,
calling_jobP: calling_jobP,
screen_dsP: null,
is_panelP: null,
argument_listP: null,
calling_trigger_prop: calling_trigger_prop,
parameters_obj_inP: refIdP?.parameters,
call_screen_propertiesP: refIdP?.properties,
};
const get_runtime_module_with_method = async function (module_name, method_name) {
const load_module = async function () {
const module_ret = await func.common.get_module(SESSION_ID, module_name);
if (typeof module_ret?.[method_name] === 'function') {
return module_ret;
}
if (typeof module_ret?.default?.[method_name] === 'function') {
return module_ret.default;
}
return module_ret;
};
let module_ret = await load_module();
if (typeof module_ret?.[method_name] === 'function') {
return module_ret;
}
for (const key of Object.keys(func.common._import_cache || {})) {
if (key.includes(module_name)) {
delete func.common._import_cache[key];
}
}
if (typeof globalThis !== 'undefined') {
globalThis.__XU_RUNTIME_MODULE_CACHE_TAG__ = Date.now();
}
module_ret = await load_module();
if (typeof module_ret?.[method_name] === 'function') {
return module_ret;
}
throw new TypeError(`${module_name}.${method_name} is not available`);
};
const fx = {
Call_window: async function () {
var is_panel;
var $calling_container;
if (_session.WORKER_OBJ.jobs[job_index]) {
if (_session.WORKER_OBJ.jobs[job_index].paramsP) {
$calling_container = func.runtime.ui.find_element_by_id(_session.WORKER_OBJ.jobs[job_index].paramsP.callingContainerP);
} else {
$calling_container = ''; // calling from datasource 0
_session.WORKER_OBJ.jobs[job_index].paramsP = {};
}
}
if (!refIdP.prog) {
func.events.delete_job(SESSION_ID, jobNoP);
return func.utils.debug_report(SESSION_ID, 'func.events.execute', 'Program is empty', 'E');
}
const params_obj = await get_params_obj();
return await func.runtime.ui.init_screen({
SESSION_ID,
prog_id: await get_prog_id(),
sourceScreenP: func.runtime.ui.get_data(containerP)?.xuData?.screenId,
callingDataSource_objP: _session.DS_GLB[dsSession],
$callingContainerP: $calling_container,
triggerIdP: eventIdP,
rowIdP: rowP,
jobNoP,
is_panelP: is_panel,
parameters_obj_inP: params_obj,
source_functionP: functionP,
call_screen_propertiesP: args.call_screen_propertiesP,
});
},
call_modal: async function () {
return await fx.Call_window();
},
call_popover: async function () {
return await fx.Call_window();
},
call_page: async function () {
return await fx.Call_window();
},
call_library: async function () {
let plugin_name = refIdP.plugin_name,
method = refIdP.library_method,
$containerP = $div,
dsP = dsSession,
propsP = refIdP.library_props,
sourceP = descP;
var _session = SESSION_OBJ[SESSION_ID];
const set_SYS_GLOBAL_OBJ_WIDGET_INFO = async function (docP) {
var obj = { ...docP };
obj.date = await func.utils.get_dateTime(SESSION_ID, 'SYS_DATE', docP.date);
obj.time = await func.utils.get_dateTime(SESSION_ID, 'SYS_TIME', docP.date);
var datasource_changes = {
[0]: {
['data_system']: {
['SYS_GLOBAL_OBJ_WIDGET_INFO']: obj,
},
},
};
await func.datasource.update(SESSION_ID, datasource_changes, null, avoid_event_refresh);
};
const call_plugin_api = async function (plugin_nameP, dataP) {
return await func.utils.call_plugin_api(SESSION_ID, plugin_nameP, dataP);
};
const report_error = function (descP, warn) {
func.utils.debug.log(SESSION_ID, _session.DS_GLB[dsP].prog_id + '_' + _session.DS_GLB[dsP].callingMenuId, {
module: 'widgets',
action: 'Init',
source: sourceP,
prop: descP,
details: descP,
result: null,
error: warn ? false : true,
fields: null,
type: 'widgets',
prog_id: _session.DS_GLB[dsP].prog_id,
});
};
const get_fields_data = async function (fields, props) {
const report_error = function (descP, warn) {
func.utils.debug.log(SESSION_ID, _session.DS_GLB[dsP].prog_id + '_' + _session.DS_GLB[dsP].callingMenuId, {
module: 'widgets',
action: 'Init',
source: sourceP,
prop: descP,
details: descP,
result: null,
error: warn ? false : true,
fields: null,
type: 'widgets',
prog_id: _session.DS_GLB[dsP].prog_id,
});
};
const get_property_value = async function (fieldIdP, val) {
// var value = props[fieldIdP];
var value = props[fieldIdP] || (typeof val.defaultValue === 'function' ? val?.defaultValue?.() : val?.defaultValue);
if (props[`xu-exp:${fieldIdP}`]) {
value = (await func.expression.get(SESSION_ID, props[`xu-exp:${fieldIdP}`], dsP, 'widget property')).result;
}
return func.common.get_cast_val(
SESSION_ID,
'widgets',
fieldIdP,
val.type, //val.type !== "string" || val.type !== "number" ? "string" : val.type,
value,
null,
);
};
var data_obj = {};
var return_code = 1;
// $.each(fields, function (key, val) {
for await (const [key, val] of Object.entries(fields)) {
try {
data_obj[key] = await get_property_value(key, val);
if (!data_obj[key] && val.mandatory) {
return_code = -1;
report_error(`${key} is a mandatory field.`);
break;
}
// console.log(val);
} catch (error) {
console.error('[xuda-runtime] caught xuda_events.js:723:', error);
}
}
return { code: return_code, data: data_obj };
};
try {
const _plugin = APP_OBJ[_session.app_id]?.app_plugins_purchased?.[plugin_name];
const index = await func.utils.get_plugin_resource(SESSION_ID, plugin_name, `${_plugin.manifest['index.mjs'].dist ? 'dist/' : ''}index.mjs`);
const methods = index.methods;
if (methods && !methods[method]) {
return report_error('method not found');
}
const fields_ret = await get_fields_data(methods[method].fields, propsP);
if (fields_ret.code < 0) {
return report_error(fields_ret.data);
}
const fields = fields_ret.data;
const plugin_setup_ret = await func.utils.get_plugin_setup(SESSION_ID, plugin_name);
if (plugin_setup_ret.code < 0) {
return report_error(plugin_setup_ret);
}
const api_utils = await func.common.get_module(SESSION_ID, 'xuda-api-library.mjs', {
func,
glb,
SESSION_OBJ,
SESSION_ID,
APP_OBJ,
dsSession: dsP,
job_id: jobNoP,
});
const params = {
SESSION_ID,
method,
_session,
dsP,
sourceP,
propsP,
plugin_name,
$containerP,
plugin_setup: plugin_setup_ret.data,
report_error,
call_plugin_api,
set_SYS_GLOBAL_OBJ_WIDGET_INFO,
api_utils,
};
const fx = await func.utils.get_plugin_resource(SESSION_ID, plugin_name, `${_plugin.manifest['runtime.mjs'].dist ? 'dist/' : ''}runtime.mjs`);
if (!fx[method]) {
throw `Method: ${method} does not exist`;
}
await fx[method](fields, params);
} catch (err) {
report_error(err);
}
func.events.delete_job(SESSION_ID, jobNoP);
},
call_native_javascript: async function () {
const module = await get_runtime_module_with_method('xuda-event-javascript-module.mjs', 'call_javascript');
const result = await module.call_javascript(SESSION_ID, jobNoP, refIdP, dsSession, false, $div);
await func.datasource.set_outputField(SESSION_ID, dsSessionP, result, args, avoid_event_refresh);
return result;
},
call_evaluate_javascript: async function () {
const module = await get_runtime_module_with_method('xuda-event-javascript-module.mjs', 'call_javascript');
const result = await module.call_javascript(SESSION_ID, jobNoP, refIdP, dsSession, true, $div);
await func.datasource.set_outputField(SESSION_ID, dsSessionP, result, args, avoid_event_refresh);
return result;
},
execute_native_javascript: async function () {
const module = await get_runtime_module_with_method('xuda-event-javascript-module.mjs', 'run_javascript');
const resolved_element_expr = `(func.runtime.ui && func.runtime.ui.find_xu_ui_in_root && func.runtime.ui.get_first_node ? func.runtime.ui.get_first_node(func.runtime.ui.find_xu_ui_in_root(SESSION_ID, ${JSON.stringify(elementP)})) : null)`;
const result = await module.run_javascript(
SESSION_ID,
jobNoP,
dsSession,
`(async function(el,evt) {
${refIdP.value}
})(${resolved_element_expr},evt)`,
null,
null,
null,
evt,
$div,
);
await func.datasource.set_outputField(SESSION_ID, dsSessionP, result, args, avoid_event_refresh);
return result;
},
execute_evaluate_javascript: async function () {
const module = await get_runtime_module_with_method('xuda-event-javascript-module.mjs', 'run_javascript');
const resolved_element_expr = `(func.runtime.ui && func.runtime.ui.find_xu_ui_in_root && func.runtime.ui.get_first_node ? func.runtime.ui.get_first_node(func.runtime.ui.find_xu_ui_in_root(SESSION_ID, ${JSON.stringify(elementP)})) : null)`;
const result = await module.run_javascript(
SESSION_ID,
jobNoP,
dsSession,
`(async function(el,evt) {
${refIdP.value}
})(${resolved_element_expr},evt)`,
true,
null,
null,
evt,
$div,
);
await func.datasource.set_outputField(SESSION_ID, dsSessionP, result, args, avoid_event_refresh);
return result;
},
loader_on: async function () {
glb.CURRENT_APP_LOADING = null;
LOADER_ACTIVE = true;
LOADER_TEXT = descP;
// }
func.events.delete_job(SESSION_ID, jobNoP);
// if (callbackP) callbackP();
},
loader_off: async function () {
LOADER_ACTIVE = false;
func.events.delete_job(SESSION_ID, jobNoP);
// if (callbackP) callbackP();
},
emit_event: async function () {
if (refIdP.value) {
// if (descP.value) {
func.runtime.platform.emit(refIdP.value, [_session.DS_GLB[dsSession]]);
} else {
func.utils.debug_report(SESSION_ID, 'func.events.execute', 'Event name missing', 'E');
}
func.events.delete_job(SESSION_ID, jobNoP);
// if (callbackP) callbackP();
},
invoke_action: async function () {
func.utils.debug.watch(SESSION_ID, calling_trigger_prop?.id, functionP, null, null, expCond);
await func.action.execute(SESSION_ID, refIdP.value, _ds, null, null, jobNoP, containerP);
},
raise_event: async function () {
var _ds = _session.DS_GLB[dsSession];
const _view_obj = await func.utils.VIEWS_OBJ.get(SESSION_ID, _ds.prog_id);
if (callingSourceP === 'grid' || callingSourceP === 'form') {
let _field_obj = func.common.find_item_by_key(_view_obj.progFields, 'field_id', field_elm);
var event_name = _field_obj?.workflow?.[eventIdP].name.event;
if (_field_obj?.workflow?.[eventIdP].name?.properties['xu-exp:event']) {
event_name = (await func.expression.get(SESSION_ID, props[`xu-exp:event`], dsSession, 'event_name expression')).result;
}
if (field_elm && event_name) {
// get container for fields events
const dsP = await func.datasource.find_event_dataSource(SESSION_ID, event_name, dsSession);
if (event_name === 'SAVE_ASSET_EVENT') {
await func.events._debug_trace_save_asset(
SESSION_ID,
'raise_event',
{
event_name,
callingSourceP,
dsP,
functionP,
source_prog: _ds?.prog_id,
},
dsSession,
);
}
return await func.datasource.run_events_functions(SESSION_ID, dsP, event_name, jobNoP, null, calling_trigger_prop?.data?.name?.parameters || {}, event_options);
}
// done_execution(event_name);
}
if (callingSourceP.includes('event')) {
let event_name = refIdP.event;
if (refIdP?.properties?.['xu-exp:event']) {
event_name = (await func.expression.get(SESSION_ID, refIdP.properties['xu-exp:event'], dsSession, 'event_name expression')).result;
}
const dsP = await func.datasource.find_event_dataSource(SESSION_ID, event_name, dsSession);
if (event_name === 'SAVE_ASSET_EVENT') {
await func.events._debug_trace_save_asset(
SESSION_ID,
'raise_event',
{
event_name,
callingSourceP,
dsP,
functionP,
source_prog: _ds?.prog_id,
},
dsSession,
);
}
await func.datasource.run_events_functions(SESSION_ID, dsP, event_name, jobNoP, calling_trigger_prop?.props?.async, calling_trigger_prop?.data?.name?.parameters || {}, event_options);
// done_execution(event_name);
}
func.events.delete_job(SESSION_ID, jobNoP);
// if (callbackP) callbackP();
func.utils.debug.watch(SESSION_ID, calling_trigger_prop?.id, functionP, '', '', expCond);
},
get_data: async function () {
const params_obj = await get_params_obj();
if (!(await get_prog_id())) {
func.utils.debug_report(SESSION_ID, 'func.events.execute', `${elementP} > ${triggerP} > ${functionP} > program ${prog} is missing`, 'E');
func.events.delete_job(SESSION_ID, jobNoP);
return;
}
var _ds = _session.DS_GLB[dsSession];
if (!_ds) {
func.events.delete_job(SESSION_ID, jobNoP);
return;
}
if (_ds) {
func.utils.debug.watch(SESSION_ID, calling_trigger_prop?.id, functionP, null, calling_trigger_prop, expCond);
const ret = await func.datasource.create(SESSION_ID, await get_prog_id(), args.dataSourceNoP, args.parentDataSourceNoP, args.containerIdP, args.rowIdP, args.jobNoP, args.calling_trigger_prop, null, null, args.callingSourceP, args.calling_jobP, args.screen_dsP, args.is_panelP, params_obj);
let _ds_new = _session.DS_GLB[ret.dsSessionP];
let parameters = args?.calling_trigger_prop?.data?.name?.parameters;
if (parameters && !xu_isEmpty(parameters)) {
await func.datasource.update_changes_for_out_parameter(SESSION_ID, _ds_new.dsSession, _ds.dsSession, avoid_event_refresh);
}
func.events.delete_job(SESSION_ID, jobNoP);
return _ds_new;
}
},
set_data: async function () {
return this.get_data();
},
batch: async function () {
const result = await this.get_data();
// await set_outputField(SESSION_ID, elementP, triggerP, functionP, dsSessionP, result);
return result;
},
update: async function () {
const resolve_update_field_id = async function (field_expr, iterate_info) {
let trimmed = field_expr?.trim?.() || '';
if (!trimmed) {
return trimmed;
}
const first = trimmed.substring(0, 1);
const last = trimmed.substring(trimmed.length - 1);
if ((first === "'" || first === '"' || first === '`') && last === first) {
trimmed = trimmed.substring(1, trimmed.length - 1).trim();
}
if (/^@?[A-Za-z_][\w\-\:\.]*$/.test(trimmed)) {
return trimmed.substring(0, 1) === '@' ? trimmed.substring(1) : trimmed;
}
let ret_field_id = await func.expression.get(SESSION_ID, trimmed, dsSessionP, 'update', null, null, null, null, null, null, iterate_info);
if (typeof ret_field_id?.result === 'string' && ret_field_id.result.substring(0, 1) === '@') {
return ret_field_id.result.substring(1);
}
return ret_field_id?.result;
};
const obj_values_to_update = func.datasource.get_viewFields_for_update_function(SESSION_ID, calling_trigger_prop, null, dsSessionP);
if (!obj_values_to_update || xu_isEmpty(obj_values_to_update)) {
func.utils.debug_report(SESSION_ID, 'Update values object is empty', '', 'W');
if (jobNoP) func.events.delete_job(SESSION_ID, jobNoP);
return;
}
var updates = [];
for await (const [key, val] of Object.entries(obj_values_to_update)) {
var $element;
var iterate_info = null;
if (elementP) {
const element_meta = func.runtime.ui.get_meta(elementP, 'xuData');
iterate_info = element_meta?.iterate_info || null;
}
let ret_value = await func.expression.get(SESSION_ID, val.val.trim(), dsSessionP, 'update', null, null, null, null, null, null, iterate_info);
let _field_id = await resolve_update_field_id(val.id, iterate_info);
let _value = ret_value.result;
updates.push({ _field_id, _value });
}
let datasource_changes = {};
for await (const change of updates) {
let ret_get_value = await func.datasource.get_value(SESSION_ID, change._field_id, dsSessionP);
if (ret_get_value.found) {
let _ds = _session.DS_GLB[ret_get_value.dsSessionP];
if (!datasource_changes[_ds.dsSession]) {
datasource_changes[_ds.dsSession] = {};
}
if (!datasource_changes[_ds.dsSession][ret_get_value.currentRecordId]) {
datasource_changes[_ds.dsSession][ret_get_value.currentRecordId] = {};
}
datasource_changes[_ds.dsSession][ret_get_value.currentRecordId][change._field_id] = change._value;
}
}
await func.datasource.update(SESSION_ID, datasource_changes, null, avoid_event_refresh, triggerP);
if (_ds.PARAM_OUT_INFO) {
for await (const [key, val] of Object.entries(_ds.PARAM_OUT_INFO)) {
await func.datasource.update_changes_for_out_parameter(SESSION_ID, _ds.dsSession, val.parentDataSourceNo, avoid_event_refresh);
}
}
if (jobNoP) func.events.delete_job(SESSION_ID, jobNoP);
// return changes;
},
call_alert: async function () {
await func.utils.alerts.invoke(SESSION_ID, 'call_alert', refIdP, log_source, dsSession);
func.events.delete_job(SESSION_ID, jobNoP);
},
alert: async function () {
await func.utils.alerts.invoke(SESSION_ID, 'alert', refIdP, log_source, dsSession);
func.events.delete_job(SESSION_ID, jobNoP);
},
delay: async function () {
return new Promise((resolve) => {
setTimeout(function () {
if (jobNoP) func.events.delete_job(SESSION_ID, jobNoP);
resolve();
}, refIdP.value);
});
},
comment: async function () {
if (jobNoP) func.events.delete_job(SESSION_ID, jobNoP);
},
call_project_api: async function () {
const params_obj = await get_params_obj();
const _prog_id = await get_prog_id();
if (!_prog_id) {
func.utils.debug_report(SESSION_ID, 'func.events.execute', `${elementP} > ${triggerP} > ${functionP} > program not defined`, 'E');
func.events.delete_job(SESSION_ID, jobNoP);
return;
}
// if (!output_field) {
// func.utils.debug_report(
// SESSION_ID,
// "func.events.execute",
// `${elementP} >${triggerP} >${functionP} > Output field not defined`,
// "W"
// );
// // func.events.delete_job(SESSION_ID, jobNoP);
// // return;
// }
const api_ret = await func.api.call_project_api(_prog_id, params_obj);
await func.datasource.set_outputField(SESSION_ID, dsSessionP, api_ret, args, avoid_event_refresh);
func.events.delete_job(SESSION_ID, jobNoP);
},
call_system_api: async function () {
const api_method = await func.datasource.get_args_property_value(SESSION_ID, dsSession, args, 'api_method');
if (!api_method) {
func.utils.debug_report(SESSION_ID, 'func.events.execute', `${elementP} >${triggerP} >${functionP} > api_method not defined`, 'E');
func.events.delete_job(SESSION_ID, jobNoP);
return;
}
let payload = {};
const _payload = await func.datasource.get_args_property_value(SESSION_ID, dsSession, args, 'payload');
if (_payload) {
const get_payload_property_value = async function (prop_name) {
let _prop = _payload;
let _value = _prop[prop_name];
if (_prop?.[`xu-exp:${prop_name}`]) {
_value = (await func.expression.get(SESSION_ID, _prop[`xu-exp:${prop_name}`], dsSession, `${prop_name} expression`)).result;
}
return _value;
};
for await (let [key, val] of Object.entries(_payload)) {
// if (key.substring(0, 7) !== "xu-exp:") {
const new_key = key.replaceAll('xu-exp:', ''); //key.substring(0, 7) === "xu-exp:" ? key.substring(7): key
payload[new_key] = await get_payload_property_value(new_key);
// }
}
}
// if (!payload) {
// func.utils.debug_report(
// SESSION_ID,
// "func.events.execute",
// `${elementP} >${triggerP} >${functionP} > payload not defined`,
// "E"
// );
// func.events.delete_job(SESSION_ID, jobNoP);
// return;
// }
const output_field = await func.datasource.get_args_property_value(SESSION_ID, dsSession, args, 'outputField');
// if (!output_field) {
// func.utils.debug_report(
// SESSION_ID,
// "func.events.execute",
// `${elementP} >${triggerP} >${functionP} > Output field not defined`,
// "E"
// );
// func.events.delete_job(SESSION_ID, jobNoP);
// return;
// }
const api_ret = await func.api.call_system_api(api_method, payload);
if (output_field) {
let datasource_changes = {};
let ret_get_value = await func.datasource.get_value(SESSION_ID, output_field, dsSessionP);
if (ret_get_value.found) {
let _ds = _session.DS_GLB[ret_get_value.dsSessionP];
if (!datasource_changes[_ds.dsSession]) {
datasource_changes[_ds.dsSession] = {};
}
if (!datasource_changes[_ds.dsSession][ret_get_value.currentRecordId]) {
datasource_changes[_ds.dsSession][ret_get_value.currentRecordId] = {};
}
datasource_changes[_ds.dsSession][ret_get_value.currentRecordId][output_field] = api_ret;
await func.datasource.update(SESSION_ID, datasource_changes, null, avoid_event_refresh);
}
}
func.events.delete_job(SESSION_ID, jobNoP);
},
call_external_api: async function () {
const method = await func.datasource.get_args_property_value(SESSION_ID, dsSession, args, 'method');
if (!method) {
func.utils.debug_report(SESSION_ID, 'func.events.execute', `${elementP} >${triggerP} >${functionP} > method not defined`, 'E');
func.events.delete_job(SESSION_ID, jobNoP);
return;
}
const url = await func.datasource.get_args_property_value(SESSION_ID, dsSession, args, 'url');
if (!url) {
func.utils.debug_report(SESSION_ID, 'func.events.execute', `${elementP} >${triggerP} >${functionP} > url not defined`, 'E');
func.events.delete_job(SESSION_ID, jobNoP);
return;
}
const payload_arr = await func.datasource.get_args_property_value(SESSION_ID, dsSession, args, 'payload');
const report_conversion_error = function (res, typeP, valP) {
var msg = `${elementP} >${triggerP} >${functionP} > error converting from ${valP} to ${typeP}`;
if (error) {
return func.utils.debug_report(SESSION_ID, msg, '', 'W');
}
func.utils.debug_report(SESSION_ID, msg + ' ' + (source.charAt(0).toUpperCase() + source.slice(1).toLowerCase()) + prog_info, '', 'E');
};
const report_conversion_warn = function (res) {
// number/boolean/bigint -> string is lossless; skip the noise (it routes as an "Unhandled Runtime Error")
if (typeP === 'string' && (typeof valP === 'number' || typeof valP === 'boolean' || typeof valP === 'bigint')) return;
var msg = `${elementP} >${triggerP} >${functionP} > type mismatch auto conversion from value ${valP} to ${typeP}`;
func.utils.debug_report(SESSION_ID, msg + ' ' + (source.charAt(0).toUpperCase() + source.slice(1).toLowerCase()) + prog_info, '', 'W');
};
// var ret = valP;
if (error) {
return report_conversion_error();
}
const module = await func.common.get_module(SESSION_ID, 'xuda-get-cast-util-module.mjs');
// return module.cast(
// typeP,
// valP,
// report_conversion_error,
// report_conversion_warn
// );
var payload = payload_arr.reduce(
(ret, val, key) => {
ret[val.key] = module.cast(val.type, val.val, report_conversion_error, report_conversion_warn);
return ret;
},
{},
);
// if (!payload) {
// func.utils.debug_report(
// SESSION_ID,
// "func.events.execute",
// `${elementP} >${triggerP} >${functionP} > payload not defined`,
// "E"
// );
// func.events.delete_job(SESSION_ID, jobNoP);
// return;
// }
const output_field = await func.datasource.get_args_property_value(SESSION_ID, dsSession, args, 'outputField');
// if (!output_field) {
// func.utils.debug_report(
// SESSION_ID,
// "func.events.execute",
// `${elementP} >${triggerP} >${functionP} > Output field not defined`,
// "E"
// );
// func.events.delete_job(SESSION_ID, jobNoP);
// return;
// }
const api_ret = await func.api.call_external_api(method, url, payload);
if (output_field) {
let datasource_changes = {};
let ret_get_value = await func.datasource.get_value(SESSION_ID, output_field, dsSessionP);
if (ret_get_value.found) {
let _ds = _session.DS_GLB[ret_get_value.dsSessionP];
if (!datasource_changes[_ds.dsSession]) {
datasource_changes[_ds.dsSession] = {};
}
if (!datasource_changes[_ds.dsSession][ret_get_value.currentRecordId]) {
datasource_changes[_ds.dsSession][ret_get_value.currentRecordId] = {};
}
datasource_changes[_ds.dsSession][ret_get_value.currentRecordId][output_field] = api_ret;
await func.datasource.update(SESSION_ID, datasource_changes, null, avoid_event_refresh);
}
}
func.events.delete_job(SESSION_ID, jobNoP);
},
};
// if (functionP.includes("alert")) {
// return await fx.alert();
// } else {
// try {
// console.log("functionP", functionP);
return await fx[functionP]();
// } catch (err) {
// console.error(err);
console.error('[xuda-runtime] caught xuda_events.js:1248:', err);
// }
// }
};
func.events.delete_job = function (SESSION_ID, jobNoP) {
var _session = SESSION_OBJ[SESSION_ID];
var job_index = func.events.find_job_index(SESSION_ID, jobNoP);
// console.log(jobNoP, job_index);
if (!_session.WORKER_OBJ.jobs[job_index]) {
_session.WORKER_OBJ.stat = null;
return;
}
var dsSession = _session.WORKER_OBJ.jobs[job_index].dsSessionP;
let ds_obj = _session?.DS_GLB[dsSession];
if (ds_obj) {
delete SCREEN_BLOCKER_OBJ[ds_obj.screenId + (ds_obj.callingScreenId ? '_' + ds_obj.callingScreenId : '')];
}
if (dsSession && ds_obj?.loops_limit && ds_obj?.loops_count < ds_obj?.loops_limit - 1) {
return;
}
_session.WORKER_OBJ.stat = null;
_session.WORKER_OBJ.jobs.splice(job_index, 1);
};
func.events.delete_job_0 = function (SESSION_ID) {
var job_index = 0;
var _session = SESSION_OBJ[SESSION_ID];
if (!_session.WORKER_OBJ.jobs[job_index]) {
_session.WORKER_OBJ.stat = null;
return;
}
var dsSession = _session.WORKER_OBJ.jobs[job_index].dsSession;
let ds_obj = _session?.DS_GLB[dsSession];
if (ds_obj) {
delete SCREEN_BLOCKER_OBJ[ds_obj.screenId + (ds_obj.callingScreenId ? '_' + ds_obj.callingScreenId : '')];
}
if (dsSession && ds_obj && ds_obj.loops_limit && ds_obj.loops_count < ds_obj.loops_limit - 1) {
return;
}
_session.WORKER_OBJ.stat = null;
_session.WORKER_OBJ.jobs.splice(job_index, 1);
};
func.events.check_jobs_idle = async function (SESSION_ID, jobsP) {
return new Promise((resolve, reject) => {
var _session = SESSION_OBJ[SESSION_ID];
if (!jobsP || (jobsP && jobsP.length === 0)) {
resolve();
return;
}
var listener = setInterval(function () {
var found;
for (const [key, val] of Object.entries(jobsP)) {
for (const [key2, val2] of Object.entries(_session.WORKER_OBJ.jobs)) {
if (key2 === val) {
found = true;
break;
}
}
}
if (!found) {
do_callback();
return;
}
}, 100);
var do_callback = function () {
clearInterval(listener);
resolve();
};
});
};
var loop_detected_obj = {};
setInterval(function () {
loop_detected_obj = {};
}, 1000);
func.events.set_browser_changes = function (dsP, fieldsChangedP) {
if (fieldsChangedP.includes('SYS_GLOBAL_STR_BROWSER_TITLE')) func.runtime.platform.set_title(dsP.dataset_new['SYS_GLOBAL_STR_BROWSER_TITLE']);
};
func.events.execute_PENDING_OPEN_URL_EVENTS = async function () {
for (let [key, url] of Object.entries(PENDING_OPEN_URL_EVENTS)) {
if (url) {
glb.WINDOW_LOCATION_SEARCH = url;
glb.ROOT_ELEMENT_ATTRIBUTES = func.UI.utils.get_root_element_attributes();
const params_obj = func.common.getObjectFromUrl(url, glb.ROOT_ELEMENT_ATTRIBUTES);
if (!params_obj.prog) {
await func.utils.report_issue(SESSION_ID, {
code: 'RUN_MSG_EVT_030',
source: 'func.events.execute_PENDING_OPEN_URL_EVENTS',
message: 'prog empty',
type: 'W',
details: {
url,
},
});
return;
}
await func.utils.TREE_OBJ.get(SESSION_ID, params_obj.prog);
let screen_ret = await func.utils.get_screen_obj(SESSION_ID, params_obj.prog);
if (screen_ret) {
await func.runtime.ui.init_screen({
SESSION_ID,
prog_id: params_obj.prog,
sourceScreenP: null,
callingDataSource_objP: null,
$callingContainerP: func.runtime.ui.get_session_root(SESSION_ID),
triggerIdP: null,
rowIdP: null,
jobNoP: null,
is_panelP: null,
parameters_obj_inP: null,
source_functionP: 'pendingUrlEvent_embed',
});
} else {
await func.utils.report_issue(SESSION_ID, {
code: 'RUN_MSG_EVT_010',
source: 'func.events.execute_PENDING_OPEN_URL_EVENTS',
message: 'Program not exist',
type: 'E',
details: {
prog_id: params_obj.prog_id,
prog: params_obj.prog,
},
});
func.UI.utils.progressScreen.show(SESSION_ID, 'Program not exist', null, true);
}
} else {
await func.utils.report_issue(SESSION_ID, {
code: 'RUN_MSG_EVT_030',
source: 'func.events.execute_PENDING_OPEN_URL_EVENTS',
message: 'url empty',
type: 'W',
});
}
}
};
func.events.invoke = async function (event_id, options) {
var _session = SESSION_OBJ[SESSION_ID];
const event_options = options && typeof options === 'object' ? options : { avoid_refresh: options === true };
if (!event_id) {
await func.utils.report_issue(SESSION_ID, {
code: 'RUN_MSG_EVT_060',
source: 'func.events.invoke',
message: 'event_id Cannot be empty',
type: 'W',
});
return false;
}
var ds;
for await (const [ds_key, val] of Object.entries(_session.DS_GLB)) {
const _view_obj = await func.utils.VIEWS_OBJ.get(SESSION_ID, val.prog_id);
if (xu_isEmpty(_view_obj.progEvents)) continue;
if (ds) break;
for await (const [key, val] of Object.entries(_view_obj.progEvents)) {
if (val?.data?.type === 'user_defined' && val.data.event_name === event_id) {
ds = ds_key;
break;
}
}
}
if (!ds) {
await func.utils.report_issue(SESSION_ID, {
code: 'RUN_MSG_EVT_060',
source: 'func.events.invoke',
message: 'event_id not found',
type: 'W',
details: {
event_id,
},
});
return false;
}
func.events.validate(SESSION_ID, 'user_defined', ds, event_id, null, null, null, event_options);
};
func.action = {};
func.action.execute = async function (SESSION_ID, actionP, paramsP, isScreenActionP, event_sourceP, jobNoP, containerP) {
const module = await func.common.get_module(SESSION_ID, 'xuda-actions-module.esm.js');
await module.action_execute(SESSION_ID, actionP, paramsP, isScreenActionP, event_sourceP, jobNoP, containerP);
};
func.fcm = {};
// func.fcm.load_resources = function (callbackP) {
// func.utils.load_js_on_demand(
// func.common.get_url(
// SESSION_ID,
// "dist",
// "runtime/node_modules/@xuda.io/firebase-app/index.js"
// ),
// function () {
// func.utils.load_js_on_demand(
// func.common.get_url(
// SESSION_ID,
// "dist",
// "runtime/node_modules/@xuda.io/firebase-analytics/index.js"
// ),
// function () {
// func.utils.load_js_on_demand(
// func.common.get_url(
// SESSION_ID,
// "dist",
// "runtime/node_modules/@xuda.io/firebase-auth/index.js"
// ),
// function () {
// func.utils.load_js_on_demand(
// func.common.get_url(
// SESSION_ID,
// "dist",
// "runtime/node_modules/@xuda.io/firebase-firestore/index.js"
// ),
// function () {
// func.utils.load_js_on_demand(
// func.common.get_url(
// SESSION_ID,
// "dist",
// "runtime/node_modules/@xuda.io/firebase-messaging/index.js"
// ),
// function () {
// callbackP();
// }
// );
// }
// );
// }
// );
// }
// );
// }
// );
// };
// func.fcm.init_mobile_xuda = function (SESSION_ID, callbackP) {
// app_id = SESSION_OBJ[SESSION_ID].app_id;
// var sender_id = "XXX";
// var device = func.utils.get_device();
// var PublicVapidKey =
// "BBe17i6AUgRsYP9BUgrECmqapd90ViAM6uFR4aBnw2aRlCQ__QZcxAx5IpFhA6K1s6LZzns2nPCua_ISpAB80Jw";
// var done = function () {
// if ($.cookie("firebase_auth_common_redirect")) {
// $.removeCookie("firebase_auth_common_redirect");
// func.fcm.getRedirectResult(callbackP);
// } else {
// callbackP();
// }
// };
// func.fcm.load_resources(function () {
// if (!device) {
// func.fcm.web_push_notification(
// SESSION_ID,
// APP_OBJ[app_id]._conf.firebaseConfig,
// PublicVapidKey,
// done
// );
// } else {
// firebase.initializeApp(APP_OBJ[app_id]._conf.firebaseConfig);
// func.fcm.device_push_notification(sender_id, done);
// }
// });
// };
// func.fcm.init_mobile_app = function (SESSION_ID, callbackP) {
// // from db
// var app_obj = APP_OBJ[SESSION_OBJ[SESSION_ID].app_id];
// var firebaseConfig = {
// apiKey: app_obj.app_firebase_api_key,
// authDomain: app_obj.app_firebase_auth_domain,
// databaseURL: app_obj.app_firebase_database_uRLy,
// projectId: app_obj.app_firebase_project_id,
// storageBucket: app_obj.app_firebase_storage_bucket,
// messagingSenderId: app_obj.app_firebase_messaging_sender_id,
// appId: app_obj.app_firebase_app_id,
// measurementId: app_obj.app_firebase_measurement_id,
// };
// var sender_id = app_obj.app_firebase_messaging_sender_id;
// var device = func.utils.get_device();
// var PublicVapidKey = app_obj.app_firebase_publicvapidkey;
// var done = function () {
// if ($.cookie("firebase_auth_common_redirect")) {
// $.removeCookie("firebase_auth_common_redirect");
// func.fcm.getRedirectResult(callbackP);
// } else {
// callbackP();
// }
// };
// func.fcm.load_resources(function () {
// if (!device) {
// func.fcm.web_push_notification(
// SESSION_ID,
// firebaseConfig,
// PublicVapidKey,
// done
// );
// } else {
// firebase.initializeApp(firebaseConfig);
// func.fcm.device_push_notification(sender_id, done);
// }
// });
// };
// func.fcm.web_push_notification = function (
// SESSION_ID,
// firebaseConfig,
// PublicVapidKey,
// callbackP
// ) {
// try {
// firebase.initializeApp(firebaseConfig);
// // Retrieve Firebase Messaging object.
// const messaging = firebase.messaging();
// // Add the public key generated from the console here.
// messaging.usePublicVapidKey(PublicVapidKey);
// Notification.requestPermission().then((permission) => {
// if (permission === "granted") {
// console.log("Notification permission granted.");
// SESSION_OBJ[SESSION_ID].PUSH_NOTIFICATION_GRANTED = true;
// } else {
// console.log("Unable to get permission to notify.");
// }
// messaging
// .getToken()
// .then((currentToken) => {
// if (currentToken) {
// sendTokenToServer(currentToken);
// } else {
// // Show permission request.
// console.log(
// "No Instance ID token available. Request permission to generate one."
// );
// // Show permission UI.
// setTokenSentToServer(false);
// }
// })
// .catch((err) => {
// console.log("An error occurred while retrieving token. ", err);
// setTokenSentToServer(false);
// if (callbackP) callbackP();
// });
// });
// // [START refresh_token]
// // Callback fired if Instance ID token is updated.
// messaging.onTokenRefresh(() => {
// messaging
// .getToken()
// .then((refreshedToken) => {
// console.log("Token refreshed.");
// setTokenSentToServer(false);
// sendTokenToServer(refreshedToken);
// resetUI();
// // [END_EXCLUDE]
// })
// .catch((err) => {
// console.log("Unable to retrieve refreshed token ", err);
// });
// });
// messaging.onMessage((payload) => {
// var widget = func.UI.widgets(SESSION_ID);
// var get_from_web = function () {
// doc = {
// push_notification_title: payload.data.title,
// push_notification_body: payload.data.body,
// push_notification_image: payload.data.image,
// push_notification_event_id: payload.data.event_id,
// push_notification_color: payload.data.color,
// user_defined_1: payload.data.user_defined_1,
// user_defined_2: payload.data.user_defined_2,
// user_defined_3: payload.data.user_defined_3,
// user_defined_4: payload.data.user_defined_4,
// user_defined_5: payload.data.user_defined_5,
// timeout: payload.data.timeout,
// };
// };
// var get_from_device = function () {
// doc = {
// push_notification_title: payload.notification.title,
// push_notification_body: payload.notification.body,
// push_notification_image: payload.notification.image,
// push_notification_event_id: payload.data["gcm.notification.event_id"],
// push_notification_color: payload.data["gcm.notification.color"],
// user_defined_1: payload.data["gcm.notification.user_defined_1"],
// user_defined_2: payload.data["gcm.notification.user_defined_2"],
// user_defined_3: payload.data["gcm.notification.user_defined_3"],
// user_defined_4: payload.data["gcm.notification.user_defined_4"],
// user_defined_5: payload.data["gcm.notification.user_defined_5"],
// timeout: payload.data["gcm.notification.timeout"],
// };
// };
// if (payload.notification) {
// get_from_device();
// } else {
// get_from_web();
// }
// widget.set_SYS_GLOBAL_OBJ_WIDGET_INFO(doc, function () {
// widget.invoke_push_notification(doc);
// func.events.validate(SESSION_ID, "notification_received", 0);
// });
// });
// function resetUI() {
// messaging
// .getToken()
// .then((currentToken) => {
// if (currentToken) {
// sendTokenToServer(currentToken);
// } else {
// console.log(
// "No Instance ID token available. Request permission to generate one."
// );
// SESSION_OBJ[SESSION_ID].FIREBASE_TOKEN_ID = null;
// setTokenSentToServer(false);
// }
// })
// .catch((err) => {
// console.log("An error occurred while retrieving token. ", err);
// setTokenSentToServer(false);
// });
// }
// function sendTokenToServer(currentToken) {
// SESSION_OBJ[SESSION_ID].FIREBASE_TOKEN_ID = currentToken;
// if (!isTokenSentToServer()) {
// console.log("Sending token to server...");
// setTokenSentToServer(true);
// } else {
// console.log(
// "Token already sent to server so won't send it again " +
// "unless it changes"
// );
// }
// if (callbackP) callbackP(currentToken);
// }
// function isTokenSentToServer() {
// return false; //window.localStorage.getItem('sentToServer') === '1';
// }
// function setTokenSentToServer(sent) {
// // window.localStorage.setItem('sentToServer', sent ? '1' : '0');
// }
// } catch (e) {
// console.warn(e);
// SESSION_OBJ[SESSION_ID].FIREBASE_TOKEN_ID = "";
// callbackP();
// }
// };
// func.fcm.getRedirectResult = function (callbackP) {
// firebase
// .auth()
// .getRedirectResult()
// .then(function (result) {
// if (result.credential) {
// var token = result.credential.accessToken;
// var user = result.additionalUserInfo.profile;
// if (result.credential.signInMethod === "apple.com") {
// var appleUserFullName = result.user.displayName;
// user.given_name = appleUserFullName.split(" ").slice(0, -1).join(" ");
// user.family_name = result.user.displayName
// .split(" ")
// .slice(-1)
// .join(" ");
// }
// var obj = {
// provider: result.credential.signInMethod,
// token: token,
// first_name: user.given_name,
// last_name: user.family_name,
// email: user.email,
// user_id: user.id,
// picture: user.picture,
// verified_email: user.verified_email,
// locale: user.locale,
// error_code: "",
// error_msg: "",
// };
// SESSION_OBJ[SESSION_ID].SYS_GLOBAL_OBJ_FIREBASE_AUTH_INFO.token = token;
// SESSION_OBJ[SESSION_ID].SYS_GLOBAL_OBJ_FIREBASE_AUTH_INFO.first_name =
// user.given_name;
// SESSION_OBJ[SESSION_ID].SYS_GLOBAL_OBJ_FIREBASE_AUTH_INFO.last_name =
// user.family_name;
// SESSION_OBJ[SESSION_ID].SYS_GLOBAL_OBJ_FIREBASE_AUTH_INFO.email =
// user.email;
// SESSION_OBJ[SESSION_ID].SYS_GLOBAL_OBJ_FIREBASE_AUTH_INFO.user_id =
// user.id;
// SESSION_OBJ[SESSION_ID].SYS_GLOBAL_OBJ_FIREBASE_AUTH_INFO.picture =
// user.picture;
// SESSION_OBJ[
// SESSION_ID
// ].SYS_GLOBAL_OBJ_FIREBASE_AUTH_INFO.verified_email =
// user.verified_email;
// SESSION_OBJ[SESSION_ID].SYS_GLOBAL_OBJ_FIREBASE_AUTH_INFO.locale =
// user.locale;
// SESSION_OBJ[SESSION_ID].SYS_GLOBAL_OBJ_FIREBASE_AUTH_INFO.provider =
// result.additionalUserInfo.providerId.split(".")[0];
// var eventChangesResults = {
// rows_changed: [],
// fieldsChanged: [],
// };
// eventChangesResults.dsSession = 0;
// eventChangesResults.rows_changed.push("");
// eventChangesResults.fieldsChanged.push(
// "SYS_GLOBAL_OBJ_FIREBASE_AUTH_INFO"
// );
// eventChangesResults.dataset_obj = {
// "": {
// SYS_GLOBAL_OBJ_WIDGET_INFO: obj,
// },
// };
// var ds = $.cookie("firebase_auth_common_redirect_ds");
// var interval = setInterval(async function () {
// if (!SESSION_OBJ[SESSION_ID].DS_GLB[ds]) return;
// clearInterval(interval);
// await func.datasource.update(SESSION_ID, eventChangesResults);
// }, 100);
// }
// callbackP();
// .catch(function (error) {
// // Handle Errors here.
// var errorCode = error.code;
// var errorMessage = error.message;
// // The email of the user's account used.
// var email = error.email;
// // The firebase.auth.AuthCredential type that was used.
// var credential = error.credential;
// // ...
// console.error(errorCode, errorMessage, credential);
// SESSION_OBJ[SESSION_ID].SYS_GLOBAL_OBJ_FIREBASE_AUTH_INFO.error_code =
// errorCode;
// SESSION_OBJ[SESSION_ID].SYS_GLOBAL_OBJ_FIREBASE_AUTH_INFO.error_msg =
// errorMessage;
// callbackP();
// });
// };
// func.fcm.device_push_notification = function (sender_id, callbackP) {
// try {
// FirebasePlugin.getToken(
// function (fcmToken) {
// SESSION_OBJ[SESSION_ID].FIREBASE_TOKEN_ID = fcmToken;
// console.log(fcmToken);
// FirebasePlugin.hasPermission((hasPermission) => {
// if (hasPermission) {
// console.log("Notification permission granted.");
// SESSION_OBJ[SESSION_ID].PUSH_NOTIFICATION_GRANTED = true;
// if (callbackP) callbackP(fcmToken);
// } else {
// console.log("Unable to get permission to notify.");
// FirebasePlugin.grantPermission(function (hasPermission) {
// console.log(
// "Permission was " + (hasPermission ? "granted" : "denied")
// );
// if (hasPermission) {
// SESSION_OBJ[SESSION_ID].PUSH_NOTIFICATION_GRANTED = true;
// } else {
// SESSION_OBJ[SESSION_ID].PUSH_NOTIFICATION_GRANTED = false;
// }
// if (callbackP) callbackP(fcmToken);
// });
// }
// });
// },
// function (error) {
// console.error(error);
// }
// );
// FirebasePlugin.onMessageReceived(
// function (message) {
// // console.log('Message type: ' + message.messageType);
// // console.log(message);
// if (message.messageType === "notification") {
// console.log("Notification message received");
// var payload = message;
// var widget = func.UI.widgets(SESSION_ID);
// var doc = {
// push_notification_title:
// func.utils.get_device() === "android"
// ? payload.title
// : payload.aps.alert.title,
// push_notification_body:
// func.utils.get_device() === "android"
// ? payload.body
// : payload.aps.alert.body,
// // push_notification_image: payload.additionalData.fcm_options.image,
// push_notification_event_id: payload["event_id"],
// push_notification_color: payload["color"],
// user_defined_1: payload["user_defined_1"],
// user_defined_2: payload["user_defined_2"],
// user_defined_3: payload["user_defined_3"],
// user_defined_4: payload["user_defined_4"],
// user_defined_5: payload["user_defined_5"],
// timeout: payload["timeout"],
// };
// widget.set_SYS_GLOBAL_OBJ_WIDGET_INFO(doc, function () {
// widget.invoke_push_notification(doc);
// func.events.validate(SESSION_ID, "notification_received", 0);
// });
// if (message.tap) {
// console.log("Tapped in " + message.tap);
// if (doc.push_notification_event_id) {
// func.events.validate(
// SESSION_ID,
// "user_defined",
// 0,
// doc.push_notification_event_id,
// null,
// "program",
// null,
// null,
// null,
// null,
// null,
// 0
// );
// }
// }
// }
// console.dir(message);
// },
// function (error) {
// console.error(error);
// }
// );
// } catch (e) {
// console.warn(e);
// callbackP();
// }
// };
func.UI.main = {};
func.UI.main.clear_SYNC_INTERVAL = function () {
// no-op — idle timeout listeners now managed natively
};
func.UI.main.embed_prog_execute = async function (SESSION_ID, prog) {
var _session = SESSION_OBJ[SESSION_ID];
// await func.utils.TREE_OBJ.get(SESSION_ID, prog);
const _prog = await func.utils.VIEWS_OBJ.get(SESSION_ID, prog);
const get_params_obj = function () {
// get in parameters
var params_obj = {};
if (_prog?.properties?.progParams) {
for (const [key, val] of Object.entries(_prog.properties.progParams)) {
// if (val.data.dir !== 'in') continue;
if (typeof _session.url_params?.[val.data.parameter] !== 'undefined') {
params_obj[val.data.parameter] = _session.url_params?.[val.data.parameter];
continue;
}
console.warn(`Warning: Program ${_prog.properties.menuName} expected In parameter: ${val.data.parameter} but received null instead`);
}
}
return params_obj;
};
let screen_ret = await func.utils.get_screen_obj(SESSION_ID, prog);
if (screen_ret) {
let ret_init = await func.runtime.ui.init_screen({
SESSION_ID,
prog_id: prog,
sourceScreenP: null,
callingDataSource_objP: null,
$callingContainerP: func.runtime.ui.get_session_root(SESSION_ID),
triggerIdP: null,
rowIdP: null,
jobNoP: null,
is_panelP: null,
parameters_obj_inP: get_params_obj(),
source_functionP: 'call_embed',
});
func.runtime.platform.set_title(screen_ret.properties.menuTitle);
return;
}
console.error('Program not exist', prog);
func.UI.utils.progressScreen.show(SESSION_ID, 'Program not exist', null, true);
// }
};
func.UI.main.embed_loader = async function (SESSION_ID) {
var _session = SESSION_OBJ[SESSION_ID];
const platform = func.runtime.platform;
const browser_hash = platform.get_url_hash();
var hash = '';
if (browser_hash) hash = browser_hash.substr(1);
_session.SYS_GLOBAL_STR_BROWSER_HASH_ID = hash;
_session.SYS_GLOBAL_STR_BROWSER_TITLE = platform.get_document()?.title || '';
const init_system_ds = async function () {
if (!['main'].includes(_session.opt.app_computing_mode)) {
await func.index.new_webworker(SESSION_ID, { menuName: 'Main' });
// await func.index.call_worker(SESSION_ID, {
// service: "create_webworker_globals",
// data: { ds_data: _session.DS_GLB[0], session_id: SESSION_ID },
// });
}
const ret = await func.datasource.create(SESSION_ID, 'system');
/////////// moved to the datasource callback to allow sync on_load events to run at worker
// if (!["main"].includes(_session.opt.app_computing_mode)) {
// // await func.index.new_webworker(SESSION_ID, { menuName: "Main" });
// await func.index.call_worker(SESSION_ID, {
// service: "create_webworker_globals",
// data: { ds_data: _session.DS_GLB[0], session_id: SESSION_ID },
// });
// }
func.index.set_ds_0_proxy(SESSION_ID);
return ret;
// });
};
const set_SYS_GLOBAL_KEYS_STATE = async function (SESSION_ID, e, state) {
if (!_session?.DS_GLB?.[0]) return;
if (e.keyCode !== 16 && e.keyCode !== 17 && e.keyCode !== 18 && e.keyCode !== 91) {
return;
}
var data = {};
if (e.keyCode === 17) {
data.SYS_GLOBAL_BOL_CONTROL_KEY_STATE = state;
}
if (e.keyCode === 16) {
data.SYS_GLOBAL_BOL_SHIFT_KEY_STATE = state;
}
if (e.keyCode === 18) {
data.SYS_GLOBAL_BOL_ALT_KEY_STATE = state;
}
if (e.keyCode === 91) {
data.SYS_GLOBAL_BOL_COMMAND_KEY_STATE = state;
}
var datasource_changes = {
[0]: {
['data_system']: data,
},
};
await func.datasource.update(SESSION_ID, datasource_changes);
};
const start_workers = async function () {
_session.WORKER_OBJ.fx = new func.utils.job_worker(SESSION_ID);
_session.WORKER_OBJ.fx.init();
};
const create_embed_container = async function () {
func.runtime.ui.ensure_embed_container(SESSION_ID);
};
const execute_PENDING_OPEN_URL_EVENTS = async function () {
if (typeof func.events.execute_PENDING_OPEN_URL_EVENTS !== 'undefined' && glb.is_cordova) {
func.events.execute_PENDING_OPEN_URL_EVENTS();
}
};
const remove_loader = async function () {
document.querySelectorAll('.loader').forEach(function (el) { el.remove(); });
const root_node = func.runtime.ui.get_first_node(_session.root_element);
if (root_node?.classList) {
root_node.classList.remove('loader_background_color');
}
};
const perform_callback = async function () {
if (_session.api_callback) {
_session.api_callback('xuda_ready', SESSION_ID, SESSION_OBJ);
}
};
const call_program = async function () {
if (_session.route_id) {
const route_obj = await func.utils.DOCS_OBJ.get(SESSION_ID, _session.route_id);
function flattenMenuItems(menu) {
let flatMenu = {};
function recurse(items) {
for (let item of items) {
flatMenu[item.id] = item;
if (item.children && item.children.length > 0) {
recurse(item.children);
}
}
}
recurse(menu);
return flatMenu;
}
const flatMenu = flattenMenuItems(route_obj.routeMenu.menu);
const menu_obj = flatMenu[_session.menu_id];
if (_session.menu_id) {
if (menu_obj) {
_session.prog_id = menu_obj.prog_id;
if (menu_obj.prog_params) {
_session.url_params = {
..._session.url_params,
...menu_obj.prog_params,
};
}
if (menu_obj.global_params) {
_session.url_params = {
..._session.url_params,
...menu_obj.global_params,
};
}
}
}
}
if (!_session.prog_id) return;
await func.utils.TREE_OBJ.get(SESSION_ID, _session.prog_id);
let screen_ret = await func.utils.get_screen_obj(SESSION_ID, _session.prog_id);
if (screen_ret) {
func.UI.main.embed_prog_execute(SESSION_ID, _session.prog_id);
} else {
console.error('Program not exist', _session.prog_id);
func.UI.utils.progressScreen.show(SESSION_ID, 'Program not exist', null, true);
}
};
const register_run_background_plugins = async function () {
if (typeof glb.SLIM_BUNDLE !== 'undefined' || glb.SLIM_BUNDLE) return;
for await (const [plugin_name, val] of Object.entries(APP_OBJ[_session.app_id].app_plugins_purchased)) {
if (val.installed && val.run_in_background && val.manifest?.['runtime.mjs']?.exist) {
try {
const plugin_runtime_src = await func.utils.get_plugin_npm_cdn(SESSION_ID, plugin_name, `${val.manifest['runtime.mjs'].dist ? 'dist/' : ''}runtime.mjs`);
if (val.manifest['runtime.mjs'].dist && val.manifest?.['runtime.mjs']?.css) {
const plugin_runtime_css_url = await func.utils.get_plugin_npm_cdn(SESSION_ID, plugin_name, 'dist/runtime.css');
func.utils.load_css_on_demand(plugin_runtime_css_url);
}
const plugin_script = await import(plugin_runtime_src);
eval(plugin_script);
let plugin_setup_script_ret = null;
if (val.manifest?.['index.mjs']?.exist) {
const plugin_setup_src = await func.utils.get_plugin_npm_cdn(SESSION_ID, plugin_name, `${val.manifest['index.mjs'].dist ? 'dist/' : ''}index.mjs`);
let plugin_setup_script = await import(plugin_setup_src);
if (plugin_setup_script) {
plugin_setup_script_ret = await func.utils.get_plugin_setup(SESSION_ID, plugin_name);
if (plugin_setup_script_ret.code < 0) {
throw plugin_setup_script_ret;
}
}
}
glb.lifecycle.plugins[plugin_name] = {
plugin_script,
setup_data: plugin_setup_script_ret?.data,
};
} catch (err) {
console.error(err);
}
}
}
};
async function updateOnlineStatus() {
if (!_session?.DS_GLB?.[0]) return;
var data = {};
if (IS_ONLINE) {
data.SYS_GLOBAL_BOL_ONLINE = 1;
} else {
data.SYS_GLOBAL_BOL_ONLINE = 0;
}
var datasource_changes = {
[0]: {
['data_system']: data,
},
};
await func.datasource.update(SESSION_ID, datasource_changes);
}
await register_run_background_plugins();
func.runtime.ui.show_root_element(SESSION_ID);
func.UI.component.create_app_root_component(SESSION_ID);
await glb.lifecycle.execute(SESSION_ID, 'beforeInit');
await start_workers();
await init_system_ds();
await glb.lifecycle.execute(SESSION_ID, 'initialized');
await create_embed_container();
await execute_PENDING_OPEN_URL_EVENTS();
await remove_loader();
await func.UI.worker.init(SESSION_ID);
await glb.lifecycle.execute(SESSION_ID, 'beforeMounted');
await call_program();
await glb.lifecycle.execute(SESSION_ID, 'mounted');
await perform_callback();
func.utils.debug.write(SESSION_ID, 'Xuda.ai started.');
await glb.lifecycle.execute(SESSION_ID, 'systemReady');
/////////////////////////////
// bridge DOM keyboard events into platform event bus
if (func.runtime.platform.has_document()) {
document.addEventListener('keydown', function (e) {
func.runtime.platform.emit('keydown', e);
});
document.addEventListener('keyup', function (e) {
func.runtime.platform.emit('keyup', e);
});
}
func.runtime.platform.on('keydown', function (e) {
set_SYS_GLOBAL_KEYS_STATE(SESSION_ID, e, 1);
});
func.runtime.platform.on('keyup', function (e) {
set_SYS_GLOBAL_KEYS_STATE(SESSION_ID, e, 0);
});
await updateOnlineStatus();
platform.add_window_listener('online', updateOnlineStatus);
platform.add_window_listener('offline', updateOnlineStatus);
console.log('xuda.ai system ready.');
platform.dispatch_body_event(glb.system_ready_event);
};
func.UI.main.set_custom_css = function (SESSION_ID, callbackP) {
const css = SESSION_OBJ[SESSION_ID].DS_GLB[0].data_system?.['SYS_GLOBAL_STR_SITE_CSS'];
if (css) {
func.runtime.platform.inject_css(css);
}
callbackP();
};
func.index = {};
////////////////////////////////////
if (document.readyState === 'loading') {
document.addEventListener('DOMContentLoaded', function () {
func.index.init_document_listeners();
func.UI.utils.indicator.worker.normal();
func.index.init_service_workers();
});
} else {
setTimeout(function () {
func.index.init_document_listeners();
func.UI.utils.indicator.worker.normal();
func.index.init_service_workers();
}, 0);
}
function xuda(...args) {
const platform = func.runtime.platform;
const runtime_location = platform.get_location();
let element = null;
let opt = {};
let callback = null;
const report_bootstrap_issue = function (type, message) {
if (func.utils?.report_issue) {
func.utils.report_issue('', {
code: 'RUN_MSG_GEN_010',
title: 'Runtime Bootstrap Configuration Error',
source: 'xuda',
message,
type,
skip_log: true,
});
return;
}
const console_method = type === 'W' ? 'warn' : type === 'I' ? 'log' : 'error';
console[console_method](`XUDA ${console_method.toUpperCase()} RUN_MSG_GEN_010`, message);
};
for (const arg of args) {
if (platform.is_html_element(arg)) {
// Detect the element (e.g., <div>, <span>, etc.)
element = arg;
} else if (typeof arg === 'object' && arg !== null && !Array.isArray(arg)) {
// Detect options (non-null object that's not an array)
opt = arg;
} else if (typeof arg === 'function') {
// Detect the callback function
callback = arg;
}
}
if (!element) {
if (typeof glb.SLIM_BUNDLE === 'undefined' || !glb.SLIM_BUNDLE) {
report_bootstrap_issue('E', 'Xuda Error - element argument is empty');
return;
}
element = 'body';
report_bootstrap_issue('W', 'root element set to body');
}
if (typeof element === 'string' ? !document.querySelector(element) : !element) {
report_bootstrap_issue('E', 'Xuda Error - element not found');
return;
}
if (typeof opt === 'undefined') {
report_bootstrap_issue('E', 'Xuda Error - opt argument is undefined');
return;
}
if (typeof opt !== 'object') {
report_bootstrap_issue('E', 'Xuda Error - opt argument is not an object');
return;
}
if (!opt.ssr_payload && func.runtime.platform.get_window()?.__XUDA_SSR__) {
opt.ssr_payload = func.runtime.platform.get_window().__XUDA_SSR__;
}
func.runtime.render.apply_runtime_bootstrap_defaults(opt);
glb.URL_PARAMS = func.common.getJsonFromUrl(platform.get_url_href());
glb.worker_type = 'Worker';
if (opt.debug_js) {
glb.debug_js = true;
if ((runtime_location?.host?.includes('localhost') || runtime_location?.host?.includes('127.0.0.1')) && typeof glb.SLIM_BUNDLE === 'undefined' && typeof glb.CODE_BUNDLE === 'undefined') {
glb.worker_type = 'Dev';
} else {
glb.worker_type = 'Debug';
}
}
const call_xuda = async function () {
const _instance_id = Date.now().toString() + Math.round(Math.random() * 10000).toString();
const _api_callback = callback;
const create_index_html = function () {
func.runtime.ui.ensure_app_shell(SESSION_ID, _session.domain);
};
const device_ready = async function () {
return new Promise(function (resolve, reject) {
if (!func.utils.get_device()) {
return resolve();
}
platform.get_document().addEventListener(
'deviceready',
function () {
glb.is_cordova = true;
resolve();
},
false,
);
});
};
const get_fingerprint_component = async function () {
return new Promise(function (resolve, reject) {
Fingerprint2.get(function (components) {
resolve(components);
});
});
};
const get_session_id = function () {
return func.runtime.session.get_fingerprint(components, _instance_id);
};
const get_fingerprint = function () {
return func.runtime.session.get_fingerprint(components);
};
const init_SESSION = function () {
return func.runtime.session.create_state(SESSION_ID, {
opt,
root_element: typeof element === 'string' ? document.querySelector(element) : element,
worker_type: glb.worker_type,
api_callback: _api_callback,
code_bundle: glb.CODE_BUNDLE,
slim_bundle: glb.SLIM_BUNDLE,
url_params: opt.url_params,
});
};
const set_SESSION = async function () {
for await (const key of ['gtp_token', 'app_token', 'prog_id', 'domain', 'engine_mode', 'crawler', 'app_id', 'route_id', 'menu_id', 'local_live_preview', 'project_data']) {
_session[key] = func.UI.utils.get_url_attribute(SESSION_ID, key);
// set defaults
if (!_session[key]) {
func.runtime.session.set_default_value(_session, key);
}
// set exceptions
switch (key) {
case 'domain':
if (_session[key].includes('localhost') || _session[key].includes('127.0.0.1')) {
const getSubdomain = (url) => {
let domain = url;
if (url.includes('://')) {
domain = url.split('://')[1];
}
let subdomain = '';
if (!_session[key].includes('127.0.0.1')) {
subdomain = domain.split('.')[0];
}
return subdomain;
};
_session[key] = getSubdomain(_session[key]) ? getSubdomain(_session[key]) + '.xuda.ai' : 'xuda.ai';
}
break;
case 'project_data': {
if (typeof glb.SLIM_BUNDLE !== 'undefined' || glb.SLIM_BUNDLE) {
const { root_element } = _session;
if (!_session[key]) {
_session[key] = {};
}
if (!_session[key].programs) {
_session[key].programs = {};
}
if (!_session[key].globals) {
_session[key].globals = {
_id: 'globals',
progDataSource: {},
properties: { menuType: 'globals' },
studio_meta: {},
progEvents: [],
progFields: [],
};
}
const _templates = document.querySelectorAll('template');
if (_templates.length) {
const module = await func.common.get_module(SESSION_ID, 'xuda-cli-plugin-html-parser-module.esm.mjs');
_templates.forEach(function (el, idx) {
const _id = el.getAttribute('id') || 'template_' + idx.toString();
if (!_session[key].programs[_id]) {
_session[key].programs[_id] = {
_id,
progDataSource: {},
properties: { menuType: 'component', renderType: 'form' },
studio_meta: {},
progEvents: [],
progFields: [],
};
}
if (el.innerHTML) {
window.xudaStringify = module.xudaStringify;
const progUi = module.xudaPrase(el.innerHTML);
_session[key].programs[_id].progUi = progUi?.[0]?.children || [];
}
});
if (!_session.prog_id) {
_session.prog_id = _templates[0]?.getAttribute('id') || 'template_0';
}
root_element.innerHTML = '';
// if (!_session[key].programs._default) {
// _session[key].programs._default = {
// _id: "_default",
// progDataSource: {},
// properties: { menuType: "component", renderType: "form" },
// studio_meta: {},
// progEvents: [],
// progFields: [],
// };
// }
// if ($("template").html()) {
// const module = await func.common.get_module(
// SESSION_ID,
// "xuda-cli-plugin-html-parser-module.esm.js"
// );
// window.xudaStringify = module.xudaStringify;
// const progUi = module.xudaPrase($("template").html());
// const { root_element } = _session;
// $(root_element).empty();
// _session[key].programs._default.progUi =
// progUi?.[0]?.children || [];
// _session.prog_id = "_default";
// }
}
}
break;
}
default:
break;
}
}
// );
_session.crawler = opt.crawler;
};
const set_SYS_GLOBAL_OBJ_CLIENT_INFO = function () {
func.runtime.session.populate_client_info(_session, components);
};
const init_globals = function () {
const { app_id, worker_type } = _session;
if (worker_type !== 'Worker') {
glb.DEBUG_MODE = true;
}
SESSION_OBJ[SESSION_ID].dataSourceSessionGlobal = -1;
PROJECT_OBJ[app_id] = {};
DOCS_OBJ[app_id] = {};
glb.APP_INFO[app_id] = {};
glb.ROOT_ELEMENT_ATTRIBUTES = func.UI.utils.get_root_element_attributes(SESSION_ID);
DATASOURCE_INTERVALS[SESSION_ID] = {};
// if (glb.DEBUG_MODE) glb.WORKER_TIMEOUT = 10000;
};
// const set_ViewUITreeObj_data = async function () {
// const { prog_id, project_data, root_element } = _session;
// if (!project_data) return;
// if (prog_id) {
// return;
// let tree_properties = project_data.programs[prog_id]?.properties;
// tree_properties.id = prog_id;
// tree_properties.renderType =
// tree_properties.flow === "multi_view" ? "grid" : "form";
// tree_properties.menuType = tree_properties.type;
// }
// // if ($(root_element).html()) {
// // const module = await func.common.get_module(
// // SESSION_ID,
// // "xuda-cli-plugin-html-parser-module.esm.js"
// // );
// // window.xudaStringify = module.xudaStringify;
// // const progUi = module.xudaPrase($(root_element).html());
// // $(root_element).empty();
// // const _id = "startup_program";
// // const d = Date.now();
// // DOCS_OBJ[_session.app_id][_id] = {
// // _id,
// // stat: 3,
// // docType: "studio",
// // docDate: d,
// // ts: d,
// // studio_meta: {
// // created: d,
// // parentId: "programs",
// // },
// // properties: {
// // progParams: [],
// // menuName: _id,
// // menuTitle: _id,
// // menuType: "component",
// // renderType: "form",
// // },
// // progEvents: [],
// // progFields: [],
// // progUi,
// // };
// // _session.prog_id = _id;
// // // console.log(code);
// // // if (prog_id) {
// // // project_data.programs[prog_id].progUi = [
// // // {
// // // children: code,
// // // tagName: root_element.tagName.toLowerCase(),
// // // type: "element",
// // // },
// // // ];
// // // }
// // }
// };
const print_version_info = function () {
const version_name = `Xuda runtime ${opt.engine_mode} ${opt?.app_version || ''} Session Id: ${SESSION_ID}`;
const divider = '#'.repeat(version_name.length);
console.info(divider);
console.info(version_name);
console.info(divider);
};
const print_xuda_banner = function () {
var banner = '';
['__ ___ _ ____ _ ', '\\ \\/ / | | | _ \\ / \\ ', ' \\ /| | | | | | |/ _ \\ ', ' / \\| |_| | |_| / ___ \\ ', '/_/\\_\\\\___/|____/_/ \\_\\'].forEach((e) => {
banner += e + '\r\n';
});
console.info(banner);
};
print_xuda_banner();
await func.index.checkConnectivity();
var SESSION_ID = Date.now();
var components;
if (typeof glb.SLIM_BUNDLE === 'undefined' || !glb.SLIM_BUNDLE) {
await device_ready();
components = await get_fingerprint_component();
SESSION_ID = get_session_id();
print_version_info();
}
var _session = init_SESSION();
await set_SESSION();
create_index_html();
APP_OBJ[_session.app_id] = {};
// _session.app_id = _session.app_id;
init_globals();
// await set_ViewUITreeObj_data();
if (typeof glb.SLIM_BUNDLE !== 'undefined' && glb.SLIM_BUNDLE) {
await func.UI.main.embed_loader(SESSION_ID);
return;
}
set_SYS_GLOBAL_OBJ_CLIENT_INFO(SESSION_ID);
if (!_session.app_id) {
func.UI.utils.progressScreen.show(SESSION_ID, 'Error reading app_id', false, true);
await func.utils.report_issue(SESSION_ID, {
code: 'RUN_MSG_GEN_010',
source: 'xuda',
message: 'no app_id found',
type: 'E',
});
return;
}
const module = await func.common.get_module(SESSION_ID, 'xuda-project-loader-module.esm.js');
const db_adapter = await func.common.get_module(SESSION_ID, 'xuda-db-adapter-module.mjs');
func.db = db_adapter._db;
await module.project_loader(SESSION_ID, _session.app_id);
func.db.pouch.init_db_replication(SESSION_ID);
};
glb.system_ready_event = new Event('on_mounted');
call_xuda();
return {
on_mounted: function (fn) {
document.body.addEventListener(
'on_mounted',
(e) => {
fn();
},
false,
);
},
};
}
// func.index.on_mounted = async function (fn) {
// fn();
// };
// export const init = function (...args) {
// return xuda(args);
// };
func.index.call_worker = async function (SESSION_ID, obj, params, promiseP) {
var _session = SESSION_OBJ[SESSION_ID];
if (_session.opt.app_computing_mode === 'main') {
return;
}
return new Promise(async function (resolve, reject) {
var worker_id;
const set_promise_queue = function (worker_id) {
var t = glb.worker_queue_num++;
try {
func.runtime.workers.set_promise(SESSION_ID, worker_id, t, {
resolve: promiseP ? promiseP.resolve : resolve,
reject: promiseP ? promiseP.reject : reject,
worker_id,
});
} catch (e) {
console.log(worker_id);
}
return t;
};
const get_worker_id = function (ds) {
// return 1; // dismiss multi thread 2021 08 26
if (!_session.DS_GLB[ds]) {
if (ds == 0) {
func.utils.report_issue(SESSION_ID, {
code: 'RUN_MSG_EVT_020',
source: 'func.index.call_worker',
message: 'Error - onscreen (window,modal etc..) event cannot be invoked by on_load',
type: 'E',
});
return;
} else {
// console.error("Error - worker not found");
return;
}
}
if (ds == 0) {
return 1;
}
if (_session.DS_GLB[ds].worker_id) {
return _session.DS_GLB[ds].worker_id;
} else {
if (typeof _session.DS_GLB[ds].parentDataSourceNo !== 'undefined') {
return get_worker_id(_session.DS_GLB[ds].parentDataSourceNo);
}
}
};
if (obj.service === 'datasource_create') {
if (!params || (params && !params.done)) {
var prog_obj = await func.utils.TREE_OBJ.get(SESSION_ID, obj.data.prog_id);
if (!prog_obj || !prog_obj.dedicatedWorker) {
// MAIN WORKER
if (!Object.keys(WEB_WORKER[SESSION_ID]).length) {
worker_id = await func.index.new_webworker(
SESSION_ID,
{
menuName: 'Main',
},
obj,
);
// return; //_resolve();
} else {
if (obj.data.IS_DATASOURCE_REFRESH) {
worker_id = get_worker_id(obj.data.parentDataSourceNo);
} else {
worker_id = get_worker_id(obj.data.parentDataSourceNoP);
}
if (!worker_id) {
}
}
} else {
// DEDICATE WORKER
if (obj.data.IS_DATASOURCE_REFRESH) {
worker_id = get_worker_id(obj.data.parentDataSourceNo);
} else {
worker_id = await func.index.new_webworker(SESSION, prog_obj, obj);
return _resolve();
}
}
} else {
worker_id = params.worker_id;
}
} else {
if (params && params.worker_id) {
worker_id = params.worker_id;
} else {
worker_id = get_worker_id(obj.data.dssession);
}
if (!worker_id) worker_id = 1; //return;
}
try {
var msg = obj;
msg.worker_id = worker_id;
if (!worker_id) {
console.warn('missing worker_id');
}
msg.promise_queue_id = set_promise_queue(worker_id);
if (!WEB_WORKER[SESSION_ID][worker_id]) {
// worker does not exist on globals on_load
return resolve();
}
msg = JSON.stringify(obj, func.utils.clean_stringify_null, '\t');
let msg_obj = JSON.parse(msg);
if (!func.runtime.workers.is_server_transport(_session)) {
msg_obj.data = JSON.stringify(msg_obj.data);
}
func.runtime.workers.send_message(SESSION_ID, worker_id, _session, msg_obj, WEBSOCKET_PROCESS_PID);
} catch (e) {
console.error(e);
return reject(e);
}
});
};
func.index.init_SCREEN_BLOCKER = async function (SESSION_ID) {
const get_loader = async function () {
if (func.runtime.session.is_slim(SESSION_ID) || typeof UI_FRAMEWORK_PLUGIN?.loader !== 'function') {
return {
dismiss: function () {},
};
}
return await UI_FRAMEWORK_PLUGIN.loader(LOADER_TEXT);
};
setInterval(async function () {
if (glb.CURRENT_APP_LOADING || (!LOADER_ACTIVE && xu_isEmpty(SCREEN_BLOCKER_OBJ))) {
return;
}
glb.CURRENT_APP_LOADING = 1;
const loader = await get_loader();
glb.CURRENT_APP_LOADING = loader;
var interval = setInterval(function () {
if (xu_isEmpty(SCREEN_BLOCKER_OBJ) && !LOADER_ACTIVE) {
if (glb.CURRENT_APP_LOADING) {
glb.CURRENT_APP_LOADING.dismiss();
}
clearInterval(interval);
glb.CURRENT_APP_LOADING = null;
}
}, 100);
}, 1000);
};
func.index.init_document_listeners = function () {
const platform = func.runtime.platform;
if (!func.index._global_error_listeners_attached) {
const report_global_error = function (payload) {
const SESSION_ID = Object.keys(SESSION_OBJ || {})[0] || '';
if (!func.utils?.report_issue) return;
func.utils.report_issue(SESSION_ID, {
code: 'RUN_MSG_GEN_000',
source: payload.source,
message: payload.message,
type: payload.type || 'E',
err: payload.err,
details: payload.details,
skip_log: !SESSION_ID,
});
};
window.addEventListener('error', function (event) {
report_global_error({
source: 'window.error',
message: event.message || 'Unhandled window error',
err: event.error,
details: {
filename: event.filename,
lineno: event.lineno,
colno: event.colno,
},
});
});
window.addEventListener('unhandledrejection', function (event) {
const reason = event.reason;
report_global_error({
code: 'RUN_MSG_GEN_020',
source: 'window.unhandledrejection',
message: reason?.message || func.utils._stringify_issue_message(reason) || 'Unhandled promise rejection',
err: reason instanceof Error ? reason : null,
details: {
reason_type: typeof reason,
reason: func.utils._serialize_issue_value(reason),
},
});
});
func.index._global_error_listeners_attached = true;
}
document.addEventListener('keydown', function (event) {
CLIENT_ACTIVITY_TS = Date.now();
var keys = {
72: {
key: 'h',
name: 'Help',
fx: function () {
let SESSION_ID = Object.keys(SESSION_OBJ)[0];
let _session = SESSION_OBJ[SESSION_ID];
let app_id = _session.app_id;
if (!_session.opt.enable_utility_screen) return;
func.UI.utils.progressScreen.show(
SESSION_ID,
`
<center>Utility Screen</center>
<div class="help_screen">
<button name="hard_reload">
<svg xmlns="http://www.w3.org/2000/svg" class="icon icon-tabler icon-tabler-refresh" width="24" height="24" viewBox="0 0 24 24" stroke-width="2" stroke="currentColor" fill="none" stroke-linecap="round" stroke-linejoin="round" style="enable-background:new 0 0 473.677 473.677; xml:space="preserve" >
<path stroke="none" d="M0 0h24v24H0z" fill="none"></path>
<path d="M20 11a8.1 8.1 0 0 0 -15.5 -2m-.5 -4v4h4"></path>
<path d="M4 13a8.1 8.1 0 0 0 15.5 2m.5 4v-4h-4"></path>
</svg><h3 style="text-align: center;display: flex;align-items: center;gap: 10px;">Clean cache & Reload <svg class="w-6 h-6" fill="none" stroke="currentColor" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M17 8l4 4m0 0l-4 4m4-4H3"></path></svg></h3>
</button>
<button name="reset_worker">
<svg xmlns="http://www.w3.org/2000/svg" class="icon icon-tabler icon-tabler-activity" width="24" height="24" viewBox="0 0 24 24" stroke-width="2" stroke="currentColor" fill="none" stroke-linecap="round" stroke-linejoin="round" style="enable-background:new 0 0 473.677 473.677; xml:space="preserve">
<path stroke="none" d="M0 0h24v24H0z" fill="none"></path>
<path d="M3 12h4l3 8l4 -16l3 8h4"></path>
</svg>
<h3 style="text-align: center;display: flex;align-items: center;gap: 10px;">Reset worker<svg class="w-6 h-6" fill="none" stroke="currentColor" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M17 8l4 4m0 0l-4 4m4-4H3"></path></svg></h3>
</button>
<button name="get_support">
<svg xmlns="http://www.w3.org/2000/svg" class="icon icon-tabler icon-tabler-lifebuoy" width="24" height="24" viewBox="0 0 24 24" stroke-width="2" stroke="currentColor" fill="none" stroke-linecap="round" stroke-linejoin="round" xml:space="preserve">
<path stroke="none" d="M0 0h24v24H0z" fill="none"></path>
<path d="M12 12m-4 0a4 4 0 1 0 8 0a4 4 0 1 0 -8 0"></path>
<path d="M12 12m-9 0a9 9 0 1 0 18 0a9 9 0 1 0 -18 0"></path>
<path d="M15 15l3.35 3.35"></path>
<path d="M9 15l-3.35 3.35"></path>
<path d="M5.65 5.65l3.35 3.35"></path>
<path d="M18.35 5.65l-3.35 3.35"></path>
</svg>
<h3 style="text-align: center;display: flex;align-items: center;gap: 10px;">Get support ${
SUPPORT_PEER ? '(in session, click to cancel)' : ''
}<svg class="w-6 h-6" fill="none" stroke="currentColor" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M17 8l4 4m0 0l-4 4m4-4H3"></path></svg></h3>
</button>
</div>
`,
);
setTimeout(() => {
const hardReloadBtn = document.querySelector('[name="hard_reload"]');
if (hardReloadBtn) {
hardReloadBtn.onclick = async function () {
await func.index.delete_pouch(SESSION_ID);
location.reload();
};
}
const resetWorkerBtn = document.querySelector('[name="reset_worker"]');
if (resetWorkerBtn) {
resetWorkerBtn.onclick = function () {
// let session_id = Object.keys(SESSION_OBJ)[0];
_session.WORKER_OBJ.jobs[0].stat = null;
_session.WORKER_OBJ.stat = null;
func.UI.utils.progressScreen.hide(SESSION_ID);
};
}
const getSupportBtn = document.querySelector('[name="get_support"]');
if (getSupportBtn) {
getSupportBtn.onclick = async function () {
const get_support = await func.common.get_module(SESSION_ID, 'xuda-get-support-module.esm.js');
var name, subject;
const prompt_name = () => {
name = window.prompt(`Get support from your ${APP_OBJ[app_id].app_general_prop?.app_name} team, \n\nYour Name (required):`);
if (name === '') prompt_name();
};
const prompt_subject = () => {
subject = window.prompt(`When you click on "Ok," you are granting permission to ${APP_OBJ[app_id]?.app_name} team to access your browser. \n\nSubject (required):`);
if (subject === '') prompt_subject();
};
if (!SUPPORT_PEER) {
// if (
// typeof firebase !== "undefined" &&
// firebase?.auth()?.currentUser?.displayName
// ) {
// name = firebase.auth().currentUser.displayName;
// } else {
// prompt_name();
// }
try {
name = firebase.auth().currentUser.displayName;
} catch (error) {
if (_session?.USR_OBJ?.usr_name) {
name = _session.USR_OBJ.usr_name;
} else {
prompt_name();
}
}
if (name === null) return;
prompt_subject();
if (subject === null) return;
func.common.db(SESSION_ID, 'get_support', {
name,
subject,
});
setTimeout(() => {
document.body.classList.add('get_support_request');
const oldTitle = document.body.querySelector('.get_support_request_title');
if (oldTitle) oldTitle.remove();
const titleDiv = document.createElement('div');
titleDiv.className = 'get_support_request_title';
titleDiv.textContent = 'Support pending';
document.body.appendChild(titleDiv);
}, 2000);
// get_support.init_peer(SESSION_ID, name, subject);
} else {
get_support.terminate_peer(SESSION_ID);
}
func.UI.utils.progressScreen.hide(SESSION_ID);
};
}
}, 1000);
},
},
};
if (event.which === 27) {
// esc
let SESSION_ID = Object.keys(SESSION_OBJ)[0];
func.UI.utils.progressScreen.hide(SESSION_ID);
}
if (event.ctrlKey && event.shiftKey) {
if (keys[event.which]) {
keys[event.which].fx();
}
// else {
// // func.utils.alerts.toast("Invalid Key", "error");
// }
}
});
document.addEventListener('mousemove', function (e) {
CLIENT_ACTIVITY_TS = Date.now();
posX = e.pageX;
posY = e.pageY;
if (SESSION_OBJ[SESSION_ID]?.DS_GLB?.[0]) {
SESSION_OBJ[SESSION_ID].DS_GLB[0].data_system['SYS_GLOBAL_OBJ_CLIENT_INFO'].cursor_pos_x = posX;
SESSION_OBJ[SESSION_ID].DS_GLB[0].data_system['SYS_GLOBAL_OBJ_CLIENT_INFO'].cursor_pos_y = posY;
}
// }
}); //get pointer position
func.index.makeDraggable = function (el) {
CLIENT_ACTIVITY_TS = Date.now();
var isFixed = getComputedStyle(el).position === 'fixed',
adjX = 0,
adjY = 0;
var _moveHandler, _upHandler;
el.addEventListener('mousedown', function (ev) {
var rect = el.getBoundingClientRect();
if (isFixed) {
adjX = window.scrollX;
adjY = window.scrollY;
}
var ox = ev.pageX - (rect.left + window.scrollX),
oy = ev.pageY - (rect.top + window.scrollY);
var dragOffset = { x: ox, y: oy };
_moveHandler = function (ev) {
ev.preventDefault();
ev.stopPropagation();
if (isFixed) {
adjX = window.scrollX;
adjY = window.scrollY;
}
el.style.left = ev.pageX - adjX - dragOffset.x + 'px';
el.style.top = ev.pageY - adjY - dragOffset.y + 'px';
};
_upHandler = function () {
window.removeEventListener('mousemove', _moveHandler);
window.removeEventListener('mouseup', _upHandler);
};
window.addEventListener('mousemove', _moveHandler);
window.addEventListener('mouseup', _upHandler);
});
return el;
};
var heartbeat_attempts = 0;
var heartbeat_internal = setInterval(async function () {
const SESSION_ID = Object.keys(SESSION_OBJ)[0];
if (!SESSION_ID) return;
let _session = SESSION_OBJ[SESSION_ID];
if (!_session) return;
if (_session.crawler) return;
const set_idle = async function (stat) {
var datasource_changes = {
[0]: {
['data_system']: { SYS_GLOBAL_BOL_IDLE: stat },
},
};
await func.datasource.update(SESSION_ID, datasource_changes);
};
if (Date.now() - CLIENT_ACTIVITY_TS > 30000) {
set_idle(1);
} else {
set_idle(0);
}
if (_session.engine_mode === 'live_preview' || !_session.opt.enable_user_assist) {
return;
}
const ret = await func.common
.db(SESSION_ID, 'heartbeat', {
stat: Date.now() - CLIENT_ACTIVITY_TS > 30000 ? 1 : 2,
})
.catch((err) => {
heartbeat_attempts++;
console.warn(err.message);
if (heartbeat_attempts < 10) return;
clearInterval(heartbeat_internal);
});
heartbeat_attempts = 0;
if (ret?.session_stat === 3) {
await func.index.delete_pouch();
// window.location.href = `https://${_session.domain}/error?error_code=408`;
platform.reload_top_window(); //href = `https://${_session.domain}?ts=${Date.now()}`;
}
document.body.classList.remove('get_support_request');
const _reqTitle = document.body.querySelector('.get_support_request_title');
if (_reqTitle) _reqTitle.remove();
document.body.classList.remove('get_support_online');
const _onlineTitle = document.body.querySelector('.get_support_online_title');
if (_onlineTitle) _onlineTitle.remove();
if (ret?.data?.peer?.peer_status === 1) {
if (ret.data.peer.peer_regional_server) {
get_support.init_peer(SESSION_ID, ret.data.peer.peer_regional_server);
}
document.body.classList.add('get_support_request');
const oldReqTitle = document.body.querySelector('.get_support_request_title');
if (oldReqTitle) oldReqTitle.remove();
const reqDiv = document.createElement('div');
reqDiv.className = 'get_support_request_title';
reqDiv.textContent = 'Support pending';
document.body.appendChild(reqDiv);
}
if (ret?.data?.peer?.peer_status === 2) {
document.body.classList.add('get_support_online');
const oldOnlineTitle = document.body.querySelector('.get_support_online_title');
if (oldOnlineTitle) oldOnlineTitle.remove();
const onlineDiv = document.createElement('div');
onlineDiv.className = 'get_support_online_title';
onlineDiv.textContent = 'Support online';
document.body.appendChild(onlineDiv);
}
_session.res_token = ret.res_token;
}, 30000);
glb.WINDOW_LOCATION_SEARCH = platform.get_url_search();
};
func.index.checkConnectivity = async function () {
const platform = func.runtime.platform;
const endpoints = ['https://xuda.ai/favicon.ico']; //'https://www.cloudflare.com/favicon.ico',
const promises = endpoints.map((url) =>
fetch(url, { method: 'HEAD', mode: 'no-cors' })
.then(() => true)
.catch(() => false),
);
const results = await Promise.all(promises);
IS_ONLINE = results.some((result) => result === true);
// Add event listeners for online/offline events
platform.add_window_listener('online', function () {
IS_ONLINE = true;
document.body.dispatchEvent(new Event('set_db_replication_from_server'));
});
platform.add_window_listener('offline', function () {
IS_ONLINE = false;
});
};
func.index.init_service_workers = function () {
const platform = func.runtime.platform;
if (platform.has_service_worker()) {
platform.add_service_worker_listener('message', function (event) {
console.log('serviceWorker message:', event);
});
platform.register_service_worker('xuda-sw.js').then(
function (registration) {
// Registration was successful
console.log('ServiceWorker registration successful with scope: ', registration.scope);
glb.sw_registration = registration;
},
function (err) {
// registration failed :(
console.log('ServiceWorker registration failed: ', err);
},
);
}
};
func.index.delete_pouch = async function (SESSION_ID = Object.keys(SESSION_OBJ)[0]) {
const db = await func.utils.connect_pouchdb(SESSION_ID);
try {
return await db.destroy();
} catch (err) {
console.log(err);
}
};
func.index.new_webworker = async function (SESSION_ID, prog_obj, obj) {
const worker_registry = func.runtime.workers.ensure_registry(SESSION_ID);
var worker_id = Object.keys(worker_registry).length + 1;
var _session = SESSION_OBJ[SESSION_ID];
if (!_session.engine_mode === 'docker') {
ver = APP_OBJ[_session.app_id].app_version;
}
var build_id = ['live_preview', 'miniapp'].includes(_session.engine_mode) ? '' : _session.opt.app_build_id;
if (typeof XUDA_BUILD_ID !== 'undefined') {
build_id = XUDA_BUILD_ID;
}
const worker_name = func.runtime.workers.build_worker_name(glb.worker_type, _session, prog_obj, worker_id, build_id);
const init_worker_session = function (worker_id) {
const { root_element, ...sessionData } = SESSION_OBJ[SESSION_ID];
var _session = JSON.parse(JSON.stringify(sessionData));
const get_parent_ds = function (ds) {
var ds_obj = {};
if (ds && _session.DS_GLB[ds].parentDataSourceNo !== null) {
ds_obj[ds] = func.utils.clean_returned_datasource(SESSION_ID, ds);
for (const [key, val] of Object.entries(get_parent_ds(_session.DS_GLB[ds].parentDataSourceNo))) {
ds_obj[key] = val;
}
} else {
ds_obj[ds] = func.utils.clean_returned_datasource(SESSION_ID, ds);
}
return ds_obj;
};
var ds_obj = {};
// send existing datasources to the worker when initiating on demand workers
if (typeof obj?.data?.parentDataSourceNoP !== 'undefined') {
ds_obj = get_parent_ds(obj.data.parentDataSourceNoP);
}
_session.DS_GLB = {};
_session.WORKER_OBJ = {
jobs: [],
num: 1000,
stat: null,
};
var app_id = _session.app_id;
var data = {
SESSION_ID,
app_id,
APP_OBJ: APP_OBJ[app_id],
PROJECT_OBJ: PROJECT_OBJ[app_id],
DOCS_OBJ: DOCS_OBJ[app_id],
APP_INFO: glb.APP_INFO[app_id],
DEBUG_MODE: glb.DEBUG_MODE,
DEBUG_INFO_OBJ: glb.DEBUG_INFO_OBJ,
WINDOW_LOCATION_SEARCH: glb.WINDOW_LOCATION_SEARCH,
ROOT_ELEMENT_ATTRIBUTES: glb.ROOT_ELEMENT_ATTRIBUTES,
DS_GLB: ds_obj,
SESSION_INFO: JSON.parse(JSON.stringify(_session)),
session_id: SESSION_ID,
engine_mode: _session.engine_mode,
STUDIO_WEBSOCKET_CONNECTION_ID: STUDIO_WEBSOCKET_CONNECTION_ID,
};
if (_session.engine_mode === 'live_preview') {
data.DOCS_OBJ = DOCS_OBJ[app_id];
}
delete data.SESSION_INFO.root_element;
data.SESSION_INFO.worker_id = worker_id;
var ds_arr = Object.keys(_session.DS_GLB);
worker_registry[worker_id].ds_arr = ds_arr;
delete data.SESSION_INFO.DS_UI_EVENTS_GLB; // contains function produce error
func.runtime.workers.send_message(
SESSION_ID,
worker_id,
_session,
{
service: 'init',
data: func.runtime.workers.is_server_transport(_session) ? data : JSON.stringify(data),
worker_id: worker_id,
},
WEBSOCKET_PROCESS_PID,
);
};
const create_worker = async function () {
return new Promise((resolve, reject) => {
if (glb.worker_type === 'Dev') {
func.runtime.workers.set_registry_entry(SESSION_ID, worker_id, {
worker: new Worker('js/xuda_worker.js', {
name: worker_name,
}),
promise_queue: {},
});
} else {
function getWorkerURL(url) {
const content = `importScripts( "${url}" );`;
return URL.createObjectURL(new Blob([content], { type: 'text/javascript' }));
}
const _session = SESSION_OBJ[SESSION_ID];
let blob = getWorkerURL(func.common.get_url(SESSION_ID, 'dist', func.utils.get_resource_filename(['live_preview', 'miniapp'].includes(_session.engine_mode) ? '' : _session?.opt?.app_build_id, 'runtime/js/xuda_worker.js')));
func.runtime.workers.set_registry_entry(SESSION_ID, worker_id, {
worker: new Worker(blob, {
name: worker_name,
}),
promise_queue: {},
});
}
func.runtime.workers.get_registry_entry(SESSION_ID, worker_id).worker.addEventListener(
'message',
function (e) {
if (e.data.service === 'worker_ready') {
return resolve();
}
worker_functions(e);
},
false,
);
});
};
const create_websocket = async function () {
return new Promise((resolve, reject) => {
func.runtime.workers.set_registry_entry(SESSION_ID, worker_id, {
worker: RUNTIME_SERVER_WEBSOCKET,
promise_queue: {},
});
func.runtime.workers.get_registry_entry(SESSION_ID, worker_id).worker.on('message', async (e) => {
if (['deployment_server', 'http_call'].includes(e.source)) return;
worker_functions({ data: e });
});
resolve();
});
};
const worker_functions = async function (e_raw) {
return new Promise(async (resolve, reject) => {
var e = {};
e.data = e_raw.data;
if (RUNTIME_SERVER_WEBSOCKET && RUNTIME_SERVER_WEBSOCKET_CONNECTED && (!_session.opt.app_computing_mode || _session.opt.app_computing_mode === 'server')) {
WEBSOCKET_PROCESS_PID = e.data.process_pid;
}
var val = e.data.params;
var fx = {
init_done: async function () {
if (!obj) {
return _resolve();
}
},
alert: function () {
if (val[1] === 'save_on') {
func.UI.utils.save(SESSION_ID, true);
return true;
}
if (val[1] === 'save_off') {
func.UI.utils.save(SESSION_ID, false);
return true;
}
func.utils.alerts.execute(SESSION_ID, val[1], val[2], val[3], val[4]);
return _resolve();
},
progress_on: function () {
func.UI.utils.progressScreen.show(SESSION_ID, val, null);
return _resolve();
},
progress_off: function () {
func.UI.utils.progressScreen.hide();
return _resolve();
},
worker_busy_on: function () {
func.UI.utils.indicator.worker.busy();
return _resolve();
},
worker_busy_off: function () {
func.UI.utils.indicator.worker.normal();
return _resolve();
},
screen_blocker_on: function () {
func.UI.utils.screen_blocker(true, 'Worker');
return _resolve();
},
ajax_error: function () {
// location.reload();
func.utils.request_error(SESSION_ID, 'ajax', 'Session error');
return _resolve();
},
screen_blocker_off: function () {
func.UI.utils.screen_blocker(false, 'Worker');
return _resolve();
},
job: function () {
// fx.datasource_event_changes();
func.events.add_to_queue(
SESSION_ID,
val.typeP,
val.eventIdP,
val.triggerP,
val.functionP,
val.refIdP,
val.containerP,
val.elementP,
val.rowP,
null,
val.descP,
null,
null,
val.dsSessionP,
null,
null,
val.event_propertiesP,
val.calling_triggerP,
val.paramsP,
null,
null,
val.calling_trigger_prop,
val.argumentsP,
val.source_event_idP,
val.calling_job,
val.args,
null,
null,
val.event_optionsP,
);
return _resolve();
},
update_client_eventChangesResults_from_worker: async function () {
await func.datasource.update(SESSION_ID, val, true);
if (!val.worker_id) {
return;
}
fx.acknowledged_worker_with_eventChangesResults_done(val.dssession, val.worker_id);
for await (const [worker_id, ds_arr] of Object.entries(WEB_WORKER[SESSION_ID])) {
if (val.worker_id == worker_id) continue;
await func.index.call_worker(
SESSION_ID,
{
service: 'update_datasource_changes_from_client',
data: data,
},
{
worker_id: worker_id,
},
);
}
},
post_datasource: async function () {
if (typeof val.dsSessionP === 'undefined' || val.dsSessionP === null) return;
if (!SESSION_OBJ[SESSION_ID].DS_GLB[val.dsSessionP]) {
SESSION_OBJ[SESSION_ID].DS_GLB[val.dsSessionP] = val.ds_obj;
} else {
const update_existing_ds_object = function (old_obj, new_obj) {
for (const [key, val] of Object.entries(new_obj)) {
if (typeof val !== 'object') {
old_obj[key] = val2;
} else {
if (!old_obj[key]) {
old_obj[key] = val;
} else update_existing_ds_object(old_obj[key], val);
}
}
};
update_existing_ds_object(SESSION_OBJ[SESSION_ID].DS_GLB[val.dsSessionP], val.ds_obj);
}
var verify_set_parent_ds = function () {
var dsSession = val.dsSessionP;
for (const [key, val] of Object.entries(SESSION_OBJ[SESSION_ID].DS_GLB[dsSession].parent_ds_chain)) {
if (SESSION_OBJ[SESSION_ID].DS_GLB[val]) {
SESSION_OBJ[SESSION_ID].DS_GLB[dsSession].parentDataSourceNo = val;
break;
}
}
};
verify_set_parent_ds();
if (val.ds_obj.dataSourceSessionGlobal > SESSION_OBJ[SESSION_ID].dataSourceSessionGlobal) SESSION_OBJ[SESSION_ID].dataSourceSessionGlobal = val.ds_obj.dataSourceSessionGlobal;
},
return_to_data_source: function (type, dsSessionP, ds) {
var data = {
session_id: SESSION_ID,
dssession: dsSessionP,
onscreen_events_active: ds.v.onscreen_events_active,
viewEventExec_arr: JSON.stringify(ds.viewEventExec_arr),
return_to_data_source_type: type,
};
func.index.call_worker(SESSION_ID, {
service: 'return_to_data_source',
data: data,
});
},
acknowledged_worker_with_eventChangesResults_done: async function (dsSessionP, worker_id) {
var data = {
session_id: SESSION_ID,
dssession: dsSessionP,
};
await func.index.call_worker(
SESSION_ID,
{
service: 'acknowledged_worker_with_eventChangesResults_done',
data: data,
},
{
worker_id: worker_id,
},
);
return _resolve();
},
execute_onscreen_view_events: async function () {
await fx.post_datasource();
var ds = SESSION_OBJ[SESSION_ID].DS_GLB[val.dsSessionP]; //val.ds_obj;
await func.datasource.execute_onscreen_view_events(SESSION_ID, val.dsSessionP, 'onscreen events');
if (!ds.v.onscreen_events_active) return;
var type = ds.v.onscreen_events_active.type;
ds.v.onscreen_events_active = null;
fx.return_to_data_source(type, val.dsSessionP, ds);
return _resolve();
},
execute_local_db_query: async function () {
await fx.post_datasource();
const data = await func.db.get_query(SESSION_ID, val.fileIdP, val.queryP, val.dsSessionP, val.viewSourceDescP, val.sourceP, val.reduceP, val.skipP, val.limitP, val.countP, val.idsP);
var msg = {};
msg.worker_id = worker_id;
msg.data = {};
msg.service = 'return_from_db_query';
msg.data.worker_id = worker_id;
msg.data.callback_id = val.callback_id;
msg.data.session_id = SESSION_ID;
msg.data.data = data;
func.runtime.workers.send_message(SESSION_ID, worker_id, _session, msg, WEBSOCKET_PROCESS_PID);
_resolve();
},
execute_local_sava_data: async function () {
await fx.post_datasource();
const data = await func.db.save_data(SESSION_ID, val.dsSessionP, val.keyP);
var msg = {};
msg.worker_id = worker_id;
msg.data = {};
msg.service = 'return_from_sava_data';
msg.data.worker_id = worker_id;
msg.data.callback_id = val.callback_id;
msg.data.session_id = SESSION_ID;
msg.data.data = data;
func.runtime.workers.send_message(SESSION_ID, worker_id, _session, msg, WEBSOCKET_PROCESS_PID);
_resolve();
},
write_debug_log: function (params) {
func.utils.debug.write(SESSION_ID, val.data);
_resolve();
},
write_log: async function (params) {
if (SESSION_OBJ[SESSION_ID].crawler) return;
const log_payload =
typeof val.data === 'object' && val.data !== null
? val.data
: {
msg: val.data,
source: 'runtime',
log_type: 'error',
};
await func.common.db(SESSION_ID, 'write_log', {
...log_payload,
});
_resolve();
},
change_loaded_image: function (params) {
const new_image = e.data.params.data;
var imgs = document.querySelectorAll('img');
imgs.forEach(function (img) {
var src = img.src;
if (src.indexOf(new_image) > 0) {
img.setAttribute('src', src + '?ts=' + new Date().valueOf());
}
});
_resolve();
},
send_watch_to_studio_websocket: function (params) {
STUDIO_WEBSOCKET.emit('message', val);
_resolve();
},
get_doc_from_studio: async function (params) {
const module = await func.common.get_module(SESSION_ID, `xuda-progs-loader-module.mjs`);
const data = await module.get_doc_from_studio(SESSION_ID, SESSION_OBJ[SESSION_ID].app_id, params.params.doc_id);
func.index.call_worker(SESSION_ID, {
service: 'return_doc_from_studio',
data,
});
_resolve();
},
get_doc_from_websocket: async function (params) {
const module = await func.common.get_module(SESSION_ID, `xuda-progs-loader-module.mjs`);
const data = await module.get_doc_from_websocket(SESSION_ID, SESSION_OBJ[SESSION_ID].app_id, params.params.doc_id);
func.index.call_worker(SESSION_ID, {
service: 'return_doc_from_websocket',
data,
});
_resolve();
},
get_dbs_data_from_websocket: async function (params) {
const data = await func.common.get_data_from_websocket(SESSION_ID, params.params.service, params.params.data);
func.index.call_worker(SESSION_ID, {
service: 'return_dbs_data_from_websocket',
data: {
data,
websocket_queue_num: params.params.websocket_queue_num,
},
});
_resolve();
},
perform_rpi_request_from_studio: async function (params) {
const data = await func.common.db(SESSION_ID, params.params.service, params.params.data);
func.index.call_worker(SESSION_ID, {
service: 'return_rpi_request_from_studio',
data: { data: data.data, table_id: params.params.req_id },
});
_resolve();
},
refresh_document_changes_for_realtime_update: async function (params) {
await func.runtime.ui.refresh_document_changes_for_realtime_update(SESSION_ID, params.params.doc_change);
_resolve();
},
};
const get_promise_queue = function (t, worker_id) {
if (!func.runtime.workers.get_registry_entry(SESSION_ID, worker_id)) {
func.utils.report_issue(SESSION_ID, {
code: 'RUN_MSG_WRK_030',
source: 'func.index.call_worker',
message: 'worker job not found',
type: 'W',
});
return;
}
return func.runtime.workers.get_promise(SESSION_ID, worker_id, t);
};
const promise_ret = await get_promise_queue(e.data.promise_queue_id, e.data.worker_id);
const _resolve = function (params) {
if (!promise_ret) return resolve();
promise_ret.resolve(params);
setTimeout(function () {
func.runtime.workers.delete_promise(SESSION_ID, e.data.worker_id, e.data.promise_queue_id);
}, 1000);
};
if (fx[e.data.fx_to_execute]) {
return await fx[e.data.fx_to_execute](e.data);
}
if (!promise_ret) {
await func.utils.report_issue(SESSION_ID, {
code: 'RUN_MSG_GEN_000',
source: 'func.index.call_worker',
message: 'promise not found',
type: 'E',
details: {
fx_to_execute: e.data.fx_to_execute,
worker_id: e.data.worker_id,
promise_queue_id: e.data.promise_queue_id,
},
});
return;
}
if (!e.data.fx_to_execute) {
// return datasource
return _resolve(e.data.params);
}
if (e.data.fx_to_execute === 'worker_response') {
return _resolve(e.data.params);
}
});
};
if (RUNTIME_SERVER_WEBSOCKET && RUNTIME_SERVER_WEBSOCKET_CONNECTED && (!_session.opt.app_computing_mode || _session.opt.app_computing_mode === 'server')) {
await create_websocket();
} else {
await create_worker();
}
init_worker_session(worker_id);
return worker_id;
};
func.index.set_ds_0_proxy = function (SESSION_ID) {
const _session = SESSION_OBJ[SESSION_ID];
let _ds = _session.DS_GLB[0];
// const _ds = func.utils.clean_returned_datasource(SESSION_ID, dsSessionP);
function createWatchedObject(obj, onChange) {
const watchers = new WeakMap();
function createProxy(target, path = []) {
if (watchers.has(target)) {
return watchers.get(target);
}
const proxy = new Proxy(target, {
set(obj, prop, value) {
const oldValue = obj[prop];
let currentPath = [...path, prop];
// Set the new value
obj[prop] = value;
// If the new value is an object, make it observable too
if (typeof value === 'object' && value !== null) {
obj[prop] = createProxy(value, currentPath);
}
// Notify of change
// if (oldValue !== value) {
if (!xu_isEqual(value, oldValue)) {
currentPath.shift();
onChange({
path: currentPath.join('.'),
oldValue,
newValue: value,
type: 'set',
timestamp: Date.now(),
});
}
return true;
},
deleteProperty(obj, prop) {
const oldValue = obj[prop];
const currentPath = [...path, prop];
delete obj[prop];
onChange({
path: currentPath.join('.'),
oldValue,
newValue: undefined,
type: 'delete',
timestamp: Date.now(),
});
return true;
},
});
// Make nested objects observable
for (const [key, value] of Object.entries(target)) {
if (typeof value === 'object' && value !== null) {
target[key] = createProxy(value, [...path, key]);
}
}
watchers.set(target, proxy);
return proxy;
}
return createProxy(obj);
}
const watchedDs = createWatchedObject({ _ref: _ds }, async (change) => {
const { path, newValue, oldValue } = change;
// console.log('Change detected:', path);
try {
const _session = SESSION_OBJ[SESSION_ID];
let watch_path = 'data_system.' + path;
const runHandler = () => {
const { handler, once } = _session?.watchers?.[watch_path] || {};
if (handler) handler(change);
if (once) {
delete _session.watchers[watch_path];
}
};
if (_session?.watchers?.[watch_path]) {
runHandler();
} else {
watch_path = 'data_system.SYS_GLOBAL_OBJ_REFS.' + path;
runHandler();
}
if (xu_isEqual(newValue, oldValue)) return;
////////////////////////
const _refs = SESSION_OBJ[SESSION_ID].DS_GLB[0].data_system.SYS_GLOBAL_OBJ_REFS;
for (const [ref_id, val] of Object.entries(_refs)) {
const prefix = `${ref_id}.ds.`;
if (!path.includes(prefix)) continue;
const clean_path_prop = path.split(prefix)[1]; //[path.split('.')[0] === 'SYS_GLOBAL_OBJ_REFS' ? 2 : 1];
if (!clean_path_prop.includes('progDataSource')) continue;
const _ref = SESSION_OBJ[SESSION_ID].DS_GLB[0].data_system.SYS_GLOBAL_OBJ_REFS[ref_id];
if (!_ref) continue;
const _ds = _ref.ds;
const target_ds = _session.DS_GLB[_ds.dsSession];
const target_value = xu_get(target_ds, clean_path_prop);
if (xu_isEqual(target_value, newValue)) continue;
const datasource_changes = {
[_ds.dsSession]: {
['datasource_main']: {
watcher: { path: clean_path_prop, newValue },
},
},
};
await func.datasource.update(SESSION_ID, datasource_changes);
}
return;
///////////////////////
// if (path.split('.')[0] !== 'SYS_GLOBAL_OBJ_REFS') return; //SYS_GLOBAL_OBJ_REFS indicates manual update
// const ref_id = path.split('.')[1];
// if (!ref_id) return;
// const prefix = `SYS_GLOBAL_OBJ_REFS.${ref_id}.ds.`;
// if (!path.includes(prefix)) return;
// const _ref = SESSION_OBJ[SESSION_ID].DS_GLB[0].data_system.SYS_GLOBAL_OBJ_REFS[ref_id];
// if (!_ref) return;
// const _ds = _ref.ds;
// const clean_path_prop = path.replace(prefix, '');
// const target_ds = _session.DS_GLB[_ds.dsSession];
// const target_value = _.get(target_ds, clean_path_prop);
// if (target_value === newValue) return;
// const datasource_changes = {
// [_ds.dsSession]: {
// ['datasource_main']: {
// watcher: { path: path.replace(prefix_path + '.', ''), newValue },
// },
// },
// };
// await func.datasource.update(SESSION_ID, datasource_changes);
///////////////////
// return;
// if (!change.path.includes('data_system.SYS_GLOBAL_OBJ_REFS')) return;
// const ref_id = change.path.split('SYS_GLOBAL_OBJ_REFS.')[1].split('.')[0];
// if (!ref_id) return;
// const _ref = SESSION_OBJ[SESSION_ID].DS_GLB[0].data_system.SYS_GLOBAL_OBJ_REFS[ref_id];
// if (!_ref) return;
// const prefix_path = `data_system.SYS_GLOBAL_OBJ_REFS.${ref_id}.ds`;
// if (!change.path.includes(prefix_path)) return;
// const _ds = _ref.ds;
// const datasource_changes = {
// [_ds.dsSession]: {
// ['datasource_main']: {
// watcher: { path: path.replace(prefix_path + '.', ''), newValue },
// },
// },
// };
// await func.datasource.update(SESSION_ID, datasource_changes);
} catch (error) {}
});
_session.DS_GLB[0] = watchedDs._ref;
};
glb.CODE_BUNDLE=1;