🚀 Socket Launch Week Day 5:Introducing Repository Access Permissions and Custom Roles.Learn more
Sign In

@kubb/ast

Package Overview
Dependencies
Maintainers
1
Versions
189
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

@kubb/ast - npm Package Compare versions

Comparing version
5.0.0-beta.80
to
5.0.0-beta.81
dist/types-XcYJovdT.d.ts

Sorry, the diff of this file is too big to display

+420
-18
import { n as __name, t as __exportAll } from "./rolldown-runtime-CNktS9qV.js";
import { a as defineMacro, c as VisitorContext, d as walk, f as schemaTypes, i as composeMacros, l as collect, n as Macro, o as ParentOf, r as applyMacros, s as Visitor, t as Enforce, u as transform } from "./defineMacro-DzsACbFo.js";
import { a as Dialect, i as createPrinter, n as PrinterFactoryOptions, o as SchemaDialect, r as PrinterPartial, s as defineDialect, t as Printer } from "./types-CWF7DV0f.js";
import { $ as ScalarSchemaType, A as SourceNode, At as createFunction, B as ContentNode, Bt as defineNode, C as ParameterNode, Ct as TypeNode, D as ExportNode, Dt as createArrowFunction, E as parameterDef, Et as constDef, F as createSource, Ft as jsxDef, G as DatetimeSchemaNode, H as createContent, Ht as NodeKind, I as exportDef, It as textDef, J as NumberSchemaNode, K as EnumSchemaNode, L as fileDef, Lt as typeDef, M as createExport, Mt as createText, N as createFile, Nt as createType, O as FileNode, Ot as createBreak, P as createImport, Pt as functionDef, Q as ScalarSchemaNode, R as importDef, Rt as DistributiveOmit, S as ParameterLocation, St as TextNode, T as createParameter, Tt as breakDef, U as ArraySchemaNode, V as contentDef, Vt as BaseNode, W as DateSchemaNode, X as PrimitiveSchemaType, Y as ObjectSchemaNode, Z as RefSchemaNode, _ as createResponse, _t as CodeNode, a as InputMeta, at as UnionSchemaNode, b as createRequestBody, bt as JSDocNode, c as inputDef, ct as schemaDef, d as HttpOperationNode, dt as createProperty, et as SchemaNode, f as OperationNode, ft as propertyDef, g as StatusCode, gt as BreakNode, h as ResponseNode, ht as ArrowFunctionNode, i as outputDef, it as TimeSchemaNode, j as UserFileNode, jt as createJsx, k as ImportNode, kt as createConst, l as GenericOperationNode, lt as PropertyNode, m as operationDef, mt as ParserOptions, n as OutputNode, nt as SchemaType, o as InputNode, ot as UrlSchemaNode, p as createOperation, pt as InferSchemaNode, q as IntersectionSchemaNode, r as createOutput, rt as StringSchemaNode, s as createInput, st as createSchema, t as Node, tt as SchemaNodeByType, u as HttpMethod, ut as UserPropertyNode, v as responseDef, vt as ConstNode, w as ParameterStyle, wt as arrowFunctionDef, x as requestBodyDef, xt as JsxNode, y as RequestBodyNode, yt as FunctionNode, z as sourceDef, zt as NodeDef } from "./index-Cu2zmNxv.js";
import { $ as importDef, $t as DistributiveOmit, A as ResponseNode, At as ArrowFunctionNode, B as createParameter, Bt as breakDef, C as inputDef, Ct as schemaDef, D as OperationNode, Dt as propertyDef, E as HttpOperationNode, Et as createProperty, F as createRequestBody, Ft as JSDocNode, G as SourceNode, Gt as createFunction, H as ExportNode, Ht as createArrowFunction, I as requestBodyDef, It as JsxNode, J as createFile, Jt as createType, K as UserFileNode, Kt as createJsx, L as ParameterLocation, Lt as TextNode, M as createResponse, Mt as CodeNode, N as responseDef, Nt as ConstNode, O as createOperation, Ot as InferSchemaNode, P as RequestBodyNode, Pt as FunctionNode, Q as fileDef, Qt as typeDef, R as ParameterNode, Rt as TypeNode, S as createInput, St as createSchema, T as HttpMethod, Tt as UserPropertyNode, U as FileNode, Ut as createBreak, V as parameterDef, Vt as constDef, W as ImportNode, Wt as createConst, X as createSource, Xt as jsxDef, Y as createImport, Yt as functionDef, Z as exportDef, Zt as textDef, _ as OutputNode, _t as SchemaType, a as Enforce, an as SchemaDialect, at as DateSchemaNode, b as InputMeta, bt as UnionSchemaNode, c as composeMacros, ct as IntersectionSchemaNode, d as Visitor, dt as PrimitiveSchemaType, en as NodeDef, et as sourceDef, f as VisitorContext, ft as RefSchemaNode, g as Node, gt as SchemaNodeByType, h as walk, ht as SchemaNode, i as createPrinter, in as Dialect, it as ArraySchemaNode, j as StatusCode, jt as BreakNode, k as operationDef, kt as ParserOptions, l as defineMacro, lt as NumberSchemaNode, m as transform, mt as ScalarSchemaType, n as PrinterFactoryOptions, nn as BaseNode, nt as contentDef, o as Macro, on as defineDialect, ot as DatetimeSchemaNode, p as collect, pt as ScalarSchemaNode, q as createExport, qt as createText, r as PrinterPartial, rn as NodeKind, rt as createContent, s as applyMacros, sn as schemaTypes, st as EnumSchemaNode, t as Printer, tn as defineNode, tt as ContentNode, u as ParentOf, ut as ObjectSchemaNode, v as createOutput, vt as StringSchemaNode, w as GenericOperationNode, wt as PropertyNode, x as InputNode, xt as UrlSchemaNode, y as outputDef, yt as TimeSchemaNode, z as ParameterStyle, zt as arrowFunctionDef } from "./types-XcYJovdT.js";
//#region ../../internals/utils/src/reserved.d.ts
/**
* Returns `true` when `name` is a syntactically valid JavaScript variable name.
*
* @example
* ```ts
* isValidVarName('status') // true
* isValidVarName('class') // false (reserved word)
* isValidVarName('42foo') // false (starts with digit)
* ```
*/
declare function isValidVarName(name: string): boolean;
//#endregion
//#region src/guards.d.ts

@@ -35,2 +46,393 @@ /**

declare function optionality(schema: SchemaNode, required: boolean): SchemaNode;
//#endregion
//#region src/utils/codegen.d.ts
/**
* Builds a JSDoc comment block from an array of lines. Returns `fallback` when there are no
* comments.
*
* @example
* ```ts
* buildJSDoc(['@type string', '@example hello'])
* // '/**\n * @type string\n * @example hello\n *\/\n '
* ```
*/
declare function buildJSDoc(comments: Array<string>, options?: {
/**
* String used to indent each comment line.
* @default ' * '
*/
indent?: string;
/**
* String appended after the closing tag.
* @default '\n '
*/
suffix?: string;
/**
* Returned as-is when `comments` is empty.
* @default ' '
*/
fallback?: string;
}): string;
/**
* Renders an object key, quoting it with single quotes only when it is not a valid identifier.
* Reserved words and globals (`name`, `class`, …) are valid bare keys and stay unquoted.
*
* @example
* ```ts
* objectKey('name') // 'name'
* objectKey('x-total') // "'x-total'"
* ```
*/
declare function objectKey(name: string): string;
/**
* Assembles a multi-line object literal from already-rendered `entries`, indenting each entry one
* level and closing the brace at column zero. Entries that are themselves multi-line objects indent
* cumulatively. Each entry ends with a trailing comma to match the formatter's multi-line style.
*
* @example
* ```ts
* buildObject(['id: z.number()', 'name: z.string()'])
* // '{\n id: z.number(),\n name: z.string(),\n}'
* ```
*/
declare function buildObject(entries: Array<string>): string;
/**
* Assembles a bracketed list (array by default) from already-rendered `items`. Keeps everything on
* one line when no item spans multiple lines, and otherwise puts each item on its own line, indented
* one level with a trailing comma and the closing bracket at column zero. Used for member lists such
* as `z.union([…])` and `z.array([…])`.
*
* @example
* ```ts
* buildList(['z.string()', 'z.number()'])
* // '[z.string(), z.number()]'
* ```
*/
declare function buildList(items: Array<string>, brackets?: [open: string, close: string]): string;
//#endregion
//#region src/utils/extractStringsFromNodes.d.ts
/**
* Extracts all string content from a `CodeNode` tree recursively.
*
* Collects text node values, identifier references in string fields (`params`, `generics`, `returnType`, `type`),
* and nested node content. Used to build the full source string for import filtering.
*/
declare function extractStringsFromNodes(nodes: Array<CodeNode> | undefined): string;
//#endregion
//#region src/utils/refs.d.ts
/**
* Returns the last path segment of a reference string.
*
* @example
* `extractRefName('#/components/schemas/Pet') // 'Pet'`
*/
declare function extractRefName(ref: string): string;
/**
* Builds a PascalCase child schema name by joining a parent name and property name.
* Returns `null` when there is no parent to nest under.
*
* @example Nested under a parent
* `childName('Order', 'shipping_address') // 'OrderShippingAddress'`
*
* @example No parent
* `childName(undefined, 'params') // null`
*/
declare function childName(parentName: string | null | undefined, propName: string): string | null;
/**
* Builds a PascalCase enum name from the parent name, property name, and a suffix, skipping any
* empty parts.
*
* @example
* `enumPropName('Order', 'status', 'enum') // 'OrderStatusEnum'`
*/
declare function enumPropName(parentName: string | null | undefined, propName: string, enumSuffix: string): string;
/**
* Merges a ref node with its resolved schema, giving usage-site fields precedence.
*
* Every field set on the ref node except `kind`, `type`, `name`, `ref`, and `schema` overrides the
* same field in the resolved `node.schema` (for example `description`, `nullable`, `readOnly`,
* `deprecated`). Fields left `undefined` on the ref do not shadow the resolved schema. Non-ref
* nodes and refs without a resolved `schema` are returned unchanged.
*
* @example
* ```ts
* const ref = createSchema({ type: 'ref', ref: '#/components/schemas/Pet', description: 'A cute pet' })
* const merged = syncSchemaRef(ref) // merges with resolved Pet schema
* ```
*/
declare function syncSchemaRef(node: SchemaNode): SchemaNode;
/**
* Type guard that returns `true` when a schema emits as a plain `string` type.
*
* Covers `string`, `uuid`, `email`, `url`, and `datetime` types. For `date` and `time`
* types, returns `true` only when `representation` is `'string'` rather than `'date'`.
*/
declare function isStringType(node: SchemaNode): boolean;
//#endregion
//#region src/utils/schemaMerge.d.ts
/**
* Merges a run of adjacent anonymous object members into one. Named or non-object members break the
* run and pass through unchanged. The merge follows member order, so callers control which members
* combine by where they place them in the sequence.
*
* @example
* ```ts
* const merged = [...mergeAdjacentObjectsLazy([objectA, objectB])]
* ```
*/
declare function mergeAdjacentObjectsLazy(members: Iterable<SchemaNode>): Generator<SchemaNode, void, undefined>;
//#endregion
//#region src/utils/strings.d.ts
/**
* Strips a single matching pair of `"..."`, `'...'`, or `` `...` `` from both ends of `text`.
* Returns the string unchanged when no balanced quote pair is found.
*
* @example
* ```ts
* trimQuotes('"hello"') // 'hello'
* trimQuotes('hello') // 'hello'
* ```
*/
declare function trimQuotes(text: string): string;
/**
* Serializes a primitive to a single-quoted string literal, stripping any surrounding quotes first.
*
* Escaping runs through `JSON.stringify`, then the result switches to single quotes so the generated
* code matches the repo style without a formatter.
*
* @example
* ```ts
* stringify('hello') // "'hello'"
* stringify('"hello"') // "'hello'"
* ```
*/
declare function stringify(value: string | number | boolean | undefined): string;
/**
* Escapes characters that are not allowed inside JS string literals, covering quotes, backslashes,
* and the Unicode line terminators U+2028 and U+2029.
*
* @see http://www.ecma-international.org/ecma-262/5.1/#sec-7.8.4
*
* @example
* ```ts
* jsStringEscape('say "hi"\nbye') // 'say \\"hi\\"\\nbye'
* ```
*/
declare function jsStringEscape(input: unknown): string;
/**
* Converts a pattern string into a `new RegExp(...)` constructor call or a regex literal string.
* Inline flags expressed as a `^(?im)` prefix are extracted and applied to the resulting expression.
* Pass `null` as the second argument to emit a `/pattern/flags` literal instead.
*
* @example
* ```ts
* toRegExpString('^(?im)foo') // 'new RegExp("^foo", "im")'
* toRegExpString('^(?im)foo', null) // '/^foo/im'
* ```
*/
declare function toRegExpString(text: string, func?: string | null): string;
/**
* Renders a plain object as multi-line `key: value` source for embedding in generated code. Nested
* objects recurse with fixed indentation, so the result drops straight into an object literal
* without re-parsing.
*
* @example
* ```ts
* stringifyObject({ foo: 'bar', nested: { a: 1 } })
* // 'foo: bar,\nnested: {\n a: 1\n }'
* ```
*/
declare function stringifyObject(value: Record<string, unknown>): string;
/**
* Renders a dotted path or string array as an optional-chaining accessor expression rooted at
* `accessor`. Returns `null` for an empty path.
*
* @example
* ```ts
* getNestedAccessor('pagination.next.id', 'lastPage')
* // "lastPage?.['pagination']?.['next']?.['id']"
* ```
*/
declare function getNestedAccessor(param: string | Array<string>, accessor: string): string | null;
//#endregion
//#region src/utils/schemaGraph.d.ts
/**
* Collects the names of all top-level schemas transitively used by a set of operations.
*
* An operation uses a schema when its parameters, request body, or responses reference it, directly
* or through other named schemas. Once a name is added to the result it is not revisited, so
* reference cycles terminate.
*
* Pair it with `include` filters so schemas reachable only from excluded operations stay ungenerated.
*
* @example Only generate schemas referenced by included operations
* ```ts
* const includedOps = operations.filter((op) => resolver.resolveOptions(op, { options, include }) !== null)
* const allowed = collectUsedSchemaNames(includedOps, schemas)
*
* for (const schema of schemas) {
* if (schema.name && !allowed.has(schema.name)) continue
* // generate schema
* }
* ```
*/
declare function collectUsedSchemaNames(operations: ReadonlyArray<OperationNode>, schemas: ReadonlyArray<SchemaNode>): Set<string>;
/**
* Finds every schema that takes part in a circular dependency chain, including direct self-loops.
*
* Wrap the returned schema positions in a deferred construct (a lazy getter or `z.lazy(() => …)`) so
* the generated code does not recurse forever. Refs are followed by name only, so the walk stays
* linear in the size of the schema graph.
*
* @note Call this once on the full graph, then check individual schemas with `containsCircularRef()`.
*/
declare function findCircularSchemas(schemas: ReadonlyArray<SchemaNode>): Set<string>;
/**
* Returns `true` when a schema, or anything nested inside it, references a circular schema.
*
* Pass `excludeName` to skip refs to a specific schema, which helps when self-references are handled
* on their own. Pair it with `findCircularSchemas()` to decide where lazy wrappers go.
*
* @note Stops at the first matching circular ref.
*/
declare function containsCircularRef(node: SchemaNode | undefined, {
circularSchemas,
excludeName
}: {
circularSchemas: ReadonlySet<string>;
excludeName?: string;
}): boolean;
//#endregion
//#region src/utils/schemaTraversal.d.ts
/**
* Converts a child schema to printer output. Plugins instantiate it with their own output type:
* `string` for the zod and faker printers, `ts.TypeNode` for the TypeScript printer. A printer's
* `this.transform` fits directly, so its `null` for an empty result carries through to `output`.
*/
type SchemaTransform<TOutput> = (schema: SchemaNode) => TOutput;
/**
* A union or intersection member, or an array or tuple item, paired with its transformed output.
*/
type MappedSchema<TOutput> = {
/**
* The original child schema, kept so the printer can read its metadata for leaf formatting.
*/
schema: SchemaNode;
/**
* The child schema after being run through the transform.
*/
output: TOutput;
};
/**
* An object property paired with its transformed output.
*/
type MappedProperty<TOutput> = {
/**
* The property name as written on the schema, before any identifier quoting.
*/
name: string;
/**
* The original property node, kept so the printer can read `required`, `schema`, and metadata.
*/
property: PropertyNode;
/**
* The property schema after being run through the transform.
*/
output: TOutput;
};
/**
* Maps each property of an object schema to its transformed output. Pairs every result with the
* original property so the printer keeps full control over modifiers, getters, and key syntax.
*
* @example
* ```ts
* const entries = mapSchemaProperties(node, (schema) => this.transform(schema))
* // entries: [{ name: 'id', property, output: 'z.number()' }, ...]
* ```
*/
declare function mapSchemaProperties<TOutput>(node: ObjectSchemaNode, transform: SchemaTransform<TOutput>): Array<MappedProperty<TOutput>>;
/**
* Maps each member of a union or intersection schema to its transformed output, pairing every
* result with the original member.
*/
declare function mapSchemaMembers<TOutput>(node: UnionSchemaNode | IntersectionSchemaNode, transform: SchemaTransform<TOutput>): Array<MappedSchema<TOutput>>;
/**
* Maps each item of an array or tuple schema to its transformed output, pairing every result with
* the original item.
*/
declare function mapSchemaItems<TOutput>(node: ArraySchemaNode, transform: SchemaTransform<TOutput>): Array<MappedSchema<TOutput>>;
/**
* Emits a lazy getter for a circular-ref property position, `get name() { return body }`. The key
* is quoted only when it is not a valid identifier. Used by the string printers to defer evaluation
* of a recursive schema until first access.
*
* @example
* ```ts
* lazyGetter({ name: 'parent', body: 'z.lazy(() => Pet)' })
* // "get parent() { return z.lazy(() => Pet) }"
* ```
*/
declare function lazyGetter({
name,
body
}: {
name: string;
body: string;
}): string;
//#endregion
//#region src/macros/macroDiscriminatorEnum.d.ts
type Props$1 = {
propertyName: string;
values: Array<string>;
enumName?: string;
};
/**
* Builds a macro that replaces a discriminator property's schema with a string enum of the given
* values. Object schemas that lack the property are returned unchanged.
*
* @example
* ```ts
* const macro = macroDiscriminatorEnum({ propertyName: 'type', values: ['dog', 'cat'] })
* const next = applyMacros(objectSchema, [macro], { depth: 'shallow' })
* ```
*/
declare function macroDiscriminatorEnum({
propertyName,
values,
enumName
}: Props$1): Macro;
//#endregion
//#region src/macros/macroEnumName.d.ts
type Props = {
parentName: string | null | undefined;
propName: string;
enumSuffix: string;
};
/**
* Builds a macro that names an inline enum schema from its parent and property name. Boolean enums
* are left anonymous. Non-enum nodes are returned unchanged.
*
* @example
* ```ts
* const macro = macroEnumName({ parentName: 'Pet', propName: 'status', enumSuffix: 'enum' })
* const named = applyMacros(propSchema, [macro], { depth: 'shallow' })
* ```
*/
declare function macroEnumName({
parentName,
propName,
enumSuffix
}: Props): Macro;
//#endregion
//#region src/macros/macroSimplifyUnion.d.ts
/**
* Removes union members a broader scalar primitive already covers, such as a multi-value string enum
* sitting next to a plain `string`. Single-value enums are kept.
*
* @example
* ```ts
* const next = applyMacros(unionSchema, [macroSimplifyUnion], { depth: 'shallow' })
* ```
*/
declare const macroSimplifyUnion: Macro;
declare namespace factory_d_exports {

@@ -62,3 +464,14 @@ export { UserFileNode, createArrowFunction, createBreak, createConst, createContent, createExport, createFile, createFunction, createImport, createInput, createJsx, createOperation, createOutput, createParameter, createProperty, createRequestBody, createResponse, createSchema, createSource, createText, createType, update };

*/
declare const nodeDefs: (NodeDef<PropertyNode, UserPropertyNode> | NodeDef<ConstNode, Omit<ConstNode, "kind">> | NodeDef<TypeNode, Omit<TypeNode, "kind">> | NodeDef<FunctionNode, Omit<FunctionNode, "kind">> | NodeDef<ArrowFunctionNode, Omit<ArrowFunctionNode, "kind">> | NodeDef<TextNode, string> | NodeDef<BreakNode, void> | NodeDef<JsxNode, string> | NodeDef<SchemaNode, (Omit<ObjectSchemaNode, "properties" | "kind" | "primitive"> & {
declare const nodeDefs: (NodeDef<InputNode<false>, Partial<Omit<InputNode<false>, "kind">>> | NodeDef<OutputNode, Partial<Omit<OutputNode, "kind">>> | NodeDef<RequestBodyNode, Omit<RequestBodyNode, "kind">> | NodeDef<OperationNode, {
[key: string]: unknown;
operationId: string;
method?: HttpOperationNode["method"];
path?: HttpOperationNode["path"];
requestBody?: Omit<RequestBodyNode, "kind">;
}> | NodeDef<ContentNode, Omit<ContentNode, "kind">> | NodeDef<ResponseNode, Pick<ResponseNode, "statusCode"> & Partial<Omit<ResponseNode, "kind" | "content" | "statusCode">> & {
content?: Array<ContentNode>;
schema?: SchemaNode;
mediaType?: string | null;
keysToOmit?: Array<string> | null;
}> | NodeDef<SchemaNode, (Omit<ObjectSchemaNode, "kind" | "properties" | "primitive"> & {
properties?: Array<PropertyNode>;

@@ -119,19 +532,8 @@ primitive?: "object";

type: "ipv6";
}) | ScalarSchemaNode, "kind">> | NodeDef<InputNode<false>, Partial<Omit<InputNode<false>, "kind">>> | NodeDef<OutputNode, Partial<Omit<OutputNode, "kind">>> | NodeDef<RequestBodyNode, Omit<RequestBodyNode, "kind">> | NodeDef<OperationNode, {
[key: string]: unknown;
operationId: string;
method?: HttpOperationNode["method"];
path?: HttpOperationNode["path"];
requestBody?: Omit<RequestBodyNode, "kind">;
}> | NodeDef<ContentNode, Omit<ContentNode, "kind">> | NodeDef<ResponseNode, Pick<ResponseNode, "statusCode"> & Partial<Omit<ResponseNode, "kind" | "content" | "statusCode">> & {
content?: Array<ContentNode>;
schema?: SchemaNode;
mediaType?: string | null;
keysToOmit?: Array<string> | null;
}> | NodeDef<ParameterNode, Pick<ParameterNode, "name" | "schema" | "in"> & Partial<Omit<ParameterNode, "name" | "kind" | "schema" | "in">>> | NodeDef<ImportNode, Omit<ImportNode, "kind">> | NodeDef<ExportNode, Omit<ExportNode, "kind">> | NodeDef<SourceNode, Omit<SourceNode, "kind">> | NodeDef<FileNode<object>, Omit<FileNode<object>, "kind">>)[];
}) | ScalarSchemaNode, "kind">> | NodeDef<PropertyNode, UserPropertyNode> | NodeDef<ParameterNode, Pick<ParameterNode, "schema" | "name" | "in"> & Partial<Omit<ParameterNode, "schema" | "kind" | "name" | "in">>> | NodeDef<ConstNode, Omit<ConstNode, "kind">> | NodeDef<TypeNode, Omit<TypeNode, "kind">> | NodeDef<FunctionNode, Omit<FunctionNode, "kind">> | NodeDef<ArrowFunctionNode, Omit<ArrowFunctionNode, "kind">> | NodeDef<TextNode, string> | NodeDef<BreakNode, void> | NodeDef<JsxNode, string> | NodeDef<ImportNode, Omit<ImportNode, "kind">> | NodeDef<ExportNode, Omit<ExportNode, "kind">> | NodeDef<SourceNode, Omit<SourceNode, "kind">> | NodeDef<FileNode<object>, Omit<FileNode<object>, "kind">>)[];
declare namespace exports_d_exports {
export { ArraySchemaNode, ArrowFunctionNode, BreakNode, CodeNode, ConstNode, ContentNode, DateSchemaNode, DatetimeSchemaNode, Dialect, DistributiveOmit, Enforce, EnumSchemaNode, ExportNode, FileNode, FunctionNode, GenericOperationNode, HttpMethod, HttpOperationNode, ImportNode, InferSchemaNode, InputMeta, InputNode, IntersectionSchemaNode, JSDocNode, JsxNode, Macro, Node, NodeDef, NodeKind, NumberSchemaNode, ObjectSchemaNode, OperationNode, OutputNode, ParameterLocation, ParameterNode, ParameterStyle, ParentOf, ParserOptions, PrimitiveSchemaType, Printer, PrinterFactoryOptions, PrinterPartial, PropertyNode, RefSchemaNode, RequestBodyNode, ResponseNode, ScalarSchemaNode, ScalarSchemaType, SchemaDialect, SchemaNode, SchemaNodeByType, SchemaType, SourceNode, StatusCode, StringSchemaNode, TextNode, TimeSchemaNode, TypeNode, UnionSchemaNode, UrlSchemaNode, UserFileNode, Visitor, VisitorContext, applyMacros, arrowFunctionDef, breakDef, collect, composeMacros, constDef, contentDef, createPrinter, defineDialect, defineMacro, defineNode, exportDef, factory_d_exports as factory, fileDef, functionDef, importDef, inputDef, isHttpOperationNode, jsxDef, narrowSchema, nodeDefs, operationDef, optionality, outputDef, parameterDef, propertyDef, requestBodyDef, responseDef, schemaDef, schemaTypes, sourceDef, textDef, transform, typeDef, walk };
export { ArraySchemaNode, ArrowFunctionNode, BreakNode, CodeNode, ConstNode, ContentNode, DateSchemaNode, DatetimeSchemaNode, Dialect, DistributiveOmit, Enforce, EnumSchemaNode, ExportNode, FileNode, FunctionNode, GenericOperationNode, HttpMethod, HttpOperationNode, ImportNode, InferSchemaNode, InputMeta, InputNode, IntersectionSchemaNode, JSDocNode, JsxNode, Macro, Node, NodeDef, NodeKind, NumberSchemaNode, ObjectSchemaNode, OperationNode, OutputNode, ParameterLocation, ParameterNode, ParameterStyle, ParentOf, ParserOptions, PrimitiveSchemaType, Printer, PrinterFactoryOptions, PrinterPartial, PropertyNode, RefSchemaNode, RequestBodyNode, ResponseNode, ScalarSchemaNode, ScalarSchemaType, SchemaDialect, SchemaNode, SchemaNodeByType, SchemaType, SourceNode, StatusCode, StringSchemaNode, TextNode, TimeSchemaNode, TypeNode, UnionSchemaNode, UrlSchemaNode, UserFileNode, Visitor, VisitorContext, applyMacros, arrowFunctionDef, breakDef, buildJSDoc, buildList, buildObject, childName, collect, collectUsedSchemaNames, composeMacros, constDef, containsCircularRef, contentDef, createPrinter, defineDialect, defineMacro, defineNode, enumPropName, exportDef, extractRefName, extractStringsFromNodes, factory_d_exports as factory, fileDef, findCircularSchemas, functionDef, getNestedAccessor, importDef, inputDef, isHttpOperationNode, isStringType, isValidVarName, jsStringEscape, jsxDef, lazyGetter, macroDiscriminatorEnum, macroEnumName, macroSimplifyUnion, mapSchemaItems, mapSchemaMembers, mapSchemaProperties, mergeAdjacentObjectsLazy, narrowSchema, nodeDefs, objectKey, operationDef, optionality, outputDef, parameterDef, propertyDef, requestBodyDef, responseDef, schemaDef, schemaTypes, sourceDef, stringify, stringifyObject, syncSchemaRef, textDef, toRegExpString, transform, trimQuotes, typeDef, walk };
}
//#endregion
export { type ArraySchemaNode, type ArrowFunctionNode, type BreakNode, type CodeNode, type ConstNode, type ContentNode, type DateSchemaNode, type DatetimeSchemaNode, type Dialect, type DistributiveOmit, type Enforce, type EnumSchemaNode, type ExportNode, type FileNode, type FunctionNode, type GenericOperationNode, type HttpMethod, type HttpOperationNode, type ImportNode, type InferSchemaNode, type InputMeta, type InputNode, type IntersectionSchemaNode, type JSDocNode, type JsxNode, type Macro, type Node, type NodeDef, type NodeKind, type NumberSchemaNode, type ObjectSchemaNode, type OperationNode, type OutputNode, type ParameterLocation, type ParameterNode, type ParameterStyle, type ParentOf, type ParserOptions, type PrimitiveSchemaType, type Printer, type PrinterFactoryOptions, type PrinterPartial, type PropertyNode, type RefSchemaNode, type RequestBodyNode, type ResponseNode, type ScalarSchemaNode, type ScalarSchemaType, type SchemaDialect, type SchemaNode, type SchemaNodeByType, type SchemaType, type SourceNode, type StatusCode, type StringSchemaNode, type TextNode, type TimeSchemaNode, type TypeNode, type UnionSchemaNode, type UrlSchemaNode, type UserFileNode, type Visitor, type VisitorContext, applyMacros, arrowFunctionDef, exports_d_exports as ast, breakDef, collect, composeMacros, constDef, contentDef, createPrinter, defineDialect, defineMacro, defineNode, exportDef, factory_d_exports as factory, fileDef, functionDef, importDef, inputDef, isHttpOperationNode, jsxDef, narrowSchema, nodeDefs, operationDef, optionality, outputDef, parameterDef, propertyDef, requestBodyDef, responseDef, schemaDef, schemaTypes, sourceDef, textDef, transform, typeDef, walk };
export { type ArraySchemaNode, type ArrowFunctionNode, type BreakNode, type CodeNode, type ConstNode, type ContentNode, type DateSchemaNode, type DatetimeSchemaNode, type Dialect, type DistributiveOmit, type Enforce, type EnumSchemaNode, type ExportNode, type FileNode, type FunctionNode, type GenericOperationNode, type HttpMethod, type HttpOperationNode, type ImportNode, type InferSchemaNode, type InputMeta, type InputNode, type IntersectionSchemaNode, type JSDocNode, type JsxNode, type Macro, type Node, type NodeDef, type NodeKind, type NumberSchemaNode, type ObjectSchemaNode, type OperationNode, type OutputNode, type ParameterLocation, type ParameterNode, type ParameterStyle, type ParentOf, type ParserOptions, type PrimitiveSchemaType, type Printer, type PrinterFactoryOptions, type PrinterPartial, type PropertyNode, type RefSchemaNode, type RequestBodyNode, type ResponseNode, type ScalarSchemaNode, type ScalarSchemaType, type SchemaDialect, type SchemaNode, type SchemaNodeByType, type SchemaType, type SourceNode, type StatusCode, type StringSchemaNode, type TextNode, type TimeSchemaNode, type TypeNode, type UnionSchemaNode, type UrlSchemaNode, type UserFileNode, type Visitor, type VisitorContext, applyMacros, arrowFunctionDef, exports_d_exports as ast, breakDef, buildJSDoc, buildList, buildObject, childName, collect, collectUsedSchemaNames, composeMacros, constDef, containsCircularRef, contentDef, createPrinter, defineDialect, defineMacro, defineNode, enumPropName, exportDef, extractRefName, extractStringsFromNodes, factory_d_exports as factory, fileDef, findCircularSchemas, functionDef, getNestedAccessor, importDef, inputDef, isHttpOperationNode, isStringType, isValidVarName, jsStringEscape, jsxDef, lazyGetter, macroDiscriminatorEnum, macroEnumName, macroSimplifyUnion, mapSchemaItems, mapSchemaMembers, mapSchemaProperties, mergeAdjacentObjectsLazy, narrowSchema, nodeDefs, objectKey, operationDef, optionality, outputDef, parameterDef, propertyDef, requestBodyDef, responseDef, schemaDef, schemaTypes, sourceDef, stringify, stringifyObject, syncSchemaRef, textDef, toRegExpString, transform, trimQuotes, typeDef, walk };
//# sourceMappingURL=index.d.ts.map
+1
-3

@@ -1,4 +0,2 @@

import { c as VisitorContext, n as Macro, o as ParentOf, s as Visitor, t as Enforce } from "./defineMacro-DzsACbFo.js";
import { a as Dialect, n as PrinterFactoryOptions, o as SchemaDialect, r as PrinterPartial, t as Printer } from "./types-CWF7DV0f.js";
import { $ as ScalarSchemaType, A as SourceNode, B as ContentNode, C as ParameterNode, Ct as TypeNode, D as ExportNode, G as DatetimeSchemaNode, Ht as NodeKind, J as NumberSchemaNode, K as EnumSchemaNode, O as FileNode, Q as ScalarSchemaNode, Rt as DistributiveOmit, S as ParameterLocation, St as TextNode, U as ArraySchemaNode, W as DateSchemaNode, X as PrimitiveSchemaType, Y as ObjectSchemaNode, Z as RefSchemaNode, _t as CodeNode, a as InputMeta, at as UnionSchemaNode, bt as JSDocNode, d as HttpOperationNode, et as SchemaNode, f as OperationNode, g as StatusCode, gt as BreakNode, h as ResponseNode, ht as ArrowFunctionNode, it as TimeSchemaNode, j as UserFileNode, k as ImportNode, l as GenericOperationNode, lt as PropertyNode, mt as ParserOptions, n as OutputNode, nt as SchemaType, o as InputNode, ot as UrlSchemaNode, pt as InferSchemaNode, q as IntersectionSchemaNode, rt as StringSchemaNode, t as Node, tt as SchemaNodeByType, u as HttpMethod, vt as ConstNode, w as ParameterStyle, xt as JsxNode, y as RequestBodyNode, yt as FunctionNode, zt as NodeDef } from "./index-Cu2zmNxv.js";
import { $t as DistributiveOmit, A as ResponseNode, At as ArrowFunctionNode, D as OperationNode, E as HttpOperationNode, Ft as JSDocNode, G as SourceNode, H as ExportNode, It as JsxNode, K as UserFileNode, L as ParameterLocation, Lt as TextNode, Mt as CodeNode, Nt as ConstNode, Ot as InferSchemaNode, P as RequestBodyNode, Pt as FunctionNode, R as ParameterNode, Rt as TypeNode, T as HttpMethod, U as FileNode, W as ImportNode, _ as OutputNode, _t as SchemaType, a as Enforce, an as SchemaDialect, at as DateSchemaNode, b as InputMeta, bt as UnionSchemaNode, ct as IntersectionSchemaNode, d as Visitor, dt as PrimitiveSchemaType, en as NodeDef, f as VisitorContext, ft as RefSchemaNode, g as Node, gt as SchemaNodeByType, ht as SchemaNode, in as Dialect, it as ArraySchemaNode, j as StatusCode, jt as BreakNode, kt as ParserOptions, lt as NumberSchemaNode, mt as ScalarSchemaType, n as PrinterFactoryOptions, o as Macro, ot as DatetimeSchemaNode, pt as ScalarSchemaNode, r as PrinterPartial, rn as NodeKind, st as EnumSchemaNode, t as Printer, tt as ContentNode, u as ParentOf, ut as ObjectSchemaNode, vt as StringSchemaNode, w as GenericOperationNode, wt as PropertyNode, x as InputNode, xt as UrlSchemaNode, yt as TimeSchemaNode, z as ParameterStyle } from "./types-XcYJovdT.js";
export type { ArraySchemaNode, ArrowFunctionNode, BreakNode, CodeNode, ConstNode, ContentNode, DateSchemaNode, DatetimeSchemaNode, Dialect, DistributiveOmit, Enforce, EnumSchemaNode, ExportNode, FileNode, FunctionNode, GenericOperationNode, HttpMethod, HttpOperationNode, ImportNode, InferSchemaNode, InputMeta, InputNode, IntersectionSchemaNode, JSDocNode, JsxNode, Macro, Node, NodeDef, NodeKind, NumberSchemaNode, ObjectSchemaNode, OperationNode, OutputNode, ParameterLocation, ParameterNode, ParameterStyle, ParentOf, ParserOptions, PrimitiveSchemaType, Printer, PrinterFactoryOptions, PrinterPartial, PropertyNode, RefSchemaNode, RequestBodyNode, ResponseNode, ScalarSchemaNode, ScalarSchemaType, SchemaDialect, SchemaNode, SchemaNodeByType, SchemaType, SourceNode, StatusCode, StringSchemaNode, TextNode, TimeSchemaNode, TypeNode, UnionSchemaNode, UrlSchemaNode, UserFileNode, Visitor, VisitorContext };
{
"name": "@kubb/ast",
"version": "5.0.0-beta.80",
"version": "5.0.0-beta.81",
"description": "Spec-agnostic AST layer for Kubb. Defines the node tree, visitor pattern, factory functions, and type guards used across all code generation plugins.",

@@ -34,6 +34,2 @@ "keywords": [

},
"./macros": {
"import": "./dist/macros.js",
"require": "./dist/macros.cjs"
},
"./types": {

@@ -43,6 +39,2 @@ "import": "./dist/types.js",

},
"./utils": {
"import": "./dist/utils.js",
"require": "./dist/utils.cjs"
},
"./package.json": "./package.json"

@@ -49,0 +41,0 @@ },

import "./rolldown-runtime-CNktS9qV.js";
import { X as visitorKeys, r as transform } from "./visitor-Dk0DNLfC.js";
//#region src/defineMacro.ts
/**
* Sort weight for an `enforce` hint. `pre` sorts before unmarked items and `post` after, so a plain
* list keeps its authored order.
*/
function enforceWeight(enforce) {
if (enforce === "pre") return 0;
if (enforce === "post") return 2;
return 1;
}
/**
* Types a macro for inference and a single construction site, mirroring `definePlugin`.
* Adds no runtime behavior.
*
* @example
* ```ts
* const macroUntagged = defineMacro({
* name: 'untagged',
* operation(node) {
* return node.tags?.length ? undefined : { ...node, tags: ['untagged'] }
* },
* })
* ```
*/
function defineMacro(macro) {
return macro;
}
/**
* Runs every macro's callback for one node kind in order, chaining the result so each macro sees
* the previous macro's output. Returns `undefined` when nothing changed, so `transform` keeps the
* original reference (structural sharing).
*/
function chain({ macros, key, node, context }) {
let current = node;
for (const macro of macros) {
const callback = macro[key];
if (!callback) continue;
if (macro.when && !macro.when(current)) continue;
const next = callback(current, context);
if (next != null) current = next;
}
return current === node ? void 0 : current;
}
/**
* Folds an ordered list of macros into a single {@link Visitor} that `transform` (and the per-plugin
* transform layer in `@kubb/core`) can run. Macros are stable-sorted by `enforce`, then applied
* sequentially per node so later macros see earlier output. This differs from a plain visitor, which
* has no names, ordering, or composition.
*
* @example
* ```ts
* const visitor = composeMacros([macroSimplifyUnion, macroDiscriminatorEnum])
* const next = transform(root, visitor)
* ```
*/
function composeMacros(macros) {
const ordered = [...macros].sort((a, b) => enforceWeight(a.enforce) - enforceWeight(b.enforce));
const visitor = {};
for (const key of visitorKeys) {
if (!ordered.some((macro) => typeof macro[key] === "function")) continue;
const callback = (node, context) => chain({
macros: ordered,
key,
node,
context
});
visitor[key] = callback;
}
return visitor;
}
/**
* Runs a list of macros over a node tree and returns the rewritten tree. Keeps `transform`'s
* structural sharing, so an empty or no-op macro list returns the same reference. Pass
* `depth: 'shallow'` to rewrite the root node only.
*
* @example
* ```ts
* const next = applyMacros(root, [macroIntegerToString])
* ```
*
* @example Apply to the root node only
* ```ts
* const named = applyMacros(node, [macroEnumName({ parentName, propName, enumSuffix })], { depth: 'shallow' })
* ```
*/
function applyMacros(root, macros, options) {
if (macros.length === 0) return root;
return transform(root, {
...composeMacros(macros),
...options
});
}
//#endregion
export { composeMacros as n, defineMacro as r, applyMacros as t };
//# sourceMappingURL=defineMacro-CqX4m8Dq.js.map
{"version":3,"file":"defineMacro-CqX4m8Dq.js","names":[],"sources":["../src/defineMacro.ts"],"sourcesContent":["import type { VisitorDepth } from './constants.ts'\nimport type { VisitorKey } from './defineNode.ts'\nimport { visitorKeys } from './defineNode.ts'\nimport type { Node } from './nodes/index.ts'\nimport type { Visitor, VisitorContext } from './visitor.ts'\nimport { transform } from './visitor.ts'\n\n/**\n * Ordering hint shared by macros and plugins. `pre` runs before unmarked items, `post` after,\n * and `undefined` keeps declaration order.\n */\nexport type Enforce = 'pre' | 'post'\n\n/**\n * Sort weight for an `enforce` hint. `pre` sorts before unmarked items and `post` after, so a plain\n * list keeps its authored order.\n */\nfunction enforceWeight(enforce?: Enforce): number {\n if (enforce === 'pre') return 0\n if (enforce === 'post') return 2\n return 1\n}\n\n/**\n * A named, composable transform over the Kubb AST. It carries the same per-kind callbacks as a\n * {@link Visitor} (`schema`, `operation`, …), plus a `name`, an optional `enforce` order, and an\n * optional `when` gate. Macros run on the shared AST, so the same macro works across every adapter\n * and output target. Exports follow the `macro<Name>` convention, mirroring plugins (`pluginTs`).\n */\nexport type Macro = Visitor & {\n /**\n * Macro identifier used to tell macros apart, for example `'simplify-union'`.\n */\n name: string\n /**\n * Ordering hint. `pre` macros run before unmarked macros, `post` macros run after.\n * Ordering within a bucket follows list order.\n */\n enforce?: Enforce\n /**\n * Gate checked against the current node before any callback runs. When it returns `false`\n * the macro is skipped for that node.\n */\n when?: (node: Node) => boolean\n}\n\n/**\n * Types a macro for inference and a single construction site, mirroring `definePlugin`.\n * Adds no runtime behavior.\n *\n * @example\n * ```ts\n * const macroUntagged = defineMacro({\n * name: 'untagged',\n * operation(node) {\n * return node.tags?.length ? undefined : { ...node, tags: ['untagged'] }\n * },\n * })\n * ```\n */\nexport function defineMacro(macro: Macro): Macro {\n return macro\n}\n\ntype MacroCallback = (node: Node, context: VisitorContext) => Node | null | undefined\n\ntype ChainProps = {\n macros: ReadonlyArray<Macro>\n key: VisitorKey\n node: Node\n context: VisitorContext\n}\n\n/**\n * Runs every macro's callback for one node kind in order, chaining the result so each macro sees\n * the previous macro's output. Returns `undefined` when nothing changed, so `transform` keeps the\n * original reference (structural sharing).\n */\nfunction chain({ macros, key, node, context }: ChainProps): Node | undefined {\n let current = node\n\n for (const macro of macros) {\n const callback = macro[key] as MacroCallback | undefined\n if (!callback) continue\n if (macro.when && !macro.when(current)) continue\n\n const next = callback(current, context)\n if (next != null) current = next\n }\n\n return current === node ? undefined : current\n}\n\n/**\n * Folds an ordered list of macros into a single {@link Visitor} that `transform` (and the per-plugin\n * transform layer in `@kubb/core`) can run. Macros are stable-sorted by `enforce`, then applied\n * sequentially per node so later macros see earlier output. This differs from a plain visitor, which\n * has no names, ordering, or composition.\n *\n * @example\n * ```ts\n * const visitor = composeMacros([macroSimplifyUnion, macroDiscriminatorEnum])\n * const next = transform(root, visitor)\n * ```\n */\nexport function composeMacros(macros: ReadonlyArray<Macro>): Visitor {\n const ordered = [...macros].sort((a, b) => enforceWeight(a.enforce) - enforceWeight(b.enforce))\n\n const visitor: Visitor = {}\n for (const key of visitorKeys) {\n if (!ordered.some((macro) => typeof macro[key] === 'function')) continue\n\n const callback = (node: Node, context: VisitorContext) => chain({ macros: ordered, key, node, context })\n ;(visitor as Record<VisitorKey, MacroCallback>)[key] = callback\n }\n\n return visitor\n}\n\n/**\n * Runs a list of macros over a node tree and returns the rewritten tree. Keeps `transform`'s\n * structural sharing, so an empty or no-op macro list returns the same reference. Pass\n * `depth: 'shallow'` to rewrite the root node only.\n *\n * @example\n * ```ts\n * const next = applyMacros(root, [macroIntegerToString])\n * ```\n *\n * @example Apply to the root node only\n * ```ts\n * const named = applyMacros(node, [macroEnumName({ parentName, propName, enumSuffix })], { depth: 'shallow' })\n * ```\n */\nexport function applyMacros<TNode extends Node>(root: TNode, macros: ReadonlyArray<Macro>, options?: { depth?: VisitorDepth }): TNode {\n if (macros.length === 0) return root\n\n return transform(root, { ...composeMacros(macros), ...options }) as TNode\n}\n"],"mappings":";;;;;;;AAiBA,SAAS,cAAc,SAA2B;CAChD,IAAI,YAAY,OAAO,OAAO;CAC9B,IAAI,YAAY,QAAQ,OAAO;CAC/B,OAAO;AACT;;;;;;;;;;;;;;;AAuCA,SAAgB,YAAY,OAAqB;CAC/C,OAAO;AACT;;;;;;AAgBA,SAAS,MAAM,EAAE,QAAQ,KAAK,MAAM,WAAyC;CAC3E,IAAI,UAAU;CAEd,KAAK,MAAM,SAAS,QAAQ;EAC1B,MAAM,WAAW,MAAM;EACvB,IAAI,CAAC,UAAU;EACf,IAAI,MAAM,QAAQ,CAAC,MAAM,KAAK,OAAO,GAAG;EAExC,MAAM,OAAO,SAAS,SAAS,OAAO;EACtC,IAAI,QAAQ,MAAM,UAAU;CAC9B;CAEA,OAAO,YAAY,OAAO,KAAA,IAAY;AACxC;;;;;;;;;;;;;AAcA,SAAgB,cAAc,QAAuC;CACnE,MAAM,UAAU,CAAC,GAAG,MAAM,CAAC,CAAC,MAAM,GAAG,MAAM,cAAc,EAAE,OAAO,IAAI,cAAc,EAAE,OAAO,CAAC;CAE9F,MAAM,UAAmB,CAAC;CAC1B,KAAK,MAAM,OAAO,aAAa;EAC7B,IAAI,CAAC,QAAQ,MAAM,UAAU,OAAO,MAAM,SAAS,UAAU,GAAG;EAEhE,MAAM,YAAY,MAAY,YAA4B,MAAM;GAAE,QAAQ;GAAS;GAAK;GAAM;EAAQ,CAAC;EACtG,QAA+C,OAAO;CACzD;CAEA,OAAO;AACT;;;;;;;;;;;;;;;;AAiBA,SAAgB,YAAgC,MAAa,QAA8B,SAA2C;CACpI,IAAI,OAAO,WAAW,GAAG,OAAO;CAEhC,OAAO,UAAU,MAAM;EAAE,GAAG,cAAc,MAAM;EAAG,GAAG;CAAQ,CAAC;AACjE"}
const require_visitor = require("./visitor-h6dEM3vR.cjs");
//#region src/defineMacro.ts
/**
* Sort weight for an `enforce` hint. `pre` sorts before unmarked items and `post` after, so a plain
* list keeps its authored order.
*/
function enforceWeight(enforce) {
if (enforce === "pre") return 0;
if (enforce === "post") return 2;
return 1;
}
/**
* Types a macro for inference and a single construction site, mirroring `definePlugin`.
* Adds no runtime behavior.
*
* @example
* ```ts
* const macroUntagged = defineMacro({
* name: 'untagged',
* operation(node) {
* return node.tags?.length ? undefined : { ...node, tags: ['untagged'] }
* },
* })
* ```
*/
function defineMacro(macro) {
return macro;
}
/**
* Runs every macro's callback for one node kind in order, chaining the result so each macro sees
* the previous macro's output. Returns `undefined` when nothing changed, so `transform` keeps the
* original reference (structural sharing).
*/
function chain({ macros, key, node, context }) {
let current = node;
for (const macro of macros) {
const callback = macro[key];
if (!callback) continue;
if (macro.when && !macro.when(current)) continue;
const next = callback(current, context);
if (next != null) current = next;
}
return current === node ? void 0 : current;
}
/**
* Folds an ordered list of macros into a single {@link Visitor} that `transform` (and the per-plugin
* transform layer in `@kubb/core`) can run. Macros are stable-sorted by `enforce`, then applied
* sequentially per node so later macros see earlier output. This differs from a plain visitor, which
* has no names, ordering, or composition.
*
* @example
* ```ts
* const visitor = composeMacros([macroSimplifyUnion, macroDiscriminatorEnum])
* const next = transform(root, visitor)
* ```
*/
function composeMacros(macros) {
const ordered = [...macros].sort((a, b) => enforceWeight(a.enforce) - enforceWeight(b.enforce));
const visitor = {};
for (const key of require_visitor.visitorKeys) {
if (!ordered.some((macro) => typeof macro[key] === "function")) continue;
const callback = (node, context) => chain({
macros: ordered,
key,
node,
context
});
visitor[key] = callback;
}
return visitor;
}
/**
* Runs a list of macros over a node tree and returns the rewritten tree. Keeps `transform`'s
* structural sharing, so an empty or no-op macro list returns the same reference. Pass
* `depth: 'shallow'` to rewrite the root node only.
*
* @example
* ```ts
* const next = applyMacros(root, [macroIntegerToString])
* ```
*
* @example Apply to the root node only
* ```ts
* const named = applyMacros(node, [macroEnumName({ parentName, propName, enumSuffix })], { depth: 'shallow' })
* ```
*/
function applyMacros(root, macros, options) {
if (macros.length === 0) return root;
return require_visitor.transform(root, {
...composeMacros(macros),
...options
});
}
//#endregion
Object.defineProperty(exports, "applyMacros", {
enumerable: true,
get: function() {
return applyMacros;
}
});
Object.defineProperty(exports, "composeMacros", {
enumerable: true,
get: function() {
return composeMacros;
}
});
Object.defineProperty(exports, "defineMacro", {
enumerable: true,
get: function() {
return defineMacro;
}
});
//# sourceMappingURL=defineMacro-DmGR7vfu.cjs.map
{"version":3,"file":"defineMacro-DmGR7vfu.cjs","names":["visitorKeys","transform"],"sources":["../src/defineMacro.ts"],"sourcesContent":["import type { VisitorDepth } from './constants.ts'\nimport type { VisitorKey } from './defineNode.ts'\nimport { visitorKeys } from './defineNode.ts'\nimport type { Node } from './nodes/index.ts'\nimport type { Visitor, VisitorContext } from './visitor.ts'\nimport { transform } from './visitor.ts'\n\n/**\n * Ordering hint shared by macros and plugins. `pre` runs before unmarked items, `post` after,\n * and `undefined` keeps declaration order.\n */\nexport type Enforce = 'pre' | 'post'\n\n/**\n * Sort weight for an `enforce` hint. `pre` sorts before unmarked items and `post` after, so a plain\n * list keeps its authored order.\n */\nfunction enforceWeight(enforce?: Enforce): number {\n if (enforce === 'pre') return 0\n if (enforce === 'post') return 2\n return 1\n}\n\n/**\n * A named, composable transform over the Kubb AST. It carries the same per-kind callbacks as a\n * {@link Visitor} (`schema`, `operation`, …), plus a `name`, an optional `enforce` order, and an\n * optional `when` gate. Macros run on the shared AST, so the same macro works across every adapter\n * and output target. Exports follow the `macro<Name>` convention, mirroring plugins (`pluginTs`).\n */\nexport type Macro = Visitor & {\n /**\n * Macro identifier used to tell macros apart, for example `'simplify-union'`.\n */\n name: string\n /**\n * Ordering hint. `pre` macros run before unmarked macros, `post` macros run after.\n * Ordering within a bucket follows list order.\n */\n enforce?: Enforce\n /**\n * Gate checked against the current node before any callback runs. When it returns `false`\n * the macro is skipped for that node.\n */\n when?: (node: Node) => boolean\n}\n\n/**\n * Types a macro for inference and a single construction site, mirroring `definePlugin`.\n * Adds no runtime behavior.\n *\n * @example\n * ```ts\n * const macroUntagged = defineMacro({\n * name: 'untagged',\n * operation(node) {\n * return node.tags?.length ? undefined : { ...node, tags: ['untagged'] }\n * },\n * })\n * ```\n */\nexport function defineMacro(macro: Macro): Macro {\n return macro\n}\n\ntype MacroCallback = (node: Node, context: VisitorContext) => Node | null | undefined\n\ntype ChainProps = {\n macros: ReadonlyArray<Macro>\n key: VisitorKey\n node: Node\n context: VisitorContext\n}\n\n/**\n * Runs every macro's callback for one node kind in order, chaining the result so each macro sees\n * the previous macro's output. Returns `undefined` when nothing changed, so `transform` keeps the\n * original reference (structural sharing).\n */\nfunction chain({ macros, key, node, context }: ChainProps): Node | undefined {\n let current = node\n\n for (const macro of macros) {\n const callback = macro[key] as MacroCallback | undefined\n if (!callback) continue\n if (macro.when && !macro.when(current)) continue\n\n const next = callback(current, context)\n if (next != null) current = next\n }\n\n return current === node ? undefined : current\n}\n\n/**\n * Folds an ordered list of macros into a single {@link Visitor} that `transform` (and the per-plugin\n * transform layer in `@kubb/core`) can run. Macros are stable-sorted by `enforce`, then applied\n * sequentially per node so later macros see earlier output. This differs from a plain visitor, which\n * has no names, ordering, or composition.\n *\n * @example\n * ```ts\n * const visitor = composeMacros([macroSimplifyUnion, macroDiscriminatorEnum])\n * const next = transform(root, visitor)\n * ```\n */\nexport function composeMacros(macros: ReadonlyArray<Macro>): Visitor {\n const ordered = [...macros].sort((a, b) => enforceWeight(a.enforce) - enforceWeight(b.enforce))\n\n const visitor: Visitor = {}\n for (const key of visitorKeys) {\n if (!ordered.some((macro) => typeof macro[key] === 'function')) continue\n\n const callback = (node: Node, context: VisitorContext) => chain({ macros: ordered, key, node, context })\n ;(visitor as Record<VisitorKey, MacroCallback>)[key] = callback\n }\n\n return visitor\n}\n\n/**\n * Runs a list of macros over a node tree and returns the rewritten tree. Keeps `transform`'s\n * structural sharing, so an empty or no-op macro list returns the same reference. Pass\n * `depth: 'shallow'` to rewrite the root node only.\n *\n * @example\n * ```ts\n * const next = applyMacros(root, [macroIntegerToString])\n * ```\n *\n * @example Apply to the root node only\n * ```ts\n * const named = applyMacros(node, [macroEnumName({ parentName, propName, enumSuffix })], { depth: 'shallow' })\n * ```\n */\nexport function applyMacros<TNode extends Node>(root: TNode, macros: ReadonlyArray<Macro>, options?: { depth?: VisitorDepth }): TNode {\n if (macros.length === 0) return root\n\n return transform(root, { ...composeMacros(macros), ...options }) as TNode\n}\n"],"mappings":";;;;;;AAiBA,SAAS,cAAc,SAA2B;CAChD,IAAI,YAAY,OAAO,OAAO;CAC9B,IAAI,YAAY,QAAQ,OAAO;CAC/B,OAAO;AACT;;;;;;;;;;;;;;;AAuCA,SAAgB,YAAY,OAAqB;CAC/C,OAAO;AACT;;;;;;AAgBA,SAAS,MAAM,EAAE,QAAQ,KAAK,MAAM,WAAyC;CAC3E,IAAI,UAAU;CAEd,KAAK,MAAM,SAAS,QAAQ;EAC1B,MAAM,WAAW,MAAM;EACvB,IAAI,CAAC,UAAU;EACf,IAAI,MAAM,QAAQ,CAAC,MAAM,KAAK,OAAO,GAAG;EAExC,MAAM,OAAO,SAAS,SAAS,OAAO;EACtC,IAAI,QAAQ,MAAM,UAAU;CAC9B;CAEA,OAAO,YAAY,OAAO,KAAA,IAAY;AACxC;;;;;;;;;;;;;AAcA,SAAgB,cAAc,QAAuC;CACnE,MAAM,UAAU,CAAC,GAAG,MAAM,CAAC,CAAC,MAAM,GAAG,MAAM,cAAc,EAAE,OAAO,IAAI,cAAc,EAAE,OAAO,CAAC;CAE9F,MAAM,UAAmB,CAAC;CAC1B,KAAK,MAAM,OAAOA,gBAAAA,aAAa;EAC7B,IAAI,CAAC,QAAQ,MAAM,UAAU,OAAO,MAAM,SAAS,UAAU,GAAG;EAEhE,MAAM,YAAY,MAAY,YAA4B,MAAM;GAAE,QAAQ;GAAS;GAAK;GAAM;EAAQ,CAAC;EACtG,QAA+C,OAAO;CACzD;CAEA,OAAO;AACT;;;;;;;;;;;;;;;;AAiBA,SAAgB,YAAgC,MAAa,QAA8B,SAA2C;CACpI,IAAI,OAAO,WAAW,GAAG,OAAO;CAEhC,OAAOC,gBAAAA,UAAU,MAAM;EAAE,GAAG,cAAc,MAAM;EAAG,GAAG;CAAQ,CAAC;AACjE"}
import { n as __name } from "./rolldown-runtime-CNktS9qV.js";
import { B as ContentNode, C as ParameterNode, et as SchemaNode, f as OperationNode, h as ResponseNode, lt as PropertyNode, n as OutputNode, o as InputNode, t as Node, y as RequestBodyNode } from "./index-Cu2zmNxv.js";
//#region src/constants.d.ts
/**
* Traversal depth for AST visitor utilities.
*
* - `'shallow'` visits only the immediate node, skipping children.
* - `'deep'` recursively visits all descendant nodes.
*/
type VisitorDepth = 'shallow' | 'deep';
/**
* Schema type discriminators used by all AST schema nodes.
*
* Each value is a stable discriminator across the AST (for example `schema.type === schemaTypes.object`).
*/
declare const schemaTypes: {
/**
* Text value.
*/
readonly string: "string";
/**
* Floating-point number (`float`, `double`).
*/
readonly number: "number";
/**
* Whole number (`int32`). Use `bigint` for `int64`.
*/
readonly integer: "integer";
/**
* 64-bit integer (`int64`). Only used when `integerType` is set to `'bigint'`.
*/
readonly bigint: "bigint";
/**
* Boolean value.
*/
readonly boolean: "boolean";
/**
* Explicit null value.
*/
readonly null: "null";
/**
* Any value (no type restriction).
*/
readonly any: "any";
/**
* Unknown value (must be narrowed before usage).
*/
readonly unknown: "unknown";
/**
* No return value (`void`).
*/
readonly void: "void";
/**
* Object with named properties.
*/
readonly object: "object";
/**
* Sequential list of items.
*/
readonly array: "array";
/**
* Fixed-length list with position-specific items.
*/
readonly tuple: "tuple";
/**
* "One of" multiple schema members.
*/
readonly union: "union";
/**
* "All of" multiple schema members.
*/
readonly intersection: "intersection";
/**
* Enum schema.
*/
readonly enum: "enum";
/**
* Reference to another schema.
*/
readonly ref: "ref";
/**
* Calendar date (for example `2026-03-24`).
*/
readonly date: "date";
/**
* Date-time value (for example `2026-03-24T09:00:00Z`).
*/
readonly datetime: "datetime";
/**
* Time-only value (for example `09:00:00`).
*/
readonly time: "time";
/**
* UUID value.
*/
readonly uuid: "uuid";
/**
* Email address value.
*/
readonly email: "email";
/**
* URL value.
*/
readonly url: "url";
/**
* IPv4 address value.
*/
readonly ipv4: "ipv4";
/**
* IPv6 address value.
*/
readonly ipv6: "ipv6";
/**
* Binary/blob value.
*/
readonly blob: "blob";
/**
* Impossible value (`never`).
*/
readonly never: "never";
};
//#endregion
//#region src/visitor.d.ts
/**
* Ordered mapping of `[NodeType, ParentType]` pairs.
*
* `ParentOf` uses this map to find parent types.
*/
type ParentNodeMap = [[InputNode, undefined], [OutputNode, undefined], [OperationNode, InputNode], [RequestBodyNode, OperationNode], [ContentNode, RequestBodyNode | ResponseNode], [SchemaNode, InputNode | ContentNode | SchemaNode | PropertyNode | ParameterNode], [PropertyNode, SchemaNode], [ParameterNode, OperationNode], [ResponseNode, OperationNode]];
/**
* Resolves the parent node type for a given AST node type.
*
* Visitor context relies on this so `ctx.parent` is typed for each callback.
*
* @example
* ```ts
* type InputParent = ParentOf<InputNode>
* // undefined
* ```
*
* @example
* ```ts
* type PropertyParent = ParentOf<PropertyNode>
* // SchemaNode
* ```
*
* @example
* ```ts
* type SchemaParent = ParentOf<SchemaNode>
* // InputNode | ContentNode | SchemaNode | PropertyNode | ParameterNode
* ```
*/
type ParentOf<T extends Node, TEntries extends ReadonlyArray<[Node, unknown]> = ParentNodeMap> = TEntries extends [infer TEntry extends [Node, unknown], ...infer TRest extends ReadonlyArray<[Node, unknown]>] ? T extends TEntry[0] ? TEntry[1] : ParentOf<T, TRest> : Node;
/**
* Traversal context passed as the second argument to every visitor callback.
* `parent` is typed from the current node type.
*
* @example
* ```ts
* const visitor: Visitor = {
* schema(node, { parent }) {
* // parent type is narrowed by node kind
* },
* }
* ```
*/
type VisitorContext<T extends Node = Node> = {
/**
* Parent node of the currently visited node.
* For `InputNode`, this is `undefined`.
*/
parent?: ParentOf<T>;
};
/**
* Synchronous visitor consumed by `transform`. Each optional callback runs
* for the matching node type. Return a new node to replace it, or `undefined`
* to leave it untouched.
*
* Plugins typically expose `transformer` so users can supply a `Visitor` that
* rewrites the AST before printing.
*
* @example Prefix every operationId
* ```ts
* const visitor: Visitor = {
* operation(node) {
* return { ...node, operationId: `api_${node.operationId}` }
* },
* }
* ```
*
* @example Strip schema descriptions
* ```ts
* const visitor: Visitor = {
* schema(node) {
* return { ...node, description: undefined }
* },
* }
* ```
*/
type Visitor = {
input?(node: InputNode, context: VisitorContext<InputNode>): undefined | null | InputNode;
output?(node: OutputNode, context: VisitorContext<OutputNode>): undefined | null | OutputNode;
operation?(node: OperationNode, context: VisitorContext<OperationNode>): undefined | null | OperationNode;
schema?(node: SchemaNode, context: VisitorContext<SchemaNode>): undefined | null | SchemaNode;
property?(node: PropertyNode, context: VisitorContext<PropertyNode>): undefined | null | PropertyNode;
parameter?(node: ParameterNode, context: VisitorContext<ParameterNode>): undefined | null | ParameterNode;
response?(node: ResponseNode, context: VisitorContext<ResponseNode>): undefined | null | ResponseNode;
};
/**
* A visitor callback result that may be sync or async.
*/
type MaybePromise<T> = T | Promise<T>;
/**
* Async visitor for `walk`. Synchronous `Visitor` objects are compatible.
*
* @example
* ```ts
* const visitor: AsyncVisitor = {
* async operation(node) {
* await Promise.resolve(node.operationId)
* },
* }
* ```
*/
type AsyncVisitor = {
input?(node: InputNode, context: VisitorContext<InputNode>): MaybePromise<undefined | null | InputNode>;
output?(node: OutputNode, context: VisitorContext<OutputNode>): MaybePromise<undefined | null | OutputNode>;
operation?(node: OperationNode, context: VisitorContext<OperationNode>): MaybePromise<undefined | null | OperationNode>;
schema?(node: SchemaNode, context: VisitorContext<SchemaNode>): MaybePromise<undefined | null | SchemaNode>;
property?(node: PropertyNode, context: VisitorContext<PropertyNode>): MaybePromise<undefined | null | PropertyNode>;
parameter?(node: ParameterNode, context: VisitorContext<ParameterNode>): MaybePromise<undefined | null | ParameterNode>;
response?(node: ResponseNode, context: VisitorContext<ResponseNode>): MaybePromise<undefined | null | ResponseNode>;
};
/**
* Visitor used by `collect`.
*
* @example
* ```ts
* const visitor: CollectVisitor<string> = {
* operation(node) {
* return node.operationId
* },
* }
* ```
*/
type CollectVisitor<T> = {
input?(node: InputNode, context: VisitorContext<InputNode>): T | null | undefined;
output?(node: OutputNode, context: VisitorContext<OutputNode>): T | null | undefined;
operation?(node: OperationNode, context: VisitorContext<OperationNode>): T | null | undefined;
schema?(node: SchemaNode, context: VisitorContext<SchemaNode>): T | null | undefined;
property?(node: PropertyNode, context: VisitorContext<PropertyNode>): T | null | undefined;
parameter?(node: ParameterNode, context: VisitorContext<ParameterNode>): T | null | undefined;
response?(node: ResponseNode, context: VisitorContext<ResponseNode>): T | null | undefined;
};
/**
* Options for `transform`.
*
* @example
* ```ts
* const options: TransformOptions = { depth: 'deep', schema: (node) => node }
* ```
*
* @example
* ```ts
* // Only transform the current node, not nested children
* const options: TransformOptions = { depth: 'shallow', schema: (node) => node }
* ```
*/
type TransformOptions = Visitor & {
/**
* Traversal depth.
* @default 'deep'
*/
depth?: VisitorDepth;
/**
* Internal parent override used during recursion.
*/
parent?: Node;
};
/**
* Options for `walk`.
*
* @example
* ```ts
* const options: WalkOptions = { depth: 'deep', concurrency: 10, root: () => {} }
* ```
*/
type WalkOptions = AsyncVisitor & {
/**
* Traversal depth.
* @default 'deep'
*/
depth?: VisitorDepth;
/**
* Maximum number of sibling nodes visited concurrently.
* @default 30
*/
concurrency?: number;
};
/**
* Options for `collect`.
*
* @example
* ```ts
* const options: CollectOptions<string> = { depth: 'shallow', schema: () => undefined }
* ```
*/
type CollectOptions<T> = CollectVisitor<T> & {
/**
* Traversal depth.
* @default 'deep'
*/
depth?: VisitorDepth;
/**
* Internal parent override used during recursion.
*/
parent?: Node;
};
/**
* Async depth-first traversal for side effects. Visitor return values are
* ignored. Use `transform` when you want to rewrite nodes.
*
* Sibling nodes at each depth run concurrently up to `options.concurrency`
* (defaults to `WALK_CONCURRENCY`). Higher values overlap I/O-bound visitor
* work. Lower values reduce memory pressure.
*
* @example Log every operation
* ```ts
* await walk(root, {
* operation(node) {
* console.log(node.operationId)
* },
* })
* ```
*
* @example Only visit the root node
* ```ts
* await walk(root, { depth: 'shallow', input: () => {} })
* ```
*/
declare function walk(node: Node, options: WalkOptions): Promise<void>;
/**
* Synchronous depth-first transform. Each visitor callback can return a
* replacement node. Returning `undefined` keeps the original.
*
* The original tree is never mutated, a new tree is returned. Pass
* `depth: 'shallow'` to skip recursion into children.
*
* @example Prefix every operationId
* ```ts
* const next = transform(root, {
* operation(node) {
* return { ...node, operationId: `prefixed_${node.operationId}` }
* },
* })
* ```
*
* @example Replace only the root node
* ```ts
* const next = transform(root, {
* depth: 'shallow',
* input: (node) => ({ ...node, meta: { ...node.meta, title: 'Rewritten' } }),
* })
* ```
*/
declare function transform(node: InputNode, options: TransformOptions): InputNode;
declare function transform(node: OutputNode, options: TransformOptions): OutputNode;
declare function transform(node: OperationNode, options: TransformOptions): OperationNode;
declare function transform(node: SchemaNode, options: TransformOptions): SchemaNode;
declare function transform(node: PropertyNode, options: TransformOptions): PropertyNode;
declare function transform(node: ParameterNode, options: TransformOptions): ParameterNode;
declare function transform(node: ResponseNode, options: TransformOptions): ResponseNode;
declare function transform(node: Node, options: TransformOptions): Node;
/**
* Eager depth-first collection pass. Gathers every non-null value the visitor
* callbacks return into an array.
*
* @example Collect every operationId
* ```ts
* const ids = collect<string>(root, {
* operation(node) {
* return node.operationId
* },
* })
* ```
*/
declare function collect<T>(node: Node, options: CollectOptions<T>): Array<T>;
//#endregion
//#region src/defineMacro.d.ts
/**
* Ordering hint shared by macros and plugins. `pre` runs before unmarked items, `post` after,
* and `undefined` keeps declaration order.
*/
type Enforce = 'pre' | 'post';
/**
* A named, composable transform over the Kubb AST. It carries the same per-kind callbacks as a
* {@link Visitor} (`schema`, `operation`, …), plus a `name`, an optional `enforce` order, and an
* optional `when` gate. Macros run on the shared AST, so the same macro works across every adapter
* and output target. Exports follow the `macro<Name>` convention, mirroring plugins (`pluginTs`).
*/
type Macro = Visitor & {
/**
* Macro identifier used to tell macros apart, for example `'simplify-union'`.
*/
name: string;
/**
* Ordering hint. `pre` macros run before unmarked macros, `post` macros run after.
* Ordering within a bucket follows list order.
*/
enforce?: Enforce;
/**
* Gate checked against the current node before any callback runs. When it returns `false`
* the macro is skipped for that node.
*/
when?: (node: Node) => boolean;
};
/**
* Types a macro for inference and a single construction site, mirroring `definePlugin`.
* Adds no runtime behavior.
*
* @example
* ```ts
* const macroUntagged = defineMacro({
* name: 'untagged',
* operation(node) {
* return node.tags?.length ? undefined : { ...node, tags: ['untagged'] }
* },
* })
* ```
*/
declare function defineMacro(macro: Macro): Macro;
/**
* Folds an ordered list of macros into a single {@link Visitor} that `transform` (and the per-plugin
* transform layer in `@kubb/core`) can run. Macros are stable-sorted by `enforce`, then applied
* sequentially per node so later macros see earlier output. This differs from a plain visitor, which
* has no names, ordering, or composition.
*
* @example
* ```ts
* const visitor = composeMacros([macroSimplifyUnion, macroDiscriminatorEnum])
* const next = transform(root, visitor)
* ```
*/
declare function composeMacros(macros: ReadonlyArray<Macro>): Visitor;
/**
* Runs a list of macros over a node tree and returns the rewritten tree. Keeps `transform`'s
* structural sharing, so an empty or no-op macro list returns the same reference. Pass
* `depth: 'shallow'` to rewrite the root node only.
*
* @example
* ```ts
* const next = applyMacros(root, [macroIntegerToString])
* ```
*
* @example Apply to the root node only
* ```ts
* const named = applyMacros(node, [macroEnumName({ parentName, propName, enumSuffix })], { depth: 'shallow' })
* ```
*/
declare function applyMacros<TNode extends Node>(root: TNode, macros: ReadonlyArray<Macro>, options?: {
depth?: VisitorDepth;
}): TNode;
//#endregion
export { defineMacro as a, VisitorContext as c, walk as d, schemaTypes as f, composeMacros as i, collect as l, Macro as n, ParentOf as o, applyMacros as r, Visitor as s, Enforce as t, transform as u };
//# sourceMappingURL=defineMacro-DzsACbFo.d.ts.map
import { n as __name } from "./rolldown-runtime-CNktS9qV.js";
//#region src/nodes/base.d.ts
/**
* `kind` values used by AST nodes.
*
* @example
* ```ts
* const kind: NodeKind = 'Schema'
* ```
*/
type NodeKind = 'Input' | 'Output' | 'Operation' | 'Schema' | 'Property' | 'Parameter' | 'Response' | 'RequestBody' | 'Content' | 'Type' | 'File' | 'Import' | 'Export' | 'Source' | 'Const' | 'Function' | 'ArrowFunction' | 'Text' | 'Break' | 'Jsx';
/**
* Base shape shared by all AST nodes.
*
* @example
* ```ts
* const base: BaseNode = { kind: 'Input' }
* ```
*/
type BaseNode = {
/**
* Node discriminator.
*/
kind: NodeKind;
};
//#endregion
//#region src/defineNode.d.ts
/**
* Visitor callback names, one per traversable node kind, in traversal order.
* Kept in sync with the keys of `Visitor` in `visitor.ts`.
*/
declare const visitorKeys: readonly ["input", "output", "operation", "schema", "property", "parameter", "response"];
/**
* One of the {@link visitorKeys} callback names.
*/
type VisitorKey = (typeof visitorKeys)[number];
/**
* Distributive `Omit` that preserves each member of a union.
*
* @example
* ```ts
* type A = { kind: 'a'; keep: string; drop: number }
* type B = { kind: 'b'; keep: boolean; drop: number }
* type Result = DistributiveOmit<A | B, 'drop'>
* // -> { kind: 'a'; keep: string } | { kind: 'b'; keep: boolean }
* ```
*/
type DistributiveOmit<T, K extends PropertyKey> = T extends unknown ? Omit<T, K> : never;
/**
* The single definition derived from one {@link defineNode} call: the node's
* `create` builder, its `is` guard, and the traversal metadata the registry
* collects into the visitor tables.
*/
type NodeDef<TNode extends BaseNode = BaseNode, TInput = never> = {
/**
* Node discriminator this definition owns.
*/
kind: NodeKind;
/**
* Builds a node from its input, applying `defaults` and the optional `build` hook.
*/
create: (input: TInput) => TNode;
/**
* Type guard matching this node kind.
*/
is: (node: unknown) => node is TNode;
/**
* Child node fields in traversal order. Feeds `VISITOR_KEYS`.
*/
children?: ReadonlyArray<string>;
/**
* Visitor callback name. Feeds `VISITOR_KEY_BY_KIND`.
*/
visitorKey?: VisitorKey;
};
type DefineNodeConfig<TNode extends BaseNode, TInput, TBuilt extends object> = {
kind: TNode['kind'];
defaults?: Partial<TNode>;
build?: (input: TInput) => TBuilt;
children?: ReadonlyArray<string>;
visitorKey?: VisitorKey;
};
/**
* Defines a node once and derives its `create` builder, `is` guard, and traversal
* metadata. `create` merges `defaults`, the `build` hook (or the raw input), and the
* `kind`, so node construction lives in one place without scattered `as` casts.
*
* @example Simple node
* ```ts
* const importDef = defineNode<ImportNode>({ kind: 'Import' })
* const createImport = importDef.create
* ```
*
* @example Node with a build hook
* ```ts
* const propertyDef = defineNode<PropertyNode, UserPropertyNode>({
* kind: 'Property',
* build: (props) => ({ ...props, required: props.required ?? false }),
* children: ['schema'],
* visitorKey: 'property',
* })
* ```
*/
declare function defineNode<TNode extends BaseNode, TInput = Omit<TNode, 'kind'>, TBuilt extends object = Omit<TNode, 'kind'>>(config: DefineNodeConfig<TNode, TInput, TBuilt>): NodeDef<TNode, TInput>;
//#endregion
//#region src/nodes/code.d.ts
/**
* JSDoc documentation metadata attached to code declarations.
*/
type JSDocNode = {
/**
* JSDoc comment lines. `undefined` entries are filtered out during rendering.
*
* @example
* ```ts
* ['@description A pet resource', '@deprecated']
* ```
*/
comments?: Array<string | undefined>;
};
/**
* AST node representing a TypeScript `const` declaration.
*
* Mirrors the props of the `Const` component from `@kubb/renderer-jsx`.
* The `children` prop of the component is represented as `nodes`.
*
* @example
* ```ts
* createConst({ name: 'pet', export: true, asConst: true })
* // export const pet = ... as const
* ```
*/
type ConstNode = BaseNode & {
kind: 'Const';
/**
* Name of the constant declaration.
*/
name: string;
/**
* Whether the declaration should be exported.
*/
export?: boolean | null;
/**
* Explicit type annotation.
*
* @example Type reference
* `'Pet'`
*/
type?: string | null;
/**
* JSDoc documentation metadata.
*/
JSDoc?: JSDocNode | null;
/**
* Whether to append `as const` to the declaration.
*/
asConst?: boolean | null;
/**
* Child nodes representing the value of the constant (children of the `Const` component).
* Each entry is a {@link CodeNode}. Use {@link TextNode} for raw string content.
*/
nodes?: Array<CodeNode>;
};
/**
* AST node representing a TypeScript `type` alias declaration.
*
* Mirrors the props of the `Type` component from `@kubb/renderer-jsx`.
* The `children` prop of the component is represented as `nodes`.
*
* @example
* ```ts
* createType({ name: 'Pet', export: true })
* // export type Pet = ...
* ```
*/
type TypeNode = BaseNode & {
kind: 'Type';
/**
* Name of the type alias.
*/
name: string;
/**
* Whether the declaration should be exported.
*/
export?: boolean | null;
/**
* JSDoc documentation metadata.
*/
JSDoc?: JSDocNode | null;
/**
* Child nodes representing the type body (children of the `Type` component).
* Each entry is a {@link CodeNode}. Use {@link TextNode} for raw string content.
*/
nodes?: Array<CodeNode>;
};
/**
* AST node representing a TypeScript `function` declaration.
*
* Mirrors the props of the `Function` component from `@kubb/renderer-jsx`.
* The `children` prop of the component is represented as `nodes`.
*
* @example
* ```ts
* createFunctionDeclaration({ name: 'getPet', export: true, async: true, returnType: 'Pet' })
* // export async function getPet(): Promise<Pet> { ... }
* ```
*/
type FunctionNode = BaseNode & {
kind: 'Function';
/**
* Name of the function.
*/
name: string;
/**
* Whether the function is a default export.
*/
default?: boolean | null;
/**
* Function parameter list as a pre-rendered string, written verbatim between the parentheses.
*
* @example
* `'id: string, config: Config = {}'`
*/
params?: string | null;
/**
* Whether the function should be exported.
*/
export?: boolean | null;
/**
* Whether the function is async. When `true`, the return type is wrapped in `Promise<>`.
*/
async?: boolean | null;
/**
* TypeScript generic type parameters.
*
* @example Constrained generics
* `['T', 'U extends string']`
*/
generics?: string | Array<string> | null;
/**
* Return type annotation.
*
* @example Type reference
* `'Pet'`
*/
returnType?: string | null;
/**
* JSDoc documentation metadata.
*/
JSDoc?: JSDocNode | null;
/**
* Child nodes representing the function body (children of the `Function` component).
* Each entry is a {@link CodeNode}. Use {@link TextNode} for raw string content.
*/
nodes?: Array<CodeNode>;
};
/**
* AST node representing a TypeScript arrow function (`const name = () => { ... }`).
*
* Mirrors the props of the `Function.Arrow` component from `@kubb/renderer-jsx`.
* The `children` prop of the component is represented as `nodes`.
*
* @example
* ```ts
* createArrowFunctionDeclaration({ name: 'getPet', export: true, singleLine: true })
* // export const getPet = () => ...
* ```
*/
type ArrowFunctionNode = Omit<FunctionNode, 'kind'> & {
kind: 'ArrowFunction';
/**
* Render the arrow function body as a single-line expression.
*/
singleLine?: boolean | null;
};
/**
* AST node representing a raw text/string fragment in the source output.
*
* Used instead of bare `string` values so that all entries in `nodes` arrays
* are typed `CodeNode` objects rather than a mixed `CodeNode | string` union.
*
* @example
* ```ts
* createText('return fetch(id)')
* // { kind: 'Text', value: 'return fetch(id)' }
* ```
*/
type TextNode = BaseNode & {
kind: 'Text';
/**
* The raw string content.
*/
value: string;
};
/**
* AST node representing a blank line in the source output.
*
* Corresponds to `<br/>` in JSX components. `printNodes` turns a `Break` between two
* statements into one blank line. Consecutive breaks, and breaks at the start or end of
* the list, are folded away, so a `Break` never produces more than one blank line.
*
* @example
* ```ts
* createBreak()
* // { kind: 'Break' }
* ```
*/
type BreakNode = BaseNode & {
kind: 'Break';
};
/**
* AST node representing a raw JSX fragment in the source output.
*
* Mirrors the `Jsx` component from `@kubb/renderer-jsx`. Embeds raw JSX/TSX markup
* (including fragments `<>…</>`) directly in generated code.
*
* @example
* ```ts
* createJsx('<>\n <a href={href}>Open</a>\n</>')
* // { kind: 'Jsx', value: '<>\n <a href={href}>Open</a>\n</>' }
* ```
*/
type JsxNode = BaseNode & {
kind: 'Jsx';
/**
* The raw JSX string content.
*/
value: string;
};
/**
* Union of all code-generation AST nodes.
*
* These nodes mirror the JSX components from `@kubb/renderer-jsx` and are used as
* structured children in {@link SourceNode.nodes}.
*/
type CodeNode = ConstNode | TypeNode | FunctionNode | ArrowFunctionNode | TextNode | BreakNode | JsxNode;
/**
* Definition for the {@link ConstNode}.
*/
declare const constDef: NodeDef<ConstNode, Omit<ConstNode, "kind">>;
/**
* Definition for the {@link TypeNode}.
*/
declare const typeDef: NodeDef<TypeNode, Omit<TypeNode, "kind">>;
/**
* Definition for the {@link FunctionNode}.
*/
declare const functionDef: NodeDef<FunctionNode, Omit<FunctionNode, "kind">>;
/**
* Definition for the {@link ArrowFunctionNode}.
*/
declare const arrowFunctionDef: NodeDef<ArrowFunctionNode, Omit<ArrowFunctionNode, "kind">>;
/**
* Definition for the {@link TextNode}.
*/
declare const textDef: NodeDef<TextNode, string>;
/**
* Definition for the {@link BreakNode}.
*/
declare const breakDef: NodeDef<BreakNode, void>;
/**
* Definition for the {@link JsxNode}.
*/
declare const jsxDef: NodeDef<JsxNode, string>;
/**
* Creates a `ConstNode` representing a TypeScript `const` declaration.
*
* @example Exported constant with type and `as const`
* ```ts
* createConst({ name: 'pets', export: true, type: 'Pet[]', asConst: true })
* // export const pets: Pet[] = ... as const
* ```
*/
declare const createConst: (input: Omit<ConstNode, "kind">) => ConstNode;
/**
* Creates a `TypeNode` representing a TypeScript `type` alias declaration.
*
* @example
* ```ts
* createType({ name: 'Pet', export: true })
* // export type Pet = ...
* ```
*/
declare const createType: (input: Omit<TypeNode, "kind">) => TypeNode;
/**
* Creates a `FunctionNode` representing a TypeScript `function` declaration.
*
* @example
* ```ts
* createFunction({ name: 'fetchPet', export: true, async: true, returnType: 'Pet' })
* // export async function fetchPet(): Promise<Pet> { ... }
* ```
*/
declare const createFunction: (input: Omit<FunctionNode, "kind">) => FunctionNode;
/**
* Creates an `ArrowFunctionNode` representing a TypeScript arrow function.
*
* @example
* ```ts
* createArrowFunction({ name: 'double', export: true, params: 'n: number', singleLine: true })
* // export const double = (n: number) => ...
* ```
*/
declare const createArrowFunction: (input: Omit<ArrowFunctionNode, "kind">) => ArrowFunctionNode;
/**
* Creates a {@link TextNode} representing a raw string fragment in the source output.
*
* @example
* ```ts
* createText('return fetch(id)')
* // { kind: 'Text', value: 'return fetch(id)' }
* ```
*/
declare const createText: (input: string) => TextNode;
/**
* Creates a {@link BreakNode} representing a line break in the source output.
*
* @example
* ```ts
* createBreak()
* // { kind: 'Break' }
* ```
*/
declare function createBreak(): BreakNode;
/**
* Creates a {@link JsxNode} representing a raw JSX fragment in the source output.
*
* @example
* ```ts
* createJsx('<>\n <a href={href}>Open</a>\n</>')
* // { kind: 'Jsx', value: '<>\n <a href={href}>Open</a>\n</>' }
* ```
*/
declare const createJsx: (input: string) => JsxNode;
//#endregion
//#region src/infer.d.ts
/**
* Options that control how the adapter parser maps source schemas to AST nodes.
*/
type ParserOptions = {
/**
* How `format: 'date-time'` schemas are represented downstream.
* - `false` falls through to a plain `string` (no validation).
* - `'string'` emits a datetime string node.
* - `'stringOffset'` emits a datetime node with timezone offset.
* - `'stringLocal'` emits a local datetime node.
* - `'date'` emits a `date` node (JavaScript `Date` object).
*/
dateType: false | 'string' | 'stringOffset' | 'stringLocal' | 'date';
/**
* How `type: 'integer'` (and `format: 'int64'`) maps to TypeScript.
* - `'bigint'` is exact for 64-bit IDs, but does not round-trip through JSON.
* - `'number'` fits most JSON APIs. Loses precision above `Number.MAX_SAFE_INTEGER`.
*
* @default 'bigint'
*/
integerType?: 'number' | 'bigint';
/**
* AST type used when a schema's type cannot be inferred from the spec
* (`additionalProperties: true`, missing `type`, ...).
*/
unknownType: 'any' | 'unknown' | 'void';
/**
* AST type used for completely empty schemas (`{}`).
*/
emptySchemaType: 'any' | 'unknown' | 'void';
/**
* Suffix appended to derived enum names when Kubb has to invent one
* (typically for inline enums on object properties).
*/
enumSuffix: 'enum' | (string & {});
};
/**
* Maps each `dateType` option value to the AST node produced by `format: 'date-time'`.
*/
type DateTimeNodeByDateType = {
date: DateSchemaNode;
string: DatetimeSchemaNode;
stringOffset: DatetimeSchemaNode;
stringLocal: DatetimeSchemaNode;
false: StringSchemaNode;
};
/**
* Resolves the AST node produced by `format: 'date-time'` based on the `dateType` option.
*/
type ResolveDateTimeNode<TDateType extends ParserOptions['dateType']> = DateTimeNodeByDateType[TDateType extends keyof DateTimeNodeByDateType ? TDateType : 'string'];
/**
* Ordered list of `[schema-shape, SchemaNode]` pairs.
* `InferSchemaNode` walks this tuple in order and returns the first matching node type.
*/
type SchemaNodeMap<TDateType extends ParserOptions['dateType'] = 'string'> = [[{
$ref: string;
}, RefSchemaNode], [{
allOf: ReadonlyArray<unknown>;
properties: object;
}, IntersectionSchemaNode], [{
allOf: readonly [unknown, unknown, ...Array<unknown>];
}, IntersectionSchemaNode], [{
allOf: ReadonlyArray<unknown>;
}, SchemaNode], [{
oneOf: ReadonlyArray<unknown>;
}, UnionSchemaNode], [{
anyOf: ReadonlyArray<unknown>;
}, UnionSchemaNode], [{
const: null;
}, ScalarSchemaNode], [{
const: string | number | boolean;
}, EnumSchemaNode], [{
type: ReadonlyArray<string>;
}, UnionSchemaNode], [{
type: 'array';
enum: ReadonlyArray<unknown>;
}, ArraySchemaNode], [{
enum: ReadonlyArray<unknown>;
}, EnumSchemaNode], [{
type: 'enum';
}, EnumSchemaNode], [{
type: 'union';
}, UnionSchemaNode], [{
type: 'intersection';
}, IntersectionSchemaNode], [{
type: 'tuple';
}, ArraySchemaNode], [{
type: 'ref';
}, RefSchemaNode], [{
type: 'datetime';
}, DatetimeSchemaNode], [{
type: 'date';
}, DateSchemaNode], [{
type: 'time';
}, TimeSchemaNode], [{
type: 'url';
}, UrlSchemaNode], [{
type: 'object';
}, ObjectSchemaNode], [{
additionalProperties: boolean | {};
}, ObjectSchemaNode], [{
type: 'array';
}, ArraySchemaNode], [{
items: object;
}, ArraySchemaNode], [{
prefixItems: ReadonlyArray<unknown>;
}, ArraySchemaNode], [{
type: string;
format: 'date-time';
}, ResolveDateTimeNode<TDateType>], [{
type: string;
format: 'date';
}, DateSchemaNode], [{
type: string;
format: 'time';
}, TimeSchemaNode], [{
format: 'date-time';
}, ResolveDateTimeNode<TDateType>], [{
format: 'date';
}, DateSchemaNode], [{
format: 'time';
}, TimeSchemaNode], [{
type: 'string';
}, StringSchemaNode], [{
type: 'number';
}, NumberSchemaNode], [{
type: 'integer';
}, NumberSchemaNode], [{
type: 'bigint';
}, NumberSchemaNode], [{
type: string;
}, ScalarSchemaNode], [{
minLength: number;
}, StringSchemaNode], [{
maxLength: number;
}, StringSchemaNode], [{
pattern: string;
}, StringSchemaNode], [{
minimum: number;
}, NumberSchemaNode], [{
maximum: number;
}, NumberSchemaNode]];
/**
* Infers the matching AST `SchemaNode` type from an input schema shape.
*/
type InferSchemaNode<TSchema extends object, TDateType extends ParserOptions['dateType'] = 'string', TEntries extends ReadonlyArray<[object, SchemaNode]> = SchemaNodeMap<TDateType>> = TEntries extends [infer TEntry extends [object, SchemaNode], ...infer TRest extends ReadonlyArray<[object, SchemaNode]>] ? TSchema extends TEntry[0] ? TEntry[1] : InferSchemaNode<TSchema, TDateType, TRest> : SchemaNode;
//#endregion
//#region src/nodes/property.d.ts
/**
* AST node representing one named object property.
*
* @example
* ```ts
* const property: PropertyNode = {
* kind: 'Property',
* name: 'id',
* schema: createSchema({ type: 'integer' }),
* required: true,
* }
* ```
*/
type PropertyNode = BaseNode & {
kind: 'Property';
/**
* Property key.
*/
name: string;
/**
* Property schema.
*/
schema: SchemaNode;
/**
* Whether the property is required.
*/
required: boolean;
};
/**
* Loosely-typed property accepted by `createProperty`, with `required` optional.
*/
type UserPropertyNode = Pick<PropertyNode, 'name' | 'schema'> & Partial<Omit<PropertyNode, 'kind' | 'name' | 'schema'>>;
/**
* Definition for the {@link PropertyNode}. `required` defaults to `false`, and the schema's
* `optional`/`nullish` flags are derived from it through {@link optionality}.
*/
declare const propertyDef: NodeDef<PropertyNode, UserPropertyNode>;
/**
* Creates a `PropertyNode`.
*
* @example
* ```ts
* const property = createProperty({
* name: 'status',
* required: true,
* schema: createSchema({ type: 'string', nullable: true }),
* })
* // required=true, no optional/nullish
* ```
*/
declare const createProperty: (input: UserPropertyNode) => PropertyNode;
//#endregion
//#region src/nodes/schema.d.ts
type PrimitiveSchemaType =
/**
* Text value.
*/
'string'
/**
* Floating-point number.
*/
| 'number'
/**
* Integer number.
*/
| 'integer'
/**
* Big integer number.
*/
| 'bigint'
/**
* Boolean value.
*/
| 'boolean'
/**
* Null value.
*/
| 'null'
/**
* Any value.
*/
| 'any'
/**
* Unknown value.
*/
| 'unknown'
/**
* No value (`void`).
*/
| 'void'
/**
* Never value.
*/
| 'never'
/**
* Object value.
*/
| 'object'
/**
* Array value.
*/
| 'array'
/**
* Date value.
*/
| 'date';
/**
* Composite schema types.
*/
type ComplexSchemaType = 'tuple' | 'union' | 'intersection' | 'enum';
/**
* Schema types that need special handling in generators.
*/
type SpecialSchemaType = 'ref' | 'datetime' | 'time' | 'uuid' | 'email' | 'url' | 'ipv4' | 'ipv6' | 'blob';
/**
* All schema type strings.
*/
type SchemaType = PrimitiveSchemaType | ComplexSchemaType | SpecialSchemaType;
/**
* Scalar schema types without extra object/array/ref structure.
*/
type ScalarSchemaType = Exclude<SchemaType, 'object' | 'array' | 'tuple' | 'union' | 'intersection' | 'enum' | 'ref' | 'datetime' | 'date' | 'time' | 'string' | 'number' | 'integer' | 'bigint' | 'url' | 'uuid' | 'email'>;
/**
* Fields shared by all schema nodes.
*/
type SchemaNodeBase = BaseNode & {
/**
* Node kind.
*/
kind: 'Schema';
/**
* Schema name for named definitions (for example, `"Pet"`).
* Inline schemas omit this field.
* `null` means Kubb has processed this and determined there is no applicable name.
* `undefined` means the name has not been set yet.
*/
name?: string | null;
/**
* Short schema title.
*/
title?: string;
/**
* Schema description text.
*/
description?: string;
/**
* Whether `null` is allowed.
*/
nullable?: boolean;
/**
* Whether the field is optional.
*/
optional?: boolean;
/**
* Both optional and nullable (`optional` + `nullable`).
*/
nullish?: boolean;
/**
* Whether the schema is deprecated.
*/
deprecated?: boolean;
/**
* Whether the schema is read-only.
*/
readOnly?: boolean;
/**
* Whether the schema is write-only.
*/
writeOnly?: boolean;
/**
* Default value.
*/
default?: unknown;
/**
* Example values from an `examples` array.
*/
examples?: Array<unknown>;
/**
* Base primitive type.
* For example, this is `'string'` for a `uuid` schema.
*/
primitive?: PrimitiveSchemaType;
/**
* Schema `format` value.
*/
format?: string;
};
/**
* Object schema with ordered properties.
*
* @example
* ```ts
* const objectSchema: ObjectSchemaNode = {
* kind: 'Schema',
* type: 'object',
* properties: [],
* }
* ```
*/
type ObjectSchemaNode = SchemaNodeBase & {
/**
* Schema type discriminator.
*/
type: 'object';
/**
* Primitive type, always `'object'` for object schemas.
*/
primitive: 'object';
/**
* Ordered object properties.
*/
properties: Array<PropertyNode>;
/**
* Additional object properties behavior:
* - `true`: allow any value
* - `false`: reject unknown properties
* - `SchemaNode`: allow values that match that schema
* - `undefined`: no additional properties constraint (open object)
*/
additionalProperties?: SchemaNode | boolean;
/**
* Pattern-based property schemas.
*/
patternProperties?: Record<string, SchemaNode>;
/**
* Minimum number of properties allowed.
*/
minProperties?: number;
/**
* Maximum number of properties allowed.
*/
maxProperties?: number;
};
/**
* Array-like schema (`array` or `tuple`).
*
* @example
* ```ts
* const arraySchema: ArraySchemaNode = {
* kind: 'Schema',
* type: 'array',
* items: [],
* }
* ```
*/
type ArraySchemaNode = SchemaNodeBase & {
/**
* Schema type discriminator (`array` or `tuple`).
*/
type: 'array' | 'tuple';
/**
* Item schemas.
*/
items?: Array<SchemaNode>;
/**
* Tuple rest-item schema for elements beyond positional `items`.
*/
rest?: SchemaNode;
/**
* Minimum item count (or tuple length).
*/
min?: number;
/**
* Maximum item count (or tuple length).
*/
max?: number;
/**
* Whether all items must be unique.
*/
unique?: boolean;
};
/**
* Shared shape for union and intersection schemas.
*/
type CompositeSchemaNodeBase = SchemaNodeBase & {
/**
* Member schemas.
*/
members?: Array<SchemaNode>;
};
/**
* Union schema, often from `oneOf` or `anyOf`.
*
* @example
* ```ts
* const unionSchema: UnionSchemaNode = {
* kind: 'Schema',
* type: 'union',
* members: [],
* }
* ```
*/
type UnionSchemaNode = CompositeSchemaNodeBase & {
/**
* Schema type discriminator.
*/
type: 'union';
/**
* Discriminator property name for a polymorphic union.
*/
discriminatorPropertyName?: string;
/**
* How many union members must be valid.
* - `'one'`: exactly one member, from `oneOf`
* - `'any'`: any number of members, from `anyOf`
*/
strategy?: 'one' | 'any';
};
/**
* Intersection schema, often from `allOf`.
*
* @example
* ```ts
* const intersectionSchema: IntersectionSchemaNode = {
* kind: 'Schema',
* type: 'intersection',
* members: [],
* }
* ```
*/
type IntersectionSchemaNode = CompositeSchemaNodeBase & {
/**
* Schema type discriminator.
*/
type: 'intersection';
};
/**
* One named enum item.
*/
type EnumValueNode = {
/**
* Enum item name.
*/
name: string;
/**
* Enum item value.
*/
value: string | number | boolean;
/**
* Primitive type of the enum value.
*/
primitive: Extract<PrimitiveSchemaType, 'string' | 'number' | 'boolean'>;
/**
* Label for the enum item, taken from the `x-enumDescriptions` or
* `x-enum-descriptions` vendor extension. `@kubb/plugin-ts` renders it as
* JSDoc on the matching enum member.
*/
description?: string;
};
/**
* Enum schema node.
*
* @example
* ```ts
* const enumSchema: EnumSchemaNode = {
* kind: 'Schema',
* type: 'enum',
* enumValues: ['a', 'b'],
* }
* ```
*/
type EnumSchemaNode = SchemaNodeBase & {
/**
* Schema type discriminator.
*/
type: 'enum';
/**
* Enum values in simple form.
*/
enumValues?: Array<string | number | boolean | null>;
/**
* Enum values in named form.
* If present, this is used instead of `enumValues`.
*/
namedEnumValues?: Array<EnumValueNode>;
};
/**
* Reference schema that points to another schema definition.
*
* @example
* ```ts
* const refSchema: RefSchemaNode = {
* kind: 'Schema',
* type: 'ref',
* ref: '#/components/schemas/Pet',
* }
* ```
*/
type RefSchemaNode = SchemaNodeBase & {
/**
* Schema type discriminator.
*/
type: 'ref';
/**
* Referenced schema name.
* `null` means Kubb has processed this and determined there is no applicable name.
*/
name?: string | null;
/**
* Original `$ref` path, for example, `#/components/schemas/Order`.
* Used to resolve names later.
*/
ref?: string;
/**
* Pattern copied from a sibling `pattern` field.
*/
pattern?: string;
/**
* The fully-parsed schema this ref resolves to, so its structure (`primitive`, `properties`)
* can be read without following the reference. Populated during parsing when the
* definition resolves, `null` when it can't or the ref is circular, and `undefined` when
* resolution has not been attempted.
*/
schema?: SchemaNode | null;
};
/**
* Datetime schema.
*
* @example
* ```ts
* const datetimeSchema: DatetimeSchemaNode = { kind: 'Schema', type: 'datetime' }
* ```
*/
type DatetimeSchemaNode = SchemaNodeBase & {
/**
* Schema type discriminator.
*/
type: 'datetime';
/**
* Whether the datetime includes a timezone offset (`dateType: 'stringOffset'`).
*/
offset?: boolean;
/**
* Whether the datetime is local (no timezone, `dateType: 'stringLocal'`).
*/
local?: boolean;
};
/**
* Shared base for `date` and `time` schemas.
*/
type TemporalSchemaNodeBase<T extends 'date' | 'time'> = SchemaNodeBase & {
/**
* Schema type discriminator.
*/
type: T;
/**
* Output representation in generated code.
*/
representation: 'date' | 'string';
};
/**
* Date schema node.
*
* @example
* ```ts
* const dateSchema: DateSchemaNode = { kind: 'Schema', type: 'date', representation: 'string' }
* ```
*/
type DateSchemaNode = TemporalSchemaNodeBase<'date'>;
/**
* Time schema node.
*
* @example
* ```ts
* const timeSchema: TimeSchemaNode = { kind: 'Schema', type: 'time', representation: 'string' }
* ```
*/
type TimeSchemaNode = TemporalSchemaNodeBase<'time'>;
/**
* String schema node.
*
* @example
* ```ts
* const stringSchema: StringSchemaNode = { kind: 'Schema', type: 'string' }
* ```
*/
type StringSchemaNode = SchemaNodeBase & {
/**
* Schema type discriminator.
*/
type: 'string';
/**
* Minimum string length.
*/
min?: number;
/**
* Maximum string length.
*/
max?: number;
/**
* Regex pattern.
*/
pattern?: string;
};
/**
* Numeric schema (`number`, `integer`, or `bigint`).
*
* @example
* ```ts
* const numberSchema: NumberSchemaNode = { kind: 'Schema', type: 'number' }
* ```
*/
type NumberSchemaNode = SchemaNodeBase & {
/**
* Schema type discriminator.
*/
type: 'number' | 'integer' | 'bigint';
/**
* Minimum value.
*/
min?: number;
/**
* Maximum value.
*/
max?: number;
/**
* Exclusive minimum value.
*/
exclusiveMinimum?: number;
/**
* Exclusive maximum value.
*/
exclusiveMaximum?: number;
/**
* The value must be a multiple of this number.
*/
multipleOf?: number;
};
/**
* Scalar schema with no extra constraints.
*
* @example
* ```ts
* const anySchema: ScalarSchemaNode = { kind: 'Schema', type: 'any' }
* ```
*/
type ScalarSchemaNode = SchemaNodeBase & {
/**
* Schema type discriminator.
*/
type: ScalarSchemaType;
};
/**
* URL schema node.
* Can include a path template for template literal types.
*
* @example
* ```ts
* const urlSchema: UrlSchemaNode = { kind: 'Schema', type: 'url', path: '/pets/{petId}' }
* ```
*/
type UrlSchemaNode = SchemaNodeBase & {
/**
* Schema type discriminator.
*/
type: 'url';
/**
* Path template, for example, `'/pets/{petId}'`.
*/
path?: string;
/**
* Minimum string length.
*/
min?: number;
/**
* Maximum string length.
*/
max?: number;
};
/**
* Format-string schema for string-based formats that support length constraints.
*
* @example
* ```ts
* const uuidSchema: FormatStringSchemaNode = { kind: 'Schema', type: 'uuid', min: 36, max: 36 }
* ```
*/
type FormatStringSchemaNode = SchemaNodeBase & {
/**
* Schema type discriminator.
*/
type: 'uuid' | 'email';
/**
* Minimum string length.
*/
min?: number;
/**
* Maximum string length.
*/
max?: number;
};
/**
* IPv4 address schema node.
*
* @example
* ```ts
* const ipv4Schema: Ipv4SchemaNode = { kind: 'Schema', type: 'ipv4' }
* ```
*/
type Ipv4SchemaNode = SchemaNodeBase & {
/**
* Schema type discriminator.
*/
type: 'ipv4';
};
/**
* IPv6 address schema node.
*
* @example
* ```ts
* const ipv6Schema: Ipv6SchemaNode = { kind: 'Schema', type: 'ipv6' }
* ```
*/
type Ipv6SchemaNode = SchemaNodeBase & {
/**
* Schema type discriminator.
*/
type: 'ipv6';
};
/**
* Mapping from schema type literals to concrete schema node types.
* Used by `narrowSchema`.
*/
type SchemaNodeByType = {
object: ObjectSchemaNode;
array: ArraySchemaNode;
tuple: ArraySchemaNode;
union: UnionSchemaNode;
intersection: IntersectionSchemaNode;
enum: EnumSchemaNode;
ref: RefSchemaNode;
datetime: DatetimeSchemaNode;
date: DateSchemaNode;
time: TimeSchemaNode;
string: StringSchemaNode;
number: NumberSchemaNode;
integer: NumberSchemaNode;
bigint: NumberSchemaNode;
boolean: ScalarSchemaNode;
null: ScalarSchemaNode;
any: ScalarSchemaNode;
unknown: ScalarSchemaNode;
void: ScalarSchemaNode;
never: ScalarSchemaNode;
uuid: FormatStringSchemaNode;
email: FormatStringSchemaNode;
url: UrlSchemaNode;
ipv4: Ipv4SchemaNode;
ipv6: Ipv6SchemaNode;
blob: ScalarSchemaNode;
};
/**
* Union of all schema node types.
*/
type SchemaNode = ObjectSchemaNode | ArraySchemaNode | UnionSchemaNode | IntersectionSchemaNode | EnumSchemaNode | RefSchemaNode | DatetimeSchemaNode | DateSchemaNode | TimeSchemaNode | StringSchemaNode | NumberSchemaNode | UrlSchemaNode | FormatStringSchemaNode | Ipv4SchemaNode | Ipv6SchemaNode | ScalarSchemaNode;
type CreateSchemaObjectInput = Omit<ObjectSchemaNode, 'kind' | 'properties' | 'primitive'> & {
properties?: Array<PropertyNode>;
primitive?: 'object';
};
type CreateSchemaInput = CreateSchemaObjectInput | DistributiveOmit<Exclude<SchemaNode, ObjectSchemaNode>, 'kind'>;
type CreateSchemaOutput<T extends CreateSchemaInput> = InferSchemaNode<T> & {
kind: 'Schema';
};
/**
* Definition for the {@link SchemaNode}. Object schemas default `properties` to an
* empty array, and `primitive` is inferred from `type` when not explicitly provided.
*/
declare const schemaDef: NodeDef<SchemaNode, CreateSchemaInput>;
/**
* Creates a `SchemaNode`, narrowed to the variant of `props.type`.
*
* @example
* ```ts
* const scalar = createSchema({ type: 'string' })
* // { kind: 'Schema', type: 'string', primitive: 'string' }
* ```
*
* @example
* ```ts
* const object = createSchema({ type: 'object' })
* // { kind: 'Schema', type: 'object', primitive: 'object', properties: [] }
* ```
*/
declare function createSchema<T extends CreateSchemaInput>(props: T): CreateSchemaOutput<T>;
declare function createSchema(props: CreateSchemaInput): SchemaNode;
//#endregion
//#region src/nodes/content.d.ts
/**
* AST node representing one content-type entry of a request body or response.
*
* There is one entry per content type declared in the spec (e.g. `application/json`,
* `multipart/form-data`), and each entry holds its own body schema.
*
* @example
* ```ts
* const content: ContentNode = {
* kind: 'Content',
* contentType: 'application/json',
* schema: createSchema({ type: 'string' }),
* }
* ```
*/
type ContentNode = BaseNode & {
/**
* Node kind.
*/
kind: 'Content';
/**
* The content type for this entry (e.g. `'application/json'`).
*/
contentType: string;
/**
* Body schema for this content type.
*/
schema?: SchemaNode;
/**
* Property keys to exclude from the generated type via `Omit<Type, Keys>`.
* Set when a referenced schema has `readOnly`/`writeOnly` fields that should be omitted.
*/
keysToOmit?: Array<string> | null;
};
/**
* Definition for the {@link ContentNode}.
*/
declare const contentDef: NodeDef<ContentNode, Omit<ContentNode, "kind">>;
/**
* Creates a `ContentNode` for a single request-body or response content type.
*/
declare const createContent: (input: Omit<ContentNode, "kind">) => ContentNode;
//#endregion
//#region src/nodes/file.d.ts
/**
* Supported file extensions.
*/
type Extname = '.ts' | '.js' | '.tsx' | '.json' | `.${string}`;
type ImportName = string | Array<string | {
propertyName: string;
name?: string;
}>;
/**
* Represents a language-agnostic import/dependency declaration.
*
* @example Named import (TypeScript: `import { useState } from 'react'`)
* ```ts
* createImport({ name: ['useState'], path: 'react' })
* ```
*
* @example Default import (TypeScript: `import React from 'react'`)
* ```ts
* createImport({ name: 'React', path: 'react' })
* ```
*
* @example Type-only import (TypeScript: `import type { FC } from 'react'`)
* ```ts
* createImport({ name: ['FC'], path: 'react', isTypeOnly: true })
* ```
*
* @example Namespace import (TypeScript: `import * as React from 'react'`)
* ```ts
* createImport({ name: 'React', path: 'react', isNameSpace: true })
* ```
*/
type ImportNode = BaseNode & {
kind: 'Import';
/**
* Import name(s) to be used.
*
* @example Named imports
* `['useState']`
*
* @example Default import
* `'React'`
*/
name: ImportName;
/**
* Path for the import.
*
* @example
* `'@kubb/core'`
*/
path: string;
/**
* Add a type-only import prefix.
* - `true` generates `import type { Type } from './path'`
* - `false` generates `import { Type } from './path'`
*/
isTypeOnly?: boolean | null;
/**
* Import the entire module as a namespace.
* - `true` generates `import * as Name from './path'`
* - `false` generates a standard import
*/
isNameSpace?: boolean | null;
/**
* When set, the import path is resolved relative to this root.
*/
root?: string | null;
};
/**
* Represents a language-agnostic export/public API declaration.
*
* @example Named export (TypeScript: `export { Pets } from './Pets'`)
* ```ts
* createExport({ name: ['Pets'], path: './Pets' })
* ```
*
* @example Type-only export (TypeScript: `export type { Pet } from './Pet'`)
* ```ts
* createExport({ name: ['Pet'], path: './Pet', isTypeOnly: true })
* ```
*
* @example Wildcard export (TypeScript: `export * from './utils'`)
* ```ts
* createExport({ path: './utils' })
* ```
*
* @example Namespace alias (TypeScript: `export * as utils from './utils'`)
* ```ts
* createExport({ name: 'utils', path: './utils', asAlias: true })
* ```
*/
type ExportNode = BaseNode & {
kind: 'Export';
/**
* Export name(s) to be used. When omitted, generates a wildcard export.
*
* @example Named exports
* `['useState']`
*
* @example Single export
* `'React'`
*/
name?: string | Array<string> | null;
/**
* Path for the export.
*
* @example
* `'@kubb/core'`
*/
path: string;
/**
* Add a type-only export prefix.
* - `true` generates `export type { Type } from './path'`
* - `false` generates `export { Type } from './path'`
*/
isTypeOnly?: boolean | null;
/**
* Export as an aliased namespace.
* - `true` generates `export * as aliasName from './path'`
* - `false` generates a standard export
*/
asAlias?: boolean | null;
};
/**
* Represents a fragment of source code within a file.
*
* @example Named exportable source
* ```ts
* createSource({ name: 'Pet', nodes: [createText('export type Pet = { id: number }')], isExportable: true, isIndexable: true })
* ```
*
* @example Inline unnamed code block
* ```ts
* createSource({ nodes: [createText('const x = 1')] })
* ```
*/
type SourceNode = BaseNode & {
kind: 'Source';
/**
* Optional name identifying this source (used for deduplication and barrel generation).
*/
name?: string | null;
/**
* Mark this source as a type-only export.
*/
isTypeOnly?: boolean | null;
/**
* Include the `export` keyword in the generated source.
*/
isExportable?: boolean | null;
/**
* Include this source in barrel/index file generation.
*/
isIndexable?: boolean | null;
/**
* Child nodes that make up this source fragment, in DOM order.
* Use a {@link TextNode} for raw string content.
*/
nodes?: Array<CodeNode>;
};
/**
* Represents a fully resolved file in the AST.
*
* Created via `createFile()`, which computes the `id`, `name`, and `extname` from the input
* and deduplicates `imports`, `exports`, and `sources`.
*
* @example
* ```ts
* const file = createFile({
* baseName: 'petStore.ts',
* path: 'src/models/petStore.ts',
* sources: [createSource({ name: 'Pet', nodes: [createText('export type Pet = { id: number }')], isExportable: true })],
* imports: [createImport({ name: ['z'], path: 'zod' })],
* exports: [createExport({ name: ['Pet'], path: './petStore' })],
* })
* // file.id = SHA256 hash of the path
* // file.name = 'petStore'
* // file.extname = '.ts'
* ```
*/
type FileNode<TMeta extends object = object> = BaseNode & {
kind: 'File';
/**
* Unique identifier derived from a SHA256 hash of the file path. `createFile`
* computes it, so callers do not need to provide it.
*/
id: string;
/**
* File name without extension, derived from `baseName`.
*
* @see https://nodejs.org/api/path.html#pathformatpathobject
*/
name: string;
/**
* File base name, including extension, shaped like `${name}${extname}`.
*
* @see https://nodejs.org/api/path.html#pathbasenamepath-suffix
*/
baseName: `${string}.${string}`;
/**
* Full qualified path to the file.
*/
path: string;
/**
* File extension extracted from `baseName`.
*/
extname: Extname;
/**
* Deduplicated list of source code fragments.
*/
sources: Array<SourceNode>;
/**
* Deduplicated list of import declarations.
*/
imports: Array<ImportNode>;
/**
* Deduplicated list of export declarations.
*/
exports: Array<ExportNode>;
/**
* Optional metadata attached to this file, read by plugins during barrel generation.
*/
meta?: TMeta;
/**
* Optional banner prepended to the generated file content.
* Accepts `null` so `resolver.resolveBanner()` results can be passed directly.
*/
banner?: string | null;
/**
* Optional footer appended to the generated file content.
* Accepts `null` so `resolver.resolveFooter()` results can be passed directly.
*/
footer?: string | null;
/**
* Absolute on-disk path to copy verbatim into the output, bypassing the parser.
*
* Use to emit a real source file shipped inside a package (a template) into the generated
* folder without reformatting or import reordering. Only `banner` and `footer` are applied
* around the copied content. When set, `copy` provides the file content and any `sources`
* nodes are ignored for output; `sources` may still carry `name`/`isExportable`/`isIndexable`
* so barrel generation treats the file the same as a rendered one.
*/
copy?: string | null;
};
/**
* Definition for the {@link ImportNode}.
*/
declare const importDef: NodeDef<ImportNode, Omit<ImportNode, "kind">>;
/**
* Definition for the {@link ExportNode}.
*/
declare const exportDef: NodeDef<ExportNode, Omit<ExportNode, "kind">>;
/**
* Definition for the {@link SourceNode}.
*/
declare const sourceDef: NodeDef<SourceNode, Omit<SourceNode, "kind">>;
/**
* Definition for the {@link FileNode}. The fully resolved builder lives in
* `createFile`, so this definition only supplies the guard.
*/
declare const fileDef: NodeDef<FileNode<object>, Omit<FileNode<object>, "kind">>;
/**
* Creates an `ImportNode` representing a language-agnostic import/dependency declaration.
*
* @example Named import
* ```ts
* createImport({ name: ['useState'], path: 'react' })
* // import { useState } from 'react'
* ```
*/
declare const createImport: (input: Omit<ImportNode, "kind">) => ImportNode;
/**
* Creates an `ExportNode` representing a language-agnostic export/public API declaration.
*
* @example Named export
* ```ts
* createExport({ name: ['Pet'], path: './Pet' })
* // export { Pet } from './Pet'
* ```
*/
declare const createExport: (input: Omit<ExportNode, "kind">) => ExportNode;
/**
* Creates a `SourceNode` representing a fragment of source code within a file.
*
* @example
* ```ts
* createSource({ name: 'Pet', nodes: [createText('export type Pet = { id: number }')], isExportable: true })
* ```
*/
declare const createSource: (input: Omit<SourceNode, "kind">) => SourceNode;
/**
* Input descriptor for {@link createFile}, before `id`, `name`, and `extname` are computed
* and `imports`/`exports`/`sources` are deduplicated.
*/
type UserFileNode<TMeta extends object = object> = Omit<FileNode<TMeta>, 'kind' | 'id' | 'name' | 'extname' | 'imports' | 'exports' | 'sources'> & Pick<Partial<FileNode<TMeta>>, 'imports' | 'exports' | 'sources'>;
/**
* Creates a fully resolved `FileNode` from a file input descriptor.
*
* Computes:
* - `id` SHA256 hash of the file path
* - `name` `baseName` without extension
* - `extname` extension extracted from `baseName`
*
* Deduplicates:
* - `sources` via `combineSources`
* - `exports` via `combineExports`
* - `imports` via `combineImports` (also filters unused imports)
*
* @throws {Error} when `baseName` has no extension.
*
* @example
* ```ts
* const file = createFile({
* baseName: 'petStore.ts',
* path: 'src/models/petStore.ts',
* sources: [createSource({ name: 'Pet', nodes: [createText('export type Pet = { id: number }')] })],
* imports: [createImport({ name: ['z'], path: 'zod' })],
* exports: [createExport({ name: ['Pet'], path: './petStore' })],
* })
* // file.id = SHA256 hash of 'src/models/petStore.ts'
* // file.name = 'petStore'
* // file.extname = '.ts'
* ```
*
* @example Copy a real file into the output verbatim
* ```ts
* const file = createFile({
* baseName: 'client.ts',
* path: 'src/gen/client.ts',
* copy: '/abs/path/to/templates/client.ts',
* })
* ```
*/
declare function createFile<TMeta extends object = object>(input: UserFileNode<TMeta>): FileNode<TMeta>;
//#endregion
//#region ../../internals/utils/src/promise.d.ts
/**
* Container that switches between an eager `Array<T>` and a lazy `AsyncIterable<T>`.
*
* `Array<T>` by default. With `Stream` set to `true` it becomes `AsyncIterable<T>`, so large
* collections can be produced lazily without holding every item in memory. Pairs with
* {@link arrayToAsyncIterable}, which lifts a plain array into the streaming form.
*
* @example
* ```ts
* type Eager = Streamable<number> // Array<number>
* type Lazy = Streamable<number, true> // AsyncIterable<number>
* ```
*/
type Streamable<T, Stream extends boolean = false> = Stream extends true ? AsyncIterable<T> : Array<T>;
//#endregion
//#region src/nodes/parameter.d.ts
type ParameterLocation = 'path' | 'query' | 'header' | 'cookie';
/**
* Parameter serialization style, controlling how a parameter value is rendered into the request.
*/
type ParameterStyle = 'matrix' | 'label' | 'form' | 'simple' | 'spaceDelimited' | 'pipeDelimited' | 'deepObject';
/**
* AST node representing one operation parameter.
*
* @example
* ```ts
* const param: ParameterNode = {
* kind: 'Parameter',
* name: 'petId',
* in: 'path',
* schema: createSchema({ type: 'string' }),
* required: true,
* }
* ```
*/
type ParameterNode = BaseNode & {
kind: 'Parameter';
/**
* Parameter name.
*/
name: string;
/**
* Parameter location (`path`, `query`, `header`, or `cookie`).
*/
in: ParameterLocation;
/**
* Parameter schema.
*/
schema: SchemaNode;
/**
* Whether the parameter is required.
*/
required: boolean;
/**
* Serialization style. Absent when the source omits it, leaving consumers to apply the
* per-location default.
*/
style?: ParameterStyle;
/**
* Whether array and object values expand into separate values. Absent when the source omits it,
* leaving consumers to apply the default for the style.
*/
explode?: boolean;
};
type UserParameterNode = Pick<ParameterNode, 'name' | 'in' | 'schema'> & Partial<Omit<ParameterNode, 'kind' | 'name' | 'in' | 'schema'>>;
/**
* Definition for the {@link ParameterNode}. `required` defaults to `false`, and the schema's
* `optional`/`nullish` flags are derived from it through {@link optionality}.
*/
declare const parameterDef: NodeDef<ParameterNode, UserParameterNode>;
/**
* Creates a `ParameterNode`.
*
* @example
* ```ts
* const param = createParameter({
* name: 'petId',
* in: 'path',
* required: true,
* schema: createSchema({ type: 'string' }),
* })
* ```
*/
declare const createParameter: (input: UserParameterNode) => ParameterNode;
//#endregion
//#region src/nodes/requestBody.d.ts
/**
* AST node representing an operation request body.
*
* Body schemas live exclusively inside the `content` array (one entry per content type),
* mirroring {@link ResponseNode}.
*
* @example
* ```ts
* const requestBody: RequestBodyNode = {
* kind: 'RequestBody',
* required: true,
* content: [{ kind: 'Content', contentType: 'application/json', schema: createSchema({ type: 'string' }) }],
* }
* ```
*/
type RequestBodyNode = BaseNode & {
kind: 'RequestBody';
/**
* Request body description carried over from the spec.
*/
description?: string;
/**
* Whether the request body is required (`requestBody.required: true` in the spec).
* When `false` or absent, the generated `data` parameter should be optional.
*/
required?: boolean;
/**
* Content type entries for this request body.
*
* When the adapter `contentType` option is set, this array contains exactly one entry for
* that content type. Otherwise it contains one entry per content type declared in the spec,
* so plugins can generate code for every variant (for example, separate hooks for
* `application/json` and `multipart/form-data`).
*/
content?: Array<ContentNode>;
};
/**
* Definition for the {@link RequestBodyNode}. Content entries are built upfront with
* {@link createContent}, mirroring how `parameters` and `responses` take prebuilt nodes.
*/
declare const requestBodyDef: NodeDef<RequestBodyNode, Omit<RequestBodyNode, "kind">>;
/**
* Creates a `RequestBodyNode`.
*/
declare const createRequestBody: (input: Omit<RequestBodyNode, "kind">) => RequestBodyNode;
//#endregion
//#region src/nodes/response.d.ts
/**
* All supported HTTP status code literals as strings, as used in API specs
* (for example, `"200"` and `"404"`).
*/
type HttpStatusCode = '100' | '101' | '102' | '103' | '200' | '201' | '202' | '203' | '204' | '205' | '206' | '207' | '208' | '226' | '300' | '301' | '302' | '303' | '304' | '305' | '307' | '308' | '400' | '401' | '402' | '403' | '404' | '405' | '406' | '407' | '408' | '409' | '410' | '411' | '412' | '413' | '414' | '415' | '416' | '417' | '418' | '421' | '422' | '423' | '424' | '425' | '426' | '428' | '429' | '431' | '451' | '500' | '501' | '502' | '503' | '504' | '505' | '506' | '507' | '508' | '510' | '511';
/**
* Response status code literal used by operations.
*
* Includes specific HTTP status code strings and `"default"` for catch-all responses.
*
* @example
* ```ts
* const status: StatusCode = '200'
* const fallback: StatusCode = 'default'
* ```
*/
type StatusCode = HttpStatusCode | 'default';
/**
* AST node representing one operation response variant.
*
* Mirrors {@link OperationNode.requestBody}: the response body schemas live exclusively inside
* the `content` array (one entry per content type), so the same schema is never duplicated at the
* node root and inside `content`.
*
* @example
* ```ts
* const response: ResponseNode = {
* kind: 'Response',
* statusCode: '200',
* content: [{ kind: 'Content', contentType: 'application/json', schema: createSchema({ type: 'string' }) }],
* }
* ```
*/
type ResponseNode = BaseNode & {
/**
* Node kind.
*/
kind: 'Response';
/**
* HTTP status code or `'default'` for a fallback response.
*/
statusCode: StatusCode;
/**
* Optional response description.
*/
description?: string;
/**
* All available content type entries for this response.
*
* When the adapter `contentType` option is set, this array contains exactly one entry for that
* content type. Otherwise it contains one entry per content type declared in the spec, so that
* plugins can generate a union of response types (e.g. `application/json` and `application/xml`).
* Body-less responses keep a single entry whose `schema` is the empty/`void` placeholder.
*
* @example
* ```ts
* // spec response declares both application/json and application/xml
* response.content[0].contentType // 'application/json'
* response.content[1].contentType // 'application/xml'
* ```
*/
content?: Array<ContentNode>;
};
type ResponseInput = Pick<ResponseNode, 'statusCode'> & Partial<Omit<ResponseNode, 'kind' | 'statusCode' | 'content'>> & {
content?: Array<ContentNode>;
schema?: SchemaNode;
mediaType?: string | null;
keysToOmit?: Array<string> | null;
};
/**
* Definition for the {@link ResponseNode}. A single legacy `schema` (with optional
* `mediaType`/`keysToOmit`) is normalized into one `content` entry.
*/
declare const responseDef: NodeDef<ResponseNode, ResponseInput>;
/**
* Creates a `ResponseNode`.
*
* @example
* ```ts
* const response = createResponse({
* statusCode: '200',
* content: [createContent({ contentType: 'application/json', schema: createSchema({ type: 'object', properties: [] }) })],
* })
* ```
*/
declare const createResponse: (input: ResponseInput) => ResponseNode;
//#endregion
//#region src/nodes/operation.d.ts
/**
* HTTP method an operation responds to.
*/
type HttpMethod = 'GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE' | 'HEAD' | 'OPTIONS' | 'TRACE';
/**
* Transport an operation belongs to.
*/
type OperationProtocol = 'http';
/**
* Fields shared by every operation, regardless of transport.
*/
type OperationNodeBase = BaseNode & {
/**
* Node kind.
*/
kind: 'Operation';
/**
* Stable identifier for the operation.
*/
operationId: string;
/**
* Group labels for the operation.
*/
tags: Array<string>;
/**
* Short one-line operation summary.
*/
summary?: string;
/**
* Full operation description.
*/
description?: string;
/**
* Marks the operation as deprecated.
*/
deprecated?: boolean;
/**
* Query, path, header, and cookie parameters for the operation.
*/
parameters: Array<ParameterNode>;
/**
* Request body for the operation.
*/
requestBody?: RequestBodyNode;
/**
* Operation responses.
*/
responses: Array<ResponseNode>;
};
/**
* Operation served over HTTP. `method` and `path` are guaranteed.
*
* @example
* ```ts
* const operation: HttpOperationNode = {
* kind: 'Operation',
* operationId: 'listPets',
* protocol: 'http',
* method: 'GET',
* path: '/pets',
* tags: [],
* parameters: [],
* responses: [],
* }
* ```
*/
type HttpOperationNode = OperationNodeBase & {
/**
* Transport the operation belongs to.
*/
protocol?: 'http';
/**
* HTTP method like `'GET'`.
*/
method: HttpMethod;
/**
* Path string, for example `/pets/{petId}`, with `{param}` notation preserved.
*/
path: string;
};
/**
* Operation for a non-HTTP transport. HTTP-only fields are forbidden.
*/
type GenericOperationNode = OperationNodeBase & {
/**
* Transport the operation belongs to.
*/
protocol?: Exclude<OperationProtocol, 'http'>;
method?: never;
path?: never;
};
/**
* AST node representing one API operation.
*
* Discriminated on `protocol`: an {@link HttpOperationNode} (`protocol: 'http'`) guarantees
* `method` and `path`, while a {@link GenericOperationNode} omits them. Narrow with
* `isHttpOperationNode(node)` or `node.protocol === 'http'` before reading `method`/`path`.
*/
type OperationNode = HttpOperationNode | GenericOperationNode;
type OperationInput = {
operationId: string;
method?: HttpOperationNode['method'];
path?: HttpOperationNode['path'];
requestBody?: Omit<RequestBodyNode, 'kind'>;
[key: string]: unknown;
};
/**
* Definition for the {@link OperationNode}. HTTP operations (those carrying both
* `method` and `path`) are tagged with `protocol: 'http'`, and the request body is
* normalized into a `RequestBodyNode`.
*/
declare const operationDef: NodeDef<OperationNode, OperationInput>;
/**
* Creates an `OperationNode` with default empty arrays for `tags`, `parameters`, and `responses`.
*
* @example
* ```ts
* const operation = createOperation({ operationId: 'getPetById', method: 'GET', path: '/pet/{petId}' })
* // tags, parameters, and responses are []
* ```
*/
declare function createOperation(props: Pick<HttpOperationNode, 'operationId' | 'method' | 'path'> & Partial<Omit<HttpOperationNode, 'kind' | 'operationId' | 'method' | 'path' | 'requestBody'>> & {
requestBody?: Omit<RequestBodyNode, 'kind'>;
}): HttpOperationNode;
declare function createOperation(props: Pick<GenericOperationNode, 'operationId'> & Partial<Omit<GenericOperationNode, 'kind' | 'operationId' | 'requestBody'>> & {
requestBody?: Omit<RequestBodyNode, 'kind'>;
}): GenericOperationNode;
//#endregion
//#region src/nodes/input.d.ts
/**
* Metadata for an API document, populated by the adapter and available to every generator.
*
* All fields are plain JSON-serializable values, no `Set`, no `Map`, no class instances.
* Computed fields (`circularNames`, `enumNames`) are pre-calculated once during the adapter
* pre-scan so generators never need to iterate the full schema list themselves.
*
* @example
* ```ts
* const meta: InputMeta = { title: 'Pet Store', version: '1.0.0', baseURL: 'https://api.example.com/v2', circularNames: [], enumNames: [] }
* ```
*/
type InputMeta = {
/**
* API title from `info.title` in the source document.
*/
title?: string;
/**
* API description from `info.description` in the source document.
*/
description?: string;
/**
* API version string from `info.version` in the source document.
*/
version?: string;
/**
* Resolved base URL from the first matching server entry in the source document.
*/
baseURL?: string | null;
/**
* Names of schemas that participate in a circular reference chain.
* Computed once during the adapter pre-scan, so a generator never has to
* call `findCircularSchemas` itself.
*
* Convert to a `Set` once at the start of a generator, not per-schema,
* so lookups stay O(1) without repeated allocations.
*
* @example Wrap a circular schema in z.lazy()
* ```ts
* const circular = new Set(meta.circularNames)
* if (circular.has(schema.name)) { ... }
* ```
*/
circularNames: ReadonlyArray<string>;
/**
* Names of schemas whose type is `enum`.
* Computed once during the adapter pre-scan, so a generator never has to
* filter the schema list itself.
*
* Convert to a `Set` once at the start of a generator when you need repeated
* membership checks, so each check stays O(1) instead of an array scan.
*
* @example Check if a referenced schema is an enum
* `const enums = new Set(meta.enumNames)`
* `const isEnum = enums.has(schemaName)`
*/
enumNames: ReadonlyArray<string>;
};
/**
* Input AST node that contains all schemas and operations for one API document.
* Produced by the adapter and consumed by all Kubb plugins.
*
* `Stream` switches `schemas` and `operations` between eager `Array`s (the default) and lazy
* `AsyncIterable`s. The streaming variant `InputNode<true>` yields nodes one at a time.
*
* @example
* ```ts
* const input: InputNode = {
* kind: 'Input',
* schemas: [],
* operations: [],
* meta: { circularNames: [], enumNames: [] },
* }
* ```
*
* @example Streaming variant for large specs
* ```ts
* for await (const schema of inputNode.schemas) {
* // only this one SchemaNode is live here. Previous ones are GC-eligible
* }
* ```
*/
type InputNode<Stream extends boolean = false> = BaseNode & {
/**
* Node kind.
*/
kind: 'Input';
/**
* All schema nodes in the document.
*/
schemas: Streamable<SchemaNode, Stream>;
/**
* All operation nodes in the document.
*/
operations: Streamable<OperationNode, Stream>;
/**
* Document metadata populated by the adapter.
*/
meta: InputMeta;
};
/**
* Definition for the {@link InputNode}.
*/
declare const inputDef: NodeDef<InputNode<false>, Partial<Omit<InputNode<false>, "kind">>>;
/**
* Creates an `InputNode`. Pass `stream: true` for the streaming variant whose `schemas` and
* `operations` are `AsyncIterable` sources. Otherwise it builds the eager variant with array
* `schemas`/`operations`. Both variants get the defaulted `meta`.
*
* @example Eager
* ```ts
* const input = createInput()
* // { kind: 'Input', schemas: [], operations: [] }
* ```
*
* @example Streaming
* ```ts
* const node = createInput({ stream: true, schemas: schemasIterable, operations: operationsIterable, meta: { title: 'My API' } })
* ```
*/
declare function createInput<Stream extends boolean = false>(options?: Partial<Omit<InputNode<Stream>, 'kind'>> & {
stream?: Stream;
}): InputNode<Stream>;
//#endregion
//#region src/nodes/output.d.ts
/**
* Output AST node that groups all generated file output for one API document.
*
* Produced by generators and consumed by the build pipeline to write files.
*
* @example
* ```ts
* const output: OutputNode = {
* kind: 'Output',
* files: [],
* }
* ```
*/
type OutputNode = BaseNode & {
/**
* Node kind.
*/
kind: 'Output';
/**
* Generated file nodes.
*/
files: Array<FileNode>;
};
/**
* Definition for the {@link OutputNode}.
*/
declare const outputDef: NodeDef<OutputNode, Partial<Omit<OutputNode, "kind">>>;
/**
* Creates an `OutputNode` with a stable default for `files`.
*
* @example
* ```ts
* const output = createOutput()
* // { kind: 'Output', files: [] }
* ```
*/
declare function createOutput(overrides?: Partial<Omit<OutputNode, 'kind'>>): OutputNode;
//#endregion
//#region src/nodes/index.d.ts
/**
* Union of all AST node types.
*
* This lets TypeScript narrow types in `switch (node.kind)` blocks.
*
* @example
* ```ts
* function getKind(node: Node): string {
* switch (node.kind) {
* case 'Input':
* return 'input'
* case 'Output':
* return 'output'
* default:
* return 'other'
* }
* }
* ```
*/
type Node = InputNode | OutputNode | OperationNode | SchemaNode | PropertyNode | ParameterNode | ResponseNode | RequestBodyNode | ContentNode | FileNode | ImportNode | ExportNode | SourceNode | ConstNode | TypeNode | FunctionNode | ArrowFunctionNode;
//#endregion
export { ScalarSchemaType as $, SourceNode as A, createFunction as At, ContentNode as B, defineNode as Bt, ParameterNode as C, TypeNode as Ct, ExportNode as D, createArrowFunction as Dt, parameterDef as E, constDef as Et, createSource as F, jsxDef as Ft, DatetimeSchemaNode as G, createContent as H, NodeKind as Ht, exportDef as I, textDef as It, NumberSchemaNode as J, EnumSchemaNode as K, fileDef as L, typeDef as Lt, createExport as M, createText as Mt, createFile as N, createType as Nt, FileNode as O, createBreak as Ot, createImport as P, functionDef as Pt, ScalarSchemaNode as Q, importDef as R, DistributiveOmit as Rt, ParameterLocation as S, TextNode as St, createParameter as T, breakDef as Tt, ArraySchemaNode as U, contentDef as V, BaseNode as Vt, DateSchemaNode as W, PrimitiveSchemaType as X, ObjectSchemaNode as Y, RefSchemaNode as Z, createResponse as _, CodeNode as _t, InputMeta as a, UnionSchemaNode as at, createRequestBody as b, JSDocNode as bt, inputDef as c, schemaDef as ct, HttpOperationNode as d, createProperty as dt, SchemaNode as et, OperationNode as f, propertyDef as ft, StatusCode as g, BreakNode as gt, ResponseNode as h, ArrowFunctionNode as ht, outputDef as i, TimeSchemaNode as it, UserFileNode as j, createJsx as jt, ImportNode as k, createConst as kt, GenericOperationNode as l, PropertyNode as lt, operationDef as m, ParserOptions as mt, OutputNode as n, SchemaType as nt, InputNode as o, UrlSchemaNode as ot, createOperation as p, InferSchemaNode as pt, IntersectionSchemaNode as q, createOutput as r, StringSchemaNode as rt, createInput as s, createSchema as st, Node as t, SchemaNodeByType as tt, HttpMethod as u, UserPropertyNode as ut, responseDef as v, ConstNode as vt, ParameterStyle as w, arrowFunctionDef as wt, requestBodyDef as x, JsxNode as xt, RequestBodyNode as y, FunctionNode as yt, sourceDef as z, NodeDef as zt };
//# sourceMappingURL=index-Cu2zmNxv.d.ts.map
Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
const require_visitor = require("./visitor-h6dEM3vR.cjs");
const require_defineMacro = require("./defineMacro-DmGR7vfu.cjs");
const require_refs = require("./refs-Bg3rmujP.cjs");
//#region src/macros/macroDiscriminatorEnum.ts
/**
* Builds a macro that replaces a discriminator property's schema with a string enum of the given
* values. Object schemas that lack the property are returned unchanged.
*
* @example
* ```ts
* const macro = macroDiscriminatorEnum({ propertyName: 'type', values: ['dog', 'cat'] })
* const next = applyMacros(objectSchema, [macro], { depth: 'shallow' })
* ```
*/
function macroDiscriminatorEnum({ propertyName, values, enumName }) {
return require_defineMacro.defineMacro({
name: "discriminator-enum",
schema(node) {
const objectNode = require_visitor.narrowSchema(node, "object");
if (!objectNode?.properties?.length) return void 0;
if (!objectNode.properties.some((prop) => prop.name === propertyName)) return void 0;
return require_visitor.createSchema({
...objectNode,
properties: objectNode.properties.map((prop) => {
if (prop.name !== propertyName) return prop;
return require_visitor.createProperty({
...prop,
schema: require_visitor.createSchema({
type: "enum",
primitive: "string",
enumValues: values,
name: enumName,
readOnly: prop.schema.readOnly,
writeOnly: prop.schema.writeOnly
})
});
})
});
}
});
}
//#endregion
//#region src/macros/macroEnumName.ts
/**
* Builds a macro that names an inline enum schema from its parent and property name. Boolean enums
* are left anonymous. Non-enum nodes are returned unchanged.
*
* @example
* ```ts
* const macro = macroEnumName({ parentName: 'Pet', propName: 'status', enumSuffix: 'enum' })
* const named = applyMacros(propSchema, [macro], { depth: 'shallow' })
* ```
*/
function macroEnumName({ parentName, propName, enumSuffix }) {
return require_defineMacro.defineMacro({
name: "enum-name",
schema(node) {
const enumNode = require_visitor.narrowSchema(node, "enum");
if (enumNode?.primitive === "boolean") return {
...node,
name: null
};
if (enumNode) return {
...node,
name: require_refs.enumPropName(parentName, propName, enumSuffix)
};
}
});
}
//#endregion
//#region src/macros/macroSimplifyUnion.ts
/**
* Scalar primitive schema types used for union simplification and type narrowing.
*/
const SCALAR_PRIMITIVE_TYPES = /* @__PURE__ */ new Set([
"string",
"number",
"integer",
"bigint",
"boolean"
]);
function isScalarPrimitive(type) {
return SCALAR_PRIMITIVE_TYPES.has(type);
}
/**
* Filters union members, dropping enum members that a broader scalar primitive already covers.
*/
function simplifyUnionMembers(members) {
const scalarPrimitives = new Set(members.filter((member) => isScalarPrimitive(member.type)).map((m) => m.type));
if (!scalarPrimitives.size) return members;
return members.filter((member) => {
const enumNode = require_visitor.narrowSchema(member, "enum");
if (!enumNode) return true;
const primitive = enumNode.primitive;
if (!primitive) return true;
if ((enumNode.namedEnumValues?.length ?? enumNode.enumValues?.length ?? 0) <= 1) return true;
if (scalarPrimitives.has(primitive)) return false;
if ((primitive === "integer" || primitive === "number") && (scalarPrimitives.has("integer") || scalarPrimitives.has("number"))) return false;
return true;
});
}
/**
* Removes union members a broader scalar primitive already covers, such as a multi-value string enum
* sitting next to a plain `string`. Single-value enums are kept.
*
* @example
* ```ts
* const next = applyMacros(unionSchema, [macroSimplifyUnion], { depth: 'shallow' })
* ```
*/
const macroSimplifyUnion = require_defineMacro.defineMacro({
name: "simplify-union",
schema(node) {
const unionNode = require_visitor.narrowSchema(node, "union");
if (!unionNode?.members?.length) return void 0;
const simplified = simplifyUnionMembers(unionNode.members);
if (simplified.length === unionNode.members.length) return void 0;
return {
...unionNode,
members: simplified
};
}
});
//#endregion
exports.macroDiscriminatorEnum = macroDiscriminatorEnum;
exports.macroEnumName = macroEnumName;
exports.macroSimplifyUnion = macroSimplifyUnion;
//# sourceMappingURL=macros.cjs.map
{"version":3,"file":"macros.cjs","names":["defineMacro","narrowSchema","createSchema","createProperty","defineMacro","narrowSchema","enumPropName","narrowSchema","defineMacro"],"sources":["../src/macros/macroDiscriminatorEnum.ts","../src/macros/macroEnumName.ts","../src/macros/macroSimplifyUnion.ts"],"sourcesContent":["import { defineMacro } from '../defineMacro.ts'\nimport { narrowSchema } from '../guards.ts'\nimport { createProperty } from '../nodes/property.ts'\nimport { createSchema } from '../nodes/schema.ts'\n\ntype Props = {\n propertyName: string\n values: Array<string>\n enumName?: string\n}\n\n/**\n * Builds a macro that replaces a discriminator property's schema with a string enum of the given\n * values. Object schemas that lack the property are returned unchanged.\n *\n * @example\n * ```ts\n * const macro = macroDiscriminatorEnum({ propertyName: 'type', values: ['dog', 'cat'] })\n * const next = applyMacros(objectSchema, [macro], { depth: 'shallow' })\n * ```\n */\nexport function macroDiscriminatorEnum({ propertyName, values, enumName }: Props) {\n return defineMacro({\n name: 'discriminator-enum',\n schema(node) {\n const objectNode = narrowSchema(node, 'object')\n if (!objectNode?.properties?.length) return undefined\n if (!objectNode.properties.some((prop) => prop.name === propertyName)) return undefined\n\n return createSchema({\n ...objectNode,\n properties: objectNode.properties.map((prop) => {\n if (prop.name !== propertyName) return prop\n\n return createProperty({\n ...prop,\n schema: createSchema({\n type: 'enum',\n primitive: 'string',\n enumValues: values,\n name: enumName,\n readOnly: prop.schema.readOnly,\n writeOnly: prop.schema.writeOnly,\n }),\n })\n }),\n })\n },\n })\n}\n","import { defineMacro } from '../defineMacro.ts'\nimport { narrowSchema } from '../guards.ts'\nimport { enumPropName } from '../utils/refs.ts'\n\ntype Props = {\n parentName: string | null | undefined\n propName: string\n enumSuffix: string\n}\n\n/**\n * Builds a macro that names an inline enum schema from its parent and property name. Boolean enums\n * are left anonymous. Non-enum nodes are returned unchanged.\n *\n * @example\n * ```ts\n * const macro = macroEnumName({ parentName: 'Pet', propName: 'status', enumSuffix: 'enum' })\n * const named = applyMacros(propSchema, [macro], { depth: 'shallow' })\n * ```\n */\nexport function macroEnumName({ parentName, propName, enumSuffix }: Props) {\n return defineMacro({\n name: 'enum-name',\n schema(node) {\n const enumNode = narrowSchema(node, 'enum')\n\n if (enumNode?.primitive === 'boolean') return { ...node, name: null }\n if (enumNode) return { ...node, name: enumPropName(parentName, propName, enumSuffix) }\n\n return undefined\n },\n })\n}\n","import { defineMacro } from '../defineMacro.ts'\nimport { narrowSchema } from '../guards.ts'\nimport type { SchemaNode } from '../nodes/schema.ts'\n\ntype ScalarPrimitive = 'string' | 'number' | 'integer' | 'bigint' | 'boolean'\n\n/**\n * Scalar primitive schema types used for union simplification and type narrowing.\n */\nconst SCALAR_PRIMITIVE_TYPES = new Set<ScalarPrimitive>(['string', 'number', 'integer', 'bigint', 'boolean'])\n\nfunction isScalarPrimitive(type: string): type is ScalarPrimitive {\n return SCALAR_PRIMITIVE_TYPES.has(type as ScalarPrimitive)\n}\n\n/**\n * Filters union members, dropping enum members that a broader scalar primitive already covers.\n */\nfunction simplifyUnionMembers(members: Array<SchemaNode>): Array<SchemaNode> {\n const scalarPrimitives = new Set(members.filter((member) => isScalarPrimitive(member.type)).map((m) => m.type))\n if (!scalarPrimitives.size) return members\n\n return members.filter((member) => {\n const enumNode = narrowSchema(member, 'enum')\n if (!enumNode) return true\n\n const primitive = enumNode.primitive\n if (!primitive) return true\n\n const enumValueCount = enumNode.namedEnumValues?.length ?? enumNode.enumValues?.length ?? 0\n if (enumValueCount <= 1) return true\n\n if (scalarPrimitives.has(primitive)) return false\n if ((primitive === 'integer' || primitive === 'number') && (scalarPrimitives.has('integer') || scalarPrimitives.has('number'))) return false\n\n return true\n })\n}\n\n/**\n * Removes union members a broader scalar primitive already covers, such as a multi-value string enum\n * sitting next to a plain `string`. Single-value enums are kept.\n *\n * @example\n * ```ts\n * const next = applyMacros(unionSchema, [macroSimplifyUnion], { depth: 'shallow' })\n * ```\n */\nexport const macroSimplifyUnion = defineMacro({\n name: 'simplify-union',\n schema(node) {\n const unionNode = narrowSchema(node, 'union')\n if (!unionNode?.members?.length) return undefined\n\n const simplified = simplifyUnionMembers(unionNode.members)\n if (simplified.length === unionNode.members.length) return undefined\n\n return { ...unionNode, members: simplified }\n },\n})\n"],"mappings":";;;;;;;;;;;;;;;AAqBA,SAAgB,uBAAuB,EAAE,cAAc,QAAQ,YAAmB;CAChF,OAAOA,oBAAAA,YAAY;EACjB,MAAM;EACN,OAAO,MAAM;GACX,MAAM,aAAaC,gBAAAA,aAAa,MAAM,QAAQ;GAC9C,IAAI,CAAC,YAAY,YAAY,QAAQ,OAAO,KAAA;GAC5C,IAAI,CAAC,WAAW,WAAW,MAAM,SAAS,KAAK,SAAS,YAAY,GAAG,OAAO,KAAA;GAE9E,OAAOC,gBAAAA,aAAa;IAClB,GAAG;IACH,YAAY,WAAW,WAAW,KAAK,SAAS;KAC9C,IAAI,KAAK,SAAS,cAAc,OAAO;KAEvC,OAAOC,gBAAAA,eAAe;MACpB,GAAG;MACH,QAAQD,gBAAAA,aAAa;OACnB,MAAM;OACN,WAAW;OACX,YAAY;OACZ,MAAM;OACN,UAAU,KAAK,OAAO;OACtB,WAAW,KAAK,OAAO;MACzB,CAAC;KACH,CAAC;IACH,CAAC;GACH,CAAC;EACH;CACF,CAAC;AACH;;;;;;;;;;;;;AC7BA,SAAgB,cAAc,EAAE,YAAY,UAAU,cAAqB;CACzE,OAAOE,oBAAAA,YAAY;EACjB,MAAM;EACN,OAAO,MAAM;GACX,MAAM,WAAWC,gBAAAA,aAAa,MAAM,MAAM;GAE1C,IAAI,UAAU,cAAc,WAAW,OAAO;IAAE,GAAG;IAAM,MAAM;GAAK;GACpE,IAAI,UAAU,OAAO;IAAE,GAAG;IAAM,MAAMC,aAAAA,aAAa,YAAY,UAAU,UAAU;GAAE;EAGvF;CACF,CAAC;AACH;;;;;;ACvBA,MAAM,yCAAyB,IAAI,IAAqB;CAAC;CAAU;CAAU;CAAW;CAAU;AAAS,CAAC;AAE5G,SAAS,kBAAkB,MAAuC;CAChE,OAAO,uBAAuB,IAAI,IAAuB;AAC3D;;;;AAKA,SAAS,qBAAqB,SAA+C;CAC3E,MAAM,mBAAmB,IAAI,IAAI,QAAQ,QAAQ,WAAW,kBAAkB,OAAO,IAAI,CAAC,CAAC,CAAC,KAAK,MAAM,EAAE,IAAI,CAAC;CAC9G,IAAI,CAAC,iBAAiB,MAAM,OAAO;CAEnC,OAAO,QAAQ,QAAQ,WAAW;EAChC,MAAM,WAAWC,gBAAAA,aAAa,QAAQ,MAAM;EAC5C,IAAI,CAAC,UAAU,OAAO;EAEtB,MAAM,YAAY,SAAS;EAC3B,IAAI,CAAC,WAAW,OAAO;EAGvB,KADuB,SAAS,iBAAiB,UAAU,SAAS,YAAY,UAAU,MACpE,GAAG,OAAO;EAEhC,IAAI,iBAAiB,IAAI,SAAS,GAAG,OAAO;EAC5C,KAAK,cAAc,aAAa,cAAc,cAAc,iBAAiB,IAAI,SAAS,KAAK,iBAAiB,IAAI,QAAQ,IAAI,OAAO;EAEvI,OAAO;CACT,CAAC;AACH;;;;;;;;;;AAWA,MAAa,qBAAqBC,oBAAAA,YAAY;CAC5C,MAAM;CACN,OAAO,MAAM;EACX,MAAM,YAAYD,gBAAAA,aAAa,MAAM,OAAO;EAC5C,IAAI,CAAC,WAAW,SAAS,QAAQ,OAAO,KAAA;EAExC,MAAM,aAAa,qBAAqB,UAAU,OAAO;EACzD,IAAI,WAAW,WAAW,UAAU,QAAQ,QAAQ,OAAO,KAAA;EAE3D,OAAO;GAAE,GAAG;GAAW,SAAS;EAAW;CAC7C;AACF,CAAC"}
import { n as __name } from "./rolldown-runtime-CNktS9qV.js";
import { n as Macro } from "./defineMacro-DzsACbFo.js";
//#region src/macros/macroDiscriminatorEnum.d.ts
type Props$1 = {
propertyName: string;
values: Array<string>;
enumName?: string;
};
/**
* Builds a macro that replaces a discriminator property's schema with a string enum of the given
* values. Object schemas that lack the property are returned unchanged.
*
* @example
* ```ts
* const macro = macroDiscriminatorEnum({ propertyName: 'type', values: ['dog', 'cat'] })
* const next = applyMacros(objectSchema, [macro], { depth: 'shallow' })
* ```
*/
declare function macroDiscriminatorEnum({
propertyName,
values,
enumName
}: Props$1): Macro;
//#endregion
//#region src/macros/macroEnumName.d.ts
type Props = {
parentName: string | null | undefined;
propName: string;
enumSuffix: string;
};
/**
* Builds a macro that names an inline enum schema from its parent and property name. Boolean enums
* are left anonymous. Non-enum nodes are returned unchanged.
*
* @example
* ```ts
* const macro = macroEnumName({ parentName: 'Pet', propName: 'status', enumSuffix: 'enum' })
* const named = applyMacros(propSchema, [macro], { depth: 'shallow' })
* ```
*/
declare function macroEnumName({
parentName,
propName,
enumSuffix
}: Props): Macro;
//#endregion
//#region src/macros/macroSimplifyUnion.d.ts
/**
* Removes union members a broader scalar primitive already covers, such as a multi-value string enum
* sitting next to a plain `string`. Single-value enums are kept.
*
* @example
* ```ts
* const next = applyMacros(unionSchema, [macroSimplifyUnion], { depth: 'shallow' })
* ```
*/
declare const macroSimplifyUnion: Macro;
//#endregion
export { macroDiscriminatorEnum, macroEnumName, macroSimplifyUnion };
//# sourceMappingURL=macros.d.ts.map
import "./rolldown-runtime-CNktS9qV.js";
import { Q as narrowSchema, o as createSchema, u as createProperty } from "./visitor-Dk0DNLfC.js";
import { r as defineMacro } from "./defineMacro-CqX4m8Dq.js";
import { n as enumPropName } from "./refs-BjBHwunY.js";
//#region src/macros/macroDiscriminatorEnum.ts
/**
* Builds a macro that replaces a discriminator property's schema with a string enum of the given
* values. Object schemas that lack the property are returned unchanged.
*
* @example
* ```ts
* const macro = macroDiscriminatorEnum({ propertyName: 'type', values: ['dog', 'cat'] })
* const next = applyMacros(objectSchema, [macro], { depth: 'shallow' })
* ```
*/
function macroDiscriminatorEnum({ propertyName, values, enumName }) {
return defineMacro({
name: "discriminator-enum",
schema(node) {
const objectNode = narrowSchema(node, "object");
if (!objectNode?.properties?.length) return void 0;
if (!objectNode.properties.some((prop) => prop.name === propertyName)) return void 0;
return createSchema({
...objectNode,
properties: objectNode.properties.map((prop) => {
if (prop.name !== propertyName) return prop;
return createProperty({
...prop,
schema: createSchema({
type: "enum",
primitive: "string",
enumValues: values,
name: enumName,
readOnly: prop.schema.readOnly,
writeOnly: prop.schema.writeOnly
})
});
})
});
}
});
}
//#endregion
//#region src/macros/macroEnumName.ts
/**
* Builds a macro that names an inline enum schema from its parent and property name. Boolean enums
* are left anonymous. Non-enum nodes are returned unchanged.
*
* @example
* ```ts
* const macro = macroEnumName({ parentName: 'Pet', propName: 'status', enumSuffix: 'enum' })
* const named = applyMacros(propSchema, [macro], { depth: 'shallow' })
* ```
*/
function macroEnumName({ parentName, propName, enumSuffix }) {
return defineMacro({
name: "enum-name",
schema(node) {
const enumNode = narrowSchema(node, "enum");
if (enumNode?.primitive === "boolean") return {
...node,
name: null
};
if (enumNode) return {
...node,
name: enumPropName(parentName, propName, enumSuffix)
};
}
});
}
//#endregion
//#region src/macros/macroSimplifyUnion.ts
/**
* Scalar primitive schema types used for union simplification and type narrowing.
*/
const SCALAR_PRIMITIVE_TYPES = /* @__PURE__ */ new Set([
"string",
"number",
"integer",
"bigint",
"boolean"
]);
function isScalarPrimitive(type) {
return SCALAR_PRIMITIVE_TYPES.has(type);
}
/**
* Filters union members, dropping enum members that a broader scalar primitive already covers.
*/
function simplifyUnionMembers(members) {
const scalarPrimitives = new Set(members.filter((member) => isScalarPrimitive(member.type)).map((m) => m.type));
if (!scalarPrimitives.size) return members;
return members.filter((member) => {
const enumNode = narrowSchema(member, "enum");
if (!enumNode) return true;
const primitive = enumNode.primitive;
if (!primitive) return true;
if ((enumNode.namedEnumValues?.length ?? enumNode.enumValues?.length ?? 0) <= 1) return true;
if (scalarPrimitives.has(primitive)) return false;
if ((primitive === "integer" || primitive === "number") && (scalarPrimitives.has("integer") || scalarPrimitives.has("number"))) return false;
return true;
});
}
/**
* Removes union members a broader scalar primitive already covers, such as a multi-value string enum
* sitting next to a plain `string`. Single-value enums are kept.
*
* @example
* ```ts
* const next = applyMacros(unionSchema, [macroSimplifyUnion], { depth: 'shallow' })
* ```
*/
const macroSimplifyUnion = defineMacro({
name: "simplify-union",
schema(node) {
const unionNode = narrowSchema(node, "union");
if (!unionNode?.members?.length) return void 0;
const simplified = simplifyUnionMembers(unionNode.members);
if (simplified.length === unionNode.members.length) return void 0;
return {
...unionNode,
members: simplified
};
}
});
//#endregion
export { macroDiscriminatorEnum, macroEnumName, macroSimplifyUnion };
//# sourceMappingURL=macros.js.map
{"version":3,"file":"macros.js","names":[],"sources":["../src/macros/macroDiscriminatorEnum.ts","../src/macros/macroEnumName.ts","../src/macros/macroSimplifyUnion.ts"],"sourcesContent":["import { defineMacro } from '../defineMacro.ts'\nimport { narrowSchema } from '../guards.ts'\nimport { createProperty } from '../nodes/property.ts'\nimport { createSchema } from '../nodes/schema.ts'\n\ntype Props = {\n propertyName: string\n values: Array<string>\n enumName?: string\n}\n\n/**\n * Builds a macro that replaces a discriminator property's schema with a string enum of the given\n * values. Object schemas that lack the property are returned unchanged.\n *\n * @example\n * ```ts\n * const macro = macroDiscriminatorEnum({ propertyName: 'type', values: ['dog', 'cat'] })\n * const next = applyMacros(objectSchema, [macro], { depth: 'shallow' })\n * ```\n */\nexport function macroDiscriminatorEnum({ propertyName, values, enumName }: Props) {\n return defineMacro({\n name: 'discriminator-enum',\n schema(node) {\n const objectNode = narrowSchema(node, 'object')\n if (!objectNode?.properties?.length) return undefined\n if (!objectNode.properties.some((prop) => prop.name === propertyName)) return undefined\n\n return createSchema({\n ...objectNode,\n properties: objectNode.properties.map((prop) => {\n if (prop.name !== propertyName) return prop\n\n return createProperty({\n ...prop,\n schema: createSchema({\n type: 'enum',\n primitive: 'string',\n enumValues: values,\n name: enumName,\n readOnly: prop.schema.readOnly,\n writeOnly: prop.schema.writeOnly,\n }),\n })\n }),\n })\n },\n })\n}\n","import { defineMacro } from '../defineMacro.ts'\nimport { narrowSchema } from '../guards.ts'\nimport { enumPropName } from '../utils/refs.ts'\n\ntype Props = {\n parentName: string | null | undefined\n propName: string\n enumSuffix: string\n}\n\n/**\n * Builds a macro that names an inline enum schema from its parent and property name. Boolean enums\n * are left anonymous. Non-enum nodes are returned unchanged.\n *\n * @example\n * ```ts\n * const macro = macroEnumName({ parentName: 'Pet', propName: 'status', enumSuffix: 'enum' })\n * const named = applyMacros(propSchema, [macro], { depth: 'shallow' })\n * ```\n */\nexport function macroEnumName({ parentName, propName, enumSuffix }: Props) {\n return defineMacro({\n name: 'enum-name',\n schema(node) {\n const enumNode = narrowSchema(node, 'enum')\n\n if (enumNode?.primitive === 'boolean') return { ...node, name: null }\n if (enumNode) return { ...node, name: enumPropName(parentName, propName, enumSuffix) }\n\n return undefined\n },\n })\n}\n","import { defineMacro } from '../defineMacro.ts'\nimport { narrowSchema } from '../guards.ts'\nimport type { SchemaNode } from '../nodes/schema.ts'\n\ntype ScalarPrimitive = 'string' | 'number' | 'integer' | 'bigint' | 'boolean'\n\n/**\n * Scalar primitive schema types used for union simplification and type narrowing.\n */\nconst SCALAR_PRIMITIVE_TYPES = new Set<ScalarPrimitive>(['string', 'number', 'integer', 'bigint', 'boolean'])\n\nfunction isScalarPrimitive(type: string): type is ScalarPrimitive {\n return SCALAR_PRIMITIVE_TYPES.has(type as ScalarPrimitive)\n}\n\n/**\n * Filters union members, dropping enum members that a broader scalar primitive already covers.\n */\nfunction simplifyUnionMembers(members: Array<SchemaNode>): Array<SchemaNode> {\n const scalarPrimitives = new Set(members.filter((member) => isScalarPrimitive(member.type)).map((m) => m.type))\n if (!scalarPrimitives.size) return members\n\n return members.filter((member) => {\n const enumNode = narrowSchema(member, 'enum')\n if (!enumNode) return true\n\n const primitive = enumNode.primitive\n if (!primitive) return true\n\n const enumValueCount = enumNode.namedEnumValues?.length ?? enumNode.enumValues?.length ?? 0\n if (enumValueCount <= 1) return true\n\n if (scalarPrimitives.has(primitive)) return false\n if ((primitive === 'integer' || primitive === 'number') && (scalarPrimitives.has('integer') || scalarPrimitives.has('number'))) return false\n\n return true\n })\n}\n\n/**\n * Removes union members a broader scalar primitive already covers, such as a multi-value string enum\n * sitting next to a plain `string`. Single-value enums are kept.\n *\n * @example\n * ```ts\n * const next = applyMacros(unionSchema, [macroSimplifyUnion], { depth: 'shallow' })\n * ```\n */\nexport const macroSimplifyUnion = defineMacro({\n name: 'simplify-union',\n schema(node) {\n const unionNode = narrowSchema(node, 'union')\n if (!unionNode?.members?.length) return undefined\n\n const simplified = simplifyUnionMembers(unionNode.members)\n if (simplified.length === unionNode.members.length) return undefined\n\n return { ...unionNode, members: simplified }\n },\n})\n"],"mappings":";;;;;;;;;;;;;;;AAqBA,SAAgB,uBAAuB,EAAE,cAAc,QAAQ,YAAmB;CAChF,OAAO,YAAY;EACjB,MAAM;EACN,OAAO,MAAM;GACX,MAAM,aAAa,aAAa,MAAM,QAAQ;GAC9C,IAAI,CAAC,YAAY,YAAY,QAAQ,OAAO,KAAA;GAC5C,IAAI,CAAC,WAAW,WAAW,MAAM,SAAS,KAAK,SAAS,YAAY,GAAG,OAAO,KAAA;GAE9E,OAAO,aAAa;IAClB,GAAG;IACH,YAAY,WAAW,WAAW,KAAK,SAAS;KAC9C,IAAI,KAAK,SAAS,cAAc,OAAO;KAEvC,OAAO,eAAe;MACpB,GAAG;MACH,QAAQ,aAAa;OACnB,MAAM;OACN,WAAW;OACX,YAAY;OACZ,MAAM;OACN,UAAU,KAAK,OAAO;OACtB,WAAW,KAAK,OAAO;MACzB,CAAC;KACH,CAAC;IACH,CAAC;GACH,CAAC;EACH;CACF,CAAC;AACH;;;;;;;;;;;;;AC7BA,SAAgB,cAAc,EAAE,YAAY,UAAU,cAAqB;CACzE,OAAO,YAAY;EACjB,MAAM;EACN,OAAO,MAAM;GACX,MAAM,WAAW,aAAa,MAAM,MAAM;GAE1C,IAAI,UAAU,cAAc,WAAW,OAAO;IAAE,GAAG;IAAM,MAAM;GAAK;GACpE,IAAI,UAAU,OAAO;IAAE,GAAG;IAAM,MAAM,aAAa,YAAY,UAAU,UAAU;GAAE;EAGvF;CACF,CAAC;AACH;;;;;;ACvBA,MAAM,yCAAyB,IAAI,IAAqB;CAAC;CAAU;CAAU;CAAW;CAAU;AAAS,CAAC;AAE5G,SAAS,kBAAkB,MAAuC;CAChE,OAAO,uBAAuB,IAAI,IAAuB;AAC3D;;;;AAKA,SAAS,qBAAqB,SAA+C;CAC3E,MAAM,mBAAmB,IAAI,IAAI,QAAQ,QAAQ,WAAW,kBAAkB,OAAO,IAAI,CAAC,CAAC,CAAC,KAAK,MAAM,EAAE,IAAI,CAAC;CAC9G,IAAI,CAAC,iBAAiB,MAAM,OAAO;CAEnC,OAAO,QAAQ,QAAQ,WAAW;EAChC,MAAM,WAAW,aAAa,QAAQ,MAAM;EAC5C,IAAI,CAAC,UAAU,OAAO;EAEtB,MAAM,YAAY,SAAS;EAC3B,IAAI,CAAC,WAAW,OAAO;EAGvB,KADuB,SAAS,iBAAiB,UAAU,SAAS,YAAY,UAAU,MACpE,GAAG,OAAO;EAEhC,IAAI,iBAAiB,IAAI,SAAS,GAAG,OAAO;EAC5C,KAAK,cAAc,aAAa,cAAc,cAAc,iBAAiB,IAAI,SAAS,KAAK,iBAAiB,IAAI,QAAQ,IAAI,OAAO;EAEvI,OAAO;CACT,CAAC;AACH;;;;;;;;;;AAWA,MAAa,qBAAqB,YAAY;CAC5C,MAAM;CACN,OAAO,MAAM;EACX,MAAM,YAAY,aAAa,MAAM,OAAO;EAC5C,IAAI,CAAC,WAAW,SAAS,QAAQ,OAAO,KAAA;EAExC,MAAM,aAAa,qBAAqB,UAAU,OAAO;EACzD,IAAI,WAAW,WAAW,UAAU,QAAQ,QAAQ,OAAO,KAAA;EAE3D,OAAO;GAAE,GAAG;GAAW,SAAS;EAAW;CAC7C;AACF,CAAC"}
const require_visitor = require("./visitor-h6dEM3vR.cjs");
//#region src/utils/refs.ts
const plainStringTypes = /* @__PURE__ */ new Set([
"string",
"uuid",
"email",
"url",
"datetime"
]);
/**
* Returns the last path segment of a reference string.
*
* @example
* `extractRefName('#/components/schemas/Pet') // 'Pet'`
*/
function extractRefName(ref) {
return ref.split("/").at(-1) ?? ref;
}
/**
* Resolves the schema name of a ref node. Uses the last segment of `ref` when set, otherwise falls
* back to `name` then nested `schema.name`.
*
* Returns `null` for non-ref nodes or when no name resolves.
*
* @example
* `resolveRefName({ kind: 'Schema', type: 'ref', ref: '#/components/schemas/Pet' }) // 'Pet'`
*/
function resolveRefName(node) {
if (!node || node.type !== "ref") return null;
if (node.ref) return extractRefName(node.ref) ?? node.name ?? node.schema?.name ?? null;
return node.name ?? node.schema?.name ?? null;
}
/**
* Builds a PascalCase child schema name by joining a parent name and property name.
* Returns `null` when there is no parent to nest under.
*
* @example Nested under a parent
* `childName('Order', 'shipping_address') // 'OrderShippingAddress'`
*
* @example No parent
* `childName(undefined, 'params') // null`
*/
function childName(parentName, propName) {
return parentName ? require_visitor.pascalCase([parentName, propName].join(" ")) : null;
}
/**
* Builds a PascalCase enum name from the parent name, property name, and a suffix, skipping any
* empty parts.
*
* @example
* `enumPropName('Order', 'status', 'enum') // 'OrderStatusEnum'`
*/
function enumPropName(parentName, propName, enumSuffix) {
return require_visitor.pascalCase([
parentName,
propName,
enumSuffix
].filter(Boolean).join(" "));
}
/**
* Merges a ref node with its resolved schema, giving usage-site fields precedence.
*
* Every field set on the ref node except `kind`, `type`, `name`, `ref`, and `schema` overrides the
* same field in the resolved `node.schema` (for example `description`, `nullable`, `readOnly`,
* `deprecated`). Fields left `undefined` on the ref do not shadow the resolved schema. Non-ref
* nodes and refs without a resolved `schema` are returned unchanged.
*
* @example
* ```ts
* const ref = createSchema({ type: 'ref', ref: '#/components/schemas/Pet', description: 'A cute pet' })
* const merged = syncSchemaRef(ref) // merges with resolved Pet schema
* ```
*/
function syncSchemaRef(node) {
const ref = require_visitor.narrowSchema(node, "ref");
if (!ref) return node;
if (!ref.schema) return node;
const { kind: _kind, type: _type, name: _name, ref: _ref, schema: _schema, ...overrides } = ref;
const definedOverrides = Object.fromEntries(Object.entries(overrides).filter(([, v]) => v !== void 0));
return require_visitor.createSchema({
...ref.schema,
...definedOverrides
});
}
/**
* Type guard that returns `true` when a schema emits as a plain `string` type.
*
* Covers `string`, `uuid`, `email`, `url`, and `datetime` types. For `date` and `time`
* types, returns `true` only when `representation` is `'string'` rather than `'date'`.
*/
function isStringType(node) {
if (plainStringTypes.has(node.type)) return true;
const temporal = require_visitor.narrowSchema(node, "date") ?? require_visitor.narrowSchema(node, "time");
if (temporal) return temporal.representation !== "date";
return false;
}
//#endregion
Object.defineProperty(exports, "childName", {
enumerable: true,
get: function() {
return childName;
}
});
Object.defineProperty(exports, "enumPropName", {
enumerable: true,
get: function() {
return enumPropName;
}
});
Object.defineProperty(exports, "extractRefName", {
enumerable: true,
get: function() {
return extractRefName;
}
});
Object.defineProperty(exports, "isStringType", {
enumerable: true,
get: function() {
return isStringType;
}
});
Object.defineProperty(exports, "resolveRefName", {
enumerable: true,
get: function() {
return resolveRefName;
}
});
Object.defineProperty(exports, "syncSchemaRef", {
enumerable: true,
get: function() {
return syncSchemaRef;
}
});
//# sourceMappingURL=refs-Bg3rmujP.cjs.map
{"version":3,"file":"refs-Bg3rmujP.cjs","names":["pascalCase","narrowSchema","createSchema"],"sources":["../src/utils/refs.ts"],"sourcesContent":["import { pascalCase } from '@internals/utils'\nimport { narrowSchema } from '../guards.ts'\nimport type { SchemaNode } from '../nodes/index.ts'\nimport { createSchema, type SchemaType } from '../nodes/schema.ts'\n\nconst plainStringTypes = new Set<SchemaType>(['string', 'uuid', 'email', 'url', 'datetime'] as const)\n\n/**\n * Returns the last path segment of a reference string.\n *\n * @example\n * `extractRefName('#/components/schemas/Pet') // 'Pet'`\n */\nexport function extractRefName(ref: string): string {\n return ref.split('/').at(-1) ?? ref\n}\n\n/**\n * Resolves the schema name of a ref node. Uses the last segment of `ref` when set, otherwise falls\n * back to `name` then nested `schema.name`.\n *\n * Returns `null` for non-ref nodes or when no name resolves.\n *\n * @example\n * `resolveRefName({ kind: 'Schema', type: 'ref', ref: '#/components/schemas/Pet' }) // 'Pet'`\n */\nexport function resolveRefName(node: SchemaNode | undefined): string | null {\n if (!node || node.type !== 'ref') return null\n if (node.ref) return extractRefName(node.ref) ?? node.name ?? node.schema?.name ?? null\n\n return node.name ?? node.schema?.name ?? null\n}\n\n/**\n * Builds a PascalCase child schema name by joining a parent name and property name.\n * Returns `null` when there is no parent to nest under.\n *\n * @example Nested under a parent\n * `childName('Order', 'shipping_address') // 'OrderShippingAddress'`\n *\n * @example No parent\n * `childName(undefined, 'params') // null`\n */\nexport function childName(parentName: string | null | undefined, propName: string): string | null {\n return parentName ? pascalCase([parentName, propName].join(' ')) : null\n}\n\n/**\n * Builds a PascalCase enum name from the parent name, property name, and a suffix, skipping any\n * empty parts.\n *\n * @example\n * `enumPropName('Order', 'status', 'enum') // 'OrderStatusEnum'`\n */\nexport function enumPropName(parentName: string | null | undefined, propName: string, enumSuffix: string): string {\n return pascalCase([parentName, propName, enumSuffix].filter(Boolean).join(' '))\n}\n\n/**\n * Merges a ref node with its resolved schema, giving usage-site fields precedence.\n *\n * Every field set on the ref node except `kind`, `type`, `name`, `ref`, and `schema` overrides the\n * same field in the resolved `node.schema` (for example `description`, `nullable`, `readOnly`,\n * `deprecated`). Fields left `undefined` on the ref do not shadow the resolved schema. Non-ref\n * nodes and refs without a resolved `schema` are returned unchanged.\n *\n * @example\n * ```ts\n * const ref = createSchema({ type: 'ref', ref: '#/components/schemas/Pet', description: 'A cute pet' })\n * const merged = syncSchemaRef(ref) // merges with resolved Pet schema\n * ```\n */\nexport function syncSchemaRef(node: SchemaNode): SchemaNode {\n const ref = narrowSchema(node, 'ref')\n\n if (!ref) return node\n if (!ref.schema) return node\n\n const { kind: _kind, type: _type, name: _name, ref: _ref, schema: _schema, ...overrides } = ref\n\n // Filter out undefined override values so they don't shadow the resolved schema's fields.\n const definedOverrides = Object.fromEntries(Object.entries(overrides).filter(([, v]) => v !== undefined))\n\n return createSchema({ ...ref.schema, ...definedOverrides })\n}\n\n/**\n * Type guard that returns `true` when a schema emits as a plain `string` type.\n *\n * Covers `string`, `uuid`, `email`, `url`, and `datetime` types. For `date` and `time`\n * types, returns `true` only when `representation` is `'string'` rather than `'date'`.\n */\nexport function isStringType(node: SchemaNode): boolean {\n if (plainStringTypes.has(node.type)) {\n return true\n }\n\n const temporal = narrowSchema(node, 'date') ?? narrowSchema(node, 'time')\n if (temporal) {\n return temporal.representation !== 'date'\n }\n\n return false\n}\n"],"mappings":";;AAKA,MAAM,mCAAmB,IAAI,IAAgB;CAAC;CAAU;CAAQ;CAAS;CAAO;AAAU,CAAU;;;;;;;AAQpG,SAAgB,eAAe,KAAqB;CAClD,OAAO,IAAI,MAAM,GAAG,CAAC,CAAC,GAAG,EAAE,KAAK;AAClC;;;;;;;;;;AAWA,SAAgB,eAAe,MAA6C;CAC1E,IAAI,CAAC,QAAQ,KAAK,SAAS,OAAO,OAAO;CACzC,IAAI,KAAK,KAAK,OAAO,eAAe,KAAK,GAAG,KAAK,KAAK,QAAQ,KAAK,QAAQ,QAAQ;CAEnF,OAAO,KAAK,QAAQ,KAAK,QAAQ,QAAQ;AAC3C;;;;;;;;;;;AAYA,SAAgB,UAAU,YAAuC,UAAiC;CAChG,OAAO,aAAaA,gBAAAA,WAAW,CAAC,YAAY,QAAQ,CAAC,CAAC,KAAK,GAAG,CAAC,IAAI;AACrE;;;;;;;;AASA,SAAgB,aAAa,YAAuC,UAAkB,YAA4B;CAChH,OAAOA,gBAAAA,WAAW;EAAC;EAAY;EAAU;CAAU,CAAC,CAAC,OAAO,OAAO,CAAC,CAAC,KAAK,GAAG,CAAC;AAChF;;;;;;;;;;;;;;;AAgBA,SAAgB,cAAc,MAA8B;CAC1D,MAAM,MAAMC,gBAAAA,aAAa,MAAM,KAAK;CAEpC,IAAI,CAAC,KAAK,OAAO;CACjB,IAAI,CAAC,IAAI,QAAQ,OAAO;CAExB,MAAM,EAAE,MAAM,OAAO,MAAM,OAAO,MAAM,OAAO,KAAK,MAAM,QAAQ,SAAS,GAAG,cAAc;CAG5F,MAAM,mBAAmB,OAAO,YAAY,OAAO,QAAQ,SAAS,CAAC,CAAC,QAAQ,GAAG,OAAO,MAAM,KAAA,CAAS,CAAC;CAExG,OAAOC,gBAAAA,aAAa;EAAE,GAAG,IAAI;EAAQ,GAAG;CAAiB,CAAC;AAC5D;;;;;;;AAQA,SAAgB,aAAa,MAA2B;CACtD,IAAI,iBAAiB,IAAI,KAAK,IAAI,GAChC,OAAO;CAGT,MAAM,WAAWD,gBAAAA,aAAa,MAAM,MAAM,KAAKA,gBAAAA,aAAa,MAAM,MAAM;CACxE,IAAI,UACF,OAAO,SAAS,mBAAmB;CAGrC,OAAO;AACT"}
import "./rolldown-runtime-CNktS9qV.js";
import { M as pascalCase, Q as narrowSchema, o as createSchema } from "./visitor-Dk0DNLfC.js";
//#region src/utils/refs.ts
const plainStringTypes = /* @__PURE__ */ new Set([
"string",
"uuid",
"email",
"url",
"datetime"
]);
/**
* Returns the last path segment of a reference string.
*
* @example
* `extractRefName('#/components/schemas/Pet') // 'Pet'`
*/
function extractRefName(ref) {
return ref.split("/").at(-1) ?? ref;
}
/**
* Resolves the schema name of a ref node. Uses the last segment of `ref` when set, otherwise falls
* back to `name` then nested `schema.name`.
*
* Returns `null` for non-ref nodes or when no name resolves.
*
* @example
* `resolveRefName({ kind: 'Schema', type: 'ref', ref: '#/components/schemas/Pet' }) // 'Pet'`
*/
function resolveRefName(node) {
if (!node || node.type !== "ref") return null;
if (node.ref) return extractRefName(node.ref) ?? node.name ?? node.schema?.name ?? null;
return node.name ?? node.schema?.name ?? null;
}
/**
* Builds a PascalCase child schema name by joining a parent name and property name.
* Returns `null` when there is no parent to nest under.
*
* @example Nested under a parent
* `childName('Order', 'shipping_address') // 'OrderShippingAddress'`
*
* @example No parent
* `childName(undefined, 'params') // null`
*/
function childName(parentName, propName) {
return parentName ? pascalCase([parentName, propName].join(" ")) : null;
}
/**
* Builds a PascalCase enum name from the parent name, property name, and a suffix, skipping any
* empty parts.
*
* @example
* `enumPropName('Order', 'status', 'enum') // 'OrderStatusEnum'`
*/
function enumPropName(parentName, propName, enumSuffix) {
return pascalCase([
parentName,
propName,
enumSuffix
].filter(Boolean).join(" "));
}
/**
* Merges a ref node with its resolved schema, giving usage-site fields precedence.
*
* Every field set on the ref node except `kind`, `type`, `name`, `ref`, and `schema` overrides the
* same field in the resolved `node.schema` (for example `description`, `nullable`, `readOnly`,
* `deprecated`). Fields left `undefined` on the ref do not shadow the resolved schema. Non-ref
* nodes and refs without a resolved `schema` are returned unchanged.
*
* @example
* ```ts
* const ref = createSchema({ type: 'ref', ref: '#/components/schemas/Pet', description: 'A cute pet' })
* const merged = syncSchemaRef(ref) // merges with resolved Pet schema
* ```
*/
function syncSchemaRef(node) {
const ref = narrowSchema(node, "ref");
if (!ref) return node;
if (!ref.schema) return node;
const { kind: _kind, type: _type, name: _name, ref: _ref, schema: _schema, ...overrides } = ref;
const definedOverrides = Object.fromEntries(Object.entries(overrides).filter(([, v]) => v !== void 0));
return createSchema({
...ref.schema,
...definedOverrides
});
}
/**
* Type guard that returns `true` when a schema emits as a plain `string` type.
*
* Covers `string`, `uuid`, `email`, `url`, and `datetime` types. For `date` and `time`
* types, returns `true` only when `representation` is `'string'` rather than `'date'`.
*/
function isStringType(node) {
if (plainStringTypes.has(node.type)) return true;
const temporal = narrowSchema(node, "date") ?? narrowSchema(node, "time");
if (temporal) return temporal.representation !== "date";
return false;
}
//#endregion
export { resolveRefName as a, isStringType as i, enumPropName as n, syncSchemaRef as o, extractRefName as r, childName as t };
//# sourceMappingURL=refs-BjBHwunY.js.map
{"version":3,"file":"refs-BjBHwunY.js","names":[],"sources":["../src/utils/refs.ts"],"sourcesContent":["import { pascalCase } from '@internals/utils'\nimport { narrowSchema } from '../guards.ts'\nimport type { SchemaNode } from '../nodes/index.ts'\nimport { createSchema, type SchemaType } from '../nodes/schema.ts'\n\nconst plainStringTypes = new Set<SchemaType>(['string', 'uuid', 'email', 'url', 'datetime'] as const)\n\n/**\n * Returns the last path segment of a reference string.\n *\n * @example\n * `extractRefName('#/components/schemas/Pet') // 'Pet'`\n */\nexport function extractRefName(ref: string): string {\n return ref.split('/').at(-1) ?? ref\n}\n\n/**\n * Resolves the schema name of a ref node. Uses the last segment of `ref` when set, otherwise falls\n * back to `name` then nested `schema.name`.\n *\n * Returns `null` for non-ref nodes or when no name resolves.\n *\n * @example\n * `resolveRefName({ kind: 'Schema', type: 'ref', ref: '#/components/schemas/Pet' }) // 'Pet'`\n */\nexport function resolveRefName(node: SchemaNode | undefined): string | null {\n if (!node || node.type !== 'ref') return null\n if (node.ref) return extractRefName(node.ref) ?? node.name ?? node.schema?.name ?? null\n\n return node.name ?? node.schema?.name ?? null\n}\n\n/**\n * Builds a PascalCase child schema name by joining a parent name and property name.\n * Returns `null` when there is no parent to nest under.\n *\n * @example Nested under a parent\n * `childName('Order', 'shipping_address') // 'OrderShippingAddress'`\n *\n * @example No parent\n * `childName(undefined, 'params') // null`\n */\nexport function childName(parentName: string | null | undefined, propName: string): string | null {\n return parentName ? pascalCase([parentName, propName].join(' ')) : null\n}\n\n/**\n * Builds a PascalCase enum name from the parent name, property name, and a suffix, skipping any\n * empty parts.\n *\n * @example\n * `enumPropName('Order', 'status', 'enum') // 'OrderStatusEnum'`\n */\nexport function enumPropName(parentName: string | null | undefined, propName: string, enumSuffix: string): string {\n return pascalCase([parentName, propName, enumSuffix].filter(Boolean).join(' '))\n}\n\n/**\n * Merges a ref node with its resolved schema, giving usage-site fields precedence.\n *\n * Every field set on the ref node except `kind`, `type`, `name`, `ref`, and `schema` overrides the\n * same field in the resolved `node.schema` (for example `description`, `nullable`, `readOnly`,\n * `deprecated`). Fields left `undefined` on the ref do not shadow the resolved schema. Non-ref\n * nodes and refs without a resolved `schema` are returned unchanged.\n *\n * @example\n * ```ts\n * const ref = createSchema({ type: 'ref', ref: '#/components/schemas/Pet', description: 'A cute pet' })\n * const merged = syncSchemaRef(ref) // merges with resolved Pet schema\n * ```\n */\nexport function syncSchemaRef(node: SchemaNode): SchemaNode {\n const ref = narrowSchema(node, 'ref')\n\n if (!ref) return node\n if (!ref.schema) return node\n\n const { kind: _kind, type: _type, name: _name, ref: _ref, schema: _schema, ...overrides } = ref\n\n // Filter out undefined override values so they don't shadow the resolved schema's fields.\n const definedOverrides = Object.fromEntries(Object.entries(overrides).filter(([, v]) => v !== undefined))\n\n return createSchema({ ...ref.schema, ...definedOverrides })\n}\n\n/**\n * Type guard that returns `true` when a schema emits as a plain `string` type.\n *\n * Covers `string`, `uuid`, `email`, `url`, and `datetime` types. For `date` and `time`\n * types, returns `true` only when `representation` is `'string'` rather than `'date'`.\n */\nexport function isStringType(node: SchemaNode): boolean {\n if (plainStringTypes.has(node.type)) {\n return true\n }\n\n const temporal = narrowSchema(node, 'date') ?? narrowSchema(node, 'time')\n if (temporal) {\n return temporal.representation !== 'date'\n }\n\n return false\n}\n"],"mappings":";;;AAKA,MAAM,mCAAmB,IAAI,IAAgB;CAAC;CAAU;CAAQ;CAAS;CAAO;AAAU,CAAU;;;;;;;AAQpG,SAAgB,eAAe,KAAqB;CAClD,OAAO,IAAI,MAAM,GAAG,CAAC,CAAC,GAAG,EAAE,KAAK;AAClC;;;;;;;;;;AAWA,SAAgB,eAAe,MAA6C;CAC1E,IAAI,CAAC,QAAQ,KAAK,SAAS,OAAO,OAAO;CACzC,IAAI,KAAK,KAAK,OAAO,eAAe,KAAK,GAAG,KAAK,KAAK,QAAQ,KAAK,QAAQ,QAAQ;CAEnF,OAAO,KAAK,QAAQ,KAAK,QAAQ,QAAQ;AAC3C;;;;;;;;;;;AAYA,SAAgB,UAAU,YAAuC,UAAiC;CAChG,OAAO,aAAa,WAAW,CAAC,YAAY,QAAQ,CAAC,CAAC,KAAK,GAAG,CAAC,IAAI;AACrE;;;;;;;;AASA,SAAgB,aAAa,YAAuC,UAAkB,YAA4B;CAChH,OAAO,WAAW;EAAC;EAAY;EAAU;CAAU,CAAC,CAAC,OAAO,OAAO,CAAC,CAAC,KAAK,GAAG,CAAC;AAChF;;;;;;;;;;;;;;;AAgBA,SAAgB,cAAc,MAA8B;CAC1D,MAAM,MAAM,aAAa,MAAM,KAAK;CAEpC,IAAI,CAAC,KAAK,OAAO;CACjB,IAAI,CAAC,IAAI,QAAQ,OAAO;CAExB,MAAM,EAAE,MAAM,OAAO,MAAM,OAAO,MAAM,OAAO,KAAK,MAAM,QAAQ,SAAS,GAAG,cAAc;CAG5F,MAAM,mBAAmB,OAAO,YAAY,OAAO,QAAQ,SAAS,CAAC,CAAC,QAAQ,GAAG,OAAO,MAAM,KAAA,CAAS,CAAC;CAExG,OAAO,aAAa;EAAE,GAAG,IAAI;EAAQ,GAAG;CAAiB,CAAC;AAC5D;;;;;;;AAQA,SAAgB,aAAa,MAA2B;CACtD,IAAI,iBAAiB,IAAI,KAAK,IAAI,GAChC,OAAO;CAGT,MAAM,WAAW,aAAa,MAAM,MAAM,KAAK,aAAa,MAAM,MAAM;CACxE,IAAI,UACF,OAAO,SAAS,mBAAmB;CAGrC,OAAO;AACT"}
import { n as __name } from "./rolldown-runtime-CNktS9qV.js";
import { et as SchemaNode, nt as SchemaType, tt as SchemaNodeByType } from "./index-Cu2zmNxv.js";
//#region src/defineDialect.d.ts
/**
* The spec-specific questions a schema parser answers while turning a source document into Kubb
* AST nodes. The rest of the pipeline is generic, so this is the one seam where source formats
* differ.
*/
type SchemaDialect<TSchema = unknown, TRef = TSchema, TDiscriminated = TSchema, TDocument = unknown> = {
/**
* Whether the schema is nullable.
*/
isNullable(schema?: TSchema): boolean;
/**
* Whether the value is a `$ref` pointer.
*/
isReference(value?: unknown): value is TRef;
/**
* Whether the schema carries a discriminator for polymorphism.
*/
isDiscriminator(value?: unknown): value is TDiscriminated;
/**
* Whether the schema is binary data, converted to a `blob` node.
*/
isBinary(schema: TSchema): boolean;
/**
* Resolves a local `$ref` against the document, or nullish when it cannot.
*/
resolveRef<TResolved>(document: TDocument, ref: string): TResolved | null | undefined;
};
/**
* A spec adapter's dialect. `name` identifies it in logs and diagnostics, and `schema` holds the
* spec-specific schema questions the parser answers.
*/
type Dialect<TSchema = unknown, TRef = TSchema, TDiscriminated = TSchema, TDocument = unknown> = {
/**
* Identifies the dialect in logs and diagnostics.
*/
name: string;
/**
* The spec-specific schema behavior. See {@link SchemaDialect}.
*/
schema: SchemaDialect<TSchema, TRef, TDiscriminated, TDocument>;
};
/**
* Types a {@link Dialect} for an adapter. Adds no runtime behavior and only pins the
* dialect's type for inference.
*
* @example
* ```ts
* export const oasDialect = defineDialect({
* name: 'oas',
* schema: {
* isNullable,
* isReference,
* isDiscriminator,
* isBinary: (schema) => schema.type === 'string' && schema.contentMediaType === 'application/octet-stream',
* resolveRef,
* },
* })
* ```
*/
declare function defineDialect<TSchema, TRef, TDiscriminated, TDocument>(dialect: Dialect<TSchema, TRef, TDiscriminated, TDocument>): Dialect<TSchema, TRef, TDiscriminated, TDocument>;
//#endregion
//#region src/createPrinter.d.ts
/**
* Runtime context passed as `this` to printer handlers.
*
* `this.transform` dispatches to node-level handlers from `nodes`.
*
* @example
* ```ts
* const context: PrinterHandlerContext<string, {}> = {
* options: {},
* transform: () => 'value',
* }
* ```
*/
type PrinterHandlerContext<TOutput, TOptions extends object> = {
/**
* Recursively transform a nested `SchemaNode` to `TOutput` using the node-level handlers.
* Use `this.transform` inside `nodes` handlers and inside the `print` override.
*/
transform: (node: SchemaNode) => TOutput | null;
/**
* Run the printer's built-in handler for the node, ignoring any override for its type.
* Inside an override, `this.base(node)` returns what the printer would have emitted,
* so the override can wrap it instead of re-implementing the handler. Nested nodes
* still dispatch through the overrides.
*/
base: (node: SchemaNode) => TOutput | null;
/**
* Options for this printer instance.
*/
options: TOptions;
};
/**
* Handler for one schema node type.
*
* Use a regular function (not an arrow function) if you need `this`.
*
* @example
* ```ts
* const handler: PrinterHandler<string, {}, 'string'> = function () {
* return 'string'
* }
* ```
*/
type PrinterHandler<TOutput, TOptions extends object, T extends SchemaType = SchemaType> = (this: PrinterHandlerContext<TOutput, TOptions>, node: SchemaNodeByType[T]) => TOutput | null;
/**
* Partial map of per-node-type handler overrides for a printer.
*
* Each key is a `SchemaType` string (e.g. `'date'`, `'string'`).
* Supply only the handlers you want to replace. The printer's built-in
* defaults fill in the rest.
*
* @example
* ```ts
* pluginZod({
* printer: {
* nodes: {
* date(): string {
* return 'z.string().date()'
* },
* } satisfies PrinterPartial<string, PrinterZodOptions>,
* },
* })
* ```
*/
type PrinterPartial<TOutput, TOptions extends object> = Partial<{ [K in SchemaType]: PrinterHandler<TOutput, TOptions, K> }>;
/**
* Generic shape used by `definePrinter`.
*
* - `TName` unique string identifier (e.g. `'zod'`, `'ts'`)
* - `TOptions` options passed to and stored on the printer instance
* - `TOutput` the type emitted by node handlers
* - `TPrintOutput` type returned by public `print` (defaults to `TOutput`)
*
* @example
* ```ts
* type MyPrinter = PrinterFactoryOptions<'my', { strict: boolean }, string>
* ```
*/
type PrinterFactoryOptions<TName extends string = string, TOptions extends object = object, TOutput = unknown, TPrintOutput = TOutput> = {
name: TName;
options: TOptions;
output: TOutput;
printOutput: TPrintOutput;
};
/**
* Printer instance returned by a printer factory.
*
* @example
* ```ts
* const printer = definePrinter((options: {}) => ({ name: 'x', options, nodes: {} }))({})
* ```
*/
type Printer<T extends PrinterFactoryOptions = PrinterFactoryOptions> = {
/**
* Unique identifier supplied at creation time.
*/
name: T['name'];
/**
* Options for this printer instance.
*/
options: T['options'];
/**
* Node-level dispatcher, converts a `SchemaNode` directly to `TOutput` using the `nodes` handlers.
* Always dispatches through the `nodes` map. Never calls the `print` override.
* Reach for it when you need the raw output (e.g. `ts.TypeNode`) without declaration wrapping.
*/
transform: (node: SchemaNode) => T['output'] | null;
/**
* Public printer. If the builder provides a root-level `print`, this calls that
* higher-level function (which may produce full declarations).
* Otherwise, falls back to the node-level dispatcher.
*/
print: (node: SchemaNode) => T['printOutput'] | null;
};
/**
* Builder function passed to `definePrinter`.
*
* It receives resolved options and returns:
* - `name`
* - `options`
* - `nodes` handlers
* - optional top-level `print` override
*
* @example
* ```ts
* const build = (options: {}) => ({ name: 'x' as const, options, nodes: {} })
* ```
*/
type PrinterBuilder<T extends PrinterFactoryOptions> = (options: T['options']) => {
name: T['name'];
/**
* Options to store on the printer.
*/
options: T['options'];
nodes: Partial<{ [K in SchemaType]: PrinterHandler<T['output'], T['options'], K> }>;
/**
* User-supplied handler overrides. An override wins over the matching `nodes` handler,
* and can call `this.base(node)` to reuse the handler it replaced. Pass overrides here
* instead of spreading them into `nodes`, otherwise `this.base` cannot find the original.
*/
overrides?: Partial<{ [K in SchemaType]: PrinterHandler<T['output'], T['options'], K> }>;
/**
* Optional root-level print override. When provided, becomes the public `printer.print`.
* Use `this.transform(node)` inside this function to dispatch to the node-level handlers (`nodes`),
* not the override itself, so recursion is safe.
*/
print?: (this: PrinterHandlerContext<T['output'], T['options']>, node: SchemaNode) => T['printOutput'] | null;
};
/**
* Creates a schema printer: a function that takes a `SchemaNode` and emits
* code in your target language. Each plugin that produces code from schemas
* (TypeScript types, Zod schemas, Faker factories) ships a printer built
* with this helper.
*
* The builder receives resolved options and returns:
*
* - `name` unique identifier for the printer.
* - `options` stored on the returned printer instance.
* - `nodes` map of `SchemaType` → handler. Handlers return the rendered
* output (a string, a TypeScript AST node, ...) for that schema type.
* - `overrides` (optional), user-supplied handlers that win over `nodes`.
* An override can call `this.base(node)` to reuse the handler it replaced.
* - `print` (optional), top-level override exposed as `printer.print`.
* Use `this.transform(node)` inside it to dispatch to `nodes` recursively.
*
* Without a `print` override, `printer.print` falls back to `printer.transform`
* (the node-level dispatcher).
*
* @example Tiny Zod printer
* ```ts
* import { createPrinter, type PrinterFactoryOptions } from '@kubb/ast'
*
* type PrinterZod = PrinterFactoryOptions<'zod', { strict?: boolean }, string>
*
* export const zodPrinter = createPrinter<PrinterZod>((options) => ({
* name: 'zod',
* options: { strict: options.strict ?? true },
* nodes: {
* string: () => 'z.string()',
* object(node) {
* const props = node.properties
* .map((p) => `${p.name}: ${this.transform(p.schema)}`)
* .join(', ')
* return `z.object({ ${props} })`
* },
* },
* }))
* ```
*/
declare function createPrinter<T extends PrinterFactoryOptions = PrinterFactoryOptions>(build: PrinterBuilder<T>): (options?: T['options']) => Printer<T>;
//#endregion
export { Dialect as a, createPrinter as i, PrinterFactoryOptions as n, SchemaDialect as o, PrinterPartial as r, defineDialect as s, Printer as t };
//# sourceMappingURL=types-CWF7DV0f.d.ts.map
Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
const require_visitor = require("./visitor-h6dEM3vR.cjs");
const require_refs = require("./refs-Bg3rmujP.cjs");
//#region ../../internals/utils/src/promise.ts
/**
* Wraps `factory` with a keyed cache backed by the provided store.
*
* Pass a `WeakMap` for object keys (results are GC-eligible when the key is
* collected) or a `Map` for primitive keys. For multi-argument functions,
* nest two `memoize` calls — the outer keyed by the first argument, the
* inner (created once per outer miss) keyed by the second.
*
* Because the cache is owned by the caller, it can be shared, inspected, or
* cleared independently of the memoized function.
*
* @example Single WeakMap key
* ```ts
* const cache = new WeakMap<SchemaNode, Set<string>>()
* const getRefs = memoize(cache, (node) => collectRefs(node))
* ```
*
* @example Single Map key (primitive)
* ```ts
* const cache = new Map<string, Resolver>()
* const getResolver = memoize(cache, (name) => buildResolver(name))
* ```
*
* @example Two-level (object + primitive)
* ```ts
* const outer = new WeakMap<Params[], Map<string, Params[]>>()
* const fn = memoize(outer, (params) => memoize(new Map(), (key) => transform(params, key)))
* fn(params)('camelcase')
* ```
*/
function memoize(store, factory) {
return (key) => {
if (store.has(key)) return store.get(key);
const value = factory(key);
store.set(key, value);
return value;
};
}
//#endregion
//#region ../../internals/utils/src/reserved.ts
/**
* JavaScript and Java reserved words.
* @link https://github.com/jonschlinkert/reserved/blob/master/index.js
*/
const reservedWords = /* @__PURE__ */ new Set([
"abstract",
"arguments",
"boolean",
"break",
"byte",
"case",
"catch",
"char",
"class",
"const",
"continue",
"debugger",
"default",
"delete",
"do",
"double",
"else",
"enum",
"eval",
"export",
"extends",
"false",
"final",
"finally",
"float",
"for",
"function",
"goto",
"if",
"implements",
"import",
"in",
"instanceof",
"int",
"interface",
"let",
"long",
"native",
"new",
"null",
"package",
"private",
"protected",
"public",
"return",
"short",
"static",
"super",
"switch",
"synchronized",
"this",
"throw",
"throws",
"transient",
"true",
"try",
"typeof",
"var",
"void",
"volatile",
"while",
"with",
"yield",
"Array",
"Date",
"hasOwnProperty",
"Infinity",
"isFinite",
"isNaN",
"isPrototypeOf",
"length",
"Math",
"name",
"NaN",
"Number",
"Object",
"prototype",
"String",
"toString",
"undefined",
"valueOf"
]);
/**
* Returns `true` when `name` is a syntactically valid JavaScript variable name.
*
* @example
* ```ts
* isValidVarName('status') // true
* isValidVarName('class') // false (reserved word)
* isValidVarName('42foo') // false (starts with digit)
* ```
*/
function isValidVarName(name) {
if (!name || reservedWords.has(name)) return false;
return isIdentifier(name);
}
/**
* Returns `true` when `name` is syntactically a valid identifier, ignoring reserved words.
*
* Reserved words and globals (`class`, `name`, `Date`, …) are valid as bare object-literal keys
* even though they are not valid variable names, so use this (not {@link isValidVarName}) when
* deciding whether an object key needs quoting.
*
* @example
* ```ts
* isIdentifier('name') // true
* isIdentifier('x-total')// false
* ```
*/
function isIdentifier(name) {
return /^[a-zA-Z_$][a-zA-Z0-9_$]*$/.test(name);
}
//#endregion
//#region ../../internals/utils/src/string.ts
/**
* Wraps a value in single quotes for emitting a single-quoted JavaScript string literal, escaping
* any backslash or single quote in the content.
*
* @example
* ```ts
* singleQuote('foo') // "'foo'"
* singleQuote("o'clock") // "'o\\'clock'"
* ```
*/
function singleQuote(value) {
if (value === void 0 || value === null) return "''";
return `'${String(value).replace(/\\/g, "\\\\").replace(/'/g, "\\'")}'`;
}
//#endregion
//#region src/utils/codegen.ts
/**
* Builds a JSDoc comment block from an array of lines. Returns `fallback` when there are no
* comments.
*
* @example
* ```ts
* buildJSDoc(['@type string', '@example hello'])
* // '/**\n * @type string\n * @example hello\n *\/\n '
* ```
*/
function buildJSDoc(comments, options = {}) {
const { indent = " * ", suffix = "\n ", fallback = " " } = options;
if (comments.length === 0) return fallback;
return `/**\n${comments.map((c) => `${indent}${c}`).join("\n")}\n */${suffix}`;
}
/**
* Indents every non-empty line of `text` by one indent level, leaving blank lines empty.
*/
function indentLines(text) {
if (!text) return "";
return text.split("\n").map((line) => line.trim() ? ` ${line}` : "").join("\n");
}
/**
* Renders an object key, quoting it with single quotes only when it is not a valid identifier.
* Reserved words and globals (`name`, `class`, …) are valid bare keys and stay unquoted.
*
* @example
* ```ts
* objectKey('name') // 'name'
* objectKey('x-total') // "'x-total'"
* ```
*/
function objectKey(name) {
return isIdentifier(name) ? name : singleQuote(name);
}
/**
* Assembles a multi-line object literal from already-rendered `entries`, indenting each entry one
* level and closing the brace at column zero. Entries that are themselves multi-line objects indent
* cumulatively. Each entry ends with a trailing comma to match the formatter's multi-line style.
*
* @example
* ```ts
* buildObject(['id: z.number()', 'name: z.string()'])
* // '{\n id: z.number(),\n name: z.string(),\n}'
* ```
*/
function buildObject(entries) {
if (entries.length === 0) return "{}";
return `{\n${entries.map((entry) => `${indentLines(entry)},`).join("\n")}\n}`;
}
/**
* Assembles a bracketed list (array by default) from already-rendered `items`. Keeps everything on
* one line when no item spans multiple lines, and otherwise puts each item on its own line, indented
* one level with a trailing comma and the closing bracket at column zero. Used for member lists such
* as `z.union([…])` and `z.array([…])`.
*
* @example
* ```ts
* buildList(['z.string()', 'z.number()'])
* // '[z.string(), z.number()]'
* ```
*/
function buildList(items, brackets = ["[", "]"]) {
const [open, close] = brackets;
if (items.length === 0) return `${open}${close}`;
if (!items.some((item) => item.includes("\n"))) return `${open}${items.join(", ")}${close}`;
return `${open}\n${items.map((item) => `${indentLines(item)},`).join("\n")}\n${close}`;
}
//#endregion
//#region src/utils/schemaMerge.ts
/**
* Merges a run of adjacent anonymous object members into one. Named or non-object members break the
* run and pass through unchanged. The merge follows member order, so callers control which members
* combine by where they place them in the sequence.
*
* @example
* ```ts
* const merged = [...mergeAdjacentObjectsLazy([objectA, objectB])]
* ```
*/
function* mergeAdjacentObjectsLazy(members) {
let acc;
for (const member of members) {
const objectMember = require_visitor.narrowSchema(member, "object");
if (objectMember && !objectMember.name && acc !== void 0) {
const accObject = require_visitor.narrowSchema(acc, "object");
if (accObject && !accObject.name) {
acc = require_visitor.createSchema({
...accObject,
properties: [...accObject.properties ?? [], ...objectMember.properties ?? []]
});
continue;
}
}
if (acc !== void 0) yield acc;
acc = member;
}
if (acc !== void 0) yield acc;
}
//#endregion
//#region src/utils/strings.ts
/**
* Strips a single matching pair of `"..."`, `'...'`, or `` `...` `` from both ends of `text`.
* Returns the string unchanged when no balanced quote pair is found.
*
* @example
* ```ts
* trimQuotes('"hello"') // 'hello'
* trimQuotes('hello') // 'hello'
* ```
*/
function trimQuotes(text) {
if (text.length >= 2) {
const first = text[0];
const last = text[text.length - 1];
if (first === "\"" && last === "\"" || first === "'" && last === "'" || first === "`" && last === "`") return text.slice(1, -1);
}
return text;
}
/**
* Serializes a primitive to a single-quoted string literal, stripping any surrounding quotes first.
*
* Escaping runs through `JSON.stringify`, then the result switches to single quotes so the generated
* code matches the repo style without a formatter.
*
* @example
* ```ts
* stringify('hello') // "'hello'"
* stringify('"hello"') // "'hello'"
* ```
*/
function stringify(value) {
if (value === void 0 || value === null) return "''";
return `'${JSON.stringify(trimQuotes(value.toString())).slice(1, -1).replace(/\\"/g, "\"").replace(/'/g, "\\'")}'`;
}
/**
* Escapes characters that are not allowed inside JS string literals, covering quotes, backslashes,
* and the Unicode line terminators U+2028 and U+2029.
*
* @see http://www.ecma-international.org/ecma-262/5.1/#sec-7.8.4
*
* @example
* ```ts
* jsStringEscape('say "hi"\nbye') // 'say \\"hi\\"\\nbye'
* ```
*/
function jsStringEscape(input) {
return `${input}`.replace(/["'\\\n\r\u2028\u2029]/g, (character) => {
switch (character) {
case "\"":
case "'":
case "\\": return `\\${character}`;
case "\n": return "\\n";
case "\r": return "\\r";
case "\u2028": return "\\u2028";
case "\u2029": return "\\u2029";
default: return "";
}
});
}
/**
* Converts a pattern string into a `new RegExp(...)` constructor call or a regex literal string.
* Inline flags expressed as a `^(?im)` prefix are extracted and applied to the resulting expression.
* Pass `null` as the second argument to emit a `/pattern/flags` literal instead.
*
* @example
* ```ts
* toRegExpString('^(?im)foo') // 'new RegExp("^foo", "im")'
* toRegExpString('^(?im)foo', null) // '/^foo/im'
* ```
*/
function toRegExpString(text, func = "RegExp") {
const raw = trimQuotes(text);
const match = raw.match(/^\^(\(\?([igmsuy]+)\))/i);
const replacementTarget = match?.[1] ?? "";
const matchedFlags = match?.[2];
const cleaned = raw.replace(/^\\?\//, "").replace(/\\?\/$/, "").replace(replacementTarget, "");
const { source, flags } = new RegExp(cleaned, matchedFlags);
if (func === null) return `/${source}/${flags}`;
return `new ${func}(${JSON.stringify(source)}${flags ? `, ${JSON.stringify(flags)}` : ""})`;
}
/**
* Renders a plain object as multi-line `key: value` source for embedding in generated code. Nested
* objects recurse with fixed indentation, so the result drops straight into an object literal
* without re-parsing.
*
* @example
* ```ts
* stringifyObject({ foo: 'bar', nested: { a: 1 } })
* // 'foo: bar,\nnested: {\n a: 1\n }'
* ```
*/
function stringifyObject(value) {
return Object.entries(value).map(([key, val]) => {
if (val !== null && typeof val === "object") return `${key}: {\n ${stringifyObject(val)}\n }`;
return `${key}: ${val}`;
}).filter(Boolean).join(",\n");
}
/**
* Renders a dotted path or string array as an optional-chaining accessor expression rooted at
* `accessor`. Returns `null` for an empty path.
*
* @example
* ```ts
* getNestedAccessor('pagination.next.id', 'lastPage')
* // "lastPage?.['pagination']?.['next']?.['id']"
* ```
*/
function getNestedAccessor(param, accessor) {
const parts = Array.isArray(param) ? param : param.split(".");
if (parts.length === 0 || parts.length === 1 && parts[0] === "") return null;
return `${accessor}?.['${`${parts.join("']?.['")}']`}`;
}
//#endregion
//#region src/utils/schemaGraph.ts
/**
* Memoized inner pass that walks a single node and returns the names of every schema it references.
*/
const collectSchemaRefs = memoize(/* @__PURE__ */ new WeakMap(), (node) => {
const refs = /* @__PURE__ */ new Set();
require_visitor.collect(node, { schema(child) {
if (child.type === "ref") {
const name = require_refs.resolveRefName(child);
if (name) refs.add(name);
}
} });
return refs;
});
/**
* Collects the names of every ref found anywhere inside a node's own subtree.
*
* Each ref contributes its name only, so the schema it points to is never traversed here. Pass `out`
* to accumulate names from several nodes into one set.
*
* @example Collect refs from a single schema
* ```ts
* const names = collectReferencedSchemaNames(petSchema)
* // Set { 'Category', 'Tag' }
* ```
*
* @example Accumulate refs from multiple schemas into one set
* ```ts
* const out = new Set<string>()
* for (const schema of schemas) {
* collectReferencedSchemaNames(schema, out)
* }
* ```
*/
function collectReferencedSchemaNames(node, out = /* @__PURE__ */ new Set()) {
if (!node) return out;
for (const name of collectSchemaRefs(node)) out.add(name);
return out;
}
/**
* Memoized two-level cache keyed first on the operations array, then on the schemas array.
*/
const collectUsedSchemaNamesMemo = memoize(/* @__PURE__ */ new WeakMap(), (ops) => memoize(/* @__PURE__ */ new WeakMap(), (schemas) => computeUsedSchemaNames(ops, schemas)));
function computeUsedSchemaNames(operations, schemas) {
const schemaMap = /* @__PURE__ */ new Map();
for (const schema of schemas) if (schema.name) schemaMap.set(schema.name, schema);
const result = /* @__PURE__ */ new Set();
function visitSchema(schema) {
const directRefs = collectReferencedSchemaNames(schema);
for (const name of directRefs) if (!result.has(name)) {
result.add(name);
const namedSchema = schemaMap.get(name);
if (namedSchema) visitSchema(namedSchema);
}
}
for (const op of operations) for (const schema of require_visitor.collectLazy(op, {
depth: "shallow",
schema: (node) => node
})) visitSchema(schema);
return result;
}
/**
* Collects the names of all top-level schemas transitively used by a set of operations.
*
* An operation uses a schema when its parameters, request body, or responses reference it, directly
* or through other named schemas. Once a name is added to the result it is not revisited, so
* reference cycles terminate.
*
* Pair it with `include` filters so schemas reachable only from excluded operations stay ungenerated.
*
* @example Only generate schemas referenced by included operations
* ```ts
* const includedOps = operations.filter((op) => resolver.resolveOptions(op, { options, include }) !== null)
* const allowed = collectUsedSchemaNames(includedOps, schemas)
*
* for (const schema of schemas) {
* if (schema.name && !allowed.has(schema.name)) continue
* // generate schema
* }
* ```
*/
function collectUsedSchemaNames(operations, schemas) {
return collectUsedSchemaNamesMemo(operations)(schemas);
}
const EMPTY_CIRCULAR_SET = /* @__PURE__ */ new Set();
const findCircularSchemasMemo = memoize(/* @__PURE__ */ new WeakMap(), (schemas) => {
const graph = /* @__PURE__ */ new Map();
for (const schema of schemas) {
if (!schema.name) continue;
graph.set(schema.name, collectReferencedSchemaNames(schema));
}
const circular = /* @__PURE__ */ new Set();
for (const start of graph.keys()) {
const visited = /* @__PURE__ */ new Set();
const stack = [...graph.get(start) ?? []];
while (stack.length > 0) {
const node = stack.pop();
if (node === start) {
circular.add(start);
break;
}
if (visited.has(node)) continue;
visited.add(node);
const next = graph.get(node);
if (next) for (const r of next) stack.push(r);
}
}
return circular;
});
/**
* Finds every schema that takes part in a circular dependency chain, including direct self-loops.
*
* Wrap the returned schema positions in a deferred construct (a lazy getter or `z.lazy(() => …)`) so
* the generated code does not recurse forever. Refs are followed by name only, so the walk stays
* linear in the size of the schema graph.
*
* @note Call this once on the full graph, then check individual schemas with `containsCircularRef()`.
*/
function findCircularSchemas(schemas) {
if (schemas.length === 0) return EMPTY_CIRCULAR_SET;
return findCircularSchemasMemo(schemas);
}
/**
* Returns `true` when a schema, or anything nested inside it, references a circular schema.
*
* Pass `excludeName` to skip refs to a specific schema, which helps when self-references are handled
* on their own. Pair it with `findCircularSchemas()` to decide where lazy wrappers go.
*
* @note Stops at the first matching circular ref.
*/
function containsCircularRef(node, { circularSchemas, excludeName }) {
if (!node || circularSchemas.size === 0) return false;
for (const _ of require_visitor.collectLazy(node, { schema(child) {
if (child.type !== "ref") return null;
const name = require_refs.resolveRefName(child);
return name && name !== excludeName && circularSchemas.has(name) ? true : null;
} })) return true;
return false;
}
//#endregion
//#region src/utils/schemaTraversal.ts
/**
* Maps each property of an object schema to its transformed output. Pairs every result with the
* original property so the printer keeps full control over modifiers, getters, and key syntax.
*
* @example
* ```ts
* const entries = mapSchemaProperties(node, (schema) => this.transform(schema))
* // entries: [{ name: 'id', property, output: 'z.number()' }, ...]
* ```
*/
function mapSchemaProperties(node, transform) {
return node.properties.map((property) => ({
name: property.name,
property,
output: transform(property.schema)
}));
}
/**
* Maps each member of a union or intersection schema to its transformed output, pairing every
* result with the original member.
*/
function mapSchemaMembers(node, transform) {
return (node.members ?? []).map((schema) => ({
schema,
output: transform(schema)
}));
}
/**
* Maps each item of an array or tuple schema to its transformed output, pairing every result with
* the original item.
*/
function mapSchemaItems(node, transform) {
return (node.items ?? []).map((schema) => ({
schema,
output: transform(schema)
}));
}
/**
* Emits a lazy getter for a circular-ref property position, `get name() { return body }`. The key
* is quoted only when it is not a valid identifier. Used by the string printers to defer evaluation
* of a recursive schema until first access.
*
* @example
* ```ts
* lazyGetter({ name: 'parent', body: 'z.lazy(() => Pet)' })
* // "get parent() { return z.lazy(() => Pet) }"
* ```
*/
function lazyGetter({ name, body }) {
return `get ${objectKey(name)}() { return ${body} }`;
}
//#endregion
exports.buildJSDoc = buildJSDoc;
exports.buildList = buildList;
exports.buildObject = buildObject;
exports.childName = require_refs.childName;
exports.collectUsedSchemaNames = collectUsedSchemaNames;
exports.containsCircularRef = containsCircularRef;
exports.enumPropName = require_refs.enumPropName;
exports.extractRefName = require_refs.extractRefName;
exports.extractStringsFromNodes = require_visitor.extractStringsFromNodes;
exports.findCircularSchemas = findCircularSchemas;
exports.getNestedAccessor = getNestedAccessor;
exports.isStringType = require_refs.isStringType;
exports.isValidVarName = isValidVarName;
exports.jsStringEscape = jsStringEscape;
exports.lazyGetter = lazyGetter;
exports.mapSchemaItems = mapSchemaItems;
exports.mapSchemaMembers = mapSchemaMembers;
exports.mapSchemaProperties = mapSchemaProperties;
exports.mergeAdjacentObjectsLazy = mergeAdjacentObjectsLazy;
exports.objectKey = objectKey;
exports.stringify = stringify;
exports.stringifyObject = stringifyObject;
exports.syncSchemaRef = require_refs.syncSchemaRef;
exports.toRegExpString = toRegExpString;
exports.trimQuotes = trimQuotes;
//# sourceMappingURL=utils.cjs.map
{"version":3,"file":"utils.cjs","names":["narrowSchema","createSchema","resolveRefName","collectLazy"],"sources":["../../../internals/utils/src/promise.ts","../../../internals/utils/src/reserved.ts","../../../internals/utils/src/string.ts","../src/utils/codegen.ts","../src/utils/schemaMerge.ts","../src/utils/strings.ts","../src/utils/schemaGraph.ts","../src/utils/schemaTraversal.ts"],"sourcesContent":["/** A value that may already be resolved or still pending.\n *\n * @example\n * ```ts\n * function load(id: string): PossiblePromise<string> {\n * return cache.get(id) ?? fetchRemote(id)\n * }\n * ```\n */\nexport type PossiblePromise<T> = Promise<T> | T\n\n/** Returns `true` when `result` is a thenable `Promise`.\n *\n * @example\n * ```ts\n * isPromise(Promise.resolve(1)) // true\n * isPromise(42) // false\n * ```\n */\nexport function isPromise<T>(result: PossiblePromise<T>): result is Promise<T> {\n return result !== null && result !== undefined && typeof (result as Record<string, unknown>)['then'] === 'function'\n}\n\ntype Store<TKey, TValue> = {\n has(key: TKey): boolean\n get(key: TKey): TValue | undefined\n set(key: TKey, value: TValue): unknown\n}\n\n/**\n * Wraps `factory` with a keyed cache backed by the provided store.\n *\n * Pass a `WeakMap` for object keys (results are GC-eligible when the key is\n * collected) or a `Map` for primitive keys. For multi-argument functions,\n * nest two `memoize` calls — the outer keyed by the first argument, the\n * inner (created once per outer miss) keyed by the second.\n *\n * Because the cache is owned by the caller, it can be shared, inspected, or\n * cleared independently of the memoized function.\n *\n * @example Single WeakMap key\n * ```ts\n * const cache = new WeakMap<SchemaNode, Set<string>>()\n * const getRefs = memoize(cache, (node) => collectRefs(node))\n * ```\n *\n * @example Single Map key (primitive)\n * ```ts\n * const cache = new Map<string, Resolver>()\n * const getResolver = memoize(cache, (name) => buildResolver(name))\n * ```\n *\n * @example Two-level (object + primitive)\n * ```ts\n * const outer = new WeakMap<Params[], Map<string, Params[]>>()\n * const fn = memoize(outer, (params) => memoize(new Map(), (key) => transform(params, key)))\n * fn(params)('camelcase')\n * ```\n */\nexport function memoize<TKey, TValue>(store: Store<TKey, TValue>, factory: (key: TKey) => TValue): (key: TKey) => TValue {\n return (key: TKey): TValue => {\n if (store.has(key)) return store.get(key)!\n const value = factory(key)\n store.set(key, value)\n return value\n }\n}\n\n/**\n * Container that switches between an eager `Array<T>` and a lazy `AsyncIterable<T>`.\n *\n * `Array<T>` by default. With `Stream` set to `true` it becomes `AsyncIterable<T>`, so large\n * collections can be produced lazily without holding every item in memory. Pairs with\n * {@link arrayToAsyncIterable}, which lifts a plain array into the streaming form.\n *\n * @example\n * ```ts\n * type Eager = Streamable<number> // Array<number>\n * type Lazy = Streamable<number, true> // AsyncIterable<number>\n * ```\n */\nexport type Streamable<T, Stream extends boolean = false> = Stream extends true ? AsyncIterable<T> : Array<T>\n\n/**\n * Wraps a plain array in a reusable `AsyncIterable`.\n * Each `[Symbol.asyncIterator]()` call returns a fresh generator so the\n * iterable can be consumed multiple times (e.g. once per plugin pre-scan).\n *\n * @example\n * ```ts\n * const stream = arrayToAsyncIterable([1, 2, 3])\n * for await (const n of stream) console.log(n) // 1, 2, 3\n * ```\n */\nexport function arrayToAsyncIterable<T>(arr: ReadonlyArray<T>): AsyncIterable<T> {\n return {\n [Symbol.asyncIterator]() {\n return (async function* () {\n yield* arr\n })()\n },\n }\n}\n","/**\n * JavaScript and Java reserved words.\n * @link https://github.com/jonschlinkert/reserved/blob/master/index.js\n */\nconst reservedWords = new Set([\n 'abstract',\n 'arguments',\n 'boolean',\n 'break',\n 'byte',\n 'case',\n 'catch',\n 'char',\n 'class',\n 'const',\n 'continue',\n 'debugger',\n 'default',\n 'delete',\n 'do',\n 'double',\n 'else',\n 'enum',\n 'eval',\n 'export',\n 'extends',\n 'false',\n 'final',\n 'finally',\n 'float',\n 'for',\n 'function',\n 'goto',\n 'if',\n 'implements',\n 'import',\n 'in',\n 'instanceof',\n 'int',\n 'interface',\n 'let',\n 'long',\n 'native',\n 'new',\n 'null',\n 'package',\n 'private',\n 'protected',\n 'public',\n 'return',\n 'short',\n 'static',\n 'super',\n 'switch',\n 'synchronized',\n 'this',\n 'throw',\n 'throws',\n 'transient',\n 'true',\n 'try',\n 'typeof',\n 'var',\n 'void',\n 'volatile',\n 'while',\n 'with',\n 'yield',\n 'Array',\n 'Date',\n 'hasOwnProperty',\n 'Infinity',\n 'isFinite',\n 'isNaN',\n 'isPrototypeOf',\n 'length',\n 'Math',\n 'name',\n 'NaN',\n 'Number',\n 'Object',\n 'prototype',\n 'String',\n 'toString',\n 'undefined',\n 'valueOf',\n] as const)\n\n/**\n * Prefixes `word` with `_` when it is a reserved JavaScript/Java identifier or starts with a digit.\n *\n * @example\n * ```ts\n * transformReservedWord('class') // '_class'\n * transformReservedWord('42foo') // '_42foo'\n * transformReservedWord('status') // 'status'\n * ```\n */\nexport function transformReservedWord(word: string): string {\n const firstChar = word.charCodeAt(0)\n if (word && (reservedWords.has(word as 'valueOf') || (firstChar >= 48 && firstChar <= 57))) {\n return `_${word}`\n }\n return word\n}\n\n/**\n * Returns `true` when `name` is a syntactically valid JavaScript variable name.\n *\n * @example\n * ```ts\n * isValidVarName('status') // true\n * isValidVarName('class') // false (reserved word)\n * isValidVarName('42foo') // false (starts with digit)\n * ```\n */\nexport function isValidVarName(name: string): boolean {\n if (!name || reservedWords.has(name as 'valueOf')) {\n return false\n }\n return isIdentifier(name)\n}\n\n/**\n * Returns `true` when `name` is syntactically a valid identifier, ignoring reserved words.\n *\n * Reserved words and globals (`class`, `name`, `Date`, …) are valid as bare object-literal keys\n * even though they are not valid variable names, so use this (not {@link isValidVarName}) when\n * deciding whether an object key needs quoting.\n *\n * @example\n * ```ts\n * isIdentifier('name') // true\n * isIdentifier('x-total')// false\n * ```\n */\nexport function isIdentifier(name: string): boolean {\n return /^[a-zA-Z_$][a-zA-Z0-9_$]*$/.test(name)\n}\n","/**\n * Wraps a value in single quotes for emitting a single-quoted JavaScript string literal, escaping\n * any backslash or single quote in the content.\n *\n * @example\n * ```ts\n * singleQuote('foo') // \"'foo'\"\n * singleQuote(\"o'clock\") // \"'o\\\\'clock'\"\n * ```\n */\nexport function singleQuote(value: string | number | boolean | undefined | null): string {\n if (value === undefined || value === null) return \"''\"\n const escaped = String(value).replace(/\\\\/g, '\\\\\\\\').replace(/'/g, \"\\\\'\")\n\n return `'${escaped}'`\n}\n","import { isIdentifier, singleQuote } from '@internals/utils'\nimport { INDENT } from '../constants.ts'\n\n/**\n * Builds a JSDoc comment block from an array of lines. Returns `fallback` when there are no\n * comments.\n *\n * @example\n * ```ts\n * buildJSDoc(['@type string', '@example hello'])\n * // '/**\\n * @type string\\n * @example hello\\n *\\/\\n '\n * ```\n */\nexport function buildJSDoc(\n comments: Array<string>,\n options: {\n /**\n * String used to indent each comment line.\n * @default ' * '\n */\n indent?: string\n /**\n * String appended after the closing tag.\n * @default '\\n '\n */\n suffix?: string\n /**\n * Returned as-is when `comments` is empty.\n * @default ' '\n */\n fallback?: string\n } = {},\n): string {\n const { indent = ' * ', suffix = '\\n ', fallback = ' ' } = options\n\n if (comments.length === 0) return fallback\n\n return `/**\\n${comments.map((c) => `${indent}${c}`).join('\\n')}\\n */${suffix}`\n}\n\n/**\n * Indents every non-empty line of `text` by one indent level, leaving blank lines empty.\n */\nfunction indentLines(text: string): string {\n if (!text) return ''\n return text\n .split('\\n')\n .map((line) => (line.trim() ? `${INDENT}${line}` : ''))\n .join('\\n')\n}\n\n/**\n * Renders an object key, quoting it with single quotes only when it is not a valid identifier.\n * Reserved words and globals (`name`, `class`, …) are valid bare keys and stay unquoted.\n *\n * @example\n * ```ts\n * objectKey('name') // 'name'\n * objectKey('x-total') // \"'x-total'\"\n * ```\n */\nexport function objectKey(name: string): string {\n return isIdentifier(name) ? name : singleQuote(name)\n}\n\n/**\n * Assembles a multi-line object literal from already-rendered `entries`, indenting each entry one\n * level and closing the brace at column zero. Entries that are themselves multi-line objects indent\n * cumulatively. Each entry ends with a trailing comma to match the formatter's multi-line style.\n *\n * @example\n * ```ts\n * buildObject(['id: z.number()', 'name: z.string()'])\n * // '{\\n id: z.number(),\\n name: z.string(),\\n}'\n * ```\n */\nexport function buildObject(entries: Array<string>): string {\n if (entries.length === 0) return '{}'\n const body = entries.map((entry) => `${indentLines(entry)},`).join('\\n')\n\n return `{\\n${body}\\n}`\n}\n\n/**\n * Assembles a bracketed list (array by default) from already-rendered `items`. Keeps everything on\n * one line when no item spans multiple lines, and otherwise puts each item on its own line, indented\n * one level with a trailing comma and the closing bracket at column zero. Used for member lists such\n * as `z.union([…])` and `z.array([…])`.\n *\n * @example\n * ```ts\n * buildList(['z.string()', 'z.number()'])\n * // '[z.string(), z.number()]'\n * ```\n */\nexport function buildList(items: Array<string>, brackets: [open: string, close: string] = ['[', ']']): string {\n const [open, close] = brackets\n if (items.length === 0) return `${open}${close}`\n if (!items.some((item) => item.includes('\\n'))) return `${open}${items.join(', ')}${close}`\n const body = items.map((item) => `${indentLines(item)},`).join('\\n')\n\n return `${open}\\n${body}\\n${close}`\n}\n","import { narrowSchema } from '../guards.ts'\nimport { createSchema, type SchemaNode } from '../nodes/schema.ts'\n\n/**\n * Merges a run of adjacent anonymous object members into one. Named or non-object members break the\n * run and pass through unchanged. The merge follows member order, so callers control which members\n * combine by where they place them in the sequence.\n *\n * @example\n * ```ts\n * const merged = [...mergeAdjacentObjectsLazy([objectA, objectB])]\n * ```\n */\nexport function* mergeAdjacentObjectsLazy(members: Iterable<SchemaNode>): Generator<SchemaNode, void, undefined> {\n let acc: SchemaNode | undefined\n\n for (const member of members) {\n const objectMember = narrowSchema(member, 'object')\n if (objectMember && !objectMember.name && acc !== undefined) {\n const accObject = narrowSchema(acc, 'object')\n if (accObject && !accObject.name) {\n acc = createSchema({\n ...accObject,\n properties: [...(accObject.properties ?? []), ...(objectMember.properties ?? [])],\n })\n continue\n }\n }\n if (acc !== undefined) yield acc\n acc = member\n }\n\n if (acc !== undefined) yield acc\n}\n","/**\n * Strips a single matching pair of `\"...\"`, `'...'`, or `` `...` `` from both ends of `text`.\n * Returns the string unchanged when no balanced quote pair is found.\n *\n * @example\n * ```ts\n * trimQuotes('\"hello\"') // 'hello'\n * trimQuotes('hello') // 'hello'\n * ```\n */\nexport function trimQuotes(text: string): string {\n if (text.length >= 2) {\n const first = text[0]\n const last = text[text.length - 1]\n if ((first === '\"' && last === '\"') || (first === \"'\" && last === \"'\") || (first === '`' && last === '`')) {\n return text.slice(1, -1)\n }\n }\n return text\n}\n\n/**\n * Serializes a primitive to a single-quoted string literal, stripping any surrounding quotes first.\n *\n * Escaping runs through `JSON.stringify`, then the result switches to single quotes so the generated\n * code matches the repo style without a formatter.\n *\n * @example\n * ```ts\n * stringify('hello') // \"'hello'\"\n * stringify('\"hello\"') // \"'hello'\"\n * ```\n */\nexport function stringify(value: string | number | boolean | undefined): string {\n if (value === undefined || value === null) return \"''\"\n const json = JSON.stringify(trimQuotes(value.toString()))\n const inner = json.slice(1, -1).replace(/\\\\\"/g, '\"').replace(/'/g, \"\\\\'\")\n return `'${inner}'`\n}\n\n/**\n * Escapes characters that are not allowed inside JS string literals, covering quotes, backslashes,\n * and the Unicode line terminators U+2028 and U+2029.\n *\n * @see http://www.ecma-international.org/ecma-262/5.1/#sec-7.8.4\n *\n * @example\n * ```ts\n * jsStringEscape('say \"hi\"\\nbye') // 'say \\\\\"hi\\\\\"\\\\nbye'\n * ```\n */\nexport function jsStringEscape(input: unknown): string {\n return `${input}`.replace(/[\"'\\\\\\n\\r\\u2028\\u2029]/g, (character) => {\n switch (character) {\n case '\"':\n case \"'\":\n case '\\\\':\n return `\\\\${character}`\n case '\\n':\n return '\\\\n'\n case '\\r':\n return '\\\\r'\n case '\\u2028':\n return '\\\\u2028'\n case '\\u2029':\n return '\\\\u2029'\n default:\n return ''\n }\n })\n}\n\n/**\n * Converts a pattern string into a `new RegExp(...)` constructor call or a regex literal string.\n * Inline flags expressed as a `^(?im)` prefix are extracted and applied to the resulting expression.\n * Pass `null` as the second argument to emit a `/pattern/flags` literal instead.\n *\n * @example\n * ```ts\n * toRegExpString('^(?im)foo') // 'new RegExp(\"^foo\", \"im\")'\n * toRegExpString('^(?im)foo', null) // '/^foo/im'\n * ```\n */\nexport function toRegExpString(text: string, func: string | null = 'RegExp'): string {\n const raw = trimQuotes(text)\n\n const match = raw.match(/^\\^(\\(\\?([igmsuy]+)\\))/i)\n const replacementTarget = match?.[1] ?? ''\n const matchedFlags = match?.[2]\n const cleaned = raw\n .replace(/^\\\\?\\//, '')\n .replace(/\\\\?\\/$/, '')\n .replace(replacementTarget, '')\n\n const { source, flags } = new RegExp(cleaned, matchedFlags)\n\n if (func === null) return `/${source}/${flags}`\n\n return `new ${func}(${JSON.stringify(source)}${flags ? `, ${JSON.stringify(flags)}` : ''})`\n}\n\n/**\n * Renders a plain object as multi-line `key: value` source for embedding in generated code. Nested\n * objects recurse with fixed indentation, so the result drops straight into an object literal\n * without re-parsing.\n *\n * @example\n * ```ts\n * stringifyObject({ foo: 'bar', nested: { a: 1 } })\n * // 'foo: bar,\\nnested: {\\n a: 1\\n }'\n * ```\n */\nexport function stringifyObject(value: Record<string, unknown>): string {\n const items = Object.entries(value)\n .map(([key, val]) => {\n if (val !== null && typeof val === 'object') {\n return `${key}: {\\n ${stringifyObject(val as Record<string, unknown>)}\\n }`\n }\n return `${key}: ${val}`\n })\n .filter(Boolean)\n return items.join(',\\n')\n}\n\n/**\n * Renders a dotted path or string array as an optional-chaining accessor expression rooted at\n * `accessor`. Returns `null` for an empty path.\n *\n * @example\n * ```ts\n * getNestedAccessor('pagination.next.id', 'lastPage')\n * // \"lastPage?.['pagination']?.['next']?.['id']\"\n * ```\n */\nexport function getNestedAccessor(param: string | Array<string>, accessor: string): string | null {\n const parts = Array.isArray(param) ? param : param.split('.')\n if (parts.length === 0 || (parts.length === 1 && parts[0] === '')) return null\n return `${accessor}?.['${`${parts.join(\"']?.['\")}']`}`\n}\n","import { memoize } from '@internals/utils'\nimport type { OperationNode, SchemaNode } from '../nodes/index.ts'\nimport { collect, collectLazy } from '../visitor.ts'\nimport { resolveRefName } from './refs.ts'\n\n/**\n * Memoized inner pass that walks a single node and returns the names of every schema it references.\n */\nconst collectSchemaRefs = memoize(new WeakMap<SchemaNode, ReadonlySet<string>>(), (node: SchemaNode): ReadonlySet<string> => {\n const refs = new Set<string>()\n collect<void>(node, {\n schema(child) {\n if (child.type === 'ref') {\n const name = resolveRefName(child)\n if (name) refs.add(name)\n }\n },\n })\n return refs\n})\n\n/**\n * Collects the names of every ref found anywhere inside a node's own subtree.\n *\n * Each ref contributes its name only, so the schema it points to is never traversed here. Pass `out`\n * to accumulate names from several nodes into one set.\n *\n * @example Collect refs from a single schema\n * ```ts\n * const names = collectReferencedSchemaNames(petSchema)\n * // Set { 'Category', 'Tag' }\n * ```\n *\n * @example Accumulate refs from multiple schemas into one set\n * ```ts\n * const out = new Set<string>()\n * for (const schema of schemas) {\n * collectReferencedSchemaNames(schema, out)\n * }\n * ```\n */\nexport function collectReferencedSchemaNames(node: SchemaNode | undefined, out: Set<string> = new Set()): Set<string> {\n if (!node) return out\n for (const name of collectSchemaRefs(node)) out.add(name)\n return out\n}\n\n/**\n * Memoized two-level cache keyed first on the operations array, then on the schemas array.\n */\nconst collectUsedSchemaNamesMemo = memoize(new WeakMap<ReadonlyArray<OperationNode>, (schemas: ReadonlyArray<SchemaNode>) => Set<string>>(), (ops) =>\n memoize(new WeakMap<ReadonlyArray<SchemaNode>, Set<string>>(), (schemas) => computeUsedSchemaNames(ops, schemas)),\n)\n\nfunction computeUsedSchemaNames(operations: ReadonlyArray<OperationNode>, schemas: ReadonlyArray<SchemaNode>): Set<string> {\n const schemaMap = new Map<string, SchemaNode>()\n for (const schema of schemas) {\n if (schema.name) schemaMap.set(schema.name, schema)\n }\n\n const result = new Set<string>()\n\n function visitSchema(schema: SchemaNode): void {\n const directRefs = collectReferencedSchemaNames(schema)\n for (const name of directRefs) {\n if (!result.has(name)) {\n result.add(name)\n const namedSchema = schemaMap.get(name)\n if (namedSchema) visitSchema(namedSchema)\n }\n }\n }\n\n for (const op of operations) {\n for (const schema of collectLazy<SchemaNode>(op, { depth: 'shallow', schema: (node) => node })) {\n visitSchema(schema)\n }\n }\n\n return result\n}\n\n/**\n * Collects the names of all top-level schemas transitively used by a set of operations.\n *\n * An operation uses a schema when its parameters, request body, or responses reference it, directly\n * or through other named schemas. Once a name is added to the result it is not revisited, so\n * reference cycles terminate.\n *\n * Pair it with `include` filters so schemas reachable only from excluded operations stay ungenerated.\n *\n * @example Only generate schemas referenced by included operations\n * ```ts\n * const includedOps = operations.filter((op) => resolver.resolveOptions(op, { options, include }) !== null)\n * const allowed = collectUsedSchemaNames(includedOps, schemas)\n *\n * for (const schema of schemas) {\n * if (schema.name && !allowed.has(schema.name)) continue\n * // generate schema\n * }\n * ```\n */\nexport function collectUsedSchemaNames(operations: ReadonlyArray<OperationNode>, schemas: ReadonlyArray<SchemaNode>): Set<string> {\n return collectUsedSchemaNamesMemo(operations)(schemas)\n}\n\nconst EMPTY_CIRCULAR_SET = new Set<string>()\n\nconst findCircularSchemasMemo = memoize(new WeakMap<ReadonlyArray<SchemaNode>, Set<string>>(), (schemas: ReadonlyArray<SchemaNode>): Set<string> => {\n const graph = new Map<string, Set<string>>()\n\n for (const schema of schemas) {\n if (!schema.name) continue\n graph.set(schema.name, collectReferencedSchemaNames(schema))\n }\n\n const circular = new Set<string>()\n for (const start of graph.keys()) {\n const visited = new Set<string>()\n const stack: Array<string> = [...(graph.get(start) ?? [])]\n while (stack.length > 0) {\n const node = stack.pop()!\n if (node === start) {\n circular.add(start)\n break\n }\n if (visited.has(node)) continue\n visited.add(node)\n\n const next = graph.get(node)\n if (next) for (const r of next) stack.push(r)\n }\n }\n\n return circular\n})\n\n/**\n * Finds every schema that takes part in a circular dependency chain, including direct self-loops.\n *\n * Wrap the returned schema positions in a deferred construct (a lazy getter or `z.lazy(() => …)`) so\n * the generated code does not recurse forever. Refs are followed by name only, so the walk stays\n * linear in the size of the schema graph.\n *\n * @note Call this once on the full graph, then check individual schemas with `containsCircularRef()`.\n */\nexport function findCircularSchemas(schemas: ReadonlyArray<SchemaNode>): Set<string> {\n if (schemas.length === 0) return EMPTY_CIRCULAR_SET\n return findCircularSchemasMemo(schemas)\n}\n\n/**\n * Returns `true` when a schema, or anything nested inside it, references a circular schema.\n *\n * Pass `excludeName` to skip refs to a specific schema, which helps when self-references are handled\n * on their own. Pair it with `findCircularSchemas()` to decide where lazy wrappers go.\n *\n * @note Stops at the first matching circular ref.\n */\nexport function containsCircularRef(\n node: SchemaNode | undefined,\n { circularSchemas, excludeName }: { circularSchemas: ReadonlySet<string>; excludeName?: string },\n): boolean {\n if (!node || circularSchemas.size === 0) return false\n\n for (const _ of collectLazy<true>(node, {\n schema(child) {\n if (child.type !== 'ref') return null\n const name = resolveRefName(child)\n return name && name !== excludeName && circularSchemas.has(name) ? true : null\n },\n })) {\n return true\n }\n\n return false\n}\n","import type { ArraySchemaNode, IntersectionSchemaNode, ObjectSchemaNode, PropertyNode, SchemaNode, UnionSchemaNode } from '../nodes/index.ts'\nimport { objectKey } from './codegen.ts'\n\n/**\n * Converts a child schema to printer output. Plugins instantiate it with their own output type:\n * `string` for the zod and faker printers, `ts.TypeNode` for the TypeScript printer. A printer's\n * `this.transform` fits directly, so its `null` for an empty result carries through to `output`.\n */\nexport type SchemaTransform<TOutput> = (schema: SchemaNode) => TOutput\n\n/**\n * A union or intersection member, or an array or tuple item, paired with its transformed output.\n */\nexport type MappedSchema<TOutput> = {\n /**\n * The original child schema, kept so the printer can read its metadata for leaf formatting.\n */\n schema: SchemaNode\n /**\n * The child schema after being run through the transform.\n */\n output: TOutput\n}\n\n/**\n * An object property paired with its transformed output.\n */\nexport type MappedProperty<TOutput> = {\n /**\n * The property name as written on the schema, before any identifier quoting.\n */\n name: string\n /**\n * The original property node, kept so the printer can read `required`, `schema`, and metadata.\n */\n property: PropertyNode\n /**\n * The property schema after being run through the transform.\n */\n output: TOutput\n}\n\n/**\n * Maps each property of an object schema to its transformed output. Pairs every result with the\n * original property so the printer keeps full control over modifiers, getters, and key syntax.\n *\n * @example\n * ```ts\n * const entries = mapSchemaProperties(node, (schema) => this.transform(schema))\n * // entries: [{ name: 'id', property, output: 'z.number()' }, ...]\n * ```\n */\nexport function mapSchemaProperties<TOutput>(node: ObjectSchemaNode, transform: SchemaTransform<TOutput>): Array<MappedProperty<TOutput>> {\n return node.properties.map((property) => ({ name: property.name, property, output: transform(property.schema) }))\n}\n\n/**\n * Maps each member of a union or intersection schema to its transformed output, pairing every\n * result with the original member.\n */\nexport function mapSchemaMembers<TOutput>(node: UnionSchemaNode | IntersectionSchemaNode, transform: SchemaTransform<TOutput>): Array<MappedSchema<TOutput>> {\n return (node.members ?? []).map((schema) => ({ schema, output: transform(schema) }))\n}\n\n/**\n * Maps each item of an array or tuple schema to its transformed output, pairing every result with\n * the original item.\n */\nexport function mapSchemaItems<TOutput>(node: ArraySchemaNode, transform: SchemaTransform<TOutput>): Array<MappedSchema<TOutput>> {\n return (node.items ?? []).map((schema) => ({ schema, output: transform(schema) }))\n}\n\n/**\n * Emits a lazy getter for a circular-ref property position, `get name() { return body }`. The key\n * is quoted only when it is not a valid identifier. Used by the string printers to defer evaluation\n * of a recursive schema until first access.\n *\n * @example\n * ```ts\n * lazyGetter({ name: 'parent', body: 'z.lazy(() => Pet)' })\n * // \"get parent() { return z.lazy(() => Pet) }\"\n * ```\n */\nexport function lazyGetter({ name, body }: { name: string; body: string }): string {\n return `get ${objectKey(name)}() { return ${body} }`\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA2DA,SAAgB,QAAsB,OAA4B,SAAuD;CACvH,QAAQ,QAAsB;EAC5B,IAAI,MAAM,IAAI,GAAG,GAAG,OAAO,MAAM,IAAI,GAAG;EACxC,MAAM,QAAQ,QAAQ,GAAG;EACzB,MAAM,IAAI,KAAK,KAAK;EACpB,OAAO;CACT;AACF;;;;;;;AC9DA,MAAM,gCAAgB,IAAI,IAAI;CAC5B;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AACF,CAAU;;;;;;;;;;;AA8BV,SAAgB,eAAe,MAAuB;CACpD,IAAI,CAAC,QAAQ,cAAc,IAAI,IAAiB,GAC9C,OAAO;CAET,OAAO,aAAa,IAAI;AAC1B;;;;;;;;;;;;;;AAeA,SAAgB,aAAa,MAAuB;CAClD,OAAO,6BAA6B,KAAK,IAAI;AAC/C;;;;;;;;;;;;;AChIA,SAAgB,YAAY,OAA6D;CACvF,IAAI,UAAU,KAAA,KAAa,UAAU,MAAM,OAAO;CAGlD,OAAO,IAFS,OAAO,KAAK,CAAC,CAAC,QAAQ,OAAO,MAAM,CAAC,CAAC,QAAQ,MAAM,KAElD,EAAE;AACrB;;;;;;;;;;;;;ACFA,SAAgB,WACd,UACA,UAgBI,CAAC,GACG;CACR,MAAM,EAAE,SAAS,SAAS,SAAS,QAAQ,WAAW,SAAS;CAE/D,IAAI,SAAS,WAAW,GAAG,OAAO;CAElC,OAAO,QAAQ,SAAS,KAAK,MAAM,GAAG,SAAS,GAAG,CAAC,CAAC,KAAK,IAAI,EAAE,SAAS;AAC1E;;;;AAKA,SAAS,YAAY,MAAsB;CACzC,IAAI,CAAC,MAAM,OAAO;CAClB,OAAO,KACJ,MAAM,IAAI,CAAC,CACX,KAAK,SAAU,KAAK,KAAK,IAAI,KAAY,SAAS,EAAG,CAAC,CACtD,KAAK,IAAI;AACd;;;;;;;;;;;AAYA,SAAgB,UAAU,MAAsB;CAC9C,OAAO,aAAa,IAAI,IAAI,OAAO,YAAY,IAAI;AACrD;;;;;;;;;;;;AAaA,SAAgB,YAAY,SAAgC;CAC1D,IAAI,QAAQ,WAAW,GAAG,OAAO;CAGjC,OAAO,MAFM,QAAQ,KAAK,UAAU,GAAG,YAAY,KAAK,EAAE,EAAE,CAAC,CAAC,KAAK,IAEnD,EAAE;AACpB;;;;;;;;;;;;;AAcA,SAAgB,UAAU,OAAsB,WAA0C,CAAC,KAAK,GAAG,GAAW;CAC5G,MAAM,CAAC,MAAM,SAAS;CACtB,IAAI,MAAM,WAAW,GAAG,OAAO,GAAG,OAAO;CACzC,IAAI,CAAC,MAAM,MAAM,SAAS,KAAK,SAAS,IAAI,CAAC,GAAG,OAAO,GAAG,OAAO,MAAM,KAAK,IAAI,IAAI;CAGpF,OAAO,GAAG,KAAK,IAFF,MAAM,KAAK,SAAS,GAAG,YAAY,IAAI,EAAE,EAAE,CAAC,CAAC,KAAK,IAEzC,EAAE,IAAI;AAC9B;;;;;;;;;;;;;ACzFA,UAAiB,yBAAyB,SAAuE;CAC/G,IAAI;CAEJ,KAAK,MAAM,UAAU,SAAS;EAC5B,MAAM,eAAeA,gBAAAA,aAAa,QAAQ,QAAQ;EAClD,IAAI,gBAAgB,CAAC,aAAa,QAAQ,QAAQ,KAAA,GAAW;GAC3D,MAAM,YAAYA,gBAAAA,aAAa,KAAK,QAAQ;GAC5C,IAAI,aAAa,CAAC,UAAU,MAAM;IAChC,MAAMC,gBAAAA,aAAa;KACjB,GAAG;KACH,YAAY,CAAC,GAAI,UAAU,cAAc,CAAC,GAAI,GAAI,aAAa,cAAc,CAAC,CAAE;IAClF,CAAC;IACD;GACF;EACF;EACA,IAAI,QAAQ,KAAA,GAAW,MAAM;EAC7B,MAAM;CACR;CAEA,IAAI,QAAQ,KAAA,GAAW,MAAM;AAC/B;;;;;;;;;;;;;ACvBA,SAAgB,WAAW,MAAsB;CAC/C,IAAI,KAAK,UAAU,GAAG;EACpB,MAAM,QAAQ,KAAK;EACnB,MAAM,OAAO,KAAK,KAAK,SAAS;EAChC,IAAK,UAAU,QAAO,SAAS,QAAS,UAAU,OAAO,SAAS,OAAS,UAAU,OAAO,SAAS,KACnG,OAAO,KAAK,MAAM,GAAG,EAAE;CAE3B;CACA,OAAO;AACT;;;;;;;;;;;;;AAcA,SAAgB,UAAU,OAAsD;CAC9E,IAAI,UAAU,KAAA,KAAa,UAAU,MAAM,OAAO;CAGlD,OAAO,IAFM,KAAK,UAAU,WAAW,MAAM,SAAS,CAAC,CACtC,CAAC,CAAC,MAAM,GAAG,EAAE,CAAC,CAAC,QAAQ,QAAQ,IAAG,CAAC,CAAC,QAAQ,MAAM,KACpD,EAAE;AACnB;;;;;;;;;;;;AAaA,SAAgB,eAAe,OAAwB;CACrD,OAAO,GAAG,QAAQ,QAAQ,4BAA4B,cAAc;EAClE,QAAQ,WAAR;GACE,KAAK;GACL,KAAK;GACL,KAAK,MACH,OAAO,KAAK;GACd,KAAK,MACH,OAAO;GACT,KAAK,MACH,OAAO;GACT,KAAK,UACH,OAAO;GACT,KAAK,UACH,OAAO;GACT,SACE,OAAO;EACX;CACF,CAAC;AACH;;;;;;;;;;;;AAaA,SAAgB,eAAe,MAAc,OAAsB,UAAkB;CACnF,MAAM,MAAM,WAAW,IAAI;CAE3B,MAAM,QAAQ,IAAI,MAAM,yBAAyB;CACjD,MAAM,oBAAoB,QAAQ,MAAM;CACxC,MAAM,eAAe,QAAQ;CAC7B,MAAM,UAAU,IACb,QAAQ,UAAU,EAAE,CAAC,CACrB,QAAQ,UAAU,EAAE,CAAC,CACrB,QAAQ,mBAAmB,EAAE;CAEhC,MAAM,EAAE,QAAQ,UAAU,IAAI,OAAO,SAAS,YAAY;CAE1D,IAAI,SAAS,MAAM,OAAO,IAAI,OAAO,GAAG;CAExC,OAAO,OAAO,KAAK,GAAG,KAAK,UAAU,MAAM,IAAI,QAAQ,KAAK,KAAK,UAAU,KAAK,MAAM,GAAG;AAC3F;;;;;;;;;;;;AAaA,SAAgB,gBAAgB,OAAwC;CAStE,OARc,OAAO,QAAQ,KAAK,CAAC,CAChC,KAAK,CAAC,KAAK,SAAS;EACnB,IAAI,QAAQ,QAAQ,OAAO,QAAQ,UACjC,OAAO,GAAG,IAAI,eAAe,gBAAgB,GAA8B,EAAE;EAE/E,OAAO,GAAG,IAAI,IAAI;CACpB,CAAC,CAAC,CACD,OAAO,OACC,CAAC,CAAC,KAAK,KAAK;AACzB;;;;;;;;;;;AAYA,SAAgB,kBAAkB,OAA+B,UAAiC;CAChG,MAAM,QAAQ,MAAM,QAAQ,KAAK,IAAI,QAAQ,MAAM,MAAM,GAAG;CAC5D,IAAI,MAAM,WAAW,KAAM,MAAM,WAAW,KAAK,MAAM,OAAO,IAAK,OAAO;CAC1E,OAAO,GAAG,SAAS,MAAM,GAAG,MAAM,KAAK,QAAQ,EAAE;AACnD;;;;;;AClIA,MAAM,oBAAoB,wBAAQ,IAAI,QAAyC,IAAI,SAA0C;CAC3H,MAAM,uBAAO,IAAI,IAAY;CAC7B,gBAAA,QAAc,MAAM,EAClB,OAAO,OAAO;EACZ,IAAI,MAAM,SAAS,OAAO;GACxB,MAAM,OAAOC,aAAAA,eAAe,KAAK;GACjC,IAAI,MAAM,KAAK,IAAI,IAAI;EACzB;CACF,EACF,CAAC;CACD,OAAO;AACT,CAAC;;;;;;;;;;;;;;;;;;;;;AAsBD,SAAgB,6BAA6B,MAA8B,sBAAmB,IAAI,IAAI,GAAgB;CACpH,IAAI,CAAC,MAAM,OAAO;CAClB,KAAK,MAAM,QAAQ,kBAAkB,IAAI,GAAG,IAAI,IAAI,IAAI;CACxD,OAAO;AACT;;;;AAKA,MAAM,6BAA6B,wBAAQ,IAAI,QAA2F,IAAI,QAC5I,wBAAQ,IAAI,QAAgD,IAAI,YAAY,uBAAuB,KAAK,OAAO,CAAC,CAClH;AAEA,SAAS,uBAAuB,YAA0C,SAAiD;CACzH,MAAM,4BAAY,IAAI,IAAwB;CAC9C,KAAK,MAAM,UAAU,SACnB,IAAI,OAAO,MAAM,UAAU,IAAI,OAAO,MAAM,MAAM;CAGpD,MAAM,yBAAS,IAAI,IAAY;CAE/B,SAAS,YAAY,QAA0B;EAC7C,MAAM,aAAa,6BAA6B,MAAM;EACtD,KAAK,MAAM,QAAQ,YACjB,IAAI,CAAC,OAAO,IAAI,IAAI,GAAG;GACrB,OAAO,IAAI,IAAI;GACf,MAAM,cAAc,UAAU,IAAI,IAAI;GACtC,IAAI,aAAa,YAAY,WAAW;EAC1C;CAEJ;CAEA,KAAK,MAAM,MAAM,YACf,KAAK,MAAM,UAAUC,gBAAAA,YAAwB,IAAI;EAAE,OAAO;EAAW,SAAS,SAAS;CAAK,CAAC,GAC3F,YAAY,MAAM;CAItB,OAAO;AACT;;;;;;;;;;;;;;;;;;;;;AAsBA,SAAgB,uBAAuB,YAA0C,SAAiD;CAChI,OAAO,2BAA2B,UAAU,CAAC,CAAC,OAAO;AACvD;AAEA,MAAM,qCAAqB,IAAI,IAAY;AAE3C,MAAM,0BAA0B,wBAAQ,IAAI,QAAgD,IAAI,YAAoD;CAClJ,MAAM,wBAAQ,IAAI,IAAyB;CAE3C,KAAK,MAAM,UAAU,SAAS;EAC5B,IAAI,CAAC,OAAO,MAAM;EAClB,MAAM,IAAI,OAAO,MAAM,6BAA6B,MAAM,CAAC;CAC7D;CAEA,MAAM,2BAAW,IAAI,IAAY;CACjC,KAAK,MAAM,SAAS,MAAM,KAAK,GAAG;EAChC,MAAM,0BAAU,IAAI,IAAY;EAChC,MAAM,QAAuB,CAAC,GAAI,MAAM,IAAI,KAAK,KAAK,CAAC,CAAE;EACzD,OAAO,MAAM,SAAS,GAAG;GACvB,MAAM,OAAO,MAAM,IAAI;GACvB,IAAI,SAAS,OAAO;IAClB,SAAS,IAAI,KAAK;IAClB;GACF;GACA,IAAI,QAAQ,IAAI,IAAI,GAAG;GACvB,QAAQ,IAAI,IAAI;GAEhB,MAAM,OAAO,MAAM,IAAI,IAAI;GAC3B,IAAI,MAAM,KAAK,MAAM,KAAK,MAAM,MAAM,KAAK,CAAC;EAC9C;CACF;CAEA,OAAO;AACT,CAAC;;;;;;;;;;AAWD,SAAgB,oBAAoB,SAAiD;CACnF,IAAI,QAAQ,WAAW,GAAG,OAAO;CACjC,OAAO,wBAAwB,OAAO;AACxC;;;;;;;;;AAUA,SAAgB,oBACd,MACA,EAAE,iBAAiB,eACV;CACT,IAAI,CAAC,QAAQ,gBAAgB,SAAS,GAAG,OAAO;CAEhD,KAAK,MAAM,KAAKA,gBAAAA,YAAkB,MAAM,EACtC,OAAO,OAAO;EACZ,IAAI,MAAM,SAAS,OAAO,OAAO;EACjC,MAAM,OAAOD,aAAAA,eAAe,KAAK;EACjC,OAAO,QAAQ,SAAS,eAAe,gBAAgB,IAAI,IAAI,IAAI,OAAO;CAC5E,EACF,CAAC,GACC,OAAO;CAGT,OAAO;AACT;;;;;;;;;;;;;AC5HA,SAAgB,oBAA6B,MAAwB,WAAqE;CACxI,OAAO,KAAK,WAAW,KAAK,cAAc;EAAE,MAAM,SAAS;EAAM;EAAU,QAAQ,UAAU,SAAS,MAAM;CAAE,EAAE;AAClH;;;;;AAMA,SAAgB,iBAA0B,MAAgD,WAAmE;CAC3J,QAAQ,KAAK,WAAW,CAAC,EAAA,CAAG,KAAK,YAAY;EAAE;EAAQ,QAAQ,UAAU,MAAM;CAAE,EAAE;AACrF;;;;;AAMA,SAAgB,eAAwB,MAAuB,WAAmE;CAChI,QAAQ,KAAK,SAAS,CAAC,EAAA,CAAG,KAAK,YAAY;EAAE;EAAQ,QAAQ,UAAU,MAAM;CAAE,EAAE;AACnF;;;;;;;;;;;;AAaA,SAAgB,WAAW,EAAE,MAAM,QAAgD;CACjF,OAAO,OAAO,UAAU,IAAI,EAAE,cAAc,KAAK;AACnD"}
import { n as __name } from "./rolldown-runtime-CNktS9qV.js";
import { U as ArraySchemaNode, Y as ObjectSchemaNode, _t as CodeNode, at as UnionSchemaNode, et as SchemaNode, f as OperationNode, lt as PropertyNode, q as IntersectionSchemaNode } from "./index-Cu2zmNxv.js";
//#region ../../internals/utils/src/reserved.d.ts
/**
* Returns `true` when `name` is a syntactically valid JavaScript variable name.
*
* @example
* ```ts
* isValidVarName('status') // true
* isValidVarName('class') // false (reserved word)
* isValidVarName('42foo') // false (starts with digit)
* ```
*/
declare function isValidVarName(name: string): boolean;
//#endregion
//#region src/utils/codegen.d.ts
/**
* Builds a JSDoc comment block from an array of lines. Returns `fallback` when there are no
* comments.
*
* @example
* ```ts
* buildJSDoc(['@type string', '@example hello'])
* // '/**\n * @type string\n * @example hello\n *\/\n '
* ```
*/
declare function buildJSDoc(comments: Array<string>, options?: {
/**
* String used to indent each comment line.
* @default ' * '
*/
indent?: string;
/**
* String appended after the closing tag.
* @default '\n '
*/
suffix?: string;
/**
* Returned as-is when `comments` is empty.
* @default ' '
*/
fallback?: string;
}): string;
/**
* Renders an object key, quoting it with single quotes only when it is not a valid identifier.
* Reserved words and globals (`name`, `class`, …) are valid bare keys and stay unquoted.
*
* @example
* ```ts
* objectKey('name') // 'name'
* objectKey('x-total') // "'x-total'"
* ```
*/
declare function objectKey(name: string): string;
/**
* Assembles a multi-line object literal from already-rendered `entries`, indenting each entry one
* level and closing the brace at column zero. Entries that are themselves multi-line objects indent
* cumulatively. Each entry ends with a trailing comma to match the formatter's multi-line style.
*
* @example
* ```ts
* buildObject(['id: z.number()', 'name: z.string()'])
* // '{\n id: z.number(),\n name: z.string(),\n}'
* ```
*/
declare function buildObject(entries: Array<string>): string;
/**
* Assembles a bracketed list (array by default) from already-rendered `items`. Keeps everything on
* one line when no item spans multiple lines, and otherwise puts each item on its own line, indented
* one level with a trailing comma and the closing bracket at column zero. Used for member lists such
* as `z.union([…])` and `z.array([…])`.
*
* @example
* ```ts
* buildList(['z.string()', 'z.number()'])
* // '[z.string(), z.number()]'
* ```
*/
declare function buildList(items: Array<string>, brackets?: [open: string, close: string]): string;
//#endregion
//#region src/utils/extractStringsFromNodes.d.ts
/**
* Extracts all string content from a `CodeNode` tree recursively.
*
* Collects text node values, identifier references in string fields (`params`, `generics`, `returnType`, `type`),
* and nested node content. Used to build the full source string for import filtering.
*/
declare function extractStringsFromNodes(nodes: Array<CodeNode> | undefined): string;
//#endregion
//#region src/utils/refs.d.ts
/**
* Returns the last path segment of a reference string.
*
* @example
* `extractRefName('#/components/schemas/Pet') // 'Pet'`
*/
declare function extractRefName(ref: string): string;
/**
* Builds a PascalCase child schema name by joining a parent name and property name.
* Returns `null` when there is no parent to nest under.
*
* @example Nested under a parent
* `childName('Order', 'shipping_address') // 'OrderShippingAddress'`
*
* @example No parent
* `childName(undefined, 'params') // null`
*/
declare function childName(parentName: string | null | undefined, propName: string): string | null;
/**
* Builds a PascalCase enum name from the parent name, property name, and a suffix, skipping any
* empty parts.
*
* @example
* `enumPropName('Order', 'status', 'enum') // 'OrderStatusEnum'`
*/
declare function enumPropName(parentName: string | null | undefined, propName: string, enumSuffix: string): string;
/**
* Merges a ref node with its resolved schema, giving usage-site fields precedence.
*
* Every field set on the ref node except `kind`, `type`, `name`, `ref`, and `schema` overrides the
* same field in the resolved `node.schema` (for example `description`, `nullable`, `readOnly`,
* `deprecated`). Fields left `undefined` on the ref do not shadow the resolved schema. Non-ref
* nodes and refs without a resolved `schema` are returned unchanged.
*
* @example
* ```ts
* const ref = createSchema({ type: 'ref', ref: '#/components/schemas/Pet', description: 'A cute pet' })
* const merged = syncSchemaRef(ref) // merges with resolved Pet schema
* ```
*/
declare function syncSchemaRef(node: SchemaNode): SchemaNode;
/**
* Type guard that returns `true` when a schema emits as a plain `string` type.
*
* Covers `string`, `uuid`, `email`, `url`, and `datetime` types. For `date` and `time`
* types, returns `true` only when `representation` is `'string'` rather than `'date'`.
*/
declare function isStringType(node: SchemaNode): boolean;
//#endregion
//#region src/utils/schemaMerge.d.ts
/**
* Merges a run of adjacent anonymous object members into one. Named or non-object members break the
* run and pass through unchanged. The merge follows member order, so callers control which members
* combine by where they place them in the sequence.
*
* @example
* ```ts
* const merged = [...mergeAdjacentObjectsLazy([objectA, objectB])]
* ```
*/
declare function mergeAdjacentObjectsLazy(members: Iterable<SchemaNode>): Generator<SchemaNode, void, undefined>;
//#endregion
//#region src/utils/strings.d.ts
/**
* Strips a single matching pair of `"..."`, `'...'`, or `` `...` `` from both ends of `text`.
* Returns the string unchanged when no balanced quote pair is found.
*
* @example
* ```ts
* trimQuotes('"hello"') // 'hello'
* trimQuotes('hello') // 'hello'
* ```
*/
declare function trimQuotes(text: string): string;
/**
* Serializes a primitive to a single-quoted string literal, stripping any surrounding quotes first.
*
* Escaping runs through `JSON.stringify`, then the result switches to single quotes so the generated
* code matches the repo style without a formatter.
*
* @example
* ```ts
* stringify('hello') // "'hello'"
* stringify('"hello"') // "'hello'"
* ```
*/
declare function stringify(value: string | number | boolean | undefined): string;
/**
* Escapes characters that are not allowed inside JS string literals, covering quotes, backslashes,
* and the Unicode line terminators U+2028 and U+2029.
*
* @see http://www.ecma-international.org/ecma-262/5.1/#sec-7.8.4
*
* @example
* ```ts
* jsStringEscape('say "hi"\nbye') // 'say \\"hi\\"\\nbye'
* ```
*/
declare function jsStringEscape(input: unknown): string;
/**
* Converts a pattern string into a `new RegExp(...)` constructor call or a regex literal string.
* Inline flags expressed as a `^(?im)` prefix are extracted and applied to the resulting expression.
* Pass `null` as the second argument to emit a `/pattern/flags` literal instead.
*
* @example
* ```ts
* toRegExpString('^(?im)foo') // 'new RegExp("^foo", "im")'
* toRegExpString('^(?im)foo', null) // '/^foo/im'
* ```
*/
declare function toRegExpString(text: string, func?: string | null): string;
/**
* Renders a plain object as multi-line `key: value` source for embedding in generated code. Nested
* objects recurse with fixed indentation, so the result drops straight into an object literal
* without re-parsing.
*
* @example
* ```ts
* stringifyObject({ foo: 'bar', nested: { a: 1 } })
* // 'foo: bar,\nnested: {\n a: 1\n }'
* ```
*/
declare function stringifyObject(value: Record<string, unknown>): string;
/**
* Renders a dotted path or string array as an optional-chaining accessor expression rooted at
* `accessor`. Returns `null` for an empty path.
*
* @example
* ```ts
* getNestedAccessor('pagination.next.id', 'lastPage')
* // "lastPage?.['pagination']?.['next']?.['id']"
* ```
*/
declare function getNestedAccessor(param: string | Array<string>, accessor: string): string | null;
//#endregion
//#region src/utils/schemaGraph.d.ts
/**
* Collects the names of all top-level schemas transitively used by a set of operations.
*
* An operation uses a schema when its parameters, request body, or responses reference it, directly
* or through other named schemas. Once a name is added to the result it is not revisited, so
* reference cycles terminate.
*
* Pair it with `include` filters so schemas reachable only from excluded operations stay ungenerated.
*
* @example Only generate schemas referenced by included operations
* ```ts
* const includedOps = operations.filter((op) => resolver.resolveOptions(op, { options, include }) !== null)
* const allowed = collectUsedSchemaNames(includedOps, schemas)
*
* for (const schema of schemas) {
* if (schema.name && !allowed.has(schema.name)) continue
* // generate schema
* }
* ```
*/
declare function collectUsedSchemaNames(operations: ReadonlyArray<OperationNode>, schemas: ReadonlyArray<SchemaNode>): Set<string>;
/**
* Finds every schema that takes part in a circular dependency chain, including direct self-loops.
*
* Wrap the returned schema positions in a deferred construct (a lazy getter or `z.lazy(() => …)`) so
* the generated code does not recurse forever. Refs are followed by name only, so the walk stays
* linear in the size of the schema graph.
*
* @note Call this once on the full graph, then check individual schemas with `containsCircularRef()`.
*/
declare function findCircularSchemas(schemas: ReadonlyArray<SchemaNode>): Set<string>;
/**
* Returns `true` when a schema, or anything nested inside it, references a circular schema.
*
* Pass `excludeName` to skip refs to a specific schema, which helps when self-references are handled
* on their own. Pair it with `findCircularSchemas()` to decide where lazy wrappers go.
*
* @note Stops at the first matching circular ref.
*/
declare function containsCircularRef(node: SchemaNode | undefined, {
circularSchemas,
excludeName
}: {
circularSchemas: ReadonlySet<string>;
excludeName?: string;
}): boolean;
//#endregion
//#region src/utils/schemaTraversal.d.ts
/**
* Converts a child schema to printer output. Plugins instantiate it with their own output type:
* `string` for the zod and faker printers, `ts.TypeNode` for the TypeScript printer. A printer's
* `this.transform` fits directly, so its `null` for an empty result carries through to `output`.
*/
type SchemaTransform<TOutput> = (schema: SchemaNode) => TOutput;
/**
* A union or intersection member, or an array or tuple item, paired with its transformed output.
*/
type MappedSchema<TOutput> = {
/**
* The original child schema, kept so the printer can read its metadata for leaf formatting.
*/
schema: SchemaNode;
/**
* The child schema after being run through the transform.
*/
output: TOutput;
};
/**
* An object property paired with its transformed output.
*/
type MappedProperty<TOutput> = {
/**
* The property name as written on the schema, before any identifier quoting.
*/
name: string;
/**
* The original property node, kept so the printer can read `required`, `schema`, and metadata.
*/
property: PropertyNode;
/**
* The property schema after being run through the transform.
*/
output: TOutput;
};
/**
* Maps each property of an object schema to its transformed output. Pairs every result with the
* original property so the printer keeps full control over modifiers, getters, and key syntax.
*
* @example
* ```ts
* const entries = mapSchemaProperties(node, (schema) => this.transform(schema))
* // entries: [{ name: 'id', property, output: 'z.number()' }, ...]
* ```
*/
declare function mapSchemaProperties<TOutput>(node: ObjectSchemaNode, transform: SchemaTransform<TOutput>): Array<MappedProperty<TOutput>>;
/**
* Maps each member of a union or intersection schema to its transformed output, pairing every
* result with the original member.
*/
declare function mapSchemaMembers<TOutput>(node: UnionSchemaNode | IntersectionSchemaNode, transform: SchemaTransform<TOutput>): Array<MappedSchema<TOutput>>;
/**
* Maps each item of an array or tuple schema to its transformed output, pairing every result with
* the original item.
*/
declare function mapSchemaItems<TOutput>(node: ArraySchemaNode, transform: SchemaTransform<TOutput>): Array<MappedSchema<TOutput>>;
/**
* Emits a lazy getter for a circular-ref property position, `get name() { return body }`. The key
* is quoted only when it is not a valid identifier. Used by the string printers to defer evaluation
* of a recursive schema until first access.
*
* @example
* ```ts
* lazyGetter({ name: 'parent', body: 'z.lazy(() => Pet)' })
* // "get parent() { return z.lazy(() => Pet) }"
* ```
*/
declare function lazyGetter({
name,
body
}: {
name: string;
body: string;
}): string;
//#endregion
export { buildJSDoc, buildList, buildObject, childName, collectUsedSchemaNames, containsCircularRef, enumPropName, extractRefName, extractStringsFromNodes, findCircularSchemas, getNestedAccessor, isStringType, isValidVarName, jsStringEscape, lazyGetter, mapSchemaItems, mapSchemaMembers, mapSchemaProperties, mergeAdjacentObjectsLazy, objectKey, stringify, stringifyObject, syncSchemaRef, toRegExpString, trimQuotes };
//# sourceMappingURL=utils.d.ts.map
import "./rolldown-runtime-CNktS9qV.js";
import { Q as narrowSchema, j as extractStringsFromNodes, n as collectLazy, o as createSchema, t as collect } from "./visitor-Dk0DNLfC.js";
import { a as resolveRefName, i as isStringType, n as enumPropName, o as syncSchemaRef, r as extractRefName, t as childName } from "./refs-BjBHwunY.js";
//#region ../../internals/utils/src/promise.ts
/**
* Wraps `factory` with a keyed cache backed by the provided store.
*
* Pass a `WeakMap` for object keys (results are GC-eligible when the key is
* collected) or a `Map` for primitive keys. For multi-argument functions,
* nest two `memoize` calls — the outer keyed by the first argument, the
* inner (created once per outer miss) keyed by the second.
*
* Because the cache is owned by the caller, it can be shared, inspected, or
* cleared independently of the memoized function.
*
* @example Single WeakMap key
* ```ts
* const cache = new WeakMap<SchemaNode, Set<string>>()
* const getRefs = memoize(cache, (node) => collectRefs(node))
* ```
*
* @example Single Map key (primitive)
* ```ts
* const cache = new Map<string, Resolver>()
* const getResolver = memoize(cache, (name) => buildResolver(name))
* ```
*
* @example Two-level (object + primitive)
* ```ts
* const outer = new WeakMap<Params[], Map<string, Params[]>>()
* const fn = memoize(outer, (params) => memoize(new Map(), (key) => transform(params, key)))
* fn(params)('camelcase')
* ```
*/
function memoize(store, factory) {
return (key) => {
if (store.has(key)) return store.get(key);
const value = factory(key);
store.set(key, value);
return value;
};
}
//#endregion
//#region ../../internals/utils/src/reserved.ts
/**
* JavaScript and Java reserved words.
* @link https://github.com/jonschlinkert/reserved/blob/master/index.js
*/
const reservedWords = /* @__PURE__ */ new Set([
"abstract",
"arguments",
"boolean",
"break",
"byte",
"case",
"catch",
"char",
"class",
"const",
"continue",
"debugger",
"default",
"delete",
"do",
"double",
"else",
"enum",
"eval",
"export",
"extends",
"false",
"final",
"finally",
"float",
"for",
"function",
"goto",
"if",
"implements",
"import",
"in",
"instanceof",
"int",
"interface",
"let",
"long",
"native",
"new",
"null",
"package",
"private",
"protected",
"public",
"return",
"short",
"static",
"super",
"switch",
"synchronized",
"this",
"throw",
"throws",
"transient",
"true",
"try",
"typeof",
"var",
"void",
"volatile",
"while",
"with",
"yield",
"Array",
"Date",
"hasOwnProperty",
"Infinity",
"isFinite",
"isNaN",
"isPrototypeOf",
"length",
"Math",
"name",
"NaN",
"Number",
"Object",
"prototype",
"String",
"toString",
"undefined",
"valueOf"
]);
/**
* Returns `true` when `name` is a syntactically valid JavaScript variable name.
*
* @example
* ```ts
* isValidVarName('status') // true
* isValidVarName('class') // false (reserved word)
* isValidVarName('42foo') // false (starts with digit)
* ```
*/
function isValidVarName(name) {
if (!name || reservedWords.has(name)) return false;
return isIdentifier(name);
}
/**
* Returns `true` when `name` is syntactically a valid identifier, ignoring reserved words.
*
* Reserved words and globals (`class`, `name`, `Date`, …) are valid as bare object-literal keys
* even though they are not valid variable names, so use this (not {@link isValidVarName}) when
* deciding whether an object key needs quoting.
*
* @example
* ```ts
* isIdentifier('name') // true
* isIdentifier('x-total')// false
* ```
*/
function isIdentifier(name) {
return /^[a-zA-Z_$][a-zA-Z0-9_$]*$/.test(name);
}
//#endregion
//#region ../../internals/utils/src/string.ts
/**
* Wraps a value in single quotes for emitting a single-quoted JavaScript string literal, escaping
* any backslash or single quote in the content.
*
* @example
* ```ts
* singleQuote('foo') // "'foo'"
* singleQuote("o'clock") // "'o\\'clock'"
* ```
*/
function singleQuote(value) {
if (value === void 0 || value === null) return "''";
return `'${String(value).replace(/\\/g, "\\\\").replace(/'/g, "\\'")}'`;
}
//#endregion
//#region src/utils/codegen.ts
/**
* Builds a JSDoc comment block from an array of lines. Returns `fallback` when there are no
* comments.
*
* @example
* ```ts
* buildJSDoc(['@type string', '@example hello'])
* // '/**\n * @type string\n * @example hello\n *\/\n '
* ```
*/
function buildJSDoc(comments, options = {}) {
const { indent = " * ", suffix = "\n ", fallback = " " } = options;
if (comments.length === 0) return fallback;
return `/**\n${comments.map((c) => `${indent}${c}`).join("\n")}\n */${suffix}`;
}
/**
* Indents every non-empty line of `text` by one indent level, leaving blank lines empty.
*/
function indentLines(text) {
if (!text) return "";
return text.split("\n").map((line) => line.trim() ? ` ${line}` : "").join("\n");
}
/**
* Renders an object key, quoting it with single quotes only when it is not a valid identifier.
* Reserved words and globals (`name`, `class`, …) are valid bare keys and stay unquoted.
*
* @example
* ```ts
* objectKey('name') // 'name'
* objectKey('x-total') // "'x-total'"
* ```
*/
function objectKey(name) {
return isIdentifier(name) ? name : singleQuote(name);
}
/**
* Assembles a multi-line object literal from already-rendered `entries`, indenting each entry one
* level and closing the brace at column zero. Entries that are themselves multi-line objects indent
* cumulatively. Each entry ends with a trailing comma to match the formatter's multi-line style.
*
* @example
* ```ts
* buildObject(['id: z.number()', 'name: z.string()'])
* // '{\n id: z.number(),\n name: z.string(),\n}'
* ```
*/
function buildObject(entries) {
if (entries.length === 0) return "{}";
return `{\n${entries.map((entry) => `${indentLines(entry)},`).join("\n")}\n}`;
}
/**
* Assembles a bracketed list (array by default) from already-rendered `items`. Keeps everything on
* one line when no item spans multiple lines, and otherwise puts each item on its own line, indented
* one level with a trailing comma and the closing bracket at column zero. Used for member lists such
* as `z.union([…])` and `z.array([…])`.
*
* @example
* ```ts
* buildList(['z.string()', 'z.number()'])
* // '[z.string(), z.number()]'
* ```
*/
function buildList(items, brackets = ["[", "]"]) {
const [open, close] = brackets;
if (items.length === 0) return `${open}${close}`;
if (!items.some((item) => item.includes("\n"))) return `${open}${items.join(", ")}${close}`;
return `${open}\n${items.map((item) => `${indentLines(item)},`).join("\n")}\n${close}`;
}
//#endregion
//#region src/utils/schemaMerge.ts
/**
* Merges a run of adjacent anonymous object members into one. Named or non-object members break the
* run and pass through unchanged. The merge follows member order, so callers control which members
* combine by where they place them in the sequence.
*
* @example
* ```ts
* const merged = [...mergeAdjacentObjectsLazy([objectA, objectB])]
* ```
*/
function* mergeAdjacentObjectsLazy(members) {
let acc;
for (const member of members) {
const objectMember = narrowSchema(member, "object");
if (objectMember && !objectMember.name && acc !== void 0) {
const accObject = narrowSchema(acc, "object");
if (accObject && !accObject.name) {
acc = createSchema({
...accObject,
properties: [...accObject.properties ?? [], ...objectMember.properties ?? []]
});
continue;
}
}
if (acc !== void 0) yield acc;
acc = member;
}
if (acc !== void 0) yield acc;
}
//#endregion
//#region src/utils/strings.ts
/**
* Strips a single matching pair of `"..."`, `'...'`, or `` `...` `` from both ends of `text`.
* Returns the string unchanged when no balanced quote pair is found.
*
* @example
* ```ts
* trimQuotes('"hello"') // 'hello'
* trimQuotes('hello') // 'hello'
* ```
*/
function trimQuotes(text) {
if (text.length >= 2) {
const first = text[0];
const last = text[text.length - 1];
if (first === "\"" && last === "\"" || first === "'" && last === "'" || first === "`" && last === "`") return text.slice(1, -1);
}
return text;
}
/**
* Serializes a primitive to a single-quoted string literal, stripping any surrounding quotes first.
*
* Escaping runs through `JSON.stringify`, then the result switches to single quotes so the generated
* code matches the repo style without a formatter.
*
* @example
* ```ts
* stringify('hello') // "'hello'"
* stringify('"hello"') // "'hello'"
* ```
*/
function stringify(value) {
if (value === void 0 || value === null) return "''";
return `'${JSON.stringify(trimQuotes(value.toString())).slice(1, -1).replace(/\\"/g, "\"").replace(/'/g, "\\'")}'`;
}
/**
* Escapes characters that are not allowed inside JS string literals, covering quotes, backslashes,
* and the Unicode line terminators U+2028 and U+2029.
*
* @see http://www.ecma-international.org/ecma-262/5.1/#sec-7.8.4
*
* @example
* ```ts
* jsStringEscape('say "hi"\nbye') // 'say \\"hi\\"\\nbye'
* ```
*/
function jsStringEscape(input) {
return `${input}`.replace(/["'\\\n\r\u2028\u2029]/g, (character) => {
switch (character) {
case "\"":
case "'":
case "\\": return `\\${character}`;
case "\n": return "\\n";
case "\r": return "\\r";
case "\u2028": return "\\u2028";
case "\u2029": return "\\u2029";
default: return "";
}
});
}
/**
* Converts a pattern string into a `new RegExp(...)` constructor call or a regex literal string.
* Inline flags expressed as a `^(?im)` prefix are extracted and applied to the resulting expression.
* Pass `null` as the second argument to emit a `/pattern/flags` literal instead.
*
* @example
* ```ts
* toRegExpString('^(?im)foo') // 'new RegExp("^foo", "im")'
* toRegExpString('^(?im)foo', null) // '/^foo/im'
* ```
*/
function toRegExpString(text, func = "RegExp") {
const raw = trimQuotes(text);
const match = raw.match(/^\^(\(\?([igmsuy]+)\))/i);
const replacementTarget = match?.[1] ?? "";
const matchedFlags = match?.[2];
const cleaned = raw.replace(/^\\?\//, "").replace(/\\?\/$/, "").replace(replacementTarget, "");
const { source, flags } = new RegExp(cleaned, matchedFlags);
if (func === null) return `/${source}/${flags}`;
return `new ${func}(${JSON.stringify(source)}${flags ? `, ${JSON.stringify(flags)}` : ""})`;
}
/**
* Renders a plain object as multi-line `key: value` source for embedding in generated code. Nested
* objects recurse with fixed indentation, so the result drops straight into an object literal
* without re-parsing.
*
* @example
* ```ts
* stringifyObject({ foo: 'bar', nested: { a: 1 } })
* // 'foo: bar,\nnested: {\n a: 1\n }'
* ```
*/
function stringifyObject(value) {
return Object.entries(value).map(([key, val]) => {
if (val !== null && typeof val === "object") return `${key}: {\n ${stringifyObject(val)}\n }`;
return `${key}: ${val}`;
}).filter(Boolean).join(",\n");
}
/**
* Renders a dotted path or string array as an optional-chaining accessor expression rooted at
* `accessor`. Returns `null` for an empty path.
*
* @example
* ```ts
* getNestedAccessor('pagination.next.id', 'lastPage')
* // "lastPage?.['pagination']?.['next']?.['id']"
* ```
*/
function getNestedAccessor(param, accessor) {
const parts = Array.isArray(param) ? param : param.split(".");
if (parts.length === 0 || parts.length === 1 && parts[0] === "") return null;
return `${accessor}?.['${`${parts.join("']?.['")}']`}`;
}
//#endregion
//#region src/utils/schemaGraph.ts
/**
* Memoized inner pass that walks a single node and returns the names of every schema it references.
*/
const collectSchemaRefs = memoize(/* @__PURE__ */ new WeakMap(), (node) => {
const refs = /* @__PURE__ */ new Set();
collect(node, { schema(child) {
if (child.type === "ref") {
const name = resolveRefName(child);
if (name) refs.add(name);
}
} });
return refs;
});
/**
* Collects the names of every ref found anywhere inside a node's own subtree.
*
* Each ref contributes its name only, so the schema it points to is never traversed here. Pass `out`
* to accumulate names from several nodes into one set.
*
* @example Collect refs from a single schema
* ```ts
* const names = collectReferencedSchemaNames(petSchema)
* // Set { 'Category', 'Tag' }
* ```
*
* @example Accumulate refs from multiple schemas into one set
* ```ts
* const out = new Set<string>()
* for (const schema of schemas) {
* collectReferencedSchemaNames(schema, out)
* }
* ```
*/
function collectReferencedSchemaNames(node, out = /* @__PURE__ */ new Set()) {
if (!node) return out;
for (const name of collectSchemaRefs(node)) out.add(name);
return out;
}
/**
* Memoized two-level cache keyed first on the operations array, then on the schemas array.
*/
const collectUsedSchemaNamesMemo = memoize(/* @__PURE__ */ new WeakMap(), (ops) => memoize(/* @__PURE__ */ new WeakMap(), (schemas) => computeUsedSchemaNames(ops, schemas)));
function computeUsedSchemaNames(operations, schemas) {
const schemaMap = /* @__PURE__ */ new Map();
for (const schema of schemas) if (schema.name) schemaMap.set(schema.name, schema);
const result = /* @__PURE__ */ new Set();
function visitSchema(schema) {
const directRefs = collectReferencedSchemaNames(schema);
for (const name of directRefs) if (!result.has(name)) {
result.add(name);
const namedSchema = schemaMap.get(name);
if (namedSchema) visitSchema(namedSchema);
}
}
for (const op of operations) for (const schema of collectLazy(op, {
depth: "shallow",
schema: (node) => node
})) visitSchema(schema);
return result;
}
/**
* Collects the names of all top-level schemas transitively used by a set of operations.
*
* An operation uses a schema when its parameters, request body, or responses reference it, directly
* or through other named schemas. Once a name is added to the result it is not revisited, so
* reference cycles terminate.
*
* Pair it with `include` filters so schemas reachable only from excluded operations stay ungenerated.
*
* @example Only generate schemas referenced by included operations
* ```ts
* const includedOps = operations.filter((op) => resolver.resolveOptions(op, { options, include }) !== null)
* const allowed = collectUsedSchemaNames(includedOps, schemas)
*
* for (const schema of schemas) {
* if (schema.name && !allowed.has(schema.name)) continue
* // generate schema
* }
* ```
*/
function collectUsedSchemaNames(operations, schemas) {
return collectUsedSchemaNamesMemo(operations)(schemas);
}
const EMPTY_CIRCULAR_SET = /* @__PURE__ */ new Set();
const findCircularSchemasMemo = memoize(/* @__PURE__ */ new WeakMap(), (schemas) => {
const graph = /* @__PURE__ */ new Map();
for (const schema of schemas) {
if (!schema.name) continue;
graph.set(schema.name, collectReferencedSchemaNames(schema));
}
const circular = /* @__PURE__ */ new Set();
for (const start of graph.keys()) {
const visited = /* @__PURE__ */ new Set();
const stack = [...graph.get(start) ?? []];
while (stack.length > 0) {
const node = stack.pop();
if (node === start) {
circular.add(start);
break;
}
if (visited.has(node)) continue;
visited.add(node);
const next = graph.get(node);
if (next) for (const r of next) stack.push(r);
}
}
return circular;
});
/**
* Finds every schema that takes part in a circular dependency chain, including direct self-loops.
*
* Wrap the returned schema positions in a deferred construct (a lazy getter or `z.lazy(() => …)`) so
* the generated code does not recurse forever. Refs are followed by name only, so the walk stays
* linear in the size of the schema graph.
*
* @note Call this once on the full graph, then check individual schemas with `containsCircularRef()`.
*/
function findCircularSchemas(schemas) {
if (schemas.length === 0) return EMPTY_CIRCULAR_SET;
return findCircularSchemasMemo(schemas);
}
/**
* Returns `true` when a schema, or anything nested inside it, references a circular schema.
*
* Pass `excludeName` to skip refs to a specific schema, which helps when self-references are handled
* on their own. Pair it with `findCircularSchemas()` to decide where lazy wrappers go.
*
* @note Stops at the first matching circular ref.
*/
function containsCircularRef(node, { circularSchemas, excludeName }) {
if (!node || circularSchemas.size === 0) return false;
for (const _ of collectLazy(node, { schema(child) {
if (child.type !== "ref") return null;
const name = resolveRefName(child);
return name && name !== excludeName && circularSchemas.has(name) ? true : null;
} })) return true;
return false;
}
//#endregion
//#region src/utils/schemaTraversal.ts
/**
* Maps each property of an object schema to its transformed output. Pairs every result with the
* original property so the printer keeps full control over modifiers, getters, and key syntax.
*
* @example
* ```ts
* const entries = mapSchemaProperties(node, (schema) => this.transform(schema))
* // entries: [{ name: 'id', property, output: 'z.number()' }, ...]
* ```
*/
function mapSchemaProperties(node, transform) {
return node.properties.map((property) => ({
name: property.name,
property,
output: transform(property.schema)
}));
}
/**
* Maps each member of a union or intersection schema to its transformed output, pairing every
* result with the original member.
*/
function mapSchemaMembers(node, transform) {
return (node.members ?? []).map((schema) => ({
schema,
output: transform(schema)
}));
}
/**
* Maps each item of an array or tuple schema to its transformed output, pairing every result with
* the original item.
*/
function mapSchemaItems(node, transform) {
return (node.items ?? []).map((schema) => ({
schema,
output: transform(schema)
}));
}
/**
* Emits a lazy getter for a circular-ref property position, `get name() { return body }`. The key
* is quoted only when it is not a valid identifier. Used by the string printers to defer evaluation
* of a recursive schema until first access.
*
* @example
* ```ts
* lazyGetter({ name: 'parent', body: 'z.lazy(() => Pet)' })
* // "get parent() { return z.lazy(() => Pet) }"
* ```
*/
function lazyGetter({ name, body }) {
return `get ${objectKey(name)}() { return ${body} }`;
}
//#endregion
export { buildJSDoc, buildList, buildObject, childName, collectUsedSchemaNames, containsCircularRef, enumPropName, extractRefName, extractStringsFromNodes, findCircularSchemas, getNestedAccessor, isStringType, isValidVarName, jsStringEscape, lazyGetter, mapSchemaItems, mapSchemaMembers, mapSchemaProperties, mergeAdjacentObjectsLazy, objectKey, stringify, stringifyObject, syncSchemaRef, toRegExpString, trimQuotes };
//# sourceMappingURL=utils.js.map
{"version":3,"file":"utils.js","names":[],"sources":["../../../internals/utils/src/promise.ts","../../../internals/utils/src/reserved.ts","../../../internals/utils/src/string.ts","../src/utils/codegen.ts","../src/utils/schemaMerge.ts","../src/utils/strings.ts","../src/utils/schemaGraph.ts","../src/utils/schemaTraversal.ts"],"sourcesContent":["/** A value that may already be resolved or still pending.\n *\n * @example\n * ```ts\n * function load(id: string): PossiblePromise<string> {\n * return cache.get(id) ?? fetchRemote(id)\n * }\n * ```\n */\nexport type PossiblePromise<T> = Promise<T> | T\n\n/** Returns `true` when `result` is a thenable `Promise`.\n *\n * @example\n * ```ts\n * isPromise(Promise.resolve(1)) // true\n * isPromise(42) // false\n * ```\n */\nexport function isPromise<T>(result: PossiblePromise<T>): result is Promise<T> {\n return result !== null && result !== undefined && typeof (result as Record<string, unknown>)['then'] === 'function'\n}\n\ntype Store<TKey, TValue> = {\n has(key: TKey): boolean\n get(key: TKey): TValue | undefined\n set(key: TKey, value: TValue): unknown\n}\n\n/**\n * Wraps `factory` with a keyed cache backed by the provided store.\n *\n * Pass a `WeakMap` for object keys (results are GC-eligible when the key is\n * collected) or a `Map` for primitive keys. For multi-argument functions,\n * nest two `memoize` calls — the outer keyed by the first argument, the\n * inner (created once per outer miss) keyed by the second.\n *\n * Because the cache is owned by the caller, it can be shared, inspected, or\n * cleared independently of the memoized function.\n *\n * @example Single WeakMap key\n * ```ts\n * const cache = new WeakMap<SchemaNode, Set<string>>()\n * const getRefs = memoize(cache, (node) => collectRefs(node))\n * ```\n *\n * @example Single Map key (primitive)\n * ```ts\n * const cache = new Map<string, Resolver>()\n * const getResolver = memoize(cache, (name) => buildResolver(name))\n * ```\n *\n * @example Two-level (object + primitive)\n * ```ts\n * const outer = new WeakMap<Params[], Map<string, Params[]>>()\n * const fn = memoize(outer, (params) => memoize(new Map(), (key) => transform(params, key)))\n * fn(params)('camelcase')\n * ```\n */\nexport function memoize<TKey, TValue>(store: Store<TKey, TValue>, factory: (key: TKey) => TValue): (key: TKey) => TValue {\n return (key: TKey): TValue => {\n if (store.has(key)) return store.get(key)!\n const value = factory(key)\n store.set(key, value)\n return value\n }\n}\n\n/**\n * Container that switches between an eager `Array<T>` and a lazy `AsyncIterable<T>`.\n *\n * `Array<T>` by default. With `Stream` set to `true` it becomes `AsyncIterable<T>`, so large\n * collections can be produced lazily without holding every item in memory. Pairs with\n * {@link arrayToAsyncIterable}, which lifts a plain array into the streaming form.\n *\n * @example\n * ```ts\n * type Eager = Streamable<number> // Array<number>\n * type Lazy = Streamable<number, true> // AsyncIterable<number>\n * ```\n */\nexport type Streamable<T, Stream extends boolean = false> = Stream extends true ? AsyncIterable<T> : Array<T>\n\n/**\n * Wraps a plain array in a reusable `AsyncIterable`.\n * Each `[Symbol.asyncIterator]()` call returns a fresh generator so the\n * iterable can be consumed multiple times (e.g. once per plugin pre-scan).\n *\n * @example\n * ```ts\n * const stream = arrayToAsyncIterable([1, 2, 3])\n * for await (const n of stream) console.log(n) // 1, 2, 3\n * ```\n */\nexport function arrayToAsyncIterable<T>(arr: ReadonlyArray<T>): AsyncIterable<T> {\n return {\n [Symbol.asyncIterator]() {\n return (async function* () {\n yield* arr\n })()\n },\n }\n}\n","/**\n * JavaScript and Java reserved words.\n * @link https://github.com/jonschlinkert/reserved/blob/master/index.js\n */\nconst reservedWords = new Set([\n 'abstract',\n 'arguments',\n 'boolean',\n 'break',\n 'byte',\n 'case',\n 'catch',\n 'char',\n 'class',\n 'const',\n 'continue',\n 'debugger',\n 'default',\n 'delete',\n 'do',\n 'double',\n 'else',\n 'enum',\n 'eval',\n 'export',\n 'extends',\n 'false',\n 'final',\n 'finally',\n 'float',\n 'for',\n 'function',\n 'goto',\n 'if',\n 'implements',\n 'import',\n 'in',\n 'instanceof',\n 'int',\n 'interface',\n 'let',\n 'long',\n 'native',\n 'new',\n 'null',\n 'package',\n 'private',\n 'protected',\n 'public',\n 'return',\n 'short',\n 'static',\n 'super',\n 'switch',\n 'synchronized',\n 'this',\n 'throw',\n 'throws',\n 'transient',\n 'true',\n 'try',\n 'typeof',\n 'var',\n 'void',\n 'volatile',\n 'while',\n 'with',\n 'yield',\n 'Array',\n 'Date',\n 'hasOwnProperty',\n 'Infinity',\n 'isFinite',\n 'isNaN',\n 'isPrototypeOf',\n 'length',\n 'Math',\n 'name',\n 'NaN',\n 'Number',\n 'Object',\n 'prototype',\n 'String',\n 'toString',\n 'undefined',\n 'valueOf',\n] as const)\n\n/**\n * Prefixes `word` with `_` when it is a reserved JavaScript/Java identifier or starts with a digit.\n *\n * @example\n * ```ts\n * transformReservedWord('class') // '_class'\n * transformReservedWord('42foo') // '_42foo'\n * transformReservedWord('status') // 'status'\n * ```\n */\nexport function transformReservedWord(word: string): string {\n const firstChar = word.charCodeAt(0)\n if (word && (reservedWords.has(word as 'valueOf') || (firstChar >= 48 && firstChar <= 57))) {\n return `_${word}`\n }\n return word\n}\n\n/**\n * Returns `true` when `name` is a syntactically valid JavaScript variable name.\n *\n * @example\n * ```ts\n * isValidVarName('status') // true\n * isValidVarName('class') // false (reserved word)\n * isValidVarName('42foo') // false (starts with digit)\n * ```\n */\nexport function isValidVarName(name: string): boolean {\n if (!name || reservedWords.has(name as 'valueOf')) {\n return false\n }\n return isIdentifier(name)\n}\n\n/**\n * Returns `true` when `name` is syntactically a valid identifier, ignoring reserved words.\n *\n * Reserved words and globals (`class`, `name`, `Date`, …) are valid as bare object-literal keys\n * even though they are not valid variable names, so use this (not {@link isValidVarName}) when\n * deciding whether an object key needs quoting.\n *\n * @example\n * ```ts\n * isIdentifier('name') // true\n * isIdentifier('x-total')// false\n * ```\n */\nexport function isIdentifier(name: string): boolean {\n return /^[a-zA-Z_$][a-zA-Z0-9_$]*$/.test(name)\n}\n","/**\n * Wraps a value in single quotes for emitting a single-quoted JavaScript string literal, escaping\n * any backslash or single quote in the content.\n *\n * @example\n * ```ts\n * singleQuote('foo') // \"'foo'\"\n * singleQuote(\"o'clock\") // \"'o\\\\'clock'\"\n * ```\n */\nexport function singleQuote(value: string | number | boolean | undefined | null): string {\n if (value === undefined || value === null) return \"''\"\n const escaped = String(value).replace(/\\\\/g, '\\\\\\\\').replace(/'/g, \"\\\\'\")\n\n return `'${escaped}'`\n}\n","import { isIdentifier, singleQuote } from '@internals/utils'\nimport { INDENT } from '../constants.ts'\n\n/**\n * Builds a JSDoc comment block from an array of lines. Returns `fallback` when there are no\n * comments.\n *\n * @example\n * ```ts\n * buildJSDoc(['@type string', '@example hello'])\n * // '/**\\n * @type string\\n * @example hello\\n *\\/\\n '\n * ```\n */\nexport function buildJSDoc(\n comments: Array<string>,\n options: {\n /**\n * String used to indent each comment line.\n * @default ' * '\n */\n indent?: string\n /**\n * String appended after the closing tag.\n * @default '\\n '\n */\n suffix?: string\n /**\n * Returned as-is when `comments` is empty.\n * @default ' '\n */\n fallback?: string\n } = {},\n): string {\n const { indent = ' * ', suffix = '\\n ', fallback = ' ' } = options\n\n if (comments.length === 0) return fallback\n\n return `/**\\n${comments.map((c) => `${indent}${c}`).join('\\n')}\\n */${suffix}`\n}\n\n/**\n * Indents every non-empty line of `text` by one indent level, leaving blank lines empty.\n */\nfunction indentLines(text: string): string {\n if (!text) return ''\n return text\n .split('\\n')\n .map((line) => (line.trim() ? `${INDENT}${line}` : ''))\n .join('\\n')\n}\n\n/**\n * Renders an object key, quoting it with single quotes only when it is not a valid identifier.\n * Reserved words and globals (`name`, `class`, …) are valid bare keys and stay unquoted.\n *\n * @example\n * ```ts\n * objectKey('name') // 'name'\n * objectKey('x-total') // \"'x-total'\"\n * ```\n */\nexport function objectKey(name: string): string {\n return isIdentifier(name) ? name : singleQuote(name)\n}\n\n/**\n * Assembles a multi-line object literal from already-rendered `entries`, indenting each entry one\n * level and closing the brace at column zero. Entries that are themselves multi-line objects indent\n * cumulatively. Each entry ends with a trailing comma to match the formatter's multi-line style.\n *\n * @example\n * ```ts\n * buildObject(['id: z.number()', 'name: z.string()'])\n * // '{\\n id: z.number(),\\n name: z.string(),\\n}'\n * ```\n */\nexport function buildObject(entries: Array<string>): string {\n if (entries.length === 0) return '{}'\n const body = entries.map((entry) => `${indentLines(entry)},`).join('\\n')\n\n return `{\\n${body}\\n}`\n}\n\n/**\n * Assembles a bracketed list (array by default) from already-rendered `items`. Keeps everything on\n * one line when no item spans multiple lines, and otherwise puts each item on its own line, indented\n * one level with a trailing comma and the closing bracket at column zero. Used for member lists such\n * as `z.union([…])` and `z.array([…])`.\n *\n * @example\n * ```ts\n * buildList(['z.string()', 'z.number()'])\n * // '[z.string(), z.number()]'\n * ```\n */\nexport function buildList(items: Array<string>, brackets: [open: string, close: string] = ['[', ']']): string {\n const [open, close] = brackets\n if (items.length === 0) return `${open}${close}`\n if (!items.some((item) => item.includes('\\n'))) return `${open}${items.join(', ')}${close}`\n const body = items.map((item) => `${indentLines(item)},`).join('\\n')\n\n return `${open}\\n${body}\\n${close}`\n}\n","import { narrowSchema } from '../guards.ts'\nimport { createSchema, type SchemaNode } from '../nodes/schema.ts'\n\n/**\n * Merges a run of adjacent anonymous object members into one. Named or non-object members break the\n * run and pass through unchanged. The merge follows member order, so callers control which members\n * combine by where they place them in the sequence.\n *\n * @example\n * ```ts\n * const merged = [...mergeAdjacentObjectsLazy([objectA, objectB])]\n * ```\n */\nexport function* mergeAdjacentObjectsLazy(members: Iterable<SchemaNode>): Generator<SchemaNode, void, undefined> {\n let acc: SchemaNode | undefined\n\n for (const member of members) {\n const objectMember = narrowSchema(member, 'object')\n if (objectMember && !objectMember.name && acc !== undefined) {\n const accObject = narrowSchema(acc, 'object')\n if (accObject && !accObject.name) {\n acc = createSchema({\n ...accObject,\n properties: [...(accObject.properties ?? []), ...(objectMember.properties ?? [])],\n })\n continue\n }\n }\n if (acc !== undefined) yield acc\n acc = member\n }\n\n if (acc !== undefined) yield acc\n}\n","/**\n * Strips a single matching pair of `\"...\"`, `'...'`, or `` `...` `` from both ends of `text`.\n * Returns the string unchanged when no balanced quote pair is found.\n *\n * @example\n * ```ts\n * trimQuotes('\"hello\"') // 'hello'\n * trimQuotes('hello') // 'hello'\n * ```\n */\nexport function trimQuotes(text: string): string {\n if (text.length >= 2) {\n const first = text[0]\n const last = text[text.length - 1]\n if ((first === '\"' && last === '\"') || (first === \"'\" && last === \"'\") || (first === '`' && last === '`')) {\n return text.slice(1, -1)\n }\n }\n return text\n}\n\n/**\n * Serializes a primitive to a single-quoted string literal, stripping any surrounding quotes first.\n *\n * Escaping runs through `JSON.stringify`, then the result switches to single quotes so the generated\n * code matches the repo style without a formatter.\n *\n * @example\n * ```ts\n * stringify('hello') // \"'hello'\"\n * stringify('\"hello\"') // \"'hello'\"\n * ```\n */\nexport function stringify(value: string | number | boolean | undefined): string {\n if (value === undefined || value === null) return \"''\"\n const json = JSON.stringify(trimQuotes(value.toString()))\n const inner = json.slice(1, -1).replace(/\\\\\"/g, '\"').replace(/'/g, \"\\\\'\")\n return `'${inner}'`\n}\n\n/**\n * Escapes characters that are not allowed inside JS string literals, covering quotes, backslashes,\n * and the Unicode line terminators U+2028 and U+2029.\n *\n * @see http://www.ecma-international.org/ecma-262/5.1/#sec-7.8.4\n *\n * @example\n * ```ts\n * jsStringEscape('say \"hi\"\\nbye') // 'say \\\\\"hi\\\\\"\\\\nbye'\n * ```\n */\nexport function jsStringEscape(input: unknown): string {\n return `${input}`.replace(/[\"'\\\\\\n\\r\\u2028\\u2029]/g, (character) => {\n switch (character) {\n case '\"':\n case \"'\":\n case '\\\\':\n return `\\\\${character}`\n case '\\n':\n return '\\\\n'\n case '\\r':\n return '\\\\r'\n case '\\u2028':\n return '\\\\u2028'\n case '\\u2029':\n return '\\\\u2029'\n default:\n return ''\n }\n })\n}\n\n/**\n * Converts a pattern string into a `new RegExp(...)` constructor call or a regex literal string.\n * Inline flags expressed as a `^(?im)` prefix are extracted and applied to the resulting expression.\n * Pass `null` as the second argument to emit a `/pattern/flags` literal instead.\n *\n * @example\n * ```ts\n * toRegExpString('^(?im)foo') // 'new RegExp(\"^foo\", \"im\")'\n * toRegExpString('^(?im)foo', null) // '/^foo/im'\n * ```\n */\nexport function toRegExpString(text: string, func: string | null = 'RegExp'): string {\n const raw = trimQuotes(text)\n\n const match = raw.match(/^\\^(\\(\\?([igmsuy]+)\\))/i)\n const replacementTarget = match?.[1] ?? ''\n const matchedFlags = match?.[2]\n const cleaned = raw\n .replace(/^\\\\?\\//, '')\n .replace(/\\\\?\\/$/, '')\n .replace(replacementTarget, '')\n\n const { source, flags } = new RegExp(cleaned, matchedFlags)\n\n if (func === null) return `/${source}/${flags}`\n\n return `new ${func}(${JSON.stringify(source)}${flags ? `, ${JSON.stringify(flags)}` : ''})`\n}\n\n/**\n * Renders a plain object as multi-line `key: value` source for embedding in generated code. Nested\n * objects recurse with fixed indentation, so the result drops straight into an object literal\n * without re-parsing.\n *\n * @example\n * ```ts\n * stringifyObject({ foo: 'bar', nested: { a: 1 } })\n * // 'foo: bar,\\nnested: {\\n a: 1\\n }'\n * ```\n */\nexport function stringifyObject(value: Record<string, unknown>): string {\n const items = Object.entries(value)\n .map(([key, val]) => {\n if (val !== null && typeof val === 'object') {\n return `${key}: {\\n ${stringifyObject(val as Record<string, unknown>)}\\n }`\n }\n return `${key}: ${val}`\n })\n .filter(Boolean)\n return items.join(',\\n')\n}\n\n/**\n * Renders a dotted path or string array as an optional-chaining accessor expression rooted at\n * `accessor`. Returns `null` for an empty path.\n *\n * @example\n * ```ts\n * getNestedAccessor('pagination.next.id', 'lastPage')\n * // \"lastPage?.['pagination']?.['next']?.['id']\"\n * ```\n */\nexport function getNestedAccessor(param: string | Array<string>, accessor: string): string | null {\n const parts = Array.isArray(param) ? param : param.split('.')\n if (parts.length === 0 || (parts.length === 1 && parts[0] === '')) return null\n return `${accessor}?.['${`${parts.join(\"']?.['\")}']`}`\n}\n","import { memoize } from '@internals/utils'\nimport type { OperationNode, SchemaNode } from '../nodes/index.ts'\nimport { collect, collectLazy } from '../visitor.ts'\nimport { resolveRefName } from './refs.ts'\n\n/**\n * Memoized inner pass that walks a single node and returns the names of every schema it references.\n */\nconst collectSchemaRefs = memoize(new WeakMap<SchemaNode, ReadonlySet<string>>(), (node: SchemaNode): ReadonlySet<string> => {\n const refs = new Set<string>()\n collect<void>(node, {\n schema(child) {\n if (child.type === 'ref') {\n const name = resolveRefName(child)\n if (name) refs.add(name)\n }\n },\n })\n return refs\n})\n\n/**\n * Collects the names of every ref found anywhere inside a node's own subtree.\n *\n * Each ref contributes its name only, so the schema it points to is never traversed here. Pass `out`\n * to accumulate names from several nodes into one set.\n *\n * @example Collect refs from a single schema\n * ```ts\n * const names = collectReferencedSchemaNames(petSchema)\n * // Set { 'Category', 'Tag' }\n * ```\n *\n * @example Accumulate refs from multiple schemas into one set\n * ```ts\n * const out = new Set<string>()\n * for (const schema of schemas) {\n * collectReferencedSchemaNames(schema, out)\n * }\n * ```\n */\nexport function collectReferencedSchemaNames(node: SchemaNode | undefined, out: Set<string> = new Set()): Set<string> {\n if (!node) return out\n for (const name of collectSchemaRefs(node)) out.add(name)\n return out\n}\n\n/**\n * Memoized two-level cache keyed first on the operations array, then on the schemas array.\n */\nconst collectUsedSchemaNamesMemo = memoize(new WeakMap<ReadonlyArray<OperationNode>, (schemas: ReadonlyArray<SchemaNode>) => Set<string>>(), (ops) =>\n memoize(new WeakMap<ReadonlyArray<SchemaNode>, Set<string>>(), (schemas) => computeUsedSchemaNames(ops, schemas)),\n)\n\nfunction computeUsedSchemaNames(operations: ReadonlyArray<OperationNode>, schemas: ReadonlyArray<SchemaNode>): Set<string> {\n const schemaMap = new Map<string, SchemaNode>()\n for (const schema of schemas) {\n if (schema.name) schemaMap.set(schema.name, schema)\n }\n\n const result = new Set<string>()\n\n function visitSchema(schema: SchemaNode): void {\n const directRefs = collectReferencedSchemaNames(schema)\n for (const name of directRefs) {\n if (!result.has(name)) {\n result.add(name)\n const namedSchema = schemaMap.get(name)\n if (namedSchema) visitSchema(namedSchema)\n }\n }\n }\n\n for (const op of operations) {\n for (const schema of collectLazy<SchemaNode>(op, { depth: 'shallow', schema: (node) => node })) {\n visitSchema(schema)\n }\n }\n\n return result\n}\n\n/**\n * Collects the names of all top-level schemas transitively used by a set of operations.\n *\n * An operation uses a schema when its parameters, request body, or responses reference it, directly\n * or through other named schemas. Once a name is added to the result it is not revisited, so\n * reference cycles terminate.\n *\n * Pair it with `include` filters so schemas reachable only from excluded operations stay ungenerated.\n *\n * @example Only generate schemas referenced by included operations\n * ```ts\n * const includedOps = operations.filter((op) => resolver.resolveOptions(op, { options, include }) !== null)\n * const allowed = collectUsedSchemaNames(includedOps, schemas)\n *\n * for (const schema of schemas) {\n * if (schema.name && !allowed.has(schema.name)) continue\n * // generate schema\n * }\n * ```\n */\nexport function collectUsedSchemaNames(operations: ReadonlyArray<OperationNode>, schemas: ReadonlyArray<SchemaNode>): Set<string> {\n return collectUsedSchemaNamesMemo(operations)(schemas)\n}\n\nconst EMPTY_CIRCULAR_SET = new Set<string>()\n\nconst findCircularSchemasMemo = memoize(new WeakMap<ReadonlyArray<SchemaNode>, Set<string>>(), (schemas: ReadonlyArray<SchemaNode>): Set<string> => {\n const graph = new Map<string, Set<string>>()\n\n for (const schema of schemas) {\n if (!schema.name) continue\n graph.set(schema.name, collectReferencedSchemaNames(schema))\n }\n\n const circular = new Set<string>()\n for (const start of graph.keys()) {\n const visited = new Set<string>()\n const stack: Array<string> = [...(graph.get(start) ?? [])]\n while (stack.length > 0) {\n const node = stack.pop()!\n if (node === start) {\n circular.add(start)\n break\n }\n if (visited.has(node)) continue\n visited.add(node)\n\n const next = graph.get(node)\n if (next) for (const r of next) stack.push(r)\n }\n }\n\n return circular\n})\n\n/**\n * Finds every schema that takes part in a circular dependency chain, including direct self-loops.\n *\n * Wrap the returned schema positions in a deferred construct (a lazy getter or `z.lazy(() => …)`) so\n * the generated code does not recurse forever. Refs are followed by name only, so the walk stays\n * linear in the size of the schema graph.\n *\n * @note Call this once on the full graph, then check individual schemas with `containsCircularRef()`.\n */\nexport function findCircularSchemas(schemas: ReadonlyArray<SchemaNode>): Set<string> {\n if (schemas.length === 0) return EMPTY_CIRCULAR_SET\n return findCircularSchemasMemo(schemas)\n}\n\n/**\n * Returns `true` when a schema, or anything nested inside it, references a circular schema.\n *\n * Pass `excludeName` to skip refs to a specific schema, which helps when self-references are handled\n * on their own. Pair it with `findCircularSchemas()` to decide where lazy wrappers go.\n *\n * @note Stops at the first matching circular ref.\n */\nexport function containsCircularRef(\n node: SchemaNode | undefined,\n { circularSchemas, excludeName }: { circularSchemas: ReadonlySet<string>; excludeName?: string },\n): boolean {\n if (!node || circularSchemas.size === 0) return false\n\n for (const _ of collectLazy<true>(node, {\n schema(child) {\n if (child.type !== 'ref') return null\n const name = resolveRefName(child)\n return name && name !== excludeName && circularSchemas.has(name) ? true : null\n },\n })) {\n return true\n }\n\n return false\n}\n","import type { ArraySchemaNode, IntersectionSchemaNode, ObjectSchemaNode, PropertyNode, SchemaNode, UnionSchemaNode } from '../nodes/index.ts'\nimport { objectKey } from './codegen.ts'\n\n/**\n * Converts a child schema to printer output. Plugins instantiate it with their own output type:\n * `string` for the zod and faker printers, `ts.TypeNode` for the TypeScript printer. A printer's\n * `this.transform` fits directly, so its `null` for an empty result carries through to `output`.\n */\nexport type SchemaTransform<TOutput> = (schema: SchemaNode) => TOutput\n\n/**\n * A union or intersection member, or an array or tuple item, paired with its transformed output.\n */\nexport type MappedSchema<TOutput> = {\n /**\n * The original child schema, kept so the printer can read its metadata for leaf formatting.\n */\n schema: SchemaNode\n /**\n * The child schema after being run through the transform.\n */\n output: TOutput\n}\n\n/**\n * An object property paired with its transformed output.\n */\nexport type MappedProperty<TOutput> = {\n /**\n * The property name as written on the schema, before any identifier quoting.\n */\n name: string\n /**\n * The original property node, kept so the printer can read `required`, `schema`, and metadata.\n */\n property: PropertyNode\n /**\n * The property schema after being run through the transform.\n */\n output: TOutput\n}\n\n/**\n * Maps each property of an object schema to its transformed output. Pairs every result with the\n * original property so the printer keeps full control over modifiers, getters, and key syntax.\n *\n * @example\n * ```ts\n * const entries = mapSchemaProperties(node, (schema) => this.transform(schema))\n * // entries: [{ name: 'id', property, output: 'z.number()' }, ...]\n * ```\n */\nexport function mapSchemaProperties<TOutput>(node: ObjectSchemaNode, transform: SchemaTransform<TOutput>): Array<MappedProperty<TOutput>> {\n return node.properties.map((property) => ({ name: property.name, property, output: transform(property.schema) }))\n}\n\n/**\n * Maps each member of a union or intersection schema to its transformed output, pairing every\n * result with the original member.\n */\nexport function mapSchemaMembers<TOutput>(node: UnionSchemaNode | IntersectionSchemaNode, transform: SchemaTransform<TOutput>): Array<MappedSchema<TOutput>> {\n return (node.members ?? []).map((schema) => ({ schema, output: transform(schema) }))\n}\n\n/**\n * Maps each item of an array or tuple schema to its transformed output, pairing every result with\n * the original item.\n */\nexport function mapSchemaItems<TOutput>(node: ArraySchemaNode, transform: SchemaTransform<TOutput>): Array<MappedSchema<TOutput>> {\n return (node.items ?? []).map((schema) => ({ schema, output: transform(schema) }))\n}\n\n/**\n * Emits a lazy getter for a circular-ref property position, `get name() { return body }`. The key\n * is quoted only when it is not a valid identifier. Used by the string printers to defer evaluation\n * of a recursive schema until first access.\n *\n * @example\n * ```ts\n * lazyGetter({ name: 'parent', body: 'z.lazy(() => Pet)' })\n * // \"get parent() { return z.lazy(() => Pet) }\"\n * ```\n */\nexport function lazyGetter({ name, body }: { name: string; body: string }): string {\n return `get ${objectKey(name)}() { return ${body} }`\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA2DA,SAAgB,QAAsB,OAA4B,SAAuD;CACvH,QAAQ,QAAsB;EAC5B,IAAI,MAAM,IAAI,GAAG,GAAG,OAAO,MAAM,IAAI,GAAG;EACxC,MAAM,QAAQ,QAAQ,GAAG;EACzB,MAAM,IAAI,KAAK,KAAK;EACpB,OAAO;CACT;AACF;;;;;;;AC9DA,MAAM,gCAAgB,IAAI,IAAI;CAC5B;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AACF,CAAU;;;;;;;;;;;AA8BV,SAAgB,eAAe,MAAuB;CACpD,IAAI,CAAC,QAAQ,cAAc,IAAI,IAAiB,GAC9C,OAAO;CAET,OAAO,aAAa,IAAI;AAC1B;;;;;;;;;;;;;;AAeA,SAAgB,aAAa,MAAuB;CAClD,OAAO,6BAA6B,KAAK,IAAI;AAC/C;;;;;;;;;;;;;AChIA,SAAgB,YAAY,OAA6D;CACvF,IAAI,UAAU,KAAA,KAAa,UAAU,MAAM,OAAO;CAGlD,OAAO,IAFS,OAAO,KAAK,CAAC,CAAC,QAAQ,OAAO,MAAM,CAAC,CAAC,QAAQ,MAAM,KAElD,EAAE;AACrB;;;;;;;;;;;;;ACFA,SAAgB,WACd,UACA,UAgBI,CAAC,GACG;CACR,MAAM,EAAE,SAAS,SAAS,SAAS,QAAQ,WAAW,SAAS;CAE/D,IAAI,SAAS,WAAW,GAAG,OAAO;CAElC,OAAO,QAAQ,SAAS,KAAK,MAAM,GAAG,SAAS,GAAG,CAAC,CAAC,KAAK,IAAI,EAAE,SAAS;AAC1E;;;;AAKA,SAAS,YAAY,MAAsB;CACzC,IAAI,CAAC,MAAM,OAAO;CAClB,OAAO,KACJ,MAAM,IAAI,CAAC,CACX,KAAK,SAAU,KAAK,KAAK,IAAI,KAAY,SAAS,EAAG,CAAC,CACtD,KAAK,IAAI;AACd;;;;;;;;;;;AAYA,SAAgB,UAAU,MAAsB;CAC9C,OAAO,aAAa,IAAI,IAAI,OAAO,YAAY,IAAI;AACrD;;;;;;;;;;;;AAaA,SAAgB,YAAY,SAAgC;CAC1D,IAAI,QAAQ,WAAW,GAAG,OAAO;CAGjC,OAAO,MAFM,QAAQ,KAAK,UAAU,GAAG,YAAY,KAAK,EAAE,EAAE,CAAC,CAAC,KAAK,IAEnD,EAAE;AACpB;;;;;;;;;;;;;AAcA,SAAgB,UAAU,OAAsB,WAA0C,CAAC,KAAK,GAAG,GAAW;CAC5G,MAAM,CAAC,MAAM,SAAS;CACtB,IAAI,MAAM,WAAW,GAAG,OAAO,GAAG,OAAO;CACzC,IAAI,CAAC,MAAM,MAAM,SAAS,KAAK,SAAS,IAAI,CAAC,GAAG,OAAO,GAAG,OAAO,MAAM,KAAK,IAAI,IAAI;CAGpF,OAAO,GAAG,KAAK,IAFF,MAAM,KAAK,SAAS,GAAG,YAAY,IAAI,EAAE,EAAE,CAAC,CAAC,KAAK,IAEzC,EAAE,IAAI;AAC9B;;;;;;;;;;;;;ACzFA,UAAiB,yBAAyB,SAAuE;CAC/G,IAAI;CAEJ,KAAK,MAAM,UAAU,SAAS;EAC5B,MAAM,eAAe,aAAa,QAAQ,QAAQ;EAClD,IAAI,gBAAgB,CAAC,aAAa,QAAQ,QAAQ,KAAA,GAAW;GAC3D,MAAM,YAAY,aAAa,KAAK,QAAQ;GAC5C,IAAI,aAAa,CAAC,UAAU,MAAM;IAChC,MAAM,aAAa;KACjB,GAAG;KACH,YAAY,CAAC,GAAI,UAAU,cAAc,CAAC,GAAI,GAAI,aAAa,cAAc,CAAC,CAAE;IAClF,CAAC;IACD;GACF;EACF;EACA,IAAI,QAAQ,KAAA,GAAW,MAAM;EAC7B,MAAM;CACR;CAEA,IAAI,QAAQ,KAAA,GAAW,MAAM;AAC/B;;;;;;;;;;;;;ACvBA,SAAgB,WAAW,MAAsB;CAC/C,IAAI,KAAK,UAAU,GAAG;EACpB,MAAM,QAAQ,KAAK;EACnB,MAAM,OAAO,KAAK,KAAK,SAAS;EAChC,IAAK,UAAU,QAAO,SAAS,QAAS,UAAU,OAAO,SAAS,OAAS,UAAU,OAAO,SAAS,KACnG,OAAO,KAAK,MAAM,GAAG,EAAE;CAE3B;CACA,OAAO;AACT;;;;;;;;;;;;;AAcA,SAAgB,UAAU,OAAsD;CAC9E,IAAI,UAAU,KAAA,KAAa,UAAU,MAAM,OAAO;CAGlD,OAAO,IAFM,KAAK,UAAU,WAAW,MAAM,SAAS,CAAC,CACtC,CAAC,CAAC,MAAM,GAAG,EAAE,CAAC,CAAC,QAAQ,QAAQ,IAAG,CAAC,CAAC,QAAQ,MAAM,KACpD,EAAE;AACnB;;;;;;;;;;;;AAaA,SAAgB,eAAe,OAAwB;CACrD,OAAO,GAAG,QAAQ,QAAQ,4BAA4B,cAAc;EAClE,QAAQ,WAAR;GACE,KAAK;GACL,KAAK;GACL,KAAK,MACH,OAAO,KAAK;GACd,KAAK,MACH,OAAO;GACT,KAAK,MACH,OAAO;GACT,KAAK,UACH,OAAO;GACT,KAAK,UACH,OAAO;GACT,SACE,OAAO;EACX;CACF,CAAC;AACH;;;;;;;;;;;;AAaA,SAAgB,eAAe,MAAc,OAAsB,UAAkB;CACnF,MAAM,MAAM,WAAW,IAAI;CAE3B,MAAM,QAAQ,IAAI,MAAM,yBAAyB;CACjD,MAAM,oBAAoB,QAAQ,MAAM;CACxC,MAAM,eAAe,QAAQ;CAC7B,MAAM,UAAU,IACb,QAAQ,UAAU,EAAE,CAAC,CACrB,QAAQ,UAAU,EAAE,CAAC,CACrB,QAAQ,mBAAmB,EAAE;CAEhC,MAAM,EAAE,QAAQ,UAAU,IAAI,OAAO,SAAS,YAAY;CAE1D,IAAI,SAAS,MAAM,OAAO,IAAI,OAAO,GAAG;CAExC,OAAO,OAAO,KAAK,GAAG,KAAK,UAAU,MAAM,IAAI,QAAQ,KAAK,KAAK,UAAU,KAAK,MAAM,GAAG;AAC3F;;;;;;;;;;;;AAaA,SAAgB,gBAAgB,OAAwC;CAStE,OARc,OAAO,QAAQ,KAAK,CAAC,CAChC,KAAK,CAAC,KAAK,SAAS;EACnB,IAAI,QAAQ,QAAQ,OAAO,QAAQ,UACjC,OAAO,GAAG,IAAI,eAAe,gBAAgB,GAA8B,EAAE;EAE/E,OAAO,GAAG,IAAI,IAAI;CACpB,CAAC,CAAC,CACD,OAAO,OACC,CAAC,CAAC,KAAK,KAAK;AACzB;;;;;;;;;;;AAYA,SAAgB,kBAAkB,OAA+B,UAAiC;CAChG,MAAM,QAAQ,MAAM,QAAQ,KAAK,IAAI,QAAQ,MAAM,MAAM,GAAG;CAC5D,IAAI,MAAM,WAAW,KAAM,MAAM,WAAW,KAAK,MAAM,OAAO,IAAK,OAAO;CAC1E,OAAO,GAAG,SAAS,MAAM,GAAG,MAAM,KAAK,QAAQ,EAAE;AACnD;;;;;;AClIA,MAAM,oBAAoB,wBAAQ,IAAI,QAAyC,IAAI,SAA0C;CAC3H,MAAM,uBAAO,IAAI,IAAY;CAC7B,QAAc,MAAM,EAClB,OAAO,OAAO;EACZ,IAAI,MAAM,SAAS,OAAO;GACxB,MAAM,OAAO,eAAe,KAAK;GACjC,IAAI,MAAM,KAAK,IAAI,IAAI;EACzB;CACF,EACF,CAAC;CACD,OAAO;AACT,CAAC;;;;;;;;;;;;;;;;;;;;;AAsBD,SAAgB,6BAA6B,MAA8B,sBAAmB,IAAI,IAAI,GAAgB;CACpH,IAAI,CAAC,MAAM,OAAO;CAClB,KAAK,MAAM,QAAQ,kBAAkB,IAAI,GAAG,IAAI,IAAI,IAAI;CACxD,OAAO;AACT;;;;AAKA,MAAM,6BAA6B,wBAAQ,IAAI,QAA2F,IAAI,QAC5I,wBAAQ,IAAI,QAAgD,IAAI,YAAY,uBAAuB,KAAK,OAAO,CAAC,CAClH;AAEA,SAAS,uBAAuB,YAA0C,SAAiD;CACzH,MAAM,4BAAY,IAAI,IAAwB;CAC9C,KAAK,MAAM,UAAU,SACnB,IAAI,OAAO,MAAM,UAAU,IAAI,OAAO,MAAM,MAAM;CAGpD,MAAM,yBAAS,IAAI,IAAY;CAE/B,SAAS,YAAY,QAA0B;EAC7C,MAAM,aAAa,6BAA6B,MAAM;EACtD,KAAK,MAAM,QAAQ,YACjB,IAAI,CAAC,OAAO,IAAI,IAAI,GAAG;GACrB,OAAO,IAAI,IAAI;GACf,MAAM,cAAc,UAAU,IAAI,IAAI;GACtC,IAAI,aAAa,YAAY,WAAW;EAC1C;CAEJ;CAEA,KAAK,MAAM,MAAM,YACf,KAAK,MAAM,UAAU,YAAwB,IAAI;EAAE,OAAO;EAAW,SAAS,SAAS;CAAK,CAAC,GAC3F,YAAY,MAAM;CAItB,OAAO;AACT;;;;;;;;;;;;;;;;;;;;;AAsBA,SAAgB,uBAAuB,YAA0C,SAAiD;CAChI,OAAO,2BAA2B,UAAU,CAAC,CAAC,OAAO;AACvD;AAEA,MAAM,qCAAqB,IAAI,IAAY;AAE3C,MAAM,0BAA0B,wBAAQ,IAAI,QAAgD,IAAI,YAAoD;CAClJ,MAAM,wBAAQ,IAAI,IAAyB;CAE3C,KAAK,MAAM,UAAU,SAAS;EAC5B,IAAI,CAAC,OAAO,MAAM;EAClB,MAAM,IAAI,OAAO,MAAM,6BAA6B,MAAM,CAAC;CAC7D;CAEA,MAAM,2BAAW,IAAI,IAAY;CACjC,KAAK,MAAM,SAAS,MAAM,KAAK,GAAG;EAChC,MAAM,0BAAU,IAAI,IAAY;EAChC,MAAM,QAAuB,CAAC,GAAI,MAAM,IAAI,KAAK,KAAK,CAAC,CAAE;EACzD,OAAO,MAAM,SAAS,GAAG;GACvB,MAAM,OAAO,MAAM,IAAI;GACvB,IAAI,SAAS,OAAO;IAClB,SAAS,IAAI,KAAK;IAClB;GACF;GACA,IAAI,QAAQ,IAAI,IAAI,GAAG;GACvB,QAAQ,IAAI,IAAI;GAEhB,MAAM,OAAO,MAAM,IAAI,IAAI;GAC3B,IAAI,MAAM,KAAK,MAAM,KAAK,MAAM,MAAM,KAAK,CAAC;EAC9C;CACF;CAEA,OAAO;AACT,CAAC;;;;;;;;;;AAWD,SAAgB,oBAAoB,SAAiD;CACnF,IAAI,QAAQ,WAAW,GAAG,OAAO;CACjC,OAAO,wBAAwB,OAAO;AACxC;;;;;;;;;AAUA,SAAgB,oBACd,MACA,EAAE,iBAAiB,eACV;CACT,IAAI,CAAC,QAAQ,gBAAgB,SAAS,GAAG,OAAO;CAEhD,KAAK,MAAM,KAAK,YAAkB,MAAM,EACtC,OAAO,OAAO;EACZ,IAAI,MAAM,SAAS,OAAO,OAAO;EACjC,MAAM,OAAO,eAAe,KAAK;EACjC,OAAO,QAAQ,SAAS,eAAe,gBAAgB,IAAI,IAAI,IAAI,OAAO;CAC5E,EACF,CAAC,GACC,OAAO;CAGT,OAAO;AACT;;;;;;;;;;;;;AC5HA,SAAgB,oBAA6B,MAAwB,WAAqE;CACxI,OAAO,KAAK,WAAW,KAAK,cAAc;EAAE,MAAM,SAAS;EAAM;EAAU,QAAQ,UAAU,SAAS,MAAM;CAAE,EAAE;AAClH;;;;;AAMA,SAAgB,iBAA0B,MAAgD,WAAmE;CAC3J,QAAQ,KAAK,WAAW,CAAC,EAAA,CAAG,KAAK,YAAY;EAAE;EAAQ,QAAQ,UAAU,MAAM;CAAE,EAAE;AACrF;;;;;AAMA,SAAgB,eAAwB,MAAuB,WAAmE;CAChI,QAAQ,KAAK,SAAS,CAAC,EAAA,CAAG,KAAK,YAAY;EAAE;EAAQ,QAAQ,UAAU,MAAM;CAAE,EAAE;AACnF;;;;;;;;;;;;AAaA,SAAgB,WAAW,EAAE,MAAM,QAAgD;CACjF,OAAO,OAAO,UAAU,IAAI,EAAE,cAAc,KAAK;AACnD"}
import "./rolldown-runtime-CNktS9qV.js";
import { hash } from "node:crypto";
import path from "node:path";
//#region src/constants.ts
const visitorDepths = {
shallow: "shallow",
deep: "deep"
};
/**
* Schema type discriminators used by all AST schema nodes.
*
* Each value is a stable discriminator across the AST (for example `schema.type === schemaTypes.object`).
*/
const schemaTypes = {
/**
* Text value.
*/
string: "string",
/**
* Floating-point number (`float`, `double`).
*/
number: "number",
/**
* Whole number (`int32`). Use `bigint` for `int64`.
*/
integer: "integer",
/**
* 64-bit integer (`int64`). Only used when `integerType` is set to `'bigint'`.
*/
bigint: "bigint",
/**
* Boolean value.
*/
boolean: "boolean",
/**
* Explicit null value.
*/
null: "null",
/**
* Any value (no type restriction).
*/
any: "any",
/**
* Unknown value (must be narrowed before usage).
*/
unknown: "unknown",
/**
* No return value (`void`).
*/
void: "void",
/**
* Object with named properties.
*/
object: "object",
/**
* Sequential list of items.
*/
array: "array",
/**
* Fixed-length list with position-specific items.
*/
tuple: "tuple",
/**
* "One of" multiple schema members.
*/
union: "union",
/**
* "All of" multiple schema members.
*/
intersection: "intersection",
/**
* Enum schema.
*/
enum: "enum",
/**
* Reference to another schema.
*/
ref: "ref",
/**
* Calendar date (for example `2026-03-24`).
*/
date: "date",
/**
* Date-time value (for example `2026-03-24T09:00:00Z`).
*/
datetime: "datetime",
/**
* Time-only value (for example `09:00:00`).
*/
time: "time",
/**
* UUID value.
*/
uuid: "uuid",
/**
* Email address value.
*/
email: "email",
/**
* URL value.
*/
url: "url",
/**
* IPv4 address value.
*/
ipv4: "ipv4",
/**
* IPv6 address value.
*/
ipv6: "ipv6",
/**
* Binary/blob value.
*/
blob: "blob",
/**
* Impossible value (`never`).
*/
never: "never"
};
//#endregion
//#region src/guards.ts
/**
* Narrows a `SchemaNode` to the variant that matches `type`.
*
* @example
* ```ts
* const schema = createSchema({ type: 'string' })
* const stringNode = narrowSchema(schema, 'string') // StringSchemaNode | null
* ```
*/
function narrowSchema(node, type) {
return node?.type === type ? node : null;
}
/**
* Narrows an `OperationNode` to an `HttpOperationNode` so `method` and `path` are present.
*
* @example
* ```ts
* if (isHttpOperationNode(node)) {
* console.log(node.method, node.path)
* }
* ```
*/
function isHttpOperationNode(node) {
return node.protocol === "http" || node.method !== void 0 && node.path !== void 0;
}
//#endregion
//#region src/defineNode.ts
/**
* Visitor callback names, one per traversable node kind, in traversal order.
* Kept in sync with the keys of `Visitor` in `visitor.ts`.
*/
const visitorKeys = [
"input",
"output",
"operation",
"schema",
"property",
"parameter",
"response"
];
/**
* Builds a type guard that matches nodes of the given `kind`.
*/
function isKind(kind) {
return (node) => node?.kind === kind;
}
/**
* Defines a node once and derives its `create` builder, `is` guard, and traversal
* metadata. `create` merges `defaults`, the `build` hook (or the raw input), and the
* `kind`, so node construction lives in one place without scattered `as` casts.
*
* @example Simple node
* ```ts
* const importDef = defineNode<ImportNode>({ kind: 'Import' })
* const createImport = importDef.create
* ```
*
* @example Node with a build hook
* ```ts
* const propertyDef = defineNode<PropertyNode, UserPropertyNode>({
* kind: 'Property',
* build: (props) => ({ ...props, required: props.required ?? false }),
* children: ['schema'],
* visitorKey: 'property',
* })
* ```
*/
function defineNode(config) {
const { kind, defaults, build, children, visitorKey } = config;
function create(input) {
const base = build ? build(input) : input;
const node = {
kind,
...defaults,
...base
};
node.kind = kind;
return node;
}
return {
kind,
create,
is: isKind(kind),
children,
visitorKey
};
}
//#endregion
//#region src/nodes/code.ts
/**
* Definition for the {@link ConstNode}.
*/
const constDef = defineNode({ kind: "Const" });
/**
* Definition for the {@link TypeNode}.
*/
const typeDef = defineNode({ kind: "Type" });
/**
* Definition for the {@link FunctionNode}.
*/
const functionDef = defineNode({ kind: "Function" });
/**
* Definition for the {@link ArrowFunctionNode}.
*/
const arrowFunctionDef = defineNode({ kind: "ArrowFunction" });
/**
* Definition for the {@link TextNode}.
*/
const textDef = defineNode({
kind: "Text",
build: (value) => ({ value })
});
/**
* Definition for the {@link BreakNode}.
*/
const breakDef = defineNode({
kind: "Break",
build: () => ({})
});
/**
* Definition for the {@link JsxNode}.
*/
const jsxDef = defineNode({
kind: "Jsx",
build: (value) => ({ value })
});
/**
* Creates a `ConstNode` representing a TypeScript `const` declaration.
*
* @example Exported constant with type and `as const`
* ```ts
* createConst({ name: 'pets', export: true, type: 'Pet[]', asConst: true })
* // export const pets: Pet[] = ... as const
* ```
*/
const createConst = constDef.create;
/**
* Creates a `TypeNode` representing a TypeScript `type` alias declaration.
*
* @example
* ```ts
* createType({ name: 'Pet', export: true })
* // export type Pet = ...
* ```
*/
const createType = typeDef.create;
/**
* Creates a `FunctionNode` representing a TypeScript `function` declaration.
*
* @example
* ```ts
* createFunction({ name: 'fetchPet', export: true, async: true, returnType: 'Pet' })
* // export async function fetchPet(): Promise<Pet> { ... }
* ```
*/
const createFunction = functionDef.create;
/**
* Creates an `ArrowFunctionNode` representing a TypeScript arrow function.
*
* @example
* ```ts
* createArrowFunction({ name: 'double', export: true, params: 'n: number', singleLine: true })
* // export const double = (n: number) => ...
* ```
*/
const createArrowFunction = arrowFunctionDef.create;
/**
* Creates a {@link TextNode} representing a raw string fragment in the source output.
*
* @example
* ```ts
* createText('return fetch(id)')
* // { kind: 'Text', value: 'return fetch(id)' }
* ```
*/
const createText = textDef.create;
/**
* Creates a {@link BreakNode} representing a line break in the source output.
*
* @example
* ```ts
* createBreak()
* // { kind: 'Break' }
* ```
*/
function createBreak() {
return breakDef.create();
}
/**
* Creates a {@link JsxNode} representing a raw JSX fragment in the source output.
*
* @example
* ```ts
* createJsx('<>\n <a href={href}>Open</a>\n</>')
* // { kind: 'Jsx', value: '<>\n <a href={href}>Open</a>\n</>' }
* ```
*/
const createJsx = jsxDef.create;
//#endregion
//#region src/nodes/content.ts
/**
* Definition for the {@link ContentNode}.
*/
const contentDef = defineNode({
kind: "Content",
children: ["schema"]
});
/**
* Creates a `ContentNode` for a single request-body or response content type.
*/
const createContent = contentDef.create;
//#endregion
//#region ../../internals/utils/src/casing.ts
/**
* Shared implementation for camelCase and PascalCase conversion.
* Splits on common word boundaries (spaces, hyphens, underscores, dots, slashes, colons)
* and capitalizes each word according to `pascal`.
*
* When `pascal` is `true` the first word is also capitalized (PascalCase), otherwise only subsequent words are.
*/
function toCamelOrPascal(text, pascal) {
return text.trim().replace(/([a-z\d])([A-Z])/g, "$1 $2").replace(/([A-Z]+)([A-Z][a-z])/g, "$1 $2").replace(/(\d)([a-z])/g, "$1 $2").split(/[\s\-_./\\:]+/).filter(Boolean).map((word, i) => {
if (word.length > 1 && word === word.toUpperCase()) return word;
return (i === 0 && !pascal ? word.charAt(0).toLowerCase() : word.charAt(0).toUpperCase()) + word.slice(1);
}).join("").replace(/[^a-zA-Z0-9]/g, "");
}
/**
* Converts `text` to PascalCase.
*
* @example Word boundaries
* `pascalCase('hello-world') // 'HelloWorld'`
*
* @example With a suffix
* `pascalCase('tag', { suffix: 'schema' }) // 'TagSchema'`
*/
function pascalCase(text, { prefix = "", suffix = "" } = {}) {
return toCamelOrPascal(`${prefix} ${text} ${suffix}`, true);
}
//#endregion
//#region ../../internals/utils/src/fs.ts
/**
* Strips the file extension from a path or file name.
* Only removes the last `.ext` segment when the dot is not part of a directory name.
*
* @example
* trimExtName('petStore.ts') // 'petStore'
* trimExtName('/src/models/pet.ts') // '/src/models/pet'
* trimExtName('/project.v2/gen/pet.ts') // '/project.v2/gen/pet'
* trimExtName('noExtension') // 'noExtension'
*/
function trimExtName(text) {
const dotIndex = text.lastIndexOf(".");
if (dotIndex > 0 && !text.includes("/", dotIndex)) return text.slice(0, dotIndex);
return text;
}
//#endregion
//#region src/utils/extractStringsFromNodes.ts
/**
* Extracts all string content from a `CodeNode` tree recursively.
*
* Collects text node values, identifier references in string fields (`params`, `generics`, `returnType`, `type`),
* and nested node content. Used to build the full source string for import filtering.
*/
function extractStringsFromNodes(nodes) {
if (!nodes?.length) return "";
const collected = [];
for (const node of nodes) {
if (typeof node === "string") {
if (node) collected.push(node);
continue;
}
if (node.kind === "Text") {
if (node.value) collected.push(node.value);
continue;
}
if (node.kind === "Break") continue;
if (node.kind === "Jsx") {
if (node.value) collected.push(node.value);
continue;
}
const parts = [];
if ("params" in node && node.params) parts.push(node.params);
if ("generics" in node && node.generics) parts.push(Array.isArray(node.generics) ? node.generics.join(", ") : node.generics);
if ("returnType" in node && node.returnType) parts.push(node.returnType);
if ("type" in node && typeof node.type === "string") parts.push(node.type);
const nested = extractStringsFromNodes(node.nodes);
if (nested) parts.push(nested);
if (parts.length) collected.push(parts.join("\n"));
}
return collected.join("\n");
}
//#endregion
//#region src/utils/fileMerge.ts
function sourceKey(source) {
return `${source.name ?? extractStringsFromNodes(source.nodes)}:${source.isExportable ?? false}:${source.isTypeOnly ?? false}`;
}
function pathTypeKey(path, isTypeOnly) {
return `${path}:${isTypeOnly ?? false}`;
}
function exportKey(path, name, isTypeOnly, asAlias) {
return `${path}:${name ?? ""}:${isTypeOnly ?? false}:${asAlias ?? ""}`;
}
function importKey(path, name, isTypeOnly) {
return `${path}:${name ?? ""}:${isTypeOnly ?? false}`;
}
/**
* Computes a multi-level sort key for exports and imports:
* non-array names first (wildcards/namespace aliases). Type-only before value. Alphabetical path. Unnamed before named.
*/
function sortKey(node) {
const isArray = Array.isArray(node.name) ? "1" : "0";
const typeOnly = node.isTypeOnly ? "0" : "1";
const hasName = node.name != null ? "1" : "0";
const name = Array.isArray(node.name) ? node.name.toSorted().join("\0") : node.name ?? "";
return `${isArray}:${typeOnly}:${node.path}:${hasName}:${name}`;
}
/**
* Deduplicates `SourceNode` objects by `name + isExportable + isTypeOnly`, keeping the first of each
* key. Unnamed sources fall back to their extracted node strings as the name part of the key. Returns
* the deduplicated array in original order.
*/
function combineSources(sources) {
const seen = /* @__PURE__ */ new Map();
for (const source of sources) {
const key = sourceKey(source);
if (!seen.has(key)) seen.set(key, source);
}
return [...seen.values()];
}
/**
* Merges `incoming` names into `existing`, preserving order and dropping duplicates.
*
* Shared by `combineExports` and `combineImports` for the same-path name-merge case.
*/
function mergeNameArrays(existing, incoming) {
const merged = new Set(existing);
for (const name of incoming) merged.add(name);
return [...merged];
}
/**
* Deduplicates and merges `ExportNode` objects by path and type.
*
* Named exports with the same path and `isTypeOnly` flag have their names merged into a single export.
* Non-array exports are deduplicated by exact identity. Returns a sorted, deduplicated array.
*/
function combineExports(exports) {
const result = [];
const namedByPath = /* @__PURE__ */ new Map();
const seen = /* @__PURE__ */ new Set();
const keyed = exports.map((node) => ({
node,
key: sortKey(node)
}));
keyed.sort((a, b) => a.key < b.key ? -1 : a.key > b.key ? 1 : 0);
for (const { node: curr } of keyed) {
const { name, path, isTypeOnly, asAlias } = curr;
if (Array.isArray(name)) {
if (!name.length) continue;
const key = pathTypeKey(path, isTypeOnly);
const existing = namedByPath.get(key);
if (existing && Array.isArray(existing.name)) existing.name = mergeNameArrays(existing.name, name);
else {
const newItem = {
...curr,
name: [...new Set(name)]
};
result.push(newItem);
namedByPath.set(key, newItem);
}
} else {
const key = exportKey(path, name, isTypeOnly, asAlias);
if (!seen.has(key)) {
result.push(curr);
seen.add(key);
}
}
}
return result;
}
/**
* Deduplicates and merges `ImportNode` objects, filtering out unused imports.
*
* Retains imports that are referenced in `source` or re-exported. Imports with the same path and
* `isTypeOnly` flag have their names merged. Returns a sorted, deduplicated, filtered array.
*/
function combineImports(imports, exports, source) {
const exportedNames = new Set(exports.flatMap((e) => Array.isArray(e.name) ? e.name : e.name ? [e.name] : []));
const isUsed = (importName) => !source || source.includes(importName) || exportedNames.has(importName);
const importNameMemo = /* @__PURE__ */ new Map();
const canonicalizeName = (n) => {
if (typeof n === "string") return n;
const key = `${n.propertyName}:${n.name ?? ""}`;
if (!importNameMemo.has(key)) importNameMemo.set(key, n);
return importNameMemo.get(key);
};
const pathsWithUsedNamedImport = /* @__PURE__ */ new Set();
for (const node of imports) {
if (!Array.isArray(node.name)) continue;
if (node.name.some((item) => typeof item === "string" ? isUsed(item) : isUsed(item.name ?? item.propertyName))) pathsWithUsedNamedImport.add(node.path);
}
const result = [];
const namedByPath = /* @__PURE__ */ new Map();
const seen = /* @__PURE__ */ new Set();
const keyed = imports.map((node) => ({
node,
key: sortKey(node)
}));
keyed.sort((a, b) => a.key < b.key ? -1 : a.key > b.key ? 1 : 0);
for (const { node: curr } of keyed) {
if (curr.path === curr.root) continue;
const { path, isTypeOnly } = curr;
let { name } = curr;
if (Array.isArray(name)) {
name = [...new Set(name.map(canonicalizeName))].filter((item) => typeof item === "string" ? isUsed(item) : isUsed(item.name ?? item.propertyName));
if (!name.length) continue;
const key = pathTypeKey(path, isTypeOnly);
const existing = namedByPath.get(key);
if (existing && Array.isArray(existing.name)) existing.name = mergeNameArrays(existing.name, name);
else {
const newItem = {
...curr,
name
};
result.push(newItem);
namedByPath.set(key, newItem);
}
} else {
if (name && !isUsed(name) && !pathsWithUsedNamedImport.has(path)) continue;
const key = importKey(path, name, isTypeOnly);
if (!seen.has(key)) {
result.push(curr);
seen.add(key);
}
}
}
return result;
}
//#endregion
//#region src/nodes/file.ts
/**
* Definition for the {@link ImportNode}.
*/
const importDef = defineNode({ kind: "Import" });
/**
* Definition for the {@link ExportNode}.
*/
const exportDef = defineNode({ kind: "Export" });
/**
* Definition for the {@link SourceNode}.
*/
const sourceDef = defineNode({ kind: "Source" });
/**
* Definition for the {@link FileNode}. The fully resolved builder lives in
* `createFile`, so this definition only supplies the guard.
*/
const fileDef = defineNode({ kind: "File" });
/**
* Creates an `ImportNode` representing a language-agnostic import/dependency declaration.
*
* @example Named import
* ```ts
* createImport({ name: ['useState'], path: 'react' })
* // import { useState } from 'react'
* ```
*/
const createImport = importDef.create;
/**
* Creates an `ExportNode` representing a language-agnostic export/public API declaration.
*
* @example Named export
* ```ts
* createExport({ name: ['Pet'], path: './Pet' })
* // export { Pet } from './Pet'
* ```
*/
const createExport = exportDef.create;
/**
* Creates a `SourceNode` representing a fragment of source code within a file.
*
* @example
* ```ts
* createSource({ name: 'Pet', nodes: [createText('export type Pet = { id: number }')], isExportable: true })
* ```
*/
const createSource = sourceDef.create;
/**
* Creates a fully resolved `FileNode` from a file input descriptor.
*
* Computes:
* - `id` SHA256 hash of the file path
* - `name` `baseName` without extension
* - `extname` extension extracted from `baseName`
*
* Deduplicates:
* - `sources` via `combineSources`
* - `exports` via `combineExports`
* - `imports` via `combineImports` (also filters unused imports)
*
* @throws {Error} when `baseName` has no extension.
*
* @example
* ```ts
* const file = createFile({
* baseName: 'petStore.ts',
* path: 'src/models/petStore.ts',
* sources: [createSource({ name: 'Pet', nodes: [createText('export type Pet = { id: number }')] })],
* imports: [createImport({ name: ['z'], path: 'zod' })],
* exports: [createExport({ name: ['Pet'], path: './petStore' })],
* })
* // file.id = SHA256 hash of 'src/models/petStore.ts'
* // file.name = 'petStore'
* // file.extname = '.ts'
* ```
*
* @example Copy a real file into the output verbatim
* ```ts
* const file = createFile({
* baseName: 'client.ts',
* path: 'src/gen/client.ts',
* copy: '/abs/path/to/templates/client.ts',
* })
* ```
*/
function createFile(input) {
const extname = path.extname(input.baseName) || (input.baseName.startsWith(".") ? input.baseName : "");
if (!extname) throw new Error(`No extname found for ${input.baseName}`);
const resolvedExports = input.exports?.length ? combineExports(input.exports) : [];
let resolvedImports = [];
if (input.imports?.length) {
const source = extractStringsFromNodes((input.sources ?? []).flatMap((item) => item.nodes ?? [])) || void 0;
const combinedImports = combineImports(input.imports, resolvedExports, source);
const localNames = new Set((input.sources ?? []).map((item) => item.name).filter((name) => Boolean(name)));
const nameOf = (item) => typeof item === "string" ? item : item.name ?? item.propertyName;
resolvedImports = combinedImports.filter((imp) => imp.path !== input.path).flatMap((imp) => {
if (!Array.isArray(imp.name)) return typeof imp.name === "string" && localNames.has(imp.name) ? [] : [imp];
const kept = imp.name.filter((item) => !localNames.has(nameOf(item)));
if (!kept.length) return [];
return [kept.length === imp.name.length ? imp : {
...imp,
name: kept
}];
});
}
const resolvedSources = input.sources?.length ? combineSources(input.sources) : [];
return {
kind: "File",
...input,
id: hash("sha256", input.path, "hex"),
name: trimExtName(input.baseName),
extname,
imports: resolvedImports,
exports: resolvedExports,
sources: resolvedSources,
meta: input.meta ?? {}
};
}
//#endregion
//#region src/nodes/input.ts
/**
* Definition for the {@link InputNode}.
*/
const inputDef = defineNode({
kind: "Input",
defaults: {
schemas: [],
operations: [],
meta: {
circularNames: [],
enumNames: []
}
},
children: ["schemas", "operations"],
visitorKey: "input"
});
/**
* Creates an `InputNode`. Pass `stream: true` for the streaming variant whose `schemas` and
* `operations` are `AsyncIterable` sources. Otherwise it builds the eager variant with array
* `schemas`/`operations`. Both variants get the defaulted `meta`.
*
* @example Eager
* ```ts
* const input = createInput()
* // { kind: 'Input', schemas: [], operations: [] }
* ```
*
* @example Streaming
* ```ts
* const node = createInput({ stream: true, schemas: schemasIterable, operations: operationsIterable, meta: { title: 'My API' } })
* ```
*/
function createInput(options = {}) {
const { stream, ...overrides } = options;
if (stream) return {
kind: "Input",
meta: {
circularNames: [],
enumNames: []
},
...overrides
};
return inputDef.create(overrides);
}
//#endregion
//#region src/nodes/requestBody.ts
/**
* Definition for the {@link RequestBodyNode}. Content entries are built upfront with
* {@link createContent}, mirroring how `parameters` and `responses` take prebuilt nodes.
*/
const requestBodyDef = defineNode({
kind: "RequestBody",
children: ["content"]
});
/**
* Creates a `RequestBodyNode`.
*/
const createRequestBody = requestBodyDef.create;
//#endregion
//#region src/nodes/operation.ts
/**
* Definition for the {@link OperationNode}. HTTP operations (those carrying both
* `method` and `path`) are tagged with `protocol: 'http'`, and the request body is
* normalized into a `RequestBodyNode`.
*/
const operationDef = defineNode({
kind: "Operation",
build: (props) => {
const { requestBody, ...rest } = props;
const isHttp = rest.method !== void 0 && rest.path !== void 0;
return {
tags: [],
parameters: [],
responses: [],
...rest,
...isHttp ? { protocol: "http" } : {},
requestBody: requestBody ? createRequestBody(requestBody) : void 0
};
},
children: [
"parameters",
"requestBody",
"responses"
],
visitorKey: "operation"
});
function createOperation(props) {
return operationDef.create(props);
}
//#endregion
//#region src/nodes/output.ts
/**
* Definition for the {@link OutputNode}.
*/
const outputDef = defineNode({
kind: "Output",
defaults: { files: [] },
visitorKey: "output"
});
/**
* Creates an `OutputNode` with a stable default for `files`.
*
* @example
* ```ts
* const output = createOutput()
* // { kind: 'Output', files: [] }
* ```
*/
function createOutput(overrides = {}) {
return outputDef.create(overrides);
}
//#endregion
//#region src/optionality.ts
/**
* Generic JSON Schema optionality: a non-required field is optional, and a
* non-required nullable field is nullish.
*/
function optionality(schema, required) {
const nullable = schema.nullable ?? false;
return {
...schema,
optional: !required && !nullable ? true : void 0,
nullish: !required && nullable ? true : void 0
};
}
//#endregion
//#region src/nodes/parameter.ts
/**
* Definition for the {@link ParameterNode}. `required` defaults to `false`, and the schema's
* `optional`/`nullish` flags are derived from it through {@link optionality}.
*/
const parameterDef = defineNode({
kind: "Parameter",
build: (props) => {
const required = props.required ?? false;
return {
...props,
required,
schema: optionality(props.schema, required)
};
},
children: ["schema"],
visitorKey: "parameter"
});
/**
* Creates a `ParameterNode`.
*
* @example
* ```ts
* const param = createParameter({
* name: 'petId',
* in: 'path',
* required: true,
* schema: createSchema({ type: 'string' }),
* })
* ```
*/
const createParameter = parameterDef.create;
//#endregion
//#region src/nodes/property.ts
/**
* Definition for the {@link PropertyNode}. `required` defaults to `false`, and the schema's
* `optional`/`nullish` flags are derived from it through {@link optionality}.
*/
const propertyDef = defineNode({
kind: "Property",
build: (props) => {
const required = props.required ?? false;
return {
...props,
required,
schema: optionality(props.schema, required)
};
},
children: ["schema"],
visitorKey: "property"
});
/**
* Creates a `PropertyNode`.
*
* @example
* ```ts
* const property = createProperty({
* name: 'status',
* required: true,
* schema: createSchema({ type: 'string', nullable: true }),
* })
* // required=true, no optional/nullish
* ```
*/
const createProperty = propertyDef.create;
//#endregion
//#region src/nodes/response.ts
/**
* Definition for the {@link ResponseNode}. A single legacy `schema` (with optional
* `mediaType`/`keysToOmit`) is normalized into one `content` entry.
*/
const responseDef = defineNode({
kind: "Response",
build: (props) => {
const { schema, mediaType, keysToOmit, content, ...rest } = props;
const entries = content ?? (schema ? [createContent({
contentType: mediaType ?? "application/json",
schema,
keysToOmit: keysToOmit ?? null
})] : void 0);
return {
...rest,
content: entries
};
},
children: ["content"],
visitorKey: "response"
});
/**
* Creates a `ResponseNode`.
*
* @example
* ```ts
* const response = createResponse({
* statusCode: '200',
* content: [createContent({ contentType: 'application/json', schema: createSchema({ type: 'object', properties: [] }) })],
* })
* ```
*/
const createResponse = responseDef.create;
//#endregion
//#region src/nodes/schema.ts
/**
* Maps schema `type` to its underlying `primitive`.
* Primitive types map to themselves and special string formats map to `'string'`.
* Any type not listed here (such as `ref`, `enum`, `union`, `intersection`, `tuple`, `ipv4`, `ipv6`, `blob`) has no `primitive`.
*/
const TYPE_TO_PRIMITIVE = {
string: "string",
number: "number",
integer: "integer",
bigint: "bigint",
boolean: "boolean",
null: "null",
any: "any",
unknown: "unknown",
void: "void",
never: "never",
object: "object",
array: "array",
date: "date",
uuid: "string",
email: "string",
url: "string",
datetime: "string",
time: "string"
};
/**
* Definition for the {@link SchemaNode}. Object schemas default `properties` to an
* empty array, and `primitive` is inferred from `type` when not explicitly provided.
*/
const schemaDef = defineNode({
kind: "Schema",
build: (props) => {
if (props.type === "object") return {
properties: [],
primitive: "object",
...props
};
return {
primitive: TYPE_TO_PRIMITIVE[props.type],
...props
};
},
children: [
"properties",
"items",
"members",
"additionalProperties"
],
visitorKey: "schema"
});
function createSchema(props) {
return schemaDef.create(props);
}
//#endregion
//#region src/registry.ts
/**
* Every node definition. Adding a node means adding its `defineNode` to one
* `nodes/*.ts` file and listing it here. The visitor tables in `visitor.ts` derive from it.
*/
const nodeDefs = [
inputDef,
outputDef,
operationDef,
requestBodyDef,
contentDef,
responseDef,
schemaDef,
propertyDef,
parameterDef,
constDef,
typeDef,
functionDef,
arrowFunctionDef,
textDef,
breakDef,
jsxDef,
importDef,
exportDef,
sourceDef,
fileDef
];
//#endregion
//#region src/visitor.ts
/**
* Child node fields per node kind, in traversal order (Babel's `VISITOR_KEYS`).
* Derived from each definition's `children`.
*/
const VISITOR_KEYS = Object.fromEntries(nodeDefs.flatMap((def) => def.children ? [[def.kind, def.children]] : []));
/**
* Maps a node kind to the matching visitor callback name. Derived from each
* definition's `visitorKey`.
*/
const VISITOR_KEY_BY_KIND = Object.fromEntries(nodeDefs.flatMap((def) => def.visitorKey ? [[def.kind, def.visitorKey]] : []));
/**
* Creates a small async concurrency limiter.
*
* At most `concurrency` tasks are in flight at once. Extra tasks are queued.
*
* @example
* ```ts
* const limit = createLimit(2)
* for (const task of [taskA, taskB, taskC]) {
* await limit(() => task())
* }
* // only 2 tasks run at the same time
* ```
*/
function createLimit(concurrency) {
let active = 0;
const queue = [];
function next() {
if (active < concurrency && queue.length > 0) {
active++;
queue.shift()();
}
}
return function limit(fn) {
return new Promise((resolve, reject) => {
queue.push(() => {
Promise.resolve(fn()).then(resolve, reject).finally(() => {
active--;
next();
});
});
next();
});
};
}
const visitorKeysByKind = VISITOR_KEYS;
/**
* Returns `true` when `value` is an AST node (an object carrying a `kind`).
*/
function isNode(value) {
return typeof value === "object" && value !== null && typeof value.kind === "string";
}
/**
* Returns the immediate traversable children of `node` based on {@link VISITOR_KEYS}.
*
* `Schema` children are only included when `recurse` is `true`. Shallow mode skips them.
*
* @example
* ```ts
* const children = getChildren(operationNode, true)
* // returns parameters, the request body, and responses
* ```
*/
function* getChildren(node, recurse) {
if (node.kind === "Schema" && !recurse) return;
const keys = visitorKeysByKind[node.kind];
if (!keys) return;
const record = node;
for (const key of keys) {
const value = record[key];
if (Array.isArray(value)) {
for (const item of value) if (isNode(item)) yield item;
} else if (isNode(value)) yield value;
}
}
/**
* Runs the visitor callback that matches `node.kind` with the traversal
* context. The result is a replacement node, a collected value, or `undefined`
* when no callback is registered for the kind.
*
* Shared by `walk`, `transform`, and `collectLazy` so node-kind dispatch lives
* in one place. `TResult` is the caller's expected return: the same node type
* for `transform`, the collected value type for `collectLazy`, ignored for `walk`.
*/
function applyVisitor(node, visitor, parent) {
const key = VISITOR_KEY_BY_KIND[node.kind];
if (!key) return void 0;
const fn = visitor[key];
return fn?.(node, { parent });
}
/**
* Async depth-first traversal for side effects. Visitor return values are
* ignored. Use `transform` when you want to rewrite nodes.
*
* Sibling nodes at each depth run concurrently up to `options.concurrency`
* (defaults to `WALK_CONCURRENCY`). Higher values overlap I/O-bound visitor
* work. Lower values reduce memory pressure.
*
* @example Log every operation
* ```ts
* await walk(root, {
* operation(node) {
* console.log(node.operationId)
* },
* })
* ```
*
* @example Only visit the root node
* ```ts
* await walk(root, { depth: 'shallow', input: () => {} })
* ```
*/
async function walk(node, options) {
return _walk(node, options, (options.depth ?? visitorDepths.deep) === visitorDepths.deep, createLimit(options.concurrency ?? 30), void 0);
}
async function _walk(node, visitor, recurse, limit, parent) {
await limit(() => applyVisitor(node, visitor, parent));
let pending;
for (const child of getChildren(node, recurse)) (pending ??= []).push(_walk(child, visitor, recurse, limit, node));
if (pending) await Promise.all(pending);
}
function transform(node, options) {
const { depth, parent, ...visitor } = options;
return transformNode(node, visitor, (depth ?? visitorDepths.deep) === visitorDepths.deep, parent);
}
/**
* Visits a single node, then immutably rebuilds its children. Returns the original
* reference when neither the visitor nor the child rebuild changed anything, so callers
* can detect "nothing changed" by identity and ancestors avoid reallocating.
*/
function transformNode(node, visitor, recurse, parent) {
return transformChildren(applyVisitor(node, visitor, parent) ?? node, visitor, recurse);
}
/**
* Immutably rebuilds a node's children using {@link VISITOR_KEYS}, transforming
* each child node and leaving non-node values (e.g. `additionalProperties: true`) intact.
* `Schema` children are skipped in shallow mode.
*/
function transformChildren(node, visitor, recurse) {
if (node.kind === "Schema" && !recurse) return node;
const keys = visitorKeysByKind[node.kind];
if (!keys) return node;
const record = node;
let updates;
for (const key of keys) {
if (!(key in record)) continue;
const value = record[key];
if (Array.isArray(value)) {
let mapped;
for (const [i, item] of value.entries()) {
const next = isNode(item) ? transformNode(item, visitor, recurse, node) : item;
if (mapped) {
mapped.push(next);
continue;
}
if (next !== item) mapped = [...value.slice(0, i), next];
}
if (mapped) (updates ??= {})[key] = mapped;
} else if (isNode(value)) {
const next = transformNode(value, visitor, recurse, node);
if (next !== value) (updates ??= {})[key] = next;
}
}
return updates ? {
...node,
...updates
} : node;
}
/**
* Lazy depth-first collection pass. Yields every non-null value returned by
* the visitor callbacks. Use `collect` for the eager array form.
*
* @example Collect every operationId
* ```ts
* const ids: string[] = []
* for (const id of collectLazy<string>(root, {
* operation(node) {
* return node.operationId
* },
* })) {
* ids.push(id)
* }
* ```
*/
function* collectLazy(node, options) {
const { depth, parent, ...visitor } = options;
yield* collectNode(node, visitor, (depth ?? visitorDepths.deep) === visitorDepths.deep, parent);
}
function* collectNode(node, visitor, recurse, parent) {
const v = applyVisitor(node, visitor, parent);
if (v != null) yield v;
for (const child of getChildren(node, recurse)) yield* collectNode(child, visitor, recurse, node);
}
/**
* Eager depth-first collection pass. Gathers every non-null value the visitor
* callbacks return into an array.
*
* @example Collect every operationId
* ```ts
* const ids = collect<string>(root, {
* operation(node) {
* return node.operationId
* },
* })
* ```
*/
function collect(node, options) {
return Array.from(collectLazy(node, options));
}
//#endregion
export { schemaTypes as $, sourceDef as A, createConst as B, createExport as C, exportDef as D, createSource as E, arrowFunctionDef as F, functionDef as G, createJsx as H, breakDef as I, typeDef as J, jsxDef as K, constDef as L, pascalCase as M, contentDef as N, fileDef as O, createContent as P, narrowSchema as Q, createArrowFunction as R, inputDef as S, createImport as T, createText as U, createFunction as V, createType as W, visitorKeys as X, defineNode as Y, isHttpOperationNode as Z, createOperation as _, nodeDefs as a, requestBodyDef as b, createResponse as c, propertyDef as d, createParameter as f, outputDef as g, createOutput as h, walk as i, extractStringsFromNodes as j, importDef as k, responseDef as l, optionality as m, collectLazy as n, createSchema as o, parameterDef as p, textDef as q, transform as r, schemaDef as s, collect as t, createProperty as u, operationDef as v, createFile as w, createInput as x, createRequestBody as y, createBreak as z };
//# sourceMappingURL=visitor-Dk0DNLfC.js.map

Sorry, the diff of this file is too big to display

//#region \0rolldown/runtime.js
var __create = Object.create;
var __defProp = Object.defineProperty;
var __name = (target, value) => __defProp(target, "name", {
value,
configurable: true
});
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __getProtoOf = Object.getPrototypeOf;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __exportAll = (all, no_symbols) => {
let target = {};
for (var name in all) __defProp(target, name, {
get: all[name],
enumerable: true
});
if (!no_symbols) __defProp(target, Symbol.toStringTag, { value: "Module" });
return target;
};
var __copyProps = (to, from, except, desc) => {
if (from && typeof from === "object" || typeof from === "function") for (var keys = __getOwnPropNames(from), i = 0, n = keys.length, key; i < n; i++) {
key = keys[i];
if (!__hasOwnProp.call(to, key) && key !== except) __defProp(to, key, {
get: ((k) => from[k]).bind(null, key),
enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable
});
}
return to;
};
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", {
value: mod,
enumerable: true
}) : target, mod));
//#endregion
let node_crypto = require("node:crypto");
let node_path = require("node:path");
node_path = __toESM(node_path, 1);
//#region src/constants.ts
const visitorDepths = {
shallow: "shallow",
deep: "deep"
};
/**
* Schema type discriminators used by all AST schema nodes.
*
* Each value is a stable discriminator across the AST (for example `schema.type === schemaTypes.object`).
*/
const schemaTypes = {
/**
* Text value.
*/
string: "string",
/**
* Floating-point number (`float`, `double`).
*/
number: "number",
/**
* Whole number (`int32`). Use `bigint` for `int64`.
*/
integer: "integer",
/**
* 64-bit integer (`int64`). Only used when `integerType` is set to `'bigint'`.
*/
bigint: "bigint",
/**
* Boolean value.
*/
boolean: "boolean",
/**
* Explicit null value.
*/
null: "null",
/**
* Any value (no type restriction).
*/
any: "any",
/**
* Unknown value (must be narrowed before usage).
*/
unknown: "unknown",
/**
* No return value (`void`).
*/
void: "void",
/**
* Object with named properties.
*/
object: "object",
/**
* Sequential list of items.
*/
array: "array",
/**
* Fixed-length list with position-specific items.
*/
tuple: "tuple",
/**
* "One of" multiple schema members.
*/
union: "union",
/**
* "All of" multiple schema members.
*/
intersection: "intersection",
/**
* Enum schema.
*/
enum: "enum",
/**
* Reference to another schema.
*/
ref: "ref",
/**
* Calendar date (for example `2026-03-24`).
*/
date: "date",
/**
* Date-time value (for example `2026-03-24T09:00:00Z`).
*/
datetime: "datetime",
/**
* Time-only value (for example `09:00:00`).
*/
time: "time",
/**
* UUID value.
*/
uuid: "uuid",
/**
* Email address value.
*/
email: "email",
/**
* URL value.
*/
url: "url",
/**
* IPv4 address value.
*/
ipv4: "ipv4",
/**
* IPv6 address value.
*/
ipv6: "ipv6",
/**
* Binary/blob value.
*/
blob: "blob",
/**
* Impossible value (`never`).
*/
never: "never"
};
//#endregion
//#region src/guards.ts
/**
* Narrows a `SchemaNode` to the variant that matches `type`.
*
* @example
* ```ts
* const schema = createSchema({ type: 'string' })
* const stringNode = narrowSchema(schema, 'string') // StringSchemaNode | null
* ```
*/
function narrowSchema(node, type) {
return node?.type === type ? node : null;
}
/**
* Narrows an `OperationNode` to an `HttpOperationNode` so `method` and `path` are present.
*
* @example
* ```ts
* if (isHttpOperationNode(node)) {
* console.log(node.method, node.path)
* }
* ```
*/
function isHttpOperationNode(node) {
return node.protocol === "http" || node.method !== void 0 && node.path !== void 0;
}
//#endregion
//#region src/defineNode.ts
/**
* Visitor callback names, one per traversable node kind, in traversal order.
* Kept in sync with the keys of `Visitor` in `visitor.ts`.
*/
const visitorKeys = [
"input",
"output",
"operation",
"schema",
"property",
"parameter",
"response"
];
/**
* Builds a type guard that matches nodes of the given `kind`.
*/
function isKind(kind) {
return (node) => node?.kind === kind;
}
/**
* Defines a node once and derives its `create` builder, `is` guard, and traversal
* metadata. `create` merges `defaults`, the `build` hook (or the raw input), and the
* `kind`, so node construction lives in one place without scattered `as` casts.
*
* @example Simple node
* ```ts
* const importDef = defineNode<ImportNode>({ kind: 'Import' })
* const createImport = importDef.create
* ```
*
* @example Node with a build hook
* ```ts
* const propertyDef = defineNode<PropertyNode, UserPropertyNode>({
* kind: 'Property',
* build: (props) => ({ ...props, required: props.required ?? false }),
* children: ['schema'],
* visitorKey: 'property',
* })
* ```
*/
function defineNode(config) {
const { kind, defaults, build, children, visitorKey } = config;
function create(input) {
const base = build ? build(input) : input;
const node = {
kind,
...defaults,
...base
};
node.kind = kind;
return node;
}
return {
kind,
create,
is: isKind(kind),
children,
visitorKey
};
}
//#endregion
//#region src/nodes/code.ts
/**
* Definition for the {@link ConstNode}.
*/
const constDef = defineNode({ kind: "Const" });
/**
* Definition for the {@link TypeNode}.
*/
const typeDef = defineNode({ kind: "Type" });
/**
* Definition for the {@link FunctionNode}.
*/
const functionDef = defineNode({ kind: "Function" });
/**
* Definition for the {@link ArrowFunctionNode}.
*/
const arrowFunctionDef = defineNode({ kind: "ArrowFunction" });
/**
* Definition for the {@link TextNode}.
*/
const textDef = defineNode({
kind: "Text",
build: (value) => ({ value })
});
/**
* Definition for the {@link BreakNode}.
*/
const breakDef = defineNode({
kind: "Break",
build: () => ({})
});
/**
* Definition for the {@link JsxNode}.
*/
const jsxDef = defineNode({
kind: "Jsx",
build: (value) => ({ value })
});
/**
* Creates a `ConstNode` representing a TypeScript `const` declaration.
*
* @example Exported constant with type and `as const`
* ```ts
* createConst({ name: 'pets', export: true, type: 'Pet[]', asConst: true })
* // export const pets: Pet[] = ... as const
* ```
*/
const createConst = constDef.create;
/**
* Creates a `TypeNode` representing a TypeScript `type` alias declaration.
*
* @example
* ```ts
* createType({ name: 'Pet', export: true })
* // export type Pet = ...
* ```
*/
const createType = typeDef.create;
/**
* Creates a `FunctionNode` representing a TypeScript `function` declaration.
*
* @example
* ```ts
* createFunction({ name: 'fetchPet', export: true, async: true, returnType: 'Pet' })
* // export async function fetchPet(): Promise<Pet> { ... }
* ```
*/
const createFunction = functionDef.create;
/**
* Creates an `ArrowFunctionNode` representing a TypeScript arrow function.
*
* @example
* ```ts
* createArrowFunction({ name: 'double', export: true, params: 'n: number', singleLine: true })
* // export const double = (n: number) => ...
* ```
*/
const createArrowFunction = arrowFunctionDef.create;
/**
* Creates a {@link TextNode} representing a raw string fragment in the source output.
*
* @example
* ```ts
* createText('return fetch(id)')
* // { kind: 'Text', value: 'return fetch(id)' }
* ```
*/
const createText = textDef.create;
/**
* Creates a {@link BreakNode} representing a line break in the source output.
*
* @example
* ```ts
* createBreak()
* // { kind: 'Break' }
* ```
*/
function createBreak() {
return breakDef.create();
}
/**
* Creates a {@link JsxNode} representing a raw JSX fragment in the source output.
*
* @example
* ```ts
* createJsx('<>\n <a href={href}>Open</a>\n</>')
* // { kind: 'Jsx', value: '<>\n <a href={href}>Open</a>\n</>' }
* ```
*/
const createJsx = jsxDef.create;
//#endregion
//#region src/nodes/content.ts
/**
* Definition for the {@link ContentNode}.
*/
const contentDef = defineNode({
kind: "Content",
children: ["schema"]
});
/**
* Creates a `ContentNode` for a single request-body or response content type.
*/
const createContent = contentDef.create;
//#endregion
//#region ../../internals/utils/src/casing.ts
/**
* Shared implementation for camelCase and PascalCase conversion.
* Splits on common word boundaries (spaces, hyphens, underscores, dots, slashes, colons)
* and capitalizes each word according to `pascal`.
*
* When `pascal` is `true` the first word is also capitalized (PascalCase), otherwise only subsequent words are.
*/
function toCamelOrPascal(text, pascal) {
return text.trim().replace(/([a-z\d])([A-Z])/g, "$1 $2").replace(/([A-Z]+)([A-Z][a-z])/g, "$1 $2").replace(/(\d)([a-z])/g, "$1 $2").split(/[\s\-_./\\:]+/).filter(Boolean).map((word, i) => {
if (word.length > 1 && word === word.toUpperCase()) return word;
return (i === 0 && !pascal ? word.charAt(0).toLowerCase() : word.charAt(0).toUpperCase()) + word.slice(1);
}).join("").replace(/[^a-zA-Z0-9]/g, "");
}
/**
* Converts `text` to PascalCase.
*
* @example Word boundaries
* `pascalCase('hello-world') // 'HelloWorld'`
*
* @example With a suffix
* `pascalCase('tag', { suffix: 'schema' }) // 'TagSchema'`
*/
function pascalCase(text, { prefix = "", suffix = "" } = {}) {
return toCamelOrPascal(`${prefix} ${text} ${suffix}`, true);
}
//#endregion
//#region ../../internals/utils/src/fs.ts
/**
* Strips the file extension from a path or file name.
* Only removes the last `.ext` segment when the dot is not part of a directory name.
*
* @example
* trimExtName('petStore.ts') // 'petStore'
* trimExtName('/src/models/pet.ts') // '/src/models/pet'
* trimExtName('/project.v2/gen/pet.ts') // '/project.v2/gen/pet'
* trimExtName('noExtension') // 'noExtension'
*/
function trimExtName(text) {
const dotIndex = text.lastIndexOf(".");
if (dotIndex > 0 && !text.includes("/", dotIndex)) return text.slice(0, dotIndex);
return text;
}
//#endregion
//#region src/utils/extractStringsFromNodes.ts
/**
* Extracts all string content from a `CodeNode` tree recursively.
*
* Collects text node values, identifier references in string fields (`params`, `generics`, `returnType`, `type`),
* and nested node content. Used to build the full source string for import filtering.
*/
function extractStringsFromNodes(nodes) {
if (!nodes?.length) return "";
const collected = [];
for (const node of nodes) {
if (typeof node === "string") {
if (node) collected.push(node);
continue;
}
if (node.kind === "Text") {
if (node.value) collected.push(node.value);
continue;
}
if (node.kind === "Break") continue;
if (node.kind === "Jsx") {
if (node.value) collected.push(node.value);
continue;
}
const parts = [];
if ("params" in node && node.params) parts.push(node.params);
if ("generics" in node && node.generics) parts.push(Array.isArray(node.generics) ? node.generics.join(", ") : node.generics);
if ("returnType" in node && node.returnType) parts.push(node.returnType);
if ("type" in node && typeof node.type === "string") parts.push(node.type);
const nested = extractStringsFromNodes(node.nodes);
if (nested) parts.push(nested);
if (parts.length) collected.push(parts.join("\n"));
}
return collected.join("\n");
}
//#endregion
//#region src/utils/fileMerge.ts
function sourceKey(source) {
return `${source.name ?? extractStringsFromNodes(source.nodes)}:${source.isExportable ?? false}:${source.isTypeOnly ?? false}`;
}
function pathTypeKey(path, isTypeOnly) {
return `${path}:${isTypeOnly ?? false}`;
}
function exportKey(path, name, isTypeOnly, asAlias) {
return `${path}:${name ?? ""}:${isTypeOnly ?? false}:${asAlias ?? ""}`;
}
function importKey(path, name, isTypeOnly) {
return `${path}:${name ?? ""}:${isTypeOnly ?? false}`;
}
/**
* Computes a multi-level sort key for exports and imports:
* non-array names first (wildcards/namespace aliases). Type-only before value. Alphabetical path. Unnamed before named.
*/
function sortKey(node) {
const isArray = Array.isArray(node.name) ? "1" : "0";
const typeOnly = node.isTypeOnly ? "0" : "1";
const hasName = node.name != null ? "1" : "0";
const name = Array.isArray(node.name) ? node.name.toSorted().join("\0") : node.name ?? "";
return `${isArray}:${typeOnly}:${node.path}:${hasName}:${name}`;
}
/**
* Deduplicates `SourceNode` objects by `name + isExportable + isTypeOnly`, keeping the first of each
* key. Unnamed sources fall back to their extracted node strings as the name part of the key. Returns
* the deduplicated array in original order.
*/
function combineSources(sources) {
const seen = /* @__PURE__ */ new Map();
for (const source of sources) {
const key = sourceKey(source);
if (!seen.has(key)) seen.set(key, source);
}
return [...seen.values()];
}
/**
* Merges `incoming` names into `existing`, preserving order and dropping duplicates.
*
* Shared by `combineExports` and `combineImports` for the same-path name-merge case.
*/
function mergeNameArrays(existing, incoming) {
const merged = new Set(existing);
for (const name of incoming) merged.add(name);
return [...merged];
}
/**
* Deduplicates and merges `ExportNode` objects by path and type.
*
* Named exports with the same path and `isTypeOnly` flag have their names merged into a single export.
* Non-array exports are deduplicated by exact identity. Returns a sorted, deduplicated array.
*/
function combineExports(exports) {
const result = [];
const namedByPath = /* @__PURE__ */ new Map();
const seen = /* @__PURE__ */ new Set();
const keyed = exports.map((node) => ({
node,
key: sortKey(node)
}));
keyed.sort((a, b) => a.key < b.key ? -1 : a.key > b.key ? 1 : 0);
for (const { node: curr } of keyed) {
const { name, path, isTypeOnly, asAlias } = curr;
if (Array.isArray(name)) {
if (!name.length) continue;
const key = pathTypeKey(path, isTypeOnly);
const existing = namedByPath.get(key);
if (existing && Array.isArray(existing.name)) existing.name = mergeNameArrays(existing.name, name);
else {
const newItem = {
...curr,
name: [...new Set(name)]
};
result.push(newItem);
namedByPath.set(key, newItem);
}
} else {
const key = exportKey(path, name, isTypeOnly, asAlias);
if (!seen.has(key)) {
result.push(curr);
seen.add(key);
}
}
}
return result;
}
/**
* Deduplicates and merges `ImportNode` objects, filtering out unused imports.
*
* Retains imports that are referenced in `source` or re-exported. Imports with the same path and
* `isTypeOnly` flag have their names merged. Returns a sorted, deduplicated, filtered array.
*/
function combineImports(imports, exports, source) {
const exportedNames = new Set(exports.flatMap((e) => Array.isArray(e.name) ? e.name : e.name ? [e.name] : []));
const isUsed = (importName) => !source || source.includes(importName) || exportedNames.has(importName);
const importNameMemo = /* @__PURE__ */ new Map();
const canonicalizeName = (n) => {
if (typeof n === "string") return n;
const key = `${n.propertyName}:${n.name ?? ""}`;
if (!importNameMemo.has(key)) importNameMemo.set(key, n);
return importNameMemo.get(key);
};
const pathsWithUsedNamedImport = /* @__PURE__ */ new Set();
for (const node of imports) {
if (!Array.isArray(node.name)) continue;
if (node.name.some((item) => typeof item === "string" ? isUsed(item) : isUsed(item.name ?? item.propertyName))) pathsWithUsedNamedImport.add(node.path);
}
const result = [];
const namedByPath = /* @__PURE__ */ new Map();
const seen = /* @__PURE__ */ new Set();
const keyed = imports.map((node) => ({
node,
key: sortKey(node)
}));
keyed.sort((a, b) => a.key < b.key ? -1 : a.key > b.key ? 1 : 0);
for (const { node: curr } of keyed) {
if (curr.path === curr.root) continue;
const { path, isTypeOnly } = curr;
let { name } = curr;
if (Array.isArray(name)) {
name = [...new Set(name.map(canonicalizeName))].filter((item) => typeof item === "string" ? isUsed(item) : isUsed(item.name ?? item.propertyName));
if (!name.length) continue;
const key = pathTypeKey(path, isTypeOnly);
const existing = namedByPath.get(key);
if (existing && Array.isArray(existing.name)) existing.name = mergeNameArrays(existing.name, name);
else {
const newItem = {
...curr,
name
};
result.push(newItem);
namedByPath.set(key, newItem);
}
} else {
if (name && !isUsed(name) && !pathsWithUsedNamedImport.has(path)) continue;
const key = importKey(path, name, isTypeOnly);
if (!seen.has(key)) {
result.push(curr);
seen.add(key);
}
}
}
return result;
}
//#endregion
//#region src/nodes/file.ts
/**
* Definition for the {@link ImportNode}.
*/
const importDef = defineNode({ kind: "Import" });
/**
* Definition for the {@link ExportNode}.
*/
const exportDef = defineNode({ kind: "Export" });
/**
* Definition for the {@link SourceNode}.
*/
const sourceDef = defineNode({ kind: "Source" });
/**
* Definition for the {@link FileNode}. The fully resolved builder lives in
* `createFile`, so this definition only supplies the guard.
*/
const fileDef = defineNode({ kind: "File" });
/**
* Creates an `ImportNode` representing a language-agnostic import/dependency declaration.
*
* @example Named import
* ```ts
* createImport({ name: ['useState'], path: 'react' })
* // import { useState } from 'react'
* ```
*/
const createImport = importDef.create;
/**
* Creates an `ExportNode` representing a language-agnostic export/public API declaration.
*
* @example Named export
* ```ts
* createExport({ name: ['Pet'], path: './Pet' })
* // export { Pet } from './Pet'
* ```
*/
const createExport = exportDef.create;
/**
* Creates a `SourceNode` representing a fragment of source code within a file.
*
* @example
* ```ts
* createSource({ name: 'Pet', nodes: [createText('export type Pet = { id: number }')], isExportable: true })
* ```
*/
const createSource = sourceDef.create;
/**
* Creates a fully resolved `FileNode` from a file input descriptor.
*
* Computes:
* - `id` SHA256 hash of the file path
* - `name` `baseName` without extension
* - `extname` extension extracted from `baseName`
*
* Deduplicates:
* - `sources` via `combineSources`
* - `exports` via `combineExports`
* - `imports` via `combineImports` (also filters unused imports)
*
* @throws {Error} when `baseName` has no extension.
*
* @example
* ```ts
* const file = createFile({
* baseName: 'petStore.ts',
* path: 'src/models/petStore.ts',
* sources: [createSource({ name: 'Pet', nodes: [createText('export type Pet = { id: number }')] })],
* imports: [createImport({ name: ['z'], path: 'zod' })],
* exports: [createExport({ name: ['Pet'], path: './petStore' })],
* })
* // file.id = SHA256 hash of 'src/models/petStore.ts'
* // file.name = 'petStore'
* // file.extname = '.ts'
* ```
*
* @example Copy a real file into the output verbatim
* ```ts
* const file = createFile({
* baseName: 'client.ts',
* path: 'src/gen/client.ts',
* copy: '/abs/path/to/templates/client.ts',
* })
* ```
*/
function createFile(input) {
const extname = node_path.default.extname(input.baseName) || (input.baseName.startsWith(".") ? input.baseName : "");
if (!extname) throw new Error(`No extname found for ${input.baseName}`);
const resolvedExports = input.exports?.length ? combineExports(input.exports) : [];
let resolvedImports = [];
if (input.imports?.length) {
const source = extractStringsFromNodes((input.sources ?? []).flatMap((item) => item.nodes ?? [])) || void 0;
const combinedImports = combineImports(input.imports, resolvedExports, source);
const localNames = new Set((input.sources ?? []).map((item) => item.name).filter((name) => Boolean(name)));
const nameOf = (item) => typeof item === "string" ? item : item.name ?? item.propertyName;
resolvedImports = combinedImports.filter((imp) => imp.path !== input.path).flatMap((imp) => {
if (!Array.isArray(imp.name)) return typeof imp.name === "string" && localNames.has(imp.name) ? [] : [imp];
const kept = imp.name.filter((item) => !localNames.has(nameOf(item)));
if (!kept.length) return [];
return [kept.length === imp.name.length ? imp : {
...imp,
name: kept
}];
});
}
const resolvedSources = input.sources?.length ? combineSources(input.sources) : [];
return {
kind: "File",
...input,
id: (0, node_crypto.hash)("sha256", input.path, "hex"),
name: trimExtName(input.baseName),
extname,
imports: resolvedImports,
exports: resolvedExports,
sources: resolvedSources,
meta: input.meta ?? {}
};
}
//#endregion
//#region src/nodes/input.ts
/**
* Definition for the {@link InputNode}.
*/
const inputDef = defineNode({
kind: "Input",
defaults: {
schemas: [],
operations: [],
meta: {
circularNames: [],
enumNames: []
}
},
children: ["schemas", "operations"],
visitorKey: "input"
});
/**
* Creates an `InputNode`. Pass `stream: true` for the streaming variant whose `schemas` and
* `operations` are `AsyncIterable` sources. Otherwise it builds the eager variant with array
* `schemas`/`operations`. Both variants get the defaulted `meta`.
*
* @example Eager
* ```ts
* const input = createInput()
* // { kind: 'Input', schemas: [], operations: [] }
* ```
*
* @example Streaming
* ```ts
* const node = createInput({ stream: true, schemas: schemasIterable, operations: operationsIterable, meta: { title: 'My API' } })
* ```
*/
function createInput(options = {}) {
const { stream, ...overrides } = options;
if (stream) return {
kind: "Input",
meta: {
circularNames: [],
enumNames: []
},
...overrides
};
return inputDef.create(overrides);
}
//#endregion
//#region src/nodes/requestBody.ts
/**
* Definition for the {@link RequestBodyNode}. Content entries are built upfront with
* {@link createContent}, mirroring how `parameters` and `responses` take prebuilt nodes.
*/
const requestBodyDef = defineNode({
kind: "RequestBody",
children: ["content"]
});
/**
* Creates a `RequestBodyNode`.
*/
const createRequestBody = requestBodyDef.create;
//#endregion
//#region src/nodes/operation.ts
/**
* Definition for the {@link OperationNode}. HTTP operations (those carrying both
* `method` and `path`) are tagged with `protocol: 'http'`, and the request body is
* normalized into a `RequestBodyNode`.
*/
const operationDef = defineNode({
kind: "Operation",
build: (props) => {
const { requestBody, ...rest } = props;
const isHttp = rest.method !== void 0 && rest.path !== void 0;
return {
tags: [],
parameters: [],
responses: [],
...rest,
...isHttp ? { protocol: "http" } : {},
requestBody: requestBody ? createRequestBody(requestBody) : void 0
};
},
children: [
"parameters",
"requestBody",
"responses"
],
visitorKey: "operation"
});
function createOperation(props) {
return operationDef.create(props);
}
//#endregion
//#region src/nodes/output.ts
/**
* Definition for the {@link OutputNode}.
*/
const outputDef = defineNode({
kind: "Output",
defaults: { files: [] },
visitorKey: "output"
});
/**
* Creates an `OutputNode` with a stable default for `files`.
*
* @example
* ```ts
* const output = createOutput()
* // { kind: 'Output', files: [] }
* ```
*/
function createOutput(overrides = {}) {
return outputDef.create(overrides);
}
//#endregion
//#region src/optionality.ts
/**
* Generic JSON Schema optionality: a non-required field is optional, and a
* non-required nullable field is nullish.
*/
function optionality(schema, required) {
const nullable = schema.nullable ?? false;
return {
...schema,
optional: !required && !nullable ? true : void 0,
nullish: !required && nullable ? true : void 0
};
}
//#endregion
//#region src/nodes/parameter.ts
/**
* Definition for the {@link ParameterNode}. `required` defaults to `false`, and the schema's
* `optional`/`nullish` flags are derived from it through {@link optionality}.
*/
const parameterDef = defineNode({
kind: "Parameter",
build: (props) => {
const required = props.required ?? false;
return {
...props,
required,
schema: optionality(props.schema, required)
};
},
children: ["schema"],
visitorKey: "parameter"
});
/**
* Creates a `ParameterNode`.
*
* @example
* ```ts
* const param = createParameter({
* name: 'petId',
* in: 'path',
* required: true,
* schema: createSchema({ type: 'string' }),
* })
* ```
*/
const createParameter = parameterDef.create;
//#endregion
//#region src/nodes/property.ts
/**
* Definition for the {@link PropertyNode}. `required` defaults to `false`, and the schema's
* `optional`/`nullish` flags are derived from it through {@link optionality}.
*/
const propertyDef = defineNode({
kind: "Property",
build: (props) => {
const required = props.required ?? false;
return {
...props,
required,
schema: optionality(props.schema, required)
};
},
children: ["schema"],
visitorKey: "property"
});
/**
* Creates a `PropertyNode`.
*
* @example
* ```ts
* const property = createProperty({
* name: 'status',
* required: true,
* schema: createSchema({ type: 'string', nullable: true }),
* })
* // required=true, no optional/nullish
* ```
*/
const createProperty = propertyDef.create;
//#endregion
//#region src/nodes/response.ts
/**
* Definition for the {@link ResponseNode}. A single legacy `schema` (with optional
* `mediaType`/`keysToOmit`) is normalized into one `content` entry.
*/
const responseDef = defineNode({
kind: "Response",
build: (props) => {
const { schema, mediaType, keysToOmit, content, ...rest } = props;
const entries = content ?? (schema ? [createContent({
contentType: mediaType ?? "application/json",
schema,
keysToOmit: keysToOmit ?? null
})] : void 0);
return {
...rest,
content: entries
};
},
children: ["content"],
visitorKey: "response"
});
/**
* Creates a `ResponseNode`.
*
* @example
* ```ts
* const response = createResponse({
* statusCode: '200',
* content: [createContent({ contentType: 'application/json', schema: createSchema({ type: 'object', properties: [] }) })],
* })
* ```
*/
const createResponse = responseDef.create;
//#endregion
//#region src/nodes/schema.ts
/**
* Maps schema `type` to its underlying `primitive`.
* Primitive types map to themselves and special string formats map to `'string'`.
* Any type not listed here (such as `ref`, `enum`, `union`, `intersection`, `tuple`, `ipv4`, `ipv6`, `blob`) has no `primitive`.
*/
const TYPE_TO_PRIMITIVE = {
string: "string",
number: "number",
integer: "integer",
bigint: "bigint",
boolean: "boolean",
null: "null",
any: "any",
unknown: "unknown",
void: "void",
never: "never",
object: "object",
array: "array",
date: "date",
uuid: "string",
email: "string",
url: "string",
datetime: "string",
time: "string"
};
/**
* Definition for the {@link SchemaNode}. Object schemas default `properties` to an
* empty array, and `primitive` is inferred from `type` when not explicitly provided.
*/
const schemaDef = defineNode({
kind: "Schema",
build: (props) => {
if (props.type === "object") return {
properties: [],
primitive: "object",
...props
};
return {
primitive: TYPE_TO_PRIMITIVE[props.type],
...props
};
},
children: [
"properties",
"items",
"members",
"additionalProperties"
],
visitorKey: "schema"
});
function createSchema(props) {
return schemaDef.create(props);
}
//#endregion
//#region src/registry.ts
/**
* Every node definition. Adding a node means adding its `defineNode` to one
* `nodes/*.ts` file and listing it here. The visitor tables in `visitor.ts` derive from it.
*/
const nodeDefs = [
inputDef,
outputDef,
operationDef,
requestBodyDef,
contentDef,
responseDef,
schemaDef,
propertyDef,
parameterDef,
constDef,
typeDef,
functionDef,
arrowFunctionDef,
textDef,
breakDef,
jsxDef,
importDef,
exportDef,
sourceDef,
fileDef
];
//#endregion
//#region src/visitor.ts
/**
* Child node fields per node kind, in traversal order (Babel's `VISITOR_KEYS`).
* Derived from each definition's `children`.
*/
const VISITOR_KEYS = Object.fromEntries(nodeDefs.flatMap((def) => def.children ? [[def.kind, def.children]] : []));
/**
* Maps a node kind to the matching visitor callback name. Derived from each
* definition's `visitorKey`.
*/
const VISITOR_KEY_BY_KIND = Object.fromEntries(nodeDefs.flatMap((def) => def.visitorKey ? [[def.kind, def.visitorKey]] : []));
/**
* Creates a small async concurrency limiter.
*
* At most `concurrency` tasks are in flight at once. Extra tasks are queued.
*
* @example
* ```ts
* const limit = createLimit(2)
* for (const task of [taskA, taskB, taskC]) {
* await limit(() => task())
* }
* // only 2 tasks run at the same time
* ```
*/
function createLimit(concurrency) {
let active = 0;
const queue = [];
function next() {
if (active < concurrency && queue.length > 0) {
active++;
queue.shift()();
}
}
return function limit(fn) {
return new Promise((resolve, reject) => {
queue.push(() => {
Promise.resolve(fn()).then(resolve, reject).finally(() => {
active--;
next();
});
});
next();
});
};
}
const visitorKeysByKind = VISITOR_KEYS;
/**
* Returns `true` when `value` is an AST node (an object carrying a `kind`).
*/
function isNode(value) {
return typeof value === "object" && value !== null && typeof value.kind === "string";
}
/**
* Returns the immediate traversable children of `node` based on {@link VISITOR_KEYS}.
*
* `Schema` children are only included when `recurse` is `true`. Shallow mode skips them.
*
* @example
* ```ts
* const children = getChildren(operationNode, true)
* // returns parameters, the request body, and responses
* ```
*/
function* getChildren(node, recurse) {
if (node.kind === "Schema" && !recurse) return;
const keys = visitorKeysByKind[node.kind];
if (!keys) return;
const record = node;
for (const key of keys) {
const value = record[key];
if (Array.isArray(value)) {
for (const item of value) if (isNode(item)) yield item;
} else if (isNode(value)) yield value;
}
}
/**
* Runs the visitor callback that matches `node.kind` with the traversal
* context. The result is a replacement node, a collected value, or `undefined`
* when no callback is registered for the kind.
*
* Shared by `walk`, `transform`, and `collectLazy` so node-kind dispatch lives
* in one place. `TResult` is the caller's expected return: the same node type
* for `transform`, the collected value type for `collectLazy`, ignored for `walk`.
*/
function applyVisitor(node, visitor, parent) {
const key = VISITOR_KEY_BY_KIND[node.kind];
if (!key) return void 0;
const fn = visitor[key];
return fn?.(node, { parent });
}
/**
* Async depth-first traversal for side effects. Visitor return values are
* ignored. Use `transform` when you want to rewrite nodes.
*
* Sibling nodes at each depth run concurrently up to `options.concurrency`
* (defaults to `WALK_CONCURRENCY`). Higher values overlap I/O-bound visitor
* work. Lower values reduce memory pressure.
*
* @example Log every operation
* ```ts
* await walk(root, {
* operation(node) {
* console.log(node.operationId)
* },
* })
* ```
*
* @example Only visit the root node
* ```ts
* await walk(root, { depth: 'shallow', input: () => {} })
* ```
*/
async function walk(node, options) {
return _walk(node, options, (options.depth ?? visitorDepths.deep) === visitorDepths.deep, createLimit(options.concurrency ?? 30), void 0);
}
async function _walk(node, visitor, recurse, limit, parent) {
await limit(() => applyVisitor(node, visitor, parent));
let pending;
for (const child of getChildren(node, recurse)) (pending ??= []).push(_walk(child, visitor, recurse, limit, node));
if (pending) await Promise.all(pending);
}
function transform(node, options) {
const { depth, parent, ...visitor } = options;
return transformNode(node, visitor, (depth ?? visitorDepths.deep) === visitorDepths.deep, parent);
}
/**
* Visits a single node, then immutably rebuilds its children. Returns the original
* reference when neither the visitor nor the child rebuild changed anything, so callers
* can detect "nothing changed" by identity and ancestors avoid reallocating.
*/
function transformNode(node, visitor, recurse, parent) {
return transformChildren(applyVisitor(node, visitor, parent) ?? node, visitor, recurse);
}
/**
* Immutably rebuilds a node's children using {@link VISITOR_KEYS}, transforming
* each child node and leaving non-node values (e.g. `additionalProperties: true`) intact.
* `Schema` children are skipped in shallow mode.
*/
function transformChildren(node, visitor, recurse) {
if (node.kind === "Schema" && !recurse) return node;
const keys = visitorKeysByKind[node.kind];
if (!keys) return node;
const record = node;
let updates;
for (const key of keys) {
if (!(key in record)) continue;
const value = record[key];
if (Array.isArray(value)) {
let mapped;
for (const [i, item] of value.entries()) {
const next = isNode(item) ? transformNode(item, visitor, recurse, node) : item;
if (mapped) {
mapped.push(next);
continue;
}
if (next !== item) mapped = [...value.slice(0, i), next];
}
if (mapped) (updates ??= {})[key] = mapped;
} else if (isNode(value)) {
const next = transformNode(value, visitor, recurse, node);
if (next !== value) (updates ??= {})[key] = next;
}
}
return updates ? {
...node,
...updates
} : node;
}
/**
* Lazy depth-first collection pass. Yields every non-null value returned by
* the visitor callbacks. Use `collect` for the eager array form.
*
* @example Collect every operationId
* ```ts
* const ids: string[] = []
* for (const id of collectLazy<string>(root, {
* operation(node) {
* return node.operationId
* },
* })) {
* ids.push(id)
* }
* ```
*/
function* collectLazy(node, options) {
const { depth, parent, ...visitor } = options;
yield* collectNode(node, visitor, (depth ?? visitorDepths.deep) === visitorDepths.deep, parent);
}
function* collectNode(node, visitor, recurse, parent) {
const v = applyVisitor(node, visitor, parent);
if (v != null) yield v;
for (const child of getChildren(node, recurse)) yield* collectNode(child, visitor, recurse, node);
}
/**
* Eager depth-first collection pass. Gathers every non-null value the visitor
* callbacks return into an array.
*
* @example Collect every operationId
* ```ts
* const ids = collect<string>(root, {
* operation(node) {
* return node.operationId
* },
* })
* ```
*/
function collect(node, options) {
return Array.from(collectLazy(node, options));
}
//#endregion
Object.defineProperty(exports, "__exportAll", {
enumerable: true,
get: function() {
return __exportAll;
}
});
Object.defineProperty(exports, "__name", {
enumerable: true,
get: function() {
return __name;
}
});
Object.defineProperty(exports, "arrowFunctionDef", {
enumerable: true,
get: function() {
return arrowFunctionDef;
}
});
Object.defineProperty(exports, "breakDef", {
enumerable: true,
get: function() {
return breakDef;
}
});
Object.defineProperty(exports, "collect", {
enumerable: true,
get: function() {
return collect;
}
});
Object.defineProperty(exports, "collectLazy", {
enumerable: true,
get: function() {
return collectLazy;
}
});
Object.defineProperty(exports, "constDef", {
enumerable: true,
get: function() {
return constDef;
}
});
Object.defineProperty(exports, "contentDef", {
enumerable: true,
get: function() {
return contentDef;
}
});
Object.defineProperty(exports, "createArrowFunction", {
enumerable: true,
get: function() {
return createArrowFunction;
}
});
Object.defineProperty(exports, "createBreak", {
enumerable: true,
get: function() {
return createBreak;
}
});
Object.defineProperty(exports, "createConst", {
enumerable: true,
get: function() {
return createConst;
}
});
Object.defineProperty(exports, "createContent", {
enumerable: true,
get: function() {
return createContent;
}
});
Object.defineProperty(exports, "createExport", {
enumerable: true,
get: function() {
return createExport;
}
});
Object.defineProperty(exports, "createFile", {
enumerable: true,
get: function() {
return createFile;
}
});
Object.defineProperty(exports, "createFunction", {
enumerable: true,
get: function() {
return createFunction;
}
});
Object.defineProperty(exports, "createImport", {
enumerable: true,
get: function() {
return createImport;
}
});
Object.defineProperty(exports, "createInput", {
enumerable: true,
get: function() {
return createInput;
}
});
Object.defineProperty(exports, "createJsx", {
enumerable: true,
get: function() {
return createJsx;
}
});
Object.defineProperty(exports, "createOperation", {
enumerable: true,
get: function() {
return createOperation;
}
});
Object.defineProperty(exports, "createOutput", {
enumerable: true,
get: function() {
return createOutput;
}
});
Object.defineProperty(exports, "createParameter", {
enumerable: true,
get: function() {
return createParameter;
}
});
Object.defineProperty(exports, "createProperty", {
enumerable: true,
get: function() {
return createProperty;
}
});
Object.defineProperty(exports, "createRequestBody", {
enumerable: true,
get: function() {
return createRequestBody;
}
});
Object.defineProperty(exports, "createResponse", {
enumerable: true,
get: function() {
return createResponse;
}
});
Object.defineProperty(exports, "createSchema", {
enumerable: true,
get: function() {
return createSchema;
}
});
Object.defineProperty(exports, "createSource", {
enumerable: true,
get: function() {
return createSource;
}
});
Object.defineProperty(exports, "createText", {
enumerable: true,
get: function() {
return createText;
}
});
Object.defineProperty(exports, "createType", {
enumerable: true,
get: function() {
return createType;
}
});
Object.defineProperty(exports, "defineNode", {
enumerable: true,
get: function() {
return defineNode;
}
});
Object.defineProperty(exports, "exportDef", {
enumerable: true,
get: function() {
return exportDef;
}
});
Object.defineProperty(exports, "extractStringsFromNodes", {
enumerable: true,
get: function() {
return extractStringsFromNodes;
}
});
Object.defineProperty(exports, "fileDef", {
enumerable: true,
get: function() {
return fileDef;
}
});
Object.defineProperty(exports, "functionDef", {
enumerable: true,
get: function() {
return functionDef;
}
});
Object.defineProperty(exports, "importDef", {
enumerable: true,
get: function() {
return importDef;
}
});
Object.defineProperty(exports, "inputDef", {
enumerable: true,
get: function() {
return inputDef;
}
});
Object.defineProperty(exports, "isHttpOperationNode", {
enumerable: true,
get: function() {
return isHttpOperationNode;
}
});
Object.defineProperty(exports, "jsxDef", {
enumerable: true,
get: function() {
return jsxDef;
}
});
Object.defineProperty(exports, "narrowSchema", {
enumerable: true,
get: function() {
return narrowSchema;
}
});
Object.defineProperty(exports, "nodeDefs", {
enumerable: true,
get: function() {
return nodeDefs;
}
});
Object.defineProperty(exports, "operationDef", {
enumerable: true,
get: function() {
return operationDef;
}
});
Object.defineProperty(exports, "optionality", {
enumerable: true,
get: function() {
return optionality;
}
});
Object.defineProperty(exports, "outputDef", {
enumerable: true,
get: function() {
return outputDef;
}
});
Object.defineProperty(exports, "parameterDef", {
enumerable: true,
get: function() {
return parameterDef;
}
});
Object.defineProperty(exports, "pascalCase", {
enumerable: true,
get: function() {
return pascalCase;
}
});
Object.defineProperty(exports, "propertyDef", {
enumerable: true,
get: function() {
return propertyDef;
}
});
Object.defineProperty(exports, "requestBodyDef", {
enumerable: true,
get: function() {
return requestBodyDef;
}
});
Object.defineProperty(exports, "responseDef", {
enumerable: true,
get: function() {
return responseDef;
}
});
Object.defineProperty(exports, "schemaDef", {
enumerable: true,
get: function() {
return schemaDef;
}
});
Object.defineProperty(exports, "schemaTypes", {
enumerable: true,
get: function() {
return schemaTypes;
}
});
Object.defineProperty(exports, "sourceDef", {
enumerable: true,
get: function() {
return sourceDef;
}
});
Object.defineProperty(exports, "textDef", {
enumerable: true,
get: function() {
return textDef;
}
});
Object.defineProperty(exports, "transform", {
enumerable: true,
get: function() {
return transform;
}
});
Object.defineProperty(exports, "typeDef", {
enumerable: true,
get: function() {
return typeDef;
}
});
Object.defineProperty(exports, "visitorKeys", {
enumerable: true,
get: function() {
return visitorKeys;
}
});
Object.defineProperty(exports, "walk", {
enumerable: true,
get: function() {
return walk;
}
});
//# sourceMappingURL=visitor-h6dEM3vR.cjs.map

Sorry, the diff of this file is too big to display

Sorry, the diff of this file is too big to display

Sorry, the diff of this file is too big to display

Sorry, the diff of this file is too big to display

Sorry, the diff of this file is too big to display