@kubb/core 5.0.0-beta.40 → 5.0.0-beta.42

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.d.ts CHANGED
@@ -1,7 +1,13 @@
1
1
  import { t as __name } from "./chunk-C0LytTxp.js";
2
- import { $ as Override, A as KubbHookEndContext, At as logLevel, B as createKubb, Bt as AsyncEventEmitter, C as KubbErrorContext, Ct as createReporter, D as KubbFilesProcessingUpdateContext, Dt as LoggerOptions, E as KubbFilesProcessingStartContext, Et as LoggerContext, F as KubbPluginsEndContext, Ft as createStorage, G as Exclude, H as GeneratorContext, I as KubbSuccessContext, It as Adapter, J as KubbPluginEndContext, K as Group, L as KubbWarnContext, Lt as AdapterFactoryOptions, M as KubbHooks, Mt as RendererFactory, N as KubbInfoContext, Nt as createRenderer, O as KubbGenerationEndContext, Ot as UserLogger, P as KubbLifecycleStartContext, Pt as Storage, Q as Output, R as PossibleConfig, Rt as AdapterSource, S as KubbDiagnosticContext, St as UserReporter, T as KubbFilesProcessingEndContext, Tt as Logger, U as defineGenerator, V as Generator, W as KubbDriver, X as KubbPluginStartContext, Y as KubbPluginSetupContext, Z as NormalizedPlugin, _ as InputPath, _t as defineParser, a as DiagnosticLocation, at as ResolveBannerFile, b as KubbBuildStartContext, bt as ReporterContext, c as PerformanceDiagnostic, ct as ResolverContext, d as SerializedDiagnostic, dt as defineResolver, et as Plugin, f as UpdateDiagnostic, ft as Middleware, g as InputData, gt as Parser, h as Config, ht as ParsedFile, i as DiagnosticKind, it as ResolveBannerContext, j as KubbHookStartContext, jt as Renderer, k as KubbGenerationStartContext, kt as defineLogger, l as ProblemCode, lt as ResolverFileParams, m as CLIOptions, mt as FileProcessorHooks, n as DiagnosticByCode, nt as definePlugin, o as DiagnosticSeverity, ot as ResolveOptionsContext, p as BuildOutput, pt as defineMiddleware, q as Include, r as DiagnosticDoc, rt as BannerMeta, s as Diagnostics, st as Resolver, t as Diagnostic, tt as PluginFactoryOptions, u as ProblemDiagnostic, ut as ResolverPathParams, v as Kubb, vt as GenerationResult, w as KubbFileProcessingUpdate, wt as selectReporters, x as KubbConfigEndContext, xt as ReporterName, y as KubbBuildEndContext, yt as Reporter, z as UserConfig, zt as createAdapter } from "./diagnostics-DhfW8YpT.js";
2
+ import { $ as Output, A as KubbHookEndContext, At as defineLogger, B as UserConfig, Bt as CachedSnapshot, C as KubbErrorContext, Ct as UserReporter, D as KubbFilesProcessingUpdateContext, Dt as LoggerContext, E as KubbFilesProcessingStartContext, Et as Logger, F as KubbLifecycleStartContext, Ft as RendererFactory, G as KubbDriver, Gt as createAdapter, H as Generator, Ht as Adapter, I as KubbPluginsEndContext, It as createRenderer, J as Include, K as Exclude, Kt as AsyncEventEmitter, L as KubbSuccessContext, Lt as Storage, M as KubbHookStartContext, Mt as FsCacheOptions, N as KubbHooks, Nt as fsCache, O as KubbGenerationEndContext, Ot as LoggerOptions, P as KubbInfoContext, Pt as Renderer, Q as NormalizedPlugin, R as KubbWarnContext, Rt as createStorage, S as KubbDiagnosticContext, St as ReporterName, T as KubbFilesProcessingEndContext, Tt as selectReporters, U as GeneratorContext, Ut as AdapterFactoryOptions, V as createKubb, Vt as createCache, W as defineGenerator, Wt as AdapterSource, X as KubbPluginSetupContext, Y as KubbPluginEndContext, Z as KubbPluginStartContext, _ as InputPath, _t as Parser, a as DiagnosticLocation, at as ResolveBannerContext, b as KubbBuildStartContext, bt as Reporter, c as PerformanceDiagnostic, ct as Resolver, d as SerializedDiagnostic, dt as ResolverPathParams, et as Override, f as UpdateDiagnostic, ft as defineResolver, g as InputData, gt as ParsedFile, h as Config, ht as FileProcessorHooks, i as DiagnosticKind, it as BannerMeta, j as KubbHookLineContext, jt as logLevel, k as KubbGenerationStartContext, kt as UserLogger, l as ProblemCode, lt as ResolverContext, m as CLIOptions, mt as defineMiddleware, n as DiagnosticByCode, nt as PluginFactoryOptions, o as DiagnosticSeverity, ot as ResolveBannerFile, p as BuildOutput, pt as Middleware, q as Group, r as DiagnosticDoc, rt as definePlugin, s as Diagnostics, st as ResolveOptionsContext, t as Diagnostic, tt as Plugin, u as ProblemDiagnostic, ut as ResolverFileParams, v as Kubb, vt as defineParser, w as KubbFileProcessingUpdate, wt as createReporter, x as KubbConfigEndContext, xt as ReporterContext, y as KubbBuildEndContext, yt as GenerationResult, z as PossibleConfig, zt as Cache } from "./diagnostics-DZGgDzSv.js";
3
3
  import * as ast from "@kubb/ast";
4
4
 
5
+ //#region ../../internals/utils/src/runtime.d.ts
6
+ /**
7
+ * Name of the JavaScript runtime executing the current process.
8
+ */
9
+ type RuntimeName = 'bun' | 'deno' | 'node';
10
+ //#endregion
5
11
  //#region ../../internals/utils/src/urlPath.d.ts
6
12
  type URLObject = {
7
13
  /**
@@ -279,6 +285,14 @@ type TelemetryEvent = {
279
285
  command: string;
280
286
  kubbVersion: string;
281
287
  nodeVersion: string;
288
+ /**
289
+ * Name of the JavaScript runtime that executed the run, `'bun'`, `'deno'`, or `'node'`.
290
+ */
291
+ runtime: RuntimeName;
292
+ /**
293
+ * Major version of the active runtime, e.g. `'1'` under Bun or `'22'` under Node.
294
+ */
295
+ runtimeVersion: string;
282
296
  platform: string;
283
297
  ci: boolean;
284
298
  plugins: Array<TelemetryPlugin>;
@@ -369,5 +383,5 @@ declare const fsStorage: (options?: Record<string, never> | undefined) => Storag
369
383
  */
370
384
  declare const memoryStorage: (options?: Record<string, never> | undefined) => Storage;
371
385
  //#endregion
372
- export { type Adapter, type AdapterFactoryOptions, type AdapterSource, AsyncEventEmitter, type BannerMeta, type BuildOutput, type CLIOptions, type Config, type Diagnostic, type DiagnosticByCode, type DiagnosticDoc, type DiagnosticKind, type DiagnosticLocation, type DiagnosticSeverity, Diagnostics, type Exclude, type FileProcessorHooks, type GenerationResult, type Generator, type GeneratorContext, type Group, type Include, type InputData, type InputPath, type Kubb, type KubbBuildEndContext, type KubbBuildStartContext, type KubbConfigEndContext, type KubbDiagnosticContext, KubbDriver, type KubbErrorContext, type KubbFileProcessingUpdate, type KubbFilesProcessingEndContext, type KubbFilesProcessingStartContext, type KubbFilesProcessingUpdateContext, type KubbGenerationEndContext, type KubbGenerationStartContext, type KubbHookEndContext, type KubbHookStartContext, type KubbHooks, type KubbInfoContext, type KubbLifecycleStartContext, type KubbPluginEndContext, type KubbPluginSetupContext, type KubbPluginStartContext, type KubbPluginsEndContext, type KubbSuccessContext, type KubbWarnContext, type Logger, type LoggerContext, type LoggerOptions, type Middleware, type NormalizedPlugin, type Output, type Override, type ParsedFile, type Parser, type PerformanceDiagnostic, type Plugin, type PluginFactoryOptions, type PossibleConfig, type ProblemCode, type ProblemDiagnostic, type Renderer, type RendererFactory, type Reporter, type ReporterContext, type ReporterName, type ResolveBannerContext, type ResolveBannerFile, type ResolveOptionsContext, type Resolver, type ResolverContext, type ResolverFileParams, type ResolverPathParams, type SerializedDiagnostic, type Storage, Telemetry, URLPath, type UpdateDiagnostic, type UserConfig, type UserLogger, type UserReporter, ast, cliReporter, createAdapter, createKubb, createRenderer, createReporter, createStorage, defineGenerator, defineLogger, defineMiddleware, defineParser, definePlugin, defineResolver, fileReporter, fsStorage, jsonReporter, logLevel, memoryStorage, selectReporters };
386
+ export { type Adapter, type AdapterFactoryOptions, type AdapterSource, AsyncEventEmitter, type BannerMeta, type BuildOutput, type CLIOptions, type Cache, type CachedSnapshot, type Config, type Diagnostic, type DiagnosticByCode, type DiagnosticDoc, type DiagnosticKind, type DiagnosticLocation, type DiagnosticSeverity, Diagnostics, type Exclude, type FileProcessorHooks, type FsCacheOptions, type GenerationResult, type Generator, type GeneratorContext, type Group, type Include, type InputData, type InputPath, type Kubb, type KubbBuildEndContext, type KubbBuildStartContext, type KubbConfigEndContext, type KubbDiagnosticContext, KubbDriver, type KubbErrorContext, type KubbFileProcessingUpdate, type KubbFilesProcessingEndContext, type KubbFilesProcessingStartContext, type KubbFilesProcessingUpdateContext, type KubbGenerationEndContext, type KubbGenerationStartContext, type KubbHookEndContext, type KubbHookLineContext, type KubbHookStartContext, type KubbHooks, type KubbInfoContext, type KubbLifecycleStartContext, type KubbPluginEndContext, type KubbPluginSetupContext, type KubbPluginStartContext, type KubbPluginsEndContext, type KubbSuccessContext, type KubbWarnContext, type Logger, type LoggerContext, type LoggerOptions, type Middleware, type NormalizedPlugin, type Output, type Override, type ParsedFile, type Parser, type PerformanceDiagnostic, type Plugin, type PluginFactoryOptions, type PossibleConfig, type ProblemCode, type ProblemDiagnostic, type Renderer, type RendererFactory, type Reporter, type ReporterContext, type ReporterName, type ResolveBannerContext, type ResolveBannerFile, type ResolveOptionsContext, type Resolver, type ResolverContext, type ResolverFileParams, type ResolverPathParams, type SerializedDiagnostic, type Storage, Telemetry, URLPath, type UpdateDiagnostic, type UserConfig, type UserLogger, type UserReporter, ast, cliReporter, createAdapter, createCache, createKubb, createRenderer, createReporter, createStorage, defineGenerator, defineLogger, defineMiddleware, defineParser, definePlugin, defineResolver, fileReporter, fsCache, fsStorage, jsonReporter, logLevel, memoryStorage, selectReporters };
373
387
  //# sourceMappingURL=index.d.ts.map
package/dist/index.js CHANGED
@@ -1,8 +1,8 @@
1
1
  import "./chunk-C0LytTxp.js";
2
- import { c as createStorage, d as URLPath, f as formatMs, g as BuildError, h as AsyncEventEmitter, l as Diagnostics, n as KubbDriver, o as defineResolver, p as getElapsedMs, r as _usingCtx, s as definePlugin, t as memoryStorage, u as OTLP_ENDPOINT } from "./memoryStorage-DTv1Kub1.js";
2
+ import { c as createStorage, d as URLPath, f as formatMs, g as BuildError, h as AsyncEventEmitter, l as Diagnostics, n as KubbDriver, o as defineResolver, p as getElapsedMs, r as _usingCtx, s as definePlugin, t as memoryStorage, u as OTLP_ENDPOINT } from "./memoryStorage-BOnaknb7.js";
3
3
  import { stripVTControlCharacters, styleText } from "node:util";
4
- import { createHash, randomBytes } from "node:crypto";
5
- import { access, mkdir, readFile, readdir, rm, writeFile } from "node:fs/promises";
4
+ import { createHash, hash, randomBytes } from "node:crypto";
5
+ import { access, glob, mkdir, readFile, rm, writeFile } from "node:fs/promises";
6
6
  import { dirname, join, relative, resolve } from "node:path";
7
7
  import { promises } from "node:dns";
8
8
  import * as ast from "@kubb/ast";
@@ -58,7 +58,26 @@ const randomColors = [
58
58
  */
59
59
  function randomCliColor(text) {
60
60
  if (!text) return "";
61
- return styleText(randomColors[createHash("sha256").update(text).digest().readUInt32BE(0) % randomColors.length] ?? "white", text);
61
+ return styleText(randomColors[hash("sha256", text, "buffer").readUInt32BE(0) % randomColors.length] ?? "white", text);
62
+ }
63
+ //#endregion
64
+ //#region ../../internals/utils/src/path.ts
65
+ /**
66
+ * Converts a filesystem path to use POSIX (`/`) separators.
67
+ *
68
+ * Most of the codebase compares and composes paths as strings (prefix matching, joining for
69
+ * import specifiers, splitting on `/`). On POSIX `path.resolve` already returns `/`-separated
70
+ * paths, but on Windows it returns `\`-separated paths, which breaks every such comparison.
71
+ *
72
+ * Routing every path that crosses a module boundary through `toPosixPath` keeps the rest of the
73
+ * code platform-agnostic. The conversion runs unconditionally so Windows-specific behavior is
74
+ * exercisable from POSIX CI.
75
+ *
76
+ * @example
77
+ * toPosixPath('C:\\repo\\src\\pet.ts') // 'C:/repo/src/pet.ts'
78
+ */
79
+ function toPosixPath(filePath) {
80
+ return filePath.replaceAll("\\", "/");
62
81
  }
63
82
  //#endregion
64
83
  //#region ../../internals/utils/src/env.ts
@@ -78,8 +97,72 @@ function isCIEnvironment() {
78
97
  return !!(process.env.CI || process.env.GITHUB_ACTIONS || process.env.GITLAB_CI || process.env.BITBUCKET_BUILD_NUMBER || process.env.JENKINS_URL || process.env.CIRCLECI || process.env.TRAVIS || process.env.TEAMCITY_VERSION || process.env.BUILDKITE || process.env.TF_BUILD);
79
98
  }
80
99
  //#endregion
100
+ //#region ../../internals/utils/src/runtime.ts
101
+ /**
102
+ * Returns `true` when the current process is running under Bun.
103
+ *
104
+ * Detection keys off the global `Bun` object rather than `process.versions`,
105
+ * because Bun polyfills `process.versions.node` for Node compatibility and would
106
+ * otherwise look like Node.
107
+ *
108
+ * @example
109
+ * ```ts
110
+ * if (isBun()) {
111
+ * await Bun.write(path, data)
112
+ * }
113
+ * ```
114
+ */
115
+ function isBun() {
116
+ return typeof Bun !== "undefined";
117
+ }
118
+ /**
119
+ * Returns `true` when the current process is running under Deno.
120
+ */
121
+ function isDeno() {
122
+ return typeof globalThis.Deno !== "undefined";
123
+ }
124
+ /**
125
+ * Returns the name of the runtime executing the current process.
126
+ *
127
+ * @example
128
+ * ```ts
129
+ * getRuntimeName() // 'bun' when run with `bun kubb`, 'node' otherwise
130
+ * ```
131
+ */
132
+ function getRuntimeName() {
133
+ if (isBun()) return "bun";
134
+ if (isDeno()) return "deno";
135
+ return "node";
136
+ }
137
+ /**
138
+ * Returns the version of the active runtime, or an empty string when it cannot be read.
139
+ *
140
+ * @example
141
+ * ```ts
142
+ * getRuntimeVersion() // '1.3.11' under Bun, '22.22.2' under Node
143
+ * ```
144
+ */
145
+ function getRuntimeVersion() {
146
+ if (isBun()) return process.versions.bun ?? "";
147
+ if (isDeno()) return globalThis.Deno?.version?.deno ?? "";
148
+ return process.versions?.node ?? "";
149
+ }
150
+ //#endregion
81
151
  //#region ../../internals/utils/src/fs.ts
82
152
  /**
153
+ * Reads the file at `path` as a UTF-8 string.
154
+ * Uses `Bun.file().text()` when running under Bun, `fs.readFile` otherwise.
155
+ *
156
+ * @example
157
+ * ```ts
158
+ * const source = await read('./src/Pet.ts')
159
+ * ```
160
+ */
161
+ async function read(path) {
162
+ if (isBun()) return Bun.file(path).text();
163
+ return readFile(path, { encoding: "utf8" });
164
+ }
165
+ /**
83
166
  * Writes `data` to `path`, trimming leading/trailing whitespace before saving.
84
167
  * Skips the write when the trimmed content is empty or identical to what is already on disk.
85
168
  * Creates any missing parent directories automatically.
@@ -96,7 +179,7 @@ async function write(path, data, options = {}) {
96
179
  const trimmed = data.trim();
97
180
  if (trimmed === "") return null;
98
181
  const resolved = resolve(path);
99
- if (typeof Bun !== "undefined") {
182
+ if (isBun()) {
100
183
  const file = Bun.file(resolved);
101
184
  if ((await file.exists() ? await file.text() : null) === trimmed) return null;
102
185
  await Bun.write(resolved, trimmed);
@@ -209,6 +292,35 @@ function createAdapter(build) {
209
292
  return (options) => build(options ?? {});
210
293
  }
211
294
  //#endregion
295
+ //#region src/createCache.ts
296
+ /**
297
+ * Defines a custom cache backend. The builder receives user options and returns a
298
+ * {@link Cache}. Reach for this when the filesystem backend doesn't fit, for
299
+ * example to store snapshots in Redis or a database.
300
+ *
301
+ * @example In-memory cache (the built-in implementation)
302
+ * ```ts
303
+ * import { createCache } from '@kubb/core'
304
+ *
305
+ * export const memoryCache = createCache(() => {
306
+ * const store = new Map<string, CachedSnapshot>()
307
+ *
308
+ * return {
309
+ * name: 'memory',
310
+ * async restore({ key }) {
311
+ * return store.get(key) ?? null
312
+ * },
313
+ * async persist({ key, snapshot }) {
314
+ * store.set(key, snapshot)
315
+ * },
316
+ * }
317
+ * })
318
+ * ```
319
+ */
320
+ function createCache(build) {
321
+ return (options) => build(options ?? {});
322
+ }
323
+ //#endregion
212
324
  //#region src/storages/fsStorage.ts
213
325
  /**
214
326
  * Built-in filesystem storage driver.
@@ -260,21 +372,21 @@ const fsStorage = createStorage(() => ({
260
372
  },
261
373
  async getKeys(base) {
262
374
  const resolvedBase = resolve(base ?? process.cwd());
263
- async function* walk(dir, prefix) {
264
- let entries;
265
- try {
266
- entries = await readdir(dir, { withFileTypes: true });
267
- } catch (_error) {
268
- return;
269
- }
270
- for (const entry of entries) {
271
- const rel = prefix ? `${prefix}/${entry.name}` : entry.name;
272
- if (entry.isDirectory()) yield* walk(join(dir, entry.name), rel);
273
- else yield rel;
274
- }
375
+ if (isBun()) {
376
+ const bunGlob = new Bun.Glob("**/*");
377
+ return Array.fromAsync(bunGlob.scan({
378
+ cwd: resolvedBase,
379
+ onlyFiles: true,
380
+ dot: true
381
+ }));
275
382
  }
276
383
  const keys = [];
277
- for await (const key of walk(resolvedBase, "")) keys.push(key);
384
+ try {
385
+ for await (const entry of glob("**/*", {
386
+ cwd: resolvedBase,
387
+ withFileTypes: true
388
+ })) if (entry.isFile()) keys.push(toPosixPath(relative(resolvedBase, join(entry.parentPath, entry.name))));
389
+ } catch (_error) {}
278
390
  return keys;
279
391
  },
280
392
  async clear(base) {
@@ -333,6 +445,7 @@ function resolveConfig(userConfig) {
333
445
  ...userConfig.output
334
446
  },
335
447
  storage: userConfig.storage ?? fsStorage(),
448
+ cache: userConfig.cache === false ? void 0 : userConfig.cache,
336
449
  reporters: userConfig.reporters ?? [],
337
450
  plugins: userConfig.plugins ?? []
338
451
  };
@@ -528,11 +641,10 @@ const logLevel = {
528
641
  verbose: 4
529
642
  };
530
643
  /**
531
- * Defines a typed logger. Use the second type parameter to declare a return
532
- * value from `install`, which is handy when the logger exposes a sink factory
533
- * or cleanup callback to the caller.
644
+ * Defines a typed logger. The `install` method subscribes to lifecycle events
645
+ * on the shared emitter and forwards them to the logger's destination.
534
646
  *
535
- * @example Basic logger
647
+ * @example
536
648
  * ```ts
537
649
  * import { defineLogger } from '@kubb/core'
538
650
  *
@@ -544,20 +656,6 @@ const logLevel = {
544
656
  * },
545
657
  * })
546
658
  * ```
547
- *
548
- * @example Logger that returns a hook sink factory
549
- * ```ts
550
- * import { defineLogger, type LoggerOptions } from '@kubb/core'
551
- * import type { HookSinkFactory } from './sinks'
552
- *
553
- * export const myLogger = defineLogger<LoggerOptions, HookSinkFactory>({
554
- * name: 'my-logger',
555
- * install(context) {
556
- * // … register event handlers …
557
- * return () => ({ onStdout: console.log })
558
- * },
559
- * })
560
- * ```
561
659
  */
562
660
  function defineLogger(logger) {
563
661
  return logger;
@@ -778,6 +876,8 @@ var Telemetry = class Telemetry {
778
876
  command: options.command,
779
877
  kubbVersion: options.kubbVersion,
780
878
  nodeVersion: process$1.versions.node.split(".")[0],
879
+ runtime: getRuntimeName(),
880
+ runtimeVersion: getRuntimeVersion().split(".")[0],
781
881
  platform: os.platform(),
782
882
  ci: isCIEnvironment(),
783
883
  plugins: options.plugins ?? [],
@@ -808,6 +908,14 @@ var Telemetry = class Telemetry {
808
908
  key: "kubb.node_version",
809
909
  value: { stringValue: event.nodeVersion }
810
910
  },
911
+ {
912
+ key: "kubb.runtime",
913
+ value: { stringValue: event.runtime }
914
+ },
915
+ {
916
+ key: "kubb.runtime_version",
917
+ value: { stringValue: event.runtimeVersion }
918
+ },
811
919
  {
812
920
  key: "kubb.platform",
813
921
  value: { stringValue: event.platform }
@@ -1039,6 +1147,132 @@ function defineParser(parser) {
1039
1147
  return parser;
1040
1148
  }
1041
1149
  //#endregion
1042
- export { AsyncEventEmitter, Diagnostics, KubbDriver, Telemetry, URLPath, ast, cliReporter, createAdapter, createKubb, createRenderer, createReporter, createStorage, defineGenerator, defineLogger, defineMiddleware, defineParser, definePlugin, defineResolver, fileReporter, fsStorage, jsonReporter, logLevel, memoryStorage, selectReporters };
1150
+ //#region src/Manifest.ts
1151
+ /**
1152
+ * Reads and prunes the local cache manifest. All methods are static, so call them as
1153
+ * `Manifest.read(dir)` and `Manifest.prune(data, ...)`. A damaged manifest reads as empty so the
1154
+ * cache degrades to misses instead of throwing. Writing goes through `write` from `@internals/utils`.
1155
+ */
1156
+ var Manifest = class Manifest {
1157
+ /**
1158
+ * On-disk layout version for the manifest itself. Bumped when the manifest shape changes; a
1159
+ * mismatch makes the whole local cache read as empty.
1160
+ */
1161
+ static version = 1;
1162
+ /**
1163
+ * Reads the manifest at `dir/manifest.json`. A missing, corrupt, or version-mismatched file reads
1164
+ * as an empty manifest.
1165
+ */
1166
+ static async read(dir) {
1167
+ try {
1168
+ const parsed = JSON.parse(await read(join(dir, "manifest.json")));
1169
+ if (parsed.version !== Manifest.version || typeof parsed.entries !== "object") return Manifest.#empty();
1170
+ return parsed;
1171
+ } catch {
1172
+ return Manifest.#empty();
1173
+ }
1174
+ }
1175
+ /**
1176
+ * Selects the keys to evict so the cache stays within `ttlDays` and `maxEntries`. Returns the
1177
+ * surviving manifest plus the evicted keys (the caller deletes their blobs). Pure, does no IO.
1178
+ */
1179
+ static prune(manifest, { maxEntries, ttlDays, now }) {
1180
+ const ttlMs = ttlDays * 24 * 60 * 60 * 1e3;
1181
+ const removed = [];
1182
+ const kept = [];
1183
+ for (const [key, entry] of Object.entries(manifest.entries)) if (now - entry.lastAccess > ttlMs) removed.push(key);
1184
+ else kept.push([key, entry]);
1185
+ if (kept.length > maxEntries) {
1186
+ kept.sort((a, b) => b[1].lastAccess - a[1].lastAccess);
1187
+ for (const [key] of kept.splice(maxEntries)) removed.push(key);
1188
+ }
1189
+ return {
1190
+ manifest: {
1191
+ version: Manifest.version,
1192
+ entries: Object.fromEntries(kept)
1193
+ },
1194
+ removed
1195
+ };
1196
+ }
1197
+ static #empty() {
1198
+ return {
1199
+ version: Manifest.version,
1200
+ entries: {}
1201
+ };
1202
+ }
1203
+ };
1204
+ //#endregion
1205
+ //#region src/caches/fsCache.ts
1206
+ function blobName(relativePath) {
1207
+ return `${createHash("sha256").update(relativePath).digest("hex")}.blob`;
1208
+ }
1209
+ /**
1210
+ * Local filesystem cache. Stores each build snapshot as content blobs plus an index,
1211
+ * tracked by a manifest under `node_modules/.cache/kubb/` (the Nx and Vitest
1212
+ * convention). Least-recently-used and expired entries are pruned on every persist.
1213
+ *
1214
+ * @example
1215
+ * ```ts
1216
+ * import { fsCache } from '@kubb/core'
1217
+ *
1218
+ * export default defineConfig({
1219
+ * cache: fsCache(),
1220
+ * })
1221
+ * ```
1222
+ */
1223
+ const fsCache = createCache((options = {}) => {
1224
+ const dir = resolve(options.dir ?? join("node_modules", ".cache", "kubb"));
1225
+ const maxEntries = options.maxEntries ?? 50;
1226
+ const ttlDays = options.ttlDays ?? 7;
1227
+ const blobsDir = join(dir, "blobs");
1228
+ const manifestPath = join(dir, "manifest.json");
1229
+ return {
1230
+ name: "fs",
1231
+ async restore({ key }) {
1232
+ const manifest = await Manifest.read(dir);
1233
+ const entry = manifest.entries[key];
1234
+ if (!entry) return null;
1235
+ try {
1236
+ const index = JSON.parse(await read(join(blobsDir, key, "index.json")));
1237
+ const files = {};
1238
+ for (const { path, blob } of index) files[path] = await read(join(blobsDir, key, blob));
1239
+ entry.lastAccess = Date.now();
1240
+ await write(manifestPath, JSON.stringify(manifest)).catch(() => {});
1241
+ return { files };
1242
+ } catch {
1243
+ return null;
1244
+ }
1245
+ },
1246
+ async persist({ key, snapshot }) {
1247
+ const entryDir = join(blobsDir, key);
1248
+ const index = [];
1249
+ for (const [path, source] of Object.entries(snapshot.files)) {
1250
+ const blob = blobName(path);
1251
+ await write(join(entryDir, blob), source);
1252
+ index.push({
1253
+ path,
1254
+ blob
1255
+ });
1256
+ }
1257
+ await write(join(entryDir, "index.json"), JSON.stringify(index));
1258
+ const manifest = await Manifest.read(dir);
1259
+ const now = Date.now();
1260
+ manifest.entries[key] = {
1261
+ files: index.map((item) => item.path),
1262
+ createdAt: now,
1263
+ lastAccess: now
1264
+ };
1265
+ const pruned = Manifest.prune(manifest, {
1266
+ maxEntries,
1267
+ ttlDays,
1268
+ now
1269
+ });
1270
+ await Promise.all(pruned.removed.map((removedKey) => clean(join(blobsDir, removedKey))));
1271
+ await write(manifestPath, JSON.stringify(pruned.manifest));
1272
+ }
1273
+ };
1274
+ });
1275
+ //#endregion
1276
+ export { AsyncEventEmitter, Diagnostics, KubbDriver, Telemetry, URLPath, ast, cliReporter, createAdapter, createCache, createKubb, createRenderer, createReporter, createStorage, defineGenerator, defineLogger, defineMiddleware, defineParser, definePlugin, defineResolver, fileReporter, fsCache, fsStorage, jsonReporter, logLevel, memoryStorage, selectReporters };
1043
1277
 
1044
1278
  //# sourceMappingURL=index.js.map