doccupine 0.0.146 → 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 (40) 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/mdx-reconciliation-coordinator.d.ts +83 -0
  5. package/dist/generator/mdx-reconciliation-coordinator.js +471 -0
  6. package/dist/generator/page-renderer.js +18 -13
  7. package/dist/generator/secure-source-fs.js +5 -4
  8. package/dist/generator/site-artifacts.js +2 -2
  9. package/dist/generator/watch-coordinator.js +3 -2
  10. package/dist/index.js +8 -2
  11. package/dist/lib/layout.js +18 -10
  12. package/dist/lib/openapi-rendering.d.ts +17 -0
  13. package/dist/lib/openapi-rendering.js +193 -0
  14. package/dist/lib/openapi.d.ts +1 -7
  15. package/dist/lib/openapi.js +2 -192
  16. package/dist/lib/structures.js +4 -0
  17. package/dist/lib/utils.d.ts +14 -0
  18. package/dist/lib/utils.js +30 -8
  19. package/dist/mdx-to-nextjs-generator.d.ts +2 -41
  20. package/dist/mdx-to-nextjs-generator.js +37 -469
  21. package/dist/templates/components/Chat.d.ts +1 -1
  22. package/dist/templates/components/Chat.js +20 -691
  23. package/dist/templates/components/ChatStyles.d.ts +1 -0
  24. package/dist/templates/components/ChatStyles.js +695 -0
  25. package/dist/templates/components/layout/ApiPlayground.d.ts +1 -1
  26. package/dist/templates/components/layout/ApiPlayground.js +14 -148
  27. package/dist/templates/mdx/platform/analytics.mdx.d.ts +1 -1
  28. package/dist/templates/mdx/platform/analytics.mdx.js +13 -0
  29. package/dist/templates/mdx/platform/fonts-settings.mdx.d.ts +1 -1
  30. package/dist/templates/mdx/platform/fonts-settings.mdx.js +16 -0
  31. package/dist/templates/mdx/platform/publishing.mdx.d.ts +1 -1
  32. package/dist/templates/mdx/platform/publishing.mdx.js +16 -1
  33. package/dist/templates/mdx/platform/self-updating-docs.mdx.d.ts +1 -1
  34. package/dist/templates/mdx/platform/self-updating-docs.mdx.js +17 -5
  35. package/dist/templates/package.js +3 -2
  36. package/dist/templates/prettierignore.d.ts +1 -1
  37. package/dist/templates/prettierignore.js +11 -0
  38. package/dist/templates/utils/apiPlayground.d.ts +1 -0
  39. package/dist/templates/utils/apiPlayground.js +149 -0
  40. package/package.json +1 -1
@@ -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">
@@ -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);
@@ -3,6 +3,7 @@ import chokidar from "chokidar";
3
3
  import fs from "fs-extra";
4
4
  import path from "node:path";
5
5
  import { isPathInside } from "../lib/output-safety.js";
6
+ import { isMdxPath } from "../lib/utils.js";
6
7
  export class WatchCoordinator {
7
8
  options;
8
9
  watcher = null;
@@ -103,7 +104,7 @@ export class WatchCoordinator {
103
104
  return `${sourcePath}:${await sourceFs.pathState(sourcePath, true)}`;
104
105
  }))).join("\n");
105
106
  return {
106
- mdx: await sourceFs.treeState(watchDir, (relativePath) => relativePath.toLowerCase().endsWith(".mdx"), true),
107
+ mdx: await sourceFs.treeState(watchDir, isMdxPath, true),
107
108
  configs,
108
109
  font: await sourceFs.pathState(path.join(rootDir, fontConfigFile), true),
109
110
  analytics: await sourceFs.pathState(path.join(rootDir, analyticsConfigFile), true),
@@ -219,7 +220,7 @@ export class WatchCoordinator {
219
220
  if (configFiles.includes(fileName)) {
220
221
  return true;
221
222
  }
222
- if (isFile && !filePath.endsWith(".mdx")) {
223
+ if (isFile && !isMdxPath(filePath)) {
223
224
  return true;
224
225
  }
225
226
  return false;
package/dist/index.js CHANGED
@@ -23,6 +23,12 @@ export function isProcessEntrypoint(entry = process.argv[1], self = __filename)
23
23
  }
24
24
  }
25
25
  if (isProcessEntrypoint()) {
26
- const { runCli } = await import("./cli.js");
27
- await runCli();
26
+ const { runCli, reportCliError } = await import("./cli.js");
27
+ try {
28
+ await runCli();
29
+ }
30
+ catch (error) {
31
+ reportCliError(error);
32
+ process.exitCode = 1;
33
+ }
28
34
  }
@@ -44,24 +44,32 @@ function fontImportLine(fontConfig) {
44
44
  : 'import { Inter } from "next/font/google";';
45
45
  }
46
46
  function fontDeclLine(fontConfig) {
47
- return isGoogleFont(fontConfig)
48
- ? `const font = ${fontConfig.googleFont.fontName}({ ${[
47
+ if (isGoogleFont(fontConfig)) {
48
+ const options = [
49
49
  fontConfig.googleFont.subsets?.length
50
- ? `subsets: ${JSON.stringify(fontConfig.googleFont.subsets)}`
50
+ ? `subsets: [${fontConfig.googleFont.subsets
51
+ .map((subset) => JSON.stringify(subset))
52
+ .join(", ")}]`
51
53
  : "",
52
54
  fontConfig.googleFont.weight?.length
53
55
  ? `weight: ${Array.isArray(fontConfig.googleFont.weight)
54
- ? JSON.stringify(fontConfig.googleFont.weight)
56
+ ? `[${fontConfig.googleFont.weight
57
+ .map((weight) => JSON.stringify(weight))
58
+ .join(", ")}]`
55
59
  : JSON.stringify(fontConfig.googleFont.weight)}`
56
60
  : "",
57
- ]
58
- .filter(Boolean)
59
- .join(", ")} });`
60
- : isLocalFont(fontConfig)
61
- ? `const font = localFont({
61
+ ].filter(Boolean);
62
+ return options.length
63
+ ? `const font = ${fontConfig.googleFont.fontName}({
64
+ ${options.join(",\n ")},
65
+ });`
66
+ : `const font = ${fontConfig.googleFont.fontName}({});`;
67
+ }
68
+ return isLocalFont(fontConfig)
69
+ ? `const font = localFont({
62
70
  src: ${getLocalFontSrc(fontConfig)},
63
71
  });`
64
- : 'const font = Inter({ subsets: ["latin"] });';
72
+ : 'const font = Inter({ subsets: ["latin"] });';
65
73
  }
66
74
  // The inline blocking script that resolves dark mode before the first paint.
67
75
  // It only has to decide the mode and record it on <html>: every painted color
@@ -0,0 +1,17 @@
1
+ import type { OperationDescriptor } from "./openapi-types.js";
2
+ export declare function firstLine(text: unknown): string;
3
+ /**
4
+ * Builds the API-reference landing page as safe MDX. Endpoint metadata is
5
+ * emitted through JSX string expressions, so arbitrary OpenAPI summaries,
6
+ * paths, tags, and descriptions remain text rather than executable MDX.
7
+ */
8
+ export declare function buildApiIndexBody(operations: OperationDescriptor[]): string;
9
+ /** Minimal markdown body for an endpoint, used by the llms.txt aggregation. */
10
+ export declare function buildEndpointBody(title: string, methodUpper: string, pathKey: string, opRaw: any): string;
11
+ /**
12
+ * Builds the MDX body for a generated endpoint page: the operation description,
13
+ * followed by `<Field>` documentation for the parameters and request body, and
14
+ * a schema/example code block per response. Spec-derived strings are emitted
15
+ * only through serialized JSX expressions. Rendered above the playground.
16
+ */
17
+ export declare function buildEndpointDoc(op: OperationDescriptor): string;
@@ -0,0 +1,193 @@
1
+ /* eslint-disable @typescript-eslint/no-explicit-any */
2
+ export function firstLine(text) {
3
+ if (typeof text !== "string")
4
+ return "";
5
+ return text.split("\n")[0]?.trim() ?? "";
6
+ }
7
+ /**
8
+ * Builds the API-reference landing page as safe MDX. Endpoint metadata is
9
+ * emitted through JSX string expressions, so arbitrary OpenAPI summaries,
10
+ * paths, tags, and descriptions remain text rather than executable MDX.
11
+ */
12
+ export function buildApiIndexBody(operations) {
13
+ const bySpec = new Map();
14
+ for (const operation of operations) {
15
+ const tag = operation.tags[0] ?? "Endpoints";
16
+ let byTag = bySpec.get(operation.specName);
17
+ if (!byTag) {
18
+ byTag = new Map();
19
+ bySpec.set(operation.specName, byTag);
20
+ }
21
+ const endpoints = byTag.get(tag) ?? [];
22
+ endpoints.push(operation);
23
+ byTag.set(tag, endpoints);
24
+ }
25
+ const lines = [
26
+ "# API Reference",
27
+ "",
28
+ `Browse all ${operations.length} API endpoint${operations.length === 1 ? "" : "s"}. Select an endpoint to view its parameters, responses, and live request playground.`,
29
+ ];
30
+ const multipleSpecs = bySpec.size > 1;
31
+ for (const [specName, byTag] of bySpec) {
32
+ if (multipleSpecs) {
33
+ lines.push("", `<h2>{${JSON.stringify(specName)}}</h2>`);
34
+ }
35
+ for (const [tag, endpoints] of byTag) {
36
+ const heading = multipleSpecs ? "h3" : "h2";
37
+ lines.push("", `<${heading}>{${JSON.stringify(tag)}}</${heading}>`, "", "<Columns cols={2}>");
38
+ for (const endpoint of endpoints) {
39
+ const method = endpoint.method.toUpperCase();
40
+ const title = endpoint.summary ?? `${method} ${endpoint.path}`;
41
+ const description = firstLine(endpoint.description) ||
42
+ `View the ${method} ${endpoint.path} endpoint.`;
43
+ const badgeColor = endpoint.method === "get"
44
+ ? "info"
45
+ : endpoint.method === "post"
46
+ ? "success"
47
+ : endpoint.method === "put" || endpoint.method === "patch"
48
+ ? "warning"
49
+ : endpoint.method === "delete"
50
+ ? "error"
51
+ : "gray";
52
+ 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>");
53
+ }
54
+ lines.push("", "</Columns>");
55
+ }
56
+ }
57
+ return lines.join("\n");
58
+ }
59
+ /** Minimal markdown body for an endpoint, used by the llms.txt aggregation. */
60
+ export function buildEndpointBody(title, methodUpper, pathKey, opRaw) {
61
+ const lines = [`# ${title}`, "", `\`${methodUpper} ${pathKey}\``];
62
+ if (opRaw.description && typeof opRaw.description === "string") {
63
+ lines.push("", opRaw.description);
64
+ }
65
+ else if (opRaw.summary && opRaw.summary !== title) {
66
+ lines.push("", opRaw.summary);
67
+ }
68
+ return lines.join("\n");
69
+ }
70
+ /** Human-readable type label for a (dereferenced) JSON schema. */
71
+ function docSchemaType(schema) {
72
+ if (!schema || typeof schema !== "object")
73
+ return "any";
74
+ if (Array.isArray(schema.type))
75
+ return schema.type.join(" | ");
76
+ if (schema.type === "array")
77
+ return `array of ${docSchemaType(schema.items)}`;
78
+ if (typeof schema.type === "string") {
79
+ return schema.format ? `${schema.type} (${schema.format})` : schema.type;
80
+ }
81
+ if (schema.properties)
82
+ return "object";
83
+ if (Array.isArray(schema.enum))
84
+ return "enum";
85
+ return "any";
86
+ }
87
+ /** Collapses a description to a single inline line safe inside JSX children. */
88
+ function inlineText(text) {
89
+ if (typeof text !== "string")
90
+ return "";
91
+ return text.replace(/\s+/g, " ").trim();
92
+ }
93
+ /** Emits untrusted prose as a JSX string expression, never as executable MDX. */
94
+ function jsxText(text) {
95
+ return `{${JSON.stringify(text)}}`;
96
+ }
97
+ function jsonCode(value) {
98
+ const serialized = JSON.stringify(value, null, 2) ?? "null";
99
+ return `<Code language="json" code=${jsxText(serialized)} />`;
100
+ }
101
+ /** The object schema whose `properties` we can document (unwraps arrays). */
102
+ function objectShape(schema) {
103
+ if (!schema || typeof schema !== "object")
104
+ return null;
105
+ if (schema.type === "array")
106
+ return objectShape(schema.items);
107
+ if (schema.properties && typeof schema.properties === "object")
108
+ return schema;
109
+ return null;
110
+ }
111
+ /**
112
+ * Renders one parameter/property as a `<Field>`, recursing into nested object
113
+ * properties up to `MAX_FIELD_DEPTH` levels. Nested fields are emitted flush so
114
+ * MDX does not treat the indentation as a code block.
115
+ */
116
+ const MAX_FIELD_DEPTH = 2;
117
+ function renderDocField(name, schema, required, description, depth) {
118
+ const type = docSchemaType(schema);
119
+ const desc = inlineText(description ?? schema?.description);
120
+ const lines = [
121
+ `<Field value={${JSON.stringify(name)}} type={${JSON.stringify(type)}}${required ? " required" : ""}>`,
122
+ ];
123
+ if (desc)
124
+ lines.push(jsxText(desc));
125
+ const shape = depth < MAX_FIELD_DEPTH ? objectShape(schema) : null;
126
+ if (shape) {
127
+ const req = Array.isArray(shape.required) ? shape.required : [];
128
+ for (const [propName, propSchema] of Object.entries(shape.properties)) {
129
+ lines.push(renderDocField(propName, propSchema, req.includes(propName), undefined, depth + 1));
130
+ }
131
+ }
132
+ lines.push(`</Field>`);
133
+ return lines.join("\n");
134
+ }
135
+ const PARAM_LOCATION_TITLES = {
136
+ path: "Path parameters",
137
+ query: "Query parameters",
138
+ header: "Header parameters",
139
+ cookie: "Cookie parameters",
140
+ };
141
+ /**
142
+ * Builds the MDX body for a generated endpoint page: the operation description,
143
+ * followed by `<Field>` documentation for the parameters and request body, and
144
+ * a schema/example code block per response. Spec-derived strings are emitted
145
+ * only through serialized JSX expressions. Rendered above the playground.
146
+ */
147
+ export function buildEndpointDoc(op) {
148
+ const out = [];
149
+ if (op.description)
150
+ out.push(jsxText(op.description));
151
+ else if (op.summary)
152
+ out.push(jsxText(op.summary));
153
+ for (const location of ["path", "query", "header", "cookie"]) {
154
+ const params = op.parameters.filter((p) => p.in === location);
155
+ if (params.length === 0)
156
+ continue;
157
+ out.push(`## ${PARAM_LOCATION_TITLES[location]}`);
158
+ for (const p of params) {
159
+ out.push(renderDocField(p.name, p.schema, p.required, p.description, 0));
160
+ }
161
+ }
162
+ const body = op.requestBody?.content.find((m) => m.contentType.includes("json")) ??
163
+ op.requestBody?.content[0];
164
+ if (body?.schema !== undefined) {
165
+ out.push("## Request body");
166
+ const shape = objectShape(body.schema);
167
+ if (shape) {
168
+ const req = Array.isArray(shape.required) ? shape.required : [];
169
+ for (const [propName, propSchema] of Object.entries(shape.properties)) {
170
+ out.push(renderDocField(propName, propSchema, req.includes(propName), undefined, 0));
171
+ }
172
+ }
173
+ else {
174
+ out.push(jsonCode(body.schema));
175
+ }
176
+ }
177
+ if (op.responses.length > 0) {
178
+ out.push("## Responses");
179
+ for (const response of op.responses) {
180
+ out.push(`<h3>{${JSON.stringify(response.status)}}</h3>`);
181
+ if (response.description) {
182
+ out.push(jsxText(inlineText(response.description)));
183
+ }
184
+ const media = response.content.find((m) => m.contentType.includes("json")) ??
185
+ response.content[0];
186
+ const payload = media?.example ?? media?.schema;
187
+ if (payload !== undefined) {
188
+ out.push(jsonCode(payload));
189
+ }
190
+ }
191
+ }
192
+ return out.join("\n\n");
193
+ }
@@ -1,4 +1,5 @@
1
1
  import type { NormalizedOpenApiSpec, PageMeta } from "./types.js";
2
+ export { buildEndpointDoc } from "./openapi-rendering.js";
2
3
  import type { AllowlistEntry, OperationDescriptor } from "./openapi-types.js";
3
4
  /** Default base route segment for the generated API reference section. */
4
5
  export declare const DEFAULT_API_BASE_SLUG = "api-reference";
@@ -50,10 +51,3 @@ export declare class OpenApiRegistry {
50
51
  private uniqueSlug;
51
52
  private addAllowlist;
52
53
  }
53
- /**
54
- * Builds the MDX body for a generated endpoint page: the operation description,
55
- * followed by `<Field>` documentation for the parameters and request body, and
56
- * a schema/example code block per response. Spec-derived strings are emitted
57
- * only through serialized JSX expressions. Rendered above the playground.
58
- */
59
- export declare function buildEndpointDoc(op: OperationDescriptor): string;
@@ -6,6 +6,8 @@ import fs from "node:fs/promises";
6
6
  import { fileURLToPath, pathToFileURL } from "node:url";
7
7
  import chalk from "chalk";
8
8
  import { bundle, dereference, parse } from "@readme/openapi-parser";
9
+ import { buildApiIndexBody, buildEndpointBody, firstLine, } from "./openapi-rendering.js";
10
+ export { buildEndpointDoc } from "./openapi-rendering.js";
9
11
  /* eslint-disable @typescript-eslint/no-explicit-any */
10
12
  /** Default base route segment for the generated API reference section. */
11
13
  export const DEFAULT_API_BASE_SLUG = "api-reference";
@@ -244,11 +246,6 @@ function resolveSecurity(requirements, schemes) {
244
246
  }
245
247
  return [...byName.values()];
246
248
  }
247
- function firstLine(text) {
248
- if (typeof text !== "string")
249
- return "";
250
- return text.split("\n")[0]?.trim() ?? "";
251
- }
252
249
  function isWithinDirectory(root, candidate) {
253
250
  const relative = path.relative(root, candidate);
254
251
  return (relative === "" ||
@@ -726,190 +723,3 @@ export class OpenApiRegistry {
726
723
  }
727
724
  }
728
725
  }
729
- /**
730
- * Builds the API-reference landing page as safe MDX. Endpoint metadata is
731
- * emitted through JSX string expressions, so arbitrary OpenAPI summaries,
732
- * paths, tags, and descriptions remain text rather than executable MDX.
733
- */
734
- function buildApiIndexBody(operations) {
735
- const bySpec = new Map();
736
- for (const operation of operations) {
737
- const tag = operation.tags[0] ?? "Endpoints";
738
- let byTag = bySpec.get(operation.specName);
739
- if (!byTag) {
740
- byTag = new Map();
741
- bySpec.set(operation.specName, byTag);
742
- }
743
- const endpoints = byTag.get(tag) ?? [];
744
- endpoints.push(operation);
745
- byTag.set(tag, endpoints);
746
- }
747
- const lines = [
748
- "# API Reference",
749
- "",
750
- `Browse all ${operations.length} API endpoint${operations.length === 1 ? "" : "s"}. Select an endpoint to view its parameters, responses, and live request playground.`,
751
- ];
752
- const multipleSpecs = bySpec.size > 1;
753
- for (const [specName, byTag] of bySpec) {
754
- if (multipleSpecs) {
755
- lines.push("", `<h2>{${JSON.stringify(specName)}}</h2>`);
756
- }
757
- for (const [tag, endpoints] of byTag) {
758
- const heading = multipleSpecs ? "h3" : "h2";
759
- lines.push("", `<${heading}>{${JSON.stringify(tag)}}</${heading}>`, "", "<Columns cols={2}>");
760
- for (const endpoint of endpoints) {
761
- const method = endpoint.method.toUpperCase();
762
- const title = endpoint.summary ?? `${method} ${endpoint.path}`;
763
- const description = firstLine(endpoint.description) ||
764
- `View the ${method} ${endpoint.path} endpoint.`;
765
- const badgeColor = endpoint.method === "get"
766
- ? "info"
767
- : endpoint.method === "post"
768
- ? "success"
769
- : endpoint.method === "put" || endpoint.method === "patch"
770
- ? "warning"
771
- : endpoint.method === "delete"
772
- ? "error"
773
- : "gray";
774
- 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>");
775
- }
776
- lines.push("", "</Columns>");
777
- }
778
- }
779
- return lines.join("\n");
780
- }
781
- /** Minimal markdown body for an endpoint, used by the llms.txt aggregation. */
782
- function buildEndpointBody(title, methodUpper, pathKey, opRaw) {
783
- const lines = [`# ${title}`, "", `\`${methodUpper} ${pathKey}\``];
784
- if (opRaw.description && typeof opRaw.description === "string") {
785
- lines.push("", opRaw.description);
786
- }
787
- else if (opRaw.summary && opRaw.summary !== title) {
788
- lines.push("", opRaw.summary);
789
- }
790
- return lines.join("\n");
791
- }
792
- /** Human-readable type label for a (dereferenced) JSON schema. */
793
- function docSchemaType(schema) {
794
- if (!schema || typeof schema !== "object")
795
- return "any";
796
- if (Array.isArray(schema.type))
797
- return schema.type.join(" | ");
798
- if (schema.type === "array")
799
- return `array of ${docSchemaType(schema.items)}`;
800
- if (typeof schema.type === "string") {
801
- return schema.format ? `${schema.type} (${schema.format})` : schema.type;
802
- }
803
- if (schema.properties)
804
- return "object";
805
- if (Array.isArray(schema.enum))
806
- return "enum";
807
- return "any";
808
- }
809
- /** Collapses a description to a single inline line safe inside JSX children. */
810
- function inlineText(text) {
811
- if (typeof text !== "string")
812
- return "";
813
- return text.replace(/\s+/g, " ").trim();
814
- }
815
- /** Emits untrusted prose as a JSX string expression, never as executable MDX. */
816
- function jsxText(text) {
817
- return `{${JSON.stringify(text)}}`;
818
- }
819
- function jsonCode(value) {
820
- const serialized = JSON.stringify(value, null, 2) ?? "null";
821
- return `<Code language="json" code=${jsxText(serialized)} />`;
822
- }
823
- /** The object schema whose `properties` we can document (unwraps arrays). */
824
- function objectShape(schema) {
825
- if (!schema || typeof schema !== "object")
826
- return null;
827
- if (schema.type === "array")
828
- return objectShape(schema.items);
829
- if (schema.properties && typeof schema.properties === "object")
830
- return schema;
831
- return null;
832
- }
833
- /**
834
- * Renders one parameter/property as a `<Field>`, recursing into nested object
835
- * properties up to `MAX_FIELD_DEPTH` levels. Nested fields are emitted flush so
836
- * MDX does not treat the indentation as a code block.
837
- */
838
- const MAX_FIELD_DEPTH = 2;
839
- function renderDocField(name, schema, required, description, depth) {
840
- const type = docSchemaType(schema);
841
- const desc = inlineText(description ?? schema?.description);
842
- const lines = [
843
- `<Field value={${JSON.stringify(name)}} type={${JSON.stringify(type)}}${required ? " required" : ""}>`,
844
- ];
845
- if (desc)
846
- lines.push(jsxText(desc));
847
- const shape = depth < MAX_FIELD_DEPTH ? objectShape(schema) : null;
848
- if (shape) {
849
- const req = Array.isArray(shape.required) ? shape.required : [];
850
- for (const [propName, propSchema] of Object.entries(shape.properties)) {
851
- lines.push(renderDocField(propName, propSchema, req.includes(propName), undefined, depth + 1));
852
- }
853
- }
854
- lines.push(`</Field>`);
855
- return lines.join("\n");
856
- }
857
- const PARAM_LOCATION_TITLES = {
858
- path: "Path parameters",
859
- query: "Query parameters",
860
- header: "Header parameters",
861
- cookie: "Cookie parameters",
862
- };
863
- /**
864
- * Builds the MDX body for a generated endpoint page: the operation description,
865
- * followed by `<Field>` documentation for the parameters and request body, and
866
- * a schema/example code block per response. Spec-derived strings are emitted
867
- * only through serialized JSX expressions. Rendered above the playground.
868
- */
869
- export function buildEndpointDoc(op) {
870
- const out = [];
871
- if (op.description)
872
- out.push(jsxText(op.description));
873
- else if (op.summary)
874
- out.push(jsxText(op.summary));
875
- for (const location of ["path", "query", "header", "cookie"]) {
876
- const params = op.parameters.filter((p) => p.in === location);
877
- if (params.length === 0)
878
- continue;
879
- out.push(`## ${PARAM_LOCATION_TITLES[location]}`);
880
- for (const p of params) {
881
- out.push(renderDocField(p.name, p.schema, p.required, p.description, 0));
882
- }
883
- }
884
- const body = op.requestBody?.content.find((m) => m.contentType.includes("json")) ??
885
- op.requestBody?.content[0];
886
- if (body?.schema !== undefined) {
887
- out.push("## Request body");
888
- const shape = objectShape(body.schema);
889
- if (shape) {
890
- const req = Array.isArray(shape.required) ? shape.required : [];
891
- for (const [propName, propSchema] of Object.entries(shape.properties)) {
892
- out.push(renderDocField(propName, propSchema, req.includes(propName), undefined, 0));
893
- }
894
- }
895
- else {
896
- out.push(jsonCode(body.schema));
897
- }
898
- }
899
- if (op.responses.length > 0) {
900
- out.push("## Responses");
901
- for (const response of op.responses) {
902
- out.push(`<h3>{${JSON.stringify(response.status)}}</h3>`);
903
- if (response.description) {
904
- out.push(jsxText(inlineText(response.description)));
905
- }
906
- const media = response.content.find((m) => m.contentType.includes("json")) ??
907
- response.content[0];
908
- const payload = media?.example ?? media?.schema;
909
- if (payload !== undefined) {
910
- out.push(jsonCode(payload));
911
- }
912
- }
913
- }
914
- return out.join("\n\n");
915
- }
@@ -14,6 +14,7 @@ import { searchRoutesTemplate } from "../templates/app/api/search/route.js";
14
14
  import { notFoundTemplate } from "../templates/app/not-found.js";
15
15
  import { themeTemplate } from "../templates/app/theme.js";
16
16
  import { chatTemplate } from "../templates/components/Chat.js";
17
+ import { chatStylesTemplate } from "../templates/components/ChatStyles.js";
17
18
  import { lockBodyScrollTemplate } from "../templates/components/LockBodyScroll.js";
18
19
  import { docsTemplate } from "../templates/components/Docs.js";
19
20
  import { docsSideBarTemplate } from "../templates/components/DocsSideBar.js";
@@ -93,6 +94,7 @@ import { configTemplate } from "../templates/utils/config.js";
93
94
  import { playgroundAllowlistTemplate } from "../templates/utils/playgroundAllowlist.js";
94
95
  import { ssrfGuardTemplate } from "../templates/utils/ssrfGuard.js";
95
96
  import { apiSnippetsTemplate } from "../templates/utils/apiSnippets.js";
97
+ import { apiPlaygroundUtilsTemplate } from "../templates/utils/apiPlayground.js";
96
98
  import { requestBodyTemplate } from "../templates/utils/requestBody.js";
97
99
  import { playgroundRoutesTemplate } from "../templates/app/api/playground/route.js";
98
100
  import { playgroundAllowlistStubTemplate } from "../templates/services/openapi/playgroundAllowlistStub.js";
@@ -207,8 +209,10 @@ export const appStructure = {
207
209
  "utils/playgroundAllowlist.ts": playgroundAllowlistTemplate,
208
210
  "utils/ssrfGuard.ts": ssrfGuardTemplate,
209
211
  "utils/apiSnippets.ts": apiSnippetsTemplate,
212
+ "utils/apiPlayground.ts": apiPlaygroundUtilsTemplate,
210
213
  "utils/requestBody.ts": requestBodyTemplate,
211
214
  "components/Chat.tsx": chatTemplate,
215
+ "components/ChatStyles.ts": chatStylesTemplate,
212
216
  "components/LockBodyScroll.ts": lockBodyScrollTemplate,
213
217
  "components/Docs.tsx": docsTemplate,
214
218
  "components/DocsSideBar.tsx": docsSideBarTemplate,