In this section
- Galaxies Wafers — App render · galaxies-wafers / app.mjs lines 1088–1609
- Code Galaxy Engine ingest · galaxies-wafers / engine/code-galaxy-engine.mjs lines 1–100
- Galaxies Wafers — Index Page render · galaxies-wafers / index.html lines 1–47
Galaxies Wafers — App
A JavaScript module that draws lines meta, families, blocks and cables, using SHA-256, and uses data from the stars repository. Served with the page at https://ventusltd.github.io/galaxies-wafers/.
rendergalaxies-wafers / app.mjs · lines 1088–1609 of 1609 (continued from section 1175) · Entry point · pattern machineDetail (shared by 2 files)
- What it does
- It draws lines meta, families, blocks and cables. Defines 91 functions or classes, including $, snapshot, clearColour, motion, indexOfKey. Side effects: changes the web page (DOM); reads or writes files; makes network requests.
- Why it exists in the grid workflow
- Domain terms in the code: cables. README: "The page (`index.html`, `app.mjs`, `lib.mjs`) is inherited unchanged from testcode/202609151339."
- Inputs & outputs
- In: data source: stars data; JSON file all-lines.meta.json; JSON file families.json; JSON file blocks.json; JSON file index.json. Out: WebGL/WebGPU drawing.
- Downstream impact
- Used directly by 1 file: Galaxies Wafers — Index Page (galaxies-wafers, https://ventusltd.github.io/galaxies-wafers/). Reached from 242 other entry points, including 404 (galaxies-wafers, https://ventusltd.github.io/galaxies-wafers/404.html); Galaxies Wafers — Iterations Page (galaxies-wafers, https://ventusltd.github.io/galaxies-wafers/iterations/); Galaxies Wafers — Proof Page (galaxies-wafers, https://ventusltd.github.io/galaxies-wafers/proof/). It is itself an entry point, published at https://ventusltd.github.io/galaxies-wafers/.
- What it achieves
- It indexes key (`indexOfKey`), builds gl (`buildGL`) and draws marks (`drawMarks`). The Line Wafer. Its code works with 100 kW. It responds to pointerdown, pointermove and pointerup events.
- Why it matters
- Loaded by the page of the same name at https://ventusltd.github.io/galaxies-wafers/.
- Application
- galaxies-wafers · / · JavaScript module
- Uses
- Galaxies Wafers — Lib (import), Stars — Index Page (estate URL)
- Used by
- loaded by Galaxies Wafers — Index Page (script src), mentioned in Standalone (comment link)
- Produces
- $, snapshot, clearColour, motion, indexOfKey, bin, tier1, tier2, compile, initGL, fallback2d, buildGL
- Defines here
- who, codeWindow, runs, changedOn, lineText, paint, lh, padTop, placeBar, refresh, select, step, runPanel, run, refusal, moduleURL, refuse, runIn, done, result, unitOf, functionBody, outputsOf, machineDetail, questions, openRoute, tileBandWidth, openArea, readURL, refuse
- Cannot conclude
- Whether this code runs, is used by a live app today, or is correct. This is a static reading.
- Evidence
- galaxies-wafers@5814793812add74605660fa821e6a39b8de80588 app.mjs:1088-1609 · blob 925d89a774d1abc7cc7ad231b4f5a460a8d67c6f · GitHub at these lines
- State
- achieves: comment · context: readme_derived · stage: output · effects: dom, filesystem, network · domain stage: unknown · users: none · canonical: unknown
if (engineModule) body.append(runPanel(engineModule, pl, lines, editor, rec.names || []));
/* the three questions and the machine detail, from the record and the source */
const fnText = lines.slice(pl.first - 1, pl.last).join('\n');
const who = (xs, verb) => xs?.length
? `${verb} ${xs.slice(0, 8).map(u => `#${u.family} ${u.name}`).join(', ')}${xs.length > 8 ? ` and ${xs.length - 8} more` : ''} (name-match inference by the modular star build: a needed name linked to the families defining it, ${[...new Set(xs.map(u => u.via || 'by name'))].join(' / ')})`
: null;
const sld = SLD[engineModule];
let sldText;
if (sld) {
const src = lines.join('\n');
const has = new RegExp(`export\\s+function\\s+${sld.fn}\\b`).test(src);
const out = has ? outputsOf(functionBody(lines, sld.fn)) : [];
sldText = has ? `${sld.element}: ${pl.path} → ${sld.fn}()${out.length ? ' returns ' + out.join('; ') : ''}. The page's module-to-element table, with the function checked present in this file at ${pl.commit.slice(0, 7)}.`
: `not established: ${sld.fn} is not exported by ${pl.path} at ${pl.commit.slice(0, 7)}.`;
} else sldText = engineModule
? `none yet: ${pl.path} is an engine module this page does not map to a diagram element.`
: `none yet: ${pl.path} in ${pl.repo} is not an engine module, and no diagram element is recorded for family #${chosen.n}.`;
const dep = block?.depends_on?.length ? `the register's depends_on for block ${block.symbol}: ${block.depends_on.join(', ')}` : null;
q.sld = sldText;
q.use = `${block ? `block ${block.symbol} (${block.title})` : 'no block'} · function ${(rec.names || []).join(', ')} · ${pl.path} @ ${pl.commit.slice(0, 7)} in ${pl.repo}${rec.places.length > 1 ? `, and ${rec.places.length - 1} other places` : ''}. Called by: ${who(rec.used_by, '') || 'no caller is recorded in the family record'}.`;
q.next = [who(rec.uses, 'It uses'), dep].filter(Boolean).join(' · ') || `not established: family #${chosen.n} records no uses and ${block ? `block ${block.symbol} declares no depends_on` : 'no block declares a dependency'}.`;
q.machine = machineDetail(fnText, lines, pl);
questions(body, q);
}
/* The code window. One <pre> holding one text node for the whole window, one
highlight bar for the tapped line and one for the selected line. Tapping a
row selects it; only the selected line is split into digit fields, in one
strip below that is re-filled on every selection. Edits live in a Map for as
long as this card is open. */
const DIGITS = /(?<![A-Za-z_$])\d+/g;
function codeWindow(lines, a, b, target) {
const edits = new Map(); /* line -> string[] of digit-run values */
const runs = n => [...lines[n - 1].matchAll(DIGITS)];
const changedOn = n => { const v = edits.get(n); return !!v && runs(n).some((m, i) => v[i] !== m[0]); };
const lineText = n => {
const vals = edits.get(n);
if (!vals) return lines[n - 1];
let i = 0;
return lines[n - 1].replace(DIGITS, m => { const v = vals[i++]; return v ?? m; });
};
let total = 0;
for (let n = a; n <= b; n++) total += runs(n).length;
const wrap = el('div', 'cc-codewrap');
const pre = el('pre', 'cc-code');
pre.setAttribute('aria-label', 'source code; tap a line to edit its digits');
const text = document.createTextNode('');
const hiTarget = el('div', 'cc-hi cc-hi-target'), hiSel = el('div', 'cc-hi cc-hi-sel');
pre.append(hiTarget, hiSel, text);
const paint = () => {
const out = [];
for (let n = a; n <= b; n++) out.push(String(n).padStart(4) + (changedOn(n) ? '*' : ' ') + ' ' + lineText(n));
text.nodeValue = out.join('\n');
};
const lh = () => parseFloat(getComputedStyle(pre).lineHeight) || 16;
const padTop = () => parseFloat(getComputedStyle(pre).paddingTop) || 0;
const placeBar = (bar, n) => { bar.style.top = (padTop() + (n - a) * lh()) + 'px'; bar.style.height = lh() + 'px'; };
const strip = el('div', 'cc-strip');
const stripHead = el('div', 'cc-grey');
const stripLine = el('div', 'cc-stripline');
const note = el('div', 'cc-local');
const nav = el('div', 'cc-nav');
let sel = target;
const refresh = () => {
let changed = 0;
for (const [n, v] of edits) runs(n).forEach((m, i) => { if (v[i] !== m[0]) changed++; });
note.textContent = `${total} digit ${total === 1 ? 'run' : 'runs'} in this window · ${changed} changed · local edit, not saved, not published`;
};
function select(n) {
sel = Math.max(a, Math.min(b, n));
placeBar(hiSel, sel);
const ms = runs(sel);
stripHead.textContent = `line ${sel}` + (ms.length ? ` · ${ms.length} digit ${ms.length === 1 ? 'run' : 'runs'}` : ' · no digits on this line; tap another line or step to the next with digits');
stripLine.replaceChildren();
if (!edits.has(sel) && ms.length) edits.set(sel, ms.map(m => m[0]));
const vals = edits.get(sel);
let last = 0;
const src = lines[sel - 1];
ms.slice(0, MAX_FIELDS).forEach((m, i) => {
if (m.index > last) stripLine.append(document.createTextNode(src.slice(last, m.index)));
const inp = el('input', 'cc-digit');
inp.value = vals[i]; inp.size = Math.max(1, vals[i].length);
inp.setAttribute('inputmode', 'numeric'); inp.setAttribute('pattern', '[0-9]*'); inp.setAttribute('autocomplete', 'off');
inp.setAttribute('aria-label', `digits ${m[0]} on line ${sel}`);
inp.dataset.line = String(sel);
inp.classList.toggle('cc-changed', vals[i] !== m[0]);
inp.addEventListener('input', () => {
const clean = inp.value.replace(/\D/g, '');
if (clean !== inp.value) inp.value = clean;
inp.size = Math.max(1, clean.length);
vals[i] = clean;
inp.classList.toggle('cc-changed', clean !== m[0]);
inp.classList.toggle('cc-blank', clean === '');
paint(); refresh();
});
stripLine.append(inp);
last = m.index + m[0].length;
});
if (ms.length > MAX_FIELDS) stripLine.append(document.createTextNode(` … ${ms.length - MAX_FIELDS} more digit runs on this line are not offered`));
else if (last < src.length) stripLine.append(document.createTextNode(src.slice(last)));
}
const step = dir => { for (let n = sel + dir; n >= a && n <= b; n += dir) if (runs(n).length) return select(n); };
nav.append(btn('◀ digits', 'cc-mini', () => step(-1)), btn('digits ▶', 'cc-mini', () => step(1)),
btn('reset digits', 'cc-mini', () => { edits.clear(); paint(); select(sel); refresh(); }));
pre.addEventListener('click', e => {
const y = e.clientY - pre.getBoundingClientRect().top + pre.scrollTop - padTop();
select(a + Math.floor(y / lh()));
});
strip.append(stripHead, stripLine, nav, note);
wrap.append(pre, strip);
paint(); refresh();
return {
node: wrap,
edits() {
const out = [];
for (const [n, v] of edits) {
if (!changedOn(n)) continue;
out.push({ line: n, before: lines[n - 1], after: lineText(n), blank: v.some(x => x === '') });
}
return out;
},
select,
scrollToTarget() {
placeBar(hiTarget, target); select(sel);
pre.scrollTop = Math.max(0, (target - a) * lh() - pre.clientHeight / 3);
}
};
}
/* ── run with my edit ──────────────────────────────────────────────────────── */
function runPanel(path, pl, lines, editor, names) {
const box = el('div', 'cc-run');
const fx = FIXTURES[path];
box.append(el('div', 'cc-sub', 'RUN THE MODULE'));
if (!fx) {
const t = el('span', 'cc-tag', 'EMPTY'); t.dataset.s = 'EMPTY';
box.append(t, el('span', 'cc-grey', ` No proof fixture is wired to this page for ${path}. Runs are offered for ${Object.keys(FIXTURES).join(' and ')}, each with the first input its own proof uses.`));
return box;
}
box.append(el('div', 'cc-grey', `Calls ${fx.fn}(${JSON.stringify(fx.input)}) — scenario input, the first fixture in ${fx.proof} — on ${path} at ${PIN.slice(0, 7)}, the commit the estate imports, in a worker with no network and a 2 s limit.`));
if (!names.includes(fx.fn)) box.append(el('div', 'cc-local', `This window is ${names.join(', ')}; the run calls ${fx.fn}. An edit here changes the answer only if ${fx.fn} reaches it.`));
const go = btn('RUN WITH MY EDIT', 'popup-btn popup-btn-images', () => run());
const out = el('div', 'cc-results');
box.append(go, out);
async function run() {
const mine = token;
go.disabled = true;
out.replaceChildren(el('div', 'cc-grey', 'reading the module, its imports and its proof at ' + PIN.slice(0, 7) + '…'));
const urls = [];
try {
const edits = editor.edits();
if (edits.some(e => e.blank)) throw refusal('A digit field is empty; an empty field is not a number, so nothing was run.');
const [pinned, proof] = await Promise.all([
readSource(ENGINE_REPO, PIN, path),
cached(onceMap, rawURL(ENGINE_REPO, PIN, fx.proof), 'text')
]);
if (!proof.replace(/\s+/g, ' ').includes(fx.evidence)) throw refusal(`The fixture was not found in ${fx.proof} at ${PIN.slice(0, 7)}, so this page will not claim it is the proof's input.`);
/* carry each edited line onto the module as imported */
const edited = pinned.slice();
const placed = [];
for (const e of edits) {
let at = -1;
if (pl.commit === PIN || pinned[e.line - 1] === e.before) at = e.line - 1;
else {
const hits = []; pinned.forEach((l, j) => { if (l === e.before) hits.push(j); });
if (hits.length !== 1) throw refusal(`Line ${e.line} as shown (${pl.commit.slice(0, 7)}) appears ${hits.length} times in ${path} at ${PIN.slice(0, 7)}, so the edit cannot be placed without guessing.`);
at = hits[0];
}
if (pinned[at] !== e.before) throw refusal(`Line ${e.line} differs at ${PIN.slice(0, 7)}; the edit was not applied.`);
edited[at] = e.after; placed.push(`line ${e.line} → ${PIN.slice(0, 7)} line ${at + 1}`);
}
const deps = new Map();
const origURL = await moduleURL(path, pinned.join('\n'), deps, urls, 0);
const editURL = edits.length ? await moduleURL(path, edited.join('\n'), deps, urls, 0) : origURL;
const [A, B] = await Promise.all([runIn(origURL, fx), edits.length ? runIn(editURL, fx) : null]);
if (mine !== token) return;
out.replaceChildren();
out.append(el('div', 'cc-grey', edits.length ? `${edits.length} edited ${edits.length === 1 ? 'line' : 'lines'} applied: ${placed.join('; ')}.` : 'No digit changed: both columns are the same published text, so the one run is shown twice.'));
const grid = el('div', 'cc-cols');
grid.append(result('as published @ ' + PIN.slice(0, 7), A), result(edits.length ? 'with your edit (local)' : 'with your edit (none made)', B ?? A));
out.append(grid, el('div', 'cc-disclaimer', DISCLAIMER));
} catch (e) {
if (mine !== token) return;
out.replaceChildren(el('div', 'cc-refuse', e.refusal ? e.message : 'Could not run: ' + e.message));
} finally {
for (const u of urls) URL.revokeObjectURL(u);
go.disabled = false;
}
}
return box;
}
const refusal = m => Object.assign(new Error(m), { refusal: true });
/* A module's text as a Blob URL, its relative imports read at PIN and rewritten
to Blob URLs of their own. Anything that would reach the network is refused. */
async function moduleURL(path, text, deps, urls, depth) {
if (depth > 6) throw refusal('The import chain is deeper than six modules; not run.');
if (/\bimport\s*\(/.test(text)) throw refusal(`${path} uses a dynamic import(), which could reach the network; not run.`);
const specRe = /(\b(?:import|export)\b[^'";]*?\bfrom\s*|\bimport\s*)(['"])([^'"]+)\2/g;
const specs = [...text.matchAll(specRe)].map(m => m[3]);
const map = new Map();
for (const s of new Set(specs)) {
if (!s.startsWith('./') && !s.startsWith('../')) throw refusal(`${path} imports "${s}", which is not a file of this repository; not run.`);
const target = new URL(s, 'https://x/' + path).pathname.slice(1);
if (!deps.has(target)) {
const t = (await readSource(ENGINE_REPO, PIN, target)).join('\n');
deps.set(target, await moduleURL(target, t, deps, urls, depth + 1));
}
map.set(s, deps.get(target));
}
const rewritten = text.replace(specRe, (all, pre, q, s) => pre + q + map.get(s) + q);
const u = URL.createObjectURL(new Blob([rewritten], { type: 'text/javascript' }));
urls.push(u);
return u;
}
const WORKER_SRC = `
const refuse = () => { throw new Error('network access is refused inside this run'); };
for (const k of ['fetch', 'XMLHttpRequest', 'WebSocket', 'EventSource', 'importScripts', 'Request', 'navigator']) {
try { Object.defineProperty(self, k, { value: refuse, configurable: false, writable: false }); } catch (e) { try { self[k] = refuse; } catch (e2) {} }
}
self.onmessage = async ({ data }) => {
try {
const m = await import(data.url);
if (typeof m[data.fn] !== 'function') { postMessage({ ok: false, kind: 'NotExported', message: 'the module exports no function named ' + data.fn }); return; }
const r = m[data.fn](data.input);
postMessage({ ok: true, result: JSON.parse(JSON.stringify(r)) });
} catch (e) {
postMessage({ ok: false, kind: (e && e.name) || 'Error', message: String(e && e.message !== undefined ? e.message : e) });
}
};`;
function runIn(url, fx) {
return new Promise(resolve => {
const wurl = URL.createObjectURL(new Blob([WORKER_SRC], { type: 'text/javascript' }));
let w;
const done = r => { clearTimeout(timer); try { w?.terminate(); } catch (e) {} URL.revokeObjectURL(wurl); resolve(r); };
const timer = setTimeout(() => done({ ok: false, kind: 'Stopped', message: `stopped after ${RUN_MS / 1000} s without an answer` }), RUN_MS);
try { w = new Worker(wurl, { type: 'module' }); }
catch (e) { done({ ok: false, kind: 'NoWorker', message: 'this browser would not start a module worker: ' + e.message }); return; }
w.onmessage = e => done(e.data);
w.onerror = e => { e.preventDefault?.(); done({ ok: false, kind: 'SyntaxOrLoadError', message: e.message || 'the edited module could not be loaded (a syntax error, or an import that failed)' }); };
w.postMessage({ url, fn: fx.fn, input: fx.input });
});
}
function result(label, r) {
const col = el('div', 'cc-col');
col.append(el('div', 'cc-sub', label));
if (!r.ok) {
col.append(el('div', 'cc-refuse', `${r.kind}: ${r.message}`));
col.dataset.value = 'refused';
return col;
}
const v = r.result;
const head = v && typeof v === 'object' && 'value' in v ? `${v.value} ${v.unit ?? ''}`.trim() : JSON.stringify(v);
col.dataset.value = v && typeof v === 'object' && 'value' in v ? String(v.value) : head;
col.append(el('div', 'cc-value', head));
if (v?.quantity) col.append(el('div', 'cc-grey', v.quantity));
const pre = el('pre', 'cc-json', JSON.stringify(v, null, 1));
col.append(pre);
return col;
}
/* ── the machine detail: read from the source text ─────────────────────────── */
const UNIT_SUFFIX = [
['OhmPerKm', 'ohm per kilometre'], ['Kwh', 'kilowatt-hours'], ['Mwh', 'megawatt-hours'], ['Gwh', 'gigawatt-hours'], ['Twh', 'terawatt-hours'],
['Kvar', 'kilovolt-amperes reactive'], ['Mva', 'megavolt-amperes'], ['Kva', 'kilovolt-amperes'], ['Va', 'volt-amperes'],
['Kw', 'kilowatts'], ['Mw', 'megawatts'], ['Gw', 'gigawatts'], ['Kv', 'kilovolts'], ['Km2', 'square kilometres'], ['Km', 'kilometres'],
['Gbp', 'pounds sterling'], ['Percent', 'percent'], ['Hz', 'hertz'], ['Deg', 'degrees'], ['M', 'metres'], ['A', 'amperes'], ['V', 'volts'], ['W', 'watts']
];
const WHOLE_NAME = { mva: 'megavolt-amperes', kv: 'kilovolts', kw: 'kilowatts', mw: 'megawatts', kva: 'kilovolt-amperes', hours: 'hours', lat: 'degrees', lon: 'degrees' };
function unitOf(name) {
if (WHOLE_NAME[name]) return WHOLE_NAME[name];
for (const [s, u] of UNIT_SUFFIX) if (name.length > s.length && name.endsWith(s) && /[a-z0-9]/.test(name[name.length - s.length - 1])) return u;
return null;
}
function functionBody(lines, fn) {
const start = lines.findIndex(l => new RegExp(`function\\s+${fn}\\b`).test(l));
if (start < 0) return '';
let depth = 0, seen = false;
for (let j = start; j < lines.length; j++) {
for (const c of lines[j].replace(/(['"`])(?:\\.|(?!\1).)*\1/g, '')) { if (c === '{') { depth++; seen = true; } else if (c === '}') depth--; }
if (seen && depth <= 0) return lines.slice(start, j + 1).join('\n');
}
return lines.slice(start).join('\n');
}
function outputsOf(text) {
const out = [];
for (const m of text.matchAll(/quantity:\s*'([^']+)'[\s\S]{0,120}?unit:\s*'([^']*)'/g)) out.push(`${m[1]} in ${m[2]}`);
return [...new Set(out)];
}
function machineDetail(fnText, lines, pl) {
const sig = fnText.match(/function\s*\*?\s*[\w$]*\s*\(([\s\S]*?)\)\s*\{/) || fnText.match(/\(([^()]*)\)\s*=>/);
let inputs = 'no parameter list read from this window';
if (sig) {
const names = sig[1].replace(/[{}\[\]]/g, '').split(',').map(p => p.split('=')[0].split(':').pop().trim()).filter(p => /^[A-Za-z_$][\w$]*$/.test(p));
inputs = names.length ? names.map(n => { const u = unitOf(n); return u ? `${n} (${u})` : `${n} (no unit in the name)`; }).join(', ') : 'none';
}
const outs = outputsOf(fnText);
const throws = [...new Set([...fnText.matchAll(/throw\s+new\s+(\w+)/g)].map(m => m[1]))];
const src = lines.join('\n');
const nc = src.match(/export\s+const\s+NOT_COMPUTED\s*=\s*Object\.freeze\(\{([\s\S]*?)\n\}\);/);
const ncKeys = nc ? [...nc[1].matchAll(/^\s{2,8}([A-Za-z_$][\w$]*)\s*:/gm)].map(m => m[1]) : [];
const other = [...src.matchAll(/export\s+const\s+(NOT_[A-Z_]+|NO_[A-Z_]+|NEVER_[A-Z_]+)\s*=/g)].map(m => m[1]).filter(n => n !== 'NOT_COMPUTED' || !nc);
return `inputs: ${inputs} (units read from parameter name suffixes, name-match inference) · outputs: ${outs.length ? outs.join('; ') : 'no quantity/unit fields in this function'} · refusals: ${throws.length ? 'throws ' + throws.join(', ') : 'no throw in this function'}${ncKeys.length ? ' · NOT_COMPUTED: ' + ncKeys.join(', ') : ''}${other.length ? ' · also ' + other.join(', ') : ''} · source ${pl … [line shortened here: 434 characters; full line on GitHub]
}
function questions(body, q) {
const d = el('details', 'cc-q');
if (window.matchMedia('(min-width: 760px)').matches) d.open = true;
d.append(el('summary', null, 'Questions'));
const dl = el('dl', 'cc-dl');
row(dl, 'draws', q.sld);
row(dl, 'used for', q.use);
row(dl, 'leads to', q.next);
d.append(el('div', 'cc-small', '1 how does this help draw a system or single-line diagram · 2 what is this code used for, and who calls it · 3 where does it lead next'), dl);
const m = el('div', 'cc-machine'); m.append(el('span', 'cc-sub', 'Machine detail '), document.createTextNode(q.machine));
d.append(m);
body.append(d);
}
/* ── a route ───────────────────────────────────────────────────────────────── */
async function openRoute(layer, f) {
const keys = f.geometry.keys || [];
mark = { kind: 'route', keys }; draw();
const p = f.properties || {};
const { body, setTag, live } = sheet(layer.label, ` route · ${fmt(keys.length)} stops`);
const dl = el('dl', 'cc-dl');
const module = [p.block && `block ${p.block}`, p.function && `function ${p.function}`, p.family != null && `family #${p.family}`, p.module_path].filter(Boolean).join(' · ');
row(dl, 'module', module || 'the route names no module');
const first = keys[0], last = keys[keys.length - 1];
row(dl, 'first line', btn(fmt(first), 'cc-key', () => openLine(first, { family: p.family })));
row(dl, 'last line', btn(fmt(last), 'cc-key', () => openLine(last, { family: p.family })));
for (const [k, v] of Object.entries(p)) if (!['block', 'function', 'family'].includes(k)) row(dl, k, typeof v === 'object' ? JSON.stringify(v) : String(v));
body.append(dl);
const stops = el('div', 'cc-stops');
stops.append(el('div', 'cc-sub', 'STOPS, IN ROUTE ORDER'));
const shownStops = keys.slice(0, 400);
stops.append(el('div', 'cc-stoplist', shownStops.map((k, j) => `${j + 1}:${k}`).join(' ') + (keys.length > 400 ? ` … and ${fmt(keys.length - 400)} more` : '')));
const pick = el('input', 'cc-pick'); pick.setAttribute('inputmode', 'numeric'); pick.setAttribute('aria-label', 'stop number'); pick.value = '1';
const openStop = btn('OPEN STOP', 'cc-mini', () => {
const j = Number(pick.value.replace(/\D/g, '')) - 1;
if (j >= 0 && j < keys.length) openLine(keys[j], { family: p.family });
else pick.value = '1';
});
const pr = el('div', 'cc-row'); pr.append(el('span', 'cc-grey', `stop 1 to ${keys.length}: `), pick, openStop);
stops.append(pr);
body.append(stops, el('div', 'cc-small', 'evidence: ' + (layer.evidence ?? 'none recorded') + ' · tap a stop to open its code card'));
if (p.family == null) {
setTag('OK', 'the route as the layer draws it');
return questions(body, { sld: 'none yet: this route names no family.', use: `drawn by the layer ${layer.id}; it names no module.`, next: 'not established: the route names no family to follow.', machine: `input: ${fmt(keys.length)} keys · output: a polyline through their placements · source: layers/${layer.id}` });
}
setTag('LOAD', `reading family #${p.family}'s record…`);
let fr, reg;
try { [fr, reg] = await Promise.all([familyRecord(p.family, () => setTag('WAIT', 'queued behind other fetches…')), register().catch(() => null)]); }
catch (e) { setTag('FAIL', 'Could not read the family record: ' + e.message); return; }
if (!live()) return;
if (fr.missing) { setTag('EMPTY', fr.missing); return; }
const rec = fr.rec, pl = rec.places?.[0], block = p.block && reg ? reg.get(p.block) : null;
if (pl) {
const h = el('div', 'cc-codehead');
h.append(`${pl.path} · ${pl.repo} @ ${pl.commit.slice(0, 7)} · lines ${pl.first}–${pl.last} · `, link(ghURL(pl.repo, pl.commit, pl.path, pl.first, pl.last), 'on GitHub'));
body.insertBefore(h, stops);
}
const sld = pl ? SLD[pl.path] : null;
setTag('OK', `family #${p.family}: ${(rec.names || []).join(', ')}`);
questions(body, {
sld: sld && pl.repo === ENGINE_REPO ? `${sld.element}: ${pl.path} → ${sld.fn}(). The page's module-to-element table; open a stop to see the function checked in its source.` : `none yet: ${pl ? pl.path : 'this family'} is not mapped to a diagram element.`,
use: `${block ? `block ${block.symbol} (${block.title})` : 'no block in the register'} · function ${(rec.names || []).join(', ')}${pl ? ` · ${pl.path} @ ${pl.commit.slice(0, 7)}` : ''} · called by: ${rec.used_by?.length ? rec.used_by.slice(0, 8).map(u => `#${u.family} ${u.name}`).join(', ') + ' (name-match inference)' : 'no caller recorded'}.`,
next: rec.uses?.length ? `uses ${rec.uses.slice(0, 8).map(u => `#${u.family} ${u.name} (${u.via})`).join(', ')} (name-match inference)` : `not established: family #${p.family} records no uses${block?.depends_on?.length ? '' : ' and its block declares no depends_on'}.`,
machine: `route: ${fmt(keys.length)} keys from ${fmt(first)} to ${fmt(last)}, ${p.route ?? 'order as stored in the layer'} · family lines in the record: ${rec.lines.length}${pl ? ` · source ${pl.repo} ${pl.path} @ ${pl.commit}` : ''}`
});
}
/* ── empty ground ──────────────────────────────────────────────────────────── */
/* The tile scheme is owned by layers-panel.mjs (its tile rule and fetch queue);
the card asks it rather than reading a manifest field no layer carries. */
async function tileBandWidth() {
const f = window.__layers?.tileScheme;
return f ? f() : null;
}
async function openArea(wx, wy, near, zoom) {
mark = { kind: 'point', x: wx, y: wy, key: near?.key ?? -1 }; draw();
const r = Math.hypot(wx, wy) / SPACING;
const b = Math.floor(r);
const k0 = b * b, k1 = (b + 1) * (b + 1);
const { body, setTag, live } = sheet('Empty ground', ` radius ${r.toFixed(2)} · no line within ${REACH} px`);
const dl = el('dl', 'cc-dl');
row(dl, 'point', `x ${wx.toFixed(2)}, y ${wy.toFixed(2)} in wafer units`);
row(dl, 'ring', `r = sqrt(key) puts radius ${b} to ${b + 1} at keys ${fmt(k0)} to ${fmt(k1 - 1)} · ${fmt(issuedIn(k0, k1))} of those ${fmt(k1 - k0)} numbers were issued`);
const bandDD = row(dl, 'tile band', 'reading the tile scheme…');
if (near) {
const dd = row(dl, 'nearest line', btn(fmt(near.key), 'cc-key', () => openLine(near.key)));
dd.append(` · ${near.d.toFixed(2)} units away, ${(near.d * zoom).toFixed(0)} px at this zoom · ${(U.ownerOf?.get(near.key) || []).length} ${(U.ownerOf?.get(near.key) || []).length === 1 ? 'family' : 'families'}`);
}
body.append(dl);
setTag('OK', 'computed from the placement law and the issued keys');
questions(body, {
sld: 'none yet: empty ground draws nothing.',
use: `nothing: no issued line sits within ${REACH} px of this point.`,
next: near ? `the nearest issued line, ${fmt(near.key)}; tap its number for its code card.` : 'not established: no issued line was found.',
machine: `input: a tap at wafer x ${wx.toFixed(2)}, y ${wy.toFixed(2)} · output: radius ${r.toFixed(3)} and key range [${k0}, ${k1}) from r = sqrt(key) · source: numbered database built ${U.meta.built_utc}`
});
try {
const t = await tileBandWidth();
if (!live()) return;
if (!t) { bandDD.textContent = 'EMPTY: no layer in the manifest is tiled, so no tile band scheme is published'; return; }
const tb = Math.floor(Math.floor(Math.sqrt(Math.max(0, Math.floor(r * r)))) / t.S);
const a = (tb * t.S) ** 2, z = ((tb + 1) * t.S) ** 2;
bandDD.textContent = `band ${tb} of the layer tiles (${t.law}, S = ${t.S}, read from ${t.path}): keys ${fmt(a)} to ${fmt(z - 1)} · ${fmt(issuedIn(a, z))} issued`;
} catch (e) { if (live()) bandDD.textContent = 'FAIL: could not read the tile scheme: ' + e.message; }
}
window.__codecard = Object.freeze({
get open() { return !$('card').hidden; },
get fetches() { return fetchCount; },
get cachedSources() { return sources.size; },
get cachedBuckets() { return buckets.size; },
openLine: (k, o) => openLine(k, o)
});
/* ── URL state: the whole of it, in permanent numbers ────────────────────── */
function readURL() {
const q = new URLSearchParams(location.search);
const pa = parseKey(q.get('line') ?? ''), pb = parseKey(q.get('to') ?? '');
if (!pa.ok) { if (q.get('line')) refuse(`The link carried a line number this page cannot use: ${pa.why}.`); return; }
$('a').value = String(pa.key);
const rawTo = q.get('to');
if (pb.ok) { $('b').value = String(pb.key); view.link = [pa.key, pb.key]; connect(pa.key, pb.key); }
else if (rawTo !== null && rawTo.trim() !== '') {
/* focus stays unset: tier 2 repaints the panel for a focused key when it
lands, which would silently replace this refusal with an ordinary card. */
refuse(`The link asked to connect to "${rawTo}", which is not a line number: ${pb.why}. `
+ `Line ${pa.key} is where the beam is pointing.`);
flyTo(pa.key);
}
else { view.focus = pa.key; paintPanel(pa.key); flyTo(pa.key); }
}
/* One refusal path, so a bad number is always visible rather than ignored. */
function refuse(sentence) {
$('panelbody').replaceChildren();
const h = document.createElement('h2'); h.textContent = 'Refused';
const p2 = document.createElement('p'); p2.className = 'refuse'; p2.textContent = sentence;
$('panelbody').append(h, p2);
$('panel').hidden = false;
}
/* Keeps the parameters other parts of the page own (layers, ground). The root
version rebuilt the query from line and to alone, so flying to a line dropped
the ticked layers from the link; iterations/21-dark-pixels/app.mjs fixed it. */
function writeURL(a, b) {
const q = new URLSearchParams(location.search);
q.delete('line'); q.delete('to');
if (a) q.set('line', String(a));
if (b) q.set('to', String(b));
const text = q.toString().replace(/%2C/gi, ',');
history.replaceState(null, '', text ? '?' + text : location.pathname);
}
/* The dark-ground toggle: off unless the reader ticks it or the link says ground=dark. */
function setGround(dark) {
GROUND.dark = !!dark;
cache.valid = false;
const box = $('darkGround');
if (box && box.checked !== GROUND.dark) box.checked = GROUND.dark;
document.body.classList.toggle('dark-ground', GROUND.dark);
const q = new URLSearchParams(location.search);
if (GROUND.dark) q.set('ground', 'dark'); else q.delete('ground');
const text = q.toString().replace(/%2C/gi, ',');
const next = location.pathname + (text ? '?' + text : '') + location.hash;
if (next !== location.pathname + location.search + location.hash) history.replaceState(history.state, '', next);
draw();
}
/* ── start ───────────────────────────────────────────────────────────────── */
(async function start() {
try {
await tier1();
} catch (e) {
$('count').textContent = 'Could not load the numbered database: ' + e.message
+ '. Check the internet connection and reload.';
return;
}
resize();
try { initGL(); } catch (e) {
ctx2d = stage.getContext('2d');
$('hint').textContent = 'GPU not available: drawn without animation';
}
home();
gestures();
if (new URLSearchParams(location.search).get('ground') === 'dark') setGround(true);
$('darkGround')?.addEventListener('change', e => setGround(e.target.checked));
window.addEventListener('resize', () => { resize(); draw(); });
$('beam').addEventListener('submit', e => {
e.preventDefault();
const pa = parseKey($('a').value), pb = parseKey($('b').value);
if (!pa.ok) { refuse(`That is not a line number: ${pa.why}.`); return; }
if ($('b').value.trim() && !pb.ok) { refuse(`Second number: ${pb.why}.`); return; }
closeCard();
if (pb.ok) { view.focus = -1; connect(pa.key, pb.key); writeURL(pa.key, pb.key); }
else { view.focus = pa.key; view.link = null; paintPanel(pa.key); flyTo(pa.key); writeURL(pa.key, null); }
document.activeElement?.blur();
});
$('close').addEventListener('click', () => { $('panel').hidden = true; view.focus = -1; view.link = null; draw(); });
readURL();
tier2().catch(e => { $('prov').textContent = 'family index unavailable: ' + e.message; });
})();Code Galaxy Engine
A JavaScript module in Galaxies Wafers that builds deep link (`buildDeepLink`) and parses deep link (`parseDeepLink`). It builds deep link (`buildDeepLink`) and parses deep link (`parseDeepLink`).
ingestgalaxies-wafers / engine/code-galaxy-engine.mjs · lines 1–100 of 100 · pattern buildDeepLink (shared by 3 files)
- What it does
- It lists and searches its content. Defines isKey, buildDeepLink, parseDeepLink.
- Downstream impact
- Used directly by 4 files: Layers Panel (galaxies-wafers, https://ventusltd.github.io/galaxies-wafers/iterations/09-deeplink-receiver/); Questions (galaxies-wafers, https://ventusltd.github.io/galaxies-wafers/iterations/09-deeplink-receiver/); Receiver (galaxies-wafers, https://ventusltd.github.io/galaxies-wafers/iterations/09-deeplink-receiver/); Engine Check (galaxies-wafers, https://ventusltd.github.io/galaxies-wafers/proof/). Reached from 3 other entry points, including Iterations — 09 Deeplink Receiver (galaxies-wafers, https://ventusltd.github.io/galaxies-wafers/iterations/09-deeplink-receiver/); Iterations — 09 Deeplink Receiver Page (galaxies-wafers, https://ventusltd.github.io/galaxies-wafers/iterations/09-deeplink-receiver/); Iterations — 45 Deeplink Round Trip Page (galaxies-wafers, https://ventusltd.github.io/galaxies-wafers/iterations/45-deeplink-round-trip/).
- What it achieves
- The Ventus Grid Engine's deep-link contract, lifted and applied to the code galaxy as a separate engine.
- Why it matters
- Imported by 4 files, including Layers Panel, Questions and Receiver.
- Application
- galaxies-wafers · engine · JavaScript module
- VEDIC
- BUILD PROJECT MAP LINK (GG2050-VEDIC-000086): Ventus Grid Engine · Map integration. base, project → URL string with supported project query parameters.
- VEDIC
- PARSE PROJECT MAP LINK (GG2050-VEDIC-000087): Ventus Grid Engine · Map integration. href → Parsed project and layer fields.
- Uses
- Galaxies Wafers — Index Page (estate URL)
- Used by
- imported by Layers Panel (import), imported by Questions (import), imported by Receiver (import), imported by Engine Check (import)
- Produces
- schema, LIFTED_FROM, IDENTITY_PARAM, PARAMS, RECEIVERS, NOT_COMPUTED, buildDeepLink, parseDeepLink
- Defines here
- isKey, buildDeepLink, parseDeepLink
- Cannot conclude
- Whether this code runs, is used by a live app today, or is correct. This is a static reading.
- Evidence
- galaxies-wafers@5814793812add74605660fa821e6a39b8de80588 engine/code-galaxy-engine.mjs:1-100 · blob 1480f62e8037e841d01ecbb0b13a4c2d0e3870ae · GitHub at these lines
- State
- achieves: comment · context: readme_derived · stage: transform · effects: none found · domain stage: unknown · users: none · canonical: unknown
/* code-galaxy-engine.mjs — the Ventus Grid Engine's deep-link contract, lifted
* and applied to the code galaxy as a separate engine.
*
* WHAT WAS LIFTED, AND FROM WHERE. ventus-grid-engine/deeplink/contract.js:
* one identity parameter, a frozen table of parameters with type, required and
* a note, a list of receivers, and two pure functions that build and parse a
* link. The Atlas centres on a project because a link carries `repd_ref`,
* `technology`, `latitude`, `longitude`, `zoom` and the receiver reads exactly
* those. That contract is why a link into the Atlas never dies silently.
*
* WHAT CHANGES. The identity is a permanent line number instead of a REPD
* reference, because in the galaxy the line number is the address: its place
* is a pure function of the number (wafer.mjs), so a link needs no latitude
* and no longitude. `to` names a second line to connect; `layers` names which
* layers the receiver should hydrate; `zoom` is the wafer's zoom.
*
* WHAT DOES NOT CHANGE. The contract lives here once, as data plus pure
* functions; the emitter and the receiver both import it; a link to a retired
* receiver throws rather than returning a dead link; no fetch, no DOM, no
* socket, so the proof runs offline. Same shape as the engine's, on purpose.
*/
export const schema = 'galaxies-wafers.code-galaxy-engine.deeplink.v1';
export const LIFTED_FROM = 'Ventusltd/ventus-grid-engine deeplink/contract.js';
export const IDENTITY_PARAM = 'line';
export const PARAMS = Object.freeze({
line: { type: 'integer', required: true, note: 'the permanent line number; the identity. Its place on the wafer is sqrt(line), line x golden angle' },
to: { type: 'integer', required: false, note: 'a second permanent line number to connect to the first' },
layers: { type: 'list', required: false, note: 'layer ids from layers/manifest.json to hydrate on arrival; unknown ids are dropped by the receiver' },
zoom: { type: 'number', required: false, note: 'the wafer zoom, 0.02 to 4000' }
});
export const RECEIVERS = Object.freeze([
Object.freeze({ id: 'galaxies-wafers', status: 'canonical', carries_layers: true,
url: 'https://ventusltd.github.io/galaxies-wafers/',
note: 'the wafer with layers; Pages must be enabled for this URL to answer' }),
Object.freeze({ id: 'line-wafer-202609151339', status: 'canonical', carries_layers: false,
url: 'https://globalgrid2050.com/testcode/202609151339/',
note: 'the inherited wafer without layers; reads line and to, ignores layers and zoom' })
]);
export const NOT_COMPUTED = Object.freeze({
place: 'This contract never computes where a line sits. That is wafer.mjs, and a link that carried a '
+ 'position could disagree with it.',
existence: 'This contract does not check that a line number was ever issued. The receiver does, against '
+ 'the numbered database, and refuses visibly.'
});
const isKey = v => Number.isSafeInteger(v) && v >= 1;
/** A link into a receiver. Throws on a retired receiver or a bad identity, so
* a dead link is never handed out. */
export function buildDeepLink(receiverId, { line, to, layers, zoom } = {}) {
const r = RECEIVERS.find(x => x.id === receiverId);
if (!r) throw new Error(`unknown receiver ${JSON.stringify(receiverId)}`);
if (r.status !== 'canonical') throw new Error(`receiver ${receiverId} is ${r.status}; a link to it would be dead on arrival`);
if (!isKey(line)) throw new TypeError(`${IDENTITY_PARAM} must be a positive safe integer, received ${JSON.stringify(line)}`);
const q = new URLSearchParams();
q.set('line', String(line));
if (to !== undefined) { if (!isKey(to)) throw new TypeError(`to must be a positive safe integer, received ${JSON.stringify(to)}`); q.set('to', String(to)); }
if (layers !== undefined) {
if (!r.carries_layers) throw new Error(`receiver ${receiverId} carries no layers; drop the layers field or choose galaxies-wafers`);
const ids = [...new Set((Array.isArray(layers) ? layers : String(layers).split(',')).map(s => String(s).trim()).filter(Boolean))];
if (ids.some(id => !/^[a-z0-9][a-z0-9-]*$/i.test(id))) throw new TypeError('layer ids are [a-z0-9-] only');
if (ids.length) q.set('layers', ids.join(','));
}
if (zoom !== undefined) {
if (typeof zoom !== 'number' || !(zoom >= 0.02 && zoom <= 4000)) throw new RangeError(`zoom must be a number in [0.02, 4000], received ${JSON.stringify(zoom)}`);
q.set('zoom', String(zoom));
}
return r.url + '?' + q.toString().replace(/%2C/gi, ',');
}
/** Read a link back. Never throws: a bad link is returned with `ok: false`
* and the reason, so a receiver can refuse visibly instead of guessing. */
export function parseDeepLink(href) {
let u;
try { u = new URL(String(href)); } catch { return { ok: false, why: 'not a URL' }; }
const q = u.searchParams;
const raw = q.get('line');
if (raw === null) return { ok: false, why: `missing ${IDENTITY_PARAM}` };
if (!/^[0-9]+$/.test(raw.trim())) return { ok: false, why: `${IDENTITY_PARAM} is not digits` };
const line = Number(raw);
if (!isKey(line)) return { ok: false, why: `${IDENTITY_PARAM} is not a positive safe integer` };
const out = { ok: true, line, receiver: RECEIVERS.find(r => href.startsWith(r.url))?.id ?? null };
if (q.has('to')) {
const t = q.get('to').trim();
if (!/^[0-9]+$/.test(t) || !isKey(Number(t))) return { ok: false, why: 'to is not a positive safe integer', line };
out.to = Number(t);
}
if (q.has('layers')) out.layers = [...new Set(q.get('layers').split(',').map(s => s.trim()).filter(Boolean))];
if (q.has('zoom')) {
const z = Number(q.get('zoom'));
if (!(z >= 0.02 && z <= 4000)) return { ok: false, why: 'zoom out of range', line };
out.zoom = z;
}
return out;
}Galaxies Wafers — Index Page
A web page that reads inputs for dark ground. Published at https://ventusltd.github.io/galaxies-wafers/.
rendergalaxies-wafers / index.html · lines 1–47 of 47 · Entry point
- What it does
- It draws its content. Side effects: changes the web page (DOM).
- Why it exists in the grid workflow
- README: "The page (`index.html`, `app.mjs`, `lib.mjs`) is inherited unchanged from testcode/202609151339."
- Inputs & outputs
- In: form fields (user input). Out: web page.
- Downstream impact
- Used directly by 21 files: Pilot (globalgrid2050, https://globalgrid2050.com/testcode/wafer-development-environment/202609190330-cable-cross-sections/); Layers Panel (galaxies-wafers, https://ventusltd.github.io/galaxies-wafers/iterations/02-tunnels/); Layers Panel (galaxies-wafers, https://ventusltd.github.io/galaxies-wafers/iterations/05-periodic-table/); Layers Panel (galaxies-wafers, https://ventusltd.github.io/galaxies-wafers/iterations/06-stars-as-engines/); and 17 more. Reached from 224 other entry points, including Iterations — 01 Route Alpha Page (galaxies-wafers, https://ventusltd.github.io/galaxies-wafers/iterations/01-route-alpha/); Iterations — 02 Tunnels Page (galaxies-wafers, https://ventusltd.github.io/galaxies-wafers/iterations/02-tunnels/); Iterations — 03 Code Particle Page (galaxies-wafers, https://ventusltd.github.io/galaxies-wafers/iterations/03-code-particle/). It is itself an entry point, published at https://ventusltd.github.io/galaxies-wafers/.
- What it achieves
- The Line Wafer — every numbered line of the estate, on one surface.
- Why it matters
- Loaded by the 404 page at https://ventusltd.github.io/galaxies-wafers/404.html and 6 other pages. Also imported by 13 files, including Pilot, Layers Panel and Code Galaxy Engine, from GlobalGrid2050. Checked by Smoke.
- Application
- galaxies-wafers · / · page
- Uses
- Galaxies Wafers — Style Sheet (stylesheet), Galaxies Wafers — Proof Page (link), Galaxies Wafers — App (script src), Layers Panel (script src)
- Used by
- named by URL in Pilot (estate URL), referenced by Layers Panel (new URL import.meta.url), referenced by Layers Panel (new URL import.meta.url), referenced by Layers Panel (new URL import.meta.url), linked from 404 (link), named by URL in Code Galaxy Engine (estate URL), linked from Iterations — 34 Cpu Floorplan Page (link), linked from Iterations — 39 Decisions and Permission Page (link), and 13 more
- Produces
- none declared
- Defines here
- none
- Cannot conclude
- Whether this code runs, is used by a live app today, or is correct. This is a static reading.
- Evidence
- galaxies-wafers@5814793812add74605660fa821e6a39b8de80588 index.html:1-47 · blob 05f7affd24cd4dbb305c1114bd4a87fb4a003a38 · GitHub at these lines
- State
- achieves: comment · context: readme_derived · stage: output · effects: dom · domain stage: unknown · users: none · canonical: unknown
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover, maximum-scale=5">
<meta name="color-scheme" content="dark">
<title>The Line Wafer — every numbered line of the estate, on one surface</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<canvas id="stage" aria-label="Every permanently numbered line of code in the estate, placed by its own number."></canvas>
<header id="bar">
<span id="wordmark">THE LINE WAFER</span>
<span id="count" class="dim">loading the numbered database…</span>
<span id="tools">
<label id="groundToggle"><input type="checkbox" id="darkGround"> dark ground</label>
<details id="questions"><summary>Questions</summary><dl id="qlist"></dl><p id="machine" class="dim"></p><p id="budget" class="dim">frame budget: waiting for the camera to move</p><p id="thin" class="dim"></p></details>
</span>
</header>
<form id="beam" autocomplete="off">
<input id="a" inputmode="numeric" pattern="[0-9]*" placeholder="line number" aria-label="line number to fly to">
<input id="b" inputmode="numeric" pattern="[0-9]*" placeholder="connect to…" aria-label="second line number to connect to">
<button id="go" type="submit">FLY</button>
</form>
<section id="card" hidden aria-live="polite"></section>
<section id="panel" hidden>
<button id="close" type="button" aria-label="close">✕</button>
<div id="panelbody"></div>
</section>
<footer id="foot">
<span id="prov" class="dim">provenance loading</span>
<span id="hint" class="dim">drag to steer · pinch or scroll to focus the beam · tap anything for its code card</span>
<a id="proofs" href="proof/">check every claim on this page</a>
</footer>
<noscript><p class="dim" style="padding:1rem">This surface is drawn from the numbered database at run time, so it needs JavaScript. Nothing here is typed into the page.</p></noscript>
<script type="module" src="app.mjs"></script>
<script type="module" src="layers-panel.mjs"></script>
</body>
</html>