@kubb/core 5.0.0-beta.7 → 5.0.0-beta.70

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.
Files changed (49) hide show
  1. package/LICENSE +17 -10
  2. package/README.md +20 -123
  3. package/dist/diagnostics-CJtO1uSM.d.ts +2892 -0
  4. package/dist/index.cjs +2340 -1129
  5. package/dist/index.cjs.map +1 -1
  6. package/dist/index.d.ts +80 -289
  7. package/dist/index.js +2330 -1124
  8. package/dist/index.js.map +1 -1
  9. package/dist/memoryStorage-B4VTTIpQ.js +905 -0
  10. package/dist/memoryStorage-B4VTTIpQ.js.map +1 -0
  11. package/dist/memoryStorage-CfycFGzX.cjs +1043 -0
  12. package/dist/memoryStorage-CfycFGzX.cjs.map +1 -0
  13. package/dist/mocks.cjs +84 -24
  14. package/dist/mocks.cjs.map +1 -1
  15. package/dist/mocks.d.ts +37 -11
  16. package/dist/mocks.js +86 -28
  17. package/dist/mocks.js.map +1 -1
  18. package/package.json +9 -23
  19. package/dist/PluginDriver-BkTRD2H2.js +0 -946
  20. package/dist/PluginDriver-BkTRD2H2.js.map +0 -1
  21. package/dist/PluginDriver-Cadu4ORh.cjs +0 -1037
  22. package/dist/PluginDriver-Cadu4ORh.cjs.map +0 -1
  23. package/dist/types-ChyWgIgi.d.ts +0 -2159
  24. package/src/FileManager.ts +0 -115
  25. package/src/FileProcessor.ts +0 -86
  26. package/src/Kubb.ts +0 -300
  27. package/src/PluginDriver.ts +0 -426
  28. package/src/constants.ts +0 -35
  29. package/src/createAdapter.ts +0 -32
  30. package/src/createKubb.ts +0 -573
  31. package/src/createRenderer.ts +0 -57
  32. package/src/createStorage.ts +0 -70
  33. package/src/defineGenerator.ts +0 -87
  34. package/src/defineLogger.ts +0 -36
  35. package/src/defineMiddleware.ts +0 -62
  36. package/src/defineParser.ts +0 -44
  37. package/src/definePlugin.ts +0 -83
  38. package/src/defineResolver.ts +0 -521
  39. package/src/devtools.ts +0 -59
  40. package/src/index.ts +0 -20
  41. package/src/mocks.ts +0 -178
  42. package/src/renderNode.ts +0 -35
  43. package/src/storages/fsStorage.ts +0 -114
  44. package/src/storages/memoryStorage.ts +0 -55
  45. package/src/types.ts +0 -1305
  46. package/src/utils/diagnostics.ts +0 -18
  47. package/src/utils/isInputPath.ts +0 -10
  48. package/src/utils/packageJSON.ts +0 -99
  49. /package/dist/{chunk--u3MIqq1.js → rolldown-runtime-C0LytTxp.js} +0 -0
@@ -0,0 +1,905 @@
1
+ import "./rolldown-runtime-C0LytTxp.js";
2
+ import { EventEmitter } from "node:events";
3
+ import { mkdir, readFile, rm, writeFile } from "node:fs/promises";
4
+ import { dirname, resolve } from "node:path";
5
+ import { ast } from "@kubb/ast";
6
+ import { extractStringsFromNodes } from "@kubb/ast/utils";
7
+ //#region ../../internals/utils/src/errors.ts
8
+ /**
9
+ * Thrown when one or more errors occur during a Kubb build.
10
+ * Carries the full list of underlying errors on `errors`.
11
+ *
12
+ * @example
13
+ * ```ts
14
+ * throw new BuildError('Build failed', { errors: [err1, err2] })
15
+ * ```
16
+ */
17
+ var BuildError = class extends Error {
18
+ errors;
19
+ constructor(message, options) {
20
+ super(message, { cause: options.cause });
21
+ this.name = "BuildError";
22
+ this.errors = options.errors;
23
+ }
24
+ };
25
+ /**
26
+ * Coerces an unknown thrown value to an `Error` instance.
27
+ * Returns the value as-is when it is already an `Error`; otherwise wraps it with `String(value)`.
28
+ *
29
+ * @example
30
+ * ```ts
31
+ * try { ... } catch(err) {
32
+ * throw new BuildError('Build failed', { cause: toError(err), errors: [] })
33
+ * }
34
+ * ```
35
+ */
36
+ function toError(value) {
37
+ return value instanceof Error ? value : new Error(String(value));
38
+ }
39
+ /**
40
+ * Extracts a human-readable message from any thrown value.
41
+ *
42
+ * @example
43
+ * ```ts
44
+ * getErrorMessage(new Error('oops')) // 'oops'
45
+ * getErrorMessage('plain string') // 'plain string'
46
+ * ```
47
+ */
48
+ function getErrorMessage(value) {
49
+ return value instanceof Error ? value.message : String(value);
50
+ }
51
+ //#endregion
52
+ //#region ../../internals/utils/src/asyncEventEmitter.ts
53
+ /**
54
+ * Typed `EventEmitter` that awaits all async listeners before resolving.
55
+ * Wraps Node's `EventEmitter` with full TypeScript event-map inference.
56
+ *
57
+ * @example
58
+ * ```ts
59
+ * const emitter = new AsyncEventEmitter<{ build: [name: string] }>()
60
+ * emitter.on('build', async (name) => { console.log(name) })
61
+ * await emitter.emit('build', 'petstore') // all listeners awaited
62
+ * ```
63
+ */
64
+ var AsyncEventEmitter = class {
65
+ /**
66
+ * Maximum number of listeners per event before Node emits a memory-leak warning.
67
+ * @default 10
68
+ */
69
+ constructor(maxListener = 10) {
70
+ this.#emitter.setMaxListeners(maxListener);
71
+ }
72
+ #emitter = new EventEmitter();
73
+ /**
74
+ * Emits `eventName` and awaits all registered listeners sequentially.
75
+ * Throws if any listener rejects, wrapping the cause with the event name and serialized arguments.
76
+ *
77
+ * @example
78
+ * ```ts
79
+ * await emitter.emit('build', 'petstore')
80
+ * ```
81
+ */
82
+ emit(eventName, ...eventArgs) {
83
+ const listeners = this.#emitter.listeners(eventName);
84
+ if (listeners.length === 0) return;
85
+ return this.#emitAll(eventName, listeners, eventArgs);
86
+ }
87
+ async #emitAll(eventName, listeners, eventArgs) {
88
+ for (const listener of listeners) try {
89
+ await listener(...eventArgs);
90
+ } catch (err) {
91
+ let serializedArgs;
92
+ try {
93
+ serializedArgs = JSON.stringify(eventArgs);
94
+ } catch {
95
+ serializedArgs = String(eventArgs);
96
+ }
97
+ throw new Error(`Error in async listener for "${eventName}" with eventArgs ${serializedArgs}`, { cause: toError(err) });
98
+ }
99
+ }
100
+ /**
101
+ * Registers a persistent listener for `eventName`.
102
+ *
103
+ * @example
104
+ * ```ts
105
+ * emitter.on('build', async (name) => { console.log(name) })
106
+ * ```
107
+ */
108
+ on(eventName, handler) {
109
+ this.#emitter.on(eventName, handler);
110
+ }
111
+ /**
112
+ * Registers a one-shot listener that removes itself after the first invocation.
113
+ *
114
+ * @example
115
+ * ```ts
116
+ * emitter.onOnce('build', async (name) => { console.log(name) })
117
+ * ```
118
+ */
119
+ onOnce(eventName, handler) {
120
+ const wrapper = (...args) => {
121
+ this.off(eventName, wrapper);
122
+ return handler(...args);
123
+ };
124
+ this.on(eventName, wrapper);
125
+ }
126
+ /**
127
+ * Removes a previously registered listener.
128
+ *
129
+ * @example
130
+ * ```ts
131
+ * emitter.off('build', handler)
132
+ * ```
133
+ */
134
+ off(eventName, handler) {
135
+ this.#emitter.off(eventName, handler);
136
+ }
137
+ /**
138
+ * Returns the number of listeners registered for `eventName`.
139
+ *
140
+ * @example
141
+ * ```ts
142
+ * emitter.on('build', handler)
143
+ * emitter.listenerCount('build') // 1
144
+ * ```
145
+ */
146
+ listenerCount(eventName) {
147
+ return this.#emitter.listenerCount(eventName);
148
+ }
149
+ /**
150
+ * Raises or lowers the per-event listener ceiling before Node warns about a memory leak.
151
+ * Set this above the expected listener count when many listeners attach by design.
152
+ *
153
+ * @example
154
+ * ```ts
155
+ * emitter.setMaxListeners(40)
156
+ * ```
157
+ */
158
+ setMaxListeners(max) {
159
+ this.#emitter.setMaxListeners(max);
160
+ }
161
+ /**
162
+ * Returns the current per-event listener ceiling.
163
+ */
164
+ getMaxListeners() {
165
+ return this.#emitter.getMaxListeners();
166
+ }
167
+ /**
168
+ * Removes all listeners from every event channel.
169
+ *
170
+ * @example
171
+ * ```ts
172
+ * emitter.removeAll()
173
+ * ```
174
+ */
175
+ removeAll() {
176
+ this.#emitter.removeAllListeners();
177
+ }
178
+ };
179
+ //#endregion
180
+ //#region ../../internals/utils/src/casing.ts
181
+ /**
182
+ * Shared implementation for camelCase and PascalCase conversion.
183
+ * Splits on common word boundaries (spaces, hyphens, underscores, dots, slashes, colons)
184
+ * and capitalizes each word according to `pascal`.
185
+ *
186
+ * When `pascal` is `true` the first word is also capitalized (PascalCase), otherwise only subsequent words are.
187
+ */
188
+ function toCamelOrPascal(text, pascal) {
189
+ return text.trim().replace(/([a-z\d])([A-Z])/g, "$1 $2").replace(/([A-Z]+)([A-Z][a-z])/g, "$1 $2").replace(/(\d)([a-z])/g, "$1 $2").split(/[\s\-_./\\:]+/).filter(Boolean).map((word, i) => {
190
+ if (word.length > 1 && word === word.toUpperCase()) return word;
191
+ return (i === 0 && !pascal ? word.charAt(0).toLowerCase() : word.charAt(0).toUpperCase()) + word.slice(1);
192
+ }).join("").replace(/[^a-zA-Z0-9]/g, "");
193
+ }
194
+ /**
195
+ * Converts `text` to camelCase.
196
+ *
197
+ * @example Word boundaries
198
+ * `camelCase('hello-world') // 'helloWorld'`
199
+ *
200
+ * @example With a prefix
201
+ * `camelCase('tag', { prefix: 'create' }) // 'createTag'`
202
+ */
203
+ function camelCase(text, { prefix = "", suffix = "" } = {}) {
204
+ return toCamelOrPascal(`${prefix} ${text} ${suffix}`, false);
205
+ }
206
+ /**
207
+ * Converts `text` to PascalCase.
208
+ *
209
+ * @example Word boundaries
210
+ * `pascalCase('hello-world') // 'HelloWorld'`
211
+ *
212
+ * @example With a suffix
213
+ * `pascalCase('tag', { suffix: 'schema' }) // 'TagSchema'`
214
+ */
215
+ function pascalCase(text, { prefix = "", suffix = "" } = {}) {
216
+ return toCamelOrPascal(`${prefix} ${text} ${suffix}`, true);
217
+ }
218
+ //#endregion
219
+ //#region ../../internals/utils/src/runtime.ts
220
+ /**
221
+ * Detects the JavaScript runtime executing the current process and exposes its name and version.
222
+ *
223
+ * Prefer the shared {@link runtime} instance over constructing your own.
224
+ */
225
+ var Runtime = class {
226
+ /**
227
+ * `true` when the current process is running under Bun.
228
+ *
229
+ * Detection keys off the global `Bun` object rather than `process.versions`,
230
+ * because Bun polyfills `process.versions.node` for Node compatibility and would
231
+ * otherwise look like Node.
232
+ *
233
+ * @example
234
+ * ```ts
235
+ * if (runtime.isBun) {
236
+ * await Bun.write(path, data)
237
+ * }
238
+ * ```
239
+ */
240
+ get isBun() {
241
+ return typeof Bun !== "undefined";
242
+ }
243
+ /**
244
+ * `true` when the current process is running under Deno.
245
+ */
246
+ get isDeno() {
247
+ return typeof globalThis.Deno !== "undefined";
248
+ }
249
+ /**
250
+ * `true` when the current process is running under Node.
251
+ *
252
+ * Bun and Deno are excluded first so a polyfilled `process` does not register as Node.
253
+ */
254
+ get isNode() {
255
+ return !this.isBun && !this.isDeno && typeof process !== "undefined" && process.versions?.node != null;
256
+ }
257
+ /**
258
+ * Name of the runtime executing the current process.
259
+ *
260
+ * @example
261
+ * ```ts
262
+ * runtime.name // 'bun' when run with `bun kubb`, 'node' otherwise
263
+ * ```
264
+ */
265
+ get name() {
266
+ if (this.isBun) return "bun";
267
+ if (this.isDeno) return "deno";
268
+ return "node";
269
+ }
270
+ /**
271
+ * Version of the active runtime, or an empty string when it cannot be read.
272
+ *
273
+ * @example
274
+ * ```ts
275
+ * runtime.version // '1.3.11' under Bun, '22.22.2' under Node
276
+ * ```
277
+ */
278
+ get version() {
279
+ if (this.isBun) return process.versions.bun ?? "";
280
+ if (this.isDeno) return globalThis.Deno?.version?.deno ?? "";
281
+ return process.versions?.node ?? "";
282
+ }
283
+ };
284
+ /**
285
+ * Shared {@link Runtime} instance describing the JavaScript runtime executing the current process.
286
+ */
287
+ const runtime = new Runtime();
288
+ //#endregion
289
+ //#region ../../internals/utils/src/fs.ts
290
+ /**
291
+ * Reads the file at `path` as a UTF-8 string.
292
+ * Uses `Bun.file().text()` when running under Bun, `fs.readFile` otherwise.
293
+ *
294
+ * @example
295
+ * ```ts
296
+ * const source = await read('./src/Pet.ts')
297
+ * ```
298
+ */
299
+ async function read(path) {
300
+ if (runtime.isBun) return Bun.file(path).text();
301
+ return readFile(path, { encoding: "utf8" });
302
+ }
303
+ /**
304
+ * Writes `data` to `path`, trimming leading/trailing whitespace before saving.
305
+ * Skips the write when the trimmed content is empty or identical to what is already on disk.
306
+ * Creates any missing parent directories automatically.
307
+ * When `sanity` is `true`, re-reads the file after writing and throws if the content does not match.
308
+ *
309
+ * @example
310
+ * ```ts
311
+ * await write('./src/Pet.ts', source) // writes and returns trimmed content
312
+ * await write('./src/Pet.ts', source) // null — file unchanged
313
+ * await write('./src/Pet.ts', ' ') // null — empty content skipped
314
+ * ```
315
+ */
316
+ async function write(path, data, options = {}) {
317
+ const trimmed = data.trim();
318
+ if (trimmed === "") return null;
319
+ const resolved = resolve(path);
320
+ if (runtime.isBun) {
321
+ const file = Bun.file(resolved);
322
+ if ((await file.exists() ? await file.text() : null) === trimmed) return null;
323
+ await Bun.write(resolved, trimmed);
324
+ return trimmed;
325
+ }
326
+ try {
327
+ if (await readFile(resolved, { encoding: "utf-8" }) === trimmed) return null;
328
+ } catch {}
329
+ await mkdir(dirname(resolved), { recursive: true });
330
+ await writeFile(resolved, trimmed, { encoding: "utf-8" });
331
+ if (options.sanity) {
332
+ const savedData = await readFile(resolved, { encoding: "utf-8" });
333
+ if (savedData !== trimmed) throw new Error(`Sanity check failed for ${path}\n\nData[${data.length}]:\n${data}\n\nSaved[${savedData.length}]:\n${savedData}\n`);
334
+ return savedData;
335
+ }
336
+ return trimmed;
337
+ }
338
+ /**
339
+ * Recursively removes `path`. Silently succeeds when `path` does not exist.
340
+ *
341
+ * @example
342
+ * ```ts
343
+ * await clean('./dist')
344
+ * ```
345
+ */
346
+ async function clean(path) {
347
+ return rm(path, {
348
+ recursive: true,
349
+ force: true
350
+ });
351
+ }
352
+ /**
353
+ * Converts a filesystem path to use POSIX (`/`) separators.
354
+ *
355
+ * Most of the codebase compares and composes paths as strings (prefix matching, joining for
356
+ * import specifiers, splitting on `/`). On POSIX `path.resolve` already returns `/`-separated
357
+ * paths, but on Windows it returns `\`-separated paths, which breaks every such comparison.
358
+ *
359
+ * Routing every path that crosses a module boundary through `toPosixPath` keeps the rest of the
360
+ * code platform-agnostic. The conversion runs unconditionally so Windows-specific behavior is
361
+ * exercisable from POSIX CI.
362
+ *
363
+ * @example
364
+ * toPosixPath('C:\\repo\\src\\pet.ts') // 'C:/repo/src/pet.ts'
365
+ */
366
+ function toPosixPath(filePath) {
367
+ return filePath.replaceAll("\\", "/");
368
+ }
369
+ /**
370
+ * Builds a nested file path from a dotted name. Splits on dots that precede a letter
371
+ * (so version numbers embedded in operationIds like `v2025.0` stay intact), camelCases
372
+ * every earlier segment, applies `caseLast` to the final segment, and joins with `/`.
373
+ *
374
+ * Empty segments are dropped before joining. They arise when the name starts with a dot
375
+ * followed by a letter (e.g. `..Schema` splits into `['..', 'Schema']` and `'..'` cases to
376
+ * an empty string). Without this a leading `/` would form, which `path.resolve` reads as an
377
+ * absolute path, letting generated files escape the configured output directory.
378
+ *
379
+ * @example Nested path from a dotted name
380
+ * `toFilePath('pet.petId') // 'pet/petId'`
381
+ *
382
+ * @example PascalCase the final segment
383
+ * `toFilePath('pet.Pet', pascalCase) // 'pet/Pet'`
384
+ *
385
+ * @example Suffix applied to the final segment only
386
+ * `toFilePath('tag.tag', (part) => camelCase(part, { suffix: 'schema' })) // 'tag/tagSchema'`
387
+ */
388
+ function toFilePath(name, caseLast = camelCase) {
389
+ const parts = name.split(/\.(?=[a-zA-Z])/);
390
+ return parts.map((part, i) => i === parts.length - 1 ? caseLast(part) : camelCase(part)).filter(Boolean).join("/");
391
+ }
392
+ //#endregion
393
+ //#region src/constants.ts
394
+ /**
395
+ * Plugin `include` filter types that select operations directly. When one of these is set
396
+ * without a `schemaName` include, the generate phase pre-scans operations to compute the set
397
+ * of schemas they reach, so unreachable schemas can be pruned for that plugin.
398
+ */
399
+ const OPERATION_FILTER_TYPES = new Set([
400
+ "tag",
401
+ "operationId",
402
+ "path",
403
+ "method",
404
+ "contentType"
405
+ ]);
406
+ /**
407
+ * Stable codes Kubb attaches to a `Diagnostic`. Each maps to a known failure mode
408
+ * and stays stable so it can be referenced in tooling and (later) docs. Reference
409
+ * these instead of inlining the string at a throw site.
410
+ */
411
+ const diagnosticCode = {
412
+ /**
413
+ * Fallback for an unstructured error with no specific code.
414
+ */
415
+ unknown: "KUBB_UNKNOWN",
416
+ /**
417
+ * The `input.path` file or URL could not be read.
418
+ */
419
+ inputNotFound: "KUBB_INPUT_NOT_FOUND",
420
+ /**
421
+ * An adapter was configured without an `input`.
422
+ */
423
+ inputRequired: "KUBB_INPUT_REQUIRED",
424
+ /**
425
+ * A `$ref` (or equivalent reference) could not be resolved in the source document.
426
+ */
427
+ refNotFound: "KUBB_REF_NOT_FOUND",
428
+ /**
429
+ * A server variable value is not allowed by its `enum`.
430
+ */
431
+ invalidServerVariable: "KUBB_INVALID_SERVER_VARIABLE",
432
+ /**
433
+ * A required plugin is missing from the config.
434
+ */
435
+ pluginNotFound: "KUBB_PLUGIN_NOT_FOUND",
436
+ /**
437
+ * A plugin threw while generating.
438
+ */
439
+ pluginFailed: "KUBB_PLUGIN_FAILED",
440
+ /**
441
+ * A plugin reported a non-fatal warning through `ctx.warn`.
442
+ */
443
+ pluginWarning: "KUBB_PLUGIN_WARNING",
444
+ /**
445
+ * A plugin reported an informational message through `ctx.info`.
446
+ */
447
+ pluginInfo: "KUBB_PLUGIN_INFO",
448
+ /**
449
+ * A schema uses a `format` Kubb does not map to a specific type. Reserved for
450
+ * adapters to emit as a `warning`.
451
+ */
452
+ unsupportedFormat: "KUBB_UNSUPPORTED_FORMAT",
453
+ /**
454
+ * A referenced schema or operation is marked `deprecated`. Reserved for adapters
455
+ * to emit as an `info`.
456
+ */
457
+ deprecated: "KUBB_DEPRECATED",
458
+ /**
459
+ * An adapter is required but the config has none. The build cannot read the input
460
+ * without one.
461
+ */
462
+ adapterRequired: "KUBB_ADAPTER_REQUIRED",
463
+ /**
464
+ * A resolved output path escapes the output directory, which can stem from a path
465
+ * traversal in the spec or a misconfigured `group.name`.
466
+ */
467
+ pathTraversal: "KUBB_PATH_TRAVERSAL",
468
+ /**
469
+ * A plugin's options are invalid, for example `output.mode: 'file'` paired with a `group` option.
470
+ */
471
+ invalidPluginOptions: "KUBB_INVALID_PLUGIN_OPTIONS",
472
+ /**
473
+ * A post-generate shell hook (`hooks.done`) exited with a failure.
474
+ */
475
+ hookFailed: "KUBB_HOOK_FAILED",
476
+ /**
477
+ * The formatter pass over the generated files failed.
478
+ */
479
+ formatFailed: "KUBB_FORMAT_FAILED",
480
+ /**
481
+ * The linter pass over the generated files failed.
482
+ */
483
+ lintFailed: "KUBB_LINT_FAILED",
484
+ /**
485
+ * Not a failure. Carries a plugin's elapsed time, summed into the run total.
486
+ */
487
+ performance: "KUBB_PERFORMANCE",
488
+ /**
489
+ * Not a failure. A newer Kubb version is available on npm.
490
+ */
491
+ updateAvailable: "KUBB_UPDATE_AVAILABLE"
492
+ };
493
+ //#endregion
494
+ //#region src/createStorage.ts
495
+ /**
496
+ * Defines a custom storage backend. The builder receives user options and
497
+ * returns a `Storage` implementation. Kubb ships with filesystem and in-memory
498
+ * storages. A custom backend writes generated files elsewhere, such as cloud
499
+ * storage or a database.
500
+ *
501
+ * @example In-memory storage (the built-in implementation)
502
+ * ```ts
503
+ * import { createStorage } from '@kubb/core'
504
+ *
505
+ * export const memoryStorage = createStorage(() => {
506
+ * const store = new Map<string, string>()
507
+ *
508
+ * return {
509
+ * name: 'memory',
510
+ * async hasItem(key) {
511
+ * return store.has(key)
512
+ * },
513
+ * async getItem(key) {
514
+ * return store.get(key) ?? null
515
+ * },
516
+ * async setItem(key, value) {
517
+ * store.set(key, value)
518
+ * },
519
+ * async removeItem(key) {
520
+ * store.delete(key)
521
+ * },
522
+ * async getKeys(base) {
523
+ * const keys = [...store.keys()]
524
+ * return base ? keys.filter((k) => k.startsWith(base)) : keys
525
+ * },
526
+ * async clear(base) {
527
+ * if (!base) store.clear()
528
+ * },
529
+ * }
530
+ * })
531
+ * ```
532
+ */
533
+ function createStorage(build) {
534
+ return (options) => build(options ?? {});
535
+ }
536
+ //#endregion
537
+ //#region src/FileManager.ts
538
+ function mergeFile(a, b) {
539
+ return {
540
+ ...a,
541
+ banner: b.banner,
542
+ footer: b.footer,
543
+ copy: b.copy ?? a.copy,
544
+ sources: a.sources.length ? b.sources.length ? [...a.sources, ...b.sources] : a.sources : b.sources,
545
+ imports: a.imports.length ? b.imports.length ? [...a.imports, ...b.imports] : a.imports : b.imports,
546
+ exports: a.exports.length ? b.exports.length ? [...a.exports, ...b.exports] : a.exports : b.exports
547
+ };
548
+ }
549
+ function isIndexPath(path) {
550
+ return path.endsWith("/index.ts") || path === "index.ts";
551
+ }
552
+ function compareFiles(a, b) {
553
+ const lenDiff = a.path.length - b.path.length;
554
+ if (lenDiff !== 0) return lenDiff;
555
+ const aIsIndex = isIndexPath(a.path);
556
+ const bIsIndex = isIndexPath(b.path);
557
+ if (aIsIndex && !bIsIndex) return 1;
558
+ if (!aIsIndex && bIsIndex) return -1;
559
+ return 0;
560
+ }
561
+ /**
562
+ * In-memory file store for generated files. Files sharing a `path` are merged
563
+ * (sources/imports/exports concatenated). The `files` getter is sorted by
564
+ * path length (barrel `index.ts` last within a bucket).
565
+ *
566
+ * @example
567
+ * ```ts
568
+ * const manager = new FileManager()
569
+ * manager.upsert(myFile)
570
+ * manager.files // sorted view
571
+ * ```
572
+ */
573
+ var FileManager = class {
574
+ /**
575
+ * Subscribe to file-store changes. Listeners on `upsert` see each resolved file as it lands
576
+ * through `add` or `upsert`.
577
+ */
578
+ hooks = new AsyncEventEmitter();
579
+ #cache = /* @__PURE__ */ new Map();
580
+ #sorted = null;
581
+ add(...files) {
582
+ return this.#store(files, false);
583
+ }
584
+ upsert(...files) {
585
+ return this.#store(files, true);
586
+ }
587
+ #store(files, mergeExisting) {
588
+ const batch = files.length > 1 ? this.#dedupe(files) : files;
589
+ const resolved = [];
590
+ for (const file of batch) {
591
+ const existing = this.#cache.get(file.path);
592
+ const merged = existing && mergeExisting ? ast.factory.createFile(mergeFile(existing, file)) : ast.factory.createFile(file);
593
+ this.#cache.set(merged.path, merged);
594
+ resolved.push(merged);
595
+ this.hooks.emit("upsert", merged);
596
+ }
597
+ if (resolved.length > 0) this.#sorted = null;
598
+ return resolved;
599
+ }
600
+ #dedupe(files) {
601
+ const seen = /* @__PURE__ */ new Map();
602
+ for (const file of files) {
603
+ const prev = seen.get(file.path);
604
+ seen.set(file.path, prev ? mergeFile(prev, file) : file);
605
+ }
606
+ return [...seen.values()];
607
+ }
608
+ getByPath(path) {
609
+ return this.#cache.get(path) ?? null;
610
+ }
611
+ deleteByPath(path) {
612
+ if (!this.#cache.delete(path)) return;
613
+ this.#sorted = null;
614
+ }
615
+ clear() {
616
+ this.#cache.clear();
617
+ this.#sorted = null;
618
+ }
619
+ /**
620
+ * Releases all stored files and clears every `hooks` listener. Called by the core after
621
+ * `kubb:build:end`.
622
+ */
623
+ dispose() {
624
+ this.clear();
625
+ this.hooks.removeAll();
626
+ }
627
+ [Symbol.dispose]() {
628
+ this.dispose();
629
+ }
630
+ /**
631
+ * All stored files in stable sort order (shortest path first, barrel files
632
+ * last within a length bucket). Returns a cached view, do not mutate.
633
+ */
634
+ get files() {
635
+ return this.#sorted ??= [...this.#cache.values()].sort(compareFiles);
636
+ }
637
+ };
638
+ //#endregion
639
+ //#region src/FileProcessor.ts
640
+ function joinSources(file) {
641
+ const sources = file.sources;
642
+ if (sources.length === 0) return "";
643
+ const parts = [];
644
+ for (const source of sources) {
645
+ const text = extractStringsFromNodes(source.nodes);
646
+ if (text) parts.push(text);
647
+ }
648
+ return parts.join("\n\n");
649
+ }
650
+ async function parseCopy(file) {
651
+ let content;
652
+ try {
653
+ content = await read(file.copy);
654
+ } catch (err) {
655
+ throw new Error(`[kubb] Could not copy file into output: ${file.copy}`, { cause: err });
656
+ }
657
+ return [
658
+ file.banner,
659
+ content,
660
+ file.footer
661
+ ].filter((segment) => Boolean(segment)).map((segment) => segment.trimEnd()).join("\n");
662
+ }
663
+ /**
664
+ * Turns `FileNode`s into source strings and writes them to storage.
665
+ *
666
+ * Two modes share the same instance. Stateless mode (`parse`, `stream`, `run`) just runs the
667
+ * conversion. Queue mode (`enqueue`, `flush`, `drain`) buffers files deduped by path and
668
+ * writes each batch through storage with up to `STREAM_FLUSH_EVERY` requests in flight.
669
+ *
670
+ * `flush` does not wait for its batch to finish, so dispatch can overlap with IO. The next
671
+ * `flush` or `drain` picks the in-flight batch up. `drain` blocks until everything has been
672
+ * written and is meant for the end of a build.
673
+ *
674
+ * To surface build-level hook signals (`kubb:files:processing:*` and friends) subscribe to
675
+ * `hooks` and re-emit on the kubb bus.
676
+ */
677
+ var FileProcessor = class {
678
+ hooks = new AsyncEventEmitter();
679
+ #parsers;
680
+ #storage;
681
+ #extension;
682
+ #pending = /* @__PURE__ */ new Map();
683
+ #runningFlush = null;
684
+ constructor(options) {
685
+ this.#parsers = options.parsers ?? null;
686
+ this.#storage = options.storage;
687
+ this.#extension = options.extension ?? null;
688
+ }
689
+ /**
690
+ * Files waiting in the queue.
691
+ */
692
+ get size() {
693
+ return this.#pending.size;
694
+ }
695
+ async parse(file) {
696
+ if (file.copy) return parseCopy(file);
697
+ const parsers = this.#parsers;
698
+ const parseExtName = this.#extension?.[file.extname] || void 0;
699
+ if (!parsers || !file.extname) return joinSources(file);
700
+ const parser = parsers.get(file.extname);
701
+ if (!parser) return joinSources(file);
702
+ return parser.parse(file, { extname: parseExtName });
703
+ }
704
+ async *stream(files) {
705
+ const total = files.length;
706
+ if (total === 0) return;
707
+ let processed = 0;
708
+ for (const file of files) {
709
+ const source = await this.parse(file);
710
+ processed++;
711
+ yield {
712
+ file,
713
+ source,
714
+ processed,
715
+ total,
716
+ percentage: processed / total * 100
717
+ };
718
+ }
719
+ }
720
+ async run(files) {
721
+ await this.hooks.emit("start", files);
722
+ for await (const { file, source, processed, total, percentage } of this.stream(files)) await this.hooks.emit("update", {
723
+ file,
724
+ source,
725
+ processed,
726
+ percentage,
727
+ total
728
+ });
729
+ await this.hooks.emit("end", files);
730
+ return files;
731
+ }
732
+ /**
733
+ * Adds a file to the next flush. A later `enqueue` for the same path replaces the previous
734
+ * entry, matching `FileManager.upsert`. Fires the `enqueue` event.
735
+ */
736
+ enqueue(file) {
737
+ this.#pending.set(file.path, file);
738
+ this.hooks.emit("enqueue", file);
739
+ }
740
+ /**
741
+ * Starts processing the queued files. Waits for any previous flush to finish (so two
742
+ * batches never run together) and then returns without waiting for the new one. The next
743
+ * `flush` or `drain` picks up the in-flight task.
744
+ */
745
+ async flush() {
746
+ if (this.#runningFlush) await this.#runningFlush;
747
+ if (this.#pending.size === 0) return;
748
+ const batch = [...this.#pending.values()];
749
+ this.#pending.clear();
750
+ this.#runningFlush = this.#processAndWrite(batch).finally(() => {
751
+ this.#runningFlush = null;
752
+ });
753
+ }
754
+ /**
755
+ * Waits for the in-flight flush and writes any files still queued. Fires the `drain` event
756
+ * when both are done.
757
+ */
758
+ async drain() {
759
+ if (this.#runningFlush) await this.#runningFlush;
760
+ if (this.#pending.size > 0) {
761
+ const batch = [...this.#pending.values()];
762
+ this.#pending.clear();
763
+ await this.#processAndWrite(batch);
764
+ }
765
+ await this.hooks.emit("drain");
766
+ }
767
+ async #processAndWrite(files) {
768
+ const storage = this.#storage;
769
+ await this.hooks.emit("start", files);
770
+ const queue = [];
771
+ for await (const item of this.stream(files)) {
772
+ await this.hooks.emit("update", item);
773
+ if (item.source) {
774
+ queue.push(storage.setItem(item.file.path, item.source));
775
+ if (queue.length >= 50) await Promise.all(queue.splice(0));
776
+ }
777
+ }
778
+ await Promise.all(queue);
779
+ await this.hooks.emit("end", files);
780
+ }
781
+ /**
782
+ * Clears every listener and the pending queue.
783
+ */
784
+ dispose() {
785
+ this.hooks.removeAll();
786
+ this.#pending.clear();
787
+ }
788
+ [Symbol.dispose]() {
789
+ this.dispose();
790
+ }
791
+ };
792
+ //#endregion
793
+ //#region \0@oxc-project+runtime@0.135.0/helpers/esm/usingCtx.js
794
+ function _usingCtx() {
795
+ var r = "function" == typeof SuppressedError ? SuppressedError : function(r, e) {
796
+ var n = Error();
797
+ return n.name = "SuppressedError", n.error = r, n.suppressed = e, n;
798
+ };
799
+ var e = {};
800
+ var n = [];
801
+ function using(r, e) {
802
+ if (null != e) {
803
+ if (Object(e) !== e) throw new TypeError("using declarations can only be used with objects, functions, null, or undefined.");
804
+ if (r) var o = e[Symbol.asyncDispose || Symbol["for"]("Symbol.asyncDispose")];
805
+ if (void 0 === o && (o = e[Symbol.dispose || Symbol["for"]("Symbol.dispose")], r)) var t = o;
806
+ if ("function" != typeof o) throw new TypeError("Object is not disposable.");
807
+ t && (o = function o() {
808
+ try {
809
+ t.call(e);
810
+ } catch (r) {
811
+ return Promise.reject(r);
812
+ }
813
+ }), n.push({
814
+ v: e,
815
+ d: o,
816
+ a: r
817
+ });
818
+ } else r && n.push({
819
+ d: e,
820
+ a: r
821
+ });
822
+ return e;
823
+ }
824
+ return {
825
+ e,
826
+ u: using.bind(null, !1),
827
+ a: using.bind(null, !0),
828
+ d: function d() {
829
+ var o;
830
+ var t = this.e;
831
+ var s = 0;
832
+ function next() {
833
+ for (; o = n.pop();) try {
834
+ if (!o.a && 1 === s) return s = 0, n.push(o), Promise.resolve().then(next);
835
+ if (o.d) {
836
+ var r = o.d.call(o.v);
837
+ if (o.a) return s |= 2, Promise.resolve(r).then(next, err);
838
+ } else s |= 1;
839
+ } catch (r) {
840
+ return err(r);
841
+ }
842
+ if (1 === s) return t !== e ? Promise.reject(t) : Promise.resolve();
843
+ if (t !== e) throw t;
844
+ }
845
+ function err(n) {
846
+ return t = t !== e ? new r(n, t) : n, next();
847
+ }
848
+ return next();
849
+ }
850
+ };
851
+ }
852
+ //#endregion
853
+ //#region src/storages/memoryStorage.ts
854
+ /**
855
+ * In-memory storage driver. Useful for testing and dry-run scenarios where
856
+ * generated output should be captured without touching the filesystem.
857
+ *
858
+ * All data lives in a `Map` scoped to the storage instance and is discarded
859
+ * when the instance is garbage-collected.
860
+ *
861
+ * @example
862
+ * ```ts
863
+ * import { memoryStorage } from '@kubb/core'
864
+ * import { defineConfig } from 'kubb'
865
+ *
866
+ * export default defineConfig({
867
+ * input: { path: './petStore.yaml' },
868
+ * output: { path: './src/gen' },
869
+ * storage: memoryStorage(),
870
+ * })
871
+ * ```
872
+ */
873
+ const memoryStorage = createStorage(() => {
874
+ const store = /* @__PURE__ */ new Map();
875
+ return {
876
+ name: "memory",
877
+ async hasItem(key) {
878
+ return store.has(key);
879
+ },
880
+ async getItem(key) {
881
+ return store.get(key) ?? null;
882
+ },
883
+ async setItem(key, value) {
884
+ store.set(key, value);
885
+ },
886
+ async removeItem(key) {
887
+ store.delete(key);
888
+ },
889
+ async getKeys(base) {
890
+ const keys = [...store.keys()];
891
+ return base ? keys.filter((k) => k.startsWith(base)) : keys;
892
+ },
893
+ async clear(base) {
894
+ if (!base) {
895
+ store.clear();
896
+ return;
897
+ }
898
+ for (const key of store.keys()) if (key.startsWith(base)) store.delete(key);
899
+ }
900
+ };
901
+ });
902
+ //#endregion
903
+ export { getErrorMessage as _, createStorage as a, clean as c, write as d, runtime as f, BuildError as g, AsyncEventEmitter as h, FileManager as i, toFilePath as l, pascalCase as m, _usingCtx as n, OPERATION_FILTER_TYPES as o, camelCase as p, FileProcessor as r, diagnosticCode as s, memoryStorage as t, toPosixPath as u };
904
+
905
+ //# sourceMappingURL=memoryStorage-B4VTTIpQ.js.map