@kubb/ast 5.22.0 → 5.23.1

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 (155) hide show
  1. package/dist/base-IpYuh3ZP.d.cts +173 -0
  2. package/dist/base-IpYuh3ZP.d.ts +173 -0
  3. package/dist/constants-Ckeonm-D.js +141 -0
  4. package/dist/constants-Ckeonm-D.js.map +1 -0
  5. package/dist/constants-CquR083U.cjs +152 -0
  6. package/dist/constants-CquR083U.cjs.map +1 -0
  7. package/dist/factory.cjs +23 -0
  8. package/dist/factory.d.cts +4 -0
  9. package/dist/factory.d.ts +4 -0
  10. package/dist/factory.js +4 -0
  11. package/dist/file-BVqSiSvV.d.cts +624 -0
  12. package/dist/file-Cg0T6cgz.cjs +319 -0
  13. package/dist/file-Cg0T6cgz.cjs.map +1 -0
  14. package/dist/file-CnuL8oUj.js +283 -0
  15. package/dist/file-CnuL8oUj.js.map +1 -0
  16. package/dist/file-CvlMAp_d.js +131 -0
  17. package/dist/file-CvlMAp_d.js.map +1 -0
  18. package/dist/file-Dd50jPkH.cjs +142 -0
  19. package/dist/file-Dd50jPkH.cjs.map +1 -0
  20. package/dist/file-xJnBQPGq.d.ts +624 -0
  21. package/dist/file.cjs +3 -0
  22. package/dist/file.d.cts +2 -0
  23. package/dist/file.d.ts +2 -0
  24. package/dist/file.js +1 -0
  25. package/dist/graph-BcwFCvei.js +144 -0
  26. package/dist/graph-BcwFCvei.js.map +1 -0
  27. package/dist/graph-DcIY6tQb.cjs +173 -0
  28. package/dist/graph-DcIY6tQb.cjs.map +1 -0
  29. package/dist/graph.cjs +6 -0
  30. package/dist/graph.d.cts +2 -0
  31. package/dist/graph.d.ts +2 -0
  32. package/dist/graph.js +1 -0
  33. package/dist/guards-B8qDgSaT.d.cts +23 -0
  34. package/dist/guards-COVJE6TU.cjs +41 -0
  35. package/dist/guards-COVJE6TU.cjs.map +1 -0
  36. package/dist/guards-D-h9R_sV.d.ts +23 -0
  37. package/dist/guards-DlJkKsT1.js +30 -0
  38. package/dist/guards-DlJkKsT1.js.map +1 -0
  39. package/dist/http-Bm5lhVK4.cjs +12 -0
  40. package/dist/http-Bm5lhVK4.cjs.map +1 -0
  41. package/dist/http-DwboM6pK.js +7 -0
  42. package/dist/http-DwboM6pK.js.map +1 -0
  43. package/dist/http.cjs +4 -0
  44. package/dist/http.d.cts +3 -0
  45. package/dist/http.d.ts +3 -0
  46. package/dist/http.js +2 -0
  47. package/dist/index-BWd95onW.d.cts +5 -0
  48. package/dist/index-Bb1kqq8H.d.cts +20 -0
  49. package/dist/index-BngGJux5.d.cts +12 -0
  50. package/dist/index-BwnMIoLl.d.ts +24 -0
  51. package/dist/index-C-vhkzwR.d.cts +79 -0
  52. package/dist/index-CAGuKv6t.d.ts +74 -0
  53. package/dist/index-CFH4ZC7q.d.ts +44 -0
  54. package/dist/index-CIqwy4EE.d.cts +74 -0
  55. package/dist/index-Cc2K3OzU.d.cts +11 -0
  56. package/dist/index-Cc2K3OzU.d.ts +11 -0
  57. package/dist/index-Csf8xsCc.d.cts +46 -0
  58. package/dist/index-D3M2spDR.d.ts +12 -0
  59. package/dist/index-DNiIem0x.d.ts +79 -0
  60. package/dist/index-DSVef1pp.d.cts +24 -0
  61. package/dist/index-DU_jYpBt.d.cts +44 -0
  62. package/dist/index-DYDha-3I.d.cts +67 -0
  63. package/dist/index-DaHsMJ_S.d.ts +5 -0
  64. package/dist/index-Dp50LM3a.d.ts +67 -0
  65. package/dist/index-cpjUxIik.d.ts +46 -0
  66. package/dist/index-eGkM4FE9.d.ts +20 -0
  67. package/dist/index.cjs +87 -2131
  68. package/dist/index.cjs.map +1 -1
  69. package/dist/index.d.cts +25 -2745
  70. package/dist/index.d.ts +25 -2745
  71. package/dist/index.js +40 -2052
  72. package/dist/index.js.map +1 -1
  73. package/dist/json-DH7_lcWm.js +74 -0
  74. package/dist/json-DH7_lcWm.js.map +1 -0
  75. package/dist/json-DURdtz9A.cjs +91 -0
  76. package/dist/json-DURdtz9A.cjs.map +1 -0
  77. package/dist/json.cjs +4 -0
  78. package/dist/json.d.cts +2 -0
  79. package/dist/json.d.ts +2 -0
  80. package/dist/json.js +1 -0
  81. package/dist/macro-D0KfNtff.js +104 -0
  82. package/dist/macro-D0KfNtff.js.map +1 -0
  83. package/dist/macro-DrTBT7fh.cjs +127 -0
  84. package/dist/macro-DrTBT7fh.cjs.map +1 -0
  85. package/dist/macro.cjs +4 -0
  86. package/dist/macro.d.cts +2 -0
  87. package/dist/macro.d.ts +2 -0
  88. package/dist/macro.js +1 -0
  89. package/dist/mediaType-CRjggmoG.js +19 -0
  90. package/dist/mediaType-CRjggmoG.js.map +1 -0
  91. package/dist/mediaType-D8uIO8sG.cjs +35 -0
  92. package/dist/mediaType-D8uIO8sG.cjs.map +1 -0
  93. package/dist/mediaType.cjs +4 -0
  94. package/dist/mediaType.d.cts +2 -0
  95. package/dist/mediaType.d.ts +2 -0
  96. package/dist/mediaType.js +1 -0
  97. package/dist/node-DjcETnc8.cjs +19 -0
  98. package/dist/node-DjcETnc8.cjs.map +1 -0
  99. package/dist/node-Djh-mZB2.js +14 -0
  100. package/dist/node-Djh-mZB2.js.map +1 -0
  101. package/dist/node.cjs +9 -0
  102. package/dist/node.d.cts +4 -0
  103. package/dist/node.d.ts +4 -0
  104. package/dist/node.js +5 -0
  105. package/dist/nodeText-DRb_rVd1.cjs +58 -0
  106. package/dist/nodeText-DRb_rVd1.cjs.map +1 -0
  107. package/dist/nodeText-DVVDZQjF.js +47 -0
  108. package/dist/nodeText-DVVDZQjF.js.map +1 -0
  109. package/dist/nodes-BB60Bq2H.cjs +320 -0
  110. package/dist/nodes-BB60Bq2H.cjs.map +1 -0
  111. package/dist/nodes-CWMa9xhW.js +231 -0
  112. package/dist/nodes-CWMa9xhW.js.map +1 -0
  113. package/dist/operation-BgRyVS7z.d.ts +1272 -0
  114. package/dist/operation-X7chCdL2.d.cts +1272 -0
  115. package/dist/optionality-D-zqzVMH.cjs +22 -0
  116. package/dist/optionality-D-zqzVMH.cjs.map +1 -0
  117. package/dist/optionality-DISn8ytP.js +17 -0
  118. package/dist/optionality-DISn8ytP.js.map +1 -0
  119. package/dist/promise-BOdlgT0N.cjs +50 -0
  120. package/dist/promise-BOdlgT0N.cjs.map +1 -0
  121. package/dist/promise-RpnEev9D.js +45 -0
  122. package/dist/promise-RpnEev9D.js.map +1 -0
  123. package/dist/ref-Bu7PoHar.js +22 -0
  124. package/dist/ref-Bu7PoHar.js.map +1 -0
  125. package/dist/ref-P0ZLT1Bg.cjs +39 -0
  126. package/dist/ref-P0ZLT1Bg.cjs.map +1 -0
  127. package/dist/ref.cjs +7 -0
  128. package/dist/ref.d.cts +2 -0
  129. package/dist/ref.d.ts +2 -0
  130. package/dist/ref.js +3 -0
  131. package/dist/refs-CYHpRlQo.cjs +131 -0
  132. package/dist/refs-CYHpRlQo.cjs.map +1 -0
  133. package/dist/refs-YCV3CznS.js +102 -0
  134. package/dist/refs-YCV3CznS.js.map +1 -0
  135. package/dist/rolldown-runtime-BV8xUvPy.cjs +52 -0
  136. package/dist/rolldown-runtime-BYyVTPww.js +16 -0
  137. package/dist/schema-2ZAQk7qE.js +44 -0
  138. package/dist/schema-2ZAQk7qE.js.map +1 -0
  139. package/dist/schema-BIErWqgc.cjs +214 -0
  140. package/dist/schema-BIErWqgc.cjs.map +1 -0
  141. package/dist/schema-DloctnMm.js +179 -0
  142. package/dist/schema-DloctnMm.js.map +1 -0
  143. package/dist/schema-hxMlgCrV.cjs +49 -0
  144. package/dist/schema-hxMlgCrV.cjs.map +1 -0
  145. package/dist/schema.cjs +16 -0
  146. package/dist/schema.d.cts +5 -0
  147. package/dist/schema.d.ts +5 -0
  148. package/dist/schema.js +6 -0
  149. package/dist/visitor-BZozlXBF.d.ts +179 -0
  150. package/dist/visitor-Bw_opzjF.d.cts +179 -0
  151. package/dist/visitor-DTrzvA3R.cjs +382 -0
  152. package/dist/visitor-DTrzvA3R.cjs.map +1 -0
  153. package/dist/visitor-NoQSUQTu.js +347 -0
  154. package/dist/visitor-NoQSUQTu.js.map +1 -0
  155. package/package.json +101 -1
package/dist/index.cjs CHANGED
@@ -1,1186 +1,21 @@
1
1
  Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
- // \0rolldown/runtime.js
3
- var __create = Object.create;
4
- var __defProp = Object.defineProperty;
5
- var __name = (target, value) => __defProp(target, "name", {
6
- value,
7
- configurable: true
8
- });
9
- var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
10
- var __getOwnPropNames = Object.getOwnPropertyNames;
11
- var __getProtoOf = Object.getPrototypeOf;
12
- var __hasOwnProp = Object.prototype.hasOwnProperty;
13
- var __exportAll = (all, flags) => {
14
- let target = Object.setPrototypeOf({}, null);
15
- for (var name in all) __defProp(target, name, {
16
- get: all[name],
17
- enumerable: true
18
- });
19
- if (!(flags & 1)) __defProp(target, Symbol.toStringTag, { value: "Module" });
20
- return flags & 2 ? target : Object.preventExtensions(target);
21
- };
22
- var __copyProps = (to, from, except, desc) => {
23
- if (from && typeof from === "object" || typeof from === "function") for (var keys = __getOwnPropNames(from), i = 0, n = keys.length, key; i < n; i++) {
24
- key = keys[i];
25
- if (!__hasOwnProp.call(to, key) && key !== except) __defProp(to, key, {
26
- get: ((k) => from[k]).bind(null, key),
27
- enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable
28
- });
29
- }
30
- return to;
31
- };
32
- var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(isNodeMode || !mod || !mod.__esModule || !__hasOwnProp.call(mod, "default") ? __defProp(target, "default", {
33
- value: mod,
34
- enumerable: true
35
- }) : target, mod));
36
- let node_path = require("node:path");
37
- node_path = __toESM(node_path, 1);
38
- let node_crypto = require("node:crypto");
39
- // ../../internals/utils/src/promise.ts
40
- /**
41
- * Returns the value cached under `key` in `store`, computing and storing it on the first call.
42
- * Pass a `WeakMap` for object keys, so an entry goes away with its key, or a `Map` for primitive
43
- * keys. A cached `null` or `undefined` counts as a hit, so `compute` runs once per key.
44
- *
45
- * @example
46
- * `const refs = memo(refCache, node, () => collectRefs(node))`
47
- */
48
- function memo(store, key, compute) {
49
- const cached = store.get(key);
50
- if (cached !== void 0 || store.has(key)) return cached;
51
- const value = compute();
52
- store.set(key, value);
53
- return value;
54
- }
55
- function createStore({ weak, max } = {}) {
56
- if (weak) return /* @__PURE__ */ new WeakMap();
57
- const entry = /* @__PURE__ */ new Map();
58
- if (max === void 0) return entry;
59
- const set = (key, value) => {
60
- if (entry.size >= max) entry.clear();
61
- entry.set(key, value);
62
- };
63
- if (max !== 1) return {
64
- has: (key) => entry.has(key),
65
- get: (key) => entry.get(key),
66
- set
67
- };
68
- const touch = (key) => {
69
- if (!entry.has(key)) return false;
70
- set(key, entry.get(key));
71
- return true;
72
- };
73
- return {
74
- has: touch,
75
- get: (key) => touch(key) ? entry.get(key) : void 0,
76
- set
77
- };
78
- }
79
- memo.create = createStore;
80
- // src/constants.ts
81
- /**
82
- * Node kind discriminators used by every AST node (for example `node.kind === nodeKinds.text`).
83
- */
84
- const nodeKinds$1 = {
85
- input: "Input",
86
- operation: "Operation",
87
- schema: "Schema",
88
- property: "Property",
89
- parameter: "Parameter",
90
- response: "Response",
91
- requestBody: "RequestBody",
92
- content: "Content",
93
- type: "Type",
94
- file: "File",
95
- import: "Import",
96
- export: "Export",
97
- source: "Source",
98
- const: "Const",
99
- function: "Function",
100
- arrowFunction: "ArrowFunction",
101
- text: "Text",
102
- break: "Break",
103
- jsx: "Jsx"
104
- };
105
- /**
106
- * Schema type discriminators used by all AST schema nodes.
107
- *
108
- * Each value is a stable discriminator across the AST (for example `schema.type === schemaTypes.object`).
109
- */
110
- const schemaTypes$1 = {
111
- /**
112
- * Text value.
113
- */
114
- string: "string",
115
- /**
116
- * Floating-point number (`float`, `double`).
117
- */
118
- number: "number",
119
- /**
120
- * Whole number (`int32`). Use `bigint` for `int64`.
121
- */
122
- integer: "integer",
123
- /**
124
- * 64-bit integer (`int64`). Only used when `integerType` is set to `'bigint'`.
125
- */
126
- bigint: "bigint",
127
- /**
128
- * Boolean value.
129
- */
130
- boolean: "boolean",
131
- /**
132
- * Explicit null value.
133
- */
134
- null: "null",
135
- /**
136
- * Any value (no type restriction).
137
- */
138
- any: "any",
139
- /**
140
- * Unknown value (must be narrowed before usage).
141
- */
142
- unknown: "unknown",
143
- /**
144
- * No return value (`void`).
145
- */
146
- void: "void",
147
- /**
148
- * Object with named properties.
149
- */
150
- object: "object",
151
- /**
152
- * Sequential list of items.
153
- */
154
- array: "array",
155
- /**
156
- * Fixed-length list with position-specific items.
157
- */
158
- tuple: "tuple",
159
- /**
160
- * "One of" multiple schema members.
161
- */
162
- union: "union",
163
- /**
164
- * "All of" multiple schema members.
165
- */
166
- intersection: "intersection",
167
- /** "Not" a single schema member. */
168
- not: "not",
169
- /**
170
- * Enum schema.
171
- */
172
- enum: "enum",
173
- /**
174
- * Reference to another schema.
175
- */
176
- ref: "ref",
177
- /**
178
- * Calendar date (for example `2026-03-24`).
179
- */
180
- date: "date",
181
- /**
182
- * Date-time value (for example `2026-03-24T09:00:00Z`).
183
- */
184
- datetime: "datetime",
185
- /**
186
- * Time-only value (for example `09:00:00`).
187
- */
188
- time: "time",
189
- /**
190
- * UUID value.
191
- */
192
- uuid: "uuid",
193
- /**
194
- * Email address value.
195
- */
196
- email: "email",
197
- /**
198
- * URL value.
199
- */
200
- url: "url",
201
- /**
202
- * IPv4 address value.
203
- */
204
- ipv4: "ipv4",
205
- /**
206
- * IPv6 address value.
207
- */
208
- ipv6: "ipv6",
209
- /**
210
- * Binary/blob value.
211
- */
212
- blob: "blob",
213
- /**
214
- * Impossible value (`never`).
215
- */
216
- never: "never"
217
- };
218
- // src/mediaType/index.ts
219
- var mediaType_exports = /* @__PURE__ */ __exportAll({
220
- getBase: () => getBase,
221
- isJson: () => isJson,
222
- isStream: () => isStream
223
- });
224
- const jsonMediaTypes = /* @__PURE__ */ new Set(["application/json", "text/json"]);
225
- const streamMediaTypes = /* @__PURE__ */ new Set([
226
- "application/jsonl",
227
- "application/x-ndjson",
228
- "application/json-seq",
229
- "text/event-stream"
230
- ]);
231
- /** The media type without its parameters, in lower case: `Text/Plain; charset=utf-8` gives `text/plain`. */
232
- function getBase(mediaType) {
233
- return (typeof mediaType === "string" ? mediaType : mediaType.contentType).split(";")[0].trim().toLowerCase();
234
- }
235
- /** Whether the media type is `application/json`, `text/json`, or has a `+json` suffix. */
236
- function isJson(mediaType) {
237
- const baseType = getBase(mediaType);
238
- return jsonMediaTypes.has(baseType) || baseType.endsWith("+json");
239
- }
240
- /** Whether the media type is a stream of items: SSE, JSON Lines, or a `+json-seq` sequence. */
241
- function isStream(mediaType) {
242
- const baseType = getBase(mediaType);
243
- return streamMediaTypes.has(baseType) || baseType.startsWith("application/") && baseType.endsWith("+json-seq");
244
- }
245
- // src/schema/embeddedJson.ts
246
- /** The schema of the JSON document a string holds (`contentMediaType` with `contentSchema`), else `undefined`. */
247
- function getEmbeddedJson({ content }) {
248
- if (!content?.schema || content.encoding || !content.mediaType) return void 0;
249
- return isJson(content.mediaType) ? content.schema : void 0;
250
- }
251
- // src/visitor.ts
252
- /**
253
- * Child node fields per node kind, in traversal order (Babel's `VISITOR_KEYS`).
254
- */
255
- const VISITOR_KEYS = {
256
- Input: ["schemas", "operations"],
257
- Operation: [
258
- "parameters",
259
- "requestBody",
260
- "responses"
261
- ],
262
- RequestBody: ["content"],
263
- Content: ["schema", "stream"],
264
- Response: ["content", "headers"],
265
- Schema: [
266
- "properties",
267
- "items",
268
- "members",
269
- "additionalProperties",
270
- "patternProperties",
271
- "propertyNames",
272
- "rest"
273
- ],
274
- Property: ["schema"],
275
- Parameter: ["schema"]
276
- };
277
- /**
278
- * Schema fields that hold checks rather than shape: the `conditionals` entries, `contains` and a string's `content`.
279
- * `transform` and `collect` skip them, and `visitChildNodes` walks them with `checks: true`.
280
- */
281
- const schemaCheckKeys = [
282
- "conditionals",
283
- "contains",
284
- "content"
285
- ];
286
- /** Visitor callback names in traversal order, the keys of {@link Visitor}. */
287
- const visitorKeys = [
288
- "input",
289
- "operation",
290
- "schema",
291
- "property",
292
- "parameter",
293
- "response"
294
- ];
295
- /**
296
- * Maps a node kind to the matching visitor callback name.
297
- */
298
- const VISITOR_KEY_BY_KIND = {
299
- Input: "input",
300
- Operation: "operation",
301
- Schema: "schema",
302
- Property: "property",
303
- Parameter: "parameter",
304
- Response: "response"
305
- };
306
- /**
307
- * Returns `true` when `value` is an AST node (an object carrying a `kind`).
308
- */
309
- function isNode(value) {
310
- return typeof value === "object" && value !== null && typeof value.kind === "string";
311
- }
312
- /**
313
- * Returns `true` for a plain object that maps names to nodes, such as `patternProperties`.
314
- */
315
- function isNodeRecord(value) {
316
- return typeof value === "object" && value !== null && !Array.isArray(value);
317
- }
318
- function isNeverPrinted({ node, key }) {
319
- if (node.kind !== nodeKinds$1.schema) return false;
320
- if (key === "contains" && (node.type === "array" || node.type === "tuple")) return node.contains?.min === 0 && node.contains.max === void 0;
321
- if (key === "content" && node.type === "string") return !getEmbeddedJson(node);
322
- return false;
323
- }
324
- /**
325
- * Child keys of a schema walked with `checks: true`: the shape keys, then {@link schemaCheckKeys}.
326
- */
327
- const SCHEMA_CHECK_VISITOR_KEYS = [...VISITOR_KEYS.Schema, ...schemaCheckKeys];
328
- function visitOnce(child, seen, visit) {
329
- if (seen.first === void 0) {
330
- seen.first = child;
331
- return visit(child);
332
- }
333
- if (seen.first === child || seen.rest?.has(child)) return false;
334
- (seen.rest ??= /* @__PURE__ */ new Set()).add(child);
335
- return visit(child);
336
- }
337
- function visitRecord(value, seen, visit) {
338
- for (const name in value) {
339
- if (!Object.hasOwn(value, name)) continue;
340
- const item = value[name];
341
- if (isNode(item) && visitOnce(item, seen, visit)) return true;
342
- }
343
- return false;
344
- }
345
- /**
346
- * Calls `visit` for each direct child node and stops at the first call that returns `true`.
347
- * With `checks: true`, a schema's {@link schemaCheckKeys} fields are walked too, except checks that cannot fail.
348
- */
349
- function visitChildNodes(node, visit, { checks = false } = {}) {
350
- const withChecks = checks && node.kind === nodeKinds$1.schema;
351
- const keys = withChecks ? SCHEMA_CHECK_VISITOR_KEYS : VISITOR_KEYS[node.kind];
352
- if (!keys) return false;
353
- const record = node;
354
- let seen;
355
- for (const key of keys) {
356
- const value = record[key];
357
- if (value === void 0 || value === null) continue;
358
- if (withChecks && isNeverPrinted({
359
- node,
360
- key
361
- })) continue;
362
- seen ??= {
363
- first: void 0,
364
- rest: void 0
365
- };
366
- if (Array.isArray(value)) {
367
- for (const item of value) if (isNode(item) ? visitOnce(item, seen, visit) : isNodeRecord(item) && visitRecord(item, seen, visit)) return true;
368
- continue;
369
- }
370
- if (isNode(value)) {
371
- if (visitOnce(value, seen, visit)) return true;
372
- continue;
373
- }
374
- if (isNodeRecord(value) && visitRecord(value, seen, visit)) return true;
375
- }
376
- return false;
377
- }
378
- const notFound = {
379
- found: void 0,
380
- low: Number.POSITIVE_INFINITY
381
- };
382
- /**
383
- * Finds the first schema that matches `predicate` in depth-first order. Set `followRefs` to include resolved ref targets.
384
- *
385
- * @example
386
- * ```ts
387
- * const firstString = findSchema(operationNode, {
388
- * predicate: (schema) => schema.type === 'string',
389
- * })
390
- * ```
391
- */
392
- function findSchema$1(node, { predicate, followRefs = false, cache }) {
393
- const state = followRefs ? /* @__PURE__ */ new Map() : void 0;
394
- const pending = [];
395
- let order = 0;
396
- const walkChildren = (current, initial) => {
397
- let result = initial;
398
- visitChildNodes(current, (child) => {
399
- const next = walk(child);
400
- result = next.found || next.low < result.low ? next : result;
401
- return next.found !== void 0;
402
- });
403
- return result;
404
- };
405
- const walkSchema = (current) => {
406
- const target = state && current.type === "ref" && current.schema ? walk(current.schema) : notFound;
407
- if (target.found) return target;
408
- return walkChildren(current, target);
409
- };
410
- const walk = (current) => {
411
- if (current.kind !== nodeKinds$1.schema) return walkChildren(current, notFound);
412
- const cached = cache?.get(current);
413
- if (cached === null) return notFound;
414
- if (cached) return {
415
- found: cached,
416
- low: Number.POSITIVE_INFINITY
417
- };
418
- if (predicate(current)) {
419
- cache?.set(current, current);
420
- return {
421
- found: current,
422
- low: Number.POSITIVE_INFINITY
423
- };
424
- }
425
- const known = state?.get(current);
426
- if (known !== void 0) return {
427
- found: void 0,
428
- low: known
429
- };
430
- const index = order++;
431
- const start = pending.length;
432
- state?.set(current, index);
433
- const result = walkSchema(current);
434
- if (result.found) {
435
- cache?.set(current, result.found);
436
- return result;
437
- }
438
- if (!state) {
439
- cache?.set(current, null);
440
- return notFound;
441
- }
442
- if (result.low < index) {
443
- state.set(current, result.low);
444
- pending.push(current);
445
- return result;
446
- }
447
- for (const done of [...pending.splice(start), current]) {
448
- state.set(done, Number.POSITIVE_INFINITY);
449
- cache?.set(done, null);
450
- }
451
- return notFound;
452
- };
453
- return walk(node).found;
454
- }
455
- __name(findSchema$1, "findSchema");
456
- /**
457
- * Runs the visitor callback that matches `node.kind` with the traversal
458
- * context. The result is a replacement node, a collected value, or `undefined`
459
- * when no callback is registered for the kind.
460
- *
461
- * Shared by `transform` and `collect` so node-kind dispatch lives in one place.
462
- * `TResult` is the caller's expected return: the same node type for `transform`,
463
- * the collected value type for `collect`.
464
- */
465
- function applyVisitor(node, visitor, parent) {
466
- const key = VISITOR_KEY_BY_KIND[node.kind];
467
- if (!key) return void 0;
468
- const fn = visitor[key];
469
- return fn?.(node, { parent });
470
- }
471
- /**
472
- * Synchronous depth-first transform. Each visitor callback can return a
473
- * replacement node. Returning `undefined` keeps the original.
474
- *
475
- * The original tree is never mutated, a new tree is returned. Pass
476
- * `depth: 'shallow'` to skip recursion into children.
477
- *
478
- * @example Prefix every operationId
479
- * ```ts
480
- * const next = transform(root, {
481
- * operation(node) {
482
- * return { ...node, operationId: `prefixed_${node.operationId}` }
483
- * },
484
- * })
485
- * ```
486
- *
487
- * @example Replace only the root node
488
- * ```ts
489
- * const next = transform(root, {
490
- * depth: 'shallow',
491
- * input: (node) => ({ ...node, meta: { ...node.meta, title: 'Rewritten' } }),
492
- * })
493
- * ```
494
- */
495
- function transform$1(node, options) {
496
- const { depth, parent, ...visitor } = options;
497
- return transformNode(node, visitor, (depth ?? "deep") === "deep", parent);
498
- }
499
- __name(transform$1, "transform");
500
- /**
501
- * Visits a single node, then immutably rebuilds its children. Returns the original
502
- * reference when neither the visitor nor the child rebuild changed anything, so callers
503
- * can detect "nothing changed" by identity and ancestors avoid reallocating.
504
- */
505
- function transformNode(node, visitor, recurse, parent) {
506
- return transformChildren(applyVisitor(node, visitor, parent) ?? node, visitor, recurse);
507
- }
508
- /**
509
- * Immutably rebuilds a node's children, transforming each child node and leaving non-node values
510
- * (e.g. `additionalProperties: true`) intact.
511
- */
512
- function transformChildren(node, visitor, recurse) {
513
- const keys = node.kind === nodeKinds$1.schema && !recurse ? void 0 : VISITOR_KEYS[node.kind];
514
- if (!keys) return node;
515
- const record = node;
516
- let updates;
517
- let done;
518
- const transformOnce = (child) => {
519
- done ??= /* @__PURE__ */ new Map();
520
- const next = done.get(child) ?? transformNode(child, visitor, recurse, node);
521
- done.set(child, next);
522
- return next;
523
- };
524
- for (const key of keys) {
525
- const value = record[key];
526
- if (value === void 0 || value === null) continue;
527
- if (Array.isArray(value)) {
528
- let mapped;
529
- for (const [i, item] of value.entries()) {
530
- const next = isNode(item) ? transformOnce(item) : item;
531
- if (mapped) {
532
- mapped.push(next);
533
- continue;
534
- }
535
- if (next !== item) mapped = [...value.slice(0, i), next];
536
- }
537
- if (mapped) (updates ??= {})[key] = mapped;
538
- continue;
539
- }
540
- if (isNode(value)) {
541
- const next = transformOnce(value);
542
- if (next !== value) (updates ??= {})[key] = next;
543
- continue;
544
- }
545
- if (isNodeRecord(value)) {
546
- let mapped;
547
- for (const [name, item] of Object.entries(value)) {
548
- const next = isNode(item) ? transformOnce(item) : item;
549
- if (next !== item) (mapped ??= { ...value })[name] = next;
550
- }
551
- if (mapped) (updates ??= {})[key] = mapped;
552
- }
553
- }
554
- if (!updates) return node;
555
- return {
556
- ...node,
557
- ...updates
558
- };
559
- }
560
- /**
561
- * Depth-first collection pass. Gathers every non-null value the visitor
562
- * callbacks return into an array.
563
- *
564
- * @example Collect every operationId
565
- * ```ts
566
- * const ids = collect<string>(root, {
567
- * operation(node) {
568
- * return node.operationId
569
- * },
570
- * })
571
- * ```
572
- */
573
- function collect$1(node, options) {
574
- const { depth, parent, ...visitor } = options;
575
- const result = [];
576
- collectInto(node, visitor, (depth ?? "deep") === "deep", parent, result);
577
- return result;
578
- }
579
- __name(collect$1, "collect");
580
- function collectInto(node, visitor, recurse, parent, result) {
581
- const v = applyVisitor(node, visitor, parent);
582
- if (v != null) result.push(v);
583
- if (node.kind === nodeKinds$1.schema && !recurse) return;
584
- visitChildNodes(node, (child) => {
585
- collectInto(child, visitor, recurse, node, result);
586
- return false;
587
- });
588
- }
589
- // src/utils/refs.ts
590
- /**
591
- * Returns the last segment of a `$ref` pointer, for example `'Pet'` for `#/components/schemas/Pet`.
592
- * The segment is decoded like the pointer resolver does: percent-escapes first, then `~1` and `~0`
593
- * (RFC 6901), so `a~1b~0c` names the component `a/b~c`.
594
- */
595
- function refName$1(ref) {
596
- return memo(refNames, ref, () => {
597
- const segment = ref.split("/").at(-1) ?? ref;
598
- let decoded = segment;
599
- try {
600
- decoded = decodeURIComponent(segment);
601
- } catch {}
602
- return decoded.replaceAll("~1", "/").replaceAll("~0", "~");
603
- });
604
- }
605
- __name(refName$1, "refName");
606
- const refNames = memo.create({ max: 1e5 });
607
- /**
608
- * Resolves the emitted name of the schema a ref node points at. Prefers `targetName` (set when
609
- * the referenced schema was renamed, e.g. to break a collision), then the last segment of `ref`,
610
- * then `name`, then the nested `schema.name`.
611
- *
612
- * Returns `null` for non-ref nodes or when no name resolves.
613
- *
614
- * @example
615
- * `resolveRefName({ kind: 'Schema', type: 'ref', ref: '#/components/schemas/Pet' }) // 'Pet'`
616
- *
617
- * @example Collision-renamed target
618
- * `resolveRefName({ kind: 'Schema', type: 'ref', ref: '#/components/schemas/Order', targetName: 'OrderSchema' }) // 'OrderSchema'`
619
- */
620
- function resolveRefName$1(node) {
621
- if (!node || node.type !== "ref") return null;
622
- if (node.targetName) return node.targetName;
623
- if (node.ref) return refName$1(node.ref);
624
- return node.name ?? node.schema?.name ?? null;
625
- }
626
- __name(resolveRefName$1, "resolveRefName");
627
- /**
628
- * Follows a resolved ref chain to its target schema. Returns an unresolved or cyclic ref as is.
629
- *
630
- * @example
631
- * ```ts
632
- * const target = resolveRef(refSchema)
633
- * ```
634
- */
635
- function resolveRef$1(node) {
636
- if (node.type !== "ref" || !node.schema) return node;
637
- const seen = /* @__PURE__ */ new WeakSet();
638
- let current = node;
639
- while (current.type === "ref" && current.schema) {
640
- if (seen.has(current)) return current;
641
- seen.add(current);
642
- current = current.schema;
643
- }
644
- return current;
645
- }
646
- __name(resolveRef$1, "resolveRef");
647
- /** Fields of a ref node that describe the ref itself, so they never override the resolved schema. */
648
- const REF_OWN_KEYS = /* @__PURE__ */ new Set([
649
- "kind",
650
- "type",
651
- "name",
652
- "ref",
653
- "schema"
654
- ]);
655
- /**
656
- * Merges a ref node with its resolved schema, giving the fields set at the usage site precedence.
657
- *
658
- * Every field on the ref except `kind`, `type`, `name`, `ref`, and `schema` overrides the same field
659
- * of the resolved `schema` (for example `description`, `nullable`, `readOnly`, `deprecated`). Fields
660
- * left `undefined` on the ref do not shadow the resolved schema. A ref without a resolved `schema`
661
- * is returned as is.
662
- *
663
- * @example
664
- * ```ts
665
- * const ref = createSchema({ type: 'ref', ref: '#/components/schemas/Pet', description: 'A pet', schema: petSchema })
666
- * mergeRefWithSchema(ref) // petSchema's fields with description 'A pet'
667
- * ```
668
- */
669
- function mergeRefWithSchema$1(node) {
670
- if (!node.schema) return node;
671
- const merged = { ...node.schema };
672
- for (const key of Object.keys(node)) {
673
- const value = node[key];
674
- if (value !== void 0 && !REF_OWN_KEYS.has(key)) merged[key] = value;
675
- }
676
- return merged;
677
- }
678
- __name(mergeRefWithSchema$1, "mergeRefWithSchema");
679
- /**
680
- * Returns `true` when a schema is a bare ref without modifiers, metadata, or omit keys.
681
- *
682
- * Modifiers inherited from the resolved schema are included in the check because a ref emits the
683
- * referenced schema variable with those modifiers already applied.
684
- */
685
- function isBareRef$1(node, keysToOmit) {
686
- if (!node || node.type !== "ref") return false;
687
- const meta = mergeRefWithSchema$1(node);
688
- return !meta.nullable && !meta.optional && !meta.nullish && meta.default === void 0 && !meta.description && !meta.examples?.length && !keysToOmit?.length;
689
- }
690
- __name(isBareRef$1, "isBareRef");
691
- // src/utils/schemaGraph.ts
692
- const refEntries = memo.create({ weak: true });
693
- const checkRefEntries = memo.create({ weak: true });
694
- const schemaRefs = memo.create({ weak: true });
695
- const importedRefNames = memo.create({ weak: true });
696
- const importedCheckRefNames = memo.create({ weak: true });
697
- /**
698
- * Walks a node's subtree once and lists every ref it holds, in traversal order, as the resolved
699
- * name plus whether the ref carries a `$ref` pointer. Memoized per node and per `checks` mode, so
700
- * each helper below scans a schema once.
701
- */
702
- function collectRefEntries(node, { checks }) {
703
- return memo(checks ? checkRefEntries : refEntries, node, () => {
704
- const entries = [];
705
- const walk = (current) => {
706
- if (current.kind === nodeKinds$1.schema && current.type === "ref") {
707
- const name = resolveRefName$1(current);
708
- if (name) entries.push({
709
- name,
710
- hasPointer: Boolean(current.ref)
711
- });
712
- }
713
- visitChildNodes(current, walk, { checks });
714
- return false;
715
- };
716
- walk(node);
717
- return entries;
718
- });
719
- }
720
- /**
721
- * Collects the names of every schema a node's subtree references, resolved with `ast.ref.getName`.
722
- * Each ref contributes its name only, so the schema it points to is never traversed. Memoized by
723
- * node identity, which lets `findCircularSchemas` and `ast.graph.containsCircular` share one scan per schema.
724
- *
725
- * @example
726
- * ```ts
727
- * collectSchemaRefs(petSchema)
728
- * // Set { 'Category', 'Tag' }
729
- * ```
730
- */
731
- function collectSchemaRefs$1(node) {
732
- return memo(schemaRefs, node, () => new Set(collectRefEntries(node, { checks: true }).map((entry) => entry.name)));
733
- }
734
- __name(collectSchemaRefs$1, "collectSchemaRefs");
735
- /**
736
- * Collects the de-duplicated target names of every pointer-carrying ref in a node's subtree, in
737
- * first-occurrence order. Memoized by node identity, so `resolver.imports` reads the same result
738
- * across the ts, zod, and faker plugins instead of re-scanning the same schema per plugin.
739
- *
740
- * Only refs that carry a `$ref` pointer count, so a synthesized ref pointing at a sibling in the
741
- * same file (a union member created by name) is left out. That leaves exactly the set
742
- * `resolver.imports` emits. Refs inside `conditionals`, `contains` and `content` count only with
743
- * `checks: true`, for a plugin that prints those checks.
744
- *
745
- * @example
746
- * ```ts
747
- * collectImportedRefNames(petSchema)
748
- * // ['Category', 'Tag']
749
- * ```
750
- */
751
- function collectImportedRefNames$1(node, { checks = false } = {}) {
752
- return memo(checks ? importedCheckRefNames : importedRefNames, node, () => [...new Set(collectRefEntries(node, { checks }).flatMap((entry) => entry.hasPointer ? [entry.name] : []))]);
753
- }
754
- __name(collectImportedRefNames$1, "collectImportedRefNames");
755
- /**
756
- * Collects the names of all top-level schemas transitively used by a set of operations.
757
- *
758
- * An operation uses a schema when its parameters, request body, or responses reference it, directly
759
- * or through other named schemas. Once a name is added to the result it is not revisited, so
760
- * reference cycles terminate.
761
- *
762
- * Pair it with `include` filters so schemas reachable only from excluded operations stay ungenerated.
763
- *
764
- * @example Only generate schemas referenced by included operations
765
- * ```ts
766
- * const includedOps = operations.filter((op) => resolver.default.options(op, { options, include }) !== null)
767
- * const allowed = collectUsedSchemaNames(includedOps, schemas)
768
- *
769
- * for (const schema of schemas) {
770
- * if (schema.name && !allowed.has(schema.name)) continue
771
- * // generate schema
772
- * }
773
- * ```
774
- */
775
- function collectUsedSchemaNames$1(operations, schemas) {
776
- const schemaMap = /* @__PURE__ */ new Map();
777
- for (const schema of schemas) if (schema.name) schemaMap.set(schema.name, schema);
778
- const result = /* @__PURE__ */ new Set();
779
- function visitSchema(schema) {
780
- for (const name of collectSchemaRefs$1(schema)) if (!result.has(name)) {
781
- result.add(name);
782
- const namedSchema = schemaMap.get(name);
783
- if (namedSchema) visitSchema(namedSchema);
784
- }
785
- }
786
- for (const op of operations) for (const schema of collect$1(op, {
787
- depth: "shallow",
788
- schema: (node) => node
789
- })) visitSchema(schema);
790
- return result;
791
- }
792
- __name(collectUsedSchemaNames$1, "collectUsedSchemaNames");
793
- /**
794
- * Finds every schema that takes part in a circular dependency chain, including direct self-loops.
795
- *
796
- * Wrap the returned schema positions in a deferred construct (a lazy getter or `z.lazy(() => …)`) so
797
- * the generated code does not recurse forever. Refs are followed by name only, so the walk stays
798
- * linear in the size of the schema graph.
799
- *
800
- * @note Call this once on the full graph, then check individual schemas with `ast.graph.containsCircular()`.
801
- */
802
- function findCircularSchemas$1(schemas) {
803
- const graph = /* @__PURE__ */ new Map();
804
- for (const schema of schemas) if (schema.name) graph.set(schema.name, collectSchemaRefs$1(schema));
805
- const circular = /* @__PURE__ */ new Set();
806
- for (const start of graph.keys()) {
807
- const visited = /* @__PURE__ */ new Set();
808
- const stack = [...graph.get(start) ?? []];
809
- while (stack.length > 0) {
810
- const node = stack.pop();
811
- if (node === start) {
812
- circular.add(start);
813
- break;
814
- }
815
- if (visited.has(node)) continue;
816
- visited.add(node);
817
- const next = graph.get(node);
818
- if (next) for (const r of next) stack.push(r);
819
- }
820
- }
821
- return circular;
822
- }
823
- __name(findCircularSchemas$1, "findCircularSchemas");
824
- // src/graph/index.ts
825
- var graph_exports = /* @__PURE__ */ __exportAll({
826
- containsCircular: () => containsCircular,
827
- getCircularNames: () => findCircularSchemas$1,
828
- getImportedNames: () => collectImportedRefNames$1,
829
- getRefNames: () => collectSchemaRefs$1,
830
- getUsedNames: () => collectUsedSchemaNames$1
831
- });
832
- /** Whether a schema, or anything inside it, refers to one of `circularSchemas`, other than `excludeName`. */
833
- function containsCircular(node, { circularSchemas, excludeName }) {
834
- if (!node || circularSchemas.size === 0) return false;
835
- for (const name of collectSchemaRefs$1(node)) if (name !== excludeName && circularSchemas.has(name)) return true;
836
- return false;
837
- }
838
- // src/guards.ts
839
- /**
840
- * Narrows a `SchemaNode` to the variant that matches `type`.
841
- *
842
- * @example
843
- * ```ts
844
- * const schema = createSchema({ type: 'string' })
845
- * const stringNode = narrowSchema(schema, 'string') // StringSchemaNode | null
846
- * ```
847
- */
848
- function narrowSchema$1(node, type) {
849
- return node?.type === type ? node : null;
850
- }
851
- __name(narrowSchema$1, "narrowSchema");
852
- /**
853
- * Narrows an `OperationNode` to an `HttpOperationNode` so `method` and `path` are present.
854
- *
855
- * @example
856
- * ```ts
857
- * if (ast.http.isOperation(node)) {
858
- * console.log(node.method, node.path)
859
- * }
860
- * ```
861
- */
862
- function isHttpOperationNode$1(node) {
863
- return node.protocol === "http" || node.method !== void 0 && node.path !== void 0;
864
- }
865
- __name(isHttpOperationNode$1, "isHttpOperationNode");
866
- // src/http/requestBody.ts
867
- var requestBody_exports = /* @__PURE__ */ __exportAll({ getSchema: () => getSchema });
868
- /** The schema of the first request body entry, else `undefined` when the operation takes no body. */
869
- function getSchema(node) {
870
- return node.requestBody?.content?.[0]?.schema;
871
- }
872
- // src/http/status.ts
873
- var status_exports = /* @__PURE__ */ __exportAll({
874
- getClass: () => statusClass,
875
- isError: () => isError,
876
- isSuccess: () => isSuccess,
877
- toCode: () => toCode
878
- });
879
- const classByRange = /* @__PURE__ */ new Map([
880
- ["1xx", 1],
881
- ["2xx", 2],
882
- ["3xx", 3],
883
- ["4xx", 4],
884
- ["5xx", 5]
885
- ]);
886
- /** The class digit of a status code or range: `2` for `201` and `2xx`, `null` for `default`. */
887
- function statusClass(input) {
888
- const statusCode = typeof input === "object" ? input.statusCode : input;
889
- const rangeClass = classByRange.get(String(statusCode));
890
- if (rangeClass) return rangeClass;
891
- const code = Number(statusCode);
892
- return Number.isNaN(code) ? null : Math.floor(code / 100);
893
- }
894
- function isSuccess(statusCode) {
895
- return statusClass(statusCode) === 2;
896
- }
897
- function isError(statusCode) {
898
- const code = statusClass(statusCode);
899
- return code !== null && code >= 4;
900
- }
901
- /** One concrete code for a status or range: `200` for `2xx` and `default`, the code itself otherwise. */
902
- function toCode(input) {
903
- const statusCode = typeof input === "object" ? input.statusCode : input;
904
- const code = Number(statusCode);
905
- return Number.isNaN(code) ? (statusClass(statusCode) ?? 2) * 100 : code;
906
- }
907
- // src/http/responses.ts
908
- var responses_exports = /* @__PURE__ */ __exportAll({
909
- filterError: () => filterError,
910
- filterSuccess: () => filterSuccess,
911
- findPrimary: () => findPrimary,
912
- getImportedNames: () => getImportedNames
913
- });
914
- /** The `4xx` and `5xx` responses, ranges included. */
915
- function filterError(node) {
916
- return node.responses.filter((response) => isError(response.statusCode));
917
- }
918
- /** The ref names the response bodies import, in order, with repeats. */
919
- function getImportedNames(responses) {
920
- return responses.flatMap((response) => (response.content ?? []).flatMap((entry) => entry.schema ? collectImportedRefNames$1(entry.schema) : []));
921
- }
922
- function filterSuccess(node) {
923
- return node.responses.filter((response) => isSuccess(response.statusCode));
924
- }
925
- /** The success response a client returns: one with a body first, then an exact code over a `2xx` range. */
926
- function findPrimary(node) {
927
- const responses = filterSuccess(node);
928
- const withBody = responses.filter((response) => response.content?.some((entry) => entry.contentType));
929
- const candidates = withBody.length ? withBody : responses;
930
- return candidates.find((response) => !Number.isNaN(Number(response.statusCode))) ?? candidates[0] ?? null;
931
- }
932
- // src/http/index.ts
933
- var http_exports = /* @__PURE__ */ __exportAll({
934
- getBaseURL: () => getBaseURL,
935
- groupParameters: () => groupParameters,
936
- isOperation: () => isHttpOperationNode$1,
937
- requestBody: () => requestBody_exports,
938
- responses: () => responses_exports,
939
- status: () => status_exports
940
- });
941
- /** The server's URL when it is absolute and has no template variables, else `undefined`. */
942
- function getBaseURL(server) {
943
- if (!server || server.variables || server.url.includes("{") || !server.url.includes("://")) return void 0;
944
- return URL.canParse(server.url) ? server.url : void 0;
945
- }
946
- const parametersByNode = memo.create({ weak: true });
947
- /** The operation's parameters by location, with a `querystring` parameter in `query`. A repeated name keeps its first parameter. */
948
- function groupParameters(node) {
949
- return memo(parametersByNode, node, () => {
950
- const group = (...locations) => {
951
- const seen = /* @__PURE__ */ new Set();
952
- return locations.flatMap((location) => node.parameters.filter((param) => {
953
- if (param.in !== location || seen.has(param.name)) return false;
954
- seen.add(param.name);
955
- return true;
956
- }));
957
- };
958
- return {
959
- path: group("path"),
960
- query: group("query", "querystring"),
961
- header: group("header"),
962
- cookie: group("cookie")
963
- };
964
- });
965
- }
966
- // src/nodes/schema.ts
967
- /**
968
- * Maps schema `type` to its underlying `primitive`.
969
- * Primitive types map to themselves and special string formats map to `'string'`.
970
- * Any type not listed here (such as `ref`, `enum`, `union`, `intersection`, `not`, `tuple`, `ipv4`, `ipv6`, `blob`) has no `primitive`.
971
- */
972
- const TYPE_TO_PRIMITIVE = {
973
- string: "string",
974
- number: "number",
975
- integer: "integer",
976
- bigint: "bigint",
977
- boolean: "boolean",
978
- null: "null",
979
- any: "any",
980
- unknown: "unknown",
981
- void: "void",
982
- never: "never",
983
- object: "object",
984
- array: "array",
985
- date: "date",
986
- uuid: "string",
987
- email: "string",
988
- url: "string",
989
- datetime: "string",
990
- time: "string"
991
- };
992
- function createSchema(props) {
993
- if (props.type === "object") return {
994
- properties: [],
995
- primitive: "object",
996
- ...props,
997
- kind: nodeKinds$1.schema
998
- };
999
- return {
1000
- primitive: TYPE_TO_PRIMITIVE[props.type],
1001
- ...props,
1002
- kind: nodeKinds$1.schema
1003
- };
1004
- }
1005
- // src/ref/index.ts
1006
- var ref_exports = /* @__PURE__ */ __exportAll({
1007
- getName: () => getName,
1008
- getSchema: () => resolveRef$1,
1009
- isAlias: () => isBareRef$1,
1010
- mergeSchema: () => mergeSchema
1011
- });
1012
- /** A resolved ref merged with its target schema, so usage-site fields such as `description` win. Other nodes come back unchanged. */
1013
- function mergeSchema(node) {
1014
- const ref = narrowSchema$1(node, "ref");
1015
- return ref?.schema ? createSchema(mergeRefWithSchema$1(ref)) : node;
1016
- }
1017
- function getName(input) {
1018
- return typeof input === "string" ? refName$1(input) : resolveRefName$1(input);
1019
- }
1020
- // src/optionality.ts
1021
- /**
1022
- * Generic JSON Schema optionality: a non-required field is optional, and a
1023
- * non-required nullable field is nullish.
1024
- */
1025
- function applyOptionality(schema, required) {
1026
- const nullable = schema.nullable ?? false;
1027
- return {
1028
- ...schema,
1029
- optional: !required && !nullable ? true : void 0,
1030
- nullish: !required && nullable ? true : void 0
1031
- };
1032
- }
1033
- // src/utils/schemaProperties.ts
1034
- /**
1035
- * Finds every matching property exposed by an object, resolved reference, or intersection.
1036
- *
1037
- * References are followed through their parsed `schema`. Circular references terminate without
1038
- * revisiting a node. Unions are not traversed because a property on one branch does not describe
1039
- * every branch.
1040
- *
1041
- * @example Faker discriminator narrowing
1042
- * ```ts
1043
- * const values = resolveSchemaProperties({ node: member, propertyName: union.discriminatorPropertyName }).flatMap(({ schema }) =>
1044
- * getSchemaLiteralValues(schema),
1045
- * )
1046
- * const typeName = `Extract<Pet, { type: ${values.map(JSON.stringify).join(' | ')} }>`
1047
- * ```
1048
- *
1049
- * @example Zod discriminated unions
1050
- * ```ts
1051
- * const canDiscriminate = union.members?.every(
1052
- * (member) => resolveSchemaProperties({ node: member, propertyName: 'type' }).length > 0,
1053
- * )
1054
- * const expression = canDiscriminate ? `z.discriminatedUnion('type', members)` : `z.union(members)`
1055
- * ```
1056
- *
1057
- * @example TypeScript property lookup
1058
- * ```ts
1059
- * const properties = resolveSchemaProperties({ node: schema, propertyName: 'status' })
1060
- * const statusSchemas = properties.map((property) => print(property.schema))
1061
- * ```
1062
- */
1063
- function resolveSchemaProperties$1({ node, propertyName }) {
1064
- const properties = [];
1065
- walkSchema(node, "intersection", (current) => {
1066
- if (current.type !== "object") return;
1067
- const property = current.properties.find((candidate) => candidate.name === propertyName);
1068
- if (property) properties.push(property);
1069
- });
1070
- return properties;
1071
- }
1072
- __name(resolveSchemaProperties$1, "resolveSchemaProperties");
1073
- function walkSchema(node, through, visit) {
1074
- const visited = /* @__PURE__ */ new WeakSet();
1075
- function walk(current) {
1076
- if (!current || visited.has(current)) return;
1077
- visited.add(current);
1078
- visit(current);
1079
- if (current.type === "ref") return walk(current.schema);
1080
- if (current.type === through) for (const member of current.members ?? []) walk(member);
1081
- }
1082
- walk(node);
1083
- }
1084
- /**
1085
- * Reads the unique literal values represented by an enum, resolved reference, or union.
1086
- *
1087
- * Named enum values take precedence over simple enum values, matching how renderers consume
1088
- * `EnumSchemaNode`.
1089
- *
1090
- * @example
1091
- * ```ts
1092
- * const values = getSchemaLiteralValues(enumNode)
1093
- * // ['cat', 'dog']
1094
- * ```
1095
- */
1096
- function getSchemaLiteralValues$1(node) {
1097
- return memo(literalValues, node, () => {
1098
- const values = /* @__PURE__ */ new Set();
1099
- walkSchema(node, "union", (current) => {
1100
- if (current.type !== "enum") return;
1101
- for (const { value } of current.namedEnumValues ?? current.enumValues?.map((value) => ({ value })) ?? []) values.add(value);
1102
- });
1103
- return Object.freeze([...values]);
1104
- });
1105
- }
1106
- __name(getSchemaLiteralValues$1, "getSchemaLiteralValues");
1107
- const literalValues = memo.create({ weak: true });
1108
- function collectPropertyNames(node) {
1109
- const names = /* @__PURE__ */ new Set();
1110
- walkSchema(node, "intersection", (current) => {
1111
- if (current.type === "object") for (const property of current.properties) names.add(property.name);
1112
- });
1113
- return names;
1114
- }
1115
- /**
1116
- * Infers an implicit discriminator: a property every member exposes with a distinct single
1117
- * literal value, the same shape a declared OpenAPI `discriminator` already narrows on.
1118
- */
1119
- function inferDiscriminatorPropertyName$1(members) {
1120
- if (members.length < 2) return void 0;
1121
- let candidates;
1122
- for (const member of members) {
1123
- const names = collectPropertyNames(member);
1124
- candidates = candidates ? new Set([...candidates].filter((name) => names.has(name))) : names;
1125
- }
1126
- for (const name of candidates ?? []) {
1127
- const values = members.map((member) => {
1128
- const literals = new Set(resolveSchemaProperties$1({
1129
- node: member,
1130
- propertyName: name
1131
- }).flatMap((property) => getSchemaLiteralValues$1(property.schema)));
1132
- return literals.size === 1 ? [...literals][0] : void 0;
1133
- });
1134
- if (values.every((value) => value !== void 0) && new Set(values).size === members.length) return name;
1135
- }
1136
- }
1137
- __name(inferDiscriminatorPropertyName$1, "inferDiscriminatorPropertyName");
1138
- // src/schema/index.ts
1139
- var schema_exports = /* @__PURE__ */ __exportAll({
1140
- applyOptionality: () => applyOptionality,
1141
- find: () => findSchema$1,
1142
- findProperties: () => resolveSchemaProperties$1,
1143
- getEmbeddedJson: () => getEmbeddedJson,
1144
- getLiterals: () => getSchemaLiteralValues$1,
1145
- getNumberBounds: () => getNumberBounds,
1146
- inferDiscriminator: () => inferDiscriminatorPropertyName$1,
1147
- isString: () => isString,
1148
- narrow: () => narrowSchema$1,
1149
- types: () => schemaTypes$1
1150
- });
1151
- const plainStringTypes = /* @__PURE__ */ new Set([
1152
- "string",
1153
- "uuid",
1154
- "email",
1155
- "url",
1156
- "datetime"
1157
- ]);
1158
- /** Whether a schema prints as a plain `string`: string-like types, and `date` or `time` with a `'string'` representation. */
1159
- function isString(node) {
1160
- if (plainStringTypes.has(node.type)) return true;
1161
- const temporal = narrowSchema$1(node, "date") ?? narrowSchema$1(node, "time");
1162
- return temporal ? temporal.representation !== "date" : false;
1163
- }
1164
- /**
1165
- * The tightest inclusive bounds of a number schema. An exclusive bound moves to the next point of `step` (`1` for an
1166
- * integer), an integer bound rounds inward, and an integer bound past `Number.MAX_SAFE_INTEGER` is left out, since it
1167
- * prints as a rounded or invalid literal.
1168
- */
1169
- function getNumberBounds({ min, max, exclusive, integer = false, step }) {
1170
- const grid = step ?? (integer ? 1 : void 0);
1171
- const above = (bound) => grid ? (Math.floor(bound / grid) + 1) * grid : bound;
1172
- const below = (bound) => grid ? (Math.ceil(bound / grid) - 1) * grid : bound;
1173
- const tightest = (pick, bounds) => {
1174
- const usable = bounds.filter((bound) => bound !== void 0 && (!integer || Number.isSafeInteger(bound)));
1175
- return usable.length ? pick(...usable) : void 0;
1176
- };
1177
- const lower = tightest(Math.max, [min !== void 0 && integer ? Math.ceil(min) : min, exclusive?.min === void 0 ? void 0 : above(exclusive.min)]);
1178
- const upper = tightest(Math.min, [max !== void 0 && integer ? Math.floor(max) : max, exclusive?.max === void 0 ? void 0 : below(exclusive.max)]);
1179
- return {
1180
- ...lower !== void 0 ? { min: lower } : {},
1181
- ...upper !== void 0 ? { max: upper } : {}
1182
- };
1183
- }
2
+ const require_rolldown_runtime = require("./rolldown-runtime-BV8xUvPy.cjs");
3
+ const require_constants = require("./constants-CquR083U.cjs");
4
+ const require_graph = require("./graph-DcIY6tQb.cjs");
5
+ const require_visitor = require("./visitor-DTrzvA3R.cjs");
6
+ const require_ref = require("./ref-P0ZLT1Bg.cjs");
7
+ const require_schema = require("./schema-BIErWqgc.cjs");
8
+ const require_guards = require("./guards-COVJE6TU.cjs");
9
+ const require_refs = require("./refs-CYHpRlQo.cjs");
10
+ const require_macro = require("./macro-DrTBT7fh.cjs");
11
+ const require_optionality = require("./optionality-D-zqzVMH.cjs");
12
+ const require_node = require("./node-DjcETnc8.cjs");
13
+ const require_file = require("./file-Dd50jPkH.cjs");
14
+ const require_nodeText = require("./nodeText-DRb_rVd1.cjs");
15
+ const require_nodes = require("./nodes-BB60Bq2H.cjs");
16
+ const require_http = require("./http-Bm5lhVK4.cjs");
17
+ const require_json = require("./json-DURdtz9A.cjs");
18
+ const require_mediaType = require("./mediaType-D8uIO8sG.cjs");
1184
19
  // src/createPrinter.ts
1185
20
  /**
1186
21
  * Creates a schema printer: a function that takes a `SchemaNode` and emits
@@ -1231,964 +66,98 @@ function createPrinter$1(build) {
1231
66
  ...overrides
1232
67
  } : nodes;
1233
68
  const collectedImports = [];
1234
- const dispatch = (table) => (node) => {
69
+ const importNode = (node) => {
70
+ collectedImports.push(node);
71
+ };
72
+ const withOptions = (current, extra) => extra ? {
73
+ ...current,
74
+ ...extra
75
+ } : current;
76
+ const dispatch = (table, node, options, parent) => {
1235
77
  const handler = table[node.type];
1236
78
  if (!handler) return null;
1237
- return handler.call(context, node);
1238
- };
1239
- const context = {
1240
- options: resolvedOptions,
1241
- import: (node) => {
1242
- collectedImports.push(node);
1243
- },
1244
- transform: dispatch(merged),
1245
- base: dispatch(nodes)
79
+ return handler.call(createContext(options, node, parent), node);
1246
80
  };
81
+ function createContext(options, current, parent) {
82
+ const context = {
83
+ options,
84
+ parent,
85
+ import: importNode,
86
+ transform: (node, extra) => dispatch(merged, node, withOptions(context.options, extra), current),
87
+ base: (node, extra) => dispatch(nodes, node, withOptions(context.options, extra), parent)
88
+ };
89
+ return context;
90
+ }
91
+ const root = createContext(resolvedOptions);
1247
92
  return {
1248
93
  name,
1249
94
  options: resolvedOptions,
1250
- transform: context.transform,
1251
- print: printOverride ? printOverride.bind(context) : context.transform,
95
+ transform: root.transform,
96
+ print: printOverride ? (node, extra) => printOverride.call(extra ? createContext(withOptions(resolvedOptions, extra)) : root, node) : root.transform,
1252
97
  drainImports: () => collectedImports.splice(0)
1253
98
  };
1254
99
  };
1255
100
  }
1256
- __name(createPrinter$1, "createPrinter");
1257
- // src/defineMacro.ts
1258
- /**
1259
- * Sort weight for an `enforce` hint. `pre` sorts before unmarked items and `post` after, so a plain
1260
- * list keeps its authored order.
1261
- */
1262
- function enforceWeight(enforce) {
1263
- if (enforce === "pre") return 0;
1264
- if (enforce === "post") return 2;
1265
- return 1;
1266
- }
1267
- /**
1268
- * Compares two `enforce` hints for `Array.prototype.sort`: `pre` first, unmarked next, `post`
1269
- * last. Equal hints compare as `0`, so a stable sort keeps authored order within a bucket.
1270
- *
1271
- * @example
1272
- * `plugins.sort((a, b) => compareMacroOrder(a.enforce, b.enforce))`
1273
- */
1274
- function compareMacroOrder(a, b) {
1275
- return enforceWeight(a) - enforceWeight(b);
1276
- }
1277
- /**
1278
- * Types a macro for inference and a single construction site, mirroring `defineExtension`.
1279
- * Adds no runtime behavior.
1280
- *
1281
- * @example
1282
- * ```ts
1283
- * const macroUntagged = defineMacro({
1284
- * name: 'untagged',
1285
- * operation(node) {
1286
- * return node.tags?.length ? undefined : { ...node, tags: ['untagged'] }
1287
- * },
1288
- * })
1289
- * ```
1290
- */
1291
- function defineMacro$1(macro) {
1292
- return macro;
1293
- }
1294
- __name(defineMacro$1, "defineMacro");
1295
- /**
1296
- * Runs every macro's callback for one node kind in order, chaining the result so each macro sees
1297
- * the previous macro's output. Returns `undefined` when nothing changed, so `transform` keeps the
1298
- * original reference (structural sharing).
1299
- */
1300
- function chain({ macros, key, node, context }) {
1301
- let current = node;
1302
- for (const macro of macros) {
1303
- const callback = macro[key];
1304
- if (!callback) continue;
1305
- if (macro.match && !macro.match(current)) continue;
1306
- const next = callback(current, context);
1307
- if (next != null) current = next;
1308
- }
1309
- return current === node ? void 0 : current;
1310
- }
1311
- /**
1312
- * Folds an ordered list of macros into a single {@link Visitor} for `transform`. Macros are
1313
- * stable-sorted by `enforce`, then applied sequentially per node so later macros see earlier output.
1314
- */
1315
- function composeMacros(macros) {
1316
- const ordered = [...macros].sort((a, b) => compareMacroOrder(a.enforce, b.enforce));
1317
- const visitor = {};
1318
- for (const key of visitorKeys) {
1319
- if (!ordered.some((macro) => typeof macro[key] === "function")) continue;
1320
- const callback = (node, context) => chain({
1321
- macros: ordered,
1322
- key,
1323
- node,
1324
- context
1325
- });
1326
- visitor[key] = callback;
1327
- }
1328
- return visitor;
1329
- }
1330
- /**
1331
- * Runs a list of macros over a node tree and returns the rewritten tree. Keeps `transform`'s
1332
- * structural sharing, so an empty or no-op macro list returns the same reference. Pass
1333
- * `depth: 'shallow'` to rewrite the root node only.
1334
- *
1335
- * @example
1336
- * ```ts
1337
- * const next = applyMacros(root, [macroIntegerToString])
1338
- * ```
1339
- *
1340
- * @example Apply to the root node only
1341
- * ```ts
1342
- * const named = applyMacros(node, [macroEnumName({ parentName, propName, enumSuffix })], { depth: 'shallow' })
1343
- * ```
1344
- */
1345
- function applyMacros$1(root, macros, options) {
1346
- if (macros.length === 0) return root;
1347
- return transform$1(root, {
1348
- ...composeMacros(macros),
1349
- ...options
1350
- });
1351
- }
1352
- __name(applyMacros$1, "applyMacros");
1353
- // src/macro/index.ts
1354
- var macro_exports = /* @__PURE__ */ __exportAll({
1355
- apply: () => applyMacros$1,
1356
- compareOrder: () => compareMacroOrder
1357
- });
1358
- // src/utils/nodeText.ts
1359
- const CODE_NODE_TEXT_FIELDS = {
1360
- Text: ["value"],
1361
- Jsx: ["value"],
1362
- Function: [
1363
- "params",
1364
- "generics",
1365
- "returnType"
1366
- ],
1367
- ArrowFunction: [
1368
- "params",
1369
- "generics",
1370
- "returnType"
1371
- ],
1372
- Const: ["type"]
1373
- };
1374
- /**
1375
- * Extracts all string content from a `CodeNode` tree recursively.
1376
- * Collects the text fields and nested node content, to build the source string for import filtering.
1377
- */
1378
- function getNodeText(nodes) {
1379
- if (!nodes?.length) return "";
1380
- const collected = [];
1381
- for (const node of nodes) {
1382
- if (typeof node === "string") {
1383
- if (node) collected.push(node);
1384
- continue;
1385
- }
1386
- if (node.kind === nodeKinds$1.break) continue;
1387
- const parts = [];
1388
- const record = node;
1389
- for (const field of CODE_NODE_TEXT_FIELDS[node.kind] ?? []) {
1390
- const value = record[field];
1391
- if (Array.isArray(value)) parts.push(value.join(", "));
1392
- if (typeof value === "string" && value) parts.push(value);
1393
- }
1394
- const nested = "nodes" in node ? getNodeText(node.nodes) : "";
1395
- if (nested) parts.push(nested);
1396
- if (parts.length) collected.push(parts.join("\n"));
1397
- }
1398
- return collected.join("\n");
1399
- }
1400
- // src/node/index.ts
1401
- var node_exports = /* @__PURE__ */ __exportAll({
1402
- collect: () => collect$1,
1403
- getText: () => getNodeText,
1404
- kinds: () => nodeKinds$1,
1405
- transform: () => transform$1
1406
- });
1407
- // src/utils/combineFileMembers.ts
1408
- /**
1409
- * File-member merging. `combineImports` and `combineExports` deduplicate and sort the import and
1410
- * export entries of one file, while `combineSources` deduplicates source entries in original order.
1411
- * `combineImports` also drops imports nothing references. This works on a file's members, not on
1412
- * schema content.
1413
- */
1414
- const IDENTIFIER_RUN = /[\w$]+/g;
1415
- /**
1416
- * How many imports a file needs before indexing the source beats scanning it once per name.
1417
- */
1418
- const INDEX_ABOVE_IMPORTS = 128;
1419
- /**
1420
- * Returns the local binding an import name item introduces: the alias when there is one, else the
1421
- * imported name.
1422
- */
1423
- function importLocalName(item) {
1424
- return typeof item === "string" ? item : item.name ?? item.propertyName;
1425
- }
1426
- /**
1427
- * Returns the specifier a member is written with: POSIX and relative to the importing file when it
1428
- * has a `root`, like `getRelativePath` in parser-ts. Sorting on it keeps the order the same on every OS.
1429
- */
1430
- function specifier(node) {
1431
- if (!node.root) return node.path;
1432
- const relative = node_path.default.relative(node_path.default.dirname(node.root), node.path).replaceAll("\\", "/");
1433
- return relative.startsWith("../") ? relative : `./${relative}`;
1434
- }
1435
- /**
1436
- * Computes a multi-level sort key for exports and imports:
1437
- * non-array names first (wildcards/namespace aliases). Type-only before value. Alphabetical specifier. Unnamed before named.
1438
- */
1439
- function sortKey(node) {
1440
- const isArray = Array.isArray(node.name) ? "1" : "0";
1441
- const typeOnly = node.isTypeOnly ? "0" : "1";
1442
- const hasName = node.name != null ? "1" : "0";
1443
- const name = Array.isArray(node.name) ? node.name.toSorted().join("\0") : node.name ?? "";
1444
- return `${isArray}:${typeOnly}:${specifier(node)}:${hasName}:${name}`;
1445
- }
1446
- /**
1447
- * Sorts members by {@link sortKey}. Keys are computed once per node, not per comparison.
1448
- */
1449
- function sortMembers(nodes) {
1450
- return nodes.map((node) => ({
1451
- node,
1452
- key: sortKey(node)
1453
- })).sort((a, b) => a.key < b.key ? -1 : a.key > b.key ? 1 : 0).map(({ node }) => node);
1454
- }
1455
- /**
1456
- * Returns a collector for array-named members. A member whose path and `isTypeOnly` were already
1457
- * seen folds its names into that entry, otherwise it joins `result` as a new entry.
1458
- */
1459
- function mergeByPath(result) {
1460
- const byPath = /* @__PURE__ */ new Map();
1461
- return ({ node, names }) => {
1462
- const key = `${node.path}:${node.isTypeOnly ?? false}`;
1463
- const existing = byPath.get(key);
1464
- if (existing) {
1465
- for (const name of names) {
1466
- if (existing.seen.has(name)) continue;
1467
- existing.seen.add(name);
1468
- existing.names.push(name);
1469
- }
1470
- return;
1471
- }
1472
- const item = {
1473
- ...node,
1474
- name: [...names]
1475
- };
1476
- result.push(item);
1477
- byPath.set(key, {
1478
- names: item.name,
1479
- seen: new Set(names)
1480
- });
1481
- };
1482
- }
1483
- /**
1484
- * Deduplicates `SourceNode` objects by `name + isExportable + isTypeOnly`, keeping the first of each
1485
- * key. An unnamed source only drops when the same node appears twice, so markdown can repeat a
1486
- * paragraph or a table. Returns the deduplicated array in original order.
1487
- */
1488
- function combineSources(sources) {
1489
- const seen = /* @__PURE__ */ new Set();
1490
- return sources.filter((source) => {
1491
- const key = source.name != null ? `${source.name}:${source.isExportable ?? false}:${source.isTypeOnly ?? false}` : source;
1492
- if (seen.has(key)) return false;
1493
- seen.add(key);
1494
- return true;
1495
- });
1496
- }
1497
- /**
1498
- * Deduplicates and merges `ExportNode` objects by path and type.
1499
- *
1500
- * Named exports with the same path and `isTypeOnly` flag have their names merged into a single export.
1501
- * Non-array exports are deduplicated by exact identity. Returns a sorted, deduplicated array.
1502
- */
1503
- function combineExports(exports) {
1504
- const result = [];
1505
- const merge = mergeByPath(result);
1506
- const seen = /* @__PURE__ */ new Set();
1507
- for (const curr of sortMembers(exports)) {
1508
- const { name, path, isTypeOnly, asAlias } = curr;
1509
- if (Array.isArray(name)) {
1510
- if (name.length) merge({
1511
- node: curr,
1512
- names: [...new Set(name)]
1513
- });
1514
- continue;
1515
- }
1516
- const key = `${path}:${name ?? ""}:${isTypeOnly ?? false}:${asAlias ?? ""}`;
1517
- if (!seen.has(key)) {
1518
- result.push(curr);
1519
- seen.add(key);
1520
- }
1521
- }
1522
- return result;
1523
- }
1524
- /**
1525
- * Deduplicates and merges `ImportNode` objects, filtering out unused imports.
1526
- *
1527
- * Retains imports that are referenced in `source` or re-exported. Imports with the same path and
1528
- * `isTypeOnly` flag have their names merged. Returns a sorted, deduplicated, filtered array.
1529
- */
1530
- function combineImports(imports, exports, source) {
1531
- const exportedNames = new Set(exports.flatMap((e) => Array.isArray(e.name) ? e.name : e.name ? [e.name] : []));
1532
- const identifiers = source && imports.length > INDEX_ABOVE_IMPORTS ? new Set(source.match(IDENTIFIER_RUN)) : null;
1533
- const isUsed = (importName) => !source || identifiers?.has(importName) || source.includes(importName) || exportedNames.has(importName);
1534
- const importNameMemo = memo.create();
1535
- const canonicalizeName = (n) => {
1536
- if (typeof n === "string") return n;
1537
- const key = `${n.propertyName}:${n.name ?? ""}`;
1538
- return memo(importNameMemo, key, () => n);
1539
- };
1540
- const pathsWithUsedNamedImport = /* @__PURE__ */ new Set();
1541
- for (const node of imports) if (Array.isArray(node.name) && node.name.some((item) => isUsed(importLocalName(item)))) pathsWithUsedNamedImport.add(node.path);
1542
- const result = [];
1543
- const merge = mergeByPath(result);
1544
- const seen = /* @__PURE__ */ new Set();
1545
- for (const curr of sortMembers(imports)) {
1546
- if (curr.path === curr.root) continue;
1547
- const { name, path, isTypeOnly } = curr;
1548
- if (Array.isArray(name)) {
1549
- const names = [...new Set(name.map(canonicalizeName))].filter((item) => isUsed(importLocalName(item)));
1550
- if (names.length) merge({
1551
- node: curr,
1552
- names
1553
- });
1554
- continue;
1555
- }
1556
- if (!isUsed(name) && !pathsWithUsedNamedImport.has(path)) continue;
1557
- const key = `${path}:${name}:${isTypeOnly ?? false}`;
1558
- if (!seen.has(key)) {
1559
- result.push(curr);
1560
- seen.add(key);
1561
- }
1562
- }
1563
- return result;
1564
- }
1565
- // src/nodes/base.ts
1566
- /** Builds a `createX` factory for a node whose only computed field is `kind`. */
1567
- function nodeFactory(kind) {
1568
- return (input) => {
1569
- return {
1570
- ...input,
1571
- kind
1572
- };
1573
- };
1574
- }
1575
- // src/nodes/file.ts
1576
- /**
1577
- * Creates an `ImportNode` representing a language-agnostic import/dependency declaration.
1578
- *
1579
- * @example Named import
1580
- * ```ts
1581
- * createImport({ name: ['useState'], path: 'react' })
1582
- * // import { useState } from 'react'
1583
- * ```
1584
- */
1585
- const createImport = nodeFactory(nodeKinds$1.import);
1586
- /**
1587
- * Creates an `ExportNode` representing a language-agnostic export/public API declaration.
1588
- *
1589
- * @example Named export
1590
- * ```ts
1591
- * createExport({ name: ['Pet'], path: './Pet' })
1592
- * // export { Pet } from './Pet'
1593
- * ```
1594
- */
1595
- const createExport = nodeFactory(nodeKinds$1.export);
1596
- /**
1597
- * Creates a `SourceNode` representing a fragment of source code within a file.
1598
- *
1599
- * @example
1600
- * ```ts
1601
- * createSource({ name: 'Pet', nodes: [createText('export type Pet = { id: number }')], isExportable: true })
1602
- * ```
1603
- */
1604
- const createSource = nodeFactory(nodeKinds$1.source);
1605
- /**
1606
- * Creates a fully resolved `FileNode` from a file input descriptor.
1607
- *
1608
- * Computes:
1609
- * - `id` SHA256 hash of the file path
1610
- * - `name` `baseName` without extension
1611
- * - `extname` extension extracted from `baseName`
1612
- *
1613
- * Deduplicates:
1614
- * - `sources` via `combineSources`
1615
- * - `exports` via `combineExports`
1616
- * - `imports` via `combineImports` (also filters unused imports)
1617
- *
1618
- * @throws {Error} when `baseName` has no extension.
1619
- *
1620
- * @example
1621
- * ```ts
1622
- * const file = createFile({
1623
- * baseName: 'petStore.ts',
1624
- * path: 'src/models/petStore.ts',
1625
- * sources: [createSource({ name: 'Pet', nodes: [createText('export type Pet = { id: number }')] })],
1626
- * imports: [createImport({ name: ['z'], path: 'zod' })],
1627
- * exports: [createExport({ name: ['Pet'], path: './petStore' })],
1628
- * })
1629
- * // file.id = SHA256 hash of 'src/models/petStore.ts'
1630
- * // file.name = 'petStore'
1631
- * // file.extname = '.ts'
1632
- * ```
1633
- *
1634
- * @example Copy a real file into the output
1635
- * ```ts
1636
- * const file = createFile({
1637
- * baseName: 'client.ts',
1638
- * path: 'src/gen/client.ts',
1639
- * copy: '/abs/path/to/templates/client.ts',
1640
- * })
1641
- * ```
1642
- */
1643
- function createFile(input) {
1644
- const extname = node_path.default.extname(input.baseName);
1645
- if (!extname) throw new Error(`No extname found for ${input.baseName}`);
1646
- const resolvedExports = input.exports?.length ? combineExports(input.exports) : [];
1647
- const resolvedSources = input.sources?.length ? combineSources(input.sources) : [];
1648
- const resolvedImports = (() => {
1649
- if (!input.imports?.length) return [];
1650
- const sourceParts = [];
1651
- const localNames = /* @__PURE__ */ new Set();
1652
- for (const item of resolvedSources) {
1653
- const extracted = item.nodes && getNodeText(item.nodes);
1654
- if (extracted) sourceParts.push(extracted);
1655
- if (item.name) localNames.add(item.name);
1656
- }
1657
- const source = sourceParts.join("\n") || void 0;
1658
- return combineImports(input.imports, resolvedExports, source).flatMap((imp) => {
1659
- if (imp.path === input.path) return [];
1660
- if (!Array.isArray(imp.name)) return typeof imp.name === "string" && localNames.has(imp.name) ? [] : [imp];
1661
- const kept = imp.name.filter((item) => !localNames.has(importLocalName(item)));
1662
- if (!kept.length) return [];
1663
- return [kept.length === imp.name.length ? imp : {
1664
- ...imp,
1665
- name: kept
1666
- }];
1667
- });
1668
- })();
1669
- return {
1670
- ...input,
1671
- kind: nodeKinds$1.file,
1672
- id: (0, node_crypto.hash)("sha256", input.path, "hex"),
1673
- name: node_path.default.basename(input.baseName, extname),
1674
- extname,
1675
- imports: resolvedImports,
1676
- exports: resolvedExports,
1677
- sources: resolvedSources,
1678
- meta: input.meta ?? {}
1679
- };
1680
- }
1681
- // src/utils/inline.ts
1682
- /**
1683
- * Replaces every name a file imports from a virtual file (one whose sources are all inline, so it is never written) with that name's
1684
- * `inline.expression`, until no inline names are left. The definitions' own imports move to the importing file.
1685
- */
1686
- function inlineFiles$1(files, { language }) {
1687
- const virtualFiles = new Map(files.filter((file) => file.sources.length > 0 && file.sources.every((source) => source.inline)).map((file) => [file.path, file]));
1688
- const result = {
1689
- files: [],
1690
- virtualPaths: [...virtualFiles.keys()],
1691
- problems: []
1692
- };
1693
- if (virtualFiles.size === 0) return result;
1694
- const definitions = /* @__PURE__ */ new Map();
1695
- function define(path, name, from, lang) {
1696
- const key = `${path}\0${name}`;
1697
- if (definitions.has(key)) {
1698
- const definition = definitions.get(key);
1699
- if (definition === null) result.problems.push({
1700
- path: from,
1701
- message: `"${name}" from "${path}" is defined in terms of itself.`
1702
- });
1703
- return definition ?? void 0;
1704
- }
1705
- const file = virtualFiles.get(path);
1706
- const inline = file.sources.find((source) => source.name === name)?.inline;
1707
- if (!inline) {
1708
- result.problems.push({
1709
- path: from,
1710
- message: `"${name}" is imported from "${path}", which never writes it and has no inline definition for it.`
1711
- });
1712
- return;
1713
- }
1714
- definitions.set(key, null);
1715
- const imports = [];
1716
- const { text, used } = replaceNames(inline.expression, file, lang, imports);
1717
- imports.push(...file.imports.flatMap((imp) => virtualFiles.has(imp.path) ? [] : pickNames(imp, used)));
1718
- const definition = {
1719
- expression: text,
1720
- imports
1721
- };
1722
- definitions.set(key, definition);
1723
- return definition;
1724
- }
1725
- function replaceNames(input, file, lang, imports) {
1726
- const used = /* @__PURE__ */ new Set();
1727
- return {
1728
- text: lang.replaceIdentifiers(input, (local) => {
1729
- const target = findTarget(file, local);
1730
- const definition = target && define(target.path, target.name, file.path, lang);
1731
- if (!definition) {
1732
- used.add(local);
1733
- return;
1734
- }
1735
- imports.push(...definition.imports);
1736
- return lang.wrap(definition.expression);
1737
- }),
1738
- used
1739
- };
1740
- }
1741
- function findTarget(file, local) {
1742
- if (virtualFiles.has(file.path) && file.sources.some((source) => source.name === local)) return {
1743
- path: file.path,
1744
- name: local
1745
- };
1746
- for (const imp of file.imports) {
1747
- const item = virtualFiles.has(imp.path) && [imp.name].flat().find((item) => importLocalName(item) === local);
1748
- if (item) return {
1749
- path: imp.path,
1750
- name: typeof item === "string" ? item : item.propertyName
1751
- };
1752
- }
1753
- }
1754
- for (const file of files) {
1755
- if (virtualFiles.has(file.path) || !file.imports.some((imp) => virtualFiles.has(imp.path))) continue;
1756
- const lang = language(file);
1757
- if (!lang) {
1758
- result.problems.push({
1759
- path: file.path,
1760
- message: `No parser for "${file.extname}" files supports inline sources.`
1761
- });
1762
- continue;
1763
- }
1764
- const carried = [];
1765
- const sources = file.sources.map((source) => ({
1766
- ...source,
1767
- nodes: rewriteNodes(source.nodes, (text) => replaceNames(text, file, lang, carried).text)
1768
- }));
1769
- const imports = [...file.imports.filter((imp) => !virtualFiles.has(imp.path)), ...carried.map((imp) => imp.root ? {
1770
- ...imp,
1771
- root: file.path
1772
- } : imp)];
1773
- result.files.push(createFile({
1774
- ...file,
1775
- sources,
1776
- imports
1777
- }));
1778
- }
1779
- return result;
1780
- }
1781
- __name(inlineFiles$1, "inlineFiles");
1782
- function pickNames(imp, used) {
1783
- if (!Array.isArray(imp.name)) return used.has(imp.name) ? [imp] : [];
1784
- const name = imp.name.filter((item) => used.has(importLocalName(item)));
1785
- return name.length > 0 ? [{
1786
- ...imp,
1787
- name
1788
- }] : [];
1789
- }
1790
- function rewriteNodes(nodes, rewrite) {
1791
- return nodes?.map((node) => {
1792
- if (typeof node === "string") return rewrite(node);
1793
- if (node.kind === nodeKinds$1.break) return node;
1794
- const next = { ...node };
1795
- for (const field of CODE_NODE_TEXT_FIELDS[node.kind] ?? []) {
1796
- const value = next[field];
1797
- if (Array.isArray(value)) next[field] = value.map(rewrite);
1798
- if (typeof value === "string" && value) next[field] = rewrite(value);
1799
- }
1800
- if ("nodes" in node && node.nodes) next.nodes = rewriteNodes(node.nodes, rewrite);
1801
- return next;
1802
- });
1803
- }
1804
- // src/file/index.ts
1805
- var file_exports = /* @__PURE__ */ __exportAll({ inline: () => inlineFiles$1 });
101
+ require_rolldown_runtime.__name(createPrinter$1, "createPrinter");
1806
102
  // src/deprecated.ts
1807
103
  /** @deprecated Use `ast.ref.isAlias`. Removed in Kubb v6. */
1808
- const isBareRef = isBareRef$1;
104
+ const isBareRef = require_refs.isBareRef;
1809
105
  /** @deprecated Use `ast.ref.mergeSchema`. Removed in Kubb v6. */
1810
- const mergeRefWithSchema = mergeRefWithSchema$1;
106
+ const mergeRefWithSchema = require_refs.mergeRefWithSchema;
1811
107
  /** @deprecated Use `ast.ref.getName`. Removed in Kubb v6. */
1812
- const refName = getName;
108
+ const refName = require_ref.getName;
1813
109
  /** @deprecated Use `ast.ref.getSchema`. Removed in Kubb v6. */
1814
- const resolveRef = resolveRef$1;
110
+ const resolveRef = require_refs.resolveRef;
1815
111
  /** @deprecated Use `ast.ref.getName`. Removed in Kubb v6. */
1816
- const resolveRefName = getName;
112
+ const resolveRefName = require_ref.getName;
1817
113
  /** @deprecated Use `ast.graph.getImportedNames`. Removed in Kubb v6. */
1818
- const collectImportedRefNames = collectImportedRefNames$1;
114
+ const collectImportedRefNames = require_graph.collectImportedRefNames;
1819
115
  /** @deprecated Use `ast.graph.getRefNames`. Removed in Kubb v6. */
1820
- const collectSchemaRefs = collectSchemaRefs$1;
116
+ const collectSchemaRefs = require_graph.collectSchemaRefs;
1821
117
  /** @deprecated Use `ast.graph.getUsedNames`. Removed in Kubb v6. */
1822
- const collectUsedSchemaNames = collectUsedSchemaNames$1;
118
+ const collectUsedSchemaNames = require_graph.collectUsedSchemaNames;
1823
119
  /** @deprecated Use `ast.graph.getCircularNames`. Removed in Kubb v6. */
1824
- const findCircularSchemas = findCircularSchemas$1;
120
+ const findCircularSchemas = require_graph.findCircularSchemas;
1825
121
  /** @deprecated Use `ast.schema.getLiterals`. Removed in Kubb v6. */
1826
- const getSchemaLiteralValues = getSchemaLiteralValues$1;
122
+ const getSchemaLiteralValues = require_schema.getSchemaLiteralValues;
1827
123
  /** @deprecated Use `ast.schema.inferDiscriminator`. Removed in Kubb v6. */
1828
- const inferDiscriminatorPropertyName = inferDiscriminatorPropertyName$1;
124
+ const inferDiscriminatorPropertyName = require_schema.inferDiscriminatorPropertyName;
1829
125
  /** @deprecated Use `ast.schema.findProperties`. Removed in Kubb v6. */
1830
- const resolveSchemaProperties = resolveSchemaProperties$1;
126
+ const resolveSchemaProperties = require_schema.resolveSchemaProperties;
1831
127
  /** @deprecated Use `ast.http.isOperation`. Removed in Kubb v6. */
1832
- const isHttpOperationNode = isHttpOperationNode$1;
128
+ const isHttpOperationNode = require_guards.isHttpOperationNode;
1833
129
  /** @deprecated Use `ast.node.collect`, which returns the same array. Removed in Kubb v6. */
1834
- const collectSync = collect$1;
130
+ const collectSync = require_visitor.collect;
1835
131
  /** @deprecated Use `ast.schema.applyOptionality`. Removed in Kubb v6. */
1836
- const optionality = applyOptionality;
132
+ const optionality = require_optionality.applyOptionality;
1837
133
  /** @deprecated Use `ast.node.getText`. Removed in Kubb v6. */
1838
- const extractStringsFromNodes = getNodeText;
134
+ const extractStringsFromNodes = require_nodeText.getNodeText;
1839
135
  /** @deprecated Use `ast.macro.compareOrder`. Removed in Kubb v6. */
1840
- const compareEnforce = compareMacroOrder;
136
+ const compareEnforce = require_macro.compareMacroOrder;
1841
137
  /** @deprecated Use `createPrinter` from `@kubb/kit`. Removed in Kubb v6. */
1842
138
  const createPrinter = createPrinter$1;
1843
139
  /** @deprecated Use `defineMacro` from `@kubb/kit`. Removed in Kubb v6. */
1844
- const defineMacro = defineMacro$1;
140
+ const defineMacro = require_macro.defineMacro;
1845
141
  /** @deprecated Use `ast.macro.apply`. Removed in Kubb v6. */
1846
- const applyMacros = applyMacros$1;
142
+ const applyMacros = require_macro.applyMacros;
1847
143
  /** @deprecated Use `ast.node.kinds`. Removed in Kubb v6. */
1848
- const nodeKinds = nodeKinds$1;
144
+ const nodeKinds = require_constants.nodeKinds;
1849
145
  /** @deprecated Use `ast.schema.types`. Removed in Kubb v6. */
1850
- const schemaTypes = schemaTypes$1;
146
+ const schemaTypes = require_constants.schemaTypes;
1851
147
  /** @deprecated Use `ast.schema.find`. Removed in Kubb v6. */
1852
- const findSchema = findSchema$1;
148
+ const findSchema = require_visitor.findSchema;
1853
149
  /** @deprecated Use `ast.schema.narrow`. Removed in Kubb v6. */
1854
- const narrowSchema = narrowSchema$1;
150
+ const narrowSchema = require_guards.narrowSchema;
1855
151
  /** @deprecated Use `ast.node.transform`. Removed in Kubb v6. */
1856
- const transform = transform$1;
152
+ const transform = require_visitor.transform;
1857
153
  /** @deprecated Use `ast.node.collect`. Removed in Kubb v6. */
1858
- const collect = collect$1;
154
+ const collect = require_visitor.collect;
1859
155
  /** @deprecated Use `ast.file.inline`. Removed in Kubb v6. */
1860
- const inlineFiles = inlineFiles$1;
1861
- // src/auth/index.ts
1862
- var auth_exports = /* @__PURE__ */ __exportAll({ getRequirements: () => getRequirements });
1863
- /** Joins each requirement with its schemes. Drops undeclared and repeated requirements, and keeps an empty one (no auth needed). */
1864
- function getRequirements({ auth, schemes }) {
1865
- const credentials = new Map(schemes?.map((scheme) => [scheme.name, scheme.credential]));
1866
- const seen = /* @__PURE__ */ new Set();
1867
- const resolved = [];
1868
- for (const requirement of auth ?? []) {
1869
- const key = requirement.map(({ scheme, scopes }) => [scheme, ...scopes ?? []].join(" ")).join("\0");
1870
- if (seen.has(key) || !requirement.every(({ scheme }) => credentials.has(scheme))) continue;
1871
- seen.add(key);
1872
- resolved.push(requirement.map(({ scheme, scopes }) => ({
1873
- name: scheme,
1874
- credential: credentials.get(scheme),
1875
- scopes: scopes ?? []
1876
- })));
1877
- }
1878
- return resolved;
1879
- }
1880
- // src/nodes/code.ts
1881
- /**
1882
- * Creates a `ConstNode` representing a TypeScript `const` declaration.
1883
- *
1884
- * @example Exported constant with type and `as const`
1885
- * ```ts
1886
- * createConst({ name: 'pets', export: true, type: 'Pet[]', asConst: true })
1887
- * // export const pets: Pet[] = ... as const
1888
- * ```
1889
- */
1890
- const createConst = nodeFactory(nodeKinds$1.const);
1891
- /**
1892
- * Creates a `TypeNode` representing a TypeScript `type` alias declaration.
1893
- *
1894
- * @example
1895
- * ```ts
1896
- * createType({ name: 'Pet', export: true })
1897
- * // export type Pet = ...
1898
- * ```
1899
- */
1900
- const createType = nodeFactory(nodeKinds$1.type);
1901
- /**
1902
- * Creates a `FunctionNode` representing a TypeScript `function` declaration.
1903
- *
1904
- * @example
1905
- * ```ts
1906
- * createFunction({ name: 'fetchPet', export: true, async: true, returnType: 'Pet' })
1907
- * // export async function fetchPet(): Promise<Pet> { ... }
1908
- * ```
1909
- */
1910
- const createFunction = nodeFactory(nodeKinds$1.function);
1911
- /**
1912
- * Creates an `ArrowFunctionNode` representing a TypeScript arrow function.
1913
- *
1914
- * @example
1915
- * ```ts
1916
- * createArrowFunction({ name: 'double', export: true, params: 'n: number', singleLine: true })
1917
- * // export const double = (n: number) => ...
1918
- * ```
1919
- */
1920
- const createArrowFunction = nodeFactory(nodeKinds$1.arrowFunction);
1921
- /**
1922
- * Creates a {@link TextNode} representing a raw string fragment in the source output.
1923
- *
1924
- * @example
1925
- * ```ts
1926
- * createText('return fetch(id)')
1927
- * // { kind: 'Text', value: 'return fetch(id)' }
1928
- * ```
1929
- */
1930
- function createText(value) {
1931
- return {
1932
- kind: nodeKinds$1.text,
1933
- value
1934
- };
1935
- }
1936
- /**
1937
- * Creates a {@link BreakNode} representing a line break in the source output.
1938
- *
1939
- * @example
1940
- * ```ts
1941
- * createBreak()
1942
- * // { kind: 'Break' }
1943
- * ```
1944
- */
1945
- function createBreak() {
1946
- return { kind: nodeKinds$1.break };
1947
- }
1948
- /**
1949
- * Creates a {@link JsxNode} representing a raw JSX fragment in the source output.
1950
- *
1951
- * @example
1952
- * ```ts
1953
- * createJsx('<>\n <a href={href}>Open</a>\n</>')
1954
- * // { kind: 'Jsx', value: '<>\n <a href={href}>Open</a>\n</>' }
1955
- * ```
1956
- */
1957
- function createJsx(value) {
1958
- return {
1959
- kind: nodeKinds$1.jsx,
1960
- value
1961
- };
1962
- }
1963
- // src/nodes/content.ts
1964
- /**
1965
- * Creates a `ContentNode` for a single request-body or response content type.
1966
- */
1967
- const createContent = nodeFactory(nodeKinds$1.content);
1968
- // src/nodes/input.ts
1969
- /**
1970
- * Creates an `InputNode`, defaulting `schemas`/`operations` to empty arrays and `meta` to an empty
1971
- * object. Every call allocates fresh defaults so no two inputs share them.
1972
- *
1973
- * @example
1974
- * ```ts
1975
- * const input = createInput()
1976
- * // { kind: 'Input', schemas: [], operations: [] }
1977
- * ```
1978
- */
1979
- function createInput(overrides = {}) {
1980
- return {
1981
- schemas: [],
1982
- operations: [],
1983
- meta: {},
1984
- ...overrides,
1985
- kind: nodeKinds$1.input
1986
- };
1987
- }
1988
- // src/nodes/requestBody.ts
1989
- /**
1990
- * Creates a `RequestBodyNode`.
1991
- */
1992
- const createRequestBody = nodeFactory(nodeKinds$1.requestBody);
1993
- // src/nodes/operation.ts
1994
- function createOperation(props) {
1995
- const { requestBody, ...rest } = props;
1996
- const isHttp = rest.method !== void 0 && rest.path !== void 0;
1997
- return {
1998
- tags: [],
1999
- parameters: [],
2000
- responses: [],
2001
- ...rest,
2002
- kind: nodeKinds$1.operation,
2003
- ...isHttp ? { protocol: "http" } : {},
2004
- requestBody: requestBody ? createRequestBody(requestBody) : void 0
2005
- };
2006
- }
2007
- // src/nodes/parameter.ts
2008
- /**
2009
- * Creates a `ParameterNode`. `required` defaults to `false`, and the schema's
2010
- * `optional`/`nullish` flags are derived from it.
2011
- *
2012
- * @example
2013
- * ```ts
2014
- * const param = createParameter({
2015
- * name: 'petId',
2016
- * in: 'path',
2017
- * required: true,
2018
- * schema: createSchema({ type: 'string' }),
2019
- * })
2020
- * ```
2021
- */
2022
- function createParameter(input) {
2023
- const required = input.required ?? false;
2024
- return {
2025
- ...input,
2026
- required,
2027
- schema: applyOptionality(input.schema, required),
2028
- kind: nodeKinds$1.parameter
2029
- };
2030
- }
2031
- // src/nodes/property.ts
2032
- /**
2033
- * Creates a `PropertyNode`. `required` defaults to `false`, and the schema's
2034
- * `optional`/`nullish` flags are derived from it.
2035
- *
2036
- * @example
2037
- * ```ts
2038
- * const property = createProperty({
2039
- * name: 'status',
2040
- * required: true,
2041
- * schema: createSchema({ type: 'string', nullable: true }),
2042
- * })
2043
- * // required=true, no optional/nullish
2044
- * ```
2045
- */
2046
- function createProperty(input) {
2047
- const required = input.required ?? false;
2048
- return {
2049
- ...input,
2050
- required,
2051
- schema: applyOptionality(input.schema, required),
2052
- kind: nodeKinds$1.property
2053
- };
2054
- }
2055
- // src/nodes/response.ts
2056
- /**
2057
- * Creates a `ResponseNode`. A single legacy `schema` (with optional `mediaType`/`keysToOmit`)
2058
- * is normalized into one `content` entry.
2059
- *
2060
- * @example
2061
- * ```ts
2062
- * const response = createResponse({
2063
- * statusCode: '200',
2064
- * content: [createContent({ contentType: 'application/json', schema: createSchema({ type: 'object', properties: [] }) })],
2065
- * })
2066
- * ```
2067
- */
2068
- function createResponse(props) {
2069
- const { schema, mediaType, keysToOmit, content, ...rest } = props;
2070
- const entries = content ?? (schema ? [createContent({
2071
- contentType: mediaType ?? "application/json",
2072
- schema,
2073
- keysToOmit: keysToOmit ?? null
2074
- })] : void 0);
2075
- return {
2076
- ...rest,
2077
- content: entries,
2078
- kind: nodeKinds$1.response
2079
- };
2080
- }
2081
- // src/nodes/index.ts
2082
- var nodes_exports = /* @__PURE__ */ __exportAll({
2083
- createArrowFunction: () => createArrowFunction,
2084
- createBreak: () => createBreak,
2085
- createConst: () => createConst,
2086
- createContent: () => createContent,
2087
- createExport: () => createExport,
2088
- createFile: () => createFile,
2089
- createFunction: () => createFunction,
2090
- createImport: () => createImport,
2091
- createInput: () => createInput,
2092
- createJsx: () => createJsx,
2093
- createOperation: () => createOperation,
2094
- createParameter: () => createParameter,
2095
- createProperty: () => createProperty,
2096
- createRequestBody: () => createRequestBody,
2097
- createResponse: () => createResponse,
2098
- createSchema: () => createSchema,
2099
- createSource: () => createSource,
2100
- createText: () => createText,
2101
- createType: () => createType
2102
- });
2103
- // src/json/index.ts
2104
- var json_exports = /* @__PURE__ */ __exportAll({
2105
- parse: () => parse,
2106
- stringify: () => stringify
2107
- });
2108
- const version = 1;
2109
- function isRef(value) {
2110
- const node = value;
2111
- return node?.kind === nodeKinds$1.schema && node.type === schemaTypes$1.ref;
2112
- }
2113
- /**
2114
- * Turns an `InputNode` into JSON text that `parse` reads back. Every schema a ref points at is written once,
2115
- * where a plain `JSON.stringify(input)` writes it again at every ref.
2116
- *
2117
- * @example
2118
- * ```ts
2119
- * await writeFile('input.json', ast.json.stringify(input))
2120
- * ```
2121
- */
2122
- function stringify(input) {
2123
- const ids = /* @__PURE__ */ new Map();
2124
- const targets = [];
2125
- function replacer(key, value) {
2126
- if (key !== "schema" || !isRef(this)) return value;
2127
- if (typeof value === "number") return [value];
2128
- if (typeof value !== "object" || value === null) return value;
2129
- if (!ids.has(value)) {
2130
- ids.set(value, targets.length);
2131
- targets.push(value);
2132
- }
2133
- return ids.get(value);
2134
- }
2135
- const root = JSON.stringify(input, replacer);
2136
- const encoded = [];
2137
- for (const target of targets) encoded.push(JSON.stringify(target, replacer));
2138
- return `{"version":${version},"input":${root},"targets":[${encoded.join(",")}]}`;
2139
- }
2140
- /**
2141
- * Reads the text `stringify` wrote back into an `InputNode`. Refs to one schema share one object again.
2142
- * Throws on another format version, or on a ref whose target is missing.
2143
- */
2144
- function parse(text) {
2145
- const document = JSON.parse(text);
2146
- if (document?.version !== version) throw new Error(`Cannot read this AST JSON: expected format version ${version}, got ${JSON.stringify(document?.version)}.`);
2147
- if (!document.input || !Array.isArray(document.targets)) throw new Error("Cannot read this AST JSON: `input` or `targets` is missing.");
2148
- const targets = document.targets;
2149
- const stack = [document.input, ...targets];
2150
- while (stack.length) {
2151
- const value = stack.pop();
2152
- const ref = isRef(value);
2153
- for (const key in value) {
2154
- const child = value[key];
2155
- if (ref && key === "schema") {
2156
- if (Array.isArray(child)) {
2157
- value.schema = child[0];
2158
- continue;
2159
- }
2160
- if (typeof child === "number") {
2161
- const target = targets[child];
2162
- if (!target) throw new Error(`Cannot read this AST JSON: a ref points at target ${child}, which is missing.`);
2163
- value.schema = target;
2164
- continue;
2165
- }
2166
- }
2167
- if (typeof child === "object" && child !== null) stack.push(child);
2168
- }
2169
- }
2170
- return document.input;
2171
- }
2172
- // src/server/index.ts
2173
- var server_exports = /* @__PURE__ */ __exportAll({
2174
- get: () => get,
2175
- groupByName: () => groupByName
2176
- });
2177
- /** The server at `index`, else the first one. */
2178
- function get({ servers, index = 0 }) {
2179
- return servers?.[index] ?? servers?.[0];
2180
- }
2181
- /** Named servers by name. The first server with a name wins. */
2182
- function groupByName(servers) {
2183
- const named = /* @__PURE__ */ new Map();
2184
- for (const server of servers ?? []) if (server.name && !named.has(server.name)) named.set(server.name, server);
2185
- return named;
2186
- }
156
+ const inlineFiles = require_file.inlineFiles;
2187
157
  // src/index.ts
2188
- var src_exports = /* @__PURE__ */ __exportAll({
158
+ var src_exports = /* @__PURE__ */ require_rolldown_runtime.__exportAll({
2189
159
  applyMacros: () => applyMacros,
2190
160
  ast: () => src_exports,
2191
- auth: () => auth_exports,
2192
161
  collect: () => collect,
2193
162
  collectImportedRefNames: () => collectImportedRefNames,
2194
163
  collectSchemaRefs: () => collectSchemaRefs,
@@ -2198,33 +167,32 @@ var src_exports = /* @__PURE__ */ __exportAll({
2198
167
  createPrinter: () => createPrinter,
2199
168
  defineMacro: () => defineMacro,
2200
169
  extractStringsFromNodes: () => extractStringsFromNodes,
2201
- factory: () => nodes_exports,
2202
- file: () => file_exports,
170
+ factory: () => require_nodes.nodes_exports,
171
+ file: () => require_file.file_exports,
2203
172
  findCircularSchemas: () => findCircularSchemas,
2204
173
  findSchema: () => findSchema,
2205
174
  getSchemaLiteralValues: () => getSchemaLiteralValues,
2206
- graph: () => graph_exports,
2207
- http: () => http_exports,
175
+ graph: () => require_graph.graph_exports,
176
+ http: () => require_http.http_exports,
2208
177
  inferDiscriminatorPropertyName: () => inferDiscriminatorPropertyName,
2209
178
  inlineFiles: () => inlineFiles,
2210
179
  isBareRef: () => isBareRef,
2211
180
  isHttpOperationNode: () => isHttpOperationNode,
2212
- json: () => json_exports,
2213
- macro: () => macro_exports,
2214
- mediaType: () => mediaType_exports,
181
+ json: () => require_json.json_exports,
182
+ macro: () => require_macro.macro_exports,
183
+ mediaType: () => require_mediaType.mediaType_exports,
2215
184
  mergeRefWithSchema: () => mergeRefWithSchema,
2216
185
  narrowSchema: () => narrowSchema,
2217
- node: () => node_exports,
186
+ node: () => require_node.node_exports,
2218
187
  nodeKinds: () => nodeKinds,
2219
188
  optionality: () => optionality,
2220
- ref: () => ref_exports,
189
+ ref: () => require_ref.ref_exports,
2221
190
  refName: () => refName,
2222
191
  resolveRef: () => resolveRef,
2223
192
  resolveRefName: () => resolveRefName,
2224
193
  resolveSchemaProperties: () => resolveSchemaProperties,
2225
- schema: () => schema_exports,
194
+ schema: () => require_schema.schema_exports,
2226
195
  schemaTypes: () => schemaTypes,
2227
- server: () => server_exports,
2228
196
  transform: () => transform
2229
197
  });
2230
198
  exports.applyMacros = applyMacros;
@@ -2234,12 +202,6 @@ Object.defineProperty(exports, "ast", {
2234
202
  return src_exports;
2235
203
  }
2236
204
  });
2237
- Object.defineProperty(exports, "auth", {
2238
- enumerable: true,
2239
- get: function() {
2240
- return auth_exports;
2241
- }
2242
- });
2243
205
  exports.collect = collect;
2244
206
  exports.collectImportedRefNames = collectImportedRefNames;
2245
207
  exports.collectSchemaRefs = collectSchemaRefs;
@@ -2252,13 +214,13 @@ exports.extractStringsFromNodes = extractStringsFromNodes;
2252
214
  Object.defineProperty(exports, "factory", {
2253
215
  enumerable: true,
2254
216
  get: function() {
2255
- return nodes_exports;
217
+ return require_nodes.nodes_exports;
2256
218
  }
2257
219
  });
2258
220
  Object.defineProperty(exports, "file", {
2259
221
  enumerable: true,
2260
222
  get: function() {
2261
- return file_exports;
223
+ return require_file.file_exports;
2262
224
  }
2263
225
  });
2264
226
  exports.findCircularSchemas = findCircularSchemas;
@@ -2267,13 +229,13 @@ exports.getSchemaLiteralValues = getSchemaLiteralValues;
2267
229
  Object.defineProperty(exports, "graph", {
2268
230
  enumerable: true,
2269
231
  get: function() {
2270
- return graph_exports;
232
+ return require_graph.graph_exports;
2271
233
  }
2272
234
  });
2273
235
  Object.defineProperty(exports, "http", {
2274
236
  enumerable: true,
2275
237
  get: function() {
2276
- return http_exports;
238
+ return require_http.http_exports;
2277
239
  }
2278
240
  });
2279
241
  exports.inferDiscriminatorPropertyName = inferDiscriminatorPropertyName;
@@ -2283,19 +245,19 @@ exports.isHttpOperationNode = isHttpOperationNode;
2283
245
  Object.defineProperty(exports, "json", {
2284
246
  enumerable: true,
2285
247
  get: function() {
2286
- return json_exports;
248
+ return require_json.json_exports;
2287
249
  }
2288
250
  });
2289
251
  Object.defineProperty(exports, "macro", {
2290
252
  enumerable: true,
2291
253
  get: function() {
2292
- return macro_exports;
254
+ return require_macro.macro_exports;
2293
255
  }
2294
256
  });
2295
257
  Object.defineProperty(exports, "mediaType", {
2296
258
  enumerable: true,
2297
259
  get: function() {
2298
- return mediaType_exports;
260
+ return require_mediaType.mediaType_exports;
2299
261
  }
2300
262
  });
2301
263
  exports.mergeRefWithSchema = mergeRefWithSchema;
@@ -2303,7 +265,7 @@ exports.narrowSchema = narrowSchema;
2303
265
  Object.defineProperty(exports, "node", {
2304
266
  enumerable: true,
2305
267
  get: function() {
2306
- return node_exports;
268
+ return require_node.node_exports;
2307
269
  }
2308
270
  });
2309
271
  exports.nodeKinds = nodeKinds;
@@ -2311,7 +273,7 @@ exports.optionality = optionality;
2311
273
  Object.defineProperty(exports, "ref", {
2312
274
  enumerable: true,
2313
275
  get: function() {
2314
- return ref_exports;
276
+ return require_ref.ref_exports;
2315
277
  }
2316
278
  });
2317
279
  exports.refName = refName;
@@ -2321,16 +283,10 @@ exports.resolveSchemaProperties = resolveSchemaProperties;
2321
283
  Object.defineProperty(exports, "schema", {
2322
284
  enumerable: true,
2323
285
  get: function() {
2324
- return schema_exports;
286
+ return require_schema.schema_exports;
2325
287
  }
2326
288
  });
2327
289
  exports.schemaTypes = schemaTypes;
2328
- Object.defineProperty(exports, "server", {
2329
- enumerable: true,
2330
- get: function() {
2331
- return server_exports;
2332
- }
2333
- });
2334
290
  exports.transform = transform;
2335
291
 
2336
292
  //# sourceMappingURL=index.cjs.map