Open History to see the last commit
1// Typechecks the TypeScript code examples in the guides and the shipped agent
2// skills against the workspace packages' source.
3//
4// Examples are fragments: they use collections and components they never
5// declare. The check declares each unknown name as `any`, so it reports what
6// an example gets wrong about the TanStack API rather than what it leaves
7// out. An unknown name that a TanStack package exports is reported instead:
8// the example uses it without importing it.
9//
10// node scripts/check-doc-snippets.mjs [--verbose] [--update-baseline]
11//
12// An example that does not parse fails too. Mark a fence ```ts nocheck to
13// skip an example that is not meant to compile.
14//
15// `doc-snippets-baseline.json` lists examples that already failed when the
16// check began, by file and a hash of their code. Editing one changes its
17// hash, so an edited example must pass; reformatting one keeps it. An example that passes must leave the
18// baseline: run with --update-baseline after fixing one.
19//
20// Debugging: SNIPPET_ONLY=<file>:<line> checks one example, and
21// SNIPPET_DUMP=<file>:<line> prints the source the check compiles for it.
22import { createHash } from 'node:crypto'
23import { existsSync, readFileSync, readdirSync, writeFileSync } from 'node:fs'
24import { join, relative } from 'node:path'
25import { fileURLToPath } from 'node:url'
26import prettier from 'prettier'
27import ts from 'typescript'
28import {
29 componentScript,
30 fingerprint,
31 frameworkOf,
32 misspelling,
33 parses,
34 selfTest,
35 tanstackImports,
36} from './doc-snippet-syntax.mjs'
37
38const root = fileURLToPath(new URL(`..`, import.meta.url))
39const verbose = process.argv.includes(`--verbose`)
40const updateBaseline = process.argv.includes(`--update-baseline`)
41const baselinePath = join(root, `scripts`, `doc-snippets-baseline.json`)
42const baseline = existsSync(baselinePath)
43 ? JSON.parse(readFileSync(baselinePath, `utf8`))
44 : {}
45const hashOf = (code) =>
46 createHash(`sha256`).update(code).digest(`hex`).slice(0, 16)
47
48function walk(dir, keep) {
49 if (!existsSync(dir)) return []
50 return readdirSync(dir, { withFileTypes: true }).flatMap((entry) => {
51 const path = join(dir, entry.name)
52 if (entry.isDirectory())
53 return entry.name === `node_modules` || entry.name === `reference`
54 ? []
55 : walk(path, keep)
56 return keep(path) ? [path] : []
57 })
58}
59
60const markdown = [
61 ...walk(join(root, `docs`), (path) => path.endsWith(`.md`)),
62 ...readdirSync(join(root, `packages`)).flatMap((pkg) =>
63 walk(join(root, `packages`, pkg, `skills`), (path) => path.endsWith(`.md`)),
64 ),
65]
66
67// Map each workspace package and its subpath exports to source. CI does not
68// build the packages, so an export that falls through to dist/ is missing.
69const paths = {}
70for (const pkg of readdirSync(join(root, `packages`))) {
71 const manifest = join(root, `packages`, pkg, `package.json`)
72 if (!existsSync(manifest)) continue
73 const {
74 name,
75 private: unpublished,
76 exports = {},
77 } = JSON.parse(readFileSync(manifest, `utf8`))
78 // Examples document published packages only.
79 if (unpublished) continue
80 for (const subpath of Object.keys(exports)) {
81 if (subpath === `./package.json`) continue
82 // `.` is src/index; `./x` is src/x.ts or src/x/index.ts.
83 const stem = subpath === `.` ? `index` : subpath.slice(2)
84 const entry = [`${stem}.ts`, `${stem}.tsx`, `${stem}/index.ts`]
85 .map((file) => join(`packages`, pkg, `src`, file))
86 .find((file) => existsSync(join(root, file)))
87 if (!entry) throw new Error(`No source for ${name} export ${subpath}`)
88 paths[subpath === `.` ? name : `${name}/${stem}`] = [entry]
89 }
90}
91
92// A fence closes with as many backticks as it opened with, so a ````ts
93// example can hold a ``` block.
94const fence =
95 /^(`{3,})(ts|tsx|typescript|svelte|vue)([^\n]*)\n([\s\S]*?)^\1[ \t]*$/gm
96const snippets = []
97for (const file of markdown) {
98 const text = readFileSync(file, `utf8`)
99 for (const match of text.matchAll(fence)) {
100 if (match[3].includes(`nocheck`)) continue
101 let line = text.slice(0, match.index).split(`\n`).length
102 let code = match[4]
103 // A component example: check its TypeScript script, not its template.
104 if (match[2] === `svelte` || match[2] === `vue`) {
105 const script = componentScript(code)
106 if (!script) continue
107 code = script.code
108 line += script.offset
109 }
110 snippets.push({
111 file: relative(root, file),
112 line,
113 code,
114 name: join(
115 root,
116 `.snippet-check`,
117 `${snippets.length}.${/<\/|<[A-Z][A-Za-z]*[ />]/.test(code) ? `tsx` : `ts`}`,
118 ),
119 })
120 }
121}
122
123selfTest()
124for (const snippet of snippets) {
125 const jsx = snippet.name.endsWith(`.tsx`)
126 snippet.hash = hashOf(fingerprint(snippet.code, jsx))
127 snippet.imports = tanstackImports(snippet.code, jsx)
128}
129
130if (process.env.SNIPPET_ONLY) {
131 const keep = snippets.filter(
132 (s) => `${s.file}:${s.line}` === process.env.SNIPPET_ONLY,
133 )
134 snippets.length = 0
135 snippets.push(...keep)
136}
137
138const options = {
139 strict: true,
140 noUnusedLocals: false,
141 noUncheckedIndexedAccess: false,
142 allowUnreachableCode: true,
143 skipLibCheck: true,
144 noEmit: true,
145 jsx: ts.JsxEmit.ReactJSX,
146 target: ts.ScriptTarget.ES2022,
147 module: ts.ModuleKind.ESNext,
148 moduleResolution: ts.ModuleResolutionKind.Bundler,
149 lib: [`lib.es2022.d.ts`, `lib.dom.d.ts`, `lib.dom.iterable.d.ts`],
150 baseUrl: root,
151 paths,
152}
153
154// Modules an example imports but this repo cannot resolve (app files, other
155// frameworks) are declared `any`, one by one. A wildcard would also erase
156// third-party types that the packages themselves use.
157const ambient = join(root, `.snippet-check`, `ambient.d.ts`)
158const missingModules = new Set()
159const ambientSource = () =>
160 [...missingModules]
161 .map((name) => `declare module ${JSON.stringify(name)}\n`)
162 .join(``) || `export {}\n`
163
164function check(sources) {
165 const host = ts.createCompilerHost(options)
166 const read = host.readFile
167 host.readFile = (path) => sources.get(path) ?? read(path)
168 const exists = host.fileExists
169 host.fileExists = (path) => sources.has(path) || exists(path)
170 const program = ts.createProgram([...sources.keys()], options, host)
171 return { program, diagnostics: ts.getPreEmitDiagnostics(program) }
172}
173
174// Names the TanStack packages export, to tell "not imported" from "app code".
175const exported = new Map()
176{
177 const probe = join(root, `.snippet-check`, `exports.ts`)
178 const packages = Object.keys(paths).filter((name) =>
179 name.startsWith(`@tanstack/`),
180 )
181 const imports = packages
182 .map((name, i) => `import * as m${i} from '${name}'`)
183 .join(`\n`)
184 const { program } = check(new Map([[probe, imports + `\n`]]))
185 const checker = program.getTypeChecker()
186 program.getSourceFile(probe).statements.forEach((statement, i) => {
187 const symbol = checker.getSymbolAtLocation(statement.moduleSpecifier)
188 if (!symbol) return
189 for (const item of checker.getExportsOfModule(symbol)) {
190 const owners = exported.get(item.name) ?? []
191 owners.push(packages[i])
192 exported.set(item.name, owners)
193 }
194 })
195}
196
197// The framework a file documents, for names several adapters export.
198function packageFor(name, file) {
199 const owners = exported.get(name)
200 if (owners.length === 1) return owners[0]
201 return (
202 owners.find((owner) => owner === `@tanstack/db`) ??
203 owners.find((owner) => owner === `@tanstack/${frameworkOf(file)}-db`) ??
204 owners[0]
205 )
206}
207
208const importsTanStack = (code) => /from ['"]@tanstack\//.test(code)
209
210function sourceOf(snippet, declared, autoImported) {
211 const byPackage = new Map()
212 for (const name of autoImported) {
213 const pkg = packageFor(name, snippet.file)
214 byPackage.set(pkg, [...(byPackage.get(pkg) ?? []), name])
215 }
216 return (
217 [...byPackage]
218 .map(([pkg, names]) => `import { ${names.join(`, `)} } from '${pkg}'\n`)
219 .join(``) +
220 `import type { Collection as SnippetCollection } from '@tanstack/db'\n` +
221 [...declared]
222 .map(
223 (name) =>
224 `declare const ${name}: ${/collection$/i.test(name) ? `SnippetCollection<Record<string, any>, string | number>` : `any`}\ntype ${name} = any\n`,
225 )
226 .join(``) +
227 snippet.code +
228 `\nexport {}\n`
229 )
230}
231
232const declared = snippets.map(() => new Set())
233const unimported = snippets.map(() => new Set())
234const autoImported = snippets.map(() => new Set())
235const misspelled = snippets.map(() => new Map())
236const unknownName = new Set([2304, 2552, 18004, 2749, 2693])
237// Docs often show alternatives side by side in one block, and leave
238// callback parameters unannotated where an app would annotate them.
239const ignored = new Set([2451, 2300, 2393, 7005, 7006, 7019, 7031, 7034, 7053])
240// An unresolvable dependency is declared as an untyped module, whose names
241// cannot be used as types.
242ignored.add(2709)
243let diagnostics = []
244// Declare unknown names until a pass adds none.
245for (let pass = 0; pass < 6; pass++) {
246 const sources = new Map([[ambient, ambientSource()]])
247 snippets.forEach((snippet, i) =>
248 sources.set(snippet.name, sourceOf(snippet, declared[i], autoImported[i])),
249 )
250 diagnostics = check(sources).diagnostics
251 let added = 0
252 for (const diagnostic of diagnostics) {
253 if (
254 diagnostic.code === 2307 &&
255 snippets.some((s) => s.name === diagnostic.file?.fileName)
256 ) {
257 const name = ts
258 .flattenDiagnosticMessageText(diagnostic.messageText, ``)
259 .match(/'([^']+)'/)?.[1]
260 if (name && !missingModules.has(name)) {
261 missingModules.add(name)
262 added++
263 }
264 continue
265 }
266 if (!unknownName.has(diagnostic.code)) continue
267 const index = snippets.findIndex(
268 (s) => s.name === diagnostic.file?.fileName,
269 )
270 if (index < 0) continue
271 const name = ts
272 .flattenDiagnosticMessageText(diagnostic.messageText, ``)
273 .match(/'([^']+)'/)?.[1]
274 if (!name) continue
275 // A near miss of a TanStack name the example imports is a typo, not app
276 // code. TypeScript stops suggesting spellings after a few, so compare here.
277 const suggestion = misspelling(name, snippets[index].imports)
278 if (suggestion !== undefined) misspelled[index].set(name, suggestion)
279 if (exported.has(name)) {
280 if (importsTanStack(snippets[index].code)) unimported[index].add(name)
281 else if (!autoImported[index].has(name)) {
282 autoImported[index].add(name)
283 added++
284 }
285 } else if (!declared[index].has(name)) {
286 declared[index].add(name)
287 added++
288 }
289 }
290 if (added === 0) break
291}
292
293if (process.env.SNIPPET_DUMP) {
294 const i = snippets.findIndex(
295 (s) => `${s.file}:${s.line}` === process.env.SNIPPET_DUMP,
296 )
297 console.log(sourceOf(snippets[i], declared[i], autoImported[i]))
298}
299const failures = []
300let unparsable = 0
301snippets.forEach((snippet, i) => {
302 const ownDiagnostics = diagnostics.filter(
303 (d) => d.file?.fileName === snippet.name,
304 )
305 // An example that does not parse cannot be checked. Pseudo-code, such as
306 // `...` placeholders, is marked nocheck.
307 if (!parses(snippet.code, snippet.name.endsWith(`.tsx`))) {
308 unparsable++
309 failures.push({
310 snippet,
311 text: `${snippet.file}:${snippet.line}\n does not parse; mark the fence nocheck if it is pseudo-code`,
312 })
313 return
314 }
315 const offset =
316 1 +
317 declared[i].size * 2 +
318 new Set([...autoImported[i]].map((n) => packageFor(n, snippet.file))).size
319 const messages = ownDiagnostics
320 .filter((d) => !unknownName.has(d.code) && !ignored.has(d.code))
321 .map((d) => {
322 const { line } = d.file.getLineAndCharacterOfPosition(d.start ?? 0)
323 return ` line ${snippet.line + line - offset}: TS${d.code} ${ts.flattenDiagnosticMessageText(d.messageText, ` `)}`
324 })
325 for (const name of unimported[i])
326 messages.push(` uses \`${name}\` without importing it`)
327 for (const [name, suggestion] of misspelled[i])
328 messages.push(` uses \`${name}\`; did you mean \`${suggestion}\`?`)
329 if (messages.length)
330 failures.push({
331 snippet,
332 text: `${snippet.file}:${snippet.line}\n${messages.join(`\n`)}`,
333 })
334})
335
336const known = (snippet) =>
337 baseline[snippet.file]?.includes(snippet.hash) ?? false
338const newFailures = failures.filter(({ snippet }) => !known(snippet))
339const failing = new Set(
340 failures.map(({ snippet }) => `${snippet.file}#${snippet.hash}`),
341)
342const stale = Object.entries(baseline).flatMap(([file, hashes]) =>
343 hashes
344 .filter((hash) => !failing.has(`${file}#${hash}`))
345 .map((hash) => `${file}#${hash}`),
346)
347
348if (updateBaseline && !process.env.SNIPPET_ONLY) {
349 const next = {}
350 for (const { snippet } of failures)
351 (next[snippet.file] ??= []).push(snippet.hash)
352 for (const hashes of Object.values(next)) hashes.sort()
353 const sorted = Object.fromEntries(
354 Object.entries(next).sort(([a], [b]) => a.localeCompare(b)),
355 )
356 writeFileSync(
357 baselinePath,
358 await prettier.format(JSON.stringify(sorted), {
359 ...(await prettier.resolveConfig(baselinePath)),
360 filepath: baselinePath,
361 }),
362 )
363 console.log(`Baseline: ${failures.length} known failing examples`)
364} else {
365 const shown = verbose ? failures : newFailures
366 if (shown.length) console.log(shown.map(({ text }) => text).join(`\n\n`))
367 if (stale.length && !process.env.SNIPPET_ONLY)
368 console.log(
369 `\n${stale.length} baseline entries now pass or no longer exist; run with --update-baseline:\n${stale.join(`\n`)}`,
370 )
371 console.log(
372 `\n${snippets.length} examples in ${markdown.length} files: ${newFailures.length} new failures, ${failures.length - newFailures.length} known, ${unparsable} of them do not parse`,
373 )
374 process.exitCode =
375 newFailures.length || (stale.length && !process.env.SNIPPET_ONLY) ? 1 : 0
376}