File size: 6,316 Bytes
e5e073b | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 | #!/usr/bin/env node
// Mirror the research-article-template page layout into the editor:
// - the grid tokens and layout stylesheets go to frontend/src/styles/template-layout/
// (loaded by the editor and inlined by the publisher), with @custom-media
// resolved because neither Vite nor the publisher runs PostCSS;
// - the paper hero styles are lifted from HeroPaper.astro's <style> block;
// - the layout scripts (TOC, heading anchors, sidenotes, meta columns, debug
// grid on ?grid) are bundled into one IIFE inlined in every published page.
//
// node scripts/sync-template-layout.mjs [templateDir] # write
// node scripts/sync-template-layout.mjs [templateDir] --check # fail if stale
//
// templateDir defaults to $TEMPLATE_DIR, then ../research-article-template
// next to this repo.
import { readFile, writeFile, mkdir } from 'node:fs/promises';
import { existsSync } from 'node:fs';
import { execFileSync } from 'node:child_process';
import { dirname, join, resolve } from 'node:path';
import { fileURLToPath } from 'node:url';
import { build } from 'esbuild';
const backendDir = resolve(dirname(fileURLToPath(import.meta.url)), '..');
const repoDir = resolve(backendDir, '..');
const args = process.argv.slice(2);
const checkOnly = args.includes('--check');
const templateDir = resolve(
args.find((a) => !a.startsWith('--')) || process.env.TEMPLATE_DIR || join(repoDir, '..', 'research-article-template'),
);
const appDir = join(templateDir, 'app', 'src');
if (!existsSync(join(appDir, 'styles', '_grid.css'))) {
console.error(`No new-layout template found at ${templateDir} (missing app/src/styles/_grid.css).`);
process.exit(1);
}
let revision = 'unknown';
try {
revision = execFileSync('git', ['-C', templateDir, 'rev-parse', '--short', 'HEAD'], { encoding: 'utf8' }).trim();
} catch {
// Not a git checkout: the header just says "unknown".
}
const read = (rel) => readFile(join(appDir, rel), 'utf8');
const customMedia = new Map();
for (const m of (await read('styles/_variables.css')).matchAll(/@custom-media\s+(--[\w-]+)\s+(\([^;]+\))\s*;/g)) {
customMedia.set(m[1], m[2]);
}
const resolveMedia = (css) => {
let out = css;
for (const [name, query] of customMedia) out = out.replaceAll(`(${name})`, query);
const left = out.match(/\(--bp-[\w-]+\)/);
if (left) throw new Error(`Unresolved custom media ${left[0]}`);
return out;
};
const cssHeader = (source) => [
'/* GENERATED FILE - do not edit by hand.',
` Source: research-article-template@${revision} app/src/${source}`,
' Regenerate with `npm run sync:template-layout` in backend/. */',
'',
'',
].join('\n');
const STYLES = {
'_grid.css': 'styles/_grid.css',
'_layout.css': 'styles/_layout.css',
'_hero.css': 'styles/layout/_hero.css',
'_toc.css': 'styles/layout/_toc.css',
'_headings.css': 'styles/layout/_headings.css',
'_sidenote.css': 'styles/layout/_sidenote.css',
'_footer.css': 'styles/layout/_footer.css',
};
const stylesOut = 'frontend/src/styles/template-layout';
const outputs = {};
for (const [name, source] of Object.entries(STYLES)) {
outputs[`${stylesOut}/${name}`] = cssHeader(source) + resolveMedia(await read(source)).trimEnd() + '\n';
}
const heroPaper = (await read('components/HeroPaper.astro')).match(/<style>([\s\S]*?)<\/style>/);
if (!heroPaper) throw new Error('HeroPaper.astro has no <style> block');
const heroPaperCss = heroPaper[1]
.replace(/:global\(([^)]*)\)/g, '$1')
.split('\n')
.map((line) => line.replace(/^ {2}/, ''))
.join('\n')
.trim();
outputs[`${stylesOut}/_hero-paper.css`] =
cssHeader('components/HeroPaper.astro (<style>)') + resolveMedia(heroPaperCss) + '\n';
const heroUtils = await read('components/heroUtils.ts');
const linkIcons = heroUtils.match(/export const LINK_ICONS[\s\S]*?\n};\n/);
const getLinkIcon = heroUtils.match(/export function getLinkIcon[\s\S]*?\n}\n/);
if (!linkIcons || !getLinkIcon) throw new Error('heroUtils.ts: LINK_ICONS / getLinkIcon not found');
outputs['backend/src/shared/link-icons.generated.ts'] = [
'// GENERATED FILE - do not edit by hand.',
`// Source: research-article-template@${revision} app/src/components/heroUtils.ts`,
'// Regenerate with `npm run sync:template-layout` in backend/.',
'',
linkIcons[0],
getLinkIcon[0],
].join('\n');
const entry = `
import { initHeadingAnchors } from "./heading-anchors";
import { initToc } from "./toc";
import { initSidenotes } from "./sidenotes";
import { initMeta } from "./meta";
initHeadingAnchors();
initToc();
initSidenotes();
initMeta();
const params = new URLSearchParams(location.search);
if ((params.has("grid") && params.get("grid") !== "0") || params.get("debug") === "grid") {
import("./debug-grid").then((m) => m.toggleDebugGrid(true));
}
`;
const bundle = await build({
stdin: { contents: entry, resolveDir: join(appDir, 'scripts', 'layout'), loader: 'ts', sourcefile: 'layout-entry.ts' },
bundle: true,
format: 'iife',
target: 'es2020',
minify: true,
write: false,
logLevel: 'silent',
});
const runtimeJs = bundle.outputFiles[0].text.trim();
outputs['backend/src/publisher/layout-runtime.generated.ts'] = [
'// GENERATED FILE - do not edit by hand.',
`// Source: research-article-template@${revision} app/src/scripts/layout/{toc,heading-anchors,sidenotes,meta,debug-grid}.ts`,
'// Regenerate with `npm run sync:template-layout` in backend/.',
'',
`export const LAYOUT_RUNTIME_JS = ${JSON.stringify(runtimeJs)};`,
'',
].join('\n');
// The revision header changes on every template commit; compare the bodies so
// --check only fails on real drift.
const body = (s) => s.replace(/research-article-template@\S+/g, '');
let stale = 0;
await mkdir(join(repoDir, stylesOut), { recursive: true });
for (const [rel, content] of Object.entries(outputs)) {
const target = join(repoDir, rel);
const current = existsSync(target) ? await readFile(target, 'utf8') : null;
if (current !== null && body(current) === body(content)) continue;
stale++;
if (checkOnly) console.error(`stale: ${rel} (run npm run sync:template-layout)`);
else {
await writeFile(target, content);
console.log(`wrote ${rel}`);
}
}
if (checkOnly && stale) process.exit(1);
if (!stale) console.log(`template layout already in sync with research-article-template@${revision}.`);
|