@moyodb/sdk 1.0.1 → 1.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +111 -28
- package/dist/assets/browser-worker-DBt51gsS.js +4 -0
- package/dist/assets/browser-worker-DBt51gsS.js.map +1 -0
- package/dist/assets/shared-worker-NdniRuEL.js +2 -0
- package/dist/assets/shared-worker-NdniRuEL.js.map +1 -0
- package/dist/browser-worker.d.ts +2 -0
- package/dist/browser-worker.d.ts.map +1 -0
- package/dist/change-events.d.ts +1 -1
- package/dist/chunks/indexing-CKtbpaZn.js +1657 -0
- package/dist/chunks/indexing-CKtbpaZn.js.map +1 -0
- package/dist/codec.d.ts +1 -1
- package/dist/compression.d.ts +16 -2
- package/dist/compression.d.ts.map +1 -1
- package/dist/demo.d.ts +2 -1
- package/dist/demo.d.ts.map +1 -1
- package/dist/engine/README.md +89 -16
- package/dist/engine/moyodb_engine.d.ts +34 -10
- package/dist/engine/moyodb_engine.js +238 -51
- package/dist/engine/moyodb_engine_bg.wasm +0 -0
- package/dist/engine/moyodb_engine_bg.wasm.d.ts +17 -10
- package/dist/engine/package.json +2 -2
- package/dist/errors.d.ts +3 -0
- package/dist/errors.d.ts.map +1 -1
- package/dist/index.d.ts +11 -5
- package/dist/index.d.ts.map +1 -1
- package/dist/indexing.d.ts +1 -1
- package/dist/internal.d.ts +6 -0
- package/dist/internal.d.ts.map +1 -1
- package/dist/moyodb-sdk.js +2362 -640
- package/dist/moyodb-sdk.js.map +1 -1
- package/dist/node-engine.js +2838 -0
- package/dist/node-engine.js.map +1 -0
- package/dist/node-storage.d.mts +16 -0
- package/dist/node-storage.mjs +669 -0
- package/dist/node-worker-client.d.ts +20 -0
- package/dist/node-worker-client.d.ts.map +1 -0
- package/dist/node-worker.mjs +119 -0
- package/dist/node.d.ts +19 -0
- package/dist/node.d.ts.map +1 -0
- package/dist/node.js +3437 -0
- package/dist/node.js.map +1 -0
- package/dist/records.d.ts +75 -0
- package/dist/records.d.ts.map +1 -0
- package/dist/registry.d.ts +12 -4
- package/dist/registry.d.ts.map +1 -1
- package/dist/shared-worker-client.d.ts +28 -0
- package/dist/shared-worker-client.d.ts.map +1 -0
- package/dist/shared-worker-protocol.d.ts +16 -0
- package/dist/shared-worker-protocol.d.ts.map +1 -0
- package/dist/shared-worker.d.ts +33 -0
- package/dist/shared-worker.d.ts.map +1 -0
- package/dist/snappy.d.ts +3 -0
- package/dist/snappy.d.ts.map +1 -0
- package/dist/sql-parser.d.ts +9 -0
- package/dist/sql-parser.d.ts.map +1 -0
- package/dist/sql-types.d.ts +82 -0
- package/dist/sql-types.d.ts.map +1 -0
- package/dist/sql.d.ts +32 -0
- package/dist/sql.d.ts.map +1 -0
- package/dist/subscriptions.d.ts +2 -2
- package/dist/subscriptions.d.ts.map +1 -1
- package/dist/types.d.ts +36 -3
- package/dist/types.d.ts.map +1 -1
- package/dist/worker-api.d.ts +19 -3
- package/dist/worker-api.d.ts.map +1 -1
- package/dist/worker-client.d.ts +30 -6
- package/dist/worker-client.d.ts.map +1 -1
- package/dist/worker-protocol.d.ts +19 -4
- package/dist/worker-protocol.d.ts.map +1 -1
- package/dist/worker-server.d.ts +10 -2
- package/dist/worker-server.d.ts.map +1 -1
- package/dist/worker.d.ts +292 -1
- package/dist/worker.d.ts.map +1 -1
- package/package.json +13 -6
- package/dist/assets/worker-KDc8Khl_.js +0 -4
- package/dist/assets/worker-KDc8Khl_.js.map +0 -1
- package/dist/engine/snippets/moyodb-engine-cff0a0e2441a7a8f/js/opfs_shim.js +0 -513
- /package/dist/engine/snippets/{moyodb-engine-8ebe6af0cc2e81b7 → moyodb-engine-54a406e33b0fb849}/js/opfs_shim.js +0 -0
package/README.md
CHANGED
|
@@ -1,21 +1,40 @@
|
|
|
1
|
-
|
|
1
|
+
<p align="center">
|
|
2
|
+
<img
|
|
3
|
+
width="100%"
|
|
4
|
+
src="https://capsule-render.vercel.app/api?type=waving&height=220&color=0:0B1220,50:1E1B4B,100:4F46E5&text=MoyoDB&fontColor=E2E8F0&fontSize=54&fontAlignY=50"
|
|
5
|
+
alt="Header banner"
|
|
6
|
+
/>
|
|
7
|
+
</p>
|
|
2
8
|
|
|
3
|
-
|
|
9
|
+
<p align="center">
|
|
10
|
+
<img alt="Rust" src="https://img.shields.io/badge/Rust-1E293B?style=for-the-badge" />
|
|
11
|
+
<img alt="WebAssembly" src="https://img.shields.io/badge/WebAssembly-1E293B?style=for-the-badge" />
|
|
12
|
+
<img alt="TypeScript" src="https://img.shields.io/badge/TypeScript-1E293B?style=for-the-badge" />
|
|
13
|
+
<img alt="JavaScript" src="https://img.shields.io/badge/JavaScript-1E293B?style=for-the-badge" />
|
|
14
|
+
<img alt="Lean 4" src="https://img.shields.io/badge/Lean%204-1E293B?style=for-the-badge" />
|
|
15
|
+
<img alt="npm" src="https://img.shields.io/badge/npm-1E293B?style=for-the-badge" />
|
|
16
|
+
</p>
|
|
4
17
|
|
|
5
|
-
|
|
18
|
+
Rust/WASM transactional database for browsers, Node.js, and native Rust applications.
|
|
6
19
|
|
|
7
|
-
|
|
20
|
+
It provides ordered keys, typed records, SQL queries, indexes, snapshots, TTL, and recovery checks. Browser storage uses OPFS; Node.js and native Rust storage use local files. The SDK runs storage operations in a worker.
|
|
8
21
|
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
22
|
+
Version 1.3.0 creates fresh databases with storage format 2. Format 1 databases are rejected before their files are changed; no in-place migration is provided. Self-contained snapshot versions 1–3 can be imported into a fresh format 2 database. The Release 1.0.1 public API, key and index encodings remain covered by historical fixtures. Unknown storage formats fail before modifying durable data.
|
|
23
|
+
|
|
24
|
+
Large values use immutable contiguous `PAY2` extents in the main file. Leaf cells with value kind `External` (3) store a descriptor and an optional prefix. Payload bodies are flushed before their references enter the WAL. B-tree page and WAL record layouts retain `PAG1` and `WAL1`; the manifest's format version distinguishes the new storage contract.
|
|
12
25
|
|
|
13
|
-
|
|
26
|
+
Fresh user and index stores use a 32-byte `BDREV001` value header with expiry and a native record revision. Managed index writes retain the primary record's revision. Matching live revisions let index validation use metadata without reading the document. Raw changes, legacy values and revision mismatches retain document validation. Snapshot export omits physical revisions; import assigns new ones, and compaction preserves them.
|
|
14
27
|
|
|
15
|
-
|
|
28
|
+
New SDK stores use Snappy compression by default for values of at least 1,024 bytes. The compressed record is kept only when it saves at least 10% of the stored bytes. For values of at least 64 KiB, three small samples first check whether compression is likely to save space. This may leave some compressible values raw. Set `compression: false` when creating a store to retain raw values; `gzip` and `deflate` remain available. The maximum decoded value is 8 MiB.
|
|
29
|
+
|
|
30
|
+
## Quick start
|
|
31
|
+
|
|
32
|
+
```bash
|
|
33
|
+
npm install @moyodb/sdk@1.3.0
|
|
34
|
+
```
|
|
16
35
|
|
|
17
36
|
```ts
|
|
18
|
-
import { openDB,
|
|
37
|
+
import { openDB, utf8Decode, utf8Encode } from '@moyodb/sdk';
|
|
19
38
|
|
|
20
39
|
const db = await openDB('app', { requestPersistence: false });
|
|
21
40
|
await db.createStore('kv');
|
|
@@ -23,37 +42,101 @@ await db.put('kv', utf8Encode('hello'), utf8Encode('world'));
|
|
|
23
42
|
|
|
24
43
|
const value = await db.get('kv', utf8Encode('hello'));
|
|
25
44
|
console.log(value ? utf8Decode(value) : null);
|
|
45
|
+
|
|
26
46
|
await db.close();
|
|
27
47
|
```
|
|
28
48
|
|
|
29
|
-
##
|
|
49
|
+
## Node.js and native storage
|
|
50
|
+
|
|
51
|
+
```ts
|
|
52
|
+
import { openNodeDB, utf8Encode, utf8Decode } from '@moyodb/sdk/node';
|
|
30
53
|
|
|
31
|
-
|
|
54
|
+
const db = await openNodeDB('app', { directory: './data' });
|
|
55
|
+
if (!(await db.listStores()).includes('kv')) await db.createStore('kv');
|
|
56
|
+
await db.put('kv', utf8Encode('hello'), utf8Encode('world'));
|
|
57
|
+
console.log(utf8Decode((await db.get('kv', utf8Encode('hello')))!));
|
|
58
|
+
await db.close();
|
|
59
|
+
```
|
|
32
60
|
|
|
33
|
-
|
|
61
|
+
Node.js and `NativeFileBackend::open_db(root, name, create_if_missing)` share `root/stackdb/hex(UTF8 name)`. Database names contain valid Unicode and at most 127 UTF-8 bytes. File flushes use `fsync`; the directory lease excludes competing Node and native owners and releases an abandoned lease only after confirming that its process exited.
|
|
34
62
|
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
npm run build
|
|
63
|
+
## Multiple clients and transactions
|
|
64
|
+
|
|
65
|
+
```ts
|
|
66
|
+
const db = await openDB('app', { workerMode: 'shared' });
|
|
40
67
|
```
|
|
41
68
|
|
|
42
|
-
|
|
69
|
+
Pages from the same origin share a storage owner through SharedWorker. Each client owns its transactions. Closing one handle preserves the other clients. When the page hosting the storage worker closes, another page reopens storage; database handles remain usable and active transactions receive invalidation.
|
|
43
70
|
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
71
|
+
Read and write transactions can overlap. Readers retain their snapshots. Commits publish sequentially; a writer whose snapshot is stale closes with `TransactionConflictError` before writing its changes. Start a new transaction to retry. Schema upgrades have one migration owner.
|
|
72
|
+
|
|
73
|
+
```ts
|
|
74
|
+
for await (const row of db.scanIter('kv')) {
|
|
75
|
+
console.log(row);
|
|
76
|
+
break;
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
let cursor: number | undefined;
|
|
80
|
+
try {
|
|
81
|
+
do {
|
|
82
|
+
const page = await db.scanPage('kv', {}, { cursor, maxRows: 256, maxBytes: 64 * 1024 });
|
|
83
|
+
cursor = page.cursor;
|
|
84
|
+
console.log(page.rows);
|
|
85
|
+
if (page.done) break;
|
|
86
|
+
} while (cursor !== undefined);
|
|
87
|
+
} finally {
|
|
88
|
+
if (cursor !== undefined) await db.closeScanCursor(cursor);
|
|
89
|
+
}
|
|
49
90
|
```
|
|
50
91
|
|
|
51
|
-
|
|
92
|
+
Paged scans retain one snapshot until exhaustion or explicit cursor close. Breaking out of `scanIter` closes its cursor. Primary and index pages limit both row count and byte size, including decoded values. A first row larger than the byte budget rejects the page.
|
|
93
|
+
|
|
94
|
+
## Typed records
|
|
95
|
+
|
|
96
|
+
```ts
|
|
97
|
+
import { createRecordStore, jsonRecordCodec, keyCodecs } from '@moyodb/sdk';
|
|
98
|
+
|
|
99
|
+
const users = await createRecordStore(db, 'users', {
|
|
100
|
+
key: keyCodecs.string,
|
|
101
|
+
value: jsonRecordCodec<{ name: string }>()
|
|
102
|
+
});
|
|
103
|
+
await users.put('alice', { name: 'Alice' });
|
|
104
|
+
console.log(await users.get('alice'));
|
|
105
|
+
```
|
|
106
|
+
|
|
107
|
+
Record stores support CRUD, batches, ordered ranges, managed indexes, and automatic transactions. Scalar and tuple key codecs retain the existing byte encodings. JSON codecs reject values that JSON cannot preserve; pass a type guard to validate an application schema.
|
|
108
|
+
|
|
109
|
+
## SQL
|
|
110
|
+
|
|
111
|
+
```ts
|
|
112
|
+
import { createSqlClient } from '@moyodb/sdk';
|
|
113
|
+
|
|
114
|
+
const sql = createSqlClient(db);
|
|
115
|
+
await sql.execute('CREATE TABLE IF NOT EXISTS people (id INTEGER PRIMARY KEY, name TEXT NOT NULL)');
|
|
116
|
+
await sql.execute('INSERT INTO people VALUES (?, ?)', [1, 'Alice']);
|
|
117
|
+
console.log(await sql.query('SELECT name FROM people WHERE id = ?', [1]));
|
|
118
|
+
console.log(await sql.explain('SELECT name FROM people WHERE id = ?', [1]));
|
|
119
|
+
```
|
|
120
|
+
|
|
121
|
+
Each statement runs in one transaction. Supported commands are `CREATE TABLE`, `DROP TABLE`, `INSERT`, `SELECT`, `UPDATE`, and `DELETE`, with positional parameters, predicates, ordering, and pagination. Columns support signed 64-bit `INTEGER`, `REAL`, `TEXT`, `BOOLEAN`, and `BLOB`; large integers use `bigint`, and blobs use `Uint8Array`. Tables have a primary key or a persistent generated row ID.
|
|
122
|
+
|
|
123
|
+
The planner reads the transaction's actual index catalog and chooses primary-key or supported scalar secondary-index access. Other predicates use a table scan; ordering sorts the result in memory. SQL schema uses `_moyodb_sql_catalog` and a reserved ownership record in each table. Access tables through SQL so schema, ownership records, row encodings, and indexes remain consistent.
|
|
124
|
+
|
|
125
|
+
## Verification
|
|
126
|
+
|
|
127
|
+
\- Lean checks run with all built-in/extra linters, Heron, JunkLinter and the full Batteries set; every finding fails CI. Run `npm run lint:lean` locally.\
|
|
128
|
+
\- `proofs/moyodb_proofs` models abstract KV/WAL/transaction semantics and independently checks real inline B-tree pages. The B-tree checker has kernel-checked certificates for structure, contents and routing for every byte-string key; CI compares real Rust mutations, lookup/scan and retained COW roots with Lean-computed states and rejects two production mutation witnesses. Format 2 external descriptors receive structural length and extent-address validation, with kernel-checked boundary examples. Their logical contents are rejected by the content checker because `PAY2` bodies are absent from its input. This proves properties of the Lean checker and checks concrete Rust executions; the Rust engine, checksums, overflow and external payload bodies, OPFS I/O, flush ordering and power loss remain outside those proofs.\
|
|
129
|
+
\- The traces exported to `proofs/artifacts` are replayed against the Rust engine by `crates/engine/tests/proof_artifacts.rs` as conformance scenarios.\
|
|
130
|
+
\- Crash behavior is covered by tests: `crates/engine/tests/crash_matrix.rs`, `crates/engine/tests/fault_injection.rs` (failed and short writes plus torn flushes at every WAL, main-file, and superblock operation during commit, checkpoint, and recovery), and `crates/engine/js/opfs_shim.test.mjs` for control-file publication.
|
|
52
131
|
|
|
53
132
|
## License
|
|
54
133
|
|
|
55
|
-
Copyright © 2026 Eluvane.
|
|
134
|
+
Copyright © 2026 Eluvane. The licensor is Eluvane; licensing requests go to [keiko1337@proton.me](mailto:keiko1337@proton.me). The official repository is [eluvane/MoyoDB](https://github.com/eluvane/MoyoDB).
|
|
135
|
+
|
|
136
|
+
MoyoDB **1.0.0** is the first release covered by the [Mother of Licenses 1.0](LICENSE) (`LicenseRef-MoL-1.0`). Earlier published releases retain their original licenses. Third-party dependencies and any separately licensed material retain their own licenses and notices.
|
|
137
|
+
|
|
138
|
+
MoL permits royalty-free use, including commercial use of unmodified code or Authorized Builds inside your own products. Private modifications and production patches are permitted for your own internal use, provided the modified code is not distributed, published, made available to third parties, or used to create a standalone or competing product or provide Project-as-a-Service. The upstream contribution workflow in Section 6 remains permitted. Other publication or distribution of modified versions, independent forks, resale of MoyoDB itself, and hosting MoyoDB itself as a service require written permission. MoyoDB under MoL is source-available, not OSI-approved open source.
|
|
56
139
|
|
|
57
|
-
|
|
140
|
+
## Contributing
|
|
58
141
|
|
|
59
|
-
|
|
142
|
+
Read [CONTRIBUTING.md](CONTRIBUTING.md) and Sections 9 and 10 of the license before submitting changes. The contribution and patent terms apply upon submission; no separate acceptance statement or PR checkbox is required by default.
|
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
function e(e){return typeof e==`object`&&!!e}function t(e,t){return e<t?-1:+(e>t)}function n(e){return!Number.isFinite(e)||e<=0?0:e>2147483647?2147483647:e}const r=`moyodb:worker-protocol:response`,i=/* @__PURE__ */ `open.close.destroy.deleteDB.begin.commit.rollback.autocommit.createStore.dropStore.clearStore.get.getMany.has.put.putMany.delete.deleteMany.applyBatch.scan.scanPage.closeCursor.getByIndex.scanByIndex.scanByIndexPage.getIndexes.reconcileIndexes.listStores.getVersion.changesSince.setSchemaVersion.exportSnapshot.importSnapshot.reset.compact.rebuild.stats.storageInfo.requestPersistence.setFailpoint`.split(`.`),a=/* @__PURE__ */ new Set([`get`,`getMany`,`has`,`put`,`putMany`,`delete`,`deleteMany`,`applyBatch`,`scan`,`getByIndex`,`scanByIndex`,`createStore`,`dropStore`,`clearStore`]);function o(e){return typeof e==`string`&&a.has(e)}const s=`moyodb:packed-binary-list:v1`,c=`moyodb:packed-scan-rows:v1`,l=`moyodb:packed-engine-scan-rows:v1`,u=`moyodb:packed-batch-ops:v1`,d=`moyodb:packed-optional-values:v1`,f=4294967295,p=16777216,m=[],h=new Set(i);function g(e){return typeof e==`string`&&h.has(e)}function _(t){return e(t)&&t.type===`moyodb:worker-protocol:request`&&t.version===1&&typeof t.id==`number`&&Number.isSafeInteger(t.id)&&typeof t.command==`string`&&Array.isArray(t.args)}function v(e){return ee(e,`moyodb:worker-protocol:request-batch`,`requests`)}function ee(t,n,r){return e(t)&&t.type===n&&t.version===1&&Array.isArray(t[r])&&t[r].length>0&&t[r].length<=128}function y(t){return e(t)&&(t.type===`moyodb:worker-protocol:request`||t.type===`moyodb:worker-protocol:response`||t.type===`moyodb:worker-protocol:request-batch`||t.type===`moyodb:worker-protocol:response-batch`||t.type===`moyodb:worker-protocol:ready`)}function te(t){if(e(t)){let e=E(t.code);return{name:E(t.name)??e??`Error`,code:e,message:E(t.message)??`Unknown error`,stack:E(t.stack)}}return{name:`Error`,message:String(t)}}function b(e,t,n=e){let r=Error(t);return r.name=e,Object.defineProperty(r,"code",{value:n,enumerable:!0,configurable:!0}),r}function ne(e,t){if(e===`autocommit`){let[e,n,r]=t;if(o(n)&&Array.isArray(r))return[e,n,ne(n,[0,...r]).slice(1)]}if(e===`getMany`||e===`deleteMany`){let[e,n,r]=t;if(!Array.isArray(r)){if(!Ee(r))throw b(`WorkerProtocolError`,`invalid packed binary-list argument`);return[e,n,ye(r)]}}if(e===`putMany`){let[e,n,r,i]=t;if(!Array.isArray(r)){if(!Ee(r))throw b(`WorkerProtocolError`,`invalid packed putMany argument`);return[e,n,be(r),i]}}if(e===`applyBatch`){let[e,n,r]=t;if(!Array.isArray(r)){if(!Oe(r))throw b(`WorkerProtocolError`,`invalid packed batch argument`);return[e,n,we(r)]}}return t}function re(e){return Ee(e)?e.bytes:null}function ie(e){return Oe(e)?e.bytes:null}function ae(e){return ye({__moyodbPacked:s,bytes:e})}function oe(e){return xe({__moyodbPacked:s,bytes:e})}function se(e){return we({__moyodbPacked:u,bytes:e})}function ce(e){return Te({__moyodbPacked:u,bytes:e})}function le(e){return{__moyodbPacked:d,bytes:e}}function ue(e){if(!(e instanceof Uint8Array)||e.byteLength<4)throw b(`WorkerProtocolError`,`invalid packed optional-values payload`);let t=new DataView(e.buffer,e.byteOffset,e.byteLength),n=t.getUint32(0,!0),r=w(4,C(n,4,`packed optional-values metadata`),`packed optional-values header`);if(r>e.byteLength)throw b(`WorkerProtocolError`,`packed optional-values metadata exceeds payload length`);let i=Array(n),a=r;for(let r=0;r<n;r+=1){let n=t.getUint32(4+r*4,!0);if(n===f){i[r]=null;continue}let o=a+n;if(o>e.byteLength)throw b(`WorkerProtocolError`,`packed optional-values item exceeds payload length`);i[r]=e.subarray(a,o),a=o}if(a!==e.byteLength)throw b(`WorkerProtocolError`,`packed optional-values payload has trailing bytes`);return i}function de(t,n){if((t===`scan`||t===`scanByIndex`)&&(pe(n)||De(n)))return{result:n,transfer:ge(n.bytes)};if(t===`scanPage`){let t=n;if(e(t)&&(pe(t.rows)||De(t.rows)))return{result:t,transfer:ge(t.rows.bytes)};if(e(t)&&Array.isArray(t.rows)){let e=Ce(t.rows);return{result:{...t,rows:e??t.rows},transfer:e?[e.bytes.buffer]:x(t.rows)}}}if(t===`getMany`&&ke(n))return{result:n,transfer:ge(n.bytes)};if(t===`scanByIndexPage`){let t=n;if(e(t)&&De(t.rows))return{result:t,transfer:x(t)};if(e(t)&&Array.isArray(t.rows)){let e=t.rows.length>0?Ce(t.rows):null,n={rows:e??t.rows,cursor:t.cursor},r=e?[e.bytes.buffer]:x(t.rows),i=S(t.cursor);return{result:n,transfer:i===null?r:[...r,i]}}}if(t===`getMany`){let e=n;if(Array.isArray(e)&&e.length>0){let t=Se(e);if(t)return{result:t,transfer:[t.bytes.buffer]}}return{result:n,transfer:x(n)}}if(t===`scan`||t===`scanByIndex`){let e=n;if(Array.isArray(e)&&e.length>0){let t=Ce(e);if(t)return{result:t,transfer:[t.bytes.buffer]}}return{result:n,transfer:x(n)}}return t===`get`||t===`getByIndex`||t===`exportSnapshot`?{result:n,transfer:ge(n)}:t===`changesSince`?{result:n,transfer:_e(n)}:{result:n,transfer:[]}}function fe(e){return{__moyodbPacked:l,bytes:e}}function pe(t){return e(t)&&t.__moyodbPacked===l&&t.bytes instanceof Uint8Array}function me(e){if(!(e instanceof Uint8Array)||e.byteLength<4)throw b(`WorkerProtocolError`,`invalid engine scan packet`);let t=new DataView(e.buffer,e.byteOffset,e.byteLength),n=t.getUint32(0,!0);if(n>(e.byteLength-4)/8)throw b(`WorkerProtocolError`,`engine scan row count exceeds packet length`);let r=Array(n),i=4;for(let a=0;a<n;a+=1){if(i+8>e.byteLength)throw b(`WorkerProtocolError`,`truncated engine scan row`);let n=t.getUint32(i,!0),o=t.getUint32(i+4,!0),s=i+8,c=s+n,l=c+o;if(l>e.byteLength)throw b(`WorkerProtocolError`,`engine scan row exceeds packet length`);r[a]={key:e.subarray(s,c),value:e.subarray(c,l)},i=l}if(i!==e.byteLength)throw b(`WorkerProtocolError`,`engine scan packet has trailing bytes`);return r}function x(e){let t=S(e);if(t!==null)return[t];if(typeof e!=`object`||!e)return m;let n=/* @__PURE__ */ new Set;return ve(e,n,/* @__PURE__ */ new WeakSet),n.size===0?m:Array.from(n)}function he(e,t){let n=t.length>0?structuredClone(e,{transfer:t.length===1?t:Array.from(new Set(t))}):structuredClone(e),r=/* @__PURE__ */ new Set,i=/* @__PURE__ */ new WeakSet,a=0,o=e=>{if(typeof e==`string`){a+=8+e.length*2;return}if(typeof e!=`object`||!e){a+=8;return}if(!i.has(e)){if(i.add(e),a+=8,e instanceof ArrayBuffer)r.add(e),a+=e.byteLength;else if(typeof SharedArrayBuffer<`u`&&e instanceof SharedArrayBuffer)a+=e.byteLength;else if(ArrayBuffer.isView(e))o(e.buffer);else if(Array.isArray(e))for(let t of e)o(t);else if(e instanceof Map)for(let[t,n]of e)o(t),o(n);else if(e instanceof Set)for(let t of e)o(t);else{let t=e;for(let e in t)Object.prototype.hasOwnProperty.call(t,e)&&(a+=8+e.length*2,o(t[e]))}}};return o(n),{value:n,transfer:r.size===0?m:Array.from(r),byteLength:a}}function ge(e){let t=S(e);return t===null?m:[t]}function S(e){if(e instanceof ArrayBuffer)return e;if(ArrayBuffer.isView(e)){let t=e.buffer;if(t instanceof ArrayBuffer&&e.byteOffset===0&&e.byteLength===t.byteLength)return t}return null}function _e(t){if(!e(t)||!Array.isArray(t.changes)||t.changes.length===0)return m;let n=null;for(let r of t.changes){if(!e(r))continue;let t=S(r.key);t!==null&&(n??=/* @__PURE__ */ new Set,n.add(t));let i=S(r.value);i!==null&&(n??=/* @__PURE__ */ new Set,n.add(i))}return n===null||n.size===0?m:Array.from(n)}function ve(e,t,n){if(e==null)return;if(e instanceof ArrayBuffer){t.add(e);return}if(ArrayBuffer.isView(e)){let n=e.buffer;n instanceof ArrayBuffer&&e.byteOffset===0&&e.byteLength===n.byteLength&&t.add(n);return}if(typeof e!=`object`)return;let r=e;if(n.has(r))return;if(n.add(r),Array.isArray(e)){for(let r of e)ve(r,t,n);return}let i=e;for(let e in i)Object.prototype.hasOwnProperty.call(i,e)&&ve(i[e],t,n)}function ye(e){let t=e.bytes;if(!(t instanceof Uint8Array)||t.byteLength<4)throw b(`WorkerProtocolError`,`invalid packed binary-list payload`);let n=new DataView(t.buffer,t.byteOffset,t.byteLength),r=n.getUint32(0,!0),i=w(4,C(r,4,`packed binary-list metadata`),`packed binary-list header`);if(i>t.byteLength)throw b(`WorkerProtocolError`,`packed binary-list metadata exceeds payload length`);let a=Array(r),o=4,s=i;for(let e=0;e<r;e+=1){let r=n.getUint32(o,!0);o+=4;let i=s+r;if(i>f||i>t.byteLength)throw b(`WorkerProtocolError`,`packed binary-list item exceeds payload length`);a[e]=t.subarray(s,i),s=i}if(s!==t.byteLength)throw b(`WorkerProtocolError`,`packed binary-list payload has trailing bytes`);return a}function be(e){let t=e.bytes;if(!(t instanceof Uint8Array)||t.byteLength<4)throw b(`WorkerProtocolError`,`invalid packed putMany payload`);let n=new DataView(t.buffer,t.byteOffset,t.byteLength),r=n.getUint32(0,!0);if(r%2!=0)throw b(`WorkerProtocolError`,`packed putMany payload has an odd item count`);let i=w(4,C(r,4,`packed putMany metadata`),`packed putMany header`);if(i>t.byteLength)throw b(`WorkerProtocolError`,`packed putMany metadata exceeds payload length`);let a=r/2,o=Array(a),s=4,c=i;for(let e=0;e<a;e+=1){let r=n.getUint32(s,!0),i=n.getUint32(s+4,!0);s+=8;let a=c+r;if(a>f||a>t.byteLength)throw b(`WorkerProtocolError`,`packed putMany key exceeds payload length`);let l=a+i;if(l>f||l>t.byteLength)throw b(`WorkerProtocolError`,`packed putMany value exceeds payload length`);o[e]=[t.subarray(c,a),t.subarray(a,l)],c=l}if(c!==t.byteLength)throw b(`WorkerProtocolError`,`packed putMany payload has trailing bytes`);return o}function xe(e){let t=e.bytes;if(!(t instanceof Uint8Array)||t.byteLength<4)throw b(`WorkerProtocolError`,`invalid packed putMany payload`);let n=new DataView(t.buffer,t.byteOffset,t.byteLength),r=n.getUint32(0,!0);if(r%2!=0)throw b(`WorkerProtocolError`,`packed putMany payload has an odd item count`);let i=w(4,C(r,4,`packed putMany metadata`),`packed putMany header`);if(i>t.byteLength)throw b(`WorkerProtocolError`,`packed putMany metadata exceeds payload length`);let a=r/2,o=Array(a),s=4,c=i;for(let e=0;e<a;e+=1){let r=n.getUint32(s,!0),i=n.getUint32(s+4,!0);s+=8;let a=c+r;if(a>f||a>t.byteLength)throw b(`WorkerProtocolError`,`packed putMany key exceeds payload length`);let l=a+i;if(l>f||l>t.byteLength)throw b(`WorkerProtocolError`,`packed putMany value exceeds payload length`);o[e]=t.subarray(c,a),c=l}if(c!==t.byteLength)throw b(`WorkerProtocolError`,`packed putMany payload has trailing bytes`);return o}function Se(e){let t=e.length,n=C(t,5,`packed nullable binary-list metadata`),r=0;for(let n=0;n<t;n+=1){let t=e[n];if(t===null)continue;if(!(t instanceof Uint8Array))throw b(`WorkerProtocolError`,`nullable binary-list payload item is not a Uint8Array or null`);let i=T(t.byteLength,`nullable binary-list item length`);if(r+=i,r>f)throw b(`WorkerProtocolError`,`packed nullable binary-list payload exceeds 32-bit payload limit`)}let i=w(4,n,`packed nullable binary-list header`),a=w(i,r,`packed nullable binary-list total`);if(a>p)return null;let o=new Uint8Array(a),s=new DataView(o.buffer);s.setUint32(0,t,!0);let c=4,l=i;for(let n=0;n<t;n+=1){let t=e[n];if(t===null){s.setUint8(c,0),s.setUint32(c+1,0,!0),c+=5;continue}let r=t.byteLength;s.setUint8(c,1),s.setUint32(c+1,r,!0),c+=5,o.set(t,l),l+=r}return{__moyodbPacked:`moyodb:packed-nullable-binary-list:v1`,bytes:o}}function Ce(t){let n=t.length,r=C(n,8,`packed scan row metadata`),i=0;for(let r=0;r<n;r+=1){let n=t[r];if(!e(n)||!(n.key instanceof Uint8Array)||!(n.value instanceof Uint8Array))throw b(`WorkerProtocolError`,`scan row payload key/value is not a Uint8Array`);let a=T(n.key.byteLength,`scan row key length`),o=T(n.value.byteLength,`scan row value length`);if(i+=a+o,i>f)throw b(`WorkerProtocolError`,`packed scan row payload exceeds 32-bit payload limit`)}let a=w(4,r,`packed scan row header`),o=w(a,i,`packed scan row total`);if(o>p)return null;let s=new Uint8Array(o),l=new DataView(s.buffer);l.setUint32(0,n,!0);let u=4,d=a;for(let e=0;e<n;e+=1){let n=t[e],r=n.key,i=n.value,a=r.byteLength,o=i.byteLength;l.setUint32(u,a,!0),l.setUint32(u+4,o,!0),u+=8,s.set(r,d),d+=a,s.set(i,d),d+=o}return{__moyodbPacked:c,bytes:s}}function we(e){let t=e.bytes;if(!(t instanceof Uint8Array)||t.byteLength<4)throw b(`WorkerProtocolError`,`invalid packed batch payload`);let n=new DataView(t.buffer,t.byteOffset,t.byteLength),r=n.getUint32(0,!0),i=w(4,C(r,9,`packed batch metadata`),`packed batch header`);if(i>t.byteLength)throw b(`WorkerProtocolError`,`packed batch metadata exceeds payload length`);let a=Array(r),o=4,s=i;for(let e=0;e<r;e+=1){let r=n.getUint8(o),i=n.getUint32(o+1,!0),c=n.getUint32(o+5,!0);o+=9;let l=s+i;if(l>f||l>t.byteLength)throw b(`WorkerProtocolError`,`packed batch key exceeds payload length`);let u=t.subarray(s,l);if(s=l,r===0){if(c!==0)throw b(`WorkerProtocolError`,`packed delete operation has a value payload`);a[e]={kind:`delete`,key:u};continue}if(r!==1)throw b(`WorkerProtocolError`,`packed batch operation has invalid kind byte: ${r}`);let d=s+c;if(d>f||d>t.byteLength)throw b(`WorkerProtocolError`,`packed batch value exceeds payload length`);a[e]={kind:`put`,key:u,value:t.subarray(s,d)},s=d}if(s!==t.byteLength)throw b(`WorkerProtocolError`,`packed batch payload has trailing bytes`);return a}function Te(e){let t=e.bytes;if(!(t instanceof Uint8Array)||t.byteLength<4)throw b(`WorkerProtocolError`,`invalid packed batch payload`);let n=new DataView(t.buffer,t.byteOffset,t.byteLength),r=n.getUint32(0,!0),i=w(4,C(r,9,`packed batch metadata`),`packed batch header`);if(i>t.byteLength)throw b(`WorkerProtocolError`,`packed batch metadata exceeds payload length`);let a=Array(r),o=4,s=i;for(let e=0;e<r;e+=1){let r=n.getUint8(o),i=n.getUint32(o+1,!0),c=n.getUint32(o+5,!0);o+=9;let l=s+i;if(l>f||l>t.byteLength)throw b(`WorkerProtocolError`,`packed batch key exceeds payload length`);let u=t.subarray(s,l);if(s=l,r===0){if(c!==0)throw b(`WorkerProtocolError`,`packed delete operation has a value payload`);a[e]={kind:`delete`,key:u};continue}if(r!==1)throw b(`WorkerProtocolError`,`packed batch operation has invalid kind byte: ${r}`);let d=s+c;if(d>f||d>t.byteLength)throw b(`WorkerProtocolError`,`packed batch value exceeds payload length`);a[e]={kind:`put`,key:u},s=d}if(s!==t.byteLength)throw b(`WorkerProtocolError`,`packed batch payload has trailing bytes`);return a}function Ee(t){return e(t)&&t.__moyodbPacked===s&&t.bytes instanceof Uint8Array}function De(t){return e(t)&&t.__moyodbPacked===c&&t.bytes instanceof Uint8Array}function Oe(t){return e(t)&&t.__moyodbPacked===u&&t.bytes instanceof Uint8Array}function ke(t){return e(t)&&t.__moyodbPacked===d&&t.bytes instanceof Uint8Array}function C(e,t,n){if(!Number.isSafeInteger(e)||e<0)throw b(`WorkerProtocolError`,`${n} count is invalid: ${e}`);return T(e*t,n)}function w(e,t,n){return T(e+t,n)}function T(e,t){if(!Number.isSafeInteger(e)||e<0||e>f)throw b(`WorkerProtocolError`,`${t} exceeds 32-bit payload limit`);return e}function E(e){return typeof e==`string`?e:void 0}const Ae=/* @__PURE__ */ new Set([`commit`,`rollback`,`createStore`,`dropStore`,`clearStore`,`get`,`getMany`,`has`,`put`,`putMany`,`delete`,`deleteMany`,`applyBatch`,`scan`,`getByIndex`,`scanByIndex`,`scanByIndexPage`,`getIndexes`,`reconcileIndexes`,`setSchemaVersion`]),je=/* @__PURE__ */ new Set([`open`,`close`,`destroy`,`importSnapshot`,`reset`,`compact`,`rebuild`]),Me=/* @__PURE__ */ new Set([`deleteDB`,`storageInfo`,`requestPersistence`]),D=()=>{};var Ne=class{#e=/* @__PURE__ */ new Map;#t=/* @__PURE__ */ new Set;#n=Promise.resolve();#r=/* @__PURE__ */ new Map;schedule(t,n,r){if(Me.has(t))return r();if(je.has(t))return this.#r.size===0?this.#a(r):this.#a(async()=>{let e=await r();return this.#r.clear(),e});if(t!==`scanPage`&&t!==`closeCursor`&&!((t===`commit`||t===`rollback`)&&this.#r.size>0))return this.#i(Pe(t,n),r);let i=t===`scanPage`&&e(n[0])?n[0]:null,a=i?.cursorId??(t===`closeCursor`?n[0]:void 0),o=(typeof a==`number`?this.#r.get(a):void 0)??(i&&typeof i.txId==`number`?i.txId:typeof a==`number`?`cursor:${a}`:Pe(t,n));return this.#i(o,async()=>{try{let t=await r();return i&&e(t)&&(typeof a==`number`&&this.#r.delete(a),typeof t.cursorId==`number`&&this.#r.set(t.cursorId,o??`cursor:${t.cursorId}`)),t}finally{if(t===`closeCursor`&&typeof a==`number`&&this.#r.delete(a),t===`commit`||t===`rollback`)for(let[e,t]of this.#r)t===n[0]&&this.#r.delete(e)}})}#i(e,t){let n=this.#n,r=e===null?void 0:this.#e.get(e),i=(async()=>(await n,r&&await r,t()))(),a=i.then(D,D);return this.#t.add(a),e!==null&&this.#e.set(e,a),a.then(()=>{this.#t.delete(a),e!==null&&this.#e.get(e)===a&&this.#e.delete(e)}),i}#a(e){let t=this.#n,n=Array.from(this.#t),r=(async()=>(await t,await Promise.all(n),e()))();return this.#n=r.then(D,D),r}};function Pe(e,t){return Ae.has(e)&&typeof t[0]==`number`?t[0]:e===`autocommit`&&t[0]===`readwrite`?`autocommit:readwrite`:null}var Fe=class{scope;queued=[];queuedBytes=0;flushScheduled=!1;flushChannel=null;closed=!1;constructor(e){this.scope=e}enqueue=(e,t=[])=>{if(this.closed)return;let n=he(e,t);this.queued.length>0&&this.queuedBytes+n.byteLength>1048576&&this.flush(),this.queued.push({response:n.value,transfer:n.transfer}),this.queuedBytes+=n.byteLength,this.flushScheduled||(this.flushScheduled=!0,queueMicrotask(()=>{if(this.closed||this.queued.length===0){this.flushScheduled=!1;return}this.flushChannel??=this.createFlushChannel(),this.flushChannel.port2.postMessage(null)})),(this.queued.length>=128||this.queuedBytes>=1048576)&&this.flush()};close(){this.closed=!0,this.queued=[],this.queuedBytes=0,this.flushChannel?.port1.close(),this.flushChannel?.port2.close(),this.flushChannel=null}createFlushChannel(){let e=new MessageChannel;return e.port1.addEventListener(`message`,()=>{this.flushScheduled=!1,this.flush()}),e.port1.start(),e}flush(){let e=this.queued;if(this.queued=[],this.queuedBytes=0,this.closed||e.length===0)return;let t=e.length===1?e[0].response:{type:`moyodb:worker-protocol:response-batch`,version:1,responses:e.map(e=>e.response)},n=[];for(let t of e)for(let e of t.transfer)n.push(e);We(this.scope,t,n)}};function Ie(e,t=self){let n=new Ne,r=new Fe(t),i=i=>{if(i.origin===``||i.origin===t.location.origin){if(v(i.data)){let a=i.data.requests.length,o=(e,t)=>{r.enqueue(e,t),--a,a===0&&r.flush()};for(let r of i.data.requests)Le(t,e,n,r,o);return}Le(t,e,n,i.data)}};return t.addEventListener(`message`,i),t.postMessage({type:`moyodb:worker-protocol:ready`,version:1,batching:1}),{close(){t.removeEventListener(`message`,i),r.close()}}}async function Le(e,t,n,r,i=(t,n)=>We(e,t,n)){if(!y(r))return;let a=typeof r.id==`number`&&Number.isSafeInteger(r.id)?r.id:0;if(!_(r)){i(Ue(a,b(`WorkerProtocolError`,`invalid worker protocol request`)));return}if(!g(r.command)){i(Ue(r.id,b(`WorkerProtocolError`,`unsupported worker command: ${String(r.command)}`)));return}let s=r.command,c=r.args;try{let e=s,a;if(s===`autocommit`){let[n,r,i]=c;if(n!==`readonly`&&n!==`readwrite`||!o(r)||!Array.isArray(i))throw b(`WorkerProtocolError`,`invalid autocommit request`);Re(t,r),e=r,a=()=>Be(t,n,r,i)}else Re(t,s),a=()=>ze(t,s,c);let l=await n.schedule(s,c,a),u=de(e,l);i(He(r.id,u.result),u.transfer)}catch(e){i(Ue(r.id,e))}}function Re(e,t){if(typeof e[t]!=`function`)throw b(`WorkerProtocolError`,`worker command is not implemented: ${t}`)}function ze(e,t,n){let r=Ve(e,t,n);return r===null?e[t].apply(e,ne(t,n)):r}async function Be(e,t,n,r){let i=await e.begin(t),a;try{a=await ze(e,n,[i,...r])}catch(t){try{await e.rollback(i)}catch{}throw t}return t===`readwrite`?await e.commit(i):await e.rollback(i),a}function Ve(e,t,n){let r=e;if(t===`getMany`||t===`deleteMany`){let[e,i,a]=n;if(typeof e!=`number`||typeof i!=`string`)return null;let o=re(a);return o===null?null:t===`getMany`&&typeof r.getManyPacked==`function`?r.getManyPacked(e,i,o):t===`deleteMany`&&typeof r.deleteManyPacked==`function`?r.deleteManyPacked(e,i,o):null}if(t===`putMany`){let[e,t,i,a]=n;if(typeof e!=`number`||typeof t!=`string`||typeof r.putManyPacked!=`function`)return null;let o=re(i);return o===null?null:r.putManyPacked(e,t,o,a)}if(t===`applyBatch`){let[e,t,i]=n;if(typeof e!=`number`||typeof t!=`string`||typeof r.applyBatchPacked!=`function`)return null;let a=ie(i);return a===null?null:r.applyBatchPacked(e,t,a)}return null}function He(e,t){return{type:r,version:1,id:e,ok:!0,result:t}}function Ue(e,t){return{type:r,version:1,id:e,ok:!1,error:te(t)}}function We(e,t,n=[]){if(n.length>0)try{e.postMessage(t,n);return}catch{}e.postMessage(t)}const Ge=new TextEncoder;new TextDecoder,new TextDecoder(`utf-8`,{fatal:!0});const Ke=BigInt(`0xffffffffffffffff`);function O(e){return Ge.encode(e)}function qe(e){return Ze(e)}function k(e){return Qe(e)}function Je(e){let t=[],n=[];for(let r=0;r<e.length;r+=1){let i=e[r];if(i!==0){n.push(i);continue}let a=e[r+1];if(a===255){n.push(0),r+=1;continue}if(a===0){t.push(Uint8Array.from(n)),n.length=0,r+=1;continue}throw TypeError(`invalid compound key encoding`)}if(n.length!==0)throw TypeError(`compound key terminated unexpectedly`);return t}function Ye(e){let t=e.slice();for(let e=t.length-1;e>=0;--e)if(t[e]!==255)return t[e]+=1,t.subarray(0,e+1);return null}function Xe(e){let t=Ye(e);return t?{gte:e,lt:t}:{gte:e}}function Ze(e){if(e===null)return Uint8Array.of(16);if(typeof e==`boolean`)return Uint8Array.of(e?33:32);if(typeof e==`number`)return $e(e);if(typeof e==`string`){for(let t of e){let e=t.codePointAt(0);if(e>=55296&&e<=57343)throw TypeError(`compound key string parts must contain valid Unicode scalar values`)}let t=O(e),n=new Uint8Array(1+t.length);return n[0]=64,n.set(t,1),n}if(e instanceof Uint8Array){let t=new Uint8Array(1+e.length);return t[0]=80,t.set(e,1),t}throw TypeError(`compound key parts must be string, number, boolean, null, or Uint8Array`)}function Qe(e){let t=0;for(let n of e){for(let e of n)t+=e===0?2:1;t+=2}let n=new Uint8Array(t),r=0;for(let t of e){for(let e of t)e===0?(n[r]=0,n[r+1]=255,r+=2):(n[r]=e,r+=1);n[r]=0,n[r+1]=0,r+=2}return n}function $e(e){if(!Number.isFinite(e))throw TypeError(`compound key number parts must be finite`);let t=Object.is(e,-0)?0:e,n=/* @__PURE__ */ new ArrayBuffer(9),r=new DataView(n);r.setUint8(0,48),r.setFloat64(1,t,!1);let i=r.getBigUint64(1,!1);return i=(i&1n<<63n)==0n?i^1n<<63n:~i&Ke,r.setBigUint64(1,i,!1),new Uint8Array(n)}const et=65536,tt=16384,nt=4294967295,rt=new Uint32Array(tt);function A(e){let t=/* @__PURE__ */ Error(`invalid Snappy block: ${e}`);return t.name=`CorruptionError`,t}function it(e,t){return(e[t]|e[t+1]<<8|e[t+2]<<16|e[t+3]<<24)>>>0}function at(e,t){return Math.imul(e,2654435761)>>>32-t}function ot(e){if(e.byteLength>nt)throw RangeError(`Snappy input exceeds the 32-bit length limit`);let t=new Uint8Array(e.byteLength+Math.ceil(e.byteLength/6)+32),n=0,r=e.byteLength;for(;r>=128;)t[n++]=r&127|128,r=Math.floor(r/128);t[n++]=r;let i=(r,i)=>{if(r===i)return;let a=i-r-1;if(a<60)t[n++]=a<<2;else{let e=a<=255?1:a<=65535?2:a<=16777215?3:4;t[n++]=59+e<<2;for(let r=0;r<e;r+=1)t[n++]=a&255,a>>>=8}t.set(e.subarray(r,i),n),n+=i-r},a=(e,r)=>{for(;r>0;){let i=Math.min(r,64);i>=4&&i<=11&&e<2048?(t[n++]=1|i-4<<2|e>>>8<<5,t[n++]=e&255):(t[n++]=2|i-1<<2,t[n++]=e&255,t[n++]=e>>>8),r-=i}},o=8;for(;1<<o<Math.min(e.byteLength,tt);)o+=1;let s=1<<o,c=rt;for(let t=0;t<e.byteLength;t+=et){let n=Math.min(t+et,e.byteLength);c.fill(0,0,s);let r=t,l=t,u=0;for(;r+4<=n;){let s=it(e,r),d=at(s,o),f=c[d];c[d]=r-t+1;let p=t+f-1;if(f===0||s!==it(e,p)){u+=1,r+=1+Math.min(u>>>5,64);continue}i(l,r);let m=r;for(r+=4;r<n&&e[r]===e[p+r-m];)r+=1;a(m-p,r-m),l=r,u=0,r+4<=n&&(c[at(it(e,r-1),o)]=r-t)}i(l,n)}return t.subarray(0,n)}function st(e,t,n){if(!Number.isSafeInteger(t)||t<0||t>nt)throw RangeError(`invalid Snappy output limit`);let r=0,i=0;for(let t=0;;t+=1){if(r>=e.byteLength||t===5)throw A(`truncated or invalid length`);let n=e[r++];if(t===4&&n>15)throw A(`length exceeds 32 bits`);if(i+=(n&127)*2**(t*7),n<128)break}if(i>t)throw A(`output exceeds ${t} byte limit`);if(n!==void 0&&i!==n)throw A(`length mismatch: expected ${n} bytes, got ${i}`);let a=new Uint8Array(i),o=0;for(;r<e.byteLength;){let t=e[r++],n=t&3;if(n===0){let n=t>>>2;if(n<60)n+=1;else{let t=n-59;if(t>e.byteLength-r)throw A(`truncated literal length`);n=1;for(let i=0;i<t;i+=1)n+=e[r++]*2**(i*8)}if(n>e.byteLength-r||n>i-o)throw A(`literal exceeds input or output`);a.set(e.subarray(r,r+n),o),r+=n,o+=n;continue}let s=n===1?1:n===2?2:4;if(s>e.byteLength-r)throw A(`truncated copy offset`);let c=n===1?4+(t>>>2&7):1+(t>>>2),l=n===1?(t&224)<<3:0;for(let t=0;t<s;t+=1)l+=e[r++]*2**(t*8);if(l===0||l>o||c>i-o)throw A(`copy exceeds output or has an invalid offset`);let u=0;for(;u<c;){let e=Math.min(l+u,c-u);a.copyWithin(o+u,o-l,o-l+e),u+=e}o+=c}if(o!==i)throw A(`length mismatch: expected ${i} bytes, got ${o}`);return a}const j=O(`BDBZVAL1`),ct=O(`BDBZSNP1`),lt=1024,M=8388608,ut=268435456,N=(()=>{let e=/* @__PURE__ */ new Uint32Array(2048);for(let t=0;t<256;t+=1){let n=t;for(let e=0;e<8;e+=1)n&1?n=n>>>1^3988292384:n>>>=1;e[t]=n>>>0}for(let t=0;t<256;t+=1){let n=e[t];for(let r=1;r<8;r+=1)n=n>>>8^e[n&255],e[r*256+t]=n>>>0}return e})();function P(e,t){let n=Error(t);return n.name=e,n}function dt(e){switch(e){case!1:return 0;case`gzip`:return 1;case`deflate`:return 2;case`snappy`:return 3;default:throw P(`InternalError`,`unsupported compression kind: ${String(e)}`)}}function ft(e){switch(e){case 0:return!1;case 1:return`gzip`;case 2:return`deflate`;case 3:return`snappy`;default:throw P(`CorruptionError`,`invalid compression tag: ${e}`)}}function pt(){return P(`UnsupportedPlatformError`,`CompressionStream and DecompressionStream are required for moyodb compression`)}function mt(){if(typeof CompressionStream!=`function`||typeof DecompressionStream!=`function`)throw pt()}function ht(e){let t=4294967295,n=0,r=e.byteLength-7;for(;n<r;n+=8){let r=t^e[n]^e[n+1]<<8^e[n+2]<<16^e[n+3]<<24;t=N[1792+(r&255)]^N[1536+(r>>>8&255)]^N[1280+(r>>>16&255)]^N[1024+(r>>>24)]^N[768+e[n+4]]^N[512+e[n+5]]^N[256+e[n+6]]^N[e[n+7]]}for(;n<e.byteLength;n+=1)t=t>>>8^N[(t^e[n])&255];return(t^4294967295)>>>0}function F(e,t,n,r){let i=new Uint8Array(18+r.byteLength);return gt(i,0,e,t,n,r),i}function gt(e,t,n,r,i,a){let o=ht(a);e.set(a,t+18),e.set(n,t),e[t+8]=1,e[t+9]=r;let s=new DataView(e.buffer,e.byteOffset+t,18);s.setUint32(10,i,!0),s.setUint32(14,o,!0)}function _t(e,t){return(t+18)*100<=e*90}function vt(e){if(e.byteLength<65536)return!0;let t=0;for(let n=0;n<3;n+=1){let r=Math.floor((e.byteLength-lt)*n/2);t+=ot(e.subarray(r,r+lt)).byteLength}return _t(lt*3,t)}function yt(e,t,n){return _t(e.byteLength,t.byteLength)?F(j,dt(n),e.byteLength,t):F(j,0,e.byteLength,e)}function bt(e){if(e.byteLength>M)throw P(`ValueTooLargeError`,`value has ${e.byteLength} bytes, exceeding the ${M} byte limit`)}function xt(e,t){if(t===!1)return{payload:e,rawLength:e.byteLength,byteLength:e.byteLength,kindTag:null};bt(e);let n=e,r=0;if(e.byteLength>=1024&&vt(e)){let t=ot(e);_t(e.byteLength,t.byteLength)&&(n=t,r=3)}return{payload:n,rawLength:e.byteLength,byteLength:18+n.byteLength,kindTag:r}}function St(e,t,n){if(!Number.isSafeInteger(n)||n<0||e.byteLength>t.byteLength-n)throw P(`InternalError`,`prepared store value exceeds its destination`);return e.kindTag===null?t.set(e.payload,n):gt(t,n,j,e.kindTag,e.rawLength,e.payload),n+e.byteLength}function Ct(e){let t=new Uint8Array(e.byteLength);return t.set(e),t}function wt(e){let t=0;return new ReadableStream({pull(n){if(t<e.byteLength){let r=Math.min(t+65536,e.byteLength);n.enqueue(e.subarray(t,r)),t=r}t===e.byteLength&&n.close()}})}function Tt(e,t,n=!0){if(t.byteLength<e.byteLength)return null;for(let n=0;n<e.byteLength;n+=1)if(t[n]!==e[n])return null;if(t.byteLength<18){if(n)throw P(`CorruptionError`,`truncated compression envelope: expected at least 18 bytes, got ${t.byteLength}`);return null}let r=new DataView(t.buffer,t.byteOffset,18);return{version:t[8],kindTag:t[9],rawLength:r.getUint32(10,!0),payloadChecksum:r.getUint32(14,!0)}}async function Et(e,t){mt();let n;try{n=wt(e).pipeThrough(new CompressionStream(t))}catch{throw pt()}try{return new Uint8Array(await new Response(n).arrayBuffer())}catch(e){throw P(`InternalError`,`failed to compress bytes with ${t}: ${String(e)}`)}}async function Dt(e,t,n,r){if(t===`snappy`)return st(e,r??M,r);mt();let i;try{i=wt(Ct(e)).pipeThrough(new DecompressionStream(t))}catch{throw pt()}try{return await Ot(i,n,r)}catch(e){throw P(`CorruptionError`,`failed to decompress ${n}: ${String(e)}`)}}async function Ot(e,t,n){let r=e.getReader(),i=[],a=0;try{for(let e=await r.read();!e.done;e=await r.read()){let o=e.value;if(a+=o.byteLength,n!==void 0&&a>n)throw await r.cancel(`decompressed ${t} exceeded ${n} bytes`),P(`CorruptionError`,`decompressed ${t} exceeds ${n} byte limit`);i.push(o)}}finally{r.releaseLock()}if(i.length===1)return i[0];let o=new Uint8Array(a),s=0;for(let e of i)o.set(e,s),s+=e.byteLength;return o}function kt(e){let t=(e&12)>>>2;switch(t){case 0:return!1;case 1:return`gzip`;case 2:return`deflate`;case 3:return`snappy`;default:throw P(`CorruptionError`,`invalid store compression flags: ${t}`)}}async function I(e,t){if(t===!1)return e;if(t===`snappy`){let n=xt(e,t),r=new Uint8Array(n.byteLength);return St(n,r,0),r}if(bt(e),e.byteLength<1024)return F(j,0,e.byteLength,e);let n=Ct(e);return yt(n,await Et(n,t),t)}async function At(e,t){let n=Tt(j,e,t.strict);if(!n)return e;if(n.version!==1){if(t.strict)throw P(`CorruptionError`,`unsupported value record version: ${n.version}`);return e}let r;try{r=ft(n.kindTag)}catch(n){if(t.strict)throw n;return e}let i=e.subarray(18);if(ht(i)!==n.payloadChecksum){if(t.strict)throw P(`CorruptionError`,`value record checksum mismatch`);return e}if(r===!1){if(i.byteLength!==n.rawLength){if(t.strict)throw P(`CorruptionError`,`value record length mismatch: expected ${n.rawLength} bytes, got ${i.byteLength}`);return e}return i.slice()}if(n.rawLength>M)throw P(`CorruptionError`,`compressed value advertises ${n.rawLength} decompressed bytes, exceeding the ${M} byte limit`);let a=await Dt(i,r,`value record (${r})`,n.rawLength);if(a.byteLength!==n.rawLength)throw P(`CorruptionError`,`decompressed value length mismatch: expected ${n.rawLength} bytes, got ${a.byteLength}`);return a}async function jt(e,t){if(t===!1)return e;if(![`gzip`,`deflate`].includes(t))throw P(`InternalError`,`unsupported snapshot compression kind: ${String(t)}`);let n=Ct(e),r=await Et(n,t);return F(ct,dt(t),n.byteLength,r)}async function Mt(e){let t=Tt(ct,e);if(!t)return e;if(t.version!==1)throw P(`CorruptionError`,`unsupported snapshot compression version: ${t.version}`);let n=ft(t.kindTag);if(n===!1)throw P(`CorruptionError`,`snapshot compression envelope cannot store kind "none"`);if(n===`snappy`)throw P(`CorruptionError`,`invalid snapshot compression tag: ${t.kindTag}`);let r=e.subarray(18);if(ht(r)!==t.payloadChecksum)throw P(`CorruptionError`,`snapshot compression checksum mismatch`);if(t.rawLength>ut)throw P(`CorruptionError`,`compressed snapshot advertises ${t.rawLength} decompressed bytes, exceeding the ${ut} byte limit`);let i=await Dt(r,n,`snapshot export (${n})`,t.rawLength);if(i.byteLength!==t.rawLength)throw P(`CorruptionError`,`decompressed snapshot length mismatch: expected ${t.rawLength} bytes, got ${i.byteLength}`);return i}var Nt=class extends Error{constructor(e,t){super(t),this.name=e,Object.setPrototypeOf(this,new.target.prototype)}},Pt=class extends Nt{constructor(e){super(`ReservedStoreNameError`,e)}},L=class extends Nt{constructor(e){super(`SerializationError`,e)}},R=class extends Nt{constructor(e){super(`InvalidOpenOptionsError`,e)}};const Ft=new TextEncoder,It=new TextDecoder(`utf-8`,{fatal:!0}),Lt=Symbol(`moyodb.indexing.missing`),Rt=BigInt(`0xcbf29ce484222325`),zt=BigInt(`0x100000001b3`),Bt=BigInt(`0xffffffffffffffff`),Vt=`__browserdb:index:`,z=`__browserdb:indexes`;function B(e){return e.startsWith(`__browserdb:`)}function Ht(e){if(B(e))throw new Pt(`reserved store name: ${e}`)}function Ut(e){if(e===void 0)return[];if(!Array.isArray(e))throw new R(`indexes must be an array`);let t=[],n=/* @__PURE__ */ new Set,r=/* @__PURE__ */ new Map;for(let i of e){if(typeof i!=`object`||!i||Array.isArray(i))throw new R(`each index definition must be an object`);let{store:e,name:a,keyPath:o,unique:s}=i;if(typeof e!=`string`||e.length===0)throw new R(`index store must be a non-empty string`);if(typeof a!=`string`||a.length===0)throw new R(`index name must be a non-empty string`);Ht(e);let c=an(o);if(s!==void 0&&typeof s!=`boolean`)throw new R(`index unique must be a boolean`);let l={store:e,name:a,keyPath:c.paths,compound:c.compound,unique:s??!1,internalStore:cn(e,a)},u=Gt(l.store,l.name);if(n.has(u))throw new R(`duplicate index definition ${l.store}.${l.name}`);n.add(u);let d=r.get(l.internalStore);if(d&&d!==u)throw new R(`index definitions ${d} and ${u} map to the same internal store ${l.internalStore}`);r.set(l.internalStore,u),t.push(l)}return t.sort(Wt),t}function Wt(e,n){let r=t(e.store,n.store);if(r!==0)return r;let i=t(e.name,n.name);if(i!==0)return i;let a=Number(e.unique)-Number(n.unique);return a===0?t(sn(e),sn(n)):a}function Gt(e,t){return JSON.stringify([e,t])}function Kt(e,t,n){return e.find(e=>e.store===t&&e.name===n)??null}function qt(e,t){return k([O(e),O(t)])}function Jt(e){return O(JSON.stringify(rn(e)))}function Yt(e){let t;try{t=JSON.parse(It.decode(e));let[n]=Ut([t]);return n}catch(e){throw new L(`invalid persisted index metadata: ${String(e)}`)}}function Xt(e,t){return k([e,t])}function V(e){let t;try{t=Je(e)}catch(e){throw new L(`invalid index entry key encoding: ${String(e)}`)}if(t.length!==2)throw new L(`invalid index entry key encoding`);return{logicalKey:t[0],primaryKey:t[1]}}function Zt(e){return Xe(k([e]))}function Qt(e={}){hn(e);let t={};if(e.reverse!==void 0&&(t.reverse=e.reverse),e.limit!==void 0&&(t.limit=e.limit),e.gte&&(t.gte=k([e.gte])),e.gt){let n=Ye(k([e.gt]));n&&(t.gte=n)}if(e.lt&&(t.lt=k([e.lt])),e.lte){let n=Ye(k([e.lte]));n&&(t.lt=n)}return t}function $t(e,t){return tn(e,dn(t))}function en(e){let t=!1,n;return r=>(t||=(n=dn(e),!0),tn(r,n))}function tn(e,t){if(e.compound){let n=[];for(let r of e.keyPath){let e=fn(t,r);if(e===Lt)return null;n.push(pn(e))}return k(n)}let n=fn(t,e.keyPath[0]);return n===Lt?null:pn(n)}function H(e){return e.map(e=>({store:e.store,name:e.name,keyPath:[...e.keyPath],compound:e.compound,unique:e.unique,internalStore:e.internalStore}))}function nn(e){return e.map(rn)}function rn(e){return{store:e.store,name:e.name,keyPath:e.compound?[...e.keyPath]:e.keyPath[0],unique:e.unique}}function an(e){if(typeof e==`string`)return on(e),{paths:[e],compound:!1};if(!Array.isArray(e)||e.length===0||!e.every(e=>typeof e==`string`))throw new R(`index keyPath must be a non-empty string or non-empty string[]`);for(let t of e)on(t);return{paths:[...e],compound:!0}}function on(e){if(e.length===0)throw new R(`index keyPath strings must be non-empty`);if(e.startsWith(`.`)||e.endsWith(`.`)||e.includes(`..`))throw new R(`invalid index keyPath: ${e}`)}function sn(e){return e.compound?`[${e.keyPath.join(`,`)}]`:e.keyPath[0]}function cn(e,t){let n=ln(O(e)),r=ln(O(t)),i=`${Vt}${n}:${r}`;if(Ft.encode(i).length<=255)return i;let a=O(`${e}\u0000${t}`);return`${Vt}h:${un(a)}`}function ln(e){let t=``;for(let n of e)t+=String.fromCharCode(n);return btoa(t).replace(/\+/g,`-`).replace(/\//g,`_`).replace(/=+$/u,``)}function un(e){let t=Rt;for(let n of e)t^=BigInt(n),t=t*zt&Bt;return t.toString(16).padStart(16,`0`)}function dn(e){try{return JSON.parse(It.decode(e))}catch(e){throw new L(`indexed values must be valid UTF-8 JSON: ${String(e)}`)}}function fn(e,t){let n=e;for(let e of t.split(`.`)){if(typeof n!=`object`||!n||!Object.hasOwn(n,e))return Lt;n=Reflect.get(n,e)}return n}function pn(e){if(e===null||typeof e==`string`||typeof e==`number`||typeof e==`boolean`||e instanceof Uint8Array)try{return qe(e)}catch(e){throw e instanceof TypeError?new L(`invalid indexed keyPath value: ${e.message}`):e}throw new L(`indexed keyPath values must resolve to string, number, boolean, null, or Uint8Array; got ${mn(e)}`)}function mn(e){return Array.isArray(e)?`array`:typeof e}function hn(e){if(e.gt!==void 0&&e.gte!==void 0)throw TypeError(`index range cannot specify both gt and gte`);if(e.lt!==void 0&&e.lte!==void 0)throw TypeError(`index range cannot specify both lt and lte`)}function U(e){return BigInt(e)}function W(e){return typeof e==`bigint`?Number(e):e}function gn(e){return e==null?null:W(e)}function _n(e){return e.ttl===void 0?e:{...e,ttl:U(e.ttl)}}function vn(e){let t={};return e.gt!==void 0&&(t.gt=e.gt),e.gte!==void 0&&(t.gte=e.gte),e.lt!==void 0&&(t.lt=e.lt),e.lte!==void 0&&(t.lte=e.lte),e.reverse!==void 0&&(t.reverse=e.reverse),e.limit!==void 0&&(t.limit=e.limit),t}const yn={},bn=/* @__PURE__ */ new Uint8Array,G=4294967295,xn=8389662,Sn=4194304,Cn=4096,wn=Array.from({length:256},(e,t)=>t.toString(16).padStart(2,`0`));function Tn(e,t,n){let r=e.get(t);if(r!==void 0)return r;let i=n();return e.set(t,i),i}function En(t){return e(t)&&t.type===`moyodb:persistence-bridge:response`&&typeof t.id==`number`&&typeof t.granted==`boolean`}var Dn=class{port=null;nextRequestId=1;pending=/* @__PURE__ */ new Map;readyResolve=null;ready;constructor(){this.ready=new Promise(e=>{this.readyResolve=e}),self.addEventListener(`message`,this.handleInitMessage)}async persisted(){return this.request(`persisted`)}async persist(){return this.request(`persist`)}close(){self.removeEventListener(`message`,this.handleInitMessage),this.readyResolve&&=(this.readyResolve(null),null),this.port&&=(this.port.onmessage=null,this.port.close(),null);for(let e of this.pending.values())e.resolve(!1);this.pending.clear()}async request(e){let t=await this.ready;return!t||this.port!==t?!1:new Promise(n=>{let r=this.nextRequestId;this.nextRequestId+=1,this.pending.set(r,{resolve:n});let i={type:`moyodb:persistence-bridge:request`,id:r,op:e};try{t.postMessage(i)}catch{this.pending.delete(r),n(!1)}})}handleInitMessage=e=>{if(e.origin!==``&&e.origin!==self.location.origin||e.data?.type!==`moyodb:persistence-bridge:init`||e.ports.length===0)return;let t=e.ports[0];if(this.port){t.close();return}this.port=t,this.port.onmessage=this.handleResponse,this.port.start(),self.removeEventListener(`message`,this.handleInitMessage),this.readyResolve?.(t),this.readyResolve=null};handleResponse=e=>{let t=e.data;if(!En(t))return;let n=this.pending.get(t.id);n&&(this.pending.delete(t.id),n.resolve(!!t.granted))}};async function On(){let e=navigator.storage;if(typeof e.estimate!=`function`)return{usage:0,quota:0};let t=await e.estimate();return{usage:t.usage??0,quota:t.quota??0}}function K(e){let t=``;for(let n=0;n<e.byteLength;n+=1)t+=wn[e[n]];return t}function q(e,t){if(e.byteLength!==t.byteLength)return!1;for(let n=0;n<e.byteLength;n+=1)if(e[n]!==t[n])return!1;return!0}function kn(e){let t=vn(e);for(let e of[`gt`,`gte`,`lt`,`lte`]){let n=t[e];n!==void 0&&(t[e]=n.slice())}return t}function An(e,t){for(let n of[`gt`,`gte`,`lt`,`lte`]){let r=e[n],i=t[n];if(r===void 0?i!==void 0:i===void 0||!q(r,i))return!1}return e.reverse===t.reverse&&e.limit===t.limit}function J(e){return e instanceof Uint8Array?e.byteOffset===0&&e.byteLength===e.buffer.byteLength?e:e.slice():new Uint8Array(e)}function jn(t){if(!e(t))return null;let n=t.name??t.code;return typeof n==`string`?n:null}function Y(e,t){return jn(e)===t}const Mn=O(`BDBIDX1`),Nn=new TextDecoder(`utf-8`,{fatal:!0});function Pn(e,t){if(t.length===0)return e;let n=O(JSON.stringify(nn(t))),r=/* @__PURE__ */ new ArrayBuffer(4);new DataView(r).setUint32(0,n.byteLength,!0);let i=new Uint8Array(e.byteLength+n.byteLength+4+Mn.byteLength),a=0;return i.set(e,a),a+=e.byteLength,i.set(n,a),a+=n.byteLength,i.set(new Uint8Array(r),a),a+=4,i.set(Mn,a),i}function Fn(e){let t=Mn.byteLength;if(e.byteLength<t+4)return{snapshot:e,indexes:[]};let n=e.byteLength-t;if(!q(e.subarray(n),Mn))return{snapshot:e,indexes:[]};let r=n-4;if(r<0)return{snapshot:e,indexes:[]};let i=r-new DataView(e.buffer,e.byteOffset+r,4).getUint32(0,!0);if(i<0)throw Z(`CorruptionError`,`invalid snapshot index trailer length`);let a;try{a=JSON.parse(Nn.decode(e.subarray(i,r)))}catch(e){throw Z(`CorruptionError`,`invalid snapshot index trailer: ${String(e)}`)}return{snapshot:e.subarray(0,i),indexes:Ut(a)}}function In(e){return new BroadcastChannel(`db:${e}:events`)}function X(e,t){let n=In(e);try{n.postMessage({type:t,dbName:e,txid:null})}finally{n.close()}}var Ln=class{releaseResolver=null;requestPromise=null;held=!1;async acquire(e,t){let r=new Promise(e=>{this.releaseResolver=e}),i=`db:${e}:owner`;if(t===0){let t=null,n=new Promise(e=>{t=e}),a=navigator.locks.request(i,{mode:`exclusive`,ifAvailable:!0},async e=>e?(this.held=!0,t?.(!0),await r,!0):(t?.(!1),!1));if(!await n)throw Z(`DatabaseBusyError`,`database ${e} is already owned by another tab`);this.requestPromise=a;return}let a=new AbortController,o=setTimeout(()=>a.abort(),n(t)),s=null,c=new Promise(e=>{s=e});this.requestPromise=navigator.locks.request(i,{mode:`exclusive`,signal:a.signal},async e=>(clearTimeout(o),this.held=!0,s?.(),await r,!0));try{await Promise.race([c,this.requestPromise])}catch{if(!this.held)throw Z(`DatabaseBusyError`,`timed out waiting for ownership of ${e}`)}}async release(){if(this.held){this.releaseResolver?.();try{await this.requestPromise}finally{this.releaseResolver=null,this.requestPromise=null,this.held=!1}}}},Rn=class{options;dbName=null;engine=null;events=null;lease=null;wasmReady=null;persistenceBridge;txChanges=/* @__PURE__ */ new Map;txModes=/* @__PURE__ */ new Map;primaryCursors=/* @__PURE__ */ new Map;nextPrimaryCursorId=1;txIndexSchemas=/* @__PURE__ */ new Map;indexesBySchema=/* @__PURE__ */ new WeakMap;txEnsuredRawStores=/* @__PURE__ */ new Map;txIndexSchemaChanged=/* @__PURE__ */ new Set;txStoreCompression=/* @__PURE__ */ new Map;committedIndexes=null;committedStoreCompression=null;openOptions=null;maintenanceOperation=null;constructor(e={}){this.options=e,this.persistenceBridge=e.persistence??new Dn}async open(e){if(this.engine)return;Bn(),zn(),this.dbName=e.dbName,this.events=new BroadcastChannel(`db:${e.dbName}:events`),this.lease=new Ln;let t=null;try{await this.lease.acquire(e.dbName,e.options.ownerWaitMs),t=new(await(this.loadWasm())).WasmEngine,await t.open(e.dbName,{create_if_missing:e.options.createIfMissing,cache_pages:e.options.cachePages}),e.options.changeFeed&&Vn(t,e.options.changeFeed),e.options.debugFailpoint&&t.set_failpoint(e.options.debugFailpoint),this.engine=t,this.openOptions=e.options,this.clearRuntimeCaches(),this.maintenanceOperation=null,this.events.postMessage({type:`owner_changed`,dbName:e.dbName,txid:null})}catch(e){throw await this.cleanupAfterFailedOpen(t),$(e)}}async close(){this.ensureNotInMaintenance();let e=this.dbName;this.clearRuntimeCaches();try{this.engine?.close()}catch(e){throw $(e)}finally{this.engine=null,e&&this.events&&this.events.postMessage({type:`db_closed`,dbName:e,txid:null}),this.events?.close(),this.events=null,e&&this.lease&&await this.lease.release(),e&&X(e,`owner_changed`),this.disposePersistenceBridge(),this.lease=null,this.dbName=null,this.openOptions=null,this.maintenanceOperation=null}}async destroy(){this.ensureNotInMaintenance();let e=this.dbName;if(!e)return;let t=null;try{this.rollbackAllTransactions(),this.engine?.abandon(),await(await this.loadWasm()).deleteDB(e),X(e,`db_deleted`)}catch(e){t=e}finally{if(this.engine=null,this.clearRuntimeCaches(),this.events?.close(),this.events=null,this.lease)try{await this.lease.release()}catch(e){t===null&&(t=e)}X(e,`owner_changed`),this.disposePersistenceBridge(),this.lease=null,this.dbName=null,this.openOptions=null,this.maintenanceOperation=null}if(t!==null)throw $(t)}async deleteDB(e){Bn(),zn();let t=new Ln,n=null,r=!1;try{await t.acquire(e,0),r=!0,await(await this.loadWasm()).deleteDB(e),X(e,`db_deleted`)}catch(e){n=e}finally{try{await t.release()}catch(e){n===null&&(n=e)}r&&X(e,`owner_changed`)}if(n!==null)throw $(n)}begin(e){this.recoverEngineIfNeeded();let t=this.loadCommittedIndexSchema(),n=this.loadCommittedStoreCompression(),r=W(this.withEngine(t=>t.begin_tx(e)));return this.txChanges.set(r,/* @__PURE__ */ new Map),this.txModes.set(r,e),this.txIndexSchemas.set(r,t),this.txStoreCompression.set(r,{owned:!1,values:n}),Promise.resolve(r)}commit(e){let t=this.txChanges.get(e)??/* @__PURE__ */ new Map,n=this.txIndexSchemaChanged.has(e)?this.txIndexSchemas.get(e):void 0,r=this.txStoreCompression.get(e),i=this.txModes.get(e),a;try{a=W(this.withEngine(t=>t.commit_tx(U(e))))}catch(t){try{this.engine&&!this.engine.needs_recovery()&&this.withEngine(t=>t.rollback_tx(U(e)))}catch{}this.cleanupTxState(e);let n=this.recoverEngineIfNeeded();if(!n?.pendingCommitted||n.pendingTxid===null||Y(t,`RecoveryRequiredError`)||Y(t,`InjectedFailureError`))throw t;a=n.pendingTxid}if(n&&(this.committedIndexes=H(n)),i===`readwrite`&&r&&(this.committedStoreCompression=r.values),this.cleanupTxState(e),this.dbName&&this.events){let e={type:`commit_applied`,dbName:this.dbName,txid:a,stores:this.finalizeTrackedChanges(t)};this.events.postMessage(e)}return Promise.resolve(a)}rollback(e){try{this.withEngine(t=>t.rollback_tx(U(e)))}finally{this.cleanupTxState(e)}return Promise.resolve()}async autocommit(e,t,n){let r=await this.begin(e),i=this[t],a;try{a=await i.apply(this,[r,...n])}catch(e){try{await this.rollback(r)}catch{}throw e}return e===`readwrite`?await this.commit(r):await this.rollback(r),a}createStore(e,t,n={}){let r=B(t)?!1:n.compression??`snappy`;return this.txEnsuredRawStores.get(e)?.delete(t),this.withEngine(n=>n.create_store(U(e),t,{compression:r})),this.recordStoreCompressionCreate(e,t,r),this.ensureInternalStoresForStore(e,t),this.markStoreTouched(e,t),Promise.resolve()}dropStore(e,t){let n=this.indexesForStoreInTx(e,t);this.txEnsuredRawStores.get(e)?.delete(t),this.withEngine(n=>n.drop_store(U(e),t)),this.recordStoreCompressionDrop(e,t);for(let t of n)this.dropRawStoreIfExists(e,t.internalStore);return this.recordStoreLevelChange(e,t,`drop`),Promise.resolve()}clearStore(e,t){let n=this.indexesForStoreInTx(e,t);this.txEnsuredRawStores.get(e)?.delete(t),this.withEngine(n=>n.clear_store(U(e),t));for(let t of n)this.clearRawStoreIfExists(e,t.internalStore);return this.recordStoreLevelChange(e,t,`clear`),Promise.resolve()}async get(e,t,n){return this.readStoreValue(e,t,n)}async getMany(e,t,n){let r=this.withEngine(r=>r.get_many(U(e),t,n)),i=!B(t)&&this.storeCompressionForTx(e,t)!==!1;for(let e=0;e<r.length;e+=1){let t=r[e];t!==null&&(r[e]=J(t))}return i?this.decodeStoreValues(e,t,r):r}async getManyPacked(e,t,n){let r=J(this.withEngine(r=>r.get_many_packed(U(e),t,n)));return B(t)||this.storeCompressionForTx(e,t)===!1?le(r):this.decodeStoreValues(e,t,ue(r))}has(e,t,n){return Promise.resolve(this.withEngine(r=>r.has(U(e),t,n)))}async put(e,t,n,r,i={}){let a=this.indexesForStoreInTx(e,t);if(a.length===0){let a=await this.encodeStoreValueForWrite(e,t,r),o=this.withEngine(r=>r.put(U(e),t,n,a,_n(i)));this.recordPutChange(e,t,n,o);return}await this.putIndexedMany(e,t,[n,r],a,i)}async putMany(e,t,n,r={}){if(n.length===0)return;let i=this.indexesForStoreInTx(e,t);if(i.length===0){let i=await this.encodeEntriesForWrite(e,t,n),a;try{a=this.withEngine(n=>n.put_many(U(e),t,i,_n(r)))}catch(r){let i=Q(r);throw this.recordPutChanges(e,t,n,i),r}if(a.length!==n.length)throw Z(`InternalError`,`put_many outcome count mismatch: ${a.length} != ${n.length}`);this.recordPutChanges(e,t,n,a);return}let a=Array(n.length*2);for(let e=0;e<n.length;e+=1)a[e*2]=n[e][0],a[e*2+1]=n[e][1];await this.putIndexedMany(e,t,a,i,r)}async putManyPacked(e,t,n,r={}){let i=this.indexesForStoreInTx(e,t);if(i.length!==0){let a=ae(n);if(a.length%2!=0)throw Z(`WorkerProtocolError`,`packed putMany payload has an odd item count`);await this.putIndexedMany(e,t,a,i,r);return}let a=this.storeCompressionForTx(e,t)===!1?null:ae(n);if(a!==null&&a.length%2!=0)throw Z(`WorkerProtocolError`,`packed putMany payload has an odd item count`);let o=a===null?oe(n):a.filter((e,t)=>t%2==0);if(o.length===0)return;let s=a===null?n:await this.encodePackedEntriesForWrite(e,t,a,o),c;try{c=this.withEngine(n=>n.put_many_packed(U(e),t,s,_n(r)))}catch(n){let r=Q(n);throw this.recordPutKeyChanges(e,t,o,r),n}if(c.length!==o.length)throw Z(`InternalError`,`put_many_packed outcome count mismatch: ${c.length} != ${o.length}`);this.recordPutKeyChanges(e,t,o,c)}async delete(e,t,n){let r=this.indexesForStoreInTx(e,t),i=r.length===0?null:await this.readStoreValue(e,t,n),a=i===null?null:en(i),o=a===null?[]:r.map(e=>({def:e,logicalKey:a(e)}));if(!this.withEngine(r=>r.delete(U(e),t,n)))return this.recordDeleteChange(e,t,n,!1),!1;for(let t of o)t.logicalKey!==null&&this.deleteIndexEntryIfPresent(e,t.def,t.logicalKey,n);return this.recordDeleteChange(e,t,n,!0),!0}async deleteMany(e,t,n){if(n.length!==0){if(this.indexesForStoreInTx(e,t).length===0){let r;try{r=this.withEngine(r=>r.delete_many(U(e),t,n))}catch(r){let i=Q(r);for(let r=0;r<i.length&&r<n.length;r+=1)this.recordDeleteChange(e,t,n[r],i[r]);throw r}if(r.length!==n.length)throw Z(`InternalError`,`delete_many outcome count mismatch: ${r.length} != ${n.length}`);for(let i=0;i<n.length;i+=1)this.recordDeleteChange(e,t,n[i],r[i]);return}for(let r of n)await this.delete(e,t,r)}}async deleteManyPacked(e,t,n){let r=this.indexesForStoreInTx(e,t),i=ae(n);if(i.length===0)return;if(r.length!==0){await this.deleteMany(e,t,i);return}let a;try{a=this.withEngine(r=>r.delete_many_packed(U(e),t,n))}catch(n){let r=Q(n);for(let n=0;n<r.length&&n<i.length;n+=1)this.recordDeleteChange(e,t,i[n],r[n]);throw n}if(a.length!==i.length)throw Z(`InternalError`,`delete_many_packed outcome count mismatch: ${a.length} != ${i.length}`);for(let n=0;n<i.length;n+=1)this.recordDeleteChange(e,t,i[n],a[n]===1)}async applyBatch(e,t,n){if(n.length!==0){if(this.indexesForStoreInTx(e,t).length===0){let r=await this.encodeBatchOpsForWrite(e,t,n),i;try{i=this.withEngine(n=>n.apply_batch(U(e),t,r))}catch(r){throw this.recordBatchOutcomes(e,t,n,Wn(r)),r}if(i.length!==n.length)throw Z(`InternalError`,`apply_batch outcome count mismatch: ${i.length} != ${n.length}`);this.recordBatchOutcomes(e,t,n,i);return}for(let r of n)r.kind===`put`?await this.put(e,t,r.key,r.value):await this.delete(e,t,r.key)}}async applyBatchPacked(e,t,n){if(this.indexesForStoreInTx(e,t).length!==0||this.storeCompressionForTx(e,t)!==!1){let r=se(n);if(r.length===0)return;await this.applyBatch(e,t,r);return}let r=ce(n);if(r.length===0)return;let i;try{i=this.withEngine(r=>r.apply_batch_packed(U(e),t,n))}catch(n){throw this.recordBatchKeyOutcomes(e,t,r,Wn(n)),n}if(i.length!==r.length)throw Z(`InternalError`,`apply_batch_packed outcome count mismatch: ${i.length} != ${r.length}`);for(let n=0;n<r.length;n+=1){let a=r[n];a.kind===`put`?this.recordPutChange(e,t,a.key,i[n]===1):this.recordDeleteChange(e,t,a.key,i[n]===1)}}async scan(e,t,n){return this.readStoreScan(e,t,n)}async scanPage(e){if(!Number.isSafeInteger(e.maxRows)||e.maxRows<=0||e.maxRows>G||!Number.isSafeInteger(e.maxBytes)||e.maxBytes<4||e.maxBytes>G)throw Z(`InvalidRangeError`,`scan page budgets must be positive u32 integers; maxBytes must be at least 4`);let t=e.cursorId,n=t===void 0?void 0:this.primaryCursors.get(t);if(t!==void 0){if(!n)throw Z(`TransactionClosedError`,`scan cursor is closed`);if(n.store!==e.store||n.callerTxId!==e.txId||!An(n.range,e.range??yn))throw Z(`InvalidRangeError`,`scan continuation does not match the cursor`)}else{let r=e.txId===void 0,i=e.txId??await this.begin(`readonly`),a=kn(e.range??yn),o;try{o=this.withEngine(t=>t.open_scan_cursor(U(i),e.store,vn(a),!1))}catch(e){if(r)try{await this.rollback(i)}catch{}throw e}t=this.nextPrimaryCursorId++,n={engineId:o,txId:i,ownsTx:r,store:e.store,range:a,callerTxId:e.txId},this.primaryCursors.set(t,n)}try{let r=this.withEngine(t=>t.scan_cursor_next(n.engineId,e.maxRows,e.maxBytes)),i=J(r.packet),a=i.byteLength<4?-1:new DataView(i.buffer,i.byteOffset,4).getUint32(0,!0);if(a!==r.rowCount||a>e.maxRows||i.byteLength>e.maxBytes)throw Z(`CorruptionError`,`scan cursor returned an invalid page budget or count`);let o=this.storeCompressionForTx(n.txId,n.store)===!1?null:me(i),s=i.byteLength;if(o!==null){s=4;for(let t of o)if(t.value=await this.decodeStoreValue(n.txId,n.store,t.value),s+=8+t.key.byteLength+t.value.byteLength,s>e.maxBytes)throw Z(`ValueTooLargeError`,`decoded scan page exceeds maxBytes`)}return r.exhausted&&await this.closeCursor(t),{rows:o??fe(i),done:r.exhausted,bytes:s,...r.exhausted?{}:{cursorId:t}}}catch(e){try{await this.closeCursor(t)}catch{}throw e}}async closeCursor(e){let t=this.primaryCursors.get(e);if(t){this.primaryCursors.delete(e);try{this.withEngine(e=>e.close_scan_cursor(t.engineId))}finally{t.ownsTx&&await this.rollback(t.txId)}}}async getByIndex(e,t,n,r){let i=this.resolveIndexDefinition(e,t,n),a=await this.loadVisibleIndexPage(e,i,{gte:r,lte:r},null,1);return a.rows.length===0?null:a.rows[0].value}async scanByIndex(e,t,n,r={}){let i=this.resolveIndexDefinition(e,t,n),a=[],o=r.limit??1/0,s=null;for(;o>0;){let t=await this.loadVisibleIndexPage(e,i,r,s,Math.min(o,256));if(a.push(...t.rows),o-=t.rows.length,t.cursor===null)break;s=t.cursor}return a}async scanByIndexPage(e,t,n,r,i,a,o=xn){if(!Number.isSafeInteger(a)||a<=0)throw Z(`InvalidRangeError`,`index scan page limit must be a positive integer`);if(!Number.isSafeInteger(o)||o<4||o>G)throw Z(`InvalidRangeError`,`index scan page maxBytes must be a u32 integer of at least 4`);let s=this.resolveIndexDefinition(e,t,n);return this.loadVisibleIndexPage(e,s,r,i,a,o)}getIndexes(e){return Promise.resolve(nn(e===void 0?this.loadCommittedIndexSchema():this.indexSchemaForTx(e)))}async reconcileIndexes(e,t){let n=Ut(t);this.ensureRawStore(e,z);let r=this.readIndexSchemaInTx(e),i=new Set(n.map(e=>e.internalStore));for(let t of r)i.has(t.internalStore)||this.dropRawStoreIfExists(e,t.internalStore);this.clearRawStoreIfExists(e,z);let a=null,o=0,s=null,c=typeof this.engine?.has_many==`function`,l=/* @__PURE__ */ new Map;for(let t of n){if(a!==t.store&&(l.clear(),o=0,s=null,a=t.store),this.ensureRawStore(e,t.internalStore),this.clearRawStoreIfExists(e,t.internalStore),this.rawStoreExistsInTx(e,t.store)){let n;if(s!==null){let r=this.withEngine(n=>n.has_many(U(e),t.store,s.map(e=>e.key)));if(r.length!==s.length)throw Z(`InternalError`,`has_many outcome count mismatch: ${r.length} != ${s.length}`);n=s.filter((e,t)=>r[t])}else if(n=await this.readStoreScan(e,t.store,yn),c&&n.length<=Cn){let e=0;for(let t of n)if(e+=t.key.byteLength+t.value.byteLength,e>Sn)break;e<=Sn&&(s=n)}for(let r of n){let n=K(r.key),i=l.get(n),a;if(i&&(i.bytes===r.value||q(i.bytes,r.value)))a=i.document,i.bytes=r.value;else{a=dn(r.value);let e=i?.inputBytes??0,t=r.key.byteLength+r.value.byteLength;(i||l.size<Cn)&&o-e+t<=Sn?(l.set(n,{bytes:r.value,inputBytes:t,document:a}),o+=t-e):i&&(l.delete(n),o-=e)}let s=tn(t,a);s!==null&&(await this.assertUniqueIndexAvailability(e,t,s,r.key),this.putIndexEntry(e,t,this.buildIndexEntryKey(t,s,r.key),bn))}}this.putRawValue(e,z,qt(t.store,t.name),Jt(t))}this.txIndexSchemas.set(e,H(n)),this.txIndexSchemaChanged.add(e)}listStores(){return Promise.resolve(this.currentStoreNames())}getVersion(){return Promise.resolve(W(this.withEngine(e=>e.get_schema_version())))}async changesSince(e,t={}){let n=t.stores?.filter(e=>!B(e)),r={...t,stores:n?[...n]:void 0,limit:n?t.limit:void 0},i=this.withEngine(t=>t.changes_since(U(e),r)),a=n?new Set(n):null,o=[];for(let e of i.changes){if(B(e.store)||a&&!a.has(e.store))continue;let n=t.limit===void 0||o.length<t.limit?J(e.key):null,r;e.value!==void 0&&(r=await this.decodeStoreValueForFeed(e.store,J(e.value))),n!==null&&o.push({txId:W(e.txId),store:e.store,key:n,kind:e.kind,value:r})}return{latestTxId:W(i.latestTxId),changes:o}}setSchemaVersion(e,t){return this.withEngine(n=>n.set_schema_version(U(e),U(t))),Promise.resolve()}async exportSnapshot(e={}){let t=H(this.loadCommittedIndexSchema());return await jt(Pn(J(this.withEngine(e=>e.export_snapshot())),t),e.compression??!1)}async importSnapshot(e){this.rollbackAllTransactions();let t=Fn(await Mt(e));this.withEngine(e=>e.import_snapshot(t.snapshot)),this.committedIndexes=[],this.committedStoreCompression=null,await this.applyCommittedIndexSchema(t.indexes)}async reset(){let e=this.dbName;if(!e)throw Z(`InternalError`,`engine is not open`);let t=H(this.loadCommittedIndexSchema());this.rollbackAllTransactions();let n=this.currentStoreNames().map(e=>({store:e,changes:[{key:/* @__PURE__ */ new Uint8Array,kind:`clear`}]})),r=W(this.withEngine(e=>e.reset()));if(this.committedIndexes=[],await this.applyCommittedIndexSchema(t),this.events){let t={type:`commit_applied`,dbName:e,txid:r,stores:n};this.events.postMessage(t)}}async compact(){return this.runCompactionOperation(`compact`)}async rebuild(){return this.runCompactionOperation(`rebuild`)}stats(){let e=this.withEngine(e=>e.stats());return Promise.resolve({...e,db_id:W(e.db_id),catalog_root_page_id:W(e.catalog_root_page_id),next_page_id:W(e.next_page_id),last_committed_txid:W(e.last_committed_txid),last_replayed_wal_offset:W(e.last_replayed_wal_offset),manifest_len:W(e.manifest_len),main_len:W(e.main_len),wal_len:W(e.wal_len),health:Un(e.health),store_count:this.currentStoreNames().length})}async storageInfo(){let[e,t,n]=await Promise.all([this.dbDirectorySize(),On(),this.persistenceBridge.persisted()]);return{dbSize:e,originUsage:t.usage,originQuota:t.quota,persisted:n}}async requestPersistence(){return this.persistenceBridge.persist()}setFailpoint(e){return this.withEngine(t=>t.set_failpoint(e)),Promise.resolve()}requireDbName(){if(!this.dbName)throw Z(`InternalError`,`engine is not open`);return this.dbName}ensureNotInMaintenance(){if(this.maintenanceOperation)throw Z(`DatabaseBusyError`,`database ${this.dbName??`database`} is busy: ${this.maintenanceOperation} in progress`)}currentCachePages(){return this.openOptions?.cachePages??256}async dbDirectorySize(){return(await this.loadWasm()).dbDirectorySize(this.requireDbName())}async applyCommittedIndexSchema(e){let t=H(e);if(t.length===0){this.committedIndexes=[];return}let n=W(this.withEngine(e=>e.begin_tx(`readwrite`),{allowDuringMaintenance:!0}));this.txChanges.set(n,/* @__PURE__ */ new Map),this.txModes.set(n,`readwrite`),this.txStoreCompression.set(n,{owned:!1,values:this.loadCommittedStoreCompression()});try{await this.reconcileIndexes(n,nn(t)),this.withEngine(e=>e.commit_tx(U(n)),{allowDuringMaintenance:!0}),this.committedIndexes=H(t)}catch(e){try{this.withEngine(e=>e.rollback_tx(U(n)),{allowDuringMaintenance:!0})}catch{}throw e}finally{this.cleanupTxState(n)}}async runCompactionOperation(e){let t=this.requireDbName();if(this.maintenanceOperation)throw Z(`DatabaseBusyError`,`database ${t} is busy: ${this.maintenanceOperation} in progress`);this.maintenanceOperation=e;let n=performance.now(),r=await this.loadWasm(),i=null,a=null,o=!1;try{let s=await r.dbDirectorySize(t),c=H(this.loadCommittedIndexSchema());this.rollbackAllTransactions({allowDuringMaintenance:!0});let l=await r.readActiveGeneration(t);a=(await r.prepareRebuildTarget(t)).generationName,i=new r.WasmEngine,await i.openGeneration(t,a,{create_if_missing:!0,cache_pages:this.currentCachePages()});let u=i;if(this.withEngine(t=>e===`rebuild`?t.compact_into_skipping_stores(u,[...c.map(e=>e.internalStore),z]):t.compact_into(u),{allowDuringMaintenance:!0}),e===`rebuild`&&c.length>0){let e=this.engine,t=this.maintenanceOperation;this.engine=u,this.maintenanceOperation=null;try{this.committedIndexes=[],this.committedStoreCompression=null,await this.applyCommittedIndexSchema(c)}finally{this.engine=e,this.maintenanceOperation=t,this.committedStoreCompression=null}}try{await r.swapActiveGeneration(t,a,l),o=!0}catch(e){if(o=await Hn(r,t)===a,!o)throw e}let d=this.engine;this.engine=i,i=null,this.committedIndexes=c,this.committedStoreCompression=null;try{d?.abandon()}catch{}try{await r.cleanupInactiveEntries(t)}catch{}let f=await r.dbDirectorySize(t);return{sizeBefore:s,sizeAfter:f,reclaimedBytes:Math.max(0,s-f),durationMs:performance.now()-n}}catch(e){if(!o){this.committedIndexes=null,this.committedStoreCompression=null;try{i?.abandon()}catch{}if(a!==null){let e=await Hn(r,t);if(e!==void 0&&e!==a)try{await r.cleanupInactiveEntries(t)}catch{}}}throw $(e)}finally{this.maintenanceOperation=null}}recoverEngineIfNeeded(){let e=this.engine;if(!e||!e.needs_recovery())return null;let t;try{t=e.recover()}catch(e){throw Z(`RecoveryRequiredError`,`database ${this.dbName??``} needs recovery and recovery failed: ${$(e).message}`)}finally{this.clearRuntimeCaches()}return{pendingTxid:gn(t.pendingTxid),pendingCommitted:t.pendingCommitted===!0}}cleanupTxState(e){for(let[t,n]of this.primaryCursors)if(n.txId===e){this.primaryCursors.delete(t);try{this.engine?.close_scan_cursor(n.engineId)}catch{}}this.txChanges.delete(e),this.txModes.delete(e),this.txIndexSchemas.delete(e),this.txEnsuredRawStores.delete(e),this.txIndexSchemaChanged.delete(e),this.txStoreCompression.delete(e)}getOrCreateTrackedTxn(e){return Tn(this.txChanges,e,()=>/* @__PURE__ */ new Map)}getOrCreateTrackedStore(e,t){return Tn(this.getOrCreateTrackedTxn(e),t,()=>({touched:!1,storeLevel:null,keys:/* @__PURE__ */ new Map}))}recordStoreLevelChange(e,t,n){if(B(t))return;let r=this.getOrCreateTrackedStore(e,t);r.touched=!0,r.storeLevel=n,r.keys.clear()}recordPutChange(e,t,n,r){this.recordKeyChange(e,t,n,r,`put`)}recordPutChanges(e,t,n,r){if(B(t))return;let i=this.getOrCreateTrackedStore(e,t);i.touched=!0;let a=Math.min(n.length,r.length);for(let e=0;e<a;e+=1)this.setTrackedKeyChange(i,n[e][0],r[e],`put`)}recordPutKeyChanges(e,t,n,r){if(B(t))return;let i=this.getOrCreateTrackedStore(e,t);i.touched=!0;let a=Math.min(n.length,r.length);for(let e=0;e<a;e+=1)this.setTrackedKeyChange(i,n[e],r[e]===!0||r[e]===1,`put`)}recordDeleteChange(e,t,n,r){r&&this.recordKeyChange(e,t,n,!0,`delete`)}recordKeyChange(e,t,n,r,i){if(B(t))return;let a=this.getOrCreateTrackedStore(e,t);a.touched=!0,this.setTrackedKeyChange(a,n,r,i)}setTrackedKeyChange(e,t,n,r){let i=K(t),a=e.keys.get(i);e.keys.set(i,{key:a?.key??t.slice(),baselineExists:a?.baselineExists??n,finalKind:r})}markStoreTouched(e,t){B(t)||(this.getOrCreateTrackedStore(e,t).touched=!0)}recordBatchOutcomes(e,t,n,r){for(let i=0;i<r.length&&i<n.length;i+=1){let a=n[i],o=r[i];a.kind===`put`&&o.kind===`put`?this.recordPutChange(e,t,a.key,o.baselineExists):a.kind===`delete`&&o.kind===`delete`&&this.recordDeleteChange(e,t,a.key,o.deleted)}}recordBatchKeyOutcomes(e,t,n,r){for(let i=0;i<r.length&&i<n.length;i+=1){let a=n[i],o=r[i];a.kind===`put`&&o.kind===`put`?this.recordPutChange(e,t,a.key,o.baselineExists):a.kind===`delete`&&o.kind===`delete`&&this.recordDeleteChange(e,t,a.key,o.deleted)}}finalizeTrackedChanges(e){let t=[];for(let[n,r]of e){if(!r.touched||B(n))continue;let e=[];r.storeLevel!==null&&e.push({key:/* @__PURE__ */ new Uint8Array,kind:r.storeLevel});for(let t of r.keys.values())(t.finalKind!==`delete`||t.baselineExists)&&e.push({key:t.key,kind:t.finalKind});t.push({store:n,changes:e})}return t}rollbackAllTransactions(e={}){if(!this.engine||this.txChanges.size===0){this.clearTxCaches();return}let t=Array.from(this.txChanges.keys());for(let n of t)try{this.withEngine(e=>e.rollback_tx(U(n)),e)}finally{this.cleanupTxState(n)}}currentStoreNames(){return this.allRawStoreNames().filter(e=>!B(e))}allRawStoreNames(){return this.withEngine(e=>e.list_stores())}loadCommittedStoreCompression(){if(this.committedStoreCompression)return this.committedStoreCompression;let e=this.withEngine(e=>e.list_store_configs()),t=/* @__PURE__ */ new Map;for(let n of e){if(typeof n.name!=`string`)throw Z(`CorruptionError`,`invalid store config row: missing name`);let e=typeof n.flags==`bigint`?Number(n.flags):n.flags;if(typeof e!=`number`||!Number.isSafeInteger(e)||e<0)throw Z(`CorruptionError`,`invalid store flags for ${n.name}`);t.set(n.name,kt(e))}return this.committedStoreCompression=t,t}ensureTxStoreCompression(e){let t=this.txStoreCompression.get(e);if(t?.owned)return t.values;let n=new Map(t?.values);return this.txStoreCompression.set(e,{owned:!0,values:n}),n}recordStoreCompressionCreate(e,t,n){B(t)||this.ensureTxStoreCompression(e).set(t,n)}recordStoreCompressionDrop(e,t){B(t)||this.ensureTxStoreCompression(e).delete(t)}storeCompressionForTx(e,t){if(B(t))return!1;let n=this.txStoreCompression.get(e);return n?n.values.get(t)??!1:this.loadCommittedStoreCompression().get(t)??!1}async encodeEntriesForWrite(e,t,n){if(B(t))return n;let r=this.storeCompressionForTx(e,t);if(r===!1)return n;let i=[];for(let[e,t]of n)i.push([e,await I(t,r)]);return i}async encodePackedEntriesForWrite(e,t,n,r){let i=Array(n.length/2);for(let r=0;r<i.length;r+=1){let a=this.preparePutValue(e,t,n[r*2+1]);i[r]=a instanceof Promise?await a:a}return this.packPreparedPutEntries(r,i)}preparePutValue(e,t,n){let r=this.storeCompressionForTx(e,t);return r===`snappy`||r===!1?xt(n,r):I(n,r)}packPreparedPutEntries(e,t){let n=4+e.length*8;for(let r=0;r<e.length;r+=1)if(n+=e[r].byteLength+t[r].byteLength,n>G)throw Z(`WorkerProtocolError`,`compressed packed putMany exceeds the u32 byte limit`);let r=new Uint8Array(n),i=new DataView(r.buffer);i.setUint32(0,e.length*2,!0);let a=4+e.length*8;for(let n=0;n<t.length;n+=1){let o=e[n],s=t[n];i.setUint32(4+n*8,o.byteLength,!0),i.setUint32(8+n*8,s.byteLength,!0),r.set(o,a),a+=o.byteLength,s instanceof Uint8Array?(r.set(s,a),a+=s.byteLength):a=St(s,r,a)}return r}async putIndexedMany(e,t,n,r,i){let a=[],o=[],s=[],c=4,l=/* @__PURE__ */ new Set,u=/* @__PURE__ */ new Set,d=()=>{if(a.length===0)return;let n=a,r=o,d=s;a=[],o=[],s=[],c=4,l.clear(),u.clear();let f=this.packPreparedPutEntries(n,r),p;try{p=this.withEngine(n=>n.put_many_indexed_packed(U(e),t,f,d,_n(i)))}catch(r){let i=Q(r);throw i.length>0&&this.recordPutKeyChanges(e,t,n,i),r}if(p.length!==n.length)throw Z(`InternalError`,`put_many_indexed_packed outcome count mismatch: ${p.length} != ${n.length}`);this.recordPutKeyChanges(e,t,n,p)};for(let f=0;f<n.length/2;f+=1){let p=n[f*2],m=n[f*2+1],h=K(p);l.has(h)&&d();try{let n=await this.readStoreValue(e,t,p),i=n===null?null:en(n),g=en(m),_=r.map(e=>({def:e,oldLogicalKey:i===null?null:i(e),newLogicalKey:g(e),newPhysicalKey:null}));if(_.some(e=>e.def.unique&&e.newLogicalKey!==null&&u.has(`${e.def.internalStore}:${K(e.newLogicalKey)}`))){d(),--f;continue}this.ensureInternalStoresForDefinitions(e,r);for(let t of _)t.newLogicalKey!==null&&(t.newPhysicalKey=this.buildIndexEntryKey(t.def,t.newLogicalKey,p),(t.oldLogicalKey===null||!q(t.oldLogicalKey,t.newLogicalKey))&&await this.assertUniqueIndexAvailability(e,t.def,t.newLogicalKey,p));let v=this.preparePutValue(e,t,m),ee=v instanceof Promise?await v:v,y=[];for(let e of _)e.oldLogicalKey!==null&&(e.newLogicalKey===null||!q(e.oldLogicalKey,e.newLogicalKey))&&y.push({store:e.def.internalStore,kind:`delete`,key:Xt(e.oldLogicalKey,p)});for(let e of _)if(e.newPhysicalKey!==null&&y.push({store:e.def.internalStore,kind:`put`,key:e.newPhysicalKey}),e.def.unique)for(let t of[e.oldLogicalKey,e.newLogicalKey])t!==null&&u.add(`${e.def.internalStore}:${K(t)}`);a.push(p),o.push(ee),s.push(y),c+=8+p.byteLength+ee.byteLength;for(let e of y)c+=e.key.byteLength;l.add(h)}catch(e){throw d(),e}(i.ttl!==void 0||a.length>=64||c>=4194304)&&d()}d()}async encodeBatchOpsForWrite(e,t,n){if(B(t))return n;let r=this.storeCompressionForTx(e,t);if(r===!1)return n;let i=[];for(let e of n)i.push(e.kind===`put`?{kind:`put`,key:e.key,value:await I(e.value,r)}:e);return i}async encodeStoreValueForWrite(e,t,n){return B(t)?n:I(n,this.storeCompressionForTx(e,t))}async decodeStoreValue(e,t,n){return B(t)||this.storeCompressionForTx(e,t)===!1?n:At(n,{strict:!0})}async decodeStoreValueForFeed(e,t){return B(e)?t:At(t,{strict:(this.loadCommittedStoreCompression().get(e)??!1)!==!1})}async readStoreValue(e,t,n){let r=this.readRawValue(e,t,n);return r===null?null:this.decodeStoreValue(e,t,r)}async readStoreScan(e,t,n){let r=this.readRawScan(e,t,n);if(B(t)||this.storeCompressionForTx(e,t)===!1)return r;let i=r.map(e=>e.value);await this.decodeStoreValues(e,t,i);for(let e=0;e<r.length;e+=1)r[e].value=i[e];return r}async decodeStoreValues(e,t,n){let r={next:0,failed:!1,failure:void 0};if(await Promise.all(Array.from({length:Math.min(8,n.length)},async()=>{for(;!r.failed&&r.next<n.length;){let i=r.next++,a=n[i];if(a!==null)try{n[i]=await this.decodeStoreValue(e,t,a)}catch(e){r.failed||(r.failed=!0,r.failure=e)}}})),r.failed)throw r.failure;return n}indexesForStoreInTx(e,t){let n=this.indexSchemaForTx(e),r=this.indexesBySchema.get(n);if(!r){r=/* @__PURE__ */ new Map;for(let e of n){let t=r.get(e.store);t?t.push(e):r.set(e.store,[e])}this.indexesBySchema.set(n,r)}return r.get(t)??[]}resolveIndexDefinition(e,t,n){if(!this.rawStoreExistsInTx(e,t))throw Z(`StoreNotFoundError`,`store not found: ${t}`);let r=Kt(this.indexesForStoreInTx(e,t),t,n);if(!r)throw Z(`IndexNotFoundError`,`index not found: ${t}.${n}`);return r}indexSchemaForTx(e){let t=this.txIndexSchemas.get(e);if(t)return t;if(this.committedIndexes)return this.committedIndexes;let n=this.readIndexSchemaInTx(e);return this.committedIndexes=H(n),this.committedIndexes}loadCommittedIndexSchema(){if(this.committedIndexes)return this.committedIndexes;let e=W(this.withEngine(e=>e.begin_tx(`readonly`)));try{let t=this.readIndexSchemaInTx(e);return this.committedIndexes=H(t),this.committedIndexes}finally{this.withEngine(t=>t.rollback_tx(U(e)))}}readIndexSchemaInTx(e){if(!this.rawStoreExistsInTx(e,`__browserdb:indexes`))return[];let t=this.readRawScan(e,z,yn).map(e=>Yt(e.value));return t.sort(Wt),t}rawStoreExistsInTx(e,t){try{return this.readRawScan(e,t,{limit:0}),!0}catch(e){if(Y(e,`StoreNotFoundError`))return!1;throw e}}ensureRawStore(e,t){let n=this.txModes.get(e)===`readwrite`;n&&this.txEnsuredRawStores.get(e)?.has(t)||(this.ignoreNamedError(`StoreExistsError`,()=>{this.withEngine(n=>n.create_store(U(e),t))}),n&&Tn(this.txEnsuredRawStores,e,()=>/* @__PURE__ */ new Set).add(t))}clearRawStoreIfExists(e,t){try{this.withEngine(n=>n.clear_store(U(e),t))}catch(n){if(!Y(n,`StoreNotFoundError`))throw n;this.txEnsuredRawStores.get(e)?.delete(t)}}dropRawStoreIfExists(e,t){this.txEnsuredRawStores.get(e)?.delete(t),this.ignoreNamedError(`StoreNotFoundError`,()=>{this.withEngine(n=>n.drop_store(U(e),t))})}ensureInternalStoresForDefinitions(e,t){for(let n of t)this.ensureRawStore(e,n.internalStore)}ensureInternalStoresForStore(e,t){this.ensureInternalStoresForDefinitions(e,this.indexesForStoreInTx(e,t))}readRawValue(e,t,n){let r=this.withEngine(r=>r.get(U(e),t,n));return r===null?null:J(r)}readRawScan(e,t,n){let r=this.withEngine(r=>r.scan(U(e),t,vn(n)));for(let e of r)e.key=J(e.key),e.value=J(e.value);return r}readIndexKeyScan(e,t,n){if(typeof this.engine?.open_scan_cursor!=`function`||typeof this.engine?.scan_cursor_next!=`function`||typeof this.engine?.close_scan_cursor!=`function`)return this.readRawScan(e,t,n);let r=n.limit??512,i=4+r*1032,a=this.withEngine(r=>r.open_scan_cursor(U(e),t,vn(n),!0));try{let e=this.withEngine(e=>e.scan_cursor_next(a,r,i)),t=J(e.packet),n=me(t);if(n.length!==e.rowCount||n.length>r||t.byteLength>i||n.some(e=>e.value.byteLength!==0))throw Z(`CorruptionError`,`index key cursor returned an invalid page`);return n}finally{this.withEngine(e=>e.close_scan_cursor(a))}}putRawValue(e,t,n,r){this.withEngine(i=>i.put(U(e),t,n,r))}putIndexEntry(e,t,n,r){if(typeof this.engine?.put_index_entry_checked==`function`){let r=V(n).primaryKey,i=this.readNativeValueState(e,t.store,r);if(i?.revisionKnown){this.withEngine(a=>a.put_index_entry_checked(U(e),t.store,t.internalStore,r,n,i.revisionEpoch,i.revisionOrdinal));return}}this.putRawValue(e,t.internalStore,n,r)}readNativeValueState(e,t,n){if(typeof this.engine?.get_many_value_states!=`function`)return null;try{let r=new Uint8Array(8+n.byteLength),i=new DataView(r.buffer);i.setUint32(0,1,!0),i.setUint32(4,n.byteLength,!0),r.set(n,8);let a=J(this.withEngine(n=>n.get_many_value_states(U(e),t,r)));return this.decodeNativeValueStates(a,1)?.[0]??null}catch{return null}}packNativeKeys(e){let t=4+e.length*4;for(let n of e)t+=n.byteLength;let n=new Uint8Array(t),r=new DataView(n.buffer);r.setUint32(0,e.length,!0);let i=4+e.length*4;for(let t=0;t<e.length;t+=1){let a=e[t];r.setUint32(4+t*4,a.byteLength,!0),n.set(a,i),i+=a.byteLength}return n}decodeNativeValueStates(e,t){if(e.byteLength!==4+t*32)return null;let n=new DataView(e.buffer,e.byteOffset,e.byteLength);if(n.getUint32(0,!0)!==t)return null;let r=Array(t);for(let e=0;e<t;e+=1){let t=4+e*32,i=n.getUint32(t,!0),a=n.getBigUint64(t+12,!0),o=n.getBigUint64(t+20,!0);if(i&-8||(i&3)==3||i&4&&(!(i&3)||a===0n||o===0n))return null;r[e]={live:!!(i&1),expired:!!(i&2),revisionKnown:!!(i&4),expiresAt:n.getBigUint64(t+4,!0),revisionEpoch:a,revisionOrdinal:o,maxValueBytes:n.getUint32(t+28,!0)}}return r}inspectIndexedValue(e,t,n,r){let i=this.readNativeValueState(e,t.store,r);if(i===null)return`unknown`;if(!i.live)return i.expired&&this.txModes.get(e)===`readwrite`&&this.withEngine(n=>n.has(U(e),t.store,r))?`unknown`:`missing`;if(!i.revisionKnown)return`unknown`;let a=this.readNativeValueState(e,t.internalStore,n);return a?.live&&a.revisionKnown&&a.revisionEpoch===i.revisionEpoch&&a.revisionOrdinal===i.revisionOrdinal?`trusted`:`unknown`}deleteIndexEntryIfPresent(e,t,n,r){let i=this.buildIndexEntryKey(t,n,r);this.ignoreNamedError(`StoreNotFoundError`,()=>{this.withEngine(n=>n.delete(U(e),t.internalStore,i))})}buildIndexEntryKey(e,t,n){let r=Xt(t,n);if(r.byteLength>1024)throw Z(`KeyTooLargeError`,`index key too large for ${e.store}.${e.name}`);return r}async assertUniqueIndexAvailability(e,t,n,r){if(!t.unique)return;let i=Zt(n),a=null,o=1;for(;;){let s={...i,limit:o};a!==null&&(s.gt=a,delete s.gte);let c=this.readIndexKeyScan(e,t.internalStore,s);for(let i of c){a=i.key;let o=V(i.key);if(q(o.primaryKey,r))continue;let s=this.inspectIndexedValue(e,t,i.key,o.primaryKey);if(s===`missing`){this.cleanupStaleIndexRow(e,t,i.key);continue}if(s===`trusted`)throw Z(`UniqueIndexConstraintError`,`unique index constraint violation on ${t.store}.${t.name}`);let c=await this.readStoreValue(e,t.store,o.primaryKey);if(c===null){this.cleanupStaleIndexRow(e,t,i.key);continue}let l=$t(t,c);if(l===null||!q(l,n)){this.cleanupStaleIndexRow(e,t,i.key);continue}throw Z(`UniqueIndexConstraintError`,`unique index constraint violation on ${t.store}.${t.name}`)}if(c.length<o)return;o=Math.min(512,o*2)}}async loadVisibleIndexPage(e,t,n,r,i,a=xn){let{limit:o,...s}=n,c=Qt(s),l=c.reverse===!0,u=r,d=[],f=4,p=1;for(;;){let n=Math.min(512,Math.max(i-d.length,p)),r={...c,limit:n};u!==null&&(l?(delete r.lte,r.lt=u):(delete r.gte,r.gt=u));let o;try{o=this.readIndexKeyScan(e,t.internalStore,r)}catch(e){if(Y(e,`StoreNotFoundError`))return{rows:[],cursor:null};throw e}let s=d.length,m=0,h=0,g=null;for(let n=0;n<o.length;n+=1){n===h&&(m=n,g=this.readIndexPrimaryValues(e,t,o,n,Math.min(o.length,n+i-d.length),a-f),h=n+(g?.entries.length??1));let r=o[n],s=g?await this.resolveVisibleIndexedValue(e,t,r.key,g.entries[n-m],g.values[n-m],g.trusted[n-m]):await this.resolveVisibleIndexedRow(e,t,r.key);if(g!==null&&(g.values[n-m]=null),!s){u=r.key;continue}let c=f+8+s.key.byteLength+s.value.byteLength;if(c>a){if(d.length===0)throw Z(`ValueTooLargeError`,`indexed scan row exceeds maxBytes`);if(u===null)throw Z(`InternalError`,`indexed scan lost its continuation key`);return{rows:d,cursor:u.slice()}}if(d.push(s),f=c,u=r.key,d.length>=i)return{rows:d,cursor:r.key.slice()}}if(o.length<n)return{rows:d,cursor:null};p=d.length===s?Math.min(512,n*2):1}}readIndexPrimaryValues(e,t,n,r,i,a){if(this.txModes.get(e)!==`readonly`||i-r<=1||typeof this.engine?.get_many_value_sizes!=`function`&&typeof this.engine?.get_many_value_states!=`function`)return null;let o,s,c,l,u;try{o=n.slice(r,i).map(e=>V(e.key));let d=this.packNativeKeys(o.map(e=>e.primaryKey)),f=null,p=null,m;if(typeof this.engine?.get_many_value_states==`function`){if(f=this.decodeNativeValueStates(J(this.withEngine(n=>n.get_many_value_states(U(e),t.store,d))),o.length),f===null)return null;if(m=Uint32Array.from(f,e=>e.live?e.maxValueBytes:G),f.some(e=>e.live&&e.revisionKnown)){let a=this.packNativeKeys(n.slice(r,i).map(e=>e.key));if(p=this.decodeNativeValueStates(J(this.withEngine(n=>n.get_many_value_states(U(e),t.internalStore,a))),o.length),p===null)return null}}else m=this.withEngine(n=>n.get_many_value_sizes(U(e),t.store,d));if(m.length!==o.length)return null;let h=0;for(let e of o){let t=m[h];if(!Number.isSafeInteger(t)||t<0||t>G)return null;let n=t===G?0:8+e.primaryKey.byteLength+t;if(n>a)break;a-=n,h+=1}if(h<=1)return null;o.length=h,c=Array(h).fill(!1);let g=[];u=[],s=Array(h).fill(null);for(let e=0;e<h;e+=1){let t=f?.[e];(t===void 0||t.live)&&(g.push(o[e].primaryKey),u.push(e));let n=p?.[e];c[e]=!!(t?.live&&t.revisionKnown&&n?.live&&n.revisionKnown&&t.revisionEpoch===n.revisionEpoch&&t.revisionOrdinal===n.revisionOrdinal)}l=g.length===0?[]:this.withEngine(n=>n.get_many(U(e),t.store,g))}catch{return null}if(l.length!==u.length)throw Z(`InternalError`,`get_many outcome count mismatch: ${l.length} != ${u.length}`);for(let e=0;e<l.length;e+=1)s[u[e]]=l[e],l[e]=null;return{entries:o,values:s,trusted:c}}async resolveVisibleIndexedRow(e,t,n){let r=V(n),i=this.inspectIndexedValue(e,t,n,r.primaryKey);if(i===`missing`)return this.cleanupStaleIndexRow(e,t,n),null;let a=this.readRawValue(e,t.store,r.primaryKey);return this.resolveVisibleIndexedValue(e,t,n,r,a,i===`trusted`)}async resolveVisibleIndexedValue(e,t,n,r,i,a=!1){if(i===null)return this.cleanupStaleIndexRow(e,t,n),null;let o=await this.decodeStoreValue(e,t.store,J(i));if(!a){let i=$t(t,o);if(i===null||!q(i,r.logicalKey))return this.cleanupStaleIndexRow(e,t,n),null}return{key:r.primaryKey,value:o}}cleanupStaleIndexRow(e,t,n){if(this.txModes.get(e)===`readwrite`)try{this.withEngine(r=>r.delete(U(e),t.internalStore,n))}catch{}}async loadWasm(){return this.wasmReady||=this.options.loadWasm?this.options.loadWasm():(async()=>{let e=new URL(`../engine/moyodb_engine.js`,``+import.meta.url).href,t=new URL(`../engine/moyodb_engine_bg.wasm`,``+import.meta.url).href,n=await import(
|
|
2
|
+
/* @vite-ignore */
|
|
3
|
+
e);return await n.default({module_or_path:t}),n})(),this.wasmReady}withEngine(e,t={}){if(this.maintenanceOperation&&!t.allowDuringMaintenance&&this.ensureNotInMaintenance(),!this.engine)throw Z(`InternalError`,`engine is not open`);try{return e(this.engine)}catch(e){throw $(e)}}ignoreNamedError(e,t){try{t()}catch(t){if(Y(t,e))return;throw t}}clearTxCaches(){this.primaryCursors.clear(),this.txChanges.clear(),this.txModes.clear(),this.txIndexSchemas.clear(),this.txEnsuredRawStores.clear(),this.txIndexSchemaChanged.clear(),this.txStoreCompression.clear()}clearRuntimeCaches(){this.clearTxCaches(),this.committedIndexes=null,this.committedStoreCompression=null}async cleanupAfterFailedOpen(e){try{e?.abandon()}catch{}if(this.engine=null,this.clearRuntimeCaches(),this.events?.close(),this.events=null,this.lease)try{await this.lease.release()}catch{}this.lease=null,this.disposePersistenceBridge(),this.dbName=null,this.openOptions=null,this.maintenanceOperation=null}disposePersistenceBridge(){this.persistenceBridge.close()}};function zn(){if(typeof navigator.storage.getDirectory!=`function`)throw Z(`UnsupportedPlatformError`,`navigator.storage.getDirectory is unavailable`);if(typeof BroadcastChannel>`u`)throw Z(`UnsupportedPlatformError`,`BroadcastChannel is unavailable`);if(typeof FileSystemFileHandle>`u`||typeof FileSystemFileHandle.prototype.createSyncAccessHandle!=`function`)throw Z(`UnsupportedPlatformError`,`createSyncAccessHandle is unavailable`)}function Bn(){if(!self.isSecureContext)throw Z(`UnsupportedPlatformError`,`moyodb requires a secure context (HTTPS)`)}function Z(e,t){let n=Error(t);return n.name=e,Object.defineProperty(n,"code",{value:e,enumerable:!0,configurable:!0}),n}function Vn(e,t){let n=e.change_feed_policy(),r=gn(n.retainTxids);if(n.enabled===t.enabled&&(!t.enabled||r===t.retainTxids))return;let i=e.begin_tx(`readwrite`);try{e.set_change_feed_policy(i,{enabled:t.enabled,retainTxids:t.retainTxids}),e.commit_tx(i)}catch(t){try{e.rollback_tx(i)}catch{}throw $(t)}}async function Hn(e,t){try{return await e.readActiveGeneration(t)}catch{return}}function Un(e){return e.state===`recoveryRequired`?{state:`recoveryRequired`,reason:e.reason,pendingTxid:gn(e.pendingTxid)}:{state:e.state}}function Q(t){return!e(t)||!Array.isArray(t.partial)?[]:t.partial.filter(e=>typeof e==`boolean`)}function Wn(t){return!e(t)||!Array.isArray(t.partial)?[]:t.partial.filter(t=>!e(t)||typeof t.kind!=`string`?!1:t.kind===`put`&&typeof t.baselineExists==`boolean`||t.kind===`delete`&&typeof t.deleted==`boolean`)}function $(t){if(t instanceof Error)return t;if(e(t)){let e=Z(typeof t.code==`string`?t.code:typeof t.name==`string`?t.name:`Error`,typeof t.message==`string`?t.message:`Unknown error`);return`partial`in t&&Object.defineProperty(e,"partial",{value:t.partial,enumerable:!0,configurable:!0}),e}return Z(`Error`,String(t))}const Gn=new Rn;let Kn=Ie(Gn),qn=!1;self.addEventListener(`message`,t=>{if(t.origin!==``&&t.origin!==self.location.origin||!e(t.data)||t.data.type!==`moyodb:worker-port:init`||!t.ports[0])return;let n=t.ports[0];if(qn){n.close();return}qn=!0,Kn.close();let r={location:{origin:self.location.origin},postMessage:(e,t)=>n.postMessage(e,t??[]),addEventListener:(e,t)=>n.addEventListener(e,t),removeEventListener:(e,t)=>n.removeEventListener(e,t)};Kn=Ie(Gn,r),n.start()});
|
|
4
|
+
//# sourceMappingURL=browser-worker-DBt51gsS.js.map
|