@kubb/ast 5.0.0-beta.43 → 5.0.0-beta.45

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/src/types.ts CHANGED
@@ -1,5 +1,4 @@
1
- export type { VisitorDepth } from './constants.ts'
2
- export type { BuildDedupePlanOptions, DedupeCanonical, DedupePlan } from './dedupe.ts'
1
+ export type { DedupePlan } from './dedupe.ts'
3
2
  export type { SchemaDialect } from './dialect.ts'
4
3
  export type { DispatchRule } from './dispatch.ts'
5
4
  export type { DistributiveOmit } from './factory.ts'
@@ -7,44 +6,32 @@ export type { InferSchemaNode, ParserOptions } from './infer.ts'
7
6
  export type {
8
7
  ArraySchemaNode,
9
8
  ArrowFunctionNode,
10
- BaseNode,
11
- BreakNode,
12
9
  CodeNode,
13
- ComplexSchemaType,
14
10
  ConstNode,
15
11
  DateSchemaNode,
16
12
  DatetimeSchemaNode,
17
13
  EnumSchemaNode,
18
- EnumValueNode,
19
14
  ExportNode,
20
15
  FileNode,
21
- FormatStringSchemaNode,
22
16
  FunctionNode,
23
17
  FunctionNodeType,
24
18
  FunctionParameterNode,
25
19
  FunctionParametersNode,
26
20
  FunctionParamNode,
27
- GenericOperationNode,
28
21
  HttpMethod,
29
22
  HttpOperationNode,
30
- HttpStatusCode,
31
23
  ImportNode,
32
24
  InputMeta,
33
25
  InputNode,
34
26
  InputStreamNode,
35
27
  IntersectionSchemaNode,
36
- Ipv4SchemaNode,
37
- Ipv6SchemaNode,
38
28
  JSDocNode,
39
29
  JsxNode,
40
- MediaType,
41
30
  Node,
42
31
  NodeKind,
43
32
  NumberSchemaNode,
44
33
  ObjectSchemaNode,
45
34
  OperationNode,
46
- OperationNodeBase,
47
- OperationProtocol,
48
35
  OutputNode,
49
36
  ParameterGroupNode,
50
37
  ParameterLocation,
@@ -54,24 +41,20 @@ export type {
54
41
  PropertyNode,
55
42
  RefSchemaNode,
56
43
  ResponseNode,
57
- ScalarSchemaNode,
58
44
  ScalarSchemaType,
59
45
  SchemaNode,
60
46
  SchemaNodeByType,
61
47
  SchemaType,
62
48
  SourceNode,
63
- SpecialSchemaType,
64
49
  StatusCode,
65
50
  StringSchemaNode,
66
51
  TextNode,
67
52
  TimeSchemaNode,
68
- TypeDeclarationNode,
69
53
  TypeNode,
70
54
  UnionSchemaNode,
71
55
  UrlSchemaNode,
72
56
  } from './nodes/index.ts'
73
- export type { AsyncVisitor, CollectOptions, CollectVisitor, ParentOf, TransformOptions, Visitor, VisitorContext, WalkOptions } from './visitor.ts'
57
+ export type { ParentOf, Visitor, VisitorContext } from './visitor.ts'
74
58
  export type { Printer, PrinterFactoryOptions, PrinterPartial } from './printer.ts'
75
- export type { ScalarPrimitive } from './constants.ts'
76
- export type { OperationParamsResolver } from './utils.ts'
59
+ export type { OperationParamsResolver } from './utils/ast.ts'
77
60
  export type { UserFileNode } from './factory.ts'
@@ -1,8 +1,7 @@
1
1
  import { camelCase, isValidVarName, memoize } from '@internals/utils'
2
2
 
3
- import { INDENT } from './constants.ts'
4
- import { createFunctionParameter, createFunctionParameters, createParameterGroup, createParamsType, createProperty, createSchema } from './factory.ts'
5
- import { narrowSchema } from './guards.ts'
3
+ import { createFunctionParameter, createFunctionParameters, createParameterGroup, createParamsType, createProperty, createSchema } from '../factory.ts'
4
+ import { narrowSchema } from '../guards.ts'
6
5
  import type {
7
6
  CodeNode,
8
7
  ExportNode,
@@ -15,10 +14,10 @@ import type {
15
14
  ParamsTypeNode,
16
15
  SchemaNode,
17
16
  SourceNode,
18
- } from './nodes/index.ts'
19
- import type { SchemaType } from './nodes/schema.ts'
20
- import { extractRefName } from './refs.ts'
21
- import { collect, collectLazy } from './visitor.ts'
17
+ } from '../nodes/index.ts'
18
+ import type { SchemaType } from '../nodes/schema.ts'
19
+ import { extractRefName } from './index.ts'
20
+ import { collect, collectLazy } from '../visitor.ts'
22
21
 
23
22
  const plainStringTypes = new Set<SchemaType>(['string', 'uuid', 'email', 'url', 'datetime'] as const)
24
23
 
@@ -119,7 +118,7 @@ export function createDiscriminantNode({ propertyName, value }: { propertyName:
119
118
  /**
120
119
  * Named type for a group of parameters (query or header) emitted as a single typed parameter.
121
120
  */
122
- export type ParamGroupType = {
121
+ type ParamGroupType = {
123
122
  /**
124
123
  * TypeNode for the group type.
125
124
  */
@@ -762,68 +761,6 @@ export function extractStringsFromNodes(nodes: Array<CodeNode> | undefined): str
762
761
  .join('\n')
763
762
  }
764
763
 
765
- /**
766
- * Indents every non-empty line of `text` by one indent level, leaving blank lines empty.
767
- */
768
- function indentLines(text: string): string {
769
- if (!text) return ''
770
- return text
771
- .split('\n')
772
- .map((line) => (line.trim() ? `${INDENT}${line}` : ''))
773
- .join('\n')
774
- }
775
-
776
- /**
777
- * Renders an object key, quoting it only when it is not a valid variable name.
778
- *
779
- * @example
780
- * ```ts
781
- * objectKey('id') // 'id'
782
- * objectKey('x-total') // '"x-total"'
783
- * ```
784
- */
785
- export function objectKey(name: string): string {
786
- return isValidVarName(name) ? name : JSON.stringify(name)
787
- }
788
-
789
- /**
790
- * Assembles a multi-line object literal from already-rendered `entries`, indenting each entry one
791
- * level and closing the brace at column zero. Nested objects built the same way indent cumulatively,
792
- * so callers never re-parse the generated code. A trailing comma is added per entry to match the
793
- * formatter's multi-line style.
794
- *
795
- * @example
796
- * ```ts
797
- * buildObject(['id: z.number()', 'name: z.string()'])
798
- * // '{\n id: z.number(),\n name: z.string(),\n}'
799
- * ```
800
- */
801
- export function buildObject(entries: Array<string>): string {
802
- if (entries.length === 0) return '{}'
803
- const body = entries.map((entry) => `${indentLines(entry)},`).join('\n')
804
- return `{\n${body}\n}`
805
- }
806
-
807
- /**
808
- * Assembles a bracketed list (array by default) from already-rendered `items`. Keeps everything on
809
- * one line when no item spans multiple lines, and otherwise puts each item on its own line, indented
810
- * one level with a trailing comma and the closing bracket at column zero. Use it for `z.union([…])`,
811
- * `z.array([…])`, and similar member lists so objects inside them nest correctly.
812
- *
813
- * @example
814
- * ```ts
815
- * buildList(['z.string()', 'z.number()'])
816
- * // '[z.string(), z.number()]'
817
- * ```
818
- */
819
- export function buildList(items: Array<string>, brackets: [open: string, close: string] = ['[', ']']): string {
820
- const [open, close] = brackets
821
- if (items.length === 0) return `${open}${close}`
822
- if (!items.some((item) => item.includes('\n'))) return `${open}${items.join(', ')}${close}`
823
- const body = items.map((item) => `${indentLines(item)},`).join('\n')
824
- return `${open}\n${body}\n${close}`
825
- }
826
-
827
764
  /**
828
765
  * Resolves the schema name of a ref node, falling back through `ref` → `name` → nested `schema.name`.
829
766
  *
@@ -0,0 +1,295 @@
1
+ import { isIdentifier, pascalCase, singleQuote } from '@internals/utils'
2
+ import { INDENT } from '../constants.ts'
3
+
4
+ export { ensureValidVarName, isValidVarName } from '@internals/utils'
5
+
6
+ /**
7
+ * Strips a single matching pair of `"..."`, `'...'`, or `` `...` `` from both ends of `text`.
8
+ * Returns the string unchanged when no balanced quote pair is found.
9
+ *
10
+ * @example
11
+ * ```ts
12
+ * trimQuotes('"hello"') // 'hello'
13
+ * trimQuotes('hello') // 'hello'
14
+ * ```
15
+ */
16
+ export function trimQuotes(text: string): string {
17
+ if (text.length >= 2) {
18
+ const first = text[0]
19
+ const last = text[text.length - 1]
20
+ if ((first === '"' && last === '"') || (first === "'" && last === "'") || (first === '`' && last === '`')) {
21
+ return text.slice(1, -1)
22
+ }
23
+ }
24
+ return text
25
+ }
26
+
27
+ /**
28
+ * Serializes a primitive value to a single-quoted string literal, stripping any surrounding quote
29
+ * characters first. Escaping comes from `JSON.stringify`, then the quote style switches to single
30
+ * quotes so generated code matches the repo style without a formatter.
31
+ *
32
+ * @example
33
+ * ```ts
34
+ * stringify('hello') // "'hello'"
35
+ * stringify('"hello"') // "'hello'"
36
+ * ```
37
+ */
38
+ export function stringify(value: string | number | boolean | undefined): string {
39
+ if (value === undefined || value === null) return "''"
40
+ const json = JSON.stringify(trimQuotes(value.toString()))
41
+ const inner = json.slice(1, -1).replace(/\\"/g, '"').replace(/'/g, "\\'")
42
+ return `'${inner}'`
43
+ }
44
+
45
+ /**
46
+ * Escapes characters that are not allowed inside JS string literals, covering quotes, backslashes,
47
+ * and the Unicode line terminators U+2028 and U+2029.
48
+ *
49
+ * @see http://www.ecma-international.org/ecma-262/5.1/#sec-7.8.4
50
+ *
51
+ * @example
52
+ * ```ts
53
+ * jsStringEscape('say "hi"\nbye') // 'say \\"hi\\"\\nbye'
54
+ * ```
55
+ */
56
+ export function jsStringEscape(input: unknown): string {
57
+ return `${input}`.replace(/["'\\\n\r\u2028\u2029]/g, (character) => {
58
+ switch (character) {
59
+ case '"':
60
+ case "'":
61
+ case '\\':
62
+ return `\\${character}`
63
+ case '\n':
64
+ return '\\n'
65
+ case '\r':
66
+ return '\\r'
67
+ case '\u2028':
68
+ return '\\u2028'
69
+ case '\u2029':
70
+ return '\\u2029'
71
+ default:
72
+ return ''
73
+ }
74
+ })
75
+ }
76
+
77
+ /**
78
+ * Converts a pattern string into a `new RegExp(...)` constructor call or a regex literal string.
79
+ * Inline flags expressed as a `^(?im)` prefix are extracted and applied to the resulting expression.
80
+ * Pass `null` as the second argument to emit a `/pattern/flags` literal instead.
81
+ *
82
+ * @example
83
+ * ```ts
84
+ * toRegExpString('^(?im)foo') // 'new RegExp("^foo", "im")'
85
+ * toRegExpString('^(?im)foo', null) // '/^foo/im'
86
+ * ```
87
+ */
88
+ export function toRegExpString(text: string, func: string | null = 'RegExp'): string {
89
+ const raw = trimQuotes(text)
90
+
91
+ const match = raw.match(/^\^(\(\?([igmsuy]+)\))/i)
92
+ const replacementTarget = match?.[1] ?? ''
93
+ const matchedFlags = match?.[2]
94
+ const cleaned = raw
95
+ .replace(/^\\?\//, '')
96
+ .replace(/\\?\/$/, '')
97
+ .replace(replacementTarget, '')
98
+
99
+ const { source, flags } = new RegExp(cleaned, matchedFlags)
100
+
101
+ if (func === null) return `/${source}/${flags}`
102
+
103
+ return `new ${func}(${JSON.stringify(source)}${flags ? `, ${JSON.stringify(flags)}` : ''})`
104
+ }
105
+
106
+ /**
107
+ * Renders a plain object as multi-line `key: value` source for embedding in generated code. Nested
108
+ * objects recurse with fixed indentation, so the result drops straight into an object literal
109
+ * without re-parsing.
110
+ *
111
+ * @example
112
+ * ```ts
113
+ * stringifyObject({ foo: 'bar', nested: { a: 1 } })
114
+ * // 'foo: bar,\nnested: {\n a: 1\n }'
115
+ * ```
116
+ */
117
+ export function stringifyObject(value: Record<string, unknown>): string {
118
+ const items = Object.entries(value)
119
+ .map(([key, val]) => {
120
+ if (val !== null && typeof val === 'object') {
121
+ return `${key}: {\n ${stringifyObject(val as Record<string, unknown>)}\n }`
122
+ }
123
+ return `${key}: ${val}`
124
+ })
125
+ .filter(Boolean)
126
+ return items.join(',\n')
127
+ }
128
+
129
+ /**
130
+ * Renders a dotted path or string array as an optional-chaining accessor expression rooted at
131
+ * `accessor`. Returns `null` for an empty path.
132
+ *
133
+ * @example
134
+ * ```ts
135
+ * getNestedAccessor('pagination.next.id', 'lastPage')
136
+ * // "lastPage?.['pagination']?.['next']?.['id']"
137
+ * ```
138
+ */
139
+ export function getNestedAccessor(param: string | Array<string>, accessor: string): string | null {
140
+ const parts = Array.isArray(param) ? param : param.split('.')
141
+ if (parts.length === 0 || (parts.length === 1 && parts[0] === '')) return null
142
+ return `${accessor}?.['${`${parts.join("']?.['")}']`}`
143
+ }
144
+
145
+ /**
146
+ * Builds a JSDoc comment block from an array of lines, returning `fallback` when there are no
147
+ * comments so callers always get a usable string.
148
+ *
149
+ * @example
150
+ * ```ts
151
+ * buildJSDoc(['@type string', '@example hello'])
152
+ * // '/**\n * @type string\n * @example hello\n *\/\n '
153
+ * ```
154
+ */
155
+ export function buildJSDoc(
156
+ comments: Array<string>,
157
+ options: {
158
+ /**
159
+ * String used to indent each comment line.
160
+ * @default ' * '
161
+ */
162
+ indent?: string
163
+ /**
164
+ * String appended after the closing tag.
165
+ * @default '\n '
166
+ */
167
+ suffix?: string
168
+ /**
169
+ * Returned as-is when `comments` is empty.
170
+ * @default ' '
171
+ */
172
+ fallback?: string
173
+ } = {},
174
+ ): string {
175
+ const { indent = ' * ', suffix = '\n ', fallback = ' ' } = options
176
+
177
+ if (comments.length === 0) return fallback
178
+
179
+ return `/**\n${comments.map((c) => `${indent}${c}`).join('\n')}\n */${suffix}`
180
+ }
181
+
182
+ /**
183
+ * Indents every non-empty line of `text` by one indent level, leaving blank lines empty.
184
+ */
185
+ function indentLines(text: string): string {
186
+ if (!text) return ''
187
+ return text
188
+ .split('\n')
189
+ .map((line) => (line.trim() ? `${INDENT}${line}` : ''))
190
+ .join('\n')
191
+ }
192
+
193
+ /**
194
+ * Renders an object key, quoting it with single quotes only when it is not a valid identifier.
195
+ * Reserved words and globals (`name`, `class`, …) are valid bare keys and stay unquoted.
196
+ *
197
+ * @example
198
+ * ```ts
199
+ * objectKey('name') // 'name'
200
+ * objectKey('x-total') // "'x-total'"
201
+ * ```
202
+ */
203
+ export function objectKey(name: string): string {
204
+ return isIdentifier(name) ? name : singleQuote(name)
205
+ }
206
+
207
+ /**
208
+ * Assembles a multi-line object literal from already-rendered `entries`, indenting each entry one
209
+ * level and closing the brace at column zero. Nested objects built the same way indent cumulatively,
210
+ * so callers never re-parse the generated code. A trailing comma is added per entry to match the
211
+ * formatter's multi-line style.
212
+ *
213
+ * @example
214
+ * ```ts
215
+ * buildObject(['id: z.number()', 'name: z.string()'])
216
+ * // '{\n id: z.number(),\n name: z.string(),\n}'
217
+ * ```
218
+ */
219
+ export function buildObject(entries: Array<string>): string {
220
+ if (entries.length === 0) return '{}'
221
+ const body = entries.map((entry) => `${indentLines(entry)},`).join('\n')
222
+ return `{\n${body}\n}`
223
+ }
224
+
225
+ /**
226
+ * Assembles a bracketed list (array by default) from already-rendered `items`. Keeps everything on
227
+ * one line when no item spans multiple lines, and otherwise puts each item on its own line, indented
228
+ * one level with a trailing comma and the closing bracket at column zero. Use it for `z.union([…])`,
229
+ * `z.array([…])`, and similar member lists so objects inside them nest correctly.
230
+ *
231
+ * @example
232
+ * ```ts
233
+ * buildList(['z.string()', 'z.number()'])
234
+ * // '[z.string(), z.number()]'
235
+ * ```
236
+ */
237
+ export function buildList(items: Array<string>, brackets: [open: string, close: string] = ['[', ']']): string {
238
+ const [open, close] = brackets
239
+ if (items.length === 0) return `${open}${close}`
240
+ if (!items.some((item) => item.includes('\n'))) return `${open}${items.join(', ')}${close}`
241
+ const body = items.map((item) => `${indentLines(item)},`).join('\n')
242
+ return `${open}\n${body}\n${close}`
243
+ }
244
+
245
+ /**
246
+ * Returns the last path segment of a reference string.
247
+ *
248
+ * @example
249
+ * ```ts
250
+ * extractRefName('#/components/schemas/Pet') // 'Pet'
251
+ * ```
252
+ */
253
+ export function extractRefName(ref: string): string {
254
+ return ref.split('/').at(-1) ?? ref
255
+ }
256
+
257
+ /**
258
+ * Builds a PascalCase child schema name by joining a parent name and property name.
259
+ * Returns `null` when there is no parent to nest under.
260
+ *
261
+ * @example
262
+ * ```ts
263
+ * childName('Order', 'shipping_address') // 'OrderShippingAddress'
264
+ * childName(undefined, 'params') // null
265
+ * ```
266
+ */
267
+ export function childName(parentName: string | null | undefined, propName: string): string | null {
268
+ return parentName ? pascalCase([parentName, propName].join(' ')) : null
269
+ }
270
+
271
+ /**
272
+ * Builds a PascalCase enum name from the parent name, property name, and a suffix, skipping any
273
+ * empty parts.
274
+ *
275
+ * @example
276
+ * ```ts
277
+ * enumPropName('Order', 'status', 'enum') // 'OrderStatusEnum'
278
+ * ```
279
+ */
280
+ export function enumPropName(parentName: string | null | undefined, propName: string, enumSuffix: string): string {
281
+ return pascalCase([parentName, propName, enumSuffix].filter(Boolean).join(' '))
282
+ }
283
+
284
+ /**
285
+ * Returns the discriminator key whose mapping value matches `ref`, or `null` when there is no match.
286
+ *
287
+ * @example
288
+ * ```ts
289
+ * findDiscriminator({ dog: '#/components/schemas/Dog' }, '#/components/schemas/Dog') // 'dog'
290
+ * ```
291
+ */
292
+ export function findDiscriminator(mapping: Record<string, string> | undefined, ref: string | undefined): string | null {
293
+ if (!mapping || !ref) return null
294
+ return Object.entries(mapping).find(([, value]) => value === ref)?.[0] ?? null
295
+ }
package/src/visitor.ts CHANGED
@@ -182,7 +182,7 @@ type MaybePromise<T> = T | Promise<T>
182
182
  * }
183
183
  * ```
184
184
  */
185
- export type AsyncVisitor = {
185
+ type AsyncVisitor = {
186
186
  input?(node: InputNode, context: VisitorContext<InputNode>): MaybePromise<undefined | null | InputNode>
187
187
  output?(node: OutputNode, context: VisitorContext<OutputNode>): MaybePromise<undefined | null | OutputNode>
188
188
  operation?(node: OperationNode, context: VisitorContext<OperationNode>): MaybePromise<undefined | null | OperationNode>
@@ -204,7 +204,7 @@ export type AsyncVisitor = {
204
204
  * }
205
205
  * ```
206
206
  */
207
- export type CollectVisitor<T> = {
207
+ type CollectVisitor<T> = {
208
208
  input?(node: InputNode, context: VisitorContext<InputNode>): T | null | undefined
209
209
  output?(node: OutputNode, context: VisitorContext<OutputNode>): T | null | undefined
210
210
  operation?(node: OperationNode, context: VisitorContext<OperationNode>): T | null | undefined
package/src/refs.ts DELETED
@@ -1,13 +0,0 @@
1
- /**
2
- * Returns the last path segment of a reference string.
3
- *
4
- * Example: `#/components/schemas/Pet` becomes `Pet`.
5
- *
6
- * @example
7
- * ```ts
8
- * extractRefName('#/components/schemas/Pet') // 'Pet'
9
- * ```
10
- */
11
- export function extractRefName(ref: string): string {
12
- return ref.split('/').at(-1) ?? ref
13
- }