doccupine 0.0.146 → 0.0.148

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 (55) hide show
  1. package/README.md +11 -2
  2. package/dist/cli.d.ts +7 -0
  3. package/dist/cli.js +41 -0
  4. package/dist/generator/mdx-reconciliation-coordinator.d.ts +83 -0
  5. package/dist/generator/mdx-reconciliation-coordinator.js +471 -0
  6. package/dist/generator/page-renderer.js +18 -13
  7. package/dist/generator/secure-source-fs.js +5 -4
  8. package/dist/generator/site-artifacts.js +2 -2
  9. package/dist/generator/watch-coordinator.js +3 -2
  10. package/dist/index.js +8 -2
  11. package/dist/lib/layout.js +18 -10
  12. package/dist/lib/openapi-rendering.d.ts +17 -0
  13. package/dist/lib/openapi-rendering.js +193 -0
  14. package/dist/lib/openapi.d.ts +1 -7
  15. package/dist/lib/openapi.js +2 -192
  16. package/dist/lib/structures.js +2 -0
  17. package/dist/lib/utils.d.ts +14 -0
  18. package/dist/lib/utils.js +30 -8
  19. package/dist/mdx-to-nextjs-generator.d.ts +2 -41
  20. package/dist/mdx-to-nextjs-generator.js +37 -469
  21. package/dist/templates/components/Chat.d.ts +1 -1
  22. package/dist/templates/components/Chat.js +226 -1457
  23. package/dist/templates/components/SearchDocs.d.ts +1 -1
  24. package/dist/templates/components/SearchDocs.js +20 -15
  25. package/dist/templates/components/SearchModalContent.d.ts +1 -1
  26. package/dist/templates/components/SearchModalContent.js +7 -1
  27. package/dist/templates/components/layout/ApiPlayground.d.ts +1 -1
  28. package/dist/templates/components/layout/ApiPlayground.js +14 -148
  29. package/dist/templates/components/layout/DocsComponents.d.ts +1 -1
  30. package/dist/templates/components/layout/DocsComponents.js +3 -3
  31. package/dist/templates/components/layout/DocsNavigation.d.ts +1 -1
  32. package/dist/templates/components/layout/DocsNavigation.js +2 -3
  33. package/dist/templates/components/layout/Footer.d.ts +1 -1
  34. package/dist/templates/components/layout/Footer.js +2 -4
  35. package/dist/templates/components/layout/Header.d.ts +1 -1
  36. package/dist/templates/components/layout/Header.js +3 -3
  37. package/dist/templates/components/layout/StaticLinks.d.ts +1 -1
  38. package/dist/templates/components/layout/StaticLinks.js +2 -3
  39. package/dist/templates/env.example.d.ts +1 -1
  40. package/dist/templates/env.example.js +8 -0
  41. package/dist/templates/mdx/platform/analytics.mdx.d.ts +1 -1
  42. package/dist/templates/mdx/platform/analytics.mdx.js +13 -0
  43. package/dist/templates/mdx/platform/fonts-settings.mdx.d.ts +1 -1
  44. package/dist/templates/mdx/platform/fonts-settings.mdx.js +16 -0
  45. package/dist/templates/mdx/platform/publishing.mdx.d.ts +1 -1
  46. package/dist/templates/mdx/platform/publishing.mdx.js +16 -1
  47. package/dist/templates/mdx/platform/self-updating-docs.mdx.d.ts +1 -1
  48. package/dist/templates/mdx/platform/self-updating-docs.mdx.js +17 -5
  49. package/dist/templates/next.config.js +40 -0
  50. package/dist/templates/package.js +11 -10
  51. package/dist/templates/prettierignore.d.ts +1 -1
  52. package/dist/templates/prettierignore.js +11 -0
  53. package/dist/templates/utils/apiPlayground.d.ts +1 -0
  54. package/dist/templates/utils/apiPlayground.js +149 -0
  55. package/package.json +3 -3
@@ -7,23 +7,21 @@ import { normalizeOpenApiConfig, validateConfig, } from "./lib/config-manager.js
7
7
  import { GeneratedArtifacts, } from "./lib/generated-artifacts.js";
8
8
  import { claimOutputDirectory, resolveOutputPath, } from "./lib/output-safety.js";
9
9
  import { OpenApiRegistry, DEFAULT_API_BASE_SLUG } from "./lib/openapi.js";
10
- import { getFullSlug, safeMatter, writeFileAtomic } from "./lib/utils.js";
10
+ import { safeMatter, writeFileAtomic } from "./lib/utils.js";
11
11
  import { nextConfigTemplate } from "./templates/next.config.js";
12
12
  import { proxyTemplate } from "./templates/proxy.js";
13
13
  import { SecureSourceFs } from "./generator/secure-source-fs.js";
14
14
  import { AppScaffolder } from "./generator/app-scaffolder.js";
15
15
  import { ApiReferenceGenerator } from "./generator/api-reference-generator.js";
16
- import { GeneratedPagePublisher } from "./generator/generated-page-publisher.js";
16
+ import { GeneratedPagePublisher, } from "./generator/generated-page-publisher.js";
17
17
  import { GeneratedRouteManager } from "./generator/generated-route-manager.js";
18
- import { MdxPassBuilder, } from "./generator/mdx-pass-builder.js";
18
+ import { MdxReconciliationCoordinator } from "./generator/mdx-reconciliation-coordinator.js";
19
19
  import { ProjectConfigRepository } from "./generator/project-config-repository.js";
20
20
  import { PublicAssetManager } from "./generator/public-asset-manager.js";
21
21
  import { WatchCoordinator } from "./generator/watch-coordinator.js";
22
22
  import { SectionIndexGenerator } from "./generator/section-index-generator.js";
23
23
  import { OpenApiRefreshCoordinator, } from "./generator/openapi-refresh-coordinator.js";
24
24
  import { addApiReferenceSection, determineSectionRoute, discoverSections, } from "./generator/section-resolver.js";
25
- import { renderHomepage, } from "./generator/page-renderer.js";
26
- import { mergePages as mergePageCatalog, RouteCollisionError, } from "./generator/page-catalog.js";
27
25
  import { loadSiteMetadata, loadSiteUrl as loadSiteUrlArtifact, writeLlmsFiles, writeRobots, writeSitemap, } from "./generator/site-artifacts.js";
28
26
  export class MDXToNextJSGenerator {
29
27
  watchDir;
@@ -53,18 +51,12 @@ export class MDXToNextJSGenerator {
53
51
  apiReferenceGenerator;
54
52
  generatedPagePublisher;
55
53
  generatedRouteManager;
56
- mdxPassBuilder;
54
+ mdxReconciliationCoordinator;
57
55
  openApiRefreshCoordinator;
58
56
  sectionIndexGenerator;
59
57
  projectConfigRepository;
60
58
  publicAssetManager;
61
59
  watchCoordinator;
62
- retainExistingMdxOutput = true;
63
- mdxSnapshotInitialized = false;
64
- successfulMdxPages = new Map();
65
- successfulMdxContent = new Map();
66
- successfulMdxSourcesBySlug = new Map();
67
- collisionBlockedMdxSources = new Set();
68
60
  constructor(watchDir, outputDir, openApiSpecs = [], rootDir = process.cwd()) {
69
61
  this.watchDir = path.resolve(watchDir);
70
62
  this.outputDir = path.resolve(outputDir);
@@ -77,14 +69,33 @@ export class MDXToNextJSGenerator {
77
69
  this.generatedRouteManager = new GeneratedRouteManager(this.outputDir, this.artifacts);
78
70
  this.generatedPagePublisher = new GeneratedPagePublisher(this.outputDir, this.generatedRouteManager);
79
71
  this.sectionIndexGenerator = new SectionIndexGenerator(this.outputDir, this.generatedRouteManager);
80
- this.mdxPassBuilder = new MdxPassBuilder({
72
+ this.mdxReconciliationCoordinator = new MdxReconciliationCoordinator({
81
73
  sourceFs: this.sourceFs,
74
+ generatedRouteManager: this.generatedRouteManager,
82
75
  getAllMdxFiles: () => this.getAllMDXFiles(),
83
76
  getSections: () => this.sectionsConfig,
77
+ setSections: (sections) => {
78
+ this.sectionsConfig = sections;
79
+ },
84
80
  loadSectionsConfig: () => this.loadSectionsConfig(),
85
81
  withApiReferenceSection: (sections) => this.withApiReferenceSection(sections),
86
82
  determineSectionForFile: (filePath, frontmatter, sections) => this.determineSectionForFile(filePath, frontmatter, sections),
87
- resolveHttpMethod: (reference) => this.apiRegistry.lookup(reference)?.method,
83
+ lookupOpenApi: (reference) => this.apiRegistry.lookup(reference),
84
+ isOpenApiRegistryEmpty: () => this.apiRegistry.isEmpty,
85
+ syntheticOpenApiPages: () => this.apiRegistry.syntheticPages(),
86
+ getMdxRoutes: () => this.artifacts.routesFor("mdx"),
87
+ getOpenApiRoutes: () => this.artifacts.routesFor("openapi"),
88
+ replaceMdxRoutes: (routes) => this.artifacts.replaceRoutesAndSave("mdx", routes),
89
+ generatePageFromMdx: (mdxFile, options) => this.generatePageFromMDX(mdxFile, options),
90
+ updateSectionIndex: (sectionSlug, frontmatter, content, sourcePath) => this.updateSectionIndex(sectionSlug, frontmatter, content, sourcePath),
91
+ writeApiPages: (realPages) => this.writeApiPages(realPages),
92
+ updatePagesIndex: (pages) => this.updatePagesIndex(pages),
93
+ updateRootLayout: (pages) => this.updateRootLayout(pages),
94
+ updateSitemap: (pages) => this.updateSitemap(pages),
95
+ updateLlmsFiles: (pages) => this.updateLlmsFiles(pages),
96
+ generateSectionIndexPages: (pages, declaredSlugs) => this.generateSectionIndexPages(pages, declaredSlugs),
97
+ maybeUpdateSections: () => this.maybeUpdateSections(),
98
+ removeOwnedRoute: (slug) => this.removeOwnedRoute(slug),
88
99
  });
89
100
  this.projectConfigRepository = new ProjectConfigRepository(this.rootDir, this.outputDir, this.sourceFs, this.configFiles, this.fontConfigFile, this.analyticsConfigFile);
90
101
  this.publicAssetManager = new PublicAssetManager(this.rootDir, this.outputDir, this.artifacts, this.sourceFs);
@@ -136,7 +147,7 @@ export class MDXToNextJSGenerator {
136
147
  this.sectionsConfig = sections;
137
148
  },
138
149
  getOpenApiRoutes: () => this.artifacts.routesFor("openapi"),
139
- getSuccessfulMdxPages: () => [...this.successfulMdxPages.values()],
150
+ getSuccessfulMdxPages: () => this.mdxReconciliationCoordinator.successfulPages(),
140
151
  resolveSections: () => this.resolveSections(),
141
152
  writeApiPages: (realPages, options) => this.writeApiPages(realPages, options),
142
153
  refreshSiteAggregates: () => this.refreshSiteAggregates(),
@@ -184,7 +195,7 @@ export class MDXToNextJSGenerator {
184
195
  if (this.analyticsConfig) {
185
196
  console.log(chalk.blue(`šŸ“Š Analytics enabled: ${this.analyticsConfig.provider}`));
186
197
  }
187
- this.retainExistingMdxOutput = false;
198
+ this.mdxReconciliationCoordinator.resetForInitialPublication();
188
199
  await this.createNextJSStructure();
189
200
  await this.copyCustomConfigFiles();
190
201
  await this.copyFontConfig();
@@ -406,449 +417,29 @@ export class MDXToNextJSGenerator {
406
417
  async startWatching() {
407
418
  return this.watchCoordinator.startWatching();
408
419
  }
409
- async captureMdxPass(files, seededSources = new Map(), refreshSections = false) {
410
- return this.mdxPassBuilder.capture(files, seededSources, refreshSections);
411
- }
412
420
  async buildRealPagesMeta() {
413
- return (await this.captureMdxPass()).pages;
421
+ return this.mdxReconciliationCoordinator.buildRealPagesMeta();
414
422
  }
415
423
  async buildAllPagesMeta() {
416
- const real = await this.buildRealPagesMeta();
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);
424
+ return this.mdxReconciliationCoordinator.buildAllPagesMeta();
571
425
  }
572
426
  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
- };
427
+ return this.mdxReconciliationCoordinator.readAggregateMdxSource(filePath);
596
428
  }
597
429
  async removeOwnedRoute(slug) {
598
430
  return this.generatedRouteManager.removeOwnedRoute(slug);
599
431
  }
600
- async removeStaleMdxRoutes(realPages, previousRoutes = this.artifacts.routesFor("mdx")) {
601
- return this.generatedRouteManager.removeStaleMdxRoutes(realPages, (slug) => this.removeOwnedRoute(slug), previousRoutes);
602
- }
603
- /**
604
- * Writes the generated page(s) for a single MDX file: the doc page and, for a
605
- * section-index file, the section landing page. Deliberately does NOT run the
606
- * site-wide aggregations (pages index, layout, sitemap, llms, section
607
- * redirects) - the caller batches those so a bulk build runs them once at the
608
- * end instead of once per file (which is what made large builds O(n²)).
609
- */
610
- async writePageForFile(filePath, content) {
611
- const commits = [];
612
- const { data: frontmatter, content: mdxContent } = safeMatter(content, filePath);
613
- const { sectionSlug, pageSlug } = this.determineSectionForFile(filePath, frontmatter);
614
- const fullSlug = getFullSlug(pageSlug, sectionSlug);
615
- const isIndex = filePath === "index.mdx" || filePath === "./index.mdx";
616
- const isSectionIndex = this.sectionsConfig && pageSlug === "" && sectionSlug !== "";
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
- }
642
- }
643
- commits.push(await this.generatePageFromMDX(mdxFile, apiOperation ? { apiOperation } : undefined));
644
- }
645
- if (isSectionIndex) {
646
- commits.push(await this.updateSectionIndex(sectionSlug, frontmatter, mdxContent, filePath));
647
- }
648
- return commits;
649
- }
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
- }
676
- }
677
- }
678
- /**
679
- * Regenerates every file that depends on the full set of pages (pages index,
680
- * root/site layout, sitemap, llms files, section redirects). Parses all MDX
681
- * exactly once and threads the result through each generator, so one refresh
682
- * is a single scan rather than one scan per generator.
683
- */
684
432
  async refreshSiteAggregates(resolvedPages, declaredSlugs) {
685
- const pages = resolvedPages ?? (await this.buildAllPagesMeta());
686
- await this.updatePagesIndex(pages);
687
- await this.updateRootLayout(pages);
688
- await this.updateSitemap(pages);
689
- await this.updateLlmsFiles(pages);
690
- await this.generateSectionIndexPages(pages, declaredSlugs);
433
+ return this.mdxReconciliationCoordinator.refreshSiteAggregates(resolvedPages, declaredSlugs);
691
434
  }
692
435
  async handleFileChange(action, filePath) {
693
- console.log(chalk.cyan(`šŸ“ File ${action}: ${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;
699
- try {
700
- // Validate the complete route set before writing this page so a collision
701
- // cannot transiently overwrite another route during watch mode.
702
- const snapshot = await this.captureMdxPass(undefined, new Map([[normalizedSource, changedSource]]), true);
703
- const realPages = snapshot.pages;
704
- const currentPage = realPages.find((page) => page.path.replace(/\\/g, "/") === normalizedSource);
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
- }
739
- console.log(chalk.green(`āœ… Generated page for: ${filePath}`));
740
- await this.maybeUpdateSections();
741
- }
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
- }
749
- console.error(chalk.red(`āŒ Error processing ${filePath}:`), error);
750
- }
436
+ return this.mdxReconciliationCoordinator.handleFileChange(action, filePath);
751
437
  }
752
438
  async handleFileDelete(filePath) {
753
- console.log(chalk.red(`šŸ—‘ļø File deleted: ${filePath}`));
754
- const previousState = this.captureSuccessfulMdxState();
755
- const pageCommits = [];
756
- try {
757
- const normalizedSource = filePath.replace(/\\/g, "/");
758
- if (filePath === "index.mdx" || filePath === "./index.mdx") {
759
- console.log(chalk.blue("šŸ  Updating homepage - index.mdx deleted"));
760
- }
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
- }
783
- console.log(chalk.green(`āœ… Removed page for: ${filePath}`));
784
- await this.maybeUpdateSections();
785
- }
786
- catch (error) {
787
- console.error(chalk.red(`āŒ Error removing page for ${filePath}:`), error);
788
- }
439
+ return this.mdxReconciliationCoordinator.handleFileDelete(filePath);
789
440
  }
790
441
  async processAllMDXFiles() {
791
- const previousState = this.captureSuccessfulMdxState();
792
- const pageCommits = [];
793
- const files = await this.getAllMDXFiles();
794
- // Fail before writing any page when two source files resolve to one route.
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;
811
- // Write each page first (the only genuinely per-file work), then run the
812
- // site-wide aggregations a single time. Doing the aggregations per file
813
- // re-scanned and re-parsed every MDX file on each iteration, which made a
814
- // full build O(n²); batching them makes it O(n). A single bad file is
815
- // logged and skipped so it never aborts the whole build.
816
- const pagesBySource = new Map(realPages.map((page) => [page.path.replace(/\\/g, "/"), page]));
817
- for (const file of files) {
818
- console.log(chalk.cyan(`šŸ“ Processing: ${file}`));
819
- const normalizedSource = file.replace(/\\/g, "/");
820
- try {
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);
830
- }
831
- catch (error) {
832
- if (!this.retainExistingMdxOutput) {
833
- this.removeSuccessfulMdxPage(normalizedSource);
834
- }
835
- console.error(chalk.red(`āŒ Error processing ${file}:`), error);
836
- }
837
- }
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
- }
442
+ return this.mdxReconciliationCoordinator.processAllMdxFiles();
852
443
  }
853
444
  async getAllMDXFiles() {
854
445
  return this.sourceFs.getAllMdxFiles();
@@ -892,15 +483,8 @@ export default function SectionIndex() {
892
483
  */
893
484
  async writeApiPages(realPages, options = {}) {
894
485
  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));
486
+ const blockedRealPages = this.mdxReconciliationCoordinator.blockOpenApiPages(resolvedRealPages);
487
+ const occupiedMdxSlugs = this.mdxReconciliationCoordinator.occupiedSlugs();
904
488
  return this.apiReferenceGenerator.writePages(this.apiRegistry, this.apiBaseSlug, blockedRealPages, async (mdxFile, options) => {
905
489
  await this.generatePageFromMDX(mdxFile, options);
906
490
  }, () => this.writeApiAllowlist(), (nextRoutes) => this.cleanupStaleApiPages(nextRoutes, occupiedMdxSlugs, options.additionalPreviousRoutes), options.writtenRoutes);
@@ -937,23 +521,7 @@ export default function SectionIndex() {
937
521
  return this.openApiRefreshCoordinator.handleConfigChange();
938
522
  }
939
523
  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();
945
- let indexMDX = null;
946
- for (const file of files) {
947
- if (file === "index.mdx" || file === "./index.mdx") {
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;
952
- const { data: frontmatter, content: mdxContent } = safeMatter(content, file);
953
- indexMDX = this.homepageSource(frontmatter, mdxContent);
954
- break;
955
- }
956
- }
524
+ const indexMDX = await this.mdxReconciliationCoordinator.readHomepageSource(pages);
957
525
  // The homepage supports the same `openapi: <METHOD> <path>` frontmatter as
958
526
  // any other page: look the operation up and embed its playground inline.
959
527
  let apiOperation;