@kubb/ast 5.0.0-beta.6 → 5.0.0-beta.60
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/LICENSE +17 -10
- package/README.md +50 -27
- package/dist/chunk-CNktS9qV.js +17 -0
- package/dist/extractStringsFromNodes-WMYJ8nQL.d.ts +82 -0
- package/dist/factory-Cl8Z7mcc.cjs +299 -0
- package/dist/factory-Cl8Z7mcc.cjs.map +1 -0
- package/dist/factory-Du7nEP4B.js +282 -0
- package/dist/factory-Du7nEP4B.js.map +1 -0
- package/dist/factory.cjs +29 -0
- package/dist/factory.d.ts +62 -0
- package/dist/factory.js +3 -0
- package/dist/index-BzjwdK2M.d.ts +2433 -0
- package/dist/index.cjs +442 -2180
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.ts +93 -3408
- package/dist/index.js +392 -2101
- 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/response-DS5S3IG4.cjs +1058 -0
- package/dist/response-DS5S3IG4.cjs.map +1 -0
- package/dist/types-olVl9v5p.d.ts +764 -0
- package/dist/types.cjs +0 -0
- package/dist/types.d.ts +5 -0
- package/dist/types.js +1 -0
- package/dist/utils-D83JA6Xx.cjs +1645 -0
- package/dist/utils-D83JA6Xx.cjs.map +1 -0
- package/dist/utils-Dj_KoXMv.js +1389 -0
- package/dist/utils-Dj_KoXMv.js.map +1 -0
- package/dist/utils.cjs +34 -0
- package/dist/utils.d.ts +332 -0
- package/dist/utils.js +3 -0
- package/package.json +17 -6
- package/src/constants.ts +19 -64
- package/src/dedupe.ts +239 -0
- package/src/dialect.ts +53 -0
- package/src/factory.ts +67 -678
- package/src/guards.ts +10 -92
- package/src/index.ts +16 -43
- package/src/infer.ts +16 -14
- package/src/mocks.ts +7 -127
- package/src/node.ts +128 -0
- package/src/nodes/base.ts +5 -12
- package/src/nodes/code.ts +165 -74
- package/src/nodes/content.ts +56 -0
- package/src/nodes/file.ts +97 -36
- package/src/nodes/function.ts +216 -156
- package/src/nodes/http.ts +1 -35
- package/src/nodes/index.ts +23 -15
- package/src/nodes/input.ts +140 -0
- package/src/nodes/operation.ts +122 -68
- package/src/nodes/output.ts +23 -0
- package/src/nodes/parameter.ts +33 -3
- package/src/nodes/property.ts +36 -3
- package/src/nodes/requestBody.ts +61 -0
- package/src/nodes/response.ts +58 -13
- package/src/nodes/schema.ts +93 -17
- package/src/printer.ts +48 -42
- package/src/registry.ts +75 -0
- package/src/signature.ts +207 -0
- package/src/transformers.ts +50 -18
- package/src/types.ts +7 -68
- 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 +11 -0
- package/src/utils/operationParams.ts +353 -0
- package/src/utils/refs.ts +112 -0
- package/src/utils/schemaGraph.ts +169 -0
- package/src/utils/schemaTraversal.ts +86 -0
- package/src/utils/strings.ts +139 -0
- package/src/visitor.ts +227 -289
- package/dist/chunk--u3MIqq1.js +0 -8
- package/src/nodes/root.ts +0 -64
- package/src/refs.ts +0 -67
- package/src/resolvers.ts +0 -45
- package/src/utils.ts +0 -915
package/package.json
CHANGED
|
@@ -1,12 +1,11 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@kubb/ast",
|
|
3
|
-
"version": "5.0.0-beta.
|
|
4
|
-
"description": "Spec-agnostic AST layer for Kubb. Defines
|
|
3
|
+
"version": "5.0.0-beta.60",
|
|
4
|
+
"description": "Spec-agnostic AST layer for Kubb. Defines the node tree, visitor pattern, factory functions, and type guards used across all code generation plugins.",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"ast",
|
|
7
7
|
"codegen",
|
|
8
8
|
"kubb",
|
|
9
|
-
"openapi",
|
|
10
9
|
"typescript"
|
|
11
10
|
],
|
|
12
11
|
"license": "MIT",
|
|
@@ -24,7 +23,6 @@
|
|
|
24
23
|
"!/**/__snapshots__/**"
|
|
25
24
|
],
|
|
26
25
|
"type": "module",
|
|
27
|
-
"sideEffects": false,
|
|
28
26
|
"main": "./dist/index.cjs",
|
|
29
27
|
"module": "./dist/index.js",
|
|
30
28
|
"types": "./dist/index.d.ts",
|
|
@@ -33,6 +31,18 @@
|
|
|
33
31
|
"import": "./dist/index.js",
|
|
34
32
|
"require": "./dist/index.cjs"
|
|
35
33
|
},
|
|
34
|
+
"./factory": {
|
|
35
|
+
"import": "./dist/factory.js",
|
|
36
|
+
"require": "./dist/factory.cjs"
|
|
37
|
+
},
|
|
38
|
+
"./types": {
|
|
39
|
+
"import": "./dist/types.js",
|
|
40
|
+
"require": "./dist/types.cjs"
|
|
41
|
+
},
|
|
42
|
+
"./utils": {
|
|
43
|
+
"import": "./dist/utils.js",
|
|
44
|
+
"require": "./dist/utils.cjs"
|
|
45
|
+
},
|
|
36
46
|
"./package.json": "./package.json"
|
|
37
47
|
},
|
|
38
48
|
"publishConfig": {
|
|
@@ -40,7 +50,7 @@
|
|
|
40
50
|
"registry": "https://registry.npmjs.org/"
|
|
41
51
|
},
|
|
42
52
|
"devDependencies": {
|
|
43
|
-
"@types/node": "^22.19.
|
|
53
|
+
"@types/node": "^22.19.21",
|
|
44
54
|
"@internals/utils": "0.0.0"
|
|
45
55
|
},
|
|
46
56
|
"engines": {
|
|
@@ -48,11 +58,12 @@
|
|
|
48
58
|
},
|
|
49
59
|
"scripts": {
|
|
50
60
|
"build": "tsdown",
|
|
51
|
-
"clean": "
|
|
61
|
+
"clean": "node -e \"require('node:fs').rmSync('./dist', {recursive:true,force:true})\"",
|
|
52
62
|
"lint": "oxlint .",
|
|
53
63
|
"lint:fix": "oxlint --fix .",
|
|
54
64
|
"release": "pnpm publish --no-git-check",
|
|
55
65
|
"release:canary": "bash ../../.github/canary.sh && node ../../scripts/build.js canary && pnpm publish --no-git-check",
|
|
66
|
+
"release:stage": "pnpm stage publish --no-git-check",
|
|
56
67
|
"start": "tsdown --watch",
|
|
57
68
|
"test": "vitest --passWithNoTests",
|
|
58
69
|
"typecheck": "tsc -p ./tsconfig.json --noEmit --emitDeclarationOnly false"
|
package/src/constants.ts
CHANGED
|
@@ -1,13 +1,11 @@
|
|
|
1
|
-
import type { NodeKind } from './nodes/base.ts'
|
|
2
|
-
import type { MediaType } from './nodes/http.ts'
|
|
3
1
|
import type { HttpMethod } from './nodes/operation.ts'
|
|
4
2
|
import type { SchemaType } from './nodes/schema.ts'
|
|
5
3
|
|
|
6
4
|
/**
|
|
7
5
|
* Traversal depth for AST visitor utilities.
|
|
8
6
|
*
|
|
9
|
-
* - `'shallow'`
|
|
10
|
-
* - `'deep'`
|
|
7
|
+
* - `'shallow'` visits only the immediate node, skipping children.
|
|
8
|
+
* - `'deep'` recursively visits all descendant nodes.
|
|
11
9
|
*/
|
|
12
10
|
export type VisitorDepth = 'shallow' | 'deep'
|
|
13
11
|
|
|
@@ -16,32 +14,11 @@ export const visitorDepths = {
|
|
|
16
14
|
deep: 'deep',
|
|
17
15
|
} as const satisfies Record<VisitorDepth, VisitorDepth>
|
|
18
16
|
|
|
19
|
-
export const nodeKinds = {
|
|
20
|
-
input: 'Input',
|
|
21
|
-
output: 'Output',
|
|
22
|
-
operation: 'Operation',
|
|
23
|
-
schema: 'Schema',
|
|
24
|
-
property: 'Property',
|
|
25
|
-
parameter: 'Parameter',
|
|
26
|
-
response: 'Response',
|
|
27
|
-
functionParameter: 'FunctionParameter',
|
|
28
|
-
parameterGroup: 'ParameterGroup',
|
|
29
|
-
functionParameters: 'FunctionParameters',
|
|
30
|
-
type: 'Type',
|
|
31
|
-
file: 'File',
|
|
32
|
-
import: 'Import',
|
|
33
|
-
export: 'Export',
|
|
34
|
-
source: 'Source',
|
|
35
|
-
text: 'Text',
|
|
36
|
-
break: 'Break',
|
|
37
|
-
} as const satisfies Record<string, NodeKind>
|
|
38
|
-
|
|
39
17
|
/**
|
|
40
18
|
* Schema type discriminators used by all AST schema nodes.
|
|
41
19
|
*
|
|
42
|
-
*
|
|
43
|
-
*
|
|
44
|
-
* and format-specific types (`date`, `uuid`, `email`). Use `isScalarPrimitive()` to check for scalar types.
|
|
20
|
+
* Each value is a stable discriminator across the AST (for example `schema.type === schemaTypes.object`).
|
|
21
|
+
* Call `isScalarPrimitive()` to check for the scalar types.
|
|
45
22
|
*/
|
|
46
23
|
export const schemaTypes = {
|
|
47
24
|
/**
|
|
@@ -61,7 +38,7 @@ export const schemaTypes = {
|
|
|
61
38
|
*/
|
|
62
39
|
bigint: 'bigint',
|
|
63
40
|
/**
|
|
64
|
-
* Boolean value
|
|
41
|
+
* Boolean value.
|
|
65
42
|
*/
|
|
66
43
|
boolean: 'boolean',
|
|
67
44
|
/**
|
|
@@ -154,15 +131,12 @@ export type ScalarPrimitive = 'string' | 'number' | 'integer' | 'bigint' | 'bool
|
|
|
154
131
|
|
|
155
132
|
/**
|
|
156
133
|
* Scalar primitive schema types used for union simplification and type narrowing.
|
|
157
|
-
*
|
|
158
|
-
* Use `isScalarPrimitive()` to safely check whether a type is a scalar primitive.
|
|
159
134
|
*/
|
|
160
|
-
|
|
135
|
+
const SCALAR_PRIMITIVE_TYPES = new Set<ScalarPrimitive>(['string', 'number', 'integer', 'bigint', 'boolean'])
|
|
161
136
|
|
|
162
137
|
/**
|
|
163
|
-
*
|
|
164
|
-
*
|
|
165
|
-
* Use this to check if a schema type can be directly assigned without wrapping (e.g., `string | number | boolean`).
|
|
138
|
+
* Returns `true` when `type` is a scalar primitive that can be assigned without wrapping
|
|
139
|
+
* (for example `string | number | boolean`).
|
|
166
140
|
*/
|
|
167
141
|
export function isScalarPrimitive(type: string): type is ScalarPrimitive {
|
|
168
142
|
return SCALAR_PRIMITIVE_TYPES.has(type as ScalarPrimitive)
|
|
@@ -170,8 +144,6 @@ export function isScalarPrimitive(type: string): type is ScalarPrimitive {
|
|
|
170
144
|
|
|
171
145
|
/**
|
|
172
146
|
* HTTP method identifiers used by operation nodes.
|
|
173
|
-
*
|
|
174
|
-
* Includes all standard HTTP methods (GET, POST, PUT, PATCH, DELETE, HEAD, OPTIONS, TRACE).
|
|
175
147
|
*/
|
|
176
148
|
export const httpMethods = {
|
|
177
149
|
get: 'GET',
|
|
@@ -185,10 +157,10 @@ export const httpMethods = {
|
|
|
185
157
|
} as const satisfies Record<Lowercase<HttpMethod>, HttpMethod>
|
|
186
158
|
|
|
187
159
|
/**
|
|
188
|
-
* Default concurrency limit for `walk()` traversal utility.
|
|
160
|
+
* Default concurrency limit for the `walk()` traversal utility.
|
|
189
161
|
*
|
|
190
|
-
* Set to 30 to balance I/O-bound resolver parallelism against event
|
|
191
|
-
*
|
|
162
|
+
* Set to 30 to balance I/O-bound resolver parallelism against event-loop and memory pressure
|
|
163
|
+
* during large spec traversals. Override it for different hardware constraints.
|
|
192
164
|
*
|
|
193
165
|
* @example
|
|
194
166
|
* ```ts
|
|
@@ -200,29 +172,12 @@ export const httpMethods = {
|
|
|
200
172
|
export const WALK_CONCURRENCY = 30
|
|
201
173
|
|
|
202
174
|
/**
|
|
203
|
-
*
|
|
204
|
-
*
|
|
205
|
-
|
|
206
|
-
|
|
175
|
+
* Number of spaces in one indentation level when assembling multi-line code as strings.
|
|
176
|
+
* Set to 2, 3, … to change the indent width used by `buildObject`/`buildList`.
|
|
177
|
+
*/
|
|
178
|
+
const INDENT_SIZE = 2
|
|
179
|
+
|
|
180
|
+
/**
|
|
181
|
+
* One indentation level, derived from {@link INDENT_SIZE}.
|
|
207
182
|
*/
|
|
208
|
-
export const
|
|
209
|
-
applicationJson: 'application/json',
|
|
210
|
-
applicationXml: 'application/xml',
|
|
211
|
-
applicationFormUrlEncoded: 'application/x-www-form-urlencoded',
|
|
212
|
-
applicationOctetStream: 'application/octet-stream',
|
|
213
|
-
applicationPdf: 'application/pdf',
|
|
214
|
-
applicationZip: 'application/zip',
|
|
215
|
-
applicationGraphql: 'application/graphql',
|
|
216
|
-
multipartFormData: 'multipart/form-data',
|
|
217
|
-
textPlain: 'text/plain',
|
|
218
|
-
textHtml: 'text/html',
|
|
219
|
-
textCsv: 'text/csv',
|
|
220
|
-
textXml: 'text/xml',
|
|
221
|
-
imagePng: 'image/png',
|
|
222
|
-
imageJpeg: 'image/jpeg',
|
|
223
|
-
imageGif: 'image/gif',
|
|
224
|
-
imageWebp: 'image/webp',
|
|
225
|
-
imageSvgXml: 'image/svg+xml',
|
|
226
|
-
audioMpeg: 'audio/mpeg',
|
|
227
|
-
videoMp4: 'video/mp4',
|
|
228
|
-
} as const satisfies Record<string, MediaType>
|
|
183
|
+
export const INDENT = Array.from({ length: INDENT_SIZE }, () => ' ').join('')
|
package/src/dedupe.ts
ADDED
|
@@ -0,0 +1,239 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Schema-shape deduplication. `buildDedupePlan` finds top-level and inline schemas that share a
|
|
3
|
+
* structural signature, picks one canonical definition, and `applyDedupe` repoints every duplicate
|
|
4
|
+
* at it. This works on `SchemaNode` content, not on files.
|
|
5
|
+
*
|
|
6
|
+
* For merging a file's imports, exports, and source nodes, see `utils/fileMerge.ts`. Same idea of
|
|
7
|
+
* collapsing duplicates, but a different domain.
|
|
8
|
+
*/
|
|
9
|
+
import type { Node, OperationNode, SchemaNode } from './nodes/index.ts'
|
|
10
|
+
import { createSchema } from './nodes/schema.ts'
|
|
11
|
+
import { signatureOf } from './signature.ts'
|
|
12
|
+
import { extractRefName } from './utils/index.ts'
|
|
13
|
+
import { collectLazy, transform } from './visitor.ts'
|
|
14
|
+
|
|
15
|
+
/**
|
|
16
|
+
* A canonical destination for a deduplicated shape: the shared schema name and
|
|
17
|
+
* the synthetic `$ref` path that points at it.
|
|
18
|
+
*/
|
|
19
|
+
export type DedupeCanonical = {
|
|
20
|
+
/**
|
|
21
|
+
* Canonical schema name every duplicate occurrence refers to.
|
|
22
|
+
*/
|
|
23
|
+
name: string
|
|
24
|
+
/**
|
|
25
|
+
* `$ref` path stored on the generated `ref` nodes (for example `#/components/schemas/Status`).
|
|
26
|
+
*/
|
|
27
|
+
ref: string
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
/**
|
|
31
|
+
* The result of {@link buildDedupePlan}: a lookup from structural signature to its
|
|
32
|
+
* canonical target, plus the freshly hoisted definitions that must be added to
|
|
33
|
+
* the schema list.
|
|
34
|
+
*/
|
|
35
|
+
export type DedupePlan = {
|
|
36
|
+
/**
|
|
37
|
+
* Maps a structural signature to the canonical schema that represents it.
|
|
38
|
+
*/
|
|
39
|
+
canonicalBySignature: Map<string, DedupeCanonical>
|
|
40
|
+
/**
|
|
41
|
+
* Maps the name of a top-level schema that duplicates a canonical one to that canonical, so
|
|
42
|
+
* references to the duplicate can be repointed at the first schema with the same content.
|
|
43
|
+
*/
|
|
44
|
+
aliasNames: Map<string, DedupeCanonical>
|
|
45
|
+
/**
|
|
46
|
+
* New top-level schema definitions created for inline shapes that had no existing
|
|
47
|
+
* named component. Nested duplicates inside each definition are already collapsed.
|
|
48
|
+
*/
|
|
49
|
+
hoisted: Array<SchemaNode>
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
/**
|
|
53
|
+
* The lookups {@link applyDedupe} needs from a {@link DedupePlan}.
|
|
54
|
+
*/
|
|
55
|
+
export type DedupeLookups = Pick<DedupePlan, 'canonicalBySignature' | 'aliasNames'>
|
|
56
|
+
|
|
57
|
+
/**
|
|
58
|
+
* Options that inject the naming and candidate policy into {@link buildDedupePlan}.
|
|
59
|
+
* The mechanics (grouping, counting, rewriting) live here. The policy lives in the caller.
|
|
60
|
+
*/
|
|
61
|
+
export type BuildDedupePlanOptions = {
|
|
62
|
+
/**
|
|
63
|
+
* Returns `true` when a node should be deduplicated. This is the only gate, so it must
|
|
64
|
+
* reject both ineligible kinds (return `false` for anything other than, say, enums and
|
|
65
|
+
* objects) and unsafe shapes (e.g. nodes that reference a circular schema).
|
|
66
|
+
*/
|
|
67
|
+
isCandidate: (node: SchemaNode) => boolean
|
|
68
|
+
/**
|
|
69
|
+
* Produces the canonical name for an inline shape with no existing named component.
|
|
70
|
+
* Return `null` to leave the shape inline (for example when no contextual name exists).
|
|
71
|
+
*/
|
|
72
|
+
nameFor: (node: SchemaNode, signature: string) => string | null
|
|
73
|
+
/**
|
|
74
|
+
* Builds the `$ref` path for a canonical name.
|
|
75
|
+
*/
|
|
76
|
+
refFor: (name: string) => string
|
|
77
|
+
/**
|
|
78
|
+
* Minimum number of occurrences before a shape is deduplicated.
|
|
79
|
+
*
|
|
80
|
+
* @default 2
|
|
81
|
+
*/
|
|
82
|
+
minOccurrences?: number
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
/**
|
|
86
|
+
* Builds the shared `ref` replacement for a duplicate occurrence, carrying the
|
|
87
|
+
* usage-slot and documentation fields that are not part of the canonical type.
|
|
88
|
+
*/
|
|
89
|
+
function createRefNode(node: SchemaNode, canonical: DedupeCanonical): SchemaNode {
|
|
90
|
+
return createSchema({
|
|
91
|
+
type: 'ref',
|
|
92
|
+
name: canonical.name,
|
|
93
|
+
ref: canonical.ref,
|
|
94
|
+
optional: node.optional,
|
|
95
|
+
nullish: node.nullish,
|
|
96
|
+
readOnly: node.readOnly,
|
|
97
|
+
writeOnly: node.writeOnly,
|
|
98
|
+
deprecated: node.deprecated,
|
|
99
|
+
description: node.description,
|
|
100
|
+
default: node.default,
|
|
101
|
+
example: node.example,
|
|
102
|
+
})
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
/**
|
|
106
|
+
* Rewrites a node, replacing every candidate sub-schema whose signature has a canonical
|
|
107
|
+
* target with a `ref` to that target. Replacing a node with a `ref` prunes its subtree,
|
|
108
|
+
* so nested duplicates inside a replaced shape are not visited again. A `ref` that points
|
|
109
|
+
* at a duplicate top-level schema (see `aliasNames`) is repointed at the first schema with
|
|
110
|
+
* the same content.
|
|
111
|
+
*
|
|
112
|
+
* Pass `skipRootMatch` when rewriting a canonical definition so its own root is not
|
|
113
|
+
* turned into a reference to itself. Nested duplicates are still collapsed.
|
|
114
|
+
*
|
|
115
|
+
* @example
|
|
116
|
+
* ```ts
|
|
117
|
+
* const next = applyDedupe(operationNode, plan)
|
|
118
|
+
* ```
|
|
119
|
+
*/
|
|
120
|
+
export function applyDedupe(node: SchemaNode, plan: DedupeLookups, skipRootMatch?: boolean): SchemaNode
|
|
121
|
+
export function applyDedupe(node: OperationNode, plan: DedupeLookups, skipRootMatch?: boolean): OperationNode
|
|
122
|
+
export function applyDedupe(node: Node, plan: DedupeLookups, skipRootMatch = false): Node {
|
|
123
|
+
const { canonicalBySignature, aliasNames } = plan
|
|
124
|
+
if (canonicalBySignature.size === 0 && aliasNames.size === 0) return node
|
|
125
|
+
|
|
126
|
+
const root = node
|
|
127
|
+
|
|
128
|
+
return transform(node, {
|
|
129
|
+
schema(schemaNode) {
|
|
130
|
+
if (schemaNode.type === 'ref') {
|
|
131
|
+
const target = schemaNode.ref ? extractRefName(schemaNode.ref) : schemaNode.name
|
|
132
|
+
const canonical = target ? aliasNames.get(target) : undefined
|
|
133
|
+
|
|
134
|
+
return canonical ? { ...schemaNode, name: canonical.name, ref: canonical.ref } : undefined
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
const signature = signatureOf(schemaNode)
|
|
138
|
+
if (skipRootMatch && schemaNode === root) return undefined
|
|
139
|
+
|
|
140
|
+
const canonical = canonicalBySignature.get(signature)
|
|
141
|
+
if (!canonical) return undefined
|
|
142
|
+
|
|
143
|
+
return createRefNode(schemaNode, canonical)
|
|
144
|
+
},
|
|
145
|
+
})
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
/**
|
|
149
|
+
* Strips usage-slot flags from a hoisted definition and applies its canonical name.
|
|
150
|
+
* A standalone definition is never optional, so `optional`/`nullish` are cleared.
|
|
151
|
+
*/
|
|
152
|
+
function cleanDefinition(node: SchemaNode, name: string): SchemaNode {
|
|
153
|
+
return { ...node, name, optional: undefined, nullish: undefined }
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
/**
|
|
157
|
+
* Scans a forest of schema and operation nodes and produces a {@link DedupePlan}.
|
|
158
|
+
*
|
|
159
|
+
* A shape that occurs at least `minOccurrences` times is deduplicated: if any occurrence
|
|
160
|
+
* is a named top-level schema, the first one becomes the canonical (so other top-level
|
|
161
|
+
* duplicates and inline copies turn into references to it). Every other top-level name with
|
|
162
|
+
* the same content is recorded in `aliasNames`, so refs to it can be repointed at the
|
|
163
|
+
* canonical. Otherwise a new definition is hoisted using `nameFor`. The plan is then applied
|
|
164
|
+
* per node with {@link applyDedupe}.
|
|
165
|
+
*
|
|
166
|
+
* @example
|
|
167
|
+
* ```ts
|
|
168
|
+
* const plan = buildDedupePlan([...schemaNodes, ...operationNodes], {
|
|
169
|
+
* isCandidate: (node) => node.type === 'enum' || node.type === 'object',
|
|
170
|
+
* nameFor: (node) => node.name ?? null,
|
|
171
|
+
* refFor: (name) => `#/components/schemas/${name}`,
|
|
172
|
+
* })
|
|
173
|
+
* ```
|
|
174
|
+
*/
|
|
175
|
+
export function buildDedupePlan(roots: ReadonlyArray<Node>, options: BuildDedupePlanOptions): DedupePlan {
|
|
176
|
+
const { isCandidate, nameFor, refFor, minOccurrences = 2 } = options
|
|
177
|
+
|
|
178
|
+
const topLevelNodes = new Set<SchemaNode>()
|
|
179
|
+
|
|
180
|
+
type Group = {
|
|
181
|
+
count: number
|
|
182
|
+
representative: SchemaNode
|
|
183
|
+
topLevelNames: Array<string>
|
|
184
|
+
}
|
|
185
|
+
const groups = new Map<string, Group>()
|
|
186
|
+
|
|
187
|
+
function record(schemaNode: SchemaNode): void {
|
|
188
|
+
const signature = signatureOf(schemaNode)
|
|
189
|
+
if (!isCandidate(schemaNode)) return
|
|
190
|
+
|
|
191
|
+
const isTopLevel = topLevelNodes.has(schemaNode) && !!schemaNode.name
|
|
192
|
+
const group = groups.get(signature)
|
|
193
|
+
if (group) {
|
|
194
|
+
group.count++
|
|
195
|
+
if (isTopLevel) group.topLevelNames.push(schemaNode.name!)
|
|
196
|
+
} else {
|
|
197
|
+
groups.set(signature, { count: 1, representative: schemaNode, topLevelNames: isTopLevel ? [schemaNode.name!] : [] })
|
|
198
|
+
}
|
|
199
|
+
}
|
|
200
|
+
|
|
201
|
+
for (const root of roots) {
|
|
202
|
+
if (root.kind === 'Schema') topLevelNodes.add(root)
|
|
203
|
+
for (const schemaNode of collectLazy<SchemaNode>(root, { schema: (node) => node })) {
|
|
204
|
+
record(schemaNode)
|
|
205
|
+
}
|
|
206
|
+
}
|
|
207
|
+
|
|
208
|
+
const canonicalBySignature = new Map<string, DedupeCanonical>()
|
|
209
|
+
const aliasNames = new Map<string, DedupeCanonical>()
|
|
210
|
+
const pendingHoists: Array<{ name: string; representative: SchemaNode }> = []
|
|
211
|
+
|
|
212
|
+
for (const [signature, group] of groups) {
|
|
213
|
+
if (group.count < minOccurrences) continue
|
|
214
|
+
|
|
215
|
+
const [firstName, ...duplicateNames] = group.topLevelNames
|
|
216
|
+
if (firstName) {
|
|
217
|
+
const canonical: DedupeCanonical = { name: firstName, ref: refFor(firstName) }
|
|
218
|
+
canonicalBySignature.set(signature, canonical)
|
|
219
|
+
for (const duplicate of duplicateNames) {
|
|
220
|
+
aliasNames.set(duplicate, canonical)
|
|
221
|
+
}
|
|
222
|
+
continue
|
|
223
|
+
}
|
|
224
|
+
|
|
225
|
+
const name = nameFor(group.representative, signature)
|
|
226
|
+
if (!name) continue
|
|
227
|
+
|
|
228
|
+
canonicalBySignature.set(signature, { name, ref: refFor(name) })
|
|
229
|
+
pendingHoists.push({ name, representative: group.representative })
|
|
230
|
+
}
|
|
231
|
+
|
|
232
|
+
// Build hoisted definitions only after every canonical name is known, so nested
|
|
233
|
+
// duplicates inside a definition also resolve to refs.
|
|
234
|
+
const hoisted = pendingHoists.map(({ name, representative }) =>
|
|
235
|
+
cleanDefinition(applyDedupe(representative, { canonicalBySignature, aliasNames }, true), name),
|
|
236
|
+
)
|
|
237
|
+
|
|
238
|
+
return { canonicalBySignature, aliasNames, hoisted }
|
|
239
|
+
}
|
package/src/dialect.ts
ADDED
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The spec-specific questions a schema parser answers while turning a source document into Kubb
|
|
3
|
+
* AST nodes. The rest of the pipeline is generic JSON Schema, so this is the one seam where
|
|
4
|
+
* OpenAPI, AsyncAPI, and plain JSON Schema differ.
|
|
5
|
+
*/
|
|
6
|
+
export type SchemaDialect<TSchema = unknown, TRef = TSchema, TDiscriminated = TSchema, TDocument = unknown> = {
|
|
7
|
+
/**
|
|
8
|
+
* Identifies the dialect in logs and diagnostics.
|
|
9
|
+
*/
|
|
10
|
+
name: string
|
|
11
|
+
/**
|
|
12
|
+
* Whether the schema is nullable.
|
|
13
|
+
*/
|
|
14
|
+
isNullable: (schema?: TSchema) => boolean
|
|
15
|
+
/**
|
|
16
|
+
* Whether the value is a `$ref` pointer.
|
|
17
|
+
*/
|
|
18
|
+
isReference: (value?: unknown) => value is TRef
|
|
19
|
+
/**
|
|
20
|
+
* Whether the schema carries a discriminator for polymorphism.
|
|
21
|
+
*/
|
|
22
|
+
isDiscriminator: (value?: unknown) => value is TDiscriminated
|
|
23
|
+
/**
|
|
24
|
+
* Whether the schema is binary data, converted to a `blob` node.
|
|
25
|
+
*/
|
|
26
|
+
isBinary: (schema: TSchema) => boolean
|
|
27
|
+
/**
|
|
28
|
+
* Resolves a local `$ref` against the document, or nullish when it cannot.
|
|
29
|
+
*/
|
|
30
|
+
resolveRef: <TResolved>(document: TDocument, ref: string) => TResolved | null | undefined
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
/**
|
|
34
|
+
* Types a {@link SchemaDialect} for an adapter. Adds no runtime behavior and only pins the
|
|
35
|
+
* dialect's type for inference.
|
|
36
|
+
*
|
|
37
|
+
* @example
|
|
38
|
+
* ```ts
|
|
39
|
+
* export const oasDialect = defineSchemaDialect({
|
|
40
|
+
* name: 'oas',
|
|
41
|
+
* isNullable,
|
|
42
|
+
* isReference,
|
|
43
|
+
* isDiscriminator,
|
|
44
|
+
* isBinary: (schema) => schema.type === 'string' && schema.contentMediaType === 'application/octet-stream',
|
|
45
|
+
* resolveRef,
|
|
46
|
+
* })
|
|
47
|
+
* ```
|
|
48
|
+
*/
|
|
49
|
+
export function defineSchemaDialect<TSchema, TRef, TDiscriminated, TDocument>(
|
|
50
|
+
dialect: SchemaDialect<TSchema, TRef, TDiscriminated, TDocument>,
|
|
51
|
+
): SchemaDialect<TSchema, TRef, TDiscriminated, TDocument> {
|
|
52
|
+
return dialect
|
|
53
|
+
}
|