@dogsbay/format-openapi 0.2.0-beta.117 → 0.2.0-beta.119

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.
package/dist/core.js ADDED
@@ -0,0 +1,842 @@
1
+ /**
2
+ * The OpenAPI conversion with no file or network access, and no Node
3
+ * built-ins: it runs in a Cloudflare Worker (dogsbay-ssg) as well as in
4
+ * the CLI. A spec comes in as text (or an already-parsed object) and goes
5
+ * out as `endpoint` TreeNodes; finding and reading the file is the
6
+ * caller's (parse.ts for the CLI, a build's file map for dogsbay-ssg).
7
+ *
8
+ * text ─ parseSpecText ─▶ object ─ prepareSpec ─▶ spec ─┬ embedSpec (one page's body)
9
+ * └ specToPages (a page per operation)
10
+ *
11
+ * `prepareSpec` is the expensive step (upgrade, dereference); `createSpecCache`
12
+ * runs it once per spec file per build. `findSpec` holds the rules for which
13
+ * file a page's `:::openapi{spec}` may name.
14
+ */
15
+ import { dereference, upgrade } from "@scalar/openapi-parser";
16
+ import MarkdownIt from "markdown-it";
17
+ import { operationToSlug, slugifyTag } from "./slug.js";
18
+ import { resolveCodeSamples } from "./code-samples.js";
19
+ export { findSpec, specCandidates } from "./spec-path.js";
20
+ const HTTP_METHODS = [
21
+ "get",
22
+ "post",
23
+ "put",
24
+ "patch",
25
+ "delete",
26
+ "head",
27
+ "options",
28
+ ];
29
+ /**
30
+ * A dereferenced spec (`prepareSpec`) as a page per operation, a page per tag
31
+ * and an info page, with their nav: for a spec that IS the source.
32
+ */
33
+ export function specToPages(spec, options = {}) {
34
+ const hrefPrefix = normalisePrefix(options.hrefPrefix);
35
+ const pages = [];
36
+ // Collect tag descriptions (from spec.tags[]) for tag overview pages.
37
+ const tagDescriptions = new Map();
38
+ for (const t of spec.tags || []) {
39
+ if (txt(t?.name))
40
+ tagDescriptions.set(t.name, txt(t.description) ?? "");
41
+ }
42
+ const tagToOps = new Map();
43
+ const untagged = [];
44
+ for (const op of collectOperations(spec)) {
45
+ const { method, path, operation, props } = op;
46
+ const primaryTag = props.tags?.[0];
47
+ const tagSlug = primaryTag ? slugifyTag(primaryTag) : "";
48
+ const opSlug = operationToSlug(method, path, txt(operation.operationId));
49
+ const slug = tagSlug ? `${tagSlug}/${opSlug}` : opSlug;
50
+ const title = txt(operation.summary) || `${method.toUpperCase()} ${path}`;
51
+ const tree = [
52
+ {
53
+ type: "endpoint",
54
+ props: structuredClone(props),
55
+ },
56
+ ];
57
+ const headings = [{ depth: 1, slug: opSlug, text: title }];
58
+ pages.push({
59
+ slug,
60
+ title,
61
+ tree,
62
+ headings,
63
+ });
64
+ const summary = {
65
+ slug,
66
+ title,
67
+ method,
68
+ path,
69
+ deprecated: operation.deprecated === true,
70
+ };
71
+ if (primaryTag) {
72
+ const arr = tagToOps.get(primaryTag) || [];
73
+ arr.push(summary);
74
+ tagToOps.set(primaryTag, arr);
75
+ }
76
+ else {
77
+ untagged.push(summary);
78
+ }
79
+ }
80
+ // Tag overview pages.
81
+ for (const [tagName, ops] of tagToOps) {
82
+ const tagSlug = slugifyTag(tagName);
83
+ const description = tagDescriptions.get(tagName) || "";
84
+ pages.push(buildTagPage(tagName, tagSlug, description, ops));
85
+ }
86
+ // Root info page.
87
+ const info = spec.info || {};
88
+ pages.push(buildInfoPage(txt(info.title) || "API Reference", txt(info.description) ?? "", txt(info.version) ?? (typeof info.version === "number" ? String(info.version) : "")));
89
+ // Build nav: tag groups in declaration order, with operations as
90
+ // children. Untagged operations land under a synthetic "Other" group
91
+ // so they're discoverable but visually separated.
92
+ const nav = buildNav(spec, pages, tagToOps, untagged, hrefPrefix);
93
+ return { pages, nav };
94
+ }
95
+ /**
96
+ * Spec text → object. JSON is read natively; YAML needs a parser passed in
97
+ * (`yaml`'s `parse`, js-yaml's `load`), so a host that has one does not
98
+ * bundle a second.
99
+ */
100
+ export function parseSpecText(text, parseYaml) {
101
+ try {
102
+ return JSON.parse(text);
103
+ }
104
+ catch (err) {
105
+ if (!parseYaml)
106
+ throw new Error(`not JSON, and no YAML parser was given (${err.message})`);
107
+ return parseYaml(text);
108
+ }
109
+ }
110
+ /**
111
+ * A parsed spec → the dereferenced OpenAPI 3 document every function here
112
+ * reads. Swagger 2.0 is upgraded to OpenAPI 3 first: everything below reads
113
+ * the 3.x shape (`requestBody`, response `content`, `servers`), so a 2.0
114
+ * spec parsed without the upgrade lost every body parameter and response
115
+ * schema while still producing plausible-looking pages. Canonical's Anbox
116
+ * Cloud API specs are 2.0.
117
+ */
118
+ export async function prepareSpec(parsed, label = "the spec") {
119
+ if (!parsed || typeof parsed !== "object")
120
+ throw new Error(`${label} is not an OpenAPI document`);
121
+ let doc = acyclic(parsed, label);
122
+ if (typeof doc.swagger === "string" && doc.swagger.startsWith("2")) {
123
+ doc = upgrade(doc).specification;
124
+ }
125
+ const { schema: spec } = await dereference(doc);
126
+ if (!spec)
127
+ throw new Error(`Failed to dereference OpenAPI spec at ${label}`);
128
+ return spec;
129
+ }
130
+ /** The most a parsed document may expand to, in characters, counting every alias at each place it is used. */
131
+ const SPEC_MAX_EXPANDED_CHARS = 64_000_000;
132
+ /**
133
+ * A parsed document with no cycles, and no larger than SPEC_MAX_EXPANDED_CHARS
134
+ * once its aliases are expanded.
135
+ *
136
+ * YAML aliases make the parsed value a graph. `&a {self: *a}` is an object
137
+ * that contains itself, which sent the dereferencer into unbounded
138
+ * recursion (a stack overflow, not an error). A value reached again while
139
+ * it is still being copied (a cycle) becomes "(circular)"; one reached
140
+ * again after (an alias used twice) is shared, as the parser shared it, so
141
+ * the copy is linear.
142
+ *
143
+ * Sharing is not enough: the dereferencer and every renderer walk each path
144
+ * through the graph, so `l2: {l: *l1, r: *l1}` doubles per level (a 724-byte
145
+ * spec took 6.8 s to dereference at depth 22, and a `summary` aliased the
146
+ * same way made a 147 MB page). So the copy also counts the expanded size
147
+ * (memoized per node, so counting is linear too) and refuses a document past
148
+ * the bound, as the `yaml` parser does with its alias limit. js-yaml, which
149
+ * dogsbay-ssg parses with, has no such limit. JSON never has either problem.
150
+ */
151
+ function acyclic(root, label) {
152
+ const done = new Map();
153
+ const open = new Set();
154
+ const add = (a, b) => Math.min(SPEC_MAX_EXPANDED_CHARS + 1, a + b);
155
+ const copy = (v, depth) => {
156
+ if (typeof v === "string")
157
+ return { out: v, size: v.length + 2 };
158
+ if (!v || typeof v !== "object" || v instanceof Date)
159
+ return { out: v, size: 8 };
160
+ const finished = done.get(v);
161
+ if (finished)
162
+ return finished;
163
+ if (open.has(v))
164
+ return { out: "(circular)", size: 12 };
165
+ if (depth > 1_000)
166
+ throw new Error(`${label} is nested more than 1,000 levels deep`);
167
+ open.add(v);
168
+ let size = 2;
169
+ let out;
170
+ if (Array.isArray(v)) {
171
+ out = v.map((e) => {
172
+ const c = copy(e, depth + 1);
173
+ size = add(size, c.size + 1);
174
+ return c.out;
175
+ });
176
+ }
177
+ else {
178
+ out = {};
179
+ for (const [k, e] of Object.entries(v)) {
180
+ const c = copy(e, depth + 1);
181
+ size = add(size, c.size + k.length + 4);
182
+ out[k] = c.out;
183
+ }
184
+ }
185
+ open.delete(v);
186
+ const r = { out, size };
187
+ done.set(v, r);
188
+ return r;
189
+ };
190
+ const r = copy(root, 0);
191
+ if (r.size > SPEC_MAX_EXPANDED_CHARS) {
192
+ throw new Error(`${label} expands to more than ${SPEC_MAX_EXPANDED_CHARS.toLocaleString("en")} characters through repeated YAML aliases`);
193
+ }
194
+ return r.out;
195
+ }
196
+ /**
197
+ * Prepared specs by path, each parsed and dereferenced once however many
198
+ * pages embed it. `read` returns the file's text; failures are cached too,
199
+ * so a broken spec is reported per page without being parsed again.
200
+ */
201
+ export function createSpecCache(read, parseYaml) {
202
+ const specs = new Map();
203
+ return {
204
+ get(path) {
205
+ let p = specs.get(path);
206
+ if (!p) {
207
+ p = Promise.resolve()
208
+ .then(() => read(path))
209
+ .then((text) => prepareSpec(parseSpecText(text, parseYaml), path));
210
+ specs.set(path, p);
211
+ }
212
+ return p;
213
+ },
214
+ get size() {
215
+ return specs.size;
216
+ },
217
+ };
218
+ }
219
+ /** A spec field read as text: a YAML alias can put any value where a string belongs. */
220
+ const txt = (v) => (typeof v === "string" ? v : undefined);
221
+ // ─── Values copied from the spec ─────────────────────────────────────
222
+ /**
223
+ * Bounds on the spec values an operation's props carry verbatim: examples,
224
+ * defaults and enums. A YAML anchor repeated through aliases is ONE object
225
+ * in the parsed spec and a full copy in every place a renderer serializes
226
+ * it: a 300-byte spec grew to a 33 MB page and 720 MB of memory in
227
+ * dogsbay-ssg, and an example that refers to itself crashed the build
228
+ * (JSON.stringify on a cycle). Values are copied here, so props are plain,
229
+ * acyclic and bounded, and every renderer is protected.
230
+ */
231
+ const VALUE_MAX_CHARS = 4_000; // one default, enum entry or property example
232
+ const EXAMPLE_MAX_CHARS = 50_000; // a request or response example
233
+ const ENUM_MAX_VALUES = 200;
234
+ const OPERATION_MAX_CHARS = 500_000; // everything copied for one operation
235
+ const VALUE_MAX_DEPTH = 32;
236
+ /** What a value over its bound is shown as. */
237
+ export const VALUE_TOO_LARGE = "(not shown: too large)";
238
+ /** The budget of the operation being collected (collectOperations is synchronous). */
239
+ let operationBudget = OPERATION_MAX_CHARS;
240
+ class TooLarge extends Error {
241
+ }
242
+ /**
243
+ * A plain JSON copy of a spec value within `max` serialized characters (and
244
+ * the operation's remaining budget), or VALUE_TOO_LARGE. A reference back
245
+ * to an enclosing value becomes "(circular)". Counting stops at the bound,
246
+ * so an exponentially aliased value costs no more than the bound to refuse.
247
+ */
248
+ function copyValue(v, max = VALUE_MAX_CHARS) {
249
+ if (v === undefined)
250
+ return undefined;
251
+ const limit = Math.min(max, operationBudget);
252
+ let left = limit;
253
+ const ancestors = new Set();
254
+ const spend = (n) => {
255
+ if ((left -= n) < 0)
256
+ throw new TooLarge();
257
+ };
258
+ const copy = (x, depth) => {
259
+ if (x === null || x === undefined)
260
+ return spend(4), null;
261
+ if (typeof x === "string")
262
+ return spend(x.length + 2), x;
263
+ if (typeof x === "number" || typeof x === "boolean")
264
+ return spend(String(x).length), x;
265
+ if (x instanceof Date)
266
+ return spend(26), Number.isNaN(x.getTime()) ? String(x) : x.toISOString();
267
+ if (typeof x !== "object")
268
+ return spend(String(x).length + 2), String(x);
269
+ if (ancestors.has(x))
270
+ return spend(10), "(circular)";
271
+ if (depth >= VALUE_MAX_DEPTH)
272
+ throw new TooLarge();
273
+ ancestors.add(x);
274
+ try {
275
+ if (Array.isArray(x))
276
+ return spend(2), x.map((e) => (spend(1), copy(e, depth + 1)));
277
+ const out = {};
278
+ spend(2);
279
+ for (const [k, e] of Object.entries(x)) {
280
+ spend(k.length + 4);
281
+ out[k] = copy(e, depth + 1);
282
+ }
283
+ return out;
284
+ }
285
+ finally {
286
+ ancestors.delete(x);
287
+ }
288
+ };
289
+ try {
290
+ const out = copy(v, 0);
291
+ operationBudget -= limit - left;
292
+ return out;
293
+ }
294
+ catch (err) {
295
+ if (!(err instanceof TooLarge))
296
+ throw err;
297
+ operationBudget -= Math.min(operationBudget, VALUE_TOO_LARGE.length);
298
+ return VALUE_TOO_LARGE;
299
+ }
300
+ }
301
+ /** An enum's values, each copied with copyValue, at most ENUM_MAX_VALUES; a cut list ends in "…". */
302
+ function copyEnum(list) {
303
+ if (!Array.isArray(list))
304
+ return undefined;
305
+ const out = [];
306
+ for (const v of list) {
307
+ if (out.length >= ENUM_MAX_VALUES || operationBudget <= 0)
308
+ return [...out, "…"];
309
+ out.push(copyValue(v));
310
+ }
311
+ return out;
312
+ }
313
+ /** Every operation in the spec, in document order, as `endpoint` props. */
314
+ function collectOperations(spec) {
315
+ const baseUrl = txt(spec.servers?.[0]?.url) ?? "";
316
+ const out = [];
317
+ for (const [path, pathItem] of Object.entries(spec.paths || {})) {
318
+ if (!pathItem)
319
+ continue;
320
+ for (const method of HTTP_METHODS) {
321
+ const operation = pathItem[method];
322
+ if (!operation)
323
+ continue;
324
+ operationBudget = OPERATION_MAX_CHARS;
325
+ const opTags = Array.isArray(operation.tags) ? operation.tags.filter((t) => typeof t === "string") : [];
326
+ const props = {
327
+ method,
328
+ path,
329
+ baseUrl,
330
+ summary: txt(operation.summary) || undefined,
331
+ description: txt(operation.description) || undefined,
332
+ operationId: txt(operation.operationId) || undefined,
333
+ tags: opTags.length > 0 ? opTags : undefined,
334
+ deprecated: operation.deprecated === true ? true : undefined,
335
+ parameters: extractParameters(operation, pathItem),
336
+ ...extractRequestBody(operation),
337
+ responses: extractResponses(operation),
338
+ codeSamples: resolveCodeSamples(operation, method, path, baseUrl),
339
+ };
340
+ out.push({ method, path, operation, props });
341
+ }
342
+ }
343
+ return out;
344
+ }
345
+ /**
346
+ * The operation a `:::openapi` directive selects from its props, or why it
347
+ * cannot: `path` and `method` come together or not at all.
348
+ */
349
+ export function directiveOperation(props) {
350
+ const path = typeof props?.path === "string" ? props.path.trim() : "";
351
+ const method = typeof props?.method === "string" ? props.method.trim().toLowerCase() : "";
352
+ if (!path && !method)
353
+ return {};
354
+ if (!path || !method)
355
+ return { error: "`path` and `method` select an operation together; give both or neither" };
356
+ if (!HTTP_METHODS.includes(method))
357
+ return { error: `not an HTTP method: ${method}` };
358
+ return { operation: { path, method } };
359
+ }
360
+ /**
361
+ * A whole spec as the BODY of one page: what Swagger UI or Redoc show when a
362
+ * page embeds them. The info version and description, then a section per tag
363
+ * (declared order, then first use; untagged operations last, under "Other"),
364
+ * each holding its operations as `endpoint` nodes in document order.
365
+ *
366
+ * `spec` is a dereferenced spec (`prepareSpec`), and is not modified: the
367
+ * nodes are copies, so one parsed spec serves every page that embeds it.
368
+ *
369
+ * `specToPages` is the other shape — a page per operation — for a spec
370
+ * that IS the source. This one is for a spec a prose page points at.
371
+ */
372
+ export function embedSpec(spec, options = {}) {
373
+ if (options.operation) {
374
+ const { path, method } = options.operation;
375
+ const op = collectOperations(spec).find((o) => o.path === path && o.method === method.toLowerCase());
376
+ if (!op)
377
+ throw new Error(`the spec has no operation ${method.toUpperCase()} ${path}`);
378
+ return { tree: [{ type: "endpoint", props: structuredClone(op.props) }], headings: [], operations: 1 };
379
+ }
380
+ const level = Math.min(6, Math.max(2, options.level ?? 2));
381
+ const tree = [];
382
+ const headings = [];
383
+ const used = new Set(options.usedIds ?? []);
384
+ // A description's own headings go under the section that holds it, with
385
+ // ids, and into the outline (a `# Title` was a second H1).
386
+ const describe = (text, minLevel) => {
387
+ const d = descriptionHtml(text, minLevel, used);
388
+ headings.push(...d.headings);
389
+ tree.push({ type: "prose", html: d.html });
390
+ };
391
+ const info = spec.info || {};
392
+ if (txt(info.version) || typeof info.version === "number") {
393
+ tree.push({
394
+ type: "prose",
395
+ html: `<p class="text-sm text-muted-foreground">Version ${escapeHtml(String(info.version))}</p>`,
396
+ });
397
+ }
398
+ if (typeof info.description === "string" && info.description.trim()) {
399
+ describe(info.description, level);
400
+ }
401
+ const tagDescriptions = new Map();
402
+ for (const t of spec.tags || []) {
403
+ if (txt(t?.name))
404
+ tagDescriptions.set(t.name, txt(t.description) ?? "");
405
+ }
406
+ const groups = new Map();
407
+ for (const t of tagDescriptions.keys())
408
+ groups.set(t, []);
409
+ const untagged = [];
410
+ const operations = collectOperations(spec);
411
+ for (const { props } of operations) {
412
+ // A copy: enum, default and example values are the spec's own objects, and the spec is shared.
413
+ const node = { type: "endpoint", props: structuredClone(props) };
414
+ const tag = props.tags?.[0];
415
+ if (!tag) {
416
+ untagged.push(node);
417
+ continue;
418
+ }
419
+ if (!groups.has(tag))
420
+ groups.set(tag, []);
421
+ groups.get(tag).push(node);
422
+ }
423
+ if (untagged.length)
424
+ groups.set("\u0000other", untagged);
425
+ for (const [tag, nodes] of groups) {
426
+ if (!nodes.length)
427
+ continue;
428
+ const text = tag === "\u0000other" ? "Other" : tag;
429
+ const id = uniqueId(slugifyTag(text) || "section", used);
430
+ tree.push({
431
+ type: "heading",
432
+ props: { level, id },
433
+ inline: [{ type: "text", text: text }],
434
+ });
435
+ headings.push({ depth: level, slug: id, text });
436
+ const description = tagDescriptions.get(tag);
437
+ if (description)
438
+ describe(description, level + 1);
439
+ tree.push(...nodes);
440
+ }
441
+ return { tree, headings, operations: operations.length };
442
+ }
443
+ function uniqueId(base, used) {
444
+ let id = base;
445
+ for (let n = 2; used.has(id); n++)
446
+ id = `${base}-${n}`;
447
+ used.add(id);
448
+ return id;
449
+ }
450
+ /**
451
+ * A description (CommonMark) → HTML with its headings shifted so the
452
+ * highest is `minLevel`, each given a unique id, and listed for the TOC.
453
+ * Raw HTML stays off (see `md`).
454
+ */
455
+ function descriptionHtml(text, minLevel, used) {
456
+ const tokens = md.parse(text, {});
457
+ const levels = tokens.filter((t) => t.type === "heading_open").map((t) => Number(t.tag.slice(1)));
458
+ const headings = [];
459
+ if (levels.length) {
460
+ const shift = Math.max(0, minLevel - Math.min(...levels));
461
+ for (let i = 0; i < tokens.length; i++) {
462
+ const t = tokens[i];
463
+ if (t.type !== "heading_open")
464
+ continue;
465
+ const depth = Math.min(6, Number(t.tag.slice(1)) + shift);
466
+ const inline = tokens[i + 1];
467
+ const label = (inline?.children ?? [])
468
+ .filter((c) => c.type === "text" || c.type === "code_inline")
469
+ .map((c) => c.content)
470
+ .join("")
471
+ .trim();
472
+ const id = uniqueId(slugifyTag(label) || "section", used);
473
+ t.tag = `h${depth}`;
474
+ t.attrSet("id", id);
475
+ if (tokens[i + 2]?.type === "heading_close")
476
+ tokens[i + 2].tag = `h${depth}`;
477
+ headings.push({ depth, slug: id, text: label });
478
+ }
479
+ }
480
+ return { html: md.renderer.render(tokens, md.options, {}).trim(), headings };
481
+ }
482
+ function normalisePrefix(p) {
483
+ if (!p)
484
+ return "";
485
+ return p.replace(/\/+$/, "");
486
+ }
487
+ /** The one non-null type of a schema: OpenAPI 3.1 (and an upgraded 2.0
488
+ * spec) writes a nullable object as `type: [object, "null"]`. */
489
+ function primaryType(schema) {
490
+ if (!schema)
491
+ return undefined;
492
+ if (!Array.isArray(schema.type))
493
+ return schema.type;
494
+ const types = schema.type.filter((t) => t !== "null");
495
+ return types.length === 1 ? types[0] : undefined;
496
+ }
497
+ function schemaToType(schema, depth = 0) {
498
+ if (!schema)
499
+ return "any";
500
+ // An array of itself (a cycle once dereferenced) has no finite name.
501
+ if (depth > SCHEMA_MAX_DEPTH)
502
+ return "any";
503
+ // OpenAPI 3.1 (and a Swagger 2.0 spec upgraded to it) writes nullable as
504
+ // a type list: `type: [string, "null"]`.
505
+ if (Array.isArray(schema.type)) {
506
+ const types = schema.type.filter((t) => t !== "null");
507
+ if (types.length === 1)
508
+ return schemaToType({ ...schema, type: types[0] }, depth + 1);
509
+ return types.length ? types.join(" | ") : "null";
510
+ }
511
+ if (schema.type === "array") {
512
+ const itemType = schema.items ? schemaToType(schema.items, depth + 1) : "any";
513
+ return `${itemType}[]`;
514
+ }
515
+ return schema.type || "any";
516
+ }
517
+ /**
518
+ * Bounds on walking one schema. A dereferenced spec is a GRAPH: a
519
+ * self-referencing schema is a cycle (the walk overflowed the stack), and
520
+ * eight properties that each reference the level below grow 8× per level
521
+ * (a 2.2 KB spec made 18 MB of tree at depth 6). Past a bound the walk stops
522
+ * and the property shows without children.
523
+ */
524
+ const SCHEMA_MAX_DEPTH = 10;
525
+ const SCHEMA_MAX_NODES = 2000;
526
+ const newWalk = () => ({ nodes: SCHEMA_MAX_NODES, depth: 0, ancestors: new Set() });
527
+ /** Run `f` one level into `schema`, or return `empty` past a bound. */
528
+ function descend(walk, schema, empty, f) {
529
+ if (!schema || typeof schema !== "object")
530
+ return f();
531
+ if (walk.depth >= SCHEMA_MAX_DEPTH || walk.nodes <= 0 || walk.ancestors.has(schema))
532
+ return empty;
533
+ walk.depth++;
534
+ walk.ancestors.add(schema);
535
+ try {
536
+ return f();
537
+ }
538
+ finally {
539
+ walk.depth--;
540
+ walk.ancestors.delete(schema);
541
+ }
542
+ }
543
+ function extractSchemaProperties(schema, requiredFields, walk = newWalk()) {
544
+ if (!schema?.properties)
545
+ return [];
546
+ return descend(walk, schema, [], () => propertiesOf(schema, requiredFields, walk));
547
+ }
548
+ function propertiesOf(schema, requiredFields, walk) {
549
+ const required = requiredFields || schema.required || [];
550
+ const out = [];
551
+ for (const [name, prop] of Object.entries(schema.properties)) {
552
+ if (walk.nodes-- <= 0)
553
+ break;
554
+ out.push(propertyOf(name, prop ?? {}, required, walk));
555
+ }
556
+ return out;
557
+ }
558
+ function propertyOf(name, prop, required, walk) {
559
+ const result = {
560
+ name,
561
+ type: schemaToType(prop),
562
+ required: required.includes(name),
563
+ };
564
+ if (txt(prop.description))
565
+ result.description = prop.description;
566
+ if (prop.nullable)
567
+ result.nullable = true;
568
+ if (txt(prop.format))
569
+ result.format = prop.format;
570
+ if (prop.enum)
571
+ result.enum = copyEnum(prop.enum);
572
+ if (prop.default !== undefined)
573
+ result.default = copyValue(prop.default);
574
+ if (prop.example !== undefined)
575
+ result.example = copyValue(prop.example);
576
+ if (primaryType(prop) === "object" && prop.properties) {
577
+ result.properties = extractSchemaProperties(prop, undefined, walk);
578
+ }
579
+ if (primaryType(prop) === "array" && prop.items) {
580
+ if (primaryType(prop.items) === "object" && prop.items.properties) {
581
+ result.items = extractSchemaProperties(prop.items, undefined, walk);
582
+ }
583
+ }
584
+ return result;
585
+ }
586
+ function extractParameters(operation, pathItem) {
587
+ const params = [];
588
+ const allParams = [
589
+ ...(pathItem.parameters || []),
590
+ ...(operation.parameters || []),
591
+ ];
592
+ // Operation-level wins over path-level on (name, in) collision.
593
+ const seen = new Map();
594
+ for (const p of allParams) {
595
+ if (!txt(p?.name) || !txt(p?.in))
596
+ continue;
597
+ seen.set(`${p.name}:${p.in}`, p);
598
+ }
599
+ for (const p of seen.values()) {
600
+ const param = {
601
+ name: p.name,
602
+ in: p.in,
603
+ type: schemaToType(p.schema),
604
+ required: p.required || false,
605
+ };
606
+ if (txt(p.description))
607
+ param.description = p.description;
608
+ if (p.schema?.default !== undefined) {
609
+ const d = copyValue(p.schema.default);
610
+ param.default = typeof d === "string" ? d : JSON.stringify(d);
611
+ }
612
+ if (p.schema?.enum)
613
+ param.enum = copyEnum(p.schema.enum);
614
+ if (p.deprecated)
615
+ param.deprecated = true;
616
+ params.push(param);
617
+ }
618
+ return params;
619
+ }
620
+ function extractRequestBody(operation) {
621
+ const body = operation.requestBody;
622
+ if (!body?.content)
623
+ return {};
624
+ const mediaType = body.content["application/json"] ||
625
+ Object.values(body.content)[0];
626
+ if (!mediaType?.schema)
627
+ return {};
628
+ return {
629
+ requestBody: extractSchemaProperties(mediaType.schema),
630
+ requestBodyExample: copyValue(generateExampleFromSchema(mediaType.schema), EXAMPLE_MAX_CHARS),
631
+ };
632
+ }
633
+ function extractResponses(operation) {
634
+ if (!operation.responses)
635
+ return [];
636
+ return Object.entries(operation.responses)
637
+ .filter(([status]) => status !== "default")
638
+ .map(([status, resp]) => {
639
+ const result = {
640
+ status,
641
+ description: txt(resp.description),
642
+ };
643
+ if (resp.content) {
644
+ const contentTypeKey = resp.content["application/json"]
645
+ ? "application/json"
646
+ : Object.keys(resp.content)[0];
647
+ const mediaType = resp.content[contentTypeKey];
648
+ if (contentTypeKey)
649
+ result.contentType = contentTypeKey;
650
+ if (mediaType?.schema) {
651
+ const rawSchema = mediaType.schema;
652
+ const schema = primaryType(rawSchema) === "array" && rawSchema.items
653
+ ? rawSchema.items
654
+ : rawSchema;
655
+ result.schema = extractSchemaProperties(schema);
656
+ result.example = copyValue(generateExampleFromSchema(rawSchema), EXAMPLE_MAX_CHARS);
657
+ }
658
+ }
659
+ return result;
660
+ })
661
+ .sort((a, b) => a.status.localeCompare(b.status));
662
+ }
663
+ function generateExampleFromSchema(schema, walk = newWalk()) {
664
+ if (!schema)
665
+ return undefined;
666
+ if (walk.nodes-- <= 0)
667
+ return null;
668
+ return descend(walk, schema, null, () => exampleOf(schema, walk));
669
+ }
670
+ function exampleOf(schema, walk) {
671
+ if (schema.example !== undefined)
672
+ return schema.example;
673
+ switch (primaryType(schema)) {
674
+ case "object": {
675
+ if (!schema.properties)
676
+ return {};
677
+ const obj = {};
678
+ for (const [name, prop] of Object.entries(schema.properties)) {
679
+ obj[name] = generateExampleFromSchema(prop, walk);
680
+ }
681
+ return obj;
682
+ }
683
+ case "array":
684
+ return schema.items ? [generateExampleFromSchema(schema.items, walk)] : [];
685
+ case "string": {
686
+ if (schema.enum)
687
+ return schema.enum[0];
688
+ if (schema.format === "date-time")
689
+ return "2024-01-01T00:00:00Z";
690
+ if (schema.format === "email")
691
+ return "user@example.com";
692
+ if (schema.format === "uri" || schema.format === "url") {
693
+ return "https://example.com";
694
+ }
695
+ if (schema.format === "uuid") {
696
+ return "550e8400-e29b-41d4-a716-446655440000";
697
+ }
698
+ if (schema.default !== undefined)
699
+ return schema.default;
700
+ return "string";
701
+ }
702
+ case "integer":
703
+ return schema.example ?? schema.default ?? 0;
704
+ case "number":
705
+ return schema.example ?? schema.default ?? 0.0;
706
+ case "boolean":
707
+ return schema.example ?? schema.default ?? true;
708
+ default:
709
+ return null;
710
+ }
711
+ }
712
+ function buildTagPage(tagName, tagSlug, description, ops) {
713
+ const tree = [
714
+ {
715
+ type: "heading",
716
+ props: { level: 1, id: tagSlug },
717
+ inline: [{ type: "text", text: tagName }],
718
+ },
719
+ ];
720
+ const used = new Set([tagSlug]);
721
+ const described = description ? descriptionHtml(description, 2, used) : null;
722
+ if (described)
723
+ tree.push({ type: "prose", html: described.html });
724
+ const items = ops.map((op) => ({
725
+ type: "list-item",
726
+ children: [
727
+ {
728
+ type: "prose",
729
+ html: `<a href="${escapeAttr(op.slug)}"><code>${op.method.toUpperCase()}</code> ${escapeHtml(op.path)}</a>${op.deprecated ? ' <span class="text-muted-foreground">(deprecated)</span>' : ""}`,
730
+ },
731
+ ],
732
+ }));
733
+ tree.push({ type: "unordered-list", children: items });
734
+ return {
735
+ slug: tagSlug,
736
+ title: tagName,
737
+ tree,
738
+ headings: [{ depth: 1, slug: tagSlug, text: tagName }, ...(described?.headings ?? [])],
739
+ };
740
+ }
741
+ function buildInfoPage(title, description, version) {
742
+ const tree = [
743
+ {
744
+ type: "heading",
745
+ props: { level: 1, id: "api-reference" },
746
+ inline: [{ type: "text", text: title }],
747
+ },
748
+ ];
749
+ if (version) {
750
+ tree.push({
751
+ type: "prose",
752
+ html: `<p class="text-sm text-muted-foreground">Version ${escapeHtml(version)}</p>`,
753
+ });
754
+ }
755
+ const described = description ? descriptionHtml(description, 2, new Set(["api-reference"])) : null;
756
+ if (described)
757
+ tree.push({ type: "prose", html: described.html });
758
+ return {
759
+ slug: "index",
760
+ title,
761
+ tree,
762
+ headings: [{ depth: 1, slug: "api-reference", text: title }, ...(described?.headings ?? [])],
763
+ };
764
+ }
765
+ function buildNav(spec, pages, tagToOps, untagged, hrefPrefix) {
766
+ const nav = [];
767
+ const root = {
768
+ label: txt(spec.info?.title) || "API Reference",
769
+ href: hrefHref(hrefPrefix, "index"),
770
+ };
771
+ nav.push(root);
772
+ // Use spec.tags[] order when present so authors control nav order.
773
+ const declaredTagOrder = Array.isArray(spec.tags)
774
+ ? spec.tags.map((t) => txt(t?.name)).filter(Boolean)
775
+ : [];
776
+ const seenTags = new Set();
777
+ const tagOrder = [];
778
+ for (const t of declaredTagOrder) {
779
+ if (tagToOps.has(t)) {
780
+ tagOrder.push(t);
781
+ seenTags.add(t);
782
+ }
783
+ }
784
+ for (const t of tagToOps.keys()) {
785
+ if (!seenTags.has(t))
786
+ tagOrder.push(t);
787
+ }
788
+ for (const tagName of tagOrder) {
789
+ const ops = tagToOps.get(tagName) || [];
790
+ const tagSlug = slugifyTag(tagName);
791
+ nav.push({
792
+ label: tagName,
793
+ href: hrefHref(hrefPrefix, tagSlug),
794
+ children: ops
795
+ .slice()
796
+ .sort(byMethodThenPath)
797
+ .map((op) => ({
798
+ label: op.title,
799
+ href: hrefHref(hrefPrefix, op.slug),
800
+ })),
801
+ });
802
+ }
803
+ if (untagged.length > 0) {
804
+ nav.push({
805
+ label: "Other",
806
+ children: untagged
807
+ .slice()
808
+ .sort(byMethodThenPath)
809
+ .map((op) => ({
810
+ label: op.title,
811
+ href: hrefHref(hrefPrefix, op.slug),
812
+ })),
813
+ });
814
+ }
815
+ return nav;
816
+ }
817
+ function byMethodThenPath(a, b) {
818
+ const m = a.method.localeCompare(b.method);
819
+ if (m !== 0)
820
+ return m;
821
+ return a.path.localeCompare(b.path);
822
+ }
823
+ function hrefHref(prefix, slug) {
824
+ const p = prefix ? `${prefix}/` : "/";
825
+ return slug === "index" ? p : `${p}${slug}`;
826
+ }
827
+ function escapeHtml(s) {
828
+ return s
829
+ .replace(/&/g, "&amp;")
830
+ .replace(/</g, "&lt;")
831
+ .replace(/>/g, "&gt;");
832
+ }
833
+ function escapeAttr(s) {
834
+ return s.replace(/&/g, "&amp;").replace(/"/g, "&quot;");
835
+ }
836
+ /**
837
+ * A spec description (CommonMark, per OpenAPI) → HTML, raw HTML off: a `<`
838
+ * in the spec is escaped, and markdown-it refuses `javascript:` links.
839
+ * Plain-text paragraphs showed a spec's `## Authentication` literally.
840
+ */
841
+ const md = new MarkdownIt({ html: false, linkify: false });
842
+ //# sourceMappingURL=core.js.map