doccupine 0.0.146 → 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.
Files changed (40) 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 +4 -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 +20 -691
  23. package/dist/templates/components/ChatStyles.d.ts +1 -0
  24. package/dist/templates/components/ChatStyles.js +695 -0
  25. package/dist/templates/components/layout/ApiPlayground.d.ts +1 -1
  26. package/dist/templates/components/layout/ApiPlayground.js +14 -148
  27. package/dist/templates/mdx/platform/analytics.mdx.d.ts +1 -1
  28. package/dist/templates/mdx/platform/analytics.mdx.js +13 -0
  29. package/dist/templates/mdx/platform/fonts-settings.mdx.d.ts +1 -1
  30. package/dist/templates/mdx/platform/fonts-settings.mdx.js +16 -0
  31. package/dist/templates/mdx/platform/publishing.mdx.d.ts +1 -1
  32. package/dist/templates/mdx/platform/publishing.mdx.js +16 -1
  33. package/dist/templates/mdx/platform/self-updating-docs.mdx.d.ts +1 -1
  34. package/dist/templates/mdx/platform/self-updating-docs.mdx.js +17 -5
  35. package/dist/templates/package.js +3 -2
  36. package/dist/templates/prettierignore.d.ts +1 -1
  37. package/dist/templates/prettierignore.js +11 -0
  38. package/dist/templates/utils/apiPlayground.d.ts +1 -0
  39. package/dist/templates/utils/apiPlayground.js +149 -0
  40. package/package.json +1 -1
package/README.md CHANGED
@@ -1,6 +1,15 @@
1
- # Doccupine
1
+ <p align="center">
2
+ <a href="https://docs.doccupine.com/"><picture><source media="(prefers-color-scheme: dark)" srcset="https://shieldcn.dev/header/graph.svg?subtitle=Documentation+made+simple.+Open+source.+AI-ready.&amp;logo=https%3A%2F%2Ffiles.riangle.com%2Fdoccupine%2Fpictogram.png&amp;size=wide&amp;mode=dark&amp;font=geist&amp;image=http%3A%2F%2Ffiles.riangle.com%2Fdoccupine%2Fcover.png&amp;overlay=0" /><img alt="Doccupine" src="https://shieldcn.dev/header/graph.svg?subtitle=Documentation+made+simple.+Open+source.+AI-ready.&amp;logo=https%3A%2F%2Ffiles.riangle.com%2Fdoccupine%2Fpictogram.png&amp;size=wide&amp;mode=light&amp;font=geist&amp;image=http%3A%2F%2Ffiles.riangle.com%2Fdoccupine%2Fcover.png&amp;overlay=0" /></picture></a>
3
+ </p>
4
+
5
+ <p align="center">
6
+ <a href="https://www.npmjs.com/package/doccupine"><picture><source media="(prefers-color-scheme: dark)" srcset="https://shieldcn.dev/npm/doccupine.svg" /><img alt="badge" src="https://shieldcn.dev/npm/doccupine.svg?mode=light" /></picture></a>
7
+ <a href="https://github.com/doccupine/cli"><picture><source media="(prefers-color-scheme: dark)" srcset="https://shieldcn.dev/github/doccupine/cli/stars.svg" /><img alt="badge" src="https://shieldcn.dev/github/doccupine/cli/stars.svg?mode=light" /></picture></a>
8
+ <a href="https://docs.doccupine.com/"><picture><source media="(prefers-color-scheme: dark)" srcset="https://shieldcn.dev/badge/Docs.svg" /><img alt="badge" src="https://shieldcn.dev/badge/Docs.svg?mode=light" /></picture></a>
9
+ <a href="https://doccupine.com/"><picture><source media="(prefers-color-scheme: dark)" srcset="https://shieldcn.dev/badge/Website.svg" /><img alt="badge" src="https://shieldcn.dev/badge/Website.svg?mode=light" /></picture></a>
10
+ </p>
2
11
 
3
- [![npm version](https://img.shields.io/npm/v/doccupine.svg)](https://www.npmjs.com/package/doccupine)
12
+ # Doccupine
4
13
 
5
14
  [Doccupine](https://doccupine.com) is an open-source CLI that turns a directory of MDX files into a full-featured Next.js documentation website. Write your docs in Markdown, and Doccupine watches for changes, generates pages, and starts a live dev server automatically.
6
15
 
package/dist/cli.d.ts CHANGED
@@ -3,5 +3,12 @@ import type { EventEmitter } from "events";
3
3
  export type WatchSignal = "SIGINT" | "SIGTERM";
4
4
  type WatchChildProcess = EventEmitter & Pick<ChildProcess, "exitCode" | "signalCode" | "kill" | "pid">;
5
5
  export declare function superviseWatchLifecycle(devServer: WatchChildProcess, stopGenerator: () => Promise<void>, signalSource?: EventEmitter): Promise<WatchSignal>;
6
+ /**
7
+ * Prints a command failure the way a CLI should: the actionable message first,
8
+ * nested causes indented under it, and the stack only when `--verbose` asked
9
+ * for it. Errors raised here are written for the person running the command,
10
+ * so a bare stack trace would bury the part that tells them what to do.
11
+ */
12
+ export declare function reportCliError(error: unknown, argv?: readonly string[]): void;
6
13
  export declare function runCli(argv?: string[]): Promise<void>;
7
14
  export {};
package/dist/cli.js CHANGED
@@ -122,6 +122,43 @@ export function superviseWatchLifecycle(devServer, stopGenerator, signalSource =
122
122
  signalSource.once("SIGTERM", onSigterm);
123
123
  });
124
124
  }
125
+ function errorMessages(error, seen = new Set()) {
126
+ if (error === null || error === undefined || seen.has(error))
127
+ return [];
128
+ seen.add(error);
129
+ if (error instanceof AggregateError) {
130
+ // The aggregate's own message is a summary ("Unable to shut down
131
+ // cleanly"); the causes underneath it are what the user can act on.
132
+ return [
133
+ error.message,
134
+ ...error.errors.flatMap((nested) => errorMessages(nested, seen)),
135
+ ].filter(Boolean);
136
+ }
137
+ if (error instanceof Error) {
138
+ return [error.message, ...errorMessages(error.cause, seen)].filter(Boolean);
139
+ }
140
+ return [String(error)].filter(Boolean);
141
+ }
142
+ /**
143
+ * Prints a command failure the way a CLI should: the actionable message first,
144
+ * nested causes indented under it, and the stack only when `--verbose` asked
145
+ * for it. Errors raised here are written for the person running the command,
146
+ * so a bare stack trace would bury the part that tells them what to do.
147
+ */
148
+ export function reportCliError(error, argv = process.argv) {
149
+ const [message, ...causes] = errorMessages(error);
150
+ console.error(chalk.red(`❌ ${message ?? "Unknown error"}`));
151
+ for (const cause of causes) {
152
+ console.error(chalk.red(` ↳ ${cause}`));
153
+ }
154
+ if (argv.includes("--verbose")) {
155
+ if (error instanceof Error && error.stack)
156
+ console.error(error.stack);
157
+ }
158
+ else {
159
+ console.error(chalk.gray(" Re-run with --verbose for the full stack."));
160
+ }
161
+ }
125
162
  async function dependencyFingerprint(outputDir, packageManager) {
126
163
  const packageJson = await fs.readFile(path.join(outputDir, "package.json"), "utf8");
127
164
  return createHash("sha256")
@@ -259,6 +296,9 @@ export async function runCli(argv) {
259
296
  .alias("generate")
260
297
  .description("Generate the Next.js app once without running its build")
261
298
  .option("--reset", "Reset configuration and prompt for new directories")
299
+ // Accepted so the failure hint printed by reportCliError is actionable
300
+ // here too, not only under `watch`.
301
+ .option("--verbose", "Show verbose output")
262
302
  .action(async (options) => {
263
303
  const configManager = new ConfigManager();
264
304
  const config = await configManager.getConfig({
@@ -273,6 +313,7 @@ export async function runCli(argv) {
273
313
  .description("Show or reset configuration")
274
314
  .option("--show", "Show current configuration")
275
315
  .option("--reset", "Reset configuration")
316
+ .option("--verbose", "Show verbose output")
276
317
  .action(async (options) => {
277
318
  const configManager = new ConfigManager();
278
319
  if (options.show) {
@@ -0,0 +1,83 @@
1
+ import type { RouteArtifact } from "../lib/generated-artifacts.js";
2
+ import type { OperationDescriptor } from "../lib/openapi-types.js";
3
+ import type { MDXFile, PageMeta, SectionConfig } from "../lib/types.js";
4
+ import type { GeneratedPageCommit } from "./generated-page-publisher.js";
5
+ import { GeneratedRouteManager } from "./generated-route-manager.js";
6
+ import { type HomepageSource } from "./page-renderer.js";
7
+ import { SecureSourceFs } from "./secure-source-fs.js";
8
+ interface MdxReconciliationCoordinatorOptions {
9
+ sourceFs: SecureSourceFs;
10
+ generatedRouteManager: GeneratedRouteManager;
11
+ getAllMdxFiles(): Promise<string[]>;
12
+ getSections(): SectionConfig[] | null;
13
+ setSections(sections: SectionConfig[] | null): void;
14
+ loadSectionsConfig(): Promise<SectionConfig[] | null>;
15
+ withApiReferenceSection(sections: SectionConfig[] | null): SectionConfig[] | null;
16
+ determineSectionForFile(filePath: string, frontmatter: Record<string, any>, sections?: SectionConfig[] | null): {
17
+ sectionSlug: string;
18
+ pageSlug: string;
19
+ };
20
+ lookupOpenApi(reference: string): OperationDescriptor | undefined;
21
+ isOpenApiRegistryEmpty(): boolean;
22
+ syntheticOpenApiPages(): PageMeta[];
23
+ getMdxRoutes(): RouteArtifact[];
24
+ getOpenApiRoutes(): RouteArtifact[];
25
+ replaceMdxRoutes(routes: Iterable<{
26
+ source: string;
27
+ slug: string;
28
+ }>): Promise<void>;
29
+ generatePageFromMdx(mdxFile: MDXFile, options?: {
30
+ apiOperation?: OperationDescriptor;
31
+ }): Promise<GeneratedPageCommit>;
32
+ updateSectionIndex(sectionSlug: string, frontmatter: Record<string, any>, mdxContent: string, sourcePath?: string): Promise<GeneratedPageCommit>;
33
+ writeApiPages(realPages?: PageMeta[]): Promise<Map<string, string>>;
34
+ updatePagesIndex(pages?: readonly PageMeta[]): Promise<void>;
35
+ updateRootLayout(pages?: PageMeta[]): Promise<void>;
36
+ updateSitemap(pages?: PageMeta[]): Promise<void>;
37
+ updateLlmsFiles(pages?: PageMeta[]): Promise<void>;
38
+ generateSectionIndexPages(pages?: PageMeta[], declaredSlugs?: Set<string>): Promise<void>;
39
+ maybeUpdateSections(): Promise<void>;
40
+ removeOwnedRoute(slug: string): Promise<void>;
41
+ }
42
+ export declare class MdxReconciliationCoordinator {
43
+ private readonly options;
44
+ private readonly mdxPassBuilder;
45
+ private retainExistingMdxOutput;
46
+ private mdxSnapshotInitialized;
47
+ private successfulMdxPages;
48
+ private successfulMdxContent;
49
+ private successfulMdxSourcesBySlug;
50
+ private collisionBlockedMdxSources;
51
+ constructor(options: MdxReconciliationCoordinatorOptions);
52
+ resetForInitialPublication(): void;
53
+ successfulPages(): PageMeta[];
54
+ occupiedSlugs(): Set<string>;
55
+ blockOpenApiPages(realPages: PageMeta[]): PageMeta[];
56
+ private captureMdxPass;
57
+ buildRealPagesMeta(): Promise<PageMeta[]>;
58
+ buildAllPagesMeta(): Promise<PageMeta[]>;
59
+ private mergeAllPagesMeta;
60
+ private successfulPagesInSourceOrder;
61
+ private recordSuccessfulMdxPage;
62
+ private removeSuccessfulMdxPage;
63
+ private captureSuccessfulMdxState;
64
+ private restoreSuccessfulMdxState;
65
+ private rollbackPageCommits;
66
+ private rollbackFailedMdxCommit;
67
+ private rollbackCommittedMdxChange;
68
+ private dropMissingMdxSnapshots;
69
+ private commitMdxSnapshot;
70
+ private refreshMdxDerivedOutput;
71
+ readAggregateMdxSource(filePath: string): Promise<{
72
+ content: string;
73
+ }>;
74
+ private homepageSource;
75
+ readHomepageSource(pages?: readonly PageMeta[]): Promise<HomepageSource | null>;
76
+ private writePageForFile;
77
+ private retryMdxPages;
78
+ refreshSiteAggregates(resolvedPages?: PageMeta[], declaredSlugs?: Set<string>): Promise<void>;
79
+ handleFileChange(action: string, filePath: string): Promise<void>;
80
+ handleFileDelete(filePath: string): Promise<void>;
81
+ processAllMdxFiles(): Promise<void>;
82
+ }
83
+ export {};
@@ -0,0 +1,471 @@
1
+ import chalk from "chalk";
2
+ import { getFullSlug, safeMatter } from "../lib/utils.js";
3
+ import { MdxPassBuilder, } from "./mdx-pass-builder.js";
4
+ import { mergePages, RouteCollisionError } from "./page-catalog.js";
5
+ export class MdxReconciliationCoordinator {
6
+ options;
7
+ mdxPassBuilder;
8
+ retainExistingMdxOutput = true;
9
+ mdxSnapshotInitialized = false;
10
+ successfulMdxPages = new Map();
11
+ successfulMdxContent = new Map();
12
+ successfulMdxSourcesBySlug = new Map();
13
+ collisionBlockedMdxSources = new Set();
14
+ constructor(options) {
15
+ this.options = options;
16
+ this.mdxPassBuilder = new MdxPassBuilder({
17
+ sourceFs: options.sourceFs,
18
+ getAllMdxFiles: () => options.getAllMdxFiles(),
19
+ getSections: () => options.getSections(),
20
+ loadSectionsConfig: () => options.loadSectionsConfig(),
21
+ withApiReferenceSection: (sections) => options.withApiReferenceSection(sections),
22
+ determineSectionForFile: (filePath, frontmatter, sections) => options.determineSectionForFile(filePath, frontmatter, sections),
23
+ resolveHttpMethod: (reference) => options.lookupOpenApi(reference)?.method,
24
+ });
25
+ }
26
+ resetForInitialPublication() {
27
+ this.retainExistingMdxOutput = false;
28
+ }
29
+ successfulPages() {
30
+ return [...this.successfulMdxPages.values()];
31
+ }
32
+ occupiedSlugs() {
33
+ return new Set(this.successfulPages().map((page) => page.slug));
34
+ }
35
+ blockOpenApiPages(realPages) {
36
+ const blockedRealPages = [...realPages];
37
+ const blockedSlugs = new Set(blockedRealPages.map((page) => page.slug));
38
+ for (const page of this.successfulMdxPages.values()) {
39
+ if (blockedSlugs.has(page.slug))
40
+ continue;
41
+ blockedSlugs.add(page.slug);
42
+ blockedRealPages.push(page);
43
+ }
44
+ return blockedRealPages;
45
+ }
46
+ async captureMdxPass(files, seededSources = new Map(), refreshSections = false) {
47
+ return this.mdxPassBuilder.capture(files, seededSources, refreshSections);
48
+ }
49
+ async buildRealPagesMeta() {
50
+ return (await this.captureMdxPass()).pages;
51
+ }
52
+ async buildAllPagesMeta() {
53
+ const real = await this.buildRealPagesMeta();
54
+ const successful = this.mdxSnapshotInitialized
55
+ ? this.successfulPagesInSourceOrder(real)
56
+ : real;
57
+ return this.mergeAllPagesMeta(successful, new Set([...real, ...successful].map((page) => page.slug)));
58
+ }
59
+ mergeAllPagesMeta(real, declaredRealSlugs = new Set(real.map((page) => page.slug))) {
60
+ return mergePages(real, this.options.isOpenApiRegistryEmpty()
61
+ ? []
62
+ : this.options
63
+ .syntheticOpenApiPages()
64
+ .filter((page) => !declaredRealSlugs.has(page.slug)));
65
+ }
66
+ successfulPagesInSourceOrder(realPages) {
67
+ const currentSources = new Set(realPages.map((page) => page.path.replace(/\\/g, "/")));
68
+ const ordered = realPages.flatMap((page) => {
69
+ const successful = this.successfulMdxPages.get(page.path.replace(/\\/g, "/"));
70
+ return successful ? [successful] : [];
71
+ });
72
+ for (const [source, page] of this.successfulMdxPages) {
73
+ if (!currentSources.has(source))
74
+ ordered.push(page);
75
+ }
76
+ return ordered;
77
+ }
78
+ recordSuccessfulMdxPage(page, sourceContent) {
79
+ const source = page.path.replace(/\\/g, "/");
80
+ const previous = this.successfulMdxPages.get(source);
81
+ if (previous &&
82
+ previous.slug !== page.slug &&
83
+ this.successfulMdxSourcesBySlug.get(previous.slug) === source) {
84
+ this.successfulMdxSourcesBySlug.delete(previous.slug);
85
+ }
86
+ const otherSource = this.successfulMdxSourcesBySlug.get(page.slug);
87
+ if (otherSource && otherSource !== source) {
88
+ this.removeSuccessfulMdxPage(otherSource);
89
+ }
90
+ this.successfulMdxPages.set(source, page);
91
+ this.successfulMdxContent.set(source, sourceContent);
92
+ this.successfulMdxSourcesBySlug.set(page.slug, source);
93
+ this.collisionBlockedMdxSources.delete(source);
94
+ }
95
+ removeSuccessfulMdxPage(source) {
96
+ const successful = this.successfulMdxPages.get(source);
97
+ if (successful &&
98
+ this.successfulMdxSourcesBySlug.get(successful.slug) === source) {
99
+ this.successfulMdxSourcesBySlug.delete(successful.slug);
100
+ }
101
+ this.successfulMdxPages.delete(source);
102
+ this.successfulMdxContent.delete(source);
103
+ }
104
+ captureSuccessfulMdxState() {
105
+ return {
106
+ pages: new Map(this.successfulMdxPages),
107
+ content: new Map(this.successfulMdxContent),
108
+ sourcesBySlug: new Map(this.successfulMdxSourcesBySlug),
109
+ collisionBlockedSources: new Set(this.collisionBlockedMdxSources),
110
+ sections: this.options.getSections()?.map((section) => ({ ...section })) ?? null,
111
+ routes: this.options.getMdxRoutes(),
112
+ snapshotInitialized: this.mdxSnapshotInitialized,
113
+ };
114
+ }
115
+ restoreSuccessfulMdxState(state) {
116
+ this.successfulMdxPages = state.pages;
117
+ this.successfulMdxContent = state.content;
118
+ this.successfulMdxSourcesBySlug = state.sourcesBySlug;
119
+ this.collisionBlockedMdxSources = state.collisionBlockedSources;
120
+ this.options.setSections(state.sections);
121
+ this.mdxSnapshotInitialized = state.snapshotInitialized;
122
+ }
123
+ async rollbackPageCommits(commits) {
124
+ const errors = [];
125
+ for (const commit of [...commits].reverse()) {
126
+ try {
127
+ await commit.rollback();
128
+ }
129
+ catch (error) {
130
+ errors.push(error);
131
+ }
132
+ }
133
+ return errors;
134
+ }
135
+ async rollbackFailedMdxCommit(error, state, commits) {
136
+ this.restoreSuccessfulMdxState(state);
137
+ const rollbackErrors = await this.rollbackPageCommits(commits);
138
+ if (rollbackErrors.length > 0) {
139
+ throw new AggregateError([error, ...rollbackErrors], "Unable to commit or restore generated MDX pages");
140
+ }
141
+ throw error;
142
+ }
143
+ async rollbackCommittedMdxChange(error, state, commits) {
144
+ this.restoreSuccessfulMdxState(state);
145
+ const rollbackErrors = await this.rollbackPageCommits(commits);
146
+ const previousPages = [...state.pages.values()];
147
+ for (const page of previousPages) {
148
+ if (page.slug === "")
149
+ continue;
150
+ const content = state.content.get(page.path.replace(/\\/g, "/"));
151
+ if (content === undefined)
152
+ continue;
153
+ try {
154
+ await this.writePageForFile(page.path, content);
155
+ }
156
+ catch (rollbackError) {
157
+ rollbackErrors.push(rollbackError);
158
+ }
159
+ }
160
+ try {
161
+ await this.options.replaceMdxRoutes(state.routes.map(({ source, slug }) => ({ source, slug })));
162
+ }
163
+ catch (rollbackError) {
164
+ rollbackErrors.push(rollbackError);
165
+ }
166
+ try {
167
+ await this.refreshMdxDerivedOutput(previousPages, previousPages);
168
+ }
169
+ catch (rollbackError) {
170
+ rollbackErrors.push(rollbackError);
171
+ }
172
+ if (rollbackErrors.length > 0) {
173
+ throw new AggregateError([error, ...rollbackErrors], "Unable to refresh or restore generated MDX output");
174
+ }
175
+ throw error;
176
+ }
177
+ dropMissingMdxSnapshots(realPages) {
178
+ const currentSources = new Set(realPages.map((page) => page.path.replace(/\\/g, "/")));
179
+ for (const source of this.successfulMdxPages.keys()) {
180
+ if (currentSources.has(source))
181
+ continue;
182
+ this.removeSuccessfulMdxPage(source);
183
+ this.collisionBlockedMdxSources.delete(source);
184
+ }
185
+ }
186
+ async commitMdxSnapshot(realPages) {
187
+ this.dropMissingMdxSnapshots(realPages);
188
+ const successfulPages = this.successfulPagesInSourceOrder(realPages);
189
+ const previousRoutes = this.options.getMdxRoutes();
190
+ await this.options.generatedRouteManager.replaceMdxRoutes(successfulPages);
191
+ try {
192
+ await this.options.generatedRouteManager.removeStaleMdxRoutes(successfulPages, (slug) => this.options.removeOwnedRoute(slug), previousRoutes);
193
+ }
194
+ catch (error) {
195
+ console.error(chalk.red("❌ Error removing stale MDX routes; cleanup will retry:"), error);
196
+ }
197
+ this.mdxSnapshotInitialized = true;
198
+ return successfulPages;
199
+ }
200
+ async refreshMdxDerivedOutput(realPages, successfulPages) {
201
+ if (!this.options.isOpenApiRegistryEmpty() ||
202
+ this.options.getOpenApiRoutes().length > 0) {
203
+ await this.options.writeApiPages(realPages);
204
+ }
205
+ const declaredSlugs = new Set(realPages.map((page) => page.slug));
206
+ const pages = this.mergeAllPagesMeta(successfulPages, declaredSlugs);
207
+ await this.refreshSiteAggregates(pages, declaredSlugs);
208
+ }
209
+ async readAggregateMdxSource(filePath) {
210
+ const cached = this.successfulMdxContent.get(filePath.replace(/\\/g, "/"));
211
+ if (this.mdxSnapshotInitialized && cached !== undefined) {
212
+ return { content: cached };
213
+ }
214
+ return this.options.sourceFs.readMdxSourceFile(filePath);
215
+ }
216
+ homepageSource(frontmatter, mdxContent) {
217
+ return {
218
+ content: mdxContent,
219
+ title: frontmatter.title || "Welcome",
220
+ description: frontmatter.description || "",
221
+ icon: frontmatter.icon,
222
+ image: frontmatter.image,
223
+ name: frontmatter.name,
224
+ date: typeof frontmatter.date === "string" ? frontmatter.date : undefined,
225
+ updated: typeof frontmatter.updated === "string"
226
+ ? frontmatter.updated
227
+ : undefined,
228
+ openapi: typeof frontmatter.openapi === "string"
229
+ ? frontmatter.openapi
230
+ : undefined,
231
+ rss: frontmatter.rss === true,
232
+ };
233
+ }
234
+ async readHomepageSource(pages) {
235
+ const files = pages
236
+ ? pages
237
+ .map((page) => page.path)
238
+ .filter((file) => file === "index.mdx" || file === "./index.mdx")
239
+ : await this.options.getAllMdxFiles();
240
+ for (const file of files) {
241
+ if (file !== "index.mdx" && file !== "./index.mdx")
242
+ continue;
243
+ const cached = this.successfulMdxContent.get(file.replace(/\\/g, "/"));
244
+ if (this.mdxSnapshotInitialized && cached === undefined)
245
+ break;
246
+ const content = cached ?? (await this.options.sourceFs.readMdxSourceFile(file)).content;
247
+ const { data: frontmatter, content: mdxContent } = safeMatter(content, file);
248
+ return this.homepageSource(frontmatter, mdxContent);
249
+ }
250
+ return null;
251
+ }
252
+ async writePageForFile(filePath, content) {
253
+ const commits = [];
254
+ const { data: frontmatter, content: mdxContent } = safeMatter(content, filePath);
255
+ const { sectionSlug, pageSlug } = this.options.determineSectionForFile(filePath, frontmatter);
256
+ const fullSlug = getFullSlug(pageSlug, sectionSlug);
257
+ const isIndex = filePath === "index.mdx" || filePath === "./index.mdx";
258
+ const isSectionIndex = this.options.getSections() && pageSlug === "" && sectionSlug !== "";
259
+ try {
260
+ if (isIndex) {
261
+ // The homepage is emitted by updatePagesIndex() in the aggregate pass,
262
+ // so there is no per-file page to write here.
263
+ console.log(chalk.blue("🏠 Updating homepage with index.mdx content"));
264
+ }
265
+ else {
266
+ const mdxFile = {
267
+ path: filePath,
268
+ content: mdxContent,
269
+ frontmatter,
270
+ slug: fullSlug,
271
+ };
272
+ let apiOperation;
273
+ if (frontmatter.openapi) {
274
+ apiOperation = this.options.lookupOpenApi(String(frontmatter.openapi));
275
+ if (!apiOperation) {
276
+ console.error(chalk.red(`❌ openapi frontmatter "${frontmatter.openapi}" in ${filePath} not found in any spec`));
277
+ }
278
+ }
279
+ commits.push(await this.options.generatePageFromMdx(mdxFile, apiOperation ? { apiOperation } : undefined));
280
+ }
281
+ if (isSectionIndex) {
282
+ commits.push(await this.options.updateSectionIndex(sectionSlug, frontmatter, mdxContent, filePath));
283
+ }
284
+ return commits;
285
+ }
286
+ catch (error) {
287
+ const rollbackErrors = await this.rollbackPageCommits(commits);
288
+ if (rollbackErrors.length > 0) {
289
+ throw new AggregateError([error, ...rollbackErrors], `Unable to generate or restore ${filePath}`);
290
+ }
291
+ throw error;
292
+ }
293
+ }
294
+ async retryMdxPages(snapshot, shouldRetry, commits) {
295
+ for (const page of snapshot.pages) {
296
+ const source = page.path.replace(/\\/g, "/");
297
+ if (!shouldRetry(source, page))
298
+ continue;
299
+ const currentOwner = this.successfulMdxSourcesBySlug.get(page.slug);
300
+ if (currentOwner && currentOwner !== source)
301
+ continue;
302
+ const captured = snapshot.sources.get(source);
303
+ if (!captured)
304
+ continue;
305
+ try {
306
+ commits.push(...(await this.writePageForFile(page.path, captured.content)));
307
+ this.recordSuccessfulMdxPage(page, captured.content);
308
+ }
309
+ catch (error) {
310
+ console.error(chalk.red(`❌ Error processing ${page.path}:`), error);
311
+ }
312
+ }
313
+ }
314
+ async refreshSiteAggregates(resolvedPages, declaredSlugs) {
315
+ const pages = resolvedPages ?? (await this.buildAllPagesMeta());
316
+ await this.options.updatePagesIndex(pages);
317
+ await this.options.updateRootLayout(pages);
318
+ await this.options.updateSitemap(pages);
319
+ await this.options.updateLlmsFiles(pages);
320
+ await this.options.generateSectionIndexPages(pages, declaredSlugs);
321
+ }
322
+ async handleFileChange(action, filePath) {
323
+ console.log(chalk.cyan(`📝 File ${action}: ${filePath}`));
324
+ const normalizedSource = filePath.replace(/\\/g, "/");
325
+ const changedSource = await this.options.sourceFs.readMdxSourceFile(filePath);
326
+ const previousState = this.captureSuccessfulMdxState();
327
+ const pageCommits = [];
328
+ let pageRendered = false;
329
+ try {
330
+ const snapshot = await this.captureMdxPass(undefined, new Map([[normalizedSource, changedSource]]), true);
331
+ const realPages = snapshot.pages;
332
+ const currentPage = realPages.find((page) => page.path.replace(/\\/g, "/") === normalizedSource);
333
+ if (!currentPage)
334
+ throw new Error(`Unable to resolve ${filePath}`);
335
+ this.options.setSections(snapshot.sections);
336
+ try {
337
+ pageCommits.push(...(await this.writePageForFile(filePath, changedSource.content)));
338
+ this.recordSuccessfulMdxPage(currentPage, changedSource.content);
339
+ pageRendered = true;
340
+ }
341
+ catch (error) {
342
+ if (this.retainExistingMdxOutput) {
343
+ this.restoreSuccessfulMdxState(previousState);
344
+ }
345
+ else {
346
+ this.removeSuccessfulMdxPage(normalizedSource);
347
+ }
348
+ const successfulPages = await this.commitMdxSnapshot(realPages);
349
+ await this.refreshMdxDerivedOutput(realPages, successfulPages);
350
+ throw error;
351
+ }
352
+ await this.retryMdxPages(snapshot, (source) => source !== normalizedSource &&
353
+ this.collisionBlockedMdxSources.has(source), pageCommits);
354
+ let successfulPages = [];
355
+ try {
356
+ successfulPages = await this.commitMdxSnapshot(realPages);
357
+ }
358
+ catch (error) {
359
+ await this.rollbackFailedMdxCommit(error, previousState, pageCommits);
360
+ }
361
+ try {
362
+ await this.refreshMdxDerivedOutput(realPages, successfulPages);
363
+ }
364
+ catch (error) {
365
+ await this.rollbackCommittedMdxChange(error, previousState, pageCommits);
366
+ }
367
+ console.log(chalk.green(`✅ Generated page for: ${filePath}`));
368
+ await this.options.maybeUpdateSections();
369
+ }
370
+ catch (error) {
371
+ if (!pageRendered && error instanceof RouteCollisionError) {
372
+ this.collisionBlockedMdxSources.add(normalizedSource);
373
+ for (const source of error.sources) {
374
+ this.collisionBlockedMdxSources.add(source.replace(/\\/g, "/"));
375
+ }
376
+ }
377
+ console.error(chalk.red(`❌ Error processing ${filePath}:`), error);
378
+ }
379
+ }
380
+ async handleFileDelete(filePath) {
381
+ console.log(chalk.red(`🗑️ File deleted: ${filePath}`));
382
+ const previousState = this.captureSuccessfulMdxState();
383
+ const pageCommits = [];
384
+ try {
385
+ const normalizedSource = filePath.replace(/\\/g, "/");
386
+ if (filePath === "index.mdx" || filePath === "./index.mdx") {
387
+ console.log(chalk.blue("🏠 Updating homepage - index.mdx deleted"));
388
+ }
389
+ const snapshot = await this.captureMdxPass(undefined, undefined, true);
390
+ this.removeSuccessfulMdxPage(normalizedSource);
391
+ this.collisionBlockedMdxSources.delete(normalizedSource);
392
+ this.options.setSections(snapshot.sections);
393
+ const realPages = snapshot.pages;
394
+ await this.retryMdxPages(snapshot, (source, page) => this.collisionBlockedMdxSources.has(source) ||
395
+ this.successfulMdxPages.get(source)?.slug !== page.slug, pageCommits);
396
+ let successfulPages = [];
397
+ try {
398
+ successfulPages = await this.commitMdxSnapshot(realPages);
399
+ }
400
+ catch (error) {
401
+ await this.rollbackFailedMdxCommit(error, previousState, pageCommits);
402
+ }
403
+ try {
404
+ await this.refreshMdxDerivedOutput(realPages, successfulPages);
405
+ }
406
+ catch (error) {
407
+ await this.rollbackCommittedMdxChange(error, previousState, pageCommits);
408
+ }
409
+ console.log(chalk.green(`✅ Removed page for: ${filePath}`));
410
+ await this.options.maybeUpdateSections();
411
+ }
412
+ catch (error) {
413
+ console.error(chalk.red(`❌ Error removing page for ${filePath}:`), error);
414
+ }
415
+ }
416
+ async processAllMdxFiles() {
417
+ const previousState = this.captureSuccessfulMdxState();
418
+ const pageCommits = [];
419
+ const files = await this.options.getAllMdxFiles();
420
+ let snapshot;
421
+ try {
422
+ snapshot = await this.captureMdxPass(files, undefined, true);
423
+ }
424
+ catch (error) {
425
+ if (error instanceof RouteCollisionError) {
426
+ for (const source of files) {
427
+ this.collisionBlockedMdxSources.add(source.replace(/\\/g, "/"));
428
+ }
429
+ }
430
+ throw error;
431
+ }
432
+ this.options.setSections(snapshot.sections);
433
+ const realPages = snapshot.pages;
434
+ const pagesBySource = new Map(realPages.map((page) => [page.path.replace(/\\/g, "/"), page]));
435
+ for (const file of files) {
436
+ console.log(chalk.cyan(`📝 Processing: ${file}`));
437
+ const normalizedSource = file.replace(/\\/g, "/");
438
+ try {
439
+ const sourceContent = snapshot.sources.get(normalizedSource)?.content;
440
+ if (sourceContent === undefined) {
441
+ throw new Error(`Unable to snapshot ${file}`);
442
+ }
443
+ pageCommits.push(...(await this.writePageForFile(file, sourceContent)));
444
+ const page = pagesBySource.get(normalizedSource);
445
+ if (!page)
446
+ throw new Error(`Unable to resolve ${file}`);
447
+ this.recordSuccessfulMdxPage(page, sourceContent);
448
+ }
449
+ catch (error) {
450
+ if (!this.retainExistingMdxOutput) {
451
+ this.removeSuccessfulMdxPage(normalizedSource);
452
+ }
453
+ console.error(chalk.red(`❌ Error processing ${file}:`), error);
454
+ }
455
+ }
456
+ let successfulPages = [];
457
+ try {
458
+ successfulPages = await this.commitMdxSnapshot(realPages);
459
+ }
460
+ catch (error) {
461
+ await this.rollbackFailedMdxCommit(error, previousState, pageCommits);
462
+ }
463
+ this.retainExistingMdxOutput = true;
464
+ try {
465
+ await this.refreshMdxDerivedOutput(realPages, successfulPages);
466
+ }
467
+ catch (error) {
468
+ await this.rollbackCommittedMdxChange(error, previousState, pageCommits);
469
+ }
470
+ }
471
+ }