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