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,7 @@
1
1
  import fs from "fs-extra";
2
+ import { randomBytes } from "node:crypto";
3
+ import { constants } from "node:fs";
4
+ import { open, unlink } from "node:fs/promises";
2
5
  import path from "path";
3
6
  import chalk from "chalk";
4
7
  import prompts from "prompts";
@@ -6,6 +9,181 @@ import { isPathInside } from "./output-safety.js";
6
9
  function pathsOverlap(a, b) {
7
10
  return isPathInside(a, b) || isPathInside(b, a);
8
11
  }
12
+ function errorCode(error) {
13
+ return error && typeof error === "object" && "code" in error
14
+ ? String(error.code)
15
+ : undefined;
16
+ }
17
+ function sameFile(left, right) {
18
+ return left.dev === right.dev && left.ino === right.ino;
19
+ }
20
+ function configPathError(configPath, detail) {
21
+ return new Error(`Refusing to use ${configPath}: ${detail}`);
22
+ }
23
+ async function inspectConfigPath(projectRoot, configPath, allowMissingAncestor) {
24
+ if (!isPathInside(projectRoot, configPath)) {
25
+ throw configPathError(configPath, `the configuration path is outside the project root ${projectRoot}.`);
26
+ }
27
+ const relativePath = path.relative(projectRoot, configPath);
28
+ const paths = [
29
+ projectRoot,
30
+ ...relativePath
31
+ .split(path.sep)
32
+ .filter(Boolean)
33
+ .map((_, index, components) => path.join(projectRoot, ...components.slice(0, index + 1))),
34
+ ];
35
+ const entries = [];
36
+ for (const [index, currentPath] of paths.entries()) {
37
+ const isFinal = index === paths.length - 1;
38
+ let stat;
39
+ try {
40
+ stat = await fs.lstat(currentPath);
41
+ }
42
+ catch (error) {
43
+ if (errorCode(error) === "ENOENT") {
44
+ if (allowMissingAncestor)
45
+ return null;
46
+ if (isFinal)
47
+ return { entries };
48
+ }
49
+ throw error;
50
+ }
51
+ if (stat.isSymbolicLink()) {
52
+ throw configPathError(configPath, `${currentPath} is a symbolic link. Replace it with a real file or directory inside the project root.`);
53
+ }
54
+ if (!isFinal && !stat.isDirectory()) {
55
+ throw configPathError(configPath, `${currentPath} is not a directory.`);
56
+ }
57
+ entries.push({ filePath: currentPath, stat });
58
+ }
59
+ return {
60
+ entries,
61
+ finalStat: entries.at(-1)?.stat,
62
+ };
63
+ }
64
+ async function assertPathEntriesUnchanged(configPath, entries) {
65
+ for (const entry of entries) {
66
+ let currentStat;
67
+ try {
68
+ currentStat = await fs.lstat(entry.filePath);
69
+ }
70
+ catch {
71
+ throw configPathError(configPath, `${entry.filePath} changed during the configuration operation.`);
72
+ }
73
+ if (currentStat.isSymbolicLink() || !sameFile(entry.stat, currentStat)) {
74
+ throw configPathError(configPath, `${entry.filePath} changed during the configuration operation.`);
75
+ }
76
+ }
77
+ }
78
+ async function readConfigFile(projectRoot, configPath) {
79
+ const inspected = await inspectConfigPath(projectRoot, configPath, true);
80
+ if (!inspected)
81
+ return null;
82
+ if (!inspected.finalStat?.isFile()) {
83
+ throw configPathError(configPath, "expected a regular configuration file.");
84
+ }
85
+ const noFollow = typeof constants.O_NOFOLLOW === "number" ? constants.O_NOFOLLOW : 0;
86
+ let handle;
87
+ try {
88
+ handle = await open(configPath, constants.O_RDONLY | noFollow);
89
+ }
90
+ catch (error) {
91
+ if (errorCode(error) === "ELOOP") {
92
+ throw configPathError(configPath, "the configuration file became a symbolic link while it was being opened.");
93
+ }
94
+ throw error;
95
+ }
96
+ try {
97
+ const beforeRead = await handle.stat();
98
+ if (!beforeRead.isFile() || !sameFile(inspected.finalStat, beforeRead)) {
99
+ throw configPathError(configPath, "the configuration file changed while it was being opened.");
100
+ }
101
+ await assertPathEntriesUnchanged(configPath, inspected.entries);
102
+ const content = await handle.readFile("utf8");
103
+ const afterRead = await handle.stat();
104
+ if (!sameFile(beforeRead, afterRead) ||
105
+ beforeRead.size !== afterRead.size ||
106
+ beforeRead.mtimeMs !== afterRead.mtimeMs ||
107
+ beforeRead.ctimeMs !== afterRead.ctimeMs) {
108
+ throw configPathError(configPath, "the configuration file changed while it was being read.");
109
+ }
110
+ await assertPathEntriesUnchanged(configPath, inspected.entries);
111
+ return content;
112
+ }
113
+ finally {
114
+ await handle.close();
115
+ }
116
+ }
117
+ async function createConfigTempFile(configPath, mode) {
118
+ const noFollow = typeof constants.O_NOFOLLOW === "number" ? constants.O_NOFOLLOW : 0;
119
+ const flags = constants.O_WRONLY | constants.O_CREAT | constants.O_EXCL | noFollow;
120
+ for (let attempt = 0; attempt < 10; attempt += 1) {
121
+ const tempPath = path.join(path.dirname(configPath), `.doccupine-config-${process.pid}-${randomBytes(16).toString("hex")}.tmp`);
122
+ try {
123
+ return { handle: await open(tempPath, flags, mode), tempPath };
124
+ }
125
+ catch (error) {
126
+ if (errorCode(error) !== "EEXIST")
127
+ throw error;
128
+ }
129
+ }
130
+ throw new Error(`Unable to create a unique temporary file for ${configPath}`);
131
+ }
132
+ async function removeConfigTempFile(tempPath) {
133
+ try {
134
+ await unlink(tempPath);
135
+ }
136
+ catch (error) {
137
+ if (errorCode(error) !== "ENOENT")
138
+ throw error;
139
+ }
140
+ }
141
+ async function writeConfigFileAtomic(projectRoot, configPath, content) {
142
+ const inspected = await inspectConfigPath(projectRoot, configPath, false);
143
+ if (inspected?.finalStat && !inspected.finalStat.isFile()) {
144
+ throw configPathError(configPath, "expected a regular configuration file.");
145
+ }
146
+ const parentEntries = inspected?.entries.filter((entry) => entry.filePath !== configPath) ?? [];
147
+ const mode = inspected?.finalStat?.isFile()
148
+ ? inspected.finalStat.mode & 0o777
149
+ : 0o666;
150
+ let handle;
151
+ let tempPath;
152
+ try {
153
+ ({ handle, tempPath } = await createConfigTempFile(configPath, mode));
154
+ if (inspected?.finalStat?.isFile())
155
+ await handle.chmod(mode);
156
+ await assertPathEntriesUnchanged(configPath, parentEntries);
157
+ await inspectConfigPath(projectRoot, configPath, false);
158
+ await handle.writeFile(content, "utf8");
159
+ await handle.sync();
160
+ await handle.close();
161
+ handle = undefined;
162
+ await assertPathEntriesUnchanged(configPath, parentEntries);
163
+ await inspectConfigPath(projectRoot, configPath, false);
164
+ await fs.rename(tempPath, configPath);
165
+ tempPath = undefined;
166
+ }
167
+ catch (error) {
168
+ if (handle) {
169
+ try {
170
+ await handle.close();
171
+ }
172
+ catch {
173
+ // Preserve the original write error.
174
+ }
175
+ }
176
+ if (tempPath) {
177
+ try {
178
+ await removeConfigTempFile(tempPath);
179
+ }
180
+ catch {
181
+ // Cleanup is best effort and must not hide the original error.
182
+ }
183
+ }
184
+ throw error;
185
+ }
186
+ }
9
187
  function isValidOpenApiConfig(value) {
10
188
  if (value === undefined || typeof value === "string")
11
189
  return true;
@@ -177,32 +355,36 @@ export function normalizeConfigPaths(config, rootDir = process.cwd()) {
177
355
  }
178
356
  export class ConfigManager {
179
357
  configPath;
358
+ projectRoot;
180
359
  constructor(configPath = "doccupine.json") {
181
- this.configPath = path.resolve(process.cwd(), configPath);
360
+ this.projectRoot = path.resolve(process.cwd());
361
+ this.configPath = path.resolve(this.projectRoot, configPath);
182
362
  }
183
363
  async loadConfig() {
184
364
  try {
185
- if (await fs.pathExists(this.configPath)) {
186
- const configContent = await fs.readFile(this.configPath, "utf8");
187
- const config = validateConfig(JSON.parse(configContent));
188
- console.log(chalk.blue("📄 Using existing configuration from doccupine.json"));
189
- return config;
190
- }
365
+ const configContent = await readConfigFile(this.projectRoot, this.configPath);
366
+ if (configContent === null)
367
+ return null;
368
+ const config = validateConfig(JSON.parse(configContent), this.projectRoot);
369
+ console.log(chalk.blue("📄 Using existing configuration from doccupine.json"));
370
+ return config;
191
371
  }
192
372
  catch (error) {
193
- if (await fs.pathExists(this.configPath)) {
194
- throw new Error(`Unable to use ${this.configPath}: ${error instanceof Error ? error.message : String(error)}. Run "doccupine config --reset" to repair the configuration.`);
195
- }
373
+ const message = error instanceof Error ? error.message : String(error);
374
+ const symlinkRepair = message.includes("symbolic link")
375
+ ? " Remove or replace the symbolic link first."
376
+ : "";
377
+ throw new Error(`Unable to use ${this.configPath}: ${message}.${symlinkRepair} Run "doccupine config --reset" to repair the configuration.`);
196
378
  }
197
- return null;
198
379
  }
199
380
  async saveConfig(config) {
200
381
  try {
201
- await fs.writeFile(this.configPath, `${JSON.stringify(config, null, 2)}\n`, "utf8");
382
+ await writeConfigFileAtomic(this.projectRoot, this.configPath, `${JSON.stringify(config, null, 2)}\n`);
202
383
  console.log(chalk.green("💾 Configuration saved to doccupine.json"));
203
384
  }
204
385
  catch (error) {
205
386
  console.error(chalk.red("❌ Error saving config file:"), error);
387
+ throw error;
206
388
  }
207
389
  }
208
390
  async promptForConfig(existingConfig) {
@@ -1,5 +1,5 @@
1
1
  export type RouteOwnerKind = "mdx" | "openapi";
2
- interface RouteArtifact {
2
+ export interface RouteArtifact {
3
3
  kind: RouteOwnerKind;
4
4
  source: string;
5
5
  slug: string;
@@ -15,15 +15,21 @@ export declare class GeneratedArtifacts {
15
15
  load(): Promise<void>;
16
16
  routeFor(kind: RouteOwnerKind, source: string): string | undefined;
17
17
  routesFor(kind: RouteOwnerKind): RouteArtifact[];
18
+ private routesWithReplacement;
18
19
  replaceRoutes(kind: RouteOwnerKind, routes: Iterable<{
19
20
  source: string;
20
21
  slug: string;
21
22
  }>): void;
23
+ replaceRoutesAndSave(kind: RouteOwnerKind, routes: Iterable<{
24
+ source: string;
25
+ slug: string;
26
+ }>): Promise<void>;
22
27
  removeRoute(kind: RouteOwnerKind, source: string): void;
28
+ removeRouteAndSave(kind: RouteOwnerKind, source: string): Promise<void>;
23
29
  llmsPageFiles(): Set<string>;
24
30
  replaceLlmsPageFiles(files: Iterable<string>): void;
25
31
  publicFiles(): Set<string>;
26
32
  replacePublicFiles(files: Iterable<string>): void;
33
+ private writeManifest;
27
34
  save(): Promise<void>;
28
35
  }
29
- export {};
@@ -119,22 +119,38 @@ export class GeneratedArtifacts {
119
119
  routesFor(kind) {
120
120
  return [...this.routes.values()].filter((route) => route.kind === kind);
121
121
  }
122
- replaceRoutes(kind, routes) {
123
- for (const [key, route] of this.routes) {
122
+ routesWithReplacement(kind, routes) {
123
+ const next = new Map(this.routes);
124
+ for (const [key, route] of next) {
124
125
  if (route.kind === kind)
125
- this.routes.delete(key);
126
+ next.delete(key);
126
127
  }
127
128
  for (const value of routes) {
128
129
  const route = normalizeRoute({ kind, ...value });
129
130
  if (!route) {
130
131
  throw new Error(`Refusing to record unsafe ${kind} route ownership`);
131
132
  }
132
- this.routes.set(this.routeKey(kind, route.source), route);
133
+ next.set(this.routeKey(kind, route.source), route);
133
134
  }
135
+ return next;
136
+ }
137
+ replaceRoutes(kind, routes) {
138
+ this.routes = this.routesWithReplacement(kind, routes);
139
+ }
140
+ async replaceRoutesAndSave(kind, routes) {
141
+ const next = this.routesWithReplacement(kind, routes);
142
+ await this.writeManifest(next);
143
+ this.routes = next;
134
144
  }
135
145
  removeRoute(kind, source) {
136
146
  this.routes.delete(this.routeKey(kind, source));
137
147
  }
148
+ async removeRouteAndSave(kind, source) {
149
+ const next = new Map(this.routes);
150
+ next.delete(this.routeKey(kind, source));
151
+ await this.writeManifest(next);
152
+ this.routes = next;
153
+ }
138
154
  llmsPageFiles() {
139
155
  return new Set(this.llmsFiles);
140
156
  }
@@ -161,13 +177,16 @@ export class GeneratedArtifacts {
161
177
  }
162
178
  this.publicFilePaths = next;
163
179
  }
164
- async save() {
180
+ async writeManifest(routes) {
165
181
  const manifest = {
166
182
  schemaVersion: 2,
167
- routes: [...this.routes.values()].sort((a, b) => `${a.kind}:${a.source}`.localeCompare(`${b.kind}:${b.source}`)),
183
+ routes: [...routes.values()].sort((a, b) => `${a.kind}:${a.source}`.localeCompare(`${b.kind}:${b.source}`)),
168
184
  llmsPageFiles: [...this.llmsFiles].sort(),
169
185
  publicFiles: [...this.publicFilePaths].sort(),
170
186
  };
171
187
  await writeFileAtomic(this.manifestPath(MANIFEST_FILE), `${JSON.stringify(manifest, null, 2)}\n`);
172
188
  }
189
+ async save() {
190
+ await this.writeManifest(this.routes);
191
+ }
173
192
  }
@@ -33,8 +33,12 @@ export declare class OpenApiRegistry {
33
33
  private pages;
34
34
  private bodies;
35
35
  private allowlistEntries;
36
+ private sourceFilePaths;
37
+ private sourceFingerprintValue;
36
38
  get all(): OperationDescriptor[];
37
39
  get isEmpty(): boolean;
40
+ get sourceFiles(): readonly string[];
41
+ get sourceFingerprint(): string;
38
42
  load(specs: NormalizedOpenApiSpec[], rootDir: string, apiBaseSlug?: string): Promise<void>;
39
43
  /** Fresh copies of the synthetic pages (caller may mutate/spread safely). */
40
44
  syntheticPages(): PageMeta[];
@@ -1,5 +1,6 @@
1
1
  import path from "path";
2
2
  import net from "node:net";
3
+ import { createHash } from "node:crypto";
3
4
  import { constants } from "node:fs";
4
5
  import fs from "node:fs/promises";
5
6
  import { fileURLToPath, pathToFileURL } from "node:url";
@@ -321,7 +322,18 @@ async function readOpenApiSnapshot(referenceRootRealPath, realPath, reference) {
321
322
  openedStat.ino !== currentStat.ino) {
322
323
  throw new Error(`OpenAPI file "${reference}" changed while being read`);
323
324
  }
324
- return await handle.readFile();
325
+ const contents = await handle.readFile();
326
+ const afterRead = await handle.stat();
327
+ if (openedStat.size !== afterRead.size ||
328
+ openedStat.mtimeMs !== afterRead.mtimeMs ||
329
+ openedStat.ctimeMs !== afterRead.ctimeMs) {
330
+ throw new Error(`OpenAPI file "${reference}" changed while being read`);
331
+ }
332
+ const hash = createHash("sha256").update(contents).digest("hex");
333
+ return {
334
+ contents,
335
+ state: `file:${openedStat.size}:${openedStat.mtimeMs}:${openedStat.dev}:${openedStat.ino}:${hash}`,
336
+ };
325
337
  }
326
338
  finally {
327
339
  await handle.close();
@@ -362,6 +374,7 @@ async function snapshotOpenApiDocuments(rootFile) {
362
374
  const referenceRootRealPath = path.dirname(rootFile);
363
375
  const byRealPath = new Map();
364
376
  const snapshots = new Map();
377
+ const sourceStates = new Map();
365
378
  const visit = async (candidate, reference, configuredRoot = false) => {
366
379
  if (!configuredRoot) {
367
380
  assertAllowedOpenApiReference(referenceRootRealPath, candidate, reference);
@@ -373,7 +386,8 @@ async function snapshotOpenApiDocuments(rootFile) {
373
386
  const existing = byRealPath.get(realPath);
374
387
  if (existing)
375
388
  return existing.url;
376
- const contents = await readOpenApiSnapshot(referenceRootRealPath, realPath, reference);
389
+ const { contents, state } = await readOpenApiSnapshot(referenceRootRealPath, realPath, reference);
390
+ sourceStates.set(realPath, state);
377
391
  const document = await parseOpenApiSnapshot(realPath, contents);
378
392
  const snapshotUrl = `file:///__doccupine_openapi_snapshot__/${byRealPath.size}.json`;
379
393
  byRealPath.set(realPath, { document, url: snapshotUrl });
@@ -401,7 +415,7 @@ async function snapshotOpenApiDocuments(rootFile) {
401
415
  return snapshotUrl;
402
416
  };
403
417
  const rootUrl = await visit(rootFile, rootFile, true);
404
- return { rootDocument: snapshots.get(rootUrl), snapshots };
418
+ return { rootDocument: snapshots.get(rootUrl), snapshots, sourceStates };
405
419
  }
406
420
  async function dereferenceOpenApiSnapshots(rootDocument, snapshots) {
407
421
  const snapshotResolver = parserFileResolver({
@@ -437,17 +451,26 @@ export class OpenApiRegistry {
437
451
  pages = [];
438
452
  bodies = new Map();
439
453
  allowlistEntries = [];
454
+ sourceFilePaths = [];
455
+ sourceFingerprintValue = "";
440
456
  get all() {
441
457
  return this.operations;
442
458
  }
443
459
  get isEmpty() {
444
460
  return this.operations.length === 0;
445
461
  }
462
+ get sourceFiles() {
463
+ return this.sourceFilePaths;
464
+ }
465
+ get sourceFingerprint() {
466
+ return this.sourceFingerprintValue;
467
+ }
446
468
  async load(specs, rootDir, apiBaseSlug = DEFAULT_API_BASE_SLUG) {
447
469
  const next = new OpenApiRegistry();
448
470
  const multi = specs.length > 1;
449
471
  const usedSlugs = new Set();
450
472
  const allowlistKeys = new Set();
473
+ const sourceStates = new Map();
451
474
  const rootRealPath = specs.length > 0 ? await fs.realpath(rootDir) : path.resolve(rootDir);
452
475
  for (const spec of specs) {
453
476
  let doc;
@@ -459,7 +482,10 @@ export class OpenApiRegistry {
459
482
  ? path.normalize(spec.file)
460
483
  : path.resolve(rootDir, spec.file);
461
484
  const absolute = await resolveLocalOpenApiFile(rootRealPath, configuredPath, spec.file, "rootDir");
462
- const { rootDocument, snapshots } = await snapshotOpenApiDocuments(absolute);
485
+ const { rootDocument, snapshots, sourceStates: capturedSourceStates, } = await snapshotOpenApiDocuments(absolute);
486
+ for (const [sourcePath, state] of capturedSourceStates) {
487
+ sourceStates.set(sourcePath, state);
488
+ }
463
489
  doc = await dereferenceOpenApiSnapshots(rootDocument, snapshots);
464
490
  }
465
491
  catch (error) {
@@ -472,6 +498,10 @@ export class OpenApiRegistry {
472
498
  throw new Error(`Failed to process OpenAPI spec "${spec.file}": ${error instanceof Error ? error.message : String(error)}`, { cause: error });
473
499
  }
474
500
  }
501
+ next.sourceFilePaths = [...sourceStates.keys()].sort();
502
+ next.sourceFingerprintValue = next.sourceFilePaths
503
+ .map((sourcePath) => `${sourcePath}:${sourceStates.get(sourcePath)}`)
504
+ .join("\n");
475
505
  if (next.operations.length > 0) {
476
506
  const body = buildApiIndexBody(next.operations);
477
507
  next.pages.unshift({
@@ -493,6 +523,8 @@ export class OpenApiRegistry {
493
523
  this.pages = next.pages;
494
524
  this.bodies = next.bodies;
495
525
  this.allowlistEntries = next.allowlistEntries;
526
+ this.sourceFilePaths = next.sourceFilePaths;
527
+ this.sourceFingerprintValue = next.sourceFingerprintValue;
496
528
  }
497
529
  /** Fresh copies of the synthetic pages (caller may mutate/spread safely). */
498
530
  syntheticPages() {
@@ -3,6 +3,7 @@ import { open } from "node:fs/promises";
3
3
  import path from "node:path";
4
4
  const MARKER_FILE = ".doccupine-generated.json";
5
5
  const SAFE_UNOWNED_FILES = new Set([".DS_Store", ".gitkeep", ".env"]);
6
+ const SAFE_UNOWNED_CACHE_DIRECTORIES = new Set([".next", "node_modules"]);
6
7
  const GENERATED_SUBTREES = new Set([
7
8
  "app",
8
9
  "components",
@@ -60,8 +61,13 @@ const LEGACY_FILE_FINGERPRINTS = [
60
61
  ],
61
62
  },
62
63
  ];
63
- function isSafeUnownedEntry(name) {
64
- return SAFE_UNOWNED_FILES.has(name) || name.startsWith(".env.");
64
+ async function isSafeUnownedEntry(outputDir, name) {
65
+ if (SAFE_UNOWNED_FILES.has(name) || name.startsWith(".env."))
66
+ return true;
67
+ if (!SAFE_UNOWNED_CACHE_DIRECTORIES.has(name))
68
+ return false;
69
+ const stat = await lstatIfPresent(path.join(outputDir, name));
70
+ return stat?.isDirectory() === true;
65
71
  }
66
72
  export function isPathInside(parent, candidate) {
67
73
  const relative = path.relative(path.resolve(parent), path.resolve(candidate));
@@ -409,7 +415,8 @@ export async function claimOutputDirectory(outputDir) {
409
415
  return;
410
416
  }
411
417
  const entries = await fs.readdir(realOutputDir);
412
- const canClaim = entries.every(isSafeUnownedEntry) ||
418
+ const safeUnownedEntries = await Promise.all(entries.map((name) => isSafeUnownedEntry(realOutputDir, name)));
419
+ const canClaim = safeUnownedEntries.every(Boolean) ||
413
420
  (await looksLikeLegacyGeneratedApp(realOutputDir));
414
421
  if (!canClaim) {
415
422
  throw new Error(`Refusing to overwrite non-empty directory ${outputDir}. Choose an empty outputDir or a Doccupine-generated directory.`);
@@ -1,5 +1,8 @@
1
1
  import type { MDXFile, PageMeta, SectionConfig, FontConfig, AnalyticsConfig, NormalizedOpenApiSpec } from "./lib/types.js";
2
2
  import type { OperationDescriptor } from "./lib/openapi-types.js";
3
+ interface GeneratedPageCommit {
4
+ rollback(): Promise<void>;
5
+ }
3
6
  export declare class MDXToNextJSGenerator {
4
7
  private watchDir;
5
8
  private outputDir;
@@ -20,14 +23,25 @@ export declare class MDXToNextJSGenerator {
20
23
  private sourceFs;
21
24
  private appScaffolder;
22
25
  private apiReferenceGenerator;
26
+ private generatedPagePublisher;
23
27
  private generatedRouteManager;
28
+ private mdxPassBuilder;
29
+ private openApiRefreshCoordinator;
30
+ private sectionIndexGenerator;
24
31
  private projectConfigRepository;
25
32
  private publicAssetManager;
26
33
  private watchCoordinator;
34
+ private retainExistingMdxOutput;
35
+ private mdxSnapshotInitialized;
36
+ private successfulMdxPages;
37
+ private successfulMdxContent;
38
+ private successfulMdxSourcesBySlug;
39
+ private collisionBlockedMdxSources;
27
40
  constructor(watchDir: string, outputDir: string, openApiSpecs?: NormalizedOpenApiSpec[], rootDir?: string);
28
41
  private outputPath;
29
42
  private readMdxSourceFile;
30
- private ensureSafeStarterPath;
43
+ private writeStarterFilesIfEmpty;
44
+ private refreshInitialDoccupineConfig;
31
45
  init(): Promise<void>;
32
46
  createNextJSStructure(): Promise<void>;
33
47
  createStartingDocs(): Promise<void>;
@@ -48,6 +62,7 @@ export declare class MDXToNextJSGenerator {
48
62
  private withApiReferenceSection;
49
63
  private reloadSections;
50
64
  private maybeUpdateSections;
65
+ private reconcileMdxSources;
51
66
  private determineSectionForFile;
52
67
  handleConfigFileChange(filePath: string): Promise<void>;
53
68
  handleConfigFileDelete(filePath: string): Promise<void>;
@@ -59,9 +74,23 @@ export declare class MDXToNextJSGenerator {
59
74
  handlePublicFileChange(filePath: string): Promise<void>;
60
75
  handlePublicFileDelete(filePath: string): Promise<void>;
61
76
  startWatching(): Promise<void>;
62
- private parseMDXFile;
77
+ private captureMdxPass;
63
78
  private buildRealPagesMeta;
64
79
  private buildAllPagesMeta;
80
+ private mergeAllPagesMeta;
81
+ private successfulPagesInSourceOrder;
82
+ private recordSuccessfulMdxPage;
83
+ private removeSuccessfulMdxPage;
84
+ private captureSuccessfulMdxState;
85
+ private restoreSuccessfulMdxState;
86
+ private rollbackPageCommits;
87
+ private rollbackFailedMdxCommit;
88
+ private rollbackCommittedMdxChange;
89
+ private dropMissingMdxSnapshots;
90
+ private commitMdxSnapshot;
91
+ private refreshMdxDerivedOutput;
92
+ private readAggregateMdxSource;
93
+ private homepageSource;
65
94
  private removeOwnedRoute;
66
95
  private removeStaleMdxRoutes;
67
96
  /**
@@ -72,6 +101,7 @@ export declare class MDXToNextJSGenerator {
72
101
  * end instead of once per file (which is what made large builds O(n²)).
73
102
  */
74
103
  private writePageForFile;
104
+ private retryMdxPages;
75
105
  /**
76
106
  * Regenerates every file that depends on the full set of pages (pages index,
77
107
  * root/site layout, sitemap, llms files, section redirects). Parses all MDX
@@ -85,21 +115,11 @@ export declare class MDXToNextJSGenerator {
85
115
  getAllMDXFiles(): Promise<string[]>;
86
116
  generateRootLayout(): Promise<string>;
87
117
  generateSiteLayout(pages?: PageMeta[]): Promise<string>;
88
- generateSectionIndexPages(pages?: PageMeta[]): Promise<void>;
89
- /**
90
- * Removes section index redirects written earlier in this session whose
91
- * section has since disappeared (e.g. the API Reference section after the
92
- * `openapi` config is removed mid-watch). Only files that still contain the
93
- * generated redirect are deleted, so a hand-written page that has taken
94
- * over the slug is never touched. Fresh processes start clean anyway -
95
- * init() wipes app/ - so in-session tracking is enough.
96
- */
97
- private cleanupStaleSectionIndexPages;
98
- /** Best-effort removal of now-empty directories up to (not incl.) stopDir. */
99
- private removeEmptyDirsUpTo;
118
+ generateSectionIndexPages(pages?: PageMeta[], declaredSlugs?: Set<string>): Promise<void>;
119
+ private writeSectionIndexRedirect;
100
120
  generatePageFromMDX(mdxFile: MDXFile, options?: {
101
121
  apiOperation?: OperationDescriptor;
102
- }): Promise<void>;
122
+ }): Promise<GeneratedPageCommit>;
103
123
  /** Parses the configured OpenAPI spec(s) into the shared registry. */
104
124
  private loadOpenApiRegistry;
105
125
  /**
@@ -120,12 +140,6 @@ export declare class MDXToNextJSGenerator {
120
140
  * so specs added mid-session are watched without a restart.
121
141
  */
122
142
  private syncOpenApiSpecWatcher;
123
- /**
124
- * Reparses the spec(s) and rewrites everything derived from them: the
125
- * endpoint pages and allowlist, the sections (the "API Reference" section
126
- * appears and disappears with the registry), and the site aggregates.
127
- */
128
- private rebuildApiReference;
129
143
  /** Reparses the spec(s) and regenerates the API reference on a watch event. */
130
144
  handleOpenApiChange(): Promise<void>;
131
145
  /**
@@ -137,8 +151,8 @@ export declare class MDXToNextJSGenerator {
137
151
  * half-written editor save) keeps the current configuration.
138
152
  */
139
153
  handleDoccupineConfigChange(): Promise<void>;
140
- updatePagesIndex(): Promise<void>;
141
- updateSectionIndex(sectionSlug: string, frontmatter: Record<string, any>, mdxContent: string, sourcePath?: string): Promise<void>;
154
+ updatePagesIndex(pages?: readonly PageMeta[]): Promise<void>;
155
+ updateSectionIndex(sectionSlug: string, frontmatter: Record<string, any>, mdxContent: string, sourcePath?: string): Promise<GeneratedPageCommit>;
142
156
  updateRootLayout(pages?: PageMeta[]): Promise<void>;
143
157
  loadSiteUrl(): Promise<string | null>;
144
158
  updateSitemap(pages?: PageMeta[]): Promise<void>;
@@ -146,3 +160,4 @@ export declare class MDXToNextJSGenerator {
146
160
  updateLlmsFiles(pages?: PageMeta[]): Promise<void>;
147
161
  stop(): Promise<void>;
148
162
  }
163
+ export {};