@kubb/core 5.0.0-alpha.7 → 5.0.0-alpha.70

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 (69) hide show
  1. package/README.md +3 -2
  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 +730 -1773
  7. package/dist/index.cjs.map +1 -1
  8. package/dist/index.d.ts +289 -240
  9. package/dist/index.js +717 -1741
  10. package/dist/index.js.map +1 -1
  11. package/dist/mocks.cjs +139 -0
  12. package/dist/mocks.cjs.map +1 -0
  13. package/dist/mocks.d.ts +74 -0
  14. package/dist/mocks.js +134 -0
  15. package/dist/mocks.js.map +1 -0
  16. package/dist/types-DWtkW2RX.d.ts +1915 -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 +205 -130
  21. package/src/PluginDriver.ts +326 -565
  22. package/src/constants.ts +20 -47
  23. package/src/createAdapter.ts +25 -0
  24. package/src/createKubb.ts +546 -0
  25. package/src/createRenderer.ts +57 -0
  26. package/src/createStorage.ts +58 -0
  27. package/src/defineGenerator.ts +88 -100
  28. package/src/defineLogger.ts +13 -3
  29. package/src/defineMiddleware.ts +64 -0
  30. package/src/defineParser.ts +45 -0
  31. package/src/definePlugin.ts +78 -7
  32. package/src/defineResolver.ts +521 -0
  33. package/src/devtools.ts +14 -14
  34. package/src/index.ts +13 -16
  35. package/src/mocks.ts +172 -0
  36. package/src/renderNode.ts +35 -0
  37. package/src/storages/fsStorage.ts +43 -13
  38. package/src/storages/memoryStorage.ts +6 -4
  39. package/src/types.ts +752 -226
  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-Dma9KhLK.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/defineAdapter.ts +0 -22
  54. package/src/defineStorage.ts +0 -56
  55. package/src/errors.ts +0 -1
  56. package/src/hooks/index.ts +0 -4
  57. package/src/hooks/useKubb.ts +0 -138
  58. package/src/hooks/useMode.ts +0 -11
  59. package/src/hooks/usePlugin.ts +0 -11
  60. package/src/hooks/usePluginDriver.ts +0 -11
  61. package/src/utils/FunctionParams.ts +0 -155
  62. package/src/utils/TreeNode.ts +0 -215
  63. package/src/utils/executeStrategies.ts +0 -81
  64. package/src/utils/formatters.ts +0 -56
  65. package/src/utils/getBarrelFiles.ts +0 -141
  66. package/src/utils/getConfigs.ts +0 -30
  67. package/src/utils/getPlugins.ts +0 -23
  68. package/src/utils/linters.ts +0 -25
  69. 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
@@ -0,0 +1,25 @@
1
+ import type { Adapter, AdapterFactoryOptions } from './types.ts'
2
+
3
+ /**
4
+ * Builder type for an {@link Adapter} — takes options and returns the adapter instance.
5
+ */
6
+ type AdapterBuilder<T extends AdapterFactoryOptions> = (options: T['options']) => Adapter<T>
7
+
8
+ /**
9
+ * Creates an adapter factory. Call the returned function with optional options to get the adapter instance.
10
+ *
11
+ * @example
12
+ * export const myAdapter = createAdapter<MyAdapter>((options) => {
13
+ * return {
14
+ * name: 'my-adapter',
15
+ * options,
16
+ * async parse(source) { ... },
17
+ * }
18
+ * })
19
+ *
20
+ * // instantiate
21
+ * const adapter = myAdapter({ validate: true })
22
+ */
23
+ export function createAdapter<T extends AdapterFactoryOptions = AdapterFactoryOptions>(build: AdapterBuilder<T>): (options?: T['options']) => Adapter<T> {
24
+ return (options) => build(options ?? ({} as T['options']))
25
+ }
@@ -0,0 +1,546 @@
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
+ write: true,
114
+ extension: DEFAULT_EXTENSION,
115
+ defaultBanner: DEFAULT_BANNER,
116
+ ...userConfig.output,
117
+ },
118
+ devtools: userConfig.devtools
119
+ ? {
120
+ studioUrl: DEFAULT_STUDIO_URL,
121
+ ...(typeof userConfig.devtools === 'boolean' ? {} : userConfig.devtools),
122
+ }
123
+ : undefined,
124
+ plugins: userConfig.plugins as unknown as Config['plugins'],
125
+ }
126
+
127
+ const storage: Storage | null = config.output.write === false ? null : (config.storage ?? fsStorage())
128
+
129
+ if (config.output.clean) {
130
+ await hooks.emit('kubb:debug', {
131
+ date: new Date(),
132
+ logs: ['Cleaning output directories', ` • Output: ${config.output.path}`],
133
+ })
134
+ await storage?.clear(resolve(config.root, config.output.path))
135
+ }
136
+
137
+ const driver = new PluginDriver(config, {
138
+ hooks,
139
+ })
140
+
141
+ // Register middleware hooks after all plugin hooks are registered.
142
+ // Because AsyncEventEmitter calls listeners in registration order,
143
+ // middleware hooks for any event fire after all plugin hooks for that event.
144
+ function registerMiddlewareHook<K extends keyof KubbHooks & string>(event: K, middlewareHooks: Middleware['hooks']) {
145
+ const handler = middlewareHooks[event]
146
+ if (handler) {
147
+ hooks.on(event, handler)
148
+ }
149
+ }
150
+
151
+ for (const middleware of config.middleware ?? []) {
152
+ for (const event of Object.keys(middleware.hooks) as Array<keyof KubbHooks & string>) {
153
+ registerMiddlewareHook(event, middleware.hooks)
154
+ }
155
+ }
156
+
157
+ const adapter = config.adapter
158
+ if (!adapter) {
159
+ throw new Error('No adapter configured. Please provide an adapter in your kubb.config.ts.')
160
+ }
161
+ const source = inputToAdapterSource(config)
162
+
163
+ await hooks.emit('kubb:debug', {
164
+ date: new Date(),
165
+ logs: [`Running adapter: ${adapter.name}`],
166
+ })
167
+
168
+ driver.adapter = adapter
169
+ driver.inputNode = await adapter.parse(source)
170
+
171
+ await hooks.emit('kubb:debug', {
172
+ date: new Date(),
173
+ logs: [
174
+ `✓ Adapter '${adapter.name}' resolved InputNode`,
175
+ ` • Schemas: ${driver.inputNode.schemas.length}`,
176
+ ` • Operations: ${driver.inputNode.operations.length}`,
177
+ ],
178
+ })
179
+
180
+ return {
181
+ config,
182
+ hooks,
183
+ driver,
184
+ sources,
185
+ storage,
186
+ }
187
+ }
188
+
189
+ /**
190
+ * Walks the AST and dispatches nodes to a plugin's direct AST hooks
191
+ * (`schema`, `operation`, `operations`).
192
+ */
193
+ async function runPluginAstHooks(plugin: NormalizedPlugin, context: GeneratorContext): Promise<void> {
194
+ const { adapter, inputNode, resolver, driver } = context
195
+ const { exclude, include, override } = plugin.options
196
+
197
+ if (!adapter || !inputNode) {
198
+ throw new Error(`[${plugin.name}] No adapter found. Add an OAS adapter (e.g. pluginOas()) before this plugin in your Kubb config.`)
199
+ }
200
+
201
+ function resolveRenderer(gen: Generator): RendererFactory | undefined {
202
+ return gen.renderer === null ? undefined : (gen.renderer ?? plugin.renderer ?? context.config.renderer)
203
+ }
204
+
205
+ const generators = plugin.generators ?? []
206
+ const collectedOperations: Array<OperationNode> = []
207
+
208
+ const generatorContext = {
209
+ ...context,
210
+ resolver: driver.getResolver(plugin.name),
211
+ }
212
+
213
+ await walk(inputNode, {
214
+ depth: 'shallow',
215
+ async schema(node) {
216
+ const transformedNode = plugin.transformer ? transform(node, plugin.transformer) : node
217
+ const options = resolver.resolveOptions(transformedNode, {
218
+ options: plugin.options,
219
+ exclude,
220
+ include,
221
+ override,
222
+ })
223
+ if (options === null) return
224
+
225
+ const ctx = { ...generatorContext, options }
226
+
227
+ for (const gen of generators) {
228
+ if (!gen.schema) continue
229
+ const result = await gen.schema(transformedNode, ctx)
230
+ await applyHookResult(result, driver, resolveRenderer(gen))
231
+ }
232
+
233
+ await driver.hooks.emit('kubb:generate:schema', transformedNode, ctx)
234
+ },
235
+ async operation(node) {
236
+ const transformedNode = plugin.transformer ? transform(node, plugin.transformer) : node
237
+ const options = resolver.resolveOptions(transformedNode, {
238
+ options: plugin.options,
239
+ exclude,
240
+ include,
241
+ override,
242
+ })
243
+ if (options !== null) {
244
+ collectedOperations.push(transformedNode)
245
+
246
+ const ctx = { ...generatorContext, options }
247
+
248
+ for (const gen of generators) {
249
+ if (!gen.operation) continue
250
+ const result = await gen.operation(transformedNode, ctx)
251
+ await applyHookResult(result, driver, resolveRenderer(gen))
252
+ }
253
+
254
+ await driver.hooks.emit('kubb:generate:operation', transformedNode, ctx)
255
+ }
256
+ },
257
+ })
258
+
259
+ if (collectedOperations.length > 0) {
260
+ const ctx = { ...generatorContext, options: plugin.options }
261
+
262
+ for (const gen of generators) {
263
+ if (!gen.operations) continue
264
+ const result = await gen.operations(collectedOperations, ctx)
265
+ await applyHookResult(result, driver, resolveRenderer(gen))
266
+ }
267
+
268
+ await driver.hooks.emit('kubb:generate:operations', collectedOperations, ctx)
269
+ }
270
+ }
271
+
272
+ async function safeBuild(setupResult: SetupResult): Promise<BuildOutput> {
273
+ const { driver, hooks, sources, storage } = setupResult
274
+
275
+ const failedPlugins = new Set<{ plugin: Plugin; error: Error }>()
276
+ const pluginTimings = new Map<string, number>()
277
+ const config = driver.config
278
+
279
+ try {
280
+ await driver.emitSetupHooks()
281
+
282
+ if (driver.adapter && driver.inputNode) {
283
+ await hooks.emit('kubb:build:start', {
284
+ config,
285
+ adapter: driver.adapter,
286
+ inputNode: driver.inputNode,
287
+ getPlugin: driver.getPlugin.bind(driver),
288
+ get files() {
289
+ return driver.fileManager.files
290
+ },
291
+ upsertFile: (...files) => driver.fileManager.upsert(...files),
292
+ })
293
+ }
294
+
295
+ for (const plugin of driver.plugins.values()) {
296
+ const context = driver.getContext(plugin)
297
+ const hrStart = process.hrtime()
298
+
299
+ try {
300
+ const timestamp = new Date()
301
+
302
+ await hooks.emit('kubb:plugin:start', { plugin })
303
+
304
+ await hooks.emit('kubb:debug', {
305
+ date: timestamp,
306
+ logs: ['Starting plugin...', ` • Plugin Name: ${plugin.name}`],
307
+ })
308
+
309
+ if (plugin.generators?.length || driver.hasRegisteredGenerators(plugin.name)) {
310
+ await runPluginAstHooks(plugin, context)
311
+ }
312
+
313
+ const duration = getElapsedMs(hrStart)
314
+ pluginTimings.set(plugin.name, duration)
315
+
316
+ await hooks.emit('kubb:plugin:end', {
317
+ plugin,
318
+ duration,
319
+ success: true,
320
+ config,
321
+ get files() {
322
+ return driver.fileManager.files
323
+ },
324
+ upsertFile: (...files) => driver.fileManager.upsert(...files),
325
+ })
326
+
327
+ await hooks.emit('kubb:debug', {
328
+ date: new Date(),
329
+ logs: [`✓ Plugin started successfully (${formatMs(duration)})`],
330
+ })
331
+ } catch (caughtError) {
332
+ const error = caughtError as Error
333
+ const errorTimestamp = new Date()
334
+ const duration = getElapsedMs(hrStart)
335
+
336
+ await hooks.emit('kubb:plugin:end', {
337
+ plugin,
338
+ duration,
339
+ success: false,
340
+ error,
341
+ config,
342
+ get files() {
343
+ return driver.fileManager.files
344
+ },
345
+ upsertFile: (...files) => driver.fileManager.upsert(...files),
346
+ })
347
+
348
+ await hooks.emit('kubb:debug', {
349
+ date: errorTimestamp,
350
+ logs: [
351
+ '✗ Plugin start failed',
352
+ ` • Plugin Name: ${plugin.name}`,
353
+ ` • Error: ${error.constructor.name} - ${error.message}`,
354
+ ' • Stack Trace:',
355
+ error.stack || 'No stack trace available',
356
+ ],
357
+ })
358
+
359
+ failedPlugins.add({ plugin, error })
360
+ }
361
+ }
362
+
363
+ await hooks.emit('kubb:plugins:end', {
364
+ config,
365
+ get files() {
366
+ return driver.fileManager.files
367
+ },
368
+ upsertFile: (...files) => driver.fileManager.upsert(...files),
369
+ })
370
+
371
+ const files = driver.fileManager.files
372
+
373
+ const parsersMap = new Map<FileNode['extname'], Parser>()
374
+ for (const parser of config.parsers) {
375
+ if (parser.extNames) {
376
+ for (const extname of parser.extNames) {
377
+ parsersMap.set(extname, parser)
378
+ }
379
+ }
380
+ }
381
+
382
+ const fileProcessor = new FileProcessor()
383
+
384
+ await hooks.emit('kubb:debug', {
385
+ date: new Date(),
386
+ logs: [`Writing ${files.length} files...`],
387
+ })
388
+
389
+ await fileProcessor.run(files, {
390
+ parsers: parsersMap,
391
+ extension: config.output.extension,
392
+ onStart: async (processingFiles) => {
393
+ await hooks.emit('kubb:files:processing:start', { files: processingFiles })
394
+ },
395
+ onUpdate: async ({ file, source, processed, total, percentage }) => {
396
+ await hooks.emit('kubb:file:processing:update', {
397
+ file,
398
+ source,
399
+ processed,
400
+ total,
401
+ percentage,
402
+ config,
403
+ })
404
+ if (source) {
405
+ await storage?.setItem(file.path, source)
406
+ sources.set(file.path, source)
407
+ }
408
+ },
409
+ onEnd: async (processedFiles) => {
410
+ await hooks.emit('kubb:files:processing:end', { files: processedFiles })
411
+ await hooks.emit('kubb:debug', {
412
+ date: new Date(),
413
+ logs: [`✓ File write process completed for ${processedFiles.length} files`],
414
+ })
415
+ },
416
+ })
417
+
418
+ await hooks.emit('kubb:build:end', {
419
+ files,
420
+ config,
421
+ outputDir: resolve(config.root, config.output.path),
422
+ })
423
+
424
+ return {
425
+ failedPlugins,
426
+ files,
427
+ driver,
428
+ pluginTimings,
429
+ sources,
430
+ }
431
+ } catch (error) {
432
+ return {
433
+ failedPlugins,
434
+ files: [],
435
+ driver,
436
+ pluginTimings,
437
+ error: error as Error,
438
+ sources,
439
+ }
440
+ } finally {
441
+ driver.dispose()
442
+ }
443
+ }
444
+
445
+ async function build(setupResult: SetupResult): Promise<BuildOutput> {
446
+ const { files, driver, failedPlugins, pluginTimings, error, sources } = await safeBuild(setupResult)
447
+
448
+ if (error) {
449
+ throw error
450
+ }
451
+
452
+ if (failedPlugins.size > 0) {
453
+ const errors = [...failedPlugins].map(({ error }) => error)
454
+
455
+ throw new BuildError(`Build Error with ${failedPlugins.size} failed plugins`, { errors })
456
+ }
457
+
458
+ return {
459
+ failedPlugins,
460
+ files,
461
+ driver,
462
+ pluginTimings,
463
+ error: undefined,
464
+ sources,
465
+ }
466
+ }
467
+
468
+ function inputToAdapterSource(config: Config): AdapterSource {
469
+ if (Array.isArray(config.input)) {
470
+ return {
471
+ type: 'paths',
472
+ paths: config.input.map((i) => (new URLPath(i.path).isURL ? i.path : resolve(config.root, i.path))),
473
+ }
474
+ }
475
+
476
+ if ('data' in config.input) {
477
+ return { type: 'data', data: config.input.data }
478
+ }
479
+
480
+ if (new URLPath(config.input.path).isURL) {
481
+ return { type: 'path', path: config.input.path }
482
+ }
483
+
484
+ const resolved = resolve(config.root, config.input.path)
485
+ return { type: 'path', path: resolved }
486
+ }
487
+
488
+ type CreateKubbOptions = {
489
+ hooks?: AsyncEventEmitter<KubbHooks>
490
+ }
491
+
492
+ /**
493
+ * Creates a Kubb instance bound to a single config entry.
494
+ *
495
+ * Accepts a user-facing config shape and resolves it to a full {@link Config} during
496
+ * `setup()`. The instance then holds shared state (`hooks`, `sources`, `driver`, `config`)
497
+ * across the `setup → build` lifecycle. Attach event listeners to `kubb.hooks` before
498
+ * calling `setup()` or `build()`.
499
+ *
500
+ * @example
501
+ * ```ts
502
+ * const kubb = createKubb(userConfig)
503
+ *
504
+ * kubb.hooks.on('kubb:plugin:end', ({ plugin, duration }) => {
505
+ * console.log(`${plugin.name} completed in ${duration}ms`)
506
+ * })
507
+ *
508
+ * const { files, failedPlugins } = await kubb.safeBuild()
509
+ * ```
510
+ */
511
+ export function createKubb(userConfig: UserConfig, options: CreateKubbOptions = {}): Kubb {
512
+ const hooks = options.hooks ?? new AsyncEventEmitter<KubbHooks>()
513
+ let setupResult: SetupResult | undefined
514
+
515
+ const instance: Kubb = {
516
+ get hooks() {
517
+ return hooks
518
+ },
519
+ get sources() {
520
+ return setupResult?.sources ?? new Map()
521
+ },
522
+ get driver() {
523
+ return setupResult?.driver
524
+ },
525
+ get config() {
526
+ return setupResult?.config
527
+ },
528
+ async setup() {
529
+ setupResult = await setup(userConfig, { hooks })
530
+ },
531
+ async build() {
532
+ if (!setupResult) {
533
+ await instance.setup()
534
+ }
535
+ return build(setupResult!)
536
+ },
537
+ async safeBuild() {
538
+ if (!setupResult) {
539
+ await instance.setup()
540
+ }
541
+ return safeBuild(setupResult!)
542
+ },
543
+ }
544
+
545
+ return instance
546
+ }
@@ -0,0 +1,57 @@
1
+ import type { FileNode } from '@kubb/ast'
2
+
3
+ /**
4
+ * Minimal interface any Kubb renderer must satisfy.
5
+ *
6
+ * The generic `TElement` is the type of the element the renderer accepts —
7
+ * e.g. `KubbReactElement` for `@kubb/renderer-jsx`, or a custom type for
8
+ * your own renderer. Defaults to `unknown` so that generators which do not
9
+ * care about the element type continue to work without specifying it.
10
+ *
11
+ * This allows core to drive rendering without a hard dependency on
12
+ * `@kubb/renderer-jsx` or any specific renderer implementation.
13
+ */
14
+ export type Renderer<TElement = unknown> = {
15
+ render(element: TElement): Promise<void>
16
+ unmount(error?: Error | number | null): void
17
+ readonly files: Array<FileNode>
18
+ }
19
+
20
+ /**
21
+ * A factory function that produces a fresh {@link Renderer} per render.
22
+ *
23
+ * Generators use this to declare which renderer handles their output.
24
+ */
25
+ export type RendererFactory<TElement = unknown> = () => Renderer<TElement>
26
+
27
+ /**
28
+ * Creates a renderer factory for use in generator definitions.
29
+ *
30
+ * Wrap your renderer factory function with this helper to register it as the
31
+ * renderer for a generator. Core will call this factory once per render cycle
32
+ * to obtain a fresh renderer instance.
33
+ *
34
+ * @example
35
+ * ```ts
36
+ * // packages/renderer-jsx/src/index.ts
37
+ * export const jsxRenderer = createRenderer(() => {
38
+ * const runtime = new Runtime()
39
+ * return {
40
+ * async render(element) { await runtime.render(element) },
41
+ * get files() { return runtime.nodes },
42
+ * unmount(error) { runtime.unmount(error) },
43
+ * }
44
+ * })
45
+ *
46
+ * // packages/plugin-zod/src/generators/zodGenerator.tsx
47
+ * import { jsxRenderer } from '@kubb/renderer-jsx'
48
+ * export const zodGenerator = defineGenerator<PluginZod>({
49
+ * name: 'zod',
50
+ * renderer: jsxRenderer,
51
+ * schema(node, options) { return <File ...>...</File> },
52
+ * })
53
+ * ```
54
+ */
55
+ export function createRenderer<TElement = unknown>(factory: RendererFactory<TElement>): RendererFactory<TElement> {
56
+ return factory
57
+ }