@kubb/core 5.0.0-beta.6 → 5.0.0-beta.60

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 (56) hide show
  1. package/LICENSE +17 -10
  2. package/README.md +25 -158
  3. package/dist/diagnostics-B-UZnFqP.d.ts +2906 -0
  4. package/dist/index.cjs +2497 -1071
  5. package/dist/index.cjs.map +1 -1
  6. package/dist/index.d.ts +80 -273
  7. package/dist/index.js +2487 -1067
  8. package/dist/index.js.map +1 -1
  9. package/dist/memoryStorage-CUj1hrxa.cjs +823 -0
  10. package/dist/memoryStorage-CUj1hrxa.cjs.map +1 -0
  11. package/dist/memoryStorage-CWFzAz4o.js +714 -0
  12. package/dist/memoryStorage-CWFzAz4o.js.map +1 -0
  13. package/dist/mocks.cjs +79 -19
  14. package/dist/mocks.cjs.map +1 -1
  15. package/dist/mocks.d.ts +35 -9
  16. package/dist/mocks.js +80 -22
  17. package/dist/mocks.js.map +1 -1
  18. package/package.json +8 -28
  19. package/src/FileManager.ts +86 -64
  20. package/src/FileProcessor.ts +170 -44
  21. package/src/KubbDriver.ts +908 -0
  22. package/src/Transform.ts +75 -0
  23. package/src/constants.ts +111 -20
  24. package/src/createAdapter.ts +112 -17
  25. package/src/createKubb.ts +140 -517
  26. package/src/createRenderer.ts +43 -28
  27. package/src/createReporter.ts +134 -0
  28. package/src/createStorage.ts +36 -23
  29. package/src/defineGenerator.ts +147 -17
  30. package/src/defineParser.ts +30 -12
  31. package/src/definePlugin.ts +370 -21
  32. package/src/defineResolver.ts +402 -212
  33. package/src/diagnostics.ts +662 -0
  34. package/src/index.ts +8 -8
  35. package/src/mocks.ts +91 -20
  36. package/src/reporters/cliReporter.ts +89 -0
  37. package/src/reporters/fileReporter.ts +103 -0
  38. package/src/reporters/jsonReporter.ts +20 -0
  39. package/src/reporters/report.ts +85 -0
  40. package/src/storages/fsStorage.ts +23 -55
  41. package/src/types.ts +411 -887
  42. package/dist/PluginDriver-BkTRD2H2.js +0 -946
  43. package/dist/PluginDriver-BkTRD2H2.js.map +0 -1
  44. package/dist/PluginDriver-Cadu4ORh.cjs +0 -1037
  45. package/dist/PluginDriver-Cadu4ORh.cjs.map +0 -1
  46. package/dist/types-DVPKmzw_.d.ts +0 -2159
  47. package/src/Kubb.ts +0 -300
  48. package/src/PluginDriver.ts +0 -426
  49. package/src/defineLogger.ts +0 -19
  50. package/src/defineMiddleware.ts +0 -62
  51. package/src/devtools.ts +0 -59
  52. package/src/renderNode.ts +0 -35
  53. package/src/utils/diagnostics.ts +0 -18
  54. package/src/utils/isInputPath.ts +0 -10
  55. package/src/utils/packageJSON.ts +0 -99
  56. /package/dist/{chunk--u3MIqq1.js → chunk-C0LytTxp.js} +0 -0
@@ -0,0 +1,714 @@
1
+ import "./chunk-C0LytTxp.js";
2
+ import { EventEmitter } from "node:events";
3
+ import * as factory from "@kubb/ast/factory";
4
+ import { extractStringsFromNodes } from "@kubb/ast/utils";
5
+ //#region ../../internals/utils/src/errors.ts
6
+ /**
7
+ * Thrown when one or more errors occur during a Kubb build.
8
+ * Carries the full list of underlying errors on `errors`.
9
+ *
10
+ * @example
11
+ * ```ts
12
+ * throw new BuildError('Build failed', { errors: [err1, err2] })
13
+ * ```
14
+ */
15
+ var BuildError = class extends Error {
16
+ errors;
17
+ constructor(message, options) {
18
+ super(message, { cause: options.cause });
19
+ this.name = "BuildError";
20
+ this.errors = options.errors;
21
+ }
22
+ };
23
+ /**
24
+ * Coerces an unknown thrown value to an `Error` instance.
25
+ * Returns the value as-is when it is already an `Error`; otherwise wraps it with `String(value)`.
26
+ *
27
+ * @example
28
+ * ```ts
29
+ * try { ... } catch(err) {
30
+ * throw new BuildError('Build failed', { cause: toError(err), errors: [] })
31
+ * }
32
+ * ```
33
+ */
34
+ function toError(value) {
35
+ return value instanceof Error ? value : new Error(String(value));
36
+ }
37
+ /**
38
+ * Extracts a human-readable message from any thrown value.
39
+ *
40
+ * @example
41
+ * ```ts
42
+ * getErrorMessage(new Error('oops')) // 'oops'
43
+ * getErrorMessage('plain string') // 'plain string'
44
+ * ```
45
+ */
46
+ function getErrorMessage(value) {
47
+ return value instanceof Error ? value.message : String(value);
48
+ }
49
+ //#endregion
50
+ //#region ../../internals/utils/src/asyncEventEmitter.ts
51
+ /**
52
+ * Typed `EventEmitter` that awaits all async listeners before resolving.
53
+ * Wraps Node's `EventEmitter` with full TypeScript event-map inference.
54
+ *
55
+ * @example
56
+ * ```ts
57
+ * const emitter = new AsyncEventEmitter<{ build: [name: string] }>()
58
+ * emitter.on('build', async (name) => { console.log(name) })
59
+ * await emitter.emit('build', 'petstore') // all listeners awaited
60
+ * ```
61
+ */
62
+ var AsyncEventEmitter = class {
63
+ /**
64
+ * Maximum number of listeners per event before Node emits a memory-leak warning.
65
+ * @default 10
66
+ */
67
+ constructor(maxListener = 10) {
68
+ this.#emitter.setMaxListeners(maxListener);
69
+ }
70
+ #emitter = new EventEmitter();
71
+ /**
72
+ * Emits `eventName` and awaits all registered listeners sequentially.
73
+ * Throws if any listener rejects, wrapping the cause with the event name and serialized arguments.
74
+ *
75
+ * @example
76
+ * ```ts
77
+ * await emitter.emit('build', 'petstore')
78
+ * ```
79
+ */
80
+ emit(eventName, ...eventArgs) {
81
+ const listeners = this.#emitter.listeners(eventName);
82
+ if (listeners.length === 0) return;
83
+ return this.#emitAll(eventName, listeners, eventArgs);
84
+ }
85
+ async #emitAll(eventName, listeners, eventArgs) {
86
+ for (const listener of listeners) try {
87
+ await listener(...eventArgs);
88
+ } catch (err) {
89
+ let serializedArgs;
90
+ try {
91
+ serializedArgs = JSON.stringify(eventArgs);
92
+ } catch {
93
+ serializedArgs = String(eventArgs);
94
+ }
95
+ throw new Error(`Error in async listener for "${eventName}" with eventArgs ${serializedArgs}`, { cause: toError(err) });
96
+ }
97
+ }
98
+ /**
99
+ * Registers a persistent listener for `eventName`.
100
+ *
101
+ * @example
102
+ * ```ts
103
+ * emitter.on('build', async (name) => { console.log(name) })
104
+ * ```
105
+ */
106
+ on(eventName, handler) {
107
+ this.#emitter.on(eventName, handler);
108
+ }
109
+ /**
110
+ * Registers a one-shot listener that removes itself after the first invocation.
111
+ *
112
+ * @example
113
+ * ```ts
114
+ * emitter.onOnce('build', async (name) => { console.log(name) })
115
+ * ```
116
+ */
117
+ onOnce(eventName, handler) {
118
+ const wrapper = (...args) => {
119
+ this.off(eventName, wrapper);
120
+ return handler(...args);
121
+ };
122
+ this.on(eventName, wrapper);
123
+ }
124
+ /**
125
+ * Removes a previously registered listener.
126
+ *
127
+ * @example
128
+ * ```ts
129
+ * emitter.off('build', handler)
130
+ * ```
131
+ */
132
+ off(eventName, handler) {
133
+ this.#emitter.off(eventName, handler);
134
+ }
135
+ /**
136
+ * Returns the number of listeners registered for `eventName`.
137
+ *
138
+ * @example
139
+ * ```ts
140
+ * emitter.on('build', handler)
141
+ * emitter.listenerCount('build') // 1
142
+ * ```
143
+ */
144
+ listenerCount(eventName) {
145
+ return this.#emitter.listenerCount(eventName);
146
+ }
147
+ /**
148
+ * Raises or lowers the per-event listener ceiling before Node warns about a memory leak.
149
+ * Set this above the expected listener count when many listeners attach by design.
150
+ *
151
+ * @example
152
+ * ```ts
153
+ * emitter.setMaxListeners(40)
154
+ * ```
155
+ */
156
+ setMaxListeners(max) {
157
+ this.#emitter.setMaxListeners(max);
158
+ }
159
+ /**
160
+ * Returns the current per-event listener ceiling.
161
+ */
162
+ getMaxListeners() {
163
+ return this.#emitter.getMaxListeners();
164
+ }
165
+ /**
166
+ * Removes all listeners from every event channel.
167
+ *
168
+ * @example
169
+ * ```ts
170
+ * emitter.removeAll()
171
+ * ```
172
+ */
173
+ removeAll() {
174
+ this.#emitter.removeAllListeners();
175
+ }
176
+ };
177
+ //#endregion
178
+ //#region ../../internals/utils/src/casing.ts
179
+ /**
180
+ * Shared implementation for camelCase and PascalCase conversion.
181
+ * Splits on common word boundaries (spaces, hyphens, underscores, dots, slashes, colons)
182
+ * and capitalizes each word according to `pascal`.
183
+ *
184
+ * When `pascal` is `true` the first word is also capitalized (PascalCase), otherwise only subsequent words are.
185
+ */
186
+ function toCamelOrPascal(text, pascal) {
187
+ 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) => {
188
+ if (word.length > 1 && word === word.toUpperCase()) return word;
189
+ return (i === 0 && !pascal ? word.charAt(0).toLowerCase() : word.charAt(0).toUpperCase()) + word.slice(1);
190
+ }).join("").replace(/[^a-zA-Z0-9]/g, "");
191
+ }
192
+ /**
193
+ * Converts `text` to camelCase.
194
+ *
195
+ * @example Word boundaries
196
+ * `camelCase('hello-world') // 'helloWorld'`
197
+ *
198
+ * @example With a prefix
199
+ * `camelCase('tag', { prefix: 'create' }) // 'createTag'`
200
+ */
201
+ function camelCase(text, { prefix = "", suffix = "" } = {}) {
202
+ return toCamelOrPascal(`${prefix} ${text} ${suffix}`, false);
203
+ }
204
+ /**
205
+ * Converts `text` to PascalCase.
206
+ *
207
+ * @example Word boundaries
208
+ * `pascalCase('hello-world') // 'HelloWorld'`
209
+ *
210
+ * @example With a suffix
211
+ * `pascalCase('tag', { suffix: 'schema' }) // 'TagSchema'`
212
+ */
213
+ function pascalCase(text, { prefix = "", suffix = "" } = {}) {
214
+ return toCamelOrPascal(`${prefix} ${text} ${suffix}`, true);
215
+ }
216
+ //#endregion
217
+ //#region src/constants.ts
218
+ /**
219
+ * Plugin `include` filter types that select operations directly. When one of these is set
220
+ * without a `schemaName` include, the generate phase pre-scans operations to compute the set
221
+ * of schemas they reach, so unreachable schemas can be pruned for that plugin.
222
+ */
223
+ const OPERATION_FILTER_TYPES = new Set([
224
+ "tag",
225
+ "operationId",
226
+ "path",
227
+ "method",
228
+ "contentType"
229
+ ]);
230
+ /**
231
+ * Stable codes Kubb attaches to a `Diagnostic`. Each maps to a known failure mode
232
+ * and stays stable so it can be referenced in tooling and (later) docs. Reference
233
+ * these instead of inlining the string at a throw site.
234
+ */
235
+ const diagnosticCode = {
236
+ /**
237
+ * Fallback for an unstructured error with no specific code.
238
+ */
239
+ unknown: "KUBB_UNKNOWN",
240
+ /**
241
+ * The `input.path` file or URL could not be read.
242
+ */
243
+ inputNotFound: "KUBB_INPUT_NOT_FOUND",
244
+ /**
245
+ * An adapter was configured without an `input`.
246
+ */
247
+ inputRequired: "KUBB_INPUT_REQUIRED",
248
+ /**
249
+ * A `$ref` (or equivalent reference) could not be resolved in the source document.
250
+ */
251
+ refNotFound: "KUBB_REF_NOT_FOUND",
252
+ /**
253
+ * A server variable value is not allowed by its `enum`.
254
+ */
255
+ invalidServerVariable: "KUBB_INVALID_SERVER_VARIABLE",
256
+ /**
257
+ * A required plugin is missing from the config.
258
+ */
259
+ pluginNotFound: "KUBB_PLUGIN_NOT_FOUND",
260
+ /**
261
+ * A plugin threw while generating.
262
+ */
263
+ pluginFailed: "KUBB_PLUGIN_FAILED",
264
+ /**
265
+ * A plugin reported a non-fatal warning through `ctx.warn`.
266
+ */
267
+ pluginWarning: "KUBB_PLUGIN_WARNING",
268
+ /**
269
+ * A plugin reported an informational message through `ctx.info`.
270
+ */
271
+ pluginInfo: "KUBB_PLUGIN_INFO",
272
+ /**
273
+ * A schema uses a `format` Kubb does not map to a specific type. Reserved for
274
+ * adapters to emit as a `warning`.
275
+ */
276
+ unsupportedFormat: "KUBB_UNSUPPORTED_FORMAT",
277
+ /**
278
+ * A referenced schema or operation is marked `deprecated`. Reserved for adapters
279
+ * to emit as an `info`.
280
+ */
281
+ deprecated: "KUBB_DEPRECATED",
282
+ /**
283
+ * An adapter is required but the config has none. The build cannot read the input
284
+ * without one.
285
+ */
286
+ adapterRequired: "KUBB_ADAPTER_REQUIRED",
287
+ /**
288
+ * A resolved output path escapes the output directory, which can stem from a path
289
+ * traversal in the spec or a misconfigured `group.name`.
290
+ */
291
+ pathTraversal: "KUBB_PATH_TRAVERSAL",
292
+ /**
293
+ * A plugin's options are invalid, for example `output.mode: 'file'` paired with a `group` option.
294
+ */
295
+ invalidPluginOptions: "KUBB_INVALID_PLUGIN_OPTIONS",
296
+ /**
297
+ * A post-generate shell hook (`hooks.done`) exited with a failure.
298
+ */
299
+ hookFailed: "KUBB_HOOK_FAILED",
300
+ /**
301
+ * The formatter pass over the generated files failed.
302
+ */
303
+ formatFailed: "KUBB_FORMAT_FAILED",
304
+ /**
305
+ * The linter pass over the generated files failed.
306
+ */
307
+ lintFailed: "KUBB_LINT_FAILED",
308
+ /**
309
+ * Not a failure. Carries a plugin's elapsed time, summed into the run total.
310
+ */
311
+ performance: "KUBB_PERFORMANCE",
312
+ /**
313
+ * Not a failure. A newer Kubb version is available on npm.
314
+ */
315
+ updateAvailable: "KUBB_UPDATE_AVAILABLE"
316
+ };
317
+ //#endregion
318
+ //#region src/createStorage.ts
319
+ /**
320
+ * Defines a custom storage backend. The builder receives user options and
321
+ * returns a `Storage` implementation. Kubb ships with filesystem and in-memory
322
+ * storages. A custom backend writes generated files elsewhere, such as cloud
323
+ * storage or a database.
324
+ *
325
+ * @example In-memory storage (the built-in implementation)
326
+ * ```ts
327
+ * import { createStorage } from '@kubb/core'
328
+ *
329
+ * export const memoryStorage = createStorage(() => {
330
+ * const store = new Map<string, string>()
331
+ *
332
+ * return {
333
+ * name: 'memory',
334
+ * async hasItem(key) {
335
+ * return store.has(key)
336
+ * },
337
+ * async getItem(key) {
338
+ * return store.get(key) ?? null
339
+ * },
340
+ * async setItem(key, value) {
341
+ * store.set(key, value)
342
+ * },
343
+ * async removeItem(key) {
344
+ * store.delete(key)
345
+ * },
346
+ * async getKeys(base) {
347
+ * const keys = [...store.keys()]
348
+ * return base ? keys.filter((k) => k.startsWith(base)) : keys
349
+ * },
350
+ * async clear(base) {
351
+ * if (!base) store.clear()
352
+ * },
353
+ * }
354
+ * })
355
+ * ```
356
+ */
357
+ function createStorage(build) {
358
+ return (options) => build(options ?? {});
359
+ }
360
+ //#endregion
361
+ //#region src/FileManager.ts
362
+ function mergeFile(a, b) {
363
+ return {
364
+ ...a,
365
+ banner: b.banner,
366
+ footer: b.footer,
367
+ sources: a.sources.length ? b.sources.length ? [...a.sources, ...b.sources] : a.sources : b.sources,
368
+ imports: a.imports.length ? b.imports.length ? [...a.imports, ...b.imports] : a.imports : b.imports,
369
+ exports: a.exports.length ? b.exports.length ? [...a.exports, ...b.exports] : a.exports : b.exports
370
+ };
371
+ }
372
+ function isIndexPath(path) {
373
+ return path.endsWith("/index.ts") || path === "index.ts";
374
+ }
375
+ function compareFiles(a, b) {
376
+ const lenDiff = a.path.length - b.path.length;
377
+ if (lenDiff !== 0) return lenDiff;
378
+ const aIsIndex = isIndexPath(a.path);
379
+ const bIsIndex = isIndexPath(b.path);
380
+ if (aIsIndex && !bIsIndex) return 1;
381
+ if (!aIsIndex && bIsIndex) return -1;
382
+ return 0;
383
+ }
384
+ /**
385
+ * In-memory file store for generated files. Files sharing a `path` are merged
386
+ * (sources/imports/exports concatenated). The `files` getter is sorted by
387
+ * path length (barrel `index.ts` last within a bucket).
388
+ *
389
+ * @example
390
+ * ```ts
391
+ * const manager = new FileManager()
392
+ * manager.upsert(myFile)
393
+ * manager.files // sorted view
394
+ * ```
395
+ */
396
+ var FileManager = class {
397
+ /**
398
+ * Subscribe to file-store changes. Listeners on `upsert` see each resolved file as it lands
399
+ * through `add` or `upsert`.
400
+ */
401
+ hooks = new AsyncEventEmitter();
402
+ #cache = /* @__PURE__ */ new Map();
403
+ #sorted = null;
404
+ add(...files) {
405
+ return this.#store(files, false);
406
+ }
407
+ upsert(...files) {
408
+ return this.#store(files, true);
409
+ }
410
+ #store(files, mergeExisting) {
411
+ const batch = files.length > 1 ? this.#dedupe(files) : files;
412
+ const resolved = [];
413
+ for (const file of batch) {
414
+ const existing = this.#cache.get(file.path);
415
+ const merged = existing && mergeExisting ? factory.createFile(mergeFile(existing, file)) : factory.createFile(file);
416
+ this.#cache.set(merged.path, merged);
417
+ resolved.push(merged);
418
+ this.hooks.emit("upsert", merged);
419
+ }
420
+ if (resolved.length > 0) this.#sorted = null;
421
+ return resolved;
422
+ }
423
+ #dedupe(files) {
424
+ const seen = /* @__PURE__ */ new Map();
425
+ for (const file of files) {
426
+ const prev = seen.get(file.path);
427
+ seen.set(file.path, prev ? mergeFile(prev, file) : file);
428
+ }
429
+ return [...seen.values()];
430
+ }
431
+ getByPath(path) {
432
+ return this.#cache.get(path) ?? null;
433
+ }
434
+ deleteByPath(path) {
435
+ if (!this.#cache.delete(path)) return;
436
+ this.#sorted = null;
437
+ }
438
+ clear() {
439
+ this.#cache.clear();
440
+ this.#sorted = null;
441
+ }
442
+ /**
443
+ * Releases all stored files and clears every `hooks` listener. Called by the core after
444
+ * `kubb:build:end`.
445
+ */
446
+ dispose() {
447
+ this.clear();
448
+ this.hooks.removeAll();
449
+ }
450
+ [Symbol.dispose]() {
451
+ this.dispose();
452
+ }
453
+ /**
454
+ * All stored files in stable sort order (shortest path first, barrel files
455
+ * last within a length bucket). Returns a cached view, do not mutate.
456
+ */
457
+ get files() {
458
+ return this.#sorted ??= [...this.#cache.values()].sort(compareFiles);
459
+ }
460
+ };
461
+ //#endregion
462
+ //#region src/FileProcessor.ts
463
+ function joinSources(file) {
464
+ const sources = file.sources;
465
+ if (sources.length === 0) return "";
466
+ const parts = [];
467
+ for (const source of sources) {
468
+ const text = extractStringsFromNodes(source.nodes);
469
+ if (text) parts.push(text);
470
+ }
471
+ return parts.join("\n\n");
472
+ }
473
+ /**
474
+ * Turns `FileNode`s into source strings and writes them to storage.
475
+ *
476
+ * Two modes share the same instance. Stateless mode (`parse`, `stream`, `run`) just runs the
477
+ * conversion. Queue mode (`enqueue`, `flush`, `drain`) buffers files deduped by path and
478
+ * writes each batch through storage with up to `STREAM_FLUSH_EVERY` requests in flight.
479
+ *
480
+ * `flush` does not wait for its batch to finish, so dispatch can overlap with IO. The next
481
+ * `flush` or `drain` picks the in-flight batch up. `drain` blocks until everything has been
482
+ * written and is meant for the end of a build.
483
+ *
484
+ * To surface build-level hook signals (`kubb:files:processing:*` and friends) subscribe to
485
+ * `hooks` and re-emit on the kubb bus.
486
+ */
487
+ var FileProcessor = class {
488
+ hooks = new AsyncEventEmitter();
489
+ #parsers;
490
+ #storage;
491
+ #extension;
492
+ #pending = /* @__PURE__ */ new Map();
493
+ #runningFlush = null;
494
+ constructor(options) {
495
+ this.#parsers = options.parsers ?? null;
496
+ this.#storage = options.storage;
497
+ this.#extension = options.extension ?? null;
498
+ }
499
+ /**
500
+ * Files waiting in the queue.
501
+ */
502
+ get size() {
503
+ return this.#pending.size;
504
+ }
505
+ parse(file) {
506
+ const parsers = this.#parsers;
507
+ const parseExtName = this.#extension?.[file.extname] || void 0;
508
+ if (!parsers || !file.extname) return joinSources(file);
509
+ const parser = parsers.get(file.extname);
510
+ if (!parser) return joinSources(file);
511
+ return parser.parse(file, { extname: parseExtName });
512
+ }
513
+ *stream(files) {
514
+ const total = files.length;
515
+ if (total === 0) return;
516
+ let processed = 0;
517
+ for (const file of files) {
518
+ const source = this.parse(file);
519
+ processed++;
520
+ yield {
521
+ file,
522
+ source,
523
+ processed,
524
+ total,
525
+ percentage: processed / total * 100
526
+ };
527
+ }
528
+ }
529
+ async run(files) {
530
+ await this.hooks.emit("start", files);
531
+ for (const { file, source, processed, total, percentage } of this.stream(files)) await this.hooks.emit("update", {
532
+ file,
533
+ source,
534
+ processed,
535
+ percentage,
536
+ total
537
+ });
538
+ await this.hooks.emit("end", files);
539
+ return files;
540
+ }
541
+ /**
542
+ * Adds a file to the next flush. A later `enqueue` for the same path replaces the previous
543
+ * entry, matching `FileManager.upsert`. Fires the `enqueue` event.
544
+ */
545
+ enqueue(file) {
546
+ this.#pending.set(file.path, file);
547
+ this.hooks.emit("enqueue", file);
548
+ }
549
+ /**
550
+ * Starts processing the queued files. Waits for any previous flush to finish (so two
551
+ * batches never run together) and then returns without waiting for the new one. The next
552
+ * `flush` or `drain` picks up the in-flight task.
553
+ */
554
+ async flush() {
555
+ if (this.#runningFlush) await this.#runningFlush;
556
+ if (this.#pending.size === 0) return;
557
+ const batch = [...this.#pending.values()];
558
+ this.#pending.clear();
559
+ this.#runningFlush = this.#processAndWrite(batch).finally(() => {
560
+ this.#runningFlush = null;
561
+ });
562
+ }
563
+ /**
564
+ * Waits for the in-flight flush and writes any files still queued. Fires the `drain` event
565
+ * when both are done.
566
+ */
567
+ async drain() {
568
+ if (this.#runningFlush) await this.#runningFlush;
569
+ if (this.#pending.size > 0) {
570
+ const batch = [...this.#pending.values()];
571
+ this.#pending.clear();
572
+ await this.#processAndWrite(batch);
573
+ }
574
+ await this.hooks.emit("drain");
575
+ }
576
+ async #processAndWrite(files) {
577
+ const storage = this.#storage;
578
+ await this.hooks.emit("start", files);
579
+ const queue = [];
580
+ for (const item of this.stream(files)) {
581
+ await this.hooks.emit("update", item);
582
+ if (item.source) {
583
+ queue.push(storage.setItem(item.file.path, item.source));
584
+ if (queue.length >= 50) await Promise.all(queue.splice(0));
585
+ }
586
+ }
587
+ await Promise.all(queue);
588
+ await this.hooks.emit("end", files);
589
+ }
590
+ /**
591
+ * Clears every listener and the pending queue.
592
+ */
593
+ dispose() {
594
+ this.hooks.removeAll();
595
+ this.#pending.clear();
596
+ }
597
+ [Symbol.dispose]() {
598
+ this.dispose();
599
+ }
600
+ };
601
+ //#endregion
602
+ //#region \0@oxc-project+runtime@0.134.0/helpers/esm/usingCtx.js
603
+ function _usingCtx() {
604
+ var r = "function" == typeof SuppressedError ? SuppressedError : function(r, e) {
605
+ var n = Error();
606
+ return n.name = "SuppressedError", n.error = r, n.suppressed = e, n;
607
+ };
608
+ var e = {};
609
+ var n = [];
610
+ function using(r, e) {
611
+ if (null != e) {
612
+ if (Object(e) !== e) throw new TypeError("using declarations can only be used with objects, functions, null, or undefined.");
613
+ if (r) var o = e[Symbol.asyncDispose || Symbol["for"]("Symbol.asyncDispose")];
614
+ if (void 0 === o && (o = e[Symbol.dispose || Symbol["for"]("Symbol.dispose")], r)) var t = o;
615
+ if ("function" != typeof o) throw new TypeError("Object is not disposable.");
616
+ t && (o = function o() {
617
+ try {
618
+ t.call(e);
619
+ } catch (r) {
620
+ return Promise.reject(r);
621
+ }
622
+ }), n.push({
623
+ v: e,
624
+ d: o,
625
+ a: r
626
+ });
627
+ } else r && n.push({
628
+ d: e,
629
+ a: r
630
+ });
631
+ return e;
632
+ }
633
+ return {
634
+ e,
635
+ u: using.bind(null, !1),
636
+ a: using.bind(null, !0),
637
+ d: function d() {
638
+ var o;
639
+ var t = this.e;
640
+ var s = 0;
641
+ function next() {
642
+ for (; o = n.pop();) try {
643
+ if (!o.a && 1 === s) return s = 0, n.push(o), Promise.resolve().then(next);
644
+ if (o.d) {
645
+ var r = o.d.call(o.v);
646
+ if (o.a) return s |= 2, Promise.resolve(r).then(next, err);
647
+ } else s |= 1;
648
+ } catch (r) {
649
+ return err(r);
650
+ }
651
+ if (1 === s) return t !== e ? Promise.reject(t) : Promise.resolve();
652
+ if (t !== e) throw t;
653
+ }
654
+ function err(n) {
655
+ return t = t !== e ? new r(n, t) : n, next();
656
+ }
657
+ return next();
658
+ }
659
+ };
660
+ }
661
+ //#endregion
662
+ //#region src/storages/memoryStorage.ts
663
+ /**
664
+ * In-memory storage driver. Useful for testing and dry-run scenarios where
665
+ * generated output should be captured without touching the filesystem.
666
+ *
667
+ * All data lives in a `Map` scoped to the storage instance and is discarded
668
+ * when the instance is garbage-collected.
669
+ *
670
+ * @example
671
+ * ```ts
672
+ * import { memoryStorage } from '@kubb/core'
673
+ * import { defineConfig } from 'kubb'
674
+ *
675
+ * export default defineConfig({
676
+ * input: { path: './petStore.yaml' },
677
+ * output: { path: './src/gen' },
678
+ * storage: memoryStorage(),
679
+ * })
680
+ * ```
681
+ */
682
+ const memoryStorage = createStorage(() => {
683
+ const store = /* @__PURE__ */ new Map();
684
+ return {
685
+ name: "memory",
686
+ async hasItem(key) {
687
+ return store.has(key);
688
+ },
689
+ async getItem(key) {
690
+ return store.get(key) ?? null;
691
+ },
692
+ async setItem(key, value) {
693
+ store.set(key, value);
694
+ },
695
+ async removeItem(key) {
696
+ store.delete(key);
697
+ },
698
+ async getKeys(base) {
699
+ const keys = [...store.keys()];
700
+ return base ? keys.filter((k) => k.startsWith(base)) : keys;
701
+ },
702
+ async clear(base) {
703
+ if (!base) {
704
+ store.clear();
705
+ return;
706
+ }
707
+ for (const key of store.keys()) if (key.startsWith(base)) store.delete(key);
708
+ }
709
+ };
710
+ });
711
+ //#endregion
712
+ export { createStorage as a, camelCase as c, BuildError as d, getErrorMessage as f, FileManager as i, pascalCase as l, _usingCtx as n, OPERATION_FILTER_TYPES as o, FileProcessor as r, diagnosticCode as s, memoryStorage as t, AsyncEventEmitter as u };
713
+
714
+ //# sourceMappingURL=memoryStorage-CWFzAz4o.js.map