All source filesscripts/build.mjs
Download raw file
import {spawnSync} from 'node:child_process';
import {mkdir, rm, writeFile, copyFile, readFile} from 'node:fs/promises';
import {dirname, join, relative, resolve, sep} from 'node:path';
import {fileURLToPath} from 'node:url';
import {PAGES, SITE_ORIGIN, normalizeGtmId, renderNotFoundPage, renderPage} from '../src/page-template.mjs';
import {ANSWER_SCHEDULE} from '../src/word-data.mjs';
const root = join(dirname(fileURLToPath(import.meta.url)), '..');
const srcDir = join(root, 'src');
const dist = join(root, 'dist');
function runPython(label, args) {
const result = spawnSync(process.env.PYTHON || 'python3', args, {cwd: root, stdio: 'inherit'});
if (result.error) throw result.error;
if (result.status !== 0) throw new Error(`${label} failed with exit code ${result.status}`);
}
function staticImportSpecifiers(source) {
const specifiers = [];
const pattern = /(?:^|\n)\s*(?:import|export)\s+(?:[^'"]*?\bfrom\s*)?['"]([^'"]+)['"]/g;
let match;
while ((match = pattern.exec(source))) specifiers.push(match[1]);
return specifiers;
}
async function browserModuleFiles(entry) {
const files = new Set();
const pending = [entry];
while (pending.length) {
const file = pending.pop();
if (files.has(file)) continue;
files.add(file);
const source = await readFile(file, 'utf8');
for (const specifier of staticImportSpecifiers(source)) {
if (!specifier.startsWith('.')) continue;
const dependency = resolve(dirname(file), specifier);
if (!dependency.startsWith(srcDir + sep)) {
throw new Error(`Browser module ${relative(root, file)} imports outside src/: ${specifier}`);
}
pending.push(dependency);
}
}
return [...files];
}
const analyticsEndpoint = (process.env.WORDHINT_ANALYTICS_ENDPOINT || '').trim();
if (analyticsEndpoint && !/^https?:\/\//i.test(analyticsEndpoint) && !(analyticsEndpoint.startsWith('/') && !analyticsEndpoint.startsWith('//'))) {
throw new Error('WORDHINT_ANALYTICS_ENDPOINT must be an absolute http(s) URL or a root-relative path');
}
const gtmId = normalizeGtmId(process.env.WORDHINT_GTM_ID || '');
const MIN_SCHEDULE_DAYS = 147;
const REQUIRED_SCHEDULE_END = '2027-04-30';
if (ANSWER_SCHEDULE.length < MIN_SCHEDULE_DAYS || ANSWER_SCHEDULE.some(entry => !entry.reviewed || !entry.clueEn || !entry.clueZh)) {
throw new Error(`At least ${MIN_SCHEDULE_DAYS} fully reviewed bilingual puzzles are required`);
}
if (ANSWER_SCHEDULE.at(-1).date < REQUIRED_SCHEDULE_END) {
throw new Error(`Answer schedule must cover through ${REQUIRED_SCHEDULE_END}; last scheduled date is ${ANSWER_SCHEDULE.at(-1).date}`);
}
for (let index = 1; index < ANSWER_SCHEDULE.length; index += 1) {
const expected = new Date(Date.parse(ANSWER_SCHEDULE[index - 1].date) + 86400000).toISOString().slice(0, 10);
if (ANSWER_SCHEDULE[index].date !== expected) {
throw new Error(`Answer schedule has a gap at ${ANSWER_SCHEDULE[index].date}; expected ${expected}`);
}
}
const license = await readFile(join(root,'data/scowl/Copyright'),'utf8');
if (!/SCOWL/i.test(license)) throw new Error('SCOWL license is missing');
await rm(dist,{recursive:true,force:true});
await mkdir(join(dist,'assets'),{recursive:true});
for (const page of PAGES) {
const target = join(dist,page.path);
await mkdir(dirname(target),{recursive:true});
await writeFile(target,renderPage(page,{analyticsEndpoint,gtmId}));
}
await writeFile(join(dist,'404.html'),renderNotFoundPage({gtmId, analyticsEndpoint}));
await writeFile(join(dist,'en/404.html'),renderNotFoundPage({locale:'en',gtmId, analyticsEndpoint}));
for (const file of await browserModuleFiles(join(srcDir, 'app.mjs'))) {
const target = join(dist, 'assets', relative(srcDir, file));
await mkdir(dirname(target), {recursive: true});
await copyFile(file, target);
}
await copyFile(join(srcDir, 'styles.css'), join(dist, 'assets', 'styles.css'));
await writeFile(join(dist,'assets/scowl-Copyright.txt'),license);
await writeFile(join(dist,'robots.txt'),`User-agent: *\nAllow: /\nDisallow: /source/files/\nSitemap: ${SITE_ORIGIN}/sitemap.xml\n`);
const urls = PAGES.map(page => ` <url><loc>${page.canonical}</loc></url>`).join('\n');
await writeFile(join(dist,'sitemap.xml'),`<?xml version="1.0" encoding="UTF-8"?>\n<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">\n${urls}\n</urlset>\n`);
runPython('Source package publishing', ['tools/publish_source.py','--root',root,'--out',dist]);
runPython('Source package verification', ['tools/verify_source.py','--root',root,'--dist',dist]);
console.log(`Built ${PAGES.length} localized pages, 2 not-found pages and ${ANSWER_SCHEDULE.length} reviewed daily puzzles into dist/ (analytics ${analyticsEndpoint ? 'enabled' : 'disabled'}, GTM ${gtmId ? `enabled: ${gtmId}` : 'disabled'}); published and verified /source/, /source.zip and /source-manifest.json`);