@kubb/core 5.10.2 → 5.10.4

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.
@@ -1,3044 +0,0 @@
1
- //#region \0rolldown/runtime.js
2
- var __create = Object.create;
3
- var __defProp = Object.defineProperty;
4
- var __name = (target, value) => __defProp(target, "name", {
5
- value,
6
- configurable: true
7
- });
8
- var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
9
- var __getOwnPropNames = Object.getOwnPropertyNames;
10
- var __getProtoOf = Object.getPrototypeOf;
11
- var __hasOwnProp = Object.prototype.hasOwnProperty;
12
- var __copyProps = (to, from, except, desc) => {
13
- if (from && typeof from === "object" || typeof from === "function") for (var keys = __getOwnPropNames(from), i = 0, n = keys.length, key; i < n; i++) {
14
- key = keys[i];
15
- if (!__hasOwnProp.call(to, key) && key !== except) __defProp(to, key, {
16
- get: ((k) => from[k]).bind(null, key),
17
- enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable
18
- });
19
- }
20
- return to;
21
- };
22
- var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(isNodeMode || !mod || !mod.__esModule || !__hasOwnProp.call(mod, "default") ? __defProp(target, "default", {
23
- value: mod,
24
- enumerable: true
25
- }) : target, mod));
26
- //#endregion
27
- let verkit = require("verkit");
28
- let node_async_hooks = require("node:async_hooks");
29
- let node_fs_promises = require("node:fs/promises");
30
- let node_path = require("node:path");
31
- node_path = __toESM(node_path, 1);
32
- let node_util = require("node:util");
33
- let _kubb_ast = require("@kubb/ast");
34
- //#region package.json
35
- var version = "5.10.2";
36
- //#endregion
37
- //#region ../../internals/utils/src/casing.ts
38
- /**
39
- * Shared implementation for camelCase and PascalCase conversion.
40
- * Splits on common word boundaries (spaces, hyphens, underscores, dots, slashes, colons)
41
- * and capitalizes each word according to `pascal`.
42
- *
43
- * When `pascal` is `true` the first word is also capitalized (PascalCase), otherwise only subsequent words are.
44
- */
45
- function toCamelOrPascal(text, pascal) {
46
- 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) => {
47
- if (word.length > 1 && word === word.toUpperCase()) return word;
48
- return (i === 0 && !pascal ? word.charAt(0).toLowerCase() : word.charAt(0).toUpperCase()) + word.slice(1);
49
- }).join("").replace(/[^a-zA-Z0-9]/g, "");
50
- }
51
- /**
52
- * Converts `text` to camelCase.
53
- *
54
- * @example Word boundaries
55
- * `camelCase('hello-world') // 'helloWorld'`
56
- *
57
- * @example With a prefix
58
- * `camelCase('tag', { prefix: 'create' }) // 'createTag'`
59
- */
60
- function camelCase(text, { prefix = "", suffix = "" } = {}) {
61
- return toCamelOrPascal(`${prefix} ${text} ${suffix}`, false);
62
- }
63
- //#endregion
64
- //#region ../../internals/utils/src/errors.ts
65
- /**
66
- * Coerces an unknown thrown value to an `Error` instance.
67
- * Returns the value as-is when it is already an `Error`; otherwise wraps it with `String(value)`.
68
- *
69
- * @example
70
- * ```ts
71
- * try { ... } catch(err) {
72
- * throw new Error('Build failed', { cause: toError(err) })
73
- * }
74
- * ```
75
- */
76
- function toError(value) {
77
- return value instanceof Error ? value : new Error(String(value));
78
- }
79
- /**
80
- * Extracts a human-readable message from any thrown value.
81
- *
82
- * @example
83
- * ```ts
84
- * getErrorMessage(new Error('oops')) // 'oops'
85
- * getErrorMessage('plain string') // 'plain string'
86
- * ```
87
- */
88
- function getErrorMessage(value) {
89
- return value instanceof Error ? value.message : String(value);
90
- }
91
- /**
92
- * Returns `error` followed by every error in its `cause` chain, outermost first. Stops at a
93
- * non-`Error` cause or a cycle.
94
- *
95
- * @example
96
- * ```ts
97
- * getErrorChain(new Error('Config failed loading', { cause: new Error('boom') })).map((error) => error.message)
98
- * // ['Config failed loading', 'boom']
99
- * ```
100
- */
101
- function getErrorChain(error) {
102
- const chain = [];
103
- for (let current = error; current instanceof Error && !chain.includes(current); current = current.cause) chain.push(current);
104
- return chain;
105
- }
106
- //#endregion
107
- //#region ../../internals/utils/src/jsonPointer.ts
108
- /**
109
- * Escapes a single JSON pointer reference token per RFC 6901 (`~` → `~0`, `/` → `~1`), so a
110
- * name holding those characters maps to a distinct pointer.
111
- *
112
- * @example
113
- * ```ts
114
- * escapePointerToken('/pets/{id}') // '~1pets~1{id}'
115
- * ```
116
- */
117
- function escapePointerToken(token) {
118
- return token.replaceAll("~", "~0").replaceAll("/", "~1");
119
- }
120
- //#endregion
121
- //#region ../../internals/utils/src/runtime.ts
122
- const isBun = typeof Bun !== "undefined";
123
- const isDeno = "Deno" in globalThis;
124
- /**
125
- * The JavaScript runtime executing the current process: its name, version and whether it is Bun.
126
- *
127
- * @example
128
- * ```ts
129
- * runtime.name // 'bun' when run with `bun kubb`, 'node' otherwise
130
- * ```
131
- */
132
- const runtime = {
133
- isBun,
134
- ...detect()
135
- };
136
- function detect() {
137
- if (isBun) return {
138
- name: "bun",
139
- version: process.versions.bun ?? ""
140
- };
141
- if (isDeno) return {
142
- name: "deno",
143
- version: globalThis.Deno?.version?.deno ?? ""
144
- };
145
- return {
146
- name: "node",
147
- version: process.versions?.node ?? ""
148
- };
149
- }
150
- //#endregion
151
- //#region ../../internals/utils/src/fs.ts
152
- /**
153
- * Reads the file at `path` as a UTF-8 string.
154
- * Uses `Bun.file().text()` when running under Bun, `fs.readFile` otherwise.
155
- *
156
- * @example
157
- * ```ts
158
- * const source = await read('./src/Pet.ts')
159
- * ```
160
- */
161
- async function read(path) {
162
- if (runtime.isBun) return Bun.file(path).text();
163
- return (0, node_fs_promises.readFile)(path, { encoding: "utf8" });
164
- }
165
- /**
166
- * Whether `stored` already holds `source`, comparing on the trimmed text rather than the exact
167
- * bytes. Surrounding whitespace is what a formatter adds and what editors strip, and neither is a
168
- * reason to rewrite the file.
169
- *
170
- * Both sides are trimmed, so a storage that keeps bytes verbatim settles on the same answer as one
171
- * that normalizes what it stores. Trimming only `stored` would leave a source with leading
172
- * whitespace rewritten on every build, since the stored copy keeps the whitespace the comparison
173
- * has already dropped.
174
- */
175
- function matchesStored({ stored, source }) {
176
- return stored.trim() === source.trim();
177
- }
178
- /**
179
- * Writes `data` to `path`, trimming surrounding whitespace and ending the file with a single newline
180
- * the way prettier, biome, and oxfmt all do.
181
- * Skips the write when the trimmed content is empty, or when the file already holds that content.
182
- * Creates any missing parent directories automatically.
183
- * When `sanity` is `true`, re-reads the file after writing and throws if the content does not match.
184
- *
185
- * @example
186
- * ```ts
187
- * await write('./src/Pet.ts', source) // writes and returns the trimmed content plus a newline
188
- * await write('./src/Pet.ts', source) // null — file unchanged
189
- * await write('./src/Pet.ts', ' ') // null — empty content skipped
190
- * ```
191
- */
192
- async function write(path, data, options = {}) {
193
- const trimmed = data.trim();
194
- if (trimmed === "") return null;
195
- const content = `${trimmed}\n`;
196
- const resolved = (0, node_path.resolve)(path);
197
- let stored = options.stored;
198
- if (stored === void 0) {
199
- if (runtime.isBun) {
200
- const file = Bun.file(resolved);
201
- stored = await file.exists() ? await file.text() : null;
202
- } else try {
203
- stored = await (0, node_fs_promises.readFile)(resolved, { encoding: "utf-8" });
204
- } catch {
205
- stored = null;
206
- }
207
- }
208
- if (matchesStored({
209
- stored: stored ?? "",
210
- source: trimmed
211
- })) return null;
212
- if (runtime.isBun) {
213
- await Bun.write(resolved, content);
214
- return content;
215
- }
216
- try {
217
- await (0, node_fs_promises.writeFile)(resolved, content, { encoding: "utf-8" });
218
- } catch (error) {
219
- if (error.code !== "ENOENT") throw error;
220
- await (0, node_fs_promises.mkdir)((0, node_path.dirname)(resolved), { recursive: true });
221
- await (0, node_fs_promises.writeFile)(resolved, content, { encoding: "utf-8" });
222
- }
223
- if (options.sanity) {
224
- const savedData = await (0, node_fs_promises.readFile)(resolved, { encoding: "utf-8" });
225
- if (savedData !== content) throw new Error(`Sanity check failed for ${path}\n\nData[${data.length}]:\n${data}\n\nSaved[${savedData.length}]:\n${savedData}\n`);
226
- return savedData;
227
- }
228
- return content;
229
- }
230
- /**
231
- * Converts a filesystem path to use POSIX (`/`) separators.
232
- *
233
- * Most of the codebase compares and composes paths as strings (prefix matching, joining for
234
- * import specifiers, splitting on `/`). On POSIX `path.resolve` already returns `/`-separated
235
- * paths, but on Windows it returns `\`-separated paths, which breaks every such comparison.
236
- *
237
- * Routing every path that crosses a module boundary through `toPosixPath` keeps the rest of the
238
- * code platform-agnostic. The conversion runs unconditionally so Windows-specific behavior is
239
- * exercisable from POSIX CI.
240
- *
241
- * @example
242
- * toPosixPath('C:\\repo\\src\\pet.ts') // 'C:/repo/src/pet.ts'
243
- */
244
- function toPosixPath(filePath) {
245
- return filePath.replaceAll("\\", "/");
246
- }
247
- /**
248
- * Resolves to `true` when `path` is `parent` itself or nested inside it. Both sides are resolved
249
- * to absolute paths first, so relative and `..`-containing inputs compare correctly.
250
- *
251
- * Guards a destructive or an out-of-tree operation: before wiping an output directory, check that
252
- * it does not contain the project root, and before loading a path a caller supplied, check that it
253
- * did not escape the directory it is allowed to read from.
254
- *
255
- * @example
256
- * isPathInside('./src/gen', '.') // true — nested inside the root
257
- * isPathInside('.', '.') // true — the same directory counts as inside
258
- * isPathInside('.', './src/gen') // false — the root is not inside its own output
259
- * isPathInside('../other', '.') // false — escapes the root
260
- */
261
- function isPathInside(path, parent) {
262
- const resolvedPath = (0, node_path.resolve)(path);
263
- const resolvedParent = (0, node_path.resolve)(parent);
264
- if (resolvedPath === resolvedParent) return true;
265
- const rel = (0, node_path.relative)(resolvedParent, resolvedPath);
266
- return rel !== "" && !rel.startsWith("..") && !(0, node_path.isAbsolute)(rel);
267
- }
268
- //#endregion
269
- //#region ../../internals/utils/src/promise.ts
270
- /**
271
- * Runs `run` over every item with at most `limit` in flight. Workers share one iterator, so each
272
- * takes the next item the moment it frees up instead of waiting for a batch to drain.
273
- *
274
- * @example
275
- * ```ts
276
- * await inParallel({ items: files, limit: 50, run: (file) => storage.writeItem(file.path, file.source) })
277
- * ```
278
- */
279
- async function inParallel({ items, limit, run }) {
280
- const queue = items.entries();
281
- const worker = async () => {
282
- for (const [index, item] of queue) await run(item, index);
283
- };
284
- await Promise.all(Array.from({ length: Math.min(limit, items.length) }, () => worker()));
285
- }
286
- //#endregion
287
- //#region ../../internals/utils/src/time.ts
288
- /**
289
- * Calculates elapsed time in milliseconds from a high-resolution `process.hrtime` start time.
290
- * Rounds to 2 decimal places for sub-millisecond precision without noise.
291
- *
292
- * @example
293
- * ```ts
294
- * const start = process.hrtime()
295
- * doWork()
296
- * getElapsedMs(start) // 42.35
297
- * ```
298
- */
299
- function getElapsedMs(hrStart) {
300
- const [seconds, nanoseconds] = process.hrtime(hrStart);
301
- const ms = seconds * 1e3 + nanoseconds / 1e6;
302
- return Math.round(ms * 100) / 100;
303
- }
304
- /**
305
- * Converts a millisecond duration into a human-readable string (`ms`, `s`, or `m s`).
306
- *
307
- * @example
308
- * ```ts
309
- * formatMs(250) // '250ms'
310
- * formatMs(1500) // '1.50s'
311
- * formatMs(90000) // '1m 30.0s'
312
- * ```
313
- */
314
- function formatMs(ms) {
315
- if (ms >= 6e4) return `${Math.floor(ms / 6e4)}m ${(ms % 6e4 / 1e3).toFixed(1)}s`;
316
- if (ms >= 1e3) return `${(ms / 1e3).toFixed(2)}s`;
317
- return `${Math.round(ms)}ms`;
318
- }
319
- //#endregion
320
- //#region src/diagnosticCatalog.ts
321
- /**
322
- * Every diagnostic code with its docs entry: a short title, what triggers it, and how to resolve
323
- * it. The source of truth for {@link diagnosticCode}, and the kubb.dev `/reference/diagnostics`
324
- * sections mirror it.
325
- */
326
- const diagnosticCatalog = {
327
- unknown: {
328
- code: "KUBB_UNKNOWN",
329
- title: "Unknown error",
330
- cause: "An error was thrown without a stable Kubb code, so it is reported as-is.",
331
- 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."
332
- },
333
- inputNotFound: {
334
- code: "KUBB_INPUT_NOT_FOUND",
335
- title: "Input not found",
336
- cause: "The file set as `input` (or passed as `kubb generate PATH`) could not be read. A URL reports `KUBB_INPUT_REQUEST_FAILED` or `KUBB_INPUT_UNREACHABLE` instead.",
337
- fix: "Check that the path exists and is readable, then set it as `input` or pass it on the CLI."
338
- },
339
- inputRequestFailed: {
340
- code: "KUBB_INPUT_REQUEST_FAILED",
341
- title: "Input request failed",
342
- cause: "A URL set as `input` (or reached through a `$ref`) answered with a 4xx or 5xx status instead of the document.",
343
- fix: "Open the URL to see what the server returns. A 401 or 403 needs credentials Kubb does not send, so download the document and point `input` at the local file. A 404 means the path is wrong, and a 5xx means the server itself failed."
344
- },
345
- inputUnreachable: {
346
- code: "KUBB_INPUT_UNREACHABLE",
347
- title: "Input unreachable",
348
- cause: "A URL set as `input` (or reached through a `$ref`) never answered, so the request failed before a status came back. A refused connection, an unknown host, an expired certificate, and a timeout all land here.",
349
- fix: "Check that the host is running and reachable from this machine. For a local server, start it and confirm the port matches the one in `input`."
350
- },
351
- inputRequired: {
352
- code: "KUBB_INPUT_REQUIRED",
353
- title: "Input required",
354
- cause: "An adapter is configured but no `input` was provided.",
355
- fix: "Set `input` to a file path, a URL, an inline spec (JSON/YAML string), or a parsed object in your Kubb config."
356
- },
357
- legacyInput: {
358
- code: "KUBB_LEGACY_INPUT",
359
- title: "Legacy input shape",
360
- cause: "`input` is a `{ path }` or `{ data }` wrapper, which v4 used to point at a document and v5 reads as the document itself.",
361
- fix: "Unwrap it: `input: { path: \"./petStore.yaml\" }` becomes `input: \"./petStore.yaml\"`, and `input: { data: spec }` becomes `input: spec`."
362
- },
363
- invalidDocument: {
364
- code: "KUBB_INVALID_DOCUMENT",
365
- title: "Invalid document",
366
- cause: "The `input` cannot be read as an OpenAPI or Swagger document: its JSON or YAML has a syntax error, it declares no `openapi` or `swagger` version field, or its version cannot be upgraded to OpenAPI 3.1.",
367
- fix: "Fix the syntax at the reported line, and check that `input` points at the spec and not an HTML page. Point `input` at a Swagger 2.0, OpenAPI 3.0, or OpenAPI 3.1 document, and check that a passed object is the spec itself rather than a wrapper around it."
368
- },
369
- invalidSpec: {
370
- code: "KUBB_INVALID_SPEC",
371
- title: "Invalid spec",
372
- cause: "The document does not pass OpenAPI schema validation. Kubb still generates from it, but the output can be incomplete or wrong.",
373
- fix: "Fix the reported problem in the spec. Run `kubb validate` to list every error, or set `validate: false` on the adapter to skip the check."
374
- },
375
- refNotFound: {
376
- code: "KUBB_REF_NOT_FOUND",
377
- title: "Reference not found",
378
- cause: "A `$ref` could not be resolved in the source document.",
379
- fix: "Add the missing definition (for example under `components.schemas`) or fix the `$ref`. Run `kubb validate` to check the spec."
380
- },
381
- invalidServerVariable: {
382
- code: "KUBB_INVALID_SERVER_VARIABLE",
383
- title: "Invalid server variable",
384
- cause: "A server variable value is not allowed by its `enum`.",
385
- fix: "Use one of the values listed in the server variable `enum`, or update the spec."
386
- },
387
- pluginNotFound: {
388
- code: "KUBB_PLUGIN_NOT_FOUND",
389
- title: "Plugin not found",
390
- cause: "A plugin that another plugin depends on is missing from the config.",
391
- fix: "Add the required plugin to the `plugins` array in kubb.config.ts, or remove the dependency on it."
392
- },
393
- incompatibleExtension: {
394
- code: "KUBB_INCOMPATIBLE_EXTENSION",
395
- title: "Incompatible extension",
396
- cause: "A plugin sets `meta.compatibility.kubb` or `meta.compatibility.node` to a range the running Kubb or Node.js version does not satisfy.",
397
- fix: "Upgrade Kubb or Node.js to a version in the range, or install a version of the plugin that supports your current Kubb and Node.js."
398
- },
399
- missingDependency: {
400
- code: "KUBB_MISSING_DEPENDENCY",
401
- title: "Missing dependency",
402
- cause: "A plugin lists another plugin in its `dependencies` record without `optional: true`, and the config does not include it.",
403
- fix: "Add the missing plugin to the `plugins` array in kubb.config.ts."
404
- },
405
- incompatibleDependency: {
406
- code: "KUBB_INCOMPATIBLE_DEPENDENCY",
407
- title: "Incompatible dependency",
408
- cause: "A plugin's `dependencies` record sets a `version` range, and the configured plugin's `meta.version` falls outside it.",
409
- fix: "Install a version of the dependency inside the range, or a version of the dependent plugin that supports the installed dependency."
410
- },
411
- pluginFailed: {
412
- code: "KUBB_PLUGIN_FAILED",
413
- title: "Plugin failed",
414
- cause: "A plugin threw while generating, or reported an error through `ctx.error`.",
415
- fix: "Check the plugin options and the node at `at:`. If it is a bug, report it with the stack at `report:`."
416
- },
417
- adapterFailed: {
418
- code: "KUBB_ADAPTER_FAILED",
419
- title: "Adapter failed",
420
- cause: "The adapter threw an unexpected error while parsing the input.",
421
- fix: "Check the input and the adapter options. If it is a bug, report it with the stack at `report:`."
422
- },
423
- parserFailed: {
424
- code: "KUBB_PARSER_FAILED",
425
- title: "Parser failed",
426
- cause: "A parser threw an unexpected error while printing a generated file.",
427
- fix: "Check the parser options. If it is a bug, report it with the stack at `report:`."
428
- },
429
- pluginWarning: {
430
- code: "KUBB_PLUGIN_WARNING",
431
- title: "Plugin warning",
432
- cause: "A plugin reported a non-fatal warning through `ctx.warn`.",
433
- fix: "Review the message. It does not fail the build; adjust the plugin options or input if the warning is unwanted."
434
- },
435
- pluginInfo: {
436
- code: "KUBB_PLUGIN_INFO",
437
- title: "Plugin info",
438
- cause: "A plugin reported an informational message through `ctx.info`.",
439
- fix: "Informational only. No action is required."
440
- },
441
- noContext: {
442
- code: "KUBB_NO_CONTEXT",
443
- title: "No plugin context",
444
- cause: "A `kubb/kit` composable such as `useKubb()` or `addGenerator()` ran outside the `setup` and `kubb:plugin:setup` of a plugin, so there is no plugin to apply it to.",
445
- fix: "Call the composable inside `setup` or `kubb:plugin:setup`, including in code that setup awaits."
446
- },
447
- unsupportedFormat: {
448
- code: "KUBB_UNSUPPORTED_FORMAT",
449
- title: "Unsupported format",
450
- cause: "A schema uses a `format` Kubb does not map to a specific type, so it falls back to the base type.",
451
- fix: "Use a format Kubb supports, or handle the custom format with a parser or plugin."
452
- },
453
- deprecated: {
454
- code: "KUBB_DEPRECATED",
455
- title: "Deprecated",
456
- cause: "A referenced schema or operation is marked `deprecated`.",
457
- fix: "Migrate off the deprecated definition if the warning is unwanted."
458
- },
459
- adapterRequired: {
460
- code: "KUBB_ADAPTER_REQUIRED",
461
- title: "Adapter required",
462
- cause: "An action needs an adapter but none is configured.",
463
- fix: "Set `adapter` in kubb.config.ts, for example `adapterOas()`."
464
- },
465
- pathTraversal: {
466
- code: "KUBB_PATH_TRAVERSAL",
467
- title: "Path traversal",
468
- cause: "A resolved output path escaped the output directory, which can stem from a path traversal in the spec or a misconfigured `group.name`.",
469
- fix: "Keep generated paths within the output directory. Review the `group.name` function and the names coming from the spec."
470
- },
471
- cleanRoot: {
472
- code: "KUBB_CLEAN_ROOT",
473
- title: "Clean targets the project root",
474
- cause: "`output.clean` is enabled and `output.path` resolves to the project root or a parent of it, so cleaning would delete `kubb.config` and every source file.",
475
- fix: "Point `output.path` at a subdirectory such as `./src/gen` so clean only removes generated code, or disable `output.clean`."
476
- },
477
- invalidPluginOptions: {
478
- code: "KUBB_INVALID_PLUGIN_OPTIONS",
479
- title: "Invalid plugin options",
480
- cause: "A plugin was configured with options that cannot be honored, for example `output.mode: 'file'` paired with a `group` option.",
481
- fix: "Fix the plugin options. A single-file output has nothing to group, so remove the `group` option or use `output.mode: 'directory'`."
482
- },
483
- postGenerateFailed: {
484
- code: "KUBB_POST_GENERATE_FAILED",
485
- title: "Post-generate command failed",
486
- cause: "A post-generate command (`output.postGenerate`) exited with a non-zero status.",
487
- fix: "Check the command is installed and correct, and run it manually to see the error."
488
- },
489
- formatFailed: {
490
- code: "KUBB_FORMAT_FAILED",
491
- title: "Format failed",
492
- cause: "The formatter pass over the generated files failed.",
493
- fix: "Check the formatter (oxfmt, biome, or prettier) is installed and its config is valid, then run it manually on the output."
494
- },
495
- lintFailed: {
496
- code: "KUBB_LINT_FAILED",
497
- title: "Lint failed",
498
- cause: "The linter pass over the generated files failed.",
499
- fix: "Check the linter (oxlint, biome, or eslint) is installed and its config is valid, then run it manually on the output."
500
- },
501
- barrelDuplicateExport: {
502
- code: "KUBB_BARREL_DUPLICATE_EXPORT",
503
- title: "Duplicate barrel export",
504
- cause: "Two generated modules export the same name, so the barrel cannot re-export both.",
505
- fix: "Rename one of the colliding declarations, or configure the plugin resolver to produce distinct names."
506
- },
507
- internalError: {
508
- code: "KUBB_INTERNAL_ERROR",
509
- title: "Internal error",
510
- cause: "Kubb hit a state it does not expect. This is a bug in Kubb, not in your config.",
511
- fix: "Rerun with `--reporter json` or `--verbose` to get the stack. Then report it at https://github.com/kubb-labs/kubb/issues with the spec and config that trigger it."
512
- },
513
- performance: {
514
- code: "KUBB_PERFORMANCE",
515
- title: "Performance",
516
- cause: "Not a failure. Records a plugin’s elapsed time, summed into the run total.",
517
- fix: "No action. This is an informational metric."
518
- },
519
- updateAvailable: {
520
- code: "KUBB_UPDATE_AVAILABLE",
521
- title: "Update available",
522
- cause: "A newer Kubb version is published on npm than the one running.",
523
- fix: "Update the `@kubb/*` packages, for example `npm install -g @kubb/cli`, to get the latest fixes."
524
- }
525
- };
526
- /**
527
- * Stable codes Kubb attaches to a `Diagnostic`, derived from {@link diagnosticCatalog}. Reference
528
- * these instead of inlining the string at a throw site.
529
- */
530
- const diagnosticCode = Object.fromEntries(Object.entries(diagnosticCatalog).map(([key, { code }]) => [key, code]));
531
- //#endregion
532
- //#region src/formatDiagnostic.ts
533
- /** A problem's `help`, or the catalog fix. `info` gets none: its catalog fix says no action is needed. */
534
- function getHelp(problem) {
535
- if (problem.help || problem.severity === "info") return problem.help;
536
- return Diagnostics.explain(problem.code).fix;
537
- }
538
- /** The `cause` chain's messages, outermost first, minus those `message` already contains. */
539
- function getCauses(problem) {
540
- return getErrorChain(problem.cause).filter((error) => !problem.message.includes(error.message)).map((error) => error.name === "Error" ? error.message : `${error.name}: ${error.message}`);
541
- }
542
- /**
543
- * Accent color per severity, which paints the icon in the `human` layout (red error, yellow
544
- * warning, blue info). The code itself stays dim.
545
- */
546
- const severityStyle = {
547
- error: "red",
548
- warning: "yellow",
549
- info: "blue"
550
- };
551
- const severityIcon = {
552
- error: "✖",
553
- warning: "⚠",
554
- info: "ℹ"
555
- };
556
- /**
557
- * Codes for a crash, which carry the root cause's stack.
558
- */
559
- const crashCodes = /* @__PURE__ */ new Set([
560
- diagnosticCode.unknown,
561
- diagnosticCode.internalError,
562
- diagnosticCode.pluginFailed,
563
- diagnosticCode.adapterFailed,
564
- diagnosticCode.parserFailed
565
- ]);
566
- /**
567
- * Reduces a diagnostic to its JSON-safe fields plus a `docsUrl`, for machine-readable
568
- * consumers, with the catalog `title`, `cause`, and fix, and the `cause` error as `causes` and
569
- * `stack`. Absent optional fields are omitted.
570
- */
571
- function serialize(diagnostic) {
572
- const problem = Diagnostics.isProblem(diagnostic) ? diagnostic : void 0;
573
- const doc = problem ? Diagnostics.explain(problem.code) : void 0;
574
- const help = problem ? getHelp(problem) : void 0;
575
- const causes = problem ? getCauses(problem) : [];
576
- const stack = problem && crashCodes.has(problem.code) ? getErrorChain(problem.cause).at(-1)?.stack : void 0;
577
- return {
578
- code: diagnostic.code,
579
- severity: diagnostic.severity,
580
- message: diagnostic.message,
581
- ...doc ? {
582
- title: doc.title,
583
- cause: doc.cause
584
- } : {},
585
- ...problem?.location ? { location: problem.location } : {},
586
- ...help ? { help } : {},
587
- ...problem?.plugin ? { plugin: problem.plugin } : {},
588
- ...problem?.issues ? { issues: problem.issues } : {},
589
- ...causes.length ? { causes } : {},
590
- ...stack ? { stack } : {},
591
- ...diagnostic.code === diagnosticCode.unknown ? {} : { docsUrl: Diagnostics.docsUrl(diagnostic.code) }
592
- };
593
- }
594
- /**
595
- * Renders a {@link Diagnostic} as lines: a headline, then indented detail rows. `agent` (the default)
596
- * prints uncolored labeled rows (`at:`, `why:`, `fix:`, `caused by:`, `stack:` for a crash,
597
- * `docs:`, `report:`). `human` prints an icon, the bold message, and the code aligned to `width`,
598
- * with `at`, `fix`, the first cause, and `Learn more` for an error, and one row for a warning.
599
- * `verbose` adds the full stack.
600
- */
601
- function format(diagnostic, { audience = "agent", verbose = false, width = 0 } = {}) {
602
- const { code, severity, message } = diagnostic;
603
- const problem = Diagnostics.isProblem(diagnostic) ? diagnostic : void 0;
604
- const human = audience === "human";
605
- const paint = human ? node_util.styleText : (_format, text) => text;
606
- const [firstLine = "", ...rest] = message.split("\n");
607
- const pointer = problem?.location && "pointer" in problem.location ? problem.location.pointer : void 0;
608
- const help = problem ? getHelp(problem) : void 0;
609
- const causes = problem ? getCauses(problem) : [];
610
- const crash = problem ? crashCodes.has(problem.code) : false;
611
- const frames = (problem && (verbose || !human && crash) ? getErrorChain(problem.cause).at(-1)?.stack : void 0)?.split("\n").slice(1, verbose ? void 0 : 4).map((frame) => ` ${paint("dim", frame.trim())}`);
612
- if (!human) {
613
- const details = rest.filter((line) => line.trim()).map((line) => ` ${line}`);
614
- const row = (label, value) => {
615
- if (value) details.push(` ${label}: ${value}`);
616
- };
617
- row("at", pointer);
618
- if (problem && severity !== "info") row("why", Diagnostics.explain(problem.code).cause);
619
- row("fix", help);
620
- for (const cause of causes) row("caused by", cause);
621
- if (frames?.length) details.push(" stack:", ...frames);
622
- if (code !== diagnosticCode.unknown) row("docs", Diagnostics.docsUrl(code));
623
- row("report", problem?.issues);
624
- return [`${severity} ${code}${problem?.plugin ? ` [${problem.plugin}]` : ""}: ${firstLine}`, ...details];
625
- }
626
- const left = `${paint(severityStyle[severity], severityIcon[severity])} ${paint("bold", firstLine)}`;
627
- const gap = Math.max(2, width - (0, node_util.stripVTControlCharacters)(left).length - code.length);
628
- const headline = `${left}${" ".repeat(gap)}${paint("dim", code)}`;
629
- const frame = rest.filter((line) => line.trim()).map((line) => ` ${paint("dim", line)}`);
630
- const label = (name) => paint("dim", name.length < 4 ? name.padEnd(4) : `${name} `);
631
- const rows = [["at", pointer && paint("cyan", pointer)], ["fix", help]];
632
- if (severity !== "error") {
633
- const first = rows.find(([, value]) => value);
634
- return [
635
- headline,
636
- ...frame,
637
- ...first ? [` ${label(first[0])} ${first[1]}`] : []
638
- ];
639
- }
640
- rows.push(["caused by", causes[0]], ["report", problem?.issues && paint("cyan", problem.issues)]);
641
- const details = [...frame, ...rows.flatMap(([name, value]) => value ? [` ${label(name)} ${value}`] : [])];
642
- if (frames?.length) details.push(` ${paint("dim", "stack")}`, ...frames);
643
- if (code !== diagnosticCode.unknown) details.push(` ${paint("dim", "↳ Learn more")} ${paint("cyan", Diagnostics.docsUrl(code).replace(/^https:\/\//, ""))}`);
644
- return [headline, ...details];
645
- }
646
- //#endregion
647
- //#region src/Diagnostics.ts
648
- /**
649
- * Docs major version, derived from the package version so the link tracks the published major.
650
- */
651
- const docsMajor = version.split(".")[0] ?? "5";
652
- /**
653
- * Builds a type guard that narrows a {@link Diagnostic} to the variant for `kind`. A diagnostic
654
- * with no `kind` is treated as a `problem`.
655
- */
656
- function isKind(kind) {
657
- return (diagnostic) => (diagnostic.kind ?? "problem") === kind;
658
- }
659
- /**
660
- * Returns `true` when the diagnostic is a build {@link ProblemDiagnostic}.
661
- *
662
- * @example
663
- * ```ts
664
- * if (isProblem(diagnostic)) {
665
- * console.log(diagnostic.location)
666
- * }
667
- * ```
668
- */
669
- const isProblem = isKind("problem");
670
- /**
671
- * Returns `true` when the diagnostic is a per-plugin {@link PerformanceDiagnostic}.
672
- *
673
- * @example
674
- * ```ts
675
- * const timings = diagnostics.filter(isPerformance)
676
- * ```
677
- */
678
- const isPerformance = isKind("performance");
679
- /**
680
- * Returns `true` when the diagnostic is a version-update {@link UpdateDiagnostic}.
681
- *
682
- * @example
683
- * ```ts
684
- * if (isUpdate(diagnostic)) {
685
- * console.log(diagnostic.latestVersion)
686
- * }
687
- * ```
688
- */
689
- const isUpdate = isKind("update");
690
- const failedCode = {
691
- plugin: diagnosticCode.pluginFailed,
692
- adapter: diagnosticCode.adapterFailed,
693
- parser: diagnosticCode.parserFailed
694
- };
695
- const docsByCode = new Map(Object.values(diagnosticCatalog).map((doc) => [doc.code, doc]));
696
- const countKey = {
697
- error: "errors",
698
- warning: "warnings",
699
- info: "infos"
700
- };
701
- /**
702
- * Static helpers for working with {@link Diagnostic}s, plus the run-scoped sink
703
- * that lets deep code report a diagnostic without threading a callback.
704
- *
705
- * The sink lives in a single `AsyncLocalStorage` in the `@kubb/core` bundle.
706
- * `Diagnostics.scope` activates it for a run, so anything inside that run (the
707
- * adapter parse, a generator) reports through `Diagnostics.report` and lands
708
- * in the same run.
709
- */
710
- var Diagnostics = class Diagnostics {
711
- static #reporterStorage = new node_async_hooks.AsyncLocalStorage();
712
- /**
713
- * The diagnostic code catalog, exposed as `Diagnostics.code` (e.g. `Diagnostics.code.refNotFound`).
714
- */
715
- static code = diagnosticCode;
716
- /**
717
- * Type guard for a build {@link ProblemDiagnostic}.
718
- */
719
- static isProblem = isProblem;
720
- /**
721
- * Type guard for a version-update {@link UpdateDiagnostic}.
722
- */
723
- static isUpdate = isUpdate;
724
- /**
725
- * Type guard for a per-plugin {@link PerformanceDiagnostic}.
726
- */
727
- static isPerformance = isPerformance;
728
- /**
729
- * An `Error` that carries a {@link Diagnostic}, so structured problems can flow
730
- * through the existing throw/catch paths while keeping their code and location.
731
- *
732
- * @example
733
- * ```ts
734
- * throw new Diagnostics.Error({ code: diagnosticCode.refNotFound, severity: 'error', message: `Could not find ${ref}`, location: { kind: 'schema', pointer: ref, ref } })
735
- * ```
736
- */
737
- static Error = class DiagnosticError extends Error {
738
- diagnostic;
739
- constructor(diagnostic) {
740
- super(diagnostic.message, { cause: diagnostic.cause });
741
- this.name = "DiagnosticError";
742
- this.diagnostic = diagnostic;
743
- }
744
- };
745
- /**
746
- * Structural check for a {@link Diagnostics.Error}, including one thrown from a duplicated
747
- * `@kubb/core` copy where `instanceof` fails. Matches on the `name` and a `diagnostic`
748
- * that carries a `code`.
749
- */
750
- static isError(error) {
751
- if (error instanceof Diagnostics.Error) return true;
752
- if (!(error instanceof Error) || error.name !== "DiagnosticError") return false;
753
- const { diagnostic } = error;
754
- return typeof diagnostic === "object" && diagnostic !== null && typeof diagnostic.code === "string";
755
- }
756
- /**
757
- * Runs `fn` with `sink` as the active diagnostic sink for the whole async
758
- * subtree, so {@link Diagnostics.report} reaches it from anywhere inside.
759
- */
760
- static scope(sink, fn) {
761
- return Diagnostics.#reporterStorage.run(sink, fn);
762
- }
763
- /**
764
- * Collects a diagnostic into the active build via the run-scoped sink, without throwing.
765
- * Returns `true` when a run consumed it, `false` when called outside a {@link Diagnostics.scope}
766
- * (so callers can fall back to throwing). Use a `warning`/`info` severity for non-fatal issues.
767
- * For rendering a diagnostic live on the hook bus, use {@link Diagnostics.emit} instead.
768
- */
769
- static report(diagnostic) {
770
- const sink = Diagnostics.#reporterStorage.getStore();
771
- if (!sink) return false;
772
- sink(diagnostic);
773
- return true;
774
- }
775
- /**
776
- * Emits a diagnostic, or any thrown value, on the run's hooks so the loggers render it live.
777
- * A coded problem or an update goes to `kubb:diagnostic`. An uncoded one goes to `kubb:error`
778
- * whole, so every wrapper's message, its help, and the stack survive. To collect a diagnostic into
779
- * the build result from deep in a run, use {@link Diagnostics.report} instead.
780
- */
781
- static async emit(hooks, value) {
782
- const thrown = value instanceof Error || typeof value?.code !== "string";
783
- const diagnostic = thrown ? Diagnostics.from(value) : value;
784
- if (!isProblem(diagnostic) || diagnostic.code !== diagnosticCode.unknown) {
785
- await hooks.callHook("kubb:diagnostic", { diagnostic });
786
- return;
787
- }
788
- const { cause, help, message } = diagnostic;
789
- const bare = cause && !help && cause.message === message;
790
- await hooks.callHook("kubb:error", { error: thrown ? toError(value) : bare ? cause : new Diagnostics.Error(diagnostic) });
791
- }
792
- /**
793
- * Coerces any thrown value into a {@link ProblemDiagnostic}. A {@link Diagnostics.Error}
794
- * keeps its structured data, and anything else becomes a `KUBB_UNKNOWN` error.
795
- */
796
- static from(error) {
797
- const chain = getErrorChain(error);
798
- const coded = chain.findLast((current) => Diagnostics.isError(current));
799
- if (coded) {
800
- const { diagnostic } = coded;
801
- return diagnostic.cause || !crashCodes.has(diagnostic.code) ? diagnostic : {
802
- ...diagnostic,
803
- cause: coded
804
- };
805
- }
806
- const root = chain.at(-1);
807
- return {
808
- code: diagnosticCode.unknown,
809
- severity: "error",
810
- message: root ? root.message : getErrorMessage(error),
811
- cause: root
812
- };
813
- }
814
- /**
815
- * Coerces an error thrown by a plugin, adapter, or parser into a diagnostic attributed to it.
816
- * A structured {@link Diagnostics.Error} keeps its code. Any other error is a crash: it gets the
817
- * kind's `*_FAILED` code and the extension's `meta.issues` link, so the user reports it to the
818
- * extension's maintainers instead of to Kubb.
819
- */
820
- static fromExtension(error, { kind, extension }) {
821
- const diagnostic = Diagnostics.from(error);
822
- const name = extension.meta?.name ?? extension.name;
823
- const owner = kind === "plugin" ? { plugin: diagnostic.plugin ?? name } : {};
824
- const crashed = diagnostic.code === diagnosticCode.unknown && diagnostic.cause?.name !== "AbortError";
825
- const failed = Object.values(failedCode).includes(diagnostic.code);
826
- if (!crashed && !failed) return {
827
- ...diagnostic,
828
- ...owner
829
- };
830
- const issues = extension.meta?.issues;
831
- return {
832
- ...diagnostic,
833
- ...owner,
834
- code: crashed ? failedCode[kind] : diagnostic.code,
835
- message: crashed && kind !== "plugin" ? `${kind} "${name}" crashed: ${diagnostic.message}` : diagnostic.message,
836
- ...issues ? { issues } : {}
837
- };
838
- }
839
- /**
840
- * Builds a per-plugin performance record. Reporters sum these into the run total.
841
- */
842
- static performance({ plugin, duration }) {
843
- return {
844
- kind: "performance",
845
- code: diagnosticCode.performance,
846
- severity: "info",
847
- message: `${plugin} generated in ${Math.round(duration)}ms`,
848
- plugin,
849
- duration
850
- };
851
- }
852
- /**
853
- * Builds the version-update notice shown when a newer Kubb is published on npm.
854
- */
855
- static update({ currentVersion, latestVersion }) {
856
- return {
857
- kind: "update",
858
- code: diagnosticCode.updateAvailable,
859
- severity: "info",
860
- message: `Update available: v${currentVersion} → v${latestVersion}. Run \`npm install -g @kubb/cli\` to update.`,
861
- currentVersion,
862
- latestVersion
863
- };
864
- }
865
- /**
866
- * True when any diagnostic is an error, the severity that fails a build. Non-error
867
- * diagnostics are ignored.
868
- */
869
- static hasError(diagnostics) {
870
- return diagnostics.some((diagnostic) => diagnostic.severity === "error");
871
- }
872
- /**
873
- * Names of the plugins that failed, deduped, derived from the error diagnostics
874
- * that carry a `plugin`.
875
- */
876
- static failedPlugins(diagnostics) {
877
- return [...new Set(diagnostics.flatMap((diagnostic) => diagnostic.severity === "error" && diagnostic.plugin ? [diagnostic.plugin] : []))];
878
- }
879
- /**
880
- * Counts `problem` diagnostics by severity for the run summary. `performance` and
881
- * `update` diagnostics are ignored.
882
- */
883
- static count(diagnostics) {
884
- const counts = {
885
- errors: 0,
886
- warnings: 0,
887
- infos: 0
888
- };
889
- for (const diagnostic of diagnostics.filter(isProblem)) counts[countKey[diagnostic.severity]] += 1;
890
- return counts;
891
- }
892
- /**
893
- * Drops duplicate `problem` diagnostics that share a code, location pointer, and
894
- * plugin, so the same issue reported across several passes is shown once. Non-problem
895
- * diagnostics are always kept.
896
- */
897
- static dedupe(diagnostics) {
898
- const seen = /* @__PURE__ */ new Set();
899
- const result = [];
900
- for (const diagnostic of diagnostics) {
901
- if (!isProblem(diagnostic)) {
902
- result.push(diagnostic);
903
- continue;
904
- }
905
- const pointer = diagnostic.location && "pointer" in diagnostic.location ? diagnostic.location.pointer : "";
906
- const key = `${diagnostic.code} ${pointer} ${diagnostic.plugin ?? ""}`;
907
- if (seen.has(key)) continue;
908
- seen.add(key);
909
- result.push(diagnostic);
910
- }
911
- return result;
912
- }
913
- /**
914
- * Builds the kubb.dev docs URL for a diagnostic code, e.g.
915
- * `KUBB_REF_NOT_FOUND` → `https://kubb.dev/docs/5.x/reference/diagnostics#kubb-ref-not-found`.
916
- */
917
- static docsUrl(code) {
918
- const slug = code.toLowerCase().replaceAll("_", "-");
919
- return `https://kubb.dev/docs/${docsMajor}.x/reference/diagnostics#${slug}`;
920
- }
921
- /**
922
- * The catalog entry for a code: its title, cause, and fix. Mirrors the kubb.dev
923
- * `/reference/diagnostics#<slug>` section.
924
- */
925
- static explain(code) {
926
- return docsByCode.get(code);
927
- }
928
- /**
929
- * Reduces a diagnostic to its JSON-safe fields plus a `docsUrl`, for machine-readable
930
- * consumers, with the catalog `title`, `cause`, and fix, and the `cause` error as `causes` and
931
- * `stack`. Absent optional fields are omitted.
932
- */
933
- static serialize = serialize;
934
- /**
935
- * Renders a diagnostic as lines for an `agent` (the default) or a `human`. See {@link format}.
936
- */
937
- static format = format;
938
- };
939
- //#endregion
940
- //#region src/defineExtension.ts
941
- /**
942
- * Returns `meta`, or `{ name }` for an extension that only sets the deprecated `name`. Throws `KUBB_INVALID_PLUGIN_OPTIONS` when it has neither.
943
- */
944
- function resolveMeta(extension) {
945
- const { name, meta } = extension;
946
- if (meta) return meta;
947
- if (name) return { name };
948
- const keys = Object.keys(extension);
949
- throw new Diagnostics.Error({
950
- code: Diagnostics.code.invalidPluginOptions,
951
- severity: "error",
952
- message: `An extension has neither \`meta.name\` nor \`name\`. Received keys: ${keys.length ? keys.join(", ") : "none"}.`,
953
- help: "Set `meta: { name }` on the plugin or parser.",
954
- location: { kind: "config" }
955
- });
956
- }
957
- /**
958
- * Throws `KUBB_INCOMPATIBLE_EXTENSION` when the running Kubb or Node.js version is outside `meta.compatibility`.
959
- */
960
- function checkCompatibility(meta) {
961
- const checks = [{
962
- target: "Kubb",
963
- range: meta.compatibility?.kubb,
964
- version
965
- }, {
966
- target: "Node.js",
967
- range: meta.compatibility?.node,
968
- version: process.versions.node
969
- }];
970
- for (const { target, range, version } of checks) {
971
- if (!range || (0, verkit.satisfies)(version, range, { includePrerelease: true })) continue;
972
- throw new Diagnostics.Error({
973
- code: Diagnostics.code.incompatibleExtension,
974
- severity: "error",
975
- message: `"${meta.name}" requires ${target} ${range}, but ${version} is running.`,
976
- help: `Use a ${target} version that satisfies ${range}, or a version of "${meta.name}" that supports ${target} ${version}.`,
977
- location: { kind: "config" },
978
- plugin: meta.name
979
- });
980
- }
981
- }
982
- /**
983
- * Throws `KUBB_MISSING_DEPENDENCY` for a missing required entry in a `dependencies` record, and
984
- * `KUBB_INCOMPATIBLE_DEPENDENCY` when an entry's `meta.version` is out of range. Arrays are not checked.
985
- */
986
- function checkDependencies({ name, dependencies, plugins }) {
987
- if (!dependencies || Array.isArray(dependencies)) return;
988
- for (const [dependencyName, dependency] of Object.entries(dependencies)) {
989
- const target = plugins.get(dependencyName);
990
- if (!target) {
991
- if (dependency?.optional) continue;
992
- throw new Diagnostics.Error({
993
- code: Diagnostics.code.missingDependency,
994
- severity: "error",
995
- message: `Plugin "${dependencyName}" is required by "${name}" but not found.`,
996
- help: `Add "${dependencyName}" to the \`plugins\` array in kubb.config.ts.`,
997
- location: { kind: "config" },
998
- plugin: name
999
- });
1000
- }
1001
- const range = dependency?.version;
1002
- const version = target.meta?.version;
1003
- if (!range || !version || (0, verkit.satisfies)(version, range, { includePrerelease: true })) continue;
1004
- throw new Diagnostics.Error({
1005
- code: Diagnostics.code.incompatibleDependency,
1006
- severity: "error",
1007
- message: `"${name}" requires "${dependencyName}" ${range}, but ${version} is configured.`,
1008
- help: `Install a version of "${dependencyName}" that satisfies ${range}.`,
1009
- location: { kind: "config" },
1010
- plugin: name
1011
- });
1012
- }
1013
- }
1014
- /**
1015
- * Builds the factory behind `defineExtension`. It passes `{}` when called without options, and carries `kind` and
1016
- * `meta` so tools can read them without calling it.
1017
- *
1018
- * @internal
1019
- */
1020
- function createExtensionFactory({ kind, meta, build }) {
1021
- return Object.assign((options = {}) => build(options), {
1022
- kind,
1023
- meta
1024
- });
1025
- }
1026
- function defineExtension(definition) {
1027
- switch (definition.kind) {
1028
- case "plugin": {
1029
- const { meta, dependencies, enforce, hooks = {}, setup } = definition;
1030
- return createExtensionFactory({
1031
- kind: "plugin",
1032
- meta,
1033
- build: (options) => ({
1034
- name: meta.name,
1035
- meta,
1036
- options,
1037
- dependencies,
1038
- enforce,
1039
- hooks,
1040
- setup
1041
- })
1042
- });
1043
- }
1044
- case "adapter": {
1045
- const { meta, setup, build } = definition;
1046
- return createExtensionFactory({
1047
- kind: "adapter",
1048
- meta,
1049
- build: (raw) => {
1050
- const options = setup ? setup(raw) : raw;
1051
- return Object.assign(build(options), {
1052
- name: meta.name,
1053
- meta,
1054
- options
1055
- });
1056
- }
1057
- });
1058
- }
1059
- case "parser": {
1060
- const { meta, build } = definition;
1061
- return createExtensionFactory({
1062
- kind: "parser",
1063
- meta,
1064
- build: (options) => ({
1065
- ...build(options),
1066
- name: meta.name,
1067
- meta,
1068
- options
1069
- })
1070
- });
1071
- }
1072
- }
1073
- }
1074
- //#endregion
1075
- //#region src/composables.ts
1076
- const kubbContextKey = Symbol.for("kubb.context");
1077
- const host = globalThis;
1078
- /**
1079
- * Holds the setup context of the plugin whose `setup` or `kubb:plugin:setup` is running. `KubbDriver` sets it for each plugin.
1080
- *
1081
- * The store lives on `globalThis`, so the ESM and CommonJS builds of `@kubb/core` share one. A plugin that a
1082
- * CommonJS config loads would otherwise read an empty store and fail with `KUBB_NO_CONTEXT`.
1083
- */
1084
- const kubbContext = host[kubbContextKey] ??= new node_async_hooks.AsyncLocalStorage();
1085
- function requireContext(caller) {
1086
- const ctx = kubbContext.getStore();
1087
- if (ctx) return ctx;
1088
- throw new Diagnostics.Error({
1089
- code: Diagnostics.code.noContext,
1090
- severity: "error",
1091
- message: `\`${caller}()\` was called outside a plugin setup.`,
1092
- help: `Call \`${caller}()\` inside \`setup\` or \`kubb:plugin:setup\`, including in code that setup awaits.`
1093
- });
1094
- }
1095
- /**
1096
- * Returns the context of the plugin whose `kubb:plugin:setup` is running. It stays available after an `await`.
1097
- * Throws `KUBB_NO_CONTEXT` outside setup.
1098
- */
1099
- function useKubb() {
1100
- return requireContext("useKubb");
1101
- }
1102
- /**
1103
- * Returns the same context as {@link useKubb}, or `undefined` outside `setup` and `kubb:plugin:setup`.
1104
- */
1105
- function tryUseKubb() {
1106
- return kubbContext.getStore();
1107
- }
1108
- /**
1109
- * Registers generators on the plugin being set up, like `ctx.addGenerator`.
1110
- *
1111
- * @example
1112
- * `addGenerator(typeGenerator, enumGenerator)`
1113
- */
1114
- function addGenerator(...generators) {
1115
- requireContext("addGenerator").addGenerator(...generators);
1116
- }
1117
- /**
1118
- * Sets the resolver of the plugin being set up, like `ctx.setResolver`.
1119
- */
1120
- function setResolver(resolver) {
1121
- requireContext("setResolver").setResolver(resolver);
1122
- }
1123
- /**
1124
- * Adds a macro to the plugin being set up, like `ctx.addMacro`.
1125
- */
1126
- function addMacro(macro) {
1127
- requireContext("addMacro").addMacro(macro);
1128
- }
1129
- /**
1130
- * Replaces the macros of the plugin being set up, like `ctx.setMacros`.
1131
- */
1132
- function setMacros(macros) {
1133
- requireContext("setMacros").setMacros(macros);
1134
- }
1135
- /**
1136
- * Adds a raw file to the build output, like `ctx.injectFile`.
1137
- */
1138
- function injectFile(file) {
1139
- requireContext("injectFile").injectFile(file);
1140
- }
1141
- /**
1142
- * Returns the options the user passed to the plugin being set up, like `ctx.options`.
1143
- */
1144
- function useOptions() {
1145
- return requireContext("useOptions").options;
1146
- }
1147
- /**
1148
- * Sets the resolved options of the plugin being set up, like `ctx.setOptions`.
1149
- */
1150
- function setOptions(options) {
1151
- requireContext("setOptions").setOptions(options);
1152
- }
1153
- /**
1154
- * Returns the resolved build configuration, like `ctx.config`.
1155
- */
1156
- function useConfig() {
1157
- return requireContext("useConfig").config;
1158
- }
1159
- /**
1160
- * Returns another plugin from the config, typed through `Kubb.PluginRegistry`, like `ctx.requirePlugin`.
1161
- */
1162
- function requirePlugin(name) {
1163
- return requireContext("requirePlugin").requirePlugin(name);
1164
- }
1165
- //#endregion
1166
- //#region src/definePlugin.ts
1167
- /**
1168
- * Merges the `output.mode` default into the output config and validates the combination.
1169
- * Throws `KUBB_INVALID_PLUGIN_OPTIONS` when `mode: 'file'` is paired with a `group` option,
1170
- * since a single-file output has nothing to group.
1171
- *
1172
- * An omitted `mode` follows the shape of `path`: an extension means a single file, anything
1173
- * else is a directory. Plugin defaults such as `path: 'types'` name a directory, so they
1174
- * generate without the caller spelling out `mode`.
1175
- */
1176
- function normalizeOutput({ output, group, pluginName }) {
1177
- const mode = output.mode ?? (node_path.default.extname(output.path) ? "file" : "directory");
1178
- if (mode === "file" && group) throw new Diagnostics.Error({
1179
- code: Diagnostics.code.invalidPluginOptions,
1180
- severity: "error",
1181
- message: `Plugin "${pluginName}" resolves \`output.mode\` to 'file' but also configures a \`group\` option.`,
1182
- help: "A single-file output has nothing to group. Remove the `group` option, give `output.path` an extensionless directory name, or set `output.mode: 'directory'` explicitly.",
1183
- location: { kind: "config" },
1184
- plugin: pluginName
1185
- });
1186
- return {
1187
- ...output,
1188
- mode
1189
- };
1190
- }
1191
- /** Throws `KUBB_INVALID_PLUGIN_OPTIONS`, listing the allowed values, when `value` is not one of `allowed`. */
1192
- function assertPluginOption({ plugin, option, value, allowed }) {
1193
- if (allowed.includes(value)) return;
1194
- const format = (item) => typeof item === "string" ? JSON.stringify(item) : String(item);
1195
- const expected = allowed.map(format).join(", ");
1196
- throw new Diagnostics.Error({
1197
- code: Diagnostics.code.invalidPluginOptions,
1198
- severity: "error",
1199
- message: `Plugin "${plugin}" option \`${option}\` is ${format(value)}, but it must be one of ${expected}.`,
1200
- help: `Set \`${option}\` to one of ${expected}.`,
1201
- location: { kind: "config" },
1202
- plugin
1203
- });
1204
- }
1205
- /**
1206
- * Defines a plugin from one object and returns a factory that takes the user's options.
1207
- *
1208
- * @deprecated Use `defineExtension` with `kind: 'plugin'` instead.
1209
- */
1210
- function definePlugin(definition) {
1211
- return defineExtension({
1212
- kind: "plugin",
1213
- ...definition
1214
- });
1215
- }
1216
- //#endregion
1217
- //#region src/input.ts
1218
- /**
1219
- * Classifies an `input` value so callers branch on it once instead of repeating the checks.
1220
- *
1221
- * A non-string is a parsed spec (`object`). A string is `inline` when it holds OpenAPI content,
1222
- * meaning it starts with `{` or `[`, spans multiple lines, or opens with a YAML `openapi:` or
1223
- * `swagger:` key. Otherwise a string is a `url` when it parses as one, or a `file` path.
1224
- */
1225
- function getInputKind(input) {
1226
- if (typeof input !== "string") return "object";
1227
- const trimmed = input.trimStart();
1228
- if (trimmed.startsWith("{") || trimmed.startsWith("[") || input.includes("\n") || /^(openapi|swagger)\s*:/i.test(trimmed)) return "inline";
1229
- if (URL.canParse(input)) return "url";
1230
- return "file";
1231
- }
1232
- /**
1233
- * The v4 `input` wrapper keys. v4 typed `input` as `{ path }` or `{ data }`; v5 takes the value
1234
- * directly, so the wrapper now matches the "already-parsed document" branch and silently yields
1235
- * an empty build.
1236
- */
1237
- const legacyInputKeys = ["path", "data"];
1238
- /**
1239
- * Detects the v4 `{ path }` / `{ data }` wrapper so it fails loudly instead of being read as a
1240
- * document. A real spec always carries more than these keys, so an object whose keys are drawn
1241
- * only from them is the old shape rather than a document that happens to have a `path` property.
1242
- */
1243
- function isLegacyInput(input) {
1244
- if (Array.isArray(input)) return input.some(isLegacyInput);
1245
- if (typeof input !== "object" || input === null) return false;
1246
- const keys = Object.keys(input);
1247
- return keys.length > 0 && keys.every((key) => legacyInputKeys.includes(key));
1248
- }
1249
- /**
1250
- * Normalizes `config.input` into an `AdapterSource` the adapter can parse.
1251
- *
1252
- * A parsed object and inline content become `{ type: 'data' }`; a URL is kept verbatim and a
1253
- * local path is resolved against `config.root`, both as `{ type: 'path' }`.
1254
- */
1255
- function inputToAdapterSource(config) {
1256
- const input = config.input;
1257
- if (input && isLegacyInput(input)) throw new Diagnostics.Error({
1258
- code: Diagnostics.code.legacyInput,
1259
- severity: "error",
1260
- message: "The `input` option uses the v4 `{ path }` / `{ data }` wrapper.",
1261
- help: "Unwrap it: `input: { path: \"./petStore.yaml\" }` becomes `input: \"./petStore.yaml\"`, and `input: { data: spec }` becomes `input: spec`.",
1262
- location: { kind: "config" }
1263
- });
1264
- if (!input) throw new Diagnostics.Error({
1265
- code: Diagnostics.code.inputRequired,
1266
- severity: "error",
1267
- message: "An adapter is configured without an input.",
1268
- help: "Set `input` to a file path, a URL, an inline spec (JSON/YAML string), or a parsed object in your Kubb config.",
1269
- location: { kind: "config" }
1270
- });
1271
- if (typeof input !== "string") return {
1272
- type: "data",
1273
- data: input
1274
- };
1275
- const kind = getInputKind(input);
1276
- if (kind === "inline") return {
1277
- type: "data",
1278
- data: input
1279
- };
1280
- if (kind === "url") return {
1281
- type: "path",
1282
- path: input
1283
- };
1284
- return {
1285
- type: "path",
1286
- path: (0, node_path.resolve)(config.root, input)
1287
- };
1288
- }
1289
- //#endregion
1290
- //#region src/Resolver.ts
1291
- function isNamespace(value) {
1292
- return typeof value === "object" && value !== null && !Array.isArray(value);
1293
- }
1294
- /**
1295
- * Shared brand for reaching a resolver's build options. `Resolver.merge` reads this instead of
1296
- * relying on `instanceof`, which fails when a CommonJS config and the ESM CLI each load their own
1297
- * copy of `@kubb/core`. `Symbol.for` resolves to one key across those copies, so the options stay
1298
- * reachable and a `file` override is never dropped.
1299
- */
1300
- const resolverOptions = Symbol.for("@kubb/core/resolver/options");
1301
- /**
1302
- * Builds a nested file path from a dotted name. Splits on dots that precede a letter
1303
- * (so version numbers embedded in operationIds like `v2025.0` stay intact), camelCases
1304
- * every segment, and joins with `/`.
1305
- *
1306
- * Empty segments are dropped before joining. They arise when the name starts with a dot
1307
- * followed by a letter (e.g. `..Schema` splits into `['..', 'Schema']` and `'..'` cases to
1308
- * an empty string). Without this a leading `/` would form, which `path.resolve` reads as an
1309
- * absolute path, letting generated files escape the configured output directory.
1310
- *
1311
- * @example Nested path from a dotted name
1312
- * `toFilePath('pet.petId') // 'pet/petId'`
1313
- */
1314
- function toFilePath(name) {
1315
- return name.split(/\.(?=[a-zA-Z])/).map((part) => camelCase(part)).filter(Boolean).join("/");
1316
- }
1317
- /** Throws `KUBB_PATH_TRAVERSAL` when `target` lies outside `parent`; `target === parent` stays allowed. */
1318
- function assertInside({ target, parent, message, help }) {
1319
- const parentWithSep = parent.endsWith(node_path.default.sep) ? parent : `${parent}${node_path.default.sep}`;
1320
- if (target === parent || target.startsWith(parentWithSep)) return;
1321
- throw new Diagnostics.Error({
1322
- code: Diagnostics.code.pathTraversal,
1323
- severity: "error",
1324
- message,
1325
- help,
1326
- location: { kind: "config" }
1327
- });
1328
- }
1329
- /**
1330
- * Built-in `file.baseName`: casts the identifier with `toFilePath` and appends the extension.
1331
- */
1332
- function toBaseName({ name, extname }) {
1333
- return `${toFilePath(name)}${extname}`;
1334
- }
1335
- /**
1336
- * Base constraint for all plugin resolver objects.
1337
- *
1338
- * The built-in machinery lives under `default`. Generators call the top-level `name`, `file`,
1339
- * and `imports`, and a plugin overrides `name` and `file` to set its conventions. Extend with
1340
- * top-level helpers (`typeName`, …) and/or grouped namespaces (`query`, `schema`, …).
1341
- *
1342
- * @example Top-level helper
1343
- * ```ts
1344
- * type MyResolver = Resolver & {
1345
- * typeName(name: string): string
1346
- * }
1347
- * ```
1348
- *
1349
- * @example Grouped namespace
1350
- * ```ts
1351
- * type MyResolver = Resolver & {
1352
- * query: {
1353
- * name(node: OperationNode): string
1354
- * keyName(node: OperationNode): string
1355
- * }
1356
- * }
1357
- * ```
1358
- */
1359
- var Resolver = class Resolver {
1360
- static #patternCache = /* @__PURE__ */ new Map();
1361
- static #optionsCache = /* @__PURE__ */ new WeakMap();
1362
- pluginName;
1363
- /** The built-in machinery, untouched by `name`/`file` overrides and built once since the driver reads it per node. */
1364
- default;
1365
- #options;
1366
- #baseName;
1367
- #filePath;
1368
- constructor(options) {
1369
- this.pluginName = options.pluginName;
1370
- this.#options = options;
1371
- this.#baseName = options.file?.baseName ? options.file.baseName.bind(this) : toBaseName;
1372
- this.#filePath = options.file?.path ? options.file.path.bind(this) : void 0;
1373
- this.default = {
1374
- name: camelCase,
1375
- options: this.#resolveOptions.bind(this),
1376
- path: this.#resolvePath.bind(this),
1377
- file: this.#resolveFile.bind(this),
1378
- banner: this.#resolveBanner.bind(this),
1379
- footer: this.#resolveFooter.bind(this)
1380
- };
1381
- this.#apply(options);
1382
- }
1383
- /** Exposes the raw build options so `Resolver.merge` can read them across `@kubb/core` copies. */
1384
- get [resolverOptions]() {
1385
- return this.#options;
1386
- }
1387
- name(name) {
1388
- return this.default.name(name);
1389
- }
1390
- file(options) {
1391
- return this.#resolveFile(options);
1392
- }
1393
- /**
1394
- * Builds one `ImportNode` per unique schema referenced in the tree, in first-occurrence
1395
- * order. Each ref's target resolves through `resolveRefName`, so collision- or macro-renamed
1396
- * schemas (`targetName`) import the emitted name. Names and paths go through the top-level
1397
- * `name` and `file`, so import entries follow the plugin's conventions, and a per-call
1398
- * `name` override wins over both.
1399
- *
1400
- * The subtree scan runs through `collectImportedRefNames`, which memoizes by node identity, so a
1401
- * schema shared across the ts, zod, and faker plugins is walked once and every plugin's resolver
1402
- * reads the same ref set instead of re-scanning it per plugin.
1403
- */
1404
- imports(options) {
1405
- const { node, root, output, group, extname = ".ts", name } = options;
1406
- const resolveName = name ?? ((schemaName) => this.name(schemaName));
1407
- return (0, _kubb_ast.collectImportedRefNames)(node).map((schemaName) => _kubb_ast.ast.factory.createImport({
1408
- name: [resolveName(schemaName)],
1409
- path: this.file({
1410
- name: schemaName,
1411
- extname,
1412
- root,
1413
- output,
1414
- group
1415
- }).path
1416
- }));
1417
- }
1418
- /**
1419
- * Folds each `override` over `base`, left to right, and returns a new resolver with helpers
1420
- * re-bound. Top-level keys replace, and a namespace (or `file`) merges per method, so overriding
1421
- * `query.name` keeps the base `query.keyName`. The last override wins per key. Used when applying
1422
- * `setResolver` partial overrides, and to compose shared resolver fragments without spreading each
1423
- * namespace by hand. Reads a resolver's options through the shared brand rather than `instanceof`,
1424
- * so a `file` override survives even when `base` and `override` come from different `@kubb/core`
1425
- * copies.
1426
- *
1427
- * @example Fold several partial overrides onto a resolver
1428
- * ```ts
1429
- * const resolver = Resolver.merge(defaultResolver, sharedNamingPatch, { name: (name) => name.toUpperCase() })
1430
- * ```
1431
- */
1432
- static merge(base, ...overrides) {
1433
- const merged = overrides.reduce((acc, override) => {
1434
- const patch = resolverOptions in override ? override[resolverOptions] : override;
1435
- for (const [key, value] of Object.entries(patch)) {
1436
- if (value === void 0) continue;
1437
- const current = acc[key];
1438
- acc[key] = isNamespace(value) && isNamespace(current) ? {
1439
- ...current,
1440
- ...value
1441
- } : value;
1442
- }
1443
- return acc;
1444
- }, { ...base[resolverOptions] });
1445
- return new Resolver(merged);
1446
- }
1447
- /**
1448
- * Binds each entry of `options` onto the resolver, so `this.name`, `this.default`, and
1449
- * `this.file` resolve there for top-level helpers and namespace methods alike. `default`
1450
- * is skipped so it can't be shadowed.
1451
- */
1452
- #apply(options) {
1453
- const root = this;
1454
- const bind = (value) => typeof value === "function" ? value.bind(root) : value;
1455
- for (const [key, value] of Object.entries(options)) {
1456
- if (key === "pluginName" || key === "default" || key === "file" || value === void 0) continue;
1457
- root[key] = isNamespace(value) ? Object.fromEntries(Object.entries(value).map(([method, member]) => [method, bind(member)])) : bind(value);
1458
- }
1459
- }
1460
- static #testPattern(value, pattern) {
1461
- if (typeof pattern === "string") {
1462
- let regex = Resolver.#patternCache.get(pattern);
1463
- regex ??= new RegExp(pattern);
1464
- Resolver.#patternCache.set(pattern, regex);
1465
- return regex.test(value);
1466
- }
1467
- return value.match(pattern) !== null;
1468
- }
1469
- static #matchesOperation(node, { type, pattern }) {
1470
- if (type === "tag") return node.tags.some((tag) => Resolver.#testPattern(tag, pattern));
1471
- if (type === "operationId") return Resolver.#testPattern(node.operationId, pattern);
1472
- if (type === "path") return node.path !== void 0 && Resolver.#testPattern(node.path, pattern);
1473
- if (type === "method") return node.method !== void 0 && Resolver.#testPattern(node.method.toLowerCase(), pattern);
1474
- if (type === "contentType") return node.requestBody?.content?.some((c) => Resolver.#testPattern(c.contentType, pattern)) ?? false;
1475
- return false;
1476
- }
1477
- /**
1478
- * Returns `null` when the filter type doesn't apply to schemas, so include rules built
1479
- * from operation filters (e.g. `tag`) don't exclude every schema.
1480
- */
1481
- static #matchesSchema(node, { type, pattern }) {
1482
- if (type === "schemaName") return node.name ? Resolver.#testPattern(node.name, pattern) : false;
1483
- return null;
1484
- }
1485
- static #computeOptions(node, { options, exclude = [], include, override = [] }) {
1486
- if (node.kind === "Operation") {
1487
- if (exclude.some((filter) => Resolver.#matchesOperation(node, filter))) return null;
1488
- if (include && !include.some((filter) => Resolver.#matchesOperation(node, filter))) return null;
1489
- return {
1490
- ...options,
1491
- ...override.find((filter) => Resolver.#matchesOperation(node, filter))?.options
1492
- };
1493
- }
1494
- if (node.kind === "Schema") {
1495
- if (exclude.some((filter) => Resolver.#matchesSchema(node, filter) === true)) return null;
1496
- if (include) {
1497
- const applicable = include.map((filter) => Resolver.#matchesSchema(node, filter)).filter((result) => result !== null);
1498
- if (applicable.length > 0 && !applicable.includes(true)) return null;
1499
- }
1500
- return {
1501
- ...options,
1502
- ...override.find((filter) => Resolver.#matchesSchema(node, filter) === true)?.options
1503
- };
1504
- }
1505
- return options;
1506
- }
1507
- /**
1508
- * Applies include/exclude filters and merges matching override options, caching the result
1509
- * per `(options, node)` pair. Returns `null` when the node is filtered out.
1510
- */
1511
- #resolveOptions(node, context) {
1512
- const { options } = context;
1513
- if (typeof options !== "object" || options === null) return Resolver.#computeOptions(node, context);
1514
- let byOptions = Resolver.#optionsCache.get(options);
1515
- if (!byOptions) {
1516
- byOptions = /* @__PURE__ */ new WeakMap();
1517
- Resolver.#optionsCache.set(options, byOptions);
1518
- }
1519
- const cached = byOptions.get(node);
1520
- if (cached) return cached.value;
1521
- const result = Resolver.#computeOptions(node, context);
1522
- byOptions.set(node, { value: result });
1523
- return result;
1524
- }
1525
- /**
1526
- * A custom `group.name` wins; otherwise `tag` groups use the camelCased tag and `path`
1527
- * groups use the first non-traversal segment (`''` when none remain, placing the file in
1528
- * the output root, kept safe by the caller's boundary check).
1529
- */
1530
- static #resolveGroupDir(group, groupValue) {
1531
- if (group.name) return group.name({ group: groupValue });
1532
- if (group.type === "tag") return camelCase(groupValue);
1533
- const segment = groupValue.split("/").filter((part) => part !== "" && part !== "." && part !== "..")[0];
1534
- return segment ? camelCase(segment) : "";
1535
- }
1536
- /**
1537
- * `mode: 'file'` (default) resolves directly to `output.path`. `mode: 'directory'` resolves
1538
- * to `output.path/{baseName}`, or into a subdirectory when `group` and a `tag`/`path` value
1539
- * are provided.
1540
- */
1541
- #resolvePath({ baseName, tag, path: groupPath, root, output, group }) {
1542
- if (output.mode !== "directory") return node_path.default.resolve(root, output.path);
1543
- const outputDir = node_path.default.resolve(root, output.path);
1544
- const result = group && (groupPath || tag) ? node_path.default.resolve(outputDir, Resolver.#resolveGroupDir(group, group.type === "path" ? groupPath : tag), baseName) : node_path.default.resolve(outputDir, baseName);
1545
- assertInside({
1546
- target: result,
1547
- parent: outputDir,
1548
- message: `Resolved path "${result}" is outside the output directory "${outputDir}".`,
1549
- 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."
1550
- });
1551
- return result;
1552
- }
1553
- /**
1554
- * Resolves a resolver-supplied full path (`file.path`) against `root`, bypassing `output.path`
1555
- * and `group`. The path may not escape `root`, which keeps a `file.path` that interpolates
1556
- * spec-derived values from writing outside the project.
1557
- */
1558
- #resolveOverridePath(filePath, root) {
1559
- const resolved = node_path.default.resolve(root, filePath);
1560
- assertInside({
1561
- target: resolved,
1562
- parent: root,
1563
- message: `Resolved path "${resolved}" is outside the project root "${root}".`,
1564
- help: "A resolver `file.path` must return a path inside the project root."
1565
- });
1566
- return resolved;
1567
- }
1568
- /**
1569
- * Builds a `FileNode`. When `#filePath` (the resolver's `file.path`) is set it owns the whole
1570
- * path; otherwise the base name (from `#baseName`, the resolver's `file.baseName` or the
1571
- * built-in `toBaseName`) is placed by the `output.path`/`group` layout. The resolved file starts
1572
- * with empty `sources`, `imports`, and `exports`, which consumers populate separately.
1573
- */
1574
- #resolveFile(options) {
1575
- const { name, extname, tag, path: groupPath, root, output, group } = options;
1576
- const baseName = this.#baseName({
1577
- name,
1578
- extname
1579
- });
1580
- const filePath = this.#filePath ? this.#resolveOverridePath(this.#filePath({
1581
- baseName,
1582
- output
1583
- }), root) : this.#resolvePath({
1584
- baseName,
1585
- tag,
1586
- path: groupPath,
1587
- root,
1588
- output,
1589
- group
1590
- });
1591
- return _kubb_ast.ast.factory.createFile({
1592
- path: filePath,
1593
- baseName: node_path.default.basename(filePath),
1594
- meta: { pluginName: this.pluginName },
1595
- sources: [],
1596
- imports: [],
1597
- exports: []
1598
- });
1599
- }
1600
- /**
1601
- * Missing fields default to empty/`false` so the `BannerMeta` shape stays stable even when
1602
- * a caller (e.g. the barrel plugin) has no document metadata.
1603
- */
1604
- static #buildBannerMeta(meta, file) {
1605
- return {
1606
- title: meta?.title,
1607
- description: meta?.description,
1608
- version: meta?.version,
1609
- baseURL: meta?.baseURL,
1610
- circularNames: meta?.circularNames ?? [],
1611
- enumNames: meta?.enumNames ?? [],
1612
- filePath: file?.path ?? "",
1613
- baseName: file?.baseName ?? "",
1614
- isBarrel: file?.isBarrel ?? false,
1615
- isAggregation: file?.isAggregation ?? false
1616
- };
1617
- }
1618
- /**
1619
- * Resolves a user-configured banner/footer value. `undefined` means not configured.
1620
- */
1621
- static #resolveUserText(value, meta, file) {
1622
- if (typeof value === "function") return value(Resolver.#buildBannerMeta(meta, file));
1623
- if (typeof value === "string") return value;
1624
- }
1625
- static #buildDefaultBanner({ title, version, config }) {
1626
- const lines = [
1627
- "/**",
1628
- "* Generated by Kubb (https://kubb.dev/).",
1629
- "* Do not edit manually."
1630
- ];
1631
- if (config.output.defaultBanner !== "simple") {
1632
- const input = config.input;
1633
- const source = typeof input === "string" ? getInputKind(input) === "inline" ? "text content" : node_path.default.basename(input) : input ? "text content" : "";
1634
- if (source) lines.push(`* Source: ${source}`);
1635
- if (title) lines.push(`* Title: ${title}`);
1636
- if (version) lines.push(`* OpenAPI spec version: ${version}`);
1637
- }
1638
- return `${lines.join("\n")}\n*/\n`;
1639
- }
1640
- /**
1641
- * A user-supplied `output.banner` overrides the default Kubb notice. When
1642
- * `config.output.defaultBanner` is `false` and no user banner is set, returns `null`.
1643
- */
1644
- #resolveBanner(meta, { output, config, file }) {
1645
- const userBanner = Resolver.#resolveUserText(output?.banner, meta, file);
1646
- if (userBanner !== void 0) return userBanner;
1647
- if (config.output.defaultBanner === false) return null;
1648
- return Resolver.#buildDefaultBanner({
1649
- title: meta?.title,
1650
- version: meta?.version,
1651
- config
1652
- });
1653
- }
1654
- #resolveFooter(meta, { output, file }) {
1655
- return Resolver.#resolveUserText(output?.footer, meta, file) ?? null;
1656
- }
1657
- };
1658
- //#endregion
1659
- //#region src/createResolver.ts
1660
- /**
1661
- * Defines a plugin resolver, the object that decides what every generated symbol and file
1662
- * path is called. Override the top-level `name` and `file` to set the plugin's conventions,
1663
- * and add your own naming helpers, top-level (`typeName`, …) or grouped in namespaces
1664
- * (`query`, `schema`, …). Every method reaches sibling helpers and the built-in machinery
1665
- * through `this.name`, `this.file`, and `this.default`.
1666
- *
1667
- * @example Custom identifier casing
1668
- * ```ts
1669
- * export const resolverTs = createResolver<PluginTs>({
1670
- * pluginName: 'plugin-ts',
1671
- * name(name) {
1672
- * return ensureValidVarName(pascalCase(name))
1673
- * },
1674
- * })
1675
- * ```
1676
- *
1677
- * @example Rename generated files with `file.baseName`
1678
- * ```ts
1679
- * export const resolverFaker = createResolver<PluginFaker>({
1680
- * pluginName: 'plugin-faker',
1681
- * name(name) {
1682
- * return camelCase(name, { prefix: 'create' })
1683
- * },
1684
- * file: {
1685
- * baseName({ name, extname }) {
1686
- * return `${camelCase(name, { prefix: 'create' })}${extname}`
1687
- * },
1688
- * },
1689
- * })
1690
- * ```
1691
- *
1692
- * @example Own the full path with `file.path`
1693
- * ```ts
1694
- * export const resolverFaker = createResolver<PluginFaker>({
1695
- * pluginName: 'plugin-faker',
1696
- * file: {
1697
- * path({ baseName, output }) {
1698
- * return `${output.path}/mocks/${baseName}`
1699
- * },
1700
- * },
1701
- * })
1702
- * ```
1703
- */
1704
- function createResolver(options) {
1705
- return new Resolver(options);
1706
- }
1707
- //#endregion
1708
- //#region \0@oxc-project+runtime@0.153.0/helpers/esm/usingCtx.js
1709
- function _usingCtx() {
1710
- var r = "function" == typeof SuppressedError ? SuppressedError : function(r, e) {
1711
- var n = Error();
1712
- return n.name = "SuppressedError", n.error = r, n.suppressed = e, n;
1713
- };
1714
- var e = {};
1715
- var n = [];
1716
- function using(r, e) {
1717
- if (null != e) {
1718
- if (Object(e) !== e) throw new TypeError("using declarations can only be used with objects, functions, null, or undefined.");
1719
- if (r) var o = e[Symbol.asyncDispose || Symbol["for"]("Symbol.asyncDispose")];
1720
- if (void 0 === o && (o = e[Symbol.dispose || Symbol["for"]("Symbol.dispose")], r)) var t = o;
1721
- if ("function" != typeof o) throw new TypeError("Object is not disposable.");
1722
- t && (o = function o() {
1723
- try {
1724
- t.call(e);
1725
- } catch (r) {
1726
- return Promise.reject(r);
1727
- }
1728
- }), n.push({
1729
- v: e,
1730
- d: o,
1731
- a: r
1732
- });
1733
- } else r && n.push({
1734
- d: e,
1735
- a: r
1736
- });
1737
- return e;
1738
- }
1739
- return {
1740
- e,
1741
- u: using.bind(null, !1),
1742
- a: using.bind(null, !0),
1743
- d: function d() {
1744
- var o;
1745
- var t = this.e;
1746
- var s = 0;
1747
- function next() {
1748
- for (; o = n.pop();) try {
1749
- if (!o.a && 1 === s) return s = 0, n.push(o), Promise.resolve().then(next);
1750
- if (o.d) {
1751
- var r = o.d.call(o.v);
1752
- if (o.a) return s |= 2, Promise.resolve(r).then(next, err);
1753
- } else s |= 1;
1754
- } catch (r) {
1755
- return err(r);
1756
- }
1757
- if (1 === s) return t !== e ? Promise.reject(t) : Promise.resolve();
1758
- if (t !== e) throw t;
1759
- }
1760
- function err(n) {
1761
- return t = t !== e ? new r(n, t) : n, next();
1762
- }
1763
- return next();
1764
- }
1765
- };
1766
- }
1767
- function joinSources(file) {
1768
- return file.sources.map((source) => (0, _kubb_ast.extractStringsFromNodes)(source.nodes)).filter(Boolean).join("\n\n");
1769
- }
1770
- /** Runs a parser call and turns a crash into a `KUBB_PARSER_FAILED` diagnostic that names the parser. */
1771
- function runParser(parser, print) {
1772
- try {
1773
- return print();
1774
- } catch (error) {
1775
- throw new Diagnostics.Error(Diagnostics.fromExtension(error, {
1776
- kind: "parser",
1777
- extension: parser
1778
- }));
1779
- }
1780
- }
1781
- /**
1782
- * Reads a `copy` file and prints it through the parser's `copy` hook, or verbatim with `banner`/`footer` when there is none.
1783
- */
1784
- async function parseCopy(file, parser) {
1785
- let content;
1786
- try {
1787
- content = await (0, node_fs_promises.readFile)(file.copy, "utf8");
1788
- } catch (err) {
1789
- throw new Diagnostics.Error({
1790
- code: Diagnostics.code.pluginFailed,
1791
- severity: "error",
1792
- message: `Could not copy file into output: ${file.copy}`,
1793
- help: "Check that the file a plugin copies into the output exists and is readable.",
1794
- cause: toError(err)
1795
- });
1796
- }
1797
- if (parser?.copy) return runParser(parser, () => parser.parse(_kubb_ast.ast.factory.createFile(parser.copy(file, content))));
1798
- return [
1799
- file.banner,
1800
- content,
1801
- file.footer
1802
- ].filter((segment) => Boolean(segment)).map((segment) => segment.trimEnd()).join("\n");
1803
- }
1804
- function mergeFile(a, b) {
1805
- return {
1806
- ...a,
1807
- banner: b.banner,
1808
- footer: b.footer,
1809
- copy: b.copy ?? a.copy,
1810
- sources: a.sources.length ? b.sources.length ? [...a.sources, ...b.sources] : a.sources : b.sources,
1811
- imports: a.imports.length ? b.imports.length ? [...a.imports, ...b.imports] : a.imports : b.imports,
1812
- exports: a.exports.length ? b.exports.length ? [...a.exports, ...b.exports] : a.exports : b.exports
1813
- };
1814
- }
1815
- function isIndexPath(path) {
1816
- return path.endsWith("/index.ts") || path === "index.ts";
1817
- }
1818
- function compareFiles(a, b) {
1819
- return a.path.length - b.path.length || Number(isIndexPath(a.path)) - Number(isIndexPath(b.path));
1820
- }
1821
- function isUnchanged({ stored, source, key, manifest }) {
1822
- if (stored === null) return false;
1823
- if (matchesStored({
1824
- stored,
1825
- source
1826
- })) return true;
1827
- return manifest?.isUpToDate({
1828
- key,
1829
- source,
1830
- disk: stored
1831
- }) ?? false;
1832
- }
1833
- /**
1834
- * In-memory file store for generated files, and the writer that turns them into source
1835
- * strings on `storage`. Files sharing a `path` are merged (sources/imports/exports
1836
- * concatenated). The `files` getter is sorted by path length (barrel `index.ts` last
1837
- * within a bucket).
1838
- *
1839
- * @example
1840
- * ```ts
1841
- * const manager = new FileManager()
1842
- * manager.upsert(myFile)
1843
- * manager.files // sorted view
1844
- * await manager.write(manager.files, { storage: fsStorage() })
1845
- * ```
1846
- */
1847
- var FileManager = class {
1848
- #cache = /* @__PURE__ */ new Map();
1849
- #sorted = null;
1850
- add(...files) {
1851
- return this.#store(files, false);
1852
- }
1853
- upsert(...files) {
1854
- return this.#store(files, true);
1855
- }
1856
- /** Stores a generator result: a file array is upserted as is, an element renders through `renderer` first, falsy is a no-op. */
1857
- async dispatch({ result, renderer }) {
1858
- try {
1859
- var _usingCtx$1 = _usingCtx();
1860
- if (!result) return;
1861
- if (Array.isArray(result)) {
1862
- this.upsert(...result);
1863
- return;
1864
- }
1865
- if (!renderer) return;
1866
- const instance = _usingCtx$1.u(renderer());
1867
- await instance.render(result);
1868
- this.upsert(...instance.files);
1869
- } catch (_) {
1870
- _usingCtx$1.e = _;
1871
- } finally {
1872
- _usingCtx$1.d();
1873
- }
1874
- }
1875
- #store(files, mergeExisting) {
1876
- const batch = files.length > 1 ? this.#dedupe(files) : files;
1877
- const resolved = [];
1878
- for (const file of batch) {
1879
- const existing = this.#cache.get(file.path);
1880
- const merged = existing && mergeExisting ? _kubb_ast.ast.factory.createFile(mergeFile(existing, file)) : _kubb_ast.ast.factory.createFile(file);
1881
- this.#cache.set(merged.path, merged);
1882
- resolved.push(merged);
1883
- }
1884
- if (resolved.length > 0) this.#sorted = null;
1885
- return resolved;
1886
- }
1887
- #dedupe(files) {
1888
- const seen = /* @__PURE__ */ new Map();
1889
- for (const file of files) {
1890
- const prev = seen.get(file.path);
1891
- seen.set(file.path, prev ? mergeFile(prev, file) : file);
1892
- }
1893
- return [...seen.values()];
1894
- }
1895
- /**
1896
- * Releases all stored files. Called by the core after `kubb:build:end`.
1897
- */
1898
- dispose() {
1899
- this.#cache.clear();
1900
- this.#sorted = null;
1901
- }
1902
- /**
1903
- * All stored files in stable sort order (shortest path first, barrel files
1904
- * last within a length bucket). Returns a cached view, do not mutate.
1905
- */
1906
- get files() {
1907
- return this.#sorted ??= [...this.#cache.values()].sort(compareFiles);
1908
- }
1909
- /**
1910
- * Converts a file's AST sources (or its `copy` source) into the final on-disk string.
1911
- */
1912
- async parse(file, { parsers } = {}) {
1913
- const parser = parsers?.get(file.extname);
1914
- if (file.copy) return parseCopy(file, parser);
1915
- if (!parser) return joinSources(file);
1916
- return runParser(parser, () => parser.parse(file));
1917
- }
1918
- /**
1919
- * Parses and writes every file through a bounded pool of workers. A small spec runs all its files
1920
- * at once; a spec with thousands of files keeps at most {@link FILE_CONCURRENCY} parsed sources in
1921
- * memory rather than holding every source, while still overlapping each file's write with the
1922
- * next file's parse. Files finish in whatever order they parse, so the update rows are sorted back
1923
- * into input order before `kubb:files:processing:update` fires once with the whole batch.
1924
- *
1925
- * A file the storage already holds is skipped, so a rebuild that generates identical output
1926
- * writes nothing and leaves every mtime where it was.
1927
- */
1928
- async write(files, { storage, parsers, manifest, signal, hooks, config }) {
1929
- if (files.length === 0) return;
1930
- await hooks?.callHook("kubb:files:processing:start", { files });
1931
- const total = files.length;
1932
- const updates = [];
1933
- await inParallel({
1934
- items: files,
1935
- limit: 50,
1936
- run: async (file, index) => {
1937
- signal?.throwIfAborted();
1938
- const source = await this.parse(file, { parsers });
1939
- if (config) updates.push({
1940
- file,
1941
- processed: index + 1,
1942
- total,
1943
- percentage: (index + 1) / total * 100,
1944
- config
1945
- });
1946
- if (!source) return;
1947
- signal?.throwIfAborted();
1948
- const stored = await storage.readItem(file.path);
1949
- if (isUnchanged({
1950
- stored,
1951
- source,
1952
- key: file.path,
1953
- manifest
1954
- })) return;
1955
- signal?.throwIfAborted();
1956
- await storage.writeItem(file.path, source, { stored });
1957
- manifest?.track({
1958
- key: file.path,
1959
- source
1960
- });
1961
- }
1962
- });
1963
- updates.sort((a, b) => a.processed - b.processed);
1964
- await hooks?.callHook("kubb:files:processing:update", { files: updates });
1965
- await hooks?.callHook("kubb:files:processing:end", { files });
1966
- }
1967
- };
1968
- //#endregion
1969
- //#region src/nodeCache.ts
1970
- /**
1971
- * Builds an empty {@link NodeCache} backed by a plain `Map`. Called once per node in the generate
1972
- * walk.
1973
- */
1974
- function createNodeCache() {
1975
- const store = /* @__PURE__ */ new Map();
1976
- return {
1977
- readItem(key) {
1978
- return store.get(key);
1979
- },
1980
- writeItem(key, value) {
1981
- store.set(key, value);
1982
- return value;
1983
- },
1984
- ensureItem(key, factory) {
1985
- if (store.has(key)) return store.get(key);
1986
- const value = factory();
1987
- store.set(key, value);
1988
- return value;
1989
- }
1990
- };
1991
- }
1992
- //#endregion
1993
- //#region src/KubbDriver.ts
1994
- const ENFORCE_ORDER = {
1995
- pre: -1,
1996
- post: 1
1997
- };
1998
- /** `include` filter types that select operations, and so prune the schemas they do not reach. */
1999
- const OPERATION_FILTER_TYPES = /* @__PURE__ */ new Set([
2000
- "tag",
2001
- "operationId",
2002
- "path",
2003
- "method",
2004
- "contentType"
2005
- ]);
2006
- const enforceWeight = (plugin) => plugin.enforce ? ENFORCE_ORDER[plugin.enforce] : 0;
2007
- /**
2008
- * The options bag a `NormalizedPlugin` starts with before a plugin refines it: a directory output
2009
- * at the plugin root and empty filter lists.
2010
- */
2011
- const defaultPluginOptions = () => ({
2012
- output: {
2013
- path: ".",
2014
- mode: "directory"
2015
- },
2016
- exclude: [],
2017
- override: []
2018
- });
2019
- /**
2020
- * Fills in the `output`, `exclude`, and `override` a `NormalizedPlugin` needs from a plugin's raw
2021
- * options, running `output` through `normalizeOutput`. Idempotent, so the driver can apply it after
2022
- * `setOptions` has already run without disturbing an already-normalized bag.
2023
- */
2024
- function normalizePluginOptions(rawOptions, pluginName) {
2025
- const options = {
2026
- ...defaultPluginOptions(),
2027
- ...rawOptions ?? {}
2028
- };
2029
- const group = "group" in options ? options.group : void 0;
2030
- options.output = normalizeOutput({
2031
- output: options.output,
2032
- group,
2033
- pluginName
2034
- });
2035
- return options;
2036
- }
2037
- /**
2038
- * Throws `KUBB_INVALID_PLUGIN_OPTIONS` when a `plugins` entry is not a plugin object, such as a
2039
- * factory passed without calling it.
2040
- */
2041
- function assertPluginEntry(entry, index) {
2042
- if (typeof entry === "function") {
2043
- const name = entry.name || "pluginName";
2044
- throw new Diagnostics.Error({
2045
- code: Diagnostics.code.invalidPluginOptions,
2046
- severity: "error",
2047
- message: `plugins[${index}] is a function ("${name}"), not a plugin.`,
2048
- help: `Call it: ${name}()`,
2049
- location: { kind: "config" }
2050
- });
2051
- }
2052
- if (typeof entry !== "object" || entry === null) throw new Diagnostics.Error({
2053
- code: Diagnostics.code.invalidPluginOptions,
2054
- severity: "error",
2055
- message: `plugins[${index}] is ${entry === null ? "null" : typeof entry}, not a plugin.`,
2056
- help: "Pass the result of a plugin factory, for example `pluginTs()`, or remove the entry.",
2057
- location: { kind: "config" }
2058
- });
2059
- }
2060
- /**
2061
- * Where a generator crashed: a label naming the node and, when the node has one, a JSON pointer
2062
- * to it. Built from the node fields so core stays adapter-agnostic.
2063
- */
2064
- function getCrashSite(node) {
2065
- if (node.kind === "Schema") return node.name ? {
2066
- label: `schema "${node.name}"`,
2067
- location: {
2068
- kind: "schema",
2069
- pointer: `#/components/schemas/${escapePointerToken(node.name)}`
2070
- }
2071
- } : { label: "an inline schema" };
2072
- if (!node.method || !node.path) return { label: `operation "${node.operationId}"` };
2073
- return {
2074
- label: `operation "${node.operationId}" (${node.method.toUpperCase()} ${node.path})`,
2075
- location: {
2076
- kind: "operation",
2077
- pointer: `#/paths/${escapePointerToken(node.path)}/${node.method.toLowerCase()}`
2078
- }
2079
- };
2080
- }
2081
- var KubbDriver = class {
2082
- config;
2083
- options;
2084
- /**
2085
- * The `InputNode` produced by the adapter. Set after adapter setup.
2086
- */
2087
- inputNode = null;
2088
- adapter = null;
2089
- /**
2090
- * Raw adapter source so `adapter.parse()` can run lazily.
2091
- * Intentionally outlives the build, cleared by `dispose()`.
2092
- */
2093
- #adapterSource = null;
2094
- /**
2095
- * Central file store for all generated files.
2096
- * Plugins should use `this.addFile()` / `this.upsertFile()` (via their context) to
2097
- * add files. This property gives direct read/write access when needed.
2098
- */
2099
- fileManager = new FileManager();
2100
- plugins = /* @__PURE__ */ new Map();
2101
- /**
2102
- * Removers for every listener the driver added (plugin, generator) so `dispose()` can detach
2103
- * them in one pass. External `hooks.hook(...)` listeners are not tracked.
2104
- */
2105
- #unhooks = [];
2106
- constructor(config, options) {
2107
- this.config = config;
2108
- this.options = options;
2109
- this.adapter = config.adapter ?? null;
2110
- }
2111
- /**
2112
- * Checks the adapter's and parsers' `meta.compatibility`, then normalizes and checks every configured plugin, orders them, and registers their lifecycle handlers.
2113
- * A plugin that another lists as a dependency runs first, then `enforce: 'pre'` before
2114
- * `'post'`. When the config has an adapter, the adapter source is resolved from the input
2115
- * so `run` can parse it later.
2116
- */
2117
- async setup() {
2118
- this.options.signal?.throwIfAborted();
2119
- for (const extension of [this.config.adapter, ...this.config.parsers]) if (extension?.meta) checkCompatibility(extension.meta);
2120
- const names = /* @__PURE__ */ new Set();
2121
- const normalized = this.#sortPlugins(this.config.plugins.map((rawPlugin, index) => {
2122
- assertPluginEntry(rawPlugin, index);
2123
- if (rawPlugin.meta) checkCompatibility(rawPlugin.meta);
2124
- const meta = resolveMeta(rawPlugin);
2125
- if (names.has(meta.name)) throw new Diagnostics.Error({
2126
- code: Diagnostics.code.invalidPluginOptions,
2127
- severity: "error",
2128
- message: `Plugin "${meta.name}" appears twice in \`plugins\`.`,
2129
- help: "Remove the duplicate, or merge its options.",
2130
- location: { kind: "config" }
2131
- });
2132
- names.add(meta.name);
2133
- return {
2134
- name: meta.name,
2135
- meta,
2136
- dependencies: typeof rawPlugin.dependencies === "function" ? rawPlugin.dependencies(rawPlugin.options ?? {}, { config: this.config }) : rawPlugin.dependencies,
2137
- enforce: rawPlugin.enforce,
2138
- hooks: rawPlugin.hooks,
2139
- setup: rawPlugin.setup,
2140
- options: rawPlugin.options ?? defaultPluginOptions(),
2141
- resolver: createResolver({ pluginName: meta.name })
2142
- };
2143
- }));
2144
- const byName = new Map(normalized.map((plugin) => [plugin.name, plugin]));
2145
- for (const plugin of normalized) checkDependencies({
2146
- name: plugin.name,
2147
- dependencies: plugin.dependencies,
2148
- plugins: byName
2149
- });
2150
- for (const plugin of normalized) {
2151
- this.#registerPlugin(plugin);
2152
- this.plugins.set(plugin.name, plugin);
2153
- }
2154
- if (this.config.adapter) this.#adapterSource = inputToAdapterSource(this.config);
2155
- }
2156
- /**
2157
- * Orders plugins so every dependency runs before its dependents (Kahn's algorithm), with
2158
- * `enforce` (`'pre'` before normal before `'post'`) and declaration order as tiebreaks.
2159
- * A pairwise `Array.sort` comparator cannot do this: dependency relations are not transitive
2160
- * at the comparator level, so a chain where A depends on B and B depends on C could come out
2161
- * wrong when A and C are never compared directly. Dependencies on plugins missing from the
2162
- * config are ignored here and surface later through `requirePlugin`.
2163
- */
2164
- #sortPlugins(plugins) {
2165
- const queue = [...plugins].sort((a, b) => enforceWeight(a) - enforceWeight(b));
2166
- const names = new Set(queue.map((plugin) => plugin.name));
2167
- const blockedBy = new Map(queue.map((plugin) => {
2168
- const dependencies = Array.isArray(plugin.dependencies) ? plugin.dependencies : Object.keys(plugin.dependencies ?? {});
2169
- return [plugin.name, new Set(dependencies.filter((name) => names.has(name) && name !== plugin.name))];
2170
- }));
2171
- const sorted = [];
2172
- for (const _ of plugins) {
2173
- const index = queue.findIndex((plugin) => blockedBy.get(plugin.name)?.size === 0);
2174
- if (index === -1) throw new Diagnostics.Error({
2175
- code: Diagnostics.code.invalidPluginOptions,
2176
- severity: "error",
2177
- message: `Plugin dependencies form a cycle: ${queue.map((plugin) => plugin.name).join(" → ")}.`,
2178
- help: "Remove one of the `dependencies` entries so the plugins can be ordered.",
2179
- location: { kind: "config" }
2180
- });
2181
- const [plugin] = queue.splice(index, 1);
2182
- if (!plugin) break;
2183
- sorted.push(plugin);
2184
- for (const blockers of blockedBy.values()) blockers.delete(plugin.name);
2185
- }
2186
- return sorted;
2187
- }
2188
- get hooks() {
2189
- return this.options.hooks;
2190
- }
2191
- /**
2192
- * Parses the adapter source into `this.inputNode`. Idempotent, so repeated calls from
2193
- * `run` do not re-parse.
2194
- */
2195
- async #parseInput() {
2196
- if (this.inputNode || !this.adapter || !this.#adapterSource) return;
2197
- this.options.signal?.throwIfAborted();
2198
- try {
2199
- this.inputNode = await this.adapter.parse(this.#adapterSource, { signal: this.options.signal });
2200
- } catch (caughtError) {
2201
- throw new Diagnostics.Error(Diagnostics.fromExtension(caughtError, {
2202
- kind: "adapter",
2203
- extension: this.adapter
2204
- }));
2205
- }
2206
- }
2207
- /**
2208
- * Registers a plugin's lifecycle hooks on the shared `Hookable` as pass-through listeners that
2209
- * external tooling can observe via `hooks.hook(...)`. The returned remover is tracked for
2210
- * `dispose`. `kubb:plugin:setup` is skipped here; `setupHooks` invokes it directly with a
2211
- * plugin-scoped context.
2212
- *
2213
- * @internal
2214
- */
2215
- #registerPlugin(plugin) {
2216
- const { hooks } = plugin;
2217
- if (!hooks) return;
2218
- const { "kubb:plugin:setup": _setup, ...configHooks } = hooks;
2219
- this.#unhooks.push(this.hooks.addHooks(configHooks));
2220
- }
2221
- /**
2222
- * Runs each plugin's `setup` and `kubb:plugin:setup` handler, in plugin order, with a context scoped to that
2223
- * plugin so `addGenerator`, `setResolver`, `addMacro`, `setMacros`, and `setOptions` target its
2224
- * `NormalizedPlugin` entry. Called once from `run` before the plugin execution loop begins, so
2225
- * plugins can configure generators, resolvers, macros, and options before `buildStart`.
2226
- */
2227
- async setupHooks() {
2228
- for (const plugin of this.plugins.values()) {
2229
- const setupHook = plugin.hooks?.["kubb:plugin:setup"];
2230
- if (!plugin.setup && !setupHook) continue;
2231
- const ctx = {
2232
- config: this.config,
2233
- options: plugin.options ?? {},
2234
- addGenerator: (...generators) => {
2235
- plugin.generators = [...plugin.generators ?? [], ...generators];
2236
- },
2237
- setResolver: (resolver) => {
2238
- plugin.resolver = Resolver.merge(createResolver({ pluginName: plugin.name }), resolver);
2239
- },
2240
- addMacro: (macro) => {
2241
- plugin.macros = [...plugin.macros ?? [], macro];
2242
- },
2243
- setMacros: (macros) => {
2244
- plugin.macros = [...macros];
2245
- },
2246
- setOptions: (opts) => {
2247
- plugin.options = normalizePluginOptions({
2248
- ...plugin.options,
2249
- ...opts
2250
- }, plugin.name);
2251
- },
2252
- injectFile: (userFileNode) => {
2253
- this.fileManager.add(_kubb_ast.ast.factory.createFile(userFileNode));
2254
- },
2255
- requirePlugin: ((name) => this.requirePlugin(name, { requiredBy: plugin.name }))
2256
- };
2257
- try {
2258
- await kubbContext.run(ctx, async () => {
2259
- if (plugin.setup) plugin.options = normalizePluginOptions(await plugin.setup(ctx.options, ctx), plugin.name);
2260
- await setupHook?.(ctx);
2261
- });
2262
- } catch (caughtError) {
2263
- throw new Diagnostics.Error(Diagnostics.fromExtension(caughtError, {
2264
- kind: "plugin",
2265
- extension: plugin
2266
- }));
2267
- }
2268
- }
2269
- }
2270
- /**
2271
- * Runs the full plugin pipeline. Returns the diagnostics collected so far even
2272
- * when an outer hook throws, since the orchestrator preserves partial state by capturing
2273
- * the failure as a {@link Diagnostic} instead of propagating. Each plugin also
2274
- * contributes a `timing` diagnostic for the run summary.
2275
- */
2276
- async run() {
2277
- const { hooks, config, fileManager } = this;
2278
- const diagnostics = [];
2279
- const parsersMap = /* @__PURE__ */ new Map();
2280
- for (const parser of config.parsers) if (parser.extNames) for (const ext of parser.extNames) parsersMap.set(ext, parser);
2281
- return Diagnostics.scope((diagnostic) => diagnostics.push(diagnostic), async () => {
2282
- try {
2283
- this.options.signal?.throwIfAborted();
2284
- const outputRoot = (0, node_path.resolve)(config.root, config.output.path);
2285
- await this.#parseInput();
2286
- await this.setupHooks();
2287
- for (const plugin of this.plugins.values()) {
2288
- this.options.signal?.throwIfAborted();
2289
- plugin.options = normalizePluginOptions(plugin.options, plugin.name);
2290
- }
2291
- if (this.adapter && this.inputNode) {
2292
- const buildStartContext = this.#withFiles({
2293
- config,
2294
- adapter: this.adapter,
2295
- meta: this.inputNode.meta,
2296
- getPlugin: this.getPlugin.bind(this)
2297
- });
2298
- await hooks.callHook("kubb:build:start", buildStartContext);
2299
- }
2300
- const generatorPlugins = [];
2301
- for (const plugin of this.plugins.values()) {
2302
- const context = this.getContext(plugin);
2303
- const hrStart = process.hrtime();
2304
- try {
2305
- await hooks.callHook("kubb:plugin:start", { plugin });
2306
- } catch (caughtError) {
2307
- const error = toError(caughtError);
2308
- const duration = getElapsedMs(hrStart);
2309
- await this.#emitPluginEnd({
2310
- plugin,
2311
- duration,
2312
- success: false,
2313
- error
2314
- });
2315
- diagnostics.push(Diagnostics.fromExtension(error, {
2316
- kind: "plugin",
2317
- extension: plugin
2318
- }), Diagnostics.performance({
2319
- plugin: plugin.name,
2320
- duration
2321
- }));
2322
- continue;
2323
- }
2324
- if ((plugin.generators?.length ?? 0) > 0) {
2325
- generatorPlugins.push({
2326
- plugin,
2327
- context,
2328
- hrStart
2329
- });
2330
- continue;
2331
- }
2332
- const duration = getElapsedMs(hrStart);
2333
- diagnostics.push(Diagnostics.performance({
2334
- plugin: plugin.name,
2335
- duration
2336
- }));
2337
- await this.#emitPluginEnd({
2338
- plugin,
2339
- duration,
2340
- success: true
2341
- });
2342
- }
2343
- diagnostics.push(...await this.#runGenerators(generatorPlugins));
2344
- await hooks.callHook("kubb:plugins:end", this.#withFiles({ config }));
2345
- if (this.options.cleanPath) await config.storage.empty(this.options.cleanPath);
2346
- await fileManager.write(fileManager.files, {
2347
- storage: config.storage,
2348
- parsers: parsersMap,
2349
- manifest: this.options.manifest,
2350
- signal: this.options.signal,
2351
- hooks,
2352
- config
2353
- });
2354
- await hooks.callHook("kubb:build:end", {
2355
- files: this.fileManager.files,
2356
- config,
2357
- outputDir: outputRoot
2358
- });
2359
- return { diagnostics: Diagnostics.dedupe(diagnostics) };
2360
- } catch (caughtError) {
2361
- diagnostics.push(Diagnostics.from(caughtError));
2362
- return { diagnostics: Diagnostics.dedupe(diagnostics) };
2363
- }
2364
- });
2365
- }
2366
- /**
2367
- * Widens `extra` with the files present at emit time and a bound `upsertFile`, the shape every
2368
- * file-carrying hook context shares. Building it here in one place keeps the `files` and
2369
- * `upsertFile` keys from being dropped by a stray spread at the call site.
2370
- */
2371
- #withFiles(extra) {
2372
- return {
2373
- ...extra,
2374
- files: this.fileManager.files,
2375
- upsertFile: (...files) => this.fileManager.upsert(...files)
2376
- };
2377
- }
2378
- #emitPluginEnd({ plugin, duration, success, error }) {
2379
- return this.hooks.callHook("kubb:plugin:end", this.#withFiles({
2380
- plugin,
2381
- duration,
2382
- success,
2383
- ...error ? { error } : {},
2384
- config: this.config
2385
- }));
2386
- }
2387
- /**
2388
- * Runs schemas and operations through every plugin's generators. The walk is node-outer: each
2389
- * schema is visited once and each operation once, and the node fans out to the matching
2390
- * generators of every plugin in dependency order. A per-node cache (`createNodeCache`) is created
2391
- * once per node and shared by all of that node's plugins, so node-derived work is computed once
2392
- * and reused instead of recomputed per plugin. Each node still runs through the plugin's macros
2393
- * and its exclude/include/override filters before that plugin's
2394
- * generator sees it, so plugins stay isolated. Schemas run before operations so file output
2395
- * stays deterministic across runs. A generator with a `match` predicate that resolves `false`
2396
- * for a node is skipped for that node, without calling `schema`/`operation`.
2397
- *
2398
- * A failing plugin is dropped from the remaining walk, contributes an error diagnostic, and no
2399
- * longer aborts the other plugins. `kubb:plugin:end` and each plugin's `timing` diagnostic fire
2400
- * in dependency order once the walk finishes, driving the CLI's `Plugins N/M` counter. The
2401
- * `operations` batch fires once per plugin after the single operation walk.
2402
- *
2403
- * When `this.inputNode` is `null`, every entry still gets a `kubb:plugin:end` so
2404
- * post-plugin listeners (the barrel writer and friends) complete.
2405
- */
2406
- async #runGenerators(entries) {
2407
- const diagnostics = [];
2408
- if (entries.length === 0) return diagnostics;
2409
- if (!this.inputNode) {
2410
- for (const { plugin, hrStart } of entries) {
2411
- const duration = getElapsedMs(hrStart);
2412
- diagnostics.push(Diagnostics.performance({
2413
- plugin: plugin.name,
2414
- duration
2415
- }));
2416
- await this.#emitPluginEnd({
2417
- plugin,
2418
- duration,
2419
- success: true
2420
- });
2421
- }
2422
- return diagnostics;
2423
- }
2424
- const { schemas, operations } = this.inputNode;
2425
- const allowedSchemaNamesByPlugin = /* @__PURE__ */ new Map();
2426
- for (const { plugin } of entries) {
2427
- const { exclude, include, override } = plugin.options;
2428
- if (!((include?.some(({ type }) => OPERATION_FILTER_TYPES.has(type)) ?? false) && !(include?.some(({ type }) => type === "schemaName") ?? false))) continue;
2429
- const resolver = this.getResolver(plugin.name);
2430
- const includedOps = operations.filter((operation) => resolver.default.options(operation, {
2431
- options: plugin.options,
2432
- exclude,
2433
- include,
2434
- override
2435
- }) !== null);
2436
- allowedSchemaNamesByPlugin.set(plugin.name, (0, _kubb_ast.collectUsedSchemaNames)(includedOps, schemas));
2437
- }
2438
- const states = entries.map(({ plugin, context, hrStart }) => {
2439
- const generatorContext = {
2440
- ...context,
2441
- resolver: this.getResolver(plugin.name)
2442
- };
2443
- const { exclude, include, override } = plugin.options;
2444
- const generators = plugin.generators ?? [];
2445
- return {
2446
- plugin,
2447
- hrStart,
2448
- generatorContext,
2449
- exclude,
2450
- include,
2451
- override,
2452
- optionsAreStatic: !exclude?.length && !include?.length && !override?.length,
2453
- allowedSchemaNames: allowedSchemaNamesByPlugin.get(plugin.name) ?? null,
2454
- schemaGenerators: generators.filter((generator) => generator.schema),
2455
- operationGenerators: generators.filter((generator) => generator.operation),
2456
- operationsGenerators: generators.filter((generator) => generator.operations),
2457
- pluginOperations: [],
2458
- error: null,
2459
- crashSite: void 0
2460
- };
2461
- });
2462
- const resolveForPlugin = (state, node) => {
2463
- const transformedNode = _kubb_ast.ast.applyMacros(node, state.plugin.macros ?? []);
2464
- if (state.optionsAreStatic) return {
2465
- transformedNode,
2466
- options: state.plugin.options
2467
- };
2468
- const options = state.generatorContext.resolver.default.options(transformedNode, {
2469
- options: state.plugin.options,
2470
- exclude: state.exclude,
2471
- include: state.include,
2472
- override: state.override
2473
- });
2474
- if (options === null) return null;
2475
- return {
2476
- transformedNode,
2477
- options
2478
- };
2479
- };
2480
- for (const node of schemas) {
2481
- const cache = createNodeCache();
2482
- for (const state of states) {
2483
- if (state.error || !state.schemaGenerators.length) continue;
2484
- try {
2485
- const resolved = resolveForPlugin(state, node);
2486
- if (!resolved) continue;
2487
- const { transformedNode, options } = resolved;
2488
- if (state.allowedSchemaNames !== null && transformedNode.name && !state.allowedSchemaNames.has(transformedNode.name)) continue;
2489
- const ctx = {
2490
- ...state.generatorContext,
2491
- options,
2492
- cache
2493
- };
2494
- await this.#dispatchNode({
2495
- generators: state.schemaGenerators,
2496
- node: transformedNode,
2497
- ctx,
2498
- generate: (generator) => generator.schema(transformedNode, ctx)
2499
- });
2500
- await this.hooks.callHook("kubb:generate:schema", transformedNode, ctx);
2501
- } catch (caughtError) {
2502
- state.error = toError(caughtError);
2503
- state.crashSite = getCrashSite(node);
2504
- }
2505
- }
2506
- }
2507
- for (const node of operations) {
2508
- const cache = createNodeCache();
2509
- for (const state of states) {
2510
- if (state.error || !state.operationGenerators.length && !state.operationsGenerators.length) continue;
2511
- try {
2512
- const resolved = resolveForPlugin(state, node);
2513
- if (!resolved) continue;
2514
- state.pluginOperations.push(resolved.transformedNode);
2515
- if (state.operationGenerators.length) {
2516
- const { transformedNode } = resolved;
2517
- const ctx = {
2518
- ...state.generatorContext,
2519
- options: resolved.options,
2520
- cache
2521
- };
2522
- await this.#dispatchNode({
2523
- generators: state.operationGenerators,
2524
- node: transformedNode,
2525
- ctx,
2526
- generate: (generator) => generator.operation(transformedNode, ctx)
2527
- });
2528
- await this.hooks.callHook("kubb:generate:operation", transformedNode, ctx);
2529
- }
2530
- } catch (caughtError) {
2531
- state.error = toError(caughtError);
2532
- state.crashSite = getCrashSite(node);
2533
- }
2534
- }
2535
- }
2536
- for (const state of states) {
2537
- if (state.error || !state.operationsGenerators.length) continue;
2538
- try {
2539
- const ctx = {
2540
- ...state.generatorContext,
2541
- options: state.plugin.options,
2542
- cache: createNodeCache()
2543
- };
2544
- for (const generator of state.operationsGenerators) await this.fileManager.dispatch({
2545
- result: await generator.operations(state.pluginOperations, ctx),
2546
- renderer: generator.renderer
2547
- });
2548
- await this.hooks.callHook("kubb:generate:operations", state.pluginOperations, ctx);
2549
- } catch (caughtError) {
2550
- state.error = toError(caughtError);
2551
- }
2552
- }
2553
- for (const state of states) {
2554
- const duration = getElapsedMs(state.hrStart);
2555
- await this.#emitPluginEnd({
2556
- plugin: state.plugin,
2557
- duration,
2558
- success: !state.error,
2559
- error: state.error ?? void 0
2560
- });
2561
- if (state.error) {
2562
- const diagnostic = Diagnostics.fromExtension(state.error, {
2563
- kind: "plugin",
2564
- extension: state.plugin
2565
- });
2566
- const site = diagnostic.code === Diagnostics.code.pluginFailed && !diagnostic.location ? state.crashSite : void 0;
2567
- diagnostics.push(site ? {
2568
- ...diagnostic,
2569
- message: `While generating ${site.label}: ${diagnostic.message}`,
2570
- ...site.location ? { location: site.location } : {}
2571
- } : diagnostic);
2572
- }
2573
- diagnostics.push(Diagnostics.performance({
2574
- plugin: state.plugin.name,
2575
- duration
2576
- }));
2577
- }
2578
- return diagnostics;
2579
- }
2580
- /** Runs `node` through the generators whose `match` accepts it; `generate` picks the method for the node kind. */
2581
- async #dispatchNode({ generators, node, ctx, generate }) {
2582
- for (const generator of generators) {
2583
- if (!(generator.match ? await generator.match(node, ctx) : true)) continue;
2584
- await this.fileManager.dispatch({
2585
- result: await generate(generator),
2586
- renderer: generator.renderer
2587
- });
2588
- }
2589
- }
2590
- /**
2591
- * Removes every listener the driver added. Listeners attached directly to `hooks` from outside
2592
- * the driver survive. Called at the end of a build to prevent leaks across repeated builds.
2593
- *
2594
- * @internal
2595
- */
2596
- dispose() {
2597
- for (const unhook of this.#unhooks) unhook();
2598
- this.#unhooks.length = 0;
2599
- this.fileManager.dispose();
2600
- this.inputNode = null;
2601
- this.#adapterSource = null;
2602
- }
2603
- [Symbol.dispose]() {
2604
- this.dispose();
2605
- }
2606
- getResolver(pluginName) {
2607
- return this.plugins.get(pluginName)?.resolver ?? createResolver({ pluginName });
2608
- }
2609
- getContext(plugin) {
2610
- const driver = this;
2611
- const report = (diagnostic) => {
2612
- Diagnostics.report({
2613
- ...diagnostic,
2614
- plugin: plugin.name
2615
- });
2616
- };
2617
- return {
2618
- config: driver.config,
2619
- signal: driver.options.signal,
2620
- get root() {
2621
- return (0, node_path.resolve)(driver.config.root, driver.config.output.path);
2622
- },
2623
- hooks: driver.hooks,
2624
- plugin,
2625
- getPlugin: driver.getPlugin.bind(driver),
2626
- requirePlugin: ((name) => driver.requirePlugin(name, { requiredBy: plugin.name })),
2627
- getResolver: driver.getResolver.bind(driver),
2628
- driver,
2629
- addFile: async (...files) => {
2630
- driver.fileManager.add(...files);
2631
- },
2632
- upsertFile: async (...files) => {
2633
- driver.fileManager.upsert(...files);
2634
- },
2635
- get meta() {
2636
- return driver.inputNode?.meta ?? {
2637
- circularNames: [],
2638
- enumNames: []
2639
- };
2640
- },
2641
- get adapter() {
2642
- return driver.adapter;
2643
- },
2644
- get resolver() {
2645
- return driver.getResolver(plugin.name);
2646
- },
2647
- warn(message, options) {
2648
- report({
2649
- code: Diagnostics.code.pluginWarning,
2650
- severity: "warning",
2651
- message,
2652
- ...options
2653
- });
2654
- },
2655
- error(error, options) {
2656
- if (Diagnostics.isError(error)) {
2657
- report({
2658
- ...options,
2659
- ...error.diagnostic
2660
- });
2661
- return;
2662
- }
2663
- const cause = typeof error === "string" ? void 0 : error;
2664
- report({
2665
- code: Diagnostics.code.pluginFailed,
2666
- severity: "error",
2667
- message: typeof error === "string" ? error : error.message,
2668
- cause,
2669
- ...options
2670
- });
2671
- },
2672
- info(message, options) {
2673
- report({
2674
- code: Diagnostics.code.pluginInfo,
2675
- severity: "info",
2676
- message,
2677
- ...options
2678
- });
2679
- }
2680
- };
2681
- }
2682
- getPlugin(pluginName) {
2683
- return this.plugins.get(pluginName);
2684
- }
2685
- requirePlugin(pluginName, context) {
2686
- const plugin = this.getPlugin(pluginName);
2687
- if (plugin) return plugin;
2688
- throw pluginNotFoundError({
2689
- pluginName,
2690
- requiredBy: context?.requiredBy
2691
- });
2692
- }
2693
- };
2694
- /** The `KUBB_PLUGIN_NOT_FOUND` error `requirePlugin` throws, naming the plugin that needed it. */
2695
- function pluginNotFoundError({ pluginName, requiredBy }) {
2696
- const by = requiredBy ? ` by "${requiredBy}"` : "";
2697
- const help = requiredBy ? ` (required by "${requiredBy}")` : "";
2698
- return new Diagnostics.Error({
2699
- code: Diagnostics.code.pluginNotFound,
2700
- severity: "error",
2701
- message: `Plugin "${pluginName}" is required${by} but not found. Make sure it is included in your Kubb config.`,
2702
- help: `Add "${pluginName}" to the \`plugins\` array in kubb.config.ts${help}, or remove the dependency on it.`,
2703
- location: { kind: "config" },
2704
- ...requiredBy ? { plugin: requiredBy } : {}
2705
- });
2706
- }
2707
- //#endregion
2708
- //#region src/Hookable.ts
2709
- /**
2710
- * Typed hook emitter that awaits all async listeners before resolving.
2711
- *
2712
- * @example
2713
- * ```ts
2714
- * const hooks = new Hookable<{ build: [name: string] }>()
2715
- * hooks.hook('build', async (name) => { console.log(name) })
2716
- * await hooks.callHook('build', 'petstore') // all listeners awaited
2717
- * ```
2718
- */
2719
- var Hookable = class {
2720
- #listeners = /* @__PURE__ */ new Map();
2721
- /**
2722
- * Calls `hookName` and awaits all registered listeners sequentially.
2723
- * Throws if any listener rejects, wrapping the cause in an error that names the hook.
2724
- *
2725
- * @example
2726
- * ```ts
2727
- * await hooks.callHook('build', 'petstore')
2728
- * ```
2729
- */
2730
- callHook(hookName, ...hookArgs) {
2731
- const listeners = this.#listeners.get(hookName);
2732
- if (!listeners?.size) return;
2733
- return this.#emitAll(hookName, [...listeners], hookArgs);
2734
- }
2735
- async #emitAll(hookName, listeners, hookArgs) {
2736
- for (const listener of listeners) try {
2737
- await listener(...hookArgs);
2738
- } catch (err) {
2739
- throw new Error(`Error in async listener for "${hookName}"`, { cause: toError(err) });
2740
- }
2741
- }
2742
- /**
2743
- * Registers a persistent listener for `hookName` and returns a function that removes it.
2744
- *
2745
- * @example
2746
- * ```ts
2747
- * const unhook = hooks.hook('build', async (name) => { console.log(name) })
2748
- * unhook() // removes it
2749
- * ```
2750
- */
2751
- hook(hookName, handler) {
2752
- let listeners = this.#listeners.get(hookName);
2753
- if (!listeners) this.#listeners.set(hookName, listeners = /* @__PURE__ */ new Set());
2754
- listeners.add(handler);
2755
- return () => this.removeHook(hookName, handler);
2756
- }
2757
- /**
2758
- * Registers every handler in `configHooks` at once and returns a function that removes them
2759
- * all. Undefined entries are skipped, so a partial hook object registers only its present keys.
2760
- *
2761
- * @example
2762
- * ```ts
2763
- * const unhook = hooks.addHooks({ build: onBuild, done: onDone })
2764
- * unhook() // removes both
2765
- * ```
2766
- */
2767
- addHooks(configHooks) {
2768
- const unhooks = Object.keys(configHooks).filter((name) => configHooks[name]).map((name) => this.hook(name, configHooks[name]));
2769
- return () => {
2770
- for (const unhook of unhooks) unhook();
2771
- };
2772
- }
2773
- /**
2774
- * Removes a previously registered listener.
2775
- *
2776
- * @example
2777
- * ```ts
2778
- * hooks.removeHook('build', handler)
2779
- * ```
2780
- */
2781
- removeHook(hookName, handler) {
2782
- this.#listeners.get(hookName)?.delete(handler);
2783
- }
2784
- /**
2785
- * Returns the number of listeners registered for `hookName`.
2786
- *
2787
- * @example
2788
- * ```ts
2789
- * hooks.hook('build', handler)
2790
- * hooks.listenerCount('build') // 1
2791
- * ```
2792
- */
2793
- listenerCount(hookName) {
2794
- return this.#listeners.get(hookName)?.size ?? 0;
2795
- }
2796
- /**
2797
- * No-op kept for callers written against the `EventEmitter`-backed version. Listeners are unbounded.
2798
- *
2799
- * @deprecated There is no listener ceiling anymore.
2800
- */
2801
- setMaxListeners(_max) {}
2802
- /**
2803
- * Removes all listeners from every hook channel.
2804
- *
2805
- * @example
2806
- * ```ts
2807
- * hooks.removeAllHooks()
2808
- * ```
2809
- */
2810
- removeAllHooks() {
2811
- this.#listeners.clear();
2812
- }
2813
- };
2814
- //#endregion
2815
- Object.defineProperty(exports, "Diagnostics", {
2816
- enumerable: true,
2817
- get: function() {
2818
- return Diagnostics;
2819
- }
2820
- });
2821
- Object.defineProperty(exports, "FileManager", {
2822
- enumerable: true,
2823
- get: function() {
2824
- return FileManager;
2825
- }
2826
- });
2827
- Object.defineProperty(exports, "Hookable", {
2828
- enumerable: true,
2829
- get: function() {
2830
- return Hookable;
2831
- }
2832
- });
2833
- Object.defineProperty(exports, "KubbDriver", {
2834
- enumerable: true,
2835
- get: function() {
2836
- return KubbDriver;
2837
- }
2838
- });
2839
- Object.defineProperty(exports, "Resolver", {
2840
- enumerable: true,
2841
- get: function() {
2842
- return Resolver;
2843
- }
2844
- });
2845
- Object.defineProperty(exports, "__name", {
2846
- enumerable: true,
2847
- get: function() {
2848
- return __name;
2849
- }
2850
- });
2851
- Object.defineProperty(exports, "__toESM", {
2852
- enumerable: true,
2853
- get: function() {
2854
- return __toESM;
2855
- }
2856
- });
2857
- Object.defineProperty(exports, "_usingCtx", {
2858
- enumerable: true,
2859
- get: function() {
2860
- return _usingCtx;
2861
- }
2862
- });
2863
- Object.defineProperty(exports, "addGenerator", {
2864
- enumerable: true,
2865
- get: function() {
2866
- return addGenerator;
2867
- }
2868
- });
2869
- Object.defineProperty(exports, "addMacro", {
2870
- enumerable: true,
2871
- get: function() {
2872
- return addMacro;
2873
- }
2874
- });
2875
- Object.defineProperty(exports, "assertPluginOption", {
2876
- enumerable: true,
2877
- get: function() {
2878
- return assertPluginOption;
2879
- }
2880
- });
2881
- Object.defineProperty(exports, "camelCase", {
2882
- enumerable: true,
2883
- get: function() {
2884
- return camelCase;
2885
- }
2886
- });
2887
- Object.defineProperty(exports, "checkCompatibility", {
2888
- enumerable: true,
2889
- get: function() {
2890
- return checkCompatibility;
2891
- }
2892
- });
2893
- Object.defineProperty(exports, "createNodeCache", {
2894
- enumerable: true,
2895
- get: function() {
2896
- return createNodeCache;
2897
- }
2898
- });
2899
- Object.defineProperty(exports, "createResolver", {
2900
- enumerable: true,
2901
- get: function() {
2902
- return createResolver;
2903
- }
2904
- });
2905
- Object.defineProperty(exports, "defineExtension", {
2906
- enumerable: true,
2907
- get: function() {
2908
- return defineExtension;
2909
- }
2910
- });
2911
- Object.defineProperty(exports, "definePlugin", {
2912
- enumerable: true,
2913
- get: function() {
2914
- return definePlugin;
2915
- }
2916
- });
2917
- Object.defineProperty(exports, "formatMs", {
2918
- enumerable: true,
2919
- get: function() {
2920
- return formatMs;
2921
- }
2922
- });
2923
- Object.defineProperty(exports, "getElapsedMs", {
2924
- enumerable: true,
2925
- get: function() {
2926
- return getElapsedMs;
2927
- }
2928
- });
2929
- Object.defineProperty(exports, "getInputKind", {
2930
- enumerable: true,
2931
- get: function() {
2932
- return getInputKind;
2933
- }
2934
- });
2935
- Object.defineProperty(exports, "inParallel", {
2936
- enumerable: true,
2937
- get: function() {
2938
- return inParallel;
2939
- }
2940
- });
2941
- Object.defineProperty(exports, "injectFile", {
2942
- enumerable: true,
2943
- get: function() {
2944
- return injectFile;
2945
- }
2946
- });
2947
- Object.defineProperty(exports, "isPathInside", {
2948
- enumerable: true,
2949
- get: function() {
2950
- return isPathInside;
2951
- }
2952
- });
2953
- Object.defineProperty(exports, "kubbContext", {
2954
- enumerable: true,
2955
- get: function() {
2956
- return kubbContext;
2957
- }
2958
- });
2959
- Object.defineProperty(exports, "pluginNotFoundError", {
2960
- enumerable: true,
2961
- get: function() {
2962
- return pluginNotFoundError;
2963
- }
2964
- });
2965
- Object.defineProperty(exports, "read", {
2966
- enumerable: true,
2967
- get: function() {
2968
- return read;
2969
- }
2970
- });
2971
- Object.defineProperty(exports, "requirePlugin", {
2972
- enumerable: true,
2973
- get: function() {
2974
- return requirePlugin;
2975
- }
2976
- });
2977
- Object.defineProperty(exports, "resolveMeta", {
2978
- enumerable: true,
2979
- get: function() {
2980
- return resolveMeta;
2981
- }
2982
- });
2983
- Object.defineProperty(exports, "setMacros", {
2984
- enumerable: true,
2985
- get: function() {
2986
- return setMacros;
2987
- }
2988
- });
2989
- Object.defineProperty(exports, "setOptions", {
2990
- enumerable: true,
2991
- get: function() {
2992
- return setOptions;
2993
- }
2994
- });
2995
- Object.defineProperty(exports, "setResolver", {
2996
- enumerable: true,
2997
- get: function() {
2998
- return setResolver;
2999
- }
3000
- });
3001
- Object.defineProperty(exports, "toError", {
3002
- enumerable: true,
3003
- get: function() {
3004
- return toError;
3005
- }
3006
- });
3007
- Object.defineProperty(exports, "toPosixPath", {
3008
- enumerable: true,
3009
- get: function() {
3010
- return toPosixPath;
3011
- }
3012
- });
3013
- Object.defineProperty(exports, "tryUseKubb", {
3014
- enumerable: true,
3015
- get: function() {
3016
- return tryUseKubb;
3017
- }
3018
- });
3019
- Object.defineProperty(exports, "useConfig", {
3020
- enumerable: true,
3021
- get: function() {
3022
- return useConfig;
3023
- }
3024
- });
3025
- Object.defineProperty(exports, "useKubb", {
3026
- enumerable: true,
3027
- get: function() {
3028
- return useKubb;
3029
- }
3030
- });
3031
- Object.defineProperty(exports, "useOptions", {
3032
- enumerable: true,
3033
- get: function() {
3034
- return useOptions;
3035
- }
3036
- });
3037
- Object.defineProperty(exports, "write", {
3038
- enumerable: true,
3039
- get: function() {
3040
- return write;
3041
- }
3042
- });
3043
-
3044
- //# sourceMappingURL=Hookable-RTuEiBd9.cjs.map