🚀 Socket Launch Week Day 4:Socket MCP Adds Org Alerts, Threat Feed Review, and Package Inspection.Learn more
Sign In

@kubb/ast

Package Overview
Dependencies
Maintainers
1
Versions
173
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.64
to
5.0.0-beta.65
+466
dist/defineMacro-BQpu6Ags.d.ts
import { n as __name } from "./rolldown-runtime-CNktS9qV.js";
import { C as ParameterNode, Et as PropertyNode, _t as SchemaNode, f as OperationNode, h as ResponseNode, n as OutputNode, o as InputNode, rt as ContentNode, t as Node, y as RequestBodyNode } from "./index-CeJAFegf.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-BQpu6Ags.d.ts.map
import { n as __name, t as __exportAll } from "./rolldown-runtime-CNktS9qV.js";
import { F as createFunctionParameters, Gt as createBreak, I as createIndexedAccessType, J as UserFileNode, Jt as createJsx, Kt as createConst, L as createObjectBindingPattern, Ot as createProperty, P as createFunctionParameter, Q as createSource, R as createTypeLiteral, Wt as createArrowFunction, X as createFile, Xt as createType, Y as createExport, Yt as createText, Z as createImport, _ as createResponse, at as createContent, b as createRequestBody, p as createOperation, qt as createFunction, r as createOutput, s as createInput, t as Node, w as createParameter, wt as createSchema } from "./index-CeJAFegf.js";
//#region src/factory.d.ts
declare namespace factory_d_exports {
export { UserFileNode, createArrowFunction, createBreak, createConst, createContent, createExport, createFile, createFunction, createFunctionParameter, createFunctionParameters, createImport, createIndexedAccessType, createInput, createJsx, createObjectBindingPattern, createOperation, createOutput, createParameter, createProperty, createRequestBody, createResponse, createSchema, createSource, createText, createType, createTypeLiteral, update };
}
/**
* Identity-preserving node update: returns `node` unchanged when every field in
* `changes` already equals (by reference) the current value, otherwise a new node
* with the changes applied.
*
* Mirrors the TypeScript compiler's `factory.updateX` contract. Pair it with the
* structural sharing in {@link transform} so a no-op rewrite does not allocate and
* downstream passes can detect "nothing changed" by identity. Comparison is shallow,
* so a structurally equal but newly allocated array or object counts as a change.
*
* @example
* ```ts
* update(node, { name: node.name }) // -> same `node` reference
* update(node, { name: 'renamed' }) // -> new node, `name` replaced
* ```
*/
declare function update<T extends Node>(node: T, changes: Partial<T>): T;
//#endregion
export { update as n, factory_d_exports as t };
//# sourceMappingURL=factory-B_qPwA1b.d.ts.map

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

import { n as __name } from "./rolldown-runtime-CNktS9qV.js";
import { C as ParameterNode, M as TypeExpression, N as TypeLiteralNode, O as FunctionParameterNode, f as OperationNode, k as FunctionParametersNode } from "./index-CeJAFegf.js";
//#region src/utils/operationParams.d.ts
/**
* Applies casing rules to parameter names and returns a new array without mutating the input.
*
* Run it before handing parameters to schema builders so output property keys get the right casing
* while `OperationNode.parameters` stays intact for other consumers. When `casing` is unset, the
* original array is returned unchanged.
*/
declare function caseParams(params: Array<ParameterNode>, casing: 'camelcase' | undefined): Array<ParameterNode>;
/**
* Named type for a group of parameters (query or header) emitted as a single typed parameter.
*/
type ParamGroupType = {
/**
* Type expression for the group, a plain group-name reference.
*/
type: TypeExpression;
/**
* Whether the parameter group is optional.
*/
optional: boolean;
};
/**
* Resolver interface for {@link createOperationParams}.
*
* `ResolverTs` from `@kubb/plugin-ts` satisfies this interface and can be passed directly.
*/
type OperationParamsResolver = {
/**
* Resolves the type name for an individual parameter.
*
* @example Individual path parameter name
* `resolver.resolveParamName(node, param) // → 'DeletePetPathPetId'`
*/
resolveParamName(node: OperationNode, param: ParameterNode): string;
/**
* Resolves the request body type name.
*
* @example Request body type name
* `resolver.resolveDataName(node) // → 'CreatePetData'`
*/
resolveDataName(node: OperationNode): string;
/**
* Resolves the grouped path parameters type name.
* When the return value equals `resolveParamName`, no indexed access is emitted.
*
* @example Grouped path params type name
* `resolver.resolvePathParamsName(node, param) // → 'DeletePetPathParams'`
*/
resolvePathParamsName(node: OperationNode, param: ParameterNode): string;
/**
* Resolves the grouped query parameters type name.
* When the return value equals `resolveParamName`, an inline struct type is emitted instead.
*
* @example Grouped query params type name
* `resolver.resolveQueryParamsName(node, param) // → 'FindPetsByStatusQueryParams'`
*/
resolveQueryParamsName(node: OperationNode, param: ParameterNode): string;
/**
* Resolves the grouped header parameters type name.
* When the return value equals `resolveParamName`, an inline struct type is emitted instead.
*
* @example Grouped header params type name
* `resolver.resolveHeaderParamsName(node, param) // → 'DeletePetHeaderParams'`
*/
resolveHeaderParamsName(node: OperationNode, param: ParameterNode): string;
};
/**
* Options for {@link createOperationParams}.
*/
type CreateOperationParamsOptions = {
/**
* How all operation parameters are grouped in the function signature.
* - `'object'` wraps all params into a single destructured object `{ petId, data, params }`
* - `'inline'` emits each param category as a separate top-level parameter
*/
paramsType: 'object' | 'inline';
/**
* How path parameters are emitted when `paramsType` is `'inline'`.
* - `'object'` groups them as `{ petId, storeId }: PathParams`
* - `'inline'` spreads them as individual parameters `petId: string, storeId: string`
* - `'inlineSpread'` emits a single rest parameter `...pathParams: PathParams`
*/
pathParamsType: 'object' | 'inline' | 'inlineSpread';
/**
* Converts parameter names to camelCase before output.
*/
paramsCasing?: 'camelcase';
/**
* Resolver for parameter and request body type names.
* Pass `ResolverTs` from `@kubb/plugin-ts` directly.
* When omitted, falls back to the schema primitive or `'unknown'`.
*/
resolver?: OperationParamsResolver;
/**
* Default value for the path parameters binding when `pathParamsType` is `'object'`.
* Falls back to `'{}'` when all path params are optional.
*/
pathParamsDefault?: string;
/**
* Extra parameters appended after the standard operation parameters.
*
* @example Plugin-specific trailing parameter
* ```ts
* extraParams: [createFunctionParameter({ name: 'options', type: 'Partial<RequestOptions>', default: '{}' })]
* ```
*/
extraParams?: Array<FunctionParameterNode>;
/**
* Override the default parameter names used for body, query, header, and rest-path groups.
*
* Useful when targeting languages or frameworks with different naming conventions.
*
* @default { data: 'data', params: 'params', headers: 'headers', path: 'pathParams' }
*/
paramNames?: {
/**
* Name for the request body parameter.
* @default 'data'
*/
data?: string;
/**
* Name for the query parameters group parameter.
* @default 'params'
*/
params?: string;
/**
* Name for the header parameters group parameter.
* @default 'headers'
*/
headers?: string;
/**
* Name for the rest path-parameters parameter when `pathParamsType` is `'inlineSpread'`.
* @default 'pathParams'
*/
path?: string;
};
/**
* Transforms every resolved type name before it lands in a parameter node, for framework-level
* type wrappers.
*
* @example Vue Query, wrap every parameter type with `MaybeRefOrGetter`
* `typeWrapper: (t) => \`MaybeRefOrGetter<${t}>\``
*/
typeWrapper?: (type: string) => string;
};
/**
* Resolves the {@link TypeExpression} for an individual parameter.
*
* Without a resolver, it falls back to the schema primitive (a plain type-name string). When the
* parameter belongs to a named group, it emits an {@link IndexedAccessTypeNode} like
* `GroupParams['petId']`, otherwise the resolved individual name.
*/
declare function resolveParamType({
node,
param,
resolver
}: {
node: OperationNode;
param: ParameterNode;
resolver: OperationParamsResolver | undefined;
}): TypeExpression;
/**
* Converts an `OperationNode` into function parameters for code generation.
*
* Centralizes parameter grouping logic for all plugins. `paramsType` chooses between one
* destructured object parameter (`object`) and separate top-level parameters (`inline`), while
* `pathParamsType` controls how path params render in inline mode. Provide a `resolver` for type
* name resolution and `extraParams` for plugin-specific trailing parameters such as an `options` object.
*/
declare function createOperationParams(node: OperationNode, options: CreateOperationParamsOptions): FunctionParametersNode;
/**
* Shared arguments for building a query or header parameter group.
*/
type BuildGroupArgs = {
name: string;
node: OperationNode;
params: Array<ParameterNode>;
groupType: ParamGroupType | null;
resolver: OperationParamsResolver | undefined;
wrapType: (type: string) => string;
};
/**
* Builds a single {@link FunctionParameterNode} for a query or header group.
* Returns an empty array when there are no params to emit.
*
* A pre-resolved `groupType` emits `name: GroupType`. Otherwise it builds an inline
* {@link TypeLiteralNode} from the individual params.
*/
declare function buildGroupParam(args: BuildGroupArgs): Array<FunctionParameterNode>;
/**
* Builds a {@link TypeLiteralNode} for an inline anonymous type grouping named fields.
*
* Used when query or header parameters have no dedicated group type name.
* Each language printer renders this appropriately (TypeScript: `{ petId: string; name?: string }`).
*/
declare function buildTypeLiteral({
node,
params,
resolver
}: {
node: OperationNode;
params: Array<ParameterNode>;
resolver: OperationParamsResolver | undefined;
}): TypeLiteralNode;
//#endregion
export { buildTypeLiteral as a, resolveParamType as c, buildGroupParam as i, OperationParamsResolver as n, caseParams as o, ParamGroupType as r, createOperationParams as s, BuildGroupArgs as t };
//# sourceMappingURL=operationParams-DCY3q4C7.d.ts.map
import { n as __name } from "./rolldown-runtime-CNktS9qV.js";
import { _t as SchemaNode, t as Node, vt as SchemaNodeByType, yt as SchemaType } from "./index-CeJAFegf.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 JSON Schema, so this is the one seam where
* OpenAPI, AsyncAPI, and plain JSON Schema 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;
};
/**
* How a dialect collapses structurally identical schemas into shared definitions. The contract is
* generic over the plan and context types, which the adapter supplies. The mechanics live in the
* adapter, not here, so `@kubb/ast` carries no dedupe logic. The returned plan owns the rewriting
* behavior, so callers interact with one object.
*/
type Dedupe<TPlan = unknown, TContext = unknown> = {
/**
* Scans a forest of nodes and produces a plan describing which shapes to share.
*/
plan(roots: ReadonlyArray<Node>, context: TContext): TPlan;
};
/**
* A spec adapter's dialect. `name` identifies it in logs and diagnostics, `schema` holds the
* spec-specific schema questions the parser answers, and `dedupe` is the schema-sharing seam.
*/
type DefineDialect<TSchema = unknown, TRef = TSchema, TDiscriminated = TSchema, TDocument = unknown, TDedupe extends Dedupe = Dedupe> = {
/**
* Identifies the dialect in logs and diagnostics.
*/
name: string;
/**
* The spec-specific schema behavior. See {@link SchemaDialect}.
*/
schema: SchemaDialect<TSchema, TRef, TDiscriminated, TDocument>;
/**
* The schema-sharing behavior. See {@link Dedupe}.
*/
dedupe: TDedupe;
};
/**
* Types a {@link DefineDialect} 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,
* },
* dedupe: { plan },
* })
* ```
*/
declare function defineDialect<TSchema, TRef, TDiscriminated, TDocument, TDedupe extends Dedupe>(dialect: DefineDialect<TSchema, TRef, TDiscriminated, TDocument, TDedupe>): DefineDialect<TSchema, TRef, TDiscriminated, TDocument, TDedupe>;
//#endregion
//#region src/definePrinter.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;
/**
* 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> }>;
/**
* 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;
};
/**
* Defines 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.
* - `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 { definePrinter, type PrinterFactoryOptions } from '@kubb/ast'
*
* type PrinterZod = PrinterFactoryOptions<'zod', { strict?: boolean }, string>
*
* export const zodPrinter = definePrinter<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 definePrinter<T extends PrinterFactoryOptions = PrinterFactoryOptions>(build: PrinterBuilder<T>): (options?: T['options']) => Printer<T>;
/**
* Generic printer factory behind `definePrinter`. Pass a `getKey` function that maps a node to its
* handler key, and it returns a `definePrinter`-style helper for that node and key type. `definePrinter`
* itself is this factory keyed by `node.type`.
*
* @example Key a printer by `node.kind` instead of `node.type`
* ```ts
* const defineFunctionPrinter = createPrinterFactory<FunctionParamNode, FunctionParamKind, Partial<Record<FunctionParamKind, FunctionParamNode>>>(
* (node) => node.kind,
* )
* ```
*/
declare function createPrinterFactory<TNode, TKey extends string, TNodeByKey extends Partial<Record<TKey, TNode>>>(getKey: (node: TNode) => TKey | null): <T extends PrinterFactoryOptions>(build: (options: T["options"]) => {
name: T["name"];
options: T["options"];
nodes: Partial<{ [K in TKey]: (this: {
transform: (node: TNode) => T["output"] | null;
options: T["options"];
}, node: TNodeByKey[K]) => T["output"] | null }>;
print?: (this: {
transform: (node: TNode) => T["output"] | null;
options: T["options"];
}, node: TNode) => T["printOutput"] | null;
}) => (options?: T["options"]) => {
name: T["name"];
options: T["options"];
transform: (node: TNode) => T["output"] | null;
print: (node: TNode) => T["printOutput"] | null;
};
//#endregion
export { definePrinter as a, SchemaDialect as c, createPrinterFactory as i, defineDialect as l, PrinterFactoryOptions as n, Dedupe as o, PrinterPartial as r, DefineDialect as s, Printer as t };
//# sourceMappingURL=types-B6thixAv.d.ts.map
+2
-2

@@ -1,3 +0,3 @@

import { F as createFunctionParameters, Gt as createBreak, I as createIndexedAccessType, J as UserFileNode, Jt as createJsx, Kt as createConst, L as createObjectBindingPattern, Ot as createProperty, P as createFunctionParameter, Q as createSource, R as createTypeLiteral, Wt as createArrowFunction, X as createFile, Xt as createType, Y as createExport, Yt as createText, Z as createImport, _ as createResponse, at as createContent, b as createRequestBody, p as createOperation, qt as createFunction, r as createOutput, s as createInput, w as createParameter, wt as createSchema } from "./index-BKD4drsX.js";
import { n as update } from "./factory-wJLzHeXT.js";
import { F as createFunctionParameters, Gt as createBreak, I as createIndexedAccessType, J as UserFileNode, Jt as createJsx, Kt as createConst, L as createObjectBindingPattern, Ot as createProperty, P as createFunctionParameter, Q as createSource, R as createTypeLiteral, Wt as createArrowFunction, X as createFile, Xt as createType, Y as createExport, Yt as createText, Z as createImport, _ as createResponse, at as createContent, b as createRequestBody, p as createOperation, qt as createFunction, r as createOutput, s as createInput, w as createParameter, wt as createSchema } from "./index-CeJAFegf.js";
import { n as update } from "./factory-B_qPwA1b.js";
export { type UserFileNode, createArrowFunction, createBreak, createConst, createContent, createExport, createFile, createFunction, createFunctionParameter, createFunctionParameters, createImport, createIndexedAccessType, createInput, createJsx, createObjectBindingPattern, createOperation, createOutput, createParameter, createProperty, createRequestBody, createResponse, createSchema, createSource, createText, createType, createTypeLiteral, update };

@@ -345,3 +345,3 @@ Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });

* share a signature when they are structurally identical, ignoring documentation (`name`, `title`,
* `description`, `example`, `default`, `deprecated`) and usage-slot flags (`optional`, `nullish`,
* `description`, `examples`, `default`, `deprecated`) and usage-slot flags (`optional`, `nullish`,
* `readOnly`, `writeOnly`). `nullable` is kept because it changes the produced type, and `ref`

@@ -348,0 +348,0 @@ * nodes compare by target name, which also terminates on circular shapes.

@@ -1,1 +0,1 @@

{"version":3,"file":"index.cjs","names":["extractRefName","obj"],"sources":["../src/defineDialect.ts","../src/definePrinter.ts","../src/signature.ts","../src/exports.ts"],"sourcesContent":["import type { Node } from './nodes/index.ts'\n\n/**\n * The spec-specific questions a schema parser answers while turning a source document into Kubb\n * AST nodes. The rest of the pipeline is generic JSON Schema, so this is the one seam where\n * OpenAPI, AsyncAPI, and plain JSON Schema differ.\n */\nexport type SchemaDialect<TSchema = unknown, TRef = TSchema, TDiscriminated = TSchema, TDocument = unknown> = {\n /**\n * Whether the schema is nullable.\n */\n isNullable(schema?: TSchema): boolean\n /**\n * Whether the value is a `$ref` pointer.\n */\n isReference(value?: unknown): value is TRef\n /**\n * Whether the schema carries a discriminator for polymorphism.\n */\n isDiscriminator(value?: unknown): value is TDiscriminated\n /**\n * Whether the schema is binary data, converted to a `blob` node.\n */\n isBinary(schema: TSchema): boolean\n /**\n * Resolves a local `$ref` against the document, or nullish when it cannot.\n */\n resolveRef<TResolved>(document: TDocument, ref: string): TResolved | null | undefined\n}\n\n/**\n * How a dialect collapses structurally identical schemas into shared definitions. The contract is\n * generic over the plan and context types, which the adapter supplies. The mechanics live in the\n * adapter, not here, so `@kubb/ast` carries no dedupe logic. The returned plan owns the rewriting\n * behavior, so callers interact with one object.\n */\nexport type Dedupe<TPlan = unknown, TContext = unknown> = {\n /**\n * Scans a forest of nodes and produces a plan describing which shapes to share.\n */\n plan(roots: ReadonlyArray<Node>, context: TContext): TPlan\n}\n\n/**\n * A spec adapter's dialect. `name` identifies it in logs and diagnostics, `schema` holds the\n * spec-specific schema questions the parser answers, and `dedupe` is the schema-sharing seam.\n */\nexport type DefineDialect<TSchema = unknown, TRef = TSchema, TDiscriminated = TSchema, TDocument = unknown, TDedupe extends Dedupe = Dedupe> = {\n /**\n * Identifies the dialect in logs and diagnostics.\n */\n name: string\n /**\n * The spec-specific schema behavior. See {@link SchemaDialect}.\n */\n schema: SchemaDialect<TSchema, TRef, TDiscriminated, TDocument>\n /**\n * The schema-sharing behavior. See {@link Dedupe}.\n */\n dedupe: TDedupe\n}\n\n/**\n * Types a {@link DefineDialect} for an adapter. Adds no runtime behavior and only pins the\n * dialect's type for inference.\n *\n * @example\n * ```ts\n * export const oasDialect = defineDialect({\n * name: 'oas',\n * schema: {\n * isNullable,\n * isReference,\n * isDiscriminator,\n * isBinary: (schema) => schema.type === 'string' && schema.contentMediaType === 'application/octet-stream',\n * resolveRef,\n * },\n * dedupe: { plan },\n * })\n * ```\n */\nexport function defineDialect<TSchema, TRef, TDiscriminated, TDocument, TDedupe extends Dedupe>(\n dialect: DefineDialect<TSchema, TRef, TDiscriminated, TDocument, TDedupe>,\n): DefineDialect<TSchema, TRef, TDiscriminated, TDocument, TDedupe> {\n return dialect\n}\n","import type { SchemaNode, SchemaNodeByType, SchemaType } from './nodes/index.ts'\n\n/**\n * Runtime context passed as `this` to printer handlers.\n *\n * `this.transform` dispatches to node-level handlers from `nodes`.\n *\n * @example\n * ```ts\n * const context: PrinterHandlerContext<string, {}> = {\n * options: {},\n * transform: () => 'value',\n * }\n * ```\n */\ntype PrinterHandlerContext<TOutput, TOptions extends object> = {\n /**\n * Recursively transform a nested `SchemaNode` to `TOutput` using the node-level handlers.\n * Use `this.transform` inside `nodes` handlers and inside the `print` override.\n */\n transform: (node: SchemaNode) => TOutput | null\n /**\n * Options for this printer instance.\n */\n options: TOptions\n}\n\n/**\n * Handler for one schema node type.\n *\n * Use a regular function (not an arrow function) if you need `this`.\n *\n * @example\n * ```ts\n * const handler: PrinterHandler<string, {}, 'string'> = function () {\n * return 'string'\n * }\n * ```\n */\ntype PrinterHandler<TOutput, TOptions extends object, T extends SchemaType = SchemaType> = (\n this: PrinterHandlerContext<TOutput, TOptions>,\n node: SchemaNodeByType[T],\n) => TOutput | null\n\n/**\n * Partial map of per-node-type handler overrides for a printer.\n *\n * Each key is a `SchemaType` string (e.g. `'date'`, `'string'`).\n * Supply only the handlers you want to replace. The printer's built-in\n * defaults fill in the rest.\n *\n * @example\n * ```ts\n * pluginZod({\n * printer: {\n * nodes: {\n * date(): string {\n * return 'z.string().date()'\n * },\n * } satisfies PrinterPartial<string, PrinterZodOptions>,\n * },\n * })\n * ```\n */\nexport type PrinterPartial<TOutput, TOptions extends object> = Partial<{\n [K in SchemaType]: PrinterHandler<TOutput, TOptions, K>\n}>\n\n/**\n * Generic shape used by `definePrinter`.\n *\n * - `TName` unique string identifier (e.g. `'zod'`, `'ts'`)\n * - `TOptions` options passed to and stored on the printer instance\n * - `TOutput` the type emitted by node handlers\n * - `TPrintOutput` type returned by public `print` (defaults to `TOutput`)\n *\n * @example\n * ```ts\n * type MyPrinter = PrinterFactoryOptions<'my', { strict: boolean }, string>\n * ```\n */\nexport type PrinterFactoryOptions<TName extends string = string, TOptions extends object = object, TOutput = unknown, TPrintOutput = TOutput> = {\n name: TName\n options: TOptions\n output: TOutput\n printOutput: TPrintOutput\n}\n\n/**\n * Printer instance returned by a printer factory.\n *\n * @example\n * ```ts\n * const printer = definePrinter((options: {}) => ({ name: 'x', options, nodes: {} }))({})\n * ```\n */\nexport type Printer<T extends PrinterFactoryOptions = PrinterFactoryOptions> = {\n /**\n * Unique identifier supplied at creation time.\n */\n name: T['name']\n /**\n * Options for this printer instance.\n */\n options: T['options']\n /**\n * Node-level dispatcher, converts a `SchemaNode` directly to `TOutput` using the `nodes` handlers.\n * Always dispatches through the `nodes` map. Never calls the `print` override.\n * Reach for it when you need the raw output (e.g. `ts.TypeNode`) without declaration wrapping.\n */\n transform: (node: SchemaNode) => T['output'] | null\n /**\n * Public printer. If the builder provides a root-level `print`, this calls that\n * higher-level function (which may produce full declarations).\n * Otherwise, falls back to the node-level dispatcher.\n */\n print: (node: SchemaNode) => T['printOutput'] | null\n}\n\n/**\n * Builder function passed to `definePrinter`.\n *\n * It receives resolved options and returns:\n * - `name`\n * - `options`\n * - `nodes` handlers\n * - optional top-level `print` override\n *\n * @example\n * ```ts\n * const build = (options: {}) => ({ name: 'x' as const, options, nodes: {} })\n * ```\n */\ntype PrinterBuilder<T extends PrinterFactoryOptions> = (options: T['options']) => {\n name: T['name']\n /**\n * Options to store on the printer.\n */\n options: T['options']\n nodes: Partial<{\n [K in SchemaType]: PrinterHandler<T['output'], T['options'], K>\n }>\n /**\n * Optional root-level print override. When provided, becomes the public `printer.print`.\n * Use `this.transform(node)` inside this function to dispatch to the node-level handlers (`nodes`),\n * not the override itself, so recursion is safe.\n */\n print?: (this: PrinterHandlerContext<T['output'], T['options']>, node: SchemaNode) => T['printOutput'] | null\n}\n/**\n * Defines a schema printer: a function that takes a `SchemaNode` and emits\n * code in your target language. Each plugin that produces code from schemas\n * (TypeScript types, Zod schemas, Faker factories) ships a printer built\n * with this helper.\n *\n * The builder receives resolved options and returns:\n *\n * - `name` unique identifier for the printer.\n * - `options` stored on the returned printer instance.\n * - `nodes` map of `SchemaType` → handler. Handlers return the rendered\n * output (a string, a TypeScript AST node, ...) for that schema type.\n * - `print` (optional), top-level override exposed as `printer.print`.\n * Use `this.transform(node)` inside it to dispatch to `nodes` recursively.\n *\n * Without a `print` override, `printer.print` falls back to `printer.transform`\n * (the node-level dispatcher).\n *\n * @example Tiny Zod printer\n * ```ts\n * import { definePrinter, type PrinterFactoryOptions } from '@kubb/ast'\n *\n * type PrinterZod = PrinterFactoryOptions<'zod', { strict?: boolean }, string>\n *\n * export const zodPrinter = definePrinter<PrinterZod>((options) => ({\n * name: 'zod',\n * options: { strict: options.strict ?? true },\n * nodes: {\n * string: () => 'z.string()',\n * object(node) {\n * const props = node.properties\n * .map((p) => `${p.name}: ${this.transform(p.schema)}`)\n * .join(', ')\n * return `z.object({ ${props} })`\n * },\n * },\n * }))\n * ```\n */\nexport function definePrinter<T extends PrinterFactoryOptions = PrinterFactoryOptions>(build: PrinterBuilder<T>): (options?: T['options']) => Printer<T> {\n return createPrinterFactory<SchemaNode, SchemaType, SchemaNodeByType>((node) => node.type)(build) as (options?: T['options']) => Printer<T>\n}\n\n/**\n * Generic printer factory behind `definePrinter`. Pass a `getKey` function that maps a node to its\n * handler key, and it returns a `definePrinter`-style helper for that node and key type. `definePrinter`\n * itself is this factory keyed by `node.type`.\n *\n * @example Key a printer by `node.kind` instead of `node.type`\n * ```ts\n * const defineFunctionPrinter = createPrinterFactory<FunctionParamNode, FunctionParamKind, Partial<Record<FunctionParamKind, FunctionParamNode>>>(\n * (node) => node.kind,\n * )\n * ```\n */\nexport function createPrinterFactory<TNode, TKey extends string, TNodeByKey extends Partial<Record<TKey, TNode>>>(getKey: (node: TNode) => TKey | null) {\n return function <T extends PrinterFactoryOptions>(\n build: (options: T['options']) => {\n name: T['name']\n options: T['options']\n nodes: Partial<{\n [K in TKey]: (\n this: {\n transform: (node: TNode) => T['output'] | null\n options: T['options']\n },\n node: TNodeByKey[K],\n ) => T['output'] | null\n }>\n print?: (\n this: {\n transform: (node: TNode) => T['output'] | null\n options: T['options']\n },\n node: TNode,\n ) => T['printOutput'] | null\n },\n ): (options?: T['options']) => {\n name: T['name']\n options: T['options']\n transform: (node: TNode) => T['output'] | null\n print: (node: TNode) => T['printOutput'] | null\n } {\n return (options) => {\n const { name, options: resolvedOptions, nodes, print: printOverride } = build(options ?? ({} as T['options']))\n\n const context = {\n options: resolvedOptions,\n transform: (node: TNode): T['output'] | null => {\n const key = getKey(node)\n if (key === null) return null\n\n const handler = nodes[key]\n\n if (!handler) return null\n\n return (handler as (this: typeof context, node: TNode) => T['output'] | null).call(context, node)\n },\n }\n\n return {\n name,\n options: resolvedOptions,\n transform: context.transform,\n print: (printOverride ? printOverride.bind(context) : context.transform) as (node: TNode) => T['printOutput'] | null,\n }\n }\n }\n}\n","import { hash } from 'node:crypto'\nimport type { SchemaNode } from './nodes/index.ts'\nimport { extractRefName } from './utils/index.ts'\n\n/**\n * The flags shared by every node kind that affect its type: `primitive`, `format`, `nullable`.\n */\nfunction flagsDescriptor(node: SchemaNode): string {\n return `${node.primitive ?? ''};${node.format ?? ''};${node.nullable ? 1 : 0}`\n}\n\nfunction refTargetName(node: Extract<SchemaNode, { type: 'ref' }>): string {\n if (node.ref) return extractRefName(node.ref)\n return node.name ?? ''\n}\n\ntype ScalarField = { kind: 'scalar'; key: string; prefix: string }\ntype BoolField = { kind: 'bool'; key: string; prefix: string }\ntype ChildField = { kind: 'child'; key: string; prefix: string }\ntype ChildrenField = { kind: 'children'; key: string; prefix: string }\ntype ObjectPropsField = { kind: 'objectProps' }\ntype AdditionalPropsField = { kind: 'additionalProps' }\ntype PatternPropsField = { kind: 'patternProps' }\ntype EnumValuesField = { kind: 'enumValues' }\ntype RefTargetField = { kind: 'refTarget' }\n\ntype ShapeField =\n | ScalarField\n | BoolField\n | ChildField\n | ChildrenField\n | ObjectPropsField\n | AdditionalPropsField\n | PatternPropsField\n | EnumValuesField\n | RefTargetField\n\nconst arrayTupleFields: ReadonlyArray<ShapeField> = [\n { kind: 'children', key: 'items', prefix: 'i' },\n { kind: 'child', key: 'rest', prefix: 'r' },\n { kind: 'scalar', key: 'min', prefix: 'mn' },\n { kind: 'scalar', key: 'max', prefix: 'mx' },\n { kind: 'bool', key: 'unique', prefix: 'u' },\n]\n\nconst numericFields: ReadonlyArray<ShapeField> = [\n { kind: 'scalar', key: 'min', prefix: 'mn' },\n { kind: 'scalar', key: 'max', prefix: 'mx' },\n { kind: 'scalar', key: 'exclusiveMinimum', prefix: 'emn' },\n { kind: 'scalar', key: 'exclusiveMaximum', prefix: 'emx' },\n { kind: 'scalar', key: 'multipleOf', prefix: 'mo' },\n]\n\nconst rangeFields: ReadonlyArray<ShapeField> = [\n { kind: 'scalar', key: 'min', prefix: 'mn' },\n { kind: 'scalar', key: 'max', prefix: 'mx' },\n]\n\n/**\n * Maps each node `type` to its ordered shape-contributing fields. Types absent from the map\n * (boolean, null, any, and other scalars) fall back to `${type}|${flags}`.\n */\nconst SHAPE_KEYS: Partial<Record<SchemaNode['type'], ReadonlyArray<ShapeField>>> = {\n object: [\n { kind: 'objectProps' },\n { kind: 'additionalProps' },\n { kind: 'patternProps' },\n { kind: 'scalar', key: 'minProperties', prefix: 'mn' },\n { kind: 'scalar', key: 'maxProperties', prefix: 'mx' },\n ],\n array: arrayTupleFields,\n tuple: arrayTupleFields,\n union: [\n { kind: 'scalar', key: 'strategy', prefix: 's' },\n { kind: 'scalar', key: 'discriminatorPropertyName', prefix: 'd' },\n { kind: 'children', key: 'members', prefix: 'm' },\n ],\n intersection: [{ kind: 'children', key: 'members', prefix: 'm' }],\n enum: [{ kind: 'enumValues' }],\n ref: [{ kind: 'refTarget' }],\n string: [\n { kind: 'scalar', key: 'min', prefix: 'mn' },\n { kind: 'scalar', key: 'max', prefix: 'mx' },\n { kind: 'scalar', key: 'pattern', prefix: 'pt' },\n ],\n number: numericFields,\n integer: numericFields,\n bigint: numericFields,\n url: [\n { kind: 'scalar', key: 'path', prefix: 'path' },\n { kind: 'scalar', key: 'min', prefix: 'mn' },\n { kind: 'scalar', key: 'max', prefix: 'mx' },\n ],\n uuid: rangeFields,\n email: rangeFields,\n datetime: [\n { kind: 'bool', key: 'offset', prefix: 'o' },\n { kind: 'bool', key: 'local', prefix: 'l' },\n ],\n date: [{ kind: 'scalar', key: 'representation', prefix: 'rep' }],\n time: [{ kind: 'scalar', key: 'representation', prefix: 'rep' }],\n}\n\nfunction serializeShapeField(field: ShapeField, node: SchemaNode, record: Record<string, unknown>): string {\n switch (field.kind) {\n case 'scalar':\n return `${field.prefix}:${record[field.key] ?? ''}`\n case 'bool':\n return `${field.prefix}:${record[field.key] ? 1 : 0}`\n case 'child': {\n const child = record[field.key] as SchemaNode | undefined\n return `${field.prefix}:${child ? signatureOf(child) : ''}`\n }\n case 'children': {\n const children = (record[field.key] as Array<SchemaNode> | undefined) ?? []\n return `${field.prefix}[${children.map((c) => signatureOf(c)).join(',')}]`\n }\n case 'objectProps': {\n const obj = node as Extract<SchemaNode, { type: 'object' }>\n const props = (obj.properties ?? []).map((prop) => `${prop.name}${prop.required ? '!' : '?'}${signatureOf(prop.schema)}`).join(',')\n return `p[${props}]`\n }\n case 'additionalProps': {\n const obj = node as Extract<SchemaNode, { type: 'object' }>\n if (typeof obj.additionalProperties === 'boolean') return `ab:${obj.additionalProperties}`\n if (obj.additionalProperties) return `as:${signatureOf(obj.additionalProperties)}`\n return ''\n }\n case 'patternProps': {\n const obj = node as Extract<SchemaNode, { type: 'object' }>\n const pattern = obj.patternProperties\n ? Object.keys(obj.patternProperties)\n .sort()\n .map((key) => `${key}=${signatureOf(obj.patternProperties![key]!)}`)\n .join(',')\n : ''\n return `pp[${pattern}]`\n }\n case 'enumValues': {\n const en = node as Extract<SchemaNode, { type: 'enum' }>\n let values = ''\n if (en.namedEnumValues?.length) {\n values = en.namedEnumValues.map((entry) => `${entry.name}=${entry.primitive}:${String(entry.value)}`).join(',')\n } else if (en.enumValues?.length) {\n values = en.enumValues.map((value) => `${value === null ? 'null' : typeof value}:${String(value)}`).join(',')\n }\n return `v[${values}]`\n }\n case 'refTarget': {\n return `->${refTargetName(node as Extract<SchemaNode, { type: 'ref' }>)}`\n }\n }\n}\n\n/**\n * Builds the local shape descriptor that {@link signatureOf} hashes: the node's kind, flags,\n * constraints, and its children's signatures.\n */\nfunction describeShape(node: SchemaNode): string {\n const flags = flagsDescriptor(node)\n const fields = SHAPE_KEYS[node.type]\n if (!fields) return `${node.type}|${flags}`\n\n const record = node as unknown as Record<string, unknown>\n const parts: Array<string> = [`${node.type}|${flags}`]\n for (const field of fields) {\n parts.push(serializeShapeField(field, node, record))\n }\n return parts.join('|')\n}\n\n/**\n * Caches the digest per node, keyed by identity. A `WeakMap` so entries die with the node, and so\n * a tree hashed during dedupe planning is not walked again when it is rewritten during streaming.\n * Reuse is safe because a signature depends only on content, and nodes are immutable once created.\n */\nconst signatureCache = new WeakMap<SchemaNode, string>()\n\n/**\n * Computes a deterministic, shape-only signature (a content hash) for a schema node. Two schemas\n * share a signature when they are structurally identical, ignoring documentation (`name`, `title`,\n * `description`, `example`, `default`, `deprecated`) and usage-slot flags (`optional`, `nullish`,\n * `readOnly`, `writeOnly`). `nullable` is kept because it changes the produced type, and `ref`\n * nodes compare by target name, which also terminates on circular shapes.\n *\n * @example Two enums with different descriptions share a signature\n * ```ts\n * signatureOf(createSchema({ type: 'enum', primitive: 'string', enumValues: ['a', 'b'], description: 'x' })) ===\n * signatureOf(createSchema({ type: 'enum', primitive: 'string', enumValues: ['a', 'b'] }))\n * ```\n */\nexport function signatureOf(node: SchemaNode): string {\n const cached = signatureCache.get(node)\n if (cached !== undefined) return cached\n const signature = hash('sha256', describeShape(node), 'hex')\n signatureCache.set(node, signature)\n\n return signature\n}\n\n/**\n * Returns `true` when two schema nodes are structurally identical under shape-only equality,\n * meaning they produce the same TypeScript type.\n */\nexport function isSchemaEqual(a: SchemaNode, b: SchemaNode): boolean {\n return signatureOf(a) === signatureOf(b)\n}\n","export { schemaTypes } from './constants.ts'\nexport { defineDialect } from './defineDialect.ts'\nexport { isHttpOperationNode, narrowSchema } from './guards.ts'\nexport { applyMacros, composeMacros, defineMacro } from './defineMacro.ts'\nexport { defineNode } from './defineNode.ts'\nexport { optionality } from './optionality.ts'\nexport { createPrinterFactory, definePrinter } from './definePrinter.ts'\nexport { signatureOf } from './signature.ts'\nexport { collect, transform, walk } from './visitor.ts'\n\nexport * as factory from './factory.ts'\nexport * from './registry.ts'\nexport type * from './types.ts'\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;AAiFA,SAAgB,cACd,SACkE;CAClE,OAAO;AACT;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ACuGA,SAAgB,cAAuE,OAAkE;CACvJ,OAAO,sBAAgE,SAAS,KAAK,IAAI,CAAC,CAAC,KAAK;AAClG;;;;;;;;;;;;;AAcA,SAAgB,qBAAkG,QAAsC;CACtJ,OAAO,SACL,OAyBA;EACA,QAAQ,YAAY;GAClB,MAAM,EAAE,MAAM,SAAS,iBAAiB,OAAO,OAAO,kBAAkB,MAAM,WAAY,CAAC,CAAkB;GAE7G,MAAM,UAAU;IACd,SAAS;IACT,YAAY,SAAoC;KAC9C,MAAM,MAA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GAAG,YAAY,QACxB,SAAS,GAAG,WAAW,KAAK,UAAU,GAAG,UAAU,OAAO,SAAS,OAAO,MAAM,GAAG,OAAO,KAAK,GAAG,CAAC,CAAC,KAAK,GAAG;GAE9G,OAAO,KAAK,OAAO;EACrB;EACA,KAAK,aACH,OAAO,KAAK,cAAc,IAA4C;CAE1E;AACF;;;;;AAMA,SAAS,cAAc,MAA0B;CAC/C,MAAM,QAAQ,gBAAgB,IAAI;CAClC,MAAM,SAAS,WAAW,KAAK;CAC/B,IAAI,CAAC,QAAQ,OAAO,GAAG,KAAK,KAAK,GAAG;CAEpC,MAAM,SAAS;CACf,MAAM,QAAuB,CAAC,GAAG,KAAK,KAAK,GAAG,OAAO;CACrD,KAAK,MAAM,SAAS,QAClB,MAAM,KAAK,oBAAoB,OAAO,MAAM,MAAM,CAAC;CAErD,OAAO,MAAM,KAAK,GAAG;AACvB;;;;;;AAOA,MAAM,iCAAiB,IAAI,QAA4B;;;;;;;;;;;;;;AAevD,SAAgB,YAAY,MAA0B;CACpD,MAAM,SAAS,eAAe,IAAI,IAAI;CACtC,IAAI,WAAW,KAAA,GAAW,OAAO;CACjC,MAAM,aAAA,GAAA,YAAA,KAAA,CAAiB,UAAU,cAAc,IAAI,GAAG,KAAK;CAC3D,eAAe,IAAI,MAAM,SAAS;CAElC,OAAO;AACT"}
{"version":3,"file":"index.cjs","names":["extractRefName","obj"],"sources":["../src/defineDialect.ts","../src/definePrinter.ts","../src/signature.ts","../src/exports.ts"],"sourcesContent":["import type { Node } from './nodes/index.ts'\n\n/**\n * The spec-specific questions a schema parser answers while turning a source document into Kubb\n * AST nodes. The rest of the pipeline is generic JSON Schema, so this is the one seam where\n * OpenAPI, AsyncAPI, and plain JSON Schema differ.\n */\nexport type SchemaDialect<TSchema = unknown, TRef = TSchema, TDiscriminated = TSchema, TDocument = unknown> = {\n /**\n * Whether the schema is nullable.\n */\n isNullable(schema?: TSchema): boolean\n /**\n * Whether the value is a `$ref` pointer.\n */\n isReference(value?: unknown): value is TRef\n /**\n * Whether the schema carries a discriminator for polymorphism.\n */\n isDiscriminator(value?: unknown): value is TDiscriminated\n /**\n * Whether the schema is binary data, converted to a `blob` node.\n */\n isBinary(schema: TSchema): boolean\n /**\n * Resolves a local `$ref` against the document, or nullish when it cannot.\n */\n resolveRef<TResolved>(document: TDocument, ref: string): TResolved | null | undefined\n}\n\n/**\n * How a dialect collapses structurally identical schemas into shared definitions. The contract is\n * generic over the plan and context types, which the adapter supplies. The mechanics live in the\n * adapter, not here, so `@kubb/ast` carries no dedupe logic. The returned plan owns the rewriting\n * behavior, so callers interact with one object.\n */\nexport type Dedupe<TPlan = unknown, TContext = unknown> = {\n /**\n * Scans a forest of nodes and produces a plan describing which shapes to share.\n */\n plan(roots: ReadonlyArray<Node>, context: TContext): TPlan\n}\n\n/**\n * A spec adapter's dialect. `name` identifies it in logs and diagnostics, `schema` holds the\n * spec-specific schema questions the parser answers, and `dedupe` is the schema-sharing seam.\n */\nexport type DefineDialect<TSchema = unknown, TRef = TSchema, TDiscriminated = TSchema, TDocument = unknown, TDedupe extends Dedupe = Dedupe> = {\n /**\n * Identifies the dialect in logs and diagnostics.\n */\n name: string\n /**\n * The spec-specific schema behavior. See {@link SchemaDialect}.\n */\n schema: SchemaDialect<TSchema, TRef, TDiscriminated, TDocument>\n /**\n * The schema-sharing behavior. See {@link Dedupe}.\n */\n dedupe: TDedupe\n}\n\n/**\n * Types a {@link DefineDialect} for an adapter. Adds no runtime behavior and only pins the\n * dialect's type for inference.\n *\n * @example\n * ```ts\n * export const oasDialect = defineDialect({\n * name: 'oas',\n * schema: {\n * isNullable,\n * isReference,\n * isDiscriminator,\n * isBinary: (schema) => schema.type === 'string' && schema.contentMediaType === 'application/octet-stream',\n * resolveRef,\n * },\n * dedupe: { plan },\n * })\n * ```\n */\nexport function defineDialect<TSchema, TRef, TDiscriminated, TDocument, TDedupe extends Dedupe>(\n dialect: DefineDialect<TSchema, TRef, TDiscriminated, TDocument, TDedupe>,\n): DefineDialect<TSchema, TRef, TDiscriminated, TDocument, TDedupe> {\n return dialect\n}\n","import type { SchemaNode, SchemaNodeByType, SchemaType } from './nodes/index.ts'\n\n/**\n * Runtime context passed as `this` to printer handlers.\n *\n * `this.transform` dispatches to node-level handlers from `nodes`.\n *\n * @example\n * ```ts\n * const context: PrinterHandlerContext<string, {}> = {\n * options: {},\n * transform: () => 'value',\n * }\n * ```\n */\ntype PrinterHandlerContext<TOutput, TOptions extends object> = {\n /**\n * Recursively transform a nested `SchemaNode` to `TOutput` using the node-level handlers.\n * Use `this.transform` inside `nodes` handlers and inside the `print` override.\n */\n transform: (node: SchemaNode) => TOutput | null\n /**\n * Options for this printer instance.\n */\n options: TOptions\n}\n\n/**\n * Handler for one schema node type.\n *\n * Use a regular function (not an arrow function) if you need `this`.\n *\n * @example\n * ```ts\n * const handler: PrinterHandler<string, {}, 'string'> = function () {\n * return 'string'\n * }\n * ```\n */\ntype PrinterHandler<TOutput, TOptions extends object, T extends SchemaType = SchemaType> = (\n this: PrinterHandlerContext<TOutput, TOptions>,\n node: SchemaNodeByType[T],\n) => TOutput | null\n\n/**\n * Partial map of per-node-type handler overrides for a printer.\n *\n * Each key is a `SchemaType` string (e.g. `'date'`, `'string'`).\n * Supply only the handlers you want to replace. The printer's built-in\n * defaults fill in the rest.\n *\n * @example\n * ```ts\n * pluginZod({\n * printer: {\n * nodes: {\n * date(): string {\n * return 'z.string().date()'\n * },\n * } satisfies PrinterPartial<string, PrinterZodOptions>,\n * },\n * })\n * ```\n */\nexport type PrinterPartial<TOutput, TOptions extends object> = Partial<{\n [K in SchemaType]: PrinterHandler<TOutput, TOptions, K>\n}>\n\n/**\n * Generic shape used by `definePrinter`.\n *\n * - `TName` unique string identifier (e.g. `'zod'`, `'ts'`)\n * - `TOptions` options passed to and stored on the printer instance\n * - `TOutput` the type emitted by node handlers\n * - `TPrintOutput` type returned by public `print` (defaults to `TOutput`)\n *\n * @example\n * ```ts\n * type MyPrinter = PrinterFactoryOptions<'my', { strict: boolean }, string>\n * ```\n */\nexport type PrinterFactoryOptions<TName extends string = string, TOptions extends object = object, TOutput = unknown, TPrintOutput = TOutput> = {\n name: TName\n options: TOptions\n output: TOutput\n printOutput: TPrintOutput\n}\n\n/**\n * Printer instance returned by a printer factory.\n *\n * @example\n * ```ts\n * const printer = definePrinter((options: {}) => ({ name: 'x', options, nodes: {} }))({})\n * ```\n */\nexport type Printer<T extends PrinterFactoryOptions = PrinterFactoryOptions> = {\n /**\n * Unique identifier supplied at creation time.\n */\n name: T['name']\n /**\n * Options for this printer instance.\n */\n options: T['options']\n /**\n * Node-level dispatcher, converts a `SchemaNode` directly to `TOutput` using the `nodes` handlers.\n * Always dispatches through the `nodes` map. Never calls the `print` override.\n * Reach for it when you need the raw output (e.g. `ts.TypeNode`) without declaration wrapping.\n */\n transform: (node: SchemaNode) => T['output'] | null\n /**\n * Public printer. If the builder provides a root-level `print`, this calls that\n * higher-level function (which may produce full declarations).\n * Otherwise, falls back to the node-level dispatcher.\n */\n print: (node: SchemaNode) => T['printOutput'] | null\n}\n\n/**\n * Builder function passed to `definePrinter`.\n *\n * It receives resolved options and returns:\n * - `name`\n * - `options`\n * - `nodes` handlers\n * - optional top-level `print` override\n *\n * @example\n * ```ts\n * const build = (options: {}) => ({ name: 'x' as const, options, nodes: {} })\n * ```\n */\ntype PrinterBuilder<T extends PrinterFactoryOptions> = (options: T['options']) => {\n name: T['name']\n /**\n * Options to store on the printer.\n */\n options: T['options']\n nodes: Partial<{\n [K in SchemaType]: PrinterHandler<T['output'], T['options'], K>\n }>\n /**\n * Optional root-level print override. When provided, becomes the public `printer.print`.\n * Use `this.transform(node)` inside this function to dispatch to the node-level handlers (`nodes`),\n * not the override itself, so recursion is safe.\n */\n print?: (this: PrinterHandlerContext<T['output'], T['options']>, node: SchemaNode) => T['printOutput'] | null\n}\n/**\n * Defines a schema printer: a function that takes a `SchemaNode` and emits\n * code in your target language. Each plugin that produces code from schemas\n * (TypeScript types, Zod schemas, Faker factories) ships a printer built\n * with this helper.\n *\n * The builder receives resolved options and returns:\n *\n * - `name` unique identifier for the printer.\n * - `options` stored on the returned printer instance.\n * - `nodes` map of `SchemaType` → handler. Handlers return the rendered\n * output (a string, a TypeScript AST node, ...) for that schema type.\n * - `print` (optional), top-level override exposed as `printer.print`.\n * Use `this.transform(node)` inside it to dispatch to `nodes` recursively.\n *\n * Without a `print` override, `printer.print` falls back to `printer.transform`\n * (the node-level dispatcher).\n *\n * @example Tiny Zod printer\n * ```ts\n * import { definePrinter, type PrinterFactoryOptions } from '@kubb/ast'\n *\n * type PrinterZod = PrinterFactoryOptions<'zod', { strict?: boolean }, string>\n *\n * export const zodPrinter = definePrinter<PrinterZod>((options) => ({\n * name: 'zod',\n * options: { strict: options.strict ?? true },\n * nodes: {\n * string: () => 'z.string()',\n * object(node) {\n * const props = node.properties\n * .map((p) => `${p.name}: ${this.transform(p.schema)}`)\n * .join(', ')\n * return `z.object({ ${props} })`\n * },\n * },\n * }))\n * ```\n */\nexport function definePrinter<T extends PrinterFactoryOptions = PrinterFactoryOptions>(build: PrinterBuilder<T>): (options?: T['options']) => Printer<T> {\n return createPrinterFactory<SchemaNode, SchemaType, SchemaNodeByType>((node) => node.type)(build) as (options?: T['options']) => Printer<T>\n}\n\n/**\n * Generic printer factory behind `definePrinter`. Pass a `getKey` function that maps a node to its\n * handler key, and it returns a `definePrinter`-style helper for that node and key type. `definePrinter`\n * itself is this factory keyed by `node.type`.\n *\n * @example Key a printer by `node.kind` instead of `node.type`\n * ```ts\n * const defineFunctionPrinter = createPrinterFactory<FunctionParamNode, FunctionParamKind, Partial<Record<FunctionParamKind, FunctionParamNode>>>(\n * (node) => node.kind,\n * )\n * ```\n */\nexport function createPrinterFactory<TNode, TKey extends string, TNodeByKey extends Partial<Record<TKey, TNode>>>(getKey: (node: TNode) => TKey | null) {\n return function <T extends PrinterFactoryOptions>(\n build: (options: T['options']) => {\n name: T['name']\n options: T['options']\n nodes: Partial<{\n [K in TKey]: (\n this: {\n transform: (node: TNode) => T['output'] | null\n options: T['options']\n },\n node: TNodeByKey[K],\n ) => T['output'] | null\n }>\n print?: (\n this: {\n transform: (node: TNode) => T['output'] | null\n options: T['options']\n },\n node: TNode,\n ) => T['printOutput'] | null\n },\n ): (options?: T['options']) => {\n name: T['name']\n options: T['options']\n transform: (node: TNode) => T['output'] | null\n print: (node: TNode) => T['printOutput'] | null\n } {\n return (options) => {\n const { name, options: resolvedOptions, nodes, print: printOverride } = build(options ?? ({} as T['options']))\n\n const context = {\n options: resolvedOptions,\n transform: (node: TNode): T['output'] | null => {\n const key = getKey(node)\n if (key === null) return null\n\n const handler = nodes[key]\n\n if (!handler) return null\n\n return (handler as (this: typeof context, node: TNode) => T['output'] | null).call(context, node)\n },\n }\n\n return {\n name,\n options: resolvedOptions,\n transform: context.transform,\n print: (printOverride ? printOverride.bind(context) : context.transform) as (node: TNode) => T['printOutput'] | null,\n }\n }\n }\n}\n","import { hash } from 'node:crypto'\nimport type { SchemaNode } from './nodes/index.ts'\nimport { extractRefName } from './utils/index.ts'\n\n/**\n * The flags shared by every node kind that affect its type: `primitive`, `format`, `nullable`.\n */\nfunction flagsDescriptor(node: SchemaNode): string {\n return `${node.primitive ?? ''};${node.format ?? ''};${node.nullable ? 1 : 0}`\n}\n\nfunction refTargetName(node: Extract<SchemaNode, { type: 'ref' }>): string {\n if (node.ref) return extractRefName(node.ref)\n return node.name ?? ''\n}\n\ntype ScalarField = { kind: 'scalar'; key: string; prefix: string }\ntype BoolField = { kind: 'bool'; key: string; prefix: string }\ntype ChildField = { kind: 'child'; key: string; prefix: string }\ntype ChildrenField = { kind: 'children'; key: string; prefix: string }\ntype ObjectPropsField = { kind: 'objectProps' }\ntype AdditionalPropsField = { kind: 'additionalProps' }\ntype PatternPropsField = { kind: 'patternProps' }\ntype EnumValuesField = { kind: 'enumValues' }\ntype RefTargetField = { kind: 'refTarget' }\n\ntype ShapeField =\n | ScalarField\n | BoolField\n | ChildField\n | ChildrenField\n | ObjectPropsField\n | AdditionalPropsField\n | PatternPropsField\n | EnumValuesField\n | RefTargetField\n\nconst arrayTupleFields: ReadonlyArray<ShapeField> = [\n { kind: 'children', key: 'items', prefix: 'i' },\n { kind: 'child', key: 'rest', prefix: 'r' },\n { kind: 'scalar', key: 'min', prefix: 'mn' },\n { kind: 'scalar', key: 'max', prefix: 'mx' },\n { kind: 'bool', key: 'unique', prefix: 'u' },\n]\n\nconst numericFields: ReadonlyArray<ShapeField> = [\n { kind: 'scalar', key: 'min', prefix: 'mn' },\n { kind: 'scalar', key: 'max', prefix: 'mx' },\n { kind: 'scalar', key: 'exclusiveMinimum', prefix: 'emn' },\n { kind: 'scalar', key: 'exclusiveMaximum', prefix: 'emx' },\n { kind: 'scalar', key: 'multipleOf', prefix: 'mo' },\n]\n\nconst rangeFields: ReadonlyArray<ShapeField> = [\n { kind: 'scalar', key: 'min', prefix: 'mn' },\n { kind: 'scalar', key: 'max', prefix: 'mx' },\n]\n\n/**\n * Maps each node `type` to its ordered shape-contributing fields. Types absent from the map\n * (boolean, null, any, and other scalars) fall back to `${type}|${flags}`.\n */\nconst SHAPE_KEYS: Partial<Record<SchemaNode['type'], ReadonlyArray<ShapeField>>> = {\n object: [\n { kind: 'objectProps' },\n { kind: 'additionalProps' },\n { kind: 'patternProps' },\n { kind: 'scalar', key: 'minProperties', prefix: 'mn' },\n { kind: 'scalar', key: 'maxProperties', prefix: 'mx' },\n ],\n array: arrayTupleFields,\n tuple: arrayTupleFields,\n union: [\n { kind: 'scalar', key: 'strategy', prefix: 's' },\n { kind: 'scalar', key: 'discriminatorPropertyName', prefix: 'd' },\n { kind: 'children', key: 'members', prefix: 'm' },\n ],\n intersection: [{ kind: 'children', key: 'members', prefix: 'm' }],\n enum: [{ kind: 'enumValues' }],\n ref: [{ kind: 'refTarget' }],\n string: [\n { kind: 'scalar', key: 'min', prefix: 'mn' },\n { kind: 'scalar', key: 'max', prefix: 'mx' },\n { kind: 'scalar', key: 'pattern', prefix: 'pt' },\n ],\n number: numericFields,\n integer: numericFields,\n bigint: numericFields,\n url: [\n { kind: 'scalar', key: 'path', prefix: 'path' },\n { kind: 'scalar', key: 'min', prefix: 'mn' },\n { kind: 'scalar', key: 'max', prefix: 'mx' },\n ],\n uuid: rangeFields,\n email: rangeFields,\n datetime: [\n { kind: 'bool', key: 'offset', prefix: 'o' },\n { kind: 'bool', key: 'local', prefix: 'l' },\n ],\n date: [{ kind: 'scalar', key: 'representation', prefix: 'rep' }],\n time: [{ kind: 'scalar', key: 'representation', prefix: 'rep' }],\n}\n\nfunction serializeShapeField(field: ShapeField, node: SchemaNode, record: Record<string, unknown>): string {\n switch (field.kind) {\n case 'scalar':\n return `${field.prefix}:${record[field.key] ?? ''}`\n case 'bool':\n return `${field.prefix}:${record[field.key] ? 1 : 0}`\n case 'child': {\n const child = record[field.key] as SchemaNode | undefined\n return `${field.prefix}:${child ? signatureOf(child) : ''}`\n }\n case 'children': {\n const children = (record[field.key] as Array<SchemaNode> | undefined) ?? []\n return `${field.prefix}[${children.map((c) => signatureOf(c)).join(',')}]`\n }\n case 'objectProps': {\n const obj = node as Extract<SchemaNode, { type: 'object' }>\n const props = (obj.properties ?? []).map((prop) => `${prop.name}${prop.required ? '!' : '?'}${signatureOf(prop.schema)}`).join(',')\n return `p[${props}]`\n }\n case 'additionalProps': {\n const obj = node as Extract<SchemaNode, { type: 'object' }>\n if (typeof obj.additionalProperties === 'boolean') return `ab:${obj.additionalProperties}`\n if (obj.additionalProperties) return `as:${signatureOf(obj.additionalProperties)}`\n return ''\n }\n case 'patternProps': {\n const obj = node as Extract<SchemaNode, { type: 'object' }>\n const pattern = obj.patternProperties\n ? Object.keys(obj.patternProperties)\n .sort()\n .map((key) => `${key}=${signatureOf(obj.patternProperties![key]!)}`)\n .join(',')\n : ''\n return `pp[${pattern}]`\n }\n case 'enumValues': {\n const en = node as Extract<SchemaNode, { type: 'enum' }>\n let values = ''\n if (en.namedEnumValues?.length) {\n values = en.namedEnumValues.map((entry) => `${entry.name}=${entry.primitive}:${String(entry.value)}`).join(',')\n } else if (en.enumValues?.length) {\n values = en.enumValues.map((value) => `${value === null ? 'null' : typeof value}:${String(value)}`).join(',')\n }\n return `v[${values}]`\n }\n case 'refTarget': {\n return `->${refTargetName(node as Extract<SchemaNode, { type: 'ref' }>)}`\n }\n }\n}\n\n/**\n * Builds the local shape descriptor that {@link signatureOf} hashes: the node's kind, flags,\n * constraints, and its children's signatures.\n */\nfunction describeShape(node: SchemaNode): string {\n const flags = flagsDescriptor(node)\n const fields = SHAPE_KEYS[node.type]\n if (!fields) return `${node.type}|${flags}`\n\n const record = node as unknown as Record<string, unknown>\n const parts: Array<string> = [`${node.type}|${flags}`]\n for (const field of fields) {\n parts.push(serializeShapeField(field, node, record))\n }\n return parts.join('|')\n}\n\n/**\n * Caches the digest per node, keyed by identity. A `WeakMap` so entries die with the node, and so\n * a tree hashed during dedupe planning is not walked again when it is rewritten during streaming.\n * Reuse is safe because a signature depends only on content, and nodes are immutable once created.\n */\nconst signatureCache = new WeakMap<SchemaNode, string>()\n\n/**\n * Computes a deterministic, shape-only signature (a content hash) for a schema node. Two schemas\n * share a signature when they are structurally identical, ignoring documentation (`name`, `title`,\n * `description`, `examples`, `default`, `deprecated`) and usage-slot flags (`optional`, `nullish`,\n * `readOnly`, `writeOnly`). `nullable` is kept because it changes the produced type, and `ref`\n * nodes compare by target name, which also terminates on circular shapes.\n *\n * @example Two enums with different descriptions share a signature\n * ```ts\n * signatureOf(createSchema({ type: 'enum', primitive: 'string', enumValues: ['a', 'b'], description: 'x' })) ===\n * signatureOf(createSchema({ type: 'enum', primitive: 'string', enumValues: ['a', 'b'] }))\n * ```\n */\nexport function signatureOf(node: SchemaNode): string {\n const cached = signatureCache.get(node)\n if (cached !== undefined) return cached\n const signature = hash('sha256', describeShape(node), 'hex')\n signatureCache.set(node, signature)\n\n return signature\n}\n\n/**\n * Returns `true` when two schema nodes are structurally identical under shape-only equality,\n * meaning they produce the same TypeScript type.\n */\nexport function isSchemaEqual(a: SchemaNode, b: SchemaNode): boolean {\n return signatureOf(a) === signatureOf(b)\n}\n","export { schemaTypes } from './constants.ts'\nexport { defineDialect } from './defineDialect.ts'\nexport { isHttpOperationNode, narrowSchema } from './guards.ts'\nexport { applyMacros, composeMacros, defineMacro } from './defineMacro.ts'\nexport { defineNode } from './defineNode.ts'\nexport { optionality } from './optionality.ts'\nexport { createPrinterFactory, definePrinter } from './definePrinter.ts'\nexport { signatureOf } from './signature.ts'\nexport { collect, transform, walk } from './visitor.ts'\n\nexport * as factory from './factory.ts'\nexport * from './registry.ts'\nexport type * from './types.ts'\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;AAiFA,SAAgB,cACd,SACkE;CAClE,OAAO;AACT;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ACuGA,SAAgB,cAAuE,OAAkE;CACvJ,OAAO,sBAAgE,SAAS,KAAK,IAAI,CAAC,CAAC,KAAK;AAClG;;;;;;;;;;;;;AAcA,SAAgB,qBAAkG,QAAsC;CACtJ,OAAO,SACL,OAyBA;EACA,QAAQ,YAAY;GAClB,MAAM,EAAE,MAAM,SAAS,iBAAiB,OAAO,OAAO,kBAAkB,MAAM,WAAY,CAAC,CAAkB;GAE7G,MAAM,UAAU;IACd,SAAS;IACT,YAAY,SAAoC;KAC9C,MAAM,MAAM,OAAO,IAAI;KACvB,IAAI,QAAQ,MAAM,OAAO;KAEzB,MAAM,UAAU,MAAM;KAEtB,IAAI,CAAC,SAAS,OAAO;KAErB,OAAQ,QAAsE,KAAK,SAAS,IAAI;IAClG;GACF;GAEA,OAAO;IACL;IACA,SAAS;IACT,WAAW,QAAQ;IACnB,OAAQ,gBAAgB,cAAc,KAAK,OAAO,IAAI,QAAQ;GAChE;EACF;CACF;AACF;;;;;;AC1PA,SAAS,gBAAgB,MAA0B;CACjD,OAAO,GAAG,KAAK,aAAa,GAAG,GAAG,KAAK,UAAU,GAAG,GAAG,KAAK,WAAW,IAA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CACf,MAAM,QAAuB,CAAC,GAAG,KAAK,KAAK,GAAG,OAAO;CACrD,KAAK,MAAM,SAAS,QAClB,MAAM,KAAK,oBAAoB,OAAO,MAAM,MAAM,CAAC;CAErD,OAAO,MAAM,KAAK,GAAG;AACvB;;;;;;AAOA,MAAM,iCAAiB,IAAI,QAA4B;;;;;;;;;;;;;;AAevD,SAAgB,YAAY,MAA0B;CACpD,MAAM,SAAS,eAAe,IAAI,IAAI;CACtC,IAAI,WAAW,KAAA,GAAW,OAAO;CACjC,MAAM,aAAA,GAAA,YAAA,KAAA,CAAiB,UAAU,cAAc,IAAI,GAAG,KAAK;CAC3D,eAAe,IAAI,MAAM,SAAS;CAElC,OAAO;AACT"}
import { n as __name, t as __exportAll } from "./rolldown-runtime-CNktS9qV.js";
import { $ as exportDef, $t as textDef, A as IndexedAccessTypeNode, At as InferSchemaNode, B as functionParametersDef, Bt as TypeNode, C as ParameterNode, Ct as UrlSchemaNode, D as FunctionParamNode, Dt as UserPropertyNode, E as FunctionParamKind, Et as PropertyNode, Ft as ConstNode, G as FileNode, H as objectBindingPatternDef, Ht as breakDef, It as FunctionNode, J as UserFileNode, K as ImportNode, Lt as JSDocNode, M as TypeExpression, Mt as ArrowFunctionNode, N as TypeLiteralNode, Nt as BreakNode, O as FunctionParameterNode, Pt as CodeNode, Qt as jsxDef, Rt as JsxNode, S as ParameterLocation, St as UnionSchemaNode, T as parameterDef, Tt as schemaDef, U as typeLiteralDef, Ut as constDef, V as indexedAccessTypeDef, Vt as arrowFunctionDef, W as ExportNode, Zt as functionDef, _t as SchemaNode, a as InputMeta, an as NodeKind, bt as StringSchemaNode, c as inputDef, ct as DatetimeSchemaNode, d as HttpOperationNode, dt as NumberSchemaNode, en as typeDef, et as fileDef, f as OperationNode, ft as ObjectSchemaNode, g as StatusCode, gt as ScalarSchemaType, h as ResponseNode, ht as ScalarSchemaNode, i as outputDef, in as BaseNode, it as contentDef, j as ObjectBindingPatternNode, jt as ParserOptions, k as FunctionParametersNode, kt as propertyDef, l as GenericOperationNode, lt as EnumSchemaNode, m as operationDef, mt as RefSchemaNode, n as OutputNode, nn as NodeDef, nt as sourceDef, o as InputNode, ot as ArraySchemaNode, pt as PrimitiveSchemaType, q as SourceNode, rn as defineNode, rt as ContentNode, st as DateSchemaNode, t as Node, tn as DistributiveOmit, tt as importDef, u as HttpMethod, ut as IntersectionSchemaNode, v as responseDef, vt as SchemaNodeByType, x as requestBodyDef, xt as TimeSchemaNode, y as RequestBodyNode, yt as SchemaType, z as functionParameterDef, zt as TextNode } from "./index-BKD4drsX.js";
import { t as factory_d_exports } from "./factory-wJLzHeXT.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-B7qm3zTd.js";
import { a as definePrinter, c as SchemaDialect, i as createPrinterFactory, l as defineDialect, n as PrinterFactoryOptions, o as Dedupe, r as PrinterPartial, s as DefineDialect, t as Printer } from "./types-BP9BZoq-.js";
import { n as OperationParamsResolver } from "./operationParams-ByVfpYr7.js";
import { $ as exportDef, $t as textDef, A as IndexedAccessTypeNode, At as InferSchemaNode, B as functionParametersDef, Bt as TypeNode, C as ParameterNode, Ct as UrlSchemaNode, D as FunctionParamNode, Dt as UserPropertyNode, E as FunctionParamKind, Et as PropertyNode, Ft as ConstNode, G as FileNode, H as objectBindingPatternDef, Ht as breakDef, It as FunctionNode, J as UserFileNode, K as ImportNode, Lt as JSDocNode, M as TypeExpression, Mt as ArrowFunctionNode, N as TypeLiteralNode, Nt as BreakNode, O as FunctionParameterNode, Pt as CodeNode, Qt as jsxDef, Rt as JsxNode, S as ParameterLocation, St as UnionSchemaNode, T as parameterDef, Tt as schemaDef, U as typeLiteralDef, Ut as constDef, V as indexedAccessTypeDef, Vt as arrowFunctionDef, W as ExportNode, Zt as functionDef, _t as SchemaNode, a as InputMeta, an as NodeKind, bt as StringSchemaNode, c as inputDef, ct as DatetimeSchemaNode, d as HttpOperationNode, dt as NumberSchemaNode, en as typeDef, et as fileDef, f as OperationNode, ft as ObjectSchemaNode, g as StatusCode, gt as ScalarSchemaType, h as ResponseNode, ht as ScalarSchemaNode, i as outputDef, in as BaseNode, it as contentDef, j as ObjectBindingPatternNode, jt as ParserOptions, k as FunctionParametersNode, kt as propertyDef, l as GenericOperationNode, lt as EnumSchemaNode, m as operationDef, mt as RefSchemaNode, n as OutputNode, nn as NodeDef, nt as sourceDef, o as InputNode, ot as ArraySchemaNode, pt as PrimitiveSchemaType, q as SourceNode, rn as defineNode, rt as ContentNode, st as DateSchemaNode, t as Node, tn as DistributiveOmit, tt as importDef, u as HttpMethod, ut as IntersectionSchemaNode, v as responseDef, vt as SchemaNodeByType, x as requestBodyDef, xt as TimeSchemaNode, y as RequestBodyNode, yt as SchemaType, z as functionParameterDef, zt as TextNode } from "./index-CeJAFegf.js";
import { t as factory_d_exports } from "./factory-B_qPwA1b.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-BQpu6Ags.js";
import { a as definePrinter, c as SchemaDialect, i as createPrinterFactory, l as defineDialect, n as PrinterFactoryOptions, o as Dedupe, r as PrinterPartial, s as DefineDialect, t as Printer } from "./types-B6thixAv.js";
import { n as OperationParamsResolver } from "./operationParams-DCY3q4C7.js";

@@ -42,3 +42,3 @@ //#region src/guards.d.ts

* share a signature when they are structurally identical, ignoring documentation (`name`, `title`,
* `description`, `example`, `default`, `deprecated`) and usage-slot flags (`optional`, `nullish`,
* `description`, `examples`, `default`, `deprecated`) and usage-slot flags (`optional`, `nullish`,
* `readOnly`, `writeOnly`). `nullable` is kept because it changes the produced type, and `ref`

@@ -60,3 +60,28 @@ * nodes compare by target name, which also terminates on circular shapes.

*/
declare const nodeDefs: (NodeDef<PropertyNode, UserPropertyNode> | NodeDef<SchemaNode, (Omit<ObjectSchemaNode, "kind" | "primitive" | "properties"> & {
declare const nodeDefs: (NodeDef<PropertyNode, UserPropertyNode> | NodeDef<ContentNode, Omit<ContentNode, "kind">> | 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">> | NodeDef<TypeLiteralNode, Pick<TypeLiteralNode, "members">> | NodeDef<IndexedAccessTypeNode, Omit<IndexedAccessTypeNode, "kind">> | NodeDef<ObjectBindingPatternNode, Pick<ObjectBindingPatternNode, "elements">> | NodeDef<FunctionParameterNode, {
name: string;
type?: TypeExpression;
optional?: boolean;
default?: string;
rest?: boolean;
} | {
properties: Array<{
name: string;
type: TypeExpression;
optional?: boolean;
}>;
optional?: boolean;
default?: string;
}> | NodeDef<FunctionParametersNode, Partial<Omit<FunctionParametersNode, "kind">>> | NodeDef<InputNode<false>, Partial<Omit<InputNode<false>, "kind">>> | NodeDef<ParameterNode, Pick<ParameterNode, "name" | "schema" | "in"> & Partial<Omit<ParameterNode, "name" | "kind" | "schema" | "in">>> | NodeDef<RequestBodyNode, Omit<RequestBodyNode, "kind">> | NodeDef<OperationNode, {
[key: string]: unknown;
operationId: string;
method?: HttpOperationNode["method"];
path?: HttpOperationNode["path"];
requestBody?: Omit<RequestBodyNode, "kind">;
}> | NodeDef<OutputNode, Partial<Omit<OutputNode, "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, "properties" | "kind" | "primitive"> & {
properties?: Array<PropertyNode>;

@@ -76,3 +101,3 @@ primitive?: "object";

default?: unknown;
example?: unknown;
examples?: Array<unknown>;
primitive?: PrimitiveSchemaType;

@@ -96,3 +121,3 @@ format?: string;

default?: unknown;
example?: unknown;
examples?: Array<unknown>;
primitive?: PrimitiveSchemaType;

@@ -114,3 +139,3 @@ format?: string;

default?: unknown;
example?: unknown;
examples?: Array<unknown>;
primitive?: PrimitiveSchemaType;

@@ -120,28 +145,3 @@ format?: string;

type: "ipv6";
}) | ScalarSchemaNode, "kind">> | NodeDef<RequestBodyNode, Omit<RequestBodyNode, "kind">> | NodeDef<OutputNode, Partial<Omit<OutputNode, "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, "kind" | "name" | "schema" | "in">>> | NodeDef<ImportNode, Omit<ImportNode, "kind">> | NodeDef<ExportNode, Omit<ExportNode, "kind">> | NodeDef<SourceNode, Omit<SourceNode, "kind">> | NodeDef<FileNode<object>, Omit<FileNode<object>, "kind">> | 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<OperationNode, {
[key: string]: unknown;
operationId: string;
method?: HttpOperationNode["method"];
path?: HttpOperationNode["path"];
requestBody?: Omit<RequestBodyNode, "kind">;
}> | NodeDef<TypeLiteralNode, Pick<TypeLiteralNode, "members">> | NodeDef<IndexedAccessTypeNode, Omit<IndexedAccessTypeNode, "kind">> | NodeDef<ObjectBindingPatternNode, Pick<ObjectBindingPatternNode, "elements">> | NodeDef<FunctionParameterNode, {
name: string;
type?: TypeExpression;
optional?: boolean;
default?: string;
rest?: boolean;
} | {
properties: Array<{
name: string;
type: TypeExpression;
optional?: boolean;
}>;
optional?: boolean;
default?: string;
}> | NodeDef<FunctionParametersNode, Partial<Omit<FunctionParametersNode, "kind">>> | NodeDef<InputNode<false>, Partial<Omit<InputNode<false>, "kind">>>)[];
}) | ScalarSchemaNode, "kind">>)[];
declare namespace exports_d_exports {

@@ -148,0 +148,0 @@ export { ArraySchemaNode, ArrowFunctionNode, BreakNode, CodeNode, ConstNode, ContentNode, DateSchemaNode, DatetimeSchemaNode, Dedupe, DefineDialect, DistributiveOmit, Enforce, EnumSchemaNode, ExportNode, FileNode, FunctionNode, FunctionParamKind, FunctionParamNode, FunctionParameterNode, FunctionParametersNode, GenericOperationNode, HttpMethod, HttpOperationNode, ImportNode, IndexedAccessTypeNode, InferSchemaNode, InputMeta, InputNode, IntersectionSchemaNode, JSDocNode, JsxNode, Macro, Node, NodeDef, NodeKind, NumberSchemaNode, ObjectBindingPatternNode, ObjectSchemaNode, OperationNode, OperationParamsResolver, OutputNode, ParameterLocation, ParameterNode, ParentOf, ParserOptions, PrimitiveSchemaType, Printer, PrinterFactoryOptions, PrinterPartial, PropertyNode, RefSchemaNode, RequestBodyNode, ResponseNode, ScalarSchemaNode, ScalarSchemaType, SchemaDialect, SchemaNode, SchemaNodeByType, SchemaType, SourceNode, StatusCode, StringSchemaNode, TextNode, TimeSchemaNode, TypeExpression, TypeLiteralNode, TypeNode, UnionSchemaNode, UrlSchemaNode, UserFileNode, Visitor, VisitorContext, applyMacros, arrowFunctionDef, breakDef, collect, composeMacros, constDef, contentDef, createPrinterFactory, defineDialect, defineMacro, defineNode, definePrinter, exportDef, factory_d_exports as factory, fileDef, functionDef, functionParameterDef, functionParametersDef, importDef, indexedAccessTypeDef, inputDef, isHttpOperationNode, jsxDef, narrowSchema, nodeDefs, objectBindingPatternDef, operationDef, optionality, outputDef, parameterDef, propertyDef, requestBodyDef, responseDef, schemaDef, schemaTypes, signatureOf, sourceDef, textDef, transform, typeDef, typeLiteralDef, walk };

@@ -345,3 +345,3 @@ import { t as __exportAll } from "./rolldown-runtime-CNktS9qV.js";

* share a signature when they are structurally identical, ignoring documentation (`name`, `title`,
* `description`, `example`, `default`, `deprecated`) and usage-slot flags (`optional`, `nullish`,
* `description`, `examples`, `default`, `deprecated`) and usage-slot flags (`optional`, `nullish`,
* `readOnly`, `writeOnly`). `nullable` is kept because it changes the produced type, and `ref`

@@ -348,0 +348,0 @@ * nodes compare by target name, which also terminates on circular shapes.

@@ -1,1 +0,1 @@

{"version":3,"file":"index.js","names":["obj"],"sources":["../src/defineDialect.ts","../src/definePrinter.ts","../src/signature.ts","../src/exports.ts"],"sourcesContent":["import type { Node } from './nodes/index.ts'\n\n/**\n * The spec-specific questions a schema parser answers while turning a source document into Kubb\n * AST nodes. The rest of the pipeline is generic JSON Schema, so this is the one seam where\n * OpenAPI, AsyncAPI, and plain JSON Schema differ.\n */\nexport type SchemaDialect<TSchema = unknown, TRef = TSchema, TDiscriminated = TSchema, TDocument = unknown> = {\n /**\n * Whether the schema is nullable.\n */\n isNullable(schema?: TSchema): boolean\n /**\n * Whether the value is a `$ref` pointer.\n */\n isReference(value?: unknown): value is TRef\n /**\n * Whether the schema carries a discriminator for polymorphism.\n */\n isDiscriminator(value?: unknown): value is TDiscriminated\n /**\n * Whether the schema is binary data, converted to a `blob` node.\n */\n isBinary(schema: TSchema): boolean\n /**\n * Resolves a local `$ref` against the document, or nullish when it cannot.\n */\n resolveRef<TResolved>(document: TDocument, ref: string): TResolved | null | undefined\n}\n\n/**\n * How a dialect collapses structurally identical schemas into shared definitions. The contract is\n * generic over the plan and context types, which the adapter supplies. The mechanics live in the\n * adapter, not here, so `@kubb/ast` carries no dedupe logic. The returned plan owns the rewriting\n * behavior, so callers interact with one object.\n */\nexport type Dedupe<TPlan = unknown, TContext = unknown> = {\n /**\n * Scans a forest of nodes and produces a plan describing which shapes to share.\n */\n plan(roots: ReadonlyArray<Node>, context: TContext): TPlan\n}\n\n/**\n * A spec adapter's dialect. `name` identifies it in logs and diagnostics, `schema` holds the\n * spec-specific schema questions the parser answers, and `dedupe` is the schema-sharing seam.\n */\nexport type DefineDialect<TSchema = unknown, TRef = TSchema, TDiscriminated = TSchema, TDocument = unknown, TDedupe extends Dedupe = Dedupe> = {\n /**\n * Identifies the dialect in logs and diagnostics.\n */\n name: string\n /**\n * The spec-specific schema behavior. See {@link SchemaDialect}.\n */\n schema: SchemaDialect<TSchema, TRef, TDiscriminated, TDocument>\n /**\n * The schema-sharing behavior. See {@link Dedupe}.\n */\n dedupe: TDedupe\n}\n\n/**\n * Types a {@link DefineDialect} for an adapter. Adds no runtime behavior and only pins the\n * dialect's type for inference.\n *\n * @example\n * ```ts\n * export const oasDialect = defineDialect({\n * name: 'oas',\n * schema: {\n * isNullable,\n * isReference,\n * isDiscriminator,\n * isBinary: (schema) => schema.type === 'string' && schema.contentMediaType === 'application/octet-stream',\n * resolveRef,\n * },\n * dedupe: { plan },\n * })\n * ```\n */\nexport function defineDialect<TSchema, TRef, TDiscriminated, TDocument, TDedupe extends Dedupe>(\n dialect: DefineDialect<TSchema, TRef, TDiscriminated, TDocument, TDedupe>,\n): DefineDialect<TSchema, TRef, TDiscriminated, TDocument, TDedupe> {\n return dialect\n}\n","import type { SchemaNode, SchemaNodeByType, SchemaType } from './nodes/index.ts'\n\n/**\n * Runtime context passed as `this` to printer handlers.\n *\n * `this.transform` dispatches to node-level handlers from `nodes`.\n *\n * @example\n * ```ts\n * const context: PrinterHandlerContext<string, {}> = {\n * options: {},\n * transform: () => 'value',\n * }\n * ```\n */\ntype PrinterHandlerContext<TOutput, TOptions extends object> = {\n /**\n * Recursively transform a nested `SchemaNode` to `TOutput` using the node-level handlers.\n * Use `this.transform` inside `nodes` handlers and inside the `print` override.\n */\n transform: (node: SchemaNode) => TOutput | null\n /**\n * Options for this printer instance.\n */\n options: TOptions\n}\n\n/**\n * Handler for one schema node type.\n *\n * Use a regular function (not an arrow function) if you need `this`.\n *\n * @example\n * ```ts\n * const handler: PrinterHandler<string, {}, 'string'> = function () {\n * return 'string'\n * }\n * ```\n */\ntype PrinterHandler<TOutput, TOptions extends object, T extends SchemaType = SchemaType> = (\n this: PrinterHandlerContext<TOutput, TOptions>,\n node: SchemaNodeByType[T],\n) => TOutput | null\n\n/**\n * Partial map of per-node-type handler overrides for a printer.\n *\n * Each key is a `SchemaType` string (e.g. `'date'`, `'string'`).\n * Supply only the handlers you want to replace. The printer's built-in\n * defaults fill in the rest.\n *\n * @example\n * ```ts\n * pluginZod({\n * printer: {\n * nodes: {\n * date(): string {\n * return 'z.string().date()'\n * },\n * } satisfies PrinterPartial<string, PrinterZodOptions>,\n * },\n * })\n * ```\n */\nexport type PrinterPartial<TOutput, TOptions extends object> = Partial<{\n [K in SchemaType]: PrinterHandler<TOutput, TOptions, K>\n}>\n\n/**\n * Generic shape used by `definePrinter`.\n *\n * - `TName` unique string identifier (e.g. `'zod'`, `'ts'`)\n * - `TOptions` options passed to and stored on the printer instance\n * - `TOutput` the type emitted by node handlers\n * - `TPrintOutput` type returned by public `print` (defaults to `TOutput`)\n *\n * @example\n * ```ts\n * type MyPrinter = PrinterFactoryOptions<'my', { strict: boolean }, string>\n * ```\n */\nexport type PrinterFactoryOptions<TName extends string = string, TOptions extends object = object, TOutput = unknown, TPrintOutput = TOutput> = {\n name: TName\n options: TOptions\n output: TOutput\n printOutput: TPrintOutput\n}\n\n/**\n * Printer instance returned by a printer factory.\n *\n * @example\n * ```ts\n * const printer = definePrinter((options: {}) => ({ name: 'x', options, nodes: {} }))({})\n * ```\n */\nexport type Printer<T extends PrinterFactoryOptions = PrinterFactoryOptions> = {\n /**\n * Unique identifier supplied at creation time.\n */\n name: T['name']\n /**\n * Options for this printer instance.\n */\n options: T['options']\n /**\n * Node-level dispatcher, converts a `SchemaNode` directly to `TOutput` using the `nodes` handlers.\n * Always dispatches through the `nodes` map. Never calls the `print` override.\n * Reach for it when you need the raw output (e.g. `ts.TypeNode`) without declaration wrapping.\n */\n transform: (node: SchemaNode) => T['output'] | null\n /**\n * Public printer. If the builder provides a root-level `print`, this calls that\n * higher-level function (which may produce full declarations).\n * Otherwise, falls back to the node-level dispatcher.\n */\n print: (node: SchemaNode) => T['printOutput'] | null\n}\n\n/**\n * Builder function passed to `definePrinter`.\n *\n * It receives resolved options and returns:\n * - `name`\n * - `options`\n * - `nodes` handlers\n * - optional top-level `print` override\n *\n * @example\n * ```ts\n * const build = (options: {}) => ({ name: 'x' as const, options, nodes: {} })\n * ```\n */\ntype PrinterBuilder<T extends PrinterFactoryOptions> = (options: T['options']) => {\n name: T['name']\n /**\n * Options to store on the printer.\n */\n options: T['options']\n nodes: Partial<{\n [K in SchemaType]: PrinterHandler<T['output'], T['options'], K>\n }>\n /**\n * Optional root-level print override. When provided, becomes the public `printer.print`.\n * Use `this.transform(node)` inside this function to dispatch to the node-level handlers (`nodes`),\n * not the override itself, so recursion is safe.\n */\n print?: (this: PrinterHandlerContext<T['output'], T['options']>, node: SchemaNode) => T['printOutput'] | null\n}\n/**\n * Defines a schema printer: a function that takes a `SchemaNode` and emits\n * code in your target language. Each plugin that produces code from schemas\n * (TypeScript types, Zod schemas, Faker factories) ships a printer built\n * with this helper.\n *\n * The builder receives resolved options and returns:\n *\n * - `name` unique identifier for the printer.\n * - `options` stored on the returned printer instance.\n * - `nodes` map of `SchemaType` → handler. Handlers return the rendered\n * output (a string, a TypeScript AST node, ...) for that schema type.\n * - `print` (optional), top-level override exposed as `printer.print`.\n * Use `this.transform(node)` inside it to dispatch to `nodes` recursively.\n *\n * Without a `print` override, `printer.print` falls back to `printer.transform`\n * (the node-level dispatcher).\n *\n * @example Tiny Zod printer\n * ```ts\n * import { definePrinter, type PrinterFactoryOptions } from '@kubb/ast'\n *\n * type PrinterZod = PrinterFactoryOptions<'zod', { strict?: boolean }, string>\n *\n * export const zodPrinter = definePrinter<PrinterZod>((options) => ({\n * name: 'zod',\n * options: { strict: options.strict ?? true },\n * nodes: {\n * string: () => 'z.string()',\n * object(node) {\n * const props = node.properties\n * .map((p) => `${p.name}: ${this.transform(p.schema)}`)\n * .join(', ')\n * return `z.object({ ${props} })`\n * },\n * },\n * }))\n * ```\n */\nexport function definePrinter<T extends PrinterFactoryOptions = PrinterFactoryOptions>(build: PrinterBuilder<T>): (options?: T['options']) => Printer<T> {\n return createPrinterFactory<SchemaNode, SchemaType, SchemaNodeByType>((node) => node.type)(build) as (options?: T['options']) => Printer<T>\n}\n\n/**\n * Generic printer factory behind `definePrinter`. Pass a `getKey` function that maps a node to its\n * handler key, and it returns a `definePrinter`-style helper for that node and key type. `definePrinter`\n * itself is this factory keyed by `node.type`.\n *\n * @example Key a printer by `node.kind` instead of `node.type`\n * ```ts\n * const defineFunctionPrinter = createPrinterFactory<FunctionParamNode, FunctionParamKind, Partial<Record<FunctionParamKind, FunctionParamNode>>>(\n * (node) => node.kind,\n * )\n * ```\n */\nexport function createPrinterFactory<TNode, TKey extends string, TNodeByKey extends Partial<Record<TKey, TNode>>>(getKey: (node: TNode) => TKey | null) {\n return function <T extends PrinterFactoryOptions>(\n build: (options: T['options']) => {\n name: T['name']\n options: T['options']\n nodes: Partial<{\n [K in TKey]: (\n this: {\n transform: (node: TNode) => T['output'] | null\n options: T['options']\n },\n node: TNodeByKey[K],\n ) => T['output'] | null\n }>\n print?: (\n this: {\n transform: (node: TNode) => T['output'] | null\n options: T['options']\n },\n node: TNode,\n ) => T['printOutput'] | null\n },\n ): (options?: T['options']) => {\n name: T['name']\n options: T['options']\n transform: (node: TNode) => T['output'] | null\n print: (node: TNode) => T['printOutput'] | null\n } {\n return (options) => {\n const { name, options: resolvedOptions, nodes, print: printOverride } = build(options ?? ({} as T['options']))\n\n const context = {\n options: resolvedOptions,\n transform: (node: TNode): T['output'] | null => {\n const key = getKey(node)\n if (key === null) return null\n\n const handler = nodes[key]\n\n if (!handler) return null\n\n return (handler as (this: typeof context, node: TNode) => T['output'] | null).call(context, node)\n },\n }\n\n return {\n name,\n options: resolvedOptions,\n transform: context.transform,\n print: (printOverride ? printOverride.bind(context) : context.transform) as (node: TNode) => T['printOutput'] | null,\n }\n }\n }\n}\n","import { hash } from 'node:crypto'\nimport type { SchemaNode } from './nodes/index.ts'\nimport { extractRefName } from './utils/index.ts'\n\n/**\n * The flags shared by every node kind that affect its type: `primitive`, `format`, `nullable`.\n */\nfunction flagsDescriptor(node: SchemaNode): string {\n return `${node.primitive ?? ''};${node.format ?? ''};${node.nullable ? 1 : 0}`\n}\n\nfunction refTargetName(node: Extract<SchemaNode, { type: 'ref' }>): string {\n if (node.ref) return extractRefName(node.ref)\n return node.name ?? ''\n}\n\ntype ScalarField = { kind: 'scalar'; key: string; prefix: string }\ntype BoolField = { kind: 'bool'; key: string; prefix: string }\ntype ChildField = { kind: 'child'; key: string; prefix: string }\ntype ChildrenField = { kind: 'children'; key: string; prefix: string }\ntype ObjectPropsField = { kind: 'objectProps' }\ntype AdditionalPropsField = { kind: 'additionalProps' }\ntype PatternPropsField = { kind: 'patternProps' }\ntype EnumValuesField = { kind: 'enumValues' }\ntype RefTargetField = { kind: 'refTarget' }\n\ntype ShapeField =\n | ScalarField\n | BoolField\n | ChildField\n | ChildrenField\n | ObjectPropsField\n | AdditionalPropsField\n | PatternPropsField\n | EnumValuesField\n | RefTargetField\n\nconst arrayTupleFields: ReadonlyArray<ShapeField> = [\n { kind: 'children', key: 'items', prefix: 'i' },\n { kind: 'child', key: 'rest', prefix: 'r' },\n { kind: 'scalar', key: 'min', prefix: 'mn' },\n { kind: 'scalar', key: 'max', prefix: 'mx' },\n { kind: 'bool', key: 'unique', prefix: 'u' },\n]\n\nconst numericFields: ReadonlyArray<ShapeField> = [\n { kind: 'scalar', key: 'min', prefix: 'mn' },\n { kind: 'scalar', key: 'max', prefix: 'mx' },\n { kind: 'scalar', key: 'exclusiveMinimum', prefix: 'emn' },\n { kind: 'scalar', key: 'exclusiveMaximum', prefix: 'emx' },\n { kind: 'scalar', key: 'multipleOf', prefix: 'mo' },\n]\n\nconst rangeFields: ReadonlyArray<ShapeField> = [\n { kind: 'scalar', key: 'min', prefix: 'mn' },\n { kind: 'scalar', key: 'max', prefix: 'mx' },\n]\n\n/**\n * Maps each node `type` to its ordered shape-contributing fields. Types absent from the map\n * (boolean, null, any, and other scalars) fall back to `${type}|${flags}`.\n */\nconst SHAPE_KEYS: Partial<Record<SchemaNode['type'], ReadonlyArray<ShapeField>>> = {\n object: [\n { kind: 'objectProps' },\n { kind: 'additionalProps' },\n { kind: 'patternProps' },\n { kind: 'scalar', key: 'minProperties', prefix: 'mn' },\n { kind: 'scalar', key: 'maxProperties', prefix: 'mx' },\n ],\n array: arrayTupleFields,\n tuple: arrayTupleFields,\n union: [\n { kind: 'scalar', key: 'strategy', prefix: 's' },\n { kind: 'scalar', key: 'discriminatorPropertyName', prefix: 'd' },\n { kind: 'children', key: 'members', prefix: 'm' },\n ],\n intersection: [{ kind: 'children', key: 'members', prefix: 'm' }],\n enum: [{ kind: 'enumValues' }],\n ref: [{ kind: 'refTarget' }],\n string: [\n { kind: 'scalar', key: 'min', prefix: 'mn' },\n { kind: 'scalar', key: 'max', prefix: 'mx' },\n { kind: 'scalar', key: 'pattern', prefix: 'pt' },\n ],\n number: numericFields,\n integer: numericFields,\n bigint: numericFields,\n url: [\n { kind: 'scalar', key: 'path', prefix: 'path' },\n { kind: 'scalar', key: 'min', prefix: 'mn' },\n { kind: 'scalar', key: 'max', prefix: 'mx' },\n ],\n uuid: rangeFields,\n email: rangeFields,\n datetime: [\n { kind: 'bool', key: 'offset', prefix: 'o' },\n { kind: 'bool', key: 'local', prefix: 'l' },\n ],\n date: [{ kind: 'scalar', key: 'representation', prefix: 'rep' }],\n time: [{ kind: 'scalar', key: 'representation', prefix: 'rep' }],\n}\n\nfunction serializeShapeField(field: ShapeField, node: SchemaNode, record: Record<string, unknown>): string {\n switch (field.kind) {\n case 'scalar':\n return `${field.prefix}:${record[field.key] ?? ''}`\n case 'bool':\n return `${field.prefix}:${record[field.key] ? 1 : 0}`\n case 'child': {\n const child = record[field.key] as SchemaNode | undefined\n return `${field.prefix}:${child ? signatureOf(child) : ''}`\n }\n case 'children': {\n const children = (record[field.key] as Array<SchemaNode> | undefined) ?? []\n return `${field.prefix}[${children.map((c) => signatureOf(c)).join(',')}]`\n }\n case 'objectProps': {\n const obj = node as Extract<SchemaNode, { type: 'object' }>\n const props = (obj.properties ?? []).map((prop) => `${prop.name}${prop.required ? '!' : '?'}${signatureOf(prop.schema)}`).join(',')\n return `p[${props}]`\n }\n case 'additionalProps': {\n const obj = node as Extract<SchemaNode, { type: 'object' }>\n if (typeof obj.additionalProperties === 'boolean') return `ab:${obj.additionalProperties}`\n if (obj.additionalProperties) return `as:${signatureOf(obj.additionalProperties)}`\n return ''\n }\n case 'patternProps': {\n const obj = node as Extract<SchemaNode, { type: 'object' }>\n const pattern = obj.patternProperties\n ? Object.keys(obj.patternProperties)\n .sort()\n .map((key) => `${key}=${signatureOf(obj.patternProperties![key]!)}`)\n .join(',')\n : ''\n return `pp[${pattern}]`\n }\n case 'enumValues': {\n const en = node as Extract<SchemaNode, { type: 'enum' }>\n let values = ''\n if (en.namedEnumValues?.length) {\n values = en.namedEnumValues.map((entry) => `${entry.name}=${entry.primitive}:${String(entry.value)}`).join(',')\n } else if (en.enumValues?.length) {\n values = en.enumValues.map((value) => `${value === null ? 'null' : typeof value}:${String(value)}`).join(',')\n }\n return `v[${values}]`\n }\n case 'refTarget': {\n return `->${refTargetName(node as Extract<SchemaNode, { type: 'ref' }>)}`\n }\n }\n}\n\n/**\n * Builds the local shape descriptor that {@link signatureOf} hashes: the node's kind, flags,\n * constraints, and its children's signatures.\n */\nfunction describeShape(node: SchemaNode): string {\n const flags = flagsDescriptor(node)\n const fields = SHAPE_KEYS[node.type]\n if (!fields) return `${node.type}|${flags}`\n\n const record = node as unknown as Record<string, unknown>\n const parts: Array<string> = [`${node.type}|${flags}`]\n for (const field of fields) {\n parts.push(serializeShapeField(field, node, record))\n }\n return parts.join('|')\n}\n\n/**\n * Caches the digest per node, keyed by identity. A `WeakMap` so entries die with the node, and so\n * a tree hashed during dedupe planning is not walked again when it is rewritten during streaming.\n * Reuse is safe because a signature depends only on content, and nodes are immutable once created.\n */\nconst signatureCache = new WeakMap<SchemaNode, string>()\n\n/**\n * Computes a deterministic, shape-only signature (a content hash) for a schema node. Two schemas\n * share a signature when they are structurally identical, ignoring documentation (`name`, `title`,\n * `description`, `example`, `default`, `deprecated`) and usage-slot flags (`optional`, `nullish`,\n * `readOnly`, `writeOnly`). `nullable` is kept because it changes the produced type, and `ref`\n * nodes compare by target name, which also terminates on circular shapes.\n *\n * @example Two enums with different descriptions share a signature\n * ```ts\n * signatureOf(createSchema({ type: 'enum', primitive: 'string', enumValues: ['a', 'b'], description: 'x' })) ===\n * signatureOf(createSchema({ type: 'enum', primitive: 'string', enumValues: ['a', 'b'] }))\n * ```\n */\nexport function signatureOf(node: SchemaNode): string {\n const cached = signatureCache.get(node)\n if (cached !== undefined) return cached\n const signature = hash('sha256', describeShape(node), 'hex')\n signatureCache.set(node, signature)\n\n return signature\n}\n\n/**\n * Returns `true` when two schema nodes are structurally identical under shape-only equality,\n * meaning they produce the same TypeScript type.\n */\nexport function isSchemaEqual(a: SchemaNode, b: SchemaNode): boolean {\n return signatureOf(a) === signatureOf(b)\n}\n","export { schemaTypes } from './constants.ts'\nexport { defineDialect } from './defineDialect.ts'\nexport { isHttpOperationNode, narrowSchema } from './guards.ts'\nexport { applyMacros, composeMacros, defineMacro } from './defineMacro.ts'\nexport { defineNode } from './defineNode.ts'\nexport { optionality } from './optionality.ts'\nexport { createPrinterFactory, definePrinter } from './definePrinter.ts'\nexport { signatureOf } from './signature.ts'\nexport { collect, transform, walk } from './visitor.ts'\n\nexport * as factory from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AAc,IAAI,GAAG,KAAK;CAC3D,eAAe,IAAI,MAAM,SAAS;CAElC,OAAO;AACT"}
{"version":3,"file":"index.js","names":["obj"],"sources":["../src/defineDialect.ts","../src/definePrinter.ts","../src/signature.ts","../src/exports.ts"],"sourcesContent":["import type { Node } from './nodes/index.ts'\n\n/**\n * The spec-specific questions a schema parser answers while turning a source document into Kubb\n * AST nodes. The rest of the pipeline is generic JSON Schema, so this is the one seam where\n * OpenAPI, AsyncAPI, and plain JSON Schema differ.\n */\nexport type SchemaDialect<TSchema = unknown, TRef = TSchema, TDiscriminated = TSchema, TDocument = unknown> = {\n /**\n * Whether the schema is nullable.\n */\n isNullable(schema?: TSchema): boolean\n /**\n * Whether the value is a `$ref` pointer.\n */\n isReference(value?: unknown): value is TRef\n /**\n * Whether the schema carries a discriminator for polymorphism.\n */\n isDiscriminator(value?: unknown): value is TDiscriminated\n /**\n * Whether the schema is binary data, converted to a `blob` node.\n */\n isBinary(schema: TSchema): boolean\n /**\n * Resolves a local `$ref` against the document, or nullish when it cannot.\n */\n resolveRef<TResolved>(document: TDocument, ref: string): TResolved | null | undefined\n}\n\n/**\n * How a dialect collapses structurally identical schemas into shared definitions. The contract is\n * generic over the plan and context types, which the adapter supplies. The mechanics live in the\n * adapter, not here, so `@kubb/ast` carries no dedupe logic. The returned plan owns the rewriting\n * behavior, so callers interact with one object.\n */\nexport type Dedupe<TPlan = unknown, TContext = unknown> = {\n /**\n * Scans a forest of nodes and produces a plan describing which shapes to share.\n */\n plan(roots: ReadonlyArray<Node>, context: TContext): TPlan\n}\n\n/**\n * A spec adapter's dialect. `name` identifies it in logs and diagnostics, `schema` holds the\n * spec-specific schema questions the parser answers, and `dedupe` is the schema-sharing seam.\n */\nexport type DefineDialect<TSchema = unknown, TRef = TSchema, TDiscriminated = TSchema, TDocument = unknown, TDedupe extends Dedupe = Dedupe> = {\n /**\n * Identifies the dialect in logs and diagnostics.\n */\n name: string\n /**\n * The spec-specific schema behavior. See {@link SchemaDialect}.\n */\n schema: SchemaDialect<TSchema, TRef, TDiscriminated, TDocument>\n /**\n * The schema-sharing behavior. See {@link Dedupe}.\n */\n dedupe: TDedupe\n}\n\n/**\n * Types a {@link DefineDialect} for an adapter. Adds no runtime behavior and only pins the\n * dialect's type for inference.\n *\n * @example\n * ```ts\n * export const oasDialect = defineDialect({\n * name: 'oas',\n * schema: {\n * isNullable,\n * isReference,\n * isDiscriminator,\n * isBinary: (schema) => schema.type === 'string' && schema.contentMediaType === 'application/octet-stream',\n * resolveRef,\n * },\n * dedupe: { plan },\n * })\n * ```\n */\nexport function defineDialect<TSchema, TRef, TDiscriminated, TDocument, TDedupe extends Dedupe>(\n dialect: DefineDialect<TSchema, TRef, TDiscriminated, TDocument, TDedupe>,\n): DefineDialect<TSchema, TRef, TDiscriminated, TDocument, TDedupe> {\n return dialect\n}\n","import type { SchemaNode, SchemaNodeByType, SchemaType } from './nodes/index.ts'\n\n/**\n * Runtime context passed as `this` to printer handlers.\n *\n * `this.transform` dispatches to node-level handlers from `nodes`.\n *\n * @example\n * ```ts\n * const context: PrinterHandlerContext<string, {}> = {\n * options: {},\n * transform: () => 'value',\n * }\n * ```\n */\ntype PrinterHandlerContext<TOutput, TOptions extends object> = {\n /**\n * Recursively transform a nested `SchemaNode` to `TOutput` using the node-level handlers.\n * Use `this.transform` inside `nodes` handlers and inside the `print` override.\n */\n transform: (node: SchemaNode) => TOutput | null\n /**\n * Options for this printer instance.\n */\n options: TOptions\n}\n\n/**\n * Handler for one schema node type.\n *\n * Use a regular function (not an arrow function) if you need `this`.\n *\n * @example\n * ```ts\n * const handler: PrinterHandler<string, {}, 'string'> = function () {\n * return 'string'\n * }\n * ```\n */\ntype PrinterHandler<TOutput, TOptions extends object, T extends SchemaType = SchemaType> = (\n this: PrinterHandlerContext<TOutput, TOptions>,\n node: SchemaNodeByType[T],\n) => TOutput | null\n\n/**\n * Partial map of per-node-type handler overrides for a printer.\n *\n * Each key is a `SchemaType` string (e.g. `'date'`, `'string'`).\n * Supply only the handlers you want to replace. The printer's built-in\n * defaults fill in the rest.\n *\n * @example\n * ```ts\n * pluginZod({\n * printer: {\n * nodes: {\n * date(): string {\n * return 'z.string().date()'\n * },\n * } satisfies PrinterPartial<string, PrinterZodOptions>,\n * },\n * })\n * ```\n */\nexport type PrinterPartial<TOutput, TOptions extends object> = Partial<{\n [K in SchemaType]: PrinterHandler<TOutput, TOptions, K>\n}>\n\n/**\n * Generic shape used by `definePrinter`.\n *\n * - `TName` unique string identifier (e.g. `'zod'`, `'ts'`)\n * - `TOptions` options passed to and stored on the printer instance\n * - `TOutput` the type emitted by node handlers\n * - `TPrintOutput` type returned by public `print` (defaults to `TOutput`)\n *\n * @example\n * ```ts\n * type MyPrinter = PrinterFactoryOptions<'my', { strict: boolean }, string>\n * ```\n */\nexport type PrinterFactoryOptions<TName extends string = string, TOptions extends object = object, TOutput = unknown, TPrintOutput = TOutput> = {\n name: TName\n options: TOptions\n output: TOutput\n printOutput: TPrintOutput\n}\n\n/**\n * Printer instance returned by a printer factory.\n *\n * @example\n * ```ts\n * const printer = definePrinter((options: {}) => ({ name: 'x', options, nodes: {} }))({})\n * ```\n */\nexport type Printer<T extends PrinterFactoryOptions = PrinterFactoryOptions> = {\n /**\n * Unique identifier supplied at creation time.\n */\n name: T['name']\n /**\n * Options for this printer instance.\n */\n options: T['options']\n /**\n * Node-level dispatcher, converts a `SchemaNode` directly to `TOutput` using the `nodes` handlers.\n * Always dispatches through the `nodes` map. Never calls the `print` override.\n * Reach for it when you need the raw output (e.g. `ts.TypeNode`) without declaration wrapping.\n */\n transform: (node: SchemaNode) => T['output'] | null\n /**\n * Public printer. If the builder provides a root-level `print`, this calls that\n * higher-level function (which may produce full declarations).\n * Otherwise, falls back to the node-level dispatcher.\n */\n print: (node: SchemaNode) => T['printOutput'] | null\n}\n\n/**\n * Builder function passed to `definePrinter`.\n *\n * It receives resolved options and returns:\n * - `name`\n * - `options`\n * - `nodes` handlers\n * - optional top-level `print` override\n *\n * @example\n * ```ts\n * const build = (options: {}) => ({ name: 'x' as const, options, nodes: {} })\n * ```\n */\ntype PrinterBuilder<T extends PrinterFactoryOptions> = (options: T['options']) => {\n name: T['name']\n /**\n * Options to store on the printer.\n */\n options: T['options']\n nodes: Partial<{\n [K in SchemaType]: PrinterHandler<T['output'], T['options'], K>\n }>\n /**\n * Optional root-level print override. When provided, becomes the public `printer.print`.\n * Use `this.transform(node)` inside this function to dispatch to the node-level handlers (`nodes`),\n * not the override itself, so recursion is safe.\n */\n print?: (this: PrinterHandlerContext<T['output'], T['options']>, node: SchemaNode) => T['printOutput'] | null\n}\n/**\n * Defines a schema printer: a function that takes a `SchemaNode` and emits\n * code in your target language. Each plugin that produces code from schemas\n * (TypeScript types, Zod schemas, Faker factories) ships a printer built\n * with this helper.\n *\n * The builder receives resolved options and returns:\n *\n * - `name` unique identifier for the printer.\n * - `options` stored on the returned printer instance.\n * - `nodes` map of `SchemaType` → handler. Handlers return the rendered\n * output (a string, a TypeScript AST node, ...) for that schema type.\n * - `print` (optional), top-level override exposed as `printer.print`.\n * Use `this.transform(node)` inside it to dispatch to `nodes` recursively.\n *\n * Without a `print` override, `printer.print` falls back to `printer.transform`\n * (the node-level dispatcher).\n *\n * @example Tiny Zod printer\n * ```ts\n * import { definePrinter, type PrinterFactoryOptions } from '@kubb/ast'\n *\n * type PrinterZod = PrinterFactoryOptions<'zod', { strict?: boolean }, string>\n *\n * export const zodPrinter = definePrinter<PrinterZod>((options) => ({\n * name: 'zod',\n * options: { strict: options.strict ?? true },\n * nodes: {\n * string: () => 'z.string()',\n * object(node) {\n * const props = node.properties\n * .map((p) => `${p.name}: ${this.transform(p.schema)}`)\n * .join(', ')\n * return `z.object({ ${props} })`\n * },\n * },\n * }))\n * ```\n */\nexport function definePrinter<T extends PrinterFactoryOptions = PrinterFactoryOptions>(build: PrinterBuilder<T>): (options?: T['options']) => Printer<T> {\n return createPrinterFactory<SchemaNode, SchemaType, SchemaNodeByType>((node) => node.type)(build) as (options?: T['options']) => Printer<T>\n}\n\n/**\n * Generic printer factory behind `definePrinter`. Pass a `getKey` function that maps a node to its\n * handler key, and it returns a `definePrinter`-style helper for that node and key type. `definePrinter`\n * itself is this factory keyed by `node.type`.\n *\n * @example Key a printer by `node.kind` instead of `node.type`\n * ```ts\n * const defineFunctionPrinter = createPrinterFactory<FunctionParamNode, FunctionParamKind, Partial<Record<FunctionParamKind, FunctionParamNode>>>(\n * (node) => node.kind,\n * )\n * ```\n */\nexport function createPrinterFactory<TNode, TKey extends string, TNodeByKey extends Partial<Record<TKey, TNode>>>(getKey: (node: TNode) => TKey | null) {\n return function <T extends PrinterFactoryOptions>(\n build: (options: T['options']) => {\n name: T['name']\n options: T['options']\n nodes: Partial<{\n [K in TKey]: (\n this: {\n transform: (node: TNode) => T['output'] | null\n options: T['options']\n },\n node: TNodeByKey[K],\n ) => T['output'] | null\n }>\n print?: (\n this: {\n transform: (node: TNode) => T['output'] | null\n options: T['options']\n },\n node: TNode,\n ) => T['printOutput'] | null\n },\n ): (options?: T['options']) => {\n name: T['name']\n options: T['options']\n transform: (node: TNode) => T['output'] | null\n print: (node: TNode) => T['printOutput'] | null\n } {\n return (options) => {\n const { name, options: resolvedOptions, nodes, print: printOverride } = build(options ?? ({} as T['options']))\n\n const context = {\n options: resolvedOptions,\n transform: (node: TNode): T['output'] | null => {\n const key = getKey(node)\n if (key === null) return null\n\n const handler = nodes[key]\n\n if (!handler) return null\n\n return (handler as (this: typeof context, node: TNode) => T['output'] | null).call(context, node)\n },\n }\n\n return {\n name,\n options: resolvedOptions,\n transform: context.transform,\n print: (printOverride ? printOverride.bind(context) : context.transform) as (node: TNode) => T['printOutput'] | null,\n }\n }\n }\n}\n","import { hash } from 'node:crypto'\nimport type { SchemaNode } from './nodes/index.ts'\nimport { extractRefName } from './utils/index.ts'\n\n/**\n * The flags shared by every node kind that affect its type: `primitive`, `format`, `nullable`.\n */\nfunction flagsDescriptor(node: SchemaNode): string {\n return `${node.primitive ?? ''};${node.format ?? ''};${node.nullable ? 1 : 0}`\n}\n\nfunction refTargetName(node: Extract<SchemaNode, { type: 'ref' }>): string {\n if (node.ref) return extractRefName(node.ref)\n return node.name ?? ''\n}\n\ntype ScalarField = { kind: 'scalar'; key: string; prefix: string }\ntype BoolField = { kind: 'bool'; key: string; prefix: string }\ntype ChildField = { kind: 'child'; key: string; prefix: string }\ntype ChildrenField = { kind: 'children'; key: string; prefix: string }\ntype ObjectPropsField = { kind: 'objectProps' }\ntype AdditionalPropsField = { kind: 'additionalProps' }\ntype PatternPropsField = { kind: 'patternProps' }\ntype EnumValuesField = { kind: 'enumValues' }\ntype RefTargetField = { kind: 'refTarget' }\n\ntype ShapeField =\n | ScalarField\n | BoolField\n | ChildField\n | ChildrenField\n | ObjectPropsField\n | AdditionalPropsField\n | PatternPropsField\n | EnumValuesField\n | RefTargetField\n\nconst arrayTupleFields: ReadonlyArray<ShapeField> = [\n { kind: 'children', key: 'items', prefix: 'i' },\n { kind: 'child', key: 'rest', prefix: 'r' },\n { kind: 'scalar', key: 'min', prefix: 'mn' },\n { kind: 'scalar', key: 'max', prefix: 'mx' },\n { kind: 'bool', key: 'unique', prefix: 'u' },\n]\n\nconst numericFields: ReadonlyArray<ShapeField> = [\n { kind: 'scalar', key: 'min', prefix: 'mn' },\n { kind: 'scalar', key: 'max', prefix: 'mx' },\n { kind: 'scalar', key: 'exclusiveMinimum', prefix: 'emn' },\n { kind: 'scalar', key: 'exclusiveMaximum', prefix: 'emx' },\n { kind: 'scalar', key: 'multipleOf', prefix: 'mo' },\n]\n\nconst rangeFields: ReadonlyArray<ShapeField> = [\n { kind: 'scalar', key: 'min', prefix: 'mn' },\n { kind: 'scalar', key: 'max', prefix: 'mx' },\n]\n\n/**\n * Maps each node `type` to its ordered shape-contributing fields. Types absent from the map\n * (boolean, null, any, and other scalars) fall back to `${type}|${flags}`.\n */\nconst SHAPE_KEYS: Partial<Record<SchemaNode['type'], ReadonlyArray<ShapeField>>> = {\n object: [\n { kind: 'objectProps' },\n { kind: 'additionalProps' },\n { kind: 'patternProps' },\n { kind: 'scalar', key: 'minProperties', prefix: 'mn' },\n { kind: 'scalar', key: 'maxProperties', prefix: 'mx' },\n ],\n array: arrayTupleFields,\n tuple: arrayTupleFields,\n union: [\n { kind: 'scalar', key: 'strategy', prefix: 's' },\n { kind: 'scalar', key: 'discriminatorPropertyName', prefix: 'd' },\n { kind: 'children', key: 'members', prefix: 'm' },\n ],\n intersection: [{ kind: 'children', key: 'members', prefix: 'm' }],\n enum: [{ kind: 'enumValues' }],\n ref: [{ kind: 'refTarget' }],\n string: [\n { kind: 'scalar', key: 'min', prefix: 'mn' },\n { kind: 'scalar', key: 'max', prefix: 'mx' },\n { kind: 'scalar', key: 'pattern', prefix: 'pt' },\n ],\n number: numericFields,\n integer: numericFields,\n bigint: numericFields,\n url: [\n { kind: 'scalar', key: 'path', prefix: 'path' },\n { kind: 'scalar', key: 'min', prefix: 'mn' },\n { kind: 'scalar', key: 'max', prefix: 'mx' },\n ],\n uuid: rangeFields,\n email: rangeFields,\n datetime: [\n { kind: 'bool', key: 'offset', prefix: 'o' },\n { kind: 'bool', key: 'local', prefix: 'l' },\n ],\n date: [{ kind: 'scalar', key: 'representation', prefix: 'rep' }],\n time: [{ kind: 'scalar', key: 'representation', prefix: 'rep' }],\n}\n\nfunction serializeShapeField(field: ShapeField, node: SchemaNode, record: Record<string, unknown>): string {\n switch (field.kind) {\n case 'scalar':\n return `${field.prefix}:${record[field.key] ?? ''}`\n case 'bool':\n return `${field.prefix}:${record[field.key] ? 1 : 0}`\n case 'child': {\n const child = record[field.key] as SchemaNode | undefined\n return `${field.prefix}:${child ? signatureOf(child) : ''}`\n }\n case 'children': {\n const children = (record[field.key] as Array<SchemaNode> | undefined) ?? []\n return `${field.prefix}[${children.map((c) => signatureOf(c)).join(',')}]`\n }\n case 'objectProps': {\n const obj = node as Extract<SchemaNode, { type: 'object' }>\n const props = (obj.properties ?? []).map((prop) => `${prop.name}${prop.required ? '!' : '?'}${signatureOf(prop.schema)}`).join(',')\n return `p[${props}]`\n }\n case 'additionalProps': {\n const obj = node as Extract<SchemaNode, { type: 'object' }>\n if (typeof obj.additionalProperties === 'boolean') return `ab:${obj.additionalProperties}`\n if (obj.additionalProperties) return `as:${signatureOf(obj.additionalProperties)}`\n return ''\n }\n case 'patternProps': {\n const obj = node as Extract<SchemaNode, { type: 'object' }>\n const pattern = obj.patternProperties\n ? Object.keys(obj.patternProperties)\n .sort()\n .map((key) => `${key}=${signatureOf(obj.patternProperties![key]!)}`)\n .join(',')\n : ''\n return `pp[${pattern}]`\n }\n case 'enumValues': {\n const en = node as Extract<SchemaNode, { type: 'enum' }>\n let values = ''\n if (en.namedEnumValues?.length) {\n values = en.namedEnumValues.map((entry) => `${entry.name}=${entry.primitive}:${String(entry.value)}`).join(',')\n } else if (en.enumValues?.length) {\n values = en.enumValues.map((value) => `${value === null ? 'null' : typeof value}:${String(value)}`).join(',')\n }\n return `v[${values}]`\n }\n case 'refTarget': {\n return `->${refTargetName(node as Extract<SchemaNode, { type: 'ref' }>)}`\n }\n }\n}\n\n/**\n * Builds the local shape descriptor that {@link signatureOf} hashes: the node's kind, flags,\n * constraints, and its children's signatures.\n */\nfunction describeShape(node: SchemaNode): string {\n const flags = flagsDescriptor(node)\n const fields = SHAPE_KEYS[node.type]\n if (!fields) return `${node.type}|${flags}`\n\n const record = node as unknown as Record<string, unknown>\n const parts: Array<string> = [`${node.type}|${flags}`]\n for (const field of fields) {\n parts.push(serializeShapeField(field, node, record))\n }\n return parts.join('|')\n}\n\n/**\n * Caches the digest per node, keyed by identity. A `WeakMap` so entries die with the node, and so\n * a tree hashed during dedupe planning is not walked again when it is rewritten during streaming.\n * Reuse is safe because a signature depends only on content, and nodes are immutable once created.\n */\nconst signatureCache = new WeakMap<SchemaNode, string>()\n\n/**\n * Computes a deterministic, shape-only signature (a content hash) for a schema node. Two schemas\n * share a signature when they are structurally identical, ignoring documentation (`name`, `title`,\n * `description`, `examples`, `default`, `deprecated`) and usage-slot flags (`optional`, `nullish`,\n * `readOnly`, `writeOnly`). `nullable` is kept because it changes the produced type, and `ref`\n * nodes compare by target name, which also terminates on circular shapes.\n *\n * @example Two enums with different descriptions share a signature\n * ```ts\n * signatureOf(createSchema({ type: 'enum', primitive: 'string', enumValues: ['a', 'b'], description: 'x' })) ===\n * signatureOf(createSchema({ type: 'enum', primitive: 'string', enumValues: ['a', 'b'] }))\n * ```\n */\nexport function signatureOf(node: SchemaNode): string {\n const cached = signatureCache.get(node)\n if (cached !== undefined) return cached\n const signature = hash('sha256', describeShape(node), 'hex')\n signatureCache.set(node, signature)\n\n return signature\n}\n\n/**\n * Returns `true` when two schema nodes are structurally identical under shape-only equality,\n * meaning they produce the same TypeScript type.\n */\nexport function isSchemaEqual(a: SchemaNode, b: SchemaNode): boolean {\n return signatureOf(a) === signatureOf(b)\n}\n","export { schemaTypes } from './constants.ts'\nexport { defineDialect } from './defineDialect.ts'\nexport { isHttpOperationNode, narrowSchema } from './guards.ts'\nexport { applyMacros, composeMacros, defineMacro } from './defineMacro.ts'\nexport { defineNode } from './defineNode.ts'\nexport { optionality } from './optionality.ts'\nexport { createPrinterFactory, definePrinter } from './definePrinter.ts'\nexport { signatureOf } from './signature.ts'\nexport { collect, transform, walk } from './visitor.ts'\n\nexport * as factory from './factory.ts'\nexport * from './registry.ts'\nexport type * from './types.ts'\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;AAiFA,SAAgB,cACd,SACkE;CAClE,OAAO;AACT;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ACuGA,SAAgB,cAAuE,OAAkE;CACvJ,OAAO,sBAAgE,SAAS,KAAK,IAAI,CAAC,CAAC,KAAK;AAClG;;;;;;;;;;;;;AAcA,SAAgB,qBAAkG,QAAsC;CACtJ,OAAO,SACL,OAyBA;EACA,QAAQ,YAAY;GAClB,MAAM,EAAE,MAAM,SAAS,iBAAiB,OAAO,OAAO,kBAAkB,MAAM,WAAY,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AU,GAAG,OAAO,MAAM,KAAK,GAAG,CAAC,CAAC,KAAK,GAAG;QACzG,IAAI,GAAG,YAAY,QACxB,SAAS,GAAG,WAAW,KAAK,UAAU,GAAG,UAAU,OAAO,SAAS,OAAO,MAAM,GAAG,OAAO,KAAK,GAAG,CAAC,CAAC,KAAK,GAAG;GAE9G,OAAO,KAAK,OAAO;EACrB;EACA,KAAK,aACH,OAAO,KAAK,cAAc,IAA4C;CAE1E;AACF;;;;;AAMA,SAAS,cAAc,MAA0B;CAC/C,MAAM,QAAQ,gBAAgB,IAAI;CAClC,MAAM,SAAS,WAAW,KAAK;CAC/B,IAAI,CAAC,QAAQ,OAAO,GAAG,KAAK,KAAK,GAAG;CAEpC,MAAM,SAAS;CACf,MAAM,QAAuB,CAAC,GAAG,KAAK,KAAK,GAAG,OAAO;CACrD,KAAK,MAAM,SAAS,QAClB,MAAM,KAAK,oBAAoB,OAAO,MAAM,MAAM,CAAC;CAErD,OAAO,MAAM,KAAK,GAAG;AACvB;;;;;;AAOA,MAAM,iCAAiB,IAAI,QAA4B;;;;;;;;;;;;;;AAevD,SAAgB,YAAY,MAA0B;CACpD,MAAM,SAAS,eAAe,IAAI,IAAI;CACtC,IAAI,WAAW,KAAA,GAAW,OAAO;CACjC,MAAM,YAAY,KAAK,UAAU,cAAc,IAAI,GAAG,KAAK;CAC3D,eAAe,IAAI,MAAM,SAAS;CAElC,OAAO;AACT"}
import { n as __name } from "./rolldown-runtime-CNktS9qV.js";
import { n as Macro } from "./defineMacro-B7qm3zTd.js";
import { n as Macro } from "./defineMacro-BQpu6Ags.js";

@@ -4,0 +4,0 @@ //#region src/macros/macroDiscriminatorEnum.d.ts

@@ -1,5 +0,5 @@

import { A as IndexedAccessTypeNode, At as InferSchemaNode, Bt as TypeNode, C as ParameterNode, Ct as UrlSchemaNode, D as FunctionParamNode, E as FunctionParamKind, Et as PropertyNode, Ft as ConstNode, G as FileNode, It as FunctionNode, J as UserFileNode, K as ImportNode, Lt as JSDocNode, M as TypeExpression, Mt as ArrowFunctionNode, N as TypeLiteralNode, Nt as BreakNode, O as FunctionParameterNode, Pt as CodeNode, Rt as JsxNode, S as ParameterLocation, St as UnionSchemaNode, W as ExportNode, _t as SchemaNode, a as InputMeta, an as NodeKind, bt as StringSchemaNode, ct as DatetimeSchemaNode, d as HttpOperationNode, dt as NumberSchemaNode, f as OperationNode, ft as ObjectSchemaNode, g as StatusCode, gt as ScalarSchemaType, h as ResponseNode, ht as ScalarSchemaNode, j as ObjectBindingPatternNode, jt as ParserOptions, k as FunctionParametersNode, l as GenericOperationNode, lt as EnumSchemaNode, mt as RefSchemaNode, n as OutputNode, nn as NodeDef, o as InputNode, ot as ArraySchemaNode, pt as PrimitiveSchemaType, q as SourceNode, rt as ContentNode, st as DateSchemaNode, t as Node, tn as DistributiveOmit, u as HttpMethod, ut as IntersectionSchemaNode, vt as SchemaNodeByType, xt as TimeSchemaNode, y as RequestBodyNode, yt as SchemaType, zt as TextNode } from "./index-BKD4drsX.js";
import { c as VisitorContext, n as Macro, o as ParentOf, s as Visitor, t as Enforce } from "./defineMacro-B7qm3zTd.js";
import { c as SchemaDialect, n as PrinterFactoryOptions, o as Dedupe, r as PrinterPartial, s as DefineDialect, t as Printer } from "./types-BP9BZoq-.js";
import { n as OperationParamsResolver } from "./operationParams-ByVfpYr7.js";
import { A as IndexedAccessTypeNode, At as InferSchemaNode, Bt as TypeNode, C as ParameterNode, Ct as UrlSchemaNode, D as FunctionParamNode, E as FunctionParamKind, Et as PropertyNode, Ft as ConstNode, G as FileNode, It as FunctionNode, J as UserFileNode, K as ImportNode, Lt as JSDocNode, M as TypeExpression, Mt as ArrowFunctionNode, N as TypeLiteralNode, Nt as BreakNode, O as FunctionParameterNode, Pt as CodeNode, Rt as JsxNode, S as ParameterLocation, St as UnionSchemaNode, W as ExportNode, _t as SchemaNode, a as InputMeta, an as NodeKind, bt as StringSchemaNode, ct as DatetimeSchemaNode, d as HttpOperationNode, dt as NumberSchemaNode, f as OperationNode, ft as ObjectSchemaNode, g as StatusCode, gt as ScalarSchemaType, h as ResponseNode, ht as ScalarSchemaNode, j as ObjectBindingPatternNode, jt as ParserOptions, k as FunctionParametersNode, l as GenericOperationNode, lt as EnumSchemaNode, mt as RefSchemaNode, n as OutputNode, nn as NodeDef, o as InputNode, ot as ArraySchemaNode, pt as PrimitiveSchemaType, q as SourceNode, rt as ContentNode, st as DateSchemaNode, t as Node, tn as DistributiveOmit, u as HttpMethod, ut as IntersectionSchemaNode, vt as SchemaNodeByType, xt as TimeSchemaNode, y as RequestBodyNode, yt as SchemaType, zt as TextNode } from "./index-CeJAFegf.js";
import { c as VisitorContext, n as Macro, o as ParentOf, s as Visitor, t as Enforce } from "./defineMacro-BQpu6Ags.js";
import { c as SchemaDialect, n as PrinterFactoryOptions, o as Dedupe, r as PrinterPartial, s as DefineDialect, t as Printer } from "./types-B6thixAv.js";
import { n as OperationParamsResolver } from "./operationParams-DCY3q4C7.js";
export type { ArraySchemaNode, ArrowFunctionNode, BreakNode, CodeNode, ConstNode, ContentNode, DateSchemaNode, DatetimeSchemaNode, Dedupe, DefineDialect, DistributiveOmit, Enforce, EnumSchemaNode, ExportNode, FileNode, FunctionNode, FunctionParamKind, FunctionParamNode, FunctionParameterNode, FunctionParametersNode, GenericOperationNode, HttpMethod, HttpOperationNode, ImportNode, IndexedAccessTypeNode, InferSchemaNode, InputMeta, InputNode, IntersectionSchemaNode, JSDocNode, JsxNode, Macro, Node, NodeDef, NodeKind, NumberSchemaNode, ObjectBindingPatternNode, ObjectSchemaNode, OperationNode, OperationParamsResolver, OutputNode, ParameterLocation, ParameterNode, ParentOf, ParserOptions, PrimitiveSchemaType, Printer, PrinterFactoryOptions, PrinterPartial, PropertyNode, RefSchemaNode, RequestBodyNode, ResponseNode, ScalarSchemaNode, ScalarSchemaType, SchemaDialect, SchemaNode, SchemaNodeByType, SchemaType, SourceNode, StatusCode, StringSchemaNode, TextNode, TimeSchemaNode, TypeExpression, TypeLiteralNode, TypeNode, UnionSchemaNode, UrlSchemaNode, UserFileNode, Visitor, VisitorContext };

@@ -1,1 +0,1 @@

{"version":3,"file":"utils-BJi0y-xg.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","../src/utils/operationParams.ts"],"sourcesContent":["function* chunks<T>(arr: ReadonlyArray<T>, size: number): Generator<Array<T>> {\n for (let i = 0; i < arr.length; i += size) {\n yield arr.slice(i, i + size)\n }\n}\n\nexport type ForBatchesOptions = {\n /**\n * Maximum batch size handed to `process`.\n * Parallel dispatch within a batch is the caller's responsibility\n * (typically via `Promise.all(batch.map(...))`).\n */\n concurrency: number\n /**\n * Called after every batch.\n *\n * Use a cheap, idempotent callback (e.g. one that short-circuits when there\n * is nothing new to do). The helper does not coalesce calls — if you need\n * throttling, do it inside `flush` itself.\n */\n flush?: () => Promise<void>\n}\n\n/**\n * Slices `source` into batches of `concurrency` items and awaits `process` for each batch.\n * Accepts both plain arrays (sync) and `AsyncIterable` (streaming).\n *\n * `process` controls whether items inside a batch run in parallel; this helper only\n * controls batch size and per-batch flushing.\n *\n * @example\n * ```ts\n * // parallel dispatch inside each batch\n * await forBatches(schemas, (batch) => Promise.all(batch.map(process)), { concurrency: 8 })\n *\n * // async iterable with a flush after every batch\n * await forBatches(stream.schemas, (batch) => dispatch(batch), { concurrency: 8, flush })\n * ```\n */\nexport async function forBatches<T>(\n source: ReadonlyArray<T> | AsyncIterable<T>,\n process: (batch: Array<T>) => Promise<unknown>,\n options: ForBatchesOptions,\n): Promise<void> {\n const { concurrency, flush } = options\n\n if (Array.isArray(source)) {\n for (const batch of chunks(source, concurrency)) {\n await process(batch)\n if (flush) await flush()\n }\n return\n }\n\n const batch: Array<T> = []\n for await (const item of source) {\n batch.push(item)\n if (batch.length >= concurrency) {\n await process(batch.splice(0))\n\n if (flush) await flush()\n }\n }\n if (batch.length > 0) {\n await process(batch.splice(0))\n\n if (flush) await flush()\n }\n}\n\n/** 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\n/** Returns `true` when `result` is a rejected `Promise.allSettled` result with a typed `reason`.\n *\n * @example\n * ```ts\n * const results = await Promise.allSettled([p1, p2])\n * results.filter(isPromiseRejectedResult<Error>).map((r) => r.reason.message)\n * ```\n */\nexport function isPromiseRejectedResult<T>(result: PromiseSettledResult<unknown>): result is Omit<PromiseRejectedResult, 'reason'> & { reason: T } {\n return result.status === 'rejected'\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","import { camelCase, isValidVarName, memoize } from '@internals/utils'\nimport { createFunctionParameter, createFunctionParameters, createIndexedAccessType, createTypeLiteral } from '../nodes/function.ts'\nimport type { FunctionParameterNode, FunctionParametersNode, OperationNode, ParameterNode, TypeExpression, TypeLiteralNode } from '../nodes/index.ts'\nimport { resolveGroupType } from './refs.ts'\n\nconst caseParamsMemo = memoize(new WeakMap<Array<ParameterNode>, (casing: string) => Array<ParameterNode>>(), (params) =>\n memoize(new Map<string, Array<ParameterNode>>(), (casing: string) =>\n params.map((param) => {\n const transformed = casing === 'camelcase' || !isValidVarName(param.name) ? camelCase(param.name) : param.name\n return { ...param, name: transformed }\n }),\n ),\n)\n\n/**\n * Applies casing rules to parameter names and returns a new array without mutating the input.\n *\n * Run it before handing parameters to schema builders so output property keys get the right casing\n * while `OperationNode.parameters` stays intact for other consumers. When `casing` is unset, the\n * original array is returned unchanged.\n */\nexport function caseParams(params: Array<ParameterNode>, casing: 'camelcase' | undefined): Array<ParameterNode> {\n if (!casing) return params\n return caseParamsMemo(params)(casing)\n}\n\n/**\n * Named type for a group of parameters (query or header) emitted as a single typed parameter.\n */\nexport type ParamGroupType = {\n /**\n * Type expression for the group, a plain group-name reference.\n */\n type: TypeExpression\n /**\n * Whether the parameter group is optional.\n */\n optional: boolean\n}\n\n/**\n * A single member of a destructured parameter group, fed to `createFunctionParameter({ properties })`.\n */\ntype GroupProperty = {\n name: string\n type: TypeExpression\n optional?: boolean\n}\n\n/**\n * Resolver interface for {@link createOperationParams}.\n *\n * `ResolverTs` from `@kubb/plugin-ts` satisfies this interface and can be passed directly.\n */\nexport type OperationParamsResolver = {\n /**\n * Resolves the type name for an individual parameter.\n *\n * @example Individual path parameter name\n * `resolver.resolveParamName(node, param) // → 'DeletePetPathPetId'`\n */\n resolveParamName(node: OperationNode, param: ParameterNode): string\n /**\n * Resolves the request body type name.\n *\n * @example Request body type name\n * `resolver.resolveDataName(node) // → 'CreatePetData'`\n */\n resolveDataName(node: OperationNode): string\n /**\n * Resolves the grouped path parameters type name.\n * When the return value equals `resolveParamName`, no indexed access is emitted.\n *\n * @example Grouped path params type name\n * `resolver.resolvePathParamsName(node, param) // → 'DeletePetPathParams'`\n */\n resolvePathParamsName(node: OperationNode, param: ParameterNode): string\n /**\n * Resolves the grouped query parameters type name.\n * When the return value equals `resolveParamName`, an inline struct type is emitted instead.\n *\n * @example Grouped query params type name\n * `resolver.resolveQueryParamsName(node, param) // → 'FindPetsByStatusQueryParams'`\n */\n resolveQueryParamsName(node: OperationNode, param: ParameterNode): string\n /**\n * Resolves the grouped header parameters type name.\n * When the return value equals `resolveParamName`, an inline struct type is emitted instead.\n *\n * @example Grouped header params type name\n * `resolver.resolveHeaderParamsName(node, param) // → 'DeletePetHeaderParams'`\n */\n resolveHeaderParamsName(node: OperationNode, param: ParameterNode): string\n}\n\n/**\n * Options for {@link createOperationParams}.\n */\nexport type CreateOperationParamsOptions = {\n /**\n * How all operation parameters are grouped in the function signature.\n * - `'object'` wraps all params into a single destructured object `{ petId, data, params }`\n * - `'inline'` emits each param category as a separate top-level parameter\n */\n paramsType: 'object' | 'inline'\n /**\n * How path parameters are emitted when `paramsType` is `'inline'`.\n * - `'object'` groups them as `{ petId, storeId }: PathParams`\n * - `'inline'` spreads them as individual parameters `petId: string, storeId: string`\n * - `'inlineSpread'` emits a single rest parameter `...pathParams: PathParams`\n */\n pathParamsType: 'object' | 'inline' | 'inlineSpread'\n /**\n * Converts parameter names to camelCase before output.\n */\n paramsCasing?: 'camelcase'\n /**\n * Resolver for parameter and request body type names.\n * Pass `ResolverTs` from `@kubb/plugin-ts` directly.\n * When omitted, falls back to the schema primitive or `'unknown'`.\n */\n resolver?: OperationParamsResolver\n /**\n * Default value for the path parameters binding when `pathParamsType` is `'object'`.\n * Falls back to `'{}'` when all path params are optional.\n */\n pathParamsDefault?: string\n /**\n * Extra parameters appended after the standard operation parameters.\n *\n * @example Plugin-specific trailing parameter\n * ```ts\n * extraParams: [createFunctionParameter({ name: 'options', type: 'Partial<RequestOptions>', default: '{}' })]\n * ```\n */\n extraParams?: Array<FunctionParameterNode>\n /**\n * Override the default parameter names used for body, query, header, and rest-path groups.\n *\n * Useful when targeting languages or frameworks with different naming conventions.\n *\n * @default { data: 'data', params: 'params', headers: 'headers', path: 'pathParams' }\n */\n paramNames?: {\n /**\n * Name for the request body parameter.\n * @default 'data'\n */\n data?: string\n /**\n * Name for the query parameters group parameter.\n * @default 'params'\n */\n params?: string\n /**\n * Name for the header parameters group parameter.\n * @default 'headers'\n */\n headers?: string\n /**\n * Name for the rest path-parameters parameter when `pathParamsType` is `'inlineSpread'`.\n * @default 'pathParams'\n */\n path?: string\n }\n /**\n * Transforms every resolved type name before it lands in a parameter node, for framework-level\n * type wrappers.\n *\n * @example Vue Query, wrap every parameter type with `MaybeRefOrGetter`\n * `typeWrapper: (t) => \\`MaybeRefOrGetter<${t}>\\``\n */\n typeWrapper?: (type: string) => string\n}\n\n/**\n * Resolves the {@link TypeExpression} for an individual parameter.\n *\n * Without a resolver, it falls back to the schema primitive (a plain type-name string). When the\n * parameter belongs to a named group, it emits an {@link IndexedAccessTypeNode} like\n * `GroupParams['petId']`, otherwise the resolved individual name.\n */\nexport function resolveParamType({\n node,\n param,\n resolver,\n}: {\n node: OperationNode\n param: ParameterNode\n resolver: OperationParamsResolver | undefined\n}): TypeExpression {\n if (!resolver) {\n return param.schema.primitive ?? 'unknown'\n }\n\n const individualName = resolver.resolveParamName(node, param)\n\n const groupLocation = param.in === 'path' || param.in === 'query' || param.in === 'header' ? param.in : undefined\n\n const groupResolvers = {\n path: resolver.resolvePathParamsName,\n query: resolver.resolveQueryParamsName,\n header: resolver.resolveHeaderParamsName,\n } as const\n\n const groupName = groupLocation ? groupResolvers[groupLocation].call(resolver, node, param) : undefined\n\n if (groupName && groupName !== individualName) {\n return createIndexedAccessType({ target: groupName, key: param.name })\n }\n\n return individualName\n}\n\n/**\n * Converts an `OperationNode` into function parameters for code generation.\n *\n * Centralizes parameter grouping logic for all plugins. `paramsType` chooses between one\n * destructured object parameter (`object`) and separate top-level parameters (`inline`), while\n * `pathParamsType` controls how path params render in inline mode. Provide a `resolver` for type\n * name resolution and `extraParams` for plugin-specific trailing parameters such as an `options` object.\n */\nexport function createOperationParams(node: OperationNode, options: CreateOperationParamsOptions): FunctionParametersNode {\n const { paramsType, pathParamsType, paramsCasing, resolver, pathParamsDefault, extraParams = [], paramNames, typeWrapper } = options\n\n const dataName = paramNames?.data ?? 'data'\n const paramsName = paramNames?.params ?? 'params'\n const headersName = paramNames?.headers ?? 'headers'\n const pathName = paramNames?.path ?? 'pathParams'\n\n const wrapType = (type: string): string => (typeWrapper ? typeWrapper(type) : type)\n // typeWrapper takes a type-name string, so only plain references are wrapped.\n // TypeLiteral and IndexedAccessType expressions are pre-resolved and pass through unchanged.\n const wrapTypeExpression = (type: TypeExpression): TypeExpression => (typeof type === 'string' ? wrapType(type) : type)\n\n const casedParams = caseParams(node.parameters, paramsCasing)\n const pathParams = casedParams.filter((p) => p.in === 'path')\n const queryParams = casedParams.filter((p) => p.in === 'query')\n const headerParams = casedParams.filter((p) => p.in === 'header')\n\n const toProperty = (param: ParameterNode): GroupProperty => ({\n name: param.name,\n type: wrapTypeExpression(resolveParamType({ node, param, resolver })),\n optional: !param.required,\n })\n const emptyObjectDefault = (props: Array<GroupProperty>): string | undefined => (props.every((p) => p.optional) ? '{}' : undefined)\n\n const bodyType = node.requestBody?.content?.[0]?.schema ? wrapType(resolver?.resolveDataName(node) ?? 'unknown') : undefined\n const bodyProperty: Array<GroupProperty> = bodyType ? [{ name: dataName, type: bodyType, optional: !(node.requestBody?.required ?? false) }] : []\n\n const trailingGroups: Array<BuildGroupArgs> = [\n { name: paramsName, node, params: queryParams, groupType: resolveGroupType({ node, params: queryParams, group: 'query', resolver }), resolver, wrapType },\n {\n name: headersName,\n node,\n params: headerParams,\n groupType: resolveGroupType({ node, params: headerParams, group: 'header', resolver }),\n resolver,\n wrapType,\n },\n ]\n\n const params: Array<FunctionParameterNode> = []\n\n if (paramsType === 'object') {\n const children = [...pathParams.map(toProperty), ...bodyProperty, ...trailingGroups.flatMap(buildGroupProperty)]\n if (children.length) {\n params.push(createFunctionParameter({ properties: children, default: emptyObjectDefault(children) }))\n }\n } else {\n if (pathParamsType === 'inlineSpread' && pathParams.length) {\n const spreadType = resolver?.resolvePathParamsName(node, pathParams[0]!)\n params.push(createFunctionParameter({ name: pathName, type: spreadType ? wrapType(spreadType) : undefined, rest: true }))\n } else if (pathParamsType === 'inline') {\n params.push(...pathParams.map((p) => createFunctionParameter(toProperty(p))))\n } else if (pathParams.length) {\n const pathChildren = pathParams.map(toProperty)\n params.push(createFunctionParameter({ properties: pathChildren, default: pathParamsDefault ?? emptyObjectDefault(pathChildren) }))\n }\n\n params.push(...bodyProperty.map((p) => createFunctionParameter(p)))\n params.push(...trailingGroups.flatMap(buildGroupParam))\n }\n\n params.push(...extraParams)\n\n return createFunctionParameters({ params })\n}\n\n/**\n * Shared arguments for building a query or header parameter group.\n */\nexport type BuildGroupArgs = {\n name: string\n node: OperationNode\n params: Array<ParameterNode>\n groupType: ParamGroupType | null\n resolver: OperationParamsResolver | undefined\n wrapType: (type: string) => string\n}\n\n/**\n * Builds the property descriptor for a query or header group.\n * Returns an empty array when there are no params to emit.\n *\n * A pre-resolved `groupType` emits `name: GroupType`. Otherwise it builds an inline\n * {@link TypeLiteralNode} from the individual params.\n */\nfunction buildGroupProperty({ name, node, params, groupType, resolver, wrapType }: BuildGroupArgs): Array<GroupProperty> {\n if (groupType) {\n const type = typeof groupType.type === 'string' ? wrapType(groupType.type) : groupType.type\n return [{ name, type, optional: groupType.optional }]\n }\n if (params.length) {\n return [{ name, type: buildTypeLiteral({ node, params, resolver }), optional: params.every((p) => !p.required) }]\n }\n return []\n}\n\n/**\n * Builds a single {@link FunctionParameterNode} for a query or header group.\n * Returns an empty array when there are no params to emit.\n *\n * A pre-resolved `groupType` emits `name: GroupType`. Otherwise it builds an inline\n * {@link TypeLiteralNode} from the individual params.\n */\nexport function buildGroupParam(args: BuildGroupArgs): Array<FunctionParameterNode> {\n return buildGroupProperty(args).map((p) => createFunctionParameter(p))\n}\n\n/**\n * Builds a {@link TypeLiteralNode} for an inline anonymous type grouping named fields.\n *\n * Used when query or header parameters have no dedicated group type name.\n * Each language printer renders this appropriately (TypeScript: `{ petId: string; name?: string }`).\n */\nexport function buildTypeLiteral({\n node,\n params,\n resolver,\n}: {\n node: OperationNode\n params: Array<ParameterNode>\n resolver: OperationParamsResolver | undefined\n}): TypeLiteralNode {\n return createTypeLiteral({\n members: params.map((p) => ({\n name: p.name,\n type: resolveParamType({ node, param: p, resolver }),\n optional: !p.required,\n })),\n })\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA6IA,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;;;;;;;AChJA,MAAM,gBAAgB,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,E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GAAM;GAAQ;EAAS,CAAC;EAAG,UAAU,OAAO,OAAO,MAAM,CAAC,EAAE,QAAQ;CAAE,CAAC;CAElH,OAAO,CAAC;AACV;;;;;;;;AASA,SAAgB,gBAAgB,MAAoD;CAClF,OAAO,mBAAmB,IAAI,CAAC,CAAC,KAAK,MAAM,wBAAwB,CAAC,CAAC;AACvE;;;;;;;AAQA,SAAgB,iBAAiB,EAC/B,MACA,QACA,YAKkB;CAClB,OAAO,kBAAkB,EACvB,SAAS,OAAO,KAAK,OAAO;EAC1B,MAAM,EAAE;EACR,MAAM,iBAAiB;GAAE;GAAM,OAAO;GAAG;EAAS,CAAC;EACnD,UAAU,CAAC,EAAE;CACf,EAAE,EACJ,CAAC;AACH"}
{"version":3,"file":"utils-BJi0y-xg.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","../src/utils/operationParams.ts"],"sourcesContent":["function* chunks<T>(arr: ReadonlyArray<T>, size: number): Generator<Array<T>> {\n for (let i = 0; i < arr.length; i += size) {\n yield arr.slice(i, i + size)\n }\n}\n\nexport type ForBatchesOptions = {\n /**\n * Maximum batch size handed to `process`.\n * Parallel dispatch within a batch is the caller's responsibility\n * (typically via `Promise.all(batch.map(...))`).\n */\n concurrency: number\n /**\n * Called after every batch.\n *\n * Use a cheap, idempotent callback (e.g. one that short-circuits when there\n * is nothing new to do). The helper does not coalesce calls — if you need\n * throttling, do it inside `flush` itself.\n */\n flush?: () => Promise<void>\n}\n\n/**\n * Slices `source` into batches of `concurrency` items and awaits `process` for each batch.\n * Accepts both plain arrays (sync) and `AsyncIterable` (streaming).\n *\n * `process` controls whether items inside a batch run in parallel; this helper only\n * controls batch size and per-batch flushing.\n *\n * @example\n * ```ts\n * // parallel dispatch inside each batch\n * await forBatches(schemas, (batch) => Promise.all(batch.map(process)), { concurrency: 8 })\n *\n * // async iterable with a flush after every batch\n * await forBatches(stream.schemas, (batch) => dispatch(batch), { concurrency: 8, flush })\n * ```\n */\nexport async function forBatches<T>(\n source: ReadonlyArray<T> | AsyncIterable<T>,\n process: (batch: Array<T>) => Promise<unknown>,\n options: ForBatchesOptions,\n): Promise<void> {\n const { concurrency, flush } = options\n\n if (Array.isArray(source)) {\n for (const batch of chunks(source, concurrency)) {\n await process(batch)\n if (flush) await flush()\n }\n return\n }\n\n const batch: Array<T> = []\n for await (const item of source) {\n batch.push(item)\n if (batch.length >= concurrency) {\n await process(batch.splice(0))\n\n if (flush) await flush()\n }\n }\n if (batch.length > 0) {\n await process(batch.splice(0))\n\n if (flush) await flush()\n }\n}\n\n/** 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","import { camelCase, isValidVarName, memoize } from '@internals/utils'\nimport { createFunctionParameter, createFunctionParameters, createIndexedAccessType, createTypeLiteral } from '../nodes/function.ts'\nimport type { FunctionParameterNode, FunctionParametersNode, OperationNode, ParameterNode, TypeExpression, TypeLiteralNode } from '../nodes/index.ts'\nimport { resolveGroupType } from './refs.ts'\n\nconst caseParamsMemo = memoize(new WeakMap<Array<ParameterNode>, (casing: string) => Array<ParameterNode>>(), (params) =>\n memoize(new Map<string, Array<ParameterNode>>(), (casing: string) =>\n params.map((param) => {\n const transformed = casing === 'camelcase' || !isValidVarName(param.name) ? camelCase(param.name) : param.name\n return { ...param, name: transformed }\n }),\n ),\n)\n\n/**\n * Applies casing rules to parameter names and returns a new array without mutating the input.\n *\n * Run it before handing parameters to schema builders so output property keys get the right casing\n * while `OperationNode.parameters` stays intact for other consumers. When `casing` is unset, the\n * original array is returned unchanged.\n */\nexport function caseParams(params: Array<ParameterNode>, casing: 'camelcase' | undefined): Array<ParameterNode> {\n if (!casing) return params\n return caseParamsMemo(params)(casing)\n}\n\n/**\n * Named type for a group of parameters (query or header) emitted as a single typed parameter.\n */\nexport type ParamGroupType = {\n /**\n * Type expression for the group, a plain group-name reference.\n */\n type: TypeExpression\n /**\n * Whether the parameter group is optional.\n */\n optional: boolean\n}\n\n/**\n * A single member of a destructured parameter group, fed to `createFunctionParameter({ properties })`.\n */\ntype GroupProperty = {\n name: string\n type: TypeExpression\n optional?: boolean\n}\n\n/**\n * Resolver interface for {@link createOperationParams}.\n *\n * `ResolverTs` from `@kubb/plugin-ts` satisfies this interface and can be passed directly.\n */\nexport type OperationParamsResolver = {\n /**\n * Resolves the type name for an individual parameter.\n *\n * @example Individual path parameter name\n * `resolver.resolveParamName(node, param) // → 'DeletePetPathPetId'`\n */\n resolveParamName(node: OperationNode, param: ParameterNode): string\n /**\n * Resolves the request body type name.\n *\n * @example Request body type name\n * `resolver.resolveDataName(node) // → 'CreatePetData'`\n */\n resolveDataName(node: OperationNode): string\n /**\n * Resolves the grouped path parameters type name.\n * When the return value equals `resolveParamName`, no indexed access is emitted.\n *\n * @example Grouped path params type name\n * `resolver.resolvePathParamsName(node, param) // → 'DeletePetPathParams'`\n */\n resolvePathParamsName(node: OperationNode, param: ParameterNode): string\n /**\n * Resolves the grouped query parameters type name.\n * When the return value equals `resolveParamName`, an inline struct type is emitted instead.\n *\n * @example Grouped query params type name\n * `resolver.resolveQueryParamsName(node, param) // → 'FindPetsByStatusQueryParams'`\n */\n resolveQueryParamsName(node: OperationNode, param: ParameterNode): string\n /**\n * Resolves the grouped header parameters type name.\n * When the return value equals `resolveParamName`, an inline struct type is emitted instead.\n *\n * @example Grouped header params type name\n * `resolver.resolveHeaderParamsName(node, param) // → 'DeletePetHeaderParams'`\n */\n resolveHeaderParamsName(node: OperationNode, param: ParameterNode): string\n}\n\n/**\n * Options for {@link createOperationParams}.\n */\nexport type CreateOperationParamsOptions = {\n /**\n * How all operation parameters are grouped in the function signature.\n * - `'object'` wraps all params into a single destructured object `{ petId, data, params }`\n * - `'inline'` emits each param category as a separate top-level parameter\n */\n paramsType: 'object' | 'inline'\n /**\n * How path parameters are emitted when `paramsType` is `'inline'`.\n * - `'object'` groups them as `{ petId, storeId }: PathParams`\n * - `'inline'` spreads them as individual parameters `petId: string, storeId: string`\n * - `'inlineSpread'` emits a single rest parameter `...pathParams: PathParams`\n */\n pathParamsType: 'object' | 'inline' | 'inlineSpread'\n /**\n * Converts parameter names to camelCase before output.\n */\n paramsCasing?: 'camelcase'\n /**\n * Resolver for parameter and request body type names.\n * Pass `ResolverTs` from `@kubb/plugin-ts` directly.\n * When omitted, falls back to the schema primitive or `'unknown'`.\n */\n resolver?: OperationParamsResolver\n /**\n * Default value for the path parameters binding when `pathParamsType` is `'object'`.\n * Falls back to `'{}'` when all path params are optional.\n */\n pathParamsDefault?: string\n /**\n * Extra parameters appended after the standard operation parameters.\n *\n * @example Plugin-specific trailing parameter\n * ```ts\n * extraParams: [createFunctionParameter({ name: 'options', type: 'Partial<RequestOptions>', default: '{}' })]\n * ```\n */\n extraParams?: Array<FunctionParameterNode>\n /**\n * Override the default parameter names used for body, query, header, and rest-path groups.\n *\n * Useful when targeting languages or frameworks with different naming conventions.\n *\n * @default { data: 'data', params: 'params', headers: 'headers', path: 'pathParams' }\n */\n paramNames?: {\n /**\n * Name for the request body parameter.\n * @default 'data'\n */\n data?: string\n /**\n * Name for the query parameters group parameter.\n * @default 'params'\n */\n params?: string\n /**\n * Name for the header parameters group parameter.\n * @default 'headers'\n */\n headers?: string\n /**\n * Name for the rest path-parameters parameter when `pathParamsType` is `'inlineSpread'`.\n * @default 'pathParams'\n */\n path?: string\n }\n /**\n * Transforms every resolved type name before it lands in a parameter node, for framework-level\n * type wrappers.\n *\n * @example Vue Query, wrap every parameter type with `MaybeRefOrGetter`\n * `typeWrapper: (t) => \\`MaybeRefOrGetter<${t}>\\``\n */\n typeWrapper?: (type: string) => string\n}\n\n/**\n * Resolves the {@link TypeExpression} for an individual parameter.\n *\n * Without a resolver, it falls back to the schema primitive (a plain type-name string). When the\n * parameter belongs to a named group, it emits an {@link IndexedAccessTypeNode} like\n * `GroupParams['petId']`, otherwise the resolved individual name.\n */\nexport function resolveParamType({\n node,\n param,\n resolver,\n}: {\n node: OperationNode\n param: ParameterNode\n resolver: OperationParamsResolver | undefined\n}): TypeExpression {\n if (!resolver) {\n return param.schema.primitive ?? 'unknown'\n }\n\n const individualName = resolver.resolveParamName(node, param)\n\n const groupLocation = param.in === 'path' || param.in === 'query' || param.in === 'header' ? param.in : undefined\n\n const groupResolvers = {\n path: resolver.resolvePathParamsName,\n query: resolver.resolveQueryParamsName,\n header: resolver.resolveHeaderParamsName,\n } as const\n\n const groupName = groupLocation ? groupResolvers[groupLocation].call(resolver, node, param) : undefined\n\n if (groupName && groupName !== individualName) {\n return createIndexedAccessType({ target: groupName, key: param.name })\n }\n\n return individualName\n}\n\n/**\n * Converts an `OperationNode` into function parameters for code generation.\n *\n * Centralizes parameter grouping logic for all plugins. `paramsType` chooses between one\n * destructured object parameter (`object`) and separate top-level parameters (`inline`), while\n * `pathParamsType` controls how path params render in inline mode. Provide a `resolver` for type\n * name resolution and `extraParams` for plugin-specific trailing parameters such as an `options` object.\n */\nexport function createOperationParams(node: OperationNode, options: CreateOperationParamsOptions): FunctionParametersNode {\n const { paramsType, pathParamsType, paramsCasing, resolver, pathParamsDefault, extraParams = [], paramNames, typeWrapper } = options\n\n const dataName = paramNames?.data ?? 'data'\n const paramsName = paramNames?.params ?? 'params'\n const headersName = paramNames?.headers ?? 'headers'\n const pathName = paramNames?.path ?? 'pathParams'\n\n const wrapType = (type: string): string => (typeWrapper ? typeWrapper(type) : type)\n // typeWrapper takes a type-name string, so only plain references are wrapped.\n // TypeLiteral and IndexedAccessType expressions are pre-resolved and pass through unchanged.\n const wrapTypeExpression = (type: TypeExpression): TypeExpression => (typeof type === 'string' ? wrapType(type) : type)\n\n const casedParams = caseParams(node.parameters, paramsCasing)\n const pathParams = casedParams.filter((p) => p.in === 'path')\n const queryParams = casedParams.filter((p) => p.in === 'query')\n const headerParams = casedParams.filter((p) => p.in === 'header')\n\n const toProperty = (param: ParameterNode): GroupProperty => ({\n name: param.name,\n type: wrapTypeExpression(resolveParamType({ node, param, resolver })),\n optional: !param.required,\n })\n const emptyObjectDefault = (props: Array<GroupProperty>): string | undefined => (props.every((p) => p.optional) ? '{}' : undefined)\n\n const bodyType = node.requestBody?.content?.[0]?.schema ? wrapType(resolver?.resolveDataName(node) ?? 'unknown') : undefined\n const bodyProperty: Array<GroupProperty> = bodyType ? [{ name: dataName, type: bodyType, optional: !(node.requestBody?.required ?? false) }] : []\n\n const trailingGroups: Array<BuildGroupArgs> = [\n { name: paramsName, node, params: queryParams, groupType: resolveGroupType({ node, params: queryParams, group: 'query', resolver }), resolver, wrapType },\n {\n name: headersName,\n node,\n params: headerParams,\n groupType: resolveGroupType({ node, params: headerParams, group: 'header', resolver }),\n resolver,\n wrapType,\n },\n ]\n\n const params: Array<FunctionParameterNode> = []\n\n if (paramsType === 'object') {\n const children = [...pathParams.map(toProperty), ...bodyProperty, ...trailingGroups.flatMap(buildGroupProperty)]\n if (children.length) {\n params.push(createFunctionParameter({ properties: children, default: emptyObjectDefault(children) }))\n }\n } else {\n if (pathParamsType === 'inlineSpread' && pathParams.length) {\n const spreadType = resolver?.resolvePathParamsName(node, pathParams[0]!)\n params.push(createFunctionParameter({ name: pathName, type: spreadType ? wrapType(spreadType) : undefined, rest: true }))\n } else if (pathParamsType === 'inline') {\n params.push(...pathParams.map((p) => createFunctionParameter(toProperty(p))))\n } else if (pathParams.length) {\n const pathChildren = pathParams.map(toProperty)\n params.push(createFunctionParameter({ properties: pathChildren, default: pathParamsDefault ?? emptyObjectDefault(pathChildren) }))\n }\n\n params.push(...bodyProperty.map((p) => createFunctionParameter(p)))\n params.push(...trailingGroups.flatMap(buildGroupParam))\n }\n\n params.push(...extraParams)\n\n return createFunctionParameters({ params })\n}\n\n/**\n * Shared arguments for building a query or header parameter group.\n */\nexport type BuildGroupArgs = {\n name: string\n node: OperationNode\n params: Array<ParameterNode>\n groupType: ParamGroupType | null\n resolver: OperationParamsResolver | undefined\n wrapType: (type: string) => string\n}\n\n/**\n * Builds the property descriptor for a query or header group.\n * Returns an empty array when there are no params to emit.\n *\n * A pre-resolved `groupType` emits `name: GroupType`. Otherwise it builds an inline\n * {@link TypeLiteralNode} from the individual params.\n */\nfunction buildGroupProperty({ name, node, params, groupType, resolver, wrapType }: BuildGroupArgs): Array<GroupProperty> {\n if (groupType) {\n const type = typeof groupType.type === 'string' ? wrapType(groupType.type) : groupType.type\n return [{ name, type, optional: groupType.optional }]\n }\n if (params.length) {\n return [{ name, type: buildTypeLiteral({ node, params, resolver }), optional: params.every((p) => !p.required) }]\n }\n return []\n}\n\n/**\n * Builds a single {@link FunctionParameterNode} for a query or header group.\n * Returns an empty array when there are no params to emit.\n *\n * A pre-resolved `groupType` emits `name: GroupType`. Otherwise it builds an inline\n * {@link TypeLiteralNode} from the individual params.\n */\nexport function buildGroupParam(args: BuildGroupArgs): Array<FunctionParameterNode> {\n return buildGroupProperty(args).map((p) => createFunctionParameter(p))\n}\n\n/**\n * Builds a {@link TypeLiteralNode} for an inline anonymous type grouping named fields.\n *\n * Used when query or header parameters have no dedicated group type name.\n * Each language printer renders this appropriately (TypeScript: `{ petId: string; name?: string }`).\n */\nexport function buildTypeLiteral({\n node,\n params,\n resolver,\n}: {\n node: OperationNode\n params: Array<ParameterNode>\n resolver: OperationParamsResolver | undefined\n}): TypeLiteralNode {\n return createTypeLiteral({\n members: params.map((p) => ({\n name: p.name,\n type: resolveParamType({ node, param: p, resolver }),\n optional: !p.required,\n })),\n })\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAiIA,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;;;;;;;ACpIA,MAAM,gBAAgB,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;CACv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AAS,WAAW,SAAS,UAAU,IAAI,IAAI,UAAU;EACjE,UAAU,UAAU;CAAS,CAAC;CAEtD,IAAI,OAAO,QACT,OAAO,CAAC;EAAE;EAAM,MAAM,iBAAiB;GAAE;GAAM;GAAQ;EAAS,CAAC;EAAG,UAAU,OAAO,OAAO,MAAM,CAAC,EAAE,QAAQ;CAAE,CAAC;CAElH,OAAO,CAAC;AACV;;;;;;;;AASA,SAAgB,gBAAgB,MAAoD;CAClF,OAAO,mBAAmB,IAAI,CAAC,CAAC,KAAK,MAAM,wBAAwB,CAAC,CAAC;AACvE;;;;;;;AAQA,SAAgB,iBAAiB,EAC/B,MACA,QACA,YAKkB;CAClB,OAAO,kBAAkB,EACvB,SAAS,OAAO,KAAK,OAAO;EAC1B,MAAM,EAAE;EACR,MAAM,iBAAiB;GAAE;GAAM,OAAO;GAAG;EAAS,CAAC;EACnD,UAAU,CAAC,EAAE;CACf,EAAE,EACJ,CAAC;AACH"}

@@ -1,1 +0,1 @@

{"version":3,"file":"utils-CEepwqmb.cjs","names":["INDENT","narrowSchema","createSchema","resolveRefName","collectLazy","camelCase","createIndexedAccessType","resolveGroupType","createFunctionParameter","createFunctionParameters","createTypeLiteral"],"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","../src/utils/operationParams.ts"],"sourcesContent":["function* chunks<T>(arr: ReadonlyArray<T>, size: number): Generator<Array<T>> {\n for (let i = 0; i < arr.length; i += size) {\n yield arr.slice(i, i + size)\n }\n}\n\nexport type ForBatchesOptions = {\n /**\n * Maximum batch size handed to `process`.\n * Parallel dispatch within a batch is the caller's responsibility\n * (typically via `Promise.all(batch.map(...))`).\n */\n concurrency: number\n /**\n * Called after every batch.\n *\n * Use a cheap, idempotent callback (e.g. one that short-circuits when there\n * is nothing new to do). The helper does not coalesce calls — if you need\n * throttling, do it inside `flush` itself.\n */\n flush?: () => Promise<void>\n}\n\n/**\n * Slices `source` into batches of `concurrency` items and awaits `process` for each batch.\n * Accepts both plain arrays (sync) and `AsyncIterable` (streaming).\n *\n * `process` controls whether items inside a batch run in parallel; this helper only\n * controls batch size and per-batch flushing.\n *\n * @example\n * ```ts\n * // parallel dispatch inside each batch\n * await forBatches(schemas, (batch) => Promise.all(batch.map(process)), { concurrency: 8 })\n *\n * // async iterable with a flush after every batch\n * await forBatches(stream.schemas, (batch) => dispatch(batch), { concurrency: 8, flush })\n * ```\n */\nexport async function forBatches<T>(\n source: ReadonlyArray<T> | AsyncIterable<T>,\n process: (batch: Array<T>) => Promise<unknown>,\n options: ForBatchesOptions,\n): Promise<void> {\n const { concurrency, flush } = options\n\n if (Array.isArray(source)) {\n for (const batch of chunks(source, concurrency)) {\n await process(batch)\n if (flush) await flush()\n }\n return\n }\n\n const batch: Array<T> = []\n for await (const item of source) {\n batch.push(item)\n if (batch.length >= concurrency) {\n await process(batch.splice(0))\n\n if (flush) await flush()\n }\n }\n if (batch.length > 0) {\n await process(batch.splice(0))\n\n if (flush) await flush()\n }\n}\n\n/** 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\n/** Returns `true` when `result` is a rejected `Promise.allSettled` result with a typed `reason`.\n *\n * @example\n * ```ts\n * const results = await Promise.allSettled([p1, p2])\n * results.filter(isPromiseRejectedResult<Error>).map((r) => r.reason.message)\n * ```\n */\nexport function isPromiseRejectedResult<T>(result: PromiseSettledResult<unknown>): result is Omit<PromiseRejectedResult, 'reason'> & { reason: T } {\n return result.status === 'rejected'\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","import { camelCase, isValidVarName, memoize } from '@internals/utils'\nimport { createFunctionParameter, createFunctionParameters, createIndexedAccessType, createTypeLiteral } from '../nodes/function.ts'\nimport type { FunctionParameterNode, FunctionParametersNode, OperationNode, ParameterNode, TypeExpression, TypeLiteralNode } from '../nodes/index.ts'\nimport { resolveGroupType } from './refs.ts'\n\nconst caseParamsMemo = memoize(new WeakMap<Array<ParameterNode>, (casing: string) => Array<ParameterNode>>(), (params) =>\n memoize(new Map<string, Array<ParameterNode>>(), (casing: string) =>\n params.map((param) => {\n const transformed = casing === 'camelcase' || !isValidVarName(param.name) ? camelCase(param.name) : param.name\n return { ...param, name: transformed }\n }),\n ),\n)\n\n/**\n * Applies casing rules to parameter names and returns a new array without mutating the input.\n *\n * Run it before handing parameters to schema builders so output property keys get the right casing\n * while `OperationNode.parameters` stays intact for other consumers. When `casing` is unset, the\n * original array is returned unchanged.\n */\nexport function caseParams(params: Array<ParameterNode>, casing: 'camelcase' | undefined): Array<ParameterNode> {\n if (!casing) return params\n return caseParamsMemo(params)(casing)\n}\n\n/**\n * Named type for a group of parameters (query or header) emitted as a single typed parameter.\n */\nexport type ParamGroupType = {\n /**\n * Type expression for the group, a plain group-name reference.\n */\n type: TypeExpression\n /**\n * Whether the parameter group is optional.\n */\n optional: boolean\n}\n\n/**\n * A single member of a destructured parameter group, fed to `createFunctionParameter({ properties })`.\n */\ntype GroupProperty = {\n name: string\n type: TypeExpression\n optional?: boolean\n}\n\n/**\n * Resolver interface for {@link createOperationParams}.\n *\n * `ResolverTs` from `@kubb/plugin-ts` satisfies this interface and can be passed directly.\n */\nexport type OperationParamsResolver = {\n /**\n * Resolves the type name for an individual parameter.\n *\n * @example Individual path parameter name\n * `resolver.resolveParamName(node, param) // → 'DeletePetPathPetId'`\n */\n resolveParamName(node: OperationNode, param: ParameterNode): string\n /**\n * Resolves the request body type name.\n *\n * @example Request body type name\n * `resolver.resolveDataName(node) // → 'CreatePetData'`\n */\n resolveDataName(node: OperationNode): string\n /**\n * Resolves the grouped path parameters type name.\n * When the return value equals `resolveParamName`, no indexed access is emitted.\n *\n * @example Grouped path params type name\n * `resolver.resolvePathParamsName(node, param) // → 'DeletePetPathParams'`\n */\n resolvePathParamsName(node: OperationNode, param: ParameterNode): string\n /**\n * Resolves the grouped query parameters type name.\n * When the return value equals `resolveParamName`, an inline struct type is emitted instead.\n *\n * @example Grouped query params type name\n * `resolver.resolveQueryParamsName(node, param) // → 'FindPetsByStatusQueryParams'`\n */\n resolveQueryParamsName(node: OperationNode, param: ParameterNode): string\n /**\n * Resolves the grouped header parameters type name.\n * When the return value equals `resolveParamName`, an inline struct type is emitted instead.\n *\n * @example Grouped header params type name\n * `resolver.resolveHeaderParamsName(node, param) // → 'DeletePetHeaderParams'`\n */\n resolveHeaderParamsName(node: OperationNode, param: ParameterNode): string\n}\n\n/**\n * Options for {@link createOperationParams}.\n */\nexport type CreateOperationParamsOptions = {\n /**\n * How all operation parameters are grouped in the function signature.\n * - `'object'` wraps all params into a single destructured object `{ petId, data, params }`\n * - `'inline'` emits each param category as a separate top-level parameter\n */\n paramsType: 'object' | 'inline'\n /**\n * How path parameters are emitted when `paramsType` is `'inline'`.\n * - `'object'` groups them as `{ petId, storeId }: PathParams`\n * - `'inline'` spreads them as individual parameters `petId: string, storeId: string`\n * - `'inlineSpread'` emits a single rest parameter `...pathParams: PathParams`\n */\n pathParamsType: 'object' | 'inline' | 'inlineSpread'\n /**\n * Converts parameter names to camelCase before output.\n */\n paramsCasing?: 'camelcase'\n /**\n * Resolver for parameter and request body type names.\n * Pass `ResolverTs` from `@kubb/plugin-ts` directly.\n * When omitted, falls back to the schema primitive or `'unknown'`.\n */\n resolver?: OperationParamsResolver\n /**\n * Default value for the path parameters binding when `pathParamsType` is `'object'`.\n * Falls back to `'{}'` when all path params are optional.\n */\n pathParamsDefault?: string\n /**\n * Extra parameters appended after the standard operation parameters.\n *\n * @example Plugin-specific trailing parameter\n * ```ts\n * extraParams: [createFunctionParameter({ name: 'options', type: 'Partial<RequestOptions>', default: '{}' })]\n * ```\n */\n extraParams?: Array<FunctionParameterNode>\n /**\n * Override the default parameter names used for body, query, header, and rest-path groups.\n *\n * Useful when targeting languages or frameworks with different naming conventions.\n *\n * @default { data: 'data', params: 'params', headers: 'headers', path: 'pathParams' }\n */\n paramNames?: {\n /**\n * Name for the request body parameter.\n * @default 'data'\n */\n data?: string\n /**\n * Name for the query parameters group parameter.\n * @default 'params'\n */\n params?: string\n /**\n * Name for the header parameters group parameter.\n * @default 'headers'\n */\n headers?: string\n /**\n * Name for the rest path-parameters parameter when `pathParamsType` is `'inlineSpread'`.\n * @default 'pathParams'\n */\n path?: string\n }\n /**\n * Transforms every resolved type name before it lands in a parameter node, for framework-level\n * type wrappers.\n *\n * @example Vue Query, wrap every parameter type with `MaybeRefOrGetter`\n * `typeWrapper: (t) => \\`MaybeRefOrGetter<${t}>\\``\n */\n typeWrapper?: (type: string) => string\n}\n\n/**\n * Resolves the {@link TypeExpression} for an individual parameter.\n *\n * Without a resolver, it falls back to the schema primitive (a plain type-name string). When the\n * parameter belongs to a named group, it emits an {@link IndexedAccessTypeNode} like\n * `GroupParams['petId']`, otherwise the resolved individual name.\n */\nexport function resolveParamType({\n node,\n param,\n resolver,\n}: {\n node: OperationNode\n param: ParameterNode\n resolver: OperationParamsResolver | undefined\n}): TypeExpression {\n if (!resolver) {\n return param.schema.primitive ?? 'unknown'\n }\n\n const individualName = resolver.resolveParamName(node, param)\n\n const groupLocation = param.in === 'path' || param.in === 'query' || param.in === 'header' ? param.in : undefined\n\n const groupResolvers = {\n path: resolver.resolvePathParamsName,\n query: resolver.resolveQueryParamsName,\n header: resolver.resolveHeaderParamsName,\n } as const\n\n const groupName = groupLocation ? groupResolvers[groupLocation].call(resolver, node, param) : undefined\n\n if (groupName && groupName !== individualName) {\n return createIndexedAccessType({ target: groupName, key: param.name })\n }\n\n return individualName\n}\n\n/**\n * Converts an `OperationNode` into function parameters for code generation.\n *\n * Centralizes parameter grouping logic for all plugins. `paramsType` chooses between one\n * destructured object parameter (`object`) and separate top-level parameters (`inline`), while\n * `pathParamsType` controls how path params render in inline mode. Provide a `resolver` for type\n * name resolution and `extraParams` for plugin-specific trailing parameters such as an `options` object.\n */\nexport function createOperationParams(node: OperationNode, options: CreateOperationParamsOptions): FunctionParametersNode {\n const { paramsType, pathParamsType, paramsCasing, resolver, pathParamsDefault, extraParams = [], paramNames, typeWrapper } = options\n\n const dataName = paramNames?.data ?? 'data'\n const paramsName = paramNames?.params ?? 'params'\n const headersName = paramNames?.headers ?? 'headers'\n const pathName = paramNames?.path ?? 'pathParams'\n\n const wrapType = (type: string): string => (typeWrapper ? typeWrapper(type) : type)\n // typeWrapper takes a type-name string, so only plain references are wrapped.\n // TypeLiteral and IndexedAccessType expressions are pre-resolved and pass through unchanged.\n const wrapTypeExpression = (type: TypeExpression): TypeExpression => (typeof type === 'string' ? wrapType(type) : type)\n\n const casedParams = caseParams(node.parameters, paramsCasing)\n const pathParams = casedParams.filter((p) => p.in === 'path')\n const queryParams = casedParams.filter((p) => p.in === 'query')\n const headerParams = casedParams.filter((p) => p.in === 'header')\n\n const toProperty = (param: ParameterNode): GroupProperty => ({\n name: param.name,\n type: wrapTypeExpression(resolveParamType({ node, param, resolver })),\n optional: !param.required,\n })\n const emptyObjectDefault = (props: Array<GroupProperty>): string | undefined => (props.every((p) => p.optional) ? '{}' : undefined)\n\n const bodyType = node.requestBody?.content?.[0]?.schema ? wrapType(resolver?.resolveDataName(node) ?? 'unknown') : undefined\n const bodyProperty: Array<GroupProperty> = bodyType ? [{ name: dataName, type: bodyType, optional: !(node.requestBody?.required ?? false) }] : []\n\n const trailingGroups: Array<BuildGroupArgs> = [\n { name: paramsName, node, params: queryParams, groupType: resolveGroupType({ node, params: queryParams, group: 'query', resolver }), resolver, wrapType },\n {\n name: headersName,\n node,\n params: headerParams,\n groupType: resolveGroupType({ node, params: headerParams, group: 'header', resolver }),\n resolver,\n wrapType,\n },\n ]\n\n const params: Array<FunctionParameterNode> = []\n\n if (paramsType === 'object') {\n const children = [...pathParams.map(toProperty), ...bodyProperty, ...trailingGroups.flatMap(buildGroupProperty)]\n if (children.length) {\n params.push(createFunctionParameter({ properties: children, default: emptyObjectDefault(children) }))\n }\n } else {\n if (pathParamsType === 'inlineSpread' && pathParams.length) {\n const spreadType = resolver?.resolvePathParamsName(node, pathParams[0]!)\n params.push(createFunctionParameter({ name: pathName, type: spreadType ? wrapType(spreadType) : undefined, rest: true }))\n } else if (pathParamsType === 'inline') {\n params.push(...pathParams.map((p) => createFunctionParameter(toProperty(p))))\n } else if (pathParams.length) {\n const pathChildren = pathParams.map(toProperty)\n params.push(createFunctionParameter({ properties: pathChildren, default: pathParamsDefault ?? emptyObjectDefault(pathChildren) }))\n }\n\n params.push(...bodyProperty.map((p) => createFunctionParameter(p)))\n params.push(...trailingGroups.flatMap(buildGroupParam))\n }\n\n params.push(...extraParams)\n\n return createFunctionParameters({ params })\n}\n\n/**\n * Shared arguments for building a query or header parameter group.\n */\nexport type BuildGroupArgs = {\n name: string\n node: OperationNode\n params: Array<ParameterNode>\n groupType: ParamGroupType | null\n resolver: OperationParamsResolver | undefined\n wrapType: (type: string) => string\n}\n\n/**\n * Builds the property descriptor for a query or header group.\n * Returns an empty array when there are no params to emit.\n *\n * A pre-resolved `groupType` emits `name: GroupType`. Otherwise it builds an inline\n * {@link TypeLiteralNode} from the individual params.\n */\nfunction buildGroupProperty({ name, node, params, groupType, resolver, wrapType }: BuildGroupArgs): Array<GroupProperty> {\n if (groupType) {\n const type = typeof groupType.type === 'string' ? wrapType(groupType.type) : groupType.type\n return [{ name, type, optional: groupType.optional }]\n }\n if (params.length) {\n return [{ name, type: buildTypeLiteral({ node, params, resolver }), optional: params.every((p) => !p.required) }]\n }\n return []\n}\n\n/**\n * Builds a single {@link FunctionParameterNode} for a query or header group.\n * Returns an empty array when there are no params to emit.\n *\n * A pre-resolved `groupType` emits `name: GroupType`. Otherwise it builds an inline\n * {@link TypeLiteralNode} from the individual params.\n */\nexport function buildGroupParam(args: BuildGroupArgs): Array<FunctionParameterNode> {\n return buildGroupProperty(args).map((p) => createFunctionParameter(p))\n}\n\n/**\n * Builds a {@link TypeLiteralNode} for an inline anonymous type grouping named fields.\n *\n * Used when query or header parameters have no dedicated group type name.\n * Each language printer renders this appropriately (TypeScript: `{ petId: string; name?: string }`).\n */\nexport function buildTypeLiteral({\n node,\n params,\n resolver,\n}: {\n node: OperationNode\n params: Array<ParameterNode>\n resolver: OperationParamsResolver | undefined\n}): TypeLiteralNode {\n return createTypeLiteral({\n members: params.map((p) => ({\n name: p.name,\n type: resolveParamType({ node, param: p, resolver }),\n optional: !p.required,\n })),\n })\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA6IA,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;;;;;;;AChJA,MAAM,gBAAgB,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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C,EAAE;CACf,EAAE,EACJ,CAAC;AACH"}
{"version":3,"file":"utils-CEepwqmb.cjs","names":["INDENT","narrowSchema","createSchema","resolveRefName","collectLazy","camelCase","createIndexedAccessType","resolveGroupType","createFunctionParameter","createFunctionParameters","createTypeLiteral"],"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","../src/utils/operationParams.ts"],"sourcesContent":["function* chunks<T>(arr: ReadonlyArray<T>, size: number): Generator<Array<T>> {\n for (let i = 0; i < arr.length; i += size) {\n yield arr.slice(i, i + size)\n }\n}\n\nexport type ForBatchesOptions = {\n /**\n * Maximum batch size handed to `process`.\n * Parallel dispatch within a batch is the caller's responsibility\n * (typically via `Promise.all(batch.map(...))`).\n */\n concurrency: number\n /**\n * Called after every batch.\n *\n * Use a cheap, idempotent callback (e.g. one that short-circuits when there\n * is nothing new to do). The helper does not coalesce calls — if you need\n * throttling, do it inside `flush` itself.\n */\n flush?: () => Promise<void>\n}\n\n/**\n * Slices `source` into batches of `concurrency` items and awaits `process` for each batch.\n * Accepts both plain arrays (sync) and `AsyncIterable` (streaming).\n *\n * `process` controls whether items inside a batch run in parallel; this helper only\n * controls batch size and per-batch flushing.\n *\n * @example\n * ```ts\n * // parallel dispatch inside each batch\n * await forBatches(schemas, (batch) => Promise.all(batch.map(process)), { concurrency: 8 })\n *\n * // async iterable with a flush after every batch\n * await forBatches(stream.schemas, (batch) => dispatch(batch), { concurrency: 8, flush })\n * ```\n */\nexport async function forBatches<T>(\n source: ReadonlyArray<T> | AsyncIterable<T>,\n process: (batch: Array<T>) => Promise<unknown>,\n options: ForBatchesOptions,\n): Promise<void> {\n const { concurrency, flush } = options\n\n if (Array.isArray(source)) {\n for (const batch of chunks(source, concurrency)) {\n await process(batch)\n if (flush) await flush()\n }\n return\n }\n\n const batch: Array<T> = []\n for await (const item of source) {\n batch.push(item)\n if (batch.length >= concurrency) {\n await process(batch.splice(0))\n\n if (flush) await flush()\n }\n }\n if (batch.length > 0) {\n await process(batch.splice(0))\n\n if (flush) await flush()\n }\n}\n\n/** 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","import { camelCase, isValidVarName, memoize } from '@internals/utils'\nimport { createFunctionParameter, createFunctionParameters, createIndexedAccessType, createTypeLiteral } from '../nodes/function.ts'\nimport type { FunctionParameterNode, FunctionParametersNode, OperationNode, ParameterNode, TypeExpression, TypeLiteralNode } from '../nodes/index.ts'\nimport { resolveGroupType } from './refs.ts'\n\nconst caseParamsMemo = memoize(new WeakMap<Array<ParameterNode>, (casing: string) => Array<ParameterNode>>(), (params) =>\n memoize(new Map<string, Array<ParameterNode>>(), (casing: string) =>\n params.map((param) => {\n const transformed = casing === 'camelcase' || !isValidVarName(param.name) ? camelCase(param.name) : param.name\n return { ...param, name: transformed }\n }),\n ),\n)\n\n/**\n * Applies casing rules to parameter names and returns a new array without mutating the input.\n *\n * Run it before handing parameters to schema builders so output property keys get the right casing\n * while `OperationNode.parameters` stays intact for other consumers. When `casing` is unset, the\n * original array is returned unchanged.\n */\nexport function caseParams(params: Array<ParameterNode>, casing: 'camelcase' | undefined): Array<ParameterNode> {\n if (!casing) return params\n return caseParamsMemo(params)(casing)\n}\n\n/**\n * Named type for a group of parameters (query or header) emitted as a single typed parameter.\n */\nexport type ParamGroupType = {\n /**\n * Type expression for the group, a plain group-name reference.\n */\n type: TypeExpression\n /**\n * Whether the parameter group is optional.\n */\n optional: boolean\n}\n\n/**\n * A single member of a destructured parameter group, fed to `createFunctionParameter({ properties })`.\n */\ntype GroupProperty = {\n name: string\n type: TypeExpression\n optional?: boolean\n}\n\n/**\n * Resolver interface for {@link createOperationParams}.\n *\n * `ResolverTs` from `@kubb/plugin-ts` satisfies this interface and can be passed directly.\n */\nexport type OperationParamsResolver = {\n /**\n * Resolves the type name for an individual parameter.\n *\n * @example Individual path parameter name\n * `resolver.resolveParamName(node, param) // → 'DeletePetPathPetId'`\n */\n resolveParamName(node: OperationNode, param: ParameterNode): string\n /**\n * Resolves the request body type name.\n *\n * @example Request body type name\n * `resolver.resolveDataName(node) // → 'CreatePetData'`\n */\n resolveDataName(node: OperationNode): string\n /**\n * Resolves the grouped path parameters type name.\n * When the return value equals `resolveParamName`, no indexed access is emitted.\n *\n * @example Grouped path params type name\n * `resolver.resolvePathParamsName(node, param) // → 'DeletePetPathParams'`\n */\n resolvePathParamsName(node: OperationNode, param: ParameterNode): string\n /**\n * Resolves the grouped query parameters type name.\n * When the return value equals `resolveParamName`, an inline struct type is emitted instead.\n *\n * @example Grouped query params type name\n * `resolver.resolveQueryParamsName(node, param) // → 'FindPetsByStatusQueryParams'`\n */\n resolveQueryParamsName(node: OperationNode, param: ParameterNode): string\n /**\n * Resolves the grouped header parameters type name.\n * When the return value equals `resolveParamName`, an inline struct type is emitted instead.\n *\n * @example Grouped header params type name\n * `resolver.resolveHeaderParamsName(node, param) // → 'DeletePetHeaderParams'`\n */\n resolveHeaderParamsName(node: OperationNode, param: ParameterNode): string\n}\n\n/**\n * Options for {@link createOperationParams}.\n */\nexport type CreateOperationParamsOptions = {\n /**\n * How all operation parameters are grouped in the function signature.\n * - `'object'` wraps all params into a single destructured object `{ petId, data, params }`\n * - `'inline'` emits each param category as a separate top-level parameter\n */\n paramsType: 'object' | 'inline'\n /**\n * How path parameters are emitted when `paramsType` is `'inline'`.\n * - `'object'` groups them as `{ petId, storeId }: PathParams`\n * - `'inline'` spreads them as individual parameters `petId: string, storeId: string`\n * - `'inlineSpread'` emits a single rest parameter `...pathParams: PathParams`\n */\n pathParamsType: 'object' | 'inline' | 'inlineSpread'\n /**\n * Converts parameter names to camelCase before output.\n */\n paramsCasing?: 'camelcase'\n /**\n * Resolver for parameter and request body type names.\n * Pass `ResolverTs` from `@kubb/plugin-ts` directly.\n * When omitted, falls back to the schema primitive or `'unknown'`.\n */\n resolver?: OperationParamsResolver\n /**\n * Default value for the path parameters binding when `pathParamsType` is `'object'`.\n * Falls back to `'{}'` when all path params are optional.\n */\n pathParamsDefault?: string\n /**\n * Extra parameters appended after the standard operation parameters.\n *\n * @example Plugin-specific trailing parameter\n * ```ts\n * extraParams: [createFunctionParameter({ name: 'options', type: 'Partial<RequestOptions>', default: '{}' })]\n * ```\n */\n extraParams?: Array<FunctionParameterNode>\n /**\n * Override the default parameter names used for body, query, header, and rest-path groups.\n *\n * Useful when targeting languages or frameworks with different naming conventions.\n *\n * @default { data: 'data', params: 'params', headers: 'headers', path: 'pathParams' }\n */\n paramNames?: {\n /**\n * Name for the request body parameter.\n * @default 'data'\n */\n data?: string\n /**\n * Name for the query parameters group parameter.\n * @default 'params'\n */\n params?: string\n /**\n * Name for the header parameters group parameter.\n * @default 'headers'\n */\n headers?: string\n /**\n * Name for the rest path-parameters parameter when `pathParamsType` is `'inlineSpread'`.\n * @default 'pathParams'\n */\n path?: string\n }\n /**\n * Transforms every resolved type name before it lands in a parameter node, for framework-level\n * type wrappers.\n *\n * @example Vue Query, wrap every parameter type with `MaybeRefOrGetter`\n * `typeWrapper: (t) => \\`MaybeRefOrGetter<${t}>\\``\n */\n typeWrapper?: (type: string) => string\n}\n\n/**\n * Resolves the {@link TypeExpression} for an individual parameter.\n *\n * Without a resolver, it falls back to the schema primitive (a plain type-name string). When the\n * parameter belongs to a named group, it emits an {@link IndexedAccessTypeNode} like\n * `GroupParams['petId']`, otherwise the resolved individual name.\n */\nexport function resolveParamType({\n node,\n param,\n resolver,\n}: {\n node: OperationNode\n param: ParameterNode\n resolver: OperationParamsResolver | undefined\n}): TypeExpression {\n if (!resolver) {\n return param.schema.primitive ?? 'unknown'\n }\n\n const individualName = resolver.resolveParamName(node, param)\n\n const groupLocation = param.in === 'path' || param.in === 'query' || param.in === 'header' ? param.in : undefined\n\n const groupResolvers = {\n path: resolver.resolvePathParamsName,\n query: resolver.resolveQueryParamsName,\n header: resolver.resolveHeaderParamsName,\n } as const\n\n const groupName = groupLocation ? groupResolvers[groupLocation].call(resolver, node, param) : undefined\n\n if (groupName && groupName !== individualName) {\n return createIndexedAccessType({ target: groupName, key: param.name })\n }\n\n return individualName\n}\n\n/**\n * Converts an `OperationNode` into function parameters for code generation.\n *\n * Centralizes parameter grouping logic for all plugins. `paramsType` chooses between one\n * destructured object parameter (`object`) and separate top-level parameters (`inline`), while\n * `pathParamsType` controls how path params render in inline mode. Provide a `resolver` for type\n * name resolution and `extraParams` for plugin-specific trailing parameters such as an `options` object.\n */\nexport function createOperationParams(node: OperationNode, options: CreateOperationParamsOptions): FunctionParametersNode {\n const { paramsType, pathParamsType, paramsCasing, resolver, pathParamsDefault, extraParams = [], paramNames, typeWrapper } = options\n\n const dataName = paramNames?.data ?? 'data'\n const paramsName = paramNames?.params ?? 'params'\n const headersName = paramNames?.headers ?? 'headers'\n const pathName = paramNames?.path ?? 'pathParams'\n\n const wrapType = (type: string): string => (typeWrapper ? typeWrapper(type) : type)\n // typeWrapper takes a type-name string, so only plain references are wrapped.\n // TypeLiteral and IndexedAccessType expressions are pre-resolved and pass through unchanged.\n const wrapTypeExpression = (type: TypeExpression): TypeExpression => (typeof type === 'string' ? wrapType(type) : type)\n\n const casedParams = caseParams(node.parameters, paramsCasing)\n const pathParams = casedParams.filter((p) => p.in === 'path')\n const queryParams = casedParams.filter((p) => p.in === 'query')\n const headerParams = casedParams.filter((p) => p.in === 'header')\n\n const toProperty = (param: ParameterNode): GroupProperty => ({\n name: param.name,\n type: wrapTypeExpression(resolveParamType({ node, param, resolver })),\n optional: !param.required,\n })\n const emptyObjectDefault = (props: Array<GroupProperty>): string | undefined => (props.every((p) => p.optional) ? '{}' : undefined)\n\n const bodyType = node.requestBody?.content?.[0]?.schema ? wrapType(resolver?.resolveDataName(node) ?? 'unknown') : undefined\n const bodyProperty: Array<GroupProperty> = bodyType ? [{ name: dataName, type: bodyType, optional: !(node.requestBody?.required ?? false) }] : []\n\n const trailingGroups: Array<BuildGroupArgs> = [\n { name: paramsName, node, params: queryParams, groupType: resolveGroupType({ node, params: queryParams, group: 'query', resolver }), resolver, wrapType },\n {\n name: headersName,\n node,\n params: headerParams,\n groupType: resolveGroupType({ node, params: headerParams, group: 'header', resolver }),\n resolver,\n wrapType,\n },\n ]\n\n const params: Array<FunctionParameterNode> = []\n\n if (paramsType === 'object') {\n const children = [...pathParams.map(toProperty), ...bodyProperty, ...trailingGroups.flatMap(buildGroupProperty)]\n if (children.length) {\n params.push(createFunctionParameter({ properties: children, default: emptyObjectDefault(children) }))\n }\n } else {\n if (pathParamsType === 'inlineSpread' && pathParams.length) {\n const spreadType = resolver?.resolvePathParamsName(node, pathParams[0]!)\n params.push(createFunctionParameter({ name: pathName, type: spreadType ? wrapType(spreadType) : undefined, rest: true }))\n } else if (pathParamsType === 'inline') {\n params.push(...pathParams.map((p) => createFunctionParameter(toProperty(p))))\n } else if (pathParams.length) {\n const pathChildren = pathParams.map(toProperty)\n params.push(createFunctionParameter({ properties: pathChildren, default: pathParamsDefault ?? emptyObjectDefault(pathChildren) }))\n }\n\n params.push(...bodyProperty.map((p) => createFunctionParameter(p)))\n params.push(...trailingGroups.flatMap(buildGroupParam))\n }\n\n params.push(...extraParams)\n\n return createFunctionParameters({ params })\n}\n\n/**\n * Shared arguments for building a query or header parameter group.\n */\nexport type BuildGroupArgs = {\n name: string\n node: OperationNode\n params: Array<ParameterNode>\n groupType: ParamGroupType | null\n resolver: OperationParamsResolver | undefined\n wrapType: (type: string) => string\n}\n\n/**\n * Builds the property descriptor for a query or header group.\n * Returns an empty array when there are no params to emit.\n *\n * A pre-resolved `groupType` emits `name: GroupType`. Otherwise it builds an inline\n * {@link TypeLiteralNode} from the individual params.\n */\nfunction buildGroupProperty({ name, node, params, groupType, resolver, wrapType }: BuildGroupArgs): Array<GroupProperty> {\n if (groupType) {\n const type = typeof groupType.type === 'string' ? wrapType(groupType.type) : groupType.type\n return [{ name, type, optional: groupType.optional }]\n }\n if (params.length) {\n return [{ name, type: buildTypeLiteral({ node, params, resolver }), optional: params.every((p) => !p.required) }]\n }\n return []\n}\n\n/**\n * Builds a single {@link FunctionParameterNode} for a query or header group.\n * Returns an empty array when there are no params to emit.\n *\n * A pre-resolved `groupType` emits `name: GroupType`. Otherwise it builds an inline\n * {@link TypeLiteralNode} from the individual params.\n */\nexport function buildGroupParam(args: BuildGroupArgs): Array<FunctionParameterNode> {\n return buildGroupProperty(args).map((p) => createFunctionParameter(p))\n}\n\n/**\n * Builds a {@link TypeLiteralNode} for an inline anonymous type grouping named fields.\n *\n * Used when query or header parameters have no dedicated group type name.\n * Each language printer renders this appropriately (TypeScript: `{ petId: string; name?: string }`).\n */\nexport function buildTypeLiteral({\n node,\n params,\n resolver,\n}: {\n node: OperationNode\n params: Array<ParameterNode>\n resolver: OperationParamsResolver | undefined\n}): TypeLiteralNode {\n return createTypeLiteral({\n members: params.map((p) => ({\n name: p.name,\n type: resolveParamType({ node, param: p, resolver }),\n optional: !p.required,\n })),\n })\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;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C;EAAG,UAAU,OAAO,OAAO,MAAM,CAAC,EAAE,QAAQ;CAAE,CAAC;CAElH,OAAO,CAAC;AACV;;;;;;;;AASA,SAAgB,gBAAgB,MAAoD;CAClF,OAAO,mBAAmB,IAAI,CAAC,CAAC,KAAK,MAAMD,eAAAA,wBAAwB,CAAC,CAAC;AACvE;;;;;;;AAQA,SAAgB,iBAAiB,EAC/B,MACA,QACA,YAKkB;CAClB,OAAOE,eAAAA,kBAAkB,EACvB,SAAS,OAAO,KAAK,OAAO;EAC1B,MAAM,EAAE;EACR,MAAM,iBAAiB;GAAE;GAAM,OAAO;GAAG;EAAS,CAAC;EACnD,UAAU,CAAC,EAAE;CACf,EAAE,EACJ,CAAC;AACH"}
import { n as __name } from "./rolldown-runtime-CNktS9qV.js";
import { C as ParameterNode, Et as PropertyNode, Pt as CodeNode, St as UnionSchemaNode, _t as SchemaNode, f as OperationNode, ft as ObjectSchemaNode, ot as ArraySchemaNode, ut as IntersectionSchemaNode } from "./index-BKD4drsX.js";
import { a as buildTypeLiteral, c as resolveParamType, i as buildGroupParam, n as OperationParamsResolver, o as caseParams, r as ParamGroupType, s as createOperationParams, t as BuildGroupArgs } from "./operationParams-ByVfpYr7.js";
import { C as ParameterNode, Et as PropertyNode, Pt as CodeNode, St as UnionSchemaNode, _t as SchemaNode, f as OperationNode, ft as ObjectSchemaNode, ot as ArraySchemaNode, ut as IntersectionSchemaNode } from "./index-CeJAFegf.js";
import { a as buildTypeLiteral, c as resolveParamType, i as buildGroupParam, n as OperationParamsResolver, o as caseParams, r as ParamGroupType, s as createOperationParams, t as BuildGroupArgs } from "./operationParams-DCY3q4C7.js";

@@ -5,0 +5,0 @@ //#region ../../internals/utils/src/reserved.d.ts

{
"name": "@kubb/ast",
"version": "5.0.0-beta.64",
"version": "5.0.0-beta.65",
"description": "Spec-agnostic AST layer for Kubb. Defines the node tree, visitor pattern, factory functions, and type guards used across all code generation plugins.",

@@ -5,0 +5,0 @@ "keywords": [

import { n as __name } from "./rolldown-runtime-CNktS9qV.js";
import { C as ParameterNode, Et as PropertyNode, _t as SchemaNode, f as OperationNode, h as ResponseNode, n as OutputNode, o as InputNode, rt as ContentNode, t as Node, y as RequestBodyNode } from "./index-BKD4drsX.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-B7qm3zTd.d.ts.map
import { n as __name, t as __exportAll } from "./rolldown-runtime-CNktS9qV.js";
import { F as createFunctionParameters, Gt as createBreak, I as createIndexedAccessType, J as UserFileNode, Jt as createJsx, Kt as createConst, L as createObjectBindingPattern, Ot as createProperty, P as createFunctionParameter, Q as createSource, R as createTypeLiteral, Wt as createArrowFunction, X as createFile, Xt as createType, Y as createExport, Yt as createText, Z as createImport, _ as createResponse, at as createContent, b as createRequestBody, p as createOperation, qt as createFunction, r as createOutput, s as createInput, t as Node, w as createParameter, wt as createSchema } from "./index-BKD4drsX.js";
//#region src/factory.d.ts
declare namespace factory_d_exports {
export { UserFileNode, createArrowFunction, createBreak, createConst, createContent, createExport, createFile, createFunction, createFunctionParameter, createFunctionParameters, createImport, createIndexedAccessType, createInput, createJsx, createObjectBindingPattern, createOperation, createOutput, createParameter, createProperty, createRequestBody, createResponse, createSchema, createSource, createText, createType, createTypeLiteral, update };
}
/**
* Identity-preserving node update: returns `node` unchanged when every field in
* `changes` already equals (by reference) the current value, otherwise a new node
* with the changes applied.
*
* Mirrors the TypeScript compiler's `factory.updateX` contract. Pair it with the
* structural sharing in {@link transform} so a no-op rewrite does not allocate and
* downstream passes can detect "nothing changed" by identity. Comparison is shallow,
* so a structurally equal but newly allocated array or object counts as a change.
*
* @example
* ```ts
* update(node, { name: node.name }) // -> same `node` reference
* update(node, { name: 'renamed' }) // -> new node, `name` replaced
* ```
*/
declare function update<T extends Node>(node: T, changes: Partial<T>): T;
//#endregion
export { update as n, factory_d_exports as t };
//# sourceMappingURL=factory-wJLzHeXT.d.ts.map

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

import { n as __name } from "./rolldown-runtime-CNktS9qV.js";
import { C as ParameterNode, M as TypeExpression, N as TypeLiteralNode, O as FunctionParameterNode, f as OperationNode, k as FunctionParametersNode } from "./index-BKD4drsX.js";
//#region src/utils/operationParams.d.ts
/**
* Applies casing rules to parameter names and returns a new array without mutating the input.
*
* Run it before handing parameters to schema builders so output property keys get the right casing
* while `OperationNode.parameters` stays intact for other consumers. When `casing` is unset, the
* original array is returned unchanged.
*/
declare function caseParams(params: Array<ParameterNode>, casing: 'camelcase' | undefined): Array<ParameterNode>;
/**
* Named type for a group of parameters (query or header) emitted as a single typed parameter.
*/
type ParamGroupType = {
/**
* Type expression for the group, a plain group-name reference.
*/
type: TypeExpression;
/**
* Whether the parameter group is optional.
*/
optional: boolean;
};
/**
* Resolver interface for {@link createOperationParams}.
*
* `ResolverTs` from `@kubb/plugin-ts` satisfies this interface and can be passed directly.
*/
type OperationParamsResolver = {
/**
* Resolves the type name for an individual parameter.
*
* @example Individual path parameter name
* `resolver.resolveParamName(node, param) // → 'DeletePetPathPetId'`
*/
resolveParamName(node: OperationNode, param: ParameterNode): string;
/**
* Resolves the request body type name.
*
* @example Request body type name
* `resolver.resolveDataName(node) // → 'CreatePetData'`
*/
resolveDataName(node: OperationNode): string;
/**
* Resolves the grouped path parameters type name.
* When the return value equals `resolveParamName`, no indexed access is emitted.
*
* @example Grouped path params type name
* `resolver.resolvePathParamsName(node, param) // → 'DeletePetPathParams'`
*/
resolvePathParamsName(node: OperationNode, param: ParameterNode): string;
/**
* Resolves the grouped query parameters type name.
* When the return value equals `resolveParamName`, an inline struct type is emitted instead.
*
* @example Grouped query params type name
* `resolver.resolveQueryParamsName(node, param) // → 'FindPetsByStatusQueryParams'`
*/
resolveQueryParamsName(node: OperationNode, param: ParameterNode): string;
/**
* Resolves the grouped header parameters type name.
* When the return value equals `resolveParamName`, an inline struct type is emitted instead.
*
* @example Grouped header params type name
* `resolver.resolveHeaderParamsName(node, param) // → 'DeletePetHeaderParams'`
*/
resolveHeaderParamsName(node: OperationNode, param: ParameterNode): string;
};
/**
* Options for {@link createOperationParams}.
*/
type CreateOperationParamsOptions = {
/**
* How all operation parameters are grouped in the function signature.
* - `'object'` wraps all params into a single destructured object `{ petId, data, params }`
* - `'inline'` emits each param category as a separate top-level parameter
*/
paramsType: 'object' | 'inline';
/**
* How path parameters are emitted when `paramsType` is `'inline'`.
* - `'object'` groups them as `{ petId, storeId }: PathParams`
* - `'inline'` spreads them as individual parameters `petId: string, storeId: string`
* - `'inlineSpread'` emits a single rest parameter `...pathParams: PathParams`
*/
pathParamsType: 'object' | 'inline' | 'inlineSpread';
/**
* Converts parameter names to camelCase before output.
*/
paramsCasing?: 'camelcase';
/**
* Resolver for parameter and request body type names.
* Pass `ResolverTs` from `@kubb/plugin-ts` directly.
* When omitted, falls back to the schema primitive or `'unknown'`.
*/
resolver?: OperationParamsResolver;
/**
* Default value for the path parameters binding when `pathParamsType` is `'object'`.
* Falls back to `'{}'` when all path params are optional.
*/
pathParamsDefault?: string;
/**
* Extra parameters appended after the standard operation parameters.
*
* @example Plugin-specific trailing parameter
* ```ts
* extraParams: [createFunctionParameter({ name: 'options', type: 'Partial<RequestOptions>', default: '{}' })]
* ```
*/
extraParams?: Array<FunctionParameterNode>;
/**
* Override the default parameter names used for body, query, header, and rest-path groups.
*
* Useful when targeting languages or frameworks with different naming conventions.
*
* @default { data: 'data', params: 'params', headers: 'headers', path: 'pathParams' }
*/
paramNames?: {
/**
* Name for the request body parameter.
* @default 'data'
*/
data?: string;
/**
* Name for the query parameters group parameter.
* @default 'params'
*/
params?: string;
/**
* Name for the header parameters group parameter.
* @default 'headers'
*/
headers?: string;
/**
* Name for the rest path-parameters parameter when `pathParamsType` is `'inlineSpread'`.
* @default 'pathParams'
*/
path?: string;
};
/**
* Transforms every resolved type name before it lands in a parameter node, for framework-level
* type wrappers.
*
* @example Vue Query, wrap every parameter type with `MaybeRefOrGetter`
* `typeWrapper: (t) => \`MaybeRefOrGetter<${t}>\``
*/
typeWrapper?: (type: string) => string;
};
/**
* Resolves the {@link TypeExpression} for an individual parameter.
*
* Without a resolver, it falls back to the schema primitive (a plain type-name string). When the
* parameter belongs to a named group, it emits an {@link IndexedAccessTypeNode} like
* `GroupParams['petId']`, otherwise the resolved individual name.
*/
declare function resolveParamType({
node,
param,
resolver
}: {
node: OperationNode;
param: ParameterNode;
resolver: OperationParamsResolver | undefined;
}): TypeExpression;
/**
* Converts an `OperationNode` into function parameters for code generation.
*
* Centralizes parameter grouping logic for all plugins. `paramsType` chooses between one
* destructured object parameter (`object`) and separate top-level parameters (`inline`), while
* `pathParamsType` controls how path params render in inline mode. Provide a `resolver` for type
* name resolution and `extraParams` for plugin-specific trailing parameters such as an `options` object.
*/
declare function createOperationParams(node: OperationNode, options: CreateOperationParamsOptions): FunctionParametersNode;
/**
* Shared arguments for building a query or header parameter group.
*/
type BuildGroupArgs = {
name: string;
node: OperationNode;
params: Array<ParameterNode>;
groupType: ParamGroupType | null;
resolver: OperationParamsResolver | undefined;
wrapType: (type: string) => string;
};
/**
* Builds a single {@link FunctionParameterNode} for a query or header group.
* Returns an empty array when there are no params to emit.
*
* A pre-resolved `groupType` emits `name: GroupType`. Otherwise it builds an inline
* {@link TypeLiteralNode} from the individual params.
*/
declare function buildGroupParam(args: BuildGroupArgs): Array<FunctionParameterNode>;
/**
* Builds a {@link TypeLiteralNode} for an inline anonymous type grouping named fields.
*
* Used when query or header parameters have no dedicated group type name.
* Each language printer renders this appropriately (TypeScript: `{ petId: string; name?: string }`).
*/
declare function buildTypeLiteral({
node,
params,
resolver
}: {
node: OperationNode;
params: Array<ParameterNode>;
resolver: OperationParamsResolver | undefined;
}): TypeLiteralNode;
//#endregion
export { buildTypeLiteral as a, resolveParamType as c, buildGroupParam as i, OperationParamsResolver as n, caseParams as o, ParamGroupType as r, createOperationParams as s, BuildGroupArgs as t };
//# sourceMappingURL=operationParams-ByVfpYr7.d.ts.map
import { n as __name } from "./rolldown-runtime-CNktS9qV.js";
import { _t as SchemaNode, t as Node, vt as SchemaNodeByType, yt as SchemaType } from "./index-BKD4drsX.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 JSON Schema, so this is the one seam where
* OpenAPI, AsyncAPI, and plain JSON Schema 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;
};
/**
* How a dialect collapses structurally identical schemas into shared definitions. The contract is
* generic over the plan and context types, which the adapter supplies. The mechanics live in the
* adapter, not here, so `@kubb/ast` carries no dedupe logic. The returned plan owns the rewriting
* behavior, so callers interact with one object.
*/
type Dedupe<TPlan = unknown, TContext = unknown> = {
/**
* Scans a forest of nodes and produces a plan describing which shapes to share.
*/
plan(roots: ReadonlyArray<Node>, context: TContext): TPlan;
};
/**
* A spec adapter's dialect. `name` identifies it in logs and diagnostics, `schema` holds the
* spec-specific schema questions the parser answers, and `dedupe` is the schema-sharing seam.
*/
type DefineDialect<TSchema = unknown, TRef = TSchema, TDiscriminated = TSchema, TDocument = unknown, TDedupe extends Dedupe = Dedupe> = {
/**
* Identifies the dialect in logs and diagnostics.
*/
name: string;
/**
* The spec-specific schema behavior. See {@link SchemaDialect}.
*/
schema: SchemaDialect<TSchema, TRef, TDiscriminated, TDocument>;
/**
* The schema-sharing behavior. See {@link Dedupe}.
*/
dedupe: TDedupe;
};
/**
* Types a {@link DefineDialect} 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,
* },
* dedupe: { plan },
* })
* ```
*/
declare function defineDialect<TSchema, TRef, TDiscriminated, TDocument, TDedupe extends Dedupe>(dialect: DefineDialect<TSchema, TRef, TDiscriminated, TDocument, TDedupe>): DefineDialect<TSchema, TRef, TDiscriminated, TDocument, TDedupe>;
//#endregion
//#region src/definePrinter.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;
/**
* 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> }>;
/**
* 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;
};
/**
* Defines 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.
* - `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 { definePrinter, type PrinterFactoryOptions } from '@kubb/ast'
*
* type PrinterZod = PrinterFactoryOptions<'zod', { strict?: boolean }, string>
*
* export const zodPrinter = definePrinter<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 definePrinter<T extends PrinterFactoryOptions = PrinterFactoryOptions>(build: PrinterBuilder<T>): (options?: T['options']) => Printer<T>;
/**
* Generic printer factory behind `definePrinter`. Pass a `getKey` function that maps a node to its
* handler key, and it returns a `definePrinter`-style helper for that node and key type. `definePrinter`
* itself is this factory keyed by `node.type`.
*
* @example Key a printer by `node.kind` instead of `node.type`
* ```ts
* const defineFunctionPrinter = createPrinterFactory<FunctionParamNode, FunctionParamKind, Partial<Record<FunctionParamKind, FunctionParamNode>>>(
* (node) => node.kind,
* )
* ```
*/
declare function createPrinterFactory<TNode, TKey extends string, TNodeByKey extends Partial<Record<TKey, TNode>>>(getKey: (node: TNode) => TKey | null): <T extends PrinterFactoryOptions>(build: (options: T["options"]) => {
name: T["name"];
options: T["options"];
nodes: Partial<{ [K in TKey]: (this: {
transform: (node: TNode) => T["output"] | null;
options: T["options"];
}, node: TNodeByKey[K]) => T["output"] | null }>;
print?: (this: {
transform: (node: TNode) => T["output"] | null;
options: T["options"];
}, node: TNode) => T["printOutput"] | null;
}) => (options?: T["options"]) => {
name: T["name"];
options: T["options"];
transform: (node: TNode) => T["output"] | null;
print: (node: TNode) => T["printOutput"] | null;
};
//#endregion
export { definePrinter as a, SchemaDialect as c, createPrinterFactory as i, defineDialect as l, PrinterFactoryOptions as n, Dedupe as o, PrinterPartial as r, DefineDialect as s, Printer as t };
//# sourceMappingURL=types-BP9BZoq-.d.ts.map

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

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