// The API reference in docs/reference/, generated from the sources of truth: // - the .d.ts files of @nowaki-dev/runtime and @nowaki-dev/markdoc (declarations and their JSDoc), // read with the TypeScript compiler API like scripts/api-surface.mjs; // - the api/*.txt snapshots (route exports, file conventions, config keys, CLI flags, environment // variables, endpoints, headers, cookies, client events), which CI keeps in step with the code; // - a few constants read from the code (default security headers, the CSP policy, create-nowaki // templates); // - scripts/gen-reference-data.mjs for descriptions the source has no doc comment for. // // node scripts/gen-reference.mjs write docs/reference/*.md // node scripts/gen-reference.mjs --check fail when docs/reference/ is out of date (CI) // // Generation fails when a stable name has no description, when a description names something that // no longer exists, when the snapshots and the types disagree (a config key or route export missing // from its type), or when a generated page links to an anchor no page has. Output is deterministic: // "\n" line endings, declarations in source order, everything else sorted or in snapshot order. import { existsSync, mkdirSync, readdirSync, readFileSync, unlinkSync, writeFileSync } from "node:fs"; import path from "node:path"; import { pathToFileURL } from "node:url"; import ts from "typescript"; import { REPO } from "./api-surface.mjs"; import { CLIENT, CREATE_FLAGS, ENV, ENV_GROUPS, FILES, HTTP } from "./gen-reference-data.mjs"; const OUT_DIR = "docs/reference"; const normalize = (s) => s.replace(/\r\n?/g, "\n"); const read = (root, file) => normalize(readFileSync(path.join(root, file), "utf8")); const NOTICE = (sources) => ``; const GENERATED = "Generated from the source by `scripts/gen-reference.mjs`; do not edit by hand."; // --------------------------------------------------------------------------------------------- // api/*.txt snapshots const COMMENT = /\s{2,}#\s.*$|\s{2,}#$/; /// Entries of a snapshot: [{ status, title, text, comment }], in file order. function snapshot(root, file) { const out = []; let section = null; for (const raw of read(root, `api/${file}`).split("\n")) { const line = raw.trimEnd(); if (!line.trim() || line.trimStart().startsWith("#")) continue; const h = line.match(/^\[(\S+)(?:\s+(.+))?\]$/); if (h) { section = { status: h[1], title: h[2] ?? "" }; continue; } const comment = line.match(COMMENT)?.[0].replace(/^\s+#\s?/, "") ?? ""; out.push({ ...section, text: line.replace(COMMENT, "").trim(), comment }); } return out; } const fail = (msg) => { throw new Error(`gen-reference: ${msg}`); }; /// Checks that `data` describes exactly the `names` (no missing, no stale keys). function described(data, names, what) { const missing = names.filter((n) => !Object.hasOwn(data, n)); const stale = Object.keys(data).filter((k) => !names.includes(k)); if (missing.length) fail(`no description for ${what} ${missing.join(", ")}; add it to scripts/gen-reference-data.mjs`); if (stale.length) fail(`scripts/gen-reference-data.mjs describes ${what} ${stale.join(", ")}, which the snapshot doesn't list; remove or rename it`); } // --------------------------------------------------------------------------------------------- // Markdown helpers /// GitHub's heading anchor: lowercase, punctuation other than "-" and "_" dropped, spaces to "-". const slug = (heading) => heading .toLowerCase() .replace(/`/g, "") .replace(/[^\p{L}\p{N}\s_-]/gu, "") .trim() .replace(/\s/g, "-"); const cell = (s) => s.replace(/\\/g, "\\\\").replace(/\|/g, "\\|").replace(/\n+/g, " "); const code = (s) => (s.includes("`") ? `\`\` ${s} \`\`` : `\`${s}\``); function table(head, rows) { return [`| ${head.join(" | ")} |`, `| ${head.map(() => "---").join(" | ")} |`, ...rows.map((r) => `| ${r.map(cell).join(" | ")} |`)].join("\n"); } /// Escapes `<` outside code spans (so `` written without backticks isn't read as HTML) and /// turns {@link Name} into a link through `link`. function inline(text, link) { return text .split(/(`+[^`]*`+)/) .map((part, i) => { if (i % 2 === 1) return part; return part .replace(/\{@link\s+([^}\s|]+)(?:[\s|]+([^}]*))?\}/g, (_, name, label) => link(name, label?.trim())) .replace(/ sf.text.startsWith("/**", c.pos) && !sf.text.startsWith("/**/", c.pos)).pop(); if (!r) return null; const body = sf.text.slice(r.pos + 3, r.end - 2); const lines = body.split("\n").map((l, i) => { const t = i === 0 ? l.replace(/^ /, "") : l.replace(/^\s*\* ?/, "").replace(/^\s*$/, ""); return t.trimEnd().replace(/\*\\\//g, "*/"); }); while (lines.length && !lines[0].trim()) lines.shift(); while (lines.length && !lines.at(-1).trim()) lines.pop(); const doc = { lines: [], tags: [] }; let cur = doc.lines; for (const l of lines) { const m = l.match(/^@(\w+)\b ?(.*)$/); if (m) { if (!TAGS.has(m[1])) fail(`${sf.fileName}: unknown JSDoc tag @${m[1]}; support it in scripts/gen-reference.mjs`); const t = { tag: m[1], lines: m[2] ? [m[2]] : [] }; doc.tags.push(t); cur = t.lines; } else cur.push(l); } return doc; } /// JSDoc description lines to Markdown. A run of lines indented by two or more spaces that isn't /// the continuation of a list item is a code sample and becomes a fenced block. function docMarkdown(lines, link) { const out = []; let inList = false; for (let i = 0; i < lines.length; i++) { const l = lines[i]; if (!l.trim()) { inList = false; out.push(""); continue; } if (/^\s{2,}\S/.test(l) && !inList) { const run = []; while (i < lines.length && (/^\s{2,}\S/.test(lines[i]) || (!lines[i].trim() && /^\s{2,}\S/.test(lines[i + 1] ?? "")))) run.push(lines[i++]); i--; const indent = Math.min(...run.filter((x) => x.trim()).map((x) => x.match(/^\s*/)[0].length)); if (out.length && out.at(-1) !== "") out.push(""); out.push("```tsx", ...run.map((x) => x.slice(indent)), "```", ""); continue; } if (/^([-*]|\d+\.) /.test(l)) inList = true; else if (!/^\s/.test(l)) inList = false; out.push(inline(l, link)); } return out.join("\n").replace(/\n{3,}/g, "\n\n").trim(); } /// First sentence of the description, on one line (for summary tables). function summary(doc) { if (!doc) return ""; const para = []; for (const l of doc.lines) { if (!l.trim() || /^\s{2,}/.test(l) || /^[-|]/.test(l)) break; para.push(l.trim()); } const text = para.join(" "); let tick = false; for (let i = 0; i < text.length; i++) { if (text[i] === "`") tick = !tick; else if (!tick && text[i] === "." && (i + 1 === text.length || text[i + 1] === " ") && !/\b(e\.g|i\.e)$/.test(text.slice(0, i))) return text.slice(0, i + 1); } return text; } function tagsMarkdown(doc, link) { if (!doc) return ""; const out = []; const by = (t) => doc.tags.filter((x) => x.tag === t); const params = by("param"); if (params.length) { out.push("Parameters:", ""); for (const p of params) { const [, name, rest] = p.lines.join("\n").match(/^(?:\{[^}]*\}\s*)?(\S+)\s*(?:-\s*)?([\s\S]*)$/) ?? []; out.push(`- \`${name}\`: ${inline(rest.replace(/\n/g, " "), link)}`); } out.push(""); } for (const r of by("returns")) out.push(`Returns: ${inline(r.lines.join(" "), link)}`, ""); for (const d of by("default")) out.push(`Default: ${inline(d.lines.join(" "), link)}`, ""); for (const s of by("see")) out.push(`See: ${inline(s.lines.join(" "), link)}`, ""); const examples = by("example"); if (examples.length) { out.push(examples.length === 1 ? "Example:" : "Examples:", ""); for (const e of examples) out.push("```tsx", ...e.lines, "```", ""); } return out.join("\n").trim(); } function deprecatedMarkdown(doc, link) { const d = doc?.tags.find((t) => t.tag === "deprecated"); return d ? `> **Deprecated.** ${inline(d.lines.join(" "), link)}` : ""; } // --------------------------------------------------------------------------------------------- // Declarations of a types file const printer = ts.createPrinter({ removeComments: true, newLine: ts.NewLineKind.LineFeed }); const hasExport = (n) => (ts.getCombinedModifierFlags(n) & ts.ModifierFlags.Export) !== 0; function parse(root, file) { return ts.createSourceFile(file, read(root, file), ts.ScriptTarget.Latest, true, ts.ScriptKind.TS); } /// Type names a node refers to (type references and `extends` clauses), in order of appearance. function typeRefs(node) { const names = []; const visit = (n) => { if (ts.isTypeReferenceNode(n) && ts.isIdentifier(n.typeName)) names.push(n.typeName.text); if (ts.isExpressionWithTypeArguments(n) && ts.isIdentifier(n.expression)) names.push(n.expression.text); ts.forEachChild(n, visit); }; visit(node); return [...new Set(names)]; } function kindOf(st) { if (ts.isFunctionDeclaration(st)) return /^[A-Z]/.test(st.name.text) ? "component" : "function"; if (ts.isClassDeclaration(st)) return "class"; if (ts.isInterfaceDeclaration(st)) return "interface"; if (ts.isTypeAliasDeclaration(st)) return "type"; if (ts.isVariableStatement(st)) return "const"; return null; } const KIND_LABEL = { component: "Component", function: "Function", class: "Class", interface: "Interface", type: "Type", const: "Constant" }; /// Members of a type with their JSDoc, recursing into object literal types (nested ones are listed /// only when documented): [{ name, doc, node }]. function membersOf(sf, members, prefix = "", all = true) { const out = []; const seen = new Set(); for (const m of members) { const name = m.name ? (ts.isIdentifier(m.name) || ts.isStringLiteral(m.name) ? m.name.text : m.name.getText(sf)) : null; if (ts.isConstructorDeclaration(m)) { out.push({ name: "constructor", doc: jsdoc(m, sf), node: m }); continue; } if (!name) continue; // index signatures const doc = jsdoc(m, sf); const key = prefix + name; if (!seen.has(key) && (all || doc)) out.push({ name: key, doc, node: m }); seen.add(key); if (m.type) out.push(...nestedMembers(sf, m.type, key)); } return out; } function nestedMembers(sf, type, prefix) { if (ts.isTypeLiteralNode(type)) return membersOf(sf, type.members, prefix ? `${prefix}.` : "", false); if (ts.isArrayTypeNode(type)) return nestedMembers(sf, type.elementType, `${prefix}[]`); if (ts.isParenthesizedTypeNode(type)) return nestedMembers(sf, type.type, prefix); if (ts.isUnionTypeNode(type) || ts.isIntersectionTypeNode(type)) return type.types.flatMap((t) => nestedMembers(sf, t, prefix)); return []; } /// Every declaration in a types file: [{ name, kind, exported, decls: [statement], doc }], plus /// re-exports [{ name, from }] and the default export's name. function declarations(sf) { const items = []; const byName = new Map(); const reexports = []; let defaultExport = null; for (const st of sf.statements) { if (ts.isImportDeclaration(st)) continue; if (ts.isExportDeclaration(st)) { const from = st.moduleSpecifier?.text; for (const el of st.exportClause?.elements ?? []) reexports.push({ name: el.name.text, from, type: st.isTypeOnly || el.isTypeOnly }); continue; } if (ts.isExportAssignment(st)) { defaultExport = st.expression.getText(sf); continue; } const kind = kindOf(st); if (!kind) continue; const names = ts.isVariableStatement(st) ? st.declarationList.declarations.map((d) => d.name.getText(sf)) : [st.name.text]; for (const name of names) { const doc = jsdoc(st, sf); if (kind === "function" || kind === "component") { const prev = byName.get(name); if (prev) { prev.decls.push(st); prev.doc ??= doc; continue; } } const item = { name, kind, exported: hasExport(st), decls: [st], doc }; byName.set(name, item); items.push(item); } } return { items, reexports, defaultExport }; } // --------------------------------------------------------------------------------------------- // Package pages const PACKAGES = [ { dir: "packages/nowaki-runtime", pkg: "@nowaki-dev/runtime", base: "runtime" }, { dir: "packages/nowaki-markdoc", pkg: "@nowaki-dev/markdoc", base: "markdoc" }, ]; /// The type-file pages: [{ page, pkg, subpath, specifier, file, sf, decl }]. function typePages(root) { const out = []; for (const p of PACKAGES) { const json = JSON.parse(read(root, `${p.dir}/package.json`)); for (const sub of Object.keys(json.exports).sort()) { if (sub.includes("*")) continue; const file = `${p.dir}/${json.exports[sub].types.replace(/^\.\//, "")}`; const page = sub === "." ? `${p.base}.md` : `${p.base}-${sub.slice(2).replace(/\//g, "-")}.md`; const sf = parse(root, file); out.push({ page, pkg: p.pkg, subpath: sub, specifier: sub === "." ? p.pkg : `${p.pkg}/${sub.slice(2)}`, file, sf, decl: declarations(sf) }); } } return out; } /// name → [{ page, anchor }] for every declaration on the type pages (exported ones first). function symbolTable(pages) { const symbols = new Map(); for (const p of pages) { const used = new Map(); for (const item of p.decl.items) { let a = slug(item.name); const n = used.get(a) ?? 0; used.set(a, n + 1); if (n) a = `${a}-${n}`; item.anchor = a; if (!symbols.has(item.name)) symbols.set(item.name, []); symbols.get(item.name).push({ page: p.page, anchor: a, exported: item.exported }); } } for (const list of symbols.values()) list.sort((x, y) => Number(y.exported) - Number(x.exported)); return symbols; } /// A link resolver for `page`: a name on the same page wins, then an exported one elsewhere. function linker(symbols, page) { const target = (name) => { const list = symbols.get(name); if (!list) return null; const t = list.find((x) => x.page === page) ?? list.find((x) => x.exported) ?? list[0]; return t.page === page ? `#${t.anchor}` : `${t.page}#${t.anchor}`; }; const link = (name, label) => { const base = name.split(".")[0]; const t = target(base); return t ? `[${code(label || name)}](${t})` : code(label || name); }; link.target = target; return link; } /// The printer writes a tuple type over several lines ("[\n a: A\n]") and an empty body as /// "{\n}"; keep those on one line. const tightTuples = (s) => s.replace(/\{\n\}/g, "{}").replace(/\[\n\s*\]/g, "[]").replace(/\[\n\s*([^[\]\n]*)\n\s*\]/g, "[$1]"); function printDecl(item, sf) { return item.decls.map((d) => tightTuples(printer.printNode(ts.EmitHint.Unspecified, d, sf).trim())).join("\n"); } function renderTypePage(p, symbols, usedBy) { const link = linker(symbols, p.page); const { items, reexports, defaultExport } = p.decl; const exported = items.filter((i) => i.exported); const local = items.filter((i) => !i.exported); const out = [ NOTICE(`\`${p.file}\``), "", `# ${p.specifier}`, "", `${GENERATED} Source: [\`${p.file}\`](../../${p.file}). All of it is covered by semver ([STABILITY.md](../STABILITY.md)).`, "", ]; const head = p.sf.statements.length ? ts.getLeadingCommentRanges(p.sf.text, 0) : null; const fileComment = head?.find((c) => p.sf.text.startsWith("//", c.pos)); if (fileComment) { const lines = []; for (const c of head) if (p.sf.text.startsWith("//", c.pos)) lines.push(p.sf.text.slice(c.pos + 2, c.end).trim()); out.push(inline(lines.join(" "), link), ""); } if (exported.length || reexports.length) { const rows = exported.map((i) => [`[${code(i.name)}](#${i.anchor})`, KIND_LABEL[i.kind], inline(summary(i.doc), link)]); for (const r of reexports) rows.push([link(r.name), r.type ? "Type (re-export)" : "Re-export", `Re-exported from \`${r.from}\`.`]); if (defaultExport) rows.push(["`default`", "Default export", `The same as ${link(defaultExport)}.`]); out.push("## Exports", "", table(["Name", "Kind", "Summary"], rows), ""); } const section = (item) => { const valueLike = ["function", "component", "class", "const"].includes(item.kind); const lines = [`### ${item.name}`, ""]; const dep = deprecatedMarkdown(item.doc, link); if (dep) lines.push(dep, ""); lines.push( item.exported ? `${KIND_LABEL[item.kind]}. \`import ${valueLike ? "" : "type "}{ ${item.name} } from "${p.specifier}";\`` : `${KIND_LABEL[item.kind]}, not exported: listed because exported declarations use it.`, "", ); lines.push("```ts", printDecl(item, p.sf), "```", ""); if (item.doc?.lines.length) lines.push(docMarkdown(item.doc.lines, link), ""); const st = item.decls[0]; let members = []; if (ts.isInterfaceDeclaration(st) || ts.isClassDeclaration(st)) members = membersOf(p.sf, st.members); else if (ts.isTypeAliasDeclaration(st)) members = nestedMembers(p.sf, st.type, ""); if (members.length) { lines.push(ts.isTypeAliasDeclaration(st) ? "Documented members:" : "Members:", ""); for (const m of members) { const ref = !m.doc && m.node.type && ts.isTypeReferenceNode(m.node.type) && ts.isIdentifier(m.node.type.typeName) ? m.node.type.typeName.text : null; const body = m.doc?.lines.length ? docMarkdown(m.doc.lines, link) : ref && link.target(ref) ? `See ${link(ref)}.` : ""; const dep2 = deprecatedMarkdown(m.doc, link); const tags = tagsMarkdown(m.doc, link); const text = [dep2, body, tags].filter(Boolean).join("\n\n"); const indented = text.split("\n").map((l, i) => (i === 0 || !l ? l : ` ${l}`)).join("\n"); lines.push(`- ${code(m.name)}${text ? `: ${indented}` : ""}`); } lines.push(""); } const tags = tagsMarkdown(item.doc, link); if (tags) lines.push(tags, ""); const uses = item.decls.flatMap((d) => typeRefs(d)).filter((n, i, a) => n !== item.name && a.indexOf(n) === i && link.target(n)); if (uses.length) lines.push(`Uses: ${uses.map((n) => link(n)).join(", ")}.`, ""); const users = (usedBy.get(item.name) ?? []).filter((u) => !(u.page === p.page && u.name === item.name)); if (users.length) lines.push(`Used by: ${users.map((u) => `[${code(u.name)}](${u.page === p.page ? "" : u.page}#${u.anchor})`).join(", ")}.`, ""); return lines.join("\n"); }; if (exported.length) out.push("## Declarations", "", ...exported.map(section)); if (local.length) out.push("## Local types", "", "Not exported. They appear in the signatures above.", "", ...local.map(section)); if (reexports.length) { out.push("## Re-exports", ""); for (const r of reexports) out.push(`- ${link(r.name)} from \`${r.from}\``); out.push(""); } return out.join("\n"); } /// name → [{ page, name, anchor }] of the declarations that refer to it. function usedByTable(pages, symbols) { const used = new Map(); for (const p of pages) { for (const item of p.decl.items) { for (const ref of new Set(item.decls.flatMap((d) => typeRefs(d)))) { if (ref === item.name || !symbols.has(ref)) continue; if (!used.has(ref)) used.set(ref, []); used.get(ref).push({ page: p.page, name: item.name, anchor: item.anchor }); } } } return used; } // --------------------------------------------------------------------------------------------- // Route exports const MODULES = ["PageModule", "LayoutModule", "ApiModule", "MiddlewareModule", "IslandModule"]; const METHODS = ["GET", "POST", "PUT", "PATCH", "DELETE", "HEAD", "OPTIONS"]; function renderRouteExports(root, pages, symbols) { const index = pages.find((p) => p.page === "runtime.md"); const link = linker(symbols, "route-exports.md"); const entries = snapshot(root, "route-exports.txt").filter((e) => e.status === "stable"); const names = new Set(entries.map((e) => e.text.split(": ")[0])); const memberNames = new Set(); const out = [ NOTICE("the route module types in `packages/nowaki-runtime/index.d.ts` and `api/route-exports.txt`"), "", "# Route and island module exports", "", `${GENERATED} What a route or island module may export, with the types \`@nowaki-dev/runtime\` gives them. File names and directories are in [file-conventions.md](file-conventions.md).`, "", "Check a module against its type with `satisfies` (see [PageModule](runtime.md#pagemodule)).", "", ]; for (const name of MODULES) { const item = index.decl.items.find((i) => i.name === name); if (!item) fail(`index.d.ts: ${name} not found`); const members = membersOf(index.sf, item.decls[0].members); out.push(`## ${name}`, "", inline(summary(item.doc), link), "", `Declared in [runtime.md](runtime.md#${item.anchor}).`, ""); const rows = members.map((m) => { memberNames.add(m.name); const type = m.node.type ? printer.printNode(ts.EmitHint.Unspecified, m.node.type, index.sf) : ""; const refs = m.node.type ? typeRefs(m.node.type).filter((n) => link.target(n)) : []; const text = m.doc ? summary(m.doc) : refs.length ? summary(pages.flatMap((p) => p.decl.items).find((i) => i.name === refs[0])?.doc) : ""; return [code(m.name) + (m.node.questionToken ? "" : " (required)"), code(type), inline(text, link) + (refs.length ? ` See ${refs.map((r) => link(r)).join(", ")}.` : "")]; }); out.push(table(["Export", "Type", "Description"], rows), ""); } // Every stable route export is a member of a module type, and the reverse. for (const n of names) { if (n === "" || n.startsWith("client:")) continue; if (!memberNames.has(n)) fail(`api/route-exports.txt lists ${n}, which no module type (${MODULES.join(", ")}) has`); } for (const n of memberNames) { if (METHODS.includes(n)) continue; if (!names.has(n)) fail(`a module type has ${n}, which api/route-exports.txt doesn't list as stable`); } out.push( "## Where each export applies", "", "From `api/route-exports.txt`, the exports the runtime reads. `` stands for the request-method exports of API and file routes. The `client:*` directives go on island elements, not in a module: see [client-events.md](client-events.md#island-directives).", "", table( ["Export", "Type and modules"], entries.map((e) => { const [n, ...rest] = e.text.split(": "); return [code(n), inline(rest.join(": ").replace(/\b([A-Z]\w+)\b/g, (w) => (link.target(w) ? `{@link ${w}}` : w)), link)]; }), ), "", ); const removed = snapshot(root, "route-exports.txt").filter((e) => e.status === "ignored"); if (removed.length) { out.push("Not route exports any more (the runtime refuses them with an error):", ""); for (const e of removed) out.push(`- ${code(e.text.split(": ")[0])}: ${e.text.split(": ").slice(1).join(": ")}`); out.push(""); } return out.join("\n"); } // --------------------------------------------------------------------------------------------- // File conventions function renderFiles(root) { const entries = snapshot(root, "files.txt").filter((e) => e.status === "stable"); described(FILES, entries.map((e) => e.text), "file convention"); const out = [ NOTICE("`api/files.txt` and `scripts/gen-reference-data.mjs`"), "", "# File conventions", "", `${GENERATED} The files and names Nowaki gives a meaning to, from \`api/files.txt\` (each line there is read from the code that implements it). Paths are relative to the app root.`, "", ]; const titles = { routes: "Routes (`routes/`)", app: "App files" }; for (const title of [...new Set(entries.map((e) => e.title))]) { out.push(`## ${titles[title] ?? title}`, ""); out.push(table(["Convention", "Meaning"], entries.filter((e) => e.title === title).map((e) => [code(e.text), FILES[e.text]])), ""); } out.push("Route module exports: [route-exports.md](route-exports.md). Config file keys: [config.md](config.md).", ""); return out.join("\n"); } // --------------------------------------------------------------------------------------------- // nowaki.config // "label: keys" where the label may hold "(provider: ...)". const NESTED = /^((?:[^:(]|\([^)]*\))+):\s(.*)$/; function renderConfig(root, pages, symbols) { const cfg = pages.find((p) => p.page === "runtime-config.md"); const link = linker(symbols, "config.md"); const entries = snapshot(root, "config.txt"); const top = entries.filter((e) => e.title === "top-level").map((e) => e.text); const nested = entries.filter((e) => e.title === "nested").map((e) => e.text); const hooks = entries.filter((e) => e.title === "plugins").map((e) => e.text); const files = entries.filter((e) => e.title === "files" && !e.text.startsWith("export ")); const item = cfg.decl.items.find((i) => i.name === "NowakiConfig"); const members = membersOf(cfg.sf, item.decls[0].members).filter((m) => !m.name.includes(".")); const memberNames = members.map((m) => m.name); const diff = (a, b) => a.filter((x) => !b.includes(x)); if (diff(top, memberNames).length || diff(memberNames, top).length) { fail(`api/config.txt top-level keys (${top.join(", ")}) and NowakiConfig members (${memberNames.join(", ")}) differ`); } const plugin = cfg.decl.items.find((i) => i.name === "NowakiPlugin"); const pluginMembers = membersOf(cfg.sf, plugin.decls[0].members).map((m) => m.name); if (diff(hooks, pluginMembers).length || diff(pluginMembers, hooks).length) { fail(`api/config.txt plugin hooks (${hooks.join(", ")}) and NowakiPlugin members (${pluginMembers.join(", ")}) differ`); } // Every nested key the validator accepts is a property somewhere in config.d.ts. const props = new Set(); const visit = (n) => { if ((ts.isPropertySignature(n) || ts.isMethodSignature(n)) && n.name) props.add(n.name.getText(cfg.sf)); ts.forEachChild(n, visit); }; visit(cfg.sf); for (const line of nested) { const [, label, keys] = line.match(NESTED); if (label === "trailingSlash") continue; for (const k of keys.split(", ")) if (!props.has(k)) fail(`api/config.txt: ${label} key ${k} has no property in config.d.ts`); } const out = [ NOTICE("`packages/nowaki-runtime/config.d.ts` and `api/config.txt`"), "", "# nowaki.config", "", `${GENERATED} The app's configuration file, read by \`nowaki dev\` and \`nowaki build\`.`, "", `File: ${files.map((f) => code(f.text)).join(" or ")} in the app root (the first one found), with the config as its default export.`, "", "```js", "// nowaki.config.mjs", 'import { defineConfig } from "@nowaki-dev/runtime/config";', "", 'export default defineConfig({ site: "https://example.com" });', "```", "", "An unknown key is an error at every level, with a \"did you mean\" hint. Types: [runtime-config.md](runtime-config.md).", "", "## Keys", "", table( ["Key", "Type", "Description"], members.map((m) => [ `[${code(m.name)}](#${slug(m.name)})`, code(printer.printNode(ts.EmitHint.Unspecified, m.node.type, cfg.sf)), inline(summary(m.doc), link), ]), ), "", ]; for (const m of members) { out.push(`### ${m.name}`, "", "```ts", `${m.name}?: ${printer.printNode(ts.EmitHint.Unspecified, m.node.type, cfg.sf)}`, "```", ""); if (m.doc) out.push(docMarkdown(m.doc.lines, link), ""); const keys = nested.filter((n) => n.split(/[:[. ]/)[0] === m.name); if (keys.length) { out.push(m.name === "trailingSlash" ? "Accepted values (from the validator):" : "Accepted keys (from the validator):", ""); for (const k of keys) { const [, label, rest] = k.match(NESTED); out.push(`- ${code(label)}: ${rest.split(/, | \| /).map(code).join(k.includes(" | ") ? " \\| " : ", ")}`); } out.push(""); } const refs = typeRefs(m.node.type).filter((n) => link.target(n)); if (refs.length) out.push(`See ${refs.map((r) => link(r)).join(", ")}.`, ""); } out.push("## Plugin hooks", "", `A plugin is an object with ${hooks.map(code).join(", ")}: see ${link("NowakiPlugin")}.`, ""); return out.join("\n"); } // --------------------------------------------------------------------------------------------- // CLI function renderCli(root) { const entries = snapshot(root, "cli.txt"); const create = snapshot(root, "create-nowaki.txt"); const out = [ NOTICE("`api/cli.txt` (clap) and `api/create-nowaki.txt`"), "", "# CLI", "", `${GENERATED} The \`nowaki\` commands and flags, from the clap definitions in \`crates/nowaki/src/main.rs\` (through \`api/cli.txt\`). The text of the CLI's output, including the build report, is not covered by semver; the exit code of a failed build is.`, "", ]; const commands = entries.filter((e) => e.title === "nowaki" && e.text.startsWith("command ")); out.push( "## nowaki", "", table( ["Command", "Description"], commands.map((c) => { const name = c.text.slice(8); return [name === "help" ? "`nowaki help`" : `[\`nowaki ${name}\`](#nowaki-${name})`, c.comment]; }), ), "", table(["Flag", "Description"], entries.filter((e) => e.title === "nowaki" && !e.text.startsWith("command ")).map((e) => [code(e.text), e.comment])), "", ); for (const title of [...new Set(entries.map((e) => e.title))].filter((t) => t !== "nowaki")) { const cmd = commands.find((c) => `nowaki ${c.text.slice(8)}` === title); out.push(`## ${title}`, "", cmd ? `${cmd.comment}.` : "", ""); const rows = entries .filter((e) => e.title === title) .map((e) => { const def = e.text.match(/ default=(\S+)/)?.[1]; const values = e.text.match(/ values=(\S+)/)?.[1]; const arg = e.text.replace(/ default=\S+/, "").replace(/ values=\S+/, ""); return [code(arg), def && def !== "false" ? code(def) : "", e.comment + (values ? ` Values: ${values.split("|").map(code).join(", ")}.` : "")]; }); out.push(table(["Argument or flag", "Default", "Description"], rows), ""); } out.push("The environment variables the servers read are in [env-vars.md](env-vars.md).", ""); const flags = create.filter((e) => e.title === "flags").map((e) => e.text); described(CREATE_FLAGS, flags, "create-nowaki flag"); const templatesSrc = read(root, "packages/create-nowaki/index.js"); const hints = new Map([...templatesSrc.matchAll(/\{ value: "(\w+)", hint: "([^"]+)" \}/g)].map((m) => [m[1], m[2]])); const templates = create.filter((e) => e.title === "templates").map((e) => e.text); for (const t of templates) if (!hints.has(t)) fail(`packages/create-nowaki/index.js: no hint for template ${t}`); out.push( "## create-nowaki", "", "`npm create nowaki@latest [dir] [flags]` (also `create-nowaki-app`) scaffolds an app. On a terminal it asks for what the flags don't say; without one (CI, a pipe, `-y`) it uses the defaults.", "", table(["Argument or flag", "Description"], flags.map((f) => [code(f), CREATE_FLAGS[f]])), "", table(["Template", "Description"], templates.map((t) => [code(t), hints.get(t)])), "", ); return out.join("\n"); } // --------------------------------------------------------------------------------------------- // Environment variables function renderEnv(root) { const entries = snapshot(root, "env.txt"); const covered = entries.filter((e) => e.status === "stable" || e.status === "dev"); described(ENV, covered.map((e) => e.text), "environment variable"); for (const e of covered) { const want = e.status === "dev" ? "dev" : null; const g = ENV[e.text].group; if ((g === "dev") !== (want === "dev")) fail(`env var ${e.text} is [${e.status}] in api/env.txt but in group "${g}" in scripts/gen-reference-data.mjs`); if (!ENV_GROUPS.some(([id]) => id === g)) fail(`env var ${e.text}: unknown group ${g}`); } const out = [ NOTICE("`api/env.txt` and `scripts/gen-reference-data.mjs`"), "", "# Environment variables", "", `${GENERATED} The variables Nowaki reads, from \`api/env.txt\` (a scan of the code). Everything above the last section is covered by semver ([STABILITY.md](../STABILITY.md)). Variables the app declares itself go in \`env.ts\` ([runtime-env.md](runtime-env.md)).`, "", "The `nowaki` CLI also takes `NOWAKI_*` variables from the app's `.env` / `.env.local` files (a variable set in the environment wins), except `NOWAKI_HOST`: the listen address (`PORT`, `NOWAKI_HOST`) comes only from the environment or the flags.", "", ]; for (const [id, title] of ENV_GROUPS) { const vars = covered.filter((e) => ENV[e.text].group === id); if (!vars.length) continue; out.push(`## ${title}`, "", table(["Variable", "Default", "Description"], vars.map((e) => [code(e.text), ENV[e.text].default, ENV[e.text].text])), ""); } const internal = entries.filter((e) => e.status === "internal").map((e) => code(e.text)); const external = entries.filter((e) => e.status === "external").map((e) => code(e.text)); out.push( "## Not for apps", "", `Internal (set by Nowaki for its own processes; may change in any release): ${internal.join(", ")}.`, "", `Standard variables Nowaki also reads: ${external.join(", ")}.`, "", ); return out.join("\n"); } // --------------------------------------------------------------------------------------------- // Endpoints, headers, cookies function stableHttp(root) { const entries = snapshot(root, "http.txt"); const stable = entries.filter((e) => e.status === "stable").map((e) => ({ ...e, name: e.text.split(" ")[0] })); described(HTTP, stable.map((e) => e.name), "HTTP name"); return { entries, stable }; } function renderEndpoints(root) { const { entries, stable } = stableHttp(root); const out = [ NOTICE("`api/http.txt` and `scripts/gen-reference-data.mjs`"), "", "# Endpoints", "", `${GENERATED} The paths Nowaki answers itself, from \`api/http.txt\` (a scan of the code).`, "", ]; for (const e of stable.filter((x) => x.name.startsWith("/__nowaki/"))) { const method = e.text.match(/\((GET|POST)/)?.[1]; out.push(`## ${method ? `${method} ` : ""}${e.name}`, "", HTTP[e.name], ""); } out.push( "## Reserved paths", "", "- `/__nowaki/`: every path under it belongs to Nowaki; don't put routes there.", ...stable.filter((x) => x.name === "/_nowaki/").map((x) => `- \`/_nowaki/\`: ${HTTP[x.name]}`), "", "## Not covered", "", "These exist and may change in any release (wire protocols that only need to match within one build, and dev-only tools):", "", `- Internal: ${entries.filter((x) => x.status === "internal" && x.text.startsWith("/")).map((x) => code(x.text)).join(", ")}.`, `- Dev server only: ${entries.filter((x) => x.status === "dev").map((x) => code(x.text)).join(", ")}.`, "", "Headers and cookies: [headers.md](headers.md).", "", ); return out.join("\n"); } function renderHeaders(root) { const { entries, stable } = stableHttp(root); const sec = read(root, "crates/nowaki/src/security_headers.rs"); const defaults = [...(sec.match(/pub const DEFAULTS: \[\(&str, &str\); \d+\] = \[([\s\S]*?)\];/)?.[1] ?? "").matchAll(/\("([^"]+)", "([^"]+)"\)/g)].map((m) => [m[1], m[2]]); const frame = sec.match(/pub const FRAME_CSP: &str = "([^"]+)";/)?.[1]; if (!defaults.length || !frame) fail("crates/nowaki/src/security_headers.rs: DEFAULTS / FRAME_CSP not found; update scripts/gen-reference.mjs"); const mjs = read(root, "packages/nowaki-runtime/server/security-headers.mjs").toLowerCase(); for (const [k, v] of defaults) if (!mjs.includes(k) || !mjs.includes(v.toLowerCase())) fail(`security-headers.mjs doesn't set ${k}: ${v} like security_headers.rs`); const csp = read(root, "crates/nowaki/src/csp.rs").match(/let mut p = format!\(\s*"([\s\S]*?)"\s*\);/)?.[1]; if (!csp) fail("crates/nowaki/src/csp.rs: the policy format string not found; update scripts/gen-reference.mjs"); const policy = csp.replace(/\\\n/g, "").replace(/\{nonce\}/g, ""); const cookies = stable.filter((e) => /\(cookie/.test(e.text)); const headers = stable.filter((e) => e.name.startsWith("x-")); const out = [ NOTICE("`api/http.txt`, `crates/nowaki/src/security_headers.rs`, `crates/nowaki/src/csp.rs` and `scripts/gen-reference-data.mjs`"), "", "# Headers and cookies", "", `${GENERATED}`, "", "## Default security headers", "", "`nowaki dev`, `nowaki start` and the adapter outputs add these to every response that doesn't set them already (ISR hits and static files included). `NOWAKI_SECURITY_HEADERS=off` removes them all. A `headers` rule in nowaki.config with the same name replaces one.", "", table(["Header", "Value"], [...defaults.map(([k, v]) => [code(k), code(v)]), [code("content-security-policy"), `${code(frame)}, only when the response has no CSP (neither the app's nor \`NOWAKI_CSP\`'s)`]]), "", "## Content Security Policy", "", "Off by default. `NOWAKI_CSP=report-only` sends `Content-Security-Policy-Report-Only`, `NOWAKI_CSP=enforce` sends `Content-Security-Policy`, with this policy (`` is new for every response; `NOWAKI_CSP_REPORT_URI` appends `; report-uri `):", "", "```text", ...policy.split("; ").map((d, i, a) => d + (i < a.length - 1 ? ";" : "")), "```", "", "The nonce goes on the scripts and styles Nowaki emits and on tags that carry `nonce()` ([runtime.md](runtime.md#nonce)); inline scripts and styles that reach the page as raw HTML get none. A response that sets its own CSP is left alone. Static output (`nowaki prerender`) has no per-response nonce.", "", "## Cache headers", "", "- An ISR page (`export const revalidate = n`) sends `Cache-Control: public, s-maxage=, stale-while-revalidate`, with `Vary` naming the request headers the render read. A render that read cookies or `Authorization` sends `Cache-Control: private, no-cache` instead.", "- A response that sets a cookie never gets a shared `Cache-Control`: `public` / `s-maxage` become `private, no-cache`.", "- `GET /__nowaki/health` sends `Cache-Control: no-store`.", "", "## Response headers", "", table(["Header", "Description"], headers.map((e) => [code(e.name), HTTP[e.name]])), "", "## Cookies", "", table(["Cookie", "Description"], cookies.map((e) => [code(e.name), HTTP[e.name]])), "", "## Not covered", "", `The other \`x-nowaki-*\` headers (the ones the client runtime sends, and the ones Nowaki's processes use among themselves) may change in any release: ${entries.filter((x) => x.status === "internal" && x.text.startsWith("x-")).map((x) => code(x.text)).join(", ")}.`, "", ]; return out.join("\n"); } // --------------------------------------------------------------------------------------------- // Client events, attributes, island directives function renderClient(root) { const entries = snapshot(root, "client.txt"); const stable = entries.filter((e) => e.status === "stable").map((e) => e.text); described(CLIENT, stable, "client name"); const jsxFile = "packages/create-nowaki/templates/_shared/nowaki-jsx.d.ts"; const sf = parse(root, jsxFile); const directives = []; const visit = (n) => { if (ts.isPropertySignature(n) && ts.isStringLiteral(n.name) && n.name.text.startsWith("client:")) directives.push({ name: n.name.text, type: n.type.getText(sf), doc: jsdoc(n, sf) }); ts.forEachChild(n, visit); }; visit(sf); const routeDirectives = snapshot(root, "route-exports.txt").filter((e) => e.status === "stable" && e.text.startsWith("client:")).map((e) => e.text.split(": ")[0]); const jsxNames = directives.map((d) => d.name); if (routeDirectives.sort().join() !== [...jsxNames].sort().join()) fail(`client:* directives differ: api/route-exports.txt has ${routeDirectives.join(", ")}, ${jsxFile} has ${jsxNames.join(", ")}`); const noLink = (n) => code(n); const events = stable.filter((n) => n.startsWith("nowaki:")); const attrs = stable.filter((n) => n.startsWith("data-")); const metas = stable.filter((n) => n.startsWith("meta[")); const out = [ NOTICE("`api/client.txt`, `packages/create-nowaki/templates/_shared/nowaki-jsx.d.ts` and `scripts/gen-reference-data.mjs`"), "", "# Client events and attributes", "", `${GENERATED} The DOM events Nowaki's client code dispatches and the attributes it reads, from \`api/client.txt\` (a scan of \`packages/nowaki-runtime/client\`).`, "", "## Island directives", "", `Put one on an island element in a page or layout to choose when it hydrates. Typed for JSX by the scaffold's \`nowaki-jsx.d.ts\`.`, "", table(["Directive", "Type", "Description"], directives.map((d) => [code(d.name), code(d.type), d.doc ? docMarkdown(d.doc.lines, noLink).replace(/\n/g, " ") : ""])), "", "## Events", "", table(["Event", "Description"], events.map((n) => [code(n), CLIENT[n]])), "", "## Attributes", "", table(["Attribute", "Description"], attrs.map((n) => [code(n), CLIENT[n]])), "", "## Meta tags", "", "Read from the page's `` (put them in `head` or `meta().head`).", "", table(["Tag", "Description"], metas.map((n) => [code(n), CLIENT[n]])), "", "Slot elements: a layout's `slots.` renders inside `\">` (`display: contents`); the `name` attribute is stable, for styling. See [LayoutProps](runtime.md#layoutprops).", "", "## Not covered", "", `Dev-only events: ${entries.filter((e) => e.status === "dev").map((e) => code(e.text)).join(", ")}. Internal attributes of generated markup: ${entries.filter((e) => e.status === "internal").map((e) => code(e.text)).join(", ")}. The \`\` / \`\` elements and \`window.__nowaki*\` globals are internal too.`, "", ]; return out.join("\n"); } // --------------------------------------------------------------------------------------------- // Index function renderIndex(root, pages) { // Docs written by hand. Listed as a plain path until the page exists (set `link` when it lands), // so this page doesn't change, and CI doesn't fail elsewhere, when another PR adds one. const other = (p, what, link) => { if (link && !existsSync(path.join(root, p))) fail(`${p} is linked from the index but doesn't exist`); return link ? `- [${what}](../${p.replace(/^docs\//, "")})` : `- ${what}: \`${p}\``; }; const out = [ NOTICE("the sources listed on each page"), "", "# Nowaki reference", "", `${GENERATED} Every page here is written by \`node scripts/gen-reference.mjs\` from the type declarations, the \`api/\` snapshots and the code, and CI fails when they are out of date. To change a page, change its source (usually a \`.d.ts\` doc comment or \`scripts/gen-reference-data.mjs\`) and regenerate: see [CONTRIBUTING.md](../../CONTRIBUTING.md#api-reference).`, "", "What is covered by semver, and what is not: [STABILITY.md](../STABILITY.md). The exact list of stable names: [`api/`](../../api/README.md).", "", "## Packages", "", table( ["Import", "Page", "Exports"], pages.map((p) => [code(p.specifier), `[${p.page}](${p.page})`, [...p.decl.items.filter((i) => i.exported).map((i) => i.name), ...p.decl.reexports.map((r) => r.name)].map(code).join(", ")]), ), "", "## App surface", "", "- [Route and island module exports](route-exports.md): `PageModule`, `LayoutModule`, `ApiModule`, `MiddlewareModule`, `IslandModule`", "- [File conventions](file-conventions.md): `routes/`, `islands/`, `content/`, `public/`, `env.ts`, `session.ts`, `nowaki.config.mjs`", "- [nowaki.config](config.md): every key", "- [CLI](cli.md): `nowaki` commands and flags, `create-nowaki`", "- [Environment variables](env-vars.md)", "- [Endpoints](endpoints.md): `/__nowaki/health`, `/__nowaki/revalidate`, reserved paths", "- [Headers and cookies](headers.md): security headers, CSP, cache headers, `x-nowaki-cache`, cookies", "- [Client events and attributes](client-events.md): `client:*` directives, `nowaki:*` events, `data-live*`, `data-nowaki-*`", "", "## Other docs", "", other("docs/README.md", "Guides, one per feature (index)", true), other("docs/deploy/README.md", "Deployment, one page per adapter", true), other("docs/troubleshooting.md", "Troubleshooting", true), other("docs/upgrade-to-1.0.md", "Upgrading to 1.0", true), other("docs/migrate-from-nextjs.md", "Migrating from Next.js", true), other("docs/migrate-from-astro.md", "Migrating from Astro", true), other("docs/STABILITY.md", "Stability and versioning", true), "", ]; return out.join("\n"); } // --------------------------------------------------------------------------------------------- // Links: every relative link on a generated page must point at a file that exists and, with a // fragment, at a heading of a generated page. function checkLinks(root, files) { const anchors = new Map(); for (const [name, text] of files) { const set = new Set(); const count = new Map(); let fence = false; for (const l of text.split("\n")) { if (l.startsWith("```")) fence = !fence; const h = !fence && l.match(/^#{1,6} (.+)$/); if (!h) continue; const s = slug(h[1]); const n = count.get(s) ?? 0; count.set(s, n + 1); set.add(n ? `${s}-${n}` : s); } anchors.set(name, set); } const bad = []; for (const [name, text] of files) { const body = text.replace(/```[\s\S]*?```/g, "").replace(/`[^`\n]*`/g, ""); for (const m of body.matchAll(/\]\(([^)\s]+)\)/g)) { const href = m[1]; if (/^[a-z]+:/.test(href)) continue; const [file, frag] = href.split("#"); const target = file ? path.posix.normalize(path.posix.join(OUT_DIR, file)) : `${OUT_DIR}/${name}`; const local = target.startsWith(`${OUT_DIR}/`) ? target.slice(OUT_DIR.length + 1) : null; if (local && files.has(local)) { if (frag && !anchors.get(local).has(frag)) bad.push(`${name}: ${href} (no such heading)`); } else if (!existsSync(path.join(root, target))) bad.push(`${name}: ${href} (no such file)`); } } if (bad.length) fail(`broken links:\n ${bad.join("\n ")}`); } // --------------------------------------------------------------------------------------------- /// Every page: Map file name → text. export function generate(root = REPO) { const pages = typePages(root); const symbols = symbolTable(pages); const usedBy = usedByTable(pages, symbols); const files = new Map(); files.set("README.md", renderIndex(root, pages)); for (const p of pages) files.set(p.page, renderTypePage(p, symbols, usedBy)); files.set("route-exports.md", renderRouteExports(root, pages, symbols)); files.set("file-conventions.md", renderFiles(root)); files.set("config.md", renderConfig(root, pages, symbols)); files.set("cli.md", renderCli(root)); files.set("env-vars.md", renderEnv(root)); files.set("endpoints.md", renderEndpoints(root)); files.set("headers.md", renderHeaders(root)); files.set("client-events.md", renderClient(root)); for (const [k, v] of files) files.set(k, v.replace(/\n{3,}/g, "\n\n").trimEnd() + "\n"); checkLinks(root, files); return new Map([...files].sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0))); } function main(argv) { const check = argv.includes("--check"); const dir = path.join(REPO, OUT_DIR); const files = generate(REPO); const present = existsSync(dir) ? readdirSync(dir).filter((f) => f.endsWith(".md")).sort() : []; const stale = []; for (const [name, text] of files) { const p = path.join(dir, name); const current = existsSync(p) ? normalize(readFileSync(p, "utf8")) : null; if (current !== text) stale.push(name); } const extra = present.filter((f) => !files.has(f)); if (check) { if (stale.length || extra.length) { if (stale.length) console.error(`gen-reference: out of date: ${stale.map((f) => `${OUT_DIR}/${f}`).join(", ")}`); if (extra.length) console.error(`gen-reference: not generated (remove them): ${extra.map((f) => `${OUT_DIR}/${f}`).join(", ")}`); console.error("Run `node scripts/gen-reference.mjs` and commit the result (CONTRIBUTING.md > API reference)."); process.exit(1); } console.log(`gen-reference: OK (${files.size} pages up to date)`); return; } mkdirSync(dir, { recursive: true }); for (const name of stale) { writeFileSync(path.join(dir, name), files.get(name)); console.log(`wrote ${OUT_DIR}/${name}`); } for (const name of extra) { unlinkSync(path.join(dir, name)); console.log(`removed ${OUT_DIR}/${name}`); } if (!stale.length && !extra.length) console.log(`gen-reference: ${files.size} pages already up to date`); } const entry = process.argv[1] ? pathToFileURL(path.resolve(process.argv[1])).href : ""; if (import.meta.url === entry) { try { main(process.argv.slice(2)); } catch (e) { console.error(e.message); process.exit(1); } }