@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
package/dist/index.js ADDED
@@ -0,0 +1,2655 @@
1
+ // src/fanout.ts
2
+ function errorKind(e) {
3
+ if (e instanceof Error) return e.name;
4
+ return typeof e;
5
+ }
6
+ var MessageFanout = class {
7
+ messageHandlers = /* @__PURE__ */ new Set();
8
+ batchHandlers = /* @__PURE__ */ new Set();
9
+ onMessage(handler) {
10
+ this.messageHandlers.add(handler);
11
+ return () => this.messageHandlers.delete(handler);
12
+ }
13
+ onMessageBatch(handler) {
14
+ this.batchHandlers.add(handler);
15
+ return () => this.batchHandlers.delete(handler);
16
+ }
17
+ get hasBatchHandlers() {
18
+ return this.batchHandlers.size > 0;
19
+ }
20
+ /** One message from the legacy per-envelope path. */
21
+ deliverOne(m) {
22
+ for (const h of this.messageHandlers) {
23
+ try {
24
+ h(m);
25
+ } catch (e) {
26
+ if (typeof console !== "undefined") {
27
+ console.debug("[ping-sdk] onMessage handler threw:", errorKind(e));
28
+ }
29
+ }
30
+ }
31
+ }
32
+ /**
33
+ * One batch or page result. An empty result is not delivered: there is
34
+ * nothing to persist, and the caller already has the result value.
35
+ */
36
+ deliverBatch(messages, meta) {
37
+ if (messages.length === 0) return;
38
+ if (this.batchHandlers.size === 0) {
39
+ for (const m of messages) this.deliverOne(m);
40
+ return;
41
+ }
42
+ for (const h of this.batchHandlers) {
43
+ try {
44
+ h(messages, meta);
45
+ } catch (e) {
46
+ if (typeof console !== "undefined") {
47
+ console.debug("[ping-sdk] onMessageBatch handler threw:", errorKind(e));
48
+ }
49
+ }
50
+ }
51
+ }
52
+ };
53
+
54
+ // src/gap-fill.ts
55
+ var GapFiller = class {
56
+ lanes = /* @__PURE__ */ new Map();
57
+ /**
58
+ * Fill the gap for `key`. `stepOnce` applies ONE page and resolves `true`
59
+ * while the server may hold more. Resolves when the loop (and any rerun a
60
+ * concurrent request asked for) has finished; rejects with the first step
61
+ * error, which ends that loop.
62
+ */
63
+ fill(key, stepOnce) {
64
+ const running = this.lanes.get(key);
65
+ if (running !== void 0) {
66
+ running.again = true;
67
+ return running.run;
68
+ }
69
+ const lane = { run: Promise.resolve(), again: false };
70
+ lane.run = (async () => {
71
+ try {
72
+ do {
73
+ lane.again = false;
74
+ let more = true;
75
+ while (more) more = await stepOnce();
76
+ } while (lane.again);
77
+ } finally {
78
+ if (this.lanes.get(key) === lane) this.lanes.delete(key);
79
+ }
80
+ })();
81
+ this.lanes.set(key, lane);
82
+ return lane.run;
83
+ }
84
+ /** Conversations with a fill loop running (diagnostics / tests). */
85
+ get inFlight() {
86
+ return this.lanes.size;
87
+ }
88
+ };
89
+
90
+ // src/inbound-coalescer.ts
91
+ var InboundCoalescer = class {
92
+ /**
93
+ * @param apply Applies one batch. A rejection settles the promises of the
94
+ * frames in that batch with the error and the lane moves on to whatever
95
+ * queued meanwhile, so one bad batch cannot wedge a conversation.
96
+ * @param maxBatch Upper bound on frames per batch. A burst larger than
97
+ * this goes out as consecutive batches of at most `maxBatch`, so a
98
+ * flood cannot turn into one unbounded wasm call.
99
+ */
100
+ constructor(apply, maxBatch = 256) {
101
+ this.apply = apply;
102
+ this.maxBatch = maxBatch;
103
+ }
104
+ apply;
105
+ maxBatch;
106
+ lanes = /* @__PURE__ */ new Map();
107
+ /**
108
+ * Queue a frame. Resolves when the batch that carried it has been applied
109
+ * (rejects if that batch failed), so a transport that awaits the dispatch
110
+ * to ack a watermark still sees the truth.
111
+ */
112
+ push(key, item) {
113
+ const lane = this.lanes.get(key);
114
+ if (lane !== void 0) {
115
+ return new Promise((resolve, reject) => {
116
+ lane.queued.push(item);
117
+ lane.waiters.push({ resolve, reject });
118
+ });
119
+ }
120
+ const fresh = { queued: [], waiters: [] };
121
+ this.lanes.set(key, fresh);
122
+ return this.run(key, fresh, [item], []);
123
+ }
124
+ /** Conversations with a batch in flight (diagnostics / tests). */
125
+ get inFlight() {
126
+ return this.lanes.size;
127
+ }
128
+ run(key, lane, items, waiters) {
129
+ let attempt;
130
+ try {
131
+ attempt = this.apply(key, items);
132
+ } catch (e) {
133
+ attempt = Promise.reject(e);
134
+ }
135
+ attempt.then(
136
+ () => {
137
+ for (const w of waiters) w.resolve();
138
+ },
139
+ (e) => {
140
+ for (const w of waiters) w.reject(e);
141
+ }
142
+ );
143
+ void attempt.then(
144
+ () => this.drain(key, lane),
145
+ () => this.drain(key, lane)
146
+ );
147
+ return attempt;
148
+ }
149
+ drain(key, lane) {
150
+ if (lane.queued.length === 0) {
151
+ if (this.lanes.get(key) === lane) this.lanes.delete(key);
152
+ return;
153
+ }
154
+ const items = lane.queued.splice(0, this.maxBatch);
155
+ const waiters = lane.waiters.splice(0, items.length);
156
+ void this.run(key, lane, items, waiters).catch(() => void 0);
157
+ }
158
+ };
159
+
160
+ // src/storage/scope.ts
161
+ function scopeStorage(storage, accountNamespace) {
162
+ const scope = (ns) => `${accountNamespace} ${ns}`;
163
+ const scoped = {
164
+ get: (ns, key) => storage.get(scope(ns), key),
165
+ put: (ns, key, value) => storage.put(scope(ns), key, value),
166
+ del: (ns, key) => storage.del(scope(ns), key),
167
+ listKeys: (ns, prefix) => storage.listKeys(scope(ns), prefix)
168
+ };
169
+ const hostApplyBatch = storage.applyBatch;
170
+ if (typeof hostApplyBatch === "function") {
171
+ scoped.applyBatch = (ns, puts, deletes) => hostApplyBatch.call(storage, scope(ns), puts, deletes);
172
+ }
173
+ const hostListEntries = storage.listEntries;
174
+ if (typeof hostListEntries === "function") {
175
+ scoped.listEntries = (ns, prefix) => hostListEntries.call(storage, scope(ns), prefix);
176
+ }
177
+ return scoped;
178
+ }
179
+ function storageFeaturesOf(storage) {
180
+ return {
181
+ applyBatch: typeof storage.applyBatch === "function",
182
+ listEntries: typeof storage.listEntries === "function"
183
+ };
184
+ }
185
+
186
+ // src/sequenced.ts
187
+ function isSequencedFrame(frame) {
188
+ return typeof frame === "object" && frame !== null && "envelope" in frame && typeof frame.envelope === "object" && frame.envelope !== null;
189
+ }
190
+ function sequencedToWire(item) {
191
+ return { envelope: item.envelope, server_seq: item.serverSeq };
192
+ }
193
+ function logPositionFromWire(p) {
194
+ return {
195
+ conversationId: p.conversation_id,
196
+ epoch: p.epoch,
197
+ serverSeq: p.server_seq,
198
+ anchored: p.anchored
199
+ };
200
+ }
201
+ function logHeadToWire(h) {
202
+ return {
203
+ conversation_id: h.conversationId,
204
+ head_server_seq: h.headServerSeq,
205
+ head_epoch: h.headEpoch
206
+ };
207
+ }
208
+ function logGapFromWire(g) {
209
+ return {
210
+ conversationId: g.conversation_id,
211
+ appliedServerSeq: g.applied_server_seq,
212
+ firstBufferedServerSeq: g.first_buffered_server_seq
213
+ };
214
+ }
215
+ function conversationUpdateFromWire(u) {
216
+ return { conversationId: u.conversation_id, epoch: u.epoch };
217
+ }
218
+ function variant(name) {
219
+ return name.charAt(0).toLowerCase() + name.slice(1);
220
+ }
221
+ function conversationRemovalFromWire(r) {
222
+ return {
223
+ conversationId: r.conversation_id,
224
+ serverSeq: r.server_seq,
225
+ epoch: r.epoch,
226
+ readmitted: r.readmitted
227
+ };
228
+ }
229
+ function welcomeFailureFromWire(w) {
230
+ return {
231
+ conversationId: w.conversation_id,
232
+ serverSeq: w.server_seq,
233
+ reason: variant(w.reason)
234
+ };
235
+ }
236
+ function strandedConversationFromWire(s) {
237
+ return {
238
+ conversationId: s.conversation_id,
239
+ serverSeq: s.server_seq,
240
+ epoch: s.epoch,
241
+ reason: variant(s.reason)
242
+ };
243
+ }
244
+ function bufferOverflowFromWire(o) {
245
+ return {
246
+ conversationId: o.conversation_id,
247
+ reason: variant(o.reason),
248
+ dropped: o.dropped
249
+ };
250
+ }
251
+ function outcomesFromWire(r) {
252
+ return {
253
+ removed: (r.removed ?? []).map(conversationRemovalFromWire),
254
+ welcomeFailures: (r.welcome_failures ?? []).map(welcomeFailureFromWire),
255
+ stranded: (r.stranded ?? []).map(strandedConversationFromWire),
256
+ proposalsPending: r.proposals_pending ?? [],
257
+ overflow: (r.overflow ?? []).map(bufferOverflowFromWire)
258
+ };
259
+ }
260
+ function applyBatchResultFromWire(r) {
261
+ return {
262
+ messages: r.messages,
263
+ applied: r.applied,
264
+ duplicates: r.duplicates,
265
+ buffered: r.buffered,
266
+ failed: r.failed,
267
+ gaps: r.gaps.map(logGapFromWire),
268
+ joined: r.joined,
269
+ updated: r.updated.map(conversationUpdateFromWire),
270
+ ...outcomesFromWire(r)
271
+ };
272
+ }
273
+ function syncStepResultFromWire(r) {
274
+ return {
275
+ messages: r.messages,
276
+ hasMore: r.has_more,
277
+ fetched: r.fetched,
278
+ position: logPositionFromWire(r.position),
279
+ updated: r.updated.map(conversationUpdateFromWire),
280
+ joined: r.joined ?? [],
281
+ ...outcomesFromWire(r)
282
+ };
283
+ }
284
+ function addMembersReportFromWire(r) {
285
+ return {
286
+ verdicts: r.verdicts.map((v) => ({
287
+ deviceId: v.device_id,
288
+ status: variant(v.status),
289
+ leafIndex: v.leaf_index ?? null
290
+ })),
291
+ epoch: r.epoch ?? null
292
+ };
293
+ }
294
+ function commitInDoubtFromWire(c) {
295
+ return {
296
+ conversationId: c.conversation_id,
297
+ attempts: c.attempts,
298
+ nextAttemptAtMs: c.next_attempt_at_ms
299
+ };
300
+ }
301
+
302
+ // src/storage/indexeddb.ts
303
+ var DB_NAME = "ping-sdk";
304
+ var DB_VERSION = 1;
305
+ var STORE = "kv";
306
+ function open() {
307
+ return new Promise((resolve, reject) => {
308
+ const req = indexedDB.open(DB_NAME, DB_VERSION);
309
+ req.onupgradeneeded = () => {
310
+ const db = req.result;
311
+ if (!db.objectStoreNames.contains(STORE)) {
312
+ const os = db.createObjectStore(STORE, { keyPath: ["ns", "key"] });
313
+ os.createIndex("ns", "ns", { unique: false });
314
+ }
315
+ };
316
+ req.onsuccess = () => resolve(req.result);
317
+ req.onerror = () => reject(req.error);
318
+ });
319
+ }
320
+ var IndexedDbStorage = class {
321
+ dbPromise;
322
+ constructor() {
323
+ this.dbPromise = open();
324
+ }
325
+ async get(namespace, key) {
326
+ const db = await this.dbPromise;
327
+ return new Promise((resolve, reject) => {
328
+ const tx = db.transaction(STORE, "readonly");
329
+ const r = tx.objectStore(STORE).get([namespace, key]);
330
+ r.onsuccess = () => resolve(r.result?.value ?? null);
331
+ r.onerror = () => reject(r.error);
332
+ });
333
+ }
334
+ async put(namespace, key, value) {
335
+ const db = await this.dbPromise;
336
+ return new Promise((resolve, reject) => {
337
+ const tx = db.transaction(STORE, "readwrite");
338
+ tx.objectStore(STORE).put({ ns: namespace, key, value });
339
+ tx.oncomplete = () => resolve();
340
+ tx.onerror = () => reject(tx.error);
341
+ });
342
+ }
343
+ async del(namespace, key) {
344
+ const db = await this.dbPromise;
345
+ return new Promise((resolve, reject) => {
346
+ const tx = db.transaction(STORE, "readwrite");
347
+ tx.objectStore(STORE).delete([namespace, key]);
348
+ tx.oncomplete = () => resolve();
349
+ tx.onerror = () => reject(tx.error);
350
+ });
351
+ }
352
+ /**
353
+ * One `readwrite` transaction for the whole batch. Every request is issued
354
+ * synchronously inside it (an await on anything else would let the
355
+ * transaction auto-commit), so a failure or a crash mid-way aborts all of
356
+ * it: the per-row MLS store relies on that to keep a checkpoint atomic.
357
+ */
358
+ async applyBatch(namespace, puts, deletes) {
359
+ if (puts.length === 0 && deletes.length === 0) return;
360
+ const db = await this.dbPromise;
361
+ return new Promise((resolve, reject) => {
362
+ const tx = db.transaction(STORE, "readwrite");
363
+ let settled = false;
364
+ const fail = (e) => {
365
+ if (settled) return;
366
+ settled = true;
367
+ reject(e instanceof Error ? e : new Error(String(e)));
368
+ };
369
+ tx.oncomplete = () => {
370
+ if (!settled) {
371
+ settled = true;
372
+ resolve();
373
+ }
374
+ };
375
+ tx.onerror = () => fail(tx.error);
376
+ tx.onabort = () => fail(tx.error ?? new Error("applyBatch aborted"));
377
+ try {
378
+ const os = tx.objectStore(STORE);
379
+ for (const [key, value] of puts) os.put({ ns: namespace, key, value });
380
+ for (const key of deletes) os.delete([namespace, key]);
381
+ } catch (e) {
382
+ try {
383
+ tx.abort();
384
+ } catch {
385
+ }
386
+ fail(e);
387
+ }
388
+ });
389
+ }
390
+ /** Every `[key, value]` under `namespace` with the prefix, in one read. */
391
+ async listEntries(namespace, prefix) {
392
+ const db = await this.dbPromise;
393
+ return new Promise((resolve, reject) => {
394
+ const tx = db.transaction(STORE, "readonly");
395
+ const idx = tx.objectStore(STORE).index("ns");
396
+ const req = idx.openCursor(IDBKeyRange.only(namespace));
397
+ const out = [];
398
+ req.onsuccess = () => {
399
+ const cur = req.result;
400
+ if (!cur) return resolve(out);
401
+ const row = cur.value;
402
+ if (!prefix || row.key.startsWith(prefix)) out.push([row.key, row.value]);
403
+ cur.continue();
404
+ };
405
+ req.onerror = () => reject(req.error);
406
+ });
407
+ }
408
+ async listKeys(namespace, prefix) {
409
+ const db = await this.dbPromise;
410
+ return new Promise((resolve, reject) => {
411
+ const tx = db.transaction(STORE, "readonly");
412
+ const idx = tx.objectStore(STORE).index("ns");
413
+ const req = idx.openCursor(IDBKeyRange.only(namespace));
414
+ const out = [];
415
+ req.onsuccess = () => {
416
+ const cur = req.result;
417
+ if (!cur) return resolve(out);
418
+ const row = cur.value;
419
+ if (!prefix || row.key.startsWith(prefix)) out.push(row.key);
420
+ cur.continue();
421
+ };
422
+ req.onerror = () => reject(req.error);
423
+ });
424
+ }
425
+ };
426
+
427
+ // src/wire-contract.ts
428
+ var PING_WIRE_CONTRACT_VERSION = 2;
429
+ var WIRE_VERSION_MIN_ACCEPTED = 1;
430
+ var CONTENT_TYPE_CBOR = "application/vnd.ping.wire.v2+cbor";
431
+ var CONTENT_TYPE_JSON = "application/vnd.ping.wire.v2+json";
432
+ var CONTENT_TYPE_CBOR_LEGACY_V1 = "application/vnd.ping.wire.v1+cbor";
433
+ var CONTENT_TYPE_JSON_LEGACY_V1 = "application/vnd.ping.wire.v1+json";
434
+ var PING_WIRE_CONTRACT_HEADER = "X-Ping-Wire-Contract";
435
+ var PING_WIRE_CONTRACT_HEADER_VALUE = `ping/${PING_WIRE_CONTRACT_VERSION}`;
436
+ var ValidationError = class extends Error {
437
+ constructor(kind, message) {
438
+ super(message);
439
+ this.kind = kind;
440
+ this.name = "PingWireContractValidationError";
441
+ }
442
+ kind;
443
+ };
444
+ var KIND_DISCRIMINANT = {
445
+ Application: 1,
446
+ Commit: 2,
447
+ Welcome: 3,
448
+ Proposal: 4,
449
+ KeyPackage: 5
450
+ };
451
+ async function sha256(bytes) {
452
+ const ab = bytes.buffer.slice(bytes.byteOffset, bytes.byteOffset + bytes.byteLength);
453
+ const hash = await crypto.subtle.digest("SHA-256", ab);
454
+ return new Uint8Array(hash);
455
+ }
456
+ function bytesEqual(a, b) {
457
+ if (a.length !== b.length) return false;
458
+ for (let i = 0; i < a.length; i++) if (a[i] !== b[i]) return false;
459
+ return true;
460
+ }
461
+ async function validate(env) {
462
+ if (env.v < WIRE_VERSION_MIN_ACCEPTED || env.v > PING_WIRE_CONTRACT_VERSION) {
463
+ throw new ValidationError(
464
+ "UnsupportedVersion",
465
+ `unsupported wire-contract version: envelope says v=${env.v}, expected v\u2208[${WIRE_VERSION_MIN_ACCEPTED}, ${PING_WIRE_CONTRACT_VERSION}]`
466
+ );
467
+ }
468
+ if (env.conversation_id.length !== 16) {
469
+ throw new ValidationError(
470
+ "BadConversationIdLen",
471
+ `conversation_id must be 16 bytes (ULID), got ${env.conversation_id.length}`
472
+ );
473
+ }
474
+ if (env.sender_device.length !== 32) {
475
+ throw new ValidationError(
476
+ "BadSenderDeviceLen",
477
+ `sender_device must be 32 bytes, got ${env.sender_device.length}`
478
+ );
479
+ }
480
+ if (env.v >= 2 && env.kind === "Application") {
481
+ return;
482
+ }
483
+ const buf = new Uint8Array(1 + env.payload.length);
484
+ buf[0] = KIND_DISCRIMINANT[env.kind];
485
+ buf.set(env.payload, 1);
486
+ const computed = await sha256(buf);
487
+ if (!bytesEqual(computed, env.content_hash)) {
488
+ throw new ValidationError(
489
+ "ContentHashMismatch",
490
+ "content_hash mismatch: envelope is forged, corrupted, or built by a non-conformant sender"
491
+ );
492
+ }
493
+ }
494
+ async function verifyApplicationContentHash(env, plaintext) {
495
+ if (env.v < 2 || env.kind !== "Application") return;
496
+ const computed = await sha256(plaintext);
497
+ if (!bytesEqual(computed, env.content_hash)) {
498
+ throw new ValidationError(
499
+ "ContentHashMismatch",
500
+ "v=2 application content_hash mismatch against decrypted plaintext"
501
+ );
502
+ }
503
+ }
504
+ function negotiates(contentType) {
505
+ if (!contentType) return false;
506
+ const primary = contentType.split(";")[0]?.trim().toLowerCase() ?? "";
507
+ return primary === CONTENT_TYPE_CBOR || primary === CONTENT_TYPE_JSON || primary === CONTENT_TYPE_CBOR_LEGACY_V1 || primary === CONTENT_TYPE_JSON_LEGACY_V1;
508
+ }
509
+
510
+ // src/transport/websocket.ts
511
+ var WebSocketTransport = class {
512
+ constructor(cfg) {
513
+ this.cfg = cfg;
514
+ this.fetchImpl = cfg.fetchImpl ?? globalThis.fetch.bind(globalThis);
515
+ this.openSocket();
516
+ }
517
+ cfg;
518
+ ws = null;
519
+ liveHandlers = /* @__PURE__ */ new Set();
520
+ fetchImpl;
521
+ openSocket() {
522
+ if (typeof WebSocket === "undefined") return;
523
+ const url = `${this.cfg.baseUrl.replace(/^http/, "ws")}/stream`;
524
+ this.ws = new WebSocket(url);
525
+ this.ws.onmessage = (ev) => {
526
+ const text = typeof ev.data === "string" ? ev.data : new TextDecoder().decode(ev.data);
527
+ try {
528
+ const env = JSON.parse(text, reviver);
529
+ for (const h of this.liveHandlers) h(env);
530
+ } catch (e) {
531
+ if (typeof console !== "undefined") console.debug("[ping-sdk] WS frame parse error:", e);
532
+ }
533
+ };
534
+ this.ws.onclose = () => setTimeout(() => this.openSocket(), 1e3);
535
+ }
536
+ async send(envelope) {
537
+ const res = await this.fetchImpl(`${this.cfg.baseUrl}/send`, {
538
+ method: "POST",
539
+ headers: {
540
+ "content-type": CONTENT_TYPE_JSON,
541
+ [PING_WIRE_CONTRACT_HEADER]: PING_WIRE_CONTRACT_HEADER_VALUE,
542
+ ...this.cfg.authHeader ? { authorization: this.cfg.authHeader } : {}
543
+ },
544
+ body: JSON.stringify(envelope, replacer)
545
+ });
546
+ if (res.status === 409) throw new Error("EpochOccupied");
547
+ if (!res.ok) throw new Error(`transport send failed: ${res.status}`);
548
+ }
549
+ async fetchSince(conversationId, cursor, limit) {
550
+ const url = new URL(`${this.cfg.baseUrl}/sync`);
551
+ url.searchParams.set("conv", toHex(conversationId));
552
+ url.searchParams.set("cursor", btoaUrl(cursor));
553
+ url.searchParams.set("limit", String(limit));
554
+ const res = await this.fetchImpl(url.toString(), {
555
+ headers: { ...this.cfg.authHeader ? { authorization: this.cfg.authHeader } : {} }
556
+ });
557
+ if (!res.ok) throw new Error(`transport fetch failed: ${res.status}`);
558
+ const text = await res.text();
559
+ return JSON.parse(text, reviver);
560
+ }
561
+ subscribe(onEvent) {
562
+ this.liveHandlers.add(onEvent);
563
+ return { unsubscribe: () => this.liveHandlers.delete(onEvent) };
564
+ }
565
+ async discoverDevices(userId) {
566
+ const res = await this.fetchImpl(`${this.cfg.baseUrl}/devices/${toHex(userId)}`, {
567
+ headers: { ...this.cfg.authHeader ? { authorization: this.cfg.authHeader } : {} }
568
+ });
569
+ if (!res.ok) throw new Error(`device discovery failed: ${res.status}`);
570
+ const text = await res.text();
571
+ return JSON.parse(text, reviver);
572
+ }
573
+ };
574
+ function replacer(_k, v) {
575
+ if (v instanceof Uint8Array) return { _bytes: Array.from(v) };
576
+ return v;
577
+ }
578
+ function reviver(_k, v) {
579
+ if (v && typeof v === "object" && Array.isArray(v._bytes)) {
580
+ return new Uint8Array(v._bytes);
581
+ }
582
+ return v;
583
+ }
584
+ function toHex(b) {
585
+ let s = "";
586
+ for (const v of b) s += v.toString(16).padStart(2, "0");
587
+ return s;
588
+ }
589
+ function btoaUrl(b) {
590
+ let s = "";
591
+ for (const v of b) s += String.fromCharCode(v);
592
+ return btoa(s).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
593
+ }
594
+
595
+ // src/wasm-memory.ts
596
+ var RESERVE_MIB_TARGETS = [192, 128, 64, 32];
597
+ var WASM_PAGE_BYTES = 64 * 1024;
598
+ var reserved = /* @__PURE__ */ new WeakSet();
599
+ function reserveLinearMemory(memory) {
600
+ if (reserved.has(memory)) return;
601
+ reserved.add(memory);
602
+ for (const mib of RESERVE_MIB_TARGETS) {
603
+ try {
604
+ memory.grow(mib * 1024 * 1024 / WASM_PAGE_BYTES);
605
+ return;
606
+ } catch {
607
+ }
608
+ }
609
+ }
610
+
611
+ // src/notification-preview.ts
612
+ async function openNotificationPreview(opts) {
613
+ const now = opts.now ?? (() => Date.now());
614
+ const scoped = opts.accountNamespace !== void 0 && opts.accountNamespace.length > 0 ? scopeStorage(opts.storage, opts.accountNamespace) : opts.storage;
615
+ const storage = readOnlyStorage(scoped);
616
+ const wasm = await import("../wasm/ping_wasm");
617
+ const out = await wasm.default(
618
+ opts.wasmModuleOrPath === void 0 ? void 0 : { module_or_path: opts.wasmModuleOrPath }
619
+ );
620
+ reserveLinearMemory(out.memory);
621
+ const client = await wasm.PingClient.openReadOnly(
622
+ opts.identityExport,
623
+ // Label is unused on the read-only path (no LocalDevice is ever minted).
624
+ "notification-preview",
625
+ storage,
626
+ silentTransport(),
627
+ now()
628
+ );
629
+ let closed = false;
630
+ return {
631
+ async previewEnvelope(envelope) {
632
+ if (closed) throw new Error("notification-preview session is closed");
633
+ const result = client.previewEnvelope(envelope, now());
634
+ return result ?? null;
635
+ },
636
+ close() {
637
+ if (closed) return;
638
+ closed = true;
639
+ client.free();
640
+ }
641
+ };
642
+ }
643
+ function readOnlyStorage(storage) {
644
+ const refuse = (op) => Promise.reject(
645
+ new Error(`notification-preview storage is read-only (attempted ${op})`)
646
+ );
647
+ const readOnly = {
648
+ get: (ns, key) => storage.get(ns, key),
649
+ put: (_ns, _key, _value) => refuse("put"),
650
+ del: (_ns, _key) => refuse("del"),
651
+ listKeys: (ns, prefix) => storage.listKeys(ns, prefix)
652
+ };
653
+ const hostListEntries = storage.listEntries;
654
+ if (typeof hostListEntries === "function") {
655
+ readOnly.listEntries = (ns, prefix) => hostListEntries.call(storage, ns, prefix);
656
+ }
657
+ return readOnly;
658
+ }
659
+ function silentTransport() {
660
+ return {
661
+ send: () => Promise.reject(new Error("notification-preview cannot send")),
662
+ fetchSince: () => Promise.resolve([]),
663
+ discoverDevices: () => Promise.resolve([]),
664
+ setNextWelcomeRecipients: () => Promise.resolve()
665
+ };
666
+ }
667
+
668
+ // src/index.ts
669
+ var MessagingClient = class _MessagingClient {
670
+ worker;
671
+ nextId = 1;
672
+ pending = /* @__PURE__ */ new Map();
673
+ storage;
674
+ transport;
675
+ now;
676
+ /** `onMessage` / `onMessageBatch` handlers and the guarded delivery to them. */
677
+ fanout = new MessageFanout();
678
+ conversationHandlers = /* @__PURE__ */ new Set();
679
+ subscription = null;
680
+ metaCache = /* @__PURE__ */ new Map();
681
+ /**
682
+ * Per-conversation batching of sequenced live frames: the first frame goes
683
+ * to the worker at once, frames that arrive while that batch is in flight
684
+ * go out as ONE `processSequencedBatch` when it returns. See
685
+ * {@link dispatchIncoming}.
686
+ */
687
+ coalescer = new InboundCoalescer(
688
+ (_key, items) => this.applyLiveBatch(items)
689
+ );
690
+ /** Single-flight gap fills, one `syncConversationStep` loop per conversation. */
691
+ gapFiller = new GapFiller();
692
+ /** Set by {@link close}: every later call rejects instead of hanging. */
693
+ closed = false;
694
+ // Cached at init() so dispatchIncoming can skip envelopes we sent ourselves — the relay
695
+ // broadcasts to all WS subscribers including the sender, and re-applying our own already-
696
+ // merged commits would error with "epoch differs".
697
+ ownDeviceId = null;
698
+ /**
699
+ * Per-conversation dispatch chains. See {@link dispatchIncoming}.
700
+ *
701
+ * Keyed by lowercase-hex conversation id. Bounded: a chain is deleted the
702
+ * moment it settles and is still the tail, so an account with thousands of
703
+ * conversations holds at most one entry per conversation with work IN FLIGHT,
704
+ * not one per conversation it has ever seen.
705
+ */
706
+ dispatchChains = /* @__PURE__ */ new Map();
707
+ constructor(cfg, worker) {
708
+ this.worker = worker;
709
+ this.storage = cfg.accountNamespace !== void 0 && cfg.accountNamespace.length > 0 ? scopeStorage(cfg.storage, cfg.accountNamespace) : cfg.storage;
710
+ this.transport = cfg.transport;
711
+ this.now = cfg.now ?? (() => Date.now());
712
+ this.worker.onmessage = (ev) => this.handleWorker(ev.data);
713
+ this.worker.onerror = () => this.failPending(new MessagingClientClosedError("worker-error"));
714
+ }
715
+ /** Generate a fresh identity. The returned bytes are a secret — store them encrypted. */
716
+ static async generateIdentity() {
717
+ return _MessagingClient.ephemeralWorkerCall({
718
+ kind: "generateIdentity",
719
+ id: 1
720
+ });
721
+ }
722
+ /**
723
+ * HPKE-seal a `LinkingTicket` for delivery to a new device ([CR-3]).
724
+ *
725
+ * Returns CBOR-encoded bytes safe to relay through an untrusted inbox. The new device's
726
+ * X25519 public key (`newDevicePub`) is exchanged out-of-band — typically as part of a
727
+ * QR-encoded handshake on the linking screen. Pure function; runs in an ephemeral
728
+ * worker so no live `MessagingClient` is required on the sender side.
729
+ *
730
+ * Suite: `DHKEM(X25519, HKDF-SHA256), HKDF-SHA256, AES-128-GCM` (matches MLS).
731
+ */
732
+ static async sealLinkingTicket(ticket, newDevicePub) {
733
+ if (newDevicePub.length !== 32) {
734
+ throw new Error("sealLinkingTicket: newDevicePub must be 32 bytes");
735
+ }
736
+ return _MessagingClient.ephemeralWorkerCall({
737
+ kind: "sealLinkingTicket",
738
+ id: 1,
739
+ ticket,
740
+ newDevicePub
741
+ });
742
+ }
743
+ /**
744
+ * HPKE-open a sealed `LinkingTicket` on the new device ([CR-3]).
745
+ *
746
+ * The receiving device hasn't booted a `MessagingClient` yet — it only has its X25519
747
+ * ephemeral keypair. This static method runs the open in an ephemeral worker, returning
748
+ * the cleartext ticket which the host then feeds to `init()` + `consumeLinkingTicket()`.
749
+ *
750
+ * On failure the error message is deliberately generic (no discriminator between "wrong
751
+ * key" vs "tampered ciphertext") so a probing attacker can't tell the new device's key
752
+ * was the issue.
753
+ */
754
+ static async openLinkingTicket(sealed, newDevicePriv) {
755
+ if (newDevicePriv.length !== 32) {
756
+ throw new Error("openLinkingTicket: newDevicePriv must be 32 bytes");
757
+ }
758
+ return _MessagingClient.ephemeralWorkerCall({
759
+ kind: "openLinkingTicket",
760
+ id: 1,
761
+ sealed,
762
+ newDevicePriv
763
+ });
764
+ }
765
+ /**
766
+ * Generic HPKE-Base seal of arbitrary bytes to `recipientPub` (32-byte X25519)
767
+ * under a caller-supplied `info`. One shared HPKE implementation so app layers
768
+ * (e.g. the device-linking auth envelope) stop hand-rolling per-platform HPKE
769
+ * that drifts and breaks cross-platform. Runs in an ephemeral worker.
770
+ */
771
+ static async hpkeSeal(plaintext, recipientPub, info) {
772
+ if (recipientPub.length !== 32) {
773
+ throw new Error("hpkeSeal: recipientPub must be 32 bytes");
774
+ }
775
+ return _MessagingClient.ephemeralWorkerCall({
776
+ kind: "hpkeSeal",
777
+ id: 1,
778
+ plaintext,
779
+ recipientPub,
780
+ info
781
+ });
782
+ }
783
+ /** Generic HPKE-Base open — inverse of {@link hpkeSeal}. `info` must match the sender. */
784
+ static async hpkeOpen(sealed, recipientPriv, info) {
785
+ if (recipientPriv.length !== 32) {
786
+ throw new Error("hpkeOpen: recipientPriv must be 32 bytes");
787
+ }
788
+ return _MessagingClient.ephemeralWorkerCall({
789
+ kind: "hpkeOpen",
790
+ id: 1,
791
+ sealed,
792
+ recipientPriv,
793
+ info
794
+ });
795
+ }
796
+ /**
797
+ * HPKE-Base seal in the RFC 9180 CANONICAL layout, `enc || ct||tag`, with no
798
+ * CBOR wrapper.
799
+ *
800
+ * Use this, not {@link hpkeSeal}, for anything the app layers already speak.
801
+ * `hpkeSeal` wraps its output in CBOR `{v, enc, ct}` for the linking ticket,
802
+ * and because that could not read the RFC layout, iOS, Android, web and the
803
+ * third-party `ping-notify` sender each ended up hand-composing their own
804
+ * HPKE for the same suite. This is the one they agree on.
805
+ */
806
+ static async hpkeSealRaw(plaintext, recipientPub, info) {
807
+ if (recipientPub.length !== 32) {
808
+ throw new Error("hpkeSealRaw: recipientPub must be 32 bytes");
809
+ }
810
+ return _MessagingClient.ephemeralWorkerCall({
811
+ kind: "hpkeSealRaw",
812
+ id: 1,
813
+ plaintext,
814
+ recipientPub,
815
+ info
816
+ });
817
+ }
818
+ /**
819
+ * Inverse of {@link hpkeSealRaw}. `info` must match the sender's.
820
+ *
821
+ * Rejects with one uniform error whatever went wrong. This opens bytes from
822
+ * an unauthenticated inbox, so a caller that could tell "wrong key" from
823
+ * "tampered" from "truncated" would be an oracle for whoever wrote them.
824
+ */
825
+ static async hpkeOpenRaw(sealed, recipientPriv, info) {
826
+ if (recipientPriv.length !== 32) {
827
+ throw new Error("hpkeOpenRaw: recipientPriv must be 32 bytes");
828
+ }
829
+ return _MessagingClient.ephemeralWorkerCall({
830
+ kind: "hpkeOpenRaw",
831
+ id: 1,
832
+ sealed,
833
+ recipientPriv,
834
+ info
835
+ });
836
+ }
837
+ /**
838
+ * A fresh X25519 keypair for the suite.
839
+ *
840
+ * Exposed so a caller minting a recipient key (a Ping Notify inbox, a linking
841
+ * handshake) does not reach for WebCrypto to do it, which is the same problem
842
+ * one layer down.
843
+ */
844
+ static async hpkeGenerateKeypair() {
845
+ const both = await _MessagingClient.ephemeralWorkerCall({
846
+ kind: "hpkeGenerateKeypair",
847
+ id: 1
848
+ });
849
+ if (both.length !== 64) {
850
+ throw new Error("hpkeGenerateKeypair: expected 64 bytes");
851
+ }
852
+ return { publicKey: both.slice(0, 32), privateKey: both.slice(32) };
853
+ }
854
+ // ---- Post-quantum HPKE (X-Wing), docs/POST_QUANTUM.md phase 2 ----
855
+ //
856
+ // The `Pq` twins of the functions above: HPKE with KEM X-Wing draft-06
857
+ // (ML-KEM-768 + X25519), HKDF-SHA256, AES-128-GCM. A public key is
858
+ // {@link HPKE_PQ_PUBLIC_KEY_BYTES} bytes, `enc` {@link HPKE_PQ_ENC_BYTES}, the
859
+ // private key a 32-byte seed. These are what the pairing, link-auth,
860
+ // history-transfer and app-inbox flows use from phase 2 on; the classical
861
+ // forms stay for app inboxes created with a 32-byte key before the roll. A
862
+ // classical private key and an X-Wing seed are both 32 bytes but are NOT
863
+ // interchangeable: the host knows which family a stored key belongs to.
864
+ /**
865
+ * HPKE-seal a `LinkingTicket` under the new device's X-Wing public key
866
+ * ([CR-3], post-quantum). CBOR `{v: 2, enc, ct}` under `ping/link/v2`; the
867
+ * classical {@link openLinkingTicket} refuses it and {@link openLinkingTicketPq}
868
+ * refuses a `v: 1` blob, so there is no downgrade in either direction.
869
+ */
870
+ static async sealLinkingTicketPq(ticket, newDevicePub) {
871
+ if (newDevicePub.length !== HPKE_PQ_PUBLIC_KEY_BYTES) {
872
+ throw new Error(`sealLinkingTicketPq: newDevicePub must be ${HPKE_PQ_PUBLIC_KEY_BYTES} bytes`);
873
+ }
874
+ return _MessagingClient.ephemeralWorkerCall({
875
+ kind: "sealLinkingTicketPq",
876
+ id: 1,
877
+ ticket,
878
+ newDevicePub
879
+ });
880
+ }
881
+ /**
882
+ * HPKE-open a sealed `v: 2` ticket with the new device's 32-byte X-Wing seed
883
+ * ([CR-3], post-quantum). The error is deliberately generic, like
884
+ * {@link openLinkingTicket}.
885
+ */
886
+ static async openLinkingTicketPq(sealed, newDevicePriv) {
887
+ if (newDevicePriv.length !== 32) {
888
+ throw new Error("openLinkingTicketPq: newDevicePriv must be 32 bytes");
889
+ }
890
+ return _MessagingClient.ephemeralWorkerCall({
891
+ kind: "openLinkingTicketPq",
892
+ id: 1,
893
+ sealed,
894
+ newDevicePriv
895
+ });
896
+ }
897
+ /** Post-quantum {@link hpkeSeal}: CBOR-wrapped (`v: 2`), `recipientPub` is 1216 bytes. */
898
+ static async hpkeSealPq(plaintext, recipientPub, info) {
899
+ if (recipientPub.length !== HPKE_PQ_PUBLIC_KEY_BYTES) {
900
+ throw new Error(`hpkeSealPq: recipientPub must be ${HPKE_PQ_PUBLIC_KEY_BYTES} bytes`);
901
+ }
902
+ return _MessagingClient.ephemeralWorkerCall({
903
+ kind: "hpkeSealPq",
904
+ id: 1,
905
+ plaintext,
906
+ recipientPub,
907
+ info
908
+ });
909
+ }
910
+ /** Inverse of {@link hpkeSealPq}. `recipientPriv` is the 32-byte seed; `info` must match. */
911
+ static async hpkeOpenPq(sealed, recipientPriv, info) {
912
+ if (recipientPriv.length !== 32) {
913
+ throw new Error("hpkeOpenPq: recipientPriv must be 32 bytes");
914
+ }
915
+ return _MessagingClient.ephemeralWorkerCall({
916
+ kind: "hpkeOpenPq",
917
+ id: 1,
918
+ sealed,
919
+ recipientPriv,
920
+ info
921
+ });
922
+ }
923
+ /**
924
+ * Post-quantum {@link hpkeSealRaw}: RFC 9180 canonical `enc(1120) || ct || tag`.
925
+ * The `v2` form of every app-layer envelope (`ping/link-auth/v2`,
926
+ * `ping/app-inbox/v2`).
927
+ */
928
+ static async hpkeSealRawPq(plaintext, recipientPub, info) {
929
+ if (recipientPub.length !== HPKE_PQ_PUBLIC_KEY_BYTES) {
930
+ throw new Error(`hpkeSealRawPq: recipientPub must be ${HPKE_PQ_PUBLIC_KEY_BYTES} bytes`);
931
+ }
932
+ return _MessagingClient.ephemeralWorkerCall({
933
+ kind: "hpkeSealRawPq",
934
+ id: 1,
935
+ plaintext,
936
+ recipientPub,
937
+ info
938
+ });
939
+ }
940
+ /** Inverse of {@link hpkeSealRawPq}. One uniform error, as for {@link hpkeOpenRaw}. */
941
+ static async hpkeOpenRawPq(sealed, recipientPriv, info) {
942
+ if (recipientPriv.length !== 32) {
943
+ throw new Error("hpkeOpenRawPq: recipientPriv must be 32 bytes");
944
+ }
945
+ return _MessagingClient.ephemeralWorkerCall({
946
+ kind: "hpkeOpenRawPq",
947
+ id: 1,
948
+ sealed,
949
+ recipientPriv,
950
+ info
951
+ });
952
+ }
953
+ /**
954
+ * A fresh X-Wing keypair: `publicKey` is {@link HPKE_PQ_PUBLIC_KEY_BYTES} bytes,
955
+ * `privateKey` the 32-byte seed. Persist only the seed and recompute the public
956
+ * half with {@link hpkePublicKeyFromSeed}; wipe both buffers when done.
957
+ */
958
+ static async hpkeGenerateKeypairPq() {
959
+ const both = await _MessagingClient.ephemeralWorkerCall({
960
+ kind: "hpkeGenerateKeypairPq",
961
+ id: 1
962
+ });
963
+ if (both.length !== HPKE_PQ_PUBLIC_KEY_BYTES + 32) {
964
+ throw new Error(`hpkeGenerateKeypairPq: expected ${HPKE_PQ_PUBLIC_KEY_BYTES + 32} bytes`);
965
+ }
966
+ return {
967
+ publicKey: both.slice(0, HPKE_PQ_PUBLIC_KEY_BYTES),
968
+ privateKey: both.slice(HPKE_PQ_PUBLIC_KEY_BYTES)
969
+ };
970
+ }
971
+ /**
972
+ * The X-Wing public key for a stored 32-byte seed. Deterministic: the pairing
973
+ * code carries SHA-256 of exactly these bytes, so what a device advertises
974
+ * always matches what it will open with.
975
+ */
976
+ static async hpkePublicKeyFromSeed(seed) {
977
+ if (seed.length !== 32) {
978
+ throw new Error("hpkePublicKeyFromSeed: seed must be 32 bytes");
979
+ }
980
+ return _MessagingClient.ephemeralWorkerCall({
981
+ kind: "hpkePublicKeyFromSeed",
982
+ id: 1,
983
+ seed
984
+ });
985
+ }
986
+ /**
987
+ * The id of an account's DeviceGroup (the private sync group of the
988
+ * account's own devices), derived by the SDK core from the account's MLS
989
+ * user id: `userId` is `client.userId()` (32 bytes), NOT the server's
990
+ * account id. Deterministic: every device of the account derives the same
991
+ * id, so a host recognises the DeviceGroup without copying the derivation.
992
+ * Stateless (no client needed); bytes that are not an MLS user id derive an
993
+ * id no device uses.
994
+ */
995
+ static async deviceGroupIdFor(userId) {
996
+ return _MessagingClient.ephemeralWorkerCall({
997
+ kind: "deviceGroupIdFor",
998
+ id: 1,
999
+ userId
1000
+ });
1001
+ }
1002
+ /** The 32-byte X25519 public key for a stored classical private key. */
1003
+ static async hpkePublicKeyFromPrivate(privateKey) {
1004
+ if (privateKey.length !== 32) {
1005
+ throw new Error("hpkePublicKeyFromPrivate: privateKey must be 32 bytes");
1006
+ }
1007
+ return _MessagingClient.ephemeralWorkerCall({
1008
+ kind: "hpkePublicKeyFromPrivate",
1009
+ id: 1,
1010
+ privateKey
1011
+ });
1012
+ }
1013
+ /**
1014
+ * Answer a device re-authentication challenge (`POST /v1/auth/device/challenge`) with
1015
+ * the device signing key, so a device whose session tokens are gone or dead gets fresh
1016
+ * ones for the SAME device without a code (`POST /v1/auth/device/verify`).
1017
+ *
1018
+ * The SDK builds the signed bytes itself (`"ping/device-reauth/v1" || challengeId ||
1019
+ * nonce || deviceId || accountId || audience`), so this cannot sign anything else with
1020
+ * the device key. `deviceSigningSecretKey` is the 32-byte secret the host passes as
1021
+ * `deviceSigningSecretKey` to {@link init}; `challengeId` (16 bytes) and `nonce`
1022
+ * (32 bytes) come from the challenge response. `accountId` (16 bytes) is the account
1023
+ * the host stored with its session; the server refuses a proof for any other account,
1024
+ * so send the same id with the proof. `audience` is the canonical origin of the API
1025
+ * THIS host is configured to reach (`new URL(apiBase).origin`, for example
1026
+ * `https://api-prod.ping.live`), never the value the server returned: that is what
1027
+ * makes a challenge relayed from another deployment useless there. The returned
1028
+ * `deviceId` is SHA-256 of the key's public half; send it with the signature.
1029
+ *
1030
+ * Rejects wrong widths and a non-canonical audience. Runs in an ephemeral worker.
1031
+ */
1032
+ static async signDeviceReauth(params) {
1033
+ const { deviceSigningSecretKey, challengeId, nonce, accountId, audience } = params;
1034
+ if (deviceSigningSecretKey.length !== 32) {
1035
+ throw new Error("signDeviceReauth: deviceSigningSecretKey must be 32 bytes");
1036
+ }
1037
+ if (challengeId.length !== 16) {
1038
+ throw new Error("signDeviceReauth: challengeId must be 16 bytes");
1039
+ }
1040
+ if (nonce.length !== 32) {
1041
+ throw new Error("signDeviceReauth: nonce must be 32 bytes");
1042
+ }
1043
+ if (accountId.length !== 16) {
1044
+ throw new Error("signDeviceReauth: accountId must be 16 bytes");
1045
+ }
1046
+ const both = await _MessagingClient.ephemeralWorkerCall({
1047
+ kind: "signDeviceReauth",
1048
+ id: 1,
1049
+ deviceSigningSecretKey,
1050
+ challengeId,
1051
+ nonce,
1052
+ accountId,
1053
+ audience
1054
+ });
1055
+ if (both.length !== 96) {
1056
+ throw new Error("signDeviceReauth: expected 96 bytes");
1057
+ }
1058
+ return { deviceId: both.slice(0, 32), signature: both.slice(32) };
1059
+ }
1060
+ /**
1061
+ * Link verification v2, on the APPROVING device: approve ONE new device on ONE
1062
+ * server link session (`POST /v1/auth/link/sessions` returned `approvalSessionId`)
1063
+ * with this device's signing key. The new device sends the result with its own
1064
+ * {@link signDeviceLinkPossession} proof to `POST /v1/auth/link/verify`.
1065
+ *
1066
+ * The SDK builds the signed bytes itself (`"ping/device-link-approve/v1" ||
1067
+ * approvalSessionId || accountId || approverDeviceId || newDeviceId ||
1068
+ * newDevicePubkey || audience`, see docs/DEVICE_LINK_V2_VECTORS.md) and derives
1069
+ * both device ids from the keys, so this cannot sign anything else with the device
1070
+ * key. `deviceSigningSecretKey` is the 32-byte seed the host holds for THIS device
1071
+ * (the one registered as its device signing key); `accountId` (16 bytes) is the
1072
+ * account stored with this device's session; `newDevicePubkey` (32 bytes) is the
1073
+ * new device's key from its handshake; `audience` is the canonical origin of the API
1074
+ * THIS host is configured to reach (`new URL(apiBase).origin`), as for
1075
+ * {@link signDeviceReauth}.
1076
+ *
1077
+ * Rejects wrong widths, a non-canonical audience, a new key that is not a canonical
1078
+ * Ed25519 point outside the small-order subgroup, and this device's own key. Runs in
1079
+ * an ephemeral worker.
1080
+ */
1081
+ static async signDeviceLinkApproval(params) {
1082
+ const { deviceSigningSecretKey, approvalSessionId, accountId, newDevicePubkey, audience } = params;
1083
+ if (deviceSigningSecretKey.length !== 32) {
1084
+ throw new Error("signDeviceLinkApproval: deviceSigningSecretKey must be 32 bytes");
1085
+ }
1086
+ if (approvalSessionId.length !== 16) {
1087
+ throw new Error("signDeviceLinkApproval: approvalSessionId must be 16 bytes");
1088
+ }
1089
+ if (accountId.length !== 16) {
1090
+ throw new Error("signDeviceLinkApproval: accountId must be 16 bytes");
1091
+ }
1092
+ if (newDevicePubkey.length !== 32) {
1093
+ throw new Error("signDeviceLinkApproval: newDevicePubkey must be 32 bytes");
1094
+ }
1095
+ const all = await _MessagingClient.ephemeralWorkerCall({
1096
+ kind: "signDeviceLinkApproval",
1097
+ id: 1,
1098
+ deviceSigningSecretKey,
1099
+ approvalSessionId,
1100
+ accountId,
1101
+ newDevicePubkey,
1102
+ audience
1103
+ });
1104
+ if (all.length !== 128) {
1105
+ throw new Error("signDeviceLinkApproval: expected 128 bytes");
1106
+ }
1107
+ return {
1108
+ approverDeviceId: all.slice(0, 32),
1109
+ newDeviceId: all.slice(32, 64),
1110
+ signature: all.slice(64)
1111
+ };
1112
+ }
1113
+ /**
1114
+ * Link verification v2, on the NEW device: prove that this device holds the key the
1115
+ * link session names (`"ping/device-link-possess/v1" || approvalSessionId ||
1116
+ * accountId || deviceId || audience`). `deviceSigningSecretKey` is this device's own
1117
+ * 32-byte seed (the key its handshake advertised); `approvalSessionId` and
1118
+ * `accountId` come from the approving device's sealed envelope; `audience` as for
1119
+ * {@link signDeviceReauth}. Check `approval.newDeviceId` equals the returned
1120
+ * `deviceId` before verifying: a substituted handshake is refused locally.
1121
+ *
1122
+ * Rejects wrong widths and a non-canonical audience. Runs in an ephemeral worker.
1123
+ */
1124
+ static async signDeviceLinkPossession(params) {
1125
+ const { deviceSigningSecretKey, approvalSessionId, accountId, audience } = params;
1126
+ if (deviceSigningSecretKey.length !== 32) {
1127
+ throw new Error("signDeviceLinkPossession: deviceSigningSecretKey must be 32 bytes");
1128
+ }
1129
+ if (approvalSessionId.length !== 16) {
1130
+ throw new Error("signDeviceLinkPossession: approvalSessionId must be 16 bytes");
1131
+ }
1132
+ if (accountId.length !== 16) {
1133
+ throw new Error("signDeviceLinkPossession: accountId must be 16 bytes");
1134
+ }
1135
+ const both = await _MessagingClient.ephemeralWorkerCall({
1136
+ kind: "signDeviceLinkPossession",
1137
+ id: 1,
1138
+ deviceSigningSecretKey,
1139
+ approvalSessionId,
1140
+ accountId,
1141
+ audience
1142
+ });
1143
+ if (both.length !== 96) {
1144
+ throw new Error("signDeviceLinkPossession: expected 96 bytes");
1145
+ }
1146
+ return { deviceId: both.slice(0, 32), signature: both.slice(32) };
1147
+ }
1148
+ // Spawn-call-terminate helper for stateless WASM functions exposed at module scope (no
1149
+ // PingClient required). Each call gets a fresh worker; the cost is acceptable because
1150
+ // these are one-shot, off-the-hot-path operations (identity gen, linking ticket seal/open).
1151
+ //
1152
+ // The returned promise ALWAYS settles and the worker is ALWAYS terminated: on its
1153
+ // result, on a worker `error` (the script failed to load or import, or threw at top
1154
+ // level), on a `messageerror` (a reply that could not be deserialised), and when the
1155
+ // worker cannot be created or the request cannot be posted. Only `onmessage` used to be
1156
+ // wired, so a worker that failed to load left `generateIdentity()` pending forever and
1157
+ // the worker alive.
1158
+ static ephemeralWorkerCall(req) {
1159
+ let w;
1160
+ try {
1161
+ w = new Worker(new URL("./worker.js", import.meta.url), { type: "module" });
1162
+ } catch {
1163
+ return Promise.reject(new EphemeralWorkerError("spawn"));
1164
+ }
1165
+ return new Promise((resolve, reject) => {
1166
+ let settled = false;
1167
+ const settle = (finish) => {
1168
+ if (settled) return;
1169
+ settled = true;
1170
+ w.onmessage = null;
1171
+ w.onerror = null;
1172
+ w.onmessageerror = null;
1173
+ w.terminate();
1174
+ finish();
1175
+ };
1176
+ w.onmessage = (ev) => {
1177
+ const msg = ev.data;
1178
+ if (msg.kind === "result" && msg.id === req.id) {
1179
+ settle(() => msg.ok ? resolve(msg.value) : reject(new Error(msg.error)));
1180
+ }
1181
+ };
1182
+ w.onerror = () => settle(() => reject(new EphemeralWorkerError("error")));
1183
+ w.onmessageerror = () => settle(() => reject(new EphemeralWorkerError("messageerror")));
1184
+ try {
1185
+ w.postMessage(req);
1186
+ } catch {
1187
+ settle(() => reject(new EphemeralWorkerError("post")));
1188
+ }
1189
+ });
1190
+ }
1191
+ static async init(cfg) {
1192
+ const worker = new Worker(new URL("./worker.js", import.meta.url), { type: "module" });
1193
+ const client = new _MessagingClient(cfg, worker);
1194
+ const transportFeatures = {
1195
+ fetchLogSince: typeof cfg.transport.fetchLogSince === "function",
1196
+ fetchLogHeads: typeof cfg.transport.fetchLogHeads === "function"
1197
+ };
1198
+ const storageFeatures = storageFeaturesOf(client.storage);
1199
+ await client.call({
1200
+ kind: "init",
1201
+ id: client.nextId++,
1202
+ identityExport: cfg.identityExport,
1203
+ deviceLabel: cfg.deviceLabel,
1204
+ nowMs: client.now(),
1205
+ ...cfg.deviceSigningSecretKey ? { deviceSigningSecretKey: cfg.deviceSigningSecretKey } : {},
1206
+ ...cfg.expectedOwners ? { expectedOwners: cfg.expectedOwners } : {},
1207
+ transportFeatures,
1208
+ storageFeatures
1209
+ });
1210
+ client.ownDeviceId = await client.deviceId();
1211
+ client.subscription = cfg.transport.subscribe(
1212
+ (frame) => client.dispatchIncoming(frame)
1213
+ );
1214
+ return client;
1215
+ }
1216
+ /**
1217
+ * Internal: route an inbound envelope to the right handler, IN ARRIVAL ORDER
1218
+ * PER CONVERSATION.
1219
+ *
1220
+ * ## Why the ordering is load-bearing
1221
+ *
1222
+ * A group invitation arrives as a Welcome immediately followed by the
1223
+ * inviter's hydration Application messages (group title, roster, avatar id).
1224
+ * `joinConversation` is asynchronous — it is several round trips to the WASM
1225
+ * worker — so a naive `void dispatchIncoming(...)` per frame let the
1226
+ * Applications reach `processEnvelope` while the join was still in flight.
1227
+ * The conversation did not exist yet, so every one of them was dropped with
1228
+ * "envelope drop: unknown conversation".
1229
+ *
1230
+ * That loss is PERMANENT and silent: MLS ratchets forward, the transport has
1231
+ * already marked the frames seen and advanced its cursor, and the server will
1232
+ * not resend them. The visible symptom was an invitation landing as an
1233
+ * unnamed "New chat" with no avatar and no roster, and — for the same reason —
1234
+ * a rename, avatar change, member add/remove or role change being lost
1235
+ * whenever it happened to land while a join or another commit for that group
1236
+ * was still being applied.
1237
+ *
1238
+ * Chaining PER CONVERSATION (not globally) is deliberate: MLS state is
1239
+ * per-group, so that is the granularity correctness actually requires, and a
1240
+ * busy conversation must not be able to head-of-line block every other one.
1241
+ * The chain is built synchronously on entry, so chain order is exactly frame
1242
+ * arrival order.
1243
+ *
1244
+ * ## Sequenced frames
1245
+ *
1246
+ * A frame that carries its server position (`{ envelope, serverSeq }`,
1247
+ * `serverSeq > 0`) does not need the chain: the core applies it at its
1248
+ * position, holds it ahead of a hole and drops it at or below what was
1249
+ * applied, whatever order it arrived in. What it needs is BATCHING: one
1250
+ * MLS checkpoint and one host transaction per burst instead of one per
1251
+ * frame. So the first frame for a conversation goes to the worker at once
1252
+ * as a batch of one, and frames that arrive while that batch is in flight
1253
+ * accumulate and go out as ONE `processSequencedBatch` when it returns; no
1254
+ * timer ever delays a frame. Own-device echoes are NOT dropped on this
1255
+ * path: the core advances the position past them without touching MLS,
1256
+ * and dropping one would leave a hole the next frame reports as a gap. A
1257
+ * sequenced frame at `serverSeq` 0 is a legacy frame in a wrapper and
1258
+ * takes the legacy path unchanged.
1259
+ */
1260
+ dispatchIncoming(frame) {
1261
+ if (isSequencedFrame(frame)) {
1262
+ if (frame.serverSeq > 0) {
1263
+ return this.coalescer.push(hexOf(frame.envelope.conversation_id), frame);
1264
+ }
1265
+ return this.dispatchLegacy(frame.envelope);
1266
+ }
1267
+ return this.dispatchLegacy(frame);
1268
+ }
1269
+ /** The legacy per-envelope path: own-device drop, then the per-conversation chain. */
1270
+ dispatchLegacy(envelope) {
1271
+ if (this.ownDeviceId && sameBytesU8(envelope.sender_device, this.ownDeviceId)) {
1272
+ return Promise.resolve();
1273
+ }
1274
+ const key = hexOf(envelope.conversation_id);
1275
+ const prior = this.dispatchChains.get(key) ?? Promise.resolve();
1276
+ const next = prior.catch(() => void 0).then(() => this.dispatchIncomingOrdered(envelope));
1277
+ const tail = next.catch(() => void 0).finally(() => {
1278
+ if (this.dispatchChains.get(key) === tail) this.dispatchChains.delete(key);
1279
+ });
1280
+ this.dispatchChains.set(key, tail);
1281
+ return next;
1282
+ }
1283
+ /** The actual routing, run inside the per-conversation chain. */
1284
+ async dispatchIncomingOrdered(envelope) {
1285
+ if (envelope.kind === "Welcome") {
1286
+ try {
1287
+ const known = await this.listConversations();
1288
+ const already = known.some((m) => sameBytesU8(m.id, envelope.conversation_id));
1289
+ if (already) {
1290
+ const stranded = await this.strandedConversations();
1291
+ const isStranded = stranded.some((id) => sameBytesU8(id, envelope.conversation_id));
1292
+ if (!isStranded) return;
1293
+ }
1294
+ await this.joinConversation(envelope);
1295
+ } catch (e) {
1296
+ if (typeof console !== "undefined") console.debug("[ping-sdk] welcome ignored:", e);
1297
+ }
1298
+ return;
1299
+ }
1300
+ try {
1301
+ await this.processEnvelope(envelope);
1302
+ } catch (e) {
1303
+ if (typeof console !== "undefined") console.debug("[ping-sdk] envelope deferred:", e);
1304
+ }
1305
+ }
1306
+ /**
1307
+ * One coalesced batch of live frames. Errors are logged at debug and
1308
+ * swallowed, exactly as the legacy path treats a failed envelope: the
1309
+ * dispatch promise a transport may await resolves either way, and the
1310
+ * core retains anything it could not apply yet.
1311
+ */
1312
+ async applyLiveBatch(items) {
1313
+ try {
1314
+ await this.processSequencedBatch(items);
1315
+ } catch (e) {
1316
+ if (typeof console !== "undefined") console.debug("[ping-sdk] sequenced batch failed:", errorKind(e));
1317
+ }
1318
+ }
1319
+ /** Start a fill for every gap a batch reported; each is single-flight. */
1320
+ scheduleGapFills(result) {
1321
+ for (const gap of result.gaps) {
1322
+ void this.fillGap(gap.conversationId).catch((e) => {
1323
+ if (typeof console !== "undefined") console.debug("[ping-sdk] gap fill failed:", errorKind(e));
1324
+ });
1325
+ }
1326
+ }
1327
+ /** One page, delivered as a page, on the requested lane. */
1328
+ async stepConversation(id, stepped) {
1329
+ const raw = await this.call({
1330
+ kind: "syncConversationStep",
1331
+ id: this.nextId++,
1332
+ conv: id,
1333
+ nowMs: this.now(),
1334
+ ...stepped ? { stepped: true } : {}
1335
+ });
1336
+ const result = syncStepResultFromWire(raw);
1337
+ this.fanout.deliverBatch(result.messages, { source: "page" });
1338
+ return result;
1339
+ }
1340
+ // ------------------------ Public API ------------------------
1341
+ async userId() {
1342
+ return await this.call({ kind: "userId", id: this.nextId++ });
1343
+ }
1344
+ /**
1345
+ * Export the account identity seed (CBOR-wrapped Ed25519, **SECRET**).
1346
+ * Transfer to a newly-linked device over the sealed linking channel so all of
1347
+ * an account's devices share one `userId` — the basis for cross-device
1348
+ * self-attribution (`IncomingMessage.sender_user_id === userId()`). Never log
1349
+ * or persist in cleartext.
1350
+ */
1351
+ async exportIdentity() {
1352
+ return await this.call({ kind: "exportIdentity", id: this.nextId++ });
1353
+ }
1354
+ /**
1355
+ * RETIRED (2026-11-03): always rejects (`Invalid`) and changes nothing.
1356
+ *
1357
+ * It moved every conversation's own leaf to a new account identity with a
1358
+ * credential-changing Commit, the way out of `409 mls_identity_conflict`.
1359
+ * Every Ping client now refuses a Commit that changes a member's leaf
1360
+ * credential (a hostile linked device could otherwise move its leaf to a
1361
+ * peer's identity and escape the account's removal), so a rotation would
1362
+ * strand every conversation it touched. The way out of an identity conflict
1363
+ * is to link this device again, or sign out and in. Kept so no caller
1364
+ * breaks. See `docs/MULTIDEVICE.md` "Identity rotation".
1365
+ *
1366
+ * @deprecated Retired: always rejects. Link this device again instead.
1367
+ */
1368
+ async rotateIdentity(newIdentityExport, nowMs = this.now()) {
1369
+ return await this.call({
1370
+ kind: "rotateIdentity",
1371
+ id: this.nextId++,
1372
+ newIdentityExport,
1373
+ nowMs
1374
+ });
1375
+ }
1376
+ /**
1377
+ * RETIRED with [[rotateIdentity]]: always rejects (`Invalid`).
1378
+ *
1379
+ * @deprecated Retired: always rejects.
1380
+ */
1381
+ async rotateIdentityRetry(conv, nowMs = this.now()) {
1382
+ await this.call({ kind: "rotateIdentityRetry", id: this.nextId++, conv, nowMs });
1383
+ }
1384
+ async deviceId() {
1385
+ return await this.call({ kind: "deviceId", id: this.nextId++ });
1386
+ }
1387
+ /**
1388
+ * Release every file lock the MLS store holds so the host process can be
1389
+ * suspended. Resolves `true` when the locks are genuinely gone.
1390
+ *
1391
+ * Present on web for API parity, and a no-op returning `true` here: this build
1392
+ * persists through the host's `Storage` (IndexedDB by default), which holds no
1393
+ * file locks and has nothing to release. It is load-bearing on the native
1394
+ * bindings, where iOS kills a backgrounded process that still holds a lock on
1395
+ * a file in an App Group container. Exposed on every platform so a host
1396
+ * sharing code across web and native does not have to branch on it.
1397
+ *
1398
+ * Pair with `resumeStorage()`.
1399
+ */
1400
+ async suspendStorage() {
1401
+ return await this.call({ kind: "suspendStorage", id: this.nextId++ });
1402
+ }
1403
+ /** Undo `suspendStorage()`. Idempotent. */
1404
+ async resumeStorage() {
1405
+ await this.call({ kind: "resumeStorage", id: this.nextId++ });
1406
+ }
1407
+ async freshKeyPackage() {
1408
+ return await this.call({ kind: "freshKeyPackage", id: this.nextId++ });
1409
+ }
1410
+ /**
1411
+ * Generate a fresh LAST-RESORT KeyPackage (RFC 9420 §10). Publish exactly one
1412
+ * per device so the server can serve it repeatedly as a fallback when the
1413
+ * single-use pool empties — invites then never hard-fail purely because the
1414
+ * peer ran out of KeyPackages.
1415
+ */
1416
+ async freshLastResortKeyPackage() {
1417
+ return await this.call({ kind: "freshLastResortKeyPackage", id: this.nextId++ });
1418
+ }
1419
+ async createConversation(opts = {}) {
1420
+ const idBytes = await this.call({
1421
+ kind: "createConversation",
1422
+ id: this.nextId++,
1423
+ name: opts.name ?? null,
1424
+ nowMs: this.now()
1425
+ });
1426
+ return this.conversationProxy(idBytes);
1427
+ }
1428
+ /**
1429
+ * Create an ephemeral per-call MLS group. Identical to {@link createConversation}
1430
+ * except the id carries the `0xFF 0xCC` call-group sentinel, so every device
1431
+ * recognises it structurally (by id alone — no name, no registry) and keeps it
1432
+ * out of the chat list. Hosts MUST use this for call groups.
1433
+ */
1434
+ async createCallConversation(opts = {}) {
1435
+ const idBytes = await this.call({
1436
+ kind: "createCallConversation",
1437
+ id: this.nextId++,
1438
+ name: opts.name ?? null,
1439
+ nowMs: this.now()
1440
+ });
1441
+ return this.conversationProxy(idBytes);
1442
+ }
1443
+ async joinConversation(welcome) {
1444
+ const idBytes = await this.call({
1445
+ kind: "joinConversation",
1446
+ id: this.nextId++,
1447
+ welcome,
1448
+ nowMs: this.now()
1449
+ });
1450
+ return this.conversationProxy(idBytes);
1451
+ }
1452
+ /**
1453
+ * Get a `Conversation` proxy for an already-known conversation. Use this when you have a
1454
+ * conversation id (e.g., from `listConversations()`) and want to send/addMembers without
1455
+ * re-creating it. Throws if the id isn't known to the worker — call `listConversations()`
1456
+ * first to verify membership.
1457
+ */
1458
+ getConversation(id) {
1459
+ return this.conversationProxy(id);
1460
+ }
1461
+ async listConversations() {
1462
+ const metas = await this.call({ kind: "listConversations", id: this.nextId++ });
1463
+ this.metaCache.clear();
1464
+ for (const m of metas) this.metaCache.set(hex(m.id), m);
1465
+ return metas;
1466
+ }
1467
+ /**
1468
+ * Conversations detected as STRANDED during catch-up — a Commit was missed
1469
+ * and the group can no longer advance from local state, so new messages stop
1470
+ * arriving. Poll after a sync and recover each (re-Welcome / state-snapshot
1471
+ * import). Returns 16-byte conversation ids; the set self-clears as a
1472
+ * conversation makes progress or is re-joined.
1473
+ */
1474
+ async strandedConversations() {
1475
+ return await this.call({ kind: "strandedConversations", id: this.nextId++ });
1476
+ }
1477
+ /**
1478
+ * Conversations this device asked to leave and is still a member of:
1479
+ * the leave is OWED. The SDK holds their state and proposes the leave
1480
+ * again by itself; the host only keeps delivering their rows (live
1481
+ * frames and catch-up pages). An id leaves the list when the leave has
1482
+ * completed: this device processed its own removal and the state is
1483
+ * deleted. Sorted 16-byte conversation ids.
1484
+ */
1485
+ async conversationsLeaving() {
1486
+ return await this.call({ kind: "conversationsLeaving", id: this.nextId++ });
1487
+ }
1488
+ /**
1489
+ * The leaving conversations whose leave has STALLED: 8 sends of it
1490
+ * FAILED and this device is still a member, or this device can no longer
1491
+ * follow the group. Nothing more is proposed for them. The host may call
1492
+ * {@link leaveConversation} again (the count starts over) or give up with
1493
+ * {@link dropConversationLocal}, which leaves this device's leaf in the group
1494
+ * until somebody removes it. Sorted 16-byte conversation ids.
1495
+ */
1496
+ async conversationsLeaveStalled() {
1497
+ return await this.call({ kind: "conversationsLeaveStalled", id: this.nextId++ });
1498
+ }
1499
+ /**
1500
+ * Conversations this device was just torn down from by a SELF-RE-ADD Commit
1501
+ * — a peer's `reAdmitDevice` of this device — whose Welcome for the new
1502
+ * leaf is expected within seconds. Treat these as "re-admission in flight",
1503
+ * not stranded or evicted: no repair advertise, no delivery-key rotation,
1504
+ * no KeyPackage-pool replace, until the join lands or the entry ages out
1505
+ * (ten minutes). Returns 16-byte conversation ids.
1506
+ */
1507
+ async readmitPendingConversations(nowMs = Date.now()) {
1508
+ return await this.call({
1509
+ kind: "readmitPendingConversations",
1510
+ id: this.nextId++,
1511
+ nowMs
1512
+ });
1513
+ }
1514
+ /**
1515
+ * How many inbound envelopes are currently RETAINED awaiting replay, across
1516
+ * all conversations.
1517
+ *
1518
+ * An envelope that cannot be applied yet — its Welcome has not been processed,
1519
+ * or a Commit that advances the epoch is missing — is buffered and replayed on
1520
+ * join / epoch advance / catch-up sync rather than dropped (see
1521
+ * docs/INVITE_HARDENING.md §S6).
1522
+ *
1523
+ * A non-zero count means "delivered but not yet applicable", which is
1524
+ * materially different from "not delivered" and is the distinction a host
1525
+ * needs to explain a chat that looks incomplete. Expected to be 0 at rest; a
1526
+ * value that stays high points at a conversation whose handshake never
1527
+ * arrived.
1528
+ */
1529
+ async undeliverableCount() {
1530
+ return await this.call({ kind: "undeliverableCount", id: this.nextId++ });
1531
+ }
1532
+ /**
1533
+ * Leave a conversation: broadcasts a self-Remove PROPOSAL (MLS forbids
1534
+ * committing your own removal: a remaining member commits it via
1535
+ * `commitPendingProposals`) and answers at once. From then on the conversation is
1536
+ * LEFT for the host: it is no longer listed, every call that names it
1537
+ * answers `UnknownConversation`, and nothing of it is surfaced again.
1538
+ *
1539
+ * Do NOT delete it locally afterwards ({@link dropConversationLocal}). The SDK keeps the
1540
+ * group's state, follows its Commits, and proposes the leave again after
1541
+ * each Commit that did not carry it (a Commit built before the proposal
1542
+ * arrived voids it), until this device is removed; then it deletes the
1543
+ * state itself. Keep delivering the conversation's rows to the client
1544
+ * while {@link conversationsLeaving} lists it. The bound is 8 FAILED sends;
1545
+ * after that {@link conversationsLeaveStalled} lists the conversation and calling
1546
+ * this again starts over.
1547
+ *
1548
+ * The group's OWNER hands over first: this call commits the successor (the
1549
+ * one every device computes when the owner's last leaf goes) and only then
1550
+ * proposes the leave. If that Commit cannot be made the call fails with the
1551
+ * Commit's error and nothing is marked: call it again. Nothing is handed
1552
+ * over when the owner's account keeps another device in the group or when
1553
+ * no other member could take over.
1554
+ */
1555
+ async leaveConversation(id, nowMs = this.now()) {
1556
+ await this.call({ kind: "leaveConversation", id: this.nextId++, conv: id, nowMs });
1557
+ }
1558
+ /**
1559
+ * Drop a conversation's local state with NO network side effect. Unlike
1560
+ * {@link leaveConversation} (which broadcasts a self-Remove proposal), this
1561
+ * sends nothing — use it for a group the SERVER does not back: an invite that
1562
+ * minted the MLS group locally but never completed server-side, so the backend
1563
+ * 404s `fetchSince` / 403s the member roster for it. Deletes the OpenMLS group
1564
+ * state + the on-disk snapshot rows so the dead group stops rehydrating on the
1565
+ * next restart (and re-materialising as a ghost "New chat"). Idempotent — safe
1566
+ * on an unknown/already-dropped id.
1567
+ */
1568
+ async dropConversationLocal(id) {
1569
+ await this.call({ kind: "dropConversationLocal", id: this.nextId++, conv: id });
1570
+ }
1571
+ /**
1572
+ * Conversations with buffered pending proposals (e.g. a peer's leave). Poll
1573
+ * after a sync; if you're the designated committer, call
1574
+ * `commitPendingProposals` to evict the leaver.
1575
+ */
1576
+ async conversationsWithPendingProposals() {
1577
+ return await this.call({
1578
+ kind: "conversationsWithPendingProposals",
1579
+ id: this.nextId++
1580
+ });
1581
+ }
1582
+ /**
1583
+ * Commit buffered pending proposals for a conversation (evicts a peer who
1584
+ * left). No-op if nothing is pending; on an epoch-advanced rejection re-sync
1585
+ * (another member already committed). Call it on receipt (a batch or page
1586
+ * result's `proposalsPending`), elected with
1587
+ * {@link pendingProposalsCommitRank}. A `send` commits pending proposals
1588
+ * itself first, so a proposal never blocks a message.
1589
+ */
1590
+ async commitPendingProposals(id, nowMs = this.now()) {
1591
+ await this.call({ kind: "commitPendingProposals", id: this.nextId++, conv: id, nowMs });
1592
+ }
1593
+ /**
1594
+ * This device's rank in the deterministic election of who commits a
1595
+ * conversation's pending proposals: members by leaf index, excluding any
1596
+ * leaf a pending proposal removes; identical on every member. `0` means
1597
+ * commit now; rank `n` means wait `n` intervals (a few seconds each), then
1598
+ * commit if the proposals are still pending. `null` when nothing is pending
1599
+ * or this device is not eligible.
1600
+ */
1601
+ async pendingProposalsCommitRank(id) {
1602
+ const rank = await this.call({
1603
+ kind: "pendingProposalsCommitRank",
1604
+ id: this.nextId++,
1605
+ conv: id
1606
+ });
1607
+ return rank ?? null;
1608
+ }
1609
+ /**
1610
+ * The Commits this device holds in doubt: a Commit whose send got no
1611
+ * definite answer (no response, a 5xx) is neither merged nor discarded; the
1612
+ * SDK settles it on a capped exponential backoff, and every operation in
1613
+ * that conversation fails with `commit in doubt` until it settles. Retry
1614
+ * such an operation at `nextAttemptAtMs`.
1615
+ */
1616
+ async commitsInDoubt() {
1617
+ const raw = await this.call({ kind: "commitsInDoubt", id: this.nextId++ });
1618
+ return raw.map(commitInDoubtFromWire);
1619
+ }
1620
+ /**
1621
+ * Member roster for a conversation, recovered locally from the MLS
1622
+ * group's leaf credentials (no network, no out-of-band message). Returns
1623
+ * one entry per device leaf — a multi-device user appears multiple times,
1624
+ * so dedup by `user_id` for a per-user roster. Empty for an unknown id.
1625
+ */
1626
+ async members(conv) {
1627
+ return await this.call({ kind: "members", id: this.nextId++, conv });
1628
+ }
1629
+ /**
1630
+ * A conversation's credential policy (account-signed device credentials,
1631
+ * 2026-11-04): whether every leaf must carry a credential the account key signed
1632
+ * (`credentialsRequired`; a KeyPackage without one gets the add verdict
1633
+ * `credentialMissing`), the roles once the policy records them (round 2), and
1634
+ * `incapableMembers`, the accounts with a member on an app too old for this
1635
+ * group, which is what blocks the upgrade. Rejects for a conversation this client
1636
+ * does not hold. No host action is needed for the credentials themselves: the SDK
1637
+ * signs and verifies them internally.
1638
+ */
1639
+ async conversationPolicy(conv) {
1640
+ return await this.call({ kind: "conversationPolicy", id: this.nextId++, conv });
1641
+ }
1642
+ /**
1643
+ * Whether a Commit of THIS device that re-admits or adds the device `deviceId` of
1644
+ * the account `identity` would pass the membership rules of the conversation in
1645
+ * its state now, without building or sending anything (2026-11-18). True when
1646
+ * this device may add a leaf of that account (the owner, an admin, or a device of
1647
+ * that same account; a device of the OWNER only when this device is the owner's)
1648
+ * and, if `deviceId` holds a leaf there, may also remove that leaf. Always true in
1649
+ * a conversation without roles. Ask it BEFORE leasing a re-admission request or
1650
+ * claiming a KeyPackage: a device that is not privileged never claims another
1651
+ * account's KeyPackage. Advisory: the Commit is judged again when it is built and
1652
+ * by every receiver. Rejects for a conversation this client does not hold.
1653
+ */
1654
+ async mayReadmit(conv, identity, deviceId) {
1655
+ return await this.call({ kind: "mayReadmit", id: this.nextId++, conv, identity, deviceId });
1656
+ }
1657
+ /**
1658
+ * The identity (the account's user id) a KeyPackage's credential CLAIMS, read
1659
+ * without changing anything (2026-11-18, rule R13). `null` for a credential that
1660
+ * is not the project's. Rejects for bytes that are not a valid KeyPackage: the
1661
+ * checks OpenMLS runs on a KeyPackage an add carries run first (both signatures
1662
+ * under the leaf's own key, the version, the init key, the extensions against the
1663
+ * capabilities, the lifetime: an expired KeyPackage rejects).
1664
+ *
1665
+ * Before adding ANOTHER account's device, read it and compare it with the account
1666
+ * you meant to add, byte for byte; a different answer, or `null`, is enough to
1667
+ * refuse the KeyPackage the server handed out, before any Commit.
1668
+ *
1669
+ * The read runs the SAME credential verdict the add runs (the device
1670
+ * credential, then the leaf-ready check) and rejects for a claim the add
1671
+ * would refuse, so an identity answered is one the account's key vouched
1672
+ * for (rulings part 13, ruling 1; until then the answer was a bare claim).
1673
+ */
1674
+ async keyPackageIdentity(keyPackage) {
1675
+ const identity = await this.call({
1676
+ kind: "keyPackageIdentity",
1677
+ id: this.nextId++,
1678
+ keyPackage
1679
+ });
1680
+ return identity ?? null;
1681
+ }
1682
+ /**
1683
+ * Replace the owners this client expects first roles writes to name
1684
+ * (2026-11-04, round 2; see `ClientConfig.expectedOwners`).
1685
+ */
1686
+ async setExpectedOwners(entries) {
1687
+ await this.call({ kind: "setExpectedOwners", id: this.nextId++, entries });
1688
+ }
1689
+ /**
1690
+ * Record a group's roles in its policy (2026-11-04, round 2): `owner` and
1691
+ * `admins` as MLS user ids (map account ids through the roster). One
1692
+ * GroupContextExtensions Commit, no Welcome, send-then-merge. Rejects with
1693
+ * "not permitted ..." before anything is sent when this device's role does not
1694
+ * allow the change, when a member's app is too old for roles
1695
+ * (`conversationPolicy().incapableMembers` names it), or in the DeviceGroup.
1696
+ * The same call as `getConversation(id).setConversationRoles`.
1697
+ */
1698
+ async setConversationRoles(conv, owner, admins) {
1699
+ await this.call({
1700
+ kind: "setConversationRoles",
1701
+ id: this.nextId++,
1702
+ conv,
1703
+ owner,
1704
+ admins,
1705
+ nowMs: this.now()
1706
+ });
1707
+ }
1708
+ /**
1709
+ * Whole-account catch-up. The worker runs it one conversation at a time and
1710
+ * lets every other request (a `send` the user is waiting on, a live frame)
1711
+ * run between conversations, so a pass over many conversations never parks
1712
+ * an interactive call behind all of them. Resolves when every conversation
1713
+ * held at the start of the pass (plus any joined while it ran) has been
1714
+ * paged, with the decrypted application messages in apply order.
1715
+ */
1716
+ async syncConversations() {
1717
+ return await this.call({
1718
+ kind: "syncConversations",
1719
+ id: this.nextId++,
1720
+ nowMs: this.now()
1721
+ });
1722
+ }
1723
+ /**
1724
+ * Catch-up for ONE conversation: the unit `syncConversations` is built from.
1725
+ * Use it to bring the conversation the user is looking at up to date ahead
1726
+ * of the rest (a message must be encrypted at the epoch the group is really
1727
+ * at, so a host calls this before the first send after a reconnect), or to
1728
+ * step a pass in an order of its own. Rejects with the SDK's
1729
+ * `unknown conversation` error for an id this client does not hold.
1730
+ */
1731
+ async syncConversation(id) {
1732
+ return await this.call({
1733
+ kind: "syncConversation",
1734
+ id: this.nextId++,
1735
+ conv: id,
1736
+ nowMs: this.now()
1737
+ });
1738
+ }
1739
+ async processEnvelope(envelope) {
1740
+ return await this.call({
1741
+ kind: "processEnvelope",
1742
+ id: this.nextId++,
1743
+ envelope,
1744
+ nowMs: this.now()
1745
+ });
1746
+ }
1747
+ // ------------------------ Sequenced log sync ------------------------
1748
+ // See docs/SYNC_PROTOCOL.md "Sequenced log sync". The subscribe path feeds
1749
+ // these itself for a transport that hands over sequenced frames; they are
1750
+ // public for hosts that drive their own socket.
1751
+ /**
1752
+ * Apply a batch of live frames, each with its server log position, and
1753
+ * checkpoint once per touched conversation. Per conversation: the next
1754
+ * position applies, one ahead of a hole is held and reported in `gaps`,
1755
+ * one at or below the applied position is a duplicate. Welcomes are routed
1756
+ * to a join inside the SDK (a join anchors the new conversation at the
1757
+ * Welcome's position); own-device echoes advance the position without
1758
+ * touching MLS, so pass them through. Frames at `serverSeq` 0 take the
1759
+ * legacy per-sender path.
1760
+ *
1761
+ * The decrypted messages are returned AND delivered: to `onMessageBatch`
1762
+ * handlers as one call (source `live`) when any is registered, else per
1763
+ * message to `onMessage` handlers. `onConversationUpdated` fires once per
1764
+ * entry of `updated`. A reported gap starts {@link fillGap} for that
1765
+ * conversation.
1766
+ */
1767
+ async processSequencedBatch(items) {
1768
+ const raw = await this.call({
1769
+ kind: "processSequencedBatch",
1770
+ id: this.nextId++,
1771
+ items: items.map(sequencedToWire),
1772
+ nowMs: this.now()
1773
+ });
1774
+ const result = applyBatchResultFromWire(raw);
1775
+ this.fanout.deliverBatch(result.messages, { source: "live" });
1776
+ this.scheduleGapFills(result);
1777
+ return result;
1778
+ }
1779
+ /**
1780
+ * ONE page of a conversation's server log through `Transport.fetchLogSince`,
1781
+ * applied in order and checkpointed once, then whatever held frames the
1782
+ * page made contiguous. `hasMore` means step again. Same delivery as
1783
+ * {@link processSequencedBatch}, with source `page`. An ordinary request:
1784
+ * it runs ahead of any background pass, so a host can bring the open chat
1785
+ * current first. Rejects with the SDK's `unknown conversation` error for an
1786
+ * id this client does not hold; the durable cursor is unchanged on a
1787
+ * transport failure.
1788
+ */
1789
+ async syncConversationStep(id) {
1790
+ return this.stepConversation(id, false);
1791
+ }
1792
+ /**
1793
+ * Fill a conversation's gap: run {@link syncConversationStep} until
1794
+ * `hasMore` is false, single-flight per conversation, on the worker's
1795
+ * stepped lane so a send posted meanwhile goes between pages. The SDK
1796
+ * starts this itself for every gap a batch reports; hosts call it for the
1797
+ * heads a socket `resume_ack` shows above the local position. A call
1798
+ * while a fill is running rides on it (and the loop runs once more after,
1799
+ * in case the running one ended before the new gap's rows were appended).
1800
+ */
1801
+ fillGap(conversationId) {
1802
+ return this.gapFiller.fill(hexOf(conversationId), async () => {
1803
+ const page = await this.stepConversation(conversationId, true);
1804
+ return page.hasMore;
1805
+ });
1806
+ }
1807
+ /**
1808
+ * This device's applied position in every conversation it holds, sorted by
1809
+ * conversation id: what a host puts in its socket resume frame and
1810
+ * compares against the server's heads.
1811
+ */
1812
+ async logPositions() {
1813
+ const raw = await this.call({ kind: "logPositions", id: this.nextId++ });
1814
+ return raw.map(logPositionFromWire);
1815
+ }
1816
+ /** This device's applied position in one conversation; `null` when not held. */
1817
+ async logPosition(id) {
1818
+ const raw = await this.call({ kind: "logPosition", id: this.nextId++, conv: id });
1819
+ return raw === null || raw === void 0 ? null : logPositionFromWire(raw);
1820
+ }
1821
+ /**
1822
+ * Anchor a conversation whose cursor predates positions at the
1823
+ * `(epoch, serverSeq)` the host had recorded for it, so an existing install
1824
+ * does not page its whole current epoch again. Resolves `false` (a no-op)
1825
+ * when the conversation is already anchored; the MLS epoch is never
1826
+ * touched. Call it once at start-up for every conversation the host's own
1827
+ * cursor store holds a position for.
1828
+ */
1829
+ async adoptLogPosition(id, epoch, serverSeq) {
1830
+ return await this.call({
1831
+ kind: "adoptLogPosition",
1832
+ id: this.nextId++,
1833
+ conv: id,
1834
+ epoch,
1835
+ serverSeq
1836
+ });
1837
+ }
1838
+ /**
1839
+ * Conversations the server's heads show this device is behind on: not
1840
+ * anchored yet, a head above the applied position, or frames held in the
1841
+ * reorder buffer. Sorted by id. A held conversation absent from `heads` is
1842
+ * not listed.
1843
+ */
1844
+ async conversationsBehind(heads) {
1845
+ return await this.call({
1846
+ kind: "conversationsBehind",
1847
+ id: this.nextId++,
1848
+ heads: heads.map(logHeadToWire)
1849
+ });
1850
+ }
1851
+ /** Frames held in reorder buffers right now (diagnostics). */
1852
+ async heldFrameCount() {
1853
+ return await this.call({ kind: "heldFrameCount", id: this.nextId++ });
1854
+ }
1855
+ /**
1856
+ * {@link joinConversation} at the Welcome's log position, so the new
1857
+ * conversation is anchored there and its first live frame applies without
1858
+ * a page. Pass `null` (or omit) when the position is unknown.
1859
+ */
1860
+ async joinConversationAt(welcome, position = null) {
1861
+ const idBytes = await this.call({
1862
+ kind: "joinConversationAt",
1863
+ id: this.nextId++,
1864
+ welcome,
1865
+ position,
1866
+ nowMs: this.now()
1867
+ });
1868
+ return this.conversationProxy(idBytes);
1869
+ }
1870
+ /**
1871
+ * The Welcome routing rule at a known position: joins when the conversation
1872
+ * is unknown or held stranded and resolves to it, resolves `null` when it
1873
+ * is held healthy (a relay duplicate), rejects when the Welcome is not
1874
+ * addressed to this device.
1875
+ */
1876
+ async processWelcomeAt(welcome, position = null) {
1877
+ const idBytes = await this.call({
1878
+ kind: "processWelcomeAt",
1879
+ id: this.nextId++,
1880
+ welcome,
1881
+ position,
1882
+ nowMs: this.now()
1883
+ });
1884
+ return idBytes === null || idBytes === void 0 ? null : this.conversationProxy(idBytes);
1885
+ }
1886
+ /**
1887
+ * [D27] Decrypted-but-unconfirmed messages surviving in the pending-apply
1888
+ * journal, oldest first.
1889
+ *
1890
+ * The MLS ratchet advances at decrypt, BEFORE the host persists its own row
1891
+ * for the message; a crash inside that gap used to lose the message for good
1892
+ * (the server re-delivers, but MLS cannot re-decrypt a consumed generation).
1893
+ * The SDK now journals every decrypt in the same checkpoint that persists
1894
+ * the ratchet advance.
1895
+ *
1896
+ * CRASH-RECOVERY CONTRACT: on boot, BEFORE advancing any sync cursor or
1897
+ * sending any delivery ack, drain this list through the normal ingest —
1898
+ * dedup by `content_hash` / envelope identity exactly as for a redelivered
1899
+ * envelope — persist each message, then {@link confirmApplied} the drained
1900
+ * ids. Reading does not consume; unconfirmed entries survive further
1901
+ * restarts (bounded: 512 entries / 4 MiB, oldest evicted). See
1902
+ * docs/PENDING_APPLIES.md.
1903
+ */
1904
+ async pendingApplies() {
1905
+ return await this.call({ kind: "pendingApplies", id: this.nextId++ });
1906
+ }
1907
+ /**
1908
+ * [D27] Delete journal entries whose messages the host has durably
1909
+ * persisted (`IncomingMessage.journal_id` from live processing, or
1910
+ * `PendingApply.journal_id` from a boot drain), and checkpoint so the
1911
+ * deletion survives a reload. Unknown ids are ignored (idempotent).
1912
+ */
1913
+ async confirmApplied(journalIds) {
1914
+ if (journalIds.length === 0) return;
1915
+ await this.call({ kind: "confirmApplied", id: this.nextId++, journalIds });
1916
+ }
1917
+ /**
1918
+ * Build a `LinkingTicket` for a new device.
1919
+ *
1920
+ * [CR-13] `lastAppEvents` is host-supplied per-conversation "what you missed" data
1921
+ * (decrypted AppEvent bytes the new device will render before sync catches up).
1922
+ * Pass `[]` to suppress catchup data — the new device will see an empty conversation
1923
+ * list until normal sync runs.
1924
+ *
1925
+ * Caller is responsible for HPKE-sealing the returned ticket via
1926
+ * `MessagingClient.sealLinkingTicket` before transmitting (CR-3).
1927
+ *
1928
+ * Rejects (`Invalid`), before anything is sent, a KeyPackage that claims the
1929
+ * identity of another account this client knows: a new device links under an
1930
+ * identity of its own, or the account's.
1931
+ */
1932
+ async buildLinkingTicket(newDeviceId, newDeviceKp, lastAppEvents = []) {
1933
+ return await this.call({
1934
+ kind: "buildLinkingTicket",
1935
+ id: this.nextId++,
1936
+ newDeviceId,
1937
+ newDeviceKp,
1938
+ lastAppEvents,
1939
+ nowMs: this.now()
1940
+ });
1941
+ }
1942
+ /**
1943
+ * Decode a `LinkingTicket.catchup_snapshot` blob ([CR-13]).
1944
+ *
1945
+ * Pure WASM — runs in an ephemeral worker so the new device can call this before
1946
+ * `MessagingClient.init()` completes (just like `openLinkingTicket`). Returns the
1947
+ * structured view: per-conversation metas + last-known AppEvent bytes.
1948
+ *
1949
+ * Throws on malformed or oversized inputs. Empty bytes return `null` — that's the
1950
+ * "no catchup data" case (sender passed `[]` to buildLinkingTicket).
1951
+ */
1952
+ static async decodeCatchupSnapshot(snapshotBytes) {
1953
+ if (snapshotBytes.length === 0) return null;
1954
+ return _MessagingClient.ephemeralWorkerCall({
1955
+ kind: "decodeCatchupSnapshot",
1956
+ id: 1,
1957
+ snapshotBytes
1958
+ });
1959
+ }
1960
+ async consumeLinkingTicket(ticket) {
1961
+ await this.call({
1962
+ kind: "consumeLinkingTicket",
1963
+ id: this.nextId++,
1964
+ ticket,
1965
+ nowMs: this.now()
1966
+ });
1967
+ }
1968
+ // ------------------------ Recovery (account backup) ------------------------
1969
+ // All static + stateless: they run on an ephemeral worker, so the recovery screen can
1970
+ // call them before any client is initialised. Same Argon2id/AES-256-GCM IdentityBackup
1971
+ // wire format as the iOS/Android FFI bindings — backups are portable across platforms.
1972
+ /** Generate a fresh 12-word BIP39 mnemonic, returned as its canonical phrase string. */
1973
+ static async generateMnemonicPhrase() {
1974
+ return _MessagingClient.ephemeralWorkerCall({
1975
+ kind: "generateMnemonicPhrase",
1976
+ id: 1
1977
+ });
1978
+ }
1979
+ /** Validate + canonicalise a user-entered phrase (BIP39 wordlist + checksum). Rejects
1980
+ * malformed input. Use on the recovery screen before calling `decryptBackup`. */
1981
+ static async normalizeMnemonicPhrase(phrase) {
1982
+ return _MessagingClient.ephemeralWorkerCall({
1983
+ kind: "normalizeMnemonicPhrase",
1984
+ id: 1,
1985
+ phrase
1986
+ });
1987
+ }
1988
+ /** Encrypt an IdentityBackup for `POST /v1/recovery/blobs`. `deviceGroupSnapshot` may be
1989
+ * empty (Conservative path) or the DeviceGroup's `exportConversationStateSnapshot`. */
1990
+ static async encryptBackup(args) {
1991
+ return _MessagingClient.ephemeralWorkerCall({
1992
+ kind: "encryptBackup",
1993
+ id: 1,
1994
+ mnemonicPhrase: args.mnemonicPhrase,
1995
+ accountId: args.accountId,
1996
+ identityExport: args.identityExport,
1997
+ deviceGroupSnapshot: args.deviceGroupSnapshot,
1998
+ conversationSnapshots: args.conversationSnapshots ?? [],
1999
+ createdAtMs: args.createdAtMs
2000
+ });
2001
+ }
2002
+ /** Decrypt a recovery blob from `GET /v1/recovery/blobs`. Throws on wrong mnemonic or a
2003
+ * tampered blob. The returned `identity_export` is the secret seed for `init`. */
2004
+ static async decryptBackup(blob, mnemonicPhrase) {
2005
+ return _MessagingClient.ephemeralWorkerCall({
2006
+ kind: "decryptBackup",
2007
+ id: 1,
2008
+ blob,
2009
+ mnemonicPhrase
2010
+ });
2011
+ }
2012
+ // ------------------------ Peer-assisted history transfer ------------------------
2013
+ // Authenticated (sign-then-encrypt) device-to-device history used by linking and
2014
+ // post-recovery peer re-add. Confidential to the recipient's ephemeral X25519 key AND
2015
+ // signed by the account identity key, so the receiver proves the sender. Plaintext-only
2016
+ // share — preserves forward secrecy (no MLS keys leave the device).
2017
+ /** Seal+sign a `HistoryBundle` for a recipient device. `recipientPub` (X25519, 32B) is the
2018
+ * recipient's ephemeral pubkey from the linking QR; `senderIdentitySecret` (Ed25519 seed,
2019
+ * 32B) is this account's identity key. Returns the blob to POST to /v1/history-transfers. */
2020
+ static async sealHistoryBundle(bundle, recipientPub, senderIdentitySecret) {
2021
+ return _MessagingClient.ephemeralWorkerCall({
2022
+ kind: "sealHistoryBundle",
2023
+ id: 1,
2024
+ bundle,
2025
+ recipientPub,
2026
+ senderIdentitySecret
2027
+ });
2028
+ }
2029
+ /** Open+verify a sealed history bundle. `recipientPriv` (X25519, 32B) is this device's
2030
+ * ephemeral private key; `senderIdentityPub` (Ed25519, 32B) is the account identity pubkey
2031
+ * from the linking handshake. Throws if the signature doesn't verify. */
2032
+ static async openHistoryBundle(sealed, recipientPriv, senderIdentityPub) {
2033
+ return _MessagingClient.ephemeralWorkerCall({
2034
+ kind: "openHistoryBundle",
2035
+ id: 1,
2036
+ sealed,
2037
+ recipientPriv,
2038
+ senderIdentityPub
2039
+ });
2040
+ }
2041
+ /**
2042
+ * Post-quantum {@link sealHistoryBundle}: `recipientPub` is the recipient's
2043
+ * X-Wing public key ({@link HPKE_PQ_PUBLIC_KEY_BYTES} bytes). Wrapper `v: 2`;
2044
+ * the classical open refuses it and vice versa.
2045
+ */
2046
+ static async sealHistoryBundlePq(bundle, recipientPub, senderIdentitySecret) {
2047
+ if (recipientPub.length !== HPKE_PQ_PUBLIC_KEY_BYTES) {
2048
+ throw new Error(`sealHistoryBundlePq: recipientPub must be ${HPKE_PQ_PUBLIC_KEY_BYTES} bytes`);
2049
+ }
2050
+ return _MessagingClient.ephemeralWorkerCall({
2051
+ kind: "sealHistoryBundlePq",
2052
+ id: 1,
2053
+ bundle,
2054
+ recipientPub,
2055
+ senderIdentitySecret
2056
+ });
2057
+ }
2058
+ /** Post-quantum {@link openHistoryBundle}: `recipientPriv` is the 32-byte X-Wing seed. */
2059
+ static async openHistoryBundlePq(sealed, recipientPriv, senderIdentityPub) {
2060
+ if (recipientPriv.length !== 32) {
2061
+ throw new Error("openHistoryBundlePq: recipientPriv must be 32 bytes");
2062
+ }
2063
+ return _MessagingClient.ephemeralWorkerCall({
2064
+ kind: "openHistoryBundlePq",
2065
+ id: 1,
2066
+ sealed,
2067
+ recipientPriv,
2068
+ senderIdentityPub
2069
+ });
2070
+ }
2071
+ /**
2072
+ * Admit a freshly-linked device to every chat in `entries` — one MLS
2073
+ * Commit + Welcome per chat, with the Welcome's `?recipient=` priming
2074
+ * handled inside the SDK. This is the post-link reconciliation step
2075
+ * that follows `consumeLinkingTicket`: the new device has the
2076
+ * DeviceGroup (from the ticket) and metadata for external chats (from
2077
+ * the catchup snapshot), but its leaf is not yet in any external
2078
+ * MLS group. The host on the EXISTING device calls this once the
2079
+ * new device shows up in `/v1/auth/sessions` and has uploaded its
2080
+ * KeyPackage batch, passing one freshly-claimed KP per chat.
2081
+ *
2082
+ * Per-chat failures (stale KP, transport error, unknown chat) are
2083
+ * captured in the returned outcomes rather than aborting — one bad
2084
+ * chat shouldn't lose the user access to all the others.
2085
+ *
2086
+ * Each KeyPackage must carry this account's identity (a linked device
2087
+ * adopts it with the link): one that claims any other identity fails its
2088
+ * chat and nothing is sent there.
2089
+ */
2090
+ async admitDeviceToChats(deviceId, entries) {
2091
+ return await this.call({
2092
+ kind: "admitDeviceToChats",
2093
+ id: this.nextId++,
2094
+ deviceId,
2095
+ entries,
2096
+ nowMs: this.now()
2097
+ });
2098
+ }
2099
+ /**
2100
+ * `admitDeviceToChats` with up to `concurrency` admissions in flight at
2101
+ * once. Same input, same per-chat outcomes in INPUT order whatever order
2102
+ * the sends finish in; `concurrency` 1 is exactly `admitDeviceToChats`,
2103
+ * 0 is treated as 1. Safe because every admission is its own conversation
2104
+ * (one Commit + Welcome per chat, the conversation lock is never held
2105
+ * across the send), so two admissions never touch the same epoch.
2106
+ *
2107
+ * This is the ONLY way to overlap admissions on web: the worker runs one
2108
+ * call at a time, so several `admitDeviceToChats` calls issued together
2109
+ * still run one after another. The overlap happens inside this one call.
2110
+ */
2111
+ async admitDeviceToChatsConcurrent(deviceId, entries, concurrency) {
2112
+ const lanes = Number.isFinite(concurrency) ? Math.min(4294967295, Math.max(1, Math.floor(concurrency))) : 1;
2113
+ return await this.call({
2114
+ kind: "admitDeviceToChatsConcurrent",
2115
+ id: this.nextId++,
2116
+ deviceId,
2117
+ entries,
2118
+ nowMs: this.now(),
2119
+ concurrency: lanes
2120
+ });
2121
+ }
2122
+ /**
2123
+ * Revoke a device ([CR-2]).
2124
+ *
2125
+ * Removes `deviceId`'s leaf from every conversation where this client locally
2126
+ * tracked the device→leaf mapping (i.e. conversations where this client itself
2127
+ * admitted the device via `addMembers`, or where this client is the device being
2128
+ * revoked). The SDK has already broadcast each Commit envelope via
2129
+ * `transport.send`; the returned array is for any additional host-side handling
2130
+ * (audit logs, UI). An empty array is a valid outcome — the device wasn't locally
2131
+ * known anywhere.
2132
+ *
2133
+ * **Scope note.** Conversations where a peer admitted the device on this client's
2134
+ * behalf are silently skipped — the leaf index isn't locally known. Host can fall
2135
+ * back to `transport.discoverDevices` + a manual `remove_members(leafIndex)` for
2136
+ * those, or wait for the affected user to revoke from a device that did the admit.
2137
+ * See `docs/architecture/multi-device.md §Device removal`.
2138
+ */
2139
+ async revokeDevice(deviceId) {
2140
+ return await this.call({
2141
+ kind: "revokeDevice",
2142
+ id: this.nextId++,
2143
+ deviceId,
2144
+ nowMs: this.now()
2145
+ });
2146
+ }
2147
+ /**
2148
+ * Remove one of THIS account's devices from every group this client is in, the
2149
+ * DeviceGroup included, without stopping at a failure, and report where it stands.
2150
+ *
2151
+ * Unlike {@link revokeDevice}, the device's leaf is read from each ratchet tree (the
2152
+ * leaf whose key hashes to the id), so this reaches leaves a sibling or a peer
2153
+ * admitted. The id is the server's word that the device is this account's; outside
2154
+ * the DeviceGroup a leaf is removed only when its credential names this account, or
2155
+ * when the device was seen in the account's DeviceGroup and its credential names no
2156
+ * other account this client knows (docs/MULTIDEVICE.md, "Which leaf"). An id that
2157
+ * names no leaf of this account is rejected before anything is sent. Every held
2158
+ * conversation is checked: a Commit of this device in doubt is settled first, and
2159
+ * the log is read to its end before the device is reported absent (what that read
2160
+ * applies comes with the next batch or page); a conversation that failed to load
2161
+ * is a failure with reason `Unloadable`. The DeviceGroup goes first, then the
2162
+ * conversations, a few at a time, each a send-then-merge Commit. Persist the report
2163
+ * and call again until `failed` is empty and `deviceGroup !== "failed"`. A
2164
+ * `CommitInDoubt` reason settles on its own backoff ({@link commitsInDoubt});
2165
+ * `NotOwnAccount` and `RefusedCommit` never resolve by retrying (for
2166
+ * `RefusedCommit`, offer to recreate the conversation). Groups this device joins
2167
+ * later are checked for the device too.
2168
+ *
2169
+ * MLS only: revoke the device on the server yourself. Rejects for this device's own
2170
+ * id (leave a conversation with `leaveConversation` instead) and for a device that
2171
+ * is not this account's.
2172
+ */
2173
+ async removeDeviceEverywhere(deviceId, nowMs = this.now()) {
2174
+ return await this.call({
2175
+ kind: "removeDeviceEverywhere",
2176
+ id: this.nextId++,
2177
+ deviceId,
2178
+ nowMs
2179
+ });
2180
+ }
2181
+ /**
2182
+ * Remove every other device of THIS account from every group this client is in,
2183
+ * except the devices in `keep` and this device: the "secure my account" sweep.
2184
+ *
2185
+ * `listed` is the server's list of this account's devices to remove (a reset's
2186
+ * `revoked_device_ids`). In the DeviceGroup every leaf but this device's and the
2187
+ * kept ones goes. Elsewhere a leaf goes when its credential names this client's
2188
+ * account (no device id has to match, so a device that moved its leaf to another
2189
+ * signature key is still reached), or when its device is in `listed` and was seen in
2190
+ * the account's DeviceGroup, whatever identity its leaf claims. A leaf the sweep
2191
+ * leaves although one of those two says it may be the account's (seen but not
2192
+ * listed, or listed but not seen) is reported: its conversation fails with
2193
+ * `NotOwnAccount`, so the report is never complete over it. Same pass and report as
2194
+ * {@link removeDeviceEverywhere}; call again until it is complete. MLS only.
2195
+ */
2196
+ async removeOwnDevicesExcept(keep, listed, nowMs = this.now()) {
2197
+ return await this.call({
2198
+ kind: "removeOwnDevicesExcept",
2199
+ id: this.nextId++,
2200
+ keep,
2201
+ listed,
2202
+ nowMs
2203
+ });
2204
+ }
2205
+ /**
2206
+ * Export a portable MLS state snapshot for one conversation ([CR-7]).
2207
+ *
2208
+ * Returned bytes can be embedded in a recovery blob or shipped through a
2209
+ * linking ticket so another device of the same user identity can re-attach to
2210
+ * the group via [[importStateSnapshot]]. The bytes contain past epoch secrets;
2211
+ * never log, never persist unencrypted, wipe (`.fill(0)`) after use.
2212
+ */
2213
+ async exportConversationStateSnapshot(conv) {
2214
+ return await this.call({
2215
+ kind: "exportConversationStateSnapshot",
2216
+ id: this.nextId++,
2217
+ conv,
2218
+ nowMs: this.now()
2219
+ });
2220
+ }
2221
+ /**
2222
+ * Import a `GroupStateSnapshot` from another device of the same user identity
2223
+ * ([CR-7]).
2224
+ *
2225
+ * On success, the conversation appears in [[listConversations]] and decryption
2226
+ * of subsequent peer-originated traffic works against the imported state. For
2227
+ * full multi-device participation, the recovered device SHOULD then issue an
2228
+ * MLS Update Proposal to rotate onto a fresh leaf (post-v1 follow-up — see
2229
+ * `docs/design/CR4_CR7_PERSISTENCE.md` open question #3).
2230
+ */
2231
+ async importStateSnapshot(snapshotBytes) {
2232
+ return await this.call({
2233
+ kind: "importStateSnapshot",
2234
+ id: this.nextId++,
2235
+ snapshotBytes,
2236
+ nowMs: this.now()
2237
+ });
2238
+ }
2239
+ /**
2240
+ * Export a derived secret from a conversation's MLS exporter ([CR-8]).
2241
+ *
2242
+ * Used to seed the ephemeral channel (`ping/ephemeral`), call-media keys
2243
+ * (`ping/calls/media/<call_id>`), and call-ephemeral framer keys
2244
+ * (`ping/calls/ephemeral/<call_id>`). The returned bytes are a secret — never log,
2245
+ * persist only encrypted, and call `bytes.fill(0)` after use to wipe the typed array.
2246
+ *
2247
+ * Same `(conversationId, current_epoch, label, context, length)` produces the same
2248
+ * bytes across every binding (Rust core, native UniFFI, WASM/JS). Cross-platform
2249
+ * byte-equality is enforced by `protocol/conformance/export_secret/`.
2250
+ */
2251
+ async exportConversationSecret(conv, label, context, length) {
2252
+ if (length <= 0 || length > 1024) {
2253
+ throw new Error("exportConversationSecret: length must be 1..=1024");
2254
+ }
2255
+ return await this.call({
2256
+ kind: "exportConversationSecret",
2257
+ id: this.nextId++,
2258
+ conv,
2259
+ label,
2260
+ context,
2261
+ length
2262
+ });
2263
+ }
2264
+ /**
2265
+ * Subscribe to decrypted application messages, one call per message. A
2266
+ * batch or page result (the sequenced paths) is fanned out here per
2267
+ * message only while no {@link onMessageBatch} handler is registered.
2268
+ */
2269
+ onMessage(handler) {
2270
+ return this.fanout.onMessage(handler);
2271
+ }
2272
+ /**
2273
+ * Subscribe to decrypted messages one BATCH at a time: one call per
2274
+ * `processSequencedBatch` result (source `live`) or per page of the server
2275
+ * log (source `page`: a gap fill, or the whole-account catch-up), so the
2276
+ * host persists the batch in one store transaction. While at least one
2277
+ * batch handler is registered, batch and page results go ONLY here, never
2278
+ * per message to `onMessage`; the legacy per-envelope path still delivers
2279
+ * per message. An empty result is not delivered.
2280
+ */
2281
+ onMessageBatch(handler) {
2282
+ return this.fanout.onMessageBatch(handler);
2283
+ }
2284
+ /** Fired after every state-changing event for a conversation (Commit, member changes). */
2285
+ /**
2286
+ * Fires after every conversation state change — joining via Welcome, processing a Commit,
2287
+ * etc. `sender` carries the device id of whoever triggered the event when known (e.g. the
2288
+ * inviter's device on auto-join), so the host can label peers in its UI.
2289
+ */
2290
+ onConversationUpdated(handler) {
2291
+ this.conversationHandlers.add(handler);
2292
+ return () => this.conversationHandlers.delete(handler);
2293
+ }
2294
+ /**
2295
+ * Stop the live subscription and terminate the worker. Every call still in
2296
+ * flight rejects with a {@link MessagingClientClosedError} (reason
2297
+ * `closed`), and every later call rejects the same way instead of waiting
2298
+ * on a worker that no longer exists. Idempotent.
2299
+ */
2300
+ async close() {
2301
+ if (this.closed) return;
2302
+ this.closed = true;
2303
+ this.subscription?.unsubscribe();
2304
+ this.worker.terminate();
2305
+ this.failPending(new MessagingClientClosedError("closed"));
2306
+ }
2307
+ /** Reject every pending call with `error` and forget them. */
2308
+ failPending(error) {
2309
+ const slots = [...this.pending.values()];
2310
+ this.pending.clear();
2311
+ for (const slot of slots) slot.reject(error);
2312
+ }
2313
+ // ------------------------ Internals ------------------------
2314
+ conversationProxy(id) {
2315
+ const self = this;
2316
+ return {
2317
+ id,
2318
+ async send(plaintext) {
2319
+ return await self.call({
2320
+ kind: "send",
2321
+ id: self.nextId++,
2322
+ conv: id,
2323
+ plaintext,
2324
+ nowMs: self.now()
2325
+ });
2326
+ },
2327
+ async addMembers(entries) {
2328
+ await self.call({
2329
+ kind: "addMembers",
2330
+ id: self.nextId++,
2331
+ conv: id,
2332
+ entries,
2333
+ nowMs: self.now()
2334
+ });
2335
+ },
2336
+ async addMembersWithVerdicts(entries) {
2337
+ const raw = await self.call({
2338
+ kind: "addMembersWithVerdicts",
2339
+ id: self.nextId++,
2340
+ conv: id,
2341
+ entries,
2342
+ nowMs: self.now()
2343
+ });
2344
+ return addMembersReportFromWire(raw);
2345
+ },
2346
+ async reAdmitDevice(entry) {
2347
+ const replaced = await self.call({
2348
+ kind: "reAdmitDevice",
2349
+ id: self.nextId++,
2350
+ conv: id,
2351
+ entry,
2352
+ nowMs: self.now()
2353
+ });
2354
+ return replaced ?? null;
2355
+ },
2356
+ async removeOwnOtherLeaves() {
2357
+ return await self.call({
2358
+ kind: "removeOwnOtherLeaves",
2359
+ id: self.nextId++,
2360
+ conv: id,
2361
+ nowMs: self.now()
2362
+ });
2363
+ },
2364
+ async removeMembersByIdentity(identities) {
2365
+ return await self.call({
2366
+ kind: "removeMembersByIdentity",
2367
+ id: self.nextId++,
2368
+ conv: id,
2369
+ identities,
2370
+ nowMs: self.now()
2371
+ });
2372
+ },
2373
+ async removeMembers(leaves) {
2374
+ await self.call({
2375
+ kind: "removeMembers",
2376
+ id: self.nextId++,
2377
+ conv: id,
2378
+ leaves,
2379
+ nowMs: self.now()
2380
+ });
2381
+ },
2382
+ async setConversationName(name) {
2383
+ await self.call({
2384
+ kind: "setConversationName",
2385
+ id: self.nextId++,
2386
+ conv: id,
2387
+ name,
2388
+ nowMs: self.now()
2389
+ });
2390
+ },
2391
+ async setConversationRoles(owner, admins) {
2392
+ await self.call({
2393
+ kind: "setConversationRoles",
2394
+ id: self.nextId++,
2395
+ conv: id,
2396
+ owner,
2397
+ admins,
2398
+ nowMs: self.now()
2399
+ });
2400
+ },
2401
+ /**
2402
+ * The conversation's MLS GroupContext name, or `undefined` when the meta
2403
+ * cache has not been primed (call `listConversations()`).
2404
+ *
2405
+ * This accessor did not exist, and hosts reasonably assumed it did:
2406
+ * `getConversation(id).name` read `undefined` on every call, which
2407
+ * silently disabled any host logic driven by group state — group titles,
2408
+ * rosters, avatars and roles carried in the GroupContext all appeared
2409
+ * absent, so a group would materialise unnamed until a best-effort
2410
+ * broadcast happened to arrive.
2411
+ *
2412
+ * A getter rather than a snapshot, so it reflects the cache at read time
2413
+ * and never goes stale against a later `listConversations()`.
2414
+ */
2415
+ get name() {
2416
+ return self.metaCache.get(hex(id))?.name ?? void 0;
2417
+ },
2418
+ /** The conversation's current MLS epoch, or `undefined` when the meta
2419
+ * cache has not been primed. */
2420
+ get epoch() {
2421
+ return self.metaCache.get(hex(id))?.epoch;
2422
+ },
2423
+ meta() {
2424
+ const cached = self.metaCache.get(hex(id));
2425
+ if (!cached) throw new Error("conversation meta not loaded; call listConversations() first");
2426
+ return cached;
2427
+ }
2428
+ };
2429
+ }
2430
+ call(req) {
2431
+ if (this.closed) return Promise.reject(new MessagingClientClosedError("closed"));
2432
+ return new Promise((resolve, reject) => {
2433
+ this.pending.set(req.id, { resolve, reject });
2434
+ this.worker.postMessage(req);
2435
+ });
2436
+ }
2437
+ /** Dispatch a worker-side transport proxy call onto the host transport.
2438
+ * `sendBatch` is the one method the worker proxy always declares but a
2439
+ * host may not implement: emulate it with sequential sends and report a
2440
+ * partial delivery with the sentinel the wasm bridge maps to
2441
+ * `TransportPartial`, so the SDK still learns the Commit landed while the
2442
+ * Welcome did not (and surfaces `WelcomeUndelivered`). The two
2443
+ * sequenced-log methods cross in the wasm's wire shape and are converted
2444
+ * to the public shape here, both ways; the worker only asks for them when
2445
+ * the host declared them at `init`. */
2446
+ async callTransportMethod(method, args) {
2447
+ const t = this.transport;
2448
+ if (method === "sendBatch" && typeof t.sendBatch !== "function") {
2449
+ await emulateSendBatch(this.transport, args[0] ?? []);
2450
+ return void 0;
2451
+ }
2452
+ if (method === "fetchLogSince") {
2453
+ if (typeof this.transport.fetchLogSince !== "function") return null;
2454
+ const [position, limit] = args;
2455
+ const rows = await this.transport.fetchLogSince(logPositionFromWire(position), limit);
2456
+ return rows === null || rows === void 0 ? null : rows.map(sequencedToWire);
2457
+ }
2458
+ if (method === "fetchLogHeads") {
2459
+ if (typeof this.transport.fetchLogHeads !== "function") return null;
2460
+ const heads = await this.transport.fetchLogHeads();
2461
+ return heads === null || heads === void 0 ? null : heads.map(logHeadToWire);
2462
+ }
2463
+ return await t[method]?.(...args);
2464
+ }
2465
+ async handleWorker(msg) {
2466
+ switch (msg.kind) {
2467
+ case "result": {
2468
+ const slot = this.pending.get(msg.id);
2469
+ if (!slot) return;
2470
+ this.pending.delete(msg.id);
2471
+ msg.ok ? slot.resolve(msg.value) : slot.reject(errorFromWorker(msg.error));
2472
+ return;
2473
+ }
2474
+ case "event.message": {
2475
+ this.fanout.deliverOne(msg.msg);
2476
+ return;
2477
+ }
2478
+ case "event.batch": {
2479
+ this.fanout.deliverBatch(msg.messages, { source: msg.source });
2480
+ return;
2481
+ }
2482
+ case "event.conversation": {
2483
+ for (const h of this.conversationHandlers) {
2484
+ try {
2485
+ h(msg.id, msg.epoch, msg.sender);
2486
+ } catch (e) {
2487
+ if (typeof console !== "undefined") {
2488
+ console.debug("[ping-sdk] onConversationUpdated handler threw:", errorKind(e));
2489
+ }
2490
+ }
2491
+ }
2492
+ return;
2493
+ }
2494
+ case "storage.call": {
2495
+ try {
2496
+ const method = this.storage[msg.method];
2497
+ if (typeof method !== "function") {
2498
+ throw new Error(`storage.${String(msg.method)} is not implemented by the host storage`);
2499
+ }
2500
+ const v = await method.apply(this.storage, msg.args);
2501
+ this.worker.postMessage({ kind: "storage.reply", id: msg.id, ok: true, value: v });
2502
+ } catch (e) {
2503
+ this.worker.postMessage({
2504
+ kind: "storage.reply",
2505
+ id: msg.id,
2506
+ ok: false,
2507
+ error: String(e)
2508
+ });
2509
+ }
2510
+ return;
2511
+ }
2512
+ case "transport.call": {
2513
+ try {
2514
+ const v = await this.callTransportMethod(msg.method, msg.args);
2515
+ this.worker.postMessage({ kind: "transport.reply", id: msg.id, ok: true, value: v });
2516
+ } catch (e) {
2517
+ this.worker.postMessage({
2518
+ kind: "transport.reply",
2519
+ id: msg.id,
2520
+ ok: false,
2521
+ error: describeTransportError(e)
2522
+ });
2523
+ }
2524
+ return;
2525
+ }
2526
+ }
2527
+ }
2528
+ };
2529
+ var EphemeralWorkerError = class extends Error {
2530
+ reason;
2531
+ constructor(reason) {
2532
+ super(`ping-openmls-sdk: one-shot worker failed (${reason})`);
2533
+ this.name = "EphemeralWorkerError";
2534
+ this.reason = reason;
2535
+ }
2536
+ };
2537
+ var MessagingClientClosedError = class extends Error {
2538
+ reason;
2539
+ constructor(reason) {
2540
+ super(reason === "closed" ? "MessagingClient is closed" : "MessagingClient worker error");
2541
+ this.name = "MessagingClientClosedError";
2542
+ this.reason = reason;
2543
+ }
2544
+ };
2545
+ var HPKE_PQ_PUBLIC_KEY_BYTES = 1216;
2546
+ var HPKE_PQ_ENC_BYTES = 1120;
2547
+ var BATCH_PARTIAL_PREFIX = "batch partial after ";
2548
+ var NOT_PERMITTED_PREFIX = "not permitted: ";
2549
+ var NotPermittedError = class extends Error {
2550
+ /** The rule that was broken: fixed text, no id, safe to log. */
2551
+ rule;
2552
+ constructor(message) {
2553
+ super(message);
2554
+ this.name = "NotPermittedError";
2555
+ this.rule = message.startsWith(NOT_PERMITTED_PREFIX) ? message.slice(NOT_PERMITTED_PREFIX.length) : message;
2556
+ }
2557
+ };
2558
+ function notPermittedRule(e) {
2559
+ const text = typeof e === "string" ? e : e !== null && typeof e === "object" && typeof e.message === "string" ? e.message : null;
2560
+ return text !== null && text.startsWith(NOT_PERMITTED_PREFIX) ? text.slice(NOT_PERMITTED_PREFIX.length) : null;
2561
+ }
2562
+ function isNotPermittedError(e) {
2563
+ return notPermittedRule(e) !== null;
2564
+ }
2565
+ var SENDER_MISMATCH_PREFIX = "sender mismatch: ";
2566
+ var SenderMismatchError = class extends Error {
2567
+ constructor(message) {
2568
+ super(message);
2569
+ this.name = "SenderMismatchError";
2570
+ }
2571
+ };
2572
+ function isSenderMismatchError(e) {
2573
+ const text = typeof e === "string" ? e : e !== null && typeof e === "object" && typeof e.message === "string" ? e.message : null;
2574
+ return text !== null && text.startsWith(SENDER_MISMATCH_PREFIX);
2575
+ }
2576
+ function errorFromWorker(text) {
2577
+ if (text.startsWith(NOT_PERMITTED_PREFIX)) return new NotPermittedError(text);
2578
+ if (text.startsWith(SENDER_MISMATCH_PREFIX)) return new SenderMismatchError(text);
2579
+ return new Error(text);
2580
+ }
2581
+ async function emulateSendBatch(transport, envelopes) {
2582
+ let delivered = 0;
2583
+ for (const envelope of envelopes) {
2584
+ try {
2585
+ await transport.send(envelope);
2586
+ } catch (e) {
2587
+ if (delivered === 0) throw e;
2588
+ throw new Error(`${BATCH_PARTIAL_PREFIX}${delivered}: ${describeTransportError(e)}`);
2589
+ }
2590
+ delivered += 1;
2591
+ }
2592
+ }
2593
+ function describeTransportError(e) {
2594
+ if (e && typeof e === "object") {
2595
+ const rec = e;
2596
+ const status = typeof rec.status === "number" ? rec.status : void 0;
2597
+ const message = typeof rec.message === "string" ? rec.message : String(e);
2598
+ if (message.startsWith(BATCH_PARTIAL_PREFIX)) return message;
2599
+ const parts = [];
2600
+ if (typeof rec.name === "string" && rec.name) parts.push(`${rec.name}:`);
2601
+ parts.push(message);
2602
+ if (status !== void 0 && !message.includes(`http ${status}`)) parts.push(`(http ${status})`);
2603
+ if (typeof rec.serverError === "string" && rec.serverError) parts.push(`[${rec.serverError}]`);
2604
+ return parts.join(" ");
2605
+ }
2606
+ return String(e);
2607
+ }
2608
+ function hex(b) {
2609
+ let s = "";
2610
+ for (const v of b) s += v.toString(16).padStart(2, "0");
2611
+ return s;
2612
+ }
2613
+ function hexOf(bytes) {
2614
+ let out = "";
2615
+ for (let i = 0; i < bytes.length; i++) out += bytes[i].toString(16).padStart(2, "0");
2616
+ return out;
2617
+ }
2618
+ function sameBytesU8(a, b) {
2619
+ if (a.length !== b.length) return false;
2620
+ for (let i = 0; i < a.length; i++) if (a[i] !== b[i]) return false;
2621
+ return true;
2622
+ }
2623
+ export {
2624
+ BATCH_PARTIAL_PREFIX,
2625
+ CONTENT_TYPE_CBOR,
2626
+ CONTENT_TYPE_CBOR_LEGACY_V1,
2627
+ CONTENT_TYPE_JSON,
2628
+ CONTENT_TYPE_JSON_LEGACY_V1,
2629
+ EphemeralWorkerError,
2630
+ HPKE_PQ_ENC_BYTES,
2631
+ HPKE_PQ_PUBLIC_KEY_BYTES,
2632
+ IndexedDbStorage,
2633
+ MessagingClient,
2634
+ MessagingClientClosedError,
2635
+ NOT_PERMITTED_PREFIX,
2636
+ NotPermittedError,
2637
+ PING_WIRE_CONTRACT_HEADER,
2638
+ PING_WIRE_CONTRACT_HEADER_VALUE,
2639
+ PING_WIRE_CONTRACT_VERSION,
2640
+ SENDER_MISMATCH_PREFIX,
2641
+ SenderMismatchError,
2642
+ ValidationError,
2643
+ WIRE_VERSION_MIN_ACCEPTED,
2644
+ WebSocketTransport,
2645
+ describeTransportError,
2646
+ emulateSendBatch,
2647
+ isNotPermittedError,
2648
+ isSenderMismatchError,
2649
+ negotiates,
2650
+ notPermittedRule,
2651
+ openNotificationPreview,
2652
+ validate,
2653
+ verifyApplicationContentHash
2654
+ };
2655
+ //# sourceMappingURL=index.js.map