doccupine 0.0.144 → 0.0.146

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 (51) hide show
  1. package/dist/generator/api-reference-generator.d.ts +4 -2
  2. package/dist/generator/api-reference-generator.js +32 -31
  3. package/dist/generator/app-scaffolder.d.ts +1 -2
  4. package/dist/generator/app-scaffolder.js +1 -6
  5. package/dist/generator/generated-page-publisher.d.ts +21 -0
  6. package/dist/generator/generated-page-publisher.js +124 -0
  7. package/dist/generator/generated-route-manager.d.ts +7 -3
  8. package/dist/generator/generated-route-manager.js +55 -19
  9. package/dist/generator/mdx-pass-builder.d.ts +31 -0
  10. package/dist/generator/mdx-pass-builder.js +45 -0
  11. package/dist/generator/openapi-refresh-coordinator.d.ts +42 -0
  12. package/dist/generator/openapi-refresh-coordinator.js +211 -0
  13. package/dist/generator/page-catalog.d.ts +4 -0
  14. package/dist/generator/page-catalog.js +8 -1
  15. package/dist/generator/project-config-repository.d.ts +8 -0
  16. package/dist/generator/project-config-repository.js +73 -15
  17. package/dist/generator/section-index-generator.d.ts +10 -0
  18. package/dist/generator/section-index-generator.js +68 -0
  19. package/dist/generator/secure-source-fs.d.ts +5 -1
  20. package/dist/generator/secure-source-fs.js +112 -3
  21. package/dist/generator/site-artifacts.d.ts +3 -2
  22. package/dist/generator/site-artifacts.js +6 -9
  23. package/dist/generator/watch-coordinator.d.ts +11 -2
  24. package/dist/generator/watch-coordinator.js +157 -62
  25. package/dist/lib/config-manager.d.ts +1 -0
  26. package/dist/lib/config-manager.js +194 -12
  27. package/dist/lib/generated-artifacts.d.ts +8 -2
  28. package/dist/lib/generated-artifacts.js +25 -6
  29. package/dist/lib/openapi.d.ts +4 -0
  30. package/dist/lib/openapi.js +36 -4
  31. package/dist/lib/output-safety.js +10 -3
  32. package/dist/mdx-to-nextjs-generator.d.ts +38 -23
  33. package/dist/mdx-to-nextjs-generator.js +521 -310
  34. package/dist/templates/mdx/api-playground.mdx.d.ts +1 -1
  35. package/dist/templates/mdx/api-playground.mdx.js +11 -2
  36. package/dist/templates/mdx/commands.mdx.d.ts +1 -1
  37. package/dist/templates/mdx/commands.mdx.js +26 -1
  38. package/dist/templates/mdx/media-and-assets.mdx.d.ts +1 -1
  39. package/dist/templates/mdx/media-and-assets.mdx.js +5 -0
  40. package/dist/templates/mdx/model-context-protocol.mdx.d.ts +1 -1
  41. package/dist/templates/mdx/model-context-protocol.mdx.js +2 -1
  42. package/dist/templates/mdx/platform/api-playground.mdx.d.ts +1 -1
  43. package/dist/templates/mdx/platform/api-playground.mdx.js +2 -2
  44. package/dist/templates/mdx/platform/publishing.mdx.d.ts +1 -1
  45. package/dist/templates/mdx/platform/publishing.mdx.js +3 -3
  46. package/dist/templates/mdx/what-is-doccupine.mdx.d.ts +1 -1
  47. package/dist/templates/mdx/what-is-doccupine.mdx.js +8 -3
  48. package/dist/templates/package.js +1 -1
  49. package/dist/templates/utils/orderNavItems.d.ts +1 -1
  50. package/dist/templates/utils/orderNavItems.js +1 -1
  51. package/package.json +2 -2
@@ -1,9 +1,10 @@
1
1
  import fs from "fs-extra";
2
+ import { createHash } from "node:crypto";
2
3
  import path from "path";
3
4
  import chalk from "chalk";
4
5
  import { rootLayoutTemplate, siteLayoutTemplate } from "./lib/layout.js";
5
6
  import { normalizeOpenApiConfig, validateConfig, } from "./lib/config-manager.js";
6
- import { GeneratedArtifacts } from "./lib/generated-artifacts.js";
7
+ import { GeneratedArtifacts, } from "./lib/generated-artifacts.js";
7
8
  import { claimOutputDirectory, resolveOutputPath, } from "./lib/output-safety.js";
8
9
  import { OpenApiRegistry, DEFAULT_API_BASE_SLUG } from "./lib/openapi.js";
9
10
  import { getFullSlug, safeMatter, writeFileAtomic } from "./lib/utils.js";
@@ -12,13 +13,17 @@ import { proxyTemplate } from "./templates/proxy.js";
12
13
  import { SecureSourceFs } from "./generator/secure-source-fs.js";
13
14
  import { AppScaffolder } from "./generator/app-scaffolder.js";
14
15
  import { ApiReferenceGenerator } from "./generator/api-reference-generator.js";
16
+ import { GeneratedPagePublisher } from "./generator/generated-page-publisher.js";
15
17
  import { GeneratedRouteManager } from "./generator/generated-route-manager.js";
18
+ import { MdxPassBuilder, } from "./generator/mdx-pass-builder.js";
16
19
  import { ProjectConfigRepository } from "./generator/project-config-repository.js";
17
20
  import { PublicAssetManager } from "./generator/public-asset-manager.js";
18
21
  import { WatchCoordinator } from "./generator/watch-coordinator.js";
22
+ import { SectionIndexGenerator } from "./generator/section-index-generator.js";
23
+ import { OpenApiRefreshCoordinator, } from "./generator/openapi-refresh-coordinator.js";
19
24
  import { addApiReferenceSection, determineSectionRoute, discoverSections, } from "./generator/section-resolver.js";
20
- import { renderHomepage, renderMdxPage, renderSectionPage, } from "./generator/page-renderer.js";
21
- import { buildRealPagesMeta as buildRealPageCatalog, mergePages as mergePageCatalog, parseMdxPageMeta, } from "./generator/page-catalog.js";
25
+ import { renderHomepage, } from "./generator/page-renderer.js";
26
+ import { mergePages as mergePageCatalog, RouteCollisionError, } from "./generator/page-catalog.js";
22
27
  import { loadSiteMetadata, loadSiteUrl as loadSiteUrlArtifact, writeLlmsFiles, writeRobots, writeSitemap, } from "./generator/site-artifacts.js";
23
28
  export class MDXToNextJSGenerator {
24
29
  watchDir;
@@ -46,10 +51,20 @@ export class MDXToNextJSGenerator {
46
51
  sourceFs;
47
52
  appScaffolder;
48
53
  apiReferenceGenerator;
54
+ generatedPagePublisher;
49
55
  generatedRouteManager;
56
+ mdxPassBuilder;
57
+ openApiRefreshCoordinator;
58
+ sectionIndexGenerator;
50
59
  projectConfigRepository;
51
60
  publicAssetManager;
52
61
  watchCoordinator;
62
+ retainExistingMdxOutput = true;
63
+ mdxSnapshotInitialized = false;
64
+ successfulMdxPages = new Map();
65
+ successfulMdxContent = new Map();
66
+ successfulMdxSourcesBySlug = new Map();
67
+ collisionBlockedMdxSources = new Set();
53
68
  constructor(watchDir, outputDir, openApiSpecs = [], rootDir = process.cwd()) {
54
69
  this.watchDir = path.resolve(watchDir);
55
70
  this.outputDir = path.resolve(outputDir);
@@ -60,6 +75,17 @@ export class MDXToNextJSGenerator {
60
75
  this.appScaffolder = new AppScaffolder(this.outputDir);
61
76
  this.apiReferenceGenerator = new ApiReferenceGenerator(this.outputDir, this.artifacts);
62
77
  this.generatedRouteManager = new GeneratedRouteManager(this.outputDir, this.artifacts);
78
+ this.generatedPagePublisher = new GeneratedPagePublisher(this.outputDir, this.generatedRouteManager);
79
+ this.sectionIndexGenerator = new SectionIndexGenerator(this.outputDir, this.generatedRouteManager);
80
+ this.mdxPassBuilder = new MdxPassBuilder({
81
+ sourceFs: this.sourceFs,
82
+ getAllMdxFiles: () => this.getAllMDXFiles(),
83
+ getSections: () => this.sectionsConfig,
84
+ loadSectionsConfig: () => this.loadSectionsConfig(),
85
+ withApiReferenceSection: (sections) => this.withApiReferenceSection(sections),
86
+ determineSectionForFile: (filePath, frontmatter, sections) => this.determineSectionForFile(filePath, frontmatter, sections),
87
+ resolveHttpMethod: (reference) => this.apiRegistry.lookup(reference)?.method,
88
+ });
63
89
  this.projectConfigRepository = new ProjectConfigRepository(this.rootDir, this.outputDir, this.sourceFs, this.configFiles, this.fontConfigFile, this.analyticsConfigFile);
64
90
  this.publicAssetManager = new PublicAssetManager(this.rootDir, this.outputDir, this.artifacts, this.sourceFs);
65
91
  this.watchCoordinator = new WatchCoordinator({
@@ -71,6 +97,7 @@ export class MDXToNextJSGenerator {
71
97
  doccupineConfigFile: this.doccupineConfigFile,
72
98
  sourceFs: this.sourceFs,
73
99
  getOpenApiSpecs: () => this.openApiSpecs,
100
+ getOpenApiSourceFiles: () => this.apiRegistry.sourceFiles,
74
101
  callbacks: {
75
102
  syncOpenApiSpecWatcher: () => this.syncOpenApiSpecWatcher(),
76
103
  handleFileChange: (action, filePath) => this.handleFileChange(action, filePath),
@@ -86,8 +113,35 @@ export class MDXToNextJSGenerator {
86
113
  copyPublicFiles: () => this.copyPublicFiles(),
87
114
  handlePublicFileChange: (filePath) => this.handlePublicFileChange(filePath),
88
115
  handlePublicFileDelete: (filePath) => this.handlePublicFileDelete(filePath),
89
- processAllMDXFiles: () => this.processAllMDXFiles(),
116
+ processAllMDXFiles: () => this.reconcileMdxSources(),
117
+ },
118
+ });
119
+ this.openApiRefreshCoordinator = new OpenApiRefreshCoordinator({
120
+ rootDir: this.rootDir,
121
+ watchDir: this.watchDir,
122
+ outputDir: this.outputDir,
123
+ configFile: this.doccupineConfigFile,
124
+ apiBaseSlug: this.apiBaseSlug,
125
+ sourceFs: this.sourceFs,
126
+ getRegistry: () => this.apiRegistry,
127
+ setRegistry: (registry) => {
128
+ this.apiRegistry = registry;
129
+ },
130
+ getSpecs: () => this.openApiSpecs,
131
+ setSpecs: (specs) => {
132
+ this.openApiSpecs = specs;
133
+ },
134
+ getSections: () => this.sectionsConfig,
135
+ setSections: (sections) => {
136
+ this.sectionsConfig = sections;
90
137
  },
138
+ getOpenApiRoutes: () => this.artifacts.routesFor("openapi"),
139
+ getSuccessfulMdxPages: () => [...this.successfulMdxPages.values()],
140
+ resolveSections: () => this.resolveSections(),
141
+ writeApiPages: (realPages, options) => this.writeApiPages(realPages, options),
142
+ refreshSiteAggregates: () => this.refreshSiteAggregates(),
143
+ syncWatcher: () => this.syncOpenApiSpecWatcher(),
144
+ removeOwnedRoute: (slug) => this.removeOwnedRoute(slug),
91
145
  });
92
146
  }
93
147
  outputPath(...segments) {
@@ -96,47 +150,58 @@ export class MDXToNextJSGenerator {
96
150
  async readMdxSourceFile(filePath) {
97
151
  return this.sourceFs.readMdxSourceFile(filePath);
98
152
  }
99
- async ensureSafeStarterPath(relativePath) {
100
- return this.sourceFs.ensureSafeStarterPath(relativePath);
153
+ async writeStarterFilesIfEmpty(files) {
154
+ return this.sourceFs.writeStarterFilesIfEmpty(files);
155
+ }
156
+ async refreshInitialDoccupineConfig() {
157
+ const configPath = path.join(this.rootDir, this.doccupineConfigFile);
158
+ if (!(await fs.pathExists(configPath)))
159
+ return undefined;
160
+ const { data, stat } = await this.sourceFs.readProjectSourceFile(configPath, "Doccupine configuration source");
161
+ const config = validateConfig(JSON.parse(data.toString("utf8")), this.rootDir);
162
+ this.openApiSpecs = normalizeOpenApiConfig(config.openapi);
163
+ const hash = createHash("sha256").update(data).digest("hex");
164
+ return `file:${stat.size}:${stat.mtimeMs}:${stat.dev}:${stat.ino}:${hash}`;
101
165
  }
102
166
  async init() {
103
167
  console.log(chalk.blue("🚀 Initializing MDX to Next.js generator..."));
104
- await fs.ensureDir(this.watchDir);
105
- await claimOutputDirectory(this.outputDir);
106
- await this.artifacts.load();
107
- this.sectionsConfig = await this.resolveSections();
108
- this.analyticsConfig = await this.loadAnalyticsConfig();
109
- if (this.analyticsConfig) {
110
- console.log(chalk.blue(`📊 Analytics enabled: ${this.analyticsConfig.provider}`));
111
- }
112
- // Parse OpenAPI spec(s) before generating structure so the synthetic
113
- // endpoint pages flow into the very first layout/sitemap/llms pass.
114
- await this.loadOpenApiRegistry();
115
- await this.createNextJSStructure();
116
- await this.createStartingDocs();
117
- await this.copyCustomConfigFiles();
118
- await this.copyFontConfig();
119
- await this.copyAnalyticsConfig();
120
- await this.copyPublicFiles();
121
- // createStartingDocs() may have written the sample docs - which carry
122
- // section frontmatter - after the initial resolveSections() ran against an
123
- // empty watch dir. Re-resolve now that every MDX file is on disk so the
124
- // build applies the correct sections in a single O(n) pass, instead of
125
- // rediscovering them per file (the old O(n²) behavior).
126
- this.sectionsConfig = await this.resolveSections();
127
- if (this.sectionsConfig) {
128
- console.log(chalk.blue(`📑 Found ${this.sectionsConfig.length} section(s): ${this.sectionsConfig.map((s) => s.label).join(", ")}`));
168
+ await this.projectConfigRepository.preflightSourceFiles();
169
+ try {
170
+ await fs.ensureDir(this.watchDir);
171
+ await claimOutputDirectory(this.outputDir);
172
+ await this.artifacts.load();
173
+ // Starter documents are part of the initial source tree. Capture the
174
+ // watcher baseline after creating them, but before reading any source
175
+ // that contributes to generated output.
176
+ await this.createStartingDocs();
177
+ const doccupineSourceState = await this.refreshInitialDoccupineConfig();
178
+ await this.loadOpenApiRegistry();
179
+ await this.watchCoordinator.establishSourceSnapshot(this.projectConfigRepository.sourceSnapshotStates(), this.apiRegistry.sourceFingerprint, doccupineSourceState);
180
+ // Resolve sections after loading OpenAPI so the generated reference is
181
+ // present in the first layout, sitemap, and LLMS pass.
182
+ this.sectionsConfig = await this.resolveSections();
183
+ this.analyticsConfig = await this.loadAnalyticsConfig();
184
+ if (this.analyticsConfig) {
185
+ console.log(chalk.blue(`📊 Analytics enabled: ${this.analyticsConfig.provider}`));
186
+ }
187
+ this.retainExistingMdxOutput = false;
188
+ await this.createNextJSStructure();
189
+ await this.copyCustomConfigFiles();
190
+ await this.copyFontConfig();
191
+ await this.copyAnalyticsConfig();
192
+ await this.copyPublicFiles();
193
+ if (this.sectionsConfig) {
194
+ console.log(chalk.blue(`📑 Found ${this.sectionsConfig.length} section(s): ${this.sectionsConfig.map((s) => s.label).join(", ")}`));
195
+ }
196
+ await this.processAllMDXFiles();
197
+ console.log(chalk.green("✅ Initial setup complete!"));
198
+ console.log(chalk.cyan("💡 To start the Next.js dev server:"));
199
+ console.log(chalk.white(` cd ${path.relative(process.cwd(), this.outputDir)}`));
200
+ console.log(chalk.white(" install dependencies, then run the dev script"));
201
+ }
202
+ finally {
203
+ this.projectConfigRepository.clearSourceSnapshot();
129
204
  }
130
- // Write the endpoint pages + request allowlist before the MDX pass so its
131
- // aggregate refresh (nav/sitemap/llms) already sees them on disk and in the
132
- // registry.
133
- await this.writeApiPages();
134
- await this.processAllMDXFiles();
135
- await this.watchCoordinator.establishSourceSnapshot();
136
- console.log(chalk.green("✅ Initial setup complete!"));
137
- console.log(chalk.cyan("💡 To start the Next.js dev server:"));
138
- console.log(chalk.white(` cd ${path.relative(process.cwd(), this.outputDir)}`));
139
- console.log(chalk.white(" install dependencies, then run the dev script"));
140
205
  }
141
206
  async createNextJSStructure() {
142
207
  return this.appScaffolder.createNextJsStructure(this.analyticsConfig, {
@@ -148,8 +213,7 @@ export class MDXToNextJSGenerator {
148
213
  }
149
214
  async createStartingDocs() {
150
215
  return this.appScaffolder.createStartingDocs({
151
- getAllMdxFiles: () => this.getAllMDXFiles(),
152
- ensureSafeStarterPath: (filePath) => this.ensureSafeStarterPath(filePath),
216
+ writeStarterFilesIfEmpty: (files) => this.writeStarterFilesIfEmpty(files),
153
217
  });
154
218
  }
155
219
  async copyCustomConfigFiles() {
@@ -224,8 +288,11 @@ export class MDXToNextJSGenerator {
224
288
  }
225
289
  }
226
290
  }
227
- determineSectionForFile(filePath, frontmatter) {
228
- return determineSectionRoute(filePath, frontmatter, this.sectionsConfig);
291
+ async reconcileMdxSources() {
292
+ await this.processAllMDXFiles();
293
+ }
294
+ determineSectionForFile(filePath, frontmatter, sections = this.sectionsConfig) {
295
+ return determineSectionRoute(filePath, frontmatter, sections);
229
296
  }
230
297
  async handleConfigFileChange(filePath) {
231
298
  const fileName = path.basename(filePath);
@@ -339,22 +406,199 @@ export class MDXToNextJSGenerator {
339
406
  async startWatching() {
340
407
  return this.watchCoordinator.startWatching();
341
408
  }
342
- async parseMDXFile(file) {
343
- return parseMdxPageMeta(file, (filePath) => this.readMdxSourceFile(filePath), (filePath, frontmatter) => this.determineSectionForFile(filePath, frontmatter), (reference) => this.apiRegistry.lookup(reference)?.method);
409
+ async captureMdxPass(files, seededSources = new Map(), refreshSections = false) {
410
+ return this.mdxPassBuilder.capture(files, seededSources, refreshSections);
344
411
  }
345
412
  async buildRealPagesMeta() {
346
- const files = await this.getAllMDXFiles();
347
- return buildRealPageCatalog(files, (file) => this.parseMDXFile(file));
413
+ return (await this.captureMdxPass()).pages;
348
414
  }
349
415
  async buildAllPagesMeta() {
350
416
  const real = await this.buildRealPagesMeta();
351
- return mergePageCatalog(real, this.apiRegistry.isEmpty ? [] : this.apiRegistry.syntheticPages());
417
+ const successful = this.mdxSnapshotInitialized
418
+ ? this.successfulPagesInSourceOrder(real)
419
+ : real;
420
+ return this.mergeAllPagesMeta(successful, new Set([...real, ...successful].map((page) => page.slug)));
421
+ }
422
+ mergeAllPagesMeta(real, declaredRealSlugs = new Set(real.map((page) => page.slug))) {
423
+ return mergePageCatalog(real, this.apiRegistry.isEmpty
424
+ ? []
425
+ : this.apiRegistry
426
+ .syntheticPages()
427
+ .filter((page) => !declaredRealSlugs.has(page.slug)));
428
+ }
429
+ successfulPagesInSourceOrder(realPages) {
430
+ const currentSources = new Set(realPages.map((page) => page.path.replace(/\\/g, "/")));
431
+ const ordered = realPages.flatMap((page) => {
432
+ const successful = this.successfulMdxPages.get(page.path.replace(/\\/g, "/"));
433
+ return successful ? [successful] : [];
434
+ });
435
+ for (const [source, page] of this.successfulMdxPages) {
436
+ if (!currentSources.has(source))
437
+ ordered.push(page);
438
+ }
439
+ return ordered;
440
+ }
441
+ recordSuccessfulMdxPage(page, sourceContent) {
442
+ const source = page.path.replace(/\\/g, "/");
443
+ const previous = this.successfulMdxPages.get(source);
444
+ if (previous &&
445
+ previous.slug !== page.slug &&
446
+ this.successfulMdxSourcesBySlug.get(previous.slug) === source) {
447
+ this.successfulMdxSourcesBySlug.delete(previous.slug);
448
+ }
449
+ const otherSource = this.successfulMdxSourcesBySlug.get(page.slug);
450
+ if (otherSource && otherSource !== source) {
451
+ this.removeSuccessfulMdxPage(otherSource);
452
+ }
453
+ this.successfulMdxPages.set(source, page);
454
+ this.successfulMdxContent.set(source, sourceContent);
455
+ this.successfulMdxSourcesBySlug.set(page.slug, source);
456
+ this.collisionBlockedMdxSources.delete(source);
457
+ }
458
+ removeSuccessfulMdxPage(source) {
459
+ const successful = this.successfulMdxPages.get(source);
460
+ if (successful &&
461
+ this.successfulMdxSourcesBySlug.get(successful.slug) === source) {
462
+ this.successfulMdxSourcesBySlug.delete(successful.slug);
463
+ }
464
+ this.successfulMdxPages.delete(source);
465
+ this.successfulMdxContent.delete(source);
466
+ }
467
+ captureSuccessfulMdxState() {
468
+ return {
469
+ pages: new Map(this.successfulMdxPages),
470
+ content: new Map(this.successfulMdxContent),
471
+ sourcesBySlug: new Map(this.successfulMdxSourcesBySlug),
472
+ collisionBlockedSources: new Set(this.collisionBlockedMdxSources),
473
+ sections: this.sectionsConfig?.map((section) => ({ ...section })) ?? null,
474
+ routes: this.artifacts.routesFor("mdx"),
475
+ snapshotInitialized: this.mdxSnapshotInitialized,
476
+ };
477
+ }
478
+ restoreSuccessfulMdxState(state) {
479
+ this.successfulMdxPages = state.pages;
480
+ this.successfulMdxContent = state.content;
481
+ this.successfulMdxSourcesBySlug = state.sourcesBySlug;
482
+ this.collisionBlockedMdxSources = state.collisionBlockedSources;
483
+ this.sectionsConfig = state.sections;
484
+ this.mdxSnapshotInitialized = state.snapshotInitialized;
485
+ }
486
+ async rollbackPageCommits(commits) {
487
+ const errors = [];
488
+ for (const commit of [...commits].reverse()) {
489
+ try {
490
+ await commit.rollback();
491
+ }
492
+ catch (error) {
493
+ errors.push(error);
494
+ }
495
+ }
496
+ return errors;
497
+ }
498
+ async rollbackFailedMdxCommit(error, state, commits) {
499
+ this.restoreSuccessfulMdxState(state);
500
+ const rollbackErrors = await this.rollbackPageCommits(commits);
501
+ if (rollbackErrors.length > 0) {
502
+ throw new AggregateError([error, ...rollbackErrors], "Unable to commit or restore generated MDX pages");
503
+ }
504
+ throw error;
505
+ }
506
+ async rollbackCommittedMdxChange(error, state, commits) {
507
+ this.restoreSuccessfulMdxState(state);
508
+ const rollbackErrors = await this.rollbackPageCommits(commits);
509
+ const previousPages = [...state.pages.values()];
510
+ for (const page of previousPages) {
511
+ if (page.slug === "")
512
+ continue;
513
+ const content = state.content.get(page.path.replace(/\\/g, "/"));
514
+ if (content === undefined)
515
+ continue;
516
+ try {
517
+ await this.writePageForFile(page.path, content);
518
+ }
519
+ catch (rollbackError) {
520
+ rollbackErrors.push(rollbackError);
521
+ }
522
+ }
523
+ try {
524
+ await this.artifacts.replaceRoutesAndSave("mdx", state.routes.map(({ source, slug }) => ({ source, slug })));
525
+ }
526
+ catch (rollbackError) {
527
+ rollbackErrors.push(rollbackError);
528
+ }
529
+ try {
530
+ await this.refreshMdxDerivedOutput(previousPages, previousPages);
531
+ }
532
+ catch (rollbackError) {
533
+ rollbackErrors.push(rollbackError);
534
+ }
535
+ if (rollbackErrors.length > 0) {
536
+ throw new AggregateError([error, ...rollbackErrors], "Unable to refresh or restore generated MDX output");
537
+ }
538
+ throw error;
539
+ }
540
+ dropMissingMdxSnapshots(realPages) {
541
+ const currentSources = new Set(realPages.map((page) => page.path.replace(/\\/g, "/")));
542
+ for (const source of this.successfulMdxPages.keys()) {
543
+ if (currentSources.has(source))
544
+ continue;
545
+ this.removeSuccessfulMdxPage(source);
546
+ this.collisionBlockedMdxSources.delete(source);
547
+ }
548
+ }
549
+ async commitMdxSnapshot(realPages) {
550
+ this.dropMissingMdxSnapshots(realPages);
551
+ const successfulPages = this.successfulPagesInSourceOrder(realPages);
552
+ const previousRoutes = this.artifacts.routesFor("mdx");
553
+ await this.generatedRouteManager.replaceMdxRoutes(successfulPages);
554
+ try {
555
+ await this.removeStaleMdxRoutes(successfulPages, previousRoutes);
556
+ }
557
+ catch (error) {
558
+ console.error(chalk.red("❌ Error removing stale MDX routes; cleanup will retry:"), error);
559
+ }
560
+ this.mdxSnapshotInitialized = true;
561
+ return successfulPages;
562
+ }
563
+ async refreshMdxDerivedOutput(realPages, successfulPages) {
564
+ if (!this.apiRegistry.isEmpty ||
565
+ this.artifacts.routesFor("openapi").length > 0) {
566
+ await this.writeApiPages(realPages);
567
+ }
568
+ const declaredSlugs = new Set(realPages.map((page) => page.slug));
569
+ const pages = this.mergeAllPagesMeta(successfulPages, declaredSlugs);
570
+ await this.refreshSiteAggregates(pages, declaredSlugs);
571
+ }
572
+ async readAggregateMdxSource(filePath) {
573
+ const cached = this.successfulMdxContent.get(filePath.replace(/\\/g, "/"));
574
+ if (this.mdxSnapshotInitialized && cached !== undefined) {
575
+ return { content: cached };
576
+ }
577
+ return this.readMdxSourceFile(filePath);
578
+ }
579
+ homepageSource(frontmatter, mdxContent) {
580
+ return {
581
+ content: mdxContent,
582
+ title: frontmatter.title || "Welcome",
583
+ description: frontmatter.description || "",
584
+ icon: frontmatter.icon,
585
+ image: frontmatter.image,
586
+ name: frontmatter.name,
587
+ date: typeof frontmatter.date === "string" ? frontmatter.date : undefined,
588
+ updated: typeof frontmatter.updated === "string"
589
+ ? frontmatter.updated
590
+ : undefined,
591
+ openapi: typeof frontmatter.openapi === "string"
592
+ ? frontmatter.openapi
593
+ : undefined,
594
+ rss: frontmatter.rss === true,
595
+ };
352
596
  }
353
597
  async removeOwnedRoute(slug) {
354
598
  return this.generatedRouteManager.removeOwnedRoute(slug);
355
599
  }
356
- async removeStaleMdxRoutes(realPages) {
357
- return this.generatedRouteManager.removeStaleMdxRoutes(realPages, (slug) => this.removeOwnedRoute(slug));
600
+ async removeStaleMdxRoutes(realPages, previousRoutes = this.artifacts.routesFor("mdx")) {
601
+ return this.generatedRouteManager.removeStaleMdxRoutes(realPages, (slug) => this.removeOwnedRoute(slug), previousRoutes);
358
602
  }
359
603
  /**
360
604
  * Writes the generated page(s) for a single MDX file: the doc page and, for a
@@ -363,39 +607,72 @@ export class MDXToNextJSGenerator {
363
607
  * redirects) - the caller batches those so a bulk build runs them once at the
364
608
  * end instead of once per file (which is what made large builds O(n²)).
365
609
  */
366
- async writePageForFile(filePath) {
367
- const { content } = await this.readMdxSourceFile(filePath);
610
+ async writePageForFile(filePath, content) {
611
+ const commits = [];
368
612
  const { data: frontmatter, content: mdxContent } = safeMatter(content, filePath);
369
613
  const { sectionSlug, pageSlug } = this.determineSectionForFile(filePath, frontmatter);
370
614
  const fullSlug = getFullSlug(pageSlug, sectionSlug);
371
615
  const isIndex = filePath === "index.mdx" || filePath === "./index.mdx";
372
616
  const isSectionIndex = this.sectionsConfig && pageSlug === "" && sectionSlug !== "";
373
- if (isIndex) {
374
- // The homepage is emitted by updatePagesIndex() in the aggregate pass, so
375
- // there is no per-file page to write here.
376
- console.log(chalk.blue("🏠 Updating homepage with index.mdx content"));
377
- }
378
- else {
379
- const mdxFile = {
380
- path: filePath,
381
- content: mdxContent,
382
- frontmatter,
383
- slug: fullSlug,
384
- };
385
- // `openapi: <METHOD> <path>` (or an operationId) in frontmatter renders
386
- // that operation's playground inline with the author's prose. An unknown
387
- // reference is logged and the page still renders its prose (graceful).
388
- let apiOperation;
389
- if (frontmatter.openapi) {
390
- apiOperation = this.apiRegistry.lookup(String(frontmatter.openapi));
391
- if (!apiOperation) {
392
- console.error(chalk.red(`❌ openapi frontmatter "${frontmatter.openapi}" in ${filePath} not found in any spec`));
617
+ try {
618
+ if (isIndex) {
619
+ // The homepage is emitted by updatePagesIndex() in the aggregate pass, so
620
+ // validate it here before its source enters the successful snapshot.
621
+ console.log(chalk.blue("🏠 Updating homepage with index.mdx content"));
622
+ renderHomepage(this.homepageSource(frontmatter, mdxContent), typeof frontmatter.openapi === "string"
623
+ ? this.apiRegistry.lookup(frontmatter.openapi)
624
+ : undefined);
625
+ }
626
+ else {
627
+ const mdxFile = {
628
+ path: filePath,
629
+ content: mdxContent,
630
+ frontmatter,
631
+ slug: fullSlug,
632
+ };
633
+ // `openapi: <METHOD> <path>` (or an operationId) in frontmatter renders
634
+ // that operation's playground inline with the author's prose. An unknown
635
+ // reference is logged and the page still renders its prose (graceful).
636
+ let apiOperation;
637
+ if (frontmatter.openapi) {
638
+ apiOperation = this.apiRegistry.lookup(String(frontmatter.openapi));
639
+ if (!apiOperation) {
640
+ console.error(chalk.red(`❌ openapi frontmatter "${frontmatter.openapi}" in ${filePath} not found in any spec`));
641
+ }
393
642
  }
643
+ commits.push(await this.generatePageFromMDX(mdxFile, apiOperation ? { apiOperation } : undefined));
394
644
  }
395
- await this.generatePageFromMDX(mdxFile, apiOperation ? { apiOperation } : undefined);
645
+ if (isSectionIndex) {
646
+ commits.push(await this.updateSectionIndex(sectionSlug, frontmatter, mdxContent, filePath));
647
+ }
648
+ return commits;
396
649
  }
397
- if (isSectionIndex) {
398
- await this.updateSectionIndex(sectionSlug, frontmatter, mdxContent, filePath);
650
+ catch (error) {
651
+ const rollbackErrors = await this.rollbackPageCommits(commits);
652
+ if (rollbackErrors.length > 0) {
653
+ throw new AggregateError([error, ...rollbackErrors], `Unable to generate or restore ${filePath}`);
654
+ }
655
+ throw error;
656
+ }
657
+ }
658
+ async retryMdxPages(snapshot, shouldRetry, commits) {
659
+ for (const page of snapshot.pages) {
660
+ const source = page.path.replace(/\\/g, "/");
661
+ if (!shouldRetry(source, page))
662
+ continue;
663
+ const currentOwner = this.successfulMdxSourcesBySlug.get(page.slug);
664
+ if (currentOwner && currentOwner !== source)
665
+ continue;
666
+ const captured = snapshot.sources.get(source);
667
+ if (!captured)
668
+ continue;
669
+ try {
670
+ commits.push(...(await this.writePageForFile(page.path, captured.content)));
671
+ this.recordSuccessfulMdxPage(page, captured.content);
672
+ }
673
+ catch (error) {
674
+ console.error(chalk.red(`❌ Error processing ${page.path}:`), error);
675
+ }
399
676
  }
400
677
  }
401
678
  /**
@@ -404,55 +681,105 @@ export class MDXToNextJSGenerator {
404
681
  * exactly once and threads the result through each generator, so one refresh
405
682
  * is a single scan rather than one scan per generator.
406
683
  */
407
- async refreshSiteAggregates(resolvedPages) {
684
+ async refreshSiteAggregates(resolvedPages, declaredSlugs) {
408
685
  const pages = resolvedPages ?? (await this.buildAllPagesMeta());
409
- await this.updatePagesIndex();
686
+ await this.updatePagesIndex(pages);
410
687
  await this.updateRootLayout(pages);
411
688
  await this.updateSitemap(pages);
412
689
  await this.updateLlmsFiles(pages);
413
- await this.generateSectionIndexPages(pages);
690
+ await this.generateSectionIndexPages(pages, declaredSlugs);
414
691
  }
415
692
  async handleFileChange(action, filePath) {
416
693
  console.log(chalk.cyan(`📝 File ${action}: ${filePath}`));
417
- await this.readMdxSourceFile(filePath);
694
+ const normalizedSource = filePath.replace(/\\/g, "/");
695
+ const changedSource = await this.readMdxSourceFile(filePath);
696
+ const previousState = this.captureSuccessfulMdxState();
697
+ const pageCommits = [];
698
+ let pageRendered = false;
418
699
  try {
419
700
  // Validate the complete route set before writing this page so a collision
420
701
  // cannot transiently overwrite another route during watch mode.
421
- const normalizedSource = filePath.replace(/\\/g, "/");
422
- const previousSlug = this.generatedRouteManager.routeForMdxSource(normalizedSource);
423
- const realPages = await this.buildRealPagesMeta();
702
+ const snapshot = await this.captureMdxPass(undefined, new Map([[normalizedSource, changedSource]]), true);
703
+ const realPages = snapshot.pages;
424
704
  const currentPage = realPages.find((page) => page.path.replace(/\\/g, "/") === normalizedSource);
425
- if (previousSlug && previousSlug !== currentPage?.slug)
426
- await this.removeStaleMdxRoutes(realPages);
427
- await this.writePageForFile(filePath);
428
- await this.generatedRouteManager.replaceMdxRoutes(realPages);
429
- if (!this.apiRegistry.isEmpty)
430
- await this.writeApiPages();
431
- const pages = await this.buildAllPagesMeta();
432
- await this.refreshSiteAggregates(pages);
705
+ if (!currentPage)
706
+ throw new Error(`Unable to resolve ${filePath}`);
707
+ this.sectionsConfig = snapshot.sections;
708
+ try {
709
+ pageCommits.push(...(await this.writePageForFile(filePath, changedSource.content)));
710
+ this.recordSuccessfulMdxPage(currentPage, changedSource.content);
711
+ pageRendered = true;
712
+ }
713
+ catch (error) {
714
+ if (this.retainExistingMdxOutput) {
715
+ this.restoreSuccessfulMdxState(previousState);
716
+ }
717
+ else {
718
+ this.removeSuccessfulMdxPage(normalizedSource);
719
+ }
720
+ const successfulPages = await this.commitMdxSnapshot(realPages);
721
+ await this.refreshMdxDerivedOutput(realPages, successfulPages);
722
+ throw error;
723
+ }
724
+ await this.retryMdxPages(snapshot, (source) => source !== normalizedSource &&
725
+ this.collisionBlockedMdxSources.has(source), pageCommits);
726
+ let successfulPages = [];
727
+ try {
728
+ successfulPages = await this.commitMdxSnapshot(realPages);
729
+ }
730
+ catch (error) {
731
+ await this.rollbackFailedMdxCommit(error, previousState, pageCommits);
732
+ }
733
+ try {
734
+ await this.refreshMdxDerivedOutput(realPages, successfulPages);
735
+ }
736
+ catch (error) {
737
+ await this.rollbackCommittedMdxChange(error, previousState, pageCommits);
738
+ }
433
739
  console.log(chalk.green(`✅ Generated page for: ${filePath}`));
434
740
  await this.maybeUpdateSections();
435
741
  }
436
742
  catch (error) {
743
+ if (!pageRendered && error instanceof RouteCollisionError) {
744
+ this.collisionBlockedMdxSources.add(normalizedSource);
745
+ for (const source of error.sources) {
746
+ this.collisionBlockedMdxSources.add(source.replace(/\\/g, "/"));
747
+ }
748
+ }
437
749
  console.error(chalk.red(`❌ Error processing ${filePath}:`), error);
438
750
  }
439
751
  }
440
752
  async handleFileDelete(filePath) {
441
753
  console.log(chalk.red(`🗑️ File deleted: ${filePath}`));
754
+ const previousState = this.captureSuccessfulMdxState();
755
+ const pageCommits = [];
442
756
  try {
757
+ const normalizedSource = filePath.replace(/\\/g, "/");
443
758
  if (filePath === "index.mdx" || filePath === "./index.mdx") {
444
759
  console.log(chalk.blue("🏠 Updating homepage - index.mdx deleted"));
445
760
  }
446
- else {
447
- const normalizedSource = filePath.replace(/\\/g, "/");
448
- const ownedSlug = this.generatedRouteManager.routeForMdxSource(normalizedSource);
449
- if (ownedSlug)
450
- await this.removeOwnedRoute(ownedSlug);
451
- await this.generatedRouteManager.removeMdxRoute(normalizedSource);
452
- }
453
- if (!this.apiRegistry.isEmpty)
454
- await this.writeApiPages();
455
- await this.refreshSiteAggregates();
761
+ const snapshot = await this.captureMdxPass(undefined, undefined, true);
762
+ this.removeSuccessfulMdxPage(normalizedSource);
763
+ this.collisionBlockedMdxSources.delete(normalizedSource);
764
+ this.sectionsConfig = snapshot.sections;
765
+ const realPages = snapshot.pages;
766
+ await this.retryMdxPages(snapshot, (source, page) => {
767
+ return (this.collisionBlockedMdxSources.has(source) ||
768
+ this.successfulMdxPages.get(source)?.slug !== page.slug);
769
+ }, pageCommits);
770
+ let successfulPages = [];
771
+ try {
772
+ successfulPages = await this.commitMdxSnapshot(realPages);
773
+ }
774
+ catch (error) {
775
+ await this.rollbackFailedMdxCommit(error, previousState, pageCommits);
776
+ }
777
+ try {
778
+ await this.refreshMdxDerivedOutput(realPages, successfulPages);
779
+ }
780
+ catch (error) {
781
+ await this.rollbackCommittedMdxChange(error, previousState, pageCommits);
782
+ }
456
783
  console.log(chalk.green(`✅ Removed page for: ${filePath}`));
457
784
  await this.maybeUpdateSections();
458
785
  }
@@ -461,27 +788,67 @@ export class MDXToNextJSGenerator {
461
788
  }
462
789
  }
463
790
  async processAllMDXFiles() {
791
+ const previousState = this.captureSuccessfulMdxState();
792
+ const pageCommits = [];
464
793
  const files = await this.getAllMDXFiles();
465
794
  // Fail before writing any page when two source files resolve to one route.
466
- const realPages = await this.buildRealPagesMeta();
467
- await this.removeStaleMdxRoutes(realPages);
795
+ let snapshot;
796
+ try {
797
+ snapshot = await this.captureMdxPass(files, undefined, true);
798
+ }
799
+ catch (error) {
800
+ if (error instanceof RouteCollisionError) {
801
+ // The catalog rejects the entire pass, so any source may have an
802
+ // unapplied content change even when it is not one of the colliders.
803
+ for (const source of files) {
804
+ this.collisionBlockedMdxSources.add(source.replace(/\\/g, "/"));
805
+ }
806
+ }
807
+ throw error;
808
+ }
809
+ this.sectionsConfig = snapshot.sections;
810
+ const realPages = snapshot.pages;
468
811
  // Write each page first (the only genuinely per-file work), then run the
469
812
  // site-wide aggregations a single time. Doing the aggregations per file
470
813
  // re-scanned and re-parsed every MDX file on each iteration, which made a
471
814
  // full build O(n²); batching them makes it O(n). A single bad file is
472
815
  // logged and skipped so it never aborts the whole build.
816
+ const pagesBySource = new Map(realPages.map((page) => [page.path.replace(/\\/g, "/"), page]));
473
817
  for (const file of files) {
474
818
  console.log(chalk.cyan(`📝 Processing: ${file}`));
819
+ const normalizedSource = file.replace(/\\/g, "/");
475
820
  try {
476
- await this.writePageForFile(file);
821
+ const sourceContent = snapshot.sources.get(normalizedSource)?.content;
822
+ if (sourceContent === undefined) {
823
+ throw new Error(`Unable to snapshot ${file}`);
824
+ }
825
+ pageCommits.push(...(await this.writePageForFile(file, sourceContent)));
826
+ const page = pagesBySource.get(normalizedSource);
827
+ if (!page)
828
+ throw new Error(`Unable to resolve ${file}`);
829
+ this.recordSuccessfulMdxPage(page, sourceContent);
477
830
  }
478
831
  catch (error) {
832
+ if (!this.retainExistingMdxOutput) {
833
+ this.removeSuccessfulMdxPage(normalizedSource);
834
+ }
479
835
  console.error(chalk.red(`❌ Error processing ${file}:`), error);
480
836
  }
481
837
  }
482
- await this.generatedRouteManager.replaceMdxRoutes(realPages);
483
- const pages = await this.buildAllPagesMeta();
484
- await this.refreshSiteAggregates(pages);
838
+ let successfulPages = [];
839
+ try {
840
+ successfulPages = await this.commitMdxSnapshot(realPages);
841
+ }
842
+ catch (error) {
843
+ await this.rollbackFailedMdxCommit(error, previousState, pageCommits);
844
+ }
845
+ this.retainExistingMdxOutput = true;
846
+ try {
847
+ await this.refreshMdxDerivedOutput(realPages, successfulPages);
848
+ }
849
+ catch (error) {
850
+ await this.rollbackCommittedMdxChange(error, previousState, pageCommits);
851
+ }
485
852
  }
486
853
  async getAllMDXFiles() {
487
854
  return this.sourceFs.getAllMdxFiles();
@@ -495,87 +862,26 @@ export class MDXToNextJSGenerator {
495
862
  const resolvedPages = pages ?? (await this.buildAllPagesMeta());
496
863
  return siteLayoutTemplate(resolvedPages, this.sectionsConfig);
497
864
  }
498
- async generateSectionIndexPages(pages) {
499
- const nextSlugs = new Set();
500
- if (this.sectionsConfig && this.sectionsConfig.length > 0) {
501
- const resolvedPages = pages ?? (await this.buildAllPagesMeta());
502
- for (const section of this.sectionsConfig) {
503
- if (section.slug === "")
504
- continue;
505
- // Check if a page already exists at the section root
506
- const hasIndex = resolvedPages.some((p) => p.slug === section.slug);
507
- if (hasIndex)
508
- continue;
509
- // Find the first page in this section
510
- const sectionPages = resolvedPages
511
- .filter((p) => p.section === section.slug)
512
- .sort((a, b) => {
513
- if (a.categoryOrder !== b.categoryOrder)
514
- return a.categoryOrder - b.categoryOrder;
515
- return a.order - b.order;
516
- });
517
- if (sectionPages.length === 0)
518
- continue;
519
- const firstPage = sectionPages[0];
520
- const redirectContent = `import { redirect } from "next/navigation";
865
+ async generateSectionIndexPages(pages, declaredSlugs) {
866
+ const resolvedPages = pages ?? (await this.buildAllPagesMeta());
867
+ return this.sectionIndexGenerator.generate(resolvedPages, this.sectionsConfig, declaredSlugs, (slug, target) => this.writeSectionIndexRedirect(slug, target));
868
+ }
869
+ async writeSectionIndexRedirect(slug, target) {
870
+ const content = `import { redirect } from "next/navigation";
521
871
 
522
872
  export default function SectionIndex() {
523
- redirect("/${firstPage.slug}");
873
+ redirect("/${target}");
524
874
  }
525
875
  `;
526
- const pagePath = resolveOutputPath(this.outputDir, "app", "(site)", section.slug, "page.tsx");
527
- await fs.ensureDir(path.dirname(pagePath));
528
- await writeFileAtomic(pagePath, redirectContent);
529
- nextSlugs.add(section.slug);
530
- console.log(chalk.blue(`🔀 Generated section index redirect: /${section.slug} -> /${firstPage.slug}`));
531
- }
532
- }
533
- await this.cleanupStaleSectionIndexPages(nextSlugs);
534
- }
535
- /**
536
- * Removes section index redirects written earlier in this session whose
537
- * section has since disappeared (e.g. the API Reference section after the
538
- * `openapi` config is removed mid-watch). Only files that still contain the
539
- * generated redirect are deleted, so a hand-written page that has taken
540
- * over the slug is never touched. Fresh processes start clean anyway -
541
- * init() wipes app/ - so in-session tracking is enough.
542
- */
543
- async cleanupStaleSectionIndexPages(nextSlugs) {
544
- return this.generatedRouteManager.cleanupStaleSectionIndexPages(nextSlugs, (dir, stopDir) => this.removeEmptyDirsUpTo(dir, stopDir));
545
- }
546
- /** Best-effort removal of now-empty directories up to (not incl.) stopDir. */
547
- async removeEmptyDirsUpTo(dir, stopDir) {
548
- return this.generatedRouteManager.removeEmptyDirsUpTo(dir, stopDir);
876
+ await writeFileAtomic(this.outputPath("app", "(site)", slug, "page.tsx"), content);
877
+ console.log(chalk.blue(`🔀 Generated section index redirect: /${slug} -> /${target}`));
549
878
  }
550
879
  async generatePageFromMDX(mdxFile, options) {
551
- const rendered = renderMdxPage(mdxFile, options);
552
- const pagePath = resolveOutputPath(this.outputDir, "app", "(site)", mdxFile.slug, "page.tsx");
553
- await fs.ensureDir(path.dirname(pagePath));
554
- await writeFileAtomic(pagePath, rendered.pageContent);
555
- // The feed route lives inside the page's directory, so a deleted page
556
- // takes its feed along (handleFileDelete removes the whole dir) and the
557
- // else-branch prunes the route when a regenerated page no longer has
558
- // Update blocks. Cross-run staleness is covered by the app/ wipe in
559
- // createNextJSStructure.
560
- if (rendered.rssRoute.action !== "preserve") {
561
- const rssDir = resolveOutputPath(path.dirname(pagePath), "rss.xml");
562
- if (rendered.rssRoute.action === "write") {
563
- await fs.ensureDir(rssDir);
564
- await writeFileAtomic(resolveOutputPath(path.dirname(pagePath), "rss.xml", "route.ts"), rendered.rssRoute.content);
565
- }
566
- else {
567
- await fs.remove(rssDir);
568
- }
569
- }
880
+ return this.generatedPagePublisher.generatePageFromMdx(mdxFile, options);
570
881
  }
571
882
  /** Parses the configured OpenAPI spec(s) into the shared registry. */
572
883
  async loadOpenApiRegistry() {
573
- if (this.openApiSpecs.length === 0)
574
- return;
575
- await this.apiRegistry.load(this.openApiSpecs, this.rootDir, this.apiBaseSlug);
576
- if (!this.apiRegistry.isEmpty) {
577
- console.log(chalk.blue(`📘 Loaded ${this.apiRegistry.all.length} API endpoint(s) from ${this.openApiSpecs.length} spec(s)`));
578
- }
884
+ return this.openApiRefreshCoordinator.loadInitialRegistry();
579
885
  }
580
886
  /**
581
887
  * Generates one page per OpenAPI operation, (re)writes the request-execution
@@ -584,17 +890,28 @@ export default function SectionIndex() {
584
890
  * - it still emits an empty allowlist and prunes any previously generated
585
891
  * pages (e.g. after the `openapi` config is removed).
586
892
  */
587
- async writeApiPages() {
588
- const realPages = await this.buildRealPagesMeta();
589
- return this.apiReferenceGenerator.writePages(this.apiRegistry, this.apiBaseSlug, realPages, (mdxFile, options) => this.generatePageFromMDX(mdxFile, options), () => this.writeApiAllowlist(), (nextRoutes, realSlugs) => this.cleanupStaleApiPages(nextRoutes, realSlugs));
893
+ async writeApiPages(realPages, options = {}) {
894
+ const resolvedRealPages = realPages ?? (await this.buildRealPagesMeta());
895
+ const blockedRealPages = [...resolvedRealPages];
896
+ const blockedSlugs = new Set(blockedRealPages.map((page) => page.slug));
897
+ for (const page of this.successfulMdxPages.values()) {
898
+ if (blockedSlugs.has(page.slug))
899
+ continue;
900
+ blockedSlugs.add(page.slug);
901
+ blockedRealPages.push(page);
902
+ }
903
+ const occupiedMdxSlugs = new Set([...this.successfulMdxPages.values()].map((page) => page.slug));
904
+ return this.apiReferenceGenerator.writePages(this.apiRegistry, this.apiBaseSlug, blockedRealPages, async (mdxFile, options) => {
905
+ await this.generatePageFromMDX(mdxFile, options);
906
+ }, () => this.writeApiAllowlist(), (nextRoutes) => this.cleanupStaleApiPages(nextRoutes, occupiedMdxSlugs, options.additionalPreviousRoutes), options.writtenRoutes);
590
907
  }
591
908
  /** Writes the request-execution allowlist (overwrites the shipped stub). */
592
909
  async writeApiAllowlist() {
593
910
  return this.apiReferenceGenerator.writeAllowlist(this.apiRegistry);
594
911
  }
595
912
  /** Removes endpoint page directories that are no longer in the spec. */
596
- async cleanupStaleApiPages(nextRoutes, realSlugs) {
597
- return this.apiReferenceGenerator.cleanupStalePages(nextRoutes, realSlugs, (slug) => this.removeOwnedRoute(slug));
913
+ async cleanupStaleApiPages(nextRoutes, occupiedMdxSlugs, additionalPreviousRoutes = []) {
914
+ return this.apiReferenceGenerator.cleanupStalePages(nextRoutes, occupiedMdxSlugs, (slug) => this.removeOwnedRoute(slug), additionalPreviousRoutes);
598
915
  }
599
916
  /**
600
917
  * (Re)points the spec-file watcher at the currently configured spec paths.
@@ -602,29 +919,11 @@ export default function SectionIndex() {
602
919
  * so specs added mid-session are watched without a restart.
603
920
  */
604
921
  async syncOpenApiSpecWatcher() {
605
- return this.watchCoordinator.syncOpenApiSpecWatcher(this.openApiSpecs);
606
- }
607
- /**
608
- * Reparses the spec(s) and rewrites everything derived from them: the
609
- * endpoint pages and allowlist, the sections (the "API Reference" section
610
- * appears and disappears with the registry), and the site aggregates.
611
- */
612
- async rebuildApiReference() {
613
- await this.apiRegistry.load(this.openApiSpecs, this.rootDir, this.apiBaseSlug);
614
- this.sectionsConfig = await this.resolveSections();
615
- await this.writeApiPages();
616
- await this.refreshSiteAggregates();
922
+ return this.watchCoordinator.syncOpenApiSpecWatcher(this.openApiSpecs, this.apiRegistry.sourceFiles);
617
923
  }
618
924
  /** Reparses the spec(s) and regenerates the API reference on a watch event. */
619
925
  async handleOpenApiChange() {
620
- console.log(chalk.cyan("📘 OpenAPI spec changed - regenerating API reference"));
621
- try {
622
- await this.rebuildApiReference();
623
- console.log(chalk.green("✅ API reference updated"));
624
- }
625
- catch (error) {
626
- console.error(chalk.red("❌ Error updating API reference:"), error);
627
- }
926
+ return this.openApiRefreshCoordinator.handleOpenApiChange();
628
927
  }
629
928
  /**
630
929
  * Applies `openapi` edits in doccupine.json without a restart: reloads the
@@ -635,93 +934,23 @@ export default function SectionIndex() {
635
934
  * half-written editor save) keeps the current configuration.
636
935
  */
637
936
  async handleDoccupineConfigChange() {
638
- const configPath = path.join(this.rootDir, this.doccupineConfigFile);
639
- let config;
640
- try {
641
- config = validateConfig(JSON.parse(await fs.readFile(configPath, "utf8")), this.rootDir);
642
- }
643
- catch (error) {
644
- console.warn(chalk.yellow("⚠️ doccupine.json is missing or invalid - keeping the current configuration"), error instanceof Error ? error.message : error);
645
- return;
646
- }
647
- if ((config.watchDir &&
648
- path.resolve(this.rootDir, config.watchDir) !== this.watchDir) ||
649
- (config.outputDir &&
650
- path.resolve(this.rootDir, config.outputDir) !== this.outputDir)) {
651
- console.log(chalk.yellow("⚠️ watchDir/outputDir changes in doccupine.json need a restart to apply"));
652
- }
653
- const nextSpecs = normalizeOpenApiConfig(config.openapi);
654
- if (JSON.stringify(nextSpecs) === JSON.stringify(this.openApiSpecs)) {
655
- return;
656
- }
657
- console.log(chalk.cyan("📘 OpenAPI configuration changed - updating API reference"));
658
- let nextRegistry;
659
- try {
660
- // Validate the complete candidate before changing the active spec list or
661
- // its watcher. A half-written/invalid replacement keeps both the current
662
- // generated reference and its live watcher intact.
663
- nextRegistry = new OpenApiRegistry();
664
- await nextRegistry.load(nextSpecs, this.rootDir, this.apiBaseSlug);
665
- }
666
- catch (error) {
667
- console.error(chalk.red("❌ Error updating API reference:"), error);
668
- return;
669
- }
670
- const previousRegistry = this.apiRegistry;
671
- const previousSpecs = this.openApiSpecs;
672
- const previousSections = this.sectionsConfig;
673
- try {
674
- this.apiRegistry = nextRegistry;
675
- this.openApiSpecs = nextSpecs;
676
- await this.syncOpenApiSpecWatcher();
677
- this.sectionsConfig = await this.resolveSections();
678
- await this.writeApiPages();
679
- await this.refreshSiteAggregates();
680
- console.log(chalk.green("✅ API reference updated"));
681
- }
682
- catch (error) {
683
- console.error(chalk.red("❌ Error updating API reference:"), error);
684
- this.apiRegistry = previousRegistry;
685
- this.openApiSpecs = previousSpecs;
686
- this.sectionsConfig = previousSections;
687
- try {
688
- await this.syncOpenApiSpecWatcher();
689
- }
690
- catch (rollbackError) {
691
- console.error(chalk.red("❌ Error restoring the previous OpenAPI watcher:"), rollbackError);
692
- }
693
- try {
694
- await this.writeApiPages();
695
- await this.refreshSiteAggregates();
696
- }
697
- catch (rollbackError) {
698
- console.error(chalk.red("❌ Error restoring previous API reference output:"), rollbackError);
699
- }
700
- }
701
- }
702
- async updatePagesIndex() {
703
- const files = await this.getAllMDXFiles();
937
+ return this.openApiRefreshCoordinator.handleConfigChange();
938
+ }
939
+ async updatePagesIndex(pages) {
940
+ const files = pages
941
+ ? pages
942
+ .map((page) => page.path)
943
+ .filter((file) => file === "index.mdx" || file === "./index.mdx")
944
+ : await this.getAllMDXFiles();
704
945
  let indexMDX = null;
705
946
  for (const file of files) {
706
947
  if (file === "index.mdx" || file === "./index.mdx") {
707
- const { content } = await this.readMdxSourceFile(file);
948
+ const cached = this.successfulMdxContent.get(file.replace(/\\/g, "/"));
949
+ if (this.mdxSnapshotInitialized && cached === undefined)
950
+ break;
951
+ const content = cached ?? (await this.readMdxSourceFile(file)).content;
708
952
  const { data: frontmatter, content: mdxContent } = safeMatter(content, file);
709
- indexMDX = {
710
- content: mdxContent,
711
- title: frontmatter.title || "Welcome",
712
- description: frontmatter.description || "",
713
- icon: frontmatter.icon,
714
- image: frontmatter.image,
715
- name: frontmatter.name,
716
- date: typeof frontmatter.date === "string" ? frontmatter.date : undefined,
717
- updated: typeof frontmatter.updated === "string"
718
- ? frontmatter.updated
719
- : undefined,
720
- openapi: typeof frontmatter.openapi === "string"
721
- ? frontmatter.openapi
722
- : undefined,
723
- rss: frontmatter.rss === true,
724
- };
953
+ indexMDX = this.homepageSource(frontmatter, mdxContent);
725
954
  break;
726
955
  }
727
956
  }
@@ -734,28 +963,10 @@ export default function SectionIndex() {
734
963
  console.error(chalk.red(`❌ openapi frontmatter "${indexMDX.openapi}" in index.mdx not found in any spec`));
735
964
  }
736
965
  }
737
- const rendered = renderHomepage(indexMDX, apiOperation);
738
- const homePath = this.outputPath("app", "(site)", "page.tsx");
739
- await fs.ensureDir(path.dirname(homePath));
740
- await writeFileAtomic(homePath, rendered.pageContent);
741
- // Same lifecycle as the per-page feeds in generatePageFromMDX: write the
742
- // root feed route while the homepage has Update blocks, prune it when
743
- // they go away or index.mdx is deleted (this runs on every aggregate
744
- // refresh, including the delete path).
745
- const rssDir = this.outputPath("app", "(site)", "rss.xml");
746
- if (rendered.rssRoute.action === "write") {
747
- await fs.ensureDir(rssDir);
748
- await writeFileAtomic(this.outputPath("app", "(site)", "rss.xml", "route.ts"), rendered.rssRoute.content);
749
- }
750
- else {
751
- await fs.remove(rssDir);
752
- }
966
+ await this.generatedPagePublisher.updateHomepage(indexMDX, apiOperation);
753
967
  }
754
968
  async updateSectionIndex(sectionSlug, frontmatter, mdxContent, sourcePath) {
755
- const rendered = renderSectionPage(sectionSlug, frontmatter, mdxContent, sourcePath);
756
- const pagePath = resolveOutputPath(this.outputDir, "app", "(site)", sectionSlug, "page.tsx");
757
- await fs.ensureDir(path.dirname(pagePath));
758
- await writeFileAtomic(pagePath, rendered.pageContent);
969
+ return this.generatedPagePublisher.updateSectionIndex(sectionSlug, frontmatter, mdxContent, sourcePath);
759
970
  }
760
971
  async updateRootLayout(pages) {
761
972
  await writeFileAtomic(this.outputPath("app", "layout.tsx"), await this.generateRootLayout());
@@ -764,7 +975,7 @@ export default function SectionIndex() {
764
975
  await writeFileAtomic(siteLayoutPath, await this.generateSiteLayout(pages));
765
976
  }
766
977
  async loadSiteUrl() {
767
- return loadSiteUrlArtifact(this.rootDir);
978
+ return loadSiteUrlArtifact(() => this.projectConfigRepository.readConfigFile());
768
979
  }
769
980
  async updateSitemap(pages) {
770
981
  return writeSitemap(this.outputDir, this.sectionsConfig, async () => pages ?? (await this.buildAllPagesMeta()), () => this.loadSiteUrl());
@@ -773,7 +984,7 @@ export default function SectionIndex() {
773
984
  return writeRobots(this.outputDir, () => this.loadSiteUrl());
774
985
  }
775
986
  async updateLlmsFiles(pages) {
776
- return writeLlmsFiles(this.outputDir, this.sectionsConfig, async () => pages ?? (await this.buildAllPagesMeta()), (filePath) => this.readMdxSourceFile(filePath), (slug) => this.apiRegistry.bodyForSlug(slug), () => loadSiteMetadata(this.rootDir), this.publicAssetManager);
987
+ 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);
777
988
  }
778
989
  async stop() {
779
990
  return this.watchCoordinator.stop();