@kubb/core 5.0.0-beta.8 → 5.0.0-beta.81

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