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.
Files changed (54) 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/generated-page-publisher.d.ts +21 -0
  5. package/dist/generator/generated-page-publisher.js +124 -0
  6. package/dist/generator/generated-route-manager.d.ts +3 -0
  7. package/dist/generator/generated-route-manager.js +21 -8
  8. package/dist/generator/mdx-pass-builder.d.ts +31 -0
  9. package/dist/generator/mdx-pass-builder.js +45 -0
  10. package/dist/generator/mdx-reconciliation-coordinator.d.ts +83 -0
  11. package/dist/generator/mdx-reconciliation-coordinator.js +471 -0
  12. package/dist/generator/openapi-refresh-coordinator.d.ts +42 -0
  13. package/dist/generator/openapi-refresh-coordinator.js +211 -0
  14. package/dist/generator/page-renderer.js +18 -13
  15. package/dist/generator/section-index-generator.d.ts +10 -0
  16. package/dist/generator/section-index-generator.js +68 -0
  17. package/dist/generator/secure-source-fs.js +5 -4
  18. package/dist/generator/site-artifacts.js +2 -2
  19. package/dist/generator/watch-coordinator.d.ts +8 -0
  20. package/dist/generator/watch-coordinator.js +131 -53
  21. package/dist/index.js +8 -2
  22. package/dist/lib/layout.js +18 -10
  23. package/dist/lib/openapi-rendering.d.ts +17 -0
  24. package/dist/lib/openapi-rendering.js +193 -0
  25. package/dist/lib/openapi.d.ts +1 -7
  26. package/dist/lib/openapi.js +2 -192
  27. package/dist/lib/output-safety.js +10 -3
  28. package/dist/lib/structures.js +4 -0
  29. package/dist/lib/utils.d.ts +14 -0
  30. package/dist/lib/utils.js +30 -8
  31. package/dist/mdx-to-nextjs-generator.d.ts +7 -65
  32. package/dist/mdx-to-nextjs-generator.js +94 -783
  33. package/dist/templates/components/Chat.d.ts +1 -1
  34. package/dist/templates/components/Chat.js +20 -691
  35. package/dist/templates/components/ChatStyles.d.ts +1 -0
  36. package/dist/templates/components/ChatStyles.js +695 -0
  37. package/dist/templates/components/layout/ApiPlayground.d.ts +1 -1
  38. package/dist/templates/components/layout/ApiPlayground.js +14 -148
  39. package/dist/templates/mdx/platform/analytics.mdx.d.ts +1 -1
  40. package/dist/templates/mdx/platform/analytics.mdx.js +13 -0
  41. package/dist/templates/mdx/platform/fonts-settings.mdx.d.ts +1 -1
  42. package/dist/templates/mdx/platform/fonts-settings.mdx.js +16 -0
  43. package/dist/templates/mdx/platform/publishing.mdx.d.ts +1 -1
  44. package/dist/templates/mdx/platform/publishing.mdx.js +16 -1
  45. package/dist/templates/mdx/platform/self-updating-docs.mdx.d.ts +1 -1
  46. package/dist/templates/mdx/platform/self-updating-docs.mdx.js +17 -5
  47. package/dist/templates/package.js +3 -2
  48. package/dist/templates/prettierignore.d.ts +1 -1
  49. package/dist/templates/prettierignore.js +11 -0
  50. package/dist/templates/utils/apiPlayground.d.ts +1 -0
  51. package/dist/templates/utils/apiPlayground.js +149 -0
  52. package/dist/templates/utils/orderNavItems.d.ts +1 -1
  53. package/dist/templates/utils/orderNavItems.js +1 -1
  54. package/package.json +1 -1
@@ -0,0 +1,211 @@
1
+ import chalk from "chalk";
2
+ import path from "node:path";
3
+ import { normalizeOpenApiConfig, validateConfig, } from "../lib/config-manager.js";
4
+ import { OpenApiRegistry } from "../lib/openapi.js";
5
+ class OpenApiRestoreError extends AggregateError {
6
+ }
7
+ class OpenApiWatcherRestoreNeededError extends Error {
8
+ originalError;
9
+ constructor(originalError) {
10
+ super("OpenAPI watcher synchronization required verified restoration");
11
+ this.originalError = originalError;
12
+ }
13
+ }
14
+ export class OpenApiRefreshCoordinator {
15
+ options;
16
+ constructor(options) {
17
+ this.options = options;
18
+ }
19
+ async loadInitialRegistry() {
20
+ const specs = this.options.getSpecs();
21
+ if (specs.length === 0)
22
+ return;
23
+ const { registry } = await this.loadStableRegistry(specs);
24
+ this.options.setRegistry(registry);
25
+ if (!registry.isEmpty) {
26
+ console.log(chalk.blue(`📘 Loaded ${registry.all.length} API endpoint(s) from ${specs.length} spec(s)`));
27
+ }
28
+ }
29
+ async sourceState(registry) {
30
+ return (await Promise.all(registry.sourceFiles.map(async (sourcePath) => {
31
+ return `${sourcePath}:${await this.options.sourceFs.pathState(sourcePath, true)}`;
32
+ }))).join("\n");
33
+ }
34
+ async loadStableRegistry(specs) {
35
+ for (let attempt = 0; attempt < 3; attempt += 1) {
36
+ const registry = new OpenApiRegistry();
37
+ await registry.load(specs, this.options.rootDir, this.options.apiBaseSlug);
38
+ const current = await this.sourceState(registry);
39
+ if (registry.sourceFingerprint === current) {
40
+ return { registry, sourceState: current };
41
+ }
42
+ }
43
+ throw new Error("OpenAPI sources changed repeatedly while being loaded");
44
+ }
45
+ async applyStableRefresh(specs) {
46
+ const previousRegistry = this.options.getRegistry();
47
+ const previousSpecs = this.options.getSpecs();
48
+ let successfulApplications = 0;
49
+ try {
50
+ let candidate = await this.loadStableRegistry(specs);
51
+ await this.applyRefresh(candidate.registry, specs);
52
+ successfulApplications += 1;
53
+ // Recheck after watcher readiness so changes in the retargeting window are
54
+ // replayed explicitly instead of being missed by ignoreInitial watchers.
55
+ for (let attempt = 0; attempt < 3; attempt += 1) {
56
+ if ((await this.sourceState(candidate.registry)) === candidate.sourceState) {
57
+ return;
58
+ }
59
+ candidate = await this.loadStableRegistry(specs);
60
+ await this.applyRefresh(candidate.registry, specs);
61
+ successfulApplications += 1;
62
+ }
63
+ if ((await this.sourceState(candidate.registry)) === candidate.sourceState) {
64
+ return;
65
+ }
66
+ throw new Error("OpenAPI sources changed repeatedly while being generated");
67
+ }
68
+ catch (error) {
69
+ const watcherRestoreNeeded = error instanceof OpenApiWatcherRestoreNeededError;
70
+ if (successfulApplications === 0 &&
71
+ !(error instanceof OpenApiRestoreError) &&
72
+ !watcherRestoreNeeded) {
73
+ throw error;
74
+ }
75
+ try {
76
+ await this.restorePreviousRefresh(previousRegistry, previousSpecs, previousSpecs !== specs || watcherRestoreNeeded);
77
+ }
78
+ catch (rollbackError) {
79
+ throw new AggregateError([error, rollbackError], "Unable to refresh or restore the previous OpenAPI reference");
80
+ }
81
+ throw watcherRestoreNeeded ? error.originalError : error;
82
+ }
83
+ }
84
+ async restorePreviousRefresh(fallbackRegistry, specs, verifySources) {
85
+ if (!verifySources || specs.length === 0) {
86
+ await this.applyRefresh(fallbackRegistry, specs);
87
+ return;
88
+ }
89
+ let candidate;
90
+ try {
91
+ candidate = await this.loadStableRegistry(specs);
92
+ }
93
+ catch {
94
+ // Invalid previous sources still retain their last successful output.
95
+ await this.applyRefresh(fallbackRegistry, specs);
96
+ return;
97
+ }
98
+ for (let attempt = 0; attempt < 4; attempt += 1) {
99
+ await this.applyRefresh(candidate.registry, specs);
100
+ if ((await this.sourceState(candidate.registry)) === candidate.sourceState) {
101
+ return;
102
+ }
103
+ if (attempt < 3)
104
+ candidate = await this.loadStableRegistry(specs);
105
+ }
106
+ throw new Error("Previous OpenAPI sources changed repeatedly while being restored");
107
+ }
108
+ async applyRefresh(nextRegistry, nextSpecs) {
109
+ const previousRegistry = this.options.getRegistry();
110
+ const previousSpecs = this.options.getSpecs();
111
+ const previousSections = this.options.getSections();
112
+ const previousRoutes = this.options.getOpenApiRoutes();
113
+ const candidateRoutes = new Map();
114
+ let watcherSyncAttempted = false;
115
+ try {
116
+ this.options.setRegistry(nextRegistry);
117
+ this.options.setSpecs(nextSpecs);
118
+ this.options.setSections(await this.options.resolveSections());
119
+ await this.options.writeApiPages(undefined, {
120
+ writtenRoutes: candidateRoutes,
121
+ });
122
+ await this.options.refreshSiteAggregates();
123
+ watcherSyncAttempted = true;
124
+ await this.options.syncWatcher();
125
+ }
126
+ catch (error) {
127
+ this.options.setRegistry(previousRegistry);
128
+ this.options.setSpecs(previousSpecs);
129
+ this.options.setSections(previousSections);
130
+ const rollbackErrors = [];
131
+ if (watcherSyncAttempted) {
132
+ try {
133
+ await this.options.syncWatcher();
134
+ }
135
+ catch (rollbackError) {
136
+ rollbackErrors.push(rollbackError);
137
+ }
138
+ }
139
+ const previousSlugs = new Set(previousRoutes.map((route) => route.slug));
140
+ const occupiedMdxSlugs = new Set(this.options.getSuccessfulMdxPages().map((page) => page.slug));
141
+ for (const slug of new Set(candidateRoutes.values())) {
142
+ if (previousSlugs.has(slug) || occupiedMdxSlugs.has(slug))
143
+ continue;
144
+ try {
145
+ await this.options.removeOwnedRoute(slug);
146
+ }
147
+ catch (rollbackError) {
148
+ rollbackErrors.push(rollbackError);
149
+ }
150
+ }
151
+ try {
152
+ await this.options.writeApiPages(undefined, {
153
+ additionalPreviousRoutes: [...candidateRoutes].map(([source, slug]) => ({ kind: "openapi", source, slug })),
154
+ });
155
+ await this.options.refreshSiteAggregates();
156
+ }
157
+ catch (rollbackError) {
158
+ rollbackErrors.push(rollbackError);
159
+ }
160
+ if (rollbackErrors.length > 0) {
161
+ throw new OpenApiRestoreError([error, ...rollbackErrors], "Unable to apply or restore the OpenAPI reference");
162
+ }
163
+ if (watcherSyncAttempted) {
164
+ throw new OpenApiWatcherRestoreNeededError(error);
165
+ }
166
+ throw error;
167
+ }
168
+ }
169
+ async handleOpenApiChange() {
170
+ console.log(chalk.cyan("📘 OpenAPI spec changed - regenerating API reference"));
171
+ try {
172
+ await this.applyStableRefresh(this.options.getSpecs());
173
+ console.log(chalk.green("✅ API reference updated"));
174
+ }
175
+ catch (error) {
176
+ console.error(chalk.red("❌ Error updating API reference:"), error);
177
+ }
178
+ }
179
+ async handleConfigChange() {
180
+ const configPath = path.join(this.options.rootDir, this.options.configFile);
181
+ let config;
182
+ try {
183
+ const { data } = await this.options.sourceFs.readProjectSourceFile(configPath, "Doccupine configuration source");
184
+ config = validateConfig(JSON.parse(data.toString("utf8")), this.options.rootDir);
185
+ }
186
+ catch (error) {
187
+ console.warn(chalk.yellow("⚠️ doccupine.json is missing or invalid - keeping the current configuration"), error instanceof Error ? error.message : error);
188
+ return;
189
+ }
190
+ if ((config.watchDir &&
191
+ path.resolve(this.options.rootDir, config.watchDir) !==
192
+ this.options.watchDir) ||
193
+ (config.outputDir &&
194
+ path.resolve(this.options.rootDir, config.outputDir) !==
195
+ this.options.outputDir)) {
196
+ console.log(chalk.yellow("⚠️ watchDir/outputDir changes in doccupine.json need a restart to apply"));
197
+ }
198
+ const nextSpecs = normalizeOpenApiConfig(config.openapi);
199
+ if (JSON.stringify(nextSpecs) === JSON.stringify(this.options.getSpecs())) {
200
+ return;
201
+ }
202
+ console.log(chalk.cyan("📘 OpenAPI configuration changed - updating API reference"));
203
+ try {
204
+ await this.applyStableRefresh(nextSpecs);
205
+ console.log(chalk.green("✅ API reference updated"));
206
+ }
207
+ catch (error) {
208
+ console.error(chalk.red("❌ Error updating API reference:"), error);
209
+ }
210
+ }
211
+ }
@@ -2,6 +2,22 @@ import { generateJsonLdScript, generateMetadataBlock, generateRuntimeOnlyMetadat
2
2
  import { parseUpdateBlocks } from "../lib/rss.js";
3
3
  import { escapeTemplateContent, toJsStringLiteral } from "../lib/utils.js";
4
4
  import { rssRouteTemplate } from "../templates/app/rssRoute.js";
5
+ /**
6
+ * The `const operation = JSON.parse(...)` declaration that carries an endpoint
7
+ * descriptor into a generated page. `toJsStringLiteral` picks the quote
8
+ * Prettier would, and the width check reproduces its break-after-operator
9
+ * choice, so the emitted file is already formatted.
10
+ */
11
+ function apiOperationDeclaration(apiOperation) {
12
+ if (!apiOperation)
13
+ return "";
14
+ const arg = toJsStringLiteral(JSON.stringify(apiOperation));
15
+ const inline = `const operation = JSON.parse(${arg});`;
16
+ const decl = inline.length <= 80
17
+ ? inline
18
+ : `const operation = JSON.parse(\n ${arg},\n);`;
19
+ return `\n${decl}\n`;
20
+ }
5
21
  export function renderMdxPage(mdxFile, options) {
6
22
  const fm = mdxFile.frontmatter;
7
23
  const apiOperation = options?.apiOperation;
@@ -36,16 +52,7 @@ export function renderMdxPage(mdxFile, options) {
36
52
  const apiImport = apiOperation
37
53
  ? `\nimport { ApiPlayground } from "@/components/layout/ApiPlayground";`
38
54
  : "";
39
- const apiConst = apiOperation
40
- ? (() => {
41
- const arg = toJsStringLiteral(JSON.stringify(apiOperation));
42
- const inline = `const operation = JSON.parse(${arg});`;
43
- const decl = inline.length <= 80
44
- ? inline
45
- : `const operation = JSON.parse(\n ${arg},\n);`;
46
- return `\n${decl}\n`;
47
- })()
48
- : "";
55
+ const apiConst = apiOperationDeclaration(apiOperation);
49
56
  const sourcePathLiteral = JSON.stringify(mdxFile.path);
50
57
  const showRssButton = hasFeed && fm.rss === true && !apiOperation;
51
58
  const docsAttrs = [
@@ -134,9 +141,7 @@ export function renderHomepage(indexMDX, apiOperation) {
134
141
  const apiImport = apiOperation
135
142
  ? `\nimport { ApiPlayground } from "@/components/layout/ApiPlayground";`
136
143
  : "";
137
- const apiConst = apiOperation
138
- ? `\nconst operation = JSON.parse(${JSON.stringify(JSON.stringify(apiOperation))});\n`
139
- : "";
144
+ const apiConst = apiOperationDeclaration(apiOperation);
140
145
  const showRssButton = hasFeed && indexMDX?.rss === true && !apiOperation;
141
146
  const docsElement = apiOperation
142
147
  ? `<Docs content={content} sourcePath="index.mdx">
@@ -0,0 +1,10 @@
1
+ import type { PageMeta, SectionConfig } from "../lib/types.js";
2
+ import { GeneratedRouteManager } from "./generated-route-manager.js";
3
+ type WriteRedirect = (slug: string, target: string) => Promise<void>;
4
+ export declare class SectionIndexGenerator {
5
+ private readonly outputDir;
6
+ private readonly routeManager;
7
+ constructor(outputDir: string, routeManager: GeneratedRouteManager);
8
+ generate(pages: PageMeta[], sections: SectionConfig[] | null, declaredSlugs: Set<string> | undefined, writeRedirect: WriteRedirect): Promise<void>;
9
+ }
10
+ export {};
@@ -0,0 +1,68 @@
1
+ import fs from "fs-extra";
2
+ import { readOutputFileIfPresent, resolveOutputPath, } from "../lib/output-safety.js";
3
+ import { writeFileAtomic } from "../lib/utils.js";
4
+ export class SectionIndexGenerator {
5
+ outputDir;
6
+ routeManager;
7
+ constructor(outputDir, routeManager) {
8
+ this.outputDir = outputDir;
9
+ this.routeManager = routeManager;
10
+ }
11
+ async generate(pages, sections, declaredSlugs, writeRedirect) {
12
+ const occupiedSlugs = new Set(pages.map((page) => page.slug));
13
+ const resolvedDeclaredSlugs = new Set(occupiedSlugs);
14
+ for (const slug of declaredSlugs ?? [])
15
+ resolvedDeclaredSlugs.add(slug);
16
+ const redirects = new Map();
17
+ for (const section of sections ?? []) {
18
+ if (section.slug === "" || resolvedDeclaredSlugs.has(section.slug)) {
19
+ continue;
20
+ }
21
+ const sectionPages = pages
22
+ .filter((page) => page.section === section.slug)
23
+ .sort((a, b) => {
24
+ if (a.categoryOrder !== b.categoryOrder) {
25
+ return a.categoryOrder - b.categoryOrder;
26
+ }
27
+ return a.order - b.order;
28
+ });
29
+ const firstPage = sectionPages[0];
30
+ if (firstPage)
31
+ redirects.set(section.slug, firstPage.slug);
32
+ }
33
+ const previousSlugs = this.routeManager.sectionIndexSlugs();
34
+ const touchedSlugs = new Set([...previousSlugs, ...redirects.keys()]);
35
+ const previousFiles = new Map();
36
+ for (const slug of touchedSlugs) {
37
+ previousFiles.set(slug, await readOutputFileIfPresent(this.outputDir, "app", "(site)", slug, "page.tsx"));
38
+ }
39
+ try {
40
+ for (const [slug, target] of redirects) {
41
+ await writeRedirect(slug, target);
42
+ }
43
+ await this.routeManager.cleanupStaleSectionIndexPages(new Set(redirects.keys()), occupiedSlugs, (dir, stopDir) => this.routeManager.removeEmptyDirsUpTo(dir, stopDir));
44
+ }
45
+ catch (error) {
46
+ const rollbackErrors = [];
47
+ this.routeManager.replaceSectionIndexSlugs(previousSlugs);
48
+ for (const [slug, content] of previousFiles) {
49
+ try {
50
+ const target = resolveOutputPath(this.outputDir, "app", "(site)", slug, "page.tsx");
51
+ if (content === null) {
52
+ await fs.remove(target);
53
+ }
54
+ else {
55
+ await writeFileAtomic(target, content);
56
+ }
57
+ }
58
+ catch (rollbackError) {
59
+ rollbackErrors.push(rollbackError);
60
+ }
61
+ }
62
+ if (rollbackErrors.length > 0) {
63
+ throw new AggregateError([error, ...rollbackErrors], "Unable to generate or restore section index redirects");
64
+ }
65
+ throw error;
66
+ }
67
+ }
68
+ }
@@ -4,6 +4,7 @@ import { constants } from "node:fs";
4
4
  import { open } from "node:fs/promises";
5
5
  import path from "node:path";
6
6
  import { isPathInside, resolveWithin } from "../lib/output-safety.js";
7
+ import { isMdxPath } from "../lib/utils.js";
7
8
  function errorCode(error) {
8
9
  return error && typeof error === "object" && "code" in error
9
10
  ? String(error.code)
@@ -124,7 +125,7 @@ export class SecureSourceFs {
124
125
  }
125
126
  }
126
127
  async readMdxSourceFile(filePath) {
127
- if (!filePath.toLowerCase().endsWith(".mdx")) {
128
+ if (!isMdxPath(filePath)) {
128
129
  throw this.sourcePathError("documentation source", filePath, "expected an .mdx file");
129
130
  }
130
131
  const { data, stat } = await this.readSafeSourceFile(this.documentationRoot, path.resolve(this.documentationRoot, filePath), "documentation source", false);
@@ -396,7 +397,7 @@ export class SecureSourceFs {
396
397
  if (errorCode(error) !== "ENOENT")
397
398
  throw error;
398
399
  }
399
- if (entry.name.endsWith(".mdx") || linksToDirectory) {
400
+ if (isMdxPath(entry.name) || linksToDirectory) {
400
401
  throw this.sourcePathError("documentation source", fullPath, "the path is a symbolic link");
401
402
  }
402
403
  continue;
@@ -408,10 +409,10 @@ export class SecureSourceFs {
408
409
  if (stat.isDirectory()) {
409
410
  await scanDir(fullPath, relPath);
410
411
  }
411
- else if (stat.isFile() && entry.name.endsWith(".mdx")) {
412
+ else if (stat.isFile() && isMdxPath(entry.name)) {
412
413
  files.push(relPath);
413
414
  }
414
- else if (!stat.isFile() && entry.name.endsWith(".mdx")) {
415
+ else if (!stat.isFile() && isMdxPath(entry.name)) {
415
416
  throw this.sourcePathError("documentation source", fullPath, "expected a regular .mdx file");
416
417
  }
417
418
  }
@@ -1,7 +1,7 @@
1
1
  import chalk from "chalk";
2
2
  import fs from "fs-extra";
3
3
  import { resolveOutputPath } from "../lib/output-safety.js";
4
- import { safeMatter, writeFileAtomic } from "../lib/utils.js";
4
+ import { isMdxPath, safeMatter, writeFileAtomic } from "../lib/utils.js";
5
5
  import { robotsTemplate } from "../templates/app/robots.js";
6
6
  import { sitemapTemplate, } from "../templates/app/sitemap.js";
7
7
  import { llmsFullTemplate, } from "../templates/llms/llmsFull.js";
@@ -100,7 +100,7 @@ export async function writeRobots(outputDir, resolveSiteUrl) {
100
100
  }
101
101
  export async function collectPageBodies(pages, readMdxSource, readOpenApiBody) {
102
102
  return Promise.all(pages.map(async (page) => {
103
- if (!page.path.endsWith(".mdx")) {
103
+ if (!isMdxPath(page.path)) {
104
104
  return { ...page, body: readOpenApiBody(page.slug) ?? "" };
105
105
  }
106
106
  const { content: raw } = await readMdxSource(page.path);
@@ -42,17 +42,25 @@ export declare class WatchCoordinator {
42
42
  private mutationQueue;
43
43
  private stopping;
44
44
  private readyCancellations;
45
+ private pendingWatcherClosures;
45
46
  private sourceSnapshot;
46
47
  private publicWatcherStarting;
48
+ private publicWatcherRestartRequested;
47
49
  constructor(options: WatchCoordinatorOptions);
48
50
  private enqueueMutation;
51
+ private closeDetachedWatcher;
49
52
  private waitForWatcherReady;
53
+ private trackWatcherReady;
54
+ private waitForPublicWatcherReady;
50
55
  private captureSourceSnapshot;
51
56
  establishSourceSnapshot(projectSourceStates?: Readonly<Record<string, string>>, openApiSourceState?: string, doccupineSourceState?: string): Promise<void>;
52
57
  private reconcileWatchedSources;
53
58
  startWatching(): Promise<void>;
59
+ private startWatchers;
54
60
  private setupPublicWatcher;
55
61
  syncOpenApiSpecWatcher(specs: readonly NormalizedOpenApiSpec[], sourceFiles?: readonly string[]): Promise<void>;
56
62
  stop(): Promise<void>;
63
+ private drainMutationQueue;
64
+ private closeCurrentWatchers;
57
65
  }
58
66
  export {};