It was blank until every module had loaded and the page's examples had been run, a fuzzer's report among them (about a second of work): first paint came 1.3 seconds into a repeat visit and about 3 into a first one. - The assembler draws the home page once, in Node, with the app's own homeView, and puts it inside #app. The browser paints it with the HTML and the stylesheet. - When the app has loaded it draws the page again, with its controls, and puts it in the prerendered one's place; the fuzzer's reports and the proof's counts are copied from the prerendered page, not worked out again. - The prerendered page shows only on the home address: the page's first inline script marks it before the first paint, and without the mark it stays hidden, so an embed or a problem's address never shows it. That script changed, and its hash in docs/Caddyfile with it. Served locally, first paint is at 0.1 to 0.2 seconds and the page with its controls at 0.2 to 0.3; both were at 1.2 to 1.4.
102 lines
6.0 KiB
JavaScript
102 lines
6.0 KiB
JavaScript
#!/usr/bin/env node
|
|
// SPDX-FileCopyrightText: 2026 Scientific Computing Studio, LLC
|
|
// SPDX-License-Identifier: Apache-2.0
|
|
// The assembled site's index.html, from the one in the repository: scripts/assemble.sh runs this on site/.
|
|
// node scripts/assemble-page.mjs <site-dir>
|
|
// It adds three things a checkout served as it is (pixi run dev) does without:
|
|
// - <meta name="pplus-version">, the commit in site/VERSION, which the footer shows (no request needed);
|
|
// - a <link rel="modulepreload"> for every module the page's static import graph reaches. Without a bundler the
|
|
// browser finds the modules one level of imports at a time, so a first visit waits for a chain of round trips
|
|
// (six levels today); with the list it asks for them all at once. The links go after the import map, which a
|
|
// browser must have read before it loads any module;
|
|
// - the home page, already drawn, inside #app (src/ui/prerender.ts): a visitor sees it with the HTML and the
|
|
// stylesheet, not after every module has loaded and the page's examples have been run (about a second of work).
|
|
// It is drawn here by the app's own homeView, in Node, on the small document of src/quarto/dom.ts.
|
|
// Nothing else in the page changes, so the hashes of its inline scripts (docs/Caddyfile's CSP) still hold.
|
|
import { readFileSync, writeFileSync, existsSync } from 'node:fs';
|
|
import { resolve, dirname, relative, join } from 'node:path';
|
|
import { fileURLToPath, pathToFileURL } from 'node:url';
|
|
|
|
const IMPORT = /(?:^|[;\n}])\s*(?:import|export)\s*(?:[\w*{}\s,$]*?\sfrom\s*)?['"]([^'"]+)['"]/g;
|
|
|
|
/**
|
|
* Every module the page's entry imports, directly or through others, as hrefs relative to the page ('./dist/…',
|
|
* './core/dist/…'), shallowest first; the entry itself is not listed (its own <script> loads it).
|
|
* @param {string} root the directory that holds index.html, dist/ and core/dist/
|
|
* @param {string} [entry] the entry module, relative to root
|
|
* @returns {string[]}
|
|
*/
|
|
export function modulePreloads(root, entry = 'dist/main.js') {
|
|
const coreDist = resolve(root, 'core/dist');
|
|
const target = (from, spec) => spec.startsWith('#core/') ? join(coreDist, spec.slice('#core/'.length)) : spec.startsWith('.') ? resolve(dirname(from), spec) : null;
|
|
const start = resolve(root, entry);
|
|
const depth = new Map([[start, 0]]);
|
|
const queue = [start];
|
|
while (queue.length) {
|
|
const file = queue.shift();
|
|
const src = readFileSync(file, 'utf8');
|
|
for (const m of src.matchAll(IMPORT)) {
|
|
const t = target(file, m[1]);
|
|
if (!t || depth.has(t)) continue;
|
|
if (!existsSync(t)) throw new Error(`${relative(root, file)} imports ${m[1]}, which is not in ${root}`);
|
|
depth.set(t, depth.get(file) + 1);
|
|
queue.push(t);
|
|
}
|
|
}
|
|
return [...depth].filter(([f]) => f !== start).sort((a, b) => a[1] - b[1] || (a[0] < b[0] ? -1 : 1)).map(([f]) => `./${relative(root, f).split('\\').join('/')}`);
|
|
}
|
|
|
|
/** Where index.html takes the prerendered home page: a comment inside #app. */
|
|
export const HOME_MARK = '<!--prerendered-home-->';
|
|
|
|
/**
|
|
* The home page as the app draws it, as HTML: the built app's own homeView, run here on the small document.
|
|
* @param {string} dist the built app's dist/ (it imports core through the package's #core/ mapping)
|
|
* @param {string | null} [version] the commit the footer names
|
|
* @returns {Promise<string>}
|
|
*/
|
|
export async function prerenderHome(dist, version = null) {
|
|
const at = (p) => pathToFileURL(join(dist, p)).href;
|
|
const { installDocument } = await import(at('quarto/dom.js'));
|
|
installDocument();
|
|
(await import(at('ui/footer.js'))).givePageVersion(version);
|
|
const { homeView } = await import(at('ui/home.js'));
|
|
return homeView().outerHTML;
|
|
}
|
|
|
|
/**
|
|
* The page with the version, the preloads and the prerendered home page in it.
|
|
* @param {string} html index.html as the repository has it
|
|
* @param {{ version?: string | null, preloads?: string[], home?: string | null }} parts
|
|
* @returns {string}
|
|
*/
|
|
export function assemblePage(html, { version = null, preloads = [], home = null } = {}) {
|
|
let out = html;
|
|
if (home) {
|
|
if (!out.includes(HOME_MARK)) throw new Error(`index.html has no ${HOME_MARK}: the prerendered home page goes there`);
|
|
// a function, so a $ in the page's text is not read as a replacement pattern
|
|
out = out.replace(HOME_MARK, () => `<div class="home-prerendered">${home}</div>`);
|
|
// the home page's Quarto example is styled by the extension's stylesheet, which the app adds when it draws the
|
|
// page (src/ui/quarto.ts, marked the same way so it is not added twice): without it here the prerendered page
|
|
// is a few lines taller than the one that takes its place
|
|
out = out.replace(/\n<\/head>/, '\n <link rel="stylesheet" href="./quarto/_extensions/pplus/pplus.css" data-pplus-ext="1">\n</head>');
|
|
}
|
|
if (version && /^[0-9a-f]{7,40}$/.test(version)) out = out.replace(/\n<\/head>/, `\n <meta name="pplus-version" content="${version}">\n</head>`);
|
|
const map = /<script type="importmap">[^<]*<\/script>\n/.exec(out);
|
|
if (!map) throw new Error('index.html has no import map: the preloads go after it');
|
|
const links = preloads.map((h) => ` <link rel="modulepreload" href="${h}">\n`).join('');
|
|
return out.slice(0, map.index + map[0].length) + links + out.slice(map.index + map[0].length);
|
|
}
|
|
|
|
if (process.argv[1] && resolve(process.argv[1]) === fileURLToPath(import.meta.url)) {
|
|
const site = resolve(process.argv[2] ?? 'site');
|
|
const page = join(site, 'index.html');
|
|
const versionFile = join(site, 'VERSION');
|
|
const version = existsSync(versionFile) ? readFileSync(versionFile, 'utf8').trim() : null;
|
|
const preloads = modulePreloads(site);
|
|
// drawn by the checkout's own build, which is what assemble.sh copied into the site
|
|
const home = await prerenderHome(resolve(dirname(fileURLToPath(import.meta.url)), '..', 'dist'), version);
|
|
writeFileSync(page, assemblePage(readFileSync(page, 'utf8'), { version, preloads, home }));
|
|
console.log(`index.html: ${preloads.length} module preloads, the home page prerendered (${Math.round(home.length / 1024)} kB)${version ? `, version ${version.slice(0, 12)}` : ''}`);
|
|
}
|