doccupine 0.0.143 → 0.0.145

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 (66) hide show
  1. package/README.md +1 -1
  2. package/dist/cli.d.ts +6 -0
  3. package/dist/cli.js +130 -22
  4. package/dist/generator/api-reference-generator.d.ts +22 -0
  5. package/dist/generator/api-reference-generator.js +96 -0
  6. package/dist/generator/app-scaffolder.d.ts +18 -0
  7. package/dist/generator/app-scaffolder.js +49 -0
  8. package/dist/generator/generated-route-manager.d.ts +18 -0
  9. package/dist/generator/generated-route-manager.js +114 -0
  10. package/dist/generator/page-catalog.d.ts +21 -0
  11. package/dist/generator/page-catalog.js +75 -0
  12. package/dist/generator/page-renderer.d.ts +31 -0
  13. package/dist/generator/page-renderer.js +248 -0
  14. package/dist/generator/project-config-repository.d.ts +33 -0
  15. package/dist/generator/project-config-repository.js +191 -0
  16. package/dist/generator/public-asset-manager.d.ts +20 -0
  17. package/dist/generator/public-asset-manager.js +225 -0
  18. package/dist/generator/section-resolver.d.ts +13 -0
  19. package/dist/generator/section-resolver.js +150 -0
  20. package/dist/generator/secure-source-fs.d.ts +31 -0
  21. package/dist/generator/secure-source-fs.js +470 -0
  22. package/dist/generator/site-artifacts.d.ts +23 -0
  23. package/dist/generator/site-artifacts.js +156 -0
  24. package/dist/generator/watch-coordinator.d.ts +58 -0
  25. package/dist/generator/watch-coordinator.js +456 -0
  26. package/dist/lib/config-manager.d.ts +1 -0
  27. package/dist/lib/config-manager.js +194 -12
  28. package/dist/lib/generated-artifacts.d.ts +11 -2
  29. package/dist/lib/generated-artifacts.js +52 -7
  30. package/dist/lib/layout.d.ts +1 -17
  31. package/dist/lib/layout.js +5 -4
  32. package/dist/lib/openapi.d.ts +4 -0
  33. package/dist/lib/openapi.js +36 -4
  34. package/dist/lib/project-config.d.ts +3 -0
  35. package/dist/lib/project-config.js +110 -0
  36. package/dist/lib/types.d.ts +14 -1
  37. package/dist/mdx-to-nextjs-generator.d.ts +50 -34
  38. package/dist/mdx-to-nextjs-generator.js +760 -1740
  39. package/dist/templates/app/api/rag/route.d.ts +1 -1
  40. package/dist/templates/app/api/rag/route.js +2 -1
  41. package/dist/templates/components/Chat.d.ts +1 -1
  42. package/dist/templates/components/Chat.js +2 -1
  43. package/dist/templates/components/layout/Accordion.d.ts +1 -1
  44. package/dist/templates/components/layout/Accordion.js +2 -3
  45. package/dist/templates/mdx/api-playground.mdx.d.ts +1 -1
  46. package/dist/templates/mdx/api-playground.mdx.js +11 -2
  47. package/dist/templates/mdx/commands.mdx.d.ts +1 -1
  48. package/dist/templates/mdx/commands.mdx.js +26 -1
  49. package/dist/templates/mdx/media-and-assets.mdx.d.ts +1 -1
  50. package/dist/templates/mdx/media-and-assets.mdx.js +5 -0
  51. package/dist/templates/mdx/model-context-protocol.mdx.d.ts +1 -1
  52. package/dist/templates/mdx/model-context-protocol.mdx.js +2 -1
  53. package/dist/templates/mdx/platform/api-playground.mdx.d.ts +1 -1
  54. package/dist/templates/mdx/platform/api-playground.mdx.js +2 -2
  55. package/dist/templates/mdx/platform/publishing.mdx.d.ts +1 -1
  56. package/dist/templates/mdx/platform/publishing.mdx.js +3 -3
  57. package/dist/templates/mdx/space.mdx.d.ts +1 -1
  58. package/dist/templates/mdx/space.mdx.js +1 -5
  59. package/dist/templates/mdx/what-is-doccupine.mdx.d.ts +1 -1
  60. package/dist/templates/mdx/what-is-doccupine.mdx.js +8 -3
  61. package/dist/templates/next.config.js +2 -2
  62. package/dist/templates/package.js +3 -3
  63. package/dist/templates/proxy.js +1 -1
  64. package/dist/templates/services/mcp/server.d.ts +1 -1
  65. package/dist/templates/services/mcp/server.js +2 -12
  66. package/package.json +3 -3
@@ -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;
@@ -8,19 +8,28 @@ export declare class GeneratedArtifacts {
8
8
  private readonly outputDir;
9
9
  private routes;
10
10
  private llmsFiles;
11
+ private publicFilePaths;
11
12
  constructor(outputDir: string);
12
13
  private manifestPath;
13
14
  private routeKey;
14
15
  load(): Promise<void>;
15
16
  routeFor(kind: RouteOwnerKind, source: string): string | undefined;
16
17
  routesFor(kind: RouteOwnerKind): RouteArtifact[];
18
+ private routesWithReplacement;
17
19
  replaceRoutes(kind: RouteOwnerKind, routes: Iterable<{
18
20
  source: string;
19
21
  slug: string;
20
22
  }>): void;
23
+ replaceRoutesAndSave(kind: RouteOwnerKind, routes: Iterable<{
24
+ source: string;
25
+ slug: string;
26
+ }>): Promise<void>;
21
27
  removeRoute(kind: RouteOwnerKind, source: string): void;
28
+ removeRouteAndSave(kind: RouteOwnerKind, source: string): Promise<void>;
22
29
  llmsPageFiles(): Set<string>;
23
30
  replaceLlmsPageFiles(files: Iterable<string>): void;
31
+ publicFiles(): Set<string>;
32
+ replacePublicFiles(files: Iterable<string>): void;
33
+ private writeManifest;
24
34
  save(): Promise<void>;
25
35
  }
26
- export {};
@@ -39,10 +39,14 @@ function normalizeLlmsPageFile(value) {
39
39
  const normalized = normalizeRelativePath(value);
40
40
  return normalized?.endsWith(".md") ? normalized : null;
41
41
  }
42
+ function normalizePublicFile(value) {
43
+ return typeof value === "string" ? normalizeRelativePath(value) : null;
44
+ }
42
45
  export class GeneratedArtifacts {
43
46
  outputDir;
44
47
  routes = new Map();
45
48
  llmsFiles = new Set();
49
+ publicFilePaths = new Set();
46
50
  constructor(outputDir) {
47
51
  this.outputDir = outputDir;
48
52
  }
@@ -55,6 +59,7 @@ export class GeneratedArtifacts {
55
59
  async load() {
56
60
  this.routes.clear();
57
61
  this.llmsFiles.clear();
62
+ this.publicFilePaths.clear();
58
63
  const manifestContent = await readOutputFileIfPresent(this.outputDir, MANIFEST_FILE);
59
64
  if (manifestContent !== null) {
60
65
  try {
@@ -73,6 +78,13 @@ export class GeneratedArtifacts {
73
78
  this.llmsFiles.add(file);
74
79
  }
75
80
  }
81
+ if (Array.isArray(parsed.publicFiles)) {
82
+ for (const value of parsed.publicFiles) {
83
+ const file = normalizePublicFile(value);
84
+ if (file)
85
+ this.publicFilePaths.add(file);
86
+ }
87
+ }
76
88
  }
77
89
  catch {
78
90
  // A corrupt manifest owns nothing. Generated output is rebuilt safely.
@@ -107,22 +119,38 @@ export class GeneratedArtifacts {
107
119
  routesFor(kind) {
108
120
  return [...this.routes.values()].filter((route) => route.kind === kind);
109
121
  }
110
- replaceRoutes(kind, routes) {
111
- 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) {
112
125
  if (route.kind === kind)
113
- this.routes.delete(key);
126
+ next.delete(key);
114
127
  }
115
128
  for (const value of routes) {
116
129
  const route = normalizeRoute({ kind, ...value });
117
130
  if (!route) {
118
131
  throw new Error(`Refusing to record unsafe ${kind} route ownership`);
119
132
  }
120
- this.routes.set(this.routeKey(kind, route.source), route);
133
+ next.set(this.routeKey(kind, route.source), route);
121
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;
122
144
  }
123
145
  removeRoute(kind, source) {
124
146
  this.routes.delete(this.routeKey(kind, source));
125
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
+ }
126
154
  llmsPageFiles() {
127
155
  return new Set(this.llmsFiles);
128
156
  }
@@ -136,12 +164,29 @@ export class GeneratedArtifacts {
136
164
  }
137
165
  this.llmsFiles = next;
138
166
  }
139
- async save() {
167
+ publicFiles() {
168
+ return new Set(this.publicFilePaths);
169
+ }
170
+ replacePublicFiles(files) {
171
+ const next = new Set();
172
+ for (const value of files) {
173
+ const file = normalizePublicFile(value);
174
+ if (!file)
175
+ throw new Error("Refusing to record an unsafe public path");
176
+ next.add(file);
177
+ }
178
+ this.publicFilePaths = next;
179
+ }
180
+ async writeManifest(routes) {
140
181
  const manifest = {
141
- schemaVersion: 1,
142
- routes: [...this.routes.values()].sort((a, b) => `${a.kind}:${a.source}`.localeCompare(`${b.kind}:${b.source}`)),
182
+ schemaVersion: 2,
183
+ routes: [...routes.values()].sort((a, b) => `${a.kind}:${a.source}`.localeCompare(`${b.kind}:${b.source}`)),
143
184
  llmsPageFiles: [...this.llmsFiles].sort(),
185
+ publicFiles: [...this.publicFilePaths].sort(),
144
186
  };
145
187
  await writeFileAtomic(this.manifestPath(MANIFEST_FILE), `${JSON.stringify(manifest, null, 2)}\n`);
146
188
  }
189
+ async save() {
190
+ await this.writeManifest(this.routes);
191
+ }
147
192
  }
@@ -1,4 +1,4 @@
1
- import type { SectionConfig } from "./types.js";
1
+ import type { FontConfig, SectionConfig } from "./types.js";
2
2
  interface PageData {
3
3
  slug: string;
4
4
  title: string;
@@ -10,22 +10,6 @@ interface PageData {
10
10
  order: number;
11
11
  section: string;
12
12
  }
13
- interface GoogleFontConfig {
14
- fontName?: string;
15
- subsets?: string[];
16
- weight?: string | string[];
17
- }
18
- interface LocalFontSrc {
19
- path: string;
20
- weight: string;
21
- style: string;
22
- }
23
- interface FontConfig {
24
- googleFont?: GoogleFontConfig;
25
- localFonts?: string | {
26
- src?: LocalFontSrc[];
27
- };
28
- }
29
13
  /**
30
14
  * Root layout ("app/layout.tsx"). Minimal shell: html/body, fonts, the theme
31
15
  * provider stack, and (optionally) PostHog. It renders `children` directly so
@@ -21,7 +21,8 @@ function formatObjectArray(items) {
21
21
  return "[\n" + formatted.join("\n") + "\n]";
22
22
  }
23
23
  function isGoogleFont(fc) {
24
- return !!fc?.googleFont?.fontName;
24
+ return (!!fc?.googleFont?.fontName &&
25
+ /^[A-Za-z_$][A-Za-z0-9_$]*$/.test(fc.googleFont.fontName));
25
26
  }
26
27
  function isLocalFont(fc) {
27
28
  if (!fc?.localFonts)
@@ -32,8 +33,8 @@ function isLocalFont(fc) {
32
33
  }
33
34
  function getLocalFontSrc(fc) {
34
35
  if (typeof fc.localFonts === "string")
35
- return `"${fc.localFonts}"`;
36
- return JSON.stringify(fc.localFonts?.src, null, 2).replace(/"([^"]+)":/g, "$1:");
36
+ return JSON.stringify(fc.localFonts);
37
+ return JSON.stringify(fc.localFonts?.src, null, 2);
37
38
  }
38
39
  function fontImportLine(fontConfig) {
39
40
  return isGoogleFont(fontConfig)
@@ -51,7 +52,7 @@ function fontDeclLine(fontConfig) {
51
52
  fontConfig.googleFont.weight?.length
52
53
  ? `weight: ${Array.isArray(fontConfig.googleFont.weight)
53
54
  ? JSON.stringify(fontConfig.googleFont.weight)
54
- : `"${fontConfig.googleFont.weight}"`}`
55
+ : JSON.stringify(fontConfig.googleFont.weight)}`
55
56
  : "",
56
57
  ]
57
58
  .filter(Boolean)
@@ -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() {
@@ -0,0 +1,3 @@
1
+ import type { AnalyticsConfig, FontConfig } from "./types.js";
2
+ export declare function validateFontConfig(value: unknown): FontConfig;
3
+ export declare function validateAnalyticsConfig(value: unknown): AnalyticsConfig;