@moyodb/sdk 1.0.0 → 1.1.0

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.
Files changed (76) hide show
  1. package/dist/LICENSE +202 -0
  2. package/dist/assets/browser-worker-DP6Mjz7c.js +4 -0
  3. package/dist/assets/browser-worker-DP6Mjz7c.js.map +1 -0
  4. package/dist/assets/shared-worker-DKzhauVf.js +2 -0
  5. package/dist/assets/shared-worker-DKzhauVf.js.map +1 -0
  6. package/dist/browser-worker.d.ts +2 -0
  7. package/dist/browser-worker.d.ts.map +1 -0
  8. package/dist/change-events.d.ts +1 -1
  9. package/dist/chunks/indexing-BzmFhWXs.js +1576 -0
  10. package/dist/chunks/indexing-BzmFhWXs.js.map +1 -0
  11. package/dist/codec.d.ts +1 -1
  12. package/dist/codec.d.ts.map +1 -1
  13. package/dist/compression.d.ts +1 -1
  14. package/dist/compression.d.ts.map +1 -1
  15. package/dist/demo.d.ts +2 -1
  16. package/dist/demo.d.ts.map +1 -1
  17. package/dist/engine/README.md +63 -16
  18. package/dist/engine/moyodb_engine.d.ts +29 -19
  19. package/dist/engine/moyodb_engine.js +78 -28
  20. package/dist/engine/moyodb_engine_bg.wasm +0 -0
  21. package/dist/engine/moyodb_engine_bg.wasm.d.ts +4 -2
  22. package/dist/engine/package.json +1 -1
  23. package/dist/engine/snippets/moyodb-engine-8ebe6af0cc2e81b7/js/opfs_shim.js +151 -62
  24. package/dist/errors.d.ts +6 -3
  25. package/dist/errors.d.ts.map +1 -1
  26. package/dist/index.d.ts +11 -5
  27. package/dist/index.d.ts.map +1 -1
  28. package/dist/indexing.d.ts +9 -1
  29. package/dist/indexing.d.ts.map +1 -1
  30. package/dist/moyodb-sdk.js +2253 -589
  31. package/dist/moyodb-sdk.js.map +1 -1
  32. package/dist/node-engine.js +2213 -0
  33. package/dist/node-engine.js.map +1 -0
  34. package/dist/node-storage.d.mts +12 -0
  35. package/dist/node-storage.mjs +634 -0
  36. package/dist/node-worker-client.d.ts +19 -0
  37. package/dist/node-worker-client.d.ts.map +1 -0
  38. package/dist/node-worker.mjs +118 -0
  39. package/dist/node.d.ts +19 -0
  40. package/dist/node.d.ts.map +1 -0
  41. package/dist/node.js +3194 -0
  42. package/dist/node.js.map +1 -0
  43. package/dist/records.d.ts +75 -0
  44. package/dist/records.d.ts.map +1 -0
  45. package/dist/registry.d.ts +13 -4
  46. package/dist/registry.d.ts.map +1 -1
  47. package/dist/shared-worker-client.d.ts +24 -0
  48. package/dist/shared-worker-client.d.ts.map +1 -0
  49. package/dist/shared-worker-protocol.d.ts +16 -0
  50. package/dist/shared-worker-protocol.d.ts.map +1 -0
  51. package/dist/shared-worker.d.ts +33 -0
  52. package/dist/shared-worker.d.ts.map +1 -0
  53. package/dist/sql-parser.d.ts +9 -0
  54. package/dist/sql-parser.d.ts.map +1 -0
  55. package/dist/sql-types.d.ts +82 -0
  56. package/dist/sql-types.d.ts.map +1 -0
  57. package/dist/sql.d.ts +32 -0
  58. package/dist/sql.d.ts.map +1 -0
  59. package/dist/subscriptions.d.ts +2 -2
  60. package/dist/subscriptions.d.ts.map +1 -1
  61. package/dist/types.d.ts +9 -6
  62. package/dist/types.d.ts.map +1 -1
  63. package/dist/worker-api.d.ts +5 -6
  64. package/dist/worker-api.d.ts.map +1 -1
  65. package/dist/worker-client.d.ts +32 -5
  66. package/dist/worker-client.d.ts.map +1 -1
  67. package/dist/worker-protocol.d.ts +36 -3
  68. package/dist/worker-protocol.d.ts.map +1 -1
  69. package/dist/worker-server.d.ts +10 -2
  70. package/dist/worker-server.d.ts.map +1 -1
  71. package/dist/worker.d.ts +263 -1
  72. package/dist/worker.d.ts.map +1 -1
  73. package/package.json +14 -5
  74. package/README.md +0 -59
  75. package/dist/assets/worker-R2dy1Ju5.js +0 -4
  76. package/dist/assets/worker-R2dy1Ju5.js.map +0 -1
@@ -0,0 +1,1576 @@
1
+ //#region src/internal.ts
2
+ function isRecord(value) {
3
+ return value !== null && typeof value === "object";
4
+ }
5
+ function compareStringsByCodeUnit(left, right) {
6
+ if (left < right) return -1;
7
+ return left > right ? 1 : 0;
8
+ }
9
+ var WORKER_PROTOCOL_READY = "moyodb:worker-protocol:ready";
10
+ var WORKER_PROTOCOL_REQUEST = "moyodb:worker-protocol:request";
11
+ var WORKER_PROTOCOL_RESPONSE = "moyodb:worker-protocol:response";
12
+ var WORKER_PROTOCOL_REQUEST_BATCH = "moyodb:worker-protocol:request-batch";
13
+ var WORKER_PROTOCOL_RESPONSE_BATCH = "moyodb:worker-protocol:response-batch";
14
+ var MAX_WORKER_BATCH_BYTES = 1048576;
15
+ var WORKER_COMMANDS = [
16
+ "open",
17
+ "close",
18
+ "destroy",
19
+ "deleteDB",
20
+ "begin",
21
+ "commit",
22
+ "rollback",
23
+ "autocommit",
24
+ "createStore",
25
+ "dropStore",
26
+ "clearStore",
27
+ "get",
28
+ "getMany",
29
+ "has",
30
+ "put",
31
+ "putMany",
32
+ "delete",
33
+ "deleteMany",
34
+ "applyBatch",
35
+ "scan",
36
+ "getByIndex",
37
+ "scanByIndex",
38
+ "scanByIndexPage",
39
+ "getIndexes",
40
+ "reconcileIndexes",
41
+ "listStores",
42
+ "getVersion",
43
+ "changesSince",
44
+ "setSchemaVersion",
45
+ "exportSnapshot",
46
+ "importSnapshot",
47
+ "reset",
48
+ "compact",
49
+ "rebuild",
50
+ "stats",
51
+ "storageInfo",
52
+ "requestPersistence",
53
+ "setFailpoint"
54
+ ];
55
+ var AUTOCOMMIT_COMMAND_SET = /* @__PURE__ */ new Set([
56
+ "get",
57
+ "getMany",
58
+ "has",
59
+ "put",
60
+ "putMany",
61
+ "delete",
62
+ "deleteMany",
63
+ "applyBatch",
64
+ "scan",
65
+ "getByIndex",
66
+ "scanByIndex",
67
+ "createStore",
68
+ "dropStore",
69
+ "clearStore"
70
+ ]);
71
+ function isAutocommitCommand(value) {
72
+ return typeof value === "string" && AUTOCOMMIT_COMMAND_SET.has(value);
73
+ }
74
+ var PACKED_BINARY_LIST_V1 = "moyodb:packed-binary-list:v1";
75
+ var PACKED_NULLABLE_BINARY_LIST_V1 = "moyodb:packed-nullable-binary-list:v1";
76
+ var PACKED_SCAN_ROWS_V1 = "moyodb:packed-scan-rows:v1";
77
+ var PACKED_BATCH_OPS_V1 = "moyodb:packed-batch-ops:v1";
78
+ var PACKED_OPTIONAL_VALUES_V1 = "moyodb:packed-optional-values:v1";
79
+ var BATCH_OP_DELETE = 0;
80
+ var BATCH_OP_PUT = 1;
81
+ var U32_MAX = 4294967295;
82
+ var MAX_PACKED_RESPONSE_BYTES = 16777216;
83
+ var EMPTY_TRANSFERABLES = [];
84
+ var WORKER_COMMAND_SET = new Set(WORKER_COMMANDS);
85
+ function isWorkerCommand(value) {
86
+ return typeof value === "string" && WORKER_COMMAND_SET.has(value);
87
+ }
88
+ function isWorkerProtocolReadyMessage(value) {
89
+ return isWorkerProtocolReadyEnvelope(value) && value.version === 1 && (value.batching === void 0 || value.batching === 1);
90
+ }
91
+ function isWorkerProtocolReadyEnvelope(value) {
92
+ return isRecord(value) && value.type === "moyodb:worker-protocol:ready";
93
+ }
94
+ function isWorkerProtocolResponseMessage(value) {
95
+ return isRecord(value) && value.type === "moyodb:worker-protocol:response" && value.version === 1 && typeof value.id === "number" && Number.isSafeInteger(value.id) && typeof value.ok === "boolean";
96
+ }
97
+ function isWorkerProtocolRequestMessage(value) {
98
+ return isRecord(value) && value.type === "moyodb:worker-protocol:request" && value.version === 1 && typeof value.id === "number" && Number.isSafeInteger(value.id) && typeof value.command === "string" && Array.isArray(value.args);
99
+ }
100
+ function isWorkerProtocolRequestBatchMessage(value) {
101
+ return isWorkerProtocolBatch(value, WORKER_PROTOCOL_REQUEST_BATCH, "requests");
102
+ }
103
+ function isWorkerProtocolResponseBatchMessage(value) {
104
+ if (!isWorkerProtocolBatch(value, "moyodb:worker-protocol:response-batch", "responses")) return false;
105
+ for (const response of value.responses) if (!isWorkerProtocolResponseMessage(response)) return false;
106
+ return true;
107
+ }
108
+ function isWorkerProtocolBatch(value, type, items) {
109
+ return isRecord(value) && value.type === type && value.version === 1 && Array.isArray(value[items]) && value[items].length > 0 && value[items].length <= 128;
110
+ }
111
+ function isWorkerProtocolEnvelope(value) {
112
+ return isRecord(value) && (value.type === "moyodb:worker-protocol:request" || value.type === "moyodb:worker-protocol:response" || value.type === "moyodb:worker-protocol:request-batch" || value.type === "moyodb:worker-protocol:response-batch" || value.type === "moyodb:worker-protocol:ready");
113
+ }
114
+ function serializeWorkerError(error) {
115
+ if (isRecord(error)) {
116
+ const code = stringOrUndefined(error.code);
117
+ return {
118
+ name: stringOrUndefined(error.name) ?? code ?? "Error",
119
+ code,
120
+ message: stringOrUndefined(error.message) ?? "Unknown error",
121
+ stack: stringOrUndefined(error.stack)
122
+ };
123
+ }
124
+ return {
125
+ name: "Error",
126
+ message: String(error)
127
+ };
128
+ }
129
+ function deserializeWorkerError(error) {
130
+ if (!isRecord(error) || typeof error.name !== "string" || typeof error.message !== "string" || error.code !== void 0 && typeof error.code !== "string" || error.stack !== void 0 && typeof error.stack !== "string") throw workerProtocolError("WorkerProtocolError", "invalid serialized worker error");
131
+ const deserialized = new Error(error.message);
132
+ deserialized.name = error.name || error.code || "Error";
133
+ if (error.stack) deserialized.stack = error.stack;
134
+ if (error.code) Object.defineProperty(deserialized, "code", {
135
+ value: error.code,
136
+ enumerable: true,
137
+ configurable: true
138
+ });
139
+ return deserialized;
140
+ }
141
+ function workerProtocolError(name, message, code = name) {
142
+ const error = new Error(message);
143
+ error.name = name;
144
+ Object.defineProperty(error, "code", {
145
+ value: code,
146
+ enumerable: true,
147
+ configurable: true
148
+ });
149
+ return error;
150
+ }
151
+ function prepareWorkerCommandPayload(command, args) {
152
+ if (command === "autocommit") {
153
+ const [mode, inner, innerArgs] = args;
154
+ if (isAutocommitCommand(inner) && Array.isArray(innerArgs)) {
155
+ const prepared = prepareWorkerCommandPayload(inner, [0, ...innerArgs]);
156
+ return {
157
+ args: [
158
+ mode,
159
+ inner,
160
+ prepared.args.slice(1)
161
+ ],
162
+ transfer: prepared.transfer
163
+ };
164
+ }
165
+ }
166
+ if (command === "get" || command === "has" || command === "delete" || command === "getByIndex" || command === "put") {
167
+ const keyIndex = command === "getByIndex" ? 3 : 2;
168
+ let copiedArgs = null;
169
+ let transfer = null;
170
+ for (let index = keyIndex; index <= (command === "put" ? 3 : keyIndex); index += 1) {
171
+ const value = args[index];
172
+ if (value instanceof Uint8Array && value.buffer instanceof ArrayBuffer && (value.byteOffset !== 0 || value.byteLength !== value.buffer.byteLength)) {
173
+ const owned = copyToOwnedUint8Array(value);
174
+ copiedArgs ??= [...args];
175
+ copiedArgs[index] = owned;
176
+ (transfer ??= []).push(owned.buffer);
177
+ }
178
+ }
179
+ if (copiedArgs !== null) return {
180
+ args: copiedArgs,
181
+ transfer: transfer ?? EMPTY_TRANSFERABLES
182
+ };
183
+ }
184
+ if (command === "importSnapshot") {
185
+ const data = args[0];
186
+ if (data instanceof Uint8Array) {
187
+ const owned = copyToOwnedUint8Array(data);
188
+ return {
189
+ args: [owned],
190
+ transfer: [owned.buffer]
191
+ };
192
+ }
193
+ }
194
+ if (command === "getMany" || command === "deleteMany") {
195
+ const [txId, store, keys] = args;
196
+ if (Array.isArray(keys) && keys.length > 0) {
197
+ const packed = packBinaryList(keys);
198
+ return {
199
+ args: [
200
+ txId,
201
+ store,
202
+ packed
203
+ ],
204
+ transfer: [packed.bytes.buffer]
205
+ };
206
+ }
207
+ }
208
+ if (command === "putMany") {
209
+ const [txId, store, entries, options] = args;
210
+ if (Array.isArray(entries) && entries.length > 0) {
211
+ const packed = packBinaryPairs(entries);
212
+ return {
213
+ args: [
214
+ txId,
215
+ store,
216
+ packed,
217
+ options
218
+ ],
219
+ transfer: [packed.bytes.buffer]
220
+ };
221
+ }
222
+ }
223
+ if (command === "applyBatch") {
224
+ const [txId, store, ops] = args;
225
+ if (Array.isArray(ops) && ops.length > 0) {
226
+ const packed = packBatchOps(ops);
227
+ return {
228
+ args: [
229
+ txId,
230
+ store,
231
+ packed
232
+ ],
233
+ transfer: [packed.bytes.buffer]
234
+ };
235
+ }
236
+ }
237
+ return {
238
+ args,
239
+ transfer: EMPTY_TRANSFERABLES
240
+ };
241
+ }
242
+ function decodeWorkerCommandPayload(command, args) {
243
+ if (command === "autocommit") {
244
+ const [mode, inner, innerArgs] = args;
245
+ if (isAutocommitCommand(inner) && Array.isArray(innerArgs)) return [
246
+ mode,
247
+ inner,
248
+ decodeWorkerCommandPayload(inner, [0, ...innerArgs]).slice(1)
249
+ ];
250
+ }
251
+ if (command === "getMany" || command === "deleteMany") {
252
+ const [txId, store, keys] = args;
253
+ if (!Array.isArray(keys)) {
254
+ if (!isPackedBinaryList(keys)) throw workerProtocolError("WorkerProtocolError", "invalid packed binary-list argument");
255
+ return [
256
+ txId,
257
+ store,
258
+ unpackBinaryList(keys)
259
+ ];
260
+ }
261
+ }
262
+ if (command === "putMany") {
263
+ const [txId, store, entries, options] = args;
264
+ if (!Array.isArray(entries)) {
265
+ if (!isPackedBinaryList(entries)) throw workerProtocolError("WorkerProtocolError", "invalid packed putMany argument");
266
+ return [
267
+ txId,
268
+ store,
269
+ unpackBinaryPairs(entries),
270
+ options
271
+ ];
272
+ }
273
+ }
274
+ if (command === "applyBatch") {
275
+ const [txId, store, ops] = args;
276
+ if (!Array.isArray(ops)) {
277
+ if (!isPackedBatchOps(ops)) throw workerProtocolError("WorkerProtocolError", "invalid packed batch argument");
278
+ return [
279
+ txId,
280
+ store,
281
+ unpackBatchOps(ops)
282
+ ];
283
+ }
284
+ }
285
+ return args;
286
+ }
287
+ function packedBinaryListBytes(value) {
288
+ return isPackedBinaryList(value) ? value.bytes : null;
289
+ }
290
+ function packedBatchOpsBytes(value) {
291
+ return isPackedBatchOps(value) ? value.bytes : null;
292
+ }
293
+ function unpackPackedBinaryList(bytes) {
294
+ return unpackBinaryList({
295
+ __moyodbPacked: PACKED_BINARY_LIST_V1,
296
+ bytes
297
+ });
298
+ }
299
+ function unpackPackedBinaryPairs(bytes) {
300
+ return unpackBinaryPairs({
301
+ __moyodbPacked: PACKED_BINARY_LIST_V1,
302
+ bytes
303
+ });
304
+ }
305
+ function unpackPackedBinaryPairKeys(bytes) {
306
+ return unpackBinaryPairKeys({
307
+ __moyodbPacked: PACKED_BINARY_LIST_V1,
308
+ bytes
309
+ });
310
+ }
311
+ function unpackPackedBatchOps(bytes) {
312
+ return unpackBatchOps({
313
+ __moyodbPacked: PACKED_BATCH_OPS_V1,
314
+ bytes
315
+ });
316
+ }
317
+ function unpackPackedBatchOpKeys(bytes) {
318
+ return unpackBatchOpKeys({
319
+ __moyodbPacked: PACKED_BATCH_OPS_V1,
320
+ bytes
321
+ });
322
+ }
323
+ function packedOptionalValues(bytes) {
324
+ return {
325
+ __moyodbPacked: PACKED_OPTIONAL_VALUES_V1,
326
+ bytes
327
+ };
328
+ }
329
+ function unpackPackedOptionalValues(bytes) {
330
+ if (!(bytes instanceof Uint8Array) || bytes.byteLength < 4) throw workerProtocolError("WorkerProtocolError", "invalid packed optional-values payload");
331
+ const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
332
+ const count = view.getUint32(0, true);
333
+ const payloadOffset = checkedAdd(4, checkedByteCount(count, 4, "packed optional-values metadata"), "packed optional-values header");
334
+ if (payloadOffset > bytes.byteLength) throw workerProtocolError("WorkerProtocolError", "packed optional-values metadata exceeds payload length");
335
+ const items = new Array(count);
336
+ let readOffset = payloadOffset;
337
+ for (let index = 0; index < count; index += 1) {
338
+ const byteLength = view.getUint32(4 + index * 4, true);
339
+ if (byteLength === U32_MAX) {
340
+ items[index] = null;
341
+ continue;
342
+ }
343
+ const end = readOffset + byteLength;
344
+ if (end > bytes.byteLength) throw workerProtocolError("WorkerProtocolError", "packed optional-values item exceeds payload length");
345
+ items[index] = bytes.subarray(readOffset, end);
346
+ readOffset = end;
347
+ }
348
+ if (readOffset !== bytes.byteLength) throw workerProtocolError("WorkerProtocolError", "packed optional-values payload has trailing bytes");
349
+ return items;
350
+ }
351
+ function prepareWorkerResponsePayload(command, result) {
352
+ if (command === "getMany" && isPackedOptionalValues(result)) return {
353
+ result,
354
+ transfer: collectDirectBinaryTransferable(result.bytes)
355
+ };
356
+ if (command === "scanByIndexPage") {
357
+ const page = result;
358
+ if (isRecord(page) && Array.isArray(page.rows)) {
359
+ const packed = page.rows.length > 0 ? packScanRows(page.rows) : null;
360
+ const response = {
361
+ rows: packed ?? page.rows,
362
+ cursor: page.cursor
363
+ };
364
+ const transfer = packed ? [packed.bytes.buffer] : collectTransferablesForValue(page.rows);
365
+ const cursorBuffer = directBinaryTransferable(page.cursor);
366
+ return {
367
+ result: response,
368
+ transfer: cursorBuffer === null ? transfer : [...transfer, cursorBuffer]
369
+ };
370
+ }
371
+ }
372
+ if (command === "getMany") {
373
+ const values = result;
374
+ if (Array.isArray(values) && values.length > 0) {
375
+ const packed = packNullableBinaryList(values);
376
+ if (packed) return {
377
+ result: packed,
378
+ transfer: [packed.bytes.buffer]
379
+ };
380
+ }
381
+ return {
382
+ result,
383
+ transfer: collectTransferablesForValue(result)
384
+ };
385
+ }
386
+ if (command === "scan" || command === "scanByIndex") {
387
+ const rows = result;
388
+ if (Array.isArray(rows) && rows.length > 0) {
389
+ const packed = packScanRows(rows);
390
+ if (packed) return {
391
+ result: packed,
392
+ transfer: [packed.bytes.buffer]
393
+ };
394
+ }
395
+ return {
396
+ result,
397
+ transfer: collectTransferablesForValue(result)
398
+ };
399
+ }
400
+ if (command === "get" || command === "getByIndex" || command === "exportSnapshot") return {
401
+ result,
402
+ transfer: collectDirectBinaryTransferable(result)
403
+ };
404
+ if (command === "changesSince") return {
405
+ result,
406
+ transfer: collectChangeFeedTransferables(result)
407
+ };
408
+ return {
409
+ result,
410
+ transfer: []
411
+ };
412
+ }
413
+ function decodeWorkerResponsePayload(command, result) {
414
+ if (command === "getMany" && isPackedNullableBinaryList(result)) return unpackNullableBinaryList(result);
415
+ if (command === "getMany" && isPackedOptionalValues(result)) return unpackPackedOptionalValues(result.bytes);
416
+ if (command === "getMany" && !Array.isArray(result)) throw workerProtocolError("WorkerProtocolError", "invalid packed getMany response");
417
+ if (command === "scanByIndexPage") {
418
+ if (!isRecord(result) || !Array.isArray(result.rows) && !isPackedScanRows(result.rows) || result.cursor !== null && !(result.cursor instanceof Uint8Array)) throw workerProtocolError("WorkerProtocolError", "invalid packed index scan page response");
419
+ return {
420
+ rows: isPackedScanRows(result.rows) ? unpackScanRows(result.rows) : result.rows,
421
+ cursor: result.cursor
422
+ };
423
+ }
424
+ if ((command === "scan" || command === "scanByIndex") && isPackedScanRows(result)) return unpackScanRows(result);
425
+ if ((command === "scan" || command === "scanByIndex") && !Array.isArray(result)) throw workerProtocolError("WorkerProtocolError", "invalid packed scan response");
426
+ return result;
427
+ }
428
+ function collectTransferablesForValue(value) {
429
+ const direct = directBinaryTransferable(value);
430
+ if (direct !== null) return [direct];
431
+ if (value === null || value === void 0 || typeof value !== "object") return EMPTY_TRANSFERABLES;
432
+ const buffers = /* @__PURE__ */ new Set();
433
+ collectTransferableBuffers(value, buffers, /* @__PURE__ */ new WeakSet());
434
+ return buffers.size === 0 ? EMPTY_TRANSFERABLES : Array.from(buffers);
435
+ }
436
+ /**
437
+ * Capture the message before batching can observe later mutations. Listed
438
+ * transferables move into the snapshot; other ArrayBuffers are cloned.
439
+ * SharedArrayBuffers remain shared. byteLength is a batch-size estimate.
440
+ */
441
+ function captureWorkerPayload(value, transfer) {
442
+ const captured = transfer.length > 0 ? structuredClone(value, { transfer: transfer.length === 1 ? transfer : Array.from(new Set(transfer)) }) : structuredClone(value);
443
+ const buffers = /* @__PURE__ */ new Set();
444
+ const seen = /* @__PURE__ */ new WeakSet();
445
+ let byteLength = 0;
446
+ const visit = (item) => {
447
+ if (typeof item === "string") {
448
+ byteLength += 8 + item.length * 2;
449
+ return;
450
+ }
451
+ if (item === null || typeof item !== "object") {
452
+ byteLength += 8;
453
+ return;
454
+ }
455
+ if (seen.has(item)) return;
456
+ seen.add(item);
457
+ byteLength += 8;
458
+ if (item instanceof ArrayBuffer) {
459
+ buffers.add(item);
460
+ byteLength += item.byteLength;
461
+ } else if (typeof SharedArrayBuffer !== "undefined" && item instanceof SharedArrayBuffer) byteLength += item.byteLength;
462
+ else if (ArrayBuffer.isView(item)) visit(item.buffer);
463
+ else if (Array.isArray(item)) for (const child of item) visit(child);
464
+ else if (item instanceof Map) for (const [key, child] of item) {
465
+ visit(key);
466
+ visit(child);
467
+ }
468
+ else if (item instanceof Set) for (const child of item) visit(child);
469
+ else {
470
+ const record = item;
471
+ for (const key in record) if (Object.prototype.hasOwnProperty.call(record, key)) {
472
+ byteLength += 8 + key.length * 2;
473
+ visit(record[key]);
474
+ }
475
+ }
476
+ };
477
+ visit(captured);
478
+ return {
479
+ value: captured,
480
+ transfer: buffers.size === 0 ? EMPTY_TRANSFERABLES : Array.from(buffers),
481
+ byteLength
482
+ };
483
+ }
484
+ function collectDirectBinaryTransferable(value) {
485
+ const direct = directBinaryTransferable(value);
486
+ return direct === null ? EMPTY_TRANSFERABLES : [direct];
487
+ }
488
+ function directBinaryTransferable(value) {
489
+ if (value instanceof ArrayBuffer) return value;
490
+ if (ArrayBuffer.isView(value)) {
491
+ const buffer = value.buffer;
492
+ if (buffer instanceof ArrayBuffer && value.byteOffset === 0 && value.byteLength === buffer.byteLength) return buffer;
493
+ }
494
+ return null;
495
+ }
496
+ function collectChangeFeedTransferables(value) {
497
+ if (!isRecord(value) || !Array.isArray(value.changes) || value.changes.length === 0) return EMPTY_TRANSFERABLES;
498
+ let buffers = null;
499
+ for (const change of value.changes) {
500
+ if (!isRecord(change)) continue;
501
+ const key = directBinaryTransferable(change.key);
502
+ if (key !== null) {
503
+ buffers ??= /* @__PURE__ */ new Set();
504
+ buffers.add(key);
505
+ }
506
+ const changedValue = directBinaryTransferable(change.value);
507
+ if (changedValue !== null) {
508
+ buffers ??= /* @__PURE__ */ new Set();
509
+ buffers.add(changedValue);
510
+ }
511
+ }
512
+ return buffers === null || buffers.size === 0 ? EMPTY_TRANSFERABLES : Array.from(buffers);
513
+ }
514
+ function collectTransferableBuffers(value, buffers, seen) {
515
+ if (value === null || value === void 0) return;
516
+ if (value instanceof ArrayBuffer) {
517
+ buffers.add(value);
518
+ return;
519
+ }
520
+ if (ArrayBuffer.isView(value)) {
521
+ const buffer = value.buffer;
522
+ if (buffer instanceof ArrayBuffer && value.byteOffset === 0 && value.byteLength === buffer.byteLength) buffers.add(buffer);
523
+ return;
524
+ }
525
+ if (typeof value !== "object") return;
526
+ const object = value;
527
+ if (seen.has(object)) return;
528
+ seen.add(object);
529
+ if (Array.isArray(value)) {
530
+ for (const item of value) collectTransferableBuffers(item, buffers, seen);
531
+ return;
532
+ }
533
+ const record = value;
534
+ for (const key in record) if (Object.prototype.hasOwnProperty.call(record, key)) collectTransferableBuffers(record[key], buffers, seen);
535
+ }
536
+ function packBinaryPairs(entries) {
537
+ const entryCount = entries.length;
538
+ const count = checkedU32(entryCount * 2, "packed putMany item count");
539
+ const metadataBytes = checkedByteCount(count, 4, "packed putMany metadata");
540
+ let payloadBytes = 0;
541
+ for (let index = 0; index < entryCount; index += 1) {
542
+ const entry = entries[index];
543
+ const key = entry[0];
544
+ const value = entry[1];
545
+ if (!(key instanceof Uint8Array) || !(value instanceof Uint8Array)) throw workerProtocolError("WorkerProtocolError", "putMany entry key/value is not a Uint8Array");
546
+ const keyLength = checkedU32(key.byteLength, "putMany key length");
547
+ const valueLength = checkedU32(value.byteLength, "putMany value length");
548
+ payloadBytes += keyLength + valueLength;
549
+ if (payloadBytes > U32_MAX) throw workerProtocolError("WorkerProtocolError", "packed putMany payload exceeds 32-bit payload limit");
550
+ }
551
+ const payloadOffset = checkedAdd(4, metadataBytes, "packed putMany header");
552
+ const totalBytes = checkedAdd(payloadOffset, payloadBytes, "packed putMany total");
553
+ const bytes = new Uint8Array(totalBytes);
554
+ const view = new DataView(bytes.buffer);
555
+ view.setUint32(0, count, true);
556
+ let metadataOffset = 4;
557
+ let writeOffset = payloadOffset;
558
+ for (let index = 0; index < entryCount; index += 1) {
559
+ const entry = entries[index];
560
+ const key = entry[0];
561
+ const value = entry[1];
562
+ const keyLength = key.byteLength;
563
+ const valueLength = value.byteLength;
564
+ view.setUint32(metadataOffset, keyLength, true);
565
+ metadataOffset += 4;
566
+ view.setUint32(metadataOffset, valueLength, true);
567
+ metadataOffset += 4;
568
+ bytes.set(key, writeOffset);
569
+ writeOffset += keyLength;
570
+ bytes.set(value, writeOffset);
571
+ writeOffset += valueLength;
572
+ }
573
+ return {
574
+ __moyodbPacked: PACKED_BINARY_LIST_V1,
575
+ bytes
576
+ };
577
+ }
578
+ function packBinaryList(items) {
579
+ const count = items.length;
580
+ const metadataBytes = checkedByteCount(count, 4, "packed binary-list metadata");
581
+ let payloadBytes = 0;
582
+ for (let index = 0; index < count; index += 1) {
583
+ const item = items[index];
584
+ if (!(item instanceof Uint8Array)) throw workerProtocolError("WorkerProtocolError", "binary-list payload item is not a Uint8Array");
585
+ const itemLength = checkedU32(item.byteLength, "binary-list item length");
586
+ payloadBytes += itemLength;
587
+ if (payloadBytes > U32_MAX) throw workerProtocolError("WorkerProtocolError", "packed binary-list payload exceeds 32-bit payload limit");
588
+ }
589
+ const payloadOffset = checkedAdd(4, metadataBytes, "packed binary-list header");
590
+ const totalBytes = checkedAdd(payloadOffset, payloadBytes, "packed binary-list total");
591
+ const bytes = new Uint8Array(totalBytes);
592
+ const view = new DataView(bytes.buffer);
593
+ view.setUint32(0, count, true);
594
+ let metadataOffset = 4;
595
+ let writeOffset = payloadOffset;
596
+ for (let index = 0; index < count; index += 1) {
597
+ const item = items[index];
598
+ const itemLength = item.byteLength;
599
+ view.setUint32(metadataOffset, itemLength, true);
600
+ metadataOffset += 4;
601
+ bytes.set(item, writeOffset);
602
+ writeOffset += itemLength;
603
+ }
604
+ return {
605
+ __moyodbPacked: PACKED_BINARY_LIST_V1,
606
+ bytes
607
+ };
608
+ }
609
+ function unpackBinaryList(payload) {
610
+ const bytes = payload.bytes;
611
+ if (!(bytes instanceof Uint8Array) || bytes.byteLength < 4) throw workerProtocolError("WorkerProtocolError", "invalid packed binary-list payload");
612
+ const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
613
+ const count = view.getUint32(0, true);
614
+ const payloadOffset = checkedAdd(4, checkedByteCount(count, 4, "packed binary-list metadata"), "packed binary-list header");
615
+ if (payloadOffset > bytes.byteLength) throw workerProtocolError("WorkerProtocolError", "packed binary-list metadata exceeds payload length");
616
+ const items = new Array(count);
617
+ let metadataOffset = 4;
618
+ let readOffset = payloadOffset;
619
+ for (let index = 0; index < count; index += 1) {
620
+ const byteLength = view.getUint32(metadataOffset, true);
621
+ metadataOffset += 4;
622
+ const end = readOffset + byteLength;
623
+ if (end > U32_MAX || end > bytes.byteLength) throw workerProtocolError("WorkerProtocolError", "packed binary-list item exceeds payload length");
624
+ items[index] = bytes.subarray(readOffset, end);
625
+ readOffset = end;
626
+ }
627
+ if (readOffset !== bytes.byteLength) throw workerProtocolError("WorkerProtocolError", "packed binary-list payload has trailing bytes");
628
+ return items;
629
+ }
630
+ function unpackBinaryPairs(payload) {
631
+ const bytes = payload.bytes;
632
+ if (!(bytes instanceof Uint8Array) || bytes.byteLength < 4) throw workerProtocolError("WorkerProtocolError", "invalid packed putMany payload");
633
+ const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
634
+ const itemCount = view.getUint32(0, true);
635
+ if (itemCount % 2 !== 0) throw workerProtocolError("WorkerProtocolError", "packed putMany payload has an odd item count");
636
+ const payloadOffset = checkedAdd(4, checkedByteCount(itemCount, 4, "packed putMany metadata"), "packed putMany header");
637
+ if (payloadOffset > bytes.byteLength) throw workerProtocolError("WorkerProtocolError", "packed putMany metadata exceeds payload length");
638
+ const entryCount = itemCount / 2;
639
+ const entries = new Array(entryCount);
640
+ let metadataOffset = 4;
641
+ let readOffset = payloadOffset;
642
+ for (let index = 0; index < entryCount; index += 1) {
643
+ const keyLength = view.getUint32(metadataOffset, true);
644
+ const valueLength = view.getUint32(metadataOffset + 4, true);
645
+ metadataOffset += 8;
646
+ const keyEnd = readOffset + keyLength;
647
+ if (keyEnd > U32_MAX || keyEnd > bytes.byteLength) throw workerProtocolError("WorkerProtocolError", "packed putMany key exceeds payload length");
648
+ const valueEnd = keyEnd + valueLength;
649
+ if (valueEnd > U32_MAX || valueEnd > bytes.byteLength) throw workerProtocolError("WorkerProtocolError", "packed putMany value exceeds payload length");
650
+ entries[index] = [bytes.subarray(readOffset, keyEnd), bytes.subarray(keyEnd, valueEnd)];
651
+ readOffset = valueEnd;
652
+ }
653
+ if (readOffset !== bytes.byteLength) throw workerProtocolError("WorkerProtocolError", "packed putMany payload has trailing bytes");
654
+ return entries;
655
+ }
656
+ function unpackBinaryPairKeys(payload) {
657
+ const bytes = payload.bytes;
658
+ if (!(bytes instanceof Uint8Array) || bytes.byteLength < 4) throw workerProtocolError("WorkerProtocolError", "invalid packed putMany payload");
659
+ const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
660
+ const itemCount = view.getUint32(0, true);
661
+ if (itemCount % 2 !== 0) throw workerProtocolError("WorkerProtocolError", "packed putMany payload has an odd item count");
662
+ const payloadOffset = checkedAdd(4, checkedByteCount(itemCount, 4, "packed putMany metadata"), "packed putMany header");
663
+ if (payloadOffset > bytes.byteLength) throw workerProtocolError("WorkerProtocolError", "packed putMany metadata exceeds payload length");
664
+ const entryCount = itemCount / 2;
665
+ const keys = new Array(entryCount);
666
+ let metadataOffset = 4;
667
+ let readOffset = payloadOffset;
668
+ for (let index = 0; index < entryCount; index += 1) {
669
+ const keyLength = view.getUint32(metadataOffset, true);
670
+ const valueLength = view.getUint32(metadataOffset + 4, true);
671
+ metadataOffset += 8;
672
+ const keyEnd = readOffset + keyLength;
673
+ if (keyEnd > U32_MAX || keyEnd > bytes.byteLength) throw workerProtocolError("WorkerProtocolError", "packed putMany key exceeds payload length");
674
+ const valueEnd = keyEnd + valueLength;
675
+ if (valueEnd > U32_MAX || valueEnd > bytes.byteLength) throw workerProtocolError("WorkerProtocolError", "packed putMany value exceeds payload length");
676
+ keys[index] = bytes.subarray(readOffset, keyEnd);
677
+ readOffset = valueEnd;
678
+ }
679
+ if (readOffset !== bytes.byteLength) throw workerProtocolError("WorkerProtocolError", "packed putMany payload has trailing bytes");
680
+ return keys;
681
+ }
682
+ function packNullableBinaryList(items) {
683
+ const count = items.length;
684
+ const metadataBytes = checkedByteCount(count, 5, "packed nullable binary-list metadata");
685
+ let payloadBytes = 0;
686
+ for (let index = 0; index < count; index += 1) {
687
+ const item = items[index];
688
+ if (item === null) continue;
689
+ if (!(item instanceof Uint8Array)) throw workerProtocolError("WorkerProtocolError", "nullable binary-list payload item is not a Uint8Array or null");
690
+ const itemLength = checkedU32(item.byteLength, "nullable binary-list item length");
691
+ payloadBytes += itemLength;
692
+ if (payloadBytes > U32_MAX) throw workerProtocolError("WorkerProtocolError", "packed nullable binary-list payload exceeds 32-bit payload limit");
693
+ }
694
+ const payloadOffset = checkedAdd(4, metadataBytes, "packed nullable binary-list header");
695
+ const totalBytes = checkedAdd(payloadOffset, payloadBytes, "packed nullable binary-list total");
696
+ if (totalBytes > MAX_PACKED_RESPONSE_BYTES) return null;
697
+ const bytes = new Uint8Array(totalBytes);
698
+ const view = new DataView(bytes.buffer);
699
+ view.setUint32(0, count, true);
700
+ let metadataOffset = 4;
701
+ let writeOffset = payloadOffset;
702
+ for (let index = 0; index < count; index += 1) {
703
+ const item = items[index];
704
+ if (item === null) {
705
+ view.setUint8(metadataOffset, 0);
706
+ view.setUint32(metadataOffset + 1, 0, true);
707
+ metadataOffset += 5;
708
+ continue;
709
+ }
710
+ const itemLength = item.byteLength;
711
+ view.setUint8(metadataOffset, 1);
712
+ view.setUint32(metadataOffset + 1, itemLength, true);
713
+ metadataOffset += 5;
714
+ bytes.set(item, writeOffset);
715
+ writeOffset += itemLength;
716
+ }
717
+ return {
718
+ __moyodbPacked: PACKED_NULLABLE_BINARY_LIST_V1,
719
+ bytes
720
+ };
721
+ }
722
+ function unpackNullableBinaryList(payload) {
723
+ const bytes = payload.bytes;
724
+ if (!(bytes instanceof Uint8Array) || bytes.byteLength < 4) throw workerProtocolError("WorkerProtocolError", "invalid packed nullable binary-list payload");
725
+ const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
726
+ const count = view.getUint32(0, true);
727
+ const payloadOffset = checkedAdd(4, checkedByteCount(count, 5, "packed nullable binary-list metadata"), "packed nullable binary-list header");
728
+ if (payloadOffset > bytes.byteLength) throw workerProtocolError("WorkerProtocolError", "packed nullable binary-list metadata exceeds payload length");
729
+ const items = new Array(count);
730
+ let metadataOffset = 4;
731
+ let readOffset = payloadOffset;
732
+ for (let index = 0; index < count; index += 1) {
733
+ const present = view.getUint8(metadataOffset);
734
+ const byteLength = view.getUint32(metadataOffset + 1, true);
735
+ metadataOffset += 5;
736
+ if (present === 0) {
737
+ if (byteLength !== 0) throw workerProtocolError("WorkerProtocolError", "packed nullable binary-list null item has a payload length");
738
+ items[index] = null;
739
+ continue;
740
+ }
741
+ if (present !== 1) throw workerProtocolError("WorkerProtocolError", `packed nullable binary-list item has invalid presence byte: ${present}`);
742
+ const end = readOffset + byteLength;
743
+ if (end > U32_MAX || end > bytes.byteLength) throw workerProtocolError("WorkerProtocolError", "packed nullable binary-list item exceeds payload length");
744
+ items[index] = bytes.subarray(readOffset, end);
745
+ readOffset = end;
746
+ }
747
+ if (readOffset !== bytes.byteLength) throw workerProtocolError("WorkerProtocolError", "packed nullable binary-list payload has trailing bytes");
748
+ return items;
749
+ }
750
+ function packScanRows(rows) {
751
+ const count = rows.length;
752
+ const metadataBytes = checkedByteCount(count, 8, "packed scan row metadata");
753
+ let payloadBytes = 0;
754
+ for (let index = 0; index < count; index += 1) {
755
+ const row = rows[index];
756
+ if (!isRecord(row) || !(row.key instanceof Uint8Array) || !(row.value instanceof Uint8Array)) throw workerProtocolError("WorkerProtocolError", "scan row payload key/value is not a Uint8Array");
757
+ const keyLength = checkedU32(row.key.byteLength, "scan row key length");
758
+ const valueLength = checkedU32(row.value.byteLength, "scan row value length");
759
+ payloadBytes += keyLength + valueLength;
760
+ if (payloadBytes > U32_MAX) throw workerProtocolError("WorkerProtocolError", "packed scan row payload exceeds 32-bit payload limit");
761
+ }
762
+ const payloadOffset = checkedAdd(4, metadataBytes, "packed scan row header");
763
+ const totalBytes = checkedAdd(payloadOffset, payloadBytes, "packed scan row total");
764
+ if (totalBytes > MAX_PACKED_RESPONSE_BYTES) return null;
765
+ const bytes = new Uint8Array(totalBytes);
766
+ const view = new DataView(bytes.buffer);
767
+ view.setUint32(0, count, true);
768
+ let metadataOffset = 4;
769
+ let writeOffset = payloadOffset;
770
+ for (let index = 0; index < count; index += 1) {
771
+ const row = rows[index];
772
+ const key = row.key;
773
+ const value = row.value;
774
+ const keyLength = key.byteLength;
775
+ const valueLength = value.byteLength;
776
+ view.setUint32(metadataOffset, keyLength, true);
777
+ view.setUint32(metadataOffset + 4, valueLength, true);
778
+ metadataOffset += 8;
779
+ bytes.set(key, writeOffset);
780
+ writeOffset += keyLength;
781
+ bytes.set(value, writeOffset);
782
+ writeOffset += valueLength;
783
+ }
784
+ return {
785
+ __moyodbPacked: PACKED_SCAN_ROWS_V1,
786
+ bytes
787
+ };
788
+ }
789
+ function unpackScanRows(payload) {
790
+ const bytes = payload.bytes;
791
+ if (!(bytes instanceof Uint8Array) || bytes.byteLength < 4) throw workerProtocolError("WorkerProtocolError", "invalid packed scan row payload");
792
+ const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
793
+ const count = view.getUint32(0, true);
794
+ const payloadOffset = checkedAdd(4, checkedByteCount(count, 8, "packed scan row metadata"), "packed scan row header");
795
+ if (payloadOffset > bytes.byteLength) throw workerProtocolError("WorkerProtocolError", "packed scan row metadata exceeds payload length");
796
+ const rows = new Array(count);
797
+ let metadataOffset = 4;
798
+ let readOffset = payloadOffset;
799
+ for (let index = 0; index < count; index += 1) {
800
+ const keyLength = view.getUint32(metadataOffset, true);
801
+ const valueLength = view.getUint32(metadataOffset + 4, true);
802
+ metadataOffset += 8;
803
+ const keyEnd = readOffset + keyLength;
804
+ if (keyEnd > U32_MAX || keyEnd > bytes.byteLength) throw workerProtocolError("WorkerProtocolError", "packed scan row key exceeds payload length");
805
+ const valueEnd = keyEnd + valueLength;
806
+ if (valueEnd > U32_MAX || valueEnd > bytes.byteLength) throw workerProtocolError("WorkerProtocolError", "packed scan row value exceeds payload length");
807
+ rows[index] = {
808
+ key: bytes.subarray(readOffset, keyEnd),
809
+ value: bytes.subarray(keyEnd, valueEnd)
810
+ };
811
+ readOffset = valueEnd;
812
+ }
813
+ if (readOffset !== bytes.byteLength) throw workerProtocolError("WorkerProtocolError", "packed scan row payload has trailing bytes");
814
+ return rows;
815
+ }
816
+ function packBatchOps(ops) {
817
+ const count = ops.length;
818
+ const metadataBytes = checkedByteCount(count, 9, "packed batch metadata");
819
+ let payloadBytes = 0;
820
+ for (let index = 0; index < count; index += 1) {
821
+ const op = ops[index];
822
+ if (!isRecord(op) || op.kind !== "put" && op.kind !== "delete") throw workerProtocolError("WorkerProtocolError", "batch operation kind is not put or delete");
823
+ if (!(op.key instanceof Uint8Array)) throw workerProtocolError("WorkerProtocolError", "batch operation key is not a Uint8Array");
824
+ const keyLength = checkedU32(op.key.byteLength, "batch operation key length");
825
+ payloadBytes += keyLength;
826
+ if (payloadBytes > U32_MAX) throw workerProtocolError("WorkerProtocolError", "packed batch payload exceeds 32-bit payload limit");
827
+ if (op.kind === "put") {
828
+ if (!(op.value instanceof Uint8Array)) throw workerProtocolError("WorkerProtocolError", "batch put value is not a Uint8Array");
829
+ const valueLength = checkedU32(op.value.byteLength, "batch put value length");
830
+ payloadBytes += valueLength;
831
+ if (payloadBytes > U32_MAX) throw workerProtocolError("WorkerProtocolError", "packed batch payload exceeds 32-bit payload limit");
832
+ }
833
+ }
834
+ const payloadOffset = checkedAdd(4, metadataBytes, "packed batch header");
835
+ const totalBytes = checkedAdd(payloadOffset, payloadBytes, "packed batch total");
836
+ const bytes = new Uint8Array(totalBytes);
837
+ const view = new DataView(bytes.buffer);
838
+ view.setUint32(0, count, true);
839
+ let metadataOffset = 4;
840
+ let writeOffset = payloadOffset;
841
+ for (let index = 0; index < count; index += 1) {
842
+ const op = ops[index];
843
+ const key = op.key;
844
+ const keyLength = key.byteLength;
845
+ const valueLength = op.kind === "put" ? op.value.byteLength : 0;
846
+ view.setUint8(metadataOffset, op.kind === "put" ? BATCH_OP_PUT : BATCH_OP_DELETE);
847
+ view.setUint32(metadataOffset + 1, keyLength, true);
848
+ view.setUint32(metadataOffset + 5, valueLength, true);
849
+ metadataOffset += 9;
850
+ bytes.set(key, writeOffset);
851
+ writeOffset += keyLength;
852
+ if (op.kind === "put") {
853
+ bytes.set(op.value, writeOffset);
854
+ writeOffset += valueLength;
855
+ }
856
+ }
857
+ return {
858
+ __moyodbPacked: PACKED_BATCH_OPS_V1,
859
+ bytes
860
+ };
861
+ }
862
+ function unpackBatchOps(payload) {
863
+ const bytes = payload.bytes;
864
+ if (!(bytes instanceof Uint8Array) || bytes.byteLength < 4) throw workerProtocolError("WorkerProtocolError", "invalid packed batch payload");
865
+ const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
866
+ const count = view.getUint32(0, true);
867
+ const payloadOffset = checkedAdd(4, checkedByteCount(count, 9, "packed batch metadata"), "packed batch header");
868
+ if (payloadOffset > bytes.byteLength) throw workerProtocolError("WorkerProtocolError", "packed batch metadata exceeds payload length");
869
+ const ops = new Array(count);
870
+ let metadataOffset = 4;
871
+ let readOffset = payloadOffset;
872
+ for (let index = 0; index < count; index += 1) {
873
+ const kind = view.getUint8(metadataOffset);
874
+ const keyLength = view.getUint32(metadataOffset + 1, true);
875
+ const valueLength = view.getUint32(metadataOffset + 5, true);
876
+ metadataOffset += 9;
877
+ const keyEnd = readOffset + keyLength;
878
+ if (keyEnd > U32_MAX || keyEnd > bytes.byteLength) throw workerProtocolError("WorkerProtocolError", "packed batch key exceeds payload length");
879
+ const key = bytes.subarray(readOffset, keyEnd);
880
+ readOffset = keyEnd;
881
+ if (kind === BATCH_OP_DELETE) {
882
+ if (valueLength !== 0) throw workerProtocolError("WorkerProtocolError", "packed delete operation has a value payload");
883
+ ops[index] = {
884
+ kind: "delete",
885
+ key
886
+ };
887
+ continue;
888
+ }
889
+ if (kind !== BATCH_OP_PUT) throw workerProtocolError("WorkerProtocolError", `packed batch operation has invalid kind byte: ${kind}`);
890
+ const valueEnd = readOffset + valueLength;
891
+ if (valueEnd > U32_MAX || valueEnd > bytes.byteLength) throw workerProtocolError("WorkerProtocolError", "packed batch value exceeds payload length");
892
+ ops[index] = {
893
+ kind: "put",
894
+ key,
895
+ value: bytes.subarray(readOffset, valueEnd)
896
+ };
897
+ readOffset = valueEnd;
898
+ }
899
+ if (readOffset !== bytes.byteLength) throw workerProtocolError("WorkerProtocolError", "packed batch payload has trailing bytes");
900
+ return ops;
901
+ }
902
+ function unpackBatchOpKeys(payload) {
903
+ const bytes = payload.bytes;
904
+ if (!(bytes instanceof Uint8Array) || bytes.byteLength < 4) throw workerProtocolError("WorkerProtocolError", "invalid packed batch payload");
905
+ const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
906
+ const count = view.getUint32(0, true);
907
+ const payloadOffset = checkedAdd(4, checkedByteCount(count, 9, "packed batch metadata"), "packed batch header");
908
+ if (payloadOffset > bytes.byteLength) throw workerProtocolError("WorkerProtocolError", "packed batch metadata exceeds payload length");
909
+ const ops = new Array(count);
910
+ let metadataOffset = 4;
911
+ let readOffset = payloadOffset;
912
+ for (let index = 0; index < count; index += 1) {
913
+ const kind = view.getUint8(metadataOffset);
914
+ const keyLength = view.getUint32(metadataOffset + 1, true);
915
+ const valueLength = view.getUint32(metadataOffset + 5, true);
916
+ metadataOffset += 9;
917
+ const keyEnd = readOffset + keyLength;
918
+ if (keyEnd > U32_MAX || keyEnd > bytes.byteLength) throw workerProtocolError("WorkerProtocolError", "packed batch key exceeds payload length");
919
+ const key = bytes.subarray(readOffset, keyEnd);
920
+ readOffset = keyEnd;
921
+ if (kind === BATCH_OP_DELETE) {
922
+ if (valueLength !== 0) throw workerProtocolError("WorkerProtocolError", "packed delete operation has a value payload");
923
+ ops[index] = {
924
+ kind: "delete",
925
+ key
926
+ };
927
+ continue;
928
+ }
929
+ if (kind !== BATCH_OP_PUT) throw workerProtocolError("WorkerProtocolError", `packed batch operation has invalid kind byte: ${kind}`);
930
+ const valueEnd = readOffset + valueLength;
931
+ if (valueEnd > U32_MAX || valueEnd > bytes.byteLength) throw workerProtocolError("WorkerProtocolError", "packed batch value exceeds payload length");
932
+ ops[index] = {
933
+ kind: "put",
934
+ key
935
+ };
936
+ readOffset = valueEnd;
937
+ }
938
+ if (readOffset !== bytes.byteLength) throw workerProtocolError("WorkerProtocolError", "packed batch payload has trailing bytes");
939
+ return ops;
940
+ }
941
+ function isPackedBinaryList(value) {
942
+ return isRecord(value) && value.__moyodbPacked === PACKED_BINARY_LIST_V1 && value.bytes instanceof Uint8Array;
943
+ }
944
+ function isPackedNullableBinaryList(value) {
945
+ return isRecord(value) && value.__moyodbPacked === PACKED_NULLABLE_BINARY_LIST_V1 && value.bytes instanceof Uint8Array;
946
+ }
947
+ function isPackedScanRows(value) {
948
+ return isRecord(value) && value.__moyodbPacked === PACKED_SCAN_ROWS_V1 && value.bytes instanceof Uint8Array;
949
+ }
950
+ function isPackedBatchOps(value) {
951
+ return isRecord(value) && value.__moyodbPacked === PACKED_BATCH_OPS_V1 && value.bytes instanceof Uint8Array;
952
+ }
953
+ function isPackedOptionalValues(value) {
954
+ return isRecord(value) && value.__moyodbPacked === PACKED_OPTIONAL_VALUES_V1 && value.bytes instanceof Uint8Array;
955
+ }
956
+ function checkedByteCount(count, itemBytes, what) {
957
+ if (!Number.isSafeInteger(count) || count < 0) throw workerProtocolError("WorkerProtocolError", `${what} count is invalid: ${count}`);
958
+ return checkedU32(count * itemBytes, what);
959
+ }
960
+ function checkedAdd(left, right, what) {
961
+ return checkedU32(left + right, what);
962
+ }
963
+ function checkedU32(value, what) {
964
+ if (!Number.isSafeInteger(value) || value < 0 || value > U32_MAX) throw workerProtocolError("WorkerProtocolError", `${what} exceeds 32-bit payload limit`);
965
+ return value;
966
+ }
967
+ function copyToOwnedUint8Array(value) {
968
+ const owned = new Uint8Array(value.byteLength);
969
+ owned.set(value);
970
+ return owned;
971
+ }
972
+ function stringOrUndefined(value) {
973
+ return typeof value === "string" ? value : void 0;
974
+ }
975
+ //#endregion
976
+ //#region src/errors.ts
977
+ var MoyoDbError = class extends Error {
978
+ constructor(name, message) {
979
+ super(message);
980
+ this.name = name;
981
+ Object.setPrototypeOf(this, new.target.prototype);
982
+ }
983
+ };
984
+ var UnsupportedPlatformError = class extends MoyoDbError {
985
+ constructor(message) {
986
+ super("UnsupportedPlatformError", message);
987
+ }
988
+ };
989
+ var DatabaseBusyError = class extends MoyoDbError {
990
+ constructor(message) {
991
+ super("DatabaseBusyError", message);
992
+ }
993
+ };
994
+ var CorruptionError = class extends MoyoDbError {
995
+ constructor(message) {
996
+ super("CorruptionError", message);
997
+ }
998
+ };
999
+ var StoreExistsError = class extends MoyoDbError {
1000
+ constructor(message) {
1001
+ super("StoreExistsError", message);
1002
+ }
1003
+ };
1004
+ var StoreNotFoundError = class extends MoyoDbError {
1005
+ constructor(message) {
1006
+ super("StoreNotFoundError", message);
1007
+ }
1008
+ };
1009
+ var IndexNotFoundError = class extends MoyoDbError {
1010
+ constructor(message) {
1011
+ super("IndexNotFoundError", message);
1012
+ }
1013
+ };
1014
+ var ConstraintError = class extends MoyoDbError {
1015
+ constructor(message) {
1016
+ super("ConstraintError", message);
1017
+ }
1018
+ };
1019
+ var UniqueIndexConstraintError = class extends ConstraintError {
1020
+ constructor(message) {
1021
+ super(message);
1022
+ this.name = "UniqueIndexConstraintError";
1023
+ }
1024
+ };
1025
+ var WriteTransactionAlreadyOpenError = class extends MoyoDbError {
1026
+ constructor(message = "write transaction already open") {
1027
+ super("WriteTransactionAlreadyOpenError", message);
1028
+ }
1029
+ };
1030
+ var TransactionConflictError = class extends MoyoDbError {
1031
+ constructor(message = "transaction snapshot is stale; start a new transaction") {
1032
+ super("TransactionConflictError", message);
1033
+ }
1034
+ };
1035
+ var ReadonlyTransactionError = class extends MoyoDbError {
1036
+ constructor(message = "readonly transaction cannot perform this operation") {
1037
+ super("ReadonlyTransactionError", message);
1038
+ }
1039
+ };
1040
+ var TransactionClosedError = class extends MoyoDbError {
1041
+ constructor(message = "transaction is already closed") {
1042
+ super("TransactionClosedError", message);
1043
+ }
1044
+ };
1045
+ var DatabaseClosedError = class extends MoyoDbError {
1046
+ constructor(message = "database handle is closed") {
1047
+ super("DatabaseClosedError", message);
1048
+ }
1049
+ };
1050
+ var ValueTooLargeError = class extends MoyoDbError {
1051
+ constructor(message) {
1052
+ super("ValueTooLargeError", message);
1053
+ }
1054
+ };
1055
+ var KeyTooLargeError = class extends MoyoDbError {
1056
+ constructor(message) {
1057
+ super("KeyTooLargeError", message);
1058
+ }
1059
+ };
1060
+ var StoreNameTooLongError = class extends MoyoDbError {
1061
+ constructor(message) {
1062
+ super("StoreNameTooLongError", message);
1063
+ }
1064
+ };
1065
+ var ReservedStoreNameError = class extends MoyoDbError {
1066
+ constructor(message) {
1067
+ super("ReservedStoreNameError", message);
1068
+ }
1069
+ };
1070
+ var InvalidRangeError = class extends MoyoDbError {
1071
+ constructor(message) {
1072
+ super("InvalidRangeError", message);
1073
+ }
1074
+ };
1075
+ var StorageError = class extends MoyoDbError {
1076
+ constructor(message) {
1077
+ super("StorageError", message);
1078
+ }
1079
+ };
1080
+ var SerializationError = class extends MoyoDbError {
1081
+ constructor(message) {
1082
+ super("SerializationError", message);
1083
+ }
1084
+ };
1085
+ var InjectedFailureError = class extends MoyoDbError {
1086
+ constructor(message) {
1087
+ super("InjectedFailureError", message);
1088
+ }
1089
+ };
1090
+ var ChangeFeedCompactedError = class extends MoyoDbError {
1091
+ constructor(message) {
1092
+ super("ChangeFeedCompactedError", message);
1093
+ }
1094
+ };
1095
+ /**
1096
+ * The engine state could not be trusted, or automatic recovery failed.
1097
+ * A failed commit may already be durable. The worker attempts recovery before
1098
+ * a new transaction and after a failed commit. Recovery discards all open transactions.
1099
+ */
1100
+ var RecoveryRequiredError = class extends MoyoDbError {
1101
+ constructor(message) {
1102
+ super("RecoveryRequiredError", message);
1103
+ }
1104
+ };
1105
+ var InternalError = class extends MoyoDbError {
1106
+ constructor(message) {
1107
+ super("InternalError", message);
1108
+ }
1109
+ };
1110
+ var InvalidOpenOptionsError = class extends MoyoDbError {
1111
+ constructor(message) {
1112
+ super("InvalidOpenOptionsError", message);
1113
+ }
1114
+ };
1115
+ var VersionError = class extends MoyoDbError {
1116
+ constructor(message) {
1117
+ super("VersionError", message);
1118
+ }
1119
+ };
1120
+ var ERROR_CONSTRUCTORS = {
1121
+ UnsupportedPlatformError,
1122
+ DatabaseBusyError,
1123
+ CorruptionError,
1124
+ StoreExistsError,
1125
+ StoreNotFoundError,
1126
+ IndexNotFoundError,
1127
+ ConstraintError,
1128
+ UniqueIndexConstraintError,
1129
+ WriteTransactionAlreadyOpenError,
1130
+ TransactionConflictError,
1131
+ ReadonlyTransactionError,
1132
+ TransactionClosedError,
1133
+ DatabaseClosedError,
1134
+ ValueTooLargeError,
1135
+ KeyTooLargeError,
1136
+ StoreNameTooLongError,
1137
+ ReservedStoreNameError,
1138
+ InvalidRangeError,
1139
+ StorageError,
1140
+ SerializationError,
1141
+ InjectedFailureError,
1142
+ ChangeFeedCompactedError,
1143
+ RecoveryRequiredError,
1144
+ InternalError,
1145
+ InvalidOpenOptionsError,
1146
+ VersionError
1147
+ };
1148
+ function instantiateError(code, message) {
1149
+ if (Object.prototype.hasOwnProperty.call(ERROR_CONSTRUCTORS, code)) {
1150
+ const ErrorConstructor = ERROR_CONSTRUCTORS[code];
1151
+ return new ErrorConstructor(message);
1152
+ }
1153
+ const err = new Error(message);
1154
+ err.name = code;
1155
+ return err;
1156
+ }
1157
+ function normalizeError(error) {
1158
+ if (error instanceof MoyoDbError) return error;
1159
+ if (error instanceof Error) {
1160
+ if (error.name === "Error") return error;
1161
+ return instantiateError(error.name, error.message);
1162
+ }
1163
+ const payload = error;
1164
+ return instantiateError(payload?.code ?? payload?.name ?? "Error", payload?.message ?? String(error));
1165
+ }
1166
+ //#endregion
1167
+ //#region src/codec.ts
1168
+ var encoder$1 = new TextEncoder();
1169
+ var decoder = new TextDecoder();
1170
+ var jsonDecoder = new TextDecoder("utf-8", { fatal: true });
1171
+ var TYPE_NULL = 16;
1172
+ var TYPE_FALSE = 32;
1173
+ var TYPE_TRUE = 33;
1174
+ var TYPE_NUMBER = 48;
1175
+ var TYPE_STRING = 64;
1176
+ var TYPE_BYTES = 80;
1177
+ var COMPOUND_ESCAPE = 0;
1178
+ var COMPOUND_ESCAPE_CONT = 255;
1179
+ var COMPOUND_TERM = 0;
1180
+ var F64_MASK = BigInt("0xffffffffffffffff");
1181
+ function utf8Encode(value) {
1182
+ return encoder$1.encode(value);
1183
+ }
1184
+ function utf8Decode(bytes) {
1185
+ return decoder.decode(bytes);
1186
+ }
1187
+ function jsonEncode(value) {
1188
+ const serialized = JSON.stringify(value);
1189
+ if (serialized === void 0) throw new TypeError("value has no JSON representation");
1190
+ return utf8Encode(serialized);
1191
+ }
1192
+ function jsonDecode(bytes) {
1193
+ return JSON.parse(jsonDecoder.decode(bytes));
1194
+ }
1195
+ function u64Key(value) {
1196
+ if (typeof value === "number" && (!Number.isSafeInteger(value) || value < 0)) throw new RangeError("u64Key number inputs must be safe non-negative integers; use bigint for larger values");
1197
+ const asBigInt = typeof value === "bigint" ? value : BigInt(value);
1198
+ if (asBigInt < 0n) throw new RangeError("u64Key only accepts non-negative values");
1199
+ if (asBigInt > F64_MASK) throw new RangeError("u64Key value exceeds the unsigned 64-bit range");
1200
+ const buf = /* @__PURE__ */ new ArrayBuffer(8);
1201
+ new DataView(buf).setBigUint64(0, asBigInt, false);
1202
+ return new Uint8Array(buf);
1203
+ }
1204
+ function isCompoundKeyPartList(value) {
1205
+ return Array.isArray(value);
1206
+ }
1207
+ function indexKey(value) {
1208
+ if (isCompoundKeyPartList(value)) return compoundKey(...value);
1209
+ return encodeCompoundKeyPart(value);
1210
+ }
1211
+ function compoundKey(...parts) {
1212
+ return encodeCompoundBytes(parts.map((part) => encodeCompoundKeyPart(part)));
1213
+ }
1214
+ function encodeIndexScalar(value) {
1215
+ return encodeCompoundKeyPart(value);
1216
+ }
1217
+ function encodeCompoundKeyParts(parts) {
1218
+ return encodeCompoundBytes(parts);
1219
+ }
1220
+ function splitCompoundKey(key) {
1221
+ const parts = [];
1222
+ const current = [];
1223
+ for (let index = 0; index < key.length; index += 1) {
1224
+ const byte = key[index];
1225
+ if (byte !== COMPOUND_ESCAPE) {
1226
+ current.push(byte);
1227
+ continue;
1228
+ }
1229
+ const next = key[index + 1];
1230
+ if (next === COMPOUND_ESCAPE_CONT) {
1231
+ current.push(COMPOUND_ESCAPE);
1232
+ index += 1;
1233
+ continue;
1234
+ }
1235
+ if (next === COMPOUND_TERM) {
1236
+ parts.push(Uint8Array.from(current));
1237
+ current.length = 0;
1238
+ index += 1;
1239
+ continue;
1240
+ }
1241
+ throw new TypeError("invalid compound key encoding");
1242
+ }
1243
+ if (current.length !== 0) throw new TypeError("compound key terminated unexpectedly");
1244
+ return parts;
1245
+ }
1246
+ function prefixSuccessor(prefix) {
1247
+ const out = prefix.slice();
1248
+ for (let index = out.length - 1; index >= 0; index -= 1) if (out[index] !== 255) {
1249
+ out[index] += 1;
1250
+ return out.subarray(0, index + 1);
1251
+ }
1252
+ return null;
1253
+ }
1254
+ function prefixRange(prefix) {
1255
+ const upper = prefixSuccessor(prefix);
1256
+ return upper ? {
1257
+ gte: prefix,
1258
+ lt: upper
1259
+ } : { gte: prefix };
1260
+ }
1261
+ function compoundKeyRange(...parts) {
1262
+ return prefixRange(compoundKey(...parts));
1263
+ }
1264
+ function encodeCompoundKeyPart(value) {
1265
+ if (value === null) return Uint8Array.of(TYPE_NULL);
1266
+ if (typeof value === "boolean") return Uint8Array.of(value ? TYPE_TRUE : TYPE_FALSE);
1267
+ if (typeof value === "number") return encodeSortableNumber(value);
1268
+ if (typeof value === "string") {
1269
+ for (const character of value) {
1270
+ const codePoint = character.codePointAt(0);
1271
+ if (codePoint >= 55296 && codePoint <= 57343) throw new TypeError("compound key string parts must contain valid Unicode scalar values");
1272
+ }
1273
+ const body = utf8Encode(value);
1274
+ const out = new Uint8Array(1 + body.length);
1275
+ out[0] = TYPE_STRING;
1276
+ out.set(body, 1);
1277
+ return out;
1278
+ }
1279
+ if (value instanceof Uint8Array) {
1280
+ const out = new Uint8Array(1 + value.length);
1281
+ out[0] = TYPE_BYTES;
1282
+ out.set(value, 1);
1283
+ return out;
1284
+ }
1285
+ throw new TypeError("compound key parts must be string, number, boolean, null, or Uint8Array");
1286
+ }
1287
+ function encodeCompoundBytes(parts) {
1288
+ let length = 0;
1289
+ for (const part of parts) {
1290
+ for (const byte of part) length += byte === COMPOUND_ESCAPE ? 2 : 1;
1291
+ length += 2;
1292
+ }
1293
+ const out = new Uint8Array(length);
1294
+ let offset = 0;
1295
+ for (const part of parts) {
1296
+ for (const byte of part) if (byte === COMPOUND_ESCAPE) {
1297
+ out[offset] = COMPOUND_ESCAPE;
1298
+ out[offset + 1] = COMPOUND_ESCAPE_CONT;
1299
+ offset += 2;
1300
+ } else {
1301
+ out[offset] = byte;
1302
+ offset += 1;
1303
+ }
1304
+ out[offset] = COMPOUND_TERM;
1305
+ out[offset + 1] = COMPOUND_TERM;
1306
+ offset += 2;
1307
+ }
1308
+ return out;
1309
+ }
1310
+ function encodeSortableNumber(value) {
1311
+ if (!Number.isFinite(value)) throw new TypeError("compound key number parts must be finite");
1312
+ const normalized = Object.is(value, -0) ? 0 : value;
1313
+ const buffer = /* @__PURE__ */ new ArrayBuffer(9);
1314
+ const view = new DataView(buffer);
1315
+ view.setUint8(0, TYPE_NUMBER);
1316
+ view.setFloat64(1, normalized, false);
1317
+ let bits = view.getBigUint64(1, false);
1318
+ bits = (bits & 1n << 63n) !== 0n ? ~bits & F64_MASK : bits ^ 1n << 63n;
1319
+ view.setBigUint64(1, bits, false);
1320
+ return new Uint8Array(buffer);
1321
+ }
1322
+ //#endregion
1323
+ //#region src/indexing.ts
1324
+ var encoder = new TextEncoder();
1325
+ var fatalDecoder = new TextDecoder("utf-8", { fatal: true });
1326
+ var MISSING = Symbol("moyodb.indexing.missing");
1327
+ var FNV64_OFFSET = BigInt("0xcbf29ce484222325");
1328
+ var FNV64_PRIME = BigInt("0x100000001b3");
1329
+ var FNV64_MASK = BigInt("0xffffffffffffffff");
1330
+ var INTERNAL_STORE_PREFIX = "__browserdb:";
1331
+ var INTERNAL_INDEX_STORE_PREFIX = "__browserdb:index:";
1332
+ var INDEX_METADATA_STORE = "__browserdb:indexes";
1333
+ function isInternalStoreName(name) {
1334
+ return name.startsWith(INTERNAL_STORE_PREFIX);
1335
+ }
1336
+ function assertPublicStoreName(name) {
1337
+ if (isInternalStoreName(name)) throw new ReservedStoreNameError(`reserved store name: ${name}`);
1338
+ }
1339
+ function normalizeIndexDefinitions(value) {
1340
+ if (value === void 0) return [];
1341
+ if (!Array.isArray(value)) throw new InvalidOpenOptionsError("indexes must be an array");
1342
+ const normalized = [];
1343
+ const identities = /* @__PURE__ */ new Set();
1344
+ const internalStores = /* @__PURE__ */ new Map();
1345
+ for (const entry of value) {
1346
+ if (entry === null || typeof entry !== "object" || Array.isArray(entry)) throw new InvalidOpenOptionsError("each index definition must be an object");
1347
+ const { store, name, keyPath, unique } = entry;
1348
+ if (typeof store !== "string" || store.length === 0) throw new InvalidOpenOptionsError("index store must be a non-empty string");
1349
+ if (typeof name !== "string" || name.length === 0) throw new InvalidOpenOptionsError("index name must be a non-empty string");
1350
+ assertPublicStoreName(store);
1351
+ const keyPathInfo = normalizeIndexKeyPath(keyPath);
1352
+ if (unique !== void 0 && typeof unique !== "boolean") throw new InvalidOpenOptionsError("index unique must be a boolean");
1353
+ const def = {
1354
+ store,
1355
+ name,
1356
+ keyPath: keyPathInfo.paths,
1357
+ compound: keyPathInfo.compound,
1358
+ unique: unique ?? false,
1359
+ internalStore: makeInternalIndexStoreName(store, name)
1360
+ };
1361
+ const identity = indexDefinitionIdentity(def.store, def.name);
1362
+ if (identities.has(identity)) throw new InvalidOpenOptionsError(`duplicate index definition ${def.store}.${def.name}`);
1363
+ identities.add(identity);
1364
+ const mappedIdentity = internalStores.get(def.internalStore);
1365
+ if (mappedIdentity && mappedIdentity !== identity) throw new InvalidOpenOptionsError(`index definitions ${mappedIdentity} and ${identity} map to the same internal store ${def.internalStore}`);
1366
+ internalStores.set(def.internalStore, identity);
1367
+ normalized.push(def);
1368
+ }
1369
+ normalized.sort(compareNormalizedIndexDefinitions);
1370
+ return normalized;
1371
+ }
1372
+ function compareNormalizedIndexDefinitions(left, right) {
1373
+ const storeCompare = compareStringsByCodeUnit(left.store, right.store);
1374
+ if (storeCompare !== 0) return storeCompare;
1375
+ const nameCompare = compareStringsByCodeUnit(left.name, right.name);
1376
+ if (nameCompare !== 0) return nameCompare;
1377
+ const uniqueCompare = Number(left.unique) - Number(right.unique);
1378
+ if (uniqueCompare !== 0) return uniqueCompare;
1379
+ return compareStringsByCodeUnit(serializeIndexKeyPath(left), serializeIndexKeyPath(right));
1380
+ }
1381
+ function indexDefinitionIdentity(store, name) {
1382
+ return JSON.stringify([store, name]);
1383
+ }
1384
+ function findIndexDefinition(defs, store, name) {
1385
+ return defs.find((def) => def.store === store && def.name === name) ?? null;
1386
+ }
1387
+ function indexesForStore(defs, store) {
1388
+ return defs.filter((def) => def.store === store);
1389
+ }
1390
+ function encodeIndexMetadataKey(store, name) {
1391
+ return encodeCompoundKeyParts([utf8Encode(store), utf8Encode(name)]);
1392
+ }
1393
+ function encodeIndexMetadataValue(def) {
1394
+ return utf8Encode(JSON.stringify(toPublicIndexDefinition(def)));
1395
+ }
1396
+ function decodeIndexMetadataValue(bytes) {
1397
+ let parsed;
1398
+ try {
1399
+ parsed = JSON.parse(fatalDecoder.decode(bytes));
1400
+ const [def] = normalizeIndexDefinitions([parsed]);
1401
+ return def;
1402
+ } catch (error) {
1403
+ throw new SerializationError(`invalid persisted index metadata: ${String(error)}`);
1404
+ }
1405
+ }
1406
+ function encodeIndexEntryKey(logicalIndexKey, primaryKey) {
1407
+ return encodeCompoundKeyParts([logicalIndexKey, primaryKey]);
1408
+ }
1409
+ function decodeIndexEntryKey(bytes) {
1410
+ let parts;
1411
+ try {
1412
+ parts = splitCompoundKey(bytes);
1413
+ } catch (error) {
1414
+ throw new SerializationError(`invalid index entry key encoding: ${String(error)}`);
1415
+ }
1416
+ if (parts.length !== 2) throw new SerializationError("invalid index entry key encoding");
1417
+ return {
1418
+ logicalKey: parts[0],
1419
+ primaryKey: parts[1]
1420
+ };
1421
+ }
1422
+ function indexKeyExactRange(logicalIndexKey) {
1423
+ return prefixRange(encodeCompoundKeyParts([logicalIndexKey]));
1424
+ }
1425
+ function indexRangeToPhysicalRange(range = {}) {
1426
+ validateIndexRangeShape(range);
1427
+ const physical = {};
1428
+ if (range.reverse !== void 0) physical.reverse = range.reverse;
1429
+ if (range.limit !== void 0) physical.limit = range.limit;
1430
+ if (range.gte) physical.gte = encodeCompoundKeyParts([range.gte]);
1431
+ if (range.gt) {
1432
+ const lower = prefixSuccessor(encodeCompoundKeyParts([range.gt]));
1433
+ if (lower) physical.gte = lower;
1434
+ }
1435
+ if (range.lt) physical.lt = encodeCompoundKeyParts([range.lt]);
1436
+ if (range.lte) {
1437
+ const upper = prefixSuccessor(encodeCompoundKeyParts([range.lte]));
1438
+ if (upper) physical.lt = upper;
1439
+ }
1440
+ return physical;
1441
+ }
1442
+ function extractLogicalIndexKey(def, valueBytes) {
1443
+ return extractLogicalIndexKeyFromDocument(def, decodeIndexedDocument(valueBytes));
1444
+ }
1445
+ /**
1446
+ * Reuse the decoded document only within one synchronous mutation plan.
1447
+ * Lazy decoding preserves validation order. Do not retain the extractor
1448
+ * across operations or an await.
1449
+ */
1450
+ function createIndexKeyExtractor(valueBytes) {
1451
+ let decoded = false;
1452
+ let documentValue;
1453
+ return (def) => {
1454
+ if (!decoded) {
1455
+ documentValue = decodeIndexedDocument(valueBytes);
1456
+ decoded = true;
1457
+ }
1458
+ return extractLogicalIndexKeyFromDocument(def, documentValue);
1459
+ };
1460
+ }
1461
+ function extractLogicalIndexKeyFromDocument(def, documentValue) {
1462
+ if (def.compound) {
1463
+ const parts = [];
1464
+ for (const keyPath of def.keyPath) {
1465
+ const resolved = resolveKeyPath(documentValue, keyPath);
1466
+ if (resolved === MISSING) return null;
1467
+ parts.push(encodeDocumentIndexValue(resolved));
1468
+ }
1469
+ return encodeCompoundKeyParts(parts);
1470
+ }
1471
+ const resolved = resolveKeyPath(documentValue, def.keyPath[0]);
1472
+ if (resolved === MISSING) return null;
1473
+ return encodeDocumentIndexValue(resolved);
1474
+ }
1475
+ function serializeNormalizedIndexDefinitions(defs) {
1476
+ return JSON.stringify(toPublicIndexDefinitions(defs));
1477
+ }
1478
+ function cloneNormalizedIndexDefinitions(defs) {
1479
+ return defs.map((def) => ({
1480
+ store: def.store,
1481
+ name: def.name,
1482
+ keyPath: [...def.keyPath],
1483
+ compound: def.compound,
1484
+ unique: def.unique,
1485
+ internalStore: def.internalStore
1486
+ }));
1487
+ }
1488
+ function toPublicIndexDefinitions(defs) {
1489
+ return defs.map(toPublicIndexDefinition);
1490
+ }
1491
+ function toPublicIndexDefinition(def) {
1492
+ return {
1493
+ store: def.store,
1494
+ name: def.name,
1495
+ keyPath: def.compound ? [...def.keyPath] : def.keyPath[0],
1496
+ unique: def.unique
1497
+ };
1498
+ }
1499
+ function normalizeIndexKeyPath(value) {
1500
+ if (typeof value === "string") {
1501
+ validateSingleKeyPath(value);
1502
+ return {
1503
+ paths: [value],
1504
+ compound: false
1505
+ };
1506
+ }
1507
+ if (!Array.isArray(value) || value.length === 0 || !value.every((item) => typeof item === "string")) throw new InvalidOpenOptionsError("index keyPath must be a non-empty string or non-empty string[]");
1508
+ for (const path of value) validateSingleKeyPath(path);
1509
+ return {
1510
+ paths: [...value],
1511
+ compound: true
1512
+ };
1513
+ }
1514
+ function validateSingleKeyPath(value) {
1515
+ if (value.length === 0) throw new InvalidOpenOptionsError("index keyPath strings must be non-empty");
1516
+ if (value.startsWith(".") || value.endsWith(".") || value.includes("..")) throw new InvalidOpenOptionsError(`invalid index keyPath: ${value}`);
1517
+ }
1518
+ function serializeIndexKeyPath(def) {
1519
+ return def.compound ? `[${def.keyPath.join(",")}]` : def.keyPath[0];
1520
+ }
1521
+ function makeInternalIndexStoreName(store, name) {
1522
+ const candidate = `${INTERNAL_INDEX_STORE_PREFIX}${base64Url(utf8Encode(store))}:${base64Url(utf8Encode(name))}`;
1523
+ if (encoder.encode(candidate).length <= 255) return candidate;
1524
+ return `${INTERNAL_INDEX_STORE_PREFIX}h:${fnv1a64Hex(utf8Encode(`${store}\u0000${name}`))}`;
1525
+ }
1526
+ function base64Url(bytes) {
1527
+ let binary = "";
1528
+ for (const byte of bytes) binary += String.fromCharCode(byte);
1529
+ return btoa(binary).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/u, "");
1530
+ }
1531
+ function fnv1a64Hex(bytes) {
1532
+ let hash = FNV64_OFFSET;
1533
+ for (const byte of bytes) {
1534
+ hash ^= BigInt(byte);
1535
+ hash = hash * FNV64_PRIME & FNV64_MASK;
1536
+ }
1537
+ return hash.toString(16).padStart(16, "0");
1538
+ }
1539
+ function decodeIndexedDocument(bytes) {
1540
+ try {
1541
+ return JSON.parse(fatalDecoder.decode(bytes));
1542
+ } catch (error) {
1543
+ throw new SerializationError(`indexed values must be valid UTF-8 JSON: ${String(error)}`);
1544
+ }
1545
+ }
1546
+ function resolveKeyPath(root, keyPath) {
1547
+ let current = root;
1548
+ for (const segment of keyPath.split(".")) {
1549
+ if (current === null || current === void 0) return MISSING;
1550
+ const target = Object(current);
1551
+ if (!Object.hasOwn(target, segment)) return MISSING;
1552
+ current = Reflect.get(target, segment);
1553
+ }
1554
+ return current;
1555
+ }
1556
+ function encodeDocumentIndexValue(value) {
1557
+ if (value === null || typeof value === "string" || typeof value === "number" || typeof value === "boolean" || value instanceof Uint8Array) try {
1558
+ return encodeIndexScalar(value);
1559
+ } catch (error) {
1560
+ if (error instanceof TypeError) throw new SerializationError(`invalid indexed keyPath value: ${error.message}`);
1561
+ throw error;
1562
+ }
1563
+ throw new SerializationError(`indexed keyPath values must resolve to string, number, boolean, null, or Uint8Array; got ${describeValue(value)}`);
1564
+ }
1565
+ function describeValue(value) {
1566
+ if (Array.isArray(value)) return "array";
1567
+ return typeof value;
1568
+ }
1569
+ function validateIndexRangeShape(range) {
1570
+ if (range.gt !== void 0 && range.gte !== void 0) throw new TypeError("index range cannot specify both gt and gte");
1571
+ if (range.lt !== void 0 && range.lte !== void 0) throw new TypeError("index range cannot specify both lt and lte");
1572
+ }
1573
+ //#endregion
1574
+ export { StoreExistsError as $, prefixRange as A, packedBinaryListBytes as At, DatabaseClosedError as B, unpackPackedOptionalValues as Bt, compoundKey as C, isWorkerProtocolReadyEnvelope as Ct, indexKey as D, isWorkerProtocolResponseBatchMessage as Dt, encodeIndexScalar as E, isWorkerProtocolRequestMessage as Et, utf8Encode as F, unpackPackedBatchOpKeys as Ft, InvalidRangeError as G, InjectedFailureError as H, compareStringsByCodeUnit as Ht, ChangeFeedCompactedError as I, unpackPackedBatchOps as It, ReadonlyTransactionError as J, KeyTooLargeError as K, ConstraintError as L, unpackPackedBinaryList as Lt, splitCompoundKey as M, prepareWorkerCommandPayload as Mt, u64Key as N, prepareWorkerResponsePayload as Nt, jsonDecode as O, isWorkerProtocolResponseMessage as Ot, utf8Decode as P, serializeWorkerError as Pt, StorageError as Q, CorruptionError as R, unpackPackedBinaryPairKeys as Rt, toPublicIndexDefinitions as S, isWorkerProtocolEnvelope as St, encodeCompoundKeyParts as T, isWorkerProtocolRequestBatchMessage as Tt, InternalError as U, isRecord as Ut, IndexNotFoundError as V, workerProtocolError as Vt, InvalidOpenOptionsError as W, ReservedStoreNameError as X, RecoveryRequiredError as Y, SerializationError as Z, indexRangeToPhysicalRange as _, decodeWorkerCommandPayload as _t, createIndexKeyExtractor as a, UnsupportedPlatformError as at, normalizeIndexDefinitions as b, isAutocommitCommand as bt, decodeIndexedDocument as c, WriteTransactionAlreadyOpenError as ct, encodeIndexMetadataValue as d, WORKER_PROTOCOL_READY as dt, StoreNameTooLongError as et, extractLogicalIndexKey as f, WORKER_PROTOCOL_REQUEST as ft, indexKeyExactRange as g, captureWorkerPayload as gt, indexDefinitionIdentity as h, WORKER_PROTOCOL_RESPONSE_BATCH as ht, compareNormalizedIndexDefinitions as i, UniqueIndexConstraintError as it, prefixSuccessor as j, packedOptionalValues as jt, jsonEncode as k, packedBatchOpsBytes as kt, encodeIndexEntryKey as l, normalizeError as lt, findIndexDefinition as m, WORKER_PROTOCOL_RESPONSE as mt, assertPublicStoreName as n, TransactionClosedError as nt, decodeIndexEntryKey as o, ValueTooLargeError as ot, extractLogicalIndexKeyFromDocument as p, WORKER_PROTOCOL_REQUEST_BATCH as pt, MoyoDbError as q, cloneNormalizedIndexDefinitions as r, TransactionConflictError as rt, decodeIndexMetadataValue as s, VersionError as st, INDEX_METADATA_STORE as t, StoreNotFoundError as tt, encodeIndexMetadataKey as u, MAX_WORKER_BATCH_BYTES as ut, indexesForStore as v, decodeWorkerResponsePayload as vt, compoundKeyRange as w, isWorkerProtocolReadyMessage as wt, serializeNormalizedIndexDefinitions as x, isWorkerCommand as xt, isInternalStoreName as y, deserializeWorkerError as yt, DatabaseBusyError as z, unpackPackedBinaryPairs as zt };
1575
+
1576
+ //# sourceMappingURL=indexing-BzmFhWXs.js.map