plateaudb 0.0.0-stage → 0.2.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/dist/index.js ADDED
@@ -0,0 +1,3188 @@
1
+ // src/key.ts
2
+ var NUMBER = 16;
3
+ var DATE = 32;
4
+ var STRING = 48;
5
+ var BINARY = 64;
6
+ var ARRAY = 80;
7
+ var f64 = new Float64Array(1);
8
+ var u32 = new Uint32Array(f64.buffer);
9
+ var LITTLE = new Uint8Array(new Uint16Array([1]).buffer)[0] === 1;
10
+ var HI = LITTLE ? 1 : 0;
11
+ var LO = LITTLE ? 0 : 1;
12
+ function encodeNumber(tag, n) {
13
+ f64[0] = n === 0 ? 0 : n;
14
+ let hi = u32[HI];
15
+ let lo = u32[LO];
16
+ if (hi >>> 31) {
17
+ hi = ~hi >>> 0;
18
+ lo = ~lo >>> 0;
19
+ } else {
20
+ hi = (hi | 2147483648) >>> 0;
21
+ }
22
+ return String.fromCharCode(tag, hi >>> 16, hi & 65535, lo >>> 16, lo & 65535);
23
+ }
24
+ function decodeNumber(s, at) {
25
+ let hi = (s.charCodeAt(at) << 16 | s.charCodeAt(at + 1)) >>> 0;
26
+ let lo = (s.charCodeAt(at + 2) << 16 | s.charCodeAt(at + 3)) >>> 0;
27
+ if (hi >>> 31) {
28
+ hi = (hi & 2147483647) >>> 0;
29
+ } else {
30
+ hi = ~hi >>> 0;
31
+ lo = ~lo >>> 0;
32
+ }
33
+ u32[HI] = hi;
34
+ u32[LO] = lo;
35
+ return f64[0];
36
+ }
37
+ function isBinary(v) {
38
+ return v instanceof ArrayBuffer || ArrayBuffer.isView(v) || Object.prototype.toString.call(v) === "[object ArrayBuffer]";
39
+ }
40
+ function bytesOf(v) {
41
+ return ArrayBuffer.isView(v) ? new Uint8Array(v.buffer, v.byteOffset, v.byteLength) : new Uint8Array(v);
42
+ }
43
+ function isDate(v) {
44
+ return v instanceof Date || Object.prototype.toString.call(v) === "[object Date]";
45
+ }
46
+ function encodeKey(v) {
47
+ return enc(v, null);
48
+ }
49
+ function enc(v, seen) {
50
+ switch (typeof v) {
51
+ case "number":
52
+ return Number.isNaN(v) ? undefined : encodeNumber(NUMBER, v);
53
+ case "string": {
54
+ let out = String.fromCharCode(STRING);
55
+ let from = 0;
56
+ for (let i = 0;i < v.length; i++) {
57
+ const c = v.charCodeAt(i);
58
+ if (c < 2) {
59
+ out += v.slice(from, i) + String.fromCharCode(1, c + 1);
60
+ from = i + 1;
61
+ }
62
+ }
63
+ return out + v.slice(from) + "\x00";
64
+ }
65
+ case "object": {
66
+ if (v === null)
67
+ return;
68
+ if (isDate(v)) {
69
+ const t = v.getTime();
70
+ return Number.isNaN(t) ? undefined : encodeNumber(DATE, t);
71
+ }
72
+ if (isBinary(v)) {
73
+ const b = bytesOf(v);
74
+ const units = new Array(b.length);
75
+ for (let i = 0;i < b.length; i++)
76
+ units[i] = b[i] + 2;
77
+ let out = String.fromCharCode(BINARY);
78
+ for (let i = 0;i < units.length; i += 8192)
79
+ out += String.fromCharCode(...units.slice(i, i + 8192));
80
+ return out + "\x00";
81
+ }
82
+ if (Array.isArray(v)) {
83
+ const stack = seen ?? [];
84
+ if (stack.includes(v))
85
+ return;
86
+ stack.push(v);
87
+ let out = String.fromCharCode(ARRAY);
88
+ for (let i = 0;i < v.length; i++) {
89
+ if (!Object.prototype.hasOwnProperty.call(v, i))
90
+ return;
91
+ const e = enc(v[i], stack);
92
+ if (e === undefined)
93
+ return;
94
+ out += e;
95
+ }
96
+ stack.pop();
97
+ return out + "\x00";
98
+ }
99
+ return;
100
+ }
101
+ default:
102
+ return;
103
+ }
104
+ }
105
+ function decodeKeyAt(s, at) {
106
+ const tag = s.charCodeAt(at);
107
+ switch (tag) {
108
+ case NUMBER:
109
+ return [decodeNumber(s, at + 1), at + 5];
110
+ case DATE:
111
+ return [new Date(decodeNumber(s, at + 1)), at + 5];
112
+ case STRING: {
113
+ let out = "";
114
+ let i = at + 1;
115
+ let from = i;
116
+ for (;; ) {
117
+ const c = s.charCodeAt(i);
118
+ if (c === 0)
119
+ return [out + s.slice(from, i), i + 1];
120
+ if (c === 1) {
121
+ out += s.slice(from, i) + String.fromCharCode(s.charCodeAt(i + 1) - 1);
122
+ i += 2;
123
+ from = i;
124
+ } else
125
+ i++;
126
+ }
127
+ }
128
+ case BINARY: {
129
+ const end = s.indexOf("\x00", at + 1);
130
+ const b = new Uint8Array(end - at - 1);
131
+ for (let i = 0;i < b.length; i++)
132
+ b[i] = s.charCodeAt(at + 1 + i) - 2;
133
+ return [b.buffer, end + 1];
134
+ }
135
+ case ARRAY: {
136
+ const out = [];
137
+ let i = at + 1;
138
+ while (s.charCodeAt(i) !== 0) {
139
+ const [k, next] = decodeKeyAt(s, i);
140
+ out.push(k);
141
+ i = next;
142
+ }
143
+ return [out, i + 1];
144
+ }
145
+ default:
146
+ throw new Error(`plateau: corrupt key encoding (tag ${tag})`);
147
+ }
148
+ }
149
+ function decodeKey(s) {
150
+ return decodeKeyAt(s, 0)[0];
151
+ }
152
+ function dataError(message) {
153
+ return new DOMException(message, "DataError");
154
+ }
155
+ function requireKey(v, what = "The parameter") {
156
+ const e = encodeKey(v);
157
+ if (e === undefined)
158
+ throw dataError(`${what} is not a valid key.`);
159
+ return e;
160
+ }
161
+ function cmp(a, b) {
162
+ const x = requireKey(a, "The first parameter");
163
+ const y = requireKey(b, "The second parameter");
164
+ return x < y ? -1 : x > y ? 1 : 0;
165
+ }
166
+ var IDENT = /^[$_\p{ID_Start}][$‌‍\p{ID_Continue}]*$/u;
167
+ function validPathString(p) {
168
+ return p === "" || p.split(".").every((part) => IDENT.test(part));
169
+ }
170
+ function validKeyPath(p) {
171
+ if (typeof p === "string")
172
+ return validPathString(p);
173
+ if (Array.isArray(p))
174
+ return p.length > 0 && p.every((x) => typeof x === "string" && validPathString(x));
175
+ return false;
176
+ }
177
+ function normalizeKeyPath(p) {
178
+ if (p === null || p === undefined)
179
+ return p;
180
+ if (Array.isArray(p))
181
+ return p.map((x) => String(x));
182
+ if (typeof p === "object" && typeof p[Symbol.iterator] === "function") {
183
+ return Array.from(p, (x) => String(x));
184
+ }
185
+ return String(p);
186
+ }
187
+ var FAIL = Symbol("no value at key path");
188
+ function evalPath(value, path) {
189
+ if (path === "")
190
+ return value;
191
+ let v = value;
192
+ for (const id of path.split(".")) {
193
+ if (typeof v === "string" && id === "length") {
194
+ v = v.length;
195
+ continue;
196
+ }
197
+ if (v === null || typeof v !== "object")
198
+ return FAIL;
199
+ if (Array.isArray(v) && id === "length") {
200
+ v = v.length;
201
+ continue;
202
+ }
203
+ if (!Object.prototype.hasOwnProperty.call(v, id))
204
+ return FAIL;
205
+ v = v[id];
206
+ }
207
+ return v;
208
+ }
209
+ function extractKey(value, path) {
210
+ if (Array.isArray(path)) {
211
+ const parts = [];
212
+ for (const p of path) {
213
+ const v = evalPath(value, p);
214
+ if (v === FAIL)
215
+ return "invalid";
216
+ parts.push(v);
217
+ }
218
+ const key = encodeKey(parts);
219
+ return key === undefined ? "invalid" : { key };
220
+ }
221
+ const v = evalPath(value, path);
222
+ if (v === FAIL)
223
+ return "missing";
224
+ const key = encodeKey(v);
225
+ return key === undefined ? "invalid" : { key };
226
+ }
227
+ function canInjectKey(value, path) {
228
+ const ids = path.split(".");
229
+ let v = value;
230
+ for (let i = 0;i < ids.length - 1; i++) {
231
+ if (v === null || typeof v !== "object")
232
+ return false;
233
+ if (!Object.prototype.hasOwnProperty.call(v, ids[i]))
234
+ return true;
235
+ v = v[ids[i]];
236
+ }
237
+ return v !== null && typeof v === "object";
238
+ }
239
+ var nativeRanges = false;
240
+ function useNativeKeyRanges() {
241
+ nativeRanges = typeof IDBKeyRange !== "undefined";
242
+ }
243
+
244
+ class PlateauKeyRange {
245
+ lo;
246
+ hi;
247
+ lowerOpen;
248
+ upperOpen;
249
+ constructor(lo, hi, lowerOpen, upperOpen) {
250
+ this.lo = lo;
251
+ this.hi = hi;
252
+ this.lowerOpen = lowerOpen;
253
+ this.upperOpen = upperOpen;
254
+ }
255
+ get lower() {
256
+ return this.lo === undefined ? undefined : decodeKey(this.lo);
257
+ }
258
+ get upper() {
259
+ return this.hi === undefined ? undefined : decodeKey(this.hi);
260
+ }
261
+ static only(value) {
262
+ if (nativeRanges)
263
+ return IDBKeyRange.only(value);
264
+ const k = requireKey(value);
265
+ return new PlateauKeyRange(k, k, false, false);
266
+ }
267
+ static lowerBound(lower, open = false) {
268
+ if (nativeRanges)
269
+ return IDBKeyRange.lowerBound(lower, open);
270
+ return new PlateauKeyRange(requireKey(lower), undefined, !!open, true);
271
+ }
272
+ static upperBound(upper, open = false) {
273
+ if (nativeRanges)
274
+ return IDBKeyRange.upperBound(upper, open);
275
+ return new PlateauKeyRange(undefined, requireKey(upper), true, !!open);
276
+ }
277
+ static bound(lower, upper, lowerOpen = false, upperOpen = false) {
278
+ if (nativeRanges)
279
+ return IDBKeyRange.bound(lower, upper, lowerOpen, upperOpen);
280
+ const lo = requireKey(lower);
281
+ const hi = requireKey(upper);
282
+ if (lo > hi || lo === hi && (lowerOpen || upperOpen))
283
+ throw dataError("The lower key is greater than the upper key.");
284
+ return new PlateauKeyRange(lo, hi, !!lowerOpen, !!upperOpen);
285
+ }
286
+ includes(key) {
287
+ return inRange(this.wire(), requireKey(key));
288
+ }
289
+ wire() {
290
+ return { lo: this.lo, hi: this.hi, loOpen: this.lowerOpen, hiOpen: this.upperOpen };
291
+ }
292
+ }
293
+ function inRange(r, k) {
294
+ if (r.lo !== undefined && (r.loOpen ? k <= r.lo : k < r.lo))
295
+ return false;
296
+ if (r.hi !== undefined && (r.hiOpen ? k >= r.hi : k > r.hi))
297
+ return false;
298
+ return true;
299
+ }
300
+ function toRange(q, nullOk) {
301
+ if (q === undefined || q === null) {
302
+ if (nullOk)
303
+ return null;
304
+ throw dataError("No key or key range specified.");
305
+ }
306
+ if (q instanceof PlateauKeyRange)
307
+ return q.wire();
308
+ if (typeof IDBKeyRange !== "undefined" && q instanceof IDBKeyRange) {
309
+ return {
310
+ lo: q.lower === undefined ? undefined : requireKey(q.lower),
311
+ hi: q.upper === undefined ? undefined : requireKey(q.upper),
312
+ loOpen: q.lowerOpen,
313
+ hiOpen: q.upperOpen
314
+ };
315
+ }
316
+ const k = requireKey(q);
317
+ return { lo: k, hi: k, loOpen: false, hiOpen: false };
318
+ }
319
+
320
+ // src/scheduler.ts
321
+ class Scheduler {
322
+ live = [];
323
+ add(tx) {
324
+ this.live.push(tx);
325
+ this.pump();
326
+ }
327
+ done(tx) {
328
+ const i = this.live.indexOf(tx);
329
+ if (i >= 0)
330
+ this.live.splice(i, 1);
331
+ this.pump();
332
+ }
333
+ pump() {
334
+ for (let i = 0;i < this.live.length; i++) {
335
+ const tx = this.live[i];
336
+ if (tx._started || tx._state === "finished")
337
+ continue;
338
+ let ok = true;
339
+ for (let j = 0;j < i && ok; j++) {
340
+ const t = this.live[j];
341
+ if (t._state === "finished")
342
+ continue;
343
+ const both = t.mode === "readonly" && tx.mode === "readonly";
344
+ if (!both && t._scope.some((s) => tx._scope.includes(s)))
345
+ ok = false;
346
+ }
347
+ if (ok)
348
+ tx._start();
349
+ }
350
+ }
351
+ }
352
+ var schedulers = new Map;
353
+ function scheduler(name) {
354
+ let s = schedulers.get(name);
355
+ if (!s)
356
+ schedulers.set(name, s = new Scheduler);
357
+ return s;
358
+ }
359
+
360
+ // src/runtime.ts
361
+ var WASM_URL = new URL("./plateau_engine_bg.wasm", import.meta.url).href;
362
+ var LEADER = "plateau/leader";
363
+ var ALIVE = "plateau/alive/";
364
+ var HUB = "plateau/hub";
365
+ var TAB = "plateau/tab/";
366
+ var versionChangeHook = () => null;
367
+ function onVersionChange(hook) {
368
+ versionChangeHook = hook;
369
+ }
370
+ var changeHook = () => {};
371
+ function onChange(hook) {
372
+ changeHook = hook;
373
+ }
374
+ var forever = () => new Promise(() => {});
375
+ function count(m, key, by) {
376
+ const n = (m.get(key) ?? 0) + by;
377
+ if (n > 0)
378
+ m.set(key, n);
379
+ else
380
+ m.delete(key);
381
+ }
382
+
383
+ class OpenQueue {
384
+ busy = false;
385
+ waiting = [];
386
+ add(job, first) {
387
+ if (first)
388
+ this.waiting.unshift(job);
389
+ else
390
+ this.waiting.push(job);
391
+ this.pump();
392
+ }
393
+ pump() {
394
+ if (this.busy)
395
+ return;
396
+ const job = this.waiting.shift();
397
+ if (!job)
398
+ return;
399
+ this.busy = true;
400
+ job().catch((e) => console.error(e)).finally(() => {
401
+ this.busy = false;
402
+ this.pump();
403
+ });
404
+ }
405
+ }
406
+
407
+ class RemoteTx {
408
+ rt;
409
+ f;
410
+ remote;
411
+ id;
412
+ db;
413
+ mode;
414
+ _scope;
415
+ _started = false;
416
+ _state = "running";
417
+ waiting = [];
418
+ constructor(rt, f, remote, id, db, begin) {
419
+ this.rt = rt;
420
+ this.f = f;
421
+ this.remote = remote;
422
+ this.id = id;
423
+ this.db = db;
424
+ this.mode = begin.mode;
425
+ this._scope = [...begin.stores];
426
+ }
427
+ receive(m) {
428
+ const local = { ...m, tx: this.id };
429
+ if (this._started)
430
+ this.rt.worker.postMessage(local);
431
+ else
432
+ this.waiting.push(local);
433
+ }
434
+ _start() {
435
+ this._started = true;
436
+ for (const m of this.waiting)
437
+ this.rt.worker.postMessage(m);
438
+ this.waiting = [];
439
+ }
440
+ _onReply(r) {
441
+ if (!this.f.gone)
442
+ this.f.port.postMessage({ ...r, tx: this.remote });
443
+ if (r.end && (r.end.ok || r.end.name !== "Deferred"))
444
+ this.finish();
445
+ }
446
+ finish() {
447
+ if (this._state === "finished")
448
+ return;
449
+ this._state = "finished";
450
+ this.rt.txs.delete(this.id);
451
+ this.f.txs.delete(this.remote);
452
+ scheduler(this.db).done(this);
453
+ }
454
+ kill() {
455
+ if (this._started && this.mode !== "readonly" && this._state !== "finished") {
456
+ this.rt.worker.postMessage({ t: "tx", tx: this.id, db: this.db, ops: [], end: "abort" });
457
+ }
458
+ this.finish();
459
+ }
460
+ }
461
+
462
+ class Runtime {
463
+ worker = null;
464
+ role = "pending";
465
+ txs = new Map;
466
+ nextTx = 1;
467
+ tab;
468
+ leading;
469
+ requested;
470
+ dead = null;
471
+ becameLeader;
472
+ started = false;
473
+ calls = new Map;
474
+ nextCall = 1;
475
+ held = [];
476
+ begun = new Set;
477
+ lost = new Set;
478
+ opened = new Map;
479
+ leaderTab = null;
480
+ hub = null;
481
+ port = null;
482
+ slots = new Map;
483
+ nextSlot = 1;
484
+ vcs = new Map;
485
+ nextVc = 1;
486
+ seen = new Map;
487
+ followers = new Map;
488
+ relayed = new Map;
489
+ queues = new Map;
490
+ slotHolds = new Map;
491
+ fanouts = new Map;
492
+ constructor(o = {}) {
493
+ this.leading = new Promise((resolve) => this.becameLeader = resolve);
494
+ this.tab = typeof crypto.randomUUID === "function" ? crypto.randomUUID() : `${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}`;
495
+ this.requested = o.backend ?? "auto";
496
+ if (this.requested === "indexeddb")
497
+ this.stop("plateau: this page uses the browser's IndexedDB");
498
+ else
499
+ this.startWorker(o);
500
+ const locks = typeof navigator !== "undefined" ? navigator.locks : undefined;
501
+ if (!locks || typeof BroadcastChannel === "undefined") {
502
+ this.lead();
503
+ return;
504
+ }
505
+ locks.request(ALIVE + this.tab, () => {
506
+ this.hub = new BroadcastChannel(HUB);
507
+ this.hub.onmessage = (e) => this.onHub(e.data);
508
+ locks.request(LEADER, { ifAvailable: true }, (lock) => {
509
+ if (lock) {
510
+ this.lead();
511
+ return forever();
512
+ }
513
+ this.hub.postMessage({ t: "who" });
514
+ locks.request(LEADER, () => {
515
+ this.lead();
516
+ return forever();
517
+ });
518
+ return;
519
+ });
520
+ return forever();
521
+ });
522
+ }
523
+ stop(message) {
524
+ if (this.dead)
525
+ return;
526
+ this.dead = new DOMException(message, "NotSupportedError");
527
+ this.worker?.terminate();
528
+ this.worker = null;
529
+ if (this.role !== "leader")
530
+ return;
531
+ for (const [id, c] of this.calls) {
532
+ this.calls.delete(id);
533
+ c.reject(this.dead);
534
+ }
535
+ for (const [id, reply] of this.relayed) {
536
+ this.relayed.delete(id);
537
+ reply({ t: "call", id, ok: false, name: this.dead.name, message: this.dead.message });
538
+ }
539
+ }
540
+ call(m) {
541
+ const id = this.nextCall++;
542
+ return new Promise((resolve, reject) => {
543
+ this.calls.set(id, { m, resolve, reject, sent: false });
544
+ if (m.t === "close")
545
+ count(this.opened, m.db, -1);
546
+ this.send({ ...m, id });
547
+ });
548
+ }
549
+ post(m, transfer = []) {
550
+ if (this.lost.size && this.lost.has(m.tx))
551
+ return;
552
+ this.send(m, transfer);
553
+ }
554
+ finished(tx) {
555
+ this.txs.delete(tx);
556
+ this.lost.delete(tx);
557
+ if (this.begun.delete(tx) && this.role === "follower")
558
+ this.port.postMessage({ t: "done", tx });
559
+ }
560
+ queue(db, job) {
561
+ const run = (done) => queueMicrotask(() => void job().catch((e) => console.error(e)).finally(done));
562
+ if (this.role === "leader") {
563
+ this.openQueue(db).add(() => new Promise(run), false);
564
+ return;
565
+ }
566
+ const id = this.nextSlot++;
567
+ const s = {
568
+ db,
569
+ held: false,
570
+ go: () => {
571
+ if (s.held)
572
+ return;
573
+ s.held = true;
574
+ run(() => {
575
+ this.slots.delete(id);
576
+ this.toLeader({ t: "slotEnd", id });
577
+ });
578
+ }
579
+ };
580
+ this.slots.set(id, s);
581
+ this.toLeader({ t: "slot", id, db, held: false });
582
+ }
583
+ changed(db, stores) {
584
+ this.hub?.postMessage({ t: "changed", db, stores });
585
+ }
586
+ versionChange(db, oldVersion, newVersion) {
587
+ if (this.role === "leader" && ![...this.followers.values()].some((f) => f.conns.has(db)))
588
+ return null;
589
+ const id = this.nextVc++;
590
+ let ack;
591
+ let closed;
592
+ const out = { ack: new Promise((r) => ack = r), closed: new Promise((r) => closed = r) };
593
+ this.vcs.set(id, { db, old: oldVersion, new: newVersion, ack, closed });
594
+ this.toLeader({ t: "vc", id, db, old: oldVersion, new: newVersion });
595
+ return out;
596
+ }
597
+ startWorker(o) {
598
+ let worker;
599
+ try {
600
+ worker = o.worker ?? new Worker(new URL("./host.worker.js", import.meta.url), { type: "module" });
601
+ if (!o.worker) {
602
+ const compiled = WebAssembly.compileStreaming(fetch(WASM_URL)).catch(async () => WebAssembly.compile(await (await fetch(WASM_URL)).arrayBuffer()));
603
+ compiled.then((module) => worker.postMessage({ t: "init", module }), (e) => this.stop(`plateau: the engine's WebAssembly does not compile here: ${e?.message ?? String(e)}`));
604
+ }
605
+ } catch (e) {
606
+ this.stop(`plateau: the engine's worker does not start here: ${e?.message ?? String(e)}`);
607
+ return;
608
+ }
609
+ this.started = !!o.worker;
610
+ worker.addEventListener("error", (e) => {
611
+ if (!this.started && this.worker === worker)
612
+ this.stop(`plateau: the engine's worker failed to load: ${e.message ?? ""}`.trim());
613
+ });
614
+ worker.addEventListener("message", (e) => {
615
+ const m = e.data;
616
+ if (m.t === "init") {
617
+ if (m.error)
618
+ this.stop(m.error);
619
+ else
620
+ this.started = true;
621
+ } else if (m.t === "call") {
622
+ const r = this.relayed.get(m.id);
623
+ if (r) {
624
+ this.relayed.delete(m.id);
625
+ r(m);
626
+ } else
627
+ this.settle(m);
628
+ } else if (m.t === "tx")
629
+ this.txs.get(m.tx)?._onReply(m);
630
+ });
631
+ this.worker = worker;
632
+ }
633
+ send(m, transfer = []) {
634
+ if (this.role === "leader" && this.dead) {
635
+ const dead = this.dead;
636
+ if (m.t !== "tx")
637
+ queueMicrotask(() => this.settle({ t: "call", id: m.id, ok: false, name: dead.name, message: dead.message }));
638
+ else if (m.begin)
639
+ queueMicrotask(() => this.txs.get(m.tx)?._onReply({ t: "tx", tx: m.tx, res: [], errs: [], end: { ok: false, name: "UnknownError", message: dead.message } }));
640
+ } else if (this.role === "leader") {
641
+ this.worker.postMessage(m, transfer);
642
+ } else if (this.role === "follower") {
643
+ if (m.t === "tx") {
644
+ if (m.begin)
645
+ this.begun.add(m.tx);
646
+ } else {
647
+ const c = this.calls.get(m.id);
648
+ if (c)
649
+ c.sent = true;
650
+ }
651
+ this.port.postMessage(m);
652
+ } else
653
+ this.held.push([m, transfer]);
654
+ }
655
+ toLeader(m) {
656
+ if (this.role === "leader")
657
+ this.onLeader(this.tab, m);
658
+ else if (this.role === "follower")
659
+ this.port.postMessage(m);
660
+ }
661
+ settle(r) {
662
+ const c = this.calls.get(r.id);
663
+ if (!c)
664
+ return;
665
+ this.calls.delete(r.id);
666
+ if (r.ok) {
667
+ if (c.m.t === "open")
668
+ count(this.opened, c.m.db, 1);
669
+ c.resolve(r.value);
670
+ } else
671
+ c.reject(new DOMException(r.message, r.name));
672
+ }
673
+ watch(tab, gone) {
674
+ navigator.locks.request(ALIVE + tab, { mode: "shared" }, () => gone());
675
+ }
676
+ onHub(m) {
677
+ if (m.t === "changed")
678
+ changeHook(m.db, m.stores);
679
+ else if (m.t === "who") {
680
+ if (this.role === "leader")
681
+ this.hub.postMessage({ t: "leader", tab: this.tab });
682
+ } else if (m.t === "leader") {
683
+ if (m.tab !== this.tab && this.role !== "leader" && m.tab !== this.leaderTab)
684
+ this.join(m.tab);
685
+ } else if (m.leader === this.tab && this.role === "leader" && !this.followers.has(m.tab)) {
686
+ this.serve(m.tab);
687
+ }
688
+ }
689
+ join(leader) {
690
+ if (this.leaderTab !== null)
691
+ this.leaderLost();
692
+ this.leaderTab = leader;
693
+ this.worker?.terminate();
694
+ this.worker = null;
695
+ this.port = new BroadcastChannel(TAB + this.tab);
696
+ this.port.onmessage = (e) => this.receive(e.data);
697
+ this.watch(leader, () => {
698
+ if (this.leaderTab === leader)
699
+ this.leaderLost();
700
+ });
701
+ this.hub.postMessage({ t: "hello", tab: this.tab, leader });
702
+ }
703
+ lead() {
704
+ if (this.leaderTab !== null)
705
+ this.leaderLost();
706
+ this.leaderTab = this.tab;
707
+ this.role = "leader";
708
+ this.becameLeader();
709
+ if (!this.worker && !this.dead)
710
+ this.startWorker({});
711
+ this.hub?.postMessage({ t: "leader", tab: this.tab });
712
+ this.flush();
713
+ }
714
+ leaderLost() {
715
+ this.leaderTab = null;
716
+ this.role = "pending";
717
+ this.port?.close();
718
+ this.port = null;
719
+ const begun = [...this.begun];
720
+ this.begun.clear();
721
+ for (const tx of begun) {
722
+ const t = this.txs.get(tx);
723
+ if (!t)
724
+ continue;
725
+ this.lost.add(tx);
726
+ t._onReply({ t: "tx", tx, res: [], errs: [], end: { ok: false, name: "UnknownError", message: "plateau: the tab that ran the database closed during the transaction" } });
727
+ }
728
+ const resend = [];
729
+ for (const [id, c] of this.calls) {
730
+ if (!c.sent)
731
+ continue;
732
+ c.sent = false;
733
+ if (c.m.t === "close") {
734
+ this.calls.delete(id);
735
+ c.resolve(null);
736
+ } else
737
+ resend.push([{ ...c.m, id }, []]);
738
+ }
739
+ this.held = [...resend, ...this.held];
740
+ }
741
+ flush() {
742
+ for (const [db, n] of this.opened)
743
+ for (let i = 0;i < n; i++)
744
+ this.send({ t: "open", db, id: this.nextCall++ });
745
+ for (const [id, s] of this.slots)
746
+ this.toLeader({ t: "slot", id, db: s.db, held: s.held });
747
+ for (const [id, v] of this.vcs)
748
+ this.toLeader({ t: "vc", id, db: v.db, old: v.old, new: v.new });
749
+ const held = this.held;
750
+ this.held = [];
751
+ for (const [m, transfer] of held)
752
+ this.send(m, transfer);
753
+ }
754
+ receive(m) {
755
+ switch (m.t) {
756
+ case "call":
757
+ this.settle(m);
758
+ return;
759
+ case "tx":
760
+ if (m.end && (m.end.ok || m.end.name !== "Deferred"))
761
+ this.begun.delete(m.tx);
762
+ this.txs.get(m.tx)?._onReply(m);
763
+ return;
764
+ case "welcome":
765
+ if (m.leader === this.leaderTab && this.role === "pending") {
766
+ this.role = "follower";
767
+ this.flush();
768
+ }
769
+ return;
770
+ case "slotGo":
771
+ this.slots.get(m.id)?.go();
772
+ return;
773
+ case "vc": {
774
+ const w = this.answer(m.key, m.db, m.old, m.new);
775
+ const id = m.id;
776
+ Promise.resolve(w?.ack ?? { blocking: false, version: 0 }).then((a) => this.toLeader({ t: "vcAck", id, ...a }));
777
+ (w?.closed ?? Promise.resolve()).then(() => this.toLeader({ t: "vcClosed", id }));
778
+ return;
779
+ }
780
+ case "vcAck":
781
+ this.vcs.get(m.id)?.ack({ blocking: m.blocking, version: m.version });
782
+ return;
783
+ case "vcClosed": {
784
+ const v = this.vcs.get(m.id);
785
+ this.vcs.delete(m.id);
786
+ v?.closed();
787
+ return;
788
+ }
789
+ }
790
+ }
791
+ answer(key, db, oldVersion, newVersion) {
792
+ let w = this.seen.get(key) ?? null;
793
+ if (!w) {
794
+ w = versionChangeHook(db, oldVersion, newVersion);
795
+ if (w) {
796
+ this.seen.set(key, w);
797
+ w.closed.then(() => this.seen.delete(key));
798
+ }
799
+ }
800
+ return w;
801
+ }
802
+ reply(tab, m) {
803
+ if (tab === this.tab)
804
+ this.receive(m);
805
+ else {
806
+ const f = this.followers.get(tab);
807
+ if (f && !f.gone)
808
+ f.port.postMessage(m);
809
+ }
810
+ }
811
+ serve(tab) {
812
+ const f = { tab, port: new BroadcastChannel(TAB + tab), conns: new Map, txs: new Map, gone: false };
813
+ f.port.onmessage = (e) => this.onLeader(tab, e.data);
814
+ this.followers.set(tab, f);
815
+ this.watch(tab, () => this.followerGone(tab));
816
+ f.port.postMessage({ t: "welcome", leader: this.tab });
817
+ }
818
+ onLeader(from, m) {
819
+ switch (m.t) {
820
+ case "tx":
821
+ return this.relayTx(from, m);
822
+ case "done":
823
+ this.followers.get(from)?.txs.get(m.tx)?.finish();
824
+ return;
825
+ case "slot":
826
+ return this.grantSlot(from, m.id, m.db, m.held);
827
+ case "slotEnd": {
828
+ const key = `${from}:${m.id}`;
829
+ const release = this.slotHolds.get(key);
830
+ this.slotHolds.delete(key);
831
+ release?.();
832
+ return;
833
+ }
834
+ case "vc":
835
+ return this.fanOut(from, m.id, m.db, m.old, m.new);
836
+ case "vcAck":
837
+ this.fanouts.get(m.id)?.ack({ blocking: m.blocking, version: m.version });
838
+ return;
839
+ case "vcClosed": {
840
+ const w = this.fanouts.get(m.id);
841
+ this.fanouts.delete(m.id);
842
+ w?.closed();
843
+ return;
844
+ }
845
+ default:
846
+ return this.relayCall(from, m);
847
+ }
848
+ }
849
+ relayCall(from, m) {
850
+ const f = this.followers.get(from);
851
+ if (!f)
852
+ return;
853
+ if (this.dead) {
854
+ f.port.postMessage({ t: "call", id: m.id, ok: false, name: this.dead.name, message: this.dead.message });
855
+ return;
856
+ }
857
+ const id = this.nextCall++;
858
+ if (m.t === "close")
859
+ count(f.conns, m.db, -1);
860
+ this.relayed.set(id, (r) => {
861
+ if (r.ok && m.t === "open") {
862
+ if (f.gone)
863
+ this.worker.postMessage({ t: "close", db: m.db, id: this.nextCall++ });
864
+ else
865
+ count(f.conns, m.db, 1);
866
+ }
867
+ if (!f.gone)
868
+ f.port.postMessage({ ...r, id: m.id });
869
+ });
870
+ this.worker.postMessage({ ...m, id });
871
+ }
872
+ relayTx(from, m) {
873
+ const f = this.followers.get(from);
874
+ if (!f)
875
+ return;
876
+ if (this.dead) {
877
+ if (m.begin)
878
+ f.port.postMessage({ t: "tx", tx: m.tx, res: [], errs: [], end: { ok: false, name: "UnknownError", message: this.dead.message } });
879
+ return;
880
+ }
881
+ let p = f.txs.get(m.tx);
882
+ if (!p) {
883
+ if (!m.begin)
884
+ return;
885
+ p = new RemoteTx(this, f, m.tx, this.nextTx++, m.db, m.begin);
886
+ f.txs.set(m.tx, p);
887
+ this.txs.set(p.id, p);
888
+ scheduler(m.db).add(p);
889
+ }
890
+ p.receive(m);
891
+ }
892
+ openQueue(db) {
893
+ let q = this.queues.get(db);
894
+ if (!q)
895
+ this.queues.set(db, q = new OpenQueue);
896
+ return q;
897
+ }
898
+ grantSlot(from, id, db, held) {
899
+ this.openQueue(db).add(() => new Promise((release) => {
900
+ if (from !== this.tab && !this.followers.has(from))
901
+ return release();
902
+ this.slotHolds.set(`${from}:${id}`, release);
903
+ if (!held)
904
+ this.reply(from, { t: "slotGo", id });
905
+ }), held);
906
+ }
907
+ fanOut(from, id, db, oldVersion, newVersion) {
908
+ const key = `${from}:${id}`;
909
+ const waits = [];
910
+ if (from !== this.tab) {
911
+ const own = this.answer(key, db, oldVersion, newVersion);
912
+ if (own)
913
+ waits.push(own);
914
+ }
915
+ for (const [tab, f] of this.followers) {
916
+ if (tab === from || !f.conns.has(db))
917
+ continue;
918
+ const fid = `${this.tab}:${this.nextVc++}`;
919
+ let ack;
920
+ let closed;
921
+ waits.push({ ack: new Promise((r) => ack = r), closed: new Promise((r) => closed = r) });
922
+ this.fanouts.set(fid, { tab, ack, closed });
923
+ f.port.postMessage({ t: "vc", id: fid, key, db, old: oldVersion, new: newVersion });
924
+ }
925
+ Promise.all(waits.map((w) => w.ack)).then((acks) => this.reply(from, { t: "vcAck", id, blocking: acks.some((a) => a.blocking), version: Math.max(0, ...acks.map((a) => a.version)) }));
926
+ Promise.all(waits.map((w) => w.closed)).then(() => this.reply(from, { t: "vcClosed", id }));
927
+ }
928
+ followerGone(tab) {
929
+ const f = this.followers.get(tab);
930
+ if (!f)
931
+ return;
932
+ f.gone = true;
933
+ this.followers.delete(tab);
934
+ f.port.close();
935
+ for (const p of [...f.txs.values()])
936
+ p.kill();
937
+ for (const [db, n] of f.conns)
938
+ for (let i = 0;i < n; i++)
939
+ this.worker?.postMessage({ t: "close", db, id: this.nextCall++ });
940
+ for (const [key, release] of this.slotHolds) {
941
+ if (!key.startsWith(`${tab}:`))
942
+ continue;
943
+ this.slotHolds.delete(key);
944
+ release();
945
+ }
946
+ for (const [id, w] of this.fanouts) {
947
+ if (w.tab !== tab)
948
+ continue;
949
+ this.fanouts.delete(id);
950
+ w.ack({ blocking: false, version: 0 });
951
+ w.closed();
952
+ }
953
+ }
954
+ }
955
+ var current = null;
956
+ function currentRuntime() {
957
+ return current;
958
+ }
959
+ function runtime(o) {
960
+ current ??= new Runtime(o);
961
+ return current;
962
+ }
963
+ function startRuntime(o) {
964
+ return runtime(o);
965
+ }
966
+
967
+ // src/backend.ts
968
+ var nativeIndexedDB = typeof indexedDB !== "undefined" ? indexedDB : undefined;
969
+ var chosen;
970
+ var choice = null;
971
+ function chosenBackend() {
972
+ return chosen;
973
+ }
974
+ function missing() {
975
+ if (typeof Worker !== "function")
976
+ return "no Worker";
977
+ if (typeof WebAssembly !== "object" || typeof WebAssembly.compile !== "function")
978
+ return "no WebAssembly";
979
+ const storage = typeof navigator !== "undefined" ? navigator.storage : undefined;
980
+ if (typeof storage?.getDirectory !== "function")
981
+ return "no OPFS (navigator.storage.getDirectory)";
982
+ return null;
983
+ }
984
+ function choose(b, why) {
985
+ chosen = b;
986
+ if (b === "indexeddb") {
987
+ useNativeKeyRanges();
988
+ runtime().stop(`plateau: this page uses the browser's IndexedDB${why ? ` (${why})` : ""}`);
989
+ }
990
+ return b;
991
+ }
992
+ function chooseBackend() {
993
+ if (choice)
994
+ return choice;
995
+ const requested = currentRuntime()?.requested ?? "auto";
996
+ if (!nativeIndexedDB || requested === "opfs")
997
+ choice = Promise.resolve(choose("opfs"));
998
+ else if (requested === "indexeddb")
999
+ choice = Promise.resolve(choose("indexeddb"));
1000
+ else {
1001
+ const why = missing();
1002
+ const rt = runtime(why ? { backend: "indexeddb" } : undefined);
1003
+ if (why)
1004
+ choice = Promise.resolve(choose("indexeddb", why));
1005
+ else
1006
+ choice = rt.call({ t: "probe" }).then(() => choose("opfs"), (e) => choose("indexeddb", e?.message));
1007
+ }
1008
+ return choice;
1009
+ }
1010
+
1011
+ // src/events.ts
1012
+ class PlateauEvent {
1013
+ type;
1014
+ bubbles;
1015
+ cancelable;
1016
+ isTrusted = true;
1017
+ target = null;
1018
+ currentTarget = null;
1019
+ eventPhase = 0;
1020
+ defaultPrevented = false;
1021
+ stopped = false;
1022
+ stoppedNow = false;
1023
+ constructor(type, init = {}) {
1024
+ this.type = type;
1025
+ this.bubbles = !!init.bubbles;
1026
+ this.cancelable = !!init.cancelable;
1027
+ }
1028
+ preventDefault() {
1029
+ if (this.cancelable)
1030
+ this.defaultPrevented = true;
1031
+ }
1032
+ stopPropagation() {
1033
+ this.stopped = true;
1034
+ }
1035
+ stopImmediatePropagation() {
1036
+ this.stopped = true;
1037
+ this.stoppedNow = true;
1038
+ }
1039
+ get timeStamp() {
1040
+ return performance.now();
1041
+ }
1042
+ get cancelBubble() {
1043
+ return this.stopped;
1044
+ }
1045
+ get returnValue() {
1046
+ return !this.defaultPrevented;
1047
+ }
1048
+ }
1049
+
1050
+ class PlateauVersionChangeEvent extends PlateauEvent {
1051
+ oldVersion;
1052
+ newVersion;
1053
+ constructor(type, init = {}) {
1054
+ super(type);
1055
+ this.oldVersion = init.oldVersion ?? 0;
1056
+ this.newVersion = init.newVersion ?? null;
1057
+ }
1058
+ }
1059
+
1060
+ class PlateauTarget {
1061
+ entries = null;
1062
+ slots = null;
1063
+ parentTarget() {
1064
+ return null;
1065
+ }
1066
+ addEventListener(type, fn, opts) {
1067
+ if (!fn)
1068
+ return;
1069
+ const capture = typeof opts === "boolean" ? opts : !!opts?.capture;
1070
+ const once = typeof opts === "object" && !!opts?.once;
1071
+ this.entries ??= [];
1072
+ if (this.entries.some((e) => !e.removed && e.type === type && e.fn === fn && e.capture === capture))
1073
+ return;
1074
+ this.entries.push({ type, capture, once, fn });
1075
+ }
1076
+ removeEventListener(type, fn, opts) {
1077
+ const capture = typeof opts === "boolean" ? opts : !!opts?.capture;
1078
+ if (!this.entries)
1079
+ return;
1080
+ const i = this.entries.findIndex((e) => !e.removed && e.type === type && e.fn === fn && e.capture === capture);
1081
+ if (i >= 0) {
1082
+ this.entries[i].removed = true;
1083
+ this.entries.splice(i, 1);
1084
+ }
1085
+ }
1086
+ getHandler(type) {
1087
+ return this.slots?.[type] ?? null;
1088
+ }
1089
+ setHandler(type, fn) {
1090
+ const f = typeof fn === "function" ? fn : null;
1091
+ this.entries ??= [];
1092
+ this.slots ??= {};
1093
+ if (f) {
1094
+ let has = false;
1095
+ for (const e of this.entries)
1096
+ if (e.slot === type)
1097
+ has = true;
1098
+ if (!has)
1099
+ this.entries.push({ type, capture: false, once: false, fn: null, slot: type });
1100
+ } else {
1101
+ const i = this.entries.findIndex((e) => e.slot === type);
1102
+ if (i >= 0) {
1103
+ this.entries[i].removed = true;
1104
+ this.entries.splice(i, 1);
1105
+ }
1106
+ }
1107
+ this.slots[type] = f;
1108
+ }
1109
+ hasListeners() {
1110
+ return this.entries !== null && this.entries.length > 0;
1111
+ }
1112
+ listensOnPath(type, bubbles) {
1113
+ const entries = this.entries;
1114
+ if (entries === null)
1115
+ return false;
1116
+ for (const e of entries)
1117
+ if (e.type === type && (bubbles || e.capture))
1118
+ return true;
1119
+ return false;
1120
+ }
1121
+ dispatchEvent(e) {
1122
+ dispatch(this, e);
1123
+ return !e.defaultPrevented;
1124
+ }
1125
+ invoke(e, phase, out) {
1126
+ const entries = this.entries;
1127
+ if (entries === null || entries.length === 0)
1128
+ return;
1129
+ let only = null;
1130
+ let matches = 0;
1131
+ for (const x of entries) {
1132
+ if (x.type === e.type) {
1133
+ matches++;
1134
+ only = x;
1135
+ }
1136
+ }
1137
+ if (matches === 0)
1138
+ return;
1139
+ if (matches !== 1)
1140
+ only = null;
1141
+ if (only !== null && only.slot !== undefined && phase !== "capture") {
1142
+ const fn = this.slots[only.slot];
1143
+ if (fn) {
1144
+ try {
1145
+ fn.call(this, e);
1146
+ } catch (err) {
1147
+ out.threw = true;
1148
+ report(err);
1149
+ }
1150
+ }
1151
+ return;
1152
+ }
1153
+ const list = entries.filter((x) => x.type === e.type && (phase === "target" || x.capture === (phase === "capture")));
1154
+ for (const x of list) {
1155
+ if (x.removed)
1156
+ continue;
1157
+ if (x.once)
1158
+ this.removeEventListener(x.type, x.fn, x.capture);
1159
+ const fn = x.slot ? this.slots[x.slot] : x.fn;
1160
+ if (!fn)
1161
+ continue;
1162
+ try {
1163
+ if (typeof fn === "function")
1164
+ fn.call(this, e);
1165
+ else
1166
+ fn.handleEvent(e);
1167
+ } catch (err) {
1168
+ out.threw = true;
1169
+ report(err);
1170
+ }
1171
+ if (e.stoppedNow)
1172
+ break;
1173
+ }
1174
+ }
1175
+ }
1176
+ function report(err) {
1177
+ const g = globalThis;
1178
+ if (g.reportError)
1179
+ g.reportError(err);
1180
+ else
1181
+ setTimeout(() => {
1182
+ throw err;
1183
+ });
1184
+ }
1185
+ function dispatch(target, e) {
1186
+ const p1 = target.parentTarget();
1187
+ const p2 = p1 === null ? null : p1.parentTarget();
1188
+ if ((p2 === null || p2.parentTarget() === null) && (p1 === null || !p1.listensOnPath(e.type, e.bubbles)) && (p2 === null || !p2.listensOnPath(e.type, e.bubbles))) {
1189
+ const out = { threw: false };
1190
+ e.target = target;
1191
+ e.eventPhase = 2;
1192
+ e.currentTarget = target;
1193
+ target.invoke(e, "target", out);
1194
+ e.eventPhase = 0;
1195
+ e.currentTarget = null;
1196
+ return out;
1197
+ }
1198
+ const path = [];
1199
+ for (let t = target.parentTarget();t; t = t.parentTarget())
1200
+ path.push(t);
1201
+ const out = { threw: false };
1202
+ e.target = target;
1203
+ e.eventPhase = 1;
1204
+ for (let i = path.length - 1;i >= 0 && !e.stopped; i--) {
1205
+ e.currentTarget = path[i];
1206
+ path[i].invoke(e, "capture", out);
1207
+ }
1208
+ if (!e.stopped) {
1209
+ e.eventPhase = 2;
1210
+ e.currentTarget = target;
1211
+ target.invoke(e, "target", out);
1212
+ }
1213
+ if (e.bubbles) {
1214
+ e.eventPhase = 3;
1215
+ for (let i = 0;i < path.length && !e.stopped; i++) {
1216
+ e.currentTarget = path[i];
1217
+ path[i].invoke(e, "bubble", out);
1218
+ }
1219
+ }
1220
+ e.eventPhase = 0;
1221
+ e.currentTarget = null;
1222
+ return out;
1223
+ }
1224
+ function handlers(cls, types) {
1225
+ for (const type of types) {
1226
+ Object.defineProperty(cls.prototype, `on${type}`, {
1227
+ get() {
1228
+ return this.getHandler(type);
1229
+ },
1230
+ set(fn) {
1231
+ this.setHandler(type, fn);
1232
+ },
1233
+ configurable: true,
1234
+ enumerable: true
1235
+ });
1236
+ }
1237
+ }
1238
+
1239
+ // src/fallback.ts
1240
+ var CHANNEL = "plateau/fallback/changed";
1241
+ var instrumented = new WeakSet;
1242
+ var closed = new WeakSet;
1243
+ var observed = new Map;
1244
+ var channel;
1245
+ function hub() {
1246
+ if (channel === undefined) {
1247
+ channel = typeof BroadcastChannel === "function" ? new BroadcastChannel(CHANNEL) : null;
1248
+ if (channel)
1249
+ channel.onmessage = (e) => notify(e.data.db, e.data.stores);
1250
+ }
1251
+ return channel;
1252
+ }
1253
+ function notify(name, stores) {
1254
+ for (const observers of observed.get(name)?.values() ?? []) {
1255
+ for (const o of observers) {
1256
+ const hit = stores.filter((s) => o.stores.has(s));
1257
+ if (!hit.length)
1258
+ continue;
1259
+ try {
1260
+ o.callback({ stores: hit });
1261
+ } catch (e) {
1262
+ reportError(e);
1263
+ }
1264
+ }
1265
+ }
1266
+ }
1267
+ function forget(db) {
1268
+ closed.add(db);
1269
+ const m = observed.get(db.name);
1270
+ m?.delete(db);
1271
+ if (m && !m.size)
1272
+ observed.delete(db.name);
1273
+ }
1274
+ function own(target, name, value) {
1275
+ Object.defineProperty(target, name, { value, configurable: true, writable: true, enumerable: false });
1276
+ }
1277
+ var protoCache = null;
1278
+ var protos = () => ({
1279
+ transaction: IDBDatabase.prototype.transaction,
1280
+ createObjectStore: IDBDatabase.prototype.createObjectStore,
1281
+ close: IDBDatabase.prototype.close,
1282
+ objectStore: IDBTransaction.prototype.objectStore,
1283
+ getAll: IDBObjectStore.prototype.getAll,
1284
+ getAllKeys: IDBObjectStore.prototype.getAllKeys,
1285
+ index: IDBObjectStore.prototype.index,
1286
+ result: Object.getOwnPropertyDescriptor(IDBRequest.prototype, "result").get
1287
+ });
1288
+ var proto = () => protoCache ??= protos();
1289
+ function instrumentDb(db) {
1290
+ if (instrumented.has(db))
1291
+ return;
1292
+ instrumented.add(db);
1293
+ own(db, "transaction", function(...args) {
1294
+ const tx = proto().transaction.apply(this, args);
1295
+ instrumentTx(tx);
1296
+ return tx;
1297
+ });
1298
+ own(db, "createObjectStore", function(...args) {
1299
+ const s = proto().createObjectStore.apply(this, args);
1300
+ instrumentStore(s);
1301
+ return s;
1302
+ });
1303
+ own(db, "close", function() {
1304
+ forget(this);
1305
+ proto().close.call(this);
1306
+ });
1307
+ own(db, "observe", function(stores, callback) {
1308
+ if (closed.has(this))
1309
+ throw new DOMException("The connection is closed.", "InvalidStateError");
1310
+ if (typeof callback !== "function")
1311
+ throw new TypeError("plateau: observe needs a callback.");
1312
+ hub();
1313
+ const o = { stores: new Set(typeof stores === "string" ? [stores] : [...stores].map(String)), callback };
1314
+ let m = observed.get(this.name);
1315
+ if (!m)
1316
+ observed.set(this.name, m = new Map);
1317
+ let set = m.get(this);
1318
+ if (!set)
1319
+ m.set(this, set = new Set);
1320
+ set.add(o);
1321
+ return () => {
1322
+ set.delete(o);
1323
+ };
1324
+ });
1325
+ own(db, "compact", async function() {
1326
+ if (closed.has(this))
1327
+ throw new DOMException("The connection is closed.", "InvalidStateError");
1328
+ });
1329
+ db.addEventListener("close", () => forget(db));
1330
+ }
1331
+ function instrumentTx(tx) {
1332
+ if (instrumented.has(tx))
1333
+ return;
1334
+ instrumented.add(tx);
1335
+ const opened = new Set;
1336
+ own(tx, "objectStore", function(name) {
1337
+ const s = proto().objectStore.call(this, name);
1338
+ instrumentStore(s);
1339
+ opened.add(s.name);
1340
+ return s;
1341
+ });
1342
+ if (tx.mode !== "readwrite")
1343
+ return;
1344
+ tx.addEventListener("complete", () => {
1345
+ if (!opened.size)
1346
+ return;
1347
+ const stores = [...opened];
1348
+ const name = tx.db.name;
1349
+ notify(name, stores);
1350
+ hub()?.postMessage({ db: name, stores });
1351
+ });
1352
+ }
1353
+ function instrumentStore(s) {
1354
+ if (instrumented.has(s))
1355
+ return;
1356
+ instrumented.add(s);
1357
+ own(s, "query", function(q) {
1358
+ return query(this, q);
1359
+ });
1360
+ }
1361
+ function instrumentOpen(r) {
1362
+ r.addEventListener("upgradeneeded", () => {
1363
+ instrumentDb(r.result);
1364
+ if (r.transaction)
1365
+ instrumentTx(r.transaction);
1366
+ });
1367
+ r.addEventListener("success", () => {
1368
+ const db = proto().result.call(r);
1369
+ if (db instanceof IDBDatabase)
1370
+ instrumentDb(db);
1371
+ });
1372
+ }
1373
+ function test(f) {
1374
+ let one;
1375
+ switch (f.op) {
1376
+ case "eq": {
1377
+ const v = Number(f.value);
1378
+ one = (x) => x === v;
1379
+ break;
1380
+ }
1381
+ case "in": {
1382
+ const set = new Set((f.values ?? []).map(Number));
1383
+ one = (x) => set.has(x);
1384
+ break;
1385
+ }
1386
+ case "range": {
1387
+ const { gt, gte, lt, lte } = f;
1388
+ if ([gt, gte, lt, lte].some((b) => b !== undefined && b !== null && Number.isNaN(Number(b))))
1389
+ return () => false;
1390
+ const has = (b) => b !== undefined && b !== null;
1391
+ one = (x) => (!has(gt) || x > gt) && (!has(gte) || x >= gte) && (!has(lt) || x < lt) && (!has(lte) || x <= lte);
1392
+ break;
1393
+ }
1394
+ default:
1395
+ throw new TypeError(`plateau: unknown query op ${String(f.op)}.`);
1396
+ }
1397
+ return (x) => {
1398
+ if (typeof x === "number")
1399
+ return !Number.isNaN(x) && one(x);
1400
+ if (Array.isArray(x))
1401
+ return x.some((y) => typeof y === "number" && one(y));
1402
+ return false;
1403
+ };
1404
+ }
1405
+ function field(v, name) {
1406
+ return v !== null && typeof v === "object" ? v[name] : undefined;
1407
+ }
1408
+ function run(q, keys, values, tests) {
1409
+ let rows = [];
1410
+ for (let i = 0;i < values.length; i++)
1411
+ if (tests.every(([f, t]) => t(field(values[i], f))))
1412
+ rows.push(i);
1413
+ if (q.count)
1414
+ return rows.length;
1415
+ const o = q.orderBy;
1416
+ if (o) {
1417
+ const dir = o.desc ? -1 : 1;
1418
+ const at = (i) => {
1419
+ const x = field(values[i], o.field);
1420
+ return typeof x === "number" && !Number.isNaN(x) ? x : null;
1421
+ };
1422
+ rows = rows.sort((a, b) => {
1423
+ const x = at(a);
1424
+ const y = at(b);
1425
+ if (x === null || y === null)
1426
+ return x === y ? cmp(keys[a], keys[b]) : x === null ? 1 : -1;
1427
+ return dir * (x - y || cmp(keys[a], keys[b]));
1428
+ });
1429
+ }
1430
+ if (q.limit !== undefined && q.limit !== null)
1431
+ rows = rows.slice(0, Math.max(0, Math.floor(Number(q.limit))));
1432
+ return rows.map((i) => values[i]);
1433
+ }
1434
+ function query(s, q) {
1435
+ if (q === null || typeof q !== "object")
1436
+ throw new TypeError("plateau: query takes an object.");
1437
+ const where = q.where ?? [];
1438
+ if (!Array.isArray(where))
1439
+ throw new TypeError("plateau: query's where must be an array.");
1440
+ const tests = where.map((f) => [String(f.field), test(f)]);
1441
+ let source = s;
1442
+ let range;
1443
+ let plan = "scan";
1444
+ for (const f of where) {
1445
+ if (f.op !== "eq" || typeof f.value !== "number" || Number.isNaN(f.value))
1446
+ continue;
1447
+ const idx = [...s.indexNames].map((n) => proto().index.call(s, n)).find((i) => i.keyPath === f.field && i.multiEntry);
1448
+ if (!idx)
1449
+ continue;
1450
+ source = idx;
1451
+ range = f.value;
1452
+ plan = `index:${idx.name}`;
1453
+ break;
1454
+ }
1455
+ const keysReq = source instanceof IDBIndex ? source.getAllKeys(range) : proto().getAllKeys.call(s);
1456
+ const valuesReq = source instanceof IDBIndex ? source.getAll(range) : proto().getAll.call(s);
1457
+ let keys = [];
1458
+ let out;
1459
+ keysReq.addEventListener("success", () => keys = keysReq.result);
1460
+ valuesReq.addEventListener("success", () => {
1461
+ out = run(q, keys, proto().result.call(valuesReq), tests);
1462
+ });
1463
+ Object.defineProperty(valuesReq, "result", {
1464
+ configurable: true,
1465
+ get() {
1466
+ proto().result.call(valuesReq);
1467
+ return out;
1468
+ }
1469
+ });
1470
+ own(valuesReq, "plan", plan);
1471
+ return valuesReq;
1472
+ }
1473
+
1474
+ // src/value.ts
1475
+ var TAGS = new Set(["$u", "$n", "$bi", "$d", "$re", "$bo", "$no", "$so", "$ab", "$ta", "$sa", "$m", "$set", "$r"]);
1476
+ var VIEWS = {
1477
+ Int8Array,
1478
+ Uint8Array,
1479
+ Uint8ClampedArray,
1480
+ Int16Array,
1481
+ Uint16Array,
1482
+ Int32Array,
1483
+ Uint32Array,
1484
+ Float32Array,
1485
+ Float64Array,
1486
+ BigInt64Array,
1487
+ BigUint64Array,
1488
+ DataView
1489
+ };
1490
+ function cloneError(what) {
1491
+ return new DOMException(`${what} could not be cloned.`, "DataCloneError");
1492
+ }
1493
+ function toBase64(b) {
1494
+ let s = "";
1495
+ for (let i = 0;i < b.length; i += 8192)
1496
+ s += String.fromCharCode(...b.subarray(i, i + 8192));
1497
+ return btoa(s);
1498
+ }
1499
+ function fromBase64(s) {
1500
+ const bin = atob(s);
1501
+ const b = new Uint8Array(bin.length);
1502
+ for (let i = 0;i < bin.length; i++)
1503
+ b[i] = bin.charCodeAt(i);
1504
+ return b.buffer;
1505
+ }
1506
+ function num(n) {
1507
+ if (Number.isFinite(n) && !Object.is(n, -0))
1508
+ return n;
1509
+ return { $n: Object.is(n, -0) ? "-0" : String(n) };
1510
+ }
1511
+ function unnum(v) {
1512
+ if (typeof v === "number")
1513
+ return v;
1514
+ const s = v.$n;
1515
+ return s === "-0" ? -0 : Number(s);
1516
+ }
1517
+
1518
+ class Encoder {
1519
+ tagged = false;
1520
+ ids = new Map;
1521
+ tag(o) {
1522
+ this.tagged = true;
1523
+ return o;
1524
+ }
1525
+ walk(v) {
1526
+ switch (typeof v) {
1527
+ case "string":
1528
+ case "boolean":
1529
+ return v;
1530
+ case "number": {
1531
+ const out = num(v);
1532
+ if (out !== v)
1533
+ this.tagged = true;
1534
+ return out;
1535
+ }
1536
+ case "undefined":
1537
+ return this.tag({ $u: 0 });
1538
+ case "bigint":
1539
+ return this.tag({ $bi: v.toString() });
1540
+ case "object":
1541
+ break;
1542
+ default:
1543
+ throw cloneError(typeof v === "function" ? "A function" : `A ${typeof v}`);
1544
+ }
1545
+ if (v === null)
1546
+ return null;
1547
+ const seen = this.ids.get(v);
1548
+ if (seen !== undefined)
1549
+ return this.tag({ $r: seen });
1550
+ this.ids.set(v, this.ids.size);
1551
+ const kind = Object.prototype.toString.call(v).slice(8, -1);
1552
+ if (Array.isArray(v)) {
1553
+ const n = v.length;
1554
+ let dense = true;
1555
+ for (let i = 0;i < n; i++) {
1556
+ if (!Object.prototype.hasOwnProperty.call(v, i)) {
1557
+ dense = false;
1558
+ break;
1559
+ }
1560
+ }
1561
+ if (dense) {
1562
+ const out = new Array(n);
1563
+ for (let i = 0;i < n; i++)
1564
+ out[i] = this.walk(v[i]);
1565
+ return out;
1566
+ }
1567
+ const items = [];
1568
+ for (const k of Object.keys(v)) {
1569
+ const i = Number(k);
1570
+ if (Number.isInteger(i) && i >= 0 && String(i) === k)
1571
+ items.push([i, this.walk(v[i])]);
1572
+ }
1573
+ return this.tag({ $sa: [n, items] });
1574
+ }
1575
+ switch (kind) {
1576
+ case "Object":
1577
+ break;
1578
+ case "Date":
1579
+ return this.tag({ $d: num(v.getTime()) });
1580
+ case "RegExp":
1581
+ return this.tag({ $re: [v.source, v.flags] });
1582
+ case "Boolean":
1583
+ return this.tag({ $bo: v.valueOf() });
1584
+ case "Number":
1585
+ return this.tag({ $no: num(v.valueOf()) });
1586
+ case "String":
1587
+ return this.tag({ $so: v.valueOf() });
1588
+ case "ArrayBuffer":
1589
+ return this.tag({ $ab: toBase64(new Uint8Array(v)) });
1590
+ case "Map": {
1591
+ const items = [];
1592
+ for (const [k, x] of v)
1593
+ items.push([this.walk(k), this.walk(x)]);
1594
+ return this.tag({ $m: items });
1595
+ }
1596
+ case "Set": {
1597
+ const items = [];
1598
+ for (const x of v)
1599
+ items.push(this.walk(x));
1600
+ return this.tag({ $set: items });
1601
+ }
1602
+ default:
1603
+ if (ArrayBuffer.isView(v) && kind in VIEWS) {
1604
+ return this.tag({ $ta: [kind, toBase64(new Uint8Array(v.buffer, v.byteOffset, v.byteLength))] });
1605
+ }
1606
+ throw cloneError(`An object of type ${kind}`);
1607
+ }
1608
+ const out = {};
1609
+ for (const k of Object.keys(v)) {
1610
+ const x = this.walk(v[k]);
1611
+ if (k.charCodeAt(0) === 36) {
1612
+ this.tagged = true;
1613
+ out["$" + k] = x;
1614
+ } else
1615
+ out[k] = x;
1616
+ }
1617
+ return out;
1618
+ }
1619
+ }
1620
+ function encodeValue(v) {
1621
+ const e = new Encoder;
1622
+ const tree = e.walk(v);
1623
+ return (e.tagged ? "T" : "J") + JSON.stringify(tree);
1624
+ }
1625
+ function decodeValue(s) {
1626
+ const tree = JSON.parse(s.slice(1));
1627
+ return s.charCodeAt(0) === 74 ? tree : new Decoder().walk(tree);
1628
+ }
1629
+ class Decoder {
1630
+ objects = [];
1631
+ walk(t) {
1632
+ if (t === null || typeof t !== "object")
1633
+ return t;
1634
+ if (Array.isArray(t)) {
1635
+ const out = new Array(t.length);
1636
+ this.objects.push(out);
1637
+ for (let i = 0;i < t.length; i++)
1638
+ out[i] = this.walk(t[i]);
1639
+ return out;
1640
+ }
1641
+ const keys = Object.keys(t);
1642
+ const o = t;
1643
+ if (keys.length === 1 && TAGS.has(keys[0])) {
1644
+ const x = o[keys[0]];
1645
+ switch (keys[0]) {
1646
+ case "$u":
1647
+ return;
1648
+ case "$n":
1649
+ return unnum(t);
1650
+ case "$bi":
1651
+ return BigInt(x);
1652
+ case "$r":
1653
+ return this.objects[x];
1654
+ }
1655
+ let out;
1656
+ const at = this.objects.length;
1657
+ this.objects.push(null);
1658
+ switch (keys[0]) {
1659
+ case "$d":
1660
+ out = new Date(unnum(x));
1661
+ break;
1662
+ case "$re":
1663
+ out = new RegExp(x[0], x[1]);
1664
+ break;
1665
+ case "$bo":
1666
+ out = new Boolean(x);
1667
+ break;
1668
+ case "$no":
1669
+ out = new Number(unnum(x));
1670
+ break;
1671
+ case "$so":
1672
+ out = new String(x);
1673
+ break;
1674
+ case "$ab":
1675
+ out = fromBase64(x);
1676
+ break;
1677
+ case "$ta": {
1678
+ const [kind, b64] = x;
1679
+ out = new VIEWS[kind](fromBase64(b64));
1680
+ break;
1681
+ }
1682
+ case "$sa": {
1683
+ const [n, items] = x;
1684
+ const arr = new Array(n);
1685
+ this.objects[at] = arr;
1686
+ for (const [i, v] of items)
1687
+ arr[i] = this.walk(v);
1688
+ return arr;
1689
+ }
1690
+ case "$m": {
1691
+ const m = new Map;
1692
+ this.objects[at] = m;
1693
+ for (const [k, v] of x) {
1694
+ const kk = this.walk(k);
1695
+ m.set(kk, this.walk(v));
1696
+ }
1697
+ return m;
1698
+ }
1699
+ case "$set": {
1700
+ const s = new Set;
1701
+ this.objects[at] = s;
1702
+ for (const v of x)
1703
+ s.add(this.walk(v));
1704
+ return s;
1705
+ }
1706
+ }
1707
+ this.objects[at] = out;
1708
+ return out;
1709
+ }
1710
+ const out = {};
1711
+ this.objects.push(out);
1712
+ for (const k of keys) {
1713
+ const v = this.walk(o[k]);
1714
+ if (k.charCodeAt(0) === 36)
1715
+ out[k.slice(1)] = v;
1716
+ else
1717
+ out[k] = v;
1718
+ }
1719
+ return out;
1720
+ }
1721
+ }
1722
+
1723
+ // src/facade.ts
1724
+ var err = (name, message) => new DOMException(message, name);
1725
+ var afterTask = (() => {
1726
+ let queue = [];
1727
+ let ch = null;
1728
+ let armed = false;
1729
+ let timerFirst = null;
1730
+ const run = (byTimer) => {
1731
+ if (!armed)
1732
+ return;
1733
+ timerFirst ??= byTimer;
1734
+ armed = false;
1735
+ const q = queue;
1736
+ queue = [];
1737
+ for (const f of q)
1738
+ f();
1739
+ };
1740
+ return (fn) => {
1741
+ if (!ch) {
1742
+ ch = new MessageChannel;
1743
+ ch.port1.onmessage = () => run(false);
1744
+ }
1745
+ queue.push(fn);
1746
+ if (!armed) {
1747
+ armed = true;
1748
+ ch.port2.postMessage(0);
1749
+ if (timerFirst !== false)
1750
+ setTimeout(() => run(true), 0);
1751
+ }
1752
+ };
1753
+ })();
1754
+ function stringList(names) {
1755
+ const a = [...names].sort();
1756
+ a.contains = (s) => a.includes(String(s));
1757
+ a.item = (i) => a[i] ?? null;
1758
+ return a;
1759
+ }
1760
+ var PREFETCH = 32;
1761
+
1762
+ class PlateauRequest extends PlateauTarget {
1763
+ _result = undefined;
1764
+ _error = null;
1765
+ _done = false;
1766
+ kind;
1767
+ cursor = null;
1768
+ source;
1769
+ transaction;
1770
+ plan;
1771
+ known = undefined;
1772
+ constructor(source, transaction, kind) {
1773
+ super();
1774
+ this.source = source;
1775
+ this.transaction = transaction;
1776
+ this.kind = kind;
1777
+ }
1778
+ get readyState() {
1779
+ return this._done ? "done" : "pending";
1780
+ }
1781
+ get result() {
1782
+ if (!this._done)
1783
+ throw err("InvalidStateError", "The request has not finished.");
1784
+ return this._result;
1785
+ }
1786
+ get error() {
1787
+ if (!this._done)
1788
+ throw err("InvalidStateError", "The request has not finished.");
1789
+ return this._error;
1790
+ }
1791
+ parentTarget() {
1792
+ return this.transaction;
1793
+ }
1794
+ }
1795
+ handlers(PlateauRequest, ["success", "error"]);
1796
+
1797
+ class PlateauOpenDBRequest extends PlateauRequest {
1798
+ constructor() {
1799
+ super(null, null, "value");
1800
+ }
1801
+ }
1802
+ handlers(PlateauOpenDBRequest, ["blocked", "upgradeneeded"]);
1803
+ function promise(r) {
1804
+ return new Promise((resolve, reject) => {
1805
+ r.addEventListener("success", () => resolve(r.result));
1806
+ r.addEventListener("error", () => reject(r.error));
1807
+ });
1808
+ }
1809
+ var connections = new Map;
1810
+ function enqueue(name, job) {
1811
+ runtime().queue(name, job);
1812
+ }
1813
+ function toVersion(v) {
1814
+ if (v === undefined)
1815
+ return;
1816
+ const n = Number(v);
1817
+ if (!Number.isFinite(n) || n < 1 || n > Number.MAX_SAFE_INTEGER)
1818
+ throw new TypeError("The version must be a positive integer.");
1819
+ return Math.floor(n);
1820
+ }
1821
+ function versionChangeHere(name, self, oldVersion, newVersion) {
1822
+ const others = [...connections.get(name) ?? []].filter((c) => c !== self && !c._closePending);
1823
+ for (const c of others) {
1824
+ if (c._closePending)
1825
+ continue;
1826
+ dispatch(c, new PlateauVersionChangeEvent("versionchange", { oldVersion: oldVersion ?? c._version, newVersion }));
1827
+ }
1828
+ const open = others.filter((c) => !c._closed);
1829
+ if (!open.length)
1830
+ return null;
1831
+ return {
1832
+ ack: { blocking: open.some((c) => !c._closePending), version: open[0]._version },
1833
+ closed: Promise.all(open.map((c) => c._closedPromise)).then(() => {})
1834
+ };
1835
+ }
1836
+ onVersionChange((name, oldVersion, newVersion) => versionChangeHere(name, null, oldVersion, newVersion));
1837
+ async function closeOthers(name, self, oldVersion, newVersion, req) {
1838
+ const here = versionChangeHere(name, self, oldVersion, newVersion);
1839
+ const elsewhere = runtime().versionChange(name, oldVersion, newVersion);
1840
+ let ack = here?.ack;
1841
+ if (!ack?.blocking && elsewhere) {
1842
+ const remote = await elsewhere.ack;
1843
+ ack = { blocking: remote.blocking, version: Math.max(ack?.version ?? 0, remote.version) };
1844
+ }
1845
+ if (ack?.blocking)
1846
+ dispatch(req, new PlateauVersionChangeEvent("blocked", { oldVersion: oldVersion ?? ack.version, newVersion }));
1847
+ await Promise.all([here?.closed, elsewhere?.closed]);
1848
+ }
1849
+ function changed(name, stores) {
1850
+ for (const c of connections.get(name) ?? []) {
1851
+ if (c._closePending)
1852
+ continue;
1853
+ for (const o of c._observers) {
1854
+ const hit = stores.filter((s) => o.stores.has(s));
1855
+ if (!hit.length)
1856
+ continue;
1857
+ try {
1858
+ o.callback({ stores: hit });
1859
+ } catch (e) {
1860
+ reportError(e);
1861
+ }
1862
+ }
1863
+ }
1864
+ }
1865
+ onChange(changed);
1866
+ function finishRequest(req, result, error) {
1867
+ req._done = true;
1868
+ req._result = result;
1869
+ req._error = error;
1870
+ }
1871
+
1872
+ class BridgedRequest extends PlateauOpenDBRequest {
1873
+ parentTarget() {
1874
+ return null;
1875
+ }
1876
+ }
1877
+ function bridge(req, nat) {
1878
+ const b = req;
1879
+ Object.setPrototypeOf(b, BridgedRequest.prototype);
1880
+ const settle = () => {
1881
+ b._done = true;
1882
+ b._result = nat.result;
1883
+ b._error = nat.error;
1884
+ };
1885
+ nat.addEventListener("upgradeneeded", (e) => {
1886
+ settle();
1887
+ b.transaction = nat.transaction;
1888
+ const out = dispatch(b, new PlateauVersionChangeEvent("upgradeneeded", { oldVersion: e.oldVersion, newVersion: e.newVersion }));
1889
+ if (out.threw)
1890
+ nat.transaction?.abort();
1891
+ });
1892
+ nat.addEventListener("blocked", (e) => {
1893
+ dispatch(b, new PlateauVersionChangeEvent("blocked", { oldVersion: e.oldVersion, newVersion: e.newVersion }));
1894
+ });
1895
+ nat.addEventListener("success", (e) => {
1896
+ settle();
1897
+ b.transaction = null;
1898
+ const v = e;
1899
+ dispatch(b, v.oldVersion === undefined ? new PlateauEvent("success") : new PlateauVersionChangeEvent("success", { oldVersion: v.oldVersion, newVersion: v.newVersion }));
1900
+ });
1901
+ nat.addEventListener("error", () => {
1902
+ settle();
1903
+ b.transaction = null;
1904
+ dispatch(b, new PlateauEvent("error", { bubbles: true, cancelable: true }));
1905
+ });
1906
+ }
1907
+ function nativeOpen(name, version) {
1908
+ const r = version === undefined ? nativeIndexedDB.open(name) : nativeIndexedDB.open(name, version);
1909
+ instrumentOpen(r);
1910
+ return r;
1911
+ }
1912
+ var fallbackBudget = null;
1913
+
1914
+ class PlateauFactory {
1915
+ get backend() {
1916
+ return chosenBackend();
1917
+ }
1918
+ chooseBackend() {
1919
+ return chooseBackend();
1920
+ }
1921
+ open(name, version) {
1922
+ const n = String(name);
1923
+ const v = toVersion(version);
1924
+ const b = chosenBackend() ?? (void chooseBackend(), chosenBackend());
1925
+ if (b === "indexeddb")
1926
+ return nativeOpen(n, v);
1927
+ const req = new PlateauOpenDBRequest;
1928
+ if (b === "opfs")
1929
+ enqueue(n, () => openDatabase(req, n, v));
1930
+ else
1931
+ chooseBackend().then((b) => b === "opfs" ? enqueue(n, () => openDatabase(req, n, v)) : bridge(req, nativeOpen(n, v)));
1932
+ return req;
1933
+ }
1934
+ deleteDatabase(name) {
1935
+ const n = String(name);
1936
+ const b = chosenBackend() ?? (void chooseBackend(), chosenBackend());
1937
+ if (b === "indexeddb")
1938
+ return nativeIndexedDB.deleteDatabase(n);
1939
+ const req = new PlateauOpenDBRequest;
1940
+ if (b === "opfs")
1941
+ this.deleteHere(req, n);
1942
+ else
1943
+ chooseBackend().then((b) => b === "opfs" ? this.deleteHere(req, n) : bridge(req, nativeIndexedDB.deleteDatabase(n)));
1944
+ return req;
1945
+ }
1946
+ deleteHere(req, n) {
1947
+ enqueue(n, async () => {
1948
+ await new Promise((r) => afterTask(r));
1949
+ await closeOthers(n, null, null, null, req);
1950
+ let old = 0;
1951
+ try {
1952
+ old = await runtime().call({ t: "delete", db: n });
1953
+ } catch (e) {
1954
+ finishRequest(req, undefined, e);
1955
+ dispatch(req, new PlateauEvent("error", { bubbles: true, cancelable: true }));
1956
+ return;
1957
+ }
1958
+ finishRequest(req, undefined, null);
1959
+ dispatch(req, new PlateauVersionChangeEvent("success", { oldVersion: old, newVersion: null }));
1960
+ });
1961
+ }
1962
+ cmp(a, b) {
1963
+ return cmp(a, b);
1964
+ }
1965
+ async databases() {
1966
+ if (await chooseBackend() === "indexeddb" && typeof nativeIndexedDB.databases === "function") {
1967
+ return await nativeIndexedDB.databases();
1968
+ }
1969
+ return [];
1970
+ }
1971
+ whenLeader() {
1972
+ return runtime().leading;
1973
+ }
1974
+ async setMemoryBudget(bytes) {
1975
+ if (bytes !== null && !(bytes > 0))
1976
+ throw new TypeError("plateau: the memory budget must be a positive number of bytes, or null.");
1977
+ if (await chooseBackend() === "indexeddb") {
1978
+ fallbackBudget = bytes;
1979
+ return;
1980
+ }
1981
+ await runtime().call({ t: "budget", bytes });
1982
+ }
1983
+ async memoryStats(name) {
1984
+ if (await chooseBackend() === "indexeddb")
1985
+ return { wasmMemoryBytes: 0, budgetBytes: fallbackBudget ?? Infinity, cachedBytes: 0 };
1986
+ return runtime().call(name === undefined ? { t: "stats" } : { t: "stats", db: String(name) });
1987
+ }
1988
+ }
1989
+ async function openDatabase(req, name, version) {
1990
+ await new Promise((r) => afterTask(r));
1991
+ const rt = runtime();
1992
+ let info;
1993
+ try {
1994
+ info = await rt.call({ t: "open", db: name });
1995
+ } catch (e) {
1996
+ finishRequest(req, undefined, e);
1997
+ dispatch(req, new PlateauEvent("error", { bubbles: true, cancelable: true }));
1998
+ return;
1999
+ }
2000
+ const cur = info.version;
2001
+ const want = version ?? Math.max(cur, 1);
2002
+ if (want < cur) {
2003
+ await rt.call({ t: "close", db: name });
2004
+ finishRequest(req, undefined, err("VersionError", `The requested version (${want}) is less than the existing version (${cur}).`));
2005
+ dispatch(req, new PlateauEvent("error", { bubbles: true, cancelable: true }));
2006
+ return;
2007
+ }
2008
+ const db = new PlateauDatabase(name, cur, info.nextId, info.stores);
2009
+ let set = connections.get(name);
2010
+ if (!set)
2011
+ connections.set(name, set = new Set);
2012
+ if (want > cur) {
2013
+ await closeOthers(name, db, cur, want, req);
2014
+ set.add(db);
2015
+ db._version = want;
2016
+ const tx = new PlateauTransaction(db, [...db._stores.keys()], "versionchange", want);
2017
+ db._upgrade = tx;
2018
+ req.transaction = tx;
2019
+ finishRequest(req, db, null);
2020
+ tx._state = "active";
2021
+ tx._settleSoon();
2022
+ const out = dispatch(req, new PlateauVersionChangeEvent("upgradeneeded", { oldVersion: cur, newVersion: want }));
2023
+ if (out.threw)
2024
+ tx._abort(err("AbortError", "An exception was thrown in the upgradeneeded handler."));
2025
+ await tx._finishedPromise();
2026
+ db._upgrade = null;
2027
+ req.transaction = null;
2028
+ if (tx._aborted || db._closePending) {
2029
+ db._version = cur;
2030
+ if (!db._closePending)
2031
+ db._closeNow();
2032
+ finishRequest(req, undefined, err("AbortError", "The upgrade transaction was aborted."));
2033
+ dispatch(req, new PlateauEvent("error", { bubbles: true, cancelable: true }));
2034
+ return;
2035
+ }
2036
+ } else
2037
+ set.add(db);
2038
+ finishRequest(req, db, null);
2039
+ dispatch(req, new PlateauEvent("success"));
2040
+ }
2041
+
2042
+ class PlateauDatabase extends PlateauTarget {
2043
+ name;
2044
+ _version;
2045
+ _stores = new Map;
2046
+ _nextId;
2047
+ _upgrade = null;
2048
+ _txs = new Set;
2049
+ _closePending = false;
2050
+ _observers = new Set;
2051
+ _closed = false;
2052
+ _closedPromise;
2053
+ markClosed = () => {};
2054
+ constructor(name, version, nextId, stores) {
2055
+ super();
2056
+ this.name = name;
2057
+ this._version = version;
2058
+ this._nextId = nextId;
2059
+ for (const s of stores)
2060
+ this._stores.set(s.name, s);
2061
+ this._closedPromise = new Promise((r) => this.markClosed = r);
2062
+ }
2063
+ get version() {
2064
+ return this._version;
2065
+ }
2066
+ get objectStoreNames() {
2067
+ return stringList(this._stores.keys());
2068
+ }
2069
+ upgradeTx() {
2070
+ const tx = this._upgrade;
2071
+ if (!tx || tx._state === "finished")
2072
+ throw err("InvalidStateError", "Not in a version change transaction.");
2073
+ if (tx._state !== "active")
2074
+ throw err("TransactionInactiveError", "The version change transaction is not active.");
2075
+ return tx;
2076
+ }
2077
+ createObjectStore(name, options = {}) {
2078
+ const tx = this.upgradeTx();
2079
+ const n = String(name);
2080
+ const keyPath = normalizeKeyPath(options?.keyPath ?? null);
2081
+ if (keyPath !== null && !validKeyPath(keyPath))
2082
+ throw err("SyntaxError", "The keyPath is not a valid key path.");
2083
+ if (this._stores.has(n))
2084
+ throw err("ConstraintError", `An object store named ${n} already exists.`);
2085
+ const autoIncrement = !!options?.autoIncrement;
2086
+ if (autoIncrement && (keyPath === "" || Array.isArray(keyPath)))
2087
+ throw err("InvalidAccessError", "autoIncrement needs a non-empty, non-array key path.");
2088
+ const id = this._nextId++;
2089
+ const def = { id, file: `s${id}`, name: n, keyPath, autoIncrement, indexes: [] };
2090
+ if (options?.columns !== undefined)
2091
+ def.columns = columnDecls(options.columns, keyPath);
2092
+ this._stores.set(n, def);
2093
+ tx._scope.push(n);
2094
+ tx._internal({ o: "mkStore", def: structuredClone(def) });
2095
+ return tx.objectStore(n);
2096
+ }
2097
+ deleteObjectStore(name) {
2098
+ const tx = this.upgradeTx();
2099
+ const n = String(name);
2100
+ const def = this._stores.get(n);
2101
+ if (!def)
2102
+ throw err("NotFoundError", `No object store named ${n}.`);
2103
+ this._stores.delete(n);
2104
+ tx._scope = tx._scope.filter((s) => s !== n);
2105
+ tx._handles.delete(n);
2106
+ tx._internal({ o: "rmStore", s: n });
2107
+ }
2108
+ transaction(names, mode = "readonly", options) {
2109
+ if (this._closePending)
2110
+ throw err("InvalidStateError", "The connection is closed.");
2111
+ if (this._upgrade && this._upgrade._state !== "finished")
2112
+ throw err("InvalidStateError", "A version change transaction is running.");
2113
+ const list = typeof names === "string" ? [names] : [...names].map(String);
2114
+ const scope = [...new Set(list)];
2115
+ for (const s of scope)
2116
+ if (!this._stores.has(s))
2117
+ throw err("NotFoundError", `No object store named ${s}.`);
2118
+ if (mode !== "readonly" && mode !== "readwrite")
2119
+ throw new TypeError(`The mode ${String(mode)} is not valid.`);
2120
+ if (!scope.length)
2121
+ throw err("InvalidAccessError", "The scope is empty.");
2122
+ const tx = new PlateauTransaction(this, scope, mode);
2123
+ tx.durability = options?.durability ?? "default";
2124
+ tx._settleSoon();
2125
+ return tx;
2126
+ }
2127
+ close() {
2128
+ if (this._closePending)
2129
+ return;
2130
+ this._closePending = true;
2131
+ this._maybeClosed();
2132
+ }
2133
+ observe(stores, callback) {
2134
+ if (this._closePending)
2135
+ throw err("InvalidStateError", "The connection is closed.");
2136
+ if (typeof callback !== "function")
2137
+ throw new TypeError("plateau: observe needs a callback.");
2138
+ const o = { stores: new Set(typeof stores === "string" ? [stores] : [...stores].map(String)), callback };
2139
+ this._observers.add(o);
2140
+ return () => {
2141
+ this._observers.delete(o);
2142
+ };
2143
+ }
2144
+ async compact() {
2145
+ if (this._closePending)
2146
+ throw err("InvalidStateError", "The connection is closed.");
2147
+ while (this._txs.size)
2148
+ await Promise.all([...this._txs].map((tx) => tx._finishedPromise().catch(() => {})));
2149
+ if (this._closePending)
2150
+ throw err("InvalidStateError", "The connection is closed.");
2151
+ await runtime().call({ t: "compact", db: this.name });
2152
+ }
2153
+ _closeNow() {
2154
+ this._closePending = true;
2155
+ this._maybeClosed();
2156
+ }
2157
+ _maybeClosed() {
2158
+ if (!this._closePending || this._closed || this._txs.size)
2159
+ return;
2160
+ this._closed = true;
2161
+ connections.get(this.name)?.delete(this);
2162
+ runtime().call({ t: "close", db: this.name }).finally(() => this.markClosed());
2163
+ }
2164
+ }
2165
+ handlers(PlateauDatabase, ["abort", "close", "error", "versionchange"]);
2166
+ var KINDS = ["u32", "u32_multi", "f64", "str"];
2167
+ function columnDecls(spec, keyPath) {
2168
+ const entries = Array.isArray(spec) ? spec.map((c) => [String(c.name), c]) : Object.entries(spec);
2169
+ const out = entries.map(([name, c]) => {
2170
+ const d = typeof c === "string" ? { kind: c } : c;
2171
+ if (!KINDS.includes(d.kind))
2172
+ throw new TypeError(`plateau: column ${name} has an unknown kind ${String(d.kind)}.`);
2173
+ if (name.startsWith("_") || name.includes("."))
2174
+ throw new TypeError(`plateau: column ${name} must be a plain field name not starting with _.`);
2175
+ const decl = { name, kind: d.kind };
2176
+ if (d.index)
2177
+ decl.index = d.index;
2178
+ if (d.group)
2179
+ decl.group = d.group;
2180
+ return decl;
2181
+ });
2182
+ const pk = out.find((c) => c.name === keyPath);
2183
+ if (typeof keyPath !== "string" || !pk || pk.kind !== "f64")
2184
+ throw new TypeError("plateau: a store with columns needs a key path naming one of them, of kind f64.");
2185
+ return out;
2186
+ }
2187
+
2188
+ class PlateauTransaction extends PlateauTarget {
2189
+ db;
2190
+ mode;
2191
+ durability = "default";
2192
+ _scope;
2193
+ _state = "active";
2194
+ _started = false;
2195
+ _aborted = false;
2196
+ _error = null;
2197
+ _handles = new Map;
2198
+ finished = null;
2199
+ markFinished = null;
2200
+ isFinished = false;
2201
+ id;
2202
+ version;
2203
+ began = false;
2204
+ unsent = [];
2205
+ unsentReqs = [];
2206
+ inflight = [];
2207
+ head = 0;
2208
+ flushQueued = false;
2209
+ settleQueued = false;
2210
+ commitSent = false;
2211
+ beforeUpgrade = null;
2212
+ nextIdBefore = 0;
2213
+ written = null;
2214
+ constructor(db, scope, mode, version) {
2215
+ super();
2216
+ this.db = db;
2217
+ this.mode = mode;
2218
+ this._scope = [...scope].sort();
2219
+ this.version = version;
2220
+ const rt = runtime();
2221
+ this.id = rt.nextTx++;
2222
+ rt.txs.set(this.id, this);
2223
+ db._txs.add(this);
2224
+ if (mode === "versionchange") {
2225
+ this.beforeUpgrade = new Map([...db._stores].map(([k, v]) => [k, structuredClone(v)]));
2226
+ this.nextIdBefore = db._nextId;
2227
+ }
2228
+ scheduler(db.name).add(this);
2229
+ }
2230
+ get objectStoreNames() {
2231
+ return stringList(this._scope);
2232
+ }
2233
+ get error() {
2234
+ return this._error;
2235
+ }
2236
+ get done() {
2237
+ return this._finishedPromise().then(() => {
2238
+ if (this._aborted)
2239
+ throw this._error ?? err("AbortError", "The transaction was aborted.");
2240
+ });
2241
+ }
2242
+ parentTarget() {
2243
+ return this.db;
2244
+ }
2245
+ _finishedPromise() {
2246
+ if (this.isFinished)
2247
+ return Promise.resolve();
2248
+ this.finished ??= new Promise((r) => this.markFinished = r);
2249
+ return this.finished;
2250
+ }
2251
+ objectStore(name) {
2252
+ if (this._state === "finished")
2253
+ throw err("InvalidStateError", "The transaction has finished.");
2254
+ const n = String(name);
2255
+ if (!this._scope.includes(n) || !this.db._stores.has(n))
2256
+ throw err("NotFoundError", `No object store named ${n} in this transaction.`);
2257
+ let h = this._handles.get(n);
2258
+ if (!h || h._def !== this.db._stores.get(n)) {
2259
+ h = new PlateauObjectStore(this, this.db._stores.get(n));
2260
+ this._handles.set(n, h);
2261
+ }
2262
+ return h;
2263
+ }
2264
+ abort() {
2265
+ if (this._state === "finished" || this._state === "committing")
2266
+ throw err("InvalidStateError", "The transaction has finished or is committing.");
2267
+ this._abort(null);
2268
+ }
2269
+ commit() {
2270
+ if (this._state !== "active")
2271
+ throw err("InvalidStateError", "The transaction is not active.");
2272
+ this._state = "inactive";
2273
+ this.settle(true);
2274
+ }
2275
+ _check(write) {
2276
+ if (this._state !== "active")
2277
+ throw err("TransactionInactiveError", "The transaction is not active.");
2278
+ if (write && this.mode === "readonly")
2279
+ throw err("ReadOnlyError", "The transaction is read-only.");
2280
+ }
2281
+ _issue(op, req) {
2282
+ this.unsent.push(op);
2283
+ this.queued(req);
2284
+ }
2285
+ _issueGet(s, key, req) {
2286
+ const last = this.unsent[this.unsent.length - 1];
2287
+ if (last !== undefined && last.o === "get" && last.s === s)
2288
+ last.ks.push(key);
2289
+ else
2290
+ this.unsent.push({ o: "get", s, ks: [key] });
2291
+ this.queued(req);
2292
+ }
2293
+ _issuePut(s, row, req) {
2294
+ const last = this.unsent[this.unsent.length - 1];
2295
+ if (last !== undefined && last.o === "put" && last.s === s)
2296
+ last.rows.push(row);
2297
+ else
2298
+ this.unsent.push({ o: "put", s, rows: [row] });
2299
+ this.queued(req);
2300
+ }
2301
+ _issueTyped(def, t, rest, add, gen, req) {
2302
+ let last = this.unsent[this.unsent.length - 1];
2303
+ if (last === undefined || last.o !== "tput" || last.s !== def.name) {
2304
+ last = { o: "tput", s: def.name, n: 0, cols: def.columns.map((c) => c.kind === "u32_multi" ? [[0], []] : []), v: null, add: [], gen: [] };
2305
+ this.unsent.push(last);
2306
+ }
2307
+ const cols = def.columns;
2308
+ for (let i = 0;i < cols.length; i++) {
2309
+ const b = last.cols[i];
2310
+ if (cols[i].kind === "u32_multi") {
2311
+ const [offsets, values] = b;
2312
+ for (const x of t[i])
2313
+ values.push(x);
2314
+ offsets.push(values.length);
2315
+ } else
2316
+ b.push(t[i]);
2317
+ }
2318
+ if (rest !== "" && last.v === null)
2319
+ last.v = new Array(last.n).fill("");
2320
+ if (last.v !== null)
2321
+ last.v.push(rest);
2322
+ if (add)
2323
+ last.add.push(last.n);
2324
+ if (gen)
2325
+ last.gen.push(last.n);
2326
+ last.n++;
2327
+ this.queued(req);
2328
+ }
2329
+ _issueDeleteNumber(s, key, req) {
2330
+ const last = this.unsent[this.unsent.length - 1];
2331
+ if (last !== undefined && last.o === "delk" && last.s === s && last.nums !== undefined)
2332
+ last.nums.push(key);
2333
+ else
2334
+ this.unsent.push({ o: "delk", s, ks: [], nums: [key] });
2335
+ this.queued(req);
2336
+ }
2337
+ _issueDelete(s, key, req) {
2338
+ const last = this.unsent[this.unsent.length - 1];
2339
+ if (last !== undefined && last.o === "delk" && last.s === s && last.nums === undefined)
2340
+ last.ks.push(key);
2341
+ else
2342
+ this.unsent.push({ o: "delk", s, ks: [key] });
2343
+ this.queued(req);
2344
+ }
2345
+ queued(req) {
2346
+ this.unsentReqs.push(req);
2347
+ if (!this.flushQueued) {
2348
+ this.flushQueued = true;
2349
+ queueMicrotask(() => this.flush());
2350
+ }
2351
+ }
2352
+ local = new Set;
2353
+ _local(req, hit) {
2354
+ this.local.add(req);
2355
+ queueMicrotask(() => {
2356
+ this.local.delete(req);
2357
+ if (this._state === "finished")
2358
+ return;
2359
+ this._state = "active";
2360
+ this._settleSoon();
2361
+ this.deliver(req, hit, false);
2362
+ });
2363
+ }
2364
+ _internal(op) {
2365
+ this._issue(op, null);
2366
+ }
2367
+ _start() {
2368
+ this._started = true;
2369
+ this.flush();
2370
+ this.settle(false);
2371
+ }
2372
+ _settleSoon() {
2373
+ if (this.settleQueued)
2374
+ return;
2375
+ this.settleQueued = true;
2376
+ afterTask(() => {
2377
+ this.settleQueued = false;
2378
+ if (this._state === "active")
2379
+ this._state = "inactive";
2380
+ this.settle(false);
2381
+ });
2382
+ }
2383
+ message(ops, end) {
2384
+ const m = { t: "tx", tx: this.id, db: this.db.name, ops };
2385
+ if (!this.began) {
2386
+ this.began = true;
2387
+ m.begin = { mode: this.mode, stores: this._scope, version: this.version };
2388
+ }
2389
+ if (end)
2390
+ m.end = end;
2391
+ return m;
2392
+ }
2393
+ flush() {
2394
+ this.flushQueued = false;
2395
+ if (!this._started || this._state === "finished" || !this.unsent.length)
2396
+ return;
2397
+ const ops = this.unsent;
2398
+ this.unsent = [];
2399
+ const transfer = [];
2400
+ for (let i = 0;i < ops.length; i++) {
2401
+ const o = ops[i].o;
2402
+ if (o === "put" || o === "tput" || o === "del" || o === "delk" || o === "clear")
2403
+ (this.written ??= new Set).add(ops[i].s);
2404
+ if (o === "tput")
2405
+ ops[i] = wireTyped(ops[i], this.db._stores.get(ops[i].s), transfer);
2406
+ }
2407
+ if (this.head === this.inflight.length) {
2408
+ this.inflight = this.unsentReqs;
2409
+ this.head = 0;
2410
+ } else
2411
+ for (const r of this.unsentReqs)
2412
+ this.inflight.push(r);
2413
+ this.unsentReqs = [];
2414
+ runtime().post(this.message(ops), transfer);
2415
+ }
2416
+ settle(explicit) {
2417
+ if (this._state !== "inactive" || !this._started || this.commitSent)
2418
+ return;
2419
+ if (this.unsent.length)
2420
+ this.flush();
2421
+ if (this.local.size)
2422
+ return;
2423
+ if (this.head === this.inflight.length) {
2424
+ this.commitSent = true;
2425
+ this._state = "committing";
2426
+ if (this.mode === "readonly") {
2427
+ if (explicit)
2428
+ afterTask(() => this.complete());
2429
+ else
2430
+ this.complete();
2431
+ } else
2432
+ runtime().post(this.message([], "commit"));
2433
+ return;
2434
+ }
2435
+ if (this.mode === "readonly")
2436
+ return;
2437
+ if (explicit || this.quiet()) {
2438
+ this.commitSent = true;
2439
+ this._state = "committing";
2440
+ runtime().post(this.message([], explicit ? "commit" : "commitIfClean"));
2441
+ }
2442
+ }
2443
+ quiet() {
2444
+ for (let i = this.head;i < this.inflight.length; i++) {
2445
+ const r = this.inflight[i];
2446
+ if (r !== null && r.hasListeners())
2447
+ return false;
2448
+ }
2449
+ return true;
2450
+ }
2451
+ _onReply(r) {
2452
+ if (this._state === "finished")
2453
+ return;
2454
+ const errs = new Map;
2455
+ for (const [i, name, message] of r.errs)
2456
+ errs.set(i, [name, message]);
2457
+ if (r.res.length) {
2458
+ const prev = this._state;
2459
+ this._state = "active";
2460
+ this._settleSoon();
2461
+ const quietPath = !this.listensOnPath("success", false) && !this.db.listensOnPath("success", false);
2462
+ for (let i = 0;i < r.res.length; i++) {
2463
+ const req = this.inflight[this.head++];
2464
+ if (this._state === "finished")
2465
+ break;
2466
+ const e = errs.get(i);
2467
+ if (req === null || req === undefined) {
2468
+ if (e)
2469
+ this._abort(err(e[0], e[1]));
2470
+ continue;
2471
+ }
2472
+ if (e)
2473
+ this.deliverError(req, err(e[0], e[1]));
2474
+ else
2475
+ this.deliver(req, r.res[i], quietPath);
2476
+ }
2477
+ if (this._state === "active" && prev === "committing")
2478
+ this._state = "committing";
2479
+ }
2480
+ if (r.end) {
2481
+ if (this._state === "finished")
2482
+ return;
2483
+ if (r.end.ok)
2484
+ this.complete();
2485
+ else if (r.end.name === "Deferred") {
2486
+ this.commitSent = false;
2487
+ if (this._state === "committing")
2488
+ this._state = "inactive";
2489
+ this._settleSoon();
2490
+ } else
2491
+ this._abort(err(r.end.name, r.end.message));
2492
+ }
2493
+ }
2494
+ deliver(req, v, quietPath) {
2495
+ let result;
2496
+ switch (req.kind) {
2497
+ case "key":
2498
+ result = v === undefined ? req.known : decodeKey(v);
2499
+ break;
2500
+ case "keys":
2501
+ result = v.map(decodeKey);
2502
+ break;
2503
+ case "cursor":
2504
+ result = req.cursor._land(v);
2505
+ break;
2506
+ case "records":
2507
+ result = v.map((x) => ({ key: decodeKey(x.k), primaryKey: decodeKey(x.p), value: x.v }));
2508
+ break;
2509
+ case "query":
2510
+ req.plan = v.plan;
2511
+ result = v.value;
2512
+ break;
2513
+ default:
2514
+ result = v;
2515
+ }
2516
+ finishRequest(req, result, null);
2517
+ if (quietPath && !req.hasListeners())
2518
+ return;
2519
+ const out = dispatch(req, new PlateauEvent("success"));
2520
+ if (out.threw)
2521
+ this._abort(err("AbortError", "An exception was thrown in a success handler."));
2522
+ }
2523
+ deliverError(req, e) {
2524
+ if (req.cursor)
2525
+ req.cursor._land(null);
2526
+ finishRequest(req, undefined, e);
2527
+ const ev = new PlateauEvent("error", { bubbles: true, cancelable: true });
2528
+ const out = dispatch(req, ev);
2529
+ if (this._state === "finished")
2530
+ return;
2531
+ if (out.threw)
2532
+ this._abort(err("AbortError", "An exception was thrown in an error handler."));
2533
+ else if (!ev.defaultPrevented)
2534
+ this._abort(e);
2535
+ }
2536
+ complete() {
2537
+ if (this._state === "finished")
2538
+ return;
2539
+ this._state = "finished";
2540
+ runtime().finished(this.id);
2541
+ dispatch(this, new PlateauEvent("complete"));
2542
+ this.finish();
2543
+ if (this.written && this.mode === "readwrite") {
2544
+ const stores = [...this.written];
2545
+ runtime().changed(this.db.name, stores);
2546
+ changed(this.db.name, stores);
2547
+ }
2548
+ }
2549
+ finish() {
2550
+ this.db._txs.delete(this);
2551
+ scheduler(this.db.name).done(this);
2552
+ this.isFinished = true;
2553
+ this.markFinished?.();
2554
+ this.db._maybeClosed();
2555
+ }
2556
+ _abort(error) {
2557
+ if (this._state === "finished")
2558
+ return;
2559
+ this._state = "finished";
2560
+ this._aborted = true;
2561
+ this._error = error;
2562
+ if (this.beforeUpgrade) {
2563
+ this.db._stores = this.beforeUpgrade;
2564
+ this.db._nextId = this.nextIdBefore;
2565
+ }
2566
+ if (this.began && this.mode !== "readonly")
2567
+ runtime().post(this.message([], "abort"));
2568
+ runtime().finished(this.id);
2569
+ const reqs = [...this.inflight.slice(this.head), ...this.unsentReqs, ...this.local].filter((r) => r !== null);
2570
+ this.local.clear();
2571
+ this.inflight = [];
2572
+ this.head = 0;
2573
+ this.unsent = [];
2574
+ this.unsentReqs = [];
2575
+ afterTask(() => {
2576
+ for (const req of reqs) {
2577
+ if (req.cursor)
2578
+ req.cursor._land(null);
2579
+ finishRequest(req, undefined, err("AbortError", "The transaction was aborted."));
2580
+ dispatch(req, new PlateauEvent("error", { bubbles: true, cancelable: true }));
2581
+ }
2582
+ dispatch(this, new PlateauEvent("abort", { bubbles: true }));
2583
+ this.finish();
2584
+ });
2585
+ }
2586
+ }
2587
+ handlers(PlateauTransaction, ["abort", "complete", "error"]);
2588
+ function direction(d) {
2589
+ const s = d === undefined ? "next" : String(d);
2590
+ if (s !== "next" && s !== "nextunique" && s !== "prev" && s !== "prevunique")
2591
+ throw new TypeError(`The direction ${s} is not valid.`);
2592
+ return s;
2593
+ }
2594
+ function count2(n) {
2595
+ if (n === undefined)
2596
+ return 0;
2597
+ const x = Number(n);
2598
+ if (!Number.isFinite(x) || x < 0 || x > 4294967295)
2599
+ throw new TypeError("The count is not valid.");
2600
+ return Math.floor(x);
2601
+ }
2602
+ function pointKey(q) {
2603
+ if (q instanceof PlateauKeyRange || typeof IDBKeyRange !== "undefined" && q instanceof IDBKeyRange)
2604
+ return;
2605
+ return requireKey(q);
2606
+ }
2607
+
2608
+ class PlateauObjectStore {
2609
+ _tx;
2610
+ _def;
2611
+ indexHandles = new Map;
2612
+ keyPathValue;
2613
+ constructor(tx, def) {
2614
+ this._tx = tx;
2615
+ this._def = def;
2616
+ this.keyPathValue = Array.isArray(def.keyPath) ? [...def.keyPath] : def.keyPath;
2617
+ }
2618
+ get name() {
2619
+ return this._def.name;
2620
+ }
2621
+ get keyPath() {
2622
+ return this.keyPathValue;
2623
+ }
2624
+ get autoIncrement() {
2625
+ return this._def.autoIncrement;
2626
+ }
2627
+ get indexNames() {
2628
+ return stringList(this._def.indexes.map((i) => i.name));
2629
+ }
2630
+ get transaction() {
2631
+ return this._tx;
2632
+ }
2633
+ _live() {
2634
+ if (this._tx.db._stores.get(this._def.name) !== this._def)
2635
+ throw err("InvalidStateError", "The object store has been deleted.");
2636
+ }
2637
+ _ready(write) {
2638
+ this._live();
2639
+ this._tx._check(write);
2640
+ }
2641
+ put(value, key) {
2642
+ return this.store(value, key, false, arguments.length > 1);
2643
+ }
2644
+ add(value, key) {
2645
+ return this.store(value, key, true, arguments.length > 1);
2646
+ }
2647
+ store(value, key, add, keyGiven, source) {
2648
+ this._ready(true);
2649
+ const def = this._def;
2650
+ const inline = def.keyPath !== null;
2651
+ keyGiven = keyGiven && key !== undefined;
2652
+ if (inline && keyGiven)
2653
+ throw dataError("The object store uses in-line keys and the key parameter was provided.");
2654
+ if (!inline && !def.autoIncrement && !keyGiven)
2655
+ throw dataError("The object store uses out-of-line keys and has no key generator and the key parameter was not provided.");
2656
+ let k;
2657
+ if (keyGiven)
2658
+ k = requireKey(key);
2659
+ if (def.columns) {
2660
+ const [t, rest, pk] = splitTyped(def, value);
2661
+ if (pk === undefined && !def.autoIncrement)
2662
+ throw dataError("The record has no number at the key path.");
2663
+ const req = new PlateauRequest(source ?? this, this._tx, "key");
2664
+ if (pk !== undefined)
2665
+ req.known = pk;
2666
+ this._tx._issueTyped(def, t, rest, add, pk === undefined, req);
2667
+ return req;
2668
+ }
2669
+ const row = { v: "", add };
2670
+ {
2671
+ row.v = encodeValue(value);
2672
+ if (inline) {
2673
+ const r = extractKey(value, def.keyPath);
2674
+ if (r === "invalid")
2675
+ throw dataError("Evaluating the object store's key path yielded a value that is not a valid key.");
2676
+ if (r === "missing") {
2677
+ if (!def.autoIncrement)
2678
+ throw dataError("Evaluating the object store's key path did not yield a value.");
2679
+ if (!canInjectKey(value, def.keyPath))
2680
+ throw dataError("A generated key could not be inserted into the value.");
2681
+ } else
2682
+ k = r.key;
2683
+ }
2684
+ }
2685
+ if (k !== undefined)
2686
+ row.k = k;
2687
+ const req = new PlateauRequest(source ?? this, this._tx, "key");
2688
+ this._tx._issuePut(def.name, row, req);
2689
+ return req;
2690
+ }
2691
+ delete(query) {
2692
+ this._ready(true);
2693
+ if (this._def.columns && typeof query === "number" && !Number.isNaN(query)) {
2694
+ const req = new PlateauRequest(this, this._tx, "none");
2695
+ this._tx._issueDeleteNumber(this._def.name, query, req);
2696
+ return req;
2697
+ }
2698
+ const k = query === undefined || query === null ? undefined : pointKey(query);
2699
+ if (k !== undefined) {
2700
+ const req = new PlateauRequest(this, this._tx, "none");
2701
+ this._tx._issueDelete(this._def.name, k, req);
2702
+ return req;
2703
+ }
2704
+ const r = toRange(query, false);
2705
+ return this.request({ o: "del", s: this._def.name, r }, "none");
2706
+ }
2707
+ clear() {
2708
+ this._ready(true);
2709
+ return this.request({ o: "clear", s: this._def.name }, "none");
2710
+ }
2711
+ get(query) {
2712
+ this._ready(false);
2713
+ const k = pointKey(query === undefined || query === null ? requireRange(query) : query);
2714
+ if (k !== undefined) {
2715
+ const req = new PlateauRequest(this, this._tx, "value");
2716
+ this._tx._issueGet(this._def.name, k, req);
2717
+ return req;
2718
+ }
2719
+ return this.request({ o: "first", s: this._def.name, r: toRange(query, false), key: false }, "value");
2720
+ }
2721
+ getKey(query) {
2722
+ this._ready(false);
2723
+ return this.request({ o: "first", s: this._def.name, r: toRange(query, false), key: true }, "key");
2724
+ }
2725
+ getAll(query, n) {
2726
+ this._ready(false);
2727
+ return this.request({ o: "all", s: this._def.name, r: toRange(query, true), n: count2(n), key: false }, "values");
2728
+ }
2729
+ getAllKeys(query, n) {
2730
+ this._ready(false);
2731
+ return this.request({ o: "all", s: this._def.name, r: toRange(query, true), n: count2(n), key: true }, "keys");
2732
+ }
2733
+ count(query) {
2734
+ this._ready(false);
2735
+ return this.request({ o: "count", s: this._def.name, r: toRange(query, true) }, "count");
2736
+ }
2737
+ getAllRecords(o = {}) {
2738
+ this._ready(false);
2739
+ return this.request({ o: "recs", s: this._def.name, r: toRange(o?.query, true), n: count2(o?.count), d: direction(o?.direction) }, "records");
2740
+ }
2741
+ openCursor(query, dir) {
2742
+ return this.cursor(query, dir, true);
2743
+ }
2744
+ openKeyCursor(query, dir) {
2745
+ return this.cursor(query, dir, false);
2746
+ }
2747
+ query(q) {
2748
+ this._ready(false);
2749
+ return this.request({ o: "query", s: this._def.name, q: JSON.stringify(q) }, "query");
2750
+ }
2751
+ cursor(query, dir, values) {
2752
+ this._ready(false);
2753
+ const d = direction(dir);
2754
+ const r = toRange(query, true);
2755
+ const req = new PlateauRequest(this, this._tx, "cursor");
2756
+ req.cursor = values ? new PlateauCursorWithValue(req, this, this, undefined, r, d, true) : new PlateauCursor(req, this, this, undefined, r, d, false);
2757
+ req.cursor._step(undefined, 1);
2758
+ return req;
2759
+ }
2760
+ request(op, kind) {
2761
+ const req = new PlateauRequest(this, this._tx, kind);
2762
+ this._tx._issue(op, req);
2763
+ return req;
2764
+ }
2765
+ index(name) {
2766
+ if (this._tx._state === "finished")
2767
+ throw err("InvalidStateError", "The transaction has finished.");
2768
+ this._live();
2769
+ const n = String(name);
2770
+ const def = this._def.indexes.find((i) => i.name === n);
2771
+ if (!def)
2772
+ throw err("NotFoundError", `No index named ${n}.`);
2773
+ let h = this.indexHandles.get(n);
2774
+ if (!h || h._def !== def) {
2775
+ h = new PlateauIndex(this, def);
2776
+ this.indexHandles.set(n, h);
2777
+ }
2778
+ return h;
2779
+ }
2780
+ createIndex(name, keyPath, options = {}) {
2781
+ const tx = this._tx;
2782
+ if (tx.mode !== "versionchange")
2783
+ throw err("InvalidStateError", "Not in a version change transaction.");
2784
+ this._live();
2785
+ if (tx._state !== "active")
2786
+ throw err("TransactionInactiveError", "The version change transaction is not active.");
2787
+ const n = String(name);
2788
+ if (this._def.indexes.some((i) => i.name === n))
2789
+ throw err("ConstraintError", `An index named ${n} already exists.`);
2790
+ const kp = normalizeKeyPath(keyPath);
2791
+ if (!validKeyPath(kp))
2792
+ throw err("SyntaxError", "The keyPath is not a valid key path.");
2793
+ const multiEntry = !!options?.multiEntry;
2794
+ if (multiEntry && Array.isArray(kp))
2795
+ throw err("InvalidAccessError", "A multiEntry index cannot have an array key path.");
2796
+ const def = { id: tx.db._nextId++, name: n, keyPath: kp, unique: !!options?.unique, multiEntry };
2797
+ this._def.indexes.push(def);
2798
+ tx._internal({ o: "mkIndex", s: this._def.name, def: structuredClone(def) });
2799
+ return this.index(n);
2800
+ }
2801
+ deleteIndex(name) {
2802
+ const tx = this._tx;
2803
+ if (tx.mode !== "versionchange")
2804
+ throw err("InvalidStateError", "Not in a version change transaction.");
2805
+ this._live();
2806
+ if (tx._state !== "active")
2807
+ throw err("TransactionInactiveError", "The version change transaction is not active.");
2808
+ const n = String(name);
2809
+ const i = this._def.indexes.findIndex((x) => x.name === n);
2810
+ if (i < 0)
2811
+ throw err("NotFoundError", `No index named ${n}.`);
2812
+ this._def.indexes.splice(i, 1);
2813
+ tx._internal({ o: "rmIndex", s: this._def.name, i: n });
2814
+ }
2815
+ }
2816
+ function requireRange(q) {
2817
+ throw dataError("No key or key range specified.");
2818
+ }
2819
+ var layouts = new WeakMap;
2820
+ function layoutOf(def) {
2821
+ let l = layouts.get(def);
2822
+ if (!l) {
2823
+ const cols = def.columns;
2824
+ l = { names: cols.map((c) => c.name), kinds: cols.map((c) => c.kind), pkAt: cols.findIndex((c) => c.name === def.keyPath), declared: new Set(cols.map((c) => c.name)) };
2825
+ layouts.set(def, l);
2826
+ }
2827
+ return l;
2828
+ }
2829
+ function splitTyped(def, value) {
2830
+ const proto = value !== null && typeof value === "object" ? Object.getPrototypeOf(value) : undefined;
2831
+ if (proto !== Object.prototype && proto !== null)
2832
+ throw dataError("plateau: a store with columns takes plain objects.");
2833
+ const v = value;
2834
+ const { names, kinds, pkAt, declared } = layoutOf(def);
2835
+ const n = names.length;
2836
+ const t = new Array(n);
2837
+ let pk;
2838
+ for (let i = 0;i < n; i++) {
2839
+ const x = v[names[i]];
2840
+ if (i === pkAt && x === undefined && def.autoIncrement && !Object.prototype.hasOwnProperty.call(v, names[i])) {
2841
+ t[i] = 0;
2842
+ continue;
2843
+ }
2844
+ if (!fits(kinds[i], x) || !Object.prototype.hasOwnProperty.call(v, names[i])) {
2845
+ throw dataError(`plateau: field ${names[i]} must hold a ${kinds[i]} value (declared column).`);
2846
+ }
2847
+ t[i] = kinds[i] === "u32_multi" ? x.slice() : x;
2848
+ if (i === pkAt)
2849
+ pk = x;
2850
+ }
2851
+ const keys = Object.keys(v);
2852
+ let rest = "";
2853
+ if (keys.length !== n) {
2854
+ const r = {};
2855
+ for (const k of keys)
2856
+ if (!declared.has(k))
2857
+ r[k] = v[k];
2858
+ rest = encodeValue(r);
2859
+ }
2860
+ return [t, rest, pk];
2861
+ }
2862
+ function wireTyped(p, def, transfer) {
2863
+ const cols = def.columns.map((c, i) => {
2864
+ const b = p.cols[i];
2865
+ switch (c.kind) {
2866
+ case "f64": {
2867
+ const a = Float64Array.from(b);
2868
+ transfer.push(a.buffer);
2869
+ return a;
2870
+ }
2871
+ case "u32": {
2872
+ const a = Uint32Array.from(b);
2873
+ transfer.push(a.buffer);
2874
+ return a;
2875
+ }
2876
+ case "u32_multi": {
2877
+ const [o, v] = b;
2878
+ const pair = [Uint32Array.from(o), Uint32Array.from(v)];
2879
+ transfer.push(pair[0].buffer, pair[1].buffer);
2880
+ return pair;
2881
+ }
2882
+ default:
2883
+ return b;
2884
+ }
2885
+ });
2886
+ return { o: "tput", s: p.s, n: p.n, cols, v: p.v, add: p.add, gen: p.gen };
2887
+ }
2888
+ function fits(kind, x) {
2889
+ switch (kind) {
2890
+ case "f64":
2891
+ return typeof x === "number" && !Number.isNaN(x);
2892
+ case "u32":
2893
+ return typeof x === "number" && Number.isInteger(x) && x >= 0 && x <= 4294967295;
2894
+ case "str":
2895
+ return typeof x === "string";
2896
+ case "u32_multi": {
2897
+ if (!Array.isArray(x))
2898
+ return false;
2899
+ for (let i = 0;i < x.length; i++) {
2900
+ const y = x[i];
2901
+ if (typeof y !== "number" || !Number.isInteger(y) || y < 0 || y > 4294967295)
2902
+ return false;
2903
+ }
2904
+ return true;
2905
+ }
2906
+ }
2907
+ }
2908
+
2909
+ class PlateauIndex {
2910
+ objectStore;
2911
+ _def;
2912
+ keyPathValue;
2913
+ constructor(store, def) {
2914
+ this.objectStore = store;
2915
+ this._def = def;
2916
+ this.keyPathValue = Array.isArray(def.keyPath) ? [...def.keyPath] : def.keyPath;
2917
+ }
2918
+ get name() {
2919
+ return this._def.name;
2920
+ }
2921
+ get keyPath() {
2922
+ return this.keyPathValue;
2923
+ }
2924
+ get unique() {
2925
+ return this._def.unique;
2926
+ }
2927
+ get multiEntry() {
2928
+ return this._def.multiEntry;
2929
+ }
2930
+ _live() {
2931
+ this.objectStore._live();
2932
+ if (!this.objectStore._def.indexes.includes(this._def))
2933
+ throw err("InvalidStateError", "The index has been deleted.");
2934
+ }
2935
+ _ready() {
2936
+ this._live();
2937
+ this.objectStore._tx._check(false);
2938
+ }
2939
+ request(op, kind) {
2940
+ const req = new PlateauRequest(this, this.objectStore._tx, kind);
2941
+ this.objectStore._tx._issue(op, req);
2942
+ return req;
2943
+ }
2944
+ get s() {
2945
+ return this.objectStore._def.name;
2946
+ }
2947
+ get(query) {
2948
+ this._ready();
2949
+ return this.request({ o: "first", s: this.s, i: this._def.name, r: toRange(query, false), key: false }, "value");
2950
+ }
2951
+ getKey(query) {
2952
+ this._ready();
2953
+ return this.request({ o: "first", s: this.s, i: this._def.name, r: toRange(query, false), key: true }, "key");
2954
+ }
2955
+ getAll(query, n) {
2956
+ this._ready();
2957
+ return this.request({ o: "all", s: this.s, i: this._def.name, r: toRange(query, true), n: count2(n), key: false }, "values");
2958
+ }
2959
+ getAllKeys(query, n) {
2960
+ this._ready();
2961
+ return this.request({ o: "all", s: this.s, i: this._def.name, r: toRange(query, true), n: count2(n), key: true }, "keys");
2962
+ }
2963
+ count(query) {
2964
+ this._ready();
2965
+ return this.request({ o: "count", s: this.s, i: this._def.name, r: toRange(query, true) }, "count");
2966
+ }
2967
+ getAllRecords(o = {}) {
2968
+ this._ready();
2969
+ return this.request({ o: "recs", s: this.s, i: this._def.name, r: toRange(o?.query, true), n: count2(o?.count), d: direction(o?.direction) }, "records");
2970
+ }
2971
+ openCursor(query, dir) {
2972
+ return this.cursor(query, dir, true);
2973
+ }
2974
+ openKeyCursor(query, dir) {
2975
+ return this.cursor(query, dir, false);
2976
+ }
2977
+ cursor(query, dir, values) {
2978
+ this._ready();
2979
+ const d = direction(dir);
2980
+ const r = toRange(query, true);
2981
+ const req = new PlateauRequest(this, this.objectStore._tx, "cursor");
2982
+ req.cursor = values ? new PlateauCursorWithValue(req, this, this.objectStore, this._def.name, r, d, true) : new PlateauCursor(req, this, this.objectStore, this._def.name, r, d, false);
2983
+ req.cursor._step(undefined, 1);
2984
+ return req;
2985
+ }
2986
+ }
2987
+
2988
+ class PlateauCursor {
2989
+ request;
2990
+ source;
2991
+ direction;
2992
+ store;
2993
+ index;
2994
+ range;
2995
+ withValues;
2996
+ at;
2997
+ gotValue = false;
2998
+ keyValue;
2999
+ pkValue;
3000
+ _value;
3001
+ ahead = [];
3002
+ aheadEnd = false;
3003
+ constructor(req, source, store, index, range, dir, values) {
3004
+ this.request = req;
3005
+ this.source = source;
3006
+ this.store = store;
3007
+ this.index = index;
3008
+ this.range = range;
3009
+ this.direction = dir;
3010
+ this.withValues = values;
3011
+ }
3012
+ get key() {
3013
+ return this.keyValue;
3014
+ }
3015
+ get primaryKey() {
3016
+ return this.pkValue;
3017
+ }
3018
+ _step(to, n) {
3019
+ const tx = this.store._tx;
3020
+ const ahead = tx.mode === "readonly" && to === undefined && n === 1 && (this.direction === "next" || this.direction === "prev");
3021
+ if (ahead && (this.ahead.length || this.aheadEnd)) {
3022
+ this.request._done = false;
3023
+ tx._local(this.request, this.ahead.shift() ?? null);
3024
+ return;
3025
+ }
3026
+ this.ahead = [];
3027
+ this.aheadEnd = false;
3028
+ const op = { o: "cur", s: this.store._def.name, r: this.range, d: this.direction, n, v: this.withValues };
3029
+ if (tx.mode === "readonly" && (this.direction === "next" || this.direction === "prev"))
3030
+ op.pre = PREFETCH;
3031
+ if (this.index !== undefined)
3032
+ op.i = this.index;
3033
+ if (this.at)
3034
+ op.at = this.at;
3035
+ if (to)
3036
+ op.to = to;
3037
+ this.request._done = false;
3038
+ this.store._tx._issue(op, this.request);
3039
+ }
3040
+ _land(hit) {
3041
+ if (hit?.more !== undefined) {
3042
+ this.ahead = hit.more;
3043
+ this.aheadEnd = this.ahead.length < PREFETCH;
3044
+ delete hit.more;
3045
+ }
3046
+ if (!hit) {
3047
+ this.ahead = [];
3048
+ this.aheadEnd = false;
3049
+ this.at = undefined;
3050
+ this.keyValue = this.pkValue = this._value = undefined;
3051
+ return null;
3052
+ }
3053
+ this.at = [hit.k, hit.p];
3054
+ this.keyValue = decodeKey(hit.k);
3055
+ this.pkValue = hit.k === hit.p ? this.keyValue : decodeKey(hit.p);
3056
+ this._value = hit.v;
3057
+ this.gotValue = true;
3058
+ return this;
3059
+ }
3060
+ ready() {
3061
+ this.store._tx._check(false);
3062
+ if (this.source instanceof PlateauIndex)
3063
+ this.source._live();
3064
+ else
3065
+ this.store._live();
3066
+ if (!this.gotValue)
3067
+ throw err("InvalidStateError", "The cursor is being iterated or has iterated past its end.");
3068
+ }
3069
+ advance(count) {
3070
+ const n = Number(count);
3071
+ if (!Number.isFinite(n) || n < 1 || n > 4294967295)
3072
+ throw new TypeError("The count must be a positive integer.");
3073
+ this.ready();
3074
+ this.gotValue = false;
3075
+ this._step(undefined, Math.floor(n));
3076
+ }
3077
+ continue(key) {
3078
+ this.ready();
3079
+ let to;
3080
+ if (key !== undefined) {
3081
+ const k = requireKey(key);
3082
+ const cur = this.at[0];
3083
+ const forward = this.direction === "next" || this.direction === "nextunique";
3084
+ if (forward ? k <= cur : k >= cur)
3085
+ throw dataError("The key is not past the cursor's position in its direction.");
3086
+ to = [k];
3087
+ }
3088
+ this.gotValue = false;
3089
+ this._step(to, 1);
3090
+ }
3091
+ continuePrimaryKey(key, primaryKey) {
3092
+ this.store._tx._check(false);
3093
+ if (this.source instanceof PlateauIndex)
3094
+ this.source._live();
3095
+ else
3096
+ this.store._live();
3097
+ if (!(this.source instanceof PlateauIndex))
3098
+ throw err("InvalidAccessError", "continuePrimaryKey needs an index cursor.");
3099
+ if (this.direction !== "next" && this.direction !== "prev")
3100
+ throw err("InvalidAccessError", "continuePrimaryKey needs a next or prev cursor.");
3101
+ if (!this.gotValue)
3102
+ throw err("InvalidStateError", "The cursor is being iterated or has iterated past its end.");
3103
+ const k = requireKey(key);
3104
+ const p = requireKey(primaryKey);
3105
+ const [ck, cp] = this.at;
3106
+ const forward = this.direction === "next";
3107
+ const c = k < ck ? -1 : k > ck ? 1 : 0;
3108
+ if (forward ? c < 0 || c === 0 && p <= cp : c > 0 || c === 0 && p >= cp)
3109
+ throw dataError("The key is not past the cursor's position in its direction.");
3110
+ this.gotValue = false;
3111
+ this._step([k, p], 1);
3112
+ }
3113
+ update(value) {
3114
+ const tx = this.store._tx;
3115
+ tx._check(false);
3116
+ if (this.source instanceof PlateauIndex)
3117
+ this.source._live();
3118
+ else
3119
+ this.store._live();
3120
+ if (tx.mode === "readonly")
3121
+ throw err("ReadOnlyError", "The transaction is read-only.");
3122
+ if (!this.gotValue)
3123
+ throw err("InvalidStateError", "The cursor is being iterated or has iterated past its end.");
3124
+ if (!this.withValues)
3125
+ throw err("InvalidStateError", "A key cursor has no value.");
3126
+ const def = this.store._def;
3127
+ if (def.keyPath !== null) {
3128
+ encodeValue(value);
3129
+ const r = def.columns ? { key: encodeKey(value?.[def.keyPath]) } : extractKey(value, def.keyPath);
3130
+ if (typeof r !== "object" || r.key !== this.at[1])
3131
+ throw dataError("The value's key does not match the cursor's primary key.");
3132
+ return this.store.store(value, undefined, false, false, this);
3133
+ }
3134
+ return this.store.store(value, this.pkValue, false, true, this);
3135
+ }
3136
+ delete() {
3137
+ const tx = this.store._tx;
3138
+ tx._check(false);
3139
+ if (this.source instanceof PlateauIndex)
3140
+ this.source._live();
3141
+ else
3142
+ this.store._live();
3143
+ if (tx.mode === "readonly")
3144
+ throw err("ReadOnlyError", "The transaction is read-only.");
3145
+ if (!this.gotValue)
3146
+ throw err("InvalidStateError", "The cursor is being iterated or has iterated past its end.");
3147
+ if (!this.withValues)
3148
+ throw err("InvalidStateError", "A key cursor cannot delete.");
3149
+ const p = this.at[1];
3150
+ const req = new PlateauRequest(this, tx, "none");
3151
+ tx._issueDelete(this.store._def.name, p, req);
3152
+ return req;
3153
+ }
3154
+ }
3155
+
3156
+ class PlateauCursorWithValue extends PlateauCursor {
3157
+ }
3158
+ Object.defineProperty(PlateauCursorWithValue.prototype, "value", {
3159
+ get() {
3160
+ return this._value;
3161
+ },
3162
+ enumerable: true,
3163
+ configurable: true
3164
+ });
3165
+ var plateau = new PlateauFactory;
3166
+ export {
3167
+ PlateauCursor,
3168
+ PlateauCursorWithValue,
3169
+ PlateauDatabase,
3170
+ PlateauEvent,
3171
+ PlateauFactory,
3172
+ PlateauIndex,
3173
+ PlateauKeyRange,
3174
+ PlateauObjectStore,
3175
+ PlateauOpenDBRequest,
3176
+ PlateauRequest,
3177
+ PlateauTransaction,
3178
+ PlateauVersionChangeEvent,
3179
+ cmp,
3180
+ decodeKey,
3181
+ decodeValue,
3182
+ encodeKey,
3183
+ encodeValue,
3184
+ plateau,
3185
+ promise,
3186
+ runtime,
3187
+ startRuntime
3188
+ };