@kubb/cli 5.11.5 → 5.12.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/{Telemetry-BlAR8vxu.js → Telemetry-B8mC2nqp.js} +2 -2
- package/dist/{Telemetry-BlAR8vxu.js.map → Telemetry-B8mC2nqp.js.map} +1 -1
- package/dist/{Telemetry-CF1YNdR-.cjs → Telemetry-Gl2uIT4u.cjs} +2 -2
- package/dist/{Telemetry-CF1YNdR-.cjs.map → Telemetry-Gl2uIT4u.cjs.map} +1 -1
- package/dist/{background-CaZZul1n.cjs → background-Bi46Uzf1.cjs} +2 -2
- package/dist/{background-CaZZul1n.cjs.map → background-Bi46Uzf1.cjs.map} +1 -1
- package/dist/{background-DUHqYiuQ.js → background-D7b5cDs_.js} +1 -1
- package/dist/{background-DKyMPeHm.js → background-DyD2KqN5.js} +2 -2
- package/dist/{background-DKyMPeHm.js.map → background-DyD2KqN5.js.map} +1 -1
- package/dist/index.cjs +19 -19
- package/dist/index.cjs.map +1 -1
- package/dist/index.js +19 -19
- package/dist/index.js.map +1 -1
- package/dist/{registry-CfYNeyOc.cjs → registry-BnkCWWeX.cjs} +3 -3
- package/dist/{registry-CfYNeyOc.cjs.map → registry-BnkCWWeX.cjs.map} +1 -1
- package/dist/{registry-D688-8EH.js → registry-Cw2X7I3b.js} +3 -3
- package/dist/{registry-D688-8EH.js.map → registry-Cw2X7I3b.js.map} +1 -1
- package/dist/{reporters-BHyW4d5Q.js → reporters-BReH227e.js} +4 -4
- package/dist/{reporters-BHyW4d5Q.js.map → reporters-BReH227e.js.map} +1 -1
- package/dist/{reporters-DrQJfnU2.cjs → reporters-lJQRYc6c.cjs} +4 -4
- package/dist/{reporters-DrQJfnU2.cjs.map → reporters-lJQRYc6c.cjs.map} +1 -1
- package/dist/{run-Cj-HJxYW.js → run-05nazgoj.js} +12 -6
- package/dist/run-05nazgoj.js.map +1 -0
- package/dist/{run-CaJbZO-f.cjs → run-8KLWLcEf.cjs} +12 -6
- package/dist/run-8KLWLcEf.cjs.map +1 -0
- package/dist/{run-CYHpe0V_.cjs → run-BDLWu55k.cjs} +22 -28
- package/dist/run-BDLWu55k.cjs.map +1 -0
- package/dist/{run-C1FHgzNR.js → run-CIE_og50.js} +2 -2
- package/dist/{run-C1FHgzNR.js.map → run-CIE_og50.js.map} +1 -1
- package/dist/{run-DkBJkKor.cjs → run-CLJnncEi.cjs} +11 -13
- package/dist/{run-DkBJkKor.cjs.map → run-CLJnncEi.cjs.map} +1 -1
- package/dist/{run-B4SKmzAG.js → run-CORf5LJQ.js} +1 -1
- package/dist/{run-S3xKq4bj.js → run-Cd6W_RNN.js} +22 -28
- package/dist/run-Cd6W_RNN.js.map +1 -0
- package/dist/{run-vBNko5TH.js → run-ChGaCan5.js} +11 -13
- package/dist/{run-vBNko5TH.js.map → run-ChGaCan5.js.map} +1 -1
- package/dist/{run-BldagXO-.cjs → run-Czt1mbNa.cjs} +2 -2
- package/dist/{run-BldagXO-.cjs.map → run-Czt1mbNa.cjs.map} +1 -1
- package/dist/{snapshot-Cvo94y5d.js → snapshot-CYfGZRlq.js} +7 -7
- package/dist/{snapshot-Cvo94y5d.js.map → snapshot-CYfGZRlq.js.map} +1 -1
- package/dist/{snapshot-CsIJRKEL.cjs → snapshot-DcLGxpoM.cjs} +7 -7
- package/dist/{snapshot-CsIJRKEL.cjs.map → snapshot-DcLGxpoM.cjs.map} +1 -1
- package/dist/{status-DTsZxa5Y.js → status-DGDWubBc.js} +3 -3
- package/dist/{status-DTsZxa5Y.js.map → status-DGDWubBc.js.map} +1 -1
- package/dist/{status-C-NPN63r.cjs → status-DrA1XG77.cjs} +3 -3
- package/dist/{status-C-NPN63r.cjs.map → status-DrA1XG77.cjs.map} +1 -1
- package/dist/studioWorker.js +2 -2
- package/dist/{summary-F11HQput.js → summary-CiCW8bRA.js} +3 -3
- package/dist/{summary-F11HQput.js.map → summary-CiCW8bRA.js.map} +1 -1
- package/dist/{summary-C22oNZu_.cjs → summary-DQ_SULKW.cjs} +3 -3
- package/dist/{summary-C22oNZu_.cjs.map → summary-DQ_SULKW.cjs.map} +1 -1
- package/dist/{text-28DwO_5A.cjs → text-BKjdI_f1.cjs} +2 -2
- package/dist/{text-28DwO_5A.cjs.map → text-BKjdI_f1.cjs.map} +1 -1
- package/dist/{text-BThr2r0T.js → text-hhzIqdVE.js} +2 -2
- package/dist/{text-BThr2r0T.js.map → text-hhzIqdVE.js.map} +1 -1
- package/dist/{utils-Cv3YUnSi.js → utils-CZzj70Rn.js} +4 -80
- package/dist/utils-CZzj70Rn.js.map +1 -0
- package/dist/{utils-BLXM2UkN.cjs → utils-Dyd-rk1U.cjs} +3 -91
- package/dist/utils-Dyd-rk1U.cjs.map +1 -0
- package/package.json +7 -7
- package/dist/run-CYHpe0V_.cjs.map +0 -1
- package/dist/run-CaJbZO-f.cjs.map +0 -1
- package/dist/run-Cj-HJxYW.js.map +0 -1
- package/dist/run-S3xKq4bj.js.map +0 -1
- package/dist/utils-BLXM2UkN.cjs.map +0 -1
- package/dist/utils-Cv3YUnSi.js.map +0 -1
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import "./rolldown-runtime-CRm0XQPb.js";
|
|
2
|
-
import { i as formatMs, o as runtime } from "./Telemetry-
|
|
3
|
-
import { p as writer } from "./text-
|
|
2
|
+
import { i as formatMs, o as runtime } from "./Telemetry-B8mC2nqp.js";
|
|
3
|
+
import { p as writer } from "./text-hhzIqdVE.js";
|
|
4
4
|
import { styleText } from "node:util";
|
|
5
5
|
import process from "node:process";
|
|
6
6
|
import { access, mkdir, readFile, readdir, writeFile } from "node:fs/promises";
|
|
@@ -320,10 +320,6 @@ const WATCHER_IGNORED_PATHS = "**/{.git,node_modules}/**";
|
|
|
320
320
|
* It outlasts chokidar's 100 ms atomic-save window, which holds back the event of a write-then-rename save.
|
|
321
321
|
*/
|
|
322
322
|
const WATCHER_DEBOUNCE_MS = 250;
|
|
323
|
-
/** Interval in milliseconds between polls of a remote `input` URL in watch mode, which emits no filesystem events. */
|
|
324
|
-
const URL_WATCHER_INTERVAL_MS = 2e3;
|
|
325
|
-
/** Upper bound in milliseconds for one URL watcher request, headers and body read, so a hung server never stalls polling. */
|
|
326
|
-
const URL_WATCHER_TIMEOUT_MS = 1e4;
|
|
327
323
|
/** `14:02:11 petStore.yaml changed`, the line a watcher prints when its input changes. */
|
|
328
324
|
function formatChange({ target, removed = false, now = /* @__PURE__ */ new Date() }) {
|
|
329
325
|
return `${styleText("dim", now.toTimeString().slice(0, 8))} ${styleText("bold", target)} ${removed ? "removed" : "changed"}`;
|
|
@@ -362,78 +358,6 @@ async function startWatcher(path, cb, log = {
|
|
|
362
358
|
await watcher.close();
|
|
363
359
|
};
|
|
364
360
|
}
|
|
365
|
-
/**
|
|
366
|
-
* Fetches the body of a remote spec URL, `undefined` when the server does not answer with a
|
|
367
|
-
* readable 2xx body before `signal` aborts. The caller seeds `startUrlWatcher` with the result, so
|
|
368
|
-
* the watcher compares polls against the content the initial build ran on.
|
|
369
|
-
*/
|
|
370
|
-
async function fetchUrlBody(url, signal = AbortSignal.timeout(URL_WATCHER_TIMEOUT_MS)) {
|
|
371
|
-
try {
|
|
372
|
-
const response = await fetch(url, { signal });
|
|
373
|
-
if (!response.ok) return void 0;
|
|
374
|
-
return await response.text();
|
|
375
|
-
} catch {
|
|
376
|
-
return;
|
|
377
|
-
}
|
|
378
|
-
}
|
|
379
|
-
/**
|
|
380
|
-
* Polls a remote spec URL and calls `cb` whenever the response body changes. A remote document
|
|
381
|
-
* emits no filesystem events, so this is the URL counterpart of `startWatcher`.
|
|
382
|
-
*
|
|
383
|
-
* `initialBody` seeds the change detection, so an edit landing between the initial build and the
|
|
384
|
-
* first poll still rebuilds. An unreachable server (the API restarting between saves) is reported
|
|
385
|
-
* once per outage and polling continues; after it recovers, a rebuild happens only when the body
|
|
386
|
-
* actually differs from the last one seen, so a plain restart with an unchanged spec stays quiet.
|
|
387
|
-
* Each request is aborted after `timeoutMs`, so a hung response delays at most one poll.
|
|
388
|
-
* `cb` must never reject: its result is not awaited.
|
|
389
|
-
*
|
|
390
|
-
* Returns a function that stops polling and aborts the in-flight request, so callers (and tests)
|
|
391
|
-
* can shut the watcher down without signaling the process.
|
|
392
|
-
*/
|
|
393
|
-
function startUrlWatcher(url, cb, options = {}) {
|
|
394
|
-
const { log = {
|
|
395
|
-
info: console.log,
|
|
396
|
-
error: console.log
|
|
397
|
-
}, intervalMs = URL_WATCHER_INTERVAL_MS, timeoutMs = URL_WATCHER_TIMEOUT_MS, initialBody } = options;
|
|
398
|
-
let lastBody = initialBody;
|
|
399
|
-
let offline = false;
|
|
400
|
-
let timer = null;
|
|
401
|
-
let controller = null;
|
|
402
|
-
let stopped = false;
|
|
403
|
-
const stop = () => {
|
|
404
|
-
stopped = true;
|
|
405
|
-
if (timer) clearTimeout(timer);
|
|
406
|
-
controller?.abort();
|
|
407
|
-
};
|
|
408
|
-
process.once("SIGINT", stop);
|
|
409
|
-
process.once("SIGTERM", stop);
|
|
410
|
-
const schedule = () => {
|
|
411
|
-
if (!stopped) timer = setTimeout(() => void poll(), intervalMs);
|
|
412
|
-
};
|
|
413
|
-
const poll = async () => {
|
|
414
|
-
controller = new AbortController();
|
|
415
|
-
const body = await fetchUrlBody(url, AbortSignal.any([controller.signal, AbortSignal.timeout(timeoutMs)]));
|
|
416
|
-
if (body === void 0) {
|
|
417
|
-
if (!offline && !stopped) {
|
|
418
|
-
offline = true;
|
|
419
|
-
log.error(styleText("red", `Cannot reach ${url}, polling until it responds again`));
|
|
420
|
-
}
|
|
421
|
-
schedule();
|
|
422
|
-
return;
|
|
423
|
-
}
|
|
424
|
-
if (offline) {
|
|
425
|
-
offline = false;
|
|
426
|
-
log.info(styleText("yellow", `${url} is reachable again`));
|
|
427
|
-
}
|
|
428
|
-
const changed = lastBody !== void 0 && body !== lastBody;
|
|
429
|
-
if (changed) log.info(formatChange({ target: url }));
|
|
430
|
-
if (changed || lastBody === void 0) cb([url]);
|
|
431
|
-
lastBody = body;
|
|
432
|
-
schedule();
|
|
433
|
-
};
|
|
434
|
-
poll();
|
|
435
|
-
return stop;
|
|
436
|
-
}
|
|
437
361
|
function createSnapshot() {
|
|
438
362
|
return {
|
|
439
363
|
schemas: /* @__PURE__ */ new Set(),
|
|
@@ -607,6 +531,6 @@ function listenForKeys({ rebuild, quit, input = process.stdin }) {
|
|
|
607
531
|
return arm;
|
|
608
532
|
}
|
|
609
533
|
//#endregion
|
|
610
|
-
export {
|
|
534
|
+
export { write as _, readOutputFiles as a, createSpinner as c, formatMsWithColor as d, getIntro as f, read as g, isPathInside as h, listenForKeys as i, withSpinner as l, exists as m, diffFiles as n, startWatcher as o, wakeUp as p, diffOutput as r, trackBuild as s, diffBuilds as t, formatBar as u };
|
|
611
535
|
|
|
612
|
-
//# sourceMappingURL=utils-
|
|
536
|
+
//# sourceMappingURL=utils-CZzj70Rn.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"utils-CZzj70Rn.js","names":[],"sources":["../../../internals/utils/src/fs.ts","../../../internals/utils/src/promise.ts","../src/loggers/banner.ts","../src/ui/spinner.ts","../src/runners/generate/utils.ts"],"sourcesContent":["import { access, glob as globNode, mkdir, readFile, writeFile } from 'node:fs/promises'\n\nimport { dirname, isAbsolute, join, relative, resolve } from 'node:path'\nimport { runtime } from './runtime.ts'\n\nexport { existsSync } from 'node:fs'\nexport { mkdir, mkdtemp, rm } from 'node:fs/promises'\n\n/**\n * Resolves to `true` when the file or directory at `path` exists.\n * Uses `Bun.file().exists()` when running under Bun, `fs.access` otherwise.\n *\n * @example\n * ```ts\n * if (await exists('./kubb.config.ts')) {\n * const content = await read('./kubb.config.ts')\n * }\n * ```\n */\nexport async function exists(path: string): Promise<boolean> {\n if (runtime.isBun) {\n return Bun.file(path).exists()\n }\n return access(path).then(\n () => true,\n () => false,\n )\n}\n\n/**\n * Reads the file at `path` as a UTF-8 string.\n * Uses `Bun.file().text()` when running under Bun, `fs.readFile` otherwise.\n *\n * @example\n * ```ts\n * const source = await read('./src/Pet.ts')\n * ```\n */\nexport async function read(path: string): Promise<string> {\n if (runtime.isBun) {\n return Bun.file(path).text()\n }\n return readFile(path, { encoding: 'utf8' })\n}\n\ntype WriteOptions = {\n /**\n * Previously read content, or `null` when the file does not exist.\n * Omitting this value reads the file before writing.\n */\n stored?: string | null\n /**\n * When `true`, re-reads the file immediately after writing and throws if the\n * content does not match — useful for catching write failures on unreliable file systems.\n */\n sanity?: boolean\n}\n\n/**\n * Whether `stored` already holds `source`, comparing on the trimmed text rather than the exact\n * bytes. Surrounding whitespace is what a formatter adds and what editors strip, and neither is a\n * reason to rewrite the file.\n *\n * Both sides are trimmed, so a storage that keeps bytes verbatim settles on the same answer as one\n * that normalizes what it stores. Trimming only `stored` would leave a source with leading\n * whitespace rewritten on every build, since the stored copy keeps the whitespace the comparison\n * has already dropped.\n */\nexport function matchesStored({ stored, source }: { stored: string; source: string }): boolean {\n return stored.trim() === source.trim()\n}\n\n/**\n * Writes `data` to `path`, trimming surrounding whitespace and ending the file with a single newline\n * the way prettier, biome, and oxfmt all do.\n * Skips the write when the trimmed content is empty, or when the file already holds that content.\n * Creates any missing parent directories automatically.\n * When `sanity` is `true`, re-reads the file after writing and throws if the content does not match.\n *\n * @example\n * ```ts\n * await write('./src/Pet.ts', source) // writes and returns the trimmed content plus a newline\n * await write('./src/Pet.ts', source) // null — file unchanged\n * await write('./src/Pet.ts', ' ') // null — empty content skipped\n * ```\n */\nexport async function write(path: string, data: string, options: WriteOptions = {}): Promise<string | null> {\n const trimmed = data.trim()\n if (trimmed === '') return null\n\n const content = `${trimmed}\\n`\n const resolved = resolve(path)\n let stored = options.stored\n\n if (stored === undefined) {\n if (runtime.isBun) {\n const file = Bun.file(resolved)\n stored = (await file.exists()) ? await file.text() : null\n } else {\n try {\n stored = await readFile(resolved, { encoding: 'utf-8' })\n } catch {\n /* file doesn't exist yet */\n stored = null\n }\n }\n }\n if (matchesStored({ stored: stored ?? '', source: trimmed })) return null\n\n await writeRaw(resolved, content)\n\n if (options.sanity) {\n const savedData = await read(resolved)\n if (savedData !== content) {\n throw new Error(`Sanity check failed for ${path}\\n\\nData[${data.length}]:\\n${data}\\n\\nSaved[${savedData.length}]:\\n${savedData}\\n`)\n }\n return savedData\n }\n\n return content\n}\n\n/**\n * Writes UTF-8 content verbatim, including empty files and surrounding whitespace.\n * Uses Bun.write under Bun and creates missing parent directories under either runtime.\n *\n * @example\n * await writeRaw('./cache/output.ts', ' // keep these bytes\\n\\n')\n */\nexport async function writeRaw(path: string, content: string): Promise<void> {\n const resolved = resolve(path)\n if (runtime.isBun) {\n await Bun.write(resolved, content)\n return\n }\n try {\n await writeFile(resolved, content, { encoding: 'utf-8' })\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error\n await mkdir(dirname(resolved), { recursive: true })\n await writeFile(resolved, content, { encoding: 'utf-8' })\n }\n}\n\n/**\n * Lists non-hidden regular files below `directory` as relative POSIX paths, excluding directories and symlinks.\n * Uses Bun.Glob under Bun because its Node glob compatibility API lacks directory-entry support.\n *\n * @example\n * for await (const path of listFiles('./src')) console.log(path)\n */\nexport async function* listFiles(directory: string): AsyncGenerator<string> {\n const cwd = resolve(directory)\n if (runtime.isBun) {\n yield* new Bun.Glob('**/*').scan({ cwd, dot: false, onlyFiles: true, followSymlinks: false })\n return\n }\n for await (const entry of globNode('**/*', { cwd, withFileTypes: true })) {\n if (entry.isFile()) yield toPosixPath(relative(cwd, join(entry.parentPath, entry.name)))\n }\n}\n\n/**\n * Converts a filesystem path to use POSIX (`/`) separators.\n *\n * Most of the codebase compares and composes paths as strings (prefix matching, joining for\n * import specifiers, splitting on `/`). On POSIX `path.resolve` already returns `/`-separated\n * paths, but on Windows it returns `\\`-separated paths, which breaks every such comparison.\n *\n * Routing every path that crosses a module boundary through `toPosixPath` keeps the rest of the\n * code platform-agnostic. The conversion runs unconditionally so Windows-specific behavior is\n * exercisable from POSIX CI.\n *\n * @example\n * toPosixPath('C:\\\\repo\\\\src\\\\pet.ts') // 'C:/repo/src/pet.ts'\n */\nexport function toPosixPath(filePath: string): string {\n return filePath.replaceAll('\\\\', '/')\n}\n\n/**\n * Strips the file extension from a path or file name.\n * Only removes the last `.ext` segment when the dot is not part of a directory name.\n *\n * @example\n * trimExtName('petStore.ts') // 'petStore'\n * trimExtName('/src/models/pet.ts') // '/src/models/pet'\n * trimExtName('/project.v2/gen/pet.ts') // '/project.v2/gen/pet'\n * trimExtName('noExtension') // 'noExtension'\n */\nexport function trimExtName(text: string): string {\n const dotIndex = text.lastIndexOf('.')\n if (dotIndex > 0 && !text.includes('/', dotIndex)) {\n return text.slice(0, dotIndex)\n }\n return text\n}\n\n/**\n * Resolves to `true` when `path` is `parent` itself or nested inside it. Both sides are resolved\n * to absolute paths first, so relative and `..`-containing inputs compare correctly.\n *\n * Guards a destructive or an out-of-tree operation: before wiping an output directory, check that\n * it does not contain the project root, and before loading a path a caller supplied, check that it\n * did not escape the directory it is allowed to read from.\n *\n * @example\n * isPathInside('./src/gen', '.') // true — nested inside the root\n * isPathInside('.', '.') // true — the same directory counts as inside\n * isPathInside('.', './src/gen') // false — the root is not inside its own output\n * isPathInside('../other', '.') // false — escapes the root\n */\nexport function isPathInside(path: string, parent: string): boolean {\n const resolvedPath = resolve(path)\n const resolvedParent = resolve(parent)\n if (resolvedPath === resolvedParent) {\n return true\n }\n\n const rel = relative(resolvedParent, resolvedPath)\n\n return rel !== '' && !rel.startsWith('..') && !isAbsolute(rel)\n}\n","/** A value that may already be resolved or still pending.\n *\n * @example\n * ```ts\n * function load(id: string): PossiblePromise<string> {\n * return cache.get(id) ?? fetchRemote(id)\n * }\n * ```\n */\nexport type PossiblePromise<T> = Promise<T> | T\n\ntype Store<TKey, TValue> = {\n has(key: TKey): boolean\n get(key: TKey): TValue | undefined\n set(key: TKey, value: TValue): unknown\n}\n\n/**\n * Wraps `factory` with a keyed cache backed by the provided store.\n *\n * Pass a `WeakMap` for object keys (results are GC-eligible when the key is\n * collected) or a `Map` for primitive keys. For multi-argument functions,\n * nest two `memoize` calls — the outer keyed by the first argument, the\n * inner (created once per outer miss) keyed by the second.\n *\n * Because the cache is owned by the caller, it can be shared, inspected, or\n * cleared independently of the memoized function.\n *\n * @example Single WeakMap key\n * ```ts\n * const cache = new WeakMap<SchemaNode, Set<string>>()\n * const getRefs = memoize(cache, (node) => collectRefs(node))\n * ```\n *\n * @example Single Map key (primitive)\n * ```ts\n * const cache = new Map<string, Resolver>()\n * const getResolver = memoize(cache, (name) => buildResolver(name))\n * ```\n *\n * @example Two-level (object + primitive)\n * ```ts\n * const outer = new WeakMap<Params[], Map<string, Params[]>>()\n * const fn = memoize(outer, (params) => memoize(new Map(), (key) => transform(params, key)))\n * fn(params)('camelcase')\n * ```\n */\nexport function memoize<TKey, TValue>(store: Store<TKey, TValue>, factory: (key: TKey) => TValue): (key: TKey) => TValue {\n return (key: TKey): TValue => {\n if (store.has(key)) return store.get(key)!\n const value = factory(key)\n store.set(key, value)\n return value\n }\n}\n\ntype ParallelOptions<TItem> = {\n /**\n * Items to work through, handed out in order.\n */\n items: ReadonlyArray<TItem>\n /**\n * How many items may be in flight at once.\n */\n limit: number\n /**\n * Runs once per item, with the item's position so a caller can report progress.\n */\n run(item: TItem, index: number): Promise<void>\n}\n\n/**\n * Runs `run` over every item with at most `limit` in flight. Workers share one iterator, so each\n * takes the next item the moment it frees up instead of waiting for a batch to drain.\n *\n * @example\n * ```ts\n * await inParallel({ items: files, limit: 50, run: (file) => storage.writeItem(file.path, file.source) })\n * ```\n */\nexport async function inParallel<TItem>({ items, limit, run }: ParallelOptions<TItem>): Promise<void> {\n const queue = items.entries()\n\n const worker = async (): Promise<void> => {\n for (const [index, item] of queue) await run(item, index)\n }\n\n await Promise.all(Array.from({ length: Math.min(limit, items.length) }, () => worker()))\n}\n","import { styleText } from 'node:util'\nimport { formatMs } from '@internals/utils'\n\n/**\n * xterm-256 color for each pixel letter of the mascot. Fixed codes rather than named colors, so a\n * terminal theme cannot repaint it.\n */\nconst colors: Record<string, number> = {\n /** Hoodie. */\n O: 208,\n /** Shadow where the hood meets the face. */\n R: 166,\n /** Face. */\n F: 223,\n /** Eyes. */\n K: 16,\n /** Blush. */\n B: 217,\n /** Mouth. */\n M: 131,\n}\n\n/**\n * The two pixel rows of the face around the eyes, for each expression.\n */\nconst eyes = {\n open: ['FFFFFFFFFF', 'FFKFFFFKFF'],\n left: ['FFFFFFFFFF', 'FKFFFFKFFF'],\n right: ['FFFFFFFFFF', 'FFFKFFFFKF'],\n blink: ['FFFFFFFFFF', 'FKKFFFFKKF'],\n happy: ['FFKFFFFKFF', 'FKFKFFKFKF'],\n} as const\n\nexport type Expression = keyof typeof eyes\n\n/**\n * The frames the mascot plays when the CLI starts, each with how long it stays on screen. It ends on\n * open eyes, which stay.\n */\nexport const wakeUp: ReadonlyArray<readonly [Expression, number]> = [\n ['blink', 100],\n ['open', 180],\n ['left', 140],\n ['right', 140],\n ['open', 80],\n ['happy', 220],\n ['open', 0],\n]\n\n/**\n * The kid in the orange hoodie from the Kubb logo, one letter per pixel and `.` for none. Each\n * 2 × 2 block becomes one terminal cell, so a block holds at most two colors.\n */\nexport function pixels(expression: Expression): Array<string> {\n const [top, bottom] = eyes[expression]\n\n // prettier-ignore\n return [\n '....OOOOOOOOOO....',\n '..OORRRRRRRRRROO..',\n `..OO${top}OO..`,\n `OOFF${bottom}FFOO`,\n 'OOFFBBFFMMFFBBFFOO',\n '..OOOOFFFFFFOOOO..',\n ]\n}\n\n/**\n * Quadrant glyphs indexed by which quarters are filled: top left 1, top right 2, bottom left 4,\n * bottom right 8.\n */\nconst quadrants = ' ▘▝▀▖▌▞▛▗▚▐▜▄▙▟█'\n\n/**\n * Draws each 2 × 2 block of pixels as one quadrant glyph. The glyph's filled quarters take the first\n * color in the block and the rest take the other.\n */\nfunction drawHead(expression: Expression): Array<string> {\n const rows = pixels(expression)\n const lines: Array<string> = []\n\n for (let y = 0; y < rows.length; y += 2) {\n let line = ''\n for (let x = 0; x < rows[y]!.length; x += 2) {\n const block = [rows[y]![x]!, rows[y]![x + 1]!, rows[y + 1]![x]!, rows[y + 1]![x + 1]!]\n const fg = block.find((pixel) => pixel in colors)\n if (!fg) {\n line += ' '\n continue\n }\n const bg = colors[block.find((pixel) => pixel !== fg) ?? '.']\n const mask = block.reduce((bits, pixel, index) => (pixel === fg ? bits | (1 << index) : bits), 0)\n line += `\\x1b[38;5;${colors[fg]}${bg === undefined ? '' : `;48;5;${bg}`}m${quadrants[mask]}\\x1b[0m`\n }\n lines.push(line)\n }\n\n return lines\n}\n\n/**\n * Generates the Kubb mascot welcome banner as an ANSI-colored string: the head with the version,\n * title, and description beside it.\n *\n * @example\n * ```ts\n * console.log(getIntro({ title: 'kubb.config.ts', description: 'generating…', version: '5.0.0', expression: 'open' }))\n * ```\n */\nexport function getIntro({\n title,\n description,\n version,\n expression,\n}: {\n /**\n * Name of the active configuration or tool being started.\n */\n title: string\n /**\n * Short subtitle shown next to the arrow prompt.\n */\n description: string\n /**\n * Kubb version string rendered in the header.\n */\n version: string\n /**\n * Which face the mascot makes.\n */\n expression: Expression\n}): string {\n // The hoodie's fixed code, so the title is Kubb orange whatever the terminal theme does to `yellow`.\n const brand = (value: string, bold = false) => `\\x1b[${bold ? '1;' : ''}38;5;${colors.O}m${value}\\x1b[0m`\n const text = [brand(`KUBB v${version}`, true), styleText('gray', title), `${brand('➜')} ${styleText('white', description)}`]\n\n return drawHead(expression)\n .map((line, index) => ` ${line} ${text[index]}`)\n .join('\\n')\n}\n\n/**\n * Formats a millisecond duration with a threshold-based ANSI color.\n * `≤ 500 ms` → green · `≤ 1 000 ms` → yellow · `> 1 000 ms` → red.\n *\n * @example\n * ```ts\n * formatMsWithColor(200) // '\\x1b[32m200ms\\x1b[39m'\n * formatMsWithColor(800) // '\\x1b[33m800ms\\x1b[39m'\n * formatMsWithColor(1500) // '\\x1b[31m1.50s\\x1b[39m'\n * ```\n */\nexport function formatMsWithColor(ms: number): string {\n const formatted = formatMs(ms)\n if (ms <= 500) return styleText('green', formatted)\n if (ms <= 1000) return styleText('yellow', formatted)\n\n return styleText('red', formatted)\n}\n\n/**\n * A `size`-cell progress bar: `done` of `total` as filled cells, the rest light. Any progress shows\n * at least one cell, and only a finished bar fills the last one.\n */\nexport function formatBar(done: number, total: number, size = 20): string {\n const filled = !done ? 0 : done >= total ? size : Math.min(size - 1, Math.max(1, Math.round((done / total) * size)))\n return styleText('magenta', '█'.repeat(filled)) + styleText('dim', '░'.repeat(size - filled))\n}\n","import type { WriterSpinner } from '../loggers/types.ts'\nimport { writer } from './log.ts'\n\n/**\n * A progress spinner, or a writer that prints each message it is given when the terminal cannot\n * animate one. Callers drive both the same way, including the failure state.\n */\nexport function createSpinner(): WriterSpinner {\n return writer().spinner()\n}\n\n/** How long a wait may run before a spinner shows, so a fast answer draws nothing. */\nconst SPINNER_DELAY_MS = 150\n\n/**\n * Awaits `promise`, showing a spinner with `message` only when it takes longer than 150 ms.\n */\nexport async function withSpinner<T>({ promise, message }: { promise: Promise<T>; message: string }): Promise<T> {\n let spinner: WriterSpinner | undefined\n const timer = setTimeout(() => {\n spinner = createSpinner()\n spinner.start(message)\n }, SPINNER_DELAY_MS)\n try {\n return await promise\n } finally {\n clearTimeout(timer)\n spinner?.clear()\n }\n}\n","import { readdir } from 'node:fs/promises'\nimport { join, relative } from 'node:path'\nimport process from 'node:process'\nimport { styleText } from 'node:util'\nimport { inParallel, matchesStored, read } from '@internals/utils'\nimport type { Hookable, KubbHooks, OutputManifest, Storage } from '@kubb/core'\n\n/** Glob pattern for paths the file watcher ignores. */\nconst WATCHER_IGNORED_PATHS = '**/{.git,node_modules}/**' as const\n\n/**\n * Quiet window in milliseconds that collapses a burst of watcher events (an editor save emits several) into one rebuild.\n * It outlasts chokidar's 100 ms atomic-save window, which holds back the event of a write-then-rename save.\n */\nconst WATCHER_DEBOUNCE_MS = 250\n\n/** `14:02:11 petStore.yaml changed`, the line a watcher prints when its input changes. */\nexport function formatChange({ target, removed = false, now = new Date() }: { target: string; removed?: boolean; now?: Date }): string {\n return `${styleText('dim', now.toTimeString().slice(0, 8))} ${styleText('bold', target)} ${removed ? 'removed' : 'changed'}`\n}\n\ntype WatcherLog = {\n info: (message: string) => void\n error: (message: string) => void\n}\n\n/**\n * Starts a file watcher on the given paths and calls `cb` on any change.\n * Ignores `.git` and `node_modules` directories. Event bursts (an editor save emits several)\n * are debounced into one call. `cb` must never reject: its result is not awaited, so the caller\n * serializes and reports its own builds. Resolves to a function that stops watching.\n */\nexport async function startWatcher(\n path: Array<string>,\n cb: (path: Array<string>) => Promise<void>,\n log: WatcherLog = { info: console.log, error: console.log },\n): Promise<() => Promise<void>> {\n const { watch } = await import('chokidar')\n // `ignoreInitial` skips the `add` events chokidar fires for existing files at startup, which\n // would otherwise rebuild right after the initial run.\n const watcher = watch(path, { ignorePermissionErrors: true, ignored: WATCHER_IGNORED_PATHS, ignoreInitial: true })\n\n for (const signal of ['SIGINT', 'SIGTERM'] as const) {\n process.once(signal, () => void watcher.close())\n }\n\n let debounceTimer: ReturnType<typeof setTimeout> | null = null\n\n watcher.on('all', (type, file) => {\n log.info(formatChange({ target: relative(process.cwd(), file), removed: type === 'unlink' }))\n if (debounceTimer) clearTimeout(debounceTimer)\n debounceTimer = setTimeout(() => {\n debounceTimer = null\n void cb(path)\n }, WATCHER_DEBOUNCE_MS)\n })\n\n return async () => {\n if (debounceTimer) clearTimeout(debounceTimer)\n await watcher.close()\n }\n}\n\n/**\n * What one build produced: the schema and operation names the plugins generated.\n */\nexport type BuildSnapshot = {\n schemas: Set<string>\n operations: Set<string>\n}\n\nfunction createSnapshot(): BuildSnapshot {\n return { schemas: new Set(), operations: new Set() }\n}\n\n/**\n * Collects a {@link BuildSnapshot} from the hooks while a build runs. `take` hands back the finished\n * build's snapshot and starts the next one.\n */\nexport function trackBuild(hooks: Hookable<KubbHooks>): { take(): BuildSnapshot } {\n let current = createSnapshot()\n\n hooks.hook('kubb:generate:schema', (node) => {\n if (node.name) current.schemas.add(node.name)\n })\n hooks.hook('kubb:generate:operation', (node) => {\n current.operations.add(node.operationId)\n })\n\n return {\n take() {\n const snapshot = current\n current = createSnapshot()\n return snapshot\n },\n }\n}\n\ntype NameChange = { added: number; removed: number }\n\n/**\n * How a rebuild differs from the build before it: the spec's added and removed schemas and operations.\n */\nexport type BuildDiff = {\n schemas: NameChange\n operations: NameChange\n}\n\nfunction diffNames(previous: Set<string>, next: Set<string>): NameChange {\n return { added: [...next].filter((name) => !previous.has(name)).length, removed: [...previous].filter((name) => !next.has(name)).length }\n}\n\n/**\n * Compares two {@link BuildSnapshot}s by name.\n */\nexport function diffBuilds(previous: BuildSnapshot, next: BuildSnapshot): BuildDiff {\n return {\n schemas: diffNames(previous.schemas, next.schemas),\n operations: diffNames(previous.operations, next.operations),\n }\n}\n\n/**\n * Compares file contents or fingerprints by path.\n */\nexport function diffFiles(previous: ReadonlyMap<string, string>, next: ReadonlyMap<string, string>): { files: Array<FileChange>; unchanged: number } {\n const files: Array<FileChange> = []\n let unchanged = 0\n for (const [path, fingerprint] of next) {\n const before = previous.get(path)\n if (before === fingerprint) unchanged++\n else files.push({ status: before === undefined ? 'A' : 'M', path })\n }\n for (const path of previous.keys()) {\n if (!next.has(path)) files.push({ status: 'D', path })\n }\n\n return { files, unchanged }\n}\n\n/** A changed file with how many lines it gains and loses, counted as a multiset, which is cheap and close enough for a plan. */\nexport type FileChange = { status: 'A' | 'M' | 'D'; path: string; added?: number; removed?: number }\n\nfunction countLineChanges(before: string, after: string): { added: number; removed: number } {\n const remaining = new Map<string, number>()\n for (const line of before ? before.split('\\n') : []) remaining.set(line, (remaining.get(line) ?? 0) + 1)\n let added = 0\n for (const line of after ? after.split('\\n') : []) {\n const count = remaining.get(line) ?? 0\n if (count > 0) remaining.set(line, count - 1)\n else added++\n }\n const removed = [...remaining.values()].reduce((sum, count) => sum + count, 0)\n return { added, removed }\n}\n\n/**\n * Reads the output before generation, so cleaning the directory cannot erase the diff baseline.\n * A missing directory or an unreadable file is skipped.\n */\nexport async function readOutputFiles(outputPath: string): Promise<Map<string, string>> {\n const entries = await readdir(outputPath, { recursive: true, withFileTypes: true }).catch(() => [])\n const files = new Map<string, string>()\n await inParallel({\n items: entries.filter((entry) => entry.isFile()).map((entry) => join(entry.parentPath, entry.name)),\n limit: 50,\n run: async (filePath) => {\n const source = await read(filePath).catch(() => null)\n if (source !== null) files.set(filePath, source)\n },\n })\n return files\n}\n\n/**\n * Compares generated output with the files captured before generation. The manifest recognizes\n * output rewritten by a formatter, and `clean` includes files the run would delete.\n */\nexport async function diffOutput({\n storage,\n paths,\n clean,\n manifest,\n previousFiles,\n}: {\n storage: Storage\n paths: ReadonlyArray<string>\n clean: boolean\n manifest?: Pick<OutputManifest, 'isUpToDate'>\n /**\n * The output captured before a real run, including files removed by cleaning.\n */\n previousFiles: ReadonlyMap<string, string>\n}): Promise<{ files: Array<FileChange>; unchanged: number }> {\n const generated = new Set(paths)\n const changes: Array<FileChange | undefined> = []\n let unchanged = 0\n await inParallel({\n items: paths,\n limit: 50,\n run: async (filePath, index) => {\n const next = await storage.readItem(filePath)\n if (next === null) return\n const previous = previousFiles.get(filePath) ?? null\n if (previous !== null && (matchesStored({ stored: previous, source: next }) || manifest?.isUpToDate({ key: filePath, source: next, disk: previous }))) {\n unchanged++\n return\n }\n changes[index] = {\n status: previous === null ? 'A' : 'M',\n path: filePath,\n ...countLineChanges(previous?.trim() ?? '', previous === null ? next.trimEnd() : next.trim()),\n }\n },\n })\n const files = changes.filter((file) => file !== undefined)\n if (clean) {\n for (const [filePath, source] of previousFiles) {\n if (!generated.has(filePath)) files.push({ status: 'D', path: filePath, ...countLineChanges(source.trimEnd(), '') })\n }\n }\n\n return { files, unchanged }\n}\n\ntype KeyInput = Pick<NodeJS.ReadStream, 'isTTY' | 'setRawMode' | 'resume' | 'pause' | 'setEncoding' | 'on'>\n\ntype KeyOptions = {\n rebuild: () => void\n /**\n * Ends the process with this exit code: `0` for `q`, `130` for ctrl+c, which raw mode turns into a key.\n */\n quit: (code: number) => void\n input?: KeyInput\n}\n\n/**\n * Reads `r` (rebuild) and `q` (quit) from an interactive stdin in raw mode, and keeps ctrl+c\n * working. Returns `undefined` when stdin is not a TTY. Otherwise returns `arm`, which turns raw\n * mode back on: a spinner restores the terminal when it stops, so call it after each build. Raw mode\n * is restored on exit.\n */\nexport function listenForKeys({ rebuild, quit, input = process.stdin }: KeyOptions): (() => void) | undefined {\n if (!input.isTTY) return undefined\n\n const arm = () => {\n input.setRawMode(true)\n input.resume()\n }\n input.setEncoding('utf8')\n input.on('data', (data: string) => {\n const key = data.trim()\n if (key === 'r') {\n rebuild()\n return\n }\n if (key === 'q' || data === '\\u0003') {\n input.setRawMode(false)\n input.pause()\n quit(key === 'q' ? 0 : 130)\n }\n })\n process.once('exit', () => input.setRawMode(false))\n arm()\n\n return arm\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;AAmBA,eAAsB,OAAO,MAAgC;CAC3D,IAAI,QAAQ,OACV,OAAO,IAAI,KAAK,IAAI,CAAC,CAAC,OAAO;CAE/B,OAAO,OAAO,IAAI,CAAC,CAAC,WACZ,YACA,KACR;AACF;;;;;;;;;;AAWA,eAAsB,KAAK,MAA+B;CACxD,IAAI,QAAQ,OACV,OAAO,IAAI,KAAK,IAAI,CAAC,CAAC,KAAK;CAE7B,OAAO,SAAS,MAAM,EAAE,UAAU,OAAO,CAAC;AAC5C;;;;;;;;;;;AAyBA,SAAgB,cAAc,EAAE,QAAQ,UAAuD;CAC7F,OAAO,OAAO,KAAK,MAAM,OAAO,KAAK;AACvC;;;;;;;;;;;;;;;AAgBA,eAAsB,MAAM,MAAc,MAAc,UAAwB,CAAC,GAA2B;CAC1G,MAAM,UAAU,KAAK,KAAK;CAC1B,IAAI,YAAY,IAAI,OAAO;CAE3B,MAAM,UAAU,GAAG,QAAQ;CAC3B,MAAM,WAAW,QAAQ,IAAI;CAC7B,IAAI,SAAS,QAAQ;CAErB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,QAAQ,KAAK;GACf,QAAQ;GACR;EACF;EACA,IAAI,QAAQ,OAAO,SAAS,KAAU;GACpC,MAAM,WAAW,KAAK;GACtB,MAAM,MAAM;GACZ,KAAK,QAAQ,MAAM,IAAI,GAAG;EAC5B;CACF,CAAC;CACD,QAAQ,KAAK,cAAc,MAAM,WAAW,KAAK,CAAC;CAClD,IAAI;CAEJ,OAAO;AACT"}
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
const require_rolldown_runtime = require("./rolldown-runtime-CPE0t6oh.cjs");
|
|
2
|
-
const require_Telemetry = require("./Telemetry-
|
|
3
|
-
const require_text = require("./text-
|
|
2
|
+
const require_Telemetry = require("./Telemetry-Gl2uIT4u.cjs");
|
|
3
|
+
const require_text = require("./text-BKjdI_f1.cjs");
|
|
4
4
|
let node_util = require("node:util");
|
|
5
5
|
let node_process = require("node:process");
|
|
6
6
|
node_process = require_rolldown_runtime.__toESM(node_process, 1);
|
|
@@ -322,10 +322,6 @@ const WATCHER_IGNORED_PATHS = "**/{.git,node_modules}/**";
|
|
|
322
322
|
* It outlasts chokidar's 100 ms atomic-save window, which holds back the event of a write-then-rename save.
|
|
323
323
|
*/
|
|
324
324
|
const WATCHER_DEBOUNCE_MS = 250;
|
|
325
|
-
/** Interval in milliseconds between polls of a remote `input` URL in watch mode, which emits no filesystem events. */
|
|
326
|
-
const URL_WATCHER_INTERVAL_MS = 2e3;
|
|
327
|
-
/** Upper bound in milliseconds for one URL watcher request, headers and body read, so a hung server never stalls polling. */
|
|
328
|
-
const URL_WATCHER_TIMEOUT_MS = 1e4;
|
|
329
325
|
/** `14:02:11 petStore.yaml changed`, the line a watcher prints when its input changes. */
|
|
330
326
|
function formatChange({ target, removed = false, now = /* @__PURE__ */ new Date() }) {
|
|
331
327
|
return `${(0, node_util.styleText)("dim", now.toTimeString().slice(0, 8))} ${(0, node_util.styleText)("bold", target)} ${removed ? "removed" : "changed"}`;
|
|
@@ -364,78 +360,6 @@ async function startWatcher(path, cb, log = {
|
|
|
364
360
|
await watcher.close();
|
|
365
361
|
};
|
|
366
362
|
}
|
|
367
|
-
/**
|
|
368
|
-
* Fetches the body of a remote spec URL, `undefined` when the server does not answer with a
|
|
369
|
-
* readable 2xx body before `signal` aborts. The caller seeds `startUrlWatcher` with the result, so
|
|
370
|
-
* the watcher compares polls against the content the initial build ran on.
|
|
371
|
-
*/
|
|
372
|
-
async function fetchUrlBody(url, signal = AbortSignal.timeout(URL_WATCHER_TIMEOUT_MS)) {
|
|
373
|
-
try {
|
|
374
|
-
const response = await fetch(url, { signal });
|
|
375
|
-
if (!response.ok) return void 0;
|
|
376
|
-
return await response.text();
|
|
377
|
-
} catch {
|
|
378
|
-
return;
|
|
379
|
-
}
|
|
380
|
-
}
|
|
381
|
-
/**
|
|
382
|
-
* Polls a remote spec URL and calls `cb` whenever the response body changes. A remote document
|
|
383
|
-
* emits no filesystem events, so this is the URL counterpart of `startWatcher`.
|
|
384
|
-
*
|
|
385
|
-
* `initialBody` seeds the change detection, so an edit landing between the initial build and the
|
|
386
|
-
* first poll still rebuilds. An unreachable server (the API restarting between saves) is reported
|
|
387
|
-
* once per outage and polling continues; after it recovers, a rebuild happens only when the body
|
|
388
|
-
* actually differs from the last one seen, so a plain restart with an unchanged spec stays quiet.
|
|
389
|
-
* Each request is aborted after `timeoutMs`, so a hung response delays at most one poll.
|
|
390
|
-
* `cb` must never reject: its result is not awaited.
|
|
391
|
-
*
|
|
392
|
-
* Returns a function that stops polling and aborts the in-flight request, so callers (and tests)
|
|
393
|
-
* can shut the watcher down without signaling the process.
|
|
394
|
-
*/
|
|
395
|
-
function startUrlWatcher(url, cb, options = {}) {
|
|
396
|
-
const { log = {
|
|
397
|
-
info: console.log,
|
|
398
|
-
error: console.log
|
|
399
|
-
}, intervalMs = URL_WATCHER_INTERVAL_MS, timeoutMs = URL_WATCHER_TIMEOUT_MS, initialBody } = options;
|
|
400
|
-
let lastBody = initialBody;
|
|
401
|
-
let offline = false;
|
|
402
|
-
let timer = null;
|
|
403
|
-
let controller = null;
|
|
404
|
-
let stopped = false;
|
|
405
|
-
const stop = () => {
|
|
406
|
-
stopped = true;
|
|
407
|
-
if (timer) clearTimeout(timer);
|
|
408
|
-
controller?.abort();
|
|
409
|
-
};
|
|
410
|
-
node_process.default.once("SIGINT", stop);
|
|
411
|
-
node_process.default.once("SIGTERM", stop);
|
|
412
|
-
const schedule = () => {
|
|
413
|
-
if (!stopped) timer = setTimeout(() => void poll(), intervalMs);
|
|
414
|
-
};
|
|
415
|
-
const poll = async () => {
|
|
416
|
-
controller = new AbortController();
|
|
417
|
-
const body = await fetchUrlBody(url, AbortSignal.any([controller.signal, AbortSignal.timeout(timeoutMs)]));
|
|
418
|
-
if (body === void 0) {
|
|
419
|
-
if (!offline && !stopped) {
|
|
420
|
-
offline = true;
|
|
421
|
-
log.error((0, node_util.styleText)("red", `Cannot reach ${url}, polling until it responds again`));
|
|
422
|
-
}
|
|
423
|
-
schedule();
|
|
424
|
-
return;
|
|
425
|
-
}
|
|
426
|
-
if (offline) {
|
|
427
|
-
offline = false;
|
|
428
|
-
log.info((0, node_util.styleText)("yellow", `${url} is reachable again`));
|
|
429
|
-
}
|
|
430
|
-
const changed = lastBody !== void 0 && body !== lastBody;
|
|
431
|
-
if (changed) log.info(formatChange({ target: url }));
|
|
432
|
-
if (changed || lastBody === void 0) cb([url]);
|
|
433
|
-
lastBody = body;
|
|
434
|
-
schedule();
|
|
435
|
-
};
|
|
436
|
-
poll();
|
|
437
|
-
return stop;
|
|
438
|
-
}
|
|
439
363
|
function createSnapshot() {
|
|
440
364
|
return {
|
|
441
365
|
schemas: /* @__PURE__ */ new Set(),
|
|
@@ -639,12 +563,6 @@ Object.defineProperty(exports, "exists", {
|
|
|
639
563
|
return exists;
|
|
640
564
|
}
|
|
641
565
|
});
|
|
642
|
-
Object.defineProperty(exports, "fetchUrlBody", {
|
|
643
|
-
enumerable: true,
|
|
644
|
-
get: function() {
|
|
645
|
-
return fetchUrlBody;
|
|
646
|
-
}
|
|
647
|
-
});
|
|
648
566
|
Object.defineProperty(exports, "formatBar", {
|
|
649
567
|
enumerable: true,
|
|
650
568
|
get: function() {
|
|
@@ -687,12 +605,6 @@ Object.defineProperty(exports, "readOutputFiles", {
|
|
|
687
605
|
return readOutputFiles;
|
|
688
606
|
}
|
|
689
607
|
});
|
|
690
|
-
Object.defineProperty(exports, "startUrlWatcher", {
|
|
691
|
-
enumerable: true,
|
|
692
|
-
get: function() {
|
|
693
|
-
return startUrlWatcher;
|
|
694
|
-
}
|
|
695
|
-
});
|
|
696
608
|
Object.defineProperty(exports, "startWatcher", {
|
|
697
609
|
enumerable: true,
|
|
698
610
|
get: function() {
|
|
@@ -724,4 +636,4 @@ Object.defineProperty(exports, "write", {
|
|
|
724
636
|
}
|
|
725
637
|
});
|
|
726
638
|
|
|
727
|
-
//# sourceMappingURL=utils-
|
|
639
|
+
//# sourceMappingURL=utils-Dyd-rk1U.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"utils-Dyd-rk1U.cjs","names":["runtime","access","readFile","resolve","writeFile","mkdir","dirname","relative","isAbsolute","styleText","formatMs","writer","styleText","relative","process","readdir","join"],"sources":["../../../internals/utils/src/fs.ts","../../../internals/utils/src/promise.ts","../src/loggers/banner.ts","../src/ui/spinner.ts","../src/runners/generate/utils.ts"],"sourcesContent":["import { access, glob as globNode, mkdir, readFile, writeFile } from 'node:fs/promises'\n\nimport { dirname, isAbsolute, join, relative, resolve } from 'node:path'\nimport { runtime } from './runtime.ts'\n\nexport { existsSync } from 'node:fs'\nexport { mkdir, mkdtemp, rm } from 'node:fs/promises'\n\n/**\n * Resolves to `true` when the file or directory at `path` exists.\n * Uses `Bun.file().exists()` when running under Bun, `fs.access` otherwise.\n *\n * @example\n * ```ts\n * if (await exists('./kubb.config.ts')) {\n * const content = await read('./kubb.config.ts')\n * }\n * ```\n */\nexport async function exists(path: string): Promise<boolean> {\n if (runtime.isBun) {\n return Bun.file(path).exists()\n }\n return access(path).then(\n () => true,\n () => false,\n )\n}\n\n/**\n * Reads the file at `path` as a UTF-8 string.\n * Uses `Bun.file().text()` when running under Bun, `fs.readFile` otherwise.\n *\n * @example\n * ```ts\n * const source = await read('./src/Pet.ts')\n * ```\n */\nexport async function read(path: string): Promise<string> {\n if (runtime.isBun) {\n return Bun.file(path).text()\n }\n return readFile(path, { encoding: 'utf8' })\n}\n\ntype WriteOptions = {\n /**\n * Previously read content, or `null` when the file does not exist.\n * Omitting this value reads the file before writing.\n */\n stored?: string | null\n /**\n * When `true`, re-reads the file immediately after writing and throws if the\n * content does not match — useful for catching write failures on unreliable file systems.\n */\n sanity?: boolean\n}\n\n/**\n * Whether `stored` already holds `source`, comparing on the trimmed text rather than the exact\n * bytes. Surrounding whitespace is what a formatter adds and what editors strip, and neither is a\n * reason to rewrite the file.\n *\n * Both sides are trimmed, so a storage that keeps bytes verbatim settles on the same answer as one\n * that normalizes what it stores. Trimming only `stored` would leave a source with leading\n * whitespace rewritten on every build, since the stored copy keeps the whitespace the comparison\n * has already dropped.\n */\nexport function matchesStored({ stored, source }: { stored: string; source: string }): boolean {\n return stored.trim() === source.trim()\n}\n\n/**\n * Writes `data` to `path`, trimming surrounding whitespace and ending the file with a single newline\n * the way prettier, biome, and oxfmt all do.\n * Skips the write when the trimmed content is empty, or when the file already holds that content.\n * Creates any missing parent directories automatically.\n * When `sanity` is `true`, re-reads the file after writing and throws if the content does not match.\n *\n * @example\n * ```ts\n * await write('./src/Pet.ts', source) // writes and returns the trimmed content plus a newline\n * await write('./src/Pet.ts', source) // null — file unchanged\n * await write('./src/Pet.ts', ' ') // null — empty content skipped\n * ```\n */\nexport async function write(path: string, data: string, options: WriteOptions = {}): Promise<string | null> {\n const trimmed = data.trim()\n if (trimmed === '') return null\n\n const content = `${trimmed}\\n`\n const resolved = resolve(path)\n let stored = options.stored\n\n if (stored === undefined) {\n if (runtime.isBun) {\n const file = Bun.file(resolved)\n stored = (await file.exists()) ? await file.text() : null\n } else {\n try {\n stored = await readFile(resolved, { encoding: 'utf-8' })\n } catch {\n /* file doesn't exist yet */\n stored = null\n }\n }\n }\n if (matchesStored({ stored: stored ?? '', source: trimmed })) return null\n\n await writeRaw(resolved, content)\n\n if (options.sanity) {\n const savedData = await read(resolved)\n if (savedData !== content) {\n throw new Error(`Sanity check failed for ${path}\\n\\nData[${data.length}]:\\n${data}\\n\\nSaved[${savedData.length}]:\\n${savedData}\\n`)\n }\n return savedData\n }\n\n return content\n}\n\n/**\n * Writes UTF-8 content verbatim, including empty files and surrounding whitespace.\n * Uses Bun.write under Bun and creates missing parent directories under either runtime.\n *\n * @example\n * await writeRaw('./cache/output.ts', ' // keep these bytes\\n\\n')\n */\nexport async function writeRaw(path: string, content: string): Promise<void> {\n const resolved = resolve(path)\n if (runtime.isBun) {\n await Bun.write(resolved, content)\n return\n }\n try {\n await writeFile(resolved, content, { encoding: 'utf-8' })\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error\n await mkdir(dirname(resolved), { recursive: true })\n await writeFile(resolved, content, { encoding: 'utf-8' })\n }\n}\n\n/**\n * Lists non-hidden regular files below `directory` as relative POSIX paths, excluding directories and symlinks.\n * Uses Bun.Glob under Bun because its Node glob compatibility API lacks directory-entry support.\n *\n * @example\n * for await (const path of listFiles('./src')) console.log(path)\n */\nexport async function* listFiles(directory: string): AsyncGenerator<string> {\n const cwd = resolve(directory)\n if (runtime.isBun) {\n yield* new Bun.Glob('**/*').scan({ cwd, dot: false, onlyFiles: true, followSymlinks: false })\n return\n }\n for await (const entry of globNode('**/*', { cwd, withFileTypes: true })) {\n if (entry.isFile()) yield toPosixPath(relative(cwd, join(entry.parentPath, entry.name)))\n }\n}\n\n/**\n * Converts a filesystem path to use POSIX (`/`) separators.\n *\n * Most of the codebase compares and composes paths as strings (prefix matching, joining for\n * import specifiers, splitting on `/`). On POSIX `path.resolve` already returns `/`-separated\n * paths, but on Windows it returns `\\`-separated paths, which breaks every such comparison.\n *\n * Routing every path that crosses a module boundary through `toPosixPath` keeps the rest of the\n * code platform-agnostic. The conversion runs unconditionally so Windows-specific behavior is\n * exercisable from POSIX CI.\n *\n * @example\n * toPosixPath('C:\\\\repo\\\\src\\\\pet.ts') // 'C:/repo/src/pet.ts'\n */\nexport function toPosixPath(filePath: string): string {\n return filePath.replaceAll('\\\\', '/')\n}\n\n/**\n * Strips the file extension from a path or file name.\n * Only removes the last `.ext` segment when the dot is not part of a directory name.\n *\n * @example\n * trimExtName('petStore.ts') // 'petStore'\n * trimExtName('/src/models/pet.ts') // '/src/models/pet'\n * trimExtName('/project.v2/gen/pet.ts') // '/project.v2/gen/pet'\n * trimExtName('noExtension') // 'noExtension'\n */\nexport function trimExtName(text: string): string {\n const dotIndex = text.lastIndexOf('.')\n if (dotIndex > 0 && !text.includes('/', dotIndex)) {\n return text.slice(0, dotIndex)\n }\n return text\n}\n\n/**\n * Resolves to `true` when `path` is `parent` itself or nested inside it. Both sides are resolved\n * to absolute paths first, so relative and `..`-containing inputs compare correctly.\n *\n * Guards a destructive or an out-of-tree operation: before wiping an output directory, check that\n * it does not contain the project root, and before loading a path a caller supplied, check that it\n * did not escape the directory it is allowed to read from.\n *\n * @example\n * isPathInside('./src/gen', '.') // true — nested inside the root\n * isPathInside('.', '.') // true — the same directory counts as inside\n * isPathInside('.', './src/gen') // false — the root is not inside its own output\n * isPathInside('../other', '.') // false — escapes the root\n */\nexport function isPathInside(path: string, parent: string): boolean {\n const resolvedPath = resolve(path)\n const resolvedParent = resolve(parent)\n if (resolvedPath === resolvedParent) {\n return true\n }\n\n const rel = relative(resolvedParent, resolvedPath)\n\n return rel !== '' && !rel.startsWith('..') && !isAbsolute(rel)\n}\n","/** A value that may already be resolved or still pending.\n *\n * @example\n * ```ts\n * function load(id: string): PossiblePromise<string> {\n * return cache.get(id) ?? fetchRemote(id)\n * }\n * ```\n */\nexport type PossiblePromise<T> = Promise<T> | T\n\ntype Store<TKey, TValue> = {\n has(key: TKey): boolean\n get(key: TKey): TValue | undefined\n set(key: TKey, value: TValue): unknown\n}\n\n/**\n * Wraps `factory` with a keyed cache backed by the provided store.\n *\n * Pass a `WeakMap` for object keys (results are GC-eligible when the key is\n * collected) or a `Map` for primitive keys. For multi-argument functions,\n * nest two `memoize` calls — the outer keyed by the first argument, the\n * inner (created once per outer miss) keyed by the second.\n *\n * Because the cache is owned by the caller, it can be shared, inspected, or\n * cleared independently of the memoized function.\n *\n * @example Single WeakMap key\n * ```ts\n * const cache = new WeakMap<SchemaNode, Set<string>>()\n * const getRefs = memoize(cache, (node) => collectRefs(node))\n * ```\n *\n * @example Single Map key (primitive)\n * ```ts\n * const cache = new Map<string, Resolver>()\n * const getResolver = memoize(cache, (name) => buildResolver(name))\n * ```\n *\n * @example Two-level (object + primitive)\n * ```ts\n * const outer = new WeakMap<Params[], Map<string, Params[]>>()\n * const fn = memoize(outer, (params) => memoize(new Map(), (key) => transform(params, key)))\n * fn(params)('camelcase')\n * ```\n */\nexport function memoize<TKey, TValue>(store: Store<TKey, TValue>, factory: (key: TKey) => TValue): (key: TKey) => TValue {\n return (key: TKey): TValue => {\n if (store.has(key)) return store.get(key)!\n const value = factory(key)\n store.set(key, value)\n return value\n }\n}\n\ntype ParallelOptions<TItem> = {\n /**\n * Items to work through, handed out in order.\n */\n items: ReadonlyArray<TItem>\n /**\n * How many items may be in flight at once.\n */\n limit: number\n /**\n * Runs once per item, with the item's position so a caller can report progress.\n */\n run(item: TItem, index: number): Promise<void>\n}\n\n/**\n * Runs `run` over every item with at most `limit` in flight. Workers share one iterator, so each\n * takes the next item the moment it frees up instead of waiting for a batch to drain.\n *\n * @example\n * ```ts\n * await inParallel({ items: files, limit: 50, run: (file) => storage.writeItem(file.path, file.source) })\n * ```\n */\nexport async function inParallel<TItem>({ items, limit, run }: ParallelOptions<TItem>): Promise<void> {\n const queue = items.entries()\n\n const worker = async (): Promise<void> => {\n for (const [index, item] of queue) await run(item, index)\n }\n\n await Promise.all(Array.from({ length: Math.min(limit, items.length) }, () => worker()))\n}\n","import { styleText } from 'node:util'\nimport { formatMs } from '@internals/utils'\n\n/**\n * xterm-256 color for each pixel letter of the mascot. Fixed codes rather than named colors, so a\n * terminal theme cannot repaint it.\n */\nconst colors: Record<string, number> = {\n /** Hoodie. */\n O: 208,\n /** Shadow where the hood meets the face. */\n R: 166,\n /** Face. */\n F: 223,\n /** Eyes. */\n K: 16,\n /** Blush. */\n B: 217,\n /** Mouth. */\n M: 131,\n}\n\n/**\n * The two pixel rows of the face around the eyes, for each expression.\n */\nconst eyes = {\n open: ['FFFFFFFFFF', 'FFKFFFFKFF'],\n left: ['FFFFFFFFFF', 'FKFFFFKFFF'],\n right: ['FFFFFFFFFF', 'FFFKFFFFKF'],\n blink: ['FFFFFFFFFF', 'FKKFFFFKKF'],\n happy: ['FFKFFFFKFF', 'FKFKFFKFKF'],\n} as const\n\nexport type Expression = keyof typeof eyes\n\n/**\n * The frames the mascot plays when the CLI starts, each with how long it stays on screen. It ends on\n * open eyes, which stay.\n */\nexport const wakeUp: ReadonlyArray<readonly [Expression, number]> = [\n ['blink', 100],\n ['open', 180],\n ['left', 140],\n ['right', 140],\n ['open', 80],\n ['happy', 220],\n ['open', 0],\n]\n\n/**\n * The kid in the orange hoodie from the Kubb logo, one letter per pixel and `.` for none. Each\n * 2 × 2 block becomes one terminal cell, so a block holds at most two colors.\n */\nexport function pixels(expression: Expression): Array<string> {\n const [top, bottom] = eyes[expression]\n\n // prettier-ignore\n return [\n '....OOOOOOOOOO....',\n '..OORRRRRRRRRROO..',\n `..OO${top}OO..`,\n `OOFF${bottom}FFOO`,\n 'OOFFBBFFMMFFBBFFOO',\n '..OOOOFFFFFFOOOO..',\n ]\n}\n\n/**\n * Quadrant glyphs indexed by which quarters are filled: top left 1, top right 2, bottom left 4,\n * bottom right 8.\n */\nconst quadrants = ' ▘▝▀▖▌▞▛▗▚▐▜▄▙▟█'\n\n/**\n * Draws each 2 × 2 block of pixels as one quadrant glyph. The glyph's filled quarters take the first\n * color in the block and the rest take the other.\n */\nfunction drawHead(expression: Expression): Array<string> {\n const rows = pixels(expression)\n const lines: Array<string> = []\n\n for (let y = 0; y < rows.length; y += 2) {\n let line = ''\n for (let x = 0; x < rows[y]!.length; x += 2) {\n const block = [rows[y]![x]!, rows[y]![x + 1]!, rows[y + 1]![x]!, rows[y + 1]![x + 1]!]\n const fg = block.find((pixel) => pixel in colors)\n if (!fg) {\n line += ' '\n continue\n }\n const bg = colors[block.find((pixel) => pixel !== fg) ?? '.']\n const mask = block.reduce((bits, pixel, index) => (pixel === fg ? bits | (1 << index) : bits), 0)\n line += `\\x1b[38;5;${colors[fg]}${bg === undefined ? '' : `;48;5;${bg}`}m${quadrants[mask]}\\x1b[0m`\n }\n lines.push(line)\n }\n\n return lines\n}\n\n/**\n * Generates the Kubb mascot welcome banner as an ANSI-colored string: the head with the version,\n * title, and description beside it.\n *\n * @example\n * ```ts\n * console.log(getIntro({ title: 'kubb.config.ts', description: 'generating…', version: '5.0.0', expression: 'open' }))\n * ```\n */\nexport function getIntro({\n title,\n description,\n version,\n expression,\n}: {\n /**\n * Name of the active configuration or tool being started.\n */\n title: string\n /**\n * Short subtitle shown next to the arrow prompt.\n */\n description: string\n /**\n * Kubb version string rendered in the header.\n */\n version: string\n /**\n * Which face the mascot makes.\n */\n expression: Expression\n}): string {\n // The hoodie's fixed code, so the title is Kubb orange whatever the terminal theme does to `yellow`.\n const brand = (value: string, bold = false) => `\\x1b[${bold ? '1;' : ''}38;5;${colors.O}m${value}\\x1b[0m`\n const text = [brand(`KUBB v${version}`, true), styleText('gray', title), `${brand('➜')} ${styleText('white', description)}`]\n\n return drawHead(expression)\n .map((line, index) => ` ${line} ${text[index]}`)\n .join('\\n')\n}\n\n/**\n * Formats a millisecond duration with a threshold-based ANSI color.\n * `≤ 500 ms` → green · `≤ 1 000 ms` → yellow · `> 1 000 ms` → red.\n *\n * @example\n * ```ts\n * formatMsWithColor(200) // '\\x1b[32m200ms\\x1b[39m'\n * formatMsWithColor(800) // '\\x1b[33m800ms\\x1b[39m'\n * formatMsWithColor(1500) // '\\x1b[31m1.50s\\x1b[39m'\n * ```\n */\nexport function formatMsWithColor(ms: number): string {\n const formatted = formatMs(ms)\n if (ms <= 500) return styleText('green', formatted)\n if (ms <= 1000) return styleText('yellow', formatted)\n\n return styleText('red', formatted)\n}\n\n/**\n * A `size`-cell progress bar: `done` of `total` as filled cells, the rest light. Any progress shows\n * at least one cell, and only a finished bar fills the last one.\n */\nexport function formatBar(done: number, total: number, size = 20): string {\n const filled = !done ? 0 : done >= total ? size : Math.min(size - 1, Math.max(1, Math.round((done / total) * size)))\n return styleText('magenta', '█'.repeat(filled)) + styleText('dim', '░'.repeat(size - filled))\n}\n","import type { WriterSpinner } from '../loggers/types.ts'\nimport { writer } from './log.ts'\n\n/**\n * A progress spinner, or a writer that prints each message it is given when the terminal cannot\n * animate one. Callers drive both the same way, including the failure state.\n */\nexport function createSpinner(): WriterSpinner {\n return writer().spinner()\n}\n\n/** How long a wait may run before a spinner shows, so a fast answer draws nothing. */\nconst SPINNER_DELAY_MS = 150\n\n/**\n * Awaits `promise`, showing a spinner with `message` only when it takes longer than 150 ms.\n */\nexport async function withSpinner<T>({ promise, message }: { promise: Promise<T>; message: string }): Promise<T> {\n let spinner: WriterSpinner | undefined\n const timer = setTimeout(() => {\n spinner = createSpinner()\n spinner.start(message)\n }, SPINNER_DELAY_MS)\n try {\n return await promise\n } finally {\n clearTimeout(timer)\n spinner?.clear()\n }\n}\n","import { readdir } from 'node:fs/promises'\nimport { join, relative } from 'node:path'\nimport process from 'node:process'\nimport { styleText } from 'node:util'\nimport { inParallel, matchesStored, read } from '@internals/utils'\nimport type { Hookable, KubbHooks, OutputManifest, Storage } from '@kubb/core'\n\n/** Glob pattern for paths the file watcher ignores. */\nconst WATCHER_IGNORED_PATHS = '**/{.git,node_modules}/**' as const\n\n/**\n * Quiet window in milliseconds that collapses a burst of watcher events (an editor save emits several) into one rebuild.\n * It outlasts chokidar's 100 ms atomic-save window, which holds back the event of a write-then-rename save.\n */\nconst WATCHER_DEBOUNCE_MS = 250\n\n/** `14:02:11 petStore.yaml changed`, the line a watcher prints when its input changes. */\nexport function formatChange({ target, removed = false, now = new Date() }: { target: string; removed?: boolean; now?: Date }): string {\n return `${styleText('dim', now.toTimeString().slice(0, 8))} ${styleText('bold', target)} ${removed ? 'removed' : 'changed'}`\n}\n\ntype WatcherLog = {\n info: (message: string) => void\n error: (message: string) => void\n}\n\n/**\n * Starts a file watcher on the given paths and calls `cb` on any change.\n * Ignores `.git` and `node_modules` directories. Event bursts (an editor save emits several)\n * are debounced into one call. `cb` must never reject: its result is not awaited, so the caller\n * serializes and reports its own builds. Resolves to a function that stops watching.\n */\nexport async function startWatcher(\n path: Array<string>,\n cb: (path: Array<string>) => Promise<void>,\n log: WatcherLog = { info: console.log, error: console.log },\n): Promise<() => Promise<void>> {\n const { watch } = await import('chokidar')\n // `ignoreInitial` skips the `add` events chokidar fires for existing files at startup, which\n // would otherwise rebuild right after the initial run.\n const watcher = watch(path, { ignorePermissionErrors: true, ignored: WATCHER_IGNORED_PATHS, ignoreInitial: true })\n\n for (const signal of ['SIGINT', 'SIGTERM'] as const) {\n process.once(signal, () => void watcher.close())\n }\n\n let debounceTimer: ReturnType<typeof setTimeout> | null = null\n\n watcher.on('all', (type, file) => {\n log.info(formatChange({ target: relative(process.cwd(), file), removed: type === 'unlink' }))\n if (debounceTimer) clearTimeout(debounceTimer)\n debounceTimer = setTimeout(() => {\n debounceTimer = null\n void cb(path)\n }, WATCHER_DEBOUNCE_MS)\n })\n\n return async () => {\n if (debounceTimer) clearTimeout(debounceTimer)\n await watcher.close()\n }\n}\n\n/**\n * What one build produced: the schema and operation names the plugins generated.\n */\nexport type BuildSnapshot = {\n schemas: Set<string>\n operations: Set<string>\n}\n\nfunction createSnapshot(): BuildSnapshot {\n return { schemas: new Set(), operations: new Set() }\n}\n\n/**\n * Collects a {@link BuildSnapshot} from the hooks while a build runs. `take` hands back the finished\n * build's snapshot and starts the next one.\n */\nexport function trackBuild(hooks: Hookable<KubbHooks>): { take(): BuildSnapshot } {\n let current = createSnapshot()\n\n hooks.hook('kubb:generate:schema', (node) => {\n if (node.name) current.schemas.add(node.name)\n })\n hooks.hook('kubb:generate:operation', (node) => {\n current.operations.add(node.operationId)\n })\n\n return {\n take() {\n const snapshot = current\n current = createSnapshot()\n return snapshot\n },\n }\n}\n\ntype NameChange = { added: number; removed: number }\n\n/**\n * How a rebuild differs from the build before it: the spec's added and removed schemas and operations.\n */\nexport type BuildDiff = {\n schemas: NameChange\n operations: NameChange\n}\n\nfunction diffNames(previous: Set<string>, next: Set<string>): NameChange {\n return { added: [...next].filter((name) => !previous.has(name)).length, removed: [...previous].filter((name) => !next.has(name)).length }\n}\n\n/**\n * Compares two {@link BuildSnapshot}s by name.\n */\nexport function diffBuilds(previous: BuildSnapshot, next: BuildSnapshot): BuildDiff {\n return {\n schemas: diffNames(previous.schemas, next.schemas),\n operations: diffNames(previous.operations, next.operations),\n }\n}\n\n/**\n * Compares file contents or fingerprints by path.\n */\nexport function diffFiles(previous: ReadonlyMap<string, string>, next: ReadonlyMap<string, string>): { files: Array<FileChange>; unchanged: number } {\n const files: Array<FileChange> = []\n let unchanged = 0\n for (const [path, fingerprint] of next) {\n const before = previous.get(path)\n if (before === fingerprint) unchanged++\n else files.push({ status: before === undefined ? 'A' : 'M', path })\n }\n for (const path of previous.keys()) {\n if (!next.has(path)) files.push({ status: 'D', path })\n }\n\n return { files, unchanged }\n}\n\n/** A changed file with how many lines it gains and loses, counted as a multiset, which is cheap and close enough for a plan. */\nexport type FileChange = { status: 'A' | 'M' | 'D'; path: string; added?: number; removed?: number }\n\nfunction countLineChanges(before: string, after: string): { added: number; removed: number } {\n const remaining = new Map<string, number>()\n for (const line of before ? before.split('\\n') : []) remaining.set(line, (remaining.get(line) ?? 0) + 1)\n let added = 0\n for (const line of after ? after.split('\\n') : []) {\n const count = remaining.get(line) ?? 0\n if (count > 0) remaining.set(line, count - 1)\n else added++\n }\n const removed = [...remaining.values()].reduce((sum, count) => sum + count, 0)\n return { added, removed }\n}\n\n/**\n * Reads the output before generation, so cleaning the directory cannot erase the diff baseline.\n * A missing directory or an unreadable file is skipped.\n */\nexport async function readOutputFiles(outputPath: string): Promise<Map<string, string>> {\n const entries = await readdir(outputPath, { recursive: true, withFileTypes: true }).catch(() => [])\n const files = new Map<string, string>()\n await inParallel({\n items: entries.filter((entry) => entry.isFile()).map((entry) => join(entry.parentPath, entry.name)),\n limit: 50,\n run: async (filePath) => {\n const source = await read(filePath).catch(() => null)\n if (source !== null) files.set(filePath, source)\n },\n })\n return files\n}\n\n/**\n * Compares generated output with the files captured before generation. The manifest recognizes\n * output rewritten by a formatter, and `clean` includes files the run would delete.\n */\nexport async function diffOutput({\n storage,\n paths,\n clean,\n manifest,\n previousFiles,\n}: {\n storage: Storage\n paths: ReadonlyArray<string>\n clean: boolean\n manifest?: Pick<OutputManifest, 'isUpToDate'>\n /**\n * The output captured before a real run, including files removed by cleaning.\n */\n previousFiles: ReadonlyMap<string, string>\n}): Promise<{ files: Array<FileChange>; unchanged: number }> {\n const generated = new Set(paths)\n const changes: Array<FileChange | undefined> = []\n let unchanged = 0\n await inParallel({\n items: paths,\n limit: 50,\n run: async (filePath, index) => {\n const next = await storage.readItem(filePath)\n if (next === null) return\n const previous = previousFiles.get(filePath) ?? null\n if (previous !== null && (matchesStored({ stored: previous, source: next }) || manifest?.isUpToDate({ key: filePath, source: next, disk: previous }))) {\n unchanged++\n return\n }\n changes[index] = {\n status: previous === null ? 'A' : 'M',\n path: filePath,\n ...countLineChanges(previous?.trim() ?? '', previous === null ? next.trimEnd() : next.trim()),\n }\n },\n })\n const files = changes.filter((file) => file !== undefined)\n if (clean) {\n for (const [filePath, source] of previousFiles) {\n if (!generated.has(filePath)) files.push({ status: 'D', path: filePath, ...countLineChanges(source.trimEnd(), '') })\n }\n }\n\n return { files, unchanged }\n}\n\ntype KeyInput = Pick<NodeJS.ReadStream, 'isTTY' | 'setRawMode' | 'resume' | 'pause' | 'setEncoding' | 'on'>\n\ntype KeyOptions = {\n rebuild: () => void\n /**\n * Ends the process with this exit code: `0` for `q`, `130` for ctrl+c, which raw mode turns into a key.\n */\n quit: (code: number) => void\n input?: KeyInput\n}\n\n/**\n * Reads `r` (rebuild) and `q` (quit) from an interactive stdin in raw mode, and keeps ctrl+c\n * working. Returns `undefined` when stdin is not a TTY. Otherwise returns `arm`, which turns raw\n * mode back on: a spinner restores the terminal when it stops, so call it after each build. Raw mode\n * is restored on exit.\n */\nexport function listenForKeys({ rebuild, quit, input = process.stdin }: KeyOptions): (() => void) | undefined {\n if (!input.isTTY) return undefined\n\n const arm = () => {\n input.setRawMode(true)\n input.resume()\n }\n input.setEncoding('utf8')\n input.on('data', (data: string) => {\n const key = data.trim()\n if (key === 'r') {\n rebuild()\n return\n }\n if (key === 'q' || data === '\\u0003') {\n input.setRawMode(false)\n input.pause()\n quit(key === 'q' ? 0 : 130)\n }\n })\n process.once('exit', () => input.setRawMode(false))\n arm()\n\n return arm\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;AAmBA,eAAsB,OAAO,MAAgC;CAC3D,IAAIA,kBAAAA,QAAQ,OACV,OAAO,IAAI,KAAK,IAAI,CAAC,CAAC,OAAO;CAE/B,QAAA,GAAOC,iBAAAA,OAAAA,CAAO,IAAI,CAAC,CAAC,WACZ,YACA,KACR;AACF;;;;;;;;;;AAWA,eAAsB,KAAK,MAA+B;CACxD,IAAID,kBAAAA,QAAQ,OACV,OAAO,IAAI,KAAK,IAAI,CAAC,CAAC,KAAK;CAE7B,QAAA,GAAOE,iBAAAA,SAAAA,CAAS,MAAM,EAAE,UAAU,OAAO,CAAC;AAC5C;;;;;;;;;;;AAyBA,SAAgB,cAAc,EAAE,QAAQ,UAAuD;CAC7F,OAAO,OAAO,KAAK,MAAM,OAAO,KAAK;AACvC;;;;;;;;;;;;;;;AAgBA,eAAsB,MAAM,MAAc,MAAc,UAAwB,CAAC,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AS;IACf,QAAQ,aAAa,OAAO,MAAM;IAClC,MAAM;IACN,GAAG,iBAAiB,UAAU,KAAK,KAAK,IAAI,aAAa,OAAO,KAAK,QAAQ,IAAI,KAAK,KAAK,CAAC;GAC9F;EACF;CACF,CAAC;CACD,MAAM,QAAQ,QAAQ,QAAQ,SAAS,SAAS,KAAA,CAAS;CACzD,IAAI,OACG;OAAA,MAAM,CAAC,UAAU,WAAW,eAC/B,IAAI,CAAC,UAAU,IAAI,QAAQ,GAAG,MAAM,KAAK;GAAE,QAAQ;GAAK,MAAM;GAAU,GAAG,iBAAiB,OAAO,QAAQ,GAAG,EAAE;EAAE,CAAC;CAAA;CAIvH,OAAO;EAAE;EAAO;CAAU;AAC5B;;;;;;;AAmBA,SAAgB,cAAc,EAAE,SAAS,MAAM,QAAQF,aAAAA,QAAQ,SAA+C;CAC5G,IAAI,CAAC,MAAM,OAAO,OAAO,KAAA;CAEzB,MAAM,YAAY;EAChB,MAAM,WAAW,IAAI;EACrB,MAAM,OAAO;CACf;CACA,MAAM,YAAY,MAAM;CACxB,MAAM,GAAG,SAAS,SAAiB;EACjC,MAAM,MAAM,KAAK,KAAK;EACtB,IAAI,QAAQ,KAAK;GACf,QAAQ;GACR;EACF;EACA,IAAI,QAAQ,OAAO,SAAS,KAAU;GACpC,MAAM,WAAW,KAAK;GACtB,MAAM,MAAM;GACZ,KAAK,QAAQ,MAAM,IAAI,GAAG;EAC5B;CACF,CAAC;CACD,aAAA,QAAQ,KAAK,cAAc,MAAM,WAAW,KAAK,CAAC;CAClD,IAAI;CAEJ,OAAO;AACT"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@kubb/cli",
|
|
3
|
-
"version": "5.
|
|
3
|
+
"version": "5.12.0",
|
|
4
4
|
"description": "Official CLI for Kubb. Run kubb generate, kubb init, kubb validate, kubb studio, and kubb mcp to manage the full code generation lifecycle.",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"cli",
|
|
@@ -68,7 +68,7 @@
|
|
|
68
68
|
"dependencies": {
|
|
69
69
|
"@clack/prompts": "^1.8.1",
|
|
70
70
|
"@gunshi/plugin-dryrun": "^0.37.3",
|
|
71
|
-
"@kubb/core": "5.
|
|
71
|
+
"@kubb/core": "5.12.0",
|
|
72
72
|
"chokidar": "^5.0.0",
|
|
73
73
|
"gunshi": "^0.37.3",
|
|
74
74
|
"jiti": "^2.7.0",
|
|
@@ -78,13 +78,13 @@
|
|
|
78
78
|
"devDependencies": {
|
|
79
79
|
"@internals/shared": "0.0.1",
|
|
80
80
|
"@internals/utils": "0.0.1",
|
|
81
|
-
"@kubb/adapter-oas": "5.
|
|
82
|
-
"@kubb/studio": "5.
|
|
81
|
+
"@kubb/adapter-oas": "5.12.0",
|
|
82
|
+
"@kubb/studio": "5.12.0"
|
|
83
83
|
},
|
|
84
84
|
"peerDependencies": {
|
|
85
|
-
"@kubb/adapter-oas": "5.
|
|
86
|
-
"@kubb/mcp": "5.
|
|
87
|
-
"@kubb/studio": "5.
|
|
85
|
+
"@kubb/adapter-oas": "5.12.0",
|
|
86
|
+
"@kubb/mcp": "5.12.0",
|
|
87
|
+
"@kubb/studio": "5.12.0"
|
|
88
88
|
},
|
|
89
89
|
"peerDependenciesMeta": {
|
|
90
90
|
"@kubb/adapter-oas": {
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"run-CYHpe0V_.cjs","names":["trackRun","process","memoryStorage","createKubb","isOutdated","version","Diagnostics","styleText","pluralize","formatMs","logLevelMap","Hookable","cliReporter","createPlainWriter","logBanner","getConfigs","createSpinner","path","jsonReporter","fileReporter","htmlReporter","selectReporters","trackBuild","getInputKind","diffBuilds","getElapsedMs","listenForKeys","fetchUrlBody","logInfo","logError","startWatcher"],"sources":["../src/runners/generate/run.ts"],"sourcesContent":["import path from 'node:path'\nimport process from 'node:process'\nimport { styleText } from 'node:util'\nimport { formatMs, formatters, getElapsedMs, linters } from '@internals/utils'\nimport {\n Hookable,\n type CLIOptions,\n cliReporter,\n type Config,\n createKubb,\n Diagnostics,\n fileReporter,\n getInputKind,\n htmlReporter,\n jsonReporter,\n type KubbHooks,\n logLevel as logLevelMap,\n memoryStorage,\n type ReporterName,\n} from '@kubb/core'\nimport { version } from '../../../package.json'\nimport { trackRun } from '../../Telemetry.ts'\nimport { pluralize } from '../../ui/text.ts'\nimport setupReporters, { selectReporters } from '../../loggers/reporters.ts'\nimport { createPlainWriter } from '../../loggers/plainWriter.ts'\nimport { logIntro, logOutro, logSpacer, logTip } from '../../ui/intro.ts'\nimport { logError, logInfo, logStep } from '../../ui/log.ts'\nimport { logBanner } from '../../ui/mascot.ts'\nimport { createSpinner } from '../../ui/spinner.ts'\nimport { getConfigs } from '../../config.ts'\nimport { isOutdated } from '../../utils/registry.ts'\nimport { type BuildDiff, type BuildSnapshot, diffBuilds, fetchUrlBody, listenForKeys, startUrlWatcher, startWatcher, trackBuild } from './utils.ts'\n\n/** NPM registry endpoint used to check for @kubb/cli updates. */\nconst KUBB_NPM_PACKAGE_URL = 'https://registry.npmjs.org/@kubb/cli/latest' as const\n\n/** Upper bound in milliseconds for the npm update check, so a slow registry never stalls a run. */\nconst UPDATE_CHECK_TIMEOUT_MS = 3_000\n\n/** The formatter names from `Config['output'].format`, without `'auto'` (detection, not a tool) and `false` (skip). */\ntype FormatterName = Exclude<NonNullable<Config['output']['format']>, 'auto' | false>\ntype LinterName = Exclude<NonNullable<Config['output']['lint']>, 'auto' | false>\n\n// Pinned here, not in `@internals/utils` (which must not import `@kubb/core`): a tool added to the union without a descriptor fails to compile.\nformatters satisfies Record<FormatterName, unknown>\nlinters satisfies Record<LinterName, unknown>\n\ntype GenerateProps = {\n input?: string\n config: Config\n hooks: Hookable<KubbHooks>\n /**\n * When `true`, generates in memory instead of writing to disk, skips formatting, linting, and\n * post-generate commands, and prints what would change on disk.\n */\n dryRun?: boolean\n}\n\nexport async function generate(options: GenerateProps): Promise<boolean> {\n const { input, hooks, dryRun = false } = options\n\n const report = trackRun({ command: 'generate', hrStart: process.hrtime() })\n\n const config: Config = {\n ...options.config,\n input: input ?? options.config.input,\n // Dry-run never touches disk, regardless of the config's own storage driver.\n storage: dryRun ? memoryStorage() : options.config.storage,\n // Also keeps core's `hasOutputPasses` false, so dry-run skips the output manifest write too.\n output: dryRun ? { ...options.config.output, format: false, lint: false, postGenerate: [] } : options.config.output,\n }\n\n // Core formats, lints and runs `output.postGenerate` after an error-free build, and reports\n // their failures as coded diagnostics that reach the summary, the json report and the exit code.\n const kubb = createKubb(config, { hooks })\n const result = await kubb.generate()\n\n await report({\n // A setup that threw leaves no driver, so read the configured plugins instead.\n plugins: kubb.config.plugins.flatMap((p) =>\n p && typeof p === 'object' ? [{ name: p.meta?.name ?? p.name ?? '', options: (p.options ?? {}) as Record<string, unknown> }] : [],\n ),\n filesCreated: result.files.length,\n status: result.success ? 'success' : 'failed',\n })\n\n return result.success\n}\n\ntype GenerateCommandOptions = {\n input?: string\n configPath?: string\n logLevel: string\n watch: boolean\n reporters?: Array<ReporterName>\n dryRun?: boolean\n}\n\n/** The latest published version, `undefined` when the registry does not answer in time. Never rejects. */\nasync function fetchLatestVersion(): Promise<string | undefined> {\n try {\n const res = await fetch(KUBB_NPM_PACKAGE_URL, { signal: AbortSignal.timeout(UPDATE_CHECK_TIMEOUT_MS) })\n const data = (await res.json()) as { version: string }\n return data.version\n } catch {\n // Ignore network errors\n return undefined\n }\n}\n\nasync function checkForUpdate({ hooks, latest }: { hooks: Hookable<KubbHooks>; latest: Promise<string | undefined> }): Promise<void> {\n const latestVersion = await latest\n if (latestVersion && isOutdated({ installed: version, latest: latestVersion })) {\n await Diagnostics.emit(hooks, Diagnostics.update({ currentVersion: version, latestVersion }))\n }\n}\n\n/** Prints `Rebuilt in 1.2s · +1 schema -2 operations`, without the names part when the spec kept the same names. */\nfunction logRebuild({ diff: { schemas, operations }, durationMs }: { diff: BuildDiff; durationMs: number }): void {\n const specChange = [\n schemas.added && styleText('green', `+${pluralize(schemas.added, 'schema')}`),\n schemas.removed && styleText('red', `-${pluralize(schemas.removed, 'schema')}`),\n operations.added && styleText('green', `+${pluralize(operations.added, 'operation')}`),\n operations.removed && styleText('red', `-${pluralize(operations.removed, 'operation')}`),\n ]\n .filter(Boolean)\n .join(' ')\n logStep([`Rebuilt in ${formatMs(durationMs)}`, specChange].filter(Boolean).join(styleText('dim', ' · ')))\n}\n\n/**\n * Runs the full Kubb generation lifecycle for the given CLI options.\n * Loads configs, sets up the reporters (CLI `--reporter` picks which of `config.reporters` to trigger),\n * checks for a newer version, and calls `generate` for each config entry.\n */\nexport async function run({ input, configPath, logLevel: logLevelKey, watch, reporters: cliReporters, dryRun }: GenerateCommandOptions): Promise<void> {\n // Started first so the registry request overlaps the banner and the config load.\n const latest = fetchLatestVersion()\n const logLevel = logLevelMap[logLevelKey as keyof typeof logLevelMap] ?? logLevelMap.info\n const hooks = new Hookable<KubbHooks>()\n\n // CLI `--reporter` selects which reporters to trigger by name, defaulting to `cli`. `defineConfig`\n // registers the built-in reporters on the config; a config exported without it falls back to them below.\n const requestedNames: Array<ReporterName> = cliReporters?.length ? cliReporters : ['cli']\n\n // The `json` reporter owns stdout, so the command writes nothing of its own around it.\n const json = requestedNames.includes('json')\n const quiet = logLevel <= logLevelMap.silent || json\n\n // Errors raised outside a build have no report entry. In `json` mode they go to a stderr logger,\n // so they are never silent and stdout stays one JSON document.\n const errorHooks = json ? new Hookable<KubbHooks>() : hooks\n if (json) setupReporters(errorHooks, { logLevel, reporters: [cliReporter], writer: createPlainWriter(console.error) })\n\n // The config loads while the banner plays; the output still prints in order once the banner is done.\n const banner = quiet ? undefined : logBanner(version)\n const loading = getConfigs({\n configPath,\n input,\n watch,\n logLevel: logLevelKey as CLIOptions['logLevel'],\n })\n // Handled below; this keeps a rejection during the banner from counting as unhandled.\n loading.catch(() => undefined)\n await banner\n\n if (!quiet) {\n logIntro({ title: 'Configuration' })\n }\n\n // Load the config first so `config.reporters` can pick the reporters. A failure here has no\n // reporter installed yet, so fall back to the default `cli` reporter to surface it.\n const configSpinner = createSpinner()\n let configs: Array<Config>\n let resolvedConfigPath: string\n try {\n if (!quiet) configSpinner.start('Loading config')\n\n const loaded = await loading\n configs = loaded.configs\n resolvedConfigPath = loaded.configPath\n\n if (!quiet) configSpinner.stop(`Loaded ${styleText('dim', path.relative(process.cwd(), resolvedConfigPath))}`)\n } catch (error) {\n if (!quiet) configSpinner.error('Config failed loading')\n\n if (!json) setupReporters(hooks, { logLevel, reporters: [cliReporter] })\n // A diagnostic thrown while the config file runs, such as invalid extension options, sits in the cause chain.\n await Diagnostics.emit(errorHooks, error)\n\n if (!quiet) logOutro(styleText('red', '✗ Configuration failed'))\n process.exit(1)\n }\n\n // Without a reporter nothing is printed, not even an error, so a config written without\n // `defineConfig` gets the same built-ins it would have registered.\n const available = configs[0]?.reporters?.length ? configs[0].reporters : [cliReporter, jsonReporter, fileReporter, htmlReporter]\n const reporters = selectReporters(available, requestedNames)\n setupReporters(hooks, { logLevel, reporters, dryRun })\n\n await hooks.callHook('kubb:lifecycle:start', { version })\n\n // Inside the bootstrap group, so an update notice reads as part of the setup rather than as part\n // of the first config's generation.\n await checkForUpdate({ hooks, latest })\n\n if (!quiet) logOutro(`${pluralize(configs.length, 'config')} ready`)\n\n try {\n let anyFailed = false\n // One tracker, one key listener and one build queue serve every watched config, so several configs never mix diffs or answer `r` twice.\n const tracker = watch ? trackBuild(hooks) : undefined\n const rebuilds: Array<() => Promise<void>> = []\n let armKeys: (() => void) | undefined\n // Configs share the hooks emitter, so every build, from any watcher or the `r` key, waits for the one before it.\n let queue = Promise.resolve()\n for (const config of configs) {\n const effectiveInput = input ?? config.input\n const inputKind = typeof effectiveInput === 'string' ? getInputKind(effectiveInput) : undefined\n const watchPath = inputKind === 'file' || inputKind === 'url' ? (effectiveInput as string) : undefined\n if (watchPath && tracker) {\n const label = styleText('yellow', `Watching ${inputKind === 'url' ? watchPath : path.relative(process.cwd(), watchPath)}`)\n let previous: BuildSnapshot | undefined\n // Don't removeAll() between builds, that would also drop logger and lifecycle\n // listeners. Plugin listeners are already disposed by safeBuild's dispose()\n // in its finally block, so re-running generate() on the same hooks emitter is safe.\n const build = async () => {\n const hrStart = process.hrtime()\n const succeeded = await generate({ input, config, hooks, dryRun })\n const snapshot = tracker.take()\n if (previous) logRebuild({ diff: diffBuilds(previous, snapshot), durationMs: getElapsedMs(hrStart) })\n previous = snapshot\n\n logStep(armKeys ? `${label} ${styleText('dim', 'r rebuild · q quit')}` : label)\n armKeys?.()\n if (succeeded) {\n logSpacer()\n logTip()\n }\n }\n // A trigger that lands while this config's build is queued joins it; one that lands during the build queues one more. Never rejects.\n let pending = false\n const rebuild = (): Promise<void> => {\n if (pending) return queue\n pending = true\n queue = queue\n .then(() => {\n pending = false\n return build()\n })\n .catch((error) => void Diagnostics.emit(errorHooks, error))\n return queue\n }\n rebuilds.push(rebuild)\n if (!quiet) {\n armKeys ??= listenForKeys({\n rebuild: () => rebuilds.forEach((trigger) => void trigger()),\n quit: (code) => void Promise.resolve(hooks.callHook('kubb:lifecycle:end')).finally(() => process.exit(code)),\n })\n }\n\n // For a URL input, capture the document before the build: it becomes the watcher's\n // change-detection baseline, so an edit landing before the first poll still rebuilds.\n // When the server is down the baseline stays undefined and the watcher rebuilds on its\n // first successful poll, so recovery with an unchanged document still generates output.\n const initialBody = inputKind === 'url' ? await fetchUrlBody(watchPath) : undefined\n\n // The watchers ignore their startup state, so run the first build here; a failing one keeps watching so the user can fix the input.\n await rebuild()\n\n if (inputKind === 'url') {\n startUrlWatcher(watchPath, rebuild, { log: { info: logInfo, error: logError }, initialBody })\n } else {\n await startWatcher([watchPath], rebuild, { info: logInfo, error: logError })\n }\n } else {\n try {\n const succeeded = await generate({ input, config, hooks, dryRun })\n if (!succeeded) anyFailed = true\n } catch (configError) {\n await Diagnostics.emit(errorHooks, configError)\n anyFailed = true\n }\n }\n }\n\n await hooks.callHook('kubb:lifecycle:end')\n\n // Watch mode prints a tip after each successful build. Regular generate commands need to\n // print one explicitly after the lifecycle group has closed so it stays outside the group.\n if (!quiet && !watch && !anyFailed) {\n logTip()\n }\n\n if (anyFailed) {\n process.exit(1)\n }\n } catch (error) {\n await Diagnostics.emit(errorHooks, error)\n process.exit(1)\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;AAkCA,MAAM,uBAAuB;;AAG7B,MAAM,0BAA0B;AAqBhC,eAAsB,SAAS,SAA0C;CACvE,MAAM,EAAE,OAAO,OAAO,SAAS,UAAU;CAEzC,MAAM,SAASA,kBAAAA,SAAS;EAAE,SAAS;EAAY,SAASC,aAAAA,QAAQ,OAAO;CAAE,CAAC;CAE1E,MAAM,SAAiB;EACrB,GAAG,QAAQ;EACX,OAAO,SAAS,QAAQ,OAAO;EAE/B,SAAS,UAAA,GAASC,WAAAA,cAAAA,CAAc,IAAI,QAAQ,OAAO;EAEnD,QAAQ,SAAS;GAAE,GAAG,QAAQ,OAAO;GAAQ,QAAQ;GAAO,MAAM;GAAO,cAAc,CAAC;EAAE,IAAI,QAAQ,OAAO;CAC/G;CAIA,MAAM,QAAA,GAAOC,WAAAA,WAAAA,CAAW,QAAQ,EAAE,MAAM,CAAC;CACzC,MAAM,SAAS,MAAM,KAAK,SAAS;CAEnC,MAAM,OAAO;EAEX,SAAS,KAAK,OAAO,QAAQ,SAAS,MACpC,KAAK,OAAO,MAAM,WAAW,CAAC;GAAE,MAAM,EAAE,MAAM,QAAQ,EAAE,QAAQ;GAAI,SAAU,EAAE,WAAW,CAAC;EAA8B,CAAC,IAAI,CAAC,CAClI;EACA,cAAc,OAAO,MAAM;EAC3B,QAAQ,OAAO,UAAU,YAAY;CACvC,CAAC;CAED,OAAO,OAAO;AAChB;;AAYA,eAAe,qBAAkD;CAC/D,IAAI;EAGF,QAAO,OADa,MADF,MAAM,sBAAsB,EAAE,QAAQ,YAAY,QAAQ,uBAAuB,EAAE,CAAC,EAAA,CAC9E,KAAK,EAAA,CACjB;CACd,QAAQ;EAEN;CACF;AAC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CAElB,SAAS,OAAO;EACd,MAAMA,WAAAA,YAAY,KAAK,YAAY,KAAK;EACxC,aAAA,QAAQ,KAAK,CAAC;CAChB;AACF"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"run-CaJbZO-f.cjs","names":["process","trackRun","findConfigFile","getConfigs","resolve","styleText","pluralize","toError"],"sources":["../src/runners/validate/run.ts"],"sourcesContent":["import process from 'node:process'\nimport { resolve } from 'node:path'\nimport { styleText } from 'node:util'\nimport { findConfigFile } from '@internals/shared'\nimport { toError } from '@internals/utils'\nimport type { Config } from '@kubb/core'\nimport { trackRun } from '../../Telemetry.ts'\nimport { getConfigs } from '../../config.ts'\nimport { pluralize } from '../../ui/text.ts'\nimport { logCommandSummary } from '../../ui/summary.ts'\n\ntype ValidateOptions = {\n /**\n * Path or URL to the specification to validate.\n */\n input: string\n configPath?: string\n}\n\n/**\n * Validates `input` with the configured adapters, falling back to OpenAPI when no config exists.\n * Exits the process with code 1 on validation failure or missing dependency.\n */\nexport async function run({ input, configPath }: ValidateOptions): Promise<void> {\n const hrStart = process.hrtime()\n const report = trackRun({ command: 'validate', hrStart })\n let adapterName: string | undefined\n\n try {\n const configFile = configPath ?? findConfigFile()\n // A config found by search that does not load must not block validating a file; an explicit `--config` still fails.\n const loaded = configFile\n ? await getConfigs({ configPath: configFile, input }).catch((error) => {\n if (configPath) throw error\n })\n : undefined\n const fallback = async () => {\n adapterName = '@kubb/adapter-oas'\n const { adapterOas } = await import('@kubb/adapter-oas')\n return [{ adapter: adapterOas(), input }]\n }\n // An array config often repeats one adapter, so each adapter and input pair is validated once.\n const unique = new Map(\n (loaded?.configs ?? []).map((config) => {\n const resolved = URL.canParse(input) ? input : resolve(config.root || process.cwd(), input)\n return [`${config.adapter?.name}\\0${resolved}`, { adapter: config.adapter, input: resolved }] as const\n }),\n )\n const targets: Array<{ adapter: Config['adapter']; input: string }> = loaded ? [...unique.values()] : await fallback()\n if (!targets.length) throw new Error('The Kubb config contains no configurations to validate.')\n for (const target of targets) {\n adapterName = target.adapter?.name\n if (!target.adapter) throw new Error('No adapter is configured. Set adapter in your Kubb config to validate this specification.')\n await target.adapter.validate(target.input, { throwOnError: true })\n }\n const specifications = new Set(targets.map((target) => target.input)).size\n const adapterNames = [...new Set(targets.flatMap((target) => target.adapter?.name ?? []))]\n await report({ status: 'success' })\n\n logCommandSummary({\n title: 'Validation passed',\n status: 'success',\n hrStart,\n lines: [\n ` ${styleText('bold', `${pluralize(specifications, 'specification')} validated`)}`,\n ` ${styleText('dim', 'Input')} ${styleText('cyan', input)}`,\n ` ${styleText('dim', adapterNames.length === 1 ? 'Adapter' : 'Adapters')} ${adapterNames.join(', ')}`,\n ],\n })\n } catch (error) {\n await report({ status: 'failed' })\n const message = toError(error).message\n const missingAdapter = adapterName === '@kubb/adapter-oas' && /(?:Cannot find|Cannot resolve|not found)[\\s\\S]*@kubb\\/adapter-oas/.test(message)\n logCommandSummary({\n title: missingAdapter ? 'Could not validate' : 'Validation failed',\n status: 'failed',\n hrStart,\n lines: [\n ` ${styleText('dim', 'Input')} ${styleText('cyan', input)}`,\n ` ${styleText('dim', 'Adapter')} ${adapterName ?? 'not configured'}${missingAdapter ? ' · not installed' : ''}`,\n '',\n styleText('bold', missingAdapter ? 'Required package' : 'Validation error'),\n ` ${styleText('red', message)}`,\n ...(missingAdapter\n ? ['', 'Install it with:', styleText('cyan', ' npm install @kubb/adapter-oas'), styleText('cyan', ' pnpm add @kubb/adapter-oas')]\n : []),\n ],\n })\n\n process.exit(1)\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;AAuBA,eAAsB,IAAI,EAAE,OAAO,cAA8C;CAC/E,MAAM,UAAUA,aAAAA,QAAQ,OAAO;CAC/B,MAAM,SAASC,kBAAAA,SAAS;EAAE,SAAS;EAAY;CAAQ,CAAC;CACxD,IAAI;CAEJ,IAAI;EACF,MAAM,aAAa,cAAcC,eAAAA,eAAe;EAEhD,MAAM,SAAS,aACX,MAAMC,eAAAA,WA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B,eAAe,EAAE,WAAW;IAChF,MAAA,GAAKD,UAAAA,UAAAA,CAAU,OAAO,OAAO,EAAE,OAAA,GAAMA,UAAAA,UAAAA,CAAU,QAAQ,KAAK;IAC5D,MAAA,GAAKA,UAAAA,UAAAA,CAAU,OAAO,aAAa,WAAW,IAAI,YAAY,UAAU,EAAE,IAAI,aAAa,KAAK,IAAI;GACtG;EACF,CAAC;CACH,SAAS,OAAO;EACd,MAAM,OAAO,EAAE,QAAQ,SAAS,CAAC;EACjC,MAAM,UAAUE,eAAAA,QAAQ,KAAK,CAAC,CAAC;EAC/B,MAAM,iBAAiB,gBAAgB,uBAAuB,oEAAoE,KAAK,OAAO;EAC9I,gBAAA,kBAAkB;GAChB,OAAO,iBAAiB,uBAAuB;GAC/C,QAAQ;GACR;GACA,OAAO;IACL,MAAA,GAAKF,UAAAA,UAAAA,CAAU,OAAO,OAAO,EAAE,OAAA,GAAMA,UAAAA,UAAAA,CAAU,QAAQ,KAAK;IAC5D,MAAA,GAAKA,UAAAA,UAAAA,CAAU,OAAO,SAAS,EAAE,IAAI,eAAe,mBAAmB,iBAAiB,qBAAqB;IAC7G;KACAA,GAAAA,UAAAA,UAAAA,CAAU,QAAQ,iBAAiB,qBAAqB,kBAAkB;IAC1E,MAAA,GAAKA,UAAAA,UAAAA,CAAU,OAAO,OAAO;IAC7B,GAAI,iBACA;KAAC;KAAI;MAAoBA,GAAAA,UAAAA,UAAAA,CAAU,QAAQ,iCAAiC;MAAGA,GAAAA,UAAAA,UAAAA,CAAU,QAAQ,8BAA8B;IAAC,IAChI,CAAC;GACP;EACF,CAAC;EAED,aAAA,QAAQ,KAAK,CAAC;CAChB;AACF"}
|
package/dist/run-Cj-HJxYW.js.map
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"run-Cj-HJxYW.js","names":[],"sources":["../src/runners/validate/run.ts"],"sourcesContent":["import process from 'node:process'\nimport { resolve } from 'node:path'\nimport { styleText } from 'node:util'\nimport { findConfigFile } from '@internals/shared'\nimport { toError } from '@internals/utils'\nimport type { Config } from '@kubb/core'\nimport { trackRun } from '../../Telemetry.ts'\nimport { getConfigs } from '../../config.ts'\nimport { pluralize } from '../../ui/text.ts'\nimport { logCommandSummary } from '../../ui/summary.ts'\n\ntype ValidateOptions = {\n /**\n * Path or URL to the specification to validate.\n */\n input: string\n configPath?: string\n}\n\n/**\n * Validates `input` with the configured adapters, falling back to OpenAPI when no config exists.\n * Exits the process with code 1 on validation failure or missing dependency.\n */\nexport async function run({ input, configPath }: ValidateOptions): Promise<void> {\n const hrStart = process.hrtime()\n const report = trackRun({ command: 'validate', hrStart })\n let adapterName: string | undefined\n\n try {\n const configFile = configPath ?? findConfigFile()\n // A config found by search that does not load must not block validating a file; an explicit `--config` still fails.\n const loaded = configFile\n ? await getConfigs({ configPath: configFile, input }).catch((error) => {\n if (configPath) throw error\n })\n : undefined\n const fallback = async () => {\n adapterName = '@kubb/adapter-oas'\n const { adapterOas } = await import('@kubb/adapter-oas')\n return [{ adapter: adapterOas(), input }]\n }\n // An array config often repeats one adapter, so each adapter and input pair is validated once.\n const unique = new Map(\n (loaded?.configs ?? []).map((config) => {\n const resolved = URL.canParse(input) ? input : resolve(config.root || process.cwd(), input)\n return [`${config.adapter?.name}\\0${resolved}`, { adapter: config.adapter, input: resolved }] as const\n }),\n )\n const targets: Array<{ adapter: Config['adapter']; input: string }> = loaded ? [...unique.values()] : await fallback()\n if (!targets.length) throw new Error('The Kubb config contains no configurations to validate.')\n for (const target of targets) {\n adapterName = target.adapter?.name\n if (!target.adapter) throw new Error('No adapter is configured. Set adapter in your Kubb config to validate this specification.')\n await target.adapter.validate(target.input, { throwOnError: true })\n }\n const specifications = new Set(targets.map((target) => target.input)).size\n const adapterNames = [...new Set(targets.flatMap((target) => target.adapter?.name ?? []))]\n await report({ status: 'success' })\n\n logCommandSummary({\n title: 'Validation passed',\n status: 'success',\n hrStart,\n lines: [\n ` ${styleText('bold', `${pluralize(specifications, 'specification')} validated`)}`,\n ` ${styleText('dim', 'Input')} ${styleText('cyan', input)}`,\n ` ${styleText('dim', adapterNames.length === 1 ? 'Adapter' : 'Adapters')} ${adapterNames.join(', ')}`,\n ],\n })\n } catch (error) {\n await report({ status: 'failed' })\n const message = toError(error).message\n const missingAdapter = adapterName === '@kubb/adapter-oas' && /(?:Cannot find|Cannot resolve|not found)[\\s\\S]*@kubb\\/adapter-oas/.test(message)\n logCommandSummary({\n title: missingAdapter ? 'Could not validate' : 'Validation failed',\n status: 'failed',\n hrStart,\n lines: [\n ` ${styleText('dim', 'Input')} ${styleText('cyan', input)}`,\n ` ${styleText('dim', 'Adapter')} ${adapterName ?? 'not configured'}${missingAdapter ? ' · not installed' : ''}`,\n '',\n styleText('bold', missingAdapter ? 'Required package' : 'Validation error'),\n ` ${styleText('red', message)}`,\n ...(missingAdapter\n ? ['', 'Install it with:', styleText('cyan', ' npm install @kubb/adapter-oas'), styleText('cyan', ' pnpm add @kubb/adapter-oas')]\n : []),\n ],\n })\n\n process.exit(1)\n }\n}\n"],"mappings":";;;;;;;;;;;;;;AAuBA,eAAsB,IAAI,EAAE,OAAO,cAA8C;CAC/E,MAAM,UAAU,QAAQ,OAAO;CAC/B,MAAM,SAAS,SAAS;EAAE,SAAS;EAAY;CAAQ,CAAC;CACxD,IAAI;CAEJ,IAAI;EACF,MAAM,aAAa,cAAc,eAAe;EAEhD,MAAM,SAAS,aACX,MAAM,WAAW;GAAE,YAAY;GAAY;EAAM,CAAC,CAAC,CAAC,OAAO,UAAU;GACnE,IAAI,YAAY,MAAM;EACxB,CAAC,IACD,KAAA;EACJ,MAAM,WAAW,YAAY;GAC3B,cAAc;GACd,MAAM,EAAE,eAAe,MAAM,OAAO;GACpC,OAAO,CAAC;IAAE,SAAS,WAAW;IAAG;GAAM,CAAC;EAC1C;EAEA,MAAM,SAAS,IAAI,KAChB,QAAQ,WAAW,CAAC,EAAA,CAAG,KAAK,WAAW;GACtC,MAAM,WAAW,IAAI,SAAS,KAAK,I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AAO;IACL,KAAK,UAAU,OAAO,OAAO,EAAE,MAAM,UAAU,QAAQ,KAAK;IAC5D,KAAK,UAAU,OAAO,SAAS,EAAE,IAAI,eAAe,mBAAmB,iBAAiB,qBAAqB;IAC7G;IACA,UAAU,QAAQ,iBAAiB,qBAAqB,kBAAkB;IAC1E,KAAK,UAAU,OAAO,OAAO;IAC7B,GAAI,iBACA;KAAC;KAAI;KAAoB,UAAU,QAAQ,iCAAiC;KAAG,UAAU,QAAQ,8BAA8B;IAAC,IAChI,CAAC;GACP;EACF,CAAC;EAED,QAAQ,KAAK,CAAC;CAChB;AACF"}
|
package/dist/run-S3xKq4bj.js.map
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"run-S3xKq4bj.js","names":["logLevel","logLevelMap"],"sources":["../src/runners/generate/run.ts"],"sourcesContent":["import path from 'node:path'\nimport process from 'node:process'\nimport { styleText } from 'node:util'\nimport { formatMs, formatters, getElapsedMs, linters } from '@internals/utils'\nimport {\n Hookable,\n type CLIOptions,\n cliReporter,\n type Config,\n createKubb,\n Diagnostics,\n fileReporter,\n getInputKind,\n htmlReporter,\n jsonReporter,\n type KubbHooks,\n logLevel as logLevelMap,\n memoryStorage,\n type ReporterName,\n} from '@kubb/core'\nimport { version } from '../../../package.json'\nimport { trackRun } from '../../Telemetry.ts'\nimport { pluralize } from '../../ui/text.ts'\nimport setupReporters, { selectReporters } from '../../loggers/reporters.ts'\nimport { createPlainWriter } from '../../loggers/plainWriter.ts'\nimport { logIntro, logOutro, logSpacer, logTip } from '../../ui/intro.ts'\nimport { logError, logInfo, logStep } from '../../ui/log.ts'\nimport { logBanner } from '../../ui/mascot.ts'\nimport { createSpinner } from '../../ui/spinner.ts'\nimport { getConfigs } from '../../config.ts'\nimport { isOutdated } from '../../utils/registry.ts'\nimport { type BuildDiff, type BuildSnapshot, diffBuilds, fetchUrlBody, listenForKeys, startUrlWatcher, startWatcher, trackBuild } from './utils.ts'\n\n/** NPM registry endpoint used to check for @kubb/cli updates. */\nconst KUBB_NPM_PACKAGE_URL = 'https://registry.npmjs.org/@kubb/cli/latest' as const\n\n/** Upper bound in milliseconds for the npm update check, so a slow registry never stalls a run. */\nconst UPDATE_CHECK_TIMEOUT_MS = 3_000\n\n/** The formatter names from `Config['output'].format`, without `'auto'` (detection, not a tool) and `false` (skip). */\ntype FormatterName = Exclude<NonNullable<Config['output']['format']>, 'auto' | false>\ntype LinterName = Exclude<NonNullable<Config['output']['lint']>, 'auto' | false>\n\n// Pinned here, not in `@internals/utils` (which must not import `@kubb/core`): a tool added to the union without a descriptor fails to compile.\nformatters satisfies Record<FormatterName, unknown>\nlinters satisfies Record<LinterName, unknown>\n\ntype GenerateProps = {\n input?: string\n config: Config\n hooks: Hookable<KubbHooks>\n /**\n * When `true`, generates in memory instead of writing to disk, skips formatting, linting, and\n * post-generate commands, and prints what would change on disk.\n */\n dryRun?: boolean\n}\n\nexport async function generate(options: GenerateProps): Promise<boolean> {\n const { input, hooks, dryRun = false } = options\n\n const report = trackRun({ command: 'generate', hrStart: process.hrtime() })\n\n const config: Config = {\n ...options.config,\n input: input ?? options.config.input,\n // Dry-run never touches disk, regardless of the config's own storage driver.\n storage: dryRun ? memoryStorage() : options.config.storage,\n // Also keeps core's `hasOutputPasses` false, so dry-run skips the output manifest write too.\n output: dryRun ? { ...options.config.output, format: false, lint: false, postGenerate: [] } : options.config.output,\n }\n\n // Core formats, lints and runs `output.postGenerate` after an error-free build, and reports\n // their failures as coded diagnostics that reach the summary, the json report and the exit code.\n const kubb = createKubb(config, { hooks })\n const result = await kubb.generate()\n\n await report({\n // A setup that threw leaves no driver, so read the configured plugins instead.\n plugins: kubb.config.plugins.flatMap((p) =>\n p && typeof p === 'object' ? [{ name: p.meta?.name ?? p.name ?? '', options: (p.options ?? {}) as Record<string, unknown> }] : [],\n ),\n filesCreated: result.files.length,\n status: result.success ? 'success' : 'failed',\n })\n\n return result.success\n}\n\ntype GenerateCommandOptions = {\n input?: string\n configPath?: string\n logLevel: string\n watch: boolean\n reporters?: Array<ReporterName>\n dryRun?: boolean\n}\n\n/** The latest published version, `undefined` when the registry does not answer in time. Never rejects. */\nasync function fetchLatestVersion(): Promise<string | undefined> {\n try {\n const res = await fetch(KUBB_NPM_PACKAGE_URL, { signal: AbortSignal.timeout(UPDATE_CHECK_TIMEOUT_MS) })\n const data = (await res.json()) as { version: string }\n return data.version\n } catch {\n // Ignore network errors\n return undefined\n }\n}\n\nasync function checkForUpdate({ hooks, latest }: { hooks: Hookable<KubbHooks>; latest: Promise<string | undefined> }): Promise<void> {\n const latestVersion = await latest\n if (latestVersion && isOutdated({ installed: version, latest: latestVersion })) {\n await Diagnostics.emit(hooks, Diagnostics.update({ currentVersion: version, latestVersion }))\n }\n}\n\n/** Prints `Rebuilt in 1.2s · +1 schema -2 operations`, without the names part when the spec kept the same names. */\nfunction logRebuild({ diff: { schemas, operations }, durationMs }: { diff: BuildDiff; durationMs: number }): void {\n const specChange = [\n schemas.added && styleText('green', `+${pluralize(schemas.added, 'schema')}`),\n schemas.removed && styleText('red', `-${pluralize(schemas.removed, 'schema')}`),\n operations.added && styleText('green', `+${pluralize(operations.added, 'operation')}`),\n operations.removed && styleText('red', `-${pluralize(operations.removed, 'operation')}`),\n ]\n .filter(Boolean)\n .join(' ')\n logStep([`Rebuilt in ${formatMs(durationMs)}`, specChange].filter(Boolean).join(styleText('dim', ' · ')))\n}\n\n/**\n * Runs the full Kubb generation lifecycle for the given CLI options.\n * Loads configs, sets up the reporters (CLI `--reporter` picks which of `config.reporters` to trigger),\n * checks for a newer version, and calls `generate` for each config entry.\n */\nexport async function run({ input, configPath, logLevel: logLevelKey, watch, reporters: cliReporters, dryRun }: GenerateCommandOptions): Promise<void> {\n // Started first so the registry request overlaps the banner and the config load.\n const latest = fetchLatestVersion()\n const logLevel = logLevelMap[logLevelKey as keyof typeof logLevelMap] ?? logLevelMap.info\n const hooks = new Hookable<KubbHooks>()\n\n // CLI `--reporter` selects which reporters to trigger by name, defaulting to `cli`. `defineConfig`\n // registers the built-in reporters on the config; a config exported without it falls back to them below.\n const requestedNames: Array<ReporterName> = cliReporters?.length ? cliReporters : ['cli']\n\n // The `json` reporter owns stdout, so the command writes nothing of its own around it.\n const json = requestedNames.includes('json')\n const quiet = logLevel <= logLevelMap.silent || json\n\n // Errors raised outside a build have no report entry. In `json` mode they go to a stderr logger,\n // so they are never silent and stdout stays one JSON document.\n const errorHooks = json ? new Hookable<KubbHooks>() : hooks\n if (json) setupReporters(errorHooks, { logLevel, reporters: [cliReporter], writer: createPlainWriter(console.error) })\n\n // The config loads while the banner plays; the output still prints in order once the banner is done.\n const banner = quiet ? undefined : logBanner(version)\n const loading = getConfigs({\n configPath,\n input,\n watch,\n logLevel: logLevelKey as CLIOptions['logLevel'],\n })\n // Handled below; this keeps a rejection during the banner from counting as unhandled.\n loading.catch(() => undefined)\n await banner\n\n if (!quiet) {\n logIntro({ title: 'Configuration' })\n }\n\n // Load the config first so `config.reporters` can pick the reporters. A failure here has no\n // reporter installed yet, so fall back to the default `cli` reporter to surface it.\n const configSpinner = createSpinner()\n let configs: Array<Config>\n let resolvedConfigPath: string\n try {\n if (!quiet) configSpinner.start('Loading config')\n\n const loaded = await loading\n configs = loaded.configs\n resolvedConfigPath = loaded.configPath\n\n if (!quiet) configSpinner.stop(`Loaded ${styleText('dim', path.relative(process.cwd(), resolvedConfigPath))}`)\n } catch (error) {\n if (!quiet) configSpinner.error('Config failed loading')\n\n if (!json) setupReporters(hooks, { logLevel, reporters: [cliReporter] })\n // A diagnostic thrown while the config file runs, such as invalid extension options, sits in the cause chain.\n await Diagnostics.emit(errorHooks, error)\n\n if (!quiet) logOutro(styleText('red', '✗ Configuration failed'))\n process.exit(1)\n }\n\n // Without a reporter nothing is printed, not even an error, so a config written without\n // `defineConfig` gets the same built-ins it would have registered.\n const available = configs[0]?.reporters?.length ? configs[0].reporters : [cliReporter, jsonReporter, fileReporter, htmlReporter]\n const reporters = selectReporters(available, requestedNames)\n setupReporters(hooks, { logLevel, reporters, dryRun })\n\n await hooks.callHook('kubb:lifecycle:start', { version })\n\n // Inside the bootstrap group, so an update notice reads as part of the setup rather than as part\n // of the first config's generation.\n await checkForUpdate({ hooks, latest })\n\n if (!quiet) logOutro(`${pluralize(configs.length, 'config')} ready`)\n\n try {\n let anyFailed = false\n // One tracker, one key listener and one build queue serve every watched config, so several configs never mix diffs or answer `r` twice.\n const tracker = watch ? trackBuild(hooks) : undefined\n const rebuilds: Array<() => Promise<void>> = []\n let armKeys: (() => void) | undefined\n // Configs share the hooks emitter, so every build, from any watcher or the `r` key, waits for the one before it.\n let queue = Promise.resolve()\n for (const config of configs) {\n const effectiveInput = input ?? config.input\n const inputKind = typeof effectiveInput === 'string' ? getInputKind(effectiveInput) : undefined\n const watchPath = inputKind === 'file' || inputKind === 'url' ? (effectiveInput as string) : undefined\n if (watchPath && tracker) {\n const label = styleText('yellow', `Watching ${inputKind === 'url' ? watchPath : path.relative(process.cwd(), watchPath)}`)\n let previous: BuildSnapshot | undefined\n // Don't removeAll() between builds, that would also drop logger and lifecycle\n // listeners. Plugin listeners are already disposed by safeBuild's dispose()\n // in its finally block, so re-running generate() on the same hooks emitter is safe.\n const build = async () => {\n const hrStart = process.hrtime()\n const succeeded = await generate({ input, config, hooks, dryRun })\n const snapshot = tracker.take()\n if (previous) logRebuild({ diff: diffBuilds(previous, snapshot), durationMs: getElapsedMs(hrStart) })\n previous = snapshot\n\n logStep(armKeys ? `${label} ${styleText('dim', 'r rebuild · q quit')}` : label)\n armKeys?.()\n if (succeeded) {\n logSpacer()\n logTip()\n }\n }\n // A trigger that lands while this config's build is queued joins it; one that lands during the build queues one more. Never rejects.\n let pending = false\n const rebuild = (): Promise<void> => {\n if (pending) return queue\n pending = true\n queue = queue\n .then(() => {\n pending = false\n return build()\n })\n .catch((error) => void Diagnostics.emit(errorHooks, error))\n return queue\n }\n rebuilds.push(rebuild)\n if (!quiet) {\n armKeys ??= listenForKeys({\n rebuild: () => rebuilds.forEach((trigger) => void trigger()),\n quit: (code) => void Promise.resolve(hooks.callHook('kubb:lifecycle:end')).finally(() => process.exit(code)),\n })\n }\n\n // For a URL input, capture the document before the build: it becomes the watcher's\n // change-detection baseline, so an edit landing before the first poll still rebuilds.\n // When the server is down the baseline stays undefined and the watcher rebuilds on its\n // first successful poll, so recovery with an unchanged document still generates output.\n const initialBody = inputKind === 'url' ? await fetchUrlBody(watchPath) : undefined\n\n // The watchers ignore their startup state, so run the first build here; a failing one keeps watching so the user can fix the input.\n await rebuild()\n\n if (inputKind === 'url') {\n startUrlWatcher(watchPath, rebuild, { log: { info: logInfo, error: logError }, initialBody })\n } else {\n await startWatcher([watchPath], rebuild, { info: logInfo, error: logError })\n }\n } else {\n try {\n const succeeded = await generate({ input, config, hooks, dryRun })\n if (!succeeded) anyFailed = true\n } catch (configError) {\n await Diagnostics.emit(errorHooks, configError)\n anyFailed = true\n }\n }\n }\n\n await hooks.callHook('kubb:lifecycle:end')\n\n // Watch mode prints a tip after each successful build. Regular generate commands need to\n // print one explicitly after the lifecycle group has closed so it stays outside the group.\n if (!quiet && !watch && !anyFailed) {\n logTip()\n }\n\n if (anyFailed) {\n process.exit(1)\n }\n } catch (error) {\n await Diagnostics.emit(errorHooks, error)\n process.exit(1)\n }\n}\n"],"mappings":";;;;;;;;;;;;;AAkCA,MAAM,uBAAuB;;AAG7B,MAAM,0BAA0B;AAqBhC,eAAsB,SAAS,SAA0C;CACvE,MAAM,EAAE,OAAO,OAAO,SAAS,UAAU;CAEzC,MAAM,SAAS,SAAS;EAAE,SAAS;EAAY,SAAS,QAAQ,OAAO;CAAE,CAAC;CAE1E,MAAM,SAAiB;EACrB,GAAG,QAAQ;EACX,OAAO,SAAS,QAAQ,OAAO;EAE/B,SAAS,SAAS,cAAc,IAAI,QAAQ,OAAO;EAEnD,QAAQ,SAAS;GAAE,GAAG,QAAQ,OAAO;GAAQ,QAAQ;GAAO,MAAM;GAAO,cAAc,CAAC;EAAE,IAAI,QAAQ,OAA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