1// Generates ux-testing/drive.mjs steps for a local build and a disposable .one fixture.
2import { readFile, writeFile } from 'node:fs/promises';
3
4const [url, fixture, output, phase = '0'] = process.argv.slice(2);
5if (!url || !fixture || !output) throw new Error('Usage: node storage_recovery.mjs APP_URL FIXTURE.one STEPS.json [0|1]');
6if (!['0', '1'].includes(phase)) throw new Error('Storage phase must be 0 or 1');
7const bytes = (await readFile(fixture)).toString('base64');
8
9async function ready() {
10 const end = Date.now() + 40000;
11 while ((!globalThis.snowboundFlushStorage || document.querySelector('#shell')) && Date.now() < end)
12 await new Promise(resolve => setTimeout(resolve, 100));
13 if (!globalThis.snowboundFlushStorage || document.querySelector('#shell')) throw new Error('App did not start');
14 const script = [...document.scripts].find(script => script.textContent.includes('import init, * as snowbound'));
15 const path = script?.textContent.match(/import init, \* as snowbound from ["']([^"']+)["']/)?.[1];
16 if (!path) throw new Error('App module import was not found');
17 const app = await import(new URL(path, location.href).href);
18 app.accessibility(true);
19 globalThis.storageProbe = {
20 app,
21 original: globalThis.snowboundFlushStorage,
22 text() {
23 const root = document.querySelector('#a11y');
24 return [root?.textContent, ...Array.from(root?.querySelectorAll('[aria-label]') ?? [], node => node.getAttribute('aria-label'))].join(' ');
25 },
26 async bytes() {
27 const root = await navigator.storage.getDirectory();
28 async function find(dir) {
29 for await (const [name, entry] of dir.entries()) {
30 if (entry.kind === 'directory') {
31 const found = await find(entry);
32 if (found) return found;
33 } else if (name === 'Storage Regression.one') {
34 return new Uint8Array(await (await entry.getFile()).arrayBuffer());
35 }
36 }
37 }
38 return find(root);
39 },
40 async disk() {
41 const bytes = await this.bytes();
42 if (!bytes) return null;
43 return { transactions: new DataView(bytes.buffer).getUint32(96, true), length: bytes.length };
44 },
45 async until(check, message) {
46 const end = Date.now() + 20000;
47 while (Date.now() < end) {
48 if (await check()) return;
49 await new Promise(resolve => setTimeout(resolve, 100));
50 }
51 throw new Error(message);
52 },
53 };
54}
55
56function arm(successfulBeforeFailure) {
57 const probe = globalThis.storageProbe;
58 probe.rejected = [];
59 probe.succeeded = 0;
60 probe.unavailable = true;
61 globalThis.snowboundFlushStorage = async () => {
62 if (probe.unavailable && probe.succeeded >= successfulBeforeFailure) {
63 probe.rejected.push(Date.now());
64 throw new Error('Injected recoverable browser storage rejection');
65 }
66 await probe.original();
67 probe.succeeded++;
68 };
69}
70
71const expression = (fn, ...args) => `(${fn})(${args.map(arg => JSON.stringify(arg)).join(',')})`;
72const steps = [
73 { goto: url },
74 { eval: expression(ready) },
75 { eval: `(async()=>{const p=storageProbe;p.app.files('open',[['Storage Regression.one',Uint8Array.from(atob(${JSON.stringify(bytes)}),c=>c.charCodeAt(0))]]);await p.until(async()=>await p.disk()&&p.text().includes('Storage Regression'),'Fixture did not open and reach OPFS');await p.original();})()` },
76];
77
78for (const [before, marker] of [[0, ' storage recovered before publication'], [1, ' storage recovered after acknowledgment']].filter(([before]) => before === Number(phase))) {
79 steps.push(
80 { eval: '(async()=>{storageProbe.base=await storageProbe.disk();})()' },
81 { eval: expression(arm, before) },
82 { click: [100, 126] },
83 { key: ['End', 'End', 35, 6] },
84 { type: marker },
85 { eval: `(async()=>{const p=storageProbe;await p.until(()=>p.rejected.length>=3,'Automatic sync did not retry the rejected flush');if(p.rejected.length>8||p.rejected.at(-1)-p.rejected[0]<1000)throw Error('Automatic sync retry loop is unbounded');const disk=await p.disk();if(disk.transactions!==p.base.transactions+${before})throw Error('Unexpected publication count during storage failure');return {rejected:p.rejected.length,disk};})()`, print: true },
86 { eval: `(async()=>{const p=storageProbe;const succeeded=p.succeeded;p.unavailable=false;await p.until(async()=>p.succeeded>succeeded&&(await p.disk()).transactions===p.base.transactions+1,'Same worker did not recover and publish exactly once');await p.original();if(!p.text().includes(${JSON.stringify(marker)}))throw Error('Recovered text is absent from the accessibility tree');return {rejected:p.rejected.length,succeeded:p.succeeded,disk:await p.disk()};})()`, print: true },
87 { goto: url },
88 { eval: expression(ready) },
89 { eval: `(async()=>{const p=storageProbe;const bytes=await p.bytes();if(!bytes)throw Error('Stored fixture is absent');p.app.files('open',[['Readback.one',bytes]]);await p.until(()=>p.text().includes(${JSON.stringify(marker)}),'Recovered edit did not survive cold opening from OPFS');return p.disk();})()`, print: true },
90 );
91}
92await writeFile(output, `${JSON.stringify(steps, null, 2)}\n`);