ahmed-rivet-convex 2.2.10 → 2.3.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -139,7 +139,7 @@ import {
139
139
  withWrite,
140
140
  withWriteNoImplicitCommit,
141
141
  wrapIterable
142
- } from "./chunk-FVFX5V7B.js";
142
+ } from "./chunk-STMINOLV.js";
143
143
 
144
144
  // ../zero-schema/src/builder/table-builder.ts
145
145
  function table(name) {
@@ -3354,9 +3354,388 @@ function dropIDBStore(name) {
3354
3354
  });
3355
3355
  }
3356
3356
 
3357
+ // ../replicache/src/kv/opfs-store.ts
3358
+ import { RWLock as RWLock3 } from "@rocicorp/lock";
3359
+ var COMPACT_MIN_BYTES = 2 * 1024 * 1024;
3360
+ var stores2 = /* @__PURE__ */ new Map();
3361
+ function isOPFSSupported() {
3362
+ return typeof Worker !== "undefined" && typeof Blob !== "undefined" && typeof URL !== "undefined" && typeof URL.createObjectURL === "function" && typeof navigator !== "undefined" && typeof navigator.storage?.getDirectory === "function";
3363
+ }
3364
+ function sanitizeFileName(name) {
3365
+ let h = 2166136261;
3366
+ for (let i = 0; i < name.length; i++) {
3367
+ h ^= name.charCodeAt(i);
3368
+ h = Math.imul(h, 16777619);
3369
+ }
3370
+ const safe = name.replace(/[^a-zA-Z0-9._-]/g, "_").slice(0, 96);
3371
+ return `${safe}_${(h >>> 0).toString(36)}.rplog`;
3372
+ }
3373
+ var OPFS_WORKER_SOURCE = `
3374
+ const enc = new TextEncoder();
3375
+ const dec = new TextDecoder();
3376
+ const OP_COMMIT = 1;
3377
+ const COMPACT_MIN_BYTES = ${COMPACT_MIN_BYTES};
3378
+
3379
+ async function withLock(lockName, fn) {
3380
+ if (typeof navigator !== 'undefined' && navigator.locks && typeof navigator.locks.request === 'function') {
3381
+ return navigator.locks.request(lockName, fn);
3382
+ }
3383
+ return fn();
3384
+ }
3385
+
3386
+ function replayFrames(buf, size, map) {
3387
+ const view = new DataView(buf.buffer, buf.byteOffset, size);
3388
+ let pos = 0;
3389
+ let frameCount = 0;
3390
+ while (pos + 5 <= size) {
3391
+ const len = view.getUint32(pos, true);
3392
+ const op = buf[pos + 4];
3393
+ if (pos + 5 + len > size) break;
3394
+ if (op === OP_COMMIT) {
3395
+ const parsed = JSON.parse(dec.decode(buf.subarray(pos + 5, pos + 5 + len)));
3396
+ if (parsed.p) {
3397
+ for (let i = 0; i < parsed.p.length; i++) {
3398
+ const pair = parsed.p[i];
3399
+ map.set(pair[0], pair[1]);
3400
+ }
3401
+ }
3402
+ if (parsed.d) {
3403
+ for (let i = 0; i < parsed.d.length; i++) {
3404
+ map.delete(parsed.d[i]);
3405
+ }
3406
+ }
3407
+ }
3408
+ pos += 5 + len;
3409
+ frameCount++;
3410
+ }
3411
+ return { pos, frameCount };
3412
+ }
3413
+
3414
+ function encodeCommitFrame(puts, dels) {
3415
+ const payload = enc.encode(JSON.stringify({ p: puts, d: dels }));
3416
+ const frame = new Uint8Array(5 + payload.byteLength);
3417
+ new DataView(frame.buffer).setUint32(0, payload.byteLength, true);
3418
+ frame[4] = OP_COMMIT;
3419
+ frame.set(payload, 5);
3420
+ return frame;
3421
+ }
3422
+
3423
+ self.onmessage = async (event) => {
3424
+ const msg = event.data;
3425
+ try {
3426
+ if (msg.op === 'load') {
3427
+ const result = await withLock('pb-opfs:' + msg.fileName, async () => {
3428
+ const root = await navigator.storage.getDirectory();
3429
+ const fh = await root.getFileHandle(msg.fileName, { create: true });
3430
+ if (typeof fh.createSyncAccessHandle !== 'function') {
3431
+ return { supported: false, entries: [] };
3432
+ }
3433
+ const handle = await fh.createSyncAccessHandle();
3434
+ try {
3435
+ const size = handle.getSize();
3436
+ if (size === 0) return { supported: true, entries: [], bytes: 0 };
3437
+ const buf = new Uint8Array(size);
3438
+ handle.read(buf, { at: 0 });
3439
+ const map = new Map();
3440
+ const { frameCount } = replayFrames(buf, size, map);
3441
+ // Compact on load if WAL has accumulated many frames and > 2 MB.
3442
+ if (size > COMPACT_MIN_BYTES && frameCount > 64) {
3443
+ const snapshotFrame = encodeCommitFrame(Array.from(map.entries()), []);
3444
+ handle.truncate(0);
3445
+ handle.write(snapshotFrame, { at: 0 });
3446
+ handle.flush();
3447
+ }
3448
+ return { supported: true, entries: Array.from(map.entries()), bytes: size };
3449
+ } finally {
3450
+ handle.close();
3451
+ }
3452
+ });
3453
+ self.postMessage({ id: msg.id, ok: true, result });
3454
+ return;
3455
+ }
3456
+
3457
+ if (msg.op === 'commit') {
3458
+ const result = await withLock('pb-opfs:' + msg.fileName, async () => {
3459
+ const root = await navigator.storage.getDirectory();
3460
+ const fh = await root.getFileHandle(msg.fileName, { create: true });
3461
+ if (typeof fh.createSyncAccessHandle !== 'function') {
3462
+ return { supported: false };
3463
+ }
3464
+ const handle = await fh.createSyncAccessHandle();
3465
+ try {
3466
+ const size = handle.getSize();
3467
+ const frame = encodeCommitFrame(msg.puts, msg.dels);
3468
+ handle.write(frame, { at: size });
3469
+ handle.flush();
3470
+ return { supported: true, bytes: size + frame.byteLength };
3471
+ } finally {
3472
+ handle.close();
3473
+ }
3474
+ });
3475
+ self.postMessage({ id: msg.id, ok: true, result });
3476
+ return;
3477
+ }
3478
+
3479
+ if (msg.op === 'drop') {
3480
+ await withLock('pb-opfs:' + msg.fileName, async () => {
3481
+ const root = await navigator.storage.getDirectory();
3482
+ try {
3483
+ await root.removeEntry(msg.fileName);
3484
+ } catch {
3485
+ /* already removed */
3486
+ }
3487
+ });
3488
+ self.postMessage({ id: msg.id, ok: true, result: true });
3489
+ return;
3490
+ }
3491
+
3492
+ self.postMessage({ id: msg.id, ok: false, error: 'unknown op' });
3493
+ } catch (err) {
3494
+ self.postMessage({
3495
+ id: msg.id,
3496
+ ok: false,
3497
+ error: err && err.message ? String(err.message) : String(err),
3498
+ });
3499
+ }
3500
+ };
3501
+ `;
3502
+ var OPFSWorkerClient = class {
3503
+ #worker = null;
3504
+ #blobUrl = null;
3505
+ #nextId = 1;
3506
+ #pending = /* @__PURE__ */ new Map();
3507
+ #ensureWorker() {
3508
+ if (this.#worker) return this.#worker;
3509
+ const blob = new Blob([OPFS_WORKER_SOURCE], {
3510
+ type: "application/javascript"
3511
+ });
3512
+ this.#blobUrl = URL.createObjectURL(blob);
3513
+ const worker = new Worker(this.#blobUrl);
3514
+ worker.onmessage = (event) => {
3515
+ const msg = event.data;
3516
+ const entry = this.#pending.get(msg.id);
3517
+ if (!entry) return;
3518
+ this.#pending.delete(msg.id);
3519
+ if (msg.ok) entry.resolve(msg.result);
3520
+ else entry.reject(new Error(msg.error ?? "OPFS worker error"));
3521
+ };
3522
+ worker.onerror = (event) => {
3523
+ const err2 = new Error(event.message || "OPFS worker error");
3524
+ for (const entry of this.#pending.values()) entry.reject(err2);
3525
+ this.#pending.clear();
3526
+ };
3527
+ this.#worker = worker;
3528
+ return worker;
3529
+ }
3530
+ call(payload) {
3531
+ const worker = this.#ensureWorker();
3532
+ const id = this.#nextId++;
3533
+ return new Promise((resolve, reject) => {
3534
+ this.#pending.set(id, {
3535
+ resolve,
3536
+ reject
3537
+ });
3538
+ worker.postMessage({ ...payload, id });
3539
+ });
3540
+ }
3541
+ terminate() {
3542
+ if (this.#worker) {
3543
+ this.#worker.terminate();
3544
+ this.#worker = null;
3545
+ }
3546
+ if (this.#blobUrl) {
3547
+ URL.revokeObjectURL(this.#blobUrl);
3548
+ this.#blobUrl = null;
3549
+ }
3550
+ }
3551
+ };
3552
+ var sharedWorkerClient = null;
3553
+ function getSharedWorkerClient() {
3554
+ if (!sharedWorkerClient) sharedWorkerClient = new OPFSWorkerClient();
3555
+ return sharedWorkerClient;
3556
+ }
3557
+ var OPFSReadImpl = class extends ReadImpl3 {
3558
+ #mapRef;
3559
+ constructor(map, release) {
3560
+ super(map, release);
3561
+ this.#mapRef = map;
3562
+ }
3563
+ getAll() {
3564
+ const closed = maybeTransactionIsClosedRejection(this);
3565
+ if (closed) return closed;
3566
+ return Promise.resolve(new Map(this.#mapRef));
3567
+ }
3568
+ };
3569
+ var OPFSWriteImpl = class extends WriteImplBase {
3570
+ #map;
3571
+ #fileName;
3572
+ #worker;
3573
+ constructor(map, release, fileName, worker) {
3574
+ super(new OPFSReadImpl(map, release));
3575
+ this.#map = map;
3576
+ this.#fileName = fileName;
3577
+ this.#worker = worker;
3578
+ }
3579
+ async commit() {
3580
+ if (this.closed) {
3581
+ return transactionIsClosedRejection();
3582
+ }
3583
+ const puts = [];
3584
+ const dels = [];
3585
+ this._pending.forEach((value, key) => {
3586
+ if (value === deleteSentinel) {
3587
+ this.#map.delete(key);
3588
+ dels.push(key);
3589
+ } else {
3590
+ this.#map.set(key, value);
3591
+ puts.push([key, value]);
3592
+ }
3593
+ });
3594
+ this._pending.clear();
3595
+ try {
3596
+ if (puts.length > 0 || dels.length > 0) {
3597
+ await this.#worker.call({
3598
+ op: "commit",
3599
+ fileName: this.#fileName,
3600
+ puts,
3601
+ dels
3602
+ });
3603
+ }
3604
+ } finally {
3605
+ this.release();
3606
+ }
3607
+ }
3608
+ };
3609
+ var OPFSStore = class {
3610
+ #name;
3611
+ #fileName;
3612
+ #lc;
3613
+ #entry;
3614
+ #closed = false;
3615
+ constructor(lc, name) {
3616
+ this.#lc = lc;
3617
+ this.#name = name;
3618
+ this.#fileName = sanitizeFileName(name);
3619
+ let entry = stores2.get(name);
3620
+ if (!entry) {
3621
+ entry = {
3622
+ lock: new RWLock3(),
3623
+ map: /* @__PURE__ */ new Map(),
3624
+ worker: getSharedWorkerClient(),
3625
+ hydrated: false,
3626
+ hydrating: null,
3627
+ opfsAvailable: isOPFSSupported(),
3628
+ fallbackStore: null
3629
+ };
3630
+ stores2.set(name, entry);
3631
+ }
3632
+ this.#entry = entry;
3633
+ }
3634
+ async #ensureHydrated() {
3635
+ if (!this.#entry.opfsAvailable) return false;
3636
+ if (this.#entry.hydrated) return true;
3637
+ if (this.#entry.hydrating) return this.#entry.hydrating;
3638
+ this.#entry.hydrating = (async () => {
3639
+ const release = await this.#entry.lock.write();
3640
+ try {
3641
+ if (this.#entry.hydrated) return true;
3642
+ const res = await this.#entry.worker.call({
3643
+ op: "load",
3644
+ fileName: this.#fileName
3645
+ });
3646
+ if (!res.supported) {
3647
+ this.#entry.opfsAvailable = false;
3648
+ return false;
3649
+ }
3650
+ if (res.entries) {
3651
+ for (let i = 0; i < res.entries.length; i++) {
3652
+ const pair = res.entries[i];
3653
+ this.#entry.map.set(pair[0], pair[1]);
3654
+ }
3655
+ }
3656
+ this.#entry.hydrated = true;
3657
+ return true;
3658
+ } catch (err2) {
3659
+ this.#lc.debug?.("OPFSStore falling back to IDB:", err2);
3660
+ this.#entry.opfsAvailable = false;
3661
+ return false;
3662
+ } finally {
3663
+ release();
3664
+ this.#entry.hydrating = null;
3665
+ }
3666
+ })();
3667
+ return this.#entry.hydrating;
3668
+ }
3669
+ #getFallback() {
3670
+ if (!this.#entry.fallbackStore) {
3671
+ this.#entry.fallbackStore = newIDBStoreWithMemFallback(
3672
+ this.#lc,
3673
+ this.#name
3674
+ );
3675
+ }
3676
+ return this.#entry.fallbackStore;
3677
+ }
3678
+ async read() {
3679
+ throwIfStoreClosed(this);
3680
+ const ok = await this.#ensureHydrated();
3681
+ if (!ok) return this.#getFallback().read();
3682
+ const release = await this.#entry.lock.read();
3683
+ return new OPFSReadImpl(this.#entry.map, release);
3684
+ }
3685
+ async write() {
3686
+ throwIfStoreClosed(this);
3687
+ const ok = await this.#ensureHydrated();
3688
+ if (!ok) return this.#getFallback().write();
3689
+ const release = await this.#entry.lock.write();
3690
+ return new OPFSWriteImpl(
3691
+ this.#entry.map,
3692
+ release,
3693
+ this.#fileName,
3694
+ this.#entry.worker
3695
+ );
3696
+ }
3697
+ async close() {
3698
+ this.#closed = true;
3699
+ if (this.#entry.fallbackStore) {
3700
+ await this.#entry.fallbackStore.close();
3701
+ }
3702
+ return promiseVoid;
3703
+ }
3704
+ get closed() {
3705
+ return this.#closed;
3706
+ }
3707
+ };
3708
+ async function dropOPFSStore(name) {
3709
+ const entry = stores2.get(name);
3710
+ stores2.delete(name);
3711
+ if (isOPFSSupported()) {
3712
+ try {
3713
+ await getSharedWorkerClient().call({
3714
+ op: "drop",
3715
+ fileName: sanitizeFileName(name)
3716
+ });
3717
+ } catch {
3718
+ }
3719
+ }
3720
+ if (entry?.fallbackStore) {
3721
+ await dropIDBStoreWithMemFallback(name);
3722
+ }
3723
+ }
3724
+
3357
3725
  // ../replicache/src/get-kv-store-provider.ts
3358
3726
  function getKVStoreProvider(lc, kvStore) {
3359
3727
  switch (kvStore) {
3728
+ case "opfs":
3729
+ if (isOPFSSupported()) {
3730
+ return {
3731
+ create: (name) => new OPFSStore(lc, name),
3732
+ drop: dropOPFSStore
3733
+ };
3734
+ }
3735
+ return {
3736
+ create: (name) => newIDBStoreWithMemFallback(lc, name),
3737
+ drop: dropIDBStoreWithMemFallback
3738
+ };
3360
3739
  case "idb":
3361
3740
  case void 0:
3362
3741
  return {
@@ -15654,7 +16033,7 @@ function makeMessage(message, context, logLevel) {
15654
16033
  }
15655
16034
 
15656
16035
  // ../zero-client/src/client/version.ts
15657
- var version2 = "2.2.10";
16036
+ var version2 = "2.3.1";
15658
16037
 
15659
16038
  // ../zero-client/src/client/log-options.ts
15660
16039
  var LevelFilterLogSink = class {
@@ -17334,9 +17713,11 @@ var Zero = class _Zero {
17334
17713
  // Reenable analytics
17335
17714
  );
17336
17715
  let { kvStore = "idb" } = options;
17337
- if (kvStore === "idb") {
17338
- if (!getBrowserGlobal("indexedDB")) {
17716
+ if (kvStore === "idb" || kvStore === "opfs") {
17717
+ if (!getBrowserGlobal("indexedDB") && kvStore === "idb") {
17339
17718
  kvStore = "mem";
17719
+ } else if (kvStore === "opfs" && (!getBrowserGlobal("Worker") || !getBrowserGlobal("navigator"))) {
17720
+ kvStore = getBrowserGlobal("indexedDB") ? "idb" : "mem";
17340
17721
  }
17341
17722
  }
17342
17723
  if (hiddenTabDisconnectDelay < 0) {
@@ -7808,6 +7808,11 @@ function applyChange(parentEntry, change, schema, relationship, format, withIDs
7808
7808
  }
7809
7809
  }
7810
7810
  function applyEdit(existing, change, schema, withIDs) {
7811
+ for (const key in change.oldNode.row) {
7812
+ if (!(key in change.node.row)) {
7813
+ delete existing[key];
7814
+ }
7815
+ }
7811
7816
  Object.assign(existing, change.node.row);
7812
7817
  if (withIDs) {
7813
7818
  existing[idSymbol] = makeID(change.node.row, schema);
@@ -22,7 +22,7 @@ import {
22
22
  unreachable,
23
23
  valita_exports,
24
24
  withRead
25
- } from "./chunk-FVFX5V7B.js";
25
+ } from "./chunk-STMINOLV.js";
26
26
 
27
27
  // ../zero-client/src/client/inspector/html-dialog-prompt.ts
28
28
  function canUseHTMLDialog() {
package/dist/react.js CHANGED
@@ -1,9 +1,9 @@
1
1
  import {
2
2
  Zero
3
- } from "./chunk-EUAHV7B3.js";
3
+ } from "./chunk-6XD2JH5S.js";
4
4
  import {
5
5
  DEFAULT_TTL_MS
6
- } from "./chunk-FVFX5V7B.js";
6
+ } from "./chunk-STMINOLV.js";
7
7
 
8
8
  // ../zero-react/src/use-query.tsx
9
9
  import React, { useSyncExternalStore } from "react";
@@ -1,4 +1,4 @@
1
1
  import type { LogContext } from '@rocicorp/logger';
2
2
  import type { StoreProvider } from './kv/store.ts';
3
- export declare function getKVStoreProvider(lc: LogContext, kvStore: 'mem' | 'idb' | StoreProvider | undefined): StoreProvider;
3
+ export declare function getKVStoreProvider(lc: LogContext, kvStore: 'mem' | 'idb' | 'opfs' | StoreProvider | undefined): StoreProvider;
4
4
  //# sourceMappingURL=get-kv-store-provider.d.ts.map
@@ -0,0 +1,21 @@
1
+ import type { LogContext } from '@rocicorp/logger';
2
+ import type { Read, Store, Write } from './store.ts';
3
+ export declare function isOPFSSupported(): boolean;
4
+ /**
5
+ * OPFS-backed transactional KV store for Replicache/Zero.
6
+ *
7
+ * Keeps an in-memory map synchronized with a Dedicated Worker writing
8
+ * binary WAL frames to OPFS via `FileSystemSyncAccessHandle` + Web Locks.
9
+ * Falls back transparently to `IDBStoreWithMemFallback` if OPFS is
10
+ * unavailable (SSR, Node, Safari Private Browsing).
11
+ */
12
+ export declare class OPFSStore implements Store {
13
+ #private;
14
+ constructor(lc: LogContext, name: string);
15
+ read(): Promise<Read>;
16
+ write(): Promise<Write>;
17
+ close(): Promise<void>;
18
+ get closed(): boolean;
19
+ }
20
+ export declare function dropOPFSStore(name: string): Promise<void>;
21
+ //# sourceMappingURL=opfs-store.d.ts.map
@@ -25,7 +25,7 @@ export type DropDatabaseOptions = {
25
25
  * Allows providing a custom implementation of the underlying storage layer.
26
26
  * Default is `'idb'`.
27
27
  */
28
- kvStore?: 'idb' | 'mem' | StoreProvider | undefined;
28
+ kvStore?: 'idb' | 'mem' | 'opfs' | StoreProvider | undefined;
29
29
  /**
30
30
  * Determines how much logging to do. When this is set to `'debug'`,
31
31
  * Replicache will also log `'info'` and `'error'` messages. When set to
@@ -191,7 +191,7 @@ export interface ReplicacheOptions<MD extends MutatorDefs> {
191
191
  /**
192
192
  * Allows providing a custom implementation of the underlying storage layer.
193
193
  */
194
- kvStore?: 'mem' | 'idb' | StoreProvider | undefined;
194
+ kvStore?: 'mem' | 'idb' | 'opfs' | StoreProvider | undefined;
195
195
  /**
196
196
  * Defines the indexes, if any, to use on the data.
197
197
  */
@@ -179,7 +179,7 @@ export interface ZeroOptions<S extends Schema, MD extends CustomMutatorDefs | un
179
179
  * You can also set this to a function that is used to create new KV stores,
180
180
  * allowing a custom implementation of the underlying storage layer.
181
181
  */
182
- kvStore?: 'mem' | 'idb' | StoreProvider | undefined;
182
+ kvStore?: 'mem' | 'idb' | 'opfs' | StoreProvider | undefined;
183
183
  /**
184
184
  * The maximum number of bytes to allow in a single header.
185
185
  *
package/dist/zero.js CHANGED
@@ -6,8 +6,8 @@ import {
6
6
  number,
7
7
  string,
8
8
  table
9
- } from "./chunk-EUAHV7B3.js";
10
- import "./chunk-FVFX5V7B.js";
9
+ } from "./chunk-6XD2JH5S.js";
10
+ import "./chunk-STMINOLV.js";
11
11
 
12
12
  // src/adapters/convex.ts
13
13
  var ConvexSyncAdapter = class {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "ahmed-rivet-convex",
3
- "version": "2.2.10",
3
+ "version": "2.3.1",
4
4
  "description": "Client-only local-first data runtime for the browser: reactive queries over IndexedDB with optimistic writes.",
5
5
  "author": "Ahmed Banihani",
6
6
  "license": "Apache-2.0",