|
| 1 | +// checks docs pages for what the dev server and a read of the page both miss. the dev server keeps |
| 2 | +// serving a page's last good render when its markdown breaks, a yaml value that isn't text renders |
| 3 | +// as [object Object], and a name imported in a sample that the package doesn't export looks as |
| 4 | +// plausible as one it does. the page goes through the site's own markdown pass, and its samples' |
| 5 | +// imports are held against the nav-router checkout beside these docs. |
| 6 | +// |
| 7 | +// node scripts/check-page.mjs src/content/docs/api/lazy.md src/content/docs/plugins/*.md |
| 8 | +// |
| 9 | +// exits 1 on an error. a link to a page or a heading that isn't written yet is a warning, since |
| 10 | +// pages are written side by side: once they are all in, a run over every page should print none. |
| 11 | +// it does not run the samples. |
| 12 | +import GithubSlugger from 'github-slugger'; |
| 13 | +import { existsSync, readFileSync } from 'node:fs'; |
| 14 | +import { dirname, relative, resolve } from 'node:path'; |
| 15 | +import { fileURLToPath, pathToFileURL } from 'node:url'; |
| 16 | +import remarkDirective from 'remark-directive'; |
| 17 | +import remarkParse from 'remark-parse'; |
| 18 | +import { unified } from 'unified'; |
| 19 | +import { visit } from 'unist-util-visit'; |
| 20 | +import { parse as parseYaml } from 'yaml'; |
| 21 | + |
| 22 | +import { FRAMEWORKS } from '../src/lib/frameworks.js'; |
| 23 | +import { remarkDocs } from '../src/lib/markdown/remark-docs.js'; |
| 24 | +import { parseMeta } from '../src/lib/markdown/shiki-meta.js'; |
| 25 | + |
| 26 | +const here = dirname(fileURLToPath(import.meta.url)); |
| 27 | +const content = resolve(here, '../src/content'); |
| 28 | +// the repo root above these docs in the monorepo, else the sibling nav-router checkout |
| 29 | +const NAV_ROUTER = [resolve(here, '../..'), resolve(here, '../../../nav-router')] |
| 30 | + .find((dir) => existsSync(resolve(dir, 'src/index.js'))); |
| 31 | + |
| 32 | +const DIRECTIVES = ['note', 'tip', 'warning', 'danger', 'steps', 'entry', 'truth']; |
| 33 | +const KINDS = ['class', 'function', 'plugin']; |
| 34 | +const parser = unified().use(remarkParse).use(remarkDirective); |
| 35 | + |
| 36 | +// what each package a sample may import from exports. the core and the reactive scaffold are |
| 37 | +// loaded, so their names are the real ones; an integration needs its framework to load, so its |
| 38 | +// names are read from its source, with the core's, which it re-exports |
| 39 | +const exportsOf = async (file) => Object.keys(await import(pathToFileURL(resolve(NAV_ROUTER, file)).href)); |
| 40 | +const core = await exportsOf('src/index.js'); |
| 41 | +const declared = (file) => { |
| 42 | + const source = readFileSync(file, 'utf8'); |
| 43 | + const named = [...source.matchAll(/export\s+(?:const|class|function)\s+(\w+)/g)].map((m) => m[1]); |
| 44 | + const listed = [...source.matchAll(/export\s*\{([^}]*)\}/g)] |
| 45 | + .flatMap((m) => m[1].split(',').map((name) => name.trim().split(/\s+as\s+/).pop())); |
| 46 | + return [...named, ...listed].filter(Boolean); |
| 47 | +}; |
| 48 | +async function packageExports(source) { |
| 49 | + if (source === 'nav-router' || source === '@nav-router/core') { return core; } |
| 50 | + if (source === 'nav-router/reactive') { return exportsOf('src/reactive-router.js'); } |
| 51 | + const [, scoped, plugin] = source.match(/^@nav-router\/([\w-]+)(?:\/([\w-]+))?$/) ?? []; |
| 52 | + if (scoped === 'plugins') { |
| 53 | + return existsSync(resolve(NAV_ROUTER, 'packages/plugins/src', `${plugin}.js`)) ? [] : null; |
| 54 | + } |
| 55 | + const integration = scoped && resolve(NAV_ROUTER, 'integrations', scoped, 'index.js'); |
| 56 | + return integration && existsSync(integration) ? [...declared(integration), ...core] : null; |
| 57 | +} |
| 58 | + |
| 59 | +// a heading's id as the site makes it: its text without the kind pill |
| 60 | +const headingText = (node) => |
| 61 | + node.children.map((c) => (c.type === 'textDirective' ? '' : c.value ?? headingText(c))).join('').trim(); |
| 62 | +function anchorsOf(body) { |
| 63 | + const slugger = new GithubSlugger(); |
| 64 | + const anchors = new Set(); |
| 65 | + visit(parser.parse(body), 'heading', (node) => anchors.add(slugger.slug(headingText(node)))); |
| 66 | + return anchors; |
| 67 | +} |
| 68 | +const split = (source) => { |
| 69 | + const [, front = '', body = source] = source.match(/^---\n([\s\S]*?)\n---\n?([\s\S]*)$/) ?? []; |
| 70 | + return { front, body, offset: front ? front.split('\n').length + 2 : 0 }; |
| 71 | +}; |
| 72 | + |
| 73 | +// where a site link lands: a docs page by its file, an example by its folder, or a landing page |
| 74 | +function linkTarget(path) { |
| 75 | + if (['/', '/plugins/', '/examples/'].includes(path)) { return { exists: true }; } |
| 76 | + const example = path.match(/^\/examples\/([\w-]+)\/$/)?.[1]; |
| 77 | + if (example) { return { exists: existsSync(resolve(content, 'examples', example, 'example.md')) }; } |
| 78 | + const file = resolve(content, 'docs', `${path.slice(1, -1)}.md`); |
| 79 | + return existsSync(file) ? { exists: true, file } : { exists: false }; |
| 80 | +} |
| 81 | + |
| 82 | +const isText = (value) => ['string', 'number', 'boolean'].includes(typeof value); |
| 83 | +function checkParam(param, say) { |
| 84 | + if (typeof param?.name !== 'string') { return say('a parameter row needs a name'); } |
| 85 | + for (const key of ['type', 'description', 'default']) { |
| 86 | + if (param[key] != null && !isText(param[key])) { |
| 87 | + say(`${param.name}: ${key} is read as yaml, not text. Quote it: ${key}: '…'`); |
| 88 | + } |
| 89 | + } |
| 90 | + (param.options ?? []).forEach((option) => checkParam(option, say)); |
| 91 | +} |
| 92 | + |
| 93 | +async function check(file) { |
| 94 | + const problems = []; |
| 95 | + const { front, body, offset } = split(readFileSync(file, 'utf8')); |
| 96 | + const report = (level, node, message) => |
| 97 | + problems.push({ level, line: (node?.position?.start.line ?? 1) + offset, message }); |
| 98 | + const error = (node, message) => report('error', node, message); |
| 99 | + |
| 100 | + let data = {}; |
| 101 | + try { |
| 102 | + data = parseYaml(front) ?? {}; |
| 103 | + } |
| 104 | + catch (e) { |
| 105 | + error(null, `frontmatter: ${e.message.split('\n')[0]}`); |
| 106 | + } |
| 107 | + for (const key of ['title', 'lede']) { |
| 108 | + if (typeof data[key] !== 'string') { error(null, `frontmatter: ${key} is missing or not text`); } |
| 109 | + } |
| 110 | + if (Number.isNaN(new Date(data.updated).getTime())) { error(null, 'frontmatter: updated needs a date'); } |
| 111 | + if (data.kind && !KINDS.includes(data.kind)) { error(null, `frontmatter: kind is one of ${KINDS.join(', ')}`); } |
| 112 | + if ( |
| 113 | + data.size && data.size !== 'core' && !existsSync(resolve(NAV_ROUTER, 'packages/plugins/src', `${data.size}.js`)) |
| 114 | + ) { |
| 115 | + error(null, `frontmatter: size "${data.size}" is neither core nor a plugin file`); |
| 116 | + } |
| 117 | + |
| 118 | + const tree = parser.parse(body); |
| 119 | + const own = anchorsOf(body); |
| 120 | + const imports = []; |
| 121 | + visit(tree, (node) => { |
| 122 | + if (node.type === 'containerDirective' && !DIRECTIVES.includes(node.name)) { |
| 123 | + error(node, `:::${node.name} is not a block the site knows (${DIRECTIVES.join(', ')})`); |
| 124 | + } |
| 125 | + if (node.type === 'text' && /(^|\n):::/.test(node.value)) { |
| 126 | + error(node, 'a stray ::: — a block holding another block needs a longer fence (::::entry around :::note)'); |
| 127 | + } |
| 128 | + if (node.type === 'code' && ['params', 'returns'].includes(node.lang)) { |
| 129 | + try { |
| 130 | + const rows = parseYaml(node.value); |
| 131 | + if (node.lang === 'params') { |
| 132 | + Array.isArray(rows) |
| 133 | + ? rows.forEach((row) => checkParam(row, (message) => error(node, message))) |
| 134 | + : error(node, 'a params block is a yaml list, one "- name:" per parameter'); |
| 135 | + } |
| 136 | + else { |
| 137 | + checkParam({ name: 'returns', ...rows }, (message) => error(node, message)); |
| 138 | + } |
| 139 | + } |
| 140 | + catch (e) { |
| 141 | + error(node, `yaml: ${e.message.split('\n')[0]}`); |
| 142 | + } |
| 143 | + } |
| 144 | + else if (node.type === 'code') { |
| 145 | + const meta = parseMeta(node.meta ?? ''); |
| 146 | + if (meta.for) { |
| 147 | + const unknown = meta.for.split(/\s+/).filter((id) => !FRAMEWORKS.some((f) => f.id === id)); |
| 148 | + if (unknown.length) { error(node, `for="${unknown.join(' ')}" is not a framework id`); } |
| 149 | + if (!meta.label) { error(node, 'a fence with for= needs label=, the name on its tab'); } |
| 150 | + } |
| 151 | + for ( |
| 152 | + const [, names = '', source] of node.value.matchAll(/import\s+(?:\{([^}]*)\}\s*from\s+)?['"]([^'"]+)['"]/g) |
| 153 | + ) { |
| 154 | + imports.push({ |
| 155 | + node, |
| 156 | + source, |
| 157 | + names: names.split(',').map((name) => name.trim().split(/\s+as\s+/)[0]).filter(Boolean), |
| 158 | + }); |
| 159 | + } |
| 160 | + } |
| 161 | + if (node.type === 'link' && node.url.startsWith('#') && !own.has(node.url.slice(1))) { |
| 162 | + error(node, `${node.url} is not a heading on this page`); |
| 163 | + } |
| 164 | + if (node.type === 'link' && node.url.startsWith('/')) { |
| 165 | + const [path, hash] = node.url.split('#'); |
| 166 | + const target = linkTarget(path); |
| 167 | + if (!path.endsWith('/')) { error(node, `${node.url}: site links end in a slash before any #anchor`); } |
| 168 | + else if (!target.exists) { report('warning', node, `${node.url} is not written yet`); } |
| 169 | + // another writer may still be adding that heading, so it is a warning until every page is in |
| 170 | + else if (hash && target.file && !anchorsOf(split(readFileSync(target.file, 'utf8')).body).has(hash)) { |
| 171 | + report('warning', node, `${node.url}: that page has no heading with the id "${hash}" yet`); |
| 172 | + } |
| 173 | + } |
| 174 | + }); |
| 175 | + |
| 176 | + for (const { node, source, names } of imports) { |
| 177 | + if (!/^@?nav-router/.test(source)) { continue; } |
| 178 | + const known = await packageExports(source); |
| 179 | + if (!known) { error(node, `"${source}" is not in the nav-router checkout`); } |
| 180 | + names.filter((name) => !known?.includes(name)).forEach((name) => |
| 181 | + known && error(node, `${source} does not export ${name}`) |
| 182 | + ); |
| 183 | + } |
| 184 | + |
| 185 | + // anything else the site's own pass refuses |
| 186 | + try { |
| 187 | + remarkDocs()(tree, {}); |
| 188 | + } |
| 189 | + catch (e) { |
| 190 | + if (!problems.length) { error(null, `the markdown pass threw: ${e.message.split('\n')[0]}`); } |
| 191 | + } |
| 192 | + return problems; |
| 193 | +} |
| 194 | + |
| 195 | +const files = process.argv.slice(2); |
| 196 | +if (!files.length) { |
| 197 | + console.error('usage: node scripts/check-page.mjs <page.md> …'); |
| 198 | + process.exit(2); |
| 199 | +} |
| 200 | +let failed = false; |
| 201 | +for (const file of files) { |
| 202 | + const problems = await check(file); |
| 203 | + const name = relative(process.cwd(), resolve(file)); |
| 204 | + problems.forEach(({ level, line, message }) => console.log(`${name}:${line} ${level}: ${message}`)); |
| 205 | + if (!problems.length) { console.log(`${name} ok`); } |
| 206 | + failed ||= problems.some((p) => p.level === 'error'); |
| 207 | +} |
| 208 | +process.exit(failed ? 1 : 0); |
0 commit comments