doccupine 0.0.140 → 0.0.141

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (145) hide show
  1. package/README.md +14 -7
  2. package/dist/cli.d.ts +1 -0
  3. package/dist/cli.js +191 -0
  4. package/dist/index.d.ts +3 -7
  5. package/dist/index.js +5 -1894
  6. package/dist/lib/config-manager.d.ts +1 -0
  7. package/dist/lib/config-manager.js +63 -3
  8. package/dist/lib/generated-artifacts.d.ts +26 -0
  9. package/dist/lib/generated-artifacts.js +147 -0
  10. package/dist/lib/layout.js +30 -30
  11. package/dist/lib/metadata.js +58 -30
  12. package/dist/lib/openapi-types.d.ts +2 -2
  13. package/dist/lib/openapi.d.ts +6 -3
  14. package/dist/lib/openapi.js +330 -50
  15. package/dist/lib/output-safety.d.ts +15 -0
  16. package/dist/lib/output-safety.js +428 -0
  17. package/dist/lib/structures.js +11 -0
  18. package/dist/lib/utils.d.ts +10 -5
  19. package/dist/lib/utils.js +108 -5
  20. package/dist/mdx-to-nextjs-generator.d.ts +166 -0
  21. package/dist/mdx-to-nextjs-generator.js +2229 -0
  22. package/dist/templates/app/api/gate/route.d.ts +1 -1
  23. package/dist/templates/app/api/gate/route.js +18 -6
  24. package/dist/templates/app/api/mcp/route.d.ts +1 -1
  25. package/dist/templates/app/api/mcp/route.js +181 -111
  26. package/dist/templates/app/api/playground/route.d.ts +1 -1
  27. package/dist/templates/app/api/playground/route.js +45 -13
  28. package/dist/templates/app/api/rag/route.d.ts +1 -1
  29. package/dist/templates/app/api/rag/route.js +72 -20
  30. package/dist/templates/app/api/search/route.d.ts +1 -1
  31. package/dist/templates/app/api/search/route.js +5 -0
  32. package/dist/templates/app/robots.d.ts +1 -1
  33. package/dist/templates/app/robots.js +1 -26
  34. package/dist/templates/app/theme.d.ts +1 -1
  35. package/dist/templates/app/theme.js +31 -19
  36. package/dist/templates/components/Chat.d.ts +1 -1
  37. package/dist/templates/components/Chat.js +342 -34
  38. package/dist/templates/components/SearchDocs.d.ts +1 -1
  39. package/dist/templates/components/SearchDocs.js +63 -11
  40. package/dist/templates/components/SearchModalContent.d.ts +1 -1
  41. package/dist/templates/components/SearchModalContent.js +191 -49
  42. package/dist/templates/components/SideBar.d.ts +1 -1
  43. package/dist/templates/components/SideBar.js +8 -2
  44. package/dist/templates/components/layout/Accordion.d.ts +1 -1
  45. package/dist/templates/components/layout/Accordion.js +26 -3
  46. package/dist/templates/components/layout/Badge.d.ts +1 -1
  47. package/dist/templates/components/layout/Badge.js +1 -1
  48. package/dist/templates/components/layout/Button.d.ts +1 -1
  49. package/dist/templates/components/layout/Button.js +4 -4
  50. package/dist/templates/components/layout/Callout.d.ts +1 -1
  51. package/dist/templates/components/layout/Callout.js +6 -6
  52. package/dist/templates/components/layout/Card.d.ts +1 -1
  53. package/dist/templates/components/layout/Card.js +9 -4
  54. package/dist/templates/components/layout/CherryThemeProvider.d.ts +1 -1
  55. package/dist/templates/components/layout/CherryThemeProvider.js +63 -12
  56. package/dist/templates/components/layout/Code.d.ts +1 -1
  57. package/dist/templates/components/layout/Code.js +5 -5
  58. package/dist/templates/components/layout/CopyButton.d.ts +1 -1
  59. package/dist/templates/components/layout/CopyButton.js +1 -1
  60. package/dist/templates/components/layout/DemoTheme.d.ts +1 -1
  61. package/dist/templates/components/layout/DemoTheme.js +8 -28
  62. package/dist/templates/components/layout/DocsComponents.d.ts +1 -1
  63. package/dist/templates/components/layout/DocsComponents.js +57 -6
  64. package/dist/templates/components/layout/GlobalStyles.d.ts +1 -1
  65. package/dist/templates/components/layout/GlobalStyles.js +15 -9
  66. package/dist/templates/components/layout/Prompt.d.ts +1 -1
  67. package/dist/templates/components/layout/Prompt.js +4 -7
  68. package/dist/templates/components/layout/Steps.d.ts +1 -1
  69. package/dist/templates/components/layout/Steps.js +7 -1
  70. package/dist/templates/components/layout/Tabs.d.ts +1 -1
  71. package/dist/templates/components/layout/Tabs.js +108 -19
  72. package/dist/templates/env.example.d.ts +1 -1
  73. package/dist/templates/env.example.js +11 -0
  74. package/dist/templates/eslint.config.d.ts +1 -1
  75. package/dist/templates/eslint.config.js +20 -0
  76. package/dist/templates/gitignore.d.ts +1 -1
  77. package/dist/templates/gitignore.js +4 -3
  78. package/dist/templates/lib/access.d.ts +1 -0
  79. package/dist/templates/lib/access.js +41 -0
  80. package/dist/templates/mdx/ai-assistant.mdx.d.ts +1 -1
  81. package/dist/templates/mdx/ai-assistant.mdx.js +17 -1
  82. package/dist/templates/mdx/api-playground.mdx.d.ts +1 -1
  83. package/dist/templates/mdx/api-playground.mdx.js +5 -3
  84. package/dist/templates/mdx/authentication.mdx.d.ts +1 -1
  85. package/dist/templates/mdx/authentication.mdx.js +5 -3
  86. package/dist/templates/mdx/commands.mdx.d.ts +1 -1
  87. package/dist/templates/mdx/commands.mdx.js +20 -6
  88. package/dist/templates/mdx/components.mdx.d.ts +1 -1
  89. package/dist/templates/mdx/components.mdx.js +3 -0
  90. package/dist/templates/mdx/deployment-and-hosting.mdx.d.ts +1 -1
  91. package/dist/templates/mdx/deployment-and-hosting.mdx.js +2 -2
  92. package/dist/templates/mdx/globals.mdx.d.ts +1 -1
  93. package/dist/templates/mdx/globals.mdx.js +14 -11
  94. package/dist/templates/mdx/model-context-protocol.mdx.d.ts +1 -1
  95. package/dist/templates/mdx/model-context-protocol.mdx.js +22 -35
  96. package/dist/templates/mdx/platform/ai-assistant.mdx.d.ts +1 -1
  97. package/dist/templates/mdx/platform/ai-assistant.mdx.js +23 -0
  98. package/dist/templates/mdx/platform/api-playground.mdx.d.ts +1 -1
  99. package/dist/templates/mdx/platform/api-playground.mdx.js +7 -0
  100. package/dist/templates/mdx/platform/authentication.mdx.d.ts +1 -0
  101. package/dist/templates/mdx/platform/authentication.mdx.js +63 -0
  102. package/dist/templates/mdx/platform/import-from-github.mdx.d.ts +1 -1
  103. package/dist/templates/mdx/platform/import-from-github.mdx.js +2 -2
  104. package/dist/templates/mdx/platform/index.mdx.d.ts +1 -1
  105. package/dist/templates/mdx/platform/index.mdx.js +1 -0
  106. package/dist/templates/mdx/platform/mcp.mdx.d.ts +1 -1
  107. package/dist/templates/mdx/platform/mcp.mdx.js +2 -1
  108. package/dist/templates/mdx/platform/navigation-settings.mdx.d.ts +1 -1
  109. package/dist/templates/mdx/platform/navigation-settings.mdx.js +12 -1
  110. package/dist/templates/mdx/platform/publishing.mdx.d.ts +1 -1
  111. package/dist/templates/mdx/platform/publishing.mdx.js +43 -10
  112. package/dist/templates/mdx/platform/self-updating-docs.mdx.d.ts +1 -1
  113. package/dist/templates/mdx/platform/self-updating-docs.mdx.js +48 -9
  114. package/dist/templates/mdx/sections.mdx.d.ts +1 -1
  115. package/dist/templates/mdx/sections.mdx.js +4 -0
  116. package/dist/templates/mdx/space.mdx.d.ts +1 -0
  117. package/dist/templates/mdx/space.mdx.js +125 -0
  118. package/dist/templates/mdx/tabs.mdx.d.ts +1 -1
  119. package/dist/templates/mdx/tabs.mdx.js +4 -0
  120. package/dist/templates/next.config.js +20 -8
  121. package/dist/templates/package.js +3 -3
  122. package/dist/templates/prettierignore.d.ts +1 -1
  123. package/dist/templates/prettierignore.js +1 -0
  124. package/dist/templates/proxy.js +47 -19
  125. package/dist/templates/scripts/build-docs-index.d.ts +1 -1
  126. package/dist/templates/scripts/build-docs-index.js +1 -0
  127. package/dist/templates/services/mcp/docsContentStub.d.ts +1 -0
  128. package/dist/templates/services/mcp/docsContentStub.js +1 -0
  129. package/dist/templates/services/mcp/server.d.ts +1 -1
  130. package/dist/templates/services/mcp/server.js +140 -83
  131. package/dist/templates/services/mcp/tools.d.ts +1 -1
  132. package/dist/templates/services/mcp/tools.js +65 -137
  133. package/dist/templates/utils/playgroundAllowlist.d.ts +1 -1
  134. package/dist/templates/utils/playgroundAllowlist.js +13 -4
  135. package/dist/templates/utils/rateLimit.d.ts +1 -1
  136. package/dist/templates/utils/rateLimit.js +40 -3
  137. package/dist/templates/utils/requestBody.d.ts +1 -0
  138. package/dist/templates/utils/requestBody.js +56 -0
  139. package/dist/templates/utils/ssrfGuard.d.ts +1 -1
  140. package/dist/templates/utils/ssrfGuard.js +138 -33
  141. package/package.json +14 -9
  142. package/dist/lib/mdxToMarkdown.d.ts +0 -1
  143. package/dist/lib/mdxToMarkdown.js +0 -134
  144. package/dist/templates/mdx/image-and-embeds.mdx.d.ts +0 -1
  145. package/dist/templates/mdx/image-and-embeds.mdx.js +0 -118
@@ -0,0 +1,2229 @@
1
+ import chokidar from "chokidar";
2
+ import fs from "fs-extra";
3
+ import { constants } from "node:fs";
4
+ import { open } from "node:fs/promises";
5
+ import path from "path";
6
+ import chalk from "chalk";
7
+ import { appStructure, obsoleteFiles, startingDocsStructure, } from "./lib/structures.js";
8
+ import { rootLayoutTemplate, siteLayoutTemplate } from "./lib/layout.js";
9
+ import { normalizeOpenApiConfig, validateConfig, } from "./lib/config-manager.js";
10
+ import { GeneratedArtifacts } from "./lib/generated-artifacts.js";
11
+ import { claimOutputDirectory, isPathInside, resolveOutputPath, resolveWithin, } from "./lib/output-safety.js";
12
+ import { OpenApiRegistry, DEFAULT_API_BASE_SLUG, buildEndpointDoc, slugifySegment, } from "./lib/openapi.js";
13
+ import { generateSlug, getFullSlug, escapeTemplateContent, toJsStringLiteral, safeMatter, writeFileAtomic, } from "./lib/utils.js";
14
+ import { generateMetadataBlock, generateRuntimeOnlyMetadataBlock, generateJsonLdScript, } from "./lib/metadata.js";
15
+ import { parseUpdateBlocks } from "./lib/rss.js";
16
+ import { nextConfigTemplate } from "./templates/next.config.js";
17
+ import { pnpmWorkspaceTemplate } from "./templates/pnpmWorkspace.js";
18
+ import { proxyTemplate } from "./templates/proxy.js";
19
+ import { robotsTemplate } from "./templates/app/robots.js";
20
+ import { rssRouteTemplate } from "./templates/app/rssRoute.js";
21
+ import { sitemapTemplate } from "./templates/app/sitemap.js";
22
+ import { llmsIndexTemplate } from "./templates/llms/llmsIndex.js";
23
+ import { llmsFullTemplate, } from "./templates/llms/llmsFull.js";
24
+ import { llmsPageTemplate } from "./templates/llms/llmsPage.js";
25
+ import { siteDocsSlug, skillMdTemplate } from "./templates/llms/skillMd.js";
26
+ const PUBLIC_AGGREGATE_PATHS = new Set([
27
+ "llms.txt",
28
+ "llms-full.txt",
29
+ "skill.md",
30
+ ".well-known/mcp.json",
31
+ ]);
32
+ function normalizePublicArtifactPath(relativePath) {
33
+ return relativePath.replace(/\\/g, "/").toLowerCase();
34
+ }
35
+ function isPublicAggregate(relativePath) {
36
+ return PUBLIC_AGGREGATE_PATHS.has(normalizePublicArtifactPath(relativePath));
37
+ }
38
+ function isManagedPublicArtifact(relativePath) {
39
+ const normalized = normalizePublicArtifactPath(relativePath);
40
+ return PUBLIC_AGGREGATE_PATHS.has(normalized) || normalized.endsWith(".md");
41
+ }
42
+ function errorCode(error) {
43
+ return error && typeof error === "object" && "code" in error
44
+ ? String(error.code)
45
+ : undefined;
46
+ }
47
+ function sameFileIdentity(left, right) {
48
+ return left.dev === right.dev && left.ino === right.ino;
49
+ }
50
+ export class MDXToNextJSGenerator {
51
+ watchDir;
52
+ outputDir;
53
+ rootDir;
54
+ watcher = null;
55
+ configWatcher = null;
56
+ fontWatcher = null;
57
+ publicWatcher = null;
58
+ rootDirWatcher = null;
59
+ analyticsWatcher = null;
60
+ openApiWatcher = null;
61
+ doccupineConfigWatcher = null;
62
+ doccupineConfigFile = "doccupine.json";
63
+ configFiles = [
64
+ "theme.json",
65
+ "navigation.json",
66
+ "config.json",
67
+ "links.json",
68
+ "sections.json",
69
+ ];
70
+ fontConfigFile = "fonts.json";
71
+ analyticsConfigFile = "analytics.json";
72
+ analyticsConfig = null;
73
+ sectionsConfig = null;
74
+ /** Guards against recursive reprocessing when maybeUpdateSections() triggers processAllMDXFiles() */
75
+ isReprocessing = false;
76
+ /** OpenAPI specs (build config) that drive the generated API reference. */
77
+ openApiSpecs;
78
+ apiBaseSlug = DEFAULT_API_BASE_SLUG;
79
+ apiRegistry = new OpenApiRegistry();
80
+ artifacts;
81
+ /** Section slugs whose index redirect we wrote this session, for cleanup. */
82
+ generatedSectionIndexSlugs = new Set();
83
+ /** Serializes watcher mutations so aggregate files never race one another. */
84
+ mutationQueue = Promise.resolve();
85
+ constructor(watchDir, outputDir, openApiSpecs = [], rootDir = process.cwd()) {
86
+ this.watchDir = path.resolve(watchDir);
87
+ this.outputDir = path.resolve(outputDir);
88
+ this.rootDir = path.resolve(rootDir);
89
+ this.openApiSpecs = openApiSpecs;
90
+ this.artifacts = new GeneratedArtifacts(this.outputDir);
91
+ }
92
+ outputPath(...segments) {
93
+ return resolveOutputPath(this.outputDir, ...segments);
94
+ }
95
+ publicOutputFilePath(relativePath) {
96
+ const parent = path.dirname(relativePath);
97
+ const outputParent = parent === "."
98
+ ? this.outputPath("public")
99
+ : this.outputPath("public", parent);
100
+ return resolveWithin(outputParent, path.basename(relativePath));
101
+ }
102
+ sourcePathError(label, sourcePath, detail) {
103
+ return new Error(`Refusing to use ${label} at ${sourcePath}: ${detail}. Replace it with a real file or directory inside the source root.`);
104
+ }
105
+ async realSourceRoot(root, label, rejectRootSymlink) {
106
+ let rootStat;
107
+ try {
108
+ rootStat = await fs.lstat(root);
109
+ }
110
+ catch (error) {
111
+ if (errorCode(error) === "ENOENT") {
112
+ throw this.sourcePathError(label, root, "the source root does not exist");
113
+ }
114
+ throw error;
115
+ }
116
+ if (rootStat.isSymbolicLink() && rejectRootSymlink) {
117
+ throw this.sourcePathError(label, root, "the source root is a symbolic link");
118
+ }
119
+ const realRoot = await fs.realpath(root);
120
+ if (!(await fs.stat(realRoot)).isDirectory()) {
121
+ throw this.sourcePathError(label, root, "the source root is not a directory");
122
+ }
123
+ return realRoot;
124
+ }
125
+ async readSafeSourceFile(root, sourcePath, label, rejectRootSymlink) {
126
+ const resolvedRoot = path.resolve(root);
127
+ const resolvedSource = path.resolve(sourcePath);
128
+ if (!isPathInside(resolvedRoot, resolvedSource)) {
129
+ throw this.sourcePathError(label, resolvedSource, `the path is outside ${resolvedRoot}`);
130
+ }
131
+ const realRoot = await this.realSourceRoot(resolvedRoot, label, rejectRootSymlink);
132
+ const relativePath = path.relative(resolvedRoot, resolvedSource);
133
+ const components = relativePath.split(path.sep).filter(Boolean);
134
+ let currentPath = resolvedRoot;
135
+ for (const [index, component] of components.entries()) {
136
+ currentPath = path.join(currentPath, component);
137
+ let stat;
138
+ try {
139
+ stat = await fs.lstat(currentPath);
140
+ }
141
+ catch (error) {
142
+ if (errorCode(error) === "ENOENT") {
143
+ throw this.sourcePathError(label, currentPath, "the path does not exist");
144
+ }
145
+ throw error;
146
+ }
147
+ if (stat.isSymbolicLink()) {
148
+ throw this.sourcePathError(label, currentPath, "the path is a symbolic link");
149
+ }
150
+ if (index < components.length - 1 && !stat.isDirectory()) {
151
+ throw this.sourcePathError(label, currentPath, "a path component is not a directory");
152
+ }
153
+ }
154
+ const sourceStat = await fs.lstat(resolvedSource);
155
+ if (!sourceStat.isFile()) {
156
+ throw this.sourcePathError(label, resolvedSource, "expected a regular file");
157
+ }
158
+ const realSource = await fs.realpath(resolvedSource);
159
+ if (!isPathInside(realRoot, realSource)) {
160
+ throw this.sourcePathError(label, resolvedSource, `the real path ${realSource} is outside ${realRoot}`);
161
+ }
162
+ const noFollow = typeof constants.O_NOFOLLOW === "number" ? constants.O_NOFOLLOW : 0;
163
+ let handle;
164
+ try {
165
+ handle = await open(resolvedSource, constants.O_RDONLY | noFollow);
166
+ }
167
+ catch (error) {
168
+ if (errorCode(error) === "ELOOP") {
169
+ throw this.sourcePathError(label, resolvedSource, "the final path became a symbolic link while it was being opened");
170
+ }
171
+ throw error;
172
+ }
173
+ try {
174
+ const openedStat = await handle.stat();
175
+ if (!openedStat.isFile()) {
176
+ throw this.sourcePathError(label, resolvedSource, "the opened source is not a regular file");
177
+ }
178
+ let currentStat;
179
+ let currentRealSource;
180
+ let currentRealStat;
181
+ try {
182
+ currentStat = await fs.lstat(resolvedSource);
183
+ currentRealSource = await fs.realpath(resolvedSource);
184
+ currentRealStat = await fs.lstat(currentRealSource);
185
+ }
186
+ catch {
187
+ throw this.sourcePathError(label, resolvedSource, "the path changed while it was being opened");
188
+ }
189
+ if (!isPathInside(realRoot, currentRealSource)) {
190
+ throw this.sourcePathError(label, resolvedSource, `the real path ${currentRealSource} is outside ${realRoot}`);
191
+ }
192
+ if (currentStat.isSymbolicLink() ||
193
+ !currentStat.isFile() ||
194
+ !currentRealStat.isFile() ||
195
+ !sameFileIdentity(sourceStat, openedStat) ||
196
+ !sameFileIdentity(openedStat, currentStat) ||
197
+ !sameFileIdentity(openedStat, currentRealStat)) {
198
+ throw this.sourcePathError(label, resolvedSource, "the source identity changed while it was being opened");
199
+ }
200
+ return { data: await handle.readFile(), stat: openedStat };
201
+ }
202
+ finally {
203
+ await handle.close();
204
+ }
205
+ }
206
+ async readMdxSourceFile(filePath) {
207
+ if (!filePath.toLowerCase().endsWith(".mdx")) {
208
+ throw this.sourcePathError("documentation source", filePath, "expected an .mdx file");
209
+ }
210
+ const { data, stat } = await this.readSafeSourceFile(this.watchDir, path.resolve(this.watchDir, filePath), "documentation source", false);
211
+ return { content: data.toString("utf8"), stat };
212
+ }
213
+ async ensureSafeStarterPath(relativePath) {
214
+ const resolvedRoot = path.resolve(this.watchDir);
215
+ const targetPath = path.resolve(resolvedRoot, relativePath);
216
+ if (!isPathInside(resolvedRoot, targetPath)) {
217
+ throw this.sourcePathError("documentation source", targetPath, `the starter path is outside ${resolvedRoot}`);
218
+ }
219
+ const realRoot = await this.realSourceRoot(resolvedRoot, "documentation source", false);
220
+ const parentRelativePath = path.relative(resolvedRoot, path.dirname(targetPath));
221
+ let currentPath = resolvedRoot;
222
+ for (const component of parentRelativePath
223
+ .split(path.sep)
224
+ .filter(Boolean)) {
225
+ currentPath = path.join(currentPath, component);
226
+ try {
227
+ await fs.mkdir(currentPath);
228
+ }
229
+ catch (error) {
230
+ if (errorCode(error) !== "EEXIST")
231
+ throw error;
232
+ }
233
+ const stat = await fs.lstat(currentPath);
234
+ if (stat.isSymbolicLink() || !stat.isDirectory()) {
235
+ throw this.sourcePathError("documentation source", currentPath, "a starter directory component is not a real directory");
236
+ }
237
+ const realPath = await fs.realpath(currentPath);
238
+ if (!isPathInside(realRoot, realPath)) {
239
+ throw this.sourcePathError("documentation source", currentPath, `the real path ${realPath} is outside ${realRoot}`);
240
+ }
241
+ }
242
+ try {
243
+ const stat = await fs.lstat(targetPath);
244
+ const detail = stat.isSymbolicLink()
245
+ ? "the starter file is a symbolic link"
246
+ : "the starter file appeared after the empty-source check";
247
+ throw this.sourcePathError("documentation source", targetPath, detail);
248
+ }
249
+ catch (error) {
250
+ if (errorCode(error) !== "ENOENT")
251
+ throw error;
252
+ }
253
+ return targetPath;
254
+ }
255
+ async copyRegularPublicFile(publicDir, sourcePath, destPath) {
256
+ const { data } = await this.readSafeSourceFile(publicDir, sourcePath, "public source", true);
257
+ await writeFileAtomic(destPath, data);
258
+ }
259
+ async copyRootSourceFile(sourcePath, destPath, label) {
260
+ const { data } = await this.readSafeSourceFile(this.rootDir, sourcePath, label, false);
261
+ await writeFileAtomic(destPath, data);
262
+ }
263
+ enqueueMutation(label, task) {
264
+ this.mutationQueue = this.mutationQueue.then(task).catch((error) => {
265
+ console.error(chalk.red(`❌ ${label}:`), error);
266
+ });
267
+ }
268
+ async init() {
269
+ console.log(chalk.blue("🚀 Initializing MDX to Next.js generator..."));
270
+ await fs.ensureDir(this.watchDir);
271
+ await claimOutputDirectory(this.outputDir);
272
+ await this.artifacts.load();
273
+ this.sectionsConfig = await this.resolveSections();
274
+ this.analyticsConfig = await this.loadAnalyticsConfig();
275
+ if (this.analyticsConfig) {
276
+ console.log(chalk.blue(`📊 Analytics enabled: ${this.analyticsConfig.provider}`));
277
+ }
278
+ // Parse OpenAPI spec(s) before generating structure so the synthetic
279
+ // endpoint pages flow into the very first layout/sitemap/llms pass.
280
+ await this.loadOpenApiRegistry();
281
+ await this.createNextJSStructure();
282
+ await this.createStartingDocs();
283
+ await this.copyCustomConfigFiles();
284
+ await this.copyFontConfig();
285
+ await this.copyAnalyticsConfig();
286
+ await this.copyPublicFiles();
287
+ // createStartingDocs() may have written the sample docs - which carry
288
+ // section frontmatter - after the initial resolveSections() ran against an
289
+ // empty watch dir. Re-resolve now that every MDX file is on disk so the
290
+ // build applies the correct sections in a single O(n) pass, instead of
291
+ // rediscovering them per file (the old O(n²) behavior).
292
+ this.sectionsConfig = await this.resolveSections();
293
+ if (this.sectionsConfig) {
294
+ console.log(chalk.blue(`📑 Found ${this.sectionsConfig.length} section(s): ${this.sectionsConfig.map((s) => s.label).join(", ")}`));
295
+ }
296
+ // Write the endpoint pages + request allowlist before the MDX pass so its
297
+ // aggregate refresh (nav/sitemap/llms) already sees them on disk and in the
298
+ // registry.
299
+ await this.writeApiPages();
300
+ await this.processAllMDXFiles();
301
+ console.log(chalk.green("✅ Initial setup complete!"));
302
+ console.log(chalk.cyan("💡 To start the Next.js dev server:"));
303
+ console.log(chalk.white(` cd ${path.relative(process.cwd(), this.outputDir)}`));
304
+ console.log(chalk.white(" install dependencies, then run the dev script"));
305
+ }
306
+ async createNextJSStructure() {
307
+ // Clear the generated app/ directory first so a fresh run never inherits
308
+ // stale routes from a previous version (e.g. pages left at their old paths
309
+ // after a route-group move would collide with the newly generated ones).
310
+ // Everything under app/ is regenerated below and by processAllMDXFiles /
311
+ // generateSectionIndexPages, so nothing here is user-authored. Config JSONs
312
+ // and other generated dirs live outside app/ and are untouched.
313
+ await fs.remove(this.outputPath("app"));
314
+ // Drop files that earlier CLI versions generated but no longer exist in
315
+ // the template set, so upgraded projects don't keep stale copies.
316
+ await Promise.all(obsoleteFiles.map((file) => fs.remove(this.outputPath(file))));
317
+ const structure = {
318
+ ...appStructure,
319
+ "next.config.ts": nextConfigTemplate(this.analyticsConfig),
320
+ "pnpm-workspace.yaml": pnpmWorkspaceTemplate,
321
+ "proxy.ts": proxyTemplate(this.analyticsConfig),
322
+ "analytics.json": `{}\n`,
323
+ "config.json": `{}\n`,
324
+ "links.json": `[]\n`,
325
+ "navigation.json": `[]\n`,
326
+ "sections.json": `[]\n`,
327
+ "theme.json": `{}\n`,
328
+ "app/robots.ts": robotsTemplate,
329
+ "app/layout.tsx": this.generateRootLayout(),
330
+ "app/(site)/layout.tsx": this.generateSiteLayout(),
331
+ };
332
+ for (const [filePath, content] of Object.entries(structure)) {
333
+ const fullPath = this.outputPath(filePath);
334
+ await fs.ensureDir(path.dirname(fullPath));
335
+ await writeFileAtomic(fullPath, String(await content));
336
+ }
337
+ await this.updateSitemap();
338
+ await this.updateLlmsFiles();
339
+ }
340
+ async createStartingDocs() {
341
+ // Seed only a genuinely empty documentation source. Checking index.mdx
342
+ // alone could overwrite an existing components.mdx or nested page.
343
+ if ((await this.getAllMDXFiles()).length > 0)
344
+ return;
345
+ for (const [filePath, content] of Object.entries(startingDocsStructure)) {
346
+ const fullPath = await this.ensureSafeStarterPath(filePath);
347
+ await writeFileAtomic(fullPath, String(content));
348
+ }
349
+ }
350
+ async copyCustomConfigFiles() {
351
+ console.log(chalk.blue(`🔍 Checking for config files in: ${this.rootDir}`));
352
+ for (const configFile of this.configFiles) {
353
+ const sourcePath = path.join(this.rootDir, configFile);
354
+ const destPath = this.outputPath(configFile);
355
+ console.log(chalk.gray(` Checking ${configFile}...`));
356
+ if (await fs.pathExists(sourcePath)) {
357
+ await this.copyRootSourceFile(sourcePath, destPath, "config source");
358
+ console.log(chalk.green(` ✓ Copied ${configFile} to Next.js app`));
359
+ }
360
+ else {
361
+ console.log(chalk.gray(` ✗ ${configFile} not found, skipping`));
362
+ }
363
+ }
364
+ }
365
+ async copyFontConfig() {
366
+ console.log(chalk.blue(`🔍 Checking for font configuration...`));
367
+ const sourcePath = path.join(this.rootDir, this.fontConfigFile);
368
+ const destPath = this.outputPath(this.fontConfigFile);
369
+ if (await fs.pathExists(sourcePath)) {
370
+ await this.copyRootSourceFile(sourcePath, destPath, "font source");
371
+ console.log(chalk.green(` ✓ Copied ${this.fontConfigFile} to Next.js app`));
372
+ }
373
+ else {
374
+ console.log(chalk.gray(` ✗ ${this.fontConfigFile} not found, skipping`));
375
+ }
376
+ }
377
+ async loadFontConfig() {
378
+ const fontPath = path.join(this.rootDir, this.fontConfigFile);
379
+ try {
380
+ if (await fs.pathExists(fontPath)) {
381
+ const fontContent = await fs.readFile(fontPath, "utf8");
382
+ return JSON.parse(fontContent);
383
+ }
384
+ }
385
+ catch (error) {
386
+ console.warn(chalk.yellow(`⚠️ Error reading ${this.fontConfigFile}`), error);
387
+ }
388
+ return null;
389
+ }
390
+ async loadAnalyticsConfig() {
391
+ const analyticsPath = path.join(this.rootDir, this.analyticsConfigFile);
392
+ try {
393
+ if (await fs.pathExists(analyticsPath)) {
394
+ const content = await fs.readFile(analyticsPath, "utf8");
395
+ const parsed = JSON.parse(content);
396
+ if (parsed?.provider === "posthog" && parsed.posthog?.key) {
397
+ return parsed;
398
+ }
399
+ }
400
+ }
401
+ catch (error) {
402
+ console.warn(chalk.yellow(`⚠️ Error reading ${this.analyticsConfigFile}`), error);
403
+ }
404
+ return null;
405
+ }
406
+ async copyAnalyticsConfig() {
407
+ console.log(chalk.blue(`🔍 Checking for analytics configuration...`));
408
+ const sourcePath = path.join(this.rootDir, this.analyticsConfigFile);
409
+ const destPath = this.outputPath(this.analyticsConfigFile);
410
+ if (await fs.pathExists(sourcePath)) {
411
+ await this.copyRootSourceFile(sourcePath, destPath, "analytics source");
412
+ console.log(chalk.green(` ✓ Copied ${this.analyticsConfigFile} to Next.js app`));
413
+ }
414
+ else {
415
+ console.log(chalk.gray(` ✗ ${this.analyticsConfigFile} not found, skipping`));
416
+ }
417
+ }
418
+ async loadSectionsConfig() {
419
+ const sectionsPath = path.join(this.rootDir, "sections.json");
420
+ try {
421
+ if (await fs.pathExists(sectionsPath)) {
422
+ const content = await fs.readFile(sectionsPath, "utf8");
423
+ const parsed = JSON.parse(content);
424
+ if (Array.isArray(parsed) && parsed.length > 0) {
425
+ const seenLabels = new Set();
426
+ const seenSlugs = new Set();
427
+ return parsed.map((entry, index) => {
428
+ if (!entry || typeof entry !== "object") {
429
+ throw new Error(`sections.json entry ${index + 1} must be an object`);
430
+ }
431
+ const candidate = entry;
432
+ const label = typeof candidate.label === "string" ? candidate.label.trim() : "";
433
+ const slug = typeof candidate.slug === "string" ? candidate.slug.trim() : "";
434
+ if (!label) {
435
+ throw new Error(`sections.json entry ${index + 1} needs a non-empty label`);
436
+ }
437
+ if (slug !== "" &&
438
+ (slug !== slugifySegment(slug) ||
439
+ slug.includes("/") ||
440
+ slug === "." ||
441
+ slug === "..")) {
442
+ throw new Error(`Unsafe section slug "${slug}"; use a lowercase URL segment such as "${slugifySegment(slug)}"`);
443
+ }
444
+ if (seenLabels.has(label) || seenSlugs.has(slug)) {
445
+ throw new Error(`Duplicate section label or slug at entry ${index + 1}`);
446
+ }
447
+ seenLabels.add(label);
448
+ seenSlugs.add(slug);
449
+ let directory;
450
+ if (candidate.directory !== undefined) {
451
+ if (typeof candidate.directory !== "string") {
452
+ throw new Error(`sections.json directory at entry ${index + 1} must be a string`);
453
+ }
454
+ directory = candidate.directory
455
+ .replace(/\\/g, "/")
456
+ .replace(/^\/+|\/+$/g, "");
457
+ const parts = directory.split("/");
458
+ if (!directory ||
459
+ parts.some((part) => part === "." ||
460
+ part === ".." ||
461
+ part !== slugifySegment(part))) {
462
+ throw new Error(`Unsafe section directory "${candidate.directory}"`);
463
+ }
464
+ }
465
+ return { label, slug, ...(directory ? { directory } : {}) };
466
+ });
467
+ }
468
+ }
469
+ }
470
+ catch (error) {
471
+ console.warn(chalk.yellow("⚠️ Error reading sections.json"), error);
472
+ }
473
+ return null;
474
+ }
475
+ async discoverSectionsFromFrontmatter() {
476
+ const files = await this.getAllMDXFiles();
477
+ const sectionMap = new Map();
478
+ let hasUnsectionedPages = false;
479
+ let defaultSectionLabel = "Docs";
480
+ for (const file of files) {
481
+ const { content } = await this.readMdxSourceFile(file);
482
+ const { data: frontmatter } = safeMatter(content, file);
483
+ if (typeof frontmatter.section === "string" &&
484
+ frontmatter.section.trim()) {
485
+ const label = frontmatter.section.trim();
486
+ const order = typeof frontmatter.sectionOrder === "number"
487
+ ? frontmatter.sectionOrder
488
+ : 0;
489
+ const existing = sectionMap.get(label);
490
+ if (!existing || order < existing.order) {
491
+ sectionMap.set(label, { label, order });
492
+ }
493
+ }
494
+ else {
495
+ hasUnsectionedPages = true;
496
+ }
497
+ if ((file === "index.mdx" || file === "./index.mdx") &&
498
+ typeof frontmatter.sectionLabel === "string" &&
499
+ frontmatter.sectionLabel.trim()) {
500
+ defaultSectionLabel = frontmatter.sectionLabel.trim();
501
+ }
502
+ }
503
+ if (sectionMap.size === 0)
504
+ return null;
505
+ const sorted = [...sectionMap.values()].sort((a, b) => a.order - b.order);
506
+ const sections = [];
507
+ // Implicit root entry for pages without a section field
508
+ if (hasUnsectionedPages) {
509
+ sections.push({ label: defaultSectionLabel, slug: "" });
510
+ }
511
+ const usedSlugs = new Set(sections.map((section) => section.slug));
512
+ for (const s of sorted) {
513
+ const slug = slugifySegment(s.label);
514
+ if (usedSlugs.has(slug)) {
515
+ throw new Error(`Section labels resolve to the same slug "${slug}". Rename one section or define sections.json explicitly.`);
516
+ }
517
+ usedSlugs.add(slug);
518
+ sections.push({
519
+ label: s.label,
520
+ slug,
521
+ });
522
+ }
523
+ return sections;
524
+ }
525
+ async resolveSections() {
526
+ const fromFile = await this.loadSectionsConfig();
527
+ const base = fromFile ?? (await this.discoverSectionsFromFrontmatter());
528
+ return this.withApiReferenceSection(base);
529
+ }
530
+ /**
531
+ * Promotes the generated OpenAPI endpoints into a dedicated "API Reference"
532
+ * section so they get their own top-level nav, separate from hand-written
533
+ * docs. When the site had no sections, a root "Documentation" section is added
534
+ * for the existing pages so both appear in the section switcher.
535
+ */
536
+ withApiReferenceSection(sections) {
537
+ if (this.apiRegistry.isEmpty)
538
+ return sections;
539
+ const apiSection = {
540
+ label: "API Reference",
541
+ slug: this.apiBaseSlug,
542
+ };
543
+ if (!sections || sections.length === 0) {
544
+ return [{ label: "Documentation", slug: "" }, apiSection];
545
+ }
546
+ if (sections.some((s) => s.slug === this.apiBaseSlug))
547
+ return sections;
548
+ return [...sections, apiSection];
549
+ }
550
+ async reloadSections() {
551
+ console.log(chalk.cyan("📑 Sections configuration changed"));
552
+ this.sectionsConfig = await this.resolveSections();
553
+ await this.processAllMDXFiles();
554
+ }
555
+ async maybeUpdateSections() {
556
+ if (this.isReprocessing)
557
+ return;
558
+ // Skip if sections.json exists (explicit config takes priority)
559
+ const fromFile = await this.loadSectionsConfig();
560
+ if (fromFile)
561
+ return;
562
+ const newSections = this.withApiReferenceSection(await this.discoverSectionsFromFrontmatter());
563
+ const changed = JSON.stringify(newSections) !== JSON.stringify(this.sectionsConfig);
564
+ if (changed) {
565
+ console.log(chalk.cyan(newSections
566
+ ? `📑 Sections updated from frontmatter: ${newSections.map((s) => s.label).join(", ")}`
567
+ : "📑 Sections cleared (no section frontmatter found)"));
568
+ this.sectionsConfig = newSections;
569
+ this.isReprocessing = true;
570
+ try {
571
+ // processAllMDXFiles() already refreshes section index pages via its
572
+ // aggregate pass, so no separate generateSectionIndexPages() here.
573
+ await this.processAllMDXFiles();
574
+ }
575
+ finally {
576
+ this.isReprocessing = false;
577
+ }
578
+ }
579
+ }
580
+ determineSectionForFile(filePath, frontmatter) {
581
+ if (!this.sectionsConfig || this.sectionsConfig.length === 0) {
582
+ return { sectionSlug: "", pageSlug: generateSlug(filePath) };
583
+ }
584
+ const normalizedPath = filePath.replace(/\\/g, "/");
585
+ const firstDir = normalizedPath.includes("/")
586
+ ? normalizedPath.split("/")[0]
587
+ : "";
588
+ // Explicit directory matching (entries with a directory field)
589
+ for (const section of this.sectionsConfig) {
590
+ if (!section.directory)
591
+ continue;
592
+ const dirPrefix = section.directory + "/";
593
+ if (normalizedPath.startsWith(dirPrefix)) {
594
+ return {
595
+ sectionSlug: section.slug,
596
+ pageSlug: generateSlug(normalizedPath.slice(dirPrefix.length)),
597
+ };
598
+ }
599
+ }
600
+ // Directory matches section slug (auto-detect)
601
+ if (firstDir) {
602
+ const match = this.sectionsConfig.find((s) => s.slug === firstDir);
603
+ if (match) {
604
+ const pathForSlug = normalizedPath.slice(firstDir.length + 1);
605
+ return {
606
+ sectionSlug: match.slug,
607
+ pageSlug: generateSlug(pathForSlug),
608
+ };
609
+ }
610
+ }
611
+ // Frontmatter section field
612
+ if (frontmatter.section) {
613
+ const label = frontmatter.section;
614
+ const match = this.sectionsConfig.find((s) => s.label === label);
615
+ if (match) {
616
+ // Strip the directory if it matches the section slug
617
+ let pathForSlug = filePath;
618
+ if (firstDir && firstDir === match.slug) {
619
+ pathForSlug = normalizedPath.slice(firstDir.length + 1);
620
+ }
621
+ return {
622
+ sectionSlug: match.slug,
623
+ pageSlug: generateSlug(pathForSlug),
624
+ };
625
+ }
626
+ }
627
+ // No section match - page stays at root
628
+ return {
629
+ sectionSlug: "",
630
+ pageSlug: generateSlug(filePath),
631
+ };
632
+ }
633
+ async handleConfigFileChange(filePath) {
634
+ const fileName = path.basename(filePath);
635
+ if (this.configFiles.includes(fileName)) {
636
+ const sourcePath = path.join(this.rootDir, fileName);
637
+ const destPath = this.outputPath(fileName);
638
+ try {
639
+ await this.copyRootSourceFile(sourcePath, destPath, "config source");
640
+ console.log(chalk.green(`📋 Updated ${fileName} in Next.js app`));
641
+ if (fileName === "sections.json") {
642
+ await this.reloadSections();
643
+ }
644
+ if (fileName === "config.json") {
645
+ await this.updateSitemap();
646
+ await this.updateRobots();
647
+ await this.updateLlmsFiles();
648
+ }
649
+ }
650
+ catch (error) {
651
+ console.error(chalk.red(`❌ Error copying ${fileName}:`), error);
652
+ }
653
+ }
654
+ }
655
+ async handleConfigFileDelete(filePath) {
656
+ const fileName = path.basename(filePath);
657
+ if (this.configFiles.includes(fileName)) {
658
+ const destPath = this.outputPath(fileName);
659
+ try {
660
+ const arrayDefaults = new Set([
661
+ "links.json",
662
+ "navigation.json",
663
+ "sections.json",
664
+ ]);
665
+ await writeFileAtomic(destPath, arrayDefaults.has(fileName) ? `[]\n` : `{}\n`);
666
+ console.log(chalk.yellow(`🗑️ Reset ${fileName} to its generated default`));
667
+ if (fileName === "sections.json") {
668
+ await this.reloadSections();
669
+ }
670
+ if (fileName === "config.json") {
671
+ await this.updateSitemap();
672
+ await this.updateRobots();
673
+ await this.updateLlmsFiles();
674
+ }
675
+ }
676
+ catch (error) {
677
+ console.error(chalk.red(`❌ Error removing ${fileName}:`), error);
678
+ }
679
+ }
680
+ }
681
+ async handleFontConfigChange() {
682
+ console.log(chalk.cyan(`🔤 Font configuration changed`));
683
+ const sourcePath = path.join(this.rootDir, this.fontConfigFile);
684
+ const destPath = this.outputPath(this.fontConfigFile);
685
+ try {
686
+ await this.copyRootSourceFile(sourcePath, destPath, "font source");
687
+ console.log(chalk.green(`📋 Updated ${this.fontConfigFile} in Next.js app`));
688
+ await this.updateRootLayout();
689
+ console.log(chalk.green(`✅ Layout updated with new font configuration`));
690
+ }
691
+ catch (error) {
692
+ console.error(chalk.red(`❌ Error updating font configuration:`), error);
693
+ }
694
+ }
695
+ async handleFontConfigDelete() {
696
+ console.log(chalk.red(`🗑️ Font configuration deleted`));
697
+ const destPath = this.outputPath(this.fontConfigFile);
698
+ try {
699
+ if (await fs.pathExists(destPath)) {
700
+ await fs.remove(destPath);
701
+ console.log(chalk.yellow(`🗑️ Removed ${this.fontConfigFile} from Next.js app`));
702
+ await this.updateRootLayout();
703
+ console.log(chalk.green(`✅ Layout updated without font configuration`));
704
+ }
705
+ }
706
+ catch (error) {
707
+ console.error(chalk.red(`❌ Error removing font configuration:`), error);
708
+ }
709
+ }
710
+ async handleAnalyticsConfigChange() {
711
+ console.log(chalk.cyan(`📊 Analytics configuration changed`));
712
+ const sourcePath = path.join(this.rootDir, this.analyticsConfigFile);
713
+ const destPath = this.outputPath(this.analyticsConfigFile);
714
+ try {
715
+ await this.copyRootSourceFile(sourcePath, destPath, "analytics source");
716
+ console.log(chalk.green(`📋 Updated ${this.analyticsConfigFile} in Next.js app`));
717
+ this.analyticsConfig = await this.loadAnalyticsConfig();
718
+ // Regenerate dynamic templates that depend on analytics config
719
+ await writeFileAtomic(this.outputPath("next.config.ts"), nextConfigTemplate(this.analyticsConfig));
720
+ await writeFileAtomic(this.outputPath("proxy.ts"), proxyTemplate(this.analyticsConfig));
721
+ await this.updateRootLayout();
722
+ console.log(chalk.green(`✅ Analytics configuration updated`));
723
+ if (this.analyticsConfig) {
724
+ console.log(chalk.yellow(`⚠️ Next.js dev server restart may be required for analytics proxy changes`));
725
+ }
726
+ }
727
+ catch (error) {
728
+ console.error(chalk.red(`❌ Error updating analytics configuration:`), error);
729
+ }
730
+ }
731
+ async handleAnalyticsConfigDelete() {
732
+ console.log(chalk.red(`🗑️ Analytics configuration deleted`));
733
+ const destPath = this.outputPath(this.analyticsConfigFile);
734
+ try {
735
+ // Write empty analytics.json so runtime imports don't break
736
+ await writeFileAtomic(destPath, `{}\n`);
737
+ this.analyticsConfig = null;
738
+ // Regenerate dynamic templates without analytics
739
+ await writeFileAtomic(this.outputPath("next.config.ts"), nextConfigTemplate(null));
740
+ await writeFileAtomic(this.outputPath("proxy.ts"), proxyTemplate(null));
741
+ await this.updateRootLayout();
742
+ console.log(chalk.green(`✅ Analytics removed from Next.js app`));
743
+ }
744
+ catch (error) {
745
+ console.error(chalk.red(`❌ Error removing analytics configuration:`), error);
746
+ }
747
+ }
748
+ async copyPublicFiles() {
749
+ const publicDir = path.join(this.rootDir, "public");
750
+ console.log(chalk.blue(`🔍 Checking for public directory...`));
751
+ let publicStat;
752
+ try {
753
+ publicStat = await fs.lstat(publicDir);
754
+ }
755
+ catch (error) {
756
+ if (errorCode(error) !== "ENOENT")
757
+ throw error;
758
+ console.log(chalk.gray(` ✗ public directory not found, skipping`));
759
+ return;
760
+ }
761
+ if (publicStat.isSymbolicLink() || !publicStat.isDirectory()) {
762
+ throw this.sourcePathError("public source", publicDir, "the public source root must be a real directory");
763
+ }
764
+ const realPublicDir = await this.realSourceRoot(publicDir, "public source", true);
765
+ const files = [];
766
+ const scanDir = async (directory, relativePath = "") => {
767
+ const entries = await fs.readdir(directory, { withFileTypes: true });
768
+ for (const entry of entries) {
769
+ const sourcePath = path.join(directory, entry.name);
770
+ const entryRelativePath = path.join(relativePath, entry.name);
771
+ const stat = await fs.lstat(sourcePath);
772
+ if (stat.isSymbolicLink()) {
773
+ throw this.sourcePathError("public source", sourcePath, "the path is a symbolic link");
774
+ }
775
+ const realPath = await fs.realpath(sourcePath);
776
+ if (!isPathInside(realPublicDir, realPath)) {
777
+ throw this.sourcePathError("public source", sourcePath, `the real path ${realPath} is outside ${realPublicDir}`);
778
+ }
779
+ if (stat.isDirectory()) {
780
+ await scanDir(sourcePath, entryRelativePath);
781
+ }
782
+ else if (stat.isFile()) {
783
+ files.push(entryRelativePath);
784
+ }
785
+ else {
786
+ throw this.sourcePathError("public source", sourcePath, "expected a regular file or directory");
787
+ }
788
+ }
789
+ };
790
+ await scanDir(publicDir);
791
+ for (const relativePath of files) {
792
+ await this.copyRegularPublicFile(publicDir, path.join(publicDir, relativePath), this.publicOutputFilePath(relativePath));
793
+ }
794
+ console.log(chalk.green(` ✓ Copied public directory to Next.js app`));
795
+ }
796
+ async handlePublicFileChange(filePath) {
797
+ const publicDir = path.join(this.rootDir, "public");
798
+ const relativePath = path.relative(publicDir, filePath);
799
+ const destRelativePath = isPublicAggregate(relativePath)
800
+ ? normalizePublicArtifactPath(relativePath)
801
+ : relativePath;
802
+ const destPath = this.publicOutputFilePath(destRelativePath);
803
+ try {
804
+ await this.copyRegularPublicFile(publicDir, filePath, destPath);
805
+ console.log(chalk.green(`📋 Updated public/${relativePath} in Next.js app`));
806
+ if (isManagedPublicArtifact(relativePath)) {
807
+ await this.updateLlmsFiles();
808
+ }
809
+ }
810
+ catch (error) {
811
+ console.error(chalk.red(`❌ Error copying public/${relativePath}:`), error);
812
+ throw error;
813
+ }
814
+ }
815
+ async handlePublicFileDelete(filePath) {
816
+ const publicDir = path.join(this.rootDir, "public");
817
+ const relativePath = path.relative(publicDir, filePath);
818
+ const destRelativePath = isPublicAggregate(relativePath)
819
+ ? normalizePublicArtifactPath(relativePath)
820
+ : relativePath;
821
+ const destPath = this.outputPath("public", destRelativePath);
822
+ try {
823
+ // A rapid replace can queue an unlink after the replacement already
824
+ // exists. Copy the current source instead of deleting its fresh mirror.
825
+ if (await fs.pathExists(filePath)) {
826
+ await this.handlePublicFileChange(filePath);
827
+ return;
828
+ }
829
+ if (await fs.pathExists(destPath)) {
830
+ await fs.remove(destPath);
831
+ console.log(chalk.yellow(`🗑️ Removed public/${relativePath} from Next.js app`));
832
+ }
833
+ if (isManagedPublicArtifact(relativePath)) {
834
+ await this.updateLlmsFiles();
835
+ }
836
+ }
837
+ catch (error) {
838
+ console.error(chalk.red(`❌ Error removing public/${relativePath}:`), error);
839
+ }
840
+ }
841
+ async startWatching() {
842
+ console.log(chalk.yellow(`👀 Watching for changes in: ${this.watchDir}`));
843
+ this.watcher = chokidar.watch(this.watchDir, {
844
+ persistent: true,
845
+ ignoreInitial: true,
846
+ followSymlinks: false,
847
+ ignored: (filePath, stats) => {
848
+ const isFile = stats?.isFile() ?? path.extname(filePath) !== "";
849
+ const fileName = path.basename(filePath);
850
+ if (this.configFiles.includes(fileName)) {
851
+ return true;
852
+ }
853
+ if (isFile && !filePath.endsWith(".mdx")) {
854
+ return true;
855
+ }
856
+ return false;
857
+ },
858
+ });
859
+ this.watcher
860
+ .on("add", (filePath) => {
861
+ const relativePath = path.relative(this.watchDir, filePath);
862
+ this.enqueueMutation("Error processing added MDX file", () => this.handleFileChange("added", relativePath));
863
+ })
864
+ .on("change", (filePath) => {
865
+ const relativePath = path.relative(this.watchDir, filePath);
866
+ this.enqueueMutation("Error processing changed MDX file", () => this.handleFileChange("changed", relativePath));
867
+ })
868
+ .on("unlink", (filePath) => {
869
+ const relativePath = path.relative(this.watchDir, filePath);
870
+ this.enqueueMutation("Error processing deleted MDX file", () => this.handleFileDelete(relativePath));
871
+ })
872
+ .on("ready", () => {
873
+ console.log(chalk.green("📁 Initial scan complete. Ready for changes..."));
874
+ })
875
+ .on("error", (error) => {
876
+ console.error(chalk.red("❌ Watcher error:"), error);
877
+ });
878
+ const configPaths = this.configFiles.map((f) => path.join(this.rootDir, f));
879
+ this.configWatcher = chokidar.watch(configPaths, {
880
+ persistent: true,
881
+ ignoreInitial: true,
882
+ });
883
+ this.configWatcher
884
+ .on("add", (filePath) => {
885
+ console.log(chalk.cyan(`📝 Config file added: ${path.basename(filePath)}`));
886
+ this.enqueueMutation("Error applying config file", () => this.handleConfigFileChange(filePath));
887
+ })
888
+ .on("change", (filePath) => {
889
+ console.log(chalk.cyan(`📝 Config file changed: ${path.basename(filePath)}`));
890
+ this.enqueueMutation("Error applying config file", () => this.handleConfigFileChange(filePath));
891
+ })
892
+ .on("unlink", (filePath) => {
893
+ console.log(chalk.red(`🗑️ Config file deleted: ${path.basename(filePath)}`));
894
+ this.enqueueMutation("Error deleting config file", () => this.handleConfigFileDelete(filePath));
895
+ })
896
+ .on("error", (error) => {
897
+ console.error(chalk.red("❌ Config watcher error:"), error);
898
+ });
899
+ const fontPath = path.join(this.rootDir, this.fontConfigFile);
900
+ this.fontWatcher = chokidar.watch(fontPath, {
901
+ persistent: true,
902
+ ignoreInitial: true,
903
+ });
904
+ this.fontWatcher
905
+ .on("add", () => {
906
+ console.log(chalk.cyan(`🔤 Font configuration added`));
907
+ this.enqueueMutation("Error applying font configuration", () => this.handleFontConfigChange());
908
+ })
909
+ .on("change", () => {
910
+ this.enqueueMutation("Error applying font configuration", () => this.handleFontConfigChange());
911
+ })
912
+ .on("unlink", () => {
913
+ this.enqueueMutation("Error deleting font configuration", () => this.handleFontConfigDelete());
914
+ })
915
+ .on("error", (error) => {
916
+ console.error(chalk.red("❌ Font watcher error:"), error);
917
+ });
918
+ const analyticsPath = path.join(this.rootDir, this.analyticsConfigFile);
919
+ this.analyticsWatcher = chokidar.watch(analyticsPath, {
920
+ persistent: true,
921
+ ignoreInitial: true,
922
+ });
923
+ this.analyticsWatcher
924
+ .on("add", () => {
925
+ console.log(chalk.cyan(`📊 Analytics configuration added`));
926
+ this.enqueueMutation("Error applying analytics configuration", () => this.handleAnalyticsConfigChange());
927
+ })
928
+ .on("change", () => {
929
+ this.enqueueMutation("Error applying analytics configuration", () => this.handleAnalyticsConfigChange());
930
+ })
931
+ .on("unlink", () => {
932
+ this.enqueueMutation("Error deleting analytics configuration", () => this.handleAnalyticsConfigDelete());
933
+ })
934
+ .on("error", (error) => {
935
+ console.error(chalk.red("❌ Analytics watcher error:"), error);
936
+ });
937
+ await this.syncOpenApiSpecWatcher();
938
+ const doccupineConfigPath = path.join(this.rootDir, this.doccupineConfigFile);
939
+ this.doccupineConfigWatcher = chokidar.watch(doccupineConfigPath, {
940
+ persistent: true,
941
+ ignoreInitial: true,
942
+ });
943
+ this.doccupineConfigWatcher
944
+ .on("add", () => this.enqueueMutation("Error applying doccupine.json", () => this.handleDoccupineConfigChange()))
945
+ .on("change", () => this.enqueueMutation("Error applying doccupine.json", () => this.handleDoccupineConfigChange()))
946
+ .on("error", (error) => {
947
+ console.error(chalk.red("❌ doccupine.json watcher error:"), error);
948
+ });
949
+ const publicDir = path.join(this.rootDir, "public");
950
+ if (await fs.pathExists(publicDir)) {
951
+ this.setupPublicWatcher();
952
+ }
953
+ // Watch rootDir for public directory creation
954
+ this.rootDirWatcher = chokidar.watch(this.rootDir, {
955
+ persistent: true,
956
+ ignoreInitial: true,
957
+ depth: 0,
958
+ });
959
+ this.rootDirWatcher
960
+ .on("addDir", (dirPath) => {
961
+ if (path.basename(dirPath) === "public" &&
962
+ path.dirname(dirPath) === this.rootDir &&
963
+ !this.publicWatcher) {
964
+ this.enqueueMutation("Error initializing public directory", async () => {
965
+ console.log(chalk.cyan("📁 Public directory created"));
966
+ await this.copyPublicFiles();
967
+ this.setupPublicWatcher();
968
+ });
969
+ }
970
+ })
971
+ .on("error", (error) => {
972
+ console.error(chalk.red("❌ Root dir watcher error:"), error);
973
+ });
974
+ }
975
+ setupPublicWatcher() {
976
+ if (this.publicWatcher) {
977
+ return;
978
+ }
979
+ const publicDir = path.join(this.rootDir, "public");
980
+ this.publicWatcher = chokidar.watch(publicDir, {
981
+ persistent: true,
982
+ ignoreInitial: true,
983
+ followSymlinks: false,
984
+ });
985
+ this.publicWatcher
986
+ .on("add", (filePath) => {
987
+ console.log(chalk.cyan(`📁 Public file added: ${path.relative(publicDir, filePath)}`));
988
+ this.enqueueMutation("Error copying public file", () => this.handlePublicFileChange(filePath));
989
+ })
990
+ .on("change", (filePath) => {
991
+ console.log(chalk.cyan(`📁 Public file changed: ${path.relative(publicDir, filePath)}`));
992
+ this.enqueueMutation("Error copying public file", () => this.handlePublicFileChange(filePath));
993
+ })
994
+ .on("unlink", (filePath) => {
995
+ console.log(chalk.red(`🗑️ Public file deleted: ${path.relative(publicDir, filePath)}`));
996
+ this.enqueueMutation("Error deleting public file", () => this.handlePublicFileDelete(filePath));
997
+ })
998
+ .on("error", (error) => {
999
+ console.error(chalk.red("❌ Public watcher error:"), error);
1000
+ });
1001
+ }
1002
+ async parseMDXFile(file) {
1003
+ const { content, stat } = await this.readMdxSourceFile(file);
1004
+ const { data: frontmatter } = safeMatter(content, file);
1005
+ const { sectionSlug, pageSlug } = this.determineSectionForFile(file, frontmatter);
1006
+ const fullSlug = getFullSlug(pageSlug, sectionSlug);
1007
+ let lastModified;
1008
+ const authoredLastModified = frontmatter.updated ?? frontmatter.date;
1009
+ if (authoredLastModified) {
1010
+ const parsed = new Date(authoredLastModified);
1011
+ if (!Number.isNaN(parsed.getTime())) {
1012
+ lastModified = parsed.toISOString();
1013
+ }
1014
+ }
1015
+ if (!lastModified) {
1016
+ lastModified = stat.mtime.toISOString();
1017
+ }
1018
+ // A hand-written page that embeds an endpoint via `openapi:` frontmatter
1019
+ // gets the same method badge in the sidebar as a generated endpoint page.
1020
+ let httpMethod;
1021
+ if (frontmatter.openapi) {
1022
+ const op = this.apiRegistry.lookup(String(frontmatter.openapi));
1023
+ if (op)
1024
+ httpMethod = op.method.toUpperCase();
1025
+ }
1026
+ return {
1027
+ slug: fullSlug,
1028
+ title: frontmatter.title || "Untitled",
1029
+ description: frontmatter.description || "",
1030
+ date: frontmatter.date || null,
1031
+ category: frontmatter.category || "",
1032
+ path: file,
1033
+ categoryOrder: frontmatter.categoryOrder || 0,
1034
+ order: frontmatter.order || 0,
1035
+ section: sectionSlug,
1036
+ // Sidebar icons (Lucide names). Kept separate from `icon`, which is
1037
+ // reserved for the favicon/OG metadata. Only emitted when set so the
1038
+ // generated page literal stays lean.
1039
+ ...(frontmatter.navIcon ? { navIcon: String(frontmatter.navIcon) } : {}),
1040
+ ...(frontmatter.categoryIcon
1041
+ ? { categoryIcon: String(frontmatter.categoryIcon) }
1042
+ : {}),
1043
+ ...(httpMethod ? { httpMethod } : {}),
1044
+ lastModified,
1045
+ };
1046
+ }
1047
+ async buildRealPagesMeta() {
1048
+ const files = await this.getAllMDXFiles();
1049
+ const real = await Promise.all(files.map((file) => this.parseMDXFile(file)));
1050
+ const bySlug = new Map();
1051
+ for (const page of real) {
1052
+ const existing = bySlug.get(page.slug);
1053
+ if (existing) {
1054
+ throw new Error(`Route collision at "/${page.slug}": both "${existing}" and "${page.path}" generate the same page.`);
1055
+ }
1056
+ bySlug.set(page.slug, page.path);
1057
+ }
1058
+ return real;
1059
+ }
1060
+ async buildAllPagesMeta() {
1061
+ const real = await this.buildRealPagesMeta();
1062
+ if (this.apiRegistry.isEmpty)
1063
+ return real;
1064
+ // Inject synthetic OpenAPI endpoint pages here - the single funnel every
1065
+ // aggregate (nav, sitemap, llms) flows through - so they cannot be dropped
1066
+ // by the .mdx-only disk scan. Hand-written pages win on any slug collision.
1067
+ const realSlugs = new Set(real.map((page) => page.slug));
1068
+ const synthetic = this.apiRegistry.syntheticPages().filter((page) => {
1069
+ if (realSlugs.has(page.slug)) {
1070
+ console.log(chalk.yellow(`⚠️ API page ${page.slug} is shadowed by a hand-written page; skipping`));
1071
+ return false;
1072
+ }
1073
+ return true;
1074
+ });
1075
+ return [...real, ...synthetic];
1076
+ }
1077
+ async removeOwnedRoute(slug) {
1078
+ if (!slug)
1079
+ return;
1080
+ const siteDir = this.outputPath("app", "(site)");
1081
+ const routeDir = resolveOutputPath(siteDir, slug);
1082
+ await Promise.all([
1083
+ fs.remove(resolveOutputPath(siteDir, slug, "page.tsx")),
1084
+ fs.remove(resolveOutputPath(siteDir, slug, "rss.xml")),
1085
+ ]);
1086
+ await this.removeEmptyDirsUpTo(routeDir, siteDir);
1087
+ }
1088
+ async removeStaleMdxRoutes(realPages) {
1089
+ const nextBySource = new Map(realPages
1090
+ .filter((page) => page.slug !== "")
1091
+ .map((page) => [page.path.replace(/\\/g, "/"), page.slug]));
1092
+ const nextSlugs = new Set(nextBySource.values());
1093
+ for (const previous of this.artifacts.routesFor("mdx")) {
1094
+ if (nextBySource.get(previous.source) === previous.slug)
1095
+ continue;
1096
+ if (nextSlugs.has(previous.slug))
1097
+ continue;
1098
+ await this.removeOwnedRoute(previous.slug);
1099
+ }
1100
+ }
1101
+ /**
1102
+ * Writes the generated page(s) for a single MDX file: the doc page and, for a
1103
+ * section-index file, the section landing page. Deliberately does NOT run the
1104
+ * site-wide aggregations (pages index, layout, sitemap, llms, section
1105
+ * redirects) - the caller batches those so a bulk build runs them once at the
1106
+ * end instead of once per file (which is what made large builds O(n²)).
1107
+ */
1108
+ async writePageForFile(filePath) {
1109
+ const { content } = await this.readMdxSourceFile(filePath);
1110
+ const { data: frontmatter, content: mdxContent } = safeMatter(content, filePath);
1111
+ const { sectionSlug, pageSlug } = this.determineSectionForFile(filePath, frontmatter);
1112
+ const fullSlug = getFullSlug(pageSlug, sectionSlug);
1113
+ const isIndex = filePath === "index.mdx" || filePath === "./index.mdx";
1114
+ const isSectionIndex = this.sectionsConfig && pageSlug === "" && sectionSlug !== "";
1115
+ if (isIndex) {
1116
+ // The homepage is emitted by updatePagesIndex() in the aggregate pass, so
1117
+ // there is no per-file page to write here.
1118
+ console.log(chalk.blue("🏠 Updating homepage with index.mdx content"));
1119
+ }
1120
+ else {
1121
+ const mdxFile = {
1122
+ path: filePath,
1123
+ content: mdxContent,
1124
+ frontmatter,
1125
+ slug: fullSlug,
1126
+ };
1127
+ // `openapi: <METHOD> <path>` (or an operationId) in frontmatter renders
1128
+ // that operation's playground inline with the author's prose. An unknown
1129
+ // reference is logged and the page still renders its prose (graceful).
1130
+ let apiOperation;
1131
+ if (frontmatter.openapi) {
1132
+ apiOperation = this.apiRegistry.lookup(String(frontmatter.openapi));
1133
+ if (!apiOperation) {
1134
+ console.error(chalk.red(`❌ openapi frontmatter "${frontmatter.openapi}" in ${filePath} not found in any spec`));
1135
+ }
1136
+ }
1137
+ await this.generatePageFromMDX(mdxFile, apiOperation ? { apiOperation } : undefined);
1138
+ }
1139
+ if (isSectionIndex) {
1140
+ await this.updateSectionIndex(sectionSlug, frontmatter, mdxContent, filePath);
1141
+ }
1142
+ }
1143
+ /**
1144
+ * Regenerates every file that depends on the full set of pages (pages index,
1145
+ * root/site layout, sitemap, llms files, section redirects). Parses all MDX
1146
+ * exactly once and threads the result through each generator, so one refresh
1147
+ * is a single scan rather than one scan per generator.
1148
+ */
1149
+ async refreshSiteAggregates(resolvedPages) {
1150
+ const pages = resolvedPages ?? (await this.buildAllPagesMeta());
1151
+ await this.updatePagesIndex();
1152
+ await this.updateRootLayout(pages);
1153
+ await this.updateSitemap(pages);
1154
+ await this.updateLlmsFiles(pages);
1155
+ await this.generateSectionIndexPages(pages);
1156
+ }
1157
+ async handleFileChange(action, filePath) {
1158
+ console.log(chalk.cyan(`📝 File ${action}: ${filePath}`));
1159
+ await this.readMdxSourceFile(filePath);
1160
+ try {
1161
+ // Validate the complete route set before writing this page so a collision
1162
+ // cannot transiently overwrite another route during watch mode.
1163
+ const normalizedSource = filePath.replace(/\\/g, "/");
1164
+ const previousSlug = this.artifacts.routeFor("mdx", normalizedSource);
1165
+ const realPages = await this.buildRealPagesMeta();
1166
+ const currentPage = realPages.find((page) => page.path.replace(/\\/g, "/") === normalizedSource);
1167
+ if (previousSlug && previousSlug !== currentPage?.slug)
1168
+ await this.removeStaleMdxRoutes(realPages);
1169
+ await this.writePageForFile(filePath);
1170
+ this.artifacts.replaceRoutes("mdx", realPages
1171
+ .filter((page) => page.slug !== "")
1172
+ .map((page) => ({ source: page.path, slug: page.slug })));
1173
+ await this.artifacts.save();
1174
+ if (!this.apiRegistry.isEmpty)
1175
+ await this.writeApiPages();
1176
+ const pages = await this.buildAllPagesMeta();
1177
+ await this.refreshSiteAggregates(pages);
1178
+ console.log(chalk.green(`✅ Generated page for: ${filePath}`));
1179
+ await this.maybeUpdateSections();
1180
+ }
1181
+ catch (error) {
1182
+ console.error(chalk.red(`❌ Error processing ${filePath}:`), error);
1183
+ }
1184
+ }
1185
+ async handleFileDelete(filePath) {
1186
+ console.log(chalk.red(`🗑️ File deleted: ${filePath}`));
1187
+ try {
1188
+ if (filePath === "index.mdx" || filePath === "./index.mdx") {
1189
+ console.log(chalk.blue("🏠 Updating homepage - index.mdx deleted"));
1190
+ }
1191
+ else {
1192
+ const normalizedSource = filePath.replace(/\\/g, "/");
1193
+ const ownedSlug = this.artifacts.routeFor("mdx", normalizedSource);
1194
+ if (ownedSlug)
1195
+ await this.removeOwnedRoute(ownedSlug);
1196
+ this.artifacts.removeRoute("mdx", normalizedSource);
1197
+ await this.artifacts.save();
1198
+ }
1199
+ if (!this.apiRegistry.isEmpty)
1200
+ await this.writeApiPages();
1201
+ await this.refreshSiteAggregates();
1202
+ console.log(chalk.green(`✅ Removed page for: ${filePath}`));
1203
+ await this.maybeUpdateSections();
1204
+ }
1205
+ catch (error) {
1206
+ console.error(chalk.red(`❌ Error removing page for ${filePath}:`), error);
1207
+ }
1208
+ }
1209
+ async processAllMDXFiles() {
1210
+ const files = await this.getAllMDXFiles();
1211
+ // Fail before writing any page when two source files resolve to one route.
1212
+ const realPages = await this.buildRealPagesMeta();
1213
+ await this.removeStaleMdxRoutes(realPages);
1214
+ // Write each page first (the only genuinely per-file work), then run the
1215
+ // site-wide aggregations a single time. Doing the aggregations per file
1216
+ // re-scanned and re-parsed every MDX file on each iteration, which made a
1217
+ // full build O(n²); batching them makes it O(n). A single bad file is
1218
+ // logged and skipped so it never aborts the whole build.
1219
+ for (const file of files) {
1220
+ console.log(chalk.cyan(`📝 Processing: ${file}`));
1221
+ try {
1222
+ await this.writePageForFile(file);
1223
+ }
1224
+ catch (error) {
1225
+ console.error(chalk.red(`❌ Error processing ${file}:`), error);
1226
+ }
1227
+ }
1228
+ this.artifacts.replaceRoutes("mdx", realPages
1229
+ .filter((page) => page.slug !== "")
1230
+ .map((page) => ({ source: page.path, slug: page.slug })));
1231
+ await this.artifacts.save();
1232
+ const pages = await this.buildAllPagesMeta();
1233
+ await this.refreshSiteAggregates(pages);
1234
+ }
1235
+ async getAllMDXFiles() {
1236
+ const files = [];
1237
+ const realWatchDir = await this.realSourceRoot(this.watchDir, "documentation source", false);
1238
+ const scanDir = async (dir, relativePath = "") => {
1239
+ const entries = await fs.readdir(dir, { withFileTypes: true });
1240
+ for (const entry of entries) {
1241
+ const fullPath = path.join(dir, entry.name);
1242
+ const relPath = path.join(relativePath, entry.name);
1243
+ const stat = await fs.lstat(fullPath);
1244
+ if (stat.isSymbolicLink()) {
1245
+ let linksToDirectory = false;
1246
+ try {
1247
+ linksToDirectory = (await fs.stat(fullPath)).isDirectory();
1248
+ }
1249
+ catch (error) {
1250
+ if (errorCode(error) !== "ENOENT")
1251
+ throw error;
1252
+ }
1253
+ if (entry.name.endsWith(".mdx") || linksToDirectory) {
1254
+ throw this.sourcePathError("documentation source", fullPath, "the path is a symbolic link");
1255
+ }
1256
+ continue;
1257
+ }
1258
+ const realPath = await fs.realpath(fullPath);
1259
+ if (!isPathInside(realWatchDir, realPath)) {
1260
+ throw this.sourcePathError("documentation source", fullPath, `the real path ${realPath} is outside ${realWatchDir}`);
1261
+ }
1262
+ if (stat.isDirectory()) {
1263
+ await scanDir(fullPath, relPath);
1264
+ }
1265
+ else if (stat.isFile() && entry.name.endsWith(".mdx")) {
1266
+ files.push(relPath);
1267
+ }
1268
+ else if (!stat.isFile() && entry.name.endsWith(".mdx")) {
1269
+ throw this.sourcePathError("documentation source", fullPath, "expected a regular .mdx file");
1270
+ }
1271
+ }
1272
+ };
1273
+ await scanDir(this.watchDir);
1274
+ return files;
1275
+ }
1276
+ async generateRootLayout() {
1277
+ const fontConfig = await this.loadFontConfig();
1278
+ const analyticsEnabled = this.analyticsConfig !== null;
1279
+ return rootLayoutTemplate(fontConfig, analyticsEnabled);
1280
+ }
1281
+ async generateSiteLayout(pages) {
1282
+ const resolvedPages = pages ?? (await this.buildAllPagesMeta());
1283
+ return siteLayoutTemplate(resolvedPages, this.sectionsConfig);
1284
+ }
1285
+ async generateSectionIndexPages(pages) {
1286
+ const nextSlugs = new Set();
1287
+ if (this.sectionsConfig && this.sectionsConfig.length > 0) {
1288
+ const resolvedPages = pages ?? (await this.buildAllPagesMeta());
1289
+ for (const section of this.sectionsConfig) {
1290
+ if (section.slug === "")
1291
+ continue;
1292
+ // Check if a page already exists at the section root
1293
+ const hasIndex = resolvedPages.some((p) => p.slug === section.slug);
1294
+ if (hasIndex)
1295
+ continue;
1296
+ // Find the first page in this section
1297
+ const sectionPages = resolvedPages
1298
+ .filter((p) => p.section === section.slug)
1299
+ .sort((a, b) => {
1300
+ if (a.categoryOrder !== b.categoryOrder)
1301
+ return a.categoryOrder - b.categoryOrder;
1302
+ return a.order - b.order;
1303
+ });
1304
+ if (sectionPages.length === 0)
1305
+ continue;
1306
+ const firstPage = sectionPages[0];
1307
+ const redirectContent = `import { redirect } from "next/navigation";
1308
+
1309
+ export default function SectionIndex() {
1310
+ redirect("/${firstPage.slug}");
1311
+ }
1312
+ `;
1313
+ const pagePath = resolveOutputPath(this.outputDir, "app", "(site)", section.slug, "page.tsx");
1314
+ await fs.ensureDir(path.dirname(pagePath));
1315
+ await writeFileAtomic(pagePath, redirectContent);
1316
+ nextSlugs.add(section.slug);
1317
+ console.log(chalk.blue(`🔀 Generated section index redirect: /${section.slug} -> /${firstPage.slug}`));
1318
+ }
1319
+ }
1320
+ await this.cleanupStaleSectionIndexPages(nextSlugs);
1321
+ }
1322
+ /**
1323
+ * Removes section index redirects written earlier in this session whose
1324
+ * section has since disappeared (e.g. the API Reference section after the
1325
+ * `openapi` config is removed mid-watch). Only files that still contain the
1326
+ * generated redirect are deleted, so a hand-written page that has taken
1327
+ * over the slug is never touched. Fresh processes start clean anyway -
1328
+ * init() wipes app/ - so in-session tracking is enough.
1329
+ */
1330
+ async cleanupStaleSectionIndexPages(nextSlugs) {
1331
+ for (const stale of this.generatedSectionIndexSlugs) {
1332
+ if (nextSlugs.has(stale))
1333
+ continue;
1334
+ const pagePath = resolveOutputPath(this.outputDir, "app", "(site)", stale, "page.tsx");
1335
+ try {
1336
+ if (!(await fs.pathExists(pagePath)))
1337
+ continue;
1338
+ const content = await fs.readFile(pagePath, "utf8");
1339
+ if (!content.includes("function SectionIndex()"))
1340
+ continue;
1341
+ await fs.remove(pagePath);
1342
+ await this.removeEmptyDirsUpTo(path.dirname(pagePath), this.outputPath("app", "(site)"));
1343
+ console.log(chalk.blue(`🧹 Removed stale section index redirect: /${stale}`));
1344
+ }
1345
+ catch {
1346
+ // ignore
1347
+ }
1348
+ }
1349
+ this.generatedSectionIndexSlugs = nextSlugs;
1350
+ }
1351
+ /** Best-effort removal of now-empty directories up to (not incl.) stopDir. */
1352
+ async removeEmptyDirsUpTo(dir, stopDir) {
1353
+ const stop = path.resolve(stopDir);
1354
+ let current = path.resolve(dir);
1355
+ while (current !== stop && current.startsWith(stop + path.sep)) {
1356
+ try {
1357
+ const entries = await fs.readdir(current);
1358
+ if (entries.length > 0)
1359
+ return;
1360
+ await fs.remove(current);
1361
+ }
1362
+ catch {
1363
+ return;
1364
+ }
1365
+ current = path.dirname(current);
1366
+ }
1367
+ }
1368
+ async generatePageFromMDX(mdxFile, options) {
1369
+ const fm = mdxFile.frontmatter;
1370
+ const apiOperation = options?.apiOperation;
1371
+ // Pages containing <Update> blocks publish a subscribable changelog: an
1372
+ // RSS feed at {page-url}/rss.xml. Synthetic OpenAPI pages never contain
1373
+ // Update blocks, so skip the parse for them.
1374
+ const isSynthetic = mdxFile.path.startsWith("@openapi/");
1375
+ const updates = isSynthetic ? [] : parseUpdateBlocks(mdxFile.content);
1376
+ const hasFeed = updates.length > 0;
1377
+ const feedPath = `/${mdxFile.slug}/rss.xml`;
1378
+ const metadataBlock = generateMetadataBlock({
1379
+ title: fm.title,
1380
+ titleFallback: "Generated with Doccupine",
1381
+ name: fm.name,
1382
+ titleOrder: "page-first",
1383
+ description: fm.description,
1384
+ icon: fm.icon,
1385
+ image: fm.image,
1386
+ canonicalPath: mdxFile.slug,
1387
+ rssPath: hasFeed ? feedPath : undefined,
1388
+ });
1389
+ const jsonLd = generateJsonLdScript({
1390
+ kind: "article",
1391
+ canonicalPath: mdxFile.slug,
1392
+ title: fm.title,
1393
+ description: fm.description,
1394
+ date: typeof fm.date === "string" ? fm.date : undefined,
1395
+ updated: typeof fm.updated === "string"
1396
+ ? fm.updated
1397
+ : typeof fm.date === "string"
1398
+ ? fm.date
1399
+ : undefined,
1400
+ image: fm.image,
1401
+ });
1402
+ // For an OpenAPI-backed page, embed the operation descriptor as a JS string
1403
+ // literal parsed at load. Serializing to JSON then re-`JSON.parse`ing is
1404
+ // total escaping for arbitrary JSON - unlike `escapeTemplateContent`, which
1405
+ // only guards backticks/`${`/backslashes for the MDX prose literal.
1406
+ const apiImport = apiOperation
1407
+ ? `\nimport { ApiPlayground } from "@/components/layout/ApiPlayground";`
1408
+ : "";
1409
+ // The descriptor JSON always exceeds the 80-col print width, so emit the
1410
+ // call pre-wrapped in the exact shape Prettier produces (argument on its own
1411
+ // line with a trailing comma, single-quoted so the JSON's own double quotes
1412
+ // need no escaping). Keeps generated endpoint pages Prettier-stable without
1413
+ // running a formatter at build time.
1414
+ const apiConst = apiOperation
1415
+ ? (() => {
1416
+ const arg = toJsStringLiteral(JSON.stringify(apiOperation));
1417
+ const inline = `const operation = JSON.parse(${arg});`;
1418
+ const decl = inline.length <= 80
1419
+ ? inline
1420
+ : `const operation = JSON.parse(\n ${arg},\n);`;
1421
+ return `\n${decl}\n`;
1422
+ })()
1423
+ : "";
1424
+ // The playground renders as a child of <Docs> so it sits inside the docs
1425
+ // content column (a sibling would escape the layout and overlap the nav).
1426
+ // Synthetic endpoint pages pass no `sourcePath`: it only namespaces Mermaid
1427
+ // diagrams (which endpoint docs never contain), and its long `@openapi/...`
1428
+ // value would push the opening tag past 80 cols and make Prettier rewrap it.
1429
+ const sourcePathLiteral = JSON.stringify(mdxFile.path);
1430
+ // `rss: true` frontmatter opts the page into an RSS button in the action
1431
+ // bar (only when a feed actually exists). The playground branch keeps its
1432
+ // fixed JSX shape - a feed on an inline-playground page stays reachable
1433
+ // via autodiscovery. The buttoned form usually exceeds the 80-col print
1434
+ // width, so pre-wrap it in the shape Prettier produces (attributes on
1435
+ // their own lines) relative to its 6-space insertion indent.
1436
+ const showRssButton = hasFeed && fm.rss === true && !apiOperation;
1437
+ const docsAttrs = [
1438
+ `content={content}`,
1439
+ `sourcePath={${sourcePathLiteral}}`,
1440
+ ...(showRssButton ? [`rssHref={${JSON.stringify(feedPath)}}`] : []),
1441
+ ];
1442
+ const inlineDocs = `<Docs ${docsAttrs.join(" ")} />`;
1443
+ const docsElement = apiOperation
1444
+ ? `<Docs content={content}>
1445
+ <ApiPlayground operation={operation} />
1446
+ </Docs>`
1447
+ : inlineDocs.length + 6 <= 80
1448
+ ? inlineDocs
1449
+ : `<Docs\n${docsAttrs.map((attr) => ` ${attr}`).join("\n")}\n />`;
1450
+ const pageContent = `import { Metadata } from "next";
1451
+ import { Docs } from "@/components/Docs";
1452
+ import { config } from "@/utils/config";${apiImport}
1453
+
1454
+ const content = \`${escapeTemplateContent(mdxFile.content)}\`;
1455
+ ${apiConst}
1456
+ ${metadataBlock}
1457
+
1458
+ // Doc pages have no per-request data: theme resolves client-side via the
1459
+ // "dark" class on <html> (set before paint by the theme-init blocking
1460
+ // script). Static rendering lets every response come from the edge cache.
1461
+ export const dynamic = "force-static";
1462
+ export const revalidate = false;
1463
+
1464
+ export default function Page() {
1465
+ ${jsonLd.declarations}
1466
+
1467
+ return (
1468
+ <>
1469
+ ${jsonLd.element}
1470
+ ${docsElement}
1471
+ </>
1472
+ );
1473
+ }
1474
+ `;
1475
+ const pagePath = resolveOutputPath(this.outputDir, "app", "(site)", mdxFile.slug, "page.tsx");
1476
+ await fs.ensureDir(path.dirname(pagePath));
1477
+ await writeFileAtomic(pagePath, pageContent);
1478
+ // The feed route lives inside the page's directory, so a deleted page
1479
+ // takes its feed along (handleFileDelete removes the whole dir) and the
1480
+ // else-branch prunes the route when a regenerated page no longer has
1481
+ // Update blocks. Cross-run staleness is covered by the app/ wipe in
1482
+ // createNextJSStructure.
1483
+ if (!isSynthetic) {
1484
+ const rssDir = resolveOutputPath(path.dirname(pagePath), "rss.xml");
1485
+ if (hasFeed) {
1486
+ await fs.ensureDir(rssDir);
1487
+ await writeFileAtomic(resolveOutputPath(path.dirname(pagePath), "rss.xml", "route.ts"), rssRouteTemplate({
1488
+ pagePath: mdxFile.slug,
1489
+ title: typeof fm.title === "string" ? fm.title : null,
1490
+ description: typeof fm.description === "string" ? fm.description : null,
1491
+ items: updates.map((update) => ({
1492
+ title: update.label,
1493
+ anchor: update.anchor,
1494
+ description: update.description,
1495
+ })),
1496
+ }));
1497
+ }
1498
+ else {
1499
+ await fs.remove(rssDir);
1500
+ }
1501
+ }
1502
+ }
1503
+ /** Parses the configured OpenAPI spec(s) into the shared registry. */
1504
+ async loadOpenApiRegistry() {
1505
+ if (this.openApiSpecs.length === 0)
1506
+ return;
1507
+ await this.apiRegistry.load(this.openApiSpecs, this.rootDir, this.apiBaseSlug);
1508
+ if (!this.apiRegistry.isEmpty) {
1509
+ console.log(chalk.blue(`📘 Loaded ${this.apiRegistry.all.length} API endpoint(s) from ${this.openApiSpecs.length} spec(s)`));
1510
+ }
1511
+ }
1512
+ /**
1513
+ * Generates one page per OpenAPI operation, (re)writes the request-execution
1514
+ * allowlist consumed by the playground proxy + component, and removes endpoint
1515
+ * pages that no longer exist in the spec. Safe to call when there are no specs
1516
+ * - it still emits an empty allowlist and prunes any previously generated
1517
+ * pages (e.g. after the `openapi` config is removed).
1518
+ */
1519
+ async writeApiPages() {
1520
+ const realSlugs = new Set((await this.buildRealPagesMeta()).map((page) => page.slug));
1521
+ const nextRoutes = new Map();
1522
+ const indexPage = this.apiRegistry
1523
+ .syntheticPages()
1524
+ .find((page) => page.slug === this.apiBaseSlug);
1525
+ if (indexPage && !realSlugs.has(indexPage.slug)) {
1526
+ try {
1527
+ await this.generatePageFromMDX({
1528
+ path: indexPage.path,
1529
+ content: this.apiRegistry.bodyForSlug(indexPage.slug) ?? "",
1530
+ frontmatter: {
1531
+ title: indexPage.title,
1532
+ description: indexPage.description,
1533
+ },
1534
+ slug: indexPage.slug,
1535
+ });
1536
+ nextRoutes.set(`@openapi/${indexPage.slug}`, indexPage.slug);
1537
+ }
1538
+ catch (error) {
1539
+ console.error(chalk.red(`❌ Error generating API index ${indexPage.slug}:`), error);
1540
+ }
1541
+ }
1542
+ for (const op of this.apiRegistry.all) {
1543
+ const methodUpper = op.method.toUpperCase();
1544
+ const mdxFile = {
1545
+ path: `@openapi/${op.specName}/${op.method}${op.path}`,
1546
+ content: buildEndpointDoc(op),
1547
+ frontmatter: {
1548
+ title: op.summary ?? `${methodUpper} ${op.path}`,
1549
+ description: op.summary ?? "",
1550
+ },
1551
+ slug: op.slug,
1552
+ };
1553
+ if (realSlugs.has(op.slug)) {
1554
+ console.log(chalk.yellow(`⚠️ API page ${op.slug} is shadowed by a hand-written page; skipping`));
1555
+ continue;
1556
+ }
1557
+ try {
1558
+ await this.generatePageFromMDX(mdxFile, { apiOperation: op });
1559
+ nextRoutes.set(`@openapi/${op.slug}`, op.slug);
1560
+ }
1561
+ catch (error) {
1562
+ console.error(chalk.red(`❌ Error generating API page ${op.slug}:`), error);
1563
+ }
1564
+ }
1565
+ await this.writeApiAllowlist();
1566
+ await this.cleanupStaleApiPages(nextRoutes, realSlugs);
1567
+ if (this.apiRegistry.all.length > 0) {
1568
+ console.log(chalk.green(`🧩 Generated ${nextRoutes.size} API reference page(s)`));
1569
+ }
1570
+ }
1571
+ /** Writes the request-execution allowlist (overwrites the shipped stub). */
1572
+ async writeApiAllowlist() {
1573
+ const target = this.outputPath("services", "openapi", "playground-allowlist.json");
1574
+ await fs.ensureDir(path.dirname(target));
1575
+ await writeFileAtomic(target, `${JSON.stringify(this.apiRegistry.allowlist(), null, 2)}\n`);
1576
+ }
1577
+ /** Removes endpoint page directories that are no longer in the spec. */
1578
+ async cleanupStaleApiPages(nextRoutes, realSlugs) {
1579
+ const nextSlugs = new Set(nextRoutes.values());
1580
+ for (const previous of this.artifacts.routesFor("openapi")) {
1581
+ if (nextRoutes.has(previous.source) || nextSlugs.has(previous.slug))
1582
+ continue;
1583
+ // A hand-written page may have taken ownership of this route since the
1584
+ // previous OpenAPI pass. Never remove an output now claimed by MDX.
1585
+ if (realSlugs.has(previous.slug))
1586
+ continue;
1587
+ try {
1588
+ await this.removeOwnedRoute(previous.slug);
1589
+ }
1590
+ catch {
1591
+ // ignore
1592
+ }
1593
+ }
1594
+ this.artifacts.replaceRoutes("openapi", [...nextRoutes].map(([source, slug]) => ({ source, slug })));
1595
+ await this.artifacts.save();
1596
+ }
1597
+ /**
1598
+ * (Re)points the spec-file watcher at the currently configured spec paths.
1599
+ * Called at startup and whenever doccupine.json changes the `openapi` set,
1600
+ * so specs added mid-session are watched without a restart.
1601
+ */
1602
+ async syncOpenApiSpecWatcher() {
1603
+ if (this.openApiWatcher) {
1604
+ await this.openApiWatcher.close();
1605
+ this.openApiWatcher = null;
1606
+ }
1607
+ if (this.openApiSpecs.length === 0)
1608
+ return;
1609
+ const specPaths = this.openApiSpecs.map((spec) => path.resolve(this.rootDir, spec.file));
1610
+ this.openApiWatcher = chokidar.watch(specPaths, {
1611
+ persistent: true,
1612
+ ignoreInitial: true,
1613
+ });
1614
+ this.openApiWatcher
1615
+ .on("add", () => this.enqueueMutation("Error rebuilding API reference", () => this.handleOpenApiChange()))
1616
+ .on("change", () => this.enqueueMutation("Error rebuilding API reference", () => this.handleOpenApiChange()))
1617
+ .on("unlink", () => this.enqueueMutation("Error rebuilding API reference", () => this.handleOpenApiChange()))
1618
+ .on("error", (error) => {
1619
+ console.error(chalk.red("❌ OpenAPI watcher error:"), error);
1620
+ });
1621
+ }
1622
+ /**
1623
+ * Reparses the spec(s) and rewrites everything derived from them: the
1624
+ * endpoint pages and allowlist, the sections (the "API Reference" section
1625
+ * appears and disappears with the registry), and the site aggregates.
1626
+ */
1627
+ async rebuildApiReference() {
1628
+ await this.apiRegistry.load(this.openApiSpecs, this.rootDir, this.apiBaseSlug);
1629
+ this.sectionsConfig = await this.resolveSections();
1630
+ await this.writeApiPages();
1631
+ await this.refreshSiteAggregates();
1632
+ }
1633
+ /** Reparses the spec(s) and regenerates the API reference on a watch event. */
1634
+ async handleOpenApiChange() {
1635
+ console.log(chalk.cyan("📘 OpenAPI spec changed - regenerating API reference"));
1636
+ try {
1637
+ await this.rebuildApiReference();
1638
+ console.log(chalk.green("✅ API reference updated"));
1639
+ }
1640
+ catch (error) {
1641
+ console.error(chalk.red("❌ Error updating API reference:"), error);
1642
+ }
1643
+ }
1644
+ /**
1645
+ * Applies `openapi` edits in doccupine.json without a restart: reloads the
1646
+ * registry, regenerates or prunes the endpoint pages and allowlist,
1647
+ * refreshes nav/sitemap/llms, and re-points the spec-file watcher. Other
1648
+ * fields (watchDir, outputDir, port) cannot be hot-applied, so a change
1649
+ * there only logs a restart hint. Invalid or missing JSON (e.g. a
1650
+ * half-written editor save) keeps the current configuration.
1651
+ */
1652
+ async handleDoccupineConfigChange() {
1653
+ const configPath = path.join(this.rootDir, this.doccupineConfigFile);
1654
+ let config;
1655
+ try {
1656
+ config = validateConfig(JSON.parse(await fs.readFile(configPath, "utf8")), this.rootDir);
1657
+ }
1658
+ catch (error) {
1659
+ console.warn(chalk.yellow("⚠️ doccupine.json is missing or invalid - keeping the current configuration"), error instanceof Error ? error.message : error);
1660
+ return;
1661
+ }
1662
+ if ((config.watchDir &&
1663
+ path.resolve(this.rootDir, config.watchDir) !== this.watchDir) ||
1664
+ (config.outputDir &&
1665
+ path.resolve(this.rootDir, config.outputDir) !== this.outputDir)) {
1666
+ console.log(chalk.yellow("⚠️ watchDir/outputDir changes in doccupine.json need a restart to apply"));
1667
+ }
1668
+ const nextSpecs = normalizeOpenApiConfig(config.openapi);
1669
+ if (JSON.stringify(nextSpecs) === JSON.stringify(this.openApiSpecs)) {
1670
+ return;
1671
+ }
1672
+ console.log(chalk.cyan("📘 OpenAPI configuration changed - updating API reference"));
1673
+ let nextRegistry;
1674
+ try {
1675
+ // Validate the complete candidate before changing the active spec list or
1676
+ // its watcher. A half-written/invalid replacement keeps both the current
1677
+ // generated reference and its live watcher intact.
1678
+ nextRegistry = new OpenApiRegistry();
1679
+ await nextRegistry.load(nextSpecs, this.rootDir, this.apiBaseSlug);
1680
+ }
1681
+ catch (error) {
1682
+ console.error(chalk.red("❌ Error updating API reference:"), error);
1683
+ return;
1684
+ }
1685
+ const previousRegistry = this.apiRegistry;
1686
+ const previousSpecs = this.openApiSpecs;
1687
+ const previousSections = this.sectionsConfig;
1688
+ try {
1689
+ this.apiRegistry = nextRegistry;
1690
+ this.openApiSpecs = nextSpecs;
1691
+ await this.syncOpenApiSpecWatcher();
1692
+ this.sectionsConfig = await this.resolveSections();
1693
+ await this.writeApiPages();
1694
+ await this.refreshSiteAggregates();
1695
+ console.log(chalk.green("✅ API reference updated"));
1696
+ }
1697
+ catch (error) {
1698
+ console.error(chalk.red("❌ Error updating API reference:"), error);
1699
+ this.apiRegistry = previousRegistry;
1700
+ this.openApiSpecs = previousSpecs;
1701
+ this.sectionsConfig = previousSections;
1702
+ try {
1703
+ await this.syncOpenApiSpecWatcher();
1704
+ }
1705
+ catch (rollbackError) {
1706
+ console.error(chalk.red("❌ Error restoring the previous OpenAPI watcher:"), rollbackError);
1707
+ }
1708
+ try {
1709
+ await this.writeApiPages();
1710
+ await this.refreshSiteAggregates();
1711
+ }
1712
+ catch (rollbackError) {
1713
+ console.error(chalk.red("❌ Error restoring previous API reference output:"), rollbackError);
1714
+ }
1715
+ }
1716
+ }
1717
+ async updatePagesIndex() {
1718
+ const files = await this.getAllMDXFiles();
1719
+ let indexMDX = null;
1720
+ for (const file of files) {
1721
+ if (file === "index.mdx" || file === "./index.mdx") {
1722
+ const { content } = await this.readMdxSourceFile(file);
1723
+ const { data: frontmatter, content: mdxContent } = safeMatter(content, file);
1724
+ indexMDX = {
1725
+ content: mdxContent,
1726
+ title: frontmatter.title || "Welcome",
1727
+ description: frontmatter.description || "",
1728
+ icon: frontmatter.icon,
1729
+ image: frontmatter.image,
1730
+ name: frontmatter.name,
1731
+ date: typeof frontmatter.date === "string" ? frontmatter.date : undefined,
1732
+ updated: typeof frontmatter.updated === "string"
1733
+ ? frontmatter.updated
1734
+ : undefined,
1735
+ openapi: typeof frontmatter.openapi === "string"
1736
+ ? frontmatter.openapi
1737
+ : undefined,
1738
+ rss: frontmatter.rss === true,
1739
+ };
1740
+ break;
1741
+ }
1742
+ }
1743
+ // The homepage publishes the same subscribable changelog as any other
1744
+ // page (see generatePageFromMDX): <Update> blocks feed the site-root
1745
+ // /rss.xml, and `rss: true` frontmatter opts into the RSS button.
1746
+ const updates = indexMDX ? parseUpdateBlocks(indexMDX.content) : [];
1747
+ const hasFeed = updates.length > 0;
1748
+ const feedPath = "/rss.xml";
1749
+ const metadataBlock = indexMDX
1750
+ ? generateMetadataBlock({
1751
+ title: indexMDX.title,
1752
+ titleFallback: "Welcome",
1753
+ name: indexMDX.name,
1754
+ titleOrder: "name-first",
1755
+ description: indexMDX.description || undefined,
1756
+ icon: indexMDX.icon,
1757
+ image: indexMDX.image,
1758
+ canonicalPath: "",
1759
+ rssPath: hasFeed ? feedPath : undefined,
1760
+ })
1761
+ : generateRuntimeOnlyMetadataBlock();
1762
+ const homeJsonLd = generateJsonLdScript({
1763
+ kind: "homepage",
1764
+ canonicalPath: "",
1765
+ title: indexMDX?.title,
1766
+ description: indexMDX?.description || undefined,
1767
+ date: indexMDX?.date,
1768
+ updated: indexMDX?.updated ?? indexMDX?.date,
1769
+ image: indexMDX?.image,
1770
+ });
1771
+ // The homepage supports the same `openapi: <METHOD> <path>` frontmatter as
1772
+ // any other page: look the operation up and embed its playground inline.
1773
+ let apiOperation;
1774
+ if (indexMDX?.openapi) {
1775
+ apiOperation = this.apiRegistry.lookup(indexMDX.openapi);
1776
+ if (!apiOperation) {
1777
+ console.error(chalk.red(`❌ openapi frontmatter "${indexMDX.openapi}" in index.mdx not found in any spec`));
1778
+ }
1779
+ }
1780
+ const apiImport = apiOperation
1781
+ ? `\nimport { ApiPlayground } from "@/components/layout/ApiPlayground";`
1782
+ : "";
1783
+ const apiConst = apiOperation
1784
+ ? `\nconst operation = JSON.parse(${JSON.stringify(JSON.stringify(apiOperation))});\n`
1785
+ : "";
1786
+ // Same gating as generatePageFromMDX: the playground branch keeps its
1787
+ // fixed JSX shape, so a feed on a playground homepage stays reachable via
1788
+ // autodiscovery. The buttoned inline form stays within the 80-col print
1789
+ // width at its 6-space insertion indent, so it is Prettier-stable as is.
1790
+ const showRssButton = hasFeed && indexMDX?.rss === true && !apiOperation;
1791
+ const docsElement = apiOperation
1792
+ ? `<Docs content={content} sourcePath="index.mdx">
1793
+ <ApiPlayground operation={operation} />
1794
+ </Docs>`
1795
+ : showRssButton
1796
+ ? `<Docs content={content} sourcePath="index.mdx" rssHref={"/rss.xml"} />`
1797
+ : `<Docs content={content} sourcePath="index.mdx" />`;
1798
+ const indexContent = `import { Metadata } from "next";
1799
+ import { Docs } from "@/components/Docs";
1800
+ import { config } from "@/utils/config";${apiImport}
1801
+
1802
+ ${indexMDX ? `const content = \`${escapeTemplateContent(indexMDX.content)}\`;` : `const content = null;`}
1803
+ ${apiConst}
1804
+ ${metadataBlock}
1805
+
1806
+ export const dynamic = "force-static";
1807
+ export const revalidate = false;
1808
+
1809
+ export default function Home() {
1810
+ ${homeJsonLd.declarations}
1811
+
1812
+ return (
1813
+ <>
1814
+ ${homeJsonLd.element}
1815
+ ${docsElement}
1816
+ </>
1817
+ );
1818
+ }
1819
+ `;
1820
+ const homePath = this.outputPath("app", "(site)", "page.tsx");
1821
+ await fs.ensureDir(path.dirname(homePath));
1822
+ await writeFileAtomic(homePath, indexContent);
1823
+ // Same lifecycle as the per-page feeds in generatePageFromMDX: write the
1824
+ // root feed route while the homepage has Update blocks, prune it when
1825
+ // they go away or index.mdx is deleted (this runs on every aggregate
1826
+ // refresh, including the delete path).
1827
+ const rssDir = this.outputPath("app", "(site)", "rss.xml");
1828
+ if (hasFeed && indexMDX) {
1829
+ await fs.ensureDir(rssDir);
1830
+ await writeFileAtomic(this.outputPath("app", "(site)", "rss.xml", "route.ts"), rssRouteTemplate({
1831
+ pagePath: "",
1832
+ title: indexMDX.title,
1833
+ description: indexMDX.description || null,
1834
+ items: updates.map((update) => ({
1835
+ title: update.label,
1836
+ anchor: update.anchor,
1837
+ description: update.description,
1838
+ })),
1839
+ }));
1840
+ }
1841
+ else {
1842
+ await fs.remove(rssDir);
1843
+ }
1844
+ }
1845
+ async updateSectionIndex(sectionSlug, frontmatter, mdxContent, sourcePath) {
1846
+ // This overwrites the page generatePageFromMDX just wrote for the same
1847
+ // slug (section landings compose their metadata name-first), so the RSS
1848
+ // state must be re-derived here or the overwrite silently drops the
1849
+ // button and autodiscovery - the feed route survives either way since it
1850
+ // lives in a sibling rss.xml/ dir.
1851
+ const updates = parseUpdateBlocks(mdxContent);
1852
+ const hasFeed = updates.length > 0;
1853
+ const feedPath = `/${sectionSlug}/rss.xml`;
1854
+ const showRssButton = hasFeed && frontmatter.rss === true;
1855
+ const metadataBlock = generateMetadataBlock({
1856
+ title: frontmatter.title,
1857
+ titleFallback: "Section",
1858
+ name: frontmatter.name,
1859
+ titleOrder: "name-first",
1860
+ description: frontmatter.description || undefined,
1861
+ icon: frontmatter.icon,
1862
+ image: frontmatter.image,
1863
+ canonicalPath: sectionSlug,
1864
+ rssPath: hasFeed ? feedPath : undefined,
1865
+ });
1866
+ const sectionJsonLd = generateJsonLdScript({
1867
+ kind: "article",
1868
+ canonicalPath: sectionSlug,
1869
+ title: frontmatter.title,
1870
+ description: frontmatter.description,
1871
+ date: typeof frontmatter.date === "string" ? frontmatter.date : undefined,
1872
+ updated: typeof frontmatter.updated === "string"
1873
+ ? frontmatter.updated
1874
+ : typeof frontmatter.date === "string"
1875
+ ? frontmatter.date
1876
+ : undefined,
1877
+ image: frontmatter.image,
1878
+ });
1879
+ // Same Prettier pre-wrap contract as generatePageFromMDX: the buttoned
1880
+ // form usually pushes the line past the 80-col print width, so emit it
1881
+ // with attributes on their own lines relative to the 6-space indent.
1882
+ const docsAttrs = [
1883
+ `content={content}`,
1884
+ `sourcePath={${JSON.stringify(sourcePath ?? `${sectionSlug}/index.mdx`)}}`,
1885
+ ...(showRssButton ? [`rssHref={${JSON.stringify(feedPath)}}`] : []),
1886
+ ];
1887
+ const inlineDocs = `<Docs ${docsAttrs.join(" ")} />`;
1888
+ const docsElement = inlineDocs.length + 6 <= 80
1889
+ ? inlineDocs
1890
+ : `<Docs\n${docsAttrs.map((attr) => ` ${attr}`).join("\n")}\n />`;
1891
+ const indexContent = `import { Metadata } from "next";
1892
+ import { Docs } from "@/components/Docs";
1893
+ import { config } from "@/utils/config";
1894
+
1895
+ const content = \`${escapeTemplateContent(mdxContent)}\`;
1896
+
1897
+ ${metadataBlock}
1898
+
1899
+ export const dynamic = "force-static";
1900
+ export const revalidate = false;
1901
+
1902
+ export default function Page() {
1903
+ ${sectionJsonLd.declarations}
1904
+
1905
+ return (
1906
+ <>
1907
+ ${sectionJsonLd.element}
1908
+ ${docsElement}
1909
+ </>
1910
+ );
1911
+ }
1912
+ `;
1913
+ const pagePath = resolveOutputPath(this.outputDir, "app", "(site)", sectionSlug, "page.tsx");
1914
+ await fs.ensureDir(path.dirname(pagePath));
1915
+ await writeFileAtomic(pagePath, indexContent);
1916
+ }
1917
+ async updateRootLayout(pages) {
1918
+ await writeFileAtomic(this.outputPath("app", "layout.tsx"), await this.generateRootLayout());
1919
+ const siteLayoutPath = this.outputPath("app", "(site)", "layout.tsx");
1920
+ await fs.ensureDir(path.dirname(siteLayoutPath));
1921
+ await writeFileAtomic(siteLayoutPath, await this.generateSiteLayout(pages));
1922
+ }
1923
+ async loadSiteUrl() {
1924
+ const fromEnv = process.env.NEXT_PUBLIC_SITE_URL?.trim();
1925
+ if (fromEnv)
1926
+ return fromEnv.replace(/\/$/, "");
1927
+ const configPath = path.join(this.rootDir, "config.json");
1928
+ try {
1929
+ if (await fs.pathExists(configPath)) {
1930
+ const content = await fs.readFile(configPath, "utf8");
1931
+ const parsed = JSON.parse(content);
1932
+ if (typeof parsed.url === "string" && parsed.url.trim() !== "") {
1933
+ return parsed.url.trim().replace(/\/$/, "");
1934
+ }
1935
+ }
1936
+ }
1937
+ catch (error) {
1938
+ console.warn(chalk.yellow("⚠️ Error reading config.json"), error);
1939
+ }
1940
+ return null;
1941
+ }
1942
+ buildSitemapEntries(pages) {
1943
+ const sectionSlugs = new Set((this.sectionsConfig || [])
1944
+ .map((s) => s.slug)
1945
+ .filter((s) => typeof s === "string" && s !== ""));
1946
+ const entries = pages.map((page) => {
1947
+ let priority = 0.5;
1948
+ if (page.slug === "") {
1949
+ priority = 1.0;
1950
+ }
1951
+ else if (sectionSlugs.has(page.slug)) {
1952
+ priority = 0.8;
1953
+ }
1954
+ return {
1955
+ slug: page.slug,
1956
+ lastModified: page.lastModified,
1957
+ changeFrequency: "weekly",
1958
+ priority,
1959
+ };
1960
+ });
1961
+ if (!entries.some((entry) => entry.slug === "")) {
1962
+ entries.unshift({
1963
+ slug: "",
1964
+ changeFrequency: "weekly",
1965
+ priority: 1.0,
1966
+ });
1967
+ }
1968
+ return entries;
1969
+ }
1970
+ async updateSitemap(pages) {
1971
+ const sitemapPath = this.outputPath("app", "sitemap.ts");
1972
+ const siteUrl = await this.loadSiteUrl();
1973
+ const resolvedPages = pages ?? (await this.buildAllPagesMeta());
1974
+ const entries = this.buildSitemapEntries(resolvedPages);
1975
+ await writeFileAtomic(sitemapPath, sitemapTemplate(entries));
1976
+ console.log(chalk.green(`🗺️ Generated sitemap.ts with ${entries.length} page(s)${siteUrl ? ` using ${siteUrl}` : " (waiting for a deployment URL)"}`));
1977
+ }
1978
+ async updateRobots() {
1979
+ const siteUrl = await this.loadSiteUrl();
1980
+ await writeFileAtomic(this.outputPath("app", "robots.ts"), robotsTemplate);
1981
+ console.log(chalk.green(siteUrl
1982
+ ? `🤖 Regenerated robots.ts with sitemap link`
1983
+ : `🤖 Regenerated robots.ts (no sitemap link)`));
1984
+ }
1985
+ async loadSiteMetadata() {
1986
+ const configPath = path.join(this.rootDir, "config.json");
1987
+ let url = null;
1988
+ let name = "Documentation";
1989
+ let description = "";
1990
+ try {
1991
+ const fromEnv = process.env.NEXT_PUBLIC_SITE_URL?.trim();
1992
+ if (fromEnv)
1993
+ url = fromEnv.replace(/\/$/, "");
1994
+ if (await fs.pathExists(configPath)) {
1995
+ const content = await fs.readFile(configPath, "utf8");
1996
+ const parsed = JSON.parse(content);
1997
+ if (!url &&
1998
+ typeof parsed.url === "string" &&
1999
+ parsed.url.trim() !== "") {
2000
+ url = parsed.url.trim().replace(/\/$/, "");
2001
+ }
2002
+ if (typeof parsed.name === "string" && parsed.name.trim() !== "") {
2003
+ name = parsed.name.trim();
2004
+ }
2005
+ else if (typeof parsed.title === "string" &&
2006
+ parsed.title.trim() !== "") {
2007
+ name = parsed.title.trim();
2008
+ }
2009
+ if (typeof parsed.description === "string" &&
2010
+ parsed.description.trim() !== "") {
2011
+ description = parsed.description.trim();
2012
+ }
2013
+ }
2014
+ }
2015
+ catch (error) {
2016
+ console.warn(chalk.yellow("⚠️ Error reading config.json for llms metadata"), error);
2017
+ }
2018
+ return { url, name, description };
2019
+ }
2020
+ async readPageWithBody(page) {
2021
+ // Synthetic OpenAPI pages have no backing .mdx file; their markdown body
2022
+ // comes from the registry instead of disk.
2023
+ if (!page.path.endsWith(".mdx")) {
2024
+ return { ...page, body: this.apiRegistry.bodyForSlug(page.slug) ?? "" };
2025
+ }
2026
+ const { content: raw } = await this.readMdxSourceFile(page.path);
2027
+ const { content: body } = safeMatter(raw, page.path);
2028
+ return { ...page, body };
2029
+ }
2030
+ async findSourcePublicAsset(relativePath) {
2031
+ const sourcePublicDir = path.join(this.rootDir, "public");
2032
+ const normalized = relativePath.replace(/\\/g, "/");
2033
+ resolveWithin(sourcePublicDir, normalized);
2034
+ let rootStat;
2035
+ try {
2036
+ rootStat = await fs.lstat(sourcePublicDir);
2037
+ }
2038
+ catch (error) {
2039
+ if (errorCode(error) === "ENOENT")
2040
+ return null;
2041
+ throw error;
2042
+ }
2043
+ if (rootStat.isSymbolicLink() || !rootStat.isDirectory()) {
2044
+ throw this.sourcePathError("public source", sourcePublicDir, "the public source root must be a real directory");
2045
+ }
2046
+ const realPublicDir = await this.realSourceRoot(sourcePublicDir, "public source", true);
2047
+ let currentPath = sourcePublicDir;
2048
+ const parts = normalized.split("/").filter(Boolean);
2049
+ for (const [index, part] of parts.entries()) {
2050
+ let entries;
2051
+ try {
2052
+ entries = await fs.readdir(currentPath);
2053
+ }
2054
+ catch {
2055
+ return null;
2056
+ }
2057
+ const actualName = entries.find((entry) => entry === part) ??
2058
+ entries.find((entry) => entry.toLowerCase() === part.toLowerCase());
2059
+ if (!actualName)
2060
+ return null;
2061
+ currentPath = path.join(currentPath, actualName);
2062
+ const stat = await fs.lstat(currentPath);
2063
+ if (stat.isSymbolicLink()) {
2064
+ throw this.sourcePathError("public source", currentPath, "the path is a symbolic link");
2065
+ }
2066
+ if (index < parts.length - 1 && !stat.isDirectory())
2067
+ return null;
2068
+ }
2069
+ const stat = await fs.lstat(currentPath);
2070
+ if (!stat.isFile())
2071
+ return null;
2072
+ const realPath = await fs.realpath(currentPath);
2073
+ if (!isPathInside(realPublicDir, realPath)) {
2074
+ throw this.sourcePathError("public source", currentPath, `the real path ${realPath} is outside ${realPublicDir}`);
2075
+ }
2076
+ return currentPath;
2077
+ }
2078
+ async writePublicAggregate(relativePath, content) {
2079
+ const sourcePath = await this.findSourcePublicAsset(relativePath);
2080
+ const targetPath = this.publicOutputFilePath(relativePath);
2081
+ if (sourcePath) {
2082
+ console.warn(chalk.yellow(`⚠️ Skipping generated public/${relativePath}; a project public asset owns that path`));
2083
+ await this.copyRegularPublicFile(path.join(this.rootDir, "public"), sourcePath, targetPath);
2084
+ return;
2085
+ }
2086
+ await fs.ensureDir(path.dirname(targetPath));
2087
+ await writeFileAtomic(targetPath, content);
2088
+ }
2089
+ async updateLlmsFiles(pages) {
2090
+ const publicDir = this.outputPath("public");
2091
+ await fs.ensureDir(publicDir);
2092
+ const { url: baseUrl, name, description } = await this.loadSiteMetadata();
2093
+ const resolvedPages = pages ?? (await this.buildAllPagesMeta());
2094
+ const pagesWithBodies = await Promise.all(resolvedPages.map((page) => this.readPageWithBody(page)));
2095
+ const docsContent = pagesWithBodies.map((page) => {
2096
+ const route = page.slug.replace(/^\/+|\/+$/g, "");
2097
+ const pagePath = route
2098
+ ? `app/(site)/${route}/page.tsx`
2099
+ : "app/(site)/page.tsx";
2100
+ return {
2101
+ uri: `docs://${route || "/"}`,
2102
+ name: page.title,
2103
+ path: pagePath,
2104
+ content: page.body,
2105
+ };
2106
+ });
2107
+ await writeFileAtomic(this.outputPath("services", "mcp", "docs-content.json"), JSON.stringify(docsContent, null, 2) + "\n");
2108
+ const indexContent = llmsIndexTemplate({
2109
+ siteName: name,
2110
+ siteDescription: description,
2111
+ baseUrl,
2112
+ pages: resolvedPages,
2113
+ sectionsConfig: this.sectionsConfig,
2114
+ });
2115
+ const fullContent = llmsFullTemplate({
2116
+ siteName: name,
2117
+ siteDescription: description,
2118
+ baseUrl,
2119
+ pages: pagesWithBodies,
2120
+ sectionsConfig: this.sectionsConfig,
2121
+ });
2122
+ await this.writePublicAggregate("llms.txt", indexContent);
2123
+ await this.writePublicAggregate("llms-full.txt", fullContent);
2124
+ const skillContent = skillMdTemplate({
2125
+ siteName: name,
2126
+ siteDescription: description,
2127
+ baseUrl,
2128
+ pages: resolvedPages,
2129
+ sectionsConfig: this.sectionsConfig,
2130
+ });
2131
+ await this.writePublicAggregate("skill.md", skillContent);
2132
+ // MCP discovery manifest. Needs an absolute URL, so it only exists when
2133
+ // config.json declares the site url; it is pruned if the url is removed.
2134
+ const mcpRelativePath = ".well-known/mcp.json";
2135
+ const mcpJsonPath = this.publicOutputFilePath(mcpRelativePath);
2136
+ const sourceMcpJsonPath = await this.findSourcePublicAsset(mcpRelativePath);
2137
+ if (sourceMcpJsonPath) {
2138
+ console.warn(chalk.yellow(`⚠️ Skipping generated public/${mcpRelativePath}; a project public asset owns that path`));
2139
+ await this.copyRegularPublicFile(path.join(this.rootDir, "public"), sourceMcpJsonPath, mcpJsonPath);
2140
+ }
2141
+ else if (baseUrl) {
2142
+ const mcpJson = JSON.stringify({
2143
+ mcpServers: {
2144
+ [siteDocsSlug(name)]: {
2145
+ url: `${baseUrl}/api/mcp`,
2146
+ transport: "streamable-http",
2147
+ },
2148
+ },
2149
+ }, null, 2) + "\n";
2150
+ await fs.ensureDir(path.dirname(mcpJsonPath));
2151
+ await writeFileAtomic(mcpJsonPath, mcpJson);
2152
+ }
2153
+ else if (await fs.pathExists(mcpJsonPath)) {
2154
+ await fs.remove(mcpJsonPath);
2155
+ }
2156
+ const nextRelativePaths = new Set();
2157
+ await Promise.all(pagesWithBodies.map(async (page) => {
2158
+ const relPath = page.slug === "" ? "index.md" : `${page.slug}.md`;
2159
+ if (isPublicAggregate(relPath))
2160
+ return;
2161
+ const sourceAssetPath = await this.findSourcePublicAsset(relPath);
2162
+ if (sourceAssetPath) {
2163
+ console.warn(chalk.yellow(`⚠️ Skipping generated public/${relPath}; a project public asset owns that path`));
2164
+ const targetPath = this.publicOutputFilePath(relPath);
2165
+ await this.copyRegularPublicFile(path.join(this.rootDir, "public"), sourceAssetPath, targetPath);
2166
+ return;
2167
+ }
2168
+ const targetPath = this.publicOutputFilePath(relPath);
2169
+ await fs.ensureDir(path.dirname(targetPath));
2170
+ await writeFileAtomic(targetPath, llmsPageTemplate(page, baseUrl));
2171
+ nextRelativePaths.add(relPath);
2172
+ }));
2173
+ const previousRelativePaths = this.artifacts.llmsPageFiles();
2174
+ for (const stale of previousRelativePaths) {
2175
+ if (!nextRelativePaths.has(stale)) {
2176
+ try {
2177
+ if (isPublicAggregate(stale))
2178
+ continue;
2179
+ if (await this.findSourcePublicAsset(stale))
2180
+ continue;
2181
+ const stalePath = resolveOutputPath(publicDir, stale);
2182
+ if (await fs.pathExists(stalePath)) {
2183
+ await fs.remove(stalePath);
2184
+ }
2185
+ }
2186
+ catch {
2187
+ // ignore
2188
+ }
2189
+ }
2190
+ }
2191
+ this.artifacts.replaceLlmsPageFiles(nextRelativePaths);
2192
+ await this.artifacts.save();
2193
+ console.log(chalk.green(`🤖 Generated llms.txt and llms-full.txt with ${resolvedPages.length} page(s)${baseUrl ? ` using ${baseUrl}` : " (relative URLs)"}`));
2194
+ }
2195
+ async stop() {
2196
+ if (this.watcher) {
2197
+ await this.watcher.close();
2198
+ console.log(chalk.yellow("👋 Stopped watching for MDX changes"));
2199
+ }
2200
+ if (this.configWatcher) {
2201
+ await this.configWatcher.close();
2202
+ console.log(chalk.yellow("👋 Stopped watching for config changes"));
2203
+ }
2204
+ if (this.fontWatcher) {
2205
+ await this.fontWatcher.close();
2206
+ console.log(chalk.yellow("👋 Stopped watching for font config changes"));
2207
+ }
2208
+ if (this.analyticsWatcher) {
2209
+ await this.analyticsWatcher.close();
2210
+ console.log(chalk.yellow("👋 Stopped watching for analytics config changes"));
2211
+ }
2212
+ if (this.openApiWatcher) {
2213
+ await this.openApiWatcher.close();
2214
+ console.log(chalk.yellow("👋 Stopped watching for OpenAPI spec changes"));
2215
+ }
2216
+ if (this.doccupineConfigWatcher) {
2217
+ await this.doccupineConfigWatcher.close();
2218
+ console.log(chalk.yellow("👋 Stopped watching for doccupine.json changes"));
2219
+ }
2220
+ if (this.publicWatcher) {
2221
+ await this.publicWatcher.close();
2222
+ console.log(chalk.yellow("👋 Stopped watching for public directory changes"));
2223
+ }
2224
+ if (this.rootDirWatcher) {
2225
+ await this.rootDirWatcher.close();
2226
+ }
2227
+ await this.mutationQueue;
2228
+ }
2229
+ }