Tested: static Astro site answering hard Bible questions
Built from the kit specs (CLAUDE.md, docs/01-05): question index import, status seals, connections graph, Pagefind search, Scripture margin, and 157 evidence articles (drafts unless published) with sources and verified "Learn more" links. Includes link, owner-notes, a11y and publish scripts. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -0,0 +1,99 @@
|
||||
#!/usr/bin/env node
|
||||
// Accessibility check: runs axe-core against the built site in light and dark themes, on desktop
|
||||
// and phone widths, using the Chrome already installed on this machine (no browser download).
|
||||
// Run with: npm run a11y (after npm run build)
|
||||
// Fails if axe reports any serious or critical issue.
|
||||
|
||||
import { spawn } from "node:child_process";
|
||||
import { chromium } from "playwright-core";
|
||||
import { AxeBuilder } from "@axe-core/playwright";
|
||||
import data from "../src/data/questions.json" with { type: "json" };
|
||||
|
||||
const PORT = 4329;
|
||||
const BASE = `http://localhost:${PORT}`;
|
||||
|
||||
const q = (id) => `/questions/${data.questions.find((x) => x.id === id).slug}/`;
|
||||
const pages = [
|
||||
"/",
|
||||
"/questions/",
|
||||
"/questions/?status=red",
|
||||
q("3.1"), // links to a whole group
|
||||
q("2.12"), // italics and curly quotes in the answer
|
||||
q("3B.14"), // a "missing book" row (no domains)
|
||||
q("7.9"),
|
||||
`/groups/${data.groups[0].slug}/`,
|
||||
"/groups/missing-books/",
|
||||
"/about/",
|
||||
"/connections/",
|
||||
"/this-page-does-not-exist/",
|
||||
];
|
||||
|
||||
const viewports = [
|
||||
{ name: "desktop", width: 1280, height: 900 },
|
||||
{ name: "phone", width: 390, height: 844 },
|
||||
];
|
||||
|
||||
// Astro allows one preview server per project; --force replaces any that's already running.
|
||||
const server = spawn("npx", ["astro", "preview", "--force", "--port", String(PORT)], {
|
||||
shell: true,
|
||||
stdio: "ignore",
|
||||
});
|
||||
|
||||
async function waitForServer() {
|
||||
for (let i = 0; i < 60; i++) {
|
||||
try {
|
||||
if ((await fetch(BASE)).ok) return;
|
||||
} catch {}
|
||||
await new Promise((r) => setTimeout(r, 500));
|
||||
}
|
||||
throw new Error("Preview server did not start");
|
||||
}
|
||||
|
||||
let failures = 0;
|
||||
const browser = await chromium.launch({ channel: "chrome" });
|
||||
try {
|
||||
await waitForServer();
|
||||
for (const theme of ["light", "dark"]) {
|
||||
for (const vp of viewports) {
|
||||
const context = await browser.newContext({
|
||||
viewport: { width: vp.width, height: vp.height },
|
||||
colorScheme: theme,
|
||||
reducedMotion: "reduce",
|
||||
});
|
||||
const page = await context.newPage();
|
||||
for (const path of pages) {
|
||||
await page.goto(BASE + path, { waitUntil: "networkidle" });
|
||||
const { violations } = await new AxeBuilder({ page })
|
||||
.withTags(["wcag2a", "wcag2aa", "wcag21a", "wcag21aa", "wcag22aa", "best-practice"])
|
||||
.analyze();
|
||||
const serious = violations.filter((v) => ["serious", "critical"].includes(v.impact));
|
||||
const minor = violations.filter((v) => !serious.includes(v));
|
||||
const label = `${theme.padEnd(5)} ${vp.name.padEnd(7)} ${path}`;
|
||||
if (!violations.length) {
|
||||
console.log(`ok ${label}`);
|
||||
continue;
|
||||
}
|
||||
failures += serious.length;
|
||||
console.log(`${serious.length ? "FAIL" : "note"} ${label}`);
|
||||
for (const v of [...serious, ...minor]) {
|
||||
console.log(` [${v.impact}] ${v.id}: ${v.help} (${v.nodes.length} element(s))`);
|
||||
for (const n of v.nodes.slice(0, 3)) console.log(` ${n.target.join(" ")}`);
|
||||
}
|
||||
}
|
||||
await context.close();
|
||||
}
|
||||
}
|
||||
} finally {
|
||||
await browser.close();
|
||||
// Killing the npx wrapper doesn't reliably stop the server on Windows; Astro's own command does.
|
||||
await new Promise((resolve) =>
|
||||
spawn("npx", ["astro", "preview", "stop"], { shell: true, stdio: "ignore" }).on(
|
||||
"exit",
|
||||
resolve,
|
||||
),
|
||||
);
|
||||
server.kill();
|
||||
}
|
||||
|
||||
console.log(failures ? `\n${failures} serious issue(s).` : "\nNo serious accessibility issues.");
|
||||
process.exit(failures ? 1 : 0);
|
||||
@@ -0,0 +1,122 @@
|
||||
#!/usr/bin/env node
|
||||
// Renders the brand SVGs in brand/ into the icons and social card in public/.
|
||||
// Run with: npm run icons (also runs as part of npm run build)
|
||||
//
|
||||
// sharp's SVG renderer only sees system fonts, and Literata / IBM Plex Sans aren't installed on most
|
||||
// machines. So every <text> element is first converted to outlined paths using the real font files,
|
||||
// which makes the PNGs look identical on any computer or build server.
|
||||
|
||||
import { readFileSync, writeFileSync, mkdirSync, copyFileSync } from "node:fs";
|
||||
import { createRequire } from "node:module";
|
||||
import opentype from "opentype.js";
|
||||
import sharp from "sharp";
|
||||
|
||||
const require = createRequire(import.meta.url);
|
||||
const out = "public";
|
||||
mkdirSync(out, { recursive: true });
|
||||
|
||||
const loadFont = (pkgFile) => {
|
||||
const buf = readFileSync(require.resolve(pkgFile));
|
||||
return opentype.parse(buf.buffer.slice(buf.byteOffset, buf.byteOffset + buf.byteLength));
|
||||
};
|
||||
const fonts = {
|
||||
literata: loadFont("@fontsource/literata/files/literata-latin-600-normal.woff"),
|
||||
plex: loadFont("@fontsource/ibm-plex-sans/files/ibm-plex-sans-latin-400-normal.woff"),
|
||||
};
|
||||
|
||||
const attr = (tag, name) => tag.match(new RegExp(`\\s${name}="([^"]*)"`))?.[1];
|
||||
|
||||
// Serialize path commands ourselves: opentype.js 2.0's toPathData() occasionally emits "NaN"
|
||||
// for some coordinates, which makes the SVG renderer stop drawing the rest of the text.
|
||||
const n = (v) => Number(v.toFixed(2));
|
||||
const pathData = (path) =>
|
||||
path.commands
|
||||
.map((c) => {
|
||||
switch (c.type) {
|
||||
case "M":
|
||||
case "L":
|
||||
return `${c.type}${n(c.x)} ${n(c.y)}`;
|
||||
case "Q":
|
||||
return `Q${n(c.x1)} ${n(c.y1)} ${n(c.x)} ${n(c.y)}`;
|
||||
case "C":
|
||||
return `C${n(c.x1)} ${n(c.y1)} ${n(c.x2)} ${n(c.y2)} ${n(c.x)} ${n(c.y)}`;
|
||||
default:
|
||||
return "Z";
|
||||
}
|
||||
})
|
||||
.join("");
|
||||
|
||||
/** Replaces each <text> with a <path> outlined in the font its font-family names. */
|
||||
function outlineText(svg) {
|
||||
return svg.replace(/<text\b([^>]*)>([^<]*)<\/text>/g, (_, attrs, raw) => {
|
||||
const family = attr(attrs, "font-family") ?? "";
|
||||
const font = /literata/i.test(family) ? fonts.literata : fonts.plex;
|
||||
const size = Number(attr(attrs, "font-size") ?? 16);
|
||||
const text = raw.replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">");
|
||||
// SVG letter-spacing is in user units; opentype.js wants a fraction of the em.
|
||||
const letterSpacing = Number(attr(attrs, "letter-spacing") ?? 0) / size;
|
||||
const path = font.getPath(
|
||||
text,
|
||||
Number(attr(attrs, "x") ?? 0),
|
||||
Number(attr(attrs, "y") ?? 0),
|
||||
size,
|
||||
{ kerning: true, letterSpacing },
|
||||
);
|
||||
const d = pathData(path);
|
||||
if (d.includes("NaN")) throw new Error(`Could not outline "${raw}"`);
|
||||
return `<path d="${d}" fill="${attr(attrs, "fill") ?? "#000"}"><title>${raw}</title></path>`;
|
||||
});
|
||||
}
|
||||
|
||||
const brand = (name) => readFileSync(`brand/${name}`, "utf8");
|
||||
const png = (svg, size) =>
|
||||
sharp(Buffer.from(svg), { density: 384 }).resize(size, size).png().toBuffer();
|
||||
|
||||
/** Packs PNG images into a .ico container (PNG-in-ICO, supported by every current browser). */
|
||||
function toIco(images) {
|
||||
const header = Buffer.alloc(6);
|
||||
header.writeUInt16LE(0, 0);
|
||||
header.writeUInt16LE(1, 2); // 1 = icon
|
||||
header.writeUInt16LE(images.length, 4);
|
||||
let offset = 6 + 16 * images.length;
|
||||
const entries = images.map(({ size, data }) => {
|
||||
const e = Buffer.alloc(16);
|
||||
e.writeUInt8(size >= 256 ? 0 : size, 0);
|
||||
e.writeUInt8(size >= 256 ? 0 : size, 1);
|
||||
e.writeUInt16LE(1, 4); // colour planes
|
||||
e.writeUInt16LE(32, 6); // bits per pixel
|
||||
e.writeUInt32LE(data.length, 8);
|
||||
e.writeUInt32LE(offset, 12);
|
||||
offset += data.length;
|
||||
return e;
|
||||
});
|
||||
return Buffer.concat([header, ...entries, ...images.map((i) => i.data)]);
|
||||
}
|
||||
|
||||
const favicon = brand("favicon.svg");
|
||||
// iOS draws its own rounded corners and fills transparency with black, so give it a square tile.
|
||||
const squareTile = favicon.replace(/\s+rx="[^"]*"/, "");
|
||||
|
||||
copyFileSync("brand/favicon.svg", `${out}/favicon.svg`);
|
||||
writeFileSync(
|
||||
`${out}/favicon.ico`,
|
||||
toIco(
|
||||
await Promise.all([16, 32, 48].map(async (size) => ({ size, data: await png(favicon, size) }))),
|
||||
),
|
||||
);
|
||||
writeFileSync(`${out}/apple-touch-icon.png`, await png(squareTile, 180));
|
||||
writeFileSync(`${out}/icon-192.png`, await png(favicon, 192));
|
||||
writeFileSync(`${out}/icon-512.png`, await png(favicon, 512));
|
||||
|
||||
const og = outlineText(brand("og-image.svg"));
|
||||
writeFileSync(
|
||||
`${out}/og-image.png`,
|
||||
await sharp(Buffer.from(og)).resize(1200, 630).png().toBuffer(),
|
||||
);
|
||||
|
||||
// An outlined copy of the full logo, safe to use anywhere the web fonts aren't loaded.
|
||||
writeFileSync(`${out}/logo-full.svg`, outlineText(brand("logo-full.svg")));
|
||||
|
||||
console.log(
|
||||
"Wrote favicon.svg, favicon.ico, apple-touch-icon.png, icon-192.png, icon-512.png, og-image.png and logo-full.svg to public/",
|
||||
);
|
||||
@@ -0,0 +1,116 @@
|
||||
#!/usr/bin/env node
|
||||
// Checks every external link in the articles (Learn more links and source URLs).
|
||||
//
|
||||
// npm run check-links check all articles
|
||||
// npm run check-links -- 2-1 7-9 check only these article files
|
||||
// npm run check-links -- --fresh ignore the cache and re-check everything
|
||||
//
|
||||
// YouTube links are checked through YouTube's oEmbed endpoint, which confirms the video exists
|
||||
// and returns its real title and channel, so you can see that each video is what it claims to be.
|
||||
// Other links get a normal request. Results are cached in .cache/links.json for a week.
|
||||
// Needs internet access, so it isn't part of `npm run build`.
|
||||
|
||||
import { readFileSync, readdirSync, writeFileSync, mkdirSync, existsSync } from "node:fs";
|
||||
import { parse } from "yaml";
|
||||
|
||||
const dir = "src/content/articles";
|
||||
const cacheFile = ".cache/links.json";
|
||||
const WEEK = 7 * 24 * 60 * 60 * 1000;
|
||||
const args = process.argv.slice(2);
|
||||
const fresh = args.includes("--fresh");
|
||||
const only = args.filter((a) => !a.startsWith("--")).map((a) => a.replace(/\.mdx$/, ""));
|
||||
|
||||
const cache = !fresh && existsSync(cacheFile) ? JSON.parse(readFileSync(cacheFile, "utf8")) : {};
|
||||
|
||||
const frontmatter = (text) => parse(text.match(/^---\r?\n([\s\S]*?)\r?\n---/)?.[1] ?? "") ?? {};
|
||||
|
||||
// Collect links per article.
|
||||
const jobs = [];
|
||||
for (const file of readdirSync(dir).filter((f) => f.endsWith(".mdx"))) {
|
||||
const id = file.replace(/\.mdx$/, "");
|
||||
if (only.length && !only.includes(id)) continue;
|
||||
const data = frontmatter(readFileSync(`${dir}/${file}`, "utf8"));
|
||||
for (const l of data.learnMore ?? [])
|
||||
jobs.push({ file, url: l.url, title: l.title, type: l.type });
|
||||
for (const s of data.sources ?? [])
|
||||
if (s.url) jobs.push({ file, url: s.url, title: s.title, type: "source" });
|
||||
}
|
||||
|
||||
const youtubeId = (url) =>
|
||||
url.match(/(?:youtube\.com\/watch\?v=|youtu\.be\/|youtube\.com\/embed\/)([\w-]{11})/)?.[1];
|
||||
|
||||
const UA =
|
||||
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/130 Safari/537.36";
|
||||
|
||||
async function check(url) {
|
||||
const hit = cache[url];
|
||||
if (hit && Date.now() - hit.at < WEEK) return hit;
|
||||
let result;
|
||||
try {
|
||||
const id = youtubeId(url);
|
||||
if (id) {
|
||||
const res = await fetch(
|
||||
`https://www.youtube.com/oembed?url=${encodeURIComponent(`https://www.youtube.com/watch?v=${id}`)}&format=json`,
|
||||
);
|
||||
result = res.ok
|
||||
? {
|
||||
ok: true,
|
||||
status: res.status,
|
||||
...(({ title, author_name }) => ({ title, channel: author_name }))(await res.json()),
|
||||
}
|
||||
: { ok: false, status: res.status };
|
||||
} else {
|
||||
const res = await fetch(url, {
|
||||
redirect: "follow",
|
||||
headers: { "User-Agent": UA, Accept: "text/html,application/xhtml+xml,*/*" },
|
||||
signal: AbortSignal.timeout(20000),
|
||||
});
|
||||
// Some sites refuse automated requests (403/429) even though the page exists.
|
||||
result = {
|
||||
ok: res.ok,
|
||||
blocked: [401, 403, 429].includes(res.status),
|
||||
status: res.status,
|
||||
final: res.url,
|
||||
};
|
||||
}
|
||||
} catch (e) {
|
||||
result = { ok: false, status: 0, error: String(e.cause?.code ?? e.message) };
|
||||
}
|
||||
result.at = Date.now();
|
||||
cache[url] = result;
|
||||
return result;
|
||||
}
|
||||
|
||||
// Check with limited concurrency.
|
||||
const unique = [...new Set(jobs.map((j) => j.url))];
|
||||
const queue = [...unique];
|
||||
await Promise.all(
|
||||
Array.from({ length: 8 }, async () => {
|
||||
while (queue.length) await check(queue.shift());
|
||||
}),
|
||||
);
|
||||
|
||||
mkdirSync(".cache", { recursive: true });
|
||||
writeFileSync(cacheFile, JSON.stringify(cache, null, 2));
|
||||
|
||||
let broken = 0;
|
||||
let blocked = 0;
|
||||
const videos = [];
|
||||
for (const j of jobs) {
|
||||
const r = cache[j.url];
|
||||
if (youtubeId(j.url) && r.ok)
|
||||
videos.push(` ${j.file.padEnd(10)} “${r.title}” — ${r.channel} (listed as: ${j.title})`);
|
||||
if (r.ok) continue;
|
||||
if (r.blocked) {
|
||||
blocked++;
|
||||
console.log(`? ${j.file.padEnd(10)} ${r.status} (site refuses automated checks) ${j.url}`);
|
||||
} else {
|
||||
broken++;
|
||||
console.log(`✗ ${j.file.padEnd(10)} ${r.status || r.error} ${j.url}`);
|
||||
}
|
||||
}
|
||||
if (videos.length) console.log(`\nVideos (real titles from YouTube):\n${videos.join("\n")}`);
|
||||
console.log(
|
||||
`\n${jobs.length} links in ${new Set(jobs.map((j) => j.file)).size} articles: ${broken} broken, ${blocked} could not be checked automatically.`,
|
||||
);
|
||||
process.exit(broken ? 1 : 0);
|
||||
@@ -0,0 +1,87 @@
|
||||
#!/usr/bin/env node
|
||||
// Build guard: fails if any private owner note (authorNotes) appears anywhere in dist/,
|
||||
// including inside the Pagefind search index. Runs at the end of `npm run build`.
|
||||
// Pass a folder to scan something else, e.g. `node scripts/check-notes.mjs src/content/articles`.
|
||||
//
|
||||
// It looks for each whole note and for every run of 8 consecutive words from it, after
|
||||
// normalising case, punctuation, tags and HTML entities, so a partial leak is caught too.
|
||||
|
||||
import { readFileSync, readdirSync, statSync } from "node:fs";
|
||||
import { join } from "node:path";
|
||||
import { gunzipSync } from "node:zlib";
|
||||
|
||||
const WINDOW = 8;
|
||||
const data = JSON.parse(readFileSync("src/data/questions.json", "utf8"));
|
||||
|
||||
const normalise = (s) =>
|
||||
s
|
||||
.replace(/<[^>]+>/g, " ")
|
||||
.replace(/&#(\d+);/g, (_, n) => String.fromCodePoint(Number(n)))
|
||||
.replace(/&#x([0-9a-f]+);/gi, (_, n) => String.fromCodePoint(parseInt(n, 16)))
|
||||
.replace(/"/g, '"')
|
||||
.replace(/&/g, "&")
|
||||
.replace(/&[a-z]+;/g, " ")
|
||||
.replace(/\\u([0-9a-f]{4})/gi, (_, n) => String.fromCharCode(parseInt(n, 16)))
|
||||
.toLowerCase()
|
||||
.replace(/[^\p{L}\p{N}]+/gu, " ")
|
||||
.trim();
|
||||
|
||||
// Every phrase to look for, remembering which question's note it came from.
|
||||
const needles = [];
|
||||
for (const q of data.questions) {
|
||||
if (!q.authorNotes) continue;
|
||||
const words = normalise(q.authorNotes).split(" ");
|
||||
if (words.length <= WINDOW) needles.push({ id: q.id, text: words.join(" ") });
|
||||
else
|
||||
for (let i = 0; i + WINDOW <= words.length; i++)
|
||||
needles.push({ id: q.id, text: words.slice(i, i + WINDOW).join(" ") });
|
||||
}
|
||||
|
||||
const walk = (dir) =>
|
||||
readdirSync(dir).flatMap((f) => {
|
||||
const p = join(dir, f);
|
||||
return statSync(p).isDirectory() ? walk(p) : [p];
|
||||
});
|
||||
|
||||
function readText(file) {
|
||||
const buf = readFileSync(file);
|
||||
// Pagefind's index files are gzipped.
|
||||
if (buf[0] === 0x1f && buf[1] === 0x8b) {
|
||||
try {
|
||||
return gunzipSync(buf).toString("utf8");
|
||||
} catch {
|
||||
return "";
|
||||
}
|
||||
}
|
||||
return /\.(html|js|mjs|json|css|xml|txt|webmanifest|svg|mdx|md|pf_\w+)$/.test(file)
|
||||
? buf.toString("utf8")
|
||||
: "";
|
||||
}
|
||||
|
||||
const problems = [];
|
||||
let scanned = 0;
|
||||
const root = process.argv[2] ?? "dist";
|
||||
for (const file of walk(root)) {
|
||||
const raw = readText(file);
|
||||
if (!raw) continue;
|
||||
scanned++;
|
||||
if (raw.includes("authorNotes")) problems.push(`${file}: contains the "authorNotes" field`);
|
||||
const text = ` ${normalise(raw)} `;
|
||||
const found = new Set();
|
||||
for (const { id, text: needle } of needles) {
|
||||
if (!found.has(id) && text.includes(` ${needle} `)) {
|
||||
found.add(id);
|
||||
problems.push(`${file}: contains owner notes from question ${id}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (problems.length) {
|
||||
console.error(
|
||||
`Owner notes leaked into the build (${problems.length}):\n- ${problems.join("\n- ")}`,
|
||||
);
|
||||
process.exit(1);
|
||||
}
|
||||
console.log(
|
||||
`Owner notes check passed: ${scanned} files scanned, ${needles.length} phrases from ${data.questions.filter((q) => q.authorNotes).length} notes, none found.`,
|
||||
);
|
||||
@@ -0,0 +1,216 @@
|
||||
#!/usr/bin/env node
|
||||
// Converts the owner's question index (Markdown export of the "Bible Defense — Question Index" doc)
|
||||
// into src/data/questions.json. Run with: npm run import
|
||||
// Usage: node scripts/import-index.mjs [input.md] [output.json]
|
||||
|
||||
import { readFileSync, writeFileSync, mkdirSync, existsSync } from "node:fs";
|
||||
import { dirname } from "node:path";
|
||||
|
||||
const input = process.argv[2] ?? "content/source/question-index.md";
|
||||
const output = process.argv[3] ?? "src/data/questions.json";
|
||||
|
||||
const STATUS = { green: "green", yellow: "yellow", red: "red" };
|
||||
const DOMAINS = new Set([
|
||||
"Scripture",
|
||||
"History",
|
||||
"Archaeology",
|
||||
"Science",
|
||||
"Philosophy",
|
||||
"Textual Criticism",
|
||||
"Context",
|
||||
"Theology",
|
||||
]);
|
||||
// Article files are named after the question id, lowercase, dots as dashes: 3B.10 -> 3b-10.mdx
|
||||
const articleFile = (id) => `src/content/articles/${id.replace(/\./g, "-").toLowerCase()}.mdx`;
|
||||
const NOTE_SPLIT = /\s*\b(?:My Notes|Note)\s*:\s*/i;
|
||||
|
||||
const decode = (s) =>
|
||||
s
|
||||
.replace(/ /g, " ")
|
||||
.replace(/&/g, "&")
|
||||
.replace(/"/g, '"')
|
||||
.replace(/'/g, "'")
|
||||
.replace(/</g, "<")
|
||||
.replace(/>/g, ">")
|
||||
.replace(/\\\n/g, " ") // hard line breaks inside cells
|
||||
.replace(/\s+/g, " ")
|
||||
.trim();
|
||||
|
||||
const slugify = (s) =>
|
||||
s
|
||||
.toLowerCase()
|
||||
.normalize("NFKD")
|
||||
.replace(/[\u0300-\u036f]/g, "")
|
||||
.replace(/['’"]/g, "")
|
||||
.replace(/[^a-z0-9]+/g, "-")
|
||||
.replace(/^-|-$/g, "")
|
||||
.slice(0, 70)
|
||||
.replace(/-$/, "");
|
||||
|
||||
// Join physical lines so each table row is one logical line (rows can span lines via "\" breaks).
|
||||
function logicalLines(md) {
|
||||
const raw = md.replace(/\r\n/g, "\n").split("\n");
|
||||
const out = [];
|
||||
for (const line of raw) {
|
||||
const prev = out[out.length - 1];
|
||||
if (prev !== undefined && prev.startsWith("|") && !prev.trimEnd().endsWith("|")) {
|
||||
out[out.length - 1] = prev + "\n" + line;
|
||||
} else {
|
||||
out.push(line);
|
||||
}
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
const splitRow = (line) =>
|
||||
line
|
||||
.trim()
|
||||
.replace(/^\|/, "")
|
||||
.replace(/\|$/, "")
|
||||
.split(/(?<!\\)\|/)
|
||||
.map((c) => c.trim());
|
||||
|
||||
// "3B.1–3B.9 Apocrypha books" -> ["3B.1", ..., "3B.9"]; "3B Missing books" -> ["group:3B"]; "4.1 Text changed?" -> ["4.1"]
|
||||
function parseRelatedLabel(label, problems, ctx) {
|
||||
const range = label.match(/^(\d+B?)\.(\d+)\s*[–-]\s*\1\.(\d+)\b/);
|
||||
if (range) {
|
||||
const [, prefix, a, b] = range;
|
||||
const ids = [];
|
||||
for (let n = Number(a); n <= Number(b); n++) ids.push(`${prefix}.${n}`);
|
||||
return ids;
|
||||
}
|
||||
const single = label.match(/^(\d+B?\.\d+)\b/);
|
||||
if (single) return [single[1]];
|
||||
const group = label.match(/^(\d+B?)\b/);
|
||||
if (group) return [`group:${group[1]}`];
|
||||
problems.push(`${ctx}: could not read related link "${label}"`);
|
||||
return [];
|
||||
}
|
||||
|
||||
function parseRelated(cell, problems, ctx) {
|
||||
const labels = [...cell.matchAll(/\[([^\]]+)\]\([^)]*\)/g)].map((m) => m[1]);
|
||||
// Fallback for plain-text (unlinked) related cells
|
||||
const list = labels.length ? labels : cell.split(/,\s*(?=\d)/).filter(Boolean);
|
||||
return [...new Set(list.flatMap((l) => parseRelatedLabel(decode(l), problems, ctx)))];
|
||||
}
|
||||
|
||||
function main() {
|
||||
const md = readFileSync(input, "utf8");
|
||||
const lines = logicalLines(md);
|
||||
const groups = [];
|
||||
const questions = [];
|
||||
const problems = [];
|
||||
let group = null;
|
||||
let header = null;
|
||||
|
||||
for (const line of lines) {
|
||||
const heading = line.match(/^#{2,3}\s+(\d+B?)\.\s+(.+)$/);
|
||||
if (heading) {
|
||||
const [, id, title] = heading;
|
||||
const clean = decode(title).replace(/^"|"$/g, "");
|
||||
group = {
|
||||
id,
|
||||
slug: slugify(id === "3B" ? "missing books" : clean),
|
||||
title: clean,
|
||||
order: groups.length + 1,
|
||||
};
|
||||
groups.push(group);
|
||||
header = null;
|
||||
continue;
|
||||
}
|
||||
if (/^#{1,3}\s/.test(line)) {
|
||||
group = null;
|
||||
header = null;
|
||||
continue;
|
||||
} // non-numbered heading (e.g. "How to read this")
|
||||
if (!group) continue;
|
||||
|
||||
if (line.startsWith("|")) {
|
||||
const cells = splitRow(line);
|
||||
if (cells.every((c) => /^:?-+:?$/.test(c))) continue; // separator row
|
||||
if (!header) {
|
||||
header = cells.map((c) => c.toLowerCase());
|
||||
continue;
|
||||
}
|
||||
|
||||
const col = (name) => cells[header.findIndex((h) => h.startsWith(name))] ?? "";
|
||||
const id = decode(col("#"));
|
||||
const ctx = `Row ${id || "?"}`;
|
||||
const title = decode(col("question") || col("book"));
|
||||
const statusWord = decode(col("status")).toLowerCase();
|
||||
const answerCell = decode(col("basic answer") || col("what it is"));
|
||||
const [answer, ...noteParts] = answerCell.split(NOTE_SPLIT);
|
||||
const domainsCell = decode(col("domains"));
|
||||
|
||||
if (!id) {
|
||||
problems.push(`${group.id}: row without an id`);
|
||||
continue;
|
||||
}
|
||||
if (!STATUS[statusWord]) problems.push(`${ctx}: unknown status "${statusWord}"`);
|
||||
if (!title) problems.push(`${ctx}: missing question title`);
|
||||
if (!answer.trim()) problems.push(`${ctx}: missing answer`);
|
||||
const domains = domainsCell ? domainsCell.split(/,\s*/).filter(Boolean) : [];
|
||||
for (const d of domains) if (!DOMAINS.has(d)) problems.push(`${ctx}: unknown domain "${d}"`);
|
||||
|
||||
const q = {
|
||||
id,
|
||||
slug: slugify(`${id} ${title}`),
|
||||
groupId: group.id,
|
||||
title,
|
||||
status: STATUS[statusWord],
|
||||
domains,
|
||||
answer: answer.trim(),
|
||||
related: parseRelated(col("related"), problems, ctx),
|
||||
hasArticle: existsSync(articleFile(id)),
|
||||
};
|
||||
if (header.some((h) => h === "group")) q.bookGroup = decode(col("group"));
|
||||
const notes = noteParts.join(" ").trim();
|
||||
if (notes) q.authorNotes = notes;
|
||||
questions.push(q);
|
||||
continue;
|
||||
}
|
||||
|
||||
// First plain paragraph under a group heading becomes its intro.
|
||||
const text = decode(line);
|
||||
if (text && !header && !group.intro) group.intro = text;
|
||||
}
|
||||
|
||||
// Validation
|
||||
const ids = new Set(questions.map((q) => q.id));
|
||||
const groupIds = new Set(groups.map((g) => g.id));
|
||||
const seen = new Set();
|
||||
const seenSlugs = new Set();
|
||||
for (const q of questions) {
|
||||
if (seen.has(q.id)) problems.push(`Duplicate id ${q.id}`);
|
||||
seen.add(q.id);
|
||||
if (seenSlugs.has(q.slug)) problems.push(`Duplicate slug ${q.slug}`);
|
||||
seenSlugs.add(q.slug);
|
||||
for (const r of q.related) {
|
||||
const ok = r.startsWith("group:") ? groupIds.has(r.slice(6)) : ids.has(r);
|
||||
if (!ok) problems.push(`${q.id}: related "${r}" does not exist`);
|
||||
if (r === q.id) problems.push(`${q.id}: links to itself`);
|
||||
}
|
||||
}
|
||||
|
||||
// Fail without writing, so a typo can never ship a guessed status or a broken link.
|
||||
if (problems.length) {
|
||||
console.error(`Import found ${problems.length} problem(s):\n- ` + problems.join("\n- "));
|
||||
console.error(`\n${output} was not updated.`);
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
mkdirSync(dirname(output), { recursive: true });
|
||||
writeFileSync(
|
||||
output,
|
||||
JSON.stringify({ generatedFrom: input, groups, questions }, null, 2) + "\n",
|
||||
);
|
||||
const counts = questions.reduce((a, q) => ((a[q.status] = (a[q.status] ?? 0) + 1), a), {});
|
||||
const articles = questions.filter((q) => q.hasArticle).length;
|
||||
console.log(
|
||||
`Wrote ${groups.length} groups and ${questions.length} questions to ${output}`,
|
||||
counts,
|
||||
{ articles },
|
||||
);
|
||||
}
|
||||
|
||||
main();
|
||||
@@ -0,0 +1,62 @@
|
||||
#!/usr/bin/env node
|
||||
// Publishes reviewed articles by removing their `draft: true` line, or puts them back as drafts.
|
||||
//
|
||||
// npm run publish -- 7.9 1.1 3B.10 publish these questions' articles
|
||||
// npm run publish -- --all publish every article
|
||||
// npm run publish -- --draft 7.9 mark an article as a draft again (also works with --all)
|
||||
// npm run publish -- --list show which articles are drafts and which are published
|
||||
|
||||
import { readFileSync, writeFileSync, readdirSync } from "node:fs";
|
||||
|
||||
const dir = "src/content/articles";
|
||||
const args = process.argv.slice(2);
|
||||
const toDraft = args.includes("--draft");
|
||||
const all = args.includes("--all");
|
||||
const ids = args.filter((a) => !a.startsWith("--"));
|
||||
|
||||
const files = readdirSync(dir).filter((f) => f.endsWith(".mdx"));
|
||||
const questionOf = (text) => text.match(/^question:\s*"([^"]+)"/m)?.[1];
|
||||
const isDraft = (text) => /^draft:\s*true\s*$/m.test(text);
|
||||
|
||||
if (args.includes("--list")) {
|
||||
const rows = files.map((f) => {
|
||||
const text = readFileSync(`${dir}/${f}`, "utf8");
|
||||
return { id: questionOf(text) ?? f, draft: isDraft(text) };
|
||||
});
|
||||
const drafts = rows.filter((r) => r.draft).map((r) => r.id);
|
||||
const published = rows.filter((r) => !r.draft).map((r) => r.id);
|
||||
console.log(`Published (${published.length}): ${published.join(", ") || "none"}`);
|
||||
console.log(`Drafts (${drafts.length}): ${drafts.join(", ") || "none"}`);
|
||||
process.exit(0);
|
||||
}
|
||||
|
||||
if (!all && ids.length === 0) {
|
||||
console.error("Name question ids (e.g. 7.9 3B.10), or pass --all. Add --draft to unpublish.");
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
const wanted = new Set(ids.map((id) => id.toUpperCase()));
|
||||
let changed = 0;
|
||||
const missing = new Set(wanted);
|
||||
|
||||
for (const f of files) {
|
||||
const path = `${dir}/${f}`;
|
||||
const text = readFileSync(path, "utf8");
|
||||
const id = questionOf(text);
|
||||
if (!id || (!all && !wanted.has(id.toUpperCase()))) continue;
|
||||
missing.delete(id.toUpperCase());
|
||||
|
||||
let next = text;
|
||||
if (toDraft && !isDraft(text)) {
|
||||
next = text.replace(/^(question:.*)$/m, "$1\ndraft: true");
|
||||
} else if (!toDraft && isDraft(text)) {
|
||||
next = text.replace(/^draft:\s*true\s*\r?\n/m, "");
|
||||
}
|
||||
if (next !== text) {
|
||||
writeFileSync(path, next);
|
||||
changed++;
|
||||
}
|
||||
}
|
||||
|
||||
if (missing.size) console.error(`No article found for: ${[...missing].join(", ")}`);
|
||||
console.log(`${toDraft ? "Marked as draft" : "Published"}: ${changed} article(s).`);
|
||||
Reference in New Issue
Block a user