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

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-CQYd4UQZ.d.ts +2888 -0
  4. package/dist/index.cjs +2350 -1102
  5. package/dist/index.cjs.map +1 -1
  6. package/dist/index.d.ts +80 -138
  7. package/dist/index.js +2344 -1101
  8. package/dist/index.js.map +1 -1
  9. package/dist/memoryStorage-9cOBg7bL.cjs +1022 -0
  10. package/dist/memoryStorage-9cOBg7bL.cjs.map +1 -0
  11. package/dist/memoryStorage-C-3NpTDQ.js +884 -0
  12. package/dist/memoryStorage-C-3NpTDQ.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 -23
  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,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
- }
@@ -1,175 +0,0 @@
1
- import type { AsyncEventEmitter, PossiblePromise } from '@internals/utils'
2
- import type { FileNode, InputNode, OperationNode, SchemaNode, Visitor } from '@kubb/ast'
3
- import type { Adapter } from './createAdapter.ts'
4
- import type { RendererFactory } from './createRenderer.ts'
5
- import type { KubbHooks } from './types.ts'
6
- import type { PluginDriver } from './PluginDriver.ts'
7
- import type { Plugin, PluginFactoryOptions } from './definePlugin.ts'
8
- import type { Resolver } from './defineResolver.ts'
9
- import type { Config, DevtoolsOptions } from './types.ts'
10
-
11
- /**
12
- * Context object passed to generator `schema`, `operation`, and `operations` methods.
13
- *
14
- * The adapter is always defined (guaranteed by `runPluginAstHooks`) so no runtime checks
15
- * are needed. `ctx.options` carries resolved per-node options after exclude/include/override
16
- * filtering for individual schema/operation calls, or plugin-level options for operations.
17
- */
18
- export type GeneratorContext<TOptions extends PluginFactoryOptions = PluginFactoryOptions> = {
19
- config: Config
20
- /**
21
- * Absolute path to the current plugin's output directory.
22
- */
23
- root: string
24
- /**
25
- * Determine output mode based on the output config.
26
- * Returns `'single'` when `output.path` is a file, `'split'` for a directory.
27
- */
28
- getMode: (output: { path: string }) => 'single' | 'split'
29
- driver: PluginDriver
30
- /**
31
- * Get a plugin by name, typed via `Kubb.PluginRegistry` when registered.
32
- */
33
- getPlugin<TName extends keyof Kubb.PluginRegistry>(name: TName): Plugin<Kubb.PluginRegistry[TName]> | undefined
34
- getPlugin(name: string): Plugin | undefined
35
- /**
36
- * Get a plugin by name, throws an error if not found.
37
- */
38
- requirePlugin<TName extends keyof Kubb.PluginRegistry>(name: TName): Plugin<Kubb.PluginRegistry[TName]>
39
- requirePlugin(name: string): Plugin
40
- /**
41
- * Get a resolver by plugin name, typed via `Kubb.PluginRegistry` when registered.
42
- */
43
- getResolver<TName extends keyof Kubb.PluginRegistry>(name: TName): Kubb.PluginRegistry[TName]['resolver']
44
- getResolver(name: string): Resolver
45
- /**
46
- * Add files only if they don't exist.
47
- */
48
- addFile: (...file: Array<FileNode>) => Promise<void>
49
- /**
50
- * Merge sources into the same output file.
51
- */
52
- upsertFile: (...file: Array<FileNode>) => Promise<void>
53
- hooks: AsyncEventEmitter<KubbHooks>
54
- /**
55
- * The current plugin instance.
56
- */
57
- plugin: Plugin<TOptions>
58
- /**
59
- * The current plugin's resolver.
60
- */
61
- resolver: TOptions['resolver']
62
- /**
63
- * The current plugin's transformer.
64
- */
65
- transformer: Visitor | undefined
66
- /**
67
- * Emit a warning.
68
- */
69
- warn: (message: string) => void
70
- /**
71
- * Emit an error.
72
- */
73
- error: (error: string | Error) => void
74
- /**
75
- * Emit an info message.
76
- */
77
- info: (message: string) => void
78
- /**
79
- * Open the current input node in Kubb Studio.
80
- */
81
- openInStudio: (options?: DevtoolsOptions) => Promise<void>
82
- /**
83
- * The configured adapter instance.
84
- */
85
- adapter: Adapter
86
- /**
87
- * The universal `InputNode` produced by the adapter.
88
- */
89
- inputNode: InputNode
90
- /**
91
- * Resolved options after exclude/include/override filtering.
92
- */
93
- options: TOptions['resolvedOptions']
94
- }
95
-
96
- /**
97
- * Declares a named generator unit that walks the AST and emits files.
98
- *
99
- * Each method (`schema`, `operation`, `operations`) is called for the matching node type.
100
- * Each method returns `TElement | Array<FileNode> | void`. JSX-based generators require a `renderer` factory.
101
- * Return `Array<FileNode>` directly or call `ctx.upsertFile()` manually and return `void` to bypass rendering.
102
- *
103
- * @note Generators are consumed by plugins and registered via `ctx.addGenerator()` in `kubb:plugin:setup`.
104
- *
105
- * @example
106
- * ```ts
107
- * import { defineGenerator } from '@kubb/core'
108
- * import { jsxRenderer } from '@kubb/renderer-jsx'
109
- *
110
- * export const typeGenerator = defineGenerator({
111
- * name: 'typescript',
112
- * renderer: jsxRenderer,
113
- * schema(node, ctx) {
114
- * const { adapter, resolver, root, options } = ctx
115
- * return <File ...><Type node={node} resolver={resolver} /></File>
116
- * },
117
- * })
118
- * ```
119
- */
120
- export type Generator<TOptions extends PluginFactoryOptions = PluginFactoryOptions, TElement = unknown> = {
121
- /**
122
- * Used in diagnostic messages and debug output.
123
- */
124
- name: string
125
- /**
126
- * Optional renderer factory that produces a {@link Renderer} for each render cycle.
127
- *
128
- * Generators that return renderer elements (e.g. JSX via `@kubb/renderer-jsx`) must set this
129
- * to the matching renderer factory (e.g. `jsxRenderer` from `@kubb/renderer-jsx`).
130
- *
131
- * Generators that only return `Array<FileNode>` or `void` do not need to set this.
132
- *
133
- * Set `renderer: null` to explicitly opt out of rendering even when the parent plugin
134
- * declares a `renderer` (overrides the plugin-level fallback).
135
- *
136
- * @example
137
- * ```ts
138
- * import { jsxRenderer } from '@kubb/renderer-jsx'
139
- * export const myGenerator = defineGenerator<PluginTs>({
140
- * renderer: jsxRenderer,
141
- * schema(node, ctx) { return <File ...>...</File> },
142
- * })
143
- * ```
144
- */
145
- renderer?: RendererFactory<TElement> | null
146
- /**
147
- * Called for each schema node in the AST walk.
148
- * `ctx` carries the plugin context with `adapter` and `inputNode` guaranteed present,
149
- * plus `ctx.options` with the per-node resolved options (after exclude/include/override).
150
- */
151
- schema?: (node: SchemaNode, ctx: GeneratorContext<TOptions>) => PossiblePromise<TElement | Array<FileNode> | void>
152
- /**
153
- * Called for each operation node in the AST walk.
154
- * `ctx` carries the plugin context with `adapter` and `inputNode` guaranteed present,
155
- * plus `ctx.options` with the per-node resolved options (after exclude/include/override).
156
- */
157
- operation?: (node: OperationNode, ctx: GeneratorContext<TOptions>) => PossiblePromise<TElement | Array<FileNode> | void>
158
- /**
159
- * Called once after all operations have been walked.
160
- * `ctx` carries the plugin context with `adapter` and `inputNode` guaranteed present,
161
- * plus `ctx.options` with the plugin-level options for the batch call.
162
- */
163
- operations?: (nodes: Array<OperationNode>, ctx: GeneratorContext<TOptions>) => PossiblePromise<TElement | Array<FileNode> | void>
164
- }
165
-
166
- /**
167
- * Defines a generator. Returns the object as-is with correct `this` typings.
168
- * `applyHookResult` handles renderer elements and `File[]` uniformly using
169
- * the generator's declared `renderer` factory.
170
- */
171
- export function defineGenerator<TOptions extends PluginFactoryOptions = PluginFactoryOptions, TElement = unknown>(
172
- generator: Generator<TOptions, TElement>,
173
- ): Generator<TOptions, TElement> {
174
- return generator
175
- }
@@ -1,58 +0,0 @@
1
- import type { AsyncEventEmitter } from '@internals/utils'
2
- import type { logLevel } from './constants.ts'
3
- import type { KubbHooks } from './types.ts'
4
-
5
- export type LoggerOptions = {
6
- /**
7
- * Log level for output verbosity.
8
- * @default 3
9
- */
10
- logLevel: (typeof logLevel)[keyof typeof logLevel]
11
- }
12
-
13
- /**
14
- * Shared context passed to plugins, parsers, and other internals.
15
- */
16
- export type LoggerContext = AsyncEventEmitter<KubbHooks>
17
-
18
- export type Logger<TOptions extends LoggerOptions = LoggerOptions, TInstallReturn = void> = {
19
- name: string
20
- install: (context: LoggerContext, options?: TOptions) => TInstallReturn | Promise<TInstallReturn>
21
- }
22
-
23
- export type UserLogger<TOptions extends LoggerOptions = LoggerOptions, TInstallReturn = void> = Logger<TOptions, TInstallReturn>
24
-
25
- /**
26
- * Wraps a logger definition into a typed {@link Logger}.
27
- *
28
- * The optional second type parameter `TInstallReturn` allows loggers to return
29
- * a value from `install` — for example, a sink factory that the caller can
30
- * forward to hook execution.
31
- *
32
- * @example Basic logger
33
- * ```ts
34
- * export const myLogger = defineLogger({
35
- * name: 'my-logger',
36
- * install(context, options) {
37
- * context.on('kubb:info', (message) => console.log('ℹ', message))
38
- * context.on('kubb:error', (error) => console.error('✗', error.message))
39
- * },
40
- * })
41
- * ```
42
- *
43
- * @example Logger that returns a hook sink factory
44
- * ```ts
45
- * export const myLogger = defineLogger<LoggerOptions, HookSinkFactory>({
46
- * name: 'my-logger',
47
- * install(context, options) {
48
- * // … register event handlers …
49
- * return (commandWithArgs) => ({ onStdout: console.log })
50
- * },
51
- * })
52
- * ```
53
- */
54
- export function defineLogger<Options extends LoggerOptions = LoggerOptions, TInstallReturn = void>(
55
- logger: UserLogger<Options, TInstallReturn>,
56
- ): Logger<Options, TInstallReturn> {
57
- return logger
58
- }
@@ -1,62 +0,0 @@
1
- import type { KubbHooks } from './types.ts'
2
-
3
- /**
4
- * A middleware instance produced by calling a factory created with `defineMiddleware`.
5
- * It declares event handlers under a `hooks` object which are registered on the
6
- * shared emitter after all plugin hooks, so middleware handlers for any event
7
- * always fire last.
8
- */
9
- export type Middleware = {
10
- /**
11
- * Unique identifier for this middleware.
12
- */
13
- name: string
14
- /**
15
- * Lifecycle event handlers for this middleware.
16
- * Any event from the global `KubbHooks` map can be subscribed to here.
17
- * Handlers are registered after all plugin handlers, so they always fire last.
18
- */
19
- hooks: {
20
- [K in keyof KubbHooks]?: (...args: KubbHooks[K]) => void | Promise<void>
21
- }
22
- }
23
-
24
- /**
25
- * Creates a middleware factory using the hook-style `hooks` API.
26
- *
27
- * Middleware handlers fire after all plugin handlers for any given event, making them ideal for post-processing, logging, and auditing.
28
- * Per-build state (such as accumulators) belongs inside the factory closure so each `createKubb` invocation gets its own isolated instance.
29
- *
30
- * @note The factory can accept typed options. See examples for using options and per-build state patterns.
31
- *
32
- * @example
33
- * ```ts
34
- * import { defineMiddleware } from '@kubb/core'
35
- *
36
- * // Stateless middleware
37
- * export const logMiddleware = defineMiddleware(() => ({
38
- * name: 'log-middleware',
39
- * hooks: {
40
- * 'kubb:build:end'({ files }) {
41
- * console.log(`Build complete with ${files.length} files`)
42
- * },
43
- * },
44
- * }))
45
- *
46
- * // Middleware with options and per-build state
47
- * export const prefixMiddleware = defineMiddleware((options: { prefix: string } = { prefix: '' }) => {
48
- * const seen = new Set<string>()
49
- * return {
50
- * name: 'prefix-middleware',
51
- * hooks: {
52
- * 'kubb:plugin:end'({ plugin }) {
53
- * seen.add(`${options.prefix}${plugin.name}`)
54
- * },
55
- * },
56
- * }
57
- * })
58
- * ```
59
- */
60
- export function defineMiddleware<TOptions extends object = object>(factory: (options: TOptions) => Middleware): (options?: TOptions) => Middleware {
61
- return (options) => factory(options ?? ({} as TOptions))
62
- }
@@ -1,44 +0,0 @@
1
- import type { FileNode } from '@kubb/ast'
2
-
3
- type PrintOptions = {
4
- extname?: FileNode['extname']
5
- }
6
-
7
- export type Parser<TMeta extends object = any> = {
8
- name: string
9
- /**
10
- * File extensions this parser handles.
11
- * Use `undefined` to create a catch-all fallback parser.
12
- *
13
- * @example Handled extensions
14
- * `['.ts', '.js']`
15
- */
16
- extNames: Array<FileNode['extname']> | undefined
17
- /**
18
- * Convert a resolved file to a string.
19
- */
20
- parse(file: FileNode<TMeta>, options?: PrintOptions): Promise<string> | string
21
- }
22
-
23
- /**
24
- * Defines a parser with type safety. Creates parsers that transform generated files to strings based on their extension.
25
- *
26
- * @note Call the returned factory with optional options to instantiate the parser.
27
- *
28
- * @example
29
- * ```ts
30
- * import { defineParser } from '@kubb/core'
31
- *
32
- * export const jsonParser = defineParser({
33
- * name: 'json',
34
- * extNames: ['.json'],
35
- * parse(file) {
36
- * const { extractStringsFromNodes } = await import('@kubb/ast')
37
- * return file.sources.map((s) => extractStringsFromNodes(s.nodes ?? [])).join('\n')
38
- * },
39
- * })
40
- * ```
41
- */
42
- export function defineParser<TMeta extends object = any>(parser: Parser<TMeta>): Parser<TMeta> {
43
- return parser
44
- }