@instantdb/resumable-stream 0.22.155 → 0.22.156
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/.turbo/turbo-build.log +8 -8
- package/dist/standalone/index.js +128 -127
- package/dist/standalone/index.umd.cjs +3 -3
- package/package.json +2 -2
package/.turbo/turbo-build.log
CHANGED
|
@@ -1,17 +1,17 @@
|
|
|
1
1
|
|
|
2
|
-
> @instantdb/resumable-stream@0.22.
|
|
2
|
+
> @instantdb/resumable-stream@0.22.156 build /home/runner/work/instant/instant/client/packages/resumable-stream
|
|
3
3
|
> rm -rf dist; npm run build:tshy && npm run build:standalone && npm run check-exports
|
|
4
4
|
|
|
5
5
|
npm warn Unknown env config "verify-deps-before-run". This will stop working in the next major version of npm.
|
|
6
6
|
npm warn Unknown user config "always-auth". This will stop working in the next major version of npm.
|
|
7
7
|
|
|
8
|
-
> @instantdb/resumable-stream@0.22.
|
|
8
|
+
> @instantdb/resumable-stream@0.22.156 build:tshy
|
|
9
9
|
> tshy
|
|
10
10
|
|
|
11
11
|
npm warn Unknown env config "verify-deps-before-run". This will stop working in the next major version of npm.
|
|
12
12
|
npm warn Unknown user config "always-auth". This will stop working in the next major version of npm.
|
|
13
13
|
|
|
14
|
-
> @instantdb/resumable-stream@0.22.
|
|
14
|
+
> @instantdb/resumable-stream@0.22.156 build:standalone
|
|
15
15
|
> vite build
|
|
16
16
|
|
|
17
17
|
[36mvite v5.4.14 [32mbuilding for production...[36m[39m
|
|
@@ -19,17 +19,17 @@ transforming...
|
|
|
19
19
|
[32m✓[39m 73 modules transformed.
|
|
20
20
|
rendering chunks...
|
|
21
21
|
computing gzip size...
|
|
22
|
-
[2mdist/standalone/[22m[36mindex.umd.cjs [39m[1m[2m66.
|
|
23
|
-
[2mdist/standalone/[22m[36mindex.js [39m[1m[2m106.
|
|
24
|
-
[32m✓ built in 1.
|
|
22
|
+
[2mdist/standalone/[22m[36mindex.umd.cjs [39m[1m[2m66.85 kB[22m[1m[22m[2m │ gzip: 21.04 kB[22m
|
|
23
|
+
[2mdist/standalone/[22m[36mindex.js [39m[1m[2m106.21 kB[22m[1m[22m[2m │ gzip: 27.79 kB[22m
|
|
24
|
+
[32m✓ built in 1.06s[39m
|
|
25
25
|
npm warn Unknown env config "verify-deps-before-run". This will stop working in the next major version of npm.
|
|
26
26
|
npm warn Unknown user config "always-auth". This will stop working in the next major version of npm.
|
|
27
27
|
|
|
28
|
-
> @instantdb/resumable-stream@0.22.
|
|
28
|
+
> @instantdb/resumable-stream@0.22.156 check-exports
|
|
29
29
|
> attw --pack .
|
|
30
30
|
|
|
31
31
|
|
|
32
|
-
@instantdb/resumable-stream v0.22.
|
|
32
|
+
@instantdb/resumable-stream v0.22.156
|
|
33
33
|
|
|
34
34
|
Build tools:
|
|
35
35
|
- @arethetypeswrong/cli@^0.17.4
|
package/dist/standalone/index.js
CHANGED
|
@@ -3,7 +3,7 @@ var Mt = (e) => {
|
|
|
3
3
|
throw TypeError(e);
|
|
4
4
|
};
|
|
5
5
|
var Cn = (e, t, n) => t in e ? _n(e, t, { enumerable: !0, configurable: !0, writable: !0, value: n }) : e[t] = n;
|
|
6
|
-
var
|
|
6
|
+
var l = (e, t, n) => Cn(e, typeof t != "symbol" ? t + "" : t, n), ot = (e, t, n) => t.has(e) || Mt("Cannot " + n);
|
|
7
7
|
var g = (e, t, n) => (ot(e, t, "read from private field"), n ? n.call(e) : t.get(e)), Q = (e, t, n) => t.has(e) ? Mt("Cannot add the same private member more than once") : t instanceof WeakSet ? t.add(e) : t.set(e, n), ae = (e, t, n, i) => (ot(e, t, "write to private field"), i ? i.call(e, n) : t.set(e, n), n), G = (e, t, n) => (ot(e, t, "access private method"), n);
|
|
8
8
|
const xn = /^(?:[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;
|
|
9
9
|
function Pe(e) {
|
|
@@ -296,7 +296,7 @@ function Fn(e, t, n, i, s) {
|
|
|
296
296
|
u.length < r.length && ([r, u] = [u, r], [n, i] = [i, n]);
|
|
297
297
|
for (let c = 0; c < r.length; c += 1)
|
|
298
298
|
if (o.get(c.toString()) && u[c] !== r[c]) {
|
|
299
|
-
const
|
|
299
|
+
const d = t.concat([c]), f = Se(d, s);
|
|
300
300
|
n.push({
|
|
301
301
|
op: T.Replace,
|
|
302
302
|
path: f,
|
|
@@ -310,7 +310,7 @@ function Fn(e, t, n, i, s) {
|
|
|
310
310
|
});
|
|
311
311
|
}
|
|
312
312
|
for (let c = r.length; c < u.length; c += 1) {
|
|
313
|
-
const
|
|
313
|
+
const d = t.concat([c]), f = Se(d, s);
|
|
314
314
|
n.push({
|
|
315
315
|
op: T.Add,
|
|
316
316
|
path: f,
|
|
@@ -321,15 +321,15 @@ function Fn(e, t, n, i, s) {
|
|
|
321
321
|
if (r.length < u.length) {
|
|
322
322
|
const { arrayLengthAssignment: c = !0 } = a.enablePatches;
|
|
323
323
|
if (c) {
|
|
324
|
-
const
|
|
324
|
+
const d = t.concat(["length"]), f = Se(d, s);
|
|
325
325
|
i.push({
|
|
326
326
|
op: T.Replace,
|
|
327
327
|
path: f,
|
|
328
328
|
value: r.length
|
|
329
329
|
});
|
|
330
330
|
} else
|
|
331
|
-
for (let
|
|
332
|
-
const f = t.concat([
|
|
331
|
+
for (let d = u.length; r.length < d; d -= 1) {
|
|
332
|
+
const f = t.concat([d - 1]), m = Se(f, s);
|
|
333
333
|
i.push({
|
|
334
334
|
op: T.Remove,
|
|
335
335
|
path: m
|
|
@@ -339,11 +339,11 @@ function Fn(e, t, n, i, s) {
|
|
|
339
339
|
}
|
|
340
340
|
function zn({ original: e, copy: t, assignedMap: n }, i, s, r, o) {
|
|
341
341
|
n.forEach((a, u) => {
|
|
342
|
-
const c = pe(e, u),
|
|
343
|
-
if (ve(c,
|
|
342
|
+
const c = pe(e, u), d = Qe(pe(t, u)), f = a ? Ne(e, u) ? T.Replace : T.Add : T.Remove;
|
|
343
|
+
if (ve(c, d) && f === T.Replace)
|
|
344
344
|
return;
|
|
345
345
|
const m = i.concat(u), y = Se(m, o);
|
|
346
|
-
s.push(f === T.Remove ? { op: f, path: y } : { op: f, path: y, value:
|
|
346
|
+
s.push(f === T.Remove ? { op: f, path: y } : { op: f, path: y, value: d }), r.push(f === T.Add ? { op: T.Remove, path: y } : f === T.Remove ? { op: T.Add, path: y, value: c } : { op: T.Replace, path: y, value: c });
|
|
347
347
|
});
|
|
348
348
|
}
|
|
349
349
|
function Vn({ original: e, copy: t }, n, i, s, r) {
|
|
@@ -483,14 +483,14 @@ const qe = (e, t, n = !1) => {
|
|
|
483
483
|
let a = e.setMap.get(o);
|
|
484
484
|
const u = k(a), c = ((s = (i = e.options).mark) === null || s === void 0 ? void 0 : s.call(i, a, Z)) === Z.mutable;
|
|
485
485
|
if (e.options.strict && qe(o, e.options, c), !c && !u && $e(o, e.options) && !e.finalized && e.original.has(o)) {
|
|
486
|
-
const
|
|
486
|
+
const d = xt.createDraft({
|
|
487
487
|
original: o,
|
|
488
488
|
parentDraft: e,
|
|
489
489
|
key: o,
|
|
490
490
|
finalities: e.finalities,
|
|
491
491
|
options: e.options
|
|
492
492
|
});
|
|
493
|
-
e.setMap.set(o,
|
|
493
|
+
e.setMap.set(o, d), a = d;
|
|
494
494
|
} else u && (a = u.proxy);
|
|
495
495
|
return {
|
|
496
496
|
done: !1,
|
|
@@ -697,24 +697,24 @@ function an(e) {
|
|
|
697
697
|
(i || "key" in e) && (a.key = i);
|
|
698
698
|
const { proxy: u, revoke: c } = Proxy.revocable(o === 1 ? Object.assign([], a) : a, on);
|
|
699
699
|
if (s.revoke.push(c), rn.add(u), a.proxy = u, n) {
|
|
700
|
-
const
|
|
701
|
-
|
|
700
|
+
const d = n;
|
|
701
|
+
d.finalities.draft.push((f, m) => {
|
|
702
702
|
var y, I;
|
|
703
703
|
const w = k(u);
|
|
704
|
-
let h =
|
|
704
|
+
let h = d.type === 3 ? d.setMap : d.copy;
|
|
705
705
|
const O = pe(h, i), b = k(O);
|
|
706
706
|
if (b) {
|
|
707
707
|
let $ = b.original;
|
|
708
|
-
b.operated && ($ = Tt(O)), pt(b), mt(b, Fe, f, m),
|
|
708
|
+
b.operated && ($ = Tt(O)), pt(b), mt(b, Fe, f, m), d.options.enableAutoFreeze && (d.options.updatedValues = (y = d.options.updatedValues) !== null && y !== void 0 ? y : /* @__PURE__ */ new WeakMap(), d.options.updatedValues.set($, b.original)), Rt(h, i, $);
|
|
709
709
|
}
|
|
710
710
|
(I = w.callbacks) === null || I === void 0 || I.forEach(($) => {
|
|
711
711
|
$(f, m);
|
|
712
712
|
});
|
|
713
713
|
});
|
|
714
714
|
} else {
|
|
715
|
-
const
|
|
716
|
-
|
|
717
|
-
pt(
|
|
715
|
+
const d = k(u);
|
|
716
|
+
d.finalities.draft.push((f, m) => {
|
|
717
|
+
pt(d), mt(d, Fe, f, m);
|
|
718
718
|
});
|
|
719
719
|
}
|
|
720
720
|
return u;
|
|
@@ -807,12 +807,13 @@ function Yn(e) {
|
|
|
807
807
|
return e.__ops;
|
|
808
808
|
}
|
|
809
809
|
class H extends Error {
|
|
810
|
-
constructor(n, i) {
|
|
810
|
+
constructor(n, i, s) {
|
|
811
811
|
super(n);
|
|
812
|
-
|
|
813
|
-
this
|
|
814
|
-
|
|
815
|
-
|
|
812
|
+
l(this, "hint");
|
|
813
|
+
l(this, "traceId");
|
|
814
|
+
this.hint = i, s && (this.traceId = s);
|
|
815
|
+
const r = new.target.prototype;
|
|
816
|
+
Object.setPrototypeOf && Object.setPrototypeOf(this, r), Error.captureStackTrace && Error.captureStackTrace(this, H), this.name = "InstantError";
|
|
816
817
|
}
|
|
817
818
|
get [Symbol.toStringTag]() {
|
|
818
819
|
return "InstantError";
|
|
@@ -822,9 +823,9 @@ class Oe extends H {
|
|
|
822
823
|
constructor(n) {
|
|
823
824
|
var r;
|
|
824
825
|
const i = ((r = n.body) == null ? void 0 : r.message) || `API Error (${n.status})`;
|
|
825
|
-
super(i, n.body.hint);
|
|
826
|
-
|
|
827
|
-
|
|
826
|
+
super(i, n.body.hint, n.body["trace-id"]);
|
|
827
|
+
l(this, "body");
|
|
828
|
+
l(this, "status");
|
|
828
829
|
const s = new.target.prototype;
|
|
829
830
|
Object.setPrototypeOf && Object.setPrototypeOf(this, s), Error.captureStackTrace && Error.captureStackTrace(this, Oe), this.name = "InstantAPIError", this.status = n.status, this.body = n.body;
|
|
830
831
|
}
|
|
@@ -833,14 +834,14 @@ class Oe extends H {
|
|
|
833
834
|
}
|
|
834
835
|
}
|
|
835
836
|
typeof window < "u" && typeof window.localStorage < "u" && (window.localStorage.getItem("devBackend"), window.localStorage.getItem("__instantLogging"), window.localStorage.getItem("__devtoolLocalDash"));
|
|
836
|
-
const je = "v0.22.
|
|
837
|
+
const je = "v0.22.156";
|
|
837
838
|
class ue {
|
|
838
839
|
constructor(t, n, i, s = { indexed: !1, unique: !1 }) {
|
|
839
|
-
|
|
840
|
-
|
|
841
|
-
|
|
842
|
-
|
|
843
|
-
|
|
840
|
+
l(this, "valueType");
|
|
841
|
+
l(this, "required");
|
|
842
|
+
l(this, "isIndexed");
|
|
843
|
+
l(this, "config");
|
|
844
|
+
l(this, "metadata", {});
|
|
844
845
|
this.valueType = t, this.required = n, this.isIndexed = i, this.config = s;
|
|
845
846
|
}
|
|
846
847
|
/**
|
|
@@ -900,9 +901,9 @@ const Wt = [
|
|
|
900
901
|
return !0;
|
|
901
902
|
}
|
|
902
903
|
}, ei = (e, t, n, i, s, r, o) => {
|
|
903
|
-
const a = r.valueType === "json", u = (c,
|
|
904
|
-
if (!fn(f,
|
|
905
|
-
throw new E(`Invalid value for operator '${c}' on attribute '${i}' in entity '${s}'. Expected ${
|
|
904
|
+
const a = r.valueType === "json", u = (c, d, f) => {
|
|
905
|
+
if (!fn(f, d, a))
|
|
906
|
+
throw new E(`Invalid value for operator '${c}' on attribute '${i}' in entity '${s}'. Expected ${d}, but received: ${typeof f}`, o);
|
|
906
907
|
};
|
|
907
908
|
switch (e) {
|
|
908
909
|
case "in":
|
|
@@ -937,8 +938,8 @@ const Wt = [
|
|
|
937
938
|
if (o)
|
|
938
939
|
return;
|
|
939
940
|
const u = e;
|
|
940
|
-
for (const [c,
|
|
941
|
-
ei(c,
|
|
941
|
+
for (const [c, d] of Object.entries(u))
|
|
942
|
+
ei(c, d, r, t, i, n, `${s}.${c}`);
|
|
942
943
|
} else if (!fn(e, r, o))
|
|
943
944
|
throw new E(`Invalid value for attribute '${t}' in entity '${i}'. Expected ${r}, but received: ${typeof e}`, s);
|
|
944
945
|
}, ti = (e, t, n, i, s) => {
|
|
@@ -946,8 +947,8 @@ const Wt = [
|
|
|
946
947
|
if (r.length < 2)
|
|
947
948
|
throw new E(`Invalid dot notation path '${e}'. Must contain at least one dot.`, s);
|
|
948
949
|
let o = n;
|
|
949
|
-
for (let
|
|
950
|
-
const f = r[
|
|
950
|
+
for (let d = 0; d < r.length - 1; d++) {
|
|
951
|
+
const f = r[d], m = i.entities[o];
|
|
951
952
|
if (!m)
|
|
952
953
|
throw new E(`Entity '${o}' does not exist in schema while traversing dot notation path '${e}'.`, s);
|
|
953
954
|
const y = m.links[f];
|
|
@@ -974,8 +975,8 @@ const Wt = [
|
|
|
974
975
|
return;
|
|
975
976
|
}
|
|
976
977
|
if (!c) {
|
|
977
|
-
const
|
|
978
|
-
throw new E(`Attribute '${a}' does not exist on entity '${o}' in dot notation path '${e}'. Available attributes: ${
|
|
978
|
+
const d = Object.keys(u.attrs);
|
|
979
|
+
throw new E(`Attribute '${a}' does not exist on entity '${o}' in dot notation path '${e}'. Available attributes: ${d.length > 0 ? d.join(", ") + ", id" : "id"}`, s);
|
|
979
980
|
}
|
|
980
981
|
Te(t, e, c, n, s);
|
|
981
982
|
}, ln = (e, t, n, i) => {
|
|
@@ -999,8 +1000,8 @@ const Wt = [
|
|
|
999
1000
|
continue;
|
|
1000
1001
|
const a = o.attrs[s], u = o.links[s];
|
|
1001
1002
|
if (!a && !u) {
|
|
1002
|
-
const c = Object.keys(o.attrs),
|
|
1003
|
-
throw new E(`Attribute or link '${s}' does not exist on entity '${t}'. Available attributes: ${c.length > 0 ? c.join(", ") : "none"}. Available links: ${
|
|
1003
|
+
const c = Object.keys(o.attrs), d = Object.keys(o.links);
|
|
1004
|
+
throw new E(`Attribute or link '${s}' does not exist on entity '${t}'. Available attributes: ${c.length > 0 ? c.join(", ") : "none"}. Available links: ${d.length > 0 ? d.join(", ") : "none"}`, `${i}.${s}`);
|
|
1004
1005
|
}
|
|
1005
1006
|
if (a)
|
|
1006
1007
|
Te(r, s, a, t, `${i}.${s}`);
|
|
@@ -1155,21 +1156,21 @@ const hn = (e) => e.length > 0 ? e.join(", ") : "none", ii = (e, t) => new B(`En
|
|
|
1155
1156
|
let ci = 0;
|
|
1156
1157
|
class ui {
|
|
1157
1158
|
constructor(t, n, i) {
|
|
1158
|
-
|
|
1159
|
-
|
|
1160
|
-
|
|
1161
|
-
|
|
1162
|
-
|
|
1163
|
-
|
|
1164
|
-
|
|
1165
|
-
|
|
1166
|
-
|
|
1167
|
-
|
|
1168
|
-
|
|
1169
|
-
|
|
1170
|
-
|
|
1171
|
-
|
|
1172
|
-
|
|
1159
|
+
l(this, "type", "sse");
|
|
1160
|
+
l(this, "initParams", null);
|
|
1161
|
+
l(this, "sendQueue", []);
|
|
1162
|
+
l(this, "sendPromise");
|
|
1163
|
+
l(this, "closeFired", !1);
|
|
1164
|
+
l(this, "sseInitTimeout");
|
|
1165
|
+
l(this, "ES");
|
|
1166
|
+
l(this, "messageUrl");
|
|
1167
|
+
l(this, "conn");
|
|
1168
|
+
l(this, "url");
|
|
1169
|
+
l(this, "id");
|
|
1170
|
+
l(this, "onopen");
|
|
1171
|
+
l(this, "onmessage");
|
|
1172
|
+
l(this, "onclose");
|
|
1173
|
+
l(this, "onerror");
|
|
1173
1174
|
this.id = `${this.type}_${ci++}`, this.url = n, this.messageUrl = i || this.url, this.ES = t, this.conn = new t(n), this.sseInitTimeout = setTimeout(() => {
|
|
1174
1175
|
this.initParams || this.handleError();
|
|
1175
1176
|
}, 1e4), this.conn.onmessage = (s) => {
|
|
@@ -1258,7 +1259,7 @@ function fi({ WStream: e, opts: t, startStream: n, appendStream: i, registerStre
|
|
|
1258
1259
|
const r = t.clientId;
|
|
1259
1260
|
let o = null, a = null, u = null;
|
|
1260
1261
|
const c = xe();
|
|
1261
|
-
let
|
|
1262
|
+
let d = !1, f = !1;
|
|
1262
1263
|
const m = [], y = [], I = [];
|
|
1263
1264
|
let w = !1, h = 0, O = 0;
|
|
1264
1265
|
const b = [], $ = new TextEncoder();
|
|
@@ -1346,10 +1347,10 @@ function fi({ WStream: e, opts: t, startStream: n, appendStream: i, registerStre
|
|
|
1346
1347
|
me(), se();
|
|
1347
1348
|
}
|
|
1348
1349
|
function ye({ offset: p, done: v }) {
|
|
1349
|
-
it(p), v && (
|
|
1350
|
+
it(p), v && (d = !0, F());
|
|
1350
1351
|
}
|
|
1351
1352
|
function be(p) {
|
|
1352
|
-
return
|
|
1353
|
+
return d ? (K(p, new H("Stream has been closed.")), null) : o || (K(p, new H("Stream has not been initialized.")), null);
|
|
1353
1354
|
}
|
|
1354
1355
|
async function st(p) {
|
|
1355
1356
|
u = p;
|
|
@@ -1455,9 +1456,9 @@ function fi({ WStream: e, opts: t, startStream: n, appendStream: i, registerStre
|
|
|
1455
1456
|
}
|
|
1456
1457
|
class li {
|
|
1457
1458
|
constructor() {
|
|
1458
|
-
|
|
1459
|
-
|
|
1460
|
-
|
|
1459
|
+
l(this, "items", []);
|
|
1460
|
+
l(this, "resolvers", []);
|
|
1461
|
+
l(this, "isClosed", !1);
|
|
1461
1462
|
}
|
|
1462
1463
|
push(t) {
|
|
1463
1464
|
if (this.isClosed)
|
|
@@ -1491,16 +1492,16 @@ function di({ RStream: e, opts: t, startStream: n, cancelStream: i }) {
|
|
|
1491
1492
|
let s = t.byteOffset || 0, r = !1;
|
|
1492
1493
|
const o = new TextDecoder("utf-8"), a = new TextEncoder();
|
|
1493
1494
|
let u, c = !1;
|
|
1494
|
-
const
|
|
1495
|
+
const d = [];
|
|
1495
1496
|
function f() {
|
|
1496
1497
|
c = !0;
|
|
1497
|
-
for (const b of
|
|
1498
|
+
for (const b of d)
|
|
1498
1499
|
b();
|
|
1499
1500
|
}
|
|
1500
1501
|
function m(b) {
|
|
1501
|
-
return
|
|
1502
|
-
const $ =
|
|
1503
|
-
$ !== -1 &&
|
|
1502
|
+
return d.push(b), () => {
|
|
1503
|
+
const $ = d.indexOf(b);
|
|
1504
|
+
$ !== -1 && d.splice($, 1);
|
|
1504
1505
|
};
|
|
1505
1506
|
}
|
|
1506
1507
|
function y(b, $) {
|
|
@@ -1615,14 +1616,14 @@ function di({ RStream: e, opts: t, startStream: n, cancelStream: i }) {
|
|
|
1615
1616
|
}
|
|
1616
1617
|
class hi {
|
|
1617
1618
|
constructor({ WStream: t, RStream: n, trySend: i, log: s }) {
|
|
1618
|
-
|
|
1619
|
-
|
|
1620
|
-
|
|
1621
|
-
|
|
1622
|
-
|
|
1623
|
-
|
|
1624
|
-
|
|
1625
|
-
|
|
1619
|
+
l(this, "trySend");
|
|
1620
|
+
l(this, "WStream");
|
|
1621
|
+
l(this, "RStream");
|
|
1622
|
+
l(this, "writeStreams", {});
|
|
1623
|
+
l(this, "startWriteStreamCbs", {});
|
|
1624
|
+
l(this, "readStreamIterators", {});
|
|
1625
|
+
l(this, "log");
|
|
1626
|
+
l(this, "activeStreams", /* @__PURE__ */ new Set());
|
|
1626
1627
|
this.WStream = t, this.RStream = n, this.trySend = i, this.log = s;
|
|
1627
1628
|
}
|
|
1628
1629
|
createWriteStream(t) {
|
|
@@ -1800,7 +1801,7 @@ function bi(e) {
|
|
|
1800
1801
|
);
|
|
1801
1802
|
const { onEvent: t = lt, onError: n = lt, onRetry: i = lt, onComment: s } = e;
|
|
1802
1803
|
let r = "", o = !0, a, u = "", c = "";
|
|
1803
|
-
function
|
|
1804
|
+
function d(w) {
|
|
1804
1805
|
const h = o ? w.replace(/^\xEF\xBB\xBF/, "") : w, [O, b] = gi(`${r}${h}`);
|
|
1805
1806
|
for (const $ of O)
|
|
1806
1807
|
f($);
|
|
@@ -1867,7 +1868,7 @@ function bi(e) {
|
|
|
1867
1868
|
function I(w = {}) {
|
|
1868
1869
|
r && w.consume && f(r), o = !0, a = void 0, u = "", c = "", r = "";
|
|
1869
1870
|
}
|
|
1870
|
-
return { feed:
|
|
1871
|
+
return { feed: d, reset: I };
|
|
1871
1872
|
}
|
|
1872
1873
|
function gi(e) {
|
|
1873
1874
|
const t = [];
|
|
@@ -1955,7 +1956,7 @@ class te extends EventTarget {
|
|
|
1955
1956
|
super(), x(this, Y), this.CONNECTING = 0, this.OPEN = 1, this.CLOSED = 2, x(this, V), x(this, we), x(this, ke), x(this, He), x(this, Xe), x(this, Le), x(this, Ce), x(this, We, null), x(this, he), x(this, Ee), x(this, Re, null), x(this, _e, null), x(this, Ue, null), x(this, wt, async (r) => {
|
|
1956
1957
|
var o;
|
|
1957
1958
|
S(this, Ee).reset();
|
|
1958
|
-
const { body: a, redirected: u, status: c, headers:
|
|
1959
|
+
const { body: a, redirected: u, status: c, headers: d } = r;
|
|
1959
1960
|
if (c === 204) {
|
|
1960
1961
|
ce(this, Y, De).call(this, "Server sent HTTP 204, not reconnecting", 204), this.close();
|
|
1961
1962
|
return;
|
|
@@ -1964,7 +1965,7 @@ class te extends EventTarget {
|
|
|
1964
1965
|
ce(this, Y, De).call(this, `Non-200 status code (${c})`, c);
|
|
1965
1966
|
return;
|
|
1966
1967
|
}
|
|
1967
|
-
if (!(
|
|
1968
|
+
if (!(d.get("content-type") || "").startsWith("text/event-stream")) {
|
|
1968
1969
|
ce(this, Y, De).call(this, 'Invalid content type, expected "text/event-stream"', c);
|
|
1969
1970
|
return;
|
|
1970
1971
|
}
|
|
@@ -2242,7 +2243,7 @@ function Oi(e, t, n) {
|
|
|
2242
2243
|
}
|
|
2243
2244
|
}), a = [], u = [], c = (h) => {
|
|
2244
2245
|
a.push(h);
|
|
2245
|
-
},
|
|
2246
|
+
}, d = (h) => {
|
|
2246
2247
|
a.splice(a.indexOf(h), 1);
|
|
2247
2248
|
}, f = (h) => {
|
|
2248
2249
|
u.push(h);
|
|
@@ -2376,7 +2377,7 @@ function Oi(e, t, n) {
|
|
|
2376
2377
|
get isClosed() {
|
|
2377
2378
|
return le(o) === "closed";
|
|
2378
2379
|
},
|
|
2379
|
-
[Symbol.asyncIterator]: Ii.bind(this, c, f,
|
|
2380
|
+
[Symbol.asyncIterator]: Ii.bind(this, c, f, d, () => 1)
|
|
2380
2381
|
};
|
|
2381
2382
|
}
|
|
2382
2383
|
var fe = {};
|
|
@@ -2495,8 +2496,8 @@ function Ri(e, t) {
|
|
|
2495
2496
|
};
|
|
2496
2497
|
let a = s + 1;
|
|
2497
2498
|
for (; a < i; ) {
|
|
2498
|
-
const u = kt(e, a, i), c = Et(e, a, u),
|
|
2499
|
-
switch (
|
|
2499
|
+
const u = kt(e, a, i), c = Et(e, a, u), d = c === -1 ? de(e, a, u) : de(e, a, c), f = c === -1 ? void 0 : de(e, c + 1, u);
|
|
2500
|
+
switch (d.toLowerCase()) {
|
|
2500
2501
|
case "httponly":
|
|
2501
2502
|
o.httpOnly = !0;
|
|
2502
2503
|
break;
|
|
@@ -2632,8 +2633,8 @@ function Li(e) {
|
|
|
2632
2633
|
return t = class {
|
|
2633
2634
|
constructor(r) {
|
|
2634
2635
|
Q(this, n);
|
|
2635
|
-
|
|
2636
|
-
|
|
2636
|
+
l(this, "source");
|
|
2637
|
+
l(this, "url");
|
|
2637
2638
|
this.url = r, this.source = G(this, n, Sn).call(this, r);
|
|
2638
2639
|
}
|
|
2639
2640
|
get onopen() {
|
|
@@ -2677,7 +2678,7 @@ function Li(e) {
|
|
|
2677
2678
|
});
|
|
2678
2679
|
}
|
|
2679
2680
|
});
|
|
2680
|
-
},
|
|
2681
|
+
}, l(t, "OPEN", te.OPEN), l(t, "CONNECTING", te.CONNECTING), l(t, "CLOSED", te.CLOSED), t;
|
|
2681
2682
|
}
|
|
2682
2683
|
function Wi(e) {
|
|
2683
2684
|
var n, i;
|
|
@@ -2695,7 +2696,7 @@ function Kt(e) {
|
|
|
2695
2696
|
}
|
|
2696
2697
|
class Fi {
|
|
2697
2698
|
constructor(t) {
|
|
2698
|
-
|
|
2699
|
+
l(this, "config");
|
|
2699
2700
|
this.config = t;
|
|
2700
2701
|
}
|
|
2701
2702
|
async getPresence(t, n) {
|
|
@@ -2707,7 +2708,7 @@ class Fi {
|
|
|
2707
2708
|
}
|
|
2708
2709
|
class zi {
|
|
2709
2710
|
constructor(t) {
|
|
2710
|
-
|
|
2711
|
+
l(this, "config");
|
|
2711
2712
|
/**
|
|
2712
2713
|
* Generates a magic code for the user with the given email.
|
|
2713
2714
|
* This is useful if you want to use your own email provider
|
|
@@ -2721,7 +2722,7 @@ class zi {
|
|
|
2721
2722
|
*
|
|
2722
2723
|
* @see https://instantdb.com/docs/backend#custom-magic-codes
|
|
2723
2724
|
*/
|
|
2724
|
-
|
|
2725
|
+
l(this, "generateMagicCode", async (t) => R(`${this.config.apiURI}/admin/magic_code?app_id=${this.config.appId}`, {
|
|
2725
2726
|
method: "POST",
|
|
2726
2727
|
headers: C(this.config),
|
|
2727
2728
|
body: JSON.stringify({ email: t })
|
|
@@ -2736,7 +2737,7 @@ class zi {
|
|
|
2736
2737
|
*
|
|
2737
2738
|
* @see https://instantdb.com/docs/backend#custom-magic-codes
|
|
2738
2739
|
*/
|
|
2739
|
-
|
|
2740
|
+
l(this, "sendMagicCode", async (t) => R(`${this.config.apiURI}/admin/send_magic_code?app_id=${this.config.appId}`, {
|
|
2740
2741
|
method: "POST",
|
|
2741
2742
|
headers: C(this.config),
|
|
2742
2743
|
body: JSON.stringify({ email: t })
|
|
@@ -2750,7 +2751,7 @@ class zi {
|
|
|
2750
2751
|
*
|
|
2751
2752
|
* @see https://instantdb.com/docs/backend#custom-magic-codes
|
|
2752
2753
|
*/
|
|
2753
|
-
|
|
2754
|
+
l(this, "verifyMagicCode", async (t, n) => {
|
|
2754
2755
|
const { user: i } = await R(`${this.config.apiURI}/admin/verify_magic_code?app_id=${this.config.appId}`, {
|
|
2755
2756
|
method: "POST",
|
|
2756
2757
|
headers: C(this.config),
|
|
@@ -2774,7 +2775,7 @@ class zi {
|
|
|
2774
2775
|
* })
|
|
2775
2776
|
* @see https://instantdb.com/docs/backend#custom-endpoints
|
|
2776
2777
|
*/
|
|
2777
|
-
|
|
2778
|
+
l(this, "verifyToken", async (t) => (await R(`${this.config.apiURI}/runtime/auth/verify_refresh_token?app_id=${this.config.appId}`, {
|
|
2778
2779
|
method: "POST",
|
|
2779
2780
|
headers: { "content-type": "application/json" },
|
|
2780
2781
|
body: JSON.stringify({
|
|
@@ -2795,7 +2796,7 @@ class zi {
|
|
|
2795
2796
|
*
|
|
2796
2797
|
* @see https://instantdb.com/docs/backend#retrieve-a-user
|
|
2797
2798
|
*/
|
|
2798
|
-
|
|
2799
|
+
l(this, "getUser", async (t) => {
|
|
2799
2800
|
const n = Object.entries(t).map(([s, r]) => `${s}=${encodeURIComponent(r)}`).join("&");
|
|
2800
2801
|
return (await R(`${this.config.apiURI}/admin/users?app_id=${this.config.appId}&${n}`, {
|
|
2801
2802
|
method: "GET",
|
|
@@ -2818,7 +2819,7 @@ class zi {
|
|
|
2818
2819
|
*
|
|
2819
2820
|
* @see https://instantdb.com/docs/backend#delete-a-user
|
|
2820
2821
|
*/
|
|
2821
|
-
|
|
2822
|
+
l(this, "deleteUser", async (t) => {
|
|
2822
2823
|
const n = Object.entries(t).map(([s, r]) => `${s}=${r}`);
|
|
2823
2824
|
return (await R(`${this.config.apiURI}/admin/users?app_id=${this.config.appId}&${n}`, {
|
|
2824
2825
|
method: "DELETE",
|
|
@@ -2832,7 +2833,7 @@ class zi {
|
|
|
2832
2833
|
* @param req The request containing a cookie synced with createInstantRouteHandler
|
|
2833
2834
|
* @param opts Allow disabling validation of refresh token
|
|
2834
2835
|
*/
|
|
2835
|
-
|
|
2836
|
+
l(this, "getUserFromRequest", async (t, n) => {
|
|
2836
2837
|
const i = t.headers.get("cookie") || "", s = $i(i), r = "instant_user_" + this.config.appId;
|
|
2837
2838
|
if (!s[r])
|
|
2838
2839
|
return null;
|
|
@@ -2861,8 +2862,8 @@ class zi {
|
|
|
2861
2862
|
const Xt = (e) => e && typeof e == "object" && typeof e.pipe == "function" && typeof e.read == "function", Vi = (e) => e && typeof e.getReader == "function";
|
|
2862
2863
|
class Yt {
|
|
2863
2864
|
constructor(t, n) {
|
|
2864
|
-
|
|
2865
|
-
|
|
2865
|
+
l(this, "config");
|
|
2866
|
+
l(this, "impersonationOpts");
|
|
2866
2867
|
/**
|
|
2867
2868
|
* Uploads file at the provided path. Accepts a Buffer or a Readable stream.
|
|
2868
2869
|
*
|
|
@@ -2871,7 +2872,7 @@ class Yt {
|
|
|
2871
2872
|
* const buffer = fs.readFileSync('demo.png');
|
|
2872
2873
|
* const isSuccess = await db.storage.uploadFile('photos/demo.png', buffer);
|
|
2873
2874
|
*/
|
|
2874
|
-
|
|
2875
|
+
l(this, "uploadFile", async (t, n, i = {}) => {
|
|
2875
2876
|
const s = {
|
|
2876
2877
|
...C(this.config, this.impersonationOpts),
|
|
2877
2878
|
path: t
|
|
@@ -2904,7 +2905,7 @@ class Yt {
|
|
|
2904
2905
|
*
|
|
2905
2906
|
* @see https://instantdb.com/docs/storage
|
|
2906
2907
|
*/
|
|
2907
|
-
|
|
2908
|
+
l(this, "delete", async (t) => R(`${this.config.apiURI}/admin/storage/files?app_id=${this.config.appId}&filename=${encodeURIComponent(t)}`, {
|
|
2908
2909
|
method: "DELETE",
|
|
2909
2910
|
headers: C(this.config, this.impersonationOpts)
|
|
2910
2911
|
}));
|
|
@@ -2919,7 +2920,7 @@ class Yt {
|
|
|
2919
2920
|
*
|
|
2920
2921
|
* @see https://instantdb.com/docs/storage
|
|
2921
2922
|
*/
|
|
2922
|
-
|
|
2923
|
+
l(this, "deleteMany", async (t) => R(`${this.config.apiURI}/admin/storage/files/delete?app_id=${this.config.appId}`, {
|
|
2923
2924
|
method: "POST",
|
|
2924
2925
|
headers: C(this.config, this.impersonationOpts),
|
|
2925
2926
|
body: JSON.stringify({ filenames: t })
|
|
@@ -2928,7 +2929,7 @@ class Yt {
|
|
|
2928
2929
|
* @deprecated. This method will be removed in the future. Use `uploadFile`
|
|
2929
2930
|
* instead
|
|
2930
2931
|
*/
|
|
2931
|
-
|
|
2932
|
+
l(this, "upload", async (t, n, i = {}) => {
|
|
2932
2933
|
const { data: s } = await R(`${this.config.apiURI}/admin/storage/signed-upload-url?app_id=${this.config.appId}`, {
|
|
2933
2934
|
method: "POST",
|
|
2934
2935
|
headers: C(this.config),
|
|
@@ -2950,7 +2951,7 @@ class Yt {
|
|
|
2950
2951
|
* @example
|
|
2951
2952
|
* const files = await db.query({ $files: {}})
|
|
2952
2953
|
*/
|
|
2953
|
-
|
|
2954
|
+
l(this, "list", async () => {
|
|
2954
2955
|
const { data: t } = await R(`${this.config.apiURI}/admin/storage/files?app_id=${this.config.appId}`, {
|
|
2955
2956
|
method: "GET",
|
|
2956
2957
|
headers: C(this.config)
|
|
@@ -2971,7 +2972,7 @@ class Yt {
|
|
|
2971
2972
|
* }
|
|
2972
2973
|
* })
|
|
2973
2974
|
*/
|
|
2974
|
-
|
|
2975
|
+
l(this, "getDownloadUrl", async (t) => {
|
|
2975
2976
|
const { data: n } = await R(`${this.config.apiURI}/admin/storage/signed-download-url?app_id=${this.config.appId}&filename=${encodeURIComponent(t)}`, {
|
|
2976
2977
|
method: "GET",
|
|
2977
2978
|
headers: C(this.config)
|
|
@@ -2994,7 +2995,7 @@ class Ji {
|
|
|
2994
2995
|
* console.log(chunk);
|
|
2995
2996
|
* }
|
|
2996
2997
|
*/
|
|
2997
|
-
|
|
2998
|
+
l(this, "createReadStream", (t) => g(this, Ae).call(this).createReadStream(t));
|
|
2998
2999
|
/**
|
|
2999
3000
|
* Creates a new WritableStream for the given clientId.
|
|
3000
3001
|
*
|
|
@@ -3004,7 +3005,7 @@ class Ji {
|
|
|
3004
3005
|
* writer.write('Hello world');
|
|
3005
3006
|
* writer.close();
|
|
3006
3007
|
*/
|
|
3007
|
-
|
|
3008
|
+
l(this, "createWriteStream", (t) => g(this, Ae).call(this).createWriteStream(t));
|
|
3008
3009
|
ae(this, Ae, t);
|
|
3009
3010
|
}
|
|
3010
3011
|
}
|
|
@@ -3023,17 +3024,17 @@ var M, Ie, N, L, A, In, Be, vn, On, $n, Ye, Ze, et, Ct, kn, tt;
|
|
|
3023
3024
|
const jt = class jt {
|
|
3024
3025
|
constructor(t) {
|
|
3025
3026
|
Q(this, A);
|
|
3026
|
-
|
|
3027
|
-
|
|
3028
|
-
|
|
3029
|
-
|
|
3030
|
-
|
|
3031
|
-
|
|
3027
|
+
l(this, "config");
|
|
3028
|
+
l(this, "auth");
|
|
3029
|
+
l(this, "storage");
|
|
3030
|
+
l(this, "streams");
|
|
3031
|
+
l(this, "rooms");
|
|
3032
|
+
l(this, "impersonationOpts");
|
|
3032
3033
|
Q(this, M, null);
|
|
3033
3034
|
Q(this, Ie, 0);
|
|
3034
3035
|
Q(this, N, null);
|
|
3035
3036
|
Q(this, L);
|
|
3036
|
-
|
|
3037
|
+
l(this, "tx", un());
|
|
3037
3038
|
/**
|
|
3038
3039
|
* Sometimes you want to scope queries to a specific user.
|
|
3039
3040
|
*
|
|
@@ -3043,7 +3044,7 @@ const jt = class jt {
|
|
|
3043
3044
|
* @example
|
|
3044
3045
|
* await db.asUser({email: "stopa@instantdb.com"}).query({ goals: {} })
|
|
3045
3046
|
*/
|
|
3046
|
-
|
|
3047
|
+
l(this, "asUser", (t) => {
|
|
3047
3048
|
const n = new jt({
|
|
3048
3049
|
...this.config
|
|
3049
3050
|
});
|
|
@@ -3064,7 +3065,7 @@ const jt = class jt {
|
|
|
3064
3065
|
* // all goals, _alongside_ their todos
|
|
3065
3066
|
* await db.query({ goals: { todos: {} } })
|
|
3066
3067
|
*/
|
|
3067
|
-
|
|
3068
|
+
l(this, "query", (t, n = {}) => {
|
|
3068
3069
|
t && n && "ruleParams" in n && (t = { $$ruleParams: n.ruleParams, ...t }), this.config.disableValidation || Ft(t, this.config.schema);
|
|
3069
3070
|
const i = n.fetchOpts || {}, s = i.headers || {};
|
|
3070
3071
|
return R(`${this.config.apiURI}/admin/query?app_id=${this.config.appId}`, {
|
|
@@ -3103,7 +3104,7 @@ const jt = class jt {
|
|
|
3103
3104
|
* db.tx.goals[goalId].link({todos: todoId}),
|
|
3104
3105
|
* ])
|
|
3105
3106
|
*/
|
|
3106
|
-
|
|
3107
|
+
l(this, "transact", (t) => (this.config.disableValidation || ai(t, this.config.schema), R(`${this.config.apiURI}/admin/transact?app_id=${this.config.appId}`, {
|
|
3107
3108
|
method: "POST",
|
|
3108
3109
|
headers: C(this.config, this.impersonationOpts),
|
|
3109
3110
|
body: JSON.stringify({
|
|
@@ -3132,7 +3133,7 @@ const jt = class jt {
|
|
|
3132
3133
|
* { rules: { goals: { allow: { read: "auth.id != null" } } }
|
|
3133
3134
|
* )
|
|
3134
3135
|
*/
|
|
3135
|
-
|
|
3136
|
+
l(this, "debugQuery", async (t, n) => {
|
|
3136
3137
|
t && n && "ruleParams" in n && (t = { $$ruleParams: n.ruleParams, ...t });
|
|
3137
3138
|
const i = { query: t, "rules-override": n == null ? void 0 : n.rules };
|
|
3138
3139
|
n != null && n.ip && (i["ip-override"] = n.ip), n != null && n.origin && (i["origin-override"] = n.origin);
|
|
@@ -3164,7 +3165,7 @@ const jt = class jt {
|
|
|
3164
3165
|
* { rules: { goals: { allow: { update: "auth.id != null" } } }
|
|
3165
3166
|
* )
|
|
3166
3167
|
*/
|
|
3167
|
-
|
|
3168
|
+
l(this, "debugTransact", (t, n) => {
|
|
3168
3169
|
const i = {
|
|
3169
3170
|
steps: Kt(t),
|
|
3170
3171
|
"rules-override": n == null ? void 0 : n.rules,
|
|
@@ -3359,14 +3360,14 @@ function qi(e) {
|
|
|
3359
3360
|
adminToken: n,
|
|
3360
3361
|
apiURI: i
|
|
3361
3362
|
});
|
|
3362
|
-
async function r(c,
|
|
3363
|
+
async function r(c, d, f) {
|
|
3363
3364
|
const m = s.streams.createWriteStream({
|
|
3364
3365
|
clientId: c,
|
|
3365
3366
|
waitUntil: e.waitUntil ?? void 0
|
|
3366
3367
|
});
|
|
3367
3368
|
try {
|
|
3368
3369
|
const y = await m.streamId();
|
|
3369
|
-
|
|
3370
|
+
d().pipeTo(m);
|
|
3370
3371
|
const w = s.streams.createReadStream({ streamId: y });
|
|
3371
3372
|
return f ? w.pipeThrough(
|
|
3372
3373
|
Ve(f)
|
|
@@ -3378,12 +3379,12 @@ function qi(e) {
|
|
|
3378
3379
|
) : I;
|
|
3379
3380
|
}
|
|
3380
3381
|
}
|
|
3381
|
-
async function o(c,
|
|
3382
|
+
async function o(c, d) {
|
|
3382
3383
|
const f = s.streams.createReadStream({ clientId: c });
|
|
3383
|
-
return
|
|
3384
|
+
return d ? f.pipeThrough(Ve(d)) : f;
|
|
3384
3385
|
}
|
|
3385
|
-
async function a(c,
|
|
3386
|
-
const m =
|
|
3386
|
+
async function a(c, d, f) {
|
|
3387
|
+
const m = d(), y = s.streams.createWriteStream({
|
|
3387
3388
|
clientId: c,
|
|
3388
3389
|
waitUntil: e.waitUntil ?? void 0
|
|
3389
3390
|
});
|
|
@@ -3393,9 +3394,9 @@ function qi(e) {
|
|
|
3393
3394
|
}
|
|
3394
3395
|
async function u(c) {
|
|
3395
3396
|
var m;
|
|
3396
|
-
const
|
|
3397
|
+
const d = await s.query({
|
|
3397
3398
|
$streams: { $: { where: { clientId: c } } }
|
|
3398
|
-
}), f = (m =
|
|
3399
|
+
}), f = (m = d == null ? void 0 : d.$streams) == null ? void 0 : m[0];
|
|
3399
3400
|
return f != null && f.done ? "DONE" : f ? !0 : null;
|
|
3400
3401
|
}
|
|
3401
3402
|
return {
|
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
(function($,_){typeof exports=="object"&&typeof module<"u"?_(exports):typeof define=="function"&&define.amd?define(["exports"],_):($=typeof globalThis<"u"?globalThis:$||self,_($.instant={}))})(this,function($){"use strict";var Qi=Object.defineProperty;var In=$=>{throw TypeError($)};var Gi=($,_,x)=>_ in $?Qi($,_,{enumerable:!0,configurable:!0,writable:!0,value:x}):$[_]=x;var d=($,_,x)=>Gi($,typeof _!="symbol"?_+"":_,x),Mt=($,_,x)=>_.has($)||In("Cannot "+x);var g=($,_,x)=>(Mt($,_,"read from private field"),x?x.call($):_.get($)),K=($,_,x)=>_.has($)?In("Cannot add the same private member more than once"):_ instanceof WeakSet?_.add($):_.set($,x),he=($,_,x,R)=>(Mt($,_,"write to private field"),R?R.call($,x):_.set($,x),x),X=($,_,x)=>(Mt($,_,"access private method"),x);var Ue,N,Oe,W,F,U,On,st,$n,kn,En,et,tt,nt,Ut,_n,it;const _=/^(?:[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 x(e){return typeof e=="string"&&_.test(e)}const R=[];for(let e=0;e<256;++e)R.push((e+256).toString(16).slice(1));function Cn(e,t=0){return(R[e[t+0]]+R[e[t+1]]+R[e[t+2]]+R[e[t+3]]+"-"+R[e[t+4]]+R[e[t+5]]+"-"+R[e[t+6]]+R[e[t+7]]+"-"+R[e[t+8]]+R[e[t+9]]+"-"+R[e[t+10]]+R[e[t+11]]+R[e[t+12]]+R[e[t+13]]+R[e[t+14]]+R[e[t+15]]).toLowerCase()}let rt;const xn=new Uint8Array(16);function Tn(){if(!rt){if(typeof crypto>"u"||!crypto.getRandomValues)throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");rt=crypto.getRandomValues.bind(crypto)}return rt(xn)}const Dt={randomUUID:typeof crypto<"u"&&crypto.randomUUID&&crypto.randomUUID.bind(crypto)};function Rn(e,t,n){var s;if(Dt.randomUUID&&!e)return Dt.randomUUID();e=e||{};const i=e.random??((s=e.rng)==null?void 0:s.call(e))??Tn();if(i.length<16)throw new Error("Random bytes length must be >= 16");return i[6]=i[6]&15|64,i[8]=i[8]&63|128,Cn(i)}const P={Remove:"remove",Replace:"replace",Add:"add"},Nt=Symbol.for("__MUTATIVE_PROXY_DRAFT__"),Qe=Symbol.iterator,Y={mutable:"mutable",immutable:"immutable"},ot={};function De(e,t){return e instanceof Map?e.has(t):Object.prototype.hasOwnProperty.call(e,t)}function Lt(e,t){if(t in e){let n=Reflect.getPrototypeOf(e);for(;n;){const i=Reflect.getOwnPropertyDescriptor(n,t);if(i)return i;n=Reflect.getPrototypeOf(n)}}}function Wt(e){return Object.getPrototypeOf(e)===Set.prototype}function Ft(e){return Object.getPrototypeOf(e)===Map.prototype}function H(e){var t;return(t=e.copy)!==null&&t!==void 0?t:e.original}function at(e){return!!E(e)}function E(e){return typeof e!="object"?null:e==null?void 0:e[Nt]}function ct(e){var t;const n=E(e);return n?(t=n.copy)!==null&&t!==void 0?t:n.original:e}function ge(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,Y))===Y.immutable||typeof n=="function")}function zt(e,t=[]){if(Object.hasOwnProperty.call(e,"key")){const n=e.parent.copy,i=E(pe(n,e.key));if(i!==null&&(i==null?void 0:i.original)!==e.original)return null;const s=e.parent.type===3,r=s?Array.from(e.parent.setMap.keys()).indexOf(e.key):e.key;if(!(s&&n.size>r||De(n,r)))return null;t.push(r)}if(e.parent)return zt(e.parent,t);t.reverse();try{An(e.copy,t)}catch{return null}return t}function Ne(e){return Array.isArray(e)?1:e instanceof Map?2:e instanceof Set?3:0}function pe(e,t){return Ne(e)===2?e.get(t):e[t]}function ut(e,t,n){Ne(e)===2?e.set(t,n):e[t]=n}function ft(e,t){const n=E(e);return(n?H(n):e)[t]}function we(e,t){return e===t?e!==0||1/e===1/t:e!==e&&t!==t}function Se(e,t){return t?e:[""].concat(e).map(n=>{const i=`${n}`;return i.indexOf("/")===-1&&i.indexOf("~")===-1?i:i.replace(/~/g,"~0").replace(/\//g,"~1")}).join("/")}function An(e,t){for(let n=0;n<t.length-1;n+=1){const i=t[n];if(e=pe(Ne(e)===3?Array.from(e):e,i),typeof e!="object")throw new Error(`Cannot resolve patch at '${t.join("/")}'.`)}return e}function Pn(e){const t=Object.create(Object.getPrototypeOf(e));return Reflect.ownKeys(e).forEach(n=>{let i=Reflect.getOwnPropertyDescriptor(e,n);if(i.enumerable&&i.configurable&&i.writable){t[n]=e[n];return}i.writable||(i.writable=!0,i.configurable=!0),(i.get||i.set)&&(i={configurable:!0,writable:!0,enumerable:i.enumerable,value:e[n]}),Reflect.defineProperty(t,n,i)}),t}const jn=Object.prototype.propertyIsEnumerable;function Mn(e,t){let n;if(Array.isArray(e))return Array.prototype.concat.call(e);if(e instanceof Set){if(!Wt(e)){const i=Object.getPrototypeOf(e).constructor;return new i(e.values())}return Set.prototype.difference?Set.prototype.difference.call(e,new Set):new Set(e.values())}else if(e instanceof Map){if(!Ft(e)){const i=Object.getPrototypeOf(e).constructor;return new i(e)}return new Map(e)}else if(t!=null&&t.mark&&(n=t.mark(e,Y),n!==void 0)&&n!==Y.mutable){if(n===Y.immutable)return Pn(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 i={};return Object.keys(e).forEach(s=>{i[s]=e[s]}),Object.getOwnPropertySymbols(e).forEach(s=>{jn.call(e,s)&&(i[s]=e[s])}),i}else throw new Error("Please check mark() to ensure that it is a stable marker draftable function.")}function L(e){e.copy||(e.copy=Mn(e.original,e.options))}function Le(e){if(!ge(e))return ct(e);if(Array.isArray(e))return e.map(Le);if(e instanceof Map){const n=Array.from(e.entries()).map(([i,s])=>[i,Le(s)]);if(!Ft(e)){const i=Object.getPrototypeOf(e).constructor;return new i(n)}return new Map(n)}if(e instanceof Set){const n=Array.from(e).map(Le);if(!Wt(e)){const i=Object.getPrototypeOf(e).constructor;return new i(n)}return new Set(n)}const t=Object.create(Object.getPrototypeOf(e));for(const n in e)t[n]=Le(e[n]);return t}function Ge(e){return at(e)?Le(e):e}function ie(e){var t;e.assignedMap=(t=e.assignedMap)!==null&&t!==void 0?t:new Map,e.operated||(e.operated=!0,e.parent&&ie(e.parent))}function Un(e,t){const n=Ne(e);if(n===0)Reflect.ownKeys(e).forEach(i=>{t(i,e[i],e)});else if(n===1){let i=0;for(const s of e)t(i,s,e),i+=1}else e.forEach((i,s)=>t(s,i,e))}function Vt(e,t,n){if(at(e)||!ge(e,n)||t.has(e)||Object.isFrozen(e))return;const i=e instanceof Set,s=i?new Map:void 0;if(t.add(e),Un(e,(r,o)=>{var a;if(at(o)){const u=E(o);L(u);const c=!((a=u.assignedMap)===null||a===void 0)&&a.size||u.operated?u.copy:u.original;ut(i?s:e,r,c)}else Vt(o,t,n)}),s){const r=e,o=Array.from(r);r.clear(),o.forEach(a=>{r.add(s.has(a)?s.get(a):a)})}}function Dn(e,t){const n=e.type===3?e.setMap:e.copy;e.finalities.revoke.length>1&&e.assignedMap.get(t)&&n&&Vt(pe(n,t),e.finalities.handledSet,e.options)}function lt(e){e.type===3&&e.copy&&(e.copy.clear(),e.setMap.forEach(t=>{e.copy.add(ct(t))}))}function dt(e,t,n,i){if(e.operated&&e.assignedMap&&e.assignedMap.size>0&&!e.finalized){if(n&&i){const r=zt(e);r&&t(e,r,n,i)}e.finalized=!0}}function ht(e,t,n,i){const s=E(n);s&&(s.callbacks||(s.callbacks=[]),s.callbacks.push((r,o)=>{var a;const u=e.type===3?e.setMap:e.copy;if(we(pe(u,t),n)){let c=s.original;s.copy&&(c=s.copy),lt(e),dt(e,i,r,o),e.options.enableAutoFreeze&&(e.options.updatedValues=(a=e.options.updatedValues)!==null&&a!==void 0?a:new WeakMap,e.options.updatedValues.set(c,s.original)),ut(u,t,c)}}),e.options.enableAutoFreeze&&s.finalities!==e.finalities&&(e.options.enableAutoFreeze=!1)),ge(n,e.options)&&e.finalities.draft.push(()=>{const r=e.type===3?e.setMap:e.copy;we(pe(r,t),n)&&Dn(e,t)})}function Nn(e,t,n,i,s){let{original:r,assignedMap:o,options:a}=e,u=e.copy;u.length<r.length&&([r,u]=[u,r],[n,i]=[i,n]);for(let c=0;c<r.length;c+=1)if(o.get(c.toString())&&u[c]!==r[c]){const l=t.concat([c]),f=Se(l,s);n.push({op:P.Replace,path:f,value:Ge(u[c])}),i.push({op:P.Replace,path:f,value:Ge(r[c])})}for(let c=r.length;c<u.length;c+=1){const l=t.concat([c]),f=Se(l,s);n.push({op:P.Add,path:f,value:Ge(u[c])})}if(r.length<u.length){const{arrayLengthAssignment:c=!0}=a.enablePatches;if(c){const l=t.concat(["length"]),f=Se(l,s);i.push({op:P.Replace,path:f,value:r.length})}else for(let l=u.length;r.length<l;l-=1){const f=t.concat([l-1]),m=Se(f,s);i.push({op:P.Remove,path:m})}}}function Ln({original:e,copy:t,assignedMap:n},i,s,r,o){n.forEach((a,u)=>{const c=pe(e,u),l=Ge(pe(t,u)),f=a?De(e,u)?P.Replace:P.Add:P.Remove;if(we(c,l)&&f===P.Replace)return;const m=i.concat(u),y=Se(m,o);s.push(f===P.Remove?{op:f,path:y}:{op:f,path:y,value:l}),r.push(f===P.Add?{op:P.Remove,path:y}:f===P.Remove?{op:P.Add,path:y,value:c}:{op:P.Replace,path:y,value:c})})}function Wn({original:e,copy:t},n,i,s,r){let o=0;e.forEach(a=>{if(!t.has(a)){const u=n.concat([o]),c=Se(u,r);i.push({op:P.Remove,path:c,value:a}),s.unshift({op:P.Add,path:c,value:a})}o+=1}),o=0,t.forEach(a=>{if(!e.has(a)){const u=n.concat([o]),c=Se(u,r);i.push({op:P.Add,path:c,value:a}),s.unshift({op:P.Remove,path:c,value:a})}o+=1})}function We(e,t,n,i){const{pathAsArray:s=!0}=e.options.enablePatches;switch(e.type){case 0:case 2:return Ln(e,t,n,i,s);case 1:return Nn(e,t,n,i,s);case 3:return Wn(e,t,n,i,s)}}const He=(e,t,n=!1)=>{if(typeof e=="object"&&e!==null&&(!ge(e,t)||n))throw new Error("Strict mode: Mutable data cannot be accessed directly, please use 'unsafe(callback)' wrap.")},pt={get size(){return H(E(this)).size},has(e){return H(E(this)).has(e)},set(e,t){const n=E(this),i=H(n);return(!i.has(e)||!we(i.get(e),t))&&(L(n),ie(n),n.assignedMap.set(e,!0),n.copy.set(e,t),ht(n,e,t,We)),this},delete(e){if(!this.has(e))return!1;const t=E(this);return L(t),ie(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){L(e),ie(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);H(n).forEach((i,s)=>{e.call(t,this.get(s),s,this)})},get(e){var t,n;const i=E(this),s=H(i).get(e),r=((n=(t=i.options).mark)===null||n===void 0?void 0:n.call(t,s,Y))===Y.mutable;if(i.options.strict&&He(s,i.options,r),r||i.finalized||!ge(s,i.options)||s!==i.original.get(e))return s;const o=ot.createDraft({original:s,parentDraft:i,key:e,finalities:i.finalities,options:i.options});return L(i),i.copy.set(e,o),o},keys(){return H(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()}},Fn=Reflect.ownKeys(pt),Jt=(e,t,{isValuesIterator:n})=>()=>{var i,s;const r=t.next();if(r.done)return r;const o=r.value;let a=e.setMap.get(o);const u=E(a),c=((s=(i=e.options).mark)===null||s===void 0?void 0:s.call(i,a,Y))===Y.mutable;if(e.options.strict&&He(o,e.options,c),!c&&!u&&ge(o,e.options)&&!e.finalized&&e.original.has(o)){const l=ot.createDraft({original:o,parentDraft:e,key:o,finalities:e.finalities,options:e.options});e.setMap.set(o,l),a=l}else u&&(a=u.proxy);return{done:!1,value:n?a:[a,a]}},Be={get size(){return E(this).setMap.size},has(e){const t=E(this);if(t.setMap.has(e))return!0;L(t);const n=E(e);return!!(n&&t.setMap.has(n.original))},add(e){const t=E(this);return this.has(e)||(L(t),ie(t),t.assignedMap.set(e,!0),t.setMap.set(e,e),ht(t,e,e,We)),this},delete(e){if(!this.has(e))return!1;const t=E(this);L(t),ie(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);L(e),ie(e);for(const t of e.original)e.assignedMap.set(t,!1);e.setMap.clear()},values(){const e=E(this);L(e);const t=e.setMap.keys();return{[Symbol.iterator]:()=>this.values(),next:Jt(e,t,{isValuesIterator:!0})}},entries(){const e=E(this);L(e);const t=e.setMap.keys();return{[Symbol.iterator]:()=>this.entries(),next:Jt(e,t,{isValuesIterator:!1})}},keys(){return this.values()},[Qe](){return this.values()},forEach(e,t){const n=this.values();let i=n.next();for(;!i.done;)e.call(t,i.value,i.value,this),i=n.next()}};Set.prototype.difference&&Object.assign(Be,{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 zn=Reflect.ownKeys(Be),Qt=new WeakSet,Gt={get(e,t,n){var i,s;const r=(i=e.copy)===null||i===void 0?void 0:i[t];if(r&&Qt.has(r))return r;if(t===Nt)return e;let o;if(e.options.mark){const c=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(c,Y),o===Y.mutable)return e.options.strict&&He(c,e.options,!0),c}const a=H(e);if(a instanceof Map&&Fn.includes(t)){if(t==="size")return Object.getOwnPropertyDescriptor(pt,"size").get.call(e.proxy);const c=pt[t];if(c)return c.bind(e.proxy)}if(a instanceof Set&&zn.includes(t)){if(t==="size")return Object.getOwnPropertyDescriptor(Be,"size").get.call(e.proxy);const c=Be[t];if(c)return c.bind(e.proxy)}if(!De(a,t)){const c=Lt(a,t);return c?"value"in c?c.value:(s=c.get)===null||s===void 0?void 0:s.call(e.proxy):void 0}const u=a[t];if(e.options.strict&&He(u,e.options),e.finalized||!ge(u,e.options))return u;if(u===ft(e.original,t)){if(L(e),e.copy[t]=Ht({original:e.original[t],parentDraft:e,key:e.type===1?Number(t):t,finalities:e.finalities,options:e.options}),typeof o=="function"){const c=E(e.copy[t]);return L(c),ie(c),c.copy}return e.copy[t]}return u},set(e,t,n){var i;if(e.type===3||e.type===2)throw new Error("Map/Set draft does not support any property assignment.");let s;if(e.type===1&&t!=="length"&&!(Number.isInteger(s=Number(t))&&s>=0&&(t===0||s===0||String(s)===String(t))))throw new Error("Only supports setting array indices and the 'length' property.");const r=Lt(H(e),t);if(r!=null&&r.set)return r.set.call(e.proxy,n),!0;const o=ft(H(e),t),a=E(o);return a&&we(a.original,n)?(e.copy[t]=n,e.assignedMap=(i=e.assignedMap)!==null&&i!==void 0?i:new Map,e.assignedMap.set(t,!1),!0):(we(n,o)&&(n!==void 0||De(e.original,t))||(L(e),ie(e),De(e.original,t)&&we(n,e.original[t])?e.assignedMap.delete(t):e.assignedMap.set(t,!0),e.copy[t]=n,ht(e,t,n,We)),!0)},has(e,t){return t in H(e)},ownKeys(e){return Reflect.ownKeys(H(e))},getOwnPropertyDescriptor(e,t){const n=H(e),i=Reflect.getOwnPropertyDescriptor(n,t);return i&&{writable:!0,configurable:e.type!==1||t!=="length",enumerable:i.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?Gt.set.call(this,e,t,void 0,e.proxy):(ft(e.original,t)!==void 0||t in e.original?(L(e),ie(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 Ht(e){const{original:t,parentDraft:n,key:i,finalities:s,options:r}=e,o=Ne(t),a={type:o,finalized:!1,parent:n,original:t,copy:null,proxy:null,finalities:s,options:r,setMap:o===3?new Map(t.entries()):void 0};(i||"key"in e)&&(a.key=i);const{proxy:u,revoke:c}=Proxy.revocable(o===1?Object.assign([],a):a,Gt);if(s.revoke.push(c),Qt.add(u),a.proxy=u,n){const l=n;l.finalities.draft.push((f,m)=>{var y,I;const w=E(u);let h=l.type===3?l.setMap:l.copy;const O=pe(h,i),b=E(O);if(b){let k=b.original;b.operated&&(k=ct(O)),lt(b),dt(b,We,f,m),l.options.enableAutoFreeze&&(l.options.updatedValues=(y=l.options.updatedValues)!==null&&y!==void 0?y:new WeakMap,l.options.updatedValues.set(k,b.original)),ut(h,i,k)}(I=w.callbacks)===null||I===void 0||I.forEach(k=>{k(f,m)})})}else{const l=E(u);l.finalities.draft.push((f,m)=>{lt(l),dt(l,We,f,m)})}return u}ot.createDraft=Ht,Object.prototype.constructor.toString();function Ce(){return Rn()}function Vn(e,t){return e.localeCompare(t)}function Jn(){let e=Vn;if(typeof Intl=="object"&&Intl.hasOwnProperty("Collator"))try{e=Intl.Collator("en-US").compare}catch{}return e}Jn();function Qn(){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 Gn=Qn();function qe(e,t,n){const i={__etype:e,__ops:n};return new Proxy(i,{get:(s,r)=>{if(r==="__ops")return n;if(r==="__etype")return e;if(Gn.has(r))return(o,a)=>qe(e,t,[...n,a?[r,e,t,o,a]:[r,e,t,o]])}})}function Hn(e,t){return`lookup__${e}__${JSON.stringify(t)}`}function Bt(e){return e.startsWith("lookup__")}function qt(e){const[t,n,...i]=e.split("__");return[n,JSON.parse(i.join("__"))]}function Bn(e){return new Proxy({__etype:e},{get(t,n){if(n==="lookup")return(s,r)=>qe(e,qt(Hn(s,r)),[]);if(n==="__etype")return e;const i=n;return Bt(i)?qe(e,qt(i),[]):qe(e,i,[])}})}function Kt(){return new Proxy({},{get(e,t){return Bn(t)}})}Kt();function qn(e){return e.__ops}class B extends Error{constructor(n,i){super(n);d(this,"hint");this.hint=i;const s=new.target.prototype;Object.setPrototypeOf&&Object.setPrototypeOf(this,s),Error.captureStackTrace&&Error.captureStackTrace(this,B),this.name="InstantError"}get[Symbol.toStringTag](){return"InstantError"}}class Ie extends B{constructor(n){var r;const i=((r=n.body)==null?void 0:r.message)||`API Error (${n.status})`;super(i,n.body.hint);d(this,"body");d(this,"status");const s=new.target.prototype;Object.setPrototypeOf&&Object.setPrototypeOf(this,s),Error.captureStackTrace&&Error.captureStackTrace(this,Ie),this.name="InstantAPIError",this.status=n.status,this.body=n.body}get[Symbol.toStringTag](){return"InstantAPIError"}}typeof window<"u"&&typeof window.localStorage<"u"&&(window.localStorage.getItem("devBackend"),window.localStorage.getItem("__instantLogging"),window.localStorage.getItem("__devtoolLocalDash"));const xe="v0.22.155";class oe{constructor(t,n,i,s={indexed:!1,unique:!1}){d(this,"valueType");d(this,"required");d(this,"isIndexed");d(this,"config");d(this,"metadata",{});this.valueType=t,this.required=n,this.isIndexed=i,this.config=s}clientRequired(){return new oe(this.valueType,!1,this.isIndexed,this.config)}optional(){return new oe(this.valueType,!1,this.isIndexed,this.config)}unique(){return new oe(this.valueType,this.required,this.isIndexed,{...this.config,unique:!0})}indexed(){return new oe(this.valueType,this.required,!0,{...this.config,indexed:!0})}}class C extends Error{constructor(t,n){const i=n?`At path '${n}': ${t}`:t;super(i),this.name="QueryValidationError"}}const Xt=["where","order","limit","last","first","offset","after","before","fields","aggregate"],Kn=e=>e.valueType||"unknown",Yt=(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}},Xn=(e,t,n,i,s,r,o)=>{const a=r.valueType==="json",u=(c,l,f)=>{if(!Yt(f,l,a))throw new C(`Invalid value for operator '${c}' on attribute '${i}' in entity '${s}'. Expected ${l}, but received: ${typeof f}`,o)};switch(e){case"in":case"$in":if(!Array.isArray(t))throw new C(`Operator '${e}' for attribute '${i}' in entity '${s}' must be an array, but received: ${typeof t}`,o);for(const c of t)u(e,n,c);break;case"$not":case"$ne":case"$gt":case"$lt":case"$gte":case"$lte":u(e,n,t);break;case"$like":case"$ilike":if(u(e,"string",t),e==="$ilike"&&!r.isIndexed)throw new C(`Operator '${e}' can only be used with indexed attributes, but '${i}' in entity '${s}' is not indexed`,o);break;case"$isNull":u(e,"boolean",t);break;default:throw new C(`Unknown operator '${e}' for attribute '${i}' in entity '${s}'`,o)}},Te=(e,t,n,i,s)=>{const r=Kn(n),o=n.valueType==="json";if(typeof e=="object"&&e!==null&&!Array.isArray(e)){if(o)return;const u=e;for(const[c,l]of Object.entries(u))Xn(c,l,r,t,i,n,`${s}.${c}`)}else if(!Yt(e,r,o))throw new C(`Invalid value for attribute '${t}' in entity '${i}'. Expected ${r}, but received: ${typeof e}`,s)},Yn=(e,t,n,i,s)=>{const r=e.split(".");if(r.length<2)throw new C(`Invalid dot notation path '${e}'. Must contain at least one dot.`,s);let o=n;for(let l=0;l<r.length-1;l++){const f=r[l],m=i.entities[o];if(!m)throw new C(`Entity '${o}' does not exist in schema while traversing dot notation path '${e}'.`,s);const y=m.links[f];if(!y){const I=Object.keys(m.links);throw new C(`Link '${f}' does not exist on entity '${o}' in dot notation path '${e}'. Available links: ${I.length>0?I.join(", "):"none"}`,s)}o=y.entityName}const a=r[r.length-1],u=i.entities[o];if(!u)throw new C(`Target entity '${o}' does not exist in schema for dot notation path '${e}'.`,s);if(a==="id"){if(typeof t=="string"&&!x(t))throw new C(`Invalid value for id field in entity '${o}'. Expected a UUID, but received: ${t}`,s);Te(t,e,new oe("string",!1,!0),n,s);return}const c=u.attrs[a];if(Object.keys(u.links).includes(a)){if(typeof t=="string"&&!x(t))throw new C(`Invalid value for link '${a}' in entity '${o}'. Expected a UUID, but received: ${t}`,s);Te(t,e,new oe("string",!1,!0),n,s);return}if(!c){const l=Object.keys(u.attrs);throw new C(`Attribute '${a}' does not exist on entity '${o}' in dot notation path '${e}'. Available attributes: ${l.length>0?l.join(", ")+", id":"id"}`,s)}Te(t,e,c,n,s)},Zt=(e,t,n,i)=>{for(const[s,r]of Object.entries(e)){if(s==="or"||s==="and"){if(Array.isArray(r))for(const c of r)typeof c=="object"&&c!==null&&Zt(c,t,n,`${i}.${s}[${c}]`);continue}if(s==="id"){Te(r,"id",new oe("string",!1,!0),t,`${i}.id`);continue}if(s.includes(".")){Yn(s,r,t,n,`${i}.${s}`);continue}const o=n.entities[t];if(!o)continue;const a=o.attrs[s],u=o.links[s];if(!a&&!u){const c=Object.keys(o.attrs),l=Object.keys(o.links);throw new C(`Attribute or link '${s}' does not exist on entity '${t}'. Available attributes: ${c.length>0?c.join(", "):"none"}. Available links: ${l.length>0?l.join(", "):"none"}`,`${i}.${s}`)}if(a)Te(r,s,a,t,`${i}.${s}`);else if(u){if(typeof r=="string"&&!x(r))throw new C(`Invalid value for link '${s}' in entity '${t}'. Expected a UUID, but received: ${r}`,`${i}.${s}`);const c=new oe("string",!1,!0);Te(r,s,c,t,`${i}.${s}`)}}},Zn=(e,t,n,i,s=0)=>{for(const o of Object.keys(e))if(!Xt.includes(o))throw new C(`Invalid query parameter '${o}' in $ object. Valid parameters are: ${Xt.join(", ")}. Found: ${o}`,i);const r=["offset","before","after","first","last"];for(const o of r)if(e[o]!==void 0&&s>0)throw new C(`'${o}' can only be used on top-level namespaces. It cannot be used in nested queries.`,i);if(e.where&&n){if(typeof e.where!="object"||e.where===null)throw new C(`'where' clause must be an object in entity '${t}', but received: ${typeof e.where}`,i?`${i}.where`:void 0);Zt(e.where,t,n,i?`${i}.where`:"where")}},en=(e,t,n,i,s=0)=>{var r;if(!e||typeof e!="object")throw new C(`Query part for entity '${t}' must be an object, but received: ${typeof e}`,i);for(const o of Object.keys(e))if(o!=="$"){if(n&&!(o in n.entities[t].links)){const u=Object.keys(n.entities[t].links);throw new C(`Link '${o}' does not exist on entity '${t}'. Available links: ${u.length>0?u.join(", "):"none"}`,`${i}.${o}`)}const a=e[o];if(typeof a=="object"&&a!==null){const u=(r=n==null?void 0:n.entities[t].links[o])==null?void 0:r.entityName;u&&en(a,u,n,`${i}.${o}`,s+1)}}else{const a=e[o];if(typeof a!="object"||a===null)throw new C(`Query parameter '$' must be an object in entity '${t}', but received: ${typeof a}`,`${i}.$`);Zn(a,t,n,`${i}.$`,s)}},tn=(e,t)=>{if(typeof e!="object"||e===null)throw new C(`Query must be an object, but received: ${typeof e}${e===null?" (null)":""}`);if(Array.isArray(e))throw new C(`Query must be an object, but received: ${typeof e}`);const n=e;for(const i of Object.keys(n)){if(Array.isArray(e[i]))throw new C(`Query keys must be strings, but found key of type: ${typeof i}`,i);if(typeof i!="string")throw new C(`Query keys must be strings, but found key of type: ${typeof i}`,i);if(i!=="$$ruleParams"){if(t&&!t.entities[i]){const s=Object.keys(t.entities);throw new C(`Entity '${i}' does not exist in schema. Available entities: ${s.length>0?s.join(", "):"none"}`,i)}en(n[i],i,t,i,0)}}},nn=e=>typeof e!="string"?!1:Bt(e)?!0:x(e);class q extends Error{constructor(t){super(t),this.name="TransactionValidationError"}}const sn=e=>e.length>0?e.join(", "):"none",ei=(e,t)=>new q(`Entity '${e}' does not exist in schema. Available entities: ${sn(t)}`),mt={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},ti=(e,t)=>{var n;return e==null?!0:((n=mt[t.valueType])==null?void 0:n.call(mt,e))??!1},rn=(e,t)=>{const n=t.entities[e];if(!n)throw ei(e,Object.keys(t.entities));return n},yt=(e,t,n)=>{const i=rn(e,n);if(typeof t!="object"||t===null)throw new q(`Arguments for data operation on entity '${e}' must be an object, but received: ${typeof t}`);for(const[s,r]of Object.entries(t)){if(s==="id")continue;const o=i.attrs[s];if(o&&!ti(r,o))throw new q(`Invalid value for attribute '${s}' in entity '${e}'. Expected ${o.valueType}, but received: ${typeof r}`)}},on=(e,t,n)=>{const i=rn(e,n);if(typeof t!="object"||t===null)throw new q(`Arguments for link operation on entity '${e}' must be an object, but received: ${typeof t}`);for(const[s,r]of Object.entries(t)){if(!i.links[s]){const a=Object.keys(i.links);throw new q(`Link '${s}' does not exist on entity '${e}'. Available links: ${sn(a)}`)}if(r!=null){if(Array.isArray(r)){for(const a of r)if(!nn(a))throw new q(`Invalid entity ID in link '${s}' for entity '${e}'. Expected a UUID or a lookup, but received: ${a}`)}else if(!nn(r))throw new q(`Invalid UUID in link '${s}' for entity '${e}'. Expected a UUID, but received: ${r}`)}}},ni={create:yt,update:yt,merge:yt,link:on,unlink:on,delete:()=>{}},ii=(e,t)=>{if(!t)return;const[n,i,s,r]=e;if(!Array.isArray(s)&&!x(s))throw new q(`Invalid id for entity '${i}'. Expected a UUID, but received: ${s}`);if(typeof i!="string")throw new q(`Entity name must be a string, but received: ${typeof i}`);const o=ni[n];o&&r!==void 0&&o(i,r,t)},si=(e,t)=>{const n=Array.isArray(e)?e:[e];for(const i of n){if(!i||typeof i!="object")throw new q(`Transaction chunk must be an object, but received: ${typeof i}`);if(!Array.isArray(i.__ops))throw new q(`Transaction chunk must have __ops array, but received: ${typeof i.__ops}`);for(const s of i.__ops){if(!Array.isArray(s))throw new q(`Transaction operation must be an array, but received: ${typeof s}`);ii(s,t)}}};let ri=0;class oi{constructor(t,n,i){d(this,"type","sse");d(this,"initParams",null);d(this,"sendQueue",[]);d(this,"sendPromise");d(this,"closeFired",!1);d(this,"sseInitTimeout");d(this,"ES");d(this,"messageUrl");d(this,"conn");d(this,"url");d(this,"id");d(this,"onopen");d(this,"onmessage");d(this,"onclose");d(this,"onerror");this.id=`${this.type}_${ri++}`,this.url=n,this.messageUrl=i||this.url,this.ES=t,this.conn=new t(n),this.sseInitTimeout=setTimeout(()=>{this.initParams||this.handleError()},1e4),this.conn.onmessage=s=>{const r=JSON.parse(s.data);if(Array.isArray(r))for(const o of r)this.handleMessage(o);else this.handleMessage(r)},this.conn.onerror=s=>{this.handleError()}}handleMessage(t){if(t.op==="sse-init"){this.initParams={machineId:t["machine-id"],sessionId:t["session-id"],sseToken:t["sse-token"]},this.onopen&&this.onopen({target:this}),clearTimeout(this.sseInitTimeout);return}this.onmessage&&this.onmessage({target:this,message:t})}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}))}async postMessages(t){var n,i,s;try{(await fetch(this.messageUrl,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({machine_id:(n=this.initParams)==null?void 0:n.machineId,session_id:(i=this.initParams)==null?void 0:i.sessionId,sse_token:(s=this.initParams)==null?void 0:s.sseToken,messages:t})})).ok||this.handleError()}catch{this.handleError()}}async flushQueue(){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 an;(function(e){e.InitialSyncBatch="InitialSyncBatch",e.InitialSyncComplete="InitialSyncComplete",e.LoadFromStorage="LoadFromStorage",e.SyncTransaction="SyncTransaction",e.Error="Error"})(an||(an={}));function ai({WStream:e,opts:t,startStream:n,appendStream:i,registerStream:s}){const r=t.clientId;let o=null,a=null,u=null;const c=Ce();let l=!1,f=!1;const m=[],y=[],I=[];let w=!1,h=0,O=0;const b=[],k=new TextEncoder;function ee(){f=!0;for(const p of m)p(a??void 0)}function D(p){return m.push(p),f&&p(a??void 0),()=>{const v=m.indexOf(p);v!==-1&&m.splice(v,1)}}function z(p){return I.push(p),()=>{const v=I.indexOf(p);v!==-1&&I.splice(v,1)}}t.waitUntil&&t.waitUntil(new Promise(p=>{I.push(p)}));function Q(){for(const p of I)try{p()}catch{}}function ue(p){return y.push(p),o&&p(o),()=>{const v=y.indexOf(p);v!==-1&&y.splice(v,1)}}function re(p){o=p;for(const v of y)v(o)}function $e(){w=!0}function At(p){let v=h,V=0,G=0;for(const{byteLen:ne}of b){const de=v+ne;if(de>p)break;v=de,V++,G+=ne}V>0&&(h+=G,O-=G,b.splice(0,V))}function te(p,v){a=v,ee(),p.error(v),Q()}async function fe(){const p=await n({clientId:r,reconnectToken:c,ruleParams:t.ruleParams});switch(p.type){case"ok":{const{streamId:v,offset:V}=p;o=v,At(V),b.length&&i({streamId:v,chunks:b.map(G=>G.chunk),offset:h}),w=!1;break}case"disconnect":{$e();break}case"error":{u&&te(u,p.error);break}}}function le(){$e(),fe()}function ke({offset:p,done:v}){At(p),v&&(l=!0,Q())}function Ee(p){return l?(te(p,new B("Stream has been closed.")),null):o||(te(p,new B("Stream has not been initialized.")),null)}async function Pt(p){u=p;let v=!0,V=0;for(;v;){let G=Date.now()+Math.min(15e3,500*(V-1));v=!1;const ne=await n({clientId:t.clientId,reconnectToken:c,ruleParams:t.ruleParams});switch(ne.type){case"ok":{const{streamId:de,offset:jt}=ne;if(jt!==0){const _e=new B("Write stream is corrupted");te(p,_e);return}re(de),s(de,{onDisconnect:$e,onFlush:ke,onConnectionReconnect:fe,onAppendFailed:le}),w=!1;return}case"disconnect":{v=!0,$e(),V++,await new Promise(de=>{setTimeout(de,Math.max(0,G-Date.now()))});break}case"error":{te(p,ne.error);return}}}}class Ji extends e{constructor(v,V){super(v,V)}async streamId(){return o||new Promise((v,V)=>{const G=[],ne=()=>{for(const _e of G)_e()},de=_e=>{v(_e),ne()},jt=_e=>{V(_e||new B("Stream is closed.")),ne()};G.push(ue(de)),G.push(D(jt))})}}return{stream:new Ji({async start(p){try{await Pt(p)}catch(v){te(p,v)}},write(p,v){const V=Ee(v);if(V){const G=k.encode(p).length;b.push({chunk:p,byteLen:G});const ne=h+O;O+=G,w||i({streamId:V,chunks:[p],offset:ne})}},close(){o?i({streamId:o,chunks:[],offset:h+O,isDone:!0}):Q(),ee()},abort(p){o?i({streamId:o,chunks:[],offset:h+O,isDone:!0,abortReason:p}):Q(),ee()}}),addCompleteCb:z,closed(){return f}}}class ci{constructor(){d(this,"items",[]);d(this,"resolvers",[]);d(this,"isClosed",!1)}push(t){if(this.isClosed)return;const n=this.resolvers.shift();n?n({value:t,done:!1}):this.items.push(t)}close(){for(this.isClosed=!0;this.resolvers.length>0;)this.resolvers.shift()({value:void 0,done:!0})}async*[Symbol.asyncIterator](){for(;;)if(this.items.length>0)yield this.items.shift();else{if(this.isClosed)return;{const{value:t,done:n}=await new Promise(i=>{this.resolvers.push(i)});if(n||!t)return;yield t}}}}function ui({RStream:e,opts:t,startStream:n,cancelStream:i}){let s=t.byteOffset||0,r=!1;const o=new TextDecoder("utf-8"),a=new TextEncoder;let u,c=!1;const l=[];function f(){c=!0;for(const b of l)b()}function m(b){return l.push(b),()=>{const k=l.indexOf(b);k!==-1&&l.splice(k,1)}}function y(b,k){b.error(k),f()}let I=0;async function w(b,k){u=Ce();const ee={...b||{},eventId:u};for await(const D of n(ee)){if(r)return;if(D.type==="reconnect")return{retry:!0};if(D.type==="error"){y(k,D.error);return}if(D.offset>s){y(k,new B("Stream is corrupted.")),r=!0;return}let z=s-D.offset;if(D.files&&D.files.length){const Q=new AbortController;let ue=fetch(D.files[0].url,{signal:Q.signal});for(let re=0;re<D.files.length;re++){const $e=D.files[re+1],te=await ue;if($e&&(ue=fetch($e.url,{signal:Q.signal})),!te.ok){if(I++,I>10){y(k,new B("Unable to process stream."));return}return{retry:!0}}if(te.body){const fe=te.body.getReader();try{for(;;){const{done:le,value:ke}=await fe.read();if(le)break;if(r){Q.abort();return}let Ee=ke;if(z>0&&(Ee=ke.subarray(z),z-=ke.length-Ee.length),!Ee.length)continue;s+=Ee.length;const Pt=o.decode(Ee);k.enqueue(Pt)}}finally{fe.releaseLock()}}else{const fe=await te.arrayBuffer();let le=fe;if(r){Q.abort();return}if(z>0&&(le=new Uint8Array(fe).subarray(z),z-=fe.byteLength-le.length),!le.byteLength)continue;s+=le.byteLength;const ke=o.decode(le);k.enqueue(ke)}}}if(I=0,D.content){let Q=D.content,ue=a.encode(D.content);if(z>0){const re=ue.subarray(z);if(z-=ue.length-re.length,!re.length)continue;ue=re,Q=o.decode(re)}s+=ue.length,k.enqueue(Q)}}}async function h(b){let k=!0,ee=0;for(;k;){k=!1;let D=Date.now()+Math.min(15e3,500*(ee-1));const z=await w({...t,offset:s},b);z!=null&&z.retry&&(k=!0,ee++,D<Date.now()-3e5&&(ee=0),await new Promise(Q=>{setTimeout(Q,Math.max(0,D-Date.now()))}))}!r&&!c&&(b.close(),f())}return{stream:new e({start(b){h(b)},cancel(b){r=!0,u&&i({eventId:u}),f()}}),addCloseCb:m,closed(){return c}}}class fi{constructor({WStream:t,RStream:n,trySend:i,log:s}){d(this,"trySend");d(this,"WStream");d(this,"RStream");d(this,"writeStreams",{});d(this,"startWriteStreamCbs",{});d(this,"readStreamIterators",{});d(this,"log");d(this,"activeStreams",new Set);this.WStream=t,this.RStream=n,this.trySend=i,this.log=s}createWriteStream(t){const{stream:n,addCompleteCb:i}=ai({WStream:this.WStream,startStream:this.startWriteStream.bind(this),appendStream:this.appendStream.bind(this),registerStream:this.registerWriteStream.bind(this),opts:t});return this.activeStreams.add(n),i(()=>{this.activeStreams.delete(n)}),n}createReadStream(t){const{stream:n,addCloseCb:i}=ui({RStream:this.RStream,opts:t,startStream:this.startReadStream.bind(this),cancelStream:this.cancelReadStream.bind(this)});return this.activeStreams.add(n),i(()=>{this.activeStreams.delete(n)}),n}startWriteStream(t){const n=Ce();let i=null;const s=new Promise(o=>{i=o});this.startWriteStreamCbs[n]=i;const r={op:"start-stream","client-id":t.clientId,"reconnect-token":t.reconnectToken};return t.ruleParams&&(r["rule-params"]=t.ruleParams),this.trySend(n,r),s}registerWriteStream(t,n){this.writeStreams[t]=n}appendStream({streamId:t,chunks:n,isDone:i,offset:s,abortReason:r}){const o={op:"append-stream","stream-id":t,chunks:n,offset:s,done:!!i};r&&(o["abort-reason"]=r),this.trySend(Ce(),o)}onAppendFailed(t){const n=this.writeStreams[t["stream-id"]];n&&n.onAppendFailed()}onStartStreamOk(t){const n=this.startWriteStreamCbs[t["client-event-id"]];if(!n){this.log.info("No stream for start-stream-ok",t);return}n({type:"ok",streamId:t["stream-id"],offset:t.offset}),delete this.startWriteStreamCbs[t["client-event-id"]]}onStreamFlushed(t){const n=t["stream-id"],i=this.writeStreams[n];if(!i){this.log.info("No stream cbs for stream-flushed",t);return}i.onFlush({offset:t.offset,done:t.done}),t.done&&delete this.writeStreams[n]}startReadStream({eventId:t,clientId:n,streamId:i,offset:s,ruleParams:r}){const o={op:"subscribe-stream"};if(!i&&!n)throw new Error("Must provide one of streamId or clientId to subscribe to the stream.");i&&(o["stream-id"]=i),n&&(o["client-id"]=n),s&&(o.offset=s),r&&(o["rule-params"]=r);const a=new ci;return this.readStreamIterators[t]=a,this.trySend(t,o),a}cancelReadStream({eventId:t}){const n={op:"unsubscribe-stream","subscribe-event-id":t};this.trySend(Ce(),n),delete this.readStreamIterators[t]}onStreamAppend(t){var s;const n=t["client-event-id"],i=this.readStreamIterators[n];if(!i){this.log.info("No iterator for read stream",t);return}if(t.error){t.retry?i.push({type:"reconnect"}):i.push({type:"error",error:new B(t.error)}),i.close(),delete this.readStreamIterators[n];return}((s=t.files)!=null&&s.length||t.content)&&i.push({type:"append",offset:t.offset,files:t.files,content:t.content}),t.done&&(i.close(),delete this.readStreamIterators[n])}onConnectionStatusChange(t){for(const n of Object.values(this.startWriteStreamCbs))n({type:"disconnect"});if(this.startWriteStreamCbs={},t!==li.AUTHENTICATED)for(const{onDisconnect:n}of Object.values(this.writeStreams))n();else{for(const{onConnectionReconnect:n}of Object.values(this.writeStreams))n();for(const n of Object.values(this.readStreamIterators))n.push({type:"reconnect"}),n.close();this.readStreamIterators={}}}onRecieveError(t){const n=t["original-event"];switch(n.op){case"append-stream":{const i=n["stream-id"],s=this.writeStreams[i];s==null||s.onAppendFailed();break}case"start-stream":{const i=t["client-event-id"],s=this.startWriteStreamCbs[i];s&&(s({type:"error",error:new B(t.message||"Unknown error",t.hint)}),delete this.startWriteStreamCbs[i]);break}case"subscribe-stream":{const i=t["client-event-id"],s=this.readStreamIterators[i];s&&(s.push({type:"error",error:new B(t.message||"Unknown error",t.hint)}),s.close(),delete this.readStreamIterators[i]);break}}}hasActiveStreams(){return this.activeStreams.size>0}}const li={AUTHENTICATED:"authenticated"};function di(){return globalThis.__instantDbSchemaHashStore=globalThis.__instantDbSchemaHashStore??new WeakMap,globalThis.__instantDbSchemaHashStore}function hi(){return globalThis.__instantDbStore=globalThis.__instantDbStore??{},globalThis.__instantDbStore}hi(),di();class cn extends Error{constructor(t,n){super(t),this.name="ParseError",this.type=n.type,this.field=n.field,this.value=n.value,this.line=n.line}}function bt(e){}function pi(e){if(typeof e=="function")throw new TypeError("`callbacks` must be an object, got a function instead. Did you mean `{onEvent: fn}`?");const{onEvent:t=bt,onError:n=bt,onRetry:i=bt,onComment:s}=e;let r="",o=!0,a,u="",c="";function l(w){const h=o?w.replace(/^\xEF\xBB\xBF/,""):w,[O,b]=mi(`${r}${h}`);for(const k of O)f(k);r=b,o=!1}function f(w){if(w===""){y();return}if(w.startsWith(":")){s&&s(w.slice(w.startsWith(": ")?2:1));return}const h=w.indexOf(":");if(h!==-1){const O=w.slice(0,h),b=w[h+1]===" "?2:1,k=w.slice(h+b);m(O,k,w);return}m(w,"",w)}function m(w,h,O){switch(w){case"event":c=h;break;case"data":u=`${u}${h}
|
|
1
|
+
(function($,_){typeof exports=="object"&&typeof module<"u"?_(exports):typeof define=="function"&&define.amd?define(["exports"],_):($=typeof globalThis<"u"?globalThis:$||self,_($.instant={}))})(this,function($){"use strict";var Qi=Object.defineProperty;var In=$=>{throw TypeError($)};var Gi=($,_,x)=>_ in $?Qi($,_,{enumerable:!0,configurable:!0,writable:!0,value:x}):$[_]=x;var l=($,_,x)=>Gi($,typeof _!="symbol"?_+"":_,x),Mt=($,_,x)=>_.has($)||In("Cannot "+x);var g=($,_,x)=>(Mt($,_,"read from private field"),x?x.call($):_.get($)),K=($,_,x)=>_.has($)?In("Cannot add the same private member more than once"):_ instanceof WeakSet?_.add($):_.set($,x),he=($,_,x,R)=>(Mt($,_,"write to private field"),R?R.call($,x):_.set($,x),x),X=($,_,x)=>(Mt($,_,"access private method"),x);var Ue,N,Oe,W,F,U,On,st,$n,kn,En,et,tt,nt,Ut,_n,it;const _=/^(?:[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 x(e){return typeof e=="string"&&_.test(e)}const R=[];for(let e=0;e<256;++e)R.push((e+256).toString(16).slice(1));function Cn(e,t=0){return(R[e[t+0]]+R[e[t+1]]+R[e[t+2]]+R[e[t+3]]+"-"+R[e[t+4]]+R[e[t+5]]+"-"+R[e[t+6]]+R[e[t+7]]+"-"+R[e[t+8]]+R[e[t+9]]+"-"+R[e[t+10]]+R[e[t+11]]+R[e[t+12]]+R[e[t+13]]+R[e[t+14]]+R[e[t+15]]).toLowerCase()}let rt;const xn=new Uint8Array(16);function Tn(){if(!rt){if(typeof crypto>"u"||!crypto.getRandomValues)throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");rt=crypto.getRandomValues.bind(crypto)}return rt(xn)}const Dt={randomUUID:typeof crypto<"u"&&crypto.randomUUID&&crypto.randomUUID.bind(crypto)};function Rn(e,t,n){var s;if(Dt.randomUUID&&!e)return Dt.randomUUID();e=e||{};const i=e.random??((s=e.rng)==null?void 0:s.call(e))??Tn();if(i.length<16)throw new Error("Random bytes length must be >= 16");return i[6]=i[6]&15|64,i[8]=i[8]&63|128,Cn(i)}const P={Remove:"remove",Replace:"replace",Add:"add"},Nt=Symbol.for("__MUTATIVE_PROXY_DRAFT__"),Qe=Symbol.iterator,Y={mutable:"mutable",immutable:"immutable"},ot={};function De(e,t){return e instanceof Map?e.has(t):Object.prototype.hasOwnProperty.call(e,t)}function Lt(e,t){if(t in e){let n=Reflect.getPrototypeOf(e);for(;n;){const i=Reflect.getOwnPropertyDescriptor(n,t);if(i)return i;n=Reflect.getPrototypeOf(n)}}}function Wt(e){return Object.getPrototypeOf(e)===Set.prototype}function Ft(e){return Object.getPrototypeOf(e)===Map.prototype}function H(e){var t;return(t=e.copy)!==null&&t!==void 0?t:e.original}function at(e){return!!E(e)}function E(e){return typeof e!="object"?null:e==null?void 0:e[Nt]}function ct(e){var t;const n=E(e);return n?(t=n.copy)!==null&&t!==void 0?t:n.original:e}function ge(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,Y))===Y.immutable||typeof n=="function")}function zt(e,t=[]){if(Object.hasOwnProperty.call(e,"key")){const n=e.parent.copy,i=E(pe(n,e.key));if(i!==null&&(i==null?void 0:i.original)!==e.original)return null;const s=e.parent.type===3,r=s?Array.from(e.parent.setMap.keys()).indexOf(e.key):e.key;if(!(s&&n.size>r||De(n,r)))return null;t.push(r)}if(e.parent)return zt(e.parent,t);t.reverse();try{An(e.copy,t)}catch{return null}return t}function Ne(e){return Array.isArray(e)?1:e instanceof Map?2:e instanceof Set?3:0}function pe(e,t){return Ne(e)===2?e.get(t):e[t]}function ut(e,t,n){Ne(e)===2?e.set(t,n):e[t]=n}function ft(e,t){const n=E(e);return(n?H(n):e)[t]}function we(e,t){return e===t?e!==0||1/e===1/t:e!==e&&t!==t}function Se(e,t){return t?e:[""].concat(e).map(n=>{const i=`${n}`;return i.indexOf("/")===-1&&i.indexOf("~")===-1?i:i.replace(/~/g,"~0").replace(/\//g,"~1")}).join("/")}function An(e,t){for(let n=0;n<t.length-1;n+=1){const i=t[n];if(e=pe(Ne(e)===3?Array.from(e):e,i),typeof e!="object")throw new Error(`Cannot resolve patch at '${t.join("/")}'.`)}return e}function Pn(e){const t=Object.create(Object.getPrototypeOf(e));return Reflect.ownKeys(e).forEach(n=>{let i=Reflect.getOwnPropertyDescriptor(e,n);if(i.enumerable&&i.configurable&&i.writable){t[n]=e[n];return}i.writable||(i.writable=!0,i.configurable=!0),(i.get||i.set)&&(i={configurable:!0,writable:!0,enumerable:i.enumerable,value:e[n]}),Reflect.defineProperty(t,n,i)}),t}const jn=Object.prototype.propertyIsEnumerable;function Mn(e,t){let n;if(Array.isArray(e))return Array.prototype.concat.call(e);if(e instanceof Set){if(!Wt(e)){const i=Object.getPrototypeOf(e).constructor;return new i(e.values())}return Set.prototype.difference?Set.prototype.difference.call(e,new Set):new Set(e.values())}else if(e instanceof Map){if(!Ft(e)){const i=Object.getPrototypeOf(e).constructor;return new i(e)}return new Map(e)}else if(t!=null&&t.mark&&(n=t.mark(e,Y),n!==void 0)&&n!==Y.mutable){if(n===Y.immutable)return Pn(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 i={};return Object.keys(e).forEach(s=>{i[s]=e[s]}),Object.getOwnPropertySymbols(e).forEach(s=>{jn.call(e,s)&&(i[s]=e[s])}),i}else throw new Error("Please check mark() to ensure that it is a stable marker draftable function.")}function L(e){e.copy||(e.copy=Mn(e.original,e.options))}function Le(e){if(!ge(e))return ct(e);if(Array.isArray(e))return e.map(Le);if(e instanceof Map){const n=Array.from(e.entries()).map(([i,s])=>[i,Le(s)]);if(!Ft(e)){const i=Object.getPrototypeOf(e).constructor;return new i(n)}return new Map(n)}if(e instanceof Set){const n=Array.from(e).map(Le);if(!Wt(e)){const i=Object.getPrototypeOf(e).constructor;return new i(n)}return new Set(n)}const t=Object.create(Object.getPrototypeOf(e));for(const n in e)t[n]=Le(e[n]);return t}function Ge(e){return at(e)?Le(e):e}function ie(e){var t;e.assignedMap=(t=e.assignedMap)!==null&&t!==void 0?t:new Map,e.operated||(e.operated=!0,e.parent&&ie(e.parent))}function Un(e,t){const n=Ne(e);if(n===0)Reflect.ownKeys(e).forEach(i=>{t(i,e[i],e)});else if(n===1){let i=0;for(const s of e)t(i,s,e),i+=1}else e.forEach((i,s)=>t(s,i,e))}function Vt(e,t,n){if(at(e)||!ge(e,n)||t.has(e)||Object.isFrozen(e))return;const i=e instanceof Set,s=i?new Map:void 0;if(t.add(e),Un(e,(r,o)=>{var a;if(at(o)){const u=E(o);L(u);const c=!((a=u.assignedMap)===null||a===void 0)&&a.size||u.operated?u.copy:u.original;ut(i?s:e,r,c)}else Vt(o,t,n)}),s){const r=e,o=Array.from(r);r.clear(),o.forEach(a=>{r.add(s.has(a)?s.get(a):a)})}}function Dn(e,t){const n=e.type===3?e.setMap:e.copy;e.finalities.revoke.length>1&&e.assignedMap.get(t)&&n&&Vt(pe(n,t),e.finalities.handledSet,e.options)}function lt(e){e.type===3&&e.copy&&(e.copy.clear(),e.setMap.forEach(t=>{e.copy.add(ct(t))}))}function dt(e,t,n,i){if(e.operated&&e.assignedMap&&e.assignedMap.size>0&&!e.finalized){if(n&&i){const r=zt(e);r&&t(e,r,n,i)}e.finalized=!0}}function ht(e,t,n,i){const s=E(n);s&&(s.callbacks||(s.callbacks=[]),s.callbacks.push((r,o)=>{var a;const u=e.type===3?e.setMap:e.copy;if(we(pe(u,t),n)){let c=s.original;s.copy&&(c=s.copy),lt(e),dt(e,i,r,o),e.options.enableAutoFreeze&&(e.options.updatedValues=(a=e.options.updatedValues)!==null&&a!==void 0?a:new WeakMap,e.options.updatedValues.set(c,s.original)),ut(u,t,c)}}),e.options.enableAutoFreeze&&s.finalities!==e.finalities&&(e.options.enableAutoFreeze=!1)),ge(n,e.options)&&e.finalities.draft.push(()=>{const r=e.type===3?e.setMap:e.copy;we(pe(r,t),n)&&Dn(e,t)})}function Nn(e,t,n,i,s){let{original:r,assignedMap:o,options:a}=e,u=e.copy;u.length<r.length&&([r,u]=[u,r],[n,i]=[i,n]);for(let c=0;c<r.length;c+=1)if(o.get(c.toString())&&u[c]!==r[c]){const d=t.concat([c]),f=Se(d,s);n.push({op:P.Replace,path:f,value:Ge(u[c])}),i.push({op:P.Replace,path:f,value:Ge(r[c])})}for(let c=r.length;c<u.length;c+=1){const d=t.concat([c]),f=Se(d,s);n.push({op:P.Add,path:f,value:Ge(u[c])})}if(r.length<u.length){const{arrayLengthAssignment:c=!0}=a.enablePatches;if(c){const d=t.concat(["length"]),f=Se(d,s);i.push({op:P.Replace,path:f,value:r.length})}else for(let d=u.length;r.length<d;d-=1){const f=t.concat([d-1]),m=Se(f,s);i.push({op:P.Remove,path:m})}}}function Ln({original:e,copy:t,assignedMap:n},i,s,r,o){n.forEach((a,u)=>{const c=pe(e,u),d=Ge(pe(t,u)),f=a?De(e,u)?P.Replace:P.Add:P.Remove;if(we(c,d)&&f===P.Replace)return;const m=i.concat(u),y=Se(m,o);s.push(f===P.Remove?{op:f,path:y}:{op:f,path:y,value:d}),r.push(f===P.Add?{op:P.Remove,path:y}:f===P.Remove?{op:P.Add,path:y,value:c}:{op:P.Replace,path:y,value:c})})}function Wn({original:e,copy:t},n,i,s,r){let o=0;e.forEach(a=>{if(!t.has(a)){const u=n.concat([o]),c=Se(u,r);i.push({op:P.Remove,path:c,value:a}),s.unshift({op:P.Add,path:c,value:a})}o+=1}),o=0,t.forEach(a=>{if(!e.has(a)){const u=n.concat([o]),c=Se(u,r);i.push({op:P.Add,path:c,value:a}),s.unshift({op:P.Remove,path:c,value:a})}o+=1})}function We(e,t,n,i){const{pathAsArray:s=!0}=e.options.enablePatches;switch(e.type){case 0:case 2:return Ln(e,t,n,i,s);case 1:return Nn(e,t,n,i,s);case 3:return Wn(e,t,n,i,s)}}const He=(e,t,n=!1)=>{if(typeof e=="object"&&e!==null&&(!ge(e,t)||n))throw new Error("Strict mode: Mutable data cannot be accessed directly, please use 'unsafe(callback)' wrap.")},pt={get size(){return H(E(this)).size},has(e){return H(E(this)).has(e)},set(e,t){const n=E(this),i=H(n);return(!i.has(e)||!we(i.get(e),t))&&(L(n),ie(n),n.assignedMap.set(e,!0),n.copy.set(e,t),ht(n,e,t,We)),this},delete(e){if(!this.has(e))return!1;const t=E(this);return L(t),ie(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){L(e),ie(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);H(n).forEach((i,s)=>{e.call(t,this.get(s),s,this)})},get(e){var t,n;const i=E(this),s=H(i).get(e),r=((n=(t=i.options).mark)===null||n===void 0?void 0:n.call(t,s,Y))===Y.mutable;if(i.options.strict&&He(s,i.options,r),r||i.finalized||!ge(s,i.options)||s!==i.original.get(e))return s;const o=ot.createDraft({original:s,parentDraft:i,key:e,finalities:i.finalities,options:i.options});return L(i),i.copy.set(e,o),o},keys(){return H(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()}},Fn=Reflect.ownKeys(pt),Jt=(e,t,{isValuesIterator:n})=>()=>{var i,s;const r=t.next();if(r.done)return r;const o=r.value;let a=e.setMap.get(o);const u=E(a),c=((s=(i=e.options).mark)===null||s===void 0?void 0:s.call(i,a,Y))===Y.mutable;if(e.options.strict&&He(o,e.options,c),!c&&!u&&ge(o,e.options)&&!e.finalized&&e.original.has(o)){const d=ot.createDraft({original:o,parentDraft:e,key:o,finalities:e.finalities,options:e.options});e.setMap.set(o,d),a=d}else u&&(a=u.proxy);return{done:!1,value:n?a:[a,a]}},Be={get size(){return E(this).setMap.size},has(e){const t=E(this);if(t.setMap.has(e))return!0;L(t);const n=E(e);return!!(n&&t.setMap.has(n.original))},add(e){const t=E(this);return this.has(e)||(L(t),ie(t),t.assignedMap.set(e,!0),t.setMap.set(e,e),ht(t,e,e,We)),this},delete(e){if(!this.has(e))return!1;const t=E(this);L(t),ie(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);L(e),ie(e);for(const t of e.original)e.assignedMap.set(t,!1);e.setMap.clear()},values(){const e=E(this);L(e);const t=e.setMap.keys();return{[Symbol.iterator]:()=>this.values(),next:Jt(e,t,{isValuesIterator:!0})}},entries(){const e=E(this);L(e);const t=e.setMap.keys();return{[Symbol.iterator]:()=>this.entries(),next:Jt(e,t,{isValuesIterator:!1})}},keys(){return this.values()},[Qe](){return this.values()},forEach(e,t){const n=this.values();let i=n.next();for(;!i.done;)e.call(t,i.value,i.value,this),i=n.next()}};Set.prototype.difference&&Object.assign(Be,{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 zn=Reflect.ownKeys(Be),Qt=new WeakSet,Gt={get(e,t,n){var i,s;const r=(i=e.copy)===null||i===void 0?void 0:i[t];if(r&&Qt.has(r))return r;if(t===Nt)return e;let o;if(e.options.mark){const c=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(c,Y),o===Y.mutable)return e.options.strict&&He(c,e.options,!0),c}const a=H(e);if(a instanceof Map&&Fn.includes(t)){if(t==="size")return Object.getOwnPropertyDescriptor(pt,"size").get.call(e.proxy);const c=pt[t];if(c)return c.bind(e.proxy)}if(a instanceof Set&&zn.includes(t)){if(t==="size")return Object.getOwnPropertyDescriptor(Be,"size").get.call(e.proxy);const c=Be[t];if(c)return c.bind(e.proxy)}if(!De(a,t)){const c=Lt(a,t);return c?"value"in c?c.value:(s=c.get)===null||s===void 0?void 0:s.call(e.proxy):void 0}const u=a[t];if(e.options.strict&&He(u,e.options),e.finalized||!ge(u,e.options))return u;if(u===ft(e.original,t)){if(L(e),e.copy[t]=Ht({original:e.original[t],parentDraft:e,key:e.type===1?Number(t):t,finalities:e.finalities,options:e.options}),typeof o=="function"){const c=E(e.copy[t]);return L(c),ie(c),c.copy}return e.copy[t]}return u},set(e,t,n){var i;if(e.type===3||e.type===2)throw new Error("Map/Set draft does not support any property assignment.");let s;if(e.type===1&&t!=="length"&&!(Number.isInteger(s=Number(t))&&s>=0&&(t===0||s===0||String(s)===String(t))))throw new Error("Only supports setting array indices and the 'length' property.");const r=Lt(H(e),t);if(r!=null&&r.set)return r.set.call(e.proxy,n),!0;const o=ft(H(e),t),a=E(o);return a&&we(a.original,n)?(e.copy[t]=n,e.assignedMap=(i=e.assignedMap)!==null&&i!==void 0?i:new Map,e.assignedMap.set(t,!1),!0):(we(n,o)&&(n!==void 0||De(e.original,t))||(L(e),ie(e),De(e.original,t)&&we(n,e.original[t])?e.assignedMap.delete(t):e.assignedMap.set(t,!0),e.copy[t]=n,ht(e,t,n,We)),!0)},has(e,t){return t in H(e)},ownKeys(e){return Reflect.ownKeys(H(e))},getOwnPropertyDescriptor(e,t){const n=H(e),i=Reflect.getOwnPropertyDescriptor(n,t);return i&&{writable:!0,configurable:e.type!==1||t!=="length",enumerable:i.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?Gt.set.call(this,e,t,void 0,e.proxy):(ft(e.original,t)!==void 0||t in e.original?(L(e),ie(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 Ht(e){const{original:t,parentDraft:n,key:i,finalities:s,options:r}=e,o=Ne(t),a={type:o,finalized:!1,parent:n,original:t,copy:null,proxy:null,finalities:s,options:r,setMap:o===3?new Map(t.entries()):void 0};(i||"key"in e)&&(a.key=i);const{proxy:u,revoke:c}=Proxy.revocable(o===1?Object.assign([],a):a,Gt);if(s.revoke.push(c),Qt.add(u),a.proxy=u,n){const d=n;d.finalities.draft.push((f,m)=>{var y,I;const w=E(u);let h=d.type===3?d.setMap:d.copy;const O=pe(h,i),b=E(O);if(b){let k=b.original;b.operated&&(k=ct(O)),lt(b),dt(b,We,f,m),d.options.enableAutoFreeze&&(d.options.updatedValues=(y=d.options.updatedValues)!==null&&y!==void 0?y:new WeakMap,d.options.updatedValues.set(k,b.original)),ut(h,i,k)}(I=w.callbacks)===null||I===void 0||I.forEach(k=>{k(f,m)})})}else{const d=E(u);d.finalities.draft.push((f,m)=>{lt(d),dt(d,We,f,m)})}return u}ot.createDraft=Ht,Object.prototype.constructor.toString();function Ce(){return Rn()}function Vn(e,t){return e.localeCompare(t)}function Jn(){let e=Vn;if(typeof Intl=="object"&&Intl.hasOwnProperty("Collator"))try{e=Intl.Collator("en-US").compare}catch{}return e}Jn();function Qn(){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 Gn=Qn();function qe(e,t,n){const i={__etype:e,__ops:n};return new Proxy(i,{get:(s,r)=>{if(r==="__ops")return n;if(r==="__etype")return e;if(Gn.has(r))return(o,a)=>qe(e,t,[...n,a?[r,e,t,o,a]:[r,e,t,o]])}})}function Hn(e,t){return`lookup__${e}__${JSON.stringify(t)}`}function Bt(e){return e.startsWith("lookup__")}function qt(e){const[t,n,...i]=e.split("__");return[n,JSON.parse(i.join("__"))]}function Bn(e){return new Proxy({__etype:e},{get(t,n){if(n==="lookup")return(s,r)=>qe(e,qt(Hn(s,r)),[]);if(n==="__etype")return e;const i=n;return Bt(i)?qe(e,qt(i),[]):qe(e,i,[])}})}function Kt(){return new Proxy({},{get(e,t){return Bn(t)}})}Kt();function qn(e){return e.__ops}class B extends Error{constructor(n,i,s){super(n);l(this,"hint");l(this,"traceId");this.hint=i,s&&(this.traceId=s);const r=new.target.prototype;Object.setPrototypeOf&&Object.setPrototypeOf(this,r),Error.captureStackTrace&&Error.captureStackTrace(this,B),this.name="InstantError"}get[Symbol.toStringTag](){return"InstantError"}}class Ie extends B{constructor(n){var r;const i=((r=n.body)==null?void 0:r.message)||`API Error (${n.status})`;super(i,n.body.hint,n.body["trace-id"]);l(this,"body");l(this,"status");const s=new.target.prototype;Object.setPrototypeOf&&Object.setPrototypeOf(this,s),Error.captureStackTrace&&Error.captureStackTrace(this,Ie),this.name="InstantAPIError",this.status=n.status,this.body=n.body}get[Symbol.toStringTag](){return"InstantAPIError"}}typeof window<"u"&&typeof window.localStorage<"u"&&(window.localStorage.getItem("devBackend"),window.localStorage.getItem("__instantLogging"),window.localStorage.getItem("__devtoolLocalDash"));const xe="v0.22.156";class oe{constructor(t,n,i,s={indexed:!1,unique:!1}){l(this,"valueType");l(this,"required");l(this,"isIndexed");l(this,"config");l(this,"metadata",{});this.valueType=t,this.required=n,this.isIndexed=i,this.config=s}clientRequired(){return new oe(this.valueType,!1,this.isIndexed,this.config)}optional(){return new oe(this.valueType,!1,this.isIndexed,this.config)}unique(){return new oe(this.valueType,this.required,this.isIndexed,{...this.config,unique:!0})}indexed(){return new oe(this.valueType,this.required,!0,{...this.config,indexed:!0})}}class C extends Error{constructor(t,n){const i=n?`At path '${n}': ${t}`:t;super(i),this.name="QueryValidationError"}}const Xt=["where","order","limit","last","first","offset","after","before","fields","aggregate"],Kn=e=>e.valueType||"unknown",Yt=(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}},Xn=(e,t,n,i,s,r,o)=>{const a=r.valueType==="json",u=(c,d,f)=>{if(!Yt(f,d,a))throw new C(`Invalid value for operator '${c}' on attribute '${i}' in entity '${s}'. Expected ${d}, but received: ${typeof f}`,o)};switch(e){case"in":case"$in":if(!Array.isArray(t))throw new C(`Operator '${e}' for attribute '${i}' in entity '${s}' must be an array, but received: ${typeof t}`,o);for(const c of t)u(e,n,c);break;case"$not":case"$ne":case"$gt":case"$lt":case"$gte":case"$lte":u(e,n,t);break;case"$like":case"$ilike":if(u(e,"string",t),e==="$ilike"&&!r.isIndexed)throw new C(`Operator '${e}' can only be used with indexed attributes, but '${i}' in entity '${s}' is not indexed`,o);break;case"$isNull":u(e,"boolean",t);break;default:throw new C(`Unknown operator '${e}' for attribute '${i}' in entity '${s}'`,o)}},Te=(e,t,n,i,s)=>{const r=Kn(n),o=n.valueType==="json";if(typeof e=="object"&&e!==null&&!Array.isArray(e)){if(o)return;const u=e;for(const[c,d]of Object.entries(u))Xn(c,d,r,t,i,n,`${s}.${c}`)}else if(!Yt(e,r,o))throw new C(`Invalid value for attribute '${t}' in entity '${i}'. Expected ${r}, but received: ${typeof e}`,s)},Yn=(e,t,n,i,s)=>{const r=e.split(".");if(r.length<2)throw new C(`Invalid dot notation path '${e}'. Must contain at least one dot.`,s);let o=n;for(let d=0;d<r.length-1;d++){const f=r[d],m=i.entities[o];if(!m)throw new C(`Entity '${o}' does not exist in schema while traversing dot notation path '${e}'.`,s);const y=m.links[f];if(!y){const I=Object.keys(m.links);throw new C(`Link '${f}' does not exist on entity '${o}' in dot notation path '${e}'. Available links: ${I.length>0?I.join(", "):"none"}`,s)}o=y.entityName}const a=r[r.length-1],u=i.entities[o];if(!u)throw new C(`Target entity '${o}' does not exist in schema for dot notation path '${e}'.`,s);if(a==="id"){if(typeof t=="string"&&!x(t))throw new C(`Invalid value for id field in entity '${o}'. Expected a UUID, but received: ${t}`,s);Te(t,e,new oe("string",!1,!0),n,s);return}const c=u.attrs[a];if(Object.keys(u.links).includes(a)){if(typeof t=="string"&&!x(t))throw new C(`Invalid value for link '${a}' in entity '${o}'. Expected a UUID, but received: ${t}`,s);Te(t,e,new oe("string",!1,!0),n,s);return}if(!c){const d=Object.keys(u.attrs);throw new C(`Attribute '${a}' does not exist on entity '${o}' in dot notation path '${e}'. Available attributes: ${d.length>0?d.join(", ")+", id":"id"}`,s)}Te(t,e,c,n,s)},Zt=(e,t,n,i)=>{for(const[s,r]of Object.entries(e)){if(s==="or"||s==="and"){if(Array.isArray(r))for(const c of r)typeof c=="object"&&c!==null&&Zt(c,t,n,`${i}.${s}[${c}]`);continue}if(s==="id"){Te(r,"id",new oe("string",!1,!0),t,`${i}.id`);continue}if(s.includes(".")){Yn(s,r,t,n,`${i}.${s}`);continue}const o=n.entities[t];if(!o)continue;const a=o.attrs[s],u=o.links[s];if(!a&&!u){const c=Object.keys(o.attrs),d=Object.keys(o.links);throw new C(`Attribute or link '${s}' does not exist on entity '${t}'. Available attributes: ${c.length>0?c.join(", "):"none"}. Available links: ${d.length>0?d.join(", "):"none"}`,`${i}.${s}`)}if(a)Te(r,s,a,t,`${i}.${s}`);else if(u){if(typeof r=="string"&&!x(r))throw new C(`Invalid value for link '${s}' in entity '${t}'. Expected a UUID, but received: ${r}`,`${i}.${s}`);const c=new oe("string",!1,!0);Te(r,s,c,t,`${i}.${s}`)}}},Zn=(e,t,n,i,s=0)=>{for(const o of Object.keys(e))if(!Xt.includes(o))throw new C(`Invalid query parameter '${o}' in $ object. Valid parameters are: ${Xt.join(", ")}. Found: ${o}`,i);const r=["offset","before","after","first","last"];for(const o of r)if(e[o]!==void 0&&s>0)throw new C(`'${o}' can only be used on top-level namespaces. It cannot be used in nested queries.`,i);if(e.where&&n){if(typeof e.where!="object"||e.where===null)throw new C(`'where' clause must be an object in entity '${t}', but received: ${typeof e.where}`,i?`${i}.where`:void 0);Zt(e.where,t,n,i?`${i}.where`:"where")}},en=(e,t,n,i,s=0)=>{var r;if(!e||typeof e!="object")throw new C(`Query part for entity '${t}' must be an object, but received: ${typeof e}`,i);for(const o of Object.keys(e))if(o!=="$"){if(n&&!(o in n.entities[t].links)){const u=Object.keys(n.entities[t].links);throw new C(`Link '${o}' does not exist on entity '${t}'. Available links: ${u.length>0?u.join(", "):"none"}`,`${i}.${o}`)}const a=e[o];if(typeof a=="object"&&a!==null){const u=(r=n==null?void 0:n.entities[t].links[o])==null?void 0:r.entityName;u&&en(a,u,n,`${i}.${o}`,s+1)}}else{const a=e[o];if(typeof a!="object"||a===null)throw new C(`Query parameter '$' must be an object in entity '${t}', but received: ${typeof a}`,`${i}.$`);Zn(a,t,n,`${i}.$`,s)}},tn=(e,t)=>{if(typeof e!="object"||e===null)throw new C(`Query must be an object, but received: ${typeof e}${e===null?" (null)":""}`);if(Array.isArray(e))throw new C(`Query must be an object, but received: ${typeof e}`);const n=e;for(const i of Object.keys(n)){if(Array.isArray(e[i]))throw new C(`Query keys must be strings, but found key of type: ${typeof i}`,i);if(typeof i!="string")throw new C(`Query keys must be strings, but found key of type: ${typeof i}`,i);if(i!=="$$ruleParams"){if(t&&!t.entities[i]){const s=Object.keys(t.entities);throw new C(`Entity '${i}' does not exist in schema. Available entities: ${s.length>0?s.join(", "):"none"}`,i)}en(n[i],i,t,i,0)}}},nn=e=>typeof e!="string"?!1:Bt(e)?!0:x(e);class q extends Error{constructor(t){super(t),this.name="TransactionValidationError"}}const sn=e=>e.length>0?e.join(", "):"none",ei=(e,t)=>new q(`Entity '${e}' does not exist in schema. Available entities: ${sn(t)}`),mt={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},ti=(e,t)=>{var n;return e==null?!0:((n=mt[t.valueType])==null?void 0:n.call(mt,e))??!1},rn=(e,t)=>{const n=t.entities[e];if(!n)throw ei(e,Object.keys(t.entities));return n},yt=(e,t,n)=>{const i=rn(e,n);if(typeof t!="object"||t===null)throw new q(`Arguments for data operation on entity '${e}' must be an object, but received: ${typeof t}`);for(const[s,r]of Object.entries(t)){if(s==="id")continue;const o=i.attrs[s];if(o&&!ti(r,o))throw new q(`Invalid value for attribute '${s}' in entity '${e}'. Expected ${o.valueType}, but received: ${typeof r}`)}},on=(e,t,n)=>{const i=rn(e,n);if(typeof t!="object"||t===null)throw new q(`Arguments for link operation on entity '${e}' must be an object, but received: ${typeof t}`);for(const[s,r]of Object.entries(t)){if(!i.links[s]){const a=Object.keys(i.links);throw new q(`Link '${s}' does not exist on entity '${e}'. Available links: ${sn(a)}`)}if(r!=null){if(Array.isArray(r)){for(const a of r)if(!nn(a))throw new q(`Invalid entity ID in link '${s}' for entity '${e}'. Expected a UUID or a lookup, but received: ${a}`)}else if(!nn(r))throw new q(`Invalid UUID in link '${s}' for entity '${e}'. Expected a UUID, but received: ${r}`)}}},ni={create:yt,update:yt,merge:yt,link:on,unlink:on,delete:()=>{}},ii=(e,t)=>{if(!t)return;const[n,i,s,r]=e;if(!Array.isArray(s)&&!x(s))throw new q(`Invalid id for entity '${i}'. Expected a UUID, but received: ${s}`);if(typeof i!="string")throw new q(`Entity name must be a string, but received: ${typeof i}`);const o=ni[n];o&&r!==void 0&&o(i,r,t)},si=(e,t)=>{const n=Array.isArray(e)?e:[e];for(const i of n){if(!i||typeof i!="object")throw new q(`Transaction chunk must be an object, but received: ${typeof i}`);if(!Array.isArray(i.__ops))throw new q(`Transaction chunk must have __ops array, but received: ${typeof i.__ops}`);for(const s of i.__ops){if(!Array.isArray(s))throw new q(`Transaction operation must be an array, but received: ${typeof s}`);ii(s,t)}}};let ri=0;class oi{constructor(t,n,i){l(this,"type","sse");l(this,"initParams",null);l(this,"sendQueue",[]);l(this,"sendPromise");l(this,"closeFired",!1);l(this,"sseInitTimeout");l(this,"ES");l(this,"messageUrl");l(this,"conn");l(this,"url");l(this,"id");l(this,"onopen");l(this,"onmessage");l(this,"onclose");l(this,"onerror");this.id=`${this.type}_${ri++}`,this.url=n,this.messageUrl=i||this.url,this.ES=t,this.conn=new t(n),this.sseInitTimeout=setTimeout(()=>{this.initParams||this.handleError()},1e4),this.conn.onmessage=s=>{const r=JSON.parse(s.data);if(Array.isArray(r))for(const o of r)this.handleMessage(o);else this.handleMessage(r)},this.conn.onerror=s=>{this.handleError()}}handleMessage(t){if(t.op==="sse-init"){this.initParams={machineId:t["machine-id"],sessionId:t["session-id"],sseToken:t["sse-token"]},this.onopen&&this.onopen({target:this}),clearTimeout(this.sseInitTimeout);return}this.onmessage&&this.onmessage({target:this,message:t})}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}))}async postMessages(t){var n,i,s;try{(await fetch(this.messageUrl,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({machine_id:(n=this.initParams)==null?void 0:n.machineId,session_id:(i=this.initParams)==null?void 0:i.sessionId,sse_token:(s=this.initParams)==null?void 0:s.sseToken,messages:t})})).ok||this.handleError()}catch{this.handleError()}}async flushQueue(){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 an;(function(e){e.InitialSyncBatch="InitialSyncBatch",e.InitialSyncComplete="InitialSyncComplete",e.LoadFromStorage="LoadFromStorage",e.SyncTransaction="SyncTransaction",e.Error="Error"})(an||(an={}));function ai({WStream:e,opts:t,startStream:n,appendStream:i,registerStream:s}){const r=t.clientId;let o=null,a=null,u=null;const c=Ce();let d=!1,f=!1;const m=[],y=[],I=[];let w=!1,h=0,O=0;const b=[],k=new TextEncoder;function ee(){f=!0;for(const p of m)p(a??void 0)}function D(p){return m.push(p),f&&p(a??void 0),()=>{const v=m.indexOf(p);v!==-1&&m.splice(v,1)}}function z(p){return I.push(p),()=>{const v=I.indexOf(p);v!==-1&&I.splice(v,1)}}t.waitUntil&&t.waitUntil(new Promise(p=>{I.push(p)}));function Q(){for(const p of I)try{p()}catch{}}function ue(p){return y.push(p),o&&p(o),()=>{const v=y.indexOf(p);v!==-1&&y.splice(v,1)}}function re(p){o=p;for(const v of y)v(o)}function $e(){w=!0}function At(p){let v=h,V=0,G=0;for(const{byteLen:ne}of b){const de=v+ne;if(de>p)break;v=de,V++,G+=ne}V>0&&(h+=G,O-=G,b.splice(0,V))}function te(p,v){a=v,ee(),p.error(v),Q()}async function fe(){const p=await n({clientId:r,reconnectToken:c,ruleParams:t.ruleParams});switch(p.type){case"ok":{const{streamId:v,offset:V}=p;o=v,At(V),b.length&&i({streamId:v,chunks:b.map(G=>G.chunk),offset:h}),w=!1;break}case"disconnect":{$e();break}case"error":{u&&te(u,p.error);break}}}function le(){$e(),fe()}function ke({offset:p,done:v}){At(p),v&&(d=!0,Q())}function Ee(p){return d?(te(p,new B("Stream has been closed.")),null):o||(te(p,new B("Stream has not been initialized.")),null)}async function Pt(p){u=p;let v=!0,V=0;for(;v;){let G=Date.now()+Math.min(15e3,500*(V-1));v=!1;const ne=await n({clientId:t.clientId,reconnectToken:c,ruleParams:t.ruleParams});switch(ne.type){case"ok":{const{streamId:de,offset:jt}=ne;if(jt!==0){const _e=new B("Write stream is corrupted");te(p,_e);return}re(de),s(de,{onDisconnect:$e,onFlush:ke,onConnectionReconnect:fe,onAppendFailed:le}),w=!1;return}case"disconnect":{v=!0,$e(),V++,await new Promise(de=>{setTimeout(de,Math.max(0,G-Date.now()))});break}case"error":{te(p,ne.error);return}}}}class Ji extends e{constructor(v,V){super(v,V)}async streamId(){return o||new Promise((v,V)=>{const G=[],ne=()=>{for(const _e of G)_e()},de=_e=>{v(_e),ne()},jt=_e=>{V(_e||new B("Stream is closed.")),ne()};G.push(ue(de)),G.push(D(jt))})}}return{stream:new Ji({async start(p){try{await Pt(p)}catch(v){te(p,v)}},write(p,v){const V=Ee(v);if(V){const G=k.encode(p).length;b.push({chunk:p,byteLen:G});const ne=h+O;O+=G,w||i({streamId:V,chunks:[p],offset:ne})}},close(){o?i({streamId:o,chunks:[],offset:h+O,isDone:!0}):Q(),ee()},abort(p){o?i({streamId:o,chunks:[],offset:h+O,isDone:!0,abortReason:p}):Q(),ee()}}),addCompleteCb:z,closed(){return f}}}class ci{constructor(){l(this,"items",[]);l(this,"resolvers",[]);l(this,"isClosed",!1)}push(t){if(this.isClosed)return;const n=this.resolvers.shift();n?n({value:t,done:!1}):this.items.push(t)}close(){for(this.isClosed=!0;this.resolvers.length>0;)this.resolvers.shift()({value:void 0,done:!0})}async*[Symbol.asyncIterator](){for(;;)if(this.items.length>0)yield this.items.shift();else{if(this.isClosed)return;{const{value:t,done:n}=await new Promise(i=>{this.resolvers.push(i)});if(n||!t)return;yield t}}}}function ui({RStream:e,opts:t,startStream:n,cancelStream:i}){let s=t.byteOffset||0,r=!1;const o=new TextDecoder("utf-8"),a=new TextEncoder;let u,c=!1;const d=[];function f(){c=!0;for(const b of d)b()}function m(b){return d.push(b),()=>{const k=d.indexOf(b);k!==-1&&d.splice(k,1)}}function y(b,k){b.error(k),f()}let I=0;async function w(b,k){u=Ce();const ee={...b||{},eventId:u};for await(const D of n(ee)){if(r)return;if(D.type==="reconnect")return{retry:!0};if(D.type==="error"){y(k,D.error);return}if(D.offset>s){y(k,new B("Stream is corrupted.")),r=!0;return}let z=s-D.offset;if(D.files&&D.files.length){const Q=new AbortController;let ue=fetch(D.files[0].url,{signal:Q.signal});for(let re=0;re<D.files.length;re++){const $e=D.files[re+1],te=await ue;if($e&&(ue=fetch($e.url,{signal:Q.signal})),!te.ok){if(I++,I>10){y(k,new B("Unable to process stream."));return}return{retry:!0}}if(te.body){const fe=te.body.getReader();try{for(;;){const{done:le,value:ke}=await fe.read();if(le)break;if(r){Q.abort();return}let Ee=ke;if(z>0&&(Ee=ke.subarray(z),z-=ke.length-Ee.length),!Ee.length)continue;s+=Ee.length;const Pt=o.decode(Ee);k.enqueue(Pt)}}finally{fe.releaseLock()}}else{const fe=await te.arrayBuffer();let le=fe;if(r){Q.abort();return}if(z>0&&(le=new Uint8Array(fe).subarray(z),z-=fe.byteLength-le.length),!le.byteLength)continue;s+=le.byteLength;const ke=o.decode(le);k.enqueue(ke)}}}if(I=0,D.content){let Q=D.content,ue=a.encode(D.content);if(z>0){const re=ue.subarray(z);if(z-=ue.length-re.length,!re.length)continue;ue=re,Q=o.decode(re)}s+=ue.length,k.enqueue(Q)}}}async function h(b){let k=!0,ee=0;for(;k;){k=!1;let D=Date.now()+Math.min(15e3,500*(ee-1));const z=await w({...t,offset:s},b);z!=null&&z.retry&&(k=!0,ee++,D<Date.now()-3e5&&(ee=0),await new Promise(Q=>{setTimeout(Q,Math.max(0,D-Date.now()))}))}!r&&!c&&(b.close(),f())}return{stream:new e({start(b){h(b)},cancel(b){r=!0,u&&i({eventId:u}),f()}}),addCloseCb:m,closed(){return c}}}class fi{constructor({WStream:t,RStream:n,trySend:i,log:s}){l(this,"trySend");l(this,"WStream");l(this,"RStream");l(this,"writeStreams",{});l(this,"startWriteStreamCbs",{});l(this,"readStreamIterators",{});l(this,"log");l(this,"activeStreams",new Set);this.WStream=t,this.RStream=n,this.trySend=i,this.log=s}createWriteStream(t){const{stream:n,addCompleteCb:i}=ai({WStream:this.WStream,startStream:this.startWriteStream.bind(this),appendStream:this.appendStream.bind(this),registerStream:this.registerWriteStream.bind(this),opts:t});return this.activeStreams.add(n),i(()=>{this.activeStreams.delete(n)}),n}createReadStream(t){const{stream:n,addCloseCb:i}=ui({RStream:this.RStream,opts:t,startStream:this.startReadStream.bind(this),cancelStream:this.cancelReadStream.bind(this)});return this.activeStreams.add(n),i(()=>{this.activeStreams.delete(n)}),n}startWriteStream(t){const n=Ce();let i=null;const s=new Promise(o=>{i=o});this.startWriteStreamCbs[n]=i;const r={op:"start-stream","client-id":t.clientId,"reconnect-token":t.reconnectToken};return t.ruleParams&&(r["rule-params"]=t.ruleParams),this.trySend(n,r),s}registerWriteStream(t,n){this.writeStreams[t]=n}appendStream({streamId:t,chunks:n,isDone:i,offset:s,abortReason:r}){const o={op:"append-stream","stream-id":t,chunks:n,offset:s,done:!!i};r&&(o["abort-reason"]=r),this.trySend(Ce(),o)}onAppendFailed(t){const n=this.writeStreams[t["stream-id"]];n&&n.onAppendFailed()}onStartStreamOk(t){const n=this.startWriteStreamCbs[t["client-event-id"]];if(!n){this.log.info("No stream for start-stream-ok",t);return}n({type:"ok",streamId:t["stream-id"],offset:t.offset}),delete this.startWriteStreamCbs[t["client-event-id"]]}onStreamFlushed(t){const n=t["stream-id"],i=this.writeStreams[n];if(!i){this.log.info("No stream cbs for stream-flushed",t);return}i.onFlush({offset:t.offset,done:t.done}),t.done&&delete this.writeStreams[n]}startReadStream({eventId:t,clientId:n,streamId:i,offset:s,ruleParams:r}){const o={op:"subscribe-stream"};if(!i&&!n)throw new Error("Must provide one of streamId or clientId to subscribe to the stream.");i&&(o["stream-id"]=i),n&&(o["client-id"]=n),s&&(o.offset=s),r&&(o["rule-params"]=r);const a=new ci;return this.readStreamIterators[t]=a,this.trySend(t,o),a}cancelReadStream({eventId:t}){const n={op:"unsubscribe-stream","subscribe-event-id":t};this.trySend(Ce(),n),delete this.readStreamIterators[t]}onStreamAppend(t){var s;const n=t["client-event-id"],i=this.readStreamIterators[n];if(!i){this.log.info("No iterator for read stream",t);return}if(t.error){t.retry?i.push({type:"reconnect"}):i.push({type:"error",error:new B(t.error)}),i.close(),delete this.readStreamIterators[n];return}((s=t.files)!=null&&s.length||t.content)&&i.push({type:"append",offset:t.offset,files:t.files,content:t.content}),t.done&&(i.close(),delete this.readStreamIterators[n])}onConnectionStatusChange(t){for(const n of Object.values(this.startWriteStreamCbs))n({type:"disconnect"});if(this.startWriteStreamCbs={},t!==li.AUTHENTICATED)for(const{onDisconnect:n}of Object.values(this.writeStreams))n();else{for(const{onConnectionReconnect:n}of Object.values(this.writeStreams))n();for(const n of Object.values(this.readStreamIterators))n.push({type:"reconnect"}),n.close();this.readStreamIterators={}}}onRecieveError(t){const n=t["original-event"];switch(n.op){case"append-stream":{const i=n["stream-id"],s=this.writeStreams[i];s==null||s.onAppendFailed();break}case"start-stream":{const i=t["client-event-id"],s=this.startWriteStreamCbs[i];s&&(s({type:"error",error:new B(t.message||"Unknown error",t.hint)}),delete this.startWriteStreamCbs[i]);break}case"subscribe-stream":{const i=t["client-event-id"],s=this.readStreamIterators[i];s&&(s.push({type:"error",error:new B(t.message||"Unknown error",t.hint)}),s.close(),delete this.readStreamIterators[i]);break}}}hasActiveStreams(){return this.activeStreams.size>0}}const li={AUTHENTICATED:"authenticated"};function di(){return globalThis.__instantDbSchemaHashStore=globalThis.__instantDbSchemaHashStore??new WeakMap,globalThis.__instantDbSchemaHashStore}function hi(){return globalThis.__instantDbStore=globalThis.__instantDbStore??{},globalThis.__instantDbStore}hi(),di();class cn extends Error{constructor(t,n){super(t),this.name="ParseError",this.type=n.type,this.field=n.field,this.value=n.value,this.line=n.line}}function bt(e){}function pi(e){if(typeof e=="function")throw new TypeError("`callbacks` must be an object, got a function instead. Did you mean `{onEvent: fn}`?");const{onEvent:t=bt,onError:n=bt,onRetry:i=bt,onComment:s}=e;let r="",o=!0,a,u="",c="";function d(w){const h=o?w.replace(/^\xEF\xBB\xBF/,""):w,[O,b]=mi(`${r}${h}`);for(const k of O)f(k);r=b,o=!1}function f(w){if(w===""){y();return}if(w.startsWith(":")){s&&s(w.slice(w.startsWith(": ")?2:1));return}const h=w.indexOf(":");if(h!==-1){const O=w.slice(0,h),b=w[h+1]===" "?2:1,k=w.slice(h+b);m(O,k,w);return}m(w,"",w)}function m(w,h,O){switch(w){case"event":c=h;break;case"data":u=`${u}${h}
|
|
2
2
|
`;break;case"id":a=h.includes("\0")?void 0:h;break;case"retry":/^\d+$/.test(h)?i(parseInt(h,10)):n(new cn(`Invalid \`retry\` value: "${h}"`,{type:"invalid-retry",value:h,line:O}));break;default:n(new cn(`Unknown field "${w.length>20?`${w.slice(0,20)}…`:w}"`,{type:"unknown-field",field:w,value:h,line:O}));break}}function y(){u.length>0&&t({id:a,event:c||void 0,data:u.endsWith(`
|
|
3
|
-
`)?u.slice(0,-1):u}),a=void 0,u="",c=""}function I(w={}){r&&w.consume&&f(r),o=!0,a=void 0,u="",c="",r=""}return{feed:
|
|
3
|
+
`)?u.slice(0,-1):u}),a=void 0,u="",c=""}function I(w={}){r&&w.consume&&f(r),o=!0,a=void 0,u="",c="",r=""}return{feed:d,reset:I}}function mi(e){const t=[];let n="",i=0;for(;i<e.length;){const s=e.indexOf("\r",i),r=e.indexOf(`
|
|
4
4
|
`,i);let o=-1;if(s!==-1&&r!==-1?o=Math.min(s,r):s!==-1?o=s:r!==-1&&(o=r),o===-1){n=e.slice(i);break}else{const a=e.slice(i,o);t.push(a),i=o+1,e[i-1]==="\r"&&e[i]===`
|
|
5
|
-
`&&i++}}return[t,n]}class un extends Event{constructor(t,n){var i,s;super(t),this.code=(i=n==null?void 0:n.code)!=null?i:void 0,this.message=(s=n==null?void 0:n.message)!=null?s:void 0}[Symbol.for("nodejs.util.inspect.custom")](t,n,i){return i(fn(this),n)}[Symbol.for("Deno.customInspect")](t,n){return t(fn(this),n)}}function yi(e){const t=globalThis.DOMException;return typeof t=="function"?new t(e,"SyntaxError"):new SyntaxError(e)}function gt(e){return e instanceof Error?"errors"in e&&Array.isArray(e.errors)?e.errors.map(gt).join(", "):"cause"in e&&e.cause instanceof Error?`${e}: ${gt(e.cause)}`:e.message:`${e}`}function fn(e){return{type:e.type,message:e.message,code:e.code,defaultPrevented:e.defaultPrevented,cancelable:e.cancelable,timeStamp:e.timeStamp}}var ln=e=>{throw TypeError(e)},wt=(e,t,n)=>t.has(e)||ln("Cannot "+n),S=(e,t,n)=>(wt(e,t,"read from private field"),n?n.call(e):t.get(e)),j=(e,t,n)=>t.has(e)?ln("Cannot add the same private member more than once"):t instanceof WeakSet?t.add(e):t.set(e,n),T=(e,t,n,i)=>(wt(e,t,"write to private field"),t.set(e,n),n),ae=(e,t,n)=>(wt(e,t,"access private method"),n),J,ve,Re,Ke,Xe,Fe,Ae,ze,me,Pe,je,Me,Ve,Z,St,It,vt,dn,Ot,$t,Je,kt,Et;class se extends EventTarget{constructor(t,n){var i,s;super(),j(this,Z),this.CONNECTING=0,this.OPEN=1,this.CLOSED=2,j(this,J),j(this,ve),j(this,Re),j(this,Ke),j(this,Xe),j(this,Fe),j(this,Ae),j(this,ze,null),j(this,me),j(this,Pe),j(this,je,null),j(this,Me,null),j(this,Ve,null),j(this,It,async r=>{var o;S(this,Pe).reset();const{body:a,redirected:u,status:c,headers:l}=r;if(c===204){ae(this,Z,Je).call(this,"Server sent HTTP 204, not reconnecting",204),this.close();return}if(u?T(this,Re,new URL(r.url)):T(this,Re,void 0),c!==200){ae(this,Z,Je).call(this,`Non-200 status code (${c})`,c);return}if(!(l.get("content-type")||"").startsWith("text/event-stream")){ae(this,Z,Je).call(this,'Invalid content type, expected "text/event-stream"',c);return}if(S(this,J)===this.CLOSED)return;T(this,J,this.OPEN);const f=new Event("open");if((o=S(this,Ve))==null||o.call(this,f),this.dispatchEvent(f),typeof a!="object"||!a||!("getReader"in a)){ae(this,Z,Je).call(this,"Invalid response body, expected a web ReadableStream",c),this.close();return}const m=new TextDecoder,y=a.getReader();let I=!0;do{const{done:w,value:h}=await y.read();h&&S(this,Pe).feed(m.decode(h,{stream:!w})),w&&(I=!1,S(this,Pe).reset(),ae(this,Z,kt).call(this))}while(I)}),j(this,vt,r=>{T(this,me,void 0),!(r.name==="AbortError"||r.type==="aborted")&&ae(this,Z,kt).call(this,gt(r))}),j(this,Ot,r=>{typeof r.id=="string"&&T(this,ze,r.id);const o=new MessageEvent(r.event||"message",{data:r.data,origin:S(this,Re)?S(this,Re).origin:S(this,ve).origin,lastEventId:r.id||""});S(this,Me)&&(!r.event||r.event==="message")&&S(this,Me).call(this,o),this.dispatchEvent(o)}),j(this,$t,r=>{T(this,Fe,r)}),j(this,Et,()=>{T(this,Ae,void 0),S(this,J)===this.CONNECTING&&ae(this,Z,St).call(this)});try{if(t instanceof URL)T(this,ve,t);else if(typeof t=="string")T(this,ve,new URL(t,bi()));else throw new Error("Invalid URL")}catch{throw yi("An invalid or illegal string was specified")}T(this,Pe,pi({onEvent:S(this,Ot),onRetry:S(this,$t)})),T(this,J,this.CONNECTING),T(this,Fe,3e3),T(this,Xe,(i=n==null?void 0:n.fetch)!=null?i:globalThis.fetch),T(this,Ke,(s=n==null?void 0:n.withCredentials)!=null?s:!1),ae(this,Z,St).call(this)}get readyState(){return S(this,J)}get url(){return S(this,ve).href}get withCredentials(){return S(this,Ke)}get onerror(){return S(this,je)}set onerror(t){T(this,je,t)}get onmessage(){return S(this,Me)}set onmessage(t){T(this,Me,t)}get onopen(){return S(this,Ve)}set onopen(t){T(this,Ve,t)}addEventListener(t,n,i){const s=n;super.addEventListener(t,s,i)}removeEventListener(t,n,i){const s=n;super.removeEventListener(t,s,i)}close(){S(this,Ae)&&clearTimeout(S(this,Ae)),S(this,J)!==this.CLOSED&&(S(this,me)&&S(this,me).abort(),T(this,J,this.CLOSED),T(this,me,void 0))}}J=new WeakMap,ve=new WeakMap,Re=new WeakMap,Ke=new WeakMap,Xe=new WeakMap,Fe=new WeakMap,Ae=new WeakMap,ze=new WeakMap,me=new WeakMap,Pe=new WeakMap,je=new WeakMap,Me=new WeakMap,Ve=new WeakMap,Z=new WeakSet,St=function(){T(this,J,this.CONNECTING),T(this,me,new AbortController),S(this,Xe)(S(this,ve),ae(this,Z,dn).call(this)).then(S(this,It)).catch(S(this,vt))},It=new WeakMap,vt=new WeakMap,dn=function(){var e;const t={mode:"cors",redirect:"follow",headers:{Accept:"text/event-stream",...S(this,ze)?{"Last-Event-ID":S(this,ze)}:void 0},cache:"no-store",signal:(e=S(this,me))==null?void 0:e.signal};return"window"in globalThis&&(t.credentials=this.withCredentials?"include":"same-origin"),t},Ot=new WeakMap,$t=new WeakMap,Je=function(e,t){var n;S(this,J)!==this.CLOSED&&T(this,J,this.CLOSED);const i=new un("error",{code:t,message:e});(n=S(this,je))==null||n.call(this,i),this.dispatchEvent(i)},kt=function(e,t){var n;if(S(this,J)===this.CLOSED)return;T(this,J,this.CONNECTING);const i=new un("error",{code:t,message:e});(n=S(this,je))==null||n.call(this,i),this.dispatchEvent(i),T(this,Ae,setTimeout(S(this,Et),S(this,Fe)))},Et=new WeakMap,se.CONNECTING=0,se.OPEN=1,se.CLOSED=2;function bi(){const e="document"in globalThis?globalThis.document:void 0;return e&&typeof e=="object"&&"baseURI"in e&&typeof e.baseURI=="string"?e.baseURI:void 0}function gi(e,t,n,i){let s=null,r=!1;const o=[],a=f=>{o.push(f),o.length>100&&o.shift(),s&&(s(),s=null)};e(a);const u=()=>(n(a),Promise.resolve({done:!0,value:void 0}));return t(()=>{r=!0,s&&s(),u()}),{next:async()=>{for(;;){if(i()==="closed"||r)return u();const f=o.shift();if(f)return{value:f,done:!1};await new Promise(y=>{s=y})}},return:u,throw(f){return n(a),Promise.reject(f)},[Symbol.asyncIterator](){return this}}}function ye(e){switch(e.readyState){case e.CLOSED:return"closed";case e.CONNECTING:return"connecting";case e.OPEN:return"open";default:return"connecting"}}function wi(e){let t=null;return{...e,text(){return t||(t=e.text()),t},json(){return t||(t=e.text()),t.then(n=>JSON.parse(n))}}}function hn(e){if(!e)return;const t={};for(const[n,i]of Object.entries(e))t[n]={startCursor:i["start-cursor"],endCursor:i["end-cursor"],hasNextPage:i["has-next-page?"],hasPreviousPage:i["has-previous-page?"]};return t}function Si(e,t,n){let i,s=!1;const r=Ce(),o=new se(`${n.apiURI}/admin/subscribe-query?local_connection_id=${r}`,{fetch(h,O){return i=null,fetch(h,{...O,method:"POST",headers:n.headers,body:JSON.stringify({query:e,"inference?":n.inference,versions:{"@instantdb/admin":xe,"@instantdb/core":xe}})}).then(b=>(b.ok||(i=wi(b)),b))}}),a=[],u=[],c=h=>{a.push(h)},l=h=>{a.splice(a.indexOf(h),1)},f=h=>{u.push(h)};t&&c(t);let m=null;function y(h){if(!s)for(const O of a)try{O(h)}catch(b){console.error("Error in subscribeQuery callback",b)}}function I(h){var O,b;switch(h.op){case"sse-init":{const k=h["machine-id"],ee=h["session-id"];m={machineId:k,sessionId:ee};break}case"add-query-ok":{y({type:"ok",data:h.result,pageInfo:hn((O=h["result-meta"])==null?void 0:O["page-info"]),sessionInfo:m});break}case"refresh-ok":{h.computations.length&&y({type:"ok",data:h.computations[0]["instaql-result"],pageInfo:hn((b=h.computations[0]["result-meta"])==null?void 0:b["page-info"]),sessionInfo:m});break}case"error":{y({type:"error",error:new Ie({body:h,status:h.status}),get readyState(){return ye(o)},get isClosed(){return ye(o)==="closed"},sessionInfo:m});break}}}return o.onerror=h=>{if(i)i.text().then(O=>{let b={type:void 0,message:O};try{b=JSON.parse(O)}catch{}y({type:"error",error:new Ie({status:i.status,body:b}),get readyState(){return ye(o)},get isClosed(){return ye(o)==="closed"},sessionInfo:m})});else{const O=()=>{y({type:"error",error:new Ie({status:h.code||500,body:{type:void 0,message:h.message||"Unknown error in subscribe query."}}),get readyState(){return ye(o)},get isClosed(){return ye(o)==="closed"},sessionInfo:m})};if(o.readyState===se.CLOSED){O();return}setTimeout(()=>{o.readyState!==se.OPEN&&O()},5e3)}},o.onmessage=h=>{I(JSON.parse(h.data))},{close:()=>{s=!0;for(const h of u)try{h()}catch(O){console.error("Error in onClose callback",O)}o.close()},[Symbol.iterator]:()=>{throw new Error("subscribeQuery does not support synchronous iteration. Use `for await` instead.")},get sessionInfo(){return m},get readyState(){return ye(o)},get isClosed(){return ye(o)==="closed"},[Symbol.asyncIterator]:gi.bind(this,c,f,l,()=>1)}}var ce={};Object.defineProperty(ce,"__esModule",{value:!0});var Ii=ce.parseCookie=yn;ce.parse=yn,ce.stringifyCookie=_i,ce.stringifySetCookie=Ye,ce.serialize=Ye,ce.parseSetCookie=Ci,ce.stringifySetCookie=Ye,ce.serialize=Ye;const pn=/^[\u0021-\u003A\u003C\u003E-\u007E]+$/,mn=/^[\u0021-\u003A\u003C-\u007E]*$/,vi=/^([.]?[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?)([.][a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?)*$/i,Oi=/^[\u0020-\u003A\u003D-\u007E]*$/,$i=/^-?\d+$/,ki=Object.prototype.toString,Ei=(()=>{const e=function(){};return e.prototype=Object.create(null),e})();function yn(e,t){const n=new Ei,i=e.length;if(i<2)return n;const s=(t==null?void 0:t.decode)||bn;let r=0;do{const o=Ct(e,r,i);if(o===-1)break;const a=_t(e,r,i);if(o>a){r=e.lastIndexOf(";",o-1)+1;continue}const u=be(e,r,o);n[u]===void 0&&(n[u]=s(be(e,o+1,a))),r=a+1}while(r<i);return n}function _i(e,t){const n=(t==null?void 0:t.encode)||encodeURIComponent,i=[];for(const s of Object.keys(e)){const r=e[s];if(r===void 0)continue;if(!pn.test(s))throw new TypeError(`cookie name is invalid: ${s}`);const o=n(r);if(!mn.test(o))throw new TypeError(`cookie val is invalid: ${r}`);i.push(`${s}=${o}`)}return i.join("; ")}function Ye(e,t,n){const i=typeof e=="object"?e:{...n,name:e,value:String(t)},s=typeof t=="object"?t:n,r=(s==null?void 0:s.encode)||encodeURIComponent;if(!pn.test(i.name))throw new TypeError(`argument name is invalid: ${i.name}`);const o=i.value?r(i.value):"";if(!mn.test(o))throw new TypeError(`argument val is invalid: ${i.value}`);let a=i.name+"="+o;if(i.maxAge!==void 0){if(!Number.isInteger(i.maxAge))throw new TypeError(`option maxAge is invalid: ${i.maxAge}`);a+="; Max-Age="+i.maxAge}if(i.domain){if(!vi.test(i.domain))throw new TypeError(`option domain is invalid: ${i.domain}`);a+="; Domain="+i.domain}if(i.path){if(!Oi.test(i.path))throw new TypeError(`option path is invalid: ${i.path}`);a+="; Path="+i.path}if(i.expires){if(!xi(i.expires)||!Number.isFinite(i.expires.valueOf()))throw new TypeError(`option expires is invalid: ${i.expires}`);a+="; Expires="+i.expires.toUTCString()}if(i.httpOnly&&(a+="; HttpOnly"),i.secure&&(a+="; Secure"),i.partitioned&&(a+="; Partitioned"),i.priority)switch(typeof i.priority=="string"?i.priority.toLowerCase():void 0){case"low":a+="; Priority=Low";break;case"medium":a+="; Priority=Medium";break;case"high":a+="; Priority=High";break;default:throw new TypeError(`option priority is invalid: ${i.priority}`)}if(i.sameSite)switch(typeof i.sameSite=="string"?i.sameSite.toLowerCase():i.sameSite){case!0:case"strict":a+="; SameSite=Strict";break;case"lax":a+="; SameSite=Lax";break;case"none":a+="; SameSite=None";break;default:throw new TypeError(`option sameSite is invalid: ${i.sameSite}`)}return a}function Ci(e,t){const n=(t==null?void 0:t.decode)||bn,i=e.length,s=_t(e,0,i),r=Ct(e,0,s),o=r===-1?{name:"",value:n(be(e,0,s))}:{name:be(e,0,r),value:n(be(e,r+1,s))};let a=s+1;for(;a<i;){const u=_t(e,a,i),c=Ct(e,a,u),l=c===-1?be(e,a,u):be(e,a,c),f=c===-1?void 0:be(e,c+1,u);switch(l.toLowerCase()){case"httponly":o.httpOnly=!0;break;case"secure":o.secure=!0;break;case"partitioned":o.partitioned=!0;break;case"domain":o.domain=f;break;case"path":o.path=f;break;case"max-age":f&&$i.test(f)&&(o.maxAge=Number(f));break;case"expires":if(!f)break;const m=new Date(f);Number.isFinite(m.valueOf())&&(o.expires=m);break;case"priority":if(!f)break;const y=f.toLowerCase();(y==="low"||y==="medium"||y==="high")&&(o.priority=y);break;case"samesite":if(!f)break;const I=f.toLowerCase();(I==="lax"||I==="strict"||I==="none")&&(o.sameSite=I);break}a=u+1}return o}function _t(e,t,n){const i=e.indexOf(";",t);return i===-1?n:i}function Ct(e,t,n){const i=e.indexOf("=",t);return i<n?i:-1}function be(e,t,n){let i=t,s=n;do{const r=e.charCodeAt(i);if(r!==32&&r!==9)break}while(++i<s);for(;s>i;){const r=e.charCodeAt(s-1);if(r!==32&&r!==9)break;s--}return e.slice(i,s)}function bn(e){if(e.indexOf("%")===-1)return e;try{return decodeURIComponent(e)}catch{return e}}function xi(e){return ki.call(e)==="[object Date]"}function Ti(e){return{...{apiURI:"https://api.instantdb.com"},...e}}function Ri(e,t){return"email"in t?e["as-email"]=t.email:"token"in t?e["as-token"]=t.token:"guest"in t&&(e["as-guest"]="true"),e}function Ai(e,t){if(!(t&&("token"in t||"guest"in t))&&!e.adminToken)throw t&&"email"in t?new Error("Admin token required. To impersonate users with an email you must pass `adminToken` to `init`."):new Error("Admin token required. To run this operation pass `adminToken` to `init`, or use `db.asUser`.")}function A(e,t){Ai(e,t);const{adminToken:n,appId:i}=e,s={"content-type":"application/json","app-id":i};return n&&(s.authorization=`Bearer ${n}`),t?Ri(s,t):s}function Pi(){return fetch.__nextPatched&&!globalThis[Symbol.for("next-patch")]}function ji(){return Pi()?{cache:"no-store"}:{}}async function Mi(e,t){const n=await t.text();try{const i=JSON.parse(n);return e(new Ie({status:t.status,body:i}))}catch{return e(new Ie({status:t.status,body:{type:void 0,message:n}}))}}async function M(e,t){const n=ji(),i={...(t==null?void 0:t.headers)||{},"Instant-Admin-Version":xe,"Instant-Core-Version":xe},s=await fetch(e,{...n,...t,headers:i});if(s.status===200){const r=await s.json();return Promise.resolve(r)}return Mi(r=>Promise.reject(r),s)}function Ui(e){var t,n,vn;return t=class{constructor(r){K(this,n);d(this,"source");d(this,"url");this.url=r,this.source=X(this,n,vn).call(this,r)}get onopen(){return this.source.onopen}set onopen(r){this.source.onopen=r}get onmessage(){return this.source.onmessage}set onmessage(r){this.source.onmessage=r}get onerror(){return this.source.onerror}set onerror(r){this.source.onerror=r}get readyState(){return this.source.readyState}close(){this.source.close()}},n=new WeakSet,vn=function(r){return new se(r,{fetch(a,u){return fetch(a,{...u,method:"POST",headers:e.headers,body:JSON.stringify({"inference?":e.inference,versions:{"@instantdb/admin":xe,"@instantdb/core":xe}})})}})},d(t,"OPEN",se.OPEN),d(t,"CONNECTING",se.CONNECTING),d(t,"CLOSED",se.CLOSED),t}function Di(e){var n,i;(!e.appId||!x(e.appId))&&console.warn("warning: Instant Admin DB must be initialized with a valid appId. Received: "+JSON.stringify(e.appId));const t={...e,appId:(n=e.appId)==null?void 0:n.trim(),adminToken:(i=e.adminToken)==null?void 0:i.trim(),useDateObjects:e.useDateObjects??!1};return new xt(t)}function gn(e){return(Array.isArray(e)?e:[e]).flatMap(qn)}class Ni{constructor(t){d(this,"config");this.config=t}async getPresence(t,n){return(await M(`${this.config.apiURI}/admin/rooms/presence?app_id=${this.config.appId}&room-type=${String(t)}&room-id=${n}`,{method:"GET",headers:A(this.config)})).sessions||{}}}class Li{constructor(t){d(this,"config");d(this,"generateMagicCode",async t=>M(`${this.config.apiURI}/admin/magic_code?app_id=${this.config.appId}`,{method:"POST",headers:A(this.config),body:JSON.stringify({email:t})}));d(this,"sendMagicCode",async t=>M(`${this.config.apiURI}/admin/send_magic_code?app_id=${this.config.appId}`,{method:"POST",headers:A(this.config),body:JSON.stringify({email:t})}));d(this,"verifyMagicCode",async(t,n)=>{const{user:i}=await M(`${this.config.apiURI}/admin/verify_magic_code?app_id=${this.config.appId}`,{method:"POST",headers:A(this.config),body:JSON.stringify({email:t,code:n})});return i});d(this,"verifyToken",async t=>(await M(`${this.config.apiURI}/runtime/auth/verify_refresh_token?app_id=${this.config.appId}`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({"app-id":this.config.appId,"refresh-token":t})})).user);d(this,"getUser",async t=>{const n=Object.entries(t).map(([s,r])=>`${s}=${encodeURIComponent(r)}`).join("&");return(await M(`${this.config.apiURI}/admin/users?app_id=${this.config.appId}&${n}`,{method:"GET",headers:A(this.config)})).user});d(this,"deleteUser",async t=>{const n=Object.entries(t).map(([s,r])=>`${s}=${r}`);return(await M(`${this.config.apiURI}/admin/users?app_id=${this.config.appId}&${n}`,{method:"DELETE",headers:A(this.config)})).deleted});d(this,"getUserFromRequest",async(t,n)=>{const i=t.headers.get("cookie")||"",s=Ii(i),r="instant_user_"+this.config.appId;if(!s[r])return null;const o=s[r],a=JSON.parse(o);return a!=null&&a.refresh_token?n!=null&&n.disableValidation?a:await this.verifyToken(a.refresh_token):null});this.config=t,this.createToken=this.createToken.bind(this)}async createToken(t){const n=typeof t=="string"?{email:t}:t;return(await M(`${this.config.apiURI}/admin/refresh_tokens?app_id=${this.config.appId}`,{method:"POST",headers:A(this.config),body:JSON.stringify(n)})).user.refresh_token}async signOut(t){const n=typeof t=="string"?{email:t}:t,i=this.config;await M(`${i.apiURI}/admin/sign_out?app_id=${this.config.appId}`,{method:"POST",headers:A(i),body:JSON.stringify(n)})}}const wn=e=>e&&typeof e=="object"&&typeof e.pipe=="function"&&typeof e.read=="function",Wi=e=>e&&typeof e.getReader=="function";class Sn{constructor(t,n){d(this,"config");d(this,"impersonationOpts");d(this,"uploadFile",async(t,n,i={})=>{const s={...A(this.config,this.impersonationOpts),path:t};i.contentDisposition&&(s["content-disposition"]=i.contentDisposition),delete s["content-type"],i.contentType&&(s["content-type"]=i.contentType);let r;if(wn(n)&&(r="half"),wn(n)||Wi(n)){if(!i.fileSize)throw new Error("fileSize is required in metadata when uploading streams");s["content-length"]=i.fileSize.toString()}let o={method:"PUT",headers:s,body:n,...r&&{duplex:r}};return M(`${this.config.apiURI}/admin/storage/upload?app_id=${this.config.appId}`,o)});d(this,"delete",async t=>M(`${this.config.apiURI}/admin/storage/files?app_id=${this.config.appId}&filename=${encodeURIComponent(t)}`,{method:"DELETE",headers:A(this.config,this.impersonationOpts)}));d(this,"deleteMany",async t=>M(`${this.config.apiURI}/admin/storage/files/delete?app_id=${this.config.appId}`,{method:"POST",headers:A(this.config,this.impersonationOpts),body:JSON.stringify({filenames:t})}));d(this,"upload",async(t,n,i={})=>{const{data:s}=await M(`${this.config.apiURI}/admin/storage/signed-upload-url?app_id=${this.config.appId}`,{method:"POST",headers:A(this.config),body:JSON.stringify({app_id:this.config.appId,filename:t})}),r={},o=i.contentType;o&&(r["Content-Type"]=o);const{ok:a}=await fetch(s,{method:"PUT",body:n,headers:r});return a});d(this,"list",async()=>{const{data:t}=await M(`${this.config.apiURI}/admin/storage/files?app_id=${this.config.appId}`,{method:"GET",headers:A(this.config)});return t});d(this,"getDownloadUrl",async t=>{const{data:n}=await M(`${this.config.apiURI}/admin/storage/signed-download-url?app_id=${this.config.appId}&filename=${encodeURIComponent(t)}`,{method:"GET",headers:A(this.config)});return n});this.config=t,this.impersonationOpts=n}}class Fi{constructor(t){K(this,Ue);d(this,"createReadStream",t=>g(this,Ue).call(this).createReadStream(t));d(this,"createWriteStream",t=>g(this,Ue).call(this).createWriteStream(t));he(this,Ue,t)}}Ue=new WeakMap;function zi(e){return{info:e?(...t)=>console.info(...t):()=>{},debug:e?(...t)=>console.debug(...t):()=>{},error:e?(...t)=>console.error(...t):()=>{}}}const Rt=class Rt{constructor(t){K(this,U);d(this,"config");d(this,"auth");d(this,"storage");d(this,"streams");d(this,"rooms");d(this,"impersonationOpts");K(this,N,null);K(this,Oe,0);K(this,W,null);K(this,F);d(this,"tx",Kt());d(this,"asUser",t=>{const n=new Rt({...this.config});return n.impersonationOpts=t,n.storage=new Sn(this.config,t),n});d(this,"query",(t,n={})=>{t&&n&&"ruleParams"in n&&(t={$$ruleParams:n.ruleParams,...t}),this.config.disableValidation||tn(t,this.config.schema);const i=n.fetchOpts||{},s=i.headers||{};return M(`${this.config.apiURI}/admin/query?app_id=${this.config.appId}`,{...i,method:"POST",headers:{...s,...A(this.config,this.impersonationOpts)},body:JSON.stringify({query:t,"inference?":!!this.config.schema})})});d(this,"transact",t=>(this.config.disableValidation||si(t,this.config.schema),M(`${this.config.apiURI}/admin/transact?app_id=${this.config.appId}`,{method:"POST",headers:A(this.config,this.impersonationOpts),body:JSON.stringify({steps:gn(t),"throw-on-missing-attrs?":!!this.config.schema})})));d(this,"debugQuery",async(t,n)=>{t&&n&&"ruleParams"in n&&(t={$$ruleParams:n.ruleParams,...t});const i={query:t,"rules-override":n==null?void 0:n.rules};n!=null&&n.ip&&(i["ip-override"]=n.ip),n!=null&&n.origin&&(i["origin-override"]=n.origin);const s=await M(`${this.config.apiURI}/admin/query_perms_check?app_id=${this.config.appId}`,{method:"POST",headers:A(this.config,this.impersonationOpts),body:JSON.stringify(i)});return{result:s.result,checkResults:s["check-results"]}});d(this,"debugTransact",(t,n)=>{const i={steps:gn(t),"rules-override":n==null?void 0:n.rules,"dangerously-commit-tx":n==null?void 0:n.__dangerouslyCommit};return n!=null&&n.ip&&(i["ip-override"]=n.ip),n!=null&&n.origin&&(i["origin-override"]=n.origin),M(`${this.config.apiURI}/admin/transact_perms_check?app_id=${this.config.appId}`,{method:"POST",headers:A(this.config,this.impersonationOpts),body:JSON.stringify(i)})});K(this,et,t=>{var n;if(t.target!==g(this,N)){g(this,F).info("[socket][open]",t.target.id,"skip; this is no longer the current transport");return}g(this,F).info("[socket][open]",t.target.id),he(this,Oe,0),(n=g(this,W))==null||n.onConnectionStatusChange("authenticated")});K(this,tt,t=>{var n;if(t.target!==g(this,N)){g(this,F).info("[socket][close]",t.target.id,"skip; this is no longer the current transport");return}g(this,F).info("[socket][close]",t.target.id),(n=g(this,W))==null||n.onConnectionStatusChange("closed"),g(this,N)&&(he(this,N,null),X(this,U,Ut).call(this)||(setTimeout(()=>X(this,U,st).call(this),g(this,Oe)),he(this,Oe,Math.min(15e3,Math.max(g(this,Oe),500)*2))))});K(this,nt,t=>{var n;if(t.target!==g(this,N)){g(this,F).info("[socket][error]",t.target.id,"skip; this is no longer the current transport");return}g(this,F).info("[socket][error]",t.target.id),(n=g(this,W))==null||n.onConnectionStatusChange("closed")});K(this,it,t=>{var i,s,r,o,a,u;if(t.target!==g(this,N)){g(this,F).info("[socket][message]",t.target.id,"skip; this is no longer the current transport");return}const n=t.message;switch(g(this,F).info("[receive]",n),n.op){case"start-stream-ok":{(i=g(this,W))==null||i.onStartStreamOk(n);break}case"stream-flushed":{(s=g(this,W))==null||s.onStreamFlushed(n);break}case"append-failed":{(r=g(this,W))==null||r.onAppendFailed(n);break}case"stream-append":{(o=g(this,W))==null||o.onStreamAppend(n);break}case"error":{switch((a=n["original-event"])==null?void 0:a.op){case"start-stream":case"append-stream":case"subscribe-stream":case"unsubscribe-stream":{(u=g(this,W))==null||u.onRecieveError(n);break}}break}}X(this,U,_n).call(this)});this.config=Ti(t),this.auth=new Li(this.config),this.storage=new Sn(this.config,this.impersonationOpts),this.streams=new Fi(X(this,U,En).bind(this)),this.rooms=new Ni(this.config),he(this,F,zi(!!this.config.verbose))}subscribeQuery(t,n,i={}){t&&i&&"ruleParams"in i&&(t={$$ruleParams:i.ruleParams,...t}),this.config.disableValidation||tn(t,this.config.schema);const o={...(i.fetchOpts||{}).headers||{},...A(this.config,this.impersonationOpts)},a=!!this.config.schema;return Si(t,n,{headers:o,inference:a,apiURI:this.config.apiURI})}};N=new WeakMap,Oe=new WeakMap,W=new WeakMap,F=new WeakMap,U=new WeakSet,On=function(){g(this,N)&&g(this,N).close();const t={...A(this.config,this.impersonationOpts)},n=!!this.config.schema,i=Ui({headers:t,inference:n}),s=new oi(i,`${this.config.apiURI}/admin/sse?app_id=${this.config.appId}`,`${this.config.apiURI}/admin/sse/push?app_id=${this.config.appId}`);return s.onopen=g(this,et),s.onmessage=g(this,it),s.onclose=g(this,tt),s.onerror=g(this,nt),he(this,N,s),s},st=function(){return g(this,N)||X(this,U,On).call(this)},$n=function(t,n){const i=X(this,U,st).call(this);g(this,F).info("[send]",t,n,{isOpen:i.isOpen()}),i.isOpen()&&i.send({"client-event-id":t,...n})},kn=function(){X(this,U,st).call(this);const t=new fi({WStream:this.config.WritableStream||WritableStream,RStream:this.config.ReadableStream||ReadableStream,trySend:(n,i)=>{X(this,U,$n).call(this,n,i)},log:g(this,F)});return he(this,W,t),t},En=function(){return g(this,W)||X(this,U,kn).call(this)},et=new WeakMap,tt=new WeakMap,nt=new WeakMap,Ut=function(){return!g(this,W)||!g(this,W).hasActiveStreams()},_n=function(){if(g(this,N)&&X(this,U,Ut).call(this)){const t=g(this,N);g(this,F).info("cleaning up unused socket",t.id),he(this,N,null),t.close()}},it=new WeakMap;let xt=Rt;var Tt={};function Ze(e){let t=e;return new TransformStream({transform(n,i){if(!t){i.enqueue(n);return}if(t>n.length){t-=n.length;return}const s=n.slice(t);t=0,i.enqueue(s)}})}function Vi(e){const t=e.appId||Tt.INSTANT_APP_ID;if(!t)throw new Error("Missing appId. Pass it as an argument to createResumableStreamContext or set the INSTANT_APP_ID environment variable.");const n=e.adminToken||Tt.INSTANT_APP_ADMIN_TOKEN;if(!n)throw new Error("Missing adminToken. Pass it as an argument to createResumableStreamContext or set the INSTANT_APP_ADMIN_TOKEN environment variable.");const i=e.apiURI||Tt.INSTANT_API_URI,s=Di({appId:t,adminToken:n,apiURI:i});async function r(c,l,f){const m=s.streams.createWriteStream({clientId:c,waitUntil:e.waitUntil??void 0});try{const y=await m.streamId();l().pipeTo(m);const w=s.streams.createReadStream({streamId:y});return f?w.pipeThrough(Ze(f)):w}catch{const I=s.streams.createReadStream({clientId:c});return f?I.pipeThrough(Ze(f)):I}}async function o(c,l){const f=s.streams.createReadStream({clientId:c});return l?f.pipeThrough(Ze(l)):f}async function a(c,l,f){const m=l(),y=s.streams.createWriteStream({clientId:c,waitUntil:e.waitUntil??void 0});await y.streamId(),m.pipeTo(y);const I=s.streams.createReadStream({clientId:c});return f?I.pipeThrough(Ze(f)):I}async function u(c){var m;const l=await s.query({$streams:{$:{where:{clientId:c}}}}),f=(m=l==null?void 0:l.$streams)==null?void 0:m[0];return f!=null&&f.done?"DONE":f?!0:null}return{resumableStream:r,resumeExistingStream:o,createNewResumableStream:a,hasExistingStream:u}}$.createResumableStreamContext=Vi,Object.defineProperty($,Symbol.toStringTag,{value:"Module"})});
|
|
5
|
+
`&&i++}}return[t,n]}class un extends Event{constructor(t,n){var i,s;super(t),this.code=(i=n==null?void 0:n.code)!=null?i:void 0,this.message=(s=n==null?void 0:n.message)!=null?s:void 0}[Symbol.for("nodejs.util.inspect.custom")](t,n,i){return i(fn(this),n)}[Symbol.for("Deno.customInspect")](t,n){return t(fn(this),n)}}function yi(e){const t=globalThis.DOMException;return typeof t=="function"?new t(e,"SyntaxError"):new SyntaxError(e)}function gt(e){return e instanceof Error?"errors"in e&&Array.isArray(e.errors)?e.errors.map(gt).join(", "):"cause"in e&&e.cause instanceof Error?`${e}: ${gt(e.cause)}`:e.message:`${e}`}function fn(e){return{type:e.type,message:e.message,code:e.code,defaultPrevented:e.defaultPrevented,cancelable:e.cancelable,timeStamp:e.timeStamp}}var ln=e=>{throw TypeError(e)},wt=(e,t,n)=>t.has(e)||ln("Cannot "+n),S=(e,t,n)=>(wt(e,t,"read from private field"),n?n.call(e):t.get(e)),j=(e,t,n)=>t.has(e)?ln("Cannot add the same private member more than once"):t instanceof WeakSet?t.add(e):t.set(e,n),T=(e,t,n,i)=>(wt(e,t,"write to private field"),t.set(e,n),n),ae=(e,t,n)=>(wt(e,t,"access private method"),n),J,ve,Re,Ke,Xe,Fe,Ae,ze,me,Pe,je,Me,Ve,Z,St,It,vt,dn,Ot,$t,Je,kt,Et;class se extends EventTarget{constructor(t,n){var i,s;super(),j(this,Z),this.CONNECTING=0,this.OPEN=1,this.CLOSED=2,j(this,J),j(this,ve),j(this,Re),j(this,Ke),j(this,Xe),j(this,Fe),j(this,Ae),j(this,ze,null),j(this,me),j(this,Pe),j(this,je,null),j(this,Me,null),j(this,Ve,null),j(this,It,async r=>{var o;S(this,Pe).reset();const{body:a,redirected:u,status:c,headers:d}=r;if(c===204){ae(this,Z,Je).call(this,"Server sent HTTP 204, not reconnecting",204),this.close();return}if(u?T(this,Re,new URL(r.url)):T(this,Re,void 0),c!==200){ae(this,Z,Je).call(this,`Non-200 status code (${c})`,c);return}if(!(d.get("content-type")||"").startsWith("text/event-stream")){ae(this,Z,Je).call(this,'Invalid content type, expected "text/event-stream"',c);return}if(S(this,J)===this.CLOSED)return;T(this,J,this.OPEN);const f=new Event("open");if((o=S(this,Ve))==null||o.call(this,f),this.dispatchEvent(f),typeof a!="object"||!a||!("getReader"in a)){ae(this,Z,Je).call(this,"Invalid response body, expected a web ReadableStream",c),this.close();return}const m=new TextDecoder,y=a.getReader();let I=!0;do{const{done:w,value:h}=await y.read();h&&S(this,Pe).feed(m.decode(h,{stream:!w})),w&&(I=!1,S(this,Pe).reset(),ae(this,Z,kt).call(this))}while(I)}),j(this,vt,r=>{T(this,me,void 0),!(r.name==="AbortError"||r.type==="aborted")&&ae(this,Z,kt).call(this,gt(r))}),j(this,Ot,r=>{typeof r.id=="string"&&T(this,ze,r.id);const o=new MessageEvent(r.event||"message",{data:r.data,origin:S(this,Re)?S(this,Re).origin:S(this,ve).origin,lastEventId:r.id||""});S(this,Me)&&(!r.event||r.event==="message")&&S(this,Me).call(this,o),this.dispatchEvent(o)}),j(this,$t,r=>{T(this,Fe,r)}),j(this,Et,()=>{T(this,Ae,void 0),S(this,J)===this.CONNECTING&&ae(this,Z,St).call(this)});try{if(t instanceof URL)T(this,ve,t);else if(typeof t=="string")T(this,ve,new URL(t,bi()));else throw new Error("Invalid URL")}catch{throw yi("An invalid or illegal string was specified")}T(this,Pe,pi({onEvent:S(this,Ot),onRetry:S(this,$t)})),T(this,J,this.CONNECTING),T(this,Fe,3e3),T(this,Xe,(i=n==null?void 0:n.fetch)!=null?i:globalThis.fetch),T(this,Ke,(s=n==null?void 0:n.withCredentials)!=null?s:!1),ae(this,Z,St).call(this)}get readyState(){return S(this,J)}get url(){return S(this,ve).href}get withCredentials(){return S(this,Ke)}get onerror(){return S(this,je)}set onerror(t){T(this,je,t)}get onmessage(){return S(this,Me)}set onmessage(t){T(this,Me,t)}get onopen(){return S(this,Ve)}set onopen(t){T(this,Ve,t)}addEventListener(t,n,i){const s=n;super.addEventListener(t,s,i)}removeEventListener(t,n,i){const s=n;super.removeEventListener(t,s,i)}close(){S(this,Ae)&&clearTimeout(S(this,Ae)),S(this,J)!==this.CLOSED&&(S(this,me)&&S(this,me).abort(),T(this,J,this.CLOSED),T(this,me,void 0))}}J=new WeakMap,ve=new WeakMap,Re=new WeakMap,Ke=new WeakMap,Xe=new WeakMap,Fe=new WeakMap,Ae=new WeakMap,ze=new WeakMap,me=new WeakMap,Pe=new WeakMap,je=new WeakMap,Me=new WeakMap,Ve=new WeakMap,Z=new WeakSet,St=function(){T(this,J,this.CONNECTING),T(this,me,new AbortController),S(this,Xe)(S(this,ve),ae(this,Z,dn).call(this)).then(S(this,It)).catch(S(this,vt))},It=new WeakMap,vt=new WeakMap,dn=function(){var e;const t={mode:"cors",redirect:"follow",headers:{Accept:"text/event-stream",...S(this,ze)?{"Last-Event-ID":S(this,ze)}:void 0},cache:"no-store",signal:(e=S(this,me))==null?void 0:e.signal};return"window"in globalThis&&(t.credentials=this.withCredentials?"include":"same-origin"),t},Ot=new WeakMap,$t=new WeakMap,Je=function(e,t){var n;S(this,J)!==this.CLOSED&&T(this,J,this.CLOSED);const i=new un("error",{code:t,message:e});(n=S(this,je))==null||n.call(this,i),this.dispatchEvent(i)},kt=function(e,t){var n;if(S(this,J)===this.CLOSED)return;T(this,J,this.CONNECTING);const i=new un("error",{code:t,message:e});(n=S(this,je))==null||n.call(this,i),this.dispatchEvent(i),T(this,Ae,setTimeout(S(this,Et),S(this,Fe)))},Et=new WeakMap,se.CONNECTING=0,se.OPEN=1,se.CLOSED=2;function bi(){const e="document"in globalThis?globalThis.document:void 0;return e&&typeof e=="object"&&"baseURI"in e&&typeof e.baseURI=="string"?e.baseURI:void 0}function gi(e,t,n,i){let s=null,r=!1;const o=[],a=f=>{o.push(f),o.length>100&&o.shift(),s&&(s(),s=null)};e(a);const u=()=>(n(a),Promise.resolve({done:!0,value:void 0}));return t(()=>{r=!0,s&&s(),u()}),{next:async()=>{for(;;){if(i()==="closed"||r)return u();const f=o.shift();if(f)return{value:f,done:!1};await new Promise(y=>{s=y})}},return:u,throw(f){return n(a),Promise.reject(f)},[Symbol.asyncIterator](){return this}}}function ye(e){switch(e.readyState){case e.CLOSED:return"closed";case e.CONNECTING:return"connecting";case e.OPEN:return"open";default:return"connecting"}}function wi(e){let t=null;return{...e,text(){return t||(t=e.text()),t},json(){return t||(t=e.text()),t.then(n=>JSON.parse(n))}}}function hn(e){if(!e)return;const t={};for(const[n,i]of Object.entries(e))t[n]={startCursor:i["start-cursor"],endCursor:i["end-cursor"],hasNextPage:i["has-next-page?"],hasPreviousPage:i["has-previous-page?"]};return t}function Si(e,t,n){let i,s=!1;const r=Ce(),o=new se(`${n.apiURI}/admin/subscribe-query?local_connection_id=${r}`,{fetch(h,O){return i=null,fetch(h,{...O,method:"POST",headers:n.headers,body:JSON.stringify({query:e,"inference?":n.inference,versions:{"@instantdb/admin":xe,"@instantdb/core":xe}})}).then(b=>(b.ok||(i=wi(b)),b))}}),a=[],u=[],c=h=>{a.push(h)},d=h=>{a.splice(a.indexOf(h),1)},f=h=>{u.push(h)};t&&c(t);let m=null;function y(h){if(!s)for(const O of a)try{O(h)}catch(b){console.error("Error in subscribeQuery callback",b)}}function I(h){var O,b;switch(h.op){case"sse-init":{const k=h["machine-id"],ee=h["session-id"];m={machineId:k,sessionId:ee};break}case"add-query-ok":{y({type:"ok",data:h.result,pageInfo:hn((O=h["result-meta"])==null?void 0:O["page-info"]),sessionInfo:m});break}case"refresh-ok":{h.computations.length&&y({type:"ok",data:h.computations[0]["instaql-result"],pageInfo:hn((b=h.computations[0]["result-meta"])==null?void 0:b["page-info"]),sessionInfo:m});break}case"error":{y({type:"error",error:new Ie({body:h,status:h.status}),get readyState(){return ye(o)},get isClosed(){return ye(o)==="closed"},sessionInfo:m});break}}}return o.onerror=h=>{if(i)i.text().then(O=>{let b={type:void 0,message:O};try{b=JSON.parse(O)}catch{}y({type:"error",error:new Ie({status:i.status,body:b}),get readyState(){return ye(o)},get isClosed(){return ye(o)==="closed"},sessionInfo:m})});else{const O=()=>{y({type:"error",error:new Ie({status:h.code||500,body:{type:void 0,message:h.message||"Unknown error in subscribe query."}}),get readyState(){return ye(o)},get isClosed(){return ye(o)==="closed"},sessionInfo:m})};if(o.readyState===se.CLOSED){O();return}setTimeout(()=>{o.readyState!==se.OPEN&&O()},5e3)}},o.onmessage=h=>{I(JSON.parse(h.data))},{close:()=>{s=!0;for(const h of u)try{h()}catch(O){console.error("Error in onClose callback",O)}o.close()},[Symbol.iterator]:()=>{throw new Error("subscribeQuery does not support synchronous iteration. Use `for await` instead.")},get sessionInfo(){return m},get readyState(){return ye(o)},get isClosed(){return ye(o)==="closed"},[Symbol.asyncIterator]:gi.bind(this,c,f,d,()=>1)}}var ce={};Object.defineProperty(ce,"__esModule",{value:!0});var Ii=ce.parseCookie=yn;ce.parse=yn,ce.stringifyCookie=_i,ce.stringifySetCookie=Ye,ce.serialize=Ye,ce.parseSetCookie=Ci,ce.stringifySetCookie=Ye,ce.serialize=Ye;const pn=/^[\u0021-\u003A\u003C\u003E-\u007E]+$/,mn=/^[\u0021-\u003A\u003C-\u007E]*$/,vi=/^([.]?[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?)([.][a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?)*$/i,Oi=/^[\u0020-\u003A\u003D-\u007E]*$/,$i=/^-?\d+$/,ki=Object.prototype.toString,Ei=(()=>{const e=function(){};return e.prototype=Object.create(null),e})();function yn(e,t){const n=new Ei,i=e.length;if(i<2)return n;const s=(t==null?void 0:t.decode)||bn;let r=0;do{const o=Ct(e,r,i);if(o===-1)break;const a=_t(e,r,i);if(o>a){r=e.lastIndexOf(";",o-1)+1;continue}const u=be(e,r,o);n[u]===void 0&&(n[u]=s(be(e,o+1,a))),r=a+1}while(r<i);return n}function _i(e,t){const n=(t==null?void 0:t.encode)||encodeURIComponent,i=[];for(const s of Object.keys(e)){const r=e[s];if(r===void 0)continue;if(!pn.test(s))throw new TypeError(`cookie name is invalid: ${s}`);const o=n(r);if(!mn.test(o))throw new TypeError(`cookie val is invalid: ${r}`);i.push(`${s}=${o}`)}return i.join("; ")}function Ye(e,t,n){const i=typeof e=="object"?e:{...n,name:e,value:String(t)},s=typeof t=="object"?t:n,r=(s==null?void 0:s.encode)||encodeURIComponent;if(!pn.test(i.name))throw new TypeError(`argument name is invalid: ${i.name}`);const o=i.value?r(i.value):"";if(!mn.test(o))throw new TypeError(`argument val is invalid: ${i.value}`);let a=i.name+"="+o;if(i.maxAge!==void 0){if(!Number.isInteger(i.maxAge))throw new TypeError(`option maxAge is invalid: ${i.maxAge}`);a+="; Max-Age="+i.maxAge}if(i.domain){if(!vi.test(i.domain))throw new TypeError(`option domain is invalid: ${i.domain}`);a+="; Domain="+i.domain}if(i.path){if(!Oi.test(i.path))throw new TypeError(`option path is invalid: ${i.path}`);a+="; Path="+i.path}if(i.expires){if(!xi(i.expires)||!Number.isFinite(i.expires.valueOf()))throw new TypeError(`option expires is invalid: ${i.expires}`);a+="; Expires="+i.expires.toUTCString()}if(i.httpOnly&&(a+="; HttpOnly"),i.secure&&(a+="; Secure"),i.partitioned&&(a+="; Partitioned"),i.priority)switch(typeof i.priority=="string"?i.priority.toLowerCase():void 0){case"low":a+="; Priority=Low";break;case"medium":a+="; Priority=Medium";break;case"high":a+="; Priority=High";break;default:throw new TypeError(`option priority is invalid: ${i.priority}`)}if(i.sameSite)switch(typeof i.sameSite=="string"?i.sameSite.toLowerCase():i.sameSite){case!0:case"strict":a+="; SameSite=Strict";break;case"lax":a+="; SameSite=Lax";break;case"none":a+="; SameSite=None";break;default:throw new TypeError(`option sameSite is invalid: ${i.sameSite}`)}return a}function Ci(e,t){const n=(t==null?void 0:t.decode)||bn,i=e.length,s=_t(e,0,i),r=Ct(e,0,s),o=r===-1?{name:"",value:n(be(e,0,s))}:{name:be(e,0,r),value:n(be(e,r+1,s))};let a=s+1;for(;a<i;){const u=_t(e,a,i),c=Ct(e,a,u),d=c===-1?be(e,a,u):be(e,a,c),f=c===-1?void 0:be(e,c+1,u);switch(d.toLowerCase()){case"httponly":o.httpOnly=!0;break;case"secure":o.secure=!0;break;case"partitioned":o.partitioned=!0;break;case"domain":o.domain=f;break;case"path":o.path=f;break;case"max-age":f&&$i.test(f)&&(o.maxAge=Number(f));break;case"expires":if(!f)break;const m=new Date(f);Number.isFinite(m.valueOf())&&(o.expires=m);break;case"priority":if(!f)break;const y=f.toLowerCase();(y==="low"||y==="medium"||y==="high")&&(o.priority=y);break;case"samesite":if(!f)break;const I=f.toLowerCase();(I==="lax"||I==="strict"||I==="none")&&(o.sameSite=I);break}a=u+1}return o}function _t(e,t,n){const i=e.indexOf(";",t);return i===-1?n:i}function Ct(e,t,n){const i=e.indexOf("=",t);return i<n?i:-1}function be(e,t,n){let i=t,s=n;do{const r=e.charCodeAt(i);if(r!==32&&r!==9)break}while(++i<s);for(;s>i;){const r=e.charCodeAt(s-1);if(r!==32&&r!==9)break;s--}return e.slice(i,s)}function bn(e){if(e.indexOf("%")===-1)return e;try{return decodeURIComponent(e)}catch{return e}}function xi(e){return ki.call(e)==="[object Date]"}function Ti(e){return{...{apiURI:"https://api.instantdb.com"},...e}}function Ri(e,t){return"email"in t?e["as-email"]=t.email:"token"in t?e["as-token"]=t.token:"guest"in t&&(e["as-guest"]="true"),e}function Ai(e,t){if(!(t&&("token"in t||"guest"in t))&&!e.adminToken)throw t&&"email"in t?new Error("Admin token required. To impersonate users with an email you must pass `adminToken` to `init`."):new Error("Admin token required. To run this operation pass `adminToken` to `init`, or use `db.asUser`.")}function A(e,t){Ai(e,t);const{adminToken:n,appId:i}=e,s={"content-type":"application/json","app-id":i};return n&&(s.authorization=`Bearer ${n}`),t?Ri(s,t):s}function Pi(){return fetch.__nextPatched&&!globalThis[Symbol.for("next-patch")]}function ji(){return Pi()?{cache:"no-store"}:{}}async function Mi(e,t){const n=await t.text();try{const i=JSON.parse(n);return e(new Ie({status:t.status,body:i}))}catch{return e(new Ie({status:t.status,body:{type:void 0,message:n}}))}}async function M(e,t){const n=ji(),i={...(t==null?void 0:t.headers)||{},"Instant-Admin-Version":xe,"Instant-Core-Version":xe},s=await fetch(e,{...n,...t,headers:i});if(s.status===200){const r=await s.json();return Promise.resolve(r)}return Mi(r=>Promise.reject(r),s)}function Ui(e){var t,n,vn;return t=class{constructor(r){K(this,n);l(this,"source");l(this,"url");this.url=r,this.source=X(this,n,vn).call(this,r)}get onopen(){return this.source.onopen}set onopen(r){this.source.onopen=r}get onmessage(){return this.source.onmessage}set onmessage(r){this.source.onmessage=r}get onerror(){return this.source.onerror}set onerror(r){this.source.onerror=r}get readyState(){return this.source.readyState}close(){this.source.close()}},n=new WeakSet,vn=function(r){return new se(r,{fetch(a,u){return fetch(a,{...u,method:"POST",headers:e.headers,body:JSON.stringify({"inference?":e.inference,versions:{"@instantdb/admin":xe,"@instantdb/core":xe}})})}})},l(t,"OPEN",se.OPEN),l(t,"CONNECTING",se.CONNECTING),l(t,"CLOSED",se.CLOSED),t}function Di(e){var n,i;(!e.appId||!x(e.appId))&&console.warn("warning: Instant Admin DB must be initialized with a valid appId. Received: "+JSON.stringify(e.appId));const t={...e,appId:(n=e.appId)==null?void 0:n.trim(),adminToken:(i=e.adminToken)==null?void 0:i.trim(),useDateObjects:e.useDateObjects??!1};return new xt(t)}function gn(e){return(Array.isArray(e)?e:[e]).flatMap(qn)}class Ni{constructor(t){l(this,"config");this.config=t}async getPresence(t,n){return(await M(`${this.config.apiURI}/admin/rooms/presence?app_id=${this.config.appId}&room-type=${String(t)}&room-id=${n}`,{method:"GET",headers:A(this.config)})).sessions||{}}}class Li{constructor(t){l(this,"config");l(this,"generateMagicCode",async t=>M(`${this.config.apiURI}/admin/magic_code?app_id=${this.config.appId}`,{method:"POST",headers:A(this.config),body:JSON.stringify({email:t})}));l(this,"sendMagicCode",async t=>M(`${this.config.apiURI}/admin/send_magic_code?app_id=${this.config.appId}`,{method:"POST",headers:A(this.config),body:JSON.stringify({email:t})}));l(this,"verifyMagicCode",async(t,n)=>{const{user:i}=await M(`${this.config.apiURI}/admin/verify_magic_code?app_id=${this.config.appId}`,{method:"POST",headers:A(this.config),body:JSON.stringify({email:t,code:n})});return i});l(this,"verifyToken",async t=>(await M(`${this.config.apiURI}/runtime/auth/verify_refresh_token?app_id=${this.config.appId}`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({"app-id":this.config.appId,"refresh-token":t})})).user);l(this,"getUser",async t=>{const n=Object.entries(t).map(([s,r])=>`${s}=${encodeURIComponent(r)}`).join("&");return(await M(`${this.config.apiURI}/admin/users?app_id=${this.config.appId}&${n}`,{method:"GET",headers:A(this.config)})).user});l(this,"deleteUser",async t=>{const n=Object.entries(t).map(([s,r])=>`${s}=${r}`);return(await M(`${this.config.apiURI}/admin/users?app_id=${this.config.appId}&${n}`,{method:"DELETE",headers:A(this.config)})).deleted});l(this,"getUserFromRequest",async(t,n)=>{const i=t.headers.get("cookie")||"",s=Ii(i),r="instant_user_"+this.config.appId;if(!s[r])return null;const o=s[r],a=JSON.parse(o);return a!=null&&a.refresh_token?n!=null&&n.disableValidation?a:await this.verifyToken(a.refresh_token):null});this.config=t,this.createToken=this.createToken.bind(this)}async createToken(t){const n=typeof t=="string"?{email:t}:t;return(await M(`${this.config.apiURI}/admin/refresh_tokens?app_id=${this.config.appId}`,{method:"POST",headers:A(this.config),body:JSON.stringify(n)})).user.refresh_token}async signOut(t){const n=typeof t=="string"?{email:t}:t,i=this.config;await M(`${i.apiURI}/admin/sign_out?app_id=${this.config.appId}`,{method:"POST",headers:A(i),body:JSON.stringify(n)})}}const wn=e=>e&&typeof e=="object"&&typeof e.pipe=="function"&&typeof e.read=="function",Wi=e=>e&&typeof e.getReader=="function";class Sn{constructor(t,n){l(this,"config");l(this,"impersonationOpts");l(this,"uploadFile",async(t,n,i={})=>{const s={...A(this.config,this.impersonationOpts),path:t};i.contentDisposition&&(s["content-disposition"]=i.contentDisposition),delete s["content-type"],i.contentType&&(s["content-type"]=i.contentType);let r;if(wn(n)&&(r="half"),wn(n)||Wi(n)){if(!i.fileSize)throw new Error("fileSize is required in metadata when uploading streams");s["content-length"]=i.fileSize.toString()}let o={method:"PUT",headers:s,body:n,...r&&{duplex:r}};return M(`${this.config.apiURI}/admin/storage/upload?app_id=${this.config.appId}`,o)});l(this,"delete",async t=>M(`${this.config.apiURI}/admin/storage/files?app_id=${this.config.appId}&filename=${encodeURIComponent(t)}`,{method:"DELETE",headers:A(this.config,this.impersonationOpts)}));l(this,"deleteMany",async t=>M(`${this.config.apiURI}/admin/storage/files/delete?app_id=${this.config.appId}`,{method:"POST",headers:A(this.config,this.impersonationOpts),body:JSON.stringify({filenames:t})}));l(this,"upload",async(t,n,i={})=>{const{data:s}=await M(`${this.config.apiURI}/admin/storage/signed-upload-url?app_id=${this.config.appId}`,{method:"POST",headers:A(this.config),body:JSON.stringify({app_id:this.config.appId,filename:t})}),r={},o=i.contentType;o&&(r["Content-Type"]=o);const{ok:a}=await fetch(s,{method:"PUT",body:n,headers:r});return a});l(this,"list",async()=>{const{data:t}=await M(`${this.config.apiURI}/admin/storage/files?app_id=${this.config.appId}`,{method:"GET",headers:A(this.config)});return t});l(this,"getDownloadUrl",async t=>{const{data:n}=await M(`${this.config.apiURI}/admin/storage/signed-download-url?app_id=${this.config.appId}&filename=${encodeURIComponent(t)}`,{method:"GET",headers:A(this.config)});return n});this.config=t,this.impersonationOpts=n}}class Fi{constructor(t){K(this,Ue);l(this,"createReadStream",t=>g(this,Ue).call(this).createReadStream(t));l(this,"createWriteStream",t=>g(this,Ue).call(this).createWriteStream(t));he(this,Ue,t)}}Ue=new WeakMap;function zi(e){return{info:e?(...t)=>console.info(...t):()=>{},debug:e?(...t)=>console.debug(...t):()=>{},error:e?(...t)=>console.error(...t):()=>{}}}const Rt=class Rt{constructor(t){K(this,U);l(this,"config");l(this,"auth");l(this,"storage");l(this,"streams");l(this,"rooms");l(this,"impersonationOpts");K(this,N,null);K(this,Oe,0);K(this,W,null);K(this,F);l(this,"tx",Kt());l(this,"asUser",t=>{const n=new Rt({...this.config});return n.impersonationOpts=t,n.storage=new Sn(this.config,t),n});l(this,"query",(t,n={})=>{t&&n&&"ruleParams"in n&&(t={$$ruleParams:n.ruleParams,...t}),this.config.disableValidation||tn(t,this.config.schema);const i=n.fetchOpts||{},s=i.headers||{};return M(`${this.config.apiURI}/admin/query?app_id=${this.config.appId}`,{...i,method:"POST",headers:{...s,...A(this.config,this.impersonationOpts)},body:JSON.stringify({query:t,"inference?":!!this.config.schema})})});l(this,"transact",t=>(this.config.disableValidation||si(t,this.config.schema),M(`${this.config.apiURI}/admin/transact?app_id=${this.config.appId}`,{method:"POST",headers:A(this.config,this.impersonationOpts),body:JSON.stringify({steps:gn(t),"throw-on-missing-attrs?":!!this.config.schema})})));l(this,"debugQuery",async(t,n)=>{t&&n&&"ruleParams"in n&&(t={$$ruleParams:n.ruleParams,...t});const i={query:t,"rules-override":n==null?void 0:n.rules};n!=null&&n.ip&&(i["ip-override"]=n.ip),n!=null&&n.origin&&(i["origin-override"]=n.origin);const s=await M(`${this.config.apiURI}/admin/query_perms_check?app_id=${this.config.appId}`,{method:"POST",headers:A(this.config,this.impersonationOpts),body:JSON.stringify(i)});return{result:s.result,checkResults:s["check-results"]}});l(this,"debugTransact",(t,n)=>{const i={steps:gn(t),"rules-override":n==null?void 0:n.rules,"dangerously-commit-tx":n==null?void 0:n.__dangerouslyCommit};return n!=null&&n.ip&&(i["ip-override"]=n.ip),n!=null&&n.origin&&(i["origin-override"]=n.origin),M(`${this.config.apiURI}/admin/transact_perms_check?app_id=${this.config.appId}`,{method:"POST",headers:A(this.config,this.impersonationOpts),body:JSON.stringify(i)})});K(this,et,t=>{var n;if(t.target!==g(this,N)){g(this,F).info("[socket][open]",t.target.id,"skip; this is no longer the current transport");return}g(this,F).info("[socket][open]",t.target.id),he(this,Oe,0),(n=g(this,W))==null||n.onConnectionStatusChange("authenticated")});K(this,tt,t=>{var n;if(t.target!==g(this,N)){g(this,F).info("[socket][close]",t.target.id,"skip; this is no longer the current transport");return}g(this,F).info("[socket][close]",t.target.id),(n=g(this,W))==null||n.onConnectionStatusChange("closed"),g(this,N)&&(he(this,N,null),X(this,U,Ut).call(this)||(setTimeout(()=>X(this,U,st).call(this),g(this,Oe)),he(this,Oe,Math.min(15e3,Math.max(g(this,Oe),500)*2))))});K(this,nt,t=>{var n;if(t.target!==g(this,N)){g(this,F).info("[socket][error]",t.target.id,"skip; this is no longer the current transport");return}g(this,F).info("[socket][error]",t.target.id),(n=g(this,W))==null||n.onConnectionStatusChange("closed")});K(this,it,t=>{var i,s,r,o,a,u;if(t.target!==g(this,N)){g(this,F).info("[socket][message]",t.target.id,"skip; this is no longer the current transport");return}const n=t.message;switch(g(this,F).info("[receive]",n),n.op){case"start-stream-ok":{(i=g(this,W))==null||i.onStartStreamOk(n);break}case"stream-flushed":{(s=g(this,W))==null||s.onStreamFlushed(n);break}case"append-failed":{(r=g(this,W))==null||r.onAppendFailed(n);break}case"stream-append":{(o=g(this,W))==null||o.onStreamAppend(n);break}case"error":{switch((a=n["original-event"])==null?void 0:a.op){case"start-stream":case"append-stream":case"subscribe-stream":case"unsubscribe-stream":{(u=g(this,W))==null||u.onRecieveError(n);break}}break}}X(this,U,_n).call(this)});this.config=Ti(t),this.auth=new Li(this.config),this.storage=new Sn(this.config,this.impersonationOpts),this.streams=new Fi(X(this,U,En).bind(this)),this.rooms=new Ni(this.config),he(this,F,zi(!!this.config.verbose))}subscribeQuery(t,n,i={}){t&&i&&"ruleParams"in i&&(t={$$ruleParams:i.ruleParams,...t}),this.config.disableValidation||tn(t,this.config.schema);const o={...(i.fetchOpts||{}).headers||{},...A(this.config,this.impersonationOpts)},a=!!this.config.schema;return Si(t,n,{headers:o,inference:a,apiURI:this.config.apiURI})}};N=new WeakMap,Oe=new WeakMap,W=new WeakMap,F=new WeakMap,U=new WeakSet,On=function(){g(this,N)&&g(this,N).close();const t={...A(this.config,this.impersonationOpts)},n=!!this.config.schema,i=Ui({headers:t,inference:n}),s=new oi(i,`${this.config.apiURI}/admin/sse?app_id=${this.config.appId}`,`${this.config.apiURI}/admin/sse/push?app_id=${this.config.appId}`);return s.onopen=g(this,et),s.onmessage=g(this,it),s.onclose=g(this,tt),s.onerror=g(this,nt),he(this,N,s),s},st=function(){return g(this,N)||X(this,U,On).call(this)},$n=function(t,n){const i=X(this,U,st).call(this);g(this,F).info("[send]",t,n,{isOpen:i.isOpen()}),i.isOpen()&&i.send({"client-event-id":t,...n})},kn=function(){X(this,U,st).call(this);const t=new fi({WStream:this.config.WritableStream||WritableStream,RStream:this.config.ReadableStream||ReadableStream,trySend:(n,i)=>{X(this,U,$n).call(this,n,i)},log:g(this,F)});return he(this,W,t),t},En=function(){return g(this,W)||X(this,U,kn).call(this)},et=new WeakMap,tt=new WeakMap,nt=new WeakMap,Ut=function(){return!g(this,W)||!g(this,W).hasActiveStreams()},_n=function(){if(g(this,N)&&X(this,U,Ut).call(this)){const t=g(this,N);g(this,F).info("cleaning up unused socket",t.id),he(this,N,null),t.close()}},it=new WeakMap;let xt=Rt;var Tt={};function Ze(e){let t=e;return new TransformStream({transform(n,i){if(!t){i.enqueue(n);return}if(t>n.length){t-=n.length;return}const s=n.slice(t);t=0,i.enqueue(s)}})}function Vi(e){const t=e.appId||Tt.INSTANT_APP_ID;if(!t)throw new Error("Missing appId. Pass it as an argument to createResumableStreamContext or set the INSTANT_APP_ID environment variable.");const n=e.adminToken||Tt.INSTANT_APP_ADMIN_TOKEN;if(!n)throw new Error("Missing adminToken. Pass it as an argument to createResumableStreamContext or set the INSTANT_APP_ADMIN_TOKEN environment variable.");const i=e.apiURI||Tt.INSTANT_API_URI,s=Di({appId:t,adminToken:n,apiURI:i});async function r(c,d,f){const m=s.streams.createWriteStream({clientId:c,waitUntil:e.waitUntil??void 0});try{const y=await m.streamId();d().pipeTo(m);const w=s.streams.createReadStream({streamId:y});return f?w.pipeThrough(Ze(f)):w}catch{const I=s.streams.createReadStream({clientId:c});return f?I.pipeThrough(Ze(f)):I}}async function o(c,d){const f=s.streams.createReadStream({clientId:c});return d?f.pipeThrough(Ze(d)):f}async function a(c,d,f){const m=d(),y=s.streams.createWriteStream({clientId:c,waitUntil:e.waitUntil??void 0});await y.streamId(),m.pipeTo(y);const I=s.streams.createReadStream({clientId:c});return f?I.pipeThrough(Ze(f)):I}async function u(c){var m;const d=await s.query({$streams:{$:{where:{clientId:c}}}}),f=(m=d==null?void 0:d.$streams)==null?void 0:m[0];return f!=null&&f.done?"DONE":f?!0:null}return{resumableStream:r,resumeExistingStream:o,createNewResumableStream:a,hasExistingStream:u}}$.createResumableStreamContext=Vi,Object.defineProperty($,Symbol.toStringTag,{value:"Module"})});
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@instantdb/resumable-stream",
|
|
3
|
-
"version": "0.22.
|
|
3
|
+
"version": "0.22.156",
|
|
4
4
|
"description": "Instant's drop-in replacement for Vercel's resumable-stream package.",
|
|
5
5
|
"homepage": "https://github.com/instantdb/instant/tree/main/client/packages/resumable-stream",
|
|
6
6
|
"repository": {
|
|
@@ -50,7 +50,7 @@
|
|
|
50
50
|
"vitest": "^1.6.0"
|
|
51
51
|
},
|
|
52
52
|
"dependencies": {
|
|
53
|
-
"@instantdb/admin": "0.22.
|
|
53
|
+
"@instantdb/admin": "0.22.156"
|
|
54
54
|
},
|
|
55
55
|
"scripts": {
|
|
56
56
|
"test": "vitest",
|