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

generate-docs.ts

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