@kubb/core 5.0.0-beta.41 → 5.0.0-beta.43

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 Output, A as KubbHookEndContext, At as defineLogger, B as UserConfig, Bt as createAdapter, C as KubbErrorContext, Ct as UserReporter, D as KubbFilesProcessingUpdateContext, Dt as LoggerContext, E as KubbFilesProcessingStartContext, Et as Logger, F as KubbLifecycleStartContext, Ft as Storage, G as KubbDriver, H as Generator, I as KubbPluginsEndContext, It as createStorage, J as Include, K as Exclude, L as KubbSuccessContext, Lt as Adapter, M as KubbHookStartContext, Mt as Renderer, N as KubbHooks, Nt as RendererFactory, O as KubbGenerationEndContext, Ot as LoggerOptions, P as KubbInfoContext, Pt as createRenderer, Q as NormalizedPlugin, R as KubbWarnContext, Rt as AdapterFactoryOptions, S as KubbDiagnosticContext, St as ReporterName, T as KubbFilesProcessingEndContext, Tt as selectReporters, U as GeneratorContext, V as createKubb, Vt as AsyncEventEmitter, W as defineGenerator, 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 AdapterSource } from "./diagnostics-Ba-FcsPo.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-CuBWjwYc.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 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, 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-DA1bnMte.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-C0n47hZ2.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
  };
@@ -763,6 +876,8 @@ var Telemetry = class Telemetry {
763
876
  command: options.command,
764
877
  kubbVersion: options.kubbVersion,
765
878
  nodeVersion: process$1.versions.node.split(".")[0],
879
+ runtime: getRuntimeName(),
880
+ runtimeVersion: getRuntimeVersion().split(".")[0],
766
881
  platform: os.platform(),
767
882
  ci: isCIEnvironment(),
768
883
  plugins: options.plugins ?? [],
@@ -793,6 +908,14 @@ var Telemetry = class Telemetry {
793
908
  key: "kubb.node_version",
794
909
  value: { stringValue: event.nodeVersion }
795
910
  },
911
+ {
912
+ key: "kubb.runtime",
913
+ value: { stringValue: event.runtime }
914
+ },
915
+ {
916
+ key: "kubb.runtime_version",
917
+ value: { stringValue: event.runtimeVersion }
918
+ },
796
919
  {
797
920
  key: "kubb.platform",
798
921
  value: { stringValue: event.platform }
@@ -903,14 +1026,8 @@ var Telemetry = class Telemetry {
903
1026
  * get files() {
904
1027
  * return runtime.files
905
1028
  * },
906
- * dispose() {
907
- * runtime.dispose()
908
- * },
909
- * unmount(error) {
910
- * runtime.dispose(error)
911
- * },
912
1029
  * [Symbol.dispose]() {
913
- * this.dispose()
1030
+ * runtime.dispose()
914
1031
  * },
915
1032
  * }
916
1033
  * })
@@ -1024,6 +1141,132 @@ function defineParser(parser) {
1024
1141
  return parser;
1025
1142
  }
1026
1143
  //#endregion
1027
- 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 };
1144
+ //#region src/Manifest.ts
1145
+ /**
1146
+ * Reads and prunes the local cache manifest. All methods are static, so call them as
1147
+ * `Manifest.read(dir)` and `Manifest.prune(data, ...)`. A damaged manifest reads as empty so the
1148
+ * cache degrades to misses instead of throwing. Writing goes through `write` from `@internals/utils`.
1149
+ */
1150
+ var Manifest = class Manifest {
1151
+ /**
1152
+ * On-disk layout version for the manifest itself. Bumped when the manifest shape changes; a
1153
+ * mismatch makes the whole local cache read as empty.
1154
+ */
1155
+ static version = 1;
1156
+ /**
1157
+ * Reads the manifest at `dir/manifest.json`. A missing, corrupt, or version-mismatched file reads
1158
+ * as an empty manifest.
1159
+ */
1160
+ static async read(dir) {
1161
+ try {
1162
+ const parsed = JSON.parse(await read(join(dir, "manifest.json")));
1163
+ if (parsed.version !== Manifest.version || typeof parsed.entries !== "object") return Manifest.#empty();
1164
+ return parsed;
1165
+ } catch {
1166
+ return Manifest.#empty();
1167
+ }
1168
+ }
1169
+ /**
1170
+ * Selects the keys to evict so the cache stays within `ttlDays` and `maxEntries`. Returns the
1171
+ * surviving manifest plus the evicted keys (the caller deletes their blobs). Pure, does no IO.
1172
+ */
1173
+ static prune(manifest, { maxEntries, ttlDays, now }) {
1174
+ const ttlMs = ttlDays * 24 * 60 * 60 * 1e3;
1175
+ const removed = [];
1176
+ const kept = [];
1177
+ for (const [key, entry] of Object.entries(manifest.entries)) if (now - entry.lastAccess > ttlMs) removed.push(key);
1178
+ else kept.push([key, entry]);
1179
+ if (kept.length > maxEntries) {
1180
+ kept.sort((a, b) => b[1].lastAccess - a[1].lastAccess);
1181
+ for (const [key] of kept.splice(maxEntries)) removed.push(key);
1182
+ }
1183
+ return {
1184
+ manifest: {
1185
+ version: Manifest.version,
1186
+ entries: Object.fromEntries(kept)
1187
+ },
1188
+ removed
1189
+ };
1190
+ }
1191
+ static #empty() {
1192
+ return {
1193
+ version: Manifest.version,
1194
+ entries: {}
1195
+ };
1196
+ }
1197
+ };
1198
+ //#endregion
1199
+ //#region src/caches/fsCache.ts
1200
+ function blobName(relativePath) {
1201
+ return `${createHash("sha256").update(relativePath).digest("hex")}.blob`;
1202
+ }
1203
+ /**
1204
+ * Local filesystem cache. Stores each build snapshot as content blobs plus an index,
1205
+ * tracked by a manifest under `node_modules/.cache/kubb/` (the Nx and Vitest
1206
+ * convention). Least-recently-used and expired entries are pruned on every persist.
1207
+ *
1208
+ * @example
1209
+ * ```ts
1210
+ * import { fsCache } from '@kubb/core'
1211
+ *
1212
+ * export default defineConfig({
1213
+ * cache: fsCache(),
1214
+ * })
1215
+ * ```
1216
+ */
1217
+ const fsCache = createCache((options = {}) => {
1218
+ const dir = resolve(options.dir ?? join("node_modules", ".cache", "kubb"));
1219
+ const maxEntries = options.maxEntries ?? 50;
1220
+ const ttlDays = options.ttlDays ?? 7;
1221
+ const blobsDir = join(dir, "blobs");
1222
+ const manifestPath = join(dir, "manifest.json");
1223
+ return {
1224
+ name: "fs",
1225
+ async restore({ key }) {
1226
+ const manifest = await Manifest.read(dir);
1227
+ const entry = manifest.entries[key];
1228
+ if (!entry) return null;
1229
+ try {
1230
+ const index = JSON.parse(await read(join(blobsDir, key, "index.json")));
1231
+ const files = {};
1232
+ for (const { path, blob } of index) files[path] = await read(join(blobsDir, key, blob));
1233
+ entry.lastAccess = Date.now();
1234
+ await write(manifestPath, JSON.stringify(manifest)).catch(() => {});
1235
+ return { files };
1236
+ } catch {
1237
+ return null;
1238
+ }
1239
+ },
1240
+ async persist({ key, snapshot }) {
1241
+ const entryDir = join(blobsDir, key);
1242
+ const index = [];
1243
+ for (const [path, source] of Object.entries(snapshot.files)) {
1244
+ const blob = blobName(path);
1245
+ await write(join(entryDir, blob), source);
1246
+ index.push({
1247
+ path,
1248
+ blob
1249
+ });
1250
+ }
1251
+ await write(join(entryDir, "index.json"), JSON.stringify(index));
1252
+ const manifest = await Manifest.read(dir);
1253
+ const now = Date.now();
1254
+ manifest.entries[key] = {
1255
+ files: index.map((item) => item.path),
1256
+ createdAt: now,
1257
+ lastAccess: now
1258
+ };
1259
+ const pruned = Manifest.prune(manifest, {
1260
+ maxEntries,
1261
+ ttlDays,
1262
+ now
1263
+ });
1264
+ await Promise.all(pruned.removed.map((removedKey) => clean(join(blobsDir, removedKey))));
1265
+ await write(manifestPath, JSON.stringify(pruned.manifest));
1266
+ }
1267
+ };
1268
+ });
1269
+ //#endregion
1270
+ 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 };
1028
1271
 
1029
1272
  //# sourceMappingURL=index.js.map