doccupine 0.0.143 → 0.0.145

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 (66) hide show
  1. package/README.md +1 -1
  2. package/dist/cli.d.ts +6 -0
  3. package/dist/cli.js +130 -22
  4. package/dist/generator/api-reference-generator.d.ts +22 -0
  5. package/dist/generator/api-reference-generator.js +96 -0
  6. package/dist/generator/app-scaffolder.d.ts +18 -0
  7. package/dist/generator/app-scaffolder.js +49 -0
  8. package/dist/generator/generated-route-manager.d.ts +18 -0
  9. package/dist/generator/generated-route-manager.js +114 -0
  10. package/dist/generator/page-catalog.d.ts +21 -0
  11. package/dist/generator/page-catalog.js +75 -0
  12. package/dist/generator/page-renderer.d.ts +31 -0
  13. package/dist/generator/page-renderer.js +248 -0
  14. package/dist/generator/project-config-repository.d.ts +33 -0
  15. package/dist/generator/project-config-repository.js +191 -0
  16. package/dist/generator/public-asset-manager.d.ts +20 -0
  17. package/dist/generator/public-asset-manager.js +225 -0
  18. package/dist/generator/section-resolver.d.ts +13 -0
  19. package/dist/generator/section-resolver.js +150 -0
  20. package/dist/generator/secure-source-fs.d.ts +31 -0
  21. package/dist/generator/secure-source-fs.js +470 -0
  22. package/dist/generator/site-artifacts.d.ts +23 -0
  23. package/dist/generator/site-artifacts.js +156 -0
  24. package/dist/generator/watch-coordinator.d.ts +58 -0
  25. package/dist/generator/watch-coordinator.js +456 -0
  26. package/dist/lib/config-manager.d.ts +1 -0
  27. package/dist/lib/config-manager.js +194 -12
  28. package/dist/lib/generated-artifacts.d.ts +11 -2
  29. package/dist/lib/generated-artifacts.js +52 -7
  30. package/dist/lib/layout.d.ts +1 -17
  31. package/dist/lib/layout.js +5 -4
  32. package/dist/lib/openapi.d.ts +4 -0
  33. package/dist/lib/openapi.js +36 -4
  34. package/dist/lib/project-config.d.ts +3 -0
  35. package/dist/lib/project-config.js +110 -0
  36. package/dist/lib/types.d.ts +14 -1
  37. package/dist/mdx-to-nextjs-generator.d.ts +50 -34
  38. package/dist/mdx-to-nextjs-generator.js +760 -1740
  39. package/dist/templates/app/api/rag/route.d.ts +1 -1
  40. package/dist/templates/app/api/rag/route.js +2 -1
  41. package/dist/templates/components/Chat.d.ts +1 -1
  42. package/dist/templates/components/Chat.js +2 -1
  43. package/dist/templates/components/layout/Accordion.d.ts +1 -1
  44. package/dist/templates/components/layout/Accordion.js +2 -3
  45. package/dist/templates/mdx/api-playground.mdx.d.ts +1 -1
  46. package/dist/templates/mdx/api-playground.mdx.js +11 -2
  47. package/dist/templates/mdx/commands.mdx.d.ts +1 -1
  48. package/dist/templates/mdx/commands.mdx.js +26 -1
  49. package/dist/templates/mdx/media-and-assets.mdx.d.ts +1 -1
  50. package/dist/templates/mdx/media-and-assets.mdx.js +5 -0
  51. package/dist/templates/mdx/model-context-protocol.mdx.d.ts +1 -1
  52. package/dist/templates/mdx/model-context-protocol.mdx.js +2 -1
  53. package/dist/templates/mdx/platform/api-playground.mdx.d.ts +1 -1
  54. package/dist/templates/mdx/platform/api-playground.mdx.js +2 -2
  55. package/dist/templates/mdx/platform/publishing.mdx.d.ts +1 -1
  56. package/dist/templates/mdx/platform/publishing.mdx.js +3 -3
  57. package/dist/templates/mdx/space.mdx.d.ts +1 -1
  58. package/dist/templates/mdx/space.mdx.js +1 -5
  59. package/dist/templates/mdx/what-is-doccupine.mdx.d.ts +1 -1
  60. package/dist/templates/mdx/what-is-doccupine.mdx.js +8 -3
  61. package/dist/templates/next.config.js +2 -2
  62. package/dist/templates/package.js +3 -3
  63. package/dist/templates/proxy.js +1 -1
  64. package/dist/templates/services/mcp/server.d.ts +1 -1
  65. package/dist/templates/services/mcp/server.js +2 -12
  66. package/package.json +3 -3
@@ -1,64 +1,30 @@
1
- import chokidar from "chokidar";
2
1
  import fs from "fs-extra";
3
- import { constants } from "node:fs";
4
- import { open } from "node:fs/promises";
2
+ import { createHash } from "node:crypto";
5
3
  import path from "path";
6
4
  import chalk from "chalk";
7
- import { appStructure, obsoleteFiles, startingDocsStructure, } from "./lib/structures.js";
8
5
  import { rootLayoutTemplate, siteLayoutTemplate } from "./lib/layout.js";
9
6
  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";
7
+ import { GeneratedArtifacts, } from "./lib/generated-artifacts.js";
8
+ import { claimOutputDirectory, readOutputFileIfPresent, resolveOutputPath, } from "./lib/output-safety.js";
9
+ import { OpenApiRegistry, DEFAULT_API_BASE_SLUG } from "./lib/openapi.js";
10
+ import { getFullSlug, safeMatter, writeFileAtomic } from "./lib/utils.js";
16
11
  import { nextConfigTemplate } from "./templates/next.config.js";
17
- import { pnpmWorkspaceTemplate } from "./templates/pnpmWorkspace.js";
18
12
  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
- }
13
+ import { SecureSourceFs } from "./generator/secure-source-fs.js";
14
+ import { AppScaffolder } from "./generator/app-scaffolder.js";
15
+ import { ApiReferenceGenerator } from "./generator/api-reference-generator.js";
16
+ import { GeneratedRouteManager } from "./generator/generated-route-manager.js";
17
+ import { ProjectConfigRepository } from "./generator/project-config-repository.js";
18
+ import { PublicAssetManager } from "./generator/public-asset-manager.js";
19
+ import { WatchCoordinator } from "./generator/watch-coordinator.js";
20
+ import { addApiReferenceSection, determineSectionRoute, discoverSections, } from "./generator/section-resolver.js";
21
+ import { renderHomepage, renderMdxPage, renderSectionPage, } from "./generator/page-renderer.js";
22
+ import { buildRealPagesMeta as buildRealPageCatalog, mergePages as mergePageCatalog, parseMdxPageMeta, RouteCollisionError, } from "./generator/page-catalog.js";
23
+ import { loadSiteMetadata, loadSiteUrl as loadSiteUrlArtifact, writeLlmsFiles, writeRobots, writeSitemap, } from "./generator/site-artifacts.js";
50
24
  export class MDXToNextJSGenerator {
51
25
  watchDir;
52
26
  outputDir;
53
27
  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
28
  doccupineConfigFile = "doccupine.json";
63
29
  configFiles = [
64
30
  "theme.json",
@@ -78,449 +44,159 @@ export class MDXToNextJSGenerator {
78
44
  apiBaseSlug = DEFAULT_API_BASE_SLUG;
79
45
  apiRegistry = new OpenApiRegistry();
80
46
  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();
47
+ sourceFs;
48
+ appScaffolder;
49
+ apiReferenceGenerator;
50
+ generatedRouteManager;
51
+ projectConfigRepository;
52
+ publicAssetManager;
53
+ watchCoordinator;
54
+ retainExistingMdxOutput = true;
55
+ mdxSnapshotInitialized = false;
56
+ successfulMdxPages = new Map();
57
+ successfulMdxContent = new Map();
58
+ successfulMdxSourcesBySlug = new Map();
59
+ collisionBlockedMdxSources = new Set();
85
60
  constructor(watchDir, outputDir, openApiSpecs = [], rootDir = process.cwd()) {
86
61
  this.watchDir = path.resolve(watchDir);
87
62
  this.outputDir = path.resolve(outputDir);
88
63
  this.rootDir = path.resolve(rootDir);
89
64
  this.openApiSpecs = openApiSpecs;
90
65
  this.artifacts = new GeneratedArtifacts(this.outputDir);
66
+ this.sourceFs = new SecureSourceFs(this.watchDir, this.rootDir);
67
+ this.appScaffolder = new AppScaffolder(this.outputDir);
68
+ this.apiReferenceGenerator = new ApiReferenceGenerator(this.outputDir, this.artifacts);
69
+ this.generatedRouteManager = new GeneratedRouteManager(this.outputDir, this.artifacts);
70
+ this.projectConfigRepository = new ProjectConfigRepository(this.rootDir, this.outputDir, this.sourceFs, this.configFiles, this.fontConfigFile, this.analyticsConfigFile);
71
+ this.publicAssetManager = new PublicAssetManager(this.rootDir, this.outputDir, this.artifacts, this.sourceFs);
72
+ this.watchCoordinator = new WatchCoordinator({
73
+ watchDir: this.watchDir,
74
+ rootDir: this.rootDir,
75
+ configFiles: this.configFiles,
76
+ fontConfigFile: this.fontConfigFile,
77
+ analyticsConfigFile: this.analyticsConfigFile,
78
+ doccupineConfigFile: this.doccupineConfigFile,
79
+ sourceFs: this.sourceFs,
80
+ getOpenApiSpecs: () => this.openApiSpecs,
81
+ getOpenApiSourceFiles: () => this.apiRegistry.sourceFiles,
82
+ callbacks: {
83
+ syncOpenApiSpecWatcher: () => this.syncOpenApiSpecWatcher(),
84
+ handleFileChange: (action, filePath) => this.handleFileChange(action, filePath),
85
+ handleFileDelete: (filePath) => this.handleFileDelete(filePath),
86
+ handleConfigFileChange: (filePath) => this.handleConfigFileChange(filePath),
87
+ handleConfigFileDelete: (filePath) => this.handleConfigFileDelete(filePath),
88
+ handleFontConfigChange: () => this.handleFontConfigChange(),
89
+ handleFontConfigDelete: () => this.handleFontConfigDelete(),
90
+ handleAnalyticsConfigChange: () => this.handleAnalyticsConfigChange(),
91
+ handleAnalyticsConfigDelete: () => this.handleAnalyticsConfigDelete(),
92
+ handleDoccupineConfigChange: () => this.handleDoccupineConfigChange(),
93
+ handleOpenApiChange: () => this.handleOpenApiChange(),
94
+ copyPublicFiles: () => this.copyPublicFiles(),
95
+ handlePublicFileChange: (filePath) => this.handlePublicFileChange(filePath),
96
+ handlePublicFileDelete: (filePath) => this.handlePublicFileDelete(filePath),
97
+ processAllMDXFiles: () => this.reconcileMdxSources(),
98
+ },
99
+ });
91
100
  }
92
101
  outputPath(...segments) {
93
102
  return resolveOutputPath(this.outputDir, ...segments);
94
103
  }
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
104
  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;
105
+ return this.sourceFs.readMdxSourceFile(filePath);
254
106
  }
255
- async copyRegularPublicFile(publicDir, sourcePath, destPath) {
256
- const { data } = await this.readSafeSourceFile(publicDir, sourcePath, "public source", true);
257
- await writeFileAtomic(destPath, data);
107
+ async writeStarterFilesIfEmpty(files) {
108
+ return this.sourceFs.writeStarterFilesIfEmpty(files);
258
109
  }
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
- });
110
+ async refreshInitialDoccupineConfig() {
111
+ const configPath = path.join(this.rootDir, this.doccupineConfigFile);
112
+ if (!(await fs.pathExists(configPath)))
113
+ return undefined;
114
+ const { data, stat } = await this.sourceFs.readProjectSourceFile(configPath, "Doccupine configuration source");
115
+ const config = validateConfig(JSON.parse(data.toString("utf8")), this.rootDir);
116
+ this.openApiSpecs = normalizeOpenApiConfig(config.openapi);
117
+ const hash = createHash("sha256").update(data).digest("hex");
118
+ return `file:${stat.size}:${stat.mtimeMs}:${stat.dev}:${stat.ino}:${hash}`;
267
119
  }
268
120
  async init() {
269
121
  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(", ")}`));
122
+ await this.projectConfigRepository.preflightSourceFiles();
123
+ try {
124
+ await fs.ensureDir(this.watchDir);
125
+ await claimOutputDirectory(this.outputDir);
126
+ await this.artifacts.load();
127
+ // Starter documents are part of the initial source tree. Capture the
128
+ // watcher baseline after creating them, but before reading any source
129
+ // that contributes to generated output.
130
+ await this.createStartingDocs();
131
+ const doccupineSourceState = await this.refreshInitialDoccupineConfig();
132
+ await this.loadOpenApiRegistry();
133
+ await this.watchCoordinator.establishSourceSnapshot(this.projectConfigRepository.sourceSnapshotStates(), this.apiRegistry.sourceFingerprint, doccupineSourceState);
134
+ // Resolve sections after loading OpenAPI so the generated reference is
135
+ // present in the first layout, sitemap, and LLMS pass.
136
+ this.sectionsConfig = await this.resolveSections();
137
+ this.analyticsConfig = await this.loadAnalyticsConfig();
138
+ if (this.analyticsConfig) {
139
+ console.log(chalk.blue(`📊 Analytics enabled: ${this.analyticsConfig.provider}`));
140
+ }
141
+ this.retainExistingMdxOutput = false;
142
+ await this.createNextJSStructure();
143
+ await this.copyCustomConfigFiles();
144
+ await this.copyFontConfig();
145
+ await this.copyAnalyticsConfig();
146
+ await this.copyPublicFiles();
147
+ if (this.sectionsConfig) {
148
+ console.log(chalk.blue(`📑 Found ${this.sectionsConfig.length} section(s): ${this.sectionsConfig.map((s) => s.label).join(", ")}`));
149
+ }
150
+ await this.processAllMDXFiles();
151
+ console.log(chalk.green("✅ Initial setup complete!"));
152
+ console.log(chalk.cyan("💡 To start the Next.js dev server:"));
153
+ console.log(chalk.white(` cd ${path.relative(process.cwd(), this.outputDir)}`));
154
+ console.log(chalk.white(" install dependencies, then run the dev script"));
155
+ }
156
+ finally {
157
+ this.projectConfigRepository.clearSourceSnapshot();
295
158
  }
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
159
  }
306
160
  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();
161
+ return this.appScaffolder.createNextJsStructure(this.analyticsConfig, {
162
+ generateRootLayout: () => this.generateRootLayout(),
163
+ generateSiteLayout: () => this.generateSiteLayout(),
164
+ updateSitemap: () => this.updateSitemap(),
165
+ updateLlmsFiles: () => this.updateLlmsFiles(),
166
+ });
339
167
  }
340
168
  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
- }
169
+ return this.appScaffolder.createStartingDocs({
170
+ writeStarterFilesIfEmpty: (files) => this.writeStarterFilesIfEmpty(files),
171
+ });
349
172
  }
350
173
  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
- }
174
+ return this.projectConfigRepository.copyCustomConfigFiles();
364
175
  }
365
176
  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
- }
177
+ return this.projectConfigRepository.copyFontConfig();
376
178
  }
377
179
  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;
180
+ return this.projectConfigRepository.loadFontConfig();
389
181
  }
390
182
  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;
183
+ return this.projectConfigRepository.loadAnalyticsConfig();
405
184
  }
406
185
  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
- }
186
+ return this.projectConfigRepository.copyAnalyticsConfig(() => this.loadAnalyticsConfig());
417
187
  }
418
188
  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;
189
+ return this.projectConfigRepository.loadSectionsConfig();
474
190
  }
475
191
  async discoverSectionsFromFrontmatter() {
476
192
  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
- });
193
+ const documents = [];
194
+ for (const filePath of files) {
195
+ const { content } = await this.readMdxSourceFile(filePath);
196
+ const { data: frontmatter } = safeMatter(content, filePath);
197
+ documents.push({ filePath, frontmatter });
522
198
  }
523
- return sections;
199
+ return discoverSections(documents);
524
200
  }
525
201
  async resolveSections() {
526
202
  const fromFile = await this.loadSectionsConfig();
@@ -534,18 +210,7 @@ export class MDXToNextJSGenerator {
534
210
  * for the existing pages so both appear in the section switcher.
535
211
  */
536
212
  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];
213
+ return addApiReferenceSection(sections, !this.apiRegistry.isEmpty, this.apiBaseSlug);
549
214
  }
550
215
  async reloadSections() {
551
216
  console.log(chalk.cyan("📑 Sections configuration changed"));
@@ -577,66 +242,17 @@ export class MDXToNextJSGenerator {
577
242
  }
578
243
  }
579
244
  }
245
+ async reconcileMdxSources() {
246
+ await this.processAllMDXFiles();
247
+ }
580
248
  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
- };
249
+ return determineSectionRoute(filePath, frontmatter, this.sectionsConfig);
632
250
  }
633
251
  async handleConfigFileChange(filePath) {
634
252
  const fileName = path.basename(filePath);
635
253
  if (this.configFiles.includes(fileName)) {
636
- const sourcePath = path.join(this.rootDir, fileName);
637
- const destPath = this.outputPath(fileName);
638
254
  try {
639
- await this.copyRootSourceFile(sourcePath, destPath, "config source");
255
+ await this.projectConfigRepository.copyConfigFile(fileName);
640
256
  console.log(chalk.green(`📋 Updated ${fileName} in Next.js app`));
641
257
  if (fileName === "sections.json") {
642
258
  await this.reloadSections();
@@ -655,14 +271,8 @@ export class MDXToNextJSGenerator {
655
271
  async handleConfigFileDelete(filePath) {
656
272
  const fileName = path.basename(filePath);
657
273
  if (this.configFiles.includes(fileName)) {
658
- const destPath = this.outputPath(fileName);
659
274
  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`);
275
+ await this.projectConfigRepository.resetConfigFile(fileName);
666
276
  console.log(chalk.yellow(`🗑️ Reset ${fileName} to its generated default`));
667
277
  if (fileName === "sections.json") {
668
278
  await this.reloadSections();
@@ -680,10 +290,8 @@ export class MDXToNextJSGenerator {
680
290
  }
681
291
  async handleFontConfigChange() {
682
292
  console.log(chalk.cyan(`🔤 Font configuration changed`));
683
- const sourcePath = path.join(this.rootDir, this.fontConfigFile);
684
- const destPath = this.outputPath(this.fontConfigFile);
685
293
  try {
686
- await this.copyRootSourceFile(sourcePath, destPath, "font source");
294
+ await this.projectConfigRepository.copyFontConfigFile();
687
295
  console.log(chalk.green(`📋 Updated ${this.fontConfigFile} in Next.js app`));
688
296
  await this.updateRootLayout();
689
297
  console.log(chalk.green(`✅ Layout updated with new font configuration`));
@@ -694,10 +302,8 @@ export class MDXToNextJSGenerator {
694
302
  }
695
303
  async handleFontConfigDelete() {
696
304
  console.log(chalk.red(`🗑️ Font configuration deleted`));
697
- const destPath = this.outputPath(this.fontConfigFile);
698
305
  try {
699
- if (await fs.pathExists(destPath)) {
700
- await fs.remove(destPath);
306
+ if (await this.projectConfigRepository.removeFontConfig()) {
701
307
  console.log(chalk.yellow(`🗑️ Removed ${this.fontConfigFile} from Next.js app`));
702
308
  await this.updateRootLayout();
703
309
  console.log(chalk.green(`✅ Layout updated without font configuration`));
@@ -709,12 +315,10 @@ export class MDXToNextJSGenerator {
709
315
  }
710
316
  async handleAnalyticsConfigChange() {
711
317
  console.log(chalk.cyan(`📊 Analytics configuration changed`));
712
- const sourcePath = path.join(this.rootDir, this.analyticsConfigFile);
713
- const destPath = this.outputPath(this.analyticsConfigFile);
714
318
  try {
715
- await this.copyRootSourceFile(sourcePath, destPath, "analytics source");
716
- console.log(chalk.green(`📋 Updated ${this.analyticsConfigFile} in Next.js app`));
717
319
  this.analyticsConfig = await this.loadAnalyticsConfig();
320
+ await this.projectConfigRepository.writeAnalyticsConfig(this.analyticsConfig);
321
+ console.log(chalk.green(`📋 Updated ${this.analyticsConfigFile} in Next.js app`));
718
322
  // Regenerate dynamic templates that depend on analytics config
719
323
  await writeFileAtomic(this.outputPath("next.config.ts"), nextConfigTemplate(this.analyticsConfig));
720
324
  await writeFileAtomic(this.outputPath("proxy.ts"), proxyTemplate(this.analyticsConfig));
@@ -730,10 +334,9 @@ export class MDXToNextJSGenerator {
730
334
  }
731
335
  async handleAnalyticsConfigDelete() {
732
336
  console.log(chalk.red(`🗑️ Analytics configuration deleted`));
733
- const destPath = this.outputPath(this.analyticsConfigFile);
734
337
  try {
735
338
  // Write empty analytics.json so runtime imports don't break
736
- await writeFileAtomic(destPath, `{}\n`);
339
+ await this.projectConfigRepository.resetAnalyticsConfig();
737
340
  this.analyticsConfig = null;
738
341
  // Regenerate dynamic templates without analytics
739
342
  await writeFileAtomic(this.outputPath("next.config.ts"), nextConfigTemplate(null));
@@ -746,357 +349,240 @@ export class MDXToNextJSGenerator {
746
349
  }
747
350
  }
748
351
  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`));
352
+ return this.publicAssetManager.copyPublicFiles();
795
353
  }
796
354
  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
- }
355
+ return this.publicAssetManager.handlePublicFileChange(filePath, () => this.updateLlmsFiles());
814
356
  }
815
357
  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;
358
+ return this.publicAssetManager.handlePublicFileDelete(filePath, () => this.handlePublicFileChange(filePath), () => this.updateLlmsFiles());
359
+ }
360
+ async startWatching() {
361
+ return this.watchCoordinator.startWatching();
362
+ }
363
+ async parseMDXFile(file, source) {
364
+ return parseMdxPageMeta(file, source
365
+ ? async () => source
366
+ : (filePath) => this.readMdxSourceFile(filePath), (filePath, frontmatter) => this.determineSectionForFile(filePath, frontmatter), (reference) => this.apiRegistry.lookup(reference)?.method);
367
+ }
368
+ async captureMdxPass(files, seededSources = new Map(), refreshSections = false) {
369
+ const resolvedFiles = files ?? (await this.getAllMDXFiles());
370
+ const sources = new Map(seededSources);
371
+ await Promise.all(resolvedFiles.map(async (file) => {
372
+ const source = file.replace(/\\/g, "/");
373
+ if (!sources.has(source)) {
374
+ sources.set(source, await this.readMdxSourceFile(file));
828
375
  }
829
- if (await fs.pathExists(destPath)) {
830
- await fs.remove(destPath);
831
- console.log(chalk.yellow(`🗑️ Removed public/${relativePath} from Next.js app`));
376
+ }));
377
+ if (refreshSections) {
378
+ const configuredSections = await this.loadSectionsConfig();
379
+ if (configuredSections !== null) {
380
+ this.sectionsConfig = this.withApiReferenceSection(configuredSections);
832
381
  }
833
- if (isManagedPublicArtifact(relativePath)) {
834
- await this.updateLlmsFiles();
382
+ else {
383
+ const documents = resolvedFiles.map((filePath) => {
384
+ const source = sources.get(filePath.replace(/\\/g, "/"));
385
+ if (!source)
386
+ throw new Error(`Unable to snapshot ${filePath}`);
387
+ return {
388
+ filePath,
389
+ frontmatter: safeMatter(source.content, filePath).data,
390
+ };
391
+ });
392
+ this.sectionsConfig = this.withApiReferenceSection(discoverSections(documents));
835
393
  }
836
394
  }
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);
395
+ const pages = await buildRealPageCatalog(resolvedFiles, (file) => {
396
+ const source = sources.get(file.replace(/\\/g, "/"));
397
+ if (!source)
398
+ throw new Error(`Unable to snapshot ${file}`);
399
+ return this.parseMDXFile(file, source);
936
400
  });
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,
401
+ return { files: resolvedFiles, pages, sources };
402
+ }
403
+ async buildRealPagesMeta() {
404
+ return (await this.captureMdxPass()).pages;
405
+ }
406
+ async buildAllPagesMeta() {
407
+ const real = await this.buildRealPagesMeta();
408
+ return this.mergeAllPagesMeta(this.mdxSnapshotInitialized
409
+ ? this.successfulPagesInSourceOrder(real)
410
+ : real, new Set(real.map((page) => page.slug)));
411
+ }
412
+ mergeAllPagesMeta(real, declaredRealSlugs = new Set(real.map((page) => page.slug))) {
413
+ return mergePageCatalog(real, this.apiRegistry.isEmpty
414
+ ? []
415
+ : this.apiRegistry
416
+ .syntheticPages()
417
+ .filter((page) => !declaredRealSlugs.has(page.slug)));
418
+ }
419
+ successfulPagesInSourceOrder(realPages) {
420
+ return realPages.flatMap((page) => {
421
+ const successful = this.successfulMdxPages.get(page.path.replace(/\\/g, "/"));
422
+ return successful ? [successful] : [];
958
423
  });
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
- });
424
+ }
425
+ recordSuccessfulMdxPage(page, sourceContent) {
426
+ const source = page.path.replace(/\\/g, "/");
427
+ const previous = this.successfulMdxPages.get(source);
428
+ if (previous &&
429
+ previous.slug !== page.slug &&
430
+ this.successfulMdxSourcesBySlug.get(previous.slug) === source) {
431
+ this.successfulMdxSourcesBySlug.delete(previous.slug);
432
+ }
433
+ const otherSource = this.successfulMdxSourcesBySlug.get(page.slug);
434
+ if (otherSource && otherSource !== source) {
435
+ this.removeSuccessfulMdxPage(otherSource);
436
+ }
437
+ this.successfulMdxPages.set(source, page);
438
+ this.successfulMdxContent.set(source, sourceContent);
439
+ this.successfulMdxSourcesBySlug.set(page.slug, source);
440
+ this.collisionBlockedMdxSources.delete(source);
441
+ }
442
+ removeSuccessfulMdxPage(source) {
443
+ const successful = this.successfulMdxPages.get(source);
444
+ if (successful &&
445
+ this.successfulMdxSourcesBySlug.get(successful.slug) === source) {
446
+ this.successfulMdxSourcesBySlug.delete(successful.slug);
447
+ }
448
+ this.successfulMdxPages.delete(source);
449
+ this.successfulMdxContent.delete(source);
450
+ }
451
+ captureSuccessfulMdxState() {
452
+ return {
453
+ pages: new Map(this.successfulMdxPages),
454
+ content: new Map(this.successfulMdxContent),
455
+ sourcesBySlug: new Map(this.successfulMdxSourcesBySlug),
456
+ collisionBlockedSources: new Set(this.collisionBlockedMdxSources),
457
+ sections: this.sectionsConfig?.map((section) => ({ ...section })) ?? null,
458
+ routes: this.artifacts.routesFor("mdx"),
459
+ snapshotInitialized: this.mdxSnapshotInitialized,
460
+ };
461
+ }
462
+ restoreSuccessfulMdxState(state) {
463
+ this.successfulMdxPages = state.pages;
464
+ this.successfulMdxContent = state.content;
465
+ this.successfulMdxSourcesBySlug = state.sourcesBySlug;
466
+ this.collisionBlockedMdxSources = state.collisionBlockedSources;
467
+ this.sectionsConfig = state.sections;
468
+ this.mdxSnapshotInitialized = state.snapshotInitialized;
469
+ }
470
+ async rollbackPageCommits(commits) {
471
+ const errors = [];
472
+ for (const commit of [...commits].reverse()) {
473
+ try {
474
+ await commit.rollback();
969
475
  }
970
- })
971
- .on("error", (error) => {
972
- console.error(chalk.red("❌ Root dir watcher error:"), error);
973
- });
476
+ catch (error) {
477
+ errors.push(error);
478
+ }
479
+ }
480
+ return errors;
974
481
  }
975
- setupPublicWatcher() {
976
- if (this.publicWatcher) {
977
- return;
482
+ async rollbackFailedMdxCommit(error, state, commits) {
483
+ this.restoreSuccessfulMdxState(state);
484
+ const rollbackErrors = await this.rollbackPageCommits(commits);
485
+ if (rollbackErrors.length > 0) {
486
+ throw new AggregateError([error, ...rollbackErrors], "Unable to commit or restore generated MDX pages");
978
487
  }
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
- });
488
+ throw error;
1001
489
  }
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();
490
+ async rollbackCommittedMdxChange(error, state, commits) {
491
+ this.restoreSuccessfulMdxState(state);
492
+ const rollbackErrors = await this.rollbackPageCommits(commits);
493
+ const previousPages = [...state.pages.values()];
494
+ for (const page of previousPages) {
495
+ if (page.slug === "")
496
+ continue;
497
+ const content = state.content.get(page.path.replace(/\\/g, "/"));
498
+ if (content === undefined)
499
+ continue;
500
+ try {
501
+ await this.writePageForFile(page.path, content);
502
+ }
503
+ catch (rollbackError) {
504
+ rollbackErrors.push(rollbackError);
1013
505
  }
1014
506
  }
1015
- if (!lastModified) {
1016
- lastModified = stat.mtime.toISOString();
507
+ try {
508
+ await this.artifacts.replaceRoutesAndSave("mdx", state.routes.map(({ source, slug }) => ({ source, slug })));
1017
509
  }
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();
510
+ catch (rollbackError) {
511
+ rollbackErrors.push(rollbackError);
1025
512
  }
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
- };
513
+ try {
514
+ await this.refreshMdxDerivedOutput(previousPages, previousPages);
515
+ }
516
+ catch (rollbackError) {
517
+ rollbackErrors.push(rollbackError);
518
+ }
519
+ if (rollbackErrors.length > 0) {
520
+ throw new AggregateError([error, ...rollbackErrors], "Unable to refresh or restore generated MDX output");
521
+ }
522
+ throw error;
1046
523
  }
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);
524
+ dropMissingMdxSnapshots(realPages) {
525
+ const currentSources = new Set(realPages.map((page) => page.path.replace(/\\/g, "/")));
526
+ for (const source of this.successfulMdxPages.keys()) {
527
+ if (currentSources.has(source))
528
+ continue;
529
+ this.removeSuccessfulMdxPage(source);
530
+ this.collisionBlockedMdxSources.delete(source);
1057
531
  }
1058
- return real;
1059
532
  }
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];
533
+ async commitMdxSnapshot(realPages) {
534
+ this.dropMissingMdxSnapshots(realPages);
535
+ const successfulPages = this.successfulPagesInSourceOrder(realPages);
536
+ const previousRoutes = this.artifacts.routesFor("mdx");
537
+ await this.generatedRouteManager.replaceMdxRoutes(successfulPages);
538
+ try {
539
+ await this.removeStaleMdxRoutes(successfulPages, previousRoutes);
540
+ }
541
+ catch (error) {
542
+ console.error(chalk.red("❌ Error removing stale MDX routes; cleanup will retry:"), error);
543
+ }
544
+ this.mdxSnapshotInitialized = true;
545
+ return successfulPages;
1076
546
  }
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);
547
+ async refreshMdxDerivedOutput(realPages, successfulPages) {
548
+ if (!this.apiRegistry.isEmpty ||
549
+ this.artifacts.routesFor("openapi").length > 0) {
550
+ await this.writeApiPages(realPages);
551
+ }
552
+ const declaredSlugs = new Set(realPages.map((page) => page.slug));
553
+ const pages = this.mergeAllPagesMeta(successfulPages, declaredSlugs);
554
+ await this.refreshSiteAggregates(pages, declaredSlugs);
555
+ }
556
+ async readAggregateMdxSource(filePath) {
557
+ const cached = this.successfulMdxContent.get(filePath.replace(/\\/g, "/"));
558
+ if (this.mdxSnapshotInitialized && cached !== undefined) {
559
+ return { content: cached };
1099
560
  }
561
+ return this.readMdxSourceFile(filePath);
562
+ }
563
+ homepageSource(frontmatter, mdxContent) {
564
+ return {
565
+ content: mdxContent,
566
+ title: frontmatter.title || "Welcome",
567
+ description: frontmatter.description || "",
568
+ icon: frontmatter.icon,
569
+ image: frontmatter.image,
570
+ name: frontmatter.name,
571
+ date: typeof frontmatter.date === "string" ? frontmatter.date : undefined,
572
+ updated: typeof frontmatter.updated === "string"
573
+ ? frontmatter.updated
574
+ : undefined,
575
+ openapi: typeof frontmatter.openapi === "string"
576
+ ? frontmatter.openapi
577
+ : undefined,
578
+ rss: frontmatter.rss === true,
579
+ };
580
+ }
581
+ async removeOwnedRoute(slug) {
582
+ return this.generatedRouteManager.removeOwnedRoute(slug);
583
+ }
584
+ async removeStaleMdxRoutes(realPages, previousRoutes = this.artifacts.routesFor("mdx")) {
585
+ return this.generatedRouteManager.removeStaleMdxRoutes(realPages, (slug) => this.removeOwnedRoute(slug), previousRoutes);
1100
586
  }
1101
587
  /**
1102
588
  * Writes the generated page(s) for a single MDX file: the doc page and, for a
@@ -1105,100 +591,177 @@ export class MDXToNextJSGenerator {
1105
591
  * redirects) - the caller batches those so a bulk build runs them once at the
1106
592
  * end instead of once per file (which is what made large builds O(n²)).
1107
593
  */
1108
- async writePageForFile(filePath) {
1109
- const { content } = await this.readMdxSourceFile(filePath);
594
+ async writePageForFile(filePath, content) {
595
+ const commits = [];
1110
596
  const { data: frontmatter, content: mdxContent } = safeMatter(content, filePath);
1111
597
  const { sectionSlug, pageSlug } = this.determineSectionForFile(filePath, frontmatter);
1112
598
  const fullSlug = getFullSlug(pageSlug, sectionSlug);
1113
599
  const isIndex = filePath === "index.mdx" || filePath === "./index.mdx";
1114
600
  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`));
601
+ try {
602
+ if (isIndex) {
603
+ // The homepage is emitted by updatePagesIndex() in the aggregate pass, so
604
+ // validate it here before its source enters the successful snapshot.
605
+ console.log(chalk.blue("🏠 Updating homepage with index.mdx content"));
606
+ renderHomepage(this.homepageSource(frontmatter, mdxContent), typeof frontmatter.openapi === "string"
607
+ ? this.apiRegistry.lookup(frontmatter.openapi)
608
+ : undefined);
609
+ }
610
+ else {
611
+ const mdxFile = {
612
+ path: filePath,
613
+ content: mdxContent,
614
+ frontmatter,
615
+ slug: fullSlug,
616
+ };
617
+ // `openapi: <METHOD> <path>` (or an operationId) in frontmatter renders
618
+ // that operation's playground inline with the author's prose. An unknown
619
+ // reference is logged and the page still renders its prose (graceful).
620
+ let apiOperation;
621
+ if (frontmatter.openapi) {
622
+ apiOperation = this.apiRegistry.lookup(String(frontmatter.openapi));
623
+ if (!apiOperation) {
624
+ console.error(chalk.red(`❌ openapi frontmatter "${frontmatter.openapi}" in ${filePath} not found in any spec`));
625
+ }
1135
626
  }
627
+ commits.push(await this.generatePageFromMDX(mdxFile, apiOperation ? { apiOperation } : undefined));
628
+ }
629
+ if (isSectionIndex) {
630
+ commits.push(await this.updateSectionIndex(sectionSlug, frontmatter, mdxContent, filePath));
1136
631
  }
1137
- await this.generatePageFromMDX(mdxFile, apiOperation ? { apiOperation } : undefined);
632
+ return commits;
1138
633
  }
1139
- if (isSectionIndex) {
1140
- await this.updateSectionIndex(sectionSlug, frontmatter, mdxContent, filePath);
634
+ catch (error) {
635
+ const rollbackErrors = await this.rollbackPageCommits(commits);
636
+ if (rollbackErrors.length > 0) {
637
+ throw new AggregateError([error, ...rollbackErrors], `Unable to generate or restore ${filePath}`);
638
+ }
639
+ throw error;
1141
640
  }
1142
641
  }
1143
- /**
642
+ async retryMdxPages(snapshot, shouldRetry, commits) {
643
+ for (const page of snapshot.pages) {
644
+ const source = page.path.replace(/\\/g, "/");
645
+ if (!shouldRetry(source, page))
646
+ continue;
647
+ const currentOwner = this.successfulMdxSourcesBySlug.get(page.slug);
648
+ if (currentOwner && currentOwner !== source)
649
+ continue;
650
+ const captured = snapshot.sources.get(source);
651
+ if (!captured)
652
+ continue;
653
+ try {
654
+ commits.push(...(await this.writePageForFile(page.path, captured.content)));
655
+ this.recordSuccessfulMdxPage(page, captured.content);
656
+ }
657
+ catch (error) {
658
+ console.error(chalk.red(`❌ Error processing ${page.path}:`), error);
659
+ }
660
+ }
661
+ }
662
+ /**
1144
663
  * Regenerates every file that depends on the full set of pages (pages index,
1145
664
  * root/site layout, sitemap, llms files, section redirects). Parses all MDX
1146
665
  * exactly once and threads the result through each generator, so one refresh
1147
666
  * is a single scan rather than one scan per generator.
1148
667
  */
1149
- async refreshSiteAggregates(resolvedPages) {
668
+ async refreshSiteAggregates(resolvedPages, declaredSlugs) {
1150
669
  const pages = resolvedPages ?? (await this.buildAllPagesMeta());
1151
670
  await this.updatePagesIndex();
1152
671
  await this.updateRootLayout(pages);
1153
672
  await this.updateSitemap(pages);
1154
673
  await this.updateLlmsFiles(pages);
1155
- await this.generateSectionIndexPages(pages);
674
+ await this.generateSectionIndexPages(pages, declaredSlugs);
1156
675
  }
1157
676
  async handleFileChange(action, filePath) {
1158
677
  console.log(chalk.cyan(`📝 File ${action}: ${filePath}`));
1159
- await this.readMdxSourceFile(filePath);
678
+ const normalizedSource = filePath.replace(/\\/g, "/");
679
+ const changedSource = await this.readMdxSourceFile(filePath);
680
+ const previousState = this.captureSuccessfulMdxState();
681
+ const pageCommits = [];
682
+ let pageRendered = false;
1160
683
  try {
1161
684
  // Validate the complete route set before writing this page so a collision
1162
685
  // 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();
686
+ const snapshot = await this.captureMdxPass(undefined, new Map([[normalizedSource, changedSource]]), true);
687
+ const realPages = snapshot.pages;
1166
688
  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);
689
+ if (!currentPage)
690
+ throw new Error(`Unable to resolve ${filePath}`);
691
+ try {
692
+ pageCommits.push(...(await this.writePageForFile(filePath, changedSource.content)));
693
+ this.recordSuccessfulMdxPage(currentPage, changedSource.content);
694
+ pageRendered = true;
695
+ }
696
+ catch (error) {
697
+ if (this.retainExistingMdxOutput) {
698
+ this.restoreSuccessfulMdxState(previousState);
699
+ }
700
+ else {
701
+ this.removeSuccessfulMdxPage(normalizedSource);
702
+ }
703
+ const successfulPages = await this.commitMdxSnapshot(realPages);
704
+ await this.refreshMdxDerivedOutput(realPages, successfulPages);
705
+ throw error;
706
+ }
707
+ await this.retryMdxPages(snapshot, (source) => source !== normalizedSource &&
708
+ this.collisionBlockedMdxSources.has(source), pageCommits);
709
+ let successfulPages = [];
710
+ try {
711
+ successfulPages = await this.commitMdxSnapshot(realPages);
712
+ }
713
+ catch (error) {
714
+ await this.rollbackFailedMdxCommit(error, previousState, pageCommits);
715
+ }
716
+ try {
717
+ await this.refreshMdxDerivedOutput(realPages, successfulPages);
718
+ }
719
+ catch (error) {
720
+ await this.rollbackCommittedMdxChange(error, previousState, pageCommits);
721
+ }
1178
722
  console.log(chalk.green(`✅ Generated page for: ${filePath}`));
1179
723
  await this.maybeUpdateSections();
1180
724
  }
1181
725
  catch (error) {
726
+ if (!pageRendered && error instanceof RouteCollisionError) {
727
+ this.collisionBlockedMdxSources.add(normalizedSource);
728
+ for (const source of error.sources) {
729
+ this.collisionBlockedMdxSources.add(source.replace(/\\/g, "/"));
730
+ }
731
+ }
1182
732
  console.error(chalk.red(`❌ Error processing ${filePath}:`), error);
1183
733
  }
1184
734
  }
1185
735
  async handleFileDelete(filePath) {
1186
736
  console.log(chalk.red(`🗑️ File deleted: ${filePath}`));
737
+ const previousState = this.captureSuccessfulMdxState();
738
+ const pageCommits = [];
1187
739
  try {
740
+ const normalizedSource = filePath.replace(/\\/g, "/");
741
+ this.removeSuccessfulMdxPage(normalizedSource);
742
+ this.collisionBlockedMdxSources.delete(normalizedSource);
1188
743
  if (filePath === "index.mdx" || filePath === "./index.mdx") {
1189
744
  console.log(chalk.blue("🏠 Updating homepage - index.mdx deleted"));
1190
745
  }
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();
746
+ const snapshot = await this.captureMdxPass(undefined, undefined, true);
747
+ const realPages = snapshot.pages;
748
+ await this.retryMdxPages(snapshot, (source, page) => {
749
+ return (this.collisionBlockedMdxSources.has(source) ||
750
+ this.successfulMdxPages.get(source)?.slug !== page.slug);
751
+ }, pageCommits);
752
+ let successfulPages = [];
753
+ try {
754
+ successfulPages = await this.commitMdxSnapshot(realPages);
755
+ }
756
+ catch (error) {
757
+ await this.rollbackFailedMdxCommit(error, previousState, pageCommits);
758
+ }
759
+ try {
760
+ await this.refreshMdxDerivedOutput(realPages, successfulPages);
761
+ }
762
+ catch (error) {
763
+ await this.rollbackCommittedMdxChange(error, previousState, pageCommits);
1198
764
  }
1199
- if (!this.apiRegistry.isEmpty)
1200
- await this.writeApiPages();
1201
- await this.refreshSiteAggregates();
1202
765
  console.log(chalk.green(`✅ Removed page for: ${filePath}`));
1203
766
  await this.maybeUpdateSections();
1204
767
  }
@@ -1207,71 +770,69 @@ export class MDXToNextJSGenerator {
1207
770
  }
1208
771
  }
1209
772
  async processAllMDXFiles() {
773
+ const previousState = this.captureSuccessfulMdxState();
774
+ const pageCommits = [];
1210
775
  const files = await this.getAllMDXFiles();
1211
776
  // Fail before writing any page when two source files resolve to one route.
1212
- const realPages = await this.buildRealPagesMeta();
1213
- await this.removeStaleMdxRoutes(realPages);
777
+ let snapshot;
778
+ try {
779
+ snapshot = await this.captureMdxPass(files, undefined, true);
780
+ }
781
+ catch (error) {
782
+ if (error instanceof RouteCollisionError) {
783
+ // The catalog rejects the entire pass, so any source may have an
784
+ // unapplied content change even when it is not one of the colliders.
785
+ for (const source of files) {
786
+ this.collisionBlockedMdxSources.add(source.replace(/\\/g, "/"));
787
+ }
788
+ }
789
+ throw error;
790
+ }
791
+ const realPages = snapshot.pages;
1214
792
  // Write each page first (the only genuinely per-file work), then run the
1215
793
  // site-wide aggregations a single time. Doing the aggregations per file
1216
794
  // re-scanned and re-parsed every MDX file on each iteration, which made a
1217
795
  // full build O(n²); batching them makes it O(n). A single bad file is
1218
796
  // logged and skipped so it never aborts the whole build.
797
+ const pagesBySource = new Map(realPages.map((page) => [page.path.replace(/\\/g, "/"), page]));
1219
798
  for (const file of files) {
1220
799
  console.log(chalk.cyan(`📝 Processing: ${file}`));
800
+ const normalizedSource = file.replace(/\\/g, "/");
1221
801
  try {
1222
- await this.writePageForFile(file);
802
+ const sourceContent = snapshot.sources.get(normalizedSource)?.content;
803
+ if (sourceContent === undefined) {
804
+ throw new Error(`Unable to snapshot ${file}`);
805
+ }
806
+ pageCommits.push(...(await this.writePageForFile(file, sourceContent)));
807
+ const page = pagesBySource.get(normalizedSource);
808
+ if (!page)
809
+ throw new Error(`Unable to resolve ${file}`);
810
+ this.recordSuccessfulMdxPage(page, sourceContent);
1223
811
  }
1224
812
  catch (error) {
813
+ if (!this.retainExistingMdxOutput) {
814
+ this.removeSuccessfulMdxPage(normalizedSource);
815
+ }
1225
816
  console.error(chalk.red(`❌ Error processing ${file}:`), error);
1226
817
  }
1227
818
  }
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);
819
+ let successfulPages = [];
820
+ try {
821
+ successfulPages = await this.commitMdxSnapshot(realPages);
822
+ }
823
+ catch (error) {
824
+ await this.rollbackFailedMdxCommit(error, previousState, pageCommits);
825
+ }
826
+ this.retainExistingMdxOutput = true;
827
+ try {
828
+ await this.refreshMdxDerivedOutput(realPages, successfulPages);
829
+ }
830
+ catch (error) {
831
+ await this.rollbackCommittedMdxChange(error, previousState, pageCommits);
832
+ }
1234
833
  }
1235
834
  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;
835
+ return this.sourceFs.getAllMdxFiles();
1275
836
  }
1276
837
  async generateRootLayout() {
1277
838
  const fontConfig = await this.loadFontConfig();
@@ -1282,15 +843,19 @@ export class MDXToNextJSGenerator {
1282
843
  const resolvedPages = pages ?? (await this.buildAllPagesMeta());
1283
844
  return siteLayoutTemplate(resolvedPages, this.sectionsConfig);
1284
845
  }
1285
- async generateSectionIndexPages(pages) {
846
+ async generateSectionIndexPages(pages, declaredSlugs) {
1286
847
  const nextSlugs = new Set();
848
+ const resolvedPages = pages ?? (await this.buildAllPagesMeta());
849
+ const occupiedSlugs = new Set(resolvedPages.map((page) => page.slug));
850
+ const resolvedDeclaredSlugs = new Set(occupiedSlugs);
851
+ for (const slug of declaredSlugs ?? [])
852
+ resolvedDeclaredSlugs.add(slug);
1287
853
  if (this.sectionsConfig && this.sectionsConfig.length > 0) {
1288
- const resolvedPages = pages ?? (await this.buildAllPagesMeta());
1289
854
  for (const section of this.sectionsConfig) {
1290
855
  if (section.slug === "")
1291
856
  continue;
1292
857
  // Check if a page already exists at the section root
1293
- const hasIndex = resolvedPages.some((p) => p.slug === section.slug);
858
+ const hasIndex = resolvedDeclaredSlugs.has(section.slug);
1294
859
  if (hasIndex)
1295
860
  continue;
1296
861
  // Find the first page in this section
@@ -1317,194 +882,126 @@ export default function SectionIndex() {
1317
882
  console.log(chalk.blue(`🔀 Generated section index redirect: /${section.slug} -> /${firstPage.slug}`));
1318
883
  }
1319
884
  }
1320
- await this.cleanupStaleSectionIndexPages(nextSlugs);
885
+ await this.cleanupStaleSectionIndexPages(nextSlugs, occupiedSlugs);
1321
886
  }
1322
887
  /**
1323
888
  * Removes section index redirects written earlier in this session whose
1324
889
  * 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.
890
+ * `openapi` config is removed mid-watch). Slugs now occupied by real pages
891
+ * are preserved. Fresh processes start clean anyway - init() wipes app/ -
892
+ * so in-session tracking is enough.
1329
893
  */
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;
894
+ async cleanupStaleSectionIndexPages(nextSlugs, occupiedSlugs) {
895
+ return this.generatedRouteManager.cleanupStaleSectionIndexPages(nextSlugs, occupiedSlugs, (dir, stopDir) => this.removeEmptyDirsUpTo(dir, stopDir));
1350
896
  }
1351
897
  /** Best-effort removal of now-empty directories up to (not incl.) stopDir. */
1352
898
  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);
899
+ return this.generatedRouteManager.removeEmptyDirsUpTo(dir, stopDir);
900
+ }
901
+ generatedFileSegments(filePath) {
902
+ return path
903
+ .relative(fs.realpathSync(this.outputDir), filePath)
904
+ .split(path.sep)
905
+ .filter(Boolean);
906
+ }
907
+ async readGeneratedFile(filePath) {
908
+ return readOutputFileIfPresent(this.outputDir, ...this.generatedFileSegments(filePath));
909
+ }
910
+ async restoreGeneratedFile(filePath, content) {
911
+ const target = this.outputPath(...this.generatedFileSegments(filePath));
912
+ if (content === null) {
913
+ await fs.remove(target);
914
+ }
915
+ else {
916
+ await writeFileAtomic(target, content);
917
+ }
918
+ }
919
+ async commitRenderedPage(pagePath, rendered) {
920
+ if (rendered.rssRoute.action === "preserve") {
921
+ const previousPage = await this.readGeneratedFile(pagePath);
922
+ await writeFileAtomic(pagePath, rendered.pageContent);
923
+ return {
924
+ rollback: () => this.restoreGeneratedFile(pagePath, previousPage),
925
+ };
926
+ }
927
+ const rssDir = resolveOutputPath(path.dirname(pagePath), "rss.xml");
928
+ const rssPath = resolveOutputPath(path.dirname(pagePath), "rss.xml", "route.ts");
929
+ const [previousPage, previousRss] = await Promise.all([
930
+ this.readGeneratedFile(pagePath),
931
+ this.readGeneratedFile(rssPath),
932
+ ]);
933
+ let pageChanged = false;
934
+ let rssChanged = false;
935
+ try {
936
+ if (rendered.rssRoute.action === "write") {
937
+ await writeFileAtomic(rssPath, rendered.rssRoute.content);
938
+ rssChanged = true;
939
+ await writeFileAtomic(pagePath, rendered.pageContent);
940
+ pageChanged = true;
1361
941
  }
1362
- catch {
1363
- return;
942
+ else {
943
+ await writeFileAtomic(pagePath, rendered.pageContent);
944
+ pageChanged = true;
945
+ await fs.remove(rssPath);
946
+ rssChanged = true;
947
+ await this.removeEmptyDirsUpTo(rssDir, path.dirname(pagePath));
948
+ }
949
+ }
950
+ catch (error) {
951
+ const rollbackErrors = [];
952
+ if (rssChanged) {
953
+ try {
954
+ await this.restoreGeneratedFile(rssPath, previousRss);
955
+ }
956
+ catch (rollbackError) {
957
+ rollbackErrors.push(rollbackError);
958
+ }
959
+ }
960
+ if (pageChanged) {
961
+ try {
962
+ await this.restoreGeneratedFile(pagePath, previousPage);
963
+ }
964
+ catch (rollbackError) {
965
+ rollbackErrors.push(rollbackError);
966
+ }
967
+ }
968
+ if (rollbackErrors.length > 0) {
969
+ throw new AggregateError([error, ...rollbackErrors], `Unable to publish or restore generated page ${pagePath}`);
1364
970
  }
1365
- current = path.dirname(current);
971
+ throw error;
1366
972
  }
973
+ return {
974
+ rollback: async () => {
975
+ const rollbackErrors = [];
976
+ try {
977
+ await this.restoreGeneratedFile(rssPath, previousRss);
978
+ }
979
+ catch (error) {
980
+ rollbackErrors.push(error);
981
+ }
982
+ try {
983
+ await this.restoreGeneratedFile(pagePath, previousPage);
984
+ }
985
+ catch (error) {
986
+ rollbackErrors.push(error);
987
+ }
988
+ if (rollbackErrors.length > 0) {
989
+ throw new AggregateError(rollbackErrors, `Unable to restore generated page ${pagePath}`);
990
+ }
991
+ },
992
+ };
1367
993
  }
1368
994
  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
- `;
995
+ const rendered = renderMdxPage(mdxFile, options);
1475
996
  const pagePath = resolveOutputPath(this.outputDir, "app", "(site)", mdxFile.slug, "page.tsx");
1476
997
  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
- }
998
+ return this.commitRenderedPage(pagePath, rendered);
1502
999
  }
1503
1000
  /** Parses the configured OpenAPI spec(s) into the shared registry. */
1504
1001
  async loadOpenApiRegistry() {
1505
1002
  if (this.openApiSpecs.length === 0)
1506
1003
  return;
1507
- await this.apiRegistry.load(this.openApiSpecs, this.rootDir, this.apiBaseSlug);
1004
+ this.apiRegistry = (await this.loadStableOpenApiRegistry(this.openApiSpecs)).registry;
1508
1005
  if (!this.apiRegistry.isEmpty) {
1509
1006
  console.log(chalk.blue(`📘 Loaded ${this.apiRegistry.all.length} API endpoint(s) from ${this.openApiSpecs.length} spec(s)`));
1510
1007
  }
@@ -1516,83 +1013,28 @@ export default function Page() {
1516
1013
  * - it still emits an empty allowlist and prunes any previously generated
1517
1014
  * pages (e.g. after the `openapi` config is removed).
1518
1015
  */
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`));
1016
+ async writeApiPages(realPages, options = {}) {
1017
+ const resolvedRealPages = realPages ?? (await this.buildRealPagesMeta());
1018
+ const blockedRealPages = [...resolvedRealPages];
1019
+ const blockedSlugs = new Set(blockedRealPages.map((page) => page.slug));
1020
+ for (const page of this.successfulMdxPages.values()) {
1021
+ if (blockedSlugs.has(page.slug))
1555
1022
  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)`));
1023
+ blockedSlugs.add(page.slug);
1024
+ blockedRealPages.push(page);
1569
1025
  }
1026
+ const occupiedMdxSlugs = new Set([...this.successfulMdxPages.values()].map((page) => page.slug));
1027
+ return this.apiReferenceGenerator.writePages(this.apiRegistry, this.apiBaseSlug, blockedRealPages, async (mdxFile, options) => {
1028
+ await this.generatePageFromMDX(mdxFile, options);
1029
+ }, () => this.writeApiAllowlist(), (nextRoutes) => this.cleanupStaleApiPages(nextRoutes, occupiedMdxSlugs, options.additionalPreviousRoutes), options.writtenRoutes);
1570
1030
  }
1571
1031
  /** Writes the request-execution allowlist (overwrites the shipped stub). */
1572
1032
  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`);
1033
+ return this.apiReferenceGenerator.writeAllowlist(this.apiRegistry);
1576
1034
  }
1577
1035
  /** 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();
1036
+ async cleanupStaleApiPages(nextRoutes, occupiedMdxSlugs, additionalPreviousRoutes = []) {
1037
+ return this.apiReferenceGenerator.cleanupStalePages(nextRoutes, occupiedMdxSlugs, (slug) => this.removeOwnedRoute(slug), additionalPreviousRoutes);
1596
1038
  }
1597
1039
  /**
1598
1040
  * (Re)points the spec-file watcher at the currently configured spec paths.
@@ -1600,41 +1042,108 @@ export default function Page() {
1600
1042
  * so specs added mid-session are watched without a restart.
1601
1043
  */
1602
1044
  async syncOpenApiSpecWatcher() {
1603
- if (this.openApiWatcher) {
1604
- await this.openApiWatcher.close();
1605
- this.openApiWatcher = null;
1045
+ return this.watchCoordinator.syncOpenApiSpecWatcher(this.openApiSpecs, this.apiRegistry.sourceFiles);
1046
+ }
1047
+ async openApiSourceState(registry) {
1048
+ return (await Promise.all(registry.sourceFiles.map(async (sourcePath) => {
1049
+ return `${sourcePath}:${await this.sourceFs.pathState(sourcePath, true)}`;
1050
+ }))).join("\n");
1051
+ }
1052
+ async loadStableOpenApiRegistry(specs) {
1053
+ for (let attempt = 0; attempt < 3; attempt += 1) {
1054
+ const registry = new OpenApiRegistry();
1055
+ await registry.load(specs, this.rootDir, this.apiBaseSlug);
1056
+ const current = await this.openApiSourceState(registry);
1057
+ if (registry.sourceFingerprint === current) {
1058
+ return { registry, sourceState: current };
1059
+ }
1060
+ }
1061
+ throw new Error("OpenAPI sources changed repeatedly while being loaded");
1062
+ }
1063
+ async applyStableOpenApiRefresh(specs, syncWatcher) {
1064
+ let candidate = await this.loadStableOpenApiRegistry(specs);
1065
+ await this.applyOpenApiRefresh(candidate.registry, specs, syncWatcher);
1066
+ // Once the new watcher is ready, compare its source against the exact
1067
+ // version rendered above. A change in the retargeting window is replayed
1068
+ // explicitly because ignoreInitial watchers cannot report it.
1069
+ for (let attempt = 0; attempt < 3; attempt += 1) {
1070
+ if ((await this.openApiSourceState(candidate.registry)) ===
1071
+ candidate.sourceState) {
1072
+ return;
1073
+ }
1074
+ candidate = await this.loadStableOpenApiRegistry(specs);
1075
+ await this.applyOpenApiRefresh(candidate.registry, specs, false);
1606
1076
  }
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
- });
1077
+ throw new Error("OpenAPI sources changed repeatedly while being generated");
1621
1078
  }
1622
1079
  /**
1623
1080
  * Reparses the spec(s) and rewrites everything derived from them: the
1624
1081
  * endpoint pages and allowlist, the sections (the "API Reference" section
1625
1082
  * appears and disappears with the registry), and the site aggregates.
1626
1083
  */
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();
1084
+ async applyOpenApiRefresh(nextRegistry, nextSpecs, syncWatcher) {
1085
+ const previousRegistry = this.apiRegistry;
1086
+ const previousSpecs = this.openApiSpecs;
1087
+ const previousSections = this.sectionsConfig;
1088
+ const previousRoutes = this.artifacts.routesFor("openapi");
1089
+ const candidateRoutes = new Map();
1090
+ let watcherSyncAttempted = false;
1091
+ try {
1092
+ this.apiRegistry = nextRegistry;
1093
+ this.openApiSpecs = nextSpecs;
1094
+ this.sectionsConfig = await this.resolveSections();
1095
+ await this.writeApiPages(undefined, { writtenRoutes: candidateRoutes });
1096
+ await this.refreshSiteAggregates();
1097
+ if (syncWatcher) {
1098
+ watcherSyncAttempted = true;
1099
+ await this.syncOpenApiSpecWatcher();
1100
+ }
1101
+ }
1102
+ catch (error) {
1103
+ this.apiRegistry = previousRegistry;
1104
+ this.openApiSpecs = previousSpecs;
1105
+ this.sectionsConfig = previousSections;
1106
+ const rollbackErrors = [];
1107
+ if (watcherSyncAttempted) {
1108
+ try {
1109
+ await this.syncOpenApiSpecWatcher();
1110
+ }
1111
+ catch (rollbackError) {
1112
+ rollbackErrors.push(rollbackError);
1113
+ }
1114
+ }
1115
+ const previousSlugs = new Set(previousRoutes.map((route) => route.slug));
1116
+ const occupiedMdxSlugs = new Set([...this.successfulMdxPages.values()].map((page) => page.slug));
1117
+ for (const slug of new Set(candidateRoutes.values())) {
1118
+ if (previousSlugs.has(slug) || occupiedMdxSlugs.has(slug))
1119
+ continue;
1120
+ try {
1121
+ await this.removeOwnedRoute(slug);
1122
+ }
1123
+ catch (rollbackError) {
1124
+ rollbackErrors.push(rollbackError);
1125
+ }
1126
+ }
1127
+ try {
1128
+ await this.writeApiPages(undefined, {
1129
+ additionalPreviousRoutes: [...candidateRoutes].map(([source, slug]) => ({ kind: "openapi", source, slug })),
1130
+ });
1131
+ await this.refreshSiteAggregates();
1132
+ }
1133
+ catch (rollbackError) {
1134
+ rollbackErrors.push(rollbackError);
1135
+ }
1136
+ if (rollbackErrors.length > 0) {
1137
+ throw new AggregateError([error, ...rollbackErrors], "Unable to apply or restore the OpenAPI reference");
1138
+ }
1139
+ throw error;
1140
+ }
1632
1141
  }
1633
1142
  /** Reparses the spec(s) and regenerates the API reference on a watch event. */
1634
1143
  async handleOpenApiChange() {
1635
1144
  console.log(chalk.cyan("📘 OpenAPI spec changed - regenerating API reference"));
1636
1145
  try {
1637
- await this.rebuildApiReference();
1146
+ await this.applyStableOpenApiRefresh(this.openApiSpecs, true);
1638
1147
  console.log(chalk.green("✅ API reference updated"));
1639
1148
  }
1640
1149
  catch (error) {
@@ -1653,7 +1162,8 @@ export default function Page() {
1653
1162
  const configPath = path.join(this.rootDir, this.doccupineConfigFile);
1654
1163
  let config;
1655
1164
  try {
1656
- config = validateConfig(JSON.parse(await fs.readFile(configPath, "utf8")), this.rootDir);
1165
+ const { data } = await this.sourceFs.readProjectSourceFile(configPath, "Doccupine configuration source");
1166
+ config = validateConfig(JSON.parse(data.toString("utf8")), this.rootDir);
1657
1167
  }
1658
1168
  catch (error) {
1659
1169
  console.warn(chalk.yellow("⚠️ doccupine.json is missing or invalid - keeping the current configuration"), error instanceof Error ? error.message : error);
@@ -1670,48 +1180,15 @@ export default function Page() {
1670
1180
  return;
1671
1181
  }
1672
1182
  console.log(chalk.cyan("📘 OpenAPI configuration changed - updating API reference"));
1673
- let nextRegistry;
1674
1183
  try {
1675
1184
  // Validate the complete candidate before changing the active spec list or
1676
1185
  // its watcher. A half-written/invalid replacement keeps both the current
1677
1186
  // 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();
1187
+ await this.applyStableOpenApiRefresh(nextSpecs, true);
1695
1188
  console.log(chalk.green("✅ API reference updated"));
1696
1189
  }
1697
1190
  catch (error) {
1698
1191
  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
1192
  }
1716
1193
  }
1717
1194
  async updatePagesIndex() {
@@ -1719,55 +1196,15 @@ export default function Page() {
1719
1196
  let indexMDX = null;
1720
1197
  for (const file of files) {
1721
1198
  if (file === "index.mdx" || file === "./index.mdx") {
1722
- const { content } = await this.readMdxSourceFile(file);
1199
+ const cached = this.successfulMdxContent.get(file.replace(/\\/g, "/"));
1200
+ if (this.mdxSnapshotInitialized && cached === undefined)
1201
+ break;
1202
+ const content = cached ?? (await this.readMdxSourceFile(file)).content;
1723
1203
  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
- };
1204
+ indexMDX = this.homepageSource(frontmatter, mdxContent);
1740
1205
  break;
1741
1206
  }
1742
1207
  }
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
1208
  // The homepage supports the same `openapi: <METHOD> <path>` frontmatter as
1772
1209
  // any other page: look the operation up and embed its playground inline.
1773
1210
  let apiOperation;
@@ -1777,142 +1214,16 @@ export default function Page() {
1777
1214
  console.error(chalk.red(`❌ openapi frontmatter "${indexMDX.openapi}" in index.mdx not found in any spec`));
1778
1215
  }
1779
1216
  }
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
- `;
1217
+ const rendered = renderHomepage(indexMDX, apiOperation);
1820
1218
  const homePath = this.outputPath("app", "(site)", "page.tsx");
1821
1219
  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
- }
1220
+ await this.commitRenderedPage(homePath, rendered);
1844
1221
  }
1845
1222
  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
- `;
1223
+ const rendered = renderSectionPage(sectionSlug, frontmatter, mdxContent, sourcePath);
1913
1224
  const pagePath = resolveOutputPath(this.outputDir, "app", "(site)", sectionSlug, "page.tsx");
1914
1225
  await fs.ensureDir(path.dirname(pagePath));
1915
- await writeFileAtomic(pagePath, indexContent);
1226
+ return this.commitRenderedPage(pagePath, rendered);
1916
1227
  }
1917
1228
  async updateRootLayout(pages) {
1918
1229
  await writeFileAtomic(this.outputPath("app", "layout.tsx"), await this.generateRootLayout());
@@ -1921,309 +1232,18 @@ export default function Page() {
1921
1232
  await writeFileAtomic(siteLayoutPath, await this.generateSiteLayout(pages));
1922
1233
  }
1923
1234
  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;
1235
+ return loadSiteUrlArtifact(() => this.projectConfigRepository.readConfigFile());
1969
1236
  }
1970
1237
  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)"}`));
1238
+ return writeSitemap(this.outputDir, this.sectionsConfig, async () => pages ?? (await this.buildAllPagesMeta()), () => this.loadSiteUrl());
1977
1239
  }
1978
1240
  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);
1241
+ return writeRobots(this.outputDir, () => this.loadSiteUrl());
2088
1242
  }
2089
1243
  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)"}`));
1244
+ return writeLlmsFiles(this.outputDir, this.sectionsConfig, async () => pages ?? (await this.buildAllPagesMeta()), (filePath) => this.readAggregateMdxSource(filePath), (slug) => this.apiRegistry.bodyForSlug(slug), () => loadSiteMetadata(() => this.projectConfigRepository.readConfigFile()), this.publicAssetManager);
2194
1245
  }
2195
1246
  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;
1247
+ return this.watchCoordinator.stop();
2228
1248
  }
2229
1249
  }