@kubb/core 5.0.0-alpha.8 → 5.0.0-beta.75

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 (70) hide show
  1. package/README.md +23 -20
  2. package/dist/PluginDriver-BXibeQk-.cjs +1036 -0
  3. package/dist/PluginDriver-BXibeQk-.cjs.map +1 -0
  4. package/dist/PluginDriver-DV3p2Hky.js +945 -0
  5. package/dist/PluginDriver-DV3p2Hky.js.map +1 -0
  6. package/dist/index.cjs +756 -1693
  7. package/dist/index.cjs.map +1 -1
  8. package/dist/index.d.ts +297 -239
  9. package/dist/index.js +743 -1661
  10. package/dist/index.js.map +1 -1
  11. package/dist/mocks.cjs +145 -0
  12. package/dist/mocks.cjs.map +1 -0
  13. package/dist/mocks.d.ts +80 -0
  14. package/dist/mocks.js +140 -0
  15. package/dist/mocks.js.map +1 -0
  16. package/dist/types-CuNocrbJ.d.ts +2148 -0
  17. package/package.json +51 -57
  18. package/src/FileManager.ts +115 -0
  19. package/src/FileProcessor.ts +86 -0
  20. package/src/Kubb.ts +208 -160
  21. package/src/PluginDriver.ts +326 -565
  22. package/src/constants.ts +20 -47
  23. package/src/createAdapter.ts +16 -6
  24. package/src/createKubb.ts +548 -0
  25. package/src/createRenderer.ts +57 -0
  26. package/src/createStorage.ts +40 -26
  27. package/src/defineGenerator.ts +87 -0
  28. package/src/defineLogger.ts +19 -0
  29. package/src/defineMiddleware.ts +62 -0
  30. package/src/defineParser.ts +44 -0
  31. package/src/definePlugin.ts +83 -0
  32. package/src/defineResolver.ts +521 -0
  33. package/src/devtools.ts +14 -14
  34. package/src/index.ts +14 -17
  35. package/src/mocks.ts +178 -0
  36. package/src/renderNode.ts +35 -0
  37. package/src/storages/fsStorage.ts +41 -11
  38. package/src/storages/memoryStorage.ts +4 -2
  39. package/src/types.ts +1054 -270
  40. package/src/utils/diagnostics.ts +4 -1
  41. package/src/utils/isInputPath.ts +10 -0
  42. package/src/utils/packageJSON.ts +99 -0
  43. package/dist/PluginDriver-DRfJIbG1.d.ts +0 -1056
  44. package/dist/chunk-ByKO4r7w.cjs +0 -38
  45. package/dist/hooks.cjs +0 -102
  46. package/dist/hooks.cjs.map +0 -1
  47. package/dist/hooks.d.ts +0 -75
  48. package/dist/hooks.js +0 -97
  49. package/dist/hooks.js.map +0 -1
  50. package/src/PackageManager.ts +0 -180
  51. package/src/build.ts +0 -419
  52. package/src/config.ts +0 -56
  53. package/src/createGenerator.ts +0 -106
  54. package/src/createLogger.ts +0 -7
  55. package/src/createPlugin.ts +0 -12
  56. package/src/errors.ts +0 -1
  57. package/src/hooks/index.ts +0 -4
  58. package/src/hooks/useKubb.ts +0 -138
  59. package/src/hooks/useMode.ts +0 -11
  60. package/src/hooks/usePlugin.ts +0 -11
  61. package/src/hooks/usePluginDriver.ts +0 -11
  62. package/src/utils/FunctionParams.ts +0 -155
  63. package/src/utils/TreeNode.ts +0 -215
  64. package/src/utils/executeStrategies.ts +0 -81
  65. package/src/utils/formatters.ts +0 -56
  66. package/src/utils/getBarrelFiles.ts +0 -141
  67. package/src/utils/getConfigs.ts +0 -30
  68. package/src/utils/getPlugins.ts +0 -23
  69. package/src/utils/linters.ts +0 -25
  70. package/src/utils/resolveOptions.ts +0 -93
package/src/constants.ts CHANGED
@@ -1,21 +1,30 @@
1
- import type { KubbFile } from '@kubb/fabric-core/types'
1
+ import type { FileNode } from '@kubb/ast'
2
2
 
3
+ /**
4
+ * Base URL for the Kubb Studio web app.
5
+ */
3
6
  export const DEFAULT_STUDIO_URL = 'https://studio.kubb.dev' as const
4
7
 
5
- export const CORE_PLUGIN_NAME = 'core' as const
6
-
7
- export const DEFAULT_MAX_LISTENERS = 100
8
-
9
- export const DEFAULT_CONCURRENCY = 15
10
-
11
- export const BARREL_FILENAME = 'index.ts' as const
8
+ /**
9
+ * Maximum number of files processed in parallel by FileProcessor.
10
+ */
11
+ export const PARALLEL_CONCURRENCY_LIMIT = 100
12
12
 
13
+ /**
14
+ * Default banner style written at the top of every generated file.
15
+ */
13
16
  export const DEFAULT_BANNER = 'simple' as const
14
17
 
15
- export const DEFAULT_EXTENSION: Record<KubbFile.Extname, KubbFile.Extname | ''> = { '.ts': '.ts' }
16
-
17
- export const PATH_SEPARATORS = ['/', '\\'] as const
18
+ /**
19
+ * Default file-extension mapping used when no explicit mapping is configured.
20
+ */
21
+ export const DEFAULT_EXTENSION: Record<FileNode['extname'], FileNode['extname'] | ''> = { '.ts': '.ts' }
18
22
 
23
+ /**
24
+ * Numeric log-level thresholds used internally to compare verbosity.
25
+ *
26
+ * Higher numbers are more verbose.
27
+ */
19
28
  export const logLevel = {
20
29
  silent: Number.NEGATIVE_INFINITY,
21
30
  error: 0,
@@ -24,39 +33,3 @@ export const logLevel = {
24
33
  verbose: 4,
25
34
  debug: 5,
26
35
  } as const
27
-
28
- export const linters = {
29
- eslint: {
30
- command: 'eslint',
31
- args: (outputPath: string) => [outputPath, '--fix'],
32
- errorMessage: 'Eslint not found',
33
- },
34
- biome: {
35
- command: 'biome',
36
- args: (outputPath: string) => ['lint', '--fix', outputPath],
37
- errorMessage: 'Biome not found',
38
- },
39
- oxlint: {
40
- command: 'oxlint',
41
- args: (outputPath: string) => ['--fix', outputPath],
42
- errorMessage: 'Oxlint not found',
43
- },
44
- } as const
45
-
46
- export const formatters = {
47
- prettier: {
48
- command: 'prettier',
49
- args: (outputPath: string) => ['--ignore-unknown', '--write', outputPath],
50
- errorMessage: 'Prettier not found',
51
- },
52
- biome: {
53
- command: 'biome',
54
- args: (outputPath: string) => ['format', '--write', outputPath],
55
- errorMessage: 'Biome not found',
56
- },
57
- oxfmt: {
58
- command: 'oxfmt',
59
- args: (outputPath: string) => [outputPath],
60
- errorMessage: 'Oxfmt not found',
61
- },
62
- } as const
@@ -3,18 +3,28 @@ import type { Adapter, AdapterFactoryOptions } from './types.ts'
3
3
  type AdapterBuilder<T extends AdapterFactoryOptions> = (options: T['options']) => Adapter<T>
4
4
 
5
5
  /**
6
- * Wraps an adapter builder to make the options parameter optional.
6
+ * Factory for implementing custom adapters that translate non-OpenAPI specs into Kubb's AST.
7
+ *
8
+ * Use this to support GraphQL schemas, gRPC definitions, AsyncAPI, or custom domain-specific languages.
9
+ * Built-in adapters include `@kubb/adapter-oas` for OpenAPI and Swagger documents.
10
+ *
11
+ * @note Adapters must parse their input format to Kubb's `InputNode` structure.
7
12
  *
8
13
  * @example
9
14
  * ```ts
10
- * export const adapterOas = createAdapter<OasAdapter>((options) => {
11
- * const { validate = true, dateType = 'string' } = options
15
+ * export const myAdapter = createAdapter<MyAdapter>((options) => {
12
16
  * return {
13
- * name: adapterOasName,
14
- * options: { validate, dateType, ... },
15
- * parse(source) { ... },
17
+ * name: 'my-adapter',
18
+ * options,
19
+ * async parse(source) {
20
+ * // Transform source format to InputNode
21
+ * return { ... }
22
+ * },
16
23
  * }
17
24
  * })
25
+ *
26
+ * // Instantiate:
27
+ * const adapter = myAdapter({ validate: true })
18
28
  * ```
19
29
  */
20
30
  export function createAdapter<T extends AdapterFactoryOptions = AdapterFactoryOptions>(build: AdapterBuilder<T>): (options?: T['options']) => Adapter<T> {
@@ -0,0 +1,548 @@
1
+ import { resolve } from 'node:path'
2
+ import { AsyncEventEmitter, BuildError, exists, formatMs, getElapsedMs, URLPath } from '@internals/utils'
3
+ import type { FileNode, OperationNode } from '@kubb/ast'
4
+ import { transform, walk } from '@kubb/ast'
5
+ import { DEFAULT_BANNER, DEFAULT_EXTENSION, DEFAULT_STUDIO_URL } from './constants.ts'
6
+ import type { RendererFactory } from './createRenderer.ts'
7
+ import type { Generator } from './defineGenerator.ts'
8
+ import type { Parser } from './defineParser.ts'
9
+ import type { Plugin } from './definePlugin.ts'
10
+ import { FileProcessor } from './FileProcessor.ts'
11
+ import type { Kubb } from './Kubb.ts'
12
+ import { PluginDriver } from './PluginDriver.ts'
13
+ import { applyHookResult } from './renderNode.ts'
14
+ import { fsStorage } from './storages/fsStorage.ts'
15
+ import type { AdapterSource, Config, GeneratorContext, KubbHooks, Middleware, NormalizedPlugin, Storage, UserConfig } from './types.ts'
16
+ import { getDiagnosticInfo } from './utils/diagnostics.ts'
17
+ import { isInputPath } from './utils/isInputPath.ts'
18
+
19
+ type SetupOptions = {
20
+ hooks?: AsyncEventEmitter<KubbHooks>
21
+ }
22
+
23
+ /**
24
+ * Full output produced by a successful or failed build.
25
+ */
26
+ export type BuildOutput = {
27
+ /**
28
+ * Plugins that threw during installation, paired with the caught error.
29
+ */
30
+ failedPlugins: Set<{ plugin: Plugin; error: Error }>
31
+ files: Array<FileNode>
32
+ driver: PluginDriver
33
+ /**
34
+ * Elapsed time in milliseconds for each plugin, keyed by plugin name.
35
+ */
36
+ pluginTimings: Map<string, number>
37
+ error?: Error
38
+ /**
39
+ * Raw generated source, keyed by absolute file path.
40
+ */
41
+ sources: Map<string, string>
42
+ }
43
+
44
+ type SetupResult = {
45
+ hooks: AsyncEventEmitter<KubbHooks>
46
+ driver: PluginDriver
47
+ sources: Map<string, string>
48
+ config: Config
49
+ storage: Storage | null
50
+ }
51
+
52
+ async function setup(userConfig: UserConfig, options: SetupOptions = {}): Promise<SetupResult> {
53
+ const hooks = options.hooks ?? new AsyncEventEmitter<KubbHooks>()
54
+
55
+ const sources: Map<string, string> = new Map<string, string>()
56
+ const diagnosticInfo = getDiagnosticInfo()
57
+
58
+ if (Array.isArray(userConfig.input)) {
59
+ await hooks.emit('kubb:warn', { message: 'This feature is still under development — use with caution' })
60
+ }
61
+
62
+ await hooks.emit('kubb:debug', {
63
+ date: new Date(),
64
+ logs: [
65
+ 'Configuration:',
66
+ ` • Name: ${userConfig.name || 'unnamed'}`,
67
+ ` • Root: ${userConfig.root || process.cwd()}`,
68
+ ` • Output: ${userConfig.output?.path || 'not specified'}`,
69
+ ` • Plugins: ${userConfig.plugins?.length || 0}`,
70
+ 'Output Settings:',
71
+ ` • Storage: ${userConfig.storage ? `custom(${userConfig.storage.name})` : userConfig.output?.write === false ? 'disabled' : 'filesystem (default)'}`,
72
+ ` • Formatter: ${userConfig.output?.format || 'none'}`,
73
+ ` • Linter: ${userConfig.output?.lint || 'none'}`,
74
+ 'Environment:',
75
+ Object.entries(diagnosticInfo)
76
+ .map(([key, value]) => ` • ${key}: ${value}`)
77
+ .join('\n'),
78
+ ],
79
+ })
80
+
81
+ try {
82
+ if (isInputPath(userConfig) && !new URLPath(userConfig.input.path).isURL) {
83
+ await exists(userConfig.input.path)
84
+
85
+ await hooks.emit('kubb:debug', {
86
+ date: new Date(),
87
+ logs: [`✓ Input file validated: ${userConfig.input.path}`],
88
+ })
89
+ }
90
+ } catch (caughtError) {
91
+ if (isInputPath(userConfig)) {
92
+ const error = caughtError as Error
93
+
94
+ throw new Error(
95
+ `Cannot read file/URL defined in \`input.path\` or set with \`kubb generate PATH\` in the CLI of your Kubb config ${userConfig.input.path}`,
96
+ {
97
+ cause: error,
98
+ },
99
+ )
100
+ }
101
+ }
102
+
103
+ if (!userConfig.adapter) {
104
+ throw new Error('Adapter should be defined')
105
+ }
106
+
107
+ const config: Config = {
108
+ ...userConfig,
109
+ root: userConfig.root || process.cwd(),
110
+ parsers: userConfig.parsers ?? [],
111
+ adapter: userConfig.adapter,
112
+ output: {
113
+ format: false,
114
+ lint: false,
115
+ write: true,
116
+ extension: DEFAULT_EXTENSION,
117
+ defaultBanner: DEFAULT_BANNER,
118
+ ...userConfig.output,
119
+ },
120
+ devtools: userConfig.devtools
121
+ ? {
122
+ studioUrl: DEFAULT_STUDIO_URL,
123
+ ...(typeof userConfig.devtools === 'boolean' ? {} : userConfig.devtools),
124
+ }
125
+ : undefined,
126
+ plugins: userConfig.plugins as unknown as Config['plugins'],
127
+ }
128
+
129
+ const storage: Storage | null = config.output.write === false ? null : (config.storage ?? fsStorage())
130
+
131
+ if (config.output.clean) {
132
+ await hooks.emit('kubb:debug', {
133
+ date: new Date(),
134
+ logs: ['Cleaning output directories', ` • Output: ${config.output.path}`],
135
+ })
136
+ await storage?.clear(resolve(config.root, config.output.path))
137
+ }
138
+
139
+ const driver = new PluginDriver(config, {
140
+ hooks,
141
+ })
142
+
143
+ // Register middleware hooks after all plugin hooks are registered.
144
+ // Because AsyncEventEmitter calls listeners in registration order,
145
+ // middleware hooks for any event fire after all plugin hooks for that event.
146
+ function registerMiddlewareHook<K extends keyof KubbHooks & string>(event: K, middlewareHooks: Middleware['hooks']) {
147
+ const handler = middlewareHooks[event]
148
+ if (handler) {
149
+ hooks.on(event, handler)
150
+ }
151
+ }
152
+
153
+ for (const middleware of config.middleware ?? []) {
154
+ for (const event of Object.keys(middleware.hooks) as Array<keyof KubbHooks & string>) {
155
+ registerMiddlewareHook(event, middleware.hooks)
156
+ }
157
+ }
158
+
159
+ const adapter = config.adapter
160
+ if (!adapter) {
161
+ throw new Error('No adapter configured. Please provide an adapter in your kubb.config.ts.')
162
+ }
163
+ const source = inputToAdapterSource(config)
164
+
165
+ await hooks.emit('kubb:debug', {
166
+ date: new Date(),
167
+ logs: [`Running adapter: ${adapter.name}`],
168
+ })
169
+
170
+ driver.adapter = adapter
171
+ driver.inputNode = await adapter.parse(source)
172
+
173
+ await hooks.emit('kubb:debug', {
174
+ date: new Date(),
175
+ logs: [
176
+ `✓ Adapter '${adapter.name}' resolved InputNode`,
177
+ ` • Schemas: ${driver.inputNode.schemas.length}`,
178
+ ` • Operations: ${driver.inputNode.operations.length}`,
179
+ ],
180
+ })
181
+
182
+ return {
183
+ config,
184
+ hooks,
185
+ driver,
186
+ sources,
187
+ storage,
188
+ }
189
+ }
190
+
191
+ /**
192
+ * Walks the AST and dispatches nodes to a plugin's direct AST hooks
193
+ * (`schema`, `operation`, `operations`).
194
+ */
195
+ async function runPluginAstHooks(plugin: NormalizedPlugin, context: GeneratorContext): Promise<void> {
196
+ const { adapter, inputNode, resolver, driver } = context
197
+ const { exclude, include, override } = plugin.options
198
+
199
+ if (!adapter || !inputNode) {
200
+ throw new Error(`[${plugin.name}] No adapter found. Add an OAS adapter (e.g. pluginOas()) before this plugin in your Kubb config.`)
201
+ }
202
+
203
+ function resolveRenderer(gen: Generator): RendererFactory | undefined {
204
+ return gen.renderer === null ? undefined : (gen.renderer ?? plugin.renderer ?? context.config.renderer)
205
+ }
206
+
207
+ const generators = plugin.generators ?? []
208
+ const collectedOperations: Array<OperationNode> = []
209
+
210
+ const generatorContext = {
211
+ ...context,
212
+ resolver: driver.getResolver(plugin.name),
213
+ }
214
+
215
+ await walk(inputNode, {
216
+ depth: 'shallow',
217
+ async schema(node) {
218
+ const transformedNode = plugin.transformer ? transform(node, plugin.transformer) : node
219
+ const options = resolver.resolveOptions(transformedNode, {
220
+ options: plugin.options,
221
+ exclude,
222
+ include,
223
+ override,
224
+ })
225
+ if (options === null) return
226
+
227
+ const ctx = { ...generatorContext, options }
228
+
229
+ for (const gen of generators) {
230
+ if (!gen.schema) continue
231
+ const result = await gen.schema(transformedNode, ctx)
232
+ await applyHookResult(result, driver, resolveRenderer(gen))
233
+ }
234
+
235
+ await driver.hooks.emit('kubb:generate:schema', transformedNode, ctx)
236
+ },
237
+ async operation(node) {
238
+ const transformedNode = plugin.transformer ? transform(node, plugin.transformer) : node
239
+ const options = resolver.resolveOptions(transformedNode, {
240
+ options: plugin.options,
241
+ exclude,
242
+ include,
243
+ override,
244
+ })
245
+ if (options !== null) {
246
+ collectedOperations.push(transformedNode)
247
+
248
+ const ctx = { ...generatorContext, options }
249
+
250
+ for (const gen of generators) {
251
+ if (!gen.operation) continue
252
+ const result = await gen.operation(transformedNode, ctx)
253
+ await applyHookResult(result, driver, resolveRenderer(gen))
254
+ }
255
+
256
+ await driver.hooks.emit('kubb:generate:operation', transformedNode, ctx)
257
+ }
258
+ },
259
+ })
260
+
261
+ if (collectedOperations.length > 0) {
262
+ const ctx = { ...generatorContext, options: plugin.options }
263
+
264
+ for (const gen of generators) {
265
+ if (!gen.operations) continue
266
+ const result = await gen.operations(collectedOperations, ctx)
267
+ await applyHookResult(result, driver, resolveRenderer(gen))
268
+ }
269
+
270
+ await driver.hooks.emit('kubb:generate:operations', collectedOperations, ctx)
271
+ }
272
+ }
273
+
274
+ async function safeBuild(setupResult: SetupResult): Promise<BuildOutput> {
275
+ const { driver, hooks, sources, storage } = setupResult
276
+
277
+ const failedPlugins = new Set<{ plugin: Plugin; error: Error }>()
278
+ const pluginTimings = new Map<string, number>()
279
+ const config = driver.config
280
+
281
+ try {
282
+ await driver.emitSetupHooks()
283
+
284
+ if (driver.adapter && driver.inputNode) {
285
+ await hooks.emit('kubb:build:start', {
286
+ config,
287
+ adapter: driver.adapter,
288
+ inputNode: driver.inputNode,
289
+ getPlugin: driver.getPlugin.bind(driver),
290
+ get files() {
291
+ return driver.fileManager.files
292
+ },
293
+ upsertFile: (...files) => driver.fileManager.upsert(...files),
294
+ })
295
+ }
296
+
297
+ for (const plugin of driver.plugins.values()) {
298
+ const context = driver.getContext(plugin)
299
+ const hrStart = process.hrtime()
300
+
301
+ try {
302
+ const timestamp = new Date()
303
+
304
+ await hooks.emit('kubb:plugin:start', { plugin })
305
+
306
+ await hooks.emit('kubb:debug', {
307
+ date: timestamp,
308
+ logs: ['Starting plugin...', ` • Plugin Name: ${plugin.name}`],
309
+ })
310
+
311
+ if (plugin.generators?.length || driver.hasRegisteredGenerators(plugin.name)) {
312
+ await runPluginAstHooks(plugin, context)
313
+ }
314
+
315
+ const duration = getElapsedMs(hrStart)
316
+ pluginTimings.set(plugin.name, duration)
317
+
318
+ await hooks.emit('kubb:plugin:end', {
319
+ plugin,
320
+ duration,
321
+ success: true,
322
+ config,
323
+ get files() {
324
+ return driver.fileManager.files
325
+ },
326
+ upsertFile: (...files) => driver.fileManager.upsert(...files),
327
+ })
328
+
329
+ await hooks.emit('kubb:debug', {
330
+ date: new Date(),
331
+ logs: [`✓ Plugin started successfully (${formatMs(duration)})`],
332
+ })
333
+ } catch (caughtError) {
334
+ const error = caughtError as Error
335
+ const errorTimestamp = new Date()
336
+ const duration = getElapsedMs(hrStart)
337
+
338
+ await hooks.emit('kubb:plugin:end', {
339
+ plugin,
340
+ duration,
341
+ success: false,
342
+ error,
343
+ config,
344
+ get files() {
345
+ return driver.fileManager.files
346
+ },
347
+ upsertFile: (...files) => driver.fileManager.upsert(...files),
348
+ })
349
+
350
+ await hooks.emit('kubb:debug', {
351
+ date: errorTimestamp,
352
+ logs: [
353
+ '✗ Plugin start failed',
354
+ ` • Plugin Name: ${plugin.name}`,
355
+ ` • Error: ${error.constructor.name} - ${error.message}`,
356
+ ' • Stack Trace:',
357
+ error.stack || 'No stack trace available',
358
+ ],
359
+ })
360
+
361
+ failedPlugins.add({ plugin, error })
362
+ }
363
+ }
364
+
365
+ await hooks.emit('kubb:plugins:end', {
366
+ config,
367
+ get files() {
368
+ return driver.fileManager.files
369
+ },
370
+ upsertFile: (...files) => driver.fileManager.upsert(...files),
371
+ })
372
+
373
+ const files = driver.fileManager.files
374
+
375
+ const parsersMap = new Map<FileNode['extname'], Parser>()
376
+ for (const parser of config.parsers) {
377
+ if (parser.extNames) {
378
+ for (const extname of parser.extNames) {
379
+ parsersMap.set(extname, parser)
380
+ }
381
+ }
382
+ }
383
+
384
+ const fileProcessor = new FileProcessor()
385
+
386
+ await hooks.emit('kubb:debug', {
387
+ date: new Date(),
388
+ logs: [`Writing ${files.length} files...`],
389
+ })
390
+
391
+ await fileProcessor.run(files, {
392
+ parsers: parsersMap,
393
+ extension: config.output.extension,
394
+ onStart: async (processingFiles) => {
395
+ await hooks.emit('kubb:files:processing:start', { files: processingFiles })
396
+ },
397
+ onUpdate: async ({ file, source, processed, total, percentage }) => {
398
+ await hooks.emit('kubb:file:processing:update', {
399
+ file,
400
+ source,
401
+ processed,
402
+ total,
403
+ percentage,
404
+ config,
405
+ })
406
+ if (source) {
407
+ await storage?.setItem(file.path, source)
408
+ sources.set(file.path, source)
409
+ }
410
+ },
411
+ onEnd: async (processedFiles) => {
412
+ await hooks.emit('kubb:files:processing:end', { files: processedFiles })
413
+ await hooks.emit('kubb:debug', {
414
+ date: new Date(),
415
+ logs: [`✓ File write process completed for ${processedFiles.length} files`],
416
+ })
417
+ },
418
+ })
419
+
420
+ await hooks.emit('kubb:build:end', {
421
+ files,
422
+ config,
423
+ outputDir: resolve(config.root, config.output.path),
424
+ })
425
+
426
+ return {
427
+ failedPlugins,
428
+ files,
429
+ driver,
430
+ pluginTimings,
431
+ sources,
432
+ }
433
+ } catch (error) {
434
+ return {
435
+ failedPlugins,
436
+ files: [],
437
+ driver,
438
+ pluginTimings,
439
+ error: error as Error,
440
+ sources,
441
+ }
442
+ } finally {
443
+ driver.dispose()
444
+ }
445
+ }
446
+
447
+ async function build(setupResult: SetupResult): Promise<BuildOutput> {
448
+ const { files, driver, failedPlugins, pluginTimings, error, sources } = await safeBuild(setupResult)
449
+
450
+ if (error) {
451
+ throw error
452
+ }
453
+
454
+ if (failedPlugins.size > 0) {
455
+ const errors = [...failedPlugins].map(({ error }) => error)
456
+
457
+ throw new BuildError(`Build Error with ${failedPlugins.size} failed plugins`, { errors })
458
+ }
459
+
460
+ return {
461
+ failedPlugins,
462
+ files,
463
+ driver,
464
+ pluginTimings,
465
+ error: undefined,
466
+ sources,
467
+ }
468
+ }
469
+
470
+ function inputToAdapterSource(config: Config): AdapterSource {
471
+ if (Array.isArray(config.input)) {
472
+ return {
473
+ type: 'paths',
474
+ paths: config.input.map((i) => (new URLPath(i.path).isURL ? i.path : resolve(config.root, i.path))),
475
+ }
476
+ }
477
+
478
+ if ('data' in config.input) {
479
+ return { type: 'data', data: config.input.data }
480
+ }
481
+
482
+ if (new URLPath(config.input.path).isURL) {
483
+ return { type: 'path', path: config.input.path }
484
+ }
485
+
486
+ const resolved = resolve(config.root, config.input.path)
487
+ return { type: 'path', path: resolved }
488
+ }
489
+
490
+ type CreateKubbOptions = {
491
+ hooks?: AsyncEventEmitter<KubbHooks>
492
+ }
493
+
494
+ /**
495
+ * Creates a Kubb instance bound to a single config entry.
496
+ *
497
+ * Accepts a user-facing config shape and resolves it to a full {@link Config} during
498
+ * `setup()`. The instance then holds shared state (`hooks`, `sources`, `driver`, `config`)
499
+ * across the `setup → build` lifecycle. Attach event listeners to `kubb.hooks` before
500
+ * calling `setup()` or `build()`.
501
+ *
502
+ * @example
503
+ * ```ts
504
+ * const kubb = createKubb(userConfig)
505
+ *
506
+ * kubb.hooks.on('kubb:plugin:end', ({ plugin, duration }) => {
507
+ * console.log(`${plugin.name} completed in ${duration}ms`)
508
+ * })
509
+ *
510
+ * const { files, failedPlugins } = await kubb.safeBuild()
511
+ * ```
512
+ */
513
+ export function createKubb(userConfig: UserConfig, options: CreateKubbOptions = {}): Kubb {
514
+ const hooks = options.hooks ?? new AsyncEventEmitter<KubbHooks>()
515
+ let setupResult: SetupResult | undefined
516
+
517
+ const instance: Kubb = {
518
+ get hooks() {
519
+ return hooks
520
+ },
521
+ get sources() {
522
+ return setupResult?.sources ?? new Map()
523
+ },
524
+ get driver() {
525
+ return setupResult?.driver
526
+ },
527
+ get config() {
528
+ return setupResult?.config
529
+ },
530
+ async setup() {
531
+ setupResult = await setup(userConfig, { hooks })
532
+ },
533
+ async build() {
534
+ if (!setupResult) {
535
+ await instance.setup()
536
+ }
537
+ return build(setupResult!)
538
+ },
539
+ async safeBuild() {
540
+ if (!setupResult) {
541
+ await instance.setup()
542
+ }
543
+ return safeBuild(setupResult!)
544
+ },
545
+ }
546
+
547
+ return instance
548
+ }