doccupine 0.0.144 → 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 (40) 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-route-manager.d.ts +4 -3
  6. package/dist/generator/generated-route-manager.js +34 -11
  7. package/dist/generator/page-catalog.d.ts +4 -0
  8. package/dist/generator/page-catalog.js +8 -1
  9. package/dist/generator/project-config-repository.d.ts +8 -0
  10. package/dist/generator/project-config-repository.js +73 -15
  11. package/dist/generator/secure-source-fs.d.ts +5 -1
  12. package/dist/generator/secure-source-fs.js +112 -3
  13. package/dist/generator/site-artifacts.d.ts +3 -2
  14. package/dist/generator/site-artifacts.js +6 -9
  15. package/dist/generator/watch-coordinator.d.ts +3 -2
  16. package/dist/generator/watch-coordinator.js +29 -11
  17. package/dist/lib/config-manager.d.ts +1 -0
  18. package/dist/lib/config-manager.js +194 -12
  19. package/dist/lib/generated-artifacts.d.ts +8 -2
  20. package/dist/lib/generated-artifacts.js +25 -6
  21. package/dist/lib/openapi.d.ts +4 -0
  22. package/dist/lib/openapi.js +36 -4
  23. package/dist/mdx-to-nextjs-generator.d.ts +43 -9
  24. package/dist/mdx-to-nextjs-generator.js +679 -211
  25. package/dist/templates/mdx/api-playground.mdx.d.ts +1 -1
  26. package/dist/templates/mdx/api-playground.mdx.js +11 -2
  27. package/dist/templates/mdx/commands.mdx.d.ts +1 -1
  28. package/dist/templates/mdx/commands.mdx.js +26 -1
  29. package/dist/templates/mdx/media-and-assets.mdx.d.ts +1 -1
  30. package/dist/templates/mdx/media-and-assets.mdx.js +5 -0
  31. package/dist/templates/mdx/model-context-protocol.mdx.d.ts +1 -1
  32. package/dist/templates/mdx/model-context-protocol.mdx.js +2 -1
  33. package/dist/templates/mdx/platform/api-playground.mdx.d.ts +1 -1
  34. package/dist/templates/mdx/platform/api-playground.mdx.js +2 -2
  35. package/dist/templates/mdx/platform/publishing.mdx.d.ts +1 -1
  36. package/dist/templates/mdx/platform/publishing.mdx.js +3 -3
  37. package/dist/templates/mdx/what-is-doccupine.mdx.d.ts +1 -1
  38. package/dist/templates/mdx/what-is-doccupine.mdx.js +8 -3
  39. package/dist/templates/package.js +1 -1
  40. package/package.json +2 -2
@@ -1,10 +1,11 @@
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 { claimOutputDirectory, resolveOutputPath, } from "./lib/output-safety.js";
7
+ import { GeneratedArtifacts, } from "./lib/generated-artifacts.js";
8
+ import { claimOutputDirectory, readOutputFileIfPresent, 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";
10
11
  import { nextConfigTemplate } from "./templates/next.config.js";
@@ -18,7 +19,7 @@ import { PublicAssetManager } from "./generator/public-asset-manager.js";
18
19
  import { WatchCoordinator } from "./generator/watch-coordinator.js";
19
20
  import { addApiReferenceSection, determineSectionRoute, discoverSections, } from "./generator/section-resolver.js";
20
21
  import { renderHomepage, renderMdxPage, renderSectionPage, } from "./generator/page-renderer.js";
21
- import { buildRealPagesMeta as buildRealPageCatalog, mergePages as mergePageCatalog, parseMdxPageMeta, } from "./generator/page-catalog.js";
22
+ import { buildRealPagesMeta as buildRealPageCatalog, mergePages as mergePageCatalog, parseMdxPageMeta, RouteCollisionError, } from "./generator/page-catalog.js";
22
23
  import { loadSiteMetadata, loadSiteUrl as loadSiteUrlArtifact, writeLlmsFiles, writeRobots, writeSitemap, } from "./generator/site-artifacts.js";
23
24
  export class MDXToNextJSGenerator {
24
25
  watchDir;
@@ -50,6 +51,12 @@ export class MDXToNextJSGenerator {
50
51
  projectConfigRepository;
51
52
  publicAssetManager;
52
53
  watchCoordinator;
54
+ retainExistingMdxOutput = true;
55
+ mdxSnapshotInitialized = false;
56
+ successfulMdxPages = new Map();
57
+ successfulMdxContent = new Map();
58
+ successfulMdxSourcesBySlug = new Map();
59
+ collisionBlockedMdxSources = new Set();
53
60
  constructor(watchDir, outputDir, openApiSpecs = [], rootDir = process.cwd()) {
54
61
  this.watchDir = path.resolve(watchDir);
55
62
  this.outputDir = path.resolve(outputDir);
@@ -71,6 +78,7 @@ export class MDXToNextJSGenerator {
71
78
  doccupineConfigFile: this.doccupineConfigFile,
72
79
  sourceFs: this.sourceFs,
73
80
  getOpenApiSpecs: () => this.openApiSpecs,
81
+ getOpenApiSourceFiles: () => this.apiRegistry.sourceFiles,
74
82
  callbacks: {
75
83
  syncOpenApiSpecWatcher: () => this.syncOpenApiSpecWatcher(),
76
84
  handleFileChange: (action, filePath) => this.handleFileChange(action, filePath),
@@ -86,7 +94,7 @@ export class MDXToNextJSGenerator {
86
94
  copyPublicFiles: () => this.copyPublicFiles(),
87
95
  handlePublicFileChange: (filePath) => this.handlePublicFileChange(filePath),
88
96
  handlePublicFileDelete: (filePath) => this.handlePublicFileDelete(filePath),
89
- processAllMDXFiles: () => this.processAllMDXFiles(),
97
+ processAllMDXFiles: () => this.reconcileMdxSources(),
90
98
  },
91
99
  });
92
100
  }
@@ -96,47 +104,58 @@ export class MDXToNextJSGenerator {
96
104
  async readMdxSourceFile(filePath) {
97
105
  return this.sourceFs.readMdxSourceFile(filePath);
98
106
  }
99
- async ensureSafeStarterPath(relativePath) {
100
- return this.sourceFs.ensureSafeStarterPath(relativePath);
107
+ async writeStarterFilesIfEmpty(files) {
108
+ return this.sourceFs.writeStarterFilesIfEmpty(files);
109
+ }
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}`;
101
119
  }
102
120
  async init() {
103
121
  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(", ")}`));
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();
129
158
  }
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
159
  }
141
160
  async createNextJSStructure() {
142
161
  return this.appScaffolder.createNextJsStructure(this.analyticsConfig, {
@@ -148,8 +167,7 @@ export class MDXToNextJSGenerator {
148
167
  }
149
168
  async createStartingDocs() {
150
169
  return this.appScaffolder.createStartingDocs({
151
- getAllMdxFiles: () => this.getAllMDXFiles(),
152
- ensureSafeStarterPath: (filePath) => this.ensureSafeStarterPath(filePath),
170
+ writeStarterFilesIfEmpty: (files) => this.writeStarterFilesIfEmpty(files),
153
171
  });
154
172
  }
155
173
  async copyCustomConfigFiles() {
@@ -224,6 +242,9 @@ export class MDXToNextJSGenerator {
224
242
  }
225
243
  }
226
244
  }
245
+ async reconcileMdxSources() {
246
+ await this.processAllMDXFiles();
247
+ }
227
248
  determineSectionForFile(filePath, frontmatter) {
228
249
  return determineSectionRoute(filePath, frontmatter, this.sectionsConfig);
229
250
  }
@@ -339,22 +360,229 @@ export class MDXToNextJSGenerator {
339
360
  async startWatching() {
340
361
  return this.watchCoordinator.startWatching();
341
362
  }
342
- async parseMDXFile(file) {
343
- return parseMdxPageMeta(file, (filePath) => this.readMdxSourceFile(filePath), (filePath, frontmatter) => this.determineSectionForFile(filePath, frontmatter), (reference) => this.apiRegistry.lookup(reference)?.method);
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));
375
+ }
376
+ }));
377
+ if (refreshSections) {
378
+ const configuredSections = await this.loadSectionsConfig();
379
+ if (configuredSections !== null) {
380
+ this.sectionsConfig = this.withApiReferenceSection(configuredSections);
381
+ }
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));
393
+ }
394
+ }
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);
400
+ });
401
+ return { files: resolvedFiles, pages, sources };
344
402
  }
345
403
  async buildRealPagesMeta() {
346
- const files = await this.getAllMDXFiles();
347
- return buildRealPageCatalog(files, (file) => this.parseMDXFile(file));
404
+ return (await this.captureMdxPass()).pages;
348
405
  }
349
406
  async buildAllPagesMeta() {
350
407
  const real = await this.buildRealPagesMeta();
351
- return mergePageCatalog(real, this.apiRegistry.isEmpty ? [] : this.apiRegistry.syntheticPages());
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] : [];
423
+ });
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();
475
+ }
476
+ catch (error) {
477
+ errors.push(error);
478
+ }
479
+ }
480
+ return errors;
481
+ }
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");
487
+ }
488
+ throw error;
489
+ }
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);
505
+ }
506
+ }
507
+ try {
508
+ await this.artifacts.replaceRoutesAndSave("mdx", state.routes.map(({ source, slug }) => ({ source, slug })));
509
+ }
510
+ catch (rollbackError) {
511
+ rollbackErrors.push(rollbackError);
512
+ }
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;
523
+ }
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);
531
+ }
532
+ }
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;
546
+ }
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 };
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
+ };
352
580
  }
353
581
  async removeOwnedRoute(slug) {
354
582
  return this.generatedRouteManager.removeOwnedRoute(slug);
355
583
  }
356
- async removeStaleMdxRoutes(realPages) {
357
- return this.generatedRouteManager.removeStaleMdxRoutes(realPages, (slug) => this.removeOwnedRoute(slug));
584
+ async removeStaleMdxRoutes(realPages, previousRoutes = this.artifacts.routesFor("mdx")) {
585
+ return this.generatedRouteManager.removeStaleMdxRoutes(realPages, (slug) => this.removeOwnedRoute(slug), previousRoutes);
358
586
  }
359
587
  /**
360
588
  * Writes the generated page(s) for a single MDX file: the doc page and, for a
@@ -363,39 +591,72 @@ export class MDXToNextJSGenerator {
363
591
  * redirects) - the caller batches those so a bulk build runs them once at the
364
592
  * end instead of once per file (which is what made large builds O(n²)).
365
593
  */
366
- async writePageForFile(filePath) {
367
- const { content } = await this.readMdxSourceFile(filePath);
594
+ async writePageForFile(filePath, content) {
595
+ const commits = [];
368
596
  const { data: frontmatter, content: mdxContent } = safeMatter(content, filePath);
369
597
  const { sectionSlug, pageSlug } = this.determineSectionForFile(filePath, frontmatter);
370
598
  const fullSlug = getFullSlug(pageSlug, sectionSlug);
371
599
  const isIndex = filePath === "index.mdx" || filePath === "./index.mdx";
372
600
  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`));
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
+ }
393
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));
394
631
  }
395
- await this.generatePageFromMDX(mdxFile, apiOperation ? { apiOperation } : undefined);
632
+ return commits;
396
633
  }
397
- if (isSectionIndex) {
398
- 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;
640
+ }
641
+ }
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
+ }
399
660
  }
400
661
  }
401
662
  /**
@@ -404,55 +665,103 @@ export class MDXToNextJSGenerator {
404
665
  * exactly once and threads the result through each generator, so one refresh
405
666
  * is a single scan rather than one scan per generator.
406
667
  */
407
- async refreshSiteAggregates(resolvedPages) {
668
+ async refreshSiteAggregates(resolvedPages, declaredSlugs) {
408
669
  const pages = resolvedPages ?? (await this.buildAllPagesMeta());
409
670
  await this.updatePagesIndex();
410
671
  await this.updateRootLayout(pages);
411
672
  await this.updateSitemap(pages);
412
673
  await this.updateLlmsFiles(pages);
413
- await this.generateSectionIndexPages(pages);
674
+ await this.generateSectionIndexPages(pages, declaredSlugs);
414
675
  }
415
676
  async handleFileChange(action, filePath) {
416
677
  console.log(chalk.cyan(`📝 File ${action}: ${filePath}`));
417
- 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;
418
683
  try {
419
684
  // Validate the complete route set before writing this page so a collision
420
685
  // 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();
686
+ const snapshot = await this.captureMdxPass(undefined, new Map([[normalizedSource, changedSource]]), true);
687
+ const realPages = snapshot.pages;
424
688
  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);
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
+ }
433
722
  console.log(chalk.green(`✅ Generated page for: ${filePath}`));
434
723
  await this.maybeUpdateSections();
435
724
  }
436
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
+ }
437
732
  console.error(chalk.red(`❌ Error processing ${filePath}:`), error);
438
733
  }
439
734
  }
440
735
  async handleFileDelete(filePath) {
441
736
  console.log(chalk.red(`🗑️ File deleted: ${filePath}`));
737
+ const previousState = this.captureSuccessfulMdxState();
738
+ const pageCommits = [];
442
739
  try {
740
+ const normalizedSource = filePath.replace(/\\/g, "/");
741
+ this.removeSuccessfulMdxPage(normalizedSource);
742
+ this.collisionBlockedMdxSources.delete(normalizedSource);
443
743
  if (filePath === "index.mdx" || filePath === "./index.mdx") {
444
744
  console.log(chalk.blue("🏠 Updating homepage - index.mdx deleted"));
445
745
  }
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();
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);
764
+ }
456
765
  console.log(chalk.green(`✅ Removed page for: ${filePath}`));
457
766
  await this.maybeUpdateSections();
458
767
  }
@@ -461,27 +770,66 @@ export class MDXToNextJSGenerator {
461
770
  }
462
771
  }
463
772
  async processAllMDXFiles() {
773
+ const previousState = this.captureSuccessfulMdxState();
774
+ const pageCommits = [];
464
775
  const files = await this.getAllMDXFiles();
465
776
  // Fail before writing any page when two source files resolve to one route.
466
- const realPages = await this.buildRealPagesMeta();
467
- 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;
468
792
  // Write each page first (the only genuinely per-file work), then run the
469
793
  // site-wide aggregations a single time. Doing the aggregations per file
470
794
  // re-scanned and re-parsed every MDX file on each iteration, which made a
471
795
  // full build O(n²); batching them makes it O(n). A single bad file is
472
796
  // logged and skipped so it never aborts the whole build.
797
+ const pagesBySource = new Map(realPages.map((page) => [page.path.replace(/\\/g, "/"), page]));
473
798
  for (const file of files) {
474
799
  console.log(chalk.cyan(`📝 Processing: ${file}`));
800
+ const normalizedSource = file.replace(/\\/g, "/");
475
801
  try {
476
- 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);
477
811
  }
478
812
  catch (error) {
813
+ if (!this.retainExistingMdxOutput) {
814
+ this.removeSuccessfulMdxPage(normalizedSource);
815
+ }
479
816
  console.error(chalk.red(`❌ Error processing ${file}:`), error);
480
817
  }
481
818
  }
482
- await this.generatedRouteManager.replaceMdxRoutes(realPages);
483
- const pages = await this.buildAllPagesMeta();
484
- 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
+ }
485
833
  }
486
834
  async getAllMDXFiles() {
487
835
  return this.sourceFs.getAllMdxFiles();
@@ -495,15 +843,19 @@ export class MDXToNextJSGenerator {
495
843
  const resolvedPages = pages ?? (await this.buildAllPagesMeta());
496
844
  return siteLayoutTemplate(resolvedPages, this.sectionsConfig);
497
845
  }
498
- async generateSectionIndexPages(pages) {
846
+ async generateSectionIndexPages(pages, declaredSlugs) {
499
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);
500
853
  if (this.sectionsConfig && this.sectionsConfig.length > 0) {
501
- const resolvedPages = pages ?? (await this.buildAllPagesMeta());
502
854
  for (const section of this.sectionsConfig) {
503
855
  if (section.slug === "")
504
856
  continue;
505
857
  // Check if a page already exists at the section root
506
- const hasIndex = resolvedPages.some((p) => p.slug === section.slug);
858
+ const hasIndex = resolvedDeclaredSlugs.has(section.slug);
507
859
  if (hasIndex)
508
860
  continue;
509
861
  // Find the first page in this section
@@ -530,49 +882,126 @@ export default function SectionIndex() {
530
882
  console.log(chalk.blue(`🔀 Generated section index redirect: /${section.slug} -> /${firstPage.slug}`));
531
883
  }
532
884
  }
533
- await this.cleanupStaleSectionIndexPages(nextSlugs);
885
+ await this.cleanupStaleSectionIndexPages(nextSlugs, occupiedSlugs);
534
886
  }
535
887
  /**
536
888
  * Removes section index redirects written earlier in this session whose
537
889
  * 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.
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.
542
893
  */
543
- async cleanupStaleSectionIndexPages(nextSlugs) {
544
- return this.generatedRouteManager.cleanupStaleSectionIndexPages(nextSlugs, (dir, stopDir) => this.removeEmptyDirsUpTo(dir, stopDir));
894
+ async cleanupStaleSectionIndexPages(nextSlugs, occupiedSlugs) {
895
+ return this.generatedRouteManager.cleanupStaleSectionIndexPages(nextSlugs, occupiedSlugs, (dir, stopDir) => this.removeEmptyDirsUpTo(dir, stopDir));
545
896
  }
546
897
  /** Best-effort removal of now-empty directories up to (not incl.) stopDir. */
547
898
  async removeEmptyDirsUpTo(dir, stopDir) {
548
899
  return this.generatedRouteManager.removeEmptyDirsUpTo(dir, stopDir);
549
900
  }
550
- 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");
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 {
562
936
  if (rendered.rssRoute.action === "write") {
563
- await fs.ensureDir(rssDir);
564
- await writeFileAtomic(resolveOutputPath(path.dirname(pagePath), "rss.xml", "route.ts"), rendered.rssRoute.content);
937
+ await writeFileAtomic(rssPath, rendered.rssRoute.content);
938
+ rssChanged = true;
939
+ await writeFileAtomic(pagePath, rendered.pageContent);
940
+ pageChanged = true;
565
941
  }
566
942
  else {
567
- await fs.remove(rssDir);
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
+ }
568
967
  }
968
+ if (rollbackErrors.length > 0) {
969
+ throw new AggregateError([error, ...rollbackErrors], `Unable to publish or restore generated page ${pagePath}`);
970
+ }
971
+ throw error;
569
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
+ };
993
+ }
994
+ async generatePageFromMDX(mdxFile, options) {
995
+ const rendered = renderMdxPage(mdxFile, options);
996
+ const pagePath = resolveOutputPath(this.outputDir, "app", "(site)", mdxFile.slug, "page.tsx");
997
+ await fs.ensureDir(path.dirname(pagePath));
998
+ return this.commitRenderedPage(pagePath, rendered);
570
999
  }
571
1000
  /** Parses the configured OpenAPI spec(s) into the shared registry. */
572
1001
  async loadOpenApiRegistry() {
573
1002
  if (this.openApiSpecs.length === 0)
574
1003
  return;
575
- await this.apiRegistry.load(this.openApiSpecs, this.rootDir, this.apiBaseSlug);
1004
+ this.apiRegistry = (await this.loadStableOpenApiRegistry(this.openApiSpecs)).registry;
576
1005
  if (!this.apiRegistry.isEmpty) {
577
1006
  console.log(chalk.blue(`📘 Loaded ${this.apiRegistry.all.length} API endpoint(s) from ${this.openApiSpecs.length} spec(s)`));
578
1007
  }
@@ -584,17 +1013,28 @@ export default function SectionIndex() {
584
1013
  * - it still emits an empty allowlist and prunes any previously generated
585
1014
  * pages (e.g. after the `openapi` config is removed).
586
1015
  */
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));
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))
1022
+ continue;
1023
+ blockedSlugs.add(page.slug);
1024
+ blockedRealPages.push(page);
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);
590
1030
  }
591
1031
  /** Writes the request-execution allowlist (overwrites the shipped stub). */
592
1032
  async writeApiAllowlist() {
593
1033
  return this.apiReferenceGenerator.writeAllowlist(this.apiRegistry);
594
1034
  }
595
1035
  /** 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));
1036
+ async cleanupStaleApiPages(nextRoutes, occupiedMdxSlugs, additionalPreviousRoutes = []) {
1037
+ return this.apiReferenceGenerator.cleanupStalePages(nextRoutes, occupiedMdxSlugs, (slug) => this.removeOwnedRoute(slug), additionalPreviousRoutes);
598
1038
  }
599
1039
  /**
600
1040
  * (Re)points the spec-file watcher at the currently configured spec paths.
@@ -602,24 +1042,108 @@ export default function SectionIndex() {
602
1042
  * so specs added mid-session are watched without a restart.
603
1043
  */
604
1044
  async syncOpenApiSpecWatcher() {
605
- return this.watchCoordinator.syncOpenApiSpecWatcher(this.openApiSpecs);
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);
1076
+ }
1077
+ throw new Error("OpenAPI sources changed repeatedly while being generated");
606
1078
  }
607
1079
  /**
608
1080
  * Reparses the spec(s) and rewrites everything derived from them: the
609
1081
  * endpoint pages and allowlist, the sections (the "API Reference" section
610
1082
  * appears and disappears with the registry), and the site aggregates.
611
1083
  */
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();
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
+ }
617
1141
  }
618
1142
  /** Reparses the spec(s) and regenerates the API reference on a watch event. */
619
1143
  async handleOpenApiChange() {
620
1144
  console.log(chalk.cyan("📘 OpenAPI spec changed - regenerating API reference"));
621
1145
  try {
622
- await this.rebuildApiReference();
1146
+ await this.applyStableOpenApiRefresh(this.openApiSpecs, true);
623
1147
  console.log(chalk.green("✅ API reference updated"));
624
1148
  }
625
1149
  catch (error) {
@@ -638,7 +1162,8 @@ export default function SectionIndex() {
638
1162
  const configPath = path.join(this.rootDir, this.doccupineConfigFile);
639
1163
  let config;
640
1164
  try {
641
- 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);
642
1167
  }
643
1168
  catch (error) {
644
1169
  console.warn(chalk.yellow("⚠️ doccupine.json is missing or invalid - keeping the current configuration"), error instanceof Error ? error.message : error);
@@ -655,48 +1180,15 @@ export default function SectionIndex() {
655
1180
  return;
656
1181
  }
657
1182
  console.log(chalk.cyan("📘 OpenAPI configuration changed - updating API reference"));
658
- let nextRegistry;
659
1183
  try {
660
1184
  // Validate the complete candidate before changing the active spec list or
661
1185
  // its watcher. A half-written/invalid replacement keeps both the current
662
1186
  // 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();
1187
+ await this.applyStableOpenApiRefresh(nextSpecs, true);
680
1188
  console.log(chalk.green("✅ API reference updated"));
681
1189
  }
682
1190
  catch (error) {
683
1191
  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
1192
  }
701
1193
  }
702
1194
  async updatePagesIndex() {
@@ -704,24 +1196,12 @@ export default function SectionIndex() {
704
1196
  let indexMDX = null;
705
1197
  for (const file of files) {
706
1198
  if (file === "index.mdx" || file === "./index.mdx") {
707
- 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;
708
1203
  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
- };
1204
+ indexMDX = this.homepageSource(frontmatter, mdxContent);
725
1205
  break;
726
1206
  }
727
1207
  }
@@ -737,25 +1217,13 @@ export default function SectionIndex() {
737
1217
  const rendered = renderHomepage(indexMDX, apiOperation);
738
1218
  const homePath = this.outputPath("app", "(site)", "page.tsx");
739
1219
  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
- }
1220
+ await this.commitRenderedPage(homePath, rendered);
753
1221
  }
754
1222
  async updateSectionIndex(sectionSlug, frontmatter, mdxContent, sourcePath) {
755
1223
  const rendered = renderSectionPage(sectionSlug, frontmatter, mdxContent, sourcePath);
756
1224
  const pagePath = resolveOutputPath(this.outputDir, "app", "(site)", sectionSlug, "page.tsx");
757
1225
  await fs.ensureDir(path.dirname(pagePath));
758
- await writeFileAtomic(pagePath, rendered.pageContent);
1226
+ return this.commitRenderedPage(pagePath, rendered);
759
1227
  }
760
1228
  async updateRootLayout(pages) {
761
1229
  await writeFileAtomic(this.outputPath("app", "layout.tsx"), await this.generateRootLayout());
@@ -764,7 +1232,7 @@ export default function SectionIndex() {
764
1232
  await writeFileAtomic(siteLayoutPath, await this.generateSiteLayout(pages));
765
1233
  }
766
1234
  async loadSiteUrl() {
767
- return loadSiteUrlArtifact(this.rootDir);
1235
+ return loadSiteUrlArtifact(() => this.projectConfigRepository.readConfigFile());
768
1236
  }
769
1237
  async updateSitemap(pages) {
770
1238
  return writeSitemap(this.outputDir, this.sectionsConfig, async () => pages ?? (await this.buildAllPagesMeta()), () => this.loadSiteUrl());
@@ -773,7 +1241,7 @@ export default function SectionIndex() {
773
1241
  return writeRobots(this.outputDir, () => this.loadSiteUrl());
774
1242
  }
775
1243
  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);
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);
777
1245
  }
778
1246
  async stop() {
779
1247
  return this.watchCoordinator.stop();