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