@kubb/core 5.6.1 → 5.6.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/KubbDriver-BZBnKODj.js +2562 -0
- package/dist/KubbDriver-BZBnKODj.js.map +1 -0
- package/dist/KubbDriver-CVFm4dwb.cjs +2737 -0
- package/dist/KubbDriver-CVFm4dwb.cjs.map +1 -0
- package/dist/index.cjs +55 -1903
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.ts +2 -2
- package/dist/index.js +14 -1862
- package/dist/index.js.map +1 -1
- package/dist/mocks.cjs +35 -7
- package/dist/mocks.cjs.map +1 -1
- package/dist/mocks.d.ts +6 -1
- package/dist/mocks.js +30 -3
- package/dist/mocks.js.map +1 -1
- package/dist/{types-B-w6zShf.d.ts → types-BjZ8hdyZ.d.ts} +18 -4
- package/package.json +2 -2
- package/dist/nodeCache-CllHsCcy.cjs +0 -805
- package/dist/nodeCache-CllHsCcy.cjs.map +0 -1
- package/dist/nodeCache-CumrOPh-.js +0 -685
- package/dist/nodeCache-CumrOPh-.js.map +0 -1
package/dist/index.cjs
CHANGED
|
@@ -1,21 +1,18 @@
|
|
|
1
1
|
Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
|
|
2
|
-
const
|
|
3
|
-
let node_async_hooks = require("node:async_hooks");
|
|
2
|
+
const require_KubbDriver = require("./KubbDriver-CVFm4dwb.cjs");
|
|
4
3
|
let node_util = require("node:util");
|
|
5
4
|
let node_process = require("node:process");
|
|
6
|
-
node_process =
|
|
5
|
+
node_process = require_KubbDriver.__toESM(node_process, 1);
|
|
7
6
|
let tinyexec = require("tinyexec");
|
|
8
7
|
let node_fs_promises = require("node:fs/promises");
|
|
9
8
|
let node_path = require("node:path");
|
|
10
|
-
node_path = require_nodeCache.__toESM(node_path, 1);
|
|
11
|
-
let _kubb_ast = require("@kubb/ast");
|
|
12
9
|
let node_crypto = require("node:crypto");
|
|
13
10
|
let node_fs = require("node:fs");
|
|
14
11
|
let node_os = require("node:os");
|
|
15
12
|
let node_readline = require("node:readline");
|
|
16
13
|
let unstorage = require("unstorage");
|
|
17
14
|
let unstorage_drivers_fs = require("unstorage/drivers/fs");
|
|
18
|
-
unstorage_drivers_fs =
|
|
15
|
+
unstorage_drivers_fs = require_KubbDriver.__toESM(unstorage_drivers_fs, 1);
|
|
19
16
|
let node_url = require("node:url");
|
|
20
17
|
//#region src/createAdapter.ts
|
|
21
18
|
/**
|
|
@@ -209,1850 +206,6 @@ function tokenize(command) {
|
|
|
209
206
|
return (command.match(/[^\s"']+|"([^"]*)"|'([^']*)'/g) ?? []).map((token) => token.replace(/^["']|["']$/g, ""));
|
|
210
207
|
}
|
|
211
208
|
//#endregion
|
|
212
|
-
//#region ../../internals/utils/src/time.ts
|
|
213
|
-
/**
|
|
214
|
-
* Calculates elapsed time in milliseconds from a high-resolution `process.hrtime` start time.
|
|
215
|
-
* Rounds to 2 decimal places for sub-millisecond precision without noise.
|
|
216
|
-
*
|
|
217
|
-
* @example
|
|
218
|
-
* ```ts
|
|
219
|
-
* const start = process.hrtime()
|
|
220
|
-
* doWork()
|
|
221
|
-
* getElapsedMs(start) // 42.35
|
|
222
|
-
* ```
|
|
223
|
-
*/
|
|
224
|
-
function getElapsedMs(hrStart) {
|
|
225
|
-
const [seconds, nanoseconds] = process.hrtime(hrStart);
|
|
226
|
-
const ms = seconds * 1e3 + nanoseconds / 1e6;
|
|
227
|
-
return Math.round(ms * 100) / 100;
|
|
228
|
-
}
|
|
229
|
-
/**
|
|
230
|
-
* Converts a millisecond duration into a human-readable string (`ms`, `s`, or `m s`).
|
|
231
|
-
*
|
|
232
|
-
* @example
|
|
233
|
-
* ```ts
|
|
234
|
-
* formatMs(250) // '250ms'
|
|
235
|
-
* formatMs(1500) // '1.50s'
|
|
236
|
-
* formatMs(90000) // '1m 30.0s'
|
|
237
|
-
* ```
|
|
238
|
-
*/
|
|
239
|
-
function formatMs(ms) {
|
|
240
|
-
if (ms >= 6e4) return `${Math.floor(ms / 6e4)}m ${(ms % 6e4 / 1e3).toFixed(1)}s`;
|
|
241
|
-
if (ms >= 1e3) return `${(ms / 1e3).toFixed(2)}s`;
|
|
242
|
-
return `${Math.round(ms)}ms`;
|
|
243
|
-
}
|
|
244
|
-
//#endregion
|
|
245
|
-
//#region package.json
|
|
246
|
-
var version = "5.6.1";
|
|
247
|
-
//#endregion
|
|
248
|
-
//#region src/constants.ts
|
|
249
|
-
/**
|
|
250
|
-
* Stable codes Kubb attaches to a `Diagnostic`. Each maps to a known failure mode
|
|
251
|
-
* and stays stable so it can be referenced in tooling and (later) docs. Reference
|
|
252
|
-
* these instead of inlining the string at a throw site.
|
|
253
|
-
*/
|
|
254
|
-
const diagnosticCode = {
|
|
255
|
-
/**
|
|
256
|
-
* Fallback for an unstructured error with no specific code.
|
|
257
|
-
*/
|
|
258
|
-
unknown: "KUBB_UNKNOWN",
|
|
259
|
-
/**
|
|
260
|
-
* The file or URL set as `input` could not be read.
|
|
261
|
-
*/
|
|
262
|
-
inputNotFound: "KUBB_INPUT_NOT_FOUND",
|
|
263
|
-
/**
|
|
264
|
-
* A URL set as `input` (or referenced by a `$ref`) answered with a 4xx or 5xx status
|
|
265
|
-
* instead of the document.
|
|
266
|
-
*/
|
|
267
|
-
inputRequestFailed: "KUBB_INPUT_REQUEST_FAILED",
|
|
268
|
-
/**
|
|
269
|
-
* A URL set as `input` (or referenced by a `$ref`) never answered, so the request failed
|
|
270
|
-
* before a status was returned.
|
|
271
|
-
*/
|
|
272
|
-
inputUnreachable: "KUBB_INPUT_UNREACHABLE",
|
|
273
|
-
/**
|
|
274
|
-
* An adapter was configured without an `input`.
|
|
275
|
-
*/
|
|
276
|
-
inputRequired: "KUBB_INPUT_REQUIRED",
|
|
277
|
-
/**
|
|
278
|
-
* `input` uses the v4 `{ path }` / `{ data }` wrapper, which v5 reads as a parsed
|
|
279
|
-
* document instead of a pointer to one.
|
|
280
|
-
*/
|
|
281
|
-
legacyInput: "KUBB_LEGACY_INPUT",
|
|
282
|
-
/**
|
|
283
|
-
* The parsed `input` carries no `openapi` or `swagger` version, so it is not a
|
|
284
|
-
* document the adapter can read.
|
|
285
|
-
*/
|
|
286
|
-
invalidDocument: "KUBB_INVALID_DOCUMENT",
|
|
287
|
-
/** The document fails OpenAPI schema validation. Reported as a warning. */
|
|
288
|
-
invalidSpec: "KUBB_INVALID_SPEC",
|
|
289
|
-
/**
|
|
290
|
-
* A `$ref` (or equivalent reference) could not be resolved in the source document.
|
|
291
|
-
*/
|
|
292
|
-
refNotFound: "KUBB_REF_NOT_FOUND",
|
|
293
|
-
/**
|
|
294
|
-
* A server variable value is not allowed by its `enum`.
|
|
295
|
-
*/
|
|
296
|
-
invalidServerVariable: "KUBB_INVALID_SERVER_VARIABLE",
|
|
297
|
-
/**
|
|
298
|
-
* A required plugin is missing from the config.
|
|
299
|
-
*/
|
|
300
|
-
pluginNotFound: "KUBB_PLUGIN_NOT_FOUND",
|
|
301
|
-
/**
|
|
302
|
-
* A plugin threw while generating.
|
|
303
|
-
*/
|
|
304
|
-
pluginFailed: "KUBB_PLUGIN_FAILED",
|
|
305
|
-
/**
|
|
306
|
-
* A plugin reported a non-fatal warning through `ctx.warn`.
|
|
307
|
-
*/
|
|
308
|
-
pluginWarning: "KUBB_PLUGIN_WARNING",
|
|
309
|
-
/**
|
|
310
|
-
* A plugin reported an informational message through `ctx.info`.
|
|
311
|
-
*/
|
|
312
|
-
pluginInfo: "KUBB_PLUGIN_INFO",
|
|
313
|
-
/**
|
|
314
|
-
* A schema uses a `format` Kubb does not map to a specific type. Reserved for
|
|
315
|
-
* adapters to emit as a `warning`.
|
|
316
|
-
*/
|
|
317
|
-
unsupportedFormat: "KUBB_UNSUPPORTED_FORMAT",
|
|
318
|
-
/**
|
|
319
|
-
* A referenced schema or operation is marked `deprecated`. Reserved for adapters
|
|
320
|
-
* to emit as an `info`.
|
|
321
|
-
*/
|
|
322
|
-
deprecated: "KUBB_DEPRECATED",
|
|
323
|
-
/**
|
|
324
|
-
* An adapter is required but the config has none. The build cannot read the input
|
|
325
|
-
* without one.
|
|
326
|
-
*/
|
|
327
|
-
adapterRequired: "KUBB_ADAPTER_REQUIRED",
|
|
328
|
-
/**
|
|
329
|
-
* A resolved output path escapes the output directory, which can stem from a path
|
|
330
|
-
* traversal in the spec or a misconfigured `group.name`.
|
|
331
|
-
*/
|
|
332
|
-
pathTraversal: "KUBB_PATH_TRAVERSAL",
|
|
333
|
-
/**
|
|
334
|
-
* `output.clean` is enabled but `output.path` resolves to the project root or a parent of it,
|
|
335
|
-
* so cleaning would delete kubb.config and every source file.
|
|
336
|
-
*/
|
|
337
|
-
cleanRoot: "KUBB_CLEAN_ROOT",
|
|
338
|
-
/**
|
|
339
|
-
* A plugin's options are invalid, for example `output.mode: 'file'` paired with a `group` option.
|
|
340
|
-
*/
|
|
341
|
-
invalidPluginOptions: "KUBB_INVALID_PLUGIN_OPTIONS",
|
|
342
|
-
/**
|
|
343
|
-
* A post-generate command (`output.postGenerate`) exited with a failure.
|
|
344
|
-
*/
|
|
345
|
-
postGenerateFailed: "KUBB_POST_GENERATE_FAILED",
|
|
346
|
-
/**
|
|
347
|
-
* The formatter pass over the generated files failed.
|
|
348
|
-
*/
|
|
349
|
-
formatFailed: "KUBB_FORMAT_FAILED",
|
|
350
|
-
/**
|
|
351
|
-
* The linter pass over the generated files failed.
|
|
352
|
-
*/
|
|
353
|
-
lintFailed: "KUBB_LINT_FAILED",
|
|
354
|
-
/**
|
|
355
|
-
* A barrel tries to re-export the same name from more than one module.
|
|
356
|
-
*/
|
|
357
|
-
barrelDuplicateExport: "KUBB_BARREL_DUPLICATE_EXPORT",
|
|
358
|
-
/**
|
|
359
|
-
* Not a failure. Carries a plugin's elapsed time, summed into the run total.
|
|
360
|
-
*/
|
|
361
|
-
performance: "KUBB_PERFORMANCE",
|
|
362
|
-
/**
|
|
363
|
-
* Not a failure. A newer Kubb version is available on npm.
|
|
364
|
-
*/
|
|
365
|
-
updateAvailable: "KUBB_UPDATE_AVAILABLE"
|
|
366
|
-
};
|
|
367
|
-
//#endregion
|
|
368
|
-
//#region src/Diagnostics.ts
|
|
369
|
-
/**
|
|
370
|
-
* Docs major version, derived from the package version so the link tracks the published major.
|
|
371
|
-
*/
|
|
372
|
-
const docsMajor = version.split(".")[0] ?? "5";
|
|
373
|
-
/**
|
|
374
|
-
* Builds a type guard that narrows a {@link Diagnostic} to the variant for `kind`. A diagnostic
|
|
375
|
-
* with no `kind` is treated as a `problem`.
|
|
376
|
-
*/
|
|
377
|
-
function isKind(kind) {
|
|
378
|
-
return (diagnostic) => (diagnostic.kind ?? "problem") === kind;
|
|
379
|
-
}
|
|
380
|
-
/**
|
|
381
|
-
* Returns `true` when the diagnostic is a build {@link ProblemDiagnostic}.
|
|
382
|
-
*
|
|
383
|
-
* @example
|
|
384
|
-
* ```ts
|
|
385
|
-
* if (isProblem(diagnostic)) {
|
|
386
|
-
* console.log(diagnostic.location)
|
|
387
|
-
* }
|
|
388
|
-
* ```
|
|
389
|
-
*/
|
|
390
|
-
const isProblem = isKind("problem");
|
|
391
|
-
/**
|
|
392
|
-
* Returns `true` when the diagnostic is a per-plugin {@link PerformanceDiagnostic}.
|
|
393
|
-
*
|
|
394
|
-
* @example
|
|
395
|
-
* ```ts
|
|
396
|
-
* const timings = diagnostics.filter(isPerformance)
|
|
397
|
-
* ```
|
|
398
|
-
*/
|
|
399
|
-
const isPerformance = isKind("performance");
|
|
400
|
-
/**
|
|
401
|
-
* Returns `true` when the diagnostic is a version-update {@link UpdateDiagnostic}.
|
|
402
|
-
*
|
|
403
|
-
* @example
|
|
404
|
-
* ```ts
|
|
405
|
-
* if (isUpdate(diagnostic)) {
|
|
406
|
-
* console.log(diagnostic.latestVersion)
|
|
407
|
-
* }
|
|
408
|
-
* ```
|
|
409
|
-
*/
|
|
410
|
-
const isUpdate = isKind("update");
|
|
411
|
-
/**
|
|
412
|
-
* Accent color per severity. The color tints the `[CODE]` tag (red error, yellow warning,
|
|
413
|
-
* blue info).
|
|
414
|
-
*/
|
|
415
|
-
const severityStyle = {
|
|
416
|
-
error: "red",
|
|
417
|
-
warning: "yellow",
|
|
418
|
-
info: "blue"
|
|
419
|
-
};
|
|
420
|
-
const countKey = {
|
|
421
|
-
error: "errors",
|
|
422
|
-
warning: "warnings",
|
|
423
|
-
info: "infos"
|
|
424
|
-
};
|
|
425
|
-
/**
|
|
426
|
-
* Explanation for every {@link diagnosticCode}. Use {@link Diagnostics.explain} to look one up
|
|
427
|
-
* and `Diagnostics.docsUrl` for the matching kubb.dev page.
|
|
428
|
-
*/
|
|
429
|
-
const diagnosticCatalog = {
|
|
430
|
-
[diagnosticCode.unknown]: {
|
|
431
|
-
title: "Unknown error",
|
|
432
|
-
cause: "An error was thrown without a stable Kubb code, so it is reported as-is.",
|
|
433
|
-
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."
|
|
434
|
-
},
|
|
435
|
-
[diagnosticCode.inputNotFound]: {
|
|
436
|
-
title: "Input not found",
|
|
437
|
-
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.",
|
|
438
|
-
fix: "Check that the path exists and is readable, then set it as `input` or pass it on the CLI."
|
|
439
|
-
},
|
|
440
|
-
[diagnosticCode.inputRequestFailed]: {
|
|
441
|
-
title: "Input request failed",
|
|
442
|
-
cause: "A URL set as `input` (or reached through a `$ref`) answered with a 4xx or 5xx status instead of the document.",
|
|
443
|
-
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."
|
|
444
|
-
},
|
|
445
|
-
[diagnosticCode.inputUnreachable]: {
|
|
446
|
-
title: "Input unreachable",
|
|
447
|
-
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.",
|
|
448
|
-
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`."
|
|
449
|
-
},
|
|
450
|
-
[diagnosticCode.inputRequired]: {
|
|
451
|
-
title: "Input required",
|
|
452
|
-
cause: "An adapter is configured but no `input` was provided.",
|
|
453
|
-
fix: "Set `input` to a file path, a URL, an inline spec (JSON/YAML string), or a parsed object in your Kubb config."
|
|
454
|
-
},
|
|
455
|
-
[diagnosticCode.legacyInput]: {
|
|
456
|
-
title: "Legacy input shape",
|
|
457
|
-
cause: "`input` is a `{ path }` or `{ data }` wrapper, which v4 used to point at a document and v5 reads as the document itself.",
|
|
458
|
-
fix: "Unwrap it: `input: { path: \"./petStore.yaml\" }` becomes `input: \"./petStore.yaml\"`, and `input: { data: spec }` becomes `input: spec`."
|
|
459
|
-
},
|
|
460
|
-
[diagnosticCode.invalidDocument]: {
|
|
461
|
-
title: "Invalid document",
|
|
462
|
-
cause: "The parsed `input` has no `openapi` or `swagger` version field, so it is not an OpenAPI or Swagger document.",
|
|
463
|
-
fix: "Point `input` at a document that declares `openapi` or `swagger`, and check that a passed object is the spec itself rather than a wrapper around it."
|
|
464
|
-
},
|
|
465
|
-
[diagnosticCode.invalidSpec]: {
|
|
466
|
-
title: "Invalid spec",
|
|
467
|
-
cause: "The document does not pass OpenAPI schema validation. Kubb still generates from it, but the output can be incomplete or wrong.",
|
|
468
|
-
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."
|
|
469
|
-
},
|
|
470
|
-
[diagnosticCode.refNotFound]: {
|
|
471
|
-
title: "Reference not found",
|
|
472
|
-
cause: "A `$ref` could not be resolved in the source document.",
|
|
473
|
-
fix: "Add the missing definition (for example under `components.schemas`) or fix the `$ref`. Run `kubb validate` to check the spec."
|
|
474
|
-
},
|
|
475
|
-
[diagnosticCode.invalidServerVariable]: {
|
|
476
|
-
title: "Invalid server variable",
|
|
477
|
-
cause: "A server variable value is not allowed by its `enum`.",
|
|
478
|
-
fix: "Use one of the values listed in the server variable `enum`, or update the spec."
|
|
479
|
-
},
|
|
480
|
-
[diagnosticCode.pluginNotFound]: {
|
|
481
|
-
title: "Plugin not found",
|
|
482
|
-
cause: "A plugin that another plugin depends on is missing from the config.",
|
|
483
|
-
fix: "Add the required plugin to the `plugins` array in kubb.config.ts, or remove the dependency on it."
|
|
484
|
-
},
|
|
485
|
-
[diagnosticCode.pluginFailed]: {
|
|
486
|
-
title: "Plugin failed",
|
|
487
|
-
cause: "A plugin threw while generating, or reported an error through `ctx.error`.",
|
|
488
|
-
fix: "Read the underlying error and check the plugin options and the schema or operation it failed on."
|
|
489
|
-
},
|
|
490
|
-
[diagnosticCode.pluginWarning]: {
|
|
491
|
-
title: "Plugin warning",
|
|
492
|
-
cause: "A plugin reported a non-fatal warning through `ctx.warn`.",
|
|
493
|
-
fix: "Review the message. It does not fail the build; adjust the plugin options or input if the warning is unwanted."
|
|
494
|
-
},
|
|
495
|
-
[diagnosticCode.pluginInfo]: {
|
|
496
|
-
title: "Plugin info",
|
|
497
|
-
cause: "A plugin reported an informational message through `ctx.info`.",
|
|
498
|
-
fix: "Informational only. No action is required."
|
|
499
|
-
},
|
|
500
|
-
[diagnosticCode.unsupportedFormat]: {
|
|
501
|
-
title: "Unsupported format",
|
|
502
|
-
cause: "A schema uses a `format` Kubb does not map to a specific type, so it falls back to the base type.",
|
|
503
|
-
fix: "Use a format Kubb supports, or handle the custom format with a parser or plugin."
|
|
504
|
-
},
|
|
505
|
-
[diagnosticCode.deprecated]: {
|
|
506
|
-
title: "Deprecated",
|
|
507
|
-
cause: "A referenced schema or operation is marked `deprecated`.",
|
|
508
|
-
fix: "Migrate off the deprecated definition if the warning is unwanted."
|
|
509
|
-
},
|
|
510
|
-
[diagnosticCode.adapterRequired]: {
|
|
511
|
-
title: "Adapter required",
|
|
512
|
-
cause: "An action needs an adapter but none is configured.",
|
|
513
|
-
fix: "Set `adapter` in kubb.config.ts, for example `adapterOas()`."
|
|
514
|
-
},
|
|
515
|
-
[diagnosticCode.pathTraversal]: {
|
|
516
|
-
title: "Path traversal",
|
|
517
|
-
cause: "A resolved output path escaped the output directory, which can stem from a path traversal in the spec or a misconfigured `group.name`.",
|
|
518
|
-
fix: "Keep generated paths within the output directory. Review the `group.name` function and the names coming from the spec."
|
|
519
|
-
},
|
|
520
|
-
[diagnosticCode.cleanRoot]: {
|
|
521
|
-
title: "Clean targets the project root",
|
|
522
|
-
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.",
|
|
523
|
-
fix: "Point `output.path` at a subdirectory such as `./src/gen` so clean only removes generated code, or disable `output.clean`."
|
|
524
|
-
},
|
|
525
|
-
[diagnosticCode.invalidPluginOptions]: {
|
|
526
|
-
title: "Invalid plugin options",
|
|
527
|
-
cause: "A plugin was configured with options that cannot be honored, for example `output.mode: 'file'` paired with a `group` option.",
|
|
528
|
-
fix: "Fix the plugin options. A single-file output has nothing to group, so remove the `group` option or use `output.mode: 'directory'`."
|
|
529
|
-
},
|
|
530
|
-
[diagnosticCode.postGenerateFailed]: {
|
|
531
|
-
title: "Post-generate command failed",
|
|
532
|
-
cause: "A post-generate command (`output.postGenerate`) exited with a non-zero status.",
|
|
533
|
-
fix: "Check the command is installed and correct, and run it manually to see the error."
|
|
534
|
-
},
|
|
535
|
-
[diagnosticCode.formatFailed]: {
|
|
536
|
-
title: "Format failed",
|
|
537
|
-
cause: "The formatter pass over the generated files failed.",
|
|
538
|
-
fix: "Check the formatter (oxfmt, biome, or prettier) is installed and its config is valid, then run it manually on the output."
|
|
539
|
-
},
|
|
540
|
-
[diagnosticCode.lintFailed]: {
|
|
541
|
-
title: "Lint failed",
|
|
542
|
-
cause: "The linter pass over the generated files failed.",
|
|
543
|
-
fix: "Check the linter (oxlint, biome, or eslint) is installed and its config is valid, then run it manually on the output."
|
|
544
|
-
},
|
|
545
|
-
[diagnosticCode.barrelDuplicateExport]: {
|
|
546
|
-
title: "Duplicate barrel export",
|
|
547
|
-
cause: "Two generated modules export the same name, so the barrel cannot re-export both.",
|
|
548
|
-
fix: "Rename one of the colliding declarations, or configure the plugin resolver to produce distinct names."
|
|
549
|
-
},
|
|
550
|
-
[diagnosticCode.performance]: {
|
|
551
|
-
title: "Performance",
|
|
552
|
-
cause: "Not a failure. Records a plugin’s elapsed time, summed into the run total.",
|
|
553
|
-
fix: "No action. This is an informational metric."
|
|
554
|
-
},
|
|
555
|
-
[diagnosticCode.updateAvailable]: {
|
|
556
|
-
title: "Update available",
|
|
557
|
-
cause: "A newer Kubb version is published on npm than the one running.",
|
|
558
|
-
fix: "Update the `@kubb/*` packages, for example `npm install -g @kubb/cli`, to get the latest fixes."
|
|
559
|
-
}
|
|
560
|
-
};
|
|
561
|
-
/**
|
|
562
|
-
* Static helpers for working with {@link Diagnostic}s, plus the run-scoped sink
|
|
563
|
-
* that lets deep code report a diagnostic without threading a callback.
|
|
564
|
-
*
|
|
565
|
-
* The sink lives in a single `AsyncLocalStorage` in the `@kubb/core` bundle.
|
|
566
|
-
* `Diagnostics.scope` activates it for a run, so anything inside that run (the
|
|
567
|
-
* adapter parse, a generator) reports through `Diagnostics.report` and lands
|
|
568
|
-
* in the same run.
|
|
569
|
-
*/
|
|
570
|
-
var Diagnostics = class Diagnostics {
|
|
571
|
-
static #reporterStorage = new node_async_hooks.AsyncLocalStorage();
|
|
572
|
-
/**
|
|
573
|
-
* The diagnostic code catalog, exposed as `Diagnostics.code` (e.g. `Diagnostics.code.refNotFound`).
|
|
574
|
-
*/
|
|
575
|
-
static code = diagnosticCode;
|
|
576
|
-
/**
|
|
577
|
-
* Type guard for a build {@link ProblemDiagnostic}.
|
|
578
|
-
*/
|
|
579
|
-
static isProblem = isProblem;
|
|
580
|
-
/**
|
|
581
|
-
* Type guard for a version-update {@link UpdateDiagnostic}.
|
|
582
|
-
*/
|
|
583
|
-
static isUpdate = isUpdate;
|
|
584
|
-
/**
|
|
585
|
-
* Type guard for a per-plugin {@link PerformanceDiagnostic}.
|
|
586
|
-
*/
|
|
587
|
-
static isPerformance = isPerformance;
|
|
588
|
-
/**
|
|
589
|
-
* An `Error` that carries a {@link Diagnostic}, so structured problems can flow
|
|
590
|
-
* through the existing throw/catch paths while keeping their code and location.
|
|
591
|
-
*
|
|
592
|
-
* @example
|
|
593
|
-
* ```ts
|
|
594
|
-
* throw new Diagnostics.Error({ code: diagnosticCode.refNotFound, severity: 'error', message: `Could not find ${ref}`, location: { kind: 'schema', pointer: ref, ref } })
|
|
595
|
-
* ```
|
|
596
|
-
*/
|
|
597
|
-
static Error = class DiagnosticError extends Error {
|
|
598
|
-
diagnostic;
|
|
599
|
-
constructor(diagnostic) {
|
|
600
|
-
super(diagnostic.message, { cause: diagnostic.cause });
|
|
601
|
-
this.name = "DiagnosticError";
|
|
602
|
-
this.diagnostic = diagnostic;
|
|
603
|
-
}
|
|
604
|
-
};
|
|
605
|
-
/**
|
|
606
|
-
* Structural check for a {@link Diagnostics.Error}, including one thrown from a duplicated
|
|
607
|
-
* `@kubb/core` copy where `instanceof` fails. Matches on the `name` and a `diagnostic`
|
|
608
|
-
* that carries a `code`.
|
|
609
|
-
*/
|
|
610
|
-
static isError(error) {
|
|
611
|
-
if (error instanceof Diagnostics.Error) return true;
|
|
612
|
-
if (!(error instanceof Error) || error.name !== "DiagnosticError") return false;
|
|
613
|
-
const { diagnostic } = error;
|
|
614
|
-
return typeof diagnostic === "object" && diagnostic !== null && typeof diagnostic.code === "string";
|
|
615
|
-
}
|
|
616
|
-
/**
|
|
617
|
-
* Runs `fn` with `sink` as the active diagnostic sink for the whole async
|
|
618
|
-
* subtree, so {@link Diagnostics.report} reaches it from anywhere inside.
|
|
619
|
-
*/
|
|
620
|
-
static scope(sink, fn) {
|
|
621
|
-
return Diagnostics.#reporterStorage.run(sink, fn);
|
|
622
|
-
}
|
|
623
|
-
/**
|
|
624
|
-
* Collects a diagnostic into the active build via the run-scoped sink, without throwing.
|
|
625
|
-
* Returns `true` when a run consumed it, `false` when called outside a {@link Diagnostics.scope}
|
|
626
|
-
* (so callers can fall back to throwing). Use a `warning`/`info` severity for non-fatal issues.
|
|
627
|
-
* For rendering a diagnostic live on the hook bus, use {@link Diagnostics.emit} instead.
|
|
628
|
-
*/
|
|
629
|
-
static report(diagnostic) {
|
|
630
|
-
const sink = Diagnostics.#reporterStorage.getStore();
|
|
631
|
-
if (!sink) return false;
|
|
632
|
-
sink(diagnostic);
|
|
633
|
-
return true;
|
|
634
|
-
}
|
|
635
|
-
/**
|
|
636
|
-
* Emits a diagnostic on the run's `kubb:diagnostic` hook so the loggers render it live.
|
|
637
|
-
* Use it instead of calling `hooks.callHook('kubb:diagnostic', ...)` directly. To collect a
|
|
638
|
-
* diagnostic into the build result from deep in a run, use {@link Diagnostics.report} instead.
|
|
639
|
-
*/
|
|
640
|
-
static async emit(hooks, diagnostic) {
|
|
641
|
-
await hooks.callHook("kubb:diagnostic", { diagnostic });
|
|
642
|
-
}
|
|
643
|
-
/**
|
|
644
|
-
* Coerces any thrown value into a {@link ProblemDiagnostic}. A {@link Diagnostics.Error}
|
|
645
|
-
* keeps its structured data, and anything else becomes a `KUBB_UNKNOWN` error.
|
|
646
|
-
*/
|
|
647
|
-
static from(error) {
|
|
648
|
-
const seen = /* @__PURE__ */ new Set();
|
|
649
|
-
let current = error;
|
|
650
|
-
let root;
|
|
651
|
-
while (current instanceof Error && !seen.has(current)) {
|
|
652
|
-
if (Diagnostics.isError(current)) return current.diagnostic;
|
|
653
|
-
seen.add(current);
|
|
654
|
-
root = current;
|
|
655
|
-
current = current.cause;
|
|
656
|
-
}
|
|
657
|
-
return {
|
|
658
|
-
code: diagnosticCode.unknown,
|
|
659
|
-
severity: "error",
|
|
660
|
-
message: root ? root.message : require_nodeCache.getErrorMessage(error),
|
|
661
|
-
cause: root
|
|
662
|
-
};
|
|
663
|
-
}
|
|
664
|
-
/**
|
|
665
|
-
* Builds a per-plugin performance record. Reporters sum these into the run total.
|
|
666
|
-
*/
|
|
667
|
-
static performance({ plugin, duration }) {
|
|
668
|
-
return {
|
|
669
|
-
kind: "performance",
|
|
670
|
-
code: diagnosticCode.performance,
|
|
671
|
-
severity: "info",
|
|
672
|
-
message: `${plugin} generated in ${Math.round(duration)}ms`,
|
|
673
|
-
plugin,
|
|
674
|
-
duration
|
|
675
|
-
};
|
|
676
|
-
}
|
|
677
|
-
/**
|
|
678
|
-
* Builds the version-update notice shown when a newer Kubb is published on npm.
|
|
679
|
-
*/
|
|
680
|
-
static update({ currentVersion, latestVersion }) {
|
|
681
|
-
return {
|
|
682
|
-
kind: "update",
|
|
683
|
-
code: diagnosticCode.updateAvailable,
|
|
684
|
-
severity: "info",
|
|
685
|
-
message: `Update available: v${currentVersion} → v${latestVersion}. Run \`npm install -g @kubb/cli\` to update.`,
|
|
686
|
-
currentVersion,
|
|
687
|
-
latestVersion
|
|
688
|
-
};
|
|
689
|
-
}
|
|
690
|
-
/**
|
|
691
|
-
* True when any diagnostic is an error, the severity that fails a build. Non-error
|
|
692
|
-
* diagnostics are ignored.
|
|
693
|
-
*/
|
|
694
|
-
static hasError(diagnostics) {
|
|
695
|
-
return diagnostics.some((diagnostic) => diagnostic.severity === "error");
|
|
696
|
-
}
|
|
697
|
-
/**
|
|
698
|
-
* Names of the plugins that failed, deduped, derived from the error diagnostics
|
|
699
|
-
* that carry a `plugin`.
|
|
700
|
-
*/
|
|
701
|
-
static failedPlugins(diagnostics) {
|
|
702
|
-
return [...new Set(diagnostics.flatMap((diagnostic) => diagnostic.severity === "error" && diagnostic.plugin ? [diagnostic.plugin] : []))];
|
|
703
|
-
}
|
|
704
|
-
/**
|
|
705
|
-
* Counts `problem` diagnostics by severity for the run summary. `performance` and
|
|
706
|
-
* `update` diagnostics are ignored.
|
|
707
|
-
*/
|
|
708
|
-
static count(diagnostics) {
|
|
709
|
-
const counts = {
|
|
710
|
-
errors: 0,
|
|
711
|
-
warnings: 0,
|
|
712
|
-
infos: 0
|
|
713
|
-
};
|
|
714
|
-
for (const diagnostic of diagnostics.filter(isProblem)) counts[countKey[diagnostic.severity]] += 1;
|
|
715
|
-
return counts;
|
|
716
|
-
}
|
|
717
|
-
/**
|
|
718
|
-
* Drops duplicate `problem` diagnostics that share a code, location pointer, and
|
|
719
|
-
* plugin, so the same issue reported across several passes is shown once. Non-problem
|
|
720
|
-
* diagnostics are always kept.
|
|
721
|
-
*/
|
|
722
|
-
static dedupe(diagnostics) {
|
|
723
|
-
const seen = /* @__PURE__ */ new Set();
|
|
724
|
-
const result = [];
|
|
725
|
-
for (const diagnostic of diagnostics) {
|
|
726
|
-
if (!isProblem(diagnostic)) {
|
|
727
|
-
result.push(diagnostic);
|
|
728
|
-
continue;
|
|
729
|
-
}
|
|
730
|
-
const pointer = diagnostic.location && "pointer" in diagnostic.location ? diagnostic.location.pointer : "";
|
|
731
|
-
const key = `${diagnostic.code} ${pointer} ${diagnostic.plugin ?? ""}`;
|
|
732
|
-
if (seen.has(key)) continue;
|
|
733
|
-
seen.add(key);
|
|
734
|
-
result.push(diagnostic);
|
|
735
|
-
}
|
|
736
|
-
return result;
|
|
737
|
-
}
|
|
738
|
-
/**
|
|
739
|
-
* Builds the kubb.dev docs URL for a diagnostic code, e.g.
|
|
740
|
-
* `KUBB_REF_NOT_FOUND` → `https://kubb.dev/docs/5.x/reference/diagnostics#kubb-ref-not-found`.
|
|
741
|
-
*/
|
|
742
|
-
static docsUrl(code) {
|
|
743
|
-
const slug = code.toLowerCase().replaceAll("_", "-");
|
|
744
|
-
return `https://kubb.dev/docs/${docsMajor}.x/reference/diagnostics#${slug}`;
|
|
745
|
-
}
|
|
746
|
-
/**
|
|
747
|
-
* The catalog entry for a code: its title, cause, and fix. Mirrors the kubb.dev
|
|
748
|
-
* `/reference/diagnostics#<slug>` section.
|
|
749
|
-
*/
|
|
750
|
-
static explain(code) {
|
|
751
|
-
return diagnosticCatalog[code];
|
|
752
|
-
}
|
|
753
|
-
/**
|
|
754
|
-
* Reduces a diagnostic to its JSON-safe fields plus a `docsUrl`, for machine-readable
|
|
755
|
-
* consumers. The `cause`, `kind`, and `duration` are dropped, and absent optional
|
|
756
|
-
* fields are omitted rather than set to `undefined`.
|
|
757
|
-
*/
|
|
758
|
-
static serialize(diagnostic) {
|
|
759
|
-
const problem = isProblem(diagnostic) ? diagnostic : void 0;
|
|
760
|
-
return {
|
|
761
|
-
code: diagnostic.code,
|
|
762
|
-
severity: diagnostic.severity,
|
|
763
|
-
message: diagnostic.message,
|
|
764
|
-
...problem?.location ? { location: problem.location } : {},
|
|
765
|
-
...problem?.help ? { help: problem.help } : {},
|
|
766
|
-
...problem?.plugin ? { plugin: problem.plugin } : {},
|
|
767
|
-
...diagnostic.code === diagnosticCode.unknown ? {} : { docsUrl: Diagnostics.docsUrl(diagnostic.code) }
|
|
768
|
-
};
|
|
769
|
-
}
|
|
770
|
-
/**
|
|
771
|
-
* Renders a {@link Diagnostic} for terminal output as its parts: the `headline`
|
|
772
|
-
* (`[CODE] plugin: message`, with the code in the severity color) and the indented `details`
|
|
773
|
-
* rows (`at:` pointer, `fix:` help, `see:` docs link).
|
|
774
|
-
*
|
|
775
|
-
* Hosts compose these to fit their gutter: a clack logger passes `[headline, ...details]` as the
|
|
776
|
-
* message with no gutter symbol, while plain text outputs use {@link Diagnostics.formatLines}.
|
|
777
|
-
*/
|
|
778
|
-
static format(diagnostic) {
|
|
779
|
-
const { code, severity, message } = diagnostic;
|
|
780
|
-
const color = severityStyle[severity];
|
|
781
|
-
const problem = isProblem(diagnostic) ? diagnostic : void 0;
|
|
782
|
-
const tag = (0, node_util.styleText)(color, (0, node_util.styleText)("bold", `[${code}]`));
|
|
783
|
-
const headline = problem?.plugin ? `${tag} ${problem.plugin}: ${message}` : `${tag}: ${message}`;
|
|
784
|
-
const details = [];
|
|
785
|
-
if (problem?.location && "pointer" in problem.location) details.push(` ${(0, node_util.styleText)("dim", "at:")} ${(0, node_util.styleText)("cyan", problem.location.pointer)}`);
|
|
786
|
-
if (problem?.help) details.push(` ${(0, node_util.styleText)("cyan", "fix:")} ${problem.help}`);
|
|
787
|
-
if (code !== diagnosticCode.unknown) details.push(` ${(0, node_util.styleText)("dim", "see:")} ${(0, node_util.styleText)("cyan", Diagnostics.docsUrl(code))}`);
|
|
788
|
-
return {
|
|
789
|
-
headline,
|
|
790
|
-
details
|
|
791
|
-
};
|
|
792
|
-
}
|
|
793
|
-
/**
|
|
794
|
-
* The self-contained block form of {@link Diagnostics.format}: the `headline` followed by the
|
|
795
|
-
* indented detail rows. Used where there is no gutter (plain and file output).
|
|
796
|
-
*/
|
|
797
|
-
static formatLines(diagnostic) {
|
|
798
|
-
const { headline, details } = Diagnostics.format(diagnostic);
|
|
799
|
-
return [headline, ...details];
|
|
800
|
-
}
|
|
801
|
-
};
|
|
802
|
-
//#endregion
|
|
803
|
-
//#region src/definePlugin.ts
|
|
804
|
-
/**
|
|
805
|
-
* Merges the `output.mode` default into the output config and validates the combination.
|
|
806
|
-
* Throws `KUBB_INVALID_PLUGIN_OPTIONS` when `mode: 'file'` is paired with a `group` option,
|
|
807
|
-
* since a single-file output has nothing to group.
|
|
808
|
-
*
|
|
809
|
-
* An omitted `mode` follows the shape of `path`: an extension means a single file, anything
|
|
810
|
-
* else is a directory. Plugin defaults such as `path: 'types'` name a directory, so they
|
|
811
|
-
* generate without the caller spelling out `mode`.
|
|
812
|
-
*/
|
|
813
|
-
function normalizeOutput({ output, group, pluginName }) {
|
|
814
|
-
const mode = output.mode ?? (node_path.default.extname(output.path) ? "file" : "directory");
|
|
815
|
-
if (mode === "file" && group) throw new Diagnostics.Error({
|
|
816
|
-
code: Diagnostics.code.invalidPluginOptions,
|
|
817
|
-
severity: "error",
|
|
818
|
-
message: `Plugin "${pluginName}" resolves \`output.mode\` to 'file' but also configures a \`group\` option.`,
|
|
819
|
-
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.",
|
|
820
|
-
location: { kind: "config" },
|
|
821
|
-
plugin: pluginName
|
|
822
|
-
});
|
|
823
|
-
return {
|
|
824
|
-
...output,
|
|
825
|
-
mode
|
|
826
|
-
};
|
|
827
|
-
}
|
|
828
|
-
/**
|
|
829
|
-
* Wraps a plugin factory and returns a function that accepts user options and
|
|
830
|
-
* yields a typed `Plugin`. Lifecycle handlers go inside a single `hooks` object.
|
|
831
|
-
*
|
|
832
|
-
* Pass a `PluginFactoryOptions` type parameter to get a typed `ctx` inside
|
|
833
|
-
* `kubb:plugin:setup`. Plugin names should follow the `plugin-<feature>`
|
|
834
|
-
* convention (`plugin-react-query`, `plugin-zod`, ...).
|
|
835
|
-
*
|
|
836
|
-
* @example
|
|
837
|
-
* ```ts
|
|
838
|
-
* import { definePlugin } from '@kubb/core'
|
|
839
|
-
*
|
|
840
|
-
* export const pluginTs = definePlugin((options: { prefix?: string } = {}) => ({
|
|
841
|
-
* name: 'plugin-ts',
|
|
842
|
-
* hooks: {
|
|
843
|
-
* 'kubb:plugin:setup'(ctx) {
|
|
844
|
-
* ctx.setResolver(resolverTs)
|
|
845
|
-
* },
|
|
846
|
-
* },
|
|
847
|
-
* }))
|
|
848
|
-
* ```
|
|
849
|
-
*/
|
|
850
|
-
function definePlugin(factory) {
|
|
851
|
-
return (options) => factory(options ?? {});
|
|
852
|
-
}
|
|
853
|
-
//#endregion
|
|
854
|
-
//#region src/input.ts
|
|
855
|
-
/**
|
|
856
|
-
* Classifies an `input` value so callers branch on it once instead of repeating the checks.
|
|
857
|
-
*
|
|
858
|
-
* A non-string is a parsed spec (`object`). A string is `inline` when it holds OpenAPI content,
|
|
859
|
-
* meaning it starts with `{` or `[`, spans multiple lines, or opens with a YAML `openapi:` or
|
|
860
|
-
* `swagger:` key. Otherwise a string is a `url` when it parses as one, or a `file` path.
|
|
861
|
-
*/
|
|
862
|
-
function getInputKind(input) {
|
|
863
|
-
if (typeof input !== "string") return "object";
|
|
864
|
-
const trimmed = input.trimStart();
|
|
865
|
-
if (trimmed.startsWith("{") || trimmed.startsWith("[") || input.includes("\n") || /^(openapi|swagger)\s*:/i.test(trimmed)) return "inline";
|
|
866
|
-
if (URL.canParse(input)) return "url";
|
|
867
|
-
return "file";
|
|
868
|
-
}
|
|
869
|
-
/**
|
|
870
|
-
* The v4 `input` wrapper keys. v4 typed `input` as `{ path }` or `{ data }`; v5 takes the value
|
|
871
|
-
* directly, so the wrapper now matches the "already-parsed document" branch and silently yields
|
|
872
|
-
* an empty build.
|
|
873
|
-
*/
|
|
874
|
-
const legacyInputKeys = ["path", "data"];
|
|
875
|
-
/**
|
|
876
|
-
* Detects the v4 `{ path }` / `{ data }` wrapper so it fails loudly instead of being read as a
|
|
877
|
-
* document. A real spec always carries more than these keys, so an object whose keys are drawn
|
|
878
|
-
* only from them is the old shape rather than a document that happens to have a `path` property.
|
|
879
|
-
*/
|
|
880
|
-
function isLegacyInput(input) {
|
|
881
|
-
if (Array.isArray(input)) return input.some(isLegacyInput);
|
|
882
|
-
if (typeof input !== "object" || input === null) return false;
|
|
883
|
-
const keys = Object.keys(input);
|
|
884
|
-
return keys.length > 0 && keys.every((key) => legacyInputKeys.includes(key));
|
|
885
|
-
}
|
|
886
|
-
/**
|
|
887
|
-
* Normalizes `config.input` into an `AdapterSource` the adapter can parse.
|
|
888
|
-
*
|
|
889
|
-
* A parsed object and inline content become `{ type: 'data' }`; a URL is kept verbatim and a
|
|
890
|
-
* local path is resolved against `config.root`, both as `{ type: 'path' }`.
|
|
891
|
-
*/
|
|
892
|
-
function inputToAdapterSource(config) {
|
|
893
|
-
const input = config.input;
|
|
894
|
-
if (input && isLegacyInput(input)) throw new Diagnostics.Error({
|
|
895
|
-
code: Diagnostics.code.legacyInput,
|
|
896
|
-
severity: "error",
|
|
897
|
-
message: "The `input` option uses the v4 `{ path }` / `{ data }` wrapper.",
|
|
898
|
-
help: "Unwrap it: `input: { path: \"./petStore.yaml\" }` becomes `input: \"./petStore.yaml\"`, and `input: { data: spec }` becomes `input: spec`.",
|
|
899
|
-
location: { kind: "config" }
|
|
900
|
-
});
|
|
901
|
-
if (!input) throw new Diagnostics.Error({
|
|
902
|
-
code: Diagnostics.code.inputRequired,
|
|
903
|
-
severity: "error",
|
|
904
|
-
message: "An adapter is configured without an input.",
|
|
905
|
-
help: "Set `input` to a file path, a URL, an inline spec (JSON/YAML string), or a parsed object in your Kubb config.",
|
|
906
|
-
location: { kind: "config" }
|
|
907
|
-
});
|
|
908
|
-
if (typeof input !== "string") return {
|
|
909
|
-
type: "data",
|
|
910
|
-
data: input
|
|
911
|
-
};
|
|
912
|
-
const kind = getInputKind(input);
|
|
913
|
-
if (kind === "inline") return {
|
|
914
|
-
type: "data",
|
|
915
|
-
data: input
|
|
916
|
-
};
|
|
917
|
-
if (kind === "url") return {
|
|
918
|
-
type: "path",
|
|
919
|
-
path: input
|
|
920
|
-
};
|
|
921
|
-
return {
|
|
922
|
-
type: "path",
|
|
923
|
-
path: (0, node_path.resolve)(config.root, input)
|
|
924
|
-
};
|
|
925
|
-
}
|
|
926
|
-
//#endregion
|
|
927
|
-
//#region src/Resolver.ts
|
|
928
|
-
function isNamespace(value) {
|
|
929
|
-
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
930
|
-
}
|
|
931
|
-
/**
|
|
932
|
-
* Shared brand for reaching a resolver's build options. `Resolver.merge` reads this instead of
|
|
933
|
-
* relying on `instanceof`, which fails when a CommonJS config and the ESM CLI each load their own
|
|
934
|
-
* copy of `@kubb/core`. `Symbol.for` resolves to one key across those copies, so the options stay
|
|
935
|
-
* reachable and a `file` override is never dropped.
|
|
936
|
-
*/
|
|
937
|
-
const resolverOptions = Symbol.for("@kubb/core/resolver/options");
|
|
938
|
-
/**
|
|
939
|
-
* Builds a nested file path from a dotted name. Splits on dots that precede a letter
|
|
940
|
-
* (so version numbers embedded in operationIds like `v2025.0` stay intact), camelCases
|
|
941
|
-
* every segment, and joins with `/`.
|
|
942
|
-
*
|
|
943
|
-
* Empty segments are dropped before joining. They arise when the name starts with a dot
|
|
944
|
-
* followed by a letter (e.g. `..Schema` splits into `['..', 'Schema']` and `'..'` cases to
|
|
945
|
-
* an empty string). Without this a leading `/` would form, which `path.resolve` reads as an
|
|
946
|
-
* absolute path, letting generated files escape the configured output directory.
|
|
947
|
-
*
|
|
948
|
-
* @example Nested path from a dotted name
|
|
949
|
-
* `toFilePath('pet.petId') // 'pet/petId'`
|
|
950
|
-
*/
|
|
951
|
-
function toFilePath(name) {
|
|
952
|
-
return name.split(/\.(?=[a-zA-Z])/).map((part) => require_nodeCache.camelCase(part)).filter(Boolean).join("/");
|
|
953
|
-
}
|
|
954
|
-
/** Throws `KUBB_PATH_TRAVERSAL` when `target` lies outside `parent`; `target === parent` stays allowed. */
|
|
955
|
-
function assertInside({ target, parent, message, help }) {
|
|
956
|
-
const parentWithSep = parent.endsWith(node_path.default.sep) ? parent : `${parent}${node_path.default.sep}`;
|
|
957
|
-
if (target === parent || target.startsWith(parentWithSep)) return;
|
|
958
|
-
throw new Diagnostics.Error({
|
|
959
|
-
code: Diagnostics.code.pathTraversal,
|
|
960
|
-
severity: "error",
|
|
961
|
-
message,
|
|
962
|
-
help,
|
|
963
|
-
location: { kind: "config" }
|
|
964
|
-
});
|
|
965
|
-
}
|
|
966
|
-
/**
|
|
967
|
-
* Built-in `file.baseName`: casts the identifier with `toFilePath` and appends the extension.
|
|
968
|
-
*/
|
|
969
|
-
function toBaseName({ name, extname }) {
|
|
970
|
-
return `${toFilePath(name)}${extname}`;
|
|
971
|
-
}
|
|
972
|
-
/**
|
|
973
|
-
* Base constraint for all plugin resolver objects.
|
|
974
|
-
*
|
|
975
|
-
* The built-in machinery lives under `default`. Generators call the top-level `name`, `file`,
|
|
976
|
-
* and `imports`, and a plugin overrides `name` and `file` to set its conventions. Extend with
|
|
977
|
-
* top-level helpers (`typeName`, …) and/or grouped namespaces (`query`, `schema`, …).
|
|
978
|
-
*
|
|
979
|
-
* @example Top-level helper
|
|
980
|
-
* ```ts
|
|
981
|
-
* type MyResolver = Resolver & {
|
|
982
|
-
* typeName(name: string): string
|
|
983
|
-
* }
|
|
984
|
-
* ```
|
|
985
|
-
*
|
|
986
|
-
* @example Grouped namespace
|
|
987
|
-
* ```ts
|
|
988
|
-
* type MyResolver = Resolver & {
|
|
989
|
-
* query: {
|
|
990
|
-
* name(node: OperationNode): string
|
|
991
|
-
* keyName(node: OperationNode): string
|
|
992
|
-
* }
|
|
993
|
-
* }
|
|
994
|
-
* ```
|
|
995
|
-
*/
|
|
996
|
-
var Resolver = class Resolver {
|
|
997
|
-
static #patternCache = /* @__PURE__ */ new Map();
|
|
998
|
-
static #optionsCache = /* @__PURE__ */ new WeakMap();
|
|
999
|
-
pluginName;
|
|
1000
|
-
/** The built-in machinery, untouched by `name`/`file` overrides and built once since the driver reads it per node. */
|
|
1001
|
-
default;
|
|
1002
|
-
#options;
|
|
1003
|
-
#baseName;
|
|
1004
|
-
#filePath;
|
|
1005
|
-
constructor(options) {
|
|
1006
|
-
this.pluginName = options.pluginName;
|
|
1007
|
-
this.#options = options;
|
|
1008
|
-
this.#baseName = options.file?.baseName ? options.file.baseName.bind(this) : toBaseName;
|
|
1009
|
-
this.#filePath = options.file?.path ? options.file.path.bind(this) : void 0;
|
|
1010
|
-
this.default = {
|
|
1011
|
-
name: require_nodeCache.camelCase,
|
|
1012
|
-
options: this.#resolveOptions.bind(this),
|
|
1013
|
-
path: this.#resolvePath.bind(this),
|
|
1014
|
-
file: this.#resolveFile.bind(this),
|
|
1015
|
-
banner: this.#resolveBanner.bind(this),
|
|
1016
|
-
footer: this.#resolveFooter.bind(this)
|
|
1017
|
-
};
|
|
1018
|
-
this.#apply(options);
|
|
1019
|
-
}
|
|
1020
|
-
/** Exposes the raw build options so `Resolver.merge` can read them across `@kubb/core` copies. */
|
|
1021
|
-
get [resolverOptions]() {
|
|
1022
|
-
return this.#options;
|
|
1023
|
-
}
|
|
1024
|
-
name(name) {
|
|
1025
|
-
return this.default.name(name);
|
|
1026
|
-
}
|
|
1027
|
-
file(options) {
|
|
1028
|
-
return this.#resolveFile(options);
|
|
1029
|
-
}
|
|
1030
|
-
/**
|
|
1031
|
-
* Builds one `ImportNode` per unique schema referenced in the tree, in first-occurrence
|
|
1032
|
-
* order. Each ref's target resolves through `resolveRefName`, so collision- or macro-renamed
|
|
1033
|
-
* schemas (`targetName`) import the emitted name. Names and paths go through the top-level
|
|
1034
|
-
* `name` and `file`, so import entries follow the plugin's conventions, and a per-call
|
|
1035
|
-
* `name` override wins over both.
|
|
1036
|
-
*
|
|
1037
|
-
* The subtree scan runs through `collectImportedRefNames`, which memoizes by node identity, so a
|
|
1038
|
-
* schema shared across the ts, zod, and faker plugins is walked once and every plugin's resolver
|
|
1039
|
-
* reads the same ref set instead of re-scanning it per plugin.
|
|
1040
|
-
*/
|
|
1041
|
-
imports(options) {
|
|
1042
|
-
const { node, root, output, group, extname = ".ts", name } = options;
|
|
1043
|
-
const resolveName = name ?? ((schemaName) => this.name(schemaName));
|
|
1044
|
-
return (0, _kubb_ast.collectImportedRefNames)(node).map((schemaName) => _kubb_ast.ast.factory.createImport({
|
|
1045
|
-
name: [resolveName(schemaName)],
|
|
1046
|
-
path: this.file({
|
|
1047
|
-
name: schemaName,
|
|
1048
|
-
extname,
|
|
1049
|
-
root,
|
|
1050
|
-
output,
|
|
1051
|
-
group
|
|
1052
|
-
}).path
|
|
1053
|
-
}));
|
|
1054
|
-
}
|
|
1055
|
-
/**
|
|
1056
|
-
* Folds each `override` over `base`, left to right, and returns a new resolver with helpers
|
|
1057
|
-
* re-bound. Top-level keys replace, and a namespace (or `file`) merges per method, so overriding
|
|
1058
|
-
* `query.name` keeps the base `query.keyName`. The last override wins per key. Used when applying
|
|
1059
|
-
* `setResolver` partial overrides, and to compose shared resolver fragments without spreading each
|
|
1060
|
-
* namespace by hand. Reads a resolver's options through the shared brand rather than `instanceof`,
|
|
1061
|
-
* so a `file` override survives even when `base` and `override` come from different `@kubb/core`
|
|
1062
|
-
* copies.
|
|
1063
|
-
*
|
|
1064
|
-
* @example Fold several partial overrides onto a resolver
|
|
1065
|
-
* ```ts
|
|
1066
|
-
* const resolver = Resolver.merge(defaultResolver, sharedNamingPatch, { name: (name) => name.toUpperCase() })
|
|
1067
|
-
* ```
|
|
1068
|
-
*/
|
|
1069
|
-
static merge(base, ...overrides) {
|
|
1070
|
-
const merged = overrides.reduce((acc, override) => {
|
|
1071
|
-
const patch = resolverOptions in override ? override[resolverOptions] : override;
|
|
1072
|
-
for (const [key, value] of Object.entries(patch)) {
|
|
1073
|
-
if (value === void 0) continue;
|
|
1074
|
-
const current = acc[key];
|
|
1075
|
-
acc[key] = isNamespace(value) && isNamespace(current) ? {
|
|
1076
|
-
...current,
|
|
1077
|
-
...value
|
|
1078
|
-
} : value;
|
|
1079
|
-
}
|
|
1080
|
-
return acc;
|
|
1081
|
-
}, { ...base[resolverOptions] });
|
|
1082
|
-
return new Resolver(merged);
|
|
1083
|
-
}
|
|
1084
|
-
/**
|
|
1085
|
-
* Binds each entry of `options` onto the resolver, so `this.name`, `this.default`, and
|
|
1086
|
-
* `this.file` resolve there for top-level helpers and namespace methods alike. `default`
|
|
1087
|
-
* is skipped so it can't be shadowed.
|
|
1088
|
-
*/
|
|
1089
|
-
#apply(options) {
|
|
1090
|
-
const root = this;
|
|
1091
|
-
const bind = (value) => typeof value === "function" ? value.bind(root) : value;
|
|
1092
|
-
for (const [key, value] of Object.entries(options)) {
|
|
1093
|
-
if (key === "pluginName" || key === "default" || key === "file" || value === void 0) continue;
|
|
1094
|
-
root[key] = isNamespace(value) ? Object.fromEntries(Object.entries(value).map(([method, member]) => [method, bind(member)])) : bind(value);
|
|
1095
|
-
}
|
|
1096
|
-
}
|
|
1097
|
-
static #testPattern(value, pattern) {
|
|
1098
|
-
if (typeof pattern === "string") {
|
|
1099
|
-
let regex = Resolver.#patternCache.get(pattern);
|
|
1100
|
-
regex ??= new RegExp(pattern);
|
|
1101
|
-
Resolver.#patternCache.set(pattern, regex);
|
|
1102
|
-
return regex.test(value);
|
|
1103
|
-
}
|
|
1104
|
-
return value.match(pattern) !== null;
|
|
1105
|
-
}
|
|
1106
|
-
static #matchesOperation(node, { type, pattern }) {
|
|
1107
|
-
if (type === "tag") return node.tags.some((tag) => Resolver.#testPattern(tag, pattern));
|
|
1108
|
-
if (type === "operationId") return Resolver.#testPattern(node.operationId, pattern);
|
|
1109
|
-
if (type === "path") return node.path !== void 0 && Resolver.#testPattern(node.path, pattern);
|
|
1110
|
-
if (type === "method") return node.method !== void 0 && Resolver.#testPattern(node.method.toLowerCase(), pattern);
|
|
1111
|
-
if (type === "contentType") return node.requestBody?.content?.some((c) => Resolver.#testPattern(c.contentType, pattern)) ?? false;
|
|
1112
|
-
return false;
|
|
1113
|
-
}
|
|
1114
|
-
/**
|
|
1115
|
-
* Returns `null` when the filter type doesn't apply to schemas, so include rules built
|
|
1116
|
-
* from operation filters (e.g. `tag`) don't exclude every schema.
|
|
1117
|
-
*/
|
|
1118
|
-
static #matchesSchema(node, { type, pattern }) {
|
|
1119
|
-
if (type === "schemaName") return node.name ? Resolver.#testPattern(node.name, pattern) : false;
|
|
1120
|
-
return null;
|
|
1121
|
-
}
|
|
1122
|
-
static #computeOptions(node, { options, exclude = [], include, override = [] }) {
|
|
1123
|
-
if (_kubb_ast.operationDef.is(node)) {
|
|
1124
|
-
if (exclude.some((filter) => Resolver.#matchesOperation(node, filter))) return null;
|
|
1125
|
-
if (include && !include.some((filter) => Resolver.#matchesOperation(node, filter))) return null;
|
|
1126
|
-
return {
|
|
1127
|
-
...options,
|
|
1128
|
-
...override.find((filter) => Resolver.#matchesOperation(node, filter))?.options
|
|
1129
|
-
};
|
|
1130
|
-
}
|
|
1131
|
-
if (_kubb_ast.schemaDef.is(node)) {
|
|
1132
|
-
if (exclude.some((filter) => Resolver.#matchesSchema(node, filter) === true)) return null;
|
|
1133
|
-
if (include) {
|
|
1134
|
-
const applicable = include.map((filter) => Resolver.#matchesSchema(node, filter)).filter((result) => result !== null);
|
|
1135
|
-
if (applicable.length > 0 && !applicable.includes(true)) return null;
|
|
1136
|
-
}
|
|
1137
|
-
return {
|
|
1138
|
-
...options,
|
|
1139
|
-
...override.find((filter) => Resolver.#matchesSchema(node, filter) === true)?.options
|
|
1140
|
-
};
|
|
1141
|
-
}
|
|
1142
|
-
return options;
|
|
1143
|
-
}
|
|
1144
|
-
/**
|
|
1145
|
-
* Applies include/exclude filters and merges matching override options, caching the result
|
|
1146
|
-
* per `(options, node)` pair. Returns `null` when the node is filtered out.
|
|
1147
|
-
*/
|
|
1148
|
-
#resolveOptions(node, context) {
|
|
1149
|
-
const { options } = context;
|
|
1150
|
-
if (typeof options !== "object" || options === null) return Resolver.#computeOptions(node, context);
|
|
1151
|
-
let byOptions = Resolver.#optionsCache.get(options);
|
|
1152
|
-
if (!byOptions) {
|
|
1153
|
-
byOptions = /* @__PURE__ */ new WeakMap();
|
|
1154
|
-
Resolver.#optionsCache.set(options, byOptions);
|
|
1155
|
-
}
|
|
1156
|
-
const cached = byOptions.get(node);
|
|
1157
|
-
if (cached) return cached.value;
|
|
1158
|
-
const result = Resolver.#computeOptions(node, context);
|
|
1159
|
-
byOptions.set(node, { value: result });
|
|
1160
|
-
return result;
|
|
1161
|
-
}
|
|
1162
|
-
/**
|
|
1163
|
-
* A custom `group.name` wins; otherwise `tag` groups use the camelCased tag and `path`
|
|
1164
|
-
* groups use the first non-traversal segment (`''` when none remain, placing the file in
|
|
1165
|
-
* the output root, kept safe by the caller's boundary check).
|
|
1166
|
-
*/
|
|
1167
|
-
static #resolveGroupDir(group, groupValue) {
|
|
1168
|
-
if (group.name) return group.name({ group: groupValue });
|
|
1169
|
-
if (group.type === "tag") return require_nodeCache.camelCase(groupValue);
|
|
1170
|
-
const segment = groupValue.split("/").filter((part) => part !== "" && part !== "." && part !== "..")[0];
|
|
1171
|
-
return segment ? require_nodeCache.camelCase(segment) : "";
|
|
1172
|
-
}
|
|
1173
|
-
/**
|
|
1174
|
-
* `mode: 'file'` (default) resolves directly to `output.path`. `mode: 'directory'` resolves
|
|
1175
|
-
* to `output.path/{baseName}`, or into a subdirectory when `group` and a `tag`/`path` value
|
|
1176
|
-
* are provided.
|
|
1177
|
-
*/
|
|
1178
|
-
#resolvePath({ baseName, tag, path: groupPath, root, output, group }) {
|
|
1179
|
-
if (output.mode !== "directory") return node_path.default.resolve(root, output.path);
|
|
1180
|
-
const outputDir = node_path.default.resolve(root, output.path);
|
|
1181
|
-
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);
|
|
1182
|
-
assertInside({
|
|
1183
|
-
target: result,
|
|
1184
|
-
parent: outputDir,
|
|
1185
|
-
message: `Resolved path "${result}" is outside the output directory "${outputDir}".`,
|
|
1186
|
-
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."
|
|
1187
|
-
});
|
|
1188
|
-
return result;
|
|
1189
|
-
}
|
|
1190
|
-
/**
|
|
1191
|
-
* Resolves a resolver-supplied full path (`file.path`) against `root`, bypassing `output.path`
|
|
1192
|
-
* and `group`. The path may not escape `root`, which keeps a `file.path` that interpolates
|
|
1193
|
-
* spec-derived values from writing outside the project.
|
|
1194
|
-
*/
|
|
1195
|
-
#resolveOverridePath(filePath, root) {
|
|
1196
|
-
const resolved = node_path.default.resolve(root, filePath);
|
|
1197
|
-
assertInside({
|
|
1198
|
-
target: resolved,
|
|
1199
|
-
parent: root,
|
|
1200
|
-
message: `Resolved path "${resolved}" is outside the project root "${root}".`,
|
|
1201
|
-
help: "A resolver `file.path` must return a path inside the project root."
|
|
1202
|
-
});
|
|
1203
|
-
return resolved;
|
|
1204
|
-
}
|
|
1205
|
-
/**
|
|
1206
|
-
* Builds a `FileNode`. When `#filePath` (the resolver's `file.path`) is set it owns the whole
|
|
1207
|
-
* path; otherwise the base name (from `#baseName`, the resolver's `file.baseName` or the
|
|
1208
|
-
* built-in `toBaseName`) is placed by the `output.path`/`group` layout. The resolved file starts
|
|
1209
|
-
* with empty `sources`, `imports`, and `exports`, which consumers populate separately.
|
|
1210
|
-
*/
|
|
1211
|
-
#resolveFile(options) {
|
|
1212
|
-
const { name, extname, tag, path: groupPath, root, output, group } = options;
|
|
1213
|
-
const baseName = this.#baseName({
|
|
1214
|
-
name,
|
|
1215
|
-
extname
|
|
1216
|
-
});
|
|
1217
|
-
const filePath = this.#filePath ? this.#resolveOverridePath(this.#filePath({
|
|
1218
|
-
baseName,
|
|
1219
|
-
output
|
|
1220
|
-
}), root) : this.#resolvePath({
|
|
1221
|
-
baseName,
|
|
1222
|
-
tag,
|
|
1223
|
-
path: groupPath,
|
|
1224
|
-
root,
|
|
1225
|
-
output,
|
|
1226
|
-
group
|
|
1227
|
-
});
|
|
1228
|
-
return _kubb_ast.ast.factory.createFile({
|
|
1229
|
-
path: filePath,
|
|
1230
|
-
baseName: node_path.default.basename(filePath),
|
|
1231
|
-
meta: { pluginName: this.pluginName },
|
|
1232
|
-
sources: [],
|
|
1233
|
-
imports: [],
|
|
1234
|
-
exports: []
|
|
1235
|
-
});
|
|
1236
|
-
}
|
|
1237
|
-
/**
|
|
1238
|
-
* Missing fields default to empty/`false` so the `BannerMeta` shape stays stable even when
|
|
1239
|
-
* a caller (e.g. the barrel plugin) has no document metadata.
|
|
1240
|
-
*/
|
|
1241
|
-
static #buildBannerMeta(meta, file) {
|
|
1242
|
-
return {
|
|
1243
|
-
title: meta?.title,
|
|
1244
|
-
description: meta?.description,
|
|
1245
|
-
version: meta?.version,
|
|
1246
|
-
baseURL: meta?.baseURL,
|
|
1247
|
-
circularNames: meta?.circularNames ?? [],
|
|
1248
|
-
enumNames: meta?.enumNames ?? [],
|
|
1249
|
-
filePath: file?.path ?? "",
|
|
1250
|
-
baseName: file?.baseName ?? "",
|
|
1251
|
-
isBarrel: file?.isBarrel ?? false,
|
|
1252
|
-
isAggregation: file?.isAggregation ?? false
|
|
1253
|
-
};
|
|
1254
|
-
}
|
|
1255
|
-
/**
|
|
1256
|
-
* Resolves a user-configured banner/footer value. `undefined` means not configured.
|
|
1257
|
-
*/
|
|
1258
|
-
static #resolveUserText(value, meta, file) {
|
|
1259
|
-
if (typeof value === "function") return value(Resolver.#buildBannerMeta(meta, file));
|
|
1260
|
-
if (typeof value === "string") return value;
|
|
1261
|
-
}
|
|
1262
|
-
static #buildDefaultBanner({ title, version, config }) {
|
|
1263
|
-
const lines = [
|
|
1264
|
-
"/**",
|
|
1265
|
-
"* Generated by Kubb (https://kubb.dev/).",
|
|
1266
|
-
"* Do not edit manually."
|
|
1267
|
-
];
|
|
1268
|
-
if (config.output.defaultBanner !== "simple") {
|
|
1269
|
-
const input = config.input;
|
|
1270
|
-
const source = typeof input === "string" ? getInputKind(input) === "inline" ? "text content" : node_path.default.basename(input) : input ? "text content" : "";
|
|
1271
|
-
if (source) lines.push(`* Source: ${source}`);
|
|
1272
|
-
if (title) lines.push(`* Title: ${title}`);
|
|
1273
|
-
if (version) lines.push(`* OpenAPI spec version: ${version}`);
|
|
1274
|
-
}
|
|
1275
|
-
return `${lines.join("\n")}\n*/\n`;
|
|
1276
|
-
}
|
|
1277
|
-
/**
|
|
1278
|
-
* A user-supplied `output.banner` overrides the default Kubb notice. When
|
|
1279
|
-
* `config.output.defaultBanner` is `false` and no user banner is set, returns `null`.
|
|
1280
|
-
*/
|
|
1281
|
-
#resolveBanner(meta, { output, config, file }) {
|
|
1282
|
-
const userBanner = Resolver.#resolveUserText(output?.banner, meta, file);
|
|
1283
|
-
if (userBanner !== void 0) return userBanner;
|
|
1284
|
-
if (config.output.defaultBanner === false) return null;
|
|
1285
|
-
return Resolver.#buildDefaultBanner({
|
|
1286
|
-
title: meta?.title,
|
|
1287
|
-
version: meta?.version,
|
|
1288
|
-
config
|
|
1289
|
-
});
|
|
1290
|
-
}
|
|
1291
|
-
#resolveFooter(meta, { output, file }) {
|
|
1292
|
-
return Resolver.#resolveUserText(output?.footer, meta, file) ?? null;
|
|
1293
|
-
}
|
|
1294
|
-
};
|
|
1295
|
-
//#endregion
|
|
1296
|
-
//#region src/createResolver.ts
|
|
1297
|
-
/**
|
|
1298
|
-
* Defines a plugin resolver, the object that decides what every generated symbol and file
|
|
1299
|
-
* path is called. Override the top-level `name` and `file` to set the plugin's conventions,
|
|
1300
|
-
* and add your own naming helpers, top-level (`typeName`, …) or grouped in namespaces
|
|
1301
|
-
* (`query`, `schema`, …). Every method reaches sibling helpers and the built-in machinery
|
|
1302
|
-
* through `this.name`, `this.file`, and `this.default`.
|
|
1303
|
-
*
|
|
1304
|
-
* @example Custom identifier casing
|
|
1305
|
-
* ```ts
|
|
1306
|
-
* export const resolverTs = createResolver<PluginTs>({
|
|
1307
|
-
* pluginName: 'plugin-ts',
|
|
1308
|
-
* name(name) {
|
|
1309
|
-
* return ensureValidVarName(pascalCase(name))
|
|
1310
|
-
* },
|
|
1311
|
-
* })
|
|
1312
|
-
* ```
|
|
1313
|
-
*
|
|
1314
|
-
* @example Rename generated files with `file.baseName`
|
|
1315
|
-
* ```ts
|
|
1316
|
-
* export const resolverFaker = createResolver<PluginFaker>({
|
|
1317
|
-
* pluginName: 'plugin-faker',
|
|
1318
|
-
* name(name) {
|
|
1319
|
-
* return camelCase(name, { prefix: 'create' })
|
|
1320
|
-
* },
|
|
1321
|
-
* file: {
|
|
1322
|
-
* baseName({ name, extname }) {
|
|
1323
|
-
* return `${camelCase(name, { prefix: 'create' })}${extname}`
|
|
1324
|
-
* },
|
|
1325
|
-
* },
|
|
1326
|
-
* })
|
|
1327
|
-
* ```
|
|
1328
|
-
*
|
|
1329
|
-
* @example Own the full path with `file.path`
|
|
1330
|
-
* ```ts
|
|
1331
|
-
* export const resolverFaker = createResolver<PluginFaker>({
|
|
1332
|
-
* pluginName: 'plugin-faker',
|
|
1333
|
-
* file: {
|
|
1334
|
-
* path({ baseName, output }) {
|
|
1335
|
-
* return `${output.path}/mocks/${baseName}`
|
|
1336
|
-
* },
|
|
1337
|
-
* },
|
|
1338
|
-
* })
|
|
1339
|
-
* ```
|
|
1340
|
-
*/
|
|
1341
|
-
function createResolver(options) {
|
|
1342
|
-
return new Resolver(options);
|
|
1343
|
-
}
|
|
1344
|
-
//#endregion
|
|
1345
|
-
//#region src/Transform.ts
|
|
1346
|
-
/**
|
|
1347
|
-
* Holds an ordered list of macros per plugin, keyed by plugin name. Each plugin's macros run in
|
|
1348
|
-
* isolation on the original adapter node and are composed into a single `Visitor` that the
|
|
1349
|
-
* `@kubb/ast` `transform` primitive applies. `applyTo` is a per-plugin lookup, not a cross-plugin
|
|
1350
|
-
* chain, so plugin A's macros never see plugin B's output. When a plugin has no macros, `applyTo`
|
|
1351
|
-
* returns the original node reference, and `transform` does the same when the composed visitor
|
|
1352
|
-
* leaves the tree untouched, so callers can detect a no-op by identity.
|
|
1353
|
-
*
|
|
1354
|
-
* Registration order matches the order setup hooks fire, which the driver has already sorted by
|
|
1355
|
-
* `enforce` and dependency edges. The registry preserves that order. Macro `enforce` only reorders
|
|
1356
|
-
* within a single plugin's list.
|
|
1357
|
-
*/
|
|
1358
|
-
var Transform = class {
|
|
1359
|
-
#macros = /* @__PURE__ */ new Map();
|
|
1360
|
-
#composed = /* @__PURE__ */ new Map();
|
|
1361
|
-
#memo = /* @__PURE__ */ new Map();
|
|
1362
|
-
/**
|
|
1363
|
-
* Appends `macro` to the plugin's list, after any macros already registered.
|
|
1364
|
-
*/
|
|
1365
|
-
add(pluginName, macro) {
|
|
1366
|
-
const list = this.#macros.get(pluginName);
|
|
1367
|
-
if (list) list.push(macro);
|
|
1368
|
-
else this.#macros.set(pluginName, [macro]);
|
|
1369
|
-
this.#invalidate(pluginName);
|
|
1370
|
-
}
|
|
1371
|
-
/**
|
|
1372
|
-
* Replaces the plugin's macro list with `macros`.
|
|
1373
|
-
*/
|
|
1374
|
-
set(pluginName, macros) {
|
|
1375
|
-
this.#macros.set(pluginName, [...macros]);
|
|
1376
|
-
this.#invalidate(pluginName);
|
|
1377
|
-
}
|
|
1378
|
-
/**
|
|
1379
|
-
* Runs the plugin's macros on `node`. Returns the original node reference when the plugin has no
|
|
1380
|
-
* macros, so callers can compare by identity to detect a no-op.
|
|
1381
|
-
*/
|
|
1382
|
-
applyTo(pluginName, node) {
|
|
1383
|
-
const visitor = this.#visitorFor(pluginName);
|
|
1384
|
-
if (!visitor) return node;
|
|
1385
|
-
let memo = this.#memo.get(pluginName);
|
|
1386
|
-
if (!memo) {
|
|
1387
|
-
memo = /* @__PURE__ */ new WeakMap();
|
|
1388
|
-
this.#memo.set(pluginName, memo);
|
|
1389
|
-
}
|
|
1390
|
-
const cached = memo.get(node);
|
|
1391
|
-
if (cached) return cached;
|
|
1392
|
-
const result = (0, _kubb_ast.transform)(node, visitor);
|
|
1393
|
-
memo.set(node, result);
|
|
1394
|
-
return result;
|
|
1395
|
-
}
|
|
1396
|
-
/**
|
|
1397
|
-
* Clears every registration. Called from the driver's `dispose()` so macros do not leak across
|
|
1398
|
-
* builds.
|
|
1399
|
-
*/
|
|
1400
|
-
dispose() {
|
|
1401
|
-
this.#macros.clear();
|
|
1402
|
-
this.#composed.clear();
|
|
1403
|
-
this.#memo.clear();
|
|
1404
|
-
}
|
|
1405
|
-
#invalidate(pluginName) {
|
|
1406
|
-
this.#composed.delete(pluginName);
|
|
1407
|
-
this.#memo.delete(pluginName);
|
|
1408
|
-
}
|
|
1409
|
-
#visitorFor(pluginName) {
|
|
1410
|
-
const macros = this.#macros.get(pluginName);
|
|
1411
|
-
if (!macros || macros.length === 0) return void 0;
|
|
1412
|
-
let composed = this.#composed.get(pluginName);
|
|
1413
|
-
if (!composed) {
|
|
1414
|
-
composed = (0, _kubb_ast.composeMacros)(macros);
|
|
1415
|
-
this.#composed.set(pluginName, composed);
|
|
1416
|
-
}
|
|
1417
|
-
return composed;
|
|
1418
|
-
}
|
|
1419
|
-
};
|
|
1420
|
-
//#endregion
|
|
1421
|
-
//#region src/KubbDriver.ts
|
|
1422
|
-
const ENFORCE_ORDER = {
|
|
1423
|
-
pre: -1,
|
|
1424
|
-
post: 1
|
|
1425
|
-
};
|
|
1426
|
-
/** `include` filter types that select operations, and so prune the schemas they do not reach. */
|
|
1427
|
-
const OPERATION_FILTER_TYPES = /* @__PURE__ */ new Set([
|
|
1428
|
-
"tag",
|
|
1429
|
-
"operationId",
|
|
1430
|
-
"path",
|
|
1431
|
-
"method",
|
|
1432
|
-
"contentType"
|
|
1433
|
-
]);
|
|
1434
|
-
const enforceWeight = (plugin) => plugin.enforce ? ENFORCE_ORDER[plugin.enforce] : 0;
|
|
1435
|
-
/**
|
|
1436
|
-
* The options bag a `NormalizedPlugin` starts with before a plugin refines it: a directory output
|
|
1437
|
-
* at the plugin root and empty filter lists.
|
|
1438
|
-
*/
|
|
1439
|
-
const defaultPluginOptions = () => ({
|
|
1440
|
-
output: {
|
|
1441
|
-
path: ".",
|
|
1442
|
-
mode: "directory"
|
|
1443
|
-
},
|
|
1444
|
-
exclude: [],
|
|
1445
|
-
override: []
|
|
1446
|
-
});
|
|
1447
|
-
/**
|
|
1448
|
-
* Fills in the `output`, `exclude`, and `override` a `NormalizedPlugin` needs from a plugin's raw
|
|
1449
|
-
* options, running `output` through `normalizeOutput`. Idempotent, so the driver can apply it after
|
|
1450
|
-
* `setOptions` has already run without disturbing an already-normalized bag.
|
|
1451
|
-
*/
|
|
1452
|
-
function normalizePluginOptions(rawOptions, pluginName) {
|
|
1453
|
-
const options = {
|
|
1454
|
-
...defaultPluginOptions(),
|
|
1455
|
-
...rawOptions ?? {}
|
|
1456
|
-
};
|
|
1457
|
-
const group = "group" in options ? options.group : void 0;
|
|
1458
|
-
options.output = normalizeOutput({
|
|
1459
|
-
output: options.output,
|
|
1460
|
-
group,
|
|
1461
|
-
pluginName
|
|
1462
|
-
});
|
|
1463
|
-
return options;
|
|
1464
|
-
}
|
|
1465
|
-
var KubbDriver = class {
|
|
1466
|
-
config;
|
|
1467
|
-
options;
|
|
1468
|
-
/**
|
|
1469
|
-
* The `InputNode` produced by the adapter. Set after adapter setup.
|
|
1470
|
-
*/
|
|
1471
|
-
inputNode = null;
|
|
1472
|
-
adapter = null;
|
|
1473
|
-
/**
|
|
1474
|
-
* Raw adapter source so `adapter.parse()` can run lazily.
|
|
1475
|
-
* Intentionally outlives the build, cleared by `dispose()`.
|
|
1476
|
-
*/
|
|
1477
|
-
#adapterSource = null;
|
|
1478
|
-
/**
|
|
1479
|
-
* Central file store for all generated files.
|
|
1480
|
-
* Plugins should use `this.addFile()` / `this.upsertFile()` (via their context) to
|
|
1481
|
-
* add files. This property gives direct read/write access when needed.
|
|
1482
|
-
*/
|
|
1483
|
-
fileManager = new require_nodeCache.FileManager();
|
|
1484
|
-
plugins = /* @__PURE__ */ new Map();
|
|
1485
|
-
/**
|
|
1486
|
-
* Removers for every listener the driver added (plugin, generator) so `dispose()` can detach
|
|
1487
|
-
* them in one pass. External `hooks.hook(...)` listeners are not tracked.
|
|
1488
|
-
*/
|
|
1489
|
-
#unhooks = [];
|
|
1490
|
-
/**
|
|
1491
|
-
* Transform registry. Plugins populate it during `kubb:plugin:setup` via `addMacro`/`setMacros`,
|
|
1492
|
-
* and `#runGenerators` reads it once per `(plugin, node)` pair through `applyTo`.
|
|
1493
|
-
*/
|
|
1494
|
-
#transforms = new Transform();
|
|
1495
|
-
constructor(config, options) {
|
|
1496
|
-
this.config = config;
|
|
1497
|
-
this.options = options;
|
|
1498
|
-
this.adapter = config.adapter ?? null;
|
|
1499
|
-
}
|
|
1500
|
-
/**
|
|
1501
|
-
* Normalizes every configured plugin, orders them, and registers their lifecycle handlers.
|
|
1502
|
-
* A plugin that another lists as a dependency runs first, then `enforce: 'pre'` before
|
|
1503
|
-
* `'post'`. When the config has an adapter, the adapter source is resolved from the input
|
|
1504
|
-
* so `run` can parse it later.
|
|
1505
|
-
*/
|
|
1506
|
-
async setup() {
|
|
1507
|
-
this.options.signal?.throwIfAborted();
|
|
1508
|
-
const normalized = this.#sortPlugins(this.config.plugins.map((rawPlugin) => {
|
|
1509
|
-
return {
|
|
1510
|
-
name: rawPlugin.name,
|
|
1511
|
-
dependencies: rawPlugin.dependencies,
|
|
1512
|
-
enforce: rawPlugin.enforce,
|
|
1513
|
-
hooks: rawPlugin.hooks,
|
|
1514
|
-
options: rawPlugin.options ?? defaultPluginOptions(),
|
|
1515
|
-
resolver: createResolver({ pluginName: rawPlugin.name })
|
|
1516
|
-
};
|
|
1517
|
-
}));
|
|
1518
|
-
for (const plugin of normalized) {
|
|
1519
|
-
this.#registerPlugin(plugin);
|
|
1520
|
-
this.plugins.set(plugin.name, plugin);
|
|
1521
|
-
}
|
|
1522
|
-
if (this.config.adapter) this.#adapterSource = inputToAdapterSource(this.config);
|
|
1523
|
-
}
|
|
1524
|
-
/**
|
|
1525
|
-
* Orders plugins so every dependency runs before its dependents (Kahn's algorithm), with
|
|
1526
|
-
* `enforce` (`'pre'` before normal before `'post'`) and declaration order as tiebreaks.
|
|
1527
|
-
* A pairwise `Array.sort` comparator cannot do this: dependency relations are not transitive
|
|
1528
|
-
* at the comparator level, so a chain where A depends on B and B depends on C could come out
|
|
1529
|
-
* wrong when A and C are never compared directly. Dependencies on plugins missing from the
|
|
1530
|
-
* config are ignored here and surface later through `requirePlugin`.
|
|
1531
|
-
*/
|
|
1532
|
-
#sortPlugins(plugins) {
|
|
1533
|
-
const queue = [...plugins].sort((a, b) => enforceWeight(a) - enforceWeight(b));
|
|
1534
|
-
const names = new Set(queue.map((plugin) => plugin.name));
|
|
1535
|
-
const blockedBy = new Map(queue.map((plugin) => [plugin.name, new Set(plugin.dependencies?.filter((name) => names.has(name) && name !== plugin.name))]));
|
|
1536
|
-
const sorted = [];
|
|
1537
|
-
for (const _ of plugins) {
|
|
1538
|
-
const index = queue.findIndex((plugin) => blockedBy.get(plugin.name)?.size === 0);
|
|
1539
|
-
if (index === -1) throw new Diagnostics.Error({
|
|
1540
|
-
code: Diagnostics.code.invalidPluginOptions,
|
|
1541
|
-
severity: "error",
|
|
1542
|
-
message: `Plugin dependencies form a cycle: ${queue.map((plugin) => plugin.name).join(" → ")}.`,
|
|
1543
|
-
help: "Remove one of the `dependencies` entries so the plugins can be ordered.",
|
|
1544
|
-
location: { kind: "config" }
|
|
1545
|
-
});
|
|
1546
|
-
const [plugin] = queue.splice(index, 1);
|
|
1547
|
-
if (!plugin) break;
|
|
1548
|
-
sorted.push(plugin);
|
|
1549
|
-
for (const blockers of blockedBy.values()) blockers.delete(plugin.name);
|
|
1550
|
-
}
|
|
1551
|
-
return sorted;
|
|
1552
|
-
}
|
|
1553
|
-
get hooks() {
|
|
1554
|
-
return this.options.hooks;
|
|
1555
|
-
}
|
|
1556
|
-
/**
|
|
1557
|
-
* Parses the adapter source into `this.inputNode`. Idempotent, so repeated calls from
|
|
1558
|
-
* `run` do not re-parse.
|
|
1559
|
-
*/
|
|
1560
|
-
async #parseInput() {
|
|
1561
|
-
if (this.inputNode || !this.adapter || !this.#adapterSource) return;
|
|
1562
|
-
this.options.signal?.throwIfAborted();
|
|
1563
|
-
this.inputNode = await this.adapter.parse(this.#adapterSource, { signal: this.options.signal });
|
|
1564
|
-
}
|
|
1565
|
-
/**
|
|
1566
|
-
* Registers a plugin's lifecycle hooks on the shared `Hookable` as pass-through listeners that
|
|
1567
|
-
* external tooling can observe via `hooks.hook(...)`. The returned remover is tracked for
|
|
1568
|
-
* `dispose`. `kubb:plugin:setup` is skipped here; `setupHooks` invokes it directly with a
|
|
1569
|
-
* plugin-scoped context.
|
|
1570
|
-
*
|
|
1571
|
-
* @internal
|
|
1572
|
-
*/
|
|
1573
|
-
#registerPlugin(plugin) {
|
|
1574
|
-
const { hooks } = plugin;
|
|
1575
|
-
if (!hooks) return;
|
|
1576
|
-
const { "kubb:plugin:setup": _setup, ...configHooks } = hooks;
|
|
1577
|
-
this.#unhooks.push(this.hooks.addHooks(configHooks));
|
|
1578
|
-
}
|
|
1579
|
-
/**
|
|
1580
|
-
* Runs each plugin's `kubb:plugin:setup` handler, in plugin order, with a context scoped to that
|
|
1581
|
-
* plugin so `addGenerator`, `setResolver`, `addMacro`, `setMacros`, and `setOptions` target its
|
|
1582
|
-
* `NormalizedPlugin` entry. Called once from `run` before the plugin execution loop begins, so
|
|
1583
|
-
* plugins can configure generators, resolvers, macros, and options before `buildStart`.
|
|
1584
|
-
*/
|
|
1585
|
-
async setupHooks() {
|
|
1586
|
-
for (const plugin of this.plugins.values()) {
|
|
1587
|
-
const setup = plugin.hooks?.["kubb:plugin:setup"];
|
|
1588
|
-
if (!setup) continue;
|
|
1589
|
-
await setup({
|
|
1590
|
-
config: this.config,
|
|
1591
|
-
options: plugin.options ?? {},
|
|
1592
|
-
addGenerator: (...generators) => {
|
|
1593
|
-
plugin.generators = [...plugin.generators ?? [], ...generators];
|
|
1594
|
-
},
|
|
1595
|
-
setResolver: (resolver) => {
|
|
1596
|
-
plugin.resolver = Resolver.merge(createResolver({ pluginName: plugin.name }), resolver);
|
|
1597
|
-
},
|
|
1598
|
-
addMacro: (macro) => {
|
|
1599
|
-
this.#transforms.add(plugin.name, macro);
|
|
1600
|
-
},
|
|
1601
|
-
setMacros: (macros) => {
|
|
1602
|
-
this.#transforms.set(plugin.name, macros);
|
|
1603
|
-
},
|
|
1604
|
-
setOptions: (opts) => {
|
|
1605
|
-
plugin.options = normalizePluginOptions({
|
|
1606
|
-
...plugin.options,
|
|
1607
|
-
...opts
|
|
1608
|
-
}, plugin.name);
|
|
1609
|
-
},
|
|
1610
|
-
injectFile: (userFileNode) => {
|
|
1611
|
-
this.fileManager.add(_kubb_ast.ast.factory.createFile(userFileNode));
|
|
1612
|
-
}
|
|
1613
|
-
});
|
|
1614
|
-
}
|
|
1615
|
-
}
|
|
1616
|
-
/** `true` once `addGenerator()` in `kubb:plugin:setup` registered a generator for the plugin. */
|
|
1617
|
-
hasHookGenerators(pluginName) {
|
|
1618
|
-
return (this.plugins.get(pluginName)?.generators?.length ?? 0) > 0;
|
|
1619
|
-
}
|
|
1620
|
-
/**
|
|
1621
|
-
* Runs the full plugin pipeline. Returns the diagnostics collected so far even
|
|
1622
|
-
* when an outer hook throws, since the orchestrator preserves partial state by capturing
|
|
1623
|
-
* the failure as a {@link Diagnostic} instead of propagating. Each plugin also
|
|
1624
|
-
* contributes a `timing` diagnostic for the run summary.
|
|
1625
|
-
*/
|
|
1626
|
-
async run() {
|
|
1627
|
-
const { hooks, config, fileManager } = this;
|
|
1628
|
-
const diagnostics = [];
|
|
1629
|
-
const parsersMap = /* @__PURE__ */ new Map();
|
|
1630
|
-
for (const parser of config.parsers) if (parser.extNames) for (const ext of parser.extNames) parsersMap.set(ext, parser);
|
|
1631
|
-
const updateBuffer = [];
|
|
1632
|
-
const unhookWrites = fileManager.hooks.addHooks({
|
|
1633
|
-
start: async (files) => {
|
|
1634
|
-
await hooks.callHook("kubb:files:processing:start", { files });
|
|
1635
|
-
},
|
|
1636
|
-
update: ({ file, processed, total, percentage }) => {
|
|
1637
|
-
updateBuffer.push({
|
|
1638
|
-
file,
|
|
1639
|
-
processed,
|
|
1640
|
-
total,
|
|
1641
|
-
percentage,
|
|
1642
|
-
config
|
|
1643
|
-
});
|
|
1644
|
-
},
|
|
1645
|
-
end: async (files) => {
|
|
1646
|
-
updateBuffer.sort((a, b) => a.processed - b.processed);
|
|
1647
|
-
await hooks.callHook("kubb:files:processing:update", { files: updateBuffer });
|
|
1648
|
-
updateBuffer.length = 0;
|
|
1649
|
-
await hooks.callHook("kubb:files:processing:end", { files });
|
|
1650
|
-
}
|
|
1651
|
-
});
|
|
1652
|
-
return Diagnostics.scope((diagnostic) => diagnostics.push(diagnostic), async () => {
|
|
1653
|
-
try {
|
|
1654
|
-
this.options.signal?.throwIfAborted();
|
|
1655
|
-
const outputRoot = (0, node_path.resolve)(config.root, config.output.path);
|
|
1656
|
-
await this.#parseInput();
|
|
1657
|
-
await this.setupHooks();
|
|
1658
|
-
for (const plugin of this.plugins.values()) {
|
|
1659
|
-
this.options.signal?.throwIfAborted();
|
|
1660
|
-
plugin.options = normalizePluginOptions(plugin.options, plugin.name);
|
|
1661
|
-
}
|
|
1662
|
-
if (this.adapter && this.inputNode) {
|
|
1663
|
-
const buildStartContext = this.#withFiles({
|
|
1664
|
-
config,
|
|
1665
|
-
adapter: this.adapter,
|
|
1666
|
-
meta: this.inputNode.meta,
|
|
1667
|
-
getPlugin: this.getPlugin.bind(this)
|
|
1668
|
-
});
|
|
1669
|
-
await hooks.callHook("kubb:build:start", buildStartContext);
|
|
1670
|
-
}
|
|
1671
|
-
const generatorPlugins = [];
|
|
1672
|
-
for (const plugin of this.plugins.values()) {
|
|
1673
|
-
const context = this.getContext(plugin);
|
|
1674
|
-
const hrStart = process.hrtime();
|
|
1675
|
-
try {
|
|
1676
|
-
await hooks.callHook("kubb:plugin:start", { plugin });
|
|
1677
|
-
} catch (caughtError) {
|
|
1678
|
-
const error = require_nodeCache.toError(caughtError);
|
|
1679
|
-
const duration = getElapsedMs(hrStart);
|
|
1680
|
-
await this.#emitPluginEnd({
|
|
1681
|
-
plugin,
|
|
1682
|
-
duration,
|
|
1683
|
-
success: false,
|
|
1684
|
-
error
|
|
1685
|
-
});
|
|
1686
|
-
diagnostics.push({
|
|
1687
|
-
...Diagnostics.from(error),
|
|
1688
|
-
plugin: plugin.name
|
|
1689
|
-
}, Diagnostics.performance({
|
|
1690
|
-
plugin: plugin.name,
|
|
1691
|
-
duration
|
|
1692
|
-
}));
|
|
1693
|
-
continue;
|
|
1694
|
-
}
|
|
1695
|
-
if (this.hasHookGenerators(plugin.name)) {
|
|
1696
|
-
generatorPlugins.push({
|
|
1697
|
-
plugin,
|
|
1698
|
-
context,
|
|
1699
|
-
hrStart
|
|
1700
|
-
});
|
|
1701
|
-
continue;
|
|
1702
|
-
}
|
|
1703
|
-
const duration = getElapsedMs(hrStart);
|
|
1704
|
-
diagnostics.push(Diagnostics.performance({
|
|
1705
|
-
plugin: plugin.name,
|
|
1706
|
-
duration
|
|
1707
|
-
}));
|
|
1708
|
-
await this.#emitPluginEnd({
|
|
1709
|
-
plugin,
|
|
1710
|
-
duration,
|
|
1711
|
-
success: true
|
|
1712
|
-
});
|
|
1713
|
-
}
|
|
1714
|
-
diagnostics.push(...await this.#runGenerators(generatorPlugins));
|
|
1715
|
-
await hooks.callHook("kubb:plugins:end", this.#withFiles({ config }));
|
|
1716
|
-
await fileManager.write(fileManager.files, {
|
|
1717
|
-
storage: config.storage,
|
|
1718
|
-
parsers: parsersMap,
|
|
1719
|
-
manifest: this.options.manifest,
|
|
1720
|
-
signal: this.options.signal
|
|
1721
|
-
});
|
|
1722
|
-
await hooks.callHook("kubb:build:end", {
|
|
1723
|
-
files: this.fileManager.files,
|
|
1724
|
-
config,
|
|
1725
|
-
outputDir: outputRoot
|
|
1726
|
-
});
|
|
1727
|
-
return { diagnostics: Diagnostics.dedupe(diagnostics) };
|
|
1728
|
-
} catch (caughtError) {
|
|
1729
|
-
diagnostics.push(Diagnostics.from(caughtError));
|
|
1730
|
-
return { diagnostics: Diagnostics.dedupe(diagnostics) };
|
|
1731
|
-
} finally {
|
|
1732
|
-
unhookWrites();
|
|
1733
|
-
}
|
|
1734
|
-
});
|
|
1735
|
-
}
|
|
1736
|
-
/**
|
|
1737
|
-
* Widens `extra` with the files present at emit time and a bound `upsertFile`, the shape every
|
|
1738
|
-
* file-carrying hook context shares. Building it here in one place keeps the `files` and
|
|
1739
|
-
* `upsertFile` keys from being dropped by a stray spread at the call site.
|
|
1740
|
-
*/
|
|
1741
|
-
#withFiles(extra) {
|
|
1742
|
-
return {
|
|
1743
|
-
...extra,
|
|
1744
|
-
files: this.fileManager.files,
|
|
1745
|
-
upsertFile: (...files) => this.fileManager.upsert(...files)
|
|
1746
|
-
};
|
|
1747
|
-
}
|
|
1748
|
-
#emitPluginEnd({ plugin, duration, success, error }) {
|
|
1749
|
-
return this.hooks.callHook("kubb:plugin:end", this.#withFiles({
|
|
1750
|
-
plugin,
|
|
1751
|
-
duration,
|
|
1752
|
-
success,
|
|
1753
|
-
...error ? { error } : {},
|
|
1754
|
-
config: this.config
|
|
1755
|
-
}));
|
|
1756
|
-
}
|
|
1757
|
-
/**
|
|
1758
|
-
* Runs schemas and operations through every plugin's generators. The walk is node-outer: each
|
|
1759
|
-
* schema is visited once and each operation once, and the node fans out to the matching
|
|
1760
|
-
* generators of every plugin in dependency order. A per-node cache (`createNodeCache`) is created
|
|
1761
|
-
* once per node and shared by all of that node's plugins, so node-derived work is computed once
|
|
1762
|
-
* and reused instead of recomputed per plugin. Each node still runs through the plugin's macros
|
|
1763
|
-
* (from `this.#transforms`) and its exclude/include/override filters before that plugin's
|
|
1764
|
-
* generator sees it, so plugins stay isolated. Schemas run before operations so file output
|
|
1765
|
-
* stays deterministic across runs. A generator with a `match` predicate that resolves `false`
|
|
1766
|
-
* for a node is skipped for that node, without calling `schema`/`operation`.
|
|
1767
|
-
*
|
|
1768
|
-
* A failing plugin is dropped from the remaining walk, contributes an error diagnostic, and no
|
|
1769
|
-
* longer aborts the other plugins. `kubb:plugin:end` and each plugin's `timing` diagnostic fire
|
|
1770
|
-
* in dependency order once the walk finishes, driving the CLI's `Plugins N/M` counter. The
|
|
1771
|
-
* `operations` batch fires once per plugin after the single operation walk.
|
|
1772
|
-
*
|
|
1773
|
-
* When `this.inputNode` is `null`, every entry still gets a `kubb:plugin:end` so
|
|
1774
|
-
* post-plugin listeners (the barrel writer and friends) complete.
|
|
1775
|
-
*/
|
|
1776
|
-
async #runGenerators(entries) {
|
|
1777
|
-
const diagnostics = [];
|
|
1778
|
-
if (entries.length === 0) return diagnostics;
|
|
1779
|
-
if (!this.inputNode) {
|
|
1780
|
-
for (const { plugin, hrStart } of entries) {
|
|
1781
|
-
const duration = getElapsedMs(hrStart);
|
|
1782
|
-
diagnostics.push(Diagnostics.performance({
|
|
1783
|
-
plugin: plugin.name,
|
|
1784
|
-
duration
|
|
1785
|
-
}));
|
|
1786
|
-
await this.#emitPluginEnd({
|
|
1787
|
-
plugin,
|
|
1788
|
-
duration,
|
|
1789
|
-
success: true
|
|
1790
|
-
});
|
|
1791
|
-
}
|
|
1792
|
-
return diagnostics;
|
|
1793
|
-
}
|
|
1794
|
-
const transforms = this.#transforms;
|
|
1795
|
-
const { schemas, operations } = this.inputNode;
|
|
1796
|
-
const allowedSchemaNamesByPlugin = /* @__PURE__ */ new Map();
|
|
1797
|
-
for (const { plugin } of entries) {
|
|
1798
|
-
const { exclude, include, override } = plugin.options;
|
|
1799
|
-
if (!((include?.some(({ type }) => OPERATION_FILTER_TYPES.has(type)) ?? false) && !(include?.some(({ type }) => type === "schemaName") ?? false))) continue;
|
|
1800
|
-
const resolver = this.getResolver(plugin.name);
|
|
1801
|
-
const includedOps = operations.filter((operation) => resolver.default.options(operation, {
|
|
1802
|
-
options: plugin.options,
|
|
1803
|
-
exclude,
|
|
1804
|
-
include,
|
|
1805
|
-
override
|
|
1806
|
-
}) !== null);
|
|
1807
|
-
allowedSchemaNamesByPlugin.set(plugin.name, (0, _kubb_ast.collectUsedSchemaNames)(includedOps, schemas));
|
|
1808
|
-
}
|
|
1809
|
-
const states = entries.map(({ plugin, context, hrStart }) => {
|
|
1810
|
-
const generatorContext = {
|
|
1811
|
-
...context,
|
|
1812
|
-
resolver: this.getResolver(plugin.name)
|
|
1813
|
-
};
|
|
1814
|
-
const { exclude, include, override } = plugin.options;
|
|
1815
|
-
const generators = plugin.generators ?? [];
|
|
1816
|
-
return {
|
|
1817
|
-
plugin,
|
|
1818
|
-
hrStart,
|
|
1819
|
-
generatorContext,
|
|
1820
|
-
exclude,
|
|
1821
|
-
include,
|
|
1822
|
-
override,
|
|
1823
|
-
optionsAreStatic: !exclude?.length && !include?.length && !override?.length,
|
|
1824
|
-
allowedSchemaNames: allowedSchemaNamesByPlugin.get(plugin.name) ?? null,
|
|
1825
|
-
schemaGenerators: generators.filter((generator) => generator.schema),
|
|
1826
|
-
operationGenerators: generators.filter((generator) => generator.operation),
|
|
1827
|
-
operationsGenerators: generators.filter((generator) => generator.operations),
|
|
1828
|
-
pluginOperations: [],
|
|
1829
|
-
error: null
|
|
1830
|
-
};
|
|
1831
|
-
});
|
|
1832
|
-
const resolveForPlugin = (state, node) => {
|
|
1833
|
-
const transformedNode = transforms.applyTo(state.plugin.name, node);
|
|
1834
|
-
if (state.optionsAreStatic) return {
|
|
1835
|
-
transformedNode,
|
|
1836
|
-
options: state.plugin.options
|
|
1837
|
-
};
|
|
1838
|
-
const options = state.generatorContext.resolver.default.options(transformedNode, {
|
|
1839
|
-
options: state.plugin.options,
|
|
1840
|
-
exclude: state.exclude,
|
|
1841
|
-
include: state.include,
|
|
1842
|
-
override: state.override
|
|
1843
|
-
});
|
|
1844
|
-
if (options === null) return null;
|
|
1845
|
-
return {
|
|
1846
|
-
transformedNode,
|
|
1847
|
-
options
|
|
1848
|
-
};
|
|
1849
|
-
};
|
|
1850
|
-
for (const node of schemas) {
|
|
1851
|
-
const cache = require_nodeCache.createNodeCache();
|
|
1852
|
-
for (const state of states) {
|
|
1853
|
-
if (state.error || !state.schemaGenerators.length) continue;
|
|
1854
|
-
try {
|
|
1855
|
-
const resolved = resolveForPlugin(state, node);
|
|
1856
|
-
if (!resolved) continue;
|
|
1857
|
-
const { transformedNode, options } = resolved;
|
|
1858
|
-
if (state.allowedSchemaNames !== null && transformedNode.name && !state.allowedSchemaNames.has(transformedNode.name)) continue;
|
|
1859
|
-
const ctx = {
|
|
1860
|
-
...state.generatorContext,
|
|
1861
|
-
options,
|
|
1862
|
-
cache
|
|
1863
|
-
};
|
|
1864
|
-
await this.#dispatchNode({
|
|
1865
|
-
generators: state.schemaGenerators,
|
|
1866
|
-
node: transformedNode,
|
|
1867
|
-
ctx,
|
|
1868
|
-
generate: (generator) => generator.schema(transformedNode, ctx)
|
|
1869
|
-
});
|
|
1870
|
-
await this.hooks.callHook("kubb:generate:schema", transformedNode, ctx);
|
|
1871
|
-
} catch (caughtError) {
|
|
1872
|
-
state.error = require_nodeCache.toError(caughtError);
|
|
1873
|
-
}
|
|
1874
|
-
}
|
|
1875
|
-
}
|
|
1876
|
-
for (const node of operations) {
|
|
1877
|
-
const cache = require_nodeCache.createNodeCache();
|
|
1878
|
-
for (const state of states) {
|
|
1879
|
-
if (state.error || !state.operationGenerators.length && !state.operationsGenerators.length) continue;
|
|
1880
|
-
try {
|
|
1881
|
-
const resolved = resolveForPlugin(state, node);
|
|
1882
|
-
if (!resolved) continue;
|
|
1883
|
-
state.pluginOperations.push(resolved.transformedNode);
|
|
1884
|
-
if (state.operationGenerators.length) {
|
|
1885
|
-
const { transformedNode } = resolved;
|
|
1886
|
-
const ctx = {
|
|
1887
|
-
...state.generatorContext,
|
|
1888
|
-
options: resolved.options,
|
|
1889
|
-
cache
|
|
1890
|
-
};
|
|
1891
|
-
await this.#dispatchNode({
|
|
1892
|
-
generators: state.operationGenerators,
|
|
1893
|
-
node: transformedNode,
|
|
1894
|
-
ctx,
|
|
1895
|
-
generate: (generator) => generator.operation(transformedNode, ctx)
|
|
1896
|
-
});
|
|
1897
|
-
await this.hooks.callHook("kubb:generate:operation", transformedNode, ctx);
|
|
1898
|
-
}
|
|
1899
|
-
} catch (caughtError) {
|
|
1900
|
-
state.error = require_nodeCache.toError(caughtError);
|
|
1901
|
-
}
|
|
1902
|
-
}
|
|
1903
|
-
}
|
|
1904
|
-
for (const state of states) {
|
|
1905
|
-
if (state.error || !state.operationsGenerators.length) continue;
|
|
1906
|
-
try {
|
|
1907
|
-
const ctx = {
|
|
1908
|
-
...state.generatorContext,
|
|
1909
|
-
options: state.plugin.options,
|
|
1910
|
-
cache: require_nodeCache.createNodeCache()
|
|
1911
|
-
};
|
|
1912
|
-
for (const generator of state.operationsGenerators) await this.dispatch({
|
|
1913
|
-
result: await generator.operations(state.pluginOperations, ctx),
|
|
1914
|
-
renderer: generator.renderer
|
|
1915
|
-
});
|
|
1916
|
-
await this.hooks.callHook("kubb:generate:operations", state.pluginOperations, ctx);
|
|
1917
|
-
} catch (caughtError) {
|
|
1918
|
-
state.error = require_nodeCache.toError(caughtError);
|
|
1919
|
-
}
|
|
1920
|
-
}
|
|
1921
|
-
for (const state of states) {
|
|
1922
|
-
const duration = getElapsedMs(state.hrStart);
|
|
1923
|
-
await this.#emitPluginEnd({
|
|
1924
|
-
plugin: state.plugin,
|
|
1925
|
-
duration,
|
|
1926
|
-
success: !state.error,
|
|
1927
|
-
error: state.error ?? void 0
|
|
1928
|
-
});
|
|
1929
|
-
if (state.error) diagnostics.push({
|
|
1930
|
-
...Diagnostics.from(state.error),
|
|
1931
|
-
plugin: state.plugin.name
|
|
1932
|
-
});
|
|
1933
|
-
diagnostics.push(Diagnostics.performance({
|
|
1934
|
-
plugin: state.plugin.name,
|
|
1935
|
-
duration
|
|
1936
|
-
}));
|
|
1937
|
-
}
|
|
1938
|
-
return diagnostics;
|
|
1939
|
-
}
|
|
1940
|
-
/** Runs `node` through the generators whose `match` accepts it; `generate` picks the method for the node kind. */
|
|
1941
|
-
async #dispatchNode({ generators, node, ctx, generate }) {
|
|
1942
|
-
for (const generator of generators) {
|
|
1943
|
-
if (!(generator.match ? await generator.match(node, ctx) : true)) continue;
|
|
1944
|
-
await this.dispatch({
|
|
1945
|
-
result: await generate(generator),
|
|
1946
|
-
renderer: generator.renderer
|
|
1947
|
-
});
|
|
1948
|
-
}
|
|
1949
|
-
}
|
|
1950
|
-
/** Stores whatever a generator method or `kubb:generate:*` hook returned, see {@link FileManager.dispatch}. */
|
|
1951
|
-
dispatch(params) {
|
|
1952
|
-
return this.fileManager.dispatch(params);
|
|
1953
|
-
}
|
|
1954
|
-
/**
|
|
1955
|
-
* Removes every listener the driver added. Listeners attached directly to `hooks` from outside
|
|
1956
|
-
* the driver survive. Called at the end of a build to prevent leaks across repeated builds.
|
|
1957
|
-
*
|
|
1958
|
-
* @internal
|
|
1959
|
-
*/
|
|
1960
|
-
dispose() {
|
|
1961
|
-
for (const unhook of this.#unhooks) unhook();
|
|
1962
|
-
this.#unhooks.length = 0;
|
|
1963
|
-
this.#transforms.dispose();
|
|
1964
|
-
this.fileManager.dispose();
|
|
1965
|
-
this.inputNode = null;
|
|
1966
|
-
this.#adapterSource = null;
|
|
1967
|
-
}
|
|
1968
|
-
[Symbol.dispose]() {
|
|
1969
|
-
this.dispose();
|
|
1970
|
-
}
|
|
1971
|
-
getResolver(pluginName) {
|
|
1972
|
-
return this.plugins.get(pluginName)?.resolver ?? createResolver({ pluginName });
|
|
1973
|
-
}
|
|
1974
|
-
getContext(plugin) {
|
|
1975
|
-
const driver = this;
|
|
1976
|
-
const report = (diagnostic) => {
|
|
1977
|
-
Diagnostics.report({
|
|
1978
|
-
...diagnostic,
|
|
1979
|
-
plugin: plugin.name
|
|
1980
|
-
});
|
|
1981
|
-
};
|
|
1982
|
-
return {
|
|
1983
|
-
config: driver.config,
|
|
1984
|
-
signal: driver.options.signal,
|
|
1985
|
-
get root() {
|
|
1986
|
-
return (0, node_path.resolve)(driver.config.root, driver.config.output.path);
|
|
1987
|
-
},
|
|
1988
|
-
hooks: driver.hooks,
|
|
1989
|
-
plugin,
|
|
1990
|
-
getPlugin: driver.getPlugin.bind(driver),
|
|
1991
|
-
requirePlugin: ((name) => driver.requirePlugin(name, { requiredBy: plugin.name })),
|
|
1992
|
-
getResolver: driver.getResolver.bind(driver),
|
|
1993
|
-
driver,
|
|
1994
|
-
addFile: async (...files) => {
|
|
1995
|
-
driver.fileManager.add(...files);
|
|
1996
|
-
},
|
|
1997
|
-
upsertFile: async (...files) => {
|
|
1998
|
-
driver.fileManager.upsert(...files);
|
|
1999
|
-
},
|
|
2000
|
-
get meta() {
|
|
2001
|
-
return driver.inputNode?.meta ?? {
|
|
2002
|
-
circularNames: [],
|
|
2003
|
-
enumNames: []
|
|
2004
|
-
};
|
|
2005
|
-
},
|
|
2006
|
-
get adapter() {
|
|
2007
|
-
return driver.adapter;
|
|
2008
|
-
},
|
|
2009
|
-
get resolver() {
|
|
2010
|
-
return driver.getResolver(plugin.name);
|
|
2011
|
-
},
|
|
2012
|
-
warn(message) {
|
|
2013
|
-
report({
|
|
2014
|
-
code: Diagnostics.code.pluginWarning,
|
|
2015
|
-
severity: "warning",
|
|
2016
|
-
message
|
|
2017
|
-
});
|
|
2018
|
-
},
|
|
2019
|
-
error(error) {
|
|
2020
|
-
const cause = typeof error === "string" ? void 0 : error;
|
|
2021
|
-
report({
|
|
2022
|
-
code: Diagnostics.code.pluginFailed,
|
|
2023
|
-
severity: "error",
|
|
2024
|
-
message: typeof error === "string" ? error : error.message,
|
|
2025
|
-
cause
|
|
2026
|
-
});
|
|
2027
|
-
},
|
|
2028
|
-
info(message) {
|
|
2029
|
-
report({
|
|
2030
|
-
code: Diagnostics.code.pluginInfo,
|
|
2031
|
-
severity: "info",
|
|
2032
|
-
message
|
|
2033
|
-
});
|
|
2034
|
-
}
|
|
2035
|
-
};
|
|
2036
|
-
}
|
|
2037
|
-
getPlugin(pluginName) {
|
|
2038
|
-
return this.plugins.get(pluginName);
|
|
2039
|
-
}
|
|
2040
|
-
requirePlugin(pluginName, context) {
|
|
2041
|
-
const plugin = this.getPlugin(pluginName);
|
|
2042
|
-
if (plugin) return plugin;
|
|
2043
|
-
const requiredBy = context?.requiredBy;
|
|
2044
|
-
const by = requiredBy ? ` by "${requiredBy}"` : "";
|
|
2045
|
-
const help = requiredBy ? ` (required by "${requiredBy}")` : "";
|
|
2046
|
-
throw new Diagnostics.Error({
|
|
2047
|
-
code: Diagnostics.code.pluginNotFound,
|
|
2048
|
-
severity: "error",
|
|
2049
|
-
message: `Plugin "${pluginName}" is required${by} but not found. Make sure it is included in your Kubb config.`,
|
|
2050
|
-
help: `Add "${pluginName}" to the \`plugins\` array in kubb.config.ts${help}, or remove the dependency on it.`,
|
|
2051
|
-
location: { kind: "config" }
|
|
2052
|
-
});
|
|
2053
|
-
}
|
|
2054
|
-
};
|
|
2055
|
-
//#endregion
|
|
2056
209
|
//#region src/outputManifest.ts
|
|
2057
210
|
/**
|
|
2058
211
|
* Bumped when the stored shape changes, so an older cache is discarded instead of misread.
|
|
@@ -2095,7 +248,7 @@ async function createOutputManifest({ storage, cache }) {
|
|
|
2095
248
|
async commit() {
|
|
2096
249
|
try {
|
|
2097
250
|
const next = { ...entries };
|
|
2098
|
-
await
|
|
251
|
+
await require_KubbDriver.inParallel({
|
|
2099
252
|
items: [...tracked],
|
|
2100
253
|
limit: 50,
|
|
2101
254
|
run: async ([key, source]) => {
|
|
@@ -2190,7 +343,7 @@ function createStorage(build) {
|
|
|
2190
343
|
const fsStorage = createStorage(() => ({
|
|
2191
344
|
name: "fs",
|
|
2192
345
|
async existsItem(key) {
|
|
2193
|
-
return
|
|
346
|
+
return require_KubbDriver.exists((0, node_path.resolve)(key));
|
|
2194
347
|
},
|
|
2195
348
|
async readItem(key) {
|
|
2196
349
|
try {
|
|
@@ -2200,7 +353,7 @@ const fsStorage = createStorage(() => ({
|
|
|
2200
353
|
}
|
|
2201
354
|
},
|
|
2202
355
|
async writeItem(key, value, options) {
|
|
2203
|
-
await
|
|
356
|
+
await require_KubbDriver.write((0, node_path.resolve)(key), value, {
|
|
2204
357
|
sanity: false,
|
|
2205
358
|
stored: options?.stored
|
|
2206
359
|
});
|
|
@@ -2215,13 +368,13 @@ const fsStorage = createStorage(() => ({
|
|
|
2215
368
|
for await (const entry of (0, node_fs_promises.glob)("**/*", {
|
|
2216
369
|
cwd: resolvedBase,
|
|
2217
370
|
withFileTypes: true
|
|
2218
|
-
})) if (entry.isFile()) keys.push(
|
|
371
|
+
})) if (entry.isFile()) keys.push(require_KubbDriver.toPosixPath((0, node_path.relative)(resolvedBase, (0, node_path.join)(entry.parentPath, entry.name))));
|
|
2219
372
|
} catch (_error) {}
|
|
2220
373
|
return keys;
|
|
2221
374
|
},
|
|
2222
375
|
async empty(base) {
|
|
2223
376
|
if (!base) return;
|
|
2224
|
-
await
|
|
377
|
+
await require_KubbDriver.clean((0, node_path.resolve)(base));
|
|
2225
378
|
}
|
|
2226
379
|
}));
|
|
2227
380
|
//#endregion
|
|
@@ -2297,7 +450,7 @@ async function settle(proc, hooks, id, commandWithArgs) {
|
|
|
2297
450
|
id,
|
|
2298
451
|
line
|
|
2299
452
|
})).catch((error) => {
|
|
2300
|
-
lineError ??=
|
|
453
|
+
lineError ??= require_KubbDriver.toError(error);
|
|
2301
454
|
});
|
|
2302
455
|
});
|
|
2303
456
|
}
|
|
@@ -2370,14 +523,14 @@ const TOOL_PASSES = [{
|
|
|
2370
523
|
verb: "Formatting",
|
|
2371
524
|
tools: formatters,
|
|
2372
525
|
preference: FORMATTER_PREFERENCE,
|
|
2373
|
-
code: Diagnostics.code.formatFailed
|
|
526
|
+
code: require_KubbDriver.Diagnostics.code.formatFailed
|
|
2374
527
|
}, {
|
|
2375
528
|
kind: "lint",
|
|
2376
529
|
label: "linter",
|
|
2377
530
|
verb: "Linting",
|
|
2378
531
|
tools: linters,
|
|
2379
532
|
preference: LINTER_PREFERENCE,
|
|
2380
|
-
code: Diagnostics.code.lintFailed
|
|
533
|
+
code: require_KubbDriver.Diagnostics.code.lintFailed
|
|
2381
534
|
}];
|
|
2382
535
|
/**
|
|
2383
536
|
* Resolves `auto` to an installed tool and runs it. Returns the failure instead of throwing.
|
|
@@ -2428,7 +581,7 @@ async function runOutputPasses({ config, outputPath, hooks, signal }) {
|
|
|
2428
581
|
cause: error
|
|
2429
582
|
};
|
|
2430
583
|
diagnostics.push(diagnostic);
|
|
2431
|
-
await Diagnostics.emit(hooks, diagnostic);
|
|
584
|
+
await require_KubbDriver.Diagnostics.emit(hooks, diagnostic);
|
|
2432
585
|
};
|
|
2433
586
|
for (const pass of TOOL_PASSES) {
|
|
2434
587
|
const setting = config.output[pass.kind];
|
|
@@ -2465,7 +618,7 @@ async function runOutputPasses({ config, outputPath, hooks, signal }) {
|
|
|
2465
618
|
signal
|
|
2466
619
|
});
|
|
2467
620
|
if (result.success) await hooks.callHook("kubb:success", { message: `${(0, node_util.styleText)("dim", name ?? command)} successfully executed` });
|
|
2468
|
-
if (!result.success) await report(Diagnostics.code.postGenerateFailed, "Post-generate command", result.error);
|
|
621
|
+
if (!result.success) await report(require_KubbDriver.Diagnostics.code.postGenerateFailed, "Post-generate command", result.error);
|
|
2469
622
|
signal?.throwIfAborted();
|
|
2470
623
|
}
|
|
2471
624
|
await hooks.callHook("kubb:hooks:end");
|
|
@@ -2530,7 +683,7 @@ var Kubb = class {
|
|
|
2530
683
|
#signal;
|
|
2531
684
|
constructor(userConfig, options = {}) {
|
|
2532
685
|
this.config = resolveConfig(userConfig);
|
|
2533
|
-
this.hooks = options.hooks ?? new
|
|
686
|
+
this.hooks = options.hooks ?? new require_KubbDriver.Hookable();
|
|
2534
687
|
this.#signal = options.signal;
|
|
2535
688
|
}
|
|
2536
689
|
get storage() {
|
|
@@ -2551,23 +704,21 @@ var Kubb = class {
|
|
|
2551
704
|
storage: config.storage,
|
|
2552
705
|
cache: cacheStorage({ root: config.root })
|
|
2553
706
|
}) : void 0;
|
|
2554
|
-
|
|
707
|
+
this.hooks.setMaxListeners(Math.max(10, config.plugins.length * HOOK_LISTENERS_PER_PLUGIN));
|
|
708
|
+
const cleanPath = config.output.clean ? (0, node_path.resolve)(config.root, config.output.path) : void 0;
|
|
709
|
+
if (cleanPath && require_KubbDriver.isPathInside(config.root, cleanPath)) throw new require_KubbDriver.Diagnostics.Error({
|
|
710
|
+
code: require_KubbDriver.Diagnostics.code.cleanRoot,
|
|
711
|
+
severity: "error",
|
|
712
|
+
message: `output.clean cannot delete "${cleanPath}" because it is the project root or a parent of it.`,
|
|
713
|
+
help: "Point `output.path` at a subdirectory such as `./src/gen` so clean only removes generated code.",
|
|
714
|
+
location: { kind: "config" }
|
|
715
|
+
});
|
|
716
|
+
const driver = new require_KubbDriver.KubbDriver(config, {
|
|
2555
717
|
hooks: this.hooks,
|
|
2556
718
|
manifest,
|
|
2557
|
-
signal
|
|
719
|
+
signal,
|
|
720
|
+
cleanPath
|
|
2558
721
|
});
|
|
2559
|
-
this.hooks.setMaxListeners(Math.max(10, config.plugins.length * HOOK_LISTENERS_PER_PLUGIN));
|
|
2560
|
-
if (config.output.clean) {
|
|
2561
|
-
const cleanPath = (0, node_path.resolve)(config.root, config.output.path);
|
|
2562
|
-
if (require_nodeCache.isPathInside(config.root, cleanPath)) throw new Diagnostics.Error({
|
|
2563
|
-
code: Diagnostics.code.cleanRoot,
|
|
2564
|
-
severity: "error",
|
|
2565
|
-
message: `output.clean cannot delete "${cleanPath}" because it is the project root or a parent of it.`,
|
|
2566
|
-
help: "Point `output.path` at a subdirectory such as `./src/gen` so clean only removes generated code.",
|
|
2567
|
-
location: { kind: "config" }
|
|
2568
|
-
});
|
|
2569
|
-
await config.storage.empty(cleanPath);
|
|
2570
|
-
}
|
|
2571
722
|
await driver.setup();
|
|
2572
723
|
this.#driver = driver;
|
|
2573
724
|
this.#manifest = manifest ?? null;
|
|
@@ -2578,8 +729,8 @@ var Kubb = class {
|
|
|
2578
729
|
*/
|
|
2579
730
|
async build() {
|
|
2580
731
|
const out = await this.safeBuild();
|
|
2581
|
-
if (Diagnostics.hasError(out.diagnostics)) {
|
|
2582
|
-
const errors = out.diagnostics.filter(Diagnostics.isProblem).filter((diagnostic) => diagnostic.severity === "error").map((diagnostic) => diagnostic.cause ?? new Diagnostics.Error(diagnostic));
|
|
732
|
+
if (require_KubbDriver.Diagnostics.hasError(out.diagnostics)) {
|
|
733
|
+
const errors = out.diagnostics.filter(require_KubbDriver.Diagnostics.isProblem).filter((diagnostic) => diagnostic.severity === "error").map((diagnostic) => diagnostic.cause ?? new require_KubbDriver.Diagnostics.Error(diagnostic));
|
|
2583
734
|
throw new AggregateError(errors, `Build failed with ${errors.length} ${errors.length === 1 ? "error" : "errors"}`);
|
|
2584
735
|
}
|
|
2585
736
|
return out;
|
|
@@ -2591,7 +742,7 @@ var Kubb = class {
|
|
|
2591
742
|
*/
|
|
2592
743
|
async safeBuild() {
|
|
2593
744
|
try {
|
|
2594
|
-
var _usingCtx$1 =
|
|
745
|
+
var _usingCtx$1 = require_KubbDriver._usingCtx();
|
|
2595
746
|
this.#signal?.throwIfAborted();
|
|
2596
747
|
if (!this.#driver) await this.setup();
|
|
2597
748
|
const self = _usingCtx$1.u(this);
|
|
@@ -2634,14 +785,14 @@ var Kubb = class {
|
|
|
2634
785
|
const { files, diagnostics, storage } = await this.safeBuild();
|
|
2635
786
|
signal?.throwIfAborted();
|
|
2636
787
|
for (const diagnostic of diagnostics) {
|
|
2637
|
-
if (!Diagnostics.isProblem(diagnostic)) continue;
|
|
2638
|
-
if (diagnostic.code === Diagnostics.code.unknown) {
|
|
788
|
+
if (!require_KubbDriver.Diagnostics.isProblem(diagnostic)) continue;
|
|
789
|
+
if (diagnostic.code === require_KubbDriver.Diagnostics.code.unknown) {
|
|
2639
790
|
await hooks.callHook("kubb:error", { error: diagnostic.cause ?? new Error(diagnostic.message) });
|
|
2640
791
|
continue;
|
|
2641
792
|
}
|
|
2642
|
-
await Diagnostics.emit(hooks, diagnostic);
|
|
793
|
+
await require_KubbDriver.Diagnostics.emit(hooks, diagnostic);
|
|
2643
794
|
}
|
|
2644
|
-
if (Diagnostics.hasError(diagnostics)) {
|
|
795
|
+
if (require_KubbDriver.Diagnostics.hasError(diagnostics)) {
|
|
2645
796
|
await hooks.callHook("kubb:generation:end", {
|
|
2646
797
|
config,
|
|
2647
798
|
storage,
|
|
@@ -2664,7 +815,7 @@ var Kubb = class {
|
|
|
2664
815
|
signal
|
|
2665
816
|
}) : [];
|
|
2666
817
|
const finalDiagnostics = [...diagnostics, ...outputDiagnostics];
|
|
2667
|
-
const failed = Diagnostics.hasError(outputDiagnostics);
|
|
818
|
+
const failed = require_KubbDriver.Diagnostics.hasError(outputDiagnostics);
|
|
2668
819
|
if (!failed) await this.#manifest?.commit();
|
|
2669
820
|
await hooks.callHook("kubb:generation:end", {
|
|
2670
821
|
config,
|
|
@@ -2772,11 +923,11 @@ function createReporter(reporter) {
|
|
|
2772
923
|
*/
|
|
2773
924
|
function buildReport(result) {
|
|
2774
925
|
const { config, diagnostics, filesCreated, status, hrStart } = result;
|
|
2775
|
-
const failed = Diagnostics.failedPlugins(diagnostics);
|
|
926
|
+
const failed = require_KubbDriver.Diagnostics.failedPlugins(diagnostics);
|
|
2776
927
|
const total = config.plugins?.length ?? 0;
|
|
2777
|
-
const counts = Diagnostics.count(diagnostics);
|
|
2778
|
-
const problems = diagnostics.filter(Diagnostics.isProblem);
|
|
2779
|
-
const timings = diagnostics.filter(Diagnostics.isPerformance).sort((a, b) => b.duration - a.duration).map((diagnostic) => ({
|
|
928
|
+
const counts = require_KubbDriver.Diagnostics.count(diagnostics);
|
|
929
|
+
const problems = diagnostics.filter(require_KubbDriver.Diagnostics.isProblem);
|
|
930
|
+
const timings = diagnostics.filter(require_KubbDriver.Diagnostics.isPerformance).sort((a, b) => b.duration - a.duration).map((diagnostic) => ({
|
|
2780
931
|
plugin: diagnostic.plugin,
|
|
2781
932
|
durationMs: diagnostic.duration
|
|
2782
933
|
}));
|
|
@@ -2790,10 +941,10 @@ function buildReport(result) {
|
|
|
2790
941
|
},
|
|
2791
942
|
counts,
|
|
2792
943
|
filesCreated,
|
|
2793
|
-
durationMs: getElapsedMs(hrStart),
|
|
944
|
+
durationMs: require_KubbDriver.getElapsedMs(hrStart),
|
|
2794
945
|
output: (0, node_path.resolve)(config.root, config.output.path),
|
|
2795
946
|
timings,
|
|
2796
|
-
diagnostics: problems.map((diagnostic) => Diagnostics.serialize(diagnostic))
|
|
947
|
+
diagnostics: problems.map((diagnostic) => require_KubbDriver.Diagnostics.serialize(diagnostic))
|
|
2797
948
|
};
|
|
2798
949
|
}
|
|
2799
950
|
//#endregion
|
|
@@ -2843,7 +994,7 @@ function formatSummary(report, { showTimings }) {
|
|
|
2843
994
|
rows.push(["Issues", issues]);
|
|
2844
995
|
}
|
|
2845
996
|
rows.push(["Files", `${(0, node_util.styleText)("green", String(filesCreated))} generated`]);
|
|
2846
|
-
rows.push(["Duration", (0, node_util.styleText)("green", formatMs(durationMs))]);
|
|
997
|
+
rows.push(["Duration", (0, node_util.styleText)("green", require_KubbDriver.formatMs(durationMs))]);
|
|
2847
998
|
rows.push(["Output", output]);
|
|
2848
999
|
const labelWidth = Math.max(...rows.map(([label]) => label.length), timings.length > 0 ? 7 : 0);
|
|
2849
1000
|
const lines = rows.map(([label, value]) => `${(0, node_util.styleText)("dim", label.padStart(labelWidth))} ${value}`);
|
|
@@ -2852,7 +1003,7 @@ function formatSummary(report, { showTimings }) {
|
|
|
2852
1003
|
const indent = " ".repeat(labelWidth + 2);
|
|
2853
1004
|
lines.push((0, node_util.styleText)("dim", "Timings".padStart(labelWidth)));
|
|
2854
1005
|
for (const timing of timings) {
|
|
2855
|
-
const timeStr = formatMs(timing.durationMs);
|
|
1006
|
+
const timeStr = require_KubbDriver.formatMs(timing.durationMs);
|
|
2856
1007
|
const barLength = Math.min(Math.ceil(timing.durationMs / 100), 10);
|
|
2857
1008
|
const bar = (0, node_util.styleText)("dim", "█".repeat(barLength));
|
|
2858
1009
|
lines.push(`${indent}${(0, node_util.styleText)("dim", "•")} ${timing.plugin.padEnd(nameWidth)} ${bar} ${timeStr}`);
|
|
@@ -2951,7 +1102,7 @@ function buildSummarySection(report) {
|
|
|
2951
1102
|
if (plugins.failed.length > 0) rows.push(["Failed", plugins.failed.join(", ")]);
|
|
2952
1103
|
rows.push(["Issues", `${counts.errors} errors | ${counts.warnings} warnings | ${counts.infos} infos`]);
|
|
2953
1104
|
rows.push(["Files", `${filesCreated} generated`]);
|
|
2954
|
-
rows.push(["Duration", formatMs(durationMs)]);
|
|
1105
|
+
rows.push(["Duration", require_KubbDriver.formatMs(durationMs)]);
|
|
2955
1106
|
rows.push(["Output", output]);
|
|
2956
1107
|
const labelWidth = Math.max(...rows.map(([label]) => label.length));
|
|
2957
1108
|
return [
|
|
@@ -2966,12 +1117,12 @@ function buildSummarySection(report) {
|
|
|
2966
1117
|
* can drop the heading.
|
|
2967
1118
|
*/
|
|
2968
1119
|
function buildProblemSection(diagnostics) {
|
|
2969
|
-
const problems = diagnostics.filter(Diagnostics.isProblem);
|
|
1120
|
+
const problems = diagnostics.filter(require_KubbDriver.Diagnostics.isProblem);
|
|
2970
1121
|
if (problems.length === 0) return [];
|
|
2971
1122
|
return [
|
|
2972
1123
|
"## Problems",
|
|
2973
1124
|
"",
|
|
2974
|
-
problems.map((diagnostic) => Diagnostics.formatLines(diagnostic).join("\n")).join("\n\n")
|
|
1125
|
+
problems.map((diagnostic) => require_KubbDriver.Diagnostics.formatLines(diagnostic).join("\n")).join("\n\n")
|
|
2975
1126
|
];
|
|
2976
1127
|
}
|
|
2977
1128
|
/**
|
|
@@ -2983,7 +1134,7 @@ function buildTimingSection(report) {
|
|
|
2983
1134
|
const { timings } = report;
|
|
2984
1135
|
if (timings.length === 0) return [];
|
|
2985
1136
|
const nameWidth = Math.max(...timings.map((timing) => timing.plugin.length));
|
|
2986
|
-
const durations = timings.map((timing) => formatMs(timing.durationMs));
|
|
1137
|
+
const durations = timings.map((timing) => require_KubbDriver.formatMs(timing.durationMs));
|
|
2987
1138
|
const durationWidth = Math.max(...durations.map((duration) => duration.length));
|
|
2988
1139
|
return [
|
|
2989
1140
|
"## Timings",
|
|
@@ -3066,7 +1217,7 @@ const htmlReporter = createReporter({
|
|
|
3066
1217
|
const dir = resolveKubbDir((0, node_path.resolve)(process.cwd(), ".kubb"));
|
|
3067
1218
|
const storage = kubbStorage({ base: dir });
|
|
3068
1219
|
const assets = new URL("./html/", require("url").pathToFileURL(__filename).href);
|
|
3069
|
-
const [html, ui] = await Promise.all([
|
|
1220
|
+
const [html, ui] = await Promise.all([require_KubbDriver.read((0, node_url.fileURLToPath)(new URL("index.html", assets))), require_KubbDriver.read((0, node_url.fileURLToPath)(new URL("ui.iife.js", assets)))]);
|
|
3070
1221
|
await Promise.all([
|
|
3071
1222
|
storage.setItem(`${baseName}/index.html`, html),
|
|
3072
1223
|
storage.setItem(`${baseName}/ui.iife.js`, ui),
|
|
@@ -3227,11 +1378,12 @@ const memoryStorage = createStorage(() => {
|
|
|
3227
1378
|
};
|
|
3228
1379
|
});
|
|
3229
1380
|
//#endregion
|
|
3230
|
-
exports.Diagnostics = Diagnostics;
|
|
3231
|
-
exports.Hookable =
|
|
3232
|
-
exports.KubbDriver = KubbDriver;
|
|
3233
|
-
exports.Resolver = Resolver;
|
|
1381
|
+
exports.Diagnostics = require_KubbDriver.Diagnostics;
|
|
1382
|
+
exports.Hookable = require_KubbDriver.Hookable;
|
|
1383
|
+
exports.KubbDriver = require_KubbDriver.KubbDriver;
|
|
1384
|
+
exports.Resolver = require_KubbDriver.Resolver;
|
|
3234
1385
|
exports.applyConfigDefaults = applyConfigDefaults;
|
|
1386
|
+
exports.assertPluginOption = require_KubbDriver.assertPluginOption;
|
|
3235
1387
|
exports.cacheStorage = cacheStorage;
|
|
3236
1388
|
exports.cliReporter = cliReporter;
|
|
3237
1389
|
exports.createAdapter = createAdapter;
|
|
@@ -3239,14 +1391,14 @@ exports.createCliReporter = createCliReporter;
|
|
|
3239
1391
|
exports.createKubb = createKubb;
|
|
3240
1392
|
exports.createRenderer = createRenderer;
|
|
3241
1393
|
exports.createReporter = createReporter;
|
|
3242
|
-
exports.createResolver = createResolver;
|
|
1394
|
+
exports.createResolver = require_KubbDriver.createResolver;
|
|
3243
1395
|
exports.createStorage = createStorage;
|
|
3244
1396
|
exports.defineGenerator = defineGenerator;
|
|
3245
1397
|
exports.defineParser = defineParser;
|
|
3246
|
-
exports.definePlugin = definePlugin;
|
|
1398
|
+
exports.definePlugin = require_KubbDriver.definePlugin;
|
|
3247
1399
|
exports.fileReporter = fileReporter;
|
|
3248
1400
|
exports.fsStorage = fsStorage;
|
|
3249
|
-
exports.getInputKind = getInputKind;
|
|
1401
|
+
exports.getInputKind = require_KubbDriver.getInputKind;
|
|
3250
1402
|
exports.htmlReporter = htmlReporter;
|
|
3251
1403
|
exports.jsonReporter = jsonReporter;
|
|
3252
1404
|
exports.kubbStorage = kubbStorage;
|