doccupine 0.0.145 → 0.0.147
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.
- package/README.md +11 -2
- package/dist/cli.d.ts +7 -0
- package/dist/cli.js +41 -0
- package/dist/generator/generated-page-publisher.d.ts +21 -0
- package/dist/generator/generated-page-publisher.js +124 -0
- package/dist/generator/generated-route-manager.d.ts +3 -0
- package/dist/generator/generated-route-manager.js +21 -8
- package/dist/generator/mdx-pass-builder.d.ts +31 -0
- package/dist/generator/mdx-pass-builder.js +45 -0
- package/dist/generator/mdx-reconciliation-coordinator.d.ts +83 -0
- package/dist/generator/mdx-reconciliation-coordinator.js +471 -0
- package/dist/generator/openapi-refresh-coordinator.d.ts +42 -0
- package/dist/generator/openapi-refresh-coordinator.js +211 -0
- package/dist/generator/page-renderer.js +18 -13
- package/dist/generator/section-index-generator.d.ts +10 -0
- package/dist/generator/section-index-generator.js +68 -0
- package/dist/generator/secure-source-fs.js +5 -4
- package/dist/generator/site-artifacts.js +2 -2
- package/dist/generator/watch-coordinator.d.ts +8 -0
- package/dist/generator/watch-coordinator.js +131 -53
- package/dist/index.js +8 -2
- package/dist/lib/layout.js +18 -10
- package/dist/lib/openapi-rendering.d.ts +17 -0
- package/dist/lib/openapi-rendering.js +193 -0
- package/dist/lib/openapi.d.ts +1 -7
- package/dist/lib/openapi.js +2 -192
- package/dist/lib/output-safety.js +10 -3
- package/dist/lib/structures.js +4 -0
- package/dist/lib/utils.d.ts +14 -0
- package/dist/lib/utils.js +30 -8
- package/dist/mdx-to-nextjs-generator.d.ts +7 -65
- package/dist/mdx-to-nextjs-generator.js +94 -783
- package/dist/templates/components/Chat.d.ts +1 -1
- package/dist/templates/components/Chat.js +20 -691
- package/dist/templates/components/ChatStyles.d.ts +1 -0
- package/dist/templates/components/ChatStyles.js +695 -0
- package/dist/templates/components/layout/ApiPlayground.d.ts +1 -1
- package/dist/templates/components/layout/ApiPlayground.js +14 -148
- package/dist/templates/mdx/platform/analytics.mdx.d.ts +1 -1
- package/dist/templates/mdx/platform/analytics.mdx.js +13 -0
- package/dist/templates/mdx/platform/fonts-settings.mdx.d.ts +1 -1
- package/dist/templates/mdx/platform/fonts-settings.mdx.js +16 -0
- package/dist/templates/mdx/platform/publishing.mdx.d.ts +1 -1
- package/dist/templates/mdx/platform/publishing.mdx.js +16 -1
- package/dist/templates/mdx/platform/self-updating-docs.mdx.d.ts +1 -1
- package/dist/templates/mdx/platform/self-updating-docs.mdx.js +17 -5
- package/dist/templates/package.js +3 -2
- package/dist/templates/prettierignore.d.ts +1 -1
- package/dist/templates/prettierignore.js +11 -0
- package/dist/templates/utils/apiPlayground.d.ts +1 -0
- package/dist/templates/utils/apiPlayground.js +149 -0
- package/dist/templates/utils/orderNavItems.d.ts +1 -1
- package/dist/templates/utils/orderNavItems.js +1 -1
- package/package.json +1 -1
|
@@ -5,21 +5,23 @@ import chalk from "chalk";
|
|
|
5
5
|
import { rootLayoutTemplate, siteLayoutTemplate } from "./lib/layout.js";
|
|
6
6
|
import { normalizeOpenApiConfig, validateConfig, } from "./lib/config-manager.js";
|
|
7
7
|
import { GeneratedArtifacts, } from "./lib/generated-artifacts.js";
|
|
8
|
-
import { claimOutputDirectory,
|
|
8
|
+
import { claimOutputDirectory, resolveOutputPath, } from "./lib/output-safety.js";
|
|
9
9
|
import { OpenApiRegistry, DEFAULT_API_BASE_SLUG } from "./lib/openapi.js";
|
|
10
|
-
import {
|
|
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
17
|
import { GeneratedRouteManager } from "./generator/generated-route-manager.js";
|
|
18
|
+
import { MdxReconciliationCoordinator } from "./generator/mdx-reconciliation-coordinator.js";
|
|
17
19
|
import { ProjectConfigRepository } from "./generator/project-config-repository.js";
|
|
18
20
|
import { PublicAssetManager } from "./generator/public-asset-manager.js";
|
|
19
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";
|
|
20
24
|
import { addApiReferenceSection, determineSectionRoute, discoverSections, } from "./generator/section-resolver.js";
|
|
21
|
-
import { renderHomepage, renderMdxPage, renderSectionPage, } from "./generator/page-renderer.js";
|
|
22
|
-
import { buildRealPagesMeta as buildRealPageCatalog, mergePages as mergePageCatalog, parseMdxPageMeta, RouteCollisionError, } from "./generator/page-catalog.js";
|
|
23
25
|
import { loadSiteMetadata, loadSiteUrl as loadSiteUrlArtifact, writeLlmsFiles, writeRobots, writeSitemap, } from "./generator/site-artifacts.js";
|
|
24
26
|
export class MDXToNextJSGenerator {
|
|
25
27
|
watchDir;
|
|
@@ -47,16 +49,14 @@ export class MDXToNextJSGenerator {
|
|
|
47
49
|
sourceFs;
|
|
48
50
|
appScaffolder;
|
|
49
51
|
apiReferenceGenerator;
|
|
52
|
+
generatedPagePublisher;
|
|
50
53
|
generatedRouteManager;
|
|
54
|
+
mdxReconciliationCoordinator;
|
|
55
|
+
openApiRefreshCoordinator;
|
|
56
|
+
sectionIndexGenerator;
|
|
51
57
|
projectConfigRepository;
|
|
52
58
|
publicAssetManager;
|
|
53
59
|
watchCoordinator;
|
|
54
|
-
retainExistingMdxOutput = true;
|
|
55
|
-
mdxSnapshotInitialized = false;
|
|
56
|
-
successfulMdxPages = new Map();
|
|
57
|
-
successfulMdxContent = new Map();
|
|
58
|
-
successfulMdxSourcesBySlug = new Map();
|
|
59
|
-
collisionBlockedMdxSources = new Set();
|
|
60
60
|
constructor(watchDir, outputDir, openApiSpecs = [], rootDir = process.cwd()) {
|
|
61
61
|
this.watchDir = path.resolve(watchDir);
|
|
62
62
|
this.outputDir = path.resolve(outputDir);
|
|
@@ -67,6 +67,36 @@ export class MDXToNextJSGenerator {
|
|
|
67
67
|
this.appScaffolder = new AppScaffolder(this.outputDir);
|
|
68
68
|
this.apiReferenceGenerator = new ApiReferenceGenerator(this.outputDir, this.artifacts);
|
|
69
69
|
this.generatedRouteManager = new GeneratedRouteManager(this.outputDir, this.artifacts);
|
|
70
|
+
this.generatedPagePublisher = new GeneratedPagePublisher(this.outputDir, this.generatedRouteManager);
|
|
71
|
+
this.sectionIndexGenerator = new SectionIndexGenerator(this.outputDir, this.generatedRouteManager);
|
|
72
|
+
this.mdxReconciliationCoordinator = new MdxReconciliationCoordinator({
|
|
73
|
+
sourceFs: this.sourceFs,
|
|
74
|
+
generatedRouteManager: this.generatedRouteManager,
|
|
75
|
+
getAllMdxFiles: () => this.getAllMDXFiles(),
|
|
76
|
+
getSections: () => this.sectionsConfig,
|
|
77
|
+
setSections: (sections) => {
|
|
78
|
+
this.sectionsConfig = sections;
|
|
79
|
+
},
|
|
80
|
+
loadSectionsConfig: () => this.loadSectionsConfig(),
|
|
81
|
+
withApiReferenceSection: (sections) => this.withApiReferenceSection(sections),
|
|
82
|
+
determineSectionForFile: (filePath, frontmatter, sections) => this.determineSectionForFile(filePath, frontmatter, sections),
|
|
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),
|
|
99
|
+
});
|
|
70
100
|
this.projectConfigRepository = new ProjectConfigRepository(this.rootDir, this.outputDir, this.sourceFs, this.configFiles, this.fontConfigFile, this.analyticsConfigFile);
|
|
71
101
|
this.publicAssetManager = new PublicAssetManager(this.rootDir, this.outputDir, this.artifacts, this.sourceFs);
|
|
72
102
|
this.watchCoordinator = new WatchCoordinator({
|
|
@@ -97,6 +127,33 @@ export class MDXToNextJSGenerator {
|
|
|
97
127
|
processAllMDXFiles: () => this.reconcileMdxSources(),
|
|
98
128
|
},
|
|
99
129
|
});
|
|
130
|
+
this.openApiRefreshCoordinator = new OpenApiRefreshCoordinator({
|
|
131
|
+
rootDir: this.rootDir,
|
|
132
|
+
watchDir: this.watchDir,
|
|
133
|
+
outputDir: this.outputDir,
|
|
134
|
+
configFile: this.doccupineConfigFile,
|
|
135
|
+
apiBaseSlug: this.apiBaseSlug,
|
|
136
|
+
sourceFs: this.sourceFs,
|
|
137
|
+
getRegistry: () => this.apiRegistry,
|
|
138
|
+
setRegistry: (registry) => {
|
|
139
|
+
this.apiRegistry = registry;
|
|
140
|
+
},
|
|
141
|
+
getSpecs: () => this.openApiSpecs,
|
|
142
|
+
setSpecs: (specs) => {
|
|
143
|
+
this.openApiSpecs = specs;
|
|
144
|
+
},
|
|
145
|
+
getSections: () => this.sectionsConfig,
|
|
146
|
+
setSections: (sections) => {
|
|
147
|
+
this.sectionsConfig = sections;
|
|
148
|
+
},
|
|
149
|
+
getOpenApiRoutes: () => this.artifacts.routesFor("openapi"),
|
|
150
|
+
getSuccessfulMdxPages: () => this.mdxReconciliationCoordinator.successfulPages(),
|
|
151
|
+
resolveSections: () => this.resolveSections(),
|
|
152
|
+
writeApiPages: (realPages, options) => this.writeApiPages(realPages, options),
|
|
153
|
+
refreshSiteAggregates: () => this.refreshSiteAggregates(),
|
|
154
|
+
syncWatcher: () => this.syncOpenApiSpecWatcher(),
|
|
155
|
+
removeOwnedRoute: (slug) => this.removeOwnedRoute(slug),
|
|
156
|
+
});
|
|
100
157
|
}
|
|
101
158
|
outputPath(...segments) {
|
|
102
159
|
return resolveOutputPath(this.outputDir, ...segments);
|
|
@@ -138,7 +195,7 @@ export class MDXToNextJSGenerator {
|
|
|
138
195
|
if (this.analyticsConfig) {
|
|
139
196
|
console.log(chalk.blue(`📊 Analytics enabled: ${this.analyticsConfig.provider}`));
|
|
140
197
|
}
|
|
141
|
-
this.
|
|
198
|
+
this.mdxReconciliationCoordinator.resetForInitialPublication();
|
|
142
199
|
await this.createNextJSStructure();
|
|
143
200
|
await this.copyCustomConfigFiles();
|
|
144
201
|
await this.copyFontConfig();
|
|
@@ -245,8 +302,8 @@ export class MDXToNextJSGenerator {
|
|
|
245
302
|
async reconcileMdxSources() {
|
|
246
303
|
await this.processAllMDXFiles();
|
|
247
304
|
}
|
|
248
|
-
determineSectionForFile(filePath, frontmatter) {
|
|
249
|
-
return determineSectionRoute(filePath, frontmatter,
|
|
305
|
+
determineSectionForFile(filePath, frontmatter, sections = this.sectionsConfig) {
|
|
306
|
+
return determineSectionRoute(filePath, frontmatter, sections);
|
|
250
307
|
}
|
|
251
308
|
async handleConfigFileChange(filePath) {
|
|
252
309
|
const fileName = path.basename(filePath);
|
|
@@ -360,476 +417,29 @@ export class MDXToNextJSGenerator {
|
|
|
360
417
|
async startWatching() {
|
|
361
418
|
return this.watchCoordinator.startWatching();
|
|
362
419
|
}
|
|
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 };
|
|
402
|
-
}
|
|
403
420
|
async buildRealPagesMeta() {
|
|
404
|
-
return
|
|
421
|
+
return this.mdxReconciliationCoordinator.buildRealPagesMeta();
|
|
405
422
|
}
|
|
406
423
|
async buildAllPagesMeta() {
|
|
407
|
-
|
|
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);
|
|
424
|
+
return this.mdxReconciliationCoordinator.buildAllPagesMeta();
|
|
555
425
|
}
|
|
556
426
|
async readAggregateMdxSource(filePath) {
|
|
557
|
-
|
|
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
|
-
};
|
|
427
|
+
return this.mdxReconciliationCoordinator.readAggregateMdxSource(filePath);
|
|
580
428
|
}
|
|
581
429
|
async removeOwnedRoute(slug) {
|
|
582
430
|
return this.generatedRouteManager.removeOwnedRoute(slug);
|
|
583
431
|
}
|
|
584
|
-
async removeStaleMdxRoutes(realPages, previousRoutes = this.artifacts.routesFor("mdx")) {
|
|
585
|
-
return this.generatedRouteManager.removeStaleMdxRoutes(realPages, (slug) => this.removeOwnedRoute(slug), previousRoutes);
|
|
586
|
-
}
|
|
587
|
-
/**
|
|
588
|
-
* Writes the generated page(s) for a single MDX file: the doc page and, for a
|
|
589
|
-
* section-index file, the section landing page. Deliberately does NOT run the
|
|
590
|
-
* site-wide aggregations (pages index, layout, sitemap, llms, section
|
|
591
|
-
* redirects) - the caller batches those so a bulk build runs them once at the
|
|
592
|
-
* end instead of once per file (which is what made large builds O(n²)).
|
|
593
|
-
*/
|
|
594
|
-
async writePageForFile(filePath, content) {
|
|
595
|
-
const commits = [];
|
|
596
|
-
const { data: frontmatter, content: mdxContent } = safeMatter(content, filePath);
|
|
597
|
-
const { sectionSlug, pageSlug } = this.determineSectionForFile(filePath, frontmatter);
|
|
598
|
-
const fullSlug = getFullSlug(pageSlug, sectionSlug);
|
|
599
|
-
const isIndex = filePath === "index.mdx" || filePath === "./index.mdx";
|
|
600
|
-
const isSectionIndex = this.sectionsConfig && pageSlug === "" && sectionSlug !== "";
|
|
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
|
-
}
|
|
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));
|
|
631
|
-
}
|
|
632
|
-
return commits;
|
|
633
|
-
}
|
|
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
|
-
}
|
|
660
|
-
}
|
|
661
|
-
}
|
|
662
|
-
/**
|
|
663
|
-
* Regenerates every file that depends on the full set of pages (pages index,
|
|
664
|
-
* root/site layout, sitemap, llms files, section redirects). Parses all MDX
|
|
665
|
-
* exactly once and threads the result through each generator, so one refresh
|
|
666
|
-
* is a single scan rather than one scan per generator.
|
|
667
|
-
*/
|
|
668
432
|
async refreshSiteAggregates(resolvedPages, declaredSlugs) {
|
|
669
|
-
|
|
670
|
-
await this.updatePagesIndex();
|
|
671
|
-
await this.updateRootLayout(pages);
|
|
672
|
-
await this.updateSitemap(pages);
|
|
673
|
-
await this.updateLlmsFiles(pages);
|
|
674
|
-
await this.generateSectionIndexPages(pages, declaredSlugs);
|
|
433
|
+
return this.mdxReconciliationCoordinator.refreshSiteAggregates(resolvedPages, declaredSlugs);
|
|
675
434
|
}
|
|
676
435
|
async handleFileChange(action, filePath) {
|
|
677
|
-
|
|
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;
|
|
683
|
-
try {
|
|
684
|
-
// Validate the complete route set before writing this page so a collision
|
|
685
|
-
// cannot transiently overwrite another route during watch mode.
|
|
686
|
-
const snapshot = await this.captureMdxPass(undefined, new Map([[normalizedSource, changedSource]]), true);
|
|
687
|
-
const realPages = snapshot.pages;
|
|
688
|
-
const currentPage = realPages.find((page) => page.path.replace(/\\/g, "/") === normalizedSource);
|
|
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
|
-
}
|
|
722
|
-
console.log(chalk.green(`✅ Generated page for: ${filePath}`));
|
|
723
|
-
await this.maybeUpdateSections();
|
|
724
|
-
}
|
|
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
|
-
}
|
|
732
|
-
console.error(chalk.red(`❌ Error processing ${filePath}:`), error);
|
|
733
|
-
}
|
|
436
|
+
return this.mdxReconciliationCoordinator.handleFileChange(action, filePath);
|
|
734
437
|
}
|
|
735
438
|
async handleFileDelete(filePath) {
|
|
736
|
-
|
|
737
|
-
const previousState = this.captureSuccessfulMdxState();
|
|
738
|
-
const pageCommits = [];
|
|
739
|
-
try {
|
|
740
|
-
const normalizedSource = filePath.replace(/\\/g, "/");
|
|
741
|
-
this.removeSuccessfulMdxPage(normalizedSource);
|
|
742
|
-
this.collisionBlockedMdxSources.delete(normalizedSource);
|
|
743
|
-
if (filePath === "index.mdx" || filePath === "./index.mdx") {
|
|
744
|
-
console.log(chalk.blue("🏠 Updating homepage - index.mdx deleted"));
|
|
745
|
-
}
|
|
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
|
-
}
|
|
765
|
-
console.log(chalk.green(`✅ Removed page for: ${filePath}`));
|
|
766
|
-
await this.maybeUpdateSections();
|
|
767
|
-
}
|
|
768
|
-
catch (error) {
|
|
769
|
-
console.error(chalk.red(`❌ Error removing page for ${filePath}:`), error);
|
|
770
|
-
}
|
|
439
|
+
return this.mdxReconciliationCoordinator.handleFileDelete(filePath);
|
|
771
440
|
}
|
|
772
441
|
async processAllMDXFiles() {
|
|
773
|
-
|
|
774
|
-
const pageCommits = [];
|
|
775
|
-
const files = await this.getAllMDXFiles();
|
|
776
|
-
// Fail before writing any page when two source files resolve to one route.
|
|
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;
|
|
792
|
-
// Write each page first (the only genuinely per-file work), then run the
|
|
793
|
-
// site-wide aggregations a single time. Doing the aggregations per file
|
|
794
|
-
// re-scanned and re-parsed every MDX file on each iteration, which made a
|
|
795
|
-
// full build O(n²); batching them makes it O(n). A single bad file is
|
|
796
|
-
// logged and skipped so it never aborts the whole build.
|
|
797
|
-
const pagesBySource = new Map(realPages.map((page) => [page.path.replace(/\\/g, "/"), page]));
|
|
798
|
-
for (const file of files) {
|
|
799
|
-
console.log(chalk.cyan(`📝 Processing: ${file}`));
|
|
800
|
-
const normalizedSource = file.replace(/\\/g, "/");
|
|
801
|
-
try {
|
|
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);
|
|
811
|
-
}
|
|
812
|
-
catch (error) {
|
|
813
|
-
if (!this.retainExistingMdxOutput) {
|
|
814
|
-
this.removeSuccessfulMdxPage(normalizedSource);
|
|
815
|
-
}
|
|
816
|
-
console.error(chalk.red(`❌ Error processing ${file}:`), error);
|
|
817
|
-
}
|
|
818
|
-
}
|
|
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
|
-
}
|
|
442
|
+
return this.mdxReconciliationCoordinator.processAllMdxFiles();
|
|
833
443
|
}
|
|
834
444
|
async getAllMDXFiles() {
|
|
835
445
|
return this.sourceFs.getAllMdxFiles();
|
|
@@ -844,167 +454,25 @@ export class MDXToNextJSGenerator {
|
|
|
844
454
|
return siteLayoutTemplate(resolvedPages, this.sectionsConfig);
|
|
845
455
|
}
|
|
846
456
|
async generateSectionIndexPages(pages, declaredSlugs) {
|
|
847
|
-
const nextSlugs = new Set();
|
|
848
457
|
const resolvedPages = pages ?? (await this.buildAllPagesMeta());
|
|
849
|
-
|
|
850
|
-
|
|
851
|
-
|
|
852
|
-
|
|
853
|
-
if (this.sectionsConfig && this.sectionsConfig.length > 0) {
|
|
854
|
-
for (const section of this.sectionsConfig) {
|
|
855
|
-
if (section.slug === "")
|
|
856
|
-
continue;
|
|
857
|
-
// Check if a page already exists at the section root
|
|
858
|
-
const hasIndex = resolvedDeclaredSlugs.has(section.slug);
|
|
859
|
-
if (hasIndex)
|
|
860
|
-
continue;
|
|
861
|
-
// Find the first page in this section
|
|
862
|
-
const sectionPages = resolvedPages
|
|
863
|
-
.filter((p) => p.section === section.slug)
|
|
864
|
-
.sort((a, b) => {
|
|
865
|
-
if (a.categoryOrder !== b.categoryOrder)
|
|
866
|
-
return a.categoryOrder - b.categoryOrder;
|
|
867
|
-
return a.order - b.order;
|
|
868
|
-
});
|
|
869
|
-
if (sectionPages.length === 0)
|
|
870
|
-
continue;
|
|
871
|
-
const firstPage = sectionPages[0];
|
|
872
|
-
const redirectContent = `import { redirect } from "next/navigation";
|
|
458
|
+
return this.sectionIndexGenerator.generate(resolvedPages, this.sectionsConfig, declaredSlugs, (slug, target) => this.writeSectionIndexRedirect(slug, target));
|
|
459
|
+
}
|
|
460
|
+
async writeSectionIndexRedirect(slug, target) {
|
|
461
|
+
const content = `import { redirect } from "next/navigation";
|
|
873
462
|
|
|
874
463
|
export default function SectionIndex() {
|
|
875
|
-
redirect("/${
|
|
464
|
+
redirect("/${target}");
|
|
876
465
|
}
|
|
877
466
|
`;
|
|
878
|
-
|
|
879
|
-
|
|
880
|
-
await writeFileAtomic(pagePath, redirectContent);
|
|
881
|
-
nextSlugs.add(section.slug);
|
|
882
|
-
console.log(chalk.blue(`🔀 Generated section index redirect: /${section.slug} -> /${firstPage.slug}`));
|
|
883
|
-
}
|
|
884
|
-
}
|
|
885
|
-
await this.cleanupStaleSectionIndexPages(nextSlugs, occupiedSlugs);
|
|
886
|
-
}
|
|
887
|
-
/**
|
|
888
|
-
* Removes section index redirects written earlier in this session whose
|
|
889
|
-
* section has since disappeared (e.g. the API Reference section after the
|
|
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.
|
|
893
|
-
*/
|
|
894
|
-
async cleanupStaleSectionIndexPages(nextSlugs, occupiedSlugs) {
|
|
895
|
-
return this.generatedRouteManager.cleanupStaleSectionIndexPages(nextSlugs, occupiedSlugs, (dir, stopDir) => this.removeEmptyDirsUpTo(dir, stopDir));
|
|
896
|
-
}
|
|
897
|
-
/** Best-effort removal of now-empty directories up to (not incl.) stopDir. */
|
|
898
|
-
async removeEmptyDirsUpTo(dir, stopDir) {
|
|
899
|
-
return this.generatedRouteManager.removeEmptyDirsUpTo(dir, stopDir);
|
|
900
|
-
}
|
|
901
|
-
generatedFileSegments(filePath) {
|
|
902
|
-
return path
|
|
903
|
-
.relative(fs.realpathSync(this.outputDir), filePath)
|
|
904
|
-
.split(path.sep)
|
|
905
|
-
.filter(Boolean);
|
|
906
|
-
}
|
|
907
|
-
async readGeneratedFile(filePath) {
|
|
908
|
-
return readOutputFileIfPresent(this.outputDir, ...this.generatedFileSegments(filePath));
|
|
909
|
-
}
|
|
910
|
-
async restoreGeneratedFile(filePath, content) {
|
|
911
|
-
const target = this.outputPath(...this.generatedFileSegments(filePath));
|
|
912
|
-
if (content === null) {
|
|
913
|
-
await fs.remove(target);
|
|
914
|
-
}
|
|
915
|
-
else {
|
|
916
|
-
await writeFileAtomic(target, content);
|
|
917
|
-
}
|
|
918
|
-
}
|
|
919
|
-
async commitRenderedPage(pagePath, rendered) {
|
|
920
|
-
if (rendered.rssRoute.action === "preserve") {
|
|
921
|
-
const previousPage = await this.readGeneratedFile(pagePath);
|
|
922
|
-
await writeFileAtomic(pagePath, rendered.pageContent);
|
|
923
|
-
return {
|
|
924
|
-
rollback: () => this.restoreGeneratedFile(pagePath, previousPage),
|
|
925
|
-
};
|
|
926
|
-
}
|
|
927
|
-
const rssDir = resolveOutputPath(path.dirname(pagePath), "rss.xml");
|
|
928
|
-
const rssPath = resolveOutputPath(path.dirname(pagePath), "rss.xml", "route.ts");
|
|
929
|
-
const [previousPage, previousRss] = await Promise.all([
|
|
930
|
-
this.readGeneratedFile(pagePath),
|
|
931
|
-
this.readGeneratedFile(rssPath),
|
|
932
|
-
]);
|
|
933
|
-
let pageChanged = false;
|
|
934
|
-
let rssChanged = false;
|
|
935
|
-
try {
|
|
936
|
-
if (rendered.rssRoute.action === "write") {
|
|
937
|
-
await writeFileAtomic(rssPath, rendered.rssRoute.content);
|
|
938
|
-
rssChanged = true;
|
|
939
|
-
await writeFileAtomic(pagePath, rendered.pageContent);
|
|
940
|
-
pageChanged = true;
|
|
941
|
-
}
|
|
942
|
-
else {
|
|
943
|
-
await writeFileAtomic(pagePath, rendered.pageContent);
|
|
944
|
-
pageChanged = true;
|
|
945
|
-
await fs.remove(rssPath);
|
|
946
|
-
rssChanged = true;
|
|
947
|
-
await this.removeEmptyDirsUpTo(rssDir, path.dirname(pagePath));
|
|
948
|
-
}
|
|
949
|
-
}
|
|
950
|
-
catch (error) {
|
|
951
|
-
const rollbackErrors = [];
|
|
952
|
-
if (rssChanged) {
|
|
953
|
-
try {
|
|
954
|
-
await this.restoreGeneratedFile(rssPath, previousRss);
|
|
955
|
-
}
|
|
956
|
-
catch (rollbackError) {
|
|
957
|
-
rollbackErrors.push(rollbackError);
|
|
958
|
-
}
|
|
959
|
-
}
|
|
960
|
-
if (pageChanged) {
|
|
961
|
-
try {
|
|
962
|
-
await this.restoreGeneratedFile(pagePath, previousPage);
|
|
963
|
-
}
|
|
964
|
-
catch (rollbackError) {
|
|
965
|
-
rollbackErrors.push(rollbackError);
|
|
966
|
-
}
|
|
967
|
-
}
|
|
968
|
-
if (rollbackErrors.length > 0) {
|
|
969
|
-
throw new AggregateError([error, ...rollbackErrors], `Unable to publish or restore generated page ${pagePath}`);
|
|
970
|
-
}
|
|
971
|
-
throw error;
|
|
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
|
-
};
|
|
467
|
+
await writeFileAtomic(this.outputPath("app", "(site)", slug, "page.tsx"), content);
|
|
468
|
+
console.log(chalk.blue(`🔀 Generated section index redirect: /${slug} -> /${target}`));
|
|
993
469
|
}
|
|
994
470
|
async generatePageFromMDX(mdxFile, options) {
|
|
995
|
-
|
|
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);
|
|
471
|
+
return this.generatedPagePublisher.generatePageFromMdx(mdxFile, options);
|
|
999
472
|
}
|
|
1000
473
|
/** Parses the configured OpenAPI spec(s) into the shared registry. */
|
|
1001
474
|
async loadOpenApiRegistry() {
|
|
1002
|
-
|
|
1003
|
-
return;
|
|
1004
|
-
this.apiRegistry = (await this.loadStableOpenApiRegistry(this.openApiSpecs)).registry;
|
|
1005
|
-
if (!this.apiRegistry.isEmpty) {
|
|
1006
|
-
console.log(chalk.blue(`📘 Loaded ${this.apiRegistry.all.length} API endpoint(s) from ${this.openApiSpecs.length} spec(s)`));
|
|
1007
|
-
}
|
|
475
|
+
return this.openApiRefreshCoordinator.loadInitialRegistry();
|
|
1008
476
|
}
|
|
1009
477
|
/**
|
|
1010
478
|
* Generates one page per OpenAPI operation, (re)writes the request-execution
|
|
@@ -1015,15 +483,8 @@ export default function SectionIndex() {
|
|
|
1015
483
|
*/
|
|
1016
484
|
async writeApiPages(realPages, options = {}) {
|
|
1017
485
|
const resolvedRealPages = realPages ?? (await this.buildRealPagesMeta());
|
|
1018
|
-
const blockedRealPages =
|
|
1019
|
-
const
|
|
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));
|
|
486
|
+
const blockedRealPages = this.mdxReconciliationCoordinator.blockOpenApiPages(resolvedRealPages);
|
|
487
|
+
const occupiedMdxSlugs = this.mdxReconciliationCoordinator.occupiedSlugs();
|
|
1027
488
|
return this.apiReferenceGenerator.writePages(this.apiRegistry, this.apiBaseSlug, blockedRealPages, async (mdxFile, options) => {
|
|
1028
489
|
await this.generatePageFromMDX(mdxFile, options);
|
|
1029
490
|
}, () => this.writeApiAllowlist(), (nextRoutes) => this.cleanupStaleApiPages(nextRoutes, occupiedMdxSlugs, options.additionalPreviousRoutes), options.writtenRoutes);
|
|
@@ -1044,111 +505,9 @@ export default function SectionIndex() {
|
|
|
1044
505
|
async syncOpenApiSpecWatcher() {
|
|
1045
506
|
return this.watchCoordinator.syncOpenApiSpecWatcher(this.openApiSpecs, this.apiRegistry.sourceFiles);
|
|
1046
507
|
}
|
|
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");
|
|
1078
|
-
}
|
|
1079
|
-
/**
|
|
1080
|
-
* Reparses the spec(s) and rewrites everything derived from them: the
|
|
1081
|
-
* endpoint pages and allowlist, the sections (the "API Reference" section
|
|
1082
|
-
* appears and disappears with the registry), and the site aggregates.
|
|
1083
|
-
*/
|
|
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
|
-
}
|
|
1141
|
-
}
|
|
1142
508
|
/** Reparses the spec(s) and regenerates the API reference on a watch event. */
|
|
1143
509
|
async handleOpenApiChange() {
|
|
1144
|
-
|
|
1145
|
-
try {
|
|
1146
|
-
await this.applyStableOpenApiRefresh(this.openApiSpecs, true);
|
|
1147
|
-
console.log(chalk.green("✅ API reference updated"));
|
|
1148
|
-
}
|
|
1149
|
-
catch (error) {
|
|
1150
|
-
console.error(chalk.red("❌ Error updating API reference:"), error);
|
|
1151
|
-
}
|
|
510
|
+
return this.openApiRefreshCoordinator.handleOpenApiChange();
|
|
1152
511
|
}
|
|
1153
512
|
/**
|
|
1154
513
|
* Applies `openapi` edits in doccupine.json without a restart: reloads the
|
|
@@ -1159,52 +518,10 @@ export default function SectionIndex() {
|
|
|
1159
518
|
* half-written editor save) keeps the current configuration.
|
|
1160
519
|
*/
|
|
1161
520
|
async handleDoccupineConfigChange() {
|
|
1162
|
-
|
|
1163
|
-
let config;
|
|
1164
|
-
try {
|
|
1165
|
-
const { data } = await this.sourceFs.readProjectSourceFile(configPath, "Doccupine configuration source");
|
|
1166
|
-
config = validateConfig(JSON.parse(data.toString("utf8")), this.rootDir);
|
|
1167
|
-
}
|
|
1168
|
-
catch (error) {
|
|
1169
|
-
console.warn(chalk.yellow("⚠️ doccupine.json is missing or invalid - keeping the current configuration"), error instanceof Error ? error.message : error);
|
|
1170
|
-
return;
|
|
1171
|
-
}
|
|
1172
|
-
if ((config.watchDir &&
|
|
1173
|
-
path.resolve(this.rootDir, config.watchDir) !== this.watchDir) ||
|
|
1174
|
-
(config.outputDir &&
|
|
1175
|
-
path.resolve(this.rootDir, config.outputDir) !== this.outputDir)) {
|
|
1176
|
-
console.log(chalk.yellow("⚠️ watchDir/outputDir changes in doccupine.json need a restart to apply"));
|
|
1177
|
-
}
|
|
1178
|
-
const nextSpecs = normalizeOpenApiConfig(config.openapi);
|
|
1179
|
-
if (JSON.stringify(nextSpecs) === JSON.stringify(this.openApiSpecs)) {
|
|
1180
|
-
return;
|
|
1181
|
-
}
|
|
1182
|
-
console.log(chalk.cyan("📘 OpenAPI configuration changed - updating API reference"));
|
|
1183
|
-
try {
|
|
1184
|
-
// Validate the complete candidate before changing the active spec list or
|
|
1185
|
-
// its watcher. A half-written/invalid replacement keeps both the current
|
|
1186
|
-
// generated reference and its live watcher intact.
|
|
1187
|
-
await this.applyStableOpenApiRefresh(nextSpecs, true);
|
|
1188
|
-
console.log(chalk.green("✅ API reference updated"));
|
|
1189
|
-
}
|
|
1190
|
-
catch (error) {
|
|
1191
|
-
console.error(chalk.red("❌ Error updating API reference:"), error);
|
|
1192
|
-
}
|
|
521
|
+
return this.openApiRefreshCoordinator.handleConfigChange();
|
|
1193
522
|
}
|
|
1194
|
-
async updatePagesIndex() {
|
|
1195
|
-
const
|
|
1196
|
-
let indexMDX = null;
|
|
1197
|
-
for (const file of files) {
|
|
1198
|
-
if (file === "index.mdx" || file === "./index.mdx") {
|
|
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;
|
|
1203
|
-
const { data: frontmatter, content: mdxContent } = safeMatter(content, file);
|
|
1204
|
-
indexMDX = this.homepageSource(frontmatter, mdxContent);
|
|
1205
|
-
break;
|
|
1206
|
-
}
|
|
1207
|
-
}
|
|
523
|
+
async updatePagesIndex(pages) {
|
|
524
|
+
const indexMDX = await this.mdxReconciliationCoordinator.readHomepageSource(pages);
|
|
1208
525
|
// The homepage supports the same `openapi: <METHOD> <path>` frontmatter as
|
|
1209
526
|
// any other page: look the operation up and embed its playground inline.
|
|
1210
527
|
let apiOperation;
|
|
@@ -1214,16 +531,10 @@ export default function SectionIndex() {
|
|
|
1214
531
|
console.error(chalk.red(`❌ openapi frontmatter "${indexMDX.openapi}" in index.mdx not found in any spec`));
|
|
1215
532
|
}
|
|
1216
533
|
}
|
|
1217
|
-
|
|
1218
|
-
const homePath = this.outputPath("app", "(site)", "page.tsx");
|
|
1219
|
-
await fs.ensureDir(path.dirname(homePath));
|
|
1220
|
-
await this.commitRenderedPage(homePath, rendered);
|
|
534
|
+
await this.generatedPagePublisher.updateHomepage(indexMDX, apiOperation);
|
|
1221
535
|
}
|
|
1222
536
|
async updateSectionIndex(sectionSlug, frontmatter, mdxContent, sourcePath) {
|
|
1223
|
-
|
|
1224
|
-
const pagePath = resolveOutputPath(this.outputDir, "app", "(site)", sectionSlug, "page.tsx");
|
|
1225
|
-
await fs.ensureDir(path.dirname(pagePath));
|
|
1226
|
-
return this.commitRenderedPage(pagePath, rendered);
|
|
537
|
+
return this.generatedPagePublisher.updateSectionIndex(sectionSlug, frontmatter, mdxContent, sourcePath);
|
|
1227
538
|
}
|
|
1228
539
|
async updateRootLayout(pages) {
|
|
1229
540
|
await writeFileAtomic(this.outputPath("app", "layout.tsx"), await this.generateRootLayout());
|