@kubb/core 5.0.0-alpha.35 → 5.0.0-alpha.36
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/dist/PluginDriver-B_65W4fv.js +1677 -0
- package/dist/PluginDriver-B_65W4fv.js.map +1 -0
- package/dist/{PluginDriver-D8lWvtUg.d.ts → PluginDriver-C9iBgYbk.d.ts} +3 -4
- package/dist/PluginDriver-CCdkwR14.cjs +1806 -0
- package/dist/PluginDriver-CCdkwR14.cjs.map +1 -0
- package/dist/hooks.d.ts +1 -1
- package/dist/index.cjs +31 -1696
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.ts +42 -2
- package/dist/index.js +6 -1676
- package/dist/index.js.map +1 -1
- package/dist/mocks.cjs +165 -0
- package/dist/mocks.cjs.map +1 -0
- package/dist/mocks.d.ts +74 -0
- package/dist/mocks.js +159 -0
- package/dist/mocks.js.map +1 -0
- package/package.json +11 -4
- package/src/index.ts +2 -0
- package/src/mocks.ts +234 -0
- package/src/types.ts +1 -2
|
@@ -0,0 +1,1677 @@
|
|
|
1
|
+
import { t as __name } from "./chunk--u3MIqq1.js";
|
|
2
|
+
import path, { basename, extname, resolve } from "node:path";
|
|
3
|
+
import { createFile, isOperationNode, isSchemaNode } from "@kubb/ast";
|
|
4
|
+
import { performance } from "node:perf_hooks";
|
|
5
|
+
import { deflateSync } from "fflate";
|
|
6
|
+
import { x } from "tinyexec";
|
|
7
|
+
//#region ../../internals/utils/src/casing.ts
|
|
8
|
+
/**
|
|
9
|
+
* Shared implementation for camelCase and PascalCase conversion.
|
|
10
|
+
* Splits on common word boundaries (spaces, hyphens, underscores, dots, slashes, colons)
|
|
11
|
+
* and capitalizes each word according to `pascal`.
|
|
12
|
+
*
|
|
13
|
+
* When `pascal` is `true` the first word is also capitalized (PascalCase), otherwise only subsequent words are.
|
|
14
|
+
*/
|
|
15
|
+
function toCamelOrPascal(text, pascal) {
|
|
16
|
+
return text.trim().replace(/([a-z\d])([A-Z])/g, "$1 $2").replace(/([A-Z]+)([A-Z][a-z])/g, "$1 $2").replace(/(\d)([a-z])/g, "$1 $2").split(/[\s\-_./\\:]+/).filter(Boolean).map((word, i) => {
|
|
17
|
+
if (word.length > 1 && word === word.toUpperCase()) return word;
|
|
18
|
+
if (i === 0 && !pascal) return word.charAt(0).toLowerCase() + word.slice(1);
|
|
19
|
+
return word.charAt(0).toUpperCase() + word.slice(1);
|
|
20
|
+
}).join("").replace(/[^a-zA-Z0-9]/g, "");
|
|
21
|
+
}
|
|
22
|
+
/**
|
|
23
|
+
* Splits `text` on `.` and applies `transformPart` to each segment.
|
|
24
|
+
* The last segment receives `isLast = true`, all earlier segments receive `false`.
|
|
25
|
+
* Segments are joined with `/` to form a file path.
|
|
26
|
+
*
|
|
27
|
+
* Only splits on dots followed by a letter so that version numbers
|
|
28
|
+
* embedded in operationIds (e.g. `v2025.0`) are kept intact.
|
|
29
|
+
*/
|
|
30
|
+
function applyToFileParts(text, transformPart) {
|
|
31
|
+
const parts = text.split(/\.(?=[a-zA-Z])/);
|
|
32
|
+
return parts.map((part, i) => transformPart(part, i === parts.length - 1)).join("/");
|
|
33
|
+
}
|
|
34
|
+
/**
|
|
35
|
+
* Converts `text` to camelCase.
|
|
36
|
+
* When `isFile` is `true`, dot-separated segments are each cased independently and joined with `/`.
|
|
37
|
+
*
|
|
38
|
+
* @example
|
|
39
|
+
* camelCase('hello-world') // 'helloWorld'
|
|
40
|
+
* camelCase('pet.petId', { isFile: true }) // 'pet/petId'
|
|
41
|
+
*/
|
|
42
|
+
function camelCase(text, { isFile, prefix = "", suffix = "" } = {}) {
|
|
43
|
+
if (isFile) return applyToFileParts(text, (part, isLast) => camelCase(part, isLast ? {
|
|
44
|
+
prefix,
|
|
45
|
+
suffix
|
|
46
|
+
} : {}));
|
|
47
|
+
return toCamelOrPascal(`${prefix} ${text} ${suffix}`, false);
|
|
48
|
+
}
|
|
49
|
+
/**
|
|
50
|
+
* Converts `text` to PascalCase.
|
|
51
|
+
* When `isFile` is `true`, the last dot-separated segment is PascalCased and earlier segments are camelCased.
|
|
52
|
+
*
|
|
53
|
+
* @example
|
|
54
|
+
* pascalCase('hello-world') // 'HelloWorld'
|
|
55
|
+
* pascalCase('pet.petId', { isFile: true }) // 'pet/PetId'
|
|
56
|
+
*/
|
|
57
|
+
function pascalCase(text, { isFile, prefix = "", suffix = "" } = {}) {
|
|
58
|
+
if (isFile) return applyToFileParts(text, (part, isLast) => isLast ? pascalCase(part, {
|
|
59
|
+
prefix,
|
|
60
|
+
suffix
|
|
61
|
+
}) : camelCase(part));
|
|
62
|
+
return toCamelOrPascal(`${prefix} ${text} ${suffix}`, true);
|
|
63
|
+
}
|
|
64
|
+
//#endregion
|
|
65
|
+
//#region ../../internals/utils/src/string.ts
|
|
66
|
+
/**
|
|
67
|
+
* Strips the file extension from a path or file name.
|
|
68
|
+
* Only removes the last `.ext` segment when the dot is not part of a directory name.
|
|
69
|
+
*
|
|
70
|
+
* @example
|
|
71
|
+
* trimExtName('petStore.ts') // 'petStore'
|
|
72
|
+
* trimExtName('/src/models/pet.ts') // '/src/models/pet'
|
|
73
|
+
* trimExtName('/project.v2/gen/pet.ts') // '/project.v2/gen/pet'
|
|
74
|
+
* trimExtName('noExtension') // 'noExtension'
|
|
75
|
+
*/
|
|
76
|
+
function trimExtName(text) {
|
|
77
|
+
const dotIndex = text.lastIndexOf(".");
|
|
78
|
+
if (dotIndex > 0 && !text.includes("/", dotIndex)) return text.slice(0, dotIndex);
|
|
79
|
+
return text;
|
|
80
|
+
}
|
|
81
|
+
//#endregion
|
|
82
|
+
//#region ../../internals/utils/src/promise.ts
|
|
83
|
+
/** Returns `true` when `result` is a rejected `Promise.allSettled` result with a typed `reason`.
|
|
84
|
+
*
|
|
85
|
+
* @example
|
|
86
|
+
* ```ts
|
|
87
|
+
* const results = await Promise.allSettled([p1, p2])
|
|
88
|
+
* results.filter(isPromiseRejectedResult<Error>).map((r) => r.reason.message)
|
|
89
|
+
* ```
|
|
90
|
+
*/
|
|
91
|
+
function isPromiseRejectedResult(result) {
|
|
92
|
+
return result.status === "rejected";
|
|
93
|
+
}
|
|
94
|
+
//#endregion
|
|
95
|
+
//#region ../../internals/utils/src/reserved.ts
|
|
96
|
+
/**
|
|
97
|
+
* JavaScript and Java reserved words.
|
|
98
|
+
* @link https://github.com/jonschlinkert/reserved/blob/master/index.js
|
|
99
|
+
*/
|
|
100
|
+
const reservedWords = new Set([
|
|
101
|
+
"abstract",
|
|
102
|
+
"arguments",
|
|
103
|
+
"boolean",
|
|
104
|
+
"break",
|
|
105
|
+
"byte",
|
|
106
|
+
"case",
|
|
107
|
+
"catch",
|
|
108
|
+
"char",
|
|
109
|
+
"class",
|
|
110
|
+
"const",
|
|
111
|
+
"continue",
|
|
112
|
+
"debugger",
|
|
113
|
+
"default",
|
|
114
|
+
"delete",
|
|
115
|
+
"do",
|
|
116
|
+
"double",
|
|
117
|
+
"else",
|
|
118
|
+
"enum",
|
|
119
|
+
"eval",
|
|
120
|
+
"export",
|
|
121
|
+
"extends",
|
|
122
|
+
"false",
|
|
123
|
+
"final",
|
|
124
|
+
"finally",
|
|
125
|
+
"float",
|
|
126
|
+
"for",
|
|
127
|
+
"function",
|
|
128
|
+
"goto",
|
|
129
|
+
"if",
|
|
130
|
+
"implements",
|
|
131
|
+
"import",
|
|
132
|
+
"in",
|
|
133
|
+
"instanceof",
|
|
134
|
+
"int",
|
|
135
|
+
"interface",
|
|
136
|
+
"let",
|
|
137
|
+
"long",
|
|
138
|
+
"native",
|
|
139
|
+
"new",
|
|
140
|
+
"null",
|
|
141
|
+
"package",
|
|
142
|
+
"private",
|
|
143
|
+
"protected",
|
|
144
|
+
"public",
|
|
145
|
+
"return",
|
|
146
|
+
"short",
|
|
147
|
+
"static",
|
|
148
|
+
"super",
|
|
149
|
+
"switch",
|
|
150
|
+
"synchronized",
|
|
151
|
+
"this",
|
|
152
|
+
"throw",
|
|
153
|
+
"throws",
|
|
154
|
+
"transient",
|
|
155
|
+
"true",
|
|
156
|
+
"try",
|
|
157
|
+
"typeof",
|
|
158
|
+
"var",
|
|
159
|
+
"void",
|
|
160
|
+
"volatile",
|
|
161
|
+
"while",
|
|
162
|
+
"with",
|
|
163
|
+
"yield",
|
|
164
|
+
"Array",
|
|
165
|
+
"Date",
|
|
166
|
+
"hasOwnProperty",
|
|
167
|
+
"Infinity",
|
|
168
|
+
"isFinite",
|
|
169
|
+
"isNaN",
|
|
170
|
+
"isPrototypeOf",
|
|
171
|
+
"length",
|
|
172
|
+
"Math",
|
|
173
|
+
"name",
|
|
174
|
+
"NaN",
|
|
175
|
+
"Number",
|
|
176
|
+
"Object",
|
|
177
|
+
"prototype",
|
|
178
|
+
"String",
|
|
179
|
+
"toString",
|
|
180
|
+
"undefined",
|
|
181
|
+
"valueOf"
|
|
182
|
+
]);
|
|
183
|
+
/**
|
|
184
|
+
* Prefixes `word` with `_` when it is a reserved JavaScript/Java identifier or starts with a digit.
|
|
185
|
+
*
|
|
186
|
+
* @example
|
|
187
|
+
* ```ts
|
|
188
|
+
* transformReservedWord('class') // '_class'
|
|
189
|
+
* transformReservedWord('42foo') // '_42foo'
|
|
190
|
+
* transformReservedWord('status') // 'status'
|
|
191
|
+
* ```
|
|
192
|
+
*/
|
|
193
|
+
function transformReservedWord(word) {
|
|
194
|
+
const firstChar = word.charCodeAt(0);
|
|
195
|
+
if (word && (reservedWords.has(word) || firstChar >= 48 && firstChar <= 57)) return `_${word}`;
|
|
196
|
+
return word;
|
|
197
|
+
}
|
|
198
|
+
/**
|
|
199
|
+
* Returns `true` when `name` is a syntactically valid JavaScript variable name.
|
|
200
|
+
*
|
|
201
|
+
* @example
|
|
202
|
+
* ```ts
|
|
203
|
+
* isValidVarName('status') // true
|
|
204
|
+
* isValidVarName('class') // false (reserved word)
|
|
205
|
+
* isValidVarName('42foo') // false (starts with digit)
|
|
206
|
+
* ```
|
|
207
|
+
*/
|
|
208
|
+
function isValidVarName(name) {
|
|
209
|
+
try {
|
|
210
|
+
new Function(`var ${name}`);
|
|
211
|
+
} catch {
|
|
212
|
+
return false;
|
|
213
|
+
}
|
|
214
|
+
return true;
|
|
215
|
+
}
|
|
216
|
+
//#endregion
|
|
217
|
+
//#region src/constants.ts
|
|
218
|
+
/**
|
|
219
|
+
* Base URL for the Kubb Studio web app.
|
|
220
|
+
*/
|
|
221
|
+
const DEFAULT_STUDIO_URL = "https://studio.kubb.dev";
|
|
222
|
+
/**
|
|
223
|
+
* File name used for generated barrel (index) files.
|
|
224
|
+
*/
|
|
225
|
+
const BARREL_FILENAME = "index.ts";
|
|
226
|
+
/**
|
|
227
|
+
* Default banner style written at the top of every generated file.
|
|
228
|
+
*/
|
|
229
|
+
const DEFAULT_BANNER = "simple";
|
|
230
|
+
/**
|
|
231
|
+
* Default file-extension mapping used when no explicit mapping is configured.
|
|
232
|
+
*/
|
|
233
|
+
const DEFAULT_EXTENSION = { ".ts": ".ts" };
|
|
234
|
+
/**
|
|
235
|
+
* Numeric log-level thresholds used internally to compare verbosity.
|
|
236
|
+
*
|
|
237
|
+
* Higher numbers are more verbose.
|
|
238
|
+
*/
|
|
239
|
+
const logLevel = {
|
|
240
|
+
silent: Number.NEGATIVE_INFINITY,
|
|
241
|
+
error: 0,
|
|
242
|
+
warn: 1,
|
|
243
|
+
info: 3,
|
|
244
|
+
verbose: 4,
|
|
245
|
+
debug: 5
|
|
246
|
+
};
|
|
247
|
+
/**
|
|
248
|
+
* CLI command descriptors for each supported linter.
|
|
249
|
+
*
|
|
250
|
+
* Each entry contains the executable `command`, an `args` factory that maps an
|
|
251
|
+
* output path to the correct argument list, and an `errorMessage` shown when
|
|
252
|
+
* the linter is not found.
|
|
253
|
+
*/
|
|
254
|
+
const linters = {
|
|
255
|
+
eslint: {
|
|
256
|
+
command: "eslint",
|
|
257
|
+
args: (outputPath) => [outputPath, "--fix"],
|
|
258
|
+
errorMessage: "Eslint not found"
|
|
259
|
+
},
|
|
260
|
+
biome: {
|
|
261
|
+
command: "biome",
|
|
262
|
+
args: (outputPath) => [
|
|
263
|
+
"lint",
|
|
264
|
+
"--fix",
|
|
265
|
+
outputPath
|
|
266
|
+
],
|
|
267
|
+
errorMessage: "Biome not found"
|
|
268
|
+
},
|
|
269
|
+
oxlint: {
|
|
270
|
+
command: "oxlint",
|
|
271
|
+
args: (outputPath) => ["--fix", outputPath],
|
|
272
|
+
errorMessage: "Oxlint not found"
|
|
273
|
+
}
|
|
274
|
+
};
|
|
275
|
+
/**
|
|
276
|
+
* CLI command descriptors for each supported code formatter.
|
|
277
|
+
*
|
|
278
|
+
* Each entry contains the executable `command`, an `args` factory that maps an
|
|
279
|
+
* output path to the correct argument list, and an `errorMessage` shown when
|
|
280
|
+
* the formatter is not found.
|
|
281
|
+
*/
|
|
282
|
+
const formatters = {
|
|
283
|
+
prettier: {
|
|
284
|
+
command: "prettier",
|
|
285
|
+
args: (outputPath) => [
|
|
286
|
+
"--ignore-unknown",
|
|
287
|
+
"--write",
|
|
288
|
+
outputPath
|
|
289
|
+
],
|
|
290
|
+
errorMessage: "Prettier not found"
|
|
291
|
+
},
|
|
292
|
+
biome: {
|
|
293
|
+
command: "biome",
|
|
294
|
+
args: (outputPath) => [
|
|
295
|
+
"format",
|
|
296
|
+
"--write",
|
|
297
|
+
outputPath
|
|
298
|
+
],
|
|
299
|
+
errorMessage: "Biome not found"
|
|
300
|
+
},
|
|
301
|
+
oxfmt: {
|
|
302
|
+
command: "oxfmt",
|
|
303
|
+
args: (outputPath) => [outputPath],
|
|
304
|
+
errorMessage: "Oxfmt not found"
|
|
305
|
+
}
|
|
306
|
+
};
|
|
307
|
+
//#endregion
|
|
308
|
+
//#region ../../node_modules/.pnpm/yocto-queue@1.2.2/node_modules/yocto-queue/index.js
|
|
309
|
+
var Node$1 = class {
|
|
310
|
+
static {
|
|
311
|
+
__name(this, "Node");
|
|
312
|
+
}
|
|
313
|
+
value;
|
|
314
|
+
next;
|
|
315
|
+
constructor(value) {
|
|
316
|
+
this.value = value;
|
|
317
|
+
}
|
|
318
|
+
};
|
|
319
|
+
var Queue = class {
|
|
320
|
+
#head;
|
|
321
|
+
#tail;
|
|
322
|
+
#size;
|
|
323
|
+
constructor() {
|
|
324
|
+
this.clear();
|
|
325
|
+
}
|
|
326
|
+
enqueue(value) {
|
|
327
|
+
const node = new Node$1(value);
|
|
328
|
+
if (this.#head) {
|
|
329
|
+
this.#tail.next = node;
|
|
330
|
+
this.#tail = node;
|
|
331
|
+
} else {
|
|
332
|
+
this.#head = node;
|
|
333
|
+
this.#tail = node;
|
|
334
|
+
}
|
|
335
|
+
this.#size++;
|
|
336
|
+
}
|
|
337
|
+
dequeue() {
|
|
338
|
+
const current = this.#head;
|
|
339
|
+
if (!current) return;
|
|
340
|
+
this.#head = this.#head.next;
|
|
341
|
+
this.#size--;
|
|
342
|
+
if (!this.#head) this.#tail = void 0;
|
|
343
|
+
return current.value;
|
|
344
|
+
}
|
|
345
|
+
peek() {
|
|
346
|
+
if (!this.#head) return;
|
|
347
|
+
return this.#head.value;
|
|
348
|
+
}
|
|
349
|
+
clear() {
|
|
350
|
+
this.#head = void 0;
|
|
351
|
+
this.#tail = void 0;
|
|
352
|
+
this.#size = 0;
|
|
353
|
+
}
|
|
354
|
+
get size() {
|
|
355
|
+
return this.#size;
|
|
356
|
+
}
|
|
357
|
+
*[Symbol.iterator]() {
|
|
358
|
+
let current = this.#head;
|
|
359
|
+
while (current) {
|
|
360
|
+
yield current.value;
|
|
361
|
+
current = current.next;
|
|
362
|
+
}
|
|
363
|
+
}
|
|
364
|
+
*drain() {
|
|
365
|
+
while (this.#head) yield this.dequeue();
|
|
366
|
+
}
|
|
367
|
+
};
|
|
368
|
+
//#endregion
|
|
369
|
+
//#region ../../node_modules/.pnpm/p-limit@7.3.0/node_modules/p-limit/index.js
|
|
370
|
+
function pLimit(concurrency) {
|
|
371
|
+
let rejectOnClear = false;
|
|
372
|
+
if (typeof concurrency === "object") ({concurrency, rejectOnClear = false} = concurrency);
|
|
373
|
+
validateConcurrency(concurrency);
|
|
374
|
+
if (typeof rejectOnClear !== "boolean") throw new TypeError("Expected `rejectOnClear` to be a boolean");
|
|
375
|
+
const queue = new Queue();
|
|
376
|
+
let activeCount = 0;
|
|
377
|
+
const resumeNext = () => {
|
|
378
|
+
if (activeCount < concurrency && queue.size > 0) {
|
|
379
|
+
activeCount++;
|
|
380
|
+
queue.dequeue().run();
|
|
381
|
+
}
|
|
382
|
+
};
|
|
383
|
+
const next = () => {
|
|
384
|
+
activeCount--;
|
|
385
|
+
resumeNext();
|
|
386
|
+
};
|
|
387
|
+
const run = async (function_, resolve, arguments_) => {
|
|
388
|
+
const result = (async () => function_(...arguments_))();
|
|
389
|
+
resolve(result);
|
|
390
|
+
try {
|
|
391
|
+
await result;
|
|
392
|
+
} catch {}
|
|
393
|
+
next();
|
|
394
|
+
};
|
|
395
|
+
const enqueue = (function_, resolve, reject, arguments_) => {
|
|
396
|
+
const queueItem = { reject };
|
|
397
|
+
new Promise((internalResolve) => {
|
|
398
|
+
queueItem.run = internalResolve;
|
|
399
|
+
queue.enqueue(queueItem);
|
|
400
|
+
}).then(run.bind(void 0, function_, resolve, arguments_));
|
|
401
|
+
if (activeCount < concurrency) resumeNext();
|
|
402
|
+
};
|
|
403
|
+
const generator = (function_, ...arguments_) => new Promise((resolve, reject) => {
|
|
404
|
+
enqueue(function_, resolve, reject, arguments_);
|
|
405
|
+
});
|
|
406
|
+
Object.defineProperties(generator, {
|
|
407
|
+
activeCount: { get: () => activeCount },
|
|
408
|
+
pendingCount: { get: () => queue.size },
|
|
409
|
+
clearQueue: { value() {
|
|
410
|
+
if (!rejectOnClear) {
|
|
411
|
+
queue.clear();
|
|
412
|
+
return;
|
|
413
|
+
}
|
|
414
|
+
const abortError = AbortSignal.abort().reason;
|
|
415
|
+
while (queue.size > 0) queue.dequeue().reject(abortError);
|
|
416
|
+
} },
|
|
417
|
+
concurrency: {
|
|
418
|
+
get: () => concurrency,
|
|
419
|
+
set(newConcurrency) {
|
|
420
|
+
validateConcurrency(newConcurrency);
|
|
421
|
+
concurrency = newConcurrency;
|
|
422
|
+
queueMicrotask(() => {
|
|
423
|
+
while (activeCount < concurrency && queue.size > 0) resumeNext();
|
|
424
|
+
});
|
|
425
|
+
}
|
|
426
|
+
},
|
|
427
|
+
map: { async value(iterable, function_) {
|
|
428
|
+
const promises = Array.from(iterable, (value, index) => this(function_, value, index));
|
|
429
|
+
return Promise.all(promises);
|
|
430
|
+
} }
|
|
431
|
+
});
|
|
432
|
+
return generator;
|
|
433
|
+
}
|
|
434
|
+
function validateConcurrency(concurrency) {
|
|
435
|
+
if (!((Number.isInteger(concurrency) || concurrency === Number.POSITIVE_INFINITY) && concurrency > 0)) throw new TypeError("Expected `concurrency` to be a number from 1 and up");
|
|
436
|
+
}
|
|
437
|
+
//#endregion
|
|
438
|
+
//#region src/definePlugin.ts
|
|
439
|
+
/**
|
|
440
|
+
* Returns `true` when `plugin` is a hook-style plugin created with `definePlugin`.
|
|
441
|
+
*
|
|
442
|
+
* Used by `PluginDriver` to distinguish hook-style plugins from legacy `createPlugin` plugins
|
|
443
|
+
* so it can normalize them and register their handlers on the `AsyncEventEmitter`.
|
|
444
|
+
*/
|
|
445
|
+
function isHookStylePlugin(plugin) {
|
|
446
|
+
return typeof plugin === "object" && plugin !== null && "hooks" in plugin;
|
|
447
|
+
}
|
|
448
|
+
/**
|
|
449
|
+
* Creates a plugin factory using the new hook-style (`hooks:`) API.
|
|
450
|
+
*
|
|
451
|
+
* The returned factory is called with optional options and produces a `HookStylePlugin`
|
|
452
|
+
* that coexists with plugins created via the legacy `createPlugin` API in the same
|
|
453
|
+
* `kubb.config.ts`.
|
|
454
|
+
*
|
|
455
|
+
* Lifecycle handlers are registered on the `PluginDriver`'s `AsyncEventEmitter`, enabling
|
|
456
|
+
* both the plugin's own handlers and external tooling (CLI, devtools) to observe every event.
|
|
457
|
+
*
|
|
458
|
+
* @example
|
|
459
|
+
* ```ts
|
|
460
|
+
* // With PluginFactoryOptions (recommended for real plugins)
|
|
461
|
+
* export const pluginTs = definePlugin<PluginTs>((options) => ({
|
|
462
|
+
* name: 'plugin-ts',
|
|
463
|
+
* hooks: {
|
|
464
|
+
* 'kubb:plugin:setup'(ctx) {
|
|
465
|
+
* ctx.setResolver(resolverTs) // typed as Partial<ResolverTs>
|
|
466
|
+
* },
|
|
467
|
+
* },
|
|
468
|
+
* }))
|
|
469
|
+
* ```
|
|
470
|
+
*/
|
|
471
|
+
function definePlugin(factory) {
|
|
472
|
+
return (options) => factory(options ?? {});
|
|
473
|
+
}
|
|
474
|
+
//#endregion
|
|
475
|
+
//#region src/defineResolver.ts
|
|
476
|
+
/**
|
|
477
|
+
* Checks if an operation matches a pattern for a given filter type (`tag`, `operationId`, `path`, `method`).
|
|
478
|
+
*/
|
|
479
|
+
function matchesOperationPattern(node, type, pattern) {
|
|
480
|
+
switch (type) {
|
|
481
|
+
case "tag": return node.tags.some((tag) => !!tag.match(pattern));
|
|
482
|
+
case "operationId": return !!node.operationId.match(pattern);
|
|
483
|
+
case "path": return !!node.path.match(pattern);
|
|
484
|
+
case "method": return !!node.method.toLowerCase().match(pattern);
|
|
485
|
+
case "contentType": return !!node.requestBody?.contentType?.match(pattern);
|
|
486
|
+
default: return false;
|
|
487
|
+
}
|
|
488
|
+
}
|
|
489
|
+
/**
|
|
490
|
+
* Checks if a schema matches a pattern for a given filter type (`schemaName`).
|
|
491
|
+
*
|
|
492
|
+
* Returns `null` when the filter type doesn't apply to schemas.
|
|
493
|
+
*/
|
|
494
|
+
function matchesSchemaPattern(node, type, pattern) {
|
|
495
|
+
switch (type) {
|
|
496
|
+
case "schemaName": return node.name ? !!node.name.match(pattern) : false;
|
|
497
|
+
default: return null;
|
|
498
|
+
}
|
|
499
|
+
}
|
|
500
|
+
/**
|
|
501
|
+
* Default name resolver used by `defineResolver`.
|
|
502
|
+
*
|
|
503
|
+
* - `camelCase` for `function` and `file` types.
|
|
504
|
+
* - `PascalCase` for `type`.
|
|
505
|
+
* - `camelCase` for everything else.
|
|
506
|
+
*/
|
|
507
|
+
function defaultResolver(name, type) {
|
|
508
|
+
let resolvedName = camelCase(name);
|
|
509
|
+
if (type === "file" || type === "function") resolvedName = camelCase(name, { isFile: type === "file" });
|
|
510
|
+
if (type === "type") resolvedName = pascalCase(name);
|
|
511
|
+
return resolvedName;
|
|
512
|
+
}
|
|
513
|
+
/**
|
|
514
|
+
* Default option resolver — applies include/exclude filters and merges matching override options.
|
|
515
|
+
*
|
|
516
|
+
* Returns `null` when the node is filtered out by an `exclude` rule or not matched by any `include` rule.
|
|
517
|
+
*
|
|
518
|
+
* @example Include/exclude filtering
|
|
519
|
+
* ```ts
|
|
520
|
+
* const options = defaultResolveOptions(operationNode, {
|
|
521
|
+
* options: { output: 'types' },
|
|
522
|
+
* exclude: [{ type: 'tag', pattern: 'internal' }],
|
|
523
|
+
* })
|
|
524
|
+
* // → null when node has tag 'internal'
|
|
525
|
+
* ```
|
|
526
|
+
*
|
|
527
|
+
* @example Override merging
|
|
528
|
+
* ```ts
|
|
529
|
+
* const options = defaultResolveOptions(operationNode, {
|
|
530
|
+
* options: { enumType: 'asConst' },
|
|
531
|
+
* override: [{ type: 'operationId', pattern: 'listPets', options: { enumType: 'enum' } }],
|
|
532
|
+
* })
|
|
533
|
+
* // → { enumType: 'enum' } when operationId matches
|
|
534
|
+
* ```
|
|
535
|
+
*/
|
|
536
|
+
function defaultResolveOptions(node, { options, exclude = [], include, override = [] }) {
|
|
537
|
+
if (isOperationNode(node)) {
|
|
538
|
+
if (exclude.some(({ type, pattern }) => matchesOperationPattern(node, type, pattern))) return null;
|
|
539
|
+
if (include && !include.some(({ type, pattern }) => matchesOperationPattern(node, type, pattern))) return null;
|
|
540
|
+
const overrideOptions = override.find(({ type, pattern }) => matchesOperationPattern(node, type, pattern))?.options;
|
|
541
|
+
return {
|
|
542
|
+
...options,
|
|
543
|
+
...overrideOptions
|
|
544
|
+
};
|
|
545
|
+
}
|
|
546
|
+
if (isSchemaNode(node)) {
|
|
547
|
+
if (exclude.some(({ type, pattern }) => matchesSchemaPattern(node, type, pattern) === true)) return null;
|
|
548
|
+
if (include) {
|
|
549
|
+
const applicable = include.map(({ type, pattern }) => matchesSchemaPattern(node, type, pattern)).filter((r) => r !== null);
|
|
550
|
+
if (applicable.length > 0 && !applicable.includes(true)) return null;
|
|
551
|
+
}
|
|
552
|
+
const overrideOptions = override.find(({ type, pattern }) => matchesSchemaPattern(node, type, pattern) === true)?.options;
|
|
553
|
+
return {
|
|
554
|
+
...options,
|
|
555
|
+
...overrideOptions
|
|
556
|
+
};
|
|
557
|
+
}
|
|
558
|
+
return options;
|
|
559
|
+
}
|
|
560
|
+
/**
|
|
561
|
+
* Default path resolver used by `defineResolver`.
|
|
562
|
+
*
|
|
563
|
+
* - Returns the output directory in `single` mode.
|
|
564
|
+
* - Resolves into a tag- or path-based subdirectory when `group` and a `tag`/`path` value are provided.
|
|
565
|
+
* - Falls back to a flat `output/baseName` path otherwise.
|
|
566
|
+
*
|
|
567
|
+
* A custom `group.name` function overrides the default subdirectory naming.
|
|
568
|
+
* For `tag` groups the default is `${camelCase(tag)}Controller`.
|
|
569
|
+
* For `path` groups the default is the first path segment after `/`.
|
|
570
|
+
*
|
|
571
|
+
* @example Flat output
|
|
572
|
+
* ```ts
|
|
573
|
+
* defaultResolvePath({ baseName: 'petTypes.ts' }, { root: '/src', output: { path: 'types' } })
|
|
574
|
+
* // → '/src/types/petTypes.ts'
|
|
575
|
+
* ```
|
|
576
|
+
*
|
|
577
|
+
* @example Tag-based grouping
|
|
578
|
+
* ```ts
|
|
579
|
+
* defaultResolvePath(
|
|
580
|
+
* { baseName: 'petTypes.ts', tag: 'pets' },
|
|
581
|
+
* { root: '/src', output: { path: 'types' }, group: { type: 'tag' } },
|
|
582
|
+
* )
|
|
583
|
+
* // → '/src/types/petsController/petTypes.ts'
|
|
584
|
+
* ```
|
|
585
|
+
*
|
|
586
|
+
* @example Path-based grouping
|
|
587
|
+
* ```ts
|
|
588
|
+
* defaultResolvePath(
|
|
589
|
+
* { baseName: 'petTypes.ts', path: '/pets/list' },
|
|
590
|
+
* { root: '/src', output: { path: 'types' }, group: { type: 'path' } },
|
|
591
|
+
* )
|
|
592
|
+
* // → '/src/types/pets/petTypes.ts'
|
|
593
|
+
* ```
|
|
594
|
+
*
|
|
595
|
+
* @example Single-file mode
|
|
596
|
+
* ```ts
|
|
597
|
+
* defaultResolvePath(
|
|
598
|
+
* { baseName: 'petTypes.ts', pathMode: 'single' },
|
|
599
|
+
* { root: '/src', output: { path: 'types' } },
|
|
600
|
+
* )
|
|
601
|
+
* // → '/src/types'
|
|
602
|
+
* ```
|
|
603
|
+
*/
|
|
604
|
+
function defaultResolvePath({ baseName, pathMode, tag, path: groupPath }, { root, output, group }) {
|
|
605
|
+
if ((pathMode ?? getMode(path.resolve(root, output.path))) === "single") return path.resolve(root, output.path);
|
|
606
|
+
if (group && (groupPath || tag)) return path.resolve(root, output.path, group.name({ group: group.type === "path" ? groupPath : tag }), baseName);
|
|
607
|
+
return path.resolve(root, output.path, baseName);
|
|
608
|
+
}
|
|
609
|
+
/**
|
|
610
|
+
* Default file resolver used by `defineResolver`.
|
|
611
|
+
*
|
|
612
|
+
* Resolves a `FileNode` by combining name resolution (`resolver.default`) with
|
|
613
|
+
* path resolution (`resolver.resolvePath`). The resolved file always has empty
|
|
614
|
+
* `sources`, `imports`, and `exports` arrays — consumers populate those separately.
|
|
615
|
+
*
|
|
616
|
+
* In `single` mode the name is omitted and the file sits directly in the output directory.
|
|
617
|
+
*
|
|
618
|
+
* @example Resolve a schema file
|
|
619
|
+
* ```ts
|
|
620
|
+
* const file = defaultResolveFile.call(resolver,
|
|
621
|
+
* { name: 'pet', extname: '.ts' },
|
|
622
|
+
* { root: '/src', output: { path: 'types' } },
|
|
623
|
+
* )
|
|
624
|
+
* // → { baseName: 'pet.ts', path: '/src/types/pet.ts', sources: [], ... }
|
|
625
|
+
* ```
|
|
626
|
+
*
|
|
627
|
+
* @example Resolve an operation file with tag grouping
|
|
628
|
+
* ```ts
|
|
629
|
+
* const file = defaultResolveFile.call(resolver,
|
|
630
|
+
* { name: 'listPets', extname: '.ts', tag: 'pets' },
|
|
631
|
+
* { root: '/src', output: { path: 'types' }, group: { type: 'tag' } },
|
|
632
|
+
* )
|
|
633
|
+
* // → { baseName: 'listPets.ts', path: '/src/types/petsController/listPets.ts', ... }
|
|
634
|
+
* ```
|
|
635
|
+
*/
|
|
636
|
+
function defaultResolveFile({ name, extname, tag, path: groupPath }, context) {
|
|
637
|
+
const pathMode = getMode(path.resolve(context.root, context.output.path));
|
|
638
|
+
const baseName = `${pathMode === "single" ? "" : this.default(name, "file")}${extname}`;
|
|
639
|
+
const filePath = this.resolvePath({
|
|
640
|
+
baseName,
|
|
641
|
+
pathMode,
|
|
642
|
+
tag,
|
|
643
|
+
path: groupPath
|
|
644
|
+
}, context);
|
|
645
|
+
return createFile({
|
|
646
|
+
path: filePath,
|
|
647
|
+
baseName: path.basename(filePath),
|
|
648
|
+
meta: { pluginName: this.pluginName },
|
|
649
|
+
sources: [],
|
|
650
|
+
imports: [],
|
|
651
|
+
exports: []
|
|
652
|
+
});
|
|
653
|
+
}
|
|
654
|
+
/**
|
|
655
|
+
* Generates the default "Generated by Kubb" banner from config and optional node metadata.
|
|
656
|
+
*/
|
|
657
|
+
function buildDefaultBanner({ title, description, version, config }) {
|
|
658
|
+
try {
|
|
659
|
+
let source = "";
|
|
660
|
+
if (Array.isArray(config.input)) {
|
|
661
|
+
const first = config.input[0];
|
|
662
|
+
if (first && "path" in first) source = path.basename(first.path);
|
|
663
|
+
} else if ("path" in config.input) source = path.basename(config.input.path);
|
|
664
|
+
else if ("data" in config.input) source = "text content";
|
|
665
|
+
let banner = "/**\n* Generated by Kubb (https://kubb.dev/).\n* Do not edit manually.\n";
|
|
666
|
+
if (config.output.defaultBanner === "simple") {
|
|
667
|
+
banner += "*/\n";
|
|
668
|
+
return banner;
|
|
669
|
+
}
|
|
670
|
+
if (source) banner += `* Source: ${source}\n`;
|
|
671
|
+
if (title) banner += `* Title: ${title}\n`;
|
|
672
|
+
if (description) {
|
|
673
|
+
const formattedDescription = description.replace(/\n/gm, "\n* ");
|
|
674
|
+
banner += `* Description: ${formattedDescription}\n`;
|
|
675
|
+
}
|
|
676
|
+
if (version) banner += `* OpenAPI spec version: ${version}\n`;
|
|
677
|
+
banner += "*/\n";
|
|
678
|
+
return banner;
|
|
679
|
+
} catch (_error) {
|
|
680
|
+
return "/**\n* Generated by Kubb (https://kubb.dev/).\n* Do not edit manually.\n*/";
|
|
681
|
+
}
|
|
682
|
+
}
|
|
683
|
+
/**
|
|
684
|
+
* Default banner resolver — returns the banner string for a generated file.
|
|
685
|
+
*
|
|
686
|
+
* A user-supplied `output.banner` overrides the default Kubb "Generated by Kubb" notice.
|
|
687
|
+
* When no `output.banner` is set, the Kubb notice is used (including `title` and `version`
|
|
688
|
+
* from the OAS spec when a `node` is provided).
|
|
689
|
+
*
|
|
690
|
+
* - When `output.banner` is a function and `node` is provided, returns `output.banner(node)`.
|
|
691
|
+
* - When `output.banner` is a function and `node` is absent, falls back to the Kubb notice.
|
|
692
|
+
* - When `output.banner` is a string, returns it directly.
|
|
693
|
+
* - When `config.output.defaultBanner` is `false`, returns `undefined`.
|
|
694
|
+
* - Otherwise returns the Kubb "Generated by Kubb" notice.
|
|
695
|
+
*
|
|
696
|
+
* @example String banner overrides default
|
|
697
|
+
* ```ts
|
|
698
|
+
* defaultResolveBanner(undefined, { output: { banner: '// my banner' }, config })
|
|
699
|
+
* // → '// my banner'
|
|
700
|
+
* ```
|
|
701
|
+
*
|
|
702
|
+
* @example Function banner with node
|
|
703
|
+
* ```ts
|
|
704
|
+
* defaultResolveBanner(inputNode, { output: { banner: (node) => `// v${node.version}` }, config })
|
|
705
|
+
* // → '// v3.0.0'
|
|
706
|
+
* ```
|
|
707
|
+
*
|
|
708
|
+
* @example No user banner — Kubb notice with OAS metadata
|
|
709
|
+
* ```ts
|
|
710
|
+
* defaultResolveBanner(inputNode, { config })
|
|
711
|
+
* // → '/** Generated by Kubb ... Title: Pet Store ... *\/'
|
|
712
|
+
* ```
|
|
713
|
+
*
|
|
714
|
+
* @example Disabled default banner
|
|
715
|
+
* ```ts
|
|
716
|
+
* defaultResolveBanner(undefined, { config: { output: { defaultBanner: false }, ...config } })
|
|
717
|
+
* // → undefined
|
|
718
|
+
* ```
|
|
719
|
+
*/
|
|
720
|
+
function defaultResolveBanner(node, { output, config }) {
|
|
721
|
+
if (typeof output?.banner === "function") return output.banner(node);
|
|
722
|
+
if (typeof output?.banner === "string") return output.banner;
|
|
723
|
+
if (config.output.defaultBanner === false) return;
|
|
724
|
+
return buildDefaultBanner({
|
|
725
|
+
title: node?.meta?.title,
|
|
726
|
+
version: node?.meta?.version,
|
|
727
|
+
config
|
|
728
|
+
});
|
|
729
|
+
}
|
|
730
|
+
/**
|
|
731
|
+
* Default footer resolver — returns the footer string for a generated file.
|
|
732
|
+
*
|
|
733
|
+
* - When `output.footer` is a function and `node` is provided, calls it with the node.
|
|
734
|
+
* - When `output.footer` is a function and `node` is absent, returns `undefined`.
|
|
735
|
+
* - When `output.footer` is a string, returns it directly.
|
|
736
|
+
* - Otherwise returns `undefined`.
|
|
737
|
+
*
|
|
738
|
+
* @example String footer
|
|
739
|
+
* ```ts
|
|
740
|
+
* defaultResolveFooter(undefined, { output: { footer: '// end of file' }, config })
|
|
741
|
+
* // → '// end of file'
|
|
742
|
+
* ```
|
|
743
|
+
*
|
|
744
|
+
* @example Function footer with node
|
|
745
|
+
* ```ts
|
|
746
|
+
* defaultResolveFooter(inputNode, { output: { footer: (node) => `// ${node.title}` }, config })
|
|
747
|
+
* // → '// Pet Store'
|
|
748
|
+
* ```
|
|
749
|
+
*/
|
|
750
|
+
function defaultResolveFooter(node, { output }) {
|
|
751
|
+
if (typeof output?.footer === "function") return node ? output.footer(node) : void 0;
|
|
752
|
+
if (typeof output?.footer === "string") return output.footer;
|
|
753
|
+
}
|
|
754
|
+
/**
|
|
755
|
+
* Defines a resolver for a plugin, injecting built-in defaults for name casing,
|
|
756
|
+
* include/exclude/override filtering, path resolution, and file construction.
|
|
757
|
+
*
|
|
758
|
+
* All four defaults can be overridden by providing them in the builder function:
|
|
759
|
+
* - `default` — name casing strategy (camelCase / PascalCase)
|
|
760
|
+
* - `resolveOptions` — include/exclude/override filtering
|
|
761
|
+
* - `resolvePath` — output path computation
|
|
762
|
+
* - `resolveFile` — full `FileNode` construction
|
|
763
|
+
*
|
|
764
|
+
* Methods in the builder have access to `this` (the full resolver object), so they
|
|
765
|
+
* can call other resolver methods without circular imports.
|
|
766
|
+
*
|
|
767
|
+
* @example Basic resolver with naming helpers
|
|
768
|
+
* ```ts
|
|
769
|
+
* export const resolver = defineResolver<PluginTs>(() => ({
|
|
770
|
+
* name: 'default',
|
|
771
|
+
* resolveName(node) {
|
|
772
|
+
* return this.default(node.name, 'function')
|
|
773
|
+
* },
|
|
774
|
+
* resolveTypedName(node) {
|
|
775
|
+
* return this.default(node.name, 'type')
|
|
776
|
+
* },
|
|
777
|
+
* }))
|
|
778
|
+
* ```
|
|
779
|
+
*
|
|
780
|
+
* @example Override resolvePath for a custom output structure
|
|
781
|
+
* ```ts
|
|
782
|
+
* export const resolver = defineResolver<PluginTs>(() => ({
|
|
783
|
+
* name: 'custom',
|
|
784
|
+
* resolvePath({ baseName }, { root, output }) {
|
|
785
|
+
* return path.resolve(root, output.path, 'generated', baseName)
|
|
786
|
+
* },
|
|
787
|
+
* }))
|
|
788
|
+
* ```
|
|
789
|
+
*
|
|
790
|
+
* @example Use this.default inside a helper
|
|
791
|
+
* ```ts
|
|
792
|
+
* export const resolver = defineResolver<PluginTs>(() => ({
|
|
793
|
+
* name: 'default',
|
|
794
|
+
* resolveParamName(node, param) {
|
|
795
|
+
* return this.default(`${node.operationId} ${param.in} ${param.name}`, 'type')
|
|
796
|
+
* },
|
|
797
|
+
* }))
|
|
798
|
+
* ```
|
|
799
|
+
*/
|
|
800
|
+
function defineResolver(build) {
|
|
801
|
+
return {
|
|
802
|
+
default: defaultResolver,
|
|
803
|
+
resolveOptions: defaultResolveOptions,
|
|
804
|
+
resolvePath: defaultResolvePath,
|
|
805
|
+
resolveFile: defaultResolveFile,
|
|
806
|
+
resolveBanner: defaultResolveBanner,
|
|
807
|
+
resolveFooter: defaultResolveFooter,
|
|
808
|
+
...build()
|
|
809
|
+
};
|
|
810
|
+
}
|
|
811
|
+
//#endregion
|
|
812
|
+
//#region src/devtools.ts
|
|
813
|
+
/**
|
|
814
|
+
* Encodes an `InputNode` as a compressed, URL-safe string.
|
|
815
|
+
*
|
|
816
|
+
* The JSON representation is deflate-compressed with {@link deflateSync} before
|
|
817
|
+
* base64url encoding, which typically reduces payload size by 70–80 % and
|
|
818
|
+
* keeps URLs well within browser and server path-length limits.
|
|
819
|
+
*
|
|
820
|
+
* Use {@link decodeAst} to reverse.
|
|
821
|
+
*/
|
|
822
|
+
function encodeAst(input) {
|
|
823
|
+
const compressed = deflateSync(new TextEncoder().encode(JSON.stringify(input)));
|
|
824
|
+
return Buffer.from(compressed).toString("base64url");
|
|
825
|
+
}
|
|
826
|
+
/**
|
|
827
|
+
* Constructs the Kubb Studio URL for the given `InputNode`.
|
|
828
|
+
* When `options.ast` is `true`, navigates to the AST inspector (`/ast`).
|
|
829
|
+
* The `input` is encoded and attached as the `?root=` query parameter so Studio
|
|
830
|
+
* can decode and render it without a round-trip to any server.
|
|
831
|
+
*/
|
|
832
|
+
function getStudioUrl(input, studioUrl, options = {}) {
|
|
833
|
+
return `${studioUrl.replace(/\/$/, "")}${options.ast ? "/ast" : ""}?root=${encodeAst(input)}`;
|
|
834
|
+
}
|
|
835
|
+
/**
|
|
836
|
+
* Opens the Kubb Studio URL for the given `InputNode` in the default browser —
|
|
837
|
+
*
|
|
838
|
+
* Falls back to printing the URL if the browser cannot be launched.
|
|
839
|
+
*/
|
|
840
|
+
async function openInStudio(input, studioUrl, options = {}) {
|
|
841
|
+
const url = getStudioUrl(input, studioUrl, options);
|
|
842
|
+
const cmd = process.platform === "win32" ? "cmd" : process.platform === "darwin" ? "open" : "xdg-open";
|
|
843
|
+
const args = process.platform === "win32" ? [
|
|
844
|
+
"/c",
|
|
845
|
+
"start",
|
|
846
|
+
"",
|
|
847
|
+
url
|
|
848
|
+
] : [url];
|
|
849
|
+
try {
|
|
850
|
+
await x(cmd, args);
|
|
851
|
+
} catch {
|
|
852
|
+
console.log(`\n ${url}\n`);
|
|
853
|
+
}
|
|
854
|
+
}
|
|
855
|
+
//#endregion
|
|
856
|
+
//#region src/FileManager.ts
|
|
857
|
+
function mergeFile(a, b) {
|
|
858
|
+
return {
|
|
859
|
+
...a,
|
|
860
|
+
sources: [...a.sources || [], ...b.sources || []],
|
|
861
|
+
imports: [...a.imports || [], ...b.imports || []],
|
|
862
|
+
exports: [...a.exports || [], ...b.exports || []]
|
|
863
|
+
};
|
|
864
|
+
}
|
|
865
|
+
/**
|
|
866
|
+
* In-memory file store for generated files.
|
|
867
|
+
*
|
|
868
|
+
* Files with the same `path` are merged — sources, imports, and exports are concatenated.
|
|
869
|
+
* The `files` getter returns all stored files sorted by path length (shortest first).
|
|
870
|
+
*
|
|
871
|
+
* @example
|
|
872
|
+
* ```ts
|
|
873
|
+
* import { FileManager } from '@kubb/core'
|
|
874
|
+
*
|
|
875
|
+
* const manager = new FileManager()
|
|
876
|
+
* manager.upsert(myFile)
|
|
877
|
+
* console.log(manager.files) // all stored files
|
|
878
|
+
* ```
|
|
879
|
+
*/
|
|
880
|
+
var FileManager = class {
|
|
881
|
+
#cache = /* @__PURE__ */ new Map();
|
|
882
|
+
#filesCache = null;
|
|
883
|
+
/**
|
|
884
|
+
* Adds one or more files. Files with the same path are merged — sources, imports,
|
|
885
|
+
* and exports from all calls with the same path are concatenated together.
|
|
886
|
+
*/
|
|
887
|
+
add(...files) {
|
|
888
|
+
const resolvedFiles = [];
|
|
889
|
+
const mergedFiles = /* @__PURE__ */ new Map();
|
|
890
|
+
files.forEach((file) => {
|
|
891
|
+
const existing = mergedFiles.get(file.path);
|
|
892
|
+
if (existing) mergedFiles.set(file.path, mergeFile(existing, file));
|
|
893
|
+
else mergedFiles.set(file.path, file);
|
|
894
|
+
});
|
|
895
|
+
for (const file of mergedFiles.values()) {
|
|
896
|
+
const resolvedFile = createFile(file);
|
|
897
|
+
this.#cache.set(resolvedFile.path, resolvedFile);
|
|
898
|
+
this.#filesCache = null;
|
|
899
|
+
resolvedFiles.push(resolvedFile);
|
|
900
|
+
}
|
|
901
|
+
return resolvedFiles;
|
|
902
|
+
}
|
|
903
|
+
/**
|
|
904
|
+
* Adds or merges one or more files.
|
|
905
|
+
* If a file with the same path already exists, its sources/imports/exports are merged together.
|
|
906
|
+
*/
|
|
907
|
+
upsert(...files) {
|
|
908
|
+
const resolvedFiles = [];
|
|
909
|
+
const mergedFiles = /* @__PURE__ */ new Map();
|
|
910
|
+
files.forEach((file) => {
|
|
911
|
+
const existing = mergedFiles.get(file.path);
|
|
912
|
+
if (existing) mergedFiles.set(file.path, mergeFile(existing, file));
|
|
913
|
+
else mergedFiles.set(file.path, file);
|
|
914
|
+
});
|
|
915
|
+
for (const file of mergedFiles.values()) {
|
|
916
|
+
const existing = this.#cache.get(file.path);
|
|
917
|
+
const resolvedFile = createFile(existing ? mergeFile(existing, file) : file);
|
|
918
|
+
this.#cache.set(resolvedFile.path, resolvedFile);
|
|
919
|
+
this.#filesCache = null;
|
|
920
|
+
resolvedFiles.push(resolvedFile);
|
|
921
|
+
}
|
|
922
|
+
return resolvedFiles;
|
|
923
|
+
}
|
|
924
|
+
getByPath(path) {
|
|
925
|
+
return this.#cache.get(path) ?? null;
|
|
926
|
+
}
|
|
927
|
+
deleteByPath(path) {
|
|
928
|
+
this.#cache.delete(path);
|
|
929
|
+
this.#filesCache = null;
|
|
930
|
+
}
|
|
931
|
+
clear() {
|
|
932
|
+
this.#cache.clear();
|
|
933
|
+
this.#filesCache = null;
|
|
934
|
+
}
|
|
935
|
+
/**
|
|
936
|
+
* All stored files, sorted by path length (shorter paths first).
|
|
937
|
+
* Barrel/index files (e.g. index.ts) are sorted last within each length bucket.
|
|
938
|
+
*/
|
|
939
|
+
get files() {
|
|
940
|
+
if (this.#filesCache) return this.#filesCache;
|
|
941
|
+
const keys = [...this.#cache.keys()].sort((a, b) => {
|
|
942
|
+
if (a.length !== b.length) return a.length - b.length;
|
|
943
|
+
const aIsIndex = trimExtName(a).endsWith("index");
|
|
944
|
+
if (aIsIndex !== trimExtName(b).endsWith("index")) return aIsIndex ? 1 : -1;
|
|
945
|
+
return 0;
|
|
946
|
+
});
|
|
947
|
+
const files = [];
|
|
948
|
+
for (const key of keys) {
|
|
949
|
+
const file = this.#cache.get(key);
|
|
950
|
+
if (file) files.push(file);
|
|
951
|
+
}
|
|
952
|
+
this.#filesCache = files;
|
|
953
|
+
return files;
|
|
954
|
+
}
|
|
955
|
+
};
|
|
956
|
+
//#endregion
|
|
957
|
+
//#region src/renderNode.ts
|
|
958
|
+
/**
|
|
959
|
+
* Handles the return value of a plugin AST hook or generator method.
|
|
960
|
+
*
|
|
961
|
+
* - Renderer output → rendered via the provided `rendererFactory` (e.g. JSX), files stored in `driver.fileManager`
|
|
962
|
+
* - `Array<FileNode>` → added directly into `driver.fileManager`
|
|
963
|
+
* - `void` / `null` / `undefined` → no-op (plugin handled it via `this.upsertFile`)
|
|
964
|
+
*
|
|
965
|
+
* Pass a `rendererFactory` (e.g. `jsxRenderer` from `@kubb/renderer-jsx`) when the result
|
|
966
|
+
* may be a renderer element. Generators that only return `Array<FileNode>` do not need one.
|
|
967
|
+
*/
|
|
968
|
+
async function applyHookResult(result, driver, rendererFactory) {
|
|
969
|
+
if (!result) return;
|
|
970
|
+
if (Array.isArray(result)) {
|
|
971
|
+
driver.fileManager.upsert(...result);
|
|
972
|
+
return;
|
|
973
|
+
}
|
|
974
|
+
if (!rendererFactory) return;
|
|
975
|
+
const renderer = rendererFactory();
|
|
976
|
+
await renderer.render(result);
|
|
977
|
+
driver.fileManager.upsert(...renderer.files);
|
|
978
|
+
renderer.unmount();
|
|
979
|
+
}
|
|
980
|
+
//#endregion
|
|
981
|
+
//#region src/utils/executeStrategies.ts
|
|
982
|
+
/**
|
|
983
|
+
* Runs promise functions in sequence, threading each result into the next call.
|
|
984
|
+
*
|
|
985
|
+
* - Each function receives the accumulated state from the previous call.
|
|
986
|
+
* - Skips functions that return a falsy value (acts as a no-op for that step).
|
|
987
|
+
* - Returns an array of all individual results.
|
|
988
|
+
* @deprecated
|
|
989
|
+
*/
|
|
990
|
+
function hookSeq(promises) {
|
|
991
|
+
return promises.filter(Boolean).reduce((promise, func) => {
|
|
992
|
+
if (typeof func !== "function") throw new Error("HookSeq needs a function that returns a promise `() => Promise<unknown>`");
|
|
993
|
+
return promise.then((state) => {
|
|
994
|
+
const calledFunc = func(state);
|
|
995
|
+
if (calledFunc) return calledFunc.then(Array.prototype.concat.bind(state));
|
|
996
|
+
return state;
|
|
997
|
+
});
|
|
998
|
+
}, Promise.resolve([]));
|
|
999
|
+
}
|
|
1000
|
+
/**
|
|
1001
|
+
* Runs promise functions in sequence and returns the first non-null result.
|
|
1002
|
+
*
|
|
1003
|
+
* - Stops as soon as `nullCheck` passes for a result (default: `!== null`).
|
|
1004
|
+
* - Subsequent functions are skipped once a match is found.
|
|
1005
|
+
* @deprecated
|
|
1006
|
+
*/
|
|
1007
|
+
function hookFirst(promises, nullCheck = (state) => state !== null) {
|
|
1008
|
+
let promise = Promise.resolve(null);
|
|
1009
|
+
for (const func of promises.filter(Boolean)) promise = promise.then((state) => {
|
|
1010
|
+
if (nullCheck(state)) return state;
|
|
1011
|
+
return func(state);
|
|
1012
|
+
});
|
|
1013
|
+
return promise;
|
|
1014
|
+
}
|
|
1015
|
+
/**
|
|
1016
|
+
* Runs promise functions concurrently and returns all settled results.
|
|
1017
|
+
*
|
|
1018
|
+
* - Limits simultaneous executions to `concurrency` (default: unlimited).
|
|
1019
|
+
* - Uses `Promise.allSettled` so individual failures do not cancel other tasks.
|
|
1020
|
+
* @deprecated
|
|
1021
|
+
*/
|
|
1022
|
+
function hookParallel(promises, concurrency = Number.POSITIVE_INFINITY) {
|
|
1023
|
+
const limit = pLimit(concurrency);
|
|
1024
|
+
const tasks = promises.filter(Boolean).map((promise) => limit(() => promise()));
|
|
1025
|
+
return Promise.allSettled(tasks);
|
|
1026
|
+
}
|
|
1027
|
+
//#endregion
|
|
1028
|
+
//#region src/PluginDriver.ts
|
|
1029
|
+
/**
|
|
1030
|
+
* Returns `'single'` when `fileOrFolder` has a file extension, `'split'` otherwise.
|
|
1031
|
+
*
|
|
1032
|
+
* @example
|
|
1033
|
+
* ```ts
|
|
1034
|
+
* getMode('src/gen/types.ts') // 'single'
|
|
1035
|
+
* getMode('src/gen/types') // 'split'
|
|
1036
|
+
* ```
|
|
1037
|
+
*/
|
|
1038
|
+
function getMode(fileOrFolder) {
|
|
1039
|
+
if (!fileOrFolder) return "split";
|
|
1040
|
+
return extname(fileOrFolder) ? "single" : "split";
|
|
1041
|
+
}
|
|
1042
|
+
const hookFirstNullCheck = (state) => !!state?.result;
|
|
1043
|
+
var PluginDriver = class {
|
|
1044
|
+
config;
|
|
1045
|
+
options;
|
|
1046
|
+
/**
|
|
1047
|
+
* The universal `@kubb/ast` `InputNode` produced by the adapter, set by
|
|
1048
|
+
* the build pipeline after the adapter's `parse()` resolves.
|
|
1049
|
+
*/
|
|
1050
|
+
inputNode = void 0;
|
|
1051
|
+
adapter = void 0;
|
|
1052
|
+
#studioIsOpen = false;
|
|
1053
|
+
/**
|
|
1054
|
+
* Central file store for all generated files.
|
|
1055
|
+
* Plugins should use `this.addFile()` / `this.upsertFile()` (via their context) to
|
|
1056
|
+
* add files; this property gives direct read/write access when needed.
|
|
1057
|
+
*/
|
|
1058
|
+
fileManager = new FileManager();
|
|
1059
|
+
plugins = /* @__PURE__ */ new Map();
|
|
1060
|
+
/**
|
|
1061
|
+
* Tracks which plugins have generators registered via `addGenerator()` (event-based path).
|
|
1062
|
+
* Used by the build loop to decide whether to emit generator events for a given plugin.
|
|
1063
|
+
*/
|
|
1064
|
+
#pluginsWithEventGenerators = /* @__PURE__ */ new Set();
|
|
1065
|
+
#resolvers = /* @__PURE__ */ new Map();
|
|
1066
|
+
#defaultResolvers = /* @__PURE__ */ new Map();
|
|
1067
|
+
#hookListeners = /* @__PURE__ */ new Map();
|
|
1068
|
+
constructor(config, options) {
|
|
1069
|
+
this.config = config;
|
|
1070
|
+
this.options = {
|
|
1071
|
+
...options,
|
|
1072
|
+
hooks: options.hooks
|
|
1073
|
+
};
|
|
1074
|
+
config.plugins.map((rawPlugin) => {
|
|
1075
|
+
if (isHookStylePlugin(rawPlugin)) return this.#normalizeHookStylePlugin(rawPlugin);
|
|
1076
|
+
return {
|
|
1077
|
+
...rawPlugin,
|
|
1078
|
+
buildStart: rawPlugin.buildStart ?? (() => {}),
|
|
1079
|
+
buildEnd: rawPlugin.buildEnd ?? (() => {})
|
|
1080
|
+
};
|
|
1081
|
+
}).filter((plugin) => {
|
|
1082
|
+
if (typeof plugin.apply === "function") return plugin.apply(config);
|
|
1083
|
+
return true;
|
|
1084
|
+
}).sort((a, b) => {
|
|
1085
|
+
if (b.dependencies?.includes(a.name)) return -1;
|
|
1086
|
+
if (a.dependencies?.includes(b.name)) return 1;
|
|
1087
|
+
return 0;
|
|
1088
|
+
}).forEach((plugin) => {
|
|
1089
|
+
this.plugins.set(plugin.name, plugin);
|
|
1090
|
+
});
|
|
1091
|
+
}
|
|
1092
|
+
get hooks() {
|
|
1093
|
+
if (!this.options.hooks) throw new Error("hooks are not defined");
|
|
1094
|
+
return this.options.hooks;
|
|
1095
|
+
}
|
|
1096
|
+
/**
|
|
1097
|
+
* Creates a `Plugin`-compatible object from a hook-style plugin and registers
|
|
1098
|
+
* its lifecycle handlers on the `AsyncEventEmitter`.
|
|
1099
|
+
*
|
|
1100
|
+
* The normalized plugin has an empty `buildStart` — generators registered via
|
|
1101
|
+
* `addGenerator()` in `kubb:plugin:setup` are stored on `normalizedPlugin.generators`
|
|
1102
|
+
* and used by `runPluginAstHooks` during the build.
|
|
1103
|
+
*/
|
|
1104
|
+
#normalizeHookStylePlugin(hookPlugin) {
|
|
1105
|
+
const generators = [];
|
|
1106
|
+
const driver = this;
|
|
1107
|
+
const normalizedPlugin = {
|
|
1108
|
+
name: hookPlugin.name,
|
|
1109
|
+
dependencies: hookPlugin.dependencies,
|
|
1110
|
+
options: {
|
|
1111
|
+
output: { path: "." },
|
|
1112
|
+
exclude: [],
|
|
1113
|
+
override: []
|
|
1114
|
+
},
|
|
1115
|
+
generators,
|
|
1116
|
+
inject: () => void 0,
|
|
1117
|
+
resolveName(name, type) {
|
|
1118
|
+
return driver.getResolver(hookPlugin.name).default(name, type);
|
|
1119
|
+
},
|
|
1120
|
+
resolvePath(baseName, pathMode, resolveOptions) {
|
|
1121
|
+
const resolver = driver.getResolver(hookPlugin.name);
|
|
1122
|
+
const opts = normalizedPlugin.options;
|
|
1123
|
+
const group = resolveOptions?.group;
|
|
1124
|
+
return resolver.resolvePath({
|
|
1125
|
+
baseName,
|
|
1126
|
+
pathMode,
|
|
1127
|
+
tag: group?.tag,
|
|
1128
|
+
path: group?.path
|
|
1129
|
+
}, {
|
|
1130
|
+
root: resolve(driver.config.root, driver.config.output.path),
|
|
1131
|
+
output: opts.output,
|
|
1132
|
+
group: opts.group
|
|
1133
|
+
});
|
|
1134
|
+
},
|
|
1135
|
+
buildStart() {},
|
|
1136
|
+
buildEnd() {}
|
|
1137
|
+
};
|
|
1138
|
+
this.registerPluginHooks(hookPlugin, normalizedPlugin);
|
|
1139
|
+
return normalizedPlugin;
|
|
1140
|
+
}
|
|
1141
|
+
/**
|
|
1142
|
+
* Registers a hook-style plugin's lifecycle handlers on the shared `AsyncEventEmitter`.
|
|
1143
|
+
*
|
|
1144
|
+
* For `kubb:plugin:setup`, the registered listener wraps the globally emitted context with a
|
|
1145
|
+
* plugin-specific one so that `addGenerator`, `setResolver`, `setTransformer`, and
|
|
1146
|
+
* `setRenderer` all target the correct `normalizedPlugin` entry in the plugins map.
|
|
1147
|
+
*
|
|
1148
|
+
* All other hooks are iterated and registered directly as pass-through listeners.
|
|
1149
|
+
* Any event key present in the global `KubbHooks` interface can be subscribed to.
|
|
1150
|
+
*
|
|
1151
|
+
* External tooling can subscribe to any of these events via `hooks.on(...)` to observe
|
|
1152
|
+
* the plugin lifecycle without modifying plugin behavior.
|
|
1153
|
+
*/
|
|
1154
|
+
registerPluginHooks(hookPlugin, normalizedPlugin) {
|
|
1155
|
+
const { hooks } = hookPlugin;
|
|
1156
|
+
if (hooks["kubb:plugin:setup"]) {
|
|
1157
|
+
const setupHandler = (globalCtx) => {
|
|
1158
|
+
const pluginCtx = {
|
|
1159
|
+
...globalCtx,
|
|
1160
|
+
options: hookPlugin.options ?? {},
|
|
1161
|
+
addGenerator: (gen) => {
|
|
1162
|
+
this.registerGenerator(normalizedPlugin.name, gen);
|
|
1163
|
+
},
|
|
1164
|
+
setResolver: (resolver) => {
|
|
1165
|
+
this.setPluginResolver(normalizedPlugin.name, resolver);
|
|
1166
|
+
},
|
|
1167
|
+
setTransformer: (visitor) => {
|
|
1168
|
+
normalizedPlugin.transformer = visitor;
|
|
1169
|
+
},
|
|
1170
|
+
setRenderer: (renderer) => {
|
|
1171
|
+
normalizedPlugin.renderer = renderer;
|
|
1172
|
+
},
|
|
1173
|
+
setOptions: (opts) => {
|
|
1174
|
+
normalizedPlugin.options = {
|
|
1175
|
+
...normalizedPlugin.options,
|
|
1176
|
+
...opts
|
|
1177
|
+
};
|
|
1178
|
+
},
|
|
1179
|
+
injectFile: (file) => {
|
|
1180
|
+
const fileNode = createFile({
|
|
1181
|
+
baseName: file.baseName,
|
|
1182
|
+
path: file.path,
|
|
1183
|
+
sources: file.sources ?? [],
|
|
1184
|
+
imports: [],
|
|
1185
|
+
exports: []
|
|
1186
|
+
});
|
|
1187
|
+
this.fileManager.add(fileNode);
|
|
1188
|
+
}
|
|
1189
|
+
};
|
|
1190
|
+
return hooks["kubb:plugin:setup"](pluginCtx);
|
|
1191
|
+
};
|
|
1192
|
+
this.hooks.on("kubb:plugin:setup", setupHandler);
|
|
1193
|
+
this.#trackHookListener("kubb:plugin:setup", setupHandler);
|
|
1194
|
+
}
|
|
1195
|
+
for (const [event, handler] of Object.entries(hooks)) {
|
|
1196
|
+
if (event === "kubb:plugin:setup" || !handler) continue;
|
|
1197
|
+
this.hooks.on(event, handler);
|
|
1198
|
+
this.#trackHookListener(event, handler);
|
|
1199
|
+
}
|
|
1200
|
+
}
|
|
1201
|
+
/**
|
|
1202
|
+
* Emits the `kubb:plugin:setup` event so that all registered hook-style plugin listeners
|
|
1203
|
+
* can configure generators, resolvers, transformers and renderers before `buildStart` runs.
|
|
1204
|
+
*
|
|
1205
|
+
* Call this once from `safeBuild` before the plugin execution loop begins.
|
|
1206
|
+
*/
|
|
1207
|
+
async emitSetupHooks() {
|
|
1208
|
+
await this.hooks.emit("kubb:plugin:setup", {
|
|
1209
|
+
config: this.config,
|
|
1210
|
+
addGenerator: () => {},
|
|
1211
|
+
setResolver: () => {},
|
|
1212
|
+
setTransformer: () => {},
|
|
1213
|
+
setRenderer: () => {},
|
|
1214
|
+
setOptions: () => {},
|
|
1215
|
+
injectFile: () => {},
|
|
1216
|
+
updateConfig: () => {},
|
|
1217
|
+
options: {}
|
|
1218
|
+
});
|
|
1219
|
+
}
|
|
1220
|
+
/**
|
|
1221
|
+
* Registers a generator for the given plugin on the shared event emitter.
|
|
1222
|
+
*
|
|
1223
|
+
* The generator's `schema`, `operation`, and `operations` methods are registered as
|
|
1224
|
+
* listeners on `kubb:generate:schema`, `kubb:generate:operation`, and `kubb:generate:operations`
|
|
1225
|
+
* respectively. Each listener is scoped to the owning plugin via a `ctx.plugin.name` check
|
|
1226
|
+
* so that generators from different plugins do not cross-fire.
|
|
1227
|
+
*
|
|
1228
|
+
* The renderer resolution chain is: `generator.renderer → plugin.renderer → config.renderer`.
|
|
1229
|
+
* Set `generator.renderer = null` to explicitly opt out of rendering even when the plugin
|
|
1230
|
+
* declares a renderer.
|
|
1231
|
+
*
|
|
1232
|
+
* Call this method inside `addGenerator()` (in `kubb:plugin:setup`) to wire up a generator.
|
|
1233
|
+
*/
|
|
1234
|
+
registerGenerator(pluginName, gen) {
|
|
1235
|
+
const resolveRenderer = () => {
|
|
1236
|
+
const plugin = this.plugins.get(pluginName);
|
|
1237
|
+
return gen.renderer === null ? void 0 : gen.renderer ?? plugin?.renderer ?? this.config.renderer;
|
|
1238
|
+
};
|
|
1239
|
+
if (gen.schema) {
|
|
1240
|
+
const schemaHandler = async (node, ctx) => {
|
|
1241
|
+
if (ctx.plugin.name !== pluginName) return;
|
|
1242
|
+
await applyHookResult(await gen.schema(node, ctx), this, resolveRenderer());
|
|
1243
|
+
};
|
|
1244
|
+
this.hooks.on("kubb:generate:schema", schemaHandler);
|
|
1245
|
+
this.#trackHookListener("kubb:generate:schema", schemaHandler);
|
|
1246
|
+
}
|
|
1247
|
+
if (gen.operation) {
|
|
1248
|
+
const operationHandler = async (node, ctx) => {
|
|
1249
|
+
if (ctx.plugin.name !== pluginName) return;
|
|
1250
|
+
await applyHookResult(await gen.operation(node, ctx), this, resolveRenderer());
|
|
1251
|
+
};
|
|
1252
|
+
this.hooks.on("kubb:generate:operation", operationHandler);
|
|
1253
|
+
this.#trackHookListener("kubb:generate:operation", operationHandler);
|
|
1254
|
+
}
|
|
1255
|
+
if (gen.operations) {
|
|
1256
|
+
const operationsHandler = async (nodes, ctx) => {
|
|
1257
|
+
if (ctx.plugin.name !== pluginName) return;
|
|
1258
|
+
await applyHookResult(await gen.operations(nodes, ctx), this, resolveRenderer());
|
|
1259
|
+
};
|
|
1260
|
+
this.hooks.on("kubb:generate:operations", operationsHandler);
|
|
1261
|
+
this.#trackHookListener("kubb:generate:operations", operationsHandler);
|
|
1262
|
+
}
|
|
1263
|
+
this.#pluginsWithEventGenerators.add(pluginName);
|
|
1264
|
+
}
|
|
1265
|
+
/**
|
|
1266
|
+
* Returns `true` when at least one generator was registered for the given plugin
|
|
1267
|
+
* via `addGenerator()` in `kubb:plugin:setup` (event-based path).
|
|
1268
|
+
*
|
|
1269
|
+
* Used by the build loop to decide whether to walk the AST and emit generator events
|
|
1270
|
+
* for a plugin that has no static `plugin.generators`.
|
|
1271
|
+
*/
|
|
1272
|
+
hasRegisteredGenerators(pluginName) {
|
|
1273
|
+
return this.#pluginsWithEventGenerators.has(pluginName);
|
|
1274
|
+
}
|
|
1275
|
+
dispose() {
|
|
1276
|
+
for (const [event, handlers] of this.#hookListeners) for (const handler of handlers) this.hooks.off(event, handler);
|
|
1277
|
+
this.#hookListeners.clear();
|
|
1278
|
+
this.#pluginsWithEventGenerators.clear();
|
|
1279
|
+
}
|
|
1280
|
+
#trackHookListener(event, handler) {
|
|
1281
|
+
let handlers = this.#hookListeners.get(event);
|
|
1282
|
+
if (!handlers) {
|
|
1283
|
+
handlers = /* @__PURE__ */ new Set();
|
|
1284
|
+
this.#hookListeners.set(event, handlers);
|
|
1285
|
+
}
|
|
1286
|
+
handlers.add(handler);
|
|
1287
|
+
}
|
|
1288
|
+
#createDefaultResolver(pluginName) {
|
|
1289
|
+
const existingResolver = this.#defaultResolvers.get(pluginName);
|
|
1290
|
+
if (existingResolver) return existingResolver;
|
|
1291
|
+
const resolver = defineResolver(() => ({
|
|
1292
|
+
name: "default",
|
|
1293
|
+
pluginName
|
|
1294
|
+
}));
|
|
1295
|
+
this.#defaultResolvers.set(pluginName, resolver);
|
|
1296
|
+
return resolver;
|
|
1297
|
+
}
|
|
1298
|
+
setPluginResolver(pluginName, partial) {
|
|
1299
|
+
const merged = {
|
|
1300
|
+
...this.#createDefaultResolver(pluginName),
|
|
1301
|
+
...partial
|
|
1302
|
+
};
|
|
1303
|
+
this.#resolvers.set(pluginName, merged);
|
|
1304
|
+
const plugin = this.plugins.get(pluginName);
|
|
1305
|
+
if (plugin) plugin.resolver = merged;
|
|
1306
|
+
}
|
|
1307
|
+
getResolver(pluginName) {
|
|
1308
|
+
const dynamicResolver = this.#resolvers.get(pluginName);
|
|
1309
|
+
if (dynamicResolver) return dynamicResolver;
|
|
1310
|
+
const pluginResolver = this.plugins.get(pluginName)?.resolver;
|
|
1311
|
+
if (pluginResolver) return pluginResolver;
|
|
1312
|
+
return this.#createDefaultResolver(pluginName);
|
|
1313
|
+
}
|
|
1314
|
+
getContext(plugin) {
|
|
1315
|
+
const driver = this;
|
|
1316
|
+
const baseContext = {
|
|
1317
|
+
config: driver.config,
|
|
1318
|
+
get root() {
|
|
1319
|
+
return resolve(driver.config.root, driver.config.output.path);
|
|
1320
|
+
},
|
|
1321
|
+
getMode(output) {
|
|
1322
|
+
return getMode(resolve(driver.config.root, driver.config.output.path, output.path));
|
|
1323
|
+
},
|
|
1324
|
+
hooks: driver.hooks,
|
|
1325
|
+
plugin,
|
|
1326
|
+
getPlugin: driver.getPlugin.bind(driver),
|
|
1327
|
+
requirePlugin: driver.requirePlugin.bind(driver),
|
|
1328
|
+
driver,
|
|
1329
|
+
addFile: async (...files) => {
|
|
1330
|
+
driver.fileManager.add(...files);
|
|
1331
|
+
},
|
|
1332
|
+
upsertFile: async (...files) => {
|
|
1333
|
+
driver.fileManager.upsert(...files);
|
|
1334
|
+
},
|
|
1335
|
+
get inputNode() {
|
|
1336
|
+
return driver.inputNode;
|
|
1337
|
+
},
|
|
1338
|
+
get adapter() {
|
|
1339
|
+
return driver.adapter;
|
|
1340
|
+
},
|
|
1341
|
+
get resolver() {
|
|
1342
|
+
return driver.getResolver(plugin.name);
|
|
1343
|
+
},
|
|
1344
|
+
get transformer() {
|
|
1345
|
+
return plugin.transformer;
|
|
1346
|
+
},
|
|
1347
|
+
warn(message) {
|
|
1348
|
+
driver.hooks.emit("kubb:warn", message);
|
|
1349
|
+
},
|
|
1350
|
+
error(error) {
|
|
1351
|
+
driver.hooks.emit("kubb:error", typeof error === "string" ? new Error(error) : error);
|
|
1352
|
+
},
|
|
1353
|
+
info(message) {
|
|
1354
|
+
driver.hooks.emit("kubb:info", message);
|
|
1355
|
+
},
|
|
1356
|
+
openInStudio(options) {
|
|
1357
|
+
if (!driver.config.devtools || driver.#studioIsOpen) return;
|
|
1358
|
+
if (typeof driver.config.devtools !== "object") throw new Error("Devtools must be an object");
|
|
1359
|
+
if (!driver.inputNode || !driver.adapter) throw new Error("adapter is not defined, make sure you have set the parser in kubb.config.ts");
|
|
1360
|
+
driver.#studioIsOpen = true;
|
|
1361
|
+
const studioUrl = driver.config.devtools?.studioUrl ?? "https://studio.kubb.dev";
|
|
1362
|
+
return openInStudio(driver.inputNode, studioUrl, options);
|
|
1363
|
+
}
|
|
1364
|
+
};
|
|
1365
|
+
let mergedExtras = {};
|
|
1366
|
+
for (const p of this.plugins.values()) if (typeof p.inject === "function") {
|
|
1367
|
+
const result = p.inject.call(baseContext);
|
|
1368
|
+
if (result !== null && typeof result === "object") mergedExtras = {
|
|
1369
|
+
...mergedExtras,
|
|
1370
|
+
...result
|
|
1371
|
+
};
|
|
1372
|
+
}
|
|
1373
|
+
return {
|
|
1374
|
+
...baseContext,
|
|
1375
|
+
...mergedExtras
|
|
1376
|
+
};
|
|
1377
|
+
}
|
|
1378
|
+
/**
|
|
1379
|
+
* @deprecated use resolvers context instead
|
|
1380
|
+
*/
|
|
1381
|
+
getFile({ name, mode, extname, pluginName, options }) {
|
|
1382
|
+
const resolvedName = mode ? mode === "single" ? "" : this.resolveName({
|
|
1383
|
+
name,
|
|
1384
|
+
pluginName,
|
|
1385
|
+
type: "file"
|
|
1386
|
+
}) : name;
|
|
1387
|
+
const path = this.resolvePath({
|
|
1388
|
+
baseName: `${resolvedName}${extname}`,
|
|
1389
|
+
mode,
|
|
1390
|
+
pluginName,
|
|
1391
|
+
options
|
|
1392
|
+
});
|
|
1393
|
+
if (!path) throw new Error(`Filepath should be defined for resolvedName "${resolvedName}" and pluginName "${pluginName}"`);
|
|
1394
|
+
return createFile({
|
|
1395
|
+
path,
|
|
1396
|
+
baseName: basename(path),
|
|
1397
|
+
meta: { pluginName },
|
|
1398
|
+
sources: [],
|
|
1399
|
+
imports: [],
|
|
1400
|
+
exports: []
|
|
1401
|
+
});
|
|
1402
|
+
}
|
|
1403
|
+
/**
|
|
1404
|
+
* @deprecated use resolvers context instead
|
|
1405
|
+
*/
|
|
1406
|
+
resolvePath = (params) => {
|
|
1407
|
+
const defaultPath = resolve(resolve(this.config.root, this.config.output.path), params.baseName);
|
|
1408
|
+
if (params.pluginName) return this.hookForPluginSync({
|
|
1409
|
+
pluginName: params.pluginName,
|
|
1410
|
+
hookName: "resolvePath",
|
|
1411
|
+
parameters: [
|
|
1412
|
+
params.baseName,
|
|
1413
|
+
params.mode,
|
|
1414
|
+
params.options
|
|
1415
|
+
]
|
|
1416
|
+
})?.at(0) || defaultPath;
|
|
1417
|
+
return this.hookFirstSync({
|
|
1418
|
+
hookName: "resolvePath",
|
|
1419
|
+
parameters: [
|
|
1420
|
+
params.baseName,
|
|
1421
|
+
params.mode,
|
|
1422
|
+
params.options
|
|
1423
|
+
]
|
|
1424
|
+
})?.result || defaultPath;
|
|
1425
|
+
};
|
|
1426
|
+
/**
|
|
1427
|
+
* @deprecated use resolvers context instead
|
|
1428
|
+
*/
|
|
1429
|
+
resolveName = (params) => {
|
|
1430
|
+
if (params.pluginName) return transformReservedWord(this.hookForPluginSync({
|
|
1431
|
+
pluginName: params.pluginName,
|
|
1432
|
+
hookName: "resolveName",
|
|
1433
|
+
parameters: [params.name.trim(), params.type]
|
|
1434
|
+
})?.at(0) ?? params.name);
|
|
1435
|
+
const name = this.hookFirstSync({
|
|
1436
|
+
hookName: "resolveName",
|
|
1437
|
+
parameters: [params.name.trim(), params.type]
|
|
1438
|
+
})?.result;
|
|
1439
|
+
return transformReservedWord(name ?? params.name);
|
|
1440
|
+
};
|
|
1441
|
+
/**
|
|
1442
|
+
* Run a specific hookName for plugin x.
|
|
1443
|
+
*/
|
|
1444
|
+
async hookForPlugin({ pluginName, hookName, parameters }) {
|
|
1445
|
+
const plugin = this.plugins.get(pluginName);
|
|
1446
|
+
if (!plugin) return [null];
|
|
1447
|
+
this.hooks.emit("kubb:plugins:hook:progress:start", {
|
|
1448
|
+
hookName,
|
|
1449
|
+
plugins: [plugin]
|
|
1450
|
+
});
|
|
1451
|
+
const result = await this.#execute({
|
|
1452
|
+
strategy: "hookFirst",
|
|
1453
|
+
hookName,
|
|
1454
|
+
parameters,
|
|
1455
|
+
plugin
|
|
1456
|
+
});
|
|
1457
|
+
this.hooks.emit("kubb:plugins:hook:progress:end", { hookName });
|
|
1458
|
+
return [result];
|
|
1459
|
+
}
|
|
1460
|
+
/**
|
|
1461
|
+
* Run a specific hookName for plugin x.
|
|
1462
|
+
*/
|
|
1463
|
+
hookForPluginSync({ pluginName, hookName, parameters }) {
|
|
1464
|
+
const plugin = this.plugins.get(pluginName);
|
|
1465
|
+
if (!plugin) return null;
|
|
1466
|
+
const result = this.#executeSync({
|
|
1467
|
+
strategy: "hookFirst",
|
|
1468
|
+
hookName,
|
|
1469
|
+
parameters,
|
|
1470
|
+
plugin
|
|
1471
|
+
});
|
|
1472
|
+
return result !== null ? [result] : [];
|
|
1473
|
+
}
|
|
1474
|
+
/**
|
|
1475
|
+
* Returns the first non-null result.
|
|
1476
|
+
*/
|
|
1477
|
+
async hookFirst({ hookName, parameters, skipped }) {
|
|
1478
|
+
const plugins = [];
|
|
1479
|
+
for (const plugin of this.plugins.values()) if (hookName in plugin && (skipped ? !skipped.has(plugin) : true)) plugins.push(plugin);
|
|
1480
|
+
this.hooks.emit("kubb:plugins:hook:progress:start", {
|
|
1481
|
+
hookName,
|
|
1482
|
+
plugins
|
|
1483
|
+
});
|
|
1484
|
+
const result = await hookFirst(plugins.map((plugin) => {
|
|
1485
|
+
return async () => {
|
|
1486
|
+
const value = await this.#execute({
|
|
1487
|
+
strategy: "hookFirst",
|
|
1488
|
+
hookName,
|
|
1489
|
+
parameters,
|
|
1490
|
+
plugin
|
|
1491
|
+
});
|
|
1492
|
+
return Promise.resolve({
|
|
1493
|
+
plugin,
|
|
1494
|
+
result: value
|
|
1495
|
+
});
|
|
1496
|
+
};
|
|
1497
|
+
}), hookFirstNullCheck);
|
|
1498
|
+
this.hooks.emit("kubb:plugins:hook:progress:end", { hookName });
|
|
1499
|
+
return result;
|
|
1500
|
+
}
|
|
1501
|
+
/**
|
|
1502
|
+
* Returns the first non-null result.
|
|
1503
|
+
*/
|
|
1504
|
+
hookFirstSync({ hookName, parameters, skipped }) {
|
|
1505
|
+
let parseResult = null;
|
|
1506
|
+
for (const plugin of this.plugins.values()) {
|
|
1507
|
+
if (!(hookName in plugin)) continue;
|
|
1508
|
+
if (skipped?.has(plugin)) continue;
|
|
1509
|
+
parseResult = {
|
|
1510
|
+
result: this.#executeSync({
|
|
1511
|
+
strategy: "hookFirst",
|
|
1512
|
+
hookName,
|
|
1513
|
+
parameters,
|
|
1514
|
+
plugin
|
|
1515
|
+
}),
|
|
1516
|
+
plugin
|
|
1517
|
+
};
|
|
1518
|
+
if (parseResult.result != null) break;
|
|
1519
|
+
}
|
|
1520
|
+
return parseResult;
|
|
1521
|
+
}
|
|
1522
|
+
/**
|
|
1523
|
+
* Runs all plugins in parallel based on `this.plugin` order and `dependencies` settings.
|
|
1524
|
+
*/
|
|
1525
|
+
async hookParallel({ hookName, parameters }) {
|
|
1526
|
+
const plugins = [];
|
|
1527
|
+
for (const plugin of this.plugins.values()) if (hookName in plugin) plugins.push(plugin);
|
|
1528
|
+
this.hooks.emit("kubb:plugins:hook:progress:start", {
|
|
1529
|
+
hookName,
|
|
1530
|
+
plugins
|
|
1531
|
+
});
|
|
1532
|
+
const pluginStartTimes = /* @__PURE__ */ new Map();
|
|
1533
|
+
const results = await hookParallel(plugins.map((plugin) => {
|
|
1534
|
+
return () => {
|
|
1535
|
+
pluginStartTimes.set(plugin, performance.now());
|
|
1536
|
+
return this.#execute({
|
|
1537
|
+
strategy: "hookParallel",
|
|
1538
|
+
hookName,
|
|
1539
|
+
parameters,
|
|
1540
|
+
plugin
|
|
1541
|
+
});
|
|
1542
|
+
};
|
|
1543
|
+
}), this.options.concurrency);
|
|
1544
|
+
results.forEach((result, index) => {
|
|
1545
|
+
if (isPromiseRejectedResult(result)) {
|
|
1546
|
+
const plugin = plugins[index];
|
|
1547
|
+
if (plugin) {
|
|
1548
|
+
const startTime = pluginStartTimes.get(plugin) ?? performance.now();
|
|
1549
|
+
this.hooks.emit("kubb:error", result.reason, {
|
|
1550
|
+
plugin,
|
|
1551
|
+
hookName,
|
|
1552
|
+
strategy: "hookParallel",
|
|
1553
|
+
duration: Math.round(performance.now() - startTime),
|
|
1554
|
+
parameters
|
|
1555
|
+
});
|
|
1556
|
+
}
|
|
1557
|
+
}
|
|
1558
|
+
});
|
|
1559
|
+
this.hooks.emit("kubb:plugins:hook:progress:end", { hookName });
|
|
1560
|
+
return results.reduce((acc, result) => {
|
|
1561
|
+
if (result.status === "fulfilled") acc.push(result.value);
|
|
1562
|
+
return acc;
|
|
1563
|
+
}, []);
|
|
1564
|
+
}
|
|
1565
|
+
/**
|
|
1566
|
+
* Execute a lifecycle hook sequentially for all plugins that implement it.
|
|
1567
|
+
*/
|
|
1568
|
+
async hookSeq({ hookName, parameters }) {
|
|
1569
|
+
const plugins = [];
|
|
1570
|
+
for (const plugin of this.plugins.values()) if (hookName in plugin) plugins.push(plugin);
|
|
1571
|
+
this.hooks.emit("kubb:plugins:hook:progress:start", {
|
|
1572
|
+
hookName,
|
|
1573
|
+
plugins
|
|
1574
|
+
});
|
|
1575
|
+
await hookSeq(plugins.map((plugin) => {
|
|
1576
|
+
return () => this.#execute({
|
|
1577
|
+
strategy: "hookSeq",
|
|
1578
|
+
hookName,
|
|
1579
|
+
parameters,
|
|
1580
|
+
plugin
|
|
1581
|
+
});
|
|
1582
|
+
}));
|
|
1583
|
+
this.hooks.emit("kubb:plugins:hook:progress:end", { hookName });
|
|
1584
|
+
}
|
|
1585
|
+
getPlugin(pluginName) {
|
|
1586
|
+
return this.plugins.get(pluginName);
|
|
1587
|
+
}
|
|
1588
|
+
requirePlugin(pluginName) {
|
|
1589
|
+
const plugin = this.plugins.get(pluginName);
|
|
1590
|
+
if (!plugin) throw new Error(`[kubb] Plugin "${pluginName}" is required but not found. Make sure it is included in your Kubb config.`);
|
|
1591
|
+
return plugin;
|
|
1592
|
+
}
|
|
1593
|
+
/**
|
|
1594
|
+
* Emit hook-processing completion metadata after a plugin hook resolves.
|
|
1595
|
+
*/
|
|
1596
|
+
#emitProcessingEnd({ startTime, output, strategy, hookName, plugin, parameters }) {
|
|
1597
|
+
this.hooks.emit("kubb:plugins:hook:processing:end", {
|
|
1598
|
+
duration: Math.round(performance.now() - startTime),
|
|
1599
|
+
parameters,
|
|
1600
|
+
output,
|
|
1601
|
+
strategy,
|
|
1602
|
+
hookName,
|
|
1603
|
+
plugin
|
|
1604
|
+
});
|
|
1605
|
+
}
|
|
1606
|
+
#execute({ strategy, hookName, parameters, plugin }) {
|
|
1607
|
+
const hook = plugin[hookName];
|
|
1608
|
+
if (!hook) return null;
|
|
1609
|
+
this.hooks.emit("kubb:plugins:hook:processing:start", {
|
|
1610
|
+
strategy,
|
|
1611
|
+
hookName,
|
|
1612
|
+
parameters,
|
|
1613
|
+
plugin
|
|
1614
|
+
});
|
|
1615
|
+
const startTime = performance.now();
|
|
1616
|
+
return (async () => {
|
|
1617
|
+
try {
|
|
1618
|
+
const output = typeof hook === "function" ? await Promise.resolve(hook.apply(this.getContext(plugin), parameters ?? [])) : hook;
|
|
1619
|
+
this.#emitProcessingEnd({
|
|
1620
|
+
startTime,
|
|
1621
|
+
output,
|
|
1622
|
+
strategy,
|
|
1623
|
+
hookName,
|
|
1624
|
+
plugin,
|
|
1625
|
+
parameters
|
|
1626
|
+
});
|
|
1627
|
+
return output;
|
|
1628
|
+
} catch (error) {
|
|
1629
|
+
this.hooks.emit("kubb:error", error, {
|
|
1630
|
+
plugin,
|
|
1631
|
+
hookName,
|
|
1632
|
+
strategy,
|
|
1633
|
+
duration: Math.round(performance.now() - startTime)
|
|
1634
|
+
});
|
|
1635
|
+
return null;
|
|
1636
|
+
}
|
|
1637
|
+
})();
|
|
1638
|
+
}
|
|
1639
|
+
/**
|
|
1640
|
+
* Execute a plugin lifecycle hook synchronously and return its output.
|
|
1641
|
+
*/
|
|
1642
|
+
#executeSync({ strategy, hookName, parameters, plugin }) {
|
|
1643
|
+
const hook = plugin[hookName];
|
|
1644
|
+
if (!hook) return null;
|
|
1645
|
+
this.hooks.emit("kubb:plugins:hook:processing:start", {
|
|
1646
|
+
strategy,
|
|
1647
|
+
hookName,
|
|
1648
|
+
parameters,
|
|
1649
|
+
plugin
|
|
1650
|
+
});
|
|
1651
|
+
const startTime = performance.now();
|
|
1652
|
+
try {
|
|
1653
|
+
const output = typeof hook === "function" ? hook.apply(this.getContext(plugin), parameters) : hook;
|
|
1654
|
+
this.#emitProcessingEnd({
|
|
1655
|
+
startTime,
|
|
1656
|
+
output,
|
|
1657
|
+
strategy,
|
|
1658
|
+
hookName,
|
|
1659
|
+
plugin,
|
|
1660
|
+
parameters
|
|
1661
|
+
});
|
|
1662
|
+
return output;
|
|
1663
|
+
} catch (error) {
|
|
1664
|
+
this.hooks.emit("kubb:error", error, {
|
|
1665
|
+
plugin,
|
|
1666
|
+
hookName,
|
|
1667
|
+
strategy,
|
|
1668
|
+
duration: Math.round(performance.now() - startTime)
|
|
1669
|
+
});
|
|
1670
|
+
return null;
|
|
1671
|
+
}
|
|
1672
|
+
}
|
|
1673
|
+
};
|
|
1674
|
+
//#endregion
|
|
1675
|
+
export { camelCase as S, DEFAULT_STUDIO_URL as _, buildDefaultBanner as a, logLevel as b, defaultResolveFooter as c, defineResolver as d, definePlugin as f, DEFAULT_EXTENSION as g, DEFAULT_BANNER as h, FileManager as i, defaultResolveOptions as l, BARREL_FILENAME as m, getMode as n, defaultResolveBanner as o, pLimit as p, applyHookResult as r, defaultResolveFile as s, PluginDriver as t, defaultResolvePath as u, formatters as v, isValidVarName as x, linters as y };
|
|
1676
|
+
|
|
1677
|
+
//# sourceMappingURL=PluginDriver-B_65W4fv.js.map
|