doccupine 0.0.144 → 0.0.146

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (51) hide show
  1. package/dist/generator/api-reference-generator.d.ts +4 -2
  2. package/dist/generator/api-reference-generator.js +32 -31
  3. package/dist/generator/app-scaffolder.d.ts +1 -2
  4. package/dist/generator/app-scaffolder.js +1 -6
  5. package/dist/generator/generated-page-publisher.d.ts +21 -0
  6. package/dist/generator/generated-page-publisher.js +124 -0
  7. package/dist/generator/generated-route-manager.d.ts +7 -3
  8. package/dist/generator/generated-route-manager.js +55 -19
  9. package/dist/generator/mdx-pass-builder.d.ts +31 -0
  10. package/dist/generator/mdx-pass-builder.js +45 -0
  11. package/dist/generator/openapi-refresh-coordinator.d.ts +42 -0
  12. package/dist/generator/openapi-refresh-coordinator.js +211 -0
  13. package/dist/generator/page-catalog.d.ts +4 -0
  14. package/dist/generator/page-catalog.js +8 -1
  15. package/dist/generator/project-config-repository.d.ts +8 -0
  16. package/dist/generator/project-config-repository.js +73 -15
  17. package/dist/generator/section-index-generator.d.ts +10 -0
  18. package/dist/generator/section-index-generator.js +68 -0
  19. package/dist/generator/secure-source-fs.d.ts +5 -1
  20. package/dist/generator/secure-source-fs.js +112 -3
  21. package/dist/generator/site-artifacts.d.ts +3 -2
  22. package/dist/generator/site-artifacts.js +6 -9
  23. package/dist/generator/watch-coordinator.d.ts +11 -2
  24. package/dist/generator/watch-coordinator.js +157 -62
  25. package/dist/lib/config-manager.d.ts +1 -0
  26. package/dist/lib/config-manager.js +194 -12
  27. package/dist/lib/generated-artifacts.d.ts +8 -2
  28. package/dist/lib/generated-artifacts.js +25 -6
  29. package/dist/lib/openapi.d.ts +4 -0
  30. package/dist/lib/openapi.js +36 -4
  31. package/dist/lib/output-safety.js +10 -3
  32. package/dist/mdx-to-nextjs-generator.d.ts +38 -23
  33. package/dist/mdx-to-nextjs-generator.js +521 -310
  34. package/dist/templates/mdx/api-playground.mdx.d.ts +1 -1
  35. package/dist/templates/mdx/api-playground.mdx.js +11 -2
  36. package/dist/templates/mdx/commands.mdx.d.ts +1 -1
  37. package/dist/templates/mdx/commands.mdx.js +26 -1
  38. package/dist/templates/mdx/media-and-assets.mdx.d.ts +1 -1
  39. package/dist/templates/mdx/media-and-assets.mdx.js +5 -0
  40. package/dist/templates/mdx/model-context-protocol.mdx.d.ts +1 -1
  41. package/dist/templates/mdx/model-context-protocol.mdx.js +2 -1
  42. package/dist/templates/mdx/platform/api-playground.mdx.d.ts +1 -1
  43. package/dist/templates/mdx/platform/api-playground.mdx.js +2 -2
  44. package/dist/templates/mdx/platform/publishing.mdx.d.ts +1 -1
  45. package/dist/templates/mdx/platform/publishing.mdx.js +3 -3
  46. package/dist/templates/mdx/what-is-doccupine.mdx.d.ts +1 -1
  47. package/dist/templates/mdx/what-is-doccupine.mdx.js +8 -3
  48. package/dist/templates/package.js +1 -1
  49. package/dist/templates/utils/orderNavItems.d.ts +1 -1
  50. package/dist/templates/utils/orderNavItems.js +1 -1
  51. package/package.json +2 -2
@@ -1,4 +1,5 @@
1
1
  import { GeneratedArtifacts } from "../lib/generated-artifacts.js";
2
+ import type { RouteArtifact } from "../lib/generated-artifacts.js";
2
3
  import { OpenApiRegistry } from "../lib/openapi.js";
3
4
  import type { OperationDescriptor } from "../lib/openapi-types.js";
4
5
  import type { MDXFile, PageMeta } from "../lib/types.js";
@@ -11,10 +12,11 @@ type CleanupStalePages = (nextRoutes: Map<string, string>, realSlugs: Set<string
11
12
  export declare class ApiReferenceGenerator {
12
13
  private readonly outputDir;
13
14
  private readonly artifacts;
15
+ private pendingStaleRoutes;
14
16
  constructor(outputDir: string, artifacts: GeneratedArtifacts);
15
17
  mergePages(registry: OpenApiRegistry, realPages: PageMeta[]): PageMeta[];
16
- writePages(registry: OpenApiRegistry, apiBaseSlug: string, realPages: PageMeta[], generatePage: GeneratePage, writeAllowlist: WriteAllowlist, cleanupStalePages: CleanupStalePages): Promise<void>;
18
+ writePages(registry: OpenApiRegistry, apiBaseSlug: string, realPages: PageMeta[], generatePage: GeneratePage, writeAllowlist: WriteAllowlist, cleanupStalePages: CleanupStalePages, writtenRoutes?: Map<string, string>): Promise<Map<string, string>>;
17
19
  writeAllowlist(registry: OpenApiRegistry): Promise<void>;
18
- cleanupStalePages(nextRoutes: Map<string, string>, realSlugs: Set<string>, removeOwnedRoute: RemoveOwnedRoute): Promise<void>;
20
+ cleanupStalePages(nextRoutes: Map<string, string>, occupiedMdxSlugs: Set<string>, removeOwnedRoute: RemoveOwnedRoute, additionalPreviousRoutes?: Iterable<RouteArtifact>): Promise<void>;
19
21
  }
20
22
  export {};
@@ -8,6 +8,7 @@ import { mergePages as mergePageCatalog } from "./page-catalog.js";
8
8
  export class ApiReferenceGenerator {
9
9
  outputDir;
10
10
  artifacts;
11
+ pendingStaleRoutes = new Map();
11
12
  constructor(outputDir, artifacts) {
12
13
  this.outputDir = outputDir;
13
14
  this.artifacts = artifacts;
@@ -15,28 +16,23 @@ export class ApiReferenceGenerator {
15
16
  mergePages(registry, realPages) {
16
17
  return mergePageCatalog(realPages, registry.isEmpty ? [] : registry.syntheticPages());
17
18
  }
18
- async writePages(registry, apiBaseSlug, realPages, generatePage, writeAllowlist, cleanupStalePages) {
19
+ async writePages(registry, apiBaseSlug, realPages, generatePage, writeAllowlist, cleanupStalePages, writtenRoutes = new Map()) {
19
20
  const realSlugs = new Set(realPages.map((page) => page.slug));
20
- const nextRoutes = new Map();
21
+ const nextRoutes = writtenRoutes;
21
22
  const indexPage = registry
22
23
  .syntheticPages()
23
24
  .find((page) => page.slug === apiBaseSlug);
24
25
  if (indexPage && !realSlugs.has(indexPage.slug)) {
25
- try {
26
- await generatePage({
27
- path: indexPage.path,
28
- content: registry.bodyForSlug(indexPage.slug) ?? "",
29
- frontmatter: {
30
- title: indexPage.title,
31
- description: indexPage.description,
32
- },
33
- slug: indexPage.slug,
34
- });
35
- nextRoutes.set(`@openapi/${indexPage.slug}`, indexPage.slug);
36
- }
37
- catch (error) {
38
- console.error(chalk.red(`❌ Error generating API index ${indexPage.slug}:`), error);
39
- }
26
+ await generatePage({
27
+ path: indexPage.path,
28
+ content: registry.bodyForSlug(indexPage.slug) ?? "",
29
+ frontmatter: {
30
+ title: indexPage.title,
31
+ description: indexPage.description,
32
+ },
33
+ slug: indexPage.slug,
34
+ });
35
+ nextRoutes.set(`@openapi/${indexPage.slug}`, indexPage.slug);
40
36
  }
41
37
  for (const op of registry.all) {
42
38
  const methodUpper = op.method.toUpperCase();
@@ -53,43 +49,48 @@ export class ApiReferenceGenerator {
53
49
  console.log(chalk.yellow(`⚠️ API page ${op.slug} is shadowed by a hand-written page; skipping`));
54
50
  continue;
55
51
  }
56
- try {
57
- await generatePage(mdxFile, { apiOperation: op });
58
- nextRoutes.set(`@openapi/${op.slug}`, op.slug);
59
- }
60
- catch (error) {
61
- console.error(chalk.red(`❌ Error generating API page ${op.slug}:`), error);
62
- }
52
+ await generatePage(mdxFile, { apiOperation: op });
53
+ nextRoutes.set(`@openapi/${op.slug}`, op.slug);
63
54
  }
64
55
  await writeAllowlist();
65
56
  await cleanupStalePages(nextRoutes, realSlugs);
66
57
  if (registry.all.length > 0) {
67
58
  console.log(chalk.green(`🧩 Generated ${nextRoutes.size} API reference page(s)`));
68
59
  }
60
+ return nextRoutes;
69
61
  }
70
62
  async writeAllowlist(registry) {
71
63
  const target = resolveOutputPath(this.outputDir, "services", "openapi", "playground-allowlist.json");
72
64
  await fs.ensureDir(path.dirname(target));
73
65
  await writeFileAtomic(target, `${JSON.stringify(registry.allowlist(), null, 2)}\n`);
74
66
  }
75
- async cleanupStalePages(nextRoutes, realSlugs, removeOwnedRoute) {
67
+ async cleanupStalePages(nextRoutes, occupiedMdxSlugs, removeOwnedRoute, additionalPreviousRoutes = []) {
68
+ const previousRoutes = new Map([
69
+ ...this.artifacts.routesFor("openapi"),
70
+ ...additionalPreviousRoutes,
71
+ ...this.pendingStaleRoutes.values(),
72
+ ].map((route) => [route.source, route]));
73
+ await this.artifacts.replaceRoutesAndSave("openapi", [...nextRoutes].map(([source, slug]) => ({ source, slug })));
76
74
  const nextSlugs = new Set(nextRoutes.values());
77
- for (const previous of this.artifacts.routesFor("openapi")) {
75
+ for (const previous of previousRoutes.values()) {
78
76
  if (nextRoutes.has(previous.source) || nextSlugs.has(previous.slug)) {
77
+ this.pendingStaleRoutes.delete(previous.source);
79
78
  continue;
80
79
  }
81
80
  // A hand-written page may have taken ownership of this route since the
82
81
  // previous OpenAPI pass. Never remove an output now claimed by MDX.
83
- if (realSlugs.has(previous.slug))
82
+ if (occupiedMdxSlugs.has(previous.slug)) {
83
+ this.pendingStaleRoutes.delete(previous.source);
84
84
  continue;
85
+ }
86
+ this.pendingStaleRoutes.set(previous.source, previous);
85
87
  try {
86
88
  await removeOwnedRoute(previous.slug);
89
+ this.pendingStaleRoutes.delete(previous.source);
87
90
  }
88
- catch {
89
- // ignore
91
+ catch (error) {
92
+ throw error;
90
93
  }
91
94
  }
92
- this.artifacts.replaceRoutes("openapi", [...nextRoutes].map(([source, slug]) => ({ source, slug })));
93
- await this.artifacts.save();
94
95
  }
95
96
  }
@@ -6,8 +6,7 @@ interface AppStructureCallbacks {
6
6
  updateLlmsFiles(): Promise<void>;
7
7
  }
8
8
  interface StarterDocumentCallbacks {
9
- getAllMdxFiles(): Promise<string[]>;
10
- ensureSafeStarterPath(relativePath: string): Promise<string>;
9
+ writeStarterFilesIfEmpty(files: Iterable<readonly [string, string | Uint8Array]>): Promise<void>;
11
10
  }
12
11
  export declare class AppScaffolder {
13
12
  private readonly outputDir;
@@ -44,11 +44,6 @@ export class AppScaffolder {
44
44
  await callbacks.updateLlmsFiles();
45
45
  }
46
46
  async createStartingDocs(callbacks) {
47
- if ((await callbacks.getAllMdxFiles()).length > 0)
48
- return;
49
- for (const [filePath, content] of Object.entries(startingDocsStructure)) {
50
- const fullPath = await callbacks.ensureSafeStarterPath(filePath);
51
- await writeFileAtomic(fullPath, String(content));
52
- }
47
+ await callbacks.writeStarterFilesIfEmpty(Object.entries(startingDocsStructure));
53
48
  }
54
49
  }
@@ -0,0 +1,21 @@
1
+ import type { MDXFile } from "../lib/types.js";
2
+ import type { OperationDescriptor } from "../lib/openapi-types.js";
3
+ import { type HomepageSource } from "./page-renderer.js";
4
+ import { GeneratedRouteManager } from "./generated-route-manager.js";
5
+ export interface GeneratedPageCommit {
6
+ rollback(): Promise<void>;
7
+ }
8
+ export declare class GeneratedPagePublisher {
9
+ private readonly outputDir;
10
+ private readonly routeManager;
11
+ constructor(outputDir: string, routeManager: GeneratedRouteManager);
12
+ private generatedFileSegments;
13
+ private readGeneratedFile;
14
+ private restoreGeneratedFile;
15
+ private commitRenderedPage;
16
+ generatePageFromMdx(mdxFile: MDXFile, options?: {
17
+ apiOperation?: OperationDescriptor;
18
+ }): Promise<GeneratedPageCommit>;
19
+ updateHomepage(source: HomepageSource | null, apiOperation?: OperationDescriptor): Promise<GeneratedPageCommit>;
20
+ updateSectionIndex(sectionSlug: string, frontmatter: Record<string, any>, mdxContent: string, sourcePath?: string): Promise<GeneratedPageCommit>;
21
+ }
@@ -0,0 +1,124 @@
1
+ import fs from "fs-extra";
2
+ import path from "node:path";
3
+ import { readOutputFileIfPresent, resolveOutputPath, } from "../lib/output-safety.js";
4
+ import { writeFileAtomic } from "../lib/utils.js";
5
+ import { renderHomepage, renderMdxPage, renderSectionPage, } from "./page-renderer.js";
6
+ export class GeneratedPagePublisher {
7
+ outputDir;
8
+ routeManager;
9
+ constructor(outputDir, routeManager) {
10
+ this.outputDir = outputDir;
11
+ this.routeManager = routeManager;
12
+ }
13
+ generatedFileSegments(filePath) {
14
+ return path
15
+ .relative(fs.realpathSync(this.outputDir), filePath)
16
+ .split(path.sep)
17
+ .filter(Boolean);
18
+ }
19
+ async readGeneratedFile(filePath) {
20
+ return readOutputFileIfPresent(this.outputDir, ...this.generatedFileSegments(filePath));
21
+ }
22
+ async restoreGeneratedFile(filePath, content) {
23
+ const target = resolveOutputPath(this.outputDir, ...this.generatedFileSegments(filePath));
24
+ if (content === null) {
25
+ await fs.remove(target);
26
+ }
27
+ else {
28
+ await writeFileAtomic(target, content);
29
+ }
30
+ }
31
+ async commitRenderedPage(pagePath, rendered) {
32
+ if (rendered.rssRoute.action === "preserve") {
33
+ const previousPage = await this.readGeneratedFile(pagePath);
34
+ await writeFileAtomic(pagePath, rendered.pageContent);
35
+ return {
36
+ rollback: () => this.restoreGeneratedFile(pagePath, previousPage),
37
+ };
38
+ }
39
+ const rssDir = resolveOutputPath(path.dirname(pagePath), "rss.xml");
40
+ const rssPath = resolveOutputPath(path.dirname(pagePath), "rss.xml", "route.ts");
41
+ const [previousPage, previousRss] = await Promise.all([
42
+ this.readGeneratedFile(pagePath),
43
+ this.readGeneratedFile(rssPath),
44
+ ]);
45
+ let pageChanged = false;
46
+ let rssChanged = false;
47
+ try {
48
+ if (rendered.rssRoute.action === "write") {
49
+ await writeFileAtomic(rssPath, rendered.rssRoute.content);
50
+ rssChanged = true;
51
+ await writeFileAtomic(pagePath, rendered.pageContent);
52
+ pageChanged = true;
53
+ }
54
+ else {
55
+ await writeFileAtomic(pagePath, rendered.pageContent);
56
+ pageChanged = true;
57
+ await fs.remove(rssPath);
58
+ rssChanged = true;
59
+ await this.routeManager.removeEmptyDirsUpTo(rssDir, path.dirname(pagePath));
60
+ }
61
+ }
62
+ catch (error) {
63
+ const rollbackErrors = [];
64
+ if (rssChanged) {
65
+ try {
66
+ await this.restoreGeneratedFile(rssPath, previousRss);
67
+ }
68
+ catch (rollbackError) {
69
+ rollbackErrors.push(rollbackError);
70
+ }
71
+ }
72
+ if (pageChanged) {
73
+ try {
74
+ await this.restoreGeneratedFile(pagePath, previousPage);
75
+ }
76
+ catch (rollbackError) {
77
+ rollbackErrors.push(rollbackError);
78
+ }
79
+ }
80
+ if (rollbackErrors.length > 0) {
81
+ throw new AggregateError([error, ...rollbackErrors], `Unable to publish or restore generated page ${pagePath}`);
82
+ }
83
+ throw error;
84
+ }
85
+ return {
86
+ rollback: async () => {
87
+ const rollbackErrors = [];
88
+ try {
89
+ await this.restoreGeneratedFile(rssPath, previousRss);
90
+ }
91
+ catch (error) {
92
+ rollbackErrors.push(error);
93
+ }
94
+ try {
95
+ await this.restoreGeneratedFile(pagePath, previousPage);
96
+ }
97
+ catch (error) {
98
+ rollbackErrors.push(error);
99
+ }
100
+ if (rollbackErrors.length > 0) {
101
+ throw new AggregateError(rollbackErrors, `Unable to restore generated page ${pagePath}`);
102
+ }
103
+ },
104
+ };
105
+ }
106
+ async generatePageFromMdx(mdxFile, options) {
107
+ const rendered = renderMdxPage(mdxFile, options);
108
+ const pagePath = resolveOutputPath(this.outputDir, "app", "(site)", mdxFile.slug, "page.tsx");
109
+ await fs.ensureDir(path.dirname(pagePath));
110
+ return this.commitRenderedPage(pagePath, rendered);
111
+ }
112
+ async updateHomepage(source, apiOperation) {
113
+ const rendered = renderHomepage(source, apiOperation);
114
+ const pagePath = resolveOutputPath(this.outputDir, "app", "(site)", "page.tsx");
115
+ await fs.ensureDir(path.dirname(pagePath));
116
+ return this.commitRenderedPage(pagePath, rendered);
117
+ }
118
+ async updateSectionIndex(sectionSlug, frontmatter, mdxContent, sourcePath) {
119
+ const rendered = renderSectionPage(sectionSlug, frontmatter, mdxContent, sourcePath);
120
+ const pagePath = resolveOutputPath(this.outputDir, "app", "(site)", sectionSlug, "page.tsx");
121
+ await fs.ensureDir(path.dirname(pagePath));
122
+ return this.commitRenderedPage(pagePath, rendered);
123
+ }
124
+ }
@@ -1,17 +1,21 @@
1
- import { GeneratedArtifacts } from "../lib/generated-artifacts.js";
1
+ import { GeneratedArtifacts, type RouteArtifact } from "../lib/generated-artifacts.js";
2
2
  import type { PageMeta } from "../lib/types.js";
3
3
  export declare class GeneratedRouteManager {
4
4
  private readonly outputDir;
5
5
  private readonly artifacts;
6
6
  private generatedSectionIndexSlugs;
7
+ private pendingStaleMdxRoutes;
7
8
  constructor(outputDir: string, artifacts: GeneratedArtifacts);
8
9
  private outputPath;
9
10
  routeForMdxSource(source: string): string | undefined;
11
+ sectionIndexSlugs(): Set<string>;
12
+ replaceSectionIndexSlugs(slugs: Iterable<string>): void;
10
13
  replaceMdxRoutes(realPages: PageMeta[]): Promise<void>;
11
14
  removeMdxRoute(source: string): Promise<void>;
12
15
  removeOwnedRoute(slug: string): Promise<void>;
13
- removeStaleMdxRoutes(realPages: PageMeta[], removeOwnedRoute: (slug: string) => Promise<void>): Promise<void>;
14
- cleanupStaleSectionIndexPages(nextSlugs: Set<string>, removeEmptyDirs: (dir: string, stopDir: string) => Promise<void>): Promise<void>;
16
+ removeStaleMdxRoutes(realPages: PageMeta[], removeOwnedRoute: (slug: string) => Promise<void>, previousRoutes?: readonly RouteArtifact[]): Promise<void>;
17
+ cleanupStaleSectionIndexPages(nextSlugs: Set<string>, occupiedSlugs: Set<string>, removeEmptyDirs: (dir: string, stopDir: string) => Promise<void>): Promise<void>;
18
+ private removeSectionIndexPage;
15
19
  /** Best-effort removal of now-empty directories up to (not incl.) stopDir. */
16
20
  removeEmptyDirsUpTo(dir: string, stopDir: string): Promise<void>;
17
21
  }
@@ -6,6 +6,7 @@ export class GeneratedRouteManager {
6
6
  outputDir;
7
7
  artifacts;
8
8
  generatedSectionIndexSlugs = new Set();
9
+ pendingStaleMdxRoutes = new Map();
9
10
  constructor(outputDir, artifacts) {
10
11
  this.outputDir = outputDir;
11
12
  this.artifacts = artifacts;
@@ -16,15 +17,19 @@ export class GeneratedRouteManager {
16
17
  routeForMdxSource(source) {
17
18
  return this.artifacts.routeFor("mdx", source);
18
19
  }
20
+ sectionIndexSlugs() {
21
+ return new Set(this.generatedSectionIndexSlugs);
22
+ }
23
+ replaceSectionIndexSlugs(slugs) {
24
+ this.generatedSectionIndexSlugs = new Set(slugs);
25
+ }
19
26
  async replaceMdxRoutes(realPages) {
20
- this.artifacts.replaceRoutes("mdx", realPages
27
+ await this.artifacts.replaceRoutesAndSave("mdx", realPages
21
28
  .filter((page) => page.slug !== "")
22
29
  .map((page) => ({ source: page.path, slug: page.slug })));
23
- await this.artifacts.save();
24
30
  }
25
31
  async removeMdxRoute(source) {
26
- this.artifacts.removeRoute("mdx", source);
27
- await this.artifacts.save();
32
+ await this.artifacts.removeRouteAndSave("mdx", source);
28
33
  }
29
34
  async removeOwnedRoute(slug) {
30
35
  if (!slug)
@@ -37,40 +42,71 @@ export class GeneratedRouteManager {
37
42
  ]);
38
43
  await this.removeEmptyDirsUpTo(routeDir, siteDir);
39
44
  }
40
- async removeStaleMdxRoutes(realPages, removeOwnedRoute) {
45
+ async removeStaleMdxRoutes(realPages, removeOwnedRoute, previousRoutes = this.artifacts.routesFor("mdx")) {
41
46
  const nextBySource = new Map(realPages
42
47
  .filter((page) => page.slug !== "")
43
48
  .map((page) => [page.path.replace(/\\/g, "/"), page.slug]));
44
49
  const nextSlugs = new Set(nextBySource.values());
45
- for (const previous of this.artifacts.routesFor("mdx")) {
50
+ const openApiSlugs = new Set(this.artifacts.routesFor("openapi").map((route) => route.slug));
51
+ for (const previous of previousRoutes) {
46
52
  if (nextBySource.get(previous.source) === previous.slug)
47
53
  continue;
48
54
  if (nextSlugs.has(previous.slug))
49
55
  continue;
50
- await removeOwnedRoute(previous.slug);
56
+ if (openApiSlugs.has(previous.slug))
57
+ continue;
58
+ this.pendingStaleMdxRoutes.set(previous.slug, previous);
59
+ }
60
+ const errors = [];
61
+ for (const [slug] of this.pendingStaleMdxRoutes) {
62
+ if (nextSlugs.has(slug)) {
63
+ this.pendingStaleMdxRoutes.delete(slug);
64
+ continue;
65
+ }
66
+ try {
67
+ if (openApiSlugs.has(slug)) {
68
+ await fs.remove(resolveOutputPath(this.outputDir, "app", "(site)", slug, "rss.xml"));
69
+ }
70
+ else {
71
+ await removeOwnedRoute(slug);
72
+ }
73
+ this.pendingStaleMdxRoutes.delete(slug);
74
+ }
75
+ catch (error) {
76
+ errors.push(error);
77
+ }
78
+ }
79
+ if (errors.length > 0) {
80
+ throw new AggregateError(errors, "Unable to remove stale MDX routes");
51
81
  }
52
82
  }
53
- async cleanupStaleSectionIndexPages(nextSlugs, removeEmptyDirs) {
83
+ async cleanupStaleSectionIndexPages(nextSlugs, occupiedSlugs, removeEmptyDirs) {
84
+ const errors = [];
54
85
  for (const stale of this.generatedSectionIndexSlugs) {
55
86
  if (nextSlugs.has(stale))
56
87
  continue;
57
- const pagePath = resolveOutputPath(this.outputDir, "app", "(site)", stale, "page.tsx");
88
+ if (occupiedSlugs.has(stale))
89
+ continue;
58
90
  try {
59
- if (!(await fs.pathExists(pagePath)))
60
- continue;
61
- const content = await fs.readFile(pagePath, "utf8");
62
- if (!content.includes("function SectionIndex()"))
63
- continue;
64
- await fs.remove(pagePath);
65
- await removeEmptyDirs(path.dirname(pagePath), this.outputPath("app", "(site)"));
66
- console.log(chalk.blue(`🧹 Removed stale section index redirect: /${stale}`));
91
+ await this.removeSectionIndexPage(stale, removeEmptyDirs);
67
92
  }
68
- catch {
69
- // ignore
93
+ catch (error) {
94
+ errors.push(error);
70
95
  }
71
96
  }
97
+ if (errors.length > 0) {
98
+ throw new AggregateError(errors, "Unable to remove stale section index redirects");
99
+ }
72
100
  this.generatedSectionIndexSlugs = nextSlugs;
73
101
  }
102
+ async removeSectionIndexPage(slug, removeEmptyDirs) {
103
+ const pagePath = resolveOutputPath(this.outputDir, "app", "(site)", slug, "page.tsx");
104
+ if (!(await fs.pathExists(pagePath)))
105
+ return;
106
+ await fs.remove(pagePath);
107
+ await removeEmptyDirs(path.dirname(pagePath), this.outputPath("app", "(site)"));
108
+ console.log(chalk.blue(`🧹 Removed stale section index redirect: /${slug}`));
109
+ }
74
110
  /** Best-effort removal of now-empty directories up to (not incl.) stopDir. */
75
111
  async removeEmptyDirsUpTo(dir, stopDir) {
76
112
  const stop = path.resolve(stopDir);
@@ -0,0 +1,31 @@
1
+ import type { Stats } from "node:fs";
2
+ import type { PageMeta, SectionConfig } from "../lib/types.js";
3
+ import { SecureSourceFs } from "./secure-source-fs.js";
4
+ export interface MdxSourceSnapshot {
5
+ content: string;
6
+ stat: Stats;
7
+ }
8
+ export interface MdxPassSnapshot {
9
+ files: string[];
10
+ pages: PageMeta[];
11
+ sources: ReadonlyMap<string, MdxSourceSnapshot>;
12
+ sections: SectionConfig[] | null;
13
+ }
14
+ interface MdxPassBuilderOptions {
15
+ sourceFs: SecureSourceFs;
16
+ getAllMdxFiles(): Promise<string[]>;
17
+ getSections(): SectionConfig[] | null;
18
+ loadSectionsConfig(): Promise<SectionConfig[] | null>;
19
+ withApiReferenceSection(sections: SectionConfig[] | null): SectionConfig[] | null;
20
+ determineSectionForFile(filePath: string, frontmatter: Record<string, any>, sections: SectionConfig[] | null): {
21
+ sectionSlug: string;
22
+ pageSlug: string;
23
+ };
24
+ resolveHttpMethod(reference: string): string | undefined;
25
+ }
26
+ export declare class MdxPassBuilder {
27
+ private readonly options;
28
+ constructor(options: MdxPassBuilderOptions);
29
+ capture(files?: string[], seededSources?: ReadonlyMap<string, MdxSourceSnapshot>, refreshSections?: boolean): Promise<MdxPassSnapshot>;
30
+ }
31
+ export {};
@@ -0,0 +1,45 @@
1
+ import { safeMatter } from "../lib/utils.js";
2
+ import { buildRealPagesMeta, parseMdxPageMeta } from "./page-catalog.js";
3
+ import { discoverSections } from "./section-resolver.js";
4
+ export class MdxPassBuilder {
5
+ options;
6
+ constructor(options) {
7
+ this.options = options;
8
+ }
9
+ async capture(files, seededSources = new Map(), refreshSections = false) {
10
+ const resolvedFiles = files ?? (await this.options.getAllMdxFiles());
11
+ const sources = new Map(seededSources);
12
+ await Promise.all(resolvedFiles.map(async (file) => {
13
+ const source = file.replace(/\\/g, "/");
14
+ if (!sources.has(source)) {
15
+ sources.set(source, await this.options.sourceFs.readMdxSourceFile(file));
16
+ }
17
+ }));
18
+ let sections = this.options.getSections();
19
+ if (refreshSections) {
20
+ const configuredSections = await this.options.loadSectionsConfig();
21
+ if (configuredSections !== null) {
22
+ sections = this.options.withApiReferenceSection(configuredSections);
23
+ }
24
+ else {
25
+ const documents = resolvedFiles.map((filePath) => {
26
+ const source = sources.get(filePath.replace(/\\/g, "/"));
27
+ if (!source)
28
+ throw new Error(`Unable to snapshot ${filePath}`);
29
+ return {
30
+ filePath,
31
+ frontmatter: safeMatter(source.content, filePath).data,
32
+ };
33
+ });
34
+ sections = this.options.withApiReferenceSection(discoverSections(documents));
35
+ }
36
+ }
37
+ const pages = await buildRealPagesMeta(resolvedFiles, async (file) => {
38
+ const source = sources.get(file.replace(/\\/g, "/"));
39
+ if (!source)
40
+ throw new Error(`Unable to snapshot ${file}`);
41
+ return parseMdxPageMeta(file, async () => source, (filePath, frontmatter) => this.options.determineSectionForFile(filePath, frontmatter, sections), (reference) => this.options.resolveHttpMethod(reference));
42
+ });
43
+ return { files: resolvedFiles, pages, sources, sections };
44
+ }
45
+ }
@@ -0,0 +1,42 @@
1
+ import type { RouteArtifact } from "../lib/generated-artifacts.js";
2
+ import { OpenApiRegistry } from "../lib/openapi.js";
3
+ import type { NormalizedOpenApiSpec, PageMeta, SectionConfig } from "../lib/types.js";
4
+ import { SecureSourceFs } from "./secure-source-fs.js";
5
+ export interface ApiPageWriteOptions {
6
+ writtenRoutes?: Map<string, string>;
7
+ additionalPreviousRoutes?: Iterable<RouteArtifact>;
8
+ }
9
+ interface OpenApiRefreshCoordinatorOptions {
10
+ rootDir: string;
11
+ watchDir: string;
12
+ outputDir: string;
13
+ configFile: string;
14
+ apiBaseSlug: string;
15
+ sourceFs: SecureSourceFs;
16
+ getRegistry(): OpenApiRegistry;
17
+ setRegistry(registry: OpenApiRegistry): void;
18
+ getSpecs(): NormalizedOpenApiSpec[];
19
+ setSpecs(specs: NormalizedOpenApiSpec[]): void;
20
+ getSections(): SectionConfig[] | null;
21
+ setSections(sections: SectionConfig[] | null): void;
22
+ getOpenApiRoutes(): RouteArtifact[];
23
+ getSuccessfulMdxPages(): PageMeta[];
24
+ resolveSections(): Promise<SectionConfig[] | null>;
25
+ writeApiPages(realPages?: PageMeta[], options?: ApiPageWriteOptions): Promise<Map<string, string>>;
26
+ refreshSiteAggregates(): Promise<void>;
27
+ syncWatcher(): Promise<void>;
28
+ removeOwnedRoute(slug: string): Promise<void>;
29
+ }
30
+ export declare class OpenApiRefreshCoordinator {
31
+ private readonly options;
32
+ constructor(options: OpenApiRefreshCoordinatorOptions);
33
+ loadInitialRegistry(): Promise<void>;
34
+ private sourceState;
35
+ private loadStableRegistry;
36
+ private applyStableRefresh;
37
+ private restorePreviousRefresh;
38
+ private applyRefresh;
39
+ handleOpenApiChange(): Promise<void>;
40
+ handleConfigChange(): Promise<void>;
41
+ }
42
+ export {};