@kubb/core 5.0.0-beta.1 → 5.0.0-beta.100

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 +25 -158
  3. package/dist/index.cjs +2262 -1130
  4. package/dist/index.cjs.map +1 -1
  5. package/dist/index.d.ts +107 -295
  6. package/dist/index.js +2253 -1122
  7. package/dist/index.js.map +1 -1
  8. package/dist/mocks.cjs +81 -32
  9. package/dist/mocks.cjs.map +1 -1
  10. package/dist/mocks.d.ts +37 -14
  11. package/dist/mocks.js +83 -36
  12. package/dist/mocks.js.map +1 -1
  13. package/dist/types-DM7-MGjZ.d.ts +2838 -0
  14. package/dist/usingCtx-BNggxUEL.js +597 -0
  15. package/dist/usingCtx-BNggxUEL.js.map +1 -0
  16. package/dist/usingCtx-CZyLSqds.cjs +705 -0
  17. package/dist/usingCtx-CZyLSqds.cjs.map +1 -0
  18. package/package.json +7 -35
  19. package/dist/PluginDriver-BXibeQk-.cjs +0 -1036
  20. package/dist/PluginDriver-BXibeQk-.cjs.map +0 -1
  21. package/dist/PluginDriver-DV3p2Hky.js +0 -945
  22. package/dist/PluginDriver-DV3p2Hky.js.map +0 -1
  23. package/dist/types-CuNocrbJ.d.ts +0 -2148
  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 -424
  28. package/src/constants.ts +0 -35
  29. package/src/createAdapter.ts +0 -32
  30. package/src/createKubb.ts +0 -548
  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 -19
  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 -1296
  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,597 @@
1
+ import "./rolldown-runtime-C0LytTxp.js";
2
+ import { mkdir, readFile, rm, writeFile } from "node:fs/promises";
3
+ import { dirname, isAbsolute, relative, resolve } from "node:path";
4
+ import { ast, extractStringsFromNodes } from "@kubb/ast";
5
+ import { EventEmitter } from "node:events";
6
+ //#region ../../internals/utils/src/casing.ts
7
+ /**
8
+ * Shared implementation for camelCase and PascalCase conversion.
9
+ * Splits on common word boundaries (spaces, hyphens, underscores, dots, slashes, colons)
10
+ * and capitalizes each word according to `pascal`.
11
+ *
12
+ * When `pascal` is `true` the first word is also capitalized (PascalCase), otherwise only subsequent words are.
13
+ */
14
+ function toCamelOrPascal(text, pascal) {
15
+ 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) => {
16
+ if (word.length > 1 && word === word.toUpperCase()) return word;
17
+ return (i === 0 && !pascal ? word.charAt(0).toLowerCase() : word.charAt(0).toUpperCase()) + word.slice(1);
18
+ }).join("").replace(/[^a-zA-Z0-9]/g, "");
19
+ }
20
+ /**
21
+ * Converts `text` to camelCase.
22
+ *
23
+ * @example Word boundaries
24
+ * `camelCase('hello-world') // 'helloWorld'`
25
+ *
26
+ * @example With a prefix
27
+ * `camelCase('tag', { prefix: 'create' }) // 'createTag'`
28
+ */
29
+ function camelCase(text, { prefix = "", suffix = "" } = {}) {
30
+ return toCamelOrPascal(`${prefix} ${text} ${suffix}`, false);
31
+ }
32
+ //#endregion
33
+ //#region ../../internals/utils/src/errors.ts
34
+ /**
35
+ * Thrown when one or more errors occur during a Kubb build.
36
+ * Carries the full list of underlying errors on `errors`.
37
+ *
38
+ * @example
39
+ * ```ts
40
+ * throw new BuildError('Build failed', { errors: [err1, err2] })
41
+ * ```
42
+ */
43
+ var BuildError = class extends Error {
44
+ errors;
45
+ constructor(message, options) {
46
+ super(message, { cause: options.cause });
47
+ this.name = "BuildError";
48
+ this.errors = options.errors;
49
+ }
50
+ };
51
+ /**
52
+ * Coerces an unknown thrown value to an `Error` instance.
53
+ * Returns the value as-is when it is already an `Error`; otherwise wraps it with `String(value)`.
54
+ *
55
+ * @example
56
+ * ```ts
57
+ * try { ... } catch(err) {
58
+ * throw new BuildError('Build failed', { cause: toError(err), errors: [] })
59
+ * }
60
+ * ```
61
+ */
62
+ function toError(value) {
63
+ return value instanceof Error ? value : new Error(String(value));
64
+ }
65
+ /**
66
+ * Extracts a human-readable message from any thrown value.
67
+ *
68
+ * @example
69
+ * ```ts
70
+ * getErrorMessage(new Error('oops')) // 'oops'
71
+ * getErrorMessage('plain string') // 'plain string'
72
+ * ```
73
+ */
74
+ function getErrorMessage(value) {
75
+ return value instanceof Error ? value.message : String(value);
76
+ }
77
+ //#endregion
78
+ //#region ../../internals/utils/src/runtime.ts
79
+ /**
80
+ * Detects the JavaScript runtime executing the current process and exposes its name and version.
81
+ *
82
+ * Prefer the shared {@link runtime} instance over constructing your own.
83
+ */
84
+ var Runtime = class {
85
+ /**
86
+ * `true` when the current process is running under Bun.
87
+ *
88
+ * Detection keys off the global `Bun` object rather than `process.versions`,
89
+ * because Bun polyfills `process.versions.node` for Node compatibility and would
90
+ * otherwise look like Node.
91
+ *
92
+ * @example
93
+ * ```ts
94
+ * if (runtime.isBun) {
95
+ * await Bun.write(path, data)
96
+ * }
97
+ * ```
98
+ */
99
+ get isBun() {
100
+ return typeof Bun !== "undefined";
101
+ }
102
+ /**
103
+ * `true` when the current process is running under Deno.
104
+ */
105
+ get isDeno() {
106
+ return typeof globalThis.Deno !== "undefined";
107
+ }
108
+ /**
109
+ * `true` when the current process is running under Node.
110
+ *
111
+ * Bun and Deno are excluded first so a polyfilled `process` does not register as Node.
112
+ */
113
+ get isNode() {
114
+ return !this.isBun && !this.isDeno && typeof process !== "undefined" && process.versions?.node != null;
115
+ }
116
+ /**
117
+ * Name of the runtime executing the current process.
118
+ *
119
+ * @example
120
+ * ```ts
121
+ * runtime.name // 'bun' when run with `bun kubb`, 'node' otherwise
122
+ * ```
123
+ */
124
+ get name() {
125
+ if (this.isBun) return "bun";
126
+ if (this.isDeno) return "deno";
127
+ return "node";
128
+ }
129
+ /**
130
+ * Version of the active runtime, or an empty string when it cannot be read.
131
+ *
132
+ * @example
133
+ * ```ts
134
+ * runtime.version // '1.3.11' under Bun, '22.22.2' under Node
135
+ * ```
136
+ */
137
+ get version() {
138
+ if (this.isBun) return process.versions.bun ?? "";
139
+ if (this.isDeno) return globalThis.Deno?.version?.deno ?? "";
140
+ return process.versions?.node ?? "";
141
+ }
142
+ };
143
+ /**
144
+ * Shared {@link Runtime} instance describing the JavaScript runtime executing the current process.
145
+ */
146
+ const runtime = new Runtime();
147
+ //#endregion
148
+ //#region ../../internals/utils/src/fs.ts
149
+ /**
150
+ * Reads the file at `path` as a UTF-8 string.
151
+ * Uses `Bun.file().text()` when running under Bun, `fs.readFile` otherwise.
152
+ *
153
+ * @example
154
+ * ```ts
155
+ * const source = await read('./src/Pet.ts')
156
+ * ```
157
+ */
158
+ async function read(path) {
159
+ if (runtime.isBun) return Bun.file(path).text();
160
+ return readFile(path, { encoding: "utf8" });
161
+ }
162
+ /**
163
+ * Writes `data` to `path`, trimming leading/trailing whitespace before saving.
164
+ * Skips the write when the trimmed content is empty or identical to what is already on disk.
165
+ * Creates any missing parent directories automatically.
166
+ * When `sanity` is `true`, re-reads the file after writing and throws if the content does not match.
167
+ *
168
+ * @example
169
+ * ```ts
170
+ * await write('./src/Pet.ts', source) // writes and returns trimmed content
171
+ * await write('./src/Pet.ts', source) // null — file unchanged
172
+ * await write('./src/Pet.ts', ' ') // null — empty content skipped
173
+ * ```
174
+ */
175
+ async function write(path, data, options = {}) {
176
+ const trimmed = data.trim();
177
+ if (trimmed === "") return null;
178
+ const resolved = resolve(path);
179
+ if (runtime.isBun) {
180
+ const file = Bun.file(resolved);
181
+ if ((await file.exists() ? await file.text() : null) === trimmed) return null;
182
+ await Bun.write(resolved, trimmed);
183
+ return trimmed;
184
+ }
185
+ try {
186
+ if (await readFile(resolved, { encoding: "utf-8" }) === trimmed) return null;
187
+ } catch {}
188
+ await mkdir(dirname(resolved), { recursive: true });
189
+ await writeFile(resolved, trimmed, { encoding: "utf-8" });
190
+ if (options.sanity) {
191
+ const savedData = await readFile(resolved, { encoding: "utf-8" });
192
+ if (savedData !== trimmed) throw new Error(`Sanity check failed for ${path}\n\nData[${data.length}]:\n${data}\n\nSaved[${savedData.length}]:\n${savedData}\n`);
193
+ return savedData;
194
+ }
195
+ return trimmed;
196
+ }
197
+ /**
198
+ * Recursively removes `path`. Silently succeeds when `path` does not exist.
199
+ *
200
+ * @example
201
+ * ```ts
202
+ * await clean('./dist')
203
+ * ```
204
+ */
205
+ async function clean(path) {
206
+ return rm(path, {
207
+ recursive: true,
208
+ force: true
209
+ });
210
+ }
211
+ /**
212
+ * Resolves to `true` when `path` is `parent` itself or nested inside it. Both sides are resolved
213
+ * to absolute paths first, so relative and `..`-containing inputs compare correctly.
214
+ *
215
+ * Guards destructive operations: before wiping an output directory, check that it does not contain
216
+ * the project root, otherwise a `clean` would delete `kubb.config` and every source file.
217
+ *
218
+ * @example
219
+ * isPathInside('./src/gen', '.') // true — nested inside the root
220
+ * isPathInside('.', '.') // true — the same directory counts as inside
221
+ * isPathInside('.', './src/gen') // false — the root is not inside its own output
222
+ * isPathInside('../other', '.') // false — escapes the root
223
+ */
224
+ function isPathInside(path, parent) {
225
+ const resolvedPath = resolve(path);
226
+ const resolvedParent = resolve(parent);
227
+ if (resolvedPath === resolvedParent) return true;
228
+ const rel = relative(resolvedParent, resolvedPath);
229
+ return rel !== "" && !rel.startsWith("..") && !isAbsolute(rel);
230
+ }
231
+ /**
232
+ * Converts a filesystem path to use POSIX (`/`) separators.
233
+ *
234
+ * Most of the codebase compares and composes paths as strings (prefix matching, joining for
235
+ * import specifiers, splitting on `/`). On POSIX `path.resolve` already returns `/`-separated
236
+ * paths, but on Windows it returns `\`-separated paths, which breaks every such comparison.
237
+ *
238
+ * Routing every path that crosses a module boundary through `toPosixPath` keeps the rest of the
239
+ * code platform-agnostic. The conversion runs unconditionally so Windows-specific behavior is
240
+ * exercisable from POSIX CI.
241
+ *
242
+ * @example
243
+ * toPosixPath('C:\\repo\\src\\pet.ts') // 'C:/repo/src/pet.ts'
244
+ */
245
+ function toPosixPath(filePath) {
246
+ return filePath.replaceAll("\\", "/");
247
+ }
248
+ /**
249
+ * Builds a nested file path from a dotted name. Splits on dots that precede a letter
250
+ * (so version numbers embedded in operationIds like `v2025.0` stay intact), camelCases
251
+ * every earlier segment, applies `caseLast` to the final segment, and joins with `/`.
252
+ *
253
+ * Empty segments are dropped before joining. They arise when the name starts with a dot
254
+ * followed by a letter (e.g. `..Schema` splits into `['..', 'Schema']` and `'..'` cases to
255
+ * an empty string). Without this a leading `/` would form, which `path.resolve` reads as an
256
+ * absolute path, letting generated files escape the configured output directory.
257
+ *
258
+ * @example Nested path from a dotted name
259
+ * `toFilePath('pet.petId') // 'pet/petId'`
260
+ *
261
+ * @example PascalCase the final segment
262
+ * `toFilePath('pet.Pet', pascalCase) // 'pet/Pet'`
263
+ *
264
+ * @example Suffix applied to the final segment only
265
+ * `toFilePath('tag.tag', (part) => camelCase(part, { suffix: 'schema' })) // 'tag/tagSchema'`
266
+ */
267
+ function toFilePath(name, caseLast = camelCase) {
268
+ const parts = name.split(/\.(?=[a-zA-Z])/);
269
+ return parts.map((part, i) => i === parts.length - 1 ? caseLast(part) : camelCase(part)).filter(Boolean).join("/");
270
+ }
271
+ //#endregion
272
+ //#region src/Hookable.ts
273
+ /**
274
+ * Typed hook emitter that awaits all async listeners before resolving.
275
+ * Wraps Node's `EventEmitter` with full TypeScript hook-map inference.
276
+ *
277
+ * @example
278
+ * ```ts
279
+ * const hooks = new Hookable<{ build: [name: string] }>()
280
+ * hooks.hook('build', async (name) => { console.log(name) })
281
+ * await hooks.callHook('build', 'petstore') // all listeners awaited
282
+ * ```
283
+ */
284
+ var Hookable = class {
285
+ /**
286
+ * Maximum number of listeners per hook before Node emits a memory-leak warning.
287
+ * @default 10
288
+ */
289
+ constructor(maxListener = 10) {
290
+ this.#emitter.setMaxListeners(maxListener);
291
+ }
292
+ #emitter = new EventEmitter();
293
+ /**
294
+ * Calls `hookName` and awaits all registered listeners sequentially.
295
+ * Throws if any listener rejects, wrapping the cause with the hook name and serialized arguments.
296
+ *
297
+ * @example
298
+ * ```ts
299
+ * await hooks.callHook('build', 'petstore')
300
+ * ```
301
+ */
302
+ callHook(hookName, ...hookArgs) {
303
+ const listeners = this.#emitter.listeners(hookName);
304
+ if (listeners.length === 0) return;
305
+ return this.#emitAll(hookName, listeners, hookArgs);
306
+ }
307
+ async #emitAll(hookName, listeners, hookArgs) {
308
+ for (const listener of listeners) try {
309
+ await listener(...hookArgs);
310
+ } catch (err) {
311
+ let serializedArgs;
312
+ try {
313
+ serializedArgs = JSON.stringify(hookArgs);
314
+ } catch {
315
+ serializedArgs = String(hookArgs);
316
+ }
317
+ throw new Error(`Error in async listener for "${hookName}" with hookArgs ${serializedArgs}`, { cause: toError(err) });
318
+ }
319
+ }
320
+ /**
321
+ * Registers a persistent listener for `hookName` and returns a function that removes it.
322
+ *
323
+ * @example
324
+ * ```ts
325
+ * const unhook = hooks.hook('build', async (name) => { console.log(name) })
326
+ * unhook() // removes it
327
+ * ```
328
+ */
329
+ hook(hookName, handler) {
330
+ this.#emitter.on(hookName, handler);
331
+ return () => this.removeHook(hookName, handler);
332
+ }
333
+ /**
334
+ * Registers every handler in `configHooks` at once and returns a function that removes them
335
+ * all. Undefined entries are skipped, so a partial hook object registers only its present keys.
336
+ *
337
+ * @example
338
+ * ```ts
339
+ * const unhook = hooks.addHooks({ build: onBuild, done: onDone })
340
+ * unhook() // removes both
341
+ * ```
342
+ */
343
+ addHooks(configHooks) {
344
+ const unhooks = Object.keys(configHooks).filter((name) => configHooks[name]).map((name) => this.hook(name, configHooks[name]));
345
+ return () => {
346
+ for (const unhook of unhooks) unhook();
347
+ };
348
+ }
349
+ /**
350
+ * Removes a previously registered listener.
351
+ *
352
+ * @example
353
+ * ```ts
354
+ * hooks.removeHook('build', handler)
355
+ * ```
356
+ */
357
+ removeHook(hookName, handler) {
358
+ this.#emitter.off(hookName, handler);
359
+ }
360
+ /**
361
+ * Returns the number of listeners registered for `hookName`.
362
+ *
363
+ * @example
364
+ * ```ts
365
+ * hooks.hook('build', handler)
366
+ * hooks.listenerCount('build') // 1
367
+ * ```
368
+ */
369
+ listenerCount(hookName) {
370
+ return this.#emitter.listenerCount(hookName);
371
+ }
372
+ /**
373
+ * Raises or lowers the per-hook listener ceiling before Node warns about a memory leak.
374
+ * Set this above the expected listener count when many listeners attach by design.
375
+ *
376
+ * @example
377
+ * ```ts
378
+ * hooks.setMaxListeners(40)
379
+ * ```
380
+ */
381
+ setMaxListeners(max) {
382
+ this.#emitter.setMaxListeners(max);
383
+ }
384
+ /**
385
+ * Removes all listeners from every hook channel.
386
+ *
387
+ * @example
388
+ * ```ts
389
+ * hooks.removeAllHooks()
390
+ * ```
391
+ */
392
+ removeAllHooks() {
393
+ this.#emitter.removeAllListeners();
394
+ }
395
+ };
396
+ //#endregion
397
+ //#region src/FileManager.ts
398
+ function joinSources(file) {
399
+ return file.sources.map((source) => extractStringsFromNodes(source.nodes)).filter(Boolean).join("\n\n");
400
+ }
401
+ async function parseCopy(file) {
402
+ let content;
403
+ try {
404
+ content = await read(file.copy);
405
+ } catch (err) {
406
+ throw new Error(`[kubb] Could not copy file into output: ${file.copy}`, { cause: err });
407
+ }
408
+ return [
409
+ file.banner,
410
+ content,
411
+ file.footer
412
+ ].filter((segment) => Boolean(segment)).map((segment) => segment.trimEnd()).join("\n");
413
+ }
414
+ function mergeFile(a, b) {
415
+ return {
416
+ ...a,
417
+ banner: b.banner,
418
+ footer: b.footer,
419
+ copy: b.copy ?? a.copy,
420
+ sources: a.sources.length ? b.sources.length ? [...a.sources, ...b.sources] : a.sources : b.sources,
421
+ imports: a.imports.length ? b.imports.length ? [...a.imports, ...b.imports] : a.imports : b.imports,
422
+ exports: a.exports.length ? b.exports.length ? [...a.exports, ...b.exports] : a.exports : b.exports
423
+ };
424
+ }
425
+ function isIndexPath(path) {
426
+ return path.endsWith("/index.ts") || path === "index.ts";
427
+ }
428
+ function compareFiles(a, b) {
429
+ const lenDiff = a.path.length - b.path.length;
430
+ if (lenDiff !== 0) return lenDiff;
431
+ const aIsIndex = isIndexPath(a.path);
432
+ const bIsIndex = isIndexPath(b.path);
433
+ if (aIsIndex && !bIsIndex) return 1;
434
+ if (!aIsIndex && bIsIndex) return -1;
435
+ return 0;
436
+ }
437
+ /**
438
+ * In-memory file store for generated files, and the writer that turns them into source
439
+ * strings on `storage`. Files sharing a `path` are merged (sources/imports/exports
440
+ * concatenated). The `files` getter is sorted by path length (barrel `index.ts` last
441
+ * within a bucket).
442
+ *
443
+ * @example
444
+ * ```ts
445
+ * const manager = new FileManager()
446
+ * manager.upsert(myFile)
447
+ * manager.files // sorted view
448
+ * await manager.write(manager.files, { storage: fsStorage() })
449
+ * ```
450
+ */
451
+ var FileManager = class {
452
+ hooks = new Hookable();
453
+ #cache = /* @__PURE__ */ new Map();
454
+ #sorted = null;
455
+ add(...files) {
456
+ return this.#store(files, false);
457
+ }
458
+ upsert(...files) {
459
+ return this.#store(files, true);
460
+ }
461
+ #store(files, mergeExisting) {
462
+ const batch = files.length > 1 ? this.#dedupe(files) : files;
463
+ const resolved = [];
464
+ for (const file of batch) {
465
+ const existing = this.#cache.get(file.path);
466
+ const merged = existing && mergeExisting ? ast.factory.createFile(mergeFile(existing, file)) : ast.factory.createFile(file);
467
+ this.#cache.set(merged.path, merged);
468
+ resolved.push(merged);
469
+ }
470
+ if (resolved.length > 0) this.#sorted = null;
471
+ return resolved;
472
+ }
473
+ #dedupe(files) {
474
+ const seen = /* @__PURE__ */ new Map();
475
+ for (const file of files) {
476
+ const prev = seen.get(file.path);
477
+ seen.set(file.path, prev ? mergeFile(prev, file) : file);
478
+ }
479
+ return [...seen.values()];
480
+ }
481
+ clear() {
482
+ this.#cache.clear();
483
+ this.#sorted = null;
484
+ }
485
+ /**
486
+ * Releases all stored files and clears every `hooks` listener. Called by the core after
487
+ * `kubb:build:end`.
488
+ */
489
+ dispose() {
490
+ this.clear();
491
+ this.hooks.removeAllHooks();
492
+ }
493
+ /**
494
+ * All stored files in stable sort order (shortest path first, barrel files
495
+ * last within a length bucket). Returns a cached view, do not mutate.
496
+ */
497
+ get files() {
498
+ return this.#sorted ??= [...this.#cache.values()].sort(compareFiles);
499
+ }
500
+ /**
501
+ * Converts a file's AST sources (or its `copy` source) into the final on-disk string.
502
+ */
503
+ async parse(file, { parsers } = {}) {
504
+ if (file.copy) return parseCopy(file);
505
+ if (!parsers || !file.extname) return joinSources(file);
506
+ const parser = parsers.get(file.extname);
507
+ if (!parser) return joinSources(file);
508
+ return parser.parse(file);
509
+ }
510
+ /**
511
+ * Converts and writes every file at once, letting `storage.setItem` decide how much of
512
+ * that runs concurrently.
513
+ */
514
+ async write(files, { storage, parsers }) {
515
+ if (files.length === 0) return;
516
+ await this.hooks.callHook("start", files);
517
+ const total = files.length;
518
+ let processed = 0;
519
+ await Promise.all(files.map(async (file) => {
520
+ const source = await this.parse(file, { parsers });
521
+ processed++;
522
+ await this.hooks.callHook("update", {
523
+ file,
524
+ source,
525
+ processed,
526
+ total,
527
+ percentage: processed / total * 100
528
+ });
529
+ if (source) await storage.setItem(file.path, source);
530
+ }));
531
+ await this.hooks.callHook("end", files);
532
+ }
533
+ };
534
+ //#endregion
535
+ //#region \0@oxc-project+runtime@0.139.0/helpers/esm/usingCtx.js
536
+ function _usingCtx() {
537
+ var r = "function" == typeof SuppressedError ? SuppressedError : function(r, e) {
538
+ var n = Error();
539
+ return n.name = "SuppressedError", n.error = r, n.suppressed = e, n;
540
+ };
541
+ var e = {};
542
+ var n = [];
543
+ function using(r, e) {
544
+ if (null != e) {
545
+ if (Object(e) !== e) throw new TypeError("using declarations can only be used with objects, functions, null, or undefined.");
546
+ if (r) var o = e[Symbol.asyncDispose || Symbol["for"]("Symbol.asyncDispose")];
547
+ if (void 0 === o && (o = e[Symbol.dispose || Symbol["for"]("Symbol.dispose")], r)) var t = o;
548
+ if ("function" != typeof o) throw new TypeError("Object is not disposable.");
549
+ t && (o = function o() {
550
+ try {
551
+ t.call(e);
552
+ } catch (r) {
553
+ return Promise.reject(r);
554
+ }
555
+ }), n.push({
556
+ v: e,
557
+ d: o,
558
+ a: r
559
+ });
560
+ } else r && n.push({
561
+ d: e,
562
+ a: r
563
+ });
564
+ return e;
565
+ }
566
+ return {
567
+ e,
568
+ u: using.bind(null, !1),
569
+ a: using.bind(null, !0),
570
+ d: function d() {
571
+ var o;
572
+ var t = this.e;
573
+ var s = 0;
574
+ function next() {
575
+ for (; o = n.pop();) try {
576
+ if (!o.a && 1 === s) return s = 0, n.push(o), Promise.resolve().then(next);
577
+ if (o.d) {
578
+ var r = o.d.call(o.v);
579
+ if (o.a) return s |= 2, Promise.resolve(r).then(next, err);
580
+ } else s |= 1;
581
+ } catch (r) {
582
+ return err(r);
583
+ }
584
+ if (1 === s) return t !== e ? Promise.reject(t) : Promise.resolve();
585
+ if (t !== e) throw t;
586
+ }
587
+ function err(n) {
588
+ return t = t !== e ? new r(n, t) : n, next();
589
+ }
590
+ return next();
591
+ }
592
+ };
593
+ }
594
+ //#endregion
595
+ export { isPathInside as a, write as c, toError as d, camelCase as f, clean as i, BuildError as l, FileManager as n, toFilePath as o, Hookable as r, toPosixPath as s, _usingCtx as t, getErrorMessage as u };
596
+
597
+ //# sourceMappingURL=usingCtx-BNggxUEL.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"usingCtx-BNggxUEL.js","names":["#emitter","NodeEventEmitter","#emitAll","#cache","#store","#dedupe","#sorted"],"sources":["../../../internals/utils/src/casing.ts","../../../internals/utils/src/errors.ts","../../../internals/utils/src/runtime.ts","../../../internals/utils/src/fs.ts","../src/Hookable.ts","../src/FileManager.ts"],"sourcesContent":["type Options = {\n /**\n * Text prepended before casing is applied.\n */\n prefix?: string\n /**\n * Text appended before casing is applied.\n */\n suffix?: string\n}\n\n/**\n * Shared implementation for camelCase and PascalCase conversion.\n * Splits on common word boundaries (spaces, hyphens, underscores, dots, slashes, colons)\n * and capitalizes each word according to `pascal`.\n *\n * When `pascal` is `true` the first word is also capitalized (PascalCase), otherwise only subsequent words are.\n */\nfunction toCamelOrPascal(text: string, pascal: boolean): string {\n return text\n .trim()\n .replace(/([a-z\\d])([A-Z])/g, '$1 $2')\n .replace(/([A-Z]+)([A-Z][a-z])/g, '$1 $2')\n .replace(/(\\d)([a-z])/g, '$1 $2')\n .split(/[\\s\\-_./\\\\:]+/)\n .filter(Boolean)\n .map((word, i) => {\n if (word.length > 1 && word === word.toUpperCase()) return word\n const head = i === 0 && !pascal ? word.charAt(0).toLowerCase() : word.charAt(0).toUpperCase()\n return head + word.slice(1)\n })\n .join('')\n .replace(/[^a-zA-Z0-9]/g, '')\n}\n\n/**\n * Converts `text` to camelCase.\n *\n * @example Word boundaries\n * `camelCase('hello-world') // 'helloWorld'`\n *\n * @example With a prefix\n * `camelCase('tag', { prefix: 'create' }) // 'createTag'`\n */\nexport function camelCase(text: string, { prefix = '', suffix = '' }: Options = {}): string {\n return toCamelOrPascal(`${prefix} ${text} ${suffix}`, false)\n}\n\n/**\n * Converts `text` to PascalCase.\n *\n * @example Word boundaries\n * `pascalCase('hello-world') // 'HelloWorld'`\n *\n * @example With a suffix\n * `pascalCase('tag', { suffix: 'schema' }) // 'TagSchema'`\n */\nexport function pascalCase(text: string, { prefix = '', suffix = '' }: Options = {}): string {\n return toCamelOrPascal(`${prefix} ${text} ${suffix}`, true)\n}\n","/**\n * Thrown when one or more errors occur during a Kubb build.\n * Carries the full list of underlying errors on `errors`.\n *\n * @example\n * ```ts\n * throw new BuildError('Build failed', { errors: [err1, err2] })\n * ```\n */\nexport class BuildError extends Error {\n errors: Array<Error>\n\n constructor(message: string, options: { cause?: Error; errors: Array<Error> }) {\n super(message, { cause: options.cause })\n this.name = 'BuildError'\n this.errors = options.errors\n }\n}\n\n/**\n * Coerces an unknown thrown value to an `Error` instance.\n * Returns the value as-is when it is already an `Error`; otherwise wraps it with `String(value)`.\n *\n * @example\n * ```ts\n * try { ... } catch(err) {\n * throw new BuildError('Build failed', { cause: toError(err), errors: [] })\n * }\n * ```\n */\nexport function toError(value: unknown): Error {\n return value instanceof Error ? value : new Error(String(value))\n}\n\n/**\n * Extracts a human-readable message from any thrown value.\n *\n * @example\n * ```ts\n * getErrorMessage(new Error('oops')) // 'oops'\n * getErrorMessage('plain string') // 'plain string'\n * ```\n */\nexport function getErrorMessage(value: unknown): string {\n return value instanceof Error ? value.message : String(value)\n}\n\n/**\n * Extracts the `.cause` of an `Error` as an `Error`, or `undefined` when absent or not an `Error`.\n *\n * @example\n * ```ts\n * const cause = toCause(buildError) // Error | undefined\n * ```\n */\nexport function toCause(error: Error): Error | undefined {\n return error.cause instanceof Error ? error.cause : undefined\n}\n","/**\n * Name of the JavaScript runtime executing the current process.\n */\ntype RuntimeName = 'bun' | 'deno' | 'node'\n\n/**\n * Detects the JavaScript runtime executing the current process and exposes its name and version.\n *\n * Prefer the shared {@link runtime} instance over constructing your own.\n */\nclass Runtime {\n /**\n * `true` when the current process is running under Bun.\n *\n * Detection keys off the global `Bun` object rather than `process.versions`,\n * because Bun polyfills `process.versions.node` for Node compatibility and would\n * otherwise look like Node.\n *\n * @example\n * ```ts\n * if (runtime.isBun) {\n * await Bun.write(path, data)\n * }\n * ```\n */\n get isBun(): boolean {\n return typeof Bun !== 'undefined'\n }\n\n /**\n * `true` when the current process is running under Deno.\n */\n get isDeno(): boolean {\n return typeof (globalThis as { Deno?: unknown }).Deno !== 'undefined'\n }\n\n /**\n * `true` when the current process is running under Node.\n *\n * Bun and Deno are excluded first so a polyfilled `process` does not register as Node.\n */\n get isNode(): boolean {\n return !this.isBun && !this.isDeno && typeof process !== 'undefined' && process.versions?.node != null\n }\n\n /**\n * Name of the runtime executing the current process.\n *\n * @example\n * ```ts\n * runtime.name // 'bun' when run with `bun kubb`, 'node' otherwise\n * ```\n */\n get name(): RuntimeName {\n if (this.isBun) return 'bun'\n if (this.isDeno) return 'deno'\n\n return 'node'\n }\n\n /**\n * Version of the active runtime, or an empty string when it cannot be read.\n *\n * @example\n * ```ts\n * runtime.version // '1.3.11' under Bun, '22.22.2' under Node\n * ```\n */\n get version(): string {\n if (this.isBun) return process.versions.bun ?? ''\n if (this.isDeno) return (globalThis as { Deno?: { version?: { deno?: string } } }).Deno?.version?.deno ?? ''\n\n return process.versions?.node ?? ''\n }\n}\n\n/**\n * Shared {@link Runtime} instance describing the JavaScript runtime executing the current process.\n */\nexport const runtime = new Runtime()\n","import { access, mkdir, readFile, rm, writeFile } from 'node:fs/promises'\nimport { dirname, isAbsolute, relative, resolve } from 'node:path'\nimport { camelCase } from './casing.ts'\nimport { runtime } from './runtime.ts'\n\n/**\n * Resolves to `true` when the file or directory at `path` exists.\n * Uses `Bun.file().exists()` when running under Bun, `fs.access` otherwise.\n *\n * @example\n * ```ts\n * if (await exists('./kubb.config.ts')) {\n * const content = await read('./kubb.config.ts')\n * }\n * ```\n */\nexport async function exists(path: string): Promise<boolean> {\n if (runtime.isBun) {\n return Bun.file(path).exists()\n }\n return access(path).then(\n () => true,\n () => false,\n )\n}\n\n/**\n * Reads the file at `path` as a UTF-8 string.\n * Uses `Bun.file().text()` when running under Bun, `fs.readFile` otherwise.\n *\n * @example\n * ```ts\n * const source = await read('./src/Pet.ts')\n * ```\n */\nexport async function read(path: string): Promise<string> {\n if (runtime.isBun) {\n return Bun.file(path).text()\n }\n return readFile(path, { encoding: 'utf8' })\n}\n\ntype WriteOptions = {\n /**\n * When `true`, re-reads the file immediately after writing and throws if the\n * content does not match — useful for catching write failures on unreliable file systems.\n */\n sanity?: boolean\n}\n\n/**\n * Writes `data` to `path`, trimming leading/trailing whitespace before saving.\n * Skips the write when the trimmed content is empty or identical to what is already on disk.\n * Creates any missing parent directories automatically.\n * When `sanity` is `true`, re-reads the file after writing and throws if the content does not match.\n *\n * @example\n * ```ts\n * await write('./src/Pet.ts', source) // writes and returns trimmed content\n * await write('./src/Pet.ts', source) // null — file unchanged\n * await write('./src/Pet.ts', ' ') // null — empty content skipped\n * ```\n */\nexport async function write(path: string, data: string, options: WriteOptions = {}): Promise<string | null> {\n const trimmed = data.trim()\n if (trimmed === '') return null\n\n const resolved = resolve(path)\n\n if (runtime.isBun) {\n const file = Bun.file(resolved)\n const oldContent = (await file.exists()) ? await file.text() : null\n if (oldContent === trimmed) return null\n await Bun.write(resolved, trimmed)\n return trimmed\n }\n\n try {\n const oldContent = await readFile(resolved, { encoding: 'utf-8' })\n if (oldContent === trimmed) return null\n } catch {\n /* file doesn't exist yet */\n }\n\n await mkdir(dirname(resolved), { recursive: true })\n await writeFile(resolved, trimmed, { encoding: 'utf-8' })\n\n if (options.sanity) {\n const savedData = await readFile(resolved, { encoding: 'utf-8' })\n if (savedData !== trimmed) {\n throw new Error(`Sanity check failed for ${path}\\n\\nData[${data.length}]:\\n${data}\\n\\nSaved[${savedData.length}]:\\n${savedData}\\n`)\n }\n return savedData\n }\n\n return trimmed\n}\n\n/**\n * Recursively removes `path`. Silently succeeds when `path` does not exist.\n *\n * @example\n * ```ts\n * await clean('./dist')\n * ```\n */\nexport async function clean(path: string): Promise<void> {\n return rm(path, { recursive: true, force: true })\n}\n\n/**\n * Resolves to `true` when `path` is `parent` itself or nested inside it. Both sides are resolved\n * to absolute paths first, so relative and `..`-containing inputs compare correctly.\n *\n * Guards destructive operations: before wiping an output directory, check that it does not contain\n * the project root, otherwise a `clean` would delete `kubb.config` and every source file.\n *\n * @example\n * isPathInside('./src/gen', '.') // true — nested inside the root\n * isPathInside('.', '.') // true — the same directory counts as inside\n * isPathInside('.', './src/gen') // false — the root is not inside its own output\n * isPathInside('../other', '.') // false — escapes the root\n */\nexport function isPathInside(path: string, parent: string): boolean {\n const resolvedPath = resolve(path)\n const resolvedParent = resolve(parent)\n if (resolvedPath === resolvedParent) return true\n\n const rel = relative(resolvedParent, resolvedPath)\n return rel !== '' && !rel.startsWith('..') && !isAbsolute(rel)\n}\n\n/**\n * Converts a filesystem path to use POSIX (`/`) separators.\n *\n * Most of the codebase compares and composes paths as strings (prefix matching, joining for\n * import specifiers, splitting on `/`). On POSIX `path.resolve` already returns `/`-separated\n * paths, but on Windows it returns `\\`-separated paths, which breaks every such comparison.\n *\n * Routing every path that crosses a module boundary through `toPosixPath` keeps the rest of the\n * code platform-agnostic. The conversion runs unconditionally so Windows-specific behavior is\n * exercisable from POSIX CI.\n *\n * @example\n * toPosixPath('C:\\\\repo\\\\src\\\\pet.ts') // 'C:/repo/src/pet.ts'\n */\nexport function toPosixPath(filePath: string): string {\n return filePath.replaceAll('\\\\', '/')\n}\n\n/**\n * Strips the file extension from a path or file name.\n * Only removes the last `.ext` segment when the dot is not part of a directory name.\n *\n * @example\n * trimExtName('petStore.ts') // 'petStore'\n * trimExtName('/src/models/pet.ts') // '/src/models/pet'\n * trimExtName('/project.v2/gen/pet.ts') // '/project.v2/gen/pet'\n * trimExtName('noExtension') // 'noExtension'\n */\nexport function trimExtName(text: string): string {\n const dotIndex = text.lastIndexOf('.')\n if (dotIndex > 0 && !text.includes('/', dotIndex)) {\n return text.slice(0, dotIndex)\n }\n return text\n}\n\n/**\n * Builds a nested file path from a dotted name. Splits on dots that precede a letter\n * (so version numbers embedded in operationIds like `v2025.0` stay intact), camelCases\n * every earlier segment, applies `caseLast` to the final segment, and joins with `/`.\n *\n * Empty segments are dropped before joining. They arise when the name starts with a dot\n * followed by a letter (e.g. `..Schema` splits into `['..', 'Schema']` and `'..'` cases to\n * an empty string). Without this a leading `/` would form, which `path.resolve` reads as an\n * absolute path, letting generated files escape the configured output directory.\n *\n * @example Nested path from a dotted name\n * `toFilePath('pet.petId') // 'pet/petId'`\n *\n * @example PascalCase the final segment\n * `toFilePath('pet.Pet', pascalCase) // 'pet/Pet'`\n *\n * @example Suffix applied to the final segment only\n * `toFilePath('tag.tag', (part) => camelCase(part, { suffix: 'schema' })) // 'tag/tagSchema'`\n */\nexport function toFilePath(name: string, caseLast: (part: string) => string = camelCase): string {\n const parts = name.split(/\\.(?=[a-zA-Z])/)\n return parts\n .map((part, i) => (i === parts.length - 1 ? caseLast(part) : camelCase(part)))\n .filter(Boolean)\n .join('/')\n}\n","import { EventEmitter as NodeEventEmitter } from 'node:events'\nimport { toError } from '@internals/utils'\n\n/**\n * A function that can be registered as a hook listener, synchronous or async. Any return value is\n * allowed and ignored, so handlers that return a result for their own callers still register.\n */\ntype AsyncListener<TArgs extends Array<unknown>> = (...args: TArgs) => unknown\n\n/**\n * Typed hook emitter that awaits all async listeners before resolving.\n * Wraps Node's `EventEmitter` with full TypeScript hook-map inference.\n *\n * @example\n * ```ts\n * const hooks = new Hookable<{ build: [name: string] }>()\n * hooks.hook('build', async (name) => { console.log(name) })\n * await hooks.callHook('build', 'petstore') // all listeners awaited\n * ```\n */\nexport class Hookable<THooks extends { [K in keyof THooks]: Array<unknown> }> {\n /**\n * Maximum number of listeners per hook before Node emits a memory-leak warning.\n * @default 10\n */\n constructor(maxListener = 10) {\n this.#emitter.setMaxListeners(maxListener)\n }\n\n #emitter = new NodeEventEmitter()\n\n /**\n * Calls `hookName` and awaits all registered listeners sequentially.\n * Throws if any listener rejects, wrapping the cause with the hook name and serialized arguments.\n *\n * @example\n * ```ts\n * await hooks.callHook('build', 'petstore')\n * ```\n */\n callHook<THookName extends keyof THooks & string>(hookName: THookName, ...hookArgs: THooks[THookName]): Promise<void> | void {\n const listeners = this.#emitter.listeners(hookName) as Array<AsyncListener<THooks[THookName]>>\n\n if (listeners.length === 0) {\n return\n }\n\n return this.#emitAll(hookName, listeners, hookArgs)\n }\n\n async #emitAll<THookName extends keyof THooks & string>(\n hookName: THookName,\n listeners: Array<AsyncListener<THooks[THookName]>>,\n hookArgs: THooks[THookName],\n ): Promise<void> {\n for (const listener of listeners) {\n try {\n await listener(...hookArgs)\n } catch (err) {\n let serializedArgs: string\n try {\n serializedArgs = JSON.stringify(hookArgs)\n } catch {\n serializedArgs = String(hookArgs)\n }\n throw new Error(`Error in async listener for \"${hookName}\" with hookArgs ${serializedArgs}`, { cause: toError(err) })\n }\n }\n }\n\n /**\n * Registers a persistent listener for `hookName` and returns a function that removes it.\n *\n * @example\n * ```ts\n * const unhook = hooks.hook('build', async (name) => { console.log(name) })\n * unhook() // removes it\n * ```\n */\n hook<THookName extends keyof THooks & string>(hookName: THookName, handler: AsyncListener<THooks[THookName]>): () => void {\n this.#emitter.on(hookName, handler as AsyncListener<Array<unknown>>)\n return () => this.removeHook(hookName, handler)\n }\n\n /**\n * Registers every handler in `configHooks` at once and returns a function that removes them\n * all. Undefined entries are skipped, so a partial hook object registers only its present keys.\n *\n * @example\n * ```ts\n * const unhook = hooks.addHooks({ build: onBuild, done: onDone })\n * unhook() // removes both\n * ```\n */\n addHooks(configHooks: Partial<{ [K in keyof THooks & string]: AsyncListener<THooks[K]> }>): () => void {\n const unhooks = (Object.keys(configHooks) as Array<keyof THooks & string>)\n .filter((name) => configHooks[name])\n .map((name) => this.hook(name, configHooks[name]!))\n\n return () => {\n for (const unhook of unhooks) unhook()\n }\n }\n\n /**\n * Removes a previously registered listener.\n *\n * @example\n * ```ts\n * hooks.removeHook('build', handler)\n * ```\n */\n removeHook<THookName extends keyof THooks & string>(hookName: THookName, handler: AsyncListener<THooks[THookName]>): void {\n this.#emitter.off(hookName, handler as AsyncListener<Array<unknown>>)\n }\n\n /**\n * Returns the number of listeners registered for `hookName`.\n *\n * @example\n * ```ts\n * hooks.hook('build', handler)\n * hooks.listenerCount('build') // 1\n * ```\n */\n listenerCount<THookName extends keyof THooks & string>(hookName: THookName): number {\n return this.#emitter.listenerCount(hookName)\n }\n\n /**\n * Raises or lowers the per-hook listener ceiling before Node warns about a memory leak.\n * Set this above the expected listener count when many listeners attach by design.\n *\n * @example\n * ```ts\n * hooks.setMaxListeners(40)\n * ```\n */\n setMaxListeners(max: number): void {\n this.#emitter.setMaxListeners(max)\n }\n\n /**\n * Removes all listeners from every hook channel.\n *\n * @example\n * ```ts\n * hooks.removeAllHooks()\n * ```\n */\n removeAllHooks(): void {\n this.#emitter.removeAllListeners()\n }\n}\n","import { read } from '@internals/utils'\nimport { ast, extractStringsFromNodes, type CodeNode, type FileNode } from '@kubb/ast'\nimport type { Storage } from './createStorage.ts'\nimport type { Parser } from './defineParser.ts'\nimport { Hookable } from './Hookable.ts'\n\n/**\n * Hooks fired around a `FileManager#write` batch: `start` before it, `update` per file, `end` after.\n */\nexport type FileManagerHooks = {\n start: [files: Array<FileNode>]\n update: [params: { file: FileNode; source?: string; processed: number; total: number; percentage: number }]\n end: [files: Array<FileNode>]\n}\n\ntype ParseOptions = {\n parsers?: Map<FileNode['extname'], Parser>\n}\n\ntype WriteOptions = ParseOptions & {\n storage: Storage\n}\n\nfunction joinSources(file: FileNode): string {\n return file.sources\n .map((source) => extractStringsFromNodes(source.nodes as Array<CodeNode>))\n .filter(Boolean)\n .join('\\n\\n')\n}\n\nasync function parseCopy(file: FileNode): Promise<string> {\n let content: string\n try {\n content = await read(file.copy as string)\n } catch (err) {\n throw new Error(`[kubb] Could not copy file into output: ${file.copy}`, { cause: err })\n }\n\n return [file.banner, content, file.footer]\n .filter((segment): segment is string => Boolean(segment))\n .map((segment) => segment.trimEnd())\n .join('\\n')\n}\n\nfunction mergeFile<TMeta extends object = object>(a: FileNode<TMeta>, b: FileNode<TMeta>): FileNode<TMeta> {\n return {\n ...a,\n // Incoming file (b) takes precedence for banner/footer so a barrel file (whose\n // banner/footer the barrel plugin resolves last) wins over a plugin-generated\n // file at the same path.\n banner: b.banner,\n footer: b.footer,\n // A verbatim-copy file cannot be merged with rendered content; the incoming `copy` wins.\n copy: b.copy ?? a.copy,\n sources: a.sources.length ? (b.sources.length ? [...a.sources, ...b.sources] : a.sources) : b.sources,\n imports: a.imports.length ? (b.imports.length ? [...a.imports, ...b.imports] : a.imports) : b.imports,\n exports: a.exports.length ? (b.exports.length ? [...a.exports, ...b.exports] : a.exports) : b.exports,\n }\n}\n\nfunction isIndexPath(path: string): boolean {\n return path.endsWith('/index.ts') || path === 'index.ts'\n}\n\n// Sort order: shortest path first. Within a length bucket, index.ts barrels last.\nfunction compareFiles(a: FileNode, b: FileNode): number {\n const lenDiff = a.path.length - b.path.length\n if (lenDiff !== 0) return lenDiff\n const aIsIndex = isIndexPath(a.path)\n const bIsIndex = isIndexPath(b.path)\n if (aIsIndex && !bIsIndex) return 1\n if (!aIsIndex && bIsIndex) return -1\n\n return 0\n}\n\n/**\n * In-memory file store for generated files, and the writer that turns them into source\n * strings on `storage`. Files sharing a `path` are merged (sources/imports/exports\n * concatenated). The `files` getter is sorted by path length (barrel `index.ts` last\n * within a bucket).\n *\n * @example\n * ```ts\n * const manager = new FileManager()\n * manager.upsert(myFile)\n * manager.files // sorted view\n * await manager.write(manager.files, { storage: fsStorage() })\n * ```\n */\nexport class FileManager {\n readonly hooks = new Hookable<FileManagerHooks>()\n readonly #cache = new Map<string, FileNode>()\n // Cached sorted view. Null means stale and rebuilt lazily on next `files` read.\n // Nulled (not mutated) on every write so callers holding a prior reference keep\n // their snapshot. `dispose()` must not silently empty an array the consumer\n // already holds.\n #sorted: Array<FileNode> | null = null\n\n add(...files: Array<FileNode>): Array<FileNode> {\n return this.#store(files, false)\n }\n\n upsert(...files: Array<FileNode>): Array<FileNode> {\n return this.#store(files, true)\n }\n\n #store(files: ReadonlyArray<FileNode>, mergeExisting: boolean): Array<FileNode> {\n const batch = files.length > 1 ? this.#dedupe(files) : files\n const resolved: Array<FileNode> = []\n\n for (const file of batch) {\n const existing = this.#cache.get(file.path)\n const merged = existing && mergeExisting ? ast.factory.createFile(mergeFile(existing, file)) : ast.factory.createFile(file)\n this.#cache.set(merged.path, merged)\n resolved.push(merged)\n }\n\n if (resolved.length > 0) this.#sorted = null\n return resolved\n }\n\n // Merges same-path entries within a batch so the cache update loop stays\n // uniform. Only called for multi-file batches.\n #dedupe(files: ReadonlyArray<FileNode>): Array<FileNode> {\n const seen = new Map<string, FileNode>()\n for (const file of files) {\n const prev = seen.get(file.path)\n seen.set(file.path, prev ? mergeFile(prev, file) : file)\n }\n return [...seen.values()]\n }\n\n clear(): void {\n this.#cache.clear()\n this.#sorted = null\n }\n\n /**\n * Releases all stored files and clears every `hooks` listener. Called by the core after\n * `kubb:build:end`.\n */\n dispose(): void {\n this.clear()\n this.hooks.removeAllHooks()\n }\n\n /**\n * All stored files in stable sort order (shortest path first, barrel files\n * last within a length bucket). Returns a cached view, do not mutate.\n */\n get files(): Array<FileNode> {\n return (this.#sorted ??= [...this.#cache.values()].sort(compareFiles))\n }\n\n /**\n * Converts a file's AST sources (or its `copy` source) into the final on-disk string.\n */\n async parse(file: FileNode, { parsers }: ParseOptions = {}): Promise<string> {\n if (file.copy) {\n return parseCopy(file)\n }\n\n if (!parsers || !file.extname) {\n return joinSources(file)\n }\n\n const parser = parsers.get(file.extname)\n\n if (!parser) {\n return joinSources(file)\n }\n\n return parser.parse(file)\n }\n\n /**\n * Converts and writes every file at once, letting `storage.setItem` decide how much of\n * that runs concurrently.\n */\n async write(files: Array<FileNode>, { storage, parsers }: WriteOptions): Promise<void> {\n if (files.length === 0) return\n\n await this.hooks.callHook('start', files)\n\n const total = files.length\n let processed = 0\n await Promise.all(\n files.map(async (file) => {\n const source = await this.parse(file, { parsers })\n processed++\n await this.hooks.callHook('update', { file, source, processed, total, percentage: (processed / total) * 100 })\n if (source) await storage.setItem(file.path, source)\n }),\n )\n\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