Skip to content
Source
Sign inSign up
TanStack/db
Open History to see the last commit

doc-snippet-syntax.mjs

278 lines9.1 KB

1// Syntax helpers for check-doc-snippets.mjs, with the cases that pin their
2// judgments. `selfTest()` runs on every check, so a change that makes a helper
3// miss a defect, or report a correct example, fails before any doc is read.
4import ts from 'typescript'
5​
6const parse = (code, jsx) =>
7 ts.createSourceFile(
8 jsx ? `example.tsx` : `example.ts`,
9 code,
10 ts.ScriptTarget.Latest,
11 true,
12 jsx ? ts.ScriptKind.TSX : ts.ScriptKind.TS,
13 )
14​
15const isJsx = (node) =>
16 ts.isJsxElement(node) ||
17 ts.isJsxSelfClosingElement(node) ||
18 ts.isJsxFragment(node)
19​
20/**
21 * The tokens of an example, without what formatting changes, so a reformatted
22 * example keeps its baseline entry: spacing, comments, trailing commas,
23 * semicolons, the parentheses around multi-line JSX, and the parentheses
24 * around a single arrow parameter. Other commas and parentheses stay, because
25 * moving one changes what the code calls. The tree, not a token scan, finds JSX: a parenthesis in JSX
26 * text is text.
27 */
28export function fingerprint(code, jsx) {
29 const tokens = []
30 const visit = (node) => {
31 if (ts.isParenthesizedExpression(node) && isJsx(node.expression))
32 return visit(node.expression)
33 const children = node.getChildren()
34 if (children.length === 0) {
35 if (
36 node.kind === ts.SyntaxKind.SemicolonToken ||
37 node.kind === ts.SyntaxKind.EndOfFileToken
38 )
39 return
40 tokens.push(
41 ts.isStringLiteral(node)
42 ? JSON.stringify(node.text)
43 : // Formatting also reflows JSX text and the HTML in a template.
44 node.getText().replace(/\s+/g, ``),
45 )
46 return
47 }
48 const bareParameter =
49 ts.isArrowFunction(node) &&
50 node.parameters.length === 1 &&
51 ts.isIdentifier(node.parameters[0].name) &&
52 !node.parameters[0].type
53 children.forEach((child, index) => {
54 const parameterParen =
55 bareParameter &&
56 (child.kind === ts.SyntaxKind.OpenParenToken ||
57 child.kind === ts.SyntaxKind.CloseParenToken)
58 // A trailing comma ends its list; other commas separate values.
59 const trailingComma =
60 child.kind === ts.SyntaxKind.CommaToken && index === children.length - 1
61 if (!parameterParen && !trailingComma) visit(child)
62 })
63 }
64 visit(parse(code, jsx))
65 return tokens.join(` `)
67​
68/**
69 * Whether an example parses. Only syntax counts: a semantic error with a 1xxx
70 * code, such as a missing default export, is still an error to report.
71 */
72export function parses(code, jsx) {
73 const { diagnostics = [] } = ts.transpileModule(code, {
74 reportDiagnostics: true,
75 fileName: jsx ? `example.tsx` : `example.ts`,
76 compilerOptions: { jsx: ts.JsxEmit.Preserve },
77 })
78 return diagnostics.length === 0
80​
81/** The names an example imports from a TanStack package, in every form. */
82export function tanstackImports(code, jsx) {
83 const names = []
84 for (const statement of parse(code, jsx).statements) {
85 if (
86 !ts.isImportDeclaration(statement) ||
87 !ts.isStringLiteral(statement.moduleSpecifier) ||
88 !statement.moduleSpecifier.text.startsWith(`@tanstack/`)
89 )
90 continue
91 const clause = statement.importClause
92 if (clause?.name) names.push(clause.name.text)
93 const bindings = clause?.namedBindings
94 if (bindings && ts.isNamedImports(bindings))
95 names.push(...bindings.elements.map((element) => element.name.text))
96 }
97 return names
99​
100function editDistance(a, b) {
101 let previous = Array.from({ length: b.length + 1 }, (_, j) => j)
102 for (let i = 1; i <= a.length; i++) {
103 const row = [i]
104 for (let j = 1; j <= b.length; j++)
105 row[j] = Math.min(
106 previous[j] + 1,
107 row[j - 1] + 1,
108 previous[j - 1] + (a[i - 1] === b[j - 1] ? 0 : 1),
109 )
110 previous = row
111 }
112 return previous[b.length]
114​
115/**
116 * The imported name that an unknown name misspells, if any. An app's own
117 * names often differ from an import only in case (`collection` and
118 * `Collection`) or by a suffix (`counter` and `count`); those are not typos.
119 */
120export function misspelling(name, imported) {
121 if (name.length < 5) return undefined
122 return imported.find(
123 (candidate) =>
124 candidate.toLowerCase() !== name.toLowerCase() &&
125 !candidate.startsWith(name) &&
126 !name.startsWith(candidate) &&
127 editDistance(name, candidate) <= (name.length >= 8 ? 2 : 1),
128 )
130​
131/**
132 * The TypeScript in a Svelte or Vue component example: its `<script>` block
133 * with `lang="ts"`, and the line it starts on, counted from the fence. The
134 * template is not TypeScript and is not checked. Undefined when the component
135 * has no TypeScript script.
136 */
137export function componentScript(code) {
138 const match =
139 /<script\b[^>]*\blang=["']ts["'][^>]*>\n?([\s\S]*?)<\/script>/.exec(code)
140 if (!match) return undefined
141 const start = match.index + match[0].indexOf(`>`) + 1
142 const offset = code.slice(0, start).split(`\n`).length - 1
143 return { code: match[1], offset: code[start] === `\n` ? offset + 1 : offset }
145​
146const frameworks = new Set([
147 `angular`,
148 `preact`,
149 `react`,
150 `solid`,
151 `svelte`,
152 `vue`,
153])
154​
155/**
156 * The framework a doc or skill file documents, from its path segments: a
157 * `docs/framework/<name>/` directory or a `packages/<name>-db/` package. A
158 * name inside a word, such as `solid` in `consolidation`, does not count.
159 * Other files document React.
160 */
161export function frameworkOf(file) {
162 const segments = file.split(`/`)
163 const name = segments.flatMap((segment, index) =>
164 segments[index - 1] === `framework`
165 ? [segment]
166 : segment.endsWith(`-db`)
167 ? [segment.slice(0, -3)]
168 : [],
169 )
170 return name.find((candidate) => frameworks.has(candidate)) ?? `react`
172​
173export function selfTest() {
174 const imports = [
175 `include`,
176 `toArray`,
177 `count`,
178 `Collection`,
179 `QueryClient`,
180 `useLiveQuery`,
181 `eq`,
182 ]
183 const typos = {
184 inclde: `include`,
185 toArry: `toArray`,
186 useLiveQuey: `useLiveQuery`,
187 useLievQuery: `useLiveQuery`,
188 collection: undefined,
189 queryClient: undefined,
190 counter: undefined,
191 counts: undefined,
192 q: undefined,
193 Colection: `Collection`,
194 }
195 for (const [name, expected] of Object.entries(typos)) {
196 const found = misspelling(name, imports)
197 if (found !== expected)
198 throw new Error(
199 `self-test: misspelling(${name}) is ${found}, not ${expected}`,
200 )
201 }
202​
203 for (const [code, expected] of [
204 [`import Db from '@tanstack/db'\nDb()`, true],
205 [`const query = useLiveQuery((q) => q.from({ todo })`, false],
206 [`q.from(...)`, false],
207 ])
208 if (parses(code, false) !== expected)
209 throw new Error(`self-test: parses(${code}) is not ${expected}`)
210​
211 const component = componentScript(
212 `<!-- A.svelte -->\n<script lang="ts">\nconst a = 1\n</script>\n<p>{a}</p>`,
213 )
214 if (component?.code !== `const a = 1\n` || component.offset !== 2)
215 throw new Error(
216 `self-test: componentScript read ${JSON.stringify(component)}`,
217 )
218 if (componentScript(`<script>\nconst a = 1\n</script>`) !== undefined)
219 throw new Error(
220 `self-test: componentScript read a script without lang="ts"`,
221 )
222 if (componentScript(`<script setup lang="ts">x</script>`)?.code !== `x`)
223 throw new Error(
224 `self-test: componentScript missed <script setup lang="ts">`,
225 )
226​
227 for (const [file, expected] of [
228 [`docs/framework/preact/overview.md`, `preact`],
229 [`docs/framework/react/overview.md`, `react`],
230 [`packages/solid-db/skills/solid-db/SKILL.md`, `solid`],
231 [
232 `docs/contributing/oracle-reviews/code-weight-multiset-consolidation.md`,
233 `react`,
234 ],
235 [`docs/guides/live-queries.md`, `react`],
236 ])
237 if (frameworkOf(file) !== expected)
238 throw new Error(`self-test: frameworkOf(${file}) is ${frameworkOf(file)}`)
239​
240 const imported = tanstackImports(
241 [
242 `import Default, { inclde, type Colection } from '@tanstack/db'`,
243 `import type { QueryClient } from '@tanstack/query-core'`,
244 `import { notTanStack } from 'other'`,
245 ].join(`\n`),
246 )
247 if (imported.join() !== `Default,inclde,Colection,QueryClient`)
248 throw new Error(`self-test: tanstackImports found ${imported.join()}`)
249​
250 // Pairs that formatting can produce must keep one fingerprint.
251 const same = [
252 [`f(a, b,);`, `f(a, b)`],
253 [`const o = { a: 1, b: [1, 2,], }`, `const o = { a: 1, b: [1, 2] }`],
254 [`list.map(x => x.id)`, `list.map((x) => x.id)`],
255 [`return (<p>:)</p>)`, `return <p>:)</p>`],
256 [
257 `return (\n <li key={t.id}>{t.text}</li>\n)`,
258 `return <li key={t.id}>{t.text}</li>`,
259 ],
260 [`q.from({ a })\n .join(x) // why`, `q.from({ a }).join(x)`],
261 ]
262 for (const [a, b] of same)
263 if (fingerprint(a, true) !== fingerprint(b, true))
264 throw new Error(`self-test: fingerprints differ for ${a} and ${b}`)
265​
266 // Edits that change what the code does must change the fingerprint.
267 const different = [
268 [`.where(eq(a, b))`, `.where(eq(a), b)`],
269 [`f(a, -b)`, `f(a - b)`],
270 [`eq(a, [b])`, `eq(a[b])`],
271 [`f((a, b) => a)`, `f(a, b => a)`],
272 [`eq(a.id, b.id)`, `eq(a.id, b.userId)`],
273 [`'a b'`, `'ab'`],
274 ]
275 for (const [a, b] of different)
276 if (fingerprint(a, true) === fingerprint(b, true))
277 throw new Error(`self-test: fingerprints match for ${a} and ${b}`)