/* CyberCity build — concatenate src/ into one self-contained index.html. * * No dependencies, no bundler, no minifier, no source maps. The modules were written to be * concatenated: each is an IIFE that resolves CC out of lexical scope, so wrapping the lot in one * more IIFE is the entire "bundling" step. Everything this script does beyond `join('\n')` is * removing the CommonJS tails that exist only so tools/headless.cjs can require the same files. * * Run: node build.js */ 'use strict'; const fs = require('fs'); const path = require('path'); const ROOT = path.join(__dirname); const SRC = path.join(ROOT, 'src'); const OUT = path.join(ROOT, 'index.html'); /* Order is load-bearing, not alphabetical: city.js binds core's helpers at make(), raycast.js * throws without CC.Surf, every element pushes onto CC.ELEMENTS before main.js reads that array, * and main.js boots on the last line of the file. compose.js is optional — the contract allows it * to not exist yet — so it is filtered out rather than assumed. */ const ORDER = [ 'core.js', 'world.js', // first after core: city.js resolves CC.World inside make(), weather_state // inside init(), surfaces inside beginFrame — all of them AFTER load, so // only the registry's existence matters here, not its value 'proj.js', // the shared element camera; every world-space element file holds one 'daylight.js', // before weather_state.js and before the elements: both read the hour 'weather_state.js', // before the elements: they read CC.Weather from init() onwards 'city.js', 'surfaces.js', '@painters', // expands to src/surf_*.js, sorted. Globbed rather than named one by one // for the same reason @elements is: a painter dropped into src/ and not // added to this list is silently absent from the bundle, and the symptom // is not an error — it is a world that renders as the city 'raycast.js', 'control.js', // after city.js, whose route it re-anchors to; before main.js, which drives it 'compose.js', '@elements', // expands to src/elements/*.js, sorted, so a build is reproducible 'render_canvas.js', 'main.js' ]; function expand(list) { const out = []; for (const name of list) { if (name === '@painters') { for (const pf of fs.readdirSync(SRC).sort()) if (/^surf_.*\.js$/.test(pf)) out.push(path.join(SRC, pf)); continue; } if (name === '@elements') { const dir = path.join(SRC, 'elements'); if (!fs.existsSync(dir)) continue; for (const f of fs.readdirSync(dir).sort()) if (f.endsWith('.js')) out.push(path.join(dir, f)); continue; } const p = path.join(SRC, name); if (fs.existsSync(p)) out.push(p); else if (name !== 'compose.js') throw new Error('missing required module src/' + name); } return out; } /* ---- CommonJS strip ------------------------------------------------------------------------- * Two shapes appear in src/, both harmless at runtime in a browser (the ternary short-circuits * before require is ever evaluated, and `typeof module` is a safe read on an undeclared name) — * but leaving them in ships dead branches referencing `require`, which is exactly the kind of * thing a CSP-conscious reader greps for in a "zero network requests" file. They come out. */ function strip(src) { return src // `(typeof CC !== 'undefined' ? CC : require('../core.js'))` -> `CC` .replace(/typeof\s+CC\s*!==\s*(['"])undefined\1\s*\?\s*CC\s*:\s*require\(\s*(['"]).*?\2\s*\)/g, 'CC') // one-liner: `if (typeof module !== 'undefined') module.exports = X;` .replace(/^[ \t]*if\s*\(\s*typeof\s+module\s*!==\s*(['"])undefined\1\s*\)\s*module\.exports\s*=[^\n]*;[ \t]*$/gm, '') // wrapped form: the `if` on its own line, the assignment on the next .replace(/^[ \t]*if\s*\(\s*typeof\s+module\s*!==\s*(['"])undefined\1\s*\)\r?\n[ \t]*module\.exports\s*=[^;]*;[ \t]*$/gm, '') .replace(/\n{3,}/g, '\n\n'); } /* ---- comment strip --------------------------------------------------------------------------- * src/ is ~40% prose by weight — this codebase explains WHY on nearly every non-obvious line — and * carrying all of it inline would put index.html at 253 KB against a 200 KB budget. The comments * belong in src/, which is where anyone editing this reads them; the deliverable is a picture. * * This is a scanner, not a regex, because a regex cannot tell `//` inside a string or a regex * literal from a comment, and getting that wrong corrupts the page silently. It tracks the three * literal forms and uses the standard previous-significant-token rule to decide whether a `/` * opens a regex or is a division. The `new Function` compile check further down is the backstop: * anything this mangles fails the build instead of shipping. */ const REGEX_OK_WORDS = new Set(['return', 'typeof', 'case', 'in', 'of', 'new', 'delete', 'void', 'instanceof', 'throw', 'do', 'else', 'yield', 'await']); const IDENT = /[A-Za-z0-9_$]/; /* A `/` after any of these is division, never a regex, because all of them end a VALUE. * `)` and `]` are the ones that matter here: `(v - 0.62) / (st.gnd - 2.2)` is everywhere in * surfaces.js, and reading that `/` as a regex opener swallows the rest of the file into a * literal and every comment after it ships. */ const DIV_AFTER = /[A-Za-z0-9_$)\]]/; /* ---- indent folding ------------------------------------------------------------------------- * Two spaces of indent per level become one, and ONLY at the start of a line the scanner reached * through the code path — never inside a string, because a template literal's newline is emitted * by the string branch below and the fold only ever fires immediately after the fallthrough or the * block-comment branch has written a '\n' itself. Multi-line templates are therefore safe by * construction rather than by inspection, which matters: there are none in src/ today and this has * to keep being true when there are. * * WHY IT HAPPENED, and it is a raise refused rather than a tidy. The 560 KB budget below is a * commitment with a whole essay attached saying the next pass over the line must CUT before it * moves the number. This pass went over — three worlds' worth of texture and colour work landed at * 575.5 KB — and the two things the essay names as cuttable are content (wrong way round; that is * the deliverable) and indentation, which it refuses on the grounds that stripping it turns a * viewable page source into a wall. * * Both of the numbers that refusal rests on are now false, and that is the finding. The note under * the return below says indentation costs "~6 KB"; the budget essay says "about 25 KB". MEASURED on * the bundle this pass produces: 84,232 bytes of leading whitespace over 16,505 lines, 14.3% of the * file. It stopped being a rounding error two worlds ago and nobody re-measured it. * * So the fold is the middle answer neither note considered: HALVE it, do not strip it. Every line * keeps its indentation and its structure, at one space per level instead of two, and the page * source is still a nested document rather than a wall — which is the thing the refusal was * actually protecting. Worth 42,134 bytes, taking the bundle to 534.4 KB with 25.6 KB of headroom * under a line that does not move. Rejected: stripping indentation outright (worth 84 KB and it is * the wall the note refuses), and stripping the blank line decomment leaves between paragraphs * (2.4 KB, and it is the only thing left separating one thought from the next). */ function foldIndent(src, i) { let w = 0; while (i < src.length && (src[i] === ' ' || src[i] === '\t')) { w++; i++; } return { text: w > 1 ? ' '.repeat(w >> 1) : '', i: i }; } function decomment(src) { let out = '', i = 0, prev = '', word = ''; const n = src.length; /* ...except after a keyword, where `return /re/` is a regex even though `n` is an ident char. */ const regexAllowed = () => prev === '' || !DIV_AFTER.test(prev) || REGEX_OK_WORDS.has(word); { const f = foldIndent(src, 0); out += f.text; i = f.i; } // the file's own first line while (i < n) { const c = src[i]; if (c === '/' && src[i + 1] === '/') { while (i < n && src[i] !== '\n') i++; // the newline itself stays: ASI depends on it continue; } if (c === '/' && src[i + 1] === '*') { const start = i; i += 2; while (i < n && !(src[i] === '*' && src[i + 1] === '/')) i++; i += 2; /* A comment sits BETWEEN two tokens, so it cannot vanish without leaving a separator behind * or an inline one welds its two neighbours into a single identifier. A multi-line one * collapses to a newline instead, so ASI keeps behaving exactly as it did in src/. */ if (src.slice(start, i).indexOf('\n') >= 0) { out += '\n'; const f = foldIndent(src, i); out += f.text; i = f.i; } else out += ' '; continue; } if (c === '"' || c === "'" || c === '`') { out += c; i++; while (i < n) { const d = src[i]; out += d; i++; if (d === '\\') { out += src[i]; i++; continue; } if (d === c) break; } prev = c; word = ''; continue; } if (c === '/' && regexAllowed()) { out += c; i++; let inClass = false; while (i < n) { const d = src[i]; out += d; i++; if (d === '\\') { out += src[i]; i++; continue; } if (d === '[') inClass = true; else if (d === ']') inClass = false; else if (d === '/' && !inClass) break; } while (i < n && IDENT.test(src[i])) { out += src[i]; i++; } // flags prev = '/'; word = ''; continue; } out += c; i++; if (c === '\n') { const f = foldIndent(src, i); out += f.text; i = f.i; continue; } if (!/\s/.test(c)) { prev = c; word = IDENT.test(c) ? word + c : ''; } } /* Trailing whitespace and the blank lines the comments left behind. Indentation is HALVED rather * than kept whole or stripped — see foldIndent above for the measurement that changed the answer * and the 84,232 bytes it was hiding. */ return out.replace(/[ \t]+$/gm, '').replace(/\n{2,}/g, '\n\n').trim(); } const files = expand(ORDER); const parts = files.map(p => { const rel = path.relative(ROOT, p).split(path.sep).join('/'); return '/* ' + rel + ' */\n' + decomment(strip(fs.readFileSync(p, 'utf8'))) + '\n'; }); /* One IIFE, one `var CC`. core.js declares CC with `var`, so it is hoisted to the top of this * function and every later module's `typeof CC !== 'undefined'` guard sees it. Nothing leaks to * window, which is the point: the page has no API surface to poke at. */ const bundle = '(function () {\n' + parts.join('\n') + '\n})();\n'; /* The page must open with ZERO network requests, so nothing may reference a module loader. */ if (/\brequire\s*\(/.test(bundle)) throw new Error('build: a require() survived the strip'); if (/\bmodule\.exports\b/.test(bundle)) throw new Error('build: a module.exports survived the strip'); if (/\bimport\s|\bexport\s/.test(bundle)) throw new Error('build: ESM syntax in the bundle'); /* A literal closing script tag anywhere in the sources would end the inline block early and dump * the rest of the city into the document as text. */ if (/<\/script/i.test(bundle)) throw new Error('build: source contains a closing script tag'); /* Every module named its global; if one is missing it was dropped, mis-ordered, or the comment * scanner ate something structural. Cheap, and it has caught both. */ for (const need of ['var CC', 'CC.City', 'CC.Surf', 'CC.Cast', 'CC.Canvas', 'CC.Main', 'CC.World', 'CC.SurfWest', 'CC.Daylight', 'CC.ELEMENTS.push']) if (!bundle.includes(need)) throw new Error('build: bundle is missing ' + need); /* Compiles the bundle without running it. This is what makes the comment scanner safe to trust: * if it ever mangles a regex literal or a template string, the build stops here. */ try { new Function(bundle); } catch (e) { throw new Error('build: bundle does not parse — ' + e.message); } /* The page is black before a single pixel of city is drawn — html, body and canvas all — so that * entering fullscreen never flashes white and never shows a seam at an edge the canvas overhangs. * The hint is CSS-only on purpose: it fades itself out and no JavaScript ever has to know it * existed, which keeps main.js free of anything resembling UI. */ const HTML = `