@aztec/kv-store 0.0.1-commit.936cb2cae → 0.0.1-commit.949a33fd8

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (43) hide show
  1. package/dest/bench/shared_map_bench.d.ts +19 -0
  2. package/dest/bench/shared_map_bench.d.ts.map +1 -0
  3. package/dest/bench/shared_map_bench.js +91 -0
  4. package/dest/lmdb-v2/read_transaction.js +21 -19
  5. package/dest/sqlite-opfs/array.d.ts +21 -0
  6. package/dest/sqlite-opfs/array.d.ts.map +1 -0
  7. package/dest/sqlite-opfs/array.js +128 -0
  8. package/dest/sqlite-opfs/index.d.ts +7 -0
  9. package/dest/sqlite-opfs/index.d.ts.map +1 -0
  10. package/dest/sqlite-opfs/index.js +13 -0
  11. package/dest/sqlite-opfs/map.d.ts +35 -0
  12. package/dest/sqlite-opfs/map.d.ts.map +1 -0
  13. package/dest/sqlite-opfs/map.js +163 -0
  14. package/dest/sqlite-opfs/messages.d.ts +58 -0
  15. package/dest/sqlite-opfs/messages.d.ts.map +1 -0
  16. package/dest/sqlite-opfs/messages.js +5 -0
  17. package/dest/sqlite-opfs/multi_map.d.ts +16 -0
  18. package/dest/sqlite-opfs/multi_map.d.ts.map +1 -0
  19. package/dest/sqlite-opfs/multi_map.js +67 -0
  20. package/dest/sqlite-opfs/set.d.ts +13 -0
  21. package/dest/sqlite-opfs/set.d.ts.map +1 -0
  22. package/dest/sqlite-opfs/set.js +19 -0
  23. package/dest/sqlite-opfs/singleton.d.ts +13 -0
  24. package/dest/sqlite-opfs/singleton.d.ts.map +1 -0
  25. package/dest/sqlite-opfs/singleton.js +48 -0
  26. package/dest/sqlite-opfs/store.d.ts +70 -0
  27. package/dest/sqlite-opfs/store.d.ts.map +1 -0
  28. package/dest/sqlite-opfs/store.js +242 -0
  29. package/dest/sqlite-opfs/worker.d.ts +2 -0
  30. package/dest/sqlite-opfs/worker.d.ts.map +1 -0
  31. package/dest/sqlite-opfs/worker.js +194 -0
  32. package/package.json +10 -7
  33. package/src/bench/shared_map_bench.ts +111 -0
  34. package/src/lmdb-v2/read_transaction.ts +23 -23
  35. package/src/sqlite-opfs/array.ts +124 -0
  36. package/src/sqlite-opfs/index.ts +27 -0
  37. package/src/sqlite-opfs/map.ts +163 -0
  38. package/src/sqlite-opfs/messages.ts +28 -0
  39. package/src/sqlite-opfs/multi_map.ts +74 -0
  40. package/src/sqlite-opfs/set.ts +29 -0
  41. package/src/sqlite-opfs/singleton.ts +48 -0
  42. package/src/sqlite-opfs/store.ts +248 -0
  43. package/src/sqlite-opfs/worker.ts +162 -0
@@ -0,0 +1,163 @@
1
+ import { Buffer } from 'buffer';
2
+ import { Encoder } from 'msgpackr';
3
+ import { hash } from 'ohash';
4
+ import { fromBufferKey, toBufferKey } from 'ordered-binary';
5
+
6
+ import type { Key, Range, Value } from '../interfaces/common.js';
7
+ import type { AztecAsyncMap } from '../interfaces/map.js';
8
+ import type { SqlValue } from './messages.js';
9
+ import type { AztecSQLiteOPFSStore } from './store.js';
10
+
11
+ /** A map backed by SQLite in OPFS. Mirrors `IndexedDBAztecMap`. */
12
+ export class SQLiteOPFSAztecMap<K extends Key, V extends Value> implements AztecAsyncMap<K, V> {
13
+ protected readonly name: string;
14
+ protected readonly container: string;
15
+ protected readonly encoder = new Encoder();
16
+
17
+ constructor(
18
+ protected readonly store: AztecSQLiteOPFSStore,
19
+ mapName: string,
20
+ ) {
21
+ this.name = mapName;
22
+ this.container = `map:${mapName}`;
23
+ }
24
+
25
+ async getAsync(key: K): Promise<V | undefined> {
26
+ const rows = await this.store.allAsync('SELECT value FROM data WHERE slot = ? LIMIT 1', [this.slot(key)]);
27
+ if (rows.length === 0) {
28
+ return undefined;
29
+ }
30
+ const raw = rows[0][0];
31
+ return raw == null ? undefined : this.decodeValue(raw);
32
+ }
33
+
34
+ async hasAsync(key: K): Promise<boolean> {
35
+ const rows = await this.store.allAsync('SELECT 1 FROM data WHERE slot = ? LIMIT 1', [this.slot(key)]);
36
+ return rows.length > 0;
37
+ }
38
+
39
+ async sizeAsync(): Promise<number> {
40
+ const rows = await this.store.allAsync('SELECT COUNT(*) FROM data WHERE container = ?', [this.container]);
41
+ return Number(rows[0]?.[0] ?? 0);
42
+ }
43
+
44
+ async set(key: K, val: V): Promise<void> {
45
+ await this.store.runAsync(
46
+ `INSERT OR REPLACE INTO data (slot, container, key, key_count, hash, value)
47
+ VALUES (?, ?, ?, ?, ?, ?)`,
48
+ [this.slot(key), this.container, this.encodedKey(key), 1, hash(val), this.encoder.pack(val)],
49
+ );
50
+ }
51
+
52
+ async setMany(entries: { key: K; value: V }[]): Promise<void> {
53
+ if (entries.length === 0) {
54
+ return;
55
+ }
56
+ await this.store.transactionAsync(async () => {
57
+ for (const { key, value } of entries) {
58
+ await this.set(key, value);
59
+ }
60
+ });
61
+ }
62
+
63
+ swap(_key: K, _fn: (val: V | undefined) => V): Promise<void> {
64
+ throw new Error('Not implemented');
65
+ }
66
+
67
+ async setIfNotExists(key: K, val: V): Promise<boolean> {
68
+ return await this.store.transactionAsync(async () => {
69
+ if (await this.hasAsync(key)) {
70
+ return false;
71
+ }
72
+ await this.set(key, val);
73
+ return true;
74
+ });
75
+ }
76
+
77
+ async delete(key: K): Promise<void> {
78
+ await this.store.runAsync('DELETE FROM data WHERE slot = ?', [this.slot(key)]);
79
+ }
80
+
81
+ async *entriesAsync(range: Range<K> = {}): AsyncIterableIterator<[K, V]> {
82
+ const rows = await this.rangeQuery(range);
83
+ for (const row of rows) {
84
+ const [_slot, keyBlob, value] = row;
85
+ if (keyBlob == null || value == null) {
86
+ continue;
87
+ }
88
+ yield [this.decodeKey(keyBlob), this.decodeValue(value)];
89
+ }
90
+ }
91
+
92
+ async *valuesAsync(range: Range<K> = {}): AsyncIterableIterator<V> {
93
+ for await (const [, value] of this.entriesAsync(range)) {
94
+ yield value;
95
+ }
96
+ }
97
+
98
+ async *keysAsync(range: Range<K> = {}): AsyncIterableIterator<K> {
99
+ for await (const [key] of this.entriesAsync(range)) {
100
+ yield key;
101
+ }
102
+ }
103
+
104
+ protected async rangeQuery(range: Range<K>): Promise<Array<[string, Uint8Array, Uint8Array | null]>> {
105
+ // Inclusivity flips with direction to match the IndexedDB backend:
106
+ // forward: [start, end) reverse: (start, end]
107
+ // That asymmetry is load-bearing — tests pin the exact inclusivity at boundaries.
108
+ const reverse = !!range.reverse;
109
+ const parts: string[] = ['container = ?'];
110
+ const bind: SqlValue[] = [this.container];
111
+ if (range.start !== undefined) {
112
+ parts.push(reverse ? 'key > ?' : 'key >= ?');
113
+ bind.push(this.encodedKey(range.start));
114
+ }
115
+ if (range.end !== undefined) {
116
+ parts.push(reverse ? 'key <= ?' : 'key < ?');
117
+ bind.push(this.encodedKey(range.end));
118
+ }
119
+ const order = reverse ? 'DESC' : 'ASC';
120
+ let sql = `SELECT slot, key, value FROM data WHERE ${parts.join(' AND ')} ORDER BY key ${order}, key_count ${order}`;
121
+ if (range.limit !== undefined) {
122
+ sql += ' LIMIT ?';
123
+ bind.push(range.limit);
124
+ }
125
+ const rows = await this.store.allAsync(sql, bind);
126
+ return rows.map(r => [String(r[0]), r[1] as Uint8Array, r[2] as Uint8Array | null]);
127
+ }
128
+
129
+ protected decodeValue(val: SqlValue): V {
130
+ if (!(val instanceof Uint8Array)) {
131
+ return val as V;
132
+ }
133
+ const unpacked = this.encoder.unpack(val);
134
+ // msgpackr returns plain Uint8Array in browsers for packed Buffers. Callers that
135
+ // stored Buffers (walletDB uses Buffer.from(...).toString('utf8') round-trips)
136
+ // rely on Buffer-flavored behavior — re-wrap at the storage boundary, mirroring
137
+ // IndexedDBAztecMap.restoreBuffers.
138
+ if (unpacked instanceof Uint8Array && !Buffer.isBuffer(unpacked)) {
139
+ return Buffer.from(unpacked) as V;
140
+ }
141
+ return unpacked as V;
142
+ }
143
+
144
+ protected decodeKey(raw: Uint8Array): K {
145
+ const parsed = fromBufferKey(Buffer.from(raw));
146
+ if (Array.isArray(parsed)) {
147
+ return (parsed.length > 1 ? parsed : parsed[0]) as K;
148
+ }
149
+ return parsed as K;
150
+ }
151
+
152
+ protected encodedKey(key: K): Buffer {
153
+ return toBufferKey(this.normalizeKey(key));
154
+ }
155
+
156
+ protected normalizeKey(key: K): (string | number | Uint8Array)[] {
157
+ return Array.isArray(key) ? key : [key];
158
+ }
159
+
160
+ protected slot(key: K, index: number = 0): string {
161
+ return `map:${this.name}:slot:${this.normalizeKey(key)}:${index}`;
162
+ }
163
+ }
@@ -0,0 +1,28 @@
1
+ /**
2
+ * RPC protocol between the main thread and the SQLite worker.
3
+ * All requests carry a unique `id`; responses echo the same id so the main thread
4
+ * can resolve the right pending promise.
5
+ */
6
+
7
+ /** Matches `@sqlite.org/sqlite-wasm`'s internal SqlValue type. Boolean is not a native SQLite type. */
8
+ export type SqlValue = string | number | bigint | null | Uint8Array;
9
+
10
+ /** A row returned in 'array' rowMode — one value per column, in select order. */
11
+ export type ResultRow = SqlValue[];
12
+
13
+ export type WorkerRequest =
14
+ | { type: 'init'; id: number; dbName: string; ephemeral: boolean; poolDirectory?: string }
15
+ | { type: 'close'; id: number }
16
+ | { type: 'deleteDb'; id: number; dbName: string }
17
+ | { type: 'run'; id: number; sql: string; bind?: SqlValue[] }
18
+ | { type: 'all'; id: number; sql: string; bind?: SqlValue[] }
19
+ | { type: 'export'; id: number }
20
+ | { type: 'begin'; id: number }
21
+ | { type: 'commit'; id: number }
22
+ | { type: 'rollback'; id: number };
23
+
24
+ export type WorkerResponse =
25
+ | { type: 'ok'; id: number; rows?: ResultRow[]; changes?: number; bytes?: Uint8Array }
26
+ | { type: 'err'; id: number; message: string };
27
+
28
+ export type WorkerRequestType = WorkerRequest['type'];
@@ -0,0 +1,74 @@
1
+ import { hash } from 'ohash';
2
+
3
+ import type { Key, Value } from '../interfaces/common.js';
4
+ import type { AztecAsyncMultiMap } from '../interfaces/multi_map.js';
5
+ import { SQLiteOPFSAztecMap } from './map.js';
6
+
7
+ /**
8
+ * Multi-map backed by SQLite. Extends the base map with always-incrementing
9
+ * `key_count` per-key so the same slot is never reused across deletions — this
10
+ * matches the IndexedDB backend's sparse-multi-map semantics.
11
+ */
12
+ export class SQLiteOPFSAztecMultiMap<K extends Key, V extends Value>
13
+ extends SQLiteOPFSAztecMap<K, V>
14
+ implements AztecAsyncMultiMap<K, V>
15
+ {
16
+ override async set(key: K, val: V): Promise<void> {
17
+ const valueHash = hash(val);
18
+ await this.store.transactionAsync(async () => {
19
+ const exists = await this.store.allAsync(
20
+ 'SELECT 1 FROM data WHERE container = ? AND key = ? AND hash = ? LIMIT 1',
21
+ [this.container, this.encodedKey(key), valueHash],
22
+ );
23
+ if (exists.length > 0) {
24
+ return;
25
+ }
26
+ const maxRow = await this.store.allAsync('SELECT MAX(key_count) FROM data WHERE container = ? AND key = ?', [
27
+ this.container,
28
+ this.encodedKey(key),
29
+ ]);
30
+ const count = Number(maxRow[0]?.[0] ?? 0);
31
+ await this.store.runAsync(
32
+ `INSERT INTO data (slot, container, key, key_count, hash, value)
33
+ VALUES (?, ?, ?, ?, ?, ?)`,
34
+ [this.slot(key, count), this.container, this.encodedKey(key), count + 1, valueHash, this.encoder.pack(val)],
35
+ );
36
+ });
37
+ }
38
+
39
+ async *getValuesAsync(key: K): AsyncIterableIterator<V> {
40
+ const rows = await this.store.allAsync(
41
+ 'SELECT value FROM data WHERE container = ? AND key = ? ORDER BY key_count ASC',
42
+ [this.container, this.encodedKey(key)],
43
+ );
44
+ for (const row of rows) {
45
+ const raw = row[0];
46
+ if (raw instanceof Uint8Array) {
47
+ yield this.decodeValue(raw);
48
+ }
49
+ }
50
+ }
51
+
52
+ async getValueCountAsync(key: K): Promise<number> {
53
+ const rows = await this.store.allAsync('SELECT COUNT(*) FROM data WHERE container = ? AND key = ?', [
54
+ this.container,
55
+ this.encodedKey(key),
56
+ ]);
57
+ return Number(rows[0]?.[0] ?? 0);
58
+ }
59
+
60
+ async deleteValue(key: K, val: V): Promise<void> {
61
+ await this.store.runAsync('DELETE FROM data WHERE container = ? AND key = ? AND hash = ?', [
62
+ this.container,
63
+ this.encodedKey(key),
64
+ hash(val),
65
+ ]);
66
+ }
67
+
68
+ override async delete(key: K): Promise<void> {
69
+ await this.store.runAsync('DELETE FROM data WHERE container = ? AND key = ?', [
70
+ this.container,
71
+ this.encodedKey(key),
72
+ ]);
73
+ }
74
+ }
@@ -0,0 +1,29 @@
1
+ import type { Key, Range } from '../interfaces/common.js';
2
+ import type { AztecAsyncSet } from '../interfaces/set.js';
3
+ import { SQLiteOPFSAztecMap } from './map.js';
4
+ import type { AztecSQLiteOPFSStore } from './store.js';
5
+
6
+ /** Set backed by SQLite. Composes a Map<K, true>. */
7
+ export class SQLiteOPFSAztecSet<K extends Key> implements AztecAsyncSet<K> {
8
+ readonly #map: SQLiteOPFSAztecMap<K, boolean>;
9
+
10
+ constructor(store: AztecSQLiteOPFSStore, name: string) {
11
+ this.#map = new SQLiteOPFSAztecMap<K, boolean>(store, name);
12
+ }
13
+
14
+ hasAsync(key: K): Promise<boolean> {
15
+ return this.#map.hasAsync(key);
16
+ }
17
+
18
+ add(key: K): Promise<void> {
19
+ return this.#map.set(key, true);
20
+ }
21
+
22
+ delete(key: K): Promise<void> {
23
+ return this.#map.delete(key);
24
+ }
25
+
26
+ async *entriesAsync(range: Range<K> = {}): AsyncIterableIterator<K> {
27
+ yield* this.#map.keysAsync(range);
28
+ }
29
+ }
@@ -0,0 +1,48 @@
1
+ import { Encoder } from 'msgpackr';
2
+ import { hash } from 'ohash';
3
+ import { toBufferKey } from 'ordered-binary';
4
+
5
+ import type { Value } from '../interfaces/common.js';
6
+ import type { AztecAsyncSingleton } from '../interfaces/singleton.js';
7
+ import type { AztecSQLiteOPFSStore } from './store.js';
8
+
9
+ /** Stores a single value identified by `name`. */
10
+ export class SQLiteOPFSAztecSingleton<T extends Value> implements AztecAsyncSingleton<T> {
11
+ readonly #container: string;
12
+ readonly #slot: string;
13
+ readonly #encoder = new Encoder();
14
+
15
+ constructor(
16
+ private readonly store: AztecSQLiteOPFSStore,
17
+ name: string,
18
+ ) {
19
+ this.#container = `singleton:${name}`;
20
+ this.#slot = `singleton:${name}:value`;
21
+ }
22
+
23
+ async getAsync(): Promise<T | undefined> {
24
+ const rows = await this.store.allAsync('SELECT value FROM data WHERE slot = ? LIMIT 1', [this.#slot]);
25
+ if (rows.length === 0) {
26
+ return undefined;
27
+ }
28
+ const raw = rows[0][0];
29
+ if (raw instanceof Uint8Array) {
30
+ return this.#encoder.unpack(raw) as T;
31
+ }
32
+ return undefined;
33
+ }
34
+
35
+ async set(val: T): Promise<boolean> {
36
+ const { changes } = await this.store.runAsync(
37
+ `INSERT OR REPLACE INTO data (slot, container, key, key_count, hash, value)
38
+ VALUES (?, ?, ?, ?, ?, ?)`,
39
+ [this.#slot, this.#container, toBufferKey([this.#slot]), 1, hash(val), this.#encoder.pack(val)],
40
+ );
41
+ return changes > 0;
42
+ }
43
+
44
+ async delete(): Promise<boolean> {
45
+ await this.store.runAsync('DELETE FROM data WHERE slot = ?', [this.#slot]);
46
+ return true;
47
+ }
48
+ }
@@ -0,0 +1,248 @@
1
+ import type { Logger } from '@aztec/foundation/log';
2
+ import { SerialQueue } from '@aztec/foundation/queue';
3
+
4
+ import type { AztecAsyncArray } from '../interfaces/array.js';
5
+ import type { Key, StoreSize, Value } from '../interfaces/common.js';
6
+ import type { AztecAsyncCounter } from '../interfaces/counter.js';
7
+ import type { AztecAsyncMap } from '../interfaces/map.js';
8
+ import type { AztecAsyncMultiMap } from '../interfaces/multi_map.js';
9
+ import type { AztecAsyncSet } from '../interfaces/set.js';
10
+ import type { AztecAsyncSingleton } from '../interfaces/singleton.js';
11
+ import type { AztecAsyncKVStore } from '../interfaces/store.js';
12
+ import { SQLiteOPFSAztecArray } from './array.js';
13
+ import { SQLiteOPFSAztecMap } from './map.js';
14
+ import type { ResultRow, SqlValue, WorkerRequest, WorkerResponse } from './messages.js';
15
+ import { SQLiteOPFSAztecMultiMap } from './multi_map.js';
16
+ import { SQLiteOPFSAztecSet } from './set.js';
17
+ import { SQLiteOPFSAztecSingleton } from './singleton.js';
18
+
19
+ /**
20
+ * Main-thread handle for a SQLite database persisted to OPFS via the `opfs-sahpool`
21
+ * VFS. Owns a dedicated Web Worker (the SAH Pool VFS requires Worker context) and
22
+ * routes every SQL op through it via typed postMessage RPC.
23
+ *
24
+ * Transaction ordering is guaranteed by a `SerialQueue` on the main thread combined
25
+ * with an `#inTx` flag: outside a `transactionAsync` block, each op acquires the
26
+ * queue for its own auto-commit; inside a block, the outer call holds the queue and
27
+ * nested ops bypass it to avoid deadlock.
28
+ */
29
+ export class AztecSQLiteOPFSStore implements AztecAsyncKVStore {
30
+ readonly #worker: Worker;
31
+ readonly #pending = new Map<number, { resolve: (r: WorkerResponse) => void; reject: (err: Error) => void }>();
32
+ readonly #txQueue = new SerialQueue();
33
+ readonly #name: string;
34
+ readonly #log: Logger;
35
+ #nextId = 0;
36
+ #inTx = false;
37
+ #closed = false;
38
+
39
+ private constructor(
40
+ worker: Worker,
41
+ name: string,
42
+ log: Logger,
43
+ public readonly isEphemeral: boolean,
44
+ ) {
45
+ this.#worker = worker;
46
+ this.#name = name;
47
+ this.#log = log;
48
+ this.#worker.onmessage = (ev: MessageEvent<WorkerResponse>) => {
49
+ const { id } = ev.data;
50
+ const handler = this.#pending.get(id);
51
+ if (!handler) {
52
+ this.#log.warn(`SQLite worker: no pending handler for id ${id}`);
53
+ return;
54
+ }
55
+ this.#pending.delete(id);
56
+ handler.resolve(ev.data);
57
+ };
58
+ this.#worker.onerror = ev => {
59
+ this.#log.error(`SQLite worker crashed: ${ev.message}`);
60
+ this.#rejectPending(`SQLite worker crashed: ${ev.message}`);
61
+ };
62
+ this.#txQueue.start();
63
+ }
64
+
65
+ /**
66
+ * Opens (or creates) a SQLite database stored in the OPFS SAH Pool. When `ephemeral`
67
+ * is true the database lives only in memory and is lost when the worker terminates.
68
+ * Pass `poolDirectory` to place the SAH Pool in a non-default OPFS subdirectory —
69
+ * required when multiple stores coexist in the same tab, because the SAH Pool holds
70
+ * an exclusive lock on its directory.
71
+ */
72
+ static async open(
73
+ log: Logger,
74
+ name?: string,
75
+ ephemeral: boolean = false,
76
+ poolDirectory?: string,
77
+ ): Promise<AztecSQLiteOPFSStore> {
78
+ const dbName = name && !ephemeral ? name : `tmp-${globalThis.crypto.getRandomValues(new Uint8Array(8)).join('')}`;
79
+ log.debug(`Opening SQLite-OPFS ${ephemeral ? 'ephemeral ' : ''}database ${dbName}`);
80
+ const worker = new Worker(new URL('./worker.js', import.meta.url), { type: 'module' });
81
+ const store = new AztecSQLiteOPFSStore(worker, dbName, log, ephemeral);
82
+ await store.#sendRequest({ type: 'init', id: store.#allocId(), dbName, ephemeral, poolDirectory });
83
+ return store;
84
+ }
85
+
86
+ openMap<K extends Key, V extends Value>(name: string): AztecAsyncMap<K, V> {
87
+ return new SQLiteOPFSAztecMap<K, V>(this, name);
88
+ }
89
+
90
+ openSet<K extends Key>(name: string): AztecAsyncSet<K> {
91
+ return new SQLiteOPFSAztecSet<K>(this, name);
92
+ }
93
+
94
+ openMultiMap<K extends Key, V extends Value>(name: string): AztecAsyncMultiMap<K, V> {
95
+ return new SQLiteOPFSAztecMultiMap<K, V>(this, name);
96
+ }
97
+
98
+ openCounter<K extends Key>(_name: string): AztecAsyncCounter<K> {
99
+ throw new Error('Method not implemented.');
100
+ }
101
+
102
+ openArray<T extends Value>(name: string): AztecAsyncArray<T> {
103
+ return new SQLiteOPFSAztecArray<T>(this, name);
104
+ }
105
+
106
+ openSingleton<T extends Value>(name: string): AztecAsyncSingleton<T> {
107
+ return new SQLiteOPFSAztecSingleton<T>(this, name);
108
+ }
109
+
110
+ transactionAsync<T>(callback: () => Promise<T>): Promise<T> {
111
+ // Nested calls join the outer transaction — SQLite does not support nested BEGIN,
112
+ // and re-acquiring the SerialQueue while the outer call holds it would deadlock.
113
+ // Errors in the nested callback propagate to the outer catch, which rolls back the
114
+ // whole thing (the standard "nested tx = savepoint-free join" semantic).
115
+ if (this.#inTx) {
116
+ return callback();
117
+ }
118
+ return this.#txQueue.put(async () => {
119
+ this.#inTx = true;
120
+ await this.#sendRequest({ type: 'begin', id: this.#allocId() });
121
+ try {
122
+ const result = await callback();
123
+ await this.#sendRequest({ type: 'commit', id: this.#allocId() });
124
+ return result;
125
+ } catch (err) {
126
+ await this.#sendRequest({ type: 'rollback', id: this.#allocId() }).catch(rollbackErr =>
127
+ this.#log.warn(`SQLite ROLLBACK failed: ${rollbackErr instanceof Error ? rollbackErr.message : rollbackErr}`),
128
+ );
129
+ throw err;
130
+ } finally {
131
+ this.#inTx = false;
132
+ }
133
+ });
134
+ }
135
+
136
+ async clear(): Promise<void> {
137
+ await this.runAsync('DELETE FROM data');
138
+ }
139
+
140
+ async delete(): Promise<void> {
141
+ if (this.#closed) {
142
+ return;
143
+ }
144
+ this.#closed = true;
145
+ await this.#txQueue.end();
146
+ await this.#sendRequest({ type: 'deleteDb', id: this.#allocId(), dbName: this.#name }).catch(err =>
147
+ this.#log.warn(`SQLite deleteDb failed: ${err instanceof Error ? err.message : err}`),
148
+ );
149
+ this.#worker.terminate();
150
+ this.#rejectPending('SQLite store deleted');
151
+ }
152
+
153
+ /**
154
+ * Placeholder — returns zeros to mirror the IndexedDB backend. SQLite exposes real
155
+ * numbers cheaply via `PRAGMA page_count` / `page_size` / `freelist_count` and
156
+ * `SELECT COUNT(*) FROM data`, which would populate `physicalFileSize`, `actualSize`,
157
+ * and `numItems` meaningfully (`mappingSize` stays 0 — it's an LMDB mmap concept).
158
+ * Upgrade when any caller actually consumes these values; all current consumers
159
+ * tolerate zeros.
160
+ */
161
+ estimateSize(): Promise<StoreSize> {
162
+ return Promise.resolve({ mappingSize: 0, physicalFileSize: 0, actualSize: 0, numItems: 0 });
163
+ }
164
+
165
+ async close(): Promise<void> {
166
+ if (this.#closed) {
167
+ return;
168
+ }
169
+ this.#closed = true;
170
+ await this.#txQueue.end();
171
+ await this.#sendRequest({ type: 'close', id: this.#allocId() }).catch(() => {});
172
+ this.#worker.terminate();
173
+ this.#rejectPending('SQLite store closed');
174
+ }
175
+
176
+ backupTo(_dstPath: string, _compact?: boolean): Promise<void> {
177
+ throw new Error('Method not implemented.');
178
+ }
179
+
180
+ /**
181
+ * Returns a raw SQLite image (bytes suitable for writing as a `.sqlite` file and
182
+ * opening in any SQLite tool). Works only for non-ephemeral DBs because the OPFS
183
+ * SAH Pool has to be initialized. Useful for inspection/debugging.
184
+ */
185
+ async exportDb(): Promise<Uint8Array> {
186
+ const resp = await this.#sendRequest({ type: 'export', id: this.#allocId() });
187
+ if (!('bytes' in resp) || !resp.bytes) {
188
+ throw new Error('exportDb: worker returned no bytes');
189
+ }
190
+ return resp.bytes;
191
+ }
192
+
193
+ /**
194
+ * Runs a write statement (INSERT/UPDATE/DELETE/DDL). If called inside a
195
+ * `transactionAsync` block, bypasses the queue; otherwise acquires it so the
196
+ * op runs in its own auto-commit.
197
+ */
198
+ runAsync(sql: string, bind?: SqlValue[]): Promise<{ changes: number }> {
199
+ const send = () =>
200
+ this.#sendRequest({ type: 'run', id: this.#allocId(), sql, bind }).then(r => ({
201
+ changes: 'changes' in r ? (r.changes ?? 0) : 0,
202
+ }));
203
+ return this.#inTx ? send() : this.#txQueue.put(send);
204
+ }
205
+
206
+ /** Runs a SELECT statement and returns rows in array row-mode. */
207
+ allAsync(sql: string, bind?: SqlValue[]): Promise<ResultRow[]> {
208
+ const send = () =>
209
+ this.#sendRequest({ type: 'all', id: this.#allocId(), sql, bind }).then(r => ('rows' in r ? (r.rows ?? []) : []));
210
+ return this.#inTx ? send() : this.#txQueue.put(send);
211
+ }
212
+
213
+ #allocId(): number {
214
+ return ++this.#nextId;
215
+ }
216
+
217
+ /**
218
+ * Reject any in-flight requests with `reason`, so callers awaiting a response to a
219
+ * request sent to a now-terminated worker don't hang forever. Called from
220
+ * close()/delete() and from the worker.onerror handler.
221
+ */
222
+ #rejectPending(reason: string): void {
223
+ if (this.#pending.size === 0) {
224
+ return;
225
+ }
226
+ const err = new Error(reason);
227
+ for (const { reject } of this.#pending.values()) {
228
+ reject(err);
229
+ }
230
+ this.#pending.clear();
231
+ }
232
+
233
+ #sendRequest(req: WorkerRequest): Promise<WorkerResponse> {
234
+ return new Promise<WorkerResponse>((resolve, reject) => {
235
+ this.#pending.set(req.id, {
236
+ resolve: resp => {
237
+ if (resp.type === 'err') {
238
+ reject(new Error(resp.message));
239
+ } else {
240
+ resolve(resp);
241
+ }
242
+ },
243
+ reject,
244
+ });
245
+ this.#worker.postMessage(req);
246
+ });
247
+ }
248
+ }