@kubb/core 5.18.7 → 5.19.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs CHANGED
@@ -29,10 +29,10 @@ let node_async_hooks = require("node:async_hooks");
29
29
  let node_process = require("node:process");
30
30
  node_process = __toESM(node_process, 1);
31
31
  let tinyexec = require("tinyexec");
32
+ let node_fs = require("node:fs");
32
33
  let node_fs_promises = require("node:fs/promises");
33
34
  let node_path = require("node:path");
34
35
  node_path = __toESM(node_path, 1);
35
- let node_fs = require("node:fs");
36
36
  let node_util = require("node:util");
37
37
  let _kubb_ast = require("@kubb/ast");
38
38
  let node_dns = require("node:dns");
@@ -45,7 +45,65 @@ let node_readline = require("node:readline");
45
45
  let node_url = require("node:url");
46
46
  let node_module = require("node:module");
47
47
  // package.json
48
- var version = "5.18.7";
48
+ var version = "5.19.0";
49
+ // ../../internals/utils/src/promise.ts
50
+ /**
51
+ * Returns the value cached under `key` in `store`, computing and storing it on the first call.
52
+ * Pass a `WeakMap` for object keys, so an entry goes away with its key, or a `Map` for primitive
53
+ * keys. A cached `null` or `undefined` counts as a hit, so `compute` runs once per key.
54
+ *
55
+ * @example
56
+ * `const refs = memo(refCache, node, () => collectRefs(node))`
57
+ */
58
+ function memo$1(store, key, compute) {
59
+ const cached = store.get(key);
60
+ if (cached !== void 0 || store.has(key)) return cached;
61
+ const value = compute();
62
+ store.set(key, value);
63
+ return value;
64
+ }
65
+ __name(memo$1, "memo");
66
+ function createStore({ weak, max } = {}) {
67
+ if (weak) return /* @__PURE__ */ new WeakMap();
68
+ const entry = /* @__PURE__ */ new Map();
69
+ if (max === void 0) return entry;
70
+ const set = (key, value) => {
71
+ if (entry.size >= max) entry.clear();
72
+ entry.set(key, value);
73
+ };
74
+ if (max !== 1) return {
75
+ has: (key) => entry.has(key),
76
+ get: (key) => entry.get(key),
77
+ set
78
+ };
79
+ const touch = (key) => {
80
+ if (!entry.has(key)) return false;
81
+ set(key, entry.get(key));
82
+ return true;
83
+ };
84
+ return {
85
+ has: touch,
86
+ get: (key) => touch(key) ? entry.get(key) : void 0,
87
+ set
88
+ };
89
+ }
90
+ memo$1.create = createStore;
91
+ /**
92
+ * Runs `run` over every item with at most `limit` in flight. Workers share one iterator, so each
93
+ * takes the next item the moment it frees up instead of waiting for a batch to drain.
94
+ *
95
+ * @example
96
+ * ```ts
97
+ * await inParallel({ items: files, limit: 50, run: (file) => storage.writeItem(file.path, file.source) })
98
+ * ```
99
+ */
100
+ async function inParallel({ items, limit, run }) {
101
+ const queue = items.entries();
102
+ const worker = async () => {
103
+ for (const [index, item] of queue) await run(item, index);
104
+ };
105
+ await Promise.all(Array.from({ length: Math.min(limit, items.length) }, () => worker()));
106
+ }
49
107
  // ../../internals/utils/src/casing.ts
50
108
  /**
51
109
  * Shared implementation for camelCase and PascalCase conversion.
@@ -60,16 +118,10 @@ function convert(text, pascal) {
60
118
  return (i === 0 && !pascal ? word.charAt(0).toLowerCase() : word.charAt(0).toUpperCase()) + word.slice(1);
61
119
  }).join("").replace(/[^a-zA-Z0-9]/g, "");
62
120
  }
63
- const cache = /* @__PURE__ */ new Map();
64
- const cacheLimit = 1e5;
121
+ const cache = memo$1.create({ max: 1e5 });
65
122
  function toCamelOrPascal(text, pascal) {
66
123
  const key = `${pascal ? "P" : "c"}${text}`;
67
- const cached = cache.get(key);
68
- if (cached !== void 0) return cached;
69
- const result = convert(text, pascal);
70
- if (cache.size >= cacheLimit) cache.clear();
71
- cache.set(key, result);
72
- return result;
124
+ return memo$1(cache, key, () => convert(text, pascal));
73
125
  }
74
126
  /**
75
127
  * Converts `text` to camelCase.
@@ -220,7 +272,25 @@ async function exists(path) {
220
272
  */
221
273
  async function read(path) {
222
274
  if (runtime.isBun) return Bun.file(path).text();
223
- return (0, node_fs_promises.readFile)(path, { encoding: "utf8" });
275
+ return new Promise((resolvePromise, reject) => (0, node_fs.readFile)(path, { encoding: "utf8" }, (error, data) => error ? reject(error) : resolvePromise(data)));
276
+ }
277
+ /**
278
+ * Reads the file at `path` as a UTF-8 string, or `null` when it does not exist or cannot be read.
279
+ * Uses `Bun.file().text()` when running under Bun, `fs.readFileSync` otherwise.
280
+ *
281
+ * @example
282
+ * ```ts
283
+ * const stored = await readIfExists('./src/gen/Pet.ts') // null on a first run
284
+ * ```
285
+ */
286
+ async function readIfExists(path) {
287
+ if (runtime.isBun) return Bun.file(path).text().catch(() => null);
288
+ if (!(0, node_fs.existsSync)(path)) return null;
289
+ try {
290
+ return (0, node_fs.readFileSync)(path, "utf8");
291
+ } catch (_error) {
292
+ return null;
293
+ }
224
294
  }
225
295
  /**
226
296
  * Whether `stored` already holds `source`, comparing on the trimmed text rather than the exact
@@ -255,7 +325,7 @@ async function write(path, data, options = {}) {
255
325
  const content = `${trimmed}\n`;
256
326
  const resolved = (0, node_path.resolve)(path);
257
327
  if (matchesStored({
258
- stored: (options.stored === void 0 ? await read(resolved).catch(() => null) : options.stored) ?? "",
328
+ stored: (options.stored === void 0 ? await readIfExists(resolved) : options.stored) ?? "",
259
329
  source: trimmed
260
330
  })) return null;
261
331
  await writeRaw(resolved, content);
@@ -280,11 +350,11 @@ async function writeRaw(path, content) {
280
350
  return;
281
351
  }
282
352
  try {
283
- await (0, node_fs_promises.writeFile)(resolved, content, { encoding: "utf-8" });
353
+ await new Promise((resolvePromise, reject) => (0, node_fs.writeFile)(resolved, content, { encoding: "utf-8" }, (error) => error ? reject(error) : resolvePromise()));
284
354
  } catch (error) {
285
355
  if (error.code !== "ENOENT") throw error;
286
356
  await (0, node_fs_promises.mkdir)((0, node_path.dirname)(resolved), { recursive: true });
287
- await (0, node_fs_promises.writeFile)(resolved, content, { encoding: "utf-8" });
357
+ await new Promise((resolvePromise, reject) => (0, node_fs.writeFile)(resolved, content, { encoding: "utf-8" }, (error) => error ? reject(error) : resolvePromise()));
288
358
  }
289
359
  }
290
360
  /**
@@ -348,38 +418,6 @@ function isPathInside(path, parent) {
348
418
  const rel = (0, node_path.relative)(resolvedParent, resolvedPath);
349
419
  return rel !== "" && !rel.startsWith("..") && !(0, node_path.isAbsolute)(rel);
350
420
  }
351
- // ../../internals/utils/src/promise.ts
352
- /**
353
- * Returns the value cached under `key` in `store`, computing and storing it on the first call.
354
- * Pass a `WeakMap` for object keys, so an entry goes away with its key, or a `Map` for primitive
355
- * keys. A cached `null` or `undefined` counts as a hit, so `compute` runs once per key.
356
- *
357
- * @example
358
- * `const refs = memo(refCache, node, () => collectRefs(node))`
359
- */
360
- function memo$1(store, key, compute) {
361
- if (store.has(key)) return store.get(key);
362
- const value = compute();
363
- store.set(key, value);
364
- return value;
365
- }
366
- __name(memo$1, "memo");
367
- /**
368
- * Runs `run` over every item with at most `limit` in flight. Workers share one iterator, so each
369
- * takes the next item the moment it frees up instead of waiting for a batch to drain.
370
- *
371
- * @example
372
- * ```ts
373
- * await inParallel({ items: files, limit: 50, run: (file) => storage.writeItem(file.path, file.source) })
374
- * ```
375
- */
376
- async function inParallel({ items, limit, run }) {
377
- const queue = items.entries();
378
- const worker = async () => {
379
- for (const [index, item] of queue) await run(item, index);
380
- };
381
- await Promise.all(Array.from({ length: Math.min(limit, items.length) }, () => worker()));
382
- }
383
421
  // ../../internals/utils/src/tools.ts
384
422
  /**
385
423
  * CLI command descriptors for each supported code formatter.
@@ -1379,8 +1417,20 @@ function injectFile(file) {
1379
1417
  }
1380
1418
  /**
1381
1419
  * Returns a value computed once per build and shared by every plugin, like `ctx.memo`.
1420
+ *
1421
+ * Pass a store first to cache in it instead, with no build needed: a `Map` or `WeakMap`, or one
1422
+ * from `memo.create`.
1423
+ *
1424
+ * @example Once per build
1425
+ * `const names = memo('myPlugin:names', () => collectNames(schemas))`
1426
+ *
1427
+ * @example In your own store
1428
+ * ```ts
1429
+ * const cache = memo.create<ast.SchemaNode, Array<string>>({ weak: true })
1430
+ * const refs = memo(cache, node, () => collectRefs(node))
1431
+ * ```
1382
1432
  */
1383
- const memo = (key, compute) => requireContext("memo").memo(key, compute);
1433
+ const memo = Object.assign((...args) => args.length === 3 ? memo$1(...args) : requireContext("memo").memo(...args), { create: memo$1.create });
1384
1434
  /**
1385
1435
  * Returns the options the user passed to the plugin being set up, like `ctx.options`.
1386
1436
  */
@@ -1741,9 +1791,9 @@ function inputToAdapterSource(config) {
1741
1791
  };
1742
1792
  }
1743
1793
  // src/resolveOptions.ts
1744
- const patterns = /* @__PURE__ */ new Map();
1745
- const methodPatterns = /* @__PURE__ */ new Map();
1746
- const nodeCaches = /* @__PURE__ */ new WeakMap();
1794
+ const patterns = memo$1.create();
1795
+ const methodPatterns = memo$1.create();
1796
+ const nodeCaches = memo$1.create({ weak: true });
1747
1797
  function testPattern(value, pattern) {
1748
1798
  if (typeof pattern === "string") return memo$1(patterns, pattern, () => new RegExp(pattern)).test(value);
1749
1799
  return value.match(pattern) !== null;
@@ -1810,6 +1860,7 @@ function isNamespace(value) {
1810
1860
  * reachable and a `file` override is never dropped.
1811
1861
  */
1812
1862
  const resolverOptions = Symbol.for("@kubb/core/resolver/options");
1863
+ const createNameNode = () => ({ next: /* @__PURE__ */ new Map() });
1813
1864
  /**
1814
1865
  * Builds a nested file path from a dotted name. Splits on dots that precede a letter
1815
1866
  * (so version numbers embedded in operationIds like `v2025.0` stay intact), camelCases
@@ -1873,8 +1924,12 @@ var Resolver = class Resolver {
1873
1924
  /** The built-in machinery, untouched by `name`/`file` overrides and built once since the driver reads it per node. */
1874
1925
  default;
1875
1926
  #options;
1876
- #memo = /* @__PURE__ */ new Map();
1927
+ #memo = memo$1.create();
1877
1928
  #usedNames = /* @__PURE__ */ new Set();
1929
+ #stringNames = memo$1.create();
1930
+ #arrayNames = createNameNode();
1931
+ #outputDirs = memo$1.create({ weak: true });
1932
+ #importPaths = memo$1.create({ weak: true });
1878
1933
  #tagParents = /* @__PURE__ */ new Map();
1879
1934
  #baseName;
1880
1935
  #filePath;
@@ -1941,16 +1996,30 @@ var Resolver = class Resolver {
1941
1996
  * ```
1942
1997
  */
1943
1998
  resolveName({ key, name, normalize = (name) => name }) {
1944
- const cacheKey = typeof key === "string" ? `s:${key}` : `a:${key.map((segment) => segment === void 0 ? "u" : `${segment.length}:${segment}`).join("")}`;
1945
- const allocate = (suffix) => {
1946
- const candidate = suffix === 1 ? name : `${name}${suffix}`;
1947
- const normalized = normalize(candidate);
1948
- const names = typeof normalized === "string" ? [normalized] : normalized;
1949
- if (names.some((emittedName) => this.#usedNames.has(emittedName))) return allocate(suffix + 1);
1950
- this.reserveNames(names);
1951
- return candidate;
1952
- };
1953
- return this.memo(`resolveName:${cacheKey}`, () => allocate(1));
1999
+ if (typeof key === "string") return memo$1(this.#stringNames, key, () => this.#allocateName({
2000
+ name,
2001
+ normalize,
2002
+ suffix: 1
2003
+ }));
2004
+ const node = key.reduce((parent, segment) => memo$1(parent.next, segment, createNameNode), this.#arrayNames);
2005
+ node.name ??= this.#allocateName({
2006
+ name,
2007
+ normalize,
2008
+ suffix: 1
2009
+ });
2010
+ return node.name;
2011
+ }
2012
+ #allocateName({ name, normalize, suffix }) {
2013
+ const candidate = suffix === 1 ? name : `${name}${suffix}`;
2014
+ const normalized = normalize(candidate);
2015
+ const names = typeof normalized === "string" ? [normalized] : normalized;
2016
+ if (names.some((emittedName) => this.#usedNames.has(emittedName))) return this.#allocateName({
2017
+ name,
2018
+ normalize,
2019
+ suffix: suffix + 1
2020
+ });
2021
+ this.reserveNames(names);
2022
+ return candidate;
1954
2023
  }
1955
2024
  file(options) {
1956
2025
  return this.#resolveFile(options);
@@ -1967,17 +2036,17 @@ var Resolver = class Resolver {
1967
2036
  * reads the same ref set instead of re-scanning it per plugin.
1968
2037
  */
1969
2038
  imports(options) {
1970
- const { node, root, output, group, extname = ".ts", name, checks } = options;
2039
+ const { node, root, output, extname = ".ts", name, checks } = options;
1971
2040
  const resolveName = name ?? ((schemaName) => this.name(schemaName));
2041
+ const paths = memo$1(memo$1(memo$1(this.#importPaths, output, () => /* @__PURE__ */ new Map()), root, () => /* @__PURE__ */ new Map()), extname, () => /* @__PURE__ */ new Map());
1972
2042
  return _kubb_ast.ast.graph.getImportedNames(node, { checks }).map((schemaName) => _kubb_ast.ast.factory.createImport({
1973
2043
  name: [resolveName(schemaName)],
1974
- path: this.#resolveFilePath({
2044
+ path: memo$1(paths, schemaName, () => this.#resolveFilePath({
1975
2045
  name: schemaName,
1976
2046
  extname,
1977
2047
  root,
1978
- output,
1979
- group
1980
- })
2048
+ output
2049
+ }))
1981
2050
  }));
1982
2051
  }
1983
2052
  /**
@@ -2049,8 +2118,8 @@ var Resolver = class Resolver {
2049
2118
  * are provided.
2050
2119
  */
2051
2120
  #resolvePath({ baseName, tag, path: groupPath, root, output, group }) {
2052
- if (output.mode !== "directory") return node_path.default.resolve(root, output.path);
2053
- const outputDir = node_path.default.resolve(root, output.path);
2121
+ const outputDir = memo$1(memo$1(this.#outputDirs, output, () => /* @__PURE__ */ new Map()), root, () => node_path.default.resolve(root, output.path));
2122
+ if (output.mode !== "directory") return outputDir;
2054
2123
  const groupValue = group?.type === "path" ? groupPath : tag;
2055
2124
  const result = group && groupValue ? node_path.default.resolve(outputDir, this.groupDir(group, groupValue), baseName) : node_path.default.resolve(outputDir, baseName);
2056
2125
  assertInside({
@@ -2328,7 +2397,8 @@ function compareFiles(a, b) {
2328
2397
  /**
2329
2398
  * Writes `source` to `file.path` unless the storage already holds it, either verbatim or, per the
2330
2399
  * manifest, as what the output passes make of it. Checking here rather than in a driver gives a
2331
- * storage writing to S3 or a database the same guarantee `fsStorage` has. `false` when skipped.
2400
+ * storage writing to S3 or a database the same guarantee `fsStorage` has. `written` is `false` when
2401
+ * skipped, and `stored` is what the storage held before the write.
2332
2402
  */
2333
2403
  async function writeChanged({ storage, manifest, file, source, signal, cleaned }) {
2334
2404
  signal?.throwIfAborted();
@@ -2340,14 +2410,20 @@ async function writeChanged({ storage, manifest, file, source, signal, cleaned }
2340
2410
  key: file.path,
2341
2411
  source,
2342
2412
  disk: stored
2343
- }))) return false;
2413
+ }))) return {
2414
+ written: false,
2415
+ stored
2416
+ };
2344
2417
  signal?.throwIfAborted();
2345
2418
  await storage.writeItem(file.path, source, { stored });
2346
2419
  manifest?.track({
2347
2420
  key: file.path,
2348
2421
  source
2349
2422
  });
2350
- return true;
2423
+ return {
2424
+ written: true,
2425
+ stored
2426
+ };
2351
2427
  }
2352
2428
  /** Reports finished files in input order: each finished file flushes the run of finished files ahead of it as one update. */
2353
2429
  function createProgress(files, config, hooks) {
@@ -2507,7 +2583,7 @@ var FileManager = class {
2507
2583
  * memory rather than holding every source, while still overlapping each file's write with the
2508
2584
  * next file's parse. Files finish in whatever order they parse, so each finished file flushes the
2509
2585
  * run of finished files ahead of it as one `kubb:files:processing:update`, keeping rows in input order.
2510
- * Each parsed source goes out once on `kubb:file:processed`, so listeners read it without the pool holding it.
2586
+ * Each parsed source goes out once on `kubb:file:processed`, next to what the storage held before the write.
2511
2587
  *
2512
2588
  * A file the storage already holds is skipped, so a rebuild that generates identical output
2513
2589
  * writes nothing and leaves every mtime where it was. `kubb:files:processing:end` lists the
@@ -2525,17 +2601,19 @@ var FileManager = class {
2525
2601
  signal?.throwIfAborted();
2526
2602
  const source = await this.parse(file, { parsers });
2527
2603
  if (source) {
2528
- if (!await writeChanged({
2604
+ const { written, stored } = await writeChanged({
2529
2605
  storage,
2530
2606
  manifest,
2531
2607
  file,
2532
2608
  source,
2533
2609
  signal,
2534
2610
  cleaned
2535
- })) unchanged.push(file.path);
2611
+ });
2612
+ if (!written) unchanged.push(file.path);
2536
2613
  await hooks?.callHook("kubb:file:processed", {
2537
2614
  file,
2538
- source
2615
+ source,
2616
+ stored
2539
2617
  });
2540
2618
  }
2541
2619
  await progress?.(index);
@@ -2658,7 +2736,7 @@ var KubbDriver = class {
2658
2736
  */
2659
2737
  fileManager = new FileManager();
2660
2738
  plugins = /* @__PURE__ */ new Map();
2661
- #memo = /* @__PURE__ */ new Map();
2739
+ #memo = memo$1.create();
2662
2740
  /**
2663
2741
  * Removers for every listener the driver added (plugin, generator) so `dispose()` can detach
2664
2742
  * them in one pass. External `hooks.hook(...)` listeners are not tracked.
@@ -3412,11 +3490,7 @@ const createStorage = (build) => (options) => build(options ?? {});
3412
3490
  const fsStorage = createStorage(() => ({
3413
3491
  name: "fs",
3414
3492
  async readItem(key) {
3415
- try {
3416
- return await read((0, node_path.resolve)(key));
3417
- } catch (_error) {
3418
- return null;
3419
- }
3493
+ return readIfExists((0, node_path.resolve)(key));
3420
3494
  },
3421
3495
  async writeItem(key, value, options) {
3422
3496
  await write((0, node_path.resolve)(key), value, {
@@ -3504,7 +3578,7 @@ const cacheStorage = createStorage(({ root = process.cwd() }) => {
3504
3578
  * ```
3505
3579
  */
3506
3580
  var Hookable = class {
3507
- #listeners = /* @__PURE__ */ new Map();
3581
+ #listeners = memo$1.create();
3508
3582
  /**
3509
3583
  * Calls `hookName` and awaits all registered listeners sequentially.
3510
3584
  * Throws if any listener rejects, wrapping the cause in an error that names the hook.
@@ -3536,9 +3610,7 @@ var Hookable = class {
3536
3610
  * ```
3537
3611
  */
3538
3612
  hook(hookName, handler) {
3539
- let listeners = this.#listeners.get(hookName);
3540
- if (!listeners) this.#listeners.set(hookName, listeners = /* @__PURE__ */ new Set());
3541
- listeners.add(handler);
3613
+ memo$1(this.#listeners, hookName, () => /* @__PURE__ */ new Set()).add(handler);
3542
3614
  return () => this.removeHook(hookName, handler);
3543
3615
  }
3544
3616
  /**