@kubb/core 5.0.0-beta.8 → 5.0.0-beta.81

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 (44) hide show
  1. package/LICENSE +17 -10
  2. package/README.md +20 -123
  3. package/dist/diagnostics-DcFh-77r.d.ts +2889 -0
  4. package/dist/index.cjs +2349 -1107
  5. package/dist/index.cjs.map +1 -1
  6. package/dist/index.d.ts +79 -138
  7. package/dist/index.js +2344 -1101
  8. package/dist/index.js.map +1 -1
  9. package/dist/memoryStorage-BjUIqpYE.js +883 -0
  10. package/dist/memoryStorage-BjUIqpYE.js.map +1 -0
  11. package/dist/memoryStorage-DQ6qXJ8o.cjs +1021 -0
  12. package/dist/memoryStorage-DQ6qXJ8o.cjs.map +1 -0
  13. package/dist/mocks.cjs +84 -24
  14. package/dist/mocks.cjs.map +1 -1
  15. package/dist/mocks.d.ts +37 -11
  16. package/dist/mocks.js +86 -28
  17. package/dist/mocks.js.map +1 -1
  18. package/package.json +8 -26
  19. package/dist/PluginDriver-Cu1Kj9S-.cjs +0 -1075
  20. package/dist/PluginDriver-Cu1Kj9S-.cjs.map +0 -1
  21. package/dist/PluginDriver-D8Z0Htid.js +0 -978
  22. package/dist/PluginDriver-D8Z0Htid.js.map +0 -1
  23. package/dist/createKubb-Cagd4PIe.d.ts +0 -2082
  24. package/src/FileManager.ts +0 -115
  25. package/src/FileProcessor.ts +0 -86
  26. package/src/PluginDriver.ts +0 -457
  27. package/src/constants.ts +0 -35
  28. package/src/createAdapter.ts +0 -108
  29. package/src/createKubb.ts +0 -1268
  30. package/src/createRenderer.ts +0 -57
  31. package/src/createStorage.ts +0 -70
  32. package/src/defineGenerator.ts +0 -175
  33. package/src/defineLogger.ts +0 -58
  34. package/src/defineMiddleware.ts +0 -62
  35. package/src/defineParser.ts +0 -44
  36. package/src/definePlugin.ts +0 -379
  37. package/src/defineResolver.ts +0 -654
  38. package/src/devtools.ts +0 -66
  39. package/src/index.ts +0 -20
  40. package/src/mocks.ts +0 -177
  41. package/src/storages/fsStorage.ts +0 -90
  42. package/src/storages/memoryStorage.ts +0 -55
  43. package/src/types.ts +0 -41
  44. /package/dist/{chunk--u3MIqq1.js → rolldown-runtime-C0LytTxp.js} +0 -0
@@ -1,115 +0,0 @@
1
- import type { FileNode } from '@kubb/ast'
2
- import { createFile } from '@kubb/ast'
3
-
4
- function mergeFile<TMeta extends object = object>(a: FileNode<TMeta>, b: FileNode<TMeta>): FileNode<TMeta> {
5
- return {
6
- ...a,
7
- // Incoming file (b) takes precedence for banner/footer so that barrel files,
8
- // which never carry a banner, can clear banners set by plugin-generated files
9
- // at the same path.
10
- banner: b.banner,
11
- footer: b.footer,
12
- sources: [...(a.sources || []), ...(b.sources || [])],
13
- imports: [...(a.imports || []), ...(b.imports || [])],
14
- exports: [...(a.exports || []), ...(b.exports || [])],
15
- }
16
- }
17
-
18
- /**
19
- * Collapses a list of files so that duplicates sharing the same `path` are merged
20
- * in arrival order. Keeps the original order of first occurrence.
21
- */
22
- function mergeFilesByPath(files: ReadonlyArray<FileNode>): Map<string, FileNode> {
23
- const merged = new Map<string, FileNode>()
24
- for (const file of files) {
25
- const existing = merged.get(file.path)
26
- merged.set(file.path, existing ? mergeFile(existing, file) : file)
27
- }
28
- return merged
29
- }
30
-
31
- /**
32
- * In-memory file store for generated files.
33
- *
34
- * Files with the same `path` are merged — sources, imports, and exports are concatenated.
35
- * The `files` getter returns all stored files sorted by path length (shortest first).
36
- *
37
- * @example
38
- * ```ts
39
- * import { FileManager } from '@kubb/core'
40
- *
41
- * const manager = new FileManager()
42
- * manager.upsert(myFile)
43
- * console.log(manager.files) // all stored files
44
- * ```
45
- */
46
- export class FileManager {
47
- readonly #cache = new Map<string, FileNode>()
48
- #filesCache: Array<FileNode> | null = null
49
-
50
- /**
51
- * Adds one or more files. Incoming files with the same path are merged
52
- * (sources/imports/exports concatenated), but existing cache entries are
53
- * replaced — use {@link upsert} when you want to merge into the cache too.
54
- */
55
- add(...files: Array<FileNode>): Array<FileNode> {
56
- return this.#store(files, false)
57
- }
58
-
59
- /**
60
- * Adds or merges one or more files.
61
- * If a file with the same path already exists in the cache, its
62
- * sources/imports/exports are merged into the incoming file.
63
- */
64
- upsert(...files: Array<FileNode>): Array<FileNode> {
65
- return this.#store(files, true)
66
- }
67
-
68
- #store(files: ReadonlyArray<FileNode>, mergeExisting: boolean): Array<FileNode> {
69
- const resolvedFiles: Array<FileNode> = []
70
- for (const file of mergeFilesByPath(files).values()) {
71
- const existing = mergeExisting ? this.#cache.get(file.path) : undefined
72
- const resolvedFile = createFile(existing ? mergeFile(existing, file) : file)
73
- this.#cache.set(resolvedFile.path, resolvedFile)
74
- resolvedFiles.push(resolvedFile)
75
- }
76
- this.#filesCache = null
77
- return resolvedFiles
78
- }
79
-
80
- getByPath(path: string): FileNode | null {
81
- return this.#cache.get(path) ?? null
82
- }
83
-
84
- deleteByPath(path: string): void {
85
- this.#cache.delete(path)
86
- this.#filesCache = null
87
- }
88
-
89
- clear(): void {
90
- this.#cache.clear()
91
- this.#filesCache = null
92
- }
93
-
94
- /**
95
- * All stored files, sorted by path length (shorter paths first).
96
- */
97
- get files(): Array<FileNode> {
98
- if (this.#filesCache) {
99
- return this.#filesCache
100
- }
101
-
102
- this.#filesCache = [...this.#cache.values()].sort((a, b) => {
103
- const lenDiff = a.path.length - b.path.length
104
- if (lenDiff !== 0) return lenDiff
105
- // Within the same length bucket, index.ts barrel files go last so other
106
- // files are always processed before their barrel file.
107
- const aIsIndex = a.path.endsWith('/index.ts') || a.path === 'index.ts'
108
- const bIsIndex = b.path.endsWith('/index.ts') || b.path === 'index.ts'
109
- if (aIsIndex && !bIsIndex) return 1
110
- if (!aIsIndex && bIsIndex) return -1
111
- return 0
112
- })
113
- return this.#filesCache
114
- }
115
- }
@@ -1,86 +0,0 @@
1
- import type { CodeNode, FileNode } from '@kubb/ast'
2
- import { extractStringsFromNodes } from '@kubb/ast'
3
- import pLimit from 'p-limit'
4
- import { PARALLEL_CONCURRENCY_LIMIT } from './constants.ts'
5
- import type { Parser } from './defineParser.ts'
6
-
7
- type ParseOptions = {
8
- parsers?: Map<FileNode['extname'], Parser>
9
- extension?: Record<FileNode['extname'], FileNode['extname'] | ''>
10
- }
11
-
12
- type RunOptions = ParseOptions & {
13
- /**
14
- * @default 'sequential'
15
- */
16
- mode?: 'sequential' | 'parallel'
17
- onStart?: (files: Array<FileNode>) => Promise<void> | void
18
- onEnd?: (files: Array<FileNode>) => Promise<void> | void
19
- onUpdate?: (params: { file: FileNode; source?: string; processed: number; total: number; percentage: number }) => Promise<void> | void
20
- }
21
-
22
- function joinSources(file: FileNode): string {
23
- return file.sources
24
- .map((item) => extractStringsFromNodes(item.nodes as Array<CodeNode>))
25
- .filter(Boolean)
26
- .join('\n\n')
27
- }
28
-
29
- /**
30
- * Converts a single file to a string using the registered parsers.
31
- * Falls back to joining source values when no matching parser is found.
32
- *
33
- * @internal
34
- */
35
- export class FileProcessor {
36
- readonly #limit = pLimit(PARALLEL_CONCURRENCY_LIMIT)
37
-
38
- async parse(file: FileNode, { parsers, extension }: ParseOptions = {}): Promise<string> {
39
- const parseExtName = extension?.[file.extname] || undefined
40
-
41
- if (!parsers || !file.extname) {
42
- return joinSources(file)
43
- }
44
-
45
- const parser = parsers.get(file.extname)
46
-
47
- if (!parser) {
48
- return joinSources(file)
49
- }
50
-
51
- return parser.parse(file, { extname: parseExtName })
52
- }
53
-
54
- async run(files: Array<FileNode>, { parsers, mode = 'sequential', extension, onStart, onEnd, onUpdate }: RunOptions = {}): Promise<Array<FileNode>> {
55
- await onStart?.(files)
56
-
57
- const total = files.length
58
- let processed = 0
59
-
60
- const processOne = async (file: FileNode) => {
61
- const source = await this.parse(file, { extension, parsers })
62
- const currentProcessed = ++processed
63
- const percentage = (currentProcessed / total) * 100
64
-
65
- await onUpdate?.({
66
- file,
67
- source,
68
- processed: currentProcessed,
69
- percentage,
70
- total,
71
- })
72
- }
73
-
74
- if (mode === 'sequential') {
75
- for (const file of files) {
76
- await processOne(file)
77
- }
78
- } else {
79
- await Promise.all(files.map((file) => this.#limit(() => processOne(file))))
80
- }
81
-
82
- await onEnd?.(files)
83
-
84
- return files
85
- }
86
- }
@@ -1,457 +0,0 @@
1
- import { resolve } from 'node:path'
2
- import type { AsyncEventEmitter } from '@internals/utils'
3
- import type { FileNode, InputNode, OperationNode, SchemaNode } from '@kubb/ast'
4
- import { createFile } from '@kubb/ast'
5
- import { DEFAULT_STUDIO_URL } from './constants.ts'
6
- import type { Generator } from './defineGenerator.ts'
7
- import type { Plugin } from './definePlugin.ts'
8
- import { getMode } from './definePlugin.ts'
9
- import { defineResolver } from './defineResolver.ts'
10
- import { openInStudio as openInStudioFn } from './devtools.ts'
11
- import { FileManager } from './FileManager.ts'
12
- import type { RendererFactory } from './createRenderer.ts'
13
-
14
- import type {
15
- Adapter,
16
- Config,
17
- DevtoolsOptions,
18
- GeneratorContext,
19
- KubbHooks,
20
- KubbPluginSetupContext,
21
- NormalizedPlugin,
22
- PluginFactoryOptions,
23
- Resolver,
24
- } from './types.ts'
25
-
26
- // inspired by: https://github.com/rollup/rollup/blob/master/src/utils/PluginDriver.ts#
27
-
28
- type Options = {
29
- hooks: AsyncEventEmitter<KubbHooks>
30
- }
31
-
32
- function enforceOrder(enforce: 'pre' | 'post' | undefined): number {
33
- return enforce === 'pre' ? -1 : enforce === 'post' ? 1 : 0
34
- }
35
-
36
- export class PluginDriver {
37
- readonly config: Config
38
- readonly options: Options
39
-
40
- /**
41
- * Returns `'single'` when `fileOrFolder` has a file extension, `'split'` otherwise.
42
- *
43
- * @example
44
- * ```ts
45
- * PluginDriver.getMode('src/gen/types.ts') // 'single'
46
- * PluginDriver.getMode('src/gen/types') // 'split'
47
- * ```
48
- */
49
- static getMode(fileOrFolder: string | undefined | null): 'single' | 'split' {
50
- return getMode(fileOrFolder)
51
- }
52
-
53
- /**
54
- * The universal `@kubb/ast` `InputNode` produced by the adapter, set by
55
- * the build pipeline after the adapter's `parse()` resolves.
56
- */
57
- inputNode: InputNode | undefined = undefined
58
- adapter: Adapter | undefined = undefined
59
- #studioIsOpen = false
60
-
61
- /**
62
- * Central file store for all generated files.
63
- * Plugins should use `this.addFile()` / `this.upsertFile()` (via their context) to
64
- * add files; this property gives direct read/write access when needed.
65
- */
66
- readonly fileManager = new FileManager()
67
-
68
- readonly plugins = new Map<string, NormalizedPlugin>()
69
-
70
- /**
71
- * Tracks which plugins have generators registered via `addGenerator()` (event-based path).
72
- * Used by the build loop to decide whether to emit generator events for a given plugin.
73
- */
74
- readonly #pluginsWithEventGenerators = new Set<string>()
75
- readonly #resolvers = new Map<string, Resolver>()
76
- readonly #defaultResolvers = new Map<string, Resolver>()
77
- readonly #hookListeners = new Map<keyof KubbHooks, Set<(...args: never[]) => void | Promise<void>>>()
78
-
79
- constructor(config: Config, options: Options) {
80
- this.config = config
81
- this.options = options
82
- config.plugins
83
- .map((rawPlugin) => this.#normalizePlugin(rawPlugin as Plugin))
84
- .filter((plugin) => {
85
- if (typeof plugin.apply === 'function') {
86
- return plugin.apply(config)
87
- }
88
- return true
89
- })
90
- .sort((a, b) => {
91
- if (b.dependencies?.includes(a.name)) return -1
92
- if (a.dependencies?.includes(b.name)) return 1
93
- // enforce: 'pre' plugins run first, 'post' plugins run last
94
- return enforceOrder(a.enforce) - enforceOrder(b.enforce)
95
- })
96
- .forEach((plugin) => {
97
- this.plugins.set(plugin.name, plugin)
98
- })
99
- }
100
-
101
- get hooks() {
102
- return this.options.hooks
103
- }
104
-
105
- /**
106
- * Creates an `NormalizedPlugin` from a hook-style plugin and registers
107
- * its lifecycle handlers on the `AsyncEventEmitter`.
108
- */
109
- #normalizePlugin(hookPlugin: Plugin): NormalizedPlugin {
110
- const normalizedPlugin = {
111
- name: hookPlugin.name,
112
- dependencies: hookPlugin.dependencies,
113
- enforce: hookPlugin.enforce,
114
- options: { output: { path: '.' }, exclude: [], override: [] },
115
- } as unknown as NormalizedPlugin
116
-
117
- this.registerPluginHooks(hookPlugin, normalizedPlugin)
118
- return normalizedPlugin
119
- }
120
-
121
- /**
122
- * Registers a hook-style plugin's lifecycle handlers on the shared `AsyncEventEmitter`.
123
- *
124
- * For `kubb:plugin:setup`, the registered listener wraps the globally emitted context with a
125
- * plugin-specific one so that `addGenerator`, `setResolver`, `setTransformer`, and
126
- * `setRenderer` all target the correct `normalizedPlugin` entry in the plugins map.
127
- *
128
- * All other hooks are iterated and registered directly as pass-through listeners.
129
- * Any event key present in the global `KubbHooks` interface can be subscribed to.
130
- *
131
- * External tooling can subscribe to any of these events via `hooks.on(...)` to observe
132
- * the plugin lifecycle without modifying plugin behavior.
133
- *
134
- * @internal
135
- */
136
- registerPluginHooks(hookPlugin: Plugin, normalizedPlugin: NormalizedPlugin): void {
137
- const { hooks } = hookPlugin
138
-
139
- if (!hooks) return
140
-
141
- // kubb:plugin:setup gets special treatment: the globally emitted context is wrapped with
142
- // plugin-specific implementations so that addGenerator / setResolver / etc. target
143
- // this plugin's normalizedPlugin entry rather than being no-ops.
144
- if (hooks['kubb:plugin:setup']) {
145
- const setupHandler = (globalCtx: KubbPluginSetupContext) => {
146
- const pluginCtx: KubbPluginSetupContext = {
147
- ...globalCtx,
148
- options: hookPlugin.options ?? {},
149
- addGenerator: (gen) => {
150
- this.registerGenerator(normalizedPlugin.name, gen)
151
- },
152
- setResolver: (resolver) => {
153
- this.setPluginResolver(normalizedPlugin.name, resolver)
154
- },
155
- setTransformer: (visitor) => {
156
- normalizedPlugin.transformer = visitor
157
- },
158
- setRenderer: (renderer) => {
159
- normalizedPlugin.renderer = renderer
160
- },
161
- setOptions: (opts) => {
162
- normalizedPlugin.options = { ...normalizedPlugin.options, ...opts }
163
- },
164
- injectFile: (userFileNode) => {
165
- this.fileManager.add(createFile(userFileNode))
166
- },
167
- }
168
- return hooks['kubb:plugin:setup']!(pluginCtx)
169
- }
170
-
171
- this.hooks.on('kubb:plugin:setup', setupHandler)
172
- this.#trackHookListener('kubb:plugin:setup', setupHandler as (...args: never[]) => void | Promise<void>)
173
- }
174
-
175
- // All other hooks are registered as direct pass-through listeners on the shared emitter.
176
- for (const [event, handler] of Object.entries(hooks) as Array<[keyof KubbHooks, ((...args: never[]) => void | Promise<void>) | undefined]>) {
177
- if (event === 'kubb:plugin:setup' || !handler) continue
178
-
179
- this.hooks.on(event, handler as never)
180
- this.#trackHookListener(event, handler as (...args: never[]) => void | Promise<void>)
181
- }
182
- }
183
-
184
- /**
185
- * Emits the `kubb:plugin:setup` event so that all registered hook-style plugin listeners
186
- * can configure generators, resolvers, transformers and renderers before `buildStart` runs.
187
- *
188
- * Call this once from `safeBuild` before the plugin execution loop begins.
189
- */
190
- async emitSetupHooks(): Promise<void> {
191
- const noop = () => {}
192
-
193
- await this.hooks.emit('kubb:plugin:setup', {
194
- config: this.config,
195
- options: {},
196
- addGenerator: noop,
197
- setResolver: noop,
198
- setTransformer: noop,
199
- setRenderer: noop,
200
- setOptions: noop,
201
- injectFile: noop,
202
- updateConfig: noop,
203
- })
204
- }
205
-
206
- /**
207
- * Registers a generator for the given plugin on the shared event emitter.
208
- *
209
- * The generator's `schema`, `operation`, and `operations` methods are registered as
210
- * listeners on `kubb:generate:schema`, `kubb:generate:operation`, and `kubb:generate:operations`
211
- * respectively. Each listener is scoped to the owning plugin via a `ctx.plugin.name` check
212
- * so that generators from different plugins do not cross-fire.
213
- *
214
- * The renderer resolution chain is: `generator.renderer → plugin.renderer → config.renderer`.
215
- * Set `generator.renderer = null` to explicitly opt out of rendering even when the plugin
216
- * declares a renderer.
217
- *
218
- * Call this method inside `addGenerator()` (in `kubb:plugin:setup`) to wire up a generator.
219
- */
220
- registerGenerator(pluginName: string, gen: Generator): void {
221
- const resolveRenderer = () => {
222
- const plugin = this.plugins.get(pluginName)
223
- return gen.renderer === null ? undefined : (gen.renderer ?? plugin?.renderer ?? this.config.renderer)
224
- }
225
-
226
- if (gen.schema) {
227
- const schemaHandler = async (node: SchemaNode, ctx: GeneratorContext) => {
228
- if (ctx.plugin.name !== pluginName) return
229
- const result = await gen.schema!(node, ctx)
230
- await applyHookResult(result, this, resolveRenderer())
231
- }
232
-
233
- this.hooks.on('kubb:generate:schema', schemaHandler)
234
- this.#trackHookListener('kubb:generate:schema', schemaHandler as (...args: never[]) => void | Promise<void>)
235
- }
236
-
237
- if (gen.operation) {
238
- const operationHandler = async (node: OperationNode, ctx: GeneratorContext) => {
239
- if (ctx.plugin.name !== pluginName) return
240
- const result = await gen.operation!(node, ctx)
241
- await applyHookResult(result, this, resolveRenderer())
242
- }
243
-
244
- this.hooks.on('kubb:generate:operation', operationHandler)
245
- this.#trackHookListener('kubb:generate:operation', operationHandler as (...args: never[]) => void | Promise<void>)
246
- }
247
-
248
- if (gen.operations) {
249
- const operationsHandler = async (nodes: Array<OperationNode>, ctx: GeneratorContext) => {
250
- if (ctx.plugin.name !== pluginName) return
251
- const result = await gen.operations!(nodes, ctx)
252
- await applyHookResult(result, this, resolveRenderer())
253
- }
254
-
255
- this.hooks.on('kubb:generate:operations', operationsHandler)
256
- this.#trackHookListener('kubb:generate:operations', operationsHandler as (...args: never[]) => void | Promise<void>)
257
- }
258
-
259
- this.#pluginsWithEventGenerators.add(pluginName)
260
- }
261
-
262
- /**
263
- * Returns `true` when at least one generator was registered for the given plugin
264
- * via `addGenerator()` in `kubb:plugin:setup` (event-based path).
265
- *
266
- * Used by the build loop to decide whether to walk the AST and emit generator events
267
- * for a plugin that has no static `plugin.generators`.
268
- */
269
- hasRegisteredGenerators(pluginName: string): boolean {
270
- return this.#pluginsWithEventGenerators.has(pluginName)
271
- }
272
-
273
- /**
274
- * Unregisters all plugin lifecycle listeners from the shared event emitter.
275
- * Called at the end of a build to prevent listener leaks across repeated builds.
276
- *
277
- * @internal
278
- */
279
- dispose(): void {
280
- for (const [event, handlers] of this.#hookListeners) {
281
- for (const handler of handlers) {
282
- this.hooks.off(event, handler as never)
283
- }
284
- }
285
- this.#hookListeners.clear()
286
- this.#pluginsWithEventGenerators.clear()
287
- }
288
-
289
- #trackHookListener(event: keyof KubbHooks, handler: (...args: never[]) => void | Promise<void>): void {
290
- let handlers = this.#hookListeners.get(event)
291
- if (!handlers) {
292
- handlers = new Set()
293
- this.#hookListeners.set(event, handlers)
294
- }
295
- handlers.add(handler)
296
- }
297
-
298
- #createDefaultResolver(pluginName: string): Resolver {
299
- const existingResolver = this.#defaultResolvers.get(pluginName)
300
- if (existingResolver) {
301
- return existingResolver
302
- }
303
-
304
- const resolver = defineResolver<PluginFactoryOptions>(() => ({
305
- name: 'default',
306
- pluginName,
307
- }))
308
- this.#defaultResolvers.set(pluginName, resolver)
309
- return resolver
310
- }
311
-
312
- /**
313
- * Merges `partial` with the plugin's default resolver and stores the result.
314
- * Also mirrors it onto `plugin.resolver` so callers using `getPlugin(name).resolver`
315
- * get the up-to-date resolver without going through `getResolver()`.
316
- */
317
- setPluginResolver(pluginName: string, partial: Partial<Resolver>): void {
318
- const defaultResolver = this.#createDefaultResolver(pluginName)
319
- const merged = { ...defaultResolver, ...partial }
320
- this.#resolvers.set(pluginName, merged)
321
- const plugin = this.plugins.get(pluginName)
322
- if (plugin) {
323
- plugin.resolver = merged
324
- }
325
- }
326
-
327
- /**
328
- * Returns the resolver for the given plugin.
329
- *
330
- * Resolution order: dynamic resolver set via `setPluginResolver` → static resolver on the
331
- * plugin → lazily created default resolver (identity name, no path transforms).
332
- */
333
- getResolver<TName extends keyof Kubb.PluginRegistry>(pluginName: TName): Kubb.PluginRegistry[TName]['resolver']
334
- getResolver<TResolver extends Resolver = Resolver>(pluginName: string): TResolver
335
- getResolver(pluginName: string): Resolver {
336
- return this.#resolvers.get(pluginName) ?? this.plugins.get(pluginName)?.resolver ?? this.#createDefaultResolver(pluginName)
337
- }
338
-
339
- getContext<TOptions extends PluginFactoryOptions>(plugin: NormalizedPlugin<TOptions>): GeneratorContext<TOptions> & Record<string, unknown> {
340
- const driver = this
341
-
342
- const baseContext = {
343
- config: driver.config,
344
- get root(): string {
345
- return resolve(driver.config.root, driver.config.output.path)
346
- },
347
- getMode(output: { path: string }): 'single' | 'split' {
348
- return PluginDriver.getMode(resolve(driver.config.root, driver.config.output.path, output.path))
349
- },
350
- hooks: driver.hooks,
351
- plugin,
352
- getPlugin: driver.getPlugin.bind(driver),
353
- requirePlugin: driver.requirePlugin.bind(driver),
354
- getResolver: driver.getResolver.bind(driver),
355
- driver,
356
- addFile: async (...files: Array<FileNode>) => {
357
- driver.fileManager.add(...files)
358
- },
359
- upsertFile: async (...files: Array<FileNode>) => {
360
- driver.fileManager.upsert(...files)
361
- },
362
- get inputNode(): InputNode | undefined {
363
- return driver.inputNode
364
- },
365
- get adapter(): Adapter | undefined {
366
- return driver.adapter
367
- },
368
- get resolver() {
369
- return driver.getResolver(plugin.name)
370
- },
371
- get transformer() {
372
- return plugin.transformer
373
- },
374
- warn(message: string) {
375
- driver.hooks.emit('kubb:warn', { message })
376
- },
377
- error(error: string | Error) {
378
- driver.hooks.emit('kubb:error', { error: typeof error === 'string' ? new Error(error) : error })
379
- },
380
- info(message: string) {
381
- driver.hooks.emit('kubb:info', { message })
382
- },
383
- openInStudio(options?: DevtoolsOptions) {
384
- if (!driver.config.devtools || driver.#studioIsOpen) {
385
- return
386
- }
387
-
388
- if (typeof driver.config.devtools !== 'object') {
389
- throw new Error('Devtools must be an object')
390
- }
391
-
392
- if (!driver.inputNode || !driver.adapter) {
393
- throw new Error('adapter is not defined, make sure you have set the parser in kubb.config.ts')
394
- }
395
-
396
- driver.#studioIsOpen = true
397
-
398
- const studioUrl = driver.config.devtools?.studioUrl ?? DEFAULT_STUDIO_URL
399
-
400
- return openInStudioFn(driver.inputNode, studioUrl, options)
401
- },
402
- } as unknown as GeneratorContext<TOptions>
403
-
404
- return baseContext
405
- }
406
-
407
- getPlugin<TName extends keyof Kubb.PluginRegistry>(pluginName: TName): Plugin<Kubb.PluginRegistry[TName]> | undefined
408
- getPlugin<TOptions extends PluginFactoryOptions = PluginFactoryOptions>(pluginName: string): Plugin<TOptions> | undefined
409
- getPlugin(pluginName: string): Plugin | undefined {
410
- return this.plugins.get(pluginName)
411
- }
412
-
413
- /**
414
- * Like `getPlugin` but throws a descriptive error when the plugin is not found.
415
- */
416
- requirePlugin<TName extends keyof Kubb.PluginRegistry>(pluginName: TName): Plugin<Kubb.PluginRegistry[TName]>
417
- requirePlugin<TOptions extends PluginFactoryOptions = PluginFactoryOptions>(pluginName: string): Plugin<TOptions>
418
- requirePlugin(pluginName: string): Plugin {
419
- const plugin = this.plugins.get(pluginName)
420
- if (!plugin) {
421
- throw new Error(`[kubb] Plugin "${pluginName}" is required but not found. Make sure it is included in your Kubb config.`)
422
- }
423
- return plugin
424
- }
425
- }
426
-
427
- /**
428
- * Handles the return value of a plugin AST hook or generator method.
429
- *
430
- * - Renderer output → rendered via the provided `rendererFactory` (e.g. JSX), files stored in `driver.fileManager`
431
- * - `Array<FileNode>` → added directly into `driver.fileManager`
432
- * - `void` / `null` / `undefined` → no-op (plugin handled it via `this.upsertFile`)
433
- *
434
- * Pass a `rendererFactory` (e.g. `jsxRenderer` from `@kubb/renderer-jsx`) when the result
435
- * may be a renderer element. Generators that only return `Array<FileNode>` do not need one.
436
- */
437
- export async function applyHookResult<TElement = unknown>(
438
- result: TElement | Array<FileNode> | void,
439
- driver: PluginDriver,
440
- rendererFactory?: RendererFactory<TElement>,
441
- ): Promise<void> {
442
- if (!result) return
443
-
444
- if (Array.isArray(result)) {
445
- driver.fileManager.upsert(...(result as Array<FileNode>))
446
- return
447
- }
448
-
449
- if (!rendererFactory) {
450
- return
451
- }
452
-
453
- const renderer = rendererFactory()
454
- await renderer.render(result)
455
- driver.fileManager.upsert(...renderer.files)
456
- renderer.unmount()
457
- }
package/src/constants.ts DELETED
@@ -1,35 +0,0 @@
1
- import type { FileNode } from '@kubb/ast'
2
-
3
- /**
4
- * Base URL for the Kubb Studio web app.
5
- */
6
- export const DEFAULT_STUDIO_URL = 'https://kubb.studio' as const
7
-
8
- /**
9
- * Maximum number of files processed in parallel by FileProcessor.
10
- */
11
- export const PARALLEL_CONCURRENCY_LIMIT = 100
12
-
13
- /**
14
- * Default banner style written at the top of every generated file.
15
- */
16
- export const DEFAULT_BANNER = 'simple' as const
17
-
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' }
22
-
23
- /**
24
- * Numeric log-level thresholds used internally to compare verbosity.
25
- *
26
- * Higher numbers are more verbose.
27
- */
28
- export const logLevel = {
29
- silent: Number.NEGATIVE_INFINITY,
30
- error: 0,
31
- warn: 1,
32
- info: 3,
33
- verbose: 4,
34
- debug: 5,
35
- } as const