@instantdb/react-common 0.22.35 → 0.22.36-experimental.drewh-cookie-sync-endpoint.18891755335.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/standalone/index.js
CHANGED
|
@@ -258,18 +258,18 @@ function Ei() {
|
|
|
258
258
|
if (Q && v && typeof Q.stack == "string") {
|
|
259
259
|
for (var E = Q.stack.split(`
|
|
260
260
|
`), W = v.stack.split(`
|
|
261
|
-
`), M = E.length - 1,
|
|
262
|
-
|
|
263
|
-
for (; M >= 1 &&
|
|
264
|
-
if (E[M] !== W[
|
|
265
|
-
if (M !== 1 ||
|
|
261
|
+
`), M = E.length - 1, D = W.length - 1; M >= 1 && D >= 0 && E[M] !== W[D]; )
|
|
262
|
+
D--;
|
|
263
|
+
for (; M >= 1 && D >= 0; M--, D--)
|
|
264
|
+
if (E[M] !== W[D]) {
|
|
265
|
+
if (M !== 1 || D !== 1)
|
|
266
266
|
do
|
|
267
|
-
if (M--,
|
|
267
|
+
if (M--, D--, D < 0 || E[M] !== W[D]) {
|
|
268
268
|
var te = `
|
|
269
269
|
` + E[M].replace(" at new ", " at ");
|
|
270
270
|
return l.displayName && te.includes("<anonymous>") && (te = te.replace("<anonymous>", l.displayName)), typeof l == "function" && et.set(l, te), te;
|
|
271
271
|
}
|
|
272
|
-
while (M >= 1 &&
|
|
272
|
+
while (M >= 1 && D >= 0);
|
|
273
273
|
break;
|
|
274
274
|
}
|
|
275
275
|
}
|
|
@@ -454,8 +454,8 @@ function Ei() {
|
|
|
454
454
|
C[k] === void 0 && (C[k] = M[k]);
|
|
455
455
|
}
|
|
456
456
|
if (E || W) {
|
|
457
|
-
var
|
|
458
|
-
E && di(C,
|
|
457
|
+
var D = typeof l == "function" ? l.displayName || l.name || "Unknown" : l;
|
|
458
|
+
E && di(C, D), W && fi(C, D);
|
|
459
459
|
}
|
|
460
460
|
return li(l, E, W, j, v, Sn.current, C);
|
|
461
461
|
}
|
|
@@ -582,9 +582,9 @@ Check the top-level render call using <` + _ + ">.");
|
|
|
582
582
|
var M;
|
|
583
583
|
l === null ? M = "null" : vt(l) ? M = "array" : l !== void 0 && l.$$typeof === n ? (M = "<" + (U(l.type) || "Unknown") + " />", E = " Did you accidentally export a JSX literal instead of a component?") : M = typeof l, S("React.jsx: type is invalid -- expected a string (for built-in components) or a class/function (for composite components) but got: %s.%s", M, E);
|
|
584
584
|
}
|
|
585
|
-
var
|
|
586
|
-
if (
|
|
587
|
-
return
|
|
585
|
+
var D = hi(l, y, _, j, k);
|
|
586
|
+
if (D == null)
|
|
587
|
+
return D;
|
|
588
588
|
if (C) {
|
|
589
589
|
var te = y.children;
|
|
590
590
|
if (te !== void 0)
|
|
@@ -612,7 +612,7 @@ React keys must be passed directly to JSX without using spread:
|
|
|
612
612
|
<%s key={someKey} {...props} />`, Ct, be, Si, be), kn[be + Ct] = !0;
|
|
613
613
|
}
|
|
614
614
|
}
|
|
615
|
-
return l === i ? _i(
|
|
615
|
+
return l === i ? _i(D) : bi(D), D;
|
|
616
616
|
}
|
|
617
617
|
}
|
|
618
618
|
function gi(l, y, _) {
|
|
@@ -666,7 +666,7 @@ function G(e) {
|
|
|
666
666
|
}
|
|
667
667
|
return G(String(e));
|
|
668
668
|
}
|
|
669
|
-
const
|
|
669
|
+
const $ = {
|
|
670
670
|
Remove: "remove",
|
|
671
671
|
Replace: "replace",
|
|
672
672
|
Add: "add"
|
|
@@ -982,12 +982,12 @@ function Mi(e, t, n, r, i) {
|
|
|
982
982
|
if (o.get(d.toString()) && a[d] !== s[d]) {
|
|
983
983
|
const c = t.concat([d]), f = ge(c, i);
|
|
984
984
|
n.push({
|
|
985
|
-
op:
|
|
985
|
+
op: $.Replace,
|
|
986
986
|
path: f,
|
|
987
987
|
// If it is a draft, it needs to be deep cloned, and it may also be non-draft.
|
|
988
988
|
value: at(a[d])
|
|
989
989
|
}), r.push({
|
|
990
|
-
op:
|
|
990
|
+
op: $.Replace,
|
|
991
991
|
path: f,
|
|
992
992
|
// If it is a draft, it needs to be deep cloned, and it may also be non-draft.
|
|
993
993
|
value: at(s[d])
|
|
@@ -996,7 +996,7 @@ function Mi(e, t, n, r, i) {
|
|
|
996
996
|
for (let d = s.length; d < a.length; d += 1) {
|
|
997
997
|
const c = t.concat([d]), f = ge(c, i);
|
|
998
998
|
n.push({
|
|
999
|
-
op:
|
|
999
|
+
op: $.Add,
|
|
1000
1000
|
path: f,
|
|
1001
1001
|
// If it is a draft, it needs to be deep cloned, and it may also be non-draft.
|
|
1002
1002
|
value: at(a[d])
|
|
@@ -1007,7 +1007,7 @@ function Mi(e, t, n, r, i) {
|
|
|
1007
1007
|
if (d) {
|
|
1008
1008
|
const c = t.concat(["length"]), f = ge(c, i);
|
|
1009
1009
|
r.push({
|
|
1010
|
-
op:
|
|
1010
|
+
op: $.Replace,
|
|
1011
1011
|
path: f,
|
|
1012
1012
|
value: s.length
|
|
1013
1013
|
});
|
|
@@ -1015,7 +1015,7 @@ function Mi(e, t, n, r, i) {
|
|
|
1015
1015
|
for (let c = a.length; s.length < c; c -= 1) {
|
|
1016
1016
|
const f = t.concat([c - 1]), h = ge(f, i);
|
|
1017
1017
|
r.push({
|
|
1018
|
-
op:
|
|
1018
|
+
op: $.Remove,
|
|
1019
1019
|
path: h
|
|
1020
1020
|
});
|
|
1021
1021
|
}
|
|
@@ -1023,11 +1023,11 @@ function Mi(e, t, n, r, i) {
|
|
|
1023
1023
|
}
|
|
1024
1024
|
function Ri({ original: e, copy: t, assignedMap: n }, r, i, s, o) {
|
|
1025
1025
|
n.forEach((u, a) => {
|
|
1026
|
-
const d = pe(e, a), c = at(pe(t, a)), f = u ? Ne(e, a) ?
|
|
1027
|
-
if (he(d, c) && f ===
|
|
1026
|
+
const d = pe(e, a), c = at(pe(t, a)), f = u ? Ne(e, a) ? $.Replace : $.Add : $.Remove;
|
|
1027
|
+
if (he(d, c) && f === $.Replace)
|
|
1028
1028
|
return;
|
|
1029
1029
|
const h = r.concat(a), p = ge(h, o);
|
|
1030
|
-
i.push(f ===
|
|
1030
|
+
i.push(f === $.Remove ? { op: f, path: p } : { op: f, path: p, value: c }), s.push(f === $.Add ? { op: $.Remove, path: p } : f === $.Remove ? { op: $.Add, path: p, value: d } : { op: $.Replace, path: p, value: d });
|
|
1031
1031
|
});
|
|
1032
1032
|
}
|
|
1033
1033
|
function $i({ original: e, copy: t }, n, r, i, s) {
|
|
@@ -1036,11 +1036,11 @@ function $i({ original: e, copy: t }, n, r, i, s) {
|
|
|
1036
1036
|
if (!t.has(u)) {
|
|
1037
1037
|
const a = n.concat([o]), d = ge(a, s);
|
|
1038
1038
|
r.push({
|
|
1039
|
-
op:
|
|
1039
|
+
op: $.Remove,
|
|
1040
1040
|
path: d,
|
|
1041
1041
|
value: u
|
|
1042
1042
|
}), i.unshift({
|
|
1043
|
-
op:
|
|
1043
|
+
op: $.Add,
|
|
1044
1044
|
path: d,
|
|
1045
1045
|
value: u
|
|
1046
1046
|
});
|
|
@@ -1050,11 +1050,11 @@ function $i({ original: e, copy: t }, n, r, i, s) {
|
|
|
1050
1050
|
if (!e.has(u)) {
|
|
1051
1051
|
const a = n.concat([o]), d = ge(a, s);
|
|
1052
1052
|
r.push({
|
|
1053
|
-
op:
|
|
1053
|
+
op: $.Add,
|
|
1054
1054
|
path: d,
|
|
1055
1055
|
value: u
|
|
1056
1056
|
}), i.unshift({
|
|
1057
|
-
op:
|
|
1057
|
+
op: $.Remove,
|
|
1058
1058
|
path: d,
|
|
1059
1059
|
value: u
|
|
1060
1060
|
});
|
|
@@ -1413,8 +1413,8 @@ function Ui(e, t, n, r, i) {
|
|
|
1413
1413
|
const d = a ? t[0] : o ? o.operated ? o.copy : o.original : e;
|
|
1414
1414
|
return o && Ut(o), i && Ee(d, d, o == null ? void 0 : o.options.updatedValues), [
|
|
1415
1415
|
d,
|
|
1416
|
-
n && a ? [{ op:
|
|
1417
|
-
r && a ? [{ op:
|
|
1416
|
+
n && a ? [{ op: $.Replace, path: [], value: t[0] }] : n,
|
|
1417
|
+
r && a ? [{ op: $.Replace, path: [], value: u }] : r
|
|
1418
1418
|
];
|
|
1419
1419
|
}
|
|
1420
1420
|
function Li(e, t) {
|
|
@@ -3825,7 +3825,7 @@ function tr(e) {
|
|
|
3825
3825
|
}, t;
|
|
3826
3826
|
}, {});
|
|
3827
3827
|
}
|
|
3828
|
-
const Kr = "v0.22.
|
|
3828
|
+
const Kr = "v0.22.36-experimental.drewh-cookie-sync-endpoint.18891755335.1";
|
|
3829
3829
|
function au(e, t) {
|
|
3830
3830
|
return {
|
|
3831
3831
|
info: e ? (...n) => console.info(...n, t()) : () => {
|
|
@@ -4277,7 +4277,7 @@ class gu {
|
|
|
4277
4277
|
this.handleClose();
|
|
4278
4278
|
}
|
|
4279
4279
|
}
|
|
4280
|
-
var
|
|
4280
|
+
var R = function(e, t, n, r) {
|
|
4281
4281
|
function i(s) {
|
|
4282
4282
|
return s instanceof n ? s : new n(function(o) {
|
|
4283
4283
|
o(s);
|
|
@@ -4496,7 +4496,7 @@ class ju {
|
|
|
4496
4496
|
throw new Error("Instant must be initialized with an appId.");
|
|
4497
4497
|
if (!je(t.appId))
|
|
4498
4498
|
throw new Error(`Instant must be initialized with a valid appId. \`${t.appId}\` is not a valid uuid.`);
|
|
4499
|
-
typeof BroadcastChannel == "function" && (this._broadcastChannel = new BroadcastChannel("@instantdb"), this._broadcastChannel.addEventListener("message", (d) =>
|
|
4499
|
+
typeof BroadcastChannel == "function" && (this._broadcastChannel = new BroadcastChannel("@instantdb"), this._broadcastChannel.addEventListener("message", (d) => R(this, void 0, void 0, function* () {
|
|
4500
4500
|
var c;
|
|
4501
4501
|
try {
|
|
4502
4502
|
if (((c = d.data) === null || c === void 0 ? void 0 : c.type) === "auth") {
|
|
@@ -4506,7 +4506,9 @@ class ju {
|
|
|
4506
4506
|
} catch (f) {
|
|
4507
4507
|
this._log.error("[error] handle broadcast channel", f);
|
|
4508
4508
|
}
|
|
4509
|
-
}))), this._initStorage(n), this._oauthCallbackResponse = this._oauthLoginInit(), this.getCurrentUser()
|
|
4509
|
+
}))), this._initStorage(n), this._oauthCallbackResponse = this._oauthLoginInit(), this.getCurrentUser().then((d) => {
|
|
4510
|
+
this.syncUserToEndpoint(d.user);
|
|
4511
|
+
}), r.getIsOnline().then((d) => {
|
|
4510
4512
|
this._isOnline = d, this._startSocket(), r.listen((c) => {
|
|
4511
4513
|
c !== this._isOnline && (this._log.info("[network] online =", c), this._isOnline = c, this._isOnline ? this._startSocket() : (this._log.info("Changing status from", this.status, "to", fe.CLOSED), this._setStatus(fe.CLOSED)));
|
|
4512
4514
|
});
|
|
@@ -4981,7 +4983,7 @@ class ju {
|
|
|
4981
4983
|
* id once, even if multiple callers call this function concurrently.
|
|
4982
4984
|
*/
|
|
4983
4985
|
getLocalId(t) {
|
|
4984
|
-
return
|
|
4986
|
+
return R(this, void 0, void 0, function* () {
|
|
4985
4987
|
const n = `localToken_${t}`, r = yield this._persister.getItem(n);
|
|
4986
4988
|
if (r)
|
|
4987
4989
|
return r;
|
|
@@ -5019,7 +5021,7 @@ class ju {
|
|
|
5019
5021
|
* @returns Promise<null | {error: {message: string}}>
|
|
5020
5022
|
*/
|
|
5021
5023
|
_oauthLoginInit() {
|
|
5022
|
-
return
|
|
5024
|
+
return R(this, void 0, void 0, function* () {
|
|
5023
5025
|
var t, n, r, i;
|
|
5024
5026
|
if (typeof window > "u" || typeof window.location > "u" || typeof URLSearchParams > "u")
|
|
5025
5027
|
return null;
|
|
@@ -5047,7 +5049,7 @@ class ju {
|
|
|
5047
5049
|
});
|
|
5048
5050
|
}
|
|
5049
5051
|
_waitForOAuthCallbackResponse() {
|
|
5050
|
-
return
|
|
5052
|
+
return R(this, void 0, void 0, function* () {
|
|
5051
5053
|
return yield this._oauthCallbackResponse;
|
|
5052
5054
|
});
|
|
5053
5055
|
}
|
|
@@ -5068,7 +5070,7 @@ class ju {
|
|
|
5068
5070
|
};
|
|
5069
5071
|
}
|
|
5070
5072
|
getAuth() {
|
|
5071
|
-
return
|
|
5073
|
+
return R(this, void 0, void 0, function* () {
|
|
5072
5074
|
const { user: t, error: n } = yield this.getCurrentUser();
|
|
5073
5075
|
if (n)
|
|
5074
5076
|
throw new ke("Could not get current user: " + n.message);
|
|
@@ -5101,7 +5103,7 @@ class ju {
|
|
|
5101
5103
|
this.connectionStatusCbs.forEach((n) => n(t));
|
|
5102
5104
|
}
|
|
5103
5105
|
setCurrentUser(t) {
|
|
5104
|
-
return
|
|
5106
|
+
return R(this, void 0, void 0, function* () {
|
|
5105
5107
|
yield this._persister.setItem(Mt, t);
|
|
5106
5108
|
});
|
|
5107
5109
|
}
|
|
@@ -5109,13 +5111,13 @@ class ju {
|
|
|
5109
5111
|
return this._currentUserCached;
|
|
5110
5112
|
}
|
|
5111
5113
|
_getCurrentUser() {
|
|
5112
|
-
return
|
|
5114
|
+
return R(this, void 0, void 0, function* () {
|
|
5113
5115
|
const t = yield this._persister.getItem(Mt);
|
|
5114
5116
|
return typeof t == "string" ? JSON.parse(t) : t;
|
|
5115
5117
|
});
|
|
5116
5118
|
}
|
|
5117
5119
|
getCurrentUser() {
|
|
5118
|
-
return
|
|
5120
|
+
return R(this, void 0, void 0, function* () {
|
|
5119
5121
|
const t = yield this._waitForOAuthCallbackResponse();
|
|
5120
5122
|
if (t != null && t.error) {
|
|
5121
5123
|
const i = { error: t.error, user: void 0 };
|
|
@@ -5126,13 +5128,13 @@ class ju {
|
|
|
5126
5128
|
});
|
|
5127
5129
|
}
|
|
5128
5130
|
_hasCurrentUser() {
|
|
5129
|
-
return
|
|
5131
|
+
return R(this, void 0, void 0, function* () {
|
|
5130
5132
|
const t = yield this._persister.getItem(Mt);
|
|
5131
5133
|
return JSON.parse(t) != null;
|
|
5132
5134
|
});
|
|
5133
5135
|
}
|
|
5134
5136
|
changeCurrentUser(t) {
|
|
5135
|
-
return
|
|
5137
|
+
return R(this, void 0, void 0, function* () {
|
|
5136
5138
|
var n;
|
|
5137
5139
|
const { user: r } = yield this.getCurrentUser();
|
|
5138
5140
|
if (!ct(r, t)) {
|
|
@@ -5145,7 +5147,21 @@ class ju {
|
|
|
5145
5147
|
}
|
|
5146
5148
|
});
|
|
5147
5149
|
}
|
|
5150
|
+
syncUserToEndpoint(t) {
|
|
5151
|
+
return R(this, void 0, void 0, function* () {
|
|
5152
|
+
this.config.endpointURI && fetch(this.config.endpointURI + "/sync-auth", {
|
|
5153
|
+
method: "POST",
|
|
5154
|
+
body: JSON.stringify({
|
|
5155
|
+
user: t
|
|
5156
|
+
}),
|
|
5157
|
+
headers: {
|
|
5158
|
+
"Content-Type": "application/json"
|
|
5159
|
+
}
|
|
5160
|
+
});
|
|
5161
|
+
});
|
|
5162
|
+
}
|
|
5148
5163
|
updateUser(t) {
|
|
5164
|
+
this.syncUserToEndpoint(t);
|
|
5149
5165
|
const n = { error: void 0, user: t };
|
|
5150
5166
|
this._currentUserCached = Object.assign({ isLoading: !1 }, n), this._dataForQueryCache = {}, this.querySubs.set((r) => (Object.keys(r).forEach((i) => {
|
|
5151
5167
|
delete r[i].result;
|
|
@@ -5159,7 +5175,7 @@ class ju {
|
|
|
5159
5175
|
});
|
|
5160
5176
|
}
|
|
5161
5177
|
signInWithMagicCode(t) {
|
|
5162
|
-
return
|
|
5178
|
+
return R(this, arguments, void 0, function* ({ email: n, code: r }) {
|
|
5163
5179
|
var i;
|
|
5164
5180
|
const s = yield this.getCurrentUser(), o = ((i = s == null ? void 0 : s.user) === null || i === void 0 ? void 0 : i.type) === "guest", u = yield Yo({
|
|
5165
5181
|
apiURI: this.config.apiURI,
|
|
@@ -5172,7 +5188,7 @@ class ju {
|
|
|
5172
5188
|
});
|
|
5173
5189
|
}
|
|
5174
5190
|
signInWithCustomToken(t) {
|
|
5175
|
-
return
|
|
5191
|
+
return R(this, void 0, void 0, function* () {
|
|
5176
5192
|
const n = yield Ho({
|
|
5177
5193
|
apiURI: this.config.apiURI,
|
|
5178
5194
|
appId: this.config.appId,
|
|
@@ -5182,7 +5198,7 @@ class ju {
|
|
|
5182
5198
|
});
|
|
5183
5199
|
}
|
|
5184
5200
|
signInAsGuest() {
|
|
5185
|
-
return
|
|
5201
|
+
return R(this, void 0, void 0, function* () {
|
|
5186
5202
|
const t = yield Jo({
|
|
5187
5203
|
apiURI: this.config.apiURI,
|
|
5188
5204
|
appId: this.config.appId
|
|
@@ -5209,7 +5225,7 @@ class ju {
|
|
|
5209
5225
|
});
|
|
5210
5226
|
}
|
|
5211
5227
|
signOut(t) {
|
|
5212
|
-
return
|
|
5228
|
+
return R(this, void 0, void 0, function* () {
|
|
5213
5229
|
const n = yield this.getCurrentUser();
|
|
5214
5230
|
this.potentiallyInvalidateToken(n, t), yield this.changeCurrentUser(null);
|
|
5215
5231
|
});
|
|
@@ -5232,7 +5248,7 @@ class ju {
|
|
|
5232
5248
|
* @param {string} [params.codeVerifier] - The code verifier used to generate the code challenge.
|
|
5233
5249
|
*/
|
|
5234
5250
|
exchangeCodeForToken(t) {
|
|
5235
|
-
return
|
|
5251
|
+
return R(this, arguments, void 0, function* ({ code: n, codeVerifier: r }) {
|
|
5236
5252
|
var i;
|
|
5237
5253
|
const s = yield this.getCurrentUser(), o = ((i = s == null ? void 0 : s.user) === null || i === void 0 ? void 0 : i.type) === "guest", u = yield Hn({
|
|
5238
5254
|
apiURI: this.config.apiURI,
|
|
@@ -5255,7 +5271,7 @@ class ju {
|
|
|
5255
5271
|
* @param {string | null | undefined} [params.nonce] - The nonce used when requesting the id_token from the external service
|
|
5256
5272
|
*/
|
|
5257
5273
|
signInWithIdToken(t) {
|
|
5258
|
-
return
|
|
5274
|
+
return R(this, arguments, void 0, function* ({ idToken: n, clientName: r, nonce: i }) {
|
|
5259
5275
|
var s;
|
|
5260
5276
|
const o = yield this.getCurrentUser(), u = (s = o == null ? void 0 : o.user) === null || s === void 0 ? void 0 : s.refresh_token, a = yield Zo({
|
|
5261
5277
|
apiURI: this.config.apiURI,
|
|
@@ -5276,10 +5292,12 @@ class ju {
|
|
|
5276
5292
|
* @returns () => void
|
|
5277
5293
|
*/
|
|
5278
5294
|
joinRoom(t, n) {
|
|
5279
|
-
|
|
5295
|
+
this._rooms[t] || (this._rooms[t] = {
|
|
5280
5296
|
isConnected: !1,
|
|
5281
5297
|
error: void 0
|
|
5282
|
-
}), this._presence[t] = this._presence[t] || {}
|
|
5298
|
+
}), this._presence[t] = this._presence[t] || {};
|
|
5299
|
+
const r = this._presence[t].result;
|
|
5300
|
+
return n && !r && (this._presence[t].result = this._presence[t].result || {}, this._presence[t].result.user = n, this._notifyPresenceSubs(t)), this._tryJoinRoom(t, n), () => {
|
|
5283
5301
|
this._cleanupRoom(t);
|
|
5284
5302
|
};
|
|
5285
5303
|
}
|
|
@@ -5406,14 +5424,14 @@ class ju {
|
|
|
5406
5424
|
// --------
|
|
5407
5425
|
// Storage
|
|
5408
5426
|
uploadFile(t, n, r) {
|
|
5409
|
-
return
|
|
5427
|
+
return R(this, void 0, void 0, function* () {
|
|
5410
5428
|
var i;
|
|
5411
5429
|
const s = yield this.getCurrentUser(), o = (i = s == null ? void 0 : s.user) === null || i === void 0 ? void 0 : i.refresh_token;
|
|
5412
5430
|
return eu(Object.assign(Object.assign({}, r), { apiURI: this.config.apiURI, appId: this.config.appId, path: t, file: n, refreshToken: o }));
|
|
5413
5431
|
});
|
|
5414
5432
|
}
|
|
5415
5433
|
deleteFile(t) {
|
|
5416
|
-
return
|
|
5434
|
+
return R(this, void 0, void 0, function* () {
|
|
5417
5435
|
var n;
|
|
5418
5436
|
const r = yield this.getCurrentUser(), i = (n = r == null ? void 0 : r.user) === null || n === void 0 ? void 0 : n.refresh_token;
|
|
5419
5437
|
return yield tu({
|
|
@@ -5427,7 +5445,7 @@ class ju {
|
|
|
5427
5445
|
// Deprecated Storage API (Jan 2025)
|
|
5428
5446
|
// ---------------------------------
|
|
5429
5447
|
upload(t, n) {
|
|
5430
|
-
return
|
|
5448
|
+
return R(this, void 0, void 0, function* () {
|
|
5431
5449
|
var r;
|
|
5432
5450
|
const i = yield this.getCurrentUser(), s = (r = i == null ? void 0 : i.user) === null || r === void 0 ? void 0 : r.refresh_token, o = t || n.name, u = yield nu({
|
|
5433
5451
|
apiURI: this.config.apiURI,
|
|
@@ -5439,7 +5457,7 @@ class ju {
|
|
|
5439
5457
|
});
|
|
5440
5458
|
}
|
|
5441
5459
|
getDownloadUrl(t) {
|
|
5442
|
-
return
|
|
5460
|
+
return R(this, void 0, void 0, function* () {
|
|
5443
5461
|
var n;
|
|
5444
5462
|
const r = yield this.getCurrentUser(), i = (n = r == null ? void 0 : r.user) === null || n === void 0 ? void 0 : n.refresh_token;
|
|
5445
5463
|
return yield iu({
|
|
@@ -17,18 +17,18 @@
|
|
|
17
17
|
*/return e.NODE_ENV!=="production"&&function(){var t=j,n=Symbol.for("react.element"),r=Symbol.for("react.portal"),i=Symbol.for("react.fragment"),s=Symbol.for("react.strict_mode"),o=Symbol.for("react.profiler"),u=Symbol.for("react.provider"),a=Symbol.for("react.context"),d=Symbol.for("react.forward_ref"),c=Symbol.for("react.suspense"),f=Symbol.for("react.suspense_list"),h=Symbol.for("react.memo"),p=Symbol.for("react.lazy"),b=Symbol.for("react.offscreen"),g=Symbol.iterator,w="@@iterator";function T(l){if(l===null||typeof l!="object")return null;var y=g&&l[g]||l[w];return typeof y=="function"?y:null}var m=t.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED;function S(l){{for(var y=arguments.length,_=new Array(y>1?y-1:0),v=1;v<y;v++)_[v-1]=arguments[v];K("error",l,_)}}function K(l,y,_){{var v=m.ReactDebugCurrentFrame,P=v.getStackAddendum();P!==""&&(y+="%s",_=_.concat([P]));var I=_.map(function(C){return String(C)});I.unshift("Warning: "+y),Function.prototype.apply.call(console[l],console,I)}}var O=!1,U=!1,W=!1,ye=!1,de=!1,Ke;Ke=Symbol.for("react.module.reference");function ut(l){return!!(typeof l=="string"||typeof l=="function"||l===i||l===o||de||l===s||l===c||l===f||ye||l===b||O||U||W||typeof l=="object"&&l!==null&&(l.$$typeof===p||l.$$typeof===h||l.$$typeof===u||l.$$typeof===a||l.$$typeof===d||l.$$typeof===Ke||l.getModuleId!==void 0))}function at(l,y,_){var v=l.displayName;if(v)return v;var P=y.displayName||y.name||"";return P!==""?_+"("+P+")":_}function k(l){return l.displayName||"Context"}function L(l){if(l==null)return null;if(typeof l.tag=="number"&&S("Received an unexpected object in getComponentNameFromType(). This is likely a bug in React. Please file an issue."),typeof l=="function")return l.displayName||l.name||null;if(typeof l=="string")return l;switch(l){case i:return"Fragment";case r:return"Portal";case o:return"Profiler";case s:return"StrictMode";case c:return"Suspense";case f:return"SuspenseList"}if(typeof l=="object")switch(l.$$typeof){case a:var y=l;return k(y)+".Consumer";case u:var _=l;return k(_._context)+".Provider";case d:return at(l,l.render,"ForwardRef");case h:var v=l.displayName||null;return v!==null?v:L(l.type)||"Memo";case p:{var P=l,I=P._payload,C=P._init;try{return L(C(I))}catch{return null}}}return null}var H=Object.assign,J=0,ue,ae,te,ct,dt,ft,lt;function ht(){}ht.__reactDisabledLog=!0;function sn(){{if(J===0){ue=console.log,ae=console.info,te=console.warn,ct=console.error,dt=console.group,ft=console.groupCollapsed,lt=console.groupEnd;var l={configurable:!0,enumerable:!0,value:ht,writable:!0};Object.defineProperties(console,{info:l,log:l,warn:l,error:l,group:l,groupCollapsed:l,groupEnd:l})}J++}}function Eu(){{if(J--,J===0){var l={configurable:!0,enumerable:!0,writable:!0};Object.defineProperties(console,{log:H({},l,{value:ue}),info:H({},l,{value:ae}),warn:H({},l,{value:te}),error:H({},l,{value:ct}),group:H({},l,{value:dt}),groupCollapsed:H({},l,{value:ft}),groupEnd:H({},l,{value:lt})})}J<0&&S("disabledDepth fell below zero. This is a bug in React. Please file an issue.")}}var on=m.ReactCurrentDispatcher,un;function pt(l,y,_){{if(un===void 0)try{throw Error()}catch(P){var v=P.stack.trim().match(/\n( *(at )?)/);un=v&&v[1]||""}return`
|
|
18
18
|
`+un+l}}var an=!1,yt;{var Au=typeof WeakMap=="function"?WeakMap:Map;yt=new Au}function Mr(l,y){if(!l||an)return"";{var _=yt.get(l);if(_!==void 0)return _}var v;an=!0;var P=Error.prepareStackTrace;Error.prepareStackTrace=void 0;var I;I=on.current,on.current=null,sn();try{if(y){var C=function(){throw Error()};if(Object.defineProperty(C.prototype,"props",{set:function(){throw Error()}}),typeof Reflect=="object"&&Reflect.construct){try{Reflect.construct(C,[])}catch(Z){v=Z}Reflect.construct(l,[],C)}else{try{C.call()}catch(Z){v=Z}l.call(C.prototype)}}else{try{throw Error()}catch(Z){v=Z}l()}}catch(Z){if(Z&&v&&typeof Z.stack=="string"){for(var A=Z.stack.split(`
|
|
19
19
|
`),q=v.stack.split(`
|
|
20
|
-
`),
|
|
21
|
-
`+A[
|
|
20
|
+
`),x=A.length-1,$=q.length-1;x>=1&&$>=0&&A[x]!==q[$];)$--;for(;x>=1&&$>=0;x--,$--)if(A[x]!==q[$]){if(x!==1||$!==1)do if(x--,$--,$<0||A[x]!==q[$]){var re=`
|
|
21
|
+
`+A[x].replace(" at new "," at ");return l.displayName&&re.includes("<anonymous>")&&(re=re.replace("<anonymous>",l.displayName)),typeof l=="function"&&yt.set(l,re),re}while(x>=1&&$>=0);break}}}finally{an=!1,on.current=I,Eu(),Error.prepareStackTrace=P}var Me=l?l.displayName||l.name:"",Se=Me?pt(Me):"";return typeof l=="function"&&yt.set(l,Se),Se}function Cu(l,y,_){return Mr(l,!1)}function ju(l){var y=l.prototype;return!!(y&&y.isReactComponent)}function bt(l,y,_){if(l==null)return"";if(typeof l=="function")return Mr(l,ju(l));if(typeof l=="string")return pt(l);switch(l){case c:return pt("Suspense");case f:return pt("SuspenseList")}if(typeof l=="object")switch(l.$$typeof){case d:return Cu(l.render);case h:return bt(l.type,y,_);case p:{var v=l,P=v._payload,I=v._init;try{return bt(I(P),y,_)}catch{}}}return""}var qe=Object.prototype.hasOwnProperty,Rr={},Dr=m.ReactDebugCurrentFrame;function _t(l){if(l){var y=l._owner,_=bt(l.type,l._source,y?y.type:null);Dr.setExtraStackFrame(_)}else Dr.setExtraStackFrame(null)}function Pu(l,y,_,v,P){{var I=Function.call.bind(qe);for(var C in l)if(I(l,C)){var A=void 0;try{if(typeof l[C]!="function"){var q=Error((v||"React class")+": "+_+" type `"+C+"` is invalid; it must be a function, usually from the `prop-types` package, but received `"+typeof l[C]+"`.This often happens because of typos such as `PropTypes.function` instead of `PropTypes.func`.");throw q.name="Invariant Violation",q}A=l[C](y,C,v,_,null,"SECRET_DO_NOT_PASS_THIS_OR_YOU_WILL_BE_FIRED")}catch(x){A=x}A&&!(A instanceof Error)&&(_t(P),S("%s: type specification of %s `%s` is invalid; the type checker function must return `null` or an `Error` but returned a %s. You may have forgotten to pass an argument to the type checker creator (arrayOf, instanceOf, objectOf, oneOf, oneOfType, and shape all require an argument).",v||"React class",_,C,typeof A),_t(null)),A instanceof Error&&!(A.message in Rr)&&(Rr[A.message]=!0,_t(P),S("Failed %s type: %s",_,A.message),_t(null))}}}var ku=Array.isArray;function cn(l){return ku(l)}function Iu(l){{var y=typeof Symbol=="function"&&Symbol.toStringTag,_=y&&l[Symbol.toStringTag]||l.constructor.name||"Object";return _}}function Mu(l){try{return xr(l),!1}catch{return!0}}function xr(l){return""+l}function $r(l){if(Mu(l))return S("The provided key is an unsupported type %s. This value must be coerced to a string before before using it here.",Iu(l)),xr(l)}var Ur=m.ReactCurrentOwner,Ru={key:!0,ref:!0,__self:!0,__source:!0},Lr,Fr;function Du(l){if(qe.call(l,"ref")){var y=Object.getOwnPropertyDescriptor(l,"ref").get;if(y&&y.isReactWarning)return!1}return l.ref!==void 0}function xu(l){if(qe.call(l,"key")){var y=Object.getOwnPropertyDescriptor(l,"key").get;if(y&&y.isReactWarning)return!1}return l.key!==void 0}function $u(l,y){typeof l.ref=="string"&&Ur.current}function Uu(l,y){{var _=function(){Lr||(Lr=!0,S("%s: `key` is not a prop. Trying to access it will result in `undefined` being returned. If you need to access the same value within the child component, you should pass it as a different prop. (https://reactjs.org/link/special-props)",y))};_.isReactWarning=!0,Object.defineProperty(l,"key",{get:_,configurable:!0})}}function Lu(l,y){{var _=function(){Fr||(Fr=!0,S("%s: `ref` is not a prop. Trying to access it will result in `undefined` being returned. If you need to access the same value within the child component, you should pass it as a different prop. (https://reactjs.org/link/special-props)",y))};_.isReactWarning=!0,Object.defineProperty(l,"ref",{get:_,configurable:!0})}}var Fu=function(l,y,_,v,P,I,C){var A={$$typeof:n,type:l,key:y,ref:_,props:C,_owner:I};return A._store={},Object.defineProperty(A._store,"validated",{configurable:!1,enumerable:!1,writable:!0,value:!1}),Object.defineProperty(A,"_self",{configurable:!1,enumerable:!1,writable:!1,value:v}),Object.defineProperty(A,"_source",{configurable:!1,enumerable:!1,writable:!1,value:P}),Object.freeze&&(Object.freeze(A.props),Object.freeze(A)),A};function Nu(l,y,_,v,P){{var I,C={},A=null,q=null;_!==void 0&&($r(_),A=""+_),xu(y)&&($r(y.key),A=""+y.key),Du(y)&&(q=y.ref,$u(y,P));for(I in y)qe.call(y,I)&&!Ru.hasOwnProperty(I)&&(C[I]=y[I]);if(l&&l.defaultProps){var x=l.defaultProps;for(I in x)C[I]===void 0&&(C[I]=x[I])}if(A||q){var $=typeof l=="function"?l.displayName||l.name||"Unknown":l;A&&Uu(C,$),q&&Lu(C,$)}return Fu(l,A,q,P,v,Ur.current,C)}}var dn=m.ReactCurrentOwner,Nr=m.ReactDebugCurrentFrame;function Ie(l){if(l){var y=l._owner,_=bt(l.type,l._source,y?y.type:null);Nr.setExtraStackFrame(_)}else Nr.setExtraStackFrame(null)}var fn;fn=!1;function ln(l){return typeof l=="object"&&l!==null&&l.$$typeof===n}function Vr(){{if(dn.current){var l=L(dn.current.type);if(l)return`
|
|
22
22
|
|
|
23
23
|
Check the render method of \``+l+"`."}return""}}function Vu(l){return""}var Wr={};function Wu(l){{var y=Vr();if(!y){var _=typeof l=="string"?l:l.displayName||l.name;_&&(y=`
|
|
24
24
|
|
|
25
|
-
Check the top-level render call using <`+_+">.")}return y}}function zr(l,y){{if(!l._store||l._store.validated||l.key!=null)return;l._store.validated=!0;var _=Wu(y);if(Wr[_])return;Wr[_]=!0;var v="";l&&l._owner&&l._owner!==dn.current&&(v=" It was passed a child from "+L(l._owner.type)+"."),Ie(l),S('Each child in a list should have a unique "key" prop.%s%s See https://reactjs.org/link/warning-keys for more information.',_,v),Ie(null)}}function Kr(l,y){{if(typeof l!="object")return;if(cn(l))for(var _=0;_<l.length;_++){var v=l[_];ln(v)&&zr(v,y)}else if(ln(l))l._store&&(l._store.validated=!0);else if(l){var P=T(l);if(typeof P=="function"&&P!==l.entries)for(var I=P.call(l),C;!(C=I.next()).done;)ln(C.value)&&zr(C.value,y)}}}function zu(l){{var y=l.type;if(y==null||typeof y=="string")return;var _;if(typeof y=="function")_=y.propTypes;else if(typeof y=="object"&&(y.$$typeof===d||y.$$typeof===h))_=y.propTypes;else return;if(_){var v=L(y);Pu(_,l.props,"prop",v,l)}else if(y.PropTypes!==void 0&&!fn){fn=!0;var P=L(y);S("Component %s declared `PropTypes` instead of `propTypes`. Did you misspell the property assignment?",P||"Unknown")}typeof y.getDefaultProps=="function"&&!y.getDefaultProps.isReactClassApproved&&S("getDefaultProps is only used on classic React.createClass definitions. Use a static property named `defaultProps` instead.")}}function Ku(l){{for(var y=Object.keys(l.props),_=0;_<y.length;_++){var v=y[_];if(v!=="children"&&v!=="key"){Ie(l),S("Invalid prop `%s` supplied to `React.Fragment`. React.Fragment can only have `key` and `children` props.",v),Ie(null);break}}l.ref!==null&&(Ie(l),S("Invalid attribute `ref` supplied to `React.Fragment`."),Ie(null))}}var qr={};function Br(l,y,_,v,P,I){{var C=ut(l);if(!C){var A="";(l===void 0||typeof l=="object"&&l!==null&&Object.keys(l).length===0)&&(A+=" You likely forgot to export your component from the file it's defined in, or you might have mixed up default and named imports.");var q=Vu();q?A+=q:A+=Vr();var
|
|
25
|
+
Check the top-level render call using <`+_+">.")}return y}}function zr(l,y){{if(!l._store||l._store.validated||l.key!=null)return;l._store.validated=!0;var _=Wu(y);if(Wr[_])return;Wr[_]=!0;var v="";l&&l._owner&&l._owner!==dn.current&&(v=" It was passed a child from "+L(l._owner.type)+"."),Ie(l),S('Each child in a list should have a unique "key" prop.%s%s See https://reactjs.org/link/warning-keys for more information.',_,v),Ie(null)}}function Kr(l,y){{if(typeof l!="object")return;if(cn(l))for(var _=0;_<l.length;_++){var v=l[_];ln(v)&&zr(v,y)}else if(ln(l))l._store&&(l._store.validated=!0);else if(l){var P=T(l);if(typeof P=="function"&&P!==l.entries)for(var I=P.call(l),C;!(C=I.next()).done;)ln(C.value)&&zr(C.value,y)}}}function zu(l){{var y=l.type;if(y==null||typeof y=="string")return;var _;if(typeof y=="function")_=y.propTypes;else if(typeof y=="object"&&(y.$$typeof===d||y.$$typeof===h))_=y.propTypes;else return;if(_){var v=L(y);Pu(_,l.props,"prop",v,l)}else if(y.PropTypes!==void 0&&!fn){fn=!0;var P=L(y);S("Component %s declared `PropTypes` instead of `propTypes`. Did you misspell the property assignment?",P||"Unknown")}typeof y.getDefaultProps=="function"&&!y.getDefaultProps.isReactClassApproved&&S("getDefaultProps is only used on classic React.createClass definitions. Use a static property named `defaultProps` instead.")}}function Ku(l){{for(var y=Object.keys(l.props),_=0;_<y.length;_++){var v=y[_];if(v!=="children"&&v!=="key"){Ie(l),S("Invalid prop `%s` supplied to `React.Fragment`. React.Fragment can only have `key` and `children` props.",v),Ie(null);break}}l.ref!==null&&(Ie(l),S("Invalid attribute `ref` supplied to `React.Fragment`."),Ie(null))}}var qr={};function Br(l,y,_,v,P,I){{var C=ut(l);if(!C){var A="";(l===void 0||typeof l=="object"&&l!==null&&Object.keys(l).length===0)&&(A+=" You likely forgot to export your component from the file it's defined in, or you might have mixed up default and named imports.");var q=Vu();q?A+=q:A+=Vr();var x;l===null?x="null":cn(l)?x="array":l!==void 0&&l.$$typeof===n?(x="<"+(L(l.type)||"Unknown")+" />",A=" Did you accidentally export a JSX literal instead of a component?"):x=typeof l,S("React.jsx: type is invalid -- expected a string (for built-in components) or a class/function (for composite components) but got: %s.%s",x,A)}var $=Nu(l,y,_,P,I);if($==null)return $;if(C){var re=y.children;if(re!==void 0)if(v)if(cn(re)){for(var Me=0;Me<re.length;Me++)Kr(re[Me],l);Object.freeze&&Object.freeze(re)}else S("React.jsx: Static children should always be an array. You are likely explicitly calling React.jsxs or React.jsxDEV. Use the Babel transform instead.");else Kr(re,l)}if(qe.call(y,"key")){var Se=L(l),Z=Object.keys(y).filter(function(Hu){return Hu!=="key"}),hn=Z.length>0?"{key: someKey, "+Z.join(": ..., ")+": ...}":"{key: someKey}";if(!qr[Se+hn]){var Yu=Z.length>0?"{"+Z.join(": ..., ")+": ...}":"{}";S(`A props object containing a "key" prop is being spread into JSX:
|
|
26
26
|
let props = %s;
|
|
27
27
|
<%s {...props} />
|
|
28
28
|
React keys must be passed directly to JSX without using spread:
|
|
29
29
|
let props = %s;
|
|
30
|
-
<%s key={someKey} {...props} />`,hn,Se,Yu,Se),qr[Se+hn]=!0}}return l===i?Ku($):zu($),$}}function qu(l,y,_){return Br(l,y,_,!0)}function Bu(l,y,_){return Br(l,y,_,!1)}var Qu=Bu,Gu=qu;De.Fragment=i,De.jsx=Qu,De.jsxs=Gu}(),De}var Yr={};Yr.NODE_ENV==="production"?gt.exports=Qr():gt.exports=Gr();var Be=gt.exports;function B(e){if(typeof e=="number")return(Math.abs(e*2654435761)>>>0).toString(16);if(typeof e=="boolean")return e?"1":"0";if(e===null)return"null";if(e===void 0)return"undefined";if(typeof e=="string"){let t=2166136261;for(let n=0;n<e.length;n++)t^=e.charCodeAt(n),t+=(t<<1)+(t<<4)+(t<<7)+(t<<8)+(t<<24),t=t>>>0;return t.toString(16)}if(Array.isArray(e)){let t=2166136261;for(let n=0;n<e.length;n++){t^=(n+1)*2654435761;const r=B(e[n]);for(let i=0;i<r.length;i++)t^=r.charCodeAt(i),t*=16777619,t=t>>>0}return t.toString(16)}if(typeof e=="object"){let t=2166136261;const n=Object.keys(e).sort();for(let r=0;r<n.length;r++){const i=n[r],s=B(i);t^=parseInt(s,16),t*=16777619,t=t>>>0;const o=B(e[i]);t^=parseInt(o,16),t*=16777619,t=t>>>0}return t.toString(16)}return B(String(e))}const R={Remove:"remove",Replace:"replace",Add:"add"},bn=Symbol.for("__MUTATIVE_PROXY_DRAFT__"),Hr=Symbol("__MUTATIVE_RAW_RETURN_SYMBOL__"),Qe=Symbol.iterator,X={mutable:"mutable",immutable:"immutable"},Tt={};function xe(e,t){return e instanceof Map?e.has(t):Object.prototype.hasOwnProperty.call(e,t)}function _n(e,t){if(t in e){let n=Reflect.getPrototypeOf(e);for(;n;){const r=Reflect.getOwnPropertyDescriptor(n,t);if(r)return r;n=Reflect.getPrototypeOf(n)}}}function wt(e){return Object.getPrototypeOf(e)===Set.prototype}function mt(e){return Object.getPrototypeOf(e)===Map.prototype}function ee(e){var t;return(t=e.copy)!==null&&t!==void 0?t:e.original}function _e(e){return!!E(e)}function E(e){return typeof e!="object"?null:e==null?void 0:e[bn]}function St(e){var t;const n=E(e);return n?(t=n.copy)!==null&&t!==void 0?t:n.original:e}function ie(e,t){if(!e||typeof e!="object")return!1;let n;return Object.getPrototypeOf(e)===Object.prototype||Array.isArray(e)||e instanceof Map||e instanceof Set||!!(t!=null&&t.mark)&&((n=t.mark(e,X))===X.immutable||typeof n=="function")}function gn(e,t=[]){if(Object.hasOwnProperty.call(e,"key")){const n=e.parent.copy,r=E(fe(n,e.key));if(r!==null&&(r==null?void 0:r.original)!==e.original)return null;const i=e.parent.type===3,s=i?Array.from(e.parent.setMap.keys()).indexOf(e.key):e.key;if(!(i&&n.size>s||xe(n,s)))return null;t.push(s)}if(e.parent)return gn(e.parent,t);t.reverse();try{Jr(e.copy,t)}catch{return null}return t}function ge(e){return Array.isArray(e)?1:e instanceof Map?2:e instanceof Set?3:0}function fe(e,t){return ge(e)===2?e.get(t):e[t]}function $e(e,t,n){ge(e)===2?e.set(t,n):e[t]=n}function vt(e,t){const n=E(e);return(n?ee(n):e)[t]}function le(e,t){return e===t?e!==0||1/e===1/t:e!==e&&t!==t}function Ot(e){if(e)for(;e.finalities.revoke.length>0;)e.finalities.revoke.pop()()}function Te(e,t){return t?e:[""].concat(e).map(n=>{const r=`${n}`;return r.indexOf("/")===-1&&r.indexOf("~")===-1?r:r.replace(/~/g,"~0").replace(/\//g,"~1")}).join("/")}function Jr(e,t){for(let n=0;n<t.length-1;n+=1){const r=t[n];if(e=fe(ge(e)===3?Array.from(e):e,r),typeof e!="object")throw new Error(`Cannot resolve patch at '${t.join("/")}'.`)}return e}function Zr(e){const t=Object.create(Object.getPrototypeOf(e));return Reflect.ownKeys(e).forEach(n=>{let r=Reflect.getOwnPropertyDescriptor(e,n);if(r.enumerable&&r.configurable&&r.writable){t[n]=e[n];return}r.writable||(r.writable=!0,r.configurable=!0),(r.get||r.set)&&(r={configurable:!0,writable:!0,enumerable:r.enumerable,value:e[n]}),Reflect.defineProperty(t,n,r)}),t}const Xr=Object.prototype.propertyIsEnumerable;function Tn(e,t){let n;if(Array.isArray(e))return Array.prototype.concat.call(e);if(e instanceof Set){if(!wt(e)){const r=Object.getPrototypeOf(e).constructor;return new r(e.values())}return Set.prototype.difference?Set.prototype.difference.call(e,new Set):new Set(e.values())}else if(e instanceof Map){if(!mt(e)){const r=Object.getPrototypeOf(e).constructor;return new r(e)}return new Map(e)}else if(t!=null&&t.mark&&(n=t.mark(e,X),n!==void 0)&&n!==X.mutable){if(n===X.immutable)return Zr(e);if(typeof n=="function"){if(t.enablePatches||t.enableAutoFreeze)throw new Error("You can't use mark and patches or auto freeze together.");return n()}throw new Error(`Unsupported mark result: ${n}`)}else if(typeof e=="object"&&Object.getPrototypeOf(e)===Object.prototype){const r={};return Object.keys(e).forEach(i=>{r[i]=e[i]}),Object.getOwnPropertySymbols(e).forEach(i=>{Xr.call(e,i)&&(r[i]=e[i])}),r}else throw new Error("Please check mark() to ensure that it is a stable marker draftable function.")}function z(e){e.copy||(e.copy=Tn(e.original,e.options))}function Ue(e){if(!ie(e))return St(e);if(Array.isArray(e))return e.map(Ue);if(e instanceof Map){const n=Array.from(e.entries()).map(([r,i])=>[r,Ue(i)]);if(!mt(e)){const r=Object.getPrototypeOf(e).constructor;return new r(n)}return new Map(n)}if(e instanceof Set){const n=Array.from(e).map(Ue);if(!wt(e)){const r=Object.getPrototypeOf(e).constructor;return new r(n)}return new Set(n)}const t=Object.create(Object.getPrototypeOf(e));for(const n in e)t[n]=Ue(e[n]);return t}function Ge(e){return _e(e)?Ue(e):e}function ce(e){var t;e.assignedMap=(t=e.assignedMap)!==null&&t!==void 0?t:new Map,e.operated||(e.operated=!0,e.parent&&ce(e.parent))}function wn(){throw new Error("Cannot modify frozen object")}function ve(e,t,n,r,i){{n=n??new WeakMap,r=r??[],i=i??[];const o=n.has(e)?n.get(e):e;if(r.length>0){const u=r.indexOf(o);if(o&&typeof o=="object"&&u!==-1)throw r[0]===o?new Error("Forbids circular reference"):new Error(`Forbids circular reference: ~/${i.slice(0,u).map((a,d)=>{if(typeof a=="symbol")return`[${a.toString()}]`;const c=r[d];return typeof a=="object"&&(c instanceof Map||c instanceof Set)?Array.from(c.keys()).indexOf(a):a}).join("/")}`);r.push(o),i.push(t)}else r.push(o)}if(Object.isFrozen(e)||_e(e)){r.pop(),i.pop();return}switch(ge(e)){case 2:for(const[u,a]of e)ve(u,u,n,r,i),ve(a,u,n,r,i);e.set=e.clear=e.delete=wn;break;case 3:for(const u of e)ve(u,u,n,r,i);e.add=e.clear=e.delete=wn;break;case 1:Object.freeze(e);let o=0;for(const u of e)ve(u,o,n,r,i),o+=1;break;default:Object.freeze(e),Object.keys(e).forEach(u=>{const a=e[u];ve(a,u,n,r,i)})}r.pop(),i.pop()}function Et(e,t){const n=ge(e);if(n===0)Reflect.ownKeys(e).forEach(r=>{t(r,e[r],e)});else if(n===1){let r=0;for(const i of e)t(r,i,e),r+=1}else e.forEach((r,i)=>t(i,r,e))}function mn(e,t,n){if(_e(e)||!ie(e,n)||t.has(e)||Object.isFrozen(e))return;const r=e instanceof Set,i=r?new Map:void 0;if(t.add(e),Et(e,(s,o)=>{var u;if(_e(o)){const a=E(o);z(a);const d=!((u=a.assignedMap)===null||u===void 0)&&u.size||a.operated?a.copy:a.original;$e(r?i:e,s,d)}else mn(o,t,n)}),i){const s=e,o=Array.from(s);s.clear(),o.forEach(u=>{s.add(i.has(u)?i.get(u):u)})}}function ei(e,t){const n=e.type===3?e.setMap:e.copy;e.finalities.revoke.length>1&&e.assignedMap.get(t)&&n&&mn(fe(n,t),e.finalities.handledSet,e.options)}function At(e){e.type===3&&e.copy&&(e.copy.clear(),e.setMap.forEach(t=>{e.copy.add(St(t))}))}function Ct(e,t,n,r){if(e.operated&&e.assignedMap&&e.assignedMap.size>0&&!e.finalized){if(n&&r){const s=gn(e);s&&t(e,s,n,r)}e.finalized=!0}}function jt(e,t,n,r){const i=E(n);i&&(i.callbacks||(i.callbacks=[]),i.callbacks.push((s,o)=>{var u;const a=e.type===3?e.setMap:e.copy;if(le(fe(a,t),n)){let d=i.original;i.copy&&(d=i.copy),At(e),Ct(e,r,s,o),e.options.enableAutoFreeze&&(e.options.updatedValues=(u=e.options.updatedValues)!==null&&u!==void 0?u:new WeakMap,e.options.updatedValues.set(d,i.original)),$e(a,t,d)}}),e.options.enableAutoFreeze&&i.finalities!==e.finalities&&(e.options.enableAutoFreeze=!1)),ie(n,e.options)&&e.finalities.draft.push(()=>{const s=e.type===3?e.setMap:e.copy;le(fe(s,t),n)&&ei(e,t)})}function ti(e,t,n,r,i){let{original:s,assignedMap:o,options:u}=e,a=e.copy;a.length<s.length&&([s,a]=[a,s],[n,r]=[r,n]);for(let d=0;d<s.length;d+=1)if(o.get(d.toString())&&a[d]!==s[d]){const c=t.concat([d]),f=Te(c,i);n.push({op:R.Replace,path:f,value:Ge(a[d])}),r.push({op:R.Replace,path:f,value:Ge(s[d])})}for(let d=s.length;d<a.length;d+=1){const c=t.concat([d]),f=Te(c,i);n.push({op:R.Add,path:f,value:Ge(a[d])})}if(s.length<a.length){const{arrayLengthAssignment:d=!0}=u.enablePatches;if(d){const c=t.concat(["length"]),f=Te(c,i);r.push({op:R.Replace,path:f,value:s.length})}else for(let c=a.length;s.length<c;c-=1){const f=t.concat([c-1]),h=Te(f,i);r.push({op:R.Remove,path:h})}}}function ni({original:e,copy:t,assignedMap:n},r,i,s,o){n.forEach((u,a)=>{const d=fe(e,a),c=Ge(fe(t,a)),f=u?xe(e,a)?R.Replace:R.Add:R.Remove;if(le(d,c)&&f===R.Replace)return;const h=r.concat(a),p=Te(h,o);i.push(f===R.Remove?{op:f,path:p}:{op:f,path:p,value:c}),s.push(f===R.Add?{op:R.Remove,path:p}:f===R.Remove?{op:R.Add,path:p,value:d}:{op:R.Replace,path:p,value:d})})}function ri({original:e,copy:t},n,r,i,s){let o=0;e.forEach(u=>{if(!t.has(u)){const a=n.concat([o]),d=Te(a,s);r.push({op:R.Remove,path:d,value:u}),i.unshift({op:R.Add,path:d,value:u})}o+=1}),o=0,t.forEach(u=>{if(!e.has(u)){const a=n.concat([o]),d=Te(a,s);r.push({op:R.Add,path:d,value:u}),i.unshift({op:R.Remove,path:d,value:u})}o+=1})}function Le(e,t,n,r){const{pathAsArray:i=!0}=e.options.enablePatches;switch(e.type){case 0:case 2:return ni(e,t,n,r,i);case 1:return ti(e,t,n,r,i);case 3:return ri(e,t,n,r,i)}}const Ye=(e,t,n=!1)=>{if(typeof e=="object"&&e!==null&&(!ie(e,t)||n))throw new Error("Strict mode: Mutable data cannot be accessed directly, please use 'unsafe(callback)' wrap.")},Pt={get size(){return ee(E(this)).size},has(e){return ee(E(this)).has(e)},set(e,t){const n=E(this),r=ee(n);return(!r.has(e)||!le(r.get(e),t))&&(z(n),ce(n),n.assignedMap.set(e,!0),n.copy.set(e,t),jt(n,e,t,Le)),this},delete(e){if(!this.has(e))return!1;const t=E(this);return z(t),ce(t),t.original.has(e)?t.assignedMap.set(e,!1):t.assignedMap.delete(e),t.copy.delete(e),!0},clear(){const e=E(this);if(this.size){z(e),ce(e),e.assignedMap=new Map;for(const[t]of e.original)e.assignedMap.set(t,!1);e.copy.clear()}},forEach(e,t){const n=E(this);ee(n).forEach((r,i)=>{e.call(t,this.get(i),i,this)})},get(e){var t,n;const r=E(this),i=ee(r).get(e),s=((n=(t=r.options).mark)===null||n===void 0?void 0:n.call(t,i,X))===X.mutable;if(r.options.strict&&Ye(i,r.options,s),s||r.finalized||!ie(i,r.options)||i!==r.original.get(e))return i;const o=Tt.createDraft({original:i,parentDraft:r,key:e,finalities:r.finalities,options:r.options});return z(r),r.copy.set(e,o),o},keys(){return ee(E(this)).keys()},values(){const e=this.keys();return{[Qe]:()=>this.values(),next:()=>{const t=e.next();return t.done?t:{done:!1,value:this.get(t.value)}}}},entries(){const e=this.keys();return{[Qe]:()=>this.entries(),next:()=>{const t=e.next();if(t.done)return t;const n=this.get(t.value);return{done:!1,value:[t.value,n]}}}},[Qe](){return this.entries()}},ii=Reflect.ownKeys(Pt),Sn=(e,t,{isValuesIterator:n})=>()=>{var r,i;const s=t.next();if(s.done)return s;const o=s.value;let u=e.setMap.get(o);const a=E(u),d=((i=(r=e.options).mark)===null||i===void 0?void 0:i.call(r,u,X))===X.mutable;if(e.options.strict&&Ye(o,e.options,d),!d&&!a&&ie(o,e.options)&&!e.finalized&&e.original.has(o)){const c=Tt.createDraft({original:o,parentDraft:e,key:o,finalities:e.finalities,options:e.options});e.setMap.set(o,c),u=c}else a&&(u=a.proxy);return{done:!1,value:n?u:[u,u]}},He={get size(){return E(this).setMap.size},has(e){const t=E(this);if(t.setMap.has(e))return!0;z(t);const n=E(e);return!!(n&&t.setMap.has(n.original))},add(e){const t=E(this);return this.has(e)||(z(t),ce(t),t.assignedMap.set(e,!0),t.setMap.set(e,e),jt(t,e,e,Le)),this},delete(e){if(!this.has(e))return!1;const t=E(this);z(t),ce(t);const n=E(e);return n&&t.setMap.has(n.original)?(t.assignedMap.set(n.original,!1),t.setMap.delete(n.original)):(!n&&t.setMap.has(e)?t.assignedMap.set(e,!1):t.assignedMap.delete(e),t.setMap.delete(e))},clear(){if(!this.size)return;const e=E(this);z(e),ce(e);for(const t of e.original)e.assignedMap.set(t,!1);e.setMap.clear()},values(){const e=E(this);z(e);const t=e.setMap.keys();return{[Symbol.iterator]:()=>this.values(),next:Sn(e,t,{isValuesIterator:!0})}},entries(){const e=E(this);z(e);const t=e.setMap.keys();return{[Symbol.iterator]:()=>this.entries(),next:Sn(e,t,{isValuesIterator:!1})}},keys(){return this.values()},[Qe](){return this.values()},forEach(e,t){const n=this.values();let r=n.next();for(;!r.done;)e.call(t,r.value,r.value,this),r=n.next()}};Set.prototype.difference&&Object.assign(He,{intersection(e){return Set.prototype.intersection.call(new Set(this.values()),e)},union(e){return Set.prototype.union.call(new Set(this.values()),e)},difference(e){return Set.prototype.difference.call(new Set(this.values()),e)},symmetricDifference(e){return Set.prototype.symmetricDifference.call(new Set(this.values()),e)},isSubsetOf(e){return Set.prototype.isSubsetOf.call(new Set(this.values()),e)},isSupersetOf(e){return Set.prototype.isSupersetOf.call(new Set(this.values()),e)},isDisjointFrom(e){return Set.prototype.isDisjointFrom.call(new Set(this.values()),e)}});const si=Reflect.ownKeys(He),vn=new WeakSet,On={get(e,t,n){var r,i;const s=(r=e.copy)===null||r===void 0?void 0:r[t];if(s&&vn.has(s))return s;if(t===bn)return e;let o;if(e.options.mark){const d=t==="size"&&(e.original instanceof Map||e.original instanceof Set)?Reflect.get(e.original,t):Reflect.get(e.original,t,n);if(o=e.options.mark(d,X),o===X.mutable)return e.options.strict&&Ye(d,e.options,!0),d}const u=ee(e);if(u instanceof Map&&ii.includes(t)){if(t==="size")return Object.getOwnPropertyDescriptor(Pt,"size").get.call(e.proxy);const d=Pt[t];if(d)return d.bind(e.proxy)}if(u instanceof Set&&si.includes(t)){if(t==="size")return Object.getOwnPropertyDescriptor(He,"size").get.call(e.proxy);const d=He[t];if(d)return d.bind(e.proxy)}if(!xe(u,t)){const d=_n(u,t);return d?"value"in d?d.value:(i=d.get)===null||i===void 0?void 0:i.call(e.proxy):void 0}const a=u[t];if(e.options.strict&&Ye(a,e.options),e.finalized||!ie(a,e.options))return a;if(a===vt(e.original,t)){if(z(e),e.copy[t]=kt({original:e.original[t],parentDraft:e,key:e.type===1?Number(t):t,finalities:e.finalities,options:e.options}),typeof o=="function"){const d=E(e.copy[t]);return z(d),ce(d),d.copy}return e.copy[t]}return a},set(e,t,n){var r;if(e.type===3||e.type===2)throw new Error("Map/Set draft does not support any property assignment.");let i;if(e.type===1&&t!=="length"&&!(Number.isInteger(i=Number(t))&&i>=0&&(t===0||i===0||String(i)===String(t))))throw new Error("Only supports setting array indices and the 'length' property.");const s=_n(ee(e),t);if(s!=null&&s.set)return s.set.call(e.proxy,n),!0;const o=vt(ee(e),t),u=E(o);return u&&le(u.original,n)?(e.copy[t]=n,e.assignedMap=(r=e.assignedMap)!==null&&r!==void 0?r:new Map,e.assignedMap.set(t,!1),!0):(le(n,o)&&(n!==void 0||xe(e.original,t))||(z(e),ce(e),xe(e.original,t)&&le(n,e.original[t])?e.assignedMap.delete(t):e.assignedMap.set(t,!0),e.copy[t]=n,jt(e,t,n,Le)),!0)},has(e,t){return t in ee(e)},ownKeys(e){return Reflect.ownKeys(ee(e))},getOwnPropertyDescriptor(e,t){const n=ee(e),r=Reflect.getOwnPropertyDescriptor(n,t);return r&&{writable:!0,configurable:e.type!==1||t!=="length",enumerable:r.enumerable,value:n[t]}},getPrototypeOf(e){return Reflect.getPrototypeOf(e.original)},setPrototypeOf(){throw new Error("Cannot call 'setPrototypeOf()' on drafts")},defineProperty(){throw new Error("Cannot call 'defineProperty()' on drafts")},deleteProperty(e,t){var n;return e.type===1?On.set.call(this,e,t,void 0,e.proxy):(vt(e.original,t)!==void 0||t in e.original?(z(e),ce(e),e.assignedMap.set(t,!1)):(e.assignedMap=(n=e.assignedMap)!==null&&n!==void 0?n:new Map,e.assignedMap.delete(t)),e.copy&&delete e.copy[t],!0)}};function kt(e){const{original:t,parentDraft:n,key:r,finalities:i,options:s}=e,o=ge(t),u={type:o,finalized:!1,parent:n,original:t,copy:null,proxy:null,finalities:i,options:s,setMap:o===3?new Map(t.entries()):void 0};(r||"key"in e)&&(u.key=r);const{proxy:a,revoke:d}=Proxy.revocable(o===1?Object.assign([],u):u,On);if(i.revoke.push(d),vn.add(a),u.proxy=a,n){const c=n;c.finalities.draft.push((f,h)=>{var p,b;const g=E(a);let w=c.type===3?c.setMap:c.copy;const T=fe(w,r),m=E(T);if(m){let S=m.original;m.operated&&(S=St(T)),At(m),Ct(m,Le,f,h),c.options.enableAutoFreeze&&(c.options.updatedValues=(p=c.options.updatedValues)!==null&&p!==void 0?p:new WeakMap,c.options.updatedValues.set(S,m.original)),$e(w,r,S)}(b=g.callbacks)===null||b===void 0||b.forEach(S=>{S(f,h)})})}else{const c=E(a);c.finalities.draft.push((f,h)=>{At(c),Ct(c,Le,f,h)})}return a}Tt.createDraft=kt;function oi(e,t,n,r,i){var s;const o=E(e),u=(s=o==null?void 0:o.original)!==null&&s!==void 0?s:e,a=!!t.length;if(o!=null&&o.operated)for(;o.finalities.draft.length>0;)o.finalities.draft.pop()(n,r);const d=a?t[0]:o?o.operated?o.copy:o.original:e;return o&&Ot(o),i&&ve(d,d,o==null?void 0:o.options.updatedValues),[d,n&&a?[{op:R.Replace,path:[],value:t[0]}]:n,r&&a?[{op:R.Replace,path:[],value:u}]:r]}function ui(e,t){var n;const r={draft:[],revoke:[],handledSet:new WeakSet};let i,s;t.enablePatches&&(i=[],s=[]);const u=((n=t.mark)===null||n===void 0?void 0:n.call(t,e,X))===X.mutable||!ie(e,t)?e:kt({original:e,parentDraft:null,finalities:r,options:t});return[u,(a=[])=>{const[d,c,f]=oi(u,a,i,s,t.enableAutoFreeze);return t.enablePatches?[d,c,f]:d}]}function It(e){const{rootDraft:t,value:n,useRawReturn:r=!1,isRoot:i=!0}=e;Et(n,(s,o,u)=>{const a=E(o);if(a&&t&&a.finalities===t.finalities){e.isContainDraft=!0;const d=a.original;if(u instanceof Set){const c=Array.from(u);u.clear(),c.forEach(f=>u.add(s===f?d:f))}else $e(u,s,d)}else typeof o=="object"&&o!==null&&(e.value=o,e.isRoot=!1,It(e))}),i&&(e.isContainDraft||console.warn("The return value does not contain any draft, please use 'rawReturn()' to wrap the return value to improve performance."),r&&console.warn("The return value contains drafts, please don't use 'rawReturn()' to wrap the return value."))}function En(e){var t;const n=E(e);if(!ie(e,n==null?void 0:n.options))return e;const r=ge(e);if(n&&!n.operated)return n.original;let i;function s(){i=r===2?mt(e)?new Map(e):new(Object.getPrototypeOf(e)).constructor(e):r===3?Array.from(n.setMap.values()):Tn(e,n==null?void 0:n.options)}if(n){n.finalized=!0;try{s()}finally{n.finalized=!1}}else i=e;if(Et(i,(o,u)=>{if(n&&le(fe(n.original,o),u))return;const a=En(u);a!==u&&(i===e&&s(),$e(i,o,a))}),r===3){const o=(t=n==null?void 0:n.original)!==null&&t!==void 0?t:i;return wt(o)?new Set(i):new(Object.getPrototypeOf(o)).constructor(i)}return i}function An(e){if(!_e(e))throw new Error(`current() is only used for Draft, parameter: ${e}`);return En(e)}const Mt=(e=>function t(n,r,i){var s,o,u;if(typeof n=="function"&&typeof r!="function")return function(O,...U){return t(O,W=>n.call(this,W,...U),r)};const a=n,d=r;let c=i;if(typeof r!="function"&&(c=r),c!==void 0&&Object.prototype.toString.call(c)!=="[object Object]")throw new Error(`Invalid options: ${c}, 'options' should be an object.`);c=Object.assign(Object.assign({},e),c);const f=_e(a)?An(a):a,h=Array.isArray(c.mark)?(O,U)=>{for(const W of c.mark){if(typeof W!="function")throw new Error(`Invalid mark: ${W}, 'mark' should be a function.`);const ye=W(O,U);if(ye)return ye}}:c.mark,p=(s=c.enablePatches)!==null&&s!==void 0?s:!1,b=(o=c.strict)!==null&&o!==void 0?o:!1,w={enableAutoFreeze:(u=c.enableAutoFreeze)!==null&&u!==void 0?u:!1,mark:h,strict:b,enablePatches:p};if(!ie(f,w)&&typeof f=="object"&&f!==null)throw new Error("Invalid base state: create() only supports plain objects, arrays, Set, Map or using mark() to mark the state as immutable.");const[T,m]=ui(f,w);if(typeof r!="function"){if(!ie(f,w))throw new Error("Invalid base state: create() only supports plain objects, arrays, Set, Map or using mark() to mark the state as immutable.");return[T,m]}let S;try{S=d(T)}catch(O){throw Ot(E(T)),O}const K=O=>{const U=E(T);if(!_e(O)){if(O!==void 0&&!le(O,T)&&(U!=null&&U.operated))throw new Error("Either the value is returned as a new non-draft value, or only the draft is modified without returning any value.");const ye=O==null?void 0:O[Hr];if(ye){const de=ye[0];return w.strict&&typeof O=="object"&&O!==null&&It({rootDraft:U,value:O,useRawReturn:!0}),m([de])}if(O!==void 0)return typeof O=="object"&&O!==null&&It({rootDraft:U,value:O}),m([O])}if(O===T||O===void 0)return m([]);const W=E(O);if(w===W.options){if(W.operated)throw new Error("Cannot return a modified child draft.");return m([An(O)])}return m([O])};return S instanceof Promise?S.then(K,O=>{throw Ot(E(T)),O}):K(S)})();Object.prototype.constructor.toString();function Cn(e,t){const n=Object.keys(e),r=Object.keys(t);return n.length===r.length&&Object.keys(e).every(i=>t.hasOwnProperty(i))}function jn(e,t){return Object.keys(e).length===Object.keys(t).length&&Object.keys(e).every(n=>t.hasOwnProperty(n)&&e[n]===t[n])}function Je(e,t){return typeof e!="object"||typeof t!="object"||e===null||t===null?e===t:Cn(e,t)?Object.keys(e).every(n=>Je(e[n],t[n])):!1}function Rt(e){if(!Fe(e))return e;const t={};for(const[n,r]of Object.entries(e))r!==void 0&&(t[n]=r);return t}function Pn(e,t){if(!Fe(e)||!Fe(t))return t;const n=Object.assign({},e);for(const r of Object.keys(t)){if(t[r]===void 0)continue;if(t[r]===null){delete n[r];continue}const i=Fe(e[r])&&Fe(t[r]);n[r]=i?Pn(e[r],t[r]):t[r]}return n}function Fe(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function ai(e,t,n){if(!e||t.length===0)return;let r=e||{};for(let s=0;s<t.length-1;s++){const o=t[s];(!(o in r)||typeof r[o]!="object")&&(r[o]=typeof t[s+1]=="number"?[]:{}),r=r[o]}const i=t[t.length-1];Array.isArray(r)&&typeof i=="number"?r.splice(i,0,n):r[i]=n}function kn(e,t,n){if(!e||t.length===0)return;let r=e||{};for(let i=0;i<t.length-1;i++){const s=t[i];(!(s in r)||typeof r[s]!="object")&&(r[s]=typeof t[i+1]=="number"?[]:{}),r=r[s]}r[t[t.length-1]]=n}function In(e,t){if(!e||t.length===0)return;const[n,...r]=t;if(n in e){if(r.length===0){Array.isArray(e)?e.splice(n,1):delete e[n];return}In(e[n],r),ci(e[n])&&delete e[n]}}function ci(e){return e&&Object.keys(e).length===0}const Mn=/ZULU|YEKT|YEKST|YAPT|YAKT|YAKST|XJT|WGT|WGST|WFT|WETDST|WET|WDT|WAT|WAST|WAKT|WADT|VUT|VOLT|VLAT|VLAST|VET|UZT|UZST|UYT|UYST|UTC|UT|ULAT|ULAST|UCT|TVT|TRUT|TOT|TMT|TKT|TJT|TFT|TAHT|SGT|SCT|SAST|SADT|RET|PYT|PYST|PWT|PST|PONT|PMST|PMDT|PKT|PKST|PHT|PGT|PETT|PETST|PET|PDT|OMST|OMSST|NZT|NZST|NZDT|NUT|NST|NPT|NOVT|NOVST|NFT|NDT|MYT|MVT|MUT|MUST|MST|MSK|MSD|MPT|MMT|MHT|MEZ|METDST|MET|MESZ|MEST|MDT|MAWT|MART|MAGT|MAGST|LKT|LINT|LIGT|LHST|LHDT|KST|KRAT|KRAST|KOST|KGT|KGST|KDT|JST|JAYT|IST|IRT|IRKT|IRKST|IOT|IDT|ICT|HST|HKT|GYT|GMT|GILT|GFT|GET|GEST|GAMT|GALT|FNT|FNST|FKT|FKST|FJT|FJST|FET|EST|EGT|EGST|EETDST|EET|EEST|EDT|EAT|EAST|EASST|DDUT|DAVT|CXT|CST|COT|CLT|CLST|CKT|CHUT|CHAST|CHADT|CETDST|CET|CEST|CDT|CCT|CAST|CADT|BTT|BST|BRT|BRST|BRA|BOT|BORT|BNT|BDT|BDST|AZT|AZST|AZOT|AZOST|AWST|AWSST|AST|ART|ARST|ANAT|ANAST|AMT|AMST|ALMT|ALMST|AKST|AKDT|AFT|AEST|AESST|AEDT|ADT|ACWST|ACT|ACST|ACSST|ACDT$/,di={ZULU:0,YEKT:18e3,YEKST:21600,YAPT:36e3,YAKT:32400,YAKST:32400,XJT:21600,WGT:-10800,WGST:-7200,WFT:43200,WETDST:3600,WET:0,WDT:32400,WAT:3600,WAST:25200,WAKT:43200,WADT:28800,VUT:39600,VOLT:10800,VLAT:36e3,VLAST:36e3,VET:-14400,UZT:18e3,UZST:21600,UYT:-10800,UYST:-7200,UTC:0,UT:0,ULAT:28800,ULAST:32400,UCT:0,TVT:43200,TRUT:36e3,TOT:46800,TMT:18e3,TKT:46800,TJT:18e3,TFT:18e3,TAHT:-36e3,SGT:28800,SCT:14400,SAST:7200,SADT:37800,RET:14400,PYT:-14400,PYST:-10800,PWT:32400,PST:-28800,PONT:39600,PMST:-10800,PMDT:-7200,PKT:18e3,PKST:21600,PHT:28800,PGT:36e3,PETT:43200,PETST:43200,PET:-18e3,PDT:-25200,OMST:21600,OMSST:21600,NZT:43200,NZST:43200,NZDT:46800,NUT:-39600,NST:-12600,NPT:20700,NOVT:25200,NOVST:25200,NFT:-12600,NDT:-9e3,MYT:28800,MVT:18e3,MUT:14400,MUST:18e3,MST:-25200,MSK:10800,MSD:14400,MPT:36e3,MMT:23400,MHT:43200,MEZ:3600,METDST:7200,MET:3600,MESZ:7200,MEST:7200,MDT:-21600,MAWT:18e3,MART:-34200,MAGT:39600,MAGST:39600,LKT:19800,LINT:50400,LIGT:36e3,LHST:37800,LHDT:37800,KST:32400,KRAT:25200,KRAST:25200,KOST:39600,KGT:21600,KGST:21600,KDT:36e3,JST:32400,JAYT:32400,IST:7200,IRT:12600,IRKT:28800,IRKST:28800,IOT:21600,IDT:10800,ICT:25200,HST:-36e3,HKT:28800,GYT:-14400,GMT:0,GILT:43200,GFT:-10800,GET:14400,GEST:14400,GAMT:-32400,GALT:-21600,FNT:-7200,FNST:-3600,FKT:-10800,FKST:-10800,FJT:43200,FJST:46800,FET:10800,EST:-18e3,EGT:-3600,EGST:0,EETDST:10800,EET:7200,EEST:10800,EDT:-14400,EAT:10800,EAST:-21600,EASST:-21600,DDUT:36e3,DAVT:25200,CXT:25200,CST:-21600,COT:-18e3,CLT:-14400,CLST:-10800,CKT:-36e3,CHUT:36e3,CHAST:45900,CHADT:49500,CETDST:7200,CET:3600,CEST:7200,CDT:-18e3,CCT:28800,CAST:34200,CADT:37800,BTT:21600,BST:3600,BRT:-10800,BRST:-7200,BRA:-10800,BOT:-14400,BORT:28800,BNT:28800,BDT:21600,BDST:7200,AZT:14400,AZST:14400,AZOT:-3600,AZOST:0,AWST:28800,AWSST:32400,AST:-14400,ART:-10800,ARST:-10800,ANAT:43200,ANAST:43200,AMT:-14400,AMST:14400,ALMT:21600,ALMST:25200,AKST:-32400,AKDT:-28800,AFT:16200,AEST:36e3,AESST:39600,AEDT:39600,ADT:-10800,ACWST:31500,ACT:-18e3,ACST:34200,ACSST:37800,ACDT:37800};function fi(e){return new Date(e)}function li(e){return new Date(e+"Z")}const hi=/^(\d+)[\./-](\d+)[\./-](\d+)$/;function pi(e){const t=e.match(hi);if(!t)return null;const[n,r,i,s]=t;return r<=0||i<=0||s<=0?null:r>999?new Date(Date.UTC(r,i-1,s,0,0,0,0)):new Date(Date.UTC(s,r-1,i,0,0,0,0))}function yi(e){const[t,n]=e.split(" ");return new Date(t+"T"+n+"Z")}function bi(e){const[t,n]=e.split(" ");return new Date(t+"T"+n+"Z")}function _i(e){return new Date(e)}function gi(e){const t=/^(\w{3}) (\w{3}) (\d{2}) (\d{4})$/;if(!e.match(t))throw new Error(`Unable to parse \`${e}\` as a date.`);const r=new Date(e+" UTC");return new Date(Date.UTC(r.getUTCFullYear(),r.getUTCMonth(),r.getUTCDate(),0,0,0,0))}function Ti(e){const t=/^(.+T.+)([+-])(\d{2})$/,n=e.match(t);if(n){const[,r,i,s]=n,o=`${r}${i}${s}:00`;return new Date(o)}return null}function wi(e){const[t,n]=e.split(", "),[r,i,s]=t.split("/").map(Number),o=n.match(/(\d{1,2}):(\d{2}):(\d{2}) (AM|PM)/);if(!o)throw new Error(`Unable to parse time from: ${e}`);let[,u,a,d,c]=o;return u=Number(u),a=Number(a),d=Number(d),c==="PM"&&u!==12?u+=12:c==="AM"&&u===12&&(u=0),new Date(Date.UTC(s,r-1,i,u,a,d))}function mi(e){switch(e){case"epoch":return new Date(0);case"infinity":case"-infinity":case"today":case"tomorrow":case"yesterday":return null}}function Si(e){const t=e.match(Mn);if(!t)return null;const[n]=t,r=di[n],i=new Date(e.replace(Mn,"Z"));return new Date(i.getTime()-r*1e3)}const vi=[pi,bi,gi,wi,_i,li,Ti,yi,fi,mi,Si];function Oi(e,t){try{const n=e(t);return n instanceof Date&&!isNaN(n.getTime())?n:null}catch{return null}}function Dt(e){for(const t of vi){const n=Oi(t,e);if(n)return n}return null}function Ei(e){try{const t=JSON.parse(e);return typeof t=="string"?Dt(t):null}catch{return null}}function Ze(e){if(e!==void 0){if(e===null)return null;if(e instanceof Date)return e;if(typeof e=="string"){const t=Dt(e)||Ei(e)||Dt(e.trim());if(!t)throw new Error(`Unable to parse \`${e}\` as a date.`);return t}else if(typeof e=="number")return new Date(e);throw new Error(`Invalid date value \`${e}\`. Expected a date, number, or string, got type ${typeof e}.`)}}function Ai(e){return e.cardinality==="one"}function xt(e){return e["value-type"]==="ref"}function $t(e){return e["value-type"]==="blob"}function Oe(e,t){return e[t]}function Xe(e,t){return t.reduce((n,r)=>n&&n.get(r),e)}function se(e,t){if(t.length===0)throw new Error("path must have at least one element");if(t.length===1){e.delete(t[0]);return}const[n,...r]=t;e.has(n)&&se(e.get(n),r)}function Q(e,t,n){if(t.length===0)throw new Error("path must have at least one element");if(t.length===1){e.set(t[0],n);return}const[r,...i]=t;let s=e.get(r);s||(s=new Map,e.set(r,s)),Q(s,i,n)}function Rn(e,t,n){const r=new Map,i=new Map,s=new Map;for(const o of t){let[u,a,d,c]=o;const f=Oe(e,a);if(!f){console.warn("no such attr",u,e);continue}f["checked-data-type"]==="date"&&n&&(d=Ze(d),o[2]=d),xt(f)&&Q(s,[d,a,u],o),Q(r,[u,a,d],o),Q(i,[a,u,d],o)}return{eav:r,aev:i,vae:s}}function Dn(e){const t=new Map,n=new Map,r=new Map,i=new Map;for(const s of Object.values(e)){const o=s["forward-identity"],[u,a,d]=o,c=s["reverse-identity"];if(Q(r,[a,d],s),$t(s)&&Q(t,[a,d],s),s["primary?"]&&Q(n,[a],s),c){const[f,h,p]=c;Q(i,[h,p],s)}}return{blobAttrs:t,primaryKeys:n,forwardIdents:r,revIdents:i}}function Ci(e){return{__type:e.__type,attrs:e.attrs,triples:G(e.eav,3),cardinalityInference:e.cardinalityInference,linkIndex:e.linkIndex,useDateObjects:e.useDateObjects}}function ji(e){return Lt(e.attrs,e.triples,e.cardinalityInference,e.linkIndex,e.useDateObjects)}function Ut(e){e.attrIndexes=Dn(e.attrs)}function Lt(e,t,n,r,i){const s=Rn(e,t,i);return s.useDateObjects=i,s.attrs=e,s.attrIndexes=Dn(e),s.cardinalityInference=n,s.linkIndex=r,s.__type="store",s}function Ne(e,t){var n,r;let i;if(Array.isArray(t[0])){const[o,u]=t[0],a=e.aev.get(o);if(!a)return null;i=(n=G(a,2).find(c=>c[2]===u))===null||n===void 0?void 0:n[0]}else i=t[0];if(!i)return null;const s=t[2];if(Array.isArray(s)&&s.length===2&&e.aev.get(s[0])){const[o,u]=s,a=e.aev.get(o);if(!a)return null;const c=(r=G(a,2).find(g=>g[2]===u))===null||r===void 0?void 0:r[0];if(!c)return null;const[f,h,p,...b]=t;return[i,h,c,...b]}else{const[o,...u]=t;return[i,...u]}}function Pi(e,t){const n=Ne(e,t);if(!n)return;const[r,i,s]=n,o=Oe(e.attrs,i);o&&(se(e.eav,[r,i,s]),se(e.aev,[i,r,s]),xt(o)&&se(e.vae,[s,i,r]))}let ki=0;function xn(e,t,n){const[r,i,s]=n;let o;const u=Xe(e.ea,[r,i,s]);return u&&(o=u[3]),o||Date.now()*10+ki++}function Ii(e,t){var n;const r=Ne(e,t);if(!r)return;let[i,s,o]=r;const u=Oe(e.attrs,s);if(!u)return;u["checked-data-type"]==="date"&&e.useDateObjects&&(o=Ze(o));const a=Xe(e.eav,[i,s,o]),d=(n=a==null?void 0:a[3])!==null&&n!==void 0?n:xn(e,u,r),c=[i,s,o,d];Ai(u)?(Q(e.eav,[i,s],new Map([[o,c]])),Q(e.aev,[s,i],new Map([[o,c]]))):(Q(e.eav,[i,s,o],c),Q(e.aev,[s,i,o],c)),xt(u)&&Q(e.vae,[o,s,i],c)}function Mi(e,t){var n;const r=Ne(e,t);if(!r)return;const[i,s,o]=r,u=Oe(e.attrs,s);if(!u)return;if(!$t(u))throw new Error("merge operation is not supported for links");const a=Xe(e.eav,[i,s]);if(!a)return;const d=(n=a.values().next())===null||n===void 0?void 0:n.value;if(!d)return;const c=d[2],f=Pn(c,o),h=[i,s,f,xn(e,u,d)];Q(e.eav,[i,s],new Map([[f,h]]))}function Ft(e,t){var n,r;const[i,s]=t,o=Ne(e,[i]);if(!o)return;const[u]=o,a=e.eav.get(u);if(a){for(const c of a.keys()){const f=e.attrs[c];f&&f["on-delete-reverse"]==="cascade"&&G(a.get(c),1).forEach(([h,p,b])=>{var g;return Ft(e,[b,(g=f["reverse-identity"])===null||g===void 0?void 0:g[1]])}),(!s||!f||((n=f["forward-identity"])===null||n===void 0?void 0:n[1])===s)&&(se(e.aev,[c,u]),se(e.eav,[u,c]))}a.size===0&&se(e.eav,[u])}const d=e.vae.get(u)&&G(e.vae.get(u),2);d&&d.forEach(c=>{var f,h,p;const[b,g,w]=c,T=e.attrs[g];(!s||!T||((f=T["reverse-identity"])===null||f===void 0?void 0:f[1])===s)&&(se(e.eav,[b,g,w]),se(e.aev,[g,b,w]),se(e.vae,[w,g,b])),T&&T["on-delete"]==="cascade"&&((h=T["reverse-identity"])===null||h===void 0?void 0:h[1])===s&&Ft(e,[b,(p=T["forward-identity"])===null||p===void 0?void 0:p[1]])}),((r=e.vae.get(u))===null||r===void 0?void 0:r.size)===0&&se(e.vae,[u])}function $n(e,t){const n=Rn(e.attrs,t,e.useDateObjects);Object.keys(n).forEach(r=>{e[r]=n[r]})}function Ri(e,[t]){e.attrs[t.id]=t,Ut(e)}function Un(e){return G(e.eav,3)}function Di(e,[t]){if(!e.attrs[t])return;const n=Un(e).filter(([r,i])=>i!==t);delete e.attrs[t],Ut(e),$n(e,n)}function xi(e,[t]){const n=e.attrs[t.id];n&&(e.attrs[t.id]=Object.assign(Object.assign({},n),t),Ut(e),$n(e,Un(e)))}function $i(e,t){const[n,...r]=t;switch(n){case"add-triple":Ii(e,r);break;case"deep-merge-triple":Mi(e,r);break;case"retract-triple":Pi(e,r);break;case"delete-entity":Ft(e,r);break;case"add-attr":Ri(e,r);break;case"delete-attr":Di(e,r);break;case"update-attr":xi(e,r);break;case"restore-attr":break;case"rule-params":break;default:throw new Error(`unhandled transaction action: ${n}`)}}function G(e,t,n=[]){if(!e||t===0)return n;if(t===1){for(const r of e.values())n.push(r);return n}for(const r of e.values())G(r,t-1,n);return n}function et(e,t,n){var r,i;const s=[];if(n!=null&&n.hasOwnProperty("$not")){for(const u of t.keys())n.$not!==u&&s.push(t.get(u));return s}if(n!=null&&n.hasOwnProperty("$isNull")){const{attrId:u,isNull:a,reverse:d}=n.$isNull;if(d)for(const c of t.keys()){const f=e.vae.get(c),h=!f||((r=f.get(u))===null||r===void 0?void 0:r.get(null))||!f.get(u);(a?h:!h)&&s.push(t.get(c))}else{const c=e.aev.get(u);for(const f of t.keys()){const h=!c||((i=c.get(f))===null||i===void 0?void 0:i.get(null))||!c.get(f);(a?h:!h)&&s.push(t.get(f))}}return s}if(n!=null&&n.$comparator)return G(t,1).filter(n.$op);const o=n.in||n.$in||[n];for(const u of o){const a=t.get(u);a&&s.push(a)}return s}function Ui(e,t,n){let r="";return e!==void 0&&(r+="e"),t!==void 0&&(r+="a"),n!==void 0&&(r+="v"),r}function Li(e,[t,n,r]){var i,s;switch(Ui(t,n,r)){case"e":{const u=e.eav.get(t);return G(u,2)}case"ea":{const u=(i=e.eav.get(t))===null||i===void 0?void 0:i.get(n);return G(u,1)}case"eav":{const u=(s=e.eav.get(t))===null||s===void 0?void 0:s.get(n);return u?et(e,u,r):[]}case"ev":{const u=e.eav.get(t);if(!u)return[];const a=[];for(const d of u.values())a.push(...et(e,d,r));return a}case"a":{const u=e.aev.get(n);return G(u,2)}case"av":{const u=e.aev.get(n);if(!u)return[];const a=[];for(const d of u.values())a.push(...et(e,d,r));return a}case"v":{const u=[];for(const a of e.eav.values())for(const d of a.values())u.push(...et(e,d,r));return u}default:return G(e.eav,3)}}function Fi(e,t,n){var r;const i={};for(const[s,o]of t.entries()){const u=(r=e.eav.get(n))===null||r===void 0?void 0:r.get(o.id),a=G(u,1);for(const d of a)i[s]=d[2]}return i}function Ee(e,t,n){var r;return(r=e.attrIndexes.forwardIdents.get(t))===null||r===void 0?void 0:r.get(n)}function Ln(e,t,n){var r;return(r=e.attrIndexes.revIdents.get(t))===null||r===void 0?void 0:r.get(n)}function Ni(e,t){return e.attrIndexes.blobAttrs.get(t)}function Fn(e,t){var n;const r=e.attrIndexes.primaryKeys.get(t);return r||((n=e.attrIndexes.forwardIdents.get(t))===null||n===void 0?void 0:n.get("id"))}function Vi(e,t){const n=Ne(e,t);if(!n)return;const[r,i,s]=n;if(Oe(e.attrs,i))return Xe(e.eav,[r,i])}function Wi(e,t){const n=t.filter(([r,i,s,o,u])=>{if(r!=="add-triple"&&r!=="deep-merge-triple")return!0;const a=u==null?void 0:u.mode;if(a!=="create"&&a!=="update")return!0;let d=!1;const c=Oe(e.attrs,s);if(c){const f=Fn(e,c["forward-identity"][1]);d=!!Vi(e,[i,f.id,i])}return!(a==="create"&&d||a==="update"&&!d)});return Mt(e,r=>{n.forEach(i=>{$i(r,i)})})}function zi(e){return typeof e=="string"&&e.startsWith("?")}function Ki(e,t,n){if(n.hasOwnProperty(e)){const r=n[e];return Vn(r,t,n)}return Object.assign(Object.assign({},n),{[e]:t})}function Nn(e,t,n){return e===t?n:null}function qi(e){switch(typeof e){case"string":return e.startsWith("?")?Ki:Nn;default:return Nn}}const Bi=["in","$in","$not","$isNull","$comparator"];function Qi(e){for(const t of Bi)if(e.hasOwnProperty(t))return!0;return!1}function Vn(e,t,n){return n?typeof e=="object"?Qi(e)?n:null:qi(e)(e,t,n):null}function Gi(e,t,n){return e.reduce((r,i,s)=>{const o=t[s];return Vn(i,o,r)},n)}function Yi(e,t,n){return Zi(e,t,n).map(r=>Gi(t,r,n)).filter(r=>r)}function Hi(e,t,n){return t.or?t.or.patterns.flatMap(r=>Nt(e,r,n)):t.and?t.and.patterns.reduce((r,i)=>Nt(e,i,r),n):n.flatMap(r=>Yi(e,t,r))}function Nt(e,t,n=[{}]){return t.reduce((r,i)=>Hi(e,i,r),n)}function Vt(e,t){return Array.isArray(t)?t.map(n=>Vt(e,n)):zi(t)?e[t]:t}function Ji(e,{find:t,where:n}){return Nt(e,n).map(i=>Vt(i,t))}function Zi(e,t,n){return Li(e,Vt(n,t))}const Xi=/^(?:[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$/i;function Ae(e){return typeof e=="string"&&Xi.test(e)}const F=[];for(let e=0;e<256;++e)F.push((e+256).toString(16).slice(1));function es(e,t=0){return(F[e[t+0]]+F[e[t+1]]+F[e[t+2]]+F[e[t+3]]+"-"+F[e[t+4]]+F[e[t+5]]+"-"+F[e[t+6]]+F[e[t+7]]+"-"+F[e[t+8]]+F[e[t+9]]+"-"+F[e[t+10]]+F[e[t+11]]+F[e[t+12]]+F[e[t+13]]+F[e[t+14]]+F[e[t+15]]).toLowerCase()}let Wt;const ts=new Uint8Array(16);function ns(){if(!Wt){if(typeof crypto>"u"||!crypto.getRandomValues)throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");Wt=crypto.getRandomValues.bind(crypto)}return Wt(ts)}const Wn={randomUUID:typeof crypto<"u"&&crypto.randomUUID&&crypto.randomUUID.bind(crypto)};function rs(e,t,n){var i;if(Wn.randomUUID&&!e)return Wn.randomUUID();e=e||{};const r=e.random??((i=e.rng)==null?void 0:i.call(e))??ns();if(r.length<16)throw new Error("Random bytes length must be >= 16");return r[6]=r[6]&15|64,r[8]=r[8]&63|128,es(r)}function zn(e){const t=e.replace(/-/g,""),n=[];for(let r=0;r<t.length;r+=2)n.push(parseInt(t.substring(r,r+2),16));return n}function is(e,t){for(let n=0;n<e.length;n++){if(e[n]<t[n])return-1;if(e[n]>t[n])return 1}return 0}function ss(e,t){return is(zn(e),zn(t))}function V(){return rs()}function os(e,t){return e.localeCompare(t)}function us(){let e=os;if(typeof Intl=="object"&&Intl.hasOwnProperty("Collator"))try{e=Intl.Collator("en-US").compare}catch{}return e}const as=us();let cs=0;function Ve(e){return tt(`_${e}`,cs++)}function tt(e,t){return`?${e}-${t}`}class Ce extends Error{constructor(t){super(t),this.name="AttrNotFoundError"}}function ds(e,t){const n=Fn(e,t);if(!n)throw new Ce(`Could not find id attr for ${t}`);return n}function Kn(e,t,n,r){return[fs(e,t,n,r)]}function fs(e,t,n,r){return[e(n,r),ds(t,n).id,e(n,r),e("time",r)]}function ls(e,t,n){return e.map(r=>r===t?n:r)}function qn(e,t,n,r,i){const s=Ee(t,n,i),o=Ln(t,n,i),u=s||o;if(!u)throw new Ce(`Could not find attr for ${[n,i]}`);if(u["value-type"]!=="ref")throw new Error(`Attr ${u.id} is not a ref`);const[a,d]=u["forward-identity"],[c,f]=u["reverse-identity"],h=r+1,p=s?[e(d,r),u.id,e(f,h),Ve("time")]:[e(d,h),u.id,e(f,r),Ve("time")];return[s?f:d,h,p,u,!!s]}function Bn(e,t){if(typeof t!="string")return function(o){return!1};const r=t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&").replace(/%/g,".*").replace(/_/g,"."),i=new RegExp(`^${r}$`,e?void 0:"i");return function(o){return typeof o!="string"?!1:i.test(o)}}function hs(e,t){if(typeof t!="object"||t.hasOwnProperty("$in")||t.hasOwnProperty("in"))return t;const n=e["checked-data-type"]==="date";if(t.hasOwnProperty("$gt"))return{$comparator:!0,$op:n?function(i){return new Date(i[2])>new Date(t.$gt)}:function(i){return i[2]>t.$gt}};if(t.hasOwnProperty("$gte"))return{$comparator:!0,$op:n?function(i){return new Date(i[2])>=new Date(t.$gte)}:function(i){return i[2]>=t.$gte}};if(t.hasOwnProperty("$lt"))return{$comparator:!0,$op:n?function(i){return new Date(i[2])<new Date(t.$lt)}:function(i){return i[2]<t.$lt}};if(t.hasOwnProperty("$lte"))return{$comparator:!0,$op:n?function(i){return new Date(i[2])<=new Date(t.$lte)}:function(i){return i[2]<=t.$lte}};if(t.hasOwnProperty("$like")){const r=Bn(!0,t.$like);return{$comparator:!0,$op:function(s){return r(s[2])}}}if(t.hasOwnProperty("$ilike")){const r=Bn(!1,t.$ilike);return{$comparator:!0,$op:function(s){return r(s[2])}}}return t}function ps(e,t,n,r,i,s){const o=Ee(t,n,i),u=Ln(t,n,i),a=o||u;if(!a)throw new Ce(`No attr for etype = ${n} label = ${i}`);if(s!=null&&s.hasOwnProperty("$isNull")){const d=Ee(t,n,"id");if(!d)throw new Ce(`No attr for etype = ${n} label = id`);return[e(n,r),d.id,{$isNull:{attrId:a.id,isNull:s.$isNull,reverse:!o}},Ve("time")]}return o?[e(n,r),a.id,hs(a,s),Ve("time")]:[s,a.id,e(n,r),Ve("time")]}function ys(e,t,n,r,i){const[s,o,u]=i.reduce((a,d)=>{const[c,f,h]=a,[p,b,g]=qn(e,t,c,f,d);return[p,b,[...h,g]]},[n,r,[]]);return[s,o,u]}function zt(e,t,n,r,i,s){const o=i.slice(0,i.length-1),u=i[i.length-1],[a,d,c]=ys(e,t,n,r,o),f=ps(e,t,a,d,u,s);return c.concat([f])}function bs(e,t){return t?[t].concat(e):e}function _s([e,t]){return e==="or"&&Array.isArray(t)}function gs([e,t]){return e==="and"&&Array.isArray(t)}function Ts(e,t,n){return(r,i)=>{const s=e(r,i);return t==s?s:`${s}-${n}`}}function Qn(e,t,n,r,i,s){const o=e(r,i),u=s.map((a,d)=>{const c=Ts(e,o,d);return Yn(c,n,r,i,a)});return{[t]:{patterns:u,joinSym:o}}}function ws(e){const t=[];for(let n=1;n<=e.length;n++)t.push(e.slice(0,n));return t}function Gn(e,t,n,r,i){return ws(i).map(s=>zt(e,t,n,r,s,{$isNull:!0}))}function Yn(e,t,n,r,i){return Object.entries(i).flatMap(([s,o])=>{if(_s([s,o]))return Qn(e,"or",t,n,r,o);if(gs([s,o]))return Qn(e,"and",t,n,r,o);if(s==="$entityIdStartsWith")return[];const u=s.split(".");if(o!=null&&o.hasOwnProperty("$ne")&&(o=Object.assign(Object.assign({},o),{$not:o.$ne}),delete o.$ne),o!=null&&o.hasOwnProperty("$not")){const a=zt(e,t,n,r,u,o),d=Gn(e,t,n,r,u);return[{or:{patterns:[a,...d],joinSym:e(n,r)}}]}return o!=null&&o.hasOwnProperty("$isNull")&&o.$isNull===!0&&u.length>1?[{or:{patterns:Gn(e,t,n,r,u),joinSym:e(n,r)}}]:zt(e,t,n,r,u,o)})}function ms(e,t,n,r){const i=tt;return r?Yn(i,e,t,n,r).concat(Kn(i,e,t,n)):Kn(i,e,t,n)}function Ss(e,t,n){return[e(t,n),e("time",n)]}function vs(e,t,n,r,i,s){const[o,u,a,d,c]=qn(e,t,n,r,i),f=ls(a,e(n,r),s);return[o,u,f,d,c]}function Os(e,t,{etype:n,level:r,form:i},s){const o=Object.keys(i).filter(u=>u!=="$");return o.length?Object.entries(s).map(function([a,d]){return o.map(function(h){var p,b,g;const w=!!(t.cardinalityInference&&(!((g=(b=(p=t.linkIndex)===null||p===void 0?void 0:p[n])===null||b===void 0?void 0:b[h])===null||g===void 0)&&g.isSingular));try{const[T,m,S]=vs(e,t,n,r,h,a),K=Jn(t,{etype:T,level:m,form:i[h],join:S}),O=w?K[0]:K;return{[h]:O}}catch(T){if(T instanceof Ce)return{[h]:w?void 0:[]};throw T}}).reduce(function(h,p){return Object.assign(Object.assign({},h),p)},d)}):Object.values(s)}function Es(e,t,n){return n==="string"?as(e,t):e>t?1:-1}function nt([e,t],[n,r],i){return t===r||t==null&&r==null?ss(e,n):r==null?1:t==null?-1:Es(t,r,i)}function Kt(e){return e==null?e:new Date(e).getTime()}function As(e,t,n,r){var i;const[s,o,u,a]=e,d=n==="desc"?1:-1;if(((i=t["forward-identity"])===null||i===void 0?void 0:i[2])==="id")return nt(r,[s,a],null)===d;const[c,f]=r,h=t["checked-data-type"],p=h==="date"?Kt(f):f,b=h==="date"?Kt(u):u;return nt([c,p],[s,b],h)===d}function Cs(e,t){const n=t[1];return e.attrs[n]}function js(e,t,n){const r=Object.keys(n)[0];return Ee(e,t,r)}function Ps(e,t,n,r){if(n)return Cs(e,n);if(r)return js(e,t,r)}function ks(e,t,n){var r,i;if(!Array.isArray(n.fields))return Ni(e,t);const s=new Map;for(const o of n.fields){const u=Ee(e,t,o),a=(r=u==null?void 0:u["forward-identity"])===null||r===void 0?void 0:r[2];a&&$t(u)&&s.set(a,u)}if(!s.has("id")){const o=Ee(e,t,"id"),u=(i=o==null?void 0:o["forward-identity"])===null||i===void 0?void 0:i[2];u&&s.set(u,o)}return s}function Is(e,{etype:t,pageInfo:n,dq:r,form:i}){var s,o;const u=(s=i==null?void 0:i.$)===null||s===void 0?void 0:s.order,a=Hn(i),d=Ms(i);let c=Ji(e,r);const f=n==null?void 0:n["start-cursor"],h=Ps(e,t,f,u);if(h&&((o=h==null?void 0:h["forward-identity"])===null||o===void 0?void 0:o[2])!=="id"){const g=h["checked-data-type"]==="date",w=h.id;c=c.map(([T])=>{var m,S,K,O,U;let W=(U=(O=(K=(S=(m=e.eav.get(T))===null||m===void 0?void 0:m.get(w))===null||S===void 0?void 0:S.values())===null||K===void 0?void 0:K.next())===null||O===void 0?void 0:O.value)===null||U===void 0?void 0:U[2];return g&&(W=Kt(W)),[T,W]})}c.sort(d==="asc"?function(w,T){return nt(w,T,h==null?void 0:h["checked-data-type"])}:function(w,T){return nt(T,w,h==null?void 0:h["checked-data-type"])});let p={};const b=ks(e,t,r);for(const g of c){const[w]=g;if(p[w]||!a&&f&&h&&As(f,h,d,g))continue;const T=Fi(e,b,w);T&&(p[w]=T)}return p}function Ms(e){var t;const n=(t=e.$)===null||t===void 0?void 0:t.order;return n&&n[Object.keys(n)[0]]||"asc"}function Hn(e){var t,n,r;const i=(t=e.$)===null||t===void 0?void 0:t.offset,s=(n=e.$)===null||n===void 0?void 0:n.before,o=(r=e.$)===null||r===void 0?void 0:r.after;return!i&&!s&&!o}function Rs(e,{etype:t,level:n,form:r,join:i,pageInfo:s}){var o,u,a,d,c;if(!Hn(r)&&(!s||!s["start-cursor"]))return[];const f=bs(ms(e,t,n,(o=r.$)===null||o===void 0?void 0:o.where),i),h=Ss(tt,t,n),p=(u=r.$)===null||u===void 0?void 0:u.fields,b=Is(e,{etype:t,pageInfo:s,form:r,dq:{where:f,find:h,fields:p}}),g=((a=r.$)===null||a===void 0?void 0:a.limit)||((d=r.$)===null||d===void 0?void 0:d.first)||((c=r.$)===null||c===void 0?void 0:c.last);if(g!=null){const w=Object.entries(b);return w.length<=g?b:Object.fromEntries(w.slice(0,g))}return b}function Ds(e,t){try{return Rs(e,t)}catch(n){if(n instanceof Ce)return{};throw n}}function Jn(e,t){const n=Ds(e,t);return Os(tt,e,t,n)}function xs(e){const t={};for(const[n,r]of Object.entries(e))t[n]={startCursor:r["start-cursor"],endCursor:r["end-cursor"],hasNextPage:r["has-next-page?"],hasPreviousPage:r["has-previous-page?"]};return t}function $s({store:e,pageInfo:t,aggregate:n},r){const s={data:Object.keys(r).reduce(function(u,a){return n!=null&&n[a]||a==="$$ruleParams"||(u[a]=Jn(e,{etype:a,form:r[a],level:0,pageInfo:t==null?void 0:t[a]})),u},{})};return t&&(s.pageInfo=xs(t)),n&&(s.aggregate=n),s}function Us(){const t={__etype:1,__ops:1,create:1,update:1,link:1,unlink:1,delete:1,merge:1,ruleParams:1};return new Set(Object.keys(t))}const Ls=Us();function qt(e,t,n){const r={__etype:e,__ops:n};return new Proxy(r,{get:(i,s)=>{if(s==="__ops")return n;if(s==="__etype")return e;if(Ls.has(s))return(o,u)=>qt(e,t,[...n,u?[s,e,t,o,u]:[s,e,t,o]])}})}function rt(e){return e.startsWith("lookup__")}function Zn(e){const[t,n,...r]=e.split("__");return[n,JSON.parse(r.join("__"))]}function Fs(e){return new Proxy({__etype:e},{get(t,n){if(n==="__etype")return e;const r=n;return rt(r)?qt(e,Zn(r),[]):qt(e,r,[])}})}function Bt(){return new Proxy({},{get(e,t){return Fs(t)}})}Bt();function Ns(e){return e.__ops}function Vs(e,t){const{attrIdMap:n,refSwapAttrIds:r}=e,i=[];for(const o of t){const u=n[o];if(u)i.push(u);else if(Array.isArray(o)&&o.length==2&&n[o[0]]){const[a,d]=o;i.push([n[a],d])}else i.push(o)}const[s]=t;if((s==="add-triple"||s==="retract-triple")&&r.has(t[2])){const o=i[1];i[1]=i[3],i[3]=o}return i}function N(e,t,n){return Object.values(e).find(r=>{const[i,s,o]=r["forward-identity"];return s===t&&o===n})}function we(e,t,n){return Object.values(e).find(r=>{const i=r["reverse-identity"];if(!i)return!1;const[s,o,u]=i;return o===t&&u===n})}function Ws(e){if(Array.isArray(e))return e;const t=Object.entries(e);if(t.length!==1)throw new Error("lookup must be an object with a single unique attr and value.");return t[0]}function Qt(e,t,n){return n.indexOf(".")!==-1&&!N(e,t,n)}function Gt(e){const[t,n,...r]=e.split(".");if(r.length>0||n!=="id")throw new Error(`${e} is not a valid lookup attribute.`);return t}function zs(e,t,n){if(!Qt(e,t,n))return N(e,t,n);const r=Gt(n),i=N(e,t,r)||we(e,t,r);if(i&&i["value-type"]!=="ref")throw new Error(`${n} does not reference a valid link attribute.`);return i}function Yt(e){return typeof e=="string"&&!rt(e)?null:typeof e=="string"&&rt(e)?Zn(e):Ws(e)}function Y(e,t,n){const r=Yt(n);if(r===null)return n;const[i,s]=r,o=zs(e,t,i);if(!o||!o["unique?"])throw new Error(`${i} is not a unique attribute.`);return[o.id,s]}function Xn(e,t,n,r){const i=Y(e,t,n);return Array.isArray(i)?[["add-triple",i,N(e,t,"id").id,i]].concat(r):r}function Ks({attrs:e},[t,n,r]){const i=Object.entries(r).flatMap(([s,o])=>{const u=Array.isArray(o)?o:[o],a=N(e,t,s),d=we(e,t,s);return u.map(c=>a?["add-triple",Y(e,t,n),a.id,Y(e,a["reverse-identity"][1],c)]:["add-triple",Y(e,d["forward-identity"][1],c),d.id,Y(e,t,n)])});return Xn(e,t,n,i)}function qs({attrs:e},[t,n,r]){const i=Object.entries(r).flatMap(([s,o])=>{const u=Array.isArray(o)?o:[o],a=N(e,t,s),d=we(e,t,s);return u.map(c=>a?["retract-triple",Y(e,t,n),a.id,Y(e,a["reverse-identity"][1],c)]:["retract-triple",Y(e,d["forward-identity"][1],c),d.id,Y(e,t,n)])});return Xn(e,t,n,i)}function Bs(e,t,n){if(Array.isArray(n)){const[r,i]=n;for(const s of e||[]){const o=s==null?void 0:s.aev.get(r);if(o){for(const[u,a,d]of G(o,2))if(d===i)return!0}}}else for(const r of e||[]){const i=r==null?void 0:r.eav.get(n);if(i){for(const s of i.keys())if(r.attrs[s]["forward-identity"][1]==t)return!0}}return!1}function er({stores:e,attrs:t},[n,r,i,s]){return(s==null?void 0:s.upsert)===!1?{mode:"update"}:(s==null?void 0:s.upsert)===!0?null:Bs(e,n,r)?{mode:"update"}:null}function Qs(e,t){const{stores:n,attrs:r}=e,[i,s,o,u]=t,a=Rt(o),d=Y(r,i,s);return[["id",d]].concat(Object.entries(a)).map(([f,h])=>{const p=N(r,i,f);return p["checked-data-type"]==="date"&&e.useDateObjects&&(h=Ze(h)),["add-triple",d,p.id,h,{mode:"create"}]})}function Gs(e,t){const{stores:n,attrs:r}=e,[i,s,o,u]=t,a=Rt(o),d=Y(r,i,s),c=er(e,[i,d,o,u]);return[["id",d]].concat(Object.entries(a)).map(([h,p])=>{const b=N(r,i,h);return b["checked-data-type"]==="date"&&e.useDateObjects&&(p=Ze(p)),["add-triple",d,b.id,p,...c?[c]:[]]})}function Ys({attrs:e},[t,n]){return[["delete-entity",Y(e,t,n),t]]}function Hs(e,t){const{stores:n,attrs:r}=e,[i,s,o,u]=t,a=Rt(o),d=Y(r,i,s),c=er(e,[i,d,o,u]),f=Object.entries(a).map(([p,b])=>{const g=N(r,i,p);return["deep-merge-triple",d,g.id,b,...c?[c]:[]]});return[["add-triple",d,N(r,i,"id").id,d,...c?[c]:[]]].concat(f)}function Js({attrs:e},[t,n,r]){return[["rule-params",Y(e,t,n),t,r]]}function Zs(e){const[t,n,r,i,s]=e;if(!i)return e;const o=Object.assign({},i);return delete o.id,[t,n,r,o,...s?[s]:[]]}function Xs(e,t){const[n,...r]=Zs(t);switch(n){case"merge":return Hs(e,r);case"create":return Qs(e,r);case"update":return Gs(e,r);case"link":return Ks(e,r);case"unlink":return qs(e,r);case"delete":return Ys(e,r);case"ruleParams":return Js(e,r);default:throw new Error(`unsupported action ${n}`)}}function eo(e){switch(e){case"string":case"date":case"boolean":case"number":return e;default:return}}function to(e,t,n){var r,i;const s=(i=(r=e.entities[t])===null||r===void 0?void 0:r.attrs)===null||i===void 0?void 0:i[n];if(n==="id")return null;if(!s)throw new Error(`${t}.${n} does not exist in your schema`);const{unique:o,indexed:u}=s==null?void 0:s.config,a=eo(s==null?void 0:s.valueType);return{"index?":u,"unique?":o,"checked-data-type":a}}function it(e,t,n,r){const i=e?to(e,t,n):null,s=V(),u=[V(),t,n];return Object.assign(Object.assign({id:s,"forward-identity":u,"value-type":"blob",cardinality:"one","unique?":!1,"index?":!1,isUnsynced:!0},i||{}),r||{})}function no(e,t,n){return Object.values(e.links).find(i=>i.forward.on===t&&i.forward.label===n||i.reverse.on===t&&i.reverse.label===n)}function ro(e,t,n){const r=no(e,t,n);if(!r)throw new Error(`Couldn't find the link ${t}.${n} in your schema`);const{forward:i,reverse:s}=r;return{"forward-identity":[V(),i.on,i.label],"reverse-identity":[V(),s.on,s.label],cardinality:i.has==="one"?"one":"many","unique?":s.has==="one","on-delete":i.onDelete,"on-delete-reverse":s.onDelete}}function tr(e,t,n,r){const i=e?ro(e,t,n):null,s=V(),o=[V(),t,n],u=[V(),n,t];return Object.assign(Object.assign({id:s,"forward-identity":o,"reverse-identity":u,"value-type":"ref",cardinality:"many","unique?":!1,"index?":!1,isUnsynced:!0},i||{}),r||{})}const io=new Set(["create","update","merge","link","unlink"]),so=new Set(["link","unlink"]),oo=new Set(["create","update","merge"]),uo=new Set(["link","unlink","create","update","merge","delete","ruleParams"]),Ht={"unique?":!0,"index?":!0},ao=Object.assign(Object.assign({},Ht),{cardinality:"one"});function co(e){const t=[],[n,r,i,s]=e;if(!uo.has(n))return t;const o=Yt(i);if(o&&t.push({etype:r,lookupPair:o}),n==="link")for(const[u,a]of Object.entries(s)){const d=Array.isArray(a)?a:[a];for(const c of d){const f=Yt(c);f&&t.push({etype:r,lookupPair:f,linkLabel:u})}}return t}function fo({attrs:e,schema:t},n){var r,i;const[s,o,u]=[new Set,Object.assign({},e),[]];function a(f){o[f.id]=f,u.push(["add-attr",f]),s.add(f.id)}function d(f){f!=null&&f.isUnsynced&&!s.has(f.id)&&(u.push(["add-attr",f]),s.add(f.id))}function c(f,h){const p=N(o,f,h),b=we(o,f,h);d(p),d(b),!p&&!b&&a(tr(t,f,h,ao))}for(const f of n)for(const{etype:h,lookupPair:p,linkLabel:b}of co(f)){const g=p[0];if(b){c(h,b);const w=N(o,h,b),T=we(o,h,b);d(w),d(T);const m=((r=w==null?void 0:w["reverse-identity"])===null||r===void 0?void 0:r[1])||((i=T==null?void 0:T["forward-identity"])===null||i===void 0?void 0:i[1])||b;if(Qt(o,m,g))c(m,Gt(g));else{const S=N(o,m,g);S||a(it(t,m,g,Ht)),d(S)}}else if(Qt(o,h,g))c(h,Gt(g));else{const w=N(o,h,g);w||a(it(t,h,g,Ht)),d(w)}}for(const f of n){const[h,p,b,g]=f;if(io.has(h)){const w=N(o,p,"id");d(w),w||a(it(t,p,"id",{"unique?":!0}));for(const T of Object.keys(g)){const m=N(o,p,T);if(d(m),oo.has(h)&&(m||a(it(t,p,T,T==="id"?{"unique?":!0}:null))),so.has(h)){const S=we(o,p,T);!m&&!S&&a(tr(t,p,T)),d(S)}}}}return[o,u]}function lo(e,t){const r=(Array.isArray(t)?t:[t]).flatMap(a=>Ns(a)),[i,s]=fo(e,r),o=Object.assign(Object.assign({},e),{attrs:i}),u=r.flatMap(a=>Xs(o,a));return[...s,...u]}var nr=function(e,t,n,r){function i(s){return s instanceof n?s:new n(function(o){o(s)})}return new(n||(n=Promise))(function(s,o){function u(c){try{d(r.next(c))}catch(f){o(f)}}function a(c){try{d(r.throw(c))}catch(f){o(f)}}function d(c){c.done?s(c.value):i(c.value).then(u,a)}d((r=r.apply(e,t||[])).next())})};class rr{constructor(t){this.dbName=t,this._storeName="kv",this._dbPromise=this._init()}_init(){return new Promise((t,n)=>{const r=indexedDB.open(this.dbName,1);r.onerror=i=>{n(i)},r.onsuccess=i=>{const s=i.target;t(s.result)},r.onupgradeneeded=i=>{i.target.result.createObjectStore(this._storeName)}})}getItem(t){return nr(this,void 0,void 0,function*(){const n=yield this._dbPromise;return new Promise((r,i)=>{const u=n.transaction([this._storeName],"readonly").objectStore(this._storeName).get(t);u.onerror=a=>{i(a)},u.onsuccess=a=>{u.result?r(u.result):r(null)}})})}setItem(t,n){return nr(this,void 0,void 0,function*(){const r=yield this._dbPromise;return new Promise((i,s)=>{const a=r.transaction([this._storeName],"readwrite").objectStore(this._storeName).put(n,t);a.onerror=d=>{s(d)},a.onsuccess=d=>{i()}})})}}var ho=function(e,t,n,r){function i(s){return s instanceof n?s:new n(function(o){o(s)})}return new(n||(n=Promise))(function(s,o){function u(c){try{d(r.next(c))}catch(f){o(f)}}function a(c){try{d(r.throw(c))}catch(f){o(f)}}function d(c){c.done?s(c.value):i(c.value).then(u,a)}d((r=r.apply(e,t||[])).next())})};class ir{static getIsOnline(){return ho(this,void 0,void 0,function*(){return navigator.onLine})}static listen(t){const n=()=>{t(!0)},r=()=>{t(!1)};return addEventListener("online",n),addEventListener("offline",r),()=>{removeEventListener("online",n),removeEventListener("offline",r)}}}class je extends Error{constructor(t,n){super(t),this.hint=n;const r=new.target.prototype;Object.setPrototypeOf&&Object.setPrototypeOf(this,r),Error.captureStackTrace&&Error.captureStackTrace(this,je),this.name="InstantError"}get[Symbol.toStringTag](){return"InstantError"}}var po=function(e,t,n,r){function i(s){return s instanceof n?s:new n(function(o){o(s)})}return new(n||(n=Promise))(function(s,o){function u(c){try{d(r.next(c))}catch(f){o(f)}}function a(c){try{d(r.throw(c))}catch(f){o(f)}}function d(c){c.done?s(c.value):i(c.value).then(u,a)}d((r=r.apply(e,t||[])).next())})};class st extends je{constructor(t){var n;const r=((n=t.body)===null||n===void 0?void 0:n.message)||`API Error (${t.status})`;super(r,t.body.hint);const i=new.target.prototype;Object.setPrototypeOf&&Object.setPrototypeOf(this,i),Error.captureStackTrace&&Error.captureStackTrace(this,st),this.name="InstantAPIError",this.status=t.status,this.body=t.body}get[Symbol.toStringTag](){return"InstantAPIError"}}function oe(e,t){return po(this,void 0,void 0,function*(){const n=yield fetch(e,t),r=yield n.json();return n.status===200?Promise.resolve(r):Promise.reject(new st({status:n.status,body:r}))})}var Pe=function(e,t,n,r){function i(s){return s instanceof n?s:new n(function(o){o(s)})}return new(n||(n=Promise))(function(s,o){function u(c){try{d(r.next(c))}catch(f){o(f)}}function a(c){try{d(r.throw(c))}catch(f){o(f)}}function d(c){c.done?s(c.value):i(c.value).then(u,a)}d((r=r.apply(e,t||[])).next())})};function yo({apiURI:e,appId:t,email:n}){return oe(`${e}/runtime/auth/send_magic_code`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({"app-id":t,email:n})})}function bo(e){return Pe(this,arguments,void 0,function*({apiURI:t,appId:n,email:r,code:i,refreshToken:s}){return yield oe(`${t}/runtime/auth/verify_magic_code`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(Object.assign({"app-id":n,email:r,code:i},s?{"refresh-token":s}:{}))})})}function _o(e){return Pe(this,arguments,void 0,function*({apiURI:t,appId:n,refreshToken:r}){return yield oe(`${t}/runtime/auth/verify_refresh_token`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({"app-id":n,"refresh-token":r})})})}function go(e){return Pe(this,arguments,void 0,function*({apiURI:t,appId:n}){return yield oe(`${t}/runtime/auth/sign_in_guest`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({"app-id":n})})})}function sr(e){return Pe(this,arguments,void 0,function*({apiURI:t,appId:n,code:r,codeVerifier:i,refreshToken:s}){return yield oe(`${t}/runtime/oauth/token`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({app_id:n,code:r,code_verifier:i,refresh_token:s})})})}function To(e){return Pe(this,arguments,void 0,function*({apiURI:t,appId:n,nonce:r,idToken:i,clientName:s,refreshToken:o}){return yield oe(`${t}/runtime/oauth/id_token`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({app_id:n,nonce:r,id_token:i,client_name:s,refresh_token:o})})})}function wo(e){return Pe(this,arguments,void 0,function*({apiURI:t,appId:n,refreshToken:r}){return yield oe(`${t}/runtime/signout`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({app_id:n,refresh_token:r})})})}var We=function(e,t,n,r){function i(s){return s instanceof n?s:new n(function(o){o(s)})}return new(n||(n=Promise))(function(s,o){function u(c){try{d(r.next(c))}catch(f){o(f)}}function a(c){try{d(r.throw(c))}catch(f){o(f)}}function d(c){c.done?s(c.value):i(c.value).then(u,a)}d((r=r.apply(e,t||[])).next())})};function mo(e){return We(this,arguments,void 0,function*({apiURI:t,appId:n,path:r,file:i,refreshToken:s,contentType:o,contentDisposition:u}){const a={app_id:n,path:r,authorization:`Bearer ${s}`,"content-type":o||i.type};return u&&(a["content-disposition"]=u),yield oe(`${t}/storage/upload`,{method:"PUT",headers:a,body:i})})}function So(e){return We(this,arguments,void 0,function*({apiURI:t,appId:n,path:r,refreshToken:i}){const{data:s}=yield oe(`${t}/storage/files?app_id=${n}&filename=${encodeURIComponent(r)}`,{method:"DELETE",headers:{"content-type":"application/json",authorization:`Bearer ${i}`}});return s})}function vo(e){return We(this,arguments,void 0,function*({apiURI:t,appId:n,fileName:r,refreshToken:i,metadata:s={}}){const{data:o}=yield oe(`${t}/storage/signed-upload-url`,{method:"POST",headers:{"content-type":"application/json",authorization:`Bearer ${i}`},body:JSON.stringify({app_id:n,filename:r})});return o})}function Oo(e,t){return We(this,void 0,void 0,function*(){return(yield fetch(e,{method:"PUT",body:t,headers:{"Content-Type":t.type}})).ok})}function Eo(e){return We(this,arguments,void 0,function*({apiURI:t,appId:n,path:r,refreshToken:i}){const{data:s}=yield oe(`${t}/storage/signed-download-url?app_id=${n}&filename=${encodeURIComponent(r)}`,{method:"GET",headers:{"content-type":"application/json",authorization:`Bearer ${i}`}});return s})}let Jt=!1,or=!1,ur=!1;typeof window<"u"&&typeof window.localStorage<"u"&&(Jt=!!window.localStorage.getItem("devBackend"),or=!!window.localStorage.getItem("__instantLogging"),ur=!!window.localStorage.getItem("__devtoolLocalDash"));function ar(e,t){if(!t)return e;const n={};return t.forEach(r=>{n[r]=e[r]}),n}function Ao(e,t,n){var r,i;const s={peers:{}};if(t&&"user"in t?t.user:!0){const u=ar((r=e.user)!==null&&r!==void 0?r:{},t==null?void 0:t.keys);s.user=Object.assign(Object.assign({},u),{peerId:n})}for(const u of Object.keys((i=e.peers)!==null&&i!==void 0?i:{})){const a=(t==null?void 0:t.peers)===void 0,d=Array.isArray(t==null?void 0:t.peers)&&(t==null?void 0:t.peers.includes(u));if(a||d){const c=ar(e.peers[u],t==null?void 0:t.keys);s.peers[u]=Object.assign(Object.assign({},c),{peerId:u})}}return s}function Co(e,t){if(e.isLoading!==t.isLoading||e.error!==t.error||(e.user||t.user)&&(!e.user||!t.user||!jn(e.user,t.user))||!Cn(e.peers,t.peers))return!0;for(const r of Object.keys(e.peers))if(!jn(e.peers[r],t.peers[r]))return!0;return!1}class cr{constructor(){this.promise=new Promise((t,n)=>{this._resolve=t,this._reject=n})}resolve(t){this._resolve(t)}reject(t){this._reject(t)}}var ze=function(e,t,n,r){function i(s){return s instanceof n?s:new n(function(o){o(s)})}return new(n||(n=Promise))(function(s,o){function u(c){try{d(r.next(c))}catch(f){o(f)}}function a(c){try{d(r.throw(c))}catch(f){o(f)}}function d(c){c.done?s(c.value):i(c.value).then(u,a)}d((r=r.apply(e,t||[])).next())})};function jo(e,t){typeof requestIdleCallback>"u"?e():requestIdleCallback(e,{timeout:t})}class dr{constructor(t,n,r,i,s=d=>d,o=d=>d,u=100,a=1e3){this._subs=[],this._nextSave=null,this._persister=t,this._key=n,this._onMerge=i,this._loadedCbs=[],this._isLoading=!0,this.currentValue=r,this.serialize=s,this.parse=o,this._saveThrottleMs=u,this._pendingSaveCbs=[],this._version=0,this._idleCallbackMaxWaitMs=a,this._load()}_getFromStorage(){return ze(this,void 0,void 0,function*(){try{return this.parse(yield this._persister.getItem(this._key))}catch(t){return console.error(`Unable to read from storage for key=${this._key}`,t),null}})}_load(){return ze(this,void 0,void 0,function*(){const t=yield this._getFromStorage();this._isLoading=!1,this._onMerge(t,this.currentValue);for(const n of this._loadedCbs)n()})}waitForLoaded(){return ze(this,void 0,void 0,function*(){if(!this._isLoading)return;yield new Promise(n=>{this._loadedCbs.push(n)})})}isLoading(){return this._isLoading}version(){return this._version}waitForSync(){return ze(this,void 0,void 0,function*(){if(!this._nextSave)return;yield new Promise(n=>{this._pendingSaveCbs.push(n)})})}_writeToStorage(){this._persister.setItem(this._key,this.serialize(this.currentValue));for(const t of this._pendingSaveCbs)t();this._pendingSaveCbs.length=0}flush(){return ze(this,void 0,void 0,function*(){this._nextSave&&(clearTimeout(this._nextSave),this._writeToStorage())})}_enqueuePersist(t){if(this._nextSave){t&&this._pendingSaveCbs.push(t);return}this._nextSave=setTimeout(()=>{jo(()=>{this._nextSave=null,this._writeToStorage()},this._idleCallbackMaxWaitMs)},this._saveThrottleMs)}set(t,n){this._version++,this.currentValue=t(this.currentValue),this._isLoading?this._loadedCbs.push(()=>this._enqueuePersist(n)):this._enqueuePersist(n);for(const r of this._subs)r(this.currentValue)}subscribe(t){return this._subs.push(t),t(this.currentValue),()=>{this._subs=this._subs.filter(n=>n!==t)}}}function fr(e,t=[]){e.forEach(n=>{const{data:r}=n,{"datalog-result":i}=r,{"join-rows":s}=i;for(const o of s)for(const u of o)t.push(u);fr(n["child-nodes"],t)})}function lr(e){const t=[];return fr(e,t),t}function hr(e){return Object.values(e.links).reduce((t,n)=>{var r,i,s,o;return(r=t[s=n.forward.on])!==null&&r!==void 0||(t[s]={}),t[n.forward.on][n.forward.label]={isForward:!0,isSingular:n.forward.has==="one",link:n},(i=t[o=n.reverse.on])!==null&&i!==void 0||(t[o]={}),t[n.reverse.on][n.reverse.label]={isForward:!1,isSingular:n.reverse.has==="one",link:n},t},{})}const pr="v0.22.35";function Po(e,t){return{info:e?(...n)=>console.info(...n,t()):()=>{},debug:e?(...n)=>console.debug(...n,t()):()=>{},error:e?(...n)=>console.error(...n,t()):()=>{}}}class he{constructor(t,n,r,i={indexed:!1,unique:!1}){this.valueType=t,this.required=n,this.isIndexed=r,this.config=i,this.metadata={}}clientRequired(){return new he(this.valueType,!1,this.isIndexed,this.config)}optional(){return new he(this.valueType,!1,this.isIndexed,this.config)}unique(){return new he(this.valueType,this.required,this.isIndexed,Object.assign(Object.assign({},this.config),{unique:!0}))}indexed(){return new he(this.valueType,this.required,!0,Object.assign(Object.assign({},this.config),{indexed:!0}))}}class M extends Error{constructor(t,n){const r=n?`At path '${n}': ${t}`:t;super(r),this.name="QueryValidationError"}}const yr=["where","order","limit","last","first","offset","after","before","fields","aggregate"],ko=e=>e.valueType||"unknown",br=(e,t,n=!1)=>{if(n||e==null)return!0;switch(t){case"string":return typeof e=="string";case"number":return typeof e=="number"&&!isNaN(e);case"boolean":return typeof e=="boolean";case"date":return e instanceof Date||typeof e=="string"||typeof e=="number";default:return!0}},Io=(e,t,n,r,i,s,o)=>{const u=s.valueType==="json",a=(d,c,f)=>{if(!br(f,c,u))throw new M(`Invalid value for operator '${d}' on attribute '${r}' in entity '${i}'. Expected ${c}, but received: ${typeof f}`,o)};switch(e){case"in":case"$in":if(!Array.isArray(t))throw new M(`Operator '${e}' for attribute '${r}' in entity '${i}' must be an array, but received: ${typeof t}`,o);for(const d of t)a(e,n,d);break;case"$not":case"$ne":case"$gt":case"$lt":case"$gte":case"$lte":a(e,n,t);break;case"$like":case"$ilike":if(a(e,"string",t),e==="$ilike"&&!s.isIndexed)throw new M(`Operator '${e}' can only be used with indexed attributes, but '${r}' in entity '${i}' is not indexed`,o);break;case"$isNull":a(e,"boolean",t);break;default:throw new M(`Unknown operator '${e}' for attribute '${r}' in entity '${i}'`,o)}},ke=(e,t,n,r,i)=>{const s=ko(n),o=n.valueType==="json";if(typeof e=="object"&&e!==null&&!Array.isArray(e)){if(o)return;const a=e;for(const[d,c]of Object.entries(a))Io(d,c,s,t,r,n,`${i}.${d}`)}else if(!br(e,s,o))throw new M(`Invalid value for attribute '${t}' in entity '${r}'. Expected ${s}, but received: ${typeof e}`,i)},Mo=(e,t,n,r,i)=>{const s=e.split(".");if(s.length<2)throw new M(`Invalid dot notation path '${e}'. Must contain at least one dot.`,i);let o=n;for(let c=0;c<s.length-1;c++){const f=s[c],h=r.entities[o];if(!h)throw new M(`Entity '${o}' does not exist in schema while traversing dot notation path '${e}'.`,i);const p=h.links[f];if(!p){const b=Object.keys(h.links);throw new M(`Link '${f}' does not exist on entity '${o}' in dot notation path '${e}'. Available links: ${b.length>0?b.join(", "):"none"}`,i)}o=p.entityName}const u=s[s.length-1],a=r.entities[o];if(!a)throw new M(`Target entity '${o}' does not exist in schema for dot notation path '${e}'.`,i);if(u==="id"){if(typeof t=="string"&&!Ae(t))throw new M(`Invalid value for id field in entity '${o}'. Expected a UUID, but received: ${t}`,i);ke(t,e,new he("string",!1,!0),n,i);return}const d=a.attrs[u];if(Object.keys(a.links).includes(u)){if(typeof t=="string"&&!Ae(t))throw new M(`Invalid value for link '${u}' in entity '${o}'. Expected a UUID, but received: ${t}`,i);ke(t,e,new he("string",!1,!0),n,i);return}if(!d){const c=Object.keys(a.attrs);throw new M(`Attribute '${u}' does not exist on entity '${o}' in dot notation path '${e}'. Available attributes: ${c.length>0?c.join(", ")+", id":"id"}`,i)}ke(t,e,d,n,i)},_r=(e,t,n,r)=>{for(const[i,s]of Object.entries(e)){if(i==="or"||i==="and"){if(Array.isArray(s))for(const d of s)typeof d=="object"&&d!==null&&_r(d,t,n,`${r}.${i}[${d}]`);continue}if(i==="id"){ke(s,"id",new he("string",!1,!0),t,`${r}.id`);continue}if(i.includes(".")){Mo(i,s,t,n,`${r}.${i}`);continue}const o=n.entities[t];if(!o)continue;const u=o.attrs[i],a=o.links[i];if(!u&&!a){const d=Object.keys(o.attrs),c=Object.keys(o.links);throw new M(`Attribute or link '${i}' does not exist on entity '${t}'. Available attributes: ${d.length>0?d.join(", "):"none"}. Available links: ${c.length>0?c.join(", "):"none"}`,`${r}.${i}`)}if(u)ke(s,i,u,t,`${r}.${i}`);else if(a){if(typeof s=="string"&&!Ae(s))throw new M(`Invalid value for link '${i}' in entity '${t}'. Expected a UUID, but received: ${s}`,`${r}.${i}`);const d=new he("string",!1,!0);ke(s,i,d,t,`${r}.${i}`)}}},Ro=(e,t,n,r,i=0)=>{for(const o of Object.keys(e))if(!yr.includes(o))throw new M(`Invalid query parameter '${o}' in $ object. Valid parameters are: ${yr.join(", ")}. Found: ${o}`,r);const s=["limit","offset","before","after","first","last"];for(const o of s)if(e[o]!==void 0&&i>0)throw new M(`'${o}' can only be used on top-level namespaces. It cannot be used in nested queries.`,r);if(e.where&&n){if(typeof e.where!="object"||e.where===null)throw new M(`'where' clause must be an object in entity '${t}', but received: ${typeof e.where}`,r?`${r}.where`:void 0);_r(e.where,t,n,r?`${r}.where`:"where")}},gr=(e,t,n,r,i=0)=>{var s;if(!e||typeof e!="object")throw new M(`Query part for entity '${t}' must be an object, but received: ${typeof e}`,r);for(const o of Object.keys(e))if(o!=="$"){if(n&&!(o in n.entities[t].links)){const a=Object.keys(n.entities[t].links);throw new M(`Link '${o}' does not exist on entity '${t}'. Available links: ${a.length>0?a.join(", "):"none"}`,`${r}.${o}`)}const u=e[o];if(typeof u=="object"&&u!==null){const a=(s=n==null?void 0:n.entities[t].links[o])===null||s===void 0?void 0:s.entityName;a&&gr(u,a,n,`${r}.${o}`,i+1)}}else{const u=e[o];if(typeof u!="object"||u===null)throw new M(`Query parameter '$' must be an object in entity '${t}', but received: ${typeof u}`,`${r}.$`);Ro(u,t,n,`${r}.$`,i)}},Tr=(e,t)=>{if(typeof e!="object"||e===null)throw new M(`Query must be an object, but received: ${typeof e}${e===null?" (null)":""}`);if(Array.isArray(e))throw new M(`Query must be an object, but received: ${typeof e}`);const n=e;for(const r of Object.keys(n)){if(Array.isArray(e[r]))throw new M(`Query keys must be strings, but found key of type: ${typeof r}`,r);if(typeof r!="string")throw new M(`Query keys must be strings, but found key of type: ${typeof r}`,r);if(r!=="$$ruleParams"){if(t&&!t.entities[r]){const i=Object.keys(t.entities);throw new M(`Entity '${r}' does not exist in schema. Available entities: ${i.length>0?i.join(", "):"none"}`,r)}gr(n[r],r,t,r,0)}}},wr=e=>typeof e!="string"?!1:rt(e)?!0:Ae(e);class ne extends Error{constructor(t){super(t),this.name="TransactionValidationError"}}const mr=e=>e.length>0?e.join(", "):"none",Do=(e,t)=>new ne(`Entity '${e}' does not exist in schema. Available entities: ${mr(t)}`),Sr={string:e=>typeof e=="string",number:e=>typeof e=="number"&&!isNaN(e),boolean:e=>typeof e=="boolean",date:e=>e instanceof Date||typeof e=="string"||typeof e=="number",json:()=>!0},xo=(e,t)=>{var n,r;return e==null?!0:(r=(n=Sr[t.valueType])===null||n===void 0?void 0:n.call(Sr,e))!==null&&r!==void 0?r:!1},vr=(e,t)=>{const n=t.entities[e];if(!n)throw Do(e,Object.keys(t.entities));return n},Zt=(e,t,n)=>{const r=vr(e,n);if(typeof t!="object"||t===null)throw new ne(`Arguments for data operation on entity '${e}' must be an object, but received: ${typeof t}`);for(const[i,s]of Object.entries(t)){if(i==="id")continue;const o=r.attrs[i];if(o&&!xo(s,o))throw new ne(`Invalid value for attribute '${i}' in entity '${e}'. Expected ${o.valueType}, but received: ${typeof s}`)}},Or=(e,t,n)=>{const r=vr(e,n);if(typeof t!="object"||t===null)throw new ne(`Arguments for link operation on entity '${e}' must be an object, but received: ${typeof t}`);for(const[i,s]of Object.entries(t)){if(!r.links[i]){const u=Object.keys(r.links);throw new ne(`Link '${i}' does not exist on entity '${e}'. Available links: ${mr(u)}`)}if(s!=null){if(Array.isArray(s)){for(const u of s)if(!wr(u))throw new ne(`Invalid entity ID in link '${i}' for entity '${e}'. Expected a UUID or a lookup, but received: ${u}`)}else if(!wr(s))throw new ne(`Invalid UUID in link '${i}' for entity '${e}'. Expected a UUID, but received: ${s}`)}}},$o={create:Zt,update:Zt,merge:Zt,link:Or,unlink:Or,delete:()=>{}},Uo=(e,t)=>{if(!t)return;const[n,r,i,s]=e;if(!Array.isArray(i)&&!Ae(i))throw new ne(`Invalid id for entity '${r}'. Expected a UUID, but received: ${i}`);if(typeof r!="string")throw new ne(`Entity name must be a string, but received: ${typeof r}`);const o=$o[n];o&&s!==void 0&&o(r,s,t)},Lo=(e,t)=>{const n=Array.isArray(e)?e:[e];for(const r of n){if(!r||typeof r!="object")throw new ne(`Transaction chunk must be an object, but received: ${typeof r}`);if(!Array.isArray(r.__ops))throw new ne(`Transaction chunk must have __ops array, but received: ${typeof r.__ops}`);for(const i of r.__ops){if(!Array.isArray(i))throw new ne(`Transaction operation must be an array, but received: ${typeof i}`);Uo(i,t)}}};var Er=function(e,t,n,r){function i(s){return s instanceof n?s:new n(function(o){o(s)})}return new(n||(n=Promise))(function(s,o){function u(c){try{d(r.next(c))}catch(f){o(f)}}function a(c){try{d(r.throw(c))}catch(f){o(f)}}function d(c){c.done?s(c.value):i(c.value).then(u,a)}d((r=r.apply(e,t||[])).next())})};let Ar=0;class Cr{constructor(t){this.type="ws",this.id=`${this.type}_${Ar++}`,this.conn=new WebSocket(t),this.conn.onopen=n=>{this.onopen&&this.onopen({target:this})},this.conn.onmessage=n=>{this.onmessage&&this.onmessage({target:this,message:JSON.parse(n.data.toString())})},this.conn.onclose=n=>{this.onclose&&this.onclose({target:this})},this.conn.onerror=n=>{this.onerror&&this.onerror({target:this})}}close(){this.conn.close()}isOpen(){return this.conn.readyState===WebSocket.OPEN}isConnecting(){return this.conn.readyState===WebSocket.CONNECTING}send(t){return this.conn.send(JSON.stringify(t))}}class Fo{constructor(t,n){this.type="sse",this.initParams=null,this.sendQueue=[],this.closeFired=!1,this.sseInitTimeout=null,this.id=`${this.type}_${Ar++}`,this.url=n,this.ES=t,this.conn=new t(n),this.sseInitTimeout=setTimeout(()=>{this.initParams||this.handleError()},1e4),this.conn.onmessage=r=>{const i=JSON.parse(r.data);if(i.op==="sse-init"){this.initParams={machineId:i["machine-id"],sessionId:i["session-id"],sseToken:i["sse-token"]},this.onopen&&this.onopen({target:this}),clearTimeout(this.sseInitTimeout);return}this.onmessage&&this.onmessage({target:this,message:i})},this.conn.onerror=r=>{this.handleError()}}handleError(){try{this.onerror&&this.onerror({target:this})}finally{this.handleClose()}}handleClose(){this.conn.close(),this.onclose&&!this.closeFired&&(this.closeFired=!0,this.onclose({target:this}))}postMessages(t){return Er(this,void 0,void 0,function*(){try{(yield fetch(this.url,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({machine_id:this.initParams.machineId,session_id:this.initParams.sessionId,sse_token:this.initParams.sseToken,messages:t})})).ok||this.handleError()}catch{this.handleError()}})}flushQueue(){return Er(this,void 0,void 0,function*(){if(this.sendPromise||!this.sendQueue.length)return;const t=this.sendQueue;this.sendQueue=[];const n=this.postMessages(t);this.sendPromise=n,n.then(()=>{this.sendPromise=null,this.flushQueue()})})}send(t){if(!this.isOpen()||!this.initParams)throw this.isConnecting()?new Error("Failed to execute 'send' on 'EventSource': Still in CONNECTING state."):this.conn.readyState===this.ES.CLOSED?new Error("EventSource is already in CLOSING or CLOSED state."):new Error("EventSource is in invalid state.");this.sendQueue.push(t),this.flushQueue()}isOpen(){return this.conn.readyState===this.ES.OPEN&&this.initParams!==null}isConnecting(){return this.conn.readyState===this.ES.CONNECTING||this.conn.readyState===this.ES.OPEN&&this.initParams===null}close(){this.handleClose()}}var x=function(e,t,n,r){function i(s){return s instanceof n?s:new n(function(o){o(s)})}return new(n||(n=Promise))(function(s,o){function u(c){try{d(r.next(c))}catch(f){o(f)}}function a(c){try{d(r.throw(c))}catch(f){o(f)}}function d(c){c.done?s(c.value):i(c.value).then(u,a)}d((r=r.apply(e,t||[])).next())})},No=function(e,t){var n={};for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&t.indexOf(r)<0&&(n[r]=e[r]);if(e!=null&&typeof Object.getOwnPropertySymbols=="function")for(var i=0,r=Object.getOwnPropertySymbols(e);i<r.length;i++)t.indexOf(r[i])<0&&Object.prototype.propertyIsEnumerable.call(e,r[i])&&(n[r[i]]=e[r[i]]);return n};const pe={CONNECTING:"connecting",OPENED:"opened",AUTHENTICATED:"authenticated",CLOSED:"closed",ERRORED:"errored"},Vo=3e4,Wo=3e4,zo=200,Ko={apiURI:"https://api.instantdb.com",websocketURI:"wss://api.instantdb.com/runtime/session"},Xt="_instant_oauth_redirect",en="currentUser";function qo({transportType:e,appId:t,apiURI:n,wsURI:r,EventSourceImpl:i}){if(!i)return new Cr(`${r}?app_id=${t}`);switch(e){case"ws":return new Cr(`${r}?app_id=${t}`);case"sse":return new Fo(i,`${n}/runtime/sse?app_id=${t}`);default:throw new Error("Unknown transport type "+e)}}function Bo(){return typeof window<"u"||typeof chrome<"u"}const jr={"set-presence":!0,"set-presence-ok":!0,"refresh-presence":!0,"patch-presence":!0};function Qo(e,t){var n;const r=typeof e=="string"?JSON.parse(e):e;for(const i in r){const s=r[i];if(!((n=s==null?void 0:s.result)===null||n===void 0)&&n.store){const o=s.result.store;s.result.store=ji(Object.assign(Object.assign({},o),{useDateObjects:t}))}}return r}function Go(e){var t;const n={};for(const r in e){const i=e[r],s=Object.assign({},i);!((t=i.result)===null||t===void 0)&&t.store&&(s.result=Object.assign(Object.assign({},i.result),{store:Ci(i.result.store)})),n[r]=s}return n}function Pr(e){return[...e].sort((t,n)=>{const[r,i]=t,[s,o]=n,u=i.order||0,a=o.order||0;return u==a?r<s?-1:r>s?1:0:u-a})}class Yo{constructor(t,n=rr,r=ir,i,s){var o,u,a;if(this._isOnline=!0,this._isShutdown=!1,this.status=pe.CONNECTING,this.queryCbs={},this.queryOnceDfds={},this.authCbs=[],this.attrsCbs=[],this.mutationErrorCbs=[],this.connectionStatusCbs=[],this.mutationDeferredStore=new Map,this._reconnectTimeoutId=null,this._reconnectTimeoutMs=0,this._transportType="ws",this._wsOk=null,this._localIdPromises={},this._errorMessage=null,this._oauthCallbackResponse=null,this._linkIndex=null,this._rooms={},this._roomsPendingLeave={},this._presence={},this._broadcastQueue=[],this._broadcastSubs={},this._currentUserCached={isLoading:!0,error:void 0,user:void 0},this._beforeUnloadCbs=[],this._dataForQueryCache={},this._inFlightMutationEventIds=new Set,this._onMergeQuerySubs=(d,c)=>{const f=d||{},h=Object.assign({},c);Object.entries(c).forEach(([b,g])=>{var w;const T=(w=f==null?void 0:f[b])===null||w===void 0?void 0:w.result,m=g.result;T&&!m&&(h[b].result=T)}),Object.keys(f).filter(b=>!c[b]).sort((b,g)=>{var w,T;const m=((w=f[b])===null||w===void 0?void 0:w.lastAccessed)||0;return(((T=f[g])===null||T===void 0?void 0:T.lastAccessed)||0)-m}).slice(0,this.queryCacheLimit).forEach(b=>{h[b]=f[b]}),this.querySubs.set(b=>h),this.loadedNotifyAll()},this._onMergePendingMutations=(d,c)=>{const f=new Map([...d.entries(),...c.entries()]);this.pendingMutations.set(p=>f),this.loadedNotifyAll(),this._rewriteMutationsSorted(this.attrs,d).forEach(([p,b])=>{!c.has(p)&&!b["tx-id"]&&this._sendMutation(p,b)})},this.getPreviousResult=d=>{const c=B(d);return this.dataForQuery(c)},this.notifyOne=d=>{var c,f;const h=(c=this.queryCbs[d])!==null&&c!==void 0?c:[],p=(f=this._dataForQueryCache[d])===null||f===void 0?void 0:f.data,b=this.dataForQuery(d);b&&(Je(b,p)||h.forEach(g=>g.cb(b)))},this.notifyOneQueryOnce=d=>{var c;const f=(c=this.queryOnceDfds[d])!==null&&c!==void 0?c:[],h=this.dataForQuery(d);f.forEach(p=>{this._completeQueryOnce(p.q,d,p.dfd),p.dfd.resolve(h)})},this.notifyQueryError=(d,c)=>{(this.queryCbs[d]||[]).forEach(h=>h.cb({error:c}))},this.pushTx=d=>{this.config.disableValidation||Lo(d,this.config.schema);try{const c=lo({attrs:this.optimisticAttrs(),schema:this.config.schema,stores:Object.values(this.querySubs.currentValue).map(f=>{var h;return(h=f==null?void 0:f.result)===null||h===void 0?void 0:h.store}),useDateObjects:this.config.useDateObjects},d);return this.pushOps(c)}catch(c){return this.pushOps([],c)}},this.pushOps=(d,c)=>{const f=V(),h=[...this.pendingMutations.currentValue.values()],p=Math.max(0,...h.map(w=>w.order||0))+1,b={op:"transact","tx-steps":d,created:Date.now(),error:c,order:p};this.pendingMutations.set(w=>(w.set(f,b),w));const g=new cr;return this.mutationDeferredStore.set(f,g),this._sendMutation(f,b),this.notifyAll(),g.promise},this._transportOnOpen=d=>{const c=d.target;if(this._transport!==c){this._log.info("[socket][open]",c.id,"skip; this is no longer the current transport");return}this._log.info("[socket][open]",this._transport.id),this._setStatus(pe.OPENED),this.getCurrentUser().then(f=>{var h;this._trySend(V(),{op:"init","app-id":this.config.appId,"refresh-token":(h=f.user)===null||h===void 0?void 0:h.refresh_token,versions:this.versions,"__admin-token":this.config.__adminToken})}).catch(f=>{this._log.error("[socket][error]",c.id,f)})},this._transportOnMessage=d=>{const c=d.target,f=d.message;if(this._transport!==c){this._log.info("[socket][message]",c.id,f,"skip; this is no longer the current transport");return}!this._wsOk&&c.type==="ws"&&(this._wsOk=!0),this._transportType="ws",this._handleReceive(c.id,d.message)},this._transportOnError=d=>{const c=d.target;if(this._transport!==c){this._log.info("[socket][error]",c.id,"skip; this is no longer the current transport");return}this._log.error("[socket][error]",c.id,d)},this._scheduleReconnect=()=>{!this._wsOk&&this._transportType!=="sse"&&(this._transportType="sse",this._reconnectTimeoutMs=0),setTimeout(()=>{if(this._reconnectTimeoutMs=Math.min(this._reconnectTimeoutMs+1e3,1e4),!this._isOnline){this._log.info("[socket][close]",this._transport.id,"we are offline, no need to start socket");return}this._startSocket()},this._reconnectTimeoutMs)},this._transportOnClose=d=>{const c=d.target;if(this._transport!==c){this._log.info("[socket][close]",c.id,"skip; this is no longer the current transport");return}this._setStatus(pe.CLOSED);for(const f of Object.values(this._rooms))f.isConnected=!1;if(this._isShutdown){this._log.info("[socket][close]",c.id,"Reactor has been shut down and will not reconnect");return}this._log.info("[socket][close]",c.id,"schedule reconnect, ms =",this._reconnectTimeoutMs),this._scheduleReconnect()},this._EventSource=s,this.config=Object.assign(Object.assign({},Ko),t),this.queryCacheLimit=(o=this.config.queryCacheLimit)!==null&&o!==void 0?o:10,this._pendingTxCleanupTimeout=(u=this.config.pendingTxCleanupTimeout)!==null&&u!==void 0?u:Wo,this._pendingMutationCleanupThreshold=(a=this.config.pendingMutationCleanupThreshold)!==null&&a!==void 0?a:zo,this._log=Po(t.verbose||Jt||or,()=>this._reactorStats()),this.versions=Object.assign(Object.assign({},i||{}),{"@instantdb/core":pr}),this.config.schema&&(this._linkIndex=hr(this.config.schema)),!!Bo()){if(!t.appId)throw new Error("Instant must be initialized with an appId.");if(!Ae(t.appId))throw new Error(`Instant must be initialized with a valid appId. \`${t.appId}\` is not a valid uuid.`);typeof BroadcastChannel=="function"&&(this._broadcastChannel=new BroadcastChannel("@instantdb"),this._broadcastChannel.addEventListener("message",d=>x(this,void 0,void 0,function*(){var c;try{if(((c=d.data)===null||c===void 0?void 0:c.type)==="auth"){const f=yield this.getCurrentUser();this.updateUser(f.user)}}catch(f){this._log.error("[error] handle broadcast channel",f)}}))),this._initStorage(n),this._oauthCallbackResponse=this._oauthLoginInit(),this.getCurrentUser(),r.getIsOnline().then(d=>{this._isOnline=d,this._startSocket(),r.listen(c=>{c!==this._isOnline&&(this._log.info("[network] online =",c),this._isOnline=c,this._isOnline?this._startSocket():(this._log.info("Changing status from",this.status,"to",pe.CLOSED),this._setStatus(pe.CLOSED)))})}),typeof addEventListener<"u"&&(this._beforeUnload=this._beforeUnload.bind(this),addEventListener("beforeunload",this._beforeUnload))}}updateSchema(t){this.config=Object.assign(Object.assign({},this.config),{schema:t,cardinalityInference:!!t}),this._linkIndex=t?hr(this.config.schema):null}_reactorStats(){return{inFlightMutationCount:this._inFlightMutationEventIds.size,pendingMutationCount:this.pendingMutations.currentValue.size,transportType:this._transportType}}_initStorage(t){this._persister=new t(`instant_${this.config.appId}_5`),this.querySubs=new dr(this._persister,"querySubs",{},this._onMergeQuerySubs,Go,n=>Qo(n,this.config.useDateObjects)),this.pendingMutations=new dr(this._persister,"pendingMutations",new Map,this._onMergePendingMutations,n=>[...n.entries()],n=>new Map(typeof n=="string"?JSON.parse(n):n),100,100),this._beforeUnloadCbs.push(()=>{this.pendingMutations.flush(),this.querySubs.flush()})}_beforeUnload(){for(const t of this._beforeUnloadCbs)t()}_finishTransaction(t,n,r){const i=this.mutationDeferredStore.get(n);this.mutationDeferredStore.delete(n);const s=t!=="error"&&t!=="timeout";if(!i&&!s&&console.error("Mutation failed",Object.assign({status:t,eventId:n},r)),!!i)if(s)i.resolve({status:t,eventId:n});else if(r.type){const{status:o}=r,u=No(r,["status"]);i.reject(new st({body:u,status:o}))}else i.reject(new je(r.message,r.hint))}_setStatus(t,n){this.status=t,this._errorMessage=n,this.notifyConnectionStatusSubs(t)}_flushEnqueuedRoomData(t){var n,r;const i=(r=(n=this._presence[t])===null||n===void 0?void 0:n.result)===null||r===void 0?void 0:r.user,s=this._broadcastQueue[t];if(this._broadcastQueue[t]=[],i&&this._trySetPresence(t,i),s)for(const o of s){const{topic:u,roomType:a,data:d}=o;this._tryBroadcast(t,a,u,d)}}_handleReceive(t,n){var r,i,s,o,u,a;const d=!!this.config.schema&&("cardinalityInference"in this.config?!!this.config.cardinalityInference:!0);switch(jr[n.op]||this._log.info("[receive]",t,n.op,n),n.op){case"init-ok":this._setStatus(pe.AUTHENTICATED),this._reconnectTimeoutMs=0,this._setAttrs(n.attrs),this._flushPendingMessages(),this._sessionId=n["session-id"];for(const k of Object.keys(this._rooms)){const L=(i=(r=this._presence[k])===null||r===void 0?void 0:r.result)===null||i===void 0?void 0:i.user;this._tryJoinRoom(k,L)}break;case"add-query-exists":this.notifyOneQueryOnce(B(n.q));break;case"add-query-ok":const{q:c,result:f}=n,h=B(c),p=(o=(s=f==null?void 0:f[0])===null||s===void 0?void 0:s.data)===null||o===void 0?void 0:o["page-info"],b=(a=(u=f==null?void 0:f[0])===null||u===void 0?void 0:u.data)===null||a===void 0?void 0:a.aggregate,g=lr(f),w=Lt(this.attrs,g,d,this._linkIndex,this.config.useDateObjects);this.querySubs.set(k=>(k[h].result={store:w,pageInfo:p,aggregate:b,processedTxId:n["processed-tx-id"]},k)),this._cleanupPendingMutationsQueries(),this.notifyOne(h),this.notifyOneQueryOnce(h),this._cleanupPendingMutationsTimeout();break;case"refresh-ok":const{computations:T,attrs:m}=n,S=n["processed-tx-id"];m&&this._setAttrs(m),this._cleanupPendingMutationsTimeout();const K=this._rewriteMutations(this.attrs,this.pendingMutations.currentValue,S);K!==this.pendingMutations.currentValue&&this.pendingMutations.set(()=>K);const O=Pr(K.entries()),U=T.map(k=>{var L,H,J,ue;const ae=k["instaql-query"],te=k["instaql-result"],ct=B(ae),dt=lr(te),ft=Lt(this.attrs,dt,d,this._linkIndex,this.config.useDateObjects),lt=this._applyOptimisticUpdates(ft,O,S),ht=(H=(L=te==null?void 0:te[0])===null||L===void 0?void 0:L.data)===null||H===void 0?void 0:H["page-info"],sn=(ue=(J=te==null?void 0:te[0])===null||J===void 0?void 0:J.data)===null||ue===void 0?void 0:ue.aggregate;return{hash:ct,store:lt,pageInfo:ht,aggregate:sn}});U.forEach(({hash:k,store:L,pageInfo:H,aggregate:J})=>{this.querySubs.set(ue=>(ue[k].result={store:L,pageInfo:H,aggregate:J,processedTxId:S},ue))}),this._cleanupPendingMutationsQueries(),U.forEach(({hash:k})=>{this.notifyOne(k)});break;case"transact-ok":{const{"client-event-id":k,"tx-id":L}=n;this._inFlightMutationEventIds.delete(k);const J=this._rewriteMutations(this.attrs,this.pendingMutations.currentValue).get(k);if(!J)break;this.pendingMutations.set(ae=>(ae.set(k,Object.assign(Object.assign({},ae.get(k)),{"tx-id":L,confirmed:Date.now()})),ae));const ue=J["tx-steps"].filter(([ae,...te])=>ae==="add-attr").map(([ae,te])=>te).concat(Object.values(this.attrs));this._setAttrs(ue),this._finishTransaction("synced",k),this._cleanupPendingMutationsTimeout();break}case"patch-presence":{const k=n["room-id"];this._patchPresencePeers(k,n.edits),this._notifyPresenceSubs(k);break}case"refresh-presence":{const k=n["room-id"];this._setPresencePeers(k,n.data),this._notifyPresenceSubs(k);break}case"server-broadcast":const W=n["room-id"],ye=n.topic;this._notifyBroadcastSubs(W,ye,n);break;case"join-room-ok":const de=n["room-id"],Ke=this._rooms[de];if(!Ke){this._roomsPendingLeave[de]&&(this._tryLeaveRoom(de),delete this._roomsPendingLeave[de]);break}Ke.isConnected=!0,this._notifyPresenceSubs(de),this._flushEnqueuedRoomData(de);break;case"join-room-error":const ut=n["room-id"],at=this._rooms[ut];at&&(at.error=n.error),this._notifyPresenceSubs(ut);break;case"error":this._handleReceiveError(n);break}}_handleMutationError(t,n,r){const i=this.pendingMutations.currentValue.get(n);if(i&&(t!=="timeout"||!i["tx-id"])){this.pendingMutations.set(o=>(o.delete(n),o)),this._inFlightMutationEventIds.delete(n);const s={message:r.message,hint:r.hint};this.notifyAll(),this.notifyAttrsSubs(),this.notifyMutationErrorSubs(s),this._finishTransaction(t,n,r)}}_handleReceiveError(t){var n,r,i,s,o;console.log("error",t);const u=t["client-event-id"];this._inFlightMutationEventIds.delete(u);const a=this.pendingMutations.currentValue.get(u),d={message:t.message||"Uh-oh, something went wrong. Ping Joe & Stopa."};if(t.hint&&(d.hint=t.hint),a){this._handleMutationError("error",u,t);return}if(!((n=t["original-event"])===null||n===void 0)&&n.hasOwnProperty("q")&&((r=t["original-event"])===null||r===void 0?void 0:r.op)==="add-query"){const h=(i=t["original-event"])===null||i===void 0?void 0:i.q,p=B(h);this.notifyQueryError(B(h),d),this.notifyQueryOnceError(h,p,u,d);return}if(((s=t["original-event"])===null||s===void 0?void 0:s.op)==="init"){if(t.type==="record-not-found"&&((o=t.hint)===null||o===void 0?void 0:o["record-type"])==="app-user"){this.changeCurrentUser(null);return}this._setStatus(pe.ERRORED,d),this.notifyAll();return}const f=Object.assign({},t);delete f.message,delete f.hint,console.error(t.message,f),t.hint&&console.error(`This error comes with some debugging information. Here it is:
|
|
31
|
-
`,t.hint)}notifyQueryOnceError(t,n,r,i){var s;const o=(s=this.queryOnceDfds[n])===null||s===void 0?void 0:s.find(u=>u.eventId===r);o&&(o.dfd.reject(i),this._completeQueryOnce(t,n,o.dfd))}_setAttrs(t){this.attrs=t.reduce((n,r)=>(n[r.id]=r,n),{}),this.notifyAttrsSubs()}_startQuerySub(t,n){const r=V();return this.querySubs.set(i=>(i[n]=i[n]||{q:t,result:null,eventId:r},i[n].lastAccessed=Date.now(),i)),this._trySendAuthed(r,{op:"add-query",q:t}),r}subscribeQuery(t,n,r){var i;this.config.disableValidation||Tr(t,this.config.schema),r&&"ruleParams"in r&&(t=Object.assign({$$ruleParams:r.ruleParams},t));const s=B(t),o=this.getPreviousResult(t);return o&&n(o),this.queryCbs[s]=(i=this.queryCbs[s])!==null&&i!==void 0?i:[],this.queryCbs[s].push({q:t,cb:n}),this._startQuerySub(t,s),()=>{this._unsubQuery(t,s,n)}}queryOnce(t,n){var r;this.config.disableValidation||Tr(t,this.config.schema),n&&"ruleParams"in n&&(t=Object.assign({$$ruleParams:n.ruleParams},t));const i=new cr;if(!this._isOnline)return i.reject(new Error("We can't run `queryOnce`, because the device is offline.")),i.promise;if(!this.querySubs)return i.reject(new Error("We can't run `queryOnce` on the backend. Use adminAPI.query instead: https://www.instantdb.com/docs/backend#query")),i.promise;const s=B(t),o=this._startQuerySub(t,s);return this.queryOnceDfds[s]=(r=this.queryOnceDfds[s])!==null&&r!==void 0?r:[],this.queryOnceDfds[s].push({q:t,dfd:i,eventId:o}),setTimeout(()=>i.reject(new Error("Query timed out")),Vo),i.promise}_completeQueryOnce(t,n,r){this.queryOnceDfds[n]&&(this.queryOnceDfds[n]=this.queryOnceDfds[n].filter(i=>i.dfd!==r),this._cleanupQuery(t,n))}_unsubQuery(t,n,r){this.queryCbs[n]&&(this.queryCbs[n]=this.queryCbs[n].filter(i=>i.cb!==r),this._cleanupQuery(t,n))}_cleanupQuery(t,n){var r,i;!((r=this.queryCbs[n])===null||r===void 0)&&r.length||!((i=this.queryOnceDfds[n])===null||i===void 0)&&i.length||(delete this.queryCbs[n],delete this.queryOnceDfds[n],this._trySendAuthed(V(),{op:"remove-query",q:t}))}_rewriteMutations(t,n,r){if(!t)return n;const i=c=>{const[f,h,p]=c["forward-identity"];return N(t,h,p)},s=c=>{const[f,h,p]=c["forward-identity"];return we(t,h,p)},o={attrIdMap:{},refSwapAttrIds:new Set};let u=!1;const a=(c,f)=>{const h=[];for(const p of c){const[b]=p;if(b==="add-attr"){const[w,T]=p,m=i(T);if(m&&T.id!==m.id){o.attrIdMap[T.id]=m.id,u=!0;continue}if(T["value-type"]==="ref"){const S=s(T);if(S){o.attrIdMap[T.id]=S.id,o.refSwapAttrIds.add(T.id),u=!0;continue}}}if(r&&f&&r>=f&&b==="add-attr"||b==="update-attr"||b==="delete-attr"){u=!0;continue}const g=u?Vs(o,p):p;h.push(g)}return u?h:c},d=new Map;for(const[c,f]of n.entries())d.set(c,Object.assign(Object.assign({},f),{"tx-steps":a(f["tx-steps"],f["tx-id"])}));return u?d:n}_rewriteMutationsSorted(t,n){return Pr(this._rewriteMutations(t,n).entries())}optimisticAttrs(){var t;const n=[...this.pendingMutations.currentValue.values()].flatMap(u=>u["tx-steps"]),r=new Set(n.filter(([u,a])=>u==="delete-attr").map(([u,a])=>a)),i=[];for(const[u,a]of n)if(u==="add-attr")i.push(a);else if(u==="update-attr"&&a.id&&(!((t=this.attrs)===null||t===void 0)&&t[a.id])){const d=Object.assign(Object.assign({},this.attrs[a.id]),a);i.push(d)}const s=[...Object.values(this.attrs||{}),...i].filter(u=>!r.has(u.id));return Object.fromEntries(s.map(u=>[u.id,u]))}dataForQuery(t){const n=this._errorMessage;if(n)return{error:n};if(!this.querySubs||!this.pendingMutations)return;const r=this.querySubs.version(),i=this.querySubs.currentValue,s=this.pendingMutations.version(),o=this.pendingMutations.currentValue,{q:u,result:a}=i[t]||{};if(!a)return;const d=this._dataForQueryCache[t];if(d&&r===d.querySubVersion&&s===d.pendingMutationsVersion)return d.data;const{store:c,pageInfo:f,aggregate:h,processedTxId:p}=a,b=this._rewriteMutationsSorted(c.attrs,o),g=this._applyOptimisticUpdates(c,b,p),w=$s({store:g,pageInfo:f,aggregate:h},u);return this._dataForQueryCache[t]={querySubVersion:r,pendingMutationsVersion:s,data:w},w}_applyOptimisticUpdates(t,n,r){for(const[i,s]of n)(!s["tx-id"]||r&&s["tx-id"]>r)&&(t=Wi(t,s["tx-steps"]));return t}notifyAll(){Object.keys(this.queryCbs).forEach(t=>{this.notifyOne(t)})}loadedNotifyAll(){this.pendingMutations.isLoading()||this.querySubs.isLoading()||this.notifyAll()}shutdown(){var t;this._log.info("[shutdown]",this.config.appId),this._isShutdown=!0,(t=this._transport)===null||t===void 0||t.close()}_sendMutation(t,n){if(n.error){this._handleMutationError("error",t,{message:n.error.message});return}if(this.status!==pe.AUTHENTICATED){this._finishTransaction("enqueued",t);return}const r=Math.max(6e3,Math.min(this._inFlightMutationEventIds.size+1,this.pendingMutations.currentValue.size+1)*6e3);this._isOnline?(this._trySend(t,n),setTimeout(()=>{this._isOnline&&this._handleMutationError("timeout",t,{message:"transaction timed out"})},r)):this._finishTransaction("enqueued",t)}_flushPendingMessages(){Object.keys(this.queryCbs).map(i=>this.querySubs.currentValue[i]).filter(i=>i).forEach(({eventId:i,q:s})=>{this._trySendAuthed(i,{op:"add-query",q:s})}),Object.values(this.queryOnceDfds).flat().forEach(({eventId:i,q:s})=>{this._trySendAuthed(i,{op:"add-query",q:s})}),this._rewriteMutationsSorted(this.attrs,this.pendingMutations.currentValue).forEach(([i,s])=>{s["tx-id"]||this._sendMutation(i,s)})}_cleanupPendingMutationsQueries(){let t=Number.MAX_SAFE_INTEGER;for(const{result:n}of Object.values(this.querySubs.currentValue))n!=null&&n.processedTxId&&(t=Math.min(t,n==null?void 0:n.processedTxId));this.pendingMutations.set(n=>{for(const[r,i]of Array.from(n.entries()))i["tx-id"]&&i["tx-id"]<=t&&n.delete(r);return n})}_cleanupPendingMutationsTimeout(){if(this.pendingMutations.currentValue.size<this._pendingMutationCleanupThreshold)return;const t=Date.now();this.pendingMutations.set(n=>{for(const[r,i]of Array.from(n.entries()))i.confirmed&&i.confirmed+this._pendingTxCleanupTimeout<t&&n.delete(r);return n})}_trySendAuthed(...t){this.status===pe.AUTHENTICATED&&this._trySend(...t)}_trySend(t,n,r){if(this._transport.isOpen()){switch(jr[n.op]||this._log.info("[send]",this._transport.id,n.op,n),n.op){case"transact":{this._inFlightMutationEventIds.add(t);break}case"init":this._inFlightMutationEventIds.clear()}this._transport.send(Object.assign({"client-event-id":t},n))}}_startSocket(){if(this._wsOk=null,this._isShutdown){this._log.info("[socket][start]",this.config.appId,"Reactor has been shut down and will not start a new socket");return}if(this._transport&&this._transport.isConnecting()){this._log.info("[socket][start]",this._transport.id,"maintained as current transport, we were still in a connecting state");return}const t=this._transport;this._transport=qo({transportType:this._transportType,appId:this.config.appId,apiURI:this.config.apiURI,wsURI:this.config.websocketURI,EventSourceImpl:this._EventSource}),this._transport.onopen=this._transportOnOpen,this._transport.onmessage=this._transportOnMessage,this._transport.onclose=this._transportOnClose,this._transport.onerror=this._transportOnError,this._log.info("[socket][start]",this._transport.id),t!=null&&t.isOpen()&&(this._log.info("[socket][start]",this._transport.id,"close previous transport id = ",t.id),t.close())}getLocalId(t){return x(this,void 0,void 0,function*(){const n=`localToken_${t}`,r=yield this._persister.getItem(n);if(r)return r;if(this._localIdPromises[n])return this._localIdPromises[n];const i=V();return this._localIdPromises[n]=this._persister.setItem(n,i).then(()=>i),this._localIdPromises[n]})}_replaceUrlAfterOAuth(){if(typeof URL>"u")return;const t=new URL(window.location.href);if(t.searchParams.get(Xt)){const n=t.toString();t.searchParams.delete(Xt),t.searchParams.delete("code"),t.searchParams.delete("error");const r=t.pathname+(t.searchParams.size?"?"+t.searchParams:"")+t.hash;if(history.replaceState(history.state,"",r),typeof navigation=="object"&&typeof navigation.addEventListener=="function"&&typeof navigation.removeEventListener=="function"){let i=!1;const s=o=>{var u;i||(i=!0,navigation.removeEventListener("navigate",s),!o.userInitiated&&o.navigationType==="replace"&&((u=o.destination)===null||u===void 0?void 0:u.url)===n&&history.replaceState(history.state,"",r))};navigation.addEventListener("navigate",s)}}}_oauthLoginInit(){return x(this,void 0,void 0,function*(){var t,n,r,i;if(typeof window>"u"||typeof window.location>"u"||typeof URLSearchParams>"u")return null;const s=new URLSearchParams(window.location.search);if(!s.get(Xt))return null;const o=s.get("error");if(o)return this._replaceUrlAfterOAuth(),{error:{message:o}};const u=s.get("code");if(!u)return null;this._replaceUrlAfterOAuth();try{const a=yield this._getCurrentUser(),d=(a==null?void 0:a.type)==="guest",{user:c}=yield sr({apiURI:this.config.apiURI,appId:this.config.appId,code:u,refreshToken:d?a.refresh_token:void 0});return this.setCurrentUser(c),null}catch(a){return((t=a==null?void 0:a.body)===null||t===void 0?void 0:t.type)==="record-not-found"&&((r=(n=a==null?void 0:a.body)===null||n===void 0?void 0:n.hint)===null||r===void 0?void 0:r["record-type"])==="app-oauth-code"&&(yield this._hasCurrentUser())?null:{error:{message:((i=a==null?void 0:a.body)===null||i===void 0?void 0:i.message)||"Error logging in."}}}})}_waitForOAuthCallbackResponse(){return x(this,void 0,void 0,function*(){return yield this._oauthCallbackResponse})}__subscribeMutationErrors(t){return this.mutationErrorCbs.push(t),()=>{this.mutationErrorCbs=this.mutationErrorCbs.filter(n=>n!==t)}}subscribeAuth(t){this.authCbs.push(t);const n=this._currentUserCached;n.isLoading||t(this._currentUserCached);let r=!1;return this.getCurrentUser().then(i=>{r||Je(i,n)||t(i)}),()=>{r=!0,this.authCbs=this.authCbs.filter(i=>i!==t)}}getAuth(){return x(this,void 0,void 0,function*(){const{user:t,error:n}=yield this.getCurrentUser();if(n)throw new je("Could not get current user: "+n.message);return t})}subscribeConnectionStatus(t){return this.connectionStatusCbs.push(t),()=>{this.connectionStatusCbs=this.connectionStatusCbs.filter(n=>n!==t)}}subscribeAttrs(t){return this.attrsCbs.push(t),this.attrs&&t(this.attrs),()=>{this.attrsCbs=this.attrsCbs.filter(n=>n!==t)}}notifyAuthSubs(t){this.authCbs.forEach(n=>n(t))}notifyMutationErrorSubs(t){this.mutationErrorCbs.forEach(n=>n(t))}notifyAttrsSubs(){if(!this.attrs)return;const t=this.optimisticAttrs();this.attrsCbs.forEach(n=>n(t))}notifyConnectionStatusSubs(t){this.connectionStatusCbs.forEach(n=>n(t))}setCurrentUser(t){return x(this,void 0,void 0,function*(){yield this._persister.setItem(en,t)})}getCurrentUserCached(){return this._currentUserCached}_getCurrentUser(){return x(this,void 0,void 0,function*(){const t=yield this._persister.getItem(en);return typeof t=="string"?JSON.parse(t):t})}getCurrentUser(){return x(this,void 0,void 0,function*(){const t=yield this._waitForOAuthCallbackResponse();if(t!=null&&t.error){const i={error:t.error,user:void 0};return this._currentUserCached=Object.assign({isLoading:!1},i),i}const r={user:yield this._getCurrentUser(),error:void 0};return this._currentUserCached=Object.assign({isLoading:!1},r),r})}_hasCurrentUser(){return x(this,void 0,void 0,function*(){const t=yield this._persister.getItem(en);return JSON.parse(t)!=null})}changeCurrentUser(t){return x(this,void 0,void 0,function*(){var n;const{user:r}=yield this.getCurrentUser();if(!Je(r,t)){yield this.setCurrentUser(t),this.updateUser(t);try{(n=this._broadcastChannel)===null||n===void 0||n.postMessage({type:"auth"})}catch(i){console.error("Error posting message to broadcast channel",i)}}})}updateUser(t){const n={error:void 0,user:t};this._currentUserCached=Object.assign({isLoading:!1},n),this._dataForQueryCache={},this.querySubs.set(r=>(Object.keys(r).forEach(i=>{delete r[i].result}),r)),this._reconnectTimeoutMs=0,this._transport.close(),this._oauthCallbackResponse=null,this.notifyAuthSubs(n)}sendMagicCode({email:t}){return yo({apiURI:this.config.apiURI,appId:this.config.appId,email:t})}signInWithMagicCode(t){return x(this,arguments,void 0,function*({email:n,code:r}){var i;const s=yield this.getCurrentUser(),o=((i=s==null?void 0:s.user)===null||i===void 0?void 0:i.type)==="guest",u=yield bo({apiURI:this.config.apiURI,appId:this.config.appId,email:n,code:r,refreshToken:o?s.user.refresh_token:void 0});return yield this.changeCurrentUser(u.user),u})}signInWithCustomToken(t){return x(this,void 0,void 0,function*(){const n=yield _o({apiURI:this.config.apiURI,appId:this.config.appId,refreshToken:t});return yield this.changeCurrentUser(n.user),n})}signInAsGuest(){return x(this,void 0,void 0,function*(){const t=yield go({apiURI:this.config.apiURI,appId:this.config.appId});return yield this.changeCurrentUser(t.user),t})}potentiallyInvalidateToken(t,n){var r;const i=(r=t==null?void 0:t.user)===null||r===void 0?void 0:r.refresh_token;if(!i)return;if(n.invalidateToken===!1){this._log.info("[auth-invalidate] skipped invalidateToken");return}wo({apiURI:this.config.apiURI,appId:this.config.appId,refreshToken:i}).then(()=>{this._log.info("[auth-invalidate] completed invalidateToken")}).catch(o=>{})}signOut(t){return x(this,void 0,void 0,function*(){const n=yield this.getCurrentUser();this.potentiallyInvalidateToken(n,t),yield this.changeCurrentUser(null)})}createAuthorizationURL({clientName:t,redirectURL:n}){const{apiURI:r,appId:i}=this.config;return`${r}/runtime/oauth/start?app_id=${i}&client_name=${t}&redirect_uri=${n}`}exchangeCodeForToken(t){return x(this,arguments,void 0,function*({code:n,codeVerifier:r}){var i;const s=yield this.getCurrentUser(),o=((i=s==null?void 0:s.user)===null||i===void 0?void 0:i.type)==="guest",u=yield sr({apiURI:this.config.apiURI,appId:this.config.appId,code:n,codeVerifier:r,refreshToken:o?s.user.refresh_token:void 0});return yield this.changeCurrentUser(u.user),u})}issuerURI(){const{apiURI:t,appId:n}=this.config;return`${t}/runtime/${n}`}signInWithIdToken(t){return x(this,arguments,void 0,function*({idToken:n,clientName:r,nonce:i}){var s;const o=yield this.getCurrentUser(),u=(s=o==null?void 0:o.user)===null||s===void 0?void 0:s.refresh_token,a=yield To({apiURI:this.config.apiURI,appId:this.config.appId,idToken:n,clientName:r,nonce:i,refreshToken:u});return yield this.changeCurrentUser(a.user),a})}joinRoom(t,n){return this._rooms[t]||(this._rooms[t]={isConnected:!1,error:void 0}),this._presence[t]=this._presence[t]||{},n&&(this._presence[t].result=this._presence[t].result||{},this._presence[t].result.user=n,this._notifyPresenceSubs(t)),this._tryJoinRoom(t,n),()=>{this._cleanupRoom(t)}}_cleanupRoom(t){var n,r,i,s;if(!(!((r=(n=this._presence[t])===null||n===void 0?void 0:n.handlers)===null||r===void 0)&&r.length)&&!Object.keys((i=this._broadcastSubs[t])!==null&&i!==void 0?i:{}).length){const o=(s=this._rooms[t])===null||s===void 0?void 0:s.isConnected;delete this._rooms[t],delete this._presence[t],delete this._broadcastSubs[t],o?this._tryLeaveRoom(t):this._roomsPendingLeave[t]=!0}}getPresence(t,n,r={}){const i=this._rooms[n],s=this._presence[n];return!i||!s||!s.result?null:Object.assign(Object.assign({},Ao(s.result,r,this._sessionId)),{isLoading:!i.isConnected,error:i.error})}publishPresence(t,n,r){const i=this._rooms[n],s=this._presence[n];if(!i||!s)return;s.result=s.result||{};const o=Object.assign(Object.assign({},s.result.user),r);s.result.user=o,i.isConnected&&(this._trySetPresence(n,o),this._notifyPresenceSubs(n))}_trySetPresence(t,n){this._trySendAuthed(V(),{op:"set-presence","room-id":t,data:n})}_tryJoinRoom(t,n){this._trySendAuthed(V(),{op:"join-room","room-id":t,data:n}),delete this._roomsPendingLeave[t]}_tryLeaveRoom(t){this._trySendAuthed(V(),{op:"leave-room","room-id":t})}subscribePresence(t,n,r,i){const s=this.joinRoom(n,r.initialData),o=Object.assign(Object.assign({},r),{roomId:n,cb:i,prev:null});return this._presence[n]=this._presence[n]||{},this._presence[n].handlers=this._presence[n].handlers||[],this._presence[n].handlers.push(o),this._notifyPresenceSub(n,o),()=>{var u,a,d;this._presence[n].handlers=(d=(a=(u=this._presence[n])===null||u===void 0?void 0:u.handlers)===null||a===void 0?void 0:a.filter(c=>c!==o))!==null&&d!==void 0?d:[],s()}}_notifyPresenceSubs(t){var n,r;(r=(n=this._presence[t])===null||n===void 0?void 0:n.handlers)===null||r===void 0||r.forEach(i=>{this._notifyPresenceSub(t,i)})}_notifyPresenceSub(t,n){const r=this.getPresence("",t,n);r&&(n.prev&&!Co(r,n.prev)||(n.prev=r,n.cb(r)))}_patchPresencePeers(t,n){var r,i,s;const o=((i=(r=this._presence[t])===null||r===void 0?void 0:r.result)===null||i===void 0?void 0:i.peers)||{};let u=Object.fromEntries(Object.entries(o).map(([d,c])=>[d,{data:c}]));(s=this._presence[t])===null||s===void 0||s.result;const a=Mt(u,d=>{for(let[c,f,h]of n)switch(f){case"+":ai(d,c,h);break;case"r":kn(d,c,h);break;case"-":In(d,c);break}delete d[this._sessionId]});this._setPresencePeers(t,a)}_setPresencePeers(t,n){const r=Object.assign({},n);delete r[this._sessionId];const i=Object.fromEntries(Object.entries(r).map(([s,o])=>[s,o.data]));this._presence=Mt(this._presence,s=>{kn(s,[t,"result","peers"],i)})}publishTopic({roomType:t,roomId:n,topic:r,data:i}){var s;const o=this._rooms[n];if(o){if(!o.isConnected){this._broadcastQueue[n]=(s=this._broadcastQueue[n])!==null&&s!==void 0?s:[],this._broadcastQueue[n].push({topic:r,roomType:t,data:i});return}this._tryBroadcast(n,t,r,i)}}_tryBroadcast(t,n,r,i){this._trySendAuthed(V(),{op:"client-broadcast","room-id":t,roomType:n,topic:r,data:i})}subscribeTopic(t,n,r){const i=this.joinRoom(t);return this._broadcastSubs[t]=this._broadcastSubs[t]||{},this._broadcastSubs[t][n]=this._broadcastSubs[t][n]||[],this._broadcastSubs[t][n].push(r),this._presence[t]=this._presence[t]||{},()=>{this._broadcastSubs[t][n]=this._broadcastSubs[t][n].filter(s=>s!==r),this._broadcastSubs[t][n].length||delete this._broadcastSubs[t][n],i()}}_notifyBroadcastSubs(t,n,r){var i,s,o;(o=(s=(i=this._broadcastSubs)===null||i===void 0?void 0:i[t])===null||s===void 0?void 0:s[n])===null||o===void 0||o.forEach(u=>{var a,d,c,f,h,p;const b=(a=r.data)===null||a===void 0?void 0:a.data,g=r.data["peer-id"]===this._sessionId?(c=(d=this._presence[t])===null||d===void 0?void 0:d.result)===null||c===void 0?void 0:c.user:(p=(h=(f=this._presence[t])===null||f===void 0?void 0:f.result)===null||h===void 0?void 0:h.peers)===null||p===void 0?void 0:p[r.data["peer-id"]];return u(b,g)})}uploadFile(t,n,r){return x(this,void 0,void 0,function*(){var i;const s=yield this.getCurrentUser(),o=(i=s==null?void 0:s.user)===null||i===void 0?void 0:i.refresh_token;return mo(Object.assign(Object.assign({},r),{apiURI:this.config.apiURI,appId:this.config.appId,path:t,file:n,refreshToken:o}))})}deleteFile(t){return x(this,void 0,void 0,function*(){var n;const r=yield this.getCurrentUser(),i=(n=r==null?void 0:r.user)===null||n===void 0?void 0:n.refresh_token;return yield So({apiURI:this.config.apiURI,appId:this.config.appId,path:t,refreshToken:i})})}upload(t,n){return x(this,void 0,void 0,function*(){var r;const i=yield this.getCurrentUser(),s=(r=i==null?void 0:i.user)===null||r===void 0?void 0:r.refresh_token,o=t||n.name,u=yield vo({apiURI:this.config.apiURI,appId:this.config.appId,fileName:o,refreshToken:s});return yield Oo(u,n)})}getDownloadUrl(t){return x(this,void 0,void 0,function*(){var n;const r=yield this.getCurrentUser(),i=(n=r==null?void 0:r.user)===null||n===void 0?void 0:n.refresh_token;return yield Eo({apiURI:this.config.apiURI,appId:this.config.appId,path:t,refreshToken:i})})}}let ot;function Ho(e,t){ot==null||ot.dispose();const n=nu(t),r=Xo(t,u),i=Zo(Jo(e));function s(c){var f;c.source===i.element.contentWindow&&((f=c.data)===null||f===void 0?void 0:f.type)==="close"&&n.isVisible()&&u()}function o(c){const f=c.shiftKey&&c.ctrlKey&&c.key==="0",h=c.key==="Escape"||c.key==="Esc";(f||h&&n.isVisible())&&u()}function u(){n.isVisible()?n.element.style.display="none":(n.element.style.display="block",n.element.contains(i.element)||n.element.appendChild(i.element))}function a(){n.element.remove(),r.element.remove(),removeEventListener("keydown",o),removeEventListener("message",s)}function d(){document.body.appendChild(n.element),document.body.appendChild(r.element),addEventListener("keydown",o),addEventListener("message",s),ot={dispose:a}}return d()}function Jo(e){return`${Jt||ur?"http://localhost:3000":"https://instantdb.com"}/_devtool?appId=${e}`}function Zo(e){const t=document.createElement("iframe");return t.src=e,t.className="instant-devtool-iframe",Object.assign(t.style,{width:"100%",height:"100%",backgroundColor:"white",border:"none"}),{element:t}}function Xo(e,t){const n=`
|
|
30
|
+
<%s key={someKey} {...props} />`,hn,Se,Yu,Se),qr[Se+hn]=!0}}return l===i?Ku($):zu($),$}}function qu(l,y,_){return Br(l,y,_,!0)}function Bu(l,y,_){return Br(l,y,_,!1)}var Qu=Bu,Gu=qu;De.Fragment=i,De.jsx=Qu,De.jsxs=Gu}(),De}var Yr={};Yr.NODE_ENV==="production"?gt.exports=Qr():gt.exports=Gr();var Be=gt.exports;function B(e){if(typeof e=="number")return(Math.abs(e*2654435761)>>>0).toString(16);if(typeof e=="boolean")return e?"1":"0";if(e===null)return"null";if(e===void 0)return"undefined";if(typeof e=="string"){let t=2166136261;for(let n=0;n<e.length;n++)t^=e.charCodeAt(n),t+=(t<<1)+(t<<4)+(t<<7)+(t<<8)+(t<<24),t=t>>>0;return t.toString(16)}if(Array.isArray(e)){let t=2166136261;for(let n=0;n<e.length;n++){t^=(n+1)*2654435761;const r=B(e[n]);for(let i=0;i<r.length;i++)t^=r.charCodeAt(i),t*=16777619,t=t>>>0}return t.toString(16)}if(typeof e=="object"){let t=2166136261;const n=Object.keys(e).sort();for(let r=0;r<n.length;r++){const i=n[r],s=B(i);t^=parseInt(s,16),t*=16777619,t=t>>>0;const o=B(e[i]);t^=parseInt(o,16),t*=16777619,t=t>>>0}return t.toString(16)}return B(String(e))}const R={Remove:"remove",Replace:"replace",Add:"add"},bn=Symbol.for("__MUTATIVE_PROXY_DRAFT__"),Hr=Symbol("__MUTATIVE_RAW_RETURN_SYMBOL__"),Qe=Symbol.iterator,X={mutable:"mutable",immutable:"immutable"},Tt={};function xe(e,t){return e instanceof Map?e.has(t):Object.prototype.hasOwnProperty.call(e,t)}function _n(e,t){if(t in e){let n=Reflect.getPrototypeOf(e);for(;n;){const r=Reflect.getOwnPropertyDescriptor(n,t);if(r)return r;n=Reflect.getPrototypeOf(n)}}}function wt(e){return Object.getPrototypeOf(e)===Set.prototype}function mt(e){return Object.getPrototypeOf(e)===Map.prototype}function ee(e){var t;return(t=e.copy)!==null&&t!==void 0?t:e.original}function _e(e){return!!E(e)}function E(e){return typeof e!="object"?null:e==null?void 0:e[bn]}function St(e){var t;const n=E(e);return n?(t=n.copy)!==null&&t!==void 0?t:n.original:e}function ie(e,t){if(!e||typeof e!="object")return!1;let n;return Object.getPrototypeOf(e)===Object.prototype||Array.isArray(e)||e instanceof Map||e instanceof Set||!!(t!=null&&t.mark)&&((n=t.mark(e,X))===X.immutable||typeof n=="function")}function gn(e,t=[]){if(Object.hasOwnProperty.call(e,"key")){const n=e.parent.copy,r=E(fe(n,e.key));if(r!==null&&(r==null?void 0:r.original)!==e.original)return null;const i=e.parent.type===3,s=i?Array.from(e.parent.setMap.keys()).indexOf(e.key):e.key;if(!(i&&n.size>s||xe(n,s)))return null;t.push(s)}if(e.parent)return gn(e.parent,t);t.reverse();try{Jr(e.copy,t)}catch{return null}return t}function ge(e){return Array.isArray(e)?1:e instanceof Map?2:e instanceof Set?3:0}function fe(e,t){return ge(e)===2?e.get(t):e[t]}function $e(e,t,n){ge(e)===2?e.set(t,n):e[t]=n}function vt(e,t){const n=E(e);return(n?ee(n):e)[t]}function le(e,t){return e===t?e!==0||1/e===1/t:e!==e&&t!==t}function Ot(e){if(e)for(;e.finalities.revoke.length>0;)e.finalities.revoke.pop()()}function Te(e,t){return t?e:[""].concat(e).map(n=>{const r=`${n}`;return r.indexOf("/")===-1&&r.indexOf("~")===-1?r:r.replace(/~/g,"~0").replace(/\//g,"~1")}).join("/")}function Jr(e,t){for(let n=0;n<t.length-1;n+=1){const r=t[n];if(e=fe(ge(e)===3?Array.from(e):e,r),typeof e!="object")throw new Error(`Cannot resolve patch at '${t.join("/")}'.`)}return e}function Zr(e){const t=Object.create(Object.getPrototypeOf(e));return Reflect.ownKeys(e).forEach(n=>{let r=Reflect.getOwnPropertyDescriptor(e,n);if(r.enumerable&&r.configurable&&r.writable){t[n]=e[n];return}r.writable||(r.writable=!0,r.configurable=!0),(r.get||r.set)&&(r={configurable:!0,writable:!0,enumerable:r.enumerable,value:e[n]}),Reflect.defineProperty(t,n,r)}),t}const Xr=Object.prototype.propertyIsEnumerable;function Tn(e,t){let n;if(Array.isArray(e))return Array.prototype.concat.call(e);if(e instanceof Set){if(!wt(e)){const r=Object.getPrototypeOf(e).constructor;return new r(e.values())}return Set.prototype.difference?Set.prototype.difference.call(e,new Set):new Set(e.values())}else if(e instanceof Map){if(!mt(e)){const r=Object.getPrototypeOf(e).constructor;return new r(e)}return new Map(e)}else if(t!=null&&t.mark&&(n=t.mark(e,X),n!==void 0)&&n!==X.mutable){if(n===X.immutable)return Zr(e);if(typeof n=="function"){if(t.enablePatches||t.enableAutoFreeze)throw new Error("You can't use mark and patches or auto freeze together.");return n()}throw new Error(`Unsupported mark result: ${n}`)}else if(typeof e=="object"&&Object.getPrototypeOf(e)===Object.prototype){const r={};return Object.keys(e).forEach(i=>{r[i]=e[i]}),Object.getOwnPropertySymbols(e).forEach(i=>{Xr.call(e,i)&&(r[i]=e[i])}),r}else throw new Error("Please check mark() to ensure that it is a stable marker draftable function.")}function z(e){e.copy||(e.copy=Tn(e.original,e.options))}function Ue(e){if(!ie(e))return St(e);if(Array.isArray(e))return e.map(Ue);if(e instanceof Map){const n=Array.from(e.entries()).map(([r,i])=>[r,Ue(i)]);if(!mt(e)){const r=Object.getPrototypeOf(e).constructor;return new r(n)}return new Map(n)}if(e instanceof Set){const n=Array.from(e).map(Ue);if(!wt(e)){const r=Object.getPrototypeOf(e).constructor;return new r(n)}return new Set(n)}const t=Object.create(Object.getPrototypeOf(e));for(const n in e)t[n]=Ue(e[n]);return t}function Ge(e){return _e(e)?Ue(e):e}function ce(e){var t;e.assignedMap=(t=e.assignedMap)!==null&&t!==void 0?t:new Map,e.operated||(e.operated=!0,e.parent&&ce(e.parent))}function wn(){throw new Error("Cannot modify frozen object")}function ve(e,t,n,r,i){{n=n??new WeakMap,r=r??[],i=i??[];const o=n.has(e)?n.get(e):e;if(r.length>0){const u=r.indexOf(o);if(o&&typeof o=="object"&&u!==-1)throw r[0]===o?new Error("Forbids circular reference"):new Error(`Forbids circular reference: ~/${i.slice(0,u).map((a,d)=>{if(typeof a=="symbol")return`[${a.toString()}]`;const c=r[d];return typeof a=="object"&&(c instanceof Map||c instanceof Set)?Array.from(c.keys()).indexOf(a):a}).join("/")}`);r.push(o),i.push(t)}else r.push(o)}if(Object.isFrozen(e)||_e(e)){r.pop(),i.pop();return}switch(ge(e)){case 2:for(const[u,a]of e)ve(u,u,n,r,i),ve(a,u,n,r,i);e.set=e.clear=e.delete=wn;break;case 3:for(const u of e)ve(u,u,n,r,i);e.add=e.clear=e.delete=wn;break;case 1:Object.freeze(e);let o=0;for(const u of e)ve(u,o,n,r,i),o+=1;break;default:Object.freeze(e),Object.keys(e).forEach(u=>{const a=e[u];ve(a,u,n,r,i)})}r.pop(),i.pop()}function Et(e,t){const n=ge(e);if(n===0)Reflect.ownKeys(e).forEach(r=>{t(r,e[r],e)});else if(n===1){let r=0;for(const i of e)t(r,i,e),r+=1}else e.forEach((r,i)=>t(i,r,e))}function mn(e,t,n){if(_e(e)||!ie(e,n)||t.has(e)||Object.isFrozen(e))return;const r=e instanceof Set,i=r?new Map:void 0;if(t.add(e),Et(e,(s,o)=>{var u;if(_e(o)){const a=E(o);z(a);const d=!((u=a.assignedMap)===null||u===void 0)&&u.size||a.operated?a.copy:a.original;$e(r?i:e,s,d)}else mn(o,t,n)}),i){const s=e,o=Array.from(s);s.clear(),o.forEach(u=>{s.add(i.has(u)?i.get(u):u)})}}function ei(e,t){const n=e.type===3?e.setMap:e.copy;e.finalities.revoke.length>1&&e.assignedMap.get(t)&&n&&mn(fe(n,t),e.finalities.handledSet,e.options)}function At(e){e.type===3&&e.copy&&(e.copy.clear(),e.setMap.forEach(t=>{e.copy.add(St(t))}))}function Ct(e,t,n,r){if(e.operated&&e.assignedMap&&e.assignedMap.size>0&&!e.finalized){if(n&&r){const s=gn(e);s&&t(e,s,n,r)}e.finalized=!0}}function jt(e,t,n,r){const i=E(n);i&&(i.callbacks||(i.callbacks=[]),i.callbacks.push((s,o)=>{var u;const a=e.type===3?e.setMap:e.copy;if(le(fe(a,t),n)){let d=i.original;i.copy&&(d=i.copy),At(e),Ct(e,r,s,o),e.options.enableAutoFreeze&&(e.options.updatedValues=(u=e.options.updatedValues)!==null&&u!==void 0?u:new WeakMap,e.options.updatedValues.set(d,i.original)),$e(a,t,d)}}),e.options.enableAutoFreeze&&i.finalities!==e.finalities&&(e.options.enableAutoFreeze=!1)),ie(n,e.options)&&e.finalities.draft.push(()=>{const s=e.type===3?e.setMap:e.copy;le(fe(s,t),n)&&ei(e,t)})}function ti(e,t,n,r,i){let{original:s,assignedMap:o,options:u}=e,a=e.copy;a.length<s.length&&([s,a]=[a,s],[n,r]=[r,n]);for(let d=0;d<s.length;d+=1)if(o.get(d.toString())&&a[d]!==s[d]){const c=t.concat([d]),f=Te(c,i);n.push({op:R.Replace,path:f,value:Ge(a[d])}),r.push({op:R.Replace,path:f,value:Ge(s[d])})}for(let d=s.length;d<a.length;d+=1){const c=t.concat([d]),f=Te(c,i);n.push({op:R.Add,path:f,value:Ge(a[d])})}if(s.length<a.length){const{arrayLengthAssignment:d=!0}=u.enablePatches;if(d){const c=t.concat(["length"]),f=Te(c,i);r.push({op:R.Replace,path:f,value:s.length})}else for(let c=a.length;s.length<c;c-=1){const f=t.concat([c-1]),h=Te(f,i);r.push({op:R.Remove,path:h})}}}function ni({original:e,copy:t,assignedMap:n},r,i,s,o){n.forEach((u,a)=>{const d=fe(e,a),c=Ge(fe(t,a)),f=u?xe(e,a)?R.Replace:R.Add:R.Remove;if(le(d,c)&&f===R.Replace)return;const h=r.concat(a),p=Te(h,o);i.push(f===R.Remove?{op:f,path:p}:{op:f,path:p,value:c}),s.push(f===R.Add?{op:R.Remove,path:p}:f===R.Remove?{op:R.Add,path:p,value:d}:{op:R.Replace,path:p,value:d})})}function ri({original:e,copy:t},n,r,i,s){let o=0;e.forEach(u=>{if(!t.has(u)){const a=n.concat([o]),d=Te(a,s);r.push({op:R.Remove,path:d,value:u}),i.unshift({op:R.Add,path:d,value:u})}o+=1}),o=0,t.forEach(u=>{if(!e.has(u)){const a=n.concat([o]),d=Te(a,s);r.push({op:R.Add,path:d,value:u}),i.unshift({op:R.Remove,path:d,value:u})}o+=1})}function Le(e,t,n,r){const{pathAsArray:i=!0}=e.options.enablePatches;switch(e.type){case 0:case 2:return ni(e,t,n,r,i);case 1:return ti(e,t,n,r,i);case 3:return ri(e,t,n,r,i)}}const Ye=(e,t,n=!1)=>{if(typeof e=="object"&&e!==null&&(!ie(e,t)||n))throw new Error("Strict mode: Mutable data cannot be accessed directly, please use 'unsafe(callback)' wrap.")},Pt={get size(){return ee(E(this)).size},has(e){return ee(E(this)).has(e)},set(e,t){const n=E(this),r=ee(n);return(!r.has(e)||!le(r.get(e),t))&&(z(n),ce(n),n.assignedMap.set(e,!0),n.copy.set(e,t),jt(n,e,t,Le)),this},delete(e){if(!this.has(e))return!1;const t=E(this);return z(t),ce(t),t.original.has(e)?t.assignedMap.set(e,!1):t.assignedMap.delete(e),t.copy.delete(e),!0},clear(){const e=E(this);if(this.size){z(e),ce(e),e.assignedMap=new Map;for(const[t]of e.original)e.assignedMap.set(t,!1);e.copy.clear()}},forEach(e,t){const n=E(this);ee(n).forEach((r,i)=>{e.call(t,this.get(i),i,this)})},get(e){var t,n;const r=E(this),i=ee(r).get(e),s=((n=(t=r.options).mark)===null||n===void 0?void 0:n.call(t,i,X))===X.mutable;if(r.options.strict&&Ye(i,r.options,s),s||r.finalized||!ie(i,r.options)||i!==r.original.get(e))return i;const o=Tt.createDraft({original:i,parentDraft:r,key:e,finalities:r.finalities,options:r.options});return z(r),r.copy.set(e,o),o},keys(){return ee(E(this)).keys()},values(){const e=this.keys();return{[Qe]:()=>this.values(),next:()=>{const t=e.next();return t.done?t:{done:!1,value:this.get(t.value)}}}},entries(){const e=this.keys();return{[Qe]:()=>this.entries(),next:()=>{const t=e.next();if(t.done)return t;const n=this.get(t.value);return{done:!1,value:[t.value,n]}}}},[Qe](){return this.entries()}},ii=Reflect.ownKeys(Pt),Sn=(e,t,{isValuesIterator:n})=>()=>{var r,i;const s=t.next();if(s.done)return s;const o=s.value;let u=e.setMap.get(o);const a=E(u),d=((i=(r=e.options).mark)===null||i===void 0?void 0:i.call(r,u,X))===X.mutable;if(e.options.strict&&Ye(o,e.options,d),!d&&!a&&ie(o,e.options)&&!e.finalized&&e.original.has(o)){const c=Tt.createDraft({original:o,parentDraft:e,key:o,finalities:e.finalities,options:e.options});e.setMap.set(o,c),u=c}else a&&(u=a.proxy);return{done:!1,value:n?u:[u,u]}},He={get size(){return E(this).setMap.size},has(e){const t=E(this);if(t.setMap.has(e))return!0;z(t);const n=E(e);return!!(n&&t.setMap.has(n.original))},add(e){const t=E(this);return this.has(e)||(z(t),ce(t),t.assignedMap.set(e,!0),t.setMap.set(e,e),jt(t,e,e,Le)),this},delete(e){if(!this.has(e))return!1;const t=E(this);z(t),ce(t);const n=E(e);return n&&t.setMap.has(n.original)?(t.assignedMap.set(n.original,!1),t.setMap.delete(n.original)):(!n&&t.setMap.has(e)?t.assignedMap.set(e,!1):t.assignedMap.delete(e),t.setMap.delete(e))},clear(){if(!this.size)return;const e=E(this);z(e),ce(e);for(const t of e.original)e.assignedMap.set(t,!1);e.setMap.clear()},values(){const e=E(this);z(e);const t=e.setMap.keys();return{[Symbol.iterator]:()=>this.values(),next:Sn(e,t,{isValuesIterator:!0})}},entries(){const e=E(this);z(e);const t=e.setMap.keys();return{[Symbol.iterator]:()=>this.entries(),next:Sn(e,t,{isValuesIterator:!1})}},keys(){return this.values()},[Qe](){return this.values()},forEach(e,t){const n=this.values();let r=n.next();for(;!r.done;)e.call(t,r.value,r.value,this),r=n.next()}};Set.prototype.difference&&Object.assign(He,{intersection(e){return Set.prototype.intersection.call(new Set(this.values()),e)},union(e){return Set.prototype.union.call(new Set(this.values()),e)},difference(e){return Set.prototype.difference.call(new Set(this.values()),e)},symmetricDifference(e){return Set.prototype.symmetricDifference.call(new Set(this.values()),e)},isSubsetOf(e){return Set.prototype.isSubsetOf.call(new Set(this.values()),e)},isSupersetOf(e){return Set.prototype.isSupersetOf.call(new Set(this.values()),e)},isDisjointFrom(e){return Set.prototype.isDisjointFrom.call(new Set(this.values()),e)}});const si=Reflect.ownKeys(He),vn=new WeakSet,On={get(e,t,n){var r,i;const s=(r=e.copy)===null||r===void 0?void 0:r[t];if(s&&vn.has(s))return s;if(t===bn)return e;let o;if(e.options.mark){const d=t==="size"&&(e.original instanceof Map||e.original instanceof Set)?Reflect.get(e.original,t):Reflect.get(e.original,t,n);if(o=e.options.mark(d,X),o===X.mutable)return e.options.strict&&Ye(d,e.options,!0),d}const u=ee(e);if(u instanceof Map&&ii.includes(t)){if(t==="size")return Object.getOwnPropertyDescriptor(Pt,"size").get.call(e.proxy);const d=Pt[t];if(d)return d.bind(e.proxy)}if(u instanceof Set&&si.includes(t)){if(t==="size")return Object.getOwnPropertyDescriptor(He,"size").get.call(e.proxy);const d=He[t];if(d)return d.bind(e.proxy)}if(!xe(u,t)){const d=_n(u,t);return d?"value"in d?d.value:(i=d.get)===null||i===void 0?void 0:i.call(e.proxy):void 0}const a=u[t];if(e.options.strict&&Ye(a,e.options),e.finalized||!ie(a,e.options))return a;if(a===vt(e.original,t)){if(z(e),e.copy[t]=kt({original:e.original[t],parentDraft:e,key:e.type===1?Number(t):t,finalities:e.finalities,options:e.options}),typeof o=="function"){const d=E(e.copy[t]);return z(d),ce(d),d.copy}return e.copy[t]}return a},set(e,t,n){var r;if(e.type===3||e.type===2)throw new Error("Map/Set draft does not support any property assignment.");let i;if(e.type===1&&t!=="length"&&!(Number.isInteger(i=Number(t))&&i>=0&&(t===0||i===0||String(i)===String(t))))throw new Error("Only supports setting array indices and the 'length' property.");const s=_n(ee(e),t);if(s!=null&&s.set)return s.set.call(e.proxy,n),!0;const o=vt(ee(e),t),u=E(o);return u&&le(u.original,n)?(e.copy[t]=n,e.assignedMap=(r=e.assignedMap)!==null&&r!==void 0?r:new Map,e.assignedMap.set(t,!1),!0):(le(n,o)&&(n!==void 0||xe(e.original,t))||(z(e),ce(e),xe(e.original,t)&&le(n,e.original[t])?e.assignedMap.delete(t):e.assignedMap.set(t,!0),e.copy[t]=n,jt(e,t,n,Le)),!0)},has(e,t){return t in ee(e)},ownKeys(e){return Reflect.ownKeys(ee(e))},getOwnPropertyDescriptor(e,t){const n=ee(e),r=Reflect.getOwnPropertyDescriptor(n,t);return r&&{writable:!0,configurable:e.type!==1||t!=="length",enumerable:r.enumerable,value:n[t]}},getPrototypeOf(e){return Reflect.getPrototypeOf(e.original)},setPrototypeOf(){throw new Error("Cannot call 'setPrototypeOf()' on drafts")},defineProperty(){throw new Error("Cannot call 'defineProperty()' on drafts")},deleteProperty(e,t){var n;return e.type===1?On.set.call(this,e,t,void 0,e.proxy):(vt(e.original,t)!==void 0||t in e.original?(z(e),ce(e),e.assignedMap.set(t,!1)):(e.assignedMap=(n=e.assignedMap)!==null&&n!==void 0?n:new Map,e.assignedMap.delete(t)),e.copy&&delete e.copy[t],!0)}};function kt(e){const{original:t,parentDraft:n,key:r,finalities:i,options:s}=e,o=ge(t),u={type:o,finalized:!1,parent:n,original:t,copy:null,proxy:null,finalities:i,options:s,setMap:o===3?new Map(t.entries()):void 0};(r||"key"in e)&&(u.key=r);const{proxy:a,revoke:d}=Proxy.revocable(o===1?Object.assign([],u):u,On);if(i.revoke.push(d),vn.add(a),u.proxy=a,n){const c=n;c.finalities.draft.push((f,h)=>{var p,b;const g=E(a);let w=c.type===3?c.setMap:c.copy;const T=fe(w,r),m=E(T);if(m){let S=m.original;m.operated&&(S=St(T)),At(m),Ct(m,Le,f,h),c.options.enableAutoFreeze&&(c.options.updatedValues=(p=c.options.updatedValues)!==null&&p!==void 0?p:new WeakMap,c.options.updatedValues.set(S,m.original)),$e(w,r,S)}(b=g.callbacks)===null||b===void 0||b.forEach(S=>{S(f,h)})})}else{const c=E(a);c.finalities.draft.push((f,h)=>{At(c),Ct(c,Le,f,h)})}return a}Tt.createDraft=kt;function oi(e,t,n,r,i){var s;const o=E(e),u=(s=o==null?void 0:o.original)!==null&&s!==void 0?s:e,a=!!t.length;if(o!=null&&o.operated)for(;o.finalities.draft.length>0;)o.finalities.draft.pop()(n,r);const d=a?t[0]:o?o.operated?o.copy:o.original:e;return o&&Ot(o),i&&ve(d,d,o==null?void 0:o.options.updatedValues),[d,n&&a?[{op:R.Replace,path:[],value:t[0]}]:n,r&&a?[{op:R.Replace,path:[],value:u}]:r]}function ui(e,t){var n;const r={draft:[],revoke:[],handledSet:new WeakSet};let i,s;t.enablePatches&&(i=[],s=[]);const u=((n=t.mark)===null||n===void 0?void 0:n.call(t,e,X))===X.mutable||!ie(e,t)?e:kt({original:e,parentDraft:null,finalities:r,options:t});return[u,(a=[])=>{const[d,c,f]=oi(u,a,i,s,t.enableAutoFreeze);return t.enablePatches?[d,c,f]:d}]}function It(e){const{rootDraft:t,value:n,useRawReturn:r=!1,isRoot:i=!0}=e;Et(n,(s,o,u)=>{const a=E(o);if(a&&t&&a.finalities===t.finalities){e.isContainDraft=!0;const d=a.original;if(u instanceof Set){const c=Array.from(u);u.clear(),c.forEach(f=>u.add(s===f?d:f))}else $e(u,s,d)}else typeof o=="object"&&o!==null&&(e.value=o,e.isRoot=!1,It(e))}),i&&(e.isContainDraft||console.warn("The return value does not contain any draft, please use 'rawReturn()' to wrap the return value to improve performance."),r&&console.warn("The return value contains drafts, please don't use 'rawReturn()' to wrap the return value."))}function En(e){var t;const n=E(e);if(!ie(e,n==null?void 0:n.options))return e;const r=ge(e);if(n&&!n.operated)return n.original;let i;function s(){i=r===2?mt(e)?new Map(e):new(Object.getPrototypeOf(e)).constructor(e):r===3?Array.from(n.setMap.values()):Tn(e,n==null?void 0:n.options)}if(n){n.finalized=!0;try{s()}finally{n.finalized=!1}}else i=e;if(Et(i,(o,u)=>{if(n&&le(fe(n.original,o),u))return;const a=En(u);a!==u&&(i===e&&s(),$e(i,o,a))}),r===3){const o=(t=n==null?void 0:n.original)!==null&&t!==void 0?t:i;return wt(o)?new Set(i):new(Object.getPrototypeOf(o)).constructor(i)}return i}function An(e){if(!_e(e))throw new Error(`current() is only used for Draft, parameter: ${e}`);return En(e)}const Mt=(e=>function t(n,r,i){var s,o,u;if(typeof n=="function"&&typeof r!="function")return function(O,...U){return t(O,W=>n.call(this,W,...U),r)};const a=n,d=r;let c=i;if(typeof r!="function"&&(c=r),c!==void 0&&Object.prototype.toString.call(c)!=="[object Object]")throw new Error(`Invalid options: ${c}, 'options' should be an object.`);c=Object.assign(Object.assign({},e),c);const f=_e(a)?An(a):a,h=Array.isArray(c.mark)?(O,U)=>{for(const W of c.mark){if(typeof W!="function")throw new Error(`Invalid mark: ${W}, 'mark' should be a function.`);const ye=W(O,U);if(ye)return ye}}:c.mark,p=(s=c.enablePatches)!==null&&s!==void 0?s:!1,b=(o=c.strict)!==null&&o!==void 0?o:!1,w={enableAutoFreeze:(u=c.enableAutoFreeze)!==null&&u!==void 0?u:!1,mark:h,strict:b,enablePatches:p};if(!ie(f,w)&&typeof f=="object"&&f!==null)throw new Error("Invalid base state: create() only supports plain objects, arrays, Set, Map or using mark() to mark the state as immutable.");const[T,m]=ui(f,w);if(typeof r!="function"){if(!ie(f,w))throw new Error("Invalid base state: create() only supports plain objects, arrays, Set, Map or using mark() to mark the state as immutable.");return[T,m]}let S;try{S=d(T)}catch(O){throw Ot(E(T)),O}const K=O=>{const U=E(T);if(!_e(O)){if(O!==void 0&&!le(O,T)&&(U!=null&&U.operated))throw new Error("Either the value is returned as a new non-draft value, or only the draft is modified without returning any value.");const ye=O==null?void 0:O[Hr];if(ye){const de=ye[0];return w.strict&&typeof O=="object"&&O!==null&&It({rootDraft:U,value:O,useRawReturn:!0}),m([de])}if(O!==void 0)return typeof O=="object"&&O!==null&&It({rootDraft:U,value:O}),m([O])}if(O===T||O===void 0)return m([]);const W=E(O);if(w===W.options){if(W.operated)throw new Error("Cannot return a modified child draft.");return m([An(O)])}return m([O])};return S instanceof Promise?S.then(K,O=>{throw Ot(E(T)),O}):K(S)})();Object.prototype.constructor.toString();function Cn(e,t){const n=Object.keys(e),r=Object.keys(t);return n.length===r.length&&Object.keys(e).every(i=>t.hasOwnProperty(i))}function jn(e,t){return Object.keys(e).length===Object.keys(t).length&&Object.keys(e).every(n=>t.hasOwnProperty(n)&&e[n]===t[n])}function Je(e,t){return typeof e!="object"||typeof t!="object"||e===null||t===null?e===t:Cn(e,t)?Object.keys(e).every(n=>Je(e[n],t[n])):!1}function Rt(e){if(!Fe(e))return e;const t={};for(const[n,r]of Object.entries(e))r!==void 0&&(t[n]=r);return t}function Pn(e,t){if(!Fe(e)||!Fe(t))return t;const n=Object.assign({},e);for(const r of Object.keys(t)){if(t[r]===void 0)continue;if(t[r]===null){delete n[r];continue}const i=Fe(e[r])&&Fe(t[r]);n[r]=i?Pn(e[r],t[r]):t[r]}return n}function Fe(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function ai(e,t,n){if(!e||t.length===0)return;let r=e||{};for(let s=0;s<t.length-1;s++){const o=t[s];(!(o in r)||typeof r[o]!="object")&&(r[o]=typeof t[s+1]=="number"?[]:{}),r=r[o]}const i=t[t.length-1];Array.isArray(r)&&typeof i=="number"?r.splice(i,0,n):r[i]=n}function kn(e,t,n){if(!e||t.length===0)return;let r=e||{};for(let i=0;i<t.length-1;i++){const s=t[i];(!(s in r)||typeof r[s]!="object")&&(r[s]=typeof t[i+1]=="number"?[]:{}),r=r[s]}r[t[t.length-1]]=n}function In(e,t){if(!e||t.length===0)return;const[n,...r]=t;if(n in e){if(r.length===0){Array.isArray(e)?e.splice(n,1):delete e[n];return}In(e[n],r),ci(e[n])&&delete e[n]}}function ci(e){return e&&Object.keys(e).length===0}const Mn=/ZULU|YEKT|YEKST|YAPT|YAKT|YAKST|XJT|WGT|WGST|WFT|WETDST|WET|WDT|WAT|WAST|WAKT|WADT|VUT|VOLT|VLAT|VLAST|VET|UZT|UZST|UYT|UYST|UTC|UT|ULAT|ULAST|UCT|TVT|TRUT|TOT|TMT|TKT|TJT|TFT|TAHT|SGT|SCT|SAST|SADT|RET|PYT|PYST|PWT|PST|PONT|PMST|PMDT|PKT|PKST|PHT|PGT|PETT|PETST|PET|PDT|OMST|OMSST|NZT|NZST|NZDT|NUT|NST|NPT|NOVT|NOVST|NFT|NDT|MYT|MVT|MUT|MUST|MST|MSK|MSD|MPT|MMT|MHT|MEZ|METDST|MET|MESZ|MEST|MDT|MAWT|MART|MAGT|MAGST|LKT|LINT|LIGT|LHST|LHDT|KST|KRAT|KRAST|KOST|KGT|KGST|KDT|JST|JAYT|IST|IRT|IRKT|IRKST|IOT|IDT|ICT|HST|HKT|GYT|GMT|GILT|GFT|GET|GEST|GAMT|GALT|FNT|FNST|FKT|FKST|FJT|FJST|FET|EST|EGT|EGST|EETDST|EET|EEST|EDT|EAT|EAST|EASST|DDUT|DAVT|CXT|CST|COT|CLT|CLST|CKT|CHUT|CHAST|CHADT|CETDST|CET|CEST|CDT|CCT|CAST|CADT|BTT|BST|BRT|BRST|BRA|BOT|BORT|BNT|BDT|BDST|AZT|AZST|AZOT|AZOST|AWST|AWSST|AST|ART|ARST|ANAT|ANAST|AMT|AMST|ALMT|ALMST|AKST|AKDT|AFT|AEST|AESST|AEDT|ADT|ACWST|ACT|ACST|ACSST|ACDT$/,di={ZULU:0,YEKT:18e3,YEKST:21600,YAPT:36e3,YAKT:32400,YAKST:32400,XJT:21600,WGT:-10800,WGST:-7200,WFT:43200,WETDST:3600,WET:0,WDT:32400,WAT:3600,WAST:25200,WAKT:43200,WADT:28800,VUT:39600,VOLT:10800,VLAT:36e3,VLAST:36e3,VET:-14400,UZT:18e3,UZST:21600,UYT:-10800,UYST:-7200,UTC:0,UT:0,ULAT:28800,ULAST:32400,UCT:0,TVT:43200,TRUT:36e3,TOT:46800,TMT:18e3,TKT:46800,TJT:18e3,TFT:18e3,TAHT:-36e3,SGT:28800,SCT:14400,SAST:7200,SADT:37800,RET:14400,PYT:-14400,PYST:-10800,PWT:32400,PST:-28800,PONT:39600,PMST:-10800,PMDT:-7200,PKT:18e3,PKST:21600,PHT:28800,PGT:36e3,PETT:43200,PETST:43200,PET:-18e3,PDT:-25200,OMST:21600,OMSST:21600,NZT:43200,NZST:43200,NZDT:46800,NUT:-39600,NST:-12600,NPT:20700,NOVT:25200,NOVST:25200,NFT:-12600,NDT:-9e3,MYT:28800,MVT:18e3,MUT:14400,MUST:18e3,MST:-25200,MSK:10800,MSD:14400,MPT:36e3,MMT:23400,MHT:43200,MEZ:3600,METDST:7200,MET:3600,MESZ:7200,MEST:7200,MDT:-21600,MAWT:18e3,MART:-34200,MAGT:39600,MAGST:39600,LKT:19800,LINT:50400,LIGT:36e3,LHST:37800,LHDT:37800,KST:32400,KRAT:25200,KRAST:25200,KOST:39600,KGT:21600,KGST:21600,KDT:36e3,JST:32400,JAYT:32400,IST:7200,IRT:12600,IRKT:28800,IRKST:28800,IOT:21600,IDT:10800,ICT:25200,HST:-36e3,HKT:28800,GYT:-14400,GMT:0,GILT:43200,GFT:-10800,GET:14400,GEST:14400,GAMT:-32400,GALT:-21600,FNT:-7200,FNST:-3600,FKT:-10800,FKST:-10800,FJT:43200,FJST:46800,FET:10800,EST:-18e3,EGT:-3600,EGST:0,EETDST:10800,EET:7200,EEST:10800,EDT:-14400,EAT:10800,EAST:-21600,EASST:-21600,DDUT:36e3,DAVT:25200,CXT:25200,CST:-21600,COT:-18e3,CLT:-14400,CLST:-10800,CKT:-36e3,CHUT:36e3,CHAST:45900,CHADT:49500,CETDST:7200,CET:3600,CEST:7200,CDT:-18e3,CCT:28800,CAST:34200,CADT:37800,BTT:21600,BST:3600,BRT:-10800,BRST:-7200,BRA:-10800,BOT:-14400,BORT:28800,BNT:28800,BDT:21600,BDST:7200,AZT:14400,AZST:14400,AZOT:-3600,AZOST:0,AWST:28800,AWSST:32400,AST:-14400,ART:-10800,ARST:-10800,ANAT:43200,ANAST:43200,AMT:-14400,AMST:14400,ALMT:21600,ALMST:25200,AKST:-32400,AKDT:-28800,AFT:16200,AEST:36e3,AESST:39600,AEDT:39600,ADT:-10800,ACWST:31500,ACT:-18e3,ACST:34200,ACSST:37800,ACDT:37800};function fi(e){return new Date(e)}function li(e){return new Date(e+"Z")}const hi=/^(\d+)[\./-](\d+)[\./-](\d+)$/;function pi(e){const t=e.match(hi);if(!t)return null;const[n,r,i,s]=t;return r<=0||i<=0||s<=0?null:r>999?new Date(Date.UTC(r,i-1,s,0,0,0,0)):new Date(Date.UTC(s,r-1,i,0,0,0,0))}function yi(e){const[t,n]=e.split(" ");return new Date(t+"T"+n+"Z")}function bi(e){const[t,n]=e.split(" ");return new Date(t+"T"+n+"Z")}function _i(e){return new Date(e)}function gi(e){const t=/^(\w{3}) (\w{3}) (\d{2}) (\d{4})$/;if(!e.match(t))throw new Error(`Unable to parse \`${e}\` as a date.`);const r=new Date(e+" UTC");return new Date(Date.UTC(r.getUTCFullYear(),r.getUTCMonth(),r.getUTCDate(),0,0,0,0))}function Ti(e){const t=/^(.+T.+)([+-])(\d{2})$/,n=e.match(t);if(n){const[,r,i,s]=n,o=`${r}${i}${s}:00`;return new Date(o)}return null}function wi(e){const[t,n]=e.split(", "),[r,i,s]=t.split("/").map(Number),o=n.match(/(\d{1,2}):(\d{2}):(\d{2}) (AM|PM)/);if(!o)throw new Error(`Unable to parse time from: ${e}`);let[,u,a,d,c]=o;return u=Number(u),a=Number(a),d=Number(d),c==="PM"&&u!==12?u+=12:c==="AM"&&u===12&&(u=0),new Date(Date.UTC(s,r-1,i,u,a,d))}function mi(e){switch(e){case"epoch":return new Date(0);case"infinity":case"-infinity":case"today":case"tomorrow":case"yesterday":return null}}function Si(e){const t=e.match(Mn);if(!t)return null;const[n]=t,r=di[n],i=new Date(e.replace(Mn,"Z"));return new Date(i.getTime()-r*1e3)}const vi=[pi,bi,gi,wi,_i,li,Ti,yi,fi,mi,Si];function Oi(e,t){try{const n=e(t);return n instanceof Date&&!isNaN(n.getTime())?n:null}catch{return null}}function Dt(e){for(const t of vi){const n=Oi(t,e);if(n)return n}return null}function Ei(e){try{const t=JSON.parse(e);return typeof t=="string"?Dt(t):null}catch{return null}}function Ze(e){if(e!==void 0){if(e===null)return null;if(e instanceof Date)return e;if(typeof e=="string"){const t=Dt(e)||Ei(e)||Dt(e.trim());if(!t)throw new Error(`Unable to parse \`${e}\` as a date.`);return t}else if(typeof e=="number")return new Date(e);throw new Error(`Invalid date value \`${e}\`. Expected a date, number, or string, got type ${typeof e}.`)}}function Ai(e){return e.cardinality==="one"}function xt(e){return e["value-type"]==="ref"}function $t(e){return e["value-type"]==="blob"}function Oe(e,t){return e[t]}function Xe(e,t){return t.reduce((n,r)=>n&&n.get(r),e)}function se(e,t){if(t.length===0)throw new Error("path must have at least one element");if(t.length===1){e.delete(t[0]);return}const[n,...r]=t;e.has(n)&&se(e.get(n),r)}function Q(e,t,n){if(t.length===0)throw new Error("path must have at least one element");if(t.length===1){e.set(t[0],n);return}const[r,...i]=t;let s=e.get(r);s||(s=new Map,e.set(r,s)),Q(s,i,n)}function Rn(e,t,n){const r=new Map,i=new Map,s=new Map;for(const o of t){let[u,a,d,c]=o;const f=Oe(e,a);if(!f){console.warn("no such attr",u,e);continue}f["checked-data-type"]==="date"&&n&&(d=Ze(d),o[2]=d),xt(f)&&Q(s,[d,a,u],o),Q(r,[u,a,d],o),Q(i,[a,u,d],o)}return{eav:r,aev:i,vae:s}}function Dn(e){const t=new Map,n=new Map,r=new Map,i=new Map;for(const s of Object.values(e)){const o=s["forward-identity"],[u,a,d]=o,c=s["reverse-identity"];if(Q(r,[a,d],s),$t(s)&&Q(t,[a,d],s),s["primary?"]&&Q(n,[a],s),c){const[f,h,p]=c;Q(i,[h,p],s)}}return{blobAttrs:t,primaryKeys:n,forwardIdents:r,revIdents:i}}function Ci(e){return{__type:e.__type,attrs:e.attrs,triples:G(e.eav,3),cardinalityInference:e.cardinalityInference,linkIndex:e.linkIndex,useDateObjects:e.useDateObjects}}function ji(e){return Lt(e.attrs,e.triples,e.cardinalityInference,e.linkIndex,e.useDateObjects)}function Ut(e){e.attrIndexes=Dn(e.attrs)}function Lt(e,t,n,r,i){const s=Rn(e,t,i);return s.useDateObjects=i,s.attrs=e,s.attrIndexes=Dn(e),s.cardinalityInference=n,s.linkIndex=r,s.__type="store",s}function Ne(e,t){var n,r;let i;if(Array.isArray(t[0])){const[o,u]=t[0],a=e.aev.get(o);if(!a)return null;i=(n=G(a,2).find(c=>c[2]===u))===null||n===void 0?void 0:n[0]}else i=t[0];if(!i)return null;const s=t[2];if(Array.isArray(s)&&s.length===2&&e.aev.get(s[0])){const[o,u]=s,a=e.aev.get(o);if(!a)return null;const c=(r=G(a,2).find(g=>g[2]===u))===null||r===void 0?void 0:r[0];if(!c)return null;const[f,h,p,...b]=t;return[i,h,c,...b]}else{const[o,...u]=t;return[i,...u]}}function Pi(e,t){const n=Ne(e,t);if(!n)return;const[r,i,s]=n,o=Oe(e.attrs,i);o&&(se(e.eav,[r,i,s]),se(e.aev,[i,r,s]),xt(o)&&se(e.vae,[s,i,r]))}let ki=0;function xn(e,t,n){const[r,i,s]=n;let o;const u=Xe(e.ea,[r,i,s]);return u&&(o=u[3]),o||Date.now()*10+ki++}function Ii(e,t){var n;const r=Ne(e,t);if(!r)return;let[i,s,o]=r;const u=Oe(e.attrs,s);if(!u)return;u["checked-data-type"]==="date"&&e.useDateObjects&&(o=Ze(o));const a=Xe(e.eav,[i,s,o]),d=(n=a==null?void 0:a[3])!==null&&n!==void 0?n:xn(e,u,r),c=[i,s,o,d];Ai(u)?(Q(e.eav,[i,s],new Map([[o,c]])),Q(e.aev,[s,i],new Map([[o,c]]))):(Q(e.eav,[i,s,o],c),Q(e.aev,[s,i,o],c)),xt(u)&&Q(e.vae,[o,s,i],c)}function Mi(e,t){var n;const r=Ne(e,t);if(!r)return;const[i,s,o]=r,u=Oe(e.attrs,s);if(!u)return;if(!$t(u))throw new Error("merge operation is not supported for links");const a=Xe(e.eav,[i,s]);if(!a)return;const d=(n=a.values().next())===null||n===void 0?void 0:n.value;if(!d)return;const c=d[2],f=Pn(c,o),h=[i,s,f,xn(e,u,d)];Q(e.eav,[i,s],new Map([[f,h]]))}function Ft(e,t){var n,r;const[i,s]=t,o=Ne(e,[i]);if(!o)return;const[u]=o,a=e.eav.get(u);if(a){for(const c of a.keys()){const f=e.attrs[c];f&&f["on-delete-reverse"]==="cascade"&&G(a.get(c),1).forEach(([h,p,b])=>{var g;return Ft(e,[b,(g=f["reverse-identity"])===null||g===void 0?void 0:g[1]])}),(!s||!f||((n=f["forward-identity"])===null||n===void 0?void 0:n[1])===s)&&(se(e.aev,[c,u]),se(e.eav,[u,c]))}a.size===0&&se(e.eav,[u])}const d=e.vae.get(u)&&G(e.vae.get(u),2);d&&d.forEach(c=>{var f,h,p;const[b,g,w]=c,T=e.attrs[g];(!s||!T||((f=T["reverse-identity"])===null||f===void 0?void 0:f[1])===s)&&(se(e.eav,[b,g,w]),se(e.aev,[g,b,w]),se(e.vae,[w,g,b])),T&&T["on-delete"]==="cascade"&&((h=T["reverse-identity"])===null||h===void 0?void 0:h[1])===s&&Ft(e,[b,(p=T["forward-identity"])===null||p===void 0?void 0:p[1]])}),((r=e.vae.get(u))===null||r===void 0?void 0:r.size)===0&&se(e.vae,[u])}function $n(e,t){const n=Rn(e.attrs,t,e.useDateObjects);Object.keys(n).forEach(r=>{e[r]=n[r]})}function Ri(e,[t]){e.attrs[t.id]=t,Ut(e)}function Un(e){return G(e.eav,3)}function Di(e,[t]){if(!e.attrs[t])return;const n=Un(e).filter(([r,i])=>i!==t);delete e.attrs[t],Ut(e),$n(e,n)}function xi(e,[t]){const n=e.attrs[t.id];n&&(e.attrs[t.id]=Object.assign(Object.assign({},n),t),Ut(e),$n(e,Un(e)))}function $i(e,t){const[n,...r]=t;switch(n){case"add-triple":Ii(e,r);break;case"deep-merge-triple":Mi(e,r);break;case"retract-triple":Pi(e,r);break;case"delete-entity":Ft(e,r);break;case"add-attr":Ri(e,r);break;case"delete-attr":Di(e,r);break;case"update-attr":xi(e,r);break;case"restore-attr":break;case"rule-params":break;default:throw new Error(`unhandled transaction action: ${n}`)}}function G(e,t,n=[]){if(!e||t===0)return n;if(t===1){for(const r of e.values())n.push(r);return n}for(const r of e.values())G(r,t-1,n);return n}function et(e,t,n){var r,i;const s=[];if(n!=null&&n.hasOwnProperty("$not")){for(const u of t.keys())n.$not!==u&&s.push(t.get(u));return s}if(n!=null&&n.hasOwnProperty("$isNull")){const{attrId:u,isNull:a,reverse:d}=n.$isNull;if(d)for(const c of t.keys()){const f=e.vae.get(c),h=!f||((r=f.get(u))===null||r===void 0?void 0:r.get(null))||!f.get(u);(a?h:!h)&&s.push(t.get(c))}else{const c=e.aev.get(u);for(const f of t.keys()){const h=!c||((i=c.get(f))===null||i===void 0?void 0:i.get(null))||!c.get(f);(a?h:!h)&&s.push(t.get(f))}}return s}if(n!=null&&n.$comparator)return G(t,1).filter(n.$op);const o=n.in||n.$in||[n];for(const u of o){const a=t.get(u);a&&s.push(a)}return s}function Ui(e,t,n){let r="";return e!==void 0&&(r+="e"),t!==void 0&&(r+="a"),n!==void 0&&(r+="v"),r}function Li(e,[t,n,r]){var i,s;switch(Ui(t,n,r)){case"e":{const u=e.eav.get(t);return G(u,2)}case"ea":{const u=(i=e.eav.get(t))===null||i===void 0?void 0:i.get(n);return G(u,1)}case"eav":{const u=(s=e.eav.get(t))===null||s===void 0?void 0:s.get(n);return u?et(e,u,r):[]}case"ev":{const u=e.eav.get(t);if(!u)return[];const a=[];for(const d of u.values())a.push(...et(e,d,r));return a}case"a":{const u=e.aev.get(n);return G(u,2)}case"av":{const u=e.aev.get(n);if(!u)return[];const a=[];for(const d of u.values())a.push(...et(e,d,r));return a}case"v":{const u=[];for(const a of e.eav.values())for(const d of a.values())u.push(...et(e,d,r));return u}default:return G(e.eav,3)}}function Fi(e,t,n){var r;const i={};for(const[s,o]of t.entries()){const u=(r=e.eav.get(n))===null||r===void 0?void 0:r.get(o.id),a=G(u,1);for(const d of a)i[s]=d[2]}return i}function Ee(e,t,n){var r;return(r=e.attrIndexes.forwardIdents.get(t))===null||r===void 0?void 0:r.get(n)}function Ln(e,t,n){var r;return(r=e.attrIndexes.revIdents.get(t))===null||r===void 0?void 0:r.get(n)}function Ni(e,t){return e.attrIndexes.blobAttrs.get(t)}function Fn(e,t){var n;const r=e.attrIndexes.primaryKeys.get(t);return r||((n=e.attrIndexes.forwardIdents.get(t))===null||n===void 0?void 0:n.get("id"))}function Vi(e,t){const n=Ne(e,t);if(!n)return;const[r,i,s]=n;if(Oe(e.attrs,i))return Xe(e.eav,[r,i])}function Wi(e,t){const n=t.filter(([r,i,s,o,u])=>{if(r!=="add-triple"&&r!=="deep-merge-triple")return!0;const a=u==null?void 0:u.mode;if(a!=="create"&&a!=="update")return!0;let d=!1;const c=Oe(e.attrs,s);if(c){const f=Fn(e,c["forward-identity"][1]);d=!!Vi(e,[i,f.id,i])}return!(a==="create"&&d||a==="update"&&!d)});return Mt(e,r=>{n.forEach(i=>{$i(r,i)})})}function zi(e){return typeof e=="string"&&e.startsWith("?")}function Ki(e,t,n){if(n.hasOwnProperty(e)){const r=n[e];return Vn(r,t,n)}return Object.assign(Object.assign({},n),{[e]:t})}function Nn(e,t,n){return e===t?n:null}function qi(e){switch(typeof e){case"string":return e.startsWith("?")?Ki:Nn;default:return Nn}}const Bi=["in","$in","$not","$isNull","$comparator"];function Qi(e){for(const t of Bi)if(e.hasOwnProperty(t))return!0;return!1}function Vn(e,t,n){return n?typeof e=="object"?Qi(e)?n:null:qi(e)(e,t,n):null}function Gi(e,t,n){return e.reduce((r,i,s)=>{const o=t[s];return Vn(i,o,r)},n)}function Yi(e,t,n){return Zi(e,t,n).map(r=>Gi(t,r,n)).filter(r=>r)}function Hi(e,t,n){return t.or?t.or.patterns.flatMap(r=>Nt(e,r,n)):t.and?t.and.patterns.reduce((r,i)=>Nt(e,i,r),n):n.flatMap(r=>Yi(e,t,r))}function Nt(e,t,n=[{}]){return t.reduce((r,i)=>Hi(e,i,r),n)}function Vt(e,t){return Array.isArray(t)?t.map(n=>Vt(e,n)):zi(t)?e[t]:t}function Ji(e,{find:t,where:n}){return Nt(e,n).map(i=>Vt(i,t))}function Zi(e,t,n){return Li(e,Vt(n,t))}const Xi=/^(?:[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$/i;function Ae(e){return typeof e=="string"&&Xi.test(e)}const F=[];for(let e=0;e<256;++e)F.push((e+256).toString(16).slice(1));function es(e,t=0){return(F[e[t+0]]+F[e[t+1]]+F[e[t+2]]+F[e[t+3]]+"-"+F[e[t+4]]+F[e[t+5]]+"-"+F[e[t+6]]+F[e[t+7]]+"-"+F[e[t+8]]+F[e[t+9]]+"-"+F[e[t+10]]+F[e[t+11]]+F[e[t+12]]+F[e[t+13]]+F[e[t+14]]+F[e[t+15]]).toLowerCase()}let Wt;const ts=new Uint8Array(16);function ns(){if(!Wt){if(typeof crypto>"u"||!crypto.getRandomValues)throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");Wt=crypto.getRandomValues.bind(crypto)}return Wt(ts)}const Wn={randomUUID:typeof crypto<"u"&&crypto.randomUUID&&crypto.randomUUID.bind(crypto)};function rs(e,t,n){var i;if(Wn.randomUUID&&!e)return Wn.randomUUID();e=e||{};const r=e.random??((i=e.rng)==null?void 0:i.call(e))??ns();if(r.length<16)throw new Error("Random bytes length must be >= 16");return r[6]=r[6]&15|64,r[8]=r[8]&63|128,es(r)}function zn(e){const t=e.replace(/-/g,""),n=[];for(let r=0;r<t.length;r+=2)n.push(parseInt(t.substring(r,r+2),16));return n}function is(e,t){for(let n=0;n<e.length;n++){if(e[n]<t[n])return-1;if(e[n]>t[n])return 1}return 0}function ss(e,t){return is(zn(e),zn(t))}function V(){return rs()}function os(e,t){return e.localeCompare(t)}function us(){let e=os;if(typeof Intl=="object"&&Intl.hasOwnProperty("Collator"))try{e=Intl.Collator("en-US").compare}catch{}return e}const as=us();let cs=0;function Ve(e){return tt(`_${e}`,cs++)}function tt(e,t){return`?${e}-${t}`}class Ce extends Error{constructor(t){super(t),this.name="AttrNotFoundError"}}function ds(e,t){const n=Fn(e,t);if(!n)throw new Ce(`Could not find id attr for ${t}`);return n}function Kn(e,t,n,r){return[fs(e,t,n,r)]}function fs(e,t,n,r){return[e(n,r),ds(t,n).id,e(n,r),e("time",r)]}function ls(e,t,n){return e.map(r=>r===t?n:r)}function qn(e,t,n,r,i){const s=Ee(t,n,i),o=Ln(t,n,i),u=s||o;if(!u)throw new Ce(`Could not find attr for ${[n,i]}`);if(u["value-type"]!=="ref")throw new Error(`Attr ${u.id} is not a ref`);const[a,d]=u["forward-identity"],[c,f]=u["reverse-identity"],h=r+1,p=s?[e(d,r),u.id,e(f,h),Ve("time")]:[e(d,h),u.id,e(f,r),Ve("time")];return[s?f:d,h,p,u,!!s]}function Bn(e,t){if(typeof t!="string")return function(o){return!1};const r=t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&").replace(/%/g,".*").replace(/_/g,"."),i=new RegExp(`^${r}$`,e?void 0:"i");return function(o){return typeof o!="string"?!1:i.test(o)}}function hs(e,t){if(typeof t!="object"||t.hasOwnProperty("$in")||t.hasOwnProperty("in"))return t;const n=e["checked-data-type"]==="date";if(t.hasOwnProperty("$gt"))return{$comparator:!0,$op:n?function(i){return new Date(i[2])>new Date(t.$gt)}:function(i){return i[2]>t.$gt}};if(t.hasOwnProperty("$gte"))return{$comparator:!0,$op:n?function(i){return new Date(i[2])>=new Date(t.$gte)}:function(i){return i[2]>=t.$gte}};if(t.hasOwnProperty("$lt"))return{$comparator:!0,$op:n?function(i){return new Date(i[2])<new Date(t.$lt)}:function(i){return i[2]<t.$lt}};if(t.hasOwnProperty("$lte"))return{$comparator:!0,$op:n?function(i){return new Date(i[2])<=new Date(t.$lte)}:function(i){return i[2]<=t.$lte}};if(t.hasOwnProperty("$like")){const r=Bn(!0,t.$like);return{$comparator:!0,$op:function(s){return r(s[2])}}}if(t.hasOwnProperty("$ilike")){const r=Bn(!1,t.$ilike);return{$comparator:!0,$op:function(s){return r(s[2])}}}return t}function ps(e,t,n,r,i,s){const o=Ee(t,n,i),u=Ln(t,n,i),a=o||u;if(!a)throw new Ce(`No attr for etype = ${n} label = ${i}`);if(s!=null&&s.hasOwnProperty("$isNull")){const d=Ee(t,n,"id");if(!d)throw new Ce(`No attr for etype = ${n} label = id`);return[e(n,r),d.id,{$isNull:{attrId:a.id,isNull:s.$isNull,reverse:!o}},Ve("time")]}return o?[e(n,r),a.id,hs(a,s),Ve("time")]:[s,a.id,e(n,r),Ve("time")]}function ys(e,t,n,r,i){const[s,o,u]=i.reduce((a,d)=>{const[c,f,h]=a,[p,b,g]=qn(e,t,c,f,d);return[p,b,[...h,g]]},[n,r,[]]);return[s,o,u]}function zt(e,t,n,r,i,s){const o=i.slice(0,i.length-1),u=i[i.length-1],[a,d,c]=ys(e,t,n,r,o),f=ps(e,t,a,d,u,s);return c.concat([f])}function bs(e,t){return t?[t].concat(e):e}function _s([e,t]){return e==="or"&&Array.isArray(t)}function gs([e,t]){return e==="and"&&Array.isArray(t)}function Ts(e,t,n){return(r,i)=>{const s=e(r,i);return t==s?s:`${s}-${n}`}}function Qn(e,t,n,r,i,s){const o=e(r,i),u=s.map((a,d)=>{const c=Ts(e,o,d);return Yn(c,n,r,i,a)});return{[t]:{patterns:u,joinSym:o}}}function ws(e){const t=[];for(let n=1;n<=e.length;n++)t.push(e.slice(0,n));return t}function Gn(e,t,n,r,i){return ws(i).map(s=>zt(e,t,n,r,s,{$isNull:!0}))}function Yn(e,t,n,r,i){return Object.entries(i).flatMap(([s,o])=>{if(_s([s,o]))return Qn(e,"or",t,n,r,o);if(gs([s,o]))return Qn(e,"and",t,n,r,o);if(s==="$entityIdStartsWith")return[];const u=s.split(".");if(o!=null&&o.hasOwnProperty("$ne")&&(o=Object.assign(Object.assign({},o),{$not:o.$ne}),delete o.$ne),o!=null&&o.hasOwnProperty("$not")){const a=zt(e,t,n,r,u,o),d=Gn(e,t,n,r,u);return[{or:{patterns:[a,...d],joinSym:e(n,r)}}]}return o!=null&&o.hasOwnProperty("$isNull")&&o.$isNull===!0&&u.length>1?[{or:{patterns:Gn(e,t,n,r,u),joinSym:e(n,r)}}]:zt(e,t,n,r,u,o)})}function ms(e,t,n,r){const i=tt;return r?Yn(i,e,t,n,r).concat(Kn(i,e,t,n)):Kn(i,e,t,n)}function Ss(e,t,n){return[e(t,n),e("time",n)]}function vs(e,t,n,r,i,s){const[o,u,a,d,c]=qn(e,t,n,r,i),f=ls(a,e(n,r),s);return[o,u,f,d,c]}function Os(e,t,{etype:n,level:r,form:i},s){const o=Object.keys(i).filter(u=>u!=="$");return o.length?Object.entries(s).map(function([a,d]){return o.map(function(h){var p,b,g;const w=!!(t.cardinalityInference&&(!((g=(b=(p=t.linkIndex)===null||p===void 0?void 0:p[n])===null||b===void 0?void 0:b[h])===null||g===void 0)&&g.isSingular));try{const[T,m,S]=vs(e,t,n,r,h,a),K=Jn(t,{etype:T,level:m,form:i[h],join:S}),O=w?K[0]:K;return{[h]:O}}catch(T){if(T instanceof Ce)return{[h]:w?void 0:[]};throw T}}).reduce(function(h,p){return Object.assign(Object.assign({},h),p)},d)}):Object.values(s)}function Es(e,t,n){return n==="string"?as(e,t):e>t?1:-1}function nt([e,t],[n,r],i){return t===r||t==null&&r==null?ss(e,n):r==null?1:t==null?-1:Es(t,r,i)}function Kt(e){return e==null?e:new Date(e).getTime()}function As(e,t,n,r){var i;const[s,o,u,a]=e,d=n==="desc"?1:-1;if(((i=t["forward-identity"])===null||i===void 0?void 0:i[2])==="id")return nt(r,[s,a],null)===d;const[c,f]=r,h=t["checked-data-type"],p=h==="date"?Kt(f):f,b=h==="date"?Kt(u):u;return nt([c,p],[s,b],h)===d}function Cs(e,t){const n=t[1];return e.attrs[n]}function js(e,t,n){const r=Object.keys(n)[0];return Ee(e,t,r)}function Ps(e,t,n,r){if(n)return Cs(e,n);if(r)return js(e,t,r)}function ks(e,t,n){var r,i;if(!Array.isArray(n.fields))return Ni(e,t);const s=new Map;for(const o of n.fields){const u=Ee(e,t,o),a=(r=u==null?void 0:u["forward-identity"])===null||r===void 0?void 0:r[2];a&&$t(u)&&s.set(a,u)}if(!s.has("id")){const o=Ee(e,t,"id"),u=(i=o==null?void 0:o["forward-identity"])===null||i===void 0?void 0:i[2];u&&s.set(u,o)}return s}function Is(e,{etype:t,pageInfo:n,dq:r,form:i}){var s,o;const u=(s=i==null?void 0:i.$)===null||s===void 0?void 0:s.order,a=Hn(i),d=Ms(i);let c=Ji(e,r);const f=n==null?void 0:n["start-cursor"],h=Ps(e,t,f,u);if(h&&((o=h==null?void 0:h["forward-identity"])===null||o===void 0?void 0:o[2])!=="id"){const g=h["checked-data-type"]==="date",w=h.id;c=c.map(([T])=>{var m,S,K,O,U;let W=(U=(O=(K=(S=(m=e.eav.get(T))===null||m===void 0?void 0:m.get(w))===null||S===void 0?void 0:S.values())===null||K===void 0?void 0:K.next())===null||O===void 0?void 0:O.value)===null||U===void 0?void 0:U[2];return g&&(W=Kt(W)),[T,W]})}c.sort(d==="asc"?function(w,T){return nt(w,T,h==null?void 0:h["checked-data-type"])}:function(w,T){return nt(T,w,h==null?void 0:h["checked-data-type"])});let p={};const b=ks(e,t,r);for(const g of c){const[w]=g;if(p[w]||!a&&f&&h&&As(f,h,d,g))continue;const T=Fi(e,b,w);T&&(p[w]=T)}return p}function Ms(e){var t;const n=(t=e.$)===null||t===void 0?void 0:t.order;return n&&n[Object.keys(n)[0]]||"asc"}function Hn(e){var t,n,r;const i=(t=e.$)===null||t===void 0?void 0:t.offset,s=(n=e.$)===null||n===void 0?void 0:n.before,o=(r=e.$)===null||r===void 0?void 0:r.after;return!i&&!s&&!o}function Rs(e,{etype:t,level:n,form:r,join:i,pageInfo:s}){var o,u,a,d,c;if(!Hn(r)&&(!s||!s["start-cursor"]))return[];const f=bs(ms(e,t,n,(o=r.$)===null||o===void 0?void 0:o.where),i),h=Ss(tt,t,n),p=(u=r.$)===null||u===void 0?void 0:u.fields,b=Is(e,{etype:t,pageInfo:s,form:r,dq:{where:f,find:h,fields:p}}),g=((a=r.$)===null||a===void 0?void 0:a.limit)||((d=r.$)===null||d===void 0?void 0:d.first)||((c=r.$)===null||c===void 0?void 0:c.last);if(g!=null){const w=Object.entries(b);return w.length<=g?b:Object.fromEntries(w.slice(0,g))}return b}function Ds(e,t){try{return Rs(e,t)}catch(n){if(n instanceof Ce)return{};throw n}}function Jn(e,t){const n=Ds(e,t);return Os(tt,e,t,n)}function xs(e){const t={};for(const[n,r]of Object.entries(e))t[n]={startCursor:r["start-cursor"],endCursor:r["end-cursor"],hasNextPage:r["has-next-page?"],hasPreviousPage:r["has-previous-page?"]};return t}function $s({store:e,pageInfo:t,aggregate:n},r){const s={data:Object.keys(r).reduce(function(u,a){return n!=null&&n[a]||a==="$$ruleParams"||(u[a]=Jn(e,{etype:a,form:r[a],level:0,pageInfo:t==null?void 0:t[a]})),u},{})};return t&&(s.pageInfo=xs(t)),n&&(s.aggregate=n),s}function Us(){const t={__etype:1,__ops:1,create:1,update:1,link:1,unlink:1,delete:1,merge:1,ruleParams:1};return new Set(Object.keys(t))}const Ls=Us();function qt(e,t,n){const r={__etype:e,__ops:n};return new Proxy(r,{get:(i,s)=>{if(s==="__ops")return n;if(s==="__etype")return e;if(Ls.has(s))return(o,u)=>qt(e,t,[...n,u?[s,e,t,o,u]:[s,e,t,o]])}})}function rt(e){return e.startsWith("lookup__")}function Zn(e){const[t,n,...r]=e.split("__");return[n,JSON.parse(r.join("__"))]}function Fs(e){return new Proxy({__etype:e},{get(t,n){if(n==="__etype")return e;const r=n;return rt(r)?qt(e,Zn(r),[]):qt(e,r,[])}})}function Bt(){return new Proxy({},{get(e,t){return Fs(t)}})}Bt();function Ns(e){return e.__ops}function Vs(e,t){const{attrIdMap:n,refSwapAttrIds:r}=e,i=[];for(const o of t){const u=n[o];if(u)i.push(u);else if(Array.isArray(o)&&o.length==2&&n[o[0]]){const[a,d]=o;i.push([n[a],d])}else i.push(o)}const[s]=t;if((s==="add-triple"||s==="retract-triple")&&r.has(t[2])){const o=i[1];i[1]=i[3],i[3]=o}return i}function N(e,t,n){return Object.values(e).find(r=>{const[i,s,o]=r["forward-identity"];return s===t&&o===n})}function we(e,t,n){return Object.values(e).find(r=>{const i=r["reverse-identity"];if(!i)return!1;const[s,o,u]=i;return o===t&&u===n})}function Ws(e){if(Array.isArray(e))return e;const t=Object.entries(e);if(t.length!==1)throw new Error("lookup must be an object with a single unique attr and value.");return t[0]}function Qt(e,t,n){return n.indexOf(".")!==-1&&!N(e,t,n)}function Gt(e){const[t,n,...r]=e.split(".");if(r.length>0||n!=="id")throw new Error(`${e} is not a valid lookup attribute.`);return t}function zs(e,t,n){if(!Qt(e,t,n))return N(e,t,n);const r=Gt(n),i=N(e,t,r)||we(e,t,r);if(i&&i["value-type"]!=="ref")throw new Error(`${n} does not reference a valid link attribute.`);return i}function Yt(e){return typeof e=="string"&&!rt(e)?null:typeof e=="string"&&rt(e)?Zn(e):Ws(e)}function Y(e,t,n){const r=Yt(n);if(r===null)return n;const[i,s]=r,o=zs(e,t,i);if(!o||!o["unique?"])throw new Error(`${i} is not a unique attribute.`);return[o.id,s]}function Xn(e,t,n,r){const i=Y(e,t,n);return Array.isArray(i)?[["add-triple",i,N(e,t,"id").id,i]].concat(r):r}function Ks({attrs:e},[t,n,r]){const i=Object.entries(r).flatMap(([s,o])=>{const u=Array.isArray(o)?o:[o],a=N(e,t,s),d=we(e,t,s);return u.map(c=>a?["add-triple",Y(e,t,n),a.id,Y(e,a["reverse-identity"][1],c)]:["add-triple",Y(e,d["forward-identity"][1],c),d.id,Y(e,t,n)])});return Xn(e,t,n,i)}function qs({attrs:e},[t,n,r]){const i=Object.entries(r).flatMap(([s,o])=>{const u=Array.isArray(o)?o:[o],a=N(e,t,s),d=we(e,t,s);return u.map(c=>a?["retract-triple",Y(e,t,n),a.id,Y(e,a["reverse-identity"][1],c)]:["retract-triple",Y(e,d["forward-identity"][1],c),d.id,Y(e,t,n)])});return Xn(e,t,n,i)}function Bs(e,t,n){if(Array.isArray(n)){const[r,i]=n;for(const s of e||[]){const o=s==null?void 0:s.aev.get(r);if(o){for(const[u,a,d]of G(o,2))if(d===i)return!0}}}else for(const r of e||[]){const i=r==null?void 0:r.eav.get(n);if(i){for(const s of i.keys())if(r.attrs[s]["forward-identity"][1]==t)return!0}}return!1}function er({stores:e,attrs:t},[n,r,i,s]){return(s==null?void 0:s.upsert)===!1?{mode:"update"}:(s==null?void 0:s.upsert)===!0?null:Bs(e,n,r)?{mode:"update"}:null}function Qs(e,t){const{stores:n,attrs:r}=e,[i,s,o,u]=t,a=Rt(o),d=Y(r,i,s);return[["id",d]].concat(Object.entries(a)).map(([f,h])=>{const p=N(r,i,f);return p["checked-data-type"]==="date"&&e.useDateObjects&&(h=Ze(h)),["add-triple",d,p.id,h,{mode:"create"}]})}function Gs(e,t){const{stores:n,attrs:r}=e,[i,s,o,u]=t,a=Rt(o),d=Y(r,i,s),c=er(e,[i,d,o,u]);return[["id",d]].concat(Object.entries(a)).map(([h,p])=>{const b=N(r,i,h);return b["checked-data-type"]==="date"&&e.useDateObjects&&(p=Ze(p)),["add-triple",d,b.id,p,...c?[c]:[]]})}function Ys({attrs:e},[t,n]){return[["delete-entity",Y(e,t,n),t]]}function Hs(e,t){const{stores:n,attrs:r}=e,[i,s,o,u]=t,a=Rt(o),d=Y(r,i,s),c=er(e,[i,d,o,u]),f=Object.entries(a).map(([p,b])=>{const g=N(r,i,p);return["deep-merge-triple",d,g.id,b,...c?[c]:[]]});return[["add-triple",d,N(r,i,"id").id,d,...c?[c]:[]]].concat(f)}function Js({attrs:e},[t,n,r]){return[["rule-params",Y(e,t,n),t,r]]}function Zs(e){const[t,n,r,i,s]=e;if(!i)return e;const o=Object.assign({},i);return delete o.id,[t,n,r,o,...s?[s]:[]]}function Xs(e,t){const[n,...r]=Zs(t);switch(n){case"merge":return Hs(e,r);case"create":return Qs(e,r);case"update":return Gs(e,r);case"link":return Ks(e,r);case"unlink":return qs(e,r);case"delete":return Ys(e,r);case"ruleParams":return Js(e,r);default:throw new Error(`unsupported action ${n}`)}}function eo(e){switch(e){case"string":case"date":case"boolean":case"number":return e;default:return}}function to(e,t,n){var r,i;const s=(i=(r=e.entities[t])===null||r===void 0?void 0:r.attrs)===null||i===void 0?void 0:i[n];if(n==="id")return null;if(!s)throw new Error(`${t}.${n} does not exist in your schema`);const{unique:o,indexed:u}=s==null?void 0:s.config,a=eo(s==null?void 0:s.valueType);return{"index?":u,"unique?":o,"checked-data-type":a}}function it(e,t,n,r){const i=e?to(e,t,n):null,s=V(),u=[V(),t,n];return Object.assign(Object.assign({id:s,"forward-identity":u,"value-type":"blob",cardinality:"one","unique?":!1,"index?":!1,isUnsynced:!0},i||{}),r||{})}function no(e,t,n){return Object.values(e.links).find(i=>i.forward.on===t&&i.forward.label===n||i.reverse.on===t&&i.reverse.label===n)}function ro(e,t,n){const r=no(e,t,n);if(!r)throw new Error(`Couldn't find the link ${t}.${n} in your schema`);const{forward:i,reverse:s}=r;return{"forward-identity":[V(),i.on,i.label],"reverse-identity":[V(),s.on,s.label],cardinality:i.has==="one"?"one":"many","unique?":s.has==="one","on-delete":i.onDelete,"on-delete-reverse":s.onDelete}}function tr(e,t,n,r){const i=e?ro(e,t,n):null,s=V(),o=[V(),t,n],u=[V(),n,t];return Object.assign(Object.assign({id:s,"forward-identity":o,"reverse-identity":u,"value-type":"ref",cardinality:"many","unique?":!1,"index?":!1,isUnsynced:!0},i||{}),r||{})}const io=new Set(["create","update","merge","link","unlink"]),so=new Set(["link","unlink"]),oo=new Set(["create","update","merge"]),uo=new Set(["link","unlink","create","update","merge","delete","ruleParams"]),Ht={"unique?":!0,"index?":!0},ao=Object.assign(Object.assign({},Ht),{cardinality:"one"});function co(e){const t=[],[n,r,i,s]=e;if(!uo.has(n))return t;const o=Yt(i);if(o&&t.push({etype:r,lookupPair:o}),n==="link")for(const[u,a]of Object.entries(s)){const d=Array.isArray(a)?a:[a];for(const c of d){const f=Yt(c);f&&t.push({etype:r,lookupPair:f,linkLabel:u})}}return t}function fo({attrs:e,schema:t},n){var r,i;const[s,o,u]=[new Set,Object.assign({},e),[]];function a(f){o[f.id]=f,u.push(["add-attr",f]),s.add(f.id)}function d(f){f!=null&&f.isUnsynced&&!s.has(f.id)&&(u.push(["add-attr",f]),s.add(f.id))}function c(f,h){const p=N(o,f,h),b=we(o,f,h);d(p),d(b),!p&&!b&&a(tr(t,f,h,ao))}for(const f of n)for(const{etype:h,lookupPair:p,linkLabel:b}of co(f)){const g=p[0];if(b){c(h,b);const w=N(o,h,b),T=we(o,h,b);d(w),d(T);const m=((r=w==null?void 0:w["reverse-identity"])===null||r===void 0?void 0:r[1])||((i=T==null?void 0:T["forward-identity"])===null||i===void 0?void 0:i[1])||b;if(Qt(o,m,g))c(m,Gt(g));else{const S=N(o,m,g);S||a(it(t,m,g,Ht)),d(S)}}else if(Qt(o,h,g))c(h,Gt(g));else{const w=N(o,h,g);w||a(it(t,h,g,Ht)),d(w)}}for(const f of n){const[h,p,b,g]=f;if(io.has(h)){const w=N(o,p,"id");d(w),w||a(it(t,p,"id",{"unique?":!0}));for(const T of Object.keys(g)){const m=N(o,p,T);if(d(m),oo.has(h)&&(m||a(it(t,p,T,T==="id"?{"unique?":!0}:null))),so.has(h)){const S=we(o,p,T);!m&&!S&&a(tr(t,p,T)),d(S)}}}}return[o,u]}function lo(e,t){const r=(Array.isArray(t)?t:[t]).flatMap(a=>Ns(a)),[i,s]=fo(e,r),o=Object.assign(Object.assign({},e),{attrs:i}),u=r.flatMap(a=>Xs(o,a));return[...s,...u]}var nr=function(e,t,n,r){function i(s){return s instanceof n?s:new n(function(o){o(s)})}return new(n||(n=Promise))(function(s,o){function u(c){try{d(r.next(c))}catch(f){o(f)}}function a(c){try{d(r.throw(c))}catch(f){o(f)}}function d(c){c.done?s(c.value):i(c.value).then(u,a)}d((r=r.apply(e,t||[])).next())})};class rr{constructor(t){this.dbName=t,this._storeName="kv",this._dbPromise=this._init()}_init(){return new Promise((t,n)=>{const r=indexedDB.open(this.dbName,1);r.onerror=i=>{n(i)},r.onsuccess=i=>{const s=i.target;t(s.result)},r.onupgradeneeded=i=>{i.target.result.createObjectStore(this._storeName)}})}getItem(t){return nr(this,void 0,void 0,function*(){const n=yield this._dbPromise;return new Promise((r,i)=>{const u=n.transaction([this._storeName],"readonly").objectStore(this._storeName).get(t);u.onerror=a=>{i(a)},u.onsuccess=a=>{u.result?r(u.result):r(null)}})})}setItem(t,n){return nr(this,void 0,void 0,function*(){const r=yield this._dbPromise;return new Promise((i,s)=>{const a=r.transaction([this._storeName],"readwrite").objectStore(this._storeName).put(n,t);a.onerror=d=>{s(d)},a.onsuccess=d=>{i()}})})}}var ho=function(e,t,n,r){function i(s){return s instanceof n?s:new n(function(o){o(s)})}return new(n||(n=Promise))(function(s,o){function u(c){try{d(r.next(c))}catch(f){o(f)}}function a(c){try{d(r.throw(c))}catch(f){o(f)}}function d(c){c.done?s(c.value):i(c.value).then(u,a)}d((r=r.apply(e,t||[])).next())})};class ir{static getIsOnline(){return ho(this,void 0,void 0,function*(){return navigator.onLine})}static listen(t){const n=()=>{t(!0)},r=()=>{t(!1)};return addEventListener("online",n),addEventListener("offline",r),()=>{removeEventListener("online",n),removeEventListener("offline",r)}}}class je extends Error{constructor(t,n){super(t),this.hint=n;const r=new.target.prototype;Object.setPrototypeOf&&Object.setPrototypeOf(this,r),Error.captureStackTrace&&Error.captureStackTrace(this,je),this.name="InstantError"}get[Symbol.toStringTag](){return"InstantError"}}var po=function(e,t,n,r){function i(s){return s instanceof n?s:new n(function(o){o(s)})}return new(n||(n=Promise))(function(s,o){function u(c){try{d(r.next(c))}catch(f){o(f)}}function a(c){try{d(r.throw(c))}catch(f){o(f)}}function d(c){c.done?s(c.value):i(c.value).then(u,a)}d((r=r.apply(e,t||[])).next())})};class st extends je{constructor(t){var n;const r=((n=t.body)===null||n===void 0?void 0:n.message)||`API Error (${t.status})`;super(r,t.body.hint);const i=new.target.prototype;Object.setPrototypeOf&&Object.setPrototypeOf(this,i),Error.captureStackTrace&&Error.captureStackTrace(this,st),this.name="InstantAPIError",this.status=t.status,this.body=t.body}get[Symbol.toStringTag](){return"InstantAPIError"}}function oe(e,t){return po(this,void 0,void 0,function*(){const n=yield fetch(e,t),r=yield n.json();return n.status===200?Promise.resolve(r):Promise.reject(new st({status:n.status,body:r}))})}var Pe=function(e,t,n,r){function i(s){return s instanceof n?s:new n(function(o){o(s)})}return new(n||(n=Promise))(function(s,o){function u(c){try{d(r.next(c))}catch(f){o(f)}}function a(c){try{d(r.throw(c))}catch(f){o(f)}}function d(c){c.done?s(c.value):i(c.value).then(u,a)}d((r=r.apply(e,t||[])).next())})};function yo({apiURI:e,appId:t,email:n}){return oe(`${e}/runtime/auth/send_magic_code`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({"app-id":t,email:n})})}function bo(e){return Pe(this,arguments,void 0,function*({apiURI:t,appId:n,email:r,code:i,refreshToken:s}){return yield oe(`${t}/runtime/auth/verify_magic_code`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(Object.assign({"app-id":n,email:r,code:i},s?{"refresh-token":s}:{}))})})}function _o(e){return Pe(this,arguments,void 0,function*({apiURI:t,appId:n,refreshToken:r}){return yield oe(`${t}/runtime/auth/verify_refresh_token`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({"app-id":n,"refresh-token":r})})})}function go(e){return Pe(this,arguments,void 0,function*({apiURI:t,appId:n}){return yield oe(`${t}/runtime/auth/sign_in_guest`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({"app-id":n})})})}function sr(e){return Pe(this,arguments,void 0,function*({apiURI:t,appId:n,code:r,codeVerifier:i,refreshToken:s}){return yield oe(`${t}/runtime/oauth/token`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({app_id:n,code:r,code_verifier:i,refresh_token:s})})})}function To(e){return Pe(this,arguments,void 0,function*({apiURI:t,appId:n,nonce:r,idToken:i,clientName:s,refreshToken:o}){return yield oe(`${t}/runtime/oauth/id_token`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({app_id:n,nonce:r,id_token:i,client_name:s,refresh_token:o})})})}function wo(e){return Pe(this,arguments,void 0,function*({apiURI:t,appId:n,refreshToken:r}){return yield oe(`${t}/runtime/signout`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({app_id:n,refresh_token:r})})})}var We=function(e,t,n,r){function i(s){return s instanceof n?s:new n(function(o){o(s)})}return new(n||(n=Promise))(function(s,o){function u(c){try{d(r.next(c))}catch(f){o(f)}}function a(c){try{d(r.throw(c))}catch(f){o(f)}}function d(c){c.done?s(c.value):i(c.value).then(u,a)}d((r=r.apply(e,t||[])).next())})};function mo(e){return We(this,arguments,void 0,function*({apiURI:t,appId:n,path:r,file:i,refreshToken:s,contentType:o,contentDisposition:u}){const a={app_id:n,path:r,authorization:`Bearer ${s}`,"content-type":o||i.type};return u&&(a["content-disposition"]=u),yield oe(`${t}/storage/upload`,{method:"PUT",headers:a,body:i})})}function So(e){return We(this,arguments,void 0,function*({apiURI:t,appId:n,path:r,refreshToken:i}){const{data:s}=yield oe(`${t}/storage/files?app_id=${n}&filename=${encodeURIComponent(r)}`,{method:"DELETE",headers:{"content-type":"application/json",authorization:`Bearer ${i}`}});return s})}function vo(e){return We(this,arguments,void 0,function*({apiURI:t,appId:n,fileName:r,refreshToken:i,metadata:s={}}){const{data:o}=yield oe(`${t}/storage/signed-upload-url`,{method:"POST",headers:{"content-type":"application/json",authorization:`Bearer ${i}`},body:JSON.stringify({app_id:n,filename:r})});return o})}function Oo(e,t){return We(this,void 0,void 0,function*(){return(yield fetch(e,{method:"PUT",body:t,headers:{"Content-Type":t.type}})).ok})}function Eo(e){return We(this,arguments,void 0,function*({apiURI:t,appId:n,path:r,refreshToken:i}){const{data:s}=yield oe(`${t}/storage/signed-download-url?app_id=${n}&filename=${encodeURIComponent(r)}`,{method:"GET",headers:{"content-type":"application/json",authorization:`Bearer ${i}`}});return s})}let Jt=!1,or=!1,ur=!1;typeof window<"u"&&typeof window.localStorage<"u"&&(Jt=!!window.localStorage.getItem("devBackend"),or=!!window.localStorage.getItem("__instantLogging"),ur=!!window.localStorage.getItem("__devtoolLocalDash"));function ar(e,t){if(!t)return e;const n={};return t.forEach(r=>{n[r]=e[r]}),n}function Ao(e,t,n){var r,i;const s={peers:{}};if(t&&"user"in t?t.user:!0){const u=ar((r=e.user)!==null&&r!==void 0?r:{},t==null?void 0:t.keys);s.user=Object.assign(Object.assign({},u),{peerId:n})}for(const u of Object.keys((i=e.peers)!==null&&i!==void 0?i:{})){const a=(t==null?void 0:t.peers)===void 0,d=Array.isArray(t==null?void 0:t.peers)&&(t==null?void 0:t.peers.includes(u));if(a||d){const c=ar(e.peers[u],t==null?void 0:t.keys);s.peers[u]=Object.assign(Object.assign({},c),{peerId:u})}}return s}function Co(e,t){if(e.isLoading!==t.isLoading||e.error!==t.error||(e.user||t.user)&&(!e.user||!t.user||!jn(e.user,t.user))||!Cn(e.peers,t.peers))return!0;for(const r of Object.keys(e.peers))if(!jn(e.peers[r],t.peers[r]))return!0;return!1}class cr{constructor(){this.promise=new Promise((t,n)=>{this._resolve=t,this._reject=n})}resolve(t){this._resolve(t)}reject(t){this._reject(t)}}var ze=function(e,t,n,r){function i(s){return s instanceof n?s:new n(function(o){o(s)})}return new(n||(n=Promise))(function(s,o){function u(c){try{d(r.next(c))}catch(f){o(f)}}function a(c){try{d(r.throw(c))}catch(f){o(f)}}function d(c){c.done?s(c.value):i(c.value).then(u,a)}d((r=r.apply(e,t||[])).next())})};function jo(e,t){typeof requestIdleCallback>"u"?e():requestIdleCallback(e,{timeout:t})}class dr{constructor(t,n,r,i,s=d=>d,o=d=>d,u=100,a=1e3){this._subs=[],this._nextSave=null,this._persister=t,this._key=n,this._onMerge=i,this._loadedCbs=[],this._isLoading=!0,this.currentValue=r,this.serialize=s,this.parse=o,this._saveThrottleMs=u,this._pendingSaveCbs=[],this._version=0,this._idleCallbackMaxWaitMs=a,this._load()}_getFromStorage(){return ze(this,void 0,void 0,function*(){try{return this.parse(yield this._persister.getItem(this._key))}catch(t){return console.error(`Unable to read from storage for key=${this._key}`,t),null}})}_load(){return ze(this,void 0,void 0,function*(){const t=yield this._getFromStorage();this._isLoading=!1,this._onMerge(t,this.currentValue);for(const n of this._loadedCbs)n()})}waitForLoaded(){return ze(this,void 0,void 0,function*(){if(!this._isLoading)return;yield new Promise(n=>{this._loadedCbs.push(n)})})}isLoading(){return this._isLoading}version(){return this._version}waitForSync(){return ze(this,void 0,void 0,function*(){if(!this._nextSave)return;yield new Promise(n=>{this._pendingSaveCbs.push(n)})})}_writeToStorage(){this._persister.setItem(this._key,this.serialize(this.currentValue));for(const t of this._pendingSaveCbs)t();this._pendingSaveCbs.length=0}flush(){return ze(this,void 0,void 0,function*(){this._nextSave&&(clearTimeout(this._nextSave),this._writeToStorage())})}_enqueuePersist(t){if(this._nextSave){t&&this._pendingSaveCbs.push(t);return}this._nextSave=setTimeout(()=>{jo(()=>{this._nextSave=null,this._writeToStorage()},this._idleCallbackMaxWaitMs)},this._saveThrottleMs)}set(t,n){this._version++,this.currentValue=t(this.currentValue),this._isLoading?this._loadedCbs.push(()=>this._enqueuePersist(n)):this._enqueuePersist(n);for(const r of this._subs)r(this.currentValue)}subscribe(t){return this._subs.push(t),t(this.currentValue),()=>{this._subs=this._subs.filter(n=>n!==t)}}}function fr(e,t=[]){e.forEach(n=>{const{data:r}=n,{"datalog-result":i}=r,{"join-rows":s}=i;for(const o of s)for(const u of o)t.push(u);fr(n["child-nodes"],t)})}function lr(e){const t=[];return fr(e,t),t}function hr(e){return Object.values(e.links).reduce((t,n)=>{var r,i,s,o;return(r=t[s=n.forward.on])!==null&&r!==void 0||(t[s]={}),t[n.forward.on][n.forward.label]={isForward:!0,isSingular:n.forward.has==="one",link:n},(i=t[o=n.reverse.on])!==null&&i!==void 0||(t[o]={}),t[n.reverse.on][n.reverse.label]={isForward:!1,isSingular:n.reverse.has==="one",link:n},t},{})}const pr="v0.22.36-experimental.drewh-cookie-sync-endpoint.18891755335.1";function Po(e,t){return{info:e?(...n)=>console.info(...n,t()):()=>{},debug:e?(...n)=>console.debug(...n,t()):()=>{},error:e?(...n)=>console.error(...n,t()):()=>{}}}class he{constructor(t,n,r,i={indexed:!1,unique:!1}){this.valueType=t,this.required=n,this.isIndexed=r,this.config=i,this.metadata={}}clientRequired(){return new he(this.valueType,!1,this.isIndexed,this.config)}optional(){return new he(this.valueType,!1,this.isIndexed,this.config)}unique(){return new he(this.valueType,this.required,this.isIndexed,Object.assign(Object.assign({},this.config),{unique:!0}))}indexed(){return new he(this.valueType,this.required,!0,Object.assign(Object.assign({},this.config),{indexed:!0}))}}class M extends Error{constructor(t,n){const r=n?`At path '${n}': ${t}`:t;super(r),this.name="QueryValidationError"}}const yr=["where","order","limit","last","first","offset","after","before","fields","aggregate"],ko=e=>e.valueType||"unknown",br=(e,t,n=!1)=>{if(n||e==null)return!0;switch(t){case"string":return typeof e=="string";case"number":return typeof e=="number"&&!isNaN(e);case"boolean":return typeof e=="boolean";case"date":return e instanceof Date||typeof e=="string"||typeof e=="number";default:return!0}},Io=(e,t,n,r,i,s,o)=>{const u=s.valueType==="json",a=(d,c,f)=>{if(!br(f,c,u))throw new M(`Invalid value for operator '${d}' on attribute '${r}' in entity '${i}'. Expected ${c}, but received: ${typeof f}`,o)};switch(e){case"in":case"$in":if(!Array.isArray(t))throw new M(`Operator '${e}' for attribute '${r}' in entity '${i}' must be an array, but received: ${typeof t}`,o);for(const d of t)a(e,n,d);break;case"$not":case"$ne":case"$gt":case"$lt":case"$gte":case"$lte":a(e,n,t);break;case"$like":case"$ilike":if(a(e,"string",t),e==="$ilike"&&!s.isIndexed)throw new M(`Operator '${e}' can only be used with indexed attributes, but '${r}' in entity '${i}' is not indexed`,o);break;case"$isNull":a(e,"boolean",t);break;default:throw new M(`Unknown operator '${e}' for attribute '${r}' in entity '${i}'`,o)}},ke=(e,t,n,r,i)=>{const s=ko(n),o=n.valueType==="json";if(typeof e=="object"&&e!==null&&!Array.isArray(e)){if(o)return;const a=e;for(const[d,c]of Object.entries(a))Io(d,c,s,t,r,n,`${i}.${d}`)}else if(!br(e,s,o))throw new M(`Invalid value for attribute '${t}' in entity '${r}'. Expected ${s}, but received: ${typeof e}`,i)},Mo=(e,t,n,r,i)=>{const s=e.split(".");if(s.length<2)throw new M(`Invalid dot notation path '${e}'. Must contain at least one dot.`,i);let o=n;for(let c=0;c<s.length-1;c++){const f=s[c],h=r.entities[o];if(!h)throw new M(`Entity '${o}' does not exist in schema while traversing dot notation path '${e}'.`,i);const p=h.links[f];if(!p){const b=Object.keys(h.links);throw new M(`Link '${f}' does not exist on entity '${o}' in dot notation path '${e}'. Available links: ${b.length>0?b.join(", "):"none"}`,i)}o=p.entityName}const u=s[s.length-1],a=r.entities[o];if(!a)throw new M(`Target entity '${o}' does not exist in schema for dot notation path '${e}'.`,i);if(u==="id"){if(typeof t=="string"&&!Ae(t))throw new M(`Invalid value for id field in entity '${o}'. Expected a UUID, but received: ${t}`,i);ke(t,e,new he("string",!1,!0),n,i);return}const d=a.attrs[u];if(Object.keys(a.links).includes(u)){if(typeof t=="string"&&!Ae(t))throw new M(`Invalid value for link '${u}' in entity '${o}'. Expected a UUID, but received: ${t}`,i);ke(t,e,new he("string",!1,!0),n,i);return}if(!d){const c=Object.keys(a.attrs);throw new M(`Attribute '${u}' does not exist on entity '${o}' in dot notation path '${e}'. Available attributes: ${c.length>0?c.join(", ")+", id":"id"}`,i)}ke(t,e,d,n,i)},_r=(e,t,n,r)=>{for(const[i,s]of Object.entries(e)){if(i==="or"||i==="and"){if(Array.isArray(s))for(const d of s)typeof d=="object"&&d!==null&&_r(d,t,n,`${r}.${i}[${d}]`);continue}if(i==="id"){ke(s,"id",new he("string",!1,!0),t,`${r}.id`);continue}if(i.includes(".")){Mo(i,s,t,n,`${r}.${i}`);continue}const o=n.entities[t];if(!o)continue;const u=o.attrs[i],a=o.links[i];if(!u&&!a){const d=Object.keys(o.attrs),c=Object.keys(o.links);throw new M(`Attribute or link '${i}' does not exist on entity '${t}'. Available attributes: ${d.length>0?d.join(", "):"none"}. Available links: ${c.length>0?c.join(", "):"none"}`,`${r}.${i}`)}if(u)ke(s,i,u,t,`${r}.${i}`);else if(a){if(typeof s=="string"&&!Ae(s))throw new M(`Invalid value for link '${i}' in entity '${t}'. Expected a UUID, but received: ${s}`,`${r}.${i}`);const d=new he("string",!1,!0);ke(s,i,d,t,`${r}.${i}`)}}},Ro=(e,t,n,r,i=0)=>{for(const o of Object.keys(e))if(!yr.includes(o))throw new M(`Invalid query parameter '${o}' in $ object. Valid parameters are: ${yr.join(", ")}. Found: ${o}`,r);const s=["limit","offset","before","after","first","last"];for(const o of s)if(e[o]!==void 0&&i>0)throw new M(`'${o}' can only be used on top-level namespaces. It cannot be used in nested queries.`,r);if(e.where&&n){if(typeof e.where!="object"||e.where===null)throw new M(`'where' clause must be an object in entity '${t}', but received: ${typeof e.where}`,r?`${r}.where`:void 0);_r(e.where,t,n,r?`${r}.where`:"where")}},gr=(e,t,n,r,i=0)=>{var s;if(!e||typeof e!="object")throw new M(`Query part for entity '${t}' must be an object, but received: ${typeof e}`,r);for(const o of Object.keys(e))if(o!=="$"){if(n&&!(o in n.entities[t].links)){const a=Object.keys(n.entities[t].links);throw new M(`Link '${o}' does not exist on entity '${t}'. Available links: ${a.length>0?a.join(", "):"none"}`,`${r}.${o}`)}const u=e[o];if(typeof u=="object"&&u!==null){const a=(s=n==null?void 0:n.entities[t].links[o])===null||s===void 0?void 0:s.entityName;a&&gr(u,a,n,`${r}.${o}`,i+1)}}else{const u=e[o];if(typeof u!="object"||u===null)throw new M(`Query parameter '$' must be an object in entity '${t}', but received: ${typeof u}`,`${r}.$`);Ro(u,t,n,`${r}.$`,i)}},Tr=(e,t)=>{if(typeof e!="object"||e===null)throw new M(`Query must be an object, but received: ${typeof e}${e===null?" (null)":""}`);if(Array.isArray(e))throw new M(`Query must be an object, but received: ${typeof e}`);const n=e;for(const r of Object.keys(n)){if(Array.isArray(e[r]))throw new M(`Query keys must be strings, but found key of type: ${typeof r}`,r);if(typeof r!="string")throw new M(`Query keys must be strings, but found key of type: ${typeof r}`,r);if(r!=="$$ruleParams"){if(t&&!t.entities[r]){const i=Object.keys(t.entities);throw new M(`Entity '${r}' does not exist in schema. Available entities: ${i.length>0?i.join(", "):"none"}`,r)}gr(n[r],r,t,r,0)}}},wr=e=>typeof e!="string"?!1:rt(e)?!0:Ae(e);class ne extends Error{constructor(t){super(t),this.name="TransactionValidationError"}}const mr=e=>e.length>0?e.join(", "):"none",Do=(e,t)=>new ne(`Entity '${e}' does not exist in schema. Available entities: ${mr(t)}`),Sr={string:e=>typeof e=="string",number:e=>typeof e=="number"&&!isNaN(e),boolean:e=>typeof e=="boolean",date:e=>e instanceof Date||typeof e=="string"||typeof e=="number",json:()=>!0},xo=(e,t)=>{var n,r;return e==null?!0:(r=(n=Sr[t.valueType])===null||n===void 0?void 0:n.call(Sr,e))!==null&&r!==void 0?r:!1},vr=(e,t)=>{const n=t.entities[e];if(!n)throw Do(e,Object.keys(t.entities));return n},Zt=(e,t,n)=>{const r=vr(e,n);if(typeof t!="object"||t===null)throw new ne(`Arguments for data operation on entity '${e}' must be an object, but received: ${typeof t}`);for(const[i,s]of Object.entries(t)){if(i==="id")continue;const o=r.attrs[i];if(o&&!xo(s,o))throw new ne(`Invalid value for attribute '${i}' in entity '${e}'. Expected ${o.valueType}, but received: ${typeof s}`)}},Or=(e,t,n)=>{const r=vr(e,n);if(typeof t!="object"||t===null)throw new ne(`Arguments for link operation on entity '${e}' must be an object, but received: ${typeof t}`);for(const[i,s]of Object.entries(t)){if(!r.links[i]){const u=Object.keys(r.links);throw new ne(`Link '${i}' does not exist on entity '${e}'. Available links: ${mr(u)}`)}if(s!=null){if(Array.isArray(s)){for(const u of s)if(!wr(u))throw new ne(`Invalid entity ID in link '${i}' for entity '${e}'. Expected a UUID or a lookup, but received: ${u}`)}else if(!wr(s))throw new ne(`Invalid UUID in link '${i}' for entity '${e}'. Expected a UUID, but received: ${s}`)}}},$o={create:Zt,update:Zt,merge:Zt,link:Or,unlink:Or,delete:()=>{}},Uo=(e,t)=>{if(!t)return;const[n,r,i,s]=e;if(!Array.isArray(i)&&!Ae(i))throw new ne(`Invalid id for entity '${r}'. Expected a UUID, but received: ${i}`);if(typeof r!="string")throw new ne(`Entity name must be a string, but received: ${typeof r}`);const o=$o[n];o&&s!==void 0&&o(r,s,t)},Lo=(e,t)=>{const n=Array.isArray(e)?e:[e];for(const r of n){if(!r||typeof r!="object")throw new ne(`Transaction chunk must be an object, but received: ${typeof r}`);if(!Array.isArray(r.__ops))throw new ne(`Transaction chunk must have __ops array, but received: ${typeof r.__ops}`);for(const i of r.__ops){if(!Array.isArray(i))throw new ne(`Transaction operation must be an array, but received: ${typeof i}`);Uo(i,t)}}};var Er=function(e,t,n,r){function i(s){return s instanceof n?s:new n(function(o){o(s)})}return new(n||(n=Promise))(function(s,o){function u(c){try{d(r.next(c))}catch(f){o(f)}}function a(c){try{d(r.throw(c))}catch(f){o(f)}}function d(c){c.done?s(c.value):i(c.value).then(u,a)}d((r=r.apply(e,t||[])).next())})};let Ar=0;class Cr{constructor(t){this.type="ws",this.id=`${this.type}_${Ar++}`,this.conn=new WebSocket(t),this.conn.onopen=n=>{this.onopen&&this.onopen({target:this})},this.conn.onmessage=n=>{this.onmessage&&this.onmessage({target:this,message:JSON.parse(n.data.toString())})},this.conn.onclose=n=>{this.onclose&&this.onclose({target:this})},this.conn.onerror=n=>{this.onerror&&this.onerror({target:this})}}close(){this.conn.close()}isOpen(){return this.conn.readyState===WebSocket.OPEN}isConnecting(){return this.conn.readyState===WebSocket.CONNECTING}send(t){return this.conn.send(JSON.stringify(t))}}class Fo{constructor(t,n){this.type="sse",this.initParams=null,this.sendQueue=[],this.closeFired=!1,this.sseInitTimeout=null,this.id=`${this.type}_${Ar++}`,this.url=n,this.ES=t,this.conn=new t(n),this.sseInitTimeout=setTimeout(()=>{this.initParams||this.handleError()},1e4),this.conn.onmessage=r=>{const i=JSON.parse(r.data);if(i.op==="sse-init"){this.initParams={machineId:i["machine-id"],sessionId:i["session-id"],sseToken:i["sse-token"]},this.onopen&&this.onopen({target:this}),clearTimeout(this.sseInitTimeout);return}this.onmessage&&this.onmessage({target:this,message:i})},this.conn.onerror=r=>{this.handleError()}}handleError(){try{this.onerror&&this.onerror({target:this})}finally{this.handleClose()}}handleClose(){this.conn.close(),this.onclose&&!this.closeFired&&(this.closeFired=!0,this.onclose({target:this}))}postMessages(t){return Er(this,void 0,void 0,function*(){try{(yield fetch(this.url,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({machine_id:this.initParams.machineId,session_id:this.initParams.sessionId,sse_token:this.initParams.sseToken,messages:t})})).ok||this.handleError()}catch{this.handleError()}})}flushQueue(){return Er(this,void 0,void 0,function*(){if(this.sendPromise||!this.sendQueue.length)return;const t=this.sendQueue;this.sendQueue=[];const n=this.postMessages(t);this.sendPromise=n,n.then(()=>{this.sendPromise=null,this.flushQueue()})})}send(t){if(!this.isOpen()||!this.initParams)throw this.isConnecting()?new Error("Failed to execute 'send' on 'EventSource': Still in CONNECTING state."):this.conn.readyState===this.ES.CLOSED?new Error("EventSource is already in CLOSING or CLOSED state."):new Error("EventSource is in invalid state.");this.sendQueue.push(t),this.flushQueue()}isOpen(){return this.conn.readyState===this.ES.OPEN&&this.initParams!==null}isConnecting(){return this.conn.readyState===this.ES.CONNECTING||this.conn.readyState===this.ES.OPEN&&this.initParams===null}close(){this.handleClose()}}var D=function(e,t,n,r){function i(s){return s instanceof n?s:new n(function(o){o(s)})}return new(n||(n=Promise))(function(s,o){function u(c){try{d(r.next(c))}catch(f){o(f)}}function a(c){try{d(r.throw(c))}catch(f){o(f)}}function d(c){c.done?s(c.value):i(c.value).then(u,a)}d((r=r.apply(e,t||[])).next())})},No=function(e,t){var n={};for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&t.indexOf(r)<0&&(n[r]=e[r]);if(e!=null&&typeof Object.getOwnPropertySymbols=="function")for(var i=0,r=Object.getOwnPropertySymbols(e);i<r.length;i++)t.indexOf(r[i])<0&&Object.prototype.propertyIsEnumerable.call(e,r[i])&&(n[r[i]]=e[r[i]]);return n};const pe={CONNECTING:"connecting",OPENED:"opened",AUTHENTICATED:"authenticated",CLOSED:"closed",ERRORED:"errored"},Vo=3e4,Wo=3e4,zo=200,Ko={apiURI:"https://api.instantdb.com",websocketURI:"wss://api.instantdb.com/runtime/session"},Xt="_instant_oauth_redirect",en="currentUser";function qo({transportType:e,appId:t,apiURI:n,wsURI:r,EventSourceImpl:i}){if(!i)return new Cr(`${r}?app_id=${t}`);switch(e){case"ws":return new Cr(`${r}?app_id=${t}`);case"sse":return new Fo(i,`${n}/runtime/sse?app_id=${t}`);default:throw new Error("Unknown transport type "+e)}}function Bo(){return typeof window<"u"||typeof chrome<"u"}const jr={"set-presence":!0,"set-presence-ok":!0,"refresh-presence":!0,"patch-presence":!0};function Qo(e,t){var n;const r=typeof e=="string"?JSON.parse(e):e;for(const i in r){const s=r[i];if(!((n=s==null?void 0:s.result)===null||n===void 0)&&n.store){const o=s.result.store;s.result.store=ji(Object.assign(Object.assign({},o),{useDateObjects:t}))}}return r}function Go(e){var t;const n={};for(const r in e){const i=e[r],s=Object.assign({},i);!((t=i.result)===null||t===void 0)&&t.store&&(s.result=Object.assign(Object.assign({},i.result),{store:Ci(i.result.store)})),n[r]=s}return n}function Pr(e){return[...e].sort((t,n)=>{const[r,i]=t,[s,o]=n,u=i.order||0,a=o.order||0;return u==a?r<s?-1:r>s?1:0:u-a})}class Yo{constructor(t,n=rr,r=ir,i,s){var o,u,a;if(this._isOnline=!0,this._isShutdown=!1,this.status=pe.CONNECTING,this.queryCbs={},this.queryOnceDfds={},this.authCbs=[],this.attrsCbs=[],this.mutationErrorCbs=[],this.connectionStatusCbs=[],this.mutationDeferredStore=new Map,this._reconnectTimeoutId=null,this._reconnectTimeoutMs=0,this._transportType="ws",this._wsOk=null,this._localIdPromises={},this._errorMessage=null,this._oauthCallbackResponse=null,this._linkIndex=null,this._rooms={},this._roomsPendingLeave={},this._presence={},this._broadcastQueue=[],this._broadcastSubs={},this._currentUserCached={isLoading:!0,error:void 0,user:void 0},this._beforeUnloadCbs=[],this._dataForQueryCache={},this._inFlightMutationEventIds=new Set,this._onMergeQuerySubs=(d,c)=>{const f=d||{},h=Object.assign({},c);Object.entries(c).forEach(([b,g])=>{var w;const T=(w=f==null?void 0:f[b])===null||w===void 0?void 0:w.result,m=g.result;T&&!m&&(h[b].result=T)}),Object.keys(f).filter(b=>!c[b]).sort((b,g)=>{var w,T;const m=((w=f[b])===null||w===void 0?void 0:w.lastAccessed)||0;return(((T=f[g])===null||T===void 0?void 0:T.lastAccessed)||0)-m}).slice(0,this.queryCacheLimit).forEach(b=>{h[b]=f[b]}),this.querySubs.set(b=>h),this.loadedNotifyAll()},this._onMergePendingMutations=(d,c)=>{const f=new Map([...d.entries(),...c.entries()]);this.pendingMutations.set(p=>f),this.loadedNotifyAll(),this._rewriteMutationsSorted(this.attrs,d).forEach(([p,b])=>{!c.has(p)&&!b["tx-id"]&&this._sendMutation(p,b)})},this.getPreviousResult=d=>{const c=B(d);return this.dataForQuery(c)},this.notifyOne=d=>{var c,f;const h=(c=this.queryCbs[d])!==null&&c!==void 0?c:[],p=(f=this._dataForQueryCache[d])===null||f===void 0?void 0:f.data,b=this.dataForQuery(d);b&&(Je(b,p)||h.forEach(g=>g.cb(b)))},this.notifyOneQueryOnce=d=>{var c;const f=(c=this.queryOnceDfds[d])!==null&&c!==void 0?c:[],h=this.dataForQuery(d);f.forEach(p=>{this._completeQueryOnce(p.q,d,p.dfd),p.dfd.resolve(h)})},this.notifyQueryError=(d,c)=>{(this.queryCbs[d]||[]).forEach(h=>h.cb({error:c}))},this.pushTx=d=>{this.config.disableValidation||Lo(d,this.config.schema);try{const c=lo({attrs:this.optimisticAttrs(),schema:this.config.schema,stores:Object.values(this.querySubs.currentValue).map(f=>{var h;return(h=f==null?void 0:f.result)===null||h===void 0?void 0:h.store}),useDateObjects:this.config.useDateObjects},d);return this.pushOps(c)}catch(c){return this.pushOps([],c)}},this.pushOps=(d,c)=>{const f=V(),h=[...this.pendingMutations.currentValue.values()],p=Math.max(0,...h.map(w=>w.order||0))+1,b={op:"transact","tx-steps":d,created:Date.now(),error:c,order:p};this.pendingMutations.set(w=>(w.set(f,b),w));const g=new cr;return this.mutationDeferredStore.set(f,g),this._sendMutation(f,b),this.notifyAll(),g.promise},this._transportOnOpen=d=>{const c=d.target;if(this._transport!==c){this._log.info("[socket][open]",c.id,"skip; this is no longer the current transport");return}this._log.info("[socket][open]",this._transport.id),this._setStatus(pe.OPENED),this.getCurrentUser().then(f=>{var h;this._trySend(V(),{op:"init","app-id":this.config.appId,"refresh-token":(h=f.user)===null||h===void 0?void 0:h.refresh_token,versions:this.versions,"__admin-token":this.config.__adminToken})}).catch(f=>{this._log.error("[socket][error]",c.id,f)})},this._transportOnMessage=d=>{const c=d.target,f=d.message;if(this._transport!==c){this._log.info("[socket][message]",c.id,f,"skip; this is no longer the current transport");return}!this._wsOk&&c.type==="ws"&&(this._wsOk=!0),this._transportType="ws",this._handleReceive(c.id,d.message)},this._transportOnError=d=>{const c=d.target;if(this._transport!==c){this._log.info("[socket][error]",c.id,"skip; this is no longer the current transport");return}this._log.error("[socket][error]",c.id,d)},this._scheduleReconnect=()=>{!this._wsOk&&this._transportType!=="sse"&&(this._transportType="sse",this._reconnectTimeoutMs=0),setTimeout(()=>{if(this._reconnectTimeoutMs=Math.min(this._reconnectTimeoutMs+1e3,1e4),!this._isOnline){this._log.info("[socket][close]",this._transport.id,"we are offline, no need to start socket");return}this._startSocket()},this._reconnectTimeoutMs)},this._transportOnClose=d=>{const c=d.target;if(this._transport!==c){this._log.info("[socket][close]",c.id,"skip; this is no longer the current transport");return}this._setStatus(pe.CLOSED);for(const f of Object.values(this._rooms))f.isConnected=!1;if(this._isShutdown){this._log.info("[socket][close]",c.id,"Reactor has been shut down and will not reconnect");return}this._log.info("[socket][close]",c.id,"schedule reconnect, ms =",this._reconnectTimeoutMs),this._scheduleReconnect()},this._EventSource=s,this.config=Object.assign(Object.assign({},Ko),t),this.queryCacheLimit=(o=this.config.queryCacheLimit)!==null&&o!==void 0?o:10,this._pendingTxCleanupTimeout=(u=this.config.pendingTxCleanupTimeout)!==null&&u!==void 0?u:Wo,this._pendingMutationCleanupThreshold=(a=this.config.pendingMutationCleanupThreshold)!==null&&a!==void 0?a:zo,this._log=Po(t.verbose||Jt||or,()=>this._reactorStats()),this.versions=Object.assign(Object.assign({},i||{}),{"@instantdb/core":pr}),this.config.schema&&(this._linkIndex=hr(this.config.schema)),!!Bo()){if(!t.appId)throw new Error("Instant must be initialized with an appId.");if(!Ae(t.appId))throw new Error(`Instant must be initialized with a valid appId. \`${t.appId}\` is not a valid uuid.`);typeof BroadcastChannel=="function"&&(this._broadcastChannel=new BroadcastChannel("@instantdb"),this._broadcastChannel.addEventListener("message",d=>D(this,void 0,void 0,function*(){var c;try{if(((c=d.data)===null||c===void 0?void 0:c.type)==="auth"){const f=yield this.getCurrentUser();this.updateUser(f.user)}}catch(f){this._log.error("[error] handle broadcast channel",f)}}))),this._initStorage(n),this._oauthCallbackResponse=this._oauthLoginInit(),this.getCurrentUser().then(d=>{this.syncUserToEndpoint(d.user)}),r.getIsOnline().then(d=>{this._isOnline=d,this._startSocket(),r.listen(c=>{c!==this._isOnline&&(this._log.info("[network] online =",c),this._isOnline=c,this._isOnline?this._startSocket():(this._log.info("Changing status from",this.status,"to",pe.CLOSED),this._setStatus(pe.CLOSED)))})}),typeof addEventListener<"u"&&(this._beforeUnload=this._beforeUnload.bind(this),addEventListener("beforeunload",this._beforeUnload))}}updateSchema(t){this.config=Object.assign(Object.assign({},this.config),{schema:t,cardinalityInference:!!t}),this._linkIndex=t?hr(this.config.schema):null}_reactorStats(){return{inFlightMutationCount:this._inFlightMutationEventIds.size,pendingMutationCount:this.pendingMutations.currentValue.size,transportType:this._transportType}}_initStorage(t){this._persister=new t(`instant_${this.config.appId}_5`),this.querySubs=new dr(this._persister,"querySubs",{},this._onMergeQuerySubs,Go,n=>Qo(n,this.config.useDateObjects)),this.pendingMutations=new dr(this._persister,"pendingMutations",new Map,this._onMergePendingMutations,n=>[...n.entries()],n=>new Map(typeof n=="string"?JSON.parse(n):n),100,100),this._beforeUnloadCbs.push(()=>{this.pendingMutations.flush(),this.querySubs.flush()})}_beforeUnload(){for(const t of this._beforeUnloadCbs)t()}_finishTransaction(t,n,r){const i=this.mutationDeferredStore.get(n);this.mutationDeferredStore.delete(n);const s=t!=="error"&&t!=="timeout";if(!i&&!s&&console.error("Mutation failed",Object.assign({status:t,eventId:n},r)),!!i)if(s)i.resolve({status:t,eventId:n});else if(r.type){const{status:o}=r,u=No(r,["status"]);i.reject(new st({body:u,status:o}))}else i.reject(new je(r.message,r.hint))}_setStatus(t,n){this.status=t,this._errorMessage=n,this.notifyConnectionStatusSubs(t)}_flushEnqueuedRoomData(t){var n,r;const i=(r=(n=this._presence[t])===null||n===void 0?void 0:n.result)===null||r===void 0?void 0:r.user,s=this._broadcastQueue[t];if(this._broadcastQueue[t]=[],i&&this._trySetPresence(t,i),s)for(const o of s){const{topic:u,roomType:a,data:d}=o;this._tryBroadcast(t,a,u,d)}}_handleReceive(t,n){var r,i,s,o,u,a;const d=!!this.config.schema&&("cardinalityInference"in this.config?!!this.config.cardinalityInference:!0);switch(jr[n.op]||this._log.info("[receive]",t,n.op,n),n.op){case"init-ok":this._setStatus(pe.AUTHENTICATED),this._reconnectTimeoutMs=0,this._setAttrs(n.attrs),this._flushPendingMessages(),this._sessionId=n["session-id"];for(const k of Object.keys(this._rooms)){const L=(i=(r=this._presence[k])===null||r===void 0?void 0:r.result)===null||i===void 0?void 0:i.user;this._tryJoinRoom(k,L)}break;case"add-query-exists":this.notifyOneQueryOnce(B(n.q));break;case"add-query-ok":const{q:c,result:f}=n,h=B(c),p=(o=(s=f==null?void 0:f[0])===null||s===void 0?void 0:s.data)===null||o===void 0?void 0:o["page-info"],b=(a=(u=f==null?void 0:f[0])===null||u===void 0?void 0:u.data)===null||a===void 0?void 0:a.aggregate,g=lr(f),w=Lt(this.attrs,g,d,this._linkIndex,this.config.useDateObjects);this.querySubs.set(k=>(k[h].result={store:w,pageInfo:p,aggregate:b,processedTxId:n["processed-tx-id"]},k)),this._cleanupPendingMutationsQueries(),this.notifyOne(h),this.notifyOneQueryOnce(h),this._cleanupPendingMutationsTimeout();break;case"refresh-ok":const{computations:T,attrs:m}=n,S=n["processed-tx-id"];m&&this._setAttrs(m),this._cleanupPendingMutationsTimeout();const K=this._rewriteMutations(this.attrs,this.pendingMutations.currentValue,S);K!==this.pendingMutations.currentValue&&this.pendingMutations.set(()=>K);const O=Pr(K.entries()),U=T.map(k=>{var L,H,J,ue;const ae=k["instaql-query"],te=k["instaql-result"],ct=B(ae),dt=lr(te),ft=Lt(this.attrs,dt,d,this._linkIndex,this.config.useDateObjects),lt=this._applyOptimisticUpdates(ft,O,S),ht=(H=(L=te==null?void 0:te[0])===null||L===void 0?void 0:L.data)===null||H===void 0?void 0:H["page-info"],sn=(ue=(J=te==null?void 0:te[0])===null||J===void 0?void 0:J.data)===null||ue===void 0?void 0:ue.aggregate;return{hash:ct,store:lt,pageInfo:ht,aggregate:sn}});U.forEach(({hash:k,store:L,pageInfo:H,aggregate:J})=>{this.querySubs.set(ue=>(ue[k].result={store:L,pageInfo:H,aggregate:J,processedTxId:S},ue))}),this._cleanupPendingMutationsQueries(),U.forEach(({hash:k})=>{this.notifyOne(k)});break;case"transact-ok":{const{"client-event-id":k,"tx-id":L}=n;this._inFlightMutationEventIds.delete(k);const J=this._rewriteMutations(this.attrs,this.pendingMutations.currentValue).get(k);if(!J)break;this.pendingMutations.set(ae=>(ae.set(k,Object.assign(Object.assign({},ae.get(k)),{"tx-id":L,confirmed:Date.now()})),ae));const ue=J["tx-steps"].filter(([ae,...te])=>ae==="add-attr").map(([ae,te])=>te).concat(Object.values(this.attrs));this._setAttrs(ue),this._finishTransaction("synced",k),this._cleanupPendingMutationsTimeout();break}case"patch-presence":{const k=n["room-id"];this._patchPresencePeers(k,n.edits),this._notifyPresenceSubs(k);break}case"refresh-presence":{const k=n["room-id"];this._setPresencePeers(k,n.data),this._notifyPresenceSubs(k);break}case"server-broadcast":const W=n["room-id"],ye=n.topic;this._notifyBroadcastSubs(W,ye,n);break;case"join-room-ok":const de=n["room-id"],Ke=this._rooms[de];if(!Ke){this._roomsPendingLeave[de]&&(this._tryLeaveRoom(de),delete this._roomsPendingLeave[de]);break}Ke.isConnected=!0,this._notifyPresenceSubs(de),this._flushEnqueuedRoomData(de);break;case"join-room-error":const ut=n["room-id"],at=this._rooms[ut];at&&(at.error=n.error),this._notifyPresenceSubs(ut);break;case"error":this._handleReceiveError(n);break}}_handleMutationError(t,n,r){const i=this.pendingMutations.currentValue.get(n);if(i&&(t!=="timeout"||!i["tx-id"])){this.pendingMutations.set(o=>(o.delete(n),o)),this._inFlightMutationEventIds.delete(n);const s={message:r.message,hint:r.hint};this.notifyAll(),this.notifyAttrsSubs(),this.notifyMutationErrorSubs(s),this._finishTransaction(t,n,r)}}_handleReceiveError(t){var n,r,i,s,o;console.log("error",t);const u=t["client-event-id"];this._inFlightMutationEventIds.delete(u);const a=this.pendingMutations.currentValue.get(u),d={message:t.message||"Uh-oh, something went wrong. Ping Joe & Stopa."};if(t.hint&&(d.hint=t.hint),a){this._handleMutationError("error",u,t);return}if(!((n=t["original-event"])===null||n===void 0)&&n.hasOwnProperty("q")&&((r=t["original-event"])===null||r===void 0?void 0:r.op)==="add-query"){const h=(i=t["original-event"])===null||i===void 0?void 0:i.q,p=B(h);this.notifyQueryError(B(h),d),this.notifyQueryOnceError(h,p,u,d);return}if(((s=t["original-event"])===null||s===void 0?void 0:s.op)==="init"){if(t.type==="record-not-found"&&((o=t.hint)===null||o===void 0?void 0:o["record-type"])==="app-user"){this.changeCurrentUser(null);return}this._setStatus(pe.ERRORED,d),this.notifyAll();return}const f=Object.assign({},t);delete f.message,delete f.hint,console.error(t.message,f),t.hint&&console.error(`This error comes with some debugging information. Here it is:
|
|
31
|
+
`,t.hint)}notifyQueryOnceError(t,n,r,i){var s;const o=(s=this.queryOnceDfds[n])===null||s===void 0?void 0:s.find(u=>u.eventId===r);o&&(o.dfd.reject(i),this._completeQueryOnce(t,n,o.dfd))}_setAttrs(t){this.attrs=t.reduce((n,r)=>(n[r.id]=r,n),{}),this.notifyAttrsSubs()}_startQuerySub(t,n){const r=V();return this.querySubs.set(i=>(i[n]=i[n]||{q:t,result:null,eventId:r},i[n].lastAccessed=Date.now(),i)),this._trySendAuthed(r,{op:"add-query",q:t}),r}subscribeQuery(t,n,r){var i;this.config.disableValidation||Tr(t,this.config.schema),r&&"ruleParams"in r&&(t=Object.assign({$$ruleParams:r.ruleParams},t));const s=B(t),o=this.getPreviousResult(t);return o&&n(o),this.queryCbs[s]=(i=this.queryCbs[s])!==null&&i!==void 0?i:[],this.queryCbs[s].push({q:t,cb:n}),this._startQuerySub(t,s),()=>{this._unsubQuery(t,s,n)}}queryOnce(t,n){var r;this.config.disableValidation||Tr(t,this.config.schema),n&&"ruleParams"in n&&(t=Object.assign({$$ruleParams:n.ruleParams},t));const i=new cr;if(!this._isOnline)return i.reject(new Error("We can't run `queryOnce`, because the device is offline.")),i.promise;if(!this.querySubs)return i.reject(new Error("We can't run `queryOnce` on the backend. Use adminAPI.query instead: https://www.instantdb.com/docs/backend#query")),i.promise;const s=B(t),o=this._startQuerySub(t,s);return this.queryOnceDfds[s]=(r=this.queryOnceDfds[s])!==null&&r!==void 0?r:[],this.queryOnceDfds[s].push({q:t,dfd:i,eventId:o}),setTimeout(()=>i.reject(new Error("Query timed out")),Vo),i.promise}_completeQueryOnce(t,n,r){this.queryOnceDfds[n]&&(this.queryOnceDfds[n]=this.queryOnceDfds[n].filter(i=>i.dfd!==r),this._cleanupQuery(t,n))}_unsubQuery(t,n,r){this.queryCbs[n]&&(this.queryCbs[n]=this.queryCbs[n].filter(i=>i.cb!==r),this._cleanupQuery(t,n))}_cleanupQuery(t,n){var r,i;!((r=this.queryCbs[n])===null||r===void 0)&&r.length||!((i=this.queryOnceDfds[n])===null||i===void 0)&&i.length||(delete this.queryCbs[n],delete this.queryOnceDfds[n],this._trySendAuthed(V(),{op:"remove-query",q:t}))}_rewriteMutations(t,n,r){if(!t)return n;const i=c=>{const[f,h,p]=c["forward-identity"];return N(t,h,p)},s=c=>{const[f,h,p]=c["forward-identity"];return we(t,h,p)},o={attrIdMap:{},refSwapAttrIds:new Set};let u=!1;const a=(c,f)=>{const h=[];for(const p of c){const[b]=p;if(b==="add-attr"){const[w,T]=p,m=i(T);if(m&&T.id!==m.id){o.attrIdMap[T.id]=m.id,u=!0;continue}if(T["value-type"]==="ref"){const S=s(T);if(S){o.attrIdMap[T.id]=S.id,o.refSwapAttrIds.add(T.id),u=!0;continue}}}if(r&&f&&r>=f&&b==="add-attr"||b==="update-attr"||b==="delete-attr"){u=!0;continue}const g=u?Vs(o,p):p;h.push(g)}return u?h:c},d=new Map;for(const[c,f]of n.entries())d.set(c,Object.assign(Object.assign({},f),{"tx-steps":a(f["tx-steps"],f["tx-id"])}));return u?d:n}_rewriteMutationsSorted(t,n){return Pr(this._rewriteMutations(t,n).entries())}optimisticAttrs(){var t;const n=[...this.pendingMutations.currentValue.values()].flatMap(u=>u["tx-steps"]),r=new Set(n.filter(([u,a])=>u==="delete-attr").map(([u,a])=>a)),i=[];for(const[u,a]of n)if(u==="add-attr")i.push(a);else if(u==="update-attr"&&a.id&&(!((t=this.attrs)===null||t===void 0)&&t[a.id])){const d=Object.assign(Object.assign({},this.attrs[a.id]),a);i.push(d)}const s=[...Object.values(this.attrs||{}),...i].filter(u=>!r.has(u.id));return Object.fromEntries(s.map(u=>[u.id,u]))}dataForQuery(t){const n=this._errorMessage;if(n)return{error:n};if(!this.querySubs||!this.pendingMutations)return;const r=this.querySubs.version(),i=this.querySubs.currentValue,s=this.pendingMutations.version(),o=this.pendingMutations.currentValue,{q:u,result:a}=i[t]||{};if(!a)return;const d=this._dataForQueryCache[t];if(d&&r===d.querySubVersion&&s===d.pendingMutationsVersion)return d.data;const{store:c,pageInfo:f,aggregate:h,processedTxId:p}=a,b=this._rewriteMutationsSorted(c.attrs,o),g=this._applyOptimisticUpdates(c,b,p),w=$s({store:g,pageInfo:f,aggregate:h},u);return this._dataForQueryCache[t]={querySubVersion:r,pendingMutationsVersion:s,data:w},w}_applyOptimisticUpdates(t,n,r){for(const[i,s]of n)(!s["tx-id"]||r&&s["tx-id"]>r)&&(t=Wi(t,s["tx-steps"]));return t}notifyAll(){Object.keys(this.queryCbs).forEach(t=>{this.notifyOne(t)})}loadedNotifyAll(){this.pendingMutations.isLoading()||this.querySubs.isLoading()||this.notifyAll()}shutdown(){var t;this._log.info("[shutdown]",this.config.appId),this._isShutdown=!0,(t=this._transport)===null||t===void 0||t.close()}_sendMutation(t,n){if(n.error){this._handleMutationError("error",t,{message:n.error.message});return}if(this.status!==pe.AUTHENTICATED){this._finishTransaction("enqueued",t);return}const r=Math.max(6e3,Math.min(this._inFlightMutationEventIds.size+1,this.pendingMutations.currentValue.size+1)*6e3);this._isOnline?(this._trySend(t,n),setTimeout(()=>{this._isOnline&&this._handleMutationError("timeout",t,{message:"transaction timed out"})},r)):this._finishTransaction("enqueued",t)}_flushPendingMessages(){Object.keys(this.queryCbs).map(i=>this.querySubs.currentValue[i]).filter(i=>i).forEach(({eventId:i,q:s})=>{this._trySendAuthed(i,{op:"add-query",q:s})}),Object.values(this.queryOnceDfds).flat().forEach(({eventId:i,q:s})=>{this._trySendAuthed(i,{op:"add-query",q:s})}),this._rewriteMutationsSorted(this.attrs,this.pendingMutations.currentValue).forEach(([i,s])=>{s["tx-id"]||this._sendMutation(i,s)})}_cleanupPendingMutationsQueries(){let t=Number.MAX_SAFE_INTEGER;for(const{result:n}of Object.values(this.querySubs.currentValue))n!=null&&n.processedTxId&&(t=Math.min(t,n==null?void 0:n.processedTxId));this.pendingMutations.set(n=>{for(const[r,i]of Array.from(n.entries()))i["tx-id"]&&i["tx-id"]<=t&&n.delete(r);return n})}_cleanupPendingMutationsTimeout(){if(this.pendingMutations.currentValue.size<this._pendingMutationCleanupThreshold)return;const t=Date.now();this.pendingMutations.set(n=>{for(const[r,i]of Array.from(n.entries()))i.confirmed&&i.confirmed+this._pendingTxCleanupTimeout<t&&n.delete(r);return n})}_trySendAuthed(...t){this.status===pe.AUTHENTICATED&&this._trySend(...t)}_trySend(t,n,r){if(this._transport.isOpen()){switch(jr[n.op]||this._log.info("[send]",this._transport.id,n.op,n),n.op){case"transact":{this._inFlightMutationEventIds.add(t);break}case"init":this._inFlightMutationEventIds.clear()}this._transport.send(Object.assign({"client-event-id":t},n))}}_startSocket(){if(this._wsOk=null,this._isShutdown){this._log.info("[socket][start]",this.config.appId,"Reactor has been shut down and will not start a new socket");return}if(this._transport&&this._transport.isConnecting()){this._log.info("[socket][start]",this._transport.id,"maintained as current transport, we were still in a connecting state");return}const t=this._transport;this._transport=qo({transportType:this._transportType,appId:this.config.appId,apiURI:this.config.apiURI,wsURI:this.config.websocketURI,EventSourceImpl:this._EventSource}),this._transport.onopen=this._transportOnOpen,this._transport.onmessage=this._transportOnMessage,this._transport.onclose=this._transportOnClose,this._transport.onerror=this._transportOnError,this._log.info("[socket][start]",this._transport.id),t!=null&&t.isOpen()&&(this._log.info("[socket][start]",this._transport.id,"close previous transport id = ",t.id),t.close())}getLocalId(t){return D(this,void 0,void 0,function*(){const n=`localToken_${t}`,r=yield this._persister.getItem(n);if(r)return r;if(this._localIdPromises[n])return this._localIdPromises[n];const i=V();return this._localIdPromises[n]=this._persister.setItem(n,i).then(()=>i),this._localIdPromises[n]})}_replaceUrlAfterOAuth(){if(typeof URL>"u")return;const t=new URL(window.location.href);if(t.searchParams.get(Xt)){const n=t.toString();t.searchParams.delete(Xt),t.searchParams.delete("code"),t.searchParams.delete("error");const r=t.pathname+(t.searchParams.size?"?"+t.searchParams:"")+t.hash;if(history.replaceState(history.state,"",r),typeof navigation=="object"&&typeof navigation.addEventListener=="function"&&typeof navigation.removeEventListener=="function"){let i=!1;const s=o=>{var u;i||(i=!0,navigation.removeEventListener("navigate",s),!o.userInitiated&&o.navigationType==="replace"&&((u=o.destination)===null||u===void 0?void 0:u.url)===n&&history.replaceState(history.state,"",r))};navigation.addEventListener("navigate",s)}}}_oauthLoginInit(){return D(this,void 0,void 0,function*(){var t,n,r,i;if(typeof window>"u"||typeof window.location>"u"||typeof URLSearchParams>"u")return null;const s=new URLSearchParams(window.location.search);if(!s.get(Xt))return null;const o=s.get("error");if(o)return this._replaceUrlAfterOAuth(),{error:{message:o}};const u=s.get("code");if(!u)return null;this._replaceUrlAfterOAuth();try{const a=yield this._getCurrentUser(),d=(a==null?void 0:a.type)==="guest",{user:c}=yield sr({apiURI:this.config.apiURI,appId:this.config.appId,code:u,refreshToken:d?a.refresh_token:void 0});return this.setCurrentUser(c),null}catch(a){return((t=a==null?void 0:a.body)===null||t===void 0?void 0:t.type)==="record-not-found"&&((r=(n=a==null?void 0:a.body)===null||n===void 0?void 0:n.hint)===null||r===void 0?void 0:r["record-type"])==="app-oauth-code"&&(yield this._hasCurrentUser())?null:{error:{message:((i=a==null?void 0:a.body)===null||i===void 0?void 0:i.message)||"Error logging in."}}}})}_waitForOAuthCallbackResponse(){return D(this,void 0,void 0,function*(){return yield this._oauthCallbackResponse})}__subscribeMutationErrors(t){return this.mutationErrorCbs.push(t),()=>{this.mutationErrorCbs=this.mutationErrorCbs.filter(n=>n!==t)}}subscribeAuth(t){this.authCbs.push(t);const n=this._currentUserCached;n.isLoading||t(this._currentUserCached);let r=!1;return this.getCurrentUser().then(i=>{r||Je(i,n)||t(i)}),()=>{r=!0,this.authCbs=this.authCbs.filter(i=>i!==t)}}getAuth(){return D(this,void 0,void 0,function*(){const{user:t,error:n}=yield this.getCurrentUser();if(n)throw new je("Could not get current user: "+n.message);return t})}subscribeConnectionStatus(t){return this.connectionStatusCbs.push(t),()=>{this.connectionStatusCbs=this.connectionStatusCbs.filter(n=>n!==t)}}subscribeAttrs(t){return this.attrsCbs.push(t),this.attrs&&t(this.attrs),()=>{this.attrsCbs=this.attrsCbs.filter(n=>n!==t)}}notifyAuthSubs(t){this.authCbs.forEach(n=>n(t))}notifyMutationErrorSubs(t){this.mutationErrorCbs.forEach(n=>n(t))}notifyAttrsSubs(){if(!this.attrs)return;const t=this.optimisticAttrs();this.attrsCbs.forEach(n=>n(t))}notifyConnectionStatusSubs(t){this.connectionStatusCbs.forEach(n=>n(t))}setCurrentUser(t){return D(this,void 0,void 0,function*(){yield this._persister.setItem(en,t)})}getCurrentUserCached(){return this._currentUserCached}_getCurrentUser(){return D(this,void 0,void 0,function*(){const t=yield this._persister.getItem(en);return typeof t=="string"?JSON.parse(t):t})}getCurrentUser(){return D(this,void 0,void 0,function*(){const t=yield this._waitForOAuthCallbackResponse();if(t!=null&&t.error){const i={error:t.error,user:void 0};return this._currentUserCached=Object.assign({isLoading:!1},i),i}const r={user:yield this._getCurrentUser(),error:void 0};return this._currentUserCached=Object.assign({isLoading:!1},r),r})}_hasCurrentUser(){return D(this,void 0,void 0,function*(){const t=yield this._persister.getItem(en);return JSON.parse(t)!=null})}changeCurrentUser(t){return D(this,void 0,void 0,function*(){var n;const{user:r}=yield this.getCurrentUser();if(!Je(r,t)){yield this.setCurrentUser(t),this.updateUser(t);try{(n=this._broadcastChannel)===null||n===void 0||n.postMessage({type:"auth"})}catch(i){console.error("Error posting message to broadcast channel",i)}}})}syncUserToEndpoint(t){return D(this,void 0,void 0,function*(){this.config.endpointURI&&fetch(this.config.endpointURI+"/sync-auth",{method:"POST",body:JSON.stringify({user:t}),headers:{"Content-Type":"application/json"}})})}updateUser(t){this.syncUserToEndpoint(t);const n={error:void 0,user:t};this._currentUserCached=Object.assign({isLoading:!1},n),this._dataForQueryCache={},this.querySubs.set(r=>(Object.keys(r).forEach(i=>{delete r[i].result}),r)),this._reconnectTimeoutMs=0,this._transport.close(),this._oauthCallbackResponse=null,this.notifyAuthSubs(n)}sendMagicCode({email:t}){return yo({apiURI:this.config.apiURI,appId:this.config.appId,email:t})}signInWithMagicCode(t){return D(this,arguments,void 0,function*({email:n,code:r}){var i;const s=yield this.getCurrentUser(),o=((i=s==null?void 0:s.user)===null||i===void 0?void 0:i.type)==="guest",u=yield bo({apiURI:this.config.apiURI,appId:this.config.appId,email:n,code:r,refreshToken:o?s.user.refresh_token:void 0});return yield this.changeCurrentUser(u.user),u})}signInWithCustomToken(t){return D(this,void 0,void 0,function*(){const n=yield _o({apiURI:this.config.apiURI,appId:this.config.appId,refreshToken:t});return yield this.changeCurrentUser(n.user),n})}signInAsGuest(){return D(this,void 0,void 0,function*(){const t=yield go({apiURI:this.config.apiURI,appId:this.config.appId});return yield this.changeCurrentUser(t.user),t})}potentiallyInvalidateToken(t,n){var r;const i=(r=t==null?void 0:t.user)===null||r===void 0?void 0:r.refresh_token;if(!i)return;if(n.invalidateToken===!1){this._log.info("[auth-invalidate] skipped invalidateToken");return}wo({apiURI:this.config.apiURI,appId:this.config.appId,refreshToken:i}).then(()=>{this._log.info("[auth-invalidate] completed invalidateToken")}).catch(o=>{})}signOut(t){return D(this,void 0,void 0,function*(){const n=yield this.getCurrentUser();this.potentiallyInvalidateToken(n,t),yield this.changeCurrentUser(null)})}createAuthorizationURL({clientName:t,redirectURL:n}){const{apiURI:r,appId:i}=this.config;return`${r}/runtime/oauth/start?app_id=${i}&client_name=${t}&redirect_uri=${n}`}exchangeCodeForToken(t){return D(this,arguments,void 0,function*({code:n,codeVerifier:r}){var i;const s=yield this.getCurrentUser(),o=((i=s==null?void 0:s.user)===null||i===void 0?void 0:i.type)==="guest",u=yield sr({apiURI:this.config.apiURI,appId:this.config.appId,code:n,codeVerifier:r,refreshToken:o?s.user.refresh_token:void 0});return yield this.changeCurrentUser(u.user),u})}issuerURI(){const{apiURI:t,appId:n}=this.config;return`${t}/runtime/${n}`}signInWithIdToken(t){return D(this,arguments,void 0,function*({idToken:n,clientName:r,nonce:i}){var s;const o=yield this.getCurrentUser(),u=(s=o==null?void 0:o.user)===null||s===void 0?void 0:s.refresh_token,a=yield To({apiURI:this.config.apiURI,appId:this.config.appId,idToken:n,clientName:r,nonce:i,refreshToken:u});return yield this.changeCurrentUser(a.user),a})}joinRoom(t,n){this._rooms[t]||(this._rooms[t]={isConnected:!1,error:void 0}),this._presence[t]=this._presence[t]||{};const r=this._presence[t].result;return n&&!r&&(this._presence[t].result=this._presence[t].result||{},this._presence[t].result.user=n,this._notifyPresenceSubs(t)),this._tryJoinRoom(t,n),()=>{this._cleanupRoom(t)}}_cleanupRoom(t){var n,r,i,s;if(!(!((r=(n=this._presence[t])===null||n===void 0?void 0:n.handlers)===null||r===void 0)&&r.length)&&!Object.keys((i=this._broadcastSubs[t])!==null&&i!==void 0?i:{}).length){const o=(s=this._rooms[t])===null||s===void 0?void 0:s.isConnected;delete this._rooms[t],delete this._presence[t],delete this._broadcastSubs[t],o?this._tryLeaveRoom(t):this._roomsPendingLeave[t]=!0}}getPresence(t,n,r={}){const i=this._rooms[n],s=this._presence[n];return!i||!s||!s.result?null:Object.assign(Object.assign({},Ao(s.result,r,this._sessionId)),{isLoading:!i.isConnected,error:i.error})}publishPresence(t,n,r){const i=this._rooms[n],s=this._presence[n];if(!i||!s)return;s.result=s.result||{};const o=Object.assign(Object.assign({},s.result.user),r);s.result.user=o,i.isConnected&&(this._trySetPresence(n,o),this._notifyPresenceSubs(n))}_trySetPresence(t,n){this._trySendAuthed(V(),{op:"set-presence","room-id":t,data:n})}_tryJoinRoom(t,n){this._trySendAuthed(V(),{op:"join-room","room-id":t,data:n}),delete this._roomsPendingLeave[t]}_tryLeaveRoom(t){this._trySendAuthed(V(),{op:"leave-room","room-id":t})}subscribePresence(t,n,r,i){const s=this.joinRoom(n,r.initialData),o=Object.assign(Object.assign({},r),{roomId:n,cb:i,prev:null});return this._presence[n]=this._presence[n]||{},this._presence[n].handlers=this._presence[n].handlers||[],this._presence[n].handlers.push(o),this._notifyPresenceSub(n,o),()=>{var u,a,d;this._presence[n].handlers=(d=(a=(u=this._presence[n])===null||u===void 0?void 0:u.handlers)===null||a===void 0?void 0:a.filter(c=>c!==o))!==null&&d!==void 0?d:[],s()}}_notifyPresenceSubs(t){var n,r;(r=(n=this._presence[t])===null||n===void 0?void 0:n.handlers)===null||r===void 0||r.forEach(i=>{this._notifyPresenceSub(t,i)})}_notifyPresenceSub(t,n){const r=this.getPresence("",t,n);r&&(n.prev&&!Co(r,n.prev)||(n.prev=r,n.cb(r)))}_patchPresencePeers(t,n){var r,i,s;const o=((i=(r=this._presence[t])===null||r===void 0?void 0:r.result)===null||i===void 0?void 0:i.peers)||{};let u=Object.fromEntries(Object.entries(o).map(([d,c])=>[d,{data:c}]));(s=this._presence[t])===null||s===void 0||s.result;const a=Mt(u,d=>{for(let[c,f,h]of n)switch(f){case"+":ai(d,c,h);break;case"r":kn(d,c,h);break;case"-":In(d,c);break}delete d[this._sessionId]});this._setPresencePeers(t,a)}_setPresencePeers(t,n){const r=Object.assign({},n);delete r[this._sessionId];const i=Object.fromEntries(Object.entries(r).map(([s,o])=>[s,o.data]));this._presence=Mt(this._presence,s=>{kn(s,[t,"result","peers"],i)})}publishTopic({roomType:t,roomId:n,topic:r,data:i}){var s;const o=this._rooms[n];if(o){if(!o.isConnected){this._broadcastQueue[n]=(s=this._broadcastQueue[n])!==null&&s!==void 0?s:[],this._broadcastQueue[n].push({topic:r,roomType:t,data:i});return}this._tryBroadcast(n,t,r,i)}}_tryBroadcast(t,n,r,i){this._trySendAuthed(V(),{op:"client-broadcast","room-id":t,roomType:n,topic:r,data:i})}subscribeTopic(t,n,r){const i=this.joinRoom(t);return this._broadcastSubs[t]=this._broadcastSubs[t]||{},this._broadcastSubs[t][n]=this._broadcastSubs[t][n]||[],this._broadcastSubs[t][n].push(r),this._presence[t]=this._presence[t]||{},()=>{this._broadcastSubs[t][n]=this._broadcastSubs[t][n].filter(s=>s!==r),this._broadcastSubs[t][n].length||delete this._broadcastSubs[t][n],i()}}_notifyBroadcastSubs(t,n,r){var i,s,o;(o=(s=(i=this._broadcastSubs)===null||i===void 0?void 0:i[t])===null||s===void 0?void 0:s[n])===null||o===void 0||o.forEach(u=>{var a,d,c,f,h,p;const b=(a=r.data)===null||a===void 0?void 0:a.data,g=r.data["peer-id"]===this._sessionId?(c=(d=this._presence[t])===null||d===void 0?void 0:d.result)===null||c===void 0?void 0:c.user:(p=(h=(f=this._presence[t])===null||f===void 0?void 0:f.result)===null||h===void 0?void 0:h.peers)===null||p===void 0?void 0:p[r.data["peer-id"]];return u(b,g)})}uploadFile(t,n,r){return D(this,void 0,void 0,function*(){var i;const s=yield this.getCurrentUser(),o=(i=s==null?void 0:s.user)===null||i===void 0?void 0:i.refresh_token;return mo(Object.assign(Object.assign({},r),{apiURI:this.config.apiURI,appId:this.config.appId,path:t,file:n,refreshToken:o}))})}deleteFile(t){return D(this,void 0,void 0,function*(){var n;const r=yield this.getCurrentUser(),i=(n=r==null?void 0:r.user)===null||n===void 0?void 0:n.refresh_token;return yield So({apiURI:this.config.apiURI,appId:this.config.appId,path:t,refreshToken:i})})}upload(t,n){return D(this,void 0,void 0,function*(){var r;const i=yield this.getCurrentUser(),s=(r=i==null?void 0:i.user)===null||r===void 0?void 0:r.refresh_token,o=t||n.name,u=yield vo({apiURI:this.config.apiURI,appId:this.config.appId,fileName:o,refreshToken:s});return yield Oo(u,n)})}getDownloadUrl(t){return D(this,void 0,void 0,function*(){var n;const r=yield this.getCurrentUser(),i=(n=r==null?void 0:r.user)===null||n===void 0?void 0:n.refresh_token;return yield Eo({apiURI:this.config.apiURI,appId:this.config.appId,path:t,refreshToken:i})})}}let ot;function Ho(e,t){ot==null||ot.dispose();const n=nu(t),r=Xo(t,u),i=Zo(Jo(e));function s(c){var f;c.source===i.element.contentWindow&&((f=c.data)===null||f===void 0?void 0:f.type)==="close"&&n.isVisible()&&u()}function o(c){const f=c.shiftKey&&c.ctrlKey&&c.key==="0",h=c.key==="Escape"||c.key==="Esc";(f||h&&n.isVisible())&&u()}function u(){n.isVisible()?n.element.style.display="none":(n.element.style.display="block",n.element.contains(i.element)||n.element.appendChild(i.element))}function a(){n.element.remove(),r.element.remove(),removeEventListener("keydown",o),removeEventListener("message",s)}function d(){document.body.appendChild(n.element),document.body.appendChild(r.element),addEventListener("keydown",o),addEventListener("message",s),ot={dispose:a}}return d()}function Jo(e){return`${Jt||ur?"http://localhost:3000":"https://instantdb.com"}/_devtool?appId=${e}`}function Zo(e){const t=document.createElement("iframe");return t.src=e,t.className="instant-devtool-iframe",Object.assign(t.style,{width:"100%",height:"100%",backgroundColor:"white",border:"none"}),{element:t}}function Xo(e,t){const n=`
|
|
32
32
|
<svg width="32" height="32" viewBox="0 0 512 512" fill="none" xmlns="http://www.w3.org/2000/svg">
|
|
33
33
|
<rect width="512" height="512" fill="black"/>
|
|
34
34
|
<rect x="97.0973" y="91.3297" width="140" height="330" fill="white"/>
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@instantdb/react-common",
|
|
3
|
-
"version": "v0.22.
|
|
3
|
+
"version": "v0.22.36-experimental.drewh-cookie-sync-endpoint.18891755335.1",
|
|
4
4
|
"description": "Instant DB shared components for React and React Native",
|
|
5
5
|
"homepage": "https://github.com/instantdb/instant/tree/main/client/packages/react-common",
|
|
6
6
|
"repository": {
|
|
@@ -53,8 +53,8 @@
|
|
|
53
53
|
"react": ">=16"
|
|
54
54
|
},
|
|
55
55
|
"dependencies": {
|
|
56
|
-
"@instantdb/core": "v0.22.
|
|
57
|
-
"@instantdb/version": "v0.22.
|
|
56
|
+
"@instantdb/core": "v0.22.36-experimental.drewh-cookie-sync-endpoint.18891755335.1",
|
|
57
|
+
"@instantdb/version": "v0.22.36-experimental.drewh-cookie-sync-endpoint.18891755335.1"
|
|
58
58
|
},
|
|
59
59
|
"scripts": {
|
|
60
60
|
"test": "vitest",
|