@moyodb/sdk 1.0.0 → 1.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -34,23 +34,32 @@ var r = /* @__PURE__ */ "open.close.destroy.deleteDB.begin.commit.rollback.autoc
34
34
  function a(e) {
35
35
  return typeof e == "string" && i.has(e);
36
36
  }
37
- var o = "moyodb:packed-binary-list:v1", s = "moyodb:packed-nullable-binary-list:v1", c = "moyodb:packed-scan-rows:v1", l = "moyodb:packed-batch-ops:v1", u = "moyodb:packed-optional-values:v1", d = 0, ee = 1, f = 4294967295, te = [];
37
+ var o = "moyodb:packed-binary-list:v1", s = "moyodb:packed-nullable-binary-list:v1", c = "moyodb:packed-scan-rows:v1", l = "moyodb:packed-batch-ops:v1", u = "moyodb:packed-optional-values:v1", d = 0, ee = 1, f = 4294967295, p = [];
38
38
  new Set(r);
39
- function ne(t) {
39
+ function te(t) {
40
40
  return e(t) && t.type === "moyodb:worker-protocol:ready" && t.version === 1;
41
41
  }
42
- function re(t) {
42
+ function ne(t) {
43
43
  return e(t) && t.type === "moyodb:worker-protocol:response" && t.version === 1 && typeof t.id == "number" && Number.isSafeInteger(t.id) && typeof t.ok == "boolean";
44
44
  }
45
- function ie(e) {
46
- let t = Error(e.message);
47
- return t.name = e.name || e.code || "Error", e.stack && (t.stack = e.stack), e.code && Object.defineProperty(t, "code", {
48
- value: e.code,
45
+ function re(e) {
46
+ if (!ie(e, "moyodb:worker-protocol:response-batch", "responses")) return !1;
47
+ for (let t of e.responses) if (!ne(t)) return !1;
48
+ return !0;
49
+ }
50
+ function ie(t, n, r) {
51
+ return e(t) && t.type === n && t.version === 1 && Array.isArray(t[r]) && t[r].length > 0 && t[r].length <= 128;
52
+ }
53
+ function ae(t) {
54
+ if (!e(t) || typeof t.name != "string" || typeof t.message != "string" || t.code !== void 0 && typeof t.code != "string" || t.stack !== void 0 && typeof t.stack != "string") throw m("WorkerProtocolError", "invalid serialized worker error");
55
+ let n = Error(t.message);
56
+ return n.name = t.name || t.code || "Error", t.stack && (n.stack = t.stack), t.code && Object.defineProperty(n, "code", {
57
+ value: t.code,
49
58
  enumerable: !0,
50
59
  configurable: !0
51
- }), t;
60
+ }), n;
52
61
  }
53
- function p(e, t, n = e) {
62
+ function m(e, t, n = e) {
54
63
  let r = Error(t);
55
64
  return r.name = e, Object.defineProperty(r, "code", {
56
65
  value: n,
@@ -58,11 +67,11 @@ function p(e, t, n = e) {
58
67
  configurable: !0
59
68
  }), r;
60
69
  }
61
- function ae(e, t) {
70
+ function oe(e, t) {
62
71
  if (e === "autocommit") {
63
72
  let [e, n, r] = t;
64
73
  if (a(n) && Array.isArray(r)) {
65
- let t = ae(n, [0, ...r]);
74
+ let t = oe(n, [0, ...r]);
66
75
  return {
67
76
  args: [
68
77
  e,
@@ -73,10 +82,24 @@ function ae(e, t) {
73
82
  };
74
83
  }
75
84
  }
85
+ if (e === "get" || e === "has" || e === "delete" || e === "getByIndex" || e === "put") {
86
+ let n = e === "getByIndex" ? 3 : 2, r = null, i = null;
87
+ for (let a = n; a <= (e === "put" ? 3 : n); a += 1) {
88
+ let e = t[a];
89
+ if (e instanceof Uint8Array && e.buffer instanceof ArrayBuffer && (e.byteOffset !== 0 || e.byteLength !== e.buffer.byteLength)) {
90
+ let n = _e(e);
91
+ r ??= [...t], r[a] = n, (i ??= []).push(n.buffer);
92
+ }
93
+ }
94
+ if (r !== null) return {
95
+ args: r,
96
+ transfer: i ?? p
97
+ };
98
+ }
76
99
  if (e === "importSnapshot") {
77
100
  let e = t[0];
78
101
  if (e instanceof Uint8Array) {
79
- let t = ge(e);
102
+ let t = _e(e);
80
103
  return {
81
104
  args: [t],
82
105
  transfer: [t.buffer]
@@ -86,7 +109,7 @@ function ae(e, t) {
86
109
  if (e === "getMany" || e === "deleteMany") {
87
110
  let [e, n, r] = t;
88
111
  if (Array.isArray(r) && r.length > 0) {
89
- let t = le(r);
112
+ let t = de(r);
90
113
  return {
91
114
  args: [
92
115
  e,
@@ -100,7 +123,7 @@ function ae(e, t) {
100
123
  if (e === "putMany") {
101
124
  let [e, n, r, i] = t;
102
125
  if (Array.isArray(r) && r.length > 0) {
103
- let t = ce(r);
126
+ let t = ue(r);
104
127
  return {
105
128
  args: [
106
129
  e,
@@ -115,7 +138,7 @@ function ae(e, t) {
115
138
  if (e === "applyBatch") {
116
139
  let [e, n, r] = t;
117
140
  if (Array.isArray(r) && r.length > 0) {
118
- let t = fe(r);
141
+ let t = me(r);
119
142
  return {
120
143
  args: [
121
144
  e,
@@ -128,13 +151,13 @@ function ae(e, t) {
128
151
  }
129
152
  return {
130
153
  args: t,
131
- transfer: te
154
+ transfer: p
132
155
  };
133
156
  }
134
- function oe(e) {
135
- if (!(e instanceof Uint8Array) || e.byteLength < 4) throw p("WorkerProtocolError", "invalid packed optional-values payload");
136
- let t = new DataView(e.buffer, e.byteOffset, e.byteLength), n = t.getUint32(0, !0), r = h(4, m(n, 4, "packed optional-values metadata"), "packed optional-values header");
137
- if (r > e.byteLength) throw p("WorkerProtocolError", "packed optional-values metadata exceeds payload length");
157
+ function se(e) {
158
+ if (!(e instanceof Uint8Array) || e.byteLength < 4) throw m("WorkerProtocolError", "invalid packed optional-values payload");
159
+ let t = new DataView(e.buffer, e.byteOffset, e.byteLength), n = t.getUint32(0, !0), r = _(4, g(n, 4, "packed optional-values metadata"), "packed optional-values header");
160
+ if (r > e.byteLength) throw m("WorkerProtocolError", "packed optional-values metadata exceeds payload length");
138
161
  let i = Array(n), a = r;
139
162
  for (let r = 0; r < n; r += 1) {
140
163
  let n = t.getUint32(4 + r * 4, !0);
@@ -143,27 +166,65 @@ function oe(e) {
143
166
  continue;
144
167
  }
145
168
  let o = a + n;
146
- if (o > e.byteLength) throw p("WorkerProtocolError", "packed optional-values item exceeds payload length");
169
+ if (o > e.byteLength) throw m("WorkerProtocolError", "packed optional-values item exceeds payload length");
147
170
  i[r] = e.subarray(a, o), a = o;
148
171
  }
149
- if (a !== e.byteLength) throw p("WorkerProtocolError", "packed optional-values payload has trailing bytes");
172
+ if (a !== e.byteLength) throw m("WorkerProtocolError", "packed optional-values payload has trailing bytes");
150
173
  return i;
151
174
  }
152
- function se(t, n) {
153
- return t === "getMany" && pe(n) ? ue(n) : t === "getMany" && he(n) ? oe(n.bytes) : t === "scanByIndexPage" && e(n) ? {
154
- rows: me(n.rows) ? de(n.rows) : n.rows,
155
- cursor: n.cursor instanceof Uint8Array ? n.cursor : null
156
- } : (t === "scan" || t === "scanByIndex") && me(n) ? de(n) : n;
175
+ function ce(t, n) {
176
+ if (t === "getMany" && he(n)) return fe(n);
177
+ if (t === "getMany" && ge(n)) return se(n.bytes);
178
+ if (t === "getMany" && !Array.isArray(n)) throw m("WorkerProtocolError", "invalid packed getMany response");
179
+ if (t === "scanByIndexPage") {
180
+ if (!e(n) || !Array.isArray(n.rows) && !h(n.rows) || n.cursor !== null && !(n.cursor instanceof Uint8Array)) throw m("WorkerProtocolError", "invalid packed index scan page response");
181
+ return {
182
+ rows: h(n.rows) ? pe(n.rows) : n.rows,
183
+ cursor: n.cursor
184
+ };
185
+ }
186
+ if ((t === "scan" || t === "scanByIndex") && h(n)) return pe(n);
187
+ if ((t === "scan" || t === "scanByIndex") && !Array.isArray(n)) throw m("WorkerProtocolError", "invalid packed scan response");
188
+ return n;
189
+ }
190
+ function le(e, t) {
191
+ let n = t.length > 0 ? structuredClone(e, { transfer: t.length === 1 ? t : Array.from(new Set(t)) }) : structuredClone(e), r = /* @__PURE__ */ new Set(), i = /* @__PURE__ */ new WeakSet(), a = 0, o = (e) => {
192
+ if (typeof e == "string") {
193
+ a += 8 + e.length * 2;
194
+ return;
195
+ }
196
+ if (typeof e != "object" || !e) {
197
+ a += 8;
198
+ return;
199
+ }
200
+ if (!i.has(e)) {
201
+ if (i.add(e), a += 8, e instanceof ArrayBuffer) r.add(e), a += e.byteLength;
202
+ else if (typeof SharedArrayBuffer < "u" && e instanceof SharedArrayBuffer) a += e.byteLength;
203
+ else if (ArrayBuffer.isView(e)) o(e.buffer);
204
+ else if (Array.isArray(e)) for (let t of e) o(t);
205
+ else if (e instanceof Map) for (let [t, n] of e) o(t), o(n);
206
+ else if (e instanceof Set) for (let t of e) o(t);
207
+ else {
208
+ let t = e;
209
+ for (let e in t) Object.prototype.hasOwnProperty.call(t, e) && (a += 8 + e.length * 2, o(t[e]));
210
+ }
211
+ }
212
+ };
213
+ return o(n), {
214
+ value: n,
215
+ transfer: r.size === 0 ? p : Array.from(r),
216
+ byteLength: a
217
+ };
157
218
  }
158
- function ce(e) {
159
- let t = e.length, n = g(t * 2, "packed putMany item count"), r = m(n, 4, "packed putMany metadata"), i = 0;
219
+ function ue(e) {
220
+ let t = e.length, n = v(t * 2, "packed putMany item count"), r = g(n, 4, "packed putMany metadata"), i = 0;
160
221
  for (let n = 0; n < t; n += 1) {
161
222
  let t = e[n], r = t[0], a = t[1];
162
- if (!(r instanceof Uint8Array) || !(a instanceof Uint8Array)) throw p("WorkerProtocolError", "putMany entry key/value is not a Uint8Array");
163
- let o = g(r.byteLength, "putMany key length"), s = g(a.byteLength, "putMany value length");
164
- if (i += o + s, i > f) throw p("WorkerProtocolError", "packed putMany payload exceeds 32-bit payload limit");
223
+ if (!(r instanceof Uint8Array) || !(a instanceof Uint8Array)) throw m("WorkerProtocolError", "putMany entry key/value is not a Uint8Array");
224
+ let o = v(r.byteLength, "putMany key length"), s = v(a.byteLength, "putMany value length");
225
+ if (i += o + s, i > f) throw m("WorkerProtocolError", "packed putMany payload exceeds 32-bit payload limit");
165
226
  }
166
- let a = h(4, r, "packed putMany header"), s = h(a, i, "packed putMany total"), c = new Uint8Array(s), l = new DataView(c.buffer);
227
+ let a = _(4, r, "packed putMany header"), s = _(a, i, "packed putMany total"), c = new Uint8Array(s), l = new DataView(c.buffer);
167
228
  l.setUint32(0, n, !0);
168
229
  let u = 4, d = a;
169
230
  for (let n = 0; n < t; n += 1) {
@@ -175,15 +236,15 @@ function ce(e) {
175
236
  bytes: c
176
237
  };
177
238
  }
178
- function le(e) {
179
- let t = e.length, n = m(t, 4, "packed binary-list metadata"), r = 0;
239
+ function de(e) {
240
+ let t = e.length, n = g(t, 4, "packed binary-list metadata"), r = 0;
180
241
  for (let n = 0; n < t; n += 1) {
181
242
  let t = e[n];
182
- if (!(t instanceof Uint8Array)) throw p("WorkerProtocolError", "binary-list payload item is not a Uint8Array");
183
- let i = g(t.byteLength, "binary-list item length");
184
- if (r += i, r > f) throw p("WorkerProtocolError", "packed binary-list payload exceeds 32-bit payload limit");
243
+ if (!(t instanceof Uint8Array)) throw m("WorkerProtocolError", "binary-list payload item is not a Uint8Array");
244
+ let i = v(t.byteLength, "binary-list item length");
245
+ if (r += i, r > f) throw m("WorkerProtocolError", "packed binary-list payload exceeds 32-bit payload limit");
185
246
  }
186
- let i = h(4, n, "packed binary-list header"), a = h(i, r, "packed binary-list total"), s = new Uint8Array(a), c = new DataView(s.buffer);
247
+ let i = _(4, n, "packed binary-list header"), a = _(i, r, "packed binary-list total"), s = new Uint8Array(a), c = new DataView(s.buffer);
187
248
  c.setUint32(0, t, !0);
188
249
  let l = 4, u = i;
189
250
  for (let n = 0; n < t; n += 1) {
@@ -195,103 +256,104 @@ function le(e) {
195
256
  bytes: s
196
257
  };
197
258
  }
198
- function ue(e) {
259
+ function fe(e) {
199
260
  let t = e.bytes;
200
- if (!(t instanceof Uint8Array) || t.byteLength < 4) throw p("WorkerProtocolError", "invalid packed nullable binary-list payload");
201
- let n = new DataView(t.buffer, t.byteOffset, t.byteLength), r = n.getUint32(0, !0), i = h(4, m(r, 5, "packed nullable binary-list metadata"), "packed nullable binary-list header");
202
- if (i > t.byteLength) throw p("WorkerProtocolError", "packed nullable binary-list metadata exceeds payload length");
261
+ if (!(t instanceof Uint8Array) || t.byteLength < 4) throw m("WorkerProtocolError", "invalid packed nullable binary-list payload");
262
+ let n = new DataView(t.buffer, t.byteOffset, t.byteLength), r = n.getUint32(0, !0), i = _(4, g(r, 5, "packed nullable binary-list metadata"), "packed nullable binary-list header");
263
+ if (i > t.byteLength) throw m("WorkerProtocolError", "packed nullable binary-list metadata exceeds payload length");
203
264
  let a = Array(r), o = 4, s = i;
204
265
  for (let e = 0; e < r; e += 1) {
205
266
  let r = n.getUint8(o), i = n.getUint32(o + 1, !0);
206
267
  if (o += 5, r === 0) {
207
- if (i !== 0) throw p("WorkerProtocolError", "packed nullable binary-list null item has a payload length");
268
+ if (i !== 0) throw m("WorkerProtocolError", "packed nullable binary-list null item has a payload length");
208
269
  a[e] = null;
209
270
  continue;
210
271
  }
211
- if (r !== 1) throw p("WorkerProtocolError", `packed nullable binary-list item has invalid presence byte: ${r}`);
272
+ if (r !== 1) throw m("WorkerProtocolError", `packed nullable binary-list item has invalid presence byte: ${r}`);
212
273
  let c = s + i;
213
- if (c > f || c > t.byteLength) throw p("WorkerProtocolError", "packed nullable binary-list item exceeds payload length");
274
+ if (c > f || c > t.byteLength) throw m("WorkerProtocolError", "packed nullable binary-list item exceeds payload length");
214
275
  a[e] = t.subarray(s, c), s = c;
215
276
  }
216
- if (s !== t.byteLength) throw p("WorkerProtocolError", "packed nullable binary-list payload has trailing bytes");
277
+ if (s !== t.byteLength) throw m("WorkerProtocolError", "packed nullable binary-list payload has trailing bytes");
217
278
  return a;
218
279
  }
219
- function de(e) {
280
+ function pe(e) {
220
281
  let t = e.bytes;
221
- if (!(t instanceof Uint8Array) || t.byteLength < 4) throw p("WorkerProtocolError", "invalid packed scan row payload");
222
- let n = new DataView(t.buffer, t.byteOffset, t.byteLength), r = n.getUint32(0, !0), i = h(4, m(r, 8, "packed scan row metadata"), "packed scan row header");
223
- if (i > t.byteLength) throw p("WorkerProtocolError", "packed scan row metadata exceeds payload length");
282
+ if (!(t instanceof Uint8Array) || t.byteLength < 4) throw m("WorkerProtocolError", "invalid packed scan row payload");
283
+ let n = new DataView(t.buffer, t.byteOffset, t.byteLength), r = n.getUint32(0, !0), i = _(4, g(r, 8, "packed scan row metadata"), "packed scan row header");
284
+ if (i > t.byteLength) throw m("WorkerProtocolError", "packed scan row metadata exceeds payload length");
224
285
  let a = Array(r), o = 4, s = i;
225
286
  for (let e = 0; e < r; e += 1) {
226
287
  let r = n.getUint32(o, !0), i = n.getUint32(o + 4, !0);
227
288
  o += 8;
228
289
  let c = s + r;
229
- if (c > f || c > t.byteLength) throw p("WorkerProtocolError", "packed scan row key exceeds payload length");
290
+ if (c > f || c > t.byteLength) throw m("WorkerProtocolError", "packed scan row key exceeds payload length");
230
291
  let l = c + i;
231
- if (l > f || l > t.byteLength) throw p("WorkerProtocolError", "packed scan row value exceeds payload length");
292
+ if (l > f || l > t.byteLength) throw m("WorkerProtocolError", "packed scan row value exceeds payload length");
232
293
  a[e] = {
233
294
  key: t.subarray(s, c),
234
295
  value: t.subarray(c, l)
235
296
  }, s = l;
236
297
  }
237
- if (s !== t.byteLength) throw p("WorkerProtocolError", "packed scan row payload has trailing bytes");
298
+ if (s !== t.byteLength) throw m("WorkerProtocolError", "packed scan row payload has trailing bytes");
238
299
  return a;
239
300
  }
240
- function fe(e) {
241
- let t = e.length, n = m(t, 9, "packed batch metadata"), r = 0;
242
- for (let n = 0; n < t; n += 1) {
243
- let t = e[n];
244
- if (!(t.key instanceof Uint8Array)) throw p("WorkerProtocolError", "batch operation key is not a Uint8Array");
245
- let i = g(t.key.byteLength, "batch operation key length");
246
- if (r += i, r > f) throw p("WorkerProtocolError", "packed batch payload exceeds 32-bit payload limit");
247
- if (t.kind === "put") {
248
- if (!(t.value instanceof Uint8Array)) throw p("WorkerProtocolError", "batch put value is not a Uint8Array");
249
- let e = g(t.value.byteLength, "batch put value length");
250
- if (r += e, r > f) throw p("WorkerProtocolError", "packed batch payload exceeds 32-bit payload limit");
301
+ function me(t) {
302
+ let n = t.length, r = g(n, 9, "packed batch metadata"), i = 0;
303
+ for (let r = 0; r < n; r += 1) {
304
+ let n = t[r];
305
+ if (!e(n) || n.kind !== "put" && n.kind !== "delete") throw m("WorkerProtocolError", "batch operation kind is not put or delete");
306
+ if (!(n.key instanceof Uint8Array)) throw m("WorkerProtocolError", "batch operation key is not a Uint8Array");
307
+ let a = v(n.key.byteLength, "batch operation key length");
308
+ if (i += a, i > f) throw m("WorkerProtocolError", "packed batch payload exceeds 32-bit payload limit");
309
+ if (n.kind === "put") {
310
+ if (!(n.value instanceof Uint8Array)) throw m("WorkerProtocolError", "batch put value is not a Uint8Array");
311
+ let e = v(n.value.byteLength, "batch put value length");
312
+ if (i += e, i > f) throw m("WorkerProtocolError", "packed batch payload exceeds 32-bit payload limit");
251
313
  }
252
314
  }
253
- let i = h(4, n, "packed batch header"), a = h(i, r, "packed batch total"), o = new Uint8Array(a), s = new DataView(o.buffer);
254
- s.setUint32(0, t, !0);
255
- let c = 4, u = i;
256
- for (let n = 0; n < t; n += 1) {
257
- let t = e[n], r = t.key, i = r.byteLength, a = t.kind === "put" ? t.value.byteLength : 0;
258
- s.setUint8(c, t.kind === "put" ? ee : d), s.setUint32(c + 1, i, !0), s.setUint32(c + 5, a, !0), c += 9, o.set(r, u), u += i, t.kind === "put" && (o.set(t.value, u), u += a);
315
+ let a = _(4, r, "packed batch header"), o = _(a, i, "packed batch total"), s = new Uint8Array(o), c = new DataView(s.buffer);
316
+ c.setUint32(0, n, !0);
317
+ let u = 4, p = a;
318
+ for (let e = 0; e < n; e += 1) {
319
+ let n = t[e], r = n.key, i = r.byteLength, a = n.kind === "put" ? n.value.byteLength : 0;
320
+ c.setUint8(u, n.kind === "put" ? ee : d), c.setUint32(u + 1, i, !0), c.setUint32(u + 5, a, !0), u += 9, s.set(r, p), p += i, n.kind === "put" && (s.set(n.value, p), p += a);
259
321
  }
260
322
  return {
261
323
  __moyodbPacked: l,
262
- bytes: o
324
+ bytes: s
263
325
  };
264
326
  }
265
- function pe(t) {
327
+ function he(t) {
266
328
  return e(t) && t.__moyodbPacked === s && t.bytes instanceof Uint8Array;
267
329
  }
268
- function me(t) {
330
+ function h(t) {
269
331
  return e(t) && t.__moyodbPacked === c && t.bytes instanceof Uint8Array;
270
332
  }
271
- function he(t) {
333
+ function ge(t) {
272
334
  return e(t) && t.__moyodbPacked === u && t.bytes instanceof Uint8Array;
273
335
  }
274
- function m(e, t, n) {
275
- if (!Number.isSafeInteger(e) || e < 0) throw p("WorkerProtocolError", `${n} count is invalid: ${e}`);
276
- return g(e * t, n);
336
+ function g(e, t, n) {
337
+ if (!Number.isSafeInteger(e) || e < 0) throw m("WorkerProtocolError", `${n} count is invalid: ${e}`);
338
+ return v(e * t, n);
277
339
  }
278
- function h(e, t, n) {
279
- return g(e + t, n);
340
+ function _(e, t, n) {
341
+ return v(e + t, n);
280
342
  }
281
- function g(e, t) {
282
- if (!Number.isSafeInteger(e) || e < 0 || e > f) throw p("WorkerProtocolError", `${t} exceeds 32-bit payload limit`);
343
+ function v(e, t) {
344
+ if (!Number.isSafeInteger(e) || e < 0 || e > f) throw m("WorkerProtocolError", `${t} exceeds 32-bit payload limit`);
283
345
  return e;
284
346
  }
285
- function ge(e) {
347
+ function _e(e) {
286
348
  let t = new Uint8Array(e.byteLength);
287
349
  return t.set(e), t;
288
350
  }
289
351
  //#endregion
290
352
  //#region src/worker-client.ts
291
- function _(e) {
353
+ function y(e) {
292
354
  e.timeout && clearTimeout(e.timeout);
293
355
  }
294
- var _e = class {
356
+ var ve = class {
295
357
  worker;
296
358
  nextRequestId = 1;
297
359
  pending = /* @__PURE__ */ new Map();
@@ -303,6 +365,11 @@ var _e = class {
303
365
  requestTimeoutMs;
304
366
  fatalHandler = null;
305
367
  closeReason = null;
368
+ batching = !1;
369
+ queuedRequests = [];
370
+ queuedBytes = 0;
371
+ flushScheduled = !1;
372
+ awaitingReady = 0;
306
373
  constructor(e, t = {}) {
307
374
  this.worker = e, this.requestTimeoutMs = t.requestTimeoutMs ?? 0, this.ready = new Promise((e, t) => {
308
375
  this.readyResolve = e, this.readyReject = t;
@@ -314,7 +381,7 @@ var _e = class {
314
381
  whenReady() {
315
382
  return this.ready;
316
383
  }
317
- dispose(e = p("WorkerTerminatedError", "worker transport was closed")) {
384
+ dispose(e = m("WorkerTerminatedError", "worker transport was closed")) {
318
385
  this.disposeInternal(e, !1);
319
386
  }
320
387
  open(e) {
@@ -499,313 +566,369 @@ var _e = class {
499
566
  return await this.send(e, t, e);
500
567
  }
501
568
  async send(e, t, n) {
502
- this.ensureOpen(), await this.ready, this.ensureOpen();
503
- let r = this.nextRequestId;
569
+ this.ensureOpen(), this.awaitingReady += 1;
570
+ try {
571
+ await this.ready;
572
+ } finally {
573
+ --this.awaitingReady;
574
+ }
575
+ this.ensureOpen();
576
+ let r = this.batching && (this.awaitingReady > 0 || this.queuedRequests.length > 0), i = this.nextRequestId;
504
577
  this.nextRequestId += 1;
505
- let i = ae(e, t), a = {
578
+ let a = oe(e, t), o = {
506
579
  type: "moyodb:worker-protocol:request",
507
580
  version: 1,
508
- id: r,
581
+ id: i,
509
582
  command: e,
510
- args: i.args
583
+ args: a.args
511
584
  };
512
- return await new Promise((t, o) => {
513
- let s = this.requestTimeoutMs > 0 ? setTimeout(() => {
514
- this.pending.delete(r), o(p("WorkerRequestTimeoutError", `worker command ${e} timed out after ${this.requestTimeoutMs}ms`));
585
+ return await new Promise((t, s) => {
586
+ let c = this.requestTimeoutMs > 0 ? setTimeout(() => {
587
+ this.pending.delete(i), s(m("WorkerRequestTimeoutError", `worker command ${e} timed out after ${this.requestTimeoutMs}ms`));
515
588
  }, this.requestTimeoutMs) : null;
516
- this.pending.set(r, {
589
+ this.pending.set(i, {
517
590
  command: n,
518
591
  resolve: (e) => t(e),
519
- reject: o,
520
- timeout: s
592
+ reject: s,
593
+ timeout: c
521
594
  });
522
595
  try {
523
- i.transfer.length > 0 ? this.worker.postMessage(a, i.transfer) : this.worker.postMessage(a);
596
+ r ? this.queueRequest(o, a.transfer) : a.transfer.length > 0 ? this.worker.postMessage(o, a.transfer) : this.worker.postMessage(o);
524
597
  } catch (e) {
525
- this.rejectPending(r, e instanceof Error ? e : Error(String(e)));
598
+ this.rejectPending(i, e instanceof Error ? e : Error(String(e)));
526
599
  }
527
600
  });
528
601
  }
602
+ queueRequest(e, t) {
603
+ let n = le(e, t);
604
+ this.pending.has(e.id) && (this.queuedRequests.length > 0 && this.queuedBytes + n.byteLength > 1048576 && this.flushRequests(), this.queuedRequests.push({
605
+ message: n.value,
606
+ transfer: n.transfer,
607
+ byteLength: n.byteLength
608
+ }), this.queuedBytes += n.byteLength, this.flushScheduled || (this.flushScheduled = !0, queueMicrotask(() => {
609
+ this.flushScheduled = !1, this.flushRequests();
610
+ })), (this.queuedRequests.length >= 128 || this.queuedBytes >= 1048576) && this.flushRequests());
611
+ }
612
+ flushRequests() {
613
+ let e = this.queuedRequests;
614
+ if (this.queuedRequests = [], this.queuedBytes = 0, this.closed) return;
615
+ let t = e.filter((e) => this.pending.has(e.message.id));
616
+ if (t.length === 0) return;
617
+ let n = t.length === 1 ? t[0].message : {
618
+ type: "moyodb:worker-protocol:request-batch",
619
+ version: 1,
620
+ requests: t.map((e) => e.message)
621
+ }, r = [];
622
+ for (let e of t) for (let t of e.transfer) r.push(t);
623
+ try {
624
+ r.length > 0 ? this.worker.postMessage(n, r) : this.worker.postMessage(n);
625
+ } catch (e) {
626
+ let n = e instanceof Error ? e : Error(String(e));
627
+ for (let e of t) this.rejectPending(e.message.id, n);
628
+ }
629
+ }
529
630
  ensureOpen() {
530
- if (this.closed) throw this.closeReason ?? p("WorkerTerminatedError", "worker transport is closed");
631
+ if (this.closed) throw this.closeReason ?? m("WorkerTerminatedError", "worker transport is closed");
531
632
  }
532
- handleMessage = (e) => {
533
- let t = e.data;
534
- if (ne(t)) {
535
- this.readyResolved = !0, this.readyResolve?.(), this.readyResolve = null, this.readyReject = null;
633
+ handleMessage = (t) => {
634
+ let n = t.data;
635
+ if (te(n)) {
636
+ if (this.readyResolved) return;
637
+ this.batching = n.batching === 1, this.readyResolved = !0, this.readyResolve?.(), this.readyResolve = null, this.readyReject = null;
638
+ return;
639
+ }
640
+ if (re(n)) {
641
+ for (let e of n.responses) this.handleResponse(e);
642
+ return;
643
+ }
644
+ if (e(n) && n.type === "moyodb:worker-protocol:response-batch" && n.version === 1) {
645
+ this.disposeInternal(m("WorkerProtocolError", "invalid worker response batch"), !0);
646
+ return;
647
+ }
648
+ this.handleResponse(n);
649
+ };
650
+ handleResponse(t) {
651
+ if (!ne(t)) {
652
+ e(t) && t.type === "moyodb:worker-protocol:response" && t.version === 1 && typeof t.id == "number" && Number.isSafeInteger(t.id) && this.rejectPending(t.id, m("WorkerProtocolError", "invalid worker response"));
536
653
  return;
537
654
  }
538
- if (!re(t)) return;
539
655
  let n = this.pending.get(t.id);
540
656
  if (n) {
541
- if (this.pending.delete(t.id), _(n), t.ok) {
542
- n.resolve(se(n.command, t.result));
543
- return;
657
+ this.pending.delete(t.id), y(n);
658
+ try {
659
+ t.ok ? n.resolve(ce(n.command, t.result)) : n.reject(ae(t.error));
660
+ } catch (e) {
661
+ n.reject(e instanceof Error && e.name === "WorkerProtocolError" ? e : m("WorkerProtocolError", "worker response could not be decoded"));
544
662
  }
545
- n.reject(ie(t.error));
546
663
  }
547
- };
664
+ }
548
665
  handleMessageError = () => {
549
- this.disposeInternal(p("WorkerMessageError", "worker message could not be deserialized"), !0);
666
+ this.disposeInternal(m("WorkerMessageError", "worker message could not be deserialized"), !0);
550
667
  };
551
668
  handleError = (e) => {
552
- let t = e.error instanceof Error ? e.error : p("WorkerError", e.message || "worker runtime failed");
669
+ let t = e.error instanceof Error ? e.error : m("WorkerError", e.message || "worker runtime failed");
553
670
  this.disposeInternal(t, !0);
554
671
  };
555
672
  rejectPending(e, t) {
556
673
  let n = this.pending.get(e);
557
- n && (this.pending.delete(e), _(n), n.reject(t));
674
+ n && (this.pending.delete(e), y(n), n.reject(t));
558
675
  }
559
676
  disposeInternal(e, t) {
560
677
  if (!this.closed) {
561
- this.closed = !0, this.closeReason = e, this.worker.removeEventListener("message", this.handleMessage), this.worker.removeEventListener("messageerror", this.handleMessageError), this.worker.removeEventListener("error", this.handleError), this.readyResolved || this.readyReject?.(e), this.readyResolve = null, this.readyReject = null;
562
- for (let t of this.pending.values()) _(t), t.reject(e);
678
+ this.closed = !0, this.closeReason = e, this.worker.removeEventListener("message", this.handleMessage), this.worker.removeEventListener("messageerror", this.handleMessageError), this.worker.removeEventListener("error", this.handleError), this.readyResolved || this.readyReject?.(e), this.readyResolve = null, this.readyReject = null, this.queuedRequests = [], this.queuedBytes = 0;
679
+ for (let t of this.pending.values()) y(t), t.reject(e);
563
680
  this.pending.clear(), t && this.fatalHandler?.(e);
564
681
  }
565
682
  }
566
- }, v = class extends Error {
683
+ }, b = class extends Error {
567
684
  constructor(e, t) {
568
685
  super(t), this.name = e, Object.setPrototypeOf(this, new.target.prototype);
569
686
  }
570
- }, y = class extends v {
687
+ }, x = class extends b {
571
688
  constructor(e) {
572
689
  super("UnsupportedPlatformError", e);
573
690
  }
574
- }, b = class extends v {
691
+ }, S = class extends b {
575
692
  constructor(e) {
576
693
  super("DatabaseBusyError", e);
577
694
  }
578
- }, ve = class extends v {
695
+ }, ye = class extends b {
579
696
  constructor(e) {
580
697
  super("CorruptionError", e);
581
698
  }
582
- }, ye = class extends v {
699
+ }, be = class extends b {
583
700
  constructor(e) {
584
701
  super("StoreExistsError", e);
585
702
  }
586
- }, be = class extends v {
703
+ }, xe = class extends b {
587
704
  constructor(e) {
588
705
  super("StoreNotFoundError", e);
589
706
  }
590
- }, xe = class extends v {
707
+ }, Se = class extends b {
591
708
  constructor(e) {
592
709
  super("IndexNotFoundError", e);
593
710
  }
594
- }, x = class extends v {
711
+ }, C = class extends b {
595
712
  constructor(e) {
596
713
  super("ConstraintError", e);
597
714
  }
598
- }, Se = class extends x {
715
+ }, Ce = class extends C {
599
716
  constructor(e) {
600
717
  super(e), this.name = "UniqueIndexConstraintError";
601
718
  }
602
- }, Ce = class extends v {
719
+ }, we = class extends b {
603
720
  constructor(e = "write transaction already open") {
604
721
  super("WriteTransactionAlreadyOpenError", e);
605
722
  }
606
- }, we = class extends v {
723
+ }, Te = class extends b {
607
724
  constructor(e = "readonly transaction cannot perform this operation") {
608
725
  super("ReadonlyTransactionError", e);
609
726
  }
610
- }, S = class extends v {
727
+ }, w = class extends b {
611
728
  constructor(e = "transaction is already closed") {
612
729
  super("TransactionClosedError", e);
613
730
  }
614
- }, C = class extends v {
731
+ }, T = class extends b {
615
732
  constructor(e = "database handle is closed") {
616
733
  super("DatabaseClosedError", e);
617
734
  }
618
- }, Te = class extends v {
735
+ }, Ee = class extends b {
619
736
  constructor(e) {
620
737
  super("ValueTooLargeError", e);
621
738
  }
622
- }, Ee = class extends v {
739
+ }, De = class extends b {
623
740
  constructor(e) {
624
741
  super("KeyTooLargeError", e);
625
742
  }
626
- }, De = class extends v {
743
+ }, Oe = class extends b {
627
744
  constructor(e) {
628
745
  super("StoreNameTooLongError", e);
629
746
  }
630
- }, w = class extends v {
747
+ }, E = class extends b {
631
748
  constructor(e) {
632
749
  super("ReservedStoreNameError", e);
633
750
  }
634
- }, Oe = class extends v {
751
+ }, ke = class extends b {
635
752
  constructor(e) {
636
753
  super("InvalidRangeError", e);
637
754
  }
638
- }, ke = class extends v {
755
+ }, Ae = class extends b {
639
756
  constructor(e) {
640
757
  super("StorageError", e);
641
758
  }
642
- }, T = class extends v {
759
+ }, D = class extends b {
643
760
  constructor(e) {
644
761
  super("SerializationError", e);
645
762
  }
646
- }, Ae = class extends v {
763
+ }, je = class extends b {
647
764
  constructor(e) {
648
765
  super("InjectedFailureError", e);
649
766
  }
650
- }, je = class extends v {
767
+ }, Me = class extends b {
651
768
  constructor(e) {
652
769
  super("ChangeFeedCompactedError", e);
653
770
  }
654
- }, Me = class extends v {
771
+ }, Ne = class extends b {
655
772
  constructor(e) {
656
773
  super("RecoveryRequiredError", e);
657
774
  }
658
- }, Ne = class extends v {
775
+ }, Pe = class extends b {
659
776
  constructor(e) {
660
777
  super("InternalError", e);
661
778
  }
662
- }, E = class extends v {
779
+ }, O = class extends b {
663
780
  constructor(e) {
664
781
  super("InvalidOpenOptionsError", e);
665
782
  }
666
- }, D = class extends v {
783
+ }, k = class extends b {
667
784
  constructor(e) {
668
785
  super("VersionError", e);
669
786
  }
670
- }, Pe = {
671
- UnsupportedPlatformError: y,
672
- DatabaseBusyError: b,
673
- CorruptionError: ve,
674
- StoreExistsError: ye,
675
- StoreNotFoundError: be,
676
- IndexNotFoundError: xe,
677
- ConstraintError: x,
678
- UniqueIndexConstraintError: Se,
679
- WriteTransactionAlreadyOpenError: Ce,
680
- ReadonlyTransactionError: we,
681
- TransactionClosedError: S,
682
- DatabaseClosedError: C,
683
- ValueTooLargeError: Te,
684
- KeyTooLargeError: Ee,
685
- StoreNameTooLongError: De,
686
- ReservedStoreNameError: w,
687
- InvalidRangeError: Oe,
688
- StorageError: ke,
689
- SerializationError: T,
690
- InjectedFailureError: Ae,
691
- ChangeFeedCompactedError: je,
692
- RecoveryRequiredError: Me,
693
- InternalError: Ne,
694
- InvalidOpenOptionsError: E,
695
- VersionError: D
787
+ }, Fe = {
788
+ UnsupportedPlatformError: x,
789
+ DatabaseBusyError: S,
790
+ CorruptionError: ye,
791
+ StoreExistsError: be,
792
+ StoreNotFoundError: xe,
793
+ IndexNotFoundError: Se,
794
+ ConstraintError: C,
795
+ UniqueIndexConstraintError: Ce,
796
+ WriteTransactionAlreadyOpenError: we,
797
+ ReadonlyTransactionError: Te,
798
+ TransactionClosedError: w,
799
+ DatabaseClosedError: T,
800
+ ValueTooLargeError: Ee,
801
+ KeyTooLargeError: De,
802
+ StoreNameTooLongError: Oe,
803
+ ReservedStoreNameError: E,
804
+ InvalidRangeError: ke,
805
+ StorageError: Ae,
806
+ SerializationError: D,
807
+ InjectedFailureError: je,
808
+ ChangeFeedCompactedError: Me,
809
+ RecoveryRequiredError: Ne,
810
+ InternalError: Pe,
811
+ InvalidOpenOptionsError: O,
812
+ VersionError: k
696
813
  };
697
- function Fe(e, t) {
698
- if (Object.prototype.hasOwnProperty.call(Pe, e)) {
699
- let n = Pe[e];
814
+ function Ie(e, t) {
815
+ if (Object.prototype.hasOwnProperty.call(Fe, e)) {
816
+ let n = Fe[e];
700
817
  return new n(t);
701
818
  }
702
819
  let n = Error(t);
703
820
  return n.name = e, n;
704
821
  }
705
- function O(e) {
706
- if (e instanceof v) return e;
707
- if (e instanceof Error) return e.name === "Error" ? e : Fe(e.name, e.message);
822
+ function A(e) {
823
+ if (e instanceof b) return e;
824
+ if (e instanceof Error) return e.name === "Error" ? e : Ie(e.name, e.message);
708
825
  let t = e;
709
- return Fe(t?.code ?? t?.name ?? "Error", t?.message ?? String(e));
826
+ return Ie(t?.code ?? t?.name ?? "Error", t?.message ?? String(e));
710
827
  }
711
828
  //#endregion
712
829
  //#region src/registry.ts
713
- var Ie = /* @__PURE__ */ new Set([
830
+ var Le = /* @__PURE__ */ new Set([
714
831
  "after_wal_flush",
715
832
  "after_main_flush",
716
833
  "before_superblock_flush"
717
- ]), Le = "moyodb:persistence-bridge:init", Re = "moyodb:persistence-bridge:request", ze = "moyodb:persistence-bridge:response";
718
- function Be(t) {
719
- return e(t) && t.type === Re && typeof t.id == "number" && (t.op === "persist" || t.op === "persisted");
834
+ ]), Re = "moyodb:persistence-bridge:init", ze = "moyodb:persistence-bridge:request", Be = "moyodb:persistence-bridge:response";
835
+ function Ve(t) {
836
+ return e(t) && t.type === ze && typeof t.id == "number" && (t.op === "persist" || t.op === "persisted");
837
+ }
838
+ var He = 1e5, j = /* @__PURE__ */ new Map(), M = /* @__PURE__ */ new Map();
839
+ function N(e, t) {
840
+ let n = (M.get(e) ?? Promise.resolve()).then(t), r = n.then(() => void 0, () => void 0);
841
+ return M.set(e, r), r.then(() => {
842
+ M.get(e) === r && M.delete(e);
843
+ }), n;
720
844
  }
721
- var Ve = 1e5, k = /* @__PURE__ */ new Map();
722
- function He(e) {
723
- if (typeof e != "object" || !e || Array.isArray(e)) throw new E("open options must be an object");
845
+ function Ue(e) {
846
+ if (typeof e != "object" || !e || Array.isArray(e)) throw new O("open options must be an object");
724
847
  }
725
- function A(e, t, n) {
848
+ function P(e, t, n) {
726
849
  if (e === void 0) return n;
727
- if (typeof e != "boolean") throw new E(`${t} must be a boolean`);
850
+ if (typeof e != "boolean") throw new O(`${t} must be a boolean`);
728
851
  return e;
729
852
  }
730
- function j(e, t, n) {
853
+ function F(e, t, n) {
731
854
  if (e === void 0) return n;
732
- if (typeof e != "number" || !Number.isSafeInteger(e) || e < 0) throw new E(`${t} must be a non-negative safe integer`);
855
+ if (typeof e != "number" || !Number.isSafeInteger(e) || e < 0) throw new O(`${t} must be a non-negative safe integer`);
733
856
  return e;
734
857
  }
735
- function Ue(e) {
736
- return Math.max(1, j(e, "cachePages", 256));
737
- }
738
858
  function We(e) {
859
+ return Math.max(1, F(e, "cachePages", 256));
860
+ }
861
+ function Ge(e) {
739
862
  if (e == null) return null;
740
- if (typeof e != "string" || !Ie.has(e)) throw new E(`debugFailpoint must be one of: ${Array.from(Ie).join(", ")}`);
863
+ if (typeof e != "string" || !Le.has(e)) throw new O(`debugFailpoint must be one of: ${Array.from(Le).join(", ")}`);
741
864
  return e;
742
865
  }
743
- function Ge(e) {
866
+ function Ke(e) {
744
867
  if (e === void 0) return null;
745
- if (typeof e != "object" || !e || Array.isArray(e)) throw new E("changeFeed must be an object");
746
- let t = e, n = A(t.enabled, "changeFeed.enabled", !0), r = Ve;
868
+ if (typeof e != "object" || !e || Array.isArray(e)) throw new O("changeFeed must be an object");
869
+ let t = e, n = P(t.enabled, "changeFeed.enabled", !0), r = He;
747
870
  if (t.retainTxids === null) r = null;
748
- else if (t.retainTxids !== void 0 && (r = j(t.retainTxids, "changeFeed.retainTxids", 0), r === 0)) throw new E("changeFeed.retainTxids must be positive; disable the feed instead");
871
+ else if (t.retainTxids !== void 0 && (r = F(t.retainTxids, "changeFeed.retainTxids", 0), r === 0)) throw new O("changeFeed.retainTxids must be positive; disable the feed instead");
749
872
  return {
750
873
  enabled: n,
751
874
  retainTxids: r
752
875
  };
753
876
  }
754
- function Ke(e = {}) {
755
- return He(e), {
756
- createIfMissing: A(e.createIfMissing, "createIfMissing", !0),
757
- ownerWaitMs: j(e.ownerWaitMs, "ownerWaitMs", 0),
758
- requestPersistence: A(e.requestPersistence, "requestPersistence", !0),
759
- cachePages: Ue(e.cachePages),
760
- debugFailpoint: We(e.debugFailpoint),
761
- changeFeed: Ge(e.changeFeed)
877
+ function qe(e = {}) {
878
+ return Ue(e), {
879
+ createIfMissing: P(e.createIfMissing, "createIfMissing", !0),
880
+ ownerWaitMs: F(e.ownerWaitMs, "ownerWaitMs", 0),
881
+ requestPersistence: P(e.requestPersistence, "requestPersistence", !0),
882
+ cachePages: We(e.cachePages),
883
+ debugFailpoint: Ge(e.debugFailpoint),
884
+ changeFeed: Ke(e.changeFeed)
762
885
  };
763
886
  }
764
- function qe(e, t) {
887
+ function Je(e, t) {
765
888
  return e?.enabled === t?.enabled && e?.retainTxids === t?.retainTxids;
766
889
  }
767
- function Je(e, t, n) {
768
- if (t.cachePages !== n.cachePages) throw new E(`database ${e} is already open in this tab with cachePages=${t.cachePages}; requested cachePages=${n.cachePages}`);
769
- if (n.changeFeed !== null && !qe(t.changeFeed, n.changeFeed)) throw new E(`database ${e} is already open in this tab with a different changeFeed policy`);
890
+ function Ye(e, t, n) {
891
+ if (t.cachePages !== n.cachePages) throw new O(`database ${e} is already open in this tab with cachePages=${t.cachePages}; requested cachePages=${n.cachePages}`);
892
+ if (n.changeFeed !== null && !Je(t.changeFeed, n.changeFeed)) throw new O(`database ${e} is already open in this tab with a different changeFeed policy`);
770
893
  }
771
- async function Ye() {
894
+ async function Xe() {
772
895
  let e = globalThis.navigator.storage;
773
896
  return typeof e.persisted == "function" && await n(e.persisted(), 1e3, !1);
774
897
  }
775
- async function Xe() {
898
+ async function Ze() {
776
899
  let e = globalThis.navigator.storage;
777
900
  return typeof e.persist == "function" && await n(e.persist(), 1e3, !1);
778
901
  }
779
- async function Ze(e, t) {
780
- let n = t.op === "persist" ? await Xe() : await Ye(), r = {
781
- type: ze,
902
+ async function Qe(e, t) {
903
+ let n = t.op === "persist" ? await Ze() : await Xe(), r = {
904
+ type: Be,
782
905
  id: t.id,
783
906
  granted: n
784
907
  };
785
908
  e.postMessage(r);
786
909
  }
787
- function Qe(e) {
910
+ function $e(e) {
788
911
  let t = new MessageChannel(), n = t.port1;
789
912
  return n.addEventListener("message", (e) => {
790
913
  let t = e.data;
791
- Be(t) && Ze(n, t);
792
- }), n.start(), e.postMessage({ type: Le }, [t.port2]), { close() {
914
+ Ve(t) && Qe(n, t);
915
+ }), n.start(), e.postMessage({ type: Re }, [t.port2]), { close() {
793
916
  n.close();
794
917
  } };
795
918
  }
796
- function $e() {
919
+ function et() {
797
920
  let e = new Worker(new URL(
798
921
  /* @vite-ignore */
799
- "/assets/worker-R2dy1Ju5.js",
922
+ "/assets/worker-KDc8Khl_.js",
800
923
  "" + import.meta.url
801
924
  ), { type: "module" });
802
925
  return {
803
926
  worker: e,
804
- proxy: new _e(e),
805
- persistenceBridge: Qe(e)
927
+ proxy: new ve(e),
928
+ persistenceBridge: $e(e)
806
929
  };
807
930
  }
808
- function et(e, t, n, r, i) {
931
+ function tt(e, t, n, r, i) {
809
932
  let a = {
810
933
  dbName: e,
811
934
  refs: 1,
@@ -814,147 +937,161 @@ function et(e, t, n, r, i) {
814
937
  persistenceBridge: r,
815
938
  options: i,
816
939
  invalidated: !1,
940
+ schemaMigrationInProgress: !1,
817
941
  txInvalidationListeners: /* @__PURE__ */ new Set(),
818
942
  handleInvalidationListeners: /* @__PURE__ */ new Set()
819
943
  };
820
944
  return n.setFatalHandler(() => {
821
- k.get(e) !== a || a.invalidated || (k.delete(e), a.refs = 0, N(a), a.persistenceBridge.close(), a.worker.terminate());
945
+ j.get(e) !== a || a.invalidated || (j.delete(e), a.refs = 0, L(a), a.persistenceBridge.close(), a.worker.terminate());
822
946
  }), a;
823
947
  }
824
- function tt(e) {
948
+ function nt(e) {
825
949
  for (let t of Array.from(e)) t();
826
950
  }
827
- function nt(e, t) {
951
+ function rt(e, t) {
828
952
  return e.txInvalidationListeners.add(t), () => {
829
953
  e.txInvalidationListeners.delete(t);
830
954
  };
831
955
  }
832
- function rt(e, t) {
956
+ function it(e, t) {
833
957
  return e.handleInvalidationListeners.add(t), () => {
834
958
  e.handleInvalidationListeners.delete(t);
835
959
  };
836
960
  }
837
- function M(e) {
838
- tt(e.txInvalidationListeners);
839
- }
840
- function N(e) {
841
- e.invalidated || (e.invalidated = !0, M(e), tt(e.handleInvalidationListeners));
842
- }
843
- function it(e) {
844
- let t = k.get(e);
845
- return t ? (k.delete(e), N(t), t.refs = 0, t.persistenceBridge.close(), t.proxy.dispose(/* @__PURE__ */ Error("worker was terminated by unsafeDebugCrashWorker")), t.worker.terminate(), !0) : !1;
846
- }
847
- async function at(e, t = {}) {
848
- let n = Ke(t), r = k.get(e);
849
- if (r) {
850
- if (r.invalidated) k.delete(e);
851
- else {
852
- if (Je(e, r.options, n), n.debugFailpoint !== null) try {
853
- await r.proxy.setFailpoint(n.debugFailpoint);
854
- } catch (e) {
855
- throw O(e);
961
+ function I(e) {
962
+ nt(e.txInvalidationListeners);
963
+ }
964
+ function L(e) {
965
+ e.invalidated || (e.invalidated = !0, I(e), nt(e.handleInvalidationListeners));
966
+ }
967
+ function at(e) {
968
+ let t = j.get(e);
969
+ return t ? (j.delete(e), L(t), t.refs = 0, t.persistenceBridge.close(), t.proxy.dispose(/* @__PURE__ */ Error("worker was terminated by unsafeDebugCrashWorker")), t.worker.terminate(), !0) : !1;
970
+ }
971
+ async function ot(e, t = {}) {
972
+ let n = qe(t);
973
+ return N(e, async () => {
974
+ let t = j.get(e);
975
+ if (t) {
976
+ if (t.invalidated) j.delete(e);
977
+ else {
978
+ if (t.schemaMigrationInProgress) throw new S(`database ${e} is migrating; wait for openDB() to resolve`);
979
+ if (Ye(e, t.options, n), n.debugFailpoint !== null) try {
980
+ await t.proxy.setFailpoint(n.debugFailpoint);
981
+ } catch (e) {
982
+ throw A(e);
983
+ }
984
+ return t.refs += 1, t;
856
985
  }
857
- return r.refs += 1, r;
858
986
  }
859
- }
860
- let { worker: i, proxy: a, persistenceBridge: o } = $e(), s = et(e, i, a, o, n);
861
- try {
862
- return await a.open({
863
- dbName: e,
864
- options: n
865
- }), k.set(e, s), s;
866
- } catch (e) {
867
- throw o.close(), a.dispose(/* @__PURE__ */ Error("worker open failed")), i.terminate(), O(e);
868
- }
869
- }
870
- async function ot(e) {
871
- if (e.invalidated) return;
872
- let t = k.get(e.dbName);
873
- if (t && (--t.refs, !(t.refs > 0))) {
874
- k.delete(e.dbName);
987
+ let { worker: r, proxy: i, persistenceBridge: a } = et(), o = tt(e, r, i, a, n);
875
988
  try {
876
- await t.proxy.close();
877
- } finally {
878
- t.persistenceBridge.close(), t.proxy.dispose(/* @__PURE__ */ Error("worker was released")), t.worker.terminate();
989
+ return await i.open({
990
+ dbName: e,
991
+ options: n
992
+ }), j.set(e, o), o;
993
+ } catch (e) {
994
+ throw a.close(), i.dispose(/* @__PURE__ */ Error("worker open failed")), r.terminate(), A(e);
879
995
  }
880
- }
996
+ });
881
997
  }
882
998
  async function st(e) {
883
- let t = k.get(e.dbName) ?? e;
884
- k.delete(e.dbName), N(t), t.refs = 0;
885
- try {
886
- await t.proxy.destroy();
887
- } catch (e) {
888
- throw O(e);
889
- } finally {
890
- t.persistenceBridge.close(), t.proxy.dispose(/* @__PURE__ */ Error("worker was released")), t.worker.terminate();
891
- }
999
+ return N(e.dbName, async () => {
1000
+ if (!(e.invalidated || j.get(e.dbName) !== e) && (--e.refs, !(e.refs > 0))) {
1001
+ j.delete(e.dbName);
1002
+ try {
1003
+ await e.proxy.close();
1004
+ } finally {
1005
+ e.persistenceBridge.close(), e.proxy.dispose(/* @__PURE__ */ Error("worker was released")), e.worker.terminate();
1006
+ }
1007
+ }
1008
+ });
892
1009
  }
893
1010
  async function ct(e) {
894
- let t = k.get(e);
895
- if (t) {
896
- await st(t);
897
- return;
898
- }
899
- let { worker: n, proxy: r, persistenceBridge: i } = $e();
1011
+ return N(e.dbName, () => lt(e));
1012
+ }
1013
+ async function lt(e) {
1014
+ if (e.invalidated || j.get(e.dbName) !== e) throw new T();
1015
+ j.delete(e.dbName), L(e), e.refs = 0;
900
1016
  try {
901
- await r.deleteDB(e);
1017
+ await e.proxy.destroy();
902
1018
  } catch (e) {
903
- throw O(e);
1019
+ throw A(e);
904
1020
  } finally {
905
- i.close(), r.dispose(/* @__PURE__ */ Error("temporary worker was terminated")), n.terminate();
1021
+ e.persistenceBridge.close(), e.proxy.dispose(/* @__PURE__ */ Error("worker was released")), e.worker.terminate();
906
1022
  }
907
1023
  }
1024
+ async function ut(e) {
1025
+ return N(e, async () => {
1026
+ let t = j.get(e);
1027
+ if (t) {
1028
+ await lt(t);
1029
+ return;
1030
+ }
1031
+ let { worker: n, proxy: r, persistenceBridge: i } = et();
1032
+ try {
1033
+ await r.deleteDB(e);
1034
+ } catch (e) {
1035
+ throw A(e);
1036
+ } finally {
1037
+ i.close(), r.dispose(/* @__PURE__ */ Error("temporary worker was terminated")), n.terminate();
1038
+ }
1039
+ });
1040
+ }
908
1041
  //#endregion
909
1042
  //#region src/codec.ts
910
- var lt = new TextEncoder(), ut = new TextDecoder(), dt = 16, ft = 32, pt = 33, mt = 48, ht = 64, gt = 80, P = 0, _t = 255, F = 0, vt = 18446744073709551615n;
911
- function I(e) {
912
- return lt.encode(e);
1043
+ var dt = new TextEncoder(), ft = new TextDecoder(), pt = new TextDecoder("utf-8", { fatal: !0 }), mt = 16, ht = 32, gt = 33, _t = 48, vt = 64, yt = 80, R = 0, bt = 255, z = 0, xt = BigInt("0xffffffffffffffff");
1044
+ function B(e) {
1045
+ return dt.encode(e);
913
1046
  }
914
- function yt(e) {
915
- return ut.decode(e);
1047
+ function St(e) {
1048
+ return ft.decode(e);
916
1049
  }
917
- function bt(e) {
918
- return I(JSON.stringify(e));
1050
+ function Ct(e) {
1051
+ let t = JSON.stringify(e);
1052
+ if (t === void 0) throw TypeError("value has no JSON representation");
1053
+ return B(t);
919
1054
  }
920
- function xt(e) {
921
- return JSON.parse(yt(e));
1055
+ function wt(e) {
1056
+ return JSON.parse(pt.decode(e));
922
1057
  }
923
- function St(e) {
1058
+ function Tt(e) {
1059
+ if (typeof e == "number" && (!Number.isSafeInteger(e) || e < 0)) throw RangeError("u64Key number inputs must be safe non-negative integers; use bigint for larger values");
924
1060
  let t = typeof e == "bigint" ? e : BigInt(e);
925
1061
  if (t < 0n) throw RangeError("u64Key only accepts non-negative values");
1062
+ if (t > xt) throw RangeError("u64Key value exceeds the unsigned 64-bit range");
926
1063
  let n = /* @__PURE__ */ new ArrayBuffer(8);
927
1064
  return new DataView(n).setBigUint64(0, t, !1), new Uint8Array(n);
928
1065
  }
929
- function Ct(e) {
1066
+ function Et(e) {
930
1067
  return Array.isArray(e);
931
1068
  }
932
- function wt(e) {
933
- return Ct(e) ? L(...e) : V(e);
1069
+ function Dt(e) {
1070
+ return Et(e) ? V(...e) : G(e);
934
1071
  }
935
- function L(...e) {
936
- return Ot(e.map((e) => V(e)));
1072
+ function V(...e) {
1073
+ return jt(e.map((e) => G(e)));
937
1074
  }
938
- function Tt(e) {
939
- return V(e);
1075
+ function Ot(e) {
1076
+ return G(e);
940
1077
  }
941
- function R(e) {
942
- return Ot(e);
1078
+ function H(e) {
1079
+ return jt(e);
943
1080
  }
944
- function Et(e) {
1081
+ function kt(e) {
945
1082
  let t = [], n = [];
946
1083
  for (let r = 0; r < e.length; r += 1) {
947
1084
  let i = e[r];
948
- if (i !== P) {
1085
+ if (i !== R) {
949
1086
  n.push(i);
950
1087
  continue;
951
1088
  }
952
1089
  let a = e[r + 1];
953
- if (a === _t) {
954
- n.push(P), r += 1;
1090
+ if (a === bt) {
1091
+ n.push(R), r += 1;
955
1092
  continue;
956
1093
  }
957
- if (a === F) {
1094
+ if (a === z) {
958
1095
  t.push(Uint8Array.from(n)), n.length = 0, r += 1;
959
1096
  continue;
960
1097
  }
@@ -963,170 +1100,185 @@ function Et(e) {
963
1100
  if (n.length !== 0) throw TypeError("compound key terminated unexpectedly");
964
1101
  return t;
965
1102
  }
966
- function z(e) {
1103
+ function U(e) {
967
1104
  let t = e.slice();
968
1105
  for (let e = t.length - 1; e >= 0; --e) if (t[e] !== 255) return t[e] += 1, t.subarray(0, e + 1);
969
1106
  return null;
970
1107
  }
971
- function B(e) {
972
- let t = z(e);
1108
+ function W(e) {
1109
+ let t = U(e);
973
1110
  return t ? {
974
1111
  gte: e,
975
1112
  lt: t
976
1113
  } : { gte: e };
977
1114
  }
978
- function Dt(...e) {
979
- return B(L(...e));
1115
+ function At(...e) {
1116
+ return W(V(...e));
980
1117
  }
981
- function V(e) {
982
- if (e === null) return Uint8Array.of(dt);
983
- if (typeof e == "boolean") return Uint8Array.of(e ? pt : ft);
984
- if (typeof e == "number") return kt(e);
1118
+ function G(e) {
1119
+ if (e === null) return Uint8Array.of(mt);
1120
+ if (typeof e == "boolean") return Uint8Array.of(e ? gt : ht);
1121
+ if (typeof e == "number") return Mt(e);
985
1122
  if (typeof e == "string") {
986
- let t = I(e), n = new Uint8Array(1 + t.length);
987
- return n[0] = ht, n.set(t, 1), n;
1123
+ for (let t of e) {
1124
+ let e = t.codePointAt(0);
1125
+ if (e >= 55296 && e <= 57343) throw TypeError("compound key string parts must contain valid Unicode scalar values");
1126
+ }
1127
+ let t = B(e), n = new Uint8Array(1 + t.length);
1128
+ return n[0] = vt, n.set(t, 1), n;
988
1129
  }
989
1130
  if (e instanceof Uint8Array) {
990
1131
  let t = new Uint8Array(1 + e.length);
991
- return t[0] = gt, t.set(e, 1), t;
1132
+ return t[0] = yt, t.set(e, 1), t;
992
1133
  }
993
1134
  throw TypeError("compound key parts must be string, number, boolean, null, or Uint8Array");
994
1135
  }
995
- function Ot(e) {
1136
+ function jt(e) {
996
1137
  let t = 0;
997
1138
  for (let n of e) {
998
- for (let e of n) t += e === P ? 2 : 1;
1139
+ for (let e of n) t += e === R ? 2 : 1;
999
1140
  t += 2;
1000
1141
  }
1001
1142
  let n = new Uint8Array(t), r = 0;
1002
1143
  for (let t of e) {
1003
- for (let e of t) e === P ? (n[r] = P, n[r + 1] = _t, r += 2) : (n[r] = e, r += 1);
1004
- n[r] = F, n[r + 1] = F, r += 2;
1144
+ for (let e of t) e === R ? (n[r] = R, n[r + 1] = bt, r += 2) : (n[r] = e, r += 1);
1145
+ n[r] = z, n[r + 1] = z, r += 2;
1005
1146
  }
1006
1147
  return n;
1007
1148
  }
1008
- function kt(e) {
1149
+ function Mt(e) {
1009
1150
  if (!Number.isFinite(e)) throw TypeError("compound key number parts must be finite");
1010
1151
  let t = Object.is(e, -0) ? 0 : e, n = /* @__PURE__ */ new ArrayBuffer(9), r = new DataView(n);
1011
- r.setUint8(0, mt), r.setFloat64(1, t, !1);
1152
+ r.setUint8(0, _t), r.setFloat64(1, t, !1);
1012
1153
  let i = r.getBigUint64(1, !1);
1013
- return i = (i & 1n << 63n) == 0n ? i ^ 1n << 63n : ~i & vt, r.setBigUint64(1, i, !1), new Uint8Array(n);
1154
+ return i = (i & 1n << 63n) == 0n ? i ^ 1n << 63n : ~i & xt, r.setBigUint64(1, i, !1), new Uint8Array(n);
1014
1155
  }
1015
1156
  //#endregion
1016
1157
  //#region src/indexing.ts
1017
- var At = new TextEncoder(), jt = new TextDecoder("utf-8", { fatal: !0 }), H = Symbol("moyodb.indexing.missing"), Mt = 14695981039346656037n, Nt = 1099511628211n, Pt = 18446744073709551615n, Ft = "__browserdb:", It = "__browserdb:index:", Lt = "__browserdb:indexes";
1018
- function Rt(e) {
1019
- return e.startsWith(Ft);
1158
+ var Nt = new TextEncoder(), Pt = new TextDecoder("utf-8", { fatal: !0 }), K = Symbol("moyodb.indexing.missing"), Ft = BigInt("0xcbf29ce484222325"), It = BigInt("0x100000001b3"), Lt = BigInt("0xffffffffffffffff"), Rt = "__browserdb:", zt = "__browserdb:index:", Bt = "__browserdb:indexes";
1159
+ function Vt(e) {
1160
+ return e.startsWith(Rt);
1020
1161
  }
1021
- function U(e) {
1022
- if (Rt(e)) throw new w(`reserved store name: ${e}`);
1162
+ function q(e) {
1163
+ if (Vt(e)) throw new E(`reserved store name: ${e}`);
1023
1164
  }
1024
- function W(e) {
1165
+ function J(e) {
1025
1166
  if (e === void 0) return [];
1026
- if (!Array.isArray(e)) throw new E("indexes must be an array");
1167
+ if (!Array.isArray(e)) throw new O("indexes must be an array");
1027
1168
  let t = [], n = /* @__PURE__ */ new Set(), r = /* @__PURE__ */ new Map();
1028
1169
  for (let i of e) {
1029
- if (typeof i != "object" || !i || Array.isArray(i)) throw new E("each index definition must be an object");
1170
+ if (typeof i != "object" || !i || Array.isArray(i)) throw new O("each index definition must be an object");
1030
1171
  let { store: e, name: a, keyPath: o, unique: s } = i;
1031
- if (typeof e != "string" || e.length === 0) throw new E("index store must be a non-empty string");
1032
- if (typeof a != "string" || a.length === 0) throw new E("index name must be a non-empty string");
1033
- U(e);
1034
- let c = Qt(o);
1035
- if (s !== void 0 && typeof s != "boolean") throw new E("index unique must be a boolean");
1172
+ if (typeof e != "string" || e.length === 0) throw new O("index store must be a non-empty string");
1173
+ if (typeof a != "string" || a.length === 0) throw new O("index name must be a non-empty string");
1174
+ q(e);
1175
+ let c = sn(o);
1176
+ if (s !== void 0 && typeof s != "boolean") throw new O("index unique must be a boolean");
1036
1177
  let l = {
1037
1178
  store: e,
1038
1179
  name: a,
1039
1180
  keyPath: c.paths,
1040
1181
  compound: c.compound,
1041
1182
  unique: s ?? !1,
1042
- internalStore: tn(e, a)
1043
- }, u = G(l.store, l.name);
1044
- if (n.has(u)) throw new E(`duplicate index definition ${l.store}.${l.name}`);
1183
+ internalStore: un(e, a)
1184
+ }, u = Ut(l.store, l.name);
1185
+ if (n.has(u)) throw new O(`duplicate index definition ${l.store}.${l.name}`);
1045
1186
  n.add(u);
1046
1187
  let d = r.get(l.internalStore);
1047
- if (d && d !== u) throw new E(`index definitions ${d} and ${u} map to the same internal store ${l.internalStore}`);
1188
+ if (d && d !== u) throw new O(`index definitions ${d} and ${u} map to the same internal store ${l.internalStore}`);
1048
1189
  r.set(l.internalStore, u), t.push(l);
1049
1190
  }
1050
- return t.sort(zt), t;
1191
+ return t.sort(Ht), t;
1051
1192
  }
1052
- function zt(e, n) {
1193
+ function Ht(e, n) {
1053
1194
  let r = t(e.store, n.store);
1054
1195
  if (r !== 0) return r;
1055
1196
  let i = t(e.name, n.name);
1056
1197
  if (i !== 0) return i;
1057
1198
  let a = Number(e.unique) - Number(n.unique);
1058
- return a === 0 ? t(en(e), en(n)) : a;
1199
+ return a === 0 ? t(ln(e), ln(n)) : a;
1059
1200
  }
1060
- function G(e, t) {
1061
- return `${e}\u0000${t}`;
1201
+ function Ut(e, t) {
1202
+ return JSON.stringify([e, t]);
1062
1203
  }
1063
- function Bt(e, t, n) {
1204
+ function Wt(e, t, n) {
1064
1205
  return e.find((e) => e.store === t && e.name === n) ?? null;
1065
1206
  }
1066
- function Vt(e, t) {
1207
+ function Gt(e, t) {
1067
1208
  return e.filter((e) => e.store === t);
1068
1209
  }
1069
- function Ht(e, t) {
1070
- return R([I(e), I(t)]);
1210
+ function Kt(e, t) {
1211
+ return H([B(e), B(t)]);
1071
1212
  }
1072
- function Ut(e) {
1073
- return I(JSON.stringify(Zt(e)));
1213
+ function qt(e) {
1214
+ return B(JSON.stringify(on(e)));
1074
1215
  }
1075
- function Wt(e) {
1216
+ function Jt(e) {
1076
1217
  let t;
1077
1218
  try {
1078
- t = JSON.parse(jt.decode(e));
1219
+ t = JSON.parse(Pt.decode(e));
1220
+ let [n] = J([t]);
1221
+ return n;
1079
1222
  } catch (e) {
1080
- throw new T(`invalid persisted index metadata: ${String(e)}`);
1223
+ throw new D(`invalid persisted index metadata: ${String(e)}`);
1081
1224
  }
1082
- let [n] = W([t]);
1083
- return n;
1084
1225
  }
1085
- function Gt(e, t) {
1086
- return R([e, t]);
1226
+ function Yt(e, t) {
1227
+ return H([e, t]);
1087
1228
  }
1088
- function Kt(e) {
1089
- let t = Et(e);
1090
- if (t.length !== 2) throw new T("invalid index entry key encoding");
1229
+ function Xt(e) {
1230
+ let t;
1231
+ try {
1232
+ t = kt(e);
1233
+ } catch (e) {
1234
+ throw new D(`invalid index entry key encoding: ${String(e)}`);
1235
+ }
1236
+ if (t.length !== 2) throw new D("invalid index entry key encoding");
1091
1237
  return {
1092
1238
  logicalKey: t[0],
1093
1239
  primaryKey: t[1]
1094
1240
  };
1095
1241
  }
1096
- function qt(e) {
1097
- return B(R([e]));
1242
+ function Zt(e) {
1243
+ return W(H([e]));
1098
1244
  }
1099
- function Jt(e = {}) {
1100
- ln(e);
1245
+ function Qt(e = {}) {
1246
+ _n(e);
1101
1247
  let t = {};
1102
- if (e.reverse !== void 0 && (t.reverse = e.reverse), e.limit !== void 0 && (t.limit = e.limit), e.gte && (t.gte = R([e.gte])), e.gt) {
1103
- let n = z(R([e.gt]));
1248
+ if (e.reverse !== void 0 && (t.reverse = e.reverse), e.limit !== void 0 && (t.limit = e.limit), e.gte && (t.gte = H([e.gte])), e.gt) {
1249
+ let n = U(H([e.gt]));
1104
1250
  n && (t.gte = n);
1105
1251
  }
1106
- if (e.lt && (t.lt = R([e.lt])), e.lte) {
1107
- let n = z(R([e.lte]));
1252
+ if (e.lt && (t.lt = H([e.lt])), e.lte) {
1253
+ let n = U(H([e.lte]));
1108
1254
  n && (t.lt = n);
1109
1255
  }
1110
1256
  return t;
1111
1257
  }
1112
- function Yt(e, t) {
1113
- let n = an(t);
1258
+ function $t(e, t) {
1259
+ return tn(e, pn(t));
1260
+ }
1261
+ function en(e) {
1262
+ let t = !1, n;
1263
+ return (r) => (t ||= (n = pn(e), !0), tn(r, n));
1264
+ }
1265
+ function tn(e, t) {
1114
1266
  if (e.compound) {
1115
- let t = [];
1267
+ let n = [];
1116
1268
  for (let r of e.keyPath) {
1117
- let e = on(n, r);
1118
- if (e === H) return null;
1119
- t.push(sn(e));
1269
+ let e = mn(t, r);
1270
+ if (e === K) return null;
1271
+ n.push(hn(e));
1120
1272
  }
1121
- return R(t);
1273
+ return H(n);
1122
1274
  }
1123
- let r = on(n, e.keyPath[0]);
1124
- return r === H ? null : sn(r);
1275
+ let n = mn(t, e.keyPath[0]);
1276
+ return n === K ? null : hn(n);
1125
1277
  }
1126
- function K(e) {
1127
- return JSON.stringify(q(e));
1278
+ function nn(e) {
1279
+ return JSON.stringify(an(e));
1128
1280
  }
1129
- function Xt(e) {
1281
+ function rn(e) {
1130
1282
  return e.map((e) => ({
1131
1283
  store: e.store,
1132
1284
  name: e.name,
@@ -1136,10 +1288,10 @@ function Xt(e) {
1136
1288
  internalStore: e.internalStore
1137
1289
  }));
1138
1290
  }
1139
- function q(e) {
1140
- return e.map(Zt);
1291
+ function an(e) {
1292
+ return e.map(on);
1141
1293
  }
1142
- function Zt(e) {
1294
+ function on(e) {
1143
1295
  return {
1144
1296
  store: e.store,
1145
1297
  name: e.name,
@@ -1147,92 +1299,96 @@ function Zt(e) {
1147
1299
  unique: e.unique
1148
1300
  };
1149
1301
  }
1150
- function Qt(e) {
1151
- if (typeof e == "string") return $t(e), {
1302
+ function sn(e) {
1303
+ if (typeof e == "string") return cn(e), {
1152
1304
  paths: [e],
1153
1305
  compound: !1
1154
1306
  };
1155
- if (!Array.isArray(e) || e.length === 0 || !e.every((e) => typeof e == "string")) throw new E("index keyPath must be a non-empty string or non-empty string[]");
1156
- for (let t of e) $t(t);
1307
+ if (!Array.isArray(e) || e.length === 0 || !e.every((e) => typeof e == "string")) throw new O("index keyPath must be a non-empty string or non-empty string[]");
1308
+ for (let t of e) cn(t);
1157
1309
  return {
1158
1310
  paths: [...e],
1159
1311
  compound: !0
1160
1312
  };
1161
1313
  }
1162
- function $t(e) {
1163
- if (e.length === 0) throw new E("index keyPath strings must be non-empty");
1164
- if (e.startsWith(".") || e.endsWith(".") || e.includes("..")) throw new E(`invalid index keyPath: ${e}`);
1314
+ function cn(e) {
1315
+ if (e.length === 0) throw new O("index keyPath strings must be non-empty");
1316
+ if (e.startsWith(".") || e.endsWith(".") || e.includes("..")) throw new O(`invalid index keyPath: ${e}`);
1165
1317
  }
1166
- function en(e) {
1318
+ function ln(e) {
1167
1319
  return e.compound ? `[${e.keyPath.join(",")}]` : e.keyPath[0];
1168
1320
  }
1169
- function tn(e, t) {
1170
- let n = `${It}${nn(I(e))}:${nn(I(t))}`;
1171
- return At.encode(n).length <= 255 ? n : `${It}h:${rn(I(G(e, t)))}`;
1321
+ function un(e, t) {
1322
+ let n = `${zt}${dn(B(e))}:${dn(B(t))}`;
1323
+ return Nt.encode(n).length <= 255 ? n : `${zt}h:${fn(B(`${e}\u0000${t}`))}`;
1172
1324
  }
1173
- function nn(e) {
1325
+ function dn(e) {
1174
1326
  let t = "";
1175
1327
  for (let n of e) t += String.fromCharCode(n);
1176
1328
  return btoa(t).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/u, "");
1177
1329
  }
1178
- function rn(e) {
1179
- let t = Mt;
1180
- for (let n of e) t ^= BigInt(n), t = t * Nt & Pt;
1330
+ function fn(e) {
1331
+ let t = Ft;
1332
+ for (let n of e) t ^= BigInt(n), t = t * It & Lt;
1181
1333
  return t.toString(16).padStart(16, "0");
1182
1334
  }
1183
- function an(e) {
1335
+ function pn(e) {
1184
1336
  try {
1185
- return JSON.parse(jt.decode(e));
1337
+ return JSON.parse(Pt.decode(e));
1186
1338
  } catch (e) {
1187
- throw new T(`indexed values must be valid UTF-8 JSON: ${String(e)}`);
1339
+ throw new D(`indexed values must be valid UTF-8 JSON: ${String(e)}`);
1188
1340
  }
1189
1341
  }
1190
- function on(e, t) {
1342
+ function mn(e, t) {
1191
1343
  let n = e;
1192
1344
  for (let e of t.split(".")) {
1193
- if (n == null) return H;
1345
+ if (n == null) return K;
1194
1346
  let t = Object(n);
1195
- if (!(e in t)) return H;
1347
+ if (!Object.hasOwn(t, e)) return K;
1196
1348
  n = Reflect.get(t, e);
1197
1349
  }
1198
1350
  return n;
1199
1351
  }
1200
- function sn(e) {
1201
- if (e instanceof Uint8Array || e === null || typeof e == "string" || typeof e == "number" || typeof e == "boolean") return Tt(e);
1202
- throw new T(`indexed keyPath values must resolve to string, number, boolean, null, or Uint8Array; got ${cn(e)}`);
1352
+ function hn(e) {
1353
+ if (e === null || typeof e == "string" || typeof e == "number" || typeof e == "boolean" || e instanceof Uint8Array) try {
1354
+ return Ot(e);
1355
+ } catch (e) {
1356
+ throw e instanceof TypeError ? new D(`invalid indexed keyPath value: ${e.message}`) : e;
1357
+ }
1358
+ throw new D(`indexed keyPath values must resolve to string, number, boolean, null, or Uint8Array; got ${gn(e)}`);
1203
1359
  }
1204
- function cn(e) {
1205
- return Array.isArray(e) ? "array" : e === null ? "null" : typeof e;
1360
+ function gn(e) {
1361
+ return Array.isArray(e) ? "array" : typeof e;
1206
1362
  }
1207
- function ln(e) {
1363
+ function _n(e) {
1208
1364
  if (e.gt !== void 0 && e.gte !== void 0) throw TypeError("index range cannot specify both gt and gte");
1209
1365
  if (e.lt !== void 0 && e.lte !== void 0) throw TypeError("index range cannot specify both lt and lte");
1210
1366
  }
1211
1367
  //#endregion
1212
1368
  //#region src/change-events.ts
1213
- function un(t) {
1369
+ function vn(t) {
1214
1370
  return !e(t) || !(t.key instanceof Uint8Array) ? !1 : t.kind === "put" || t.kind === "delete" || (t.kind === "clear" || t.kind === "drop") && t.key.byteLength === 0;
1215
1371
  }
1216
- function dn(t) {
1217
- return e(t) && typeof t.store == "string" && Array.isArray(t.changes) && t.changes.every(un);
1372
+ function yn(t) {
1373
+ return e(t) && typeof t.store == "string" && Array.isArray(t.changes) && t.changes.every(vn);
1218
1374
  }
1219
- function fn(t) {
1220
- return e(t) && t.type === "commit_applied" && typeof t.dbName == "string" && typeof t.txid == "number" && Array.isArray(t.stores) && t.stores.every(dn);
1375
+ function bn(t) {
1376
+ return e(t) && t.type === "commit_applied" && typeof t.dbName == "string" && typeof t.txid == "number" && Array.isArray(t.stores) && t.stores.every(yn);
1221
1377
  }
1222
1378
  //#endregion
1223
1379
  //#region src/subscriptions.ts
1224
- function pn(e) {
1380
+ function xn(e) {
1225
1381
  return e.map((e) => ({
1226
1382
  key: e.key.slice(),
1227
1383
  kind: e.kind
1228
1384
  }));
1229
1385
  }
1230
- function mn(e, t) {
1386
+ function Sn(e, t) {
1231
1387
  if (t.byteLength > e.byteLength) return !1;
1232
1388
  for (let n = 0; n < t.byteLength; n += 1) if (e[n] !== t[n]) return !1;
1233
1389
  return !0;
1234
1390
  }
1235
- function hn(e, t, n) {
1391
+ function Cn(e, t, n) {
1236
1392
  if (typeof e == "function") {
1237
1393
  if (t !== void 0 || n !== void 0) throw TypeError("subscribe(callback) accepts exactly one callback argument");
1238
1394
  return {
@@ -1242,7 +1398,7 @@ function hn(e, t, n) {
1242
1398
  };
1243
1399
  }
1244
1400
  if (typeof e != "string") throw TypeError("subscribe() storeName must be a string");
1245
- if (U(e), typeof t == "function") {
1401
+ if (q(e), typeof t == "function") {
1246
1402
  if (n !== void 0) throw TypeError("subscribe(storeName, callback) accepts exactly two arguments");
1247
1403
  return {
1248
1404
  store: e,
@@ -1257,7 +1413,7 @@ function hn(e, t, n) {
1257
1413
  };
1258
1414
  throw TypeError("subscribe() expects one of: (callback), (storeName, callback), (storeName, keyPrefix, callback)");
1259
1415
  }
1260
- var gn = class {
1416
+ var wn = class {
1261
1417
  #e;
1262
1418
  #t = null;
1263
1419
  #n = /* @__PURE__ */ new Set();
@@ -1266,8 +1422,8 @@ var gn = class {
1266
1422
  this.#e = e;
1267
1423
  }
1268
1424
  subscribe(e, t, n) {
1269
- if (this.#r) throw new C();
1270
- let r = hn(e, t, n), i = {
1425
+ if (this.#r) throw new T();
1426
+ let r = Cn(e, t, n), i = {
1271
1427
  active: !0,
1272
1428
  store: r.store,
1273
1429
  keyPrefix: r.keyPrefix,
@@ -1278,7 +1434,11 @@ var gn = class {
1278
1434
  };
1279
1435
  }
1280
1436
  close() {
1281
- this.#r || (this.#r = !0, this.#n.clear(), this.#a());
1437
+ if (!this.#r) {
1438
+ this.#r = !0;
1439
+ for (let e of this.#n) e.active = !1;
1440
+ this.#n.clear(), this.#a();
1441
+ }
1282
1442
  }
1283
1443
  #i() {
1284
1444
  if (this.#t !== null || this.#r) return;
@@ -1291,13 +1451,13 @@ var gn = class {
1291
1451
  this.#t?.close(), this.#t = null;
1292
1452
  }
1293
1453
  #o(e) {
1294
- if (!fn(e) || e.dbName !== this.#e || this.#n.size === 0) return;
1454
+ if (!bn(e) || e.dbName !== this.#e || this.#n.size === 0) return;
1295
1455
  let t = Array.from(this.#n);
1296
1456
  for (let n of e.stores) for (let r of t) {
1297
1457
  if (!r.active || r.store !== null && r.store !== n.store) continue;
1298
1458
  let t, i = r.keyPrefix;
1299
- if (i === null) t = pn(n.changes);
1300
- else if (t = pn(n.changes.filter((e) => e.kind === "clear" || e.kind === "drop" || mn(e.key, i))), t.length === 0) continue;
1459
+ if (i === null) t = xn(n.changes);
1460
+ else if (t = xn(n.changes.filter((e) => e.kind === "clear" || e.kind === "drop" || Sn(e.key, i))), t.length === 0) continue;
1301
1461
  try {
1302
1462
  r.callback(n.store, t, e.txid);
1303
1463
  } catch (e) {
@@ -1307,15 +1467,15 @@ var gn = class {
1307
1467
  }
1308
1468
  }
1309
1469
  }
1310
- }, _n = 256;
1311
- async function J(e) {
1470
+ }, Tn = 256;
1471
+ async function Y(e) {
1312
1472
  try {
1313
1473
  return await e();
1314
1474
  } catch (e) {
1315
- throw O(e);
1475
+ throw A(e);
1316
1476
  }
1317
1477
  }
1318
- var vn = class {
1478
+ var En = class {
1319
1479
  mode;
1320
1480
  #e;
1321
1481
  #t;
@@ -1325,59 +1485,59 @@ var vn = class {
1325
1485
  this.#e = e, this.#t = t, this.mode = n, this.#r = r;
1326
1486
  }
1327
1487
  async get(e, t) {
1328
- return this.#i(), U(e), J(() => this.#e.proxy.get(this.#t, e, t));
1488
+ return this.#i(), q(e), Y(() => this.#e.proxy.get(this.#t, e, t));
1329
1489
  }
1330
1490
  async getMany(e, t) {
1331
- return this.#i(), U(e), J(() => this.#e.proxy.getMany(this.#t, e, t));
1491
+ return this.#i(), q(e), Y(() => this.#e.proxy.getMany(this.#t, e, t));
1332
1492
  }
1333
1493
  async has(e, t) {
1334
- return this.#i(), U(e), J(() => this.#e.proxy.has(this.#t, e, t));
1494
+ return this.#i(), q(e), Y(() => this.#e.proxy.has(this.#t, e, t));
1335
1495
  }
1336
1496
  async put(e, t, n, r = {}) {
1337
- return this.#i(), U(e), J(() => this.#e.proxy.put(this.#t, e, t, n, $(r)));
1497
+ return this.#i(), q(e), Y(() => this.#e.proxy.put(this.#t, e, t, n, $(r)));
1338
1498
  }
1339
1499
  async putMany(e, t, n = {}) {
1340
- return this.#i(), U(e), J(() => this.#e.proxy.putMany(this.#t, e, t, $(n)));
1500
+ return this.#i(), q(e), Y(() => this.#e.proxy.putMany(this.#t, e, t, $(n)));
1341
1501
  }
1342
1502
  async delete(e, t) {
1343
- return this.#i(), U(e), J(() => this.#e.proxy.delete(this.#t, e, t));
1503
+ return this.#i(), q(e), Y(() => this.#e.proxy.delete(this.#t, e, t));
1344
1504
  }
1345
1505
  async deleteMany(e, t) {
1346
- return this.#i(), U(e), J(() => this.#e.proxy.deleteMany(this.#t, e, t));
1506
+ return this.#i(), q(e), Y(() => this.#e.proxy.deleteMany(this.#t, e, t));
1347
1507
  }
1348
1508
  async applyBatch(e, t) {
1349
- return this.#i(), U(e), J(() => this.#e.proxy.applyBatch(this.#t, e, t));
1509
+ return this.#i(), q(e), Y(() => this.#e.proxy.applyBatch(this.#t, e, t));
1350
1510
  }
1351
1511
  async scan(e, t = {}) {
1352
- return this.#i(), U(e), J(() => this.#e.proxy.scan(this.#t, e, t));
1512
+ return this.#i(), q(e), Y(() => this.#e.proxy.scan(this.#t, e, t));
1353
1513
  }
1354
1514
  async getByIndex(e, t, n) {
1355
- return this.#i(), U(e), J(() => this.#e.proxy.getByIndex(this.#t, e, t, n));
1515
+ return this.#i(), q(e), Y(() => this.#e.proxy.getByIndex(this.#t, e, t, n));
1356
1516
  }
1357
1517
  async *scanByIndex(e, t, n = {}) {
1358
- this.#i(), U(e);
1518
+ this.#i(), q(e);
1359
1519
  let r = n.limit ?? Infinity, i = null;
1360
1520
  for (; r > 0;) {
1361
1521
  this.#i();
1362
- let a = Math.min(r, _n), o = i, s = await J(() => this.#e.proxy.scanByIndexPage(this.#t, e, t, n, o, a));
1522
+ let a = Math.min(r, Tn), o = i, s = await Y(() => this.#e.proxy.scanByIndexPage(this.#t, e, t, n, o, a));
1363
1523
  for (let e of s.rows) yield [e.key, e.value];
1364
1524
  if (r -= s.rows.length, s.cursor === null) return;
1365
1525
  i = s.cursor;
1366
1526
  }
1367
1527
  }
1368
1528
  async createStore(e, t = {}) {
1369
- return this.#i(), U(e), J(() => this.#e.proxy.createStore(this.#t, e, kn(t)));
1529
+ return this.#i(), q(e), Y(() => this.#e.proxy.createStore(this.#t, e, Rn(t)));
1370
1530
  }
1371
1531
  async dropStore(e) {
1372
- return this.#i(), U(e), J(() => this.#e.proxy.dropStore(this.#t, e));
1532
+ return this.#i(), q(e), Y(() => this.#e.proxy.dropStore(this.#t, e));
1373
1533
  }
1374
1534
  async clearStore(e) {
1375
- return this.#i(), U(e), J(() => this.#e.proxy.clearStore(this.#t, e));
1535
+ return this.#i(), q(e), Y(() => this.#e.proxy.clearStore(this.#t, e));
1376
1536
  }
1377
1537
  async commit() {
1378
1538
  this.#i();
1379
1539
  try {
1380
- await J(() => this.#e.proxy.commit(this.#t));
1540
+ await Y(() => this.#e.proxy.commit(this.#t));
1381
1541
  } finally {
1382
1542
  this.#a();
1383
1543
  }
@@ -1385,7 +1545,7 @@ var vn = class {
1385
1545
  async rollback() {
1386
1546
  this.#i();
1387
1547
  try {
1388
- await J(() => this.#e.proxy.rollback(this.#t));
1548
+ await Y(() => this.#e.proxy.rollback(this.#t));
1389
1549
  } finally {
1390
1550
  this.#a();
1391
1551
  }
@@ -1399,8 +1559,8 @@ var vn = class {
1399
1559
  try {
1400
1560
  await this.#e.proxy.rollback(this.#t);
1401
1561
  } catch (e) {
1402
- let t = O(e);
1403
- if (!(t instanceof S)) throw t;
1562
+ let t = A(e);
1563
+ if (!(t instanceof w)) throw t;
1404
1564
  } finally {
1405
1565
  this.#a();
1406
1566
  }
@@ -1413,31 +1573,34 @@ var vn = class {
1413
1573
  return this.#t;
1414
1574
  }
1415
1575
  #i() {
1416
- if (this.#n || this.#e.invalidated) throw new S();
1576
+ if (this.#n || this.#e.invalidated) throw new w();
1417
1577
  }
1418
1578
  #a() {
1419
1579
  this.#n || (this.#n = !0, this.#r());
1420
1580
  }
1421
- }, yn = class {
1581
+ }, Dn = class {
1422
1582
  #e;
1423
1583
  #t = !1;
1424
- #n = /* @__PURE__ */ new Set();
1425
- #r;
1426
- #i = null;
1427
- #a = null;
1584
+ #n = null;
1585
+ #r = /* @__PURE__ */ new Set();
1586
+ #i = /* @__PURE__ */ new Set();
1587
+ #a = 0;
1588
+ #o;
1589
+ #s = null;
1590
+ #c = null;
1428
1591
  constructor(e) {
1429
- this.#e = e, this.#r = new gn(e.dbName), this.#i = nt(e, () => {
1430
- this.#l();
1431
- }), this.#a = rt(e, () => {
1432
- this.#u();
1592
+ this.#e = e, this.#o = new wn(e.dbName), this.#s = rt(e, () => {
1593
+ this.#p();
1594
+ }), this.#c = it(e, () => {
1595
+ this.#m();
1433
1596
  });
1434
1597
  }
1435
1598
  async begin(e = "readonly") {
1436
- return this.#o(e);
1599
+ return this.#l(e);
1437
1600
  }
1438
1601
  async runSchemaMigration(e, t, n, r) {
1439
- this.#d();
1440
- let i = await this.#o("readwrite"), a = new bn(), o = new xn(i, a), s = new Sn(this, o, a);
1602
+ this.#h();
1603
+ let i = await this.#l("readwrite"), a = new On(), o = new kn(i, a), s = new An(this, o, a);
1441
1604
  try {
1442
1605
  await this.#e.proxy.reconcileIndexes(i.internalId(), r), await n({
1443
1606
  db: s,
@@ -1453,42 +1616,51 @@ var vn = class {
1453
1616
  }
1454
1617
  }
1455
1618
  async listStores() {
1456
- return this.#d(), J(() => this.#e.proxy.listStores());
1619
+ return this.#h(), Y(() => this.#e.proxy.listStores());
1457
1620
  }
1458
1621
  async getVersion() {
1459
- return this.#d(), J(() => this.#e.proxy.getVersion());
1622
+ return this.#h(), Y(() => this.#e.proxy.getVersion());
1460
1623
  }
1461
1624
  async changesSince(e, t = {}) {
1462
- return this.#d(), J(() => this.#e.proxy.changesSince(jn(e), Mn(t)));
1625
+ return this.#h(), Y(() => this.#e.proxy.changesSince(Bn(e), Vn(t)));
1463
1626
  }
1464
- async #o(e) {
1465
- return this.#d(), J(async () => {
1466
- let t = await this.#e.proxy.begin(e), n = new vn(this.#e, t, e, () => {
1467
- this.#n.delete(n);
1627
+ async #l(e) {
1628
+ this.#h();
1629
+ let t = this.#a, n = Y(async () => {
1630
+ let n = await this.#e.proxy.begin(e), r = new En(this.#e, n, e, () => {
1631
+ this.#r.delete(r);
1468
1632
  });
1469
- return this.#n.add(n), n;
1633
+ if (this.#r.add(r), this.#t || this.#e.invalidated) throw this.#e.invalidated && r.forceClose(), new T();
1634
+ if (t !== this.#a) throw await r.rollbackIfOpen(), new w();
1635
+ return r;
1470
1636
  });
1637
+ this.#i.add(n);
1638
+ try {
1639
+ return await n;
1640
+ } finally {
1641
+ this.#i.delete(n);
1642
+ }
1471
1643
  }
1472
1644
  async createStore(e, t = {}) {
1473
- U(e), await this.#s("readwrite", "createStore", [e, kn(t)]);
1645
+ q(e), await this.#u("readwrite", "createStore", [e, Rn(t)]);
1474
1646
  }
1475
1647
  async dropStore(e) {
1476
- U(e), await this.#s("readwrite", "dropStore", [e]);
1648
+ q(e), await this.#u("readwrite", "dropStore", [e]);
1477
1649
  }
1478
1650
  async clearStore(e) {
1479
- U(e), await this.#s("readwrite", "clearStore", [e]);
1651
+ q(e), await this.#u("readwrite", "clearStore", [e]);
1480
1652
  }
1481
1653
  async get(e, t) {
1482
- return U(e), this.#s("readonly", "get", [e, t]);
1654
+ return q(e), this.#u("readonly", "get", [e, t]);
1483
1655
  }
1484
1656
  async getMany(e, t) {
1485
- return U(e), this.#s("readonly", "getMany", [e, t]);
1657
+ return q(e), this.#u("readonly", "getMany", [e, t]);
1486
1658
  }
1487
1659
  async has(e, t) {
1488
- return U(e), this.#s("readonly", "has", [e, t]);
1660
+ return q(e), this.#u("readonly", "has", [e, t]);
1489
1661
  }
1490
1662
  async put(e, t, n, r = {}) {
1491
- U(e), await this.#s("readwrite", "put", [
1663
+ q(e), await this.#u("readwrite", "put", [
1492
1664
  e,
1493
1665
  t,
1494
1666
  n,
@@ -1496,54 +1668,54 @@ var vn = class {
1496
1668
  ]);
1497
1669
  }
1498
1670
  async delete(e, t) {
1499
- return U(e), this.#s("readwrite", "delete", [e, t]);
1671
+ return q(e), this.#u("readwrite", "delete", [e, t]);
1500
1672
  }
1501
1673
  async scan(e, t = {}) {
1502
- return U(e), this.#s("readonly", "scan", [e, t]);
1674
+ return q(e), this.#u("readonly", "scan", [e, t]);
1503
1675
  }
1504
- async #s(e, t, n) {
1505
- return this.#d(), J(() => this.#e.proxy.autocommit(e, t, n));
1676
+ async #u(e, t, n) {
1677
+ return this.#h(), Y(() => this.#e.proxy.autocommit(e, t, n));
1506
1678
  }
1507
1679
  async exportSnapshot(e = {}) {
1508
- return this.#d(), J(async () => {
1509
- let t = await this.#e.proxy.exportSnapshot(An(e));
1680
+ return this.#h(), Y(async () => {
1681
+ let t = await this.#e.proxy.exportSnapshot(zn(e));
1510
1682
  return t instanceof Uint8Array ? t : new Uint8Array(t);
1511
1683
  });
1512
1684
  }
1513
1685
  async importSnapshot(e) {
1514
- return this.#d(), J(() => {
1686
+ return this.#h(), I(this.#e), Y(() => {
1515
1687
  let t = e instanceof Uint8Array ? e : new Uint8Array(e);
1516
1688
  return this.#e.proxy.importSnapshot(t);
1517
1689
  });
1518
1690
  }
1519
1691
  async reset() {
1520
- return this.#d(), M(this.#e), J(() => this.#e.proxy.reset());
1692
+ return this.#h(), I(this.#e), Y(() => this.#e.proxy.reset());
1521
1693
  }
1522
1694
  async compact() {
1523
- return this.#d(), M(this.#e), J(() => this.#e.proxy.compact());
1695
+ return this.#h(), I(this.#e), Y(() => this.#e.proxy.compact());
1524
1696
  }
1525
1697
  async rebuild() {
1526
- return this.#d(), M(this.#e), J(() => this.#e.proxy.rebuild());
1698
+ return this.#h(), I(this.#e), Y(() => this.#e.proxy.rebuild());
1527
1699
  }
1528
1700
  async stats() {
1529
- return this.#d(), J(() => this.#e.proxy.stats());
1701
+ return this.#h(), Y(() => this.#e.proxy.stats());
1530
1702
  }
1531
1703
  async storageInfo() {
1532
- return this.#d(), J(() => this.#e.proxy.storageInfo());
1704
+ return this.#h(), Y(() => this.#e.proxy.storageInfo());
1533
1705
  }
1534
1706
  async requestPersistence() {
1535
- return this.#d(), J(() => this.#e.proxy.requestPersistence());
1707
+ return this.#h(), Y(() => this.#e.proxy.requestPersistence());
1536
1708
  }
1537
1709
  async destroy() {
1538
- return this.#d(), J(() => st(this.#e));
1710
+ return this.#h(), Y(() => ct(this.#e));
1539
1711
  }
1540
1712
  async setFailpoint(e) {
1541
- return this.#d(), J(() => this.#e.proxy.setFailpoint(e));
1713
+ return this.#h(), Y(() => this.#e.proxy.setFailpoint(e));
1542
1714
  }
1543
1715
  subscribe(e, t, n) {
1544
- if (this.#d(), typeof e == "function") return this.#r.subscribe(e);
1545
- if (typeof t == "function") return this.#r.subscribe(e, t);
1546
- if (t instanceof Uint8Array && typeof n == "function") return this.#r.subscribe(e, t, n);
1716
+ if (this.#h(), typeof e == "function") return this.#o.subscribe(e);
1717
+ if (typeof t == "function") return this.#o.subscribe(e, t);
1718
+ if (t instanceof Uint8Array && typeof n == "function") return this.#o.subscribe(e, t, n);
1547
1719
  throw TypeError("subscribe() expects one of: (callback), (storeName, callback), (storeName, keyPrefix, callback)");
1548
1720
  }
1549
1721
  watch(e, t, n) {
@@ -1552,34 +1724,37 @@ var vn = class {
1552
1724
  if (t instanceof Uint8Array && typeof n == "function") return this.subscribe(e, t, n);
1553
1725
  throw TypeError("watch() expects one of: (callback), (storeName, callback), (storeName, keyPrefix, callback)");
1554
1726
  }
1555
- async close() {
1556
- if (this.#t) return;
1557
- this.#t = !0, this.#c(), this.#r.close();
1558
- let e = null, t = Array.from(this.#n);
1727
+ close() {
1728
+ return this.#n === null ? this.#t ? Promise.resolve() : (this.#t = !0, this.#f(), this.#o.close(), this.#n = this.#d(), this.#n) : this.#n;
1729
+ }
1730
+ async #d() {
1731
+ await Promise.allSettled(Array.from(this.#i));
1732
+ let e = null, t = Array.from(this.#r);
1559
1733
  if (t.length > 0) {
1560
1734
  let n = await Promise.allSettled(t.map((e) => e.rollbackIfOpen()));
1561
- for (let t of n) t.status === "rejected" && e === null && (e = O(t.reason));
1735
+ for (let t of n) t.status === "rejected" && e === null && (e = A(t.reason));
1562
1736
  }
1563
1737
  try {
1564
- await ot(this.#e);
1738
+ await st(this.#e);
1565
1739
  } catch (e) {
1566
- throw O(e);
1740
+ throw A(e);
1567
1741
  }
1568
1742
  if (e) throw e;
1569
1743
  }
1570
- #c() {
1571
- this.#i?.(), this.#i = null, this.#a?.(), this.#a = null;
1744
+ #f() {
1745
+ this.#s?.(), this.#s = null, this.#c?.(), this.#c = null;
1572
1746
  }
1573
- #l() {
1574
- for (let e of Array.from(this.#n)) e.forceClose();
1747
+ #p() {
1748
+ this.#a += 1;
1749
+ for (let e of Array.from(this.#r)) e.forceClose();
1575
1750
  }
1576
- #u() {
1577
- this.#t || (this.#t = !0, this.#c(), this.#l(), this.#r.close());
1751
+ #m() {
1752
+ this.#t || (this.#t = !0, this.#f(), this.#p(), this.#o.close());
1578
1753
  }
1579
- #d() {
1580
- if (this.#t || this.#e.invalidated) throw new C();
1754
+ #h() {
1755
+ if (this.#t || this.#e.invalidated) throw new T();
1581
1756
  }
1582
- }, bn = class {
1757
+ }, On = class {
1583
1758
  #e = /* @__PURE__ */ new Set();
1584
1759
  #t = /* @__PURE__ */ new Set();
1585
1760
  recordCreate(e) {
@@ -1594,7 +1769,7 @@ var vn = class {
1594
1769
  for (let e of this.#t) n.delete(e);
1595
1770
  return Array.from(n).sort(t);
1596
1771
  }
1597
- }, xn = class {
1772
+ }, kn = class {
1598
1773
  #e;
1599
1774
  #t;
1600
1775
  constructor(e, t) {
@@ -1646,12 +1821,12 @@ var vn = class {
1646
1821
  await this.#e.clearStore(e);
1647
1822
  }
1648
1823
  commit() {
1649
- return Promise.reject(Y("transaction.commit"));
1824
+ return Promise.reject(X("transaction.commit"));
1650
1825
  }
1651
1826
  rollback() {
1652
- return Promise.reject(Y("transaction.rollback"));
1827
+ return Promise.reject(X("transaction.rollback"));
1653
1828
  }
1654
- }, Sn = class {
1829
+ }, An = class {
1655
1830
  #e;
1656
1831
  #t;
1657
1832
  #n;
@@ -1659,7 +1834,7 @@ var vn = class {
1659
1834
  this.#e = e, this.#t = t, this.#n = n;
1660
1835
  }
1661
1836
  begin(e = "readonly") {
1662
- return Promise.reject(Y("db.begin"));
1837
+ return Promise.reject(X("db.begin"));
1663
1838
  }
1664
1839
  async createStore(e, t = {}) {
1665
1840
  await this.#t.createStore(e, t);
@@ -1677,7 +1852,7 @@ var vn = class {
1677
1852
  return this.#e.getVersion();
1678
1853
  }
1679
1854
  changesSince(e, t = {}) {
1680
- return Promise.reject(Y("db.changesSince"));
1855
+ return Promise.reject(X("db.changesSince"));
1681
1856
  }
1682
1857
  async get(e, t) {
1683
1858
  return this.#t.get(e, t);
@@ -1698,19 +1873,19 @@ var vn = class {
1698
1873
  return this.#t.scan(e, t);
1699
1874
  }
1700
1875
  exportSnapshot(e = {}) {
1701
- return Promise.reject(Y("db.exportSnapshot"));
1876
+ return Promise.reject(X("db.exportSnapshot"));
1702
1877
  }
1703
1878
  importSnapshot(e) {
1704
- return Promise.reject(Y("db.importSnapshot"));
1879
+ return Promise.reject(X("db.importSnapshot"));
1705
1880
  }
1706
1881
  reset() {
1707
- return Promise.reject(Y("db.reset"));
1882
+ return Promise.reject(X("db.reset"));
1708
1883
  }
1709
1884
  compact() {
1710
- return Promise.reject(Y("db.compact"));
1885
+ return Promise.reject(X("db.compact"));
1711
1886
  }
1712
1887
  rebuild() {
1713
- return Promise.reject(Y("db.rebuild"));
1888
+ return Promise.reject(X("db.rebuild"));
1714
1889
  }
1715
1890
  async stats() {
1716
1891
  return this.#e.stats();
@@ -1722,135 +1897,141 @@ var vn = class {
1722
1897
  return this.#e.requestPersistence();
1723
1898
  }
1724
1899
  close() {
1725
- return Promise.reject(Y("db.close"));
1900
+ return Promise.reject(X("db.close"));
1726
1901
  }
1727
1902
  destroy() {
1728
- return Promise.reject(Y("db.destroy"));
1903
+ return Promise.reject(X("db.destroy"));
1729
1904
  }
1730
1905
  setFailpoint(e) {
1731
- return Promise.reject(Y("db.setFailpoint"));
1906
+ return Promise.reject(X("db.setFailpoint"));
1732
1907
  }
1733
1908
  subscribe(e, t, n) {
1734
- throw Y("db.subscribe");
1909
+ throw X("db.subscribe");
1735
1910
  }
1736
1911
  watch(e, t, n) {
1737
- throw Y("db.watch");
1912
+ throw X("db.watch");
1738
1913
  }
1739
1914
  };
1740
- function Y(e) {
1915
+ function X(e) {
1741
1916
  let t = /* @__PURE__ */ Error(`${e}() is not available inside openDB() migrations; use the provided migration transaction and wait for openDB() to resolve`);
1742
1917
  return t.name = "InvalidStateError", t;
1743
1918
  }
1744
- function X(e, t) {
1919
+ function jn(e, t) {
1745
1920
  if (typeof e != "string" || e.length === 0) throw TypeError(`${t}() database name must be a non-empty string`);
1746
1921
  return e;
1747
1922
  }
1748
- var Cn = (e) => TypeError(e), wn = (e) => new E(e);
1749
- function Z(e, t, n = Cn) {
1923
+ var Mn = (e) => TypeError(e), Nn = (e) => new O(e);
1924
+ function Z(e, t, n = Mn) {
1750
1925
  if (e === void 0) return {};
1751
1926
  if (typeof e != "object" || !e || Array.isArray(e)) throw n(t);
1752
1927
  return e;
1753
1928
  }
1754
- function Tn(e, t, n = Cn) {
1929
+ function Pn(e, t, n = Mn) {
1755
1930
  if (typeof e != "number" || !Number.isSafeInteger(e) || e < 0) throw n(t);
1756
1931
  return e;
1757
1932
  }
1758
1933
  function Q(e, t, n) {
1759
- return e === void 0 ? void 0 : Tn(e, t, n);
1934
+ return e === void 0 ? void 0 : Pn(e, t, n);
1760
1935
  }
1761
- function En(e) {
1762
- return Z(e, "open options must be an object", wn);
1936
+ function Fn(e) {
1937
+ return Z(e, "open options must be an object", Nn);
1763
1938
  }
1764
- function Dn(e) {
1765
- return Q(e, "version must be a non-negative safe integer", wn);
1939
+ function In(e) {
1940
+ return Q(e, "version must be a non-negative safe integer", Nn);
1766
1941
  }
1767
1942
  function $(e) {
1768
1943
  let { ttl: t } = Z(e, "put options must be an object"), n = Q(t, "ttl must be a non-negative safe integer");
1769
1944
  return n === void 0 ? {} : { ttl: n };
1770
1945
  }
1771
- function On(e, t) {
1946
+ function Ln(e, t) {
1772
1947
  let { compression: n } = Z(e, t);
1773
1948
  if (n === void 0) return {};
1774
1949
  if (n !== !1 && n !== "gzip" && n !== "deflate") throw TypeError("compression must be \"gzip\", \"deflate\", or false");
1775
1950
  return { compression: n };
1776
1951
  }
1777
- function kn(e) {
1778
- return On(e, "createStore options must be an object");
1952
+ function Rn(e) {
1953
+ return Ln(e, "createStore options must be an object");
1779
1954
  }
1780
- function An(e) {
1781
- return On(e, "exportSnapshot options must be an object");
1955
+ function zn(e) {
1956
+ return Ln(e, "exportSnapshot options must be an object");
1782
1957
  }
1783
- function jn(e) {
1784
- return Tn(e, "txid must be a non-negative safe integer");
1958
+ function Bn(e) {
1959
+ return Pn(e, "txid must be a non-negative safe integer");
1785
1960
  }
1786
- function Mn(e) {
1961
+ function Vn(e) {
1787
1962
  let { stores: t, limit: n } = Z(e, "change feed options must be an object"), r = {};
1788
1963
  if (t !== void 0) {
1789
1964
  if (!Array.isArray(t) || !t.every((e) => typeof e == "string")) throw TypeError("stores must be an array of strings");
1790
- for (let e of t) U(e);
1965
+ for (let e of t) q(e);
1791
1966
  r.stores = [...t];
1792
1967
  }
1793
1968
  let i = Q(n, "limit must be a non-negative safe integer");
1794
1969
  return i !== void 0 && (r.limit = i), r;
1795
1970
  }
1796
- function Nn(e) {
1971
+ function Hn(e) {
1797
1972
  if (e !== void 0) {
1798
- if (typeof e != "function") throw new E("migrate must be a function");
1973
+ if (typeof e != "function") throw new O("migrate must be a function");
1799
1974
  return e;
1800
1975
  }
1801
1976
  }
1802
- function Pn(e) {
1803
- if (e !== void 0) return W(e);
1977
+ function Un(e) {
1978
+ if (e !== void 0) return J(e);
1804
1979
  }
1805
- function Fn(e, t) {
1806
- return K(e) === K(t);
1980
+ function Wn(e, t) {
1981
+ return nn(e) === nn(t);
1807
1982
  }
1808
- async function In(e) {
1809
- return W(await e.proxy.getIndexes());
1983
+ async function Gn(e) {
1984
+ return J(await e.proxy.getIndexes());
1810
1985
  }
1811
- function Ln() {
1812
- if (!globalThis.isSecureContext) throw new y("moyodb requires a secure context (HTTPS)");
1813
- if (typeof globalThis.navigator.storage.getDirectory != "function") throw new y("navigator.storage.getDirectory is unavailable");
1814
- if (typeof globalThis.Worker != "function") throw new y("Worker is unavailable");
1815
- if (globalThis.BroadcastChannel === void 0) throw new y("BroadcastChannel is unavailable");
1986
+ function Kn() {
1987
+ if (!globalThis.isSecureContext) throw new x("moyodb requires a secure context (HTTPS)");
1988
+ if (typeof globalThis.navigator.storage.getDirectory != "function") throw new x("navigator.storage.getDirectory is unavailable");
1989
+ if (typeof globalThis.Worker != "function") throw new x("Worker is unavailable");
1990
+ if (globalThis.BroadcastChannel === void 0) throw new x("BroadcastChannel is unavailable");
1816
1991
  }
1817
- async function Rn(e) {
1992
+ async function qn(e) {
1818
1993
  let t = globalThis.navigator;
1819
1994
  (e.requestPersistence ?? !0) && typeof t.storage.persist == "function" && await n(t.storage.persist(), 1e3, !1);
1820
1995
  }
1821
- async function zn(e, t = {}) {
1822
- let n = X(e, "openDB"), r = En(t), i = Dn(r.version), a = Nn(r.migrate), o = Pn(r.indexes);
1823
- if (i === void 0 && a !== void 0) throw new E("migrate requires version");
1824
- if (i === void 0 && o !== void 0) throw new E("indexes requires version");
1825
- Ln(), await Rn(r);
1826
- let s = await at(n, r), c = new yn(s), l = !1;
1996
+ async function Jn(e, t = {}) {
1997
+ let n = jn(e, "openDB"), r = Fn(t), i = In(r.version), a = Hn(r.migrate), o = Un(r.indexes);
1998
+ if (i === void 0 && a !== void 0) throw new O("migrate requires version");
1999
+ if (i === void 0 && o !== void 0) throw new O("indexes requires version");
2000
+ Kn(), await qn(r);
2001
+ let s = await ot(n, r), c = new Dn(s);
1827
2002
  try {
1828
- if (i === void 0) return l = !0, c;
1829
- let [e, t] = await Promise.all([c.getVersion(), In(s)]);
1830
- if (i < e) throw new D(`cannot open database ${n} at schema version ${i}; current schema version is ${e}`);
2003
+ if (i === void 0) return c;
2004
+ let [e, t] = await Promise.all([c.getVersion(), Gn(s)]);
2005
+ if (i < e) throw new k(`cannot open database ${n} at schema version ${i}; current schema version is ${e}`);
1831
2006
  if (i === e) {
1832
- if (o !== void 0 && !Fn(o, t)) throw new D(`database ${n} is already at schema version ${e}, but the requested index catalog does not match the committed schema`);
1833
- return l = !0, c;
2007
+ if (o !== void 0 && !Wn(o, t)) throw new k(`database ${n} is already at schema version ${e}, but the requested index catalog does not match the committed schema`);
2008
+ return c;
1834
2009
  }
1835
- if (s.refs > 1) throw new b(`database ${n} is already open in this tab; close existing handles before migrating from version ${e} to ${i}`);
1836
- if (!a) throw new D(`database ${n} requires migration from version ${e} to ${i}, but no migrate hook was provided`);
2010
+ if (s.refs > 1) throw new S(`database ${n} is already open in this tab; close existing handles before migrating from version ${e} to ${i}`);
2011
+ if (!a) throw new k(`database ${n} requires migration from version ${e} to ${i}, but no migrate hook was provided`);
1837
2012
  let r = o ?? t;
1838
- return await c.runSchemaMigration(e, i, a, q(r)), l = !0, c;
2013
+ s.schemaMigrationInProgress = !0;
2014
+ try {
2015
+ await c.runSchemaMigration(e, i, a, an(r));
2016
+ } finally {
2017
+ s.schemaMigrationInProgress = !1;
2018
+ }
2019
+ return c;
1839
2020
  } catch (e) {
1840
- if (!l) try {
2021
+ try {
1841
2022
  await c.close();
1842
2023
  } catch {}
1843
- throw O(e);
2024
+ throw A(e);
1844
2025
  }
1845
2026
  }
1846
- async function Bn(e) {
1847
- let t = X(e, "deleteDB");
1848
- Ln(), await ct(t);
2027
+ async function Yn(e) {
2028
+ let t = jn(e, "deleteDB");
2029
+ Kn(), await ut(t);
1849
2030
  }
1850
- function Vn(e) {
1851
- return it(X(e, "unsafeDebugCrashWorker"));
2031
+ function Xn(e) {
2032
+ return at(jn(e, "unsafeDebugCrashWorker"));
1852
2033
  }
1853
2034
  //#endregion
1854
- export { je as ChangeFeedCompactedError, x as ConstraintError, ve as CorruptionError, b as DatabaseBusyError, C as DatabaseClosedError, Lt as INDEX_METADATA_STORE, xe as IndexNotFoundError, Ae as InjectedFailureError, Ne as InternalError, E as InvalidOpenOptionsError, Oe as InvalidRangeError, Ee as KeyTooLargeError, v as MoyoDbError, we as ReadonlyTransactionError, Me as RecoveryRequiredError, w as ReservedStoreNameError, T as SerializationError, ke as StorageError, ye as StoreExistsError, De as StoreNameTooLongError, be as StoreNotFoundError, S as TransactionClosedError, Se as UniqueIndexConstraintError, y as UnsupportedPlatformError, Te as ValueTooLargeError, D as VersionError, Ce as WriteTransactionAlreadyOpenError, U as assertPublicStoreName, Xt as cloneNormalizedIndexDefinitions, zt as compareNormalizedIndexDefinitions, L as compoundKey, Dt as compoundKeyRange, Kt as decodeIndexEntryKey, Wt as decodeIndexMetadataValue, Bn as deleteDB, R as encodeCompoundKeyParts, Gt as encodeIndexEntryKey, Ht as encodeIndexMetadataKey, Ut as encodeIndexMetadataValue, Tt as encodeIndexScalar, Yt as extractLogicalIndexKey, Bt as findIndexDefinition, G as indexDefinitionIdentity, wt as indexKey, qt as indexKeyExactRange, Jt as indexRangeToPhysicalRange, Vt as indexesForStore, Rt as isInternalStoreName, xt as jsonDecode, bt as jsonEncode, O as normalizeError, W as normalizeIndexDefinitions, zn as openDB, B as prefixRange, z as prefixSuccessor, K as serializeNormalizedIndexDefinitions, Et as splitCompoundKey, q as toPublicIndexDefinitions, St as u64Key, Vn as unsafeDebugCrashWorker, yt as utf8Decode, I as utf8Encode };
2035
+ export { Me as ChangeFeedCompactedError, C as ConstraintError, ye as CorruptionError, S as DatabaseBusyError, T as DatabaseClosedError, Bt as INDEX_METADATA_STORE, Se as IndexNotFoundError, je as InjectedFailureError, Pe as InternalError, O as InvalidOpenOptionsError, ke as InvalidRangeError, De as KeyTooLargeError, b as MoyoDbError, Te as ReadonlyTransactionError, Ne as RecoveryRequiredError, E as ReservedStoreNameError, D as SerializationError, Ae as StorageError, be as StoreExistsError, Oe as StoreNameTooLongError, xe as StoreNotFoundError, w as TransactionClosedError, Ce as UniqueIndexConstraintError, x as UnsupportedPlatformError, Ee as ValueTooLargeError, k as VersionError, we as WriteTransactionAlreadyOpenError, q as assertPublicStoreName, rn as cloneNormalizedIndexDefinitions, Ht as compareNormalizedIndexDefinitions, V as compoundKey, At as compoundKeyRange, en as createIndexKeyExtractor, Xt as decodeIndexEntryKey, Jt as decodeIndexMetadataValue, pn as decodeIndexedDocument, Yn as deleteDB, H as encodeCompoundKeyParts, Yt as encodeIndexEntryKey, Kt as encodeIndexMetadataKey, qt as encodeIndexMetadataValue, Ot as encodeIndexScalar, $t as extractLogicalIndexKey, tn as extractLogicalIndexKeyFromDocument, Wt as findIndexDefinition, Ut as indexDefinitionIdentity, Dt as indexKey, Zt as indexKeyExactRange, Qt as indexRangeToPhysicalRange, Gt as indexesForStore, Vt as isInternalStoreName, wt as jsonDecode, Ct as jsonEncode, A as normalizeError, J as normalizeIndexDefinitions, Jn as openDB, W as prefixRange, U as prefixSuccessor, nn as serializeNormalizedIndexDefinitions, kt as splitCompoundKey, an as toPublicIndexDefinitions, Tt as u64Key, Xn as unsafeDebugCrashWorker, St as utf8Decode, B as utf8Encode };
1855
2036
 
1856
2037
  //# sourceMappingURL=moyodb-sdk.js.map