@moyodb/sdk 1.0.0 → 1.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -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';\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-native getMany output: u32 count | count x u32 length (u32::MAX =\n// missing) | concatenated values, all little-endian. Forwarded without repacking.\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};\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 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\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 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_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 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 // Inner arguments are packed exactly as for the transaction-scoped\n // command; the placeholder transaction id is stripped again.\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 (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 (isPackedBinaryList(keys)) {\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 (isPackedBinaryList(entries)) {\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 (isPackedBatchOps(ops)) {\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 // The remaining command results are protocol scalars, voids, or JSON-like\n // metadata. Avoid a generic deep walk when the result type cannot contain\n // transfer-worthy binary payloads.\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 === 'scanByIndexPage' && isRecord(result)) {\n const rows = isPackedScanRows(result.rows) ? unpackScanRows(result.rows) : result.rows;\n const cursor = result.cursor instanceof Uint8Array ? result.cursor : null;\n return { rows, cursor } as WorkerCommandResult<M>;\n }\n\n if ((command === 'scan' || command === 'scanByIndex') && isPackedScanRows(result)) {\n return unpackScanRows(result);\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\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 = ops[index];\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 WORKER_PROTOCOL_REQUEST,\n WORKER_PROTOCOL_VERSION,\n deserializeWorkerError,\n decodeWorkerResponsePayload,\n isWorkerProtocolReadyMessage,\n isWorkerProtocolResponseMessage,\n prepareWorkerCommandPayload,\n workerProtocolError,\n type AutocommitArgs,\n type WorkerCommand,\n type WorkerCommandArgs,\n type WorkerCommandResult,\n type WorkerProtocolRequestMessage\n} from './worker-protocol';\n\ninterface PendingRequest {\n /** Command whose response format the result is decoded with. */\n command: WorkerCommand;\n resolve: (value: unknown) => void;\n reject: (error: Error) => void;\n timeout: ReturnType<typeof setTimeout> | null;\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\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 await this.ready;\n this.ensureOpen();\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 (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 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 this.readyResolved = true;\n this.readyResolve?.();\n this.readyResolve = null;\n this.readyReject = null;\n return;\n }\n if (!isWorkerProtocolResponseMessage(data)) {\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 if (data.ok) {\n pending.resolve(decodeWorkerResponsePayload(pending.command, data.result));\n return;\n }\n pending.reject(deserializeWorkerError(data.error));\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 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 outcome of a commit could not be confirmed (storage failed at or after\n * the WAL append) or the engine hit an unrecoverable fault. The database\n * rejects further work until it is reopened, which replays durable state.\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 { 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 txInvalidationListeners: Set<() => void>;\n handleInvalidationListeners: Set<() => void>;\n}\nconst registry = new Map<string, RegistryEntry>();\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 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 const existing = registry.get(dbName);\n if (existing) {\n if (existing.invalidated) {\n registry.delete(dbName);\n } else {\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}\nexport async function releaseDbWorker(entry: RegistryEntry): Promise<void> {\n if (entry.invalidated) {\n return;\n }\n const current = registry.get(entry.dbName);\n if (!current) {\n return;\n }\n current.refs -= 1;\n if (current.refs > 0) {\n return;\n }\n registry.delete(entry.dbName);\n try {\n await current.proxy.close();\n } finally {\n current.persistenceBridge.close();\n current.proxy.dispose(new Error('worker was released'));\n current.worker.terminate();\n }\n}\nexport async function destroyDbWorker(entry: RegistryEntry): Promise<void> {\n const current = registry.get(entry.dbName) ?? entry;\n registry.delete(entry.dbName);\n invalidateEntry(current);\n current.refs = 0;\n try {\n await current.proxy.destroy();\n } catch (error) {\n throw normalizeError(error);\n } finally {\n current.persistenceBridge.close();\n current.proxy.dispose(new Error('worker was released'));\n current.worker.terminate();\n }\n}\nexport async function deleteDbByName(dbName: string): Promise<void> {\n const current = registry.get(dbName);\n if (current) {\n await destroyDbWorker(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","import type { Range } from './types';\nconst encoder = new TextEncoder();\nconst decoder = new TextDecoder();\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 = 0xffffffffffffffffn;\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 return utf8Encode(JSON.stringify(value));\n}\nexport function jsonDecode<T>(bytes: Uint8Array): T {\n return JSON.parse(utf8Decode(bytes)) as T;\n}\nexport function u64Key(value: bigint | number): Uint8Array {\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 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 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 = 0xcbf29ce484222325n;\nconst FNV64_PRIME = 0x100000001b3n;\nconst FNV64_MASK = 0xffffffffffffffffn;\n// Legacy SDK internal namespace preserved for storage-format compatibility; do not rename without 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 `${store}\\u0000${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 } catch (error) {\n throw new SerializationError(`invalid persisted index metadata: ${String(error)}`);\n }\n const [def] = normalizeIndexDefinitions([parsed]);\n return def;\n}\nexport function encodeIndexEntryKey(logicalIndexKey: Uint8Array, primaryKey: Uint8Array): Uint8Array {\n return encodeCompoundKeyParts([logicalIndexKey, primaryKey]);\n}\nexport function decodeIndexEntryKey(bytes: Uint8Array): DecodedIndexEntryKey {\n const parts = splitCompoundKey(bytes);\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 const documentValue = decodeIndexedDocument(valueBytes);\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 const payload = utf8Encode(indexDefinitionIdentity(store, 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}\nfunction 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 (!(segment in target)) {\n return MISSING;\n }\n current = Reflect.get(target, segment);\n }\n return current;\n}\nfunction encodeDocumentIndexValue(value: unknown): Uint8Array {\n if (value instanceof Uint8Array) {\n return encodeIndexScalar(value);\n }\n if (value === null || typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') {\n return encodeIndexScalar(value);\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 if (value === null) {\n return 'null';\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 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 #transactions = new Set<TransactionImpl>();\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 return 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 return tx;\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 /** Begin, run and commit (or release) a single operation in one worker round trip. */\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 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 async close(): Promise<void> {\n if (this.#closed) {\n return;\n }\n this.#closed = true;\n this.#disposeRegistrySubscriptions();\n this.#subscriptions.close();\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 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 let keepHandle = false;\n try {\n if (requestedVersion === undefined) {\n keepHandle = true;\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 keepHandle = true;\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 await db.runSchemaMigration(currentVersion, requestedVersion, migrate, toPublicIndexDefinitions(targetIndexes));\n keepHandle = true;\n return db;\n } catch (error) {\n if (!keepHandle) {\n try {\n await db.close();\n } catch {}\n }\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,IAGa,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,KAAsC,CAAC;AA0ElB,IAAI,IAAY,CAAe;AAM1D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B,MAAM,QAAQ,IAAI,CAAC,EAAG,WAAW,GAAG,GAAsB,CAAK,CAAC,CAAC;EAC1G,IAAI,IAAmB,GACnB,MAAM,IAAI,EACN,wBAAwB,EAAO,qBAAqB,EAAiB,8BAA8B,GACvG;EAEJ,IAAI,MAAqB,GAAgB;GACrC,IAAI,MAAqB,KAAA,KAAa,CAAC,GAAsB,GAAkB,CAAc,GACzF,MAAM,IAAI,EACN,YAAY,EAAO,gCAAgC,EAAe,sEACtE;GAGJ,OADA,IAAa,IACN;EACX;EACA,IAAI,EAAM,OAAO,GACb,MAAM,IAAI,EACN,YAAY,EAAO,qFAAqF,EAAe,MAAM,GACjI;EAEJ,IAAI,CAAC,GACD,MAAM,IAAI,EACN,YAAY,EAAO,mCAAmC,EAAe,MAAM,EAAiB,mCAChG;EAEJ,IAAM,IAAgB,KAAoB;EAG1C,OAFA,MAAM,EAAG,mBAAmB,GAAgB,GAAkB,GAAS,EAAyB,CAAa,CAAC,GAC9G,IAAa,IACN;CACX,SAAS,GAAO;EACZ,IAAI,CAAC,GACD,IAAI;GACA,MAAM,EAAG,MAAM;EACnB,QAAQ,CAAC;EAEb,MAAM,EAAe,CAAK;CAC9B;AACJ;AACA,eAAsB,GAAS,GAA6B;CACxD,IAAM,IAAS,EAAsB,GAAM,UAAU;CAErD,AADA,GAA6B,GAC7B,MAAM,GAAe,CAAM;AAC/B;AACA,SAAgB,GAAuB,GAAuB;CAE1D,OAAO,GADQ,EAAsB,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/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,yC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