doccupine 0.0.139 → 0.0.141

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 (151) hide show
  1. package/README.md +14 -7
  2. package/dist/cli.d.ts +1 -0
  3. package/dist/cli.js +191 -0
  4. package/dist/index.d.ts +3 -7
  5. package/dist/index.js +5 -1895
  6. package/dist/lib/config-manager.d.ts +1 -0
  7. package/dist/lib/config-manager.js +63 -3
  8. package/dist/lib/generated-artifacts.d.ts +26 -0
  9. package/dist/lib/generated-artifacts.js +147 -0
  10. package/dist/lib/layout.js +30 -30
  11. package/dist/lib/metadata.js +58 -30
  12. package/dist/lib/openapi-types.d.ts +2 -2
  13. package/dist/lib/openapi.d.ts +6 -3
  14. package/dist/lib/openapi.js +330 -50
  15. package/dist/lib/output-safety.d.ts +15 -0
  16. package/dist/lib/output-safety.js +428 -0
  17. package/dist/lib/structures.js +11 -0
  18. package/dist/lib/utils.d.ts +18 -0
  19. package/dist/lib/utils.js +125 -0
  20. package/dist/mdx-to-nextjs-generator.d.ts +166 -0
  21. package/dist/mdx-to-nextjs-generator.js +2229 -0
  22. package/dist/templates/app/api/gate/route.d.ts +1 -1
  23. package/dist/templates/app/api/gate/route.js +18 -6
  24. package/dist/templates/app/api/mcp/route.d.ts +1 -1
  25. package/dist/templates/app/api/mcp/route.js +181 -111
  26. package/dist/templates/app/api/playground/route.d.ts +1 -1
  27. package/dist/templates/app/api/playground/route.js +45 -13
  28. package/dist/templates/app/api/rag/route.d.ts +1 -1
  29. package/dist/templates/app/api/rag/route.js +102 -25
  30. package/dist/templates/app/api/search/route.d.ts +1 -1
  31. package/dist/templates/app/api/search/route.js +5 -0
  32. package/dist/templates/app/robots.d.ts +1 -1
  33. package/dist/templates/app/robots.js +1 -26
  34. package/dist/templates/app/theme.d.ts +1 -1
  35. package/dist/templates/app/theme.js +31 -19
  36. package/dist/templates/components/Chat.d.ts +1 -1
  37. package/dist/templates/components/Chat.js +411 -104
  38. package/dist/templates/components/Docs.d.ts +1 -1
  39. package/dist/templates/components/Docs.js +56 -13
  40. package/dist/templates/components/SearchDocs.d.ts +1 -1
  41. package/dist/templates/components/SearchDocs.js +63 -11
  42. package/dist/templates/components/SearchModalContent.d.ts +1 -1
  43. package/dist/templates/components/SearchModalContent.js +191 -49
  44. package/dist/templates/components/SideBar.d.ts +1 -1
  45. package/dist/templates/components/SideBar.js +8 -2
  46. package/dist/templates/components/layout/Accordion.d.ts +1 -1
  47. package/dist/templates/components/layout/Accordion.js +26 -3
  48. package/dist/templates/components/layout/ApiPlayground.d.ts +1 -1
  49. package/dist/templates/components/layout/ApiPlayground.js +4 -7
  50. package/dist/templates/components/layout/Badge.d.ts +1 -1
  51. package/dist/templates/components/layout/Badge.js +1 -1
  52. package/dist/templates/components/layout/Button.d.ts +1 -1
  53. package/dist/templates/components/layout/Button.js +4 -4
  54. package/dist/templates/components/layout/Callout.d.ts +1 -1
  55. package/dist/templates/components/layout/Callout.js +6 -6
  56. package/dist/templates/components/layout/Card.d.ts +1 -1
  57. package/dist/templates/components/layout/Card.js +9 -4
  58. package/dist/templates/components/layout/CherryThemeProvider.d.ts +1 -1
  59. package/dist/templates/components/layout/CherryThemeProvider.js +63 -12
  60. package/dist/templates/components/layout/Code.d.ts +1 -1
  61. package/dist/templates/components/layout/Code.js +5 -5
  62. package/dist/templates/components/layout/CopyButton.d.ts +1 -1
  63. package/dist/templates/components/layout/CopyButton.js +1 -1
  64. package/dist/templates/components/layout/DemoTheme.d.ts +1 -1
  65. package/dist/templates/components/layout/DemoTheme.js +8 -28
  66. package/dist/templates/components/layout/DocsComponents.d.ts +1 -1
  67. package/dist/templates/components/layout/DocsComponents.js +57 -18
  68. package/dist/templates/components/layout/GlobalStyles.d.ts +1 -1
  69. package/dist/templates/components/layout/GlobalStyles.js +15 -9
  70. package/dist/templates/components/layout/Prompt.d.ts +1 -1
  71. package/dist/templates/components/layout/Prompt.js +4 -7
  72. package/dist/templates/components/layout/Steps.d.ts +1 -1
  73. package/dist/templates/components/layout/Steps.js +7 -1
  74. package/dist/templates/components/layout/Tabs.d.ts +1 -1
  75. package/dist/templates/components/layout/Tabs.js +108 -19
  76. package/dist/templates/env.example.d.ts +1 -1
  77. package/dist/templates/env.example.js +11 -0
  78. package/dist/templates/eslint.config.d.ts +1 -1
  79. package/dist/templates/eslint.config.js +20 -0
  80. package/dist/templates/gitignore.d.ts +1 -1
  81. package/dist/templates/gitignore.js +4 -3
  82. package/dist/templates/lib/access.d.ts +1 -0
  83. package/dist/templates/lib/access.js +41 -0
  84. package/dist/templates/mdx/ai-assistant.mdx.d.ts +1 -1
  85. package/dist/templates/mdx/ai-assistant.mdx.js +17 -1
  86. package/dist/templates/mdx/api-playground.mdx.d.ts +1 -1
  87. package/dist/templates/mdx/api-playground.mdx.js +5 -3
  88. package/dist/templates/mdx/authentication.mdx.d.ts +1 -1
  89. package/dist/templates/mdx/authentication.mdx.js +5 -3
  90. package/dist/templates/mdx/commands.mdx.d.ts +1 -1
  91. package/dist/templates/mdx/commands.mdx.js +20 -6
  92. package/dist/templates/mdx/components.mdx.d.ts +1 -1
  93. package/dist/templates/mdx/components.mdx.js +3 -0
  94. package/dist/templates/mdx/deployment-and-hosting.mdx.d.ts +1 -1
  95. package/dist/templates/mdx/deployment-and-hosting.mdx.js +2 -2
  96. package/dist/templates/mdx/globals.mdx.d.ts +1 -1
  97. package/dist/templates/mdx/globals.mdx.js +14 -11
  98. package/dist/templates/mdx/model-context-protocol.mdx.d.ts +1 -1
  99. package/dist/templates/mdx/model-context-protocol.mdx.js +22 -35
  100. package/dist/templates/mdx/platform/ai-assistant.mdx.d.ts +1 -1
  101. package/dist/templates/mdx/platform/ai-assistant.mdx.js +23 -0
  102. package/dist/templates/mdx/platform/api-playground.mdx.d.ts +1 -1
  103. package/dist/templates/mdx/platform/api-playground.mdx.js +7 -0
  104. package/dist/templates/mdx/platform/authentication.mdx.d.ts +1 -0
  105. package/dist/templates/mdx/platform/authentication.mdx.js +63 -0
  106. package/dist/templates/mdx/platform/build-and-deploy.mdx.d.ts +1 -1
  107. package/dist/templates/mdx/platform/build-and-deploy.mdx.js +1 -1
  108. package/dist/templates/mdx/platform/import-from-github.mdx.d.ts +1 -1
  109. package/dist/templates/mdx/platform/import-from-github.mdx.js +2 -2
  110. package/dist/templates/mdx/platform/index.mdx.d.ts +1 -1
  111. package/dist/templates/mdx/platform/index.mdx.js +1 -0
  112. package/dist/templates/mdx/platform/mcp.mdx.d.ts +1 -1
  113. package/dist/templates/mdx/platform/mcp.mdx.js +2 -1
  114. package/dist/templates/mdx/platform/navigation-settings.mdx.d.ts +1 -1
  115. package/dist/templates/mdx/platform/navigation-settings.mdx.js +12 -1
  116. package/dist/templates/mdx/platform/publishing.mdx.d.ts +1 -1
  117. package/dist/templates/mdx/platform/publishing.mdx.js +43 -10
  118. package/dist/templates/mdx/platform/self-updating-docs.mdx.d.ts +1 -1
  119. package/dist/templates/mdx/platform/self-updating-docs.mdx.js +48 -9
  120. package/dist/templates/mdx/sections.mdx.d.ts +1 -1
  121. package/dist/templates/mdx/sections.mdx.js +4 -0
  122. package/dist/templates/mdx/space.mdx.d.ts +1 -0
  123. package/dist/templates/mdx/space.mdx.js +125 -0
  124. package/dist/templates/mdx/tabs.mdx.d.ts +1 -1
  125. package/dist/templates/mdx/tabs.mdx.js +4 -0
  126. package/dist/templates/next.config.js +20 -8
  127. package/dist/templates/package.js +3 -3
  128. package/dist/templates/prettierignore.d.ts +1 -1
  129. package/dist/templates/prettierignore.js +1 -0
  130. package/dist/templates/proxy.js +47 -19
  131. package/dist/templates/scripts/build-docs-index.d.ts +1 -1
  132. package/dist/templates/scripts/build-docs-index.js +1 -0
  133. package/dist/templates/services/mcp/docsContentStub.d.ts +1 -0
  134. package/dist/templates/services/mcp/docsContentStub.js +1 -0
  135. package/dist/templates/services/mcp/server.d.ts +1 -1
  136. package/dist/templates/services/mcp/server.js +140 -83
  137. package/dist/templates/services/mcp/tools.d.ts +1 -1
  138. package/dist/templates/services/mcp/tools.js +65 -137
  139. package/dist/templates/utils/playgroundAllowlist.d.ts +1 -1
  140. package/dist/templates/utils/playgroundAllowlist.js +13 -4
  141. package/dist/templates/utils/rateLimit.d.ts +1 -1
  142. package/dist/templates/utils/rateLimit.js +40 -3
  143. package/dist/templates/utils/requestBody.d.ts +1 -0
  144. package/dist/templates/utils/requestBody.js +56 -0
  145. package/dist/templates/utils/ssrfGuard.d.ts +1 -1
  146. package/dist/templates/utils/ssrfGuard.js +138 -33
  147. package/package.json +14 -9
  148. package/dist/lib/mdxToMarkdown.d.ts +0 -1
  149. package/dist/lib/mdxToMarkdown.js +0 -134
  150. package/dist/templates/mdx/image-and-embeds.mdx.d.ts +0 -1
  151. package/dist/templates/mdx/image-and-embeds.mdx.js +0 -118
@@ -1,6 +1,10 @@
1
1
  import path from "path";
2
+ import net from "node:net";
3
+ import { constants } from "node:fs";
4
+ import fs from "node:fs/promises";
5
+ import { fileURLToPath, pathToFileURL } from "node:url";
2
6
  import chalk from "chalk";
3
- import { dereference } from "@readme/openapi-parser";
7
+ import { bundle, dereference, parse } from "@readme/openapi-parser";
4
8
  /* eslint-disable @typescript-eslint/no-explicit-any */
5
9
  /** Default base route segment for the generated API reference section. */
6
10
  export const DEFAULT_API_BASE_SLUG = "api-reference";
@@ -15,6 +19,7 @@ const HTTP_METHODS = [
15
19
  "trace",
16
20
  ];
17
21
  const MAX_SERIALIZE_DEPTH = 20;
22
+ const OPENAPI_REFERENCE_EXTENSIONS = new Set([".json", ".yaml", ".yml"]);
18
23
  /**
19
24
  * Slugifies a single route/anchor segment: lowercase, collapse any run of
20
25
  * non-alphanumerics to a single dash, trim edge dashes. Never returns "" and
@@ -123,36 +128,47 @@ function resolveServerUrl(server) {
123
128
  return url;
124
129
  }
125
130
  /**
126
- * True when a host literal is loopback/private/link-local/CGNAT (or localhost).
127
- * Used ONLY at build time to mark an allowlist entry `allowPrivate` when the
128
- * spec's own declared server is a local-dev host. The runtime SSRF guard still
129
- * enforces the range checks; this just records the operator's explicit intent.
131
+ * True only for a loopback host. Loopback is useful for a local playground, but
132
+ * broader private and link-local ranges are never auto-enabled from spec input:
133
+ * an imported spec must not be able to turn the generated site into an internal
134
+ * network or cloud-metadata proxy.
130
135
  */
131
- function isLocalOrPrivateHost(host) {
136
+ function isLoopbackHost(host) {
132
137
  if (host === "localhost" || host.endsWith(".localhost"))
133
138
  return true;
134
139
  if (host === "::1")
135
140
  return true;
136
- // IPv6 link-local (fe80::/10) and unique-local (fc00::/7 -> fc../fd..).
137
- if (host.startsWith("fe80:") ||
138
- host.startsWith("fc") ||
139
- host.startsWith("fd")) {
140
- return true;
141
- }
142
141
  const m = host.match(/^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.\d{1,3}$/);
143
- if (m) {
144
- const a = Number(m[1]);
145
- const b = Number(m[2]);
146
- if (a === 0 || a === 127 || a === 10)
147
- return true;
148
- if (a === 169 && b === 254)
149
- return true;
150
- if (a === 172 && b >= 16 && b <= 31)
151
- return true;
152
- if (a === 192 && b === 168)
153
- return true;
154
- if (a === 100 && b >= 64 && b <= 127)
155
- return true;
142
+ return Boolean(m && Number(m[1]) === 127);
143
+ }
144
+ /** True when the runtime proxy will reject a non-loopback IP literal. */
145
+ function isBlockedNonLoopbackLiteral(host) {
146
+ const type = net.isIP(host);
147
+ if (type === 4) {
148
+ const [a, b] = host.split(".").map(Number);
149
+ return (a === 0 ||
150
+ a === 10 ||
151
+ (a === 100 && b >= 64 && b <= 127) ||
152
+ (a === 169 && b === 254) ||
153
+ (a === 172 && b >= 16 && b <= 31) ||
154
+ (a === 192 && b === 168) ||
155
+ a >= 224);
156
+ }
157
+ if (type === 6) {
158
+ const clean = host.toLowerCase().split("%")[0];
159
+ const head = clean.split(":")[0];
160
+ return (clean === "::" ||
161
+ head.startsWith("fc") ||
162
+ head.startsWith("fd") ||
163
+ head.startsWith("fe8") ||
164
+ head.startsWith("fe9") ||
165
+ head.startsWith("fea") ||
166
+ head.startsWith("feb") ||
167
+ head.startsWith("fec") ||
168
+ head.startsWith("fed") ||
169
+ head.startsWith("fee") ||
170
+ head.startsWith("fef") ||
171
+ head.startsWith("ff"));
156
172
  }
157
173
  return false;
158
174
  }
@@ -167,7 +183,10 @@ function serverToAllowlistEntry(server) {
167
183
  }
168
184
  if (url.protocol !== "http:" && url.protocol !== "https:")
169
185
  return null;
170
- const host = url.hostname.toLowerCase().replace(/\.$/, "");
186
+ const host = url.hostname
187
+ .toLowerCase()
188
+ .replace(/\.$/, "")
189
+ .replace(/^\[|\]$/g, "");
171
190
  const entry = {
172
191
  scheme: url.protocol === "https:" ? "https" : "http",
173
192
  host,
@@ -176,7 +195,7 @@ function serverToAllowlistEntry(server) {
176
195
  if (url.pathname && url.pathname !== "/") {
177
196
  entry.basePath = url.pathname.replace(/\/+$/, "");
178
197
  }
179
- if (isLocalOrPrivateHost(host))
198
+ if (isLoopbackHost(host))
180
199
  entry.allowPrivate = true;
181
200
  return entry;
182
201
  }
@@ -229,14 +248,187 @@ function firstLine(text) {
229
248
  return "";
230
249
  return text.split("\n")[0]?.trim() ?? "";
231
250
  }
251
+ function isWithinDirectory(root, candidate) {
252
+ const relative = path.relative(root, candidate);
253
+ return (relative === "" ||
254
+ (relative !== ".." &&
255
+ !relative.startsWith(`..${path.sep}`) &&
256
+ !path.isAbsolute(relative)));
257
+ }
258
+ export function isLocalOpenApiPath(reference) {
259
+ if (path.win32.isAbsolute(reference))
260
+ return true;
261
+ return !/^[a-z][a-z\d+.-]*:/i.test(reference);
262
+ }
263
+ async function resolveLocalOpenApiFile(boundaryRealPath, candidate, reference, boundaryName) {
264
+ let realPath;
265
+ try {
266
+ realPath = await fs.realpath(candidate);
267
+ }
268
+ catch (error) {
269
+ throw new Error(`Unable to resolve OpenAPI file "${reference}"`, {
270
+ cause: error,
271
+ });
272
+ }
273
+ if (!isWithinDirectory(boundaryRealPath, realPath)) {
274
+ throw new Error(`OpenAPI file "${reference}" resolves outside ${boundaryName}`);
275
+ }
276
+ return realPath;
277
+ }
278
+ function assertAllowedOpenApiReference(referenceRootRealPath, candidate, reference) {
279
+ if (!isWithinDirectory(referenceRootRealPath, candidate)) {
280
+ throw new Error(`OpenAPI external reference "${reference}" must stay within the configured root spec directory`);
281
+ }
282
+ const relativeParts = path
283
+ .relative(referenceRootRealPath, candidate)
284
+ .split(path.sep)
285
+ .filter(Boolean);
286
+ if (relativeParts.some((part) => part.startsWith("."))) {
287
+ throw new Error(`OpenAPI external reference "${reference}" must not target a dotfile or a file inside a dot-directory`);
288
+ }
289
+ const extension = path.extname(candidate).toLowerCase();
290
+ if (!OPENAPI_REFERENCE_EXTENSIONS.has(extension)) {
291
+ throw new Error(`OpenAPI external reference "${reference}" must use a .json, .yaml, or .yml file`);
292
+ }
293
+ }
294
+ // The wrapper's runtime passes resolver objects through, although its public
295
+ // ParserOptions type narrows resolve.file to boolean.
296
+ function parserFileResolver(resolver) {
297
+ return resolver;
298
+ }
299
+ async function readOpenApiSnapshot(referenceRootRealPath, realPath, reference) {
300
+ let handle;
301
+ try {
302
+ const noFollow = process.platform === "win32" ? 0 : constants.O_NOFOLLOW;
303
+ handle = await fs.open(realPath, constants.O_RDONLY | noFollow);
304
+ }
305
+ catch (error) {
306
+ throw new Error(`Unable to open OpenAPI file "${reference}"`, {
307
+ cause: error,
308
+ });
309
+ }
310
+ try {
311
+ const [openedStat, confirmedRealPath] = await Promise.all([
312
+ handle.stat(),
313
+ fs.realpath(realPath),
314
+ ]);
315
+ if (!openedStat.isFile() ||
316
+ !isWithinDirectory(referenceRootRealPath, confirmedRealPath)) {
317
+ throw new Error(`OpenAPI file "${reference}" resolves outside the configured root spec directory`);
318
+ }
319
+ const currentStat = await fs.stat(confirmedRealPath);
320
+ if (openedStat.dev !== currentStat.dev ||
321
+ openedStat.ino !== currentStat.ino) {
322
+ throw new Error(`OpenAPI file "${reference}" changed while being read`);
323
+ }
324
+ return await handle.readFile();
325
+ }
326
+ finally {
327
+ await handle.close();
328
+ }
329
+ }
330
+ async function parseOpenApiSnapshot(filePath, contents) {
331
+ return parse(filePath, {
332
+ resolve: {
333
+ file: parserFileResolver({
334
+ order: 1,
335
+ canRead: () => true,
336
+ read: () => contents,
337
+ }),
338
+ },
339
+ });
340
+ }
341
+ function resolveOpenApiReference(filePath, reference) {
342
+ if (path.isAbsolute(reference) || path.win32.isAbsolute(reference)) {
343
+ return path.normalize(reference);
344
+ }
345
+ try {
346
+ const url = new URL(reference, pathToFileURL(filePath));
347
+ if (url.protocol !== "file:")
348
+ throw new Error("Not a local file");
349
+ return fileURLToPath(url);
350
+ }
351
+ catch (error) {
352
+ throw new Error(`Invalid OpenAPI external reference "${reference}"`, {
353
+ cause: error,
354
+ });
355
+ }
356
+ }
357
+ /**
358
+ * Captures every allowed file once and rewrites external refs to closed,
359
+ * in-memory snapshot URLs. No parser phase after this function reads disk.
360
+ */
361
+ async function snapshotOpenApiDocuments(rootFile) {
362
+ const referenceRootRealPath = path.dirname(rootFile);
363
+ const byRealPath = new Map();
364
+ const snapshots = new Map();
365
+ const visit = async (candidate, reference, configuredRoot = false) => {
366
+ if (!configuredRoot) {
367
+ assertAllowedOpenApiReference(referenceRootRealPath, candidate, reference);
368
+ }
369
+ const realPath = await resolveLocalOpenApiFile(referenceRootRealPath, candidate, reference, "the configured root spec directory");
370
+ if (!configuredRoot) {
371
+ assertAllowedOpenApiReference(referenceRootRealPath, realPath, reference);
372
+ }
373
+ const existing = byRealPath.get(realPath);
374
+ if (existing)
375
+ return existing.url;
376
+ const contents = await readOpenApiSnapshot(referenceRootRealPath, realPath, reference);
377
+ const document = await parseOpenApiSnapshot(realPath, contents);
378
+ const snapshotUrl = `file:///__doccupine_openapi_snapshot__/${byRealPath.size}.json`;
379
+ byRealPath.set(realPath, { document, url: snapshotUrl });
380
+ snapshots.set(snapshotUrl, document);
381
+ const seen = new WeakSet();
382
+ const scan = async (value) => {
383
+ if (value === null || typeof value !== "object" || seen.has(value))
384
+ return;
385
+ seen.add(value);
386
+ if (typeof value.$ref === "string") {
387
+ const hashIndex = value.$ref.indexOf("#");
388
+ const externalPath = hashIndex >= 0 ? value.$ref.slice(0, hashIndex) : value.$ref;
389
+ if (externalPath) {
390
+ if (!isLocalOpenApiPath(externalPath)) {
391
+ throw new Error(`OpenAPI external reference "${value.$ref}" must be a local file`);
392
+ }
393
+ const targetUrl = await visit(resolveOpenApiReference(realPath, externalPath), value.$ref);
394
+ const fragment = hashIndex >= 0 ? value.$ref.slice(hashIndex) : "";
395
+ value.$ref = `${targetUrl}${fragment}`;
396
+ }
397
+ }
398
+ await Promise.all(Object.values(value).map(scan));
399
+ };
400
+ await scan(document);
401
+ return snapshotUrl;
402
+ };
403
+ const rootUrl = await visit(rootFile, rootFile, true);
404
+ return { rootDocument: snapshots.get(rootUrl), snapshots };
405
+ }
406
+ async function dereferenceOpenApiSnapshots(rootDocument, snapshots) {
407
+ const snapshotResolver = parserFileResolver({
408
+ order: 1,
409
+ canRead: (file) => snapshots.has(file.url),
410
+ read: (file) => {
411
+ const document = snapshots.get(file.url);
412
+ if (document === undefined) {
413
+ throw new Error(`Unknown OpenAPI snapshot "${file.url}"`);
414
+ }
415
+ return document;
416
+ },
417
+ });
418
+ const bundled = await bundle(rootDocument, {
419
+ resolve: { file: snapshotResolver },
420
+ });
421
+ return dereference(bundled, { resolve: { external: false } });
422
+ }
232
423
  /**
233
424
  * Parses one or more OpenAPI specs and exposes everything the generator needs:
234
425
  * the operation descriptors, lookup indices for the MDX frontmatter path,
235
426
  * synthetic sidebar/sitemap `PageMeta` objects, per-endpoint markdown bodies
236
427
  * (for llms output), and the request-execution allowlist.
237
428
  *
238
- * `load()` never throws: a spec that fails to parse is logged and skipped so one
239
- * malformed file cannot abort a build or crash a watcher.
429
+ * `load()` is transactional: every configured spec must parse and process
430
+ * successfully before the current registry is replaced. A failed reload throws
431
+ * and leaves the last-known-good state available to callers.
240
432
  */
241
433
  export class OpenApiRegistry {
242
434
  operations = [];
@@ -252,32 +444,55 @@ export class OpenApiRegistry {
252
444
  return this.operations.length === 0;
253
445
  }
254
446
  async load(specs, rootDir, apiBaseSlug = DEFAULT_API_BASE_SLUG) {
255
- this.operations = [];
256
- this.byOperationId.clear();
257
- this.byMethodPath.clear();
258
- this.pages = [];
259
- this.bodies.clear();
260
- this.allowlistEntries = [];
447
+ const next = new OpenApiRegistry();
261
448
  const multi = specs.length > 1;
262
449
  const usedSlugs = new Set();
263
450
  const allowlistKeys = new Set();
451
+ const rootRealPath = specs.length > 0 ? await fs.realpath(rootDir) : path.resolve(rootDir);
264
452
  for (const spec of specs) {
265
- const absolute = path.resolve(rootDir, spec.file);
266
453
  let doc;
267
454
  try {
268
- doc = await dereference(absolute);
455
+ if (!isLocalOpenApiPath(spec.file)) {
456
+ throw new Error(`OpenAPI spec "${spec.file}" must be a local file within rootDir`);
457
+ }
458
+ const configuredPath = path.isAbsolute(spec.file) || path.win32.isAbsolute(spec.file)
459
+ ? path.normalize(spec.file)
460
+ : path.resolve(rootDir, spec.file);
461
+ const absolute = await resolveLocalOpenApiFile(rootRealPath, configuredPath, spec.file, "rootDir");
462
+ const { rootDocument, snapshots } = await snapshotOpenApiDocuments(absolute);
463
+ doc = await dereferenceOpenApiSnapshots(rootDocument, snapshots);
269
464
  }
270
465
  catch (error) {
271
- console.error(chalk.red(`❌ Failed to parse OpenAPI spec "${spec.file}":`), error instanceof Error ? error.message : error);
272
- continue;
466
+ throw new Error(`Failed to parse OpenAPI spec "${spec.file}": ${error instanceof Error ? error.message : String(error)}`, { cause: error });
273
467
  }
274
468
  try {
275
- this.ingest(doc, spec, multi, apiBaseSlug, usedSlugs, allowlistKeys);
469
+ next.ingest(doc, spec, multi, apiBaseSlug, usedSlugs, allowlistKeys);
276
470
  }
277
471
  catch (error) {
278
- console.error(chalk.red(`❌ Failed to process OpenAPI spec "${spec.file}":`), error instanceof Error ? error.message : error);
472
+ throw new Error(`Failed to process OpenAPI spec "${spec.file}": ${error instanceof Error ? error.message : String(error)}`, { cause: error });
279
473
  }
280
474
  }
475
+ if (next.operations.length > 0) {
476
+ const body = buildApiIndexBody(next.operations);
477
+ next.pages.unshift({
478
+ slug: apiBaseSlug,
479
+ title: "API Reference",
480
+ description: `Browse all ${next.operations.length} API endpoints.`,
481
+ date: null,
482
+ category: "Overview",
483
+ path: "@openapi/index",
484
+ categoryOrder: -1,
485
+ order: -1,
486
+ section: apiBaseSlug,
487
+ });
488
+ next.bodies.set(apiBaseSlug, body);
489
+ }
490
+ this.operations = next.operations;
491
+ this.byOperationId = next.byOperationId;
492
+ this.byMethodPath = next.byMethodPath;
493
+ this.pages = next.pages;
494
+ this.bodies = next.bodies;
495
+ this.allowlistEntries = next.allowlistEntries;
281
496
  }
282
497
  /** Fresh copies of the synthetic pages (caller may mutate/spread safely). */
283
498
  syntheticPages() {
@@ -471,10 +686,66 @@ export class OpenApiRegistry {
471
686
  if (keys.has(key))
472
687
  continue;
473
688
  keys.add(key);
689
+ if (isBlockedNonLoopbackLiteral(entry.host)) {
690
+ console.warn(chalk.yellow(`⚠️ OpenAPI server "${resolveServerUrl(server)}" is a private or reserved IP. ` +
691
+ "It remains documented, but the generated playground proxy will block requests to it."));
692
+ }
474
693
  this.allowlistEntries.push(entry);
475
694
  }
476
695
  }
477
696
  }
697
+ /**
698
+ * Builds the API-reference landing page as safe MDX. Endpoint metadata is
699
+ * emitted through JSX string expressions, so arbitrary OpenAPI summaries,
700
+ * paths, tags, and descriptions remain text rather than executable MDX.
701
+ */
702
+ function buildApiIndexBody(operations) {
703
+ const bySpec = new Map();
704
+ for (const operation of operations) {
705
+ const tag = operation.tags[0] ?? "Endpoints";
706
+ let byTag = bySpec.get(operation.specName);
707
+ if (!byTag) {
708
+ byTag = new Map();
709
+ bySpec.set(operation.specName, byTag);
710
+ }
711
+ const endpoints = byTag.get(tag) ?? [];
712
+ endpoints.push(operation);
713
+ byTag.set(tag, endpoints);
714
+ }
715
+ const lines = [
716
+ "# API Reference",
717
+ "",
718
+ `Browse all ${operations.length} API endpoint${operations.length === 1 ? "" : "s"}. Select an endpoint to view its parameters, responses, and live request playground.`,
719
+ ];
720
+ const multipleSpecs = bySpec.size > 1;
721
+ for (const [specName, byTag] of bySpec) {
722
+ if (multipleSpecs) {
723
+ lines.push("", `<h2>{${JSON.stringify(specName)}}</h2>`);
724
+ }
725
+ for (const [tag, endpoints] of byTag) {
726
+ const heading = multipleSpecs ? "h3" : "h2";
727
+ lines.push("", `<${heading}>{${JSON.stringify(tag)}}</${heading}>`, "", "<Columns cols={2}>");
728
+ for (const endpoint of endpoints) {
729
+ const method = endpoint.method.toUpperCase();
730
+ const title = endpoint.summary ?? `${method} ${endpoint.path}`;
731
+ const description = firstLine(endpoint.description) ||
732
+ `View the ${method} ${endpoint.path} endpoint.`;
733
+ const badgeColor = endpoint.method === "get"
734
+ ? "info"
735
+ : endpoint.method === "post"
736
+ ? "success"
737
+ : endpoint.method === "put" || endpoint.method === "patch"
738
+ ? "warning"
739
+ : endpoint.method === "delete"
740
+ ? "error"
741
+ : "gray";
742
+ lines.push("", `<Card title={${JSON.stringify(title)}} href={${JSON.stringify(`/${endpoint.slug}`)}}>`, ` <Badge color=${JSON.stringify(badgeColor)} size="sm">{${JSON.stringify(method)}}</Badge>`, ` <code>{${JSON.stringify(endpoint.path)}}</code>`, ` <p>{${JSON.stringify(description)}}</p>`, "</Card>");
743
+ }
744
+ lines.push("", "</Columns>");
745
+ }
746
+ }
747
+ return lines.join("\n");
748
+ }
478
749
  /** Minimal markdown body for an endpoint, used by the llms.txt aggregation. */
479
750
  function buildEndpointBody(title, methodUpper, pathKey, opRaw) {
480
751
  const lines = [`# ${title}`, "", `\`${methodUpper} ${pathKey}\``];
@@ -509,6 +780,14 @@ function inlineText(text) {
509
780
  return "";
510
781
  return text.replace(/\s+/g, " ").trim();
511
782
  }
783
+ /** Emits untrusted prose as a JSX string expression, never as executable MDX. */
784
+ function jsxText(text) {
785
+ return `{${JSON.stringify(text)}}`;
786
+ }
787
+ function jsonCode(value) {
788
+ const serialized = JSON.stringify(value, null, 2) ?? "null";
789
+ return `<Code language="json" code=${jsxText(serialized)} />`;
790
+ }
512
791
  /** The object schema whose `properties` we can document (unwraps arrays). */
513
792
  function objectShape(schema) {
514
793
  if (!schema || typeof schema !== "object")
@@ -529,10 +808,10 @@ function renderDocField(name, schema, required, description, depth) {
529
808
  const type = docSchemaType(schema);
530
809
  const desc = inlineText(description ?? schema?.description);
531
810
  const lines = [
532
- `<Field value="${name}" type="${type}"${required ? " required" : ""}>`,
811
+ `<Field value={${JSON.stringify(name)}} type={${JSON.stringify(type)}}${required ? " required" : ""}>`,
533
812
  ];
534
813
  if (desc)
535
- lines.push(desc);
814
+ lines.push(jsxText(desc));
536
815
  const shape = depth < MAX_FIELD_DEPTH ? objectShape(schema) : null;
537
816
  if (shape) {
538
817
  const req = Array.isArray(shape.required) ? shape.required : [];
@@ -552,14 +831,15 @@ const PARAM_LOCATION_TITLES = {
552
831
  /**
553
832
  * Builds the MDX body for a generated endpoint page: the operation description,
554
833
  * followed by `<Field>` documentation for the parameters and request body, and
555
- * a schema/example code block per response. Rendered above the playground.
834
+ * a schema/example code block per response. Spec-derived strings are emitted
835
+ * only through serialized JSX expressions. Rendered above the playground.
556
836
  */
557
837
  export function buildEndpointDoc(op) {
558
838
  const out = [];
559
839
  if (op.description)
560
- out.push(op.description);
840
+ out.push(jsxText(op.description));
561
841
  else if (op.summary)
562
- out.push(op.summary);
842
+ out.push(jsxText(op.summary));
563
843
  for (const location of ["path", "query", "header", "cookie"]) {
564
844
  const params = op.parameters.filter((p) => p.in === location);
565
845
  if (params.length === 0)
@@ -581,21 +861,21 @@ export function buildEndpointDoc(op) {
581
861
  }
582
862
  }
583
863
  else {
584
- out.push("```json\n" + JSON.stringify(body.schema, null, 2) + "\n```");
864
+ out.push(jsonCode(body.schema));
585
865
  }
586
866
  }
587
867
  if (op.responses.length > 0) {
588
868
  out.push("## Responses");
589
869
  for (const response of op.responses) {
590
- out.push(`### ${response.status}`);
870
+ out.push(`<h3>{${JSON.stringify(response.status)}}</h3>`);
591
871
  if (response.description) {
592
- out.push(inlineText(response.description));
872
+ out.push(jsxText(inlineText(response.description)));
593
873
  }
594
874
  const media = response.content.find((m) => m.contentType.includes("json")) ??
595
875
  response.content[0];
596
876
  const payload = media?.example ?? media?.schema;
597
877
  if (payload !== undefined) {
598
- out.push("```json\n" + JSON.stringify(payload, null, 2) + "\n```");
878
+ out.push(jsonCode(payload));
599
879
  }
600
880
  }
601
881
  }
@@ -0,0 +1,15 @@
1
+ export declare function isPathInside(parent: string, candidate: string): boolean;
2
+ export declare function resolveWithin(root: string, ...segments: string[]): string;
3
+ /** Revalidates the claimed output root containing a previously resolved path. */
4
+ export declare function assertClaimedOutputPath(filePath: string): void;
5
+ /**
6
+ * Resolves a generated destination and rejects any existing symlink component.
7
+ * This is synchronous so callers can validate immediately before an fs call.
8
+ */
9
+ export declare function resolveOutputPath(root: string, ...segments: string[]): string;
10
+ export declare function readOutputFileIfPresent(root: string, ...segments: string[]): Promise<string | null>;
11
+ /**
12
+ * Claims an empty output directory, recognizes directories generated by older
13
+ * Doccupine versions, and refuses to overwrite arbitrary existing projects.
14
+ */
15
+ export declare function claimOutputDirectory(outputDir: string): Promise<void>;