@kubb/core 5.0.0-beta.10 → 5.0.0-beta.101
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.
- package/LICENSE +17 -10
- package/README.md +20 -123
- package/dist/index.cjs +2301 -1122
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.ts +131 -179
- package/dist/index.js +2293 -1115
- package/dist/index.js.map +1 -1
- package/dist/mocks.cjs +81 -32
- package/dist/mocks.cjs.map +1 -1
- package/dist/mocks.d.ts +37 -14
- package/dist/mocks.js +83 -36
- package/dist/mocks.js.map +1 -1
- package/dist/types-B14Ba9P7.d.ts +2880 -0
- package/dist/usingCtx-BNggxUEL.js +597 -0
- package/dist/usingCtx-BNggxUEL.js.map +1 -0
- package/dist/usingCtx-CZyLSqds.cjs +705 -0
- package/dist/usingCtx-CZyLSqds.cjs.map +1 -0
- package/package.json +7 -28
- package/dist/PluginDriver-Cu1Kj9S-.cjs +0 -1075
- package/dist/PluginDriver-Cu1Kj9S-.cjs.map +0 -1
- package/dist/PluginDriver-D8Z0Htid.js +0 -978
- package/dist/PluginDriver-D8Z0Htid.js.map +0 -1
- package/dist/createKubb-ALdb8lmq.d.ts +0 -2082
- package/src/FileManager.ts +0 -115
- package/src/FileProcessor.ts +0 -86
- package/src/PluginDriver.ts +0 -457
- package/src/constants.ts +0 -35
- package/src/createAdapter.ts +0 -108
- package/src/createKubb.ts +0 -1266
- package/src/createRenderer.ts +0 -57
- package/src/createStorage.ts +0 -70
- package/src/defineGenerator.ts +0 -175
- package/src/defineLogger.ts +0 -58
- package/src/defineMiddleware.ts +0 -62
- package/src/defineParser.ts +0 -44
- package/src/definePlugin.ts +0 -379
- package/src/defineResolver.ts +0 -654
- package/src/devtools.ts +0 -66
- package/src/index.ts +0 -20
- package/src/mocks.ts +0 -177
- package/src/storages/fsStorage.ts +0 -89
- package/src/storages/memoryStorage.ts +0 -55
- package/src/types.ts +0 -41
- /package/dist/{chunk--u3MIqq1.js → rolldown-runtime-C0LytTxp.js} +0 -0
package/dist/index.cjs
CHANGED
|
@@ -1,150 +1,67 @@
|
|
|
1
1
|
Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
|
|
2
|
-
const
|
|
3
|
-
let
|
|
2
|
+
const require_usingCtx = require("./usingCtx-CZyLSqds.cjs");
|
|
3
|
+
let node_async_hooks = require("node:async_hooks");
|
|
4
|
+
let node_util = require("node:util");
|
|
5
|
+
let node_crypto = require("node:crypto");
|
|
4
6
|
let node_fs_promises = require("node:fs/promises");
|
|
5
7
|
let node_path = require("node:path");
|
|
8
|
+
node_path = require_usingCtx.__toESM(node_path, 1);
|
|
6
9
|
let _kubb_ast = require("@kubb/ast");
|
|
7
|
-
_kubb_ast = require_PluginDriver.__toESM(_kubb_ast, 1);
|
|
8
10
|
let node_process = require("node:process");
|
|
9
|
-
|
|
11
|
+
node_process = require_usingCtx.__toESM(node_process, 1);
|
|
12
|
+
//#region src/createAdapter.ts
|
|
10
13
|
/**
|
|
11
|
-
*
|
|
12
|
-
*
|
|
14
|
+
* Defines a custom adapter that translates a spec format into Kubb's universal
|
|
15
|
+
* AST, for example GraphQL, gRPC, or AsyncAPI. The built-in `@kubb/adapter-oas`
|
|
16
|
+
* handles OpenAPI/Swagger documents.
|
|
13
17
|
*
|
|
14
|
-
*
|
|
15
|
-
*
|
|
16
|
-
* throw new BuildError('Build failed', { errors: [err1, err2] })
|
|
17
|
-
* ```
|
|
18
|
-
*/
|
|
19
|
-
var BuildError = class extends Error {
|
|
20
|
-
errors;
|
|
21
|
-
constructor(message, options) {
|
|
22
|
-
super(message, { cause: options.cause });
|
|
23
|
-
this.name = "BuildError";
|
|
24
|
-
this.errors = options.errors;
|
|
25
|
-
}
|
|
26
|
-
};
|
|
27
|
-
/**
|
|
28
|
-
* Coerces an unknown thrown value to an `Error` instance.
|
|
29
|
-
* Returns the value as-is when it is already an `Error`; otherwise wraps it with `String(value)`.
|
|
18
|
+
* Adapters must return an `InputNode` from `parse`. That node is what every
|
|
19
|
+
* plugin in the build consumes.
|
|
30
20
|
*
|
|
31
21
|
* @example
|
|
32
22
|
* ```ts
|
|
33
|
-
*
|
|
34
|
-
*
|
|
35
|
-
*
|
|
23
|
+
* import { createAdapter, type AdapterFactoryOptions } from '@kubb/core'
|
|
24
|
+
* import { ast } from '@kubb/ast'
|
|
25
|
+
*
|
|
26
|
+
* type MyAdapter = AdapterFactoryOptions<'my-adapter', { validate?: boolean }>
|
|
27
|
+
*
|
|
28
|
+
* export const myAdapter = createAdapter<MyAdapter>((options) => ({
|
|
29
|
+
* name: 'my-adapter',
|
|
30
|
+
* options,
|
|
31
|
+
* document: null,
|
|
32
|
+
* async parse(_source) {
|
|
33
|
+
* // Convert the source (path or inline data) into an InputNode.
|
|
34
|
+
* return ast.factory.createInput()
|
|
35
|
+
* },
|
|
36
|
+
* async validate() {
|
|
37
|
+
* // Throw here when the spec is invalid.
|
|
38
|
+
* },
|
|
39
|
+
* }))
|
|
36
40
|
* ```
|
|
37
41
|
*/
|
|
38
|
-
function
|
|
39
|
-
return
|
|
42
|
+
function createAdapter(build) {
|
|
43
|
+
return (options) => build(options ?? {});
|
|
40
44
|
}
|
|
41
45
|
//#endregion
|
|
42
|
-
//#region
|
|
46
|
+
//#region src/applyConfigDefaults.ts
|
|
43
47
|
/**
|
|
44
|
-
*
|
|
45
|
-
*
|
|
46
|
-
*
|
|
47
|
-
*
|
|
48
|
-
*
|
|
49
|
-
* const emitter = new AsyncEventEmitter<{ build: [name: string] }>()
|
|
50
|
-
* emitter.on('build', async (name) => { console.log(name) })
|
|
51
|
-
* await emitter.emit('build', 'petstore') // all listeners awaited
|
|
52
|
-
* ```
|
|
48
|
+
* Fills in the config defaults shared by `defineConfig` and the unplugin factory: the fallback
|
|
49
|
+
* adapter, `defaultOutput`'s fields, and appending the barrel plugin when it's not already
|
|
50
|
+
* registered. Both entry points construct their own adapter, barrel plugin, and output defaults
|
|
51
|
+
* (`barrel` is a `@kubb/plugin-barrel` extension field core doesn't know about) and pass them in,
|
|
52
|
+
* so `@kubb/core` doesn't need to depend on `@kubb/adapter-oas` or `@kubb/plugin-barrel`.
|
|
53
53
|
*/
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
#emitter = new node_events.EventEmitter();
|
|
63
|
-
/**
|
|
64
|
-
* Emits `eventName` and awaits all registered listeners sequentially.
|
|
65
|
-
* Throws if any listener rejects, wrapping the cause with the event name and serialized arguments.
|
|
66
|
-
*
|
|
67
|
-
* @example
|
|
68
|
-
* ```ts
|
|
69
|
-
* await emitter.emit('build', 'petstore')
|
|
70
|
-
* ```
|
|
71
|
-
*/
|
|
72
|
-
async emit(eventName, ...eventArgs) {
|
|
73
|
-
const listeners = this.#emitter.listeners(eventName);
|
|
74
|
-
if (listeners.length === 0) return;
|
|
75
|
-
for (const listener of listeners) try {
|
|
76
|
-
await listener(...eventArgs);
|
|
77
|
-
} catch (err) {
|
|
78
|
-
let serializedArgs;
|
|
79
|
-
try {
|
|
80
|
-
serializedArgs = JSON.stringify(eventArgs);
|
|
81
|
-
} catch {
|
|
82
|
-
serializedArgs = String(eventArgs);
|
|
83
|
-
}
|
|
84
|
-
throw new Error(`Error in async listener for "${eventName}" with eventArgs ${serializedArgs}`, { cause: toError(err) });
|
|
54
|
+
function applyConfigDefaults(config, { defaultAdapter, barrelPlugin, barrelPluginName, defaultOutput }) {
|
|
55
|
+
const plugins = config.plugins?.some((plugin) => plugin.name === barrelPluginName) ? config.plugins ?? [] : [...config.plugins ?? [], barrelPlugin];
|
|
56
|
+
return {
|
|
57
|
+
adapter: config.adapter ?? defaultAdapter,
|
|
58
|
+
plugins,
|
|
59
|
+
output: {
|
|
60
|
+
...defaultOutput,
|
|
61
|
+
...config.output
|
|
85
62
|
}
|
|
86
|
-
}
|
|
87
|
-
|
|
88
|
-
* Registers a persistent listener for `eventName`.
|
|
89
|
-
*
|
|
90
|
-
* @example
|
|
91
|
-
* ```ts
|
|
92
|
-
* emitter.on('build', async (name) => { console.log(name) })
|
|
93
|
-
* ```
|
|
94
|
-
*/
|
|
95
|
-
on(eventName, handler) {
|
|
96
|
-
this.#emitter.on(eventName, handler);
|
|
97
|
-
}
|
|
98
|
-
/**
|
|
99
|
-
* Registers a one-shot listener that removes itself after the first invocation.
|
|
100
|
-
*
|
|
101
|
-
* @example
|
|
102
|
-
* ```ts
|
|
103
|
-
* emitter.onOnce('build', async (name) => { console.log(name) })
|
|
104
|
-
* ```
|
|
105
|
-
*/
|
|
106
|
-
onOnce(eventName, handler) {
|
|
107
|
-
const wrapper = (...args) => {
|
|
108
|
-
this.off(eventName, wrapper);
|
|
109
|
-
return handler(...args);
|
|
110
|
-
};
|
|
111
|
-
this.on(eventName, wrapper);
|
|
112
|
-
}
|
|
113
|
-
/**
|
|
114
|
-
* Removes a previously registered listener.
|
|
115
|
-
*
|
|
116
|
-
* @example
|
|
117
|
-
* ```ts
|
|
118
|
-
* emitter.off('build', handler)
|
|
119
|
-
* ```
|
|
120
|
-
*/
|
|
121
|
-
off(eventName, handler) {
|
|
122
|
-
this.#emitter.off(eventName, handler);
|
|
123
|
-
}
|
|
124
|
-
/**
|
|
125
|
-
* Returns the number of listeners registered for `eventName`.
|
|
126
|
-
*
|
|
127
|
-
* @example
|
|
128
|
-
* ```ts
|
|
129
|
-
* emitter.on('build', handler)
|
|
130
|
-
* emitter.listenerCount('build') // 1
|
|
131
|
-
* ```
|
|
132
|
-
*/
|
|
133
|
-
listenerCount(eventName) {
|
|
134
|
-
return this.#emitter.listenerCount(eventName);
|
|
135
|
-
}
|
|
136
|
-
/**
|
|
137
|
-
* Removes all listeners from every event channel.
|
|
138
|
-
*
|
|
139
|
-
* @example
|
|
140
|
-
* ```ts
|
|
141
|
-
* emitter.removeAll()
|
|
142
|
-
* ```
|
|
143
|
-
*/
|
|
144
|
-
removeAll() {
|
|
145
|
-
this.#emitter.removeAllListeners();
|
|
146
|
-
}
|
|
147
|
-
};
|
|
63
|
+
};
|
|
64
|
+
}
|
|
148
65
|
//#endregion
|
|
149
66
|
//#region ../../internals/utils/src/time.ts
|
|
150
67
|
/**
|
|
@@ -179,557 +96,1829 @@ function formatMs(ms) {
|
|
|
179
96
|
return `${Math.round(ms)}ms`;
|
|
180
97
|
}
|
|
181
98
|
//#endregion
|
|
182
|
-
//#region ../../internals/utils/src/
|
|
99
|
+
//#region ../../internals/utils/src/colors.ts
|
|
100
|
+
/**
|
|
101
|
+
* Parses a CSS hex color string (`#RGB`) into its RGB channels.
|
|
102
|
+
* Falls back to `255` for any channel that cannot be parsed.
|
|
103
|
+
*/
|
|
104
|
+
function parseHex(color) {
|
|
105
|
+
const int = Number.parseInt(color.replace("#", ""), 16);
|
|
106
|
+
return Number.isNaN(int) ? {
|
|
107
|
+
r: 255,
|
|
108
|
+
g: 255,
|
|
109
|
+
b: 255
|
|
110
|
+
} : {
|
|
111
|
+
r: int >> 16 & 255,
|
|
112
|
+
g: int >> 8 & 255,
|
|
113
|
+
b: int & 255
|
|
114
|
+
};
|
|
115
|
+
}
|
|
116
|
+
/**
|
|
117
|
+
* Returns a function that wraps a string in a 24-bit ANSI true-color escape sequence
|
|
118
|
+
* for the given hex color.
|
|
119
|
+
*/
|
|
120
|
+
function hex(color) {
|
|
121
|
+
const { r, g, b } = parseHex(color);
|
|
122
|
+
return (text) => `\x1b[38;2;${r};${g};${b}m${text}\x1b[0m`;
|
|
123
|
+
}
|
|
124
|
+
hex("#F55A17"), hex("#F5A217"), hex("#F58517"), hex("#B45309"), hex("#FFFFFF"), hex("#adadc6"), hex("#FDA4AF");
|
|
183
125
|
/**
|
|
184
|
-
*
|
|
185
|
-
|
|
126
|
+
* ANSI color names used by {@link randomCliColor} for deterministic terminal coloring.
|
|
127
|
+
*/
|
|
128
|
+
const randomColors = [
|
|
129
|
+
"black",
|
|
130
|
+
"red",
|
|
131
|
+
"green",
|
|
132
|
+
"yellow",
|
|
133
|
+
"blue",
|
|
134
|
+
"white",
|
|
135
|
+
"magenta",
|
|
136
|
+
"cyan",
|
|
137
|
+
"gray"
|
|
138
|
+
];
|
|
139
|
+
/**
|
|
140
|
+
* Wraps `text` in a deterministic ANSI color derived from the text's SHA-256 hash.
|
|
186
141
|
*
|
|
187
142
|
* @example
|
|
188
143
|
* ```ts
|
|
189
|
-
*
|
|
190
|
-
* const content = await read('./kubb.config.ts')
|
|
191
|
-
* }
|
|
144
|
+
* randomCliColor('petstore') // '\x1b[33m' + 'petstore' + '\x1b[39m' (always the same color for 'petstore')
|
|
192
145
|
* ```
|
|
193
146
|
*/
|
|
194
|
-
|
|
195
|
-
if (
|
|
196
|
-
|
|
147
|
+
function randomCliColor(text) {
|
|
148
|
+
if (!text) return "";
|
|
149
|
+
const index = (0, node_crypto.hash)("sha256", text, "buffer").readUInt32BE(0) % randomColors.length;
|
|
150
|
+
return (0, node_util.styleText)(randomColors[index] ?? "white", text);
|
|
151
|
+
}
|
|
152
|
+
//#endregion
|
|
153
|
+
//#region package.json
|
|
154
|
+
var version = "5.0.0-beta.101";
|
|
155
|
+
//#endregion
|
|
156
|
+
//#region src/constants.ts
|
|
157
|
+
/**
|
|
158
|
+
* Plugin `include` filter types that select operations directly. When one of these is set
|
|
159
|
+
* without a `schemaName` include, the generate phase pre-scans operations to compute the set
|
|
160
|
+
* of schemas they reach, so unreachable schemas can be pruned for that plugin.
|
|
161
|
+
*/
|
|
162
|
+
const OPERATION_FILTER_TYPES = /* @__PURE__ */ new Set([
|
|
163
|
+
"tag",
|
|
164
|
+
"operationId",
|
|
165
|
+
"path",
|
|
166
|
+
"method",
|
|
167
|
+
"contentType"
|
|
168
|
+
]);
|
|
169
|
+
/**
|
|
170
|
+
* Stable codes Kubb attaches to a `Diagnostic`. Each maps to a known failure mode
|
|
171
|
+
* and stays stable so it can be referenced in tooling and (later) docs. Reference
|
|
172
|
+
* these instead of inlining the string at a throw site.
|
|
173
|
+
*/
|
|
174
|
+
const diagnosticCode = {
|
|
175
|
+
/**
|
|
176
|
+
* Fallback for an unstructured error with no specific code.
|
|
177
|
+
*/
|
|
178
|
+
unknown: "KUBB_UNKNOWN",
|
|
179
|
+
/**
|
|
180
|
+
* The file or URL set as `input` could not be read.
|
|
181
|
+
*/
|
|
182
|
+
inputNotFound: "KUBB_INPUT_NOT_FOUND",
|
|
183
|
+
/**
|
|
184
|
+
* An adapter was configured without an `input`.
|
|
185
|
+
*/
|
|
186
|
+
inputRequired: "KUBB_INPUT_REQUIRED",
|
|
187
|
+
/**
|
|
188
|
+
* A `$ref` (or equivalent reference) could not be resolved in the source document.
|
|
189
|
+
*/
|
|
190
|
+
refNotFound: "KUBB_REF_NOT_FOUND",
|
|
191
|
+
/**
|
|
192
|
+
* A server variable value is not allowed by its `enum`.
|
|
193
|
+
*/
|
|
194
|
+
invalidServerVariable: "KUBB_INVALID_SERVER_VARIABLE",
|
|
195
|
+
/**
|
|
196
|
+
* A required plugin is missing from the config.
|
|
197
|
+
*/
|
|
198
|
+
pluginNotFound: "KUBB_PLUGIN_NOT_FOUND",
|
|
199
|
+
/**
|
|
200
|
+
* A plugin threw while generating.
|
|
201
|
+
*/
|
|
202
|
+
pluginFailed: "KUBB_PLUGIN_FAILED",
|
|
203
|
+
/**
|
|
204
|
+
* A plugin reported a non-fatal warning through `ctx.warn`.
|
|
205
|
+
*/
|
|
206
|
+
pluginWarning: "KUBB_PLUGIN_WARNING",
|
|
207
|
+
/**
|
|
208
|
+
* A plugin reported an informational message through `ctx.info`.
|
|
209
|
+
*/
|
|
210
|
+
pluginInfo: "KUBB_PLUGIN_INFO",
|
|
211
|
+
/**
|
|
212
|
+
* A schema uses a `format` Kubb does not map to a specific type. Reserved for
|
|
213
|
+
* adapters to emit as a `warning`.
|
|
214
|
+
*/
|
|
215
|
+
unsupportedFormat: "KUBB_UNSUPPORTED_FORMAT",
|
|
216
|
+
/**
|
|
217
|
+
* A referenced schema or operation is marked `deprecated`. Reserved for adapters
|
|
218
|
+
* to emit as an `info`.
|
|
219
|
+
*/
|
|
220
|
+
deprecated: "KUBB_DEPRECATED",
|
|
221
|
+
/**
|
|
222
|
+
* An adapter is required but the config has none. The build cannot read the input
|
|
223
|
+
* without one.
|
|
224
|
+
*/
|
|
225
|
+
adapterRequired: "KUBB_ADAPTER_REQUIRED",
|
|
226
|
+
/**
|
|
227
|
+
* A resolved output path escapes the output directory, which can stem from a path
|
|
228
|
+
* traversal in the spec or a misconfigured `group.name`.
|
|
229
|
+
*/
|
|
230
|
+
pathTraversal: "KUBB_PATH_TRAVERSAL",
|
|
231
|
+
/**
|
|
232
|
+
* `output.clean` is enabled but `output.path` resolves to the project root or a parent of it,
|
|
233
|
+
* so cleaning would delete kubb.config and every source file.
|
|
234
|
+
*/
|
|
235
|
+
cleanRoot: "KUBB_CLEAN_ROOT",
|
|
236
|
+
/**
|
|
237
|
+
* A plugin's options are invalid, for example `output.mode: 'file'` paired with a `group` option.
|
|
238
|
+
*/
|
|
239
|
+
invalidPluginOptions: "KUBB_INVALID_PLUGIN_OPTIONS",
|
|
240
|
+
/**
|
|
241
|
+
* A post-generate command (`output.postGenerate`) exited with a failure.
|
|
242
|
+
*/
|
|
243
|
+
postGenerateFailed: "KUBB_POST_GENERATE_FAILED",
|
|
244
|
+
/**
|
|
245
|
+
* The formatter pass over the generated files failed.
|
|
246
|
+
*/
|
|
247
|
+
formatFailed: "KUBB_FORMAT_FAILED",
|
|
248
|
+
/**
|
|
249
|
+
* The linter pass over the generated files failed.
|
|
250
|
+
*/
|
|
251
|
+
lintFailed: "KUBB_LINT_FAILED",
|
|
252
|
+
/**
|
|
253
|
+
* Not a failure. Carries a plugin's elapsed time, summed into the run total.
|
|
254
|
+
*/
|
|
255
|
+
performance: "KUBB_PERFORMANCE",
|
|
256
|
+
/**
|
|
257
|
+
* Not a failure. A newer Kubb version is available on npm.
|
|
258
|
+
*/
|
|
259
|
+
updateAvailable: "KUBB_UPDATE_AVAILABLE"
|
|
260
|
+
};
|
|
261
|
+
//#endregion
|
|
262
|
+
//#region src/Diagnostics.ts
|
|
263
|
+
/**
|
|
264
|
+
* Docs major version, derived from the package version so the link tracks the published major.
|
|
265
|
+
*/
|
|
266
|
+
const docsMajor = version.split(".")[0] ?? "5";
|
|
267
|
+
/**
|
|
268
|
+
* Builds a type guard that narrows a {@link Diagnostic} to the variant for `kind`. A diagnostic
|
|
269
|
+
* with no `kind` is treated as a `problem`.
|
|
270
|
+
*/
|
|
271
|
+
function isKind(kind) {
|
|
272
|
+
return (diagnostic) => (diagnostic.kind ?? "problem") === kind;
|
|
197
273
|
}
|
|
198
274
|
/**
|
|
199
|
-
*
|
|
200
|
-
* Skips the write when the trimmed content is empty or identical to what is already on disk.
|
|
201
|
-
* Creates any missing parent directories automatically.
|
|
202
|
-
* When `sanity` is `true`, re-reads the file after writing and throws if the content does not match.
|
|
275
|
+
* Returns `true` when the diagnostic is a build {@link ProblemDiagnostic}.
|
|
203
276
|
*
|
|
204
277
|
* @example
|
|
205
278
|
* ```ts
|
|
206
|
-
*
|
|
207
|
-
*
|
|
208
|
-
*
|
|
279
|
+
* if (isProblem(diagnostic)) {
|
|
280
|
+
* console.log(diagnostic.location)
|
|
281
|
+
* }
|
|
209
282
|
* ```
|
|
210
283
|
*/
|
|
211
|
-
|
|
212
|
-
const trimmed = data.trim();
|
|
213
|
-
if (trimmed === "") return null;
|
|
214
|
-
const resolved = (0, node_path.resolve)(path);
|
|
215
|
-
if (typeof Bun !== "undefined") {
|
|
216
|
-
const file = Bun.file(resolved);
|
|
217
|
-
if ((await file.exists() ? await file.text() : null) === trimmed) return null;
|
|
218
|
-
await Bun.write(resolved, trimmed);
|
|
219
|
-
return trimmed;
|
|
220
|
-
}
|
|
221
|
-
try {
|
|
222
|
-
if (await (0, node_fs_promises.readFile)(resolved, { encoding: "utf-8" }) === trimmed) return null;
|
|
223
|
-
} catch {}
|
|
224
|
-
await (0, node_fs_promises.mkdir)((0, node_path.dirname)(resolved), { recursive: true });
|
|
225
|
-
await (0, node_fs_promises.writeFile)(resolved, trimmed, { encoding: "utf-8" });
|
|
226
|
-
if (options.sanity) {
|
|
227
|
-
const savedData = await (0, node_fs_promises.readFile)(resolved, { encoding: "utf-8" });
|
|
228
|
-
if (savedData !== trimmed) throw new Error(`Sanity check failed for ${path}\n\nData[${data.length}]:\n${data}\n\nSaved[${savedData.length}]:\n${savedData}\n`);
|
|
229
|
-
return savedData;
|
|
230
|
-
}
|
|
231
|
-
return trimmed;
|
|
232
|
-
}
|
|
284
|
+
const isProblem = isKind("problem");
|
|
233
285
|
/**
|
|
234
|
-
*
|
|
286
|
+
* Returns `true` when the diagnostic is a per-plugin {@link PerformanceDiagnostic}.
|
|
235
287
|
*
|
|
236
288
|
* @example
|
|
237
289
|
* ```ts
|
|
238
|
-
*
|
|
290
|
+
* const timings = diagnostics.filter(isPerformance)
|
|
239
291
|
* ```
|
|
240
292
|
*/
|
|
241
|
-
|
|
242
|
-
return (0, node_fs_promises.rm)(path, {
|
|
243
|
-
recursive: true,
|
|
244
|
-
force: true
|
|
245
|
-
});
|
|
246
|
-
}
|
|
247
|
-
//#endregion
|
|
248
|
-
//#region ../../internals/utils/src/reserved.ts
|
|
249
|
-
/**
|
|
250
|
-
* JavaScript and Java reserved words.
|
|
251
|
-
* @link https://github.com/jonschlinkert/reserved/blob/master/index.js
|
|
252
|
-
*/
|
|
253
|
-
const reservedWords = new Set([
|
|
254
|
-
"abstract",
|
|
255
|
-
"arguments",
|
|
256
|
-
"boolean",
|
|
257
|
-
"break",
|
|
258
|
-
"byte",
|
|
259
|
-
"case",
|
|
260
|
-
"catch",
|
|
261
|
-
"char",
|
|
262
|
-
"class",
|
|
263
|
-
"const",
|
|
264
|
-
"continue",
|
|
265
|
-
"debugger",
|
|
266
|
-
"default",
|
|
267
|
-
"delete",
|
|
268
|
-
"do",
|
|
269
|
-
"double",
|
|
270
|
-
"else",
|
|
271
|
-
"enum",
|
|
272
|
-
"eval",
|
|
273
|
-
"export",
|
|
274
|
-
"extends",
|
|
275
|
-
"false",
|
|
276
|
-
"final",
|
|
277
|
-
"finally",
|
|
278
|
-
"float",
|
|
279
|
-
"for",
|
|
280
|
-
"function",
|
|
281
|
-
"goto",
|
|
282
|
-
"if",
|
|
283
|
-
"implements",
|
|
284
|
-
"import",
|
|
285
|
-
"in",
|
|
286
|
-
"instanceof",
|
|
287
|
-
"int",
|
|
288
|
-
"interface",
|
|
289
|
-
"let",
|
|
290
|
-
"long",
|
|
291
|
-
"native",
|
|
292
|
-
"new",
|
|
293
|
-
"null",
|
|
294
|
-
"package",
|
|
295
|
-
"private",
|
|
296
|
-
"protected",
|
|
297
|
-
"public",
|
|
298
|
-
"return",
|
|
299
|
-
"short",
|
|
300
|
-
"static",
|
|
301
|
-
"super",
|
|
302
|
-
"switch",
|
|
303
|
-
"synchronized",
|
|
304
|
-
"this",
|
|
305
|
-
"throw",
|
|
306
|
-
"throws",
|
|
307
|
-
"transient",
|
|
308
|
-
"true",
|
|
309
|
-
"try",
|
|
310
|
-
"typeof",
|
|
311
|
-
"var",
|
|
312
|
-
"void",
|
|
313
|
-
"volatile",
|
|
314
|
-
"while",
|
|
315
|
-
"with",
|
|
316
|
-
"yield",
|
|
317
|
-
"Array",
|
|
318
|
-
"Date",
|
|
319
|
-
"hasOwnProperty",
|
|
320
|
-
"Infinity",
|
|
321
|
-
"isFinite",
|
|
322
|
-
"isNaN",
|
|
323
|
-
"isPrototypeOf",
|
|
324
|
-
"length",
|
|
325
|
-
"Math",
|
|
326
|
-
"name",
|
|
327
|
-
"NaN",
|
|
328
|
-
"Number",
|
|
329
|
-
"Object",
|
|
330
|
-
"prototype",
|
|
331
|
-
"String",
|
|
332
|
-
"toString",
|
|
333
|
-
"undefined",
|
|
334
|
-
"valueOf"
|
|
335
|
-
]);
|
|
293
|
+
const isPerformance = isKind("performance");
|
|
336
294
|
/**
|
|
337
|
-
* Returns `true` when
|
|
295
|
+
* Returns `true` when the diagnostic is a version-update {@link UpdateDiagnostic}.
|
|
338
296
|
*
|
|
339
297
|
* @example
|
|
340
298
|
* ```ts
|
|
341
|
-
*
|
|
342
|
-
*
|
|
343
|
-
*
|
|
299
|
+
* if (isUpdate(diagnostic)) {
|
|
300
|
+
* console.log(diagnostic.latestVersion)
|
|
301
|
+
* }
|
|
344
302
|
* ```
|
|
345
303
|
*/
|
|
346
|
-
|
|
347
|
-
|
|
348
|
-
|
|
349
|
-
|
|
350
|
-
|
|
351
|
-
|
|
304
|
+
const isUpdate = isKind("update");
|
|
305
|
+
/**
|
|
306
|
+
* Accent color per severity. The color tints the `[CODE]` tag (red error, yellow warning,
|
|
307
|
+
* blue info).
|
|
308
|
+
*/
|
|
309
|
+
const severityStyle = {
|
|
310
|
+
error: "red",
|
|
311
|
+
warning: "yellow",
|
|
312
|
+
info: "blue"
|
|
313
|
+
};
|
|
314
|
+
/**
|
|
315
|
+
* Explanation for every {@link diagnosticCode}. Use {@link Diagnostics.explain} to look one up
|
|
316
|
+
* and `Diagnostics.docsUrl` for the matching kubb.dev page.
|
|
317
|
+
*/
|
|
318
|
+
const diagnosticCatalog = {
|
|
319
|
+
[diagnosticCode.unknown]: {
|
|
320
|
+
title: "Unknown error",
|
|
321
|
+
cause: "An error was thrown without a stable Kubb code, so it is reported as-is.",
|
|
322
|
+
fix: "Read the underlying message and stack. If it comes from a plugin or adapter, check its configuration; otherwise report it as a possible Kubb bug."
|
|
323
|
+
},
|
|
324
|
+
[diagnosticCode.inputNotFound]: {
|
|
325
|
+
title: "Input not found",
|
|
326
|
+
cause: "The file or URL set as `input` (or passed as `kubb generate PATH`) could not be read.",
|
|
327
|
+
fix: "Check that the path or URL exists and is readable, then set it as `input` or pass it on the CLI."
|
|
328
|
+
},
|
|
329
|
+
[diagnosticCode.inputRequired]: {
|
|
330
|
+
title: "Input required",
|
|
331
|
+
cause: "An adapter is configured but no `input` was provided.",
|
|
332
|
+
fix: "Set `input` to a file path, a URL, an inline spec (JSON/YAML string), or a parsed object in your Kubb config."
|
|
333
|
+
},
|
|
334
|
+
[diagnosticCode.refNotFound]: {
|
|
335
|
+
title: "Reference not found",
|
|
336
|
+
cause: "A `$ref` could not be resolved in the source document.",
|
|
337
|
+
fix: "Add the missing definition (for example under `components.schemas`) or fix the `$ref`. Run `kubb validate` to check the spec."
|
|
338
|
+
},
|
|
339
|
+
[diagnosticCode.invalidServerVariable]: {
|
|
340
|
+
title: "Invalid server variable",
|
|
341
|
+
cause: "A server variable value is not allowed by its `enum`.",
|
|
342
|
+
fix: "Use one of the values listed in the server variable `enum`, or update the spec."
|
|
343
|
+
},
|
|
344
|
+
[diagnosticCode.pluginNotFound]: {
|
|
345
|
+
title: "Plugin not found",
|
|
346
|
+
cause: "A plugin that another plugin depends on is missing from the config.",
|
|
347
|
+
fix: "Add the required plugin to the `plugins` array in kubb.config.ts, or remove the dependency on it."
|
|
348
|
+
},
|
|
349
|
+
[diagnosticCode.pluginFailed]: {
|
|
350
|
+
title: "Plugin failed",
|
|
351
|
+
cause: "A plugin threw while generating, or reported an error through `ctx.error`.",
|
|
352
|
+
fix: "Read the underlying error and check the plugin options and the schema or operation it failed on."
|
|
353
|
+
},
|
|
354
|
+
[diagnosticCode.pluginWarning]: {
|
|
355
|
+
title: "Plugin warning",
|
|
356
|
+
cause: "A plugin reported a non-fatal warning through `ctx.warn`.",
|
|
357
|
+
fix: "Review the message. It does not fail the build; adjust the plugin options or input if the warning is unwanted."
|
|
358
|
+
},
|
|
359
|
+
[diagnosticCode.pluginInfo]: {
|
|
360
|
+
title: "Plugin info",
|
|
361
|
+
cause: "A plugin reported an informational message through `ctx.info`.",
|
|
362
|
+
fix: "Informational only. No action is required."
|
|
363
|
+
},
|
|
364
|
+
[diagnosticCode.unsupportedFormat]: {
|
|
365
|
+
title: "Unsupported format",
|
|
366
|
+
cause: "A schema uses a `format` Kubb does not map to a specific type, so it falls back to the base type.",
|
|
367
|
+
fix: "Use a format Kubb supports, or handle the custom format with a parser or plugin."
|
|
368
|
+
},
|
|
369
|
+
[diagnosticCode.deprecated]: {
|
|
370
|
+
title: "Deprecated",
|
|
371
|
+
cause: "A referenced schema or operation is marked `deprecated`.",
|
|
372
|
+
fix: "Migrate off the deprecated definition if the warning is unwanted."
|
|
373
|
+
},
|
|
374
|
+
[diagnosticCode.adapterRequired]: {
|
|
375
|
+
title: "Adapter required",
|
|
376
|
+
cause: "An action needs an adapter but none is configured.",
|
|
377
|
+
fix: "Set `adapter` in kubb.config.ts, for example `adapterOas()`."
|
|
378
|
+
},
|
|
379
|
+
[diagnosticCode.pathTraversal]: {
|
|
380
|
+
title: "Path traversal",
|
|
381
|
+
cause: "A resolved output path escaped the output directory, which can stem from a path traversal in the spec or a misconfigured `group.name`.",
|
|
382
|
+
fix: "Keep generated paths within the output directory. Review the `group.name` function and the names coming from the spec."
|
|
383
|
+
},
|
|
384
|
+
[diagnosticCode.cleanRoot]: {
|
|
385
|
+
title: "Clean targets the project root",
|
|
386
|
+
cause: "`output.clean` is enabled and `output.path` resolves to the project root or a parent of it, so cleaning would delete `kubb.config` and every source file.",
|
|
387
|
+
fix: "Point `output.path` at a subdirectory such as `./src/gen` so clean only removes generated code, or disable `output.clean`."
|
|
388
|
+
},
|
|
389
|
+
[diagnosticCode.invalidPluginOptions]: {
|
|
390
|
+
title: "Invalid plugin options",
|
|
391
|
+
cause: "A plugin was configured with options that cannot be honored, for example `output.mode: 'file'` paired with a `group` option.",
|
|
392
|
+
fix: "Fix the plugin options. A single-file output has nothing to group, so remove the `group` option or use `output.mode: 'directory'`."
|
|
393
|
+
},
|
|
394
|
+
[diagnosticCode.postGenerateFailed]: {
|
|
395
|
+
title: "Post-generate command failed",
|
|
396
|
+
cause: "A post-generate command (`output.postGenerate`) exited with a non-zero status.",
|
|
397
|
+
fix: "Check the command is installed and correct, and run it manually to see the error."
|
|
398
|
+
},
|
|
399
|
+
[diagnosticCode.formatFailed]: {
|
|
400
|
+
title: "Format failed",
|
|
401
|
+
cause: "The formatter pass over the generated files failed.",
|
|
402
|
+
fix: "Check the formatter (oxfmt, biome, or prettier) is installed and its config is valid, then run it manually on the output."
|
|
403
|
+
},
|
|
404
|
+
[diagnosticCode.lintFailed]: {
|
|
405
|
+
title: "Lint failed",
|
|
406
|
+
cause: "The linter pass over the generated files failed.",
|
|
407
|
+
fix: "Check the linter (oxlint, biome, or eslint) is installed and its config is valid, then run it manually on the output."
|
|
408
|
+
},
|
|
409
|
+
[diagnosticCode.performance]: {
|
|
410
|
+
title: "Performance",
|
|
411
|
+
cause: "Not a failure. Records a plugin’s elapsed time, summed into the run total.",
|
|
412
|
+
fix: "No action. This is an informational metric."
|
|
413
|
+
},
|
|
414
|
+
[diagnosticCode.updateAvailable]: {
|
|
415
|
+
title: "Update available",
|
|
416
|
+
cause: "A newer Kubb version is published on npm than the one running.",
|
|
417
|
+
fix: "Update the `@kubb/*` packages, for example `npm install -g @kubb/cli`, to get the latest fixes."
|
|
418
|
+
}
|
|
419
|
+
};
|
|
352
420
|
/**
|
|
353
|
-
*
|
|
421
|
+
* Static helpers for working with {@link Diagnostic}s, plus the run-scoped sink
|
|
422
|
+
* that lets deep code report a diagnostic without threading a callback.
|
|
354
423
|
*
|
|
355
|
-
*
|
|
356
|
-
*
|
|
357
|
-
*
|
|
358
|
-
*
|
|
424
|
+
* The sink lives in a single `AsyncLocalStorage` in the `@kubb/core` bundle.
|
|
425
|
+
* `Diagnostics.scope` activates it for a run, so anything inside that run (the
|
|
426
|
+
* adapter parse, a generator) reports through `Diagnostics.report` and lands
|
|
427
|
+
* in the same run.
|
|
359
428
|
*/
|
|
360
|
-
var
|
|
429
|
+
var Diagnostics = class Diagnostics {
|
|
430
|
+
static #reporterStorage = new node_async_hooks.AsyncLocalStorage();
|
|
361
431
|
/**
|
|
362
|
-
* The
|
|
432
|
+
* The diagnostic code catalog, exposed as `Diagnostics.code` (e.g. `Diagnostics.code.refNotFound`).
|
|
363
433
|
*/
|
|
364
|
-
|
|
365
|
-
|
|
366
|
-
|
|
367
|
-
|
|
368
|
-
|
|
369
|
-
|
|
370
|
-
|
|
434
|
+
static code = diagnosticCode;
|
|
435
|
+
/**
|
|
436
|
+
* Type guard for a build {@link ProblemDiagnostic}.
|
|
437
|
+
*/
|
|
438
|
+
static isProblem = isProblem;
|
|
439
|
+
/**
|
|
440
|
+
* Type guard for a version-update {@link UpdateDiagnostic}.
|
|
441
|
+
*/
|
|
442
|
+
static isUpdate = isUpdate;
|
|
443
|
+
/**
|
|
444
|
+
* Type guard for a per-plugin {@link PerformanceDiagnostic}.
|
|
445
|
+
*/
|
|
446
|
+
static isPerformance = isPerformance;
|
|
447
|
+
/**
|
|
448
|
+
* An `Error` that carries a {@link Diagnostic}, so structured problems can flow
|
|
449
|
+
* through the existing throw/catch paths while keeping their code and location.
|
|
371
450
|
*
|
|
372
451
|
* @example
|
|
373
452
|
* ```ts
|
|
374
|
-
* new
|
|
453
|
+
* throw new Diagnostics.Error({ code: diagnosticCode.refNotFound, severity: 'error', message: `Could not find ${ref}`, location: { kind: 'schema', pointer: ref, ref } })
|
|
375
454
|
* ```
|
|
376
455
|
*/
|
|
377
|
-
|
|
378
|
-
|
|
456
|
+
static Error = class DiagnosticError extends Error {
|
|
457
|
+
diagnostic;
|
|
458
|
+
constructor(diagnostic) {
|
|
459
|
+
super(diagnostic.message, { cause: diagnostic.cause });
|
|
460
|
+
this.name = "DiagnosticError";
|
|
461
|
+
this.diagnostic = diagnostic;
|
|
462
|
+
}
|
|
463
|
+
};
|
|
464
|
+
/**
|
|
465
|
+
* Structural check for a {@link Diagnostics.Error}, including one thrown from a duplicated
|
|
466
|
+
* `@kubb/core` copy where `instanceof` fails. Matches on the `name` and a `diagnostic`
|
|
467
|
+
* that carries a `code`.
|
|
468
|
+
*/
|
|
469
|
+
static isError(error) {
|
|
470
|
+
if (error instanceof Diagnostics.Error) return true;
|
|
471
|
+
return error instanceof Error && error.name === "DiagnosticError" && "diagnostic" in error && typeof error.diagnostic === "object" && error.diagnostic !== null && typeof error.diagnostic?.code === "string";
|
|
379
472
|
}
|
|
380
|
-
/**
|
|
381
|
-
*
|
|
382
|
-
* @
|
|
383
|
-
* ```ts
|
|
384
|
-
* new URLPath('https://petstore.swagger.io/v2/pet').isURL // true
|
|
385
|
-
* new URLPath('/pet/{petId}').isURL // false
|
|
386
|
-
* ```
|
|
473
|
+
/**
|
|
474
|
+
* Runs `fn` with `sink` as the active diagnostic sink for the whole async
|
|
475
|
+
* subtree, so {@link Diagnostics.report} reaches it from anywhere inside.
|
|
387
476
|
*/
|
|
388
|
-
|
|
389
|
-
|
|
390
|
-
|
|
391
|
-
|
|
392
|
-
|
|
477
|
+
static scope(sink, fn) {
|
|
478
|
+
return Diagnostics.#reporterStorage.run(sink, fn);
|
|
479
|
+
}
|
|
480
|
+
/**
|
|
481
|
+
* Collects a diagnostic into the active build via the run-scoped sink, without throwing.
|
|
482
|
+
* Returns `true` when a run consumed it, `false` when called outside a {@link Diagnostics.scope}
|
|
483
|
+
* (so callers can fall back to throwing). Use a `warning`/`info` severity for non-fatal issues.
|
|
484
|
+
* For rendering a diagnostic live on the hook bus, use {@link Diagnostics.emit} instead.
|
|
485
|
+
*/
|
|
486
|
+
static report(diagnostic) {
|
|
487
|
+
const sink = Diagnostics.#reporterStorage.getStore();
|
|
488
|
+
if (!sink) return false;
|
|
489
|
+
sink(diagnostic);
|
|
490
|
+
return true;
|
|
491
|
+
}
|
|
492
|
+
/**
|
|
493
|
+
* Emits a diagnostic on the run's `kubb:diagnostic` hook so the loggers render it live.
|
|
494
|
+
* Use it instead of calling `hooks.callHook('kubb:diagnostic', ...)` directly. To collect a
|
|
495
|
+
* diagnostic into the build result from deep in a run, use {@link Diagnostics.report} instead.
|
|
496
|
+
*/
|
|
497
|
+
static async emit(hooks, diagnostic) {
|
|
498
|
+
await hooks.callHook("kubb:diagnostic", { diagnostic });
|
|
499
|
+
}
|
|
500
|
+
/**
|
|
501
|
+
* Coerces any thrown value into a {@link ProblemDiagnostic}. A {@link Diagnostics.Error}
|
|
502
|
+
* keeps its structured data, and anything else becomes a `KUBB_UNKNOWN` error.
|
|
503
|
+
*/
|
|
504
|
+
static from(error) {
|
|
505
|
+
const seen = /* @__PURE__ */ new Set();
|
|
506
|
+
let current = error;
|
|
507
|
+
let root;
|
|
508
|
+
while (current instanceof Error && !seen.has(current)) {
|
|
509
|
+
if (Diagnostics.isError(current)) return current.diagnostic;
|
|
510
|
+
seen.add(current);
|
|
511
|
+
root = current;
|
|
512
|
+
current = current.cause;
|
|
393
513
|
}
|
|
514
|
+
return {
|
|
515
|
+
code: diagnosticCode.unknown,
|
|
516
|
+
severity: "error",
|
|
517
|
+
message: root ? root.message : require_usingCtx.getErrorMessage(error),
|
|
518
|
+
cause: root
|
|
519
|
+
};
|
|
394
520
|
}
|
|
395
521
|
/**
|
|
396
|
-
*
|
|
397
|
-
*
|
|
398
|
-
* @example
|
|
399
|
-
* new URLPath('/pet/{petId}').template // '`/pet/${petId}`'
|
|
400
|
-
* new URLPath('/account/monetary-accountID').template // '`/account/${monetaryAccountId}`'
|
|
522
|
+
* Builds a per-plugin performance record. Reporters sum these into the run total.
|
|
401
523
|
*/
|
|
402
|
-
|
|
403
|
-
return
|
|
524
|
+
static performance({ plugin, duration }) {
|
|
525
|
+
return {
|
|
526
|
+
kind: "performance",
|
|
527
|
+
code: diagnosticCode.performance,
|
|
528
|
+
severity: "info",
|
|
529
|
+
message: `${plugin} generated in ${Math.round(duration)}ms`,
|
|
530
|
+
plugin,
|
|
531
|
+
duration
|
|
532
|
+
};
|
|
404
533
|
}
|
|
405
|
-
/**
|
|
406
|
-
*
|
|
407
|
-
* @example
|
|
408
|
-
* ```ts
|
|
409
|
-
* new URLPath('/pet/{petId}').object
|
|
410
|
-
* // { url: '/pet/:petId', params: { petId: 'petId' } }
|
|
411
|
-
* ```
|
|
534
|
+
/**
|
|
535
|
+
* Builds the version-update notice shown when a newer Kubb is published on npm.
|
|
412
536
|
*/
|
|
413
|
-
|
|
414
|
-
return
|
|
537
|
+
static update({ currentVersion, latestVersion }) {
|
|
538
|
+
return {
|
|
539
|
+
kind: "update",
|
|
540
|
+
code: diagnosticCode.updateAvailable,
|
|
541
|
+
severity: "info",
|
|
542
|
+
message: `Update available: v${currentVersion} → v${latestVersion}. Run \`npm install -g @kubb/cli\` to update.`,
|
|
543
|
+
currentVersion,
|
|
544
|
+
latestVersion
|
|
545
|
+
};
|
|
415
546
|
}
|
|
416
|
-
/**
|
|
417
|
-
*
|
|
418
|
-
*
|
|
419
|
-
* ```ts
|
|
420
|
-
* new URLPath('/pet/{petId}').params // { petId: 'petId' }
|
|
421
|
-
* new URLPath('/pet').params // undefined
|
|
422
|
-
* ```
|
|
547
|
+
/**
|
|
548
|
+
* True when any diagnostic is an error, the severity that fails a build. Non-error
|
|
549
|
+
* diagnostics are ignored.
|
|
423
550
|
*/
|
|
424
|
-
|
|
425
|
-
return
|
|
551
|
+
static hasError(diagnostics) {
|
|
552
|
+
return diagnostics.some((diagnostic) => diagnostic.severity === "error");
|
|
426
553
|
}
|
|
427
|
-
|
|
428
|
-
|
|
429
|
-
|
|
554
|
+
/**
|
|
555
|
+
* Names of the plugins that failed, deduped, derived from the error diagnostics
|
|
556
|
+
* that carry a `plugin`.
|
|
557
|
+
*/
|
|
558
|
+
static failedPlugins(diagnostics) {
|
|
559
|
+
const names = /* @__PURE__ */ new Set();
|
|
560
|
+
for (const diagnostic of diagnostics) if (diagnostic.severity === "error" && diagnostic.plugin) names.add(diagnostic.plugin);
|
|
561
|
+
return [...names];
|
|
430
562
|
}
|
|
431
563
|
/**
|
|
432
|
-
*
|
|
564
|
+
* Counts `problem` diagnostics by severity for the run summary. `performance` and
|
|
565
|
+
* `update` diagnostics are ignored.
|
|
433
566
|
*/
|
|
434
|
-
|
|
435
|
-
|
|
436
|
-
|
|
437
|
-
|
|
567
|
+
static count(diagnostics) {
|
|
568
|
+
let errors = 0;
|
|
569
|
+
let warnings = 0;
|
|
570
|
+
let infos = 0;
|
|
571
|
+
for (const diagnostic of diagnostics) {
|
|
572
|
+
if (!isProblem(diagnostic)) continue;
|
|
573
|
+
if (diagnostic.severity === "error") errors += 1;
|
|
574
|
+
else if (diagnostic.severity === "warning") warnings += 1;
|
|
575
|
+
else infos += 1;
|
|
438
576
|
}
|
|
439
|
-
|
|
440
|
-
|
|
441
|
-
|
|
442
|
-
|
|
443
|
-
params: this.getParams()
|
|
577
|
+
return {
|
|
578
|
+
errors,
|
|
579
|
+
warnings,
|
|
580
|
+
infos
|
|
444
581
|
};
|
|
445
|
-
|
|
446
|
-
|
|
447
|
-
|
|
448
|
-
|
|
582
|
+
}
|
|
583
|
+
/**
|
|
584
|
+
* Drops duplicate `problem` diagnostics that share a code, location pointer, and
|
|
585
|
+
* plugin, so the same issue reported across several passes is shown once. Non-problem
|
|
586
|
+
* diagnostics are always kept.
|
|
587
|
+
*/
|
|
588
|
+
static dedupe(diagnostics) {
|
|
589
|
+
const seen = /* @__PURE__ */ new Set();
|
|
590
|
+
const result = [];
|
|
591
|
+
for (const diagnostic of diagnostics) {
|
|
592
|
+
if (!isProblem(diagnostic)) {
|
|
593
|
+
result.push(diagnostic);
|
|
594
|
+
continue;
|
|
595
|
+
}
|
|
596
|
+
const pointer = diagnostic.location && "pointer" in diagnostic.location ? diagnostic.location.pointer : "";
|
|
597
|
+
const key = `${diagnostic.code} ${pointer} ${diagnostic.plugin ?? ""}`;
|
|
598
|
+
if (seen.has(key)) continue;
|
|
599
|
+
seen.add(key);
|
|
600
|
+
result.push(diagnostic);
|
|
449
601
|
}
|
|
450
|
-
return
|
|
602
|
+
return result;
|
|
451
603
|
}
|
|
452
604
|
/**
|
|
453
|
-
*
|
|
454
|
-
*
|
|
455
|
-
*
|
|
456
|
-
* @example
|
|
457
|
-
* new URLPath('/pet/{petId}').toTemplateString() // '`/pet/${petId}`'
|
|
605
|
+
* Builds the kubb.dev docs URL for a diagnostic code, e.g.
|
|
606
|
+
* `KUBB_REF_NOT_FOUND` → `https://kubb.dev/docs/5.x/reference/diagnostics/kubb-ref-not-found`.
|
|
458
607
|
*/
|
|
459
|
-
|
|
460
|
-
|
|
461
|
-
|
|
462
|
-
const param = this.#transformParam(part);
|
|
463
|
-
return `\${${replacer ? replacer(param) : param}}`;
|
|
464
|
-
}).join("")}\``;
|
|
608
|
+
static docsUrl(code) {
|
|
609
|
+
const slug = code.toLowerCase().replaceAll("_", "-");
|
|
610
|
+
return `https://kubb.dev/docs/${docsMajor}.x/reference/diagnostics/${slug}`;
|
|
465
611
|
}
|
|
466
612
|
/**
|
|
467
|
-
*
|
|
468
|
-
*
|
|
469
|
-
* Returns `undefined` when no path parameters are found.
|
|
470
|
-
*
|
|
471
|
-
* @example
|
|
472
|
-
* ```ts
|
|
473
|
-
* new URLPath('/pet/{petId}/tag/{tagId}').getParams()
|
|
474
|
-
* // { petId: 'petId', tagId: 'tagId' }
|
|
475
|
-
* ```
|
|
613
|
+
* The catalog entry for a code: its title, cause, and fix. Mirrors the kubb.dev
|
|
614
|
+
* `/diagnostics/<slug>` page.
|
|
476
615
|
*/
|
|
477
|
-
|
|
478
|
-
|
|
479
|
-
|
|
480
|
-
|
|
481
|
-
|
|
482
|
-
|
|
483
|
-
|
|
616
|
+
static explain(code) {
|
|
617
|
+
return diagnosticCatalog[code];
|
|
618
|
+
}
|
|
619
|
+
/**
|
|
620
|
+
* Reduces a diagnostic to its JSON-safe fields plus a `docsUrl`, for machine-readable
|
|
621
|
+
* consumers. The `cause`, `kind`, and `duration` are dropped, and absent optional
|
|
622
|
+
* fields are omitted rather than set to `undefined`.
|
|
623
|
+
*/
|
|
624
|
+
static serialize(diagnostic) {
|
|
625
|
+
const problem = isProblem(diagnostic) ? diagnostic : void 0;
|
|
626
|
+
return {
|
|
627
|
+
code: diagnostic.code,
|
|
628
|
+
severity: diagnostic.severity,
|
|
629
|
+
message: diagnostic.message,
|
|
630
|
+
...problem?.location ? { location: problem.location } : {},
|
|
631
|
+
...problem?.help ? { help: problem.help } : {},
|
|
632
|
+
...problem?.plugin ? { plugin: problem.plugin } : {},
|
|
633
|
+
...diagnostic.code === diagnosticCode.unknown ? {} : { docsUrl: Diagnostics.docsUrl(diagnostic.code) }
|
|
634
|
+
};
|
|
484
635
|
}
|
|
485
|
-
/**
|
|
636
|
+
/**
|
|
637
|
+
* Renders a {@link Diagnostic} for terminal output as its parts: the `headline`
|
|
638
|
+
* (`[CODE] plugin: message`, with the code in the severity color) and the indented `details`
|
|
639
|
+
* rows (`at:` pointer, `fix:` help, `see:` docs link).
|
|
486
640
|
*
|
|
487
|
-
*
|
|
488
|
-
*
|
|
489
|
-
|
|
490
|
-
|
|
641
|
+
* Hosts compose these to fit their gutter: a clack logger passes `[headline, ...details]` as the
|
|
642
|
+
* message with no gutter symbol, while plain text outputs use {@link Diagnostics.formatLines}.
|
|
643
|
+
*/
|
|
644
|
+
static format(diagnostic) {
|
|
645
|
+
const { code, severity, message } = diagnostic;
|
|
646
|
+
const color = severityStyle[severity];
|
|
647
|
+
const problem = isProblem(diagnostic) ? diagnostic : void 0;
|
|
648
|
+
const tag = (0, node_util.styleText)(color, (0, node_util.styleText)("bold", `[${code}]`));
|
|
649
|
+
const headline = problem?.plugin ? `${tag} ${problem.plugin}: ${message}` : `${tag}: ${message}`;
|
|
650
|
+
const details = [];
|
|
651
|
+
if (problem?.location && "pointer" in problem.location) details.push(` ${(0, node_util.styleText)("dim", "at:")} ${(0, node_util.styleText)("cyan", problem.location.pointer)}`);
|
|
652
|
+
if (problem?.help) details.push(` ${(0, node_util.styleText)("cyan", "fix:")} ${problem.help}`);
|
|
653
|
+
if (code !== diagnosticCode.unknown) details.push(` ${(0, node_util.styleText)("dim", "see:")} ${(0, node_util.styleText)("cyan", Diagnostics.docsUrl(code))}`);
|
|
654
|
+
return {
|
|
655
|
+
headline,
|
|
656
|
+
details
|
|
657
|
+
};
|
|
658
|
+
}
|
|
659
|
+
/**
|
|
660
|
+
* The self-contained block form of {@link Diagnostics.format}: the `headline` followed by the
|
|
661
|
+
* indented detail rows. Used where there is no gutter (plain and file output).
|
|
491
662
|
*/
|
|
492
|
-
|
|
493
|
-
|
|
663
|
+
static formatLines(diagnostic) {
|
|
664
|
+
const { headline, details } = Diagnostics.format(diagnostic);
|
|
665
|
+
return [headline, ...details];
|
|
494
666
|
}
|
|
495
667
|
};
|
|
496
668
|
//#endregion
|
|
497
|
-
//#region src/
|
|
669
|
+
//#region src/definePlugin.ts
|
|
498
670
|
/**
|
|
499
|
-
*
|
|
500
|
-
*
|
|
501
|
-
*
|
|
502
|
-
|
|
503
|
-
|
|
504
|
-
|
|
505
|
-
|
|
671
|
+
* Merges the `output.mode` default into the output config and validates the combination.
|
|
672
|
+
* Throws `KUBB_INVALID_PLUGIN_OPTIONS` when `mode: 'file'` is paired with a `group` option,
|
|
673
|
+
* since a single-file output has nothing to group.
|
|
674
|
+
*/
|
|
675
|
+
function normalizeOutput({ output, group, pluginName }) {
|
|
676
|
+
const mode = output.mode ?? "file";
|
|
677
|
+
if (mode === "file" && group) throw new Diagnostics.Error({
|
|
678
|
+
code: diagnosticCode.invalidPluginOptions,
|
|
679
|
+
severity: "error",
|
|
680
|
+
message: `Plugin "${pluginName}" sets \`output.mode: 'file'\` but also configures a \`group\` option.`,
|
|
681
|
+
help: "A single-file output has nothing to group. Remove the `group` option, or use `output.mode: 'directory'` to organize files into subdirectories.",
|
|
682
|
+
location: { kind: "config" },
|
|
683
|
+
plugin: pluginName
|
|
684
|
+
});
|
|
685
|
+
return {
|
|
686
|
+
...output,
|
|
687
|
+
mode
|
|
688
|
+
};
|
|
689
|
+
}
|
|
690
|
+
/**
|
|
691
|
+
* Wraps a plugin factory and returns a function that accepts user options and
|
|
692
|
+
* yields a typed `Plugin`. Lifecycle handlers go inside a single `hooks` object.
|
|
693
|
+
*
|
|
694
|
+
* Pass a `PluginFactoryOptions` type parameter to get a typed `ctx` inside
|
|
695
|
+
* `kubb:plugin:setup`. Plugin names should follow the `plugin-<feature>`
|
|
696
|
+
* convention (`plugin-react-query`, `plugin-zod`, ...).
|
|
697
|
+
*
|
|
506
698
|
* @example
|
|
507
699
|
* ```ts
|
|
508
|
-
*
|
|
509
|
-
* return {
|
|
510
|
-
* name: 'my-adapter',
|
|
511
|
-
* options,
|
|
512
|
-
* async parse(source) {
|
|
513
|
-
* // Transform source format to InputNode
|
|
514
|
-
* return { ... }
|
|
515
|
-
* },
|
|
516
|
-
* }
|
|
517
|
-
* })
|
|
700
|
+
* import { definePlugin } from '@kubb/core'
|
|
518
701
|
*
|
|
519
|
-
*
|
|
520
|
-
*
|
|
702
|
+
* export const pluginTs = definePlugin((options: { prefix?: string } = {}) => ({
|
|
703
|
+
* name: 'plugin-ts',
|
|
704
|
+
* hooks: {
|
|
705
|
+
* 'kubb:plugin:setup'(ctx) {
|
|
706
|
+
* ctx.setResolver(resolverTs)
|
|
707
|
+
* },
|
|
708
|
+
* },
|
|
709
|
+
* }))
|
|
521
710
|
* ```
|
|
522
711
|
*/
|
|
523
|
-
function
|
|
524
|
-
return (options) =>
|
|
712
|
+
function definePlugin(factory) {
|
|
713
|
+
return (options) => factory(options ?? {});
|
|
525
714
|
}
|
|
526
715
|
//#endregion
|
|
527
|
-
//#region
|
|
528
|
-
|
|
716
|
+
//#region src/input.ts
|
|
717
|
+
/**
|
|
718
|
+
* Classifies an `input` value so callers branch on it once instead of repeating the checks.
|
|
719
|
+
*
|
|
720
|
+
* A non-string is a parsed spec (`object`). A string is `inline` when it holds OpenAPI content,
|
|
721
|
+
* meaning it starts with `{` or `[`, spans multiple lines, or opens with a YAML `openapi:` or
|
|
722
|
+
* `swagger:` key. Otherwise a string is a `url` when it parses as one, or a `file` path.
|
|
723
|
+
*/
|
|
724
|
+
function getInputKind(input) {
|
|
725
|
+
if (typeof input !== "string") return "object";
|
|
726
|
+
const trimmed = input.trimStart();
|
|
727
|
+
if (trimmed.startsWith("{") || trimmed.startsWith("[") || input.includes("\n") || /^(openapi|swagger)\s*:/i.test(trimmed)) return "inline";
|
|
728
|
+
if (URL.canParse(input)) return "url";
|
|
729
|
+
return "file";
|
|
730
|
+
}
|
|
731
|
+
/**
|
|
732
|
+
* Normalizes `config.input` into an `AdapterSource` the adapter can parse.
|
|
733
|
+
*
|
|
734
|
+
* A parsed object and inline content become `{ type: 'data' }`; a URL is kept verbatim and a
|
|
735
|
+
* local path is resolved against `config.root`, both as `{ type: 'path' }`.
|
|
736
|
+
*/
|
|
737
|
+
function inputToAdapterSource(config) {
|
|
738
|
+
const input = config.input;
|
|
739
|
+
if (!input) throw new Diagnostics.Error({
|
|
740
|
+
code: Diagnostics.code.inputRequired,
|
|
741
|
+
severity: "error",
|
|
742
|
+
message: "An adapter is configured without an input.",
|
|
743
|
+
help: "Set `input` to a file path, a URL, an inline spec (JSON/YAML string), or a parsed object in your Kubb config.",
|
|
744
|
+
location: { kind: "config" }
|
|
745
|
+
});
|
|
746
|
+
if (typeof input !== "string") return {
|
|
747
|
+
type: "data",
|
|
748
|
+
data: input
|
|
749
|
+
};
|
|
750
|
+
const kind = getInputKind(input);
|
|
751
|
+
if (kind === "inline") return {
|
|
752
|
+
type: "data",
|
|
753
|
+
data: input
|
|
754
|
+
};
|
|
755
|
+
if (kind === "url") return {
|
|
756
|
+
type: "path",
|
|
757
|
+
path: input
|
|
758
|
+
};
|
|
759
|
+
return {
|
|
760
|
+
type: "path",
|
|
761
|
+
path: (0, node_path.resolve)(config.root, input)
|
|
762
|
+
};
|
|
763
|
+
}
|
|
529
764
|
//#endregion
|
|
530
|
-
//#region
|
|
531
|
-
|
|
532
|
-
value;
|
|
533
|
-
|
|
534
|
-
|
|
535
|
-
|
|
765
|
+
//#region src/Resolver.ts
|
|
766
|
+
function isNamespace(value) {
|
|
767
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
768
|
+
}
|
|
769
|
+
/**
|
|
770
|
+
* Shared brand for reaching a resolver's build options. `Resolver.merge` reads this instead of
|
|
771
|
+
* relying on `instanceof`, which fails when a CommonJS config and the ESM CLI each load their own
|
|
772
|
+
* copy of `@kubb/core`. `Symbol.for` resolves to one key across those copies, so the options stay
|
|
773
|
+
* reachable and a `file` override is never dropped.
|
|
774
|
+
*/
|
|
775
|
+
const resolverOptions = Symbol.for("@kubb/core/resolver/options");
|
|
776
|
+
/**
|
|
777
|
+
* Built-in `file.baseName`: casts the identifier with `toFilePath` and appends the extension.
|
|
778
|
+
*/
|
|
779
|
+
function toBaseName({ name, extname }) {
|
|
780
|
+
return `${require_usingCtx.toFilePath(name)}${extname}`;
|
|
781
|
+
}
|
|
782
|
+
/**
|
|
783
|
+
* Base constraint for all plugin resolver objects.
|
|
784
|
+
*
|
|
785
|
+
* The built-in machinery lives under `default`. Generators call the top-level `name`, `file`,
|
|
786
|
+
* and `imports`, and a plugin overrides `name` and `file` to set its conventions. Extend with
|
|
787
|
+
* top-level helpers (`typeName`, …) and/or grouped namespaces (`query`, `schema`, …).
|
|
788
|
+
*
|
|
789
|
+
* @example Top-level helper
|
|
790
|
+
* ```ts
|
|
791
|
+
* type MyResolver = Resolver & {
|
|
792
|
+
* typeName(name: string): string
|
|
793
|
+
* }
|
|
794
|
+
* ```
|
|
795
|
+
*
|
|
796
|
+
* @example Grouped namespace
|
|
797
|
+
* ```ts
|
|
798
|
+
* type MyResolver = Resolver & {
|
|
799
|
+
* query: {
|
|
800
|
+
* name(node: OperationNode): string
|
|
801
|
+
* keyName(node: OperationNode): string
|
|
802
|
+
* }
|
|
803
|
+
* }
|
|
804
|
+
* ```
|
|
805
|
+
*/
|
|
806
|
+
var Resolver = class Resolver {
|
|
807
|
+
static #patternCache = /* @__PURE__ */ new Map();
|
|
808
|
+
static #optionsCache = /* @__PURE__ */ new WeakMap();
|
|
809
|
+
pluginName;
|
|
810
|
+
#options;
|
|
811
|
+
#baseName;
|
|
812
|
+
#filePath;
|
|
813
|
+
constructor(options) {
|
|
814
|
+
this.pluginName = options.pluginName;
|
|
815
|
+
this.#options = options;
|
|
816
|
+
this.#baseName = options.file?.baseName ? options.file.baseName.bind(this) : toBaseName;
|
|
817
|
+
this.#filePath = options.file?.path ? options.file.path.bind(this) : void 0;
|
|
818
|
+
this.#apply(options);
|
|
536
819
|
}
|
|
537
|
-
|
|
538
|
-
|
|
539
|
-
|
|
540
|
-
|
|
541
|
-
|
|
542
|
-
|
|
543
|
-
|
|
544
|
-
|
|
545
|
-
|
|
546
|
-
|
|
547
|
-
|
|
548
|
-
this.#
|
|
549
|
-
this.#
|
|
550
|
-
|
|
551
|
-
this.#
|
|
552
|
-
this.#
|
|
820
|
+
/** Exposes the raw build options so `Resolver.merge` can read them across `@kubb/core` copies. */
|
|
821
|
+
get [resolverOptions]() {
|
|
822
|
+
return this.#options;
|
|
823
|
+
}
|
|
824
|
+
/**
|
|
825
|
+
* The built-in resolution machinery. Always reaches the untouched defaults, even when a
|
|
826
|
+
* plugin overrides the top-level `name` or `file`.
|
|
827
|
+
*/
|
|
828
|
+
get default() {
|
|
829
|
+
return {
|
|
830
|
+
name: require_usingCtx.camelCase,
|
|
831
|
+
options: this.#resolveOptions.bind(this),
|
|
832
|
+
path: this.#resolvePath.bind(this),
|
|
833
|
+
file: this.#resolveFile.bind(this),
|
|
834
|
+
banner: this.#resolveBanner.bind(this),
|
|
835
|
+
footer: this.#resolveFooter.bind(this)
|
|
836
|
+
};
|
|
837
|
+
}
|
|
838
|
+
name(name) {
|
|
839
|
+
return this.default.name(name);
|
|
840
|
+
}
|
|
841
|
+
file(options) {
|
|
842
|
+
return this.#resolveFile(options);
|
|
843
|
+
}
|
|
844
|
+
/**
|
|
845
|
+
* Builds one `ImportNode` per unique schema referenced in the tree, in first-occurrence
|
|
846
|
+
* order. Each ref's target resolves through `resolveRefName`, so collision- or macro-renamed
|
|
847
|
+
* schemas (`targetName`) import the emitted name. Names and paths go through the top-level
|
|
848
|
+
* `name` and `file`, so import entries follow the plugin's conventions, and a per-call
|
|
849
|
+
* `name` override wins over both.
|
|
850
|
+
*/
|
|
851
|
+
imports(options) {
|
|
852
|
+
const { node, root, output, group, extname = ".ts", name } = options;
|
|
853
|
+
const resolveName = name ?? ((schemaName) => this.name(schemaName));
|
|
854
|
+
const seen = /* @__PURE__ */ new Set();
|
|
855
|
+
return (0, _kubb_ast.collectSync)(node, { schema: (schemaNode) => {
|
|
856
|
+
const schemaRef = (0, _kubb_ast.narrowSchema)(schemaNode, "ref");
|
|
857
|
+
if (!schemaRef?.ref) return null;
|
|
858
|
+
const schemaName = (0, _kubb_ast.resolveRefName)(schemaRef);
|
|
859
|
+
if (!schemaName || seen.has(schemaName)) return null;
|
|
860
|
+
seen.add(schemaName);
|
|
861
|
+
return _kubb_ast.ast.factory.createImport({
|
|
862
|
+
name: [resolveName(schemaName)],
|
|
863
|
+
path: this.file({
|
|
864
|
+
name: schemaName,
|
|
865
|
+
extname,
|
|
866
|
+
root,
|
|
867
|
+
output,
|
|
868
|
+
group
|
|
869
|
+
}).path
|
|
870
|
+
});
|
|
871
|
+
} });
|
|
872
|
+
}
|
|
873
|
+
/**
|
|
874
|
+
* Folds each `override` over `base`, left to right, and returns a new resolver with helpers
|
|
875
|
+
* re-bound. Top-level keys replace, and a namespace (or `file`) merges per method, so overriding
|
|
876
|
+
* `query.name` keeps the base `query.keyName`. The last override wins per key. Used when applying
|
|
877
|
+
* `setResolver` partial overrides, and to compose shared resolver fragments without spreading each
|
|
878
|
+
* namespace by hand. Reads a resolver's options through the shared brand rather than `instanceof`,
|
|
879
|
+
* so a `file` override survives even when `base` and `override` come from different `@kubb/core`
|
|
880
|
+
* copies.
|
|
881
|
+
*
|
|
882
|
+
* @example Fold several partial overrides onto a resolver
|
|
883
|
+
* ```ts
|
|
884
|
+
* const resolver = Resolver.merge(defaultResolver, sharedNamingPatch, { name: (name) => name.toUpperCase() })
|
|
885
|
+
* ```
|
|
886
|
+
*/
|
|
887
|
+
static merge(base, ...overrides) {
|
|
888
|
+
const merged = overrides.reduce((acc, override) => {
|
|
889
|
+
const patch = resolverOptions in override ? override[resolverOptions] : override;
|
|
890
|
+
for (const [key, value] of Object.entries(patch)) {
|
|
891
|
+
if (value === void 0) continue;
|
|
892
|
+
const current = acc[key];
|
|
893
|
+
acc[key] = isNamespace(value) && isNamespace(current) ? {
|
|
894
|
+
...current,
|
|
895
|
+
...value
|
|
896
|
+
} : value;
|
|
897
|
+
}
|
|
898
|
+
return acc;
|
|
899
|
+
}, { ...base[resolverOptions] });
|
|
900
|
+
return new Resolver(merged);
|
|
901
|
+
}
|
|
902
|
+
/**
|
|
903
|
+
* Binds each entry of `options` onto the resolver, so `this.name`, `this.default`, and
|
|
904
|
+
* `this.file` resolve there for top-level helpers and namespace methods alike. `default`
|
|
905
|
+
* is skipped so it can't be shadowed.
|
|
906
|
+
*/
|
|
907
|
+
#apply(options) {
|
|
908
|
+
const root = this;
|
|
909
|
+
const bind = (value) => typeof value === "function" ? value.bind(root) : value;
|
|
910
|
+
for (const [key, value] of Object.entries(options)) {
|
|
911
|
+
if (key === "pluginName" || key === "default" || key === "file" || value === void 0) continue;
|
|
912
|
+
root[key] = isNamespace(value) ? Object.fromEntries(Object.entries(value).map(([method, member]) => [method, bind(member)])) : bind(value);
|
|
913
|
+
}
|
|
914
|
+
}
|
|
915
|
+
static #testPattern(value, pattern) {
|
|
916
|
+
if (typeof pattern === "string") {
|
|
917
|
+
let regex = Resolver.#patternCache.get(pattern);
|
|
918
|
+
regex ??= new RegExp(pattern);
|
|
919
|
+
Resolver.#patternCache.set(pattern, regex);
|
|
920
|
+
return regex.test(value);
|
|
921
|
+
}
|
|
922
|
+
return value.match(pattern) !== null;
|
|
923
|
+
}
|
|
924
|
+
static #matchesOperation(node, { type, pattern }) {
|
|
925
|
+
if (type === "tag") return node.tags.some((tag) => Resolver.#testPattern(tag, pattern));
|
|
926
|
+
if (type === "operationId") return Resolver.#testPattern(node.operationId, pattern);
|
|
927
|
+
if (type === "path") return node.path !== void 0 && Resolver.#testPattern(node.path, pattern);
|
|
928
|
+
if (type === "method") return node.method !== void 0 && Resolver.#testPattern(node.method.toLowerCase(), pattern);
|
|
929
|
+
if (type === "contentType") return node.requestBody?.content?.some((c) => Resolver.#testPattern(c.contentType, pattern)) ?? false;
|
|
930
|
+
return false;
|
|
931
|
+
}
|
|
932
|
+
/**
|
|
933
|
+
* Returns `null` when the filter type doesn't apply to schemas, so include rules built
|
|
934
|
+
* from operation filters (e.g. `tag`) don't exclude every schema.
|
|
935
|
+
*/
|
|
936
|
+
static #matchesSchema(node, { type, pattern }) {
|
|
937
|
+
if (type === "schemaName") return node.name ? Resolver.#testPattern(node.name, pattern) : false;
|
|
938
|
+
return null;
|
|
939
|
+
}
|
|
940
|
+
static #computeOptions(node, { options, exclude = [], include, override = [] }) {
|
|
941
|
+
if (_kubb_ast.operationDef.is(node)) {
|
|
942
|
+
if (exclude.some((filter) => Resolver.#matchesOperation(node, filter))) return null;
|
|
943
|
+
if (include && !include.some((filter) => Resolver.#matchesOperation(node, filter))) return null;
|
|
944
|
+
return {
|
|
945
|
+
...options,
|
|
946
|
+
...override.find((filter) => Resolver.#matchesOperation(node, filter))?.options
|
|
947
|
+
};
|
|
948
|
+
}
|
|
949
|
+
if (_kubb_ast.schemaDef.is(node)) {
|
|
950
|
+
if (exclude.some((filter) => Resolver.#matchesSchema(node, filter) === true)) return null;
|
|
951
|
+
if (include) {
|
|
952
|
+
const applicable = include.map((filter) => Resolver.#matchesSchema(node, filter)).filter((result) => result !== null);
|
|
953
|
+
if (applicable.length > 0 && !applicable.includes(true)) return null;
|
|
954
|
+
}
|
|
955
|
+
return {
|
|
956
|
+
...options,
|
|
957
|
+
...override.find((filter) => Resolver.#matchesSchema(node, filter) === true)?.options
|
|
958
|
+
};
|
|
553
959
|
}
|
|
554
|
-
|
|
555
|
-
}
|
|
556
|
-
|
|
557
|
-
|
|
558
|
-
|
|
559
|
-
|
|
560
|
-
|
|
561
|
-
|
|
562
|
-
return
|
|
563
|
-
|
|
564
|
-
|
|
565
|
-
|
|
566
|
-
|
|
567
|
-
}
|
|
568
|
-
clear() {
|
|
569
|
-
this.#head = void 0;
|
|
570
|
-
this.#tail = void 0;
|
|
571
|
-
this.#size = 0;
|
|
572
|
-
}
|
|
573
|
-
get size() {
|
|
574
|
-
return this.#size;
|
|
575
|
-
}
|
|
576
|
-
*[Symbol.iterator]() {
|
|
577
|
-
let current = this.#head;
|
|
578
|
-
while (current) {
|
|
579
|
-
yield current.value;
|
|
580
|
-
current = current.next;
|
|
960
|
+
return options;
|
|
961
|
+
}
|
|
962
|
+
/**
|
|
963
|
+
* Applies include/exclude filters and merges matching override options, caching the result
|
|
964
|
+
* per `(options, node)` pair. Returns `null` when the node is filtered out.
|
|
965
|
+
*/
|
|
966
|
+
#resolveOptions(node, context) {
|
|
967
|
+
const { options } = context;
|
|
968
|
+
if (typeof options !== "object" || options === null) return Resolver.#computeOptions(node, context);
|
|
969
|
+
let byOptions = Resolver.#optionsCache.get(options);
|
|
970
|
+
if (!byOptions) {
|
|
971
|
+
byOptions = /* @__PURE__ */ new WeakMap();
|
|
972
|
+
Resolver.#optionsCache.set(options, byOptions);
|
|
581
973
|
}
|
|
974
|
+
const cached = byOptions.get(node);
|
|
975
|
+
if (cached) return cached.value;
|
|
976
|
+
const result = Resolver.#computeOptions(node, context);
|
|
977
|
+
byOptions.set(node, { value: result });
|
|
978
|
+
return result;
|
|
979
|
+
}
|
|
980
|
+
/**
|
|
981
|
+
* A custom `group.name` wins; otherwise `tag` groups use the camelCased tag and `path`
|
|
982
|
+
* groups use the first non-traversal segment (`''` when none remain, placing the file in
|
|
983
|
+
* the output root, kept safe by the caller's boundary check).
|
|
984
|
+
*/
|
|
985
|
+
static #resolveGroupDir(group, groupValue) {
|
|
986
|
+
if (group.name) return group.name({ group: groupValue });
|
|
987
|
+
if (group.type === "tag") return require_usingCtx.camelCase(groupValue);
|
|
988
|
+
const segment = groupValue.split("/").filter((part) => part !== "" && part !== "." && part !== "..")[0];
|
|
989
|
+
return segment ? require_usingCtx.camelCase(segment) : "";
|
|
582
990
|
}
|
|
583
|
-
|
|
584
|
-
|
|
991
|
+
/**
|
|
992
|
+
* `mode: 'file'` (default) resolves directly to `output.path`. `mode: 'directory'` resolves
|
|
993
|
+
* to `output.path/{baseName}`, or into a subdirectory when `group` and a `tag`/`path` value
|
|
994
|
+
* are provided.
|
|
995
|
+
*/
|
|
996
|
+
#resolvePath({ baseName, tag, path: groupPath, root, output, group }) {
|
|
997
|
+
if (output.mode !== "directory") return node_path.default.resolve(root, output.path);
|
|
998
|
+
const outputDir = node_path.default.resolve(root, output.path);
|
|
999
|
+
const result = group && (groupPath || tag) ? node_path.default.resolve(outputDir, Resolver.#resolveGroupDir(group, group.type === "path" ? groupPath : tag), baseName) : node_path.default.resolve(outputDir, baseName);
|
|
1000
|
+
const outputDirWithSep = outputDir.endsWith(node_path.default.sep) ? outputDir : `${outputDir}${node_path.default.sep}`;
|
|
1001
|
+
if (result !== outputDir && !result.startsWith(outputDirWithSep)) throw new Diagnostics.Error({
|
|
1002
|
+
code: Diagnostics.code.pathTraversal,
|
|
1003
|
+
severity: "error",
|
|
1004
|
+
message: `Resolved path "${result}" is outside the output directory "${outputDir}".`,
|
|
1005
|
+
help: "This can stem from a path traversal in the OpenAPI specification or a misconfigured `group.name` function. Keep generated paths within the output directory.",
|
|
1006
|
+
location: { kind: "config" }
|
|
1007
|
+
});
|
|
1008
|
+
return result;
|
|
1009
|
+
}
|
|
1010
|
+
/**
|
|
1011
|
+
* Resolves a resolver-supplied full path (`file.path`) against `root`, bypassing `output.path`
|
|
1012
|
+
* and `group`. The path may not escape `root`, which keeps a `file.path` that interpolates
|
|
1013
|
+
* spec-derived values from writing outside the project.
|
|
1014
|
+
*/
|
|
1015
|
+
#resolveOverridePath(filePath, root) {
|
|
1016
|
+
const resolved = node_path.default.resolve(root, filePath);
|
|
1017
|
+
const rootWithSep = root.endsWith(node_path.default.sep) ? root : `${root}${node_path.default.sep}`;
|
|
1018
|
+
if (resolved !== root && !resolved.startsWith(rootWithSep)) throw new Diagnostics.Error({
|
|
1019
|
+
code: Diagnostics.code.pathTraversal,
|
|
1020
|
+
severity: "error",
|
|
1021
|
+
message: `Resolved path "${resolved}" is outside the project root "${root}".`,
|
|
1022
|
+
help: "A resolver `file.path` must return a path inside the project root.",
|
|
1023
|
+
location: { kind: "config" }
|
|
1024
|
+
});
|
|
1025
|
+
return resolved;
|
|
1026
|
+
}
|
|
1027
|
+
/**
|
|
1028
|
+
* Builds a `FileNode`. When `#filePath` (the resolver's `file.path`) is set it owns the whole
|
|
1029
|
+
* path; otherwise the base name (from `#baseName`, the resolver's `file.baseName` or the
|
|
1030
|
+
* built-in `toBaseName`) is placed by the `output.path`/`group` layout. The resolved file starts
|
|
1031
|
+
* with empty `sources`, `imports`, and `exports`, which consumers populate separately.
|
|
1032
|
+
*/
|
|
1033
|
+
#resolveFile(options) {
|
|
1034
|
+
const { name, extname, tag, path: groupPath, root, output, group } = options;
|
|
1035
|
+
const baseName = this.#baseName({
|
|
1036
|
+
name,
|
|
1037
|
+
extname
|
|
1038
|
+
});
|
|
1039
|
+
const filePath = this.#filePath ? this.#resolveOverridePath(this.#filePath({
|
|
1040
|
+
baseName,
|
|
1041
|
+
output
|
|
1042
|
+
}), root) : this.#resolvePath({
|
|
1043
|
+
baseName,
|
|
1044
|
+
tag,
|
|
1045
|
+
path: groupPath,
|
|
1046
|
+
root,
|
|
1047
|
+
output,
|
|
1048
|
+
group
|
|
1049
|
+
});
|
|
1050
|
+
return _kubb_ast.ast.factory.createFile({
|
|
1051
|
+
path: filePath,
|
|
1052
|
+
baseName: node_path.default.basename(filePath),
|
|
1053
|
+
meta: { pluginName: this.pluginName },
|
|
1054
|
+
sources: [],
|
|
1055
|
+
imports: [],
|
|
1056
|
+
exports: []
|
|
1057
|
+
});
|
|
1058
|
+
}
|
|
1059
|
+
/**
|
|
1060
|
+
* Missing fields default to empty/`false` so the `BannerMeta` shape stays stable even when
|
|
1061
|
+
* a caller (e.g. the barrel plugin) has no document metadata.
|
|
1062
|
+
*/
|
|
1063
|
+
static #buildBannerMeta(meta, file) {
|
|
1064
|
+
return {
|
|
1065
|
+
title: meta?.title,
|
|
1066
|
+
description: meta?.description,
|
|
1067
|
+
version: meta?.version,
|
|
1068
|
+
baseURL: meta?.baseURL,
|
|
1069
|
+
circularNames: meta?.circularNames ?? [],
|
|
1070
|
+
enumNames: meta?.enumNames ?? [],
|
|
1071
|
+
filePath: file?.path ?? "",
|
|
1072
|
+
baseName: file?.baseName ?? "",
|
|
1073
|
+
isBarrel: file?.isBarrel ?? false,
|
|
1074
|
+
isAggregation: file?.isAggregation ?? false
|
|
1075
|
+
};
|
|
1076
|
+
}
|
|
1077
|
+
/**
|
|
1078
|
+
* Resolves a user-configured banner/footer value. `undefined` means not configured.
|
|
1079
|
+
*/
|
|
1080
|
+
static #resolveUserText(value, meta, file) {
|
|
1081
|
+
if (typeof value === "function") return value(Resolver.#buildBannerMeta(meta, file));
|
|
1082
|
+
if (typeof value === "string") return value;
|
|
1083
|
+
}
|
|
1084
|
+
static #buildDefaultBanner({ title, version, config }) {
|
|
1085
|
+
const lines = [
|
|
1086
|
+
"/**",
|
|
1087
|
+
"* Generated by Kubb (https://kubb.dev/).",
|
|
1088
|
+
"* Do not edit manually."
|
|
1089
|
+
];
|
|
1090
|
+
if (config.output.defaultBanner !== "simple") {
|
|
1091
|
+
const input = config.input;
|
|
1092
|
+
let source = "";
|
|
1093
|
+
if (typeof input === "string") source = getInputKind(input) === "inline" ? "text content" : node_path.default.basename(input);
|
|
1094
|
+
else if (input) source = "text content";
|
|
1095
|
+
if (source) lines.push(`* Source: ${source}`);
|
|
1096
|
+
if (title) lines.push(`* Title: ${title}`);
|
|
1097
|
+
if (version) lines.push(`* OpenAPI spec version: ${version}`);
|
|
1098
|
+
}
|
|
1099
|
+
return `${lines.join("\n")}\n*/\n`;
|
|
1100
|
+
}
|
|
1101
|
+
/**
|
|
1102
|
+
* A user-supplied `output.banner` overrides the default Kubb notice. When
|
|
1103
|
+
* `config.output.defaultBanner` is `false` and no user banner is set, returns `null`.
|
|
1104
|
+
*/
|
|
1105
|
+
#resolveBanner(meta, { output, config, file }) {
|
|
1106
|
+
const userBanner = Resolver.#resolveUserText(output?.banner, meta, file);
|
|
1107
|
+
if (userBanner !== void 0) return userBanner;
|
|
1108
|
+
if (config.output.defaultBanner === false) return null;
|
|
1109
|
+
return Resolver.#buildDefaultBanner({
|
|
1110
|
+
title: meta?.title,
|
|
1111
|
+
version: meta?.version,
|
|
1112
|
+
config
|
|
1113
|
+
});
|
|
1114
|
+
}
|
|
1115
|
+
#resolveFooter(meta, { output, file }) {
|
|
1116
|
+
return Resolver.#resolveUserText(output?.footer, meta, file) ?? null;
|
|
585
1117
|
}
|
|
586
1118
|
};
|
|
587
1119
|
//#endregion
|
|
588
|
-
//#region
|
|
589
|
-
|
|
590
|
-
|
|
591
|
-
|
|
592
|
-
|
|
593
|
-
|
|
594
|
-
|
|
595
|
-
|
|
596
|
-
|
|
597
|
-
|
|
598
|
-
|
|
599
|
-
|
|
1120
|
+
//#region src/createResolver.ts
|
|
1121
|
+
/**
|
|
1122
|
+
* Defines a plugin resolver, the object that decides what every generated symbol and file
|
|
1123
|
+
* path is called. Override the top-level `name` and `file` to set the plugin's conventions,
|
|
1124
|
+
* and add your own naming helpers, top-level (`typeName`, …) or grouped in namespaces
|
|
1125
|
+
* (`query`, `schema`, …). Every method reaches sibling helpers and the built-in machinery
|
|
1126
|
+
* through `this.name`, `this.file`, and `this.default`.
|
|
1127
|
+
*
|
|
1128
|
+
* @example Custom identifier casing
|
|
1129
|
+
* ```ts
|
|
1130
|
+
* export const resolverTs = createResolver<PluginTs>({
|
|
1131
|
+
* pluginName: 'plugin-ts',
|
|
1132
|
+
* name(name) {
|
|
1133
|
+
* return ensureValidVarName(pascalCase(name))
|
|
1134
|
+
* },
|
|
1135
|
+
* })
|
|
1136
|
+
* ```
|
|
1137
|
+
*
|
|
1138
|
+
* @example Rename generated files with `file.baseName`
|
|
1139
|
+
* ```ts
|
|
1140
|
+
* export const resolverFaker = createResolver<PluginFaker>({
|
|
1141
|
+
* pluginName: 'plugin-faker',
|
|
1142
|
+
* name(name) {
|
|
1143
|
+
* return camelCase(name, { prefix: 'create' })
|
|
1144
|
+
* },
|
|
1145
|
+
* file: {
|
|
1146
|
+
* baseName({ name, extname }) {
|
|
1147
|
+
* return `${camelCase(name, { prefix: 'create' })}${extname}`
|
|
1148
|
+
* },
|
|
1149
|
+
* },
|
|
1150
|
+
* })
|
|
1151
|
+
* ```
|
|
1152
|
+
*
|
|
1153
|
+
* @example Own the full path with `file.path`
|
|
1154
|
+
* ```ts
|
|
1155
|
+
* export const resolverFaker = createResolver<PluginFaker>({
|
|
1156
|
+
* pluginName: 'plugin-faker',
|
|
1157
|
+
* file: {
|
|
1158
|
+
* path({ baseName, output }) {
|
|
1159
|
+
* return `${output.path}/mocks/${baseName}`
|
|
1160
|
+
* },
|
|
1161
|
+
* },
|
|
1162
|
+
* })
|
|
1163
|
+
* ```
|
|
1164
|
+
*/
|
|
1165
|
+
function createResolver(options) {
|
|
1166
|
+
return new Resolver(options);
|
|
1167
|
+
}
|
|
1168
|
+
//#endregion
|
|
1169
|
+
//#region src/Transform.ts
|
|
1170
|
+
/**
|
|
1171
|
+
* Holds an ordered list of macros per plugin, keyed by plugin name. Each plugin's macros run in
|
|
1172
|
+
* isolation on the original adapter node and are composed into a single `Visitor` that the
|
|
1173
|
+
* `@kubb/ast` `transform` primitive applies. `applyTo` is a per-plugin lookup, not a cross-plugin
|
|
1174
|
+
* chain, so plugin A's macros never see plugin B's output. When a plugin has no macros, `applyTo`
|
|
1175
|
+
* returns the original node reference, and `transform` does the same when the composed visitor
|
|
1176
|
+
* leaves the tree untouched, so callers can detect a no-op by identity.
|
|
1177
|
+
*
|
|
1178
|
+
* Registration order matches the order setup hooks fire, which the driver has already sorted by
|
|
1179
|
+
* `enforce` and dependency edges. The registry preserves that order. Macro `enforce` only reorders
|
|
1180
|
+
* within a single plugin's list.
|
|
1181
|
+
*/
|
|
1182
|
+
var Transform = class {
|
|
1183
|
+
#macros = /* @__PURE__ */ new Map();
|
|
1184
|
+
#composed = /* @__PURE__ */ new Map();
|
|
1185
|
+
#memo = /* @__PURE__ */ new Map();
|
|
1186
|
+
/**
|
|
1187
|
+
* Appends `macro` to the plugin's list, after any macros already registered.
|
|
1188
|
+
*/
|
|
1189
|
+
add(pluginName, macro) {
|
|
1190
|
+
const list = this.#macros.get(pluginName);
|
|
1191
|
+
if (list) list.push(macro);
|
|
1192
|
+
else this.#macros.set(pluginName, [macro]);
|
|
1193
|
+
this.#invalidate(pluginName);
|
|
1194
|
+
}
|
|
1195
|
+
/**
|
|
1196
|
+
* Replaces the plugin's macro list with `macros`.
|
|
1197
|
+
*/
|
|
1198
|
+
set(pluginName, macros) {
|
|
1199
|
+
this.#macros.set(pluginName, [...macros]);
|
|
1200
|
+
this.#invalidate(pluginName);
|
|
1201
|
+
}
|
|
1202
|
+
/**
|
|
1203
|
+
* Runs the plugin's macros on `node`. Returns the original node reference when the plugin has no
|
|
1204
|
+
* macros, so callers can compare by identity to detect a no-op.
|
|
1205
|
+
*/
|
|
1206
|
+
applyTo(pluginName, node) {
|
|
1207
|
+
const visitor = this.#visitorFor(pluginName);
|
|
1208
|
+
if (!visitor) return node;
|
|
1209
|
+
let memo = this.#memo.get(pluginName);
|
|
1210
|
+
if (!memo) {
|
|
1211
|
+
memo = /* @__PURE__ */ new WeakMap();
|
|
1212
|
+
this.#memo.set(pluginName, memo);
|
|
600
1213
|
}
|
|
1214
|
+
const cached = memo.get(node);
|
|
1215
|
+
if (cached) return cached;
|
|
1216
|
+
const result = (0, _kubb_ast.transform)(node, visitor);
|
|
1217
|
+
memo.set(node, result);
|
|
1218
|
+
return result;
|
|
1219
|
+
}
|
|
1220
|
+
/**
|
|
1221
|
+
* Clears every registration. Called from the driver's `dispose()` so macros do not leak across
|
|
1222
|
+
* builds.
|
|
1223
|
+
*/
|
|
1224
|
+
dispose() {
|
|
1225
|
+
this.#macros.clear();
|
|
1226
|
+
this.#composed.clear();
|
|
1227
|
+
this.#memo.clear();
|
|
1228
|
+
}
|
|
1229
|
+
#invalidate(pluginName) {
|
|
1230
|
+
this.#composed.delete(pluginName);
|
|
1231
|
+
this.#memo.delete(pluginName);
|
|
1232
|
+
}
|
|
1233
|
+
#visitorFor(pluginName) {
|
|
1234
|
+
const macros = this.#macros.get(pluginName);
|
|
1235
|
+
if (!macros || macros.length === 0) return void 0;
|
|
1236
|
+
let composed = this.#composed.get(pluginName);
|
|
1237
|
+
if (!composed) {
|
|
1238
|
+
composed = (0, _kubb_ast.composeMacros)(macros);
|
|
1239
|
+
this.#composed.set(pluginName, composed);
|
|
1240
|
+
}
|
|
1241
|
+
return composed;
|
|
1242
|
+
}
|
|
1243
|
+
};
|
|
1244
|
+
//#endregion
|
|
1245
|
+
//#region src/KubbDriver.ts
|
|
1246
|
+
const ENFORCE_ORDER = {
|
|
1247
|
+
pre: -1,
|
|
1248
|
+
post: 1
|
|
1249
|
+
};
|
|
1250
|
+
const enforceWeight = (plugin) => plugin.enforce ? ENFORCE_ORDER[plugin.enforce] : 0;
|
|
1251
|
+
/**
|
|
1252
|
+
* The options bag a `NormalizedPlugin` starts with before a plugin refines it: a directory output
|
|
1253
|
+
* at the plugin root and empty filter lists.
|
|
1254
|
+
*/
|
|
1255
|
+
function defaultPluginOptions() {
|
|
1256
|
+
return {
|
|
1257
|
+
output: {
|
|
1258
|
+
path: ".",
|
|
1259
|
+
mode: "directory"
|
|
1260
|
+
},
|
|
1261
|
+
exclude: [],
|
|
1262
|
+
override: []
|
|
601
1263
|
};
|
|
602
|
-
|
|
603
|
-
|
|
604
|
-
|
|
605
|
-
|
|
606
|
-
|
|
607
|
-
|
|
608
|
-
|
|
609
|
-
|
|
610
|
-
|
|
611
|
-
|
|
612
|
-
next();
|
|
613
|
-
};
|
|
614
|
-
const enqueue = (function_, resolve, reject, arguments_) => {
|
|
615
|
-
const queueItem = { reject };
|
|
616
|
-
new Promise((internalResolve) => {
|
|
617
|
-
queueItem.run = internalResolve;
|
|
618
|
-
queue.enqueue(queueItem);
|
|
619
|
-
}).then(run.bind(void 0, function_, resolve, arguments_));
|
|
620
|
-
if (activeCount < concurrency) resumeNext();
|
|
1264
|
+
}
|
|
1265
|
+
/**
|
|
1266
|
+
* Fills in the `output`, `exclude`, and `override` a `NormalizedPlugin` needs from a plugin's raw
|
|
1267
|
+
* options, running `output` through `normalizeOutput`. Idempotent, so the driver can apply it after
|
|
1268
|
+
* `setOptions` has already run without disturbing an already-normalized bag.
|
|
1269
|
+
*/
|
|
1270
|
+
function normalizePluginOptions(rawOptions, pluginName) {
|
|
1271
|
+
const options = {
|
|
1272
|
+
...defaultPluginOptions(),
|
|
1273
|
+
...rawOptions ?? {}
|
|
621
1274
|
};
|
|
622
|
-
const
|
|
623
|
-
|
|
1275
|
+
const group = "group" in options ? options.group : void 0;
|
|
1276
|
+
options.output = normalizeOutput({
|
|
1277
|
+
output: options.output,
|
|
1278
|
+
group,
|
|
1279
|
+
pluginName
|
|
624
1280
|
});
|
|
625
|
-
|
|
626
|
-
|
|
627
|
-
|
|
628
|
-
|
|
629
|
-
|
|
630
|
-
|
|
631
|
-
|
|
1281
|
+
return options;
|
|
1282
|
+
}
|
|
1283
|
+
var KubbDriver = class {
|
|
1284
|
+
config;
|
|
1285
|
+
options;
|
|
1286
|
+
/**
|
|
1287
|
+
* The `InputNode` produced by the adapter. Set after adapter setup.
|
|
1288
|
+
*/
|
|
1289
|
+
inputNode = null;
|
|
1290
|
+
adapter = null;
|
|
1291
|
+
/**
|
|
1292
|
+
* Raw adapter source so `adapter.parse()` can run lazily.
|
|
1293
|
+
* Intentionally outlives the build, cleared by `dispose()`.
|
|
1294
|
+
*/
|
|
1295
|
+
#adapterSource = null;
|
|
1296
|
+
/**
|
|
1297
|
+
* Central file store for all generated files.
|
|
1298
|
+
* Plugins should use `this.addFile()` / `this.upsertFile()` (via their context) to
|
|
1299
|
+
* add files. This property gives direct read/write access when needed.
|
|
1300
|
+
*/
|
|
1301
|
+
fileManager = new require_usingCtx.FileManager();
|
|
1302
|
+
plugins = /* @__PURE__ */ new Map();
|
|
1303
|
+
/**
|
|
1304
|
+
* Removers for every listener the driver added (plugin, generator) so `dispose()` can detach
|
|
1305
|
+
* them in one pass. External `hooks.hook(...)` listeners are not tracked.
|
|
1306
|
+
*/
|
|
1307
|
+
#unhooks = [];
|
|
1308
|
+
/**
|
|
1309
|
+
* Transform registry. Plugins populate it during `kubb:plugin:setup` via `addMacro`/`setMacros`,
|
|
1310
|
+
* and `#runGenerators` reads it once per `(plugin, node)` pair through `applyTo`.
|
|
1311
|
+
*/
|
|
1312
|
+
#transforms = new Transform();
|
|
1313
|
+
constructor(config, options) {
|
|
1314
|
+
this.config = config;
|
|
1315
|
+
this.options = options;
|
|
1316
|
+
this.adapter = config.adapter ?? null;
|
|
1317
|
+
}
|
|
1318
|
+
/**
|
|
1319
|
+
* Normalizes every configured plugin, orders them, and registers their lifecycle handlers.
|
|
1320
|
+
* A plugin that another lists as a dependency runs first, then `enforce: 'pre'` before
|
|
1321
|
+
* `'post'`. When the config has an adapter, the adapter source is resolved from the input
|
|
1322
|
+
* so `run` can parse it later.
|
|
1323
|
+
*/
|
|
1324
|
+
async setup() {
|
|
1325
|
+
const normalized = this.#sortPlugins(this.config.plugins.map((rawPlugin) => {
|
|
1326
|
+
return {
|
|
1327
|
+
name: rawPlugin.name,
|
|
1328
|
+
dependencies: rawPlugin.dependencies,
|
|
1329
|
+
enforce: rawPlugin.enforce,
|
|
1330
|
+
hooks: rawPlugin.hooks,
|
|
1331
|
+
options: rawPlugin.options ?? defaultPluginOptions(),
|
|
1332
|
+
resolver: createResolver({ pluginName: rawPlugin.name })
|
|
1333
|
+
};
|
|
1334
|
+
}));
|
|
1335
|
+
for (const plugin of normalized) {
|
|
1336
|
+
this.#registerPlugin(plugin);
|
|
1337
|
+
this.plugins.set(plugin.name, plugin);
|
|
1338
|
+
}
|
|
1339
|
+
if (this.config.adapter) this.#adapterSource = inputToAdapterSource(this.config);
|
|
1340
|
+
}
|
|
1341
|
+
/**
|
|
1342
|
+
* Orders plugins so every dependency runs before its dependents (Kahn's algorithm), with
|
|
1343
|
+
* `enforce` (`'pre'` before normal before `'post'`) and declaration order as tiebreaks.
|
|
1344
|
+
* A pairwise `Array.sort` comparator cannot do this: dependency relations are not transitive
|
|
1345
|
+
* at the comparator level, so a chain where A depends on B and B depends on C could come out
|
|
1346
|
+
* wrong when A and C are never compared directly. Dependencies on plugins missing from the
|
|
1347
|
+
* config are ignored here and surface later through `requirePlugin`.
|
|
1348
|
+
*/
|
|
1349
|
+
#sortPlugins(plugins) {
|
|
1350
|
+
const queue = [...plugins].sort((a, b) => enforceWeight(a) - enforceWeight(b));
|
|
1351
|
+
const names = new Set(queue.map((plugin) => plugin.name));
|
|
1352
|
+
const blockedBy = new Map(queue.map((plugin) => [plugin.name, new Set(plugin.dependencies?.filter((name) => names.has(name) && name !== plugin.name))]));
|
|
1353
|
+
const sorted = [];
|
|
1354
|
+
for (const _ of plugins) {
|
|
1355
|
+
const index = queue.findIndex((plugin) => blockedBy.get(plugin.name)?.size === 0);
|
|
1356
|
+
if (index === -1) throw new Diagnostics.Error({
|
|
1357
|
+
code: Diagnostics.code.invalidPluginOptions,
|
|
1358
|
+
severity: "error",
|
|
1359
|
+
message: `Plugin dependencies form a cycle: ${queue.map((plugin) => plugin.name).join(" → ")}.`,
|
|
1360
|
+
help: "Remove one of the `dependencies` entries so the plugins can be ordered.",
|
|
1361
|
+
location: { kind: "config" }
|
|
1362
|
+
});
|
|
1363
|
+
const [plugin] = queue.splice(index, 1);
|
|
1364
|
+
if (!plugin) break;
|
|
1365
|
+
sorted.push(plugin);
|
|
1366
|
+
for (const blockers of blockedBy.values()) blockers.delete(plugin.name);
|
|
1367
|
+
}
|
|
1368
|
+
return sorted;
|
|
1369
|
+
}
|
|
1370
|
+
get hooks() {
|
|
1371
|
+
return this.options.hooks;
|
|
1372
|
+
}
|
|
1373
|
+
/**
|
|
1374
|
+
* Parses the adapter source into `this.inputNode`. Idempotent, so repeated calls from
|
|
1375
|
+
* `run` do not re-parse.
|
|
1376
|
+
*/
|
|
1377
|
+
async #parseInput() {
|
|
1378
|
+
if (this.inputNode || !this.adapter || !this.#adapterSource) return;
|
|
1379
|
+
this.inputNode = await this.adapter.parse(this.#adapterSource);
|
|
1380
|
+
}
|
|
1381
|
+
/**
|
|
1382
|
+
* Registers a plugin's lifecycle hooks on the shared `Hookable` as pass-through listeners that
|
|
1383
|
+
* external tooling can observe via `hooks.hook(...)`. The returned remover is tracked for
|
|
1384
|
+
* `dispose`. `kubb:plugin:setup` is skipped here; `setupHooks` invokes it directly with a
|
|
1385
|
+
* plugin-scoped context.
|
|
1386
|
+
*
|
|
1387
|
+
* @internal
|
|
1388
|
+
*/
|
|
1389
|
+
#registerPlugin(plugin) {
|
|
1390
|
+
const { hooks } = plugin;
|
|
1391
|
+
if (!hooks) return;
|
|
1392
|
+
const { "kubb:plugin:setup": _setup, ...configHooks } = hooks;
|
|
1393
|
+
this.#unhooks.push(this.hooks.addHooks(configHooks));
|
|
1394
|
+
}
|
|
1395
|
+
/**
|
|
1396
|
+
* Runs each plugin's `kubb:plugin:setup` handler, in plugin order, with a context scoped to that
|
|
1397
|
+
* plugin so `addGenerator`, `setResolver`, `addMacro`, `setMacros`, and `setOptions` target its
|
|
1398
|
+
* `NormalizedPlugin` entry. Called once from `run` before the plugin execution loop begins, so
|
|
1399
|
+
* plugins can configure generators, resolvers, macros, and options before `buildStart`.
|
|
1400
|
+
*/
|
|
1401
|
+
async setupHooks() {
|
|
1402
|
+
for (const plugin of this.plugins.values()) {
|
|
1403
|
+
const setup = plugin.hooks?.["kubb:plugin:setup"];
|
|
1404
|
+
if (!setup) continue;
|
|
1405
|
+
await setup({
|
|
1406
|
+
config: this.config,
|
|
1407
|
+
options: plugin.options ?? {},
|
|
1408
|
+
addGenerator: (...generators) => {
|
|
1409
|
+
for (const generator of generators) this.registerGenerator(plugin.name, generator);
|
|
1410
|
+
},
|
|
1411
|
+
setResolver: (resolver) => {
|
|
1412
|
+
this.setPluginResolver(plugin.name, resolver);
|
|
1413
|
+
},
|
|
1414
|
+
addMacro: (macro) => {
|
|
1415
|
+
this.#transforms.add(plugin.name, macro);
|
|
1416
|
+
},
|
|
1417
|
+
setMacros: (macros) => {
|
|
1418
|
+
this.#transforms.set(plugin.name, macros);
|
|
1419
|
+
},
|
|
1420
|
+
setOptions: (opts) => {
|
|
1421
|
+
plugin.options = {
|
|
1422
|
+
...plugin.options,
|
|
1423
|
+
...opts
|
|
1424
|
+
};
|
|
1425
|
+
if (plugin.options.output) {
|
|
1426
|
+
const group = "group" in plugin.options ? plugin.options.group : void 0;
|
|
1427
|
+
plugin.options.output = normalizeOutput({
|
|
1428
|
+
output: plugin.options.output,
|
|
1429
|
+
group,
|
|
1430
|
+
pluginName: plugin.name
|
|
1431
|
+
});
|
|
1432
|
+
}
|
|
1433
|
+
},
|
|
1434
|
+
injectFile: (userFileNode) => {
|
|
1435
|
+
this.fileManager.add(_kubb_ast.ast.factory.createFile(userFileNode));
|
|
1436
|
+
}
|
|
1437
|
+
});
|
|
1438
|
+
}
|
|
1439
|
+
}
|
|
1440
|
+
/**
|
|
1441
|
+
* Appends a generator to its owning plugin so the generate loop can call it directly.
|
|
1442
|
+
*
|
|
1443
|
+
* The generator's `schema`, `operation`, and `operations` methods run per node during the AST
|
|
1444
|
+
* walk in `#runGenerators`, and their result is routed through `dispatch`. Because a generator is
|
|
1445
|
+
* bound to a plugin, generators from different plugins never cross-fire without a name check. The
|
|
1446
|
+
* renderer comes from `generator.renderer`; set it to `null` (or leave it unset) to opt out of
|
|
1447
|
+
* rendering.
|
|
1448
|
+
*
|
|
1449
|
+
* Call this method inside `addGenerator()` (in `kubb:plugin:setup`) to wire up a generator.
|
|
1450
|
+
*/
|
|
1451
|
+
registerGenerator(pluginName, generator) {
|
|
1452
|
+
const plugin = this.plugins.get(pluginName);
|
|
1453
|
+
if (!plugin) return;
|
|
1454
|
+
plugin.generators = plugin.generators ? [...plugin.generators, generator] : [generator];
|
|
1455
|
+
}
|
|
1456
|
+
/**
|
|
1457
|
+
* Returns `true` when at least one generator was registered for the given plugin
|
|
1458
|
+
* via `addGenerator()` in `kubb:plugin:setup`.
|
|
1459
|
+
*
|
|
1460
|
+
* Used by the build loop to decide whether to walk the AST and run the generators
|
|
1461
|
+
* for a plugin.
|
|
1462
|
+
*/
|
|
1463
|
+
hasHookGenerators(pluginName) {
|
|
1464
|
+
return (this.plugins.get(pluginName)?.generators?.length ?? 0) > 0;
|
|
1465
|
+
}
|
|
1466
|
+
/**
|
|
1467
|
+
* Runs the full plugin pipeline. Returns the diagnostics collected so far even
|
|
1468
|
+
* when an outer hook throws, since the orchestrator preserves partial state by capturing
|
|
1469
|
+
* the failure as a {@link Diagnostic} instead of propagating. Each plugin also
|
|
1470
|
+
* contributes a `timing` diagnostic for the run summary.
|
|
1471
|
+
*/
|
|
1472
|
+
async run() {
|
|
1473
|
+
const { hooks, config, fileManager } = this;
|
|
1474
|
+
const diagnostics = [];
|
|
1475
|
+
const updateBuffer = [];
|
|
1476
|
+
const parsersMap = /* @__PURE__ */ new Map();
|
|
1477
|
+
for (const parser of config.parsers) if (parser.extNames) for (const ext of parser.extNames) parsersMap.set(ext, parser);
|
|
1478
|
+
const unhookWrites = fileManager.hooks.addHooks({
|
|
1479
|
+
start: async (files) => {
|
|
1480
|
+
await hooks.callHook("kubb:files:processing:start", { files });
|
|
1481
|
+
},
|
|
1482
|
+
update: (item) => {
|
|
1483
|
+
updateBuffer.push(item);
|
|
1484
|
+
},
|
|
1485
|
+
end: async (files) => {
|
|
1486
|
+
await hooks.callHook("kubb:files:processing:update", { files: updateBuffer.map((item) => ({
|
|
1487
|
+
...item,
|
|
1488
|
+
config
|
|
1489
|
+
})) });
|
|
1490
|
+
updateBuffer.length = 0;
|
|
1491
|
+
await hooks.callHook("kubb:files:processing:end", { files });
|
|
632
1492
|
}
|
|
633
|
-
|
|
634
|
-
|
|
635
|
-
|
|
636
|
-
|
|
637
|
-
|
|
638
|
-
|
|
639
|
-
|
|
640
|
-
|
|
641
|
-
|
|
642
|
-
|
|
1493
|
+
});
|
|
1494
|
+
return Diagnostics.scope((diagnostic) => diagnostics.push(diagnostic), async () => {
|
|
1495
|
+
try {
|
|
1496
|
+
const outputRoot = (0, node_path.resolve)(config.root, config.output.path);
|
|
1497
|
+
await this.#parseInput();
|
|
1498
|
+
await this.setupHooks();
|
|
1499
|
+
for (const plugin of this.plugins.values()) plugin.options = normalizePluginOptions(plugin.options, plugin.name);
|
|
1500
|
+
if (this.adapter && this.inputNode) {
|
|
1501
|
+
const buildStartContext = this.#withFiles({
|
|
1502
|
+
config,
|
|
1503
|
+
adapter: this.adapter,
|
|
1504
|
+
meta: this.inputNode.meta,
|
|
1505
|
+
getPlugin: this.getPlugin.bind(this)
|
|
1506
|
+
});
|
|
1507
|
+
await hooks.callHook("kubb:build:start", buildStartContext);
|
|
1508
|
+
}
|
|
1509
|
+
const generatorPlugins = [];
|
|
1510
|
+
for (const plugin of this.plugins.values()) {
|
|
1511
|
+
const context = this.getContext(plugin);
|
|
1512
|
+
const hrStart = process.hrtime();
|
|
1513
|
+
try {
|
|
1514
|
+
await hooks.callHook("kubb:plugin:start", { plugin });
|
|
1515
|
+
} catch (caughtError) {
|
|
1516
|
+
const error = require_usingCtx.toError(caughtError);
|
|
1517
|
+
const duration = getElapsedMs(hrStart);
|
|
1518
|
+
await this.#emitPluginEnd({
|
|
1519
|
+
plugin,
|
|
1520
|
+
duration,
|
|
1521
|
+
success: false,
|
|
1522
|
+
error
|
|
1523
|
+
});
|
|
1524
|
+
diagnostics.push({
|
|
1525
|
+
...Diagnostics.from(error),
|
|
1526
|
+
plugin: plugin.name
|
|
1527
|
+
}, Diagnostics.performance({
|
|
1528
|
+
plugin: plugin.name,
|
|
1529
|
+
duration
|
|
1530
|
+
}));
|
|
1531
|
+
continue;
|
|
1532
|
+
}
|
|
1533
|
+
if (this.hasHookGenerators(plugin.name)) {
|
|
1534
|
+
generatorPlugins.push({
|
|
1535
|
+
plugin,
|
|
1536
|
+
context,
|
|
1537
|
+
hrStart
|
|
1538
|
+
});
|
|
1539
|
+
continue;
|
|
1540
|
+
}
|
|
1541
|
+
const duration = getElapsedMs(hrStart);
|
|
1542
|
+
diagnostics.push(Diagnostics.performance({
|
|
1543
|
+
plugin: plugin.name,
|
|
1544
|
+
duration
|
|
1545
|
+
}));
|
|
1546
|
+
await this.#emitPluginEnd({
|
|
1547
|
+
plugin,
|
|
1548
|
+
duration,
|
|
1549
|
+
success: true
|
|
1550
|
+
});
|
|
1551
|
+
}
|
|
1552
|
+
diagnostics.push(...await this.#runGenerators(generatorPlugins));
|
|
1553
|
+
await hooks.callHook("kubb:plugins:end", this.#withFiles({ config }));
|
|
1554
|
+
await fileManager.write(fileManager.files, {
|
|
1555
|
+
storage: config.storage,
|
|
1556
|
+
parsers: parsersMap
|
|
1557
|
+
});
|
|
1558
|
+
await hooks.callHook("kubb:build:end", {
|
|
1559
|
+
files: this.fileManager.files,
|
|
1560
|
+
config,
|
|
1561
|
+
outputDir: outputRoot
|
|
643
1562
|
});
|
|
1563
|
+
return { diagnostics: Diagnostics.dedupe(diagnostics) };
|
|
1564
|
+
} catch (caughtError) {
|
|
1565
|
+
diagnostics.push(Diagnostics.from(caughtError));
|
|
1566
|
+
return { diagnostics: Diagnostics.dedupe(diagnostics) };
|
|
1567
|
+
} finally {
|
|
1568
|
+
unhookWrites();
|
|
644
1569
|
}
|
|
645
|
-
}
|
|
646
|
-
|
|
647
|
-
|
|
648
|
-
|
|
649
|
-
|
|
650
|
-
|
|
651
|
-
|
|
652
|
-
|
|
653
|
-
|
|
654
|
-
|
|
655
|
-
|
|
656
|
-
|
|
657
|
-
|
|
658
|
-
|
|
659
|
-
|
|
660
|
-
|
|
661
|
-
|
|
662
|
-
|
|
663
|
-
|
|
664
|
-
|
|
665
|
-
|
|
666
|
-
|
|
667
|
-
|
|
668
|
-
|
|
669
|
-
|
|
670
|
-
|
|
671
|
-
|
|
672
|
-
|
|
673
|
-
|
|
674
|
-
|
|
675
|
-
|
|
676
|
-
|
|
677
|
-
|
|
678
|
-
|
|
679
|
-
|
|
680
|
-
|
|
681
|
-
|
|
682
|
-
|
|
683
|
-
|
|
1570
|
+
});
|
|
1571
|
+
}
|
|
1572
|
+
/**
|
|
1573
|
+
* Widens `extra` with the files present at emit time and a bound `upsertFile`, the shape every
|
|
1574
|
+
* file-carrying hook context shares. Building it here in one place keeps the `files` and
|
|
1575
|
+
* `upsertFile` keys from being dropped by a stray spread at the call site.
|
|
1576
|
+
*/
|
|
1577
|
+
#withFiles(extra) {
|
|
1578
|
+
return {
|
|
1579
|
+
...extra,
|
|
1580
|
+
files: this.fileManager.files,
|
|
1581
|
+
upsertFile: (...files) => this.fileManager.upsert(...files)
|
|
1582
|
+
};
|
|
1583
|
+
}
|
|
1584
|
+
#emitPluginEnd({ plugin, duration, success, error }) {
|
|
1585
|
+
return this.hooks.callHook("kubb:plugin:end", this.#withFiles({
|
|
1586
|
+
plugin,
|
|
1587
|
+
duration,
|
|
1588
|
+
success,
|
|
1589
|
+
...error ? { error } : {},
|
|
1590
|
+
config: this.config
|
|
1591
|
+
}));
|
|
1592
|
+
}
|
|
1593
|
+
/**
|
|
1594
|
+
* Runs schemas and operations through every plugin's generators. Each node is run
|
|
1595
|
+
* through the plugin's macros (from `this.#transforms`) before the generator sees it,
|
|
1596
|
+
* so plugins stay isolated and the hot path stays per-node. Schemas run before operations
|
|
1597
|
+
* so file output stays deterministic across runs.
|
|
1598
|
+
* A failing plugin contributes an error diagnostic so the rest of the build continues.
|
|
1599
|
+
* Every plugin also contributes a `timing` diagnostic.
|
|
1600
|
+
*
|
|
1601
|
+
* Plugins are processed one at a time, in full, so `kubb:plugin:end` fires as each one
|
|
1602
|
+
* completes rather than all at once at the end. That ordering drives the CLI's
|
|
1603
|
+
* `Plugins N/M` counter.
|
|
1604
|
+
*
|
|
1605
|
+
* When `this.inputNode` is `null`, every entry still gets a `kubb:plugin:end` so
|
|
1606
|
+
* post-plugin listeners (the barrel writer and friends) complete.
|
|
1607
|
+
*/
|
|
1608
|
+
async #runGenerators(entries) {
|
|
1609
|
+
const diagnostics = [];
|
|
1610
|
+
if (entries.length === 0) return diagnostics;
|
|
1611
|
+
if (!this.inputNode) {
|
|
1612
|
+
for (const { plugin, hrStart } of entries) {
|
|
1613
|
+
const duration = getElapsedMs(hrStart);
|
|
1614
|
+
diagnostics.push(Diagnostics.performance({
|
|
1615
|
+
plugin: plugin.name,
|
|
1616
|
+
duration
|
|
1617
|
+
}));
|
|
1618
|
+
await this.#emitPluginEnd({
|
|
1619
|
+
plugin,
|
|
1620
|
+
duration,
|
|
1621
|
+
success: true
|
|
1622
|
+
});
|
|
1623
|
+
}
|
|
1624
|
+
return diagnostics;
|
|
1625
|
+
}
|
|
1626
|
+
const transforms = this.#transforms;
|
|
1627
|
+
const { schemas, operations } = this.inputNode;
|
|
1628
|
+
const allowedSchemaNamesByPlugin = /* @__PURE__ */ new Map();
|
|
1629
|
+
for (const { plugin } of entries) {
|
|
1630
|
+
const { exclude, include, override } = plugin.options;
|
|
1631
|
+
if (!((include?.some(({ type }) => OPERATION_FILTER_TYPES.has(type)) ?? false) && !(include?.some(({ type }) => type === "schemaName") ?? false))) continue;
|
|
1632
|
+
const resolver = this.getResolver(plugin.name);
|
|
1633
|
+
const includedOps = operations.filter((operation) => resolver.default.options(operation, {
|
|
1634
|
+
options: plugin.options,
|
|
1635
|
+
exclude,
|
|
1636
|
+
include,
|
|
1637
|
+
override
|
|
1638
|
+
}) !== null);
|
|
1639
|
+
allowedSchemaNamesByPlugin.set(plugin.name, (0, _kubb_ast.collectUsedSchemaNames)(includedOps, schemas));
|
|
1640
|
+
}
|
|
1641
|
+
for (const { plugin, context, hrStart } of entries) {
|
|
1642
|
+
const generatorContext = {
|
|
1643
|
+
...context,
|
|
1644
|
+
resolver: this.getResolver(plugin.name)
|
|
1645
|
+
};
|
|
1646
|
+
const { exclude, include, override } = plugin.options;
|
|
1647
|
+
const optionsAreStatic = !exclude?.length && !include?.length && !override?.length;
|
|
1648
|
+
const allowedSchemaNames = allowedSchemaNamesByPlugin.get(plugin.name) ?? null;
|
|
1649
|
+
const generators = plugin.generators ?? [];
|
|
1650
|
+
const schemaGenerators = generators.filter((generator) => generator.schema);
|
|
1651
|
+
const operationGenerators = generators.filter((generator) => generator.operation);
|
|
1652
|
+
const operationsGenerators = generators.filter((generator) => generator.operations);
|
|
1653
|
+
let error = null;
|
|
1654
|
+
const resolveForPlugin = (node) => {
|
|
1655
|
+
const transformedNode = transforms.applyTo(plugin.name, node);
|
|
1656
|
+
if (optionsAreStatic) return {
|
|
1657
|
+
transformedNode,
|
|
1658
|
+
options: plugin.options
|
|
1659
|
+
};
|
|
1660
|
+
const options = generatorContext.resolver.default.options(transformedNode, {
|
|
1661
|
+
options: plugin.options,
|
|
1662
|
+
exclude,
|
|
1663
|
+
include,
|
|
1664
|
+
override
|
|
1665
|
+
});
|
|
1666
|
+
if (options === null) return null;
|
|
1667
|
+
return {
|
|
1668
|
+
transformedNode,
|
|
1669
|
+
options
|
|
1670
|
+
};
|
|
1671
|
+
};
|
|
1672
|
+
if (schemaGenerators.length) for (const node of schemas) {
|
|
1673
|
+
if (error) break;
|
|
1674
|
+
try {
|
|
1675
|
+
const resolved = resolveForPlugin(node);
|
|
1676
|
+
if (!resolved) continue;
|
|
1677
|
+
const { transformedNode, options } = resolved;
|
|
1678
|
+
if (allowedSchemaNames !== null && transformedNode.name && !allowedSchemaNames.has(transformedNode.name)) continue;
|
|
1679
|
+
const ctx = {
|
|
1680
|
+
...generatorContext,
|
|
1681
|
+
options
|
|
1682
|
+
};
|
|
1683
|
+
for (const generator of schemaGenerators) await this.dispatch({
|
|
1684
|
+
result: await generator.schema(transformedNode, ctx),
|
|
1685
|
+
renderer: generator.renderer
|
|
1686
|
+
});
|
|
1687
|
+
await this.hooks.callHook("kubb:generate:schema", transformedNode, ctx);
|
|
1688
|
+
} catch (caughtError) {
|
|
1689
|
+
error = require_usingCtx.toError(caughtError);
|
|
1690
|
+
}
|
|
1691
|
+
}
|
|
1692
|
+
const pluginOperations = [];
|
|
1693
|
+
if (operationGenerators.length || operationsGenerators.length) for (const node of operations) {
|
|
1694
|
+
if (error) break;
|
|
1695
|
+
try {
|
|
1696
|
+
const resolved = resolveForPlugin(node);
|
|
1697
|
+
if (!resolved) continue;
|
|
1698
|
+
pluginOperations.push(resolved.transformedNode);
|
|
1699
|
+
if (operationGenerators.length) {
|
|
1700
|
+
const ctx = {
|
|
1701
|
+
...generatorContext,
|
|
1702
|
+
options: resolved.options
|
|
1703
|
+
};
|
|
1704
|
+
for (const generator of operationGenerators) await this.dispatch({
|
|
1705
|
+
result: await generator.operation(resolved.transformedNode, ctx),
|
|
1706
|
+
renderer: generator.renderer
|
|
1707
|
+
});
|
|
1708
|
+
await this.hooks.callHook("kubb:generate:operation", resolved.transformedNode, ctx);
|
|
1709
|
+
}
|
|
1710
|
+
} catch (caughtError) {
|
|
1711
|
+
error = require_usingCtx.toError(caughtError);
|
|
1712
|
+
}
|
|
1713
|
+
}
|
|
1714
|
+
if (!error && operationsGenerators.length) try {
|
|
1715
|
+
const ctx = {
|
|
1716
|
+
...generatorContext,
|
|
1717
|
+
options: plugin.options
|
|
1718
|
+
};
|
|
1719
|
+
for (const generator of operationsGenerators) await this.dispatch({
|
|
1720
|
+
result: await generator.operations(pluginOperations, ctx),
|
|
1721
|
+
renderer: generator.renderer
|
|
1722
|
+
});
|
|
1723
|
+
await this.hooks.callHook("kubb:generate:operations", pluginOperations, ctx);
|
|
1724
|
+
} catch (caughtError) {
|
|
1725
|
+
error = require_usingCtx.toError(caughtError);
|
|
1726
|
+
}
|
|
1727
|
+
const duration = getElapsedMs(hrStart);
|
|
1728
|
+
await this.#emitPluginEnd({
|
|
1729
|
+
plugin,
|
|
1730
|
+
duration,
|
|
1731
|
+
success: !error,
|
|
1732
|
+
error: error ?? void 0
|
|
684
1733
|
});
|
|
685
|
-
|
|
686
|
-
|
|
687
|
-
|
|
688
|
-
file,
|
|
689
|
-
source,
|
|
690
|
-
processed: currentProcessed,
|
|
691
|
-
percentage,
|
|
692
|
-
total
|
|
1734
|
+
if (error) diagnostics.push({
|
|
1735
|
+
...Diagnostics.from(error),
|
|
1736
|
+
plugin: plugin.name
|
|
693
1737
|
});
|
|
1738
|
+
diagnostics.push(Diagnostics.performance({
|
|
1739
|
+
plugin: plugin.name,
|
|
1740
|
+
duration
|
|
1741
|
+
}));
|
|
1742
|
+
}
|
|
1743
|
+
return diagnostics;
|
|
1744
|
+
}
|
|
1745
|
+
/**
|
|
1746
|
+
* Stores whatever a generator method or `kubb:generate:*` hook returned.
|
|
1747
|
+
*
|
|
1748
|
+
* - An `Array<FileNode>` goes straight into `fileManager` via `upsert`.
|
|
1749
|
+
* - A renderer element runs through `renderer` (the renderer factory, e.g. JSX) and the
|
|
1750
|
+
* produced files go to `fileManager.upsert`.
|
|
1751
|
+
* - A falsy result is treated as a no-op. The generator wrote files itself via
|
|
1752
|
+
* `ctx.upsertFile`.
|
|
1753
|
+
*
|
|
1754
|
+
* Pass `renderer` when the result may be a renderer element. Generators that only return
|
|
1755
|
+
* `Array<FileNode>` do not need one.
|
|
1756
|
+
*/
|
|
1757
|
+
async dispatch({ result, renderer }) {
|
|
1758
|
+
try {
|
|
1759
|
+
var _usingCtx$2 = require_usingCtx._usingCtx();
|
|
1760
|
+
if (!result) return;
|
|
1761
|
+
if (Array.isArray(result)) {
|
|
1762
|
+
this.fileManager.upsert(...result);
|
|
1763
|
+
return;
|
|
1764
|
+
}
|
|
1765
|
+
if (!renderer) return;
|
|
1766
|
+
const instance = _usingCtx$2.u(renderer());
|
|
1767
|
+
await instance.render(result);
|
|
1768
|
+
this.fileManager.upsert(...instance.files);
|
|
1769
|
+
} catch (_) {
|
|
1770
|
+
_usingCtx$2.e = _;
|
|
1771
|
+
} finally {
|
|
1772
|
+
_usingCtx$2.d();
|
|
1773
|
+
}
|
|
1774
|
+
}
|
|
1775
|
+
/**
|
|
1776
|
+
* Removes every listener the driver added. Listeners attached directly to `hooks` from outside
|
|
1777
|
+
* the driver survive. Called at the end of a build to prevent leaks across repeated builds.
|
|
1778
|
+
*
|
|
1779
|
+
* @internal
|
|
1780
|
+
*/
|
|
1781
|
+
dispose() {
|
|
1782
|
+
for (const unhook of this.#unhooks) unhook();
|
|
1783
|
+
this.#unhooks.length = 0;
|
|
1784
|
+
this.#transforms.dispose();
|
|
1785
|
+
this.fileManager.dispose();
|
|
1786
|
+
this.inputNode = null;
|
|
1787
|
+
this.#adapterSource = null;
|
|
1788
|
+
}
|
|
1789
|
+
[Symbol.dispose]() {
|
|
1790
|
+
this.dispose();
|
|
1791
|
+
}
|
|
1792
|
+
/**
|
|
1793
|
+
* Merges `partial` onto a fresh default resolver and stores the result on `plugin.resolver`,
|
|
1794
|
+
* which is the single source `getResolver` and `getPlugin(name).resolver` both read.
|
|
1795
|
+
*/
|
|
1796
|
+
setPluginResolver(pluginName, partial) {
|
|
1797
|
+
const plugin = this.plugins.get(pluginName);
|
|
1798
|
+
if (!plugin) return;
|
|
1799
|
+
plugin.resolver = Resolver.merge(createResolver({ pluginName }), partial);
|
|
1800
|
+
}
|
|
1801
|
+
getResolver(pluginName) {
|
|
1802
|
+
return this.plugins.get(pluginName)?.resolver ?? createResolver({ pluginName });
|
|
1803
|
+
}
|
|
1804
|
+
getContext(plugin) {
|
|
1805
|
+
const driver = this;
|
|
1806
|
+
const report = (diagnostic) => {
|
|
1807
|
+
Diagnostics.report({
|
|
1808
|
+
...diagnostic,
|
|
1809
|
+
plugin: plugin.name
|
|
1810
|
+
});
|
|
1811
|
+
};
|
|
1812
|
+
return {
|
|
1813
|
+
config: driver.config,
|
|
1814
|
+
get root() {
|
|
1815
|
+
return (0, node_path.resolve)(driver.config.root, driver.config.output.path);
|
|
1816
|
+
},
|
|
1817
|
+
hooks: driver.hooks,
|
|
1818
|
+
plugin,
|
|
1819
|
+
getPlugin: driver.getPlugin.bind(driver),
|
|
1820
|
+
requirePlugin: ((name) => driver.requirePlugin(name, { requiredBy: plugin.name })),
|
|
1821
|
+
getResolver: driver.getResolver.bind(driver),
|
|
1822
|
+
driver,
|
|
1823
|
+
addFile: async (...files) => {
|
|
1824
|
+
driver.fileManager.add(...files);
|
|
1825
|
+
},
|
|
1826
|
+
upsertFile: async (...files) => {
|
|
1827
|
+
driver.fileManager.upsert(...files);
|
|
1828
|
+
},
|
|
1829
|
+
get meta() {
|
|
1830
|
+
return driver.inputNode?.meta ?? {
|
|
1831
|
+
circularNames: [],
|
|
1832
|
+
enumNames: []
|
|
1833
|
+
};
|
|
1834
|
+
},
|
|
1835
|
+
get adapter() {
|
|
1836
|
+
return driver.adapter;
|
|
1837
|
+
},
|
|
1838
|
+
get resolver() {
|
|
1839
|
+
return driver.getResolver(plugin.name);
|
|
1840
|
+
},
|
|
1841
|
+
warn(message) {
|
|
1842
|
+
report({
|
|
1843
|
+
code: Diagnostics.code.pluginWarning,
|
|
1844
|
+
severity: "warning",
|
|
1845
|
+
message
|
|
1846
|
+
});
|
|
1847
|
+
},
|
|
1848
|
+
error(error) {
|
|
1849
|
+
const cause = typeof error === "string" ? void 0 : error;
|
|
1850
|
+
report({
|
|
1851
|
+
code: Diagnostics.code.pluginFailed,
|
|
1852
|
+
severity: "error",
|
|
1853
|
+
message: typeof error === "string" ? error : error.message,
|
|
1854
|
+
cause
|
|
1855
|
+
});
|
|
1856
|
+
},
|
|
1857
|
+
info(message) {
|
|
1858
|
+
report({
|
|
1859
|
+
code: Diagnostics.code.pluginInfo,
|
|
1860
|
+
severity: "info",
|
|
1861
|
+
message
|
|
1862
|
+
});
|
|
1863
|
+
}
|
|
694
1864
|
};
|
|
695
|
-
|
|
696
|
-
|
|
697
|
-
|
|
698
|
-
|
|
1865
|
+
}
|
|
1866
|
+
getPlugin(pluginName) {
|
|
1867
|
+
return this.plugins.get(pluginName);
|
|
1868
|
+
}
|
|
1869
|
+
requirePlugin(pluginName, context) {
|
|
1870
|
+
const plugin = this.getPlugin(pluginName);
|
|
1871
|
+
if (plugin) return plugin;
|
|
1872
|
+
const requiredBy = context?.requiredBy;
|
|
1873
|
+
const by = requiredBy ? ` by "${requiredBy}"` : "";
|
|
1874
|
+
const help = requiredBy ? ` (required by "${requiredBy}")` : "";
|
|
1875
|
+
throw new Diagnostics.Error({
|
|
1876
|
+
code: Diagnostics.code.pluginNotFound,
|
|
1877
|
+
severity: "error",
|
|
1878
|
+
message: `Plugin "${pluginName}" is required${by} but not found. Make sure it is included in your Kubb config.`,
|
|
1879
|
+
help: `Add "${pluginName}" to the \`plugins\` array in kubb.config.ts${help}, or remove the dependency on it.`,
|
|
1880
|
+
location: { kind: "config" }
|
|
1881
|
+
});
|
|
699
1882
|
}
|
|
700
1883
|
};
|
|
701
1884
|
//#endregion
|
|
702
1885
|
//#region src/createStorage.ts
|
|
703
1886
|
/**
|
|
704
|
-
*
|
|
705
|
-
*
|
|
706
|
-
*
|
|
707
|
-
*
|
|
708
|
-
*
|
|
709
|
-
* @note Call the returned factory with optional options to instantiate the storage adapter.
|
|
1887
|
+
* Defines a custom storage backend. The builder receives user options and
|
|
1888
|
+
* returns a `Storage` implementation. Kubb ships with filesystem and in-memory
|
|
1889
|
+
* storages. A custom backend writes generated files elsewhere, such as cloud
|
|
1890
|
+
* storage or a database.
|
|
710
1891
|
*
|
|
711
|
-
* @example
|
|
1892
|
+
* @example In-memory storage (the built-in implementation)
|
|
712
1893
|
* ```ts
|
|
713
1894
|
* import { createStorage } from '@kubb/core'
|
|
714
1895
|
*
|
|
715
1896
|
* export const memoryStorage = createStorage(() => {
|
|
716
1897
|
* const store = new Map<string, string>()
|
|
1898
|
+
*
|
|
717
1899
|
* return {
|
|
718
1900
|
* name: 'memory',
|
|
719
|
-
* async hasItem(key) {
|
|
720
|
-
*
|
|
721
|
-
*
|
|
722
|
-
* async
|
|
1901
|
+
* async hasItem(key) {
|
|
1902
|
+
* return store.has(key)
|
|
1903
|
+
* },
|
|
1904
|
+
* async getItem(key) {
|
|
1905
|
+
* return store.get(key) ?? null
|
|
1906
|
+
* },
|
|
1907
|
+
* async setItem(key, value) {
|
|
1908
|
+
* store.set(key, value)
|
|
1909
|
+
* },
|
|
1910
|
+
* async removeItem(key) {
|
|
1911
|
+
* store.delete(key)
|
|
1912
|
+
* },
|
|
723
1913
|
* async getKeys(base) {
|
|
724
1914
|
* const keys = [...store.keys()]
|
|
725
1915
|
* return base ? keys.filter((k) => k.startsWith(base)) : keys
|
|
726
1916
|
* },
|
|
727
|
-
* async clear(base) {
|
|
1917
|
+
* async clear(base) {
|
|
1918
|
+
* if (!base) store.clear()
|
|
1919
|
+
* },
|
|
728
1920
|
* }
|
|
729
1921
|
* })
|
|
730
|
-
*
|
|
731
|
-
* // Instantiate:
|
|
732
|
-
* const storage = memoryStorage()
|
|
733
1922
|
* ```
|
|
734
1923
|
*/
|
|
735
1924
|
function createStorage(build) {
|
|
@@ -737,6 +1926,29 @@ function createStorage(build) {
|
|
|
737
1926
|
}
|
|
738
1927
|
//#endregion
|
|
739
1928
|
//#region src/storages/fsStorage.ts
|
|
1929
|
+
const WRITE_CONCURRENCY = 50;
|
|
1930
|
+
function createLimiter(concurrency) {
|
|
1931
|
+
let active = 0;
|
|
1932
|
+
const queue = [];
|
|
1933
|
+
function next() {
|
|
1934
|
+
if (active >= concurrency) return;
|
|
1935
|
+
const run = queue.shift();
|
|
1936
|
+
if (!run) return;
|
|
1937
|
+
active++;
|
|
1938
|
+
run();
|
|
1939
|
+
}
|
|
1940
|
+
return function limit(task) {
|
|
1941
|
+
return new Promise((resolve, reject) => {
|
|
1942
|
+
queue.push(() => {
|
|
1943
|
+
task().then(resolve, reject).finally(() => {
|
|
1944
|
+
active--;
|
|
1945
|
+
next();
|
|
1946
|
+
});
|
|
1947
|
+
});
|
|
1948
|
+
next();
|
|
1949
|
+
});
|
|
1950
|
+
};
|
|
1951
|
+
}
|
|
740
1952
|
/**
|
|
741
1953
|
* Built-in filesystem storage driver.
|
|
742
1954
|
*
|
|
@@ -744,11 +1956,13 @@ function createStorage(build) {
|
|
|
744
1956
|
* Keys are resolved against `process.cwd()`, so root-relative paths such as
|
|
745
1957
|
* `src/gen/api/getPets.ts` are written to the correct location without extra configuration.
|
|
746
1958
|
*
|
|
747
|
-
*
|
|
748
|
-
* -
|
|
749
|
-
* -
|
|
750
|
-
* -
|
|
751
|
-
* -
|
|
1959
|
+
* Writes are deduplicated and directory-safe:
|
|
1960
|
+
* - leading and trailing whitespace is trimmed before writing
|
|
1961
|
+
* - the write is skipped when the file content is already identical
|
|
1962
|
+
* - missing parent directories are created automatically
|
|
1963
|
+
* - Bun's native file API is used when running under Bun
|
|
1964
|
+
* - concurrent `setItem` calls are capped at {@link WRITE_CONCURRENCY} in flight, so a caller
|
|
1965
|
+
* can fire every file's write without pacing itself
|
|
752
1966
|
*
|
|
753
1967
|
* @example
|
|
754
1968
|
* ```ts
|
|
@@ -756,630 +1970,599 @@ function createStorage(build) {
|
|
|
756
1970
|
* import { defineConfig } from 'kubb'
|
|
757
1971
|
*
|
|
758
1972
|
* export default defineConfig({
|
|
759
|
-
* input:
|
|
760
|
-
* output: { path: './src/gen' },
|
|
761
|
-
* storage: fsStorage(),
|
|
762
|
-
* })
|
|
763
|
-
* ```
|
|
764
|
-
*/
|
|
765
|
-
const fsStorage = createStorage(() =>
|
|
766
|
-
|
|
767
|
-
|
|
768
|
-
|
|
769
|
-
|
|
770
|
-
return true;
|
|
771
|
-
} catch (_error) {
|
|
772
|
-
return false;
|
|
773
|
-
}
|
|
774
|
-
},
|
|
775
|
-
async getItem(key) {
|
|
776
|
-
try {
|
|
777
|
-
return await (0, node_fs_promises.readFile)((0, node_path.resolve)(key), "utf8");
|
|
778
|
-
} catch (_error) {
|
|
779
|
-
return null;
|
|
780
|
-
}
|
|
781
|
-
},
|
|
782
|
-
async setItem(key, value) {
|
|
783
|
-
await write((0, node_path.resolve)(key), value, { sanity: false });
|
|
784
|
-
},
|
|
785
|
-
async removeItem(key) {
|
|
786
|
-
await (0, node_fs_promises.rm)((0, node_path.resolve)(key), { force: true });
|
|
787
|
-
},
|
|
788
|
-
async getKeys(base) {
|
|
789
|
-
const keys = [];
|
|
790
|
-
const resolvedBase = (0, node_path.resolve)(base ?? process.cwd());
|
|
791
|
-
async function walk(dir, prefix) {
|
|
792
|
-
let entries;
|
|
1973
|
+
* input: './petStore.yaml',
|
|
1974
|
+
* output: { path: './src/gen' },
|
|
1975
|
+
* storage: fsStorage(),
|
|
1976
|
+
* })
|
|
1977
|
+
* ```
|
|
1978
|
+
*/
|
|
1979
|
+
const fsStorage = createStorage(() => {
|
|
1980
|
+
const limit = createLimiter(WRITE_CONCURRENCY);
|
|
1981
|
+
return {
|
|
1982
|
+
name: "fs",
|
|
1983
|
+
async hasItem(key) {
|
|
793
1984
|
try {
|
|
794
|
-
|
|
1985
|
+
await (0, node_fs_promises.access)((0, node_path.resolve)(key));
|
|
1986
|
+
return true;
|
|
795
1987
|
} catch (_error) {
|
|
796
|
-
return;
|
|
1988
|
+
return false;
|
|
797
1989
|
}
|
|
798
|
-
|
|
799
|
-
|
|
800
|
-
|
|
801
|
-
|
|
1990
|
+
},
|
|
1991
|
+
async getItem(key) {
|
|
1992
|
+
try {
|
|
1993
|
+
return await (0, node_fs_promises.readFile)((0, node_path.resolve)(key), "utf8");
|
|
1994
|
+
} catch (_error) {
|
|
1995
|
+
return null;
|
|
802
1996
|
}
|
|
1997
|
+
},
|
|
1998
|
+
async setItem(key, value) {
|
|
1999
|
+
await limit(() => require_usingCtx.write((0, node_path.resolve)(key), value, { sanity: false }));
|
|
2000
|
+
},
|
|
2001
|
+
async removeItem(key) {
|
|
2002
|
+
await (0, node_fs_promises.rm)((0, node_path.resolve)(key), { force: true });
|
|
2003
|
+
},
|
|
2004
|
+
async getKeys(base) {
|
|
2005
|
+
const resolvedBase = (0, node_path.resolve)(base ?? process.cwd());
|
|
2006
|
+
const keys = [];
|
|
2007
|
+
try {
|
|
2008
|
+
for await (const entry of (0, node_fs_promises.glob)("**/*", {
|
|
2009
|
+
cwd: resolvedBase,
|
|
2010
|
+
withFileTypes: true
|
|
2011
|
+
})) if (entry.isFile()) keys.push(require_usingCtx.toPosixPath((0, node_path.relative)(resolvedBase, (0, node_path.join)(entry.parentPath, entry.name))));
|
|
2012
|
+
} catch (_error) {}
|
|
2013
|
+
return keys;
|
|
2014
|
+
},
|
|
2015
|
+
async clear(base) {
|
|
2016
|
+
if (!base) return;
|
|
2017
|
+
await require_usingCtx.clean((0, node_path.resolve)(base));
|
|
803
2018
|
}
|
|
804
|
-
|
|
805
|
-
|
|
806
|
-
},
|
|
807
|
-
async clear(base) {
|
|
808
|
-
if (!base) return;
|
|
809
|
-
await clean((0, node_path.resolve)(base));
|
|
810
|
-
}
|
|
811
|
-
}));
|
|
2019
|
+
};
|
|
2020
|
+
});
|
|
812
2021
|
//#endregion
|
|
813
2022
|
//#region src/createKubb.ts
|
|
814
|
-
|
|
815
|
-
|
|
816
|
-
const config = {
|
|
2023
|
+
function resolveConfig(userConfig) {
|
|
2024
|
+
return {
|
|
817
2025
|
...userConfig,
|
|
818
2026
|
root: userConfig.root || process.cwd(),
|
|
819
2027
|
parsers: userConfig.parsers ?? [],
|
|
820
|
-
adapter: userConfig.adapter,
|
|
821
2028
|
output: {
|
|
822
2029
|
format: false,
|
|
823
2030
|
lint: false,
|
|
824
|
-
|
|
825
|
-
defaultBanner: require_PluginDriver.DEFAULT_BANNER,
|
|
2031
|
+
defaultBanner: "simple",
|
|
826
2032
|
...userConfig.output
|
|
827
2033
|
},
|
|
828
2034
|
storage: userConfig.storage ?? fsStorage(),
|
|
829
|
-
|
|
830
|
-
studioUrl: require_PluginDriver.DEFAULT_STUDIO_URL,
|
|
831
|
-
...typeof userConfig.devtools === "boolean" ? {} : userConfig.devtools
|
|
832
|
-
} : void 0,
|
|
2035
|
+
reporters: userConfig.reporters ?? [],
|
|
833
2036
|
plugins: userConfig.plugins ?? []
|
|
834
2037
|
};
|
|
835
|
-
const driver = new require_PluginDriver.PluginDriver(config, { hooks });
|
|
836
|
-
const sources = /* @__PURE__ */ new Map();
|
|
837
|
-
const diagnosticInfo = getDiagnosticInfo();
|
|
838
|
-
await hooks.emit("kubb:debug", {
|
|
839
|
-
date: /* @__PURE__ */ new Date(),
|
|
840
|
-
logs: [
|
|
841
|
-
"Configuration:",
|
|
842
|
-
` • Name: ${userConfig.name || "unnamed"}`,
|
|
843
|
-
` • Root: ${userConfig.root || process.cwd()}`,
|
|
844
|
-
` • Output: ${userConfig.output?.path || "not specified"}`,
|
|
845
|
-
` • Plugins: ${userConfig.plugins?.length || 0}`,
|
|
846
|
-
"Output Settings:",
|
|
847
|
-
` • Storage: ${config.storage.name}`,
|
|
848
|
-
` • Formatter: ${userConfig.output?.format || "none"}`,
|
|
849
|
-
` • Linter: ${userConfig.output?.lint || "none"}`,
|
|
850
|
-
"Environment:",
|
|
851
|
-
Object.entries(diagnosticInfo).map(([key, value]) => ` • ${key}: ${value}`).join("\n")
|
|
852
|
-
]
|
|
853
|
-
});
|
|
854
|
-
try {
|
|
855
|
-
if (isInputPath(userConfig) && !new URLPath(userConfig.input.path).isURL) {
|
|
856
|
-
await exists(userConfig.input.path);
|
|
857
|
-
await hooks.emit("kubb:debug", {
|
|
858
|
-
date: /* @__PURE__ */ new Date(),
|
|
859
|
-
logs: [`✓ Input file validated: ${userConfig.input.path}`]
|
|
860
|
-
});
|
|
861
|
-
}
|
|
862
|
-
} catch (caughtError) {
|
|
863
|
-
if (isInputPath(userConfig)) {
|
|
864
|
-
const error = caughtError;
|
|
865
|
-
throw new Error(`Cannot read file/URL defined in \`input.path\` or set with \`kubb generate PATH\` in the CLI of your Kubb config ${userConfig.input.path}`, { cause: error });
|
|
866
|
-
}
|
|
867
|
-
}
|
|
868
|
-
if (config.output.clean) {
|
|
869
|
-
await hooks.emit("kubb:debug", {
|
|
870
|
-
date: /* @__PURE__ */ new Date(),
|
|
871
|
-
logs: ["Cleaning output directories", ` • Output: ${config.output.path}`]
|
|
872
|
-
});
|
|
873
|
-
await config.storage.clear((0, node_path.resolve)(config.root, config.output.path));
|
|
874
|
-
}
|
|
875
|
-
function registerMiddlewareHook(event, middlewareHooks) {
|
|
876
|
-
const handler = middlewareHooks[event];
|
|
877
|
-
if (handler) hooks.on(event, handler);
|
|
878
|
-
}
|
|
879
|
-
for (const middleware of config.middleware ?? []) for (const event of Object.keys(middleware.hooks)) registerMiddlewareHook(event, middleware.hooks);
|
|
880
|
-
if (config.adapter) {
|
|
881
|
-
const source = inputToAdapterSource(config);
|
|
882
|
-
await hooks.emit("kubb:debug", {
|
|
883
|
-
date: /* @__PURE__ */ new Date(),
|
|
884
|
-
logs: [`Running adapter: ${config.adapter.name}`]
|
|
885
|
-
});
|
|
886
|
-
driver.adapter = config.adapter;
|
|
887
|
-
driver.inputNode = await config.adapter.parse(source);
|
|
888
|
-
await hooks.emit("kubb:debug", {
|
|
889
|
-
date: /* @__PURE__ */ new Date(),
|
|
890
|
-
logs: [
|
|
891
|
-
`✓ Adapter '${config.adapter.name}' resolved InputNode`,
|
|
892
|
-
` • Schemas: ${driver.inputNode.schemas.length}`,
|
|
893
|
-
` • Operations: ${driver.inputNode.operations.length}`
|
|
894
|
-
]
|
|
895
|
-
});
|
|
896
|
-
}
|
|
897
|
-
return {
|
|
898
|
-
config,
|
|
899
|
-
hooks,
|
|
900
|
-
driver,
|
|
901
|
-
sources
|
|
902
|
-
};
|
|
903
2038
|
}
|
|
904
2039
|
/**
|
|
905
|
-
*
|
|
906
|
-
*
|
|
2040
|
+
* Kubb code-generation instance bound to a single config entry. Resolves the user
|
|
2041
|
+
* config in the constructor, so `config` is available right away, and shares `hooks`,
|
|
2042
|
+
* `storage`, and `driver` across the `setup → build` lifecycle.
|
|
2043
|
+
*
|
|
2044
|
+
* `createKubb` takes a plain config object (the shape `defineConfig` produces),
|
|
2045
|
+
* not a fluent builder.
|
|
907
2046
|
*
|
|
908
|
-
*
|
|
909
|
-
*
|
|
910
|
-
*
|
|
911
|
-
*
|
|
912
|
-
*
|
|
2047
|
+
* Attach hook listeners to `.hooks` before calling `setup()` or `build()`.
|
|
2048
|
+
*
|
|
2049
|
+
* @example
|
|
2050
|
+
* ```ts
|
|
2051
|
+
* const kubb = createKubb(userConfig)
|
|
2052
|
+
* kubb.hooks.hook('kubb:plugin:end', ({ plugin, duration }) => console.log(plugin.name, duration))
|
|
2053
|
+
* const { files, diagnostics } = await kubb.safeBuild()
|
|
2054
|
+
* ```
|
|
913
2055
|
*/
|
|
914
|
-
|
|
915
|
-
|
|
916
|
-
|
|
917
|
-
|
|
918
|
-
|
|
919
|
-
|
|
920
|
-
|
|
921
|
-
|
|
922
|
-
|
|
923
|
-
|
|
924
|
-
|
|
925
|
-
|
|
926
|
-
}
|
|
927
|
-
|
|
928
|
-
"
|
|
929
|
-
|
|
930
|
-
|
|
931
|
-
|
|
932
|
-
|
|
933
|
-
|
|
934
|
-
|
|
935
|
-
|
|
936
|
-
|
|
937
|
-
|
|
938
|
-
|
|
939
|
-
|
|
940
|
-
|
|
941
|
-
|
|
942
|
-
|
|
943
|
-
|
|
944
|
-
|
|
945
|
-
|
|
946
|
-
const transformedNode = plugin.transformer ? (0, _kubb_ast.transform)(node, plugin.transformer) : node;
|
|
947
|
-
if (allowedSchemaNames !== void 0 && transformedNode.name && !allowedSchemaNames.has(transformedNode.name)) return;
|
|
948
|
-
const options = resolver.resolveOptions(transformedNode, {
|
|
949
|
-
options: plugin.options,
|
|
950
|
-
exclude,
|
|
951
|
-
include,
|
|
952
|
-
override
|
|
953
|
-
});
|
|
954
|
-
if (options === null) return;
|
|
955
|
-
const ctx = {
|
|
956
|
-
...generatorContext,
|
|
957
|
-
options
|
|
958
|
-
};
|
|
959
|
-
for (const gen of generators) {
|
|
960
|
-
if (!gen.schema) continue;
|
|
961
|
-
await require_PluginDriver.applyHookResult(await gen.schema(transformedNode, ctx), driver, resolveRenderer(gen));
|
|
962
|
-
}
|
|
963
|
-
await driver.hooks.emit("kubb:generate:schema", transformedNode, ctx);
|
|
964
|
-
},
|
|
965
|
-
async operation(node) {
|
|
966
|
-
const transformedNode = plugin.transformer ? (0, _kubb_ast.transform)(node, plugin.transformer) : node;
|
|
967
|
-
const options = resolver.resolveOptions(transformedNode, {
|
|
968
|
-
options: plugin.options,
|
|
969
|
-
exclude,
|
|
970
|
-
include,
|
|
971
|
-
override
|
|
2056
|
+
var Kubb = class {
|
|
2057
|
+
hooks;
|
|
2058
|
+
config;
|
|
2059
|
+
#driver = null;
|
|
2060
|
+
#storage = null;
|
|
2061
|
+
constructor(userConfig, options = {}) {
|
|
2062
|
+
this.config = resolveConfig(userConfig);
|
|
2063
|
+
this.hooks = options.hooks ?? new require_usingCtx.Hookable();
|
|
2064
|
+
}
|
|
2065
|
+
get storage() {
|
|
2066
|
+
if (!this.#storage) throw new Error("[kubb] setup() must be called before accessing storage");
|
|
2067
|
+
return this.#storage;
|
|
2068
|
+
}
|
|
2069
|
+
get driver() {
|
|
2070
|
+
if (!this.#driver) throw new Error("[kubb] setup() must be called before accessing driver");
|
|
2071
|
+
return this.#driver;
|
|
2072
|
+
}
|
|
2073
|
+
/**
|
|
2074
|
+
* Initializes the driver and storage. `build()` calls this automatically.
|
|
2075
|
+
*/
|
|
2076
|
+
async setup() {
|
|
2077
|
+
const config = this.config;
|
|
2078
|
+
const driver = new KubbDriver(config, { hooks: this.hooks });
|
|
2079
|
+
this.hooks.setMaxListeners(Math.max(10, config.plugins.length * 4));
|
|
2080
|
+
if (config.output.clean) {
|
|
2081
|
+
const cleanPath = (0, node_path.resolve)(config.root, config.output.path);
|
|
2082
|
+
if (require_usingCtx.isPathInside(config.root, cleanPath)) throw new Diagnostics.Error({
|
|
2083
|
+
code: Diagnostics.code.cleanRoot,
|
|
2084
|
+
severity: "error",
|
|
2085
|
+
message: `output.clean cannot delete "${cleanPath}" because it is the project root or a parent of it.`,
|
|
2086
|
+
help: "Point `output.path` at a subdirectory such as `./src/gen` so clean only removes generated code.",
|
|
2087
|
+
location: { kind: "config" }
|
|
972
2088
|
});
|
|
973
|
-
|
|
974
|
-
collectedOperations.push(transformedNode);
|
|
975
|
-
const ctx = {
|
|
976
|
-
...generatorContext,
|
|
977
|
-
options
|
|
978
|
-
};
|
|
979
|
-
for (const gen of generators) {
|
|
980
|
-
if (!gen.operation) continue;
|
|
981
|
-
await require_PluginDriver.applyHookResult(await gen.operation(transformedNode, ctx), driver, resolveRenderer(gen));
|
|
982
|
-
}
|
|
983
|
-
await driver.hooks.emit("kubb:generate:operation", transformedNode, ctx);
|
|
984
|
-
}
|
|
2089
|
+
await config.storage.clear(cleanPath);
|
|
985
2090
|
}
|
|
986
|
-
|
|
987
|
-
|
|
988
|
-
|
|
989
|
-
|
|
990
|
-
|
|
991
|
-
|
|
992
|
-
|
|
993
|
-
|
|
994
|
-
|
|
2091
|
+
await driver.setup();
|
|
2092
|
+
this.#driver = driver;
|
|
2093
|
+
this.#storage = config.storage;
|
|
2094
|
+
}
|
|
2095
|
+
/**
|
|
2096
|
+
* Runs the full pipeline and throws on any plugin error.
|
|
2097
|
+
* Automatically calls `setup()` if needed.
|
|
2098
|
+
*/
|
|
2099
|
+
async build() {
|
|
2100
|
+
const out = await this.safeBuild();
|
|
2101
|
+
if (Diagnostics.hasError(out.diagnostics)) {
|
|
2102
|
+
const errors = out.diagnostics.filter(Diagnostics.isProblem).filter((diagnostic) => diagnostic.severity === "error").map((diagnostic) => diagnostic.cause ?? new Diagnostics.Error(diagnostic));
|
|
2103
|
+
throw new require_usingCtx.BuildError(`Build failed with ${errors.length} ${errors.length === 1 ? "error" : "errors"}`, { errors });
|
|
995
2104
|
}
|
|
996
|
-
|
|
2105
|
+
return out;
|
|
997
2106
|
}
|
|
998
|
-
|
|
999
|
-
|
|
1000
|
-
|
|
1001
|
-
|
|
1002
|
-
|
|
1003
|
-
|
|
1004
|
-
|
|
1005
|
-
|
|
1006
|
-
|
|
1007
|
-
|
|
1008
|
-
|
|
1009
|
-
|
|
1010
|
-
|
|
1011
|
-
|
|
1012
|
-
|
|
1013
|
-
|
|
1014
|
-
|
|
1015
|
-
|
|
1016
|
-
|
|
1017
|
-
|
|
1018
|
-
|
|
1019
|
-
|
|
1020
|
-
|
|
1021
|
-
|
|
1022
|
-
|
|
1023
|
-
|
|
1024
|
-
|
|
1025
|
-
|
|
1026
|
-
|
|
1027
|
-
|
|
1028
|
-
|
|
1029
|
-
|
|
1030
|
-
|
|
1031
|
-
|
|
1032
|
-
|
|
1033
|
-
|
|
1034
|
-
|
|
1035
|
-
|
|
1036
|
-
|
|
1037
|
-
|
|
1038
|
-
|
|
1039
|
-
|
|
1040
|
-
|
|
1041
|
-
|
|
1042
|
-
|
|
1043
|
-
|
|
1044
|
-
|
|
1045
|
-
|
|
1046
|
-
|
|
1047
|
-
|
|
1048
|
-
plugin,
|
|
1049
|
-
duration,
|
|
1050
|
-
success: false,
|
|
1051
|
-
error,
|
|
1052
|
-
config,
|
|
1053
|
-
get files() {
|
|
1054
|
-
return driver.fileManager.files;
|
|
1055
|
-
},
|
|
1056
|
-
upsertFile: (...files) => driver.fileManager.upsert(...files)
|
|
1057
|
-
});
|
|
1058
|
-
await hooks.emit("kubb:debug", {
|
|
1059
|
-
date: errorTimestamp,
|
|
1060
|
-
logs: [
|
|
1061
|
-
"✗ Plugin start failed",
|
|
1062
|
-
` • Plugin Name: ${plugin.name}`,
|
|
1063
|
-
` • Error: ${error.constructor.name} - ${error.message}`,
|
|
1064
|
-
" • Stack Trace:",
|
|
1065
|
-
error.stack || "No stack trace available"
|
|
1066
|
-
]
|
|
1067
|
-
});
|
|
1068
|
-
failedPlugins.add({
|
|
1069
|
-
plugin,
|
|
1070
|
-
error
|
|
1071
|
-
});
|
|
2107
|
+
/**
|
|
2108
|
+
* Runs the full pipeline and captures errors in `BuildOutput` instead of throwing.
|
|
2109
|
+
* Automatically calls `setup()` if needed. This is the canonical call: it never throws on
|
|
2110
|
+
* plugin errors, so callers stay in control of how failures surface.
|
|
2111
|
+
*/
|
|
2112
|
+
async safeBuild() {
|
|
2113
|
+
try {
|
|
2114
|
+
var _usingCtx$1 = require_usingCtx._usingCtx();
|
|
2115
|
+
if (!this.#driver) await this.setup();
|
|
2116
|
+
const self = _usingCtx$1.u(this);
|
|
2117
|
+
const driver = self.driver;
|
|
2118
|
+
const storage = self.storage;
|
|
2119
|
+
const { diagnostics } = await driver.run();
|
|
2120
|
+
return {
|
|
2121
|
+
diagnostics,
|
|
2122
|
+
files: driver.fileManager.files,
|
|
2123
|
+
driver,
|
|
2124
|
+
storage
|
|
2125
|
+
};
|
|
2126
|
+
} catch (_) {
|
|
2127
|
+
_usingCtx$1.e = _;
|
|
2128
|
+
} finally {
|
|
2129
|
+
_usingCtx$1.d();
|
|
2130
|
+
}
|
|
2131
|
+
}
|
|
2132
|
+
/**
|
|
2133
|
+
* Run one build and its output passes end to end, emitting the surrounding `kubb:generation:*`
|
|
2134
|
+
* hooks. Never throws on a build error: the outcome comes back in {@link GenerateResult} so the
|
|
2135
|
+
* host decides how failures surface. Telemetry and progress narration stay with the host, which
|
|
2136
|
+
* reads the result and subscribes to the `kubb:*` hooks.
|
|
2137
|
+
*
|
|
2138
|
+
* @example
|
|
2139
|
+
* ```ts
|
|
2140
|
+
* const result = await createKubb(config, { hooks }).generate()
|
|
2141
|
+
* if (!result.success) process.exitCode = 1
|
|
2142
|
+
* ```
|
|
2143
|
+
*/
|
|
2144
|
+
async generate(options = {}) {
|
|
2145
|
+
const { hooks, config } = this;
|
|
2146
|
+
const hrStart = process.hrtime();
|
|
2147
|
+
await hooks.callHook("kubb:generation:start", { config });
|
|
2148
|
+
await hooks.callHook("kubb:setup:start");
|
|
2149
|
+
await this.setup();
|
|
2150
|
+
await hooks.callHook("kubb:setup:end");
|
|
2151
|
+
const { files, diagnostics, storage } = await this.safeBuild();
|
|
2152
|
+
for (const diagnostic of diagnostics) {
|
|
2153
|
+
if (!Diagnostics.isProblem(diagnostic)) continue;
|
|
2154
|
+
if (diagnostic.code === Diagnostics.code.unknown) {
|
|
2155
|
+
await hooks.callHook("kubb:error", { error: diagnostic.cause ?? new Error(diagnostic.message) });
|
|
2156
|
+
continue;
|
|
1072
2157
|
}
|
|
2158
|
+
await Diagnostics.emit(hooks, diagnostic);
|
|
2159
|
+
}
|
|
2160
|
+
if (Diagnostics.hasError(diagnostics)) {
|
|
2161
|
+
await hooks.callHook("kubb:generation:end", {
|
|
2162
|
+
config,
|
|
2163
|
+
storage,
|
|
2164
|
+
diagnostics,
|
|
2165
|
+
filesCreated: files.length,
|
|
2166
|
+
status: "failed",
|
|
2167
|
+
hrStart
|
|
2168
|
+
});
|
|
2169
|
+
return {
|
|
2170
|
+
success: false,
|
|
2171
|
+
files,
|
|
2172
|
+
diagnostics
|
|
2173
|
+
};
|
|
1073
2174
|
}
|
|
1074
|
-
await
|
|
2175
|
+
const outputDiagnostics = options.processOutput ? await options.processOutput({
|
|
1075
2176
|
config,
|
|
1076
|
-
|
|
1077
|
-
|
|
1078
|
-
|
|
1079
|
-
|
|
1080
|
-
|
|
1081
|
-
const files = driver.fileManager.files;
|
|
1082
|
-
const parsersMap = /* @__PURE__ */ new Map();
|
|
1083
|
-
for (const parser of config.parsers) if (parser.extNames) for (const extname of parser.extNames) parsersMap.set(extname, parser);
|
|
1084
|
-
const fileProcessor = new FileProcessor();
|
|
1085
|
-
await hooks.emit("kubb:debug", {
|
|
1086
|
-
date: /* @__PURE__ */ new Date(),
|
|
1087
|
-
logs: [`Writing ${files.length} files...`]
|
|
1088
|
-
});
|
|
1089
|
-
await fileProcessor.run(files, {
|
|
1090
|
-
parsers: parsersMap,
|
|
1091
|
-
mode: "parallel",
|
|
1092
|
-
extension: config.output.extension,
|
|
1093
|
-
onStart: async (processingFiles) => {
|
|
1094
|
-
await hooks.emit("kubb:files:processing:start", { files: processingFiles });
|
|
1095
|
-
},
|
|
1096
|
-
onUpdate: async ({ file, source, processed, total, percentage }) => {
|
|
1097
|
-
await hooks.emit("kubb:file:processing:update", {
|
|
1098
|
-
file,
|
|
1099
|
-
source,
|
|
1100
|
-
processed,
|
|
1101
|
-
total,
|
|
1102
|
-
percentage,
|
|
1103
|
-
config
|
|
1104
|
-
});
|
|
1105
|
-
if (source) {
|
|
1106
|
-
await config.storage.setItem(file.path, source);
|
|
1107
|
-
sources.set(file.path, source);
|
|
1108
|
-
}
|
|
1109
|
-
},
|
|
1110
|
-
onEnd: async (processedFiles) => {
|
|
1111
|
-
await hooks.emit("kubb:files:processing:end", { files: processedFiles });
|
|
1112
|
-
await hooks.emit("kubb:debug", {
|
|
1113
|
-
date: /* @__PURE__ */ new Date(),
|
|
1114
|
-
logs: [`✓ File write process completed for ${processedFiles.length} files`]
|
|
1115
|
-
});
|
|
1116
|
-
}
|
|
1117
|
-
});
|
|
1118
|
-
await hooks.emit("kubb:build:end", {
|
|
1119
|
-
files,
|
|
2177
|
+
outputPath: (0, node_path.resolve)(config.root, config.output.path)
|
|
2178
|
+
}) : [];
|
|
2179
|
+
const finalDiagnostics = [...diagnostics, ...outputDiagnostics];
|
|
2180
|
+
const failed = Diagnostics.hasError(outputDiagnostics);
|
|
2181
|
+
await hooks.callHook("kubb:generation:end", {
|
|
1120
2182
|
config,
|
|
1121
|
-
|
|
2183
|
+
storage,
|
|
2184
|
+
diagnostics: finalDiagnostics,
|
|
2185
|
+
filesCreated: files.length,
|
|
2186
|
+
status: failed ? "failed" : "success",
|
|
2187
|
+
hrStart
|
|
1122
2188
|
});
|
|
1123
2189
|
return {
|
|
1124
|
-
|
|
2190
|
+
success: !failed,
|
|
1125
2191
|
files,
|
|
1126
|
-
|
|
1127
|
-
pluginTimings,
|
|
1128
|
-
sources
|
|
1129
|
-
};
|
|
1130
|
-
} catch (error) {
|
|
1131
|
-
return {
|
|
1132
|
-
failedPlugins,
|
|
1133
|
-
files: [],
|
|
1134
|
-
driver,
|
|
1135
|
-
pluginTimings,
|
|
1136
|
-
error,
|
|
1137
|
-
sources
|
|
2192
|
+
diagnostics: finalDiagnostics
|
|
1138
2193
|
};
|
|
1139
|
-
} finally {
|
|
1140
|
-
driver.dispose();
|
|
1141
2194
|
}
|
|
1142
|
-
|
|
1143
|
-
|
|
1144
|
-
const { files, driver, failedPlugins, pluginTimings, error, sources } = await safeBuild(setupResult);
|
|
1145
|
-
if (error) throw error;
|
|
1146
|
-
if (failedPlugins.size > 0) {
|
|
1147
|
-
const errors = [...failedPlugins].map(({ error }) => error);
|
|
1148
|
-
throw new BuildError(`Build Error with ${failedPlugins.size} failed plugins`, { errors });
|
|
2195
|
+
dispose() {
|
|
2196
|
+
this.#driver?.dispose();
|
|
1149
2197
|
}
|
|
1150
|
-
|
|
1151
|
-
|
|
1152
|
-
|
|
1153
|
-
|
|
1154
|
-
pluginTimings,
|
|
1155
|
-
error: void 0,
|
|
1156
|
-
sources
|
|
1157
|
-
};
|
|
1158
|
-
}
|
|
1159
|
-
/**
|
|
1160
|
-
* Returns a snapshot of the current runtime environment.
|
|
1161
|
-
*
|
|
1162
|
-
* Useful for attaching context to debug logs and error reports so that
|
|
1163
|
-
* issues can be reproduced without manual information gathering.
|
|
1164
|
-
*/
|
|
1165
|
-
function getDiagnosticInfo() {
|
|
1166
|
-
return {
|
|
1167
|
-
nodeVersion: node_process.version,
|
|
1168
|
-
KubbVersion: version,
|
|
1169
|
-
platform: process.platform,
|
|
1170
|
-
arch: process.arch,
|
|
1171
|
-
cwd: process.cwd()
|
|
1172
|
-
};
|
|
1173
|
-
}
|
|
1174
|
-
function isInputPath(config) {
|
|
1175
|
-
return typeof config?.input === "object" && config.input !== null && "path" in config.input;
|
|
1176
|
-
}
|
|
1177
|
-
function inputToAdapterSource(config) {
|
|
1178
|
-
const input = config.input;
|
|
1179
|
-
if (!input) throw new Error("[kubb] input is required when using an adapter. Provide input.path or input.data in your config.");
|
|
1180
|
-
if ("data" in input) return {
|
|
1181
|
-
type: "data",
|
|
1182
|
-
data: input.data
|
|
1183
|
-
};
|
|
1184
|
-
if (new URLPath(input.path).isURL) return {
|
|
1185
|
-
type: "path",
|
|
1186
|
-
path: input.path
|
|
1187
|
-
};
|
|
1188
|
-
return {
|
|
1189
|
-
type: "path",
|
|
1190
|
-
path: (0, node_path.resolve)(config.root, input.path)
|
|
1191
|
-
};
|
|
1192
|
-
}
|
|
2198
|
+
[Symbol.dispose]() {
|
|
2199
|
+
this.dispose();
|
|
2200
|
+
}
|
|
2201
|
+
};
|
|
1193
2202
|
/**
|
|
1194
|
-
*
|
|
1195
|
-
*
|
|
1196
|
-
* Accepts a user-facing config shape and resolves it to a full {@link Config} during
|
|
1197
|
-
* `setup()`. The instance then holds shared state (`hooks`, `sources`, `driver`, `config`)
|
|
1198
|
-
* across the `setup → build` lifecycle. Attach event listeners to `kubb.hooks` before
|
|
1199
|
-
* calling `setup()` or `build()`.
|
|
2203
|
+
* Constructs a {@link Kubb} build orchestrator from a user config. Equivalent
|
|
2204
|
+
* to `new Kubb(userConfig, options)` and the canonical public entry point.
|
|
1200
2205
|
*
|
|
1201
2206
|
* @example
|
|
1202
2207
|
* ```ts
|
|
1203
|
-
*
|
|
2208
|
+
* import { createKubb } from '@kubb/core'
|
|
2209
|
+
* import { adapterOas } from '@kubb/adapter-oas'
|
|
2210
|
+
* import { pluginTs } from '@kubb/plugin-ts'
|
|
1204
2211
|
*
|
|
1205
|
-
* kubb
|
|
1206
|
-
*
|
|
2212
|
+
* const kubb = createKubb({
|
|
2213
|
+
* input: './petStore.yaml',
|
|
2214
|
+
* output: { path: './src/gen' },
|
|
2215
|
+
* adapter: adapterOas(),
|
|
2216
|
+
* plugins: [pluginTs()],
|
|
1207
2217
|
* })
|
|
1208
2218
|
*
|
|
1209
|
-
*
|
|
2219
|
+
* await kubb.build()
|
|
1210
2220
|
* ```
|
|
1211
2221
|
*/
|
|
1212
2222
|
function createKubb(userConfig, options = {}) {
|
|
1213
|
-
|
|
1214
|
-
let setupResult;
|
|
1215
|
-
const instance = {
|
|
1216
|
-
get hooks() {
|
|
1217
|
-
return hooks;
|
|
1218
|
-
},
|
|
1219
|
-
get sources() {
|
|
1220
|
-
return setupResult?.sources ?? /* @__PURE__ */ new Map();
|
|
1221
|
-
},
|
|
1222
|
-
get driver() {
|
|
1223
|
-
return setupResult?.driver;
|
|
1224
|
-
},
|
|
1225
|
-
get config() {
|
|
1226
|
-
return setupResult?.config;
|
|
1227
|
-
},
|
|
1228
|
-
async setup() {
|
|
1229
|
-
setupResult = await setup(userConfig, { hooks });
|
|
1230
|
-
},
|
|
1231
|
-
async build() {
|
|
1232
|
-
if (!setupResult) await instance.setup();
|
|
1233
|
-
return build(setupResult);
|
|
1234
|
-
},
|
|
1235
|
-
async safeBuild() {
|
|
1236
|
-
if (!setupResult) await instance.setup();
|
|
1237
|
-
return safeBuild(setupResult);
|
|
1238
|
-
}
|
|
1239
|
-
};
|
|
1240
|
-
return instance;
|
|
2223
|
+
return new Kubb(userConfig, options);
|
|
1241
2224
|
}
|
|
1242
2225
|
//#endregion
|
|
1243
|
-
//#region src/
|
|
2226
|
+
//#region src/createReporter.ts
|
|
1244
2227
|
/**
|
|
1245
|
-
*
|
|
2228
|
+
* Numeric log-level thresholds used internally to compare verbosity.
|
|
1246
2229
|
*
|
|
1247
|
-
*
|
|
1248
|
-
|
|
1249
|
-
|
|
2230
|
+
* Higher numbers are more verbose.
|
|
2231
|
+
*/
|
|
2232
|
+
const logLevel = {
|
|
2233
|
+
silent: Number.NEGATIVE_INFINITY,
|
|
2234
|
+
error: 0,
|
|
2235
|
+
warn: 1,
|
|
2236
|
+
info: 3,
|
|
2237
|
+
verbose: 4
|
|
2238
|
+
};
|
|
2239
|
+
/**
|
|
2240
|
+
* Defines a reporter. The returned reporter buffers each value `report` returns in order and, when
|
|
2241
|
+
* the definition has a `drain`, hands the array to `drain` once and then clears it. Wiring the
|
|
2242
|
+
* reporter onto the run's hooks is the host's job, so the reporter only ever deals with a
|
|
2243
|
+
* {@link GenerationResult}.
|
|
1250
2244
|
*
|
|
1251
2245
|
* @example
|
|
1252
2246
|
* ```ts
|
|
1253
|
-
*
|
|
1254
|
-
* export const jsxRenderer = createRenderer(() => {
|
|
1255
|
-
* const runtime = new Runtime()
|
|
1256
|
-
* return {
|
|
1257
|
-
* async render(element) { await runtime.render(element) },
|
|
1258
|
-
* get files() { return runtime.nodes },
|
|
1259
|
-
* unmount(error) { runtime.unmount(error) },
|
|
1260
|
-
* }
|
|
1261
|
-
* })
|
|
2247
|
+
* import { createReporter, Diagnostics } from '@kubb/core'
|
|
1262
2248
|
*
|
|
1263
|
-
*
|
|
1264
|
-
*
|
|
1265
|
-
*
|
|
1266
|
-
*
|
|
1267
|
-
*
|
|
1268
|
-
*
|
|
2249
|
+
* export const jsonReporter = createReporter({
|
|
2250
|
+
* name: 'json',
|
|
2251
|
+
* report(result) {
|
|
2252
|
+
* return { status: Diagnostics.hasError(result.diagnostics) ? 'failed' : 'success', diagnostics: result.diagnostics }
|
|
2253
|
+
* },
|
|
2254
|
+
* drain(context, reports) {
|
|
2255
|
+
* process.stdout.write(`${JSON.stringify(reports, null, 2)}\n`)
|
|
2256
|
+
* },
|
|
1269
2257
|
* })
|
|
1270
2258
|
* ```
|
|
1271
2259
|
*/
|
|
1272
|
-
function
|
|
1273
|
-
|
|
2260
|
+
function createReporter(reporter) {
|
|
2261
|
+
const reports = [];
|
|
2262
|
+
return {
|
|
2263
|
+
name: reporter.name,
|
|
2264
|
+
async report(result, context) {
|
|
2265
|
+
const report = await reporter.report(result, context);
|
|
2266
|
+
if (reporter.drain) reports.push(report);
|
|
2267
|
+
},
|
|
2268
|
+
async drain(context) {
|
|
2269
|
+
await reporter.drain?.(context, [...reports]);
|
|
2270
|
+
reports.length = 0;
|
|
2271
|
+
},
|
|
2272
|
+
[Symbol.dispose]() {
|
|
2273
|
+
reports.length = 0;
|
|
2274
|
+
}
|
|
2275
|
+
};
|
|
1274
2276
|
}
|
|
1275
2277
|
//#endregion
|
|
1276
|
-
//#region src/
|
|
2278
|
+
//#region src/reporters/report.ts
|
|
1277
2279
|
/**
|
|
1278
|
-
*
|
|
1279
|
-
*
|
|
1280
|
-
*
|
|
2280
|
+
* Builds the normalized {@link Report} for one config from its {@link GenerationResult}. Splits the
|
|
2281
|
+
* diagnostics into problems and per-plugin timings (slowest first) and derives the plugin and issue
|
|
2282
|
+
* counts, so every reporter renders the same data.
|
|
1281
2283
|
*/
|
|
1282
|
-
function
|
|
1283
|
-
|
|
2284
|
+
function buildReport(result) {
|
|
2285
|
+
const { config, diagnostics, filesCreated, status, hrStart } = result;
|
|
2286
|
+
const failed = Diagnostics.failedPlugins(diagnostics);
|
|
2287
|
+
const total = config.plugins?.length ?? 0;
|
|
2288
|
+
const counts = Diagnostics.count(diagnostics);
|
|
2289
|
+
const problems = diagnostics.filter(Diagnostics.isProblem);
|
|
2290
|
+
const timings = diagnostics.filter(Diagnostics.isPerformance).sort((a, b) => b.duration - a.duration).map((diagnostic) => ({
|
|
2291
|
+
plugin: diagnostic.plugin,
|
|
2292
|
+
durationMs: diagnostic.duration
|
|
2293
|
+
}));
|
|
2294
|
+
return {
|
|
2295
|
+
name: config.name ?? "",
|
|
2296
|
+
status,
|
|
2297
|
+
plugins: {
|
|
2298
|
+
passed: total - failed.length,
|
|
2299
|
+
failed,
|
|
2300
|
+
total
|
|
2301
|
+
},
|
|
2302
|
+
counts,
|
|
2303
|
+
filesCreated,
|
|
2304
|
+
durationMs: getElapsedMs(hrStart),
|
|
2305
|
+
output: (0, node_path.resolve)(config.root, config.output.path),
|
|
2306
|
+
timings,
|
|
2307
|
+
diagnostics: problems.map((diagnostic) => Diagnostics.serialize(diagnostic))
|
|
2308
|
+
};
|
|
2309
|
+
}
|
|
2310
|
+
//#endregion
|
|
2311
|
+
//#region src/reporters/cliReporter.ts
|
|
2312
|
+
/**
|
|
2313
|
+
* Builds the vitest/jest-style summary for one {@link Report}: right-aligned dim labels with
|
|
2314
|
+
* `N passed (total)` counts, and a per-plugin `Timings` section when `showTimings`.
|
|
2315
|
+
*/
|
|
2316
|
+
function buildSummaryLines(report, { showTimings }) {
|
|
2317
|
+
const { status, plugins, counts, filesCreated, durationMs, output, timings } = report;
|
|
2318
|
+
const rows = [];
|
|
2319
|
+
rows.push(["Plugins", status === "success" ? `${(0, node_util.styleText)("green", `${plugins.passed} passed`)} (${plugins.total})` : `${(0, node_util.styleText)("green", `${plugins.passed} passed`)} | ${(0, node_util.styleText)("red", `${plugins.failed.length} failed`)} (${plugins.total})`]);
|
|
2320
|
+
if (status === "failed" && plugins.failed.length > 0) rows.push(["Failed", plugins.failed.map((name) => randomCliColor(name)).join(", ")]);
|
|
2321
|
+
if (counts.errors > 0 || counts.warnings > 0) {
|
|
2322
|
+
const issues = [counts.errors > 0 ? (0, node_util.styleText)("red", `${counts.errors} ${counts.errors === 1 ? "error" : "errors"}`) : void 0, counts.warnings > 0 ? (0, node_util.styleText)("yellow", `${counts.warnings} ${counts.warnings === 1 ? "warning" : "warnings"}`) : void 0].filter(Boolean).join(" | ");
|
|
2323
|
+
rows.push(["Issues", issues]);
|
|
2324
|
+
}
|
|
2325
|
+
rows.push(["Files", `${(0, node_util.styleText)("green", String(filesCreated))} generated`]);
|
|
2326
|
+
rows.push(["Duration", (0, node_util.styleText)("green", formatMs(durationMs))]);
|
|
2327
|
+
rows.push(["Output", output]);
|
|
2328
|
+
const labelWidth = Math.max(...rows.map(([label]) => label.length), timings.length > 0 ? 7 : 0);
|
|
2329
|
+
const lines = rows.map(([label, value]) => `${(0, node_util.styleText)("dim", label.padStart(labelWidth))} ${value}`);
|
|
2330
|
+
if (showTimings && timings.length > 0) {
|
|
2331
|
+
const nameWidth = Math.max(0, ...timings.map((timing) => timing.plugin.length));
|
|
2332
|
+
const indent = " ".repeat(labelWidth + 2);
|
|
2333
|
+
lines.push((0, node_util.styleText)("dim", "Timings".padStart(labelWidth)));
|
|
2334
|
+
for (const timing of timings) {
|
|
2335
|
+
const timeStr = formatMs(timing.durationMs);
|
|
2336
|
+
const barLength = Math.min(Math.ceil(timing.durationMs / 100), 10);
|
|
2337
|
+
const bar = (0, node_util.styleText)("dim", "█".repeat(barLength));
|
|
2338
|
+
lines.push(`${indent}${(0, node_util.styleText)("dim", "•")} ${timing.plugin.padEnd(nameWidth)} ${bar} ${timeStr}`);
|
|
2339
|
+
}
|
|
2340
|
+
}
|
|
2341
|
+
return lines;
|
|
1284
2342
|
}
|
|
2343
|
+
/**
|
|
2344
|
+
* Renders the summary as plain `console.log` lines so it works in every CLI (no clack/TTY
|
|
2345
|
+
* dependency): a blank line, the config name colored by status, then the summary rows.
|
|
2346
|
+
*/
|
|
2347
|
+
function renderSummary(lines, { title, status }) {
|
|
2348
|
+
console.log("");
|
|
2349
|
+
if (title) console.log((0, node_util.styleText)(status === "failed" ? "red" : "green", title));
|
|
2350
|
+
for (const line of lines) console.log(line);
|
|
2351
|
+
}
|
|
2352
|
+
/**
|
|
2353
|
+
* The default `cli` reporter. Renders the {@link Report} for each config as it finishes, independent
|
|
2354
|
+
* of the live logger view. Suppressed at `silent`. The `verbose` level adds the per-plugin timings.
|
|
2355
|
+
*/
|
|
2356
|
+
const cliReporter = createReporter({
|
|
2357
|
+
name: "cli",
|
|
2358
|
+
report(result, { logLevel: logLevel$1 }) {
|
|
2359
|
+
if (logLevel$1 <= logLevel.silent) return;
|
|
2360
|
+
const report = buildReport(result);
|
|
2361
|
+
renderSummary(buildSummaryLines(report, { showTimings: logLevel$1 >= logLevel.verbose }), {
|
|
2362
|
+
title: report.name,
|
|
2363
|
+
status: report.status
|
|
2364
|
+
});
|
|
2365
|
+
}
|
|
2366
|
+
});
|
|
1285
2367
|
//#endregion
|
|
1286
|
-
//#region src/
|
|
2368
|
+
//#region src/reporters/fileReporter.ts
|
|
2369
|
+
/**
|
|
2370
|
+
* Builds the `## Summary` section: the same counts the cli and json reporters expose, as a list of
|
|
2371
|
+
* `label value` rows with the labels padded to a common width.
|
|
2372
|
+
*/
|
|
2373
|
+
function buildSummarySection(report) {
|
|
2374
|
+
const { status, plugins, counts, filesCreated, durationMs, output } = report;
|
|
2375
|
+
const rows = [["Status", status], ["Plugins", status === "success" ? `${plugins.passed} passed (${plugins.total})` : `${plugins.passed} passed | ${plugins.failed.length} failed (${plugins.total})`]];
|
|
2376
|
+
if (plugins.failed.length > 0) rows.push(["Failed", plugins.failed.join(", ")]);
|
|
2377
|
+
rows.push(["Issues", `${counts.errors} errors | ${counts.warnings} warnings | ${counts.infos} infos`]);
|
|
2378
|
+
rows.push(["Files", `${filesCreated} generated`]);
|
|
2379
|
+
rows.push(["Duration", formatMs(durationMs)]);
|
|
2380
|
+
rows.push(["Output", output]);
|
|
2381
|
+
const labelWidth = Math.max(...rows.map(([label]) => label.length));
|
|
2382
|
+
return [
|
|
2383
|
+
"## Summary",
|
|
2384
|
+
"",
|
|
2385
|
+
...rows.map(([label, value]) => ` ${label.padEnd(labelWidth)} ${value}`)
|
|
2386
|
+
];
|
|
2387
|
+
}
|
|
2388
|
+
/**
|
|
2389
|
+
* Builds the `## Problems` section: each problem rendered in the miette block format, blocks
|
|
2390
|
+
* separated by a blank line. Returns an empty array when there are no problems, so the caller
|
|
2391
|
+
* can drop the heading.
|
|
2392
|
+
*/
|
|
2393
|
+
function buildProblemSection(diagnostics) {
|
|
2394
|
+
const problems = diagnostics.filter(Diagnostics.isProblem);
|
|
2395
|
+
if (problems.length === 0) return [];
|
|
2396
|
+
return [
|
|
2397
|
+
"## Problems",
|
|
2398
|
+
"",
|
|
2399
|
+
problems.map((diagnostic) => Diagnostics.formatLines(diagnostic).join("\n")).join("\n\n")
|
|
2400
|
+
];
|
|
2401
|
+
}
|
|
2402
|
+
/**
|
|
2403
|
+
* Builds the `## Timings` section from a {@link Report}: one `plugin duration` row per record,
|
|
2404
|
+
* slowest first with the plugin names left-aligned and the durations right-aligned. Returns an
|
|
2405
|
+
* empty array when there are no timings.
|
|
2406
|
+
*/
|
|
2407
|
+
function buildTimingSection(report) {
|
|
2408
|
+
const { timings } = report;
|
|
2409
|
+
if (timings.length === 0) return [];
|
|
2410
|
+
const nameWidth = Math.max(...timings.map((timing) => timing.plugin.length));
|
|
2411
|
+
const durations = timings.map((timing) => formatMs(timing.durationMs));
|
|
2412
|
+
const durationWidth = Math.max(...durations.map((duration) => duration.length));
|
|
2413
|
+
return [
|
|
2414
|
+
"## Timings",
|
|
2415
|
+
"",
|
|
2416
|
+
...timings.map((timing, index) => ` ${timing.plugin.padEnd(nameWidth)} ${durations[index].padStart(durationWidth)}`)
|
|
2417
|
+
];
|
|
2418
|
+
}
|
|
1287
2419
|
/**
|
|
1288
|
-
*
|
|
2420
|
+
* The `file` reporter. Writes a config's {@link Report} to `.kubb/kubb-<name>-<timestamp>.log` as a
|
|
2421
|
+
* plain-text document: a `# <name> — <timestamp>` header, a `## Summary` with the same counts the
|
|
2422
|
+
* cli and json reporters expose, a `## Problems` section in the miette block format, and a
|
|
2423
|
+
* `## Timings` section. Selected with `--reporter file` (or `reporters: ['file']`).
|
|
1289
2424
|
*
|
|
1290
|
-
*
|
|
1291
|
-
*
|
|
1292
|
-
*
|
|
2425
|
+
* @note It captures the collected diagnostics once a config finishes, not the live
|
|
2426
|
+
* `kubb:info`/`kubb:plugin` hook stream. Color is stripped so the file stays plain text even when
|
|
2427
|
+
* the run is attached to a TTY.
|
|
2428
|
+
*/
|
|
2429
|
+
const fileReporter = createReporter({
|
|
2430
|
+
name: "file",
|
|
2431
|
+
async report(result) {
|
|
2432
|
+
const { diagnostics, config } = result;
|
|
2433
|
+
if (diagnostics.length === 0) return;
|
|
2434
|
+
const report = buildReport(result);
|
|
2435
|
+
const content = (0, node_util.stripVTControlCharacters)([config.name ? `# ${config.name} — ${(/* @__PURE__ */ new Date()).toISOString()}` : `# ${(/* @__PURE__ */ new Date()).toISOString()}`, ...[
|
|
2436
|
+
buildSummarySection(report),
|
|
2437
|
+
buildProblemSection(diagnostics),
|
|
2438
|
+
buildTimingSection(report)
|
|
2439
|
+
].filter((section) => section.length > 0).map((section) => section.join("\n"))].join("\n\n"));
|
|
2440
|
+
const baseName = `${[
|
|
2441
|
+
"kubb",
|
|
2442
|
+
config.name,
|
|
2443
|
+
Date.now()
|
|
2444
|
+
].filter(Boolean).join("-")}.log`;
|
|
2445
|
+
const pathName = (0, node_path.resolve)(node_process.default.cwd(), ".kubb", baseName);
|
|
2446
|
+
await require_usingCtx.write(pathName, `${content}\n`);
|
|
2447
|
+
console.error(`Debug log written to ${(0, node_path.relative)(node_process.default.cwd(), pathName)}`);
|
|
2448
|
+
}
|
|
2449
|
+
});
|
|
2450
|
+
//#endregion
|
|
2451
|
+
//#region src/reporters/jsonReporter.ts
|
|
2452
|
+
/**
|
|
2453
|
+
* The `json` reporter. `report` returns one config's {@link Report}, which {@link createReporter}
|
|
2454
|
+
* buffers, and `drain` writes them as a single pretty-printed JSON array on `kubb:lifecycle:end`.
|
|
2455
|
+
* Buffering keeps a multi-config run one valid JSON document on stdout instead of concatenated
|
|
2456
|
+
* objects that would break `jq .`. The terminal reporter is suppressed while `json` is active so
|
|
2457
|
+
* stdout stays valid JSON.
|
|
2458
|
+
*/
|
|
2459
|
+
const jsonReporter = createReporter({
|
|
2460
|
+
name: "json",
|
|
2461
|
+
report(result) {
|
|
2462
|
+
return buildReport(result);
|
|
2463
|
+
},
|
|
2464
|
+
drain(_context, reports) {
|
|
2465
|
+
node_process.default.stdout.write(`${JSON.stringify(reports, null, 2)}\n`);
|
|
2466
|
+
}
|
|
2467
|
+
});
|
|
2468
|
+
//#endregion
|
|
2469
|
+
//#region src/createRenderer.ts
|
|
2470
|
+
/**
|
|
2471
|
+
* Defines a renderer factory. Renderers turn the generator's return value
|
|
2472
|
+
* (JSX, a template string, a tree of any shape) into `FileNode`s that get
|
|
2473
|
+
* written to disk.
|
|
1293
2474
|
*
|
|
1294
|
-
*
|
|
1295
|
-
*
|
|
1296
|
-
*
|
|
1297
|
-
* name: 'my-logger',
|
|
1298
|
-
* install(context, options) {
|
|
1299
|
-
* context.on('kubb:info', (message) => console.log('ℹ', message))
|
|
1300
|
-
* context.on('kubb:error', (error) => console.error('✗', error.message))
|
|
1301
|
-
* },
|
|
1302
|
-
* })
|
|
1303
|
-
* ```
|
|
2475
|
+
* A renderer can target output formats beyond JSX, for instance a Handlebars
|
|
2476
|
+
* renderer or one that writes binary files. Plugins and generators pick the
|
|
2477
|
+
* renderer to use via the `renderer` field on `defineGenerator`.
|
|
1304
2478
|
*
|
|
1305
|
-
* @example
|
|
2479
|
+
* @example A minimal renderer that wraps a custom runtime
|
|
1306
2480
|
* ```ts
|
|
1307
|
-
*
|
|
1308
|
-
*
|
|
1309
|
-
*
|
|
1310
|
-
*
|
|
1311
|
-
*
|
|
1312
|
-
*
|
|
2481
|
+
* import { createRenderer } from '@kubb/core'
|
|
2482
|
+
*
|
|
2483
|
+
* export const myRenderer = createRenderer(() => {
|
|
2484
|
+
* const runtime = new MyRuntime()
|
|
2485
|
+
* return {
|
|
2486
|
+
* async render(element) {
|
|
2487
|
+
* await runtime.render(element)
|
|
2488
|
+
* },
|
|
2489
|
+
* get files() {
|
|
2490
|
+
* return runtime.files
|
|
2491
|
+
* },
|
|
2492
|
+
* [Symbol.dispose]() {
|
|
2493
|
+
* runtime.dispose()
|
|
2494
|
+
* },
|
|
2495
|
+
* }
|
|
1313
2496
|
* })
|
|
1314
2497
|
* ```
|
|
1315
2498
|
*/
|
|
1316
|
-
function
|
|
1317
|
-
return
|
|
2499
|
+
function createRenderer(factory) {
|
|
2500
|
+
return factory;
|
|
1318
2501
|
}
|
|
1319
2502
|
//#endregion
|
|
1320
|
-
//#region src/
|
|
2503
|
+
//#region src/defineGenerator.ts
|
|
1321
2504
|
/**
|
|
1322
|
-
*
|
|
1323
|
-
*
|
|
1324
|
-
*
|
|
1325
|
-
* Per-build state (such as accumulators) belongs inside the factory closure so each `createKubb` invocation gets its own isolated instance.
|
|
2505
|
+
* Defines a generator: a unit of work that runs during the plugin's AST walk
|
|
2506
|
+
* and produces files. Plugins register generators via `ctx.addGenerator()`
|
|
2507
|
+
* inside `kubb:plugin:setup`.
|
|
1326
2508
|
*
|
|
1327
|
-
*
|
|
2509
|
+
* The returned object is the input as-is, but with `this` types preserved so
|
|
2510
|
+
* `schema`/`operation`/`operations` methods are correctly typed against the
|
|
2511
|
+
* plugin's `PluginFactoryOptions`. Renderer elements and `FileNode[]` returns
|
|
2512
|
+
* are both handled by the runtime, so pick whichever style fits.
|
|
1328
2513
|
*
|
|
1329
|
-
* @example
|
|
1330
|
-
* ```
|
|
1331
|
-
* import {
|
|
2514
|
+
* @example JSX-based schema generator
|
|
2515
|
+
* ```tsx
|
|
2516
|
+
* import { defineGenerator } from '@kubb/core'
|
|
2517
|
+
* import { jsxRenderer } from '@kubb/renderer-jsx'
|
|
1332
2518
|
*
|
|
1333
|
-
*
|
|
1334
|
-
*
|
|
1335
|
-
*
|
|
1336
|
-
*
|
|
1337
|
-
*
|
|
1338
|
-
*
|
|
1339
|
-
*
|
|
2519
|
+
* export const typeGenerator = defineGenerator({
|
|
2520
|
+
* name: 'typescript',
|
|
2521
|
+
* renderer: jsxRenderer,
|
|
2522
|
+
* schema(node, ctx) {
|
|
2523
|
+
* return (
|
|
2524
|
+
* <File path={`${ctx.root}/${node.name}.ts`}>
|
|
2525
|
+
* <Type node={node} resolver={ctx.resolver} />
|
|
2526
|
+
* </File>
|
|
2527
|
+
* )
|
|
1340
2528
|
* },
|
|
1341
|
-
* }))
|
|
1342
|
-
*
|
|
1343
|
-
* // Middleware with options and per-build state
|
|
1344
|
-
* export const prefixMiddleware = defineMiddleware((options: { prefix: string } = { prefix: '' }) => {
|
|
1345
|
-
* const seen = new Set<string>()
|
|
1346
|
-
* return {
|
|
1347
|
-
* name: 'prefix-middleware',
|
|
1348
|
-
* hooks: {
|
|
1349
|
-
* 'kubb:plugin:end'({ plugin }) {
|
|
1350
|
-
* seen.add(`${options.prefix}${plugin.name}`)
|
|
1351
|
-
* },
|
|
1352
|
-
* },
|
|
1353
|
-
* }
|
|
1354
2529
|
* })
|
|
1355
2530
|
* ```
|
|
1356
2531
|
*/
|
|
1357
|
-
function
|
|
1358
|
-
return
|
|
2532
|
+
function defineGenerator(generator) {
|
|
2533
|
+
return generator;
|
|
1359
2534
|
}
|
|
1360
2535
|
//#endregion
|
|
1361
2536
|
//#region src/defineParser.ts
|
|
1362
2537
|
/**
|
|
1363
|
-
*
|
|
2538
|
+
* Wraps a parser factory and returns a function that accepts user options and
|
|
2539
|
+
* yields a typed {@link Parser}. Mirrors {@link definePlugin}: the factory
|
|
2540
|
+
* receives the caller's options, and calling the returned function without
|
|
2541
|
+
* options passes an empty object.
|
|
1364
2542
|
*
|
|
1365
|
-
*
|
|
2543
|
+
* Register the result in the `parsers` array on `defineConfig`, calling it to
|
|
2544
|
+
* apply options (`parserTs({ extension: { '.ts': '.js' } })`).
|
|
1366
2545
|
*
|
|
1367
2546
|
* @example
|
|
1368
2547
|
* ```ts
|
|
1369
2548
|
* import { defineParser } from '@kubb/core'
|
|
2549
|
+
* import { extractStringsFromNodes } from '@kubb/ast'
|
|
1370
2550
|
*
|
|
1371
|
-
* export const
|
|
2551
|
+
* export const parserJson = defineParser((options: { pretty?: boolean } = {}) => ({
|
|
1372
2552
|
* name: 'json',
|
|
1373
2553
|
* extNames: ['.json'],
|
|
1374
2554
|
* parse(file) {
|
|
1375
|
-
* const
|
|
1376
|
-
* return
|
|
2555
|
+
* const source = file.sources.map((source) => extractStringsFromNodes(source.nodes ?? [])).join('\n')
|
|
2556
|
+
* return options.pretty ? JSON.stringify(JSON.parse(source), null, 2) : source
|
|
1377
2557
|
* },
|
|
1378
|
-
*
|
|
2558
|
+
* print(...nodes) {
|
|
2559
|
+
* return nodes.map(String).join('\n')
|
|
2560
|
+
* },
|
|
2561
|
+
* }))
|
|
1379
2562
|
* ```
|
|
1380
2563
|
*/
|
|
1381
|
-
function defineParser(
|
|
1382
|
-
return
|
|
2564
|
+
function defineParser(factory) {
|
|
2565
|
+
return (options) => factory(options ?? {});
|
|
1383
2566
|
}
|
|
1384
2567
|
//#endregion
|
|
1385
2568
|
//#region src/storages/memoryStorage.ts
|
|
@@ -1396,7 +2579,7 @@ function defineParser(parser) {
|
|
|
1396
2579
|
* import { defineConfig } from 'kubb'
|
|
1397
2580
|
*
|
|
1398
2581
|
* export default defineConfig({
|
|
1399
|
-
* input:
|
|
2582
|
+
* input: './petStore.yaml',
|
|
1400
2583
|
* output: { path: './src/gen' },
|
|
1401
2584
|
* storage: memoryStorage(),
|
|
1402
2585
|
* })
|
|
@@ -1432,30 +2615,26 @@ const memoryStorage = createStorage(() => {
|
|
|
1432
2615
|
};
|
|
1433
2616
|
});
|
|
1434
2617
|
//#endregion
|
|
1435
|
-
exports.
|
|
1436
|
-
exports.
|
|
1437
|
-
exports.
|
|
1438
|
-
exports.
|
|
1439
|
-
exports.
|
|
1440
|
-
|
|
1441
|
-
enumerable: true,
|
|
1442
|
-
get: function() {
|
|
1443
|
-
return _kubb_ast;
|
|
1444
|
-
}
|
|
1445
|
-
});
|
|
2618
|
+
exports.Diagnostics = Diagnostics;
|
|
2619
|
+
exports.Hookable = require_usingCtx.Hookable;
|
|
2620
|
+
exports.KubbDriver = KubbDriver;
|
|
2621
|
+
exports.Resolver = Resolver;
|
|
2622
|
+
exports.applyConfigDefaults = applyConfigDefaults;
|
|
2623
|
+
exports.cliReporter = cliReporter;
|
|
1446
2624
|
exports.createAdapter = createAdapter;
|
|
1447
2625
|
exports.createKubb = createKubb;
|
|
1448
2626
|
exports.createRenderer = createRenderer;
|
|
2627
|
+
exports.createReporter = createReporter;
|
|
2628
|
+
exports.createResolver = createResolver;
|
|
1449
2629
|
exports.createStorage = createStorage;
|
|
1450
2630
|
exports.defineGenerator = defineGenerator;
|
|
1451
|
-
exports.defineLogger = defineLogger;
|
|
1452
|
-
exports.defineMiddleware = defineMiddleware;
|
|
1453
2631
|
exports.defineParser = defineParser;
|
|
1454
|
-
exports.definePlugin =
|
|
1455
|
-
exports.
|
|
2632
|
+
exports.definePlugin = definePlugin;
|
|
2633
|
+
exports.fileReporter = fileReporter;
|
|
1456
2634
|
exports.fsStorage = fsStorage;
|
|
1457
|
-
exports.
|
|
1458
|
-
exports.
|
|
2635
|
+
exports.getInputKind = getInputKind;
|
|
2636
|
+
exports.jsonReporter = jsonReporter;
|
|
2637
|
+
exports.logLevel = logLevel;
|
|
1459
2638
|
exports.memoryStorage = memoryStorage;
|
|
1460
2639
|
|
|
1461
2640
|
//# sourceMappingURL=index.cjs.map
|