Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

generate-api-reference.ts

889 lines27.4 KB

1import * as fs from "node:fs/promises";
2import * as path from "node:path";
3​
4import { Node, Project, type SourceFile } from "ts-morph";
5​
6const websiteRoot = path.join(import.meta.dir, "../website");
7​
8const config = {
9 srcRoot: path.join(import.meta.dir, "../packages/alchemy/src"),
10 outRoot: path.join(websiteRoot, "src/content/docs/providers"),
11 tsConfig: path.join(import.meta.dir, "../packages/alchemy/tsconfig.json"),
12};
13​
14interface FileEntry {
15 relativePath: string;
16 absolutePath: string;
18​
19interface ExampleBlock {
20 title: string;
21 body: string;
23​
24interface ExampleSection {
25 title: string;
26 description: string;
27 examples: ExampleBlock[];
29​
30interface PageDoc {
31 title: string;
32 relativePath: string;
33 summary: string;
34 sections: ExampleSection[];
36​
37const normalizeSlashes = (value: string) => value.split(path.sep).join("/");
38​
39async function discoverFiles(): Promise<FileEntry[]> {
40 const entries: FileEntry[] = [];
41​
42 const topLevelEntries = await fs.readdir(config.srcRoot, {
43 withFileTypes: true,
44 });
45 const dirs = topLevelEntries
46 .filter((entry) => entry.isDirectory())
47 .map((entry) => entry.name);
48​
49 for (const dir of dirs) {
50 const dirPath = path.join(config.srcRoot, dir);
51 let files: string[];
52 try {
53 files = (await fs.readdir(dirPath, { recursive: true })) as string[];
54 } catch {
55 continue;
56 }
57​
58 for (const file of files) {
59 const baseName = path.basename(file);
60 if (!baseName.endsWith(".ts") && !baseName.endsWith(".tsx")) continue;
61 if (baseName.endsWith(".d.ts")) continue;
62 if (baseName === "index.ts") continue;
63​
64 const relativePath = path.join(dir, file);
65 entries.push({
66 relativePath,
67 absolutePath: path.join(config.srcRoot, relativePath),
68 });
69 }
70 }
71​
72 entries.sort((a, b) => a.relativePath.localeCompare(b.relativePath));
73 return entries;
75​
76function getJsDocText(node: Node): string {
77 const getter = (node as Node & { getJsDocs?: () => { getText(): string }[] })
78 .getJsDocs;
79 if (!getter) return "";
80 return getter
81 .call(node)
82 .map((doc) => doc.getText())
83 .join("\n");
85​
86function cleanDocComment(raw: string): string {
87 return raw
88 .replace(/^\/\*\*?/, "")
89 .replace(/\*\/$/, "")
90 .split("\n")
91 .map((line) => line.replace(/^\s*\*\s?/, ""))
92 .join("\n");
94​
95interface ParsedJSDoc {
96 summary: string;
97 sections: ExampleSection[];
98 hasResourceTag: boolean;
99 hasBindingTag: boolean;
100 category: string;
101 product: string;
103​
104function parseJSDoc(node: Node): ParsedJSDoc {
105 const raw = getJsDocText(node);
106 if (!raw) {
107 return {
108 summary: "",
109 sections: [],
110 hasResourceTag: false,
111 hasBindingTag: false,
112 category: "",
113 product: "",
114 };
115 }
116​
117 const lines = cleanDocComment(raw).split("\n");
118​
119 const summaryLines: string[] = [];
120 const sections: ExampleSection[] = [];
121 let hasResourceTag = false;
122 let hasBindingTag = false;
123 let category = "";
124 let product = "";
125 let sawTag = false;
126 let currentSection: ExampleSection | undefined;
127 let currentExample: ExampleBlock | undefined;
128​
129 let sectionDescLines: string[] = [];
130 let collectingSectionDesc = false;
131 let insideFence = false;
132​
133 const flushExample = () => {
134 if (!currentExample) return;
135 currentExample.body = currentExample.body.trim();
136 if (!currentSection) {
137 currentSection = { title: "Examples", description: "", examples: [] };
138 sections.push(currentSection);
139 }
140 currentSection.examples.push(currentExample);
141 currentExample = undefined;
142 };
143​
144 const flushSectionDesc = () => {
145 if (currentSection && sectionDescLines.length > 0) {
146 currentSection.description = sectionDescLines.join("\n").trim();
147 }
148 sectionDescLines = [];
149 collectingSectionDesc = false;
150 };
151​
152 for (const line of lines) {
153 // Track fenced code blocks so an `@`-prefixed line inside an example
154 // (e.g. a decorator) is never mistaken for a JSDoc tag.
155 if (line.trim().startsWith("```")) {
156 insideFence = !insideFence;
157 }
158​
159 const tag = insideFence ? null : line.trim().match(/^@(\w+)\s*(.*)$/);
160 if (tag) {
161 sawTag = true;
162 const [, name, rest] = tag;
163 const value = (rest ?? "").trim();
164 switch (name) {
165 case "resource":
166 hasResourceTag = true;
167 break;
168 case "binding":
169 hasBindingTag = true;
170 break;
171 case "category":
172 case "group":
173 if (value) category = value;
174 break;
175 case "product":
176 case "label":
177 if (value) product = value;
178 break;
179 case "section":
180 flushExample();
181 flushSectionDesc();
182 currentSection = {
183 title: value || "Examples",
184 description: "",
185 examples: [],
186 };
187 sections.push(currentSection);
188 collectingSectionDesc = true;
189 break;
190 case "example":
191 flushSectionDesc();
192 flushExample();
193 currentExample = { title: value || "Example", body: "" };
194 break;
195 }
196 continue;
197 }
198​
199 if (!sawTag) {
200 summaryLines.push(line);
201 continue;
202 }
203​
204 if (currentExample) {
205 currentExample.body += `${line}\n`;
206 } else if (collectingSectionDesc) {
207 sectionDescLines.push(line);
208 }
209 }
210​
211 flushSectionDesc();
212 flushExample();
213​
214 return {
215 summary: summaryLines.join("\n").trim(),
216 sections,
217 hasResourceTag,
218 hasBindingTag,
219 category,
220 product,
221 };
223​
224function declName(node: Node): string {
225 if (Node.isVariableStatement(node)) {
226 return node.getDeclarations()[0]?.getName() ?? "";
227 }
228 if (
229 Node.isClassDeclaration(node) ||
230 Node.isInterfaceDeclaration(node) ||
231 Node.isTypeAliasDeclaration(node)
232 ) {
233 return node.getName() ?? "";
234 }
235 return "";
237​
238interface Primary {
239 name: string;
240 doc: ParsedJSDoc;
241 category: string;
242 product: string;
244​
245const hasContent = (doc: ParsedJSDoc) =>
246 Boolean(doc.summary) || doc.sections.length > 0;
247​
248/**
249 * Map a public export name back to its local declaration name when a file
250 * re-exports under an alias, e.g. `export { VpcLinkResource as VpcLink }`
251 * lets us find the documented `VpcLinkResource` const from the tagged
252 * `VpcLink` interface.
253 */
254function localNameForExport(
255 sourceFile: SourceFile,
256 publicName: string,
257): string | undefined {
258 for (const ed of sourceFile.getExportDeclarations()) {
259 if (ed.getModuleSpecifier()) continue;
260 for (const spec of ed.getNamedExports()) {
261 if (spec.getAliasNode()?.getText() === publicName) {
262 return spec.getNameNode().getText();
263 }
264 }
265 }
266 return undefined;
268​
269/**
270 * The page for a file is owned by the single exported declaration tagged
271 * `@resource` or `@binding`, and named after it. Authors sometimes write the
272 * docs (summary/@section/@example) on a sibling declaration of the same name
273 * (an `interface X` paired with `const X`) or on an internal const that is
274 * re-exported under the tagged name (the ApiGateway `XResource as X` pattern).
275 * When the tagged declaration itself has no content, pull it from that related
276 * declaration so the page isn't dropped as empty.
277 */
278function findTaggedPrimary(sourceFile: SourceFile): Primary | undefined {
279 const candidates: Node[] = [
280 ...sourceFile.getVariableStatements().filter((s) => s.isExported()),
281 ...sourceFile.getClasses().filter((c) => c.isExported()),
282 ...sourceFile.getInterfaces().filter((i) => i.isExported()),
283 ];
284​
285 for (const node of candidates) {
286 const doc = parseJSDoc(node);
287 if (!doc.hasResourceTag && !doc.hasBindingTag) continue;
288 const name = declName(node);
289 if (!name) continue;
290 const category = doc.category;
291 const product = doc.product;
292 if (hasContent(doc)) return { name, doc, category, product };
293​
294 // Tagged declaration has no prose — look for the related declaration that
295 // carries the docs (same name, or re-exported under this name).
296 const localName = localNameForExport(sourceFile, name);
297 const related: Node[] = [
298 ...sourceFile.getVariableStatements(),
299 ...sourceFile.getClasses(),
300 ...sourceFile.getInterfaces(),
301 ...sourceFile.getTypeAliases(),
302 ].filter((d) => {
303 if (d === node) return false;
304 const dn = declName(d);
305 return dn === name || (localName !== undefined && dn === localName);
306 });
307​
308 let best: ParsedJSDoc | undefined;
309 for (const d of related) {
310 const pd = parseJSDoc(d);
311 if (pd.sections.length > 0) {
312 best = pd;
313 break;
314 }
315 if (!best && pd.summary) best = pd;
316 }
317 return { name, doc: best ?? doc, category, product };
318 }
319 return undefined;
321​
322const LINK_TAG_RE = /\{@link\s+([^}]+)\}/g;
323​
324/** Split a `{@link ...}` tag's inner text into target + optional label. */
325function parseLinkTag(inner: string): { target: string; label?: string } {
326 const trimmed = inner.trim();
327 const pipe = trimmed.indexOf("|");
328 if (pipe !== -1) {
329 return {
330 target: trimmed.slice(0, pipe).trim(),
331 label: trimmed.slice(pipe + 1).trim() || undefined,
332 };
333 }
334 const space = trimmed.search(/\s/);
335 if (space !== -1) {
336 return {
337 target: trimmed.slice(0, space).trim(),
338 label: trimmed.slice(space + 1).trim() || undefined,
339 };
340 }
341 return { target: trimmed };
343​
344/**
345 * Reduce a typedoc-style `import("./Secrets.ts").Secrets` target to the bare
346 * symbol name — resolution (same-directory first) and display both want the
347 * name, not the module expression.
348 */
349function normalizeLinkTarget(target: string): string {
350 const match = target.match(/^import\((["'])[^"']+\1\)\.(.+)$/);
351 return match ? match[2] : target;
353​
354/** Resolves a `{@link}` symbol target to a generated page URL, if any. */
355type LinkResolver = (target: string) => string | undefined;
356​
357/**
358 * Build a per-page resolver factory. A symbol resolves to another generated
359 * page preferring (in order): a same-directory page named after it, a
360 * same-directory page whose source file exports it (an access-level service
361 * like `ReadNamespace` documented on its `ReadWriteNamespace` page), a unique
362 * name match within the same provider, a unique exporter within the same
363 * provider, then a unique global name match. Member suffixes
364 * (`Cluster#capacityProviders`), provider-qualified names (`Cloudflare.Worker`)
365 * and `FooProps` interfaces resolve to the base resource's page.
366 */
367function makeLinkResolverFactory(
368 pages: PageEntry[],
369): (fromDir: string) => LinkResolver {
370 const byName = new Map<string, PageEntry[]>();
371 const byExport = new Map<string, PageEntry[]>();
372 for (const p of pages) {
373 if (!byName.has(p.resource)) byName.set(p.resource, []);
374 byName.get(p.resource)!.push(p);
375 for (const name of p.exports) {
376 if (!byExport.has(name)) byExport.set(name, []);
377 byExport.get(name)!.push(p);
378 }
379 }
380 const providers = new Set(pages.map((p) => p.provider));
381​
382 return (fromDir: string) => {
383 const fromProvider = fromDir.split("/")[0] ?? "";
384​
385 const lookup = (
386 name: string,
387 provider?: string,
388 ): PageEntry | undefined => {
389 const scope = (list: PageEntry[] | undefined) =>
390 (list ?? []).filter((c) => !provider || c.provider === provider);
391 const named = scope(byName.get(name));
392 const exporting = scope(byExport.get(name));
393​
394 const sameDirNamed = named.filter((c) => c.dir === fromDir);
395 if (sameDirNamed.length === 1) return sameDirNamed[0];
396 const sameDirExporting = exporting.filter((c) => c.dir === fromDir);
397 if (sameDirExporting.length === 1) return sameDirExporting[0];
398 const providerNamed = named.filter((c) => c.provider === fromProvider);
399 if (providerNamed.length === 1) return providerNamed[0];
400 const providerExporting = exporting.filter(
401 (c) => c.provider === fromProvider,
402 );
403 if (providerExporting.length === 1) return providerExporting[0];
404 if (named.length === 1) return named[0];
405 return undefined;
406 };
407​
408 return (target: string) => {
409 // Strip a `#member` suffix — the link lands on the owning resource page.
410 const base = target.split("#")[0];
411​
412 const attempts: { name: string; provider?: string }[] = [{ name: base }];
413 if (base.includes(".")) {
414 const segments = base.split(".");
415 const first = segments[0];
416 const last = segments[segments.length - 1];
417 if (providers.has(first)) {
418 // Provider-qualified: `Cloudflare.Worker`, `Cloudflare.KV.Namespace`.
419 attempts.push({ name: last, provider: first });
420 } else {
421 // Member access on a symbol: `KeyPairProps.publicKeyMaterial`.
422 attempts.push({ name: first });
423 if (first.endsWith("Props")) {
424 attempts.push({ name: first.slice(0, -"Props".length) });
425 }
426 }
427 } else if (base.endsWith("Props")) {
428 attempts.push({ name: base.slice(0, -"Props".length) });
429 }
430​
431 for (const attempt of attempts) {
432 const found = lookup(attempt.name, attempt.provider);
433 if (found) return found.link;
434 }
435 return undefined;
436 };
437 };
439​
440const isUrl = (target: string) => /^https?:\/\//.test(target);
441​
442/**
443 * Replace `{@link ...}` tags with markdown links, skipping fenced code
444 * blocks. Symbols that don't resolve to a generated page render as inline
445 * code (or their label) instead of leaking the raw tag.
446 */
447/** Symbol targets that didn't resolve to a page, for the end-of-run summary. */
448const unresolvedLinkTargets = new Map<string, number>();
449​
450function linkifyMarkdown(markdown: string, resolve: LinkResolver): string {
451 const replaceTags = (chunk: string) =>
452 chunk.replace(LINK_TAG_RE, (_, inner: string) => {
453 // A tag wrapped across source lines carries the line break in its
454 // label — collapse it so the markdown link stays intact.
455 const parsed = parseLinkTag(inner.replace(/\s+/g, " "));
456 const label = parsed.label;
457 if (isUrl(parsed.target)) {
458 return `[${label ?? parsed.target}](${parsed.target})`;
459 }
460 const target = normalizeLinkTarget(parsed.target);
461 const url = resolve(target);
462 if (!url) {
463 unresolvedLinkTargets.set(
464 target,
465 (unresolvedLinkTargets.get(target) ?? 0) + 1,
466 );
467 }
468 const text = label ?? `\`${target}\``;
469 return url ? `[${text}](${url})` : text;
470 });
471​
472 // Apply across contiguous non-fence chunks (a `{@link}` may span lines);
473 // leave fenced code blocks untouched.
474 const out: string[] = [];
475 let chunk: string[] = [];
476 let insideFence = false;
477 const flushChunk = () => {
478 if (chunk.length > 0) {
479 out.push(replaceTags(chunk.join("\n")));
480 chunk = [];
481 }
482 };
483 for (const line of markdown.split("\n")) {
484 if (line.trim().startsWith("```")) {
485 if (!insideFence) flushChunk();
486 insideFence = !insideFence;
487 out.push(line);
488 continue;
489 }
490 if (insideFence) {
491 out.push(line);
492 } else {
493 chunk.push(line);
494 }
495 }
496 flushChunk();
497 return out.join("\n");
499​
500/** Reduce `{@link ...}` tags to plain text for frontmatter descriptions. */
501function stripLinkTags(text: string): string {
502 return text.replace(LINK_TAG_RE, (_, inner: string) => {
503 const { target, label } = parseLinkTag(inner.replace(/\s+/g, " "));
504 return (label ?? normalizeLinkTarget(target)).replace(/`/g, "");
505 });
507​
508function yamlString(value: string): string {
509 if (/[\n:"{}[\],&*?|>!%@`#]/.test(value) || value.trim() !== value) {
510 return JSON.stringify(value);
511 }
512 return value;
514​
515function firstParagraph(value: string): string {
516 const idx = value.indexOf("\n\n");
517 const para = idx === -1 ? value : value.slice(0, idx);
518 return para.replace(/\s+/g, " ").trim();
520​
521function renderPageBody(doc: PageDoc): string {
522 const parts: string[] = [];
523​
524 if (doc.summary) {
525 parts.push(doc.summary);
526 }
527​
528 for (const section of doc.sections) {
529 const secParts = [`## ${section.title}`];
530 if (section.description) {
531 secParts.push(section.description);
532 }
533 for (const example of section.examples) {
534 if (section.examples.length > 1) {
535 secParts.push(`**${example.title}**`);
536 }
537 secParts.push(example.body);
538 }
539 parts.push(secParts.join("\n\n"));
540 }
541​
542 return parts.join("\n\n");
544​
545function renderPage(doc: PageDoc, resolve: LinkResolver): string {
546 const sourcePath = `src/${normalizeSlashes(doc.relativePath)}`;
547 const description =
548 stripLinkTags(firstParagraph(doc.summary)) ||
549 `API reference for ${doc.title}`;
550 const frontmatter = [
551 "---",
552 `title: ${yamlString(doc.title)}`,
553 `description: ${yamlString(description)}`,
554 "---",
555 ].join("\n");
556​
557 const sourceBlock = `> **Source:** \`${sourcePath}\``;
558 const body = linkifyMarkdown(renderPageBody(doc).trim(), resolve);
559​
560 if (body) {
561 return `${frontmatter}\n\n${sourceBlock}\n\n${body}\n`;
562 }
563 return `${frontmatter}\n\n${sourceBlock}\n`;
565​
566/** Providers shown first in the sidebar; the rest follow alphabetically. */
567const PROVIDER_ORDER = ["AWS", "Cloudflare"];
568​
569/**
570 * Uncategorized providers with at most this many pages render as a flat
571 * resource list instead of per-service folders (see buildProvidersSidebar).
572 */
573const FLAT_PROVIDER_MAX_PAGES = 16;
574​
575interface SidebarLeaf {
576 label: string;
577 link: string;
579interface SidebarGroup {
580 label: string;
581 collapsed: true;
582 items: SidebarItem[];
584type SidebarItem = SidebarLeaf | SidebarGroup;
585​
586interface PageEntry {
587 provider: string;
588 service: string;
589 resource: string;
590 category: string;
591 product: string;
592 link: string;
593 /** Source directory relative to srcRoot (slash-normalized), e.g. `Cloudflare/KV`. */
594 dir: string;
595 /** All names the page's source file exports — `{@link}` targets documented on this page. */
596 exports: string[];
598​
599const byLabel = (a: { label: string }, b: { label: string }) =>
600 a.label.localeCompare(b.label);
601​
602function orderedKeys(keys: string[], order: string[]): string[] {
603 const ranked = keys.filter((k) => order.includes(k));
604 ranked.sort((a, b) => order.indexOf(a) - order.indexOf(b));
605 const rest = keys.filter((k) => !order.includes(k)).sort();
606 return [...ranked, ...rest];
608​
609/**
610 * Build sidebar items for one set of pages sharing a provider+category:
611 * every product is its own collapsible folder containing its resource
612 * pages, mirroring how Cloudflare's API reference gives each product its
613 * own section — even single-page products like D1 or Organization — so
614 * the grouping is uniform.
615 *
616 * Grouping is by resolved product LABEL (`@product`, falling back to the
617 * service dir name), not by directory: two directories declaring the same
618 * product merge into one group instead of rendering duplicate siblings.
619 */
620function buildServiceItems(pages: PageEntry[]): SidebarItem[] {
621 const byLabelKey = new Map<string, PageEntry[]>();
622 for (const p of pages) {
623 const key = p.product || p.service || p.resource;
624 if (!byLabelKey.has(key)) byLabelKey.set(key, []);
625 byLabelKey.get(key)!.push(p);
626 }
627 const items: SidebarItem[] = [];
628 for (const [label, productPages] of byLabelKey) {
629 items.push({
630 label,
631 collapsed: true,
632 items: productPages
633 .map((p) => ({ label: p.resource, link: p.link }))
634 .sort(byLabel),
635 });
636 }
637 return items.sort(byLabel);
639​
640function buildProvidersSidebar(entries: PageEntry[]): SidebarItem[] {
641 const byProvider = new Map<string, PageEntry[]>();
642 for (const e of entries) {
643 if (!byProvider.has(e.provider)) byProvider.set(e.provider, []);
644 byProvider.get(e.provider)!.push(e);
645 }
646​
647 const providers: SidebarGroup[] = [];
648 for (const provider of orderedKeys([...byProvider.keys()], PROVIDER_ORDER)) {
649 const pages = byProvider.get(provider)!;
650​
651 // `@category` is per-file; a documented file that omits it must not fall
652 // out of its service's category and render a duplicate service group at
653 // the provider root. Inherit the category any sibling page of the same
654 // service dir declares.
655 const categoryByService = new Map<string, string>();
656 for (const p of pages) {
657 if (p.service && p.category && !categoryByService.has(p.service)) {
658 categoryByService.set(p.service, p.category);
659 }
660 }
661​
662 const categorized = new Map<string, PageEntry[]>();
663 const uncategorized: PageEntry[] = [];
664 for (const p of pages) {
665 const category = p.category || categoryByService.get(p.service) || "";
666 if (category) {
667 if (!categorized.has(category)) categorized.set(category, []);
668 categorized.get(category)!.push(p);
669 } else {
670 uncategorized.push(p);
671 }
672 }
673​
674 const items: SidebarItem[] = [];
675 for (const cat of [...categorized.keys()].sort((a, b) =>
676 a.localeCompare(b),
677 )) {
678 items.push({
679 label: cat,
680 collapsed: true,
681 items: buildServiceItems(categorized.get(cat)!),
682 });
683 }
684 if (categorized.size === 0 && pages.length <= FLAT_PROVIDER_MAX_PAGES) {
685 // Small uncategorized providers (Neon, Planetscale, Axiom, GitHub, …)
686 // render as a flat resource list — per-service folders around one or
687 // two pages ("Branch > Branch") are redundant nesting, and prefixed
688 // resource names (MySQLBranch/PostgresBranch) already carry the
689 // grouping information.
690 items.push(
691 ...uncategorized
692 .map((p) => ({ label: p.resource, link: p.link }))
693 .sort(byLabel),
694 );
695 } else {
696 // Pages without a category fall back to service grouping directly under
697 // the provider (this is how AWS renders until it gets categorized).
698 items.push(...buildServiceItems(uncategorized));
699 }
700​
701 providers.push({ label: provider, collapsed: true, items });
702 }
703​
704 assertNoDuplicateSiblings(providers, []);
705 return providers;
707​
708/**
709 * Duplicate sibling labels are always a tagging bug (e.g. two products
710 * resolving to the same name in one category) and render as confusing
711 * twin sections — fail the generation instead of shipping them.
712 */
713function assertNoDuplicateSiblings(items: SidebarItem[], path: string[]) {
714 const seen = new Map<string, number>();
715 for (const item of items) {
716 seen.set(item.label, (seen.get(item.label) ?? 0) + 1);
717 }
718 const dups = [...seen.entries()].filter(([, n]) => n > 1);
719 if (dups.length > 0) {
720 throw new Error(
721 `Duplicate sidebar sibling label(s) under "${path.join(" > ") || "(root)"}": ${dups
722 .map(([label, n]) => `"${label}" ×${n}`)
723 .join(", ")} — fix the @product/@category tags on the offending files.`,
724 );
725 }
726 for (const item of items) {
727 if ("items" in item) {
728 assertNoDuplicateSiblings(item.items, [...path, item.label]);
729 }
730 }
732​
733async function main() {
734 const entries = await discoverFiles();
735 console.log(`Discovered ${entries.length} source files.`);
736​
737 const project = new Project({
738 tsConfigFilePath: config.tsConfig,
739 skipFileDependencyResolution: true,
740 });
741​
742 await fs.rm(config.outRoot, { recursive: true, force: true });
743 await fs.mkdir(config.outRoot, { recursive: true });
744​
745 const seen = new Map<string, string>();
746 const pageEntries: PageEntry[] = [];
747 const pending: { outputRelative: string; doc: PageDoc }[] = [];
748 let written = 0;
749 let skipped = 0;
750​
751 for (const entry of entries) {
752 const sourceFile = project.getSourceFile(entry.absolutePath);
753 if (!sourceFile) {
754 console.warn(` skipped (not in project): ${entry.relativePath}`);
755 skipped++;
756 continue;
757 }
758​
759 const primary = findTaggedPrimary(sourceFile);
760 if (!primary) {
761 skipped++;
762 continue;
763 }
764​
765 // Only emit a page when there's actual documented content; a bare
766 // frontmatter + source link stub is noise.
767 if (!primary.doc.summary && primary.doc.sections.length === 0) {
768 skipped++;
769 continue;
770 }
771​
772 // Mirror the source directory structure; name the page after the
773 // tagged declaration (e.g. Cloudflare.AI.Search/AiSearchInstance.md).
774 const relDir = path.dirname(entry.relativePath);
775 const outputRelative = path.join(relDir, `${primary.name}.md`);
776​
777 const existing = seen.get(outputRelative);
778 if (existing) {
779 console.warn(
780 ` collision: ${outputRelative} from ${entry.relativePath} (already from ${existing})`,
781 );
782 }
783 seen.set(outputRelative, entry.relativePath);
784​
785 const doc: PageDoc = {
786 title: primary.name,
787 relativePath: entry.relativePath,
788 summary: primary.doc.summary,
789 sections: primary.doc.sections,
790 };
791 pending.push({ outputRelative, doc });
792​
793 let exportNames: string[] = [];
794 try {
795 exportNames = [...sourceFile.getExportedDeclarations().keys()];
796 } catch {
797 // Unresolvable re-exports — page-name resolution still applies.
798 }
799​
800 const segments = normalizeSlashes(outputRelative).split("/");
801 pageEntries.push({
802 provider: segments[0] ?? "",
803 service: segments.length > 2 ? segments[1] : "",
804 resource: primary.name,
805 category: primary.category,
806 product: primary.product,
807 link: `/providers/${normalizeSlashes(outputRelative)
808 .replace(/\.md$/, "")
809 .toLowerCase()}`,
810 dir: normalizeSlashes(relDir),
811 exports: exportNames,
812 });
813 }
814​
815 // Second pass: render with `{@link}` resolution — the full page set must be
816 // known before symbol targets can resolve to their pages.
817 const resolverFor = makeLinkResolverFactory(pageEntries);
818 for (const page of pending) {
819 const resolve = resolverFor(
820 normalizeSlashes(path.dirname(page.outputRelative)),
821 );
822 const outputPath = path.join(config.outRoot, page.outputRelative);
823 await fs.mkdir(path.dirname(outputPath), { recursive: true });
824 await fs.writeFile(outputPath, renderPage(page.doc, resolve), "utf8");
825 written++;
826 }
827​
828 const sidebar = buildProvidersSidebar(pageEntries);
829​
830 // Landing page for the Reference tab (/providers): a provider directory.
831 // Each provider's reference belongs to its docs hub — the directory just
832 // routes there (or into the tree, for providers without a hub). The
833 // ProviderDirectory component reads the generated sidebar for counts.
834 // Regenerated with the rest of the tree on every run.
835 const referenceIndex = [
836 "---",
837 "title: API Reference",
838 "description: Every provider alchemy can manage — pick a provider to open its docs hub and resource reference.",
839 "---",
840 "",
841 'import ProviderDirectory from "../../../components/ProviderDirectory.astro";',
842 "",
843 "Every resource alchemy can manage, documented from the source JSDoc and",
844 "organized by provider. A provider's reference lives in its docs hub —",
845 "pick one below, or search with `⌘K`.",
846 "",
847 "<ProviderDirectory />",
848 "",
849 ].join("\n");
850 await fs.rm(path.join(config.outRoot, "index.md"), { force: true });
851 await fs.writeFile(
852 path.join(config.outRoot, "index.mdx"),
853 referenceIndex,
854 "utf8",
855 );
856​
857 const sidebarPath = path.join(
858 websiteRoot,
859 "src/generated/providers-sidebar.json",
860 );
861 await fs.mkdir(path.dirname(sidebarPath), { recursive: true });
862 await fs.writeFile(
863 sidebarPath,
864 `${JSON.stringify(sidebar, null, 2)}\n`,
865 "utf8",
866 );
867​
868 console.log(
869 `Done. Wrote ${written} resource pages (skipped ${skipped} untagged) to ${normalizeSlashes(
870 path.relative(path.join(import.meta.dir, ".."), config.outRoot),
871 )}.`,
872 );
873 if (unresolvedLinkTargets.size > 0) {
874 const list = [...unresolvedLinkTargets.entries()]
875 .sort((a, b) => b[1] - a[1])
876 .map(([target, n]) => (n > 1 ? `${target} ×${n}` : target))
877 .join(", ");
878 console.log(
879 `{@link} targets without a page (rendered as inline code): ${list}`,
880 );
881 }
882 console.log(
883 `Wrote provider sidebar to ${normalizeSlashes(
884 path.relative(path.join(import.meta.dir, ".."), sidebarPath),
885 )}.`,
886 );
888​
889await main();