@kubb/core 5.0.0-beta.62 → 5.0.0-beta.64

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 (43) hide show
  1. package/dist/{diagnostics-D0G07LHG.d.ts → diagnostics-BqiNAWVS.d.ts} +47 -40
  2. package/dist/index.cjs +47 -52
  3. package/dist/index.cjs.map +1 -1
  4. package/dist/index.d.ts +7 -8
  5. package/dist/index.js +49 -54
  6. package/dist/index.js.map +1 -1
  7. package/dist/{memoryStorage-CWFzAz4o.js → memoryStorage-DWnhqUf2.js} +3 -3
  8. package/dist/memoryStorage-DWnhqUf2.js.map +1 -0
  9. package/dist/{memoryStorage-CUj1hrxa.cjs → memoryStorage-mojU6pbA.cjs} +2 -2
  10. package/dist/memoryStorage-mojU6pbA.cjs.map +1 -0
  11. package/dist/mocks.cjs +2 -2
  12. package/dist/mocks.cjs.map +1 -1
  13. package/dist/mocks.d.ts +3 -3
  14. package/dist/mocks.js +3 -3
  15. package/dist/mocks.js.map +1 -1
  16. package/package.json +4 -5
  17. package/dist/memoryStorage-CUj1hrxa.cjs.map +0 -1
  18. package/dist/memoryStorage-CWFzAz4o.js.map +0 -1
  19. package/src/FileManager.ts +0 -137
  20. package/src/FileProcessor.ts +0 -212
  21. package/src/KubbDriver.ts +0 -893
  22. package/src/Transform.ts +0 -105
  23. package/src/constants.ts +0 -126
  24. package/src/createAdapter.ts +0 -127
  25. package/src/createKubb.ts +0 -196
  26. package/src/createRenderer.ts +0 -72
  27. package/src/createReporter.ts +0 -134
  28. package/src/createStorage.ts +0 -83
  29. package/src/defineGenerator.ts +0 -210
  30. package/src/defineParser.ts +0 -62
  31. package/src/definePlugin.ts +0 -437
  32. package/src/defineResolver.ts +0 -711
  33. package/src/diagnostics.ts +0 -662
  34. package/src/index.ts +0 -20
  35. package/src/mocks.ts +0 -249
  36. package/src/reporters/cliReporter.ts +0 -89
  37. package/src/reporters/fileReporter.ts +0 -103
  38. package/src/reporters/jsonReporter.ts +0 -20
  39. package/src/reporters/report.ts +0 -85
  40. package/src/storages/fsStorage.ts +0 -82
  41. package/src/storages/memoryStorage.ts +0 -55
  42. package/src/types.ts +0 -829
  43. /package/dist/{chunk-C0LytTxp.js → rolldown-runtime-C0LytTxp.js} +0 -0
@@ -1,134 +0,0 @@
1
- import type { Config } from './types.ts'
2
- import type { Diagnostic } from './diagnostics.ts'
3
-
4
- /**
5
- * Numeric log-level thresholds used internally to compare verbosity.
6
- *
7
- * Higher numbers are more verbose.
8
- */
9
- export const logLevel = {
10
- silent: Number.NEGATIVE_INFINITY,
11
- error: 0,
12
- warn: 1,
13
- info: 3,
14
- verbose: 4,
15
- } as const
16
-
17
- /**
18
- * A built-in reporter that renders a run's output, independent of the live logger view.
19
- *
20
- * - `cli` renders the per-config summary to the terminal (the default).
21
- * - `json` writes a machine-readable report to stdout, for CI.
22
- * - `file` writes a config's diagnostics to `.kubb/kubb-<name>-<timestamp>.log`.
23
- */
24
- export type ReporterName = 'cli' | 'json' | 'file'
25
-
26
- /**
27
- * One config's outcome within a run, as handed to a {@link Reporter}.
28
- */
29
- export type GenerationResult = {
30
- config: Config
31
- /**
32
- * Diagnostics collected while generating this config.
33
- */
34
- diagnostics: Array<Diagnostic>
35
- /**
36
- * Number of files written for this config.
37
- */
38
- filesCreated: number
39
- status: 'success' | 'failed'
40
- /**
41
- * `process.hrtime()` snapshot taken when this config started generating.
42
- */
43
- hrStart: [number, number]
44
- }
45
-
46
- /**
47
- * Render context passed alongside the {@link GenerationResult}, carrying knobs a reporter needs
48
- * but that are not part of the run data (e.g. verbosity).
49
- */
50
- export type ReporterContext = {
51
- /**
52
- * Output verbosity. Use the `logLevel` constants exported from `@kubb/core`
53
- * (`silent`, `error`, `warn`, `info`, `verbose`, `debug`).
54
- */
55
- logLevel: (typeof logLevel)[keyof typeof logLevel]
56
- }
57
-
58
- /**
59
- * Host-facing reporter, as installed onto a run. Unlike a Logger (the live TUI view), a reporter
60
- * never sees the event emitter. `report` runs once per config. `drain`, when present, runs once
61
- * after the last config.
62
- */
63
- export type Reporter = {
64
- /**
65
- * Display name, matching a {@link ReporterName} for the built-ins.
66
- */
67
- name: string
68
- /**
69
- * Called once per config with that config's result and the render context.
70
- */
71
- report: (result: GenerationResult, context: ReporterContext) => void | Promise<void>
72
- /**
73
- * Optional finalizer called once after the run's last config. The host wires it to
74
- * `kubb:lifecycle:end`. {@link createReporter} closes it over the reports `report` returned.
75
- */
76
- drain?: (context: ReporterContext) => void | Promise<void>
77
- }
78
-
79
- /**
80
- * Reporter definition passed to {@link createReporter}. `report` returns the value to collect for
81
- * this config (e.g. a built report), and the optional `drain` receives the collected reports to
82
- * emit as one document. `T` is inferred from `report`'s return type.
83
- */
84
- export type UserReporter<T = void> = {
85
- name: string
86
- report: (result: GenerationResult, context: ReporterContext) => T | Promise<T>
87
- drain?: (context: ReporterContext, reports: Array<T>) => void | Promise<void>
88
- }
89
-
90
- /**
91
- * Defines a reporter. When the definition has a `drain`, the returned reporter buffers each value
92
- * `report` returns and hands the array to `drain` once, then clears it. Without a `drain`, nothing
93
- * is buffered. Wiring the reporter onto the run's events is the host's job, so the reporter only
94
- * ever deals with a {@link GenerationResult}.
95
- *
96
- * @example
97
- * ```ts
98
- * import { createReporter, Diagnostics } from '@kubb/core'
99
- *
100
- * export const jsonReporter = createReporter({
101
- * name: 'json',
102
- * report(result) {
103
- * return { status: Diagnostics.hasError(result.diagnostics) ? 'failed' : 'success', diagnostics: result.diagnostics }
104
- * },
105
- * drain(context, reports) {
106
- * process.stdout.write(`${JSON.stringify(reports, null, 2)}\n`)
107
- * },
108
- * })
109
- * ```
110
- */
111
- export function createReporter<T = void>(reporter: UserReporter<T>): Reporter {
112
- const drain = reporter.drain
113
- if (!drain) {
114
- return {
115
- name: reporter.name,
116
- async report(result, context) {
117
- await reporter.report(result, context)
118
- },
119
- }
120
- }
121
-
122
- const reports: Array<T> = []
123
-
124
- return {
125
- name: reporter.name,
126
- async report(result, context) {
127
- reports.push(await reporter.report(result, context))
128
- },
129
- async drain(context) {
130
- await drain(context, reports)
131
- reports.length = 0
132
- },
133
- }
134
- }
@@ -1,83 +0,0 @@
1
- /**
2
- * Backend that persists generated files. Kubb ships with `fsStorage` (writes
3
- * to disk) and `memoryStorage` (keeps everything in RAM). Implement this
4
- * interface to write somewhere else, such as S3 or a database.
5
- */
6
- export type Storage = {
7
- /**
8
- * Identifier used in logs and diagnostics (`'fs'`, `'memory'`, `'s3'`).
9
- */
10
- readonly name: string
11
- /**
12
- * Returns `true` when an entry for `key` exists.
13
- */
14
- hasItem(key: string): Promise<boolean>
15
- /**
16
- * Reads the stored string. Returns `null` when the key is missing.
17
- */
18
- getItem(key: string): Promise<string | null>
19
- /**
20
- * Stores `value` under `key`, creating any required structure (directories,
21
- * buckets, ...).
22
- */
23
- setItem(key: string, value: string): Promise<void>
24
- /**
25
- * Deletes the entry for `key`. No-op when the key does not exist.
26
- */
27
- removeItem(key: string): Promise<void>
28
- /**
29
- * Returns every key. Pass `base` to filter to keys starting with that prefix.
30
- */
31
- getKeys(base?: string): Promise<Array<string>>
32
- /**
33
- * Removes every entry. Pass `base` to scope the wipe to a key prefix.
34
- */
35
- clear(base?: string): Promise<void>
36
- /**
37
- * Optional teardown hook called after the build completes. Use to flush
38
- * buffers, close connections, or release file locks.
39
- */
40
- dispose?(): Promise<void>
41
- }
42
-
43
- /**
44
- * Defines a custom storage backend. The builder receives user options and
45
- * returns a `Storage` implementation. Kubb ships with filesystem and in-memory
46
- * storages. A custom backend writes generated files elsewhere, such as cloud
47
- * storage or a database.
48
- *
49
- * @example In-memory storage (the built-in implementation)
50
- * ```ts
51
- * import { createStorage } from '@kubb/core'
52
- *
53
- * export const memoryStorage = createStorage(() => {
54
- * const store = new Map<string, string>()
55
- *
56
- * return {
57
- * name: 'memory',
58
- * async hasItem(key) {
59
- * return store.has(key)
60
- * },
61
- * async getItem(key) {
62
- * return store.get(key) ?? null
63
- * },
64
- * async setItem(key, value) {
65
- * store.set(key, value)
66
- * },
67
- * async removeItem(key) {
68
- * store.delete(key)
69
- * },
70
- * async getKeys(base) {
71
- * const keys = [...store.keys()]
72
- * return base ? keys.filter((k) => k.startsWith(base)) : keys
73
- * },
74
- * async clear(base) {
75
- * if (!base) store.clear()
76
- * },
77
- * }
78
- * })
79
- * ```
80
- */
81
- export function createStorage<TOptions = Record<string, never>>(build: (options: TOptions) => Storage): (options?: TOptions) => Storage {
82
- return (options) => build(options ?? ({} as TOptions))
83
- }
@@ -1,210 +0,0 @@
1
- import type { AsyncEventEmitter, PossiblePromise } from '@internals/utils'
2
- import type { FileNode, InputMeta, OperationNode, SchemaNode } 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 { KubbDriver } from './KubbDriver.ts'
7
- import type { Plugin, PluginFactoryOptions } from './definePlugin.ts'
8
- import type { Resolver } from './defineResolver.ts'
9
- import type { Config } 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
- /**
20
- * The resolved Kubb config for this build, including `root`, `input`, `output`, and the
21
- * full plugin list.
22
- */
23
- config: Config
24
- /**
25
- * Absolute path to the current plugin's output directory.
26
- */
27
- root: string
28
- /**
29
- * The driver running this build. Most generators never need it. Prefer the scoped helpers
30
- * on this context (`getPlugin`, `getResolver`, `upsertFile`) over reaching into the driver.
31
- */
32
- driver: KubbDriver
33
- /**
34
- * Get a plugin by name, typed via `Kubb.PluginRegistry` when registered.
35
- */
36
- getPlugin<TName extends keyof Kubb.PluginRegistry>(name: TName): Plugin<Kubb.PluginRegistry[TName]> | undefined
37
- getPlugin(name: string): Plugin | undefined
38
- /**
39
- * Get a plugin by name, throws an error if not found.
40
- */
41
- requirePlugin<TName extends keyof Kubb.PluginRegistry>(name: TName): Plugin<Kubb.PluginRegistry[TName]>
42
- requirePlugin(name: string): Plugin
43
- /**
44
- * Get a resolver by plugin name, typed via `Kubb.PluginRegistry` when registered.
45
- */
46
- getResolver<TName extends keyof Kubb.PluginRegistry>(name: TName): Kubb.PluginRegistry[TName]['resolver']
47
- getResolver(name: string): Resolver
48
- /**
49
- * Add files only if they don't exist.
50
- */
51
- addFile: (...file: Array<FileNode>) => Promise<void>
52
- /**
53
- * Merge sources into the same output file.
54
- */
55
- upsertFile: (...file: Array<FileNode>) => Promise<void>
56
- /**
57
- * The build's event bus. Emit or listen to any `KubbHooks` event, for example to react to
58
- * `kubb:build:end` from inside a generator.
59
- */
60
- hooks: AsyncEventEmitter<KubbHooks>
61
- /**
62
- * The current plugin instance.
63
- */
64
- plugin: Plugin<TOptions>
65
- /**
66
- * The current plugin's resolver. It decides what every generated symbol and file path is
67
- * called. Kubb picks a `setResolver` registration first, then the plugin's static
68
- * `resolver`, then the built-in default.
69
- *
70
- * @example Resolve a type name
71
- * `ctx.resolver.default('pet', 'type') // 'Pet'`
72
- *
73
- * @example Resolve an output file
74
- * `ctx.resolver.resolveFile({ name: 'pet', extname: '.ts' }, { root, output })`
75
- */
76
- resolver: TOptions['resolver']
77
- /**
78
- * Report a warning. Collected as a `warning` diagnostic attributed to the current
79
- * plugin. It surfaces in the run summary but does not fail the build. For a structured
80
- * diagnostic with a code and source location, use `Diagnostics.report` or throw a
81
- * `Diagnostics.Error` directly.
82
- */
83
- warn: (message: string) => void
84
- /**
85
- * Report an error. Collected as an `error` diagnostic attributed to the current
86
- * plugin, which fails the build.
87
- */
88
- error: (error: string | Error) => void
89
- /**
90
- * Report an informational message. Collected as an `info` diagnostic attributed to
91
- * the current plugin.
92
- */
93
- info: (message: string) => void
94
- /**
95
- * The configured adapter instance.
96
- */
97
- adapter: Adapter
98
- /**
99
- * Document metadata from the adapter: title, version, base URL, and pre-computed
100
- * schema index fields (`circularNames`, `enumNames`).
101
- */
102
- meta: InputMeta
103
- /**
104
- * Resolved options after exclude/include/override filtering.
105
- */
106
- options: TOptions['resolvedOptions']
107
- }
108
-
109
- /**
110
- * Declares a named generator unit that walks the AST and emits files.
111
- *
112
- * Each method (`schema`, `operation`, `operations`) is called for the matching node type.
113
- * JSX-based generators require a `renderer` factory. Return `Array<FileNode>` directly, or call
114
- * `ctx.upsertFile()` manually and return `null` to bypass rendering.
115
- *
116
- * @note Generators are consumed by plugins and registered via `ctx.addGenerator()` in `kubb:plugin:setup`.
117
- *
118
- * @example
119
- * ```ts
120
- * import { defineGenerator } from '@kubb/core'
121
- * import { jsxRenderer } from '@kubb/renderer-jsx'
122
- *
123
- * export const typeGenerator = defineGenerator({
124
- * name: 'typescript',
125
- * renderer: jsxRenderer,
126
- * schema(node, ctx) {
127
- * const { adapter, resolver, root, options } = ctx
128
- * return <File ...><Type node={node} resolver={resolver} /></File>
129
- * },
130
- * })
131
- * ```
132
- */
133
- export type Generator<TOptions extends PluginFactoryOptions = PluginFactoryOptions, TElement = unknown> = {
134
- /**
135
- * Used in diagnostic messages and debug output.
136
- */
137
- name: string
138
- /**
139
- * Optional renderer factory that produces a {@link Renderer} for each render cycle.
140
- *
141
- * Generators that return renderer elements (e.g. JSX via `@kubb/renderer-jsx`) must set this
142
- * to the matching renderer factory (e.g. `jsxRenderer` from `@kubb/renderer-jsx`).
143
- *
144
- * Generators that only return `Array<FileNode>` or `void` do not need to set this.
145
- *
146
- * Leave it unset or set `renderer: null` to opt out of rendering.
147
- *
148
- * @example
149
- * ```ts
150
- * import { jsxRenderer } from '@kubb/renderer-jsx'
151
- * export const myGenerator = defineGenerator<PluginTs>({
152
- * renderer: jsxRenderer,
153
- * schema(node, ctx) { return <File ...>...</File> },
154
- * })
155
- * ```
156
- */
157
- renderer?: RendererFactory<TElement> | null
158
- /**
159
- * Called for each schema node in the AST walk.
160
- * `ctx` carries the plugin context with `adapter` and `meta` (document metadata),
161
- * plus `ctx.options` with the per-node resolved options (after exclude/include/override).
162
- */
163
- schema?: (node: SchemaNode, ctx: GeneratorContext<TOptions>) => PossiblePromise<TElement | Array<FileNode> | undefined | null>
164
- /**
165
- * Called for each operation node in the AST walk.
166
- * `ctx` carries the plugin context with `adapter` and `meta` (document metadata),
167
- * plus `ctx.options` with the per-node resolved options (after exclude/include/override).
168
- */
169
- operation?: (node: OperationNode, ctx: GeneratorContext<TOptions>) => PossiblePromise<TElement | Array<FileNode> | undefined | null>
170
- /**
171
- * Called once after all operations have been walked.
172
- * `ctx` carries the plugin context with `adapter` and `meta` (document metadata),
173
- * plus `ctx.options` with the plugin-level options for the batch call.
174
- */
175
- operations?: (nodes: Array<OperationNode>, ctx: GeneratorContext<TOptions>) => PossiblePromise<TElement | Array<FileNode> | undefined | null>
176
- }
177
-
178
- /**
179
- * Defines a generator: a unit of work that runs during the plugin's AST walk
180
- * and produces files. Plugins register generators via `ctx.addGenerator()`
181
- * inside `kubb:plugin:setup`.
182
- *
183
- * The returned object is the input as-is, but with `this` types preserved so
184
- * `schema`/`operation`/`operations` methods are correctly typed against the
185
- * plugin's `PluginFactoryOptions`. Renderer elements and `FileNode[]` returns
186
- * are both handled by the runtime, so pick whichever style fits.
187
- *
188
- * @example JSX-based schema generator
189
- * ```tsx
190
- * import { defineGenerator } from '@kubb/core'
191
- * import { jsxRenderer } from '@kubb/renderer-jsx'
192
- *
193
- * export const typeGenerator = defineGenerator({
194
- * name: 'typescript',
195
- * renderer: jsxRenderer,
196
- * schema(node, ctx) {
197
- * return (
198
- * <File path={`${ctx.root}/${node.name}.ts`}>
199
- * <Type node={node} resolver={ctx.resolver} />
200
- * </File>
201
- * )
202
- * },
203
- * })
204
- * ```
205
- */
206
- export function defineGenerator<TOptions extends PluginFactoryOptions = PluginFactoryOptions, TElement = unknown>(
207
- generator: Generator<TOptions, TElement>,
208
- ): Generator<TOptions, TElement> {
209
- return generator
210
- }
@@ -1,62 +0,0 @@
1
- import type { FileNode } from '@kubb/ast'
2
-
3
- type PrintOptions = {
4
- extname?: FileNode['extname']
5
- }
6
-
7
- /**
8
- * Converts a resolved {@link FileNode} into the final source string that gets
9
- * written to disk. Kubb ships with TypeScript and TSX parsers. Add your own
10
- * for new file types (JSON, Markdown, ...).
11
- */
12
- export type Parser<TMeta extends object = object, TNode = unknown> = {
13
- /**
14
- * Display name used in diagnostics and the parser registry.
15
- */
16
- name: string
17
- /**
18
- * File extensions this parser handles. Set to `undefined` to define a
19
- * catch-all fallback used when no other parser claims the extension.
20
- *
21
- * @example
22
- * `['.ts', '.js']`
23
- */
24
- extNames: Array<FileNode['extname']> | undefined
25
- /**
26
- * Serialize the file's AST into source code.
27
- */
28
- parse(file: FileNode<TMeta>, options?: PrintOptions): string
29
- /**
30
- * Render compiler AST nodes for this parser's language into source text.
31
- * Plugins call this to format the nodes they assemble before handing them
32
- * back to the parser as `FileNode.sources`.
33
- */
34
- print(...nodes: Array<TNode>): string
35
- }
36
-
37
- /**
38
- * Defines a parser with type-safe `this`. Used to register handlers for new
39
- * file extensions or to plug a non-TypeScript output into the build.
40
- *
41
- * @example
42
- * ```ts
43
- * import { defineParser } from '@kubb/core'
44
- * import { extractStringsFromNodes } from '@kubb/ast/utils'
45
- *
46
- * export const jsonParser = defineParser({
47
- * name: 'json',
48
- * extNames: ['.json'],
49
- * parse(file) {
50
- * return file.sources
51
- * .map((source) => extractStringsFromNodes(source.nodes ?? []))
52
- * .join('\n')
53
- * },
54
- * print(...nodes) {
55
- * return nodes.map(String).join('\n')
56
- * },
57
- * })
58
- * ```
59
- */
60
- export function defineParser<T extends Parser>(parser: T): T {
61
- return parser
62
- }