@kubb/ast 5.0.0-beta.57 → 5.0.0-beta.59
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +21 -7
- package/dist/casing-BE2R1RXg.cjs +88 -0
- package/dist/casing-BE2R1RXg.cjs.map +1 -0
- package/dist/chunk-CNktS9qV.js +17 -0
- package/dist/extractStringsFromNodes-WMYJ8nQL.d.ts +82 -0
- package/dist/factory-BmcGBdeg.cjs +1251 -0
- package/dist/factory-BmcGBdeg.cjs.map +1 -0
- package/dist/factory-Du7nEP4B.js +282 -0
- package/dist/factory-Du7nEP4B.js.map +1 -0
- package/dist/factory.cjs +28 -0
- package/dist/factory.d.ts +62 -0
- package/dist/factory.js +3 -0
- package/dist/{types-C5aVnRE1.d.ts → index-BzjwdK2M.d.ts} +94 -1146
- package/dist/index.cjs +220 -1481
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.ts +96 -58
- package/dist/index.js +182 -1920
- package/dist/index.js.map +1 -1
- package/dist/operationParams-BZ07xDm0.d.ts +204 -0
- package/dist/response-DKxTr522.js +683 -0
- package/dist/response-DKxTr522.js.map +1 -0
- package/dist/types-olVl9v5p.d.ts +764 -0
- package/dist/types.d.ts +5 -2
- package/dist/utils-BCtRXfhI.cjs +275 -0
- package/dist/utils-BCtRXfhI.cjs.map +1 -0
- package/dist/utils-SdZU0F3H.js +1336 -0
- package/dist/utils-SdZU0F3H.js.map +1 -0
- package/dist/utils.cjs +129 -13
- package/dist/utils.d.ts +127 -76
- package/dist/utils.js +3 -2
- package/package.json +5 -1
- package/src/constants.ts +8 -14
- package/src/dedupe.ts +8 -0
- package/src/factory.ts +18 -1
- package/src/guards.ts +1 -1
- package/src/index.ts +7 -50
- package/src/node.ts +1 -1
- package/src/nodes/base.ts +0 -10
- package/src/nodes/code.ts +29 -47
- package/src/nodes/content.ts +2 -2
- package/src/nodes/file.ts +28 -23
- package/src/nodes/function.ts +2 -17
- package/src/nodes/index.ts +1 -1
- package/src/nodes/input.ts +20 -19
- package/src/nodes/operation.ts +1 -1
- package/src/nodes/parameter.ts +0 -3
- package/src/nodes/property.ts +0 -3
- package/src/nodes/requestBody.ts +3 -6
- package/src/nodes/schema.ts +3 -2
- package/src/printer.ts +4 -4
- package/src/registry.ts +31 -26
- package/src/signature.ts +3 -3
- package/src/transformers.ts +28 -1
- package/src/types.ts +2 -53
- package/src/utils/codegen.ts +104 -0
- package/src/utils/extractStringsFromNodes.ts +34 -0
- package/src/utils/fileMerge.ts +184 -0
- package/src/utils/index.ts +8 -296
- package/src/utils/operationParams.ts +353 -0
- package/src/utils/refs.ts +112 -0
- package/src/utils/schemaGraph.ts +169 -0
- package/src/utils/strings.ts +139 -0
- package/src/visitor.ts +43 -19
- package/dist/chunk-C0LytTxp.js +0 -8
- package/dist/utils-0p8ZO287.js +0 -570
- package/dist/utils-0p8ZO287.js.map +0 -1
- package/dist/utils-cdQ6Pzyi.cjs +0 -726
- package/dist/utils-cdQ6Pzyi.cjs.map +0 -1
- package/src/utils/ast.ts +0 -879
package/dist/index.js
CHANGED
|
@@ -1,189 +1,8 @@
|
|
|
1
|
-
import "./chunk-
|
|
2
|
-
import {
|
|
1
|
+
import "./chunk-CNktS9qV.js";
|
|
2
|
+
import { A as isHttpOperationNode, C as simplifyUnion, D as extractRefName, L as httpMethods, R as schemaTypes, S as setEnumName, b as mergeAdjacentObjectsLazy, d as transform, f as walk, j as narrowSchema, l as collect, p as nodeDefs, u as collectLazy, x as setDiscriminatorEnum } from "./utils-SdZU0F3H.js";
|
|
3
|
+
import { $ as defineNode, A as contentDef, D as fileDef, E as exportDef, G as typeDef, H as functionDef, J as extractStringsFromNodes, M as arrowFunctionDef, N as breakDef, O as importDef, P as constDef, Q as schemaDef, S as typeLiteralDef, U as jsxDef, W as textDef, Z as createSchema, b as indexedAccessTypeDef, c as operationDef, et as syncOptionality, f as inputDef, i as parameterDef, k as sourceDef, n as responseDef, o as outputDef, q as propertyDef, u as requestBodyDef, v as functionParameterDef, x as objectBindingPatternDef, y as functionParametersDef } from "./response-DKxTr522.js";
|
|
4
|
+
import { n as factory_exports } from "./factory-Du7nEP4B.js";
|
|
3
5
|
import { hash } from "node:crypto";
|
|
4
|
-
import path from "node:path";
|
|
5
|
-
//#region src/node.ts
|
|
6
|
-
/**
|
|
7
|
-
* Builds a type guard that matches nodes of the given `kind`.
|
|
8
|
-
*/
|
|
9
|
-
function isKind(kind) {
|
|
10
|
-
return (node) => node.kind === kind;
|
|
11
|
-
}
|
|
12
|
-
/**
|
|
13
|
-
* Updates a schema's `optional` and `nullish` flags from a parent's `required`
|
|
14
|
-
* value and the schema's own `nullable`. Mirrors how OpenAPI parameters and
|
|
15
|
-
* object properties combine "required" and "nullable" into a single AST.
|
|
16
|
-
*
|
|
17
|
-
* - Non-required + non-nullable → `optional: true`.
|
|
18
|
-
* - Non-required + nullable → `nullish: true`.
|
|
19
|
-
* - Required → both flags cleared.
|
|
20
|
-
*/
|
|
21
|
-
function syncOptionality(schema, required) {
|
|
22
|
-
const nullable = schema.nullable ?? false;
|
|
23
|
-
return {
|
|
24
|
-
...schema,
|
|
25
|
-
optional: !required && !nullable ? true : void 0,
|
|
26
|
-
nullish: !required && nullable ? true : void 0
|
|
27
|
-
};
|
|
28
|
-
}
|
|
29
|
-
/**
|
|
30
|
-
* Defines a node once and derives its `create` builder, `is` guard, and traversal
|
|
31
|
-
* metadata. `create` merges `defaults`, the `build` hook (or the raw input), and the
|
|
32
|
-
* `kind`, so node construction lives in one place without scattered `as` casts.
|
|
33
|
-
*
|
|
34
|
-
* Set `rebuild: true` when the `build` hook derives fields from children. After a
|
|
35
|
-
* transform rewrites those children, the registry reruns `create` so the derived
|
|
36
|
-
* fields stay correct.
|
|
37
|
-
*
|
|
38
|
-
* @example Simple node
|
|
39
|
-
* ```ts
|
|
40
|
-
* const importDef = defineNode<ImportNode>({ kind: 'Import' })
|
|
41
|
-
* const createImport = importDef.create
|
|
42
|
-
* ```
|
|
43
|
-
*
|
|
44
|
-
* @example Node with a build hook that is rerun on transform
|
|
45
|
-
* ```ts
|
|
46
|
-
* const propertyDef = defineNode<PropertyNode, UserPropertyNode>({
|
|
47
|
-
* kind: 'Property',
|
|
48
|
-
* build: (props) => ({ ...props, required: props.required ?? false }),
|
|
49
|
-
* children: ['schema'],
|
|
50
|
-
* visitorKey: 'property',
|
|
51
|
-
* rebuild: true,
|
|
52
|
-
* })
|
|
53
|
-
* ```
|
|
54
|
-
*/
|
|
55
|
-
function defineNode(config) {
|
|
56
|
-
const { kind, defaults, build, children, visitorKey, rebuild } = config;
|
|
57
|
-
function create(input) {
|
|
58
|
-
const base = build ? build(input) : input;
|
|
59
|
-
return {
|
|
60
|
-
...defaults,
|
|
61
|
-
...base,
|
|
62
|
-
kind
|
|
63
|
-
};
|
|
64
|
-
}
|
|
65
|
-
return {
|
|
66
|
-
kind,
|
|
67
|
-
create,
|
|
68
|
-
is: isKind(kind),
|
|
69
|
-
children,
|
|
70
|
-
visitorKey,
|
|
71
|
-
rebuild
|
|
72
|
-
};
|
|
73
|
-
}
|
|
74
|
-
//#endregion
|
|
75
|
-
//#region src/nodes/schema.ts
|
|
76
|
-
/**
|
|
77
|
-
* Maps schema `type` to its underlying `primitive`.
|
|
78
|
-
* Primitive types map to themselves. Special string formats map to `'string'`.
|
|
79
|
-
* Complex types (`ref`, `enum`, `union`, `intersection`, `tuple`, `blob`) are left unset.
|
|
80
|
-
*/
|
|
81
|
-
const TYPE_TO_PRIMITIVE = {
|
|
82
|
-
string: "string",
|
|
83
|
-
number: "number",
|
|
84
|
-
integer: "integer",
|
|
85
|
-
bigint: "bigint",
|
|
86
|
-
boolean: "boolean",
|
|
87
|
-
null: "null",
|
|
88
|
-
any: "any",
|
|
89
|
-
unknown: "unknown",
|
|
90
|
-
void: "void",
|
|
91
|
-
never: "never",
|
|
92
|
-
object: "object",
|
|
93
|
-
array: "array",
|
|
94
|
-
date: "date",
|
|
95
|
-
uuid: "string",
|
|
96
|
-
email: "string",
|
|
97
|
-
url: "string",
|
|
98
|
-
datetime: "string",
|
|
99
|
-
time: "string"
|
|
100
|
-
};
|
|
101
|
-
/**
|
|
102
|
-
* Definition for the {@link SchemaNode}. Object schemas default `properties` to an
|
|
103
|
-
* empty array, and `primitive` is inferred from `type` when not explicitly provided.
|
|
104
|
-
*/
|
|
105
|
-
const schemaDef = defineNode({
|
|
106
|
-
kind: "Schema",
|
|
107
|
-
build: (props) => {
|
|
108
|
-
if (props.type === "object") return {
|
|
109
|
-
properties: [],
|
|
110
|
-
primitive: "object",
|
|
111
|
-
...props
|
|
112
|
-
};
|
|
113
|
-
return {
|
|
114
|
-
primitive: TYPE_TO_PRIMITIVE[props.type],
|
|
115
|
-
...props
|
|
116
|
-
};
|
|
117
|
-
},
|
|
118
|
-
children: [
|
|
119
|
-
"properties",
|
|
120
|
-
"items",
|
|
121
|
-
"members",
|
|
122
|
-
"additionalProperties"
|
|
123
|
-
],
|
|
124
|
-
visitorKey: "schema"
|
|
125
|
-
});
|
|
126
|
-
function createSchema(props) {
|
|
127
|
-
return schemaDef.create(props);
|
|
128
|
-
}
|
|
129
|
-
//#endregion
|
|
130
|
-
//#region ../../internals/utils/src/fs.ts
|
|
131
|
-
/**
|
|
132
|
-
* Strips the file extension from a path or file name.
|
|
133
|
-
* Only removes the last `.ext` segment when the dot is not part of a directory name.
|
|
134
|
-
*
|
|
135
|
-
* @example
|
|
136
|
-
* trimExtName('petStore.ts') // 'petStore'
|
|
137
|
-
* trimExtName('/src/models/pet.ts') // '/src/models/pet'
|
|
138
|
-
* trimExtName('/project.v2/gen/pet.ts') // '/project.v2/gen/pet'
|
|
139
|
-
* trimExtName('noExtension') // 'noExtension'
|
|
140
|
-
*/
|
|
141
|
-
function trimExtName(text) {
|
|
142
|
-
const dotIndex = text.lastIndexOf(".");
|
|
143
|
-
if (dotIndex > 0 && !text.includes("/", dotIndex)) return text.slice(0, dotIndex);
|
|
144
|
-
return text;
|
|
145
|
-
}
|
|
146
|
-
//#endregion
|
|
147
|
-
//#region ../../internals/utils/src/promise.ts
|
|
148
|
-
/**
|
|
149
|
-
* Wraps `factory` with a keyed cache backed by the provided store.
|
|
150
|
-
*
|
|
151
|
-
* Pass a `WeakMap` for object keys (results are GC-eligible when the key is
|
|
152
|
-
* collected) or a `Map` for primitive keys. For multi-argument functions,
|
|
153
|
-
* nest two `memoize` calls — the outer keyed by the first argument, the
|
|
154
|
-
* inner (created once per outer miss) keyed by the second.
|
|
155
|
-
*
|
|
156
|
-
* Because the cache is owned by the caller, it can be shared, inspected, or
|
|
157
|
-
* cleared independently of the memoized function.
|
|
158
|
-
*
|
|
159
|
-
* @example Single WeakMap key
|
|
160
|
-
* ```ts
|
|
161
|
-
* const cache = new WeakMap<SchemaNode, Set<string>>()
|
|
162
|
-
* const getRefs = memoize(cache, (node) => collectRefs(node))
|
|
163
|
-
* ```
|
|
164
|
-
*
|
|
165
|
-
* @example Single Map key (primitive)
|
|
166
|
-
* ```ts
|
|
167
|
-
* const cache = new Map<string, Resolver>()
|
|
168
|
-
* const getResolver = memoize(cache, (name) => buildResolver(name))
|
|
169
|
-
* ```
|
|
170
|
-
*
|
|
171
|
-
* @example Two-level (object + primitive)
|
|
172
|
-
* ```ts
|
|
173
|
-
* const outer = new WeakMap<Params[], Map<string, Params[]>>()
|
|
174
|
-
* const fn = memoize(outer, (params) => memoize(new Map(), (key) => transform(params, key)))
|
|
175
|
-
* fn(params)('camelcase')
|
|
176
|
-
* ```
|
|
177
|
-
*/
|
|
178
|
-
function memoize(store, factory) {
|
|
179
|
-
return (key) => {
|
|
180
|
-
if (store.has(key)) return store.get(key);
|
|
181
|
-
const value = factory(key);
|
|
182
|
-
store.set(key, value);
|
|
183
|
-
return value;
|
|
184
|
-
};
|
|
185
|
-
}
|
|
186
|
-
//#endregion
|
|
187
6
|
//#region src/signature.ts
|
|
188
7
|
/**
|
|
189
8
|
* The flags shared by every node kind that affect its type: `primitive`, `format`, `nullable`.
|
|
@@ -410,9 +229,9 @@ function describeShape(node) {
|
|
|
410
229
|
return parts.join("|");
|
|
411
230
|
}
|
|
412
231
|
/**
|
|
413
|
-
*
|
|
414
|
-
* hashed during dedupe planning is not walked again when it is rewritten during streaming.
|
|
415
|
-
* is safe because a signature depends only on content, and nodes are immutable once created.
|
|
232
|
+
* Caches the digest per node, keyed by identity. A `WeakMap` so entries die with the node, and so
|
|
233
|
+
* a tree hashed during dedupe planning is not walked again when it is rewritten during streaming.
|
|
234
|
+
* Reuse is safe because a signature depends only on content, and nodes are immutable once created.
|
|
416
235
|
*/
|
|
417
236
|
const signatureCache = /* @__PURE__ */ new WeakMap();
|
|
418
237
|
/**
|
|
@@ -436,1658 +255,208 @@ function signatureOf(node) {
|
|
|
436
255
|
return signature;
|
|
437
256
|
}
|
|
438
257
|
//#endregion
|
|
439
|
-
//#region src/
|
|
440
|
-
/**
|
|
441
|
-
* Definition for the {@link ConstNode}.
|
|
442
|
-
*/
|
|
443
|
-
const constDef = defineNode({ kind: "Const" });
|
|
258
|
+
//#region src/dedupe.ts
|
|
444
259
|
/**
|
|
445
|
-
*
|
|
446
|
-
*
|
|
447
|
-
* @example Exported constant with type and `as const`
|
|
448
|
-
* ```ts
|
|
449
|
-
* createConst({ name: 'pets', export: true, type: 'Pet[]', asConst: true })
|
|
450
|
-
* // export const pets: Pet[] = ... as const
|
|
451
|
-
* ```
|
|
260
|
+
* Builds the shared `ref` replacement for a duplicate occurrence, carrying the
|
|
261
|
+
* usage-slot and documentation fields that are not part of the canonical type.
|
|
452
262
|
*/
|
|
453
|
-
|
|
263
|
+
function createRefNode(node, canonical) {
|
|
264
|
+
return createSchema({
|
|
265
|
+
type: "ref",
|
|
266
|
+
name: canonical.name,
|
|
267
|
+
ref: canonical.ref,
|
|
268
|
+
optional: node.optional,
|
|
269
|
+
nullish: node.nullish,
|
|
270
|
+
readOnly: node.readOnly,
|
|
271
|
+
writeOnly: node.writeOnly,
|
|
272
|
+
deprecated: node.deprecated,
|
|
273
|
+
description: node.description,
|
|
274
|
+
default: node.default,
|
|
275
|
+
example: node.example
|
|
276
|
+
});
|
|
277
|
+
}
|
|
278
|
+
function applyDedupe(node, plan, skipRootMatch = false) {
|
|
279
|
+
const { canonicalBySignature, aliasNames } = plan;
|
|
280
|
+
if (canonicalBySignature.size === 0 && aliasNames.size === 0) return node;
|
|
281
|
+
const root = node;
|
|
282
|
+
return transform(node, { schema(schemaNode) {
|
|
283
|
+
if (schemaNode.type === "ref") {
|
|
284
|
+
const target = schemaNode.ref ? extractRefName(schemaNode.ref) : schemaNode.name;
|
|
285
|
+
const canonical = target ? aliasNames.get(target) : void 0;
|
|
286
|
+
return canonical ? {
|
|
287
|
+
...schemaNode,
|
|
288
|
+
name: canonical.name,
|
|
289
|
+
ref: canonical.ref
|
|
290
|
+
} : void 0;
|
|
291
|
+
}
|
|
292
|
+
const signature = signatureOf(schemaNode);
|
|
293
|
+
if (skipRootMatch && schemaNode === root) return void 0;
|
|
294
|
+
const canonical = canonicalBySignature.get(signature);
|
|
295
|
+
if (!canonical) return void 0;
|
|
296
|
+
return createRefNode(schemaNode, canonical);
|
|
297
|
+
} });
|
|
298
|
+
}
|
|
454
299
|
/**
|
|
455
|
-
*
|
|
300
|
+
* Strips usage-slot flags from a hoisted definition and applies its canonical name.
|
|
301
|
+
* A standalone definition is never optional, so `optional`/`nullish` are cleared.
|
|
456
302
|
*/
|
|
457
|
-
|
|
303
|
+
function cleanDefinition(node, name) {
|
|
304
|
+
return {
|
|
305
|
+
...node,
|
|
306
|
+
name,
|
|
307
|
+
optional: void 0,
|
|
308
|
+
nullish: void 0
|
|
309
|
+
};
|
|
310
|
+
}
|
|
458
311
|
/**
|
|
459
|
-
*
|
|
312
|
+
* Scans a forest of schema and operation nodes and produces a {@link DedupePlan}.
|
|
460
313
|
*
|
|
461
|
-
*
|
|
462
|
-
*
|
|
463
|
-
*
|
|
464
|
-
*
|
|
465
|
-
*
|
|
466
|
-
|
|
467
|
-
const createType = typeDef.create;
|
|
468
|
-
/**
|
|
469
|
-
* Definition for the {@link FunctionNode}.
|
|
470
|
-
*/
|
|
471
|
-
const functionDef = defineNode({ kind: "Function" });
|
|
472
|
-
/**
|
|
473
|
-
* Creates a `FunctionNode` representing a TypeScript `function` declaration.
|
|
314
|
+
* A shape that occurs at least `minOccurrences` times is deduplicated: if any occurrence
|
|
315
|
+
* is a named top-level schema, the first one becomes the canonical (so other top-level
|
|
316
|
+
* duplicates and inline copies turn into references to it). Every other top-level name with
|
|
317
|
+
* the same content is recorded in `aliasNames`, so refs to it can be repointed at the
|
|
318
|
+
* canonical. Otherwise a new definition is hoisted using `nameFor`. The plan is then applied
|
|
319
|
+
* per node with {@link applyDedupe}.
|
|
474
320
|
*
|
|
475
321
|
* @example
|
|
476
322
|
* ```ts
|
|
477
|
-
*
|
|
478
|
-
*
|
|
323
|
+
* const plan = buildDedupePlan([...schemaNodes, ...operationNodes], {
|
|
324
|
+
* isCandidate: (node) => node.type === 'enum' || node.type === 'object',
|
|
325
|
+
* nameFor: (node) => node.name ?? null,
|
|
326
|
+
* refFor: (name) => `#/components/schemas/${name}`,
|
|
327
|
+
* })
|
|
479
328
|
* ```
|
|
480
329
|
*/
|
|
481
|
-
|
|
482
|
-
|
|
483
|
-
|
|
484
|
-
*/
|
|
485
|
-
|
|
330
|
+
function buildDedupePlan(roots, options) {
|
|
331
|
+
const { isCandidate, nameFor, refFor, minOccurrences = 2 } = options;
|
|
332
|
+
const topLevelNodes = /* @__PURE__ */ new Set();
|
|
333
|
+
const groups = /* @__PURE__ */ new Map();
|
|
334
|
+
function record(schemaNode) {
|
|
335
|
+
const signature = signatureOf(schemaNode);
|
|
336
|
+
if (!isCandidate(schemaNode)) return;
|
|
337
|
+
const isTopLevel = topLevelNodes.has(schemaNode) && !!schemaNode.name;
|
|
338
|
+
const group = groups.get(signature);
|
|
339
|
+
if (group) {
|
|
340
|
+
group.count++;
|
|
341
|
+
if (isTopLevel) group.topLevelNames.push(schemaNode.name);
|
|
342
|
+
} else groups.set(signature, {
|
|
343
|
+
count: 1,
|
|
344
|
+
representative: schemaNode,
|
|
345
|
+
topLevelNames: isTopLevel ? [schemaNode.name] : []
|
|
346
|
+
});
|
|
347
|
+
}
|
|
348
|
+
for (const root of roots) {
|
|
349
|
+
if (root.kind === "Schema") topLevelNodes.add(root);
|
|
350
|
+
for (const schemaNode of collectLazy(root, { schema: (node) => node })) record(schemaNode);
|
|
351
|
+
}
|
|
352
|
+
const canonicalBySignature = /* @__PURE__ */ new Map();
|
|
353
|
+
const aliasNames = /* @__PURE__ */ new Map();
|
|
354
|
+
const pendingHoists = [];
|
|
355
|
+
for (const [signature, group] of groups) {
|
|
356
|
+
if (group.count < minOccurrences) continue;
|
|
357
|
+
const [firstName, ...duplicateNames] = group.topLevelNames;
|
|
358
|
+
if (firstName) {
|
|
359
|
+
const canonical = {
|
|
360
|
+
name: firstName,
|
|
361
|
+
ref: refFor(firstName)
|
|
362
|
+
};
|
|
363
|
+
canonicalBySignature.set(signature, canonical);
|
|
364
|
+
for (const duplicate of duplicateNames) aliasNames.set(duplicate, canonical);
|
|
365
|
+
continue;
|
|
366
|
+
}
|
|
367
|
+
const name = nameFor(group.representative, signature);
|
|
368
|
+
if (!name) continue;
|
|
369
|
+
canonicalBySignature.set(signature, {
|
|
370
|
+
name,
|
|
371
|
+
ref: refFor(name)
|
|
372
|
+
});
|
|
373
|
+
pendingHoists.push({
|
|
374
|
+
name,
|
|
375
|
+
representative: group.representative
|
|
376
|
+
});
|
|
377
|
+
}
|
|
378
|
+
return {
|
|
379
|
+
canonicalBySignature,
|
|
380
|
+
aliasNames,
|
|
381
|
+
hoisted: pendingHoists.map(({ name, representative }) => cleanDefinition(applyDedupe(representative, {
|
|
382
|
+
canonicalBySignature,
|
|
383
|
+
aliasNames
|
|
384
|
+
}, true), name))
|
|
385
|
+
};
|
|
386
|
+
}
|
|
387
|
+
//#endregion
|
|
388
|
+
//#region src/dialect.ts
|
|
486
389
|
/**
|
|
487
|
-
*
|
|
390
|
+
* Types a {@link SchemaDialect} for an adapter. Adds no runtime behavior and only pins the
|
|
391
|
+
* dialect's type for inference.
|
|
488
392
|
*
|
|
489
393
|
* @example
|
|
490
394
|
* ```ts
|
|
491
|
-
*
|
|
492
|
-
*
|
|
395
|
+
* export const oasDialect = defineSchemaDialect({
|
|
396
|
+
* name: 'oas',
|
|
397
|
+
* isNullable,
|
|
398
|
+
* isReference,
|
|
399
|
+
* isDiscriminator,
|
|
400
|
+
* isBinary: (schema) => schema.type === 'string' && schema.contentMediaType === 'application/octet-stream',
|
|
401
|
+
* resolveRef,
|
|
402
|
+
* })
|
|
493
403
|
* ```
|
|
494
404
|
*/
|
|
495
|
-
|
|
496
|
-
|
|
497
|
-
|
|
498
|
-
|
|
499
|
-
|
|
500
|
-
kind: "Text",
|
|
501
|
-
build: (value) => ({ value })
|
|
502
|
-
});
|
|
405
|
+
function defineSchemaDialect(dialect) {
|
|
406
|
+
return dialect;
|
|
407
|
+
}
|
|
408
|
+
//#endregion
|
|
409
|
+
//#region src/printer.ts
|
|
503
410
|
/**
|
|
504
|
-
*
|
|
411
|
+
* Defines a schema printer: a function that takes a `SchemaNode` and emits
|
|
412
|
+
* code in your target language. Each plugin that produces code from schemas
|
|
413
|
+
* (TypeScript types, Zod schemas, Faker factories) ships a printer built
|
|
414
|
+
* with this helper.
|
|
505
415
|
*
|
|
506
|
-
*
|
|
507
|
-
* ```ts
|
|
508
|
-
* createText('return fetch(id)')
|
|
509
|
-
* // { kind: 'Text', value: 'return fetch(id)' }
|
|
510
|
-
* ```
|
|
511
|
-
*/
|
|
512
|
-
const createText = textDef.create;
|
|
513
|
-
/**
|
|
514
|
-
* Definition for the {@link BreakNode}.
|
|
515
|
-
*/
|
|
516
|
-
const breakDef = defineNode({
|
|
517
|
-
kind: "Break",
|
|
518
|
-
build: () => ({})
|
|
519
|
-
});
|
|
520
|
-
/**
|
|
521
|
-
* Creates a {@link BreakNode} representing a line break in the source output.
|
|
416
|
+
* The builder receives resolved options and returns:
|
|
522
417
|
*
|
|
523
|
-
*
|
|
418
|
+
* - `name` unique identifier for the printer.
|
|
419
|
+
* - `options` stored on the returned printer instance.
|
|
420
|
+
* - `nodes` map of `SchemaType` → handler. Handlers return the rendered
|
|
421
|
+
* output (a string, a TypeScript AST node, ...) for that schema type.
|
|
422
|
+
* - `print` (optional), top-level override exposed as `printer.print`.
|
|
423
|
+
* Use `this.transform(node)` inside it to dispatch to `nodes` recursively.
|
|
424
|
+
*
|
|
425
|
+
* Without a `print` override, `printer.print` falls back to `printer.transform`
|
|
426
|
+
* (the node-level dispatcher).
|
|
427
|
+
*
|
|
428
|
+
* @example Tiny Zod printer
|
|
524
429
|
* ```ts
|
|
525
|
-
*
|
|
526
|
-
*
|
|
430
|
+
* import { definePrinter, type PrinterFactoryOptions } from '@kubb/ast'
|
|
431
|
+
*
|
|
432
|
+
* type PrinterZod = PrinterFactoryOptions<'zod', { strict?: boolean }, string>
|
|
433
|
+
*
|
|
434
|
+
* export const zodPrinter = definePrinter<PrinterZod>((options) => ({
|
|
435
|
+
* name: 'zod',
|
|
436
|
+
* options: { strict: options.strict ?? true },
|
|
437
|
+
* nodes: {
|
|
438
|
+
* string: () => 'z.string()',
|
|
439
|
+
* object(node) {
|
|
440
|
+
* const props = node.properties
|
|
441
|
+
* .map((p) => `${p.name}: ${this.transform(p.schema)}`)
|
|
442
|
+
* .join(', ')
|
|
443
|
+
* return `z.object({ ${props} })`
|
|
444
|
+
* },
|
|
445
|
+
* },
|
|
446
|
+
* }))
|
|
527
447
|
* ```
|
|
528
448
|
*/
|
|
529
|
-
function
|
|
530
|
-
return
|
|
449
|
+
function definePrinter(build) {
|
|
450
|
+
return createPrinterFactory((node) => node.type)(build);
|
|
531
451
|
}
|
|
532
452
|
/**
|
|
533
|
-
*
|
|
534
|
-
*/
|
|
535
|
-
const jsxDef = defineNode({
|
|
536
|
-
kind: "Jsx",
|
|
537
|
-
build: (value) => ({ value })
|
|
538
|
-
});
|
|
539
|
-
/**
|
|
540
|
-
* Creates a {@link JsxNode} representing a raw JSX fragment in the source output.
|
|
453
|
+
* Generic printer-factory function used by `definePrinter` and `defineFunctionPrinter`.
|
|
541
454
|
*
|
|
542
455
|
* @example
|
|
543
456
|
* ```ts
|
|
544
|
-
*
|
|
545
|
-
*
|
|
546
|
-
*
|
|
547
|
-
*/
|
|
548
|
-
const createJsx = jsxDef.create;
|
|
549
|
-
//#endregion
|
|
550
|
-
//#region src/nodes/content.ts
|
|
551
|
-
/**
|
|
552
|
-
* Definition for the {@link ContentNode}.
|
|
553
|
-
*/
|
|
554
|
-
const contentDef = defineNode({
|
|
555
|
-
kind: "Content",
|
|
556
|
-
children: ["schema"]
|
|
557
|
-
});
|
|
558
|
-
/**
|
|
559
|
-
* Creates a `ContentNode` for a single request-body or response content type.
|
|
560
|
-
*/
|
|
561
|
-
const createContent = contentDef.create;
|
|
562
|
-
//#endregion
|
|
563
|
-
//#region src/nodes/file.ts
|
|
564
|
-
/**
|
|
565
|
-
* Definition for the {@link ImportNode}.
|
|
566
|
-
*/
|
|
567
|
-
const importDef = defineNode({ kind: "Import" });
|
|
568
|
-
/**
|
|
569
|
-
* Creates an `ImportNode` representing a language-agnostic import/dependency declaration.
|
|
570
|
-
*
|
|
571
|
-
* @example Named import
|
|
572
|
-
* ```ts
|
|
573
|
-
* createImport({ name: ['useState'], path: 'react' })
|
|
574
|
-
* // import { useState } from 'react'
|
|
575
|
-
* ```
|
|
576
|
-
*/
|
|
577
|
-
const createImport = importDef.create;
|
|
578
|
-
/**
|
|
579
|
-
* Definition for the {@link ExportNode}.
|
|
580
|
-
*/
|
|
581
|
-
const exportDef = defineNode({ kind: "Export" });
|
|
582
|
-
/**
|
|
583
|
-
* Creates an `ExportNode` representing a language-agnostic export/public API declaration.
|
|
584
|
-
*
|
|
585
|
-
* @example Named export
|
|
586
|
-
* ```ts
|
|
587
|
-
* createExport({ name: ['Pet'], path: './Pet' })
|
|
588
|
-
* // export { Pet } from './Pet'
|
|
589
|
-
* ```
|
|
590
|
-
*/
|
|
591
|
-
const createExport = exportDef.create;
|
|
592
|
-
/**
|
|
593
|
-
* Definition for the {@link SourceNode}.
|
|
594
|
-
*/
|
|
595
|
-
const sourceDef = defineNode({ kind: "Source" });
|
|
596
|
-
/**
|
|
597
|
-
* Creates a `SourceNode` representing a fragment of source code within a file.
|
|
598
|
-
*
|
|
599
|
-
* @example
|
|
600
|
-
* ```ts
|
|
601
|
-
* createSource({ name: 'Pet', nodes: [createText('export type Pet = { id: number }')], isExportable: true })
|
|
602
|
-
* ```
|
|
603
|
-
*/
|
|
604
|
-
const createSource = sourceDef.create;
|
|
605
|
-
/**
|
|
606
|
-
* Definition for the {@link FileNode}. The fully resolved builder lives in
|
|
607
|
-
* `createFile`, so this definition only supplies the guard.
|
|
608
|
-
*/
|
|
609
|
-
const fileDef = defineNode({ kind: "File" });
|
|
610
|
-
//#endregion
|
|
611
|
-
//#region src/nodes/function.ts
|
|
612
|
-
/**
|
|
613
|
-
* Definition for the {@link TypeLiteralNode}.
|
|
614
|
-
*/
|
|
615
|
-
const typeLiteralDef = defineNode({ kind: "TypeLiteral" });
|
|
616
|
-
/**
|
|
617
|
-
* Creates a {@link TypeLiteralNode} representing an inline anonymous object type.
|
|
618
|
-
*
|
|
619
|
-
* @example
|
|
620
|
-
* ```ts
|
|
621
|
-
* createTypeLiteral({ members: [{ name: 'petId', type: 'string', optional: false }] })
|
|
622
|
-
* // { petId: string }
|
|
623
|
-
* ```
|
|
624
|
-
*/
|
|
625
|
-
const createTypeLiteral = typeLiteralDef.create;
|
|
626
|
-
/**
|
|
627
|
-
* Definition for the {@link IndexedAccessTypeNode}.
|
|
628
|
-
*/
|
|
629
|
-
const indexedAccessTypeDef = defineNode({ kind: "IndexedAccessType" });
|
|
630
|
-
/**
|
|
631
|
-
* Creates an {@link IndexedAccessTypeNode} representing a single field accessed from a named type.
|
|
632
|
-
*
|
|
633
|
-
* @example
|
|
634
|
-
* ```ts
|
|
635
|
-
* createIndexedAccessType({ objectType: 'DeletePetPathParams', indexType: 'petId' })
|
|
636
|
-
* // DeletePetPathParams['petId']
|
|
637
|
-
* ```
|
|
638
|
-
*/
|
|
639
|
-
const createIndexedAccessType = indexedAccessTypeDef.create;
|
|
640
|
-
/**
|
|
641
|
-
* Definition for the {@link ObjectBindingPatternNode}.
|
|
642
|
-
*/
|
|
643
|
-
const objectBindingPatternDef = defineNode({ kind: "ObjectBindingPattern" });
|
|
644
|
-
/**
|
|
645
|
-
* Creates an {@link ObjectBindingPatternNode} for a destructured parameter binding.
|
|
646
|
-
*
|
|
647
|
-
* @example
|
|
648
|
-
* ```ts
|
|
649
|
-
* createObjectBindingPattern({ elements: [{ name: 'id' }, { name: 'name' }] })
|
|
650
|
-
* // { id, name }
|
|
651
|
-
* ```
|
|
652
|
-
*/
|
|
653
|
-
const createObjectBindingPattern = objectBindingPatternDef.create;
|
|
654
|
-
/**
|
|
655
|
-
* Definition for the {@link FunctionParameterNode}. `optional` defaults to `false`.
|
|
656
|
-
* Passing `properties` builds a destructured group: an {@link ObjectBindingPatternNode} name
|
|
657
|
-
* paired with a {@link TypeLiteralNode} type.
|
|
658
|
-
*/
|
|
659
|
-
const functionParameterDef = defineNode({
|
|
660
|
-
kind: "FunctionParameter",
|
|
661
|
-
build: (input) => {
|
|
662
|
-
if ("properties" in input) return {
|
|
663
|
-
name: createObjectBindingPattern({ elements: input.properties.map((p) => ({ name: p.name })) }),
|
|
664
|
-
type: createTypeLiteral({ members: input.properties.map((p) => ({
|
|
665
|
-
name: p.name,
|
|
666
|
-
type: p.type,
|
|
667
|
-
optional: p.optional ?? false
|
|
668
|
-
})) }),
|
|
669
|
-
optional: input.optional ?? false,
|
|
670
|
-
...input.default !== void 0 ? { default: input.default } : {}
|
|
671
|
-
};
|
|
672
|
-
return {
|
|
673
|
-
optional: false,
|
|
674
|
-
...input
|
|
675
|
-
};
|
|
676
|
-
}
|
|
677
|
-
});
|
|
678
|
-
/**
|
|
679
|
-
* Creates a `FunctionParameterNode`. `optional` defaults to `false`.
|
|
680
|
-
*
|
|
681
|
-
* @example Optional param
|
|
682
|
-
* ```ts
|
|
683
|
-
* createFunctionParameter({ name: 'params', type: 'QueryParams', optional: true })
|
|
684
|
-
* // → params?: QueryParams
|
|
685
|
-
* ```
|
|
686
|
-
*
|
|
687
|
-
* @example Destructured group
|
|
688
|
-
* ```ts
|
|
689
|
-
* createFunctionParameter({ properties: [{ name: 'id', type: 'string' }, { name: 'name', type: 'string', optional: true }], default: '{}' })
|
|
690
|
-
* // → { id, name }: { id: string; name?: string } = {}
|
|
691
|
-
* ```
|
|
692
|
-
*/
|
|
693
|
-
const createFunctionParameter = functionParameterDef.create;
|
|
694
|
-
/**
|
|
695
|
-
* Definition for the {@link FunctionParametersNode}.
|
|
696
|
-
*/
|
|
697
|
-
const functionParametersDef = defineNode({
|
|
698
|
-
kind: "FunctionParameters",
|
|
699
|
-
defaults: { params: [] }
|
|
700
|
-
});
|
|
701
|
-
/**
|
|
702
|
-
* Creates a `FunctionParametersNode` from an ordered list of parameters.
|
|
703
|
-
*
|
|
704
|
-
* @example
|
|
705
|
-
* ```ts
|
|
706
|
-
* const empty = createFunctionParameters()
|
|
707
|
-
* // { kind: 'FunctionParameters', params: [] }
|
|
708
|
-
* ```
|
|
709
|
-
*/
|
|
710
|
-
function createFunctionParameters(props = {}) {
|
|
711
|
-
return functionParametersDef.create(props);
|
|
712
|
-
}
|
|
713
|
-
//#endregion
|
|
714
|
-
//#region src/nodes/input.ts
|
|
715
|
-
/**
|
|
716
|
-
* Definition for the {@link InputNode}.
|
|
717
|
-
*/
|
|
718
|
-
const inputDef = defineNode({
|
|
719
|
-
kind: "Input",
|
|
720
|
-
defaults: {
|
|
721
|
-
schemas: [],
|
|
722
|
-
operations: [],
|
|
723
|
-
meta: {
|
|
724
|
-
circularNames: [],
|
|
725
|
-
enumNames: []
|
|
726
|
-
}
|
|
727
|
-
},
|
|
728
|
-
children: ["schemas", "operations"],
|
|
729
|
-
visitorKey: "input"
|
|
730
|
-
});
|
|
731
|
-
/**
|
|
732
|
-
* Creates an `InputNode` with stable defaults for `schemas` and `operations`.
|
|
733
|
-
*
|
|
734
|
-
* @example
|
|
735
|
-
* ```ts
|
|
736
|
-
* const input = createInput()
|
|
737
|
-
* // { kind: 'Input', schemas: [], operations: [] }
|
|
738
|
-
* ```
|
|
739
|
-
*/
|
|
740
|
-
function createInput(overrides = {}) {
|
|
741
|
-
return inputDef.create(overrides);
|
|
742
|
-
}
|
|
743
|
-
/**
|
|
744
|
-
* Creates a streaming `InputNode<true>` from pre-built `AsyncIterable` sources.
|
|
745
|
-
*
|
|
746
|
-
* @example
|
|
747
|
-
* ```ts
|
|
748
|
-
* const node = createStreamInput(schemasIterable, operationsIterable, { title: 'My API' })
|
|
749
|
-
* ```
|
|
750
|
-
*/
|
|
751
|
-
function createStreamInput(schemas, operations, meta) {
|
|
752
|
-
return {
|
|
753
|
-
kind: "Input",
|
|
754
|
-
schemas,
|
|
755
|
-
operations,
|
|
756
|
-
meta
|
|
757
|
-
};
|
|
758
|
-
}
|
|
759
|
-
//#endregion
|
|
760
|
-
//#region src/nodes/requestBody.ts
|
|
761
|
-
/**
|
|
762
|
-
* Definition for the {@link RequestBodyNode}, normalizing each content entry into a `ContentNode`.
|
|
763
|
-
*/
|
|
764
|
-
const requestBodyDef = defineNode({
|
|
765
|
-
kind: "RequestBody",
|
|
766
|
-
build: (props) => ({
|
|
767
|
-
...props,
|
|
768
|
-
content: props.content?.map(createContent)
|
|
769
|
-
}),
|
|
770
|
-
children: ["content"]
|
|
771
|
-
});
|
|
772
|
-
/**
|
|
773
|
-
* Creates a `RequestBodyNode`, normalizing each content entry into a `ContentNode`.
|
|
774
|
-
*/
|
|
775
|
-
const createRequestBody = requestBodyDef.create;
|
|
776
|
-
//#endregion
|
|
777
|
-
//#region src/nodes/operation.ts
|
|
778
|
-
/**
|
|
779
|
-
* Definition for the {@link OperationNode}. HTTP operations (those carrying both
|
|
780
|
-
* `method` and `path`) are tagged with `protocol: 'http'`, and the request body is
|
|
781
|
-
* normalized into a `RequestBodyNode`.
|
|
782
|
-
*/
|
|
783
|
-
const operationDef = defineNode({
|
|
784
|
-
kind: "Operation",
|
|
785
|
-
build: (props) => {
|
|
786
|
-
const { requestBody, ...rest } = props;
|
|
787
|
-
const isHttp = rest.method !== void 0 && rest.path !== void 0;
|
|
788
|
-
return {
|
|
789
|
-
tags: [],
|
|
790
|
-
parameters: [],
|
|
791
|
-
responses: [],
|
|
792
|
-
...rest,
|
|
793
|
-
...isHttp ? { protocol: "http" } : {},
|
|
794
|
-
requestBody: requestBody ? createRequestBody(requestBody) : void 0
|
|
795
|
-
};
|
|
796
|
-
},
|
|
797
|
-
children: [
|
|
798
|
-
"parameters",
|
|
799
|
-
"requestBody",
|
|
800
|
-
"responses"
|
|
801
|
-
],
|
|
802
|
-
visitorKey: "operation"
|
|
803
|
-
});
|
|
804
|
-
function createOperation(props) {
|
|
805
|
-
return operationDef.create(props);
|
|
806
|
-
}
|
|
807
|
-
//#endregion
|
|
808
|
-
//#region src/nodes/output.ts
|
|
809
|
-
/**
|
|
810
|
-
* Definition for the {@link OutputNode}.
|
|
811
|
-
*/
|
|
812
|
-
const outputDef = defineNode({
|
|
813
|
-
kind: "Output",
|
|
814
|
-
defaults: { files: [] },
|
|
815
|
-
visitorKey: "output"
|
|
816
|
-
});
|
|
817
|
-
/**
|
|
818
|
-
* Creates an `OutputNode` with a stable default for `files`.
|
|
819
|
-
*
|
|
820
|
-
* @example
|
|
821
|
-
* ```ts
|
|
822
|
-
* const output = createOutput()
|
|
823
|
-
* // { kind: 'Output', files: [] }
|
|
824
|
-
* ```
|
|
825
|
-
*/
|
|
826
|
-
function createOutput(overrides = {}) {
|
|
827
|
-
return outputDef.create(overrides);
|
|
828
|
-
}
|
|
829
|
-
//#endregion
|
|
830
|
-
//#region src/nodes/parameter.ts
|
|
831
|
-
/**
|
|
832
|
-
* Definition for the {@link ParameterNode}. `required` defaults to `false` and the
|
|
833
|
-
* schema's `optional`/`nullish` flags are kept in sync with it.
|
|
834
|
-
*/
|
|
835
|
-
const parameterDef = defineNode({
|
|
836
|
-
kind: "Parameter",
|
|
837
|
-
build: (props) => {
|
|
838
|
-
const required = props.required ?? false;
|
|
839
|
-
return {
|
|
840
|
-
...props,
|
|
841
|
-
required,
|
|
842
|
-
schema: syncOptionality(props.schema, required)
|
|
843
|
-
};
|
|
844
|
-
},
|
|
845
|
-
children: ["schema"],
|
|
846
|
-
visitorKey: "parameter",
|
|
847
|
-
rebuild: true
|
|
848
|
-
});
|
|
849
|
-
/**
|
|
850
|
-
* Creates a `ParameterNode`.
|
|
851
|
-
*
|
|
852
|
-
* @example
|
|
853
|
-
* ```ts
|
|
854
|
-
* const param = createParameter({
|
|
855
|
-
* name: 'petId',
|
|
856
|
-
* in: 'path',
|
|
857
|
-
* required: true,
|
|
858
|
-
* schema: createSchema({ type: 'string' }),
|
|
859
|
-
* })
|
|
860
|
-
* ```
|
|
861
|
-
*/
|
|
862
|
-
const createParameter = parameterDef.create;
|
|
863
|
-
//#endregion
|
|
864
|
-
//#region src/nodes/property.ts
|
|
865
|
-
/**
|
|
866
|
-
* Definition for the {@link PropertyNode}. `required` defaults to `false` and the
|
|
867
|
-
* schema's `optional`/`nullish` flags are kept in sync with it.
|
|
868
|
-
*/
|
|
869
|
-
const propertyDef = defineNode({
|
|
870
|
-
kind: "Property",
|
|
871
|
-
build: (props) => {
|
|
872
|
-
const required = props.required ?? false;
|
|
873
|
-
return {
|
|
874
|
-
...props,
|
|
875
|
-
required,
|
|
876
|
-
schema: syncOptionality(props.schema, required)
|
|
877
|
-
};
|
|
878
|
-
},
|
|
879
|
-
children: ["schema"],
|
|
880
|
-
visitorKey: "property",
|
|
881
|
-
rebuild: true
|
|
882
|
-
});
|
|
883
|
-
/**
|
|
884
|
-
* Creates a `PropertyNode`.
|
|
885
|
-
*
|
|
886
|
-
* @example
|
|
887
|
-
* ```ts
|
|
888
|
-
* const property = createProperty({
|
|
889
|
-
* name: 'status',
|
|
890
|
-
* required: true,
|
|
891
|
-
* schema: createSchema({ type: 'string', nullable: true }),
|
|
892
|
-
* })
|
|
893
|
-
* // required=true, no optional/nullish
|
|
894
|
-
* ```
|
|
895
|
-
*/
|
|
896
|
-
const createProperty = propertyDef.create;
|
|
897
|
-
//#endregion
|
|
898
|
-
//#region src/nodes/response.ts
|
|
899
|
-
/**
|
|
900
|
-
* Definition for the {@link ResponseNode}. A single legacy `schema` (with optional
|
|
901
|
-
* `mediaType`/`keysToOmit`) is normalized into one `content` entry.
|
|
902
|
-
*/
|
|
903
|
-
const responseDef = defineNode({
|
|
904
|
-
kind: "Response",
|
|
905
|
-
build: (props) => {
|
|
906
|
-
const { schema, mediaType, keysToOmit, content, ...rest } = props;
|
|
907
|
-
const entries = content ?? (schema ? [{
|
|
908
|
-
contentType: mediaType ?? "application/json",
|
|
909
|
-
schema,
|
|
910
|
-
keysToOmit: keysToOmit ?? null
|
|
911
|
-
}] : void 0);
|
|
912
|
-
return {
|
|
913
|
-
...rest,
|
|
914
|
-
content: entries?.map(createContent)
|
|
915
|
-
};
|
|
916
|
-
},
|
|
917
|
-
children: ["content"],
|
|
918
|
-
visitorKey: "response"
|
|
919
|
-
});
|
|
920
|
-
/**
|
|
921
|
-
* Creates a `ResponseNode`.
|
|
922
|
-
*
|
|
923
|
-
* @example
|
|
924
|
-
* ```ts
|
|
925
|
-
* const response = createResponse({
|
|
926
|
-
* statusCode: '200',
|
|
927
|
-
* content: [{ contentType: 'application/json', schema: createSchema({ type: 'object', properties: [] }) }],
|
|
928
|
-
* })
|
|
929
|
-
* ```
|
|
930
|
-
*/
|
|
931
|
-
const createResponse = responseDef.create;
|
|
932
|
-
//#endregion
|
|
933
|
-
//#region src/registry.ts
|
|
934
|
-
/**
|
|
935
|
-
* Every node definition. Adding a node means adding its `defineNode` to one
|
|
936
|
-
* `nodes/*.ts` file and listing it here. The visitor tables below derive from it.
|
|
937
|
-
*/
|
|
938
|
-
const nodeDefs = [
|
|
939
|
-
inputDef,
|
|
940
|
-
outputDef,
|
|
941
|
-
operationDef,
|
|
942
|
-
requestBodyDef,
|
|
943
|
-
contentDef,
|
|
944
|
-
responseDef,
|
|
945
|
-
schemaDef,
|
|
946
|
-
propertyDef,
|
|
947
|
-
parameterDef,
|
|
948
|
-
functionParameterDef,
|
|
949
|
-
functionParametersDef,
|
|
950
|
-
typeLiteralDef,
|
|
951
|
-
indexedAccessTypeDef,
|
|
952
|
-
objectBindingPatternDef,
|
|
953
|
-
constDef,
|
|
954
|
-
typeDef,
|
|
955
|
-
functionDef,
|
|
956
|
-
arrowFunctionDef,
|
|
957
|
-
textDef,
|
|
958
|
-
breakDef,
|
|
959
|
-
jsxDef,
|
|
960
|
-
importDef,
|
|
961
|
-
exportDef,
|
|
962
|
-
sourceDef,
|
|
963
|
-
fileDef
|
|
964
|
-
];
|
|
965
|
-
/**
|
|
966
|
-
* Child node fields per node kind, in traversal order (Babel's `VISITOR_KEYS`).
|
|
967
|
-
* Derived from each definition's `children`.
|
|
968
|
-
*/
|
|
969
|
-
const VISITOR_KEYS = Object.fromEntries(nodeDefs.flatMap((def) => def.children ? [[def.kind, def.children]] : []));
|
|
970
|
-
/**
|
|
971
|
-
* Maps a node kind to the matching visitor callback name. Derived from each
|
|
972
|
-
* definition's `visitorKey`.
|
|
973
|
-
*/
|
|
974
|
-
const VISITOR_KEY_BY_KIND = Object.fromEntries(nodeDefs.flatMap((def) => def.visitorKey ? [[def.kind, def.visitorKey]] : []));
|
|
975
|
-
/**
|
|
976
|
-
* Per-kind builders rerun after children are rebuilt. Derived from each
|
|
977
|
-
* definition's `rebuild` flag.
|
|
978
|
-
*/
|
|
979
|
-
const nodeRebuilders = Object.fromEntries(nodeDefs.flatMap((def) => def.rebuild ? [[def.kind, def.create]] : []));
|
|
980
|
-
//#endregion
|
|
981
|
-
//#region src/visitor.ts
|
|
982
|
-
/**
|
|
983
|
-
* Creates a small async concurrency limiter.
|
|
984
|
-
*
|
|
985
|
-
* At most `concurrency` tasks are in flight at once. Extra tasks are queued.
|
|
986
|
-
*
|
|
987
|
-
* @example
|
|
988
|
-
* ```ts
|
|
989
|
-
* const limit = createLimit(2)
|
|
990
|
-
* for (const task of [taskA, taskB, taskC]) {
|
|
991
|
-
* await limit(() => task())
|
|
992
|
-
* }
|
|
993
|
-
* // only 2 tasks run at the same time
|
|
994
|
-
* ```
|
|
995
|
-
*/
|
|
996
|
-
function createLimit(concurrency) {
|
|
997
|
-
let active = 0;
|
|
998
|
-
const queue = [];
|
|
999
|
-
function next() {
|
|
1000
|
-
if (active < concurrency && queue.length > 0) {
|
|
1001
|
-
active++;
|
|
1002
|
-
queue.shift()();
|
|
1003
|
-
}
|
|
1004
|
-
}
|
|
1005
|
-
return function limit(fn) {
|
|
1006
|
-
return new Promise((resolve, reject) => {
|
|
1007
|
-
queue.push(() => {
|
|
1008
|
-
Promise.resolve(fn()).then(resolve, reject).finally(() => {
|
|
1009
|
-
active--;
|
|
1010
|
-
next();
|
|
1011
|
-
});
|
|
1012
|
-
});
|
|
1013
|
-
next();
|
|
1014
|
-
});
|
|
1015
|
-
};
|
|
1016
|
-
}
|
|
1017
|
-
const visitorKeysByKind = VISITOR_KEYS;
|
|
1018
|
-
/**
|
|
1019
|
-
* Returns `true` when `value` is an AST node (an object carrying a `kind`).
|
|
1020
|
-
*/
|
|
1021
|
-
function isNode(value) {
|
|
1022
|
-
return typeof value === "object" && value !== null && "kind" in value;
|
|
1023
|
-
}
|
|
1024
|
-
/**
|
|
1025
|
-
* Returns the immediate traversable children of `node` based on {@link VISITOR_KEYS}.
|
|
1026
|
-
*
|
|
1027
|
-
* `Schema` children are only included when `recurse` is `true`. Shallow mode skips them.
|
|
1028
|
-
*
|
|
1029
|
-
* @example
|
|
1030
|
-
* ```ts
|
|
1031
|
-
* const children = getChildren(operationNode, true)
|
|
1032
|
-
* // returns parameters, the request body, and responses
|
|
1033
|
-
* ```
|
|
1034
|
-
*/
|
|
1035
|
-
function* getChildren(node, recurse) {
|
|
1036
|
-
if (node.kind === "Schema" && !recurse) return;
|
|
1037
|
-
const keys = visitorKeysByKind[node.kind];
|
|
1038
|
-
if (!keys) return;
|
|
1039
|
-
const record = node;
|
|
1040
|
-
for (const key of keys) {
|
|
1041
|
-
const value = record[key];
|
|
1042
|
-
if (Array.isArray(value)) {
|
|
1043
|
-
for (const item of value) if (isNode(item)) yield item;
|
|
1044
|
-
} else if (isNode(value)) yield value;
|
|
1045
|
-
}
|
|
1046
|
-
}
|
|
1047
|
-
/**
|
|
1048
|
-
* Invokes the visitor callback that matches `node.kind`, passing the traversal
|
|
1049
|
-
* context. Returns the callback's result (a replacement node, a collected
|
|
1050
|
-
* value, or `undefined` when no callback is registered for the kind).
|
|
1051
|
-
*
|
|
1052
|
-
* Shared by `walk`, `transform`, and `collectLazy` so node-kind dispatch lives
|
|
1053
|
-
* in one place. `TResult` is the caller's expected return: the same node type
|
|
1054
|
-
* for `transform`, the collected value type for `collectLazy`, ignored for `walk`.
|
|
1055
|
-
*/
|
|
1056
|
-
function applyVisitor(node, visitor, parent) {
|
|
1057
|
-
const key = VISITOR_KEY_BY_KIND[node.kind];
|
|
1058
|
-
if (!key) return void 0;
|
|
1059
|
-
const fn = visitor[key];
|
|
1060
|
-
return fn?.(node, { parent });
|
|
1061
|
-
}
|
|
1062
|
-
/**
|
|
1063
|
-
* Async depth-first traversal for side effects. Visitor return values are
|
|
1064
|
-
* ignored. Use `transform` when you want to rewrite nodes.
|
|
1065
|
-
*
|
|
1066
|
-
* Sibling nodes at each depth run concurrently up to `options.concurrency`
|
|
1067
|
-
* (defaults to `WALK_CONCURRENCY`). Higher values overlap I/O-bound visitor
|
|
1068
|
-
* work. Lower values reduce memory pressure.
|
|
1069
|
-
*
|
|
1070
|
-
* @example Log every operation
|
|
1071
|
-
* ```ts
|
|
1072
|
-
* await walk(root, {
|
|
1073
|
-
* operation(node) {
|
|
1074
|
-
* console.log(node.operationId)
|
|
1075
|
-
* },
|
|
1076
|
-
* })
|
|
1077
|
-
* ```
|
|
1078
|
-
*
|
|
1079
|
-
* @example Only visit the root node
|
|
1080
|
-
* ```ts
|
|
1081
|
-
* await walk(root, { depth: 'shallow', input: () => {} })
|
|
1082
|
-
* ```
|
|
1083
|
-
*/
|
|
1084
|
-
async function walk(node, options) {
|
|
1085
|
-
return _walk(node, options, (options.depth ?? visitorDepths.deep) === visitorDepths.deep, createLimit(options.concurrency ?? 30), void 0);
|
|
1086
|
-
}
|
|
1087
|
-
async function _walk(node, visitor, recurse, limit, parent) {
|
|
1088
|
-
await limit(() => applyVisitor(node, visitor, parent));
|
|
1089
|
-
const children = Array.from(getChildren(node, recurse));
|
|
1090
|
-
if (children.length === 0) return;
|
|
1091
|
-
await Promise.all(children.map((child) => _walk(child, visitor, recurse, limit, node)));
|
|
1092
|
-
}
|
|
1093
|
-
function transform(node, options) {
|
|
1094
|
-
const { depth, parent, ...visitor } = options;
|
|
1095
|
-
const recurse = (depth ?? visitorDepths.deep) === visitorDepths.deep;
|
|
1096
|
-
const rebuilt = transformChildren(applyVisitor(node, visitor, parent) ?? node, options, recurse);
|
|
1097
|
-
if (rebuilt === node) return node;
|
|
1098
|
-
const rebuild = nodeRebuilders[rebuilt.kind];
|
|
1099
|
-
return rebuild ? rebuild(rebuilt) : rebuilt;
|
|
1100
|
-
}
|
|
1101
|
-
/**
|
|
1102
|
-
* Immutably rebuilds a node's children using {@link VISITOR_KEYS}, transforming
|
|
1103
|
-
* each child node and leaving non-node values (e.g. `additionalProperties: true`) intact.
|
|
1104
|
-
* `Schema` children are skipped in shallow mode.
|
|
1105
|
-
*/
|
|
1106
|
-
function transformChildren(node, options, recurse) {
|
|
1107
|
-
if (node.kind === "Schema" && !recurse) return node;
|
|
1108
|
-
const keys = visitorKeysByKind[node.kind];
|
|
1109
|
-
if (!keys) return node;
|
|
1110
|
-
const record = node;
|
|
1111
|
-
const childOptions = {
|
|
1112
|
-
...options,
|
|
1113
|
-
parent: node
|
|
1114
|
-
};
|
|
1115
|
-
let updates;
|
|
1116
|
-
for (const key of keys) {
|
|
1117
|
-
if (!(key in record)) continue;
|
|
1118
|
-
const value = record[key];
|
|
1119
|
-
if (Array.isArray(value)) {
|
|
1120
|
-
let changed = false;
|
|
1121
|
-
const mapped = value.map((item) => {
|
|
1122
|
-
if (!isNode(item)) return item;
|
|
1123
|
-
const next = transform(item, childOptions);
|
|
1124
|
-
if (next !== item) changed = true;
|
|
1125
|
-
return next;
|
|
1126
|
-
});
|
|
1127
|
-
if (changed) (updates ??= {})[key] = mapped;
|
|
1128
|
-
} else if (isNode(value)) {
|
|
1129
|
-
const next = transform(value, childOptions);
|
|
1130
|
-
if (next !== value) (updates ??= {})[key] = next;
|
|
1131
|
-
}
|
|
1132
|
-
}
|
|
1133
|
-
return updates ? {
|
|
1134
|
-
...node,
|
|
1135
|
-
...updates
|
|
1136
|
-
} : node;
|
|
1137
|
-
}
|
|
1138
|
-
/**
|
|
1139
|
-
* Lazy depth-first collection pass. Yields every non-null value returned by
|
|
1140
|
-
* the visitor callbacks. Use `collect` for the eager array form.
|
|
1141
|
-
*
|
|
1142
|
-
* @example Collect every operationId
|
|
1143
|
-
* ```ts
|
|
1144
|
-
* const ids: string[] = []
|
|
1145
|
-
* for (const id of collectLazy<string>(root, {
|
|
1146
|
-
* operation(node) {
|
|
1147
|
-
* return node.operationId
|
|
1148
|
-
* },
|
|
1149
|
-
* })) {
|
|
1150
|
-
* ids.push(id)
|
|
1151
|
-
* }
|
|
1152
|
-
* ```
|
|
1153
|
-
*/
|
|
1154
|
-
function* collectLazy(node, options) {
|
|
1155
|
-
const { depth, parent, ...visitor } = options;
|
|
1156
|
-
const recurse = (depth ?? visitorDepths.deep) === visitorDepths.deep;
|
|
1157
|
-
const v = applyVisitor(node, visitor, parent);
|
|
1158
|
-
if (v != null) yield v;
|
|
1159
|
-
for (const child of getChildren(node, recurse)) yield* collectLazy(child, {
|
|
1160
|
-
...options,
|
|
1161
|
-
parent: node
|
|
1162
|
-
});
|
|
1163
|
-
}
|
|
1164
|
-
/**
|
|
1165
|
-
* Eager depth-first collection pass. Returns an array of every non-null value
|
|
1166
|
-
* the visitor callbacks return.
|
|
1167
|
-
*
|
|
1168
|
-
* @example Collect every operationId
|
|
1169
|
-
* ```ts
|
|
1170
|
-
* const ids = collect<string>(root, {
|
|
1171
|
-
* operation(node) {
|
|
1172
|
-
* return node.operationId
|
|
1173
|
-
* },
|
|
1174
|
-
* })
|
|
1175
|
-
* ```
|
|
1176
|
-
*/
|
|
1177
|
-
function collect(node, options) {
|
|
1178
|
-
return Array.from(collectLazy(node, options));
|
|
1179
|
-
}
|
|
1180
|
-
//#endregion
|
|
1181
|
-
//#region src/dedupe.ts
|
|
1182
|
-
/**
|
|
1183
|
-
* Builds the shared `ref` replacement for a duplicate occurrence, carrying the
|
|
1184
|
-
* usage-slot and documentation fields that are not part of the canonical type.
|
|
1185
|
-
*/
|
|
1186
|
-
function createRefNode(node, canonical) {
|
|
1187
|
-
return createSchema({
|
|
1188
|
-
type: "ref",
|
|
1189
|
-
name: canonical.name,
|
|
1190
|
-
ref: canonical.ref,
|
|
1191
|
-
optional: node.optional,
|
|
1192
|
-
nullish: node.nullish,
|
|
1193
|
-
readOnly: node.readOnly,
|
|
1194
|
-
writeOnly: node.writeOnly,
|
|
1195
|
-
deprecated: node.deprecated,
|
|
1196
|
-
description: node.description,
|
|
1197
|
-
default: node.default,
|
|
1198
|
-
example: node.example
|
|
1199
|
-
});
|
|
1200
|
-
}
|
|
1201
|
-
function applyDedupe(node, plan, skipRootMatch = false) {
|
|
1202
|
-
const { canonicalBySignature, aliasNames } = plan;
|
|
1203
|
-
if (canonicalBySignature.size === 0 && aliasNames.size === 0) return node;
|
|
1204
|
-
const root = node;
|
|
1205
|
-
return transform(node, { schema(schemaNode) {
|
|
1206
|
-
if (schemaNode.type === "ref") {
|
|
1207
|
-
const target = schemaNode.ref ? extractRefName(schemaNode.ref) : schemaNode.name;
|
|
1208
|
-
const canonical = target ? aliasNames.get(target) : void 0;
|
|
1209
|
-
return canonical ? {
|
|
1210
|
-
...schemaNode,
|
|
1211
|
-
name: canonical.name,
|
|
1212
|
-
ref: canonical.ref
|
|
1213
|
-
} : void 0;
|
|
1214
|
-
}
|
|
1215
|
-
const signature = signatureOf(schemaNode);
|
|
1216
|
-
if (skipRootMatch && schemaNode === root) return void 0;
|
|
1217
|
-
const canonical = canonicalBySignature.get(signature);
|
|
1218
|
-
if (!canonical) return void 0;
|
|
1219
|
-
return createRefNode(schemaNode, canonical);
|
|
1220
|
-
} });
|
|
1221
|
-
}
|
|
1222
|
-
/**
|
|
1223
|
-
* Strips usage-slot flags from a hoisted definition and applies its canonical name.
|
|
1224
|
-
* A standalone definition is never optional, so `optional`/`nullish` are cleared.
|
|
1225
|
-
*/
|
|
1226
|
-
function cleanDefinition(node, name) {
|
|
1227
|
-
return {
|
|
1228
|
-
...node,
|
|
1229
|
-
name,
|
|
1230
|
-
optional: void 0,
|
|
1231
|
-
nullish: void 0
|
|
1232
|
-
};
|
|
1233
|
-
}
|
|
1234
|
-
/**
|
|
1235
|
-
* Scans a forest of schema and operation nodes and produces a {@link DedupePlan}.
|
|
1236
|
-
*
|
|
1237
|
-
* A shape that occurs at least `minOccurrences` times is deduplicated: if any occurrence
|
|
1238
|
-
* is a named top-level schema, the first one becomes the canonical (so other top-level
|
|
1239
|
-
* duplicates and inline copies turn into references to it). Every other top-level name with
|
|
1240
|
-
* the same content is recorded in `aliasNames`, so refs to it can be repointed at the
|
|
1241
|
-
* canonical. Otherwise a new definition is hoisted using `nameFor`. The plan is then applied
|
|
1242
|
-
* per node with {@link applyDedupe}.
|
|
1243
|
-
*
|
|
1244
|
-
* @example
|
|
1245
|
-
* ```ts
|
|
1246
|
-
* const plan = buildDedupePlan([...schemaNodes, ...operationNodes], {
|
|
1247
|
-
* isCandidate: (node) => node.type === 'enum' || node.type === 'object',
|
|
1248
|
-
* nameFor: (node) => node.name ?? null,
|
|
1249
|
-
* refFor: (name) => `#/components/schemas/${name}`,
|
|
1250
|
-
* })
|
|
1251
|
-
* ```
|
|
1252
|
-
*/
|
|
1253
|
-
function buildDedupePlan(roots, options) {
|
|
1254
|
-
const { isCandidate, nameFor, refFor, minOccurrences = 2 } = options;
|
|
1255
|
-
const topLevelNodes = /* @__PURE__ */ new Set();
|
|
1256
|
-
const groups = /* @__PURE__ */ new Map();
|
|
1257
|
-
function record(schemaNode) {
|
|
1258
|
-
const signature = signatureOf(schemaNode);
|
|
1259
|
-
if (!isCandidate(schemaNode)) return;
|
|
1260
|
-
const isTopLevel = topLevelNodes.has(schemaNode) && !!schemaNode.name;
|
|
1261
|
-
const group = groups.get(signature);
|
|
1262
|
-
if (group) {
|
|
1263
|
-
group.count++;
|
|
1264
|
-
if (isTopLevel) group.topLevelNames.push(schemaNode.name);
|
|
1265
|
-
} else groups.set(signature, {
|
|
1266
|
-
count: 1,
|
|
1267
|
-
representative: schemaNode,
|
|
1268
|
-
topLevelNames: isTopLevel ? [schemaNode.name] : []
|
|
1269
|
-
});
|
|
1270
|
-
}
|
|
1271
|
-
for (const root of roots) {
|
|
1272
|
-
if (root.kind === "Schema") topLevelNodes.add(root);
|
|
1273
|
-
for (const schemaNode of collectLazy(root, { schema: (node) => node })) record(schemaNode);
|
|
1274
|
-
}
|
|
1275
|
-
const canonicalBySignature = /* @__PURE__ */ new Map();
|
|
1276
|
-
const aliasNames = /* @__PURE__ */ new Map();
|
|
1277
|
-
const pendingHoists = [];
|
|
1278
|
-
for (const [signature, group] of groups) {
|
|
1279
|
-
if (group.count < minOccurrences) continue;
|
|
1280
|
-
const [firstName, ...duplicateNames] = group.topLevelNames;
|
|
1281
|
-
if (firstName) {
|
|
1282
|
-
const canonical = {
|
|
1283
|
-
name: firstName,
|
|
1284
|
-
ref: refFor(firstName)
|
|
1285
|
-
};
|
|
1286
|
-
canonicalBySignature.set(signature, canonical);
|
|
1287
|
-
for (const duplicate of duplicateNames) aliasNames.set(duplicate, canonical);
|
|
1288
|
-
continue;
|
|
1289
|
-
}
|
|
1290
|
-
const name = nameFor(group.representative, signature);
|
|
1291
|
-
if (!name) continue;
|
|
1292
|
-
canonicalBySignature.set(signature, {
|
|
1293
|
-
name,
|
|
1294
|
-
ref: refFor(name)
|
|
1295
|
-
});
|
|
1296
|
-
pendingHoists.push({
|
|
1297
|
-
name,
|
|
1298
|
-
representative: group.representative
|
|
1299
|
-
});
|
|
1300
|
-
}
|
|
1301
|
-
return {
|
|
1302
|
-
canonicalBySignature,
|
|
1303
|
-
aliasNames,
|
|
1304
|
-
hoisted: pendingHoists.map(({ name, representative }) => cleanDefinition(applyDedupe(representative, {
|
|
1305
|
-
canonicalBySignature,
|
|
1306
|
-
aliasNames
|
|
1307
|
-
}, true), name))
|
|
1308
|
-
};
|
|
1309
|
-
}
|
|
1310
|
-
//#endregion
|
|
1311
|
-
//#region src/dialect.ts
|
|
1312
|
-
/**
|
|
1313
|
-
* Types a {@link SchemaDialect} for an adapter. Adds no runtime behavior and only pins the
|
|
1314
|
-
* dialect's type for inference.
|
|
1315
|
-
*
|
|
1316
|
-
* @example
|
|
1317
|
-
* ```ts
|
|
1318
|
-
* export const oasDialect = defineSchemaDialect({
|
|
1319
|
-
* name: 'oas',
|
|
1320
|
-
* isNullable,
|
|
1321
|
-
* isReference,
|
|
1322
|
-
* isDiscriminator,
|
|
1323
|
-
* isBinary: (schema) => schema.type === 'string' && schema.contentMediaType === 'application/octet-stream',
|
|
1324
|
-
* resolveRef,
|
|
1325
|
-
* })
|
|
1326
|
-
* ```
|
|
1327
|
-
*/
|
|
1328
|
-
function defineSchemaDialect(dialect) {
|
|
1329
|
-
return dialect;
|
|
1330
|
-
}
|
|
1331
|
-
//#endregion
|
|
1332
|
-
//#region src/guards.ts
|
|
1333
|
-
/**
|
|
1334
|
-
* Narrows a `SchemaNode` to the variant that matches `type`.
|
|
1335
|
-
*
|
|
1336
|
-
* @example
|
|
1337
|
-
* ```ts
|
|
1338
|
-
* const schema = createSchema({ type: 'string' })
|
|
1339
|
-
* const stringNode = narrowSchema(schema, 'string') // StringSchemaNode | null
|
|
1340
|
-
* ```
|
|
1341
|
-
*/
|
|
1342
|
-
function narrowSchema(node, type) {
|
|
1343
|
-
return node?.type === type ? node : null;
|
|
1344
|
-
}
|
|
1345
|
-
/**
|
|
1346
|
-
* Narrows an `OperationNode` to an `HttpOperationNode`, guaranteeing `method` and `path`.
|
|
1347
|
-
*
|
|
1348
|
-
* @example
|
|
1349
|
-
* ```ts
|
|
1350
|
-
* if (isHttpOperationNode(node)) {
|
|
1351
|
-
* console.log(node.method, node.path)
|
|
1352
|
-
* }
|
|
1353
|
-
* ```
|
|
1354
|
-
*/
|
|
1355
|
-
function isHttpOperationNode(node) {
|
|
1356
|
-
return node.protocol === "http" || node.method !== void 0 && node.path !== void 0;
|
|
1357
|
-
}
|
|
1358
|
-
//#endregion
|
|
1359
|
-
//#region src/utils/ast.ts
|
|
1360
|
-
const plainStringTypes = new Set([
|
|
1361
|
-
"string",
|
|
1362
|
-
"uuid",
|
|
1363
|
-
"email",
|
|
1364
|
-
"url",
|
|
1365
|
-
"datetime"
|
|
1366
|
-
]);
|
|
1367
|
-
/**
|
|
1368
|
-
* Merges a ref node with its resolved schema, giving usage-site fields precedence.
|
|
1369
|
-
*
|
|
1370
|
-
* Usage-site fields (`description`, `readOnly`, `nullable`, `deprecated`) on the ref node
|
|
1371
|
-
* override the same fields in the resolved `node.schema`. Non-ref nodes are returned unchanged.
|
|
1372
|
-
*
|
|
1373
|
-
* @example
|
|
1374
|
-
* ```ts
|
|
1375
|
-
* // Ref with description override
|
|
1376
|
-
* const ref = createSchema({ type: 'ref', ref: '#/components/schemas/Pet', description: 'A cute pet' })
|
|
1377
|
-
* const merged = syncSchemaRef(ref) // merges with resolved Pet schema
|
|
1378
|
-
* ```
|
|
1379
|
-
*/
|
|
1380
|
-
function syncSchemaRef(node) {
|
|
1381
|
-
const ref = narrowSchema(node, "ref");
|
|
1382
|
-
if (!ref) return node;
|
|
1383
|
-
if (!ref.schema) return node;
|
|
1384
|
-
const { kind: _kind, type: _type, name: _name, ref: _ref, schema: _schema, ...overrides } = ref;
|
|
1385
|
-
const definedOverrides = Object.fromEntries(Object.entries(overrides).filter(([, v]) => v !== void 0));
|
|
1386
|
-
return createSchema({
|
|
1387
|
-
...ref.schema,
|
|
1388
|
-
...definedOverrides
|
|
1389
|
-
});
|
|
1390
|
-
}
|
|
1391
|
-
/**
|
|
1392
|
-
* Type guard that returns `true` when a schema emits as a plain `string` type.
|
|
1393
|
-
*
|
|
1394
|
-
* Covers `string`, `uuid`, `email`, `url`, and `datetime` types. For `date` and `time`
|
|
1395
|
-
* types, returns `true` only when `representation` is `'string'` rather than `'date'`.
|
|
1396
|
-
*/
|
|
1397
|
-
function isStringType(node) {
|
|
1398
|
-
if (plainStringTypes.has(node.type)) return true;
|
|
1399
|
-
const temporal = narrowSchema(node, "date") ?? narrowSchema(node, "time");
|
|
1400
|
-
if (temporal) return temporal.representation !== "date";
|
|
1401
|
-
return false;
|
|
1402
|
-
}
|
|
1403
|
-
/**
|
|
1404
|
-
* Applies casing rules to parameter names and returns a new parameter array.
|
|
1405
|
-
*
|
|
1406
|
-
* Use this before passing parameters to schema builders so output property keys match
|
|
1407
|
-
* the desired casing while preserving `OperationNode.parameters` for other consumers.
|
|
1408
|
-
* The input array is not mutated. When `casing` is not set, the original array is returned unchanged.
|
|
1409
|
-
*/
|
|
1410
|
-
const caseParamsMemo = memoize(/* @__PURE__ */ new WeakMap(), (params) => memoize(/* @__PURE__ */ new Map(), (casing) => params.map((param) => {
|
|
1411
|
-
const transformed = casing === "camelcase" || !isValidVarName(param.name) ? camelCase(param.name) : param.name;
|
|
1412
|
-
return {
|
|
1413
|
-
...param,
|
|
1414
|
-
name: transformed
|
|
1415
|
-
};
|
|
1416
|
-
})));
|
|
1417
|
-
function caseParams(params, casing) {
|
|
1418
|
-
if (!casing) return params;
|
|
1419
|
-
return caseParamsMemo(params)(casing);
|
|
1420
|
-
}
|
|
1421
|
-
/**
|
|
1422
|
-
* Creates a single-property object schema used as a discriminator literal.
|
|
1423
|
-
*
|
|
1424
|
-
* @example
|
|
1425
|
-
* ```ts
|
|
1426
|
-
* createDiscriminantNode({ propertyName: 'type', value: 'dog' })
|
|
1427
|
-
* // -> { type: 'object', properties: [{ name: 'type', required: true, schema: enum('dog') }] }
|
|
1428
|
-
* ```
|
|
1429
|
-
*/
|
|
1430
|
-
function createDiscriminantNode({ propertyName, value }) {
|
|
1431
|
-
return createSchema({
|
|
1432
|
-
type: "object",
|
|
1433
|
-
primitive: "object",
|
|
1434
|
-
properties: [createProperty({
|
|
1435
|
-
name: propertyName,
|
|
1436
|
-
schema: createSchema({
|
|
1437
|
-
type: "enum",
|
|
1438
|
-
primitive: "string",
|
|
1439
|
-
enumValues: [value]
|
|
1440
|
-
}),
|
|
1441
|
-
required: true
|
|
1442
|
-
})]
|
|
1443
|
-
});
|
|
1444
|
-
}
|
|
1445
|
-
/**
|
|
1446
|
-
* Resolves the {@link TypeExpression} for an individual parameter.
|
|
1447
|
-
*
|
|
1448
|
-
* Without a resolver, falls back to the schema primitive (a plain type-name string).
|
|
1449
|
-
* When the parameter belongs to a named group, emits an {@link IndexedAccessTypeNode}
|
|
1450
|
-
* (`GroupParams['petId']`); otherwise the resolved individual name as a plain string.
|
|
1451
|
-
*/
|
|
1452
|
-
function resolveParamType({ node, param, resolver }) {
|
|
1453
|
-
if (!resolver) return param.schema.primitive ?? "unknown";
|
|
1454
|
-
const individualName = resolver.resolveParamName(node, param);
|
|
1455
|
-
const groupLocation = param.in === "path" || param.in === "query" || param.in === "header" ? param.in : void 0;
|
|
1456
|
-
const groupResolvers = {
|
|
1457
|
-
path: resolver.resolvePathParamsName,
|
|
1458
|
-
query: resolver.resolveQueryParamsName,
|
|
1459
|
-
header: resolver.resolveHeaderParamsName
|
|
1460
|
-
};
|
|
1461
|
-
const groupName = groupLocation ? groupResolvers[groupLocation].call(resolver, node, param) : void 0;
|
|
1462
|
-
if (groupName && groupName !== individualName) return createIndexedAccessType({
|
|
1463
|
-
objectType: groupName,
|
|
1464
|
-
indexType: param.name
|
|
1465
|
-
});
|
|
1466
|
-
return individualName;
|
|
1467
|
-
}
|
|
1468
|
-
/**
|
|
1469
|
-
* Converts an `OperationNode` into function parameters for code generation.
|
|
1470
|
-
*
|
|
1471
|
-
* Centralizes parameter grouping logic for all plugins. `paramsType` chooses between one
|
|
1472
|
-
* destructured object parameter (`object`) and separate top-level parameters (`inline`), while
|
|
1473
|
-
* `pathParamsType` controls how path params render in inline mode. Provide a `resolver` for type
|
|
1474
|
-
* name resolution and `extraParams` for plugin-specific trailing parameters such as an `options` object.
|
|
1475
|
-
*/
|
|
1476
|
-
function createOperationParams(node, options) {
|
|
1477
|
-
const { paramsType, pathParamsType, paramsCasing, resolver, pathParamsDefault, extraParams = [], paramNames, typeWrapper } = options;
|
|
1478
|
-
const dataName = paramNames?.data ?? "data";
|
|
1479
|
-
const paramsName = paramNames?.params ?? "params";
|
|
1480
|
-
const headersName = paramNames?.headers ?? "headers";
|
|
1481
|
-
const pathName = paramNames?.path ?? "pathParams";
|
|
1482
|
-
const wrapType = (type) => typeWrapper ? typeWrapper(type) : type;
|
|
1483
|
-
const wrapTypeExpression = (type) => typeof type === "string" ? wrapType(type) : type;
|
|
1484
|
-
const casedParams = caseParams(node.parameters, paramsCasing);
|
|
1485
|
-
const pathParams = casedParams.filter((p) => p.in === "path");
|
|
1486
|
-
const queryParams = casedParams.filter((p) => p.in === "query");
|
|
1487
|
-
const headerParams = casedParams.filter((p) => p.in === "header");
|
|
1488
|
-
const toProperty = (param) => ({
|
|
1489
|
-
name: param.name,
|
|
1490
|
-
type: wrapTypeExpression(resolveParamType({
|
|
1491
|
-
node,
|
|
1492
|
-
param,
|
|
1493
|
-
resolver
|
|
1494
|
-
})),
|
|
1495
|
-
optional: !param.required
|
|
1496
|
-
});
|
|
1497
|
-
const emptyObjectDefault = (props) => props.every((p) => p.optional) ? "{}" : void 0;
|
|
1498
|
-
const bodyType = node.requestBody?.content?.[0]?.schema ? wrapType(resolver?.resolveDataName(node) ?? "unknown") : void 0;
|
|
1499
|
-
const bodyProperty = bodyType ? [{
|
|
1500
|
-
name: dataName,
|
|
1501
|
-
type: bodyType,
|
|
1502
|
-
optional: !(node.requestBody?.required ?? false)
|
|
1503
|
-
}] : [];
|
|
1504
|
-
const trailingGroups = [{
|
|
1505
|
-
name: paramsName,
|
|
1506
|
-
node,
|
|
1507
|
-
params: queryParams,
|
|
1508
|
-
groupType: resolveGroupType({
|
|
1509
|
-
node,
|
|
1510
|
-
params: queryParams,
|
|
1511
|
-
group: "query",
|
|
1512
|
-
resolver
|
|
1513
|
-
}),
|
|
1514
|
-
resolver,
|
|
1515
|
-
wrapType
|
|
1516
|
-
}, {
|
|
1517
|
-
name: headersName,
|
|
1518
|
-
node,
|
|
1519
|
-
params: headerParams,
|
|
1520
|
-
groupType: resolveGroupType({
|
|
1521
|
-
node,
|
|
1522
|
-
params: headerParams,
|
|
1523
|
-
group: "header",
|
|
1524
|
-
resolver
|
|
1525
|
-
}),
|
|
1526
|
-
resolver,
|
|
1527
|
-
wrapType
|
|
1528
|
-
}];
|
|
1529
|
-
const params = [];
|
|
1530
|
-
if (paramsType === "object") {
|
|
1531
|
-
const children = [
|
|
1532
|
-
...pathParams.map(toProperty),
|
|
1533
|
-
...bodyProperty,
|
|
1534
|
-
...trailingGroups.flatMap(buildGroupProperty)
|
|
1535
|
-
];
|
|
1536
|
-
if (children.length) params.push(createFunctionParameter({
|
|
1537
|
-
properties: children,
|
|
1538
|
-
default: emptyObjectDefault(children)
|
|
1539
|
-
}));
|
|
1540
|
-
} else {
|
|
1541
|
-
if (pathParamsType === "inlineSpread" && pathParams.length) {
|
|
1542
|
-
const spreadType = resolver?.resolvePathParamsName(node, pathParams[0]);
|
|
1543
|
-
params.push(createFunctionParameter({
|
|
1544
|
-
name: pathName,
|
|
1545
|
-
type: spreadType ? wrapType(spreadType) : void 0,
|
|
1546
|
-
rest: true
|
|
1547
|
-
}));
|
|
1548
|
-
} else if (pathParamsType === "inline") params.push(...pathParams.map((p) => createFunctionParameter(toProperty(p))));
|
|
1549
|
-
else if (pathParams.length) {
|
|
1550
|
-
const pathChildren = pathParams.map(toProperty);
|
|
1551
|
-
params.push(createFunctionParameter({
|
|
1552
|
-
properties: pathChildren,
|
|
1553
|
-
default: pathParamsDefault ?? emptyObjectDefault(pathChildren)
|
|
1554
|
-
}));
|
|
1555
|
-
}
|
|
1556
|
-
params.push(...bodyProperty.map((p) => createFunctionParameter(p)));
|
|
1557
|
-
params.push(...trailingGroups.flatMap(buildGroupParam));
|
|
1558
|
-
}
|
|
1559
|
-
params.push(...extraParams);
|
|
1560
|
-
return createFunctionParameters({ params });
|
|
1561
|
-
}
|
|
1562
|
-
/**
|
|
1563
|
-
* Builds the property descriptor for a query or header group.
|
|
1564
|
-
* Returns an empty array when there are no params to emit.
|
|
1565
|
-
*
|
|
1566
|
-
* A pre-resolved `groupType` emits `name: GroupType`. Otherwise it builds an inline
|
|
1567
|
-
* {@link TypeLiteralNode} from the individual params.
|
|
1568
|
-
*/
|
|
1569
|
-
function buildGroupProperty({ name, node, params, groupType, resolver, wrapType }) {
|
|
1570
|
-
if (groupType) return [{
|
|
1571
|
-
name,
|
|
1572
|
-
type: typeof groupType.type === "string" ? wrapType(groupType.type) : groupType.type,
|
|
1573
|
-
optional: groupType.optional
|
|
1574
|
-
}];
|
|
1575
|
-
if (params.length) return [{
|
|
1576
|
-
name,
|
|
1577
|
-
type: buildTypeLiteral({
|
|
1578
|
-
node,
|
|
1579
|
-
params,
|
|
1580
|
-
resolver
|
|
1581
|
-
}),
|
|
1582
|
-
optional: params.every((p) => !p.required)
|
|
1583
|
-
}];
|
|
1584
|
-
return [];
|
|
1585
|
-
}
|
|
1586
|
-
/**
|
|
1587
|
-
* Builds a single {@link FunctionParameterNode} for a query or header group.
|
|
1588
|
-
* Returns an empty array when there are no params to emit.
|
|
1589
|
-
*
|
|
1590
|
-
* A pre-resolved `groupType` emits `name: GroupType`. Otherwise it builds an inline
|
|
1591
|
-
* {@link TypeLiteralNode} from the individual params.
|
|
1592
|
-
*/
|
|
1593
|
-
function buildGroupParam(args) {
|
|
1594
|
-
return buildGroupProperty(args).map((p) => createFunctionParameter(p));
|
|
1595
|
-
}
|
|
1596
|
-
/**
|
|
1597
|
-
* Derives a {@link ParamGroupType} for a query or header group from the resolver.
|
|
1598
|
-
*
|
|
1599
|
-
* Returns `null` when there is no resolver, no params, or the group name equals the
|
|
1600
|
-
* individual param name (so there is no real group to emit).
|
|
1601
|
-
*/
|
|
1602
|
-
function resolveGroupType({ node, params, group, resolver }) {
|
|
1603
|
-
if (!resolver || !params.length) return null;
|
|
1604
|
-
const firstParam = params[0];
|
|
1605
|
-
const groupName = (group === "query" ? resolver.resolveQueryParamsName : resolver.resolveHeaderParamsName).call(resolver, node, firstParam);
|
|
1606
|
-
if (groupName === resolver.resolveParamName(node, firstParam)) return null;
|
|
1607
|
-
return {
|
|
1608
|
-
type: groupName,
|
|
1609
|
-
optional: params.every((p) => !p.required)
|
|
1610
|
-
};
|
|
1611
|
-
}
|
|
1612
|
-
/**
|
|
1613
|
-
* Builds a {@link TypeLiteralNode} for an inline anonymous type grouping named fields.
|
|
1614
|
-
*
|
|
1615
|
-
* Used when query or header parameters have no dedicated group type name.
|
|
1616
|
-
* Each language printer renders this appropriately (TypeScript: `{ petId: string; name?: string }`).
|
|
1617
|
-
*/
|
|
1618
|
-
function buildTypeLiteral({ node, params, resolver }) {
|
|
1619
|
-
return createTypeLiteral({ members: params.map((p) => ({
|
|
1620
|
-
name: p.name,
|
|
1621
|
-
type: resolveParamType({
|
|
1622
|
-
node,
|
|
1623
|
-
param: p,
|
|
1624
|
-
resolver
|
|
1625
|
-
}),
|
|
1626
|
-
optional: !p.required
|
|
1627
|
-
})) });
|
|
1628
|
-
}
|
|
1629
|
-
function sourceKey(source) {
|
|
1630
|
-
return `${source.name ?? extractStringsFromNodes(source.nodes)}:${source.isExportable ?? false}:${source.isTypeOnly ?? false}`;
|
|
1631
|
-
}
|
|
1632
|
-
function pathTypeKey(path, isTypeOnly) {
|
|
1633
|
-
return `${path}:${isTypeOnly ?? false}`;
|
|
1634
|
-
}
|
|
1635
|
-
function exportKey(path, name, isTypeOnly, asAlias) {
|
|
1636
|
-
return `${path}:${name ?? ""}:${isTypeOnly ?? false}:${asAlias ?? ""}`;
|
|
1637
|
-
}
|
|
1638
|
-
function importKey(path, name, isTypeOnly) {
|
|
1639
|
-
return `${path}:${name ?? ""}:${isTypeOnly ?? false}`;
|
|
1640
|
-
}
|
|
1641
|
-
/**
|
|
1642
|
-
* Computes a multi-level sort key for exports and imports:
|
|
1643
|
-
* non-array names first (wildcards/namespace aliases). Type-only before value. Alphabetical path. Unnamed before named.
|
|
1644
|
-
*/
|
|
1645
|
-
function sortKey(node) {
|
|
1646
|
-
const isArray = Array.isArray(node.name) ? "1" : "0";
|
|
1647
|
-
const typeOnly = node.isTypeOnly ? "0" : "1";
|
|
1648
|
-
const hasName = node.name != null ? "1" : "0";
|
|
1649
|
-
const name = Array.isArray(node.name) ? node.name.toSorted().join("\0") : node.name ?? "";
|
|
1650
|
-
return `${isArray}:${typeOnly}:${node.path}:${hasName}:${name}`;
|
|
1651
|
-
}
|
|
1652
|
-
/**
|
|
1653
|
-
* Deduplicates and merges `SourceNode` objects by `name + isExportable + isTypeOnly`.
|
|
1654
|
-
*
|
|
1655
|
-
* Unnamed sources are deduplicated by object reference. Returns a deduplicated array in original order.
|
|
1656
|
-
*/
|
|
1657
|
-
function combineSources(sources) {
|
|
1658
|
-
const seen = /* @__PURE__ */ new Map();
|
|
1659
|
-
for (const source of sources) {
|
|
1660
|
-
const key = sourceKey(source);
|
|
1661
|
-
if (!seen.has(key)) seen.set(key, source);
|
|
1662
|
-
}
|
|
1663
|
-
return [...seen.values()];
|
|
1664
|
-
}
|
|
1665
|
-
/**
|
|
1666
|
-
* Merges `incoming` names into `existing`, preserving order and dropping duplicates.
|
|
1667
|
-
*
|
|
1668
|
-
* Shared by `combineExports` and `combineImports` for the same-path name-merge case.
|
|
1669
|
-
*/
|
|
1670
|
-
function mergeNameArrays(existing, incoming) {
|
|
1671
|
-
const merged = new Set(existing);
|
|
1672
|
-
for (const name of incoming) merged.add(name);
|
|
1673
|
-
return [...merged];
|
|
1674
|
-
}
|
|
1675
|
-
/**
|
|
1676
|
-
* Deduplicates and merges `ExportNode` objects by path and type.
|
|
1677
|
-
*
|
|
1678
|
-
* Named exports with the same path and `isTypeOnly` flag have their names merged into a single export.
|
|
1679
|
-
* Non-array exports are deduplicated by exact identity. Returns a sorted, deduplicated array.
|
|
1680
|
-
*/
|
|
1681
|
-
function combineExports(exports) {
|
|
1682
|
-
const result = [];
|
|
1683
|
-
const namedByPath = /* @__PURE__ */ new Map();
|
|
1684
|
-
const seen = /* @__PURE__ */ new Set();
|
|
1685
|
-
const keyed = exports.map((node) => ({
|
|
1686
|
-
node,
|
|
1687
|
-
key: sortKey(node)
|
|
1688
|
-
}));
|
|
1689
|
-
keyed.sort((a, b) => a.key < b.key ? -1 : a.key > b.key ? 1 : 0);
|
|
1690
|
-
for (const { node: curr } of keyed) {
|
|
1691
|
-
const { name, path, isTypeOnly, asAlias } = curr;
|
|
1692
|
-
if (Array.isArray(name)) {
|
|
1693
|
-
if (!name.length) continue;
|
|
1694
|
-
const key = pathTypeKey(path, isTypeOnly);
|
|
1695
|
-
const existing = namedByPath.get(key);
|
|
1696
|
-
if (existing && Array.isArray(existing.name)) existing.name = mergeNameArrays(existing.name, name);
|
|
1697
|
-
else {
|
|
1698
|
-
const newItem = {
|
|
1699
|
-
...curr,
|
|
1700
|
-
name: [...new Set(name)]
|
|
1701
|
-
};
|
|
1702
|
-
result.push(newItem);
|
|
1703
|
-
namedByPath.set(key, newItem);
|
|
1704
|
-
}
|
|
1705
|
-
} else {
|
|
1706
|
-
const key = exportKey(path, name, isTypeOnly, asAlias);
|
|
1707
|
-
if (!seen.has(key)) {
|
|
1708
|
-
result.push(curr);
|
|
1709
|
-
seen.add(key);
|
|
1710
|
-
}
|
|
1711
|
-
}
|
|
1712
|
-
}
|
|
1713
|
-
return result;
|
|
1714
|
-
}
|
|
1715
|
-
/**
|
|
1716
|
-
* Deduplicates and merges `ImportNode` objects, filtering out unused imports.
|
|
1717
|
-
*
|
|
1718
|
-
* Retains imports that are referenced in `source` or re-exported. Imports with the same path and
|
|
1719
|
-
* `isTypeOnly` flag have their names merged. Returns a sorted, deduplicated, filtered array.
|
|
1720
|
-
*
|
|
1721
|
-
* @note Use this when combining imports from multiple files to avoid duplicate declarations.
|
|
1722
|
-
*/
|
|
1723
|
-
function combineImports(imports, exports, source) {
|
|
1724
|
-
const exportedNames = new Set(exports.flatMap((e) => Array.isArray(e.name) ? e.name : e.name ? [e.name] : []));
|
|
1725
|
-
const isUsed = (importName) => !source || source.includes(importName) || exportedNames.has(importName);
|
|
1726
|
-
const importNameMemo = /* @__PURE__ */ new Map();
|
|
1727
|
-
const canonicalizeName = (n) => {
|
|
1728
|
-
if (typeof n === "string") return n;
|
|
1729
|
-
const key = `${n.propertyName}:${n.name ?? ""}`;
|
|
1730
|
-
if (!importNameMemo.has(key)) importNameMemo.set(key, n);
|
|
1731
|
-
return importNameMemo.get(key);
|
|
1732
|
-
};
|
|
1733
|
-
const pathsWithUsedNamedImport = /* @__PURE__ */ new Set();
|
|
1734
|
-
for (const node of imports) {
|
|
1735
|
-
if (!Array.isArray(node.name)) continue;
|
|
1736
|
-
if (node.name.some((item) => typeof item === "string" ? isUsed(item) : isUsed(item.name ?? item.propertyName))) pathsWithUsedNamedImport.add(node.path);
|
|
1737
|
-
}
|
|
1738
|
-
const result = [];
|
|
1739
|
-
const namedByPath = /* @__PURE__ */ new Map();
|
|
1740
|
-
const seen = /* @__PURE__ */ new Set();
|
|
1741
|
-
const keyed = imports.map((node) => ({
|
|
1742
|
-
node,
|
|
1743
|
-
key: sortKey(node)
|
|
1744
|
-
}));
|
|
1745
|
-
keyed.sort((a, b) => a.key < b.key ? -1 : a.key > b.key ? 1 : 0);
|
|
1746
|
-
for (const { node: curr } of keyed) {
|
|
1747
|
-
if (curr.path === curr.root) continue;
|
|
1748
|
-
const { path, isTypeOnly } = curr;
|
|
1749
|
-
let { name } = curr;
|
|
1750
|
-
if (Array.isArray(name)) {
|
|
1751
|
-
name = [...new Set(name.map(canonicalizeName))].filter((item) => typeof item === "string" ? isUsed(item) : isUsed(item.name ?? item.propertyName));
|
|
1752
|
-
if (!name.length) continue;
|
|
1753
|
-
const key = pathTypeKey(path, isTypeOnly);
|
|
1754
|
-
const existing = namedByPath.get(key);
|
|
1755
|
-
if (existing && Array.isArray(existing.name)) existing.name = mergeNameArrays(existing.name, name);
|
|
1756
|
-
else {
|
|
1757
|
-
const newItem = {
|
|
1758
|
-
...curr,
|
|
1759
|
-
name
|
|
1760
|
-
};
|
|
1761
|
-
result.push(newItem);
|
|
1762
|
-
namedByPath.set(key, newItem);
|
|
1763
|
-
}
|
|
1764
|
-
} else {
|
|
1765
|
-
if (name && !isUsed(name) && !pathsWithUsedNamedImport.has(path)) continue;
|
|
1766
|
-
const key = importKey(path, name, isTypeOnly);
|
|
1767
|
-
if (!seen.has(key)) {
|
|
1768
|
-
result.push(curr);
|
|
1769
|
-
seen.add(key);
|
|
1770
|
-
}
|
|
1771
|
-
}
|
|
1772
|
-
}
|
|
1773
|
-
return result;
|
|
1774
|
-
}
|
|
1775
|
-
/**
|
|
1776
|
-
* Extracts all string content from a `CodeNode` tree recursively.
|
|
1777
|
-
*
|
|
1778
|
-
* Collects text node values, identifier references in string fields (`params`, `generics`, `returnType`, `type`),
|
|
1779
|
-
* and nested node content. Used internally to build the full source string for import filtering.
|
|
1780
|
-
*/
|
|
1781
|
-
function extractStringsFromNodes(nodes) {
|
|
1782
|
-
if (!nodes?.length) return "";
|
|
1783
|
-
return nodes.map((node) => {
|
|
1784
|
-
if (typeof node === "string") return node;
|
|
1785
|
-
if (node.kind === "Text") return node.value;
|
|
1786
|
-
if (node.kind === "Break") return "";
|
|
1787
|
-
if (node.kind === "Jsx") return node.value;
|
|
1788
|
-
const parts = [];
|
|
1789
|
-
if ("params" in node && node.params) parts.push(node.params);
|
|
1790
|
-
if ("generics" in node && node.generics) parts.push(Array.isArray(node.generics) ? node.generics.join(", ") : node.generics);
|
|
1791
|
-
if ("returnType" in node && node.returnType) parts.push(node.returnType);
|
|
1792
|
-
if ("type" in node && typeof node.type === "string") parts.push(node.type);
|
|
1793
|
-
const nested = extractStringsFromNodes(node.nodes);
|
|
1794
|
-
if (nested) parts.push(nested);
|
|
1795
|
-
return parts.join("\n");
|
|
1796
|
-
}).filter(Boolean).join("\n");
|
|
1797
|
-
}
|
|
1798
|
-
/**
|
|
1799
|
-
* Resolves the schema name of a ref node, falling back through `ref` → `name` → nested `schema.name`.
|
|
1800
|
-
*
|
|
1801
|
-
* Returns `null` for non-ref nodes or when no name can be resolved. Use this to get a schema's
|
|
1802
|
-
* identifier for type definitions or error messages.
|
|
1803
|
-
*
|
|
1804
|
-
* @example
|
|
1805
|
-
* ```ts
|
|
1806
|
-
* resolveRefName({ kind: 'Schema', type: 'ref', ref: '#/components/schemas/Pet' })
|
|
1807
|
-
* // => 'Pet'
|
|
1808
|
-
* ```
|
|
1809
|
-
*/
|
|
1810
|
-
function resolveRefName(node) {
|
|
1811
|
-
if (!node || node.type !== "ref") return null;
|
|
1812
|
-
if (node.ref) return extractRefName(node.ref) ?? node.name ?? node.schema?.name ?? null;
|
|
1813
|
-
return node.name ?? node.schema?.name ?? null;
|
|
1814
|
-
}
|
|
1815
|
-
/**
|
|
1816
|
-
* Collects every named schema referenced (transitively) from a node via ref edges.
|
|
1817
|
-
*
|
|
1818
|
-
* Refs are followed by name only, the resolved `node.schema` is not traversed inline.
|
|
1819
|
-
* Use this to determine schema dependencies, build reference graphs, or detect what schemas need to be emitted.
|
|
1820
|
-
*
|
|
1821
|
-
* @example Collect refs from a single schema
|
|
1822
|
-
* ```ts
|
|
1823
|
-
* const names = collectReferencedSchemaNames(petSchema)
|
|
1824
|
-
* // → Set { 'Category', 'Tag' }
|
|
1825
|
-
* ```
|
|
1826
|
-
*
|
|
1827
|
-
* @example Accumulate refs from multiple schemas into one set
|
|
1828
|
-
* ```ts
|
|
1829
|
-
* const out = new Set<string>()
|
|
1830
|
-
* for (const schema of schemas) {
|
|
1831
|
-
* collectReferencedSchemaNames(schema, out)
|
|
1832
|
-
* }
|
|
1833
|
-
* ```
|
|
1834
|
-
*/
|
|
1835
|
-
const collectSchemaRefs = memoize(/* @__PURE__ */ new WeakMap(), (node) => {
|
|
1836
|
-
const refs = /* @__PURE__ */ new Set();
|
|
1837
|
-
collect(node, { schema(child) {
|
|
1838
|
-
if (child.type === "ref") {
|
|
1839
|
-
const name = resolveRefName(child);
|
|
1840
|
-
if (name) refs.add(name);
|
|
1841
|
-
}
|
|
1842
|
-
} });
|
|
1843
|
-
return refs;
|
|
1844
|
-
});
|
|
1845
|
-
function collectReferencedSchemaNames(node, out = /* @__PURE__ */ new Set()) {
|
|
1846
|
-
if (!node) return out;
|
|
1847
|
-
for (const name of collectSchemaRefs(node)) out.add(name);
|
|
1848
|
-
return out;
|
|
1849
|
-
}
|
|
1850
|
-
/**
|
|
1851
|
-
* Collects the names of all top-level schemas transitively used by a set of operations.
|
|
1852
|
-
*
|
|
1853
|
-
* An operation uses a schema when any of its parameters, request body content, or responses
|
|
1854
|
-
* reference it, directly or indirectly through other named schemas.
|
|
1855
|
-
* The walk is iterative and safe against reference cycles.
|
|
1856
|
-
*
|
|
1857
|
-
* Use this together with `include` filters to determine which schemas from `components/schemas`
|
|
1858
|
-
* are reachable from the allowed operations, so that schemas used only by excluded operations
|
|
1859
|
-
* are not generated.
|
|
1860
|
-
*
|
|
1861
|
-
* @example Only generate schemas referenced by included operations
|
|
1862
|
-
* ```ts
|
|
1863
|
-
* const includedOps = operations.filter(op => resolver.resolveOptions(op, { options, include }) !== null)
|
|
1864
|
-
* const allowed = collectUsedSchemaNames(includedOps, schemas)
|
|
1865
|
-
*
|
|
1866
|
-
* for (const schema of schemas) {
|
|
1867
|
-
* if (schema.name && !allowed.has(schema.name)) continue
|
|
1868
|
-
* // … generate schema
|
|
1869
|
-
* }
|
|
1870
|
-
* ```
|
|
1871
|
-
*
|
|
1872
|
-
* @example Check whether a specific schema is needed
|
|
1873
|
-
* ```ts
|
|
1874
|
-
* const allowed = collectUsedSchemaNames(includedOps, schemas)
|
|
1875
|
-
* allowed.has('OrderStatus') // false when no included operation references OrderStatus
|
|
1876
|
-
* ```
|
|
1877
|
-
*/
|
|
1878
|
-
const collectUsedSchemaNamesMemo = memoize(/* @__PURE__ */ new WeakMap(), (ops) => memoize(/* @__PURE__ */ new WeakMap(), (schemas) => computeUsedSchemaNames(ops, schemas)));
|
|
1879
|
-
function computeUsedSchemaNames(operations, schemas) {
|
|
1880
|
-
const schemaMap = /* @__PURE__ */ new Map();
|
|
1881
|
-
for (const schema of schemas) if (schema.name) schemaMap.set(schema.name, schema);
|
|
1882
|
-
const result = /* @__PURE__ */ new Set();
|
|
1883
|
-
function visitSchema(schema) {
|
|
1884
|
-
const directRefs = collectReferencedSchemaNames(schema);
|
|
1885
|
-
for (const name of directRefs) if (!result.has(name)) {
|
|
1886
|
-
result.add(name);
|
|
1887
|
-
const namedSchema = schemaMap.get(name);
|
|
1888
|
-
if (namedSchema) visitSchema(namedSchema);
|
|
1889
|
-
}
|
|
1890
|
-
}
|
|
1891
|
-
for (const op of operations) for (const schema of collectLazy(op, {
|
|
1892
|
-
depth: "shallow",
|
|
1893
|
-
schema: (node) => node
|
|
1894
|
-
})) visitSchema(schema);
|
|
1895
|
-
return result;
|
|
1896
|
-
}
|
|
1897
|
-
function collectUsedSchemaNames(operations, schemas) {
|
|
1898
|
-
return collectUsedSchemaNamesMemo(operations)(schemas);
|
|
1899
|
-
}
|
|
1900
|
-
const EMPTY_CIRCULAR_SET = /* @__PURE__ */ new Set();
|
|
1901
|
-
const findCircularSchemasMemo = memoize(/* @__PURE__ */ new WeakMap(), (schemas) => {
|
|
1902
|
-
const graph = /* @__PURE__ */ new Map();
|
|
1903
|
-
for (const schema of schemas) {
|
|
1904
|
-
if (!schema.name) continue;
|
|
1905
|
-
graph.set(schema.name, collectReferencedSchemaNames(schema));
|
|
1906
|
-
}
|
|
1907
|
-
const circular = /* @__PURE__ */ new Set();
|
|
1908
|
-
for (const start of graph.keys()) {
|
|
1909
|
-
const visited = /* @__PURE__ */ new Set();
|
|
1910
|
-
const stack = [...graph.get(start) ?? []];
|
|
1911
|
-
while (stack.length > 0) {
|
|
1912
|
-
const node = stack.pop();
|
|
1913
|
-
if (node === start) {
|
|
1914
|
-
circular.add(start);
|
|
1915
|
-
break;
|
|
1916
|
-
}
|
|
1917
|
-
if (visited.has(node)) continue;
|
|
1918
|
-
visited.add(node);
|
|
1919
|
-
const next = graph.get(node);
|
|
1920
|
-
if (next) for (const r of next) stack.push(r);
|
|
1921
|
-
}
|
|
1922
|
-
}
|
|
1923
|
-
return circular;
|
|
1924
|
-
});
|
|
1925
|
-
/**
|
|
1926
|
-
* Identifies all schemas that participate in circular dependency chains, including direct self-loops.
|
|
1927
|
-
*
|
|
1928
|
-
* Returns a Set of schema names with circular dependencies. Use this to wrap recursive schema positions
|
|
1929
|
-
* in deferred constructs (lazy getter, `z.lazy(() => …)`) to prevent infinite recursion when generated code runs.
|
|
1930
|
-
* Refs are followed by name only, keeping the algorithm linear in the schema graph size.
|
|
1931
|
-
*
|
|
1932
|
-
* @note Call this once on the full schema graph, then use `containsCircularRef()` to check individual schemas.
|
|
1933
|
-
*/
|
|
1934
|
-
function findCircularSchemas(schemas) {
|
|
1935
|
-
if (schemas.length === 0) return EMPTY_CIRCULAR_SET;
|
|
1936
|
-
return findCircularSchemasMemo(schemas);
|
|
1937
|
-
}
|
|
1938
|
-
/**
|
|
1939
|
-
* Type guard returning `true` when a schema or anything nested within it contains a ref to a circular schema.
|
|
1940
|
-
*
|
|
1941
|
-
* Use `excludeName` to ignore refs to specific schemas (useful when self-references are handled separately).
|
|
1942
|
-
* Commonly used with `findCircularSchemas()` to detect where lazy wrappers are needed in code generation.
|
|
1943
|
-
*
|
|
1944
|
-
* @note Returns `true` for the first matching circular ref found. Use for fast dependency checks.
|
|
1945
|
-
*/
|
|
1946
|
-
function containsCircularRef(node, { circularSchemas, excludeName }) {
|
|
1947
|
-
if (!node || circularSchemas.size === 0) return false;
|
|
1948
|
-
for (const _ of collectLazy(node, { schema(child) {
|
|
1949
|
-
if (child.type !== "ref") return null;
|
|
1950
|
-
const name = resolveRefName(child);
|
|
1951
|
-
return name && name !== excludeName && circularSchemas.has(name) ? true : null;
|
|
1952
|
-
} })) return true;
|
|
1953
|
-
return false;
|
|
1954
|
-
}
|
|
1955
|
-
//#endregion
|
|
1956
|
-
//#region src/factory.ts
|
|
1957
|
-
/**
|
|
1958
|
-
* Identity-preserving node update: returns `node` unchanged when every field in
|
|
1959
|
-
* `changes` already equals (by reference) the current value, otherwise a new node
|
|
1960
|
-
* with the changes applied.
|
|
1961
|
-
*
|
|
1962
|
-
* Mirrors the TypeScript compiler's `factory.updateX` contract, pair it with the
|
|
1963
|
-
* structural sharing in {@link transform} so a no-op rewrite doesn't allocate and
|
|
1964
|
-
* downstream passes can detect "nothing changed" by identity. Comparison is
|
|
1965
|
-
* shallow: a structurally-equal but newly-allocated array/object counts as a change.
|
|
1966
|
-
*
|
|
1967
|
-
* @example
|
|
1968
|
-
* ```ts
|
|
1969
|
-
* update(node, { name: node.name }) // -> same `node` reference
|
|
1970
|
-
* update(node, { name: 'renamed' }) // -> new node, `name` replaced
|
|
1971
|
-
* ```
|
|
1972
|
-
*/
|
|
1973
|
-
function update(node, changes) {
|
|
1974
|
-
for (const key in changes) if (changes[key] !== node[key]) return {
|
|
1975
|
-
...node,
|
|
1976
|
-
...changes
|
|
1977
|
-
};
|
|
1978
|
-
return node;
|
|
1979
|
-
}
|
|
1980
|
-
/**
|
|
1981
|
-
* Creates a fully resolved `FileNode` from a file input descriptor.
|
|
1982
|
-
*
|
|
1983
|
-
* Computes:
|
|
1984
|
-
* - `id` SHA256 hash of the file path
|
|
1985
|
-
* - `name` `baseName` without extension
|
|
1986
|
-
* - `extname` extension extracted from `baseName`
|
|
1987
|
-
*
|
|
1988
|
-
* Deduplicates:
|
|
1989
|
-
* - `sources` via `combineSources`
|
|
1990
|
-
* - `exports` via `combineExports`
|
|
1991
|
-
* - `imports` via `combineImports` (also filters unused imports)
|
|
1992
|
-
*
|
|
1993
|
-
* @throws {Error} when `baseName` has no extension.
|
|
1994
|
-
*
|
|
1995
|
-
* @example
|
|
1996
|
-
* ```ts
|
|
1997
|
-
* const file = createFile({
|
|
1998
|
-
* baseName: 'petStore.ts',
|
|
1999
|
-
* path: 'src/models/petStore.ts',
|
|
2000
|
-
* sources: [createSource({ name: 'Pet', nodes: [createText('export type Pet = { id: number }')] })],
|
|
2001
|
-
* imports: [createImport({ name: ['z'], path: 'zod' })],
|
|
2002
|
-
* exports: [createExport({ name: ['Pet'], path: './petStore' })],
|
|
2003
|
-
* })
|
|
2004
|
-
* // file.id = SHA256 hash of 'src/models/petStore.ts'
|
|
2005
|
-
* // file.name = 'petStore'
|
|
2006
|
-
* // file.extname = '.ts'
|
|
2007
|
-
* ```
|
|
2008
|
-
*/
|
|
2009
|
-
function createFile(input) {
|
|
2010
|
-
const extname = path.extname(input.baseName) || (input.baseName.startsWith(".") ? input.baseName : "");
|
|
2011
|
-
if (!extname) throw new Error(`No extname found for ${input.baseName}`);
|
|
2012
|
-
const source = (input.sources ?? []).flatMap((item) => item.nodes ?? []).map((node) => extractStringsFromNodes([node])).filter(Boolean).join("\n\n");
|
|
2013
|
-
const resolvedExports = input.exports?.length ? combineExports(input.exports) : [];
|
|
2014
|
-
const combinedImports = input.imports?.length ? combineImports(input.imports, resolvedExports, source || void 0) : [];
|
|
2015
|
-
const localNames = new Set((input.sources ?? []).map((item) => item.name).filter((name) => Boolean(name)));
|
|
2016
|
-
const nameOf = (item) => typeof item === "string" ? item : item.name ?? item.propertyName;
|
|
2017
|
-
const resolvedImports = combinedImports.filter((imp) => imp.path !== input.path).flatMap((imp) => {
|
|
2018
|
-
if (!Array.isArray(imp.name)) return typeof imp.name === "string" && localNames.has(imp.name) ? [] : [imp];
|
|
2019
|
-
const kept = imp.name.filter((item) => !localNames.has(nameOf(item)));
|
|
2020
|
-
if (!kept.length) return [];
|
|
2021
|
-
return [kept.length === imp.name.length ? imp : {
|
|
2022
|
-
...imp,
|
|
2023
|
-
name: kept
|
|
2024
|
-
}];
|
|
2025
|
-
});
|
|
2026
|
-
const resolvedSources = input.sources?.length ? combineSources(input.sources) : [];
|
|
2027
|
-
return {
|
|
2028
|
-
kind: "File",
|
|
2029
|
-
...input,
|
|
2030
|
-
id: hash("sha256", input.path, "hex"),
|
|
2031
|
-
name: trimExtName(input.baseName),
|
|
2032
|
-
extname,
|
|
2033
|
-
imports: resolvedImports,
|
|
2034
|
-
exports: resolvedExports,
|
|
2035
|
-
sources: resolvedSources,
|
|
2036
|
-
meta: input.meta ?? {}
|
|
2037
|
-
};
|
|
2038
|
-
}
|
|
2039
|
-
//#endregion
|
|
2040
|
-
//#region src/printer.ts
|
|
2041
|
-
/**
|
|
2042
|
-
* Defines a schema printer: a function that takes a `SchemaNode` and emits
|
|
2043
|
-
* code in your target language. Each plugin that produces code from schemas
|
|
2044
|
-
* (TypeScript types, Zod schemas, Faker factories) ships a printer built
|
|
2045
|
-
* with this helper.
|
|
2046
|
-
*
|
|
2047
|
-
* The builder receives resolved options and returns:
|
|
2048
|
-
*
|
|
2049
|
-
* - `name` unique identifier for the printer.
|
|
2050
|
-
* - `options` stored on the returned printer instance.
|
|
2051
|
-
* - `nodes` map of `SchemaType` → handler. Handlers return the rendered
|
|
2052
|
-
* output (a string, a TypeScript AST node, ...) for that schema type.
|
|
2053
|
-
* - `print` (optional), top-level override exposed as `printer.print`.
|
|
2054
|
-
* Use `this.transform(node)` inside it to dispatch to `nodes` recursively.
|
|
2055
|
-
*
|
|
2056
|
-
* Without a `print` override, `printer.print` falls back to `printer.transform`
|
|
2057
|
-
* (the node-level dispatcher).
|
|
2058
|
-
*
|
|
2059
|
-
* @example Tiny Zod printer
|
|
2060
|
-
* ```ts
|
|
2061
|
-
* import { definePrinter, type PrinterFactoryOptions } from '@kubb/ast'
|
|
2062
|
-
*
|
|
2063
|
-
* type PrinterZod = PrinterFactoryOptions<'zod', { strict?: boolean }, string>
|
|
2064
|
-
*
|
|
2065
|
-
* export const zodPrinter = definePrinter<PrinterZod>((options) => ({
|
|
2066
|
-
* name: 'zod',
|
|
2067
|
-
* options: { strict: options.strict ?? true },
|
|
2068
|
-
* nodes: {
|
|
2069
|
-
* string: () => 'z.string()',
|
|
2070
|
-
* object(node) {
|
|
2071
|
-
* const props = node.properties
|
|
2072
|
-
* .map((p) => `${p.name}: ${this.transform(p.schema)}`)
|
|
2073
|
-
* .join(', ')
|
|
2074
|
-
* return `z.object({ ${props} })`
|
|
2075
|
-
* },
|
|
2076
|
-
* },
|
|
2077
|
-
* }))
|
|
2078
|
-
* ```
|
|
2079
|
-
*/
|
|
2080
|
-
function definePrinter(build) {
|
|
2081
|
-
return createPrinterFactory((node) => node.type)(build);
|
|
2082
|
-
}
|
|
2083
|
-
/**
|
|
2084
|
-
* Generic printer-factory function used by `definePrinter` and `defineFunctionPrinter`.
|
|
2085
|
-
**
|
|
2086
|
-
* @example
|
|
2087
|
-
* ```ts
|
|
2088
|
-
* export const defineFunctionPrinter = createPrinterFactory<FunctionNode, FunctionNodeType, FunctionNodeByType>(
|
|
2089
|
-
* (node) => kindToHandlerKey[node.kind],
|
|
2090
|
-
* )
|
|
457
|
+
* export const defineFunctionPrinter = createPrinterFactory<FunctionParamNode, FunctionParamKind, Partial<Record<FunctionParamKind, FunctionParamNode>>>(
|
|
458
|
+
* (node) => node.kind,
|
|
459
|
+
* )
|
|
2091
460
|
* ```
|
|
2092
461
|
*/
|
|
2093
462
|
function createPrinterFactory(getKey) {
|
|
@@ -2114,113 +483,6 @@ function createPrinterFactory(getKey) {
|
|
|
2114
483
|
};
|
|
2115
484
|
}
|
|
2116
485
|
//#endregion
|
|
2117
|
-
|
|
2118
|
-
/**
|
|
2119
|
-
* Replaces a discriminator property's schema with a string enum of allowed values.
|
|
2120
|
-
*
|
|
2121
|
-
* If `node` is not an object schema, or if the property does not exist, the input
|
|
2122
|
-
* node is returned as-is.
|
|
2123
|
-
*
|
|
2124
|
-
* @example
|
|
2125
|
-
* ```ts
|
|
2126
|
-
* const schema = createSchema({
|
|
2127
|
-
* type: 'object',
|
|
2128
|
-
* properties: [createProperty({ name: 'type', required: true, schema: createSchema({ type: 'string' }) })],
|
|
2129
|
-
* })
|
|
2130
|
-
* const result = setDiscriminatorEnum({ node: schema, propertyName: 'type', values: ['dog', 'cat'] })
|
|
2131
|
-
* ```
|
|
2132
|
-
*/
|
|
2133
|
-
function setDiscriminatorEnum({ node, propertyName, values, enumName }) {
|
|
2134
|
-
const objectNode = narrowSchema(node, "object");
|
|
2135
|
-
if (!objectNode?.properties?.length) return node;
|
|
2136
|
-
if (!objectNode.properties.some((prop) => prop.name === propertyName)) return node;
|
|
2137
|
-
return createSchema({
|
|
2138
|
-
...objectNode,
|
|
2139
|
-
properties: objectNode.properties.map((prop) => {
|
|
2140
|
-
if (prop.name !== propertyName) return prop;
|
|
2141
|
-
return createProperty({
|
|
2142
|
-
...prop,
|
|
2143
|
-
schema: createSchema({
|
|
2144
|
-
type: "enum",
|
|
2145
|
-
primitive: "string",
|
|
2146
|
-
enumValues: values,
|
|
2147
|
-
name: enumName,
|
|
2148
|
-
readOnly: prop.schema.readOnly,
|
|
2149
|
-
writeOnly: prop.schema.writeOnly
|
|
2150
|
-
})
|
|
2151
|
-
});
|
|
2152
|
-
})
|
|
2153
|
-
});
|
|
2154
|
-
}
|
|
2155
|
-
/**
|
|
2156
|
-
* Merges adjacent anonymous object members into a single anonymous object member.
|
|
2157
|
-
*
|
|
2158
|
-
* @example
|
|
2159
|
-
* ```ts
|
|
2160
|
-
* const merged = mergeAdjacentObjects([
|
|
2161
|
-
* createSchema({ type: 'object', properties: [createProperty({ name: 'a', schema: createSchema({ type: 'string' }) })] }),
|
|
2162
|
-
* createSchema({ type: 'object', properties: [createProperty({ name: 'b', schema: createSchema({ type: 'number' }) })] }),
|
|
2163
|
-
* ])
|
|
2164
|
-
* ```
|
|
2165
|
-
*/
|
|
2166
|
-
function* mergeAdjacentObjectsLazy(members) {
|
|
2167
|
-
let acc;
|
|
2168
|
-
for (const member of members) {
|
|
2169
|
-
const objectMember = narrowSchema(member, "object");
|
|
2170
|
-
if (objectMember && !objectMember.name && acc !== void 0) {
|
|
2171
|
-
const accObject = narrowSchema(acc, "object");
|
|
2172
|
-
if (accObject && !accObject.name) {
|
|
2173
|
-
acc = createSchema({
|
|
2174
|
-
...accObject,
|
|
2175
|
-
properties: [...accObject.properties ?? [], ...objectMember.properties ?? []]
|
|
2176
|
-
});
|
|
2177
|
-
continue;
|
|
2178
|
-
}
|
|
2179
|
-
}
|
|
2180
|
-
if (acc !== void 0) yield acc;
|
|
2181
|
-
acc = member;
|
|
2182
|
-
}
|
|
2183
|
-
if (acc !== void 0) yield acc;
|
|
2184
|
-
}
|
|
2185
|
-
/**
|
|
2186
|
-
* Removes enum members that are covered by broader scalar primitives in the same union.
|
|
2187
|
-
*
|
|
2188
|
-
* @example
|
|
2189
|
-
* ```ts
|
|
2190
|
-
* const simplified = simplifyUnion([
|
|
2191
|
-
* createSchema({ type: 'enum', primitive: 'string', enumValues: ['active'] }),
|
|
2192
|
-
* createSchema({ type: 'string' }),
|
|
2193
|
-
* ])
|
|
2194
|
-
* // keeps only string member
|
|
2195
|
-
* ```
|
|
2196
|
-
*/
|
|
2197
|
-
function simplifyUnion(members) {
|
|
2198
|
-
const scalarPrimitives = new Set(members.filter((member) => isScalarPrimitive(member.type)).map((m) => m.type));
|
|
2199
|
-
if (!scalarPrimitives.size) return members;
|
|
2200
|
-
return members.filter((member) => {
|
|
2201
|
-
const enumNode = narrowSchema(member, "enum");
|
|
2202
|
-
if (!enumNode) return true;
|
|
2203
|
-
const primitive = enumNode.primitive;
|
|
2204
|
-
if (!primitive) return true;
|
|
2205
|
-
if ((enumNode.namedEnumValues?.length ?? enumNode.enumValues?.length ?? 0) <= 1) return true;
|
|
2206
|
-
if (scalarPrimitives.has(primitive)) return false;
|
|
2207
|
-
if ((primitive === "integer" || primitive === "number") && (scalarPrimitives.has("integer") || scalarPrimitives.has("number"))) return false;
|
|
2208
|
-
return true;
|
|
2209
|
-
});
|
|
2210
|
-
}
|
|
2211
|
-
function setEnumName(propNode, parentName, propName, enumSuffix) {
|
|
2212
|
-
const enumNode = narrowSchema(propNode, "enum");
|
|
2213
|
-
if (enumNode?.primitive === "boolean") return {
|
|
2214
|
-
...propNode,
|
|
2215
|
-
name: null
|
|
2216
|
-
};
|
|
2217
|
-
if (enumNode) return {
|
|
2218
|
-
...propNode,
|
|
2219
|
-
name: enumPropName(parentName, propName, enumSuffix)
|
|
2220
|
-
};
|
|
2221
|
-
return propNode;
|
|
2222
|
-
}
|
|
2223
|
-
//#endregion
|
|
2224
|
-
export { applyDedupe, arrowFunctionDef, breakDef, buildDedupePlan, caseParams, collect, collectUsedSchemaNames, constDef, containsCircularRef, contentDef, createArrowFunction, createBreak, createConst, createDiscriminantNode, createExport, createFile, createFunction, createFunctionParameter, createFunctionParameters, createImport, createIndexedAccessType, createInput, createJsx, createObjectBindingPattern, createOperation, createOperationParams, createOutput, createParameter, createPrinterFactory, createProperty, createResponse, createSchema, createSource, createStreamInput, createText, createType, createTypeLiteral, defineNode, definePrinter, defineSchemaDialect, exportDef, extractStringsFromNodes, fileDef, findCircularSchemas, functionDef, functionParameterDef, functionParametersDef, httpMethods, importDef, indexedAccessTypeDef, inputDef, isHttpOperationNode, isStringType, jsxDef, mergeAdjacentObjectsLazy, narrowSchema, objectBindingPatternDef, operationDef, outputDef, parameterDef, propertyDef, requestBodyDef, responseDef, schemaDef, schemaTypes, setDiscriminatorEnum, setEnumName, signatureOf, simplifyUnion, sourceDef, syncOptionality, syncSchemaRef, textDef, transform, typeDef, typeLiteralDef, update, walk };
|
|
486
|
+
export { applyDedupe, arrowFunctionDef, breakDef, buildDedupePlan, collect, constDef, contentDef, createPrinterFactory, defineNode, definePrinter, defineSchemaDialect, exportDef, extractStringsFromNodes, factory_exports as factory, fileDef, functionDef, functionParameterDef, functionParametersDef, httpMethods, importDef, indexedAccessTypeDef, inputDef, isHttpOperationNode, jsxDef, mergeAdjacentObjectsLazy, narrowSchema, nodeDefs, objectBindingPatternDef, operationDef, outputDef, parameterDef, propertyDef, requestBodyDef, responseDef, schemaDef, schemaTypes, setDiscriminatorEnum, setEnumName, signatureOf, simplifyUnion, sourceDef, syncOptionality, textDef, transform, typeDef, typeLiteralDef, walk };
|
|
2225
487
|
|
|
2226
488
|
//# sourceMappingURL=index.js.map
|