@kubb/core 5.0.0-beta.3 → 5.0.0-beta.31

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.
Files changed (46) hide show
  1. package/README.md +8 -38
  2. package/dist/KubbDriver-CFx2DdhF.js +2131 -0
  3. package/dist/KubbDriver-CFx2DdhF.js.map +1 -0
  4. package/dist/KubbDriver-vyD7F0Ip.cjs +2252 -0
  5. package/dist/KubbDriver-vyD7F0Ip.cjs.map +1 -0
  6. package/dist/{types-CC09VtBt.d.ts → createKubb-6zii1jo-.d.ts} +1610 -1257
  7. package/dist/index.cjs +351 -1125
  8. package/dist/index.cjs.map +1 -1
  9. package/dist/index.d.ts +3 -186
  10. package/dist/index.js +341 -1119
  11. package/dist/index.js.map +1 -1
  12. package/dist/mocks.cjs +30 -21
  13. package/dist/mocks.cjs.map +1 -1
  14. package/dist/mocks.d.ts +5 -5
  15. package/dist/mocks.js +29 -20
  16. package/dist/mocks.js.map +1 -1
  17. package/package.json +6 -18
  18. package/src/FileManager.ts +78 -61
  19. package/src/FileProcessor.ts +48 -38
  20. package/src/KubbDriver.ts +930 -0
  21. package/src/constants.ts +11 -6
  22. package/src/createAdapter.ts +113 -17
  23. package/src/createKubb.ts +1039 -478
  24. package/src/createRenderer.ts +58 -27
  25. package/src/createStorage.ts +36 -23
  26. package/src/defineGenerator.ts +127 -15
  27. package/src/defineLogger.ts +66 -7
  28. package/src/defineMiddleware.ts +19 -17
  29. package/src/defineParser.ts +30 -13
  30. package/src/definePlugin.ts +329 -14
  31. package/src/defineResolver.ts +365 -167
  32. package/src/devtools.ts +8 -1
  33. package/src/index.ts +2 -2
  34. package/src/mocks.ts +11 -14
  35. package/src/storages/fsStorage.ts +13 -37
  36. package/src/types.ts +48 -1292
  37. package/dist/PluginDriver-BXibeQk-.cjs +0 -1036
  38. package/dist/PluginDriver-BXibeQk-.cjs.map +0 -1
  39. package/dist/PluginDriver-DV3p2Hky.js +0 -945
  40. package/dist/PluginDriver-DV3p2Hky.js.map +0 -1
  41. package/src/Kubb.ts +0 -300
  42. package/src/PluginDriver.ts +0 -424
  43. package/src/renderNode.ts +0 -35
  44. package/src/utils/diagnostics.ts +0 -18
  45. package/src/utils/isInputPath.ts +0 -10
  46. package/src/utils/packageJSON.ts +0 -99
@@ -0,0 +1,930 @@
1
+ import { resolve } from 'node:path'
2
+ import { arrayToAsyncIterable, type AsyncEventEmitter, forBatches, formatMs, getElapsedMs, isPromise, memoize, URLPath } from '@internals/utils'
3
+ import { collectUsedSchemaNames, createFile, createStreamInput, transform } from '@kubb/ast'
4
+ import type { FileNode, InputMeta, InputNode, InputStreamNode, OperationNode, SchemaNode } from '@kubb/ast'
5
+ import { DEFAULT_STUDIO_URL, SCHEMA_PARALLEL, STREAM_FLUSH_EVERY } from './constants.ts'
6
+ import type { Storage } from './createStorage.ts'
7
+ import type { Generator } from './defineGenerator.ts'
8
+ import type { Parser } from './defineParser.ts'
9
+ import type { Plugin } from './definePlugin.ts'
10
+ import { getMode } from './definePlugin.ts'
11
+ import { defineResolver } from './defineResolver.ts'
12
+ import { openInStudio as openInStudioFn } from './devtools.ts'
13
+ import { FileManager } from './FileManager.ts'
14
+ import { FileProcessor } from './FileProcessor.ts'
15
+ import type { Renderer, RendererFactory } from './createRenderer.ts'
16
+
17
+ import type {
18
+ Adapter,
19
+ AdapterSource,
20
+ Config,
21
+ DevtoolsOptions,
22
+ GeneratorContext,
23
+ KubbHooks,
24
+ KubbPluginSetupContext,
25
+ Middleware,
26
+ NormalizedPlugin,
27
+ PluginFactoryOptions,
28
+ Resolver,
29
+ } from './types.ts'
30
+
31
+ type Options = {
32
+ hooks: AsyncEventEmitter<KubbHooks>
33
+ }
34
+
35
+ function enforceOrder(enforce: 'pre' | 'post' | undefined): number {
36
+ return enforce === 'pre' ? -1 : enforce === 'post' ? 1 : 0
37
+ }
38
+
39
+ const OPERATION_FILTER_TYPES = new Set(['tag', 'operationId', 'path', 'method', 'contentType'])
40
+
41
+ export class KubbDriver {
42
+ readonly config: Config
43
+ readonly options: Options
44
+
45
+ /**
46
+ * Returns `'single'` when `fileOrFolder` has a file extension, `'split'` otherwise.
47
+ *
48
+ * @example
49
+ * ```ts
50
+ * KubbDriver.getMode('src/gen/types.ts') // 'single'
51
+ * KubbDriver.getMode('src/gen/types') // 'split'
52
+ * ```
53
+ */
54
+ static getMode(fileOrFolder: string | undefined | null): 'single' | 'split' {
55
+ return getMode(fileOrFolder)
56
+ }
57
+
58
+ /**
59
+ * The streaming `InputStreamNode` produced by the adapter.
60
+ * Always set after adapter setup — parse-only adapters are wrapped automatically.
61
+ */
62
+ inputNode: InputStreamNode | null = null
63
+ adapter: Adapter | null = null
64
+ /**
65
+ * Studio session state, kept together so `dispose()` can reset it atomically.
66
+ *
67
+ * - `source` holds the raw adapter source so `adapter.parse()` can be called lazily.
68
+ * Intentionally outlives the build; cleared by `dispose()`.
69
+ * - `isOpen` prevents opening the studio more than once per build.
70
+ * - `inputNode` caches the parse promise so `adapter.parse()` is called at most once
71
+ * per studio session, even when `openInStudio()` is called multiple times.
72
+ */
73
+ #studio: { source: AdapterSource | null; isOpen: boolean; inputNode: Promise<InputNode> | null } = {
74
+ source: null,
75
+ isOpen: false,
76
+ inputNode: null,
77
+ }
78
+
79
+ // Register middleware hooks after all plugin hooks are registered.
80
+ // Because AsyncEventEmitter calls listeners in registration order,
81
+ // middleware hooks for any event fire after all plugin hooks for that event.
82
+ // Handlers are tracked so they can be removed after each build (disposeMiddleware),
83
+ // preventing accumulation when multiple configs share the same hooks instance.
84
+ #middlewareListeners: Array<[keyof KubbHooks & string, (...args: Array<never>) => void | Promise<void>]> = []
85
+
86
+ /**
87
+ * Central file store for all generated files.
88
+ * Plugins should use `this.addFile()` / `this.upsertFile()` (via their context) to
89
+ * add files; this property gives direct read/write access when needed.
90
+ */
91
+ readonly fileManager = new FileManager()
92
+ readonly #fileProcessor = new FileProcessor()
93
+
94
+ readonly plugins = new Map<string, NormalizedPlugin>()
95
+
96
+ /**
97
+ * Tracks which plugins have generators registered via `addGenerator()` (event-based path).
98
+ * Used by the build loop to decide whether to emit generator events for a given plugin.
99
+ */
100
+ readonly #eventGeneratorPlugins = new Set<string>()
101
+ readonly #resolvers = new Map<string, Resolver>()
102
+ readonly #defaultResolvers = new Map<string, Resolver>()
103
+ readonly #hookListeners = new Map<keyof KubbHooks, Set<(...args: Array<never>) => void | Promise<void>>>()
104
+
105
+ constructor(config: Config, options: Options) {
106
+ this.config = config
107
+ this.options = options
108
+ this.adapter = config.adapter ?? null
109
+ }
110
+
111
+ async setup() {
112
+ const normalized: Array<NormalizedPlugin> = this.config.plugins.map((rawPlugin) => this.#normalizePlugin(rawPlugin as Plugin))
113
+
114
+ normalized.sort((a, b) => {
115
+ if (b.dependencies?.includes(a.name)) return -1
116
+ if (a.dependencies?.includes(b.name)) return 1
117
+
118
+ return enforceOrder(a.enforce) - enforceOrder(b.enforce)
119
+ })
120
+
121
+ for (const plugin of normalized) {
122
+ if (plugin.apply) {
123
+ plugin.apply(this.config)
124
+ }
125
+
126
+ this.#registerPlugin(plugin)
127
+ this.plugins.set(plugin.name, plugin)
128
+ }
129
+
130
+ if (this.config.middleware) {
131
+ for (const middleware of this.config.middleware) {
132
+ for (const event of Object.keys(middleware.hooks) as Array<keyof KubbHooks & string>) {
133
+ this.#registerMiddleware(event, middleware.hooks)
134
+ }
135
+ }
136
+ }
137
+ if (this.config.adapter) {
138
+ await this.#registerAdapter(this.config.adapter)
139
+ }
140
+ }
141
+
142
+ get hooks() {
143
+ return this.options.hooks
144
+ }
145
+
146
+ /**
147
+ * Creates an `NormalizedPlugin` from a hook-style plugin and registers
148
+ * its lifecycle handlers on the `AsyncEventEmitter`.
149
+ */
150
+ #normalizePlugin(plugin: Plugin): NormalizedPlugin {
151
+ const normalized: NormalizedPlugin = {
152
+ name: plugin.name,
153
+ dependencies: plugin.dependencies,
154
+ enforce: plugin.enforce,
155
+ hooks: plugin.hooks,
156
+ options: plugin.options ?? { output: { path: '.' }, exclude: [], override: [] },
157
+ } as NormalizedPlugin
158
+
159
+ if ('apply' in plugin && typeof plugin.apply === 'function') {
160
+ normalized.apply = plugin.apply as (config: Config) => boolean
161
+ }
162
+
163
+ return normalized
164
+ }
165
+
166
+ async #registerAdapter(adapter: Adapter) {
167
+ const source = inputToAdapterSource(this.config)
168
+ this.#studio.source = source
169
+
170
+ if (adapter.stream) {
171
+ this.inputNode = await adapter.stream(source)
172
+
173
+ await this.hooks.emit('kubb:debug', {
174
+ date: new Date(),
175
+ logs: [`✓ Adapter '${adapter.name}' producing input stream`],
176
+ })
177
+ } else {
178
+ // Adapter does not implement stream() — eagerly parse and wrap in a
179
+ // reusable AsyncIterable so the rest of the pipeline stays stream-only.
180
+ const inputNode = await adapter.parse(source)
181
+ this.inputNode = createStreamInput(arrayToAsyncIterable(inputNode.schemas), arrayToAsyncIterable(inputNode.operations), inputNode.meta)
182
+
183
+ await this.hooks.emit('kubb:debug', {
184
+ date: new Date(),
185
+ logs: [
186
+ `✓ Adapter '${adapter.name}' resolved InputNode (wrapped as stream)`,
187
+ ` • Schemas: ${inputNode.schemas.length}`,
188
+ ` • Operations: ${inputNode.operations.length}`,
189
+ ],
190
+ })
191
+ }
192
+ }
193
+
194
+ #registerMiddleware<K extends keyof KubbHooks & string>(event: K, middlewareHooks: Middleware['hooks']) {
195
+ const handler = middlewareHooks[event]
196
+
197
+ if (!handler) {
198
+ return
199
+ }
200
+
201
+ this.hooks.on(event, handler)
202
+ this.#middlewareListeners.push([event, handler as (...args: Array<never>) => void | Promise<void>])
203
+ }
204
+
205
+ /**
206
+ * Registers a hook-style plugin's lifecycle handlers on the shared `AsyncEventEmitter`.
207
+ *
208
+ * For `kubb:plugin:setup`, the registered listener wraps the globally emitted context with a
209
+ * plugin-specific one so that `addGenerator`, `setResolver`, `setTransformer`, and
210
+ * `setRenderer` all target the correct `normalizedPlugin` entry in the plugins map.
211
+ *
212
+ * All other hooks are iterated and registered directly as pass-through listeners.
213
+ * Any event key present in the global `KubbHooks` interface can be subscribed to.
214
+ *
215
+ * External tooling can subscribe to any of these events via `hooks.on(...)` to observe
216
+ * the plugin lifecycle without modifying plugin behavior.
217
+ *
218
+ * @internal
219
+ */
220
+ #registerPlugin(plugin: NormalizedPlugin): void {
221
+ const { hooks } = plugin
222
+
223
+ if (!hooks) return
224
+
225
+ // kubb:plugin:setup gets special treatment: the globally emitted context is wrapped with
226
+ // plugin-specific implementations so that addGenerator / setResolver / etc. target
227
+ // this plugin's normalizedPlugin entry rather than being no-ops.
228
+ if (hooks['kubb:plugin:setup']) {
229
+ const setupHandler = (globalCtx: KubbPluginSetupContext) => {
230
+ const pluginCtx: KubbPluginSetupContext = {
231
+ ...globalCtx,
232
+ options: plugin.options ?? {},
233
+ addGenerator: (gen) => {
234
+ this.registerGenerator(plugin.name, gen)
235
+ },
236
+ setResolver: (resolver) => {
237
+ this.setPluginResolver(plugin.name, resolver)
238
+ },
239
+ setTransformer: (visitor) => {
240
+ plugin.transformer = visitor
241
+ },
242
+ setRenderer: (renderer) => {
243
+ plugin.renderer = renderer
244
+ },
245
+ setOptions: (opts) => {
246
+ plugin.options = { ...plugin.options, ...opts }
247
+ },
248
+ injectFile: (userFileNode) => {
249
+ this.fileManager.add(createFile(userFileNode))
250
+ },
251
+ }
252
+ return hooks['kubb:plugin:setup']!(pluginCtx)
253
+ }
254
+
255
+ this.hooks.on('kubb:plugin:setup', setupHandler)
256
+ this.#trackHookListener('kubb:plugin:setup', setupHandler as (...args: Array<never>) => void | Promise<void>)
257
+ }
258
+
259
+ // All other hooks are registered as direct pass-through listeners on the shared emitter.
260
+ for (const [event, handler] of Object.entries(hooks) as Array<[keyof KubbHooks, ((...args: Array<never>) => void | Promise<void>) | undefined]>) {
261
+ if (event === 'kubb:plugin:setup' || !handler) continue
262
+
263
+ this.hooks.on(event, handler as never)
264
+ this.#trackHookListener(event, handler as (...args: Array<never>) => void | Promise<void>)
265
+ }
266
+ }
267
+
268
+ /**
269
+ * Emits the `kubb:plugin:setup` event so that all registered hook-style plugin listeners
270
+ * can configure generators, resolvers, transformers and renderers before `buildStart` runs.
271
+ *
272
+ * Call this once from `safeBuild` before the plugin execution loop begins.
273
+ */
274
+ async emitSetupHooks(): Promise<void> {
275
+ const noop = () => {}
276
+
277
+ await this.hooks.emit('kubb:plugin:setup', {
278
+ config: this.config,
279
+ options: {},
280
+ addGenerator: noop,
281
+ setResolver: noop,
282
+ setTransformer: noop,
283
+ setRenderer: noop,
284
+ setOptions: noop,
285
+ injectFile: noop,
286
+ updateConfig: noop,
287
+ })
288
+ }
289
+
290
+ /**
291
+ * Registers a generator for the given plugin on the shared event emitter.
292
+ *
293
+ * The generator's `schema`, `operation`, and `operations` methods are registered as
294
+ * listeners on `kubb:generate:schema`, `kubb:generate:operation`, and `kubb:generate:operations`
295
+ * respectively. Each listener is scoped to the owning plugin via a `ctx.plugin.name` check
296
+ * so that generators from different plugins do not cross-fire.
297
+ *
298
+ * The renderer resolution chain is: `generator.renderer → plugin.renderer → config.renderer`.
299
+ * Set `generator.renderer = null` to explicitly opt out of rendering even when the plugin
300
+ * declares a renderer.
301
+ *
302
+ * Call this method inside `addGenerator()` (in `kubb:plugin:setup`) to wire up a generator.
303
+ */
304
+ registerGenerator(pluginName: string, gen: Generator): void {
305
+ const resolveRenderer = () => {
306
+ const plugin = this.plugins.get(pluginName)
307
+ return gen.renderer === null ? undefined : (gen.renderer ?? plugin?.renderer ?? this.config.renderer)
308
+ }
309
+
310
+ if (gen.schema) {
311
+ const schemaHandler = async (node: SchemaNode, ctx: GeneratorContext) => {
312
+ if (ctx.plugin.name !== pluginName) return
313
+ const result = await gen.schema!(node, ctx)
314
+ await applyHookResult({ result, driver: this, rendererFactory: resolveRenderer() })
315
+ }
316
+
317
+ this.hooks.on('kubb:generate:schema', schemaHandler)
318
+ this.#trackHookListener('kubb:generate:schema', schemaHandler as (...args: Array<never>) => void | Promise<void>)
319
+ }
320
+
321
+ if (gen.operation) {
322
+ const operationHandler = async (node: OperationNode, ctx: GeneratorContext) => {
323
+ if (ctx.plugin.name !== pluginName) return
324
+ const result = await gen.operation!(node, ctx)
325
+ await applyHookResult({ result, driver: this, rendererFactory: resolveRenderer() })
326
+ }
327
+
328
+ this.hooks.on('kubb:generate:operation', operationHandler)
329
+ this.#trackHookListener('kubb:generate:operation', operationHandler as (...args: Array<never>) => void | Promise<void>)
330
+ }
331
+
332
+ if (gen.operations) {
333
+ const operationsHandler = async (nodes: Array<OperationNode>, ctx: GeneratorContext) => {
334
+ if (ctx.plugin.name !== pluginName) return
335
+ const result = await gen.operations!(nodes, ctx)
336
+ await applyHookResult({ result, driver: this, rendererFactory: resolveRenderer() })
337
+ }
338
+
339
+ this.hooks.on('kubb:generate:operations', operationsHandler)
340
+ this.#trackHookListener('kubb:generate:operations', operationsHandler as (...args: Array<never>) => void | Promise<void>)
341
+ }
342
+
343
+ this.#eventGeneratorPlugins.add(pluginName)
344
+ }
345
+
346
+ /**
347
+ * Returns `true` when at least one generator was registered for the given plugin
348
+ * via `addGenerator()` in `kubb:plugin:setup` (event-based path).
349
+ *
350
+ * Used by the build loop to decide whether to walk the AST and emit generator events
351
+ * for a plugin that has no static `plugin.generators`.
352
+ */
353
+ hasEventGenerators(pluginName: string): boolean {
354
+ return this.#eventGeneratorPlugins.has(pluginName)
355
+ }
356
+
357
+ /**
358
+ * Runs the full plugin pipeline. Returns timings/failures collected so far even
359
+ * when an outer hook throws — the orchestrator preserves partial state by capturing
360
+ * the error into `error` instead of propagating.
361
+ */
362
+ async run({ storage }: { storage: Storage }): Promise<{
363
+ failedPlugins: Set<{ plugin: Plugin; error: Error }>
364
+ pluginTimings: Map<string, number>
365
+ error?: Error
366
+ }> {
367
+ const hooks = this.hooks
368
+ const config = this.config
369
+ const failedPlugins = new Set<{ plugin: Plugin; error: Error }>()
370
+ const pluginTimings = new Map<string, number>()
371
+ const parsersMap = new Map<FileNode['extname'], Parser>()
372
+
373
+ for (const parser of config.parsers) {
374
+ if (parser.extNames) {
375
+ for (const ext of parser.extNames) parsersMap.set(ext, parser)
376
+ }
377
+ }
378
+
379
+ const pendingFiles = new Map<string, FileNode>()
380
+ this.fileManager.setOnUpsert((file) => {
381
+ pendingFiles.set(file.path, file)
382
+ })
383
+
384
+ try {
385
+ const flushPending = async (): Promise<void> => {
386
+ if (pendingFiles.size === 0) return
387
+ const files = [...pendingFiles.values()]
388
+ pendingFiles.clear()
389
+
390
+ await hooks.emit('kubb:debug', { date: new Date(), logs: [`Writing ${files.length} files...`] })
391
+ await hooks.emit('kubb:files:processing:start', { files })
392
+
393
+ const items = [...this.#fileProcessor.stream(files, { parsers: parsersMap, extension: config.output.extension })]
394
+
395
+ await hooks.emit('kubb:files:processing:update', {
396
+ files: items.map(({ file, source, processed, total, percentage }) => ({ file, source, processed, total, percentage, config })),
397
+ })
398
+
399
+ const queue: Array<Promise<void>> = []
400
+ for (const { file, source } of items) {
401
+ if (source) {
402
+ queue.push(storage.setItem(file.path, source))
403
+ if (queue.length >= STREAM_FLUSH_EVERY) await Promise.all(queue.splice(0))
404
+ }
405
+ }
406
+ await Promise.all(queue)
407
+
408
+ await hooks.emit('kubb:files:processing:end', { files })
409
+ await hooks.emit('kubb:debug', { date: new Date(), logs: [`✓ File write process completed for ${files.length} files`] })
410
+ }
411
+
412
+ await this.emitSetupHooks()
413
+
414
+ if (this.adapter && this.inputNode) {
415
+ await hooks.emit(
416
+ 'kubb:build:start',
417
+ Object.assign({ config, adapter: this.adapter, meta: this.inputNode.meta, getPlugin: this.getPlugin.bind(this) }, this.#filesPayload()),
418
+ )
419
+ }
420
+
421
+ const generatorPlugins: Array<{ plugin: NormalizedPlugin; context: GeneratorContext; hrStart: ReturnType<typeof process.hrtime> }> = []
422
+
423
+ for (const plugin of this.plugins.values()) {
424
+ const context = this.getContext(plugin)
425
+ const hrStart = process.hrtime()
426
+
427
+ try {
428
+ await hooks.emit('kubb:plugin:start', { plugin })
429
+ await hooks.emit('kubb:debug', { date: new Date(), logs: ['Starting plugin...', ` • Plugin Name: ${plugin.name}`] })
430
+ } catch (caughtError) {
431
+ const error = caughtError as Error
432
+ const duration = getElapsedMs(hrStart)
433
+ pluginTimings.set(plugin.name, duration)
434
+ await this.#emitPluginEnd({ plugin, duration, success: false, error })
435
+ failedPlugins.add({ plugin, error })
436
+ continue
437
+ }
438
+
439
+ if (plugin.generators?.length || this.hasEventGenerators(plugin.name)) {
440
+ generatorPlugins.push({ plugin, context, hrStart })
441
+ continue
442
+ }
443
+
444
+ const duration = getElapsedMs(hrStart)
445
+ pluginTimings.set(plugin.name, duration)
446
+ await this.#emitPluginEnd({ plugin, duration, success: true })
447
+ await hooks.emit('kubb:debug', { date: new Date(), logs: [`✓ Plugin started successfully (${formatMs(duration)})`] })
448
+ }
449
+
450
+ if (generatorPlugins.length > 0) {
451
+ if (this.inputNode) {
452
+ const { timings, failed } = await this.#runGenerators(generatorPlugins, flushPending)
453
+ // Drain any files written after the last batch's flush.
454
+ await flushPending()
455
+ for (const [name, duration] of timings) pluginTimings.set(name, duration)
456
+ for (const entry of failed) failedPlugins.add(entry)
457
+ } else {
458
+ // No adapter input: generator-plugins have nothing to dispatch, but still
459
+ // need their `kubb:plugin:end` so middleware (e.g. barrel) completes.
460
+ for (const { plugin, hrStart } of generatorPlugins) {
461
+ const duration = getElapsedMs(hrStart)
462
+ pluginTimings.set(plugin.name, duration)
463
+ await this.#emitPluginEnd({ plugin, duration, success: true })
464
+ }
465
+ }
466
+ }
467
+
468
+ await hooks.emit('kubb:plugins:end', Object.assign({ config }, this.#filesPayload()))
469
+
470
+ await flushPending()
471
+
472
+ const files = this.fileManager.files
473
+
474
+ await hooks.emit('kubb:build:end', { files, config, outputDir: resolve(config.root, config.output.path) })
475
+
476
+ return { failedPlugins, pluginTimings }
477
+ } catch (caughtError) {
478
+ return { failedPlugins, pluginTimings, error: caughtError as Error }
479
+ } finally {
480
+ this.fileManager.setOnUpsert(null)
481
+ }
482
+ }
483
+
484
+ // Returns a fresh object with a lazy `files` getter and a bound `upsertFile`.
485
+ // Caller must use `Object.assign(extra, this.#filesPayload())`, not object spread —
486
+ // spread would eagerly invoke the getter and freeze a stale snapshot into the payload.
487
+ #filesPayload(): { readonly files: Array<FileNode>; upsertFile: (...files: Array<FileNode>) => Array<FileNode> } {
488
+ const driver = this
489
+ return {
490
+ get files() {
491
+ return driver.fileManager.files
492
+ },
493
+ upsertFile: (...files: Array<FileNode>) => driver.fileManager.upsert(...files),
494
+ }
495
+ }
496
+
497
+ #emitPluginEnd({ plugin, duration, success, error }: { plugin: NormalizedPlugin; duration: number; success: boolean; error?: Error }): Promise<void> | void {
498
+ return this.hooks.emit(
499
+ 'kubb:plugin:end',
500
+ Object.assign({ plugin, duration, success, ...(error ? { error } : {}), config: this.config }, this.#filesPayload()),
501
+ )
502
+ }
503
+
504
+ async #runGenerators(
505
+ entries: Array<{ plugin: NormalizedPlugin; context: GeneratorContext; hrStart: ReturnType<typeof process.hrtime> }>,
506
+ flushPending: () => Promise<void>,
507
+ ): Promise<{ timings: Map<string, number>; failed: Set<{ plugin: Plugin; error: Error }> }> {
508
+ const timings = new Map<string, number>()
509
+ const failed = new Set<{ plugin: Plugin; error: Error }>()
510
+ type PluginState = {
511
+ plugin: NormalizedPlugin
512
+ generatorContext: GeneratorContext
513
+ generators: Array<Generator>
514
+ hrStart: ReturnType<typeof process.hrtime>
515
+ failed: boolean
516
+ error: Error | null
517
+ optionsAreStatic: boolean
518
+ allowedSchemaNames: Set<string> | null
519
+ }
520
+
521
+ const driver = this
522
+ const { schemas, operations } = this.inputNode!
523
+ const states: Array<PluginState> = entries.map(({ plugin, context, hrStart }) => {
524
+ const { exclude, include, override } = plugin.options
525
+ const hasExclude = Array.isArray(exclude) && exclude.length > 0
526
+ const hasInclude = Array.isArray(include) && include.length > 0
527
+ const hasOverride = Array.isArray(override) && override.length > 0
528
+ return {
529
+ plugin,
530
+ generatorContext: { ...context, resolver: this.getResolver(plugin.name) },
531
+ generators: plugin.generators ?? [],
532
+ hrStart,
533
+ failed: false,
534
+ error: null,
535
+ optionsAreStatic: !hasExclude && !hasInclude && !hasOverride,
536
+ allowedSchemaNames: null,
537
+ }
538
+ })
539
+
540
+ const emitsSchemaHook = this.hooks.listenerCount('kubb:generate:schema') > 0
541
+ const emitsOperationHook = this.hooks.listenerCount('kubb:generate:operation') > 0
542
+
543
+ // Pre-scan: plugins with operation-based includes (but no schemaName include) need
544
+ // the reachable schema set. This requires the full schema graph in memory at once —
545
+ // transitive reachability can't be derived from a single node. `allSchemas` is
546
+ // released as soon as the pre-scan returns; the main passes get fresh iterators.
547
+ const pruningStates = states.filter(({ plugin }) => {
548
+ const { include } = plugin.options
549
+ return (include?.some(({ type }) => OPERATION_FILTER_TYPES.has(type)) ?? false) && !(include?.some(({ type }) => type === 'schemaName') ?? false)
550
+ })
551
+
552
+ if (pruningStates.length > 0) {
553
+ const allSchemas: Array<SchemaNode> = []
554
+ for await (const schema of schemas) allSchemas.push(schema)
555
+
556
+ const includedOpsByState = new Map<PluginState, Array<OperationNode>>(pruningStates.map((s) => [s, []]))
557
+ for await (const operation of operations) {
558
+ for (const state of pruningStates) {
559
+ const { exclude, include, override } = state.plugin.options
560
+ const options = state.generatorContext.resolver.resolveOptions(operation, { options: state.plugin.options, exclude, include, override })
561
+ if (options !== null) includedOpsByState.get(state)?.push(operation)
562
+ }
563
+ }
564
+
565
+ for (const state of pruningStates) {
566
+ state.allowedSchemaNames = collectUsedSchemaNames(includedOpsByState.get(state) ?? [], allSchemas)
567
+ includedOpsByState.delete(state)
568
+ }
569
+ }
570
+
571
+ const resolveRendererFor = (gen: Generator, state: PluginState): RendererFactory | undefined =>
572
+ gen.renderer === null ? undefined : (gen.renderer ?? state.plugin.renderer ?? state.generatorContext.config.renderer)
573
+
574
+ // Schema and operation passes share this body. They differ only in which
575
+ // generator method runs, which hook is emitted, and the schema-only
576
+ // `allowedSchemaNames` prune (operations don't carry that constraint).
577
+ const dispatchNode = async <TNode extends SchemaNode | OperationNode>(
578
+ state: PluginState,
579
+ node: TNode,
580
+ dispatch: {
581
+ method: 'schema' | 'operation'
582
+ checkAllowedNames: boolean
583
+ emit: ((node: TNode, ctx: GeneratorContext) => Promise<void> | void) | null
584
+ },
585
+ ): Promise<void> => {
586
+ if (state.failed) return
587
+ try {
588
+ const { plugin, generatorContext, generators } = state
589
+ const transformedNode: TNode = plugin.transformer ? (transform(node, plugin.transformer) as TNode) : node
590
+
591
+ if (
592
+ dispatch.checkAllowedNames &&
593
+ state.allowedSchemaNames !== null &&
594
+ 'name' in transformedNode &&
595
+ transformedNode.name &&
596
+ !state.allowedSchemaNames.has(transformedNode.name)
597
+ ) {
598
+ return
599
+ }
600
+
601
+ const { exclude, include, override } = plugin.options
602
+ const options = state.optionsAreStatic
603
+ ? plugin.options
604
+ : generatorContext.resolver.resolveOptions(transformedNode, { options: plugin.options, exclude, include, override })
605
+ if (options === null) return
606
+
607
+ const ctx = { ...generatorContext, options }
608
+ for (const gen of generators) {
609
+ const generate = gen[dispatch.method] as ((node: TNode, ctx: GeneratorContext) => unknown) | undefined
610
+ if (!generate) continue
611
+ const raw = generate(transformedNode, ctx)
612
+ const result = isPromise(raw) ? await raw : raw
613
+ const applied = applyHookResult({ result, driver, rendererFactory: resolveRendererFor(gen, state) })
614
+ if (isPromise(applied)) await applied
615
+ }
616
+ if (dispatch.emit) await dispatch.emit(transformedNode, ctx)
617
+ } catch (caughtError) {
618
+ state.failed = true
619
+ state.error = caughtError as Error
620
+ }
621
+ }
622
+
623
+ const schemaDispatch = {
624
+ method: 'schema',
625
+ checkAllowedNames: true,
626
+ emit: emitsSchemaHook ? (node: SchemaNode, ctx: GeneratorContext) => this.hooks.emit('kubb:generate:schema', node, ctx) : null,
627
+ } as const
628
+ const operationDispatch = {
629
+ method: 'operation',
630
+ checkAllowedNames: false,
631
+ emit: emitsOperationHook ? (node: OperationNode, ctx: GeneratorContext) => this.hooks.emit('kubb:generate:operation', node, ctx) : null,
632
+ } as const
633
+
634
+ // Skip building the aggregated operations array when nothing consumes it.
635
+ // Saves an N-sized allocation that lives until the build ends, on the common
636
+ // path where plugins only define per-node `gen.operation`.
637
+ const needsCollectedOperations = this.hooks.listenerCount('kubb:generate:operations') > 0 || states.some((s) => s.generators.some((g) => !!g.operations))
638
+ const collectedOperations: Array<OperationNode> = needsCollectedOperations ? [] : (undefined as never)
639
+
640
+ // Run schemas before operations: the two passes share `flushPending` and the
641
+ // FileProcessor's event emitter, so running them concurrently would interleave
642
+ // `kubb:files:processing:start|end` events and race on the shared dirty list.
643
+ await forBatches(schemas, (nodes) => Promise.all(nodes.flatMap((n) => states.map((state) => dispatchNode(state, n, schemaDispatch)))), {
644
+ concurrency: SCHEMA_PARALLEL,
645
+ flush: flushPending,
646
+ })
647
+
648
+ await forBatches(
649
+ operations,
650
+ (nodes) => {
651
+ if (needsCollectedOperations) collectedOperations.push(...nodes)
652
+ return Promise.all(nodes.flatMap((n) => states.map((state) => dispatchNode(state, n, operationDispatch))))
653
+ },
654
+ { concurrency: SCHEMA_PARALLEL, flush: flushPending },
655
+ )
656
+
657
+ for (const state of states) {
658
+ if (!state.failed && needsCollectedOperations) {
659
+ try {
660
+ const { plugin, generatorContext, generators } = state
661
+ const ctx = { ...generatorContext, options: plugin.options }
662
+ // Filter to operations this plugin would have dispatched to gen.operation():
663
+ // excludes/includes/overrides that resolve to null in dispatchOperation must also
664
+ // be hidden from the batched gen.operations() hook, otherwise grouped/barrel
665
+ // generators emit references to operation files that the per-op hook intentionally skipped.
666
+ const pluginOperations = state.optionsAreStatic
667
+ ? collectedOperations
668
+ : collectedOperations.filter((node) => {
669
+ const transformed = plugin.transformer ? transform(node, plugin.transformer) : node
670
+ const { exclude, include, override } = plugin.options
671
+
672
+ return generatorContext.resolver.resolveOptions(transformed, { options: plugin.options, exclude, include, override }) !== null
673
+ })
674
+ for (const gen of generators) {
675
+ if (!gen.operations) continue
676
+ const result = await gen.operations(pluginOperations, ctx)
677
+ await applyHookResult({ result, driver, rendererFactory: resolveRendererFor(gen, state) })
678
+ }
679
+ await this.hooks.emit('kubb:generate:operations', pluginOperations, ctx)
680
+ } catch (caughtError) {
681
+ state.failed = true
682
+ state.error = caughtError as Error
683
+ }
684
+ }
685
+
686
+ const duration = getElapsedMs(state.hrStart)
687
+ timings.set(state.plugin.name, duration)
688
+ await this.#emitPluginEnd({ plugin: state.plugin, duration, success: !state.failed, error: state.failed && state.error ? state.error : undefined })
689
+
690
+ if (state.failed && state.error) failed.add({ plugin: state.plugin, error: state.error })
691
+
692
+ await this.hooks.emit('kubb:debug', {
693
+ date: new Date(),
694
+ logs: [state.failed ? '✗ Plugin start failed' : `✓ Plugin started successfully (${formatMs(duration)})`],
695
+ })
696
+ }
697
+
698
+ return { timings, failed }
699
+ }
700
+
701
+ /**
702
+ * Unregisters all plugin lifecycle listeners from the shared event emitter.
703
+ * Called at the end of a build to prevent listener leaks across repeated builds.
704
+ *
705
+ * @internal
706
+ */
707
+ dispose(): void {
708
+ for (const [event, handlers] of this.#hookListeners) {
709
+ for (const handler of handlers) {
710
+ this.hooks.off(event, handler as never)
711
+ }
712
+ }
713
+
714
+ this.#hookListeners.clear()
715
+ this.#eventGeneratorPlugins.clear()
716
+ // Release resolver closures — the driver is rebuilt for each build() call
717
+ // so there is no value in retaining these maps after disposal.
718
+ this.#resolvers.clear()
719
+ this.#defaultResolvers.clear()
720
+ // Release the FileNode cache, parsed adapter graph, and studio state so
721
+ // memory is reclaimed between builds. The returned `BuildOutput.files`
722
+ // array still references any FileNodes the caller needs to inspect.
723
+ this.fileManager.dispose()
724
+ this.#fileProcessor.dispose()
725
+ this.inputNode = null
726
+ this.#studio = { source: null, isOpen: false, inputNode: null }
727
+
728
+ for (const [event, handler] of this.#middlewareListeners) {
729
+ this.hooks.off(event, handler as never)
730
+ }
731
+ }
732
+
733
+ [Symbol.dispose](): void {
734
+ this.dispose()
735
+ }
736
+
737
+ #trackHookListener(event: keyof KubbHooks, handler: (...args: Array<never>) => void | Promise<void>): void {
738
+ let handlers = this.#hookListeners.get(event)
739
+ if (!handlers) {
740
+ handlers = new Set()
741
+ this.#hookListeners.set(event, handlers)
742
+ }
743
+ handlers.add(handler)
744
+ }
745
+
746
+ #getDefaultResolver = memoize(
747
+ this.#defaultResolvers,
748
+ (pluginName: string): Resolver => defineResolver<PluginFactoryOptions>(() => ({ name: 'default', pluginName })),
749
+ )
750
+
751
+ /**
752
+ * Merges `partial` with the plugin's default resolver and stores the result.
753
+ * Also mirrors it onto `plugin.resolver` so callers using `getPlugin(name).resolver`
754
+ * get the up-to-date resolver without going through `getResolver()`.
755
+ */
756
+ setPluginResolver(pluginName: string, partial: Partial<Resolver>): void {
757
+ const defaultResolver = this.#getDefaultResolver(pluginName)
758
+ const merged = { ...defaultResolver, ...partial }
759
+ this.#resolvers.set(pluginName, merged)
760
+ const plugin = this.plugins.get(pluginName)
761
+ if (plugin) {
762
+ plugin.resolver = merged
763
+ }
764
+ }
765
+
766
+ /**
767
+ * Returns the resolver for the given plugin.
768
+ *
769
+ * Resolution order: dynamic resolver set via `setPluginResolver` → static resolver on the
770
+ * plugin → lazily created default resolver (identity name, no path transforms).
771
+ */
772
+ getResolver<TName extends keyof Kubb.PluginRegistry>(pluginName: TName): Kubb.PluginRegistry[TName]['resolver']
773
+ getResolver<TResolver extends Resolver = Resolver>(pluginName: string): TResolver
774
+ getResolver(pluginName: string): Resolver {
775
+ return this.#resolvers.get(pluginName) ?? this.plugins.get(pluginName)?.resolver ?? this.#getDefaultResolver(pluginName)
776
+ }
777
+
778
+ getContext<TOptions extends PluginFactoryOptions>(plugin: NormalizedPlugin<TOptions>): GeneratorContext<TOptions> & Record<string, unknown> {
779
+ const driver = this
780
+
781
+ return {
782
+ config: driver.config,
783
+ get root(): string {
784
+ return resolve(driver.config.root, driver.config.output.path)
785
+ },
786
+ getMode(output: { path: string }): 'single' | 'split' {
787
+ return KubbDriver.getMode(resolve(driver.config.root, driver.config.output.path, output.path))
788
+ },
789
+ hooks: driver.hooks,
790
+ plugin,
791
+ getPlugin: driver.getPlugin.bind(driver),
792
+ requirePlugin: driver.requirePlugin.bind(driver),
793
+ getResolver: driver.getResolver.bind(driver),
794
+ driver,
795
+ addFile: async (...files: Array<FileNode>) => {
796
+ driver.fileManager.add(...files)
797
+ },
798
+ upsertFile: async (...files: Array<FileNode>) => {
799
+ driver.fileManager.upsert(...files)
800
+ },
801
+ get meta(): InputMeta {
802
+ return driver.inputNode?.meta ?? { circularNames: [], enumNames: [] }
803
+ },
804
+ get adapter(): Adapter | null {
805
+ return driver.adapter
806
+ },
807
+ get resolver() {
808
+ return driver.getResolver(plugin.name)
809
+ },
810
+ get transformer() {
811
+ return plugin.transformer
812
+ },
813
+ warn(message: string) {
814
+ driver.hooks.emit('kubb:warn', { message })
815
+ },
816
+ error(error: string | Error) {
817
+ driver.hooks.emit('kubb:error', { error: typeof error === 'string' ? new Error(error) : error })
818
+ },
819
+ info(message: string) {
820
+ driver.hooks.emit('kubb:info', { message })
821
+ },
822
+ async openInStudio(options?: DevtoolsOptions) {
823
+ if (!driver.config.devtools || driver.#studio.isOpen) {
824
+ return
825
+ }
826
+
827
+ if (typeof driver.config.devtools !== 'object') {
828
+ throw new Error('Devtools must be an object')
829
+ }
830
+
831
+ if (!driver.adapter || !driver.#studio.source) {
832
+ throw new Error('adapter is not defined, make sure you have set the parser in kubb.config.ts')
833
+ }
834
+
835
+ driver.#studio.isOpen = true
836
+
837
+ const studioUrl = driver.config.devtools?.studioUrl ?? DEFAULT_STUDIO_URL
838
+ driver.#studio.inputNode ??= Promise.resolve(driver.adapter.parse(driver.#studio.source))
839
+ const inputNode = await driver.#studio.inputNode
840
+
841
+ return openInStudioFn(inputNode, studioUrl, options)
842
+ },
843
+ } as unknown as GeneratorContext<TOptions>
844
+ }
845
+
846
+ getPlugin<TName extends keyof Kubb.PluginRegistry>(pluginName: TName): Plugin<Kubb.PluginRegistry[TName]> | undefined
847
+ getPlugin<TOptions extends PluginFactoryOptions = PluginFactoryOptions>(pluginName: string): Plugin<TOptions> | undefined
848
+ getPlugin(pluginName: string): Plugin | undefined {
849
+ return this.plugins.get(pluginName)
850
+ }
851
+
852
+ /**
853
+ * Like `getPlugin` but throws a descriptive error when the plugin is not found.
854
+ */
855
+ requirePlugin<TName extends keyof Kubb.PluginRegistry>(pluginName: TName): Plugin<Kubb.PluginRegistry[TName]>
856
+ requirePlugin<TOptions extends PluginFactoryOptions = PluginFactoryOptions>(pluginName: string): Plugin<TOptions>
857
+ requirePlugin(pluginName: string): Plugin {
858
+ const plugin = this.plugins.get(pluginName)
859
+ if (!plugin) {
860
+ throw new Error(`[kubb] Plugin "${pluginName}" is required but not found. Make sure it is included in your Kubb config.`)
861
+ }
862
+ return plugin
863
+ }
864
+ }
865
+
866
+ /**
867
+ * Handles the return value of a plugin AST hook or generator method.
868
+ *
869
+ * - Renderer output → rendered via the provided `rendererFactory` (e.g. JSX), files stored in `driver.fileManager`
870
+ * - `Array<FileNode>` → added directly into `driver.fileManager`
871
+ * - `void` / `null` / `undefined` → no-op (plugin handled it via `this.upsertFile`)
872
+ *
873
+ * Pass a `rendererFactory` (e.g. `jsxRenderer` from `@kubb/renderer-jsx`) when the result
874
+ * may be a renderer element. Generators that only return `Array<FileNode>` do not need one.
875
+ */
876
+ export function applyHookResult<TElement = unknown>({
877
+ result,
878
+ driver,
879
+ rendererFactory,
880
+ }: {
881
+ result: TElement | Array<FileNode> | undefined | null
882
+ driver: KubbDriver
883
+ rendererFactory?: RendererFactory<TElement> | null
884
+ }): void | Promise<void> {
885
+ if (!result) return
886
+
887
+ if (Array.isArray(result)) {
888
+ driver.fileManager.upsert(...(result as Array<FileNode>))
889
+ return
890
+ }
891
+
892
+ if (!rendererFactory) {
893
+ return
894
+ }
895
+
896
+ const renderer = rendererFactory()
897
+ if (renderer.stream) {
898
+ using r = renderer
899
+ for (const file of r.stream!(result)) {
900
+ driver.fileManager.upsert(file)
901
+ }
902
+ return
903
+ }
904
+ return applyAsyncRender({ renderer, result, driver })
905
+ }
906
+
907
+ async function applyAsyncRender<TElement>({ renderer, result, driver }: { renderer: Renderer<TElement>; result: TElement; driver: KubbDriver }): Promise<void> {
908
+ using r = renderer
909
+ await r.render(result)
910
+ driver.fileManager.upsert(...r.files)
911
+ }
912
+
913
+ function inputToAdapterSource(config: Config): AdapterSource {
914
+ const input = config.input
915
+ if (!input) {
916
+ throw new Error('[kubb] input is required when using an adapter. Provide input.path or input.data in your config.')
917
+ }
918
+
919
+ if ('data' in input) {
920
+ return { type: 'data', data: input.data }
921
+ }
922
+
923
+ if (new URLPath(input.path).isURL) {
924
+ return { type: 'path', path: input.path }
925
+ }
926
+
927
+ const resolved = resolve(config.root, input.path)
928
+
929
+ return { type: 'path', path: resolved }
930
+ }