Oregami
Repositories/oxedyne/fe2o3

oxedyne/fe2o3/fe2o3_net/lens/js/test/adapter/make_adapter.mjs

9.2 KiB, 1 run

created by r1870400018:65610, which is this file's identity for as long as the history lasts, whatever it is later renamed to

download · who wrote it · its history

1// make_adapter.mjs -- builds `daimond_debugshare.js`: what Daimond's `www/js/debugshare.js` becomes
2// when it adopts the extracted writer core.
3//
4// node test/adapter/make_adapter.mjs <path to daimond/www/js/debugshare.js>
5//
6// The app layer (the Settings flag and its sync, the snapshot and telemetry lanes, the beat, the
7// screen, the fold inference, the indicator) is cut from Daimond's own file by line range, so it
8// is Daimond's code and not a rewrite. What the core now owns (the outbox, the envelope, the
9// fit, the drain and its clock, console and error capture, the redactor, the scrubber) is
10// replaced by the glue below. The result is committed, so the test needs no Daimond file but the
11// two it runs; this script is how it was made, and the line ranges are valid for the file whose
12// sha-256 begins as recorded in `T5b_record.md`.
13import { readFileSync, writeFileSync } from 'node:fs';
14import { dirname, join } from 'node:path';
15import { fileURLToPath } from 'node:url';
16
17const HERE = dirname(fileURLToPath(import.meta.url));
18const src = readFileSync(process.argv[2], 'utf8').split('\n');
19const seg = (a, b) => src.slice(a - 1, b).join('\n');
20
21function sub(text, from, to) {
22 if (text.split(from).length !== 2) throw new Error('expected exactly one: ' + from.slice(0, 70));
23 return text.replace(from, () => to);
24}
25
26// ── Daimond's own text, by line range ──
27let consts = [seg(113, 145), seg(153, 156), seg(163, 165), seg(166, 182), seg(199, 240)].join('\n');
28let reading = [seg(319, 345), seg(358, 374)].join('\n');
29let assembly = [seg(682, 774), seg(776, 1036)].join('\n');
30let caps = seg(1209, 1226);
31let fold = seg(1287, 1315);
32let beat = seg(1507, 1553);
33let device = seg(1596, 1599);
34let enqueue = seg(1711, 1734);
35let indic = seg(1736, 1803);
36let sw = seg(1805, 2075);
37let exports = seg(2164, 2245);
38
39// ── What changes where the core took over ──
40beat = sub(beat, 'ob: outbox.length,', 'ob: W.depth(),');
41beat = sub(beat, 'throttled: throttledCount,', 'throttled: W.health().throttled,');
42beat = sub(beat, 'postFail: postFailCount,', 'postFail: W.health().postFail,');
43beat = sub(beat, 'cdrop: (function () { var n = conDropped; conDropped = 0; return n; })(),', 'cdrop: W.takeConsoleDropped(),');
44beat = sub(beat, 'flushConsole(now, true);', 'W.flushConsole(now, true);');
45fold = sub(fold, "emit('fold', {", "W.event('fold', {");
46fold = sub(fold, 'catch (e) { fault(e); }', 'catch (e) { W.fault(e); }');
47const a = sw.indexOf('\t\t\t// AND THE OUTBOX.');
48const b = sw.indexOf('\t\t\tpersistNow();') + '\t\t\tpersistNow();'.length;
49if (a < 0 || b < a) throw new Error('applyState off-branch not found');
50sw = sw.slice(0, a) + '\t\t\t// The outbox, and what the console lane held, go with it: see `W.reset`.\n\t\t\tW.reset();' + sw.slice(b);
51enqueue = enqueue.replace(/(?<![.\w])drain\(\)/g, 'W.drain()');
52sw = sw.replace(/(?<![.\w])drain\(\)/g, 'W.drain()');
53// `feedOff` was a local; the writer owns it now.
54const feed = (t) => t.replace(/\bfeedOff\b/g, '!W.ok()');
55beat = feed(beat); enqueue = feed(enqueue); sw = feed(sw); exports = feed(exports);
56exports = sub(exports, 'outboxDepth: function () { return outbox.length; },', 'outboxDepth: function () { return W.depth(); },');
57exports = sub(exports, '_outbox: function () { return outbox.slice(); },', '_outbox: function () { return W.outbox(); },');
58exports = sub(exports, '_backoffMs: function (n) { failStreak = n; return backoffMs(); },', '_backoffMs: function (n) { return W.backoffMs(n); },');
59exports = sub(exports, '_drain: drain,', '_drain: function () { return W.drain(); },');
60const h0 = exports.indexOf('\t\t_health: function () {');
61const h1 = exports.indexOf('\t\t},', h0) + '\t\t},'.length;
62exports = exports.slice(0, h0) + '\t\t_health: function () { return W.health(); },' + exports.slice(h1);
63
64const out = `/* daimond_debugshare.js -- GENERATED by make_adapter.mjs. Daimond's www/js/debugshare.js as it
65 * would stand after adopting fe2o3_net/lens/js/writer.js: its own app layer, cut from its own
66 * file by line range, over the extracted writer core in \`__lensCore\`.
67 *
68 * It is a classic script, evaluated by Daimond's own test harness exactly as the original is, so
69 * the core arrives as a global the preload supplies; in the page it would be an import.
70 */
71(function () {
72\t'use strict';
73\tvar L = __lensCore;
74
75${consts.split('\n').slice(1).join('\n')}
76
77\t// ── App state. What the writer owns (the outbox, the post clock, the console lane) is gone. ──
78\tvar enabled = read(ENABLED_KEY) === '1';
79\tvar provider = null; // registered by daimond.js: () -> (obj | Promise<obj>)
80\tvar statsFn = null; // registered by daimond.js: () -> live-stats obj (sync, cheap)
81\tvar screenFn = null; // registered by daimond.js: () -> {view,seat,role,text,dlg,comp,locked}
82\tvar crossIx = {}; // diamondId -> model -> {turns, usd}, filled while on
83\tvar telQueue = []; // priority lane: telemetry posts, each an array of rows
84\tvar snapQueue = []; // snapshot lane: drained only when telQueue is empty
85\tvar telTimer = null, snapTimer = null, beatTimer = null;
86\tvar lastBeatAt = 0;
87\tvar lastScreenAt = 0, lastScreenKey = null;
88\tvar lastCtx = {};
89\tvar lastRealFold = {};
90\tvar indicator = null;
91\tvar lastLedgerLen = 0, lastTrailLen = 0, lastDiagLen = 0;
92
93${reading}
94
95\t// ── Names, content shapes and the redactor: the core's, with Daimond's two parameters. ──
96\tvar SCRUB = L.createScrubber({
97\t\t// The gateway's own session cookie. It is HttpOnly, so this app cannot read it, but a server
98\t\t// log line pasted into a chat is not bound by that.
99\t\tpairs: [{ k: 'cookie', g: 2, re: /(daimond_gw_sess=)([^;,\\s"'\\[\\]]{4,})/g }],
100\t\t// \`body\` is the archive's own snapshot FILENAME, which the entropy catch used to take.
101\t\tidKeys: { holder: 1, self: 1, nominated: 1, body: 1 },
102\t});
103\tvar REDACT = L.createRedactor();
104\tvar REDACT_CONFIG = L.createRedactor({ loose: true });
105\tfunction scrubText(s, isId) { return SCRUB.text(s, isId); }
106\tfunction scrubDeep(o) { return SCRUB.deep(o); }
107\tfunction redact(o) { return REDACT.value(o); }
108\tfunction redactConfig(o) { return REDACT_CONFIG.value(o); }
109\tfunction fingerprint(v) { return L.fingerprint(v); }
110\tfunction byteLen(s) { return L.byteLen(s); }
111\tfunction str(o) { return JSON.stringify(o); }
112
113${assembly}
114
115${caps}
116
117${fold}
118
119${beat}
120
121${device}
122
123\t// ── The writer core, handed Daimond's seams ──
124\tfunction buildRaw() {
125\t\ttry {
126\t\t\tif (window.DaimondUpdater && DaimondUpdater.booted && DaimondUpdater.booted()) return DaimondUpdater.booted();
127\t\t} catch (e) { /* the updater has not polled */ }
128\t\treturn read(BUILD_KEY) || '';
129\t}
130\tvar W = L.createWriter({
131\t\thost: { storage: localStorage, setTimeout: setTimeout, clearTimeout: clearTimeout, console: console,
132\t\t now: function () { return Date.now(); }, document: typeof document !== 'undefined' ? document : null,
133 // Read at call time, so the test that swaps the tab's Error for one with no stack is seen.
134 get Error() { return Error; } },
135\t\tkeys: { outbox: EVENT_KEY, seq: SEQ_KEY, postAt: POST_AT_KEY },
136\t\tdevice: deviceId,
137\t\tbuild: buildRaw,
138\t\tenabled: function () { return enabled; },
139\t\tsend: function (rows) {
140\t\t\treturn fetch(ENDPOINT, {
141\t\t\t\tmethod: 'POST',
142\t\t\t\tcredentials: 'same-origin',
143\t\t\t\theaders: { 'content-type': 'application/json', 'x-daimond-api': String(CLIENT_API) },
144\t\t\t\tbody: W.postBody(rows),
145\t\t\t});
146\t\t},
147\t\tredact: REDACT,
148\t\tscrub: SCRUB,
149\t\textra: function (kind) {
150\t\t\tif (kind !== 'boot' && kind !== 'beat') return null;
151\t\t\tvar cap = capabilities();
152\t\t\treturn { tools: cap.tools, folder: cap.folder, mayCommit: cap.mayCommit };
153\t\t},
154\t\tlane: {
155\t\t\tpending: function () { return telQueue.length > 0 || snapQueue.length > 0; },
156\t\t\tnext: function () { return telQueue.length ? telQueue.shift() : snapQueue.shift(); },
157\t\t},
158\t\townPath: ENDPOINT,
159\t\tskipFrames: ['debugshare.js'],
160\t\tafter: function (kind, payload) { if (kind === 'round') inferFold(payload); },
161\t\tonFault: function () { stopTimers(); },
162\t\tcaps: { gapMs: DRAIN_MS },
163\t});
164\tfunction clip(s, n) { return W.clip(s, n); }
165\tfunction event(kind, payload) { return W.event(kind, payload); }
166\tfunction fault(e) { W.fault(e); }
167\tfunction noteFetchFail(p, s, l, e) { return W.noteFetchFail(p, s, l, e); }
168\tfunction persistNow() { W.persistNow(); }
169\tfunction noteError(m, w) { W.noteError(m, w); }
170\tfunction noteConsole(lvl, args) { W.noteConsole(lvl, args); }
171\tfunction flushConsole(t, force) { W.flushConsole(t, force); }
172\tfunction looksSecret(m) { return L.looksSecret(m); }
173\tfunction gapLeft() { return W.gapLeft(); }
174\tfunction fit(o) { return W.fit(o); }
175\tfunction eventBatch() { return W.eventBatch(); }
176
177${enqueue}
178
179${indic}
180
181${sw}
182
183\t// ── Capture: errors, the console, and the page going away. All three are the core's. ──
184\tW.captureErrors(window);
185\tW.captureConsole(typeof console !== 'undefined' ? console : null);
186\tW.captureLifecycle(window, typeof document !== 'undefined' ? document : undefined);
187
188${exports}
189`;
190writeFileSync(join(HERE, 'daimond_debugshare.js'), out);
191console.log('wrote daimond_debugshare.js, ' + out.split('\n').length + ' lines');