@kubb/core 5.0.0-alpha.5 → 5.0.0-alpha.50

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 (71) hide show
  1. package/README.md +3 -2
  2. package/dist/PluginDriver-DtwggkXg.cjs +1082 -0
  3. package/dist/PluginDriver-DtwggkXg.cjs.map +1 -0
  4. package/dist/PluginDriver-mXeqWp-U.js +979 -0
  5. package/dist/PluginDriver-mXeqWp-U.js.map +1 -0
  6. package/dist/index.cjs +1013 -1829
  7. package/dist/index.cjs.map +1 -1
  8. package/dist/index.d.ts +274 -265
  9. package/dist/index.js +1003 -1799
  10. package/dist/index.js.map +1 -1
  11. package/dist/mocks.cjs +138 -0
  12. package/dist/mocks.cjs.map +1 -0
  13. package/dist/mocks.d.ts +74 -0
  14. package/dist/mocks.js +133 -0
  15. package/dist/mocks.js.map +1 -0
  16. package/dist/types-DfEv9d_c.d.ts +1721 -0
  17. package/package.json +51 -57
  18. package/src/FileManager.ts +133 -0
  19. package/src/FileProcessor.ts +86 -0
  20. package/src/Kubb.ts +154 -101
  21. package/src/PluginDriver.ts +418 -0
  22. package/src/constants.ts +43 -47
  23. package/src/createAdapter.ts +25 -0
  24. package/src/createKubb.ts +614 -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/defineParser.ts +45 -0
  30. package/src/definePlugin.ts +68 -7
  31. package/src/defineResolver.ts +501 -0
  32. package/src/devtools.ts +14 -14
  33. package/src/index.ts +12 -17
  34. package/src/mocks.ts +171 -0
  35. package/src/renderNode.ts +35 -0
  36. package/src/storages/fsStorage.ts +40 -11
  37. package/src/storages/memoryStorage.ts +4 -3
  38. package/src/types.ts +575 -205
  39. package/src/utils/TreeNode.ts +47 -9
  40. package/src/utils/diagnostics.ts +4 -1
  41. package/src/utils/getBarrelFiles.ts +94 -16
  42. package/src/utils/isInputPath.ts +10 -0
  43. package/src/utils/packageJSON.ts +99 -0
  44. package/dist/PluginManager-vZodFEMe.d.ts +0 -1056
  45. package/dist/chunk-ByKO4r7w.cjs +0 -38
  46. package/dist/hooks.cjs +0 -60
  47. package/dist/hooks.cjs.map +0 -1
  48. package/dist/hooks.d.ts +0 -56
  49. package/dist/hooks.js +0 -56
  50. package/dist/hooks.js.map +0 -1
  51. package/src/BarrelManager.ts +0 -74
  52. package/src/PackageManager.ts +0 -180
  53. package/src/PluginManager.ts +0 -667
  54. package/src/PromiseManager.ts +0 -40
  55. package/src/build.ts +0 -419
  56. package/src/config.ts +0 -56
  57. package/src/defineAdapter.ts +0 -22
  58. package/src/defineStorage.ts +0 -56
  59. package/src/errors.ts +0 -1
  60. package/src/hooks/index.ts +0 -4
  61. package/src/hooks/useKubb.ts +0 -46
  62. package/src/hooks/useMode.ts +0 -11
  63. package/src/hooks/usePlugin.ts +0 -11
  64. package/src/hooks/usePluginManager.ts +0 -11
  65. package/src/utils/FunctionParams.ts +0 -155
  66. package/src/utils/executeStrategies.ts +0 -81
  67. package/src/utils/formatters.ts +0 -56
  68. package/src/utils/getConfigs.ts +0 -30
  69. package/src/utils/getPlugins.ts +0 -23
  70. package/src/utils/linters.ts +0 -25
  71. package/src/utils/resolveOptions.ts +0 -93
@@ -0,0 +1,614 @@
1
+ import { dirname, resolve } from 'node:path'
2
+ import { AsyncEventEmitter, BuildError, exists, formatMs, getElapsedMs, getRelativePath, URLPath } from '@internals/utils'
3
+ import type { ExportNode, FileNode, OperationNode } from '@kubb/ast'
4
+ import { createExport, createFile, transform, walk } from '@kubb/ast'
5
+ import { BARREL_FILENAME, 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, NormalizedPlugin, Storage, UserConfig } from './types.ts'
16
+ import { getDiagnosticInfo } from './utils/diagnostics.ts'
17
+ import type { FileMetaBase } from './utils/getBarrelFiles.ts'
18
+ import { getBarrelFiles } from './utils/getBarrelFiles.ts'
19
+ import { isInputPath } from './utils/isInputPath.ts'
20
+
21
+ type SetupOptions = {
22
+ hooks?: AsyncEventEmitter<KubbHooks>
23
+ }
24
+
25
+ /**
26
+ * Full output produced by a successful or failed build.
27
+ */
28
+ export type BuildOutput = {
29
+ /**
30
+ * Plugins that threw during installation, paired with the caught error.
31
+ */
32
+ failedPlugins: Set<{ plugin: Plugin; error: Error }>
33
+ files: Array<FileNode>
34
+ driver: PluginDriver
35
+ /**
36
+ * Elapsed time in milliseconds for each plugin, keyed by plugin name.
37
+ */
38
+ pluginTimings: Map<string, number>
39
+ error?: Error
40
+ /**
41
+ * Raw generated source, keyed by absolute file path.
42
+ */
43
+ sources: Map<string, string>
44
+ }
45
+
46
+ type SetupResult = {
47
+ hooks: AsyncEventEmitter<KubbHooks>
48
+ driver: PluginDriver
49
+ sources: Map<string, string>
50
+ config: Config
51
+ storage: Storage | null
52
+ }
53
+
54
+ async function setup(userConfig: UserConfig, options: SetupOptions = {}): Promise<SetupResult> {
55
+ const hooks = options.hooks ?? new AsyncEventEmitter<KubbHooks>()
56
+
57
+ const sources: Map<string, string> = new Map<string, string>()
58
+ const diagnosticInfo = getDiagnosticInfo()
59
+
60
+ if (Array.isArray(userConfig.input)) {
61
+ await hooks.emit('kubb:warn', 'This feature is still under development — use with caution')
62
+ }
63
+
64
+ await hooks.emit('kubb:debug', {
65
+ date: new Date(),
66
+ logs: [
67
+ 'Configuration:',
68
+ ` • Name: ${userConfig.name || 'unnamed'}`,
69
+ ` • Root: ${userConfig.root || process.cwd()}`,
70
+ ` • Output: ${userConfig.output?.path || 'not specified'}`,
71
+ ` • Plugins: ${userConfig.plugins?.length || 0}`,
72
+ 'Output Settings:',
73
+ ` • Storage: ${userConfig.output?.storage ? `custom(${userConfig.output.storage.name})` : userConfig.output?.write === false ? 'disabled' : 'filesystem (default)'}`,
74
+ ` • Formatter: ${userConfig.output?.format || 'none'}`,
75
+ ` • Linter: ${userConfig.output?.lint || 'none'}`,
76
+ 'Environment:',
77
+ Object.entries(diagnosticInfo)
78
+ .map(([key, value]) => ` • ${key}: ${value}`)
79
+ .join('\n'),
80
+ ],
81
+ })
82
+
83
+ try {
84
+ if (isInputPath(userConfig) && !new URLPath(userConfig.input.path).isURL) {
85
+ await exists(userConfig.input.path)
86
+
87
+ await hooks.emit('kubb:debug', {
88
+ date: new Date(),
89
+ logs: [`✓ Input file validated: ${userConfig.input.path}`],
90
+ })
91
+ }
92
+ } catch (caughtError) {
93
+ if (isInputPath(userConfig)) {
94
+ const error = caughtError as Error
95
+
96
+ throw new Error(
97
+ `Cannot read file/URL defined in \`input.path\` or set with \`kubb generate PATH\` in the CLI of your Kubb config ${userConfig.input.path}`,
98
+ {
99
+ cause: error,
100
+ },
101
+ )
102
+ }
103
+ }
104
+
105
+ if (!userConfig.adapter) {
106
+ throw new Error('Adapter should be defined')
107
+ }
108
+
109
+ const config: Config = {
110
+ ...userConfig,
111
+ root: userConfig.root || process.cwd(),
112
+ parsers: userConfig.parsers ?? [],
113
+ adapter: userConfig.adapter,
114
+ output: {
115
+ write: true,
116
+ barrelType: 'named',
117
+ extension: DEFAULT_EXTENSION,
118
+ defaultBanner: DEFAULT_BANNER,
119
+ ...userConfig.output,
120
+ },
121
+ devtools: userConfig.devtools
122
+ ? {
123
+ studioUrl: DEFAULT_STUDIO_URL,
124
+ ...(typeof userConfig.devtools === 'boolean' ? {} : userConfig.devtools),
125
+ }
126
+ : undefined,
127
+ plugins: userConfig.plugins as unknown as Config['plugins'],
128
+ }
129
+
130
+ const storage: Storage | null = config.output.write === false ? null : (config.output.storage ?? fsStorage())
131
+
132
+ if (config.output.clean) {
133
+ await hooks.emit('kubb:debug', {
134
+ date: new Date(),
135
+ logs: ['Cleaning output directories', ` • Output: ${config.output.path}`],
136
+ })
137
+ await storage?.clear(resolve(config.root, config.output.path))
138
+ }
139
+
140
+ const driver = new PluginDriver(config, {
141
+ hooks,
142
+ })
143
+
144
+ const adapter = config.adapter
145
+ if (!adapter) {
146
+ throw new Error('No adapter configured. Please provide an adapter in your kubb.config.ts.')
147
+ }
148
+ const source = inputToAdapterSource(config)
149
+
150
+ await hooks.emit('kubb:debug', {
151
+ date: new Date(),
152
+ logs: [`Running adapter: ${adapter.name}`],
153
+ })
154
+
155
+ driver.adapter = adapter
156
+ driver.inputNode = await adapter.parse(source)
157
+
158
+ await hooks.emit('kubb:debug', {
159
+ date: new Date(),
160
+ logs: [
161
+ `✓ Adapter '${adapter.name}' resolved InputNode`,
162
+ ` • Schemas: ${driver.inputNode.schemas.length}`,
163
+ ` • Operations: ${driver.inputNode.operations.length}`,
164
+ ],
165
+ })
166
+
167
+ return {
168
+ config,
169
+ hooks,
170
+ driver,
171
+ sources,
172
+ storage,
173
+ }
174
+ }
175
+
176
+ /**
177
+ * Walks the AST and dispatches nodes to a plugin's direct AST hooks
178
+ * (`schema`, `operation`, `operations`).
179
+ */
180
+ async function runPluginAstHooks(plugin: NormalizedPlugin, context: GeneratorContext): Promise<void> {
181
+ const { adapter, inputNode, resolver, driver } = context
182
+ const { exclude, include, override } = plugin.options
183
+
184
+ if (!adapter || !inputNode) {
185
+ throw new Error(`[${plugin.name}] No adapter found. Add an OAS adapter (e.g. pluginOas()) before this plugin in your Kubb config.`)
186
+ }
187
+
188
+ function resolveRenderer(gen: Generator): RendererFactory | undefined {
189
+ return gen.renderer === null ? undefined : (gen.renderer ?? plugin.renderer ?? context.config.renderer)
190
+ }
191
+
192
+ const generators = plugin.generators ?? []
193
+ const collectedOperations: Array<OperationNode> = []
194
+
195
+ const generatorContext = {
196
+ ...context,
197
+ resolver: driver.getResolver(plugin.name),
198
+ }
199
+
200
+ await walk(inputNode, {
201
+ depth: 'shallow',
202
+ async schema(node) {
203
+ const transformedNode = plugin.transformer ? transform(node, plugin.transformer) : node
204
+ const options = resolver.resolveOptions(transformedNode, {
205
+ options: plugin.options,
206
+ exclude,
207
+ include,
208
+ override,
209
+ })
210
+ if (options === null) return
211
+
212
+ const ctx = { ...generatorContext, options }
213
+
214
+ for (const gen of generators) {
215
+ if (!gen.schema) continue
216
+ const result = await gen.schema(transformedNode, ctx)
217
+ await applyHookResult(result, driver, resolveRenderer(gen))
218
+ }
219
+
220
+ await driver.hooks.emit('kubb:generate:schema', transformedNode, ctx)
221
+ },
222
+ async operation(node) {
223
+ const transformedNode = plugin.transformer ? transform(node, plugin.transformer) : node
224
+ const options = resolver.resolveOptions(transformedNode, {
225
+ options: plugin.options,
226
+ exclude,
227
+ include,
228
+ override,
229
+ })
230
+ if (options !== null) {
231
+ collectedOperations.push(transformedNode)
232
+
233
+ const ctx = { ...generatorContext, options }
234
+
235
+ for (const gen of generators) {
236
+ if (!gen.operation) continue
237
+ const result = await gen.operation(transformedNode, ctx)
238
+ await applyHookResult(result, driver, resolveRenderer(gen))
239
+ }
240
+
241
+ await driver.hooks.emit('kubb:generate:operation', transformedNode, ctx)
242
+ }
243
+ },
244
+ })
245
+
246
+ if (collectedOperations.length > 0) {
247
+ const ctx = { ...generatorContext, options: plugin.options }
248
+
249
+ for (const gen of generators) {
250
+ if (!gen.operations) continue
251
+ const result = await gen.operations(collectedOperations, ctx)
252
+ await applyHookResult(result, driver, resolveRenderer(gen))
253
+ }
254
+
255
+ await driver.hooks.emit('kubb:generate:operations', collectedOperations, ctx)
256
+ }
257
+ }
258
+
259
+ async function safeBuild(setupResult: SetupResult): Promise<BuildOutput> {
260
+ const { driver, hooks, sources, storage } = setupResult
261
+
262
+ const failedPlugins = new Set<{ plugin: Plugin; error: Error }>()
263
+ const pluginTimings = new Map<string, number>()
264
+ const config = driver.config
265
+
266
+ try {
267
+ await driver.emitSetupHooks()
268
+
269
+ if (driver.adapter && driver.inputNode) {
270
+ await hooks.emit('kubb:build:start', {
271
+ config,
272
+ adapter: driver.adapter,
273
+ inputNode: driver.inputNode,
274
+ getPlugin: driver.getPlugin.bind(driver),
275
+ })
276
+ }
277
+
278
+ for (const plugin of driver.plugins.values()) {
279
+ const context = driver.getContext(plugin)
280
+ const hrStart = process.hrtime()
281
+ const { output } = plugin.options ?? {}
282
+ const root = resolve(config.root, config.output.path)
283
+
284
+ try {
285
+ const timestamp = new Date()
286
+
287
+ await hooks.emit('kubb:plugin:start', plugin)
288
+
289
+ await hooks.emit('kubb:debug', {
290
+ date: timestamp,
291
+ logs: ['Starting plugin...', ` • Plugin Name: ${plugin.name}`],
292
+ })
293
+
294
+ if (plugin.generators?.length || driver.hasRegisteredGenerators(plugin.name)) {
295
+ await runPluginAstHooks(plugin, context)
296
+ }
297
+
298
+ if (output) {
299
+ const barrelFiles = await getBarrelFiles(driver.fileManager.files, {
300
+ type: output.barrelType ?? 'named',
301
+ root,
302
+ output,
303
+ meta: { pluginName: plugin.name },
304
+ })
305
+ await context.upsertFile(...barrelFiles)
306
+ }
307
+
308
+ const duration = getElapsedMs(hrStart)
309
+ pluginTimings.set(plugin.name, duration)
310
+
311
+ await hooks.emit('kubb:plugin:end', plugin, {
312
+ duration,
313
+ success: true,
314
+ })
315
+
316
+ await hooks.emit('kubb:debug', {
317
+ date: new Date(),
318
+ logs: [`✓ Plugin started successfully (${formatMs(duration)})`],
319
+ })
320
+ } catch (caughtError) {
321
+ const error = caughtError as Error
322
+ const errorTimestamp = new Date()
323
+ const duration = getElapsedMs(hrStart)
324
+
325
+ await hooks.emit('kubb:plugin:end', plugin, {
326
+ duration,
327
+ success: false,
328
+ error,
329
+ })
330
+
331
+ await hooks.emit('kubb:debug', {
332
+ date: errorTimestamp,
333
+ logs: [
334
+ '✗ Plugin start failed',
335
+ ` • Plugin Name: ${plugin.name}`,
336
+ ` • Error: ${error.constructor.name} - ${error.message}`,
337
+ ' • Stack Trace:',
338
+ error.stack || 'No stack trace available',
339
+ ],
340
+ })
341
+
342
+ failedPlugins.add({ plugin, error })
343
+ }
344
+ }
345
+
346
+ if (config.output.barrelType) {
347
+ const root = resolve(config.root)
348
+ const rootPath = resolve(root, config.output.path, BARREL_FILENAME)
349
+ const rootDir = dirname(rootPath)
350
+
351
+ await hooks.emit('kubb:debug', {
352
+ date: new Date(),
353
+ logs: ['Generating barrel file', ` • Type: ${config.output.barrelType}`, ` • Path: ${rootPath}`],
354
+ })
355
+
356
+ const barrelFiles = driver.fileManager.files.filter((file) => {
357
+ return file.sources.some((source) => source.isIndexable)
358
+ })
359
+
360
+ await hooks.emit('kubb:debug', {
361
+ date: new Date(),
362
+ logs: [`Found ${barrelFiles.length} indexable files for barrel export`],
363
+ })
364
+
365
+ const existingBarrel = driver.fileManager.files.find((f) => f.path === rootPath)
366
+ const existingExports = new Set(
367
+ existingBarrel?.exports?.flatMap((e) => (Array.isArray(e.name) ? e.name : [e.name])).filter((n): n is string => Boolean(n)) ?? [],
368
+ )
369
+
370
+ const rootFile = createFile<object>({
371
+ path: rootPath,
372
+ baseName: BARREL_FILENAME,
373
+ exports: buildBarrelExports({
374
+ barrelFiles,
375
+ rootDir,
376
+ existingExports,
377
+ config,
378
+ driver,
379
+ }).map((e) => createExport(e)),
380
+ sources: [],
381
+ imports: [],
382
+ meta: {},
383
+ })
384
+
385
+ driver.fileManager.upsert(rootFile)
386
+
387
+ await hooks.emit('kubb:debug', {
388
+ date: new Date(),
389
+ logs: [`✓ Generated barrel file (${rootFile.exports?.length || 0} exports)`],
390
+ })
391
+ }
392
+
393
+ const files = driver.fileManager.files
394
+
395
+ const parsersMap = new Map<FileNode['extname'], Parser>()
396
+ for (const parser of config.parsers) {
397
+ if (parser.extNames) {
398
+ for (const extname of parser.extNames) {
399
+ parsersMap.set(extname, parser)
400
+ }
401
+ }
402
+ }
403
+
404
+ const fileProcessor = new FileProcessor()
405
+
406
+ await hooks.emit('kubb:debug', {
407
+ date: new Date(),
408
+ logs: [`Writing ${files.length} files...`],
409
+ })
410
+
411
+ await fileProcessor.run(files, {
412
+ parsers: parsersMap,
413
+ extension: config.output.extension,
414
+ onStart: async (processingFiles) => {
415
+ await hooks.emit('kubb:files:processing:start', processingFiles)
416
+ },
417
+ onUpdate: async ({ file, source, processed, total, percentage }) => {
418
+ await hooks.emit('kubb:file:processing:update', {
419
+ file,
420
+ source,
421
+ processed,
422
+ total,
423
+ percentage,
424
+ config,
425
+ })
426
+ if (source) {
427
+ await storage?.setItem(file.path, source)
428
+ sources.set(file.path, source)
429
+ }
430
+ },
431
+ onEnd: async (processedFiles) => {
432
+ await hooks.emit('kubb:files:processing:end', processedFiles)
433
+ await hooks.emit('kubb:debug', {
434
+ date: new Date(),
435
+ logs: [`✓ File write process completed for ${processedFiles.length} files`],
436
+ })
437
+ },
438
+ })
439
+
440
+ await hooks.emit('kubb:build:end', {
441
+ files,
442
+ config,
443
+ outputDir: resolve(config.root, config.output.path),
444
+ })
445
+
446
+ return {
447
+ failedPlugins,
448
+ files,
449
+ driver,
450
+ pluginTimings,
451
+ sources,
452
+ }
453
+ } catch (error) {
454
+ return {
455
+ failedPlugins,
456
+ files: [],
457
+ driver,
458
+ pluginTimings,
459
+ error: error as Error,
460
+ sources,
461
+ }
462
+ } finally {
463
+ driver.dispose()
464
+ }
465
+ }
466
+
467
+ async function build(setupResult: SetupResult): Promise<BuildOutput> {
468
+ const { files, driver, failedPlugins, pluginTimings, error, sources } = await safeBuild(setupResult)
469
+
470
+ if (error) {
471
+ throw error
472
+ }
473
+
474
+ if (failedPlugins.size > 0) {
475
+ const errors = [...failedPlugins].map(({ error }) => error)
476
+
477
+ throw new BuildError(`Build Error with ${failedPlugins.size} failed plugins`, { errors })
478
+ }
479
+
480
+ return {
481
+ failedPlugins,
482
+ files,
483
+ driver,
484
+ pluginTimings,
485
+ error: undefined,
486
+ sources,
487
+ }
488
+ }
489
+
490
+ type BuildBarrelExportsParams = {
491
+ barrelFiles: FileNode[]
492
+ rootDir: string
493
+ existingExports: Set<string>
494
+ config: Config
495
+ driver: PluginDriver
496
+ }
497
+
498
+ function buildBarrelExports({ barrelFiles, rootDir, existingExports, config, driver }: BuildBarrelExportsParams): ExportNode[] {
499
+ const pluginNameMap = new Map<string, NormalizedPlugin>()
500
+ for (const plugin of driver.plugins.values()) {
501
+ pluginNameMap.set(plugin.name, plugin)
502
+ }
503
+
504
+ return barrelFiles.flatMap((file) => {
505
+ const containsOnlyTypes = file.sources?.every((source) => source.isTypeOnly)
506
+
507
+ return (file.sources ?? []).flatMap((source) => {
508
+ if (!file.path || !source.isIndexable) {
509
+ return []
510
+ }
511
+
512
+ const meta = file.meta as FileMetaBase | undefined
513
+ const plugin = meta?.pluginName ? pluginNameMap.get(meta.pluginName) : undefined
514
+ const pluginOptions = plugin?.options
515
+
516
+ if (!pluginOptions || pluginOptions.output?.barrelType === false) {
517
+ return []
518
+ }
519
+
520
+ const exportName = config.output.barrelType === 'all' ? undefined : source.name ? [source.name] : undefined
521
+ if (exportName?.some((n) => existingExports.has(n))) {
522
+ return []
523
+ }
524
+
525
+ return [
526
+ createExport({
527
+ name: exportName,
528
+ path: getRelativePath(rootDir, file.path),
529
+ isTypeOnly: config.output.barrelType === 'all' ? containsOnlyTypes : source.isTypeOnly,
530
+ }),
531
+ ]
532
+ })
533
+ })
534
+ }
535
+
536
+ function inputToAdapterSource(config: Config): AdapterSource {
537
+ if (Array.isArray(config.input)) {
538
+ return {
539
+ type: 'paths',
540
+ paths: config.input.map((i) => (new URLPath(i.path).isURL ? i.path : resolve(config.root, i.path))),
541
+ }
542
+ }
543
+
544
+ if ('data' in config.input) {
545
+ return { type: 'data', data: config.input.data }
546
+ }
547
+
548
+ if (new URLPath(config.input.path).isURL) {
549
+ return { type: 'path', path: config.input.path }
550
+ }
551
+
552
+ const resolved = resolve(config.root, config.input.path)
553
+ return { type: 'path', path: resolved }
554
+ }
555
+
556
+ type CreateKubbOptions = {
557
+ hooks?: AsyncEventEmitter<KubbHooks>
558
+ }
559
+
560
+ /**
561
+ * Creates a Kubb instance bound to a single config entry.
562
+ *
563
+ * Accepts a user-facing config shape and resolves it to a full {@link Config} during
564
+ * `setup()`. The instance then holds shared state (`hooks`, `sources`, `driver`, `config`)
565
+ * across the `setup → build` lifecycle. Attach event listeners to `kubb.hooks` before
566
+ * calling `setup()` or `build()`.
567
+ *
568
+ * @example
569
+ * ```ts
570
+ * const kubb = createKubb(userConfig)
571
+ *
572
+ * kubb.hooks.on('kubb:plugin:end', (plugin, { duration }) => {
573
+ * console.log(`${plugin.name} completed in ${duration}ms`)
574
+ * })
575
+ *
576
+ * const { files, failedPlugins } = await kubb.safeBuild()
577
+ * ```
578
+ */
579
+ export function createKubb(userConfig: UserConfig, options: CreateKubbOptions = {}): Kubb {
580
+ const hooks = options.hooks ?? new AsyncEventEmitter<KubbHooks>()
581
+ let setupResult: SetupResult | undefined
582
+
583
+ const instance: Kubb = {
584
+ get hooks() {
585
+ return hooks
586
+ },
587
+ get sources() {
588
+ return setupResult?.sources ?? new Map()
589
+ },
590
+ get driver() {
591
+ return setupResult?.driver
592
+ },
593
+ get config() {
594
+ return setupResult?.config
595
+ },
596
+ async setup() {
597
+ setupResult = await setup(userConfig, { hooks })
598
+ },
599
+ async build() {
600
+ if (!setupResult) {
601
+ await instance.setup()
602
+ }
603
+ return build(setupResult!)
604
+ },
605
+ async safeBuild() {
606
+ if (!setupResult) {
607
+ await instance.setup()
608
+ }
609
+ return safeBuild(setupResult!)
610
+ },
611
+ }
612
+
613
+ return instance
614
+ }
@@ -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
+ }