@moyodb/sdk 1.0.1 → 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 (69) hide show
  1. package/dist/assets/browser-worker-DP6Mjz7c.js +4 -0
  2. package/dist/assets/browser-worker-DP6Mjz7c.js.map +1 -0
  3. package/dist/assets/shared-worker-DKzhauVf.js +2 -0
  4. package/dist/assets/shared-worker-DKzhauVf.js.map +1 -0
  5. package/dist/browser-worker.d.ts +2 -0
  6. package/dist/browser-worker.d.ts.map +1 -0
  7. package/dist/change-events.d.ts +1 -1
  8. package/dist/chunks/indexing-BzmFhWXs.js +1576 -0
  9. package/dist/chunks/indexing-BzmFhWXs.js.map +1 -0
  10. package/dist/codec.d.ts +1 -1
  11. package/dist/compression.d.ts +1 -1
  12. package/dist/demo.d.ts +2 -1
  13. package/dist/demo.d.ts.map +1 -1
  14. package/dist/engine/README.md +62 -16
  15. package/dist/engine/moyodb_engine.js +1 -1
  16. package/dist/engine/moyodb_engine_bg.wasm +0 -0
  17. package/dist/engine/package.json +1 -1
  18. package/dist/errors.d.ts +3 -0
  19. package/dist/errors.d.ts.map +1 -1
  20. package/dist/index.d.ts +11 -5
  21. package/dist/index.d.ts.map +1 -1
  22. package/dist/indexing.d.ts +1 -1
  23. package/dist/moyodb-sdk.js +2026 -543
  24. package/dist/moyodb-sdk.js.map +1 -1
  25. package/dist/node-engine.js +2213 -0
  26. package/dist/node-engine.js.map +1 -0
  27. package/dist/node-storage.d.mts +12 -0
  28. package/dist/node-storage.mjs +634 -0
  29. package/dist/node-worker-client.d.ts +19 -0
  30. package/dist/node-worker-client.d.ts.map +1 -0
  31. package/dist/node-worker.mjs +118 -0
  32. package/dist/node.d.ts +19 -0
  33. package/dist/node.d.ts.map +1 -0
  34. package/dist/node.js +3194 -0
  35. package/dist/node.js.map +1 -0
  36. package/dist/records.d.ts +75 -0
  37. package/dist/records.d.ts.map +1 -0
  38. package/dist/registry.d.ts +12 -4
  39. package/dist/registry.d.ts.map +1 -1
  40. package/dist/shared-worker-client.d.ts +24 -0
  41. package/dist/shared-worker-client.d.ts.map +1 -0
  42. package/dist/shared-worker-protocol.d.ts +16 -0
  43. package/dist/shared-worker-protocol.d.ts.map +1 -0
  44. package/dist/shared-worker.d.ts +33 -0
  45. package/dist/shared-worker.d.ts.map +1 -0
  46. package/dist/sql-parser.d.ts +9 -0
  47. package/dist/sql-parser.d.ts.map +1 -0
  48. package/dist/sql-types.d.ts +82 -0
  49. package/dist/sql-types.d.ts.map +1 -0
  50. package/dist/sql.d.ts +32 -0
  51. package/dist/sql.d.ts.map +1 -0
  52. package/dist/subscriptions.d.ts +2 -2
  53. package/dist/subscriptions.d.ts.map +1 -1
  54. package/dist/types.d.ts +3 -0
  55. package/dist/types.d.ts.map +1 -1
  56. package/dist/worker-api.d.ts +2 -2
  57. package/dist/worker-api.d.ts.map +1 -1
  58. package/dist/worker-client.d.ts +24 -5
  59. package/dist/worker-client.d.ts.map +1 -1
  60. package/dist/worker-protocol.d.ts +8 -3
  61. package/dist/worker-protocol.d.ts.map +1 -1
  62. package/dist/worker-server.d.ts +10 -2
  63. package/dist/worker-server.d.ts.map +1 -1
  64. package/dist/worker.d.ts +263 -1
  65. package/dist/worker.d.ts.map +1 -1
  66. package/package.json +13 -6
  67. package/README.md +0 -59
  68. package/dist/assets/worker-KDc8Khl_.js +0 -4
  69. package/dist/assets/worker-KDc8Khl_.js.map +0 -1
@@ -1 +1 @@
1
- {"version":3,"file":"moyodb-sdk.js","names":[],"sources":["../src/internal.ts","../src/worker-protocol.ts","../src/worker-client.ts","../src/errors.ts","../src/registry.ts","../src/codec.ts","../src/indexing.ts","../src/change-events.ts","../src/subscriptions.ts","../src/index.ts"],"sourcesContent":["export function isRecord(value: unknown): value is Record<string, unknown> {\n return value !== null && typeof value === 'object';\n}\n\nexport function compareStringsByCodeUnit(left: string, right: string): number {\n if (left < right) {\n return -1;\n }\n return left > right ? 1 : 0;\n}\n\nexport function withTimeout<T>(promise: Promise<T>, timeoutMs: number, fallback: T): Promise<T> {\n return new Promise((resolve) => {\n const timeout = setTimeout(() => resolve(fallback), timeoutMs);\n promise.then(\n (value) => {\n clearTimeout(timeout);\n resolve(value);\n },\n () => {\n clearTimeout(timeout);\n resolve(fallback);\n }\n );\n });\n}\n","import type { AutocommitCommand, IndexScanPage, WorkerApi } from './worker-api';\nimport type { BatchOp } from './types';\nimport { isRecord } from './internal';\n\nexport const WORKER_PROTOCOL_VERSION = 1;\nexport const WORKER_PROTOCOL_READY = 'moyodb:worker-protocol:ready';\nexport const WORKER_PROTOCOL_REQUEST = 'moyodb:worker-protocol:request';\nexport const WORKER_PROTOCOL_RESPONSE = 'moyodb:worker-protocol:response';\nexport const WORKER_PROTOCOL_REQUEST_BATCH = 'moyodb:worker-protocol:request-batch';\nexport const WORKER_PROTOCOL_RESPONSE_BATCH = 'moyodb:worker-protocol:response-batch';\nexport const MAX_WORKER_BATCH_MESSAGES = 128;\nexport const MAX_WORKER_BATCH_BYTES = 1024 * 1024;\n\nexport const WORKER_COMMANDS = [\n 'open',\n 'close',\n 'destroy',\n 'deleteDB',\n 'begin',\n 'commit',\n 'rollback',\n 'autocommit',\n 'createStore',\n 'dropStore',\n 'clearStore',\n 'get',\n 'getMany',\n 'has',\n 'put',\n 'putMany',\n 'delete',\n 'deleteMany',\n 'applyBatch',\n 'scan',\n 'getByIndex',\n 'scanByIndex',\n 'scanByIndexPage',\n 'getIndexes',\n 'reconcileIndexes',\n 'listStores',\n 'getVersion',\n 'changesSince',\n 'setSchemaVersion',\n 'exportSnapshot',\n 'importSnapshot',\n 'reset',\n 'compact',\n 'rebuild',\n 'stats',\n 'storageInfo',\n 'requestPersistence',\n 'setFailpoint'\n] as const;\n\nexport type WorkerCommand = (typeof WORKER_COMMANDS)[number];\n\ntype WorkerMethod<M extends WorkerCommand> = WorkerApi[M] extends (...args: infer Args) => Promise<infer Result>\n ? { args: Args; result: Result }\n : never;\n\nexport type WorkerCommandArgs<M extends WorkerCommand> = WorkerMethod<M>['args'];\nexport type WorkerCommandResult<M extends WorkerCommand> = WorkerMethod<M>['result'];\n/** Arguments of an autocommit command without the leading transaction id. */\nexport type AutocommitArgs<M extends AutocommitCommand> =\n WorkerCommandArgs<M> extends [number, ...infer Rest] ? Rest : never;\n\nexport const AUTOCOMMIT_COMMANDS = [\n 'get',\n 'getMany',\n 'has',\n 'put',\n 'putMany',\n 'delete',\n 'deleteMany',\n 'applyBatch',\n 'scan',\n 'getByIndex',\n 'scanByIndex',\n 'createStore',\n 'dropStore',\n 'clearStore'\n] as const satisfies readonly AutocommitCommand[];\n\nconst AUTOCOMMIT_COMMAND_SET = new Set<string>(AUTOCOMMIT_COMMANDS);\n\nexport function isAutocommitCommand(value: unknown): value is AutocommitCommand {\n return typeof value === 'string' && AUTOCOMMIT_COMMAND_SET.has(value);\n}\n\nexport type PackedBatchOpKey = {\n kind: 'put' | 'delete';\n key: Uint8Array;\n};\n\ntype PreparedWorkerCommandArgs<M extends WorkerCommand> = WorkerCommandArgs<M> | unknown[];\n\nconst PACKED_BINARY_LIST_V1 = 'moyodb:packed-binary-list:v1';\nconst PACKED_NULLABLE_BINARY_LIST_V1 = 'moyodb:packed-nullable-binary-list:v1';\nconst PACKED_SCAN_ROWS_V1 = 'moyodb:packed-scan-rows:v1';\nconst PACKED_BATCH_OPS_V1 = 'moyodb:packed-batch-ops:v1';\n// Engine getMany format: u32 count | count x u32 length | concatenated values.\n// Integers are little-endian; u32::MAX marks a missing value. No repacking is needed.\nconst PACKED_OPTIONAL_VALUES_V1 = 'moyodb:packed-optional-values:v1';\nconst BATCH_OP_DELETE = 0;\nconst BATCH_OP_PUT = 1;\nconst U32_MAX = 0xffff_ffff;\nconst MAX_PACKED_RESPONSE_BYTES = 16 * 1024 * 1024;\nconst EMPTY_TRANSFERABLES: Transferable[] = [];\n\ninterface PackedBinaryListV1 {\n __moyodbPacked: typeof PACKED_BINARY_LIST_V1;\n bytes: Uint8Array;\n}\n\ninterface PackedNullableBinaryListV1 {\n __moyodbPacked: typeof PACKED_NULLABLE_BINARY_LIST_V1;\n bytes: Uint8Array;\n}\n\ninterface PackedScanRowsV1 {\n __moyodbPacked: typeof PACKED_SCAN_ROWS_V1;\n bytes: Uint8Array;\n}\n\ninterface PackedBatchOpsV1 {\n __moyodbPacked: typeof PACKED_BATCH_OPS_V1;\n bytes: Uint8Array;\n}\n\nexport interface PackedOptionalValuesV1 {\n __moyodbPacked: typeof PACKED_OPTIONAL_VALUES_V1;\n bytes: Uint8Array;\n}\n\ninterface PackedIndexScanPage {\n rows: PackedScanRowsV1 | IndexScanPage['rows'];\n cursor: Uint8Array | null;\n}\n\nexport type WorkerProtocolReadyMessage = {\n type: typeof WORKER_PROTOCOL_READY;\n version: typeof WORKER_PROTOCOL_VERSION;\n /** Enables batching; omitted by peers that use single messages. */\n batching?: 1;\n};\n\nexport type WorkerProtocolRequestMessage = {\n [M in WorkerCommand]: {\n type: typeof WORKER_PROTOCOL_REQUEST;\n version: typeof WORKER_PROTOCOL_VERSION;\n id: number;\n command: M;\n args: PreparedWorkerCommandArgs<M>;\n };\n}[WorkerCommand];\n\nexport interface WorkerProtocolRequestBatchMessage {\n type: typeof WORKER_PROTOCOL_REQUEST_BATCH;\n version: typeof WORKER_PROTOCOL_VERSION;\n requests: WorkerProtocolRequestMessage[];\n}\n\nexport interface SerializedWorkerError {\n name: string;\n code?: string;\n message: string;\n stack?: string;\n}\n\nexport type WorkerProtocolSuccessMessage = {\n [M in WorkerCommand]: {\n type: typeof WORKER_PROTOCOL_RESPONSE;\n version: typeof WORKER_PROTOCOL_VERSION;\n id: number;\n ok: true;\n result: WorkerCommandResult<M>;\n };\n}[WorkerCommand];\n\nexport interface WorkerProtocolErrorMessage {\n type: typeof WORKER_PROTOCOL_RESPONSE;\n version: typeof WORKER_PROTOCOL_VERSION;\n id: number;\n ok: false;\n error: SerializedWorkerError;\n}\n\nexport type WorkerProtocolResponseMessage = WorkerProtocolSuccessMessage | WorkerProtocolErrorMessage;\n\nexport interface WorkerProtocolResponseBatchMessage {\n type: typeof WORKER_PROTOCOL_RESPONSE_BATCH;\n version: typeof WORKER_PROTOCOL_VERSION;\n responses: WorkerProtocolResponseMessage[];\n}\n\nconst WORKER_COMMAND_SET = new Set<string>(WORKER_COMMANDS);\n\nexport function isWorkerCommand(value: unknown): value is WorkerCommand {\n return typeof value === 'string' && WORKER_COMMAND_SET.has(value);\n}\n\nexport function isWorkerProtocolReadyMessage(value: unknown): value is WorkerProtocolReadyMessage {\n return isRecord(value) && value.type === WORKER_PROTOCOL_READY && value.version === WORKER_PROTOCOL_VERSION;\n}\n\nexport function isWorkerProtocolResponseMessage(value: unknown): value is WorkerProtocolResponseMessage {\n return (\n isRecord(value) &&\n value.type === WORKER_PROTOCOL_RESPONSE &&\n value.version === WORKER_PROTOCOL_VERSION &&\n typeof value.id === 'number' &&\n Number.isSafeInteger(value.id) &&\n typeof value.ok === 'boolean'\n );\n}\n\nexport function isWorkerProtocolRequestMessage(value: unknown): value is WorkerProtocolRequestMessage {\n return (\n isRecord(value) &&\n value.type === WORKER_PROTOCOL_REQUEST &&\n value.version === WORKER_PROTOCOL_VERSION &&\n typeof value.id === 'number' &&\n Number.isSafeInteger(value.id) &&\n typeof value.command === 'string' &&\n Array.isArray(value.args)\n );\n}\n\nexport function isWorkerProtocolRequestBatchMessage(value: unknown): value is WorkerProtocolRequestBatchMessage {\n return isWorkerProtocolBatch(value, WORKER_PROTOCOL_REQUEST_BATCH, 'requests');\n}\n\nexport function isWorkerProtocolResponseBatchMessage(value: unknown): value is WorkerProtocolResponseBatchMessage {\n if (!isWorkerProtocolBatch(value, WORKER_PROTOCOL_RESPONSE_BATCH, 'responses')) {\n return false;\n }\n for (const response of (value as WorkerProtocolResponseBatchMessage).responses) {\n if (!isWorkerProtocolResponseMessage(response)) return false;\n }\n return true;\n}\n\nfunction isWorkerProtocolBatch(value: unknown, type: string, items: string): boolean {\n return (\n isRecord(value) &&\n value.type === type &&\n value.version === WORKER_PROTOCOL_VERSION &&\n Array.isArray(value[items]) &&\n value[items].length > 0 &&\n value[items].length <= MAX_WORKER_BATCH_MESSAGES\n );\n}\n\nexport function isWorkerProtocolEnvelope(value: unknown): value is { type: string; id?: unknown } {\n return (\n isRecord(value) &&\n (value.type === WORKER_PROTOCOL_REQUEST ||\n value.type === WORKER_PROTOCOL_RESPONSE ||\n value.type === WORKER_PROTOCOL_REQUEST_BATCH ||\n value.type === WORKER_PROTOCOL_RESPONSE_BATCH ||\n value.type === WORKER_PROTOCOL_READY)\n );\n}\n\nexport function serializeWorkerError(error: unknown): SerializedWorkerError {\n if (isRecord(error)) {\n const code = stringOrUndefined(error.code);\n const name = stringOrUndefined(error.name) ?? code ?? 'Error';\n return {\n name,\n code,\n message: stringOrUndefined(error.message) ?? 'Unknown error',\n stack: stringOrUndefined(error.stack)\n };\n }\n return {\n name: 'Error',\n message: String(error)\n };\n}\n\nexport function deserializeWorkerError(error: SerializedWorkerError): Error {\n if (\n !isRecord(error) ||\n typeof error.name !== 'string' ||\n typeof error.message !== 'string' ||\n (error.code !== undefined && typeof error.code !== 'string') ||\n (error.stack !== undefined && typeof error.stack !== 'string')\n ) {\n throw workerProtocolError('WorkerProtocolError', 'invalid serialized worker error');\n }\n const deserialized = new Error(error.message);\n deserialized.name = error.name || error.code || 'Error';\n if (error.stack) {\n deserialized.stack = error.stack;\n }\n if (error.code) {\n Object.defineProperty(deserialized, 'code', {\n value: error.code,\n enumerable: true,\n configurable: true\n });\n }\n return deserialized;\n}\n\nexport function workerProtocolError(name: string, message: string, code = name): Error {\n const error = new Error(message);\n error.name = name;\n Object.defineProperty(error, 'code', {\n value: code,\n enumerable: true,\n configurable: true\n });\n return error;\n}\n\nexport function prepareWorkerCommandPayload<M extends WorkerCommand>(\n command: M,\n args: WorkerCommandArgs<M>\n): { args: PreparedWorkerCommandArgs<M>; transfer: Transferable[] } {\n if (command === 'autocommit') {\n const [mode, inner, innerArgs] = args as WorkerCommandArgs<'autocommit'>;\n if (isAutocommitCommand(inner) && Array.isArray(innerArgs)) {\n // The normal packer expects a transaction ID. Use a placeholder, then remove it.\n const prepared = prepareWorkerCommandPayload(inner, [0, ...innerArgs] as never);\n return {\n args: [mode, inner, (prepared.args as unknown[]).slice(1)],\n transfer: prepared.transfer\n };\n }\n }\n\n if (\n command === 'get' ||\n command === 'has' ||\n command === 'delete' ||\n command === 'getByIndex' ||\n command === 'put'\n ) {\n const keyIndex = command === 'getByIndex' ? 3 : 2;\n let copiedArgs: unknown[] | null = null;\n let transfer: Transferable[] | null = null;\n for (let index = keyIndex; index <= (command === 'put' ? 3 : keyIndex); index += 1) {\n const value = args[index];\n if (\n value instanceof Uint8Array &&\n value.buffer instanceof ArrayBuffer &&\n (value.byteOffset !== 0 || value.byteLength !== value.buffer.byteLength)\n ) {\n const owned = copyToOwnedUint8Array(value);\n copiedArgs ??= [...args];\n copiedArgs[index] = owned;\n (transfer ??= []).push(owned.buffer);\n }\n }\n if (copiedArgs !== null) {\n return { args: copiedArgs, transfer: transfer ?? EMPTY_TRANSFERABLES };\n }\n }\n\n if (command === 'importSnapshot') {\n const data = args[0];\n if (data instanceof Uint8Array) {\n const owned = copyToOwnedUint8Array(data);\n return {\n args: [owned] as WorkerCommandArgs<M>,\n transfer: [owned.buffer]\n };\n }\n }\n\n if (command === 'getMany' || command === 'deleteMany') {\n const [txId, store, keys] = args as WorkerCommandArgs<'getMany'> | WorkerCommandArgs<'deleteMany'>;\n if (Array.isArray(keys) && keys.length > 0) {\n const packed = packBinaryList(keys);\n return {\n args: [txId, store, packed],\n transfer: [packed.bytes.buffer]\n };\n }\n }\n\n if (command === 'putMany') {\n const [txId, store, entries, options] = args as WorkerCommandArgs<'putMany'>;\n if (Array.isArray(entries) && entries.length > 0) {\n const packed = packBinaryPairs(entries);\n return {\n args: [txId, store, packed, options],\n transfer: [packed.bytes.buffer]\n };\n }\n }\n\n if (command === 'applyBatch') {\n const [txId, store, ops] = args as WorkerCommandArgs<'applyBatch'>;\n if (Array.isArray(ops) && ops.length > 0) {\n const packed = packBatchOps(ops);\n return {\n args: [txId, store, packed],\n transfer: [packed.bytes.buffer]\n };\n }\n }\n\n return { args, transfer: EMPTY_TRANSFERABLES };\n}\n\nexport function decodeWorkerCommandPayload<M extends WorkerCommand>(\n command: M,\n args: PreparedWorkerCommandArgs<M>\n): WorkerCommandArgs<M> {\n if (command === 'autocommit') {\n const [mode, inner, innerArgs] = args as WorkerCommandArgs<'autocommit'>;\n if (isAutocommitCommand(inner) && Array.isArray(innerArgs)) {\n const decoded = decodeWorkerCommandPayload(inner, [0, ...innerArgs]) as unknown[];\n return [mode, inner, decoded.slice(1)] as WorkerCommandArgs<M>;\n }\n }\n\n if (command === 'getMany' || command === 'deleteMany') {\n const [txId, store, keys] = args as WorkerCommandArgs<'getMany'> | WorkerCommandArgs<'deleteMany'>;\n if (!Array.isArray(keys)) {\n if (!isPackedBinaryList(keys)) {\n throw workerProtocolError('WorkerProtocolError', 'invalid packed binary-list argument');\n }\n return [txId, store, unpackBinaryList(keys)] as WorkerCommandArgs<M>;\n }\n }\n\n if (command === 'putMany') {\n const [txId, store, entries, options] = args as WorkerCommandArgs<'putMany'>;\n if (!Array.isArray(entries)) {\n if (!isPackedBinaryList(entries)) {\n throw workerProtocolError('WorkerProtocolError', 'invalid packed putMany argument');\n }\n return [txId, store, unpackBinaryPairs(entries), options] as WorkerCommandArgs<M>;\n }\n }\n\n if (command === 'applyBatch') {\n const [txId, store, ops] = args as WorkerCommandArgs<'applyBatch'>;\n if (!Array.isArray(ops)) {\n if (!isPackedBatchOps(ops)) {\n throw workerProtocolError('WorkerProtocolError', 'invalid packed batch argument');\n }\n return [txId, store, unpackBatchOps(ops)] as WorkerCommandArgs<M>;\n }\n }\n\n return args;\n}\n\nexport function packedBinaryListBytes(value: unknown): Uint8Array | null {\n return isPackedBinaryList(value) ? value.bytes : null;\n}\n\nexport function packedBatchOpsBytes(value: unknown): Uint8Array | null {\n return isPackedBatchOps(value) ? value.bytes : null;\n}\n\nexport function unpackPackedBinaryList(bytes: Uint8Array): Uint8Array[] {\n return unpackBinaryList({ __moyodbPacked: PACKED_BINARY_LIST_V1, bytes });\n}\n\nexport function unpackPackedBinaryPairs(bytes: Uint8Array): Array<[Uint8Array, Uint8Array]> {\n return unpackBinaryPairs({ __moyodbPacked: PACKED_BINARY_LIST_V1, bytes });\n}\n\nexport function unpackPackedBinaryPairKeys(bytes: Uint8Array): Uint8Array[] {\n return unpackBinaryPairKeys({ __moyodbPacked: PACKED_BINARY_LIST_V1, bytes });\n}\n\nexport function unpackPackedBatchOps(bytes: Uint8Array): Array<BatchOp> {\n return unpackBatchOps({ __moyodbPacked: PACKED_BATCH_OPS_V1, bytes });\n}\n\nexport function unpackPackedBatchOpKeys(bytes: Uint8Array): PackedBatchOpKey[] {\n return unpackBatchOpKeys({ __moyodbPacked: PACKED_BATCH_OPS_V1, bytes });\n}\n\nexport function packedOptionalValues(bytes: Uint8Array): PackedOptionalValuesV1 {\n return { __moyodbPacked: PACKED_OPTIONAL_VALUES_V1, bytes };\n}\n\nexport function unpackPackedOptionalValues(bytes: Uint8Array): Array<Uint8Array | null> {\n if (!(bytes instanceof Uint8Array) || bytes.byteLength < 4) {\n throw workerProtocolError('WorkerProtocolError', 'invalid packed optional-values payload');\n }\n const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);\n const count = view.getUint32(0, true);\n const metadataBytes = checkedByteCount(count, 4, 'packed optional-values metadata');\n const payloadOffset = checkedAdd(4, metadataBytes, 'packed optional-values header');\n if (payloadOffset > bytes.byteLength) {\n throw workerProtocolError('WorkerProtocolError', 'packed optional-values metadata exceeds payload length');\n }\n const items = new Array<Uint8Array | null>(count);\n let readOffset = payloadOffset;\n for (let index = 0; index < count; index += 1) {\n const byteLength = view.getUint32(4 + index * 4, true);\n if (byteLength === U32_MAX) {\n items[index] = null;\n continue;\n }\n const end = readOffset + byteLength;\n if (end > bytes.byteLength) {\n throw workerProtocolError('WorkerProtocolError', 'packed optional-values item exceeds payload length');\n }\n items[index] = bytes.subarray(readOffset, end);\n readOffset = end;\n }\n if (readOffset !== bytes.byteLength) {\n throw workerProtocolError('WorkerProtocolError', 'packed optional-values payload has trailing bytes');\n }\n return items;\n}\n\nexport function prepareWorkerResponsePayload<M extends WorkerCommand>(\n command: M,\n result: WorkerCommandResult<M>\n): { result: unknown; transfer: Transferable[] } {\n if (command === 'getMany' && isPackedOptionalValues(result)) {\n return {\n result,\n transfer: collectDirectBinaryTransferable(result.bytes)\n };\n }\n\n if (command === 'scanByIndexPage') {\n const page = result as WorkerCommandResult<'scanByIndexPage'>;\n if (isRecord(page) && Array.isArray(page.rows)) {\n const packed = page.rows.length > 0 ? packScanRows(page.rows) : null;\n const response: PackedIndexScanPage = { rows: packed ?? page.rows, cursor: page.cursor };\n const transfer = packed ? [packed.bytes.buffer] : collectTransferablesForValue(page.rows);\n const cursorBuffer = directBinaryTransferable(page.cursor);\n return {\n result: response,\n transfer: cursorBuffer === null ? transfer : [...transfer, cursorBuffer]\n };\n }\n }\n\n if (command === 'getMany') {\n const values = result as WorkerCommandResult<'getMany'>;\n if (Array.isArray(values) && values.length > 0) {\n const packed = packNullableBinaryList(values);\n if (packed) {\n return {\n result: packed,\n transfer: [packed.bytes.buffer]\n };\n }\n }\n return {\n result,\n transfer: collectTransferablesForValue(result)\n };\n }\n\n if (command === 'scan' || command === 'scanByIndex') {\n const rows = result as WorkerCommandResult<'scan'>;\n if (Array.isArray(rows) && rows.length > 0) {\n const packed = packScanRows(rows);\n if (packed) {\n return {\n result: packed,\n transfer: [packed.bytes.buffer]\n };\n }\n }\n return {\n result,\n transfer: collectTransferablesForValue(result)\n };\n }\n\n if (command === 'get' || command === 'getByIndex' || command === 'exportSnapshot') {\n return {\n result,\n transfer: collectDirectBinaryTransferable(result)\n };\n }\n\n if (command === 'changesSince') {\n return {\n result,\n transfer: collectChangeFeedTransferables(result)\n };\n }\n\n // Remaining result types contain no binary payloads, so they need no buffer walk.\n return {\n result,\n transfer: []\n };\n}\n\nexport function decodeWorkerResponsePayload<M extends WorkerCommand>(\n command: M,\n result: unknown\n): WorkerCommandResult<M> {\n if (command === 'getMany' && isPackedNullableBinaryList(result)) {\n return unpackNullableBinaryList(result);\n }\n\n if (command === 'getMany' && isPackedOptionalValues(result)) {\n return unpackPackedOptionalValues(result.bytes) as WorkerCommandResult<M>;\n }\n\n if (command === 'getMany' && !Array.isArray(result)) {\n throw workerProtocolError('WorkerProtocolError', 'invalid packed getMany response');\n }\n\n if (command === 'scanByIndexPage') {\n if (\n !isRecord(result) ||\n (!Array.isArray(result.rows) && !isPackedScanRows(result.rows)) ||\n (result.cursor !== null && !(result.cursor instanceof Uint8Array))\n ) {\n throw workerProtocolError('WorkerProtocolError', 'invalid packed index scan page response');\n }\n const rows = isPackedScanRows(result.rows) ? unpackScanRows(result.rows) : result.rows;\n return { rows, cursor: result.cursor } as WorkerCommandResult<M>;\n }\n\n if ((command === 'scan' || command === 'scanByIndex') && isPackedScanRows(result)) {\n return unpackScanRows(result);\n }\n\n if ((command === 'scan' || command === 'scanByIndex') && !Array.isArray(result)) {\n throw workerProtocolError('WorkerProtocolError', 'invalid packed scan response');\n }\n\n return result;\n}\n\nexport function collectTransferablesForValue(value: unknown): Transferable[] {\n const direct = directBinaryTransferable(value);\n if (direct !== null) {\n return [direct];\n }\n if (value === null || value === undefined || typeof value !== 'object') {\n return EMPTY_TRANSFERABLES;\n }\n\n const buffers = new Set<ArrayBuffer>();\n const seen = new WeakSet<object>();\n collectTransferableBuffers(value, buffers, seen);\n return buffers.size === 0 ? EMPTY_TRANSFERABLES : Array.from(buffers);\n}\n\n/**\n * Capture the message before batching can observe later mutations. Listed\n * transferables move into the snapshot; other ArrayBuffers are cloned.\n * SharedArrayBuffers remain shared. byteLength is a batch-size estimate.\n */\nexport function captureWorkerPayload<T>(\n value: T,\n transfer: Transferable[]\n): { value: T; transfer: Transferable[]; byteLength: number } {\n const captured =\n transfer.length > 0\n ? structuredClone(value, { transfer: transfer.length === 1 ? transfer : Array.from(new Set(transfer)) })\n : structuredClone(value);\n const buffers = new Set<ArrayBuffer>();\n const seen = new WeakSet<object>();\n let byteLength = 0;\n const visit = (item: unknown): void => {\n if (typeof item === 'string') {\n byteLength += 8 + item.length * 2;\n return;\n }\n if (item === null || typeof item !== 'object') {\n byteLength += 8;\n return;\n }\n if (seen.has(item)) return;\n seen.add(item);\n byteLength += 8;\n if (item instanceof ArrayBuffer) {\n buffers.add(item);\n byteLength += item.byteLength;\n } else if (typeof SharedArrayBuffer !== 'undefined' && item instanceof SharedArrayBuffer) {\n byteLength += item.byteLength;\n } else if (ArrayBuffer.isView(item)) {\n visit(item.buffer);\n } else if (Array.isArray(item)) {\n for (const child of item) visit(child);\n } else if (item instanceof Map) {\n for (const [key, child] of item) {\n visit(key);\n visit(child);\n }\n } else if (item instanceof Set) {\n for (const child of item) visit(child);\n } else {\n const record = item as Record<string, unknown>;\n for (const key in record) {\n if (Object.prototype.hasOwnProperty.call(record, key)) {\n byteLength += 8 + key.length * 2;\n visit(record[key]);\n }\n }\n }\n };\n visit(captured);\n return {\n value: captured,\n transfer: buffers.size === 0 ? EMPTY_TRANSFERABLES : Array.from(buffers),\n byteLength\n };\n}\n\nfunction collectDirectBinaryTransferable(value: unknown): Transferable[] {\n const direct = directBinaryTransferable(value);\n return direct === null ? EMPTY_TRANSFERABLES : [direct];\n}\n\nfunction directBinaryTransferable(value: unknown): ArrayBuffer | null {\n if (value instanceof ArrayBuffer) {\n return value;\n }\n if (ArrayBuffer.isView(value)) {\n const buffer = value.buffer;\n if (buffer instanceof ArrayBuffer && value.byteOffset === 0 && value.byteLength === buffer.byteLength) {\n return buffer;\n }\n }\n return null;\n}\n\nfunction collectChangeFeedTransferables(value: unknown): Transferable[] {\n if (!isRecord(value) || !Array.isArray(value.changes) || value.changes.length === 0) {\n return EMPTY_TRANSFERABLES;\n }\n\n let buffers: Set<ArrayBuffer> | null = null;\n for (const change of value.changes) {\n if (!isRecord(change)) {\n continue;\n }\n const key = directBinaryTransferable(change.key);\n if (key !== null) {\n buffers ??= new Set<ArrayBuffer>();\n buffers.add(key);\n }\n const changedValue = directBinaryTransferable(change.value);\n if (changedValue !== null) {\n buffers ??= new Set<ArrayBuffer>();\n buffers.add(changedValue);\n }\n }\n return buffers === null || buffers.size === 0 ? EMPTY_TRANSFERABLES : Array.from(buffers);\n}\n\nfunction collectTransferableBuffers(value: unknown, buffers: Set<ArrayBuffer>, seen: WeakSet<object>): void {\n if (value === null || value === undefined) {\n return;\n }\n if (value instanceof ArrayBuffer) {\n buffers.add(value);\n return;\n }\n if (ArrayBuffer.isView(value)) {\n const buffer = value.buffer;\n if (buffer instanceof ArrayBuffer && value.byteOffset === 0 && value.byteLength === buffer.byteLength) {\n buffers.add(buffer);\n }\n return;\n }\n if (typeof value !== 'object') {\n return;\n }\n const object = value;\n if (seen.has(object)) {\n return;\n }\n seen.add(object);\n if (Array.isArray(value)) {\n for (const item of value) {\n collectTransferableBuffers(item, buffers, seen);\n }\n return;\n }\n const record = value as Record<string, unknown>;\n for (const key in record) {\n if (Object.prototype.hasOwnProperty.call(record, key)) {\n collectTransferableBuffers(record[key], buffers, seen);\n }\n }\n}\n\nfunction packBinaryPairs(entries: Array<[Uint8Array, Uint8Array]>): PackedBinaryListV1 {\n const entryCount = entries.length;\n const count = checkedU32(entryCount * 2, 'packed putMany item count');\n const metadataBytes = checkedByteCount(count, 4, 'packed putMany metadata');\n let payloadBytes = 0;\n for (let index = 0; index < entryCount; index += 1) {\n const entry = entries[index];\n const key = entry[0];\n const value = entry[1];\n if (!(key instanceof Uint8Array) || !(value instanceof Uint8Array)) {\n throw workerProtocolError('WorkerProtocolError', 'putMany entry key/value is not a Uint8Array');\n }\n const keyLength = checkedU32(key.byteLength, 'putMany key length');\n const valueLength = checkedU32(value.byteLength, 'putMany value length');\n payloadBytes += keyLength + valueLength;\n if (payloadBytes > U32_MAX) {\n throw workerProtocolError('WorkerProtocolError', 'packed putMany payload exceeds 32-bit payload limit');\n }\n }\n const payloadOffset = checkedAdd(4, metadataBytes, 'packed putMany header');\n const totalBytes = checkedAdd(payloadOffset, payloadBytes, 'packed putMany total');\n const bytes = new Uint8Array(totalBytes);\n const view = new DataView(bytes.buffer);\n view.setUint32(0, count, true);\n let metadataOffset = 4;\n let writeOffset = payloadOffset;\n for (let index = 0; index < entryCount; index += 1) {\n const entry = entries[index];\n const key = entry[0];\n const value = entry[1];\n const keyLength = key.byteLength;\n const valueLength = value.byteLength;\n view.setUint32(metadataOffset, keyLength, true);\n metadataOffset += 4;\n view.setUint32(metadataOffset, valueLength, true);\n metadataOffset += 4;\n bytes.set(key, writeOffset);\n writeOffset += keyLength;\n bytes.set(value, writeOffset);\n writeOffset += valueLength;\n }\n return {\n __moyodbPacked: PACKED_BINARY_LIST_V1,\n bytes\n };\n}\n\nfunction packBinaryList(items: Uint8Array[]): PackedBinaryListV1 {\n const count = items.length;\n const metadataBytes = checkedByteCount(count, 4, 'packed binary-list metadata');\n let payloadBytes = 0;\n for (let index = 0; index < count; index += 1) {\n const item = items[index];\n if (!(item instanceof Uint8Array)) {\n throw workerProtocolError('WorkerProtocolError', 'binary-list payload item is not a Uint8Array');\n }\n const itemLength = checkedU32(item.byteLength, 'binary-list item length');\n payloadBytes += itemLength;\n if (payloadBytes > U32_MAX) {\n throw workerProtocolError('WorkerProtocolError', 'packed binary-list payload exceeds 32-bit payload limit');\n }\n }\n const payloadOffset = checkedAdd(4, metadataBytes, 'packed binary-list header');\n const totalBytes = checkedAdd(payloadOffset, payloadBytes, 'packed binary-list total');\n const bytes = new Uint8Array(totalBytes);\n const view = new DataView(bytes.buffer);\n view.setUint32(0, count, true);\n let metadataOffset = 4;\n let writeOffset = payloadOffset;\n for (let index = 0; index < count; index += 1) {\n const item = items[index];\n const itemLength = item.byteLength;\n view.setUint32(metadataOffset, itemLength, true);\n metadataOffset += 4;\n bytes.set(item, writeOffset);\n writeOffset += itemLength;\n }\n return {\n __moyodbPacked: PACKED_BINARY_LIST_V1,\n bytes\n };\n}\n\nfunction unpackBinaryList(payload: PackedBinaryListV1): Uint8Array[] {\n const bytes = payload.bytes;\n if (!(bytes instanceof Uint8Array) || bytes.byteLength < 4) {\n throw workerProtocolError('WorkerProtocolError', 'invalid packed binary-list payload');\n }\n const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);\n const count = view.getUint32(0, true);\n const metadataBytes = checkedByteCount(count, 4, 'packed binary-list metadata');\n const payloadOffset = checkedAdd(4, metadataBytes, 'packed binary-list header');\n if (payloadOffset > bytes.byteLength) {\n throw workerProtocolError('WorkerProtocolError', 'packed binary-list metadata exceeds payload length');\n }\n\n const items = new Array<Uint8Array>(count);\n let metadataOffset = 4;\n let readOffset = payloadOffset;\n for (let index = 0; index < count; index += 1) {\n const byteLength = view.getUint32(metadataOffset, true);\n metadataOffset += 4;\n const end = readOffset + byteLength;\n if (end > U32_MAX || end > bytes.byteLength) {\n throw workerProtocolError('WorkerProtocolError', 'packed binary-list item exceeds payload length');\n }\n items[index] = bytes.subarray(readOffset, end);\n readOffset = end;\n }\n if (readOffset !== bytes.byteLength) {\n throw workerProtocolError('WorkerProtocolError', 'packed binary-list payload has trailing bytes');\n }\n return items;\n}\n\nfunction unpackBinaryPairs(payload: PackedBinaryListV1): Array<[Uint8Array, Uint8Array]> {\n const bytes = payload.bytes;\n if (!(bytes instanceof Uint8Array) || bytes.byteLength < 4) {\n throw workerProtocolError('WorkerProtocolError', 'invalid packed putMany payload');\n }\n const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);\n const itemCount = view.getUint32(0, true);\n if (itemCount % 2 !== 0) {\n throw workerProtocolError('WorkerProtocolError', 'packed putMany payload has an odd item count');\n }\n const metadataBytes = checkedByteCount(itemCount, 4, 'packed putMany metadata');\n const payloadOffset = checkedAdd(4, metadataBytes, 'packed putMany header');\n if (payloadOffset > bytes.byteLength) {\n throw workerProtocolError('WorkerProtocolError', 'packed putMany metadata exceeds payload length');\n }\n\n const entryCount = itemCount / 2;\n const entries = new Array<[Uint8Array, Uint8Array]>(entryCount);\n let metadataOffset = 4;\n let readOffset = payloadOffset;\n for (let index = 0; index < entryCount; index += 1) {\n const keyLength = view.getUint32(metadataOffset, true);\n const valueLength = view.getUint32(metadataOffset + 4, true);\n metadataOffset += 8;\n\n const keyEnd = readOffset + keyLength;\n if (keyEnd > U32_MAX || keyEnd > bytes.byteLength) {\n throw workerProtocolError('WorkerProtocolError', 'packed putMany key exceeds payload length');\n }\n const valueEnd = keyEnd + valueLength;\n if (valueEnd > U32_MAX || valueEnd > bytes.byteLength) {\n throw workerProtocolError('WorkerProtocolError', 'packed putMany value exceeds payload length');\n }\n entries[index] = [bytes.subarray(readOffset, keyEnd), bytes.subarray(keyEnd, valueEnd)];\n readOffset = valueEnd;\n }\n if (readOffset !== bytes.byteLength) {\n throw workerProtocolError('WorkerProtocolError', 'packed putMany payload has trailing bytes');\n }\n return entries;\n}\n\nfunction unpackBinaryPairKeys(payload: PackedBinaryListV1): Uint8Array[] {\n const bytes = payload.bytes;\n if (!(bytes instanceof Uint8Array) || bytes.byteLength < 4) {\n throw workerProtocolError('WorkerProtocolError', 'invalid packed putMany payload');\n }\n const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);\n const itemCount = view.getUint32(0, true);\n if (itemCount % 2 !== 0) {\n throw workerProtocolError('WorkerProtocolError', 'packed putMany payload has an odd item count');\n }\n const metadataBytes = checkedByteCount(itemCount, 4, 'packed putMany metadata');\n const payloadOffset = checkedAdd(4, metadataBytes, 'packed putMany header');\n if (payloadOffset > bytes.byteLength) {\n throw workerProtocolError('WorkerProtocolError', 'packed putMany metadata exceeds payload length');\n }\n\n const entryCount = itemCount / 2;\n const keys = new Array<Uint8Array>(entryCount);\n let metadataOffset = 4;\n let readOffset = payloadOffset;\n for (let index = 0; index < entryCount; index += 1) {\n const keyLength = view.getUint32(metadataOffset, true);\n const valueLength = view.getUint32(metadataOffset + 4, true);\n metadataOffset += 8;\n\n const keyEnd = readOffset + keyLength;\n if (keyEnd > U32_MAX || keyEnd > bytes.byteLength) {\n throw workerProtocolError('WorkerProtocolError', 'packed putMany key exceeds payload length');\n }\n const valueEnd = keyEnd + valueLength;\n if (valueEnd > U32_MAX || valueEnd > bytes.byteLength) {\n throw workerProtocolError('WorkerProtocolError', 'packed putMany value exceeds payload length');\n }\n keys[index] = bytes.subarray(readOffset, keyEnd);\n readOffset = valueEnd;\n }\n if (readOffset !== bytes.byteLength) {\n throw workerProtocolError('WorkerProtocolError', 'packed putMany payload has trailing bytes');\n }\n return keys;\n}\n\nfunction packNullableBinaryList(items: Array<Uint8Array | null>): PackedNullableBinaryListV1 | null {\n const count = items.length;\n const metadataBytes = checkedByteCount(count, 5, 'packed nullable binary-list metadata');\n let payloadBytes = 0;\n for (let index = 0; index < count; index += 1) {\n const item = items[index];\n if (item === null) {\n continue;\n }\n if (!(item instanceof Uint8Array)) {\n throw workerProtocolError(\n 'WorkerProtocolError',\n 'nullable binary-list payload item is not a Uint8Array or null'\n );\n }\n const itemLength = checkedU32(item.byteLength, 'nullable binary-list item length');\n payloadBytes += itemLength;\n if (payloadBytes > U32_MAX) {\n throw workerProtocolError(\n 'WorkerProtocolError',\n 'packed nullable binary-list payload exceeds 32-bit payload limit'\n );\n }\n }\n const payloadOffset = checkedAdd(4, metadataBytes, 'packed nullable binary-list header');\n const totalBytes = checkedAdd(payloadOffset, payloadBytes, 'packed nullable binary-list total');\n if (totalBytes > MAX_PACKED_RESPONSE_BYTES) {\n return null;\n }\n const bytes = new Uint8Array(totalBytes);\n const view = new DataView(bytes.buffer);\n view.setUint32(0, count, true);\n let metadataOffset = 4;\n let writeOffset = payloadOffset;\n for (let index = 0; index < count; index += 1) {\n const item = items[index];\n if (item === null) {\n view.setUint8(metadataOffset, 0);\n view.setUint32(metadataOffset + 1, 0, true);\n metadataOffset += 5;\n continue;\n }\n const itemLength = item.byteLength;\n view.setUint8(metadataOffset, 1);\n view.setUint32(metadataOffset + 1, itemLength, true);\n metadataOffset += 5;\n bytes.set(item, writeOffset);\n writeOffset += itemLength;\n }\n return {\n __moyodbPacked: PACKED_NULLABLE_BINARY_LIST_V1,\n bytes\n };\n}\n\nfunction unpackNullableBinaryList(payload: PackedNullableBinaryListV1): Array<Uint8Array | null> {\n const bytes = payload.bytes;\n if (!(bytes instanceof Uint8Array) || bytes.byteLength < 4) {\n throw workerProtocolError('WorkerProtocolError', 'invalid packed nullable binary-list payload');\n }\n const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);\n const count = view.getUint32(0, true);\n const metadataBytes = checkedByteCount(count, 5, 'packed nullable binary-list metadata');\n const payloadOffset = checkedAdd(4, metadataBytes, 'packed nullable binary-list header');\n if (payloadOffset > bytes.byteLength) {\n throw workerProtocolError('WorkerProtocolError', 'packed nullable binary-list metadata exceeds payload length');\n }\n\n const items = new Array<Uint8Array | null>(count);\n let metadataOffset = 4;\n let readOffset = payloadOffset;\n for (let index = 0; index < count; index += 1) {\n const present = view.getUint8(metadataOffset);\n const byteLength = view.getUint32(metadataOffset + 1, true);\n metadataOffset += 5;\n if (present === 0) {\n if (byteLength !== 0) {\n throw workerProtocolError(\n 'WorkerProtocolError',\n 'packed nullable binary-list null item has a payload length'\n );\n }\n items[index] = null;\n continue;\n }\n if (present !== 1) {\n throw workerProtocolError(\n 'WorkerProtocolError',\n `packed nullable binary-list item has invalid presence byte: ${present}`\n );\n }\n const end = readOffset + byteLength;\n if (end > U32_MAX || end > bytes.byteLength) {\n throw workerProtocolError('WorkerProtocolError', 'packed nullable binary-list item exceeds payload length');\n }\n items[index] = bytes.subarray(readOffset, end);\n readOffset = end;\n }\n if (readOffset !== bytes.byteLength) {\n throw workerProtocolError('WorkerProtocolError', 'packed nullable binary-list payload has trailing bytes');\n }\n return items;\n}\n\nfunction packScanRows(rows: Array<{ key: Uint8Array; value: Uint8Array }>): PackedScanRowsV1 | null {\n const count = rows.length;\n const metadataBytes = checkedByteCount(count, 8, 'packed scan row metadata');\n let payloadBytes = 0;\n for (let index = 0; index < count; index += 1) {\n const row = rows[index];\n if (!isRecord(row) || !(row.key instanceof Uint8Array) || !(row.value instanceof Uint8Array)) {\n throw workerProtocolError('WorkerProtocolError', 'scan row payload key/value is not a Uint8Array');\n }\n const keyLength = checkedU32(row.key.byteLength, 'scan row key length');\n const valueLength = checkedU32(row.value.byteLength, 'scan row value length');\n payloadBytes += keyLength + valueLength;\n if (payloadBytes > U32_MAX) {\n throw workerProtocolError('WorkerProtocolError', 'packed scan row payload exceeds 32-bit payload limit');\n }\n }\n const payloadOffset = checkedAdd(4, metadataBytes, 'packed scan row header');\n const totalBytes = checkedAdd(payloadOffset, payloadBytes, 'packed scan row total');\n if (totalBytes > MAX_PACKED_RESPONSE_BYTES) {\n return null;\n }\n const bytes = new Uint8Array(totalBytes);\n const view = new DataView(bytes.buffer);\n view.setUint32(0, count, true);\n let metadataOffset = 4;\n let writeOffset = payloadOffset;\n for (let index = 0; index < count; index += 1) {\n const row = rows[index];\n const key = row.key;\n const value = row.value;\n const keyLength = key.byteLength;\n const valueLength = value.byteLength;\n view.setUint32(metadataOffset, keyLength, true);\n view.setUint32(metadataOffset + 4, valueLength, true);\n metadataOffset += 8;\n bytes.set(key, writeOffset);\n writeOffset += keyLength;\n bytes.set(value, writeOffset);\n writeOffset += valueLength;\n }\n return {\n __moyodbPacked: PACKED_SCAN_ROWS_V1,\n bytes\n };\n}\n\nfunction unpackScanRows(payload: PackedScanRowsV1): Array<{ key: Uint8Array; value: Uint8Array }> {\n const bytes = payload.bytes;\n if (!(bytes instanceof Uint8Array) || bytes.byteLength < 4) {\n throw workerProtocolError('WorkerProtocolError', 'invalid packed scan row payload');\n }\n const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);\n const count = view.getUint32(0, true);\n const metadataBytes = checkedByteCount(count, 8, 'packed scan row metadata');\n const payloadOffset = checkedAdd(4, metadataBytes, 'packed scan row header');\n if (payloadOffset > bytes.byteLength) {\n throw workerProtocolError('WorkerProtocolError', 'packed scan row metadata exceeds payload length');\n }\n\n const rows = new Array<{ key: Uint8Array; value: Uint8Array }>(count);\n let metadataOffset = 4;\n let readOffset = payloadOffset;\n for (let index = 0; index < count; index += 1) {\n const keyLength = view.getUint32(metadataOffset, true);\n const valueLength = view.getUint32(metadataOffset + 4, true);\n metadataOffset += 8;\n const keyEnd = readOffset + keyLength;\n if (keyEnd > U32_MAX || keyEnd > bytes.byteLength) {\n throw workerProtocolError('WorkerProtocolError', 'packed scan row key exceeds payload length');\n }\n const valueEnd = keyEnd + valueLength;\n if (valueEnd > U32_MAX || valueEnd > bytes.byteLength) {\n throw workerProtocolError('WorkerProtocolError', 'packed scan row value exceeds payload length');\n }\n rows[index] = {\n key: bytes.subarray(readOffset, keyEnd),\n value: bytes.subarray(keyEnd, valueEnd)\n };\n readOffset = valueEnd;\n }\n if (readOffset !== bytes.byteLength) {\n throw workerProtocolError('WorkerProtocolError', 'packed scan row payload has trailing bytes');\n }\n return rows;\n}\n\nfunction packBatchOps(ops: Array<BatchOp>): PackedBatchOpsV1 {\n const count = ops.length;\n const metadataBytes = checkedByteCount(count, 9, 'packed batch metadata');\n let payloadBytes = 0;\n for (let index = 0; index < count; index += 1) {\n const op: unknown = ops[index];\n if (!isRecord(op) || (op.kind !== 'put' && op.kind !== 'delete')) {\n throw workerProtocolError('WorkerProtocolError', 'batch operation kind is not put or delete');\n }\n if (!(op.key instanceof Uint8Array)) {\n throw workerProtocolError('WorkerProtocolError', 'batch operation key is not a Uint8Array');\n }\n const keyLength = checkedU32(op.key.byteLength, 'batch operation key length');\n payloadBytes += keyLength;\n if (payloadBytes > U32_MAX) {\n throw workerProtocolError('WorkerProtocolError', 'packed batch payload exceeds 32-bit payload limit');\n }\n if (op.kind === 'put') {\n if (!(op.value instanceof Uint8Array)) {\n throw workerProtocolError('WorkerProtocolError', 'batch put value is not a Uint8Array');\n }\n const valueLength = checkedU32(op.value.byteLength, 'batch put value length');\n payloadBytes += valueLength;\n if (payloadBytes > U32_MAX) {\n throw workerProtocolError('WorkerProtocolError', 'packed batch payload exceeds 32-bit payload limit');\n }\n }\n }\n const payloadOffset = checkedAdd(4, metadataBytes, 'packed batch header');\n const totalBytes = checkedAdd(payloadOffset, payloadBytes, 'packed batch total');\n const bytes = new Uint8Array(totalBytes);\n const view = new DataView(bytes.buffer);\n view.setUint32(0, count, true);\n let metadataOffset = 4;\n let writeOffset = payloadOffset;\n for (let index = 0; index < count; index += 1) {\n const op = ops[index];\n const key = op.key;\n const keyLength = key.byteLength;\n const valueLength = op.kind === 'put' ? op.value.byteLength : 0;\n view.setUint8(metadataOffset, op.kind === 'put' ? BATCH_OP_PUT : BATCH_OP_DELETE);\n view.setUint32(metadataOffset + 1, keyLength, true);\n view.setUint32(metadataOffset + 5, valueLength, true);\n metadataOffset += 9;\n bytes.set(key, writeOffset);\n writeOffset += keyLength;\n if (op.kind === 'put') {\n bytes.set(op.value, writeOffset);\n writeOffset += valueLength;\n }\n }\n return {\n __moyodbPacked: PACKED_BATCH_OPS_V1,\n bytes\n };\n}\n\nfunction unpackBatchOps(payload: PackedBatchOpsV1): Array<BatchOp> {\n const bytes = payload.bytes;\n if (!(bytes instanceof Uint8Array) || bytes.byteLength < 4) {\n throw workerProtocolError('WorkerProtocolError', 'invalid packed batch payload');\n }\n const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);\n const count = view.getUint32(0, true);\n const metadataBytes = checkedByteCount(count, 9, 'packed batch metadata');\n const payloadOffset = checkedAdd(4, metadataBytes, 'packed batch header');\n if (payloadOffset > bytes.byteLength) {\n throw workerProtocolError('WorkerProtocolError', 'packed batch metadata exceeds payload length');\n }\n\n const ops = new Array<BatchOp>(count);\n let metadataOffset = 4;\n let readOffset = payloadOffset;\n for (let index = 0; index < count; index += 1) {\n const kind = view.getUint8(metadataOffset);\n const keyLength = view.getUint32(metadataOffset + 1, true);\n const valueLength = view.getUint32(metadataOffset + 5, true);\n metadataOffset += 9;\n\n const keyEnd = readOffset + keyLength;\n if (keyEnd > U32_MAX || keyEnd > bytes.byteLength) {\n throw workerProtocolError('WorkerProtocolError', 'packed batch key exceeds payload length');\n }\n const key = bytes.subarray(readOffset, keyEnd);\n readOffset = keyEnd;\n\n if (kind === BATCH_OP_DELETE) {\n if (valueLength !== 0) {\n throw workerProtocolError('WorkerProtocolError', 'packed delete operation has a value payload');\n }\n ops[index] = { kind: 'delete', key };\n continue;\n }\n\n if (kind !== BATCH_OP_PUT) {\n throw workerProtocolError('WorkerProtocolError', `packed batch operation has invalid kind byte: ${kind}`);\n }\n const valueEnd = readOffset + valueLength;\n if (valueEnd > U32_MAX || valueEnd > bytes.byteLength) {\n throw workerProtocolError('WorkerProtocolError', 'packed batch value exceeds payload length');\n }\n ops[index] = { kind: 'put', key, value: bytes.subarray(readOffset, valueEnd) };\n readOffset = valueEnd;\n }\n if (readOffset !== bytes.byteLength) {\n throw workerProtocolError('WorkerProtocolError', 'packed batch payload has trailing bytes');\n }\n return ops;\n}\n\nfunction unpackBatchOpKeys(payload: PackedBatchOpsV1): PackedBatchOpKey[] {\n const bytes = payload.bytes;\n if (!(bytes instanceof Uint8Array) || bytes.byteLength < 4) {\n throw workerProtocolError('WorkerProtocolError', 'invalid packed batch payload');\n }\n const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);\n const count = view.getUint32(0, true);\n const metadataBytes = checkedByteCount(count, 9, 'packed batch metadata');\n const payloadOffset = checkedAdd(4, metadataBytes, 'packed batch header');\n if (payloadOffset > bytes.byteLength) {\n throw workerProtocolError('WorkerProtocolError', 'packed batch metadata exceeds payload length');\n }\n\n const ops = new Array<PackedBatchOpKey>(count);\n let metadataOffset = 4;\n let readOffset = payloadOffset;\n for (let index = 0; index < count; index += 1) {\n const kind = view.getUint8(metadataOffset);\n const keyLength = view.getUint32(metadataOffset + 1, true);\n const valueLength = view.getUint32(metadataOffset + 5, true);\n metadataOffset += 9;\n\n const keyEnd = readOffset + keyLength;\n if (keyEnd > U32_MAX || keyEnd > bytes.byteLength) {\n throw workerProtocolError('WorkerProtocolError', 'packed batch key exceeds payload length');\n }\n const key = bytes.subarray(readOffset, keyEnd);\n readOffset = keyEnd;\n\n if (kind === BATCH_OP_DELETE) {\n if (valueLength !== 0) {\n throw workerProtocolError('WorkerProtocolError', 'packed delete operation has a value payload');\n }\n ops[index] = { kind: 'delete', key };\n continue;\n }\n\n if (kind !== BATCH_OP_PUT) {\n throw workerProtocolError('WorkerProtocolError', `packed batch operation has invalid kind byte: ${kind}`);\n }\n const valueEnd = readOffset + valueLength;\n if (valueEnd > U32_MAX || valueEnd > bytes.byteLength) {\n throw workerProtocolError('WorkerProtocolError', 'packed batch value exceeds payload length');\n }\n ops[index] = { kind: 'put', key };\n readOffset = valueEnd;\n }\n if (readOffset !== bytes.byteLength) {\n throw workerProtocolError('WorkerProtocolError', 'packed batch payload has trailing bytes');\n }\n return ops;\n}\n\nfunction isPackedBinaryList(value: unknown): value is PackedBinaryListV1 {\n return isRecord(value) && value.__moyodbPacked === PACKED_BINARY_LIST_V1 && value.bytes instanceof Uint8Array;\n}\n\nfunction isPackedNullableBinaryList(value: unknown): value is PackedNullableBinaryListV1 {\n return (\n isRecord(value) && value.__moyodbPacked === PACKED_NULLABLE_BINARY_LIST_V1 && value.bytes instanceof Uint8Array\n );\n}\n\nfunction isPackedScanRows(value: unknown): value is PackedScanRowsV1 {\n return isRecord(value) && value.__moyodbPacked === PACKED_SCAN_ROWS_V1 && value.bytes instanceof Uint8Array;\n}\n\nfunction isPackedBatchOps(value: unknown): value is PackedBatchOpsV1 {\n return isRecord(value) && value.__moyodbPacked === PACKED_BATCH_OPS_V1 && value.bytes instanceof Uint8Array;\n}\n\nfunction isPackedOptionalValues(value: unknown): value is PackedOptionalValuesV1 {\n return isRecord(value) && value.__moyodbPacked === PACKED_OPTIONAL_VALUES_V1 && value.bytes instanceof Uint8Array;\n}\n\nfunction checkedByteCount(count: number, itemBytes: number, what: string): number {\n if (!Number.isSafeInteger(count) || count < 0) {\n throw workerProtocolError('WorkerProtocolError', `${what} count is invalid: ${count}`);\n }\n return checkedU32(count * itemBytes, what);\n}\n\nfunction checkedAdd(left: number, right: number, what: string): number {\n const total = left + right;\n return checkedU32(total, what);\n}\n\nfunction checkedU32(value: number, what: string): number {\n if (!Number.isSafeInteger(value) || value < 0 || value > U32_MAX) {\n throw workerProtocolError('WorkerProtocolError', `${what} exceeds 32-bit payload limit`);\n }\n return value;\n}\n\nfunction copyToOwnedUint8Array(value: Uint8Array): Uint8Array {\n const owned = new Uint8Array(value.byteLength);\n owned.set(value);\n return owned;\n}\n\nfunction stringOrUndefined(value: unknown): string | undefined {\n return typeof value === 'string' ? value : undefined;\n}\n","import type { AutocommitCommand, IndexScanPage, WorkerApi, WorkerOpenRequest } from './worker-api';\nimport type {\n BatchOp,\n ChangeFeed,\n ChangeFeedOptions,\n CompactionResult,\n CreateStoreOptions,\n DebugFailpoint,\n DbStats,\n ExportSnapshotOptions,\n IndexDef,\n PutOptions,\n Range,\n ScanItem,\n StorageInfo,\n TxMode\n} from './types';\nimport {\n MAX_WORKER_BATCH_BYTES,\n MAX_WORKER_BATCH_MESSAGES,\n WORKER_PROTOCOL_REQUEST,\n WORKER_PROTOCOL_REQUEST_BATCH,\n WORKER_PROTOCOL_RESPONSE,\n WORKER_PROTOCOL_RESPONSE_BATCH,\n WORKER_PROTOCOL_VERSION,\n captureWorkerPayload,\n deserializeWorkerError,\n decodeWorkerResponsePayload,\n isWorkerProtocolReadyMessage,\n isWorkerProtocolResponseBatchMessage,\n isWorkerProtocolResponseMessage,\n prepareWorkerCommandPayload,\n workerProtocolError,\n type AutocommitArgs,\n type WorkerCommand,\n type WorkerCommandArgs,\n type WorkerCommandResult,\n type WorkerProtocolRequestBatchMessage,\n type WorkerProtocolRequestMessage\n} from './worker-protocol';\nimport { isRecord } from './internal';\n\ninterface PendingRequest {\n /** Response command; autocommit replies use the inner command's format. */\n command: WorkerCommand;\n resolve: (value: unknown) => void;\n reject: (error: Error) => void;\n timeout: ReturnType<typeof setTimeout> | null;\n}\n\ninterface QueuedRequest {\n message: WorkerProtocolRequestMessage;\n transfer: Transferable[];\n byteLength: number;\n}\n\nfunction clearPendingTimeout(pending: PendingRequest): void {\n if (pending.timeout) {\n clearTimeout(pending.timeout);\n }\n}\n\nexport interface WorkerProtocolClientOptions {\n requestTimeoutMs?: number;\n}\n\nexport class WorkerProtocolClient implements WorkerApi {\n private nextRequestId = 1;\n private pending = new Map<number, PendingRequest>();\n private closed = false;\n private readyResolved = false;\n private readyResolve: (() => void) | null = null;\n private readyReject: ((error: Error) => void) | null = null;\n private ready: Promise<void>;\n private requestTimeoutMs: number;\n private fatalHandler: ((error: Error) => void) | null = null;\n private closeReason: Error | null = null;\n private batching = false;\n private queuedRequests: QueuedRequest[] = [];\n private queuedBytes = 0;\n private flushScheduled = false;\n private awaitingReady = 0;\n\n constructor(\n private readonly worker: Worker,\n options: WorkerProtocolClientOptions = {}\n ) {\n this.requestTimeoutMs = options.requestTimeoutMs ?? 0;\n this.ready = new Promise<void>((resolve, reject) => {\n this.readyResolve = resolve;\n this.readyReject = reject;\n });\n this.worker.addEventListener('message', this.handleMessage);\n this.worker.addEventListener('messageerror', this.handleMessageError);\n this.worker.addEventListener('error', this.handleError);\n }\n\n setFatalHandler(handler: ((error: Error) => void) | null): void {\n this.fatalHandler = handler;\n }\n\n whenReady(): Promise<void> {\n return this.ready;\n }\n\n dispose(reason: Error = workerProtocolError('WorkerTerminatedError', 'worker transport was closed')): void {\n this.disposeInternal(reason, false);\n }\n\n open(request: WorkerOpenRequest): Promise<void> {\n return this.request('open', [request]);\n }\n\n close(): Promise<void> {\n return this.request('close', []);\n }\n\n destroy(): Promise<void> {\n return this.request('destroy', []);\n }\n\n deleteDB(dbName: string): Promise<void> {\n return this.request('deleteDB', [dbName]);\n }\n\n begin(mode: TxMode): Promise<number> {\n return this.request('begin', [mode]);\n }\n\n commit(txId: number): Promise<number> {\n return this.request('commit', [txId]);\n }\n\n rollback(txId: number): Promise<void> {\n return this.request('rollback', [txId]);\n }\n\n autocommit<M extends AutocommitCommand>(\n mode: TxMode,\n command: M,\n args: AutocommitArgs<M>\n ): Promise<WorkerCommandResult<M>> {\n return this.send('autocommit', [mode, command, args as unknown[]], command) as Promise<WorkerCommandResult<M>>;\n }\n\n createStore(txId: number, name: string, options?: CreateStoreOptions): Promise<void> {\n return this.request('createStore', [txId, name, options]);\n }\n\n dropStore(txId: number, name: string): Promise<void> {\n return this.request('dropStore', [txId, name]);\n }\n\n clearStore(txId: number, name: string): Promise<void> {\n return this.request('clearStore', [txId, name]);\n }\n\n get(txId: number, store: string, key: Uint8Array): Promise<Uint8Array | null> {\n return this.request('get', [txId, store, key]);\n }\n\n getMany(txId: number, store: string, keys: Array<Uint8Array>): Promise<Array<Uint8Array | null>> {\n return this.request('getMany', [txId, store, keys]);\n }\n\n has(txId: number, store: string, key: Uint8Array): Promise<boolean> {\n return this.request('has', [txId, store, key]);\n }\n\n put(txId: number, store: string, key: Uint8Array, value: Uint8Array, options?: PutOptions): Promise<void> {\n return this.request('put', [txId, store, key, value, options]);\n }\n\n putMany(\n txId: number,\n store: string,\n entries: Array<[Uint8Array, Uint8Array]>,\n options?: PutOptions\n ): Promise<void> {\n return this.request('putMany', [txId, store, entries, options]);\n }\n\n delete(txId: number, store: string, key: Uint8Array): Promise<boolean> {\n return this.request('delete', [txId, store, key]);\n }\n\n deleteMany(txId: number, store: string, keys: Array<Uint8Array>): Promise<void> {\n return this.request('deleteMany', [txId, store, keys]);\n }\n\n applyBatch(txId: number, store: string, ops: Array<BatchOp>): Promise<void> {\n return this.request('applyBatch', [txId, store, ops]);\n }\n\n scan(txId: number, store: string, range: Range): Promise<ScanItem[]> {\n return this.request('scan', [txId, store, range]);\n }\n\n getByIndex(txId: number, store: string, indexName: string, key: Uint8Array): Promise<Uint8Array | null> {\n return this.request('getByIndex', [txId, store, indexName, key]);\n }\n\n scanByIndex(txId: number, store: string, indexName: string, range: Range): Promise<ScanItem[]> {\n return this.request('scanByIndex', [txId, store, indexName, range]);\n }\n\n scanByIndexPage(\n txId: number,\n store: string,\n indexName: string,\n range: Range,\n cursor: Uint8Array | null,\n limit: number\n ): Promise<IndexScanPage> {\n return this.request('scanByIndexPage', [txId, store, indexName, range, cursor, limit]);\n }\n\n getIndexes(): Promise<IndexDef[]> {\n return this.request('getIndexes', []);\n }\n\n reconcileIndexes(txId: number, indexes: IndexDef[]): Promise<void> {\n return this.request('reconcileIndexes', [txId, indexes]);\n }\n\n listStores(): Promise<string[]> {\n return this.request('listStores', []);\n }\n\n getVersion(): Promise<number> {\n return this.request('getVersion', []);\n }\n\n changesSince(txId: number, options: ChangeFeedOptions): Promise<ChangeFeed> {\n return this.request('changesSince', [txId, options]);\n }\n\n setSchemaVersion(txId: number, version: number): Promise<void> {\n return this.request('setSchemaVersion', [txId, version]);\n }\n\n exportSnapshot(options?: ExportSnapshotOptions): Promise<Uint8Array> {\n return this.request('exportSnapshot', [options]);\n }\n\n importSnapshot(data: Uint8Array): Promise<void> {\n return this.request('importSnapshot', [data]);\n }\n\n reset(): Promise<void> {\n return this.request('reset', []);\n }\n\n compact(): Promise<CompactionResult> {\n return this.request('compact', []);\n }\n\n rebuild(): Promise<CompactionResult> {\n return this.request('rebuild', []);\n }\n\n stats(): Promise<DbStats> {\n return this.request('stats', []);\n }\n\n storageInfo(): Promise<StorageInfo> {\n return this.request('storageInfo', []);\n }\n\n requestPersistence(): Promise<boolean> {\n return this.request('requestPersistence', []);\n }\n\n setFailpoint(failpoint: DebugFailpoint): Promise<void> {\n return this.request('setFailpoint', [failpoint]);\n }\n\n async request<M extends WorkerCommand>(command: M, args: WorkerCommandArgs<M>): Promise<WorkerCommandResult<M>> {\n return (await this.send(command, args, command)) as WorkerCommandResult<M>;\n }\n\n private async send<M extends WorkerCommand>(\n command: M,\n args: WorkerCommandArgs<M>,\n responseCommand: WorkerCommand\n ): Promise<unknown> {\n this.ensureOpen();\n this.awaitingReady += 1;\n try {\n await this.ready;\n } finally {\n this.awaitingReady -= 1;\n }\n this.ensureOpen();\n // Calls awaiting readiness together can share a batch. A lone call posts immediately.\n const shouldQueue = this.batching && (this.awaitingReady > 0 || this.queuedRequests.length > 0);\n const id = this.nextRequestId;\n this.nextRequestId += 1;\n const prepared = prepareWorkerCommandPayload(command, args);\n const message: WorkerProtocolRequestMessage = {\n type: WORKER_PROTOCOL_REQUEST,\n version: WORKER_PROTOCOL_VERSION,\n id,\n command,\n args: prepared.args\n } as WorkerProtocolRequestMessage;\n return await new Promise<unknown>((resolve, reject) => {\n const timeout =\n this.requestTimeoutMs > 0\n ? setTimeout(() => {\n this.pending.delete(id);\n reject(\n workerProtocolError(\n 'WorkerRequestTimeoutError',\n `worker command ${command} timed out after ${this.requestTimeoutMs}ms`\n )\n );\n }, this.requestTimeoutMs)\n : null;\n this.pending.set(id, {\n command: responseCommand,\n resolve: (value) => resolve(value),\n reject,\n timeout\n });\n try {\n if (shouldQueue) {\n this.queueRequest(message, prepared.transfer);\n } else if (prepared.transfer.length > 0) {\n this.worker.postMessage(message, prepared.transfer);\n } else {\n this.worker.postMessage(message);\n }\n } catch (error) {\n this.rejectPending(id, error instanceof Error ? error : new Error(String(error)));\n }\n });\n }\n\n private queueRequest(message: WorkerProtocolRequestMessage, transfer: Transferable[]): void {\n const captured = captureWorkerPayload(message, transfer);\n if (!this.pending.has(message.id)) return;\n if (this.queuedRequests.length > 0 && this.queuedBytes + captured.byteLength > MAX_WORKER_BATCH_BYTES) {\n this.flushRequests();\n }\n this.queuedRequests.push({\n message: captured.value,\n transfer: captured.transfer,\n byteLength: captured.byteLength\n });\n this.queuedBytes += captured.byteLength;\n if (!this.flushScheduled) {\n this.flushScheduled = true;\n queueMicrotask(() => {\n this.flushScheduled = false;\n this.flushRequests();\n });\n }\n if (this.queuedRequests.length >= MAX_WORKER_BATCH_MESSAGES || this.queuedBytes >= MAX_WORKER_BATCH_BYTES) {\n this.flushRequests();\n }\n }\n\n private flushRequests(): void {\n const queued = this.queuedRequests;\n this.queuedRequests = [];\n this.queuedBytes = 0;\n if (this.closed) return;\n const active = queued.filter((entry) => this.pending.has(entry.message.id));\n if (active.length === 0) return;\n const message: WorkerProtocolRequestMessage | WorkerProtocolRequestBatchMessage =\n active.length === 1\n ? active[0].message\n : {\n type: WORKER_PROTOCOL_REQUEST_BATCH,\n version: WORKER_PROTOCOL_VERSION,\n requests: active.map((entry) => entry.message)\n };\n const transfer: Transferable[] = [];\n for (const entry of active) {\n for (const buffer of entry.transfer) transfer.push(buffer);\n }\n try {\n if (transfer.length > 0) {\n this.worker.postMessage(message, transfer);\n } else {\n this.worker.postMessage(message);\n }\n } catch (error) {\n const reason = error instanceof Error ? error : new Error(String(error));\n for (const entry of active) this.rejectPending(entry.message.id, reason);\n }\n }\n\n private ensureOpen(): void {\n if (this.closed) {\n throw this.closeReason ?? workerProtocolError('WorkerTerminatedError', 'worker transport is closed');\n }\n }\n\n private handleMessage = (event: MessageEvent<unknown>): void => {\n const data = event.data;\n if (isWorkerProtocolReadyMessage(data)) {\n if (this.readyResolved) return;\n this.batching = data.batching === 1;\n this.readyResolved = true;\n this.readyResolve?.();\n this.readyResolve = null;\n this.readyReject = null;\n return;\n }\n if (isWorkerProtocolResponseBatchMessage(data)) {\n for (const response of data.responses) this.handleResponse(response);\n return;\n }\n if (\n isRecord(data) &&\n data.type === WORKER_PROTOCOL_RESPONSE_BATCH &&\n data.version === WORKER_PROTOCOL_VERSION\n ) {\n this.disposeInternal(workerProtocolError('WorkerProtocolError', 'invalid worker response batch'), true);\n return;\n }\n this.handleResponse(data);\n };\n\n private handleResponse(data: unknown): void {\n if (!isWorkerProtocolResponseMessage(data)) {\n if (\n isRecord(data) &&\n data.type === WORKER_PROTOCOL_RESPONSE &&\n data.version === WORKER_PROTOCOL_VERSION &&\n typeof data.id === 'number' &&\n Number.isSafeInteger(data.id)\n ) {\n this.rejectPending(data.id, workerProtocolError('WorkerProtocolError', 'invalid worker response'));\n }\n return;\n }\n const pending = this.pending.get(data.id);\n if (!pending) {\n return;\n }\n this.pending.delete(data.id);\n clearPendingTimeout(pending);\n try {\n if (data.ok) {\n pending.resolve(decodeWorkerResponsePayload(pending.command, data.result));\n } else {\n pending.reject(deserializeWorkerError(data.error));\n }\n } catch (error) {\n pending.reject(\n error instanceof Error && error.name === 'WorkerProtocolError'\n ? error\n : workerProtocolError('WorkerProtocolError', 'worker response could not be decoded')\n );\n }\n }\n\n private handleMessageError = (): void => {\n this.disposeInternal(\n workerProtocolError('WorkerMessageError', 'worker message could not be deserialized'),\n true\n );\n };\n\n private handleError = (event: ErrorEvent): void => {\n const error =\n event.error instanceof Error\n ? event.error\n : workerProtocolError('WorkerError', event.message || 'worker runtime failed');\n this.disposeInternal(error, true);\n };\n\n private rejectPending(id: number, error: Error): void {\n const pending = this.pending.get(id);\n if (!pending) {\n return;\n }\n this.pending.delete(id);\n clearPendingTimeout(pending);\n pending.reject(error);\n }\n\n private disposeInternal(reason: Error, notifyFatal: boolean): void {\n if (this.closed) {\n return;\n }\n this.closed = true;\n this.closeReason = reason;\n this.worker.removeEventListener('message', this.handleMessage);\n this.worker.removeEventListener('messageerror', this.handleMessageError);\n this.worker.removeEventListener('error', this.handleError);\n if (!this.readyResolved) {\n this.readyReject?.(reason);\n }\n this.readyResolve = null;\n this.readyReject = null;\n this.queuedRequests = [];\n this.queuedBytes = 0;\n for (const pending of this.pending.values()) {\n clearPendingTimeout(pending);\n pending.reject(reason);\n }\n this.pending.clear();\n if (notifyFatal) {\n this.fatalHandler?.(reason);\n }\n }\n}\n","export class MoyoDbError extends Error {\n constructor(name: string, message: string) {\n super(message);\n this.name = name;\n Object.setPrototypeOf(this, new.target.prototype);\n }\n}\nexport class UnsupportedPlatformError extends MoyoDbError {\n constructor(message: string) {\n super('UnsupportedPlatformError', message);\n }\n}\nexport class DatabaseBusyError extends MoyoDbError {\n constructor(message: string) {\n super('DatabaseBusyError', message);\n }\n}\nexport class CorruptionError extends MoyoDbError {\n constructor(message: string) {\n super('CorruptionError', message);\n }\n}\nexport class StoreExistsError extends MoyoDbError {\n constructor(message: string) {\n super('StoreExistsError', message);\n }\n}\nexport class StoreNotFoundError extends MoyoDbError {\n constructor(message: string) {\n super('StoreNotFoundError', message);\n }\n}\nexport class IndexNotFoundError extends MoyoDbError {\n constructor(message: string) {\n super('IndexNotFoundError', message);\n }\n}\nexport class ConstraintError extends MoyoDbError {\n constructor(message: string) {\n super('ConstraintError', message);\n }\n}\nexport class UniqueIndexConstraintError extends ConstraintError {\n constructor(message: string) {\n super(message);\n this.name = 'UniqueIndexConstraintError';\n }\n}\nexport class WriteTransactionAlreadyOpenError extends MoyoDbError {\n constructor(message = 'write transaction already open') {\n super('WriteTransactionAlreadyOpenError', message);\n }\n}\nexport class ReadonlyTransactionError extends MoyoDbError {\n constructor(message = 'readonly transaction cannot perform this operation') {\n super('ReadonlyTransactionError', message);\n }\n}\nexport class TransactionClosedError extends MoyoDbError {\n constructor(message = 'transaction is already closed') {\n super('TransactionClosedError', message);\n }\n}\nexport class DatabaseClosedError extends MoyoDbError {\n constructor(message = 'database handle is closed') {\n super('DatabaseClosedError', message);\n }\n}\nexport class ValueTooLargeError extends MoyoDbError {\n constructor(message: string) {\n super('ValueTooLargeError', message);\n }\n}\nexport class KeyTooLargeError extends MoyoDbError {\n constructor(message: string) {\n super('KeyTooLargeError', message);\n }\n}\nexport class StoreNameTooLongError extends MoyoDbError {\n constructor(message: string) {\n super('StoreNameTooLongError', message);\n }\n}\nexport class ReservedStoreNameError extends MoyoDbError {\n constructor(message: string) {\n super('ReservedStoreNameError', message);\n }\n}\nexport class InvalidRangeError extends MoyoDbError {\n constructor(message: string) {\n super('InvalidRangeError', message);\n }\n}\nexport class StorageError extends MoyoDbError {\n constructor(message: string) {\n super('StorageError', message);\n }\n}\nexport class SerializationError extends MoyoDbError {\n constructor(message: string) {\n super('SerializationError', message);\n }\n}\nexport class InjectedFailureError extends MoyoDbError {\n constructor(message: string) {\n super('InjectedFailureError', message);\n }\n}\nexport class ChangeFeedCompactedError extends MoyoDbError {\n constructor(message: string) {\n super('ChangeFeedCompactedError', message);\n }\n}\n/**\n * The engine state could not be trusted, or automatic recovery failed.\n * A failed commit may already be durable. The worker attempts recovery before\n * a new transaction and after a failed commit. Recovery discards all open transactions.\n */\nexport class RecoveryRequiredError extends MoyoDbError {\n constructor(message: string) {\n super('RecoveryRequiredError', message);\n }\n}\nexport class InternalError extends MoyoDbError {\n constructor(message: string) {\n super('InternalError', message);\n }\n}\nexport class InvalidOpenOptionsError extends MoyoDbError {\n constructor(message: string) {\n super('InvalidOpenOptionsError', message);\n }\n}\nexport class VersionError extends MoyoDbError {\n constructor(message: string) {\n super('VersionError', message);\n }\n}\ntype ErrorPayload = {\n code?: string;\n name?: string;\n message?: string;\n};\ntype ErrorConstructor = new (message: string) => Error;\nconst ERROR_CONSTRUCTORS = {\n UnsupportedPlatformError,\n DatabaseBusyError,\n CorruptionError,\n StoreExistsError,\n StoreNotFoundError,\n IndexNotFoundError,\n ConstraintError,\n UniqueIndexConstraintError,\n WriteTransactionAlreadyOpenError,\n ReadonlyTransactionError,\n TransactionClosedError,\n DatabaseClosedError,\n ValueTooLargeError,\n KeyTooLargeError,\n StoreNameTooLongError,\n ReservedStoreNameError,\n InvalidRangeError,\n StorageError,\n SerializationError,\n InjectedFailureError,\n ChangeFeedCompactedError,\n RecoveryRequiredError,\n InternalError,\n InvalidOpenOptionsError,\n VersionError\n} satisfies Record<string, ErrorConstructor>;\n\nfunction instantiateError(code: string, message: string): Error {\n if (Object.prototype.hasOwnProperty.call(ERROR_CONSTRUCTORS, code)) {\n const ErrorConstructor = ERROR_CONSTRUCTORS[code as keyof typeof ERROR_CONSTRUCTORS];\n return new ErrorConstructor(message);\n }\n const err = new Error(message);\n err.name = code;\n return err;\n}\n\nexport function normalizeError(error: unknown): Error {\n if (error instanceof MoyoDbError) {\n return error;\n }\n if (error instanceof Error) {\n if (error.name === 'Error') {\n return error;\n }\n return instantiateError(error.name, error.message);\n }\n const payload = error as ErrorPayload | undefined;\n const code = payload?.code ?? payload?.name ?? 'Error';\n const message = payload?.message ?? String(error);\n return instantiateError(code, message);\n}\n","import { WorkerProtocolClient } from './worker-client';\nimport type { ChangeFeedSettings, DebugFailpoint, OpenOptions } from './types';\nimport { DatabaseBusyError, DatabaseClosedError, InvalidOpenOptionsError, normalizeError } from './errors';\nimport { isRecord, withTimeout } from './internal';\nconst VALID_FAILPOINTS = new Set<Exclude<DebugFailpoint, null>>([\n 'after_wal_flush',\n 'after_main_flush',\n 'before_superblock_flush'\n]);\nconst PERSISTENCE_BRIDGE_INIT = 'moyodb:persistence-bridge:init';\nconst PERSISTENCE_BRIDGE_REQUEST = 'moyodb:persistence-bridge:request';\nconst PERSISTENCE_BRIDGE_RESPONSE = 'moyodb:persistence-bridge:response';\ntype PersistenceBridgeOperation = 'persist' | 'persisted';\ninterface PersistenceBridgeRequest {\n type: typeof PERSISTENCE_BRIDGE_REQUEST;\n id: number;\n op: PersistenceBridgeOperation;\n}\ninterface PersistenceBridgeResponse {\n type: typeof PERSISTENCE_BRIDGE_RESPONSE;\n id: number;\n granted: boolean;\n}\nfunction isPersistenceBridgeRequest(value: unknown): value is PersistenceBridgeRequest {\n return (\n isRecord(value) &&\n value.type === PERSISTENCE_BRIDGE_REQUEST &&\n typeof value.id === 'number' &&\n (value.op === 'persist' || value.op === 'persisted')\n );\n}\ninterface MainThreadPersistenceBridge {\n close(): void;\n}\nexport interface NormalizedOpenOptions {\n createIfMissing: boolean;\n ownerWaitMs: number;\n requestPersistence: boolean;\n cachePages: number;\n debugFailpoint: DebugFailpoint;\n changeFeed: Required<ChangeFeedSettings> | null;\n}\nconst DEFAULT_CHANGE_FEED_RETAIN_TXIDS = 100_000;\nexport interface RegistryEntry {\n dbName: string;\n refs: number;\n worker: Worker;\n proxy: WorkerProtocolClient;\n persistenceBridge: MainThreadPersistenceBridge;\n options: NormalizedOpenOptions;\n invalidated: boolean;\n schemaMigrationInProgress: boolean;\n txInvalidationListeners: Set<() => void>;\n handleInvalidationListeners: Set<() => void>;\n}\nconst registry = new Map<string, RegistryEntry>();\nconst lifecycleOperations = new Map<string, Promise<void>>();\nfunction queueLifecycleOperation<T>(dbName: string, operation: () => Promise<T>): Promise<T> {\n const previous = lifecycleOperations.get(dbName) ?? Promise.resolve();\n const result = previous.then(operation);\n const settled = result.then(\n () => undefined,\n () => undefined\n );\n lifecycleOperations.set(dbName, settled);\n void settled.then(() => {\n if (lifecycleOperations.get(dbName) === settled) {\n lifecycleOperations.delete(dbName);\n }\n });\n return result;\n}\nfunction requirePlainOptionsObject(options: unknown): asserts options is OpenOptions {\n if (options === null || typeof options !== 'object' || Array.isArray(options)) {\n throw new InvalidOpenOptionsError('open options must be an object');\n }\n}\nfunction normalizeBoolean(value: unknown, field: string, defaultValue: boolean): boolean {\n if (value === undefined) {\n return defaultValue;\n }\n if (typeof value !== 'boolean') {\n throw new InvalidOpenOptionsError(`${field} must be a boolean`);\n }\n return value;\n}\nfunction normalizeNonNegativeInteger(value: unknown, field: string, defaultValue: number): number {\n if (value === undefined) {\n return defaultValue;\n }\n if (typeof value !== 'number' || !Number.isSafeInteger(value) || value < 0) {\n throw new InvalidOpenOptionsError(`${field} must be a non-negative safe integer`);\n }\n return value;\n}\nfunction normalizeCachePages(value: unknown): number {\n return Math.max(1, normalizeNonNegativeInteger(value, 'cachePages', 256));\n}\nfunction normalizeFailpoint(value: unknown): DebugFailpoint {\n if (value === undefined || value === null) {\n return null;\n }\n if (typeof value !== 'string' || !VALID_FAILPOINTS.has(value as Exclude<DebugFailpoint, null>)) {\n throw new InvalidOpenOptionsError(`debugFailpoint must be one of: ${Array.from(VALID_FAILPOINTS).join(', ')}`);\n }\n return value as Exclude<DebugFailpoint, null>;\n}\nfunction normalizeChangeFeed(value: unknown): Required<ChangeFeedSettings> | null {\n if (value === undefined) {\n return null;\n }\n if (value === null || typeof value !== 'object' || Array.isArray(value)) {\n throw new InvalidOpenOptionsError('changeFeed must be an object');\n }\n const settings = value as ChangeFeedSettings;\n const enabled = normalizeBoolean(settings.enabled, 'changeFeed.enabled', true);\n let retainTxids: number | null = DEFAULT_CHANGE_FEED_RETAIN_TXIDS;\n if (settings.retainTxids === null) {\n retainTxids = null;\n } else if (settings.retainTxids !== undefined) {\n retainTxids = normalizeNonNegativeInteger(settings.retainTxids, 'changeFeed.retainTxids', 0);\n if (retainTxids === 0) {\n throw new InvalidOpenOptionsError('changeFeed.retainTxids must be positive; disable the feed instead');\n }\n }\n return { enabled, retainTxids };\n}\nfunction normalizeOptions(options: OpenOptions = {}): NormalizedOpenOptions {\n requirePlainOptionsObject(options);\n return {\n createIfMissing: normalizeBoolean(options.createIfMissing, 'createIfMissing', true),\n ownerWaitMs: normalizeNonNegativeInteger(options.ownerWaitMs, 'ownerWaitMs', 0),\n requestPersistence: normalizeBoolean(options.requestPersistence, 'requestPersistence', true),\n cachePages: normalizeCachePages(options.cachePages),\n debugFailpoint: normalizeFailpoint(options.debugFailpoint),\n changeFeed: normalizeChangeFeed(options.changeFeed)\n };\n}\nfunction sameChangeFeed(left: NormalizedOpenOptions['changeFeed'], right: NormalizedOpenOptions['changeFeed']) {\n return left?.enabled === right?.enabled && left?.retainTxids === right?.retainTxids;\n}\nfunction assertCompatibleOptions(dbName: string, current: NormalizedOpenOptions, next: NormalizedOpenOptions) {\n if (current.cachePages !== next.cachePages) {\n throw new InvalidOpenOptionsError(\n `database ${dbName} is already open in this tab with cachePages=${current.cachePages}; requested cachePages=${next.cachePages}`\n );\n }\n if (next.changeFeed !== null && !sameChangeFeed(current.changeFeed, next.changeFeed)) {\n throw new InvalidOpenOptionsError(\n `database ${dbName} is already open in this tab with a different changeFeed policy`\n );\n }\n}\nasync function queryPersistentStorageState(): Promise<boolean> {\n const storage = globalThis.navigator.storage;\n if (typeof storage.persisted !== 'function') {\n return false;\n }\n return await withTimeout(storage.persisted(), 1000, false);\n}\nasync function requestPersistentStorageGrant(): Promise<boolean> {\n const storage = globalThis.navigator.storage;\n if (typeof storage.persist !== 'function') {\n return false;\n }\n return await withTimeout(storage.persist(), 1000, false);\n}\nasync function handlePersistenceBridgeRequest(port: MessagePort, request: PersistenceBridgeRequest): Promise<void> {\n const granted =\n request.op === 'persist' ? await requestPersistentStorageGrant() : await queryPersistentStorageState();\n const response: PersistenceBridgeResponse = {\n type: PERSISTENCE_BRIDGE_RESPONSE,\n id: request.id,\n granted\n };\n port.postMessage(response);\n}\nfunction createMainThreadPersistenceBridge(worker: Worker): MainThreadPersistenceBridge {\n const channel = new MessageChannel();\n const port = channel.port1;\n port.addEventListener('message', (event: MessageEvent<unknown>) => {\n const data = event.data;\n if (!isPersistenceBridgeRequest(data)) {\n return;\n }\n void handlePersistenceBridgeRequest(port, data);\n });\n port.start();\n worker.postMessage({ type: PERSISTENCE_BRIDGE_INIT }, [channel.port2]);\n return {\n close() {\n port.close();\n }\n };\n}\nfunction createWorker(): {\n worker: Worker;\n proxy: WorkerProtocolClient;\n persistenceBridge: MainThreadPersistenceBridge;\n} {\n const worker = new Worker(new URL('./worker.ts', import.meta.url), { type: 'module' });\n const proxy = new WorkerProtocolClient(worker);\n const persistenceBridge = createMainThreadPersistenceBridge(worker);\n return { worker, proxy, persistenceBridge };\n}\nfunction createEntry(\n dbName: string,\n worker: Worker,\n proxy: WorkerProtocolClient,\n persistenceBridge: MainThreadPersistenceBridge,\n options: NormalizedOpenOptions\n): RegistryEntry {\n const entry: RegistryEntry = {\n dbName,\n refs: 1,\n worker,\n proxy,\n persistenceBridge,\n options,\n invalidated: false,\n schemaMigrationInProgress: false,\n txInvalidationListeners: new Set(),\n handleInvalidationListeners: new Set()\n };\n proxy.setFatalHandler(() => {\n const current = registry.get(dbName);\n if (current !== entry || entry.invalidated) {\n return;\n }\n registry.delete(dbName);\n entry.refs = 0;\n invalidateEntry(entry);\n entry.persistenceBridge.close();\n entry.worker.terminate();\n });\n return entry;\n}\nfunction emitListeners(listeners: Iterable<() => void>) {\n for (const listener of Array.from(listeners)) {\n listener();\n }\n}\nexport function subscribeTransactionsInvalidated(entry: RegistryEntry, listener: () => void): () => void {\n entry.txInvalidationListeners.add(listener);\n return () => {\n entry.txInvalidationListeners.delete(listener);\n };\n}\nexport function subscribeHandleInvalidated(entry: RegistryEntry, listener: () => void): () => void {\n entry.handleInvalidationListeners.add(listener);\n return () => {\n entry.handleInvalidationListeners.delete(listener);\n };\n}\nexport function invalidateTransactions(entry: RegistryEntry): void {\n emitListeners(entry.txInvalidationListeners);\n}\nfunction invalidateEntry(entry: RegistryEntry): void {\n if (entry.invalidated) {\n return;\n }\n entry.invalidated = true;\n invalidateTransactions(entry);\n emitListeners(entry.handleInvalidationListeners);\n}\nexport function unsafeDebugCrashWorker(dbName: string): boolean {\n const current = registry.get(dbName);\n if (!current) {\n return false;\n }\n registry.delete(dbName);\n invalidateEntry(current);\n current.refs = 0;\n current.persistenceBridge.close();\n current.proxy.dispose(new Error('worker was terminated by unsafeDebugCrashWorker'));\n current.worker.terminate();\n return true;\n}\nexport async function acquireDbWorker(dbName: string, options: OpenOptions = {}): Promise<RegistryEntry> {\n const normalized = normalizeOptions(options);\n return queueLifecycleOperation(dbName, async () => {\n const existing = registry.get(dbName);\n if (existing) {\n if (existing.invalidated) {\n registry.delete(dbName);\n } else {\n if (existing.schemaMigrationInProgress) {\n throw new DatabaseBusyError(`database ${dbName} is migrating; wait for openDB() to resolve`);\n }\n assertCompatibleOptions(dbName, existing.options, normalized);\n if (normalized.debugFailpoint !== null) {\n try {\n await existing.proxy.setFailpoint(normalized.debugFailpoint);\n } catch (error) {\n throw normalizeError(error);\n }\n }\n existing.refs += 1;\n return existing;\n }\n }\n const { worker, proxy, persistenceBridge } = createWorker();\n const entry = createEntry(dbName, worker, proxy, persistenceBridge, normalized);\n try {\n await proxy.open({\n dbName,\n options: normalized\n });\n registry.set(dbName, entry);\n return entry;\n } catch (error) {\n persistenceBridge.close();\n proxy.dispose(new Error('worker open failed'));\n worker.terminate();\n throw normalizeError(error);\n }\n });\n}\nexport async function releaseDbWorker(entry: RegistryEntry): Promise<void> {\n return queueLifecycleOperation(entry.dbName, async () => {\n if (entry.invalidated || registry.get(entry.dbName) !== entry) {\n return;\n }\n entry.refs -= 1;\n if (entry.refs > 0) {\n return;\n }\n registry.delete(entry.dbName);\n try {\n await entry.proxy.close();\n } finally {\n entry.persistenceBridge.close();\n entry.proxy.dispose(new Error('worker was released'));\n entry.worker.terminate();\n }\n });\n}\nexport async function destroyDbWorker(entry: RegistryEntry): Promise<void> {\n return queueLifecycleOperation(entry.dbName, () => destroyEntry(entry));\n}\nasync function destroyEntry(entry: RegistryEntry): Promise<void> {\n if (entry.invalidated || registry.get(entry.dbName) !== entry) {\n throw new DatabaseClosedError();\n }\n registry.delete(entry.dbName);\n invalidateEntry(entry);\n entry.refs = 0;\n try {\n await entry.proxy.destroy();\n } catch (error) {\n throw normalizeError(error);\n } finally {\n entry.persistenceBridge.close();\n entry.proxy.dispose(new Error('worker was released'));\n entry.worker.terminate();\n }\n}\nexport async function deleteDbByName(dbName: string): Promise<void> {\n return queueLifecycleOperation(dbName, async () => {\n const current = registry.get(dbName);\n if (current) {\n await destroyEntry(current);\n return;\n }\n const { worker, proxy, persistenceBridge } = createWorker();\n try {\n await proxy.deleteDB(dbName);\n } catch (error) {\n throw normalizeError(error);\n } finally {\n persistenceBridge.close();\n proxy.dispose(new Error('temporary worker was terminated'));\n worker.terminate();\n }\n });\n}\n","import type { Range } from './types';\nconst encoder = new TextEncoder();\nconst decoder = new TextDecoder();\nconst jsonDecoder = new TextDecoder('utf-8', { fatal: true });\nconst TYPE_NULL = 0x10;\nconst TYPE_FALSE = 0x20;\nconst TYPE_TRUE = 0x21;\nconst TYPE_NUMBER = 0x30;\nconst TYPE_STRING = 0x40;\nconst TYPE_BYTES = 0x50;\nconst COMPOUND_ESCAPE = 0x00;\nconst COMPOUND_ESCAPE_CONT = 0xff;\nconst COMPOUND_TERM = 0x00;\nconst F64_MASK = BigInt('0xffffffffffffffff');\nexport type CompoundKeyPart = string | number | boolean | null | Uint8Array;\nexport type IndexKeyPrimitive = CompoundKeyPart;\nexport function utf8Encode(value: string): Uint8Array {\n return encoder.encode(value);\n}\nexport function utf8Decode(bytes: Uint8Array): string {\n return decoder.decode(bytes);\n}\nexport function jsonEncode(value: unknown): Uint8Array {\n const serialized = JSON.stringify(value) as string | undefined;\n if (serialized === undefined) {\n throw new TypeError('value has no JSON representation');\n }\n return utf8Encode(serialized);\n}\nexport function jsonDecode<T>(bytes: Uint8Array): T {\n return JSON.parse(jsonDecoder.decode(bytes)) as T;\n}\nexport function u64Key(value: bigint | number): Uint8Array {\n if (typeof value === 'number' && (!Number.isSafeInteger(value) || value < 0)) {\n throw new RangeError('u64Key number inputs must be safe non-negative integers; use bigint for larger values');\n }\n const asBigInt = typeof value === 'bigint' ? value : BigInt(value);\n if (asBigInt < 0n) {\n throw new RangeError('u64Key only accepts non-negative values');\n }\n if (asBigInt > F64_MASK) {\n throw new RangeError('u64Key value exceeds the unsigned 64-bit range');\n }\n const buf = new ArrayBuffer(8);\n const view = new DataView(buf);\n view.setBigUint64(0, asBigInt, false);\n return new Uint8Array(buf);\n}\nfunction isCompoundKeyPartList(\n value: CompoundKeyPart | ReadonlyArray<CompoundKeyPart>\n): value is ReadonlyArray<CompoundKeyPart> {\n return Array.isArray(value);\n}\nexport function indexKey(value: CompoundKeyPart | ReadonlyArray<CompoundKeyPart>): Uint8Array {\n if (isCompoundKeyPartList(value)) {\n return compoundKey(...value);\n }\n return encodeCompoundKeyPart(value);\n}\nexport function compoundKey(...parts: CompoundKeyPart[]): Uint8Array {\n return encodeCompoundBytes(parts.map((part) => encodeCompoundKeyPart(part)));\n}\nexport function encodeIndexScalar(value: IndexKeyPrimitive): Uint8Array {\n return encodeCompoundKeyPart(value);\n}\nexport function encodeCompoundKeyParts(parts: ReadonlyArray<Uint8Array>): Uint8Array {\n return encodeCompoundBytes(parts);\n}\nexport function splitCompoundKey(key: Uint8Array): Uint8Array[] {\n const parts: Uint8Array[] = [];\n const current: number[] = [];\n for (let index = 0; index < key.length; index += 1) {\n const byte = key[index];\n if (byte !== COMPOUND_ESCAPE) {\n current.push(byte);\n continue;\n }\n const next = key[index + 1];\n if (next === COMPOUND_ESCAPE_CONT) {\n current.push(COMPOUND_ESCAPE);\n index += 1;\n continue;\n }\n if (next === COMPOUND_TERM) {\n parts.push(Uint8Array.from(current));\n current.length = 0;\n index += 1;\n continue;\n }\n throw new TypeError('invalid compound key encoding');\n }\n if (current.length !== 0) {\n throw new TypeError('compound key terminated unexpectedly');\n }\n return parts;\n}\nexport function prefixSuccessor(prefix: Uint8Array): Uint8Array | null {\n const out = prefix.slice();\n for (let index = out.length - 1; index >= 0; index -= 1) {\n if (out[index] !== 0xff) {\n out[index] += 1;\n return out.subarray(0, index + 1);\n }\n }\n return null;\n}\nexport function prefixRange(prefix: Uint8Array): Range {\n const upper = prefixSuccessor(prefix);\n return upper ? { gte: prefix, lt: upper } : { gte: prefix };\n}\nexport function compoundKeyRange(...parts: CompoundKeyPart[]): Range {\n return prefixRange(compoundKey(...parts));\n}\nfunction encodeCompoundKeyPart(value: CompoundKeyPart): Uint8Array {\n if (value === null) {\n return Uint8Array.of(TYPE_NULL);\n }\n if (typeof value === 'boolean') {\n return Uint8Array.of(value ? TYPE_TRUE : TYPE_FALSE);\n }\n if (typeof value === 'number') {\n return encodeSortableNumber(value);\n }\n if (typeof value === 'string') {\n // Reject lone surrogates so TextEncoder cannot map distinct keys to U+FFFD.\n for (const character of value) {\n const codePoint = character.codePointAt(0) as number;\n if (codePoint >= 0xd800 && codePoint <= 0xdfff) {\n throw new TypeError('compound key string parts must contain valid Unicode scalar values');\n }\n }\n const body = utf8Encode(value);\n const out = new Uint8Array(1 + body.length);\n out[0] = TYPE_STRING;\n out.set(body, 1);\n return out;\n }\n if (value instanceof Uint8Array) {\n const out = new Uint8Array(1 + value.length);\n out[0] = TYPE_BYTES;\n out.set(value, 1);\n return out;\n }\n throw new TypeError('compound key parts must be string, number, boolean, null, or Uint8Array');\n}\nfunction encodeCompoundBytes(parts: ReadonlyArray<Uint8Array>): Uint8Array {\n let length = 0;\n for (const part of parts) {\n for (const byte of part) {\n length += byte === COMPOUND_ESCAPE ? 2 : 1;\n }\n length += 2;\n }\n const out = new Uint8Array(length);\n let offset = 0;\n for (const part of parts) {\n for (const byte of part) {\n if (byte === COMPOUND_ESCAPE) {\n out[offset] = COMPOUND_ESCAPE;\n out[offset + 1] = COMPOUND_ESCAPE_CONT;\n offset += 2;\n } else {\n out[offset] = byte;\n offset += 1;\n }\n }\n out[offset] = COMPOUND_TERM;\n out[offset + 1] = COMPOUND_TERM;\n offset += 2;\n }\n return out;\n}\nfunction encodeSortableNumber(value: number): Uint8Array {\n if (!Number.isFinite(value)) {\n throw new TypeError('compound key number parts must be finite');\n }\n const normalized = Object.is(value, -0) ? 0 : value;\n const buffer = new ArrayBuffer(9);\n const view = new DataView(buffer);\n view.setUint8(0, TYPE_NUMBER);\n view.setFloat64(1, normalized, false);\n let bits = view.getBigUint64(1, false);\n bits = (bits & (1n << 63n)) !== 0n ? ~bits & F64_MASK : bits ^ (1n << 63n);\n view.setBigUint64(1, bits, false);\n return new Uint8Array(buffer);\n}\n","import { InvalidOpenOptionsError, ReservedStoreNameError, SerializationError } from './errors';\nimport { compareStringsByCodeUnit } from './internal';\nimport {\n encodeCompoundKeyParts,\n encodeIndexScalar,\n prefixRange,\n prefixSuccessor,\n splitCompoundKey,\n utf8Encode\n} from './codec';\nimport type { IndexDef, Range } from './types';\nconst encoder = new TextEncoder();\nconst fatalDecoder = new TextDecoder('utf-8', { fatal: true });\nconst MISSING = Symbol('moyodb.indexing.missing');\nconst FNV64_OFFSET = BigInt('0xcbf29ce484222325');\nconst FNV64_PRIME = BigInt('0x100000001b3');\nconst FNV64_MASK = BigInt('0xffffffffffffffff');\n// Persisted store names use this legacy namespace. Renaming requires a migration.\nconst INTERNAL_STORE_PREFIX = '__browserdb:';\nconst INTERNAL_INDEX_STORE_PREFIX = '__browserdb:index:';\nexport const INDEX_METADATA_STORE = '__browserdb:indexes';\nexport interface NormalizedIndexDef {\n store: string;\n name: string;\n keyPath: string[];\n compound: boolean;\n unique: boolean;\n internalStore: string;\n}\nexport interface DecodedIndexEntryKey {\n logicalKey: Uint8Array;\n primaryKey: Uint8Array;\n}\nexport function isInternalStoreName(name: string): boolean {\n return name.startsWith(INTERNAL_STORE_PREFIX);\n}\nexport function assertPublicStoreName(name: string): void {\n if (isInternalStoreName(name)) {\n throw new ReservedStoreNameError(`reserved store name: ${name}`);\n }\n}\nexport function normalizeIndexDefinitions(value: unknown): NormalizedIndexDef[] {\n if (value === undefined) {\n return [];\n }\n if (!Array.isArray(value)) {\n throw new InvalidOpenOptionsError('indexes must be an array');\n }\n const normalized: NormalizedIndexDef[] = [];\n const identities = new Set<string>();\n const internalStores = new Map<string, string>();\n for (const entry of value) {\n if (entry === null || typeof entry !== 'object' || Array.isArray(entry)) {\n throw new InvalidOpenOptionsError('each index definition must be an object');\n }\n const { store, name, keyPath, unique } = entry as {\n store?: unknown;\n name?: unknown;\n keyPath?: unknown;\n unique?: unknown;\n };\n if (typeof store !== 'string' || store.length === 0) {\n throw new InvalidOpenOptionsError('index store must be a non-empty string');\n }\n if (typeof name !== 'string' || name.length === 0) {\n throw new InvalidOpenOptionsError('index name must be a non-empty string');\n }\n assertPublicStoreName(store);\n const keyPathInfo = normalizeIndexKeyPath(keyPath);\n if (unique !== undefined && typeof unique !== 'boolean') {\n throw new InvalidOpenOptionsError('index unique must be a boolean');\n }\n const def: NormalizedIndexDef = {\n store,\n name,\n keyPath: keyPathInfo.paths,\n compound: keyPathInfo.compound,\n unique: unique ?? false,\n internalStore: makeInternalIndexStoreName(store, name)\n };\n const identity = indexDefinitionIdentity(def.store, def.name);\n if (identities.has(identity)) {\n throw new InvalidOpenOptionsError(`duplicate index definition ${def.store}.${def.name}`);\n }\n identities.add(identity);\n const mappedIdentity = internalStores.get(def.internalStore);\n if (mappedIdentity && mappedIdentity !== identity) {\n throw new InvalidOpenOptionsError(\n `index definitions ${mappedIdentity} and ${identity} map to the same internal store ${def.internalStore}`\n );\n }\n internalStores.set(def.internalStore, identity);\n normalized.push(def);\n }\n normalized.sort(compareNormalizedIndexDefinitions);\n return normalized;\n}\nexport function compareNormalizedIndexDefinitions(left: NormalizedIndexDef, right: NormalizedIndexDef): number {\n const storeCompare = compareStringsByCodeUnit(left.store, right.store);\n if (storeCompare !== 0) {\n return storeCompare;\n }\n const nameCompare = compareStringsByCodeUnit(left.name, right.name);\n if (nameCompare !== 0) {\n return nameCompare;\n }\n const uniqueCompare = Number(left.unique) - Number(right.unique);\n if (uniqueCompare !== 0) {\n return uniqueCompare;\n }\n return compareStringsByCodeUnit(serializeIndexKeyPath(left), serializeIndexKeyPath(right));\n}\nexport function indexDefinitionIdentity(store: string, name: string): string {\n return JSON.stringify([store, name]);\n}\nexport function findIndexDefinition(\n defs: ReadonlyArray<NormalizedIndexDef>,\n store: string,\n name: string\n): NormalizedIndexDef | null {\n return defs.find((def) => def.store === store && def.name === name) ?? null;\n}\nexport function indexesForStore(defs: ReadonlyArray<NormalizedIndexDef>, store: string): NormalizedIndexDef[] {\n return defs.filter((def) => def.store === store);\n}\nexport function encodeIndexMetadataKey(store: string, name: string): Uint8Array {\n return encodeCompoundKeyParts([utf8Encode(store), utf8Encode(name)]);\n}\nexport function encodeIndexMetadataValue(def: NormalizedIndexDef): Uint8Array {\n return utf8Encode(JSON.stringify(toPublicIndexDefinition(def)));\n}\nexport function decodeIndexMetadataValue(bytes: Uint8Array): NormalizedIndexDef {\n let parsed: unknown;\n try {\n parsed = JSON.parse(fatalDecoder.decode(bytes));\n const [def] = normalizeIndexDefinitions([parsed]);\n return def;\n } catch (error) {\n throw new SerializationError(`invalid persisted index metadata: ${String(error)}`);\n }\n}\nexport function encodeIndexEntryKey(logicalIndexKey: Uint8Array, primaryKey: Uint8Array): Uint8Array {\n return encodeCompoundKeyParts([logicalIndexKey, primaryKey]);\n}\nexport function decodeIndexEntryKey(bytes: Uint8Array): DecodedIndexEntryKey {\n let parts: Uint8Array[];\n try {\n parts = splitCompoundKey(bytes);\n } catch (error) {\n throw new SerializationError(`invalid index entry key encoding: ${String(error)}`);\n }\n if (parts.length !== 2) {\n throw new SerializationError('invalid index entry key encoding');\n }\n return {\n logicalKey: parts[0],\n primaryKey: parts[1]\n };\n}\nexport function indexKeyExactRange(logicalIndexKey: Uint8Array): Range {\n return prefixRange(encodeCompoundKeyParts([logicalIndexKey]));\n}\nexport function indexRangeToPhysicalRange(range: Range = {}): Range {\n validateIndexRangeShape(range);\n const physical: Range = {};\n if (range.reverse !== undefined) {\n physical.reverse = range.reverse;\n }\n if (range.limit !== undefined) {\n physical.limit = range.limit;\n }\n if (range.gte) {\n physical.gte = encodeCompoundKeyParts([range.gte]);\n }\n if (range.gt) {\n const lower = prefixSuccessor(encodeCompoundKeyParts([range.gt]));\n if (lower) {\n physical.gte = lower;\n }\n }\n if (range.lt) {\n physical.lt = encodeCompoundKeyParts([range.lt]);\n }\n if (range.lte) {\n const upper = prefixSuccessor(encodeCompoundKeyParts([range.lte]));\n if (upper) {\n physical.lt = upper;\n }\n }\n return physical;\n}\nexport function extractLogicalIndexKey(def: NormalizedIndexDef, valueBytes: Uint8Array): Uint8Array | null {\n return extractLogicalIndexKeyFromDocument(def, decodeIndexedDocument(valueBytes));\n}\n/**\n * Reuse the decoded document only within one synchronous mutation plan.\n * Lazy decoding preserves validation order. Do not retain the extractor\n * across operations or an await.\n */\nexport function createIndexKeyExtractor(valueBytes: Uint8Array): (def: NormalizedIndexDef) => Uint8Array | null {\n let decoded = false;\n let documentValue: unknown;\n return (def) => {\n if (!decoded) {\n documentValue = decodeIndexedDocument(valueBytes);\n decoded = true;\n }\n return extractLogicalIndexKeyFromDocument(def, documentValue);\n };\n}\nexport function extractLogicalIndexKeyFromDocument(def: NormalizedIndexDef, documentValue: unknown): Uint8Array | null {\n if (def.compound) {\n const parts: Uint8Array[] = [];\n for (const keyPath of def.keyPath) {\n const resolved = resolveKeyPath(documentValue, keyPath);\n if (resolved === MISSING) {\n return null;\n }\n parts.push(encodeDocumentIndexValue(resolved));\n }\n return encodeCompoundKeyParts(parts);\n }\n const resolved = resolveKeyPath(documentValue, def.keyPath[0]);\n if (resolved === MISSING) {\n return null;\n }\n return encodeDocumentIndexValue(resolved);\n}\nexport function serializeNormalizedIndexDefinitions(defs: ReadonlyArray<NormalizedIndexDef>): string {\n return JSON.stringify(toPublicIndexDefinitions(defs));\n}\nexport function cloneNormalizedIndexDefinitions(defs: ReadonlyArray<NormalizedIndexDef>): NormalizedIndexDef[] {\n return defs.map((def) => ({\n store: def.store,\n name: def.name,\n keyPath: [...def.keyPath],\n compound: def.compound,\n unique: def.unique,\n internalStore: def.internalStore\n }));\n}\nexport function toPublicIndexDefinitions(defs: ReadonlyArray<NormalizedIndexDef>): IndexDef[] {\n return defs.map(toPublicIndexDefinition);\n}\nfunction toPublicIndexDefinition(def: NormalizedIndexDef): IndexDef {\n return {\n store: def.store,\n name: def.name,\n keyPath: def.compound ? [...def.keyPath] : def.keyPath[0],\n unique: def.unique\n };\n}\nfunction normalizeIndexKeyPath(value: unknown): {\n paths: string[];\n compound: boolean;\n} {\n if (typeof value === 'string') {\n validateSingleKeyPath(value);\n return { paths: [value], compound: false };\n }\n if (\n !Array.isArray(value) ||\n value.length === 0 ||\n !value.every((item): item is string => typeof item === 'string')\n ) {\n throw new InvalidOpenOptionsError('index keyPath must be a non-empty string or non-empty string[]');\n }\n for (const path of value) {\n validateSingleKeyPath(path);\n }\n return { paths: [...value], compound: true };\n}\nfunction validateSingleKeyPath(value: string): void {\n if (value.length === 0) {\n throw new InvalidOpenOptionsError('index keyPath strings must be non-empty');\n }\n if (value.startsWith('.') || value.endsWith('.') || value.includes('..')) {\n throw new InvalidOpenOptionsError(`invalid index keyPath: ${value}`);\n }\n}\nfunction serializeIndexKeyPath(def: NormalizedIndexDef): string {\n return def.compound ? `[${def.keyPath.join(',')}]` : def.keyPath[0];\n}\nfunction makeInternalIndexStoreName(store: string, name: string): string {\n const storeToken = base64Url(utf8Encode(store));\n const nameToken = base64Url(utf8Encode(name));\n const candidate = `${INTERNAL_INDEX_STORE_PREFIX}${storeToken}:${nameToken}`;\n if (encoder.encode(candidate).length <= 255) {\n return candidate;\n }\n // Preserve the persisted hash format. Normalization rejects distinct\n // identities that map to the same internal store, including separator collisions.\n const payload = utf8Encode(`${store}\\u0000${name}`);\n return `${INTERNAL_INDEX_STORE_PREFIX}h:${fnv1a64Hex(payload)}`;\n}\nfunction base64Url(bytes: Uint8Array): string {\n let binary = '';\n for (const byte of bytes) {\n binary += String.fromCharCode(byte);\n }\n return btoa(binary).replace(/\\+/g, '-').replace(/\\//g, '_').replace(/=+$/u, '');\n}\nfunction fnv1a64Hex(bytes: Uint8Array): string {\n let hash = FNV64_OFFSET;\n for (const byte of bytes) {\n hash ^= BigInt(byte);\n hash = (hash * FNV64_PRIME) & FNV64_MASK;\n }\n return hash.toString(16).padStart(16, '0');\n}\nexport function decodeIndexedDocument(bytes: Uint8Array): unknown {\n try {\n return JSON.parse(fatalDecoder.decode(bytes));\n } catch (error) {\n throw new SerializationError(`indexed values must be valid UTF-8 JSON: ${String(error)}`);\n }\n}\nfunction resolveKeyPath(root: unknown, keyPath: string): unknown {\n let current: unknown = root;\n for (const segment of keyPath.split('.')) {\n if (current === null || current === undefined) {\n return MISSING;\n }\n const target = Object(current) as Record<string, unknown>;\n if (!Object.hasOwn(target, segment)) {\n return MISSING;\n }\n current = Reflect.get(target, segment);\n }\n return current;\n}\nfunction encodeDocumentIndexValue(value: unknown): Uint8Array {\n if (\n value === null ||\n typeof value === 'string' ||\n typeof value === 'number' ||\n typeof value === 'boolean' ||\n value instanceof Uint8Array\n ) {\n try {\n return encodeIndexScalar(value);\n } catch (error) {\n if (error instanceof TypeError) {\n throw new SerializationError(`invalid indexed keyPath value: ${error.message}`);\n }\n throw error;\n }\n }\n throw new SerializationError(\n `indexed keyPath values must resolve to string, number, boolean, null, or Uint8Array; got ${describeValue(value)}`\n );\n}\nfunction describeValue(value: unknown): string {\n if (Array.isArray(value)) {\n return 'array';\n }\n return typeof value;\n}\nfunction validateIndexRangeShape(range: Range): void {\n if (range.gt !== undefined && range.gte !== undefined) {\n throw new TypeError('index range cannot specify both gt and gte');\n }\n if (range.lt !== undefined && range.lte !== undefined) {\n throw new TypeError('index range cannot specify both lt and lte');\n }\n}\n","import type { DbChange } from './types';\nimport { isRecord } from './internal';\nexport interface StoreChangeSet {\n store: string;\n changes: DbChange[];\n}\nexport interface CommitAppliedEvent {\n type: 'commit_applied';\n dbName: string;\n txid: number;\n stores: StoreChangeSet[];\n}\nexport interface OwnerChangedEvent {\n type: 'owner_changed';\n dbName: string;\n txid: null;\n}\nexport interface DbClosedEvent {\n type: 'db_closed';\n dbName: string;\n txid: null;\n}\nexport interface DbDeletedEvent {\n type: 'db_deleted';\n dbName: string;\n txid: null;\n}\nexport type WorkerBroadcastEvent = CommitAppliedEvent | OwnerChangedEvent | DbClosedEvent | DbDeletedEvent;\nfunction isDbChange(value: unknown): value is DbChange {\n if (!isRecord(value) || !(value.key instanceof Uint8Array)) {\n return false;\n }\n if (value.kind === 'put' || value.kind === 'delete') {\n return true;\n }\n return (value.kind === 'clear' || value.kind === 'drop') && value.key.byteLength === 0;\n}\nfunction isStoreChangeSet(value: unknown): value is StoreChangeSet {\n return (\n isRecord(value) &&\n typeof value.store === 'string' &&\n Array.isArray(value.changes) &&\n value.changes.every(isDbChange)\n );\n}\nexport function isCommitAppliedEvent(value: unknown): value is CommitAppliedEvent {\n return (\n isRecord(value) &&\n value.type === 'commit_applied' &&\n typeof value.dbName === 'string' &&\n typeof value.txid === 'number' &&\n Array.isArray(value.stores) &&\n value.stores.every(isStoreChangeSet)\n );\n}\n","import { DatabaseClosedError } from './errors';\nimport { isCommitAppliedEvent } from './change-events';\nimport { assertPublicStoreName } from './indexing';\nimport type { DbChange, DbSubscriptionCallback, Unsubscribe } from './types';\ninterface SubscriptionEntry {\n active: boolean;\n store: string | null;\n keyPrefix: Uint8Array | null;\n callback: DbSubscriptionCallback;\n}\ninterface SubscriptionSpec {\n store: string | null;\n keyPrefix: Uint8Array | null;\n callback: DbSubscriptionCallback;\n}\nfunction cloneChanges(changes: readonly DbChange[]): DbChange[] {\n return changes.map((change) => ({\n key: change.key.slice(),\n kind: change.kind\n }));\n}\nfunction hasKeyPrefix(key: Uint8Array, prefix: Uint8Array): boolean {\n if (prefix.byteLength > key.byteLength) {\n return false;\n }\n for (let index = 0; index < prefix.byteLength; index += 1) {\n if (key[index] !== prefix[index]) {\n return false;\n }\n }\n return true;\n}\nfunction normalizeSubscriptionSpec(\n arg1: string | DbSubscriptionCallback,\n arg2?: Uint8Array | DbSubscriptionCallback,\n arg3?: DbSubscriptionCallback\n): SubscriptionSpec {\n if (typeof arg1 === 'function') {\n if (arg2 !== undefined || arg3 !== undefined) {\n throw new TypeError('subscribe(callback) accepts exactly one callback argument');\n }\n return {\n store: null,\n keyPrefix: null,\n callback: arg1\n };\n }\n if (typeof arg1 !== 'string') {\n throw new TypeError('subscribe() storeName must be a string');\n }\n assertPublicStoreName(arg1);\n if (typeof arg2 === 'function') {\n if (arg3 !== undefined) {\n throw new TypeError('subscribe(storeName, callback) accepts exactly two arguments');\n }\n return {\n store: arg1,\n keyPrefix: null,\n callback: arg2\n };\n }\n if (arg2 instanceof Uint8Array && typeof arg3 === 'function') {\n return {\n store: arg1,\n keyPrefix: arg2.slice(),\n callback: arg3\n };\n }\n throw new TypeError(\n 'subscribe() expects one of: (callback), (storeName, callback), (storeName, keyPrefix, callback)'\n );\n}\nexport class SubscriptionHub {\n #dbName: string;\n #channel: BroadcastChannel | null = null;\n #entries = new Set<SubscriptionEntry>();\n #closed = false;\n constructor(dbName: string) {\n this.#dbName = dbName;\n }\n subscribe(callback: DbSubscriptionCallback): Unsubscribe;\n subscribe(storeName: string, callback: DbSubscriptionCallback): Unsubscribe;\n subscribe(storeName: string, keyPrefix: Uint8Array, callback: DbSubscriptionCallback): Unsubscribe;\n subscribe(\n arg1: string | DbSubscriptionCallback,\n arg2?: Uint8Array | DbSubscriptionCallback,\n arg3?: DbSubscriptionCallback\n ): Unsubscribe {\n if (this.#closed) {\n throw new DatabaseClosedError();\n }\n const spec = normalizeSubscriptionSpec(arg1, arg2, arg3);\n const entry: SubscriptionEntry = {\n active: true,\n store: spec.store,\n keyPrefix: spec.keyPrefix,\n callback: spec.callback\n };\n this.#ensureChannel();\n this.#entries.add(entry);\n return () => {\n if (!entry.active) {\n return;\n }\n entry.active = false;\n this.#entries.delete(entry);\n if (this.#entries.size === 0) {\n this.#disposeChannel();\n }\n };\n }\n close(): void {\n if (this.#closed) {\n return;\n }\n this.#closed = true;\n for (const entry of this.#entries) {\n entry.active = false;\n }\n this.#entries.clear();\n this.#disposeChannel();\n }\n #ensureChannel() {\n if (this.#channel !== null || this.#closed) {\n return;\n }\n const channel = new BroadcastChannel(`db:${this.#dbName}:events`);\n channel.onmessage = (event) => {\n this.#handleMessage(event.data);\n };\n this.#channel = channel;\n }\n #disposeChannel() {\n this.#channel?.close();\n this.#channel = null;\n }\n #handleMessage(payload: unknown) {\n if (!isCommitAppliedEvent(payload) || payload.dbName !== this.#dbName || this.#entries.size === 0) {\n return;\n }\n const entries = Array.from(this.#entries);\n for (const storeEvent of payload.stores) {\n for (const entry of entries) {\n if (!entry.active) {\n continue;\n }\n if (entry.store !== null && entry.store !== storeEvent.store) {\n continue;\n }\n let changes: DbChange[];\n const keyPrefix = entry.keyPrefix;\n if (keyPrefix === null) {\n changes = cloneChanges(storeEvent.changes);\n } else {\n changes = cloneChanges(\n storeEvent.changes.filter(\n (change) =>\n change.kind === 'clear' || change.kind === 'drop' || hasKeyPrefix(change.key, keyPrefix)\n )\n );\n if (changes.length === 0) {\n continue;\n }\n }\n try {\n entry.callback(storeEvent.store, changes, payload.txid);\n } catch (error) {\n queueMicrotask(() => {\n throw error;\n });\n }\n }\n }\n }\n}\n","import type {\n BatchOp,\n ChangeFeed,\n ChangeFeedOptions,\n CompactionResult,\n CreateStoreOptions,\n DB,\n DbSubscriptionCallback,\n DebugFailpoint,\n ExportSnapshotOptions,\n IndexDef,\n MigrateHook,\n OpenOptions,\n PutOptions,\n Range,\n ScanItem,\n StorageInfo,\n Transaction,\n TxId,\n TxMode,\n Unsubscribe\n} from './types';\nimport {\n acquireDbWorker,\n deleteDbByName,\n destroyDbWorker,\n invalidateTransactions,\n releaseDbWorker,\n subscribeHandleInvalidated,\n subscribeTransactionsInvalidated,\n unsafeDebugCrashWorker as crashWorkerByName,\n type RegistryEntry\n} from './registry';\nimport {\n DatabaseBusyError,\n DatabaseClosedError,\n InvalidOpenOptionsError,\n normalizeError,\n TransactionClosedError,\n UnsupportedPlatformError,\n VersionError\n} from './errors';\nimport {\n assertPublicStoreName,\n normalizeIndexDefinitions,\n serializeNormalizedIndexDefinitions,\n toPublicIndexDefinitions,\n type NormalizedIndexDef\n} from './indexing';\nimport { SubscriptionHub } from './subscriptions';\nimport { compareStringsByCodeUnit, withTimeout } from './internal';\nimport type { AutocommitCommand, IndexScanPage } from './worker-api';\nimport type { AutocommitArgs, WorkerCommandResult } from './worker-protocol';\n\nconst INDEX_SCAN_PAGE_ROWS = 256;\n\nasync function callProxy<T>(fn: () => Promise<T>): Promise<T> {\n try {\n return await fn();\n } catch (error) {\n throw normalizeError(error);\n }\n}\n\nclass TransactionImpl implements Transaction {\n readonly mode: TxMode;\n #entry: RegistryEntry;\n #txId: number;\n #closed = false;\n #onClose: () => void;\n constructor(entry: RegistryEntry, txId: number, mode: TxMode, onClose: () => void) {\n this.#entry = entry;\n this.#txId = txId;\n this.mode = mode;\n this.#onClose = onClose;\n }\n async get(store: string, key: Uint8Array): Promise<Uint8Array | null> {\n this.#ensureOpen();\n assertPublicStoreName(store);\n return callProxy(() => this.#entry.proxy.get(this.#txId, store, key));\n }\n async getMany(store: string, keys: Array<Uint8Array>): Promise<Array<Uint8Array | null>> {\n this.#ensureOpen();\n assertPublicStoreName(store);\n return callProxy(() => this.#entry.proxy.getMany(this.#txId, store, keys));\n }\n async has(store: string, key: Uint8Array): Promise<boolean> {\n this.#ensureOpen();\n assertPublicStoreName(store);\n return callProxy(() => this.#entry.proxy.has(this.#txId, store, key));\n }\n async put(store: string, key: Uint8Array, value: Uint8Array, options: PutOptions = {}): Promise<void> {\n this.#ensureOpen();\n assertPublicStoreName(store);\n return callProxy(() => this.#entry.proxy.put(this.#txId, store, key, value, normalizePutOptions(options)));\n }\n async putMany(store: string, entries: Array<[Uint8Array, Uint8Array]>, options: PutOptions = {}): Promise<void> {\n this.#ensureOpen();\n assertPublicStoreName(store);\n return callProxy(() => this.#entry.proxy.putMany(this.#txId, store, entries, normalizePutOptions(options)));\n }\n async delete(store: string, key: Uint8Array): Promise<boolean> {\n this.#ensureOpen();\n assertPublicStoreName(store);\n return callProxy(() => this.#entry.proxy.delete(this.#txId, store, key));\n }\n async deleteMany(store: string, keys: Array<Uint8Array>): Promise<void> {\n this.#ensureOpen();\n assertPublicStoreName(store);\n return callProxy(() => this.#entry.proxy.deleteMany(this.#txId, store, keys));\n }\n async applyBatch(store: string, ops: Array<BatchOp>): Promise<void> {\n this.#ensureOpen();\n assertPublicStoreName(store);\n return callProxy(() => this.#entry.proxy.applyBatch(this.#txId, store, ops));\n }\n async scan(store: string, range: Range = {}): Promise<ScanItem[]> {\n this.#ensureOpen();\n assertPublicStoreName(store);\n return callProxy(() => this.#entry.proxy.scan(this.#txId, store, range));\n }\n async getByIndex(store: string, indexName: string, key: Uint8Array): Promise<Uint8Array | null> {\n this.#ensureOpen();\n assertPublicStoreName(store);\n return callProxy(() => this.#entry.proxy.getByIndex(this.#txId, store, indexName, key));\n }\n async *scanByIndex(store: string, indexName: string, range: Range = {}): AsyncIterable<[Uint8Array, Uint8Array]> {\n this.#ensureOpen();\n assertPublicStoreName(store);\n let remaining = range.limit ?? Number.POSITIVE_INFINITY;\n let cursor: Uint8Array | null = null;\n while (remaining > 0) {\n this.#ensureOpen();\n const pageLimit = Math.min(remaining, INDEX_SCAN_PAGE_ROWS);\n const resumeAfter: Uint8Array | null = cursor;\n const page: IndexScanPage = await callProxy(() =>\n this.#entry.proxy.scanByIndexPage(this.#txId, store, indexName, range, resumeAfter, pageLimit)\n );\n for (const row of page.rows) {\n yield [row.key, row.value];\n }\n remaining -= page.rows.length;\n if (page.cursor === null) {\n return;\n }\n cursor = page.cursor;\n }\n }\n async createStore(name: string, options: CreateStoreOptions = {}): Promise<void> {\n this.#ensureOpen();\n assertPublicStoreName(name);\n return callProxy(() => this.#entry.proxy.createStore(this.#txId, name, normalizeCreateStoreOptions(options)));\n }\n async dropStore(name: string): Promise<void> {\n this.#ensureOpen();\n assertPublicStoreName(name);\n return callProxy(() => this.#entry.proxy.dropStore(this.#txId, name));\n }\n async clearStore(name: string): Promise<void> {\n this.#ensureOpen();\n assertPublicStoreName(name);\n return callProxy(() => this.#entry.proxy.clearStore(this.#txId, name));\n }\n async commit(): Promise<void> {\n this.#ensureOpen();\n try {\n await callProxy(() => this.#entry.proxy.commit(this.#txId));\n } finally {\n this.#markClosed();\n }\n }\n async rollback(): Promise<void> {\n this.#ensureOpen();\n try {\n await callProxy(() => this.#entry.proxy.rollback(this.#txId));\n } finally {\n this.#markClosed();\n }\n }\n async rollbackIfOpen(): Promise<void> {\n if (this.#closed) {\n return;\n }\n if (this.#entry.invalidated) {\n this.#markClosed();\n return;\n }\n try {\n await this.#entry.proxy.rollback(this.#txId);\n } catch (error) {\n const normalized = normalizeError(error);\n if (!(normalized instanceof TransactionClosedError)) {\n throw normalized;\n }\n } finally {\n this.#markClosed();\n }\n }\n forceClose(): void {\n this.#markClosed();\n }\n internalId(): number {\n return this.#txId;\n }\n #ensureOpen() {\n if (this.#closed || this.#entry.invalidated) {\n throw new TransactionClosedError();\n }\n }\n #markClosed() {\n if (this.#closed) {\n return;\n }\n this.#closed = true;\n this.#onClose();\n }\n}\nclass DBImpl implements DB {\n #entry: RegistryEntry;\n #closed = false;\n #closePromise: Promise<void> | null = null;\n #transactions = new Set<TransactionImpl>();\n #pendingBegins = new Set<Promise<TransactionImpl>>();\n #transactionGeneration = 0;\n #subscriptions: SubscriptionHub;\n #unsubscribeTxInvalidated: (() => void) | null = null;\n #unsubscribeHandleInvalidated: (() => void) | null = null;\n constructor(entry: RegistryEntry) {\n this.#entry = entry;\n this.#subscriptions = new SubscriptionHub(entry.dbName);\n this.#unsubscribeTxInvalidated = subscribeTransactionsInvalidated(entry, () => {\n this.#forceCloseTransactions();\n });\n this.#unsubscribeHandleInvalidated = subscribeHandleInvalidated(entry, () => {\n this.#markInvalidated();\n });\n }\n async begin(mode: TxMode = 'readonly'): Promise<Transaction> {\n return this.#beginImpl(mode);\n }\n async runSchemaMigration(\n oldVersion: number,\n newVersion: number,\n migrate: MigrateHook,\n targetIndexes: IndexDef[]\n ): Promise<void> {\n this.#ensureOpen();\n const tx = await this.#beginImpl('readwrite');\n const tracker = new MigrationCatalogTracker();\n const migrationTransaction = new MigrationTransactionImpl(tx, tracker);\n const migrationDb = new MigrationDbImpl(this, migrationTransaction, tracker);\n try {\n await this.#entry.proxy.reconcileIndexes(tx.internalId(), targetIndexes);\n await migrate({\n db: migrationDb,\n oldVersion,\n newVersion,\n transaction: migrationTransaction\n });\n await this.#entry.proxy.setSchemaVersion(tx.internalId(), newVersion);\n await tx.commit();\n } catch (error) {\n try {\n await tx.rollbackIfOpen();\n } catch {}\n throw error;\n }\n }\n async listStores(): Promise<string[]> {\n this.#ensureOpen();\n return callProxy(() => this.#entry.proxy.listStores());\n }\n async getVersion(): Promise<number> {\n this.#ensureOpen();\n return callProxy(() => this.#entry.proxy.getVersion());\n }\n async changesSince(txid: TxId, options: ChangeFeedOptions = {}): Promise<ChangeFeed> {\n this.#ensureOpen();\n return callProxy(() =>\n this.#entry.proxy.changesSince(normalizeTxId(txid), normalizeChangeFeedOptions(options))\n );\n }\n async #beginImpl(mode: TxMode): Promise<TransactionImpl> {\n this.#ensureOpen();\n const generation = this.#transactionGeneration;\n const pending = callProxy(async () => {\n const txId = await this.#entry.proxy.begin(mode);\n const tx = new TransactionImpl(this.#entry, txId, mode, () => {\n this.#transactions.delete(tx);\n });\n this.#transactions.add(tx);\n if (this.#closed || this.#entry.invalidated) {\n if (this.#entry.invalidated) {\n tx.forceClose();\n }\n throw new DatabaseClosedError();\n }\n if (generation !== this.#transactionGeneration) {\n await tx.rollbackIfOpen();\n throw new TransactionClosedError();\n }\n return tx;\n });\n this.#pendingBegins.add(pending);\n try {\n return await pending;\n } finally {\n this.#pendingBegins.delete(pending);\n }\n }\n async createStore(name: string, options: CreateStoreOptions = {}): Promise<void> {\n assertPublicStoreName(name);\n await this.#autocommit('readwrite', 'createStore', [name, normalizeCreateStoreOptions(options)]);\n }\n async dropStore(name: string): Promise<void> {\n assertPublicStoreName(name);\n await this.#autocommit('readwrite', 'dropStore', [name]);\n }\n async clearStore(name: string): Promise<void> {\n assertPublicStoreName(name);\n await this.#autocommit('readwrite', 'clearStore', [name]);\n }\n async get(store: string, key: Uint8Array): Promise<Uint8Array | null> {\n assertPublicStoreName(store);\n return this.#autocommit('readonly', 'get', [store, key]);\n }\n async getMany(store: string, keys: Array<Uint8Array>): Promise<Array<Uint8Array | null>> {\n assertPublicStoreName(store);\n return this.#autocommit('readonly', 'getMany', [store, keys]);\n }\n async has(store: string, key: Uint8Array): Promise<boolean> {\n assertPublicStoreName(store);\n return this.#autocommit('readonly', 'has', [store, key]);\n }\n async put(store: string, key: Uint8Array, value: Uint8Array, options: PutOptions = {}): Promise<void> {\n assertPublicStoreName(store);\n await this.#autocommit('readwrite', 'put', [store, key, value, normalizePutOptions(options)]);\n }\n async delete(store: string, key: Uint8Array): Promise<boolean> {\n assertPublicStoreName(store);\n return this.#autocommit('readwrite', 'delete', [store, key]);\n }\n async scan(store: string, range: Range = {}): Promise<ScanItem[]> {\n assertPublicStoreName(store);\n return this.#autocommit('readonly', 'scan', [store, range]);\n }\n /** The transaction boundary stays in the worker, so one round trip is enough. */\n async #autocommit<M extends AutocommitCommand>(\n mode: TxMode,\n command: M,\n args: AutocommitArgs<M>\n ): Promise<WorkerCommandResult<M>> {\n this.#ensureOpen();\n return callProxy(() => this.#entry.proxy.autocommit(mode, command, args));\n }\n async exportSnapshot(options: ExportSnapshotOptions = {}): Promise<Uint8Array> {\n this.#ensureOpen();\n return callProxy(async () => {\n const bytes = await this.#entry.proxy.exportSnapshot(normalizeExportSnapshotOptions(options));\n return bytes instanceof Uint8Array ? bytes : new Uint8Array(bytes);\n });\n }\n async importSnapshot(data: Uint8Array): Promise<void> {\n this.#ensureOpen();\n invalidateTransactions(this.#entry);\n return callProxy(() => {\n const bytes = data instanceof Uint8Array ? data : new Uint8Array(data);\n return this.#entry.proxy.importSnapshot(bytes);\n });\n }\n async reset(): Promise<void> {\n this.#ensureOpen();\n invalidateTransactions(this.#entry);\n return callProxy(() => this.#entry.proxy.reset());\n }\n async compact(): Promise<CompactionResult> {\n this.#ensureOpen();\n invalidateTransactions(this.#entry);\n return callProxy(() => this.#entry.proxy.compact());\n }\n async rebuild(): Promise<CompactionResult> {\n this.#ensureOpen();\n invalidateTransactions(this.#entry);\n return callProxy(() => this.#entry.proxy.rebuild());\n }\n async stats() {\n this.#ensureOpen();\n return callProxy(() => this.#entry.proxy.stats());\n }\n async storageInfo(): Promise<StorageInfo> {\n this.#ensureOpen();\n return callProxy(() => this.#entry.proxy.storageInfo());\n }\n async requestPersistence(): Promise<boolean> {\n this.#ensureOpen();\n return callProxy(() => this.#entry.proxy.requestPersistence());\n }\n async destroy(): Promise<void> {\n this.#ensureOpen();\n return callProxy(() => destroyDbWorker(this.#entry));\n }\n async setFailpoint(failpoint: DebugFailpoint): Promise<void> {\n this.#ensureOpen();\n return callProxy(() => this.#entry.proxy.setFailpoint(failpoint));\n }\n subscribe(callback: DbSubscriptionCallback): Unsubscribe;\n subscribe(storeName: string, callback: DbSubscriptionCallback): Unsubscribe;\n subscribe(storeName: string, keyPrefix: Uint8Array, callback: DbSubscriptionCallback): Unsubscribe;\n subscribe(\n arg1: string | DbSubscriptionCallback,\n arg2?: Uint8Array | DbSubscriptionCallback,\n arg3?: DbSubscriptionCallback\n ): Unsubscribe {\n this.#ensureOpen();\n if (typeof arg1 === 'function') {\n return this.#subscriptions.subscribe(arg1);\n }\n if (typeof arg2 === 'function') {\n return this.#subscriptions.subscribe(arg1, arg2);\n }\n if (arg2 instanceof Uint8Array && typeof arg3 === 'function') {\n return this.#subscriptions.subscribe(arg1, arg2, arg3);\n }\n throw new TypeError(\n 'subscribe() expects one of: (callback), (storeName, callback), (storeName, keyPrefix, callback)'\n );\n }\n watch(callback: DbSubscriptionCallback): Unsubscribe;\n watch(storeName: string, callback: DbSubscriptionCallback): Unsubscribe;\n watch(storeName: string, keyPrefix: Uint8Array, callback: DbSubscriptionCallback): Unsubscribe;\n watch(\n arg1: string | DbSubscriptionCallback,\n arg2?: Uint8Array | DbSubscriptionCallback,\n arg3?: DbSubscriptionCallback\n ): Unsubscribe {\n if (typeof arg1 === 'function') {\n return this.subscribe(arg1);\n }\n if (typeof arg2 === 'function') {\n return this.subscribe(arg1, arg2);\n }\n if (arg2 instanceof Uint8Array && typeof arg3 === 'function') {\n return this.subscribe(arg1, arg2, arg3);\n }\n throw new TypeError(\n 'watch() expects one of: (callback), (storeName, callback), (storeName, keyPrefix, callback)'\n );\n }\n close(): Promise<void> {\n if (this.#closePromise !== null) {\n return this.#closePromise;\n }\n if (this.#closed) {\n return Promise.resolve();\n }\n this.#closed = true;\n this.#disposeRegistrySubscriptions();\n this.#subscriptions.close();\n this.#closePromise = this.#finishClose();\n return this.#closePromise;\n }\n async #finishClose(): Promise<void> {\n await Promise.allSettled(Array.from(this.#pendingBegins));\n let rollbackError: Error | null = null;\n const txs = Array.from(this.#transactions);\n if (txs.length > 0) {\n const results = await Promise.allSettled(txs.map((tx) => tx.rollbackIfOpen()));\n for (const result of results) {\n if (result.status === 'rejected' && rollbackError === null) {\n rollbackError = normalizeError(result.reason);\n }\n }\n }\n try {\n await releaseDbWorker(this.#entry);\n } catch (error) {\n throw normalizeError(error);\n }\n if (rollbackError) {\n throw rollbackError;\n }\n }\n #disposeRegistrySubscriptions() {\n this.#unsubscribeTxInvalidated?.();\n this.#unsubscribeTxInvalidated = null;\n this.#unsubscribeHandleInvalidated?.();\n this.#unsubscribeHandleInvalidated = null;\n }\n #forceCloseTransactions() {\n this.#transactionGeneration += 1;\n for (const tx of Array.from(this.#transactions)) {\n tx.forceClose();\n }\n }\n #markInvalidated() {\n if (this.#closed) {\n return;\n }\n this.#closed = true;\n this.#disposeRegistrySubscriptions();\n this.#forceCloseTransactions();\n this.#subscriptions.close();\n }\n #ensureOpen() {\n if (this.#closed || this.#entry.invalidated) {\n throw new DatabaseClosedError();\n }\n }\n}\nclass MigrationCatalogTracker {\n #created = new Set<string>();\n #dropped = new Set<string>();\n recordCreate(name: string): void {\n this.#dropped.delete(name);\n this.#created.add(name);\n }\n recordDrop(name: string): void {\n if (this.#created.delete(name)) {\n return;\n }\n this.#dropped.add(name);\n }\n apply(stores: string[]): string[] {\n const visible = new Set(stores);\n for (const name of this.#created) {\n visible.add(name);\n }\n for (const name of this.#dropped) {\n visible.delete(name);\n }\n return Array.from(visible).sort(compareStringsByCodeUnit);\n }\n}\nclass MigrationTransactionImpl implements Transaction {\n #inner: TransactionImpl;\n #tracker: MigrationCatalogTracker;\n constructor(inner: TransactionImpl, tracker: MigrationCatalogTracker) {\n this.#inner = inner;\n this.#tracker = tracker;\n }\n get mode(): TxMode {\n return this.#inner.mode;\n }\n async get(store: string, key: Uint8Array): Promise<Uint8Array | null> {\n return this.#inner.get(store, key);\n }\n async getMany(store: string, keys: Array<Uint8Array>): Promise<Array<Uint8Array | null>> {\n return this.#inner.getMany(store, keys);\n }\n async has(store: string, key: Uint8Array): Promise<boolean> {\n return this.#inner.has(store, key);\n }\n async put(store: string, key: Uint8Array, value: Uint8Array, options: PutOptions = {}): Promise<void> {\n await this.#inner.put(store, key, value, options);\n }\n async putMany(store: string, entries: Array<[Uint8Array, Uint8Array]>, options: PutOptions = {}): Promise<void> {\n await this.#inner.putMany(store, entries, options);\n }\n async delete(store: string, key: Uint8Array): Promise<boolean> {\n return this.#inner.delete(store, key);\n }\n async deleteMany(store: string, keys: Array<Uint8Array>): Promise<void> {\n await this.#inner.deleteMany(store, keys);\n }\n async applyBatch(store: string, ops: Array<BatchOp>): Promise<void> {\n await this.#inner.applyBatch(store, ops);\n }\n async scan(store: string, range: Range = {}): Promise<ScanItem[]> {\n return this.#inner.scan(store, range);\n }\n async getByIndex(store: string, indexName: string, key: Uint8Array): Promise<Uint8Array | null> {\n return this.#inner.getByIndex(store, indexName, key);\n }\n scanByIndex(store: string, indexName: string, range: Range = {}): AsyncIterable<[Uint8Array, Uint8Array]> {\n return this.#inner.scanByIndex(store, indexName, range);\n }\n async createStore(name: string, options: CreateStoreOptions = {}): Promise<void> {\n await this.#inner.createStore(name, options);\n this.#tracker.recordCreate(name);\n }\n async dropStore(name: string): Promise<void> {\n await this.#inner.dropStore(name);\n this.#tracker.recordDrop(name);\n }\n async clearStore(name: string): Promise<void> {\n await this.#inner.clearStore(name);\n }\n commit(): Promise<void> {\n return Promise.reject(migrationUnsupportedMethod('transaction.commit'));\n }\n rollback(): Promise<void> {\n return Promise.reject(migrationUnsupportedMethod('transaction.rollback'));\n }\n}\nclass MigrationDbImpl implements DB {\n #db: DBImpl;\n #transaction: MigrationTransactionImpl;\n #tracker: MigrationCatalogTracker;\n constructor(db: DBImpl, transaction: MigrationTransactionImpl, tracker: MigrationCatalogTracker) {\n this.#db = db;\n this.#transaction = transaction;\n this.#tracker = tracker;\n }\n begin(_mode: TxMode = 'readonly'): Promise<Transaction> {\n return Promise.reject(migrationUnsupportedMethod('db.begin'));\n }\n async createStore(name: string, options: CreateStoreOptions = {}): Promise<void> {\n await this.#transaction.createStore(name, options);\n }\n async dropStore(name: string): Promise<void> {\n await this.#transaction.dropStore(name);\n }\n async clearStore(name: string): Promise<void> {\n await this.#transaction.clearStore(name);\n }\n async listStores(): Promise<string[]> {\n return this.#tracker.apply(await this.#db.listStores());\n }\n async getVersion(): Promise<number> {\n return this.#db.getVersion();\n }\n changesSince(_txid: TxId, _options: ChangeFeedOptions = {}): Promise<ChangeFeed> {\n return Promise.reject(migrationUnsupportedMethod('db.changesSince'));\n }\n async get(store: string, key: Uint8Array): Promise<Uint8Array | null> {\n return this.#transaction.get(store, key);\n }\n async getMany(store: string, keys: Array<Uint8Array>): Promise<Array<Uint8Array | null>> {\n return this.#transaction.getMany(store, keys);\n }\n async has(store: string, key: Uint8Array): Promise<boolean> {\n return this.#transaction.has(store, key);\n }\n async put(store: string, key: Uint8Array, value: Uint8Array, options: PutOptions = {}): Promise<void> {\n await this.#transaction.put(store, key, value, options);\n }\n async delete(store: string, key: Uint8Array): Promise<boolean> {\n return this.#transaction.delete(store, key);\n }\n async scan(store: string, range: Range = {}): Promise<ScanItem[]> {\n return this.#transaction.scan(store, range);\n }\n exportSnapshot(_options: ExportSnapshotOptions = {}): Promise<Uint8Array> {\n return Promise.reject(migrationUnsupportedMethod('db.exportSnapshot'));\n }\n importSnapshot(_data: Uint8Array): Promise<void> {\n return Promise.reject(migrationUnsupportedMethod('db.importSnapshot'));\n }\n reset(): Promise<void> {\n return Promise.reject(migrationUnsupportedMethod('db.reset'));\n }\n compact(): Promise<CompactionResult> {\n return Promise.reject(migrationUnsupportedMethod('db.compact'));\n }\n rebuild(): Promise<CompactionResult> {\n return Promise.reject(migrationUnsupportedMethod('db.rebuild'));\n }\n async stats() {\n return this.#db.stats();\n }\n async storageInfo(): Promise<StorageInfo> {\n return this.#db.storageInfo();\n }\n async requestPersistence(): Promise<boolean> {\n return this.#db.requestPersistence();\n }\n close(): Promise<void> {\n return Promise.reject(migrationUnsupportedMethod('db.close'));\n }\n destroy(): Promise<void> {\n return Promise.reject(migrationUnsupportedMethod('db.destroy'));\n }\n setFailpoint(_failpoint: DebugFailpoint): Promise<void> {\n return Promise.reject(migrationUnsupportedMethod('db.setFailpoint'));\n }\n subscribe(callback: DbSubscriptionCallback): Unsubscribe;\n subscribe(storeName: string, callback: DbSubscriptionCallback): Unsubscribe;\n subscribe(storeName: string, keyPrefix: Uint8Array, callback: DbSubscriptionCallback): Unsubscribe;\n subscribe(\n _arg1: string | DbSubscriptionCallback,\n _arg2?: Uint8Array | DbSubscriptionCallback,\n _arg3?: DbSubscriptionCallback\n ): Unsubscribe {\n throw migrationUnsupportedMethod('db.subscribe');\n }\n watch(callback: DbSubscriptionCallback): Unsubscribe;\n watch(storeName: string, callback: DbSubscriptionCallback): Unsubscribe;\n watch(storeName: string, keyPrefix: Uint8Array, callback: DbSubscriptionCallback): Unsubscribe;\n watch(\n _arg1: string | DbSubscriptionCallback,\n _arg2?: Uint8Array | DbSubscriptionCallback,\n _arg3?: DbSubscriptionCallback\n ): Unsubscribe {\n throw migrationUnsupportedMethod('db.watch');\n }\n}\nfunction migrationUnsupportedMethod(method: string): Error {\n const error = new Error(\n `${method}() is not available inside openDB() migrations; use the provided migration transaction and wait for openDB() to resolve`\n );\n error.name = 'InvalidStateError';\n return error;\n}\nfunction normalizeDatabaseName(value: unknown, method: 'openDB' | 'deleteDB' | 'unsafeDebugCrashWorker'): string {\n if (typeof value !== 'string' || value.length === 0) {\n throw new TypeError(`${method}() database name must be a non-empty string`);\n }\n return value;\n}\ntype ErrorFactory = (message: string) => Error;\n\nconst typeError: ErrorFactory = (message) => new TypeError(message);\nconst invalidOpenOptionsError: ErrorFactory = (message) => new InvalidOpenOptionsError(message);\n\nfunction normalizeOptionsObject<T>(options: unknown, message: string, createError: ErrorFactory = typeError): T {\n if (options === undefined) {\n return {} as T;\n }\n if (options === null || typeof options !== 'object' || Array.isArray(options)) {\n throw createError(message);\n }\n return options as T;\n}\n\nfunction normalizeNonNegativeSafeInteger(\n value: unknown,\n message: string,\n createError: ErrorFactory = typeError\n): number {\n if (typeof value !== 'number' || !Number.isSafeInteger(value) || value < 0) {\n throw createError(message);\n }\n return value;\n}\n\nfunction normalizeOptionalNonNegativeSafeInteger(\n value: unknown,\n message: string,\n createError?: ErrorFactory\n): number | undefined {\n return value === undefined ? undefined : normalizeNonNegativeSafeInteger(value, message, createError);\n}\n\nfunction normalizeOpenOptionsInput(options: unknown): OpenOptions {\n return normalizeOptionsObject(options, 'open options must be an object', invalidOpenOptionsError);\n}\nfunction normalizeSchemaVersion(value: unknown): number | undefined {\n return normalizeOptionalNonNegativeSafeInteger(\n value,\n 'version must be a non-negative safe integer',\n invalidOpenOptionsError\n );\n}\nfunction normalizePutOptions(options: unknown): PutOptions {\n const { ttl } = normalizeOptionsObject<{\n ttl?: unknown;\n }>(options, 'put options must be an object');\n const normalizedTtl = normalizeOptionalNonNegativeSafeInteger(ttl, 'ttl must be a non-negative safe integer');\n return normalizedTtl === undefined ? {} : { ttl: normalizedTtl };\n}\nfunction normalizeCompressionOptions<T extends CreateStoreOptions | ExportSnapshotOptions>(\n options: unknown,\n message: string\n): T {\n const { compression } = normalizeOptionsObject<{\n compression?: unknown;\n }>(options, message);\n if (compression === undefined) {\n return {} as T;\n }\n if (compression !== false && compression !== 'gzip' && compression !== 'deflate') {\n throw new TypeError('compression must be \"gzip\", \"deflate\", or false');\n }\n return { compression } as T;\n}\n\nfunction normalizeCreateStoreOptions(options: unknown): CreateStoreOptions {\n return normalizeCompressionOptions(options, 'createStore options must be an object');\n}\n\nfunction normalizeExportSnapshotOptions(options: unknown): ExportSnapshotOptions {\n return normalizeCompressionOptions(options, 'exportSnapshot options must be an object');\n}\nfunction normalizeTxId(value: unknown): TxId {\n return normalizeNonNegativeSafeInteger(value, 'txid must be a non-negative safe integer');\n}\nfunction normalizeChangeFeedOptions(options: unknown): ChangeFeedOptions {\n const { stores, limit } = normalizeOptionsObject<{\n stores?: unknown;\n limit?: unknown;\n }>(options, 'change feed options must be an object');\n const normalized: ChangeFeedOptions = {};\n if (stores !== undefined) {\n if (!Array.isArray(stores) || !stores.every((store): store is string => typeof store === 'string')) {\n throw new TypeError('stores must be an array of strings');\n }\n for (const store of stores) {\n assertPublicStoreName(store);\n }\n normalized.stores = [...stores];\n }\n const normalizedLimit = normalizeOptionalNonNegativeSafeInteger(limit, 'limit must be a non-negative safe integer');\n if (normalizedLimit !== undefined) {\n normalized.limit = normalizedLimit;\n }\n return normalized;\n}\nfunction normalizeMigrateHook(value: unknown): MigrateHook | undefined {\n if (value === undefined) {\n return undefined;\n }\n if (typeof value !== 'function') {\n throw new InvalidOpenOptionsError('migrate must be a function');\n }\n return value as MigrateHook;\n}\nfunction normalizeRequestedIndexes(value: unknown): NormalizedIndexDef[] | undefined {\n if (value === undefined) {\n return undefined;\n }\n return normalizeIndexDefinitions(value);\n}\nfunction indexDefinitionsMatch(\n left: ReadonlyArray<NormalizedIndexDef>,\n right: ReadonlyArray<NormalizedIndexDef>\n): boolean {\n return serializeNormalizedIndexDefinitions(left) === serializeNormalizedIndexDefinitions(right);\n}\nasync function loadNormalizedIndexes(entry: RegistryEntry): Promise<NormalizedIndexDef[]> {\n return normalizeIndexDefinitions(await entry.proxy.getIndexes());\n}\nfunction assertMainThreadCapabilities() {\n if (!globalThis.isSecureContext) {\n throw new UnsupportedPlatformError('moyodb requires a secure context (HTTPS)');\n }\n const nav = globalThis.navigator;\n if (typeof nav.storage.getDirectory !== 'function') {\n throw new UnsupportedPlatformError('navigator.storage.getDirectory is unavailable');\n }\n if (typeof globalThis.Worker !== 'function') {\n throw new UnsupportedPlatformError('Worker is unavailable');\n }\n if (typeof globalThis.BroadcastChannel === 'undefined') {\n throw new UnsupportedPlatformError('BroadcastChannel is unavailable');\n }\n}\nasync function requestPersistentStorageOnOpen(options: OpenOptions): Promise<void> {\n const nav = globalThis.navigator;\n if ((options.requestPersistence ?? true) && typeof nav.storage.persist === 'function') {\n await withTimeout(nav.storage.persist(), 1000, false);\n }\n}\nexport async function openDB(name: string, options: OpenOptions = {}): Promise<DB> {\n const dbName = normalizeDatabaseName(name, 'openDB');\n const normalizedOptions = normalizeOpenOptionsInput(options);\n const requestedVersion = normalizeSchemaVersion(normalizedOptions.version);\n const migrate = normalizeMigrateHook(normalizedOptions.migrate);\n const requestedIndexes = normalizeRequestedIndexes(normalizedOptions.indexes);\n if (requestedVersion === undefined && migrate !== undefined) {\n throw new InvalidOpenOptionsError('migrate requires version');\n }\n if (requestedVersion === undefined && requestedIndexes !== undefined) {\n throw new InvalidOpenOptionsError('indexes requires version');\n }\n assertMainThreadCapabilities();\n await requestPersistentStorageOnOpen(normalizedOptions);\n const entry = await acquireDbWorker(dbName, normalizedOptions);\n const db = new DBImpl(entry);\n try {\n if (requestedVersion === undefined) {\n return db;\n }\n const [currentVersion, currentIndexes] = await Promise.all([db.getVersion(), loadNormalizedIndexes(entry)]);\n if (requestedVersion < currentVersion) {\n throw new VersionError(\n `cannot open database ${dbName} at schema version ${requestedVersion}; current schema version is ${currentVersion}`\n );\n }\n if (requestedVersion === currentVersion) {\n if (requestedIndexes !== undefined && !indexDefinitionsMatch(requestedIndexes, currentIndexes)) {\n throw new VersionError(\n `database ${dbName} is already at schema version ${currentVersion}, but the requested index catalog does not match the committed schema`\n );\n }\n return db;\n }\n if (entry.refs > 1) {\n throw new DatabaseBusyError(\n `database ${dbName} is already open in this tab; close existing handles before migrating from version ${currentVersion} to ${requestedVersion}`\n );\n }\n if (!migrate) {\n throw new VersionError(\n `database ${dbName} requires migration from version ${currentVersion} to ${requestedVersion}, but no migrate hook was provided`\n );\n }\n const targetIndexes = requestedIndexes ?? currentIndexes;\n entry.schemaMigrationInProgress = true;\n try {\n await db.runSchemaMigration(\n currentVersion,\n requestedVersion,\n migrate,\n toPublicIndexDefinitions(targetIndexes)\n );\n } finally {\n entry.schemaMigrationInProgress = false;\n }\n return db;\n } catch (error) {\n try {\n await db.close();\n } catch {}\n throw normalizeError(error);\n }\n}\nexport async function deleteDB(name: string): Promise<void> {\n const dbName = normalizeDatabaseName(name, 'deleteDB');\n assertMainThreadCapabilities();\n await deleteDbByName(dbName);\n}\nexport function unsafeDebugCrashWorker(name: string): boolean {\n const dbName = normalizeDatabaseName(name, 'unsafeDebugCrashWorker');\n return crashWorkerByName(dbName);\n}\nexport * from './codec';\nexport * from './errors';\nexport * from './indexing';\nexport type * from './types';\n"],"mappings":";AAAA,SAAgB,EAAS,GAAkD;CACvE,OAAyB,OAAO,KAAU,cAAnC;AACX;AAEA,SAAgB,EAAyB,GAAc,GAAuB;CAI1E,OAHI,IAAO,IACA,KAEJ,MAAO;AAClB;AAEA,SAAgB,EAAe,GAAqB,GAAmB,GAAyB;CAC5F,OAAO,IAAI,SAAS,MAAY;EAC5B,IAAM,IAAU,iBAAiB,EAAQ,CAAQ,GAAG,CAAS;EAC7D,EAAQ,MACH,MAAU;GAEP,AADA,aAAa,CAAO,GACpB,EAAQ,CAAK;EACjB,SACM;GAEF,AADA,aAAa,CAAO,GACpB,EAAQ,CAAQ;EACpB,CACJ;CACJ,CAAC;AACL;ACnBA,IAOa,IAAkB,oZAuC/B,GA+BM,oBAAyB,IAAI,IAAY;CAhB3C;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AAG2C,CAAmB;AAElE,SAAgB,EAAoB,GAA4C;CAC5E,OAAO,OAAO,KAAU,YAAY,EAAuB,IAAI,CAAK;AACxE;AASA,IAAM,IAAwB,gCACxB,IAAiC,yCACjC,IAAsB,8BACtB,IAAsB,8BAGtB,IAA4B,oCAC5B,IAAkB,GAClB,KAAe,GACf,IAAU,YAEV,IAAsC,CAAC;AAwFlB,IAAI,IAAY,CAAe;AAM1D,SAAgB,GAA6B,GAAqD;CAC9F,OAAO,EAAS,CAAK,KAAK,EAAM,SAAA,kCAAkC,EAAM,YAAA;AAC5E;AAEA,SAAgB,GAAgC,GAAwD;CACpG,OACI,EAAS,CAAK,KACd,EAAM,SAAA,qCACN,EAAM,YAAA,KACN,OAAO,EAAM,MAAO,YACpB,OAAO,cAAc,EAAM,EAAE,KAC7B,OAAO,EAAM,MAAO;AAE5B;AAkBA,SAAgB,GAAqC,GAA6D;CAC9G,IAAI,CAAC,GAAsB,GAAA,yCAAuC,WAAW,GACzE,OAA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,eAAsB,GAAS,GAA6B;CACxD,IAAM,IAAS,GAAsB,GAAM,UAAU;CAErD,AADA,GAA6B,GAC7B,MAAM,GAAe,CAAM;AAC/B;AACA,SAAgB,GAAuB,GAAuB;CAE1D,OAAO,GADQ,GAAsB,GAAM,wBAClB,CAAM;AACnC"}
1
+ {"version":3,"file":"moyodb-sdk.js","names":[],"sources":["../src/internal.ts","../src/worker-protocol.ts","../src/worker-client.ts","../src/shared-worker-protocol.ts","../src/shared-worker-client.ts","../src/errors.ts","../src/registry.ts","../src/codec.ts","../src/indexing.ts","../src/change-events.ts","../src/subscriptions.ts","../src/records.ts","../src/sql-types.ts","../src/sql-parser.ts","../src/sql.ts","../src/index.ts"],"sourcesContent":["export function isRecord(value: unknown): value is Record<string, unknown> {\n return value !== null && typeof value === 'object';\n}\n\nexport function compareStringsByCodeUnit(left: string, right: string): number {\n if (left < right) {\n return -1;\n }\n return left > right ? 1 : 0;\n}\n\nexport function withTimeout<T>(promise: Promise<T>, timeoutMs: number, fallback: T): Promise<T> {\n return new Promise((resolve) => {\n const timeout = setTimeout(() => resolve(fallback), timeoutMs);\n promise.then(\n (value) => {\n clearTimeout(timeout);\n resolve(value);\n },\n () => {\n clearTimeout(timeout);\n resolve(fallback);\n }\n );\n });\n}\n","import type { AutocommitCommand, IndexScanPage, WorkerApi } from './worker-api';\nimport type { BatchOp } from './types';\nimport { isRecord } from './internal';\n\nexport const WORKER_PROTOCOL_VERSION = 1;\nexport const WORKER_PROTOCOL_READY = 'moyodb:worker-protocol:ready';\nexport const WORKER_PROTOCOL_REQUEST = 'moyodb:worker-protocol:request';\nexport const WORKER_PROTOCOL_RESPONSE = 'moyodb:worker-protocol:response';\nexport const WORKER_PROTOCOL_REQUEST_BATCH = 'moyodb:worker-protocol:request-batch';\nexport const WORKER_PROTOCOL_RESPONSE_BATCH = 'moyodb:worker-protocol:response-batch';\nexport const MAX_WORKER_BATCH_MESSAGES = 128;\nexport const MAX_WORKER_BATCH_BYTES = 1024 * 1024;\n\nexport const WORKER_COMMANDS = [\n 'open',\n 'close',\n 'destroy',\n 'deleteDB',\n 'begin',\n 'commit',\n 'rollback',\n 'autocommit',\n 'createStore',\n 'dropStore',\n 'clearStore',\n 'get',\n 'getMany',\n 'has',\n 'put',\n 'putMany',\n 'delete',\n 'deleteMany',\n 'applyBatch',\n 'scan',\n 'getByIndex',\n 'scanByIndex',\n 'scanByIndexPage',\n 'getIndexes',\n 'reconcileIndexes',\n 'listStores',\n 'getVersion',\n 'changesSince',\n 'setSchemaVersion',\n 'exportSnapshot',\n 'importSnapshot',\n 'reset',\n 'compact',\n 'rebuild',\n 'stats',\n 'storageInfo',\n 'requestPersistence',\n 'setFailpoint'\n] as const;\n\nexport type WorkerCommand = (typeof WORKER_COMMANDS)[number];\n\ntype WorkerMethod<M extends WorkerCommand> = WorkerApi[M] extends (...args: infer Args) => Promise<infer Result>\n ? { args: Args; result: Result }\n : never;\n\nexport type WorkerCommandArgs<M extends WorkerCommand> = WorkerMethod<M>['args'];\nexport type WorkerCommandResult<M extends WorkerCommand> = WorkerMethod<M>['result'];\n/** Arguments of an autocommit command without the leading transaction id. */\nexport type AutocommitArgs<M extends AutocommitCommand> =\n WorkerCommandArgs<M> extends [number, ...infer Rest] ? Rest : never;\n\nexport const AUTOCOMMIT_COMMANDS = [\n 'get',\n 'getMany',\n 'has',\n 'put',\n 'putMany',\n 'delete',\n 'deleteMany',\n 'applyBatch',\n 'scan',\n 'getByIndex',\n 'scanByIndex',\n 'createStore',\n 'dropStore',\n 'clearStore'\n] as const satisfies readonly AutocommitCommand[];\n\nconst AUTOCOMMIT_COMMAND_SET = new Set<string>(AUTOCOMMIT_COMMANDS);\n\nexport function isAutocommitCommand(value: unknown): value is AutocommitCommand {\n return typeof value === 'string' && AUTOCOMMIT_COMMAND_SET.has(value);\n}\n\nexport type PackedBatchOpKey = {\n kind: 'put' | 'delete';\n key: Uint8Array;\n};\n\ntype PreparedWorkerCommandArgs<M extends WorkerCommand> = WorkerCommandArgs<M> | unknown[];\n\nconst PACKED_BINARY_LIST_V1 = 'moyodb:packed-binary-list:v1';\nconst PACKED_NULLABLE_BINARY_LIST_V1 = 'moyodb:packed-nullable-binary-list:v1';\nconst PACKED_SCAN_ROWS_V1 = 'moyodb:packed-scan-rows:v1';\nconst PACKED_BATCH_OPS_V1 = 'moyodb:packed-batch-ops:v1';\n// Engine getMany format: u32 count | count x u32 length | concatenated values.\n// Integers are little-endian; u32::MAX marks a missing value. No repacking is needed.\nconst PACKED_OPTIONAL_VALUES_V1 = 'moyodb:packed-optional-values:v1';\nconst BATCH_OP_DELETE = 0;\nconst BATCH_OP_PUT = 1;\nconst U32_MAX = 0xffff_ffff;\nconst MAX_PACKED_RESPONSE_BYTES = 16 * 1024 * 1024;\nconst EMPTY_TRANSFERABLES: Transferable[] = [];\n\ninterface PackedBinaryListV1 {\n __moyodbPacked: typeof PACKED_BINARY_LIST_V1;\n bytes: Uint8Array;\n}\n\ninterface PackedNullableBinaryListV1 {\n __moyodbPacked: typeof PACKED_NULLABLE_BINARY_LIST_V1;\n bytes: Uint8Array;\n}\n\ninterface PackedScanRowsV1 {\n __moyodbPacked: typeof PACKED_SCAN_ROWS_V1;\n bytes: Uint8Array;\n}\n\ninterface PackedBatchOpsV1 {\n __moyodbPacked: typeof PACKED_BATCH_OPS_V1;\n bytes: Uint8Array;\n}\n\nexport interface PackedOptionalValuesV1 {\n __moyodbPacked: typeof PACKED_OPTIONAL_VALUES_V1;\n bytes: Uint8Array;\n}\n\ninterface PackedIndexScanPage {\n rows: PackedScanRowsV1 | IndexScanPage['rows'];\n cursor: Uint8Array | null;\n}\n\nexport type WorkerProtocolReadyMessage = {\n type: typeof WORKER_PROTOCOL_READY;\n version: typeof WORKER_PROTOCOL_VERSION;\n /** Enables batching; omitted by peers that use single messages. */\n batching?: 1;\n};\n\nexport type WorkerProtocolRequestMessage = {\n [M in WorkerCommand]: {\n type: typeof WORKER_PROTOCOL_REQUEST;\n version: typeof WORKER_PROTOCOL_VERSION;\n id: number;\n command: M;\n args: PreparedWorkerCommandArgs<M>;\n };\n}[WorkerCommand];\n\nexport interface WorkerProtocolRequestBatchMessage {\n type: typeof WORKER_PROTOCOL_REQUEST_BATCH;\n version: typeof WORKER_PROTOCOL_VERSION;\n requests: WorkerProtocolRequestMessage[];\n}\n\nexport interface SerializedWorkerError {\n name: string;\n code?: string;\n message: string;\n stack?: string;\n}\n\nexport type WorkerProtocolSuccessMessage = {\n [M in WorkerCommand]: {\n type: typeof WORKER_PROTOCOL_RESPONSE;\n version: typeof WORKER_PROTOCOL_VERSION;\n id: number;\n ok: true;\n result: WorkerCommandResult<M>;\n };\n}[WorkerCommand];\n\nexport interface WorkerProtocolErrorMessage {\n type: typeof WORKER_PROTOCOL_RESPONSE;\n version: typeof WORKER_PROTOCOL_VERSION;\n id: number;\n ok: false;\n error: SerializedWorkerError;\n}\n\nexport type WorkerProtocolResponseMessage = WorkerProtocolSuccessMessage | WorkerProtocolErrorMessage;\n\nexport interface WorkerProtocolResponseBatchMessage {\n type: typeof WORKER_PROTOCOL_RESPONSE_BATCH;\n version: typeof WORKER_PROTOCOL_VERSION;\n responses: WorkerProtocolResponseMessage[];\n}\n\nconst WORKER_COMMAND_SET = new Set<string>(WORKER_COMMANDS);\n\nexport function isWorkerCommand(value: unknown): value is WorkerCommand {\n return typeof value === 'string' && WORKER_COMMAND_SET.has(value);\n}\n\nexport function isWorkerProtocolReadyMessage(value: unknown): value is WorkerProtocolReadyMessage {\n return (\n isWorkerProtocolReadyEnvelope(value) &&\n value.version === WORKER_PROTOCOL_VERSION &&\n (value.batching === undefined || value.batching === 1)\n );\n}\n\nexport function isWorkerProtocolReadyEnvelope(\n value: unknown\n): value is { type: typeof WORKER_PROTOCOL_READY; version?: unknown; batching?: unknown } {\n return isRecord(value) && value.type === WORKER_PROTOCOL_READY;\n}\n\nexport function isWorkerProtocolResponseMessage(value: unknown): value is WorkerProtocolResponseMessage {\n return (\n isRecord(value) &&\n value.type === WORKER_PROTOCOL_RESPONSE &&\n value.version === WORKER_PROTOCOL_VERSION &&\n typeof value.id === 'number' &&\n Number.isSafeInteger(value.id) &&\n typeof value.ok === 'boolean'\n );\n}\n\nexport function isWorkerProtocolRequestMessage(value: unknown): value is WorkerProtocolRequestMessage {\n return (\n isRecord(value) &&\n value.type === WORKER_PROTOCOL_REQUEST &&\n value.version === WORKER_PROTOCOL_VERSION &&\n typeof value.id === 'number' &&\n Number.isSafeInteger(value.id) &&\n typeof value.command === 'string' &&\n Array.isArray(value.args)\n );\n}\n\nexport function isWorkerProtocolRequestBatchMessage(value: unknown): value is WorkerProtocolRequestBatchMessage {\n return isWorkerProtocolBatch(value, WORKER_PROTOCOL_REQUEST_BATCH, 'requests');\n}\n\nexport function isWorkerProtocolResponseBatchMessage(value: unknown): value is WorkerProtocolResponseBatchMessage {\n if (!isWorkerProtocolBatch(value, WORKER_PROTOCOL_RESPONSE_BATCH, 'responses')) {\n return false;\n }\n for (const response of (value as WorkerProtocolResponseBatchMessage).responses) {\n if (!isWorkerProtocolResponseMessage(response)) return false;\n }\n return true;\n}\n\nfunction isWorkerProtocolBatch(value: unknown, type: string, items: string): boolean {\n return (\n isRecord(value) &&\n value.type === type &&\n value.version === WORKER_PROTOCOL_VERSION &&\n Array.isArray(value[items]) &&\n value[items].length > 0 &&\n value[items].length <= MAX_WORKER_BATCH_MESSAGES\n );\n}\n\nexport function isWorkerProtocolEnvelope(value: unknown): value is { type: string; id?: unknown } {\n return (\n isRecord(value) &&\n (value.type === WORKER_PROTOCOL_REQUEST ||\n value.type === WORKER_PROTOCOL_RESPONSE ||\n value.type === WORKER_PROTOCOL_REQUEST_BATCH ||\n value.type === WORKER_PROTOCOL_RESPONSE_BATCH ||\n value.type === WORKER_PROTOCOL_READY)\n );\n}\n\nexport function serializeWorkerError(error: unknown): SerializedWorkerError {\n if (isRecord(error)) {\n const code = stringOrUndefined(error.code);\n const name = stringOrUndefined(error.name) ?? code ?? 'Error';\n return {\n name,\n code,\n message: stringOrUndefined(error.message) ?? 'Unknown error',\n stack: stringOrUndefined(error.stack)\n };\n }\n return {\n name: 'Error',\n message: String(error)\n };\n}\n\nexport function deserializeWorkerError(error: unknown): Error {\n if (\n !isRecord(error) ||\n typeof error.name !== 'string' ||\n typeof error.message !== 'string' ||\n (error.code !== undefined && typeof error.code !== 'string') ||\n (error.stack !== undefined && typeof error.stack !== 'string')\n ) {\n throw workerProtocolError('WorkerProtocolError', 'invalid serialized worker error');\n }\n const deserialized = new Error(error.message);\n deserialized.name = error.name || error.code || 'Error';\n if (error.stack) {\n deserialized.stack = error.stack;\n }\n if (error.code) {\n Object.defineProperty(deserialized, 'code', {\n value: error.code,\n enumerable: true,\n configurable: true\n });\n }\n return deserialized;\n}\n\nexport function workerProtocolError(name: string, message: string, code = name): Error {\n const error = new Error(message);\n error.name = name;\n Object.defineProperty(error, 'code', {\n value: code,\n enumerable: true,\n configurable: true\n });\n return error;\n}\n\nexport function prepareWorkerCommandPayload<M extends WorkerCommand>(\n command: M,\n args: WorkerCommandArgs<M>\n): { args: PreparedWorkerCommandArgs<M>; transfer: Transferable[] } {\n if (command === 'autocommit') {\n const [mode, inner, innerArgs] = args as WorkerCommandArgs<'autocommit'>;\n if (isAutocommitCommand(inner) && Array.isArray(innerArgs)) {\n // The normal packer expects a transaction ID. Use a placeholder, then remove it.\n const prepared = prepareWorkerCommandPayload(inner, [0, ...innerArgs] as never);\n return {\n args: [mode, inner, (prepared.args as unknown[]).slice(1)],\n transfer: prepared.transfer\n };\n }\n }\n\n if (\n command === 'get' ||\n command === 'has' ||\n command === 'delete' ||\n command === 'getByIndex' ||\n command === 'put'\n ) {\n const keyIndex = command === 'getByIndex' ? 3 : 2;\n let copiedArgs: unknown[] | null = null;\n let transfer: Transferable[] | null = null;\n for (let index = keyIndex; index <= (command === 'put' ? 3 : keyIndex); index += 1) {\n const value = args[index];\n if (\n value instanceof Uint8Array &&\n value.buffer instanceof ArrayBuffer &&\n (value.byteOffset !== 0 || value.byteLength !== value.buffer.byteLength)\n ) {\n const owned = copyToOwnedUint8Array(value);\n copiedArgs ??= [...args];\n copiedArgs[index] = owned;\n (transfer ??= []).push(owned.buffer);\n }\n }\n if (copiedArgs !== null) {\n return { args: copiedArgs, transfer: transfer ?? EMPTY_TRANSFERABLES };\n }\n }\n\n if (command === 'importSnapshot') {\n const data = args[0];\n if (data instanceof Uint8Array) {\n const owned = copyToOwnedUint8Array(data);\n return {\n args: [owned] as WorkerCommandArgs<M>,\n transfer: [owned.buffer]\n };\n }\n }\n\n if (command === 'getMany' || command === 'deleteMany') {\n const [txId, store, keys] = args as WorkerCommandArgs<'getMany'> | WorkerCommandArgs<'deleteMany'>;\n if (Array.isArray(keys) && keys.length > 0) {\n const packed = packBinaryList(keys);\n return {\n args: [txId, store, packed],\n transfer: [packed.bytes.buffer]\n };\n }\n }\n\n if (command === 'putMany') {\n const [txId, store, entries, options] = args as WorkerCommandArgs<'putMany'>;\n if (Array.isArray(entries) && entries.length > 0) {\n const packed = packBinaryPairs(entries);\n return {\n args: [txId, store, packed, options],\n transfer: [packed.bytes.buffer]\n };\n }\n }\n\n if (command === 'applyBatch') {\n const [txId, store, ops] = args as WorkerCommandArgs<'applyBatch'>;\n if (Array.isArray(ops) && ops.length > 0) {\n const packed = packBatchOps(ops);\n return {\n args: [txId, store, packed],\n transfer: [packed.bytes.buffer]\n };\n }\n }\n\n return { args, transfer: EMPTY_TRANSFERABLES };\n}\n\nexport function decodeWorkerCommandPayload<M extends WorkerCommand>(\n command: M,\n args: PreparedWorkerCommandArgs<M>\n): WorkerCommandArgs<M> {\n if (command === 'autocommit') {\n const [mode, inner, innerArgs] = args as WorkerCommandArgs<'autocommit'>;\n if (isAutocommitCommand(inner) && Array.isArray(innerArgs)) {\n const decoded = decodeWorkerCommandPayload(inner, [0, ...innerArgs]) as unknown[];\n return [mode, inner, decoded.slice(1)] as WorkerCommandArgs<M>;\n }\n }\n\n if (command === 'getMany' || command === 'deleteMany') {\n const [txId, store, keys] = args as WorkerCommandArgs<'getMany'> | WorkerCommandArgs<'deleteMany'>;\n if (!Array.isArray(keys)) {\n if (!isPackedBinaryList(keys)) {\n throw workerProtocolError('WorkerProtocolError', 'invalid packed binary-list argument');\n }\n return [txId, store, unpackBinaryList(keys)] as WorkerCommandArgs<M>;\n }\n }\n\n if (command === 'putMany') {\n const [txId, store, entries, options] = args as WorkerCommandArgs<'putMany'>;\n if (!Array.isArray(entries)) {\n if (!isPackedBinaryList(entries)) {\n throw workerProtocolError('WorkerProtocolError', 'invalid packed putMany argument');\n }\n return [txId, store, unpackBinaryPairs(entries), options] as WorkerCommandArgs<M>;\n }\n }\n\n if (command === 'applyBatch') {\n const [txId, store, ops] = args as WorkerCommandArgs<'applyBatch'>;\n if (!Array.isArray(ops)) {\n if (!isPackedBatchOps(ops)) {\n throw workerProtocolError('WorkerProtocolError', 'invalid packed batch argument');\n }\n return [txId, store, unpackBatchOps(ops)] as WorkerCommandArgs<M>;\n }\n }\n\n return args;\n}\n\nexport function packedBinaryListBytes(value: unknown): Uint8Array | null {\n return isPackedBinaryList(value) ? value.bytes : null;\n}\n\nexport function packedBatchOpsBytes(value: unknown): Uint8Array | null {\n return isPackedBatchOps(value) ? value.bytes : null;\n}\n\nexport function unpackPackedBinaryList(bytes: Uint8Array): Uint8Array[] {\n return unpackBinaryList({ __moyodbPacked: PACKED_BINARY_LIST_V1, bytes });\n}\n\nexport function unpackPackedBinaryPairs(bytes: Uint8Array): Array<[Uint8Array, Uint8Array]> {\n return unpackBinaryPairs({ __moyodbPacked: PACKED_BINARY_LIST_V1, bytes });\n}\n\nexport function unpackPackedBinaryPairKeys(bytes: Uint8Array): Uint8Array[] {\n return unpackBinaryPairKeys({ __moyodbPacked: PACKED_BINARY_LIST_V1, bytes });\n}\n\nexport function unpackPackedBatchOps(bytes: Uint8Array): Array<BatchOp> {\n return unpackBatchOps({ __moyodbPacked: PACKED_BATCH_OPS_V1, bytes });\n}\n\nexport function unpackPackedBatchOpKeys(bytes: Uint8Array): PackedBatchOpKey[] {\n return unpackBatchOpKeys({ __moyodbPacked: PACKED_BATCH_OPS_V1, bytes });\n}\n\nexport function packedOptionalValues(bytes: Uint8Array): PackedOptionalValuesV1 {\n return { __moyodbPacked: PACKED_OPTIONAL_VALUES_V1, bytes };\n}\n\nexport function unpackPackedOptionalValues(bytes: Uint8Array): Array<Uint8Array | null> {\n if (!(bytes instanceof Uint8Array) || bytes.byteLength < 4) {\n throw workerProtocolError('WorkerProtocolError', 'invalid packed optional-values payload');\n }\n const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);\n const count = view.getUint32(0, true);\n const metadataBytes = checkedByteCount(count, 4, 'packed optional-values metadata');\n const payloadOffset = checkedAdd(4, metadataBytes, 'packed optional-values header');\n if (payloadOffset > bytes.byteLength) {\n throw workerProtocolError('WorkerProtocolError', 'packed optional-values metadata exceeds payload length');\n }\n const items = new Array<Uint8Array | null>(count);\n let readOffset = payloadOffset;\n for (let index = 0; index < count; index += 1) {\n const byteLength = view.getUint32(4 + index * 4, true);\n if (byteLength === U32_MAX) {\n items[index] = null;\n continue;\n }\n const end = readOffset + byteLength;\n if (end > bytes.byteLength) {\n throw workerProtocolError('WorkerProtocolError', 'packed optional-values item exceeds payload length');\n }\n items[index] = bytes.subarray(readOffset, end);\n readOffset = end;\n }\n if (readOffset !== bytes.byteLength) {\n throw workerProtocolError('WorkerProtocolError', 'packed optional-values payload has trailing bytes');\n }\n return items;\n}\n\nexport function prepareWorkerResponsePayload<M extends WorkerCommand>(\n command: M,\n result: WorkerCommandResult<M>\n): { result: unknown; transfer: Transferable[] } {\n if (command === 'getMany' && isPackedOptionalValues(result)) {\n return {\n result,\n transfer: collectDirectBinaryTransferable(result.bytes)\n };\n }\n\n if (command === 'scanByIndexPage') {\n const page = result as WorkerCommandResult<'scanByIndexPage'>;\n if (isRecord(page) && Array.isArray(page.rows)) {\n const packed = page.rows.length > 0 ? packScanRows(page.rows) : null;\n const response: PackedIndexScanPage = { rows: packed ?? page.rows, cursor: page.cursor };\n const transfer = packed ? [packed.bytes.buffer] : collectTransferablesForValue(page.rows);\n const cursorBuffer = directBinaryTransferable(page.cursor);\n return {\n result: response,\n transfer: cursorBuffer === null ? transfer : [...transfer, cursorBuffer]\n };\n }\n }\n\n if (command === 'getMany') {\n const values = result as WorkerCommandResult<'getMany'>;\n if (Array.isArray(values) && values.length > 0) {\n const packed = packNullableBinaryList(values);\n if (packed) {\n return {\n result: packed,\n transfer: [packed.bytes.buffer]\n };\n }\n }\n return {\n result,\n transfer: collectTransferablesForValue(result)\n };\n }\n\n if (command === 'scan' || command === 'scanByIndex') {\n const rows = result as WorkerCommandResult<'scan'>;\n if (Array.isArray(rows) && rows.length > 0) {\n const packed = packScanRows(rows);\n if (packed) {\n return {\n result: packed,\n transfer: [packed.bytes.buffer]\n };\n }\n }\n return {\n result,\n transfer: collectTransferablesForValue(result)\n };\n }\n\n if (command === 'get' || command === 'getByIndex' || command === 'exportSnapshot') {\n return {\n result,\n transfer: collectDirectBinaryTransferable(result)\n };\n }\n\n if (command === 'changesSince') {\n return {\n result,\n transfer: collectChangeFeedTransferables(result)\n };\n }\n\n // Remaining result types contain no binary payloads, so they need no buffer walk.\n return {\n result,\n transfer: []\n };\n}\n\nexport function decodeWorkerResponsePayload<M extends WorkerCommand>(\n command: M,\n result: unknown\n): WorkerCommandResult<M> {\n if (command === 'getMany' && isPackedNullableBinaryList(result)) {\n return unpackNullableBinaryList(result);\n }\n\n if (command === 'getMany' && isPackedOptionalValues(result)) {\n return unpackPackedOptionalValues(result.bytes) as WorkerCommandResult<M>;\n }\n\n if (command === 'getMany' && !Array.isArray(result)) {\n throw workerProtocolError('WorkerProtocolError', 'invalid packed getMany response');\n }\n\n if (command === 'scanByIndexPage') {\n if (\n !isRecord(result) ||\n (!Array.isArray(result.rows) && !isPackedScanRows(result.rows)) ||\n (result.cursor !== null && !(result.cursor instanceof Uint8Array))\n ) {\n throw workerProtocolError('WorkerProtocolError', 'invalid packed index scan page response');\n }\n const rows = isPackedScanRows(result.rows) ? unpackScanRows(result.rows) : result.rows;\n return { rows, cursor: result.cursor } as WorkerCommandResult<M>;\n }\n\n if ((command === 'scan' || command === 'scanByIndex') && isPackedScanRows(result)) {\n return unpackScanRows(result);\n }\n\n if ((command === 'scan' || command === 'scanByIndex') && !Array.isArray(result)) {\n throw workerProtocolError('WorkerProtocolError', 'invalid packed scan response');\n }\n\n return result;\n}\n\nexport function collectTransferablesForValue(value: unknown): Transferable[] {\n const direct = directBinaryTransferable(value);\n if (direct !== null) {\n return [direct];\n }\n if (value === null || value === undefined || typeof value !== 'object') {\n return EMPTY_TRANSFERABLES;\n }\n\n const buffers = new Set<ArrayBuffer>();\n const seen = new WeakSet<object>();\n collectTransferableBuffers(value, buffers, seen);\n return buffers.size === 0 ? EMPTY_TRANSFERABLES : Array.from(buffers);\n}\n\n/**\n * Capture the message before batching can observe later mutations. Listed\n * transferables move into the snapshot; other ArrayBuffers are cloned.\n * SharedArrayBuffers remain shared. byteLength is a batch-size estimate.\n */\nexport function captureWorkerPayload<T>(\n value: T,\n transfer: Transferable[]\n): { value: T; transfer: Transferable[]; byteLength: number } {\n const captured =\n transfer.length > 0\n ? structuredClone(value, { transfer: transfer.length === 1 ? transfer : Array.from(new Set(transfer)) })\n : structuredClone(value);\n const buffers = new Set<ArrayBuffer>();\n const seen = new WeakSet<object>();\n let byteLength = 0;\n const visit = (item: unknown): void => {\n if (typeof item === 'string') {\n byteLength += 8 + item.length * 2;\n return;\n }\n if (item === null || typeof item !== 'object') {\n byteLength += 8;\n return;\n }\n if (seen.has(item)) return;\n seen.add(item);\n byteLength += 8;\n if (item instanceof ArrayBuffer) {\n buffers.add(item);\n byteLength += item.byteLength;\n } else if (typeof SharedArrayBuffer !== 'undefined' && item instanceof SharedArrayBuffer) {\n byteLength += item.byteLength;\n } else if (ArrayBuffer.isView(item)) {\n visit(item.buffer);\n } else if (Array.isArray(item)) {\n for (const child of item) visit(child);\n } else if (item instanceof Map) {\n for (const [key, child] of item) {\n visit(key);\n visit(child);\n }\n } else if (item instanceof Set) {\n for (const child of item) visit(child);\n } else {\n const record = item as Record<string, unknown>;\n for (const key in record) {\n if (Object.prototype.hasOwnProperty.call(record, key)) {\n byteLength += 8 + key.length * 2;\n visit(record[key]);\n }\n }\n }\n };\n visit(captured);\n return {\n value: captured,\n transfer: buffers.size === 0 ? EMPTY_TRANSFERABLES : Array.from(buffers),\n byteLength\n };\n}\n\nfunction collectDirectBinaryTransferable(value: unknown): Transferable[] {\n const direct = directBinaryTransferable(value);\n return direct === null ? EMPTY_TRANSFERABLES : [direct];\n}\n\nfunction directBinaryTransferable(value: unknown): ArrayBuffer | null {\n if (value instanceof ArrayBuffer) {\n return value;\n }\n if (ArrayBuffer.isView(value)) {\n const buffer = value.buffer;\n if (buffer instanceof ArrayBuffer && value.byteOffset === 0 && value.byteLength === buffer.byteLength) {\n return buffer;\n }\n }\n return null;\n}\n\nfunction collectChangeFeedTransferables(value: unknown): Transferable[] {\n if (!isRecord(value) || !Array.isArray(value.changes) || value.changes.length === 0) {\n return EMPTY_TRANSFERABLES;\n }\n\n let buffers: Set<ArrayBuffer> | null = null;\n for (const change of value.changes) {\n if (!isRecord(change)) {\n continue;\n }\n const key = directBinaryTransferable(change.key);\n if (key !== null) {\n buffers ??= new Set<ArrayBuffer>();\n buffers.add(key);\n }\n const changedValue = directBinaryTransferable(change.value);\n if (changedValue !== null) {\n buffers ??= new Set<ArrayBuffer>();\n buffers.add(changedValue);\n }\n }\n return buffers === null || buffers.size === 0 ? EMPTY_TRANSFERABLES : Array.from(buffers);\n}\n\nfunction collectTransferableBuffers(value: unknown, buffers: Set<ArrayBuffer>, seen: WeakSet<object>): void {\n if (value === null || value === undefined) {\n return;\n }\n if (value instanceof ArrayBuffer) {\n buffers.add(value);\n return;\n }\n if (ArrayBuffer.isView(value)) {\n const buffer = value.buffer;\n if (buffer instanceof ArrayBuffer && value.byteOffset === 0 && value.byteLength === buffer.byteLength) {\n buffers.add(buffer);\n }\n return;\n }\n if (typeof value !== 'object') {\n return;\n }\n const object = value;\n if (seen.has(object)) {\n return;\n }\n seen.add(object);\n if (Array.isArray(value)) {\n for (const item of value) {\n collectTransferableBuffers(item, buffers, seen);\n }\n return;\n }\n const record = value as Record<string, unknown>;\n for (const key in record) {\n if (Object.prototype.hasOwnProperty.call(record, key)) {\n collectTransferableBuffers(record[key], buffers, seen);\n }\n }\n}\n\nfunction packBinaryPairs(entries: Array<[Uint8Array, Uint8Array]>): PackedBinaryListV1 {\n const entryCount = entries.length;\n const count = checkedU32(entryCount * 2, 'packed putMany item count');\n const metadataBytes = checkedByteCount(count, 4, 'packed putMany metadata');\n let payloadBytes = 0;\n for (let index = 0; index < entryCount; index += 1) {\n const entry = entries[index];\n const key = entry[0];\n const value = entry[1];\n if (!(key instanceof Uint8Array) || !(value instanceof Uint8Array)) {\n throw workerProtocolError('WorkerProtocolError', 'putMany entry key/value is not a Uint8Array');\n }\n const keyLength = checkedU32(key.byteLength, 'putMany key length');\n const valueLength = checkedU32(value.byteLength, 'putMany value length');\n payloadBytes += keyLength + valueLength;\n if (payloadBytes > U32_MAX) {\n throw workerProtocolError('WorkerProtocolError', 'packed putMany payload exceeds 32-bit payload limit');\n }\n }\n const payloadOffset = checkedAdd(4, metadataBytes, 'packed putMany header');\n const totalBytes = checkedAdd(payloadOffset, payloadBytes, 'packed putMany total');\n const bytes = new Uint8Array(totalBytes);\n const view = new DataView(bytes.buffer);\n view.setUint32(0, count, true);\n let metadataOffset = 4;\n let writeOffset = payloadOffset;\n for (let index = 0; index < entryCount; index += 1) {\n const entry = entries[index];\n const key = entry[0];\n const value = entry[1];\n const keyLength = key.byteLength;\n const valueLength = value.byteLength;\n view.setUint32(metadataOffset, keyLength, true);\n metadataOffset += 4;\n view.setUint32(metadataOffset, valueLength, true);\n metadataOffset += 4;\n bytes.set(key, writeOffset);\n writeOffset += keyLength;\n bytes.set(value, writeOffset);\n writeOffset += valueLength;\n }\n return {\n __moyodbPacked: PACKED_BINARY_LIST_V1,\n bytes\n };\n}\n\nfunction packBinaryList(items: Uint8Array[]): PackedBinaryListV1 {\n const count = items.length;\n const metadataBytes = checkedByteCount(count, 4, 'packed binary-list metadata');\n let payloadBytes = 0;\n for (let index = 0; index < count; index += 1) {\n const item = items[index];\n if (!(item instanceof Uint8Array)) {\n throw workerProtocolError('WorkerProtocolError', 'binary-list payload item is not a Uint8Array');\n }\n const itemLength = checkedU32(item.byteLength, 'binary-list item length');\n payloadBytes += itemLength;\n if (payloadBytes > U32_MAX) {\n throw workerProtocolError('WorkerProtocolError', 'packed binary-list payload exceeds 32-bit payload limit');\n }\n }\n const payloadOffset = checkedAdd(4, metadataBytes, 'packed binary-list header');\n const totalBytes = checkedAdd(payloadOffset, payloadBytes, 'packed binary-list total');\n const bytes = new Uint8Array(totalBytes);\n const view = new DataView(bytes.buffer);\n view.setUint32(0, count, true);\n let metadataOffset = 4;\n let writeOffset = payloadOffset;\n for (let index = 0; index < count; index += 1) {\n const item = items[index];\n const itemLength = item.byteLength;\n view.setUint32(metadataOffset, itemLength, true);\n metadataOffset += 4;\n bytes.set(item, writeOffset);\n writeOffset += itemLength;\n }\n return {\n __moyodbPacked: PACKED_BINARY_LIST_V1,\n bytes\n };\n}\n\nfunction unpackBinaryList(payload: PackedBinaryListV1): Uint8Array[] {\n const bytes = payload.bytes;\n if (!(bytes instanceof Uint8Array) || bytes.byteLength < 4) {\n throw workerProtocolError('WorkerProtocolError', 'invalid packed binary-list payload');\n }\n const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);\n const count = view.getUint32(0, true);\n const metadataBytes = checkedByteCount(count, 4, 'packed binary-list metadata');\n const payloadOffset = checkedAdd(4, metadataBytes, 'packed binary-list header');\n if (payloadOffset > bytes.byteLength) {\n throw workerProtocolError('WorkerProtocolError', 'packed binary-list metadata exceeds payload length');\n }\n\n const items = new Array<Uint8Array>(count);\n let metadataOffset = 4;\n let readOffset = payloadOffset;\n for (let index = 0; index < count; index += 1) {\n const byteLength = view.getUint32(metadataOffset, true);\n metadataOffset += 4;\n const end = readOffset + byteLength;\n if (end > U32_MAX || end > bytes.byteLength) {\n throw workerProtocolError('WorkerProtocolError', 'packed binary-list item exceeds payload length');\n }\n items[index] = bytes.subarray(readOffset, end);\n readOffset = end;\n }\n if (readOffset !== bytes.byteLength) {\n throw workerProtocolError('WorkerProtocolError', 'packed binary-list payload has trailing bytes');\n }\n return items;\n}\n\nfunction unpackBinaryPairs(payload: PackedBinaryListV1): Array<[Uint8Array, Uint8Array]> {\n const bytes = payload.bytes;\n if (!(bytes instanceof Uint8Array) || bytes.byteLength < 4) {\n throw workerProtocolError('WorkerProtocolError', 'invalid packed putMany payload');\n }\n const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);\n const itemCount = view.getUint32(0, true);\n if (itemCount % 2 !== 0) {\n throw workerProtocolError('WorkerProtocolError', 'packed putMany payload has an odd item count');\n }\n const metadataBytes = checkedByteCount(itemCount, 4, 'packed putMany metadata');\n const payloadOffset = checkedAdd(4, metadataBytes, 'packed putMany header');\n if (payloadOffset > bytes.byteLength) {\n throw workerProtocolError('WorkerProtocolError', 'packed putMany metadata exceeds payload length');\n }\n\n const entryCount = itemCount / 2;\n const entries = new Array<[Uint8Array, Uint8Array]>(entryCount);\n let metadataOffset = 4;\n let readOffset = payloadOffset;\n for (let index = 0; index < entryCount; index += 1) {\n const keyLength = view.getUint32(metadataOffset, true);\n const valueLength = view.getUint32(metadataOffset + 4, true);\n metadataOffset += 8;\n\n const keyEnd = readOffset + keyLength;\n if (keyEnd > U32_MAX || keyEnd > bytes.byteLength) {\n throw workerProtocolError('WorkerProtocolError', 'packed putMany key exceeds payload length');\n }\n const valueEnd = keyEnd + valueLength;\n if (valueEnd > U32_MAX || valueEnd > bytes.byteLength) {\n throw workerProtocolError('WorkerProtocolError', 'packed putMany value exceeds payload length');\n }\n entries[index] = [bytes.subarray(readOffset, keyEnd), bytes.subarray(keyEnd, valueEnd)];\n readOffset = valueEnd;\n }\n if (readOffset !== bytes.byteLength) {\n throw workerProtocolError('WorkerProtocolError', 'packed putMany payload has trailing bytes');\n }\n return entries;\n}\n\nfunction unpackBinaryPairKeys(payload: PackedBinaryListV1): Uint8Array[] {\n const bytes = payload.bytes;\n if (!(bytes instanceof Uint8Array) || bytes.byteLength < 4) {\n throw workerProtocolError('WorkerProtocolError', 'invalid packed putMany payload');\n }\n const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);\n const itemCount = view.getUint32(0, true);\n if (itemCount % 2 !== 0) {\n throw workerProtocolError('WorkerProtocolError', 'packed putMany payload has an odd item count');\n }\n const metadataBytes = checkedByteCount(itemCount, 4, 'packed putMany metadata');\n const payloadOffset = checkedAdd(4, metadataBytes, 'packed putMany header');\n if (payloadOffset > bytes.byteLength) {\n throw workerProtocolError('WorkerProtocolError', 'packed putMany metadata exceeds payload length');\n }\n\n const entryCount = itemCount / 2;\n const keys = new Array<Uint8Array>(entryCount);\n let metadataOffset = 4;\n let readOffset = payloadOffset;\n for (let index = 0; index < entryCount; index += 1) {\n const keyLength = view.getUint32(metadataOffset, true);\n const valueLength = view.getUint32(metadataOffset + 4, true);\n metadataOffset += 8;\n\n const keyEnd = readOffset + keyLength;\n if (keyEnd > U32_MAX || keyEnd > bytes.byteLength) {\n throw workerProtocolError('WorkerProtocolError', 'packed putMany key exceeds payload length');\n }\n const valueEnd = keyEnd + valueLength;\n if (valueEnd > U32_MAX || valueEnd > bytes.byteLength) {\n throw workerProtocolError('WorkerProtocolError', 'packed putMany value exceeds payload length');\n }\n keys[index] = bytes.subarray(readOffset, keyEnd);\n readOffset = valueEnd;\n }\n if (readOffset !== bytes.byteLength) {\n throw workerProtocolError('WorkerProtocolError', 'packed putMany payload has trailing bytes');\n }\n return keys;\n}\n\nfunction packNullableBinaryList(items: Array<Uint8Array | null>): PackedNullableBinaryListV1 | null {\n const count = items.length;\n const metadataBytes = checkedByteCount(count, 5, 'packed nullable binary-list metadata');\n let payloadBytes = 0;\n for (let index = 0; index < count; index += 1) {\n const item = items[index];\n if (item === null) {\n continue;\n }\n if (!(item instanceof Uint8Array)) {\n throw workerProtocolError(\n 'WorkerProtocolError',\n 'nullable binary-list payload item is not a Uint8Array or null'\n );\n }\n const itemLength = checkedU32(item.byteLength, 'nullable binary-list item length');\n payloadBytes += itemLength;\n if (payloadBytes > U32_MAX) {\n throw workerProtocolError(\n 'WorkerProtocolError',\n 'packed nullable binary-list payload exceeds 32-bit payload limit'\n );\n }\n }\n const payloadOffset = checkedAdd(4, metadataBytes, 'packed nullable binary-list header');\n const totalBytes = checkedAdd(payloadOffset, payloadBytes, 'packed nullable binary-list total');\n if (totalBytes > MAX_PACKED_RESPONSE_BYTES) {\n return null;\n }\n const bytes = new Uint8Array(totalBytes);\n const view = new DataView(bytes.buffer);\n view.setUint32(0, count, true);\n let metadataOffset = 4;\n let writeOffset = payloadOffset;\n for (let index = 0; index < count; index += 1) {\n const item = items[index];\n if (item === null) {\n view.setUint8(metadataOffset, 0);\n view.setUint32(metadataOffset + 1, 0, true);\n metadataOffset += 5;\n continue;\n }\n const itemLength = item.byteLength;\n view.setUint8(metadataOffset, 1);\n view.setUint32(metadataOffset + 1, itemLength, true);\n metadataOffset += 5;\n bytes.set(item, writeOffset);\n writeOffset += itemLength;\n }\n return {\n __moyodbPacked: PACKED_NULLABLE_BINARY_LIST_V1,\n bytes\n };\n}\n\nfunction unpackNullableBinaryList(payload: PackedNullableBinaryListV1): Array<Uint8Array | null> {\n const bytes = payload.bytes;\n if (!(bytes instanceof Uint8Array) || bytes.byteLength < 4) {\n throw workerProtocolError('WorkerProtocolError', 'invalid packed nullable binary-list payload');\n }\n const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);\n const count = view.getUint32(0, true);\n const metadataBytes = checkedByteCount(count, 5, 'packed nullable binary-list metadata');\n const payloadOffset = checkedAdd(4, metadataBytes, 'packed nullable binary-list header');\n if (payloadOffset > bytes.byteLength) {\n throw workerProtocolError('WorkerProtocolError', 'packed nullable binary-list metadata exceeds payload length');\n }\n\n const items = new Array<Uint8Array | null>(count);\n let metadataOffset = 4;\n let readOffset = payloadOffset;\n for (let index = 0; index < count; index += 1) {\n const present = view.getUint8(metadataOffset);\n const byteLength = view.getUint32(metadataOffset + 1, true);\n metadataOffset += 5;\n if (present === 0) {\n if (byteLength !== 0) {\n throw workerProtocolError(\n 'WorkerProtocolError',\n 'packed nullable binary-list null item has a payload length'\n );\n }\n items[index] = null;\n continue;\n }\n if (present !== 1) {\n throw workerProtocolError(\n 'WorkerProtocolError',\n `packed nullable binary-list item has invalid presence byte: ${present}`\n );\n }\n const end = readOffset + byteLength;\n if (end > U32_MAX || end > bytes.byteLength) {\n throw workerProtocolError('WorkerProtocolError', 'packed nullable binary-list item exceeds payload length');\n }\n items[index] = bytes.subarray(readOffset, end);\n readOffset = end;\n }\n if (readOffset !== bytes.byteLength) {\n throw workerProtocolError('WorkerProtocolError', 'packed nullable binary-list payload has trailing bytes');\n }\n return items;\n}\n\nfunction packScanRows(rows: Array<{ key: Uint8Array; value: Uint8Array }>): PackedScanRowsV1 | null {\n const count = rows.length;\n const metadataBytes = checkedByteCount(count, 8, 'packed scan row metadata');\n let payloadBytes = 0;\n for (let index = 0; index < count; index += 1) {\n const row = rows[index];\n if (!isRecord(row) || !(row.key instanceof Uint8Array) || !(row.value instanceof Uint8Array)) {\n throw workerProtocolError('WorkerProtocolError', 'scan row payload key/value is not a Uint8Array');\n }\n const keyLength = checkedU32(row.key.byteLength, 'scan row key length');\n const valueLength = checkedU32(row.value.byteLength, 'scan row value length');\n payloadBytes += keyLength + valueLength;\n if (payloadBytes > U32_MAX) {\n throw workerProtocolError('WorkerProtocolError', 'packed scan row payload exceeds 32-bit payload limit');\n }\n }\n const payloadOffset = checkedAdd(4, metadataBytes, 'packed scan row header');\n const totalBytes = checkedAdd(payloadOffset, payloadBytes, 'packed scan row total');\n if (totalBytes > MAX_PACKED_RESPONSE_BYTES) {\n return null;\n }\n const bytes = new Uint8Array(totalBytes);\n const view = new DataView(bytes.buffer);\n view.setUint32(0, count, true);\n let metadataOffset = 4;\n let writeOffset = payloadOffset;\n for (let index = 0; index < count; index += 1) {\n const row = rows[index];\n const key = row.key;\n const value = row.value;\n const keyLength = key.byteLength;\n const valueLength = value.byteLength;\n view.setUint32(metadataOffset, keyLength, true);\n view.setUint32(metadataOffset + 4, valueLength, true);\n metadataOffset += 8;\n bytes.set(key, writeOffset);\n writeOffset += keyLength;\n bytes.set(value, writeOffset);\n writeOffset += valueLength;\n }\n return {\n __moyodbPacked: PACKED_SCAN_ROWS_V1,\n bytes\n };\n}\n\nfunction unpackScanRows(payload: PackedScanRowsV1): Array<{ key: Uint8Array; value: Uint8Array }> {\n const bytes = payload.bytes;\n if (!(bytes instanceof Uint8Array) || bytes.byteLength < 4) {\n throw workerProtocolError('WorkerProtocolError', 'invalid packed scan row payload');\n }\n const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);\n const count = view.getUint32(0, true);\n const metadataBytes = checkedByteCount(count, 8, 'packed scan row metadata');\n const payloadOffset = checkedAdd(4, metadataBytes, 'packed scan row header');\n if (payloadOffset > bytes.byteLength) {\n throw workerProtocolError('WorkerProtocolError', 'packed scan row metadata exceeds payload length');\n }\n\n const rows = new Array<{ key: Uint8Array; value: Uint8Array }>(count);\n let metadataOffset = 4;\n let readOffset = payloadOffset;\n for (let index = 0; index < count; index += 1) {\n const keyLength = view.getUint32(metadataOffset, true);\n const valueLength = view.getUint32(metadataOffset + 4, true);\n metadataOffset += 8;\n const keyEnd = readOffset + keyLength;\n if (keyEnd > U32_MAX || keyEnd > bytes.byteLength) {\n throw workerProtocolError('WorkerProtocolError', 'packed scan row key exceeds payload length');\n }\n const valueEnd = keyEnd + valueLength;\n if (valueEnd > U32_MAX || valueEnd > bytes.byteLength) {\n throw workerProtocolError('WorkerProtocolError', 'packed scan row value exceeds payload length');\n }\n rows[index] = {\n key: bytes.subarray(readOffset, keyEnd),\n value: bytes.subarray(keyEnd, valueEnd)\n };\n readOffset = valueEnd;\n }\n if (readOffset !== bytes.byteLength) {\n throw workerProtocolError('WorkerProtocolError', 'packed scan row payload has trailing bytes');\n }\n return rows;\n}\n\nfunction packBatchOps(ops: Array<BatchOp>): PackedBatchOpsV1 {\n const count = ops.length;\n const metadataBytes = checkedByteCount(count, 9, 'packed batch metadata');\n let payloadBytes = 0;\n for (let index = 0; index < count; index += 1) {\n const op: unknown = ops[index];\n if (!isRecord(op) || (op.kind !== 'put' && op.kind !== 'delete')) {\n throw workerProtocolError('WorkerProtocolError', 'batch operation kind is not put or delete');\n }\n if (!(op.key instanceof Uint8Array)) {\n throw workerProtocolError('WorkerProtocolError', 'batch operation key is not a Uint8Array');\n }\n const keyLength = checkedU32(op.key.byteLength, 'batch operation key length');\n payloadBytes += keyLength;\n if (payloadBytes > U32_MAX) {\n throw workerProtocolError('WorkerProtocolError', 'packed batch payload exceeds 32-bit payload limit');\n }\n if (op.kind === 'put') {\n if (!(op.value instanceof Uint8Array)) {\n throw workerProtocolError('WorkerProtocolError', 'batch put value is not a Uint8Array');\n }\n const valueLength = checkedU32(op.value.byteLength, 'batch put value length');\n payloadBytes += valueLength;\n if (payloadBytes > U32_MAX) {\n throw workerProtocolError('WorkerProtocolError', 'packed batch payload exceeds 32-bit payload limit');\n }\n }\n }\n const payloadOffset = checkedAdd(4, metadataBytes, 'packed batch header');\n const totalBytes = checkedAdd(payloadOffset, payloadBytes, 'packed batch total');\n const bytes = new Uint8Array(totalBytes);\n const view = new DataView(bytes.buffer);\n view.setUint32(0, count, true);\n let metadataOffset = 4;\n let writeOffset = payloadOffset;\n for (let index = 0; index < count; index += 1) {\n const op = ops[index];\n const key = op.key;\n const keyLength = key.byteLength;\n const valueLength = op.kind === 'put' ? op.value.byteLength : 0;\n view.setUint8(metadataOffset, op.kind === 'put' ? BATCH_OP_PUT : BATCH_OP_DELETE);\n view.setUint32(metadataOffset + 1, keyLength, true);\n view.setUint32(metadataOffset + 5, valueLength, true);\n metadataOffset += 9;\n bytes.set(key, writeOffset);\n writeOffset += keyLength;\n if (op.kind === 'put') {\n bytes.set(op.value, writeOffset);\n writeOffset += valueLength;\n }\n }\n return {\n __moyodbPacked: PACKED_BATCH_OPS_V1,\n bytes\n };\n}\n\nfunction unpackBatchOps(payload: PackedBatchOpsV1): Array<BatchOp> {\n const bytes = payload.bytes;\n if (!(bytes instanceof Uint8Array) || bytes.byteLength < 4) {\n throw workerProtocolError('WorkerProtocolError', 'invalid packed batch payload');\n }\n const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);\n const count = view.getUint32(0, true);\n const metadataBytes = checkedByteCount(count, 9, 'packed batch metadata');\n const payloadOffset = checkedAdd(4, metadataBytes, 'packed batch header');\n if (payloadOffset > bytes.byteLength) {\n throw workerProtocolError('WorkerProtocolError', 'packed batch metadata exceeds payload length');\n }\n\n const ops = new Array<BatchOp>(count);\n let metadataOffset = 4;\n let readOffset = payloadOffset;\n for (let index = 0; index < count; index += 1) {\n const kind = view.getUint8(metadataOffset);\n const keyLength = view.getUint32(metadataOffset + 1, true);\n const valueLength = view.getUint32(metadataOffset + 5, true);\n metadataOffset += 9;\n\n const keyEnd = readOffset + keyLength;\n if (keyEnd > U32_MAX || keyEnd > bytes.byteLength) {\n throw workerProtocolError('WorkerProtocolError', 'packed batch key exceeds payload length');\n }\n const key = bytes.subarray(readOffset, keyEnd);\n readOffset = keyEnd;\n\n if (kind === BATCH_OP_DELETE) {\n if (valueLength !== 0) {\n throw workerProtocolError('WorkerProtocolError', 'packed delete operation has a value payload');\n }\n ops[index] = { kind: 'delete', key };\n continue;\n }\n\n if (kind !== BATCH_OP_PUT) {\n throw workerProtocolError('WorkerProtocolError', `packed batch operation has invalid kind byte: ${kind}`);\n }\n const valueEnd = readOffset + valueLength;\n if (valueEnd > U32_MAX || valueEnd > bytes.byteLength) {\n throw workerProtocolError('WorkerProtocolError', 'packed batch value exceeds payload length');\n }\n ops[index] = { kind: 'put', key, value: bytes.subarray(readOffset, valueEnd) };\n readOffset = valueEnd;\n }\n if (readOffset !== bytes.byteLength) {\n throw workerProtocolError('WorkerProtocolError', 'packed batch payload has trailing bytes');\n }\n return ops;\n}\n\nfunction unpackBatchOpKeys(payload: PackedBatchOpsV1): PackedBatchOpKey[] {\n const bytes = payload.bytes;\n if (!(bytes instanceof Uint8Array) || bytes.byteLength < 4) {\n throw workerProtocolError('WorkerProtocolError', 'invalid packed batch payload');\n }\n const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);\n const count = view.getUint32(0, true);\n const metadataBytes = checkedByteCount(count, 9, 'packed batch metadata');\n const payloadOffset = checkedAdd(4, metadataBytes, 'packed batch header');\n if (payloadOffset > bytes.byteLength) {\n throw workerProtocolError('WorkerProtocolError', 'packed batch metadata exceeds payload length');\n }\n\n const ops = new Array<PackedBatchOpKey>(count);\n let metadataOffset = 4;\n let readOffset = payloadOffset;\n for (let index = 0; index < count; index += 1) {\n const kind = view.getUint8(metadataOffset);\n const keyLength = view.getUint32(metadataOffset + 1, true);\n const valueLength = view.getUint32(metadataOffset + 5, true);\n metadataOffset += 9;\n\n const keyEnd = readOffset + keyLength;\n if (keyEnd > U32_MAX || keyEnd > bytes.byteLength) {\n throw workerProtocolError('WorkerProtocolError', 'packed batch key exceeds payload length');\n }\n const key = bytes.subarray(readOffset, keyEnd);\n readOffset = keyEnd;\n\n if (kind === BATCH_OP_DELETE) {\n if (valueLength !== 0) {\n throw workerProtocolError('WorkerProtocolError', 'packed delete operation has a value payload');\n }\n ops[index] = { kind: 'delete', key };\n continue;\n }\n\n if (kind !== BATCH_OP_PUT) {\n throw workerProtocolError('WorkerProtocolError', `packed batch operation has invalid kind byte: ${kind}`);\n }\n const valueEnd = readOffset + valueLength;\n if (valueEnd > U32_MAX || valueEnd > bytes.byteLength) {\n throw workerProtocolError('WorkerProtocolError', 'packed batch value exceeds payload length');\n }\n ops[index] = { kind: 'put', key };\n readOffset = valueEnd;\n }\n if (readOffset !== bytes.byteLength) {\n throw workerProtocolError('WorkerProtocolError', 'packed batch payload has trailing bytes');\n }\n return ops;\n}\n\nfunction isPackedBinaryList(value: unknown): value is PackedBinaryListV1 {\n return isRecord(value) && value.__moyodbPacked === PACKED_BINARY_LIST_V1 && value.bytes instanceof Uint8Array;\n}\n\nfunction isPackedNullableBinaryList(value: unknown): value is PackedNullableBinaryListV1 {\n return (\n isRecord(value) && value.__moyodbPacked === PACKED_NULLABLE_BINARY_LIST_V1 && value.bytes instanceof Uint8Array\n );\n}\n\nfunction isPackedScanRows(value: unknown): value is PackedScanRowsV1 {\n return isRecord(value) && value.__moyodbPacked === PACKED_SCAN_ROWS_V1 && value.bytes instanceof Uint8Array;\n}\n\nfunction isPackedBatchOps(value: unknown): value is PackedBatchOpsV1 {\n return isRecord(value) && value.__moyodbPacked === PACKED_BATCH_OPS_V1 && value.bytes instanceof Uint8Array;\n}\n\nfunction isPackedOptionalValues(value: unknown): value is PackedOptionalValuesV1 {\n return isRecord(value) && value.__moyodbPacked === PACKED_OPTIONAL_VALUES_V1 && value.bytes instanceof Uint8Array;\n}\n\nfunction checkedByteCount(count: number, itemBytes: number, what: string): number {\n if (!Number.isSafeInteger(count) || count < 0) {\n throw workerProtocolError('WorkerProtocolError', `${what} count is invalid: ${count}`);\n }\n return checkedU32(count * itemBytes, what);\n}\n\nfunction checkedAdd(left: number, right: number, what: string): number {\n const total = left + right;\n return checkedU32(total, what);\n}\n\nfunction checkedU32(value: number, what: string): number {\n if (!Number.isSafeInteger(value) || value < 0 || value > U32_MAX) {\n throw workerProtocolError('WorkerProtocolError', `${what} exceeds 32-bit payload limit`);\n }\n return value;\n}\n\nfunction copyToOwnedUint8Array(value: Uint8Array): Uint8Array {\n const owned = new Uint8Array(value.byteLength);\n owned.set(value);\n return owned;\n}\n\nfunction stringOrUndefined(value: unknown): string | undefined {\n return typeof value === 'string' ? value : undefined;\n}\n","import type { AutocommitCommand, IndexScanPage, WorkerApi, WorkerOpenRequest } from './worker-api';\nimport type {\n BatchOp,\n ChangeFeed,\n ChangeFeedOptions,\n CompactionResult,\n CreateStoreOptions,\n DebugFailpoint,\n DbStats,\n ExportSnapshotOptions,\n IndexDef,\n PutOptions,\n Range,\n ScanItem,\n StorageInfo,\n TxMode\n} from './types';\nimport {\n MAX_WORKER_BATCH_BYTES,\n MAX_WORKER_BATCH_MESSAGES,\n WORKER_PROTOCOL_REQUEST,\n WORKER_PROTOCOL_REQUEST_BATCH,\n WORKER_PROTOCOL_RESPONSE,\n WORKER_PROTOCOL_RESPONSE_BATCH,\n WORKER_PROTOCOL_VERSION,\n captureWorkerPayload,\n deserializeWorkerError,\n decodeWorkerResponsePayload,\n isWorkerProtocolReadyMessage,\n isWorkerProtocolReadyEnvelope,\n isWorkerProtocolResponseBatchMessage,\n isWorkerProtocolResponseMessage,\n prepareWorkerCommandPayload,\n workerProtocolError,\n type AutocommitArgs,\n type WorkerCommand,\n type WorkerCommandArgs,\n type WorkerCommandResult,\n type WorkerProtocolRequestBatchMessage,\n type WorkerProtocolRequestMessage\n} from './worker-protocol';\nimport { isRecord } from './internal';\n\ninterface PendingRequest {\n /** Response command; autocommit replies use the inner command's format. */\n command: WorkerCommand;\n resolve: (value: unknown) => void;\n reject: (error: Error) => void;\n timeout: ReturnType<typeof setTimeout> | null;\n}\n\ninterface QueuedRequest {\n message: WorkerProtocolRequestMessage;\n transfer: Transferable[];\n byteLength: number;\n}\n\nfunction clearPendingTimeout(pending: PendingRequest): void {\n if (pending.timeout) {\n clearTimeout(pending.timeout);\n }\n}\n\nexport interface WorkerProtocolClientOptions {\n requestTimeoutMs?: number;\n readyTimeoutMs?: number;\n}\n\nexport interface WorkerTransport {\n postMessage(message: unknown, transfer?: Transferable[]): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject): void;\n}\n\nexport interface WorkerClient extends WorkerApi {\n autocommit<M extends AutocommitCommand>(\n mode: TxMode,\n command: M,\n args: AutocommitArgs<M>\n ): Promise<WorkerCommandResult<M>>;\n request<M extends WorkerCommand>(command: M, args: WorkerCommandArgs<M>): Promise<WorkerCommandResult<M>>;\n setFatalHandler(handler: ((error: Error) => void) | null): void;\n whenReady(): Promise<void>;\n dispose(reason?: Error): void;\n acquireMigration?(): Promise<void>;\n releaseMigration?(): Promise<void>;\n setTransactionsInvalidatedHandler?(handler: (() => void) | null): void;\n crash?(): void;\n}\n\nexport class WorkerProtocolClient implements WorkerApi {\n private nextRequestId = 1;\n private pending = new Map<number, PendingRequest>();\n private closed = false;\n private readyResolved = false;\n private readyResolve: (() => void) | null = null;\n private readyReject: ((error: Error) => void) | null = null;\n private ready: Promise<void>;\n private requestTimeoutMs: number;\n private fatalHandler: ((error: Error) => void) | null = null;\n private closeReason: Error | null = null;\n private batching = false;\n private queuedRequests: QueuedRequest[] = [];\n private queuedBytes = 0;\n private flushScheduled = false;\n private awaitingReady = 0;\n private readyTimeout: ReturnType<typeof setTimeout> | null = null;\n\n constructor(\n private readonly worker: WorkerTransport,\n options: WorkerProtocolClientOptions = {}\n ) {\n this.requestTimeoutMs = options.requestTimeoutMs ?? 0;\n this.ready = new Promise<void>((resolve, reject) => {\n this.readyResolve = resolve;\n this.readyReject = reject;\n });\n if ((options.readyTimeoutMs ?? 0) > 0) {\n this.readyTimeout = setTimeout(() => {\n this.fail(workerProtocolError('WorkerReadyTimeoutError', 'worker did not become ready'));\n }, options.readyTimeoutMs);\n }\n void this.ready.catch(() => undefined);\n this.worker.addEventListener('message', this.handleMessage as EventListener);\n this.worker.addEventListener('messageerror', this.handleMessageError);\n this.worker.addEventListener('error', this.handleError as EventListener);\n }\n\n setFatalHandler(handler: ((error: Error) => void) | null): void {\n this.fatalHandler = handler;\n }\n\n whenReady(): Promise<void> {\n return this.ready;\n }\n\n dispose(reason: Error = workerProtocolError('WorkerTerminatedError', 'worker transport was closed')): void {\n this.disposeInternal(reason, false);\n }\n\n protected fail(reason: Error): void {\n this.disposeInternal(reason, true);\n }\n\n open(request: WorkerOpenRequest): Promise<void> {\n return this.request('open', [request]);\n }\n\n close(): Promise<void> {\n return this.request('close', []);\n }\n\n destroy(): Promise<void> {\n return this.request('destroy', []);\n }\n\n deleteDB(dbName: string): Promise<void> {\n return this.request('deleteDB', [dbName]);\n }\n\n begin(mode: TxMode): Promise<number> {\n return this.request('begin', [mode]);\n }\n\n commit(txId: number): Promise<number> {\n return this.request('commit', [txId]);\n }\n\n rollback(txId: number): Promise<void> {\n return this.request('rollback', [txId]);\n }\n\n autocommit<M extends AutocommitCommand>(\n mode: TxMode,\n command: M,\n args: AutocommitArgs<M>\n ): Promise<WorkerCommandResult<M>> {\n return this.send('autocommit', [mode, command, args as unknown[]], command) as Promise<WorkerCommandResult<M>>;\n }\n\n createStore(txId: number, name: string, options?: CreateStoreOptions): Promise<void> {\n return this.request('createStore', [txId, name, options]);\n }\n\n dropStore(txId: number, name: string): Promise<void> {\n return this.request('dropStore', [txId, name]);\n }\n\n clearStore(txId: number, name: string): Promise<void> {\n return this.request('clearStore', [txId, name]);\n }\n\n get(txId: number, store: string, key: Uint8Array): Promise<Uint8Array | null> {\n return this.request('get', [txId, store, key]);\n }\n\n getMany(txId: number, store: string, keys: Array<Uint8Array>): Promise<Array<Uint8Array | null>> {\n return this.request('getMany', [txId, store, keys]);\n }\n\n has(txId: number, store: string, key: Uint8Array): Promise<boolean> {\n return this.request('has', [txId, store, key]);\n }\n\n put(txId: number, store: string, key: Uint8Array, value: Uint8Array, options?: PutOptions): Promise<void> {\n return this.request('put', [txId, store, key, value, options]);\n }\n\n putMany(\n txId: number,\n store: string,\n entries: Array<[Uint8Array, Uint8Array]>,\n options?: PutOptions\n ): Promise<void> {\n return this.request('putMany', [txId, store, entries, options]);\n }\n\n delete(txId: number, store: string, key: Uint8Array): Promise<boolean> {\n return this.request('delete', [txId, store, key]);\n }\n\n deleteMany(txId: number, store: string, keys: Array<Uint8Array>): Promise<void> {\n return this.request('deleteMany', [txId, store, keys]);\n }\n\n applyBatch(txId: number, store: string, ops: Array<BatchOp>): Promise<void> {\n return this.request('applyBatch', [txId, store, ops]);\n }\n\n scan(txId: number, store: string, range: Range): Promise<ScanItem[]> {\n return this.request('scan', [txId, store, range]);\n }\n\n getByIndex(txId: number, store: string, indexName: string, key: Uint8Array): Promise<Uint8Array | null> {\n return this.request('getByIndex', [txId, store, indexName, key]);\n }\n\n scanByIndex(txId: number, store: string, indexName: string, range: Range): Promise<ScanItem[]> {\n return this.request('scanByIndex', [txId, store, indexName, range]);\n }\n\n scanByIndexPage(\n txId: number,\n store: string,\n indexName: string,\n range: Range,\n cursor: Uint8Array | null,\n limit: number\n ): Promise<IndexScanPage> {\n return this.request('scanByIndexPage', [txId, store, indexName, range, cursor, limit]);\n }\n\n getIndexes(txId?: number): Promise<IndexDef[]> {\n return this.request('getIndexes', txId === undefined ? [] : [txId]);\n }\n\n reconcileIndexes(txId: number, indexes: IndexDef[]): Promise<void> {\n return this.request('reconcileIndexes', [txId, indexes]);\n }\n\n listStores(): Promise<string[]> {\n return this.request('listStores', []);\n }\n\n getVersion(): Promise<number> {\n return this.request('getVersion', []);\n }\n\n changesSince(txId: number, options: ChangeFeedOptions): Promise<ChangeFeed> {\n return this.request('changesSince', [txId, options]);\n }\n\n setSchemaVersion(txId: number, version: number): Promise<void> {\n return this.request('setSchemaVersion', [txId, version]);\n }\n\n exportSnapshot(options?: ExportSnapshotOptions): Promise<Uint8Array> {\n return this.request('exportSnapshot', [options]);\n }\n\n importSnapshot(data: Uint8Array): Promise<void> {\n return this.request('importSnapshot', [data]);\n }\n\n reset(): Promise<void> {\n return this.request('reset', []);\n }\n\n compact(): Promise<CompactionResult> {\n return this.request('compact', []);\n }\n\n rebuild(): Promise<CompactionResult> {\n return this.request('rebuild', []);\n }\n\n stats(): Promise<DbStats> {\n return this.request('stats', []);\n }\n\n storageInfo(): Promise<StorageInfo> {\n return this.request('storageInfo', []);\n }\n\n requestPersistence(): Promise<boolean> {\n return this.request('requestPersistence', []);\n }\n\n setFailpoint(failpoint: DebugFailpoint): Promise<void> {\n return this.request('setFailpoint', [failpoint]);\n }\n\n async request<M extends WorkerCommand>(command: M, args: WorkerCommandArgs<M>): Promise<WorkerCommandResult<M>> {\n return (await this.send(command, args, command)) as WorkerCommandResult<M>;\n }\n\n private async send<M extends WorkerCommand>(\n command: M,\n args: WorkerCommandArgs<M>,\n responseCommand: WorkerCommand\n ): Promise<unknown> {\n this.ensureOpen();\n this.awaitingReady += 1;\n try {\n await this.ready;\n } finally {\n this.awaitingReady -= 1;\n }\n this.ensureOpen();\n // Calls awaiting readiness together can share a batch. A lone call posts immediately.\n const shouldQueue = this.batching && (this.awaitingReady > 0 || this.queuedRequests.length > 0);\n const id = this.nextRequestId;\n this.nextRequestId += 1;\n const prepared = prepareWorkerCommandPayload(command, args);\n const message: WorkerProtocolRequestMessage = {\n type: WORKER_PROTOCOL_REQUEST,\n version: WORKER_PROTOCOL_VERSION,\n id,\n command,\n args: prepared.args\n } as WorkerProtocolRequestMessage;\n return await new Promise<unknown>((resolve, reject) => {\n const timeout =\n this.requestTimeoutMs > 0\n ? setTimeout(() => {\n this.pending.delete(id);\n reject(\n workerProtocolError(\n 'WorkerRequestTimeoutError',\n `worker command ${command} timed out after ${this.requestTimeoutMs}ms`\n )\n );\n }, this.requestTimeoutMs)\n : null;\n this.pending.set(id, {\n command: responseCommand,\n resolve: (value) => resolve(value),\n reject,\n timeout\n });\n try {\n if (shouldQueue) {\n this.queueRequest(message, prepared.transfer);\n } else if (prepared.transfer.length > 0) {\n this.worker.postMessage(message, prepared.transfer);\n } else {\n this.worker.postMessage(message);\n }\n } catch (error) {\n this.rejectPending(id, error instanceof Error ? error : new Error(String(error)));\n }\n });\n }\n\n private queueRequest(message: WorkerProtocolRequestMessage, transfer: Transferable[]): void {\n const captured = captureWorkerPayload(message, transfer);\n if (!this.pending.has(message.id)) return;\n if (this.queuedRequests.length > 0 && this.queuedBytes + captured.byteLength > MAX_WORKER_BATCH_BYTES) {\n this.flushRequests();\n }\n this.queuedRequests.push({\n message: captured.value,\n transfer: captured.transfer,\n byteLength: captured.byteLength\n });\n this.queuedBytes += captured.byteLength;\n if (!this.flushScheduled) {\n this.flushScheduled = true;\n queueMicrotask(() => {\n this.flushScheduled = false;\n this.flushRequests();\n });\n }\n if (this.queuedRequests.length >= MAX_WORKER_BATCH_MESSAGES || this.queuedBytes >= MAX_WORKER_BATCH_BYTES) {\n this.flushRequests();\n }\n }\n\n private flushRequests(): void {\n const queued = this.queuedRequests;\n this.queuedRequests = [];\n this.queuedBytes = 0;\n if (this.closed) return;\n const active = queued.filter((entry) => this.pending.has(entry.message.id));\n if (active.length === 0) return;\n const message: WorkerProtocolRequestMessage | WorkerProtocolRequestBatchMessage =\n active.length === 1\n ? active[0].message\n : {\n type: WORKER_PROTOCOL_REQUEST_BATCH,\n version: WORKER_PROTOCOL_VERSION,\n requests: active.map((entry) => entry.message)\n };\n const transfer: Transferable[] = [];\n for (const entry of active) {\n for (const buffer of entry.transfer) transfer.push(buffer);\n }\n try {\n if (transfer.length > 0) {\n this.worker.postMessage(message, transfer);\n } else {\n this.worker.postMessage(message);\n }\n } catch (error) {\n const reason = error instanceof Error ? error : new Error(String(error));\n for (const entry of active) this.rejectPending(entry.message.id, reason);\n }\n }\n\n private ensureOpen(): void {\n if (this.closed) {\n throw this.closeReason ?? workerProtocolError('WorkerTerminatedError', 'worker transport is closed');\n }\n }\n\n private handleMessage = (event: MessageEvent<unknown>): void => {\n const data = event.data;\n if (isWorkerProtocolReadyMessage(data)) {\n if (this.readyResolved) return;\n this.batching = data.batching === 1;\n this.readyResolved = true;\n if (this.readyTimeout) clearTimeout(this.readyTimeout);\n this.readyTimeout = null;\n this.readyResolve?.();\n this.readyResolve = null;\n this.readyReject = null;\n return;\n }\n if (isWorkerProtocolReadyEnvelope(data)) {\n this.fail(workerProtocolError('WorkerProtocolError', 'incompatible worker protocol ready message'));\n return;\n }\n if (isWorkerProtocolResponseBatchMessage(data)) {\n for (const response of data.responses) this.handleResponse(response);\n return;\n }\n if (\n isRecord(data) &&\n data.type === WORKER_PROTOCOL_RESPONSE_BATCH &&\n data.version === WORKER_PROTOCOL_VERSION\n ) {\n this.fail(workerProtocolError('WorkerProtocolError', 'invalid worker response batch'));\n return;\n }\n this.handleResponse(data);\n };\n\n private handleResponse(data: unknown): void {\n if (!isWorkerProtocolResponseMessage(data)) {\n if (\n isRecord(data) &&\n data.type === WORKER_PROTOCOL_RESPONSE &&\n data.version === WORKER_PROTOCOL_VERSION &&\n typeof data.id === 'number' &&\n Number.isSafeInteger(data.id)\n ) {\n this.rejectPending(data.id, workerProtocolError('WorkerProtocolError', 'invalid worker response'));\n }\n return;\n }\n const pending = this.pending.get(data.id);\n if (!pending) {\n return;\n }\n this.pending.delete(data.id);\n clearPendingTimeout(pending);\n try {\n if (data.ok) {\n pending.resolve(decodeWorkerResponsePayload(pending.command, data.result));\n } else {\n pending.reject(deserializeWorkerError(data.error));\n }\n } catch (error) {\n pending.reject(\n error instanceof Error && error.name === 'WorkerProtocolError'\n ? error\n : workerProtocolError('WorkerProtocolError', 'worker response could not be decoded')\n );\n }\n }\n\n private handleMessageError = (): void => {\n this.fail(workerProtocolError('WorkerMessageError', 'worker message could not be deserialized'));\n };\n\n private handleError = (event: ErrorEvent): void => {\n const error =\n event.error instanceof Error\n ? event.error\n : workerProtocolError('WorkerError', event.message || 'worker runtime failed');\n this.fail(error);\n };\n\n private rejectPending(id: number, error: Error): void {\n const pending = this.pending.get(id);\n if (!pending) {\n return;\n }\n this.pending.delete(id);\n clearPendingTimeout(pending);\n pending.reject(error);\n }\n\n private disposeInternal(reason: Error, notifyFatal: boolean): void {\n if (this.closed) {\n return;\n }\n this.closed = true;\n this.closeReason = reason;\n this.worker.removeEventListener('message', this.handleMessage as EventListener);\n this.worker.removeEventListener('messageerror', this.handleMessageError);\n this.worker.removeEventListener('error', this.handleError as EventListener);\n if (this.readyTimeout) clearTimeout(this.readyTimeout);\n this.readyTimeout = null;\n if (!this.readyResolved) {\n this.readyReject?.(reason);\n }\n this.readyResolve = null;\n this.readyReject = null;\n this.queuedRequests = [];\n this.queuedBytes = 0;\n for (const pending of this.pending.values()) {\n clearPendingTimeout(pending);\n pending.reject(reason);\n }\n this.pending.clear();\n if (notifyFatal) {\n this.fatalHandler?.(reason);\n }\n }\n}\n","export const SHARED_WORKER_CONTROL = 'moyodb:shared-worker:control';\nexport const SHARED_WORKER_CONTROL_RESULT = 'moyodb:shared-worker:control-result';\nexport const SHARED_WORKER_FATAL = 'moyodb:shared-worker:fatal';\nexport const SHARED_WORKER_INVALIDATE_TRANSACTIONS = 'moyodb:shared-worker:invalidate-transactions';\nexport const SHARED_WORKER_OWNER_REQUEST = 'moyodb:shared-worker:owner-request';\nexport const SHARED_WORKER_OWNER_RESPONSE = 'moyodb:shared-worker:owner-response';\nexport const SHARED_WORKER_OWNER_HOST_MESSAGE = 'moyodb:shared-worker:owner-host-message';\nexport const SHARED_WORKER_HEARTBEAT_MS = 5_000;\nexport const SHARED_WORKER_LEASE_MS = 120_000;\n\nexport type SharedWorkerControlOperation = 'ping' | 'detach' | 'acquireMigration' | 'releaseMigration' | 'crash';\n\nexport interface SharedWorkerControlRequest {\n type: typeof SHARED_WORKER_CONTROL;\n id: number;\n op: SharedWorkerControlOperation;\n}\n","import { isRecord, withTimeout } from './internal';\nimport { WorkerProtocolClient } from './worker-client';\nimport { deserializeWorkerError, serializeWorkerError, workerProtocolError } from './worker-protocol';\nimport {\n SHARED_WORKER_CONTROL,\n SHARED_WORKER_CONTROL_RESULT,\n SHARED_WORKER_FATAL,\n SHARED_WORKER_HEARTBEAT_MS,\n SHARED_WORKER_INVALIDATE_TRANSACTIONS,\n SHARED_WORKER_LEASE_MS,\n SHARED_WORKER_OWNER_REQUEST,\n SHARED_WORKER_OWNER_RESPONSE,\n SHARED_WORKER_OWNER_HOST_MESSAGE,\n type SharedWorkerControlOperation,\n type SharedWorkerControlRequest\n} from './shared-worker-protocol';\n\nfunction decodeControlError(error: unknown): Error {\n try {\n return deserializeWorkerError(error);\n } catch {\n return workerProtocolError('WorkerProtocolError', 'invalid shared worker error');\n }\n}\n\n// The page retains this worker while other clients still use its database.\nfunction hostStorageWorker(): { workerPort: MessagePort; hostPort: MessagePort } {\n const worker = new Worker(new URL('./browser-worker.ts', import.meta.url), { type: 'module' });\n const storage = new MessageChannel();\n const host = new MessageChannel();\n const persistence = new MessageChannel();\n const heartbeat = setInterval(() => {\n host.port1.postMessage({ type: SHARED_WORKER_OWNER_HOST_MESSAGE, op: 'ping' });\n }, SHARED_WORKER_HEARTBEAT_MS);\n let stopped = false;\n const stop = () => {\n if (stopped) return;\n stopped = true;\n clearInterval(heartbeat);\n worker.terminate();\n host.port1.close();\n persistence.port1.close();\n globalThis.removeEventListener?.('pagehide', handlePageHide);\n };\n const handlePageHide = () => {\n host.port1.postMessage({ type: SHARED_WORKER_OWNER_HOST_MESSAGE, op: 'gone' });\n stop();\n };\n worker.addEventListener('error', (event: ErrorEvent) => {\n host.port1.postMessage({\n type: SHARED_WORKER_OWNER_HOST_MESSAGE,\n op: 'error',\n error: serializeWorkerError(event.error ?? workerProtocolError('WorkerError', event.message))\n });\n stop();\n });\n host.port1.addEventListener('message', (event: MessageEvent<unknown>) => {\n if (isRecord(event.data) && event.data.type === SHARED_WORKER_OWNER_HOST_MESSAGE && event.data.op === 'stop')\n stop();\n });\n host.port1.start();\n persistence.port1.addEventListener('message', (event: MessageEvent<unknown>) => {\n const data = event.data;\n if (!isRecord(data) || data.type !== 'moyodb:persistence-bridge:request' || typeof data.id !== 'number') return;\n const operation = data.op === 'persist' ? navigator.storage.persist?.() : navigator.storage.persisted?.();\n void withTimeout(Promise.resolve(operation ?? false), 1000, false).then((granted) => {\n if (!stopped)\n persistence.port1.postMessage({ type: 'moyodb:persistence-bridge:response', id: data.id, granted });\n });\n });\n persistence.port1.start();\n globalThis.addEventListener?.('pagehide', handlePageHide);\n worker.postMessage({ type: 'moyodb:worker-port:init' }, [storage.port2]);\n worker.postMessage({ type: 'moyodb:persistence-bridge:init' }, [persistence.port2]);\n return { workerPort: storage.port1, hostPort: host.port2 };\n}\n\nexport class SharedWorkerProtocolClient extends WorkerProtocolClient {\n private controlId = 1;\n private controls = new Map<number, { resolve: () => void; reject: (reason: Error) => void }>();\n private invalidationHandler: (() => void) | null = null;\n private heartbeat: ReturnType<typeof setInterval> | null;\n private lastPong = Date.now();\n private disposed = false;\n\n constructor(private readonly sharedWorker: SharedWorker) {\n super(sharedWorker.port, { readyTimeoutMs: 10_000 });\n sharedWorker.port.addEventListener('message', this.handleControl);\n sharedWorker.addEventListener('error', this.handleSharedError);\n sharedWorker.port.start();\n globalThis.addEventListener?.('pagehide', this.handlePageHide);\n this.heartbeat = setInterval(() => {\n if (Date.now() - this.lastPong > SHARED_WORKER_LEASE_MS) {\n this.fail(workerProtocolError('WorkerTerminatedError', 'shared worker heartbeat expired'));\n return;\n }\n this.sendControl('ping', 0);\n }, SHARED_WORKER_HEARTBEAT_MS);\n }\n\n acquireMigration(): Promise<void> {\n return this.control('acquireMigration');\n }\n\n releaseMigration(): Promise<void> {\n return this.control('releaseMigration');\n }\n\n setTransactionsInvalidatedHandler(handler: (() => void) | null): void {\n this.invalidationHandler = handler;\n }\n\n crash(): void {\n this.sendControl('crash', 0);\n }\n\n override dispose(reason: Error = workerProtocolError('WorkerTerminatedError', 'shared worker port closed')): void {\n this.cleanup(reason);\n super.dispose(reason);\n }\n\n protected override fail(reason: Error): void {\n this.cleanup(reason);\n super.fail(reason);\n }\n\n private async control(op: SharedWorkerControlOperation): Promise<void> {\n await this.whenReady();\n if (this.disposed) throw workerProtocolError('WorkerTerminatedError', 'shared worker port closed');\n const id = this.controlId++;\n return new Promise<void>((resolve, reject) => {\n this.controls.set(id, { resolve, reject });\n try {\n this.sendControl(op, id);\n } catch (error) {\n this.controls.delete(id);\n reject(error instanceof Error ? error : new Error(String(error)));\n }\n });\n }\n\n private sendControl(op: SharedWorkerControlOperation, id: number): void {\n const request: SharedWorkerControlRequest = { type: SHARED_WORKER_CONTROL, op, id };\n this.sharedWorker.port.postMessage(request);\n }\n\n private handleControl = (event: MessageEvent<unknown>): void => {\n const data = event.data;\n if (!isRecord(data)) return;\n if (data.type === SHARED_WORKER_OWNER_REQUEST && typeof data.id === 'number') {\n try {\n const { workerPort, hostPort } = hostStorageWorker();\n this.sharedWorker.port.postMessage({ type: SHARED_WORKER_OWNER_RESPONSE, id: data.id, ok: true }, [\n workerPort,\n hostPort\n ]);\n } catch (error) {\n this.sharedWorker.port.postMessage({\n type: SHARED_WORKER_OWNER_RESPONSE,\n id: data.id,\n ok: false,\n error: serializeWorkerError(error)\n });\n }\n return;\n }\n if (data.type === SHARED_WORKER_FATAL) {\n this.fail(decodeControlError(data.error));\n return;\n }\n if (data.type === SHARED_WORKER_INVALIDATE_TRANSACTIONS) {\n this.invalidationHandler?.();\n return;\n }\n if (data.type !== SHARED_WORKER_CONTROL_RESULT) return;\n if (data.id === 0 && data.ok === true) {\n this.lastPong = Date.now();\n return;\n }\n if (typeof data.id !== 'number') return;\n const pending = this.controls.get(data.id);\n if (!pending) return;\n this.controls.delete(data.id);\n if (data.ok === true) pending.resolve();\n else pending.reject(decodeControlError(data.error));\n };\n\n private handleSharedError = (event: ErrorEvent): void => {\n this.fail(workerProtocolError('WorkerError', event.message || 'shared worker runtime failed'));\n };\n\n private handlePageHide = (): void => {\n this.fail(workerProtocolError('WorkerTerminatedError', 'shared worker page was unloaded'));\n };\n\n private cleanup(reason: Error): void {\n if (this.disposed) return;\n this.disposed = true;\n if (this.heartbeat !== null) clearInterval(this.heartbeat);\n this.heartbeat = null;\n try {\n this.sendControl('detach', 0);\n } catch {}\n this.sharedWorker.port.removeEventListener('message', this.handleControl);\n this.sharedWorker.removeEventListener('error', this.handleSharedError);\n globalThis.removeEventListener?.('pagehide', this.handlePageHide);\n for (const pending of this.controls.values()) pending.reject(reason);\n this.controls.clear();\n this.invalidationHandler = null;\n }\n}\n","export class MoyoDbError extends Error {\n constructor(name: string, message: string) {\n super(message);\n this.name = name;\n Object.setPrototypeOf(this, new.target.prototype);\n }\n}\nexport class UnsupportedPlatformError extends MoyoDbError {\n constructor(message: string) {\n super('UnsupportedPlatformError', message);\n }\n}\nexport class DatabaseBusyError extends MoyoDbError {\n constructor(message: string) {\n super('DatabaseBusyError', message);\n }\n}\nexport class CorruptionError extends MoyoDbError {\n constructor(message: string) {\n super('CorruptionError', message);\n }\n}\nexport class StoreExistsError extends MoyoDbError {\n constructor(message: string) {\n super('StoreExistsError', message);\n }\n}\nexport class StoreNotFoundError extends MoyoDbError {\n constructor(message: string) {\n super('StoreNotFoundError', message);\n }\n}\nexport class IndexNotFoundError extends MoyoDbError {\n constructor(message: string) {\n super('IndexNotFoundError', message);\n }\n}\nexport class ConstraintError extends MoyoDbError {\n constructor(message: string) {\n super('ConstraintError', message);\n }\n}\nexport class UniqueIndexConstraintError extends ConstraintError {\n constructor(message: string) {\n super(message);\n this.name = 'UniqueIndexConstraintError';\n }\n}\nexport class WriteTransactionAlreadyOpenError extends MoyoDbError {\n constructor(message = 'write transaction already open') {\n super('WriteTransactionAlreadyOpenError', message);\n }\n}\nexport class TransactionConflictError extends MoyoDbError {\n constructor(message = 'transaction snapshot is stale; start a new transaction') {\n super('TransactionConflictError', message);\n }\n}\nexport class ReadonlyTransactionError extends MoyoDbError {\n constructor(message = 'readonly transaction cannot perform this operation') {\n super('ReadonlyTransactionError', message);\n }\n}\nexport class TransactionClosedError extends MoyoDbError {\n constructor(message = 'transaction is already closed') {\n super('TransactionClosedError', message);\n }\n}\nexport class DatabaseClosedError extends MoyoDbError {\n constructor(message = 'database handle is closed') {\n super('DatabaseClosedError', message);\n }\n}\nexport class ValueTooLargeError extends MoyoDbError {\n constructor(message: string) {\n super('ValueTooLargeError', message);\n }\n}\nexport class KeyTooLargeError extends MoyoDbError {\n constructor(message: string) {\n super('KeyTooLargeError', message);\n }\n}\nexport class StoreNameTooLongError extends MoyoDbError {\n constructor(message: string) {\n super('StoreNameTooLongError', message);\n }\n}\nexport class ReservedStoreNameError extends MoyoDbError {\n constructor(message: string) {\n super('ReservedStoreNameError', message);\n }\n}\nexport class InvalidRangeError extends MoyoDbError {\n constructor(message: string) {\n super('InvalidRangeError', message);\n }\n}\nexport class StorageError extends MoyoDbError {\n constructor(message: string) {\n super('StorageError', message);\n }\n}\nexport class SerializationError extends MoyoDbError {\n constructor(message: string) {\n super('SerializationError', message);\n }\n}\nexport class InjectedFailureError extends MoyoDbError {\n constructor(message: string) {\n super('InjectedFailureError', message);\n }\n}\nexport class ChangeFeedCompactedError extends MoyoDbError {\n constructor(message: string) {\n super('ChangeFeedCompactedError', message);\n }\n}\n/**\n * The engine state could not be trusted, or automatic recovery failed.\n * A failed commit may already be durable. The worker attempts recovery before\n * a new transaction and after a failed commit. Recovery discards all open transactions.\n */\nexport class RecoveryRequiredError extends MoyoDbError {\n constructor(message: string) {\n super('RecoveryRequiredError', message);\n }\n}\nexport class InternalError extends MoyoDbError {\n constructor(message: string) {\n super('InternalError', message);\n }\n}\nexport class InvalidOpenOptionsError extends MoyoDbError {\n constructor(message: string) {\n super('InvalidOpenOptionsError', message);\n }\n}\nexport class VersionError extends MoyoDbError {\n constructor(message: string) {\n super('VersionError', message);\n }\n}\ntype ErrorPayload = {\n code?: string;\n name?: string;\n message?: string;\n};\ntype ErrorConstructor = new (message: string) => Error;\nconst ERROR_CONSTRUCTORS = {\n UnsupportedPlatformError,\n DatabaseBusyError,\n CorruptionError,\n StoreExistsError,\n StoreNotFoundError,\n IndexNotFoundError,\n ConstraintError,\n UniqueIndexConstraintError,\n WriteTransactionAlreadyOpenError,\n TransactionConflictError,\n ReadonlyTransactionError,\n TransactionClosedError,\n DatabaseClosedError,\n ValueTooLargeError,\n KeyTooLargeError,\n StoreNameTooLongError,\n ReservedStoreNameError,\n InvalidRangeError,\n StorageError,\n SerializationError,\n InjectedFailureError,\n ChangeFeedCompactedError,\n RecoveryRequiredError,\n InternalError,\n InvalidOpenOptionsError,\n VersionError\n} satisfies Record<string, ErrorConstructor>;\n\nfunction instantiateError(code: string, message: string): Error {\n if (Object.prototype.hasOwnProperty.call(ERROR_CONSTRUCTORS, code)) {\n const ErrorConstructor = ERROR_CONSTRUCTORS[code as keyof typeof ERROR_CONSTRUCTORS];\n return new ErrorConstructor(message);\n }\n const err = new Error(message);\n err.name = code;\n return err;\n}\n\nexport function normalizeError(error: unknown): Error {\n if (error instanceof MoyoDbError) {\n return error;\n }\n if (error instanceof Error) {\n if (error.name === 'Error') {\n return error;\n }\n return instantiateError(error.name, error.message);\n }\n const payload = error as ErrorPayload | undefined;\n const code = payload?.code ?? payload?.name ?? 'Error';\n const message = payload?.message ?? String(error);\n return instantiateError(code, message);\n}\n","import { WorkerProtocolClient, type WorkerClient, type WorkerTransport } from './worker-client';\nimport { SharedWorkerProtocolClient } from './shared-worker-client';\nimport type { ChangeFeedSettings, DebugFailpoint, OpenOptions } from './types';\nimport {\n DatabaseBusyError,\n DatabaseClosedError,\n InvalidOpenOptionsError,\n UnsupportedPlatformError,\n normalizeError\n} from './errors';\nimport { isRecord, withTimeout } from './internal';\nconst VALID_FAILPOINTS = new Set<Exclude<DebugFailpoint, null>>([\n 'after_wal_flush',\n 'after_main_flush',\n 'before_superblock_flush'\n]);\nconst PERSISTENCE_BRIDGE_INIT = 'moyodb:persistence-bridge:init';\nconst PERSISTENCE_BRIDGE_REQUEST = 'moyodb:persistence-bridge:request';\nconst PERSISTENCE_BRIDGE_RESPONSE = 'moyodb:persistence-bridge:response';\ntype PersistenceBridgeOperation = 'persist' | 'persisted';\ninterface PersistenceBridgeRequest {\n type: typeof PERSISTENCE_BRIDGE_REQUEST;\n id: number;\n op: PersistenceBridgeOperation;\n}\ninterface PersistenceBridgeResponse {\n type: typeof PERSISTENCE_BRIDGE_RESPONSE;\n id: number;\n granted: boolean;\n}\nfunction isPersistenceBridgeRequest(value: unknown): value is PersistenceBridgeRequest {\n return (\n isRecord(value) &&\n value.type === PERSISTENCE_BRIDGE_REQUEST &&\n typeof value.id === 'number' &&\n (value.op === 'persist' || value.op === 'persisted')\n );\n}\ninterface MainThreadPersistenceBridge {\n close(): void;\n}\nexport interface NormalizedOpenOptions {\n workerMode: 'dedicated' | 'shared';\n createIfMissing: boolean;\n ownerWaitMs: number;\n requestPersistence: boolean;\n cachePages: number;\n debugFailpoint: DebugFailpoint;\n changeFeed: Required<ChangeFeedSettings> | null;\n}\nconst DEFAULT_CHANGE_FEED_RETAIN_TXIDS = 100_000;\nexport interface RegistryEntry {\n dbName: string;\n refs: number;\n worker: { terminate(): void | Promise<number> };\n proxy: WorkerClient;\n persistenceBridge: MainThreadPersistenceBridge;\n options: NormalizedOpenOptions;\n invalidated: boolean;\n schemaMigrationInProgress: boolean;\n txInvalidationListeners: Set<() => void>;\n handleInvalidationListeners: Set<() => void>;\n release?: () => Promise<void>;\n destroy?: () => Promise<void>;\n channelName?: string;\n}\nconst registry = new Map<string, RegistryEntry>();\nconst lifecycleOperations = new Map<string, Promise<void>>();\nfunction queueLifecycleOperation<T>(dbName: string, operation: () => Promise<T>): Promise<T> {\n const previous = lifecycleOperations.get(dbName) ?? Promise.resolve();\n const result = previous.then(operation);\n const settled = result.then(\n () => undefined,\n () => undefined\n );\n lifecycleOperations.set(dbName, settled);\n void settled.then(() => {\n if (lifecycleOperations.get(dbName) === settled) {\n lifecycleOperations.delete(dbName);\n }\n });\n return result;\n}\nfunction requirePlainOptionsObject(options: unknown): asserts options is OpenOptions {\n if (options === null || typeof options !== 'object' || Array.isArray(options)) {\n throw new InvalidOpenOptionsError('open options must be an object');\n }\n}\nfunction normalizeBoolean(value: unknown, field: string, defaultValue: boolean): boolean {\n if (value === undefined) {\n return defaultValue;\n }\n if (typeof value !== 'boolean') {\n throw new InvalidOpenOptionsError(`${field} must be a boolean`);\n }\n return value;\n}\nfunction normalizeNonNegativeInteger(value: unknown, field: string, defaultValue: number): number {\n if (value === undefined) {\n return defaultValue;\n }\n if (typeof value !== 'number' || !Number.isSafeInteger(value) || value < 0) {\n throw new InvalidOpenOptionsError(`${field} must be a non-negative safe integer`);\n }\n return value;\n}\nfunction normalizeCachePages(value: unknown): number {\n return Math.max(1, normalizeNonNegativeInteger(value, 'cachePages', 256));\n}\nfunction normalizeFailpoint(value: unknown): DebugFailpoint {\n if (value === undefined || value === null) {\n return null;\n }\n if (typeof value !== 'string' || !VALID_FAILPOINTS.has(value as Exclude<DebugFailpoint, null>)) {\n throw new InvalidOpenOptionsError(`debugFailpoint must be one of: ${Array.from(VALID_FAILPOINTS).join(', ')}`);\n }\n return value as Exclude<DebugFailpoint, null>;\n}\nfunction normalizeChangeFeed(value: unknown): Required<ChangeFeedSettings> | null {\n if (value === undefined) {\n return null;\n }\n if (value === null || typeof value !== 'object' || Array.isArray(value)) {\n throw new InvalidOpenOptionsError('changeFeed must be an object');\n }\n const settings = value as ChangeFeedSettings;\n const enabled = normalizeBoolean(settings.enabled, 'changeFeed.enabled', true);\n let retainTxids: number | null = DEFAULT_CHANGE_FEED_RETAIN_TXIDS;\n if (settings.retainTxids === null) {\n retainTxids = null;\n } else if (settings.retainTxids !== undefined) {\n retainTxids = normalizeNonNegativeInteger(settings.retainTxids, 'changeFeed.retainTxids', 0);\n if (retainTxids === 0) {\n throw new InvalidOpenOptionsError('changeFeed.retainTxids must be positive; disable the feed instead');\n }\n }\n return { enabled, retainTxids };\n}\nfunction normalizeWorkerMode(value: unknown): NormalizedOpenOptions['workerMode'] {\n if (value === undefined) return 'dedicated';\n if (value !== 'dedicated' && value !== 'shared') {\n throw new InvalidOpenOptionsError('workerMode must be dedicated or shared');\n }\n return value;\n}\nexport function normalizeOptions(options: OpenOptions = {}): NormalizedOpenOptions {\n requirePlainOptionsObject(options);\n return {\n workerMode: normalizeWorkerMode(options.workerMode),\n createIfMissing: normalizeBoolean(options.createIfMissing, 'createIfMissing', true),\n ownerWaitMs: normalizeNonNegativeInteger(options.ownerWaitMs, 'ownerWaitMs', 0),\n requestPersistence: normalizeBoolean(options.requestPersistence, 'requestPersistence', true),\n cachePages: normalizeCachePages(options.cachePages),\n debugFailpoint: normalizeFailpoint(options.debugFailpoint),\n changeFeed: normalizeChangeFeed(options.changeFeed)\n };\n}\nfunction sameChangeFeed(left: NormalizedOpenOptions['changeFeed'], right: NormalizedOpenOptions['changeFeed']) {\n return left?.enabled === right?.enabled && left?.retainTxids === right?.retainTxids;\n}\nexport function assertCompatibleOptions(dbName: string, current: NormalizedOpenOptions, next: NormalizedOpenOptions) {\n if (current.workerMode !== next.workerMode) {\n throw new InvalidOpenOptionsError(`database ${dbName} is already open with workerMode=${current.workerMode}`);\n }\n if (current.cachePages !== next.cachePages) {\n throw new InvalidOpenOptionsError(\n `database ${dbName} is already open in this tab with cachePages=${current.cachePages}; requested cachePages=${next.cachePages}`\n );\n }\n if (next.changeFeed !== null && !sameChangeFeed(current.changeFeed, next.changeFeed)) {\n throw new InvalidOpenOptionsError(\n `database ${dbName} is already open in this tab with a different changeFeed policy`\n );\n }\n}\nasync function queryPersistentStorageState(): Promise<boolean> {\n const storage = globalThis.navigator.storage;\n if (typeof storage.persisted !== 'function') {\n return false;\n }\n return await withTimeout(storage.persisted(), 1000, false);\n}\nasync function requestPersistentStorageGrant(): Promise<boolean> {\n const storage = globalThis.navigator.storage;\n if (typeof storage.persist !== 'function') {\n return false;\n }\n return await withTimeout(storage.persist(), 1000, false);\n}\nasync function handlePersistenceBridgeRequest(port: MessagePort, request: PersistenceBridgeRequest): Promise<void> {\n const granted =\n request.op === 'persist' ? await requestPersistentStorageGrant() : await queryPersistentStorageState();\n const response: PersistenceBridgeResponse = {\n type: PERSISTENCE_BRIDGE_RESPONSE,\n id: request.id,\n granted\n };\n port.postMessage(response);\n}\nfunction createMainThreadPersistenceBridge(worker: WorkerTransport): MainThreadPersistenceBridge {\n const channel = new MessageChannel();\n const port = channel.port1;\n port.addEventListener('message', (event: MessageEvent<unknown>) => {\n const data = event.data;\n if (!isPersistenceBridgeRequest(data)) {\n return;\n }\n void handlePersistenceBridgeRequest(port, data);\n });\n port.start();\n worker.postMessage({ type: PERSISTENCE_BRIDGE_INIT }, [channel.port2]);\n return {\n close() {\n port.close();\n }\n };\n}\nfunction createWorker(\n dbName: string,\n mode: NormalizedOpenOptions['workerMode'] = 'dedicated'\n): {\n worker: RegistryEntry['worker'];\n proxy: WorkerClient;\n persistenceBridge: MainThreadPersistenceBridge;\n} {\n if (mode === 'shared') {\n if (typeof globalThis.SharedWorker !== 'function') {\n throw new UnsupportedPlatformError('SharedWorker is unavailable; workerMode=shared cannot be opened');\n }\n const sharedWorker = new SharedWorker(new URL('./shared-worker.ts', import.meta.url), {\n type: 'module',\n name: `moyodb:${dbName}`\n });\n const proxy = new SharedWorkerProtocolClient(sharedWorker);\n const persistenceBridge = { close() {} };\n return { worker: { terminate: () => sharedWorker.port.close() }, proxy, persistenceBridge };\n }\n const worker = new Worker(new URL('./browser-worker.ts', import.meta.url), { type: 'module' });\n const proxy = new WorkerProtocolClient(worker);\n const persistenceBridge = createMainThreadPersistenceBridge(worker);\n return { worker, proxy, persistenceBridge };\n}\nfunction createEntry(\n dbName: string,\n worker: RegistryEntry['worker'],\n proxy: WorkerClient,\n persistenceBridge: MainThreadPersistenceBridge,\n options: NormalizedOpenOptions\n): RegistryEntry {\n const entry: RegistryEntry = {\n dbName,\n refs: 1,\n worker,\n proxy,\n persistenceBridge,\n options,\n invalidated: false,\n schemaMigrationInProgress: false,\n txInvalidationListeners: new Set(),\n handleInvalidationListeners: new Set()\n };\n proxy.setTransactionsInvalidatedHandler?.(() => invalidateTransactions(entry));\n proxy.setFatalHandler(() => {\n const current = registry.get(dbName);\n if (current !== entry || entry.invalidated) {\n return;\n }\n registry.delete(dbName);\n entry.refs = 0;\n invalidateEntry(entry);\n entry.persistenceBridge.close();\n void entry.worker.terminate();\n });\n return entry;\n}\nfunction emitListeners(listeners: Iterable<() => void>) {\n for (const listener of Array.from(listeners)) {\n listener();\n }\n}\nexport function subscribeTransactionsInvalidated(entry: RegistryEntry, listener: () => void): () => void {\n entry.txInvalidationListeners.add(listener);\n return () => {\n entry.txInvalidationListeners.delete(listener);\n };\n}\nexport function subscribeHandleInvalidated(entry: RegistryEntry, listener: () => void): () => void {\n entry.handleInvalidationListeners.add(listener);\n return () => {\n entry.handleInvalidationListeners.delete(listener);\n };\n}\nexport function invalidateTransactions(entry: RegistryEntry): void {\n emitListeners(entry.txInvalidationListeners);\n}\nfunction invalidateEntry(entry: RegistryEntry): void {\n if (entry.invalidated) {\n return;\n }\n entry.invalidated = true;\n invalidateTransactions(entry);\n emitListeners(entry.handleInvalidationListeners);\n}\nexport function unsafeDebugCrashWorker(dbName: string): boolean {\n const current = registry.get(dbName);\n if (!current) {\n return false;\n }\n registry.delete(dbName);\n invalidateEntry(current);\n current.refs = 0;\n current.persistenceBridge.close();\n current.proxy.crash?.();\n current.proxy.dispose(new Error('worker was terminated by unsafeDebugCrashWorker'));\n void current.worker.terminate();\n return true;\n}\nexport async function acquireDbWorker(dbName: string, options: OpenOptions = {}): Promise<RegistryEntry> {\n const normalized = normalizeOptions(options);\n return queueLifecycleOperation(dbName, async () => {\n const existing = registry.get(dbName);\n if (existing) {\n if (existing.invalidated) {\n registry.delete(dbName);\n } else {\n if (existing.schemaMigrationInProgress) {\n throw new DatabaseBusyError(`database ${dbName} is migrating; wait for openDB() to resolve`);\n }\n assertCompatibleOptions(dbName, existing.options, normalized);\n if (normalized.debugFailpoint !== null) {\n try {\n await existing.proxy.setFailpoint(normalized.debugFailpoint);\n } catch (error) {\n throw normalizeError(error);\n }\n }\n existing.refs += 1;\n return existing;\n }\n }\n const { worker, proxy, persistenceBridge } = createWorker(dbName, normalized.workerMode);\n const entry = createEntry(dbName, worker, proxy, persistenceBridge, normalized);\n try {\n await proxy.open({\n dbName,\n options: normalized\n });\n registry.set(dbName, entry);\n return entry;\n } catch (error) {\n persistenceBridge.close();\n proxy.dispose(new Error('worker open failed'));\n await worker.terminate();\n throw normalizeError(error);\n }\n });\n}\nexport async function releaseDbWorker(entry: RegistryEntry): Promise<void> {\n if (entry.release) return entry.release();\n return queueLifecycleOperation(entry.dbName, async () => {\n if (entry.invalidated || registry.get(entry.dbName) !== entry) {\n return;\n }\n entry.refs -= 1;\n if (entry.refs > 0) {\n return;\n }\n registry.delete(entry.dbName);\n try {\n await entry.proxy.close();\n } finally {\n entry.persistenceBridge.close();\n entry.proxy.dispose(new Error('worker was released'));\n await entry.worker.terminate();\n }\n });\n}\nexport async function destroyDbWorker(entry: RegistryEntry): Promise<void> {\n if (entry.destroy) return entry.destroy();\n return queueLifecycleOperation(entry.dbName, () => destroyEntry(entry));\n}\nasync function destroyEntry(entry: RegistryEntry): Promise<void> {\n if (entry.invalidated || registry.get(entry.dbName) !== entry) {\n throw new DatabaseClosedError();\n }\n if (entry.options.workerMode === 'shared') {\n try {\n await entry.proxy.destroy();\n } catch (error) {\n throw normalizeError(error);\n }\n registry.delete(entry.dbName);\n invalidateEntry(entry);\n entry.refs = 0;\n entry.persistenceBridge.close();\n entry.proxy.dispose(new Error('worker was released'));\n await entry.worker.terminate();\n return;\n }\n registry.delete(entry.dbName);\n invalidateEntry(entry);\n entry.refs = 0;\n try {\n await entry.proxy.destroy();\n } catch (error) {\n throw normalizeError(error);\n } finally {\n entry.persistenceBridge.close();\n entry.proxy.dispose(new Error('worker was released'));\n await entry.worker.terminate();\n }\n}\nexport async function deleteDbByName(dbName: string): Promise<void> {\n return queueLifecycleOperation(dbName, async () => {\n const current = registry.get(dbName);\n if (current) {\n await destroyEntry(current);\n return;\n }\n const { worker, proxy, persistenceBridge } = createWorker(dbName);\n try {\n await proxy.deleteDB(dbName);\n } catch (error) {\n throw normalizeError(error);\n } finally {\n persistenceBridge.close();\n proxy.dispose(new Error('temporary worker was terminated'));\n await worker.terminate();\n }\n });\n}\n","import type { Range } from './types';\nconst encoder = new TextEncoder();\nconst decoder = new TextDecoder();\nconst jsonDecoder = new TextDecoder('utf-8', { fatal: true });\nconst TYPE_NULL = 0x10;\nconst TYPE_FALSE = 0x20;\nconst TYPE_TRUE = 0x21;\nconst TYPE_NUMBER = 0x30;\nconst TYPE_STRING = 0x40;\nconst TYPE_BYTES = 0x50;\nconst COMPOUND_ESCAPE = 0x00;\nconst COMPOUND_ESCAPE_CONT = 0xff;\nconst COMPOUND_TERM = 0x00;\nconst F64_MASK = BigInt('0xffffffffffffffff');\nexport type CompoundKeyPart = string | number | boolean | null | Uint8Array;\nexport type IndexKeyPrimitive = CompoundKeyPart;\nexport function utf8Encode(value: string): Uint8Array {\n return encoder.encode(value);\n}\nexport function utf8Decode(bytes: Uint8Array): string {\n return decoder.decode(bytes);\n}\nexport function jsonEncode(value: unknown): Uint8Array {\n const serialized = JSON.stringify(value) as string | undefined;\n if (serialized === undefined) {\n throw new TypeError('value has no JSON representation');\n }\n return utf8Encode(serialized);\n}\nexport function jsonDecode<T>(bytes: Uint8Array): T {\n return JSON.parse(jsonDecoder.decode(bytes)) as T;\n}\nexport function u64Key(value: bigint | number): Uint8Array {\n if (typeof value === 'number' && (!Number.isSafeInteger(value) || value < 0)) {\n throw new RangeError('u64Key number inputs must be safe non-negative integers; use bigint for larger values');\n }\n const asBigInt = typeof value === 'bigint' ? value : BigInt(value);\n if (asBigInt < 0n) {\n throw new RangeError('u64Key only accepts non-negative values');\n }\n if (asBigInt > F64_MASK) {\n throw new RangeError('u64Key value exceeds the unsigned 64-bit range');\n }\n const buf = new ArrayBuffer(8);\n const view = new DataView(buf);\n view.setBigUint64(0, asBigInt, false);\n return new Uint8Array(buf);\n}\nfunction isCompoundKeyPartList(\n value: CompoundKeyPart | ReadonlyArray<CompoundKeyPart>\n): value is ReadonlyArray<CompoundKeyPart> {\n return Array.isArray(value);\n}\nexport function indexKey(value: CompoundKeyPart | ReadonlyArray<CompoundKeyPart>): Uint8Array {\n if (isCompoundKeyPartList(value)) {\n return compoundKey(...value);\n }\n return encodeCompoundKeyPart(value);\n}\nexport function compoundKey(...parts: CompoundKeyPart[]): Uint8Array {\n return encodeCompoundBytes(parts.map((part) => encodeCompoundKeyPart(part)));\n}\nexport function encodeIndexScalar(value: IndexKeyPrimitive): Uint8Array {\n return encodeCompoundKeyPart(value);\n}\nexport function encodeCompoundKeyParts(parts: ReadonlyArray<Uint8Array>): Uint8Array {\n return encodeCompoundBytes(parts);\n}\nexport function splitCompoundKey(key: Uint8Array): Uint8Array[] {\n const parts: Uint8Array[] = [];\n const current: number[] = [];\n for (let index = 0; index < key.length; index += 1) {\n const byte = key[index];\n if (byte !== COMPOUND_ESCAPE) {\n current.push(byte);\n continue;\n }\n const next = key[index + 1];\n if (next === COMPOUND_ESCAPE_CONT) {\n current.push(COMPOUND_ESCAPE);\n index += 1;\n continue;\n }\n if (next === COMPOUND_TERM) {\n parts.push(Uint8Array.from(current));\n current.length = 0;\n index += 1;\n continue;\n }\n throw new TypeError('invalid compound key encoding');\n }\n if (current.length !== 0) {\n throw new TypeError('compound key terminated unexpectedly');\n }\n return parts;\n}\nexport function prefixSuccessor(prefix: Uint8Array): Uint8Array | null {\n const out = prefix.slice();\n for (let index = out.length - 1; index >= 0; index -= 1) {\n if (out[index] !== 0xff) {\n out[index] += 1;\n return out.subarray(0, index + 1);\n }\n }\n return null;\n}\nexport function prefixRange(prefix: Uint8Array): Range {\n const upper = prefixSuccessor(prefix);\n return upper ? { gte: prefix, lt: upper } : { gte: prefix };\n}\nexport function compoundKeyRange(...parts: CompoundKeyPart[]): Range {\n return prefixRange(compoundKey(...parts));\n}\nfunction encodeCompoundKeyPart(value: CompoundKeyPart): Uint8Array {\n if (value === null) {\n return Uint8Array.of(TYPE_NULL);\n }\n if (typeof value === 'boolean') {\n return Uint8Array.of(value ? TYPE_TRUE : TYPE_FALSE);\n }\n if (typeof value === 'number') {\n return encodeSortableNumber(value);\n }\n if (typeof value === 'string') {\n // Reject lone surrogates so TextEncoder cannot map distinct keys to U+FFFD.\n for (const character of value) {\n const codePoint = character.codePointAt(0) as number;\n if (codePoint >= 0xd800 && codePoint <= 0xdfff) {\n throw new TypeError('compound key string parts must contain valid Unicode scalar values');\n }\n }\n const body = utf8Encode(value);\n const out = new Uint8Array(1 + body.length);\n out[0] = TYPE_STRING;\n out.set(body, 1);\n return out;\n }\n if (value instanceof Uint8Array) {\n const out = new Uint8Array(1 + value.length);\n out[0] = TYPE_BYTES;\n out.set(value, 1);\n return out;\n }\n throw new TypeError('compound key parts must be string, number, boolean, null, or Uint8Array');\n}\nfunction encodeCompoundBytes(parts: ReadonlyArray<Uint8Array>): Uint8Array {\n let length = 0;\n for (const part of parts) {\n for (const byte of part) {\n length += byte === COMPOUND_ESCAPE ? 2 : 1;\n }\n length += 2;\n }\n const out = new Uint8Array(length);\n let offset = 0;\n for (const part of parts) {\n for (const byte of part) {\n if (byte === COMPOUND_ESCAPE) {\n out[offset] = COMPOUND_ESCAPE;\n out[offset + 1] = COMPOUND_ESCAPE_CONT;\n offset += 2;\n } else {\n out[offset] = byte;\n offset += 1;\n }\n }\n out[offset] = COMPOUND_TERM;\n out[offset + 1] = COMPOUND_TERM;\n offset += 2;\n }\n return out;\n}\nfunction encodeSortableNumber(value: number): Uint8Array {\n if (!Number.isFinite(value)) {\n throw new TypeError('compound key number parts must be finite');\n }\n const normalized = Object.is(value, -0) ? 0 : value;\n const buffer = new ArrayBuffer(9);\n const view = new DataView(buffer);\n view.setUint8(0, TYPE_NUMBER);\n view.setFloat64(1, normalized, false);\n let bits = view.getBigUint64(1, false);\n bits = (bits & (1n << 63n)) !== 0n ? ~bits & F64_MASK : bits ^ (1n << 63n);\n view.setBigUint64(1, bits, false);\n return new Uint8Array(buffer);\n}\n","import { InvalidOpenOptionsError, ReservedStoreNameError, SerializationError } from './errors';\nimport { compareStringsByCodeUnit } from './internal';\nimport {\n encodeCompoundKeyParts,\n encodeIndexScalar,\n prefixRange,\n prefixSuccessor,\n splitCompoundKey,\n utf8Encode\n} from './codec';\nimport type { IndexDef, Range } from './types';\nconst encoder = new TextEncoder();\nconst fatalDecoder = new TextDecoder('utf-8', { fatal: true });\nconst MISSING = Symbol('moyodb.indexing.missing');\nconst FNV64_OFFSET = BigInt('0xcbf29ce484222325');\nconst FNV64_PRIME = BigInt('0x100000001b3');\nconst FNV64_MASK = BigInt('0xffffffffffffffff');\n// Persisted store names use this legacy namespace. Renaming requires a migration.\nconst INTERNAL_STORE_PREFIX = '__browserdb:';\nconst INTERNAL_INDEX_STORE_PREFIX = '__browserdb:index:';\nexport const INDEX_METADATA_STORE = '__browserdb:indexes';\nexport interface NormalizedIndexDef {\n store: string;\n name: string;\n keyPath: string[];\n compound: boolean;\n unique: boolean;\n internalStore: string;\n}\nexport interface DecodedIndexEntryKey {\n logicalKey: Uint8Array;\n primaryKey: Uint8Array;\n}\nexport function isInternalStoreName(name: string): boolean {\n return name.startsWith(INTERNAL_STORE_PREFIX);\n}\nexport function assertPublicStoreName(name: string): void {\n if (isInternalStoreName(name)) {\n throw new ReservedStoreNameError(`reserved store name: ${name}`);\n }\n}\nexport function normalizeIndexDefinitions(value: unknown): NormalizedIndexDef[] {\n if (value === undefined) {\n return [];\n }\n if (!Array.isArray(value)) {\n throw new InvalidOpenOptionsError('indexes must be an array');\n }\n const normalized: NormalizedIndexDef[] = [];\n const identities = new Set<string>();\n const internalStores = new Map<string, string>();\n for (const entry of value) {\n if (entry === null || typeof entry !== 'object' || Array.isArray(entry)) {\n throw new InvalidOpenOptionsError('each index definition must be an object');\n }\n const { store, name, keyPath, unique } = entry as {\n store?: unknown;\n name?: unknown;\n keyPath?: unknown;\n unique?: unknown;\n };\n if (typeof store !== 'string' || store.length === 0) {\n throw new InvalidOpenOptionsError('index store must be a non-empty string');\n }\n if (typeof name !== 'string' || name.length === 0) {\n throw new InvalidOpenOptionsError('index name must be a non-empty string');\n }\n assertPublicStoreName(store);\n const keyPathInfo = normalizeIndexKeyPath(keyPath);\n if (unique !== undefined && typeof unique !== 'boolean') {\n throw new InvalidOpenOptionsError('index unique must be a boolean');\n }\n const def: NormalizedIndexDef = {\n store,\n name,\n keyPath: keyPathInfo.paths,\n compound: keyPathInfo.compound,\n unique: unique ?? false,\n internalStore: makeInternalIndexStoreName(store, name)\n };\n const identity = indexDefinitionIdentity(def.store, def.name);\n if (identities.has(identity)) {\n throw new InvalidOpenOptionsError(`duplicate index definition ${def.store}.${def.name}`);\n }\n identities.add(identity);\n const mappedIdentity = internalStores.get(def.internalStore);\n if (mappedIdentity && mappedIdentity !== identity) {\n throw new InvalidOpenOptionsError(\n `index definitions ${mappedIdentity} and ${identity} map to the same internal store ${def.internalStore}`\n );\n }\n internalStores.set(def.internalStore, identity);\n normalized.push(def);\n }\n normalized.sort(compareNormalizedIndexDefinitions);\n return normalized;\n}\nexport function compareNormalizedIndexDefinitions(left: NormalizedIndexDef, right: NormalizedIndexDef): number {\n const storeCompare = compareStringsByCodeUnit(left.store, right.store);\n if (storeCompare !== 0) {\n return storeCompare;\n }\n const nameCompare = compareStringsByCodeUnit(left.name, right.name);\n if (nameCompare !== 0) {\n return nameCompare;\n }\n const uniqueCompare = Number(left.unique) - Number(right.unique);\n if (uniqueCompare !== 0) {\n return uniqueCompare;\n }\n return compareStringsByCodeUnit(serializeIndexKeyPath(left), serializeIndexKeyPath(right));\n}\nexport function indexDefinitionIdentity(store: string, name: string): string {\n return JSON.stringify([store, name]);\n}\nexport function findIndexDefinition(\n defs: ReadonlyArray<NormalizedIndexDef>,\n store: string,\n name: string\n): NormalizedIndexDef | null {\n return defs.find((def) => def.store === store && def.name === name) ?? null;\n}\nexport function indexesForStore(defs: ReadonlyArray<NormalizedIndexDef>, store: string): NormalizedIndexDef[] {\n return defs.filter((def) => def.store === store);\n}\nexport function encodeIndexMetadataKey(store: string, name: string): Uint8Array {\n return encodeCompoundKeyParts([utf8Encode(store), utf8Encode(name)]);\n}\nexport function encodeIndexMetadataValue(def: NormalizedIndexDef): Uint8Array {\n return utf8Encode(JSON.stringify(toPublicIndexDefinition(def)));\n}\nexport function decodeIndexMetadataValue(bytes: Uint8Array): NormalizedIndexDef {\n let parsed: unknown;\n try {\n parsed = JSON.parse(fatalDecoder.decode(bytes));\n const [def] = normalizeIndexDefinitions([parsed]);\n return def;\n } catch (error) {\n throw new SerializationError(`invalid persisted index metadata: ${String(error)}`);\n }\n}\nexport function encodeIndexEntryKey(logicalIndexKey: Uint8Array, primaryKey: Uint8Array): Uint8Array {\n return encodeCompoundKeyParts([logicalIndexKey, primaryKey]);\n}\nexport function decodeIndexEntryKey(bytes: Uint8Array): DecodedIndexEntryKey {\n let parts: Uint8Array[];\n try {\n parts = splitCompoundKey(bytes);\n } catch (error) {\n throw new SerializationError(`invalid index entry key encoding: ${String(error)}`);\n }\n if (parts.length !== 2) {\n throw new SerializationError('invalid index entry key encoding');\n }\n return {\n logicalKey: parts[0],\n primaryKey: parts[1]\n };\n}\nexport function indexKeyExactRange(logicalIndexKey: Uint8Array): Range {\n return prefixRange(encodeCompoundKeyParts([logicalIndexKey]));\n}\nexport function indexRangeToPhysicalRange(range: Range = {}): Range {\n validateIndexRangeShape(range);\n const physical: Range = {};\n if (range.reverse !== undefined) {\n physical.reverse = range.reverse;\n }\n if (range.limit !== undefined) {\n physical.limit = range.limit;\n }\n if (range.gte) {\n physical.gte = encodeCompoundKeyParts([range.gte]);\n }\n if (range.gt) {\n const lower = prefixSuccessor(encodeCompoundKeyParts([range.gt]));\n if (lower) {\n physical.gte = lower;\n }\n }\n if (range.lt) {\n physical.lt = encodeCompoundKeyParts([range.lt]);\n }\n if (range.lte) {\n const upper = prefixSuccessor(encodeCompoundKeyParts([range.lte]));\n if (upper) {\n physical.lt = upper;\n }\n }\n return physical;\n}\nexport function extractLogicalIndexKey(def: NormalizedIndexDef, valueBytes: Uint8Array): Uint8Array | null {\n return extractLogicalIndexKeyFromDocument(def, decodeIndexedDocument(valueBytes));\n}\n/**\n * Reuse the decoded document only within one synchronous mutation plan.\n * Lazy decoding preserves validation order. Do not retain the extractor\n * across operations or an await.\n */\nexport function createIndexKeyExtractor(valueBytes: Uint8Array): (def: NormalizedIndexDef) => Uint8Array | null {\n let decoded = false;\n let documentValue: unknown;\n return (def) => {\n if (!decoded) {\n documentValue = decodeIndexedDocument(valueBytes);\n decoded = true;\n }\n return extractLogicalIndexKeyFromDocument(def, documentValue);\n };\n}\nexport function extractLogicalIndexKeyFromDocument(def: NormalizedIndexDef, documentValue: unknown): Uint8Array | null {\n if (def.compound) {\n const parts: Uint8Array[] = [];\n for (const keyPath of def.keyPath) {\n const resolved = resolveKeyPath(documentValue, keyPath);\n if (resolved === MISSING) {\n return null;\n }\n parts.push(encodeDocumentIndexValue(resolved));\n }\n return encodeCompoundKeyParts(parts);\n }\n const resolved = resolveKeyPath(documentValue, def.keyPath[0]);\n if (resolved === MISSING) {\n return null;\n }\n return encodeDocumentIndexValue(resolved);\n}\nexport function serializeNormalizedIndexDefinitions(defs: ReadonlyArray<NormalizedIndexDef>): string {\n return JSON.stringify(toPublicIndexDefinitions(defs));\n}\nexport function cloneNormalizedIndexDefinitions(defs: ReadonlyArray<NormalizedIndexDef>): NormalizedIndexDef[] {\n return defs.map((def) => ({\n store: def.store,\n name: def.name,\n keyPath: [...def.keyPath],\n compound: def.compound,\n unique: def.unique,\n internalStore: def.internalStore\n }));\n}\nexport function toPublicIndexDefinitions(defs: ReadonlyArray<NormalizedIndexDef>): IndexDef[] {\n return defs.map(toPublicIndexDefinition);\n}\nfunction toPublicIndexDefinition(def: NormalizedIndexDef): IndexDef {\n return {\n store: def.store,\n name: def.name,\n keyPath: def.compound ? [...def.keyPath] : def.keyPath[0],\n unique: def.unique\n };\n}\nfunction normalizeIndexKeyPath(value: unknown): {\n paths: string[];\n compound: boolean;\n} {\n if (typeof value === 'string') {\n validateSingleKeyPath(value);\n return { paths: [value], compound: false };\n }\n if (\n !Array.isArray(value) ||\n value.length === 0 ||\n !value.every((item): item is string => typeof item === 'string')\n ) {\n throw new InvalidOpenOptionsError('index keyPath must be a non-empty string or non-empty string[]');\n }\n for (const path of value) {\n validateSingleKeyPath(path);\n }\n return { paths: [...value], compound: true };\n}\nfunction validateSingleKeyPath(value: string): void {\n if (value.length === 0) {\n throw new InvalidOpenOptionsError('index keyPath strings must be non-empty');\n }\n if (value.startsWith('.') || value.endsWith('.') || value.includes('..')) {\n throw new InvalidOpenOptionsError(`invalid index keyPath: ${value}`);\n }\n}\nfunction serializeIndexKeyPath(def: NormalizedIndexDef): string {\n return def.compound ? `[${def.keyPath.join(',')}]` : def.keyPath[0];\n}\nfunction makeInternalIndexStoreName(store: string, name: string): string {\n const storeToken = base64Url(utf8Encode(store));\n const nameToken = base64Url(utf8Encode(name));\n const candidate = `${INTERNAL_INDEX_STORE_PREFIX}${storeToken}:${nameToken}`;\n if (encoder.encode(candidate).length <= 255) {\n return candidate;\n }\n // Preserve the persisted hash format. Normalization rejects distinct\n // identities that map to the same internal store, including separator collisions.\n const payload = utf8Encode(`${store}\\u0000${name}`);\n return `${INTERNAL_INDEX_STORE_PREFIX}h:${fnv1a64Hex(payload)}`;\n}\nfunction base64Url(bytes: Uint8Array): string {\n let binary = '';\n for (const byte of bytes) {\n binary += String.fromCharCode(byte);\n }\n return btoa(binary).replace(/\\+/g, '-').replace(/\\//g, '_').replace(/=+$/u, '');\n}\nfunction fnv1a64Hex(bytes: Uint8Array): string {\n let hash = FNV64_OFFSET;\n for (const byte of bytes) {\n hash ^= BigInt(byte);\n hash = (hash * FNV64_PRIME) & FNV64_MASK;\n }\n return hash.toString(16).padStart(16, '0');\n}\nexport function decodeIndexedDocument(bytes: Uint8Array): unknown {\n try {\n return JSON.parse(fatalDecoder.decode(bytes));\n } catch (error) {\n throw new SerializationError(`indexed values must be valid UTF-8 JSON: ${String(error)}`);\n }\n}\nfunction resolveKeyPath(root: unknown, keyPath: string): unknown {\n let current: unknown = root;\n for (const segment of keyPath.split('.')) {\n if (current === null || current === undefined) {\n return MISSING;\n }\n const target = Object(current) as Record<string, unknown>;\n if (!Object.hasOwn(target, segment)) {\n return MISSING;\n }\n current = Reflect.get(target, segment);\n }\n return current;\n}\nfunction encodeDocumentIndexValue(value: unknown): Uint8Array {\n if (\n value === null ||\n typeof value === 'string' ||\n typeof value === 'number' ||\n typeof value === 'boolean' ||\n value instanceof Uint8Array\n ) {\n try {\n return encodeIndexScalar(value);\n } catch (error) {\n if (error instanceof TypeError) {\n throw new SerializationError(`invalid indexed keyPath value: ${error.message}`);\n }\n throw error;\n }\n }\n throw new SerializationError(\n `indexed keyPath values must resolve to string, number, boolean, null, or Uint8Array; got ${describeValue(value)}`\n );\n}\nfunction describeValue(value: unknown): string {\n if (Array.isArray(value)) {\n return 'array';\n }\n return typeof value;\n}\nfunction validateIndexRangeShape(range: Range): void {\n if (range.gt !== undefined && range.gte !== undefined) {\n throw new TypeError('index range cannot specify both gt and gte');\n }\n if (range.lt !== undefined && range.lte !== undefined) {\n throw new TypeError('index range cannot specify both lt and lte');\n }\n}\n","import type { DbChange } from './types';\nimport { isRecord } from './internal';\nexport interface StoreChangeSet {\n store: string;\n changes: DbChange[];\n}\nexport interface CommitAppliedEvent {\n type: 'commit_applied';\n dbName: string;\n txid: number;\n stores: StoreChangeSet[];\n}\nexport interface OwnerChangedEvent {\n type: 'owner_changed';\n dbName: string;\n txid: null;\n}\nexport interface DbClosedEvent {\n type: 'db_closed';\n dbName: string;\n txid: null;\n}\nexport interface DbDeletedEvent {\n type: 'db_deleted';\n dbName: string;\n txid: null;\n}\nexport type WorkerBroadcastEvent = CommitAppliedEvent | OwnerChangedEvent | DbClosedEvent | DbDeletedEvent;\nfunction isDbChange(value: unknown): value is DbChange {\n if (!isRecord(value) || !(value.key instanceof Uint8Array)) {\n return false;\n }\n if (value.kind === 'put' || value.kind === 'delete') {\n return true;\n }\n return (value.kind === 'clear' || value.kind === 'drop') && value.key.byteLength === 0;\n}\nfunction isStoreChangeSet(value: unknown): value is StoreChangeSet {\n return (\n isRecord(value) &&\n typeof value.store === 'string' &&\n Array.isArray(value.changes) &&\n value.changes.every(isDbChange)\n );\n}\nexport function isCommitAppliedEvent(value: unknown): value is CommitAppliedEvent {\n return (\n isRecord(value) &&\n value.type === 'commit_applied' &&\n typeof value.dbName === 'string' &&\n typeof value.txid === 'number' &&\n Array.isArray(value.stores) &&\n value.stores.every(isStoreChangeSet)\n );\n}\n","import { DatabaseClosedError } from './errors';\nimport { isCommitAppliedEvent } from './change-events';\nimport { assertPublicStoreName } from './indexing';\nimport type { DbChange, DbSubscriptionCallback, Unsubscribe } from './types';\ninterface SubscriptionEntry {\n active: boolean;\n store: string | null;\n keyPrefix: Uint8Array | null;\n callback: DbSubscriptionCallback;\n}\ninterface SubscriptionSpec {\n store: string | null;\n keyPrefix: Uint8Array | null;\n callback: DbSubscriptionCallback;\n}\nfunction cloneChanges(changes: readonly DbChange[]): DbChange[] {\n return changes.map((change) => ({\n key: change.key.slice(),\n kind: change.kind\n }));\n}\nfunction hasKeyPrefix(key: Uint8Array, prefix: Uint8Array): boolean {\n if (prefix.byteLength > key.byteLength) {\n return false;\n }\n for (let index = 0; index < prefix.byteLength; index += 1) {\n if (key[index] !== prefix[index]) {\n return false;\n }\n }\n return true;\n}\nfunction normalizeSubscriptionSpec(\n arg1: string | DbSubscriptionCallback,\n arg2?: Uint8Array | DbSubscriptionCallback,\n arg3?: DbSubscriptionCallback\n): SubscriptionSpec {\n if (typeof arg1 === 'function') {\n if (arg2 !== undefined || arg3 !== undefined) {\n throw new TypeError('subscribe(callback) accepts exactly one callback argument');\n }\n return {\n store: null,\n keyPrefix: null,\n callback: arg1\n };\n }\n if (typeof arg1 !== 'string') {\n throw new TypeError('subscribe() storeName must be a string');\n }\n assertPublicStoreName(arg1);\n if (typeof arg2 === 'function') {\n if (arg3 !== undefined) {\n throw new TypeError('subscribe(storeName, callback) accepts exactly two arguments');\n }\n return {\n store: arg1,\n keyPrefix: null,\n callback: arg2\n };\n }\n if (arg2 instanceof Uint8Array && typeof arg3 === 'function') {\n return {\n store: arg1,\n keyPrefix: arg2.slice(),\n callback: arg3\n };\n }\n throw new TypeError(\n 'subscribe() expects one of: (callback), (storeName, callback), (storeName, keyPrefix, callback)'\n );\n}\nexport class SubscriptionHub {\n #dbName: string;\n #channelName: string;\n #channel: BroadcastChannel | null = null;\n #entries = new Set<SubscriptionEntry>();\n #closed = false;\n constructor(dbName: string, channelName = dbName) {\n this.#dbName = dbName;\n this.#channelName = channelName;\n }\n subscribe(callback: DbSubscriptionCallback): Unsubscribe;\n subscribe(storeName: string, callback: DbSubscriptionCallback): Unsubscribe;\n subscribe(storeName: string, keyPrefix: Uint8Array, callback: DbSubscriptionCallback): Unsubscribe;\n subscribe(\n arg1: string | DbSubscriptionCallback,\n arg2?: Uint8Array | DbSubscriptionCallback,\n arg3?: DbSubscriptionCallback\n ): Unsubscribe {\n if (this.#closed) {\n throw new DatabaseClosedError();\n }\n const spec = normalizeSubscriptionSpec(arg1, arg2, arg3);\n const entry: SubscriptionEntry = {\n active: true,\n store: spec.store,\n keyPrefix: spec.keyPrefix,\n callback: spec.callback\n };\n this.#ensureChannel();\n this.#entries.add(entry);\n return () => {\n if (!entry.active) {\n return;\n }\n entry.active = false;\n this.#entries.delete(entry);\n if (this.#entries.size === 0) {\n this.#disposeChannel();\n }\n };\n }\n close(): void {\n if (this.#closed) {\n return;\n }\n this.#closed = true;\n for (const entry of this.#entries) {\n entry.active = false;\n }\n this.#entries.clear();\n this.#disposeChannel();\n }\n #ensureChannel() {\n if (this.#channel !== null || this.#closed) {\n return;\n }\n const channel = new BroadcastChannel(`db:${this.#channelName}:events`);\n channel.onmessage = (event) => {\n this.#handleMessage(event.data);\n };\n this.#channel = channel;\n }\n #disposeChannel() {\n this.#channel?.close();\n this.#channel = null;\n }\n #handleMessage(payload: unknown) {\n if (!isCommitAppliedEvent(payload) || payload.dbName !== this.#dbName || this.#entries.size === 0) {\n return;\n }\n const entries = Array.from(this.#entries);\n for (const storeEvent of payload.stores) {\n for (const entry of entries) {\n if (!entry.active) {\n continue;\n }\n if (entry.store !== null && entry.store !== storeEvent.store) {\n continue;\n }\n let changes: DbChange[];\n const keyPrefix = entry.keyPrefix;\n if (keyPrefix === null) {\n changes = cloneChanges(storeEvent.changes);\n } else {\n changes = cloneChanges(\n storeEvent.changes.filter(\n (change) =>\n change.kind === 'clear' || change.kind === 'drop' || hasKeyPrefix(change.key, keyPrefix)\n )\n );\n if (changes.length === 0) {\n continue;\n }\n }\n try {\n entry.callback(storeEvent.store, changes, payload.txid);\n } catch (error) {\n queueMicrotask(() => {\n throw error;\n });\n }\n }\n }\n }\n}\n","import {\n encodeCompoundKeyParts,\n encodeIndexScalar,\n jsonDecode,\n jsonEncode,\n splitCompoundKey,\n type CompoundKeyPart\n} from './codec';\nimport { TransactionClosedError } from './errors';\nimport type { BatchOp, CreateStoreOptions, DB, PutOptions, Range, Transaction, TxMode } from './types';\n\nexport interface RecordCodec<T> {\n encode(value: T): Uint8Array;\n decode(bytes: Uint8Array): T;\n}\n\nexport interface RecordCodecs<K, V> {\n key: RecordCodec<K>;\n value: RecordCodec<V>;\n}\n\nexport interface RecordRange<K> {\n gt?: K;\n gte?: K;\n lt?: K;\n lte?: K;\n reverse?: boolean;\n limit?: number;\n}\n\nexport interface RecordItem<K, V> {\n key: K;\n value: V;\n}\n\nexport type RecordBatchOp<K, V> = { kind: 'put'; key: K; value: V } | { kind: 'delete'; key: K };\nexport type JsonValue = null | boolean | number | string | JsonValue[] | { [key: string]: JsonValue };\n\nconst fatalDecoder = new TextDecoder('utf-8', { fatal: true });\nconst NUMBER_MASK = (1n << 64n) - 1n;\nconst NUMBER_SIGN = 1n << 63n;\n\nfunction sameBytes(left: Uint8Array, right: Uint8Array): boolean {\n return left.length === right.length && left.every((byte, index) => byte === right[index]);\n}\n\nfunction decodeScalarKey(bytes: Uint8Array): CompoundKeyPart {\n if (!(bytes instanceof Uint8Array) || bytes.length === 0) {\n throw new TypeError('invalid scalar key encoding');\n }\n let value: CompoundKeyPart;\n switch (bytes[0]) {\n case 0x10:\n value = null;\n break;\n case 0x20:\n value = false;\n break;\n case 0x21:\n value = true;\n break;\n case 0x30: {\n if (bytes.length !== 9) {\n throw new TypeError('invalid number key encoding');\n }\n const view = new DataView(bytes.buffer, bytes.byteOffset + 1, 8);\n const ordered = view.getBigUint64(0, false);\n const bits = (ordered & NUMBER_SIGN) !== 0n ? ordered ^ NUMBER_SIGN : ordered ^ NUMBER_MASK;\n const buffer = new ArrayBuffer(8);\n const decoded = new DataView(buffer);\n decoded.setBigUint64(0, bits, false);\n value = decoded.getFloat64(0, false);\n break;\n }\n case 0x40:\n value = fatalDecoder.decode(bytes.subarray(1));\n break;\n case 0x50:\n value = bytes.slice(1);\n break;\n default:\n throw new TypeError('invalid scalar key type');\n }\n if (!sameBytes(encodeIndexScalar(value), bytes)) {\n throw new TypeError('noncanonical scalar key encoding');\n }\n return value;\n}\n\nexport const scalarKeyCodec: RecordCodec<CompoundKeyPart> = Object.freeze({\n encode: encodeIndexScalar,\n decode: decodeScalarKey\n});\n\nfunction typedKeyCodec<T extends CompoundKeyPart>(\n type: string,\n accepts: (value: CompoundKeyPart) => value is T\n): RecordCodec<T> {\n function check(value: CompoundKeyPart): T {\n if (!accepts(value)) {\n throw new TypeError(`key must be ${type}`);\n }\n return value;\n }\n return Object.freeze({\n encode(value: T): Uint8Array {\n return encodeIndexScalar(check(value));\n },\n decode(bytes: Uint8Array): T {\n return check(decodeScalarKey(bytes));\n }\n });\n}\n\nexport const keyCodecs = Object.freeze({\n string: typedKeyCodec('a string', (value): value is string => typeof value === 'string'),\n number: typedKeyCodec('a finite number', (value): value is number => typeof value === 'number'),\n boolean: typedKeyCodec('a boolean', (value): value is boolean => typeof value === 'boolean'),\n null: typedKeyCodec('null', (value): value is null => value === null),\n bytes: typedKeyCodec('Uint8Array', (value): value is Uint8Array => value instanceof Uint8Array)\n});\n\nexport function compoundKeyCodec<T extends readonly CompoundKeyPart[]>(\n ...parts: { [I in keyof T]: RecordCodec<T[I]> }\n): RecordCodec<T> {\n return Object.freeze({\n encode(value: T): Uint8Array {\n if (!Array.isArray(value) || value.length !== parts.length) {\n throw new TypeError(`compound key must contain ${parts.length} parts`);\n }\n return encodeCompoundKeyParts(parts.map((codec, index) => codec.encode(value[index] as CompoundKeyPart)));\n },\n decode(bytes: Uint8Array): T {\n const encoded = splitCompoundKey(bytes);\n if (encoded.length !== parts.length) {\n throw new TypeError(`compound key must contain ${parts.length} parts`);\n }\n return parts.map((codec, index) => codec.decode(encoded[index])) as unknown as T;\n }\n });\n}\n\nfunction assertJsonValue(value: unknown): asserts value is JsonValue {\n const pending: Array<{ value: unknown; leave?: boolean }> = [{ value }];\n const active = new Set<object>();\n while (pending.length > 0) {\n const entry = pending.pop() as { value: unknown; leave?: boolean };\n const current = entry.value;\n if (entry.leave) {\n active.delete(current as object);\n continue;\n }\n if (current === null || typeof current === 'string' || typeof current === 'boolean') {\n continue;\n }\n if (typeof current === 'number' && Number.isFinite(current) && !Object.is(current, -0)) {\n continue;\n }\n if (typeof current !== 'object' || active.has(current)) {\n throw new TypeError('record must contain JSON values without cycles, nonfinite numbers or negative zero');\n }\n const array = Array.isArray(current);\n if (Object.getPrototypeOf(current) !== (array ? Array.prototype : Object.prototype)) {\n throw new TypeError('record objects must be plain objects or arrays');\n }\n active.add(current);\n pending.push({ value: current, leave: true });\n const keys = Reflect.ownKeys(current);\n if (array && keys.length !== current.length + 1) {\n throw new TypeError('record arrays must be dense and have no extra properties');\n }\n for (const key of keys) {\n if (array && key === 'length') {\n continue;\n }\n if (typeof key !== 'string') {\n throw new TypeError('record properties must have string keys');\n }\n if (array && (!/^(?:0|[1-9]\\d*)$/.test(key) || Number(key) >= current.length)) {\n throw new TypeError('record arrays must have no extra properties');\n }\n const descriptor = Object.getOwnPropertyDescriptor(current, key);\n if (!descriptor || !descriptor.enumerable || !Object.hasOwn(descriptor, 'value')) {\n throw new TypeError('record properties must be enumerable data properties');\n }\n pending.push({ value: descriptor.value as unknown });\n }\n }\n}\n\n/** A type guard checks the application schema. Without one, only the JSON domain is checked. */\nexport function jsonRecordCodec<T = JsonValue>(validate?: (value: unknown) => value is T): RecordCodec<T> {\n function check(value: unknown): T {\n assertJsonValue(value);\n if (validate) {\n if (!validate(value)) {\n throw new TypeError('record does not match its schema');\n }\n assertJsonValue(value);\n }\n return value as T;\n }\n return Object.freeze({\n encode(value: T): Uint8Array {\n return jsonEncode(check(value));\n },\n decode(bytes: Uint8Array): T {\n return check(jsonDecode<unknown>(bytes));\n }\n });\n}\n\nfunction encodeRange<K>(codec: RecordCodec<K>, range: RecordRange<K>): Range {\n const encoded: Range = {};\n for (const bound of ['gt', 'gte', 'lt', 'lte'] as const) {\n if (Object.hasOwn(range, bound)) {\n encoded[bound] = codec.encode(range[bound] as K);\n }\n }\n if (range.reverse !== undefined) {\n encoded.reverse = range.reverse;\n }\n if (range.limit !== undefined) {\n encoded.limit = range.limit;\n }\n return encoded;\n}\n\nexport async function withRecordTransaction<R>(\n db: DB,\n mode: TxMode,\n action: (transaction: Transaction) => Promise<R> | R\n): Promise<R> {\n const transaction = await db.begin(mode);\n let result: R;\n try {\n result = await action(transaction);\n } catch (error) {\n try {\n await transaction.rollback();\n } catch (rollbackError) {\n if (!(rollbackError instanceof TransactionClosedError)) {\n throw new AggregateError([error, rollbackError], 'record transaction and rollback failed', {\n cause: rollbackError\n });\n }\n }\n throw error;\n }\n // SDK completion methods close the transaction even when they fail.\n if (mode === 'readwrite') {\n await transaction.commit();\n } else {\n await transaction.rollback();\n }\n return result;\n}\n\nfunction useTransaction<R>(\n source: DB | Transaction,\n mode: TxMode,\n action: (transaction: Transaction) => Promise<R>\n): Promise<R> {\n return 'begin' in source ? withRecordTransaction(source, mode, action) : action(source);\n}\n\nexport class RecordIndex<I, K, V> {\n readonly name: string;\n #source: DB | Transaction;\n #store: string;\n #indexKey: RecordCodec<I>;\n #codecs: RecordCodecs<K, V>;\n\n constructor(\n source: DB | Transaction,\n store: string,\n name: string,\n indexKey: RecordCodec<I>,\n codecs: RecordCodecs<K, V>\n ) {\n this.#source = source;\n this.#store = store;\n this.name = name;\n this.#indexKey = indexKey;\n this.#codecs = codecs;\n }\n\n async get(key: I): Promise<V | null> {\n const encoded = this.#indexKey.encode(key);\n return useTransaction(this.#source, 'readonly', async (transaction) => {\n const value = await transaction.getByIndex(this.#store, this.name, encoded);\n return value === null ? null : this.#codecs.value.decode(value);\n });\n }\n\n async scan(range: RecordRange<I> = {}): Promise<Array<RecordItem<K, V>>> {\n const encoded = encodeRange(this.#indexKey, range);\n return useTransaction(this.#source, 'readonly', async (transaction) => {\n const rows: Array<RecordItem<K, V>> = [];\n for await (const [key, value] of transaction.scanByIndex(this.#store, this.name, encoded)) {\n rows.push({ key: this.#codecs.key.decode(key), value: this.#codecs.value.decode(value) });\n }\n return rows;\n });\n }\n}\n\nexport class RecordStore<K, V> {\n readonly name: string;\n #source: DB | Transaction;\n #codecs: RecordCodecs<K, V>;\n\n constructor(source: DB | Transaction, name: string, codecs: RecordCodecs<K, V>) {\n this.#source = source;\n this.name = name;\n this.#codecs = codecs;\n }\n\n async get(key: K): Promise<V | null> {\n const value = await this.#source.get(this.name, this.#codecs.key.encode(key));\n return value === null ? null : this.#codecs.value.decode(value);\n }\n\n async getMany(keys: readonly K[]): Promise<Array<V | null>> {\n const values = await this.#source.getMany(\n this.name,\n keys.map((key) => this.#codecs.key.encode(key))\n );\n return values.map((value) => (value === null ? null : this.#codecs.value.decode(value)));\n }\n\n async has(key: K): Promise<boolean> {\n return this.#source.has(this.name, this.#codecs.key.encode(key));\n }\n\n async put(key: K, value: V, options?: PutOptions): Promise<void> {\n await this.#source.put(this.name, this.#codecs.key.encode(key), this.#codecs.value.encode(value), options);\n }\n\n async putMany(entries: ReadonlyArray<readonly [K, V]>, options?: PutOptions): Promise<void> {\n const encoded = entries.map(([key, value]): [Uint8Array, Uint8Array] => [\n this.#codecs.key.encode(key),\n this.#codecs.value.encode(value)\n ]);\n await useTransaction(this.#source, 'readwrite', (transaction) =>\n transaction.putMany(this.name, encoded, options)\n );\n }\n\n async delete(key: K): Promise<boolean> {\n return this.#source.delete(this.name, this.#codecs.key.encode(key));\n }\n\n async deleteMany(keys: readonly K[]): Promise<void> {\n const encoded = keys.map((key) => this.#codecs.key.encode(key));\n await useTransaction(this.#source, 'readwrite', (transaction) => transaction.deleteMany(this.name, encoded));\n }\n\n async applyBatch(operations: ReadonlyArray<RecordBatchOp<K, V>>): Promise<void> {\n const encoded = operations.map((operation): BatchOp => {\n const kind = (operation as { kind: unknown }).kind;\n if (kind !== 'put' && kind !== 'delete') {\n throw new TypeError('record batch operation must be put or delete');\n }\n const key = this.#codecs.key.encode(operation.key);\n if (operation.kind === 'delete') {\n return { kind: 'delete', key };\n }\n return { kind: 'put', key, value: this.#codecs.value.encode(operation.value) };\n });\n await useTransaction(this.#source, 'readwrite', (transaction) => transaction.applyBatch(this.name, encoded));\n }\n\n async scan(range: RecordRange<K> = {}): Promise<Array<RecordItem<K, V>>> {\n const rows = await this.#source.scan(this.name, encodeRange(this.#codecs.key, range));\n return rows.map(({ key, value }) => ({\n key: this.#codecs.key.decode(key),\n value: this.#codecs.value.decode(value)\n }));\n }\n\n async clear(): Promise<void> {\n await this.#source.clearStore(this.name);\n }\n\n index<I>(name: string, key: RecordCodec<I>): RecordIndex<I, K, V> {\n return new RecordIndex(this.#source, this.name, name, key, this.#codecs);\n }\n\n transaction<R>(\n mode: TxMode,\n action: (store: RecordStore<K, V>, transaction: Transaction) => Promise<R> | R\n ): Promise<R> {\n if (!('begin' in this.#source)) {\n return Promise.reject(new TypeError('record store already belongs to a transaction'));\n }\n return withRecordTransaction(this.#source, mode, (transaction) =>\n action(new RecordStore(transaction, this.name, this.#codecs), transaction)\n );\n }\n}\n\n/** Bind codecs to an existing store. The database still enforces store existence. */\nexport function openRecordStore<K, V>(\n source: DB | Transaction,\n name: string,\n codecs: RecordCodecs<K, V>\n): RecordStore<K, V> {\n return new RecordStore(source, name, codecs);\n}\n\nexport async function createRecordStore<K, V>(\n source: DB | Transaction,\n name: string,\n codecs: RecordCodecs<K, V>,\n options?: CreateStoreOptions\n): Promise<RecordStore<K, V>> {\n await source.createStore(name, options);\n return openRecordStore(source, name, codecs);\n}\n","export const SQL_INTEGER_MIN = -(1n << 63n);\nexport const SQL_INTEGER_MAX = (1n << 63n) - 1n;\n\nexport type SqlValue = null | boolean | number | bigint | string | Uint8Array;\nexport type SqlColumnType = 'INTEGER' | 'REAL' | 'TEXT' | 'BOOLEAN' | 'BLOB';\n\nexport interface SqlColumnDefinition {\n name: string;\n type: SqlColumnType;\n primaryKey: boolean;\n nullable: boolean;\n}\n\nexport type SqlValueExpression = { kind: 'literal'; value: SqlValue } | { kind: 'parameter'; index: number };\nexport type SqlComparisonOperator = '=' | '!=' | '<' | '<=' | '>' | '>=';\nexport type SqlExpression =\n | { kind: 'comparison'; column: string; operator: SqlComparisonOperator; value: SqlValueExpression }\n | { kind: 'isNull'; column: string; negated: boolean }\n | { kind: 'and' | 'or'; left: SqlExpression; right: SqlExpression };\n\nexport interface SqlOrderBy {\n column: string;\n direction: 'asc' | 'desc';\n}\n\nexport interface SqlCreateTableStatement {\n kind: 'createTable';\n table: string;\n columns: SqlColumnDefinition[];\n ifNotExists: boolean;\n}\n\nexport interface SqlDropTableStatement {\n kind: 'dropTable';\n table: string;\n ifExists: boolean;\n}\n\nexport interface SqlInsertStatement {\n kind: 'insert';\n table: string;\n columns: string[] | null;\n rows: SqlValueExpression[][];\n}\n\nexport interface SqlSelectStatement {\n kind: 'select';\n table: string;\n columns: string[] | null;\n where: SqlExpression | null;\n orderBy: SqlOrderBy[];\n limit: SqlValueExpression | null;\n offset: SqlValueExpression | null;\n}\n\nexport interface SqlUpdateStatement {\n kind: 'update';\n table: string;\n assignments: { column: string; value: SqlValueExpression }[];\n where: SqlExpression | null;\n}\n\nexport interface SqlDeleteStatement {\n kind: 'delete';\n table: string;\n where: SqlExpression | null;\n}\n\nexport type SqlStatement =\n | SqlCreateTableStatement\n | SqlDropTableStatement\n | SqlInsertStatement\n | SqlSelectStatement\n | SqlUpdateStatement\n | SqlDeleteStatement;\n\nexport interface SqlParseResult {\n statement: SqlStatement;\n parameterCount: number;\n}\n","import {\n SQL_INTEGER_MAX,\n SQL_INTEGER_MIN,\n type SqlColumnDefinition,\n type SqlColumnType,\n type SqlComparisonOperator,\n type SqlExpression,\n type SqlOrderBy,\n type SqlParseResult,\n type SqlStatement,\n type SqlValue,\n type SqlValueExpression\n} from './sql-types';\n\nconst MAX_SQL_LENGTH = 1_048_576;\nconst MAX_TOKENS = 16_384;\nconst MAX_NESTING = 64;\nconst MAX_PREDICATES = 128;\nconst MAX_IDENTIFIER_LENGTH = 128;\nconst MAX_NUMBER_LENGTH = 1_024;\nconst FORBIDDEN_IDENTIFIERS = new Set(['__proto__', 'prototype', 'constructor']);\nconst COLUMN_TYPES = new Set<SqlColumnType>(['INTEGER', 'REAL', 'TEXT', 'BOOLEAN', 'BLOB']);\nconst KEYWORDS = new Set([\n 'CREATE',\n 'TABLE',\n 'IF',\n 'NOT',\n 'EXISTS',\n 'DROP',\n 'INSERT',\n 'INTO',\n 'VALUES',\n 'SELECT',\n 'FROM',\n 'WHERE',\n 'ORDER',\n 'BY',\n 'ASC',\n 'DESC',\n 'LIMIT',\n 'OFFSET',\n 'UPDATE',\n 'SET',\n 'DELETE',\n 'PRIMARY',\n 'KEY',\n 'NULL',\n 'TRUE',\n 'FALSE',\n 'IS',\n 'AND',\n 'OR',\n 'JOIN',\n 'LEFT',\n 'RIGHT',\n 'INNER',\n 'OUTER',\n 'CROSS',\n 'ON',\n 'AS',\n 'DISTINCT',\n 'GROUP',\n 'HAVING',\n 'UNION',\n 'ALL',\n 'IN',\n 'LIKE',\n 'BETWEEN',\n 'DEFAULT',\n 'UNIQUE',\n 'CHECK',\n 'REFERENCES',\n 'CONSTRAINT',\n 'FOREIGN',\n 'AUTOINCREMENT',\n 'RETURNING',\n 'CONFLICT',\n ...COLUMN_TYPES\n]);\n\ntype TokenKind = 'word' | 'identifier' | 'string' | 'number' | 'symbol' | 'parameter' | 'end';\ninterface Token {\n kind: TokenKind;\n text: string;\n position: number;\n}\n\nexport class SqlSyntaxError extends SyntaxError {\n readonly position: number;\n\n constructor(message: string, position: number) {\n super(`${message} at position ${position}`);\n this.name = 'SqlSyntaxError';\n this.position = position;\n }\n}\n\nexport function parseSql(sql: string): SqlParseResult {\n if (typeof sql !== 'string') {\n throw new TypeError('SQL must be a string');\n }\n if (sql.length > MAX_SQL_LENGTH) {\n throw new SqlSyntaxError(`SQL exceeds ${MAX_SQL_LENGTH} characters`, MAX_SQL_LENGTH);\n }\n return new Parser(tokenize(sql)).parse();\n}\n\nexport function bindSqlParameters(parsed: SqlParseResult, parameters: readonly unknown[] = []): SqlValue[] {\n if (!Array.isArray(parameters)) {\n throw new TypeError('SQL parameters must be an array');\n }\n if (parameters.length !== parsed.parameterCount) {\n throw new RangeError(`SQL expects ${parsed.parameterCount} parameters; received ${parameters.length}`);\n }\n return Array.from<unknown, SqlValue>(parameters, (value, index) => {\n if (value === null || typeof value === 'boolean') {\n return value;\n }\n if (typeof value === 'number') {\n if (!Number.isFinite(value) || (Number.isInteger(value) && !Number.isSafeInteger(value))) {\n throw new RangeError(\n `SQL parameter ${index + 1} must be finite; use bigint for integers outside the safe range`\n );\n }\n return value;\n }\n if (typeof value === 'bigint') {\n if (value < SQL_INTEGER_MIN || value > SQL_INTEGER_MAX) {\n throw new RangeError(`SQL parameter ${index + 1} exceeds the signed 64-bit integer range`);\n }\n return value;\n }\n if (typeof value === 'string') {\n if (!hasValidUnicode(value)) {\n throw new TypeError(`SQL parameter ${index + 1} must contain valid Unicode scalar values`);\n }\n return value;\n }\n if (value instanceof Uint8Array) {\n return Uint8Array.from(value);\n }\n throw new TypeError(`SQL parameter ${index + 1} must be null, boolean, number, bigint, string, or Uint8Array`);\n });\n}\n\nexport function resolveSqlValue(expression: SqlValueExpression, parameters: readonly SqlValue[]): SqlValue {\n if (expression.kind === 'literal') {\n return expression.value;\n }\n if (!Number.isSafeInteger(expression.index) || expression.index < 0 || expression.index >= parameters.length) {\n throw new RangeError(`SQL parameter ${expression.index + 1} is missing`);\n }\n const value = parameters.at(expression.index);\n if (value === undefined) {\n throw new RangeError(`SQL parameter ${expression.index + 1} is missing`);\n }\n return value;\n}\n\nclass Parser {\n #tokens: Token[];\n #index = 0;\n #parameterCount = 0;\n #nesting = 0;\n #predicates = 0;\n\n constructor(tokens: Token[]) {\n this.#tokens = tokens;\n }\n\n parse(): SqlParseResult {\n const statement = this.#parseStatement();\n this.#acceptSymbol(';');\n if (this.#current().kind !== 'end') {\n throw this.#error('Unexpected or unsupported SQL syntax');\n }\n return { statement, parameterCount: this.#parameterCount };\n }\n\n #parseStatement(): SqlStatement {\n if (this.#acceptKeyword('CREATE')) {\n return this.#createTable();\n }\n if (this.#acceptKeyword('DROP')) {\n return this.#dropTable();\n }\n if (this.#acceptKeyword('INSERT')) {\n return this.#insert();\n }\n if (this.#acceptKeyword('SELECT')) {\n return this.#select();\n }\n if (this.#acceptKeyword('UPDATE')) {\n return this.#update();\n }\n if (this.#acceptKeyword('DELETE')) {\n return this.#delete();\n }\n throw this.#error('Expected CREATE TABLE, DROP TABLE, INSERT, SELECT, UPDATE, or DELETE');\n }\n\n #createTable(): SqlStatement {\n this.#expectKeyword('TABLE');\n const ifNotExists = this.#acceptKeyword('IF');\n if (ifNotExists) {\n this.#expectKeyword('NOT');\n this.#expectKeyword('EXISTS');\n }\n const table = this.#identifier();\n this.#expectSymbol('(');\n const columns: SqlColumnDefinition[] = [];\n const names = new Set<string>();\n let primaryKeyCount = 0;\n do {\n const name = this.#identifier();\n this.#assertUnique(names, name, 'column');\n const typeToken = this.#current();\n const type = typeToken.text.toUpperCase() as SqlColumnType;\n if (typeToken.kind !== 'word' || !COLUMN_TYPES.has(type)) {\n throw this.#error('Expected INTEGER, REAL, TEXT, BOOLEAN, or BLOB column type');\n }\n this.#index += 1;\n let primaryKey = false;\n let nullable = true;\n let nullabilitySpecified = false;\n for (;;) {\n if (this.#acceptKeyword('PRIMARY')) {\n if (primaryKey) {\n throw this.#error('Duplicate PRIMARY KEY constraint');\n }\n this.#expectKeyword('KEY');\n primaryKey = true;\n primaryKeyCount += 1;\n if (primaryKeyCount > 1) {\n throw this.#error('Only one inline PRIMARY KEY is supported');\n }\n } else if (this.#acceptKeyword('NOT')) {\n this.#expectKeyword('NULL');\n if (nullabilitySpecified) {\n throw this.#error('Duplicate nullability constraint');\n }\n nullable = false;\n nullabilitySpecified = true;\n } else if (this.#acceptKeyword('NULL')) {\n if (nullabilitySpecified) {\n throw this.#error('Duplicate nullability constraint');\n }\n nullable = true;\n nullabilitySpecified = true;\n } else {\n break;\n }\n }\n if (primaryKey && nullable && nullabilitySpecified) {\n throw this.#error('PRIMARY KEY cannot be declared NULL');\n }\n columns.push({ name, type, primaryKey, nullable: primaryKey ? false : nullable });\n } while (this.#acceptSymbol(','));\n this.#expectSymbol(')');\n return { kind: 'createTable', table, columns, ifNotExists };\n }\n\n #dropTable(): SqlStatement {\n this.#expectKeyword('TABLE');\n const ifExists = this.#acceptKeyword('IF');\n if (ifExists) {\n this.#expectKeyword('EXISTS');\n }\n return { kind: 'dropTable', table: this.#identifier(), ifExists };\n }\n\n #insert(): SqlStatement {\n this.#expectKeyword('INTO');\n const table = this.#identifier();\n let columns: string[] | null = null;\n if (this.#acceptSymbol('(')) {\n columns = this.#identifierList();\n this.#expectSymbol(')');\n }\n this.#expectKeyword('VALUES');\n const rows: SqlValueExpression[][] = [];\n let width = columns?.length;\n do {\n this.#expectSymbol('(');\n const row = [this.#value()];\n while (this.#acceptSymbol(',')) {\n row.push(this.#value());\n }\n this.#expectSymbol(')');\n width ??= row.length;\n if (row.length !== width) {\n throw this.#error('INSERT rows must match the column count');\n }\n rows.push(row);\n } while (this.#acceptSymbol(','));\n return { kind: 'insert', table, columns, rows };\n }\n\n #select(): SqlStatement {\n const columns = this.#acceptSymbol('*') ? null : this.#identifierList();\n this.#expectKeyword('FROM');\n const table = this.#identifier();\n const where = this.#where();\n const orderBy: SqlOrderBy[] = [];\n if (this.#acceptKeyword('ORDER')) {\n this.#expectKeyword('BY');\n const names = new Set<string>();\n do {\n const column = this.#identifier();\n this.#assertUnique(names, column, 'ORDER BY column');\n const direction = this.#acceptKeyword('DESC') ? 'desc' : 'asc';\n if (direction === 'asc') {\n this.#acceptKeyword('ASC');\n }\n orderBy.push({ column, direction });\n } while (this.#acceptSymbol(','));\n }\n let limit: SqlValueExpression | null = null;\n let offset: SqlValueExpression | null = null;\n if (this.#acceptKeyword('LIMIT')) {\n limit = this.#rowCount('LIMIT');\n if (this.#acceptKeyword('OFFSET')) {\n offset = this.#rowCount('OFFSET');\n }\n }\n return { kind: 'select', table, columns, where, orderBy, limit, offset };\n }\n\n #update(): SqlStatement {\n const table = this.#identifier();\n this.#expectKeyword('SET');\n const assignments: { column: string; value: SqlValueExpression }[] = [];\n const names = new Set<string>();\n do {\n const column = this.#identifier();\n this.#assertUnique(names, column, 'assignment');\n this.#expectSymbol('=');\n assignments.push({ column, value: this.#value() });\n } while (this.#acceptSymbol(','));\n return { kind: 'update', table, assignments, where: this.#where() };\n }\n\n #delete(): SqlStatement {\n this.#expectKeyword('FROM');\n return { kind: 'delete', table: this.#identifier(), where: this.#where() };\n }\n\n #where(): SqlExpression | null {\n return this.#acceptKeyword('WHERE') ? this.#or() : null;\n }\n\n #or(): SqlExpression {\n let expression = this.#and();\n while (this.#acceptKeyword('OR')) {\n expression = { kind: 'or', left: expression, right: this.#and() };\n }\n return expression;\n }\n\n #and(): SqlExpression {\n let expression = this.#predicate();\n while (this.#acceptKeyword('AND')) {\n expression = { kind: 'and', left: expression, right: this.#predicate() };\n }\n return expression;\n }\n\n #predicate(): SqlExpression {\n if (this.#acceptSymbol('(')) {\n this.#nesting += 1;\n if (this.#nesting > MAX_NESTING) {\n throw this.#error(`WHERE nesting exceeds ${MAX_NESTING}`);\n }\n const expression = this.#or();\n this.#expectSymbol(')');\n this.#nesting -= 1;\n return expression;\n }\n this.#predicates += 1;\n if (this.#predicates > MAX_PREDICATES) {\n throw this.#error(`WHERE predicates exceed ${MAX_PREDICATES}`);\n }\n const column = this.#identifier();\n if (this.#acceptKeyword('IS')) {\n const negated = this.#acceptKeyword('NOT');\n this.#expectKeyword('NULL');\n return { kind: 'isNull', column, negated };\n }\n const token = this.#current();\n if (token.kind !== 'symbol' || !['=', '!=', '<>', '<', '<=', '>', '>='].includes(token.text)) {\n throw this.#error('Expected a comparison operator or IS [NOT] NULL');\n }\n this.#index += 1;\n const operator = (token.text === '<>' ? '!=' : token.text) as SqlComparisonOperator;\n return { kind: 'comparison', column, operator, value: this.#value() };\n }\n\n #rowCount(clause: string): SqlValueExpression {\n const value = this.#value();\n if (\n value.kind === 'literal' &&\n (typeof value.value !== 'number' || !Number.isSafeInteger(value.value) || value.value < 0)\n ) {\n throw this.#error(`${clause} must be a non-negative safe integer or parameter`);\n }\n return value;\n }\n\n #value(): SqlValueExpression {\n const token = this.#current();\n if (token.kind === 'parameter') {\n this.#index += 1;\n return { kind: 'parameter', index: this.#parameterCount++ };\n }\n if (token.kind === 'string') {\n this.#index += 1;\n return { kind: 'literal', value: token.text };\n }\n if (this.#acceptKeyword('NULL')) {\n return { kind: 'literal', value: null };\n }\n if (this.#acceptKeyword('TRUE')) {\n return { kind: 'literal', value: true };\n }\n if (this.#acceptKeyword('FALSE')) {\n return { kind: 'literal', value: false };\n }\n const sign = this.#acceptSymbol('-') ? '-' : this.#acceptSymbol('+') ? '+' : '';\n const number = this.#current();\n if (number.kind === 'number') {\n this.#index += 1;\n return { kind: 'literal', value: parseNumber(sign + number.text, token.position) };\n }\n throw this.#error('Expected a scalar literal or positional ? parameter');\n }\n\n #identifierList(): string[] {\n const names = new Set<string>();\n const columns: string[] = [];\n do {\n const name = this.#identifier();\n this.#assertUnique(names, name, 'column');\n columns.push(name);\n } while (this.#acceptSymbol(','));\n return columns;\n }\n\n #identifier(): string {\n const token = this.#current();\n if (token.kind !== 'identifier' && (token.kind !== 'word' || KEYWORDS.has(token.text.toUpperCase()))) {\n throw this.#error('Expected an identifier; use double quotes for keywords');\n }\n if (\n token.text.length === 0 ||\n token.text.length > MAX_IDENTIFIER_LENGTH ||\n hasControlCharacters(token.text) ||\n FORBIDDEN_IDENTIFIERS.has(token.text.toLowerCase()) ||\n !hasValidUnicode(token.text)\n ) {\n throw this.#error('Invalid or reserved identifier');\n }\n this.#index += 1;\n return token.text;\n }\n\n #assertUnique(names: Set<string>, name: string, label: string): void {\n if (names.has(name)) {\n throw this.#error(`Duplicate ${label}: ${name}`);\n }\n names.add(name);\n }\n\n #current(): Token {\n return this.#tokens[this.#index];\n }\n\n #acceptKeyword(keyword: string): boolean {\n const token = this.#current();\n if (token.kind !== 'word' || token.text.toUpperCase() !== keyword) {\n return false;\n }\n this.#index += 1;\n return true;\n }\n\n #expectKeyword(keyword: string): void {\n if (!this.#acceptKeyword(keyword)) {\n throw this.#error(`Expected ${keyword}`);\n }\n }\n\n #acceptSymbol(symbol: string): boolean {\n const token = this.#current();\n if (token.kind !== 'symbol' || token.text !== symbol) {\n return false;\n }\n this.#index += 1;\n return true;\n }\n\n #expectSymbol(symbol: string): void {\n if (!this.#acceptSymbol(symbol)) {\n throw this.#error(`Expected ${symbol}`);\n }\n }\n\n #error(message: string): SqlSyntaxError {\n return new SqlSyntaxError(message, this.#current().position);\n }\n}\n\nfunction tokenize(sql: string): Token[] {\n const tokens: Token[] = [];\n let index = 0;\n while (index < sql.length) {\n const character = sql[index];\n if (/\\s/u.test(character)) {\n index += 1;\n continue;\n }\n if (sql.startsWith('--', index)) {\n index += 2;\n while (index < sql.length && sql[index] !== '\\n' && sql[index] !== '\\r') {\n index += 1;\n }\n continue;\n }\n if (sql.startsWith('/*', index)) {\n const end = sql.indexOf('*/', index + 2);\n if (end < 0) {\n throw new SqlSyntaxError('Unterminated block comment', index);\n }\n index = end + 2;\n continue;\n }\n if (tokens.length >= MAX_TOKENS) {\n throw new SqlSyntaxError(`SQL token count exceeds ${MAX_TOKENS}`, index);\n }\n const position = index;\n if (character === \"'\" || character === '\"') {\n const quote = character;\n let text = '';\n let closed = false;\n index += 1;\n while (index < sql.length) {\n if (sql[index] === quote) {\n if (sql[index + 1] === quote) {\n text += quote;\n index += 2;\n } else {\n index += 1;\n closed = true;\n break;\n }\n } else {\n text += sql[index++];\n }\n }\n if (!closed) {\n throw new SqlSyntaxError('Unterminated quoted token', position);\n }\n if (!hasValidUnicode(text)) {\n throw new SqlSyntaxError('Quoted token must contain valid Unicode scalar values', position);\n }\n tokens.push({ kind: quote === \"'\" ? 'string' : 'identifier', text, position });\n } else if (/[A-Za-z_]/u.test(character)) {\n index += 1;\n while (index < sql.length && /\\w/u.test(sql[index])) {\n index += 1;\n }\n tokens.push({ kind: 'word', text: sql.slice(position, index), position });\n } else if (/\\d/u.test(character) || (character === '.' && /\\d/u.test(sql[index + 1] ?? ''))) {\n index += 1;\n while (index < sql.length && /\\d/u.test(sql[index])) {\n index += 1;\n }\n if (character !== '.' && sql[index] === '.') {\n index += 1;\n while (index < sql.length && /\\d/u.test(sql[index])) {\n index += 1;\n }\n }\n if (sql[index] === 'e' || sql[index] === 'E') {\n index += 1;\n if (sql[index] === '+' || sql[index] === '-') {\n index += 1;\n }\n const exponentStart = index;\n while (index < sql.length && /\\d/u.test(sql[index])) {\n index += 1;\n }\n if (index === exponentStart) {\n throw new SqlSyntaxError('Invalid numeric exponent', position);\n }\n }\n const text = sql.slice(position, index);\n if (text.length > MAX_NUMBER_LENGTH) {\n throw new SqlSyntaxError(`Numeric literal exceeds ${MAX_NUMBER_LENGTH} characters`, position);\n }\n tokens.push({ kind: 'number', text, position });\n } else if (character === '?') {\n index += 1;\n tokens.push({ kind: 'parameter', text: character, position });\n } else {\n const pair = sql.slice(index, index + 2);\n if (['<=', '>=', '<>', '!='].includes(pair)) {\n index += 2;\n tokens.push({ kind: 'symbol', text: pair, position });\n } else if ('(),;*=<>+-'.includes(character)) {\n index += 1;\n tokens.push({ kind: 'symbol', text: character, position });\n } else {\n throw new SqlSyntaxError(`Unsupported SQL character: ${character}`, position);\n }\n }\n }\n tokens.push({ kind: 'end', text: '', position: sql.length });\n return tokens;\n}\n\nfunction parseNumber(text: string, position: number): number | bigint {\n if (/^[+-]?\\d+$/u.test(text)) {\n const integer = BigInt(text);\n if (integer < SQL_INTEGER_MIN || integer > SQL_INTEGER_MAX) {\n throw new SqlSyntaxError('Integer literal exceeds the signed 64-bit range', position);\n }\n return integer >= BigInt(Number.MIN_SAFE_INTEGER) && integer <= BigInt(Number.MAX_SAFE_INTEGER)\n ? Number(integer)\n : integer;\n }\n const value = Number(text);\n if (!Number.isFinite(value) || (Number.isInteger(value) && !Number.isSafeInteger(value))) {\n throw new SqlSyntaxError('REAL literal must be finite; use integer notation for large integers', position);\n }\n const [mantissa, exponentText = '0'] = text.toLowerCase().split('e');\n const digits = mantissa.replace(/[+.-]/gu, '');\n const nonzero = /[1-9]/u.test(digits);\n if (value === 0 && nonzero) {\n throw new SqlSyntaxError('REAL literal underflows to zero', position);\n }\n if (Number.isInteger(value) && nonzero) {\n const fractionLength = mantissa.includes('.') ? mantissa.length - mantissa.indexOf('.') - 1 : 0;\n const trailingZeros = digits.length - digits.replace(/0+$/u, '').length;\n if (Number(exponentText) - fractionLength + trailingZeros < 0) {\n throw new SqlSyntaxError('REAL literal loses its fractional part', position);\n }\n }\n return value;\n}\n\nfunction hasValidUnicode(value: string): boolean {\n for (const character of value) {\n const codePoint = character.codePointAt(0) as number;\n if (codePoint >= 0xd800 && codePoint <= 0xdfff) {\n return false;\n }\n }\n return true;\n}\n\nfunction hasControlCharacters(value: string): boolean {\n for (const character of value) {\n const codePoint = character.codePointAt(0) as number;\n if (codePoint < 0x20 || codePoint === 0x7f) {\n return true;\n }\n }\n return false;\n}\n","import { indexKey, jsonDecode, jsonEncode, u64Key, utf8Encode } from './codec';\nimport { ConstraintError, SerializationError, StoreNotFoundError } from './errors';\nimport { normalizeIndexDefinitions, serializeNormalizedIndexDefinitions, type NormalizedIndexDef } from './indexing';\nimport { bindSqlParameters, parseSql, resolveSqlValue } from './sql-parser';\nimport type {\n SqlColumnDefinition,\n SqlExpression,\n SqlOrderBy,\n SqlStatement,\n SqlValue,\n SqlValueExpression\n} from './sql-types';\nimport type { DB, IndexDef, Range, ScanItem, Transaction } from './types';\n\nconst CATALOG = '_moyodb_sql_catalog';\nconst OWNER_KEY = Uint8Array.of(0);\nconst OWNER = { format: 'moyodb.sql', version: 1 };\nconst TABLE_OWNER_KEY = Uint8Array.of(255);\nconst TABLE_OWNER_FIELD = '\\u0000moyodb.sql.table';\nconst INTEGER_MIN = -(1n << 63n);\nconst INTEGER_MAX = (1n << 63n) - 1n;\nconst ROW_ID_MAX = (1n << 64n) - 1n;\nconst COLUMN_TYPES = new Set(['INTEGER', 'REAL', 'TEXT', 'BOOLEAN', 'BLOB']);\n\nexport type SqlRow = Record<string, SqlValue>;\nexport interface SqlQueryPlan {\n table: string;\n access: 'primary-key-lookup' | 'primary-key-range' | 'index-lookup' | 'index-range' | 'table-scan';\n column?: string;\n index?: string;\n sort: 'none' | 'memory';\n reason: string;\n}\nexport interface SqlResult {\n rows: SqlRow[];\n rowsAffected: number;\n plan?: SqlQueryPlan;\n}\nexport interface SqlClientOptions {\n indexes?: IndexDef[];\n}\nexport interface SqlClient {\n execute(sql: string, parameters?: readonly unknown[]): Promise<SqlResult>;\n query(sql: string, parameters?: readonly unknown[]): Promise<SqlRow[]>;\n explain(sql: string, parameters?: readonly unknown[]): Promise<SqlQueryPlan>;\n}\nexport class SqlSchemaError extends Error {\n constructor(message: string, options?: ErrorOptions) {\n super(message, options);\n this.name = 'SqlSchemaError';\n }\n}\nexport class SqlTypeError extends TypeError {\n constructor(message: string) {\n super(message);\n this.name = 'SqlTypeError';\n }\n}\ninterface TableSchema {\n version: 1;\n table: string;\n columns: SqlColumnDefinition[];\n nextRowId: string;\n}\ninterface StoredRow {\n key: Uint8Array;\n row: SqlRow;\n}\ninterface AccessPlan {\n public: SqlQueryPlan;\n key?: Uint8Array;\n range?: Range;\n empty?: boolean;\n}\ntype Comparison = Extract<SqlExpression, { kind: 'comparison' }>;\ntype Truth = boolean | null;\n\nexport function createSqlClient(db: DB, options: SqlClientOptions = {}): SqlClient {\n const expectedIndexes = options.indexes === undefined ? null : normalizeIndexDefinitions(options.indexes);\n const run = async (sql: string, parameters: readonly unknown[], explain: boolean): Promise<SqlResult> => {\n const parsed = parseSql(sql);\n const bound = bindSqlParameters(parsed, parameters);\n const statement = parsed.statement;\n if (explain && !isRowStatement(statement)) {\n throw new SqlSchemaError('EXPLAIN requires SELECT, UPDATE, or DELETE');\n }\n const tx = await db.begin(statement.kind === 'select' || explain ? 'readonly' : 'readwrite');\n let finished = false;\n try {\n const indexes = normalizeIndexDefinitions((await tx.listIndexes?.()) ?? []);\n if (\n expectedIndexes &&\n serializeNormalizedIndexDefinitions(expectedIndexes) !== serializeNormalizedIndexDefinitions(indexes)\n ) {\n throw new SqlSchemaError('SQL index definitions do not match the transaction catalog');\n }\n const result = await executeStatement(tx, statement, bound, indexes, explain);\n // Finalization closes the SDK transaction even when it fails.\n finished = true;\n if (tx.mode === 'readwrite') {\n await tx.commit();\n } else {\n await tx.rollback();\n }\n return result;\n } catch (error) {\n if (!finished) {\n try {\n await tx.rollback();\n } catch (rollbackError) {\n throw new AggregateError([error, rollbackError], 'SQL statement and rollback failed', {\n cause: rollbackError\n });\n }\n }\n throw error;\n }\n };\n return {\n execute: (sql, parameters = []) => run(sql, parameters, false),\n async query(sql, parameters = []) {\n if (parseSql(sql).statement.kind !== 'select') {\n throw new SqlSchemaError('query() requires SELECT');\n }\n return (await run(sql, parameters, false)).rows;\n },\n async explain(sql, parameters = []) {\n const result = await run(sql, parameters, true);\n if (!result.plan) {\n throw new SqlSchemaError('statement has no query plan');\n }\n return result.plan;\n }\n };\n}\n\nasync function executeStatement(\n tx: Transaction,\n statement: SqlStatement,\n parameters: SqlValue[],\n indexes: NormalizedIndexDef[],\n explain: boolean\n): Promise<SqlResult> {\n assertTableName(statement.table);\n const catalogExists = await readCatalog(tx);\n const schema = catalogExists ? await readSchema(tx, statement.table) : null;\n if (schema) await assertTableOwnership(tx, schema);\n if (statement.kind === 'createTable') {\n if (schema) {\n if (statement.ifNotExists) return { rows: [], rowsAffected: 0 };\n throw new SqlSchemaError(`table already exists: ${statement.table}`);\n }\n const created: TableSchema = {\n version: 1,\n table: statement.table,\n columns: statement.columns,\n nextRowId: '1'\n };\n validateSchema(created, statement.table);\n if (!catalogExists) {\n await tx.createStore(CATALOG);\n await tx.put(CATALOG, OWNER_KEY, jsonEncode(OWNER));\n }\n await tx.createStore(statement.table);\n await tx.put(statement.table, TABLE_OWNER_KEY, tableOwnerValue(created));\n await tx.put(CATALOG, schemaKey(statement.table), jsonEncode(created));\n return { rows: [], rowsAffected: 0 };\n }\n if (!schema) {\n if (statement.kind === 'dropTable' && statement.ifExists) return { rows: [], rowsAffected: 0 };\n throw new SqlSchemaError(`table does not exist: ${statement.table}`);\n }\n if (statement.kind === 'dropTable') {\n await tx.dropStore(statement.table);\n await tx.delete(CATALOG, schemaKey(statement.table));\n return { rows: [], rowsAffected: 0 };\n }\n if (statement.kind === 'insert') {\n return insertRows(tx, schema, statement, parameters);\n }\n validateWhere(schema, statement.where, parameters);\n if (statement.kind === 'select') {\n validateColumnList(schema, statement.columns);\n for (const order of statement.orderBy) getColumn(schema, order.column);\n }\n if (statement.kind === 'update') {\n validateColumnList(\n schema,\n statement.assignments.map((assignment) => assignment.column)\n );\n for (const assignment of statement.assignments) {\n normalizeValue(getColumn(schema, assignment.column), resolveSqlValue(assignment.value, parameters));\n }\n }\n const orderBy = statement.kind === 'select' ? statement.orderBy : [];\n const plan = planAccess(schema, statement.where, orderBy, parameters, indexes);\n const limit = statement.kind === 'select' ? resolveCount(statement.limit, parameters, 'LIMIT') : null;\n const offset = statement.kind === 'select' ? (resolveCount(statement.offset, parameters, 'OFFSET') ?? 0) : 0;\n if (explain) return { rows: [], rowsAffected: 0, plan: plan.public };\n const candidates = limit === 0 ? [] : await readRows(tx, schema, plan);\n const rows = candidates.filter(\n ({ row }) => !statement.where || evaluateWhere(row, statement.where, parameters) === true\n );\n if (statement.kind === 'select') {\n if (orderBy.length) rows.sort((left, right) => compareRows(left, right, orderBy));\n const selected = rows.slice(offset, limit === null ? undefined : offset + limit);\n return {\n rows: selected.map(({ row }) =>\n projectRow(row, statement.columns ?? schema.columns.map((column) => column.name))\n ),\n rowsAffected: 0,\n plan: plan.public\n };\n }\n if (statement.kind === 'delete') {\n await tx.deleteMany(\n schema.table,\n rows.map(({ key }) => key)\n );\n return { rows: [], rowsAffected: rows.length, plan: plan.public };\n }\n const updates = rows.map(({ key, row }) => {\n const updated = { ...row };\n for (const assignment of statement.assignments) {\n updated[assignment.column] = normalizeValue(\n getColumn(schema, assignment.column),\n resolveSqlValue(assignment.value, parameters)\n );\n }\n const primary = primaryColumn(schema);\n return { oldKey: key, key: primary ? primaryKey(primary, updated[primary.name]) : key, row: updated };\n });\n const destinations = new Set<string>();\n const oldKeys = new Set(rows.map(({ key }) => bytesIdentity(key)));\n for (const update of updates) {\n const identity = bytesIdentity(update.key);\n if (destinations.has(identity)) throw new ConstraintError(`duplicate primary key in ${schema.table}`);\n destinations.add(identity);\n if (!oldKeys.has(identity) && (await tx.has(schema.table, update.key))) {\n throw new ConstraintError(`duplicate primary key in ${schema.table}`);\n }\n }\n await tx.deleteMany(\n schema.table,\n updates.map(({ oldKey }) => oldKey)\n );\n for (const update of updates) await tx.put(schema.table, update.key, encodeRow(schema, update.row));\n return { rows: [], rowsAffected: updates.length, plan: plan.public };\n}\n\nasync function readCatalog(tx: Transaction): Promise<boolean> {\n let value: Uint8Array | null;\n try {\n value = await tx.get(CATALOG, OWNER_KEY);\n } catch (error) {\n if (error instanceof StoreNotFoundError || (error instanceof Error && error.name === 'StoreNotFoundError'))\n return false;\n throw error;\n }\n if (!value) throw new SqlSchemaError(`SQL catalog store is not owned by SQL: ${CATALOG}`);\n const owner: unknown = decodeJson(value);\n if (!isRecord(owner) || owner.format !== OWNER.format || owner.version !== OWNER.version) {\n throw new SqlSchemaError('invalid SQL catalog metadata');\n }\n return true;\n}\n\nasync function readSchema(tx: Transaction, table: string): Promise<TableSchema | null> {\n const value = await tx.get(CATALOG, schemaKey(table));\n if (!value) return null;\n const schema: unknown = decodeJson(value);\n validateSchema(schema, table);\n return schema;\n}\n\nasync function assertTableOwnership(tx: Transaction, schema: TableSchema): Promise<void> {\n let owner: Uint8Array | null;\n try {\n owner = await tx.get(schema.table, TABLE_OWNER_KEY);\n } catch (error) {\n if (error instanceof StoreNotFoundError || (error instanceof Error && error.name === 'StoreNotFoundError')) {\n throw new SqlSchemaError(`SQL table store is missing: ${schema.table}`, { cause: error });\n }\n throw error;\n }\n if (!owner || compareBytes(owner, tableOwnerValue(schema)) !== 0) {\n throw new SqlSchemaError(`SQL table ownership does not match its catalog: ${schema.table}`);\n }\n}\n\nfunction tableOwnerValue(schema: TableSchema): Uint8Array {\n return jsonEncode({\n [TABLE_OWNER_FIELD]: JSON.stringify({\n format: 'moyodb.sql.table',\n version: schema.version,\n table: schema.table,\n columns: schema.columns\n })\n });\n}\n\nfunction validateSchema(value: unknown, table: string): asserts value is TableSchema {\n if (\n !isRecord(value) ||\n value.version !== 1 ||\n value.table !== table ||\n !Array.isArray(value.columns) ||\n !value.columns.length ||\n typeof value.nextRowId !== 'string' ||\n value.nextRowId.length > 20 ||\n !/^[1-9]\\d*$/u.test(value.nextRowId) ||\n BigInt(value.nextRowId) > ROW_ID_MAX + 1n\n ) {\n throw new SqlSchemaError(`invalid schema metadata for ${table}`);\n }\n const names = new Set<string>();\n let primaries = 0;\n for (const candidate of value.columns as unknown[]) {\n if (\n !isRecord(candidate) ||\n typeof candidate.name !== 'string' ||\n !candidate.name.length ||\n typeof candidate.type !== 'string' ||\n !COLUMN_TYPES.has(candidate.type) ||\n typeof candidate.primaryKey !== 'boolean' ||\n typeof candidate.nullable !== 'boolean' ||\n names.has(candidate.name) ||\n (candidate.primaryKey && candidate.nullable)\n ) {\n throw new SqlSchemaError(`invalid column metadata for ${table}`);\n }\n names.add(candidate.name);\n if (candidate.primaryKey) primaries += 1;\n }\n if (primaries > 1) throw new SqlSchemaError(`multiple primary keys in ${table}`);\n}\n\nasync function insertRows(\n tx: Transaction,\n schema: TableSchema,\n statement: Extract<SqlStatement, { kind: 'insert' }>,\n parameters: SqlValue[]\n): Promise<SqlResult> {\n const columns = statement.columns ?? schema.columns.map((column) => column.name);\n validateColumnList(schema, columns);\n const primary = primaryColumn(schema);\n let nextRowId = BigInt(schema.nextRowId);\n const entries: Array<[Uint8Array, Uint8Array]> = [];\n const keys = new Set<string>();\n for (const values of statement.rows) {\n if (values.length !== columns.length) throw new SqlSchemaError('INSERT column count does not match VALUES');\n const row = Object.create(null) as SqlRow;\n for (const column of schema.columns) row[column.name] = null;\n values.forEach((expression, index) => {\n row[columns[index]] = resolveSqlValue(expression, parameters);\n });\n for (const column of schema.columns) row[column.name] = normalizeValue(column, row[column.name]);\n if (!primary && nextRowId > ROW_ID_MAX)\n throw new ConstraintError(`row identifier space exhausted in ${schema.table}`);\n const key = primary ? primaryKey(primary, row[primary.name]) : u64Key(nextRowId++);\n const identity = bytesIdentity(key);\n if (keys.has(identity) || (await tx.has(schema.table, key)))\n throw new ConstraintError(`duplicate primary key in ${schema.table}`);\n keys.add(identity);\n entries.push([key, encodeRow(schema, row)]);\n }\n await tx.putMany(schema.table, entries);\n if (!primary) {\n schema.nextRowId = nextRowId.toString();\n await tx.put(CATALOG, schemaKey(schema.table), jsonEncode(schema));\n }\n return { rows: [], rowsAffected: entries.length };\n}\n\nfunction normalizeValue(column: SqlColumnDefinition, value: SqlValue): SqlValue {\n if (value === null) {\n if (!column.nullable) throw new ConstraintError(`column ${column.name} cannot be NULL`);\n return null;\n }\n switch (column.type) {\n case 'INTEGER': {\n if (typeof value !== 'bigint' && (typeof value !== 'number' || !Number.isSafeInteger(value))) break;\n const integer = typeof value === 'bigint' ? value : BigInt(value);\n if (integer < INTEGER_MIN || integer > INTEGER_MAX) break;\n return integer >= BigInt(Number.MIN_SAFE_INTEGER) && integer <= BigInt(Number.MAX_SAFE_INTEGER)\n ? Number(integer)\n : integer;\n }\n case 'REAL':\n if (typeof value === 'number' && Number.isFinite(value)) return Object.is(value, -0) ? 0 : value;\n if (\n typeof value === 'bigint' &&\n value >= BigInt(Number.MIN_SAFE_INTEGER) &&\n value <= BigInt(Number.MAX_SAFE_INTEGER)\n )\n return Number(value);\n break;\n case 'TEXT':\n if (typeof value === 'string') {\n indexKey(value);\n return value;\n }\n break;\n case 'BOOLEAN':\n if (typeof value === 'boolean') return value;\n break;\n case 'BLOB':\n if (value instanceof Uint8Array) return value.slice();\n break;\n }\n throw new SqlTypeError(`column ${column.name} requires ${column.type}`);\n}\n\nfunction primaryKey(column: SqlColumnDefinition, value: SqlValue): Uint8Array {\n if (value === null) throw new ConstraintError(`primary key ${column.name} cannot be NULL`);\n if (column.type === 'INTEGER') return u64Key(BigInt(value as number | bigint) - INTEGER_MIN);\n if (typeof value === 'bigint') throw new SqlTypeError(`invalid primary key ${column.name}`);\n return indexKey(value);\n}\n\nfunction encodeRow(schema: TableSchema, row: SqlRow): Uint8Array {\n const stored = Object.create(null) as Record<string, unknown>;\n for (const column of schema.columns) stored[column.name] = storedValue(row[column.name]);\n return jsonEncode(stored);\n}\n\nfunction storedValue(value: SqlValue): null | boolean | number | string {\n // Keep native index fields scalar. The table schema restores integers and bytes.\n if (typeof value === 'bigint') return value.toString();\n if (value instanceof Uint8Array) return bytesIdentity(value);\n return value;\n}\n\nfunction decodeRow(schema: TableSchema, item: ScanItem): StoredRow {\n const stored: unknown = decodeJson(item.value);\n if (!isRecord(stored) || Object.keys(stored).length !== schema.columns.length)\n throw new SerializationError(`invalid SQL row in ${schema.table}`);\n const row = Object.create(null) as SqlRow;\n try {\n for (const column of schema.columns) {\n if (!Object.hasOwn(stored, column.name)) throw new Error('missing SQL column');\n let value = stored[column.name];\n if (column.type === 'INTEGER' && typeof value === 'string') {\n if (value.length > 20 || !/^-?(?:0|[1-9]\\d*)$/u.test(value)) throw new Error('invalid stored integer');\n value = BigInt(value);\n } else if (column.type === 'BLOB' && typeof value === 'string') {\n if (value.length % 2 || !/^[0-9a-f]*$/u.test(value)) throw new Error('invalid stored blob');\n value = Uint8Array.from(value.match(/.{2}/gu) ?? [], (byte) => Number.parseInt(byte, 16));\n }\n if (\n value !== null &&\n typeof value !== 'boolean' &&\n typeof value !== 'number' &&\n typeof value !== 'string' &&\n typeof value !== 'bigint' &&\n !(value instanceof Uint8Array)\n )\n throw new Error('invalid stored value');\n row[column.name] = normalizeValue(column, value);\n }\n const primary = primaryColumn(schema);\n if (primary && compareBytes(primaryKey(primary, row[primary.name]), item.key) !== 0)\n throw new Error('SQL row primary key differs from storage key');\n } catch (error) {\n throw new SerializationError(\n `invalid SQL row in ${schema.table}: ${error instanceof Error ? error.message : 'invalid value'}`\n );\n }\n return { key: item.key, row };\n}\n\nfunction validateWhere(schema: TableSchema, expression: SqlExpression | null, parameters: SqlValue[]): void {\n if (!expression) return;\n if ('left' in expression) {\n validateWhere(schema, expression.left, parameters);\n validateWhere(schema, expression.right, parameters);\n return;\n }\n const column = getColumn(schema, expression.column);\n if (expression.kind === 'comparison') {\n const value = resolveSqlValue(expression.value, parameters);\n if (value === null) return;\n if (column.type === 'INTEGER' || column.type === 'REAL') {\n if (typeof value === 'bigint' || (typeof value === 'number' && Number.isFinite(value))) return;\n throw new SqlTypeError(`comparison for ${column.name} requires a numeric value`);\n }\n normalizeValue({ ...column, nullable: true }, value);\n }\n}\n\nfunction evaluateWhere(row: SqlRow, expression: SqlExpression, parameters: SqlValue[]): Truth {\n if ('left' in expression) {\n const left = evaluateWhere(row, expression.left, parameters);\n const right = evaluateWhere(row, expression.right, parameters);\n if (expression.kind === 'and')\n return left === false || right === false ? false : left === null || right === null ? null : true;\n return left === true || right === true ? true : left === null || right === null ? null : false;\n }\n const left = row[expression.column];\n if (expression.kind === 'isNull') return expression.negated ? left !== null : left === null;\n const right = resolveSqlValue(expression.value, parameters);\n if (left === null || right === null) return null;\n const compared = compareValues(left, right);\n switch (expression.operator) {\n case '=':\n return compared === 0;\n case '!=':\n return compared !== 0;\n case '<':\n return compared < 0;\n case '<=':\n return compared <= 0;\n case '>':\n return compared > 0;\n case '>=':\n return compared >= 0;\n }\n}\n\nfunction planAccess(\n schema: TableSchema,\n where: SqlExpression | null,\n orderBy: SqlOrderBy[],\n parameters: SqlValue[],\n indexes: NormalizedIndexDef[]\n): AccessPlan {\n const comparisons = conjunctiveComparisons(where);\n const primary = primaryColumn(schema);\n const candidates: Array<{ column: SqlColumnDefinition; index?: NormalizedIndexDef }> = [];\n if (primary) candidates.push({ column: primary });\n for (const index of indexes) {\n // Native dotted paths address nested fields. SQL columns are flat properties.\n if (\n index.store === schema.table &&\n !index.compound &&\n index.keyPath.length === 1 &&\n !index.keyPath[0].includes('.')\n ) {\n const column = schema.columns.find((entry) => entry.name === index.keyPath[0]);\n if (column) candidates.push({ column, index });\n }\n }\n for (const equalityOnly of [true, false]) {\n for (const candidate of candidates) {\n const selected = comparisons.filter(\n (entry) =>\n entry.column === candidate.column.name &&\n (equalityOnly ? entry.operator === '=' : ['<', '<=', '>', '>='].includes(entry.operator))\n );\n let key: Uint8Array | undefined;\n const range: Range = {};\n for (const comparison of selected) {\n const value = resolveSqlValue(comparison.value, parameters);\n const encoded = planKey(candidate.column, value, Boolean(candidate.index), equalityOnly);\n if (!encoded) continue;\n if (equalityOnly) {\n key = encoded;\n break;\n }\n setRangeBound(range, comparison.operator, encoded);\n }\n if (!key && !Object.keys(range).length) continue;\n const access: SqlQueryPlan['access'] = candidate.index\n ? equalityOnly\n ? 'index-lookup'\n : 'index-range'\n : equalityOnly\n ? 'primary-key-lookup'\n : 'primary-key-range';\n return {\n public: {\n table: schema.table,\n access,\n column: candidate.column.name,\n ...(candidate.index ? { index: candidate.index.name } : {}),\n sort: orderBy.length ? 'memory' : 'none',\n reason: `use ${candidate.index ? `index ${candidate.index.name}` : 'primary key'} for ${equalityOnly ? 'equality' : 'range'}; apply remaining predicates after lookup`\n },\n key,\n range,\n empty: !key && emptyRange(range)\n };\n }\n }\n return {\n public: {\n table: schema.table,\n access: 'table-scan',\n sort: orderBy.length ? 'memory' : 'none',\n reason: 'no supported primary key or index bound; filter table rows'\n }\n };\n}\n\nfunction planKey(\n column: SqlColumnDefinition,\n value: SqlValue,\n secondary: boolean,\n equality: boolean\n): Uint8Array | null {\n if (value === null) return null;\n if (column.type === 'INTEGER') {\n if (typeof value !== 'bigint' && (typeof value !== 'number' || !Number.isSafeInteger(value))) return null;\n if (secondary && !equality) return null;\n const normalized = normalizeValue({ ...column, nullable: true }, value);\n return secondary ? indexKey(storedValue(normalized)) : primaryKey(column, normalized);\n }\n if (\n column.type === 'REAL' &&\n typeof value === 'bigint' &&\n (value < BigInt(Number.MIN_SAFE_INTEGER) || value > BigInt(Number.MAX_SAFE_INTEGER))\n )\n return null;\n const normalized = normalizeValue({ ...column, nullable: true }, value);\n return secondary ? indexKey(storedValue(normalized)) : primaryKey(column, normalized);\n}\n\nfunction conjunctiveComparisons(where: SqlExpression | null): Comparison[] {\n if (!where) return [];\n if (where.kind === 'comparison') return [where];\n if (where.kind === 'and') return [...conjunctiveComparisons(where.left), ...conjunctiveComparisons(where.right)];\n return [];\n}\n\nfunction setRangeBound(range: Range, operator: Comparison['operator'], key: Uint8Array): void {\n if (operator === '>' || operator === '>=') {\n const current = range.gt ?? range.gte;\n const compared = current ? compareBytes(key, current) : 1;\n if (compared > 0 || (compared === 0 && operator === '>')) {\n delete range.gt;\n delete range.gte;\n if (operator === '>') range.gt = key;\n else range.gte = key;\n }\n } else if (operator === '<' || operator === '<=') {\n const current = range.lt ?? range.lte;\n const compared = current ? compareBytes(key, current) : -1;\n if (compared < 0 || (compared === 0 && operator === '<')) {\n delete range.lt;\n delete range.lte;\n if (operator === '<') range.lt = key;\n else range.lte = key;\n }\n }\n}\n\nfunction emptyRange(range: Range): boolean {\n const lower = range.gt ?? range.gte;\n const upper = range.lt ?? range.lte;\n if (!lower || !upper) return false;\n const compared = compareBytes(lower, upper);\n return compared > 0 || (compared === 0 && (Boolean(range.gt) || Boolean(range.lt)));\n}\n\nasync function readRows(tx: Transaction, schema: TableSchema, plan: AccessPlan): Promise<StoredRow[]> {\n if (plan.empty) return [];\n let items: ScanItem[];\n if (plan.public.index) {\n items = [];\n const range = plan.key ? { gte: plan.key, lte: plan.key } : plan.range;\n for await (const [key, value] of tx.scanByIndex(schema.table, plan.public.index, range))\n items.push({ key, value });\n } else if (plan.key) {\n const value = await tx.get(schema.table, plan.key);\n items = value ? [{ key: plan.key, value }] : [];\n } else {\n items = await tx.scan(schema.table, plan.range);\n }\n return items\n .filter(({ key }) => key.length !== 1 || key[0] !== TABLE_OWNER_KEY[0])\n .map((item) => decodeRow(schema, item));\n}\n\nfunction compareRows(left: StoredRow, right: StoredRow, orders: SqlOrderBy[]): number {\n for (const order of orders) {\n const compared = compareValues(left.row[order.column], right.row[order.column]);\n if (compared) return order.direction === 'desc' ? -compared : compared;\n }\n return compareBytes(left.key, right.key);\n}\n\nfunction compareValues(left: SqlValue, right: SqlValue): number {\n if (left === null) return right === null ? 0 : -1;\n if (right === null) return 1;\n if (\n (typeof left === 'number' || typeof left === 'bigint') &&\n (typeof right === 'number' || typeof right === 'bigint')\n )\n return left < right ? -1 : left > right ? 1 : 0;\n if (typeof left === 'string' && typeof right === 'string') return compareBytes(indexKey(left), indexKey(right));\n if (typeof left === 'boolean' && typeof right === 'boolean') return Number(left) - Number(right);\n if (left instanceof Uint8Array && right instanceof Uint8Array) return compareBytes(left, right);\n throw new SqlTypeError('comparison values have different SQL types');\n}\n\nfunction resolveCount(expression: SqlValueExpression | null, parameters: SqlValue[], clause: string): number | null {\n if (!expression) return null;\n const value = resolveSqlValue(expression, parameters);\n if (typeof value !== 'number' || !Number.isSafeInteger(value) || value < 0)\n throw new SqlTypeError(`${clause} requires a non-negative safe integer`);\n return value;\n}\n\nfunction projectRow(row: SqlRow, columns: string[]): SqlRow {\n const result: SqlRow = {};\n for (const column of columns)\n Object.defineProperty(result, column, {\n value: row[column] instanceof Uint8Array ? row[column].slice() : row[column],\n enumerable: true,\n configurable: true,\n writable: true\n });\n return result;\n}\n\nfunction validateColumnList(schema: TableSchema, columns: string[] | null): void {\n if (!columns) return;\n const seen = new Set<string>();\n for (const name of columns) {\n getColumn(schema, name);\n if (seen.has(name)) throw new SqlSchemaError(`duplicate column: ${name}`);\n seen.add(name);\n }\n}\n\nfunction getColumn(schema: TableSchema, name: string): SqlColumnDefinition {\n const column = schema.columns.find((entry) => entry.name === name);\n if (!column) throw new SqlSchemaError(`unknown column: ${name}`);\n return column;\n}\n\nfunction primaryColumn(schema: TableSchema): SqlColumnDefinition | undefined {\n return schema.columns.find((column) => column.primaryKey);\n}\nfunction schemaKey(table: string): Uint8Array {\n return utf8Encode(`table:${table}`);\n}\nfunction assertTableName(table: string): void {\n if (table === CATALOG || table.startsWith('__browserdb:'))\n throw new SqlSchemaError(`reserved SQL table name: ${table}`);\n}\nfunction isRowStatement(statement: SqlStatement): boolean {\n return statement.kind === 'select' || statement.kind === 'update' || statement.kind === 'delete';\n}\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return value !== null && typeof value === 'object' && !Array.isArray(value);\n}\nfunction decodeJson(value: Uint8Array): unknown {\n try {\n return jsonDecode<unknown>(value);\n } catch {\n throw new SerializationError('invalid SQL JSON data');\n }\n}\nfunction bytesIdentity(bytes: Uint8Array): string {\n return Array.from(bytes, (byte) => byte.toString(16).padStart(2, '0')).join('');\n}\nfunction compareBytes(left: Uint8Array, right: Uint8Array): number {\n for (let index = 0; index < Math.min(left.length, right.length); index += 1)\n if (left[index] !== right[index]) return left[index] - right[index];\n return left.length - right.length;\n}\n","import type {\n BatchOp,\n ChangeFeed,\n ChangeFeedOptions,\n CompactionResult,\n CreateStoreOptions,\n DB,\n DbSubscriptionCallback,\n DebugFailpoint,\n ExportSnapshotOptions,\n IndexDef,\n MigrateHook,\n OpenOptions,\n PutOptions,\n Range,\n ScanItem,\n StorageInfo,\n Transaction,\n TxId,\n TxMode,\n Unsubscribe\n} from './types';\nimport {\n acquireDbWorker,\n deleteDbByName,\n destroyDbWorker,\n invalidateTransactions,\n releaseDbWorker,\n subscribeHandleInvalidated,\n subscribeTransactionsInvalidated,\n unsafeDebugCrashWorker as crashWorkerByName,\n type RegistryEntry\n} from './registry';\nimport {\n DatabaseBusyError,\n DatabaseClosedError,\n InvalidOpenOptionsError,\n normalizeError,\n TransactionClosedError,\n UnsupportedPlatformError,\n VersionError\n} from './errors';\nimport {\n assertPublicStoreName,\n normalizeIndexDefinitions,\n serializeNormalizedIndexDefinitions,\n toPublicIndexDefinitions,\n type NormalizedIndexDef\n} from './indexing';\nimport { SubscriptionHub } from './subscriptions';\nimport { compareStringsByCodeUnit, withTimeout } from './internal';\nimport type { AutocommitCommand, IndexScanPage } from './worker-api';\nimport type { AutocommitArgs, WorkerCommandResult } from './worker-protocol';\n\nconst INDEX_SCAN_PAGE_ROWS = 256;\n\nasync function callProxy<T>(fn: () => Promise<T>): Promise<T> {\n try {\n return await fn();\n } catch (error) {\n throw normalizeError(error);\n }\n}\n\nclass TransactionImpl implements Transaction {\n readonly mode: TxMode;\n #entry: RegistryEntry;\n #txId: number;\n #closed = false;\n #onClose: () => void;\n constructor(entry: RegistryEntry, txId: number, mode: TxMode, onClose: () => void) {\n this.#entry = entry;\n this.#txId = txId;\n this.mode = mode;\n this.#onClose = onClose;\n }\n async listIndexes(): Promise<IndexDef[]> {\n this.#ensureOpen();\n return callProxy(() => this.#entry.proxy.getIndexes(this.#txId));\n }\n async get(store: string, key: Uint8Array): Promise<Uint8Array | null> {\n this.#ensureOpen();\n assertPublicStoreName(store);\n return callProxy(() => this.#entry.proxy.get(this.#txId, store, key));\n }\n async getMany(store: string, keys: Array<Uint8Array>): Promise<Array<Uint8Array | null>> {\n this.#ensureOpen();\n assertPublicStoreName(store);\n return callProxy(() => this.#entry.proxy.getMany(this.#txId, store, keys));\n }\n async has(store: string, key: Uint8Array): Promise<boolean> {\n this.#ensureOpen();\n assertPublicStoreName(store);\n return callProxy(() => this.#entry.proxy.has(this.#txId, store, key));\n }\n async put(store: string, key: Uint8Array, value: Uint8Array, options: PutOptions = {}): Promise<void> {\n this.#ensureOpen();\n assertPublicStoreName(store);\n return callProxy(() => this.#entry.proxy.put(this.#txId, store, key, value, normalizePutOptions(options)));\n }\n async putMany(store: string, entries: Array<[Uint8Array, Uint8Array]>, options: PutOptions = {}): Promise<void> {\n this.#ensureOpen();\n assertPublicStoreName(store);\n return callProxy(() => this.#entry.proxy.putMany(this.#txId, store, entries, normalizePutOptions(options)));\n }\n async delete(store: string, key: Uint8Array): Promise<boolean> {\n this.#ensureOpen();\n assertPublicStoreName(store);\n return callProxy(() => this.#entry.proxy.delete(this.#txId, store, key));\n }\n async deleteMany(store: string, keys: Array<Uint8Array>): Promise<void> {\n this.#ensureOpen();\n assertPublicStoreName(store);\n return callProxy(() => this.#entry.proxy.deleteMany(this.#txId, store, keys));\n }\n async applyBatch(store: string, ops: Array<BatchOp>): Promise<void> {\n this.#ensureOpen();\n assertPublicStoreName(store);\n return callProxy(() => this.#entry.proxy.applyBatch(this.#txId, store, ops));\n }\n async scan(store: string, range: Range = {}): Promise<ScanItem[]> {\n this.#ensureOpen();\n assertPublicStoreName(store);\n return callProxy(() => this.#entry.proxy.scan(this.#txId, store, range));\n }\n async getByIndex(store: string, indexName: string, key: Uint8Array): Promise<Uint8Array | null> {\n this.#ensureOpen();\n assertPublicStoreName(store);\n return callProxy(() => this.#entry.proxy.getByIndex(this.#txId, store, indexName, key));\n }\n async *scanByIndex(store: string, indexName: string, range: Range = {}): AsyncIterable<[Uint8Array, Uint8Array]> {\n this.#ensureOpen();\n assertPublicStoreName(store);\n let remaining = range.limit ?? Number.POSITIVE_INFINITY;\n let cursor: Uint8Array | null = null;\n while (remaining > 0) {\n this.#ensureOpen();\n const pageLimit = Math.min(remaining, INDEX_SCAN_PAGE_ROWS);\n const resumeAfter: Uint8Array | null = cursor;\n const page: IndexScanPage = await callProxy(() =>\n this.#entry.proxy.scanByIndexPage(this.#txId, store, indexName, range, resumeAfter, pageLimit)\n );\n for (const row of page.rows) {\n yield [row.key, row.value];\n }\n remaining -= page.rows.length;\n if (page.cursor === null) {\n return;\n }\n cursor = page.cursor;\n }\n }\n async createStore(name: string, options: CreateStoreOptions = {}): Promise<void> {\n this.#ensureOpen();\n assertPublicStoreName(name);\n return callProxy(() => this.#entry.proxy.createStore(this.#txId, name, normalizeCreateStoreOptions(options)));\n }\n async dropStore(name: string): Promise<void> {\n this.#ensureOpen();\n assertPublicStoreName(name);\n return callProxy(() => this.#entry.proxy.dropStore(this.#txId, name));\n }\n async clearStore(name: string): Promise<void> {\n this.#ensureOpen();\n assertPublicStoreName(name);\n return callProxy(() => this.#entry.proxy.clearStore(this.#txId, name));\n }\n async commit(): Promise<void> {\n this.#ensureOpen();\n try {\n await callProxy(() => this.#entry.proxy.commit(this.#txId));\n } finally {\n this.#markClosed();\n }\n }\n async rollback(): Promise<void> {\n this.#ensureOpen();\n try {\n await callProxy(() => this.#entry.proxy.rollback(this.#txId));\n } finally {\n this.#markClosed();\n }\n }\n async rollbackIfOpen(): Promise<void> {\n if (this.#closed) {\n return;\n }\n if (this.#entry.invalidated) {\n this.#markClosed();\n return;\n }\n try {\n await this.#entry.proxy.rollback(this.#txId);\n } catch (error) {\n const normalized = normalizeError(error);\n if (!(normalized instanceof TransactionClosedError)) {\n throw normalized;\n }\n } finally {\n this.#markClosed();\n }\n }\n forceClose(): void {\n this.#markClosed();\n }\n internalId(): number {\n return this.#txId;\n }\n #ensureOpen() {\n if (this.#closed || this.#entry.invalidated) {\n throw new TransactionClosedError();\n }\n }\n #markClosed() {\n if (this.#closed) {\n return;\n }\n this.#closed = true;\n this.#onClose();\n }\n}\nclass DBImpl implements DB {\n #entry: RegistryEntry;\n #closed = false;\n #closePromise: Promise<void> | null = null;\n #transactions = new Set<TransactionImpl>();\n #pendingBegins = new Set<Promise<TransactionImpl>>();\n #transactionGeneration = 0;\n #subscriptions: SubscriptionHub;\n #unsubscribeTxInvalidated: (() => void) | null = null;\n #unsubscribeHandleInvalidated: (() => void) | null = null;\n constructor(entry: RegistryEntry) {\n this.#entry = entry;\n this.#subscriptions = new SubscriptionHub(entry.dbName, entry.channelName);\n this.#unsubscribeTxInvalidated = subscribeTransactionsInvalidated(entry, () => {\n this.#forceCloseTransactions();\n });\n this.#unsubscribeHandleInvalidated = subscribeHandleInvalidated(entry, () => {\n this.#markInvalidated();\n });\n }\n async begin(mode: TxMode = 'readonly'): Promise<Transaction> {\n return this.#beginImpl(mode);\n }\n async runSchemaMigration(\n oldVersion: number,\n newVersion: number,\n migrate: MigrateHook,\n targetIndexes: IndexDef[]\n ): Promise<void> {\n this.#ensureOpen();\n const tx = await this.#beginImpl('readwrite');\n const tracker = new MigrationCatalogTracker();\n const migrationTransaction = new MigrationTransactionImpl(tx, tracker);\n const migrationDb = new MigrationDbImpl(this, migrationTransaction, tracker);\n try {\n await this.#entry.proxy.reconcileIndexes(tx.internalId(), targetIndexes);\n await migrate({\n db: migrationDb,\n oldVersion,\n newVersion,\n transaction: migrationTransaction\n });\n await this.#entry.proxy.setSchemaVersion(tx.internalId(), newVersion);\n await tx.commit();\n } catch (error) {\n try {\n await tx.rollbackIfOpen();\n } catch {}\n throw error;\n }\n }\n async listStores(): Promise<string[]> {\n this.#ensureOpen();\n return callProxy(() => this.#entry.proxy.listStores());\n }\n async listIndexes(): Promise<IndexDef[]> {\n this.#ensureOpen();\n return callProxy(() => this.#entry.proxy.getIndexes());\n }\n async getVersion(): Promise<number> {\n this.#ensureOpen();\n return callProxy(() => this.#entry.proxy.getVersion());\n }\n async changesSince(txid: TxId, options: ChangeFeedOptions = {}): Promise<ChangeFeed> {\n this.#ensureOpen();\n return callProxy(() =>\n this.#entry.proxy.changesSince(normalizeTxId(txid), normalizeChangeFeedOptions(options))\n );\n }\n async #beginImpl(mode: TxMode): Promise<TransactionImpl> {\n this.#ensureOpen();\n const generation = this.#transactionGeneration;\n const pending = callProxy(async () => {\n const txId = await this.#entry.proxy.begin(mode);\n const tx = new TransactionImpl(this.#entry, txId, mode, () => {\n this.#transactions.delete(tx);\n });\n this.#transactions.add(tx);\n if (this.#closed || this.#entry.invalidated) {\n if (this.#entry.invalidated) {\n tx.forceClose();\n }\n throw new DatabaseClosedError();\n }\n if (generation !== this.#transactionGeneration) {\n await tx.rollbackIfOpen();\n throw new TransactionClosedError();\n }\n return tx;\n });\n this.#pendingBegins.add(pending);\n try {\n return await pending;\n } finally {\n this.#pendingBegins.delete(pending);\n }\n }\n async createStore(name: string, options: CreateStoreOptions = {}): Promise<void> {\n assertPublicStoreName(name);\n await this.#autocommit('readwrite', 'createStore', [name, normalizeCreateStoreOptions(options)]);\n }\n async dropStore(name: string): Promise<void> {\n assertPublicStoreName(name);\n await this.#autocommit('readwrite', 'dropStore', [name]);\n }\n async clearStore(name: string): Promise<void> {\n assertPublicStoreName(name);\n await this.#autocommit('readwrite', 'clearStore', [name]);\n }\n async get(store: string, key: Uint8Array): Promise<Uint8Array | null> {\n assertPublicStoreName(store);\n return this.#autocommit('readonly', 'get', [store, key]);\n }\n async getMany(store: string, keys: Array<Uint8Array>): Promise<Array<Uint8Array | null>> {\n assertPublicStoreName(store);\n return this.#autocommit('readonly', 'getMany', [store, keys]);\n }\n async has(store: string, key: Uint8Array): Promise<boolean> {\n assertPublicStoreName(store);\n return this.#autocommit('readonly', 'has', [store, key]);\n }\n async put(store: string, key: Uint8Array, value: Uint8Array, options: PutOptions = {}): Promise<void> {\n assertPublicStoreName(store);\n await this.#autocommit('readwrite', 'put', [store, key, value, normalizePutOptions(options)]);\n }\n async delete(store: string, key: Uint8Array): Promise<boolean> {\n assertPublicStoreName(store);\n return this.#autocommit('readwrite', 'delete', [store, key]);\n }\n async scan(store: string, range: Range = {}): Promise<ScanItem[]> {\n assertPublicStoreName(store);\n return this.#autocommit('readonly', 'scan', [store, range]);\n }\n /** The transaction boundary stays in the worker, so one round trip is enough. */\n async #autocommit<M extends AutocommitCommand>(\n mode: TxMode,\n command: M,\n args: AutocommitArgs<M>\n ): Promise<WorkerCommandResult<M>> {\n this.#ensureOpen();\n return callProxy(() => this.#entry.proxy.autocommit(mode, command, args));\n }\n async exportSnapshot(options: ExportSnapshotOptions = {}): Promise<Uint8Array> {\n this.#ensureOpen();\n return callProxy(async () => {\n const bytes = await this.#entry.proxy.exportSnapshot(normalizeExportSnapshotOptions(options));\n return bytes instanceof Uint8Array ? bytes : new Uint8Array(bytes);\n });\n }\n async importSnapshot(data: Uint8Array): Promise<void> {\n this.#ensureOpen();\n invalidateTransactions(this.#entry);\n return callProxy(() => {\n const bytes = data instanceof Uint8Array ? data : new Uint8Array(data);\n return this.#entry.proxy.importSnapshot(bytes);\n });\n }\n async reset(): Promise<void> {\n this.#ensureOpen();\n invalidateTransactions(this.#entry);\n return callProxy(() => this.#entry.proxy.reset());\n }\n async compact(): Promise<CompactionResult> {\n this.#ensureOpen();\n invalidateTransactions(this.#entry);\n return callProxy(() => this.#entry.proxy.compact());\n }\n async rebuild(): Promise<CompactionResult> {\n this.#ensureOpen();\n invalidateTransactions(this.#entry);\n return callProxy(() => this.#entry.proxy.rebuild());\n }\n async stats() {\n this.#ensureOpen();\n return callProxy(() => this.#entry.proxy.stats());\n }\n async storageInfo(): Promise<StorageInfo> {\n this.#ensureOpen();\n return callProxy(() => this.#entry.proxy.storageInfo());\n }\n async requestPersistence(): Promise<boolean> {\n this.#ensureOpen();\n return callProxy(() => this.#entry.proxy.requestPersistence());\n }\n async destroy(): Promise<void> {\n this.#ensureOpen();\n return callProxy(() => this.#entry.destroy?.() ?? destroyDbWorker(this.#entry));\n }\n async setFailpoint(failpoint: DebugFailpoint): Promise<void> {\n this.#ensureOpen();\n return callProxy(() => this.#entry.proxy.setFailpoint(failpoint));\n }\n subscribe(callback: DbSubscriptionCallback): Unsubscribe;\n subscribe(storeName: string, callback: DbSubscriptionCallback): Unsubscribe;\n subscribe(storeName: string, keyPrefix: Uint8Array, callback: DbSubscriptionCallback): Unsubscribe;\n subscribe(\n arg1: string | DbSubscriptionCallback,\n arg2?: Uint8Array | DbSubscriptionCallback,\n arg3?: DbSubscriptionCallback\n ): Unsubscribe {\n this.#ensureOpen();\n if (typeof arg1 === 'function') {\n return this.#subscriptions.subscribe(arg1);\n }\n if (typeof arg2 === 'function') {\n return this.#subscriptions.subscribe(arg1, arg2);\n }\n if (arg2 instanceof Uint8Array && typeof arg3 === 'function') {\n return this.#subscriptions.subscribe(arg1, arg2, arg3);\n }\n throw new TypeError(\n 'subscribe() expects one of: (callback), (storeName, callback), (storeName, keyPrefix, callback)'\n );\n }\n watch(callback: DbSubscriptionCallback): Unsubscribe;\n watch(storeName: string, callback: DbSubscriptionCallback): Unsubscribe;\n watch(storeName: string, keyPrefix: Uint8Array, callback: DbSubscriptionCallback): Unsubscribe;\n watch(\n arg1: string | DbSubscriptionCallback,\n arg2?: Uint8Array | DbSubscriptionCallback,\n arg3?: DbSubscriptionCallback\n ): Unsubscribe {\n if (typeof arg1 === 'function') {\n return this.subscribe(arg1);\n }\n if (typeof arg2 === 'function') {\n return this.subscribe(arg1, arg2);\n }\n if (arg2 instanceof Uint8Array && typeof arg3 === 'function') {\n return this.subscribe(arg1, arg2, arg3);\n }\n throw new TypeError(\n 'watch() expects one of: (callback), (storeName, callback), (storeName, keyPrefix, callback)'\n );\n }\n close(): Promise<void> {\n if (this.#closePromise !== null) {\n return this.#closePromise;\n }\n if (this.#closed) {\n return Promise.resolve();\n }\n this.#closed = true;\n this.#disposeRegistrySubscriptions();\n this.#subscriptions.close();\n this.#closePromise = this.#finishClose();\n return this.#closePromise;\n }\n async #finishClose(): Promise<void> {\n await Promise.allSettled(Array.from(this.#pendingBegins));\n let rollbackError: Error | null = null;\n const txs = Array.from(this.#transactions);\n if (txs.length > 0) {\n const results = await Promise.allSettled(txs.map((tx) => tx.rollbackIfOpen()));\n for (const result of results) {\n if (result.status === 'rejected' && rollbackError === null) {\n rollbackError = normalizeError(result.reason);\n }\n }\n }\n try {\n await (this.#entry.release?.() ?? releaseDbWorker(this.#entry));\n } catch (error) {\n throw normalizeError(error);\n }\n if (rollbackError) {\n throw rollbackError;\n }\n }\n #disposeRegistrySubscriptions() {\n this.#unsubscribeTxInvalidated?.();\n this.#unsubscribeTxInvalidated = null;\n this.#unsubscribeHandleInvalidated?.();\n this.#unsubscribeHandleInvalidated = null;\n }\n #forceCloseTransactions() {\n this.#transactionGeneration += 1;\n for (const tx of Array.from(this.#transactions)) {\n tx.forceClose();\n }\n }\n #markInvalidated() {\n if (this.#closed) {\n return;\n }\n this.#closed = true;\n this.#disposeRegistrySubscriptions();\n this.#forceCloseTransactions();\n this.#subscriptions.close();\n }\n #ensureOpen() {\n if (this.#closed || this.#entry.invalidated) {\n throw new DatabaseClosedError();\n }\n }\n}\nclass MigrationCatalogTracker {\n #created = new Set<string>();\n #dropped = new Set<string>();\n recordCreate(name: string): void {\n this.#dropped.delete(name);\n this.#created.add(name);\n }\n recordDrop(name: string): void {\n if (this.#created.delete(name)) {\n return;\n }\n this.#dropped.add(name);\n }\n apply(stores: string[]): string[] {\n const visible = new Set(stores);\n for (const name of this.#created) {\n visible.add(name);\n }\n for (const name of this.#dropped) {\n visible.delete(name);\n }\n return Array.from(visible).sort(compareStringsByCodeUnit);\n }\n}\nclass MigrationTransactionImpl implements Transaction {\n #inner: TransactionImpl;\n #tracker: MigrationCatalogTracker;\n constructor(inner: TransactionImpl, tracker: MigrationCatalogTracker) {\n this.#inner = inner;\n this.#tracker = tracker;\n }\n get mode(): TxMode {\n return this.#inner.mode;\n }\n async listIndexes(): Promise<IndexDef[]> {\n return this.#inner.listIndexes();\n }\n async get(store: string, key: Uint8Array): Promise<Uint8Array | null> {\n return this.#inner.get(store, key);\n }\n async getMany(store: string, keys: Array<Uint8Array>): Promise<Array<Uint8Array | null>> {\n return this.#inner.getMany(store, keys);\n }\n async has(store: string, key: Uint8Array): Promise<boolean> {\n return this.#inner.has(store, key);\n }\n async put(store: string, key: Uint8Array, value: Uint8Array, options: PutOptions = {}): Promise<void> {\n await this.#inner.put(store, key, value, options);\n }\n async putMany(store: string, entries: Array<[Uint8Array, Uint8Array]>, options: PutOptions = {}): Promise<void> {\n await this.#inner.putMany(store, entries, options);\n }\n async delete(store: string, key: Uint8Array): Promise<boolean> {\n return this.#inner.delete(store, key);\n }\n async deleteMany(store: string, keys: Array<Uint8Array>): Promise<void> {\n await this.#inner.deleteMany(store, keys);\n }\n async applyBatch(store: string, ops: Array<BatchOp>): Promise<void> {\n await this.#inner.applyBatch(store, ops);\n }\n async scan(store: string, range: Range = {}): Promise<ScanItem[]> {\n return this.#inner.scan(store, range);\n }\n async getByIndex(store: string, indexName: string, key: Uint8Array): Promise<Uint8Array | null> {\n return this.#inner.getByIndex(store, indexName, key);\n }\n scanByIndex(store: string, indexName: string, range: Range = {}): AsyncIterable<[Uint8Array, Uint8Array]> {\n return this.#inner.scanByIndex(store, indexName, range);\n }\n async createStore(name: string, options: CreateStoreOptions = {}): Promise<void> {\n await this.#inner.createStore(name, options);\n this.#tracker.recordCreate(name);\n }\n async dropStore(name: string): Promise<void> {\n await this.#inner.dropStore(name);\n this.#tracker.recordDrop(name);\n }\n async clearStore(name: string): Promise<void> {\n await this.#inner.clearStore(name);\n }\n commit(): Promise<void> {\n return Promise.reject(migrationUnsupportedMethod('transaction.commit'));\n }\n rollback(): Promise<void> {\n return Promise.reject(migrationUnsupportedMethod('transaction.rollback'));\n }\n}\nclass MigrationDbImpl implements DB {\n #db: DBImpl;\n #transaction: MigrationTransactionImpl;\n #tracker: MigrationCatalogTracker;\n constructor(db: DBImpl, transaction: MigrationTransactionImpl, tracker: MigrationCatalogTracker) {\n this.#db = db;\n this.#transaction = transaction;\n this.#tracker = tracker;\n }\n begin(_mode: TxMode = 'readonly'): Promise<Transaction> {\n return Promise.reject(migrationUnsupportedMethod('db.begin'));\n }\n async createStore(name: string, options: CreateStoreOptions = {}): Promise<void> {\n await this.#transaction.createStore(name, options);\n }\n async dropStore(name: string): Promise<void> {\n await this.#transaction.dropStore(name);\n }\n async clearStore(name: string): Promise<void> {\n await this.#transaction.clearStore(name);\n }\n async listStores(): Promise<string[]> {\n return this.#tracker.apply(await this.#db.listStores());\n }\n async listIndexes(): Promise<IndexDef[]> {\n return this.#transaction.listIndexes();\n }\n async getVersion(): Promise<number> {\n return this.#db.getVersion();\n }\n changesSince(_txid: TxId, _options: ChangeFeedOptions = {}): Promise<ChangeFeed> {\n return Promise.reject(migrationUnsupportedMethod('db.changesSince'));\n }\n async get(store: string, key: Uint8Array): Promise<Uint8Array | null> {\n return this.#transaction.get(store, key);\n }\n async getMany(store: string, keys: Array<Uint8Array>): Promise<Array<Uint8Array | null>> {\n return this.#transaction.getMany(store, keys);\n }\n async has(store: string, key: Uint8Array): Promise<boolean> {\n return this.#transaction.has(store, key);\n }\n async put(store: string, key: Uint8Array, value: Uint8Array, options: PutOptions = {}): Promise<void> {\n await this.#transaction.put(store, key, value, options);\n }\n async delete(store: string, key: Uint8Array): Promise<boolean> {\n return this.#transaction.delete(store, key);\n }\n async scan(store: string, range: Range = {}): Promise<ScanItem[]> {\n return this.#transaction.scan(store, range);\n }\n exportSnapshot(_options: ExportSnapshotOptions = {}): Promise<Uint8Array> {\n return Promise.reject(migrationUnsupportedMethod('db.exportSnapshot'));\n }\n importSnapshot(_data: Uint8Array): Promise<void> {\n return Promise.reject(migrationUnsupportedMethod('db.importSnapshot'));\n }\n reset(): Promise<void> {\n return Promise.reject(migrationUnsupportedMethod('db.reset'));\n }\n compact(): Promise<CompactionResult> {\n return Promise.reject(migrationUnsupportedMethod('db.compact'));\n }\n rebuild(): Promise<CompactionResult> {\n return Promise.reject(migrationUnsupportedMethod('db.rebuild'));\n }\n async stats() {\n return this.#db.stats();\n }\n async storageInfo(): Promise<StorageInfo> {\n return this.#db.storageInfo();\n }\n async requestPersistence(): Promise<boolean> {\n return this.#db.requestPersistence();\n }\n close(): Promise<void> {\n return Promise.reject(migrationUnsupportedMethod('db.close'));\n }\n destroy(): Promise<void> {\n return Promise.reject(migrationUnsupportedMethod('db.destroy'));\n }\n setFailpoint(_failpoint: DebugFailpoint): Promise<void> {\n return Promise.reject(migrationUnsupportedMethod('db.setFailpoint'));\n }\n subscribe(callback: DbSubscriptionCallback): Unsubscribe;\n subscribe(storeName: string, callback: DbSubscriptionCallback): Unsubscribe;\n subscribe(storeName: string, keyPrefix: Uint8Array, callback: DbSubscriptionCallback): Unsubscribe;\n subscribe(\n _arg1: string | DbSubscriptionCallback,\n _arg2?: Uint8Array | DbSubscriptionCallback,\n _arg3?: DbSubscriptionCallback\n ): Unsubscribe {\n throw migrationUnsupportedMethod('db.subscribe');\n }\n watch(callback: DbSubscriptionCallback): Unsubscribe;\n watch(storeName: string, callback: DbSubscriptionCallback): Unsubscribe;\n watch(storeName: string, keyPrefix: Uint8Array, callback: DbSubscriptionCallback): Unsubscribe;\n watch(\n _arg1: string | DbSubscriptionCallback,\n _arg2?: Uint8Array | DbSubscriptionCallback,\n _arg3?: DbSubscriptionCallback\n ): Unsubscribe {\n throw migrationUnsupportedMethod('db.watch');\n }\n}\nfunction migrationUnsupportedMethod(method: string): Error {\n const error = new Error(\n `${method}() is not available inside openDB() migrations; use the provided migration transaction and wait for openDB() to resolve`\n );\n error.name = 'InvalidStateError';\n return error;\n}\nfunction normalizeDatabaseName(value: unknown, method: 'openDB' | 'deleteDB' | 'unsafeDebugCrashWorker'): string {\n if (typeof value !== 'string' || value.length === 0) {\n throw new TypeError(`${method}() database name must be a non-empty string`);\n }\n return value;\n}\ntype ErrorFactory = (message: string) => Error;\n\nconst typeError: ErrorFactory = (message) => new TypeError(message);\nconst invalidOpenOptionsError: ErrorFactory = (message) => new InvalidOpenOptionsError(message);\n\nfunction normalizeOptionsObject<T>(options: unknown, message: string, createError: ErrorFactory = typeError): T {\n if (options === undefined) {\n return {} as T;\n }\n if (options === null || typeof options !== 'object' || Array.isArray(options)) {\n throw createError(message);\n }\n return options as T;\n}\n\nfunction normalizeNonNegativeSafeInteger(\n value: unknown,\n message: string,\n createError: ErrorFactory = typeError\n): number {\n if (typeof value !== 'number' || !Number.isSafeInteger(value) || value < 0) {\n throw createError(message);\n }\n return value;\n}\n\nfunction normalizeOptionalNonNegativeSafeInteger(\n value: unknown,\n message: string,\n createError?: ErrorFactory\n): number | undefined {\n return value === undefined ? undefined : normalizeNonNegativeSafeInteger(value, message, createError);\n}\n\nfunction normalizeOpenOptionsInput(options: unknown): OpenOptions {\n return normalizeOptionsObject(options, 'open options must be an object', invalidOpenOptionsError);\n}\nfunction normalizeSchemaVersion(value: unknown): number | undefined {\n return normalizeOptionalNonNegativeSafeInteger(\n value,\n 'version must be a non-negative safe integer',\n invalidOpenOptionsError\n );\n}\nfunction normalizePutOptions(options: unknown): PutOptions {\n const { ttl } = normalizeOptionsObject<{\n ttl?: unknown;\n }>(options, 'put options must be an object');\n const normalizedTtl = normalizeOptionalNonNegativeSafeInteger(ttl, 'ttl must be a non-negative safe integer');\n return normalizedTtl === undefined ? {} : { ttl: normalizedTtl };\n}\nfunction normalizeCompressionOptions<T extends CreateStoreOptions | ExportSnapshotOptions>(\n options: unknown,\n message: string\n): T {\n const { compression } = normalizeOptionsObject<{\n compression?: unknown;\n }>(options, message);\n if (compression === undefined) {\n return {} as T;\n }\n if (compression !== false && compression !== 'gzip' && compression !== 'deflate') {\n throw new TypeError('compression must be \"gzip\", \"deflate\", or false');\n }\n return { compression } as T;\n}\n\nfunction normalizeCreateStoreOptions(options: unknown): CreateStoreOptions {\n return normalizeCompressionOptions(options, 'createStore options must be an object');\n}\n\nfunction normalizeExportSnapshotOptions(options: unknown): ExportSnapshotOptions {\n return normalizeCompressionOptions(options, 'exportSnapshot options must be an object');\n}\nfunction normalizeTxId(value: unknown): TxId {\n return normalizeNonNegativeSafeInteger(value, 'txid must be a non-negative safe integer');\n}\nfunction normalizeChangeFeedOptions(options: unknown): ChangeFeedOptions {\n const { stores, limit } = normalizeOptionsObject<{\n stores?: unknown;\n limit?: unknown;\n }>(options, 'change feed options must be an object');\n const normalized: ChangeFeedOptions = {};\n if (stores !== undefined) {\n if (!Array.isArray(stores) || !stores.every((store): store is string => typeof store === 'string')) {\n throw new TypeError('stores must be an array of strings');\n }\n for (const store of stores) {\n assertPublicStoreName(store);\n }\n normalized.stores = [...stores];\n }\n const normalizedLimit = normalizeOptionalNonNegativeSafeInteger(limit, 'limit must be a non-negative safe integer');\n if (normalizedLimit !== undefined) {\n normalized.limit = normalizedLimit;\n }\n return normalized;\n}\nfunction normalizeMigrateHook(value: unknown): MigrateHook | undefined {\n if (value === undefined) {\n return undefined;\n }\n if (typeof value !== 'function') {\n throw new InvalidOpenOptionsError('migrate must be a function');\n }\n return value as MigrateHook;\n}\nfunction normalizeRequestedIndexes(value: unknown): NormalizedIndexDef[] | undefined {\n if (value === undefined) {\n return undefined;\n }\n return normalizeIndexDefinitions(value);\n}\nfunction indexDefinitionsMatch(\n left: ReadonlyArray<NormalizedIndexDef>,\n right: ReadonlyArray<NormalizedIndexDef>\n): boolean {\n return serializeNormalizedIndexDefinitions(left) === serializeNormalizedIndexDefinitions(right);\n}\nasync function loadNormalizedIndexes(entry: RegistryEntry): Promise<NormalizedIndexDef[]> {\n return normalizeIndexDefinitions(await entry.proxy.getIndexes());\n}\nfunction assertMainThreadCapabilities() {\n if (!globalThis.isSecureContext) {\n throw new UnsupportedPlatformError('moyodb requires a secure context (HTTPS)');\n }\n const nav = globalThis.navigator;\n if (typeof nav?.storage?.getDirectory !== 'function') {\n throw new UnsupportedPlatformError('navigator.storage.getDirectory is unavailable');\n }\n if (typeof globalThis.Worker !== 'function') {\n throw new UnsupportedPlatformError('Worker is unavailable');\n }\n if (typeof globalThis.BroadcastChannel === 'undefined') {\n throw new UnsupportedPlatformError('BroadcastChannel is unavailable');\n }\n}\nasync function requestPersistentStorageOnOpen(options: OpenOptions): Promise<void> {\n const nav = globalThis.navigator;\n if ((options.requestPersistence ?? true) && typeof nav.storage.persist === 'function') {\n await withTimeout(nav.storage.persist(), 1000, false);\n }\n}\nexport async function openDB(name: string, options: OpenOptions = {}): Promise<DB> {\n return openDBWithWorker(name, options, async (dbName, normalizedOptions) => {\n assertMainThreadCapabilities();\n await requestPersistentStorageOnOpen(normalizedOptions);\n return acquireDbWorker(dbName, normalizedOptions);\n });\n}\nexport async function openDBWithWorker(\n name: string,\n options: OpenOptions,\n acquire: (name: string, options: OpenOptions) => Promise<RegistryEntry>\n): Promise<DB> {\n const dbName = normalizeDatabaseName(name, 'openDB');\n const normalizedOptions = normalizeOpenOptionsInput(options);\n const requestedVersion = normalizeSchemaVersion(normalizedOptions.version);\n const migrate = normalizeMigrateHook(normalizedOptions.migrate);\n const requestedIndexes = normalizeRequestedIndexes(normalizedOptions.indexes);\n if (requestedVersion === undefined && migrate !== undefined) {\n throw new InvalidOpenOptionsError('migrate requires version');\n }\n if (requestedVersion === undefined && requestedIndexes !== undefined) {\n throw new InvalidOpenOptionsError('indexes requires version');\n }\n const entry = await acquire(dbName, normalizedOptions);\n const db = new DBImpl(entry);\n try {\n await entry.proxy.acquireMigration?.();\n try {\n if (requestedVersion === undefined) {\n return db;\n }\n const [currentVersion, currentIndexes] = await Promise.all([db.getVersion(), loadNormalizedIndexes(entry)]);\n if (requestedVersion < currentVersion) {\n throw new VersionError(\n `cannot open database ${dbName} at schema version ${requestedVersion}; current schema version is ${currentVersion}`\n );\n }\n if (requestedVersion === currentVersion) {\n if (requestedIndexes !== undefined && !indexDefinitionsMatch(requestedIndexes, currentIndexes)) {\n throw new VersionError(\n `database ${dbName} is already at schema version ${currentVersion}, but the requested index catalog does not match the committed schema`\n );\n }\n return db;\n }\n if (entry.refs > 1) {\n throw new DatabaseBusyError(\n `database ${dbName} is already open in this tab; close existing handles before migrating from version ${currentVersion} to ${requestedVersion}`\n );\n }\n if (!migrate) {\n throw new VersionError(\n `database ${dbName} requires migration from version ${currentVersion} to ${requestedVersion}, but no migrate hook was provided`\n );\n }\n const targetIndexes = requestedIndexes ?? currentIndexes;\n entry.schemaMigrationInProgress = true;\n try {\n await db.runSchemaMigration(\n currentVersion,\n requestedVersion,\n migrate,\n toPublicIndexDefinitions(targetIndexes)\n );\n } finally {\n entry.schemaMigrationInProgress = false;\n }\n return db;\n } finally {\n await entry.proxy.releaseMigration?.();\n }\n } catch (error) {\n try {\n await db.close();\n } catch {}\n throw normalizeError(error);\n }\n}\nexport async function deleteDB(name: string): Promise<void> {\n const dbName = normalizeDatabaseName(name, 'deleteDB');\n assertMainThreadCapabilities();\n await deleteDbByName(dbName);\n}\nexport function unsafeDebugCrashWorker(name: string): boolean {\n const dbName = normalizeDatabaseName(name, 'unsafeDebugCrashWorker');\n return crashWorkerByName(dbName);\n}\nexport * from './codec';\nexport * from './errors';\nexport * from './indexing';\nexport * from './records';\nexport * from './sql';\nexport { SqlSyntaxError } from './sql-parser';\nexport type * from './sql-types';\nexport type * from './types';\n"],"mappings":";AAAA,SAAgB,EAAS,GAAkD;CACvE,OAAyB,OAAO,KAAU,cAAnC;AACX;AAEA,SAAgB,EAAyB,GAAc,GAAuB;CAI1E,OAHI,IAAO,IACA,KAEJ,MAAO;AAClB;AAEA,SAAgB,EAAe,GAAqB,GAAmB,GAAyB;CAC5F,OAAO,IAAI,SAAS,MAAY;EAC5B,IAAM,IAAU,iBAAiB,EAAQ,CAAQ,GAAG,CAAS;EAC7D,EAAQ,MACH,MAAU;GAEP,AADA,aAAa,CAAO,GACpB,EAAQ,CAAK;EACjB,SACM;GAEF,AADA,aAAa,CAAO,GACpB,EAAQ,CAAQ;EACpB,CACJ;CACJ,CAAC;AACL;ACnBA,IAOa,IAAkB,oZAuC/B,GA+BM,oBAAyB,IAAI,IAAY;CAhB3C;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AAG2C,CAAmB;AAElE,SAAgB,EAAoB,GAA4C;CAC5E,OAAO,OAAO,KAAU,YAAY,EAAuB,IAAI,CAAK;AACxE;AASA,IAAM,IAAwB,gCACxB,IAAiC,yCACjC,IAAsB,8BACtB,IAAsB,8BAGtB,IAA4B,oCAC5B,IAAkB,GAClB,IAAe,GACf,IAAU,YAEV,IAAsC,CAAC;AAwFlB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