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