@ping-app/ping-openmls-sdk 0.10.2 → 0.10.4

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.
@@ -85,9 +85,7 @@ async function openNotificationPreview(opts) {
85
85
  opts.wasmModuleOrPath === void 0 ? void 0 : { module_or_path: opts.wasmModuleOrPath }
86
86
  );
87
87
  reserveLinearMemory(out.memory);
88
- const client = await wasm.PingClient.openReadOnly(
89
- opts.identityExport,
90
- // Label is unused on the read-only path (no LocalDevice is ever minted).
88
+ const client = await wasm.PingClient.openReadOnlyFromDeviceRecord(
91
89
  "notification-preview",
92
90
  storage,
93
91
  silentTransport(),
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/notification-preview.ts","../src/storage/scope.ts","../src/wasm-memory.ts"],"sourcesContent":["// [CR-5] Read-only notification preview for the web Service Worker.\n//\n// The web mirror of the iOS Notification Service Extension: a second JS realm\n// (the push-handling Service Worker, woken while the tab may be closed OR open\n// and writing) that must turn one push-delivered envelope into a sender and a\n// body preview, and change NOTHING.\n//\n// This module deliberately does NOT go through the SDK's usual Worker bridge:\n// a Service Worker cannot spawn a dedicated `Worker` on every browser, and a\n// preview needs one decrypt, not a message pipeline. The WASM module is loaded\n// INLINE in the calling realm (no DOM APIs are touched), wrapping the core's\n// `MessagingClient::open_read_only` + `preview_envelope` — the same read-only\n// seam the iOS NSE uses, with the same semantics:\n//\n// * the SDK storage is opened READ-ONLY: the MLS snapshot is copied into\n// memory at open and never written back, so the tab remains the single\n// writer and cannot be disturbed (two writers on the whole-state blob\n// REPLACE each other — see `StorageBackend::AsyncBlobReadOnly`);\n// * the ratchet advance from the preview decrypt is thrown away; the tab\n// decrypts the same message again later, independently. Nothing is\n// consumed that the tab needs, and nothing this session does is\n// observable by the tab;\n// * handshake traffic (Commit/Welcome/Proposal), unknown conversations, and\n// replays the hydrated cursor rejects all resolve to `null` — show the\n// generic banner, it is a normal answer;\n// * a message the tab ALREADY consumed and checkpointed cannot be decrypted\n// from the newer snapshot (its generation is burned): `previewEnvelope`\n// rejects. Treat ANY rejection as \"no preview\" (generic banner), never as\n// fatal.\n//\n// Concurrent-open safety: IndexedDB reads never block the tab's writes and the\n// session takes a point-in-time copy of the `__mls snapshot` blob at open, so\n// opening while a tab is live is safe by construction. The copy can be STALE\n// relative to the tab, which only widens the `null`/reject cases above. Open a\n// fresh session per push event (or per small batch) rather than caching one —\n// a fresh open sees the newest checkpoint.\n//\n// See docs/NOTIFICATION_PREVIEW_WEB.md for the full Service Worker guide\n// (wasm init in module vs classic workers, account-slot storage, ping-prime\n// wiring).\n\nimport { scopeStorage } from \"./storage/scope\";\nimport type { IncomingMessage, MessageEnvelope, Storage } from \"./types\";\nimport { reserveLinearMemory } from \"./wasm-memory\";\n\nexport interface NotificationPreviewOptions {\n /**\n * The account identity export (CBOR-wrapped Ed25519 seed, SECRET) — the\n * same bytes the tab passes to `MessagingClient.init`. The Service Worker\n * host must read it from wherever the tab keeps it (e.g. the encrypted IDB\n * slot); it never crosses the network.\n */\n identityExport: Uint8Array;\n /**\n * The SAME `Storage` implementation (and underlying IndexedDB database)\n * the tab's `MessagingClient` persists to. It is wrapped read-only here:\n * `put`/`del` reject, so a host bug cannot make the Service Worker a\n * second writer.\n */\n storage: Storage;\n /**\n * The tab's `ClientConfig.accountNamespace` for this account slot, when it\n * uses one. MUST match exactly — the preview scopes every namespace with\n * the same `\"${accountNamespace} \"` prefix rule as `MessagingClient`, and a\n * mismatch reads an empty store (open rejects with \"no checkpoint\").\n */\n accountNamespace?: string;\n /**\n * Where to load `ping_wasm_bg.wasm` from, passed through to the\n * wasm-bindgen `init`. Defaults to the URL baked next to the module —\n * correct when the bundler ships the `wasm/` directory alongside. Classic\n * (importScripts) Service Workers, or bundlers that relocate assets, pass\n * an explicit URL here.\n */\n wasmModuleOrPath?: string | URL | WebAssembly.Module;\n /** Override the wall clock (test/sim only). */\n now?: () => number;\n}\n\n/**\n * The most prerequisite envelopes `previewEnvelopeWithPrerequisites` accepts.\n * The envelopes come from the server before anything authenticates them, so\n * the work they can cause is bounded. Mirrors the core's\n * `PREVIEW_PREREQUISITES_MAX`.\n */\nexport const MAX_PREVIEW_PREREQUISITES = 64;\n\nexport interface NotificationPreviewSession {\n /**\n * Decrypt ONE push-delivered envelope for display. Resolves to the\n * decrypted message (sender ids, conversation id, plaintext — everything a\n * banner needs) or `null` when there is nothing to show. Rejects when the\n * snapshot cannot decrypt it (commonly: the tab consumed it first) — treat\n * a rejection exactly like `null` and fall back to the generic banner.\n *\n * The returned message never carries a `journal_id`: a preview decrypt is\n * not journaled (nothing durable happened) and needs no `confirmApplied`.\n */\n previewEnvelope(envelope: MessageEnvelope): Promise<IncomingMessage | null>;\n /**\n * Decrypt ONE push-delivered envelope that this device cannot read yet,\n * because the handshake traffic in front of it has not been processed: the\n * first message of a conversation whose Welcome is still pending, or a\n * message sent after a Commit the tab has not applied.\n *\n * `prerequisites` are the envelopes that precede `envelope`, oldest first:\n * the pending Welcome (if any) and the Commits and Proposals after it.\n * They are applied to this session's private in-memory copy and then\n * `envelope` is decrypted. Nothing is persisted, the one-time KeyPackage\n * the Welcome was sealed to stays in the store, and the tab later joins and\n * decrypts for itself as if this call never happened.\n *\n * Envelopes for other conversations are ignored, a Welcome is not applied\n * to a conversation the snapshot already holds and can read, and a\n * prerequisite that does not apply is skipped. At most\n * {@link MAX_PREVIEW_PREREQUISITES} prerequisites; more rejects.\n *\n * Same result contract as `previewEnvelope`: `null` when there is nothing\n * to show, a rejection when the message cannot be decrypted. Treat both as\n * \"no preview\" and fall back to the generic banner.\n *\n * The applied prerequisites stay in the session's memory, so open a fresh\n * session per push event (the module comment already says to).\n */\n previewEnvelopeWithPrerequisites(\n prerequisites: MessageEnvelope[],\n envelope: MessageEnvelope,\n ): Promise<IncomingMessage | null>;\n /** Release the WASM instance. The session is unusable afterwards. */\n close(): void;\n}\n\n/**\n * Open the SDK read-only for notification previews, from a Service Worker (or\n * any realm without the SDK's Worker bridge). Rejects when the store holds no\n * checkpoint or no device identity — a Service Worker for an account that\n * never initialised locally has nothing to decrypt with, and \"successfully\n * decrypt nothing\" would be the worst possible answer.\n */\nexport async function openNotificationPreview(\n opts: NotificationPreviewOptions,\n): Promise<NotificationPreviewSession> {\n const now = opts.now ?? (() => Date.now());\n const scoped =\n opts.accountNamespace !== undefined && opts.accountNamespace.length > 0\n ? scopeStorage(opts.storage, opts.accountNamespace)\n : opts.storage;\n const storage = readOnlyStorage(scoped);\n\n // Inline WASM load — the module ships no DOM dependency, so this works in\n // window, worker, and service-worker realms alike. `init` is idempotent per\n // realm (subsequent opens reuse the instantiated module).\n const wasm = await import(\"../wasm/ping_wasm\");\n const out = await wasm.default(\n opts.wasmModuleOrPath === undefined\n ? undefined\n : ({ module_or_path: opts.wasmModuleOrPath } as never),\n );\n // Same Safari mitigation as the worker (`wasm-memory.ts`): grow from JS\n // once so the module never executes `memory.grow` itself. Idempotent.\n reserveLinearMemory(out.memory);\n\n const client = await wasm.PingClient.openReadOnly(\n opts.identityExport,\n // Label is unused on the read-only path (no LocalDevice is ever minted).\n \"notification-preview\",\n storage as never,\n silentTransport() as never,\n now(),\n );\n\n let closed = false;\n return {\n async previewEnvelope(envelope: MessageEnvelope): Promise<IncomingMessage | null> {\n if (closed) throw new Error(\"notification-preview session is closed\");\n const result = client.previewEnvelope(envelope as never, now());\n return (result ?? null) as IncomingMessage | null;\n },\n async previewEnvelopeWithPrerequisites(\n prerequisites: MessageEnvelope[],\n envelope: MessageEnvelope,\n ): Promise<IncomingMessage | null> {\n if (closed) throw new Error(\"notification-preview session is closed\");\n assertPrerequisiteCount(prerequisites);\n const result = client.previewEnvelopeWithPrerequisites(\n prerequisites as never,\n envelope as never,\n now(),\n );\n return (result ?? null) as IncomingMessage | null;\n },\n close() {\n if (closed) return;\n closed = true;\n client.free();\n },\n };\n}\n\n/**\n * Refuse an oversized prerequisite list before it crosses into WASM. The core\n * enforces the same bound; checking here keeps the copy out of linear memory.\n * Exported for tests.\n */\nexport function assertPrerequisiteCount(prerequisites: readonly unknown[]): void {\n if (!Array.isArray(prerequisites)) {\n throw new Error(\"notification-preview prerequisites must be an array\");\n }\n if (prerequisites.length > MAX_PREVIEW_PREREQUISITES) {\n throw new Error(\n `notification-preview takes at most ${MAX_PREVIEW_PREREQUISITES} prerequisite envelopes`,\n );\n }\n}\n\n/**\n * The per-account scope rule, shared with `MessagingClient` so the preview and\n * the tab's writer always read the same slot. Re-exported for tests.\n */\nexport { scopeStorage };\n\n/**\n * Wrap a host `Storage` so writes REJECT. The Rust side already opens the MLS\n * snapshot through a read-only backend; this guards the host-KV half\n * (`device`, `groups`, `cursors`, …), which the read-only MLS backend cannot\n * see. Defense in depth against a host bug making the Service Worker a second\n * writer. Exported for tests.\n */\nexport function readOnlyStorage(storage: Storage): Storage {\n const refuse = (op: string): Promise<never> =>\n Promise.reject(\n new Error(`notification-preview storage is read-only (attempted ${op})`),\n );\n const readOnly: Storage = {\n get: (ns, key) => storage.get(ns, key),\n put: (_ns, _key, _value) => refuse(\"put\"),\n del: (_ns, _key) => refuse(\"del\"),\n listKeys: (ns, prefix) => storage.listKeys(ns, prefix),\n };\n // `listEntries` is a read, so the read-only open keeps its one-call path.\n // `applyBatch` is a write and is deliberately absent: the wasm only uses\n // the methods it finds, and the read-only backend never batches.\n const hostListEntries = storage.listEntries;\n if (typeof hostListEntries === \"function\") {\n readOnly.listEntries = (ns, prefix) => hostListEntries.call(storage, ns, prefix);\n }\n return readOnly;\n}\n\n/**\n * A transport that can never be used: the preview client never sends, never\n * fetches, never discovers. `send` rejects loudly so a wiring mistake is\n * caught instead of silently networking from a push handler.\n */\nfunction silentTransport(): {\n send(envelope: unknown): Promise<never>;\n fetchSince(conv: unknown, cursor: unknown, limit: number): Promise<unknown[]>;\n discoverDevices(userId: unknown): Promise<unknown[]>;\n setNextWelcomeRecipients(conv: unknown, recipients: unknown): Promise<void>;\n} {\n return {\n send: () => Promise.reject(new Error(\"notification-preview cannot send\")),\n fetchSince: () => Promise.resolve([]),\n discoverDevices: () => Promise.resolve([]),\n setNextWelcomeRecipients: () => Promise.resolve(),\n };\n}\n","// Per-account storage scoping, and the optional-method probe that has to agree\n// with it.\n//\n// `MessagingClient` and `openNotificationPreview` both scope through\n// `scopeStorage`, so the tab's writer and the Service Worker's reader can never\n// disagree about which slot a namespace lives in.\n\nimport type { StorageFeatures } from \"../protocol\";\nimport type { Storage } from \"../types\";\n\n/**\n * Wrap a host `Storage` so every namespace carries the per-account scope\n * prefix: `\"${accountNamespace} ${ns}\"`, space separator. Keys and values pass\n * through untouched.\n *\n * The optional batch methods are forwarded exactly when the host has them.\n * That matters because the client tells the wasm which of them exist by\n * probing the storage it will actually call (`storageFeaturesOf`). This\n * wrapper once forwarded only the four basic methods, while the probe looked\n * at the unwrapped host: every scoped account was told `listEntries` existed,\n * the call reached the wrapper, resolved `undefined`, and the store open failed\n * with \"listEntries must resolve to an array\". A dropped `applyBatch` would\n * have been worse, acknowledging writes that never happened.\n */\nexport function scopeStorage(storage: Storage, accountNamespace: string): Storage {\n const scope = (ns: string): string => `${accountNamespace} ${ns}`;\n const scoped: Storage = {\n get: (ns, key) => storage.get(scope(ns), key),\n put: (ns, key, value) => storage.put(scope(ns), key, value),\n del: (ns, key) => storage.del(scope(ns), key),\n listKeys: (ns, prefix) => storage.listKeys(scope(ns), prefix),\n };\n const hostApplyBatch = storage.applyBatch;\n if (typeof hostApplyBatch === \"function\") {\n scoped.applyBatch = (ns, puts, deletes) =>\n hostApplyBatch.call(storage, scope(ns), puts, deletes);\n }\n const hostListEntries = storage.listEntries;\n if (typeof hostListEntries === \"function\") {\n scoped.listEntries = (ns, prefix) => hostListEntries.call(storage, scope(ns), prefix);\n }\n return scoped;\n}\n\n/**\n * Which optional methods `storage` really has. Probe the storage the client\n * dispatches to (after any wrapping), never the one the host passed in: the\n * worker hands the wasm a proxy for exactly these, and a method the dispatch\n * target lacks must never be advertised.\n */\nexport function storageFeaturesOf(storage: Storage): StorageFeatures {\n return {\n applyBatch: typeof storage.applyBatch === \"function\",\n listEntries: typeof storage.listEntries === \"function\",\n };\n}\n","// Linear-memory reservation shared by every realm that instantiates the wasm.\n\n/**\n * Linear-memory headroom the worker reserves from JavaScript right after\n * instantiation, largest first; a target the engine refuses (`RangeError`)\n * falls through to the next. Sized so the Argon2id recovery backup\n * (64 MiB of blocks in ONE allocation) and a large history bundle fit\n * inside memory the module already owns.\n *\n * Why from JS and not inside the module: Safari/JSC (macOS 26 / iOS 26,\n * IPInt) crashes the WebContent process when the wasm `memory.grow`\n * INSTRUCTION runs in a Worker while the Web Inspector is attached — the GC\n * it triggers walks the stack and dies on the wasm frame. The same grow\n * requested through `WebAssembly.Memory.prototype.grow` has only JS frames\n * on the stack and is fine. The module's allocator (`ping-wasm/src/alloc.rs`)\n * claims these pages before it would ever execute the instruction itself.\n * The pages are virtual until touched, so an idle worker costs nothing extra.\n */\nexport const RESERVE_MIB_TARGETS = [192, 128, 64, 32] as const;\nconst WASM_PAGE_BYTES = 64 * 1024;\n\n/** Memories already reserved: `init` is idempotent per realm and returns the\n * same instance, so a second open must not grow it again. */\nconst reserved = new WeakSet<WebAssembly.Memory>();\n\nexport function reserveLinearMemory(memory: WebAssembly.Memory): void {\n if (reserved.has(memory)) return;\n reserved.add(memory);\n for (const mib of RESERVE_MIB_TARGETS) {\n try {\n memory.grow((mib * 1024 * 1024) / WASM_PAGE_BYTES);\n return;\n } catch {\n // Over the engine's limit for this memory; try a smaller reservation.\n }\n }\n}\n\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACwBO,SAAS,aAAa,SAAkB,kBAAmC;AAChF,QAAM,QAAQ,CAAC,OAAuB,GAAG,gBAAgB,IAAI,EAAE;AAC/D,QAAM,SAAkB;AAAA,IACtB,KAAK,CAAC,IAAI,QAAQ,QAAQ,IAAI,MAAM,EAAE,GAAG,GAAG;AAAA,IAC5C,KAAK,CA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,IAChC,UAAU,CAAC,IAAI,WAAW,QAAQ,SAAS,IAAI,MAAM;AAAA,EACvD;AAIA,QAAM,kBAAkB,QAAQ;AAChC,MAAI,OAAO,oBAAoB,YAAY;AACzC,aAAS,cAAc,CAAC,IAAI,WAAW,gBAAgB,KAAK,SAAS,IAAI,MAAM;AAAA,EACjF;AACA,SAAO;AACT;AAOA,SAAS,kBAKP;AACA,SAAO;AAAA,IACL,MAAM,MAAM,QAAQ,OAAO,IAAI,MAAM,kCAAkC,CAAC;AAAA,IACxE,YAAY,MAAM,QAAQ,QAAQ,CAAC,CAAC;AAAA,IACpC,iBAAiB,MAAM,QAAQ,QAAQ,CAAC,CAAC;AAAA,IACzC,0BAA0B,MAAM,QAAQ,QAAQ;AAAA,EAClD;AACF;","names":[]}
1
+ {"version":3,"sources":["../src/notification-preview.ts","../src/storage/scope.ts","../src/wasm-memory.ts"],"sourcesContent":["// [CR-5] Read-only notification preview for the web Service Worker.\n//\n// The web mirror of the iOS Notification Service Extension: a second JS realm\n// (the push-handling Service Worker, woken while the tab may be closed OR open\n// and writing) that must turn one push-delivered envelope into a sender and a\n// body preview, and change NOTHING.\n//\n// This module deliberately does NOT go through the SDK's usual Worker bridge:\n// a Service Worker cannot spawn a dedicated `Worker` on every browser, and a\n// preview needs one decrypt, not a message pipeline. The WASM module is loaded\n// INLINE in the calling realm (no DOM APIs are touched), wrapping the core's\n// `MessagingClient::open_read_only` + `preview_envelope` — the same read-only\n// seam the iOS NSE uses, with the same semantics:\n//\n// * the SDK storage is opened READ-ONLY: the MLS snapshot is copied into\n// memory at open and never written back, so the tab remains the single\n// writer and cannot be disturbed (two writers on the whole-state blob\n// REPLACE each other — see `StorageBackend::AsyncBlobReadOnly`);\n// * the ratchet advance from the preview decrypt is thrown away; the tab\n// decrypts the same message again later, independently. Nothing is\n// consumed that the tab needs, and nothing this session does is\n// observable by the tab;\n// * handshake traffic (Commit/Welcome/Proposal), unknown conversations, and\n// replays the hydrated cursor rejects all resolve to `null` — show the\n// generic banner, it is a normal answer;\n// * a message the tab ALREADY consumed and checkpointed cannot be decrypted\n// from the newer snapshot (its generation is burned): `previewEnvelope`\n// rejects. Treat ANY rejection as \"no preview\" (generic banner), never as\n// fatal.\n//\n// Concurrent-open safety: IndexedDB reads never block the tab's writes and the\n// session takes a point-in-time copy of the `__mls snapshot` blob at open, so\n// opening while a tab is live is safe by construction. The copy can be STALE\n// relative to the tab, which only widens the `null`/reject cases above. Open a\n// fresh session per push event (or per small batch) rather than caching one —\n// a fresh open sees the newest checkpoint.\n//\n// See docs/NOTIFICATION_PREVIEW_WEB.md for the full Service Worker guide\n// (wasm init in module vs classic workers, account-slot storage, ping-prime\n// wiring).\n\nimport { scopeStorage } from \"./storage/scope\";\nimport type { IncomingMessage, MessageEnvelope, Storage } from \"./types\";\nimport { reserveLinearMemory } from \"./wasm-memory\";\n\nexport interface NotificationPreviewOptions {\n /**\n * The SAME `Storage` implementation (and underlying IndexedDB database)\n * the tab's `MessagingClient` persists to. It is wrapped read-only here:\n * `put`/`del` reject, so a host bug cannot make the Service Worker a\n * second writer.\n */\n storage: Storage;\n /**\n * The tab's `ClientConfig.accountNamespace` for this account slot, when it\n * uses one. MUST match exactly — the preview scopes every namespace with\n * the same `\"${accountNamespace} \"` prefix rule as `MessagingClient`, and a\n * mismatch reads an empty store (open rejects with \"no checkpoint\").\n */\n accountNamespace?: string;\n /**\n * Where to load `ping_wasm_bg.wasm` from, passed through to the\n * wasm-bindgen `init`. Defaults to the URL baked next to the module —\n * correct when the bundler ships the `wasm/` directory alongside. Classic\n * (importScripts) Service Workers, or bundlers that relocate assets, pass\n * an explicit URL here.\n */\n wasmModuleOrPath?: string | URL | WebAssembly.Module;\n /** Override the wall clock (test/sim only). */\n now?: () => number;\n}\n\n/**\n * The most prerequisite envelopes `previewEnvelopeWithPrerequisites` accepts.\n * The envelopes come from the server before anything authenticates them, so\n * the work they can cause is bounded. Mirrors the core's\n * `PREVIEW_PREREQUISITES_MAX`.\n */\nexport const MAX_PREVIEW_PREREQUISITES = 64;\n\nexport interface NotificationPreviewSession {\n /**\n * Decrypt ONE push-delivered envelope for display. Resolves to the\n * decrypted message (sender ids, conversation id, plaintext — everything a\n * banner needs) or `null` when there is nothing to show. Rejects when the\n * snapshot cannot decrypt it (commonly: the tab consumed it first) — treat\n * a rejection exactly like `null` and fall back to the generic banner.\n *\n * The returned message never carries a `journal_id`: a preview decrypt is\n * not journaled (nothing durable happened) and needs no `confirmApplied`.\n */\n previewEnvelope(envelope: MessageEnvelope): Promise<IncomingMessage | null>;\n /**\n * Decrypt ONE push-delivered envelope that this device cannot read yet,\n * because the handshake traffic in front of it has not been processed: the\n * first message of a conversation whose Welcome is still pending, or a\n * message sent after a Commit the tab has not applied.\n *\n * `prerequisites` are the envelopes that precede `envelope`, oldest first:\n * the pending Welcome (if any) and the Commits and Proposals after it.\n * They are applied to this session's private in-memory copy and then\n * `envelope` is decrypted. Nothing is persisted, the one-time KeyPackage\n * the Welcome was sealed to stays in the store, and the tab later joins and\n * decrypts for itself as if this call never happened.\n *\n * Envelopes for other conversations are ignored, a Welcome is not applied\n * to a conversation the snapshot already holds and can read, and a\n * prerequisite that does not apply is skipped. At most\n * {@link MAX_PREVIEW_PREREQUISITES} prerequisites; more rejects.\n *\n * Same result contract as `previewEnvelope`: `null` when there is nothing\n * to show, a rejection when the message cannot be decrypted. Treat both as\n * \"no preview\" and fall back to the generic banner.\n *\n * The applied prerequisites stay in the session's memory, so open a fresh\n * session per push event (the module comment already says to).\n */\n previewEnvelopeWithPrerequisites(\n prerequisites: MessageEnvelope[],\n envelope: MessageEnvelope,\n ): Promise<IncomingMessage | null>;\n /** Release the WASM instance. The session is unusable afterwards. */\n close(): void;\n}\n\n/**\n * Open the SDK read-only for notification previews, from a Service Worker (or\n * any realm without the SDK's Worker bridge). Rejects when the store holds no\n * checkpoint or no device identity — a Service Worker for an account that\n * never initialised locally has nothing to decrypt with, and \"successfully\n * decrypt nothing\" would be the worst possible answer.\n */\nexport async function openNotificationPreview(\n opts: NotificationPreviewOptions,\n): Promise<NotificationPreviewSession> {\n const now = opts.now ?? (() => Date.now());\n const scoped =\n opts.accountNamespace !== undefined && opts.accountNamespace.length > 0\n ? scopeStorage(opts.storage, opts.accountNamespace)\n : opts.storage;\n const storage = readOnlyStorage(scoped);\n\n // Inline WASM load — the module ships no DOM dependency, so this works in\n // window, worker, and service-worker realms alike. `init` is idempotent per\n // realm (subsequent opens reuse the instantiated module).\n const wasm = await import(\"../wasm/ping_wasm\");\n const out = await wasm.default(\n opts.wasmModuleOrPath === undefined\n ? undefined\n : ({ module_or_path: opts.wasmModuleOrPath } as never),\n );\n // Same Safari mitigation as the worker (`wasm-memory.ts`): grow from JS\n // once so the module never executes `memory.grow` itself. Idempotent.\n reserveLinearMemory(out.memory);\n\n // Label is unused on the read-only path (no LocalDevice is ever minted).\n const client =\n await wasm.PingClient.openReadOnlyFromDeviceRecord(\n \"notification-preview\",\n storage as never,\n silentTransport() as never,\n now(),\n );\n\n let closed = false;\n return {\n async previewEnvelope(envelope: MessageEnvelope): Promise<IncomingMessage | null> {\n if (closed) throw new Error(\"notification-preview session is closed\");\n const result = client.previewEnvelope(envelope as never, now());\n return (result ?? null) as IncomingMessage | null;\n },\n async previewEnvelopeWithPrerequisites(\n prerequisites: MessageEnvelope[],\n envelope: MessageEnvelope,\n ): Promise<IncomingMessage | null> {\n if (closed) throw new Error(\"notification-preview session is closed\");\n assertPrerequisiteCount(prerequisites);\n const result = client.previewEnvelopeWithPrerequisites(\n prerequisites as never,\n envelope as never,\n now(),\n );\n return (result ?? null) as IncomingMessage | null;\n },\n close() {\n if (closed) return;\n closed = true;\n client.free();\n },\n };\n}\n\n/**\n * Refuse an oversized prerequisite list before it crosses into WASM. The core\n * enforces the same bound; checking here keeps the copy out of linear memory.\n * Exported for tests.\n */\nexport function assertPrerequisiteCount(prerequisites: readonly unknown[]): void {\n if (!Array.isArray(prerequisites)) {\n throw new Error(\"notification-preview prerequisites must be an array\");\n }\n if (prerequisites.length > MAX_PREVIEW_PREREQUISITES) {\n throw new Error(\n `notification-preview takes at most ${MAX_PREVIEW_PREREQUISITES} prerequisite envelopes`,\n );\n }\n}\n\n/**\n * The per-account scope rule, shared with `MessagingClient` so the preview and\n * the tab's writer always read the same slot. Re-exported for tests.\n */\nexport { scopeStorage };\n\n/**\n * Wrap a host `Storage` so writes REJECT. The Rust side already opens the MLS\n * snapshot through a read-only backend; this guards the host-KV half\n * (`device`, `groups`, `cursors`, …), which the read-only MLS backend cannot\n * see. Defense in depth against a host bug making the Service Worker a second\n * writer. Exported for tests.\n */\nexport function readOnlyStorage(storage: Storage): Storage {\n const refuse = (op: string): Promise<never> =>\n Promise.reject(\n new Error(`notification-preview storage is read-only (attempted ${op})`),\n );\n const readOnly: Storage = {\n get: (ns, key) => storage.get(ns, key),\n put: (_ns, _key, _value) => refuse(\"put\"),\n del: (_ns, _key) => refuse(\"del\"),\n listKeys: (ns, prefix) => storage.listKeys(ns, prefix),\n };\n // `listEntries` is a read, so the read-only open keeps its one-call path.\n // `applyBatch` is a write and is deliberately absent: the wasm only uses\n // the methods it finds, and the read-only backend never batches.\n const hostListEntries = storage.listEntries;\n if (typeof hostListEntries === \"function\") {\n readOnly.listEntries = (ns, prefix) => hostListEntries.call(storage, ns, prefix);\n }\n return readOnly;\n}\n\n/**\n * A transport that can never be used: the preview client never sends, never\n * fetches, never discovers. `send` rejects loudly so a wiring mistake is\n * caught instead of silently networking from a push handler.\n */\nfunction silentTransport(): {\n send(envelope: unknown): Promise<never>;\n fetchSince(conv: unknown, cursor: unknown, limit: number): Promise<unknown[]>;\n discoverDevices(userId: unknown): Promise<unknown[]>;\n setNextWelcomeRecipients(conv: unknown, recipients: unknown): Promise<void>;\n} {\n return {\n send: () => Promise.reject(new Error(\"notification-preview cannot send\")),\n fetchSince: () => Promise.resolve([]),\n discoverDevices: () => Promise.resolve([]),\n setNextWelcomeRecipients: () => Promise.resolve(),\n };\n}\n","// Per-account storage scoping, and the optional-method probe that has to agree\n// with it.\n//\n// `MessagingClient` and `openNotificationPreview` both scope through\n// `scopeStorage`, so the tab's writer and the Service Worker's reader can never\n// disagree about which slot a namespace lives in.\n\nimport type { StorageFeatures } from \"../protocol\";\nimport type { Storage } from \"../types\";\n\n/**\n * Wrap a host `Storage` so every namespace carries the per-account scope\n * prefix: `\"${accountNamespace} ${ns}\"`, space separator. Keys and values pass\n * through untouched.\n *\n * The optional batch methods are forwarded exactly when the host has them.\n * That matters because the client tells the wasm which of them exist by\n * probing the storage it will actually call (`storageFeaturesOf`). This\n * wrapper once forwarded only the four basic methods, while the probe looked\n * at the unwrapped host: every scoped account was told `listEntries` existed,\n * the call reached the wrapper, resolved `undefined`, and the store open failed\n * with \"listEntries must resolve to an array\". A dropped `applyBatch` would\n * have been worse, acknowledging writes that never happened.\n */\nexport function scopeStorage(storage: Storage, accountNamespace: string): Storage {\n const scope = (ns: string): string => `${accountNamespace} ${ns}`;\n const scoped: Storage = {\n get: (ns, key) => storage.get(scope(ns), key),\n put: (ns, key, value) => storage.put(scope(ns), key, value),\n del: (ns, key) => storage.del(scope(ns), key),\n listKeys: (ns, prefix) => storage.listKeys(scope(ns), prefix),\n };\n const hostApplyBatch = storage.applyBatch;\n if (typeof hostApplyBatch === \"function\") {\n scoped.applyBatch = (ns, puts, deletes) =>\n hostApplyBatch.call(storage, scope(ns), puts, deletes);\n }\n const hostListEntries = storage.listEntries;\n if (typeof hostListEntries === \"function\") {\n scoped.listEntries = (ns, prefix) => hostListEntries.call(storage, scope(ns), prefix);\n }\n return scoped;\n}\n\n/**\n * Which optional methods `storage` really has. Probe the storage the client\n * dispatches to (after any wrapping), never the one the host passed in: the\n * worker hands the wasm a proxy for exactly these, and a method the dispatch\n * target lacks must never be advertised.\n */\nexport function storageFeaturesOf(storage: Storage): StorageFeatures {\n return {\n applyBatch: typeof storage.applyBatch === \"function\",\n listEntries: typeof storage.listEntries === \"function\",\n };\n}\n","// Linear-memory reservation shared by every realm that instantiates the wasm.\n\n/**\n * Linear-memory headroom the worker reserves from JavaScript right after\n * instantiation, largest first; a target the engine refuses (`RangeError`)\n * falls through to the next. Sized so the Argon2id recovery backup\n * (64 MiB of blocks in ONE allocation) and a large history bundle fit\n * inside memory the module already owns.\n *\n * Why from JS and not inside the module: Safari/JSC (macOS 26 / iOS 26,\n * IPInt) crashes the WebContent process when the wasm `memory.grow`\n * INSTRUCTION runs in a Worker while the Web Inspector is attached — the GC\n * it triggers walks the stack and dies on the wasm frame. The same grow\n * requested through `WebAssembly.Memory.prototype.grow` has only JS frames\n * on the stack and is fine. The module's allocator (`ping-wasm/src/alloc.rs`)\n * claims these pages before it would ever execute the instruction itself.\n * The pages are virtual until touched, so an idle worker costs nothing extra.\n */\nexport const RESERVE_MIB_TARGETS = [192, 128, 64, 32] as const;\nconst WASM_PAGE_BYTES = 64 * 1024;\n\n/** Memories already reserved: `init` is idempotent per realm and returns the\n * same instance, so a second open must not grow it again. */\nconst reserved = new WeakSet<WebAssembly.Memory>();\n\nexport function reserveLinearMemory(memory: WebAssembly.Memory): void {\n if (reserved.has(memory)) return;\n reserved.add(memory);\n for (const mib of RESERVE_MIB_TARGETS) {\n try {\n memory.grow((mib * 1024 * 1024) / WASM_PAGE_BYTES);\n return;\n } catch {\n // Over the engine's limit for this memory; try a smaller reservation.\n }\n }\n}\n\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACwBO,SAAS,aAAa,SAAkB,kBAAmC;AAChF,QAAM,QAAQ,CAAC,OAAuB,GAAG,gBAAgB,IAAI,EAAE;AAC/D,QAAM,SAAkB;AAAA,IACtB,KAAK,CAAC,IAAI,QAAQ,QAAQ,IAAI,MAAM,EAAE,GAAG,GAAG;AAAA,IAC5C,KAAK,CAAC,IAAI,KAAK,UAAU,QAAQ,IAAI,MAAM,EAAE,GAAG,KAAK,KAAK;AAAA,IAC1D,KAAK,CAAC,IAAI,QA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YAAY;AACzC,aAAS,cAAc,CAAC,IAAI,WAAW,gBAAgB,KAAK,SAAS,IAAI,MAAM;AAAA,EACjF;AACA,SAAO;AACT;AAOA,SAAS,kBAKP;AACA,SAAO;AAAA,IACL,MAAM,MAAM,QAAQ,OAAO,IAAI,MAAM,kCAAkC,CAAC;AAAA,IACxE,YAAY,MAAM,QAAQ,QAAQ,CAAC,CAAC;AAAA,IACpC,iBAAiB,MAAM,QAAQ,QAAQ,CAAC,CAAC;AAAA,IACzC,0BAA0B,MAAM,QAAQ,QAAQ;AAAA,EAClD;AACF;","names":[]}
@@ -1,4 +1,4 @@
1
- import { S as Storage, M as MessageEnvelope, i as IncomingMessage } from './types-gAmJFSC-.cjs';
1
+ import { S as Storage, M as MessageEnvelope, I as IncomingMessage } from './types-omhvRjtq.cjs';
2
2
 
3
3
  /**
4
4
  * Wrap a host `Storage` so every namespace carries the per-account scope
@@ -17,13 +17,6 @@ import { S as Storage, M as MessageEnvelope, i as IncomingMessage } from './type
17
17
  declare function scopeStorage(storage: Storage, accountNamespace: string): Storage;
18
18
 
19
19
  interface NotificationPreviewOptions {
20
- /**
21
- * The account identity export (CBOR-wrapped Ed25519 seed, SECRET) — the
22
- * same bytes the tab passes to `MessagingClient.init`. The Service Worker
23
- * host must read it from wherever the tab keeps it (e.g. the encrypted IDB
24
- * slot); it never crosses the network.
25
- */
26
- identityExport: Uint8Array;
27
20
  /**
28
21
  * The SAME `Storage` implementation (and underlying IndexedDB database)
29
22
  * the tab's `MessagingClient` persists to. It is wrapped read-only here:
@@ -1,4 +1,4 @@
1
- import { S as Storage, M as MessageEnvelope, i as IncomingMessage } from './types-gAmJFSC-.js';
1
+ import { S as Storage, M as MessageEnvelope, I as IncomingMessage } from './types-omhvRjtq.js';
2
2
 
3
3
  /**
4
4
  * Wrap a host `Storage` so every namespace carries the per-account scope
@@ -17,13 +17,6 @@ import { S as Storage, M as MessageEnvelope, i as IncomingMessage } from './type
17
17
  declare function scopeStorage(storage: Storage, accountNamespace: string): Storage;
18
18
 
19
19
  interface NotificationPreviewOptions {
20
- /**
21
- * The account identity export (CBOR-wrapped Ed25519 seed, SECRET) — the
22
- * same bytes the tab passes to `MessagingClient.init`. The Service Worker
23
- * host must read it from wherever the tab keeps it (e.g. the encrypted IDB
24
- * slot); it never crosses the network.
25
- */
26
- identityExport: Uint8Array;
27
20
  /**
28
21
  * The SAME `Storage` implementation (and underlying IndexedDB database)
29
22
  * the tab's `MessagingClient` persists to. It is wrapped read-only here:
@@ -45,9 +45,7 @@ async function openNotificationPreview(opts) {
45
45
  opts.wasmModuleOrPath === void 0 ? void 0 : { module_or_path: opts.wasmModuleOrPath }
46
46
  );
47
47
  reserveLinearMemory(out.memory);
48
- const client = await wasm.PingClient.openReadOnly(
49
- opts.identityExport,
50
- // Label is unused on the read-only path (no LocalDevice is ever minted).
48
+ const client = await wasm.PingClient.openReadOnlyFromDeviceRecord(
51
49
  "notification-preview",
52
50
  storage,
53
51
  silentTransport(),
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/storage/scope.ts","../src/wasm-memory.ts","../src/notification-preview.ts"],"sourcesContent":["// Per-account storage scoping, and the optional-method probe that has to agree\n// with it.\n//\n// `MessagingClient` and `openNotificationPreview` both scope through\n// `scopeStorage`, so the tab's writer and the Service Worker's reader can never\n// disagree about which slot a namespace lives in.\n\nimport type { StorageFeatures } from \"../protocol\";\nimport type { Storage } from \"../types\";\n\n/**\n * Wrap a host `Storage` so every namespace carries the per-account scope\n * prefix: `\"${accountNamespace} ${ns}\"`, space separator. Keys and values pass\n * through untouched.\n *\n * The optional batch methods are forwarded exactly when the host has them.\n * That matters because the client tells the wasm which of them exist by\n * probing the storage it will actually call (`storageFeaturesOf`). This\n * wrapper once forwarded only the four basic methods, while the probe looked\n * at the unwrapped host: every scoped account was told `listEntries` existed,\n * the call reached the wrapper, resolved `undefined`, and the store open failed\n * with \"listEntries must resolve to an array\". A dropped `applyBatch` would\n * have been worse, acknowledging writes that never happened.\n */\nexport function scopeStorage(storage: Storage, accountNamespace: string): Storage {\n const scope = (ns: string): string => `${accountNamespace} ${ns}`;\n const scoped: Storage = {\n get: (ns, key) => storage.get(scope(ns), key),\n put: (ns, key, value) => storage.put(scope(ns), key, value),\n del: (ns, key) => storage.del(scope(ns), key),\n listKeys: (ns, prefix) => storage.listKeys(scope(ns), prefix),\n };\n const hostApplyBatch = storage.applyBatch;\n if (typeof hostApplyBatch === \"function\") {\n scoped.applyBatch = (ns, puts, deletes) =>\n hostApplyBatch.call(storage, scope(ns), puts, deletes);\n }\n const hostListEntries = storage.listEntries;\n if (typeof hostListEntries === \"function\") {\n scoped.listEntries = (ns, prefix) => hostListEntries.call(storage, scope(ns), prefix);\n }\n return scoped;\n}\n\n/**\n * Which optional methods `storage` really has. Probe the storage the client\n * dispatches to (after any wrapping), never the one the host passed in: the\n * worker hands the wasm a proxy for exactly these, and a method the dispatch\n * target lacks must never be advertised.\n */\nexport function storageFeaturesOf(storage: Storage): StorageFeatures {\n return {\n applyBatch: typeof storage.applyBatch === \"function\",\n listEntries: typeof storage.listEntries === \"function\",\n };\n}\n","// Linear-memory reservation shared by every realm that instantiates the wasm.\n\n/**\n * Linear-memory headroom the worker reserves from JavaScript right after\n * instantiation, largest first; a target the engine refuses (`RangeError`)\n * falls through to the next. Sized so the Argon2id recovery backup\n * (64 MiB of blocks in ONE allocation) and a large history bundle fit\n * inside memory the module already owns.\n *\n * Why from JS and not inside the module: Safari/JSC (macOS 26 / iOS 26,\n * IPInt) crashes the WebContent process when the wasm `memory.grow`\n * INSTRUCTION runs in a Worker while the Web Inspector is attached — the GC\n * it triggers walks the stack and dies on the wasm frame. The same grow\n * requested through `WebAssembly.Memory.prototype.grow` has only JS frames\n * on the stack and is fine. The module's allocator (`ping-wasm/src/alloc.rs`)\n * claims these pages before it would ever execute the instruction itself.\n * The pages are virtual until touched, so an idle worker costs nothing extra.\n */\nexport const RESERVE_MIB_TARGETS = [192, 128, 64, 32] as const;\nconst WASM_PAGE_BYTES = 64 * 1024;\n\n/** Memories already reserved: `init` is idempotent per realm and returns the\n * same instance, so a second open must not grow it again. */\nconst reserved = new WeakSet<WebAssembly.Memory>();\n\nexport function reserveLinearMemory(memory: WebAssembly.Memory): void {\n if (reserved.has(memory)) return;\n reserved.add(memory);\n for (const mib of RESERVE_MIB_TARGETS) {\n try {\n memory.grow((mib * 1024 * 1024) / WASM_PAGE_BYTES);\n return;\n } catch {\n // Over the engine's limit for this memory; try a smaller reservation.\n }\n }\n}\n\n","// [CR-5] Read-only notification preview for the web Service Worker.\n//\n// The web mirror of the iOS Notification Service Extension: a second JS realm\n// (the push-handling Service Worker, woken while the tab may be closed OR open\n// and writing) that must turn one push-delivered envelope into a sender and a\n// body preview, and change NOTHING.\n//\n// This module deliberately does NOT go through the SDK's usual Worker bridge:\n// a Service Worker cannot spawn a dedicated `Worker` on every browser, and a\n// preview needs one decrypt, not a message pipeline. The WASM module is loaded\n// INLINE in the calling realm (no DOM APIs are touched), wrapping the core's\n// `MessagingClient::open_read_only` + `preview_envelope` — the same read-only\n// seam the iOS NSE uses, with the same semantics:\n//\n// * the SDK storage is opened READ-ONLY: the MLS snapshot is copied into\n// memory at open and never written back, so the tab remains the single\n// writer and cannot be disturbed (two writers on the whole-state blob\n// REPLACE each other — see `StorageBackend::AsyncBlobReadOnly`);\n// * the ratchet advance from the preview decrypt is thrown away; the tab\n// decrypts the same message again later, independently. Nothing is\n// consumed that the tab needs, and nothing this session does is\n// observable by the tab;\n// * handshake traffic (Commit/Welcome/Proposal), unknown conversations, and\n// replays the hydrated cursor rejects all resolve to `null` — show the\n// generic banner, it is a normal answer;\n// * a message the tab ALREADY consumed and checkpointed cannot be decrypted\n// from the newer snapshot (its generation is burned): `previewEnvelope`\n// rejects. Treat ANY rejection as \"no preview\" (generic banner), never as\n// fatal.\n//\n// Concurrent-open safety: IndexedDB reads never block the tab's writes and the\n// session takes a point-in-time copy of the `__mls snapshot` blob at open, so\n// opening while a tab is live is safe by construction. The copy can be STALE\n// relative to the tab, which only widens the `null`/reject cases above. Open a\n// fresh session per push event (or per small batch) rather than caching one —\n// a fresh open sees the newest checkpoint.\n//\n// See docs/NOTIFICATION_PREVIEW_WEB.md for the full Service Worker guide\n// (wasm init in module vs classic workers, account-slot storage, ping-prime\n// wiring).\n\nimport { scopeStorage } from \"./storage/scope\";\nimport type { IncomingMessage, MessageEnvelope, Storage } from \"./types\";\nimport { reserveLinearMemory } from \"./wasm-memory\";\n\nexport interface NotificationPreviewOptions {\n /**\n * The account identity export (CBOR-wrapped Ed25519 seed, SECRET) — the\n * same bytes the tab passes to `MessagingClient.init`. The Service Worker\n * host must read it from wherever the tab keeps it (e.g. the encrypted IDB\n * slot); it never crosses the network.\n */\n identityExport: Uint8Array;\n /**\n * The SAME `Storage` implementation (and underlying IndexedDB database)\n * the tab's `MessagingClient` persists to. It is wrapped read-only here:\n * `put`/`del` reject, so a host bug cannot make the Service Worker a\n * second writer.\n */\n storage: Storage;\n /**\n * The tab's `ClientConfig.accountNamespace` for this account slot, when it\n * uses one. MUST match exactly — the preview scopes every namespace with\n * the same `\"${accountNamespace} \"` prefix rule as `MessagingClient`, and a\n * mismatch reads an empty store (open rejects with \"no checkpoint\").\n */\n accountNamespace?: string;\n /**\n * Where to load `ping_wasm_bg.wasm` from, passed through to the\n * wasm-bindgen `init`. Defaults to the URL baked next to the module —\n * correct when the bundler ships the `wasm/` directory alongside. Classic\n * (importScripts) Service Workers, or bundlers that relocate assets, pass\n * an explicit URL here.\n */\n wasmModuleOrPath?: string | URL | WebAssembly.Module;\n /** Override the wall clock (test/sim only). */\n now?: () => number;\n}\n\n/**\n * The most prerequisite envelopes `previewEnvelopeWithPrerequisites` accepts.\n * The envelopes come from the server before anything authenticates them, so\n * the work they can cause is bounded. Mirrors the core's\n * `PREVIEW_PREREQUISITES_MAX`.\n */\nexport const MAX_PREVIEW_PREREQUISITES = 64;\n\nexport interface NotificationPreviewSession {\n /**\n * Decrypt ONE push-delivered envelope for display. Resolves to the\n * decrypted message (sender ids, conversation id, plaintext — everything a\n * banner needs) or `null` when there is nothing to show. Rejects when the\n * snapshot cannot decrypt it (commonly: the tab consumed it first) — treat\n * a rejection exactly like `null` and fall back to the generic banner.\n *\n * The returned message never carries a `journal_id`: a preview decrypt is\n * not journaled (nothing durable happened) and needs no `confirmApplied`.\n */\n previewEnvelope(envelope: MessageEnvelope): Promise<IncomingMessage | null>;\n /**\n * Decrypt ONE push-delivered envelope that this device cannot read yet,\n * because the handshake traffic in front of it has not been processed: the\n * first message of a conversation whose Welcome is still pending, or a\n * message sent after a Commit the tab has not applied.\n *\n * `prerequisites` are the envelopes that precede `envelope`, oldest first:\n * the pending Welcome (if any) and the Commits and Proposals after it.\n * They are applied to this session's private in-memory copy and then\n * `envelope` is decrypted. Nothing is persisted, the one-time KeyPackage\n * the Welcome was sealed to stays in the store, and the tab later joins and\n * decrypts for itself as if this call never happened.\n *\n * Envelopes for other conversations are ignored, a Welcome is not applied\n * to a conversation the snapshot already holds and can read, and a\n * prerequisite that does not apply is skipped. At most\n * {@link MAX_PREVIEW_PREREQUISITES} prerequisites; more rejects.\n *\n * Same result contract as `previewEnvelope`: `null` when there is nothing\n * to show, a rejection when the message cannot be decrypted. Treat both as\n * \"no preview\" and fall back to the generic banner.\n *\n * The applied prerequisites stay in the session's memory, so open a fresh\n * session per push event (the module comment already says to).\n */\n previewEnvelopeWithPrerequisites(\n prerequisites: MessageEnvelope[],\n envelope: MessageEnvelope,\n ): Promise<IncomingMessage | null>;\n /** Release the WASM instance. The session is unusable afterwards. */\n close(): void;\n}\n\n/**\n * Open the SDK read-only for notification previews, from a Service Worker (or\n * any realm without the SDK's Worker bridge). Rejects when the store holds no\n * checkpoint or no device identity — a Service Worker for an account that\n * never initialised locally has nothing to decrypt with, and \"successfully\n * decrypt nothing\" would be the worst possible answer.\n */\nexport async function openNotificationPreview(\n opts: NotificationPreviewOptions,\n): Promise<NotificationPreviewSession> {\n const now = opts.now ?? (() => Date.now());\n const scoped =\n opts.accountNamespace !== undefined && opts.accountNamespace.length > 0\n ? scopeStorage(opts.storage, opts.accountNamespace)\n : opts.storage;\n const storage = readOnlyStorage(scoped);\n\n // Inline WASM load — the module ships no DOM dependency, so this works in\n // window, worker, and service-worker realms alike. `init` is idempotent per\n // realm (subsequent opens reuse the instantiated module).\n const wasm = await import(\"../wasm/ping_wasm\");\n const out = await wasm.default(\n opts.wasmModuleOrPath === undefined\n ? undefined\n : ({ module_or_path: opts.wasmModuleOrPath } as never),\n );\n // Same Safari mitigation as the worker (`wasm-memory.ts`): grow from JS\n // once so the module never executes `memory.grow` itself. Idempotent.\n reserveLinearMemory(out.memory);\n\n const client = await wasm.PingClient.openReadOnly(\n opts.identityExport,\n // Label is unused on the read-only path (no LocalDevice is ever minted).\n \"notification-preview\",\n storage as never,\n silentTransport() as never,\n now(),\n );\n\n let closed = false;\n return {\n async previewEnvelope(envelope: MessageEnvelope): Promise<IncomingMessage | null> {\n if (closed) throw new Error(\"notification-preview session is closed\");\n const result = client.previewEnvelope(envelope as never, now());\n return (result ?? null) as IncomingMessage | null;\n },\n async previewEnvelopeWithPrerequisites(\n prerequisites: MessageEnvelope[],\n envelope: MessageEnvelope,\n ): Promise<IncomingMessage | null> {\n if (closed) throw new Error(\"notification-preview session is closed\");\n assertPrerequisiteCount(prerequisites);\n const result = client.previewEnvelopeWithPrerequisites(\n prerequisites as never,\n envelope as never,\n now(),\n );\n return (result ?? null) as IncomingMessage | null;\n },\n close() {\n if (closed) return;\n closed = true;\n client.free();\n },\n };\n}\n\n/**\n * Refuse an oversized prerequisite list before it crosses into WASM. The core\n * enforces the same bound; checking here keeps the copy out of linear memory.\n * Exported for tests.\n */\nexport function assertPrerequisiteCount(prerequisites: readonly unknown[]): void {\n if (!Array.isArray(prerequisites)) {\n throw new Error(\"notification-preview prerequisites must be an array\");\n }\n if (prerequisites.length > MAX_PREVIEW_PREREQUISITES) {\n throw new Error(\n `notification-preview takes at most ${MAX_PREVIEW_PREREQUISITES} prerequisite envelopes`,\n );\n }\n}\n\n/**\n * The per-account scope rule, shared with `MessagingClient` so the preview and\n * the tab's writer always read the same slot. Re-exported for tests.\n */\nexport { scopeStorage };\n\n/**\n * Wrap a host `Storage` so writes REJECT. The Rust side already opens the MLS\n * snapshot through a read-only backend; this guards the host-KV half\n * (`device`, `groups`, `cursors`, …), which the read-only MLS backend cannot\n * see. Defense in depth against a host bug making the Service Worker a second\n * writer. Exported for tests.\n */\nexport function readOnlyStorage(storage: Storage): Storage {\n const refuse = (op: string): Promise<never> =>\n Promise.reject(\n new Error(`notification-preview storage is read-only (attempted ${op})`),\n );\n const readOnly: Storage = {\n get: (ns, key) => storage.get(ns, key),\n put: (_ns, _key, _value) => refuse(\"put\"),\n del: (_ns, _key) => refuse(\"del\"),\n listKeys: (ns, prefix) => storage.listKeys(ns, prefix),\n };\n // `listEntries` is a read, so the read-only open keeps its one-call path.\n // `applyBatch` is a write and is deliberately absent: the wasm only uses\n // the methods it finds, and the read-only backend never batches.\n const hostListEntries = storage.listEntries;\n if (typeof hostListEntries === \"function\") {\n readOnly.listEntries = (ns, prefix) => hostListEntries.call(storage, ns, prefix);\n }\n return readOnly;\n}\n\n/**\n * A transport that can never be used: the preview client never sends, never\n * fetches, never discovers. `send` rejects loudly so a wiring mistake is\n * caught instead of silently networking from a push handler.\n */\nfunction silentTransport(): {\n send(envelope: unknown): Promise<never>;\n fetchSince(conv: unknown, cursor: unknown, limit: number): Promise<unknown[]>;\n discoverDevices(userId: unknown): Promise<unknown[]>;\n setNextWelcomeRecipients(conv: unknown, recipients: unknown): Promise<void>;\n} {\n return {\n send: () => Promise.reject(new Error(\"notification-preview cannot send\")),\n fetchSince: () => Promise.resolve([]),\n discoverDevices: () => Promise.resolve([]),\n setNextWelcomeRecipients: () => Promise.resolve(),\n };\n}\n"],"mappings":";AAwBO,SAAS,aAAa,SAAkB,kBAAmC;AAChF,QAAM,QAAQ,CAAC,OAAuB,GAAG,gBAAgB,IAAI,EAAE;AAC/D,QAAM,SAAkB;A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KAAK,CAAC,KAAK,MAAM,WAAW,OAAO,KAAK;AAAA,IACxC,KAAK,CAAC,KAAK,SAAS,OAAO,KAAK;AAAA,IAChC,UAAU,CAAC,IAAI,WAAW,QAAQ,SAAS,IAAI,MAAM;AAAA,EACvD;AAIA,QAAM,kBAAkB,QAAQ;AAChC,MAAI,OAAO,oBAAoB,YAAY;AACzC,aAAS,cAAc,CAAC,IAAI,WAAW,gBAAgB,KAAK,SAAS,IAAI,MAAM;AAAA,EACjF;AACA,SAAO;AACT;AAOA,SAAS,kBAKP;AACA,SAAO;AAAA,IACL,MAAM,MAAM,QAAQ,OAAO,IAAI,MAAM,kCAAkC,CAAC;AAAA,IACxE,YAAY,MAAM,QAAQ,QAAQ,CAAC,CAAC;AAAA,IACpC,iBAAiB,MAAM,QAAQ,QAAQ,CAAC,CAAC;AAAA,IACzC,0BAA0B,MAAM,QAAQ,QAAQ;AAAA,EAClD;AACF;","names":[]}
1
+ {"version":3,"sources":["../src/storage/scope.ts","../src/wasm-memory.ts","../src/notification-preview.ts"],"sourcesContent":["// Per-account storage scoping, and the optional-method probe that has to agree\n// with it.\n//\n// `MessagingClient` and `openNotificationPreview` both scope through\n// `scopeStorage`, so the tab's writer and the Service Worker's reader can never\n// disagree about which slot a namespace lives in.\n\nimport type { StorageFeatures } from \"../protocol\";\nimport type { Storage } from \"../types\";\n\n/**\n * Wrap a host `Storage` so every namespace carries the per-account scope\n * prefix: `\"${accountNamespace} ${ns}\"`, space separator. Keys and values pass\n * through untouched.\n *\n * The optional batch methods are forwarded exactly when the host has them.\n * That matters because the client tells the wasm which of them exist by\n * probing the storage it will actually call (`storageFeaturesOf`). This\n * wrapper once forwarded only the four basic methods, while the probe looked\n * at the unwrapped host: every scoped account was told `listEntries` existed,\n * the call reached the wrapper, resolved `undefined`, and the store open failed\n * with \"listEntries must resolve to an array\". A dropped `applyBatch` would\n * have been worse, acknowledging writes that never happened.\n */\nexport function scopeStorage(storage: Storage, accountNamespace: string): Storage {\n const scope = (ns: string): string => `${accountNamespace} ${ns}`;\n const scoped: Storage = {\n get: (ns, key) => storage.get(scope(ns), key),\n put: (ns, key, value) => storage.put(scope(ns), key, value),\n del: (ns, key) => storage.del(scope(ns), key),\n listKeys: (ns, prefix) => storage.listKeys(scope(ns), prefix),\n };\n const hostApplyBatch = storage.applyBatch;\n if (typeof hostApplyBatch === \"function\") {\n scoped.applyBatch = (ns, puts, deletes) =>\n hostApplyBatch.call(storage, scope(ns), puts, deletes);\n }\n const hostListEntries = storage.listEntries;\n if (typeof hostListEntries === \"function\") {\n scoped.listEntries = (ns, prefix) => hostListEntries.call(storage, scope(ns), prefix);\n }\n return scoped;\n}\n\n/**\n * Which optional methods `storage` really has. Probe the storage the client\n * dispatches to (after any wrapping), never the one the host passed in: the\n * worker hands the wasm a proxy for exactly these, and a method the dispatch\n * target lacks must never be advertised.\n */\nexport function storageFeaturesOf(storage: Storage): StorageFeatures {\n return {\n applyBatch: typeof storage.applyBatch === \"function\",\n listEntries: typeof storage.listEntries === \"function\",\n };\n}\n","// Linear-memory reservation shared by every realm that instantiates the wasm.\n\n/**\n * Linear-memory headroom the worker reserves from JavaScript right after\n * instantiation, largest first; a target the engine refuses (`RangeError`)\n * falls through to the next. Sized so the Argon2id recovery backup\n * (64 MiB of blocks in ONE allocation) and a large history bundle fit\n * inside memory the module already owns.\n *\n * Why from JS and not inside the module: Safari/JSC (macOS 26 / iOS 26,\n * IPInt) crashes the WebContent process when the wasm `memory.grow`\n * INSTRUCTION runs in a Worker while the Web Inspector is attached — the GC\n * it triggers walks the stack and dies on the wasm frame. The same grow\n * requested through `WebAssembly.Memory.prototype.grow` has only JS frames\n * on the stack and is fine. The module's allocator (`ping-wasm/src/alloc.rs`)\n * claims these pages before it would ever execute the instruction itself.\n * The pages are virtual until touched, so an idle worker costs nothing extra.\n */\nexport const RESERVE_MIB_TARGETS = [192, 128, 64, 32] as const;\nconst WASM_PAGE_BYTES = 64 * 1024;\n\n/** Memories already reserved: `init` is idempotent per realm and returns the\n * same instance, so a second open must not grow it again. */\nconst reserved = new WeakSet<WebAssembly.Memory>();\n\nexport function reserveLinearMemory(memory: WebAssembly.Memory): void {\n if (reserved.has(memory)) return;\n reserved.add(memory);\n for (const mib of RESERVE_MIB_TARGETS) {\n try {\n memory.grow((mib * 1024 * 1024) / WASM_PAGE_BYTES);\n return;\n } catch {\n // Over the engine's limit for this memory; try a smaller reservation.\n }\n }\n}\n\n","// [CR-5] Read-only notification preview for the web Service Worker.\n//\n// The web mirror of the iOS Notification Service Extension: a second JS realm\n// (the push-handling Service Worker, woken while the tab may be closed OR open\n// and writing) that must turn one push-delivered envelope into a sender and a\n// body preview, and change NOTHING.\n//\n// This module deliberately does NOT go through the SDK's usual Worker bridge:\n// a Service Worker cannot spawn a dedicated `Worker` on every browser, and a\n// preview needs one decrypt, not a message pipeline. The WASM module is loaded\n// INLINE in the calling realm (no DOM APIs are touched), wrapping the core's\n// `MessagingClient::open_read_only` + `preview_envelope` — the same read-only\n// seam the iOS NSE uses, with the same semantics:\n//\n// * the SDK storage is opened READ-ONLY: the MLS snapshot is copied into\n// memory at open and never written back, so the tab remains the single\n// writer and cannot be disturbed (two writers on the whole-state blob\n// REPLACE each other — see `StorageBackend::AsyncBlobReadOnly`);\n// * the ratchet advance from the preview decrypt is thrown away; the tab\n// decrypts the same message again later, independently. Nothing is\n// consumed that the tab needs, and nothing this session does is\n// observable by the tab;\n// * handshake traffic (Commit/Welcome/Proposal), unknown conversations, and\n// replays the hydrated cursor rejects all resolve to `null` — show the\n// generic banner, it is a normal answer;\n// * a message the tab ALREADY consumed and checkpointed cannot be decrypted\n// from the newer snapshot (its generation is burned): `previewEnvelope`\n// rejects. Treat ANY rejection as \"no preview\" (generic banner), never as\n// fatal.\n//\n// Concurrent-open safety: IndexedDB reads never block the tab's writes and the\n// session takes a point-in-time copy of the `__mls snapshot` blob at open, so\n// opening while a tab is live is safe by construction. The copy can be STALE\n// relative to the tab, which only widens the `null`/reject cases above. Open a\n// fresh session per push event (or per small batch) rather than caching one —\n// a fresh open sees the newest checkpoint.\n//\n// See docs/NOTIFICATION_PREVIEW_WEB.md for the full Service Worker guide\n// (wasm init in module vs classic workers, account-slot storage, ping-prime\n// wiring).\n\nimport { scopeStorage } from \"./storage/scope\";\nimport type { IncomingMessage, MessageEnvelope, Storage } from \"./types\";\nimport { reserveLinearMemory } from \"./wasm-memory\";\n\nexport interface NotificationPreviewOptions {\n /**\n * The SAME `Storage` implementation (and underlying IndexedDB database)\n * the tab's `MessagingClient` persists to. It is wrapped read-only here:\n * `put`/`del` reject, so a host bug cannot make the Service Worker a\n * second writer.\n */\n storage: Storage;\n /**\n * The tab's `ClientConfig.accountNamespace` for this account slot, when it\n * uses one. MUST match exactly — the preview scopes every namespace with\n * the same `\"${accountNamespace} \"` prefix rule as `MessagingClient`, and a\n * mismatch reads an empty store (open rejects with \"no checkpoint\").\n */\n accountNamespace?: string;\n /**\n * Where to load `ping_wasm_bg.wasm` from, passed through to the\n * wasm-bindgen `init`. Defaults to the URL baked next to the module —\n * correct when the bundler ships the `wasm/` directory alongside. Classic\n * (importScripts) Service Workers, or bundlers that relocate assets, pass\n * an explicit URL here.\n */\n wasmModuleOrPath?: string | URL | WebAssembly.Module;\n /** Override the wall clock (test/sim only). */\n now?: () => number;\n}\n\n/**\n * The most prerequisite envelopes `previewEnvelopeWithPrerequisites` accepts.\n * The envelopes come from the server before anything authenticates them, so\n * the work they can cause is bounded. Mirrors the core's\n * `PREVIEW_PREREQUISITES_MAX`.\n */\nexport const MAX_PREVIEW_PREREQUISITES = 64;\n\nexport interface NotificationPreviewSession {\n /**\n * Decrypt ONE push-delivered envelope for display. Resolves to the\n * decrypted message (sender ids, conversation id, plaintext — everything a\n * banner needs) or `null` when there is nothing to show. Rejects when the\n * snapshot cannot decrypt it (commonly: the tab consumed it first) — treat\n * a rejection exactly like `null` and fall back to the generic banner.\n *\n * The returned message never carries a `journal_id`: a preview decrypt is\n * not journaled (nothing durable happened) and needs no `confirmApplied`.\n */\n previewEnvelope(envelope: MessageEnvelope): Promise<IncomingMessage | null>;\n /**\n * Decrypt ONE push-delivered envelope that this device cannot read yet,\n * because the handshake traffic in front of it has not been processed: the\n * first message of a conversation whose Welcome is still pending, or a\n * message sent after a Commit the tab has not applied.\n *\n * `prerequisites` are the envelopes that precede `envelope`, oldest first:\n * the pending Welcome (if any) and the Commits and Proposals after it.\n * They are applied to this session's private in-memory copy and then\n * `envelope` is decrypted. Nothing is persisted, the one-time KeyPackage\n * the Welcome was sealed to stays in the store, and the tab later joins and\n * decrypts for itself as if this call never happened.\n *\n * Envelopes for other conversations are ignored, a Welcome is not applied\n * to a conversation the snapshot already holds and can read, and a\n * prerequisite that does not apply is skipped. At most\n * {@link MAX_PREVIEW_PREREQUISITES} prerequisites; more rejects.\n *\n * Same result contract as `previewEnvelope`: `null` when there is nothing\n * to show, a rejection when the message cannot be decrypted. Treat both as\n * \"no preview\" and fall back to the generic banner.\n *\n * The applied prerequisites stay in the session's memory, so open a fresh\n * session per push event (the module comment already says to).\n */\n previewEnvelopeWithPrerequisites(\n prerequisites: MessageEnvelope[],\n envelope: MessageEnvelope,\n ): Promise<IncomingMessage | null>;\n /** Release the WASM instance. The session is unusable afterwards. */\n close(): void;\n}\n\n/**\n * Open the SDK read-only for notification previews, from a Service Worker (or\n * any realm without the SDK's Worker bridge). Rejects when the store holds no\n * checkpoint or no device identity — a Service Worker for an account that\n * never initialised locally has nothing to decrypt with, and \"successfully\n * decrypt nothing\" would be the worst possible answer.\n */\nexport async function openNotificationPreview(\n opts: NotificationPreviewOptions,\n): Promise<NotificationPreviewSession> {\n const now = opts.now ?? (() => Date.now());\n const scoped =\n opts.accountNamespace !== undefined && opts.accountNamespace.length > 0\n ? scopeStorage(opts.storage, opts.accountNamespace)\n : opts.storage;\n const storage = readOnlyStorage(scoped);\n\n // Inline WASM load — the module ships no DOM dependency, so this works in\n // window, worker, and service-worker realms alike. `init` is idempotent per\n // realm (subsequent opens reuse the instantiated module).\n const wasm = await import(\"../wasm/ping_wasm\");\n const out = await wasm.default(\n opts.wasmModuleOrPath === undefined\n ? undefined\n : ({ module_or_path: opts.wasmModuleOrPath } as never),\n );\n // Same Safari mitigation as the worker (`wasm-memory.ts`): grow from JS\n // once so the module never executes `memory.grow` itself. Idempotent.\n reserveLinearMemory(out.memory);\n\n // Label is unused on the read-only path (no LocalDevice is ever minted).\n const client =\n await wasm.PingClient.openReadOnlyFromDeviceRecord(\n \"notification-preview\",\n storage as never,\n silentTransport() as never,\n now(),\n );\n\n let closed = false;\n return {\n async previewEnvelope(envelope: MessageEnvelope): Promise<IncomingMessage | null> {\n if (closed) throw new Error(\"notification-preview session is closed\");\n const result = client.previewEnvelope(envelope as never, now());\n return (result ?? null) as IncomingMessage | null;\n },\n async previewEnvelopeWithPrerequisites(\n prerequisites: MessageEnvelope[],\n envelope: MessageEnvelope,\n ): Promise<IncomingMessage | null> {\n if (closed) throw new Error(\"notification-preview session is closed\");\n assertPrerequisiteCount(prerequisites);\n const result = client.previewEnvelopeWithPrerequisites(\n prerequisites as never,\n envelope as never,\n now(),\n );\n return (result ?? null) as IncomingMessage | null;\n },\n close() {\n if (closed) return;\n closed = true;\n client.free();\n },\n };\n}\n\n/**\n * Refuse an oversized prerequisite list before it crosses into WASM. The core\n * enforces the same bound; checking here keeps the copy out of linear memory.\n * Exported for tests.\n */\nexport function assertPrerequisiteCount(prerequisites: readonly unknown[]): void {\n if (!Array.isArray(prerequisites)) {\n throw new Error(\"notification-preview prerequisites must be an array\");\n }\n if (prerequisites.length > MAX_PREVIEW_PREREQUISITES) {\n throw new Error(\n `notification-preview takes at most ${MAX_PREVIEW_PREREQUISITES} prerequisite envelopes`,\n );\n }\n}\n\n/**\n * The per-account scope rule, shared with `MessagingClient` so the preview and\n * the tab's writer always read the same slot. Re-exported for tests.\n */\nexport { scopeStorage };\n\n/**\n * Wrap a host `Storage` so writes REJECT. The Rust side already opens the MLS\n * snapshot through a read-only backend; this guards the host-KV half\n * (`device`, `groups`, `cursors`, …), which the read-only MLS backend cannot\n * see. Defense in depth against a host bug making the Service Worker a second\n * writer. Exported for tests.\n */\nexport function readOnlyStorage(storage: Storage): Storage {\n const refuse = (op: string): Promise<never> =>\n Promise.reject(\n new Error(`notification-preview storage is read-only (attempted ${op})`),\n );\n const readOnly: Storage = {\n get: (ns, key) => storage.get(ns, key),\n put: (_ns, _key, _value) => refuse(\"put\"),\n del: (_ns, _key) => refuse(\"del\"),\n listKeys: (ns, prefix) => storage.listKeys(ns, prefix),\n };\n // `listEntries` is a read, so the read-only open keeps its one-call path.\n // `applyBatch` is a write and is deliberately absent: the wasm only uses\n // the methods it finds, and the read-only backend never batches.\n const hostListEntries = storage.listEntries;\n if (typeof hostListEntries === \"function\") {\n readOnly.listEntries = (ns, prefix) => hostListEntries.call(storage, ns, prefix);\n }\n return readOnly;\n}\n\n/**\n * A transport that can never be used: the preview client never sends, never\n * fetches, never discovers. `send` rejects loudly so a wiring mistake is\n * caught instead of silently networking from a push handler.\n */\nfunction silentTransport(): {\n send(envelope: unknown): Promise<never>;\n fetchSince(conv: unknown, cursor: unknown, limit: number): Promise<unknown[]>;\n discoverDevices(userId: unknown): Promise<unknown[]>;\n setNextWelcomeRecipients(conv: unknown, recipients: unknown): Promise<void>;\n} {\n return {\n send: () => Promise.reject(new Error(\"notification-preview cannot send\")),\n fetchSince: () => Promise.resolve([]),\n discoverDevices: () => Promise.resolve([]),\n setNextWelcomeRecipients: () => Promise.resolve(),\n };\n}\n"],"mappings":";AAwBO,SAAS,aAAa,SAAkB,kBAAmC;AAChF,QAAM,QAAQ,CAAC,OAAuB,GAAG,gBAAgB,IAAI,EAAE;AAC/D,QAAM,SAAkB;AAAA,IACtB,KAAK,CAAC,IAAI,QAAQ,QAAQ,IAAI,MAAM,EAAE,GAAG,GAAG;AAAA,IAC5C,KAAK,CAAC,IAAI,KAAK,UAAU,QAAQ,IAAI,MAAM,EAAE,GAAG,KAAK,KAAK;AAAA,IAC1D,KAAK,CAAC,IAAI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oB,YAAY;AACzC,aAAS,cAAc,CAAC,IAAI,WAAW,gBAAgB,KAAK,SAAS,IAAI,MAAM;AAAA,EACjF;AACA,SAAO;AACT;AAOA,SAAS,kBAKP;AACA,SAAO;AAAA,IACL,MAAM,MAAM,QAAQ,OAAO,IAAI,MAAM,kCAAkC,CAAC;AAAA,IACxE,YAAY,MAAM,QAAQ,QAAQ,CAAC,CAAC;AAAA,IACpC,iBAAiB,MAAM,QAAQ,QAAQ,CAAC,CAAC;AAAA,IACzC,0BAA0B,MAAM,QAAQ,QAAQ;AAAA,EAClD;AACF;","names":[]}
@@ -26,6 +26,7 @@ module.exports = __toCommonJS(indexeddb_exports);
26
26
  var DB_NAME = "ping-sdk";
27
27
  var DB_VERSION = 1;
28
28
  var STORE = "kv";
29
+ var DURABLE = { durability: "strict" };
29
30
  function open() {
30
31
  return new Promise((resolve, reject) => {
31
32
  const req = indexedDB.open(DB_NAME, DB_VERSION);
@@ -57,7 +58,7 @@ var IndexedDbStorage = class {
57
58
  async put(namespace, key, value) {
58
59
  const db = await this.dbPromise;
59
60
  return new Promise((resolve, reject) => {
60
- const tx = db.transaction(STORE, "readwrite");
61
+ const tx = db.transaction(STORE, "readwrite", DURABLE);
61
62
  tx.objectStore(STORE).put({ ns: namespace, key, value });
62
63
  tx.oncomplete = () => resolve();
63
64
  tx.onerror = () => reject(tx.error);
@@ -66,7 +67,7 @@ var IndexedDbStorage = class {
66
67
  async del(namespace, key) {
67
68
  const db = await this.dbPromise;
68
69
  return new Promise((resolve, reject) => {
69
- const tx = db.transaction(STORE, "readwrite");
70
+ const tx = db.transaction(STORE, "readwrite", DURABLE);
70
71
  tx.objectStore(STORE).delete([namespace, key]);
71
72
  tx.oncomplete = () => resolve();
72
73
  tx.onerror = () => reject(tx.error);
@@ -82,7 +83,7 @@ var IndexedDbStorage = class {
82
83
  if (puts.length === 0 && deletes.length === 0) return;
83
84
  const db = await this.dbPromise;
84
85
  return new Promise((resolve, reject) => {
85
- const tx = db.transaction(STORE, "readwrite");
86
+ const tx = db.transaction(STORE, "readwrite", DURABLE);
86
87
  let settled = false;
87
88
  const fail = (e) => {
88
89
  if (settled) return;
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/storage/indexeddb.ts"],"sourcesContent":["// Default IndexedDB-backed Storage implementation. Hosts can supply their own.\n\nimport type { Storage } from \"../types\";\n\nconst DB_NAME = \"ping-sdk\";\nconst DB_VERSION = 1;\nconst STORE = \"kv\";\n\ninterface Row { ns: string; key: string; value: Uint8Array }\n\nfunction open(): Promise<IDBDatabase> {\n return new Promise((resolve, reject) => {\n const req = indexedDB.open(DB_NAME, DB_VERSION);\n req.onupgradeneeded = () => {\n const db = req.result;\n if (!db.objectStoreNames.contains(STORE)) {\n const os = db.createObjectStore(STORE, { keyPath: [\"ns\", \"key\"] });\n os.createIndex(\"ns\", \"ns\", { unique: false });\n }\n };\n req.onsuccess = () => resolve(req.result);\n req.onerror = () => reject(req.error);\n });\n}\n\nexport class IndexedDbStorage implements Storage {\n private dbPromise: Promise<IDBDatabase>;\n\n constructor() { this.dbPromise = open(); }\n\n async get(namespace: string, key: string): Promise<Uint8Array | null> {\n const db = await this.dbPromise;\n return new Promise((resolve, reject) => {\n const tx = db.transaction(STORE, \"readonly\");\n const r = tx.objectStore(STORE).get([namespace, key]);\n r.onsuccess = () => resolve(((r.result as Row | undefined)?.value) ?? null);\n r.onerror = () => reject(r.error);\n });\n }\n\n async put(namespace: string, key: string, value: Uint8Array): Promise<void> {\n const db = await this.dbPromise;\n return new Promise((resolve, reject) => {\n const tx = db.transaction(STORE, \"readwrite\");\n tx.objectStore(STORE).put({ ns: namespace, key, value } as Row);\n tx.oncomplete = () => resolve();\n tx.onerror = () => reject(tx.error);\n });\n }\n\n async del(namespace: string, key: string): Promise<void> {\n const db = await this.dbPromise;\n return new Promise((resolve, reject) => {\n const tx = db.transaction(STORE, \"readwrite\");\n tx.objectStore(STORE).delete([namespace, key]);\n tx.oncomplete = () => resolve();\n tx.onerror = () => reject(tx.error);\n });\n }\n\n /**\n * One `readwrite` transaction for the whole batch. Every request is issued\n * synchronously inside it (an await on anything else would let the\n * transaction auto-commit), so a failure or a crash mid-way aborts all of\n * it: the per-row MLS store relies on that to keep a checkpoint atomic.\n */\n async applyBatch(\n namespace: string,\n puts: Array<[key: string, value: Uint8Array]>,\n deletes: string[],\n ): Promise<void> {\n if (puts.length === 0 && deletes.length === 0) return;\n const db = await this.dbPromise;\n return new Promise((resolve, reject) => {\n const tx = db.transaction(STORE, \"readwrite\");\n let settled = false;\n const fail = (e: unknown) => {\n if (settled) return;\n settled = true;\n reject(e instanceof Error ? e : new Error(String(e)));\n };\n tx.oncomplete = () => {\n if (!settled) {\n settled = true;\n resolve();\n }\n };\n tx.onerror = () => fail(tx.error);\n tx.onabort = () => fail(tx.error ?? new Error(\"applyBatch aborted\"));\n try {\n const os = tx.objectStore(STORE);\n for (const [key, value] of puts) os.put({ ns: namespace, key, value } as Row);\n for (const key of deletes) os.delete([namespace, key]);\n } catch (e) {\n // A request that throws synchronously (an unserialisable key) does\n // not abort the transaction on its own; the requests already issued\n // would commit. Abort explicitly so the batch stays all-or-nothing.\n try {\n tx.abort();\n } catch {\n // Already aborted or finished.\n }\n fail(e);\n }\n });\n }\n\n /** Every `[key, value]` under `namespace` with the prefix, in one read. */\n async listEntries(\n namespace: string,\n prefix: string,\n ): Promise<Array<[key: string, value: Uint8Array]>> {\n const db = await this.dbPromise;\n return new Promise((resolve, reject) => {\n const tx = db.transaction(STORE, \"readonly\");\n const idx = tx.objectStore(STORE).index(\"ns\");\n const req = idx.openCursor(IDBKeyRange.only(namespace));\n const out: Array<[string, Uint8Array]> = [];\n req.onsuccess = () => {\n const cur = req.result;\n if (!cur) return resolve(out);\n const row = cur.value as Row;\n if (!prefix || row.key.startsWith(prefix)) out.push([row.key, row.value]);\n cur.continue();\n };\n req.onerror = () => reject(req.error);\n });\n }\n\n async listKeys(namespace: string, prefix: string): Promise<string[]> {\n const db = await this.dbPromise;\n return new Promise((resolve, reject) => {\n const tx = db.transaction(STORE, \"readonly\");\n const idx = tx.objectStore(STORE).index(\"ns\");\n const req = idx.openCursor(IDBKeyRange.only(namespace));\n const out: string[] = [];\n req.onsuccess = () => {\n const cur = req.result;\n if (!cur) return resolve(out);\n const row = cur.value as Row;\n if (!prefix || row.key.startsWith(prefix)) out.push(row.key);\n cur.continue();\n };\n req.onerror = () => reject(req.error);\n });\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAIA,IAAM,UAAU;AAChB,IAAM,aAAa;AACnB,IAAM,QAAQ;AAId,SAAS,OAA6B;AACpC,SAAO,IAAI,QAAQ,CAAC,SAAS,WAAW;AACtC,UAAM,MAAM,UAAU,KAAK,SAAS,UAAU;AAC9C,QAAI,kBAAkB,MAAM;AAC1B,YAAM,KAAK,IAAI;AACf,UAAI,CAAC,GAAG,iBAAiB,SAAS,KAAK,GAAG;AACxC,cAAM,KAAK,GAAG,kBAAkB,OAAO,EAAE,SAAS,CAAC,MAAM,KAAK,EAAE,CAAC;AACjE,WAAG,YAAY,MAAM,MAAM,EAAE,QAAQ,MAAM,CAAC;AAAA,MAC9C;AAAA,IACF;AACA,QAAI,YAAY,MAAM,QAAQ,IAAI,MAAM;AACxC,QAAI,UAAU,MAAM,OAAO,IAAI,KAAK;AAAA,EACtC,CAAC;AACH;AAEO,IAAM,mBAAN,MAA0C;AAAA,EACvC;AAAA,EAER,cAAc;AAAE,SAAK,YAAY,KAAK;AAAA,EAAG;AAAA,EAEzC,MAAM,IAAI,WAAmB,KAAyC;AACpE,UAAM,KAAK,MAAM,KAAK;AACtB,WAAO,IAAI,QAAQ,CAAC,SAAS,WAAW;AACtC,YAAM,KAAK,GAAG,YAAY,OAAO,UAAU;AAC3C,YAAM,IAAI,GAAG,YAAY,KAAK,EAAE,IAAI,CAAC,WAAW,GAAG,CAAC;AACpD,QAAE,YAAY,MAAM,QAAU,EAAE,QAA4B,SAAU,IAAI;A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YAAY,KAAK,EAAE,MAAM,IAAI;AAC5C,YAAM,MAAM,IAAI,WAAW,YAAY,KAAK,SAAS,CAAC;AACtD,YAAM,MAAgB,CAAC;AACvB,UAAI,YAAY,MAAM;AACpB,cAAM,MAAM,IAAI;AAChB,YAAI,CAAC,IAAK,QAAO,QAAQ,GAAG;AAC5B,cAAM,MAAM,IAAI;AAChB,YAAI,CAAC,UAAU,IAAI,IAAI,WAAW,MAAM,EAAG,KAAI,KAAK,IAAI,GAAG;AAC3D,YAAI,SAAS;AAAA,MACf;AACA,UAAI,UAAU,MAAM,OAAO,IAAI,KAAK;AAAA,IACtC,CAAC;AAAA,EACH;AACF;","names":[]}
1
+ {"version":3,"sources":["../../src/storage/indexeddb.ts"],"sourcesContent":["// Default IndexedDB-backed Storage implementation. Hosts can supply their own.\n\nimport type { Storage } from \"../types\";\n\nconst DB_NAME = \"ping-sdk\";\nconst DB_VERSION = 1;\nconst STORE = \"kv\";\n\ninterface Row { ns: string; key: string; value: Uint8Array }\n\n/**\n * Every write transaction asks for STRICT durability: `oncomplete` fires only\n * after the data was flushed to the device, so a write this store reported\n * done also survives an operating-system crash or a power loss. The default\n * of the browsers is weaker (Chromium has used `relaxed` since version 121:\n * `oncomplete` can fire before the flush, which survives a tab or browser\n * crash only). The SDK releases a sealed message only after the write of its\n * ratchet step and of its send counter completed; with a relaxed write a\n * power loss could roll both back after the message left, and the next\n * message would be sealed under a key that was used before. Reads are not\n * affected. A browser that does not know the option ignores it and keeps its\n * default.\n */\nconst DURABLE: IDBTransactionOptions = { durability: \"strict\" };\n\nfunction open(): Promise<IDBDatabase> {\n return new Promise((resolve, reject) => {\n const req = indexedDB.open(DB_NAME, DB_VERSION);\n req.onupgradeneeded = () => {\n const db = req.result;\n if (!db.objectStoreNames.contains(STORE)) {\n const os = db.createObjectStore(STORE, { keyPath: [\"ns\", \"key\"] });\n os.createIndex(\"ns\", \"ns\", { unique: false });\n }\n };\n req.onsuccess = () => resolve(req.result);\n req.onerror = () => reject(req.error);\n });\n}\n\nexport class IndexedDbStorage implements Storage {\n private dbPromise: Promise<IDBDatabase>;\n\n constructor() { this.dbPromise = open(); }\n\n async get(namespace: string, key: string): Promise<Uint8Array | null> {\n const db = await this.dbPromise;\n return new Promise((resolve, reject) => {\n const tx = db.transaction(STORE, \"readonly\");\n const r = tx.objectStore(STORE).get([namespace, key]);\n r.onsuccess = () => resolve(((r.result as Row | undefined)?.value) ?? null);\n r.onerror = () => reject(r.error);\n });\n }\n\n async put(namespace: string, key: string, value: Uint8Array): Promise<void> {\n const db = await this.dbPromise;\n return new Promise((resolve, reject) => {\n const tx = db.transaction(STORE, \"readwrite\", DURABLE);\n tx.objectStore(STORE).put({ ns: namespace, key, value } as Row);\n tx.oncomplete = () => resolve();\n tx.onerror = () => reject(tx.error);\n });\n }\n\n async del(namespace: string, key: string): Promise<void> {\n const db = await this.dbPromise;\n return new Promise((resolve, reject) => {\n const tx = db.transaction(STORE, \"readwrite\", DURABLE);\n tx.objectStore(STORE).delete([namespace, key]);\n tx.oncomplete = () => resolve();\n tx.onerror = () => reject(tx.error);\n });\n }\n\n /**\n * One `readwrite` transaction for the whole batch. Every request is issued\n * synchronously inside it (an await on anything else would let the\n * transaction auto-commit), so a failure or a crash mid-way aborts all of\n * it: the per-row MLS store relies on that to keep a checkpoint atomic.\n */\n async applyBatch(\n namespace: string,\n puts: Array<[key: string, value: Uint8Array]>,\n deletes: string[],\n ): Promise<void> {\n if (puts.length === 0 && deletes.length === 0) return;\n const db = await this.dbPromise;\n return new Promise((resolve, reject) => {\n const tx = db.transaction(STORE, \"readwrite\", DURABLE);\n let settled = false;\n const fail = (e: unknown) => {\n if (settled) return;\n settled = true;\n reject(e instanceof Error ? e : new Error(String(e)));\n };\n tx.oncomplete = () => {\n if (!settled) {\n settled = true;\n resolve();\n }\n };\n tx.onerror = () => fail(tx.error);\n tx.onabort = () => fail(tx.error ?? new Error(\"applyBatch aborted\"));\n try {\n const os = tx.objectStore(STORE);\n for (const [key, value] of puts) os.put({ ns: namespace, key, value } as Row);\n for (const key of deletes) os.delete([namespace, key]);\n } catch (e) {\n // A request that throws synchronously (an unserialisable key) does\n // not abort the transaction on its own; the requests already issued\n // would commit. Abort explicitly so the batch stays all-or-nothing.\n try {\n tx.abort();\n } catch {\n // Already aborted or finished.\n }\n fail(e);\n }\n });\n }\n\n /** Every `[key, value]` under `namespace` with the prefix, in one read. */\n async listEntries(\n namespace: string,\n prefix: string,\n ): Promise<Array<[key: string, value: Uint8Array]>> {\n const db = await this.dbPromise;\n return new Promise((resolve, reject) => {\n const tx = db.transaction(STORE, \"readonly\");\n const idx = tx.objectStore(STORE).index(\"ns\");\n const req = idx.openCursor(IDBKeyRange.only(namespace));\n const out: Array<[string, Uint8Array]> = [];\n req.onsuccess = () => {\n const cur = req.result;\n if (!cur) return resolve(out);\n const row = cur.value as Row;\n if (!prefix || row.key.startsWith(prefix)) out.push([row.key, row.value]);\n cur.continue();\n };\n req.onerror = () => reject(req.error);\n });\n }\n\n async listKeys(namespace: string, prefix: string): Promise<string[]> {\n const db = await this.dbPromise;\n return new Promise((resolve, reject) => {\n const tx = db.transaction(STORE, \"readonly\");\n const idx = tx.objectStore(STORE).index(\"ns\");\n const req = idx.openCursor(IDBKeyRange.only(namespace));\n const out: string[] = [];\n req.onsuccess = () => {\n const cur = req.result;\n if (!cur) return resolve(out);\n const row = cur.value as Row;\n if (!prefix || row.key.startsWith(prefix)) out.push(row.key);\n cur.continue();\n };\n req.onerror = () => reject(req.error);\n });\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAIA,IAAM,UAAU;AAChB,IAAM,aAAa;AACnB,IAAM,QAAQ;AAiBd,IAAM,UAAiC,EAAE,YAAY,SAAS;AAE9D,SAAS,OAA6B;AACpC,SAAO,IAAI,QAAQ,CAAC,SAAS,WAAW;AACtC,UAAM,MAAM,UAAU,KAAK,SAAS,UAAU;AAC9C,QAAI,kBAAkB,MAAM;A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tq.cjs';
2
2
 
3
3
  declare class IndexedDbStorage implements Storage {
4
4
  private dbPromise;
@@ -1,4 +1,4 @@
1
- import { S as Storage } from '../types-gAmJFSC-.js';
1
+ import { S as Storage } from '../types-omhvRjtq.js';
2
2
 
3
3
  declare class IndexedDbStorage implements Storage {
4
4
  private dbPromise;
@@ -2,6 +2,7 @@
2
2
  var DB_NAME = "ping-sdk";
3
3
  var DB_VERSION = 1;
4
4
  var STORE = "kv";
5
+ var DURABLE = { durability: "strict" };
5
6
  function open() {
6
7
  return new Promise((resolve, reject) => {
7
8
  const req = indexedDB.open(DB_NAME, DB_VERSION);
@@ -33,7 +34,7 @@ var IndexedDbStorage = class {
33
34
  async put(namespace, key, value) {
34
35
  const db = await this.dbPromise;
35
36
  return new Promise((resolve, reject) => {
36
- const tx = db.transaction(STORE, "readwrite");
37
+ const tx = db.transaction(STORE, "readwrite", DURABLE);
37
38
  tx.objectStore(STORE).put({ ns: namespace, key, value });
38
39
  tx.oncomplete = () => resolve();
39
40
  tx.onerror = () => reject(tx.error);
@@ -42,7 +43,7 @@ var IndexedDbStorage = class {
42
43
  async del(namespace, key) {
43
44
  const db = await this.dbPromise;
44
45
  return new Promise((resolve, reject) => {
45
- const tx = db.transaction(STORE, "readwrite");
46
+ const tx = db.transaction(STORE, "readwrite", DURABLE);
46
47
  tx.objectStore(STORE).delete([namespace, key]);
47
48
  tx.oncomplete = () => resolve();
48
49
  tx.onerror = () => reject(tx.error);
@@ -58,7 +59,7 @@ var IndexedDbStorage = class {
58
59
  if (puts.length === 0 && deletes.length === 0) return;
59
60
  const db = await this.dbPromise;
60
61
  return new Promise((resolve, reject) => {
61
- const tx = db.transaction(STORE, "readwrite");
62
+ const tx = db.transaction(STORE, "readwrite", DURABLE);
62
63
  let settled = false;
63
64
  const fail = (e) => {
64
65
  if (settled) return;
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/storage/indexeddb.ts"],"sourcesContent":["// Default IndexedDB-backed Storage implementation. Hosts can supply their own.\n\nimport type { Storage } from \"../types\";\n\nconst DB_NAME = \"ping-sdk\";\nconst DB_VERSION = 1;\nconst STORE = \"kv\";\n\ninterface Row { ns: string; key: string; value: Uint8Array }\n\nfunction open(): Promise<IDBDatabase> {\n return new Promise((resolve, reject) => {\n const req = indexedDB.open(DB_NAME, DB_VERSION);\n req.onupgradeneeded = () => {\n const db = req.result;\n if (!db.objectStoreNames.contains(STORE)) {\n const os = db.createObjectStore(STORE, { keyPath: [\"ns\", \"key\"] });\n os.createIndex(\"ns\", \"ns\", { unique: false });\n }\n };\n req.onsuccess = () => resolve(req.result);\n req.onerror = () => reject(req.error);\n });\n}\n\nexport class IndexedDbStorage implements Storage {\n private dbPromise: Promise<IDBDatabase>;\n\n constructor() { this.dbPromise = open(); }\n\n async get(namespace: string, key: string): Promise<Uint8Array | null> {\n const db = await this.dbPromise;\n return new Promise((resolve, reject) => {\n const tx = db.transaction(STORE, \"readonly\");\n const r = tx.objectStore(STORE).get([namespace, key]);\n r.onsuccess = () => resolve(((r.result as Row | undefined)?.value) ?? null);\n r.onerror = () => reject(r.error);\n });\n }\n\n async put(namespace: string, key: string, value: Uint8Array): Promise<void> {\n const db = await this.dbPromise;\n return new Promise((resolve, reject) => {\n const tx = db.transaction(STORE, \"readwrite\");\n tx.objectStore(STORE).put({ ns: namespace, key, value } as Row);\n tx.oncomplete = () => resolve();\n tx.onerror = () => reject(tx.error);\n });\n }\n\n async del(namespace: string, key: string): Promise<void> {\n const db = await this.dbPromise;\n return new Promise((resolve, reject) => {\n const tx = db.transaction(STORE, \"readwrite\");\n tx.objectStore(STORE).delete([namespace, key]);\n tx.oncomplete = () => resolve();\n tx.onerror = () => reject(tx.error);\n });\n }\n\n /**\n * One `readwrite` transaction for the whole batch. Every request is issued\n * synchronously inside it (an await on anything else would let the\n * transaction auto-commit), so a failure or a crash mid-way aborts all of\n * it: the per-row MLS store relies on that to keep a checkpoint atomic.\n */\n async applyBatch(\n namespace: string,\n puts: Array<[key: string, value: Uint8Array]>,\n deletes: string[],\n ): Promise<void> {\n if (puts.length === 0 && deletes.length === 0) return;\n const db = await this.dbPromise;\n return new Promise((resolve, reject) => {\n const tx = db.transaction(STORE, \"readwrite\");\n let settled = false;\n const fail = (e: unknown) => {\n if (settled) return;\n settled = true;\n reject(e instanceof Error ? e : new Error(String(e)));\n };\n tx.oncomplete = () => {\n if (!settled) {\n settled = true;\n resolve();\n }\n };\n tx.onerror = () => fail(tx.error);\n tx.onabort = () => fail(tx.error ?? new Error(\"applyBatch aborted\"));\n try {\n const os = tx.objectStore(STORE);\n for (const [key, value] of puts) os.put({ ns: namespace, key, value } as Row);\n for (const key of deletes) os.delete([namespace, key]);\n } catch (e) {\n // A request that throws synchronously (an unserialisable key) does\n // not abort the transaction on its own; the requests already issued\n // would commit. Abort explicitly so the batch stays all-or-nothing.\n try {\n tx.abort();\n } catch {\n // Already aborted or finished.\n }\n fail(e);\n }\n });\n }\n\n /** Every `[key, value]` under `namespace` with the prefix, in one read. */\n async listEntries(\n namespace: string,\n prefix: string,\n ): Promise<Array<[key: string, value: Uint8Array]>> {\n const db = await this.dbPromise;\n return new Promise((resolve, reject) => {\n const tx = db.transaction(STORE, \"readonly\");\n const idx = tx.objectStore(STORE).index(\"ns\");\n const req = idx.openCursor(IDBKeyRange.only(namespace));\n const out: Array<[string, Uint8Array]> = [];\n req.onsuccess = () => {\n const cur = req.result;\n if (!cur) return resolve(out);\n const row = cur.value as Row;\n if (!prefix || row.key.startsWith(prefix)) out.push([row.key, row.value]);\n cur.continue();\n };\n req.onerror = () => reject(req.error);\n });\n }\n\n async listKeys(namespace: string, prefix: string): Promise<string[]> {\n const db = await this.dbPromise;\n return new Promise((resolve, reject) => {\n const tx = db.transaction(STORE, \"readonly\");\n const idx = tx.objectStore(STORE).index(\"ns\");\n const req = idx.openCursor(IDBKeyRange.only(namespace));\n const out: string[] = [];\n req.onsuccess = () => {\n const cur = req.result;\n if (!cur) return resolve(out);\n const row = cur.value as Row;\n if (!prefix || row.key.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U,IAAI,IAAI,WAAW,MAAM,EAAG,KAAI,KAAK,IAAI,GAAG;AAC3D,YAAI,SAAS;AAAA,MACf;AACA,UAAI,UAAU,MAAM,OAAO,IAAI,KAAK;AAAA,IACtC,CAAC;AAAA,EACH;AACF;","names":[]}
1
+ {"version":3,"sources":["../../src/storage/indexeddb.ts"],"sourcesContent":["// Default IndexedDB-backed Storage implementation. Hosts can supply their own.\n\nimport type { Storage } from \"../types\";\n\nconst DB_NAME = \"ping-sdk\";\nconst DB_VERSION = 1;\nconst STORE = \"kv\";\n\ninterface Row { ns: string; key: string; value: Uint8Array }\n\n/**\n * Every write transaction asks for STRICT durability: `oncomplete` fires only\n * after the data was flushed to the device, so a write this store reported\n * done also survives an operating-system crash or a power loss. The default\n * of the browsers is weaker (Chromium has used `relaxed` since version 121:\n * `oncomplete` can fire before the flush, which survives a tab or browser\n * crash only). The SDK releases a sealed message only after the write of its\n * ratchet step and of its send counter completed; with a relaxed write a\n * power loss could roll both back after the message left, and the next\n * message would be sealed under a key that was used before. Reads are not\n * affected. A browser that does not know the option ignores it and keeps its\n * default.\n */\nconst DURABLE: IDBTransactionOptions = { durability: \"strict\" };\n\nfunction open(): Promise<IDBDatabase> {\n return new Promise((resolve, reject) => {\n const req = indexedDB.open(DB_NAME, DB_VERSION);\n req.onupgradeneeded = () => {\n const db = req.result;\n if (!db.objectStoreNames.contains(STORE)) {\n const os = db.createObjectStore(STORE, { keyPath: [\"ns\", \"key\"] });\n os.createIndex(\"ns\", \"ns\", { unique: false });\n }\n };\n req.onsuccess = () => resolve(req.result);\n req.onerror = () => reject(req.error);\n });\n}\n\nexport class IndexedDbStorage implements Storage {\n private dbPromise: Promise<IDBDatabase>;\n\n constructor() { this.dbPromise = open(); }\n\n async get(namespace: string, key: string): Promise<Uint8Array | null> {\n const db = await this.dbPromise;\n return new Promise((resolve, reject) => {\n const tx = db.transaction(STORE, \"readonly\");\n const r = tx.objectStore(STORE).get([namespace, key]);\n r.onsuccess = () => resolve(((r.result as Row | undefined)?.value) ?? null);\n r.onerror = () => reject(r.error);\n });\n }\n\n async put(namespace: string, key: string, value: Uint8Array): Promise<void> {\n const db = await this.dbPromise;\n return new Promise((resolve, reject) => {\n const tx = db.transaction(STORE, \"readwrite\", DURABLE);\n tx.objectStore(STORE).put({ ns: namespace, key, value } as Row);\n tx.oncomplete = () => resolve();\n tx.onerror = () => reject(tx.error);\n });\n }\n\n async del(namespace: string, key: string): Promise<void> {\n const db = await this.dbPromise;\n return new Promise((resolve, reject) => {\n const tx = db.transaction(STORE, \"readwrite\", DURABLE);\n tx.objectStore(STORE).delete([namespace, key]);\n tx.oncomplete = () => resolve();\n tx.onerror = () => reject(tx.error);\n });\n }\n\n /**\n * One `readwrite` transaction for the whole batch. Every request is issued\n * synchronously inside it (an await on anything else would let the\n * transaction auto-commit), so a failure or a crash mid-way aborts all of\n * it: the per-row MLS store relies on that to keep a checkpoint atomic.\n */\n async applyBatch(\n namespace: string,\n puts: Array<[key: string, value: Uint8Array]>,\n deletes: string[],\n ): Promise<void> {\n if (puts.length === 0 && deletes.length === 0) return;\n const db = await this.dbPromise;\n return new Promise((resolve, reject) => {\n const tx = db.transaction(STORE, \"readwrite\", DURABLE);\n let settled = false;\n const fail = (e: unknown) => {\n if (settled) return;\n settled = true;\n reject(e instanceof Error ? e : new Error(String(e)));\n };\n tx.oncomplete = () => {\n if (!settled) {\n settled = true;\n resolve();\n }\n };\n tx.onerror = () => fail(tx.error);\n tx.onabort = () => fail(tx.error ?? new Error(\"applyBatch aborted\"));\n try {\n const os = tx.objectStore(STORE);\n for (const [key, value] of puts) os.put({ ns: namespace, key, value } as Row);\n for (const key of deletes) os.delete([namespace, key]);\n } catch (e) {\n // A request that throws synchronously (an unserialisable key) does\n // not abort the transaction on its own; the requests already issued\n // would commit. Abort explicitly so the batch stays all-or-nothing.\n try {\n tx.abort();\n } catch {\n // Already aborted or finished.\n }\n fail(e);\n }\n });\n }\n\n /** Every `[key, value]` under `namespace` with the prefix, in one read. */\n async listEntries(\n namespace: string,\n prefix: string,\n ): Promise<Array<[key: string, value: Uint8Array]>> {\n const db = await this.dbPromise;\n return new Promise((resolve, reject) => {\n const tx = db.transaction(STORE, \"readonly\");\n const idx = tx.objectStore(STORE).index(\"ns\");\n const req = idx.openCursor(IDBKeyRange.only(namespace));\n const out: Array<[string, Uint8Array]> = [];\n req.onsuccess = () => {\n const cur = req.result;\n if (!cur) return resolve(out);\n const row = cur.value as Row;\n if (!prefix || row.key.startsWith(prefix)) out.push([row.key, row.value]);\n cur.continue();\n };\n req.onerror = () => reject(req.error);\n });\n }\n\n async listKeys(namespace: string, prefix: string): Promise<string[]> {\n const db = await this.dbPromise;\n return new Promise((resolve, reject) => {\n const tx = db.transaction(STORE, \"readonly\");\n const idx = tx.objectStore(STORE).index(\"ns\");\n const req = idx.openCursor(IDBKeyRange.only(namespace));\n const out: string[] = [];\n req.onsuccess = () => {\n const cur = req.result;\n if (!cur) return resolve(out);\n const row = cur.value as Row;\n if (!prefix || row.key.startsWith(prefix)) out.push(row.key);\n cur.continue();\n };\n req.onerror = () => reject(req.error);\n });\n }\n}\n"],"mappings":";AAIA,IAAM,UAAU;AAChB,IAAM,aAAa;AACnB,IAAM,QAAQ;AAiBd,IAAM,UAAiC,EAAE,YAAY,SAAS;AAE9D,SAAS,OAA6B;AACpC,SAAO,IAAI,QAAQ,CAAC,SAAS,WAAW;AACtC,UAAM,MAAM,UAAU,KAAK,SAAS,UAAU;AAC9C,QAAI,kBAAkB,MAAM;AAC1B,YAAM,KAAK,IAAI;AACf,UAAI,CAAC,GAAG,iBAAiB,SAAS,KAAK,GAAG;AACxC,cAAM,KAAK,GAAG,kBAAkB,OAAO,EAAE,SAAS,CAAC,MAAM,KAAK,EAAE,CAAC;AACjE,WAAG,YAAY,MAAM,MAAM,EAAE,QAAQ,MAAM,CAAC;AAAA,MAC9C;AAAA,IACF;AACA,QAAI,YAAY,MAAM,QAAQ,IAAI,MAAM;AACxC,QAAI,UAAU,MAAM,OA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AAK,QAAO,QAAQ,GAAG;AAC5B,cAAM,MAAM,IAAI;AAChB,YAAI,CAAC,UAAU,IAAI,IAAI,WAAW,MAAM,EAAG,KAAI,KAAK,CAAC,IAAI,KAAK,IAAI,KAAK,CAAC;AACxE,YAAI,SAAS;AAAA,MACf;AACA,UAAI,UAAU,MAAM,OAAO,IAAI,KAAK;AAAA,IACtC,CAAC;AAAA,EACH;AAAA,EAEA,MAAM,SAAS,WAAmB,QAAmC;AACnE,UAAM,KAAK,MAAM,KAAK;AACtB,WAAO,IAAI,QAAQ,CAAC,SAAS,WAAW;AACtC,YAAM,KAAK,GAAG,YAAY,OAAO,UAAU;AAC3C,YAAM,MAAM,GAAG,YAAY,KAAK,EAAE,MAAM,IAAI;AAC5C,YAAM,MAAM,IAAI,WAAW,YAAY,KAAK,SAAS,CAAC;AACtD,YAAM,MAAgB,CAAC;AACvB,UAAI,YAAY,MAAM;AACpB,cAAM,MAAM,IAAI;AAChB,YAAI,CAAC,IAAK,QAAO,QAAQ,GAAG;AAC5B,cAAM,MAAM,IAAI;AAChB,YAAI,CAAC,UAAU,IAAI,IAAI,WAAW,MAAM,EAAG,KAAI,KAAK,IAAI,GAAG;AAC3D,YAAI,SAAS;AAAA,MACf;AACA,UAAI,UAAU,MAAM,OAAO,IAAI,KAAK;AAAA,IACtC,CAAC;AAAA,EACH;AACF;","names":[]}
@@ -1,4 +1,4 @@
1
- import { T as Transport, M as MessageEnvelope, C as ConversationId, U as UserId, D as DiscoveredDevice } from '../types-gAmJFSC-.cjs';
1
+ import { T as Transport, M as MessageEnvelope, C as ConversationId, U as UserId, D as DiscoveredDevice } from '../types-omhvRjtq.cjs';
2
2
 
3
3
  interface WsTransportConfig {
4
4
  baseUrl: string;
@@ -1,4 +1,4 @@
1
- import { T as Transport, M as MessageEnvelope, C as ConversationId, U as UserId, D as DiscoveredDevice } from '../types-gAmJFSC-.js';
1
+ import { T as Transport, M as MessageEnvelope, C as ConversationId, U as UserId, D as DiscoveredDevice } from '../types-omhvRjtq.js';
2
2
 
3
3
  interface WsTransportConfig {
4
4
  baseUrl: string;