@kubb/ast 5.23.1 → 5.23.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,5 +1,5 @@
1
1
  import { t as Node } from "./index-BwnMIoLl.js";
2
- import { r as VisitorDepth, t as Visitor } from "./visitor-BZozlXBF.js";
2
+ import { i as VisitorKey, n as VisitorContext, r as VisitorDepth, t as Visitor } from "./visitor-1TSWTMe1.js";
3
3
  /**
4
4
  * Ordering hint shared by macros and plugins. `pre` runs before unmarked items, `post` after,
5
5
  * and `undefined` keeps declaration order.
@@ -13,13 +13,18 @@ type Enforce = 'pre' | 'post';
13
13
  * `plugins.sort((a, b) => compareMacroOrder(a.enforce, b.enforce))`
14
14
  */
15
15
  declare function compareMacroOrder(a?: Enforce, b?: Enforce): number;
16
+ /**
17
+ * The {@link Visitor} callbacks with `this` typed as the {@link VisitorContext}. A macro callback gets
18
+ * the context both as `this` and as its second argument.
19
+ */
20
+ type MacroCallbacks = { [K in VisitorKey]?: (this: VisitorContext, ...args: Parameters<NonNullable<Visitor[K]>>) => ReturnType<NonNullable<Visitor[K]>>; };
16
21
  /**
17
22
  * A named, composable transform over the Kubb AST. It carries the same per-kind callbacks as a
18
23
  * {@link Visitor} (`schema`, `operation`, …), plus a `name`, an optional `enforce` order, and an
19
24
  * optional `match` predicate. Macros run on the shared AST, so the same macro works across every
20
25
  * adapter and output target. Exports follow the `macro<Name>` convention, mirroring plugins (`pluginTs`).
21
26
  */
22
- type Macro = Visitor & {
27
+ type Macro = MacroCallbacks & {
23
28
  /**
24
29
  * Macro identifier used to tell macros apart, for example `'dedupe-union'`.
25
30
  */
@@ -1,6 +1,6 @@
1
1
  import { i as nodeKinds } from "./base-IpYuh3ZP.cjs";
2
2
  import { f as CodeNode } from "./file-BVqSiSvV.cjs";
3
- import { i as collect, o as transform } from "./visitor-Bw_opzjF.cjs";
3
+ import { a as collect, s as transform } from "./visitor-CUbaaX8R.cjs";
4
4
  /**
5
5
  * Extracts all string content from a `CodeNode` tree recursively.
6
6
  * Collects the text fields and nested node content, to build the source string for import filtering.
@@ -1,6 +1,6 @@
1
1
  import { i as nodeKinds } from "./base-IpYuh3ZP.js";
2
2
  import { f as CodeNode } from "./file-xJnBQPGq.js";
3
- import { i as collect, o as transform } from "./visitor-BZozlXBF.js";
3
+ import { a as collect, s as transform } from "./visitor-1TSWTMe1.js";
4
4
  /**
5
5
  * Extracts all string content from a `CodeNode` tree recursively.
6
6
  * Collects the text fields and nested node content, to build the source string for import filtering.
@@ -1,5 +1,5 @@
1
1
  import { t as Node } from "./index-DSVef1pp.cjs";
2
- import { r as VisitorDepth, t as Visitor } from "./visitor-Bw_opzjF.cjs";
2
+ import { i as VisitorKey, n as VisitorContext, r as VisitorDepth, t as Visitor } from "./visitor-CUbaaX8R.cjs";
3
3
  /**
4
4
  * Ordering hint shared by macros and plugins. `pre` runs before unmarked items, `post` after,
5
5
  * and `undefined` keeps declaration order.
@@ -13,13 +13,18 @@ type Enforce = 'pre' | 'post';
13
13
  * `plugins.sort((a, b) => compareMacroOrder(a.enforce, b.enforce))`
14
14
  */
15
15
  declare function compareMacroOrder(a?: Enforce, b?: Enforce): number;
16
+ /**
17
+ * The {@link Visitor} callbacks with `this` typed as the {@link VisitorContext}. A macro callback gets
18
+ * the context both as `this` and as its second argument.
19
+ */
20
+ type MacroCallbacks = { [K in VisitorKey]?: (this: VisitorContext, ...args: Parameters<NonNullable<Visitor[K]>>) => ReturnType<NonNullable<Visitor[K]>>; };
16
21
  /**
17
22
  * A named, composable transform over the Kubb AST. It carries the same per-kind callbacks as a
18
23
  * {@link Visitor} (`schema`, `operation`, …), plus a `name`, an optional `enforce` order, and an
19
24
  * optional `match` predicate. Macros run on the shared AST, so the same macro works across every
20
25
  * adapter and output target. Exports follow the `macro<Name>` convention, mirroring plugins (`pluginTs`).
21
26
  */
22
- type Macro = Visitor & {
27
+ type Macro = MacroCallbacks & {
23
28
  /**
24
29
  * Macro identifier used to tell macros apart, for example `'dedupe-union'`.
25
30
  */
@@ -1,7 +1,7 @@
1
1
  import { G as StringSchemaNode, H as SchemaNode, X as PropertyNode } from "./operation-X7chCdL2.cjs";
2
2
  import { a as schemaTypes } from "./base-IpYuh3ZP.cjs";
3
3
  import { n as narrowSchema } from "./guards-B8qDgSaT.cjs";
4
- import { a as findSchema } from "./visitor-Bw_opzjF.cjs";
4
+ import { o as findSchema } from "./visitor-CUbaaX8R.cjs";
5
5
  /**
6
6
  * Generic JSON Schema optionality: a non-required field is optional, and a
7
7
  * non-required nullable field is nullish.
@@ -1,7 +1,7 @@
1
1
  import { G as StringSchemaNode, H as SchemaNode, X as PropertyNode } from "./operation-BgRyVS7z.js";
2
2
  import { a as schemaTypes } from "./base-IpYuh3ZP.js";
3
3
  import { n as narrowSchema } from "./guards-D-h9R_sV.js";
4
- import { a as findSchema } from "./visitor-BZozlXBF.js";
4
+ import { o as findSchema } from "./visitor-1TSWTMe1.js";
5
5
  /**
6
6
  * Generic JSON Schema optionality: a non-required field is optional, and a
7
7
  * non-required nullable field is nullish.
package/dist/index.cjs CHANGED
@@ -7,7 +7,7 @@ const require_ref = require("./ref-P0ZLT1Bg.cjs");
7
7
  const require_schema = require("./schema-BIErWqgc.cjs");
8
8
  const require_guards = require("./guards-COVJE6TU.cjs");
9
9
  const require_refs = require("./refs-CYHpRlQo.cjs");
10
- const require_macro = require("./macro-DrTBT7fh.cjs");
10
+ const require_macro = require("./macro-V_cNODx2.cjs");
11
11
  const require_optionality = require("./optionality-D-zqzVMH.cjs");
12
12
  const require_node = require("./node-DjcETnc8.cjs");
13
13
  const require_file = require("./file-Dd50jPkH.cjs");
@@ -76,7 +76,8 @@ function createPrinter$1(build) {
76
76
  const dispatch = (table, node, options, parent) => {
77
77
  const handler = table[node.type];
78
78
  if (!handler) return null;
79
- return handler.call(createContext(options, node, parent), node);
79
+ const context = createContext(options, node, parent);
80
+ return handler.call(context, node, context);
80
81
  };
81
82
  function createContext(options, current, parent) {
82
83
  const context = {
@@ -88,14 +89,19 @@ function createPrinter$1(build) {
88
89
  };
89
90
  return context;
90
91
  }
91
- const root = createContext(resolvedOptions);
92
- return {
93
- name,
94
- options: resolvedOptions,
95
- transform: root.transform,
96
- print: printOverride ? (node, extra) => printOverride.call(extra ? createContext(withOptions(resolvedOptions, extra)) : root, node) : root.transform,
97
- drainImports: () => collectedImports.splice(0)
92
+ const drainImports = () => collectedImports.splice(0);
93
+ const toPrinter = (options) => {
94
+ const root = createContext(options);
95
+ return {
96
+ name,
97
+ options,
98
+ transform: (node) => root.transform(node),
99
+ print: printOverride ? (node) => printOverride.call(root, node, root) : (node) => root.transform(node),
100
+ with: (extra) => toPrinter(withOptions(options, extra)),
101
+ drainImports
102
+ };
98
103
  };
104
+ return toPrinter(resolvedOptions);
99
105
  };
100
106
  }
101
107
  require_rolldown_runtime.__name(createPrinter$1, "createPrinter");
@@ -1 +1 @@
1
- {"version":3,"file":"index.cjs","names":["createPrinter","mergeRef","createPrinterImpl","defineMacroImpl"],"sources":["../src/createPrinter.ts","../src/deprecated.ts","../src/index.ts"],"sourcesContent":["import type { ImportNode } from './nodes/file.ts'\nimport type { SchemaNode, SchemaNodeByType, SchemaType } from './nodes/schema.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 * base: () => '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 * The optional `options` are merged over `this.options` for that child call only.\n */\n transform: (node: SchemaNode, options?: Partial<TOptions>) => TOutput | null\n /**\n * Run the printer's built-in handler for the node, ignoring any override for its type.\n * Inside an override, `this.base(node)` returns what the printer would have emitted,\n * so the override can wrap it instead of re-implementing the handler. Nested nodes\n * still dispatch through the overrides. The optional `options` merge like `this.transform`.\n */\n base: (node: SchemaNode, options?: Partial<TOptions>) => TOutput | null\n /** Declares an import the printed code needs. The generator reads it back with `printer.drainImports()`. */\n import: (node: ImportNode) => void\n /**\n * Options for this printer instance.\n */\n options: TOptions\n /** The schema node whose handler called `this.transform`, `undefined` at the root. */\n parent?: SchemaNode\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, options?: Partial<T['options']>) => 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, options?: Partial<T['options']>) => T['printOutput'] | null\n /** Returns the imports declared with `this.import(...)` since the last call, then clears them. */\n drainImports: () => Array<ImportNode>\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: PrinterPartial<T['output'], T['options']>\n /**\n * User-supplied handler overrides. An override wins over the matching `nodes` handler,\n * and can call `this.base(node)` to reuse the handler it replaced. Pass overrides here\n * instead of spreading them into `nodes`, otherwise `this.base` cannot find the original.\n */\n overrides?: PrinterPartial<T['output'], T['options']>\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 * Creates 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 * - `overrides` (optional), user-supplied handlers that win over `nodes`.\n * An override can call `this.base(node)` to reuse the handler it replaced.\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 { ast, createPrinter } from '@kubb/kit'\n *\n * type PrinterZod = ast.PrinterFactoryOptions<'zod', { strict?: boolean }, string>\n *\n * export const zodPrinter = createPrinter<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 createPrinter<T extends PrinterFactoryOptions = PrinterFactoryOptions>(build: PrinterBuilder<T>): (options?: T['options']) => Printer<T> {\n return (options) => {\n const { name, options: resolvedOptions, nodes, overrides, print: printOverride } = build((options ?? {}) as T['options'])\n const merged = overrides ? { ...nodes, ...overrides } : nodes\n\n const collectedImports: Array<ImportNode> = []\n const importNode = (node: ImportNode): void => {\n collectedImports.push(node)\n }\n type Context = PrinterHandlerContext<T['output'], T['options']>\n const withOptions = (current: T['options'], extra?: Partial<T['options']>): T['options'] => (extra ? { ...current, ...extra } : current)\n\n const dispatch = (table: PrinterPartial<T['output'], T['options']>, node: SchemaNode, options: T['options'], parent?: SchemaNode): T['output'] | null => {\n const handler = table[node.type]\n if (!handler) return null\n\n return (handler as (this: Context, node: SchemaNode) => T['output'] | null).call(createContext(options, node, parent), node)\n }\n\n // `current` is the node whose handler gets this context, so it becomes the parent of what that handler transforms.\n function createContext(options: T['options'], current?: SchemaNode, parent?: SchemaNode): Context {\n const context: Context = {\n options,\n parent,\n import: importNode,\n transform: (node, extra) => dispatch(merged, node, withOptions(context.options, extra), current),\n base: (node, extra) => dispatch(nodes, node, withOptions(context.options, extra), parent),\n }\n return context\n }\n\n const root = createContext(resolvedOptions)\n\n return {\n name,\n options: resolvedOptions,\n transform: root.transform,\n print: (printOverride\n ? (node: SchemaNode, extra?: Partial<T['options']>) => printOverride.call(extra ? createContext(withOptions(resolvedOptions, extra)) : root, node)\n : root.transform) as Printer<T>['print'],\n drainImports: () => collectedImports.splice(0),\n }\n }\n}\n","import * as graph from './graph/index.ts'\nimport * as http from './http/index.ts'\nimport * as ref from './ref/index.ts'\nimport * as schema from './schema/index.ts'\nimport { mergeRefWithSchema as mergeRef } from './utils/refs.ts'\nimport { createPrinter as createPrinterImpl } from './createPrinter.ts'\nimport { defineMacro as defineMacroImpl } from './defineMacro.ts'\nimport * as macro from './macro/index.ts'\nimport * as node from './node/index.ts'\nimport * as file from './file/index.ts'\n\n/** @deprecated Use `ast.ref.isAlias`. Removed in Kubb v6. */\nexport const isBareRef = ref.isAlias\n\n/** @deprecated Use `ast.ref.mergeSchema`. Removed in Kubb v6. */\nexport const mergeRefWithSchema = mergeRef\n\n/** @deprecated Use `ast.ref.getName`. Removed in Kubb v6. */\nexport const refName = ref.getName\n\n/** @deprecated Use `ast.ref.getSchema`. Removed in Kubb v6. */\nexport const resolveRef = ref.getSchema\n\n/** @deprecated Use `ast.ref.getName`. Removed in Kubb v6. */\nexport const resolveRefName = ref.getName\n\n/** @deprecated Use `ast.graph.getImportedNames`. Removed in Kubb v6. */\nexport const collectImportedRefNames = graph.getImportedNames\n\n/** @deprecated Use `ast.graph.getRefNames`. Removed in Kubb v6. */\nexport const collectSchemaRefs = graph.getRefNames\n\n/** @deprecated Use `ast.graph.getUsedNames`. Removed in Kubb v6. */\nexport const collectUsedSchemaNames = graph.getUsedNames\n\n/** @deprecated Use `ast.graph.getCircularNames`. Removed in Kubb v6. */\nexport const findCircularSchemas = graph.getCircularNames\n\n/** @deprecated Use `ast.schema.getLiterals`. Removed in Kubb v6. */\nexport const getSchemaLiteralValues = schema.getLiterals\n\n/** @deprecated Use `ast.schema.inferDiscriminator`. Removed in Kubb v6. */\nexport const inferDiscriminatorPropertyName = schema.inferDiscriminator\n\n/** @deprecated Use `ast.schema.findProperties`. Removed in Kubb v6. */\nexport const resolveSchemaProperties = schema.findProperties\n\n/** @deprecated Use `ast.http.isOperation`. Removed in Kubb v6. */\nexport const isHttpOperationNode = http.isOperation\n\n/** @deprecated Use `ast.node.collect`, which returns the same array. Removed in Kubb v6. */\nexport const collectSync = node.collect\n\n/** @deprecated Use `ast.schema.applyOptionality`. Removed in Kubb v6. */\nexport const optionality = schema.applyOptionality\n\n/** @deprecated Use `ast.node.getText`. Removed in Kubb v6. */\nexport const extractStringsFromNodes = node.getText\n\n/** @deprecated Use `ast.macro.compareOrder`. Removed in Kubb v6. */\nexport const compareEnforce = macro.compareOrder\n\n/** @deprecated Use `createPrinter` from `@kubb/kit`. Removed in Kubb v6. */\nexport const createPrinter = createPrinterImpl\n\n/** @deprecated Use `defineMacro` from `@kubb/kit`. Removed in Kubb v6. */\nexport const defineMacro = defineMacroImpl\n\n/** @deprecated Use `ast.macro.apply`. Removed in Kubb v6. */\nexport const applyMacros = macro.apply\n\n/** @deprecated Use `ast.node.kinds`. Removed in Kubb v6. */\nexport const nodeKinds = node.kinds\n\n/** @deprecated Use `ast.schema.types`. Removed in Kubb v6. */\nexport const schemaTypes = schema.types\n\n/** @deprecated Use `ast.schema.find`. Removed in Kubb v6. */\nexport const findSchema = schema.find\n\n/** @deprecated Use `ast.schema.narrow`. Removed in Kubb v6. */\nexport const narrowSchema = schema.narrow\n\n/** @deprecated Use `ast.node.transform`. Removed in Kubb v6. */\nexport const transform = node.transform\n\n/** @deprecated Use `ast.node.collect`. Removed in Kubb v6. */\nexport const collect = node.collect\n\n/** @deprecated Use `ast.file.inline`. Removed in Kubb v6. */\nexport const inlineFiles = file.inline\n","export type { InlineLanguage } from './utils/inline.ts'\nexport * from './deprecated.ts'\n\nexport * as factory from './nodes/index.ts'\nexport * as file from './file/index.ts'\nexport * as graph from './graph/index.ts'\nexport * as http from './http/index.ts'\nexport * as json from './json/index.ts'\nexport * as macro from './macro/index.ts'\nexport * as mediaType from './mediaType/index.ts'\nexport * as node from './node/index.ts'\nexport * as ref from './ref/index.ts'\nexport * as schema from './schema/index.ts'\nexport type * from './types.ts'\nexport * as ast from './index.ts'\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAkNA,SAAgBA,gBAAuE,OAAkE;CACvJ,QAAQ,YAAY;EAClB,MAAM,EAAE,MAAM,SAAS,iBAAiB,OAAO,WAAW,OAAO,kBAAkB,MAAO,WAAW,CAAC,CAAkB;EACxH,MAAM,SAAS,YAAY;GAAE,GAAG;GAAO,GAAG;EAAU,IAAI;EAExD,MAAM,mBAAsC,CAAC;EAC7C,MAAM,cAAc,SAA2B;GAC7C,iBAAiB,KAAK,IAAI;EAC5B;EAEA,MAAM,eAAe,SAAuB,UAAiD,QAAQ;GAAE,GAAG;GAAS,GAAG;EAAM,IAAI;EAEhI,MAAM,YAAY,OAAkD,MAAkB,SAAuB,WAA4C;GACvJ,MAAM,UAAU,MAAM,KAAK;GAC3B,IAAI,CAAC,SAAS,OAAO;GAErB,OAAQ,QAAoE,KAAK,cAAc,SAAS,MAAM,MAAM,GAAG,IAAI;EAC7H;EAGA,SAAS,cAAc,SAAuB,SAAsB,QAA8B;GAChG,MAAM,UAAmB;IACvB;IACA;IACA,QAAQ;IACR,YAAY,MAAM,UAAU,SAAS,QAAQ,MAAM,YAAY,QAAQ,SAAS,KAAK,GAAG,OAAO;IAC/F,OAAO,MAAM,UAAU,SAAS,OAAO,MAAM,YAAY,QAAQ,SAAS,KAAK,GAAG,MAAM;GAC1F;GACA,OAAO;EACT;EAEA,MAAM,OAAO,cAAc,eAAe;EAE1C,OAAO;GACL;GACA,SAAS;GACT,WAAW,KAAK;GAChB,OAAQ,iBACH,MAAkB,UAAkC,cAAc,KAAK,QAAQ,cAAc,YAAY,iBAAiB,KAAK,CAAC,IAAI,MAAM,IAAI,IAC/I,KAAK;GACT,oBAAoB,iBAAiB,OAAO,CAAC;EAC/C;CACF;AACF;;;;ACjPA,MAAa,YAAA,aAAA;;AAGb,MAAa,qBAAqBC,aAAAA;;AAGlC,MAAa,UAAA,YAAA;;AAGb,MAAa,aAAA,aAAA;;AAGb,MAAa,iBAAA,YAAA;;AAGb,MAAa,0BAAA,cAAA;;AAGb,MAAa,oBAAA,cAAA;;AAGb,MAAa,yBAAA,cAAA;;AAGb,MAAa,sBAAA,cAAA;;AAGb,MAAa,yBAAA,eAAA;;AAGb,MAAa,iCAAA,eAAA;;AAGb,MAAa,0BAAA,eAAA;;AAGb,MAAa,sBAAA,eAAA;;AAGb,MAAa,cAAA,gBAAA;;AAGb,MAAa,cAAA,oBAAA;;AAGb,MAAa,0BAAA,iBAAA;;AAGb,MAAa,iBAAA,cAAA;;AAGb,MAAa,gBAAgBC;;AAG7B,MAAa,cAAcC,cAAAA;;AAG3B,MAAa,cAAA,cAAA;;AAGb,MAAa,YAAA,kBAAA;;AAGb,MAAa,cAAA,kBAAA;;AAGb,MAAa,aAAA,gBAAA;;AAGb,MAAa,eAAA,eAAA;;AAGb,MAAa,YAAA,gBAAA;;AAGb,MAAa,UAAA,gBAAA;;AAGb,MAAa,cAAA,aAAA"}
1
+ {"version":3,"file":"index.cjs","names":["createPrinter","mergeRef","createPrinterImpl","defineMacroImpl"],"sources":["../src/createPrinter.ts","../src/deprecated.ts","../src/index.ts"],"sourcesContent":["import type { ImportNode } from './nodes/file.ts'\nimport type { SchemaNode, SchemaNodeByType, SchemaType } from './nodes/schema.ts'\n\n/**\n * Runtime context passed to printer handlers, both as `this` and as the second argument.\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 * base: () => '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 * The optional `options` are merged over `this.options` for that child call only.\n */\n transform: (node: SchemaNode, options?: Partial<TOptions>) => TOutput | null\n /**\n * Run the printer's built-in handler for the node, ignoring any override for its type.\n * Inside an override, `this.base(node)` returns what the printer would have emitted,\n * so the override can wrap it instead of re-implementing the handler. Nested nodes\n * still dispatch through the overrides. The optional `options` merge like `this.transform`.\n */\n base: (node: SchemaNode, options?: Partial<TOptions>) => TOutput | null\n /** Declares an import the printed code needs. The generator reads it back with `printer.drainImports()`. */\n import: (node: ImportNode) => void\n /**\n * Options for this printer instance.\n */\n options: TOptions\n /** The schema node whose handler called `this.transform`, `undefined` at the root. */\n parent?: SchemaNode\n}\n\n/**\n * Handler for one schema node type. The handler context is `this` and the second argument,\n * so an arrow function can read it as `ctx`. The second argument is typed as optional, so an\n * arrow function asserts it with `ctx!`.\n *\n * @example\n * ```ts\n * const handler: PrinterHandler<string, {}, 'array'> = (node, ctx) => `Array<${ctx!.transform(node.items[0]!)}>`\n * ```\n */\ntype PrinterHandler<TOutput, TOptions extends object, T extends SchemaType = SchemaType> = (\n this: PrinterHandlerContext<TOutput, TOptions>,\n node: SchemaNodeByType[T],\n // Optional and without the options type, so one-argument handler types stay assignable and\n // a union of printer tables keeps its contextual `this`. Use `this.options` for typed options.\n ctx?: PrinterHandlerContext<TOutput, object>,\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 /** Returns this printer with `extra` merged over its options, sharing its handlers and imports, such as `printer.with({ keysToOmit: ['id'] })`. */\n with: (extra: Partial<T['options']>) => Printer<T>\n /** Returns the imports declared with `this.import(...)` since the last call, then clears them. */\n drainImports: () => Array<ImportNode>\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: PrinterPartial<T['output'], T['options']>\n /**\n * User-supplied handler overrides. An override wins over the matching `nodes` handler,\n * and can call `this.base(node)` to reuse the handler it replaced. Pass overrides here\n * instead of spreading them into `nodes`, otherwise `this.base` cannot find the original.\n */\n overrides?: PrinterPartial<T['output'], T['options']>\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. The root context is also the second argument.\n */\n print?: (\n this: PrinterHandlerContext<T['output'], T['options']>,\n node: SchemaNode,\n ctx: PrinterHandlerContext<T['output'], T['options']>,\n ) => T['printOutput'] | null\n}\n/**\n * Creates 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 * - `overrides` (optional), user-supplied handlers that win over `nodes`.\n * An override can call `this.base(node)` to reuse the handler it replaced.\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 { ast, createPrinter } from '@kubb/kit'\n *\n * type PrinterZod = ast.PrinterFactoryOptions<'zod', { strict?: boolean }, string>\n *\n * export const zodPrinter = createPrinter<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 createPrinter<T extends PrinterFactoryOptions = PrinterFactoryOptions>(build: PrinterBuilder<T>): (options?: T['options']) => Printer<T> {\n return (options) => {\n const { name, options: resolvedOptions, nodes, overrides, print: printOverride } = build((options ?? {}) as T['options'])\n const merged = overrides ? { ...nodes, ...overrides } : nodes\n\n const collectedImports: Array<ImportNode> = []\n const importNode = (node: ImportNode): void => {\n collectedImports.push(node)\n }\n type Context = PrinterHandlerContext<T['output'], T['options']>\n const withOptions = (current: T['options'], extra?: Partial<T['options']>): T['options'] => (extra ? { ...current, ...extra } : current)\n\n const dispatch = (table: PrinterPartial<T['output'], T['options']>, node: SchemaNode, options: T['options'], parent?: SchemaNode): T['output'] | null => {\n const handler = table[node.type]\n if (!handler) return null\n\n const context = createContext(options, node, parent)\n return (handler as (this: Context, node: SchemaNode, ctx: Context) => T['output'] | null).call(context, node, context)\n }\n\n // `current` is the node whose handler gets this context, so it becomes the parent of what that handler transforms.\n function createContext(options: T['options'], current?: SchemaNode, parent?: SchemaNode): Context {\n const context: Context = {\n options,\n parent,\n import: importNode,\n transform: (node, extra) => dispatch(merged, node, withOptions(context.options, extra), current),\n base: (node, extra) => dispatch(nodes, node, withOptions(context.options, extra), parent),\n }\n return context\n }\n\n const drainImports = () => collectedImports.splice(0)\n\n const toPrinter = (options: T['options']): Printer<T> => {\n const root = createContext(options)\n return {\n name,\n options,\n transform: (node) => root.transform(node),\n print: (printOverride ? (node: SchemaNode) => printOverride.call(root, node, root) : (node: SchemaNode) => root.transform(node)) as Printer<T>['print'],\n with: (extra) => toPrinter(withOptions(options, extra)),\n drainImports,\n }\n }\n\n return toPrinter(resolvedOptions)\n }\n}\n","import * as graph from './graph/index.ts'\nimport * as http from './http/index.ts'\nimport * as ref from './ref/index.ts'\nimport * as schema from './schema/index.ts'\nimport { mergeRefWithSchema as mergeRef } from './utils/refs.ts'\nimport { createPrinter as createPrinterImpl } from './createPrinter.ts'\nimport { defineMacro as defineMacroImpl } from './defineMacro.ts'\nimport * as macro from './macro/index.ts'\nimport * as node from './node/index.ts'\nimport * as file from './file/index.ts'\n\n/** @deprecated Use `ast.ref.isAlias`. Removed in Kubb v6. */\nexport const isBareRef = ref.isAlias\n\n/** @deprecated Use `ast.ref.mergeSchema`. Removed in Kubb v6. */\nexport const mergeRefWithSchema = mergeRef\n\n/** @deprecated Use `ast.ref.getName`. Removed in Kubb v6. */\nexport const refName = ref.getName\n\n/** @deprecated Use `ast.ref.getSchema`. Removed in Kubb v6. */\nexport const resolveRef = ref.getSchema\n\n/** @deprecated Use `ast.ref.getName`. Removed in Kubb v6. */\nexport const resolveRefName = ref.getName\n\n/** @deprecated Use `ast.graph.getImportedNames`. Removed in Kubb v6. */\nexport const collectImportedRefNames = graph.getImportedNames\n\n/** @deprecated Use `ast.graph.getRefNames`. Removed in Kubb v6. */\nexport const collectSchemaRefs = graph.getRefNames\n\n/** @deprecated Use `ast.graph.getUsedNames`. Removed in Kubb v6. */\nexport const collectUsedSchemaNames = graph.getUsedNames\n\n/** @deprecated Use `ast.graph.getCircularNames`. Removed in Kubb v6. */\nexport const findCircularSchemas = graph.getCircularNames\n\n/** @deprecated Use `ast.schema.getLiterals`. Removed in Kubb v6. */\nexport const getSchemaLiteralValues = schema.getLiterals\n\n/** @deprecated Use `ast.schema.inferDiscriminator`. Removed in Kubb v6. */\nexport const inferDiscriminatorPropertyName = schema.inferDiscriminator\n\n/** @deprecated Use `ast.schema.findProperties`. Removed in Kubb v6. */\nexport const resolveSchemaProperties = schema.findProperties\n\n/** @deprecated Use `ast.http.isOperation`. Removed in Kubb v6. */\nexport const isHttpOperationNode = http.isOperation\n\n/** @deprecated Use `ast.node.collect`, which returns the same array. Removed in Kubb v6. */\nexport const collectSync = node.collect\n\n/** @deprecated Use `ast.schema.applyOptionality`. Removed in Kubb v6. */\nexport const optionality = schema.applyOptionality\n\n/** @deprecated Use `ast.node.getText`. Removed in Kubb v6. */\nexport const extractStringsFromNodes = node.getText\n\n/** @deprecated Use `ast.macro.compareOrder`. Removed in Kubb v6. */\nexport const compareEnforce = macro.compareOrder\n\n/** @deprecated Use `createPrinter` from `@kubb/kit`. Removed in Kubb v6. */\nexport const createPrinter = createPrinterImpl\n\n/** @deprecated Use `defineMacro` from `@kubb/kit`. Removed in Kubb v6. */\nexport const defineMacro = defineMacroImpl\n\n/** @deprecated Use `ast.macro.apply`. Removed in Kubb v6. */\nexport const applyMacros = macro.apply\n\n/** @deprecated Use `ast.node.kinds`. Removed in Kubb v6. */\nexport const nodeKinds = node.kinds\n\n/** @deprecated Use `ast.schema.types`. Removed in Kubb v6. */\nexport const schemaTypes = schema.types\n\n/** @deprecated Use `ast.schema.find`. Removed in Kubb v6. */\nexport const findSchema = schema.find\n\n/** @deprecated Use `ast.schema.narrow`. Removed in Kubb v6. */\nexport const narrowSchema = schema.narrow\n\n/** @deprecated Use `ast.node.transform`. Removed in Kubb v6. */\nexport const transform = node.transform\n\n/** @deprecated Use `ast.node.collect`. Removed in Kubb v6. */\nexport const collect = node.collect\n\n/** @deprecated Use `ast.file.inline`. Removed in Kubb v6. */\nexport const inlineFiles = file.inline\n","export type { InlineLanguage } from './utils/inline.ts'\nexport * from './deprecated.ts'\n\nexport * as factory from './nodes/index.ts'\nexport * as file from './file/index.ts'\nexport * as graph from './graph/index.ts'\nexport * as http from './http/index.ts'\nexport * as json from './json/index.ts'\nexport * as macro from './macro/index.ts'\nexport * as mediaType from './mediaType/index.ts'\nexport * as node from './node/index.ts'\nexport * as ref from './ref/index.ts'\nexport * as schema from './schema/index.ts'\nexport type * from './types.ts'\nexport * as ast from './index.ts'\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAyNA,SAAgBA,gBAAuE,OAAkE;CACvJ,QAAQ,YAAY;EAClB,MAAM,EAAE,MAAM,SAAS,iBAAiB,OAAO,WAAW,OAAO,kBAAkB,MAAO,WAAW,CAAC,CAAkB;EACxH,MAAM,SAAS,YAAY;GAAE,GAAG;GAAO,GAAG;EAAU,IAAI;EAExD,MAAM,mBAAsC,CAAC;EAC7C,MAAM,cAAc,SAA2B;GAC7C,iBAAiB,KAAK,IAAI;EAC5B;EAEA,MAAM,eAAe,SAAuB,UAAiD,QAAQ;GAAE,GAAG;GAAS,GAAG;EAAM,IAAI;EAEhI,MAAM,YAAY,OAAkD,MAAkB,SAAuB,WAA4C;GACvJ,MAAM,UAAU,MAAM,KAAK;GAC3B,IAAI,CAAC,SAAS,OAAO;GAErB,MAAM,UAAU,cAAc,SAAS,MAAM,MAAM;GACnD,OAAQ,QAAkF,KAAK,SAAS,MAAM,OAAO;EACvH;EAGA,SAAS,cAAc,SAAuB,SAAsB,QAA8B;GAChG,MAAM,UAAmB;IACvB;IACA;IACA,QAAQ;IACR,YAAY,MAAM,UAAU,SAAS,QAAQ,MAAM,YAAY,QAAQ,SAAS,KAAK,GAAG,OAAO;IAC/F,OAAO,MAAM,UAAU,SAAS,OAAO,MAAM,YAAY,QAAQ,SAAS,KAAK,GAAG,MAAM;GAC1F;GACA,OAAO;EACT;EAEA,MAAM,qBAAqB,iBAAiB,OAAO,CAAC;EAEpD,MAAM,aAAa,YAAsC;GACvD,MAAM,OAAO,cAAc,OAAO;GAClC,OAAO;IACL;IACA;IACA,YAAY,SAAS,KAAK,UAAU,IAAI;IACxC,OAAQ,iBAAiB,SAAqB,cAAc,KAAK,MAAM,MAAM,IAAI,KAAK,SAAqB,KAAK,UAAU,IAAI;IAC9H,OAAO,UAAU,UAAU,YAAY,SAAS,KAAK,CAAC;IACtD;GACF;EACF;EAEA,OAAO,UAAU,eAAe;CAClC;AACF;;;;AC7PA,MAAa,YAAA,aAAA;;AAGb,MAAa,qBAAqBC,aAAAA;;AAGlC,MAAa,UAAA,YAAA;;AAGb,MAAa,aAAA,aAAA;;AAGb,MAAa,iBAAA,YAAA;;AAGb,MAAa,0BAAA,cAAA;;AAGb,MAAa,oBAAA,cAAA;;AAGb,MAAa,yBAAA,cAAA;;AAGb,MAAa,sBAAA,cAAA;;AAGb,MAAa,yBAAA,eAAA;;AAGb,MAAa,iCAAA,eAAA;;AAGb,MAAa,0BAAA,eAAA;;AAGb,MAAa,sBAAA,eAAA;;AAGb,MAAa,cAAA,gBAAA;;AAGb,MAAa,cAAA,oBAAA;;AAGb,MAAa,0BAAA,iBAAA;;AAGb,MAAa,iBAAA,cAAA;;AAGb,MAAa,gBAAgBC;;AAG7B,MAAa,cAAcC,cAAAA;;AAG3B,MAAa,cAAA,cAAA;;AAGb,MAAa,YAAA,kBAAA;;AAGb,MAAa,cAAA,kBAAA;;AAGb,MAAa,aAAA,gBAAA;;AAGb,MAAa,eAAA,eAAA;;AAGb,MAAa,YAAA,gBAAA;;AAGb,MAAa,UAAA,gBAAA;;AAGb,MAAa,cAAA,aAAA"}
package/dist/index.d.cts CHANGED
@@ -2,19 +2,19 @@ import { n as InlineLanguage, r as inlineFiles$1, t as index_d_exports$2 } from
2
2
  import { a as findCircularSchemas$1, i as collectUsedSchemaNames$1, n as collectImportedRefNames$1, r as collectSchemaRefs$1, t as index_d_exports$3 } from "./index-DYDha-3I.cjs";
3
3
  import { t as index_d_exports$4 } from "./index-BWd95onW.cjs";
4
4
  import { a as mergeRefWithSchema$1, i as isBareRef$1, n as index_d_exports$9, o as resolveRef$1, t as getName } from "./index-DU_jYpBt.cjs";
5
- import { a as resolveSchemaProperties$1, d as applyOptionality, i as inferDiscriminatorPropertyName$1, r as getSchemaLiteralValues$1, t as index_d_exports$10 } from "./index-C-vhkzwR.cjs";
5
+ import { a as resolveSchemaProperties$1, d as applyOptionality, i as inferDiscriminatorPropertyName$1, r as getSchemaLiteralValues$1, t as index_d_exports$10 } from "./index-DKJdlX1l.cjs";
6
6
  import { n as narrowSchema$1, t as isHttpOperationNode$1 } from "./guards-B8qDgSaT.cjs";
7
7
  import { _ as TextNode, a as UserFileNode, d as BreakNode, f as CodeNode, g as JsxNode, h as JSDocNode, i as SourceNode, m as FunctionNode, n as FileNode, p as ConstNode, r as ImportNode, t as ExportNode, u as ArrowFunctionNode, v as TypeNode } from "./file-BVqSiSvV.cjs";
8
8
  import { A as ArraySchemaNode, B as ScalarSchemaNode, C as ExternalDocs, D as InputTag, E as InputServer, F as NotSchemaNode, G as StringSchemaNode, H as SchemaNode, I as NumberSchemaNode, J as UrlSchemaNode, K as TimeSchemaNode, L as ObjectSchemaNode, M as DatetimeSchemaNode, N as EnumSchemaNode, O as OAuthFlow, P as IntersectionSchemaNode, R as PrimitiveSchemaType, S as AuthScheme, T as InputNode, U as SchemaNodeByType, V as ScalarSchemaType, W as SchemaType, X as PropertyNode, _ as EncodingNode, b as AuthCredential, c as StatusCode, f as ParameterLocation, g as ContentNode, i as OperationNode, j as DateSchemaNode, m as ParameterStyle, n as HttpMethod, o as ResponseLink, p as ParameterNode, q as UnionSchemaNode, r as HttpOperationNode, s as ResponseNode, t as GenericOperationNode, u as RequestBodyNode, v as ExampleNode, w as InputMeta, x as AuthRequirement, z as RefSchemaNode } from "./operation-X7chCdL2.cjs";
9
- import { a as compareMacroOrder, i as applyMacros$1, n as Enforce, o as defineMacro$1, r as Macro, t as index_d_exports$6 } from "./index-CIqwy4EE.cjs";
10
- import { n as getNodeText, t as index_d_exports$8 } from "./index-BngGJux5.cjs";
9
+ import { a as compareMacroOrder, i as applyMacros$1, n as Enforce, o as defineMacro$1, r as Macro, t as index_d_exports$6 } from "./index-CwLhqYbA.cjs";
10
+ import { n as getNodeText, t as index_d_exports$8 } from "./index-BVuX3-Th.cjs";
11
11
  import { n as index_d_exports$1, t as Node } from "./index-DSVef1pp.cjs";
12
12
  import { t as index_d_exports$5 } from "./index-Bb1kqq8H.cjs";
13
13
  import { n as index_d_exports$7 } from "./index-Cc2K3OzU.cjs";
14
14
  import { n as DistributiveOmit, r as NodeKind } from "./base-IpYuh3ZP.cjs";
15
- import { a as findSchema$1, i as collect$1, n as VisitorContext, o as transform$1, t as Visitor } from "./visitor-Bw_opzjF.cjs";
15
+ import { a as collect$1, n as VisitorContext, o as findSchema$1, s as transform$1, t as Visitor } from "./visitor-CUbaaX8R.cjs";
16
16
  /**
17
- * Runtime context passed as `this` to printer handlers.
17
+ * Runtime context passed to printer handlers, both as `this` and as the second argument.
18
18
  *
19
19
  * `this.transform` dispatches to node-level handlers from `nodes`.
20
20
  *
@@ -51,18 +51,16 @@ type PrinterHandlerContext<TOutput, TOptions extends object> = {
51
51
  parent?: SchemaNode;
52
52
  };
53
53
  /**
54
- * Handler for one schema node type.
55
- *
56
- * Use a regular function (not an arrow function) if you need `this`.
54
+ * Handler for one schema node type. The handler context is `this` and the second argument,
55
+ * so an arrow function can read it as `ctx`. The second argument is typed as optional, so an
56
+ * arrow function asserts it with `ctx!`.
57
57
  *
58
58
  * @example
59
59
  * ```ts
60
- * const handler: PrinterHandler<string, {}, 'string'> = function () {
61
- * return 'string'
62
- * }
60
+ * const handler: PrinterHandler<string, {}, 'array'> = (node, ctx) => `Array<${ctx!.transform(node.items[0]!)}>`
63
61
  * ```
64
62
  */
65
- type PrinterHandler<TOutput, TOptions extends object, T extends SchemaType = SchemaType> = (this: PrinterHandlerContext<TOutput, TOptions>, node: SchemaNodeByType[T]) => TOutput | null;
63
+ type PrinterHandler<TOutput, TOptions extends object, T extends SchemaType = SchemaType> = (this: PrinterHandlerContext<TOutput, TOptions>, node: SchemaNodeByType[T], ctx?: PrinterHandlerContext<TOutput, object>) => TOutput | null;
66
64
  /**
67
65
  * Partial map of per-node-type handler overrides for a printer.
68
66
  *
@@ -125,13 +123,15 @@ type Printer<T extends PrinterFactoryOptions = PrinterFactoryOptions> = {
125
123
  * Always dispatches through the `nodes` map. Never calls the `print` override.
126
124
  * Reach for it when you need the raw output (e.g. `ts.TypeNode`) without declaration wrapping.
127
125
  */
128
- transform: (node: SchemaNode, options?: Partial<T['options']>) => T['output'] | null;
126
+ transform: (node: SchemaNode) => T['output'] | null;
129
127
  /**
130
128
  * Public printer. If the builder provides a root-level `print`, this calls that
131
129
  * higher-level function (which may produce full declarations).
132
130
  * Otherwise, falls back to the node-level dispatcher.
133
131
  */
134
- print: (node: SchemaNode, options?: Partial<T['options']>) => T['printOutput'] | null;
132
+ print: (node: SchemaNode) => T['printOutput'] | null;
133
+ /** Returns this printer with `extra` merged over its options, sharing its handlers and imports, such as `printer.with({ keysToOmit: ['id'] })`. */
134
+ with: (extra: Partial<T['options']>) => Printer<T>;
135
135
  /** Returns the imports declared with `this.import(...)` since the last call, then clears them. */
136
136
  drainImports: () => Array<ImportNode>;
137
137
  };
@@ -165,9 +165,9 @@ type PrinterBuilder<T extends PrinterFactoryOptions> = (options: T['options']) =
165
165
  /**
166
166
  * Optional root-level print override. When provided, becomes the public `printer.print`.
167
167
  * Use `this.transform(node)` inside this function to dispatch to the node-level handlers (`nodes`),
168
- * not the override itself, so recursion is safe.
168
+ * not the override itself, so recursion is safe. The root context is also the second argument.
169
169
  */
170
- print?: (this: PrinterHandlerContext<T['output'], T['options']>, node: SchemaNode) => T['printOutput'] | null;
170
+ print?: (this: PrinterHandlerContext<T['output'], T['options']>, node: SchemaNode, ctx: PrinterHandlerContext<T['output'], T['options']>) => T['printOutput'] | null;
171
171
  };
172
172
  /**
173
173
  * Creates a schema printer: a function that takes a `SchemaNode` and emits
package/dist/index.d.ts CHANGED
@@ -2,19 +2,19 @@ import { n as InlineLanguage, r as inlineFiles$1, t as index_d_exports$2 } from
2
2
  import { a as findCircularSchemas$1, i as collectUsedSchemaNames$1, n as collectImportedRefNames$1, r as collectSchemaRefs$1, t as index_d_exports$3 } from "./index-Dp50LM3a.js";
3
3
  import { t as index_d_exports$4 } from "./index-DaHsMJ_S.js";
4
4
  import { a as mergeRefWithSchema$1, i as isBareRef$1, n as index_d_exports$9, o as resolveRef$1, t as getName } from "./index-CFH4ZC7q.js";
5
- import { a as resolveSchemaProperties$1, d as applyOptionality, i as inferDiscriminatorPropertyName$1, r as getSchemaLiteralValues$1, t as index_d_exports$10 } from "./index-DNiIem0x.js";
5
+ import { a as resolveSchemaProperties$1, d as applyOptionality, i as inferDiscriminatorPropertyName$1, r as getSchemaLiteralValues$1, t as index_d_exports$10 } from "./index-W6yFx0sy.js";
6
6
  import { n as narrowSchema$1, t as isHttpOperationNode$1 } from "./guards-D-h9R_sV.js";
7
7
  import { _ as TextNode, a as UserFileNode, d as BreakNode, f as CodeNode, g as JsxNode, h as JSDocNode, i as SourceNode, m as FunctionNode, n as FileNode, p as ConstNode, r as ImportNode, t as ExportNode, u as ArrowFunctionNode, v as TypeNode } from "./file-xJnBQPGq.js";
8
8
  import { A as ArraySchemaNode, B as ScalarSchemaNode, C as ExternalDocs, D as InputTag, E as InputServer, F as NotSchemaNode, G as StringSchemaNode, H as SchemaNode, I as NumberSchemaNode, J as UrlSchemaNode, K as TimeSchemaNode, L as ObjectSchemaNode, M as DatetimeSchemaNode, N as EnumSchemaNode, O as OAuthFlow, P as IntersectionSchemaNode, R as PrimitiveSchemaType, S as AuthScheme, T as InputNode, U as SchemaNodeByType, V as ScalarSchemaType, W as SchemaType, X as PropertyNode, _ as EncodingNode, b as AuthCredential, c as StatusCode, f as ParameterLocation, g as ContentNode, i as OperationNode, j as DateSchemaNode, m as ParameterStyle, n as HttpMethod, o as ResponseLink, p as ParameterNode, q as UnionSchemaNode, r as HttpOperationNode, s as ResponseNode, t as GenericOperationNode, u as RequestBodyNode, v as ExampleNode, w as InputMeta, x as AuthRequirement, z as RefSchemaNode } from "./operation-BgRyVS7z.js";
9
- import { a as compareMacroOrder, i as applyMacros$1, n as Enforce, o as defineMacro$1, r as Macro, t as index_d_exports$6 } from "./index-CAGuKv6t.js";
10
- import { n as getNodeText, t as index_d_exports$8 } from "./index-D3M2spDR.js";
9
+ import { a as compareMacroOrder, i as applyMacros$1, n as Enforce, o as defineMacro$1, r as Macro, t as index_d_exports$6 } from "./index-BSf-ETQP.js";
10
+ import { n as getNodeText, t as index_d_exports$8 } from "./index-CoRdlrVx.js";
11
11
  import { n as index_d_exports$1, t as Node } from "./index-BwnMIoLl.js";
12
12
  import { t as index_d_exports$5 } from "./index-eGkM4FE9.js";
13
13
  import { n as index_d_exports$7 } from "./index-Cc2K3OzU.js";
14
14
  import { n as DistributiveOmit, r as NodeKind } from "./base-IpYuh3ZP.js";
15
- import { a as findSchema$1, i as collect$1, n as VisitorContext, o as transform$1, t as Visitor } from "./visitor-BZozlXBF.js";
15
+ import { a as collect$1, n as VisitorContext, o as findSchema$1, s as transform$1, t as Visitor } from "./visitor-1TSWTMe1.js";
16
16
  /**
17
- * Runtime context passed as `this` to printer handlers.
17
+ * Runtime context passed to printer handlers, both as `this` and as the second argument.
18
18
  *
19
19
  * `this.transform` dispatches to node-level handlers from `nodes`.
20
20
  *
@@ -51,18 +51,16 @@ type PrinterHandlerContext<TOutput, TOptions extends object> = {
51
51
  parent?: SchemaNode;
52
52
  };
53
53
  /**
54
- * Handler for one schema node type.
55
- *
56
- * Use a regular function (not an arrow function) if you need `this`.
54
+ * Handler for one schema node type. The handler context is `this` and the second argument,
55
+ * so an arrow function can read it as `ctx`. The second argument is typed as optional, so an
56
+ * arrow function asserts it with `ctx!`.
57
57
  *
58
58
  * @example
59
59
  * ```ts
60
- * const handler: PrinterHandler<string, {}, 'string'> = function () {
61
- * return 'string'
62
- * }
60
+ * const handler: PrinterHandler<string, {}, 'array'> = (node, ctx) => `Array<${ctx!.transform(node.items[0]!)}>`
63
61
  * ```
64
62
  */
65
- type PrinterHandler<TOutput, TOptions extends object, T extends SchemaType = SchemaType> = (this: PrinterHandlerContext<TOutput, TOptions>, node: SchemaNodeByType[T]) => TOutput | null;
63
+ type PrinterHandler<TOutput, TOptions extends object, T extends SchemaType = SchemaType> = (this: PrinterHandlerContext<TOutput, TOptions>, node: SchemaNodeByType[T], ctx?: PrinterHandlerContext<TOutput, object>) => TOutput | null;
66
64
  /**
67
65
  * Partial map of per-node-type handler overrides for a printer.
68
66
  *
@@ -125,13 +123,15 @@ type Printer<T extends PrinterFactoryOptions = PrinterFactoryOptions> = {
125
123
  * Always dispatches through the `nodes` map. Never calls the `print` override.
126
124
  * Reach for it when you need the raw output (e.g. `ts.TypeNode`) without declaration wrapping.
127
125
  */
128
- transform: (node: SchemaNode, options?: Partial<T['options']>) => T['output'] | null;
126
+ transform: (node: SchemaNode) => T['output'] | null;
129
127
  /**
130
128
  * Public printer. If the builder provides a root-level `print`, this calls that
131
129
  * higher-level function (which may produce full declarations).
132
130
  * Otherwise, falls back to the node-level dispatcher.
133
131
  */
134
- print: (node: SchemaNode, options?: Partial<T['options']>) => T['printOutput'] | null;
132
+ print: (node: SchemaNode) => T['printOutput'] | null;
133
+ /** Returns this printer with `extra` merged over its options, sharing its handlers and imports, such as `printer.with({ keysToOmit: ['id'] })`. */
134
+ with: (extra: Partial<T['options']>) => Printer<T>;
135
135
  /** Returns the imports declared with `this.import(...)` since the last call, then clears them. */
136
136
  drainImports: () => Array<ImportNode>;
137
137
  };
@@ -165,9 +165,9 @@ type PrinterBuilder<T extends PrinterFactoryOptions> = (options: T['options']) =
165
165
  /**
166
166
  * Optional root-level print override. When provided, becomes the public `printer.print`.
167
167
  * Use `this.transform(node)` inside this function to dispatch to the node-level handlers (`nodes`),
168
- * not the override itself, so recursion is safe.
168
+ * not the override itself, so recursion is safe. The root context is also the second argument.
169
169
  */
170
- print?: (this: PrinterHandlerContext<T['output'], T['options']>, node: SchemaNode) => T['printOutput'] | null;
170
+ print?: (this: PrinterHandlerContext<T['output'], T['options']>, node: SchemaNode, ctx: PrinterHandlerContext<T['output'], T['options']>) => T['printOutput'] | null;
171
171
  };
172
172
  /**
173
173
  * Creates a schema printer: a function that takes a `SchemaNode` and emits
package/dist/index.js CHANGED
@@ -6,7 +6,7 @@ import { r as ref_exports, t as getName } from "./ref-Bu7PoHar.js";
6
6
  import { a as resolveSchemaProperties$1, i as inferDiscriminatorPropertyName$1, n as schema_exports, r as getSchemaLiteralValues$1 } from "./schema-DloctnMm.js";
7
7
  import { n as narrowSchema$1, t as isHttpOperationNode$1 } from "./guards-DlJkKsT1.js";
8
8
  import { i as resolveRef$1, n as mergeRefWithSchema$1, t as isBareRef$1 } from "./refs-YCV3CznS.js";
9
- import { i as defineMacro$1, n as applyMacros$1, r as compareMacroOrder, t as macro_exports } from "./macro-D0KfNtff.js";
9
+ import { i as defineMacro$1, n as applyMacros$1, r as compareMacroOrder, t as macro_exports } from "./macro-4N8vHE-2.js";
10
10
  import { t as applyOptionality } from "./optionality-DISn8ytP.js";
11
11
  import { t as node_exports } from "./node-Djh-mZB2.js";
12
12
  import { n as inlineFiles$1, t as file_exports } from "./file-CvlMAp_d.js";
@@ -75,7 +75,8 @@ function createPrinter$1(build) {
75
75
  const dispatch = (table, node, options, parent) => {
76
76
  const handler = table[node.type];
77
77
  if (!handler) return null;
78
- return handler.call(createContext(options, node, parent), node);
78
+ const context = createContext(options, node, parent);
79
+ return handler.call(context, node, context);
79
80
  };
80
81
  function createContext(options, current, parent) {
81
82
  const context = {
@@ -87,14 +88,19 @@ function createPrinter$1(build) {
87
88
  };
88
89
  return context;
89
90
  }
90
- const root = createContext(resolvedOptions);
91
- return {
92
- name,
93
- options: resolvedOptions,
94
- transform: root.transform,
95
- print: printOverride ? (node, extra) => printOverride.call(extra ? createContext(withOptions(resolvedOptions, extra)) : root, node) : root.transform,
96
- drainImports: () => collectedImports.splice(0)
91
+ const drainImports = () => collectedImports.splice(0);
92
+ const toPrinter = (options) => {
93
+ const root = createContext(options);
94
+ return {
95
+ name,
96
+ options,
97
+ transform: (node) => root.transform(node),
98
+ print: printOverride ? (node) => printOverride.call(root, node, root) : (node) => root.transform(node),
99
+ with: (extra) => toPrinter(withOptions(options, extra)),
100
+ drainImports
101
+ };
97
102
  };
103
+ return toPrinter(resolvedOptions);
98
104
  };
99
105
  }
100
106
  __name(createPrinter$1, "createPrinter");
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","names":["createPrinter","ref.isAlias","mergeRef","ref.getName","ref.getSchema","graph.getImportedNames","graph.getRefNames","graph.getUsedNames","graph.getCircularNames","schema.getLiterals","schema.inferDiscriminator","schema.findProperties","http.isOperation","node.collect","schema.applyOptionality","node.getText","macro.compareOrder","createPrinterImpl","defineMacroImpl","macro.apply","node.kinds","schema.types","schema.find","schema.narrow","node.transform","file.inline"],"sources":["../src/createPrinter.ts","../src/deprecated.ts","../src/index.ts"],"sourcesContent":["import type { ImportNode } from './nodes/file.ts'\nimport type { SchemaNode, SchemaNodeByType, SchemaType } from './nodes/schema.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 * base: () => '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 * The optional `options` are merged over `this.options` for that child call only.\n */\n transform: (node: SchemaNode, options?: Partial<TOptions>) => TOutput | null\n /**\n * Run the printer's built-in handler for the node, ignoring any override for its type.\n * Inside an override, `this.base(node)` returns what the printer would have emitted,\n * so the override can wrap it instead of re-implementing the handler. Nested nodes\n * still dispatch through the overrides. The optional `options` merge like `this.transform`.\n */\n base: (node: SchemaNode, options?: Partial<TOptions>) => TOutput | null\n /** Declares an import the printed code needs. The generator reads it back with `printer.drainImports()`. */\n import: (node: ImportNode) => void\n /**\n * Options for this printer instance.\n */\n options: TOptions\n /** The schema node whose handler called `this.transform`, `undefined` at the root. */\n parent?: SchemaNode\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, options?: Partial<T['options']>) => 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, options?: Partial<T['options']>) => T['printOutput'] | null\n /** Returns the imports declared with `this.import(...)` since the last call, then clears them. */\n drainImports: () => Array<ImportNode>\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: PrinterPartial<T['output'], T['options']>\n /**\n * User-supplied handler overrides. An override wins over the matching `nodes` handler,\n * and can call `this.base(node)` to reuse the handler it replaced. Pass overrides here\n * instead of spreading them into `nodes`, otherwise `this.base` cannot find the original.\n */\n overrides?: PrinterPartial<T['output'], T['options']>\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 * Creates 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 * - `overrides` (optional), user-supplied handlers that win over `nodes`.\n * An override can call `this.base(node)` to reuse the handler it replaced.\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 { ast, createPrinter } from '@kubb/kit'\n *\n * type PrinterZod = ast.PrinterFactoryOptions<'zod', { strict?: boolean }, string>\n *\n * export const zodPrinter = createPrinter<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 createPrinter<T extends PrinterFactoryOptions = PrinterFactoryOptions>(build: PrinterBuilder<T>): (options?: T['options']) => Printer<T> {\n return (options) => {\n const { name, options: resolvedOptions, nodes, overrides, print: printOverride } = build((options ?? {}) as T['options'])\n const merged = overrides ? { ...nodes, ...overrides } : nodes\n\n const collectedImports: Array<ImportNode> = []\n const importNode = (node: ImportNode): void => {\n collectedImports.push(node)\n }\n type Context = PrinterHandlerContext<T['output'], T['options']>\n const withOptions = (current: T['options'], extra?: Partial<T['options']>): T['options'] => (extra ? { ...current, ...extra } : current)\n\n const dispatch = (table: PrinterPartial<T['output'], T['options']>, node: SchemaNode, options: T['options'], parent?: SchemaNode): T['output'] | null => {\n const handler = table[node.type]\n if (!handler) return null\n\n return (handler as (this: Context, node: SchemaNode) => T['output'] | null).call(createContext(options, node, parent), node)\n }\n\n // `current` is the node whose handler gets this context, so it becomes the parent of what that handler transforms.\n function createContext(options: T['options'], current?: SchemaNode, parent?: SchemaNode): Context {\n const context: Context = {\n options,\n parent,\n import: importNode,\n transform: (node, extra) => dispatch(merged, node, withOptions(context.options, extra), current),\n base: (node, extra) => dispatch(nodes, node, withOptions(context.options, extra), parent),\n }\n return context\n }\n\n const root = createContext(resolvedOptions)\n\n return {\n name,\n options: resolvedOptions,\n transform: root.transform,\n print: (printOverride\n ? (node: SchemaNode, extra?: Partial<T['options']>) => printOverride.call(extra ? createContext(withOptions(resolvedOptions, extra)) : root, node)\n : root.transform) as Printer<T>['print'],\n drainImports: () => collectedImports.splice(0),\n }\n }\n}\n","import * as graph from './graph/index.ts'\nimport * as http from './http/index.ts'\nimport * as ref from './ref/index.ts'\nimport * as schema from './schema/index.ts'\nimport { mergeRefWithSchema as mergeRef } from './utils/refs.ts'\nimport { createPrinter as createPrinterImpl } from './createPrinter.ts'\nimport { defineMacro as defineMacroImpl } from './defineMacro.ts'\nimport * as macro from './macro/index.ts'\nimport * as node from './node/index.ts'\nimport * as file from './file/index.ts'\n\n/** @deprecated Use `ast.ref.isAlias`. Removed in Kubb v6. */\nexport const isBareRef = ref.isAlias\n\n/** @deprecated Use `ast.ref.mergeSchema`. Removed in Kubb v6. */\nexport const mergeRefWithSchema = mergeRef\n\n/** @deprecated Use `ast.ref.getName`. Removed in Kubb v6. */\nexport const refName = ref.getName\n\n/** @deprecated Use `ast.ref.getSchema`. Removed in Kubb v6. */\nexport const resolveRef = ref.getSchema\n\n/** @deprecated Use `ast.ref.getName`. Removed in Kubb v6. */\nexport const resolveRefName = ref.getName\n\n/** @deprecated Use `ast.graph.getImportedNames`. Removed in Kubb v6. */\nexport const collectImportedRefNames = graph.getImportedNames\n\n/** @deprecated Use `ast.graph.getRefNames`. Removed in Kubb v6. */\nexport const collectSchemaRefs = graph.getRefNames\n\n/** @deprecated Use `ast.graph.getUsedNames`. Removed in Kubb v6. */\nexport const collectUsedSchemaNames = graph.getUsedNames\n\n/** @deprecated Use `ast.graph.getCircularNames`. Removed in Kubb v6. */\nexport const findCircularSchemas = graph.getCircularNames\n\n/** @deprecated Use `ast.schema.getLiterals`. Removed in Kubb v6. */\nexport const getSchemaLiteralValues = schema.getLiterals\n\n/** @deprecated Use `ast.schema.inferDiscriminator`. Removed in Kubb v6. */\nexport const inferDiscriminatorPropertyName = schema.inferDiscriminator\n\n/** @deprecated Use `ast.schema.findProperties`. Removed in Kubb v6. */\nexport const resolveSchemaProperties = schema.findProperties\n\n/** @deprecated Use `ast.http.isOperation`. Removed in Kubb v6. */\nexport const isHttpOperationNode = http.isOperation\n\n/** @deprecated Use `ast.node.collect`, which returns the same array. Removed in Kubb v6. */\nexport const collectSync = node.collect\n\n/** @deprecated Use `ast.schema.applyOptionality`. Removed in Kubb v6. */\nexport const optionality = schema.applyOptionality\n\n/** @deprecated Use `ast.node.getText`. Removed in Kubb v6. */\nexport const extractStringsFromNodes = node.getText\n\n/** @deprecated Use `ast.macro.compareOrder`. Removed in Kubb v6. */\nexport const compareEnforce = macro.compareOrder\n\n/** @deprecated Use `createPrinter` from `@kubb/kit`. Removed in Kubb v6. */\nexport const createPrinter = createPrinterImpl\n\n/** @deprecated Use `defineMacro` from `@kubb/kit`. Removed in Kubb v6. */\nexport const defineMacro = defineMacroImpl\n\n/** @deprecated Use `ast.macro.apply`. Removed in Kubb v6. */\nexport const applyMacros = macro.apply\n\n/** @deprecated Use `ast.node.kinds`. Removed in Kubb v6. */\nexport const nodeKinds = node.kinds\n\n/** @deprecated Use `ast.schema.types`. Removed in Kubb v6. */\nexport const schemaTypes = schema.types\n\n/** @deprecated Use `ast.schema.find`. Removed in Kubb v6. */\nexport const findSchema = schema.find\n\n/** @deprecated Use `ast.schema.narrow`. Removed in Kubb v6. */\nexport const narrowSchema = schema.narrow\n\n/** @deprecated Use `ast.node.transform`. Removed in Kubb v6. */\nexport const transform = node.transform\n\n/** @deprecated Use `ast.node.collect`. Removed in Kubb v6. */\nexport const collect = node.collect\n\n/** @deprecated Use `ast.file.inline`. Removed in Kubb v6. */\nexport const inlineFiles = file.inline\n","export type { InlineLanguage } from './utils/inline.ts'\nexport * from './deprecated.ts'\n\nexport * as factory from './nodes/index.ts'\nexport * as file from './file/index.ts'\nexport * as graph from './graph/index.ts'\nexport * as http from './http/index.ts'\nexport * as json from './json/index.ts'\nexport * as macro from './macro/index.ts'\nexport * as mediaType from './mediaType/index.ts'\nexport * as node from './node/index.ts'\nexport * as ref from './ref/index.ts'\nexport * as schema from './schema/index.ts'\nexport type * from './types.ts'\nexport * as ast from './index.ts'\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAkNA,SAAgBA,gBAAuE,OAAkE;CACvJ,QAAQ,YAAY;EAClB,MAAM,EAAE,MAAM,SAAS,iBAAiB,OAAO,WAAW,OAAO,kBAAkB,MAAO,WAAW,CAAC,CAAkB;EACxH,MAAM,SAAS,YAAY;GAAE,GAAG;GAAO,GAAG;EAAU,IAAI;EAExD,MAAM,mBAAsC,CAAC;EAC7C,MAAM,cAAc,SAA2B;GAC7C,iBAAiB,KAAK,IAAI;EAC5B;EAEA,MAAM,eAAe,SAAuB,UAAiD,QAAQ;GAAE,GAAG;GAAS,GAAG;EAAM,IAAI;EAEhI,MAAM,YAAY,OAAkD,MAAkB,SAAuB,WAA4C;GACvJ,MAAM,UAAU,MAAM,KAAK;GAC3B,IAAI,CAAC,SAAS,OAAO;GAErB,OAAQ,QAAoE,KAAK,cAAc,SAAS,MAAM,MAAM,GAAG,IAAI;EAC7H;EAGA,SAAS,cAAc,SAAuB,SAAsB,QAA8B;GAChG,MAAM,UAAmB;IACvB;IACA;IACA,QAAQ;IACR,YAAY,MAAM,UAAU,SAAS,QAAQ,MAAM,YAAY,QAAQ,SAAS,KAAK,GAAG,OAAO;IAC/F,OAAO,MAAM,UAAU,SAAS,OAAO,MAAM,YAAY,QAAQ,SAAS,KAAK,GAAG,MAAM;GAC1F;GACA,OAAO;EACT;EAEA,MAAM,OAAO,cAAc,eAAe;EAE1C,OAAO;GACL;GACA,SAAS;GACT,WAAW,KAAK;GAChB,OAAQ,iBACH,MAAkB,UAAkC,cAAc,KAAK,QAAQ,cAAc,YAAY,iBAAiB,KAAK,CAAC,IAAI,MAAM,IAAI,IAC/I,KAAK;GACT,oBAAoB,iBAAiB,OAAO,CAAC;EAC/C;CACF;AACF;;;;ACjPA,MAAa,YAAYC;;AAGzB,MAAa,qBAAqBC;;AAGlC,MAAa,UAAUC;;AAGvB,MAAa,aAAaC;;AAG1B,MAAa,iBAAiBD;;AAG9B,MAAa,0BAA0BE;;AAGvC,MAAa,oBAAoBC;;AAGjC,MAAa,yBAAyBC;;AAGtC,MAAa,sBAAsBC;;AAGnC,MAAa,yBAAyBC;;AAGtC,MAAa,iCAAiCC;;AAG9C,MAAa,0BAA0BC;;AAGvC,MAAa,sBAAsBC;;AAGnC,MAAa,cAAcC;;AAG3B,MAAa,cAAcC;;AAG3B,MAAa,0BAA0BC;;AAGvC,MAAa,iBAAiBC;;AAG9B,MAAa,gBAAgBC;;AAG7B,MAAa,cAAcC;;AAG3B,MAAa,cAAcC;;AAG3B,MAAa,YAAYC;;AAGzB,MAAa,cAAcC;;AAG3B,MAAa,aAAaC;;AAG1B,MAAa,eAAeC;;AAG5B,MAAa,YAAYC;;AAGzB,MAAa,UAAUX;;AAGvB,MAAa,cAAcY"}
1
+ {"version":3,"file":"index.js","names":["createPrinter","ref.isAlias","mergeRef","ref.getName","ref.getSchema","graph.getImportedNames","graph.getRefNames","graph.getUsedNames","graph.getCircularNames","schema.getLiterals","schema.inferDiscriminator","schema.findProperties","http.isOperation","node.collect","schema.applyOptionality","node.getText","macro.compareOrder","createPrinterImpl","defineMacroImpl","macro.apply","node.kinds","schema.types","schema.find","schema.narrow","node.transform","file.inline"],"sources":["../src/createPrinter.ts","../src/deprecated.ts","../src/index.ts"],"sourcesContent":["import type { ImportNode } from './nodes/file.ts'\nimport type { SchemaNode, SchemaNodeByType, SchemaType } from './nodes/schema.ts'\n\n/**\n * Runtime context passed to printer handlers, both as `this` and as the second argument.\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 * base: () => '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 * The optional `options` are merged over `this.options` for that child call only.\n */\n transform: (node: SchemaNode, options?: Partial<TOptions>) => TOutput | null\n /**\n * Run the printer's built-in handler for the node, ignoring any override for its type.\n * Inside an override, `this.base(node)` returns what the printer would have emitted,\n * so the override can wrap it instead of re-implementing the handler. Nested nodes\n * still dispatch through the overrides. The optional `options` merge like `this.transform`.\n */\n base: (node: SchemaNode, options?: Partial<TOptions>) => TOutput | null\n /** Declares an import the printed code needs. The generator reads it back with `printer.drainImports()`. */\n import: (node: ImportNode) => void\n /**\n * Options for this printer instance.\n */\n options: TOptions\n /** The schema node whose handler called `this.transform`, `undefined` at the root. */\n parent?: SchemaNode\n}\n\n/**\n * Handler for one schema node type. The handler context is `this` and the second argument,\n * so an arrow function can read it as `ctx`. The second argument is typed as optional, so an\n * arrow function asserts it with `ctx!`.\n *\n * @example\n * ```ts\n * const handler: PrinterHandler<string, {}, 'array'> = (node, ctx) => `Array<${ctx!.transform(node.items[0]!)}>`\n * ```\n */\ntype PrinterHandler<TOutput, TOptions extends object, T extends SchemaType = SchemaType> = (\n this: PrinterHandlerContext<TOutput, TOptions>,\n node: SchemaNodeByType[T],\n // Optional and without the options type, so one-argument handler types stay assignable and\n // a union of printer tables keeps its contextual `this`. Use `this.options` for typed options.\n ctx?: PrinterHandlerContext<TOutput, object>,\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 /** Returns this printer with `extra` merged over its options, sharing its handlers and imports, such as `printer.with({ keysToOmit: ['id'] })`. */\n with: (extra: Partial<T['options']>) => Printer<T>\n /** Returns the imports declared with `this.import(...)` since the last call, then clears them. */\n drainImports: () => Array<ImportNode>\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: PrinterPartial<T['output'], T['options']>\n /**\n * User-supplied handler overrides. An override wins over the matching `nodes` handler,\n * and can call `this.base(node)` to reuse the handler it replaced. Pass overrides here\n * instead of spreading them into `nodes`, otherwise `this.base` cannot find the original.\n */\n overrides?: PrinterPartial<T['output'], T['options']>\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. The root context is also the second argument.\n */\n print?: (\n this: PrinterHandlerContext<T['output'], T['options']>,\n node: SchemaNode,\n ctx: PrinterHandlerContext<T['output'], T['options']>,\n ) => T['printOutput'] | null\n}\n/**\n * Creates 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 * - `overrides` (optional), user-supplied handlers that win over `nodes`.\n * An override can call `this.base(node)` to reuse the handler it replaced.\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 { ast, createPrinter } from '@kubb/kit'\n *\n * type PrinterZod = ast.PrinterFactoryOptions<'zod', { strict?: boolean }, string>\n *\n * export const zodPrinter = createPrinter<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 createPrinter<T extends PrinterFactoryOptions = PrinterFactoryOptions>(build: PrinterBuilder<T>): (options?: T['options']) => Printer<T> {\n return (options) => {\n const { name, options: resolvedOptions, nodes, overrides, print: printOverride } = build((options ?? {}) as T['options'])\n const merged = overrides ? { ...nodes, ...overrides } : nodes\n\n const collectedImports: Array<ImportNode> = []\n const importNode = (node: ImportNode): void => {\n collectedImports.push(node)\n }\n type Context = PrinterHandlerContext<T['output'], T['options']>\n const withOptions = (current: T['options'], extra?: Partial<T['options']>): T['options'] => (extra ? { ...current, ...extra } : current)\n\n const dispatch = (table: PrinterPartial<T['output'], T['options']>, node: SchemaNode, options: T['options'], parent?: SchemaNode): T['output'] | null => {\n const handler = table[node.type]\n if (!handler) return null\n\n const context = createContext(options, node, parent)\n return (handler as (this: Context, node: SchemaNode, ctx: Context) => T['output'] | null).call(context, node, context)\n }\n\n // `current` is the node whose handler gets this context, so it becomes the parent of what that handler transforms.\n function createContext(options: T['options'], current?: SchemaNode, parent?: SchemaNode): Context {\n const context: Context = {\n options,\n parent,\n import: importNode,\n transform: (node, extra) => dispatch(merged, node, withOptions(context.options, extra), current),\n base: (node, extra) => dispatch(nodes, node, withOptions(context.options, extra), parent),\n }\n return context\n }\n\n const drainImports = () => collectedImports.splice(0)\n\n const toPrinter = (options: T['options']): Printer<T> => {\n const root = createContext(options)\n return {\n name,\n options,\n transform: (node) => root.transform(node),\n print: (printOverride ? (node: SchemaNode) => printOverride.call(root, node, root) : (node: SchemaNode) => root.transform(node)) as Printer<T>['print'],\n with: (extra) => toPrinter(withOptions(options, extra)),\n drainImports,\n }\n }\n\n return toPrinter(resolvedOptions)\n }\n}\n","import * as graph from './graph/index.ts'\nimport * as http from './http/index.ts'\nimport * as ref from './ref/index.ts'\nimport * as schema from './schema/index.ts'\nimport { mergeRefWithSchema as mergeRef } from './utils/refs.ts'\nimport { createPrinter as createPrinterImpl } from './createPrinter.ts'\nimport { defineMacro as defineMacroImpl } from './defineMacro.ts'\nimport * as macro from './macro/index.ts'\nimport * as node from './node/index.ts'\nimport * as file from './file/index.ts'\n\n/** @deprecated Use `ast.ref.isAlias`. Removed in Kubb v6. */\nexport const isBareRef = ref.isAlias\n\n/** @deprecated Use `ast.ref.mergeSchema`. Removed in Kubb v6. */\nexport const mergeRefWithSchema = mergeRef\n\n/** @deprecated Use `ast.ref.getName`. Removed in Kubb v6. */\nexport const refName = ref.getName\n\n/** @deprecated Use `ast.ref.getSchema`. Removed in Kubb v6. */\nexport const resolveRef = ref.getSchema\n\n/** @deprecated Use `ast.ref.getName`. Removed in Kubb v6. */\nexport const resolveRefName = ref.getName\n\n/** @deprecated Use `ast.graph.getImportedNames`. Removed in Kubb v6. */\nexport const collectImportedRefNames = graph.getImportedNames\n\n/** @deprecated Use `ast.graph.getRefNames`. Removed in Kubb v6. */\nexport const collectSchemaRefs = graph.getRefNames\n\n/** @deprecated Use `ast.graph.getUsedNames`. Removed in Kubb v6. */\nexport const collectUsedSchemaNames = graph.getUsedNames\n\n/** @deprecated Use `ast.graph.getCircularNames`. Removed in Kubb v6. */\nexport const findCircularSchemas = graph.getCircularNames\n\n/** @deprecated Use `ast.schema.getLiterals`. Removed in Kubb v6. */\nexport const getSchemaLiteralValues = schema.getLiterals\n\n/** @deprecated Use `ast.schema.inferDiscriminator`. Removed in Kubb v6. */\nexport const inferDiscriminatorPropertyName = schema.inferDiscriminator\n\n/** @deprecated Use `ast.schema.findProperties`. Removed in Kubb v6. */\nexport const resolveSchemaProperties = schema.findProperties\n\n/** @deprecated Use `ast.http.isOperation`. Removed in Kubb v6. */\nexport const isHttpOperationNode = http.isOperation\n\n/** @deprecated Use `ast.node.collect`, which returns the same array. Removed in Kubb v6. */\nexport const collectSync = node.collect\n\n/** @deprecated Use `ast.schema.applyOptionality`. Removed in Kubb v6. */\nexport const optionality = schema.applyOptionality\n\n/** @deprecated Use `ast.node.getText`. Removed in Kubb v6. */\nexport const extractStringsFromNodes = node.getText\n\n/** @deprecated Use `ast.macro.compareOrder`. Removed in Kubb v6. */\nexport const compareEnforce = macro.compareOrder\n\n/** @deprecated Use `createPrinter` from `@kubb/kit`. Removed in Kubb v6. */\nexport const createPrinter = createPrinterImpl\n\n/** @deprecated Use `defineMacro` from `@kubb/kit`. Removed in Kubb v6. */\nexport const defineMacro = defineMacroImpl\n\n/** @deprecated Use `ast.macro.apply`. Removed in Kubb v6. */\nexport const applyMacros = macro.apply\n\n/** @deprecated Use `ast.node.kinds`. Removed in Kubb v6. */\nexport const nodeKinds = node.kinds\n\n/** @deprecated Use `ast.schema.types`. Removed in Kubb v6. */\nexport const schemaTypes = schema.types\n\n/** @deprecated Use `ast.schema.find`. Removed in Kubb v6. */\nexport const findSchema = schema.find\n\n/** @deprecated Use `ast.schema.narrow`. Removed in Kubb v6. */\nexport const narrowSchema = schema.narrow\n\n/** @deprecated Use `ast.node.transform`. Removed in Kubb v6. */\nexport const transform = node.transform\n\n/** @deprecated Use `ast.node.collect`. Removed in Kubb v6. */\nexport const collect = node.collect\n\n/** @deprecated Use `ast.file.inline`. Removed in Kubb v6. */\nexport const inlineFiles = file.inline\n","export type { InlineLanguage } from './utils/inline.ts'\nexport * from './deprecated.ts'\n\nexport * as factory from './nodes/index.ts'\nexport * as file from './file/index.ts'\nexport * as graph from './graph/index.ts'\nexport * as http from './http/index.ts'\nexport * as json from './json/index.ts'\nexport * as macro from './macro/index.ts'\nexport * as mediaType from './mediaType/index.ts'\nexport * as node from './node/index.ts'\nexport * as ref from './ref/index.ts'\nexport * as schema from './schema/index.ts'\nexport type * from './types.ts'\nexport * as ast from './index.ts'\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAyNA,SAAgBA,gBAAuE,OAAkE;CACvJ,QAAQ,YAAY;EAClB,MAAM,EAAE,MAAM,SAAS,iBAAiB,OAAO,WAAW,OAAO,kBAAkB,MAAO,WAAW,CAAC,CAAkB;EACxH,MAAM,SAAS,YAAY;GAAE,GAAG;GAAO,GAAG;EAAU,IAAI;EAExD,MAAM,mBAAsC,CAAC;EAC7C,MAAM,cAAc,SAA2B;GAC7C,iBAAiB,KAAK,IAAI;EAC5B;EAEA,MAAM,eAAe,SAAuB,UAAiD,QAAQ;GAAE,GAAG;GAAS,GAAG;EAAM,IAAI;EAEhI,MAAM,YAAY,OAAkD,MAAkB,SAAuB,WAA4C;GACvJ,MAAM,UAAU,MAAM,KAAK;GAC3B,IAAI,CAAC,SAAS,OAAO;GAErB,MAAM,UAAU,cAAc,SAAS,MAAM,MAAM;GACnD,OAAQ,QAAkF,KAAK,SAAS,MAAM,OAAO;EACvH;EAGA,SAAS,cAAc,SAAuB,SAAsB,QAA8B;GAChG,MAAM,UAAmB;IACvB;IACA;IACA,QAAQ;IACR,YAAY,MAAM,UAAU,SAAS,QAAQ,MAAM,YAAY,QAAQ,SAAS,KAAK,GAAG,OAAO;IAC/F,OAAO,MAAM,UAAU,SAAS,OAAO,MAAM,YAAY,QAAQ,SAAS,KAAK,GAAG,MAAM;GAC1F;GACA,OAAO;EACT;EAEA,MAAM,qBAAqB,iBAAiB,OAAO,CAAC;EAEpD,MAAM,aAAa,YAAsC;GACvD,MAAM,OAAO,cAAc,OAAO;GAClC,OAAO;IACL;IACA;IACA,YAAY,SAAS,KAAK,UAAU,IAAI;IACxC,OAAQ,iBAAiB,SAAqB,cAAc,KAAK,MAAM,MAAM,IAAI,KAAK,SAAqB,KAAK,UAAU,IAAI;IAC9H,OAAO,UAAU,UAAU,YAAY,SAAS,KAAK,CAAC;IACtD;GACF;EACF;EAEA,OAAO,UAAU,eAAe;CAClC;AACF;;;;AC7PA,MAAa,YAAYC;;AAGzB,MAAa,qBAAqBC;;AAGlC,MAAa,UAAUC;;AAGvB,MAAa,aAAaC;;AAG1B,MAAa,iBAAiBD;;AAG9B,MAAa,0BAA0BE;;AAGvC,MAAa,oBAAoBC;;AAGjC,MAAa,yBAAyBC;;AAGtC,MAAa,sBAAsBC;;AAGnC,MAAa,yBAAyBC;;AAGtC,MAAa,iCAAiCC;;AAG9C,MAAa,0BAA0BC;;AAGvC,MAAa,sBAAsBC;;AAGnC,MAAa,cAAcC;;AAG3B,MAAa,cAAcC;;AAG3B,MAAa,0BAA0BC;;AAGvC,MAAa,iBAAiBC;;AAG9B,MAAa,gBAAgBC;;AAG7B,MAAa,cAAcC;;AAG3B,MAAa,cAAcC;;AAG3B,MAAa,YAAYC;;AAGzB,MAAa,cAAcC;;AAG3B,MAAa,aAAaC;;AAG1B,MAAa,eAAeC;;AAG5B,MAAa,YAAYC;;AAGzB,MAAa,UAAUX;;AAGvB,MAAa,cAAcY"}
@@ -48,7 +48,7 @@ function chain({ macros, key, node, context }) {
48
48
  const callback = macro[key];
49
49
  if (!callback) continue;
50
50
  if (macro.match && !macro.match(current)) continue;
51
- const next = callback(current, context);
51
+ const next = callback.call(context, current, context);
52
52
  if (next != null) current = next;
53
53
  }
54
54
  return current === node ? void 0 : current;
@@ -101,4 +101,4 @@ var macro_exports = /* @__PURE__ */ __exportAll({
101
101
  });
102
102
  export { defineMacro as i, applyMacros as n, compareMacroOrder as r, macro_exports as t };
103
103
 
104
- //# sourceMappingURL=macro-D0KfNtff.js.map
104
+ //# sourceMappingURL=macro-4N8vHE-2.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"macro-4N8vHE-2.js","names":[],"sources":["../src/defineMacro.ts","../src/macro/index.ts"],"sourcesContent":["import type { Node } from './nodes/index.ts'\nimport type { Visitor, VisitorContext, VisitorDepth, VisitorKey } from './visitor.ts'\nimport { transform, visitorKeys } from './visitor.ts'\n\n/**\n * Ordering hint shared by macros and plugins. `pre` runs before unmarked items, `post` after,\n * and `undefined` keeps declaration order.\n */\nexport type Enforce = 'pre' | 'post'\n\n/**\n * Sort weight for an `enforce` hint. `pre` sorts before unmarked items and `post` after, so a plain\n * list keeps its authored order.\n */\nfunction enforceWeight(enforce?: Enforce): number {\n if (enforce === 'pre') return 0\n if (enforce === 'post') return 2\n return 1\n}\n\n/**\n * Compares two `enforce` hints for `Array.prototype.sort`: `pre` first, unmarked next, `post`\n * last. Equal hints compare as `0`, so a stable sort keeps authored order within a bucket.\n *\n * @example\n * `plugins.sort((a, b) => compareMacroOrder(a.enforce, b.enforce))`\n */\nexport function compareMacroOrder(a?: Enforce, b?: Enforce): number {\n return enforceWeight(a) - enforceWeight(b)\n}\n\n/**\n * The {@link Visitor} callbacks with `this` typed as the {@link VisitorContext}. A macro callback gets\n * the context both as `this` and as its second argument.\n */\ntype MacroCallbacks = {\n [K in VisitorKey]?: (this: VisitorContext, ...args: Parameters<NonNullable<Visitor[K]>>) => ReturnType<NonNullable<Visitor[K]>>\n}\n\n/**\n * A named, composable transform over the Kubb AST. It carries the same per-kind callbacks as a\n * {@link Visitor} (`schema`, `operation`, …), plus a `name`, an optional `enforce` order, and an\n * optional `match` predicate. Macros run on the shared AST, so the same macro works across every\n * adapter and output target. Exports follow the `macro<Name>` convention, mirroring plugins (`pluginTs`).\n */\nexport type Macro = MacroCallbacks & {\n /**\n * Macro identifier used to tell macros apart, for example `'dedupe-union'`.\n */\n name: string\n /**\n * Ordering hint. `pre` macros run before unmarked macros, `post` macros run after.\n * Ordering within a bucket follows list order.\n */\n enforce?: Enforce\n /**\n * Predicate checked against the current node before any callback runs. Returning `false`\n * skips the macro for that node.\n */\n match?: (node: Node) => boolean\n}\n\n/**\n * Types a macro for inference and a single construction site, mirroring `defineExtension`.\n * Adds no runtime behavior.\n *\n * @example\n * ```ts\n * const macroUntagged = defineMacro({\n * name: 'untagged',\n * operation(node) {\n * return node.tags?.length ? undefined : { ...node, tags: ['untagged'] }\n * },\n * })\n * ```\n */\nexport function defineMacro(macro: Macro): Macro {\n return macro\n}\n\ntype MacroCallback = (this: VisitorContext, node: Node, context: VisitorContext) => Node | null | undefined\n\ntype ChainProps = {\n macros: ReadonlyArray<Macro>\n key: VisitorKey\n node: Node\n context: VisitorContext\n}\n\n/**\n * Runs every macro's callback for one node kind in order, chaining the result so each macro sees\n * the previous macro's output. Returns `undefined` when nothing changed, so `transform` keeps the\n * original reference (structural sharing).\n */\nfunction chain({ macros, key, node, context }: ChainProps): Node | undefined {\n let current = node\n\n for (const macro of macros) {\n const callback = macro[key] as MacroCallback | undefined\n if (!callback) continue\n if (macro.match && !macro.match(current)) continue\n\n const next = callback.call(context, current, context)\n if (next != null) current = next\n }\n\n return current === node ? undefined : current\n}\n\n/**\n * Folds an ordered list of macros into a single {@link Visitor} for `transform`. Macros are\n * stable-sorted by `enforce`, then applied sequentially per node so later macros see earlier output.\n */\nfunction composeMacros(macros: ReadonlyArray<Macro>): Visitor {\n const ordered = [...macros].sort((a, b) => compareMacroOrder(a.enforce, b.enforce))\n\n const visitor: Visitor = {}\n for (const key of visitorKeys) {\n if (!ordered.some((macro) => typeof macro[key] === 'function')) continue\n\n const callback = (node: Node, context: VisitorContext) => chain({ macros: ordered, key, node, context })\n ;(visitor as Record<VisitorKey, MacroCallback>)[key] = callback\n }\n\n return visitor\n}\n\n/**\n * Runs a list of macros over a node tree and returns the rewritten tree. Keeps `transform`'s\n * structural sharing, so an empty or no-op macro list returns the same reference. Pass\n * `depth: 'shallow'` to skip the children of every schema node; non-schema nodes, such as an operation's parameters and responses, are still rewritten.\n *\n * @example\n * ```ts\n * const next = applyMacros(root, [macroIntegerToString])\n * ```\n *\n * @example Rewrite a schema without walking its children\n * ```ts\n * const named = applyMacros(node, [macroEnumName({ parentName, propName, enumSuffix })], { depth: 'shallow' })\n * ```\n */\nexport function applyMacros<TNode extends Node>(root: TNode, macros: ReadonlyArray<Macro>, options?: { depth?: VisitorDepth }): TNode {\n if (macros.length === 0) return root\n\n return transform(root, { ...composeMacros(macros), ...options }) as TNode\n}\n","export { applyMacros as apply, compareMacroOrder as compareOrder } from '../defineMacro.ts'\n"],"mappings":";;;;;;;AAcA,SAAS,cAAc,SAA2B;CAChD,IAAI,YAAY,OAAO,OAAO;CAC9B,IAAI,YAAY,QAAQ,OAAO;CAC/B,OAAO;AACT;;;;;;;;AASA,SAAgB,kBAAkB,GAAa,GAAqB;CAClE,OAAO,cAAc,CAAC,IAAI,cAAc,CAAC;AAC3C;;;;;;;;;;;;;;;AA+CA,SAAgB,YAAY,OAAqB;CAC/C,OAAO;AACT;;;;;;AAgBA,SAAS,MAAM,EAAE,QAAQ,KAAK,MAAM,WAAyC;CAC3E,IAAI,UAAU;CAEd,KAAK,MAAM,SAAS,QAAQ;EAC1B,MAAM,WAAW,MAAM;EACvB,IAAI,CAAC,UAAU;EACf,IAAI,MAAM,SAAS,CAAC,MAAM,MAAM,OAAO,GAAG;EAE1C,MAAM,OAAO,SAAS,KAAK,SAAS,SAAS,OAAO;EACpD,IAAI,QAAQ,MAAM,UAAU;CAC9B;CAEA,OAAO,YAAY,OAAO,KAAA,IAAY;AACxC;;;;;AAMA,SAAS,cAAc,QAAuC;CAC5D,MAAM,UAAU,CAAC,GAAG,MAAM,CAAC,CAAC,MAAM,GAAG,MAAM,kBAAkB,EAAE,SAAS,EAAE,OAAO,CAAC;CAElF,MAAM,UAAmB,CAAC;CAC1B,KAAK,MAAM,OAAO,aAAa;EAC7B,IAAI,CAAC,QAAQ,MAAM,UAAU,OAAO,MAAM,SAAS,UAAU,GAAG;EAEhE,MAAM,YAAY,MAAY,YAA4B,MAAM;GAAE,QAAQ;GAAS;GAAK;GAAM;EAAQ,CAAC;EACrG,QAA8C,OAAO;CACzD;CAEA,OAAO;AACT;;;;;;;;;;;;;;;;AAiBA,SAAgB,YAAgC,MAAa,QAA8B,SAA2C;CACpI,IAAI,OAAO,WAAW,GAAG,OAAO;CAEhC,OAAO,UAAU,MAAM;EAAE,GAAG,cAAc,MAAM;EAAG,GAAG;CAAQ,CAAC;AACjE"}
@@ -48,7 +48,7 @@ function chain({ macros, key, node, context }) {
48
48
  const callback = macro[key];
49
49
  if (!callback) continue;
50
50
  if (macro.match && !macro.match(current)) continue;
51
- const next = callback(current, context);
51
+ const next = callback.call(context, current, context);
52
52
  if (next != null) current = next;
53
53
  }
54
54
  return current === node ? void 0 : current;
@@ -124,4 +124,4 @@ Object.defineProperty(exports, "macro_exports", {
124
124
  }
125
125
  });
126
126
 
127
- //# sourceMappingURL=macro-DrTBT7fh.cjs.map
127
+ //# sourceMappingURL=macro-V_cNODx2.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"macro-V_cNODx2.cjs","names":["visitorKeys","transform"],"sources":["../src/defineMacro.ts","../src/macro/index.ts"],"sourcesContent":["import type { Node } from './nodes/index.ts'\nimport type { Visitor, VisitorContext, VisitorDepth, VisitorKey } from './visitor.ts'\nimport { transform, visitorKeys } from './visitor.ts'\n\n/**\n * Ordering hint shared by macros and plugins. `pre` runs before unmarked items, `post` after,\n * and `undefined` keeps declaration order.\n */\nexport type Enforce = 'pre' | 'post'\n\n/**\n * Sort weight for an `enforce` hint. `pre` sorts before unmarked items and `post` after, so a plain\n * list keeps its authored order.\n */\nfunction enforceWeight(enforce?: Enforce): number {\n if (enforce === 'pre') return 0\n if (enforce === 'post') return 2\n return 1\n}\n\n/**\n * Compares two `enforce` hints for `Array.prototype.sort`: `pre` first, unmarked next, `post`\n * last. Equal hints compare as `0`, so a stable sort keeps authored order within a bucket.\n *\n * @example\n * `plugins.sort((a, b) => compareMacroOrder(a.enforce, b.enforce))`\n */\nexport function compareMacroOrder(a?: Enforce, b?: Enforce): number {\n return enforceWeight(a) - enforceWeight(b)\n}\n\n/**\n * The {@link Visitor} callbacks with `this` typed as the {@link VisitorContext}. A macro callback gets\n * the context both as `this` and as its second argument.\n */\ntype MacroCallbacks = {\n [K in VisitorKey]?: (this: VisitorContext, ...args: Parameters<NonNullable<Visitor[K]>>) => ReturnType<NonNullable<Visitor[K]>>\n}\n\n/**\n * A named, composable transform over the Kubb AST. It carries the same per-kind callbacks as a\n * {@link Visitor} (`schema`, `operation`, …), plus a `name`, an optional `enforce` order, and an\n * optional `match` predicate. Macros run on the shared AST, so the same macro works across every\n * adapter and output target. Exports follow the `macro<Name>` convention, mirroring plugins (`pluginTs`).\n */\nexport type Macro = MacroCallbacks & {\n /**\n * Macro identifier used to tell macros apart, for example `'dedupe-union'`.\n */\n name: string\n /**\n * Ordering hint. `pre` macros run before unmarked macros, `post` macros run after.\n * Ordering within a bucket follows list order.\n */\n enforce?: Enforce\n /**\n * Predicate checked against the current node before any callback runs. Returning `false`\n * skips the macro for that node.\n */\n match?: (node: Node) => boolean\n}\n\n/**\n * Types a macro for inference and a single construction site, mirroring `defineExtension`.\n * Adds no runtime behavior.\n *\n * @example\n * ```ts\n * const macroUntagged = defineMacro({\n * name: 'untagged',\n * operation(node) {\n * return node.tags?.length ? undefined : { ...node, tags: ['untagged'] }\n * },\n * })\n * ```\n */\nexport function defineMacro(macro: Macro): Macro {\n return macro\n}\n\ntype MacroCallback = (this: VisitorContext, node: Node, context: VisitorContext) => Node | null | undefined\n\ntype ChainProps = {\n macros: ReadonlyArray<Macro>\n key: VisitorKey\n node: Node\n context: VisitorContext\n}\n\n/**\n * Runs every macro's callback for one node kind in order, chaining the result so each macro sees\n * the previous macro's output. Returns `undefined` when nothing changed, so `transform` keeps the\n * original reference (structural sharing).\n */\nfunction chain({ macros, key, node, context }: ChainProps): Node | undefined {\n let current = node\n\n for (const macro of macros) {\n const callback = macro[key] as MacroCallback | undefined\n if (!callback) continue\n if (macro.match && !macro.match(current)) continue\n\n const next = callback.call(context, current, context)\n if (next != null) current = next\n }\n\n return current === node ? undefined : current\n}\n\n/**\n * Folds an ordered list of macros into a single {@link Visitor} for `transform`. Macros are\n * stable-sorted by `enforce`, then applied sequentially per node so later macros see earlier output.\n */\nfunction composeMacros(macros: ReadonlyArray<Macro>): Visitor {\n const ordered = [...macros].sort((a, b) => compareMacroOrder(a.enforce, b.enforce))\n\n const visitor: Visitor = {}\n for (const key of visitorKeys) {\n if (!ordered.some((macro) => typeof macro[key] === 'function')) continue\n\n const callback = (node: Node, context: VisitorContext) => chain({ macros: ordered, key, node, context })\n ;(visitor as Record<VisitorKey, MacroCallback>)[key] = callback\n }\n\n return visitor\n}\n\n/**\n * Runs a list of macros over a node tree and returns the rewritten tree. Keeps `transform`'s\n * structural sharing, so an empty or no-op macro list returns the same reference. Pass\n * `depth: 'shallow'` to skip the children of every schema node; non-schema nodes, such as an operation's parameters and responses, are still rewritten.\n *\n * @example\n * ```ts\n * const next = applyMacros(root, [macroIntegerToString])\n * ```\n *\n * @example Rewrite a schema without walking its children\n * ```ts\n * const named = applyMacros(node, [macroEnumName({ parentName, propName, enumSuffix })], { depth: 'shallow' })\n * ```\n */\nexport function applyMacros<TNode extends Node>(root: TNode, macros: ReadonlyArray<Macro>, options?: { depth?: VisitorDepth }): TNode {\n if (macros.length === 0) return root\n\n return transform(root, { ...composeMacros(macros), ...options }) as TNode\n}\n","export { applyMacros as apply, compareMacroOrder as compareOrder } from '../defineMacro.ts'\n"],"mappings":";;;;;;;AAcA,SAAS,cAAc,SAA2B;CAChD,IAAI,YAAY,OAAO,OAAO;CAC9B,IAAI,YAAY,QAAQ,OAAO;CAC/B,OAAO;AACT;;;;;;;;AASA,SAAgB,kBAAkB,GAAa,GAAqB;CAClE,OAAO,cAAc,CAAC,IAAI,cAAc,CAAC;AAC3C;;;;;;;;;;;;;;;AA+CA,SAAgB,YAAY,OAAqB;CAC/C,OAAO;AACT;;;;;;AAgBA,SAAS,MAAM,EAAE,QAAQ,KAAK,MAAM,WAAyC;CAC3E,IAAI,UAAU;CAEd,KAAK,MAAM,SAAS,QAAQ;EAC1B,MAAM,WAAW,MAAM;EACvB,IAAI,CAAC,UAAU;EACf,IAAI,MAAM,SAAS,CAAC,MAAM,MAAM,OAAO,GAAG;EAE1C,MAAM,OAAO,SAAS,KAAK,SAAS,SAAS,OAAO;EACpD,IAAI,QAAQ,MAAM,UAAU;CAC9B;CAEA,OAAO,YAAY,OAAO,KAAA,IAAY;AACxC;;;;;AAMA,SAAS,cAAc,QAAuC;CAC5D,MAAM,UAAU,CAAC,GAAG,MAAM,CAAC,CAAC,MAAM,GAAG,MAAM,kBAAkB,EAAE,SAAS,EAAE,OAAO,CAAC;CAElF,MAAM,UAAmB,CAAC;CAC1B,KAAK,MAAM,OAAOA,gBAAAA,aAAa;EAC7B,IAAI,CAAC,QAAQ,MAAM,UAAU,OAAO,MAAM,SAAS,UAAU,GAAG;EAEhE,MAAM,YAAY,MAAY,YAA4B,MAAM;GAAE,QAAQ;GAAS;GAAK;GAAM;EAAQ,CAAC;EACrG,QAA8C,OAAO;CACzD;CAEA,OAAO;AACT;;;;;;;;;;;;;;;;AAiBA,SAAgB,YAAgC,MAAa,QAA8B,SAA2C;CACpI,IAAI,OAAO,WAAW,GAAG,OAAO;CAEhC,OAAOC,gBAAAA,UAAU,MAAM;EAAE,GAAG,cAAc,MAAM;EAAG,GAAG;CAAQ,CAAC;AACjE"}
package/dist/macro.cjs CHANGED
@@ -1,4 +1,4 @@
1
1
  Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
- const require_macro = require("./macro-DrTBT7fh.cjs");
2
+ const require_macro = require("./macro-V_cNODx2.cjs");
3
3
  exports.apply = require_macro.applyMacros;
4
4
  exports.compareOrder = require_macro.compareMacroOrder;
package/dist/macro.d.cts CHANGED
@@ -1,2 +1,2 @@
1
- import { a as compareMacroOrder, i as applyMacros } from "./index-CIqwy4EE.cjs";
1
+ import { a as compareMacroOrder, i as applyMacros } from "./index-CwLhqYbA.cjs";
2
2
  export { applyMacros as apply, compareMacroOrder as compareOrder };
package/dist/macro.d.ts CHANGED
@@ -1,2 +1,2 @@
1
- import { a as compareMacroOrder, i as applyMacros } from "./index-CAGuKv6t.js";
1
+ import { a as compareMacroOrder, i as applyMacros } from "./index-BSf-ETQP.js";
2
2
  export { applyMacros as apply, compareMacroOrder as compareOrder };
package/dist/macro.js CHANGED
@@ -1 +1 @@
1
- export { n as apply, r as compareOrder } from "./macro-D0KfNtff.js";
1
+ export { n as apply, r as compareOrder } from "./macro-4N8vHE-2.js";
package/dist/node.d.cts CHANGED
@@ -1,4 +1,4 @@
1
1
  import { i as nodeKinds } from "./base-IpYuh3ZP.cjs";
2
- import { i as collect, o as transform } from "./visitor-Bw_opzjF.cjs";
3
- import { n as getNodeText } from "./index-BngGJux5.cjs";
2
+ import { a as collect, s as transform } from "./visitor-CUbaaX8R.cjs";
3
+ import { n as getNodeText } from "./index-BVuX3-Th.cjs";
4
4
  export { collect, getNodeText as getText, nodeKinds as kinds, transform };
package/dist/node.d.ts CHANGED
@@ -1,4 +1,4 @@
1
1
  import { i as nodeKinds } from "./base-IpYuh3ZP.js";
2
- import { i as collect, o as transform } from "./visitor-BZozlXBF.js";
3
- import { n as getNodeText } from "./index-D3M2spDR.js";
2
+ import { a as collect, s as transform } from "./visitor-1TSWTMe1.js";
3
+ import { n as getNodeText } from "./index-CoRdlrVx.js";
4
4
  export { collect, getNodeText as getText, nodeKinds as kinds, transform };
package/dist/schema.d.cts CHANGED
@@ -1,5 +1,5 @@
1
1
  import { a as schemaTypes } from "./base-IpYuh3ZP.cjs";
2
2
  import { n as narrowSchema } from "./guards-B8qDgSaT.cjs";
3
- import { a as resolveSchemaProperties, c as SchemaKind, d as applyOptionality, i as inferDiscriminatorPropertyName, l as is, n as isString, o as IsOptions, r as getSchemaLiteralValues, s as SchemaFollow, u as getEmbeddedJson } from "./index-C-vhkzwR.cjs";
4
- import { a as findSchema } from "./visitor-Bw_opzjF.cjs";
3
+ import { a as resolveSchemaProperties, c as SchemaKind, d as applyOptionality, i as inferDiscriminatorPropertyName, l as is, n as isString, o as IsOptions, r as getSchemaLiteralValues, s as SchemaFollow, u as getEmbeddedJson } from "./index-DKJdlX1l.cjs";
4
+ import { o as findSchema } from "./visitor-CUbaaX8R.cjs";
5
5
  export { type IsOptions, type SchemaFollow, type SchemaKind, applyOptionality, findSchema as find, resolveSchemaProperties as findProperties, getEmbeddedJson, getSchemaLiteralValues as getLiterals, inferDiscriminatorPropertyName as inferDiscriminator, is, isString, narrowSchema as narrow, schemaTypes as types };
package/dist/schema.d.ts CHANGED
@@ -1,5 +1,5 @@
1
1
  import { a as schemaTypes } from "./base-IpYuh3ZP.js";
2
2
  import { n as narrowSchema } from "./guards-D-h9R_sV.js";
3
- import { a as resolveSchemaProperties, c as SchemaKind, d as applyOptionality, i as inferDiscriminatorPropertyName, l as is, n as isString, o as IsOptions, r as getSchemaLiteralValues, s as SchemaFollow, u as getEmbeddedJson } from "./index-DNiIem0x.js";
4
- import { a as findSchema } from "./visitor-BZozlXBF.js";
3
+ import { a as resolveSchemaProperties, c as SchemaKind, d as applyOptionality, i as inferDiscriminatorPropertyName, l as is, n as isString, o as IsOptions, r as getSchemaLiteralValues, s as SchemaFollow, u as getEmbeddedJson } from "./index-W6yFx0sy.js";
4
+ import { o as findSchema } from "./visitor-1TSWTMe1.js";
5
5
  export { type IsOptions, type SchemaFollow, type SchemaKind, applyOptionality, findSchema as find, resolveSchemaProperties as findProperties, getEmbeddedJson, getSchemaLiteralValues as getLiterals, inferDiscriminatorPropertyName as inferDiscriminator, is, isString, narrowSchema as narrow, schemaTypes as types };
@@ -8,6 +8,9 @@ import { H as SchemaNode, T as InputNode, X as PropertyNode, i as OperationNode,
8
8
  * - `'deep'` recursively visits all descendant nodes, including schema subtrees.
9
9
  */
10
10
  type VisitorDepth = 'shallow' | 'deep';
11
+ /** Visitor callback names in traversal order, the keys of {@link Visitor}. */
12
+ declare const visitorKeys: readonly ['input', 'operation', 'schema', 'property', 'parameter', 'response'];
13
+ type VisitorKey = (typeof visitorKeys)[number];
11
14
  /**
12
15
  * Traversal context passed as the second argument to every visitor callback.
13
16
  *
@@ -176,4 +179,4 @@ declare function transform<T extends Node>(node: T, options: TransformOptions):
176
179
  * ```
177
180
  */
178
181
  declare function collect<T>(node: Node, options: CollectOptions<T>): Array<T>;
179
- export { findSchema as a, collect as i, VisitorContext as n, transform as o, VisitorDepth as r, Visitor as t };
182
+ export { collect as a, VisitorKey as i, VisitorContext as n, findSchema as o, VisitorDepth as r, transform as s, Visitor as t };
@@ -8,6 +8,9 @@ import { H as SchemaNode, T as InputNode, X as PropertyNode, i as OperationNode,
8
8
  * - `'deep'` recursively visits all descendant nodes, including schema subtrees.
9
9
  */
10
10
  type VisitorDepth = 'shallow' | 'deep';
11
+ /** Visitor callback names in traversal order, the keys of {@link Visitor}. */
12
+ declare const visitorKeys: readonly ['input', 'operation', 'schema', 'property', 'parameter', 'response'];
13
+ type VisitorKey = (typeof visitorKeys)[number];
11
14
  /**
12
15
  * Traversal context passed as the second argument to every visitor callback.
13
16
  *
@@ -176,4 +179,4 @@ declare function transform<T extends Node>(node: T, options: TransformOptions):
176
179
  * ```
177
180
  */
178
181
  declare function collect<T>(node: Node, options: CollectOptions<T>): Array<T>;
179
- export { findSchema as a, collect as i, VisitorContext as n, transform as o, VisitorDepth as r, Visitor as t };
182
+ export { collect as a, VisitorKey as i, VisitorContext as n, findSchema as o, VisitorDepth as r, transform as s, Visitor as t };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@kubb/ast",
3
- "version": "5.23.1",
3
+ "version": "5.23.2",
4
4
  "description": "Spec-agnostic AST layer for Kubb. Defines the node tree, visitor pattern, factory functions, and type guards used across all code generation plugins.",
5
5
  "keywords": [
6
6
  "ast",
@@ -1 +0,0 @@
1
- {"version":3,"file":"macro-D0KfNtff.js","names":[],"sources":["../src/defineMacro.ts","../src/macro/index.ts"],"sourcesContent":["import type { Node } from './nodes/index.ts'\nimport type { Visitor, VisitorContext, VisitorDepth, VisitorKey } from './visitor.ts'\nimport { transform, visitorKeys } from './visitor.ts'\n\n/**\n * Ordering hint shared by macros and plugins. `pre` runs before unmarked items, `post` after,\n * and `undefined` keeps declaration order.\n */\nexport type Enforce = 'pre' | 'post'\n\n/**\n * Sort weight for an `enforce` hint. `pre` sorts before unmarked items and `post` after, so a plain\n * list keeps its authored order.\n */\nfunction enforceWeight(enforce?: Enforce): number {\n if (enforce === 'pre') return 0\n if (enforce === 'post') return 2\n return 1\n}\n\n/**\n * Compares two `enforce` hints for `Array.prototype.sort`: `pre` first, unmarked next, `post`\n * last. Equal hints compare as `0`, so a stable sort keeps authored order within a bucket.\n *\n * @example\n * `plugins.sort((a, b) => compareMacroOrder(a.enforce, b.enforce))`\n */\nexport function compareMacroOrder(a?: Enforce, b?: Enforce): number {\n return enforceWeight(a) - enforceWeight(b)\n}\n\n/**\n * A named, composable transform over the Kubb AST. It carries the same per-kind callbacks as a\n * {@link Visitor} (`schema`, `operation`, …), plus a `name`, an optional `enforce` order, and an\n * optional `match` predicate. Macros run on the shared AST, so the same macro works across every\n * adapter and output target. Exports follow the `macro<Name>` convention, mirroring plugins (`pluginTs`).\n */\nexport type Macro = Visitor & {\n /**\n * Macro identifier used to tell macros apart, for example `'dedupe-union'`.\n */\n name: string\n /**\n * Ordering hint. `pre` macros run before unmarked macros, `post` macros run after.\n * Ordering within a bucket follows list order.\n */\n enforce?: Enforce\n /**\n * Predicate checked against the current node before any callback runs. Returning `false`\n * skips the macro for that node.\n */\n match?: (node: Node) => boolean\n}\n\n/**\n * Types a macro for inference and a single construction site, mirroring `defineExtension`.\n * Adds no runtime behavior.\n *\n * @example\n * ```ts\n * const macroUntagged = defineMacro({\n * name: 'untagged',\n * operation(node) {\n * return node.tags?.length ? undefined : { ...node, tags: ['untagged'] }\n * },\n * })\n * ```\n */\nexport function defineMacro(macro: Macro): Macro {\n return macro\n}\n\ntype MacroCallback = (node: Node, context: VisitorContext) => Node | null | undefined\n\ntype ChainProps = {\n macros: ReadonlyArray<Macro>\n key: VisitorKey\n node: Node\n context: VisitorContext\n}\n\n/**\n * Runs every macro's callback for one node kind in order, chaining the result so each macro sees\n * the previous macro's output. Returns `undefined` when nothing changed, so `transform` keeps the\n * original reference (structural sharing).\n */\nfunction chain({ macros, key, node, context }: ChainProps): Node | undefined {\n let current = node\n\n for (const macro of macros) {\n const callback = macro[key] as MacroCallback | undefined\n if (!callback) continue\n if (macro.match && !macro.match(current)) continue\n\n const next = callback(current, context)\n if (next != null) current = next\n }\n\n return current === node ? undefined : current\n}\n\n/**\n * Folds an ordered list of macros into a single {@link Visitor} for `transform`. Macros are\n * stable-sorted by `enforce`, then applied sequentially per node so later macros see earlier output.\n */\nfunction composeMacros(macros: ReadonlyArray<Macro>): Visitor {\n const ordered = [...macros].sort((a, b) => compareMacroOrder(a.enforce, b.enforce))\n\n const visitor: Visitor = {}\n for (const key of visitorKeys) {\n if (!ordered.some((macro) => typeof macro[key] === 'function')) continue\n\n const callback = (node: Node, context: VisitorContext) => chain({ macros: ordered, key, node, context })\n ;(visitor as Record<VisitorKey, MacroCallback>)[key] = callback\n }\n\n return visitor\n}\n\n/**\n * Runs a list of macros over a node tree and returns the rewritten tree. Keeps `transform`'s\n * structural sharing, so an empty or no-op macro list returns the same reference. Pass\n * `depth: 'shallow'` to skip the children of every schema node; non-schema nodes, such as an operation's parameters and responses, are still rewritten.\n *\n * @example\n * ```ts\n * const next = applyMacros(root, [macroIntegerToString])\n * ```\n *\n * @example Rewrite a schema without walking its children\n * ```ts\n * const named = applyMacros(node, [macroEnumName({ parentName, propName, enumSuffix })], { depth: 'shallow' })\n * ```\n */\nexport function applyMacros<TNode extends Node>(root: TNode, macros: ReadonlyArray<Macro>, options?: { depth?: VisitorDepth }): TNode {\n if (macros.length === 0) return root\n\n return transform(root, { ...composeMacros(macros), ...options }) as TNode\n}\n","export { applyMacros as apply, compareMacroOrder as compareOrder } from '../defineMacro.ts'\n"],"mappings":";;;;;;;AAcA,SAAS,cAAc,SAA2B;CAChD,IAAI,YAAY,OAAO,OAAO;CAC9B,IAAI,YAAY,QAAQ,OAAO;CAC/B,OAAO;AACT;;;;;;;;AASA,SAAgB,kBAAkB,GAAa,GAAqB;CAClE,OAAO,cAAc,CAAC,IAAI,cAAc,CAAC;AAC3C;;;;;;;;;;;;;;;AAuCA,SAAgB,YAAY,OAAqB;CAC/C,OAAO;AACT;;;;;;AAgBA,SAAS,MAAM,EAAE,QAAQ,KAAK,MAAM,WAAyC;CAC3E,IAAI,UAAU;CAEd,KAAK,MAAM,SAAS,QAAQ;EAC1B,MAAM,WAAW,MAAM;EACvB,IAAI,CAAC,UAAU;EACf,IAAI,MAAM,SAAS,CAAC,MAAM,MAAM,OAAO,GAAG;EAE1C,MAAM,OAAO,SAAS,SAAS,OAAO;EACtC,IAAI,QAAQ,MAAM,UAAU;CAC9B;CAEA,OAAO,YAAY,OAAO,KAAA,IAAY;AACxC;;;;;AAMA,SAAS,cAAc,QAAuC;CAC5D,MAAM,UAAU,CAAC,GAAG,MAAM,CAAC,CAAC,MAAM,GAAG,MAAM,kBAAkB,EAAE,SAAS,EAAE,OAAO,CAAC;CAElF,MAAM,UAAmB,CAAC;CAC1B,KAAK,MAAM,OAAO,aAAa;EAC7B,IAAI,CAAC,QAAQ,MAAM,UAAU,OAAO,MAAM,SAAS,UAAU,GAAG;EAEhE,MAAM,YAAY,MAAY,YAA4B,MAAM;GAAE,QAAQ;GAAS;GAAK;GAAM;EAAQ,CAAC;EACrG,QAA8C,OAAO;CACzD;CAEA,OAAO;AACT;;;;;;;;;;;;;;;;AAiBA,SAAgB,YAAgC,MAAa,QAA8B,SAA2C;CACpI,IAAI,OAAO,WAAW,GAAG,OAAO;CAEhC,OAAO,UAAU,MAAM;EAAE,GAAG,cAAc,MAAM;EAAG,GAAG;CAAQ,CAAC;AACjE"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"macro-DrTBT7fh.cjs","names":["visitorKeys","transform"],"sources":["../src/defineMacro.ts","../src/macro/index.ts"],"sourcesContent":["import type { Node } from './nodes/index.ts'\nimport type { Visitor, VisitorContext, VisitorDepth, VisitorKey } from './visitor.ts'\nimport { transform, visitorKeys } from './visitor.ts'\n\n/**\n * Ordering hint shared by macros and plugins. `pre` runs before unmarked items, `post` after,\n * and `undefined` keeps declaration order.\n */\nexport type Enforce = 'pre' | 'post'\n\n/**\n * Sort weight for an `enforce` hint. `pre` sorts before unmarked items and `post` after, so a plain\n * list keeps its authored order.\n */\nfunction enforceWeight(enforce?: Enforce): number {\n if (enforce === 'pre') return 0\n if (enforce === 'post') return 2\n return 1\n}\n\n/**\n * Compares two `enforce` hints for `Array.prototype.sort`: `pre` first, unmarked next, `post`\n * last. Equal hints compare as `0`, so a stable sort keeps authored order within a bucket.\n *\n * @example\n * `plugins.sort((a, b) => compareMacroOrder(a.enforce, b.enforce))`\n */\nexport function compareMacroOrder(a?: Enforce, b?: Enforce): number {\n return enforceWeight(a) - enforceWeight(b)\n}\n\n/**\n * A named, composable transform over the Kubb AST. It carries the same per-kind callbacks as a\n * {@link Visitor} (`schema`, `operation`, …), plus a `name`, an optional `enforce` order, and an\n * optional `match` predicate. Macros run on the shared AST, so the same macro works across every\n * adapter and output target. Exports follow the `macro<Name>` convention, mirroring plugins (`pluginTs`).\n */\nexport type Macro = Visitor & {\n /**\n * Macro identifier used to tell macros apart, for example `'dedupe-union'`.\n */\n name: string\n /**\n * Ordering hint. `pre` macros run before unmarked macros, `post` macros run after.\n * Ordering within a bucket follows list order.\n */\n enforce?: Enforce\n /**\n * Predicate checked against the current node before any callback runs. Returning `false`\n * skips the macro for that node.\n */\n match?: (node: Node) => boolean\n}\n\n/**\n * Types a macro for inference and a single construction site, mirroring `defineExtension`.\n * Adds no runtime behavior.\n *\n * @example\n * ```ts\n * const macroUntagged = defineMacro({\n * name: 'untagged',\n * operation(node) {\n * return node.tags?.length ? undefined : { ...node, tags: ['untagged'] }\n * },\n * })\n * ```\n */\nexport function defineMacro(macro: Macro): Macro {\n return macro\n}\n\ntype MacroCallback = (node: Node, context: VisitorContext) => Node | null | undefined\n\ntype ChainProps = {\n macros: ReadonlyArray<Macro>\n key: VisitorKey\n node: Node\n context: VisitorContext\n}\n\n/**\n * Runs every macro's callback for one node kind in order, chaining the result so each macro sees\n * the previous macro's output. Returns `undefined` when nothing changed, so `transform` keeps the\n * original reference (structural sharing).\n */\nfunction chain({ macros, key, node, context }: ChainProps): Node | undefined {\n let current = node\n\n for (const macro of macros) {\n const callback = macro[key] as MacroCallback | undefined\n if (!callback) continue\n if (macro.match && !macro.match(current)) continue\n\n const next = callback(current, context)\n if (next != null) current = next\n }\n\n return current === node ? undefined : current\n}\n\n/**\n * Folds an ordered list of macros into a single {@link Visitor} for `transform`. Macros are\n * stable-sorted by `enforce`, then applied sequentially per node so later macros see earlier output.\n */\nfunction composeMacros(macros: ReadonlyArray<Macro>): Visitor {\n const ordered = [...macros].sort((a, b) => compareMacroOrder(a.enforce, b.enforce))\n\n const visitor: Visitor = {}\n for (const key of visitorKeys) {\n if (!ordered.some((macro) => typeof macro[key] === 'function')) continue\n\n const callback = (node: Node, context: VisitorContext) => chain({ macros: ordered, key, node, context })\n ;(visitor as Record<VisitorKey, MacroCallback>)[key] = callback\n }\n\n return visitor\n}\n\n/**\n * Runs a list of macros over a node tree and returns the rewritten tree. Keeps `transform`'s\n * structural sharing, so an empty or no-op macro list returns the same reference. Pass\n * `depth: 'shallow'` to skip the children of every schema node; non-schema nodes, such as an operation's parameters and responses, are still rewritten.\n *\n * @example\n * ```ts\n * const next = applyMacros(root, [macroIntegerToString])\n * ```\n *\n * @example Rewrite a schema without walking its children\n * ```ts\n * const named = applyMacros(node, [macroEnumName({ parentName, propName, enumSuffix })], { depth: 'shallow' })\n * ```\n */\nexport function applyMacros<TNode extends Node>(root: TNode, macros: ReadonlyArray<Macro>, options?: { depth?: VisitorDepth }): TNode {\n if (macros.length === 0) return root\n\n return transform(root, { ...composeMacros(macros), ...options }) as TNode\n}\n","export { applyMacros as apply, compareMacroOrder as compareOrder } from '../defineMacro.ts'\n"],"mappings":";;;;;;;AAcA,SAAS,cAAc,SAA2B;CAChD,IAAI,YAAY,OAAO,OAAO;CAC9B,IAAI,YAAY,QAAQ,OAAO;CAC/B,OAAO;AACT;;;;;;;;AASA,SAAgB,kBAAkB,GAAa,GAAqB;CAClE,OAAO,cAAc,CAAC,IAAI,cAAc,CAAC;AAC3C;;;;;;;;;;;;;;;AAuCA,SAAgB,YAAY,OAAqB;CAC/C,OAAO;AACT;;;;;;AAgBA,SAAS,MAAM,EAAE,QAAQ,KAAK,MAAM,WAAyC;CAC3E,IAAI,UAAU;CAEd,KAAK,MAAM,SAAS,QAAQ;EAC1B,MAAM,WAAW,MAAM;EACvB,IAAI,CAAC,UAAU;EACf,IAAI,MAAM,SAAS,CAAC,MAAM,MAAM,OAAO,GAAG;EAE1C,MAAM,OAAO,SAAS,SAAS,OAAO;EACtC,IAAI,QAAQ,MAAM,UAAU;CAC9B;CAEA,OAAO,YAAY,OAAO,KAAA,IAAY;AACxC;;;;;AAMA,SAAS,cAAc,QAAuC;CAC5D,MAAM,UAAU,CAAC,GAAG,MAAM,CAAC,CAAC,MAAM,GAAG,MAAM,kBAAkB,EAAE,SAAS,EAAE,OAAO,CAAC;CAElF,MAAM,UAAmB,CAAC;CAC1B,KAAK,MAAM,OAAOA,gBAAAA,aAAa;EAC7B,IAAI,CAAC,QAAQ,MAAM,UAAU,OAAO,MAAM,SAAS,UAAU,GAAG;EAEhE,MAAM,YAAY,MAAY,YAA4B,MAAM;GAAE,QAAQ;GAAS;GAAK;GAAM;EAAQ,CAAC;EACrG,QAA8C,OAAO;CACzD;CAEA,OAAO;AACT;;;;;;;;;;;;;;;;AAiBA,SAAgB,YAAgC,MAAa,QAA8B,SAA2C;CACpI,IAAI,OAAO,WAAW,GAAG,OAAO;CAEhC,OAAOC,gBAAAA,UAAU,MAAM;EAAE,GAAG,cAAc,MAAM;EAAG,GAAG;CAAQ,CAAC;AACjE"}