@kubb/core 5.0.0-beta.75 → 5.0.0-beta.76

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