@kubb/cli 5.10.1 → 5.10.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (90) hide show
  1. package/dist/{Telemetry-BfdvvZus.cjs → Telemetry-BV4GonCV.cjs} +2 -2
  2. package/dist/Telemetry-BV4GonCV.cjs.map +1 -0
  3. package/dist/Telemetry-CH2kkxWK.cjs +322 -0
  4. package/dist/Telemetry-CH2kkxWK.cjs.map +1 -0
  5. package/dist/{Telemetry-Bf6lUdai.js → Telemetry-Cz9QCzRo.js} +2 -2
  6. package/dist/Telemetry-Cz9QCzRo.js.map +1 -0
  7. package/dist/{background-D5K6ecEo.js → background-DFME5huR.js} +30 -7
  8. package/dist/background-DFME5huR.js.map +1 -0
  9. package/dist/{background-obsD4Gj2.cjs → background-DVZB1n4j.cjs} +25 -6
  10. package/dist/background-DVZB1n4j.cjs.map +1 -0
  11. package/dist/background-WaKtfQWr.cjs +192 -0
  12. package/dist/background-WaKtfQWr.cjs.map +1 -0
  13. package/dist/{background-C8doa9-4.js → background-_A5NwvYH.js} +1 -1
  14. package/dist/{config-CcqzzfB7.cjs → config-DKAqX5sW.cjs} +18 -4
  15. package/dist/config-DKAqX5sW.cjs.map +1 -0
  16. package/dist/{config-IMZ26zcb.js → config-DV_7s1m-.js} +19 -5
  17. package/dist/config-DV_7s1m-.js.map +1 -0
  18. package/dist/config-OL_izsmp.cjs +113 -0
  19. package/dist/config-OL_izsmp.cjs.map +1 -0
  20. package/dist/credentials-xOkTTDWj.cjs +113 -0
  21. package/dist/credentials-xOkTTDWj.cjs.map +1 -0
  22. package/dist/index.cjs +65 -24
  23. package/dist/index.cjs.map +1 -1
  24. package/dist/index.d.cts +8 -0
  25. package/dist/index.d.ts +0 -1
  26. package/dist/index.js +65 -24
  27. package/dist/index.js.map +1 -1
  28. package/dist/output-C5g7AtWH.cjs +1008 -0
  29. package/dist/output-C5g7AtWH.cjs.map +1 -0
  30. package/dist/{output-mwVt_Vj9.js → output-D_gc1nrM.js} +99 -44
  31. package/dist/output-D_gc1nrM.js.map +1 -0
  32. package/dist/{output-DLrxGtuN.cjs → output-nieBFDgM.cjs} +104 -43
  33. package/dist/output-nieBFDgM.cjs.map +1 -0
  34. package/dist/{registry-x-_nbYR6.cjs → registry-C8E_G7Xc.cjs} +49 -15
  35. package/dist/registry-C8E_G7Xc.cjs.map +1 -0
  36. package/dist/registry-CIpW2zQc.cjs +157 -0
  37. package/dist/registry-CIpW2zQc.cjs.map +1 -0
  38. package/dist/{registry-ChqX2AFQ.js → registry-De1vVn1d.js} +50 -16
  39. package/dist/registry-De1vVn1d.js.map +1 -0
  40. package/dist/rolldown-runtime-C0BPl7ul.cjs +43 -0
  41. package/dist/run-BbhrOuK6.cjs +40 -0
  42. package/dist/{run-1MJA0P5x.cjs.map → run-BbhrOuK6.cjs.map} +1 -1
  43. package/dist/{run-DHiVlG37.cjs → run-BnLba1gt.cjs} +27 -14
  44. package/dist/run-BnLba1gt.cjs.map +1 -0
  45. package/dist/{run-D4vOhfbJ.js → run-Bp47k1W1.js} +2 -2
  46. package/dist/{run-D4vOhfbJ.js.map → run-Bp47k1W1.js.map} +1 -1
  47. package/dist/run-BpdJ6X75.cjs +32 -0
  48. package/dist/{run-B13e9GQz.cjs.map → run-BpdJ6X75.cjs.map} +1 -1
  49. package/dist/{run-Cm0sJO0h.js → run-CCMlmk-z.js} +1 -1
  50. package/dist/{run-DTz7gAk1.js → run-CPYD1Lp0.js} +27 -14
  51. package/dist/run-CPYD1Lp0.js.map +1 -0
  52. package/dist/run-CSOEGpWZ.cjs +326 -0
  53. package/dist/run-CSOEGpWZ.cjs.map +1 -0
  54. package/dist/{run-B13e9GQz.cjs → run-CvE8ZdKG.cjs} +2 -2
  55. package/dist/run-CvE8ZdKG.cjs.map +1 -0
  56. package/dist/{run-Cu3pmezx.js → run-DaFK-Uy2.js} +2 -2
  57. package/dist/{run-Cu3pmezx.js.map → run-DaFK-Uy2.js.map} +1 -1
  58. package/dist/{run-BAlcXyYw.js → run-Ij84bqza.js} +22 -16
  59. package/dist/run-Ij84bqza.js.map +1 -0
  60. package/dist/{run-1MJA0P5x.cjs → run-MFjzBB_M.cjs} +2 -2
  61. package/dist/run-MFjzBB_M.cjs.map +1 -0
  62. package/dist/run-hgSZImuK.cjs +345 -0
  63. package/dist/run-hgSZImuK.cjs.map +1 -0
  64. package/dist/{run-CUyhuGlK.cjs → run-hyi91b22.cjs} +22 -16
  65. package/dist/run-hyi91b22.cjs.map +1 -0
  66. package/dist/{snapshot-DCG-Jf1A.js → snapshot-B6w3BLum.js} +22 -9
  67. package/dist/snapshot-B6w3BLum.js.map +1 -0
  68. package/dist/snapshot-DP9Pcnsg.cjs +264 -0
  69. package/dist/snapshot-DP9Pcnsg.cjs.map +1 -0
  70. package/dist/{snapshot-C5cthCuU.cjs → snapshot-D_F4XkYQ.cjs} +22 -9
  71. package/dist/snapshot-D_F4XkYQ.cjs.map +1 -0
  72. package/dist/studioWorker.js +2 -2
  73. package/package.json +15 -10
  74. package/dist/Telemetry-Bf6lUdai.js.map +0 -1
  75. package/dist/Telemetry-BfdvvZus.cjs.map +0 -1
  76. package/dist/background-D5K6ecEo.js.map +0 -1
  77. package/dist/background-obsD4Gj2.cjs.map +0 -1
  78. package/dist/config-CcqzzfB7.cjs.map +0 -1
  79. package/dist/config-IMZ26zcb.js.map +0 -1
  80. package/dist/output-DLrxGtuN.cjs.map +0 -1
  81. package/dist/output-mwVt_Vj9.js.map +0 -1
  82. package/dist/registry-ChqX2AFQ.js.map +0 -1
  83. package/dist/registry-x-_nbYR6.cjs.map +0 -1
  84. package/dist/run-BAlcXyYw.js.map +0 -1
  85. package/dist/run-CUyhuGlK.cjs.map +0 -1
  86. package/dist/run-DHiVlG37.cjs.map +0 -1
  87. package/dist/run-DTz7gAk1.js.map +0 -1
  88. package/dist/snapshot-C5cthCuU.cjs.map +0 -1
  89. package/dist/snapshot-DCG-Jf1A.js.map +0 -1
  90. package/dist/studioWorker.d.ts +0 -1
@@ -1,8 +1,8 @@
1
1
  import "./rolldown-runtime-CRm0XQPb.js";
2
- import { l as toError, n as trackRun, r as version } from "./Telemetry-Bf6lUdai.js";
3
- import { a as logInfo, c as logSpacer, h as pluralize, i as logError, l as logStep, n as logBanner, o as logIntro, s as logOutro, t as createSpinner, u as logTip } from "./output-mwVt_Vj9.js";
4
- import { a as isOutdated } from "./registry-ChqX2AFQ.js";
5
- import { n as selectReporters, r as setupReporters, t as getConfigs } from "./config-IMZ26zcb.js";
2
+ import { l as toError, n as trackRun, r as version } from "./Telemetry-Cz9QCzRo.js";
3
+ import { a as logInfo, c as logSpacer, f as createPlainLogger, h as pluralize, i as logError, l as logStep, n as logBanner, o as logIntro, s as logOutro, t as createSpinner, u as logTip } from "./output-D_gc1nrM.js";
4
+ import { a as isOutdated } from "./registry-De1vVn1d.js";
5
+ import { n as selectReporters, r as setupReporters, t as getConfigs } from "./config-DV_7s1m-.js";
6
6
  import { styleText } from "node:util";
7
7
  import process from "node:process";
8
8
  import path from "node:path";
@@ -199,10 +199,10 @@ async function generate(options) {
199
199
  info: `${result.files.length} file(s) would be generated`
200
200
  });
201
201
  await report({
202
- plugins: Array.from(kubb.driver.plugins.values(), (p) => ({
203
- name: p.name,
204
- options: p.options
205
- })),
202
+ plugins: kubb.config.plugins.flatMap((p) => p && typeof p === "object" ? [{
203
+ name: p.meta?.name ?? p.name ?? "",
204
+ options: p.options ?? {}
205
+ }] : []),
206
206
  filesCreated: result.files.length,
207
207
  status: result.success ? "success" : "failed"
208
208
  });
@@ -229,7 +229,14 @@ async function run({ input, configPath, logLevel: logLevelKey, watch, reporters:
229
229
  const logLevel$1 = logLevel[logLevelKey] ?? logLevel.info;
230
230
  const hooks = new Hookable();
231
231
  const requestedNames = cliReporters?.length ? cliReporters : ["cli"];
232
- const quiet = logLevel$1 <= logLevel.silent || requestedNames.includes("json");
232
+ const json = requestedNames.includes("json");
233
+ const quiet = logLevel$1 <= logLevel.silent || json;
234
+ const errorHooks = json ? new Hookable() : hooks;
235
+ if (json) setupReporters(errorHooks, {
236
+ logLevel: logLevel$1,
237
+ reporters: [cliReporter],
238
+ logger: createPlainLogger(console.error)
239
+ });
233
240
  if (!quiet) {
234
241
  logBanner(version);
235
242
  logIntro({ title: "Configuration" });
@@ -250,12 +257,11 @@ async function run({ input, configPath, logLevel: logLevelKey, watch, reporters:
250
257
  if (!quiet) configSpinner.stop(`Loaded ${styleText("dim", path.relative(process.cwd(), resolvedConfigPath))}`);
251
258
  } catch (error) {
252
259
  if (!quiet) configSpinner.error("Config failed loading");
253
- setupReporters(hooks, {
260
+ if (!json) setupReporters(hooks, {
254
261
  logLevel: logLevel$1,
255
262
  reporters: [cliReporter]
256
263
  });
257
- const diagnostic = Diagnostics.from(error);
258
- await (diagnostic.code === Diagnostics.code.unknown ? hooks.callHook("kubb:error", { error: toError(error) }) : Diagnostics.emit(hooks, diagnostic));
264
+ await Diagnostics.emit(errorHooks, error);
259
265
  if (!quiet) logOutro(styleText("red", "✗ Configuration failed"));
260
266
  process.exit(1);
261
267
  }
@@ -298,7 +304,7 @@ async function run({ input, configPath, logLevel: logLevelKey, watch, reporters:
298
304
  try {
299
305
  await build(watchedPaths);
300
306
  } catch (buildError) {
301
- await hooks.callHook("kubb:error", { error: toError(buildError) });
307
+ await Diagnostics.emit(errorHooks, buildError);
302
308
  }
303
309
  if (inputKind === "url") startUrlWatcher(watchPath, build, {
304
310
  log: {
@@ -319,7 +325,7 @@ async function run({ input, configPath, logLevel: logLevelKey, watch, reporters:
319
325
  dryRun
320
326
  })) anyFailed = true;
321
327
  } catch (configError) {
322
- await hooks.callHook("kubb:error", { error: toError(configError) });
328
+ await Diagnostics.emit(errorHooks, configError);
323
329
  anyFailed = true;
324
330
  }
325
331
  }
@@ -327,11 +333,11 @@ async function run({ input, configPath, logLevel: logLevelKey, watch, reporters:
327
333
  if (!quiet && !watch && !anyFailed) logTip();
328
334
  if (anyFailed) process.exit(1);
329
335
  } catch (error) {
330
- await hooks.callHook("kubb:error", { error: toError(error) });
336
+ await Diagnostics.emit(errorHooks, error);
331
337
  process.exit(1);
332
338
  }
333
339
  }
334
340
  //#endregion
335
341
  export { run };
336
342
 
337
- //# sourceMappingURL=run-BAlcXyYw.js.map
343
+ //# sourceMappingURL=run-Ij84bqza.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"run-Ij84bqza.js","names":["logLevel","logLevelMap"],"sources":["../src/runners/generate/utils.ts","../src/runners/generate/run.ts"],"sourcesContent":["import process from 'node:process'\nimport { styleText } from 'node:util'\nimport { toError } from '@internals/utils'\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/** Interval in milliseconds between polls of a remote `input` URL in watch mode, which emits no filesystem events. */\nconst URL_WATCHER_INTERVAL_MS = 2_000\n\n/** Upper bound in milliseconds for one URL watcher request, headers and body read, so a hung server never stalls polling. */\nconst URL_WATCHER_TIMEOUT_MS = 10_000\n\ntype SerialRunnerOptions = {\n /**\n * The async work to serialize.\n */\n run(): Promise<void>\n /**\n * Receives errors thrown by `run`, so a failure never rejects the returned trigger.\n */\n onError(error: Error): void\n}\n\n/**\n * Wraps `run` so invocations never overlap: a trigger that lands while a run is in flight\n * marks it dirty and runs once more after it finishes, no matter how many triggers arrived.\n * Useful for event-driven reruns (a file watcher, a queue drain) where bursts should\n * coalesce into a single trailing run.\n *\n * @example\n * ```ts\n * const rebuild = createSerialRunner({\n * run: () => build(),\n * onError: (error) => log.error(error.message),\n * })\n * watcher.on('change', () => void rebuild())\n * ```\n */\nexport function createSerialRunner({ run, onError }: SerialRunnerOptions): () => Promise<void> {\n let running = false\n let dirty = false\n\n return async (): Promise<void> => {\n if (running) {\n dirty = true\n return\n }\n running = true\n do {\n dirty = false\n try {\n await run()\n } catch (error) {\n onError(toError(error))\n }\n } while (dirty)\n running = false\n }\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 build, and builds never overlap: changes during a build queue exactly\n * one rebuild. 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 process.once('SIGINT', () => {\n watcher.close()\n })\n process.once('SIGTERM', () => {\n watcher.close()\n })\n\n // Bursts never overlap builds on the shared hooks emitter: a change during a build\n // queues exactly one rerun.\n const runBuild = createSerialRunner({\n run: () => cb(path),\n onError: () => log.error(styleText('red', 'Watcher failed')),\n })\n let debounceTimer: ReturnType<typeof setTimeout> | null = null\n\n watcher.on('all', (type, file) => {\n log.info(styleText('yellow', styleText('bold', `Change detected: ${type} ${file}`)))\n if (debounceTimer) clearTimeout(debounceTimer)\n debounceTimer = setTimeout(() => {\n debounceTimer = null\n void runBuild()\n }, WATCHER_DEBOUNCE_MS)\n })\n\n return async () => {\n if (debounceTimer) clearTimeout(debounceTimer)\n await watcher.close()\n }\n}\n\n/**\n * Fetches the body of a remote spec URL, `undefined` when the server does not answer with a\n * readable 2xx body before `signal` aborts. The caller seeds `startUrlWatcher` with the result, so\n * the watcher compares polls against the content the initial build ran on.\n */\nexport async function fetchUrlBody(url: string, signal: AbortSignal = AbortSignal.timeout(URL_WATCHER_TIMEOUT_MS)): Promise<string | undefined> {\n try {\n const response = await fetch(url, { signal })\n if (!response.ok) return undefined\n return await response.text()\n } catch {\n return undefined\n }\n}\n\ntype UrlWatcherOptions = {\n /**\n * Sink for watcher messages, `console.log` by default.\n */\n log?: WatcherLog\n /**\n * Time in milliseconds between polls.\n */\n intervalMs?: number\n /**\n * Upper bound in milliseconds for one poll request, covering headers and body read.\n */\n timeoutMs?: number\n /**\n * Body the initial build ran against, the baseline for change detection. When omitted (the\n * server was unreachable at startup), the first successful poll rebuilds so the output catches\n * up as soon as the server responds.\n */\n initialBody?: string\n}\n\n/**\n * Polls a remote spec URL and calls `cb` whenever the response body changes. A remote document\n * emits no filesystem events, so this is the URL counterpart of `startWatcher`.\n *\n * `initialBody` seeds the change detection, so an edit landing between the initial build and the\n * first poll still rebuilds. An unreachable server (the API restarting between saves) is reported\n * once per outage and polling continues; after it recovers, a rebuild happens only when the body\n * actually differs from the last one seen, so a plain restart with an unchanged spec stays quiet.\n * Each request is aborted after `timeoutMs`, so a hung response delays at most one poll.\n *\n * Returns a function that stops polling and aborts the in-flight request, so callers (and tests)\n * can shut the watcher down without signaling the process.\n */\nexport function startUrlWatcher(url: string, cb: (path: Array<string>) => Promise<void>, options: UrlWatcherOptions = {}): () => void {\n const { log = { info: console.log, error: console.log }, intervalMs = URL_WATCHER_INTERVAL_MS, timeoutMs = URL_WATCHER_TIMEOUT_MS, initialBody } = options\n\n let lastBody = initialBody\n let offline = false\n let timer: ReturnType<typeof setTimeout> | null = null\n let controller: AbortController | null = null\n let stopped = false\n\n const stop = () => {\n stopped = true\n if (timer) clearTimeout(timer)\n controller?.abort()\n }\n process.once('SIGINT', stop)\n process.once('SIGTERM', stop)\n\n // Builds never overlap on the shared hooks emitter: a change during a build queues exactly\n // one rerun.\n const runBuild = createSerialRunner({\n run: () => cb([url]),\n onError: () => log.error(styleText('red', 'Watcher failed')),\n })\n\n const schedule = () => {\n if (!stopped) {\n timer = setTimeout(() => void poll(), intervalMs)\n }\n }\n\n const poll = async (): Promise<void> => {\n controller = new AbortController()\n // The signal also aborts the body read, so a response that stalls mid-stream still times out.\n const body = await fetchUrlBody(url, AbortSignal.any([controller.signal, AbortSignal.timeout(timeoutMs)]))\n\n if (body === undefined) {\n // `lastBody` survives the outage so recovery rebuilds only on real content changes.\n if (!offline && !stopped) {\n offline = true\n log.error(styleText('red', `Cannot reach ${url}, polling until it responds again`))\n }\n schedule()\n return\n }\n\n if (offline) {\n offline = false\n log.info(styleText('yellow', `${url} is reachable again`))\n }\n const changed = lastBody !== undefined && body !== lastBody\n if (changed) {\n log.info(styleText('yellow', styleText('bold', `Change detected: ${url}`)))\n }\n if (changed || lastBody === undefined) {\n void runBuild()\n }\n lastBody = body\n schedule()\n }\n\n void poll()\n\n return stop\n}\n","import path from 'node:path'\nimport process from 'node:process'\nimport { styleText } from 'node:util'\nimport { formatters, 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 '../../loggers/createLogger.ts'\nimport setupReporters, { selectReporters } from '../../loggers/reporters.ts'\nimport { createPlainLogger } from '../../loggers/plainLogger.ts'\nimport { createSpinner, logBanner, logError, logInfo, logIntro, logOutro, logSpacer, logStep, logTip } from '../../loggers/output.ts'\nimport { getConfigs } from '../../config.ts'\nimport { isOutdated } from '../../utils/registry.ts'\nimport { fetchUrlBody, startUrlWatcher, startWatcher } 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, and skips formatting, linting,\n * and post-generate commands.\n */\n dryRun?: boolean\n}\n\nasync 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 if (dryRun) {\n await hooks.callHook('kubb:info', { message: 'Dry run: no files were written', info: `${result.files.length} file(s) would be generated` })\n }\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\nasync function checkForUpdate(hooks: Hookable<KubbHooks>): Promise<void> {\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 if (data.version && isOutdated({ installed: version, latest: data.version })) {\n await Diagnostics.emit(hooks, Diagnostics.update({ currentVersion: version, latestVersion: data.version }))\n }\n } catch {\n // Ignore network errors\n }\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 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], logger: createPlainLogger(console.error) })\n\n if (!quiet) {\n logBanner(version)\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 getConfigs({\n configPath,\n input,\n watch,\n logLevel: logLevelKey as CLIOptions['logLevel'],\n })\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 })\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)\n\n if (!quiet) logOutro(`${pluralize(configs.length, 'config')} ready`)\n\n try {\n let anyFailed = false\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 && watch) {\n const watchedPaths = [watchPath]\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 (paths: Array<string>) => {\n const succeeded = await generate({ input, config, hooks, dryRun })\n logStep(styleText('yellow', `Watching for changes in ${paths.join(' and ')}`))\n if (succeeded) {\n logSpacer()\n logTip()\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 try {\n await build(watchedPaths)\n } catch (buildError) {\n await Diagnostics.emit(errorHooks, buildError)\n }\n\n if (inputKind === 'url') {\n startUrlWatcher(watchPath, build, { log: { info: logInfo, error: logError }, initialBody })\n } else {\n await startWatcher(watchedPaths, build, { 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":";;;;;;;;;;;AAKA,MAAM,wBAAwB;;;;;AAM9B,MAAM,sBAAsB;;AAG5B,MAAM,0BAA0B;;AAGhC,MAAM,yBAAyB;;;;;;;;;;;;;;;;AA4B/B,SAAgB,mBAAmB,EAAE,KAAK,WAAqD;CAC7F,IAAI,UAAU;CACd,IAAI,QAAQ;CAEZ,OAAO,YAA2B;EAChC,IAAI,SAAS;GACX,QAAQ;GACR;EACF;EACA,UAAU;EACV,GAAG;GACD,QAAQ;GACR,IAAI;IACF,MAAM,IAAI;GACZ,SAAS,OAAO;IACd,QAAQ,QAAQ,KAAK,CAAC;GACxB;EACF,SAAS;EACT,UAAU;CACZ;AACF;;;;;;;AAaA,eAAsB,aACpB,MACA,IACA,MAAkB;CAAE,MAAM,QAAQ;CAAK,OAAO,QAAQ;AAAI,GAC5B;CAC9B,MAAM,EAAE,UAAU,MAAM,OAAO;CAG/B,MAAM,UAAU,MAAM,MAAM;EAAE,wBAAwB;EAAM,SAAS;EAAuB,eAAe;CAAK,CAAC;CAEjH,QAAQ,KAAK,gBAAgB;EAC3B,QAAQ,MAAM;CAChB,CAAC;CACD,QAAQ,KAAK,iBAAiB;EAC5B,QAAQ,MAAM;CA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OAAO;IACtB,MAAM,eAAe,CAAC,SAAS;IAI/B,MAAM,QAAQ,OAAO,UAAyB;KAC5C,MAAM,YAAY,MAAM,SAAS;MAAE;MAAO;MAAQ;MAAO;KAAO,CAAC;KACjE,QAAQ,UAAU,UAAU,2BAA2B,MAAM,KAAK,OAAO,GAAG,CAAC;KAC7E,IAAI,WAAW;MACb,UAAU;MACV,OAAO;KACT;IACF;IAMA,MAAM,cAAc,cAAc,QAAQ,MAAM,aAAa,SAAS,IAAI,KAAA;IAG1E,IAAI;KACF,MAAM,MAAM,YAAY;IAC1B,SAAS,YAAY;KACnB,MAAM,YAAY,KAAK,YAAY,UAAU;IAC/C;IAEA,IAAI,cAAc,OAChB,gBAAgB,WAAW,OAAO;KAAE,KAAK;MAAE,MAAM;MAAS,OAAO;KAAS;KAAG;IAAY,CAAC;SAE1F,MAAM,aAAa,cAAc,OAAO;KAAE,MAAM;KAAS,OAAO;IAAS,CAAC;GAE9E,OACE,IAAI;IAEF,IAAI,CAAC,MADmB,SAAS;KAAE;KAAO;KAAQ;KAAO;IAAO,CAAC,GACjD,YAAY;GAC9B,SAAS,aAAa;IACpB,MAAM,YAAY,KAAK,YAAY,WAAW;IAC9C,YAAY;GACd;EAEJ;EAEA,MAAM,MAAM,SAAS,oBAAoB;EAIzC,IAAI,CAAC,SAAS,CAAC,SAAS,CAAC,WACvB,OAAO;EAGT,IAAI,WACF,QAAQ,KAAK,CAAC;CAElB,SAAS,OAAO;EACd,MAAM,YAAY,KAAK,YAAY,KAAK;EACxC,QAAQ,KAAK,CAAC;CAChB;AACF"}
@@ -1,5 +1,5 @@
1
1
  const require_rolldown_runtime = require("./rolldown-runtime-CPE0t6oh.cjs");
2
- const require_Telemetry = require("./Telemetry-BfdvvZus.cjs");
2
+ const require_Telemetry = require("./Telemetry-BV4GonCV.cjs");
3
3
  let node_util = require("node:util");
4
4
  let node_process = require("node:process");
5
5
  node_process = require_rolldown_runtime.__toESM(node_process, 1);
@@ -37,4 +37,4 @@ async function run({ input }) {
37
37
  //#endregion
38
38
  exports.run = run;
39
39
 
40
- //# sourceMappingURL=run-1MJA0P5x.cjs.map
40
+ //# sourceMappingURL=run-MFjzBB_M.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"run-MFjzBB_M.cjs","names":["trackRun","process","styleText","toError"],"sources":["../src/runners/validate/run.ts"],"sourcesContent":["import process from 'node:process'\nimport { styleText } from 'node:util'\nimport { toError } from '@internals/utils'\nimport { trackRun } from '../../Telemetry.ts'\n\ntype ValidateOptions = {\n /**\n * Path or URL to the OpenAPI/Swagger file to validate.\n */\n input: string\n}\n\n/**\n * Validates an OpenAPI/Swagger file at `input` using `@kubb/adapter-oas`.\n * Exits the process with code 1 on validation failure or missing dependency.\n */\nexport async function run({ input }: ValidateOptions): Promise<void> {\n const report = trackRun({ command: 'validate', hrStart: process.hrtime() })\n\n try {\n const { adapterOas } = await import('@kubb/adapter-oas')\n\n await adapterOas().validate(input, { throwOnError: true })\n await report({ status: 'success' })\n\n console.log('✅ Validation success')\n } catch (error) {\n await report({ status: 'failed' })\n if (error instanceof Error && /@kubb\\/adapter-oas/.test(error.message)) {\n console.error(styleText('red', 'The @kubb/adapter-oas package is not installed.'))\n console.error('')\n console.error('Install it with:')\n console.error(styleText('cyan', ' npm install @kubb/adapter-oas'))\n console.error(styleText('cyan', ' # or'))\n console.error(styleText('cyan', ' pnpm install @kubb/adapter-oas'))\n console.error('')\n }\n console.error('❌ Validation failed')\n console.error(toError(error).message)\n\n process.exit(1)\n }\n}\n"],"mappings":";;;;;;;;;;AAgBA,eAAsB,IAAI,EAAE,SAAyC;CACnE,MAAM,SAASA,kBAAAA,SAAS;EAAE,SAAS;EAAY,SAASC,aAAAA,QAAQ,OAAO;CAAE,CAAC;CAE1E,IAAI;EACF,MAAM,EAAE,eAAe,MAAM,OAAO;EAEpC,MAAM,WAAW,CAAC,CAAC,SAAS,OAAO,EAAE,cAAc,KAAK,CAAC;EACzD,MAAM,OAAO,EAAE,QAAQ,UAAU,CAAC;EAElC,QAAQ,IAAI,sBAAsB;CACpC,SAAS,OAAO;EACd,MAAM,OAAO,EAAE,QAAQ,SAAS,CAAC;EACjC,IAAI,iBAAiB,SAAS,qBAAqB,KAAK,MAAM,OAAO,GAAG;GACtE,QAAQ,OAAA,GAAMC,UAAAA,UAAAA,CAAU,OAAO,iDAAiD,CAAC;GACjF,QAAQ,MAAM,EAAE;GAChB,QAAQ,MAAM,kBAAkB;GAChC,QAAQ,OAAA,GAAMA,UAAAA,UAAAA,CAAU,QAAQ,iCAAiC,CAAC;GAClE,QAAQ,OAAA,GAAMA,UAAAA,UAAAA,CAAU,QAAQ,QAAQ,CAAC;GACzC,QAAQ,OAAA,GAAMA,UAAAA,UAAAA,CAAU,QAAQ,kCAAkC,CAAC;GACnE,QAAQ,MAAM,EAAE;EAClB;EACA,QAAQ,MAAM,qBAAqB;EACnC,QAAQ,MAAMC,kBAAAA,QAAQ,KAAK,CAAC,CAAC,OAAO;EAEpC,aAAA,QAAQ,KAAK,CAAC;CAChB;AACF"}
@@ -0,0 +1,345 @@
1
+ const require_rolldown_runtime = require("./rolldown-runtime-C0BPl7ul.cjs");
2
+ const require_Telemetry = require("./Telemetry-CH2kkxWK.cjs");
3
+ const require_output = require("./output-C5g7AtWH.cjs");
4
+ const require_registry = require("./registry-CIpW2zQc.cjs");
5
+ const require_config = require("./config-OL_izsmp.cjs");
6
+ let node_util = require("node:util");
7
+ let node_process = require("node:process");
8
+ node_process = require_rolldown_runtime.__toESM(node_process, 1);
9
+ let node_path = require("node:path");
10
+ node_path = require_rolldown_runtime.__toESM(node_path, 1);
11
+ let _kubb_core = require("@kubb/core");
12
+ //#region src/runners/generate/utils.ts
13
+ /** Glob pattern for paths the file watcher ignores. */
14
+ const WATCHER_IGNORED_PATHS = "**/{.git,node_modules}/**";
15
+ /**
16
+ * Quiet window in milliseconds that collapses a burst of watcher events (an editor save emits several) into one rebuild.
17
+ * It outlasts chokidar's 100 ms atomic-save window, which holds back the event of a write-then-rename save.
18
+ */
19
+ const WATCHER_DEBOUNCE_MS = 250;
20
+ /** Interval in milliseconds between polls of a remote `input` URL in watch mode, which emits no filesystem events. */
21
+ const URL_WATCHER_INTERVAL_MS = 2e3;
22
+ /** Upper bound in milliseconds for one URL watcher request, headers and body read, so a hung server never stalls polling. */
23
+ const URL_WATCHER_TIMEOUT_MS = 1e4;
24
+ /**
25
+ * Wraps `run` so invocations never overlap: a trigger that lands while a run is in flight
26
+ * marks it dirty and runs once more after it finishes, no matter how many triggers arrived.
27
+ * Useful for event-driven reruns (a file watcher, a queue drain) where bursts should
28
+ * coalesce into a single trailing run.
29
+ *
30
+ * @example
31
+ * ```ts
32
+ * const rebuild = createSerialRunner({
33
+ * run: () => build(),
34
+ * onError: (error) => log.error(error.message),
35
+ * })
36
+ * watcher.on('change', () => void rebuild())
37
+ * ```
38
+ */
39
+ function createSerialRunner({ run, onError }) {
40
+ let running = false;
41
+ let dirty = false;
42
+ return async () => {
43
+ if (running) {
44
+ dirty = true;
45
+ return;
46
+ }
47
+ running = true;
48
+ do {
49
+ dirty = false;
50
+ try {
51
+ await run();
52
+ } catch (error) {
53
+ onError(require_Telemetry.toError(error));
54
+ }
55
+ } while (dirty);
56
+ running = false;
57
+ };
58
+ }
59
+ /**
60
+ * Starts a file watcher on the given paths and calls `cb` on any change.
61
+ * Ignores `.git` and `node_modules` directories. Event bursts (an editor save emits several)
62
+ * are debounced into one build, and builds never overlap: changes during a build queue exactly
63
+ * one rebuild. Resolves to a function that stops watching.
64
+ */
65
+ async function startWatcher(path, cb, log = {
66
+ info: console.log,
67
+ error: console.log
68
+ }) {
69
+ const { watch } = await import("chokidar");
70
+ const watcher = watch(path, {
71
+ ignorePermissionErrors: true,
72
+ ignored: WATCHER_IGNORED_PATHS,
73
+ ignoreInitial: true
74
+ });
75
+ node_process.default.once("SIGINT", () => {
76
+ watcher.close();
77
+ });
78
+ node_process.default.once("SIGTERM", () => {
79
+ watcher.close();
80
+ });
81
+ const runBuild = createSerialRunner({
82
+ run: () => cb(path),
83
+ onError: () => log.error((0, node_util.styleText)("red", "Watcher failed"))
84
+ });
85
+ let debounceTimer = null;
86
+ watcher.on("all", (type, file) => {
87
+ log.info((0, node_util.styleText)("yellow", (0, node_util.styleText)("bold", `Change detected: ${type} ${file}`)));
88
+ if (debounceTimer) clearTimeout(debounceTimer);
89
+ debounceTimer = setTimeout(() => {
90
+ debounceTimer = null;
91
+ runBuild();
92
+ }, WATCHER_DEBOUNCE_MS);
93
+ });
94
+ return async () => {
95
+ if (debounceTimer) clearTimeout(debounceTimer);
96
+ await watcher.close();
97
+ };
98
+ }
99
+ /**
100
+ * Fetches the body of a remote spec URL, `undefined` when the server does not answer with a
101
+ * readable 2xx body before `signal` aborts. The caller seeds `startUrlWatcher` with the result, so
102
+ * the watcher compares polls against the content the initial build ran on.
103
+ */
104
+ async function fetchUrlBody(url, signal = AbortSignal.timeout(URL_WATCHER_TIMEOUT_MS)) {
105
+ try {
106
+ const response = await fetch(url, { signal });
107
+ if (!response.ok) return void 0;
108
+ return await response.text();
109
+ } catch {
110
+ return;
111
+ }
112
+ }
113
+ /**
114
+ * Polls a remote spec URL and calls `cb` whenever the response body changes. A remote document
115
+ * emits no filesystem events, so this is the URL counterpart of `startWatcher`.
116
+ *
117
+ * `initialBody` seeds the change detection, so an edit landing between the initial build and the
118
+ * first poll still rebuilds. An unreachable server (the API restarting between saves) is reported
119
+ * once per outage and polling continues; after it recovers, a rebuild happens only when the body
120
+ * actually differs from the last one seen, so a plain restart with an unchanged spec stays quiet.
121
+ * Each request is aborted after `timeoutMs`, so a hung response delays at most one poll.
122
+ *
123
+ * Returns a function that stops polling and aborts the in-flight request, so callers (and tests)
124
+ * can shut the watcher down without signaling the process.
125
+ */
126
+ function startUrlWatcher(url, cb, options = {}) {
127
+ const { log = {
128
+ info: console.log,
129
+ error: console.log
130
+ }, intervalMs = URL_WATCHER_INTERVAL_MS, timeoutMs = URL_WATCHER_TIMEOUT_MS, initialBody } = options;
131
+ let lastBody = initialBody;
132
+ let offline = false;
133
+ let timer = null;
134
+ let controller = null;
135
+ let stopped = false;
136
+ const stop = () => {
137
+ stopped = true;
138
+ if (timer) clearTimeout(timer);
139
+ controller?.abort();
140
+ };
141
+ node_process.default.once("SIGINT", stop);
142
+ node_process.default.once("SIGTERM", stop);
143
+ const runBuild = createSerialRunner({
144
+ run: () => cb([url]),
145
+ onError: () => log.error((0, node_util.styleText)("red", "Watcher failed"))
146
+ });
147
+ const schedule = () => {
148
+ if (!stopped) timer = setTimeout(() => void poll(), intervalMs);
149
+ };
150
+ const poll = async () => {
151
+ controller = new AbortController();
152
+ const body = await fetchUrlBody(url, AbortSignal.any([controller.signal, AbortSignal.timeout(timeoutMs)]));
153
+ if (body === void 0) {
154
+ if (!offline && !stopped) {
155
+ offline = true;
156
+ log.error((0, node_util.styleText)("red", `Cannot reach ${url}, polling until it responds again`));
157
+ }
158
+ schedule();
159
+ return;
160
+ }
161
+ if (offline) {
162
+ offline = false;
163
+ log.info((0, node_util.styleText)("yellow", `${url} is reachable again`));
164
+ }
165
+ const changed = lastBody !== void 0 && body !== lastBody;
166
+ if (changed) log.info((0, node_util.styleText)("yellow", (0, node_util.styleText)("bold", `Change detected: ${url}`)));
167
+ if (changed || lastBody === void 0) runBuild();
168
+ lastBody = body;
169
+ schedule();
170
+ };
171
+ poll();
172
+ return stop;
173
+ }
174
+ //#endregion
175
+ //#region src/runners/generate/run.ts
176
+ /** NPM registry endpoint used to check for @kubb/cli updates. */
177
+ const KUBB_NPM_PACKAGE_URL = "https://registry.npmjs.org/@kubb/cli/latest";
178
+ /** Upper bound in milliseconds for the npm update check, so a slow registry never stalls a run. */
179
+ const UPDATE_CHECK_TIMEOUT_MS = 3e3;
180
+ async function generate(options) {
181
+ const { input, hooks, dryRun = false } = options;
182
+ const report = require_Telemetry.trackRun({
183
+ command: "generate",
184
+ hrStart: node_process.default.hrtime()
185
+ });
186
+ const config = {
187
+ ...options.config,
188
+ input: input ?? options.config.input,
189
+ storage: dryRun ? (0, _kubb_core.memoryStorage)() : options.config.storage,
190
+ output: dryRun ? {
191
+ ...options.config.output,
192
+ format: false,
193
+ lint: false,
194
+ postGenerate: []
195
+ } : options.config.output
196
+ };
197
+ const kubb = (0, _kubb_core.createKubb)(config, { hooks });
198
+ const result = await kubb.generate();
199
+ if (dryRun) await hooks.callHook("kubb:info", {
200
+ message: "Dry run: no files were written",
201
+ info: `${result.files.length} file(s) would be generated`
202
+ });
203
+ await report({
204
+ plugins: kubb.config.plugins.flatMap((p) => p && typeof p === "object" ? [{
205
+ name: p.meta?.name ?? p.name ?? "",
206
+ options: p.options ?? {}
207
+ }] : []),
208
+ filesCreated: result.files.length,
209
+ status: result.success ? "success" : "failed"
210
+ });
211
+ return result.success;
212
+ }
213
+ async function checkForUpdate(hooks) {
214
+ try {
215
+ const data = await (await fetch(KUBB_NPM_PACKAGE_URL, { signal: AbortSignal.timeout(UPDATE_CHECK_TIMEOUT_MS) })).json();
216
+ if (data.version && require_registry.isOutdated({
217
+ installed: require_Telemetry.version,
218
+ latest: data.version
219
+ })) await _kubb_core.Diagnostics.emit(hooks, _kubb_core.Diagnostics.update({
220
+ currentVersion: require_Telemetry.version,
221
+ latestVersion: data.version
222
+ }));
223
+ } catch {}
224
+ }
225
+ /**
226
+ * Runs the full Kubb generation lifecycle for the given CLI options.
227
+ * Loads configs, sets up the reporters (CLI `--reporter` picks which of `config.reporters` to trigger),
228
+ * checks for a newer version, and calls `generate` for each config entry.
229
+ */
230
+ async function run({ input, configPath, logLevel: logLevelKey, watch, reporters: cliReporters, dryRun }) {
231
+ const logLevel = _kubb_core.logLevel[logLevelKey] ?? _kubb_core.logLevel.info;
232
+ const hooks = new _kubb_core.Hookable();
233
+ const requestedNames = cliReporters?.length ? cliReporters : ["cli"];
234
+ const json = requestedNames.includes("json");
235
+ const quiet = logLevel <= _kubb_core.logLevel.silent || json;
236
+ const errorHooks = json ? new _kubb_core.Hookable() : hooks;
237
+ if (json) require_config.setupReporters(errorHooks, {
238
+ logLevel,
239
+ reporters: [_kubb_core.cliReporter],
240
+ logger: require_output.createPlainLogger(console.error)
241
+ });
242
+ if (!quiet) {
243
+ require_output.logBanner(require_Telemetry.version);
244
+ require_output.logIntro({ title: "Configuration" });
245
+ }
246
+ const configSpinner = require_output.createSpinner();
247
+ let configs;
248
+ let resolvedConfigPath;
249
+ try {
250
+ if (!quiet) configSpinner.start("Loading config");
251
+ const loaded = await require_config.getConfigs({
252
+ configPath,
253
+ input,
254
+ watch,
255
+ logLevel: logLevelKey
256
+ });
257
+ configs = loaded.configs;
258
+ resolvedConfigPath = loaded.configPath;
259
+ if (!quiet) configSpinner.stop(`Loaded ${(0, node_util.styleText)("dim", node_path.default.relative(node_process.default.cwd(), resolvedConfigPath))}`);
260
+ } catch (error) {
261
+ if (!quiet) configSpinner.error("Config failed loading");
262
+ if (!json) require_config.setupReporters(hooks, {
263
+ logLevel,
264
+ reporters: [_kubb_core.cliReporter]
265
+ });
266
+ await _kubb_core.Diagnostics.emit(errorHooks, error);
267
+ if (!quiet) require_output.logOutro((0, node_util.styleText)("red", "✗ Configuration failed"));
268
+ node_process.default.exit(1);
269
+ }
270
+ const available = configs[0]?.reporters?.length ? configs[0].reporters : [
271
+ _kubb_core.cliReporter,
272
+ _kubb_core.jsonReporter,
273
+ _kubb_core.fileReporter,
274
+ _kubb_core.htmlReporter
275
+ ];
276
+ const reporters = require_config.selectReporters(available, requestedNames);
277
+ require_config.setupReporters(hooks, {
278
+ logLevel,
279
+ reporters
280
+ });
281
+ await hooks.callHook("kubb:lifecycle:start", { version: require_Telemetry.version });
282
+ await checkForUpdate(hooks);
283
+ if (!quiet) require_output.logOutro(`${require_output.pluralize(configs.length, "config")} ready`);
284
+ try {
285
+ let anyFailed = false;
286
+ for (const config of configs) {
287
+ const effectiveInput = input ?? config.input;
288
+ const inputKind = typeof effectiveInput === "string" ? (0, _kubb_core.getInputKind)(effectiveInput) : void 0;
289
+ const watchPath = inputKind === "file" || inputKind === "url" ? effectiveInput : void 0;
290
+ if (watchPath && watch) {
291
+ const watchedPaths = [watchPath];
292
+ const build = async (paths) => {
293
+ const succeeded = await generate({
294
+ input,
295
+ config,
296
+ hooks,
297
+ dryRun
298
+ });
299
+ require_output.logStep((0, node_util.styleText)("yellow", `Watching for changes in ${paths.join(" and ")}`));
300
+ if (succeeded) {
301
+ require_output.logSpacer();
302
+ require_output.logTip();
303
+ }
304
+ };
305
+ const initialBody = inputKind === "url" ? await fetchUrlBody(watchPath) : void 0;
306
+ try {
307
+ await build(watchedPaths);
308
+ } catch (buildError) {
309
+ await _kubb_core.Diagnostics.emit(errorHooks, buildError);
310
+ }
311
+ if (inputKind === "url") startUrlWatcher(watchPath, build, {
312
+ log: {
313
+ info: require_output.logInfo,
314
+ error: require_output.logError
315
+ },
316
+ initialBody
317
+ });
318
+ else await startWatcher(watchedPaths, build, {
319
+ info: require_output.logInfo,
320
+ error: require_output.logError
321
+ });
322
+ } else try {
323
+ if (!await generate({
324
+ input,
325
+ config,
326
+ hooks,
327
+ dryRun
328
+ })) anyFailed = true;
329
+ } catch (configError) {
330
+ await _kubb_core.Diagnostics.emit(errorHooks, configError);
331
+ anyFailed = true;
332
+ }
333
+ }
334
+ await hooks.callHook("kubb:lifecycle:end");
335
+ if (!quiet && !watch && !anyFailed) require_output.logTip();
336
+ if (anyFailed) node_process.default.exit(1);
337
+ } catch (error) {
338
+ await _kubb_core.Diagnostics.emit(errorHooks, error);
339
+ node_process.default.exit(1);
340
+ }
341
+ }
342
+ //#endregion
343
+ exports.run = run;
344
+
345
+ //# sourceMappingURL=run-hgSZImuK.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"run-hgSZImuK.cjs","names":["toError","styleText","trackRun","process","memoryStorage","createKubb","isOutdated","version","Diagnostics","logLevelMap","Hookable","cliReporter","createPlainLogger","createSpinner","getConfigs","styleText","path","jsonReporter","fileReporter","htmlReporter","selectReporters","pluralize","getInputKind","logInfo","logError"],"sources":["../src/runners/generate/utils.ts","../src/runners/generate/run.ts"],"sourcesContent":["import process from 'node:process'\nimport { styleText } from 'node:util'\nimport { toError } from '@internals/utils'\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/** Interval in milliseconds between polls of a remote `input` URL in watch mode, which emits no filesystem events. */\nconst URL_WATCHER_INTERVAL_MS = 2_000\n\n/** Upper bound in milliseconds for one URL watcher request, headers and body read, so a hung server never stalls polling. */\nconst URL_WATCHER_TIMEOUT_MS = 10_000\n\ntype SerialRunnerOptions = {\n /**\n * The async work to serialize.\n */\n run(): Promise<void>\n /**\n * Receives errors thrown by `run`, so a failure never rejects the returned trigger.\n */\n onError(error: Error): void\n}\n\n/**\n * Wraps `run` so invocations never overlap: a trigger that lands while a run is in flight\n * marks it dirty and runs once more after it finishes, no matter how many triggers arrived.\n * Useful for event-driven reruns (a file watcher, a queue drain) where bursts should\n * coalesce into a single trailing run.\n *\n * @example\n * ```ts\n * const rebuild = createSerialRunner({\n * run: () => build(),\n * onError: (error) => log.error(error.message),\n * })\n * watcher.on('change', () => void rebuild())\n * ```\n */\nexport function createSerialRunner({ run, onError }: SerialRunnerOptions): () => Promise<void> {\n let running = false\n let dirty = false\n\n return async (): Promise<void> => {\n if (running) {\n dirty = true\n return\n }\n running = true\n do {\n dirty = false\n try {\n await run()\n } catch (error) {\n onError(toError(error))\n }\n } while (dirty)\n running = false\n }\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 build, and builds never overlap: changes during a build queue exactly\n * one rebuild. 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 process.once('SIGINT', () => {\n watcher.close()\n })\n process.once('SIGTERM', () => {\n watcher.close()\n })\n\n // Bursts never overlap builds on the shared hooks emitter: a change during a build\n // queues exactly one rerun.\n const runBuild = createSerialRunner({\n run: () => cb(path),\n onError: () => log.error(styleText('red', 'Watcher failed')),\n })\n let debounceTimer: ReturnType<typeof setTimeout> | null = null\n\n watcher.on('all', (type, file) => {\n log.info(styleText('yellow', styleText('bold', `Change detected: ${type} ${file}`)))\n if (debounceTimer) clearTimeout(debounceTimer)\n debounceTimer = setTimeout(() => {\n debounceTimer = null\n void runBuild()\n }, WATCHER_DEBOUNCE_MS)\n })\n\n return async () => {\n if (debounceTimer) clearTimeout(debounceTimer)\n await watcher.close()\n }\n}\n\n/**\n * Fetches the body of a remote spec URL, `undefined` when the server does not answer with a\n * readable 2xx body before `signal` aborts. The caller seeds `startUrlWatcher` with the result, so\n * the watcher compares polls against the content the initial build ran on.\n */\nexport async function fetchUrlBody(url: string, signal: AbortSignal = AbortSignal.timeout(URL_WATCHER_TIMEOUT_MS)): Promise<string | undefined> {\n try {\n const response = await fetch(url, { signal })\n if (!response.ok) return undefined\n return await response.text()\n } catch {\n return undefined\n }\n}\n\ntype UrlWatcherOptions = {\n /**\n * Sink for watcher messages, `console.log` by default.\n */\n log?: WatcherLog\n /**\n * Time in milliseconds between polls.\n */\n intervalMs?: number\n /**\n * Upper bound in milliseconds for one poll request, covering headers and body read.\n */\n timeoutMs?: number\n /**\n * Body the initial build ran against, the baseline for change detection. When omitted (the\n * server was unreachable at startup), the first successful poll rebuilds so the output catches\n * up as soon as the server responds.\n */\n initialBody?: string\n}\n\n/**\n * Polls a remote spec URL and calls `cb` whenever the response body changes. A remote document\n * emits no filesystem events, so this is the URL counterpart of `startWatcher`.\n *\n * `initialBody` seeds the change detection, so an edit landing between the initial build and the\n * first poll still rebuilds. An unreachable server (the API restarting between saves) is reported\n * once per outage and polling continues; after it recovers, a rebuild happens only when the body\n * actually differs from the last one seen, so a plain restart with an unchanged spec stays quiet.\n * Each request is aborted after `timeoutMs`, so a hung response delays at most one poll.\n *\n * Returns a function that stops polling and aborts the in-flight request, so callers (and tests)\n * can shut the watcher down without signaling the process.\n */\nexport function startUrlWatcher(url: string, cb: (path: Array<string>) => Promise<void>, options: UrlWatcherOptions = {}): () => void {\n const { log = { info: console.log, error: console.log }, intervalMs = URL_WATCHER_INTERVAL_MS, timeoutMs = URL_WATCHER_TIMEOUT_MS, initialBody } = options\n\n let lastBody = initialBody\n let offline = false\n let timer: ReturnType<typeof setTimeout> | null = null\n let controller: AbortController | null = null\n let stopped = false\n\n const stop = () => {\n stopped = true\n if (timer) clearTimeout(timer)\n controller?.abort()\n }\n process.once('SIGINT', stop)\n process.once('SIGTERM', stop)\n\n // Builds never overlap on the shared hooks emitter: a change during a build queues exactly\n // one rerun.\n const runBuild = createSerialRunner({\n run: () => cb([url]),\n onError: () => log.error(styleText('red', 'Watcher failed')),\n })\n\n const schedule = () => {\n if (!stopped) {\n timer = setTimeout(() => void poll(), intervalMs)\n }\n }\n\n const poll = async (): Promise<void> => {\n controller = new AbortController()\n // The signal also aborts the body read, so a response that stalls mid-stream still times out.\n const body = await fetchUrlBody(url, AbortSignal.any([controller.signal, AbortSignal.timeout(timeoutMs)]))\n\n if (body === undefined) {\n // `lastBody` survives the outage so recovery rebuilds only on real content changes.\n if (!offline && !stopped) {\n offline = true\n log.error(styleText('red', `Cannot reach ${url}, polling until it responds again`))\n }\n schedule()\n return\n }\n\n if (offline) {\n offline = false\n log.info(styleText('yellow', `${url} is reachable again`))\n }\n const changed = lastBody !== undefined && body !== lastBody\n if (changed) {\n log.info(styleText('yellow', styleText('bold', `Change detected: ${url}`)))\n }\n if (changed || lastBody === undefined) {\n void runBuild()\n }\n lastBody = body\n schedule()\n }\n\n void poll()\n\n return stop\n}\n","import path from 'node:path'\nimport process from 'node:process'\nimport { styleText } from 'node:util'\nimport { formatters, 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 '../../loggers/createLogger.ts'\nimport setupReporters, { selectReporters } from '../../loggers/reporters.ts'\nimport { createPlainLogger } from '../../loggers/plainLogger.ts'\nimport { createSpinner, logBanner, logError, logInfo, logIntro, logOutro, logSpacer, logStep, logTip } from '../../loggers/output.ts'\nimport { getConfigs } from '../../config.ts'\nimport { isOutdated } from '../../utils/registry.ts'\nimport { fetchUrlBody, startUrlWatcher, startWatcher } 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, and skips formatting, linting,\n * and post-generate commands.\n */\n dryRun?: boolean\n}\n\nasync 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 if (dryRun) {\n await hooks.callHook('kubb:info', { message: 'Dry run: no files were written', info: `${result.files.length} file(s) would be generated` })\n }\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\nasync function checkForUpdate(hooks: Hookable<KubbHooks>): Promise<void> {\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 if (data.version && isOutdated({ installed: version, latest: data.version })) {\n await Diagnostics.emit(hooks, Diagnostics.update({ currentVersion: version, latestVersion: data.version }))\n }\n } catch {\n // Ignore network errors\n }\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 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], logger: createPlainLogger(console.error) })\n\n if (!quiet) {\n logBanner(version)\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 getConfigs({\n configPath,\n input,\n watch,\n logLevel: logLevelKey as CLIOptions['logLevel'],\n })\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 })\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)\n\n if (!quiet) logOutro(`${pluralize(configs.length, 'config')} ready`)\n\n try {\n let anyFailed = false\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 && watch) {\n const watchedPaths = [watchPath]\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 (paths: Array<string>) => {\n const succeeded = await generate({ input, config, hooks, dryRun })\n logStep(styleText('yellow', `Watching for changes in ${paths.join(' and ')}`))\n if (succeeded) {\n logSpacer()\n logTip()\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 try {\n await build(watchedPaths)\n } catch (buildError) {\n await Diagnostics.emit(errorHooks, buildError)\n }\n\n if (inputKind === 'url') {\n startUrlWatcher(watchPath, build, { log: { info: logInfo, error: logError }, initialBody })\n } else {\n await startWatcher(watchedPaths, build, { 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":";;;;;;;;;;;;;AAKA,MAAM,wBAAwB;;;;;AAM9B,MAAM,sBAAsB;;AAG5B,MAAM,0BAA0B;;AAGhC,MAAM,yBAAyB;;;;;;;;;;;;;;;;AA4B/B,SAAgB,mBAAmB,EAAE,KAAK,WAAqD;CAC7F,IAAI,UAAU;CACd,IAAI,QAAQ;CAEZ,OAAO,YAA2B;EAChC,IAAI,SAAS;GACX,QAAQ;GACR;EACF;EACA,UAAU;EACV,GAAG;GACD,QAAQ;GACR,IAAI;IACF,MAAM,IAAI;GACZ,SAAS,OAAO;IACd,QAAQA,kBAAAA,QAAQ,KAAK,CAAC;GACxB;EACF,SAAS;EACT,UAAU;CACZ;AACF;;;;;;;AAaA,eAAsB,aACpB,MACA,IACA,MAAkB;CAAE,MAAM,QAAQ;CAAK,OAAO,QAAQ;AAAI,GAC5B;CAC9B,MAAM,EAAE,UAAU,MAAM,OAAO;CAG/B,MAAM,UAAU,MAAM,MAAM;EAAE,wBAAwB;EAAM,SAAS;EAAuB,eAAe;CAAK,CAAC;CAEjH,aAAA,QAAQ,KAAK,gBAAgB;EAC3B,QAAQ,MAAM;CAChB,CAAC;CACD,aAAA,QAAQ,KAAK,iBAAiB;EAC5B,QAAQ,MAAM;CAChB,CAAC;CAID,MAAM,WAAW,mBAAmB;EAClC,WAAW,GAAG,IAAI;EAClB,eAAe,IAAI,OAAA,GAAMC,UAAAA,UAAAA,CAAU,OAAO,gBAAgB,CAAC;CAC7D,CAAC;CACD,IAAI,gBAAsD;CAE1D,QAAQ,GAAG,QAAQ,MAAM,SAAS;EAChC,IAAI,MAAA,GAAKA,UAAAA,UAAAA,CAAU,WAAA,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