@kubb/core 5.5.6 → 5.6.1

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/index.js CHANGED
@@ -1,15 +1,18 @@
1
1
  import "./rolldown-runtime-C0LytTxp.js";
2
- import { a as OPERATION_FILTER_TYPES, c as clean, d as toPosixPath, f as write, h as camelCase, i as Hookable, l as isPathInside, m as toError, n as createNodeCache, o as diagnosticCode, p as getErrorMessage, r as FileManager, s as inParallel, t as _usingCtx, u as read } from "./usingCtx-DdG2edpx.js";
2
+ import { a as inParallel, c as isPathInside, d as write, f as getErrorMessage, i as Hookable, l as read, m as camelCase, n as FileManager, o as clean, p as toError, r as _usingCtx, s as exists, t as createNodeCache, u as toPosixPath } from "./nodeCache-CumrOPh-.js";
3
3
  import { AsyncLocalStorage } from "node:async_hooks";
4
4
  import { stripVTControlCharacters, styleText } from "node:util";
5
5
  import process$1 from "node:process";
6
- import { execFile } from "node:child_process";
7
- import { access, glob, readFile, rm } from "node:fs/promises";
6
+ import { x } from "tinyexec";
7
+ import { glob, readFile, rm } from "node:fs/promises";
8
8
  import path, { join, relative, resolve } from "node:path";
9
9
  import { ast, collectImportedRefNames, collectUsedSchemaNames, composeMacros, operationDef, schemaDef, transform } from "@kubb/ast";
10
- import { hash } from "node:crypto";
11
- import { existsSync } from "node:fs";
12
- import { tmpdir } from "node:os";
10
+ import { hash, randomUUID } from "node:crypto";
11
+ import { chmodSync, existsSync, mkdirSync } from "node:fs";
12
+ import { homedir, tmpdir } from "node:os";
13
+ import { createInterface } from "node:readline";
14
+ import { createStorage as createStorage$1 } from "unstorage";
15
+ import fsDriver from "unstorage/drivers/fs";
13
16
  import { fileURLToPath } from "node:url";
14
17
  //#region src/createAdapter.ts
15
18
  /**
@@ -76,18 +79,131 @@ function isCIEnvironment() {
76
79
  }
77
80
  //#endregion
78
81
  //#region ../../internals/utils/src/openInBrowser.ts
82
+ const ignore = () => {};
79
83
  /**
80
84
  * Opens a URL or local file in the default browser, unless running in CI.
81
85
  */
82
86
  function openInBrowser(target) {
83
87
  if (isCIEnvironment()) return;
84
- if (process$1.platform === "win32") execFile("cmd", [
85
- "/c",
86
- "start",
87
- "",
88
- target
89
- ], () => {});
90
- else execFile(process$1.platform === "darwin" ? "open" : "xdg-open", [target], () => {});
88
+ if (process$1.platform === "win32") {
89
+ x("cmd", [
90
+ "/c",
91
+ "start",
92
+ "",
93
+ target
94
+ ]).then(ignore, ignore);
95
+ return;
96
+ }
97
+ x(process$1.platform === "darwin" ? "open" : "xdg-open", [target]).then(ignore, ignore);
98
+ }
99
+ //#endregion
100
+ //#region ../../internals/utils/src/tools.ts
101
+ /**
102
+ * CLI command descriptors for each supported code formatter.
103
+ */
104
+ const formatters = {
105
+ prettier: {
106
+ command: "prettier",
107
+ args: (outputPath) => [
108
+ "--ignore-unknown",
109
+ "--write",
110
+ outputPath
111
+ ],
112
+ errorMessage: "Prettier not found"
113
+ },
114
+ biome: {
115
+ command: "biome",
116
+ args: (outputPath) => [
117
+ "format",
118
+ "--write",
119
+ outputPath
120
+ ],
121
+ errorMessage: "Biome not found"
122
+ },
123
+ oxfmt: {
124
+ command: "oxfmt",
125
+ args: (outputPath) => [outputPath],
126
+ errorMessage: "Oxfmt not found"
127
+ }
128
+ };
129
+ /**
130
+ * CLI command descriptors for each supported linter.
131
+ */
132
+ const linters = {
133
+ eslint: {
134
+ command: "eslint",
135
+ args: (outputPath) => [outputPath, "--fix"],
136
+ errorMessage: "Eslint not found"
137
+ },
138
+ biome: {
139
+ command: "biome",
140
+ args: (outputPath) => [
141
+ "lint",
142
+ "--fix",
143
+ outputPath
144
+ ],
145
+ errorMessage: "Biome not found"
146
+ },
147
+ oxlint: {
148
+ command: "oxlint",
149
+ args: (outputPath) => [
150
+ "--fix",
151
+ "--no-ignore",
152
+ outputPath
153
+ ],
154
+ errorMessage: "Oxlint not found"
155
+ }
156
+ };
157
+ /**
158
+ * Preference order for `format: 'auto'`, most-preferred first. Spelled out rather than taken from
159
+ * the table's key order, which is arbitrary and would silently change what `auto` picks.
160
+ */
161
+ const FORMATTER_PREFERENCE = [
162
+ "oxfmt",
163
+ "biome",
164
+ "prettier"
165
+ ];
166
+ /**
167
+ * Preference order for `lint: 'auto'`, most-preferred first.
168
+ */
169
+ const LINTER_PREFERENCE = [
170
+ "oxlint",
171
+ "biome",
172
+ "eslint"
173
+ ];
174
+ /**
175
+ * Whether `name` is on PATH or in a `node_modules/.bin` above `cwd` and answers `--version` with a zero exit.
176
+ */
177
+ async function isToolAvailable(name, cwd) {
178
+ return x(name, ["--version"], {
179
+ throwOnError: false,
180
+ nodeOptions: {
181
+ cwd,
182
+ stdio: "ignore"
183
+ }
184
+ }).then(({ exitCode }) => exitCode === 0, () => false);
185
+ }
186
+ /**
187
+ * Returns the first installed executable from `candidates`, or `null` when none are found.
188
+ *
189
+ * Not memoized: a long-running host that probes repeatedly should cache the result itself, and a
190
+ * `--watch` build should keep noticing a tool installed mid-session.
191
+ */
192
+ async function detectTool(candidates, cwd) {
193
+ for (const candidate of candidates) if (await isToolAvailable(candidate, cwd)) return candidate;
194
+ return null;
195
+ }
196
+ /**
197
+ * Tokenizes a shell command string, respecting single and double quotes.
198
+ *
199
+ * @example
200
+ * ```ts
201
+ * tokenize('git commit -m "initial commit"')
202
+ * // → ['git', 'commit', '-m', 'initial commit']
203
+ * ```
204
+ */
205
+ function tokenize(command) {
206
+ return (command.match(/[^\s"']+|"([^"]*)"|'([^']*)'/g) ?? []).map((token) => token.replace(/^["']|["']$/g, ""));
91
207
  }
92
208
  //#endregion
93
209
  //#region ../../internals/utils/src/time.ts
@@ -123,11 +239,134 @@ function formatMs(ms) {
123
239
  return `${Math.round(ms)}ms`;
124
240
  }
125
241
  //#endregion
242
+ //#region package.json
243
+ var version = "5.6.1";
244
+ //#endregion
245
+ //#region src/constants.ts
246
+ /**
247
+ * Stable codes Kubb attaches to a `Diagnostic`. Each maps to a known failure mode
248
+ * and stays stable so it can be referenced in tooling and (later) docs. Reference
249
+ * these instead of inlining the string at a throw site.
250
+ */
251
+ const diagnosticCode = {
252
+ /**
253
+ * Fallback for an unstructured error with no specific code.
254
+ */
255
+ unknown: "KUBB_UNKNOWN",
256
+ /**
257
+ * The file or URL set as `input` could not be read.
258
+ */
259
+ inputNotFound: "KUBB_INPUT_NOT_FOUND",
260
+ /**
261
+ * A URL set as `input` (or referenced by a `$ref`) answered with a 4xx or 5xx status
262
+ * instead of the document.
263
+ */
264
+ inputRequestFailed: "KUBB_INPUT_REQUEST_FAILED",
265
+ /**
266
+ * A URL set as `input` (or referenced by a `$ref`) never answered, so the request failed
267
+ * before a status was returned.
268
+ */
269
+ inputUnreachable: "KUBB_INPUT_UNREACHABLE",
270
+ /**
271
+ * An adapter was configured without an `input`.
272
+ */
273
+ inputRequired: "KUBB_INPUT_REQUIRED",
274
+ /**
275
+ * `input` uses the v4 `{ path }` / `{ data }` wrapper, which v5 reads as a parsed
276
+ * document instead of a pointer to one.
277
+ */
278
+ legacyInput: "KUBB_LEGACY_INPUT",
279
+ /**
280
+ * The parsed `input` carries no `openapi` or `swagger` version, so it is not a
281
+ * document the adapter can read.
282
+ */
283
+ invalidDocument: "KUBB_INVALID_DOCUMENT",
284
+ /** The document fails OpenAPI schema validation. Reported as a warning. */
285
+ invalidSpec: "KUBB_INVALID_SPEC",
286
+ /**
287
+ * A `$ref` (or equivalent reference) could not be resolved in the source document.
288
+ */
289
+ refNotFound: "KUBB_REF_NOT_FOUND",
290
+ /**
291
+ * A server variable value is not allowed by its `enum`.
292
+ */
293
+ invalidServerVariable: "KUBB_INVALID_SERVER_VARIABLE",
294
+ /**
295
+ * A required plugin is missing from the config.
296
+ */
297
+ pluginNotFound: "KUBB_PLUGIN_NOT_FOUND",
298
+ /**
299
+ * A plugin threw while generating.
300
+ */
301
+ pluginFailed: "KUBB_PLUGIN_FAILED",
302
+ /**
303
+ * A plugin reported a non-fatal warning through `ctx.warn`.
304
+ */
305
+ pluginWarning: "KUBB_PLUGIN_WARNING",
306
+ /**
307
+ * A plugin reported an informational message through `ctx.info`.
308
+ */
309
+ pluginInfo: "KUBB_PLUGIN_INFO",
310
+ /**
311
+ * A schema uses a `format` Kubb does not map to a specific type. Reserved for
312
+ * adapters to emit as a `warning`.
313
+ */
314
+ unsupportedFormat: "KUBB_UNSUPPORTED_FORMAT",
315
+ /**
316
+ * A referenced schema or operation is marked `deprecated`. Reserved for adapters
317
+ * to emit as an `info`.
318
+ */
319
+ deprecated: "KUBB_DEPRECATED",
320
+ /**
321
+ * An adapter is required but the config has none. The build cannot read the input
322
+ * without one.
323
+ */
324
+ adapterRequired: "KUBB_ADAPTER_REQUIRED",
325
+ /**
326
+ * A resolved output path escapes the output directory, which can stem from a path
327
+ * traversal in the spec or a misconfigured `group.name`.
328
+ */
329
+ pathTraversal: "KUBB_PATH_TRAVERSAL",
330
+ /**
331
+ * `output.clean` is enabled but `output.path` resolves to the project root or a parent of it,
332
+ * so cleaning would delete kubb.config and every source file.
333
+ */
334
+ cleanRoot: "KUBB_CLEAN_ROOT",
335
+ /**
336
+ * A plugin's options are invalid, for example `output.mode: 'file'` paired with a `group` option.
337
+ */
338
+ invalidPluginOptions: "KUBB_INVALID_PLUGIN_OPTIONS",
339
+ /**
340
+ * A post-generate command (`output.postGenerate`) exited with a failure.
341
+ */
342
+ postGenerateFailed: "KUBB_POST_GENERATE_FAILED",
343
+ /**
344
+ * The formatter pass over the generated files failed.
345
+ */
346
+ formatFailed: "KUBB_FORMAT_FAILED",
347
+ /**
348
+ * The linter pass over the generated files failed.
349
+ */
350
+ lintFailed: "KUBB_LINT_FAILED",
351
+ /**
352
+ * A barrel tries to re-export the same name from more than one module.
353
+ */
354
+ barrelDuplicateExport: "KUBB_BARREL_DUPLICATE_EXPORT",
355
+ /**
356
+ * Not a failure. Carries a plugin's elapsed time, summed into the run total.
357
+ */
358
+ performance: "KUBB_PERFORMANCE",
359
+ /**
360
+ * Not a failure. A newer Kubb version is available on npm.
361
+ */
362
+ updateAvailable: "KUBB_UPDATE_AVAILABLE"
363
+ };
364
+ //#endregion
126
365
  //#region src/Diagnostics.ts
127
366
  /**
128
367
  * Docs major version, derived from the package version so the link tracks the published major.
129
368
  */
130
- const docsMajor = "5.5.6".split(".")[0] ?? "5";
369
+ const docsMajor = version.split(".")[0] ?? "5";
131
370
  /**
132
371
  * Builds a type guard that narrows a {@link Diagnostic} to the variant for `kind`. A diagnostic
133
372
  * with no `kind` is treated as a `problem`.
@@ -175,6 +414,11 @@ const severityStyle = {
175
414
  warning: "yellow",
176
415
  info: "blue"
177
416
  };
417
+ const countKey = {
418
+ error: "errors",
419
+ warning: "warnings",
420
+ info: "infos"
421
+ };
178
422
  /**
179
423
  * Explanation for every {@link diagnosticCode}. Use {@link Diagnostics.explain} to look one up
180
424
  * and `Diagnostics.docsUrl` for the matching kubb.dev page.
@@ -362,7 +606,9 @@ var Diagnostics = class Diagnostics {
362
606
  */
363
607
  static isError(error) {
364
608
  if (error instanceof Diagnostics.Error) return true;
365
- return error instanceof Error && error.name === "DiagnosticError" && "diagnostic" in error && typeof error.diagnostic === "object" && error.diagnostic !== null && typeof error.diagnostic?.code === "string";
609
+ if (!(error instanceof Error) || error.name !== "DiagnosticError") return false;
610
+ const { diagnostic } = error;
611
+ return typeof diagnostic === "object" && diagnostic !== null && typeof diagnostic.code === "string";
366
612
  }
367
613
  /**
368
614
  * Runs `fn` with `sink` as the active diagnostic sink for the whole async
@@ -450,35 +696,20 @@ var Diagnostics = class Diagnostics {
450
696
  * that carry a `plugin`.
451
697
  */
452
698
  static failedPlugins(diagnostics) {
453
- const names = /* @__PURE__ */ new Set();
454
- for (const diagnostic of diagnostics) if (diagnostic.severity === "error" && diagnostic.plugin) names.add(diagnostic.plugin);
455
- return [...names];
699
+ return [...new Set(diagnostics.flatMap((diagnostic) => diagnostic.severity === "error" && diagnostic.plugin ? [diagnostic.plugin] : []))];
456
700
  }
457
701
  /**
458
702
  * Counts `problem` diagnostics by severity for the run summary. `performance` and
459
703
  * `update` diagnostics are ignored.
460
704
  */
461
705
  static count(diagnostics) {
462
- let errors = 0;
463
- let warnings = 0;
464
- let infos = 0;
465
- for (const diagnostic of diagnostics) {
466
- if (!isProblem(diagnostic)) continue;
467
- if (diagnostic.severity === "error") {
468
- errors += 1;
469
- continue;
470
- }
471
- if (diagnostic.severity === "warning") {
472
- warnings += 1;
473
- continue;
474
- }
475
- infos += 1;
476
- }
477
- return {
478
- errors,
479
- warnings,
480
- infos
706
+ const counts = {
707
+ errors: 0,
708
+ warnings: 0,
709
+ infos: 0
481
710
  };
711
+ for (const diagnostic of diagnostics.filter(isProblem)) counts[countKey[diagnostic.severity]] += 1;
712
+ return counts;
482
713
  }
483
714
  /**
484
715
  * Drops duplicate `problem` diagnostics that share a code, location pointer, and
@@ -579,7 +810,7 @@ var Diagnostics = class Diagnostics {
579
810
  function normalizeOutput({ output, group, pluginName }) {
580
811
  const mode = output.mode ?? (path.extname(output.path) ? "file" : "directory");
581
812
  if (mode === "file" && group) throw new Diagnostics.Error({
582
- code: diagnosticCode.invalidPluginOptions,
813
+ code: Diagnostics.code.invalidPluginOptions,
583
814
  severity: "error",
584
815
  message: `Plugin "${pluginName}" resolves \`output.mode\` to 'file' but also configures a \`group\` option.`,
585
816
  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.",
@@ -704,7 +935,7 @@ const resolverOptions = Symbol.for("@kubb/core/resolver/options");
704
935
  /**
705
936
  * Builds a nested file path from a dotted name. Splits on dots that precede a letter
706
937
  * (so version numbers embedded in operationIds like `v2025.0` stay intact), camelCases
707
- * every earlier segment, applies `caseLast` to the final segment, and joins with `/`.
938
+ * every segment, and joins with `/`.
708
939
  *
709
940
  * Empty segments are dropped before joining. They arise when the name starts with a dot
710
941
  * followed by a letter (e.g. `..Schema` splits into `['..', 'Schema']` and `'..'` cases to
@@ -713,16 +944,21 @@ const resolverOptions = Symbol.for("@kubb/core/resolver/options");
713
944
  *
714
945
  * @example Nested path from a dotted name
715
946
  * `toFilePath('pet.petId') // 'pet/petId'`
716
- *
717
- * @example PascalCase the final segment
718
- * `toFilePath('pet.Pet', pascalCase) // 'pet/Pet'`
719
- *
720
- * @example Suffix applied to the final segment only
721
- * `toFilePath('tag.tag', (part) => camelCase(part, { suffix: 'schema' })) // 'tag/tagSchema'`
722
947
  */
723
- function toFilePath(name, caseLast = camelCase) {
724
- const parts = name.split(/\.(?=[a-zA-Z])/);
725
- return parts.map((part, i) => i === parts.length - 1 ? caseLast(part) : camelCase(part)).filter(Boolean).join("/");
948
+ function toFilePath(name) {
949
+ return name.split(/\.(?=[a-zA-Z])/).map((part) => camelCase(part)).filter(Boolean).join("/");
950
+ }
951
+ /** Throws `KUBB_PATH_TRAVERSAL` when `target` lies outside `parent`; `target === parent` stays allowed. */
952
+ function assertInside({ target, parent, message, help }) {
953
+ const parentWithSep = parent.endsWith(path.sep) ? parent : `${parent}${path.sep}`;
954
+ if (target === parent || target.startsWith(parentWithSep)) return;
955
+ throw new Diagnostics.Error({
956
+ code: Diagnostics.code.pathTraversal,
957
+ severity: "error",
958
+ message,
959
+ help,
960
+ location: { kind: "config" }
961
+ });
726
962
  }
727
963
  /**
728
964
  * Built-in `file.baseName`: casts the identifier with `toFilePath` and appends the extension.
@@ -758,6 +994,8 @@ var Resolver = class Resolver {
758
994
  static #patternCache = /* @__PURE__ */ new Map();
759
995
  static #optionsCache = /* @__PURE__ */ new WeakMap();
760
996
  pluginName;
997
+ /** The built-in machinery, untouched by `name`/`file` overrides and built once since the driver reads it per node. */
998
+ default;
761
999
  #options;
762
1000
  #baseName;
763
1001
  #filePath;
@@ -766,18 +1004,7 @@ var Resolver = class Resolver {
766
1004
  this.#options = options;
767
1005
  this.#baseName = options.file?.baseName ? options.file.baseName.bind(this) : toBaseName;
768
1006
  this.#filePath = options.file?.path ? options.file.path.bind(this) : void 0;
769
- this.#apply(options);
770
- }
771
- /** Exposes the raw build options so `Resolver.merge` can read them across `@kubb/core` copies. */
772
- get [resolverOptions]() {
773
- return this.#options;
774
- }
775
- /**
776
- * The built-in resolution machinery. Always reaches the untouched defaults, even when a
777
- * plugin overrides the top-level `name` or `file`.
778
- */
779
- get default() {
780
- return {
1007
+ this.default = {
781
1008
  name: camelCase,
782
1009
  options: this.#resolveOptions.bind(this),
783
1010
  path: this.#resolvePath.bind(this),
@@ -785,6 +1012,11 @@ var Resolver = class Resolver {
785
1012
  banner: this.#resolveBanner.bind(this),
786
1013
  footer: this.#resolveFooter.bind(this)
787
1014
  };
1015
+ this.#apply(options);
1016
+ }
1017
+ /** Exposes the raw build options so `Resolver.merge` can read them across `@kubb/core` copies. */
1018
+ get [resolverOptions]() {
1019
+ return this.#options;
788
1020
  }
789
1021
  name(name) {
790
1022
  return this.default.name(name);
@@ -944,13 +1176,11 @@ var Resolver = class Resolver {
944
1176
  if (output.mode !== "directory") return path.resolve(root, output.path);
945
1177
  const outputDir = path.resolve(root, output.path);
946
1178
  const result = group && (groupPath || tag) ? path.resolve(outputDir, Resolver.#resolveGroupDir(group, group.type === "path" ? groupPath : tag), baseName) : path.resolve(outputDir, baseName);
947
- const outputDirWithSep = outputDir.endsWith(path.sep) ? outputDir : `${outputDir}${path.sep}`;
948
- if (result !== outputDir && !result.startsWith(outputDirWithSep)) throw new Diagnostics.Error({
949
- code: Diagnostics.code.pathTraversal,
950
- severity: "error",
1179
+ assertInside({
1180
+ target: result,
1181
+ parent: outputDir,
951
1182
  message: `Resolved path "${result}" is outside the output directory "${outputDir}".`,
952
- 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.",
953
- location: { kind: "config" }
1183
+ 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."
954
1184
  });
955
1185
  return result;
956
1186
  }
@@ -961,13 +1191,11 @@ var Resolver = class Resolver {
961
1191
  */
962
1192
  #resolveOverridePath(filePath, root) {
963
1193
  const resolved = path.resolve(root, filePath);
964
- const rootWithSep = root.endsWith(path.sep) ? root : `${root}${path.sep}`;
965
- if (resolved !== root && !resolved.startsWith(rootWithSep)) throw new Diagnostics.Error({
966
- code: Diagnostics.code.pathTraversal,
967
- severity: "error",
1194
+ assertInside({
1195
+ target: resolved,
1196
+ parent: root,
968
1197
  message: `Resolved path "${resolved}" is outside the project root "${root}".`,
969
- help: "A resolver `file.path` must return a path inside the project root.",
970
- location: { kind: "config" }
1198
+ help: "A resolver `file.path` must return a path inside the project root."
971
1199
  });
972
1200
  return resolved;
973
1201
  }
@@ -1192,21 +1420,27 @@ const ENFORCE_ORDER = {
1192
1420
  pre: -1,
1193
1421
  post: 1
1194
1422
  };
1423
+ /** `include` filter types that select operations, and so prune the schemas they do not reach. */
1424
+ const OPERATION_FILTER_TYPES = /* @__PURE__ */ new Set([
1425
+ "tag",
1426
+ "operationId",
1427
+ "path",
1428
+ "method",
1429
+ "contentType"
1430
+ ]);
1195
1431
  const enforceWeight = (plugin) => plugin.enforce ? ENFORCE_ORDER[plugin.enforce] : 0;
1196
1432
  /**
1197
1433
  * The options bag a `NormalizedPlugin` starts with before a plugin refines it: a directory output
1198
1434
  * at the plugin root and empty filter lists.
1199
1435
  */
1200
- function defaultPluginOptions() {
1201
- return {
1202
- output: {
1203
- path: ".",
1204
- mode: "directory"
1205
- },
1206
- exclude: [],
1207
- override: []
1208
- };
1209
- }
1436
+ const defaultPluginOptions = () => ({
1437
+ output: {
1438
+ path: ".",
1439
+ mode: "directory"
1440
+ },
1441
+ exclude: [],
1442
+ override: []
1443
+ });
1210
1444
  /**
1211
1445
  * Fills in the `output`, `exclude`, and `override` a `NormalizedPlugin` needs from a plugin's raw
1212
1446
  * options, running `output` through `normalizeOutput`. Idempotent, so the driver can apply it after
@@ -1353,10 +1587,10 @@ var KubbDriver = class {
1353
1587
  config: this.config,
1354
1588
  options: plugin.options ?? {},
1355
1589
  addGenerator: (...generators) => {
1356
- for (const generator of generators) this.registerGenerator(plugin.name, generator);
1590
+ plugin.generators = [...plugin.generators ?? [], ...generators];
1357
1591
  },
1358
1592
  setResolver: (resolver) => {
1359
- this.setPluginResolver(plugin.name, resolver);
1593
+ plugin.resolver = Resolver.merge(createResolver({ pluginName: plugin.name }), resolver);
1360
1594
  },
1361
1595
  addMacro: (macro) => {
1362
1596
  this.#transforms.add(plugin.name, macro);
@@ -1365,18 +1599,10 @@ var KubbDriver = class {
1365
1599
  this.#transforms.set(plugin.name, macros);
1366
1600
  },
1367
1601
  setOptions: (opts) => {
1368
- plugin.options = {
1602
+ plugin.options = normalizePluginOptions({
1369
1603
  ...plugin.options,
1370
1604
  ...opts
1371
- };
1372
- if (plugin.options.output) {
1373
- const group = "group" in plugin.options ? plugin.options.group : void 0;
1374
- plugin.options.output = normalizeOutput({
1375
- output: plugin.options.output,
1376
- group,
1377
- pluginName: plugin.name
1378
- });
1379
- }
1605
+ }, plugin.name);
1380
1606
  },
1381
1607
  injectFile: (userFileNode) => {
1382
1608
  this.fileManager.add(ast.factory.createFile(userFileNode));
@@ -1384,29 +1610,7 @@ var KubbDriver = class {
1384
1610
  });
1385
1611
  }
1386
1612
  }
1387
- /**
1388
- * Appends a generator to its owning plugin so the generate loop can call it directly.
1389
- *
1390
- * The generator's `schema`, `operation`, and `operations` methods run per node during the AST
1391
- * walk in `#runGenerators`, and their result is routed through `dispatch`. Because a generator is
1392
- * bound to a plugin, generators from different plugins never cross-fire without a name check. The
1393
- * renderer comes from `generator.renderer`; set it to `null` (or leave it unset) to opt out of
1394
- * rendering.
1395
- *
1396
- * Call this method inside `addGenerator()` (in `kubb:plugin:setup`) to wire up a generator.
1397
- */
1398
- registerGenerator(pluginName, generator) {
1399
- const plugin = this.plugins.get(pluginName);
1400
- if (!plugin) return;
1401
- plugin.generators = plugin.generators ? [...plugin.generators, generator] : [generator];
1402
- }
1403
- /**
1404
- * Returns `true` when at least one generator was registered for the given plugin
1405
- * via `addGenerator()` in `kubb:plugin:setup`.
1406
- *
1407
- * Used by the build loop to decide whether to walk the AST and run the generators
1408
- * for a plugin.
1409
- */
1613
+ /** `true` once `addGenerator()` in `kubb:plugin:setup` registered a generator for the plugin. */
1410
1614
  hasHookGenerators(pluginName) {
1411
1615
  return (this.plugins.get(pluginName)?.generators?.length ?? 0) > 0;
1412
1616
  }
@@ -1654,13 +1858,12 @@ var KubbDriver = class {
1654
1858
  options,
1655
1859
  cache
1656
1860
  };
1657
- for (const generator of state.schemaGenerators) {
1658
- if (!(generator.match ? await generator.match(transformedNode, ctx) : true)) continue;
1659
- await this.dispatch({
1660
- result: await generator.schema(transformedNode, ctx),
1661
- renderer: generator.renderer
1662
- });
1663
- }
1861
+ await this.#dispatchNode({
1862
+ generators: state.schemaGenerators,
1863
+ node: transformedNode,
1864
+ ctx,
1865
+ generate: (generator) => generator.schema(transformedNode, ctx)
1866
+ });
1664
1867
  await this.hooks.callHook("kubb:generate:schema", transformedNode, ctx);
1665
1868
  } catch (caughtError) {
1666
1869
  state.error = toError(caughtError);
@@ -1676,19 +1879,19 @@ var KubbDriver = class {
1676
1879
  if (!resolved) continue;
1677
1880
  state.pluginOperations.push(resolved.transformedNode);
1678
1881
  if (state.operationGenerators.length) {
1882
+ const { transformedNode } = resolved;
1679
1883
  const ctx = {
1680
1884
  ...state.generatorContext,
1681
1885
  options: resolved.options,
1682
1886
  cache
1683
1887
  };
1684
- for (const generator of state.operationGenerators) {
1685
- if (!(generator.match ? await generator.match(resolved.transformedNode, ctx) : true)) continue;
1686
- await this.dispatch({
1687
- result: await generator.operation(resolved.transformedNode, ctx),
1688
- renderer: generator.renderer
1689
- });
1690
- }
1691
- await this.hooks.callHook("kubb:generate:operation", resolved.transformedNode, ctx);
1888
+ await this.#dispatchNode({
1889
+ generators: state.operationGenerators,
1890
+ node: transformedNode,
1891
+ ctx,
1892
+ generate: (generator) => generator.operation(transformedNode, ctx)
1893
+ });
1894
+ await this.hooks.callHook("kubb:generate:operation", transformedNode, ctx);
1692
1895
  }
1693
1896
  } catch (caughtError) {
1694
1897
  state.error = toError(caughtError);
@@ -1731,36 +1934,20 @@ var KubbDriver = class {
1731
1934
  }
1732
1935
  return diagnostics;
1733
1936
  }
1734
- /**
1735
- * Stores whatever a generator method or `kubb:generate:*` hook returned.
1736
- *
1737
- * - An `Array<FileNode>` goes straight into `fileManager` via `upsert`.
1738
- * - A renderer element runs through `renderer` (the renderer factory, e.g. JSX) and the
1739
- * produced files go to `fileManager.upsert`.
1740
- * - A falsy result is treated as a no-op. The generator wrote files itself via
1741
- * `ctx.upsertFile`.
1742
- *
1743
- * Pass `renderer` when the result may be a renderer element. Generators that only return
1744
- * `Array<FileNode>` do not need one.
1745
- */
1746
- async dispatch({ result, renderer }) {
1747
- try {
1748
- var _usingCtx$2 = _usingCtx();
1749
- if (!result) return;
1750
- if (Array.isArray(result)) {
1751
- this.fileManager.upsert(...result);
1752
- return;
1753
- }
1754
- if (!renderer) return;
1755
- const instance = _usingCtx$2.u(renderer());
1756
- await instance.render(result);
1757
- this.fileManager.upsert(...instance.files);
1758
- } catch (_) {
1759
- _usingCtx$2.e = _;
1760
- } finally {
1761
- _usingCtx$2.d();
1937
+ /** Runs `node` through the generators whose `match` accepts it; `generate` picks the method for the node kind. */
1938
+ async #dispatchNode({ generators, node, ctx, generate }) {
1939
+ for (const generator of generators) {
1940
+ if (!(generator.match ? await generator.match(node, ctx) : true)) continue;
1941
+ await this.dispatch({
1942
+ result: await generate(generator),
1943
+ renderer: generator.renderer
1944
+ });
1762
1945
  }
1763
1946
  }
1947
+ /** Stores whatever a generator method or `kubb:generate:*` hook returned, see {@link FileManager.dispatch}. */
1948
+ dispatch(params) {
1949
+ return this.fileManager.dispatch(params);
1950
+ }
1764
1951
  /**
1765
1952
  * Removes every listener the driver added. Listeners attached directly to `hooks` from outside
1766
1953
  * the driver survive. Called at the end of a build to prevent leaks across repeated builds.
@@ -1778,15 +1965,6 @@ var KubbDriver = class {
1778
1965
  [Symbol.dispose]() {
1779
1966
  this.dispose();
1780
1967
  }
1781
- /**
1782
- * Merges `partial` onto a fresh default resolver and stores the result on `plugin.resolver`,
1783
- * which is the single source `getResolver` and `getPlugin(name).resolver` both read.
1784
- */
1785
- setPluginResolver(pluginName, partial) {
1786
- const plugin = this.plugins.get(pluginName);
1787
- if (!plugin) return;
1788
- plugin.resolver = Resolver.merge(createResolver({ pluginName }), partial);
1789
- }
1790
1968
  getResolver(pluginName) {
1791
1969
  return this.plugins.get(pluginName)?.resolver ?? createResolver({ pluginName });
1792
1970
  }
@@ -1979,29 +2157,6 @@ function createStorage(build) {
1979
2157
  }
1980
2158
  //#endregion
1981
2159
  //#region src/storages/fsStorage.ts
1982
- const WRITE_CONCURRENCY = 50;
1983
- function createLimiter(concurrency) {
1984
- let active = 0;
1985
- const queue = [];
1986
- function next() {
1987
- if (active >= concurrency) return;
1988
- const run = queue.shift();
1989
- if (!run) return;
1990
- active++;
1991
- run();
1992
- }
1993
- return function limit(task) {
1994
- return new Promise((resolve, reject) => {
1995
- queue.push(() => {
1996
- task().then(resolve, reject).finally(() => {
1997
- active--;
1998
- next();
1999
- });
2000
- });
2001
- next();
2002
- });
2003
- };
2004
- }
2005
2160
  /**
2006
2161
  * Built-in filesystem storage driver.
2007
2162
  *
@@ -2015,8 +2170,7 @@ function createLimiter(concurrency) {
2015
2170
  * a formatter left behind
2016
2171
  * - missing parent directories are created automatically
2017
2172
  * - Bun's native file API is used when running under Bun
2018
- * - concurrent `writeItem` calls are capped at {@link WRITE_CONCURRENCY} in flight, so a caller
2019
- * can fire every file's write without pacing itself
2173
+ * - `FileManager.write` bounds in-flight writes, so this driver does not pace itself
2020
2174
  *
2021
2175
  * @example
2022
2176
  * ```ts
@@ -2030,51 +2184,43 @@ function createLimiter(concurrency) {
2030
2184
  * })
2031
2185
  * ```
2032
2186
  */
2033
- const fsStorage = createStorage(() => {
2034
- const limit = createLimiter(WRITE_CONCURRENCY);
2035
- return {
2036
- name: "fs",
2037
- async existsItem(key) {
2038
- try {
2039
- await access(resolve(key));
2040
- return true;
2041
- } catch (_error) {
2042
- return false;
2043
- }
2044
- },
2045
- async readItem(key) {
2046
- try {
2047
- return await readFile(resolve(key), "utf8");
2048
- } catch (_error) {
2049
- return null;
2050
- }
2051
- },
2052
- async writeItem(key, value, options) {
2053
- await limit(() => write(resolve(key), value, {
2054
- sanity: false,
2055
- stored: options?.stored
2056
- }));
2057
- },
2058
- async removeItem(key) {
2059
- await rm(resolve(key), { force: true });
2060
- },
2061
- async readKeys(base) {
2062
- const resolvedBase = resolve(base ?? process.cwd());
2063
- const keys = [];
2064
- try {
2065
- for await (const entry of glob("**/*", {
2066
- cwd: resolvedBase,
2067
- withFileTypes: true
2068
- })) if (entry.isFile()) keys.push(toPosixPath(relative(resolvedBase, join(entry.parentPath, entry.name))));
2069
- } catch (_error) {}
2070
- return keys;
2071
- },
2072
- async empty(base) {
2073
- if (!base) return;
2074
- await clean(resolve(base));
2187
+ const fsStorage = createStorage(() => ({
2188
+ name: "fs",
2189
+ async existsItem(key) {
2190
+ return exists(resolve(key));
2191
+ },
2192
+ async readItem(key) {
2193
+ try {
2194
+ return await readFile(resolve(key), "utf8");
2195
+ } catch (_error) {
2196
+ return null;
2075
2197
  }
2076
- };
2077
- });
2198
+ },
2199
+ async writeItem(key, value, options) {
2200
+ await write(resolve(key), value, {
2201
+ sanity: false,
2202
+ stored: options?.stored
2203
+ });
2204
+ },
2205
+ async removeItem(key) {
2206
+ await rm(resolve(key), { force: true });
2207
+ },
2208
+ async readKeys(base) {
2209
+ const resolvedBase = resolve(base ?? process.cwd());
2210
+ const keys = [];
2211
+ try {
2212
+ for await (const entry of glob("**/*", {
2213
+ cwd: resolvedBase,
2214
+ withFileTypes: true
2215
+ })) if (entry.isFile()) keys.push(toPosixPath(relative(resolvedBase, join(entry.parentPath, entry.name))));
2216
+ } catch (_error) {}
2217
+ return keys;
2218
+ },
2219
+ async empty(base) {
2220
+ if (!base) return;
2221
+ await clean(resolve(base));
2222
+ }
2223
+ }));
2078
2224
  //#endregion
2079
2225
  //#region src/storages/cacheStorage.ts
2080
2226
  /**
@@ -2130,7 +2276,202 @@ const cacheStorage = createStorage(({ root = process.cwd() }) => {
2130
2276
  };
2131
2277
  });
2132
2278
  //#endregion
2279
+ //#region src/output/runHook.ts
2280
+ const KILL_GRACE_MS = 2e3;
2281
+ async function settle(proc, hooks, id, commandWithArgs) {
2282
+ let childError = null;
2283
+ let lineError = null;
2284
+ let lines = Promise.resolve();
2285
+ let killTimer;
2286
+ proc.process?.once("error", (error) => {
2287
+ childError = error;
2288
+ killTimer = setTimeout(() => proc.kill("SIGKILL"), KILL_GRACE_MS).unref();
2289
+ });
2290
+ if (hooks.listenerCount("kubb:hook:line") > 0) for (const input of [proc.process?.stdout, proc.process?.stderr]) {
2291
+ if (!input) continue;
2292
+ createInterface({ input }).on("line", (line) => {
2293
+ lines = lines.then(() => hooks.callHook("kubb:hook:line", {
2294
+ id,
2295
+ line
2296
+ })).catch((error) => {
2297
+ lineError ??= toError(error);
2298
+ });
2299
+ });
2300
+ }
2301
+ const output = await Promise.resolve(proc).catch(() => null);
2302
+ clearTimeout(killTimer);
2303
+ await lines;
2304
+ const error = childError ?? lineError;
2305
+ if (error) return {
2306
+ success: false,
2307
+ error
2308
+ };
2309
+ if (output?.exitCode === 0) return {
2310
+ success: true,
2311
+ error: null
2312
+ };
2313
+ return {
2314
+ success: false,
2315
+ error: /* @__PURE__ */ new Error(`Hook execute failed: ${commandWithArgs}`),
2316
+ stdout: output?.stdout,
2317
+ stderr: output?.stderr
2318
+ };
2319
+ }
2320
+ /**
2321
+ * Spawns a command and returns its outcome, announcing it through `kubb:hook:start`,
2322
+ * `kubb:hook:line` (one per stdout or stderr line, only while a listener is attached) and
2323
+ * `kubb:hook:end`. A non-zero exit, a spawn failure, an abort or a throwing line listener returns
2324
+ * `success: false` instead of throwing. The failure travels on the result and `kubb:hook:end`
2325
+ * only, and the caller emits `kubb:success` or a diagnostic, so nothing is reported twice.
2326
+ */
2327
+ async function runHook({ hooks, command, args = [], name, cwd = process$1.cwd(), signal }) {
2328
+ const id = randomUUID();
2329
+ await hooks.callHook("kubb:hook:start", {
2330
+ id,
2331
+ command,
2332
+ name,
2333
+ args
2334
+ });
2335
+ const result = await settle(x(command, [...args], {
2336
+ signal,
2337
+ throwOnError: false,
2338
+ nodeOptions: {
2339
+ cwd,
2340
+ windowsHide: true,
2341
+ stdio: [
2342
+ "ignore",
2343
+ "pipe",
2344
+ "pipe"
2345
+ ],
2346
+ detached: process$1.platform !== "win32"
2347
+ }
2348
+ }), hooks, id, [command, ...args].join(" "));
2349
+ await hooks.callHook("kubb:hook:end", {
2350
+ id,
2351
+ command,
2352
+ name,
2353
+ args,
2354
+ ...result
2355
+ });
2356
+ return result;
2357
+ }
2358
+ //#endregion
2359
+ //#region src/output/runOutputPasses.ts
2360
+ /**
2361
+ * Format and lint are one pass over the output directory that differs only in these values.
2362
+ * `label` and `verb` are spelled out: deriving them from `kind` gives "lintter" and "lintting".
2363
+ */
2364
+ const TOOL_PASSES = [{
2365
+ kind: "format",
2366
+ label: "formatter",
2367
+ verb: "Formatting",
2368
+ tools: formatters,
2369
+ preference: FORMATTER_PREFERENCE,
2370
+ code: Diagnostics.code.formatFailed
2371
+ }, {
2372
+ kind: "lint",
2373
+ label: "linter",
2374
+ verb: "Linting",
2375
+ tools: linters,
2376
+ preference: LINTER_PREFERENCE,
2377
+ code: Diagnostics.code.lintFailed
2378
+ }];
2379
+ /**
2380
+ * Resolves `auto` to an installed tool and runs it. Returns the failure instead of throwing.
2381
+ */
2382
+ async function runToolPass({ pass, setting, outputPath, hooks, cwd, signal }) {
2383
+ const detected = setting === "auto" ? await detectTool(pass.preference, cwd) : setting;
2384
+ if (!detected) {
2385
+ await hooks.callHook("kubb:warn", { message: `No ${pass.label} found (${pass.preference.join(", ")}). Skipping ${pass.verb.toLowerCase()}.` });
2386
+ return null;
2387
+ }
2388
+ if (setting === "auto") await hooks.callHook("kubb:info", { message: `Auto-detected ${pass.label}: ${styleText("dim", detected)}` });
2389
+ const tool = pass.tools[detected];
2390
+ if (!tool || !existsSync(outputPath)) return null;
2391
+ const result = await runHook({
2392
+ hooks,
2393
+ command: tool.command,
2394
+ args: tool.args(outputPath),
2395
+ cwd,
2396
+ signal
2397
+ });
2398
+ if (result.success) {
2399
+ await hooks.callHook("kubb:success", { message: `${pass.verb} with ${styleText("dim", detected)} on ${styleText("dim", outputPath)} successfully` });
2400
+ return null;
2401
+ }
2402
+ return result.error;
2403
+ }
2404
+ /**
2405
+ * Runs `output.format`, `output.lint` and `output.postGenerate` over the generated output and
2406
+ * returns the diagnostics they produced. Each failure is emitted through `Diagnostics.emit` and
2407
+ * returned, so it reaches the summary, the reporters and the exit code; the passes keep going so
2408
+ * one failing tool does not hide the next. `Kubb.generate()` runs this after an error-free build
2409
+ * unless the host passes its own `processOutput`.
2410
+ *
2411
+ * @example
2412
+ * ```ts
2413
+ * const diagnostics = await runOutputPasses({ config, outputPath: '/repo/src/gen', hooks })
2414
+ * ```
2415
+ */
2416
+ async function runOutputPasses({ config, outputPath, hooks, signal }) {
2417
+ const diagnostics = [];
2418
+ const report = async (code, label, error) => {
2419
+ const diagnostic = {
2420
+ code,
2421
+ severity: "error",
2422
+ message: `${label} failed: ${error.message}`,
2423
+ help: "Check that the tool is installed and that the command and its config are correct.",
2424
+ location: { kind: "config" },
2425
+ cause: error
2426
+ };
2427
+ diagnostics.push(diagnostic);
2428
+ await Diagnostics.emit(hooks, diagnostic);
2429
+ };
2430
+ for (const pass of TOOL_PASSES) {
2431
+ const setting = config.output[pass.kind];
2432
+ if (!setting) continue;
2433
+ await hooks.callHook(`kubb:${pass.kind}:start`);
2434
+ const error = await runToolPass({
2435
+ pass,
2436
+ setting,
2437
+ outputPath,
2438
+ hooks,
2439
+ cwd: config.root,
2440
+ signal
2441
+ });
2442
+ if (error) await report(pass.code, pass.label, error);
2443
+ await hooks.callHook(`kubb:${pass.kind}:end`);
2444
+ signal?.throwIfAborted();
2445
+ }
2446
+ const commands = config.output.postGenerate ?? [];
2447
+ if (commands.length === 0) return diagnostics;
2448
+ await hooks.callHook("kubb:hooks:start");
2449
+ for (const entry of commands) {
2450
+ const { command, name } = typeof entry === "string" ? {
2451
+ command: entry,
2452
+ name: void 0
2453
+ } : entry;
2454
+ const [executable, ...args] = tokenize(command);
2455
+ if (!executable) continue;
2456
+ const result = await runHook({
2457
+ hooks,
2458
+ command: executable,
2459
+ args,
2460
+ name,
2461
+ cwd: config.root,
2462
+ signal
2463
+ });
2464
+ if (result.success) await hooks.callHook("kubb:success", { message: `${styleText("dim", name ?? command)} successfully executed` });
2465
+ if (!result.success) await report(Diagnostics.code.postGenerateFailed, "Post-generate command", result.error);
2466
+ signal?.throwIfAborted();
2467
+ }
2468
+ await hooks.callHook("kubb:hooks:end");
2469
+ return diagnostics;
2470
+ }
2471
+ //#endregion
2133
2472
  //#region src/createKubb.ts
2473
+ /** Upper bound of listeners one plugin adds to a hook, sizing the emitter ceiling for large plugin sets. */
2474
+ const HOOK_LISTENERS_PER_PLUGIN = 4;
2134
2475
  function resolveConfig(userConfig) {
2135
2476
  return {
2136
2477
  ...userConfig,
@@ -2148,11 +2489,18 @@ function resolveConfig(userConfig) {
2148
2489
  };
2149
2490
  }
2150
2491
  /**
2492
+ * Only the fs storage writes `output.path`, so only then do the passes have fresh files to run
2493
+ * over; a memory or custom storage would leave them formatting whatever an earlier run left there.
2494
+ */
2495
+ function writesOutputDirectory(storage) {
2496
+ return storage.name === "fs";
2497
+ }
2498
+ /**
2151
2499
  * Whether anything runs over the output directory after the files are written. Only then can the
2152
2500
  * bytes on disk stop matching what Kubb wrote, which is what the manifest exists to track.
2153
2501
  */
2154
- function hasOutputPasses(output) {
2155
- return Boolean(output.format || output.lint || output.postGenerate?.length);
2502
+ function hasOutputPasses({ output, storage }) {
2503
+ return writesOutputDirectory(storage) && Boolean(output.format || output.lint || output.postGenerate?.length);
2156
2504
  }
2157
2505
  /**
2158
2506
  * Kubb code-generation instance bound to a single config entry. Resolves the user
@@ -2175,7 +2523,6 @@ var Kubb = class {
2175
2523
  hooks;
2176
2524
  config;
2177
2525
  #driver = null;
2178
- #storage = null;
2179
2526
  #manifest = null;
2180
2527
  #signal;
2181
2528
  constructor(userConfig, options = {}) {
@@ -2184,8 +2531,7 @@ var Kubb = class {
2184
2531
  this.#signal = options.signal;
2185
2532
  }
2186
2533
  get storage() {
2187
- if (!this.#storage) throw new Error("[kubb] setup() must be called before accessing storage");
2188
- return this.#storage;
2534
+ return this.config.storage;
2189
2535
  }
2190
2536
  get driver() {
2191
2537
  if (!this.#driver) throw new Error("[kubb] setup() must be called before accessing driver");
@@ -2198,7 +2544,7 @@ var Kubb = class {
2198
2544
  const signal = this.#signal;
2199
2545
  signal?.throwIfAborted();
2200
2546
  const config = this.config;
2201
- const manifest = hasOutputPasses(config.output) ? await createOutputManifest({
2547
+ const manifest = hasOutputPasses(config) ? await createOutputManifest({
2202
2548
  storage: config.storage,
2203
2549
  cache: cacheStorage({ root: config.root })
2204
2550
  }) : void 0;
@@ -2207,7 +2553,7 @@ var Kubb = class {
2207
2553
  manifest,
2208
2554
  signal
2209
2555
  });
2210
- this.hooks.setMaxListeners(Math.max(10, config.plugins.length * 4));
2556
+ this.hooks.setMaxListeners(Math.max(10, config.plugins.length * HOOK_LISTENERS_PER_PLUGIN));
2211
2557
  if (config.output.clean) {
2212
2558
  const cleanPath = resolve(config.root, config.output.path);
2213
2559
  if (isPathInside(config.root, cleanPath)) throw new Diagnostics.Error({
@@ -2221,7 +2567,6 @@ var Kubb = class {
2221
2567
  }
2222
2568
  await driver.setup();
2223
2569
  this.#driver = driver;
2224
- this.#storage = config.storage;
2225
2570
  this.#manifest = manifest ?? null;
2226
2571
  }
2227
2572
  /**
@@ -2308,9 +2653,12 @@ var Kubb = class {
2308
2653
  diagnostics
2309
2654
  };
2310
2655
  }
2311
- const outputDiagnostics = options.processOutput ? await options.processOutput({
2656
+ const processOutput = options.processOutput ?? runOutputPasses;
2657
+ const outputDiagnostics = writesOutputDirectory(config.storage) ? await processOutput({
2312
2658
  config,
2313
- outputPath: resolve(config.root, config.output.path)
2659
+ outputPath: resolve(config.root, config.output.path),
2660
+ hooks,
2661
+ signal
2314
2662
  }) : [];
2315
2663
  const finalDiagnostics = [...diagnostics, ...outputDiagnostics];
2316
2664
  const failed = Diagnostics.hasError(outputDiagnostics);
@@ -2551,6 +2899,44 @@ function createCliReporter({ render = consoleRenderer } = {}) {
2551
2899
  */
2552
2900
  const cliReporter = createCliReporter();
2553
2901
  //#endregion
2902
+ //#region src/storages/kubbStorage.ts
2903
+ function ensurePrivateDir(dir) {
2904
+ mkdirSync(dir, {
2905
+ recursive: true,
2906
+ mode: 448
2907
+ });
2908
+ chmodSync(dir, 448);
2909
+ return dir;
2910
+ }
2911
+ /**
2912
+ * Folder Kubb keeps its own files in, created with mode 0700. `base` resolves inside `KUBB_HOME`
2913
+ * (default `~/.kubb`). When that folder is not writable, it falls back to a folder in the OS temp directory.
2914
+ *
2915
+ * @example
2916
+ * `resolveKubbDir('cache') // '/home/me/.kubb/cache'`
2917
+ */
2918
+ function resolveKubbDir(base = "") {
2919
+ const dir = resolve(process$1.env.KUBB_HOME ?? join(homedir(), ".kubb"), base);
2920
+ try {
2921
+ return ensurePrivateDir(dir);
2922
+ } catch {
2923
+ return ensurePrivateDir(join(tmpdir(), "kubb", hash("sha256", dir).slice(0, 16)));
2924
+ }
2925
+ }
2926
+ /**
2927
+ * unstorage on the fs driver, rooted at {@link resolveKubbDir}. The fs driver cannot set a file
2928
+ * mode, so the 0700 folder keeps files such as a stored token private.
2929
+ *
2930
+ * @example
2931
+ * ```ts
2932
+ * const storage = kubbStorage({ base: 'cache' })
2933
+ * await storage.setItem('machine-secret', secret)
2934
+ * ```
2935
+ */
2936
+ function kubbStorage({ base } = {}) {
2937
+ return createStorage$1({ driver: fsDriver({ base: resolveKubbDir(base) }) });
2938
+ }
2939
+ //#endregion
2554
2940
  //#region src/reporters/fileReporter.ts
2555
2941
  /**
2556
2942
  * Builds the `## Summary` section: the same counts the cli and json reporters expose, as a list of
@@ -2627,12 +3013,12 @@ const fileReporter = createReporter({
2627
3013
  const content = stripVTControlCharacters([header, ...sections.map((section) => section.join("\n"))].join("\n\n"));
2628
3014
  const baseName = `${[
2629
3015
  "kubb",
2630
- config.name,
3016
+ config.name?.replace(/[^a-zA-Z0-9_-]+/g, "-").replace(/^-+|-+$/g, ""),
2631
3017
  Date.now()
2632
3018
  ].filter(Boolean).join("-")}.log`;
2633
- const pathName = resolve(process$1.cwd(), ".kubb", baseName);
2634
- await write(pathName, `${content}\n`);
2635
- console.error(`Debug log written to ${relative(process$1.cwd(), pathName)}`);
3019
+ const dir = resolveKubbDir(resolve(process$1.cwd(), ".kubb"));
3020
+ await kubbStorage({ base: dir }).setItem(baseName, `${content}\n`);
3021
+ console.error(`Debug log written to ${relative(process$1.cwd(), join(dir, baseName))}`);
2636
3022
  }
2637
3023
  });
2638
3024
  //#endregion
@@ -2674,15 +3060,16 @@ const htmlReporter = createReporter({
2674
3060
  result.config.name?.replace(/[^a-zA-Z0-9_-]+/g, "-").replace(/^-+|-+$/g, ""),
2675
3061
  Date.now()
2676
3062
  ].filter(Boolean).join("-");
2677
- const pathName = resolve(process.cwd(), ".kubb", baseName);
3063
+ const dir = resolveKubbDir(resolve(process.cwd(), ".kubb"));
3064
+ const storage = kubbStorage({ base: dir });
2678
3065
  const assets = new URL("./html/", import.meta.url);
2679
3066
  const [html, ui] = await Promise.all([read(fileURLToPath(new URL("index.html", assets))), read(fileURLToPath(new URL("ui.iife.js", assets)))]);
2680
3067
  await Promise.all([
2681
- write(resolve(pathName, "index.html"), html),
2682
- write(resolve(pathName, "ui.iife.js"), ui),
2683
- write(resolve(pathName, "data.js"), serializeReport(result))
3068
+ storage.setItem(`${baseName}/index.html`, html),
3069
+ storage.setItem(`${baseName}/ui.iife.js`, ui),
3070
+ storage.setItem(`${baseName}/data.js`, serializeReport(result))
2684
3071
  ]);
2685
- const reportPath = resolve(pathName, "index.html");
3072
+ const reportPath = join(dir, baseName, "index.html");
2686
3073
  console.error(`HTML report written to ${relative(process.cwd(), reportPath)}`);
2687
3074
  openInBrowser(reportPath);
2688
3075
  }
@@ -2837,6 +3224,6 @@ const memoryStorage = createStorage(() => {
2837
3224
  };
2838
3225
  });
2839
3226
  //#endregion
2840
- export { Diagnostics, Hookable, KubbDriver, Resolver, applyConfigDefaults, cacheStorage, cliReporter, createAdapter, createCliReporter, createKubb, createRenderer, createReporter, createResolver, createStorage, defineGenerator, defineParser, definePlugin, fileReporter, fsStorage, getInputKind, htmlReporter, jsonReporter, logLevel, memoryStorage, resolveCacheDir };
3227
+ export { Diagnostics, Hookable, KubbDriver, Resolver, applyConfigDefaults, cacheStorage, cliReporter, createAdapter, createCliReporter, createKubb, createRenderer, createReporter, createResolver, createStorage, defineGenerator, defineParser, definePlugin, fileReporter, fsStorage, getInputKind, htmlReporter, jsonReporter, kubbStorage, logLevel, memoryStorage, resolveCacheDir, resolveKubbDir, runHook, runOutputPasses };
2841
3228
 
2842
3229
  //# sourceMappingURL=index.js.map