forked from CopilotKit/CopilotKit
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdocs-render.tsx
More file actions
1723 lines (1603 loc) · 65.4 KB
/
Copy pathdocs-render.tsx
File metadata and controls
1723 lines (1603 loc) · 65.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Shared helpers for rendering MDX docs pages. Pulled out of
// `app/docs/[[...slug]]/page.tsx` so both the classic `/docs/<slug>`
// route and the new `/<framework>/<slug>` catch-all can share the same
// nav-tree builder, snippet inliner, and component map.
//
// Only the pieces that don't depend on the rendered React tree live
// here; the big `components` map still lives alongside the docs page
// for now so it can import client components without circular issues.
import fs from "fs";
import path from "path";
import matter from "gray-matter";
import { resolveWithinDir } from "./safe-fs";
import { getDocsMode } from "./registry";
import { isRouteGroupSegment } from "./route-groups";
export const CONTENT_DIR = path.join(process.cwd(), "src/content/docs");
export const SNIPPETS_DIR = path.join(CONTENT_DIR, "..", "snippets");
// Re-exported from lib/framework-categories so client components can
// pull the constant without dragging fs through the bundle.
export {
FRAMEWORK_CATEGORY_ORDER,
type FrameworkCategory,
} from "./framework-categories";
// ---------------------------------------------------------------------------
// Nav tree types
// ---------------------------------------------------------------------------
export type NavNode =
| { type: "page"; title: string; slug: string; icon?: string }
| { type: "section"; title: string; icon?: string }
| {
type: "group";
title: string;
slug: string;
children: NavNode[];
defaultOpen?: boolean;
icon?: string;
};
// Section headers (the all-caps separators) carry the only icons in
// the sidebar — top-level visual scaffolding. Title comparison is
// case-insensitive so meta.json edits don't need to match this map's
// capitalization exactly. Update keys here when section names change
// in `content/docs/meta.json`.
//
// Includes both the agnostic root sections AND per-framework
// `docs_mode: "authored"` sections (e.g. Built-in Agent's own IA,
// whose meta.json lives at
// `content/docs/integrations/built-in-agent/meta.json`). Authored
// frameworks don't merge into the root tree, so they need their own
// section names registered here to receive icons — otherwise the
// section header renders without a glyph and looks visually distinct
// from the generated-mode sidebars.
const SECTION_ICONS: Record<string, string> = {
// Agnostic root sections (`content/docs/meta.json`).
"get started": "lucide/Rocket",
concepts: "lucide/BookOpen",
"build chat uis": "lucide/MessageSquare",
"build generative ui": "lucide/Paintbrush",
"add agent powers": "lucide/Wand2",
runtime: "lucide/Cpu",
"observe & operate": "lucide/SearchCheck",
enterprise: "custom/copilotkit-kite",
deploy: "lucide/Cloud",
other: "lucide/MoreHorizontal",
// Built-in Agent (authored) sections — match the section names in
// `content/docs/integrations/built-in-agent/meta.json`. Adjust here
// when those section labels change in that meta.json.
"getting started": "lucide/Rocket",
basics: "lucide/BookOpen",
"generative ui": "lucide/Paintbrush",
"app control": "lucide/WandSparkles",
"built-in agent": "lucide/Bot",
backend: "lucide/Server",
"premium features": "custom/copilotkit-kite",
tutorials: "lucide/ListChecks",
troubleshooting: "lucide/LifeBuoy",
};
export function sectionIconFor(title: string): string | undefined {
return SECTION_ICONS[title.toLowerCase()];
}
/**
* Extract the frontmatter block (content between leading `---` fences)
* from a raw MDX/Markdown source. Returns empty string when the file
* has no frontmatter. Used to scope frontmatter regexes so we don't
* accidentally match `title:` or `description:` that happen to appear
* inside the MDX body.
*/
function extractFrontmatter(raw: string): string {
// Accept both LF and CRLF line endings so Windows-authored MDX
// doesn't silently bypass frontmatter extraction.
const fmMatch = raw.match(/^---\r?\n([\s\S]*?)\r?\n---/);
return fmMatch?.[1] ?? "";
}
// Escape text for safe interpolation into an HTML attribute/text context.
// Duplicated here (rather than imported from components/snippet.tsx) to
// keep docs-render server-only / framework-free — snippet.tsx is a
// client component and importing it here would pull client code into
// the server bundle. If this ever grows, extract to a shared util.
export function escapeHtml(s: string): string {
return s
.replace(/&/g, "&")
.replace(/</g, "<")
.replace(/>/g, ">")
.replace(/"/g, """)
.replace(/'/g, "'");
}
// Process-scoped memoization for frequently-called filesystem readers.
// buildNavTree walks the entire content tree on every page render and
// calls readTitle / readMeta O(pages) times per request. Without this
// cache each call reopens and re-parses the file from disk.
//
// Production / build: cache the entire process lifetime — content is
// frozen at deploy time so stale reads aren't possible.
//
// Development: skip the cache so meta.json / frontmatter edits show up
// in the sidebar nav without restarting the dev server. The
// performance hit is acceptable for local dev (the request path
// already does plenty of fs work for MDX rendering).
//
// Memory footprint in production: titles are tiny strings, meta is a
// small JSON object — negligible even with hundreds of docs files.
const isDev = process.env.NODE_ENV === "development";
const titleCache = new Map<string, string | null>();
const metaCache = new Map<
string,
{ title?: string; pages?: string[]; root?: boolean } | null
>();
// Tree-level cache. Even with title/meta cached, `buildNavTree` still
// allocates ~200 NavNode objects per call and is invoked from every
// page render (sometimes twice in the same render via DocsPageView +
// the route's own pageTree). Keying on `${dir}|${prefix}` makes
// repeated calls return the same array reference. Dev mode skips it
// so meta.json edits propagate without a restart.
const navTreeCache = new Map<string, NavNode[]>();
export function readTitle(filePath: string): string | null {
const cacheKey = path.resolve(filePath);
if (!isDev && titleCache.has(cacheKey)) return titleCache.get(cacheKey)!;
if (!fs.existsSync(filePath)) {
titleCache.set(cacheKey, null);
return null;
}
let raw: string;
try {
raw = fs.readFileSync(filePath, "utf-8");
} catch (err) {
// A single bad file / permission error used to crash the whole
// page render. Log loudly and cache a null so we don't retry on
// every nav build in the same process.
console.error("[docs-render] failed to read", filePath, err);
titleCache.set(cacheKey, null);
return null;
}
// Restrict frontmatter matches to the frontmatter block so we don't
// grab a `title:` line that lives inside an MDX body (e.g. inside a
// code sample or example config). Falls back to the first H1 when no
// frontmatter title is set.
const fm = extractFrontmatter(raw);
const fmMatch = fm.match(/^title:\s*["']?(.+?)["']?\s*$/m);
let title: string | null = null;
if (fmMatch) {
title = fmMatch[1].replace(/["']$/, "");
} else {
const headingMatch = raw.match(/^#\s+(.+)$/m);
if (headingMatch) title = headingMatch[1];
}
titleCache.set(cacheKey, title);
return title;
}
// Read the `icon:` field from an MDX file's frontmatter. Mirrors
// `readTitle` so the icon survives the same caching / extraction story
// (frontmatter-scoped regex, dev cache bypass). Returns the raw spec
// string (e.g. `"lucide/Paintbrush"`); the bridge resolves it to a
// React element when building the PageTree.
export function readIcon(filePath: string): string | null {
const cacheKey = `icon:${path.resolve(filePath)}`;
if (!isDev && titleCache.has(cacheKey)) return titleCache.get(cacheKey)!;
if (!fs.existsSync(filePath)) {
titleCache.set(cacheKey, null);
return null;
}
let raw: string;
try {
raw = fs.readFileSync(filePath, "utf-8");
} catch {
titleCache.set(cacheKey, null);
return null;
}
const fm = extractFrontmatter(raw);
const match = fm.match(/^icon:\s*["']?(.+?)["']?\s*$/m);
const icon = match ? match[1].replace(/["']$/, "") : null;
titleCache.set(cacheKey, icon);
return icon;
}
// A meta.json `pages` entry is either a string (page slug, section
// header `---Title---`, or spread `...folder`) or an inline-folder
// object: `{ title, pages, defaultOpen?, icon? }`. Inline folders let
// a parent meta.json declare a folder grouping without moving the
// underlying MDX files into a subdirectory — useful for visual
// grouping inside a single content tier.
export type MetaPageEntry =
| string
| {
title: string;
pages: MetaPageEntry[];
defaultOpen?: boolean;
icon?: string;
};
export function readMeta(dir: string): {
title?: string;
pages?: MetaPageEntry[];
root?: boolean;
icon?: string;
} | null {
const metaPath = path.join(dir, "meta.json");
const cacheKey = path.resolve(metaPath);
if (!isDev && metaCache.has(cacheKey)) return metaCache.get(cacheKey)!;
if (!fs.existsSync(metaPath)) {
metaCache.set(cacheKey, null);
return null;
}
try {
const parsed = JSON.parse(fs.readFileSync(metaPath, "utf-8"));
metaCache.set(cacheKey, parsed);
return parsed;
} catch (err) {
// Previously swallowed silently — a malformed meta.json rendered
// as "no nav ordering" with zero signal. Log loudly so authors
// see the offending path and parse error. Cache the null so we
// don't re-parse a bad file on every call.
console.error("[docs-render] failed to parse", metaPath, err);
metaCache.set(cacheKey, null);
return null;
}
}
export function buildNavTree(dir: string, prefix: string = ""): NavNode[] {
const cacheKey = `${path.resolve(dir)}|${prefix}`;
if (!isDev) {
const cached = navTreeCache.get(cacheKey);
if (cached) return cached;
}
const tree = buildNavTreeInner(dir, prefix);
if (!isDev) navTreeCache.set(cacheKey, tree);
return tree;
}
function buildNavTreeInner(dir: string, prefix: string): NavNode[] {
const meta = readMeta(dir);
if (!meta) return buildNavTreeFromFilesystem(dir, prefix);
const pages = meta.pages;
if (!pages || !Array.isArray(pages)) {
return buildNavTreeFromFilesystem(dir, prefix);
}
return parseMetaPages(dir, prefix, pages);
}
// Parse a meta.json `pages` array into NavNodes. Recursive: inline-folder
// objects re-enter via the recursive call so the inner page syntax stays
// identical to the surrounding tree.
function parseMetaPages(
dir: string,
prefix: string,
pages: MetaPageEntry[],
): NavNode[] {
const nodes: NavNode[] = [];
for (const entry of pages) {
// Inline-folder object: `{ title, pages, defaultOpen?, icon? }`.
// Lets a meta.json declare a folder grouping without moving its
// MDX files into a subdirectory. The inner pages re-enter this
// same parser (via the recursive call below) so the syntax inside
// an inline folder is identical to the surrounding tree.
if (typeof entry === "object" && entry !== null) {
const children = parseMetaPages(dir, prefix, entry.pages);
if (children.length > 0) {
nodes.push({
type: "group",
title: entry.title,
// No backing directory — slug is purely a stable key for
// sidebar React reconciliation. Prefix it so the React key
// doesn't collide with a real folder of the same name.
slug: `${prefix}#${entry.title}`,
children,
defaultOpen: entry.defaultOpen,
icon: entry.icon,
});
}
continue;
}
const sectionMatch = entry.match(/^---(.+)---$/);
if (sectionMatch) {
const title = sectionMatch[1];
nodes.push({ type: "section", title, icon: sectionIconFor(title) });
continue;
}
if (entry.startsWith("[")) continue;
const spreadMatch = entry.match(/^\.\.\.(.+)$/);
if (spreadMatch) {
const subDir = path.join(dir, spreadMatch[1]);
const subPrefix = prefix ? `${prefix}/${spreadMatch[1]}` : spreadMatch[1];
if (fs.existsSync(subDir) && fs.statSync(subDir).isDirectory()) {
const subMeta = readMeta(subDir);
if (subMeta?.root) continue;
const subChildren = buildNavTree(subDir, subPrefix);
if (subChildren.length > 0) {
const rawGroupTitle =
subMeta?.title ||
spreadMatch[1].replace(/[()-]/g, " ").replace(/\s+/g, " ").trim();
const groupTitle =
rawGroupTitle.charAt(0).toUpperCase() + rawGroupTitle.slice(1);
// If the previous emitted node is a section header with the
// same title as this group's title, the section header
// already labels this content. Suppress the group title
// (empty string) so the renderer skips rendering it — the
// group still wraps its children for indentation/nesting.
// Without this dedup the sidebar shows "BUILD GENERATIVE UI"
// (section, uppercase) followed immediately by "Build
// Generative UI" (group, regular case) — same text, doubled.
const prev = nodes[nodes.length - 1];
const isDuplicateOfSection =
prev?.type === "section" && prev.title === groupTitle;
nodes.push({
type: "group",
title: isDuplicateOfSection ? "" : groupTitle,
slug: subPrefix,
children: subChildren,
icon: subMeta?.icon,
});
}
}
continue;
}
const slug = prefix ? `${prefix}/${entry}` : entry;
const mdxFile = path.join(dir, `${entry}.mdx`);
const indexFile = path.join(dir, entry, "index.mdx");
const subDir = path.join(dir, entry);
// Special case: a literal `"index"` entry in a folder's meta.json
// represents the folder's root page (URL = `/<folder>` with no
// trailing slug). Always emit a page node — even when `index.mdx`
// doesn't yet exist on disk — so the framework override nav can
// rewrite it onto the bare `/<framework>` URL where the data-driven
// `FrameworkOverview` renders. Title falls back to "Introduction"
// when no MDX is present to read from. `buildFrameworkOverridesNav`
// handles the final slug rewrite (`"index"` → `""`).
if (entry === "index") {
const title = fs.existsSync(mdxFile)
? readTitle(mdxFile) || "Introduction"
: "Introduction";
// At the docs root (no prefix), `"index"` represents the bare
// `/` page (the unscoped docs landing). Rewrite the slug to ""
// so the bridge builds `/` rather than `/index`. Inside a
// sub-folder, `"index"` keeps the folder-relative slug (e.g.
// `agentic-protocols/index`) and `buildFrameworkOverridesNav`
// handles the final framework-scoped rewrite separately.
const indexSlug = prefix ? slug : "";
const icon = fs.existsSync(mdxFile) ? readIcon(mdxFile) : null;
nodes.push({
type: "page",
title,
slug: indexSlug,
icon: icon ?? undefined,
});
continue;
}
if (fs.existsSync(mdxFile)) {
const title =
readTitle(mdxFile) || entry.split("/").pop()!.replace(/-/g, " ");
const icon = readIcon(mdxFile);
nodes.push({ type: "page", title, slug, icon: icon ?? undefined });
} else if (fs.existsSync(subDir) && fs.statSync(subDir).isDirectory()) {
const subMeta = readMeta(subDir);
if (subMeta?.root) continue;
const subPrefix = prefix ? `${prefix}/${entry}` : entry;
if (subMeta?.pages) {
const subChildren = buildNavTree(subDir, subPrefix);
const groupTitle = subMeta.title || entry.replace(/-/g, " ");
nodes.push({
type: "group",
title: groupTitle.charAt(0).toUpperCase() + groupTitle.slice(1),
slug: subPrefix,
children: subChildren,
icon: subMeta.icon,
});
} else if (fs.existsSync(indexFile)) {
const title =
readTitle(indexFile) || subMeta?.title || entry.replace(/-/g, " ");
const icon = readIcon(indexFile);
nodes.push({
type: "page",
title,
slug: subPrefix,
icon: icon ?? undefined,
});
} else {
const subChildren = buildNavTreeFromFilesystem(subDir, subPrefix);
if (subChildren.length > 0) {
const groupTitle = subMeta?.title || entry.replace(/-/g, " ");
nodes.push({
type: "group",
title: groupTitle.charAt(0).toUpperCase() + groupTitle.slice(1),
slug: subPrefix,
children: subChildren,
});
}
}
} else if (fs.existsSync(indexFile)) {
const title = readTitle(indexFile) || entry.replace(/-/g, " ");
nodes.push({ type: "page", title, slug });
}
}
return nodes;
}
export function buildNavTreeFromFilesystem(
dir: string,
prefix: string,
): NavNode[] {
if (!fs.existsSync(dir)) return [];
const nodes: NavNode[] = [];
let entries: fs.Dirent[];
try {
entries = fs.readdirSync(dir, { withFileTypes: true });
} catch (err) {
// Permission denied / ENOTDIR / etc. Log and return an empty tree
// rather than crashing every docs page render downstream.
console.error("[docs-render] failed to read dir", dir, err);
return [];
}
for (const entry of entries) {
if (entry.name.startsWith(".") || entry.name === "meta.json") continue;
if (entry.name.startsWith("(")) continue;
const slug = prefix
? `${prefix}/${entry.name.replace(".mdx", "")}`
: entry.name.replace(".mdx", "");
if (entry.isDirectory()) {
const subMeta = readMeta(path.join(dir, entry.name));
if (subMeta?.root) continue;
const subChildren = buildNavTree(path.join(dir, entry.name), slug);
if (subChildren.length > 0) {
const groupTitle = subMeta?.title || entry.name.replace(/-/g, " ");
nodes.push({
type: "group",
title: groupTitle.charAt(0).toUpperCase() + groupTitle.slice(1),
slug,
children: subChildren,
});
}
} else if (entry.name.endsWith(".mdx") && entry.name !== "index.mdx") {
const title =
readTitle(path.join(dir, entry.name)) ||
entry.name.replace(".mdx", "").replace(/-/g, " ");
nodes.push({ type: "page", title, slug });
}
}
return nodes;
}
/**
* Walk `content/docs/integrations/<folder>/` and return NavNodes for
* pages that have NO root equivalent. These are framework-specific
* topics (e.g. Built-in Agent's `copilot-runtime`, LangGraph's `auth`
* and `subgraphs`) that live only in the per-framework tree and need
* their own sidebar entries. Pages that duplicate root files are
* skipped — root wins, and the framework view already renders the
* root MDX with a framework override.
*
* Takes the resolved folder name (not the URL slug). Callers should
* use `getDocsFolder(slug)` from lib/registry to map language/runtime
* variants to their shared folder (e.g. langgraph-python / typescript
* / fastapi → `langgraph/`).
*/
export function buildFrameworkOverridesNav(folder: string): NavNode[] {
const frameworkDir = path.join(CONTENT_DIR, "integrations", folder);
if (!fs.existsSync(frameworkDir)) return [];
const nodes = buildNavTree(frameworkDir, `integrations/${folder}`);
// Drop entries whose equivalent root file exists. Root wins when
// both are present — the per-framework tree is only an escape hatch
// for framework-specific topics, not an alternative rendering.
const prefix = `integrations/${folder}/`;
const rewriteSlug = (slug: string): string => {
const stripped = slug.replace(prefix, "");
if (stripped === "index") return "";
if (stripped.endsWith("/index")) return stripped.slice(0, -"/index".length);
return stripped;
};
const rootEquivalentExists = (slug: string): boolean => {
const rootSlug = rewriteSlug(slug);
if (rootSlug === "") return false;
const rootMdx = path.join(CONTENT_DIR, `${rootSlug}.mdx`);
const rootIndex = path.join(CONTENT_DIR, rootSlug, "index.mdx");
return fs.existsSync(rootMdx) || fs.existsSync(rootIndex);
};
const rewriteNode = (node: NavNode): NavNode | null => {
if (node.type === "page") {
if (rootEquivalentExists(node.slug)) return null;
return { ...node, slug: rewriteSlug(node.slug) };
}
if (node.type === "group") {
const children = node.children
.map(rewriteNode)
.filter((child): child is NavNode => child !== null);
if (children.length > 0) {
return { ...node, slug: rewriteSlug(node.slug), children };
}
return null;
}
// Intentionally drop section nodes. Per-framework meta.json files
// tend to mirror the root tree's sections ("Getting Started",
// "Basics", etc.) and flowing them through here would (a) collide
// with root sections of the same name on React keys and (b) double
// up the visual hierarchy — the override block is already wrapped
// in a single `{frameworkName}` section by mergeFrameworkNav.
return null;
};
const filtered = nodes
.map(rewriteNode)
.filter((node): node is NavNode => node !== null);
// Flatten empty-title wrapper groups. buildNavTree clears the title on
// a spread-derived group when the preceding section header has the
// same name (so the renderer doesn't double-print "Generative UI").
// After we drop section headers above, those wrappers are left as
// titleless containers that only add an extra indent step around
// their children. Inline the children at the wrapper's level instead.
const flattened: NavNode[] = [];
for (const node of filtered) {
if (node.type === "group" && node.title === "") {
flattened.push(...node.children);
} else {
flattened.push(node);
}
}
return flattened;
}
/**
* Build a sidebar that contains ONLY the per-framework MDX tree
* (no merge with root nav, no root-equivalent filtering). Authored
* integrations use this because their `integrations/<folder>/meta.json`
* is the source of truth for page order and section grouping.
*
* Slugs are rewritten to drop the `integrations/<folder>/` prefix and
* the literal `index` → "" rewrite, so links resolve at
* `/<framework>/<topic>` and the framework root at `/<framework>`.
*/
export function buildFrameworkOnlyNav(folder: string): NavNode[] {
const frameworkDir = path.join(CONTENT_DIR, "integrations", folder);
if (!fs.existsSync(frameworkDir)) return [];
const nodes = buildNavTree(frameworkDir, `integrations/${folder}`);
const prefix = `integrations/${folder}/`;
// Recursive slug rewrite so nested groups (e.g. `human-in-the-loop/`,
// `premium/`) also get the prefix stripped from their children.
//
// Two `index` cases need rewriting:
// 1. Top-level `index` → "" so the framework-root entry resolves to
// `/<framework>` (not `/<framework>/index`).
// 2. Nested `<group>/index` → `<group>` so a folder's own root page
// (e.g. `human-in-the-loop/index.mdx`) resolves to
// `/<framework>/human-in-the-loop` (the folder URL), not
// `/<framework>/human-in-the-loop/index` which 404s. Without
// this rewrite the sidebar links into folder-root pages dead-end.
const rewrite = (node: NavNode): NavNode => {
if (node.type === "page") {
const stripped = node.slug.replace(prefix, "");
let slug = stripped;
if (stripped === "index") slug = "";
else if (stripped.endsWith("/index"))
slug = stripped.slice(0, -"/index".length);
return { ...node, slug };
}
if (node.type === "group") {
const stripped = node.slug.replace(prefix, "");
return {
...node,
slug: stripped,
children: node.children.map(rewrite),
};
}
return node;
};
return appendSharedRootSections(nodes.map(rewrite));
}
const SHARED_ROOT_SECTIONS = ["Platforms"];
function sectionRange(
navTree: NavNode[],
sectionTitle: string,
): { start: number; end: number } | null {
const start = navTree.findIndex(
(node) =>
node.type === "section" &&
node.title.toLowerCase() === sectionTitle.toLowerCase(),
);
if (start === -1) return null;
const nextSection = navTree.findIndex(
(node, index) => index > start && node.type === "section",
);
return { start, end: nextSection === -1 ? navTree.length : nextSection };
}
function hasPageSlug(navTree: NavNode[], slug: string): boolean {
return navTree.some((node) => {
if (node.type === "page") return node.slug === slug;
if (node.type === "group") return hasPageSlug(node.children, slug);
return false;
});
}
function filterMissingPages(node: NavNode, navTree: NavNode[]): NavNode | null {
if (node.type === "page") {
return hasPageSlug(navTree, node.slug) ? null : node;
}
if (node.type === "group") {
const children = node.children
.map((child) => filterMissingPages(child, navTree))
.filter((child): child is NavNode => child !== null);
return children.length > 0 ? { ...node, children } : null;
}
return node;
}
/**
* Authored framework sidebars own their page order, but some root docs
* sections are global product guidance rather than framework IA. Keep
* those shared sections in every framework sidebar without duplicating
* entries across each authored integration's meta.json.
*/
function appendSharedRootSections(navTree: NavNode[]): NavNode[] {
let nextNavTree = navTree;
const rootNavTree = buildNavTree(CONTENT_DIR);
for (const sectionTitle of SHARED_ROOT_SECTIONS) {
const rootRange = sectionRange(rootNavTree, sectionTitle);
if (!rootRange) continue;
const section = rootNavTree[rootRange.start];
const missingNodes = rootNavTree
.slice(rootRange.start + 1, rootRange.end)
.map((node) => filterMissingPages(node, nextNavTree))
.filter((node): node is NavNode => node !== null);
if (missingNodes.length === 0) continue;
const existingRange = sectionRange(nextNavTree, sectionTitle);
if (existingRange) {
nextNavTree = [
...nextNavTree.slice(0, existingRange.end),
...missingNodes,
...nextNavTree.slice(existingRange.end),
];
} else {
nextNavTree = [...nextNavTree, section, ...missingNodes];
}
}
return nextNavTree;
}
// Map a framework slug to the section-header icon spec used by the
// sidebar bridge. LangGraph variants (-python, -typescript, -fastapi)
// share the LangGraph mark; other integrations have no custom mark yet
// and fall back to no icon. Extend as we ship more.
export function frameworkSectionIcon(framework: string): string | undefined {
if (framework.startsWith("langgraph")) return "custom/langgraph";
return undefined;
}
/**
* Merge per-framework overrides into the root nav tree. The override
* block is inserted as a labeled section right after the agent-control
* section in the root ordering.
*
* Authored and generated frameworks both use this merged shell so the
* sidebar information architecture is stable across framework switches.
* Content resolution still decides whether a given slug renders authored
* MDX first or the generated/root page first.
*/
export function mergeFrameworkNav(
rootNav: NavNode[],
overrideNav: NavNode[],
frameworkName: string,
frameworkIcon?: string,
): NavNode[] {
if (overrideNav.length === 0) return rootNav;
// Pull the framework-root page (the "Introduction" entry from
// integrations/<folder>/meta.json's literal "index" slot —
// buildFrameworkOverridesNav rewrites its slug to "") out of the override
// nav so we can place it inside the global "Get Started" section instead
// of stranding it above all section headers as a top-level prefix.
const introIdx = overrideNav.findIndex(
(n) => n.type === "page" && n.slug === "",
);
const introNode = introIdx >= 0 ? overrideNav[introIdx] : null;
const remainingOverrideNav =
introIdx >= 0
? [...overrideNav.slice(0, introIdx), ...overrideNav.slice(introIdx + 1)]
: overrideNav;
const sectionHeader: NavNode = {
type: "section",
title: frameworkName,
icon: frameworkIcon,
};
const isSection = (n: NavNode, title: string) =>
n.type === "section" && n.title.toLowerCase() === title.toLowerCase();
// Section names tried in priority order. The first match wins; the
// override block is inserted right before the *next* section header
// after the matched anchor. Update this list when the JTBD section
// names change in content/docs/meta.json.
const ANCHOR_CANDIDATES = [
"add agent powers",
"give your app agent powers",
"app control",
"agents & backends",
"backend",
"runtime",
];
let insertAt = -1;
for (const anchor of ANCHOR_CANDIDATES) {
const anchorIdx = rootNav.findIndex((n) => isSection(n, anchor));
if (anchorIdx === -1) continue;
for (let i = anchorIdx + 1; i < rootNav.length; i++) {
if (rootNav[i].type === "section") {
insertAt = i;
break;
}
}
if (insertAt !== -1) break;
}
// Reconcile the rootNav's existing root-level introduction with the
// framework's own introNode. At a framework view we want exactly one
// Introduction entry, and it should link to the framework root.
const rootHasIntro = rootNav.some((n) => n.type === "page" && n.slug === "");
const rootNavWithIntro = (() => {
if (!introNode) return rootNav;
if (rootHasIntro) {
return rootNav.map((n) =>
n.type === "page" && n.slug === "" ? introNode : n,
);
}
const getStartedIdx = rootNav.findIndex((n) => isSection(n, "get started"));
if (getStartedIdx === -1) return [introNode, ...rootNav];
return [
...rootNav.slice(0, getStartedIdx + 1),
introNode,
...rootNav.slice(getStartedIdx + 1),
];
})();
if (insertAt === -1) {
return [...rootNavWithIntro, sectionHeader, ...remainingOverrideNav];
}
const getStartedIdx = rootNav.findIndex((n) => isSection(n, "get started"));
const prepended = !!introNode && !rootHasIntro && getStartedIdx === -1;
const splicedAfterAnchor =
!!introNode &&
!rootHasIntro &&
getStartedIdx !== -1 &&
insertAt > getStartedIdx;
const adjustedInsertAt =
prepended || splicedAfterAnchor ? insertAt + 1 : insertAt;
return [
...rootNavWithIntro.slice(0, adjustedInsertAt),
sectionHeader,
...remainingOverrideNav,
...rootNavWithIntro.slice(adjustedInsertAt),
];
}
/**
* Build the framework-scoped sidebar IA used by generated framework
* routes. Generated docs share the root docs IA and layer sparse
* framework-specific overrides into that tree.
*/
export function buildFrameworkNav(
docsFolder: string,
frameworkName: string,
frameworkSlug: string,
): NavNode[] {
return mergeFrameworkNav(
buildNavTree(CONTENT_DIR),
buildFrameworkOverridesNav(docsFolder),
frameworkName,
frameworkSectionIcon(frameworkSlug),
);
}
/**
* Return the list of framework slugs whose `integrations/<folder>/`
* tree contains an MDX file for `slugPath`. Matches either
* `<slug>.mdx` or `<slug>/index.mdx`. Used by the framework-scoped
* router to detect that a topic is available in *some* framework but
* not the one the user is currently viewing, so we can render a
* helpful "not available for <X>" page instead of a bare 404.
*
* Most slugs map 1:1 to their folder, but language/runtime variants
* share one folder (langgraph-python/typescript/fastapi → `langgraph/`,
* ms-agent-dotnet/python → `microsoft-agent-framework/`) and two
* legacy slugs were renamed after the folder existed (google-adk →
* `adk/`, strands → `aws-strands/`). The caller supplies the
* slug→folder resolver so this helper stays decoupled from the registry's
* docs-folder mapping.
*
* `docs_mode: hidden` frameworks are filtered out — the "Try X, Y, Z"
* suggestion surfaces would otherwise dead-end on a 404 (those frameworks
* have no `/<slug>` route by design).
*/
export function findFrameworksWithPage(
slugPath: string,
integrationSlugs: readonly string[],
slugToFolder: (slug: string) => string,
): string[] {
const matches: string[] = [];
for (const slug of integrationSlugs) {
if (getDocsMode(slug) === "hidden") continue;
const folder = slugToFolder(slug);
const mdx = path.join(
CONTENT_DIR,
"integrations",
folder,
`${slugPath}.mdx`,
);
const indexMdx = path.join(
CONTENT_DIR,
"integrations",
folder,
slugPath,
"index.mdx",
);
if (fs.existsSync(mdx) || fs.existsSync(indexMdx)) matches.push(slug);
}
return matches;
}
// ---------------------------------------------------------------------------
// Snippet inlining (same rules as the docs page)
// ---------------------------------------------------------------------------
// Maps `<ComponentName />` MDX references to the relative snippet file
// under SNIPPETS_DIR. Keys are JSX component names (PascalCase) and
// must match EXACTLY what authors write in MDX — they are not
// filesystem paths and are case-sensitive on both sides of the map.
//
// Aliases (same target under multiple keys) are intentional and exist
// because the codebase historically shipped both spellings:
// - `AgUI` / `AGUI` — two legal casings; keep both
// so authors writing either render correctly. Upstream consumers
// reach this via SUBPATH_TO_COMPONENT which uses `AGUI`.
// - `FrontendTools` / `FrontEndToolsImpl` — historical name kept
// for backward compat with existing MDX that still uses
// `<FrontEndToolsImpl />` (confirmed in live docs content). Don't
// collapse these without first rewriting all .mdx references.
//
// Filename casing: `migrate-to-1.10.X.mdx` and `migrate-to-1.8.2.mdx`
// match the on-disk files exactly (uppercase X in 1.10.X), verified
// against src/content/snippets/shared/troubleshooting/.
export const SNIPPET_MAP: Record<string, string> = {
A2UI: "shared/generative-ui/a2ui.mdx",
AgUI: "shared/backend/ag-ui.mdx",
AGUI: "shared/backend/ag-ui.mdx", // alias of AgUI
BuildWithAgents: "shared/guides/build-with-agents.mdx",
CodingAgents: "shared/coding-agents.mdx",
CommonIssues: "shared/troubleshooting/common-issues.mdx",
CopilotRuntime: "copilot-runtime.mdx",
CustomAgent: "shared/backend/custom-agent.mdx",
DebugMode: "shared/troubleshooting/debug-mode.mdx",
DisplayOnly: "shared/generative-ui/display-only.mdx",
ErrorDebugging: "shared/troubleshooting/error-debugging.mdx",
FrontendTools: "shared/app-control/frontend-tools.mdx",
FrontEndToolsImpl: "shared/app-control/frontend-tools.mdx", // alias of FrontendTools
GenerativeUISpecsOverview: "shared/generative-ui-specs-overview.mdx",
HeadlessUI: "shared/basics/headless-ui.mdx",
Inspector: "shared/premium/inspector.mdx",
Interactive: "shared/generative-ui/interactive.mdx",
MCPApps: "shared/generative-ui/mcp-apps.mdx",
MCPSetup: "shared/guides/mcp-server-setup.mdx",
MigrateTo1100: "shared/troubleshooting/migrate-to-1.10.X.mdx",
MigrateTo182: "shared/troubleshooting/migrate-to-1.8.2.mdx",
MigrateToV2: "shared/troubleshooting/migrate-to-v2.mdx",
Observability: "shared/premium/observability.mdx",
ObservabilityConnectors:
"shared/troubleshooting/observability-connectors.mdx",
Overview: "shared/premium/overview.mdx",
PrebuiltComponents: "shared/basics/prebuilt-components.mdx",
ProgrammaticControl: "shared/basics/programmatic-control.mdx",
ReasoningMessages:
"shared/guides/custom-look-and-feel/reasoning-messages.mdx",
SelfHosting: "shared/premium/self-hosting.mdx",
Slots: "shared/basics/slots.mdx",
Threads: "shared/threads/threads.mdx",
ToolRenderer: "shared/generative-ui/tool-rendering.mdx", // alias of ToolRendering
ToolRendering: "shared/generative-ui/tool-rendering.mdx",
DefaultToolRendering: "shared/guides/default-tool-rendering.mdx",
// Versionless aliases retained for backward compat with older MDX that
// emits `<MigrateTo />` / `<MigrateToV />`; both resolve to v2.
MigrateTo: "shared/troubleshooting/migrate-to-v2.mdx",
MigrateToV: "shared/troubleshooting/migrate-to-v2.mdx",
CopilotUI: "copilot-ui.mdx",
LandingCodeShowcase: "landing-code-showcase.mdx",
UseAgentSnippet: "use-agent.mdx",
InstallSDKSnippet: "install-sdk.mdx",
InstallPythonSDK: "install-python-sdk.mdx",
RunAndConnect: "coagents/run-and-connect-agent.mdx",
RunAndConnectSnippet: "coagents/run-and-connect-agent.mdx", // alias of RunAndConnect
CopilotCloudConfigureCopilotKitProvider:
"copilot-cloud-configure-copilotkit-provider.mdx",
// Historical spelling (no `Provider` suffix) still appears in tutorials.
CopilotCloudConfigureCopilotKit:
"copilot-cloud-configure-copilotkit-provider.mdx",
SelfHostingCopilotRuntimeCreateEndpoint:
"self-hosting-copilot-runtime-create-endpoint.mdx",
SelfHostingCopilotRuntimeConfigureCopilotKitProvider:
"self-hosting-copilot-runtime-configure-copilotkit-provider.mdx",
SelfHostingCopilotRuntimeConfigureCopilotKit:
"self-hosting-copilot-runtime-configure-copilotkit-provider.mdx",
};
export const SUBPATH_TO_COMPONENT: Record<string, string> = {
"ag-ui": "AGUI",
"build-with-agents": "CodingAgents",
"copilot-runtime": "CopilotRuntime",
"custom-look-and-feel/headless-ui": "HeadlessUI",
"custom-look-and-feel/slots": "Slots",
"frontend-tools": "FrontendTools",
"generative-ui/a2ui": "A2UI",
"generative-ui/mcp-apps": "MCPApps",
"generative-ui/tool-rendering": "ToolRendering",
"generative-ui/your-components/display-only": "DisplayOnly",
"generative-ui/your-components/interactive": "Interactive",
inspector: "Inspector",
"prebuilt-components": "PrebuiltComponents",
"programmatic-control": "ProgrammaticControl",
"premium/headless-ui": "HeadlessUI",
"premium/observability": "Observability",
"premium/overview": "Overview",
"troubleshooting/common-issues": "CommonIssues",
"troubleshooting/error-debugging": "ErrorDebugging",
"troubleshooting/migrate-to-1.10.X": "MigrateTo1100",
"troubleshooting/migrate-to-1.8.2": "MigrateTo182",
"troubleshooting/migrate-to-v2": "MigrateToV2",
"troubleshooting/observability-connectors": "ObservabilityConnectors",
};
/**
* Strip leading `import ...` statements from an MDX source WITHOUT
* touching lines inside fenced code blocks. Previously we ran
* `/^import\s+.+$/gm` over the whole source, which mangled real code
* samples like `import os` inside python fences. This implementation
* walks the source line-by-line, tracks fence state with ``` / ~~~,
* and only strips `import` lines that appear at the top of the file
* (before the first non-import, non-blank content line). Import lines
* that appear *later* in the prose are also preserved — the only ones
* we want to remove are MDX's JSX component imports, which always sit
* in the top-of-file block.
*
* Covered by: snippet contents that include a Python/JS code fence
* with an `import` statement must have the `import` preserved in the
* rendered output.
*/
export function stripLeadingImports(source: string): string {
const lines = source.split("\n");
const out: string[] = [];
let inFence = false;
let fenceMarker: string | null = null;
let pastHeader = false;
// When an `import { ... }` is split across lines, the opening line
// matches the single-line drop rule but the continuation lines
// (` Foo,`, `} from "...";`) do not — historically those continuation
// lines fell into the content branch and flipped `pastHeader = true`,
// which then preserved every subsequent import in the MDX body and
// produced runtime errors like `<p>{Tab}</p>`. Track an open import