chat / client / test / helpers / app-fakes.mjs
  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
/**
 * Implementation-agnostic doubles + scripted scenarios for chat's own layer
 * (everything above the vendored p2p lib, which rooms-kit's helpers/fakes.mjs
 * already covers).
 *
 * Every function here is driven by BOTH `test/vectors/generate.mjs` (against the
 * TypeScript, to produce the fixtures) and `test/*.test.mjs` (against the
 * ClojureScript build, to check them). Nothing in this file knows which
 * implementation it is running: the classes arrive as arguments and hard-private
 * members are reached through a `priv(obj, name)` adapter — `__t[name]` for the
 * TS build, `obj["_" + name]` for the port.
 *
 * `Date.now` is pinned while a script runs, so timestamps land in the transcripts
 * as exact numbers.
 */

import { installClock, realSetTimeout } from "./det-clock.mjs";

const T0 = 1_700_000_000_000;

/**
 * Pins the clock for the duration of `fn`, through helpers/det-clock.mjs.
 *
 * The whole `Date` constructor is replaced, not just `Date.now`: V8 reads the
 * real system clock for `new Date()` with no arguments, and app/rooms's default
 * room label is `t("room.word") + " · " + fmtDate(new Date(), …)` — a fixture
 * that recorded that would have silently expired at midnight.
 *
 * `fn` receives the clock handle. `tick` and `now` are the pre-3b pair (advance
 * the clock, fire nothing), so vectors recorded through it stay byte-identical;
 * `advance`, `runNext`, `pending` and `ops` are the new surface.
 */
export async function withClock(t0, fn) {
  const clock = installClock({ t0, dateCtor: true });
  try {
    return await fn(clock);
  } finally {
    clock.uninstall();
  }
}

/** The seed rooms-kit's fixtures use, so author ids line up across repos. */
export const SEED = "AQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQE";
/** A 43-char base64url pub that is NOT a real key — enough for id-less paths. */
export const FAKE_PUB = "bnoc3Smwt4_ROvTFWY_v9O8qlxZuPKby5Pv8zYBQW_E";

// ------------------------------------------------------------------ doubles --

/** The slice of RoomLog that app/chat.ts and app/migrate.ts actually touch. */
export function fakeChatLog(myAuthorId = FAKE_PUB) {
  const appended = [];
  let n = 0;
  return {
    myAuthorId,
    appended,
    imgCalls: [],
    pruneCalls: [],
    getCalls: [],
    async append(op) {
      // the wire bytes, byte-exact: canonical serialisation is JSON.stringify
      // in key-insertion order (dev/docs/CLJS.md), never pr-str
      appended.push(JSON.stringify(op));
      return `hash${++n}`;
    },
    async putImage(data) {
      this.imgCalls.push(data.length);
      return { cid: "bafkreiFAKEIMAGECID", bytes: data.length };
    },
    async getImage(cid) {
      // deliberately "not fetchable (yet)": the projector then leaves the
      // attachment !complete with no blob URL, which is a DETERMINISTIC
      // snapshot. Returning bytes would make the fixture depend on how many
      // microtasks each implementation takes to finish the fetch chain.
      this.getCalls.push(cid);
      return null;
    },
    async pruneImages(keep, dropped) {
      this.pruneCalls.push([[...keep].sort(), [...dropped]]);
    },
  };
}

/** The slice of Net that app/chat.ts and app/call.ts actually touch. */
export function fakeChatNet(myId = "12D3KooWSELF") {
  const sent = [];
  return {
    myId,
    sent,
    async broadcast(payload) {
      sent.push(["broadcast", JSON.stringify(payload)]);
    },
    async sendTo(peer, payload) {
      sent.push(["sendTo", peer, JSON.stringify(payload)]);
    },
    async sendFrame() {},
    async handleFrames() {},
  };
}

/** Canvas + createImageBitmap, only for the duration of one image send. */
async function withCanvas(bitmapW, bitmapH, fn) {
  const g = globalThis;
  const realCreate = g.document.createElement;
  const realBitmap = g.createImageBitmap;
  g.createImageBitmap = async () => ({ width: bitmapW, height: bitmapH, close() {} });
  g.document.createElement = (tag) => {
    if (tag !== "canvas") return realCreate.call(g.document, tag);
    const c = {
      width: 0,
      height: 0,
      getContext: () => ({ drawImage() {} }),
      toBlob(cb, type) {
        // 64 deterministic bytes; sender re-encode output is never compared to
        // the input, only its length/type reach the log op
        cb(new Blob([new Uint8Array(64).fill(0xab)], { type }));
      },
    };
    return c;
  };
  try {
    // MUST await: a synchronous `finally` would restore the real globals
    // before reencodeImage ever touched the stub
    return await fn();
  } finally {
    g.document.createElement = realCreate;
    if (realBitmap === undefined) delete g.createImageBitmap;
    else g.createImageBitmap = realBitmap;
  }
}

/**
 * Drain the promise chains the code under test schedules, until a probe stops
 * changing. NEVER "advance by one tick": dev/docs/CLJS.md's third method rule —
 * a fixture that records a half-finished queue encodes the harness's
 * microtask-count, and TS and CLJS do not agree on that.
 */
export async function settle(probe, max = 200) {
  let prev = probe();
  for (let i = 0; i < max; i++) {
    await new Promise((r) => realSetTimeout(r, 0));
    const now = probe();
    if (now === prev && i > 2) return;
    prev = now;
  }
  throw new Error("settle: never quiesced");
}

const meta = (hash, from, clock, op) => ({ hash, from, clock, op });

/** One message's reaction tally as sorted [emoji, [authors]] pairs. */
const rxPairs = (reactions) => {
  const out = [];
  reactions.forEach((by, emoji) => out.push([emoji, [...by].sort()]));
  return out.sort((a, b) => (a[0] < b[0] ? -1 : 1));
};

/**
 * Deterministic, serialisable view of a projected Message.
 *
 * ADAPTED, NOT RE-BASELINED (Phase 5b). The Message model moved under this
 * helper — `reactions` became a Clojure map {emoji #{author}}, `ident` left the
 * message for one trust map keyed by author pub, and `img.url` left it for a
 * blob registry keyed by CID — and every fixture below still comes out
 * byte-identical. The vector is the spec; the helper follows the model.
 *
 *   `rx`     `forEach` instead of `.values()` + `r.emoji`/`r.by`. CLJS map
 *            types carry the ES6 Map surface, and their `forEach` has the same
 *            (value, key) argument order js/Map's does — but MIND THE OTHER
 *            HALF: `keys()`/`values()`/`entries()` hand back an ES6 ITERATOR,
 *            which is not itself iterable, so `[...m.reactions.entries()]`
 *            throws where the js/Map version worked. `[...m.reactions]` does
 *            iterate, but it yields MapEntry objects rather than [k, v] pairs.
 *            `forEach` is the one shape that reads both models unchanged.
 *            (CLJS SETS are plain ES6-iterable, so `[...by]` is fine.)
 *   `url`    always absent now, so always null. It was ALSO always null before:
 *            fakeChatLog's `getImage` deliberately returns null, so no fixture
 *            has ever recorded a fetched image. Kept spelled out rather than
 *            hard-coded, because the position of the key in the output is what
 *            the recorded bytes depend on.
 *   `ident`  gone, and it never fired: every `from` in the recorded scripts is
 *            "AUTHOR-X"/"AUTHOR-ME"/"", none of which is the 43-char base64url
 *            an authorship badge needs, so `attach-ident!` never ran and no
 *            fixture carries the key. The badge is covered instead — and for
 *            the first time — by test/vectors/msgs-view.json's four trust
 *            cases, which is a strictly stronger position than this line ever
 *            held.
 */
const msgView = (m) => ({
  id: m.id,
  from: m.from,
  name: m.name,
  ts: m.ts,
  ...(m.text !== undefined ? { text: m.text } : {}),
  ...(m.thread !== undefined ? { thread: m.thread } : {}),
  mine: m.mine,
  ...(m.img ? { img: { ...m.img, url: m.img.url === undefined ? null : "blob" } } : {}),
  rx: rxPairs(m.reactions),
});

// ------------------------------------------------------------------ scripts --

/**
 * Every LogOp and live payload chat's own layer builds, as wire bytes.
 * THE crown jewel: `#js {}` / `js-obj` scrambles key order at nine pairs or
 * more, and the `img` op has exactly nine with a thread (dev/docs/CLJS.md).
 */
export async function chatOpsScript({ ChatStore, APP_SALT, priv }) {
  return withClock(T0, async () => {
    const out = {};
    const log = fakeChatLog();
    const net = fakeChatNet();
    const room = { appSalt: APP_SALT, roomId: "ROOMID" };
    const self = { pub: FAKE_PUB, sig: "SIGSIGSIG", hue: 210, glyph: "🜂" };
    const store = new ChatStore(net, log, "bot", room, self);

    // chat ops: trimmed, thread optional, empty refused
    store.sendText("hello");
    store.sendText("  threaded  ", "h1");
    store.sendText("   ");
    store.sendText("x".repeat(20));

    // a target message must exist before a reaction can be toggled
    store.applyEntry(meta("h1", FAKE_PUB, 1, { t: "chat", ts: T0 - 1000, name: "bot", text: "target" }));
    store.toggleReaction("h1", "🔥"); // add
    await Promise.resolve();
    store.applyEntry(meta("r1", FAKE_PUB, 2, { t: "react", ts: T0, name: "bot", target: "h1", emoji: "🔥", op: "add" }));
    store.toggleReaction("h1", "🔥"); // now a remove
    store.toggleReaction("missing", "🔥"); // unknown target: no op

    await Promise.resolve();
    out.appendedBeforeImages = log.appended.slice();

    // the nine-key img op (and its eight-key threaded-less sibling)
    await withCanvas(3200, 1600, async () => {
      await store.sendImage(new Blob([new Uint8Array(8)], { type: "image/heic" }));
      await store.sendImage(new Blob([new Uint8Array(8)], { type: "image/heic" }), "h1");
    });
    out.appended = log.appended.slice();
    out.imgPutBytes = log.imgCalls.slice();

    // live payloads: {kind, name, ...idFields} — the spread lands after `name`
    store.setName("renamed");
    store.onChannelOpen("12D3KooWPeer");
    await Promise.resolve();
    out.sent = net.sent.slice();
    out.idFields = JSON.stringify(priv(store, "idFields")());

    // identity-less: the id fields vanish entirely (no null placeholders)
    const anonNet = fakeChatNet();
    const anon = new ChatStore(anonNet, fakeChatLog(""), "anon", room, null);
    anon.setName("anon2");
    anon.onChannelOpen("12D3KooWPeer");
    await Promise.resolve();
    out.anonSent = anonNet.sent.slice();
    out.anonIdFields = JSON.stringify(priv(anon, "idFields")());

    // hue/glyph are optional and only appear when present
    const partialNet = fakeChatNet();
    const partial = new ChatStore(partialNet, fakeChatLog(), "p", room, {
      pub: FAKE_PUB,
      sig: "S",
      hue: null,
      glyph: "",
    });
    partial.setName("p2");
    await Promise.resolve();
    out.partialSent = partialNet.sent.slice();

    // the roomsync wrapper: {kind, rooms, gone} — directed only (PROTOCOL §6)
    out.roomsyncShape = JSON.stringify({ kind: "roomsync", rooms: [], gone: [] });
    // the "started a call" system line room.ts appends
    out.callOpShape = JSON.stringify({ t: "call", ts: T0, name: "bot" });
    return out;
  });
}

/** app/call.ts's live call payload: {kind, op, audio, video, name}. */
export async function callScript({ CallManager, priv }) {
  return withClock(T0, async () => {
    const net = fakeChatNet();
    const media = {
      attachMedia() {},
      detachMedia() {},
      detachAllMedia() {},
      dropPeer(p) {
        media.dropped.push(p);
      },
      dropped: [],
      close() {},
    };
    const cm = new CallManager(net, media, () => "caller");
    const out = { payloads: {}, roster: [] };
    for (const op of ["join", "state", "leave"]) {
      out.payloads[op] = JSON.stringify(priv(cm, "statePayload")(op));
    }
    cm.onRoster = (self, members) => {
      out.roster.push([
        self === null ? null : { micOn: self.micOn, camOn: self.camOn },
        [...members.entries()].map(([id, m]) => [id, { audio: m.audio, video: m.video, name: m.name }]),
      ]);
    };
    // remote membership arrives on the topic; we are not in the call
    cm.onWire("12D3KooWA", { kind: "call", op: "join", audio: true, video: false, name: "a" });
    cm.onWire("12D3KooWA", { kind: "call", op: "state", audio: false, video: true, name: "a" });
    cm.onWire("12D3KooWB", { kind: "call", op: "join", name: "b" }); // audio defaults on
    cm.onWire("12D3KooWA", { kind: "call", op: "leave", name: "a" });
    cm.onWire("12D3KooWB", { kind: "notcall" }); // ignored
    out.active = cm.active;
    out.self = cm.self();
    out.dropped = media.dropped.slice();
    cm.onPeerGone("12D3KooWB");
    out.afterGone = [...cm.members.keys()];
    out.sent = net.sent.slice();
    return out;
  });
}

/**
 * The projector: ordering by (ts, hash), reaction folding by (clock, hash),
 * clamping of hostile timestamps/dimensions/mime, buffered reactions whose
 * target has not replicated yet, and the legacy import fold.
 */
export async function projectorScript({ ChatStore, APP_SALT }) {
  return withClock(T0, async () => {
    const out = {};
    const log = fakeChatLog("AUTHOR-ME");
    const store = new ChatStore(fakeChatNet(), log, "me", { appSalt: APP_SALT, roomId: "ROOMID" }, null);
    const changes = [];
    store.onChange = () => changes.push(1);
    const incoming = [];
    store.onIncoming = (m) => incoming.push(m.id);

    // out-of-order arrival: rendered by (ts, hash), deterministic everywhere
    store.applyEntry(meta("b", "AUTHOR-X", 1, { t: "chat", ts: 2000, name: "x", text: "second" }));
    store.applyEntry(meta("a", "AUTHOR-ME", 2, { t: "chat", ts: 1000, name: "me", text: "first" }));
    store.applyEntry(meta("c", "AUTHOR-X", 3, { t: "chat", ts: 2000, name: "x", text: "tie-breaks-by-hash" }));
    // a reaction for a message that has not arrived yet is buffered
    store.applyEntry(meta("r0", "AUTHOR-X", 4, { t: "react", ts: 3000, name: "x", target: "later", emoji: "👍", op: "add" }));
    store.applyEntry(meta("later", "AUTHOR-X", 5, { t: "chat", ts: 4000, name: "x", text: "arrives late" }));
    // remove wins by higher clock; a stale re-add by lower clock loses
    store.applyEntry(meta("r1", "AUTHOR-X", 9, { t: "react", ts: 3000, name: "x", target: "later", emoji: "👍", op: "remove" }));
    store.applyEntry(meta("r2", "AUTHOR-X", 6, { t: "react", ts: 3000, name: "x", target: "later", emoji: "👍", op: "add" }));
    // equal clock: the higher hash wins
    store.applyEntry(meta("zz", "AUTHOR-X", 9, { t: "react", ts: 3000, name: "x", target: "later", emoji: "👍", op: "add" }));
    // an author-less entry gets a per-op pseudo-author that cannot toggle
    store.applyEntry(meta("r3", "", 1, { t: "react", ts: 3000, name: "?", target: "a", emoji: "❤️", op: "add" }));
    // hostile / malformed ops must be dropped or clamped, never crash
    store.applyEntry(meta("d1", "AUTHOR-X", 1, { t: "chat", ts: 1000, name: "x" })); // no text
    store.applyEntry(meta("d2", "AUTHOR-X", 1, { t: "chat", ts: 1000, name: "x", text: "" }));
    store.applyEntry(meta("d3", "AUTHOR-X", 1, { t: "chat", ts: "nope", name: "x", text: "bad ts" }));
    store.applyEntry(meta("d4", "AUTHOR-X", 1, { t: "chat", ts: -5, name: "x", text: "negative ts" }));
    store.applyEntry(meta("d5", "AUTHOR-X", 1, { t: "chat", ts: T0 + 999_999, name: "x", text: "far future" }));
    store.applyEntry(meta("d6", "AUTHOR-X", 1, { t: "chat", ts: 1000, name: "x".repeat(80), text: "long name" }));
    store.applyEntry(meta("d7", "AUTHOR-X", 1, { t: "react", ts: 1, name: "x", target: "a", emoji: "x".repeat(9), op: "add" }));
    store.applyEntry(meta("d8", "AUTHOR-X", 1, { t: "name", ts: 1, name: "reserved" }));
    store.applyEntry(meta("d9", "AUTHOR-X", 1, { t: "unknown-op", ts: 1 }));
    // images: mime + dimension clamps, byte-size bounds
    store.applyEntry(meta("i1", "AUTHOR-X", 1, { t: "img", ts: 5000, name: "x", cid: "cid1", mime: "image/webp", bytes: 100, w: 640, h: 480 }));
    store.applyEntry(meta("i2", "AUTHOR-X", 1, { t: "img", ts: 5001, name: "x", cid: "cid2", mime: "image/svg+xml", bytes: 100, w: -1, h: 99999, thread: "a" }));
    store.applyEntry(meta("i3", "AUTHOR-X", 1, { t: "img", ts: 5002, name: "x", cid: "cid3", mime: "image/jpeg", bytes: 0, w: 1, h: 1 }));
    store.applyEntry(meta("i4", "AUTHOR-X", 1, { t: "img", ts: 5003, name: "x", bytes: 10, w: 1, h: 1 }));
    // the one-shot v1 import
    store.legacyMine.add("mine-lid");
    store.applyEntry(meta("L", "", 1, {
      t: "legacy",
      ts: 6000,
      msgs: [
        { lid: "mine-lid", from: "p1", name: "old", ts: 500, text: "legacy mine" },
        { lid: "l2", from: "p2", name: "n".repeat(50), ts: 600, text: "legacy other", thread: "mine-lid", rx: [["👍", ["pa", "pb"]], ["bad", 1], [1, ["x"]]] },
        { lid: "l3", from: "p3", name: "x", ts: 700 }, // no text: still projected
        { lid: 7, ts: 800, text: "bad lid" },
        { lid: "l4", ts: "bad", text: "bad ts" },
      ],
    }));
    await settle(() => log.getCalls.length);
    out.messages = store.messages.map(msgView);
    out.changes = changes.length > 0;
    out.incoming = incoming;
    out.threadRepliesOfA = store.threadReplies("a").map((m) => m.id);
    out.hasMessage = { a: store.hasMessage("a"), nope: store.hasMessage("nope"), legacy: store.hasMessage("v1:l2") };
    out.imageFetches = log.getCalls.slice();

    // the newest-20 image window: older attachments expire and are unpinned
    const wlog = fakeChatLog("W");
    const win = new ChatStore(fakeChatNet(), wlog, "w", { appSalt: APP_SALT, roomId: "R" }, null);
    for (let i = 0; i < 23; i++) {
      win.applyEntry(meta(`w${String(i).padStart(2, "0")}`, "W", 1, {
        t: "img", ts: 10_000 + i, name: "w", cid: `wcid${i}`, mime: "image/webp", bytes: 10, w: 2, h: 2,
      }));
    }
    await settle(() => wlog.getCalls.length + wlog.pruneCalls.length);
    out.pruneCalls = JSON.parse(JSON.stringify(wlog.pruneCalls));
    out.expired = win.messages.filter((m) => m.img?.expired).map((m) => m.id);
    out.windowFetches = wlog.getCalls.slice();

    // markLive() gates notifications: replayed history must never notify
    const live = new ChatStore(fakeChatNet(), fakeChatLog("ME"), "me", { appSalt: APP_SALT, roomId: "R" }, null);
    const liveIncoming = [];
    live.onIncoming = (m) => liveIncoming.push(m.id);
    live.applyEntry(meta("before", "X", 1, { t: "chat", ts: T0, name: "x", text: "pre-live" }));
    live.markLive();
    live.applyEntry(meta("fresh", "X", 1, { t: "chat", ts: T0, name: "x", text: "fresh" }));
    live.applyEntry(meta("old", "X", 1, { t: "chat", ts: T0 - 200_000, name: "x", text: "backfilled" }));
    live.applyEntry(meta("mine", "ME", 1, { t: "chat", ts: T0, name: "me", text: "my own" }));
    out.liveIncoming = liveIncoming;
    return out;
  });
}

/** TOFU bindings and out-of-band verification, plus the stored JSON. */
export async function trustScript({ trustObserve, trustSetVerified, trustIsVerified, nsKey, localStorageStub }) {
  localStorageStub.clear();
  const out = { steps: [] };
  const step = (label, v) => out.steps.push([label, v]);
  step("first-sight", trustObserve("Ana", "PUB-A"));
  step("same-key-again", trustObserve("ana", "PUB-A"));
  step("case-folded-and-trimmed", trustObserve("  ANA  ", "PUB-A"));
  step("key-changed", trustObserve("Ana", "PUB-B"));
  step("unverified", trustIsVerified("PUB-A"));
  trustSetVerified("PUB-B", "Ana", true);
  step("after-verify-A", trustObserve("Ana", "PUB-A"));
  step("after-verify-B", trustObserve("Ana", "PUB-B"));
  step("isVerified-B", trustIsVerified("PUB-B"));
  trustSetVerified("PUB-B", "Ana", false);
  step("after-unverify", trustIsVerified("PUB-B"));
  // attacker-chosen display names must hit own properties, never the prototype
  step("proto-name", trustObserve("__proto__", "PUB-P"));
  step("constructor-name", trustObserve("constructor", "PUB-C"));
  step("proto-again", trustObserve("__proto__", "PUB-OTHER"));
  out.stored = JSON.parse(localStorageStub.getItem(nsKey("trust")));
  out.storedRaw = localStorageStub.getItem(nsKey("trust"));
  // garbage in storage must not throw
  localStorageStub.setItem(nsKey("trust"), "{{{not json");
  step("after-garbage", trustObserve("Ana", "PUB-A"));
  localStorageStub.setItem(nsKey("trust"), JSON.stringify({ names: { a: 1, b: "PUB" }, verified: null }));
  step("after-typed-garbage", trustObserve("b", "PUB"));
  localStorageStub.clear();
  return out;
}

/** The room directory + the same-identity merge (PROTOCOL.md §6). */
export async function roomsScript(M) {
  const { touchRoom, renameRoom, forgetRoom, buildRoomSync, mergeRooms, loadRooms, nsKey, localStorageStub } = M;
  const A = "A".repeat(43);
  const B = "B".repeat(43);
  const C = "C".repeat(43);
  return withClock(T0, async (clock) => {
    localStorageStub.clear();
    const out = { steps: [] };
    const snap = (label) => out.steps.push([label, JSON.parse(JSON.stringify({
      rooms: loadRooms(),
      gone: JSON.parse(localStorageStub.getItem(nsKey("rooms-gone")) ?? "[]"),
    }))]);

    out.firstVisit = JSON.parse(JSON.stringify(touchRoom(A)));
    snap("after-first-visit");
    clock.tick(60_000);
    touchRoom(B);
    renameRoom(B, "  the other room  ");
    renameRoom(C, "no such room");
    snap("after-second-room");
    clock.tick(60_000);
    forgetRoom(A);
    snap("after-forget");
    clock.tick(60_000);
    out.rejoin = JSON.parse(JSON.stringify(touchRoom(A))); // beats its own tombstone
    snap("after-rejoin");
    out.buildRoomSync = JSON.parse(JSON.stringify(buildRoomSync()));

    // ---- merge: remote input from a device that proved OUR identity --------
    clock.tick(60_000);
    out.merges = [];
    const merge = (label, remote, current) => {
      const added = mergeRooms(remote, current);
      out.merges.push([label, added, JSON.parse(JSON.stringify({
        rooms: loadRooms(),
        gone: JSON.parse(localStorageStub.getItem(nsKey("rooms-gone")) ?? "[]"),
      }))]);
    };
    merge("not-an-array", { rooms: "nope", gone: null }, A);
    merge("new-room", { rooms: [{ s: C, label: "from other device", ts: clock.now(), lts: clock.now() }], gone: [] }, A);
    merge("bad-secrets", {
      rooms: [{ s: "too-short", label: "x", ts: 1 }, { s: 42, label: "x", ts: 1 }, { s: "!".repeat(43), label: "x", ts: 1 }],
      gone: [],
    }, A);
    merge("control-chars-and-length", {
      rooms: [{ s: C, label: `stripme${"y".repeat(60)}`, ts: clock.now() + 1, lts: clock.now() + 1 }],
      gone: [],
    }, A);
    merge("empty-label-gets-default", { rooms: [{ s: B, label: "", ts: 1, lts: clock.now() + 5 }], gone: [] }, A);
    merge("future-ts-clamped", { rooms: [{ s: B, label: "clamped", ts: clock.now() + 999_999_999, lts: clock.now() + 999_999_999 }], gone: [] }, A);
    merge("dedupe-within-payload", {
      rooms: [{ s: C, label: "older", ts: 10 }, { s: C, label: "newer", ts: clock.now(), lts: clock.now() + 9 }],
      gone: [],
    }, A);
    merge("remote-tombstone-wins", { rooms: [], gone: [{ s: C, ts: clock.now() + 10 }] }, A);
    merge("tombstone-never-for-current", { rooms: [], gone: [{ s: A, ts: clock.now() + 10 }] }, A);
    merge("entry-newer-than-tombstone", { rooms: [{ s: C, label: "back", ts: clock.now() + 20 }], gone: [] }, A);
    merge("caps", {
      rooms: Array.from({ length: 60 }, (_, i) => ({ s: `${String(i).padStart(2, "0")}${"z".repeat(41)}`, label: `r${i}`, ts: 1000 + i })),
      gone: [],
    }, A);
    out.finalCount = loadRooms().length;
    localStorageStub.clear();
    return out;
  });
}

/** The one-shot v1 → v2 history import (app/migrate.ts). */
export async function migrateScript(M) {
  const { migrateLegacyHistory, ChatStore, RoomCrypto, APP_SALT, nsKey, localStorageStub } = M;
  const secret = "M".repeat(43);
  const saltV1 = APP_SALT.replace(/\/v2$/, "/v1");
  const roomIdV1 = (await RoomCrypto.create(secret, saltV1)).roomId;
  await putHistory(roomIdV1, {
    savedAt: 1,
    mineIds: ["p1:1", 42],
    msgs: [
      { id: "p1:1", from: "p1", name: "mine", ts: 1000, seq: 1, text: "hello v1" },
      { id: "p1:2", from: "p1", name: "n".repeat(60), ts: 1001, seq: 2, text: "x".repeat(9000), thread: "p1:1", rx: [["👍", ["p2"]]] },
      { id: "p2:1", from: "p2", name: "img", ts: 1002, seq: 1, img: { w: 1, h: 1, bytes: 1 } },
      { id: "p2:2", from: "p2", name: "blank", ts: 1003, seq: 2, text: "" },
      { id: 7, from: "p2", name: "bad id", ts: 1004, seq: 3, text: "x" },
      { id: "p2:3", from: "p2", name: "bad ts", ts: "no", seq: 4, text: "x" },
    ],
  });
  return withClock(T0, async () => {
    localStorageStub.clear();
    const out = {};
    const log = fakeChatLog();
    const store = new ChatStore(fakeChatNet(), log, "me", { appSalt: APP_SALT, roomId: "R" }, null);
    out.roomIdV1 = roomIdV1;
    out.flagKey = nsKey(`migrated:${roomIdV1}`);
    out.published = await migrateLegacyHistory(secret, APP_SALT, log, store);
    out.appended = log.appended.slice();
    out.legacyMine = [...store.legacyMine].sort();
    out.flag = localStorageStub.getItem(out.flagKey);
    // second run on the same device is a no-op (the flag is set)
    out.secondRun = await migrateLegacyHistory(secret, APP_SALT, log, store);
    // and with the flag cleared, the already-folded ids stop it instead
    localStorageStub.removeItem(out.flagKey);
    const store2 = new ChatStore(fakeChatNet(), fakeChatLog(), "me", { appSalt: APP_SALT, roomId: "R" }, null);
    store2.applyEntry(meta("L", "", 1, { t: "legacy", ts: 1, msgs: [{ lid: "p1:1", from: "p1", name: "old", ts: 1000, text: "hello v1" }] }));
    const log3 = fakeChatLog();
    out.probeGuard = await migrateLegacyHistory(secret, APP_SALT, log3, store2);
    out.probeGuardAppended = log3.appended.length;
    // an absent v1 record is a silent zero
    out.absent = await migrateLegacyHistory("Z".repeat(43), APP_SALT, fakeChatLog(), store);
    // batching: 130 messages become 3 legacy ops of 60/60/10
    await putHistory((await RoomCrypto.create("Q".repeat(43), saltV1)).roomId, {
      savedAt: 1,
      mineIds: [],
      msgs: Array.from({ length: 130 }, (_, i) => ({ id: `q:${i}`, from: "q", name: "q", ts: 1000 + i, seq: i, text: `m${i}` })),
    });
    const logQ = fakeChatLog();
    out.batched = await migrateLegacyHistory("Q".repeat(43), APP_SALT, logQ, new ChatStore(fakeChatNet(), logQ, "q", { appSalt: APP_SALT, roomId: "R" }, null));
    out.batchSizes = logQ.appended.map((s) => JSON.parse(s).msgs.length);
    localStorageStub.clear();
    return out;
  });
}

/** The legacy-namespace storage migration (app/migrate-storage.ts). */
export async function storageScript(M) {
  const { migrateStorageNS, NS, nsDb, nsKey, localStorageStub } = M;
  // the marker is `String(Date.now())`, so the clock must be pinned or the
  // fixture would record the generating machine's wall clock
  return withClock(T0, async () => storageBody(M, { migrateStorageNS, NS, nsDb, nsKey, localStorageStub }));
}

async function storageBody(_M, { migrateStorageNS, NS, nsDb, nsKey, localStorageStub }) {
  const out = {};
  localStorageStub.clear();

  // a fresh install: nothing to move, but the marker must be set so the scan
  // never runs again
  await migrateStorageNS();
  out.fresh = localStorageStub.snapshot();

  localStorageStub.clear();
  for (const [k, v] of [
    ["sueta:id", "SEEDSEED"],
    ["sueta:name", "ana"],
    ["sueta:notify", "1"],
    ["sueta:trust", '{"names":{},"verified":{}}'],
    ["sueta:rooms", '[{"s":"A","label":"l","ts":1}]'],
    ["sueta:migrated:XYZ", "123"],
    ["sueta:unrelated", "keep-me-put"],
    ["sueta:rooms-gone", "[]"], // NOT in LS_KEYS — deliberately not migrated
    [`${NS}:name`, "already-there"], // an existing target is never overwritten
  ]) {
    localStorageStub.setItem(k, v);
  }
  await putIdb("sueta-blocks", "sueta-blocks", [["k1", "v1"], ["k2", "v2"]]);
  await putIdb("sueta-data", "sueta-data", [["d1", "x"]]);
  const warnings = [];
  await migrateStorageNS((m) => warnings.push(m));
  out.migrated = localStorageStub.snapshot();
  out.warnings = warnings;
  out.markerIsTimestamp = /^\d+$/.test(localStorageStub.getItem(nsKey("storage-migrated")) ?? "");
  out.blocks = await readIdb(nsDb("blocks"), nsDb("blocks"));
  out.data = await readIdb(nsDb("data"), nsDb("data"));
  out.legacyKept = await readIdb("sueta-blocks", "sueta-blocks");

  // a second run is a no-op
  localStorageStub.setItem("sueta:name", "changed-after");
  await migrateStorageNS();
  out.secondRun = localStorageStub.getItem(nsKey("name"));
  localStorageStub.clear();
  return out;
}

/** The read-only v1 history loader (app/history.ts). */
export async function historyScript({ loadHistory }) {
  const rec = { savedAt: 7, mineIds: ["a"], msgs: [{ id: "a", from: "p", name: "n", ts: 1, seq: 1, text: "t" }] };
  await putHistory("ROOM-H", rec);
  return {
    hit: JSON.parse(JSON.stringify(await loadHistory("ROOM-H"))),
    miss: await loadHistory("NO-SUCH-ROOM"),
  };
}

/** The mailbox: envelope bytes, the persistent queue, dedup, replay. */
export async function mailboxScript(M) {
  const { MailboxAuth, MailboxClient, MailboxSync, RoomCrypto, APP_SALT, nsKey, priv, localStorageStub } = M;
  const { installDetRandom, resetRandom, restoreRandom } = await import("./det-random.mjs");
  const hex = (u8) => [...u8].map((b) => b.toString(16).padStart(2, "0")).join("");
  const out = {};
  const realFetch = globalThis.fetch;

  return withClock(T0, async (clock) => {
    try {
      localStorageStub.clear();

      // ---- auth: open mint, cached until 5 min before expiry --------------
      let mints = 0;
      const urls = [];
      globalThis.fetch = async (url) => {
        urls.push(String(url));
        mints++;
        return { ok: true, status: 200, json: async () => ({ token: `tok${mints}`, ttl: 3600 }) };
      };
      const auth = new MailboxAuth("https://relay.example/mint", "MBX ROOM/ID");
      out.auth = { first: await auth.get() };
      out.auth.cached = await auth.get();
      clock.tick(3600_000 - 300_000 - 1);
      out.auth.stillCached = await auth.get();
      clock.tick(2);
      out.auth.reminted = await auth.get();
      auth.invalidate();
      out.auth.afterInvalidate = await auth.get();
      out.auth.urls = urls.slice();
      out.auth.mints = mints;

      // ---- client: status → typed result table ---------------------------
      const reqs = [];
      let respond = null;
      let mintN = 0;
      globalThis.fetch = async (url, init) => {
        // the mint and the message endpoint are DIFFERENT requests: every
        // MailboxClient call first pulls a bearer from MailboxAuth, so a stub
        // that answers both with the deposit response makes every case "net"
        if (String(url).includes("/mint")) {
          return { ok: true, status: 200, json: async () => ({ token: `tok${++mintN}`, ttl: 3600 }) };
        }
        reqs.push([String(url), init?.method ?? "GET", init?.headers?.authorization ?? null]);
        return respond();
      };
      const mkClient = () => new MailboxClient("https://relay.example/mbx/", "MBX ROOM/ID", new MailboxAuth("https://relay.example/mint", "MBX ROOM/ID"));
      out.deposit = {};
      const depositCases = {
        created: () => ({ ok: true, status: 201, json: async () => ({ deduped: false, seq: "0001" }) }),
        deduped: () => ({ ok: true, status: 200, json: async () => ({ deduped: true, seq: "0001" }) }),
        "no-json": () => ({ ok: true, status: 200, json: async () => { throw new Error("x"); } }),
        "too-large": () => ({ ok: false, status: 413, json: async () => ({}) }),
        auth: () => ({ ok: false, status: 401, json: async () => ({}) }),
        forbidden: () => ({ ok: false, status: 403, json: async () => ({}) }),
        throttled: () => ({ ok: false, status: 429, json: async () => ({}) }),
        full: () => ({ ok: false, status: 507, json: async () => ({}) }),
        server: () => ({ ok: false, status: 500, json: async () => ({}) }),
      };
      for (const [label, impl] of Object.entries(depositCases)) {
        respond = impl;
        out.deposit[label] = JSON.parse(JSON.stringify(await mkClient().deposit(new Uint8Array([1, 2, 3]))));
      }
      respond = async () => { throw new Error("offline"); };
      out.deposit.network = JSON.parse(JSON.stringify(await mkClient().deposit(new Uint8Array([1]))));

      out.replay = {};
      reqs.length = 0;
      respond = () => ({ ok: true, status: 200, json: async () => ({ messages: [{ seq: "0002", id: "i", ts: 1, payload: "AQ==" }], has_more: true, oldest_seq: "0001", latest_seq: "0009" }) });
      out.replay.page = JSON.parse(JSON.stringify(await mkClient().replay("0001", 100)));
      out.replay.noCursor = JSON.parse(JSON.stringify(await mkClient().replay(null, 50)));
      respond = () => ({ ok: true, status: 200, json: async () => ({}) });
      out.replay.empty = JSON.parse(JSON.stringify(await mkClient().replay(null, 10)));
      respond = () => ({ ok: false, status: 401, json: async () => ({}) });
      out.replay.auth = JSON.parse(JSON.stringify(await mkClient().replay(null, 10)));
      out.replay.urls = reqs.map((r) => r[0]);
      out.replay.reqs = reqs.map((r) => [r[0], r[1], r[2]]);

      // ---- sync: envelope bytes, queue persistence, dedup ----------------
      const rc = await RoomCrypto.create("X".repeat(43), APP_SALT, "12D3KooWMbx");
      const cipher = await rc.mbxCipher();
      const keys = {
        cursor: nsKey("mbx-cursor:R"),
        queue: nsKey("mbx-queue:R"),
        sent: nsKey("mbx-sent:R"),
        retry: nsKey("mbx-retry:R"),
        ident: nsKey("mbx-ident:R"),
      };
      out.keys = keys;

      // A real CID + block so the 0x01 envelope is byte-checkable. The entry
      // hash is a base58btc dag-cbor CID, exactly as OrbitDB produces.
      const { CID } = await import("multiformats/cid");
      const { base58btc } = await import("multiformats/bases/base58");
      const { sha256 } = await import("multiformats/hashes/sha2");
      const entryBlock = new Uint8Array([0xa1, 0x61, 0x61, 0x01]); // dag-cbor {a:1}
      const entryCid = CID.createV1(0x71, await sha256.digest(entryBlock));
      const entryHash = entryCid.toString(base58btc);
      const imgBlock = new Uint8Array([9, 9, 9]);
      const imgCid = CID.createV1(0x55, await sha256.digest(imgBlock));
      const identBlock = new Uint8Array([1, 2, 3, 4]);
      const identCid = CID.createV1(0x71, await sha256.digest(identBlock));

      const deposits = [];
      const client = {
        async deposit(payload) {
          deposits.push(hex(payload));
          return { ok: true, deduped: false, seq: `s${deposits.length}` };
        },
        async replay() {
          return { ok: false, kind: "net" };
        },
      };
      const log = {
        onAppended: null,
        onImageStored: null,
        imageChunkBytes: null,
        async sealedEntryBytes(h) {
          return h === entryHash ? entryBlock : null;
        },
        async rawBlock() {
          return imgBlock;
        },
        myIdentityBlock() {
          return { cid: identCid, bytes: identBlock };
        },
        async imageDagBlocks() {
          return [{ cid: imgCid, bytes: imgBlock }];
        },
        async hasEntry() {
          return false;
        },
        async decodeSealedEntry() {
          return null;
        },
        async putEntryBlock() {},
        async putRawBlock(cid) {
          rawPuts.push(cid.toString());
        },
        async putIdentityBlock(cid) {
          identPuts.push(cid.toString());
        },
        async ingestEntry() {
          return "rejected";
        },
        async entryMeta() {
          return null;
        },
        async emitUnseen() {},
        async pinImageIfLocal() {
          return true;
        },
      };
      const rawPuts = [];
      const identPuts = [];

      installDetRandom();
      resetRandom(77);
      const sync = new MailboxSync({ log, client, cipher, maxMessageKb: 64, keys, hasIdentity: true });
      out.stateEmpty = JSON.parse(JSON.stringify(sync.state));
      // the identity record is enqueued once, ahead of the first entry
      sync.enqueueEntry(entryHash);
      out.queueAfterEntry = JSON.parse(localStorageStub.getItem(keys.queue));
      await settle(() => deposits.length);
      out.deposits = deposits.slice();
      out.identFlag = localStorageStub.getItem(keys.ident);
      out.sent = JSON.parse(localStorageStub.getItem(keys.sent) ?? "[]");
      // a re-enqueue of a deposited hash is dropped
      sync.enqueueEntry(entryHash);
      out.queueAfterRepeat = JSON.parse(localStorageStub.getItem(keys.queue) ?? "[]");
      // the identity envelope is 0x02 | mbx-seal(cid||block); random IV, so its
      // bytes are pinned only under the deterministic stream above
      out.identEnvelopePrefix = out.deposits.map((d) => d.slice(0, 2));

      // queue-shape fixtures (localStorage JSON: key order is on disk)
      out.qItemShapes = {
        entry: JSON.stringify({ t: "entry", hash: entryHash }),
        img: JSON.stringify({ t: "img", cid: imgCid.toString(), group: "root" }),
        ident: JSON.stringify({ t: "ident" }),
      };

      // an over-cap payload is dropped exactly like a 413
      const small = new MailboxSync({ log, client, cipher, maxMessageKb: 0, keys: { ...keys, queue: nsKey("mbx-queue:S") }, hasIdentity: false });
      small.enqueueEntry(entryHash);
      await settle(() => (localStorageStub.getItem(nsKey("mbx-queue:S")) ?? "").length);
      out.overCapQueue = JSON.parse(localStorageStub.getItem(nsKey("mbx-queue:S")) ?? "[]");

      // replay: prefix classification, CID re-hash, sealed identity blocks
      const toB64 = (u8) => Buffer.from(u8).toString("base64");
      const cat = (...parts) => {
        const n = parts.reduce((a, p) => a + p.length, 0);
        const o = new Uint8Array(n);
        let off = 0;
        for (const p of parts) {
          o.set(p, off);
          off += p.length;
        }
        return o;
      };
      const sync2 = new MailboxSync({ log, client, cipher, maxMessageKb: 64, keys: { ...keys, queue: nsKey("mbx-queue:P") }, hasIdentity: false });
      const process = priv(sync2, "processMessage");
      const cases = {
        "raw-image-block": toB64(cat(new Uint8Array([1]), imgCid.bytes, imgBlock)),
        "wrong-prefix": toB64(cat(new Uint8Array([9]), imgCid.bytes, imgBlock)),
        "too-short": toB64(new Uint8Array([1])),
        "cid-mismatch": toB64(cat(new Uint8Array([1]), imgCid.bytes, new Uint8Array([8, 8, 8]))),
        "sealed-not-ours": toB64(cat(new Uint8Array([2]), new Uint8Array(40))),
        garbage: toB64(cat(new Uint8Array([1]), new Uint8Array([255, 255, 255, 255]))),
      };
      out.processed = {};
      for (const [label, payload] of Object.entries(cases)) {
        rawPuts.length = 0;
        identPuts.length = 0;
        const collected = [];
        await process({ seq: "1", id: "i", ts: 1, payload }, collected);
        out.processed[label] = { rawPuts: rawPuts.slice(), identPuts: identPuts.slice(), collected: collected.length };
      }
      // a real sealed identity record round-trips and is stored
      const sealedIdent = await cipher.seal(cat(identCid.bytes, identBlock));
      rawPuts.length = 0;
      identPuts.length = 0;
      await process({ seq: "1", id: "i", ts: 1, payload: toB64(cat(new Uint8Array([2]), sealedIdent)) }, []);
      out.processed["sealed-identity"] = { rawPuts: rawPuts.slice(), identPuts: identPuts.slice(), collected: 0 };

      restoreRandom();
      localStorageStub.clear();
      return out;
    } finally {
      restoreRandom();
      globalThis.fetch = realFetch;
    }
  });
}

// -------------------------------------------------------------- IDB helpers --

const DB_HISTORY = "sueta-history";

function idbOpen(name, upgrade) {
  return new Promise((resolve, reject) => {
    const req = indexedDB.open(name, 1);
    req.onupgradeneeded = () => upgrade(req.result);
    req.onsuccess = () => resolve(req.result);
    req.onerror = () => reject(req.error);
  });
}

export async function putHistory(roomId, rec) {
  const db = await idbOpen(DB_HISTORY, (d) => {
    if (!d.objectStoreNames.contains("rooms")) d.createObjectStore("rooms");
  });
  await new Promise((resolve, reject) => {
    const tx = db.transaction("rooms", "readwrite");
    tx.objectStore("rooms").put(rec, roomId);
    tx.oncomplete = () => resolve();
    tx.onerror = () => reject(tx.error);
  });
  db.close();
}

export async function putIdb(dbName, storeName, rows) {
  const db = await idbOpen(dbName, (d) => {
    if (!d.objectStoreNames.contains(storeName)) d.createObjectStore(storeName);
  });
  await new Promise((resolve, reject) => {
    const tx = db.transaction(storeName, "readwrite");
    for (const [k, v] of rows) tx.objectStore(storeName).put(v, k);
    tx.oncomplete = () => resolve();
    tx.onerror = () => reject(tx.error);
  });
  db.close();
}

export async function readIdb(dbName, storeName) {
  const all = await indexedDB.databases?.();
  if (all && !all.some((d) => d.name === dbName)) return null;
  const db = await idbOpen(dbName, () => {});
  if (!db.objectStoreNames.contains(storeName)) {
    db.close();
    return null;
  }
  const rows = await new Promise((resolve, reject) => {
    const req = db.transaction(storeName).objectStore(storeName).openCursor();
    const out = [];
    req.onsuccess = () => {
      const c = req.result;
      if (c) {
        out.push([String(c.key), String(c.value)]);
        c.continue();
      } else resolve(out);
    };
    req.onerror = () => reject(req.error);
  });
  db.close();
  return rows.sort((a, b) => (a[0] < b[0] ? -1 : 1));
}

static mirror of HEAD · about · clone: git clone https://git.ardegazu.ro/chat.git