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

generate-docs.ts

1,096 lines37.1 KB

1import { mkdir, readFile, readdir, rm, writeFile } from 'node:fs/promises'
2import { createRequire } from 'node:module'
3import { dirname, resolve } from 'node:path'
4import { fileURLToPath } from 'node:url'
5import ts from 'typescript'
6​
7const __dirname = fileURLToPath(new URL('.', import.meta.url))
8const require = createRequire(import.meta.url)
9const typedocConfigPackageJson =
10 require.resolve('@tanstack/typedoc-config/package.json')
11const typedocConfigRequire = createRequire(typedocConfigPackageJson)
12const TypeDoc = await import(typedocConfigRequire.resolve('typedoc'))
13​
14type PackageReferenceDocsConfig = {
15 entryPoints: Array<string>
16 tsconfig: string
17 outputDir: string
18 exclude?: Array<string>
19 simplifyLitQueriesControllerTypes?: boolean
20 trimGeneratedMarkdown?: boolean
21 // Maps a generated page's path (relative to outputDir, no extension) to the flat
22 // `docs/framework/<framework>/reference/<name>.md` URLs it replaced, so old links/bookmarks redirect
23 // instead of falling through to the framework docs index. See https://github.com/TanStack/query/issues/11371
24 redirectFrom?: Record<string, Array<string>>
26​
27type TypeDocReflectionWithSignatures = {
28 name: string
29 children?: Array<TypeDocReflectionWithSignatures>
30 signatures?: Array<{
31 typeParameters?: Array<{
32 name: string
33 default?: unknown
34 }>
35 }>
37​
38function simplifyLitQueriesControllerTypes(
39 project: TypeDocReflectionWithSignatures,
40) {
41 const stack: Array<TypeDocReflectionWithSignatures> = [project]
42​
43 for (const reflection of stack) {
44 stack.push(...(reflection.children ?? []))
45​
46 if (reflection.name !== 'createQueriesController') {
47 continue
48 }
49​
50 for (const signature of reflection.signatures ?? []) {
51 const combinedResult = signature.typeParameters?.find(
52 (typeParameter) => typeParameter.name === 'TCombinedResult',
53 )
54​
55 if (!combinedResult?.default) {
56 continue
57 }
58​
59 const queryOptionsType = TypeDoc.ReferenceType.createBrokenReference(
60 'TQueryOptions',
61 project,
62 undefined,
63 )
64 queryOptionsType.refersToTypeParameter = true
65​
66 // CreateQueriesResults is internal; render it as plain text, not a link.
67 const queriesResultsType = TypeDoc.ReferenceType.createBrokenReference(
68 'CreateQueriesResults',
69 project,
70 undefined,
71 )
72 queriesResultsType.typeArguments = [queryOptionsType]
73​
74 combinedResult.default = queriesResultsType
75 }
76 }
78​
79async function trimTrailingWhitespaceInMarkdown(outputDir: string) {
80 const entries = await readdir(outputDir, { withFileTypes: true })
81​
82 await Promise.all(
83 entries.map(async (entry) => {
84 const path = resolve(outputDir, entry.name)
85​
86 if (entry.isDirectory()) {
87 await trimTrailingWhitespaceInMarkdown(path)
88 return
89 }
90​
91 if (!entry.isFile() || !path.endsWith('.md')) {
92 return
93 }
94​
95 const markdown = await readFile(path, 'utf8')
96 const trimmed = markdown.replace(/[ \t]+$/gm, '')
97​
98 if (trimmed !== markdown) {
99 await writeFile(path, trimmed)
100 }
101 }),
102 )
104​
105async function addRedirectFromToFileFrontmatter(
106 filePath: string,
107 fromPaths: Array<string>,
108) {
109 const markdown = await readFile(filePath, 'utf8')
110​
111 const frontmatterMatch = markdown.match(/^---\n([\s\S]*?)\n---\n/)
112 if (!frontmatterMatch) {
113 throw new Error(`Expected frontmatter in ${filePath}`)
114 }
115​
116 const redirectLines = fromPaths
117 .map((fromPath) => ` - ${fromPath}`)
118 .join('\n')
119 const updatedFrontmatter = `---\n${frontmatterMatch[1]}\nredirect_from:\n${redirectLines}\n---\n`
120​
121 await writeFile(
122 filePath,
123 updatedFrontmatter + markdown.slice(frontmatterMatch[0].length),
124 )
126​
127async function addRedirectFromToFrontmatter(
128 outputDir: string,
129 redirectFrom: Record<string, Array<string>>,
130) {
131 for (const [pagePath, fromPaths] of Object.entries(redirectFrom)) {
132 await addRedirectFromToFileFrontmatter(
133 resolve(outputDir, `${pagePath}.md`),
134 fromPaths,
135 )
136 }
138​
139async function generatePackageReferenceDocs(pkg: PackageReferenceDocsConfig) {
140 const outputDir = pkg.outputDir
141 await rm(outputDir, { recursive: true, force: true })
142 await mkdir(outputDir, { recursive: true })
143​
144 const app = await TypeDoc.Application.bootstrapWithPlugins({
145 plugin: [
146 'typedoc-plugin-markdown',
147 'typedoc-plugin-frontmatter',
148 '@tanstack/typedoc-config/typedoc-custom-settings',
149 ],
150 hideGenerator: true,
151 readme: 'none',
152 entryFileName: 'index',
153 hideBreadcrumbs: true,
154 hidePageHeader: true,
155 hidePageTitle: true,
156 useCodeBlocks: true,
157 // `parametersFormat` and `typeDeclarationFormat` are deliberately left as lists: the first
158 // puts the huge conditional types of `useQueries` into a single cell and drops `@default`
159 // blocks, and the second collapses `@example` code blocks onto one line, which swallows the
160 // following statement into a `//` comment.
161 interfacePropertiesFormat: 'table',
162 typeAliasPropertiesFormat: 'table',
163 tableColumnSettings: {
164 hideInherited: true,
165 hideSources: true,
166 },
167 // Without this, a function property renders as `(data) => TData` β€” the table and list formats
168 // both omit the parameter types otherwise.
169 expandParameters: true,
170 excludePrivate: true,
171 excludeProtected: true,
172 excludeInternal: true,
173 excludeExternals: true,
174 sourceLinkTemplate:
175 'https://github.com/TanStack/query/blob/{gitRevision}/{path}#L{line}',
176 gitRevision: 'main',
177 displayBasePath: resolve(__dirname, '..'),
178 entryPoints: pkg.entryPoints,
179 tsconfig: pkg.tsconfig,
180 ...(pkg.exclude && { exclude: pkg.exclude }),
181 out: outputDir,
182 })
183​
184 // TypeScript flattens an alias out of an intersection, so `Options<T> & QueryKeyWithDataTag<T>`
185 // would render as the members of `Options` followed by the tag. Convert declared intersections from
186 // the source instead, so signatures keep the alias names they were written with.
187 app.converter.on(
188 TypeDoc.Converter.EVENT_CREATE_SIGNATURE,
189 (
190 context: InstanceType<typeof TypeDoc.Context>,
191 signature: InstanceType<typeof TypeDoc.SignatureReflection>,
192 declaration?: ts.Node,
193 ) => {
194 if (!declaration || !ts.isFunctionLike(declaration)) {
195 return
196 }
197 const scope = context.withScope(signature)
198 if (declaration.type && ts.isIntersectionTypeNode(declaration.type)) {
199 signature.type = scope.converter.convertType(scope, declaration.type)
200 }
201 declaration.parameters.forEach((parameter, index) => {
202 const reflection = signature.parameters?.[index]
203 if (
204 reflection &&
205 parameter.type &&
206 ts.isIntersectionTypeNode(parameter.type)
207 ) {
208 reflection.type = scope.converter.convertType(scope, parameter.type)
209 }
210 })
211 },
212 )
213​
214 const project = await app.convert()
215​
216 // `outputDir` was emptied above, so a failed conversion would otherwise leave it that way and
217 // look like every page was intentionally deleted. Fail loudly instead β€” TypeDoc reports the
218 // underlying diagnostics on stderr.
219 //
220 // One known cause is TS6305: a package that reaches `@tanstack/query-devtools` through a
221 // TypeScript project reference consumes that package's emitted `.d.ts` rather than its source
222 // (which is solid-js JSX and cannot be compiled under another framework's tsconfig). The
223 // `generate-docs` script builds it first, so this should only surface if that build was skipped.
224 if (!project) {
225 throw new Error(
226 `TypeDoc failed to convert ${pkg.entryPoints.join(', ')}. See the diagnostics above.`,
227 )
228 }
229​
230 if (pkg.simplifyLitQueriesControllerTypes) {
231 simplifyLitQueriesControllerTypes(project)
232 }
233​
234 await app.generateOutputs(project)
235​
236 if (pkg.trimGeneratedMarkdown) {
237 await trimTrailingWhitespaceInMarkdown(outputDir)
238 }
239​
240 if (pkg.redirectFrom) {
241 await addRedirectFromToFrontmatter(outputDir, pkg.redirectFrom)
242 }
243​
244 await addReferenceDetails(outputDir)
246​
247// Splits the escaped type arguments (`\\<…\\>`) that follow a type name from the rest of the line.
248function splitTypeArguments(rest: string) {
249 if (!rest.startsWith('\\<')) {
250 return { typeArguments: undefined, after: rest }
251 }
252 let depth = 0
253 for (let index = 0; index < rest.length; index++) {
254 if (rest.startsWith('\\<', index)) {
255 depth++
256 } else if (rest.startsWith('\\>', index) && --depth === 0) {
257 return {
258 typeArguments: rest.slice(2, index),
259 after: rest.slice(index + 2),
260 }
261 }
262 }
263 return { typeArguments: undefined, after: rest }
265​
266// The type page a `Parameters`/`Returns` type line refers to when the whole line is that one type
267// (with an optional default value), looking through wrappers that only change how the value is
268// passed, i.e. aliases like `Accessor<T> = () => T` and inline `() => T`.
269// Whether a type alias only changes how its single type argument is passed, e.g. `Accessor<T> = () => T`.
270async function isWrapperAlias(outputDir: string, from: string) {
271 const code = (await readPage(outputDir, from))?.match(
272 /```ts\ntype \w+<(\w+)> = ([^\n]*);\n```/,
273 )
274 return (
275 !!code &&
276 code[2]!
277 .split(' | ')
278 .every((member) => member === code[1] || member === `() => ${code[1]}`)
279 )
281​
282// The type page a `Parameters`/`Returns` type line refers to when the whole line is that one type
283// (with an optional default value), looking through wrappers that only change how the value is
284// passed, i.e. aliases like `Accessor<T> = () => T` and inline `() => T`.
285async function linkedTypePage(outputDir: string, typeLine: string) {
286 let line = typeLine
287 for (;;) {
288 line = line.replace(/^\(\) => /, '')
289 const link = line.match(
290 /^\[`\w+`\]\(\.\.\/((?:interfaces|type-aliases)\/\w+)\.md\)/,
291 )
292 if (!link) {
293 return undefined
294 }
295 const { typeArguments, after } = splitTypeArguments(
296 line.slice(link[0].length),
297 )
298 if (typeArguments && (await isWrapperAlias(outputDir, link[1]!))) {
299 line = typeArguments
300 continue
301 }
302 return after === '' || after.startsWith(' = ') ? link[1] : undefined
303 }
305​
306// The name of the type a signature's code starts with, looking through the same wrappers.
307async function typeNameInCode(outputDir: string, code: string) {
308 let type = code
309 for (;;) {
310 type = type.replace(/^\(\) => /, '')
311 const name = type.match(/^\w+/)?.[0]
312 if (
313 !name ||
314 type[name.length] !== '<' ||
315 !(await isWrapperAlias(outputDir, `type-aliases/${name}`))
316 ) {
317 return name
318 }
319 let depth = 0
320 for (let index = name.length; index < type.length; index++) {
321 if (type[index] === '<') {
322 depth++
323 } else if (
324 type[index] === '>' &&
325 type[index - 1] !== '=' &&
326 --depth === 0
327 ) {
328 type = type.slice(name.length + 1, index)
329 break
330 }
331 }
332 }
334​
335// The parameter and return types of the declaration a call signature's "Defined in" line points to, as
336// written in the source. The rendered code loses aliases that TypeScript flattens into an intersection,
337// e.g. `Options<T> & QueryKeyWithDataTag<T>` becomes the members of `Options` followed by the tag.
338const sourceFiles = new Map<string, ts.SourceFile>()
339async function declaredSignatureTypes(signature: string) {
340 const location = signature.match(/^Defined in: \[([^\]]+):(\d+)\]/m)
341 if (!location) {
342 return undefined
343 }
344 const [, file, line] = location
345 let source = sourceFiles.get(file!)
346 if (!source) {
347 const text = await readFile(resolve(__dirname, '..', file!), 'utf8').catch(
348 () => undefined,
349 )
350 if (text === undefined) {
351 return undefined
352 }
353 source = ts.createSourceFile(file!, text, ts.ScriptTarget.Latest, true)
354 sourceFiles.set(file!, source)
355 }
356 let found: ts.SignatureDeclaration | undefined
357 const visit = (node: ts.Node) => {
358 if (found) {
359 return
360 }
361 if (
362 ts.isFunctionLike(node) &&
363 'parameters' in node &&
364 source.getLineAndCharacterOfPosition(node.getStart()).line ===
365 Number(line) - 1
366 ) {
367 found = node
368 return
369 }
370 ts.forEachChild(node, visit)
371 }
372 visit(source)
373 return found && { parameter: found.parameters[0]?.type, returns: found.type }
375​
376// Types that only transform their first type argument, so a label keeps that argument to stay
377// meaningful, e.g. `Omit<UseMutationOptions>` instead of `Omit`.
378const typeTransforms = new Set([
379 'Awaited',
380 'DistributiveOmit',
381 'NonNullable',
382 'Omit',
383 'OmitKeyof',
384 'Partial',
385 'Readonly',
386 'Required',
387 'ReturnType',
388 'WithRequired',
389])
390​
391// The label of a declared type: the members of an intersection or union joined, a getter's result, the
392// keys of an object type, or the name looked up through the same wrappers as `typeNameInCode`.
393async function declaredTypeLabel(
394 outputDir: string,
395 node: ts.TypeNode,
396): Promise<string | undefined> {
397 if (ts.isParenthesizedTypeNode(node)) {
398 return declaredTypeLabel(outputDir, node.type)
399 }
400 if (ts.isIntersectionTypeNode(node) || ts.isUnionTypeNode(node)) {
401 const members = await Promise.all(
402 node.types.map((member) => declaredTypeLabel(outputDir, member)),
403 )
404 return members.every(Boolean)
405 ? members.join(ts.isIntersectionTypeNode(node) ? ' & ' : ' | ')
406 : undefined
407 }
408 if (ts.isFunctionTypeNode(node) && node.parameters.length === 0) {
409 const result = await declaredTypeLabel(outputDir, node.type)
410 return result && `() => ${result}`
411 }
412 if (ts.isTypeLiteralNode(node)) {
413 const keys = node.members
414 .map((member) => member.name?.getText())
415 .filter(Boolean)
416 return keys.length > 0 ? `{ ${keys.join(', ')} }` : undefined
417 }
418 if (
419 ts.isTypeReferenceNode(node) &&
420 typeTransforms.has(node.typeName.getText()) &&
421 node.typeArguments?.[0]
422 ) {
423 const target = await declaredTypeLabel(outputDir, node.typeArguments[0])
424 return target && `${node.typeName.getText()}<${target}>`
425 }
426 return typeNameInCode(outputDir, node.getText())
428​
429// The property table for the first type line that has one.
430async function findPropertiesTable(
431 outputDir: string,
432 typeLines: Array<string>,
433) {
434 for (const typeLine of typeLines) {
435 const link = await linkedTypePage(outputDir, typeLine)
436 const from = link && (await propertiesPage(outputDir, link))
437 const table = from && (await readPropertiesTable(outputDir, from))
438 if (table) {
439 return table
440 }
441 }
442 const bases = await findBasePages(outputDir, typeLines)
443 if (bases.length) {
444 return `Built from ${bases
445 .map(
446 (base) => `[\`${base.split('/').at(-1)}\`](../${base}.md#properties)`,
447 )
448 .join(', ')}. See the type above for what it changes.`
449 }
450 return undefined
452​
453// Splits a type expression at a top-level separator, outside `<>`, `()`, `{}`, and `[]`.
454function splitTopLevel(type: string, separator: string) {
455 const parts: Array<string> = []
456 let depth = 0
457 let start = 0
458 for (let index = 0; index < type.length; index++) {
459 const char = type[index]!
460 if ('<({['.includes(char)) {
461 depth++
462 } else if (
463 ')}]'.includes(char) ||
464 (char === '>' && type[index - 1] !== '=')
465 ) {
466 depth--
467 } else if (depth === 0 && type.startsWith(separator, index)) {
468 parts.push(type.slice(start, index))
469 start = index + separator.length
470 index += separator.length - 1
471 }
472 }
473 parts.push(type.slice(start))
474 return parts.map((part) => part.trim()).filter(Boolean)
476​
477async function typePage(outputDir: string, name: string) {
478 for (const from of [`interfaces/${name}`, `type-aliases/${name}`]) {
479 if ((await readPage(outputDir, from)) !== undefined) {
480 return from
481 }
482 }
483 return undefined
485​
486// The pages with a `## Properties` table that a type expression without one is built from: every
487// member of an intersection (skipping object literals, which only add properties), and the first type
488// argument of a utility that isn't built from one itself, like `Omit<…>`. Returns nothing unless every part is found.
489async function basePagesOfType(
490 outputDir: string,
491 type: string,
492 seen: Set<string>,
493): Promise<Array<string>> {
494 const expression = splitTopLevel(type, ' = ')[0]!
495 .replace(/^[|&]\s*/, '')
496 .replace(/^\(\) => /, '')
497 .trim()
498 const members = splitTopLevel(expression, ' & ').filter(
499 (member) => member !== 'object' && !member.startsWith('{'),
500 )
501 if (members.length > 1) {
502 const pages: Array<string> = []
503 for (const member of members) {
504 const memberPages = await basePagesOfType(outputDir, member, seen)
505 if (!memberPages.length) {
506 return []
507 }
508 pages.push(...memberPages)
509 }
510 return [...new Set(pages)]
511 }
512 const reference = members[0]?.match(/^(\w+)(?:<([\s\S]*)>)?$/)
513 if (!reference) {
514 return []
515 }
516 const [, name, typeArguments] = reference
517 const [firstTypeArgument] = typeArguments
518 ? splitTopLevel(typeArguments, ',')
519 : []
520 const page = await typePage(outputDir, name!)
521 const pages =
522 page && !(await isWrapperAlias(outputDir, page))
523 ? await basePages(outputDir, page, seen)
524 : []
525 if (pages.length) {
526 return pages
527 }
528 return firstTypeArgument
529 ? basePagesOfType(outputDir, firstTypeArgument, seen)
530 : []
532​
533async function basePages(
534 outputDir: string,
535 from: string,
536 seen: Set<string>,
537): Promise<Array<string>> {
538 if (seen.has(from)) {
539 return []
540 }
541 seen.add(from)
542 const page = await propertiesPage(outputDir, from)
543 if (page) {
544 return [page]
545 }
546 const code = typeAliasBody(await readPage(outputDir, from))
547 return code ? basePagesOfType(outputDir, code, seen) : []
549​
550// The base pages of the first type line that has any.
551async function findBasePages(outputDir: string, typeLines: Array<string>) {
552 for (const typeLine of typeLines) {
553 const type = typeLine
554 .replace(/\[`?(\w+)`?\]\([^)]*\)/g, '$1')
555 .replace(/[\\`]/g, '')
556 const pages = await basePagesOfType(outputDir, type, new Set())
557 if (pages.length) {
558 return pages
559 }
560 }
561 return []
563​
564// The type line of each parameter and of the return value in one call signature.
565function signatureTypes(signature: string) {
566 const parametersHeading = signature.match(/\n#{2,3} Parameters\n/)
567 const returnsHeading = signature.match(/\n#{2,3} Returns\n/)
568 const parameters = parametersHeading
569 ? signature.slice(
570 parametersHeading.index! + parametersHeading[0].length - 1,
571 returnsHeading?.index,
572 )
573 : ''
574 // Only the headings one level below `Parameters`, not the properties of an inline object argument.
575 const parameterHeading = '#'.repeat(
576 (parametersHeading?.[0].trim().indexOf(' ') ?? 0) + 1,
577 )
578 return {
579 parameters: new Map(
580 [
581 ...parameters.matchAll(
582 new RegExp(`\\n${parameterHeading} (\\S+)\\n\\n([^\\n]*)`, 'g'),
583 ),
584 ].map(([, name, typeLine]) => [name!, typeLine!]),
585 ),
586 returns: returnsHeading
587 ? signature
588 .slice(returnsHeading.index! + returnsHeading[0].length)
589 .trim()
590 .split('\n')[0]!
591 : undefined,
592 }
594​
595function typeAliasBody(source: string | undefined) {
596 const declaration = source?.match(/```ts\ntype \w+/)
597 if (!source || !declaration) {
598 return undefined
599 }
600 let index = declaration.index! + declaration[0].length
601 if (source[index] === '<') {
602 let depth = 0
603 for (; index < source.length; index++) {
604 if (source[index] === '<') {
605 depth++
606 } else if (
607 source[index] === '>' &&
608 source[index - 1] !== '=' &&
609 --depth === 0
610 ) {
611 index++
612 break
613 }
614 }
615 }
616 return source.slice(index).match(/^ = ([\s\S]*?);\n```/)?.[1]
618​
619function readPage(outputDir: string, from: string) {
620 return readFile(resolve(outputDir, `${from}.md`), 'utf8').then(
621 (source) => source,
622 () => undefined,
623 )
625​
626// Resolves a type page to the interface pages it stands for: itself when it has a `## Properties`
627// table, or the members of a plain alias or union. Anything else (intersections, `Omit`, `Override`, …)
628// resolves to nothing, since no generated table describes it as-is.
629async function resolveInterfacePages(
630 outputDir: string,
631 from: string,
632): Promise<Array<string> | undefined> {
633 const source = await readPage(outputDir, from)
634 if (source === undefined) {
635 return undefined
636 }
637 if (source.includes('\n## Properties\n')) {
638 return [from]
639 }
640 const code = typeAliasBody(source)
641 if (!code) {
642 return undefined
643 }
644 let members = code
645 while (/<[^<>]*>/.test(members)) {
646 members = members.replace(/<[^<>]*>/g, '')
647 }
648 const names = members
649 .split('|')
650 .map((member) => member.trim())
651 .filter(Boolean)
652 if (!names.every((name) => /^\w+$/.test(name))) {
653 return undefined
654 }
655 const pages: Array<string> = []
656 for (const name of names) {
657 const resolved =
658 (await resolveInterfacePages(outputDir, `interfaces/${name}`)) ??
659 (await resolveInterfacePages(outputDir, `type-aliases/${name}`))
660 if (!resolved) {
661 return undefined
662 }
663 pages.push(...resolved)
664 }
665 return pages
667​
668// The page whose `## Properties` table describes the type: the type itself, or the interface every
669// member of a union extends.
670async function propertiesPage(outputDir: string, from: string) {
671 const pages = await resolveInterfacePages(outputDir, from)
672 if (!pages?.length) {
673 return undefined
674 }
675 if (pages.length === 1) {
676 return pages[0]
677 }
678 const bases = new Set<string>()
679 for (const page of pages) {
680 const base = (await readPage(outputDir, page))?.match(
681 /\n## Extends\n\n- \[`\w+`\]\((\w+)\.md\)[^\n]*\n\n##/,
682 )?.[1]
683 if (!base) {
684 return undefined
685 }
686 bases.add(`${dirname(page)}/${base}`)
687 }
688 return bases.size === 1 ? [...bases][0] : undefined
690​
691async function readPropertiesTable(outputDir: string, from: string) {
692 const source = await readPage(outputDir, from)
693 const start = source?.indexOf('\n## Properties\n') ?? -1
694 if (source === undefined || start === -1) {
695 return undefined
696 }
697 const fromDir = dirname(from)
698 return source
699 .slice(start + '\n## Properties\n'.length)
700 .trim()
701 .replace(
702 /\]\((?!https?:|#)([^)]+)\)/g,
703 (_, link: string) =>
704 `](../${link.startsWith('../') ? link.slice(3) : `${fromDir}/${link}`})`,
705 )
707​
708// Adds to every function page without changing what TypeDoc generated: the properties of each
709// argument and of the result, and an `## Overview` of every call signature on overloaded pages. The
710// properties come from the generated page of the type, following plain aliases and, for a union,
711// the interface all of its members extend. Types that override or omit properties get no table.
712async function addReferenceDetails(outputDir: string) {
713 const files = await readdir(resolve(outputDir, 'functions')).catch(
714 () => [] as Array<string>,
715 )
716 for (const file of files.filter((name) => name.endsWith('.md'))) {
717 const pagePath = `functions/${file.slice(0, -3)}`
718 const pageFile = resolve(outputDir, `${pagePath}.md`)
719 const page = await readFile(pageFile, 'utf8')
720 const [head, ...signatures] = page.split('\n## Call Signature\n')
721 const isOverloaded = signatures.length > 1
722 const lastSignature = signatures.at(-1) ?? page
723​
724 // Property tables of the arguments whose type has a `## Properties` table, and of the result.
725 const tables: Array<{
726 id: string
727 title: string
728 table: string
729 parameter?: string
730 }> = []
731 const parametersHeading = lastSignature.match(/\n#{2,3} Parameters\n/)
732 const returnsHeading = lastSignature.match(/\n#{2,3} Returns\n/)
733 const parameters = parametersHeading
734 ? lastSignature.slice(
735 parametersHeading.index! + parametersHeading[0].length - 1,
736 returnsHeading?.index,
737 )
738 : ''
739 // Overloads describe the same arguments with different types, so a table missing from the
740 // last (most general) signature is taken from the latest earlier one that has it.
741 const signatureTypeLines = (signatures.length ? signatures : [page])
742 .map(signatureTypes)
743 .reverse()
744 for (const name of signatureTypeLines[0]!.parameters.keys()) {
745 const table = await findPropertiesTable(
746 outputDir,
747 signatureTypeLines.flatMap((types) => types.parameters.get(name) ?? []),
748 )
749 if (!table) {
750 continue
751 }
752 const argument = name.replace(/\\/g, '').replace(/\?$/, '')
753 const key = argument === '__namedParameters' ? 'props' : argument
754 tables.push({
755 id: `${key}-properties`,
756 title: `\`${key}\` properties`,
757 table,
758 parameter: name,
759 })
760 }
761 const resultTable = await findPropertiesTable(
762 outputDir,
763 signatureTypeLines.flatMap((types) => types.returns ?? []),
764 )
765 if (resultTable) {
766 tables.push({
767 id: 'result-properties',
768 title: 'Result properties',
769 table: resultTable,
770 })
771 }
772​
773 // Property anchors are prefixed with the table's name, so they stay unique when two tables on
774 // the same page list the same properties.
775 const section = (
776 level: number,
777 { id, title, table }: (typeof tables)[number],
778 ) =>
779 `<a id="${id}"></a>\n\n${'#'.repeat(level)} ${title}\n\n${table.replace(
780 /<a id="([^"]+)"><\/a>/g,
781 `<a id="${id.replace(/-properties$/, '')}-$1"></a>`,
782 )}`
783​
784 if (!isOverloaded) {
785 // Put each table at the end of the section it describes, so nothing is repeated.
786 let updated = page.trimEnd()
787 for (const entry of tables) {
788 const heading = entry.parameter
789 ? `\n### ${entry.parameter}\n`
790 : '\n## Returns\n'
791 const level = entry.parameter ? 3 : 2
792 const start = updated.indexOf(heading)
793 if (start === -1) {
794 continue
795 }
796 const next = updated
797 .slice(start + heading.length)
798 .search(new RegExp(`\\n#{1,${level}} `))
799 const insertAt =
800 next === -1 ? updated.length : start + heading.length + next
801 updated = `${updated.slice(0, insertAt).trimEnd()}\n\n${section(level + 1, entry)}\n${updated.slice(insertAt)}`
802 }
803 await writeFile(pageFile, `${updated.trimEnd()}\n`)
804 continue
805 }
806​
807 const entries = await Promise.all(
808 signatures.map(async (signature, index) => {
809 const code = signature.match(/```ts\n([\s\S]*?)\n```/)?.[1] ?? ''
810 const summary = signature
811 .split('\n### ')[0]!
812 .split('\n\n')
813 .map((block) => block.trim())
814 .find(
815 (block) =>
816 block !== '' &&
817 !block.startsWith('```') &&
818 !block.startsWith('Defined in:'),
819 )
820 const declared = await declaredSignatureTypes(signature)
821 const label = (
822 await Promise.all(
823 [
824 [
825 declared?.parameter,
826 code.match(/\((?:\w+\??): ([\s\S]*)/)?.[1],
827 ] as const,
828 [declared?.returns, code.match(/\): ([\s\S]*)/)?.[1]] as const,
829 ].map(async ([node, type]) =>
830 node
831 ? ((await declaredTypeLabel(outputDir, node)) ??
832 (type && typeNameInCode(outputDir, type)))
833 : type && typeNameInCode(outputDir, type),
834 ),
835 )
836 )
837 .filter(Boolean)
838 .map((type) => `\`${type}\``)
839 .join(' β†’ ')
840 return {
841 code,
842 line: `- [${label || `Call signature ${index + 1}`}](#call-signature-${index + 1})${summary ? `: ${summary.replace(/\n/g, ' ')}` : ''}`,
843 }
844 }),
845 )
846 // Repeat the last (most general) signature's `Parameters` and `Returns` once at the end, one
847 // heading level up, with the property tables, so every argument and the result are listed together.
848 const promote = (block: string) => block.replace(/^#(#+) /gm, '$1 ')
849 let parametersSummary = parametersHeading
850 ? `## Parameters\n\n${promote(parameters.trim())}`
851 : ''
852 for (const entry of tables.filter((table) => table.parameter)) {
853 const heading = `\n### ${entry.parameter}\n`
854 const start = parametersSummary.indexOf(heading)
855 if (start === -1) {
856 continue
857 }
858 const next = parametersSummary
859 .slice(start + heading.length)
860 .search(/\n#{1,3} /)
861 const insertAt =
862 next === -1 ? parametersSummary.length : start + heading.length + next
863 parametersSummary = `${parametersSummary.slice(0, insertAt).trimEnd()}\n\n${section(4, entry)}\n${parametersSummary.slice(insertAt)}`
864 }
865 const returnsBlock = returnsHeading
866 ? lastSignature
867 .slice(returnsHeading.index! + returnsHeading[0].length)
868 .split(/\n#{2,3} /)[0]!
869 .trim()
870 : ''
871 const resultEntry = tables.find((table) => !table.parameter)
872 const summaries = [
873 parametersSummary
874 ? `<a id="parameters-summary"></a>\n\n${parametersSummary.trimEnd()}`
875 : '',
876 returnsBlock
877 ? [
878 '<a id="returns-summary"></a>',
879 '',
880 '## Returns',
881 '',
882 returnsBlock,
883 ...(resultEntry ? ['', section(3, resultEntry)] : []),
884 ].join('\n')
885 : '',
886 ].filter(Boolean)
887 const links = [
888 ...(parametersSummary ? ['[Parameters](#parameters-summary)'] : []),
889 ...(returnsBlock ? ['[Returns](#returns-summary)'] : []),
890 ]
891 const overview = [
892 '## Overview',
893 '',
894 '```ts',
895 ...entries.map((entry) => entry.code),
896 '```',
897 '',
898 ...entries.map((entry) => entry.line),
899 ...(links.length > 0 ? ['', `See also: ${links.join(' Β· ')}`] : []),
900 ].join('\n')
901 const body = signatures
902 .map(
903 (signature, index) =>
904 `\n<a id="call-signature-${index + 1}"></a>\n\n## Call Signature\n${signature}`,
905 )
906 .join('')
907 .trimEnd()
908 const appended = summaries.join('\n\n')
909 await writeFile(
910 pageFile,
911 `${head!.trimEnd()}\n\n${overview}\n${body}${appended ? `\n\n${appended}` : ''}\n`,
912 )
913 }
915​
916const packages: Array<PackageReferenceDocsConfig> = [
917 {
918 entryPoints: [resolve(__dirname, '../packages/angular-query/src/index.ts')],
919 tsconfig: resolve(__dirname, '../packages/angular-query/tsconfig.json'),
920 outputDir: resolve(__dirname, '../docs/framework/angular/reference'),
921 },
922 {
923 entryPoints: [resolve(__dirname, '../packages/svelte-query/src/index.ts')],
924 tsconfig: resolve(__dirname, '../packages/svelte-query/tsconfig.json'),
925 outputDir: resolve(__dirname, '../docs/framework/svelte/reference'),
926 },
927 {
928 entryPoints: [resolve(__dirname, '../packages/solid-query/src/index.ts')],
929 tsconfig: resolve(__dirname, '../packages/solid-query/tsconfig.json'),
930 outputDir: resolve(__dirname, '../docs/framework/solid/reference'),
931 redirectFrom: {
932 'functions/infiniteQueryOptions': [
933 'framework/solid/reference/infiniteQueryOptions',
934 ],
935 'functions/mutationOptions': [
936 'framework/solid/reference/mutationOptions',
937 ],
938 'functions/queryOptions': ['framework/solid/reference/queryOptions'],
939 'functions/useInfiniteQuery': [
940 'framework/solid/reference/useInfiniteQuery',
941 ],
942 'functions/useIsFetching': ['framework/solid/reference/useIsFetching'],
943 'functions/useIsMutating': ['framework/solid/reference/useIsMutating'],
944 'functions/useMutation': ['framework/solid/reference/useMutation'],
945 'functions/useMutationState': [
946 'framework/solid/reference/useMutationState',
947 ],
948 'functions/useQueries': ['framework/solid/reference/useQueries'],
949 'functions/useQuery': ['framework/solid/reference/useQuery'],
950 },
951 },
952 {
953 entryPoints: [resolve(__dirname, '../packages/vue-query/src/index.ts')],
954 tsconfig: resolve(__dirname, '../packages/vue-query/tsconfig.json'),
955 outputDir: resolve(__dirname, '../docs/framework/vue/reference'),
956 redirectFrom: {
957 'functions/infiniteQueryOptions': [
958 'framework/vue/reference/infiniteQueryOptions',
959 ],
960 'functions/mutationOptions': ['framework/vue/reference/mutationOptions'],
961 'functions/queryOptions': ['framework/vue/reference/queryOptions'],
962 'functions/useInfiniteQuery': [
963 'framework/vue/reference/useInfiniteQuery',
964 ],
965 'functions/useIsFetching': ['framework/vue/reference/useIsFetching'],
966 'functions/useIsMutating': ['framework/vue/reference/useIsMutating'],
967 'functions/useMutation': ['framework/vue/reference/useMutation'],
968 'functions/useMutationState': [
969 'framework/vue/reference/useMutationState',
970 ],
971 'functions/usePrefetchInfiniteQuery': [
972 'framework/vue/reference/usePrefetchInfiniteQuery',
973 ],
974 'functions/usePrefetchQuery': [
975 'framework/vue/reference/usePrefetchQuery',
976 ],
977 'functions/useQueries': ['framework/vue/reference/useQueries'],
978 'functions/useQuery': ['framework/vue/reference/useQuery'],
979 'functions/useQueryClient': ['framework/vue/reference/useQueryClient'],
980 },
981 },
982 {
983 entryPoints: [resolve(__dirname, '../packages/react-query/src/index.ts')],
984 tsconfig: resolve(__dirname, '../packages/react-query/tsconfig.json'),
985 outputDir: resolve(__dirname, '../docs/framework/react/reference'),
986 redirectFrom: {
987 'functions/infiniteQueryOptions': [
988 'framework/react/reference/infiniteQueryOptions',
989 ],
990 'functions/mutationOptions': [
991 'framework/react/reference/mutationOptions',
992 ],
993 'functions/QueryClientProvider': [
994 'framework/react/reference/QueryClientProvider',
995 ],
996 'functions/QueryErrorResetBoundary': [
997 'framework/react/reference/QueryErrorResetBoundary',
998 ],
999 'functions/queryOptions': ['framework/react/reference/queryOptions'],
1000 'functions/useInfiniteQuery': [
1001 'framework/react/reference/useInfiniteQuery',
1002 ],
1003 'functions/useIsFetching': ['framework/react/reference/useIsFetching'],
1004 'functions/useIsMutating': ['framework/react/reference/useIsMutating'],
1005 'functions/useMutation': ['framework/react/reference/useMutation'],
1006 'functions/useMutationState': [
1007 'framework/react/reference/useMutationState',
1008 ],
1009 'functions/usePrefetchInfiniteQuery': [
1010 'framework/react/reference/usePrefetchInfiniteQuery',
1011 ],
1012 'functions/usePrefetchQuery': [
1013 'framework/react/reference/usePrefetchQuery',
1014 ],
1015 'functions/useQueries': ['framework/react/reference/useQueries'],
1016 'functions/useQuery': ['framework/react/reference/useQuery'],
1017 'functions/useQueryClient': ['framework/react/reference/useQueryClient'],
1018 'functions/useQueryErrorResetBoundary': [
1019 'framework/react/reference/useQueryErrorResetBoundary',
1020 ],
1021 'functions/useSuspenseInfiniteQuery': [
1022 'framework/react/reference/useSuspenseInfiniteQuery',
1023 ],
1024 'functions/useSuspenseQueries': [
1025 'framework/react/reference/useSuspenseQueries',
1026 ],
1027 'functions/useSuspenseQuery': [
1028 'framework/react/reference/useSuspenseQuery',
1029 ],
1030 // Redirects from the legacy hand-written docs/reference/*.md pages, removed in favor of
1031 // this generated reference.
1032 'classes/QueryClient': [
1033 'reference/QueryClient',
1034 'framework/react/reference/QueryClient',
1035 ],
1036 'classes/QueryCache': [
1037 'reference/QueryCache',
1038 'framework/react/reference/QueryCache',
1039 ],
1040 'classes/MutationCache': [
1041 'reference/MutationCache',
1042 'framework/react/reference/MutationCache',
1043 ],
1044 'classes/QueryObserver': [
1045 'reference/QueryObserver',
1046 'framework/react/reference/QueryObserver',
1047 ],
1048 'classes/InfiniteQueryObserver': [
1049 'reference/InfiniteQueryObserver',
1050 'framework/react/reference/InfiniteQueryObserver',
1051 ],
1052 'classes/QueriesObserver': [
1053 'reference/QueriesObserver',
1054 'framework/react/reference/QueriesObserver',
1055 ],
1056 // focusManager/onlineManager/timeoutManager are class instances, not object literals, so
1057 // TypeDoc can't inline their methods onto the `variables/*` instance page β€” the method docs
1058 // that the legacy pages covered now live on the `interfaces/*` page for the class itself.
1059 'interfaces/FocusManager': [
1060 'reference/focusManager',
1061 'framework/react/reference/focusManager',
1062 ],
1063 'interfaces/OnlineManager': [
1064 'reference/onlineManager',
1065 'framework/react/reference/onlineManager',
1066 ],
1067 'interfaces/TimeoutManager': ['reference/timeoutManager'],
1068 'variables/notifyManager': [
1069 'reference/notifyManager',
1070 'framework/react/reference/notifyManager',
1071 ],
1072 'variables/environmentManager': ['reference/environmentManager'],
1073 'functions/experimental_streamedQuery': ['reference/streamedQuery'],
1074 },
1075 },
1077 entryPoints: [resolve(__dirname, '../packages/preact-query/src/index.ts')],
1078 tsconfig: resolve(__dirname, '../packages/preact-query/tsconfig.json'),
1079 outputDir: resolve(__dirname, '../docs/framework/preact/reference'),
1080 },
1082 entryPoints: [resolve(__dirname, '../packages/lit-query/src/index.ts')],
1083 tsconfig: resolve(__dirname, '../packages/lit-query/tsconfig.json'),
1084 outputDir: resolve(__dirname, '../docs/framework/lit/reference'),
1085 simplifyLitQueriesControllerTypes: true,
1086 trimGeneratedMarkdown: true,
1087 },
1089​
1090for (const pkg of packages) {
1091 await generatePackageReferenceDocs(pkg)
1093​
1094console.log('\nβœ… All markdown files have been processed!')
1095​
1096process.exit(0)