@ping-app/ping-openmls-sdk 0.0.0-stage → 0.9.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (39) hide show
  1. package/README.md +94 -2
  2. package/dist/index.cjs +2722 -0
  3. package/dist/index.cjs.map +1 -0
  4. package/dist/index.d.cts +1182 -0
  5. package/dist/index.d.ts +1182 -0
  6. package/dist/index.js +2655 -0
  7. package/dist/index.js.map +1 -0
  8. package/dist/notification-preview.cjs +137 -0
  9. package/dist/notification-preview.cjs.map +1 -0
  10. package/dist/notification-preview.d.cts +85 -0
  11. package/dist/notification-preview.d.ts +85 -0
  12. package/dist/notification-preview.js +98 -0
  13. package/dist/notification-preview.js.map +1 -0
  14. package/dist/storage/indexeddb.cjs +153 -0
  15. package/dist/storage/indexeddb.cjs.map +1 -0
  16. package/dist/storage/indexeddb.d.cts +21 -0
  17. package/dist/storage/indexeddb.d.ts +21 -0
  18. package/dist/storage/indexeddb.js +128 -0
  19. package/dist/storage/indexeddb.js.map +1 -0
  20. package/dist/transport/websocket.cjs +121 -0
  21. package/dist/transport/websocket.cjs.map +1 -0
  22. package/dist/transport/websocket.d.cts +23 -0
  23. package/dist/transport/websocket.d.ts +23 -0
  24. package/dist/transport/websocket.js +94 -0
  25. package/dist/transport/websocket.js.map +1 -0
  26. package/dist/types-B1GFwNXa.d.cts +535 -0
  27. package/dist/types-B1GFwNXa.d.ts +535 -0
  28. package/dist/worker.cjs +686 -0
  29. package/dist/worker.cjs.map +1 -0
  30. package/dist/worker.d.cts +2 -0
  31. package/dist/worker.d.ts +2 -0
  32. package/dist/worker.js +693 -0
  33. package/dist/worker.js.map +1 -0
  34. package/package.json +61 -4
  35. package/wasm/package.json +17 -0
  36. package/wasm/ping_wasm.d.ts +890 -0
  37. package/wasm/ping_wasm.js +2992 -0
  38. package/wasm/ping_wasm_bg.wasm +0 -0
  39. package/wasm/ping_wasm_bg.wasm.d.ts +111 -0
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/wasm-memory.ts","../src/worker.ts","../src/epoch-events.ts","../src/catch-up-pass.ts","../src/request-lanes.ts"],"sourcesContent":["// 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","// Web Worker entry. Owns the WASM `PingClient` instance. Receives Requests from the main thread\n// and posts Responses back. Storage / Transport calls back to the main thread are tracked by id.\n//\n// The WASM module is loaded lazily on the first `init` so that ephemeral identity-only spawns\n// (used by `MessagingClient.generateIdentity()`) don't pay the cost.\n\n/// <reference lib=\"webworker\" />\n\nimport { reserveLinearMemory } from \"./wasm-memory\";\nimport init, {\n PingClient,\n sealLinkingTicket as wasmSealLinkingTicket,\n openLinkingTicket as wasmOpenLinkingTicket,\n hpkeSeal as wasmHpkeSeal,\n hpkeOpen as wasmHpkeOpen,\n hpkeSealRaw as wasmHpkeSealRaw,\n hpkeOpenRaw as wasmHpkeOpenRaw,\n hpkeGenerateKeypair as wasmHpkeGenerateKeypair,\n sealLinkingTicketPq as wasmSealLinkingTicketPq,\n openLinkingTicketPq as wasmOpenLinkingTicketPq,\n hpkeSealPq as wasmHpkeSealPq,\n hpkeOpenPq as wasmHpkeOpenPq,\n hpkeSealRawPq as wasmHpkeSealRawPq,\n hpkeOpenRawPq as wasmHpkeOpenRawPq,\n hpkeGenerateKeypairPq as wasmHpkeGenerateKeypairPq,\n deviceGroupIdFor as wasmDeviceGroupIdFor,\n hpkePublicKeyFromSeed as wasmHpkePublicKeyFromSeed,\n hpkePublicKeyFromPrivate as wasmHpkePublicKeyFromPrivate,\n signDeviceReauth as wasmSignDeviceReauth,\n signDeviceLinkApproval as wasmSignDeviceLinkApproval,\n signDeviceLinkPossession as wasmSignDeviceLinkPossession,\n decodeCatchupSnapshot as wasmDecodeCatchupSnapshot,\n generateMnemonicPhrase as wasmGenerateMnemonicPhrase,\n normalizeMnemonicPhrase as wasmNormalizeMnemonicPhrase,\n encryptBackup as wasmEncryptBackup,\n decryptBackup as wasmDecryptBackup,\n sealHistoryBundle as wasmSealHistoryBundle,\n openHistoryBundle as wasmOpenHistoryBundle,\n sealHistoryBundlePq as wasmSealHistoryBundlePq,\n openHistoryBundlePq as wasmOpenHistoryBundlePq,\n} from \"../wasm/ping_wasm\";\nimport { catchUpPass } from \"./catch-up-pass\";\nimport { advancedEpochs, type ConversationEpoch, conversationKey, epochMap } from \"./epoch-events\";\nimport type { Request, Response, StorageFeatures, TransportFeatures } from \"./protocol\";\nimport { RequestScheduler } from \"./request-lanes\";\nimport type {\n ApplyBatchResultWire,\n ConversationUpdateWire,\n LogHeadWire,\n SequencedEnvelopeWire,\n SyncStepResultWire,\n} from \"./sequenced\";\nimport type { DeviceId, IncomingMessage, MessageEnvelope } from \"./types\";\n\ndeclare const self: DedicatedWorkerGlobalScope;\n\nlet client: PingClient | null = null;\nlet wasmReady: Promise<void> | null = null;\n\nconst pendingStorage = new Map<number, (r: { ok: boolean; value: unknown }) => void>();\nconst pendingTransport = new Map<number, (r: { ok: boolean; value: unknown }) => void>();\nlet nextStorageId = 1;\nlet nextTransportId = 1;\n\nconst proxyStorage = {\n get: (namespace: string, key: string) => callMain<Uint8Array | null>(\"storage\", \"get\", [namespace, key]),\n put: (namespace: string, key: string, value: Uint8Array) =>\n callMain<void>(\"storage\", \"put\", [namespace, key, value]),\n del: (namespace: string, key: string) => callMain<void>(\"storage\", \"del\", [namespace, key]),\n listKeys: (namespace: string, prefix: string) =>\n callMain<string[]>(\"storage\", \"listKeys\", [namespace, prefix]),\n};\n// The two optional methods are declared on the proxy ONLY when the host\n// storage has them: the wasm bridge decides by their presence whether to hand\n// the per-row MLS store's delta to the host as one atomic batch (and read the\n// rows in one call) or to take its own journalled row-by-row fallback.\nconst applyBatchProxy = (namespace: string, puts: Array<[string, Uint8Array]>, deletes: string[]) =>\n callMain<void>(\"storage\", \"applyBatch\", [namespace, puts, deletes]);\nconst listEntriesProxy = (namespace: string, prefix: string) =>\n callMain<Array<[string, Uint8Array]>>(\"storage\", \"listEntries\", [namespace, prefix]);\nfunction makeProxyStorage(features: StorageFeatures | undefined) {\n return {\n ...proxyStorage,\n ...(features?.applyBatch ? { applyBatch: applyBatchProxy } : {}),\n ...(features?.listEntries ? { listEntries: listEntriesProxy } : {}),\n };\n}\nconst proxyTransport = {\n send: (envelope: MessageEnvelope) => callMain<void>(\"transport\", \"send\", [envelope]),\n // Always declared here: the main-thread dispatch emulates it with\n // sequential sends when the host transport has no `sendBatch`, encoding a\n // partial delivery with the `batch partial after <n>:` sentinel the wasm\n // bridge understands (see index.ts `BATCH_PARTIAL_PREFIX`).\n sendBatch: (envelopes: MessageEnvelope[]) => callMain<void>(\"transport\", \"sendBatch\", [envelopes]),\n fetchSince: (conv: Uint8Array, cursor: Uint8Array, limit: number) =>\n callMain<MessageEnvelope[]>(\"transport\", \"fetchSince\", [conv, cursor, limit]),\n discoverDevices: (userId: Uint8Array) => callMain<unknown[]>(\"transport\", \"discoverDevices\", [userId]),\n // Optional on the host (see `Transport.setNextWelcomeRecipients` in types.ts).\n // The main-thread dispatch (index.ts `handleWorker → case \"transport.call\"`)\n // resolves `undefined` to a `transport.reply { ok: true, value: undefined }`\n // when the host hasn't implemented the method, which we treat as a no-op.\n setNextWelcomeRecipients: (conv: Uint8Array, recipients: Uint8Array[]) =>\n callMain<void>(\"transport\", \"setNextWelcomeRecipients\", [conv, recipients]),\n};\n\n/** What the host transport declared at `init`; read by the catch-up pass. */\nlet transportFeatures: TransportFeatures = { fetchLogSince: false, fetchLogHeads: false };\n\nconst fetchLogSinceProxy = (position: unknown, limit: number) =>\n callMain<SequencedEnvelopeWire[] | null>(\"transport\", \"fetchLogSince\", [position, limit]);\nconst fetchLogHeadsProxy = () =>\n callMain<LogHeadWire[] | null | undefined>(\"transport\", \"fetchLogHeads\", []);\n\n/**\n * The transport proxy the wasm sees. Unlike `setNextWelcomeRecipients`, the\n * two sequenced-log methods are NOT always declared: the wasm bridge decides\n * by their presence whether to call them or fall back to the core default\n * (`fetchSince` at position 0; no heads), and `fetchLogSince` has no\n * main-thread emulation because only the core can encode the legacy cursor.\n */\nfunction makeProxyTransport(features: TransportFeatures) {\n return {\n ...proxyTransport,\n ...(features.fetchLogSince ? { fetchLogSince: fetchLogSinceProxy } : {}),\n ...(features.fetchLogHeads ? { fetchLogHeads: fetchLogHeadsProxy } : {}),\n };\n}\n\nfunction callMain<T>(kind: \"storage\" | \"transport\", method: string, args: unknown[]): Promise<T> {\n return new Promise((resolve, reject) => {\n const id = kind === \"storage\" ? nextStorageId++ : nextTransportId++;\n const map = kind === \"storage\" ? pendingStorage : pendingTransport;\n map.set(id, ({ ok, value }) => ok ? resolve(value as T) : reject(new Error(String(value))));\n self.postMessage({ kind: `${kind}.call`, id, method, args } as Response);\n });\n}\n\nasync function ensureWasm() {\n if (wasmReady) return wasmReady;\n // The bundled wasm path is rewritten by the build script to be relative to `dist/`.\n wasmReady = init().then((out) => {\n reserveLinearMemory(out.memory);\n });\n return wasmReady;\n}\n\n// The WASM `PingClient` is SINGLE-THREADED (this one worker). Its async\n// methods hold internal locks across `.await` (e.g. a `conversations`\n// RwLock guard kept while `snapshot_to_storage` awaits IndexedDB). If we\n// let `onmessage` dispatch a SECOND top-level request while the first is\n// suspended at an await, the two WASM calls interleave on the single\n// thread, the second re-acquires a held lock, and `parking_lot`'s wasm\n// stub `panic!`s with \"Parking not supported on this platform\" — which\n// poisons the module (`RuntimeError: unreachable`) and breaks every\n// subsequent call. We therefore SERIALIZE top-level request dispatch:\n// one WASM call runs to completion before the next begins.\n//\n// ONE CALL AT A TIME IS NOT THE SAME AS FIRST COME, FIRST SERVED. A\n// whole-account `syncConversations` used to be one request: every\n// conversation paged inside a single turn, one network round trip each,\n// and a `send` posted while it ran started only after the last of them.\n// On a tab returning from an idle hour that was the whole visible cost of\n// the first message: the composer cleared, the bubble sat on a clock for\n// the length of the pass, and the second message went out at once. The\n// scheduler below keeps the one-call invariant but runs a whole-account\n// pass as a sequence of per-conversation steps (`syncConversation`) and\n// lets everything else queued run between steps. Ordinary requests stay\n// FIFO among themselves, so the inbound ordering that per-conversation\n// chaining on the main thread relies on is untouched; a host's own\n// `syncConversation` for the chat the user is looking at is an ordinary\n// request too, so it runs ahead of the background pass.\n//\n// CRUCIAL: `storage.reply` / `transport.reply` are NOT serialized — an\n// in-flight request awaits those replies (via `callMain`), so queuing\n// them behind the request would deadlock. They resolve pending callbacks\n// immediately, exactly as before.\nconst scheduler = new RequestScheduler();\n\n// Requests that can advance a conversation's MLS epoch WITHOUT an inbound\n// envelope to announce it.\n//\n// `event.conversation` was only ever emitted from `processEnvelope` and\n// `joinConversation`, so it announced exactly one of the three ways an epoch\n// moves: a Commit received from someone else. The other two were invisible to\n// every consumer:\n//\n// 1. A commit THIS device authored. `MessagingClient.dispatchIncoming` drops\n// envelopes whose `sender_device` is ours (the relay echoes our own\n// sends), so the author's own commit never reaches `processEnvelope`.\n// A host that re-derives exported secrets on epoch change — call media\n// keys are the load-bearing case — therefore kept using the PREVIOUS\n// epoch's secret after adding a member, and went silent against everyone\n// who had rotated. It is specifically the device that INVITES that breaks.\n// 2. A commit applied during catch-up. `syncConversations` fetches and\n// applies envelopes but posted nothing, so a client that reconnected after\n// missing a commit resumed on a stale secret.\n//\n// Rather than enumerate emissions per operation (and miss the next one added),\n// the epoch map is snapshotted around these requests and any conversation whose\n// epoch actually MOVED is announced. Conversations are only compared, never\n// created, so this can never invent an event: a freshly joined conversation is\n// already announced by `joinConversation`, and one that disappears (leave/drop)\n// is not an epoch change.\n//\n// `send` is deliberately absent: application messages do not advance the epoch,\n// and it is the hot path — it must not pay for two `listConversations` calls.\nconst EPOCH_ADVANCING_REQUESTS: ReadonlySet<string> = new Set([\n \"addMembers\",\n \"addMembersWithVerdicts\",\n \"reAdmitDevice\",\n \"removeMembers\",\n \"removeOwnOtherLeaves\",\n \"removeMembersByIdentity\",\n \"commitPendingProposals\",\n \"setConversationName\",\n \"setConversationRoles\",\n \"admitDeviceToChats\",\n \"admitDeviceToChatsConcurrent\",\n \"revokeDevice\",\n \"removeDeviceEverywhere\",\n \"removeOwnDevicesExcept\",\n \"syncConversations\",\n \"syncConversation\",\n \"consumeLinkingTicket\",\n \"importStateSnapshot\",\n]);\n\n/** Current epoch per conversation. Best-effort: an error yields an empty map,\n * which simply means no epoch change is reported for that request. */\nfunction epochSnapshot(): Map<string, number> {\n if (!client) return new Map();\n try {\n return epochMap(client.listConversations() as unknown as ConversationEpoch[]);\n } catch {\n // A client mid-teardown (or a storage read failure) is not a reason to fail\n // the request the caller actually made.\n return new Map();\n }\n}\n\n/** Announce every conversation whose epoch moved since `before`. */\nfunction emitEpochAdvances(before: Map<string, number>): void {\n if (!client) return;\n let metas: ConversationEpoch[];\n try {\n metas = client.listConversations() as unknown as ConversationEpoch[];\n } catch {\n return;\n }\n for (const meta of advancedEpochs(before, metas)) {\n (self.postMessage as (m: Response) => void)({\n kind: \"event.conversation\",\n id: meta.id,\n epoch: meta.epoch,\n });\n }\n}\n\n/**\n * Announce the conversations a batch or page moved. The sequenced paths\n * report `updated` exactly (the core lists every conversation whose epoch\n * moved or that was joined), so there is nothing to diff: one event per\n * entry. `senders` labels a join with the inviter's device, as\n * `joinConversation` does.\n */\nfunction announceUpdated(\n updated: ConversationUpdateWire[],\n senders: Map<string, DeviceId> = new Map(),\n): void {\n for (const u of updated) {\n const sender = senders.get(conversationKey(u.conversation_id));\n (self.postMessage as (m: Response) => void)({\n kind: \"event.conversation\",\n id: u.conversation_id,\n epoch: u.epoch,\n ...(sender !== undefined ? { sender } : {}),\n });\n }\n}\n\n/** The inviter's device for every conversation a batch joined, from the\n * Welcome that joined it. */\nfunction welcomeSenders(items: SequencedEnvelopeWire[], joined: Uint8Array[]): Map<string, DeviceId> {\n const out = new Map<string, DeviceId>();\n if (joined.length === 0) return out;\n const wanted = new Set(joined.map((id) => conversationKey(id)));\n for (const item of items) {\n if (item.envelope.kind !== \"Welcome\") continue;\n const key = conversationKey(item.envelope.conversation_id);\n if (wanted.has(key) && !out.has(key)) out.set(key, item.envelope.sender_device);\n }\n return out;\n}\n\nasync function runRequest(msg: Request): Promise<void> {\n // Snapshot BEFORE the request and diff after, so a self-authored commit or a\n // catch-up-applied one is announced like any other epoch change.\n const watchEpochs = client !== null && EPOCH_ADVANCING_REQUESTS.has(msg.kind);\n const before = watchEpochs ? epochSnapshot() : null;\n try {\n const value = await dispatch(msg);\n // Announce the epoch change BEFORE resolving the caller, so a host that\n // awaits `addMembers` and then reads a derived secret cannot observe the\n // new epoch before being told about it.\n if (before) emitEpochAdvances(before);\n (self.postMessage as (m: Response) => void)({ kind: \"result\", id: msg.id, ok: true, value });\n } catch (e) {\n // A failed request can still have advanced the epoch (a commit that merged\n // locally before a later step threw), so report the change either way.\n if (before) emitEpochAdvances(before);\n (self.postMessage as (m: Response) => void)({\n kind: \"result\", id: msg.id, ok: false, error: e instanceof Error ? e.message : String(e),\n });\n }\n}\n\nself.onmessage = (ev: MessageEvent<Request>) => {\n const msg = ev.data;\n\n // Storage / transport responses from the main thread — handle\n // immediately (they unblock the in-flight request). Never queued.\n if (msg.kind === \"storage.reply\") {\n const slot = pendingStorage.get(msg.id);\n if (slot) {\n pendingStorage.delete(msg.id);\n msg.ok ? slot({ ok: true, value: msg.value })\n : slot({ ok: false, value: msg.error });\n }\n return;\n }\n if (msg.kind === \"transport.reply\") {\n const slot = pendingTransport.get(msg.id);\n if (slot) {\n pendingTransport.delete(msg.id);\n msg.ok ? slot({ ok: true, value: msg.value })\n : slot({ ok: false, value: msg.error });\n }\n return;\n }\n\n // Top-level client request. A whole-account catch-up becomes a stepped\n // pass the scheduler runs one conversation per turn, behind everything\n // else queued; every other request runs FIFO, one WASM call at a time.\n // `runRequest` and the pass stepper never reject (errors are posted as\n // results), so the scheduler can't wedge.\n if (msg.kind === \"syncConversations\") {\n scheduler.enqueueStepped(catchUpPassStepper(msg));\n return;\n }\n // The SDK's own gap fill: one page per turn on the stepped lane, so a\n // send posted while a long fill runs goes between pages.\n if (msg.kind === \"syncConversationStep\" && msg.stepped === true) {\n scheduler.enqueueStepped(async () => {\n await runRequest(msg);\n return false;\n });\n return;\n }\n scheduler.enqueue(() => runRequest(msg));\n};\n\n/**\n * One whole-account catch-up as a stepped job: ONE PAGE of one conversation\n * per scheduler turn (`catch-up-pass.ts` has the policy). The scheduler runs\n * queued ordinary requests between pages. When the host transport reports\n * the server's log heads, only the conversations that are behind are\n * stepped. Each page's messages are posted as an `event.batch` (source\n * `page`) and its conversation updates come from the core's exact `updated`\n * list, so nothing here diffs epochs. The result is posted once, when the\n * pass is complete, with every decrypted application message in apply\n * order, the same contract `syncConversations()` callers have always had.\n */\nfunction catchUpPassStepper(\n msg: Extract<Request, { kind: \"syncConversations\" }>,\n): () => Promise<boolean> {\n const post = (m: Response): void => (self.postMessage as (m: Response) => void)(m);\n let pass: (() => Promise<boolean>) | null = null;\n return async (): Promise<boolean> => {\n if (pass === null) {\n try {\n await ensureWasm();\n ensureClient();\n } catch (e) {\n post({\n kind: \"result\", id: msg.id, ok: false,\n error: e instanceof Error ? e.message : String(e),\n });\n return false;\n }\n pass = catchUpPass({\n listConversationIds: () =>\n (ensureClient().listConversations() as unknown as ConversationEpoch[]).map((meta) => meta.id),\n fetchHeads: async () =>\n transportFeatures.fetchLogHeads ? (await fetchLogHeadsProxy()) ?? null : null,\n conversationsBehind: (heads) =>\n ensureClient().conversationsBehind(heads) as unknown as Uint8Array[],\n step: (id) =>\n ensureClient().syncConversationStep(id, msg.nowMs) as unknown as Promise<SyncStepResultWire>,\n onPage: (page) => {\n announceUpdated(page.updated);\n if (page.messages.length > 0) {\n post({ kind: \"event.batch\", messages: page.messages, source: \"page\" });\n }\n },\n finish: (ok, value) => {\n if (ok) {\n post({ kind: \"result\", id: msg.id, ok: true, value });\n } else {\n post({\n kind: \"result\", id: msg.id, ok: false,\n error: value instanceof Error ? value.message : String(value),\n });\n }\n },\n });\n }\n return pass();\n };\n}\n\nasync function dispatch(msg: Request): Promise<unknown> {\n await ensureWasm();\n switch (msg.kind) {\n case \"init\": {\n transportFeatures = msg.transportFeatures ?? { fetchLogSince: false, fetchLogHeads: false };\n client = await PingClient.init(\n msg.identityExport, msg.deviceLabel,\n makeProxyStorage(msg.storageFeatures) as unknown as never,\n makeProxyTransport(transportFeatures) as unknown as never,\n msg.nowMs,\n // Optional Ed25519 device signing secret — see protocol.ts\n // and ClientConfig.deviceSigningSecretKey. Forwarding `null`\n // explicitly when absent so the wasm-bindgen `Option<Vec<u8>>`\n // shape is matched correctly.\n msg.deviceSigningSecretKey ?? null,\n // The owner each conversation's FIRST roles write must name\n // (2026-11-04, round 2); `null` for none.\n msg.expectedOwners ?? null,\n );\n // Wire decrypted application-message callback back to the main thread.\n client.onMessage((m: unknown) => {\n (self.postMessage as (m: Response) => void)({ kind: \"event.message\", msg: m as never });\n });\n return null;\n }\n case \"openReadOnly\": {\n // No `onMessage` wiring here: a read-only client exists to answer one\n // question about one envelope, not to stream. Registering the callback\n // would also fire the tab's handlers from the worker.\n client = await PingClient.openReadOnly(\n msg.identityExport, msg.deviceLabel,\n makeProxyStorage(msg.storageFeatures) as unknown as never,\n proxyTransport as unknown as never,\n msg.nowMs,\n );\n return null;\n }\n\n case \"previewEnvelope\":\n return ensureClient().previewEnvelope(msg.envelope as unknown as never, msg.nowMs);\n\n case \"generateIdentity\":\n return PingClient.generateIdentity();\n case \"userId\": return ensureClient().userId();\n case \"exportIdentity\": return ensureClient().exportIdentity();\n case \"rotateIdentity\":\n // One self-update Commit per conversation moves the leaf credential to\n // the new user id; the device signing key and deviceId stay put. The\n // identity swaps even when some conversations end up in `failed`.\n return await ensureClient().rotateIdentity(msg.newIdentityExport, msg.nowMs);\n case \"rotateIdentityRetry\":\n return await ensureClient().rotateIdentityRetry(msg.conv, msg.nowMs);\n case \"deviceId\": return ensureClient().deviceId();\n case \"suspendStorage\": return ensureClient().suspendStorage();\n case \"resumeStorage\": return ensureClient().resumeStorage();\n case \"freshKeyPackage\": return ensureClient().freshKeyPackage();\n case \"freshLastResortKeyPackage\": return ensureClient().freshLastResortKeyPackage();\n case \"createConversation\":\n return await ensureClient().createConversation(msg.name ?? undefined, msg.nowMs);\n case \"createCallConversation\":\n return await ensureClient().createCallConversation(msg.name ?? undefined, msg.nowMs);\n case \"joinConversation\": {\n const id = await ensureClient().joinConversation(msg.welcome, msg.nowMs) as Uint8Array;\n // Notify the main thread that we just entered a new conversation. We forward the\n // Welcome's `sender_device` so the host can label \"joined chat with <inviter>\".\n (self.postMessage as (m: Response) => void)({\n kind: \"event.conversation\",\n id,\n epoch: 0,\n sender: msg.welcome.sender_device,\n });\n return id;\n }\n case \"listConversations\":\n return ensureClient().listConversations();\n case \"strandedConversations\":\n return ensureClient().strandedConversations();\n case \"conversationsLeaving\":\n return ensureClient().conversationsLeaving();\n case \"conversationsLeaveStalled\":\n return ensureClient().conversationsLeaveStalled();\n case \"readmitPendingConversations\":\n return ensureClient().readmitPendingConversations(msg.nowMs);\n case \"undeliverableCount\":\n return ensureClient().undeliverableCount();\n case \"members\":\n return ensureClient().members(msg.conv);\n case \"conversationPolicy\":\n return ensureClient().conversationPolicy(msg.conv);\n case \"setExpectedOwners\":\n return ensureClient().setExpectedOwners(msg.entries);\n case \"setConversationRoles\":\n return await ensureClient().setConversationRoles(msg.conv, msg.owner, msg.admins, msg.nowMs);\n case \"send\":\n return await ensureClient().send(msg.conv, msg.plaintext, msg.nowMs);\n case \"addMembers\":\n // wasm-bindgen takes the entries as a plain array of {deviceId, keyPackage};\n // serde-wasm-bindgen on the Rust side deserialises into Vec<JsAddMemberEntry>.\n return await ensureClient().addMembers(msg.conv, msg.entries, msg.nowMs);\n case \"addMembersWithVerdicts\":\n // Per-entry verdicts; resolves to the serialised AddMembersReport.\n return await ensureClient().addMembersWithVerdicts(msg.conv, msg.entries, msg.nowMs);\n case \"reAdmitDevice\":\n // Re-admit one device that kept its key: the leaf with the KeyPackage's\n // own signature key goes and the fresh KeyPackage is added. Never an add:\n // with no such leaf it rejects \"not permitted: ...\", and so does a\n // committer the roles do not permit. Resolves to the device id of the\n // replaced leaf.\n return await ensureClient().reAdmitDevice(msg.conv, msg.entry, msg.nowMs);\n case \"mayReadmit\":\n // A pure query: would this device's Commit re-admitting or adding that\n // device pass the membership rules now. Nothing is built or sent.\n return ensureClient().mayReadmit(msg.conv, msg.identity, msg.deviceId);\n case \"keyPackageIdentity\":\n // A pure read: the identity the KeyPackage's credential claims, after the\n // KeyPackage was validated (signatures, lifetime). `undefined` for a\n // credential that is not the project's; throws for anything else.\n return ensureClient().keyPackageIdentity(msg.keyPackage);\n case \"setConversationName\":\n // GroupContextExtensions commit carrying the new conversation name — the\n // rename / avatar-id change propagates to every member via group state.\n return await ensureClient().setConversationName(msg.conv, msg.name ?? undefined, msg.nowMs);\n case \"admitDeviceToChats\":\n // Per-chat add for a newly-linked device. Returns Vec<JsAdmitChatOutcome>\n // — the host inspects per-entry status to decide whether to retry.\n return await ensureClient().admitDeviceToChats(msg.deviceId, msg.entries, msg.nowMs);\n case \"admitDeviceToChatsConcurrent\":\n // Same per-chat add with up to `concurrency` admissions in flight inside\n // this ONE wasm call (the worker still runs one call at a time; the\n // overlap is the core's, across conversations). Outcomes in input order.\n return await ensureClient().admitDeviceToChatsConcurrent(\n msg.deviceId,\n msg.entries,\n msg.nowMs,\n msg.concurrency,\n );\n case \"removeMembers\":\n // wasm-bindgen exposes Vec<u32> as Uint32Array; convert from the protocol's number[].\n return await ensureClient().removeMembers(msg.conv, new Uint32Array(msg.leaves), msg.nowMs);\n case \"removeOwnOtherLeaves\":\n // Every OTHER leaf of this account in one conversation; resolves to the count.\n return await ensureClient().removeOwnOtherLeaves(msg.conv, msg.nowMs);\n case \"removeMembersByIdentity\":\n // Every leaf whose credential verifies for one of `identities`; resolves to the count.\n return await ensureClient().removeMembersByIdentity(msg.conv, msg.identities, msg.nowMs);\n case \"leaveConversation\":\n return await ensureClient().leaveConversation(msg.conv, msg.nowMs);\n case \"dropConversationLocal\":\n return await ensureClient().dropConversationLocal(msg.conv);\n case \"conversationsWithPendingProposals\":\n return ensureClient().conversationsWithPendingProposals();\n case \"commitPendingProposals\":\n return await ensureClient().commitPendingProposals(msg.conv, msg.nowMs);\n case \"pendingProposalsCommitRank\":\n return ensureClient().pendingProposalsCommitRank(msg.conv) ?? null;\n case \"commitsInDoubt\":\n return ensureClient().commitsInDoubt();\n case \"revokeDevice\":\n // [CR-2] returns the array of Commit envelopes the SDK has already broadcast.\n return await ensureClient().revokeDevice(msg.deviceId, msg.nowMs);\n case \"removeDeviceEverywhere\":\n // Every group, DeviceGroup first, never stopping at a failure; resolves\n // to the report the host persists and retries from.\n return await ensureClient().removeDeviceEverywhere(msg.deviceId, msg.nowMs);\n case \"removeOwnDevicesExcept\":\n // The \"secure my account\" sweep: every other leaf of this account\n // except `keep` (by credential, or listed by the server); same report.\n return await ensureClient().removeOwnDevicesExcept(msg.keep, msg.listed, msg.nowMs);\n case \"processEnvelope\": {\n const result = await ensureClient().processEnvelope(msg.envelope, msg.nowMs);\n (self.postMessage as (m: Response) => void)({\n kind: \"event.conversation\",\n id: msg.envelope.conversation_id,\n epoch: msg.envelope.epoch,\n });\n return result;\n }\n case \"pendingApplies\":\n // [D27] Journal listing — reading does not consume.\n return ensureClient().pendingApplies();\n case \"confirmApplied\":\n // [D27] Removes + checkpoints; unknown ids are ignored (idempotent).\n return await ensureClient().confirmApplied(msg.journalIds);\n case \"syncConversations\":\n // Reached only if a caller bypasses `onmessage`; the scheduler turns\n // this kind into a stepped pass before it can get here.\n return await ensureClient().syncConversations(msg.nowMs);\n case \"syncConversation\":\n return await ensureClient().syncConversation(msg.conv, msg.nowMs);\n // Sequenced log sync. The batch and page results carry their messages\n // (the wasm does not fan them out through `onMessage`); the main thread\n // delivers them from the result. Conversation updates are announced from\n // the core's exact `updated` list, before the result resolves.\n case \"processSequencedBatch\": {\n const raw = await ensureClient().processSequencedBatch(msg.items, msg.nowMs) as unknown as ApplyBatchResultWire;\n announceUpdated(raw.updated, welcomeSenders(msg.items, raw.joined));\n return raw;\n }\n case \"syncConversationStep\": {\n const raw = await ensureClient().syncConversationStep(msg.conv, msg.nowMs) as unknown as SyncStepResultWire;\n announceUpdated(raw.updated);\n return raw;\n }\n case \"logPositions\":\n return ensureClient().logPositions();\n case \"logPosition\":\n return ensureClient().logPosition(msg.conv);\n case \"adoptLogPosition\":\n return await ensureClient().adoptLogPosition(msg.conv, msg.epoch, msg.serverSeq);\n case \"conversationsBehind\":\n return ensureClient().conversationsBehind(msg.heads);\n case \"heldFrameCount\":\n return ensureClient().heldFrameCount();\n case \"joinConversationAt\": {\n const id = await ensureClient().joinConversationAt(msg.welcome, msg.position, msg.nowMs) as Uint8Array;\n (self.postMessage as (m: Response) => void)({\n kind: \"event.conversation\",\n id,\n epoch: 0,\n sender: msg.welcome.sender_device,\n });\n return id;\n }\n case \"processWelcomeAt\": {\n const id = await ensureClient().processWelcomeAt(msg.welcome, msg.position, msg.nowMs) as Uint8Array | null;\n if (id !== null && id !== undefined) {\n (self.postMessage as (m: Response) => void)({\n kind: \"event.conversation\",\n id,\n epoch: 0,\n sender: msg.welcome.sender_device,\n });\n return id;\n }\n return null;\n }\n case \"buildLinkingTicket\":\n return await ensureClient().buildLinkingTicket(\n msg.newDeviceId, msg.newDeviceKp, msg.lastAppEvents, msg.nowMs,\n );\n case \"consumeLinkingTicket\":\n await ensureClient().consumeLinkingTicket(msg.ticket, msg.nowMs);\n return null;\n case \"decodeCatchupSnapshot\":\n // Pure WASM — no client state required. The new device may call this in an\n // ephemeral worker before init() completes.\n return wasmDecodeCatchupSnapshot(msg.snapshotBytes);\n case \"exportConversationSecret\":\n // wasm-bindgen returns a Uint8Array sized to `length`. The bytes are a secret —\n // the main thread is responsible for clearing the typed array when done.\n return ensureClient().exportConversationSecret(\n msg.conv, msg.label, msg.context, msg.length,\n );\n case \"sealLinkingTicket\":\n // Pure WASM call — no client state required. Lets a sender seal a ticket from an\n // ephemeral worker without standing up the full PingClient.\n return wasmSealLinkingTicket(msg.ticket, msg.newDevicePub);\n case \"openLinkingTicket\":\n // Same — runs without an initialised client, which is the receiving device's\n // pre-bootstrap state (it has the X25519 ephemeral key but no identity yet).\n return wasmOpenLinkingTicket(msg.sealed, msg.newDevicePriv);\n case \"hpkeSeal\":\n // Generic HPKE seal for app-layer envelopes (e.g. linking auth envelope).\n return wasmHpkeSeal(msg.plaintext, msg.recipientPub, msg.info);\n case \"hpkeOpen\":\n return wasmHpkeOpen(msg.sealed, msg.recipientPriv, msg.info);\n case \"hpkeSealRaw\":\n // The RFC 9180 canonical layout (`enc || ct`), which the app layers use.\n return wasmHpkeSealRaw(msg.plaintext, msg.recipientPub, msg.info);\n case \"hpkeOpenRaw\":\n return wasmHpkeOpenRaw(msg.sealed, msg.recipientPriv, msg.info);\n case \"hpkeGenerateKeypair\":\n return wasmHpkeGenerateKeypair();\n // Post-quantum (X-Wing) twins: all pure WASM, no client state required.\n case \"sealLinkingTicketPq\":\n return wasmSealLinkingTicketPq(msg.ticket, msg.newDevicePub);\n case \"openLinkingTicketPq\":\n return wasmOpenLinkingTicketPq(msg.sealed, msg.newDevicePriv);\n case \"hpkeSealPq\":\n return wasmHpkeSealPq(msg.plaintext, msg.recipientPub, msg.info);\n case \"hpkeOpenPq\":\n return wasmHpkeOpenPq(msg.sealed, msg.recipientPriv, msg.info);\n case \"hpkeSealRawPq\":\n return wasmHpkeSealRawPq(msg.plaintext, msg.recipientPub, msg.info);\n case \"hpkeOpenRawPq\":\n return wasmHpkeOpenRawPq(msg.sealed, msg.recipientPriv, msg.info);\n case \"hpkeGenerateKeypairPq\":\n return wasmHpkeGenerateKeypairPq();\n case \"hpkePublicKeyFromSeed\":\n return wasmHpkePublicKeyFromSeed(msg.seed);\n case \"deviceGroupIdFor\":\n // Pure: the core's DeviceGroup id derivation for an MLS user id.\n return wasmDeviceGroupIdFor(msg.userId);\n case \"hpkePublicKeyFromPrivate\":\n return wasmHpkePublicKeyFromPrivate(msg.privateKey);\n case \"signDeviceReauth\":\n // Pure WASM: the SDK builds the signed bytes, so this signs nothing else\n // with the device key. Returns `deviceId (32) || signature (64)`.\n return wasmSignDeviceReauth(msg.deviceSigningSecretKey, msg.challengeId, msg.nonce, msg.accountId, msg.audience);\n case \"signDeviceLinkApproval\":\n // Pure WASM, link verification v2: the SDK builds the signed bytes and\n // derives both ids. Returns `approverDeviceId (32) || newDeviceId (32) ||\n // signature (64)`.\n return wasmSignDeviceLinkApproval(msg.deviceSigningSecretKey, msg.approvalSessionId, msg.accountId, msg.newDevicePubkey, msg.audience);\n case \"signDeviceLinkPossession\":\n // Pure WASM. Returns `deviceId (32) || signature (64)`.\n return wasmSignDeviceLinkPossession(msg.deviceSigningSecretKey, msg.approvalSessionId, msg.accountId, msg.audience);\n case \"exportConversationStateSnapshot\":\n // [CR-7] state snapshot bytes are a secret (past epoch keys); the main thread\n // is responsible for clearing the typed array when done.\n return ensureClient().exportConversationStateSnapshot(msg.conv, msg.nowMs);\n case \"importStateSnapshot\":\n // [CR-7] returns the imported conversation id as a Uint8Array.\n return await ensureClient().importStateSnapshot(msg.snapshotBytes, msg.nowMs);\n // Recovery — all pure WASM; no client state required.\n case \"generateMnemonicPhrase\":\n return wasmGenerateMnemonicPhrase();\n case \"normalizeMnemonicPhrase\":\n return wasmNormalizeMnemonicPhrase(msg.phrase);\n case \"encryptBackup\":\n return wasmEncryptBackup(\n msg.mnemonicPhrase, msg.accountId, msg.identityExport,\n msg.deviceGroupSnapshot,\n // Map idiomatic camelCase → the snake_case keys serde expects on the\n // WASM boundary (matches the decrypt view's account_id / group_state_bytes).\n msg.conversationSnapshots.map((c) => ({\n conversation_id: c.conversationId,\n group_state_bytes: c.groupStateBytes,\n })),\n msg.createdAtMs,\n );\n case \"decryptBackup\":\n return wasmDecryptBackup(msg.blob, msg.mnemonicPhrase);\n case \"sealHistoryBundle\":\n return wasmSealHistoryBundle(msg.bundle, msg.recipientPub, msg.senderIdentitySecret);\n case \"openHistoryBundle\":\n return wasmOpenHistoryBundle(msg.sealed, msg.recipientPriv, msg.senderIdentityPub);\n case \"sealHistoryBundlePq\":\n return wasmSealHistoryBundlePq(msg.bundle, msg.recipientPub, msg.senderIdentitySecret);\n case \"openHistoryBundlePq\":\n return wasmOpenHistoryBundlePq(msg.sealed, msg.recipientPriv, msg.senderIdentityPub);\n default:\n throw new Error(`unknown request kind: ${(msg as { kind: string }).kind}`);\n }\n}\n\nfunction ensureClient(): PingClient {\n if (!client) throw new Error(\"client not initialised\");\n return client;\n}\n","// Which conversations' MLS epochs moved, and therefore which `event.conversation`\n// notifications the worker owes the main thread.\n//\n// This lives outside `worker.ts` purely so it is testable: importing the worker\n// module runs its top-level `self.onmessage` wiring, which needs a\n// `DedicatedWorkerGlobalScope`. The rule it encodes is small but load-bearing —\n// see `EPOCH_ADVANCING_REQUESTS` in the worker for why a self-authored or\n// catch-up-applied commit would otherwise be announced to nobody.\n\n/** The two fields of a `ConversationMeta` this comparison needs. */\nexport interface ConversationEpoch {\n id: Uint8Array;\n epoch: number;\n}\n\n/** Stable map key for a 16-byte conversation id. */\nexport function conversationKey(id: Uint8Array): string {\n let out = \"\";\n for (let i = 0; i < id.length; i += 1) out += (id[i] ?? 0).toString(16).padStart(2, \"0\");\n return out;\n}\n\n/** Epoch per conversation, keyed by `conversationKey`. */\nexport function epochMap(metas: readonly ConversationEpoch[]): Map<string, number> {\n const out = new Map<string, number>();\n for (const meta of metas) out.set(conversationKey(meta.id), meta.epoch);\n return out;\n}\n\n/**\n * Conversations whose epoch STRICTLY advanced between `before` and `after`.\n *\n * Only conversations present in both are considered:\n * - a conversation that is new since `before` was either just created by this\n * caller or just joined, and `joinConversation` already announces the\n * latter — announcing it here would double-fire;\n * - a conversation that has disappeared (left / dropped) has no epoch to\n * report;\n * - an epoch that did not move is not an event, however many times the\n * request that ran touched the group.\n */\nexport function advancedEpochs(\n before: ReadonlyMap<string, number>,\n after: readonly ConversationEpoch[],\n): ConversationEpoch[] {\n const out: ConversationEpoch[] = [];\n for (const meta of after) {\n const previous = before.get(conversationKey(meta.id));\n if (previous === undefined || meta.epoch <= previous) continue;\n out.push(meta);\n }\n return out;\n}\n","// The whole-account catch-up as a stepped job: one PAGE of one conversation\n// per scheduler turn.\n//\n// `syncConversations()` used to page each conversation to its end inside one\n// wasm call; a 2,000-message group backlog was eight pages behind which\n// every queued send waited. Each call of the returned step now applies ONE\n// page through `syncConversationStep` and yields, so the primary lane (a\n// send, a live batch, a host's own step) runs between pages as well as\n// between conversations. A conversation whose page was full stays at the\n// head of the queue and continues next turn.\n//\n// When the transport can report the server's log heads, only the\n// conversations `conversationsBehind` names are stepped: one request instead\n// of one page per conversation the account holds. A transport without\n// `fetchLogHeads` (or one that answers `null`: the relay has no heads route)\n// gets the whole-account walk, as before. A heads request that FAILS ends\n// the pass with that error instead: walking every conversation on a network\n// that just failed one request would fail N more times, and the host retries\n// the pass on its next trigger (reconnect, foreground, heartbeat), by which\n// time the socket's `resume_ack` has usually named what is behind anyway.\n//\n// The pass ends with one re-list so a conversation joined while it ran is\n// still covered, exactly as the core re-reads its map. Conversations already\n// evaluated (stepped, or present in the heads snapshot) are not re-stepped.\n//\n// Lives outside `worker.ts` so it is testable without a\n// `DedicatedWorkerGlobalScope`; the worker supplies the dependencies.\n\nimport { conversationKey } from \"./epoch-events\";\nimport type { LogHeadWire, SyncStepResultWire } from \"./sequenced\";\nimport type { IncomingMessage } from \"./types\";\n\nexport interface CatchUpPassDeps {\n /** Ids of every conversation the client holds right now. */\n listConversationIds(): Uint8Array[];\n /** The server's heads, or `null` when the transport cannot report them. */\n fetchHeads(): Promise<LogHeadWire[] | null>;\n /** The core's verdict on which of `heads` this device is behind on. */\n conversationsBehind(heads: LogHeadWire[]): Uint8Array[];\n /** Apply ONE page of one conversation. */\n step(id: Uint8Array): Promise<SyncStepResultWire>;\n /** Deliver a page: its conversation updates and its messages. */\n onPage(result: SyncStepResultWire): void;\n /** Post the pass result: every message in apply order, or the error. */\n finish(ok: boolean, value: IncomingMessage[] | unknown): void;\n}\n\n/**\n * Build the stepped job. Each call runs one step and resolves `true` while\n * the pass has more to do; it never rejects (errors are posted through\n * `finish`).\n */\nexport function catchUpPass(deps: CatchUpPassDeps): () => Promise<boolean> {\n const seen = new Set<string>();\n const delivered: IncomingMessage[] = [];\n let pending: Uint8Array[] | null = null;\n let relisted = false;\n\n const sortedUnseen = (ids: Uint8Array[]): Uint8Array[] =>\n ids\n .filter((id) => !seen.has(conversationKey(id)))\n .sort((a, b) => (conversationKey(a) < conversationKey(b) ? -1 : 1));\n\n const initial = async (): Promise<Uint8Array[]> => {\n // A rejection propagates to the caller, which posts it through `finish`.\n const heads = await deps.fetchHeads();\n if (heads === null) return sortedUnseen(deps.listConversationIds());\n // Every conversation the heads describe has been evaluated: the ones\n // that are current are not stepped now and not re-stepped by the re-list.\n for (const h of heads) seen.add(conversationKey(h.conversation_id));\n const behind = deps.conversationsBehind(heads);\n for (const id of behind) seen.delete(conversationKey(id));\n return sortedUnseen(behind);\n };\n\n return async (): Promise<boolean> => {\n try {\n if (pending === null) pending = await initial();\n if (pending.length === 0 && !relisted) {\n relisted = true;\n pending = sortedUnseen(deps.listConversationIds());\n }\n } catch (e) {\n deps.finish(false, e);\n return false;\n }\n const id = pending[0];\n if (id === undefined) {\n deps.finish(true, delivered);\n return false;\n }\n let more = false;\n try {\n const page = await deps.step(id);\n for (const m of page.messages) delivered.push(m);\n deps.onPage(page);\n more = page.has_more;\n } catch {\n // Dropped between the listing and this step (a wipe, a self-removal),\n // a transport failure, or a checkpoint failure: this conversation's\n // paging ends for this pass. The durable cursor is where the next\n // pass resumes, which is what the whole-account request did too.\n }\n if (!more) {\n seen.add(conversationKey(id));\n pending.shift();\n }\n return true;\n };\n}\n","// Request scheduling for the WASM worker: one call in flight at a time, in\n// two lanes.\n//\n// The worker may run only ONE WASM call at a time (see `worker.ts`), so every\n// request waits for the one before it. That is fine for the requests a user\n// is waiting on (a send, a live frame) — they are short. It was not fine for a\n// whole-account catch-up, which paged every conversation inside a single\n// request: a `send` posted while it ran started after all of them, and on a\n// tab returning from an idle hour that wait WAS the first message's latency.\n//\n// This scheduler keeps the one-call invariant and adds a second lane for\n// work that is allowed to be interrupted between its natural steps. An\n// ordinary request runs FIFO in the primary lane; a stepped job runs one\n// step per turn and only when the primary lane is empty, so anything queued\n// while a step ran goes next. Stepped jobs are FIFO among themselves and a\n// job's steps never interleave with another job's.\n//\n// Lives outside `worker.ts` so it is testable without a\n// `DedicatedWorkerGlobalScope` (the same reason `epoch-events.ts` exists).\n\n/** An ordinary request: runs to completion in one turn. Must not reject. */\nexport type LaneJob = () => Promise<void>;\n\n/**\n * A stepped job: each call runs ONE step and resolves `true` while more steps\n * remain. A rejected step ends the job (the scheduler treats it as `false`).\n */\nexport type SteppedJob = () => Promise<boolean>;\n\nexport class RequestScheduler {\n private readonly primary: LaneJob[] = [];\n private readonly stepped: SteppedJob[] = [];\n private pumping = false;\n\n /** Queue an ordinary request behind the ordinary requests before it. */\n enqueue(job: LaneJob): void {\n this.primary.push(job);\n void this.pump();\n }\n\n /** Queue a stepped job; its steps run whenever the primary lane is empty. */\n enqueueStepped(job: SteppedJob): void {\n this.stepped.push(job);\n void this.pump();\n }\n\n /** Requests waiting in the primary lane (diagnostics / tests). */\n get pendingPrimary(): number {\n return this.primary.length;\n }\n\n /** Stepped jobs not yet finished (diagnostics / tests). */\n get pendingStepped(): number {\n return this.stepped.length;\n }\n\n private async pump(): Promise<void> {\n if (this.pumping) return;\n this.pumping = true;\n try {\n for (;;) {\n const job = this.primary.shift();\n if (job !== undefined) {\n // A job posts its own error as a result; a rejection here would\n // only mean a bug in the job, and it must not stall the lane.\n await job().catch(() => undefined);\n continue;\n }\n const step = this.stepped[0];\n if (step === undefined) return;\n let more = false;\n try {\n more = await step();\n } catch {\n more = false;\n }\n if (!more) this.stepped.shift();\n }\n } finally {\n this.pumping = false;\n }\n }\n}\n"],"mappings":";AAkBO,IAAM,sBAAsB,CAAC,KAAK,KAAK,IAAI,EAAE;AACpD,IAAM,kBAAkB,KAAK;AAI7B,IAAM,WAAW,oBAAI,QAA4B;AAE1C,SAAS,oBAAoB,QAAkC;AACpE,MAAI,SAAS,IAAI,MAAM,EAAG;AAC1B,WAAS,IAAI,MAAM;AACnB,aAAW,OAAO,qBAAqB;AACrC,QAAI;AACF,aAAO,KAAM,MAAM,OAAO,OAAQ,eAAe;AACjD;AAAA,IACF,QAAQ;AAAA,IAER;AAAA,EACF;AACF;;;AC3BA,OAAO;AAAA,EACL;AAAA,EACA,qBAAqB;AAAA,EACrB,qBAAqB;AAAA,EACrB,YAAY;AAAA,EACZ,YAAY;AAAA,EACZ,eAAe;AAAA,EACf,eAAe;AAAA,EACf,uBAAuB;AAAA,EACvB,uBAAuB;AAAA,EACvB,uBAAuB;AA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QAAQ;AAAA,IACpH,KAAK;AAGH,aAAO,aAAa,EAAE,gCAAgC,IAAI,MAAM,IAAI,KAAK;AAAA,IAC3E,KAAK;AAEH,aAAO,MAAM,aAAa,EAAE,oBAAoB,IAAI,eAAe,IAAI,KAAK;AAAA;AAAA,IAE9E,KAAK;AACH,aAAO,2BAA2B;AAAA,IACpC,KAAK;AACH,aAAO,4BAA4B,IAAI,MAAM;AAAA,IAC/C,KAAK;AACH,aAAO;AAAA,QACL,IAAI;AAAA,QAAgB,IAAI;AAAA,QAAW,IAAI;AAAA,QACvC,IAAI;AAAA;AAAA;AAAA,QAGJ,IAAI,sBAAsB,IAAI,CAAC,OAAO;AAAA,UACpC,iBAAiB,EAAE;AAAA,UACnB,mBAAmB,EAAE;AAAA,QACvB,EAAE;AAAA,QACF,IAAI;AAAA,MACN;AAAA,IACF,KAAK;AACH,aAAO,kBAAkB,IAAI,MAAM,IAAI,cAAc;AAAA,IACvD,KAAK;AACH,aAAO,sBAAsB,IAAI,QAAQ,IAAI,cAAc,IAAI,oBAAoB;AAAA,IACrF,KAAK;AACH,aAAO,sBAAsB,IAAI,QAAQ,IAAI,eAAe,IAAI,iBAAiB;AAAA,IACnF,KAAK;AACH,aAAO,wBAAwB,IAAI,QAAQ,IAAI,cAAc,IAAI,oBAAoB;AAAA,IACvF,KAAK;AACH,aAAO,wBAAwB,IAAI,QAAQ,IAAI,eAAe,IAAI,iBAAiB;AAAA,IACrF;AACE,YAAM,IAAI,MAAM,yBAA0B,IAAyB,IAAI,EAAE;AAAA,EAC7E;AACF;AAEA,SAAS,eAA2B;AAClC,MAAI,CAAC,OAAQ,OAAM,IAAI,MAAM,wBAAwB;AACrD,SAAO;AACT;","names":[]}
package/package.json CHANGED
@@ -1,6 +1,63 @@
1
1
  {
2
2
  "name": "@ping-app/ping-openmls-sdk",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.9.2",
4
+ "description": "OpenMLS-based secure messaging SDK — runs in browsers, React Native, RN-Web, and Electron/Tauri.",
5
+ "license": "Apache-2.0",
6
+ "repository": {
7
+ "type": "git",
8
+ "url": "git+https://github.com/AMP-Media-Development/ping-openmls-sdk.git",
9
+ "directory": "sdk/js"
10
+ },
11
+ "publishConfig": {
12
+ "access": "public"
13
+ },
14
+ "type": "module",
15
+ "main": "./dist/index.cjs",
16
+ "module": "./dist/index.js",
17
+ "types": "./dist/index.d.ts",
18
+ "exports": {
19
+ ".": {
20
+ "types": "./dist/index.d.ts",
21
+ "import": "./dist/index.js",
22
+ "require": "./dist/index.cjs"
23
+ },
24
+ "./worker": {
25
+ "types": "./dist/worker.d.ts",
26
+ "import": "./dist/worker.js"
27
+ },
28
+ "./notification-preview": {
29
+ "types": "./dist/notification-preview.d.ts",
30
+ "import": "./dist/notification-preview.js"
31
+ },
32
+ "./storage/indexeddb": {
33
+ "types": "./dist/storage/indexeddb.d.ts",
34
+ "import": "./dist/storage/indexeddb.js"
35
+ },
36
+ "./transport/websocket": {
37
+ "types": "./dist/transport/websocket.d.ts",
38
+ "import": "./dist/transport/websocket.js"
39
+ }
40
+ },
41
+ "files": [
42
+ "dist",
43
+ "wasm"
44
+ ],
45
+ "scripts": {
46
+ "build:wasm": "../../scripts/build-wasm.sh",
47
+ "build:ts": "tsup",
48
+ "build": "npm run build:wasm && npm run build:ts",
49
+ "test": "vitest run --passWithNoTests",
50
+ "lint": "eslint src",
51
+ "typecheck": "tsc --noEmit"
52
+ },
53
+ "devDependencies": {
54
+ "@types/node": "^20.10.0",
55
+ "fake-indexeddb": "^6.2.5",
56
+ "tsup": "^8.0.0",
57
+ "typescript": "^5.3.0",
58
+ "vitest": "^1.0.0"
59
+ },
60
+ "engines": {
61
+ "node": ">=18"
62
+ }
63
+ }
@@ -0,0 +1,17 @@
1
+ {
2
+ "name": "ping-openmls-sdk-wasm",
3
+ "type": "module",
4
+ "description": "wasm-bindgen surface for the Ping OpenMLS SDK — drives the ping-openmls-sdk npm package",
5
+ "version": "0.9.1",
6
+ "license": "Apache-2.0",
7
+ "files": [
8
+ "ping_wasm_bg.wasm",
9
+ "ping_wasm.js",
10
+ "ping_wasm.d.ts"
11
+ ],
12
+ "main": "ping_wasm.js",
13
+ "types": "ping_wasm.d.ts",
14
+ "sideEffects": [
15
+ "./snippets/*"
16
+ ]
17
+ }