@kubb/core 5.0.0-alpha.4 → 5.0.0-alpha.41

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