Files

253 lines
9.9 KiB
JavaScript
Raw Permalink Normal View History

2026-10-12 16:11:44 -04:00
import ts from 'typescript';
2026-10-12 21:21:20 -04:00
import { readFileSync, writeFileSync } from 'node:fs';
2026-10-12 16:11:44 -04:00
import { dirname, extname, resolve } from 'node:path';
import { fileURLToPath } from 'node:url';
2026-10-12 21:21:20 -04:00
// Fills the generated parts of the SDK docs: the view catalogue (views.json and the published view models)
// and the UI primitive reference in THEMES.md, and every code sample in either file, read from
// packages/sdk/docs-samples where `npm run sdk:check` compiles it. `--check` fails on stale docs.
2026-10-12 16:11:44 -04:00
const root = resolve(dirname(fileURLToPath(import.meta.url)), '..');
const sdk = resolve(root, 'packages/sdk');
2026-10-12 17:51:49 -04:00
const documents = ['README.md', 'THEMES.md'];
2026-10-12 16:11:44 -04:00
const read = (path) => readFileSync(resolve(sdk, path), 'utf8');
const program = ts.createProgram(
['types/index.d.ts', 'types/theme.d.ts', 'types/testing.d.ts'].map((path) => resolve(sdk, path)),
{
strict: true,
noEmit: true,
skipLibCheck: true,
target: ts.ScriptTarget.ES2022,
module: ts.ModuleKind.ESNext,
moduleResolution: ts.ModuleResolutionKind.Bundler,
jsx: ts.JsxEmit.ReactJSX,
types: [],
}
);
const checker = program.getTypeChecker();
2026-10-12 21:26:31 -04:00
function exported(file, name) {
2026-10-12 16:11:44 -04:00
const source = program.getSourceFile(resolve(sdk, file));
const symbol = checker.getExportsOfModule(checker.getSymbolAtLocation(source)).find((entry) => entry.name === name);
if (!symbol) throw new Error(`${file} does not export ${name}.`);
2026-10-12 21:26:31 -04:00
return symbol;
2026-10-12 16:11:44 -04:00
}
2026-10-12 21:26:31 -04:00
/** An interface the SDK declares, with every module augmentation merged in. */
const declared = (file, name) => checker.getDeclaredTypeOfSymbol(exported(file, name));
2026-10-12 16:11:44 -04:00
2026-10-12 21:26:31 -04:00
const properties = (type) => new Map(checker.getPropertiesOfType(type).map((property) => [property.name, property]));
2026-10-12 16:11:44 -04:00
/** The type a property is declared with, as written, or as the checker prints it. */
function typeText(property) {
const declaration = property.valueDeclaration ?? property.declarations?.[0];
if (declaration && ts.isPropertySignature(declaration) && declaration.type) {
return declaration.type.getText().replace(/\s+/g, ' ');
}
2026-10-12 21:26:31 -04:00
return checker.typeToString(checker.getTypeOfSymbol(property));
2026-10-12 16:11:44 -04:00
}
/** The union a type node spells out, following type aliases, so its members keep their written order. */
function unionNode(node) {
if (!node) return null;
if (ts.isUnionTypeNode(node)) return node;
if (!ts.isTypeReferenceNode(node)) return null;
const symbol = checker.getSymbolAtLocation(node.typeName);
const target = symbol && symbol.flags & ts.SymbolFlags.Alias ? checker.getAliasedSymbol(symbol) : symbol;
return unionNode(target?.declarations?.find(ts.isTypeAliasDeclaration)?.type);
}
const optional = (property) => (property.flags & ts.SymbolFlags.Optional ? '?' : '');
const code = (text) => `\`${text.replaceAll('|', '\\|')}\``;
const documentation = (symbol) => ts.displayPartsToString(symbol.getDocumentationComment(checker)).replace(/\s+/g, ' ');
/** The literal values of a property's union type, such as `'sm' | 'md'`, in written order; null for any other type. */
function literals(property) {
const declaration = property.valueDeclaration;
const node = declaration && ts.isPropertySignature(declaration) ? unionNode(declaration.type) : null;
if (node?.types.every((member) => ts.isLiteralTypeNode(member) && ts.isStringLiteral(member.literal))) {
return node.types.map((member) => member.literal.text);
}
const type = checker.getTypeOfSymbol(property);
const members = (type.isUnion() ? type.types : [type]).filter(
(member) => !(member.flags & (ts.TypeFlags.Undefined | ts.TypeFlags.Null))
);
if (members.every((member) => member.flags & ts.TypeFlags.BooleanLiteral)) return 'boolean';
if (members.every((member) => member.isStringLiteral() || member.isNumberLiteral())) {
return members.map((member) => String(member.value));
}
return null;
}
function viewCatalogue() {
const views = JSON.parse(read('views.json'));
const models = properties(declared('types/views/registry.d.ts', 'ViewModels'));
const inputs = properties(declared('types/views/registry.d.ts', 'ViewInputs'));
const model = (name) => {
const property = models.get(name);
if (!property) throw new Error(`views.json names ${name}, which has no published model.`);
return typeText(property);
};
2026-10-12 17:51:49 -04:00
const row = (withEngine) => ([name, view]) => {
2026-10-12 16:11:44 -04:00
const input = inputs.get(name);
const inputText = input
? [...properties(checker.getTypeOfSymbol(input)).values()]
.map((property) => code(`${property.name}${optional(property)}: ${typeText(property)}`))
.join(', ')
: '';
2026-10-12 19:14:14 -04:00
const area = view.areaSlots ? `<br>where it draws an area's navigation: ${view.areaSlots.map(code).join(' ')}` : '';
2026-10-12 16:11:44 -04:00
return [
code(name),
view.context,
code(model(name)),
2026-10-12 21:57:49 -04:00
inputText,
2026-10-12 19:14:14 -04:00
view.slots.map(code).join(' ') + area,
...(withEngine ? [(view.engineSlots ?? []).map(code).join(' ')] : []),
2026-10-12 16:11:44 -04:00
view.fixtures.join(', '),
];
};
2026-10-12 17:51:49 -04:00
const table = (title, entries, withEngine = false) =>
2026-10-12 16:11:44 -04:00
[
`#### ${title}`,
'',
2026-10-12 21:57:49 -04:00
`| View | Context | Model | Inputs | Slots |${withEngine ? ' Engine slots |' : ''} Fixtures |`,
2026-10-12 17:51:49 -04:00
`| --- | --- | --- | --- | --- |${withEngine ? ' --- |' : ''} --- |`,
...entries.map(row(withEngine)).map((cells) => `| ${cells.join(' | ')} |`),
2026-10-12 16:11:44 -04:00
].join('\n');
const all = Object.entries(views);
return [
table(
'Layouts',
all.filter(([, view]) => view.kind === 'layout')
),
table(
'Pages',
2026-10-12 21:26:31 -04:00
all.filter(([, view]) => view.kind === 'page'),
2026-10-12 17:51:49 -04:00
true
2026-10-12 16:11:44 -04:00
),
table(
'Blocks',
all.filter(([, view]) => view.kind === 'block')
),
].join('\n\n');
}
const kebab = (name) => name.replaceAll(/[A-Z]/g, (letter) => `-${letter.toLowerCase()}`);
function primitiveReference() {
const primitives = properties(declared('types/themes/primitives.d.ts', 'UiPrimitives'));
2026-10-12 21:26:31 -04:00
const partLists = properties(checker.getTypeOfSymbol(exported('types/themes/primitives.d.ts', 'UI_PRIMITIVE_PARTS')));
2026-10-12 16:11:44 -04:00
const rows = [...primitives.values()].map((primitive) => {
const shape = properties(checker.getTypeOfSymbol(primitive));
2026-10-12 21:26:31 -04:00
const parts = checker
.getTypeArguments(checker.getTypeOfSymbol(partLists.get(primitive.name)))
.map((part) => part.value);
2026-10-12 16:11:44 -04:00
const state = [...properties(checker.getTypeOfSymbol(shape.get('state'))).values()].map((property) => {
const values = literals(property);
const attribute = code(`data-${kebab(property.name)}`);
return values === 'boolean' || values === null ? attribute : `${attribute}: ${values.join(', ')}`;
});
const notes = [documentation(primitive), documentation(shape.get('state'))].filter(Boolean).join(' ');
return [
primitive.name,
parts.map(code).join(', '),
state.join('; ') || 'none',
shape.has('props') ? 'yes' : 'no',
notes,
];
});
return [
'| Primitive | Parts | State on `root` | Replaceable | Notes |',
'| --- | --- | --- | --- | --- |',
...rows.map((cells) => `| ${cells.join(' | ')} |`),
].join('\n');
}
const languages = { '.tsx': 'tsx', '.ts': 'ts', '.css': 'css', '.json': 'json', '.mjs': 'js', '.js': 'js' };
2026-10-12 16:21:56 -04:00
const marker = /^\s*(?:\/\/|\/\*|\{\/\*)\s*#(?:end)?region\b.*$/;
2026-10-12 16:11:44 -04:00
2026-10-12 16:21:56 -04:00
/** The lines of each `#region name` … `#endregion` block in a file, dedented and joined by a blank line. */
function regions(path, lines, name) {
const blocks = [];
2026-10-12 16:11:44 -04:00
2026-10-12 16:21:56 -04:00
lines.forEach((line, start) => {
if (!new RegExp(`#region ${name}\\b`).test(line)) return;
2026-10-12 16:11:44 -04:00
2026-10-12 16:21:56 -04:00
const end = lines.findIndex((candidate, index) => index > start && /#endregion/.test(candidate));
const block = lines.slice(start + 1, end);
const indent = Math.min(...block.filter((entry) => entry.trim()).map((entry) => /^\s*/.exec(entry)[0].length));
2026-10-12 16:11:44 -04:00
2026-10-12 16:21:56 -04:00
blocks.push(block.map((entry) => entry.slice(indent)).join('\n'));
});
if (!blocks.length) throw new Error(`docs-samples/${path} has no region "${name}".`);
2026-10-12 16:11:44 -04:00
2026-10-12 16:21:56 -04:00
return blocks.join('\n\n').split('\n');
}
/** A sample file, or its regions of one name, without the region markers. */
function sample(reference) {
const [path, region] = reference.split('#');
const lines = read(`docs-samples/${path}`).split('\n');
const body = (region ? regions(path, lines, region) : lines)
2026-10-12 16:11:44 -04:00
.filter((line) => !marker.test(line))
.join('\n')
.trim();
return `\`\`\`${languages[extname(path)] ?? ''}\n${body}\n\`\`\``;
}
function fill(readme) {
2026-10-12 21:21:20 -04:00
const generated = { views: viewCatalogue, primitives: primitiveReference };
2026-10-12 16:11:44 -04:00
const output = readme.replace(
/(<!-- generated:(\w+) -->)[\s\S]*?(<!-- \/generated:\2 -->)/g,
(_, open, name, close) => {
if (!generated[name]) throw new Error(`Unknown generated section "${name}".`);
return `${open}\n${generated[name]()}\n${close}`;
}
);
return output.replace(
/(<!-- sample: (\S+) -->)[\s\S]*?(<!-- \/sample -->)/g,
(_, open, reference, close) => `${open}\n${sample(reference)}\n${close}`
);
}
2026-10-12 17:51:49 -04:00
const stale = documents.filter((document) => {
const path = resolve(sdk, document);
const text = readFileSync(path, 'utf8');
const output = fill(text);
2026-10-12 16:11:44 -04:00
2026-10-12 17:51:49 -04:00
if (output !== text && !process.argv.includes('--check')) {
writeFileSync(path, output);
2026-10-12 16:11:44 -04:00
}
2026-10-12 17:51:49 -04:00
return output !== text;
});
if (stale.length && process.argv.includes('--check')) {
console.error(`${stale.map((document) => `packages/sdk/${document}`).join(' and ')} stale. Run npm run sdk:generate.`);
process.exit(1);
2026-10-12 16:11:44 -04:00
}
2026-10-12 17:51:49 -04:00
console.log(`SDK: docs samples and references ${stale.length ? `regenerated in ${stale.join(', ')}` : 'current'}`);