@kubb/core 5.0.0-beta.93 → 5.0.0-beta.95

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/mocks.cjs CHANGED
@@ -43,18 +43,14 @@ function createMockedPluginDriver(options = {}) {
43
43
  /**
44
44
  * Creates a minimal `Adapter` mock for unit tests.
45
45
  * `parse` returns an empty `InputNode` by default. Override via `options.parse`.
46
- * `getImports` returns `[]` by default.
47
46
  */
48
47
  function createMockedAdapter(options = {}) {
49
48
  return {
50
49
  name: options.name ?? "oas",
51
50
  options: options.resolvedOptions ?? {},
52
- parse: options.parse ?? (async () => ({
53
- kind: "Input",
54
- schemas: [],
55
- operations: []
56
- })),
57
- getImports: options.getImports ?? ((_node, _resolve) => [])
51
+ document: null,
52
+ parse: options.parse ?? (async () => _kubb_ast.ast.factory.createInput()),
53
+ validate: async () => {}
58
54
  };
59
55
  }
60
56
  /**
@@ -89,7 +85,7 @@ function createMockedPluginContext(opts) {
89
85
  },
90
86
  addFile: async (...files) => opts.driver.fileManager.add(...files),
91
87
  upsertFile: async (...files) => opts.driver.fileManager.upsert(...files),
92
- hooks: opts.driver.hooks ?? {},
88
+ hooks: opts.driver.hooks ?? new require_usingCtx.Hookable(),
93
89
  warn: (msg) => console.warn(msg),
94
90
  error: (msg) => console.error(msg),
95
91
  info: (msg) => console.info(msg)
@@ -1 +1 @@
1
- {"version":3,"file":"mocks.cjs","names":["FileManager","path","camelCase"],"sources":["../src/mocks.ts"],"sourcesContent":["import path, { resolve } from 'node:path'\nimport { camelCase } from '@internals/utils'\nimport type { FileNode, InputMeta, Macro, OperationNode, SchemaNode } from '@kubb/ast'\nimport { applyMacros } from '@kubb/ast'\nimport { expect } from 'vitest'\nimport type { Parser } from './defineParser.ts'\nimport { FileManager } from './FileManager.ts'\nimport type { KubbDriver } from './KubbDriver.ts'\nimport type { Adapter, AdapterFactoryOptions, Config, Generator, GeneratorContext, NormalizedPlugin, PluginFactoryOptions, RendererFactory } from './types.ts'\n\n/**\n * Creates a minimal `KubbDriver` mock for unit tests.\n */\nexport function createMockedPluginDriver(options: { name?: string; plugin?: NormalizedPlugin; config?: Config } = {}): KubbDriver {\n const fileManager = new FileManager()\n\n return {\n config: options?.config ?? {\n root: '.',\n output: {\n path: './path',\n },\n },\n getPlugin(_pluginName: string): NormalizedPlugin | undefined {\n return options?.plugin\n },\n getResolver: (_pluginName: string) => options?.plugin?.resolver,\n fileManager,\n async dispatch({ result, renderer }: { result: unknown; renderer?: RendererFactory | null }): Promise<void> {\n if (!result) return\n\n if (Array.isArray(result)) {\n fileManager.upsert(...(result as Array<FileNode>))\n return\n }\n\n if (!renderer) return\n\n using instance = renderer()\n await instance.render(result)\n fileManager.upsert(...instance.files)\n },\n } as unknown as KubbDriver\n}\n\n/**\n * Creates a minimal `Adapter` mock for unit tests.\n * `parse` returns an empty `InputNode` by default. Override via `options.parse`.\n * `getImports` returns `[]` by default.\n */\nexport function createMockedAdapter<TOptions extends AdapterFactoryOptions = AdapterFactoryOptions>(\n options: {\n name?: TOptions['name']\n resolvedOptions?: TOptions['resolvedOptions']\n parse?: Adapter<TOptions>['parse']\n getImports?: Adapter<TOptions>['getImports']\n } = {},\n): Adapter<TOptions> {\n return {\n name: (options.name ?? 'oas') as TOptions['name'],\n options: (options.resolvedOptions ?? {}) as TOptions['resolvedOptions'],\n parse: options.parse ?? (async () => ({ kind: 'Input' as const, schemas: [], operations: [] })),\n getImports: options.getImports ?? ((_node: SchemaNode, _resolve: (schemaName: string) => { name: string; path: string }) => []),\n } as Adapter<TOptions>\n}\n\n/**\n * Creates a minimal plugin mock for unit tests.\n *\n * @example\n * `const plugin = createMockedPlugin<PluginTs>({ name: '@kubb/plugin-ts', options })`\n */\nexport function createMockedPlugin<TOptions extends PluginFactoryOptions = PluginFactoryOptions>(params: {\n name: TOptions['name']\n options: TOptions['resolvedOptions']\n resolver?: TOptions['resolver']\n macros?: Array<Macro>\n dependencies?: Array<string>\n}): NormalizedPlugin<TOptions> {\n return {\n name: params.name,\n options: params.options,\n resolver: params.resolver,\n macros: params.macros,\n dependencies: params.dependencies,\n hooks: {},\n } as unknown as NormalizedPlugin<TOptions>\n}\n\ntype RenderGeneratorOptions<TOptions extends PluginFactoryOptions> = {\n config: Config\n adapter: Adapter\n meta?: InputMeta\n driver: KubbDriver\n plugin: NormalizedPlugin<TOptions>\n options: TOptions['resolvedOptions']\n resolver: TOptions['resolver']\n}\n\nfunction createMockedPluginContext<TOptions extends PluginFactoryOptions>(opts: RenderGeneratorOptions<TOptions>): Omit<GeneratorContext<TOptions>, 'options'> {\n const root = resolve(opts.config.root, opts.config.output.path)\n\n return {\n config: opts.config,\n root,\n adapter: opts.adapter,\n resolver: opts.resolver,\n plugin: opts.plugin,\n driver: opts.driver,\n getResolver: (name: string) => opts.driver.getResolver(name),\n meta: opts.meta ?? { circularNames: [], enumNames: [] },\n addFile: async (...files: Array<FileNode>) => opts.driver.fileManager.add(...files),\n upsertFile: async (...files: Array<FileNode>) => opts.driver.fileManager.upsert(...files),\n hooks: opts.driver.hooks ?? ({} as never),\n warn: (msg: string) => console.warn(msg),\n error: (msg: string) => console.error(msg),\n info: (msg: string) => console.info(msg),\n } as unknown as Omit<GeneratorContext<TOptions>, 'options'>\n}\n\n/**\n * Renders a generator's `schema` method in a test context.\n *\n * @example\n * ```ts\n * await renderGeneratorSchema(typeGenerator, node, { config, adapter, driver, plugin, options, resolver })\n * await matchFiles(driver.fileManager.files)\n * ```\n */\nexport async function renderGeneratorSchema<TOptions extends PluginFactoryOptions>(\n generator: Generator<TOptions>,\n node: SchemaNode,\n opts: RenderGeneratorOptions<TOptions>,\n): Promise<void> {\n if (!generator.schema) return\n const context = createMockedPluginContext(opts)\n const transformedNode = opts.plugin.macros?.length ? applyMacros(node, opts.plugin.macros) : node\n const result = await generator.schema(transformedNode, {\n ...context,\n options: opts.options,\n })\n await opts.driver.dispatch({ result, renderer: generator.renderer })\n}\n\n/**\n * Renders a generator's `operation` method in a test context.\n *\n * @example\n * ```ts\n * await renderGeneratorOperation(typeGenerator, node, { config, adapter, driver, plugin, options, resolver })\n * await matchFiles(driver.fileManager.files)\n * ```\n */\nexport async function renderGeneratorOperation<TOptions extends PluginFactoryOptions>(\n generator: Generator<TOptions>,\n node: OperationNode,\n opts: RenderGeneratorOptions<TOptions>,\n): Promise<void> {\n if (!generator.operation) return\n const context = createMockedPluginContext(opts)\n const transformedNode = opts.plugin.macros?.length ? applyMacros(node, opts.plugin.macros) : node\n const result = await generator.operation(transformedNode, {\n ...context,\n options: opts.options,\n })\n await opts.driver.dispatch({ result, renderer: generator.renderer })\n}\n\n/**\n * Renders a generator's `operations` method in a test context.\n *\n * @example\n * ```ts\n * await renderGeneratorOperations(classClientGenerator, nodes, { config, adapter, driver, plugin, options, resolver })\n * await matchFiles(driver.fileManager.files)\n * ```\n */\nexport async function renderGeneratorOperations<TOptions extends PluginFactoryOptions>(\n generator: Generator<TOptions>,\n nodes: Array<OperationNode>,\n opts: RenderGeneratorOptions<TOptions>,\n): Promise<void> {\n if (!generator.operations) return\n const context = createMockedPluginContext(opts)\n const transformedNodes = opts.plugin.macros?.length ? nodes.map((n) => applyMacros(n, opts.plugin.macros!)) : nodes\n const result = await generator.operations(transformedNodes, {\n ...context,\n options: opts.options,\n })\n await opts.driver.dispatch({ result, renderer: generator.renderer })\n}\n\ntype MatchFilesOptions = {\n /**\n * Parsers indexed by file extension, used to render each `FileNode` to source.\n * Without a matching parser the file's raw content is used.\n */\n parsers?: Map<FileNode['extname'], Parser>\n /**\n * Formatter applied to non-JSON output before snapshotting, e.g. prettier. When\n * omitted the parsed source is snapshotted as-is.\n */\n format?: (source?: string) => string | Promise<string>\n /**\n * Subfolder under `__snapshots__`, camelCased. Useful to keep variant snapshots apart.\n */\n pre?: string\n}\n\n/**\n * Renders the driver's collected `FileNode`s to source and asserts each against a file snapshot.\n * Pair it with the `renderGenerator*` helpers to snapshot a generator's output.\n *\n * @example\n * ```ts\n * await renderGeneratorSchema(typeGenerator, node, { config, adapter, driver, plugin, options, resolver })\n * await matchFiles(driver.fileManager.files, { parsers, format })\n * ```\n */\nexport async function matchFiles(files: Array<FileNode> | undefined, options: MatchFilesOptions = {}): Promise<Map<string, string> | undefined> {\n if (!files?.length) return\n\n const { parsers = new Map(), format, pre } = options\n const fileManager = new FileManager()\n const processed = new Map<string, string>()\n\n for (const file of files) {\n if (!file?.path || processed.has(file.path)) {\n continue\n }\n\n const parsed = await fileManager.parse(file, { parsers })\n const code = file.baseName.endsWith('.json') || !format ? parsed : await format(parsed)\n\n processed.set(file.path, code)\n\n const snapshotPath = path.join('__snapshots__', ...(pre ? [camelCase(pre)] : []), file.baseName)\n await expect(code).toMatchFileSnapshot(snapshotPath)\n }\n\n return processed\n}\n"],"mappings":";;;;;;;;;;AAaA,SAAgB,yBAAyB,UAAyE,CAAC,GAAe;CAChI,MAAM,cAAc,IAAIA,iBAAAA,YAAY;CAEpC,OAAO;EACL,QAAQ,SAAS,UAAU;GACzB,MAAM;GACN,QAAQ,EACN,MAAM,SACR;EACF;EACA,UAAU,aAAmD;GAC3D,OAAO,SAAS;EAClB;EACA,cAAc,gBAAwB,SAAS,QAAQ;EACvD;EACA,MAAM,SAAS,EAAE,QAAQ,YAAmF;;;IAC1G,IAAI,CAAC,QAAQ;IAEb,IAAI,MAAM,QAAQ,MAAM,GAAG;KACzB,YAAY,OAAO,GAAI,MAA0B;KACjD;IACF;IAEA,IAAI,CAAC,UAAU;IAEf,MAAM,WAAA,YAAA,EAAW,SAAS,CAAA;IAC1B,MAAM,SAAS,OAAO,MAAM;IAC5B,YAAY,OAAO,GAAG,SAAS,KAAK;;;;;;EACtC;CACF;AACF;;;;;;AAOA,SAAgB,oBACd,UAKI,CAAC,GACc;CACnB,OAAO;EACL,MAAO,QAAQ,QAAQ;EACvB,SAAU,QAAQ,mBAAmB,CAAC;EACtC,OAAO,QAAQ,UAAU,aAAa;GAAE,MAAM;GAAkB,SAAS,CAAC;GAAG,YAAY,CAA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EtF,UAAU,IAAI,KAAK,MAAM,IAAI;EAE7B,MAAM,eAAeC,UAAAA,QAAK,KAAK,iBAAiB,GAAI,MAAM,CAACC,iBAAAA,UAAU,GAAG,CAAC,IAAI,CAAC,GAAI,KAAK,QAAQ;EAC/F,OAAA,GAAA,OAAA,OAAA,CAAa,IAAI,CAAC,CAAC,oBAAoB,YAAY;CACrD;CAEA,OAAO;AACT"}
1
+ {"version":3,"file":"mocks.cjs","names":["FileManager","ast","Hookable","path","camelCase"],"sources":["../src/mocks.ts"],"sourcesContent":["import path, { resolve } from 'node:path'\nimport { camelCase } from '@internals/utils'\nimport type { FileNode, InputMeta, Macro, OperationNode, SchemaNode } from '@kubb/ast'\nimport { applyMacros, ast } from '@kubb/ast'\nimport { expect } from 'vitest'\nimport type { Parser } from './defineParser.ts'\nimport { FileManager } from './FileManager.ts'\nimport { Hookable } from './Hookable.ts'\nimport type { KubbDriver } from './KubbDriver.ts'\nimport type {\n Adapter,\n AdapterFactoryOptions,\n Config,\n Generator,\n GeneratorContext,\n KubbHooks,\n NormalizedPlugin,\n PluginFactoryOptions,\n RendererFactory,\n} from './types.ts'\n\n/**\n * Creates a minimal `KubbDriver` mock for unit tests.\n */\nexport function createMockedPluginDriver(options: { name?: string; plugin?: NormalizedPlugin; config?: Config } = {}): KubbDriver {\n const fileManager = new FileManager()\n\n return {\n config: options?.config ?? {\n root: '.',\n output: {\n path: './path',\n },\n },\n getPlugin(_pluginName: string): NormalizedPlugin | undefined {\n return options?.plugin\n },\n getResolver: (_pluginName: string) => options?.plugin?.resolver,\n fileManager,\n async dispatch({ result, renderer }: { result: unknown; renderer?: RendererFactory | null }): Promise<void> {\n if (!result) return\n\n if (Array.isArray(result)) {\n fileManager.upsert(...(result as Array<FileNode>))\n return\n }\n\n if (!renderer) return\n\n using instance = renderer()\n await instance.render(result)\n fileManager.upsert(...instance.files)\n },\n } as unknown as KubbDriver\n}\n\n/**\n * Creates a minimal `Adapter` mock for unit tests.\n * `parse` returns an empty `InputNode` by default. Override via `options.parse`.\n */\nexport function createMockedAdapter<TOptions extends AdapterFactoryOptions = AdapterFactoryOptions>(\n options: {\n name?: TOptions['name']\n resolvedOptions?: TOptions['resolvedOptions']\n parse?: Adapter<TOptions>['parse']\n } = {},\n): Adapter<TOptions> {\n const adapter: Adapter<TOptions> = {\n name: (options.name ?? 'oas') as TOptions['name'],\n options: (options.resolvedOptions ?? {}) as TOptions['resolvedOptions'],\n document: null,\n parse: options.parse ?? (async () => ast.factory.createInput()),\n validate: async () => {},\n }\n return adapter\n}\n\n/**\n * Creates a minimal plugin mock for unit tests.\n *\n * @example\n * `const plugin = createMockedPlugin<PluginTs>({ name: '@kubb/plugin-ts', options })`\n */\nexport function createMockedPlugin<TOptions extends PluginFactoryOptions = PluginFactoryOptions>(params: {\n name: TOptions['name']\n options: TOptions['resolvedOptions']\n resolver?: TOptions['resolver']\n macros?: Array<Macro>\n dependencies?: Array<string>\n}): NormalizedPlugin<TOptions> {\n return {\n name: params.name,\n options: params.options,\n resolver: params.resolver,\n macros: params.macros,\n dependencies: params.dependencies,\n hooks: {},\n } as unknown as NormalizedPlugin<TOptions>\n}\n\ntype RenderGeneratorOptions<TOptions extends PluginFactoryOptions> = {\n config: Config\n adapter: Adapter\n meta?: InputMeta\n driver: KubbDriver\n plugin: NormalizedPlugin<TOptions>\n options: TOptions['resolvedOptions']\n resolver: TOptions['resolver']\n}\n\nfunction createMockedPluginContext<TOptions extends PluginFactoryOptions>(opts: RenderGeneratorOptions<TOptions>): Omit<GeneratorContext<TOptions>, 'options'> {\n const root = resolve(opts.config.root, opts.config.output.path)\n\n return {\n config: opts.config,\n root,\n adapter: opts.adapter,\n resolver: opts.resolver,\n plugin: opts.plugin,\n driver: opts.driver,\n getResolver: (name: string) => opts.driver.getResolver(name),\n meta: opts.meta ?? { circularNames: [], enumNames: [] },\n addFile: async (...files: Array<FileNode>) => opts.driver.fileManager.add(...files),\n upsertFile: async (...files: Array<FileNode>) => opts.driver.fileManager.upsert(...files),\n hooks: opts.driver.hooks ?? new Hookable<KubbHooks>(),\n warn: (msg: string) => console.warn(msg),\n error: (msg: string) => console.error(msg),\n info: (msg: string) => console.info(msg),\n } as unknown as Omit<GeneratorContext<TOptions>, 'options'>\n}\n\n/**\n * Renders a generator's `schema` method in a test context.\n *\n * @example\n * ```ts\n * await renderGeneratorSchema(typeGenerator, node, { config, adapter, driver, plugin, options, resolver })\n * await matchFiles(driver.fileManager.files)\n * ```\n */\nexport async function renderGeneratorSchema<TOptions extends PluginFactoryOptions>(\n generator: Generator<TOptions>,\n node: SchemaNode,\n opts: RenderGeneratorOptions<TOptions>,\n): Promise<void> {\n if (!generator.schema) return\n const context = createMockedPluginContext(opts)\n const transformedNode = opts.plugin.macros?.length ? applyMacros(node, opts.plugin.macros) : node\n const result = await generator.schema(transformedNode, {\n ...context,\n options: opts.options,\n })\n await opts.driver.dispatch({ result, renderer: generator.renderer })\n}\n\n/**\n * Renders a generator's `operation` method in a test context.\n *\n * @example\n * ```ts\n * await renderGeneratorOperation(typeGenerator, node, { config, adapter, driver, plugin, options, resolver })\n * await matchFiles(driver.fileManager.files)\n * ```\n */\nexport async function renderGeneratorOperation<TOptions extends PluginFactoryOptions>(\n generator: Generator<TOptions>,\n node: OperationNode,\n opts: RenderGeneratorOptions<TOptions>,\n): Promise<void> {\n if (!generator.operation) return\n const context = createMockedPluginContext(opts)\n const transformedNode = opts.plugin.macros?.length ? applyMacros(node, opts.plugin.macros) : node\n const result = await generator.operation(transformedNode, {\n ...context,\n options: opts.options,\n })\n await opts.driver.dispatch({ result, renderer: generator.renderer })\n}\n\n/**\n * Renders a generator's `operations` method in a test context.\n *\n * @example\n * ```ts\n * await renderGeneratorOperations(classClientGenerator, nodes, { config, adapter, driver, plugin, options, resolver })\n * await matchFiles(driver.fileManager.files)\n * ```\n */\nexport async function renderGeneratorOperations<TOptions extends PluginFactoryOptions>(\n generator: Generator<TOptions>,\n nodes: Array<OperationNode>,\n opts: RenderGeneratorOptions<TOptions>,\n): Promise<void> {\n if (!generator.operations) return\n const context = createMockedPluginContext(opts)\n const transformedNodes = opts.plugin.macros?.length ? nodes.map((n) => applyMacros(n, opts.plugin.macros!)) : nodes\n const result = await generator.operations(transformedNodes, {\n ...context,\n options: opts.options,\n })\n await opts.driver.dispatch({ result, renderer: generator.renderer })\n}\n\ntype MatchFilesOptions = {\n /**\n * Parsers indexed by file extension, used to render each `FileNode` to source.\n * Without a matching parser the file's raw content is used.\n */\n parsers?: Map<FileNode['extname'], Parser>\n /**\n * Formatter applied to non-JSON output before snapshotting, e.g. prettier. When\n * omitted the parsed source is snapshotted as-is.\n */\n format?: (source?: string) => string | Promise<string>\n /**\n * Subfolder under `__snapshots__`, camelCased. Useful to keep variant snapshots apart.\n */\n pre?: string\n}\n\n/**\n * Renders the driver's collected `FileNode`s to source and asserts each against a file snapshot.\n * Pair it with the `renderGenerator*` helpers to snapshot a generator's output.\n *\n * @example\n * ```ts\n * await renderGeneratorSchema(typeGenerator, node, { config, adapter, driver, plugin, options, resolver })\n * await matchFiles(driver.fileManager.files, { parsers, format })\n * ```\n */\nexport async function matchFiles(files: Array<FileNode> | undefined, options: MatchFilesOptions = {}): Promise<Map<string, string> | undefined> {\n if (!files?.length) return\n\n const { parsers = new Map(), format, pre } = options\n const fileManager = new FileManager()\n const processed = new Map<string, string>()\n\n for (const file of files) {\n if (!file?.path || processed.has(file.path)) {\n continue\n }\n\n const parsed = await fileManager.parse(file, { parsers })\n const code = file.baseName.endsWith('.json') || !format ? parsed : await format(parsed)\n\n processed.set(file.path, code)\n\n const snapshotPath = path.join('__snapshots__', ...(pre ? [camelCase(pre)] : []), file.baseName)\n await expect(code).toMatchFileSnapshot(snapshotPath)\n }\n\n return processed\n}\n"],"mappings":";;;;;;;;;;AAwBA,SAAgB,yBAAyB,UAAyE,CAAC,GAAe;CAChI,MAAM,cAAc,IAAIA,iBAAAA,YAAY;CAEpC,OAAO;EACL,QAAQ,SAAS,UAAU;GACzB,MAAM;GACN,QAA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AAG;EACH,SAAS,KAAK;CAChB,CAAC;CACD,MAAM,KAAK,OAAO,SAAS;EAAE;EAAQ,UAAU,UAAU;CAAS,CAAC;AACrE;;;;;;;;;;;AA6BA,eAAsB,WAAW,OAAoC,UAA6B,CAAC,GAA6C;CAC9I,IAAI,CAAC,OAAO,QAAQ;CAEpB,MAAM,EAAE,0BAAU,IAAI,IAAI,GAAG,QAAQ,QAAQ;CAC7C,MAAM,cAAc,IAAIF,iBAAAA,YAAY;CACpC,MAAM,4BAAY,IAAI,IAAoB;CAE1C,KAAK,MAAM,QAAQ,OAAO;EACxB,IAAI,CAAC,MAAM,QAAQ,UAAU,IAAI,KAAK,IAAI,GACxC;EAGF,MAAM,SAAS,MAAM,YAAY,MAAM,MAAM,EAAE,QAAQ,CAAC;EACxD,MAAM,OAAO,KAAK,SAAS,SAAS,OAAO,KAAK,CAAC,SAAS,SAAS,MAAM,OAAO,MAAM;EAEtF,UAAU,IAAI,KAAK,MAAM,IAAI;EAE7B,MAAM,eAAeG,UAAAA,QAAK,KAAK,iBAAiB,GAAI,MAAM,CAACC,iBAAAA,UAAU,GAAG,CAAC,IAAI,CAAC,GAAI,KAAK,QAAQ;EAC/F,OAAA,GAAA,OAAA,OAAA,CAAa,IAAI,CAAC,CAAC,oBAAoB,YAAY;CACrD;CAEA,OAAO;AACT"}
package/dist/mocks.d.ts CHANGED
@@ -1,7 +1,6 @@
1
1
  import { t as __name } from "./rolldown-runtime-C0LytTxp.js";
2
- import { A as Generator, F as Parser, Ft as Adapter, It as AdapterFactoryOptions, N as KubbDriver, W as NormalizedPlugin, X as PluginFactoryOptions, r as Config } from "./types-BLFyAJLZ.js";
2
+ import { A as Generator, F as Parser, N as KubbDriver, Rt as Adapter, W as NormalizedPlugin, X as PluginFactoryOptions, r as Config, zt as AdapterFactoryOptions } from "./types-Bl0feoGY.js";
3
3
  import { FileNode, InputMeta, Macro, OperationNode, SchemaNode } from "@kubb/ast";
4
-
5
4
  //#region src/mocks.d.ts
6
5
  /**
7
6
  * Creates a minimal `KubbDriver` mock for unit tests.
@@ -14,13 +13,11 @@ declare function createMockedPluginDriver(options?: {
14
13
  /**
15
14
  * Creates a minimal `Adapter` mock for unit tests.
16
15
  * `parse` returns an empty `InputNode` by default. Override via `options.parse`.
17
- * `getImports` returns `[]` by default.
18
16
  */
19
17
  declare function createMockedAdapter<TOptions extends AdapterFactoryOptions = AdapterFactoryOptions>(options?: {
20
18
  name?: TOptions['name'];
21
19
  resolvedOptions?: TOptions['resolvedOptions'];
22
20
  parse?: Adapter<TOptions>['parse'];
23
- getImports?: Adapter<TOptions>['getImports'];
24
21
  }): Adapter<TOptions>;
25
22
  /**
26
23
  * Creates a minimal plugin mock for unit tests.
package/dist/mocks.js CHANGED
@@ -1,7 +1,7 @@
1
1
  import "./rolldown-runtime-C0LytTxp.js";
2
- import { d as camelCase, n as FileManager, t as _usingCtx } from "./usingCtx-BriKju-v.js";
2
+ import { d as camelCase, n as FileManager, r as Hookable, t as _usingCtx } from "./usingCtx-BriKju-v.js";
3
3
  import path, { resolve } from "node:path";
4
- import { applyMacros } from "@kubb/ast";
4
+ import { applyMacros, ast } from "@kubb/ast";
5
5
  import { expect } from "vitest";
6
6
  //#region src/mocks.ts
7
7
  /**
@@ -42,18 +42,14 @@ function createMockedPluginDriver(options = {}) {
42
42
  /**
43
43
  * Creates a minimal `Adapter` mock for unit tests.
44
44
  * `parse` returns an empty `InputNode` by default. Override via `options.parse`.
45
- * `getImports` returns `[]` by default.
46
45
  */
47
46
  function createMockedAdapter(options = {}) {
48
47
  return {
49
48
  name: options.name ?? "oas",
50
49
  options: options.resolvedOptions ?? {},
51
- parse: options.parse ?? (async () => ({
52
- kind: "Input",
53
- schemas: [],
54
- operations: []
55
- })),
56
- getImports: options.getImports ?? ((_node, _resolve) => [])
50
+ document: null,
51
+ parse: options.parse ?? (async () => ast.factory.createInput()),
52
+ validate: async () => {}
57
53
  };
58
54
  }
59
55
  /**
@@ -88,7 +84,7 @@ function createMockedPluginContext(opts) {
88
84
  },
89
85
  addFile: async (...files) => opts.driver.fileManager.add(...files),
90
86
  upsertFile: async (...files) => opts.driver.fileManager.upsert(...files),
91
- hooks: opts.driver.hooks ?? {},
87
+ hooks: opts.driver.hooks ?? new Hookable(),
92
88
  warn: (msg) => console.warn(msg),
93
89
  error: (msg) => console.error(msg),
94
90
  info: (msg) => console.info(msg)
package/dist/mocks.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"mocks.js","names":[],"sources":["../src/mocks.ts"],"sourcesContent":["import path, { resolve } from 'node:path'\nimport { camelCase } from '@internals/utils'\nimport type { FileNode, InputMeta, Macro, OperationNode, SchemaNode } from '@kubb/ast'\nimport { applyMacros } from '@kubb/ast'\nimport { expect } from 'vitest'\nimport type { Parser } from './defineParser.ts'\nimport { FileManager } from './FileManager.ts'\nimport type { KubbDriver } from './KubbDriver.ts'\nimport type { Adapter, AdapterFactoryOptions, Config, Generator, GeneratorContext, NormalizedPlugin, PluginFactoryOptions, RendererFactory } from './types.ts'\n\n/**\n * Creates a minimal `KubbDriver` mock for unit tests.\n */\nexport function createMockedPluginDriver(options: { name?: string; plugin?: NormalizedPlugin; config?: Config } = {}): KubbDriver {\n const fileManager = new FileManager()\n\n return {\n config: options?.config ?? {\n root: '.',\n output: {\n path: './path',\n },\n },\n getPlugin(_pluginName: string): NormalizedPlugin | undefined {\n return options?.plugin\n },\n getResolver: (_pluginName: string) => options?.plugin?.resolver,\n fileManager,\n async dispatch({ result, renderer }: { result: unknown; renderer?: RendererFactory | null }): Promise<void> {\n if (!result) return\n\n if (Array.isArray(result)) {\n fileManager.upsert(...(result as Array<FileNode>))\n return\n }\n\n if (!renderer) return\n\n using instance = renderer()\n await instance.render(result)\n fileManager.upsert(...instance.files)\n },\n } as unknown as KubbDriver\n}\n\n/**\n * Creates a minimal `Adapter` mock for unit tests.\n * `parse` returns an empty `InputNode` by default. Override via `options.parse`.\n * `getImports` returns `[]` by default.\n */\nexport function createMockedAdapter<TOptions extends AdapterFactoryOptions = AdapterFactoryOptions>(\n options: {\n name?: TOptions['name']\n resolvedOptions?: TOptions['resolvedOptions']\n parse?: Adapter<TOptions>['parse']\n getImports?: Adapter<TOptions>['getImports']\n } = {},\n): Adapter<TOptions> {\n return {\n name: (options.name ?? 'oas') as TOptions['name'],\n options: (options.resolvedOptions ?? {}) as TOptions['resolvedOptions'],\n parse: options.parse ?? (async () => ({ kind: 'Input' as const, schemas: [], operations: [] })),\n getImports: options.getImports ?? ((_node: SchemaNode, _resolve: (schemaName: string) => { name: string; path: string }) => []),\n } as Adapter<TOptions>\n}\n\n/**\n * Creates a minimal plugin mock for unit tests.\n *\n * @example\n * `const plugin = createMockedPlugin<PluginTs>({ name: '@kubb/plugin-ts', options })`\n */\nexport function createMockedPlugin<TOptions extends PluginFactoryOptions = PluginFactoryOptions>(params: {\n name: TOptions['name']\n options: TOptions['resolvedOptions']\n resolver?: TOptions['resolver']\n macros?: Array<Macro>\n dependencies?: Array<string>\n}): NormalizedPlugin<TOptions> {\n return {\n name: params.name,\n options: params.options,\n resolver: params.resolver,\n macros: params.macros,\n dependencies: params.dependencies,\n hooks: {},\n } as unknown as NormalizedPlugin<TOptions>\n}\n\ntype RenderGeneratorOptions<TOptions extends PluginFactoryOptions> = {\n config: Config\n adapter: Adapter\n meta?: InputMeta\n driver: KubbDriver\n plugin: NormalizedPlugin<TOptions>\n options: TOptions['resolvedOptions']\n resolver: TOptions['resolver']\n}\n\nfunction createMockedPluginContext<TOptions extends PluginFactoryOptions>(opts: RenderGeneratorOptions<TOptions>): Omit<GeneratorContext<TOptions>, 'options'> {\n const root = resolve(opts.config.root, opts.config.output.path)\n\n return {\n config: opts.config,\n root,\n adapter: opts.adapter,\n resolver: opts.resolver,\n plugin: opts.plugin,\n driver: opts.driver,\n getResolver: (name: string) => opts.driver.getResolver(name),\n meta: opts.meta ?? { circularNames: [], enumNames: [] },\n addFile: async (...files: Array<FileNode>) => opts.driver.fileManager.add(...files),\n upsertFile: async (...files: Array<FileNode>) => opts.driver.fileManager.upsert(...files),\n hooks: opts.driver.hooks ?? ({} as never),\n warn: (msg: string) => console.warn(msg),\n error: (msg: string) => console.error(msg),\n info: (msg: string) => console.info(msg),\n } as unknown as Omit<GeneratorContext<TOptions>, 'options'>\n}\n\n/**\n * Renders a generator's `schema` method in a test context.\n *\n * @example\n * ```ts\n * await renderGeneratorSchema(typeGenerator, node, { config, adapter, driver, plugin, options, resolver })\n * await matchFiles(driver.fileManager.files)\n * ```\n */\nexport async function renderGeneratorSchema<TOptions extends PluginFactoryOptions>(\n generator: Generator<TOptions>,\n node: SchemaNode,\n opts: RenderGeneratorOptions<TOptions>,\n): Promise<void> {\n if (!generator.schema) return\n const context = createMockedPluginContext(opts)\n const transformedNode = opts.plugin.macros?.length ? applyMacros(node, opts.plugin.macros) : node\n const result = await generator.schema(transformedNode, {\n ...context,\n options: opts.options,\n })\n await opts.driver.dispatch({ result, renderer: generator.renderer })\n}\n\n/**\n * Renders a generator's `operation` method in a test context.\n *\n * @example\n * ```ts\n * await renderGeneratorOperation(typeGenerator, node, { config, adapter, driver, plugin, options, resolver })\n * await matchFiles(driver.fileManager.files)\n * ```\n */\nexport async function renderGeneratorOperation<TOptions extends PluginFactoryOptions>(\n generator: Generator<TOptions>,\n node: OperationNode,\n opts: RenderGeneratorOptions<TOptions>,\n): Promise<void> {\n if (!generator.operation) return\n const context = createMockedPluginContext(opts)\n const transformedNode = opts.plugin.macros?.length ? applyMacros(node, opts.plugin.macros) : node\n const result = await generator.operation(transformedNode, {\n ...context,\n options: opts.options,\n })\n await opts.driver.dispatch({ result, renderer: generator.renderer })\n}\n\n/**\n * Renders a generator's `operations` method in a test context.\n *\n * @example\n * ```ts\n * await renderGeneratorOperations(classClientGenerator, nodes, { config, adapter, driver, plugin, options, resolver })\n * await matchFiles(driver.fileManager.files)\n * ```\n */\nexport async function renderGeneratorOperations<TOptions extends PluginFactoryOptions>(\n generator: Generator<TOptions>,\n nodes: Array<OperationNode>,\n opts: RenderGeneratorOptions<TOptions>,\n): Promise<void> {\n if (!generator.operations) return\n const context = createMockedPluginContext(opts)\n const transformedNodes = opts.plugin.macros?.length ? nodes.map((n) => applyMacros(n, opts.plugin.macros!)) : nodes\n const result = await generator.operations(transformedNodes, {\n ...context,\n options: opts.options,\n })\n await opts.driver.dispatch({ result, renderer: generator.renderer })\n}\n\ntype MatchFilesOptions = {\n /**\n * Parsers indexed by file extension, used to render each `FileNode` to source.\n * Without a matching parser the file's raw content is used.\n */\n parsers?: Map<FileNode['extname'], Parser>\n /**\n * Formatter applied to non-JSON output before snapshotting, e.g. prettier. When\n * omitted the parsed source is snapshotted as-is.\n */\n format?: (source?: string) => string | Promise<string>\n /**\n * Subfolder under `__snapshots__`, camelCased. Useful to keep variant snapshots apart.\n */\n pre?: string\n}\n\n/**\n * Renders the driver's collected `FileNode`s to source and asserts each against a file snapshot.\n * Pair it with the `renderGenerator*` helpers to snapshot a generator's output.\n *\n * @example\n * ```ts\n * await renderGeneratorSchema(typeGenerator, node, { config, adapter, driver, plugin, options, resolver })\n * await matchFiles(driver.fileManager.files, { parsers, format })\n * ```\n */\nexport async function matchFiles(files: Array<FileNode> | undefined, options: MatchFilesOptions = {}): Promise<Map<string, string> | undefined> {\n if (!files?.length) return\n\n const { parsers = new Map(), format, pre } = options\n const fileManager = new FileManager()\n const processed = new Map<string, string>()\n\n for (const file of files) {\n if (!file?.path || processed.has(file.path)) {\n continue\n }\n\n const parsed = await fileManager.parse(file, { parsers })\n const code = file.baseName.endsWith('.json') || !format ? parsed : await format(parsed)\n\n processed.set(file.path, code)\n\n const snapshotPath = path.join('__snapshots__', ...(pre ? [camelCase(pre)] : []), file.baseName)\n await expect(code).toMatchFileSnapshot(snapshotPath)\n }\n\n return processed\n}\n"],"mappings":";;;;;;;;;AAaA,SAAgB,yBAAyB,UAAyE,CAAC,GAAe;CAChI,MAAM,cAAc,IAAI,YAAY;CAEpC,OAAO;EACL,QAAQ,SAAS,UAAU;GACzB,MAAM;GACN,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KAAK,OAAO,SAAS;EAAE;EAAQ,UAAU,UAAU;CAAS,CAAC;AACrE;;;;;;;;;;;AA6BA,eAAsB,WAAW,OAAoC,UAA6B,CAAC,GAA6C;CAC9I,IAAI,CAAC,OAAO,QAAQ;CAEpB,MAAM,EAAE,0BAAU,IAAI,IAAI,GAAG,QAAQ,QAAQ;CAC7C,MAAM,cAAc,IAAI,YAAY;CACpC,MAAM,4BAAY,IAAI,IAAoB;CAE1C,KAAK,MAAM,QAAQ,OAAO;EACxB,IAAI,CAAC,MAAM,QAAQ,UAAU,IAAI,KAAK,IAAI,GACxC;EAGF,MAAM,SAAS,MAAM,YAAY,MAAM,MAAM,EAAE,QAAQ,CAAC;EACxD,MAAM,OAAO,KAAK,SAAS,SAAS,OAAO,KAAK,CAAC,SAAS,SAAS,MAAM,OAAO,MAAM;EAEtF,UAAU,IAAI,KAAK,MAAM,IAAI;EAE7B,MAAM,eAAe,KAAK,KAAK,iBAAiB,GAAI,MAAM,CAAC,UAAU,GAAG,CAAC,IAAI,CAAC,GAAI,KAAK,QAAQ;EAC/F,MAAM,OAAO,IAAI,CAAC,CAAC,oBAAoB,YAAY;CACrD;CAEA,OAAO;AACT"}
1
+ {"version":3,"file":"mocks.js","names":[],"sources":["../src/mocks.ts"],"sourcesContent":["import path, { resolve } from 'node:path'\nimport { camelCase } from '@internals/utils'\nimport type { FileNode, InputMeta, Macro, OperationNode, SchemaNode } from '@kubb/ast'\nimport { applyMacros, ast } from '@kubb/ast'\nimport { expect } from 'vitest'\nimport type { Parser } from './defineParser.ts'\nimport { FileManager } from './FileManager.ts'\nimport { Hookable } from './Hookable.ts'\nimport type { KubbDriver } from './KubbDriver.ts'\nimport type {\n Adapter,\n AdapterFactoryOptions,\n Config,\n Generator,\n GeneratorContext,\n KubbHooks,\n NormalizedPlugin,\n PluginFactoryOptions,\n RendererFactory,\n} from './types.ts'\n\n/**\n * Creates a minimal `KubbDriver` mock for unit tests.\n */\nexport function createMockedPluginDriver(options: { name?: string; plugin?: NormalizedPlugin; config?: Config } = {}): KubbDriver {\n const fileManager = new FileManager()\n\n return {\n config: options?.config ?? {\n root: '.',\n output: {\n path: './path',\n },\n },\n getPlugin(_pluginName: string): NormalizedPlugin | undefined {\n return options?.plugin\n },\n getResolver: (_pluginName: string) => options?.plugin?.resolver,\n fileManager,\n async dispatch({ result, renderer }: { result: unknown; renderer?: RendererFactory | null }): Promise<void> {\n if (!result) return\n\n if (Array.isArray(result)) {\n fileManager.upsert(...(result as Array<FileNode>))\n return\n }\n\n if (!renderer) return\n\n using instance = renderer()\n await instance.render(result)\n fileManager.upsert(...instance.files)\n },\n } as unknown as KubbDriver\n}\n\n/**\n * Creates a minimal `Adapter` mock for unit tests.\n * `parse` returns an empty `InputNode` by default. Override via `options.parse`.\n */\nexport function createMockedAdapter<TOptions extends AdapterFactoryOptions = AdapterFactoryOptions>(\n options: {\n name?: TOptions['name']\n resolvedOptions?: TOptions['resolvedOptions']\n parse?: Adapter<TOptions>['parse']\n } = {},\n): Adapter<TOptions> {\n const adapter: Adapter<TOptions> = {\n name: (options.name ?? 'oas') as TOptions['name'],\n options: (options.resolvedOptions ?? {}) as TOptions['resolvedOptions'],\n document: null,\n parse: options.parse ?? (async () => ast.factory.createInput()),\n validate: async () => {},\n }\n return adapter\n}\n\n/**\n * Creates a minimal plugin mock for unit tests.\n *\n * @example\n * `const plugin = createMockedPlugin<PluginTs>({ name: '@kubb/plugin-ts', options })`\n */\nexport function createMockedPlugin<TOptions extends PluginFactoryOptions = PluginFactoryOptions>(params: {\n name: TOptions['name']\n options: TOptions['resolvedOptions']\n resolver?: TOptions['resolver']\n macros?: Array<Macro>\n dependencies?: Array<string>\n}): NormalizedPlugin<TOptions> {\n return {\n name: params.name,\n options: params.options,\n resolver: params.resolver,\n macros: params.macros,\n dependencies: params.dependencies,\n hooks: {},\n } as unknown as NormalizedPlugin<TOptions>\n}\n\ntype RenderGeneratorOptions<TOptions extends PluginFactoryOptions> = {\n config: Config\n adapter: Adapter\n meta?: InputMeta\n driver: KubbDriver\n plugin: NormalizedPlugin<TOptions>\n options: TOptions['resolvedOptions']\n resolver: TOptions['resolver']\n}\n\nfunction createMockedPluginContext<TOptions extends PluginFactoryOptions>(opts: RenderGeneratorOptions<TOptions>): Omit<GeneratorContext<TOptions>, 'options'> {\n const root = resolve(opts.config.root, opts.config.output.path)\n\n return {\n config: opts.config,\n root,\n adapter: opts.adapter,\n resolver: opts.resolver,\n plugin: opts.plugin,\n driver: opts.driver,\n getResolver: (name: string) => opts.driver.getResolver(name),\n meta: opts.meta ?? { circularNames: [], enumNames: [] },\n addFile: async (...files: Array<FileNode>) => opts.driver.fileManager.add(...files),\n upsertFile: async (...files: Array<FileNode>) => opts.driver.fileManager.upsert(...files),\n hooks: opts.driver.hooks ?? new Hookable<KubbHooks>(),\n warn: (msg: string) => console.warn(msg),\n error: (msg: string) => console.error(msg),\n info: (msg: string) => console.info(msg),\n } as unknown as Omit<GeneratorContext<TOptions>, 'options'>\n}\n\n/**\n * Renders a generator's `schema` method in a test context.\n *\n * @example\n * ```ts\n * await renderGeneratorSchema(typeGenerator, node, { config, adapter, driver, plugin, options, resolver })\n * await matchFiles(driver.fileManager.files)\n * ```\n */\nexport async function renderGeneratorSchema<TOptions extends PluginFactoryOptions>(\n generator: Generator<TOptions>,\n node: SchemaNode,\n opts: RenderGeneratorOptions<TOptions>,\n): Promise<void> {\n if (!generator.schema) return\n const context = createMockedPluginContext(opts)\n const transformedNode = opts.plugin.macros?.length ? applyMacros(node, opts.plugin.macros) : node\n const result = await generator.schema(transformedNode, {\n ...context,\n options: opts.options,\n })\n await opts.driver.dispatch({ result, renderer: generator.renderer })\n}\n\n/**\n * Renders a generator's `operation` method in a test context.\n *\n * @example\n * ```ts\n * await renderGeneratorOperation(typeGenerator, node, { config, adapter, driver, plugin, options, resolver })\n * await matchFiles(driver.fileManager.files)\n * ```\n */\nexport async function renderGeneratorOperation<TOptions extends PluginFactoryOptions>(\n generator: Generator<TOptions>,\n node: OperationNode,\n opts: RenderGeneratorOptions<TOptions>,\n): Promise<void> {\n if (!generator.operation) return\n const context = createMockedPluginContext(opts)\n const transformedNode = opts.plugin.macros?.length ? applyMacros(node, opts.plugin.macros) : node\n const result = await generator.operation(transformedNode, {\n ...context,\n options: opts.options,\n })\n await opts.driver.dispatch({ result, renderer: generator.renderer })\n}\n\n/**\n * Renders a generator's `operations` method in a test context.\n *\n * @example\n * ```ts\n * await renderGeneratorOperations(classClientGenerator, nodes, { config, adapter, driver, plugin, options, resolver })\n * await matchFiles(driver.fileManager.files)\n * ```\n */\nexport async function renderGeneratorOperations<TOptions extends PluginFactoryOptions>(\n generator: Generator<TOptions>,\n nodes: Array<OperationNode>,\n opts: RenderGeneratorOptions<TOptions>,\n): Promise<void> {\n if (!generator.operations) return\n const context = createMockedPluginContext(opts)\n const transformedNodes = opts.plugin.macros?.length ? nodes.map((n) => applyMacros(n, opts.plugin.macros!)) : nodes\n const result = await generator.operations(transformedNodes, {\n ...context,\n options: opts.options,\n })\n await opts.driver.dispatch({ result, renderer: generator.renderer })\n}\n\ntype MatchFilesOptions = {\n /**\n * Parsers indexed by file extension, used to render each `FileNode` to source.\n * Without a matching parser the file's raw content is used.\n */\n parsers?: Map<FileNode['extname'], Parser>\n /**\n * Formatter applied to non-JSON output before snapshotting, e.g. prettier. When\n * omitted the parsed source is snapshotted as-is.\n */\n format?: (source?: string) => string | Promise<string>\n /**\n * Subfolder under `__snapshots__`, camelCased. Useful to keep variant snapshots apart.\n */\n pre?: string\n}\n\n/**\n * Renders the driver's collected `FileNode`s to source and asserts each against a file snapshot.\n * Pair it with the `renderGenerator*` helpers to snapshot a generator's output.\n *\n * @example\n * ```ts\n * await renderGeneratorSchema(typeGenerator, node, { config, adapter, driver, plugin, options, resolver })\n * await matchFiles(driver.fileManager.files, { parsers, format })\n * ```\n */\nexport async function matchFiles(files: Array<FileNode> | undefined, options: MatchFilesOptions = {}): Promise<Map<string, string> | undefined> {\n if (!files?.length) return\n\n const { parsers = new Map(), format, pre } = options\n const fileManager = new FileManager()\n const processed = new Map<string, string>()\n\n for (const file of files) {\n if (!file?.path || processed.has(file.path)) {\n continue\n }\n\n const parsed = await fileManager.parse(file, { parsers })\n const code = file.baseName.endsWith('.json') || !format ? parsed : await format(parsed)\n\n processed.set(file.path, code)\n\n const snapshotPath = path.join('__snapshots__', ...(pre ? [camelCase(pre)] : []), file.baseName)\n await expect(code).toMatchFileSnapshot(snapshotPath)\n }\n\n return processed\n}\n"],"mappings":";;;;;;;;;AAwBA,SAAgB,yBAAyB,UAAyE,CAAC,GAAe;CAChI,MAAM,cAAc,IAAI,YAAY;CAEpC,OAAO;EACL,QAAQ,SAAS,UAAU;GACzB,MAAM;GACN,QAAQ,EACN,MAAM,SACR;EACF;EACA,UAAU,aAAmD;GAC3D,OAAO,SAAS;EAClB;EACA,cAAc,gBAAwB,SAAS,QAAQ;EACvD;EACA,MAAM,SAAS,EAAE,QAAQ,YAAmF;;;IAC1G,IAAI,CAAC,QAAQ;IAEb,IAAI,MAAM,QAAQ,MAAM,GAAG;KACzB,YAAY,OAAO,GAAI,MAA0B;KACjD;IACF;IAEA,IAAI,CAAC,UAAU;IAEf,MAAM,WAAA,YAAA,EAAW,SAAS,CAAA;IAC1B,MAAM,SAAS,OAAO,MAAM;IAC5B,YAAY,OAAO,GAAG,SAAS,KAAK;;;;;;EACtC;CACF;AACF;;;;;AAMA,SAAgB,oBACd,UAII,CAAC,GACc;CAQnB,OAAO;EANL,MAAO,QAAQ,QAAQ;EACvB,SAAU,QAAQ,mBAAmB,CAAC;EACtC,UAAU;EACV,OAAO,QAAQ,UAAU,YAAY,IAAI,QAAQ,YAAY;EAC7D,UAAU,YAAY,CAAC;CAEZ;AACf;;;;;;;AAQA,SAAgB,mBAAiF,QAMlE;CAC7B,OAAO;EACL,MAAM,OAAO;EACb,SAAS,OAAO;EAChB,UAAU,OAAO;EACjB,QAAQ,OAAO;EACf,cAAc,OAAO;EACrB,OAAO,CAAC;CACV;AACF;AA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, InputMeta, InputNode, Macro, Node, OperationNode, SchemaNode, UserFileNode } from "@kubb/ast";
3
-
4
3
  //#region ../../internals/utils/src/promise.d.ts
5
4
  /** A value that may already be resolved or still pending.
6
5
  *
@@ -13,6 +12,20 @@ import { Enforce, FileNode, HttpMethod, ImportNode, InputMeta, InputNode, Macro,
13
12
  */
14
13
  type PossiblePromise<T> = Promise<T> | T;
15
14
  //#endregion
15
+ //#region ../../internals/utils/src/types.d.ts
16
+ /** A union of known literals that still accepts any other value of `Base`, without collapsing
17
+ * the literals away. Editors keep autocompleting the known members while arbitrary strings stay
18
+ * assignable.
19
+ *
20
+ * @example
21
+ * ```ts
22
+ * type PluginName = LiteralUnion<'plugin-ts' | 'plugin-zod'>
23
+ * const a: PluginName = 'plugin-ts' // autocompletes
24
+ * const b: PluginName = 'anything' // still allowed
25
+ * ```
26
+ */
27
+ type LiteralUnion<T extends Base, Base = string> = T | (Base & {});
28
+ //#endregion
16
29
  //#region src/createAdapter.d.ts
17
30
  /**
18
31
  * Source data handed to an adapter's `parse` function. Mirrors the config
@@ -78,19 +91,13 @@ type Adapter<TOptions extends AdapterFactoryOptions = AdapterFactoryOptions> = {
78
91
  document: TOptions['document'] | null;
79
92
  /**
80
93
  * Parse the source into a universal `InputNode`.
81
- */
82
- parse: (source: AdapterSource) => PossiblePromise<InputNode>;
83
- /**
84
- * Extract `ImportNode` entries for a schema tree.
85
- * Returns an empty array before the first `parse()` call.
86
94
  *
87
- * The `resolve` callback receives the collision-corrected schema name and must
88
- * return `{ name, path }` for the import, or `undefined` to skip it.
95
+ * An adapter that renames schemas (e.g. collision handling) must stamp `targetName` on
96
+ * every ref node pointing at a renamed schema, so `resolveRefName` and `resolver.imports`
97
+ * resolve a `$ref` to the file that is actually generated. Refs that keep their pointer's
98
+ * last segment need no stamp.
89
99
  */
90
- getImports: (node: SchemaNode, resolve: (schemaName: string) => {
91
- name: string;
92
- path: string;
93
- }) => Array<ImportNode>;
100
+ parse: (source: AdapterSource) => PossiblePromise<InputNode>;
94
101
  /**
95
102
  * Validate the document at the given path or URL.
96
103
  */
@@ -122,7 +129,6 @@ type AdapterBuilder<T extends AdapterFactoryOptions> = (options: T['options']) =
122
129
  * // Convert the source (path or inline data) into an InputNode.
123
130
  * return ast.factory.createInput()
124
131
  * },
125
- * getImports: () => [],
126
132
  * async validate() {
127
133
  * // Throw here when the spec is invalid.
128
134
  * },
@@ -241,7 +247,7 @@ type AsyncListener<TArgs extends Array<unknown>> = (...args: TArgs) => unknown;
241
247
  * await hooks.callHook('build', 'petstore') // all listeners awaited
242
248
  * ```
243
249
  */
244
- declare class Hookable<THooks extends { [K in keyof THooks]: Array<unknown> }> {
250
+ declare class Hookable<THooks extends { [K in keyof THooks]: Array<unknown>; }> {
245
251
  #private;
246
252
  /**
247
253
  * Maximum number of listeners per hook before Node emits a memory-leak warning.
@@ -278,7 +284,7 @@ declare class Hookable<THooks extends { [K in keyof THooks]: Array<unknown> }> {
278
284
  * unhook() // removes both
279
285
  * ```
280
286
  */
281
- addHooks(configHooks: Partial<{ [K in keyof THooks & string]: AsyncListener<THooks[K]> }>): () => void;
287
+ addHooks(configHooks: Partial<{ [K in keyof THooks & string]: AsyncListener<THooks[K]>; }>): () => void;
282
288
  /**
283
289
  * Removes a previously registered listener.
284
290
  *
@@ -573,20 +579,14 @@ declare class Diagnostics {
573
579
  /**
574
580
  * Builds a per-plugin performance record. Reporters sum these into the run total.
575
581
  */
576
- static performance({
577
- plugin,
578
- duration
579
- }: {
582
+ static performance({ plugin, duration }: {
580
583
  plugin: string;
581
584
  duration: number;
582
585
  }): PerformanceDiagnostic;
583
586
  /**
584
587
  * Builds the version-update notice shown when a newer Kubb is published on npm.
585
588
  */
586
- static update({
587
- currentVersion,
588
- latestVersion
589
- }: {
589
+ static update({ currentVersion, latestVersion }: {
590
590
  currentVersion: string;
591
591
  latestVersion: string;
592
592
  }): UpdateDiagnostic;
@@ -710,7 +710,7 @@ type Reporter = {
710
710
  /**
711
711
  * Display name, matching a {@link ReporterName} for the built-ins.
712
712
  */
713
- name: string;
713
+ name: LiteralUnion<ReporterName>;
714
714
  /**
715
715
  * Called once per config with that config's result and the render context.
716
716
  */
@@ -728,15 +728,15 @@ type Reporter = {
728
728
  * emit as one document. `T` is inferred from `report`'s return type.
729
729
  */
730
730
  type UserReporter<T = void> = {
731
- name: string;
731
+ name: LiteralUnion<ReporterName>;
732
732
  report: (result: GenerationResult, context: ReporterContext) => T | Promise<T>;
733
733
  drain?: (context: ReporterContext, reports: Array<T>) => void | Promise<void>;
734
734
  };
735
735
  /**
736
- * Defines a reporter. When the definition has a `drain`, the returned reporter buffers each value
737
- * `report` returns and hands the array to `drain` once, then clears it. Without a `drain`, nothing
738
- * is buffered. Wiring the reporter onto the run's hooks is the host's job, so the reporter only
739
- * ever deals with a {@link GenerationResult}.
736
+ * Defines a reporter. The returned reporter buffers each value `report` returns in order and, when
737
+ * the definition has a `drain`, hands the array to `drain` once and then clears it. Wiring the
738
+ * reporter onto the run's hooks is the host's job, so the reporter only ever deals with a
739
+ * {@link GenerationResult}.
740
740
  *
741
741
  * @example
742
742
  * ```ts
@@ -788,7 +788,11 @@ type Storage = {
788
788
  */
789
789
  getKeys(base?: string): Promise<Array<string>>;
790
790
  /**
791
- * Removes every entry. Pass `base` to scope the wipe to a key prefix.
791
+ * Removes stored entries. Pass `base` to scope the wipe to a key prefix.
792
+ *
793
+ * Omitting `base` is implementation-defined: in-memory stores wipe every
794
+ * entry, while filesystem-backed stores treat a missing `base` as a no-op so
795
+ * a bare `clear()` can never delete outside a known output directory.
792
796
  */
793
797
  clear(base?: string): Promise<void>;
794
798
  };
@@ -992,6 +996,37 @@ type ResolveFileOptions = ResolverFileParams & {
992
996
  output: Output;
993
997
  group?: Group;
994
998
  };
999
+ /**
1000
+ * Options for `resolver.imports`: the schema tree to scan (`node`) and where the generated
1001
+ * files live (`root`, `output`, `group`). Pass `name` to override how a referenced schema
1002
+ * name becomes the imported identifier; it defaults to the resolver's top-level `name`.
1003
+ *
1004
+ * @example
1005
+ * ```ts
1006
+ * resolver.imports({ node, root, output, group })
1007
+ * // → [{ kind: 'Import', name: ['pet'], path: '/src/types/pet.ts' }]
1008
+ * ```
1009
+ */
1010
+ type ResolveImportsOptions = {
1011
+ /**
1012
+ * Schema tree scanned for `$ref` occurrences. Each ref contributes one import entry.
1013
+ */
1014
+ node: SchemaNode;
1015
+ root: string;
1016
+ output: Output;
1017
+ group?: Group;
1018
+ /**
1019
+ * Extension of the generated files the imports point at.
1020
+ *
1021
+ * @default '.ts'
1022
+ */
1023
+ extname?: FileNode['extname'];
1024
+ /**
1025
+ * Overrides how a referenced schema name becomes the imported identifier, for example to
1026
+ * point enum refs at a suffixed type name. Defaults to the resolver's top-level `name`.
1027
+ */
1028
+ name?: (schemaName: string) => string;
1029
+ };
995
1030
  /**
996
1031
  * The `file` field of a resolver: decides what a generated file is called and, optionally, where
997
1032
  * it lives. This is how a resolver renames or relocates its files, replacing the older per-call
@@ -1104,7 +1139,6 @@ type ResolverBuildOptions = {
1104
1139
  pluginName: string;
1105
1140
  name?: (name: string) => string;
1106
1141
  file?: ResolverFile;
1107
- [key: string]: unknown;
1108
1142
  };
1109
1143
  /**
1110
1144
  * Partial resolver fields accepted by `Resolver.merge` and `setResolver`. Parameterize with a
@@ -1113,7 +1147,7 @@ type ResolverBuildOptions = {
1113
1147
  * (`query.name`) and the rest keep the plugin defaults. Overriding a whole resolver is not the
1114
1148
  * job of this patch, that is what a custom plugin is for.
1115
1149
  */
1116
- type ResolverPatch<T extends Resolver = Resolver> = { [K in keyof Omit<T, keyof Resolver>]?: T[K] extends ((...args: Array<never>) => unknown) ? T[K] : Partial<T[K]> } & {
1150
+ type ResolverPatch<T extends Resolver = Resolver> = { [K in keyof Omit<T, keyof Resolver>]?: T[K] extends ((...args: Array<never>) => unknown) ? T[K] : Partial<T[K]>; } & {
1117
1151
  name?: T['name'];
1118
1152
  file?: ResolverFile;
1119
1153
  } & ThisType<T>;
@@ -1127,9 +1161,9 @@ declare const resolverOptions: unique symbol;
1127
1161
  /**
1128
1162
  * Base constraint for all plugin resolver objects.
1129
1163
  *
1130
- * The built-in machinery lives under `default`. Generators call the top-level `name` and
1131
- * `file`, and a plugin overrides them to set its conventions. Extend with top-level helpers
1132
- * (`typeName`, …) and/or grouped namespaces (`query`, `schema`, …).
1164
+ * The built-in machinery lives under `default`. Generators call the top-level `name`, `file`,
1165
+ * and `imports`, and a plugin overrides `name` and `file` to set its conventions. Extend with
1166
+ * top-level helpers (`typeName`, …) and/or grouped namespaces (`query`, `schema`, …).
1133
1167
  *
1134
1168
  * @example Top-level helper
1135
1169
  * ```ts
@@ -1161,6 +1195,14 @@ declare class Resolver {
1161
1195
  get default(): ResolverDefault;
1162
1196
  name(name: string): string;
1163
1197
  file(options: ResolveFileOptions): FileNode;
1198
+ /**
1199
+ * Builds one `ImportNode` per unique schema referenced in the tree, in first-occurrence
1200
+ * order. Each ref's target resolves through `resolveRefName`, so collision- or macro-renamed
1201
+ * schemas (`targetName`) import the emitted name. Names and paths go through the top-level
1202
+ * `name` and `file`, so import entries follow the plugin's conventions, and a per-call
1203
+ * `name` override wins over both.
1204
+ */
1205
+ imports(options: ResolveImportsOptions): Array<ImportNode>;
1164
1206
  /**
1165
1207
  * Merges `override` over `base` and returns a new resolver with helpers re-bound. Top-level
1166
1208
  * keys replace, and a namespace (or `file`) merges per method, so overriding `query.name`
@@ -1173,6 +1215,16 @@ declare class Resolver {
1173
1215
  //#endregion
1174
1216
  //#region src/definePlugin.d.ts
1175
1217
  type ExtractRegistryKey$1<T, K extends PropertyKey> = K extends keyof T ? T[K] : {};
1218
+ /**
1219
+ * A plugin name as accepted by `getPlugin`/`requirePlugin`/`getResolver`. Registered names from
1220
+ * `Kubb.PluginRegistry` autocomplete, and any other string is still allowed.
1221
+ */
1222
+ type PluginName = LiteralUnion<keyof Kubb.PluginRegistry>;
1223
+ /**
1224
+ * Resolves a plugin name to its `PluginFactoryOptions`. A name registered in `Kubb.PluginRegistry`
1225
+ * maps to its exact factory options, any other string falls back to the generic options.
1226
+ */
1227
+ type ResolvePluginOptions<TName> = TName extends keyof Kubb.PluginRegistry ? Kubb.PluginRegistry[TName] : PluginFactoryOptions;
1176
1228
  /**
1177
1229
  * How a plugin consolidates its generated code into files.
1178
1230
  * - `'directory'` writes one file per operation or schema under `path`.
@@ -1474,7 +1526,7 @@ type Plugin<TFactory extends PluginFactoryOptions = PluginFactoryOptions> = {
1474
1526
  * Plugins that must be registered before this plugin executes.
1475
1527
  * An error is thrown at startup when any listed dependency is missing.
1476
1528
  */
1477
- dependencies?: Array<string>;
1529
+ dependencies?: Array<PluginName>;
1478
1530
  /**
1479
1531
  * Controls the execution order of this plugin relative to others.
1480
1532
  *
@@ -1493,7 +1545,7 @@ type Plugin<TFactory extends PluginFactoryOptions = PluginFactoryOptions> = {
1493
1545
  * Lifecycle hook handlers for this plugin.
1494
1546
  * Any hook from the global `KubbHooks` map can be subscribed to here.
1495
1547
  */
1496
- hooks: { [K in keyof KubbHooks as K extends 'kubb:plugin:setup' ? never : K]?: (...args: KubbHooks[K]) => void | Promise<void> } & {
1548
+ hooks: { [K in keyof KubbHooks as K extends 'kubb:plugin:setup' ? never : K]?: (...args: KubbHooks[K]) => void | Promise<void>; } & {
1497
1549
  'kubb:plugin:setup'?(ctx: KubbPluginSetupContext<TFactory>): void | Promise<void>;
1498
1550
  };
1499
1551
  };
@@ -1671,17 +1723,12 @@ declare class FileManager {
1671
1723
  /**
1672
1724
  * Converts a file's AST sources (or its `copy` source) into the final on-disk string.
1673
1725
  */
1674
- parse(file: FileNode, {
1675
- parsers
1676
- }?: ParseOptions): Promise<string>;
1726
+ parse(file: FileNode, { parsers }?: ParseOptions): Promise<string>;
1677
1727
  /**
1678
1728
  * Converts and writes every file at once, letting `storage.setItem` decide how much of
1679
1729
  * that runs concurrently.
1680
1730
  */
1681
- write(files: Array<FileNode>, {
1682
- storage,
1683
- parsers
1684
- }: WriteOptions): Promise<void>;
1731
+ write(files: Array<FileNode>, { storage, parsers }: WriteOptions): Promise<void>;
1685
1732
  }
1686
1733
  //#endregion
1687
1734
  //#region src/KubbDriver.d.ts
@@ -1770,10 +1817,7 @@ declare class KubbDriver {
1770
1817
  * Pass `renderer` when the result may be a renderer element. Generators that only return
1771
1818
  * `Array<FileNode>` do not need one.
1772
1819
  */
1773
- dispatch<TElement = unknown>({
1774
- result,
1775
- renderer
1776
- }: {
1820
+ dispatch<TElement = unknown>({ result, renderer }: {
1777
1821
  result: TElement | Array<FileNode> | undefined | null;
1778
1822
  renderer?: RendererFactory<TElement> | null;
1779
1823
  }): Promise<void>;
@@ -1797,16 +1841,13 @@ declare class KubbDriver {
1797
1841
  * Resolution order: resolver set via `setPluginResolver` → lazily created default
1798
1842
  * resolver (identity name, no path transforms).
1799
1843
  */
1800
- getResolver<TName extends keyof Kubb.PluginRegistry>(pluginName: TName): Kubb.PluginRegistry[TName]['resolver'];
1801
- getResolver<TResolver extends Resolver = Resolver>(pluginName: string): TResolver;
1844
+ getResolver<TName extends PluginName>(pluginName: TName): ResolvePluginOptions<TName>['resolver'];
1802
1845
  getContext<TOptions extends PluginFactoryOptions>(plugin: NormalizedPlugin<TOptions>): Omit<GeneratorContext<TOptions>, 'options'>;
1803
- getPlugin<TName extends keyof Kubb.PluginRegistry>(pluginName: TName): Plugin<Kubb.PluginRegistry[TName]> | undefined;
1804
- getPlugin<TOptions extends PluginFactoryOptions = PluginFactoryOptions>(pluginName: string): Plugin<TOptions> | undefined;
1846
+ getPlugin<TName extends PluginName>(pluginName: TName): Plugin<ResolvePluginOptions<TName>> | undefined;
1805
1847
  /**
1806
1848
  * Like `getPlugin` but throws a descriptive error when the plugin is not found.
1807
1849
  */
1808
- requirePlugin<TName extends keyof Kubb.PluginRegistry>(pluginName: TName, context?: RequirePluginContext): Plugin<Kubb.PluginRegistry[TName]>;
1809
- requirePlugin<TOptions extends PluginFactoryOptions = PluginFactoryOptions>(pluginName: string, context?: RequirePluginContext): Plugin<TOptions>;
1850
+ requirePlugin<TName extends PluginName>(pluginName: TName, context?: RequirePluginContext): Plugin<ResolvePluginOptions<TName>>;
1810
1851
  }
1811
1852
  //#endregion
1812
1853
  //#region src/defineGenerator.d.ts
@@ -1835,18 +1876,15 @@ type GeneratorContext<TOptions extends PluginFactoryOptions = PluginFactoryOptio
1835
1876
  /**
1836
1877
  * Get a plugin by name, typed via `Kubb.PluginRegistry` when registered.
1837
1878
  */
1838
- getPlugin<TName extends keyof Kubb.PluginRegistry>(name: TName): Plugin<Kubb.PluginRegistry[TName]> | undefined;
1839
- getPlugin(name: string): Plugin | undefined;
1879
+ getPlugin<TName extends PluginName>(name: TName): Plugin<ResolvePluginOptions<TName>> | undefined;
1840
1880
  /**
1841
1881
  * Get a plugin by name, throws an error if not found.
1842
1882
  */
1843
- requirePlugin<TName extends keyof Kubb.PluginRegistry>(name: TName): Plugin<Kubb.PluginRegistry[TName]>;
1844
- requirePlugin(name: string): Plugin;
1883
+ requirePlugin<TName extends PluginName>(name: TName): Plugin<ResolvePluginOptions<TName>>;
1845
1884
  /**
1846
1885
  * Get a resolver by plugin name, typed via `Kubb.PluginRegistry` when registered.
1847
1886
  */
1848
- getResolver<TName extends keyof Kubb.PluginRegistry>(name: TName): Kubb.PluginRegistry[TName]['resolver'];
1849
- getResolver(name: string): Resolver;
1887
+ getResolver<TName extends PluginName>(name: TName): ResolvePluginOptions<TName>['resolver'];
1850
1888
  /**
1851
1889
  * Add files only if they don't exist.
1852
1890
  */
@@ -2473,8 +2511,7 @@ type KubbBuildStartContext = {
2473
2511
  /**
2474
2512
  * Looks up a registered plugin by name, typed by the plugin registry.
2475
2513
  */
2476
- getPlugin<TName extends keyof Kubb.PluginRegistry>(name: TName): Plugin<Kubb.PluginRegistry[TName]> | undefined;
2477
- getPlugin(name: string): Plugin | undefined;
2514
+ getPlugin<TName extends PluginName>(name: TName): Plugin<ResolvePluginOptions<TName>> | undefined;
2478
2515
  /**
2479
2516
  * Snapshot of all files accumulated so far.
2480
2517
  */
@@ -2781,5 +2818,5 @@ type BuildOutput = {
2781
2818
  storage: Storage;
2782
2819
  };
2783
2820
  //#endregion
2784
- export { ResolveBannerContext as $, Generator as A, ProblemCode as At, Include as B, KubbWarnContext as C, Diagnostic as Ct, CreateKubbOptions as D, DiagnosticSeverity as Dt, UserConfig as E, DiagnosticLocation as Et, Parser as F, Adapter as Ft, Output as G, KubbPluginSetupContext as H, defineParser as I, AdapterFactoryOptions as It, Override as J, OutputMode as K, Exclude$1 as L, AdapterSource as Lt, defineGenerator as M, SerializedDiagnostic as Mt, KubbDriver as N, UpdateDiagnostic as Nt, Kubb$1 as O, Diagnostics as Ot, FileManagerHooks as P, Hookable as Pt, BannerMeta as Q, Filter as R, createAdapter as Rt, KubbSuccessContext as S, logLevel as St, PostGenerateCommand as T, DiagnosticKind as Tt, KubbPluginStartContext as U, KubbPluginEndContext as V, NormalizedPlugin as W, PluginFactoryOptions as X, Plugin as Y, definePlugin as Z, KubbHookStartContext as _, Reporter as _t, KubbBuildEndContext as a, ResolverDefault as at, KubbLifecycleStartContext as b, UserReporter as bt, KubbErrorContext as c, ResolverFilePathParams as ct, KubbFilesProcessingStartContext as d, Renderer as dt, ResolveBannerFile as et, KubbFilesProcessingUpdateContext as f, RendererFactory as ft, KubbHookLineContext as g, GenerationResult as gt, KubbHookEndContext as h, createStorage as ht, Input as i, Resolver as it, GeneratorContext as j, ProblemDiagnostic as jt, createKubb as k, PerformanceDiagnostic as kt, KubbFileProcessingUpdate as l, ResolverPatch as lt, KubbGenerationStartContext as m, Storage as mt, CLIOptions as n, ResolveOptionsContext as nt, KubbBuildStartContext as o, ResolverFile as ot, KubbGenerationEndContext as p, createRenderer as pt, OutputOptions as q, Config as r, ResolvePathOptions as rt, KubbDiagnosticContext as s, ResolverFileParams as st, BuildOutput as t, ResolveFileOptions as tt, KubbFilesProcessingEndContext as u, ResolverPathParams as ut, KubbHooks as v, ReporterContext as vt, PossibleConfig as w, DiagnosticDoc as wt, KubbPluginsEndContext as x, createReporter as xt, KubbInfoContext as y, ReporterName as yt, Group as z };
2785
- //# sourceMappingURL=types-BLFyAJLZ.d.ts.map
2821
+ export { definePlugin as $, Generator as A, DiagnosticSeverity as At, Include as B, AdapterSource as Bt, KubbWarnContext as C, UserReporter as Ct, CreateKubbOptions as D, DiagnosticDoc as Dt, UserConfig as E, Diagnostic as Et, Parser as F, SerializedDiagnostic as Ft, Output as G, KubbPluginSetupContext as H, defineParser as I, UpdateDiagnostic as It, Override as J, OutputMode as K, Exclude$1 as L, Hookable as Lt, defineGenerator as M, PerformanceDiagnostic as Mt, KubbDriver as N, ProblemCode as Nt, Kubb$1 as O, DiagnosticKind as Ot, FileManagerHooks as P, ProblemDiagnostic as Pt, ResolvePluginOptions as Q, Filter as R, Adapter as Rt, KubbSuccessContext as S, ReporterName as St, PostGenerateCommand as T, logLevel as Tt, KubbPluginStartContext as U, KubbPluginEndContext as V, createAdapter as Vt, NormalizedPlugin as W, PluginFactoryOptions as X, Plugin as Y, PluginName as Z, KubbHookStartContext as _, Storage as _t, KubbBuildEndContext as a, ResolveOptionsContext as at, KubbLifecycleStartContext as b, Reporter as bt, KubbErrorContext as c, ResolverDefault as ct, KubbFilesProcessingStartContext as d, ResolverFilePathParams as dt, BannerMeta as et, KubbFilesProcessingUpdateContext as f, ResolverPatch as ft, KubbHookLineContext as g, createRenderer as gt, KubbHookEndContext as h, RendererFactory as ht, Input as i, ResolveImportsOptions as it, GeneratorContext as j, Diagnostics as jt, createKubb as k, DiagnosticLocation as kt, KubbFileProcessingUpdate as l, ResolverFile as lt, KubbGenerationStartContext as m, Renderer as mt, CLIOptions as n, ResolveBannerFile as nt, KubbBuildStartContext as o, ResolvePathOptions as ot, KubbGenerationEndContext as p, ResolverPathParams as pt, OutputOptions as q, Config as r, ResolveFileOptions as rt, KubbDiagnosticContext as s, Resolver as st, BuildOutput as t, ResolveBannerContext as tt, KubbFilesProcessingEndContext as u, ResolverFileParams as ut, KubbHooks as v, createStorage as vt, PossibleConfig as w, createReporter as wt, KubbPluginsEndContext as x, ReporterContext as xt, KubbInfoContext as y, GenerationResult as yt, Group as z, AdapterFactoryOptions as zt };
2822
+ //# sourceMappingURL=types-Bl0feoGY.d.ts.map