|
| 1 | +/** |
| 2 | + * Content example type-check gate (#1159, B2.4): TypeScript/TSX fenced code |
| 3 | + * blocks in the authored bilingual guides that import `@openelement/*` must |
| 4 | + * type-check against the real v0.44 framework sources. zh duplicates of an |
| 5 | + * en block are deduped by content. Fails closed with compiler diagnostics. |
| 6 | + * |
| 7 | + * Elision convention: guide snippets are written as consumer-project modules |
| 8 | + * and legitimately omit application context. The harness therefore suppresses |
| 9 | + * only the diagnostics that express that elision — unresolved non-framework |
| 10 | + * module specifiers (TS2307 outside `@openelement/*`; the virtual |
| 11 | + * `@openelement/generated/*` namespace is adapter-generated consumer code), |
| 12 | + * undefined names from elided app code (TS2304), implicit-any (TS7006) and |
| 13 | + * property access on the uninferred loader-data generic (TS2339 on `{}`). |
| 14 | + * Everything on the framework surface — unknown `@openelement` modules or |
| 15 | + * exports, argument/assignability errors against real APIs, syntax and JSX |
| 16 | + * errors — fails the gate. |
| 17 | + */ |
| 18 | +import ts from 'typescript'; |
| 19 | +import { walk } from '@std/fs/walk'; |
| 20 | +import { readPackages } from './lib/package-graph.ts'; |
| 21 | + |
| 22 | +export interface ExampleFailure { |
| 23 | + file: string; |
| 24 | + message: string; |
| 25 | +} |
| 26 | + |
| 27 | +export interface ContentExample { |
| 28 | + /** First source document the block was found in. */ |
| 29 | + file: string; |
| 30 | + index: number; |
| 31 | + lang: string; |
| 32 | + code: string; |
| 33 | +} |
| 34 | + |
| 35 | +const FENCE_PATTERN = /```(ts|tsx)\n([\s\S]*?)```/g; |
| 36 | + |
| 37 | +/** Extract unique ts/tsx fenced blocks that import @openelement packages. */ |
| 38 | +export function extractExamples(file: string, markdown: string): ContentExample[] { |
| 39 | + const examples: ContentExample[] = []; |
| 40 | + for (const match of markdown.matchAll(FENCE_PATTERN)) { |
| 41 | + const code = match[2]; |
| 42 | + if (!code.includes('@openelement/')) continue; |
| 43 | + examples.push({ file, index: examples.length, lang: match[1], code }); |
| 44 | + } |
| 45 | + return examples; |
| 46 | +} |
| 47 | + |
| 48 | +/** Build a paths map resolving workspace @openelement/* specifiers to files. */ |
| 49 | +export async function workspacePaths(): Promise<Record<string, string[]>> { |
| 50 | + const paths: Record<string, string[]> = {}; |
| 51 | + for (const pkg of await readPackages()) { |
| 52 | + const entries = typeof pkg.exports === 'string' |
| 53 | + ? { '.': pkg.exports } |
| 54 | + : (pkg.exports ?? {}) as Record<string, string>; |
| 55 | + for (const [key, target] of Object.entries(entries)) { |
| 56 | + if (typeof target !== 'string') continue; |
| 57 | + const specifier = key === '.' ? pkg.name : `${pkg.name}/${key.replace(/^\.\//, '')}`; |
| 58 | + paths[specifier] = [`${pkg.dir}/${target.replace(/^\.\//, '')}`]; |
| 59 | + } |
| 60 | + } |
| 61 | + return paths; |
| 62 | +} |
| 63 | + |
| 64 | +/** |
| 65 | + * Type-check the given example blocks against the real framework. Each block |
| 66 | + * is compiled as its own module in one shared program so diagnostics carry |
| 67 | + * the example's virtual file name. |
| 68 | + */ |
| 69 | +export async function typeCheckExamples(examples: ContentExample[]): Promise<ExampleFailure[]> { |
| 70 | + if (examples.length === 0) return []; |
| 71 | + // The temp dir must live inside the workspace so node_modules resolution |
| 72 | + // (vite, preact, ...) walks up to the repo's dependencies; `.tmp` is |
| 73 | + // gitignored, so create it first (clean CI checkouts do not carry it). |
| 74 | + await Deno.mkdir('.tmp', { recursive: true }); |
| 75 | + const dir = await Deno.makeTempDir({ dir: '.tmp', prefix: 'content-examples-' }); |
| 76 | + try { |
| 77 | + const files: string[] = []; |
| 78 | + for (const [index, example] of examples.entries()) { |
| 79 | + const name = `example-${index}.${example.lang}`; |
| 80 | + await Deno.writeTextFile(`${dir}/${name}`, example.code); |
| 81 | + files.push(`${dir}/${name}`); |
| 82 | + } |
| 83 | + const paths = await workspacePaths(); |
| 84 | + const options: ts.CompilerOptions = { |
| 85 | + allowImportingTsExtensions: true, |
| 86 | + experimentalDecorators: true, |
| 87 | + jsx: ts.JsxEmit.ReactJSX, |
| 88 | + jsxImportSource: '@openelement/element', |
| 89 | + module: ts.ModuleKind.ESNext, |
| 90 | + moduleResolution: ts.ModuleResolutionKind.Bundler, |
| 91 | + noEmit: true, |
| 92 | + skipLibCheck: true, |
| 93 | + strict: true, |
| 94 | + target: ts.ScriptTarget.ESNext, |
| 95 | + baseUrl: Deno.cwd(), |
| 96 | + paths, |
| 97 | + // Doc snippets are teaching material, not shippable modules: unused |
| 98 | + // locals and missing return-type annotations are not defects there. |
| 99 | + noUnusedLocals: false, |
| 100 | + noUnusedParameters: false, |
| 101 | + }; |
| 102 | + const program = ts.createProgram(files, options); |
| 103 | + const failures: ExampleFailure[] = []; |
| 104 | + for (const [index, file] of files.entries()) { |
| 105 | + const source = program.getSourceFile(file); |
| 106 | + if (!source) { |
| 107 | + failures.push({ file: examples[index].file, message: 'example failed to parse' }); |
| 108 | + continue; |
| 109 | + } |
| 110 | + const diagnostics = [ |
| 111 | + ...program.getSyntacticDiagnostics(source), |
| 112 | + ...program.getSemanticDiagnostics(source), |
| 113 | + ]; |
| 114 | + for (const diagnostic of diagnostics) { |
| 115 | + if (suppressElidedDiagnostic(diagnostic)) continue; |
| 116 | + const position = diagnostic.file?.getLineAndCharacterOfPosition(diagnostic.start ?? 0); |
| 117 | + failures.push({ |
| 118 | + file: `${examples[index].file} (block ${examples[index].index + 1})`, |
| 119 | + message: `TS${diagnostic.code} at line ${(position?.line ?? 0) + 1}: ${ |
| 120 | + ts.flattenDiagnosticMessageText(diagnostic.messageText, ' ') |
| 121 | + }`, |
| 122 | + }); |
| 123 | + } |
| 124 | + } |
| 125 | + return failures; |
| 126 | + } finally { |
| 127 | + await Deno.remove(dir, { recursive: true }); |
| 128 | + } |
| 129 | +} |
| 130 | + |
| 131 | +/** |
| 132 | + * Elided-context suppression (see the module header): returns true only for |
| 133 | + * diagnostics that express documented snippet elision, never framework-surface |
| 134 | + * errors. |
| 135 | + */ |
| 136 | +export function suppressElidedDiagnostic(diagnostic: ts.Diagnostic): boolean { |
| 137 | + const text = ts.flattenDiagnosticMessageText(diagnostic.messageText, ' '); |
| 138 | + if (diagnostic.code === 2307) { |
| 139 | + // Unresolved module: only framework modules are harness truth. The |
| 140 | + // `@openelement/generated/*` namespace is adapter-emitted consumer code. |
| 141 | + if (/Cannot find module '@openelement\/(?!generated\/)/.test(text)) return false; |
| 142 | + return true; |
| 143 | + } |
| 144 | + // Undefined names from elided application code. |
| 145 | + if (diagnostic.code === 2304) return true; |
| 146 | + // Implicit-any in teaching snippets. |
| 147 | + if (diagnostic.code === 7006) return true; |
| 148 | + // Property access on the uninferred loader-data generic (`{}`). |
| 149 | + if (diagnostic.code === 2339 && text.includes(`on type '{}'`)) return true; |
| 150 | + return false; |
| 151 | +} |
| 152 | + |
| 153 | +export async function checkContentExamples(): Promise<ExampleFailure[]> { |
| 154 | + const seen = new Set<string>(); |
| 155 | + const examples: ContentExample[] = []; |
| 156 | + for (const dir of ['www/content/guide', 'www/content/architecture']) { |
| 157 | + for await (const entry of walk(dir, { includeDirs: false, exts: ['.md'] })) { |
| 158 | + const markdown = await Deno.readTextFile(entry.path); |
| 159 | + for (const example of extractExamples(entry.path, markdown)) { |
| 160 | + // en/zh translations carry identical code — check each block once. |
| 161 | + if (seen.has(example.code)) continue; |
| 162 | + seen.add(example.code); |
| 163 | + examples.push(example); |
| 164 | + } |
| 165 | + } |
| 166 | + } |
| 167 | + return await typeCheckExamples(examples); |
| 168 | +} |
| 169 | + |
| 170 | +if (import.meta.main) { |
| 171 | + const failures = await checkContentExamples(); |
| 172 | + if (failures.length > 0) { |
| 173 | + console.error('Content example type-check failed:'); |
| 174 | + for (const failure of failures) { |
| 175 | + console.error(`- ${failure.file}: ${failure.message}`); |
| 176 | + } |
| 177 | + Deno.exit(1); |
| 178 | + } |
| 179 | + console.log('Content example type-check passed.'); |
| 180 | +} |
0 commit comments