@kubb/cli 5.21.0 → 5.21.1
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-BhTLEYwh.js → Telemetry-B8HIo9K9.js} +2 -2
- package/dist/{Telemetry-BhTLEYwh.js.map → Telemetry-B8HIo9K9.js.map} +1 -1
- package/dist/{Telemetry-JW5aPuIg.cjs → Telemetry-CFa6j6jh.cjs} +2 -2
- package/dist/{Telemetry-JW5aPuIg.cjs.map → Telemetry-CFa6j6jh.cjs.map} +1 -1
- package/dist/{background-BiY18dWr.js → background-B13TMGFC.js} +2 -2
- package/dist/{background-BiY18dWr.js.map → background-B13TMGFC.js.map} +1 -1
- package/dist/{background-ClORtnNm.cjs → background-B7UFmDDf.cjs} +2 -2
- package/dist/{background-ClORtnNm.cjs.map → background-B7UFmDDf.cjs.map} +1 -1
- package/dist/{background-N-_UTHNT.js → background-VU2BSEnH.js} +1 -1
- package/dist/index.cjs +9 -9
- package/dist/index.js +9 -9
- package/dist/{mcp-ue2vjz2J.js → mcp-CYV5okVO.js} +2 -2
- package/dist/{mcp-ue2vjz2J.js.map → mcp-CYV5okVO.js.map} +1 -1
- package/dist/{mcp-7JMboUx2.cjs → mcp-DSpviI8q.cjs} +2 -2
- package/dist/{mcp-7JMboUx2.cjs.map → mcp-DSpviI8q.cjs.map} +1 -1
- package/dist/{package-Bxc60RcQ.cjs → package-BugC4svC.cjs} +2 -2
- package/dist/package-BugC4svC.cjs.map +1 -0
- package/dist/package-YxLU4Yha.js +5 -0
- package/dist/package-YxLU4Yha.js.map +1 -0
- package/dist/{run-h-R9yKUi.cjs → run-70QKFTKm.cjs} +3 -3
- package/dist/{run-h-R9yKUi.cjs.map → run-70QKFTKm.cjs.map} +1 -1
- package/dist/{run-DvQUP5ea.js → run-B18jS3z1.js} +2 -2
- package/dist/{run-DvQUP5ea.js.map → run-B18jS3z1.js.map} +1 -1
- package/dist/{run-C994a4Y5.cjs → run-BW6US_E0.cjs} +2 -2
- package/dist/{run-C994a4Y5.cjs.map → run-BW6US_E0.cjs.map} +1 -1
- package/dist/{run-Cb1lJjC_.js → run-Bow_ntPo.js} +1 -1
- package/dist/{run-BGrgzLo2.cjs → run-C4cU9oxc.cjs} +2 -2
- package/dist/{run-BGrgzLo2.cjs.map → run-C4cU9oxc.cjs.map} +1 -1
- package/dist/{run-CUQ0GuHO.js → run-C70KILiO.js} +2 -2
- package/dist/{run-CUQ0GuHO.js.map → run-C70KILiO.js.map} +1 -1
- package/dist/{run-Nh3NdjRM.cjs → run-C9PwQp2D.cjs} +2 -2
- package/dist/{run-Nh3NdjRM.cjs.map → run-C9PwQp2D.cjs.map} +1 -1
- package/dist/{run-CE4pXu0n.js → run-CGEX3q1b.js} +2 -2
- package/dist/{run-CE4pXu0n.js.map → run-CGEX3q1b.js.map} +1 -1
- package/dist/{run-Bl3rprW8.js → run-Cdp4qf86.js} +3 -3
- package/dist/{run-Bl3rprW8.js.map → run-Cdp4qf86.js.map} +1 -1
- package/dist/{run-DMZvyW7F.js → run-CpPnINxG.js} +5 -5
- package/dist/{run-DMZvyW7F.js.map → run-CpPnINxG.js.map} +1 -1
- package/dist/{run-D07CFyBy.cjs → run-Dh4ZvkS2.cjs} +5 -5
- package/dist/{run-D07CFyBy.cjs.map → run-Dh4ZvkS2.cjs.map} +1 -1
- package/dist/{run-D3lgs00n.cjs → run-DtNj6omd.cjs} +2 -2
- package/dist/{run-D3lgs00n.cjs.map → run-DtNj6omd.cjs.map} +1 -1
- package/dist/{run-C3J0YrXl.js → run-Eu4KPHj1.js} +2 -2
- package/dist/{run-C3J0YrXl.js.map → run-Eu4KPHj1.js.map} +1 -1
- package/dist/{snapshot-C6c3fg6g.js → snapshot-CQScqGuz.js} +2 -2
- package/dist/{snapshot-C6c3fg6g.js.map → snapshot-CQScqGuz.js.map} +1 -1
- package/dist/{snapshot-DIU2jDHY.cjs → snapshot-DhsME8tB.cjs} +2 -2
- package/dist/{snapshot-DIU2jDHY.cjs.map → snapshot-DhsME8tB.cjs.map} +1 -1
- package/dist/{status-DwTnX_1X.js → status-BxRdsdtL.js} +2 -2
- package/dist/{status-DwTnX_1X.js.map → status-BxRdsdtL.js.map} +1 -1
- package/dist/{status-C1M8ggsY.cjs → status-D2bLvqWJ.cjs} +2 -2
- package/dist/{status-C1M8ggsY.cjs.map → status-D2bLvqWJ.cjs.map} +1 -1
- package/dist/{studio-NeCXG9kR.cjs → studio-BAnzHeK9.cjs} +11 -11
- package/dist/{studio-NeCXG9kR.cjs.map → studio-BAnzHeK9.cjs.map} +1 -1
- package/dist/{studio-DtSk5Z-c.js → studio-Cncg3dtw.js} +11 -11
- package/dist/{studio-DtSk5Z-c.js.map → studio-Cncg3dtw.js.map} +1 -1
- package/dist/studioWorker.js +2 -2
- package/dist/{validate-DFRXoUyQ.cjs → validate-Bkk7Fvy_.cjs} +2 -2
- package/dist/{validate-DFRXoUyQ.cjs.map → validate-Bkk7Fvy_.cjs.map} +1 -1
- package/dist/{validate-jfKFC1n1.js → validate-CTSD0rYL.js} +2 -2
- package/dist/{validate-jfKFC1n1.js.map → validate-CTSD0rYL.js.map} +1 -1
- package/package.json +7 -7
- package/dist/package-BoMS1AZ6.js +0 -5
- package/dist/package-BoMS1AZ6.js.map +0 -1
- package/dist/package-Bxc60RcQ.cjs.map +0 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"run-h-R9yKUi.cjs","names":["isValid","isCIEnvironment","kubbStorage","memoryStorage","process","trackRun","Kubb","Diagnostics","delay","isOutdated","version","styleText","pluralize","logStep","formatMs","getInputKind","logWarn","path","trackBuild","diffBuilds","getElapsedMs","logSpacer","logTip","listenForKeys","startWatcher","logInfo","logError","logLevelMap","Hookable","setupReporters","cliReporter","createPlainWriter","logBanner","getConfigs","logIntro","createSpinner","logOutro","jsonReporter","fileReporter","htmlReporter","selectReporters"],"sources":["../src/utils/updateCheck.ts","../src/runners/generate/run.ts"],"sourcesContent":["import { isCIEnvironment } from '@internals/utils'\nimport { kubbStorage } from '@kubb/core'\nimport { isValid } from 'verkit'\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/** How long a stored registry answer stays fresh. */\nexport const UPDATE_CHECK_INTERVAL_MS = 24 * 60 * 60 * 1_000\n\nconst STORE_KEY = 'update-check.json'\n\ntype StoredCheck = {\n version: string\n checkedAt: number\n}\n\nfunction isStoredCheck(value: unknown): value is StoredCheck {\n const check = value as Partial<StoredCheck> | null\n return typeof check?.version === 'string' && isValid(check.version) && typeof check.checkedAt === 'number'\n}\n\n// A timestamp in the future, from a clock set back, counts as stale so it cannot hide updates.\nfunction isFresh(checkedAt: number): boolean {\n const age = Date.now() - checkedAt\n return age >= 0 && age < UPDATE_CHECK_INTERVAL_MS\n}\n\n/** The latest published version, `undefined` when the registry does not answer in time or `signal` aborts. Never rejects. */\nasync function fetchLatestVersion(signal: AbortSignal): Promise<string | undefined> {\n try {\n const res = await fetch(KUBB_NPM_PACKAGE_URL, { signal: AbortSignal.any([signal, AbortSignal.timeout(UPDATE_CHECK_TIMEOUT_MS)]) })\n if (!res.ok) return undefined\n const data = (await res.json()) as { version?: unknown }\n return typeof data.version === 'string' && isValid(data.version) ? data.version : undefined\n } catch {\n return undefined\n }\n}\n\n/**\n * The latest published `@kubb/cli` version for the update notice. Skipped in CI. Asks npm at most once per\n * {@link UPDATE_CHECK_INTERVAL_MS} and keeps the answer in `~/.kubb/cache` (or `KUBB_HOME`).\n * Resolves `undefined` when there is nothing to show. Never rejects.\n */\nexport async function getLatestVersion(signal: AbortSignal): Promise<string | undefined> {\n if (isCIEnvironment()) return undefined\n\n const storage = (() => {\n try {\n return kubbStorage({ base: 'cache' })\n } catch {\n return undefined\n }\n })()\n const stored = await storage?.getItem(STORE_KEY).catch(() => null)\n if (isStoredCheck(stored) && isFresh(stored.checkedAt)) return stored.version\n\n const latest = await fetchLatestVersion(signal)\n if (latest) await storage?.setItem(STORE_KEY, { version: latest, checkedAt: Date.now() }).catch(() => undefined)\n return latest\n}\n","import path from 'node:path'\nimport process from 'node:process'\nimport { setTimeout as delay } from 'node:timers/promises'\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 Diagnostics,\n fileReporter,\n getInputKind,\n htmlReporter,\n jsonReporter,\n Kubb,\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, logWarn } 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 { getLatestVersion } from '../../utils/updateCheck.ts'\nimport { type BuildDiff, type BuildSnapshot, diffBuilds, listenForKeys, startWatcher, trackBuild } from './utils.ts'\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\nfunction toRunConfig({ config, input, dryRun }: { config: Config; input?: string; dryRun: boolean }): Config {\n return {\n ...config,\n input: input ?? config.input,\n // Dry-run never touches disk, regardless of the config's own storage driver.\n storage: dryRun ? memoryStorage() : config.storage,\n // Also keeps core's `hasOutputPasses` false, so dry-run skips the output manifest write too.\n output: dryRun ? { ...config.output, format: false, lint: false, postGenerate: [] } : config.output,\n }\n}\n\ntype GenerateProps = {\n configs: Array<Config>\n hooks: Hookable<KubbHooks>\n}\n\n/**\n * Generates the configs and returns whether every build succeeded.\n */\nexport async function generate({ configs, hooks }: GenerateProps): Promise<boolean> {\n // Not awaited: a detached process sends each request, so it never delays the summary or the exit.\n const untrack = hooks.hook('kubb:generation:end', ({ config, filesCreated = 0, status = 'success', hrStart = process.hrtime() }) => {\n void trackRun({ command: 'generate', hrStart })({\n plugins: 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,\n status,\n })\n })\n let succeeded = true\n try {\n for await (const { success, error } of Kubb.generate(configs, { hooks })) {\n if (error) await Diagnostics.emit(hooks, error)\n succeeded &&= success\n }\n } finally {\n untrack()\n }\n return succeeded\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/** Upper bound in milliseconds for the update check's cache read or write once generation is done. */\nconst UPDATE_WAIT_MS = 1_000\n\n/** `promise`'s value, or `undefined` when it takes longer than `ms`. */\nfunction withTimeout<T>({ promise, ms }: { promise: Promise<T>; ms: number }): Promise<T | undefined> {\n const timer = new AbortController()\n const timeout = delay(ms, undefined, { signal: timer.signal }).catch(() => undefined)\n return Promise.race([promise, timeout]).finally(() => timer.abort())\n}\n\nasync function checkForUpdate({ hooks, latestVersion }: { hooks: Hookable<KubbHooks>; latestVersion: string | undefined }): Promise<void> {\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 * Generates the configs, then again whenever a local `input` file changes. Returns whether the build succeeded when there is no file to watch.\n */\nasync function watch({ configs, hooks, quiet }: GenerateProps & { quiet: boolean }): Promise<boolean> {\n const watchPaths = [...new Set(configs.flatMap(({ input }) => (typeof input === 'string' && getInputKind(input) === 'file' ? [input] : [])))]\n if (!watchPaths.length) {\n if (!quiet) logWarn('Watch mode only follows a local `input` file, so the configs are generated once.')\n return generate({ configs, hooks })\n }\n\n const label = styleText('yellow', `Watching ${watchPaths.map((watchPath) => path.relative(process.cwd(), watchPath)).join(', ')}`)\n const tracker = trackBuild(hooks)\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 // Every config builds again, since an edited spec can change what the configs share.\n const succeeded = await generate({ configs, hooks })\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 a build is queued joins it. One that lands during the build queues one more. Never rejects.\n let queue = Promise.resolve()\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(hooks, error))\n return queue\n }\n const armKeys = quiet\n ? undefined\n : listenForKeys({\n rebuild: () => void rebuild(),\n quit: (code) => void Promise.resolve(hooks.callHook('kubb:lifecycle:end')).finally(() => process.exit(code)),\n })\n\n // The watcher ignores its startup state, so run the first build here. A failing one keeps watching so the user can fix the input.\n await rebuild()\n await startWatcher(watchPaths, rebuild, { info: logInfo, error: logError })\n return true\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 * calls `generate` for each config entry, and prints an update notice when a newer version is known.\n */\nexport async function run({\n input,\n configPath,\n logLevel: logLevelKey,\n watch: watchMode,\n reporters: cliReporters,\n dryRun,\n}: GenerateCommandOptions): Promise<void> {\n // Started first: the notice prints at the end only when the stored answer or the registry is there by then.\n const updateCheck = new AbortController()\n const latestVersion = getLatestVersion(updateCheck.signal)\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 // The run log goes to stderr in `json` mode, so an error with no report entry is never silent and stdout stays one JSON document.\n if (json) setupReporters(hooks, { logLevel, reporters: [cliReporter], writer: createPlainWriter(console.error) })\n\n // The config loads while the banner plays. Once it settles the banner jumps to its last frame, so\n // the build starts right away and no frame lands between log lines.\n const bannerCut = new AbortController()\n const banner = quiet ? undefined : logBanner({ version, signal: bannerCut.signal })\n const loading = getConfigs({\n configPath,\n input,\n watch: watchMode,\n logLevel: logLevelKey as CLIOptions['logLevel'],\n reporters: cliReporters,\n })\n // A rejection is handled below; this also keeps it from counting as unhandled during the banner.\n void loading.then(\n () => bannerCut.abort(),\n () => bannerCut.abort(),\n )\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(hooks, 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 const runConfigs = configs.map((config) => toRunConfig({ config, input, dryRun: dryRun ?? false }))\n\n if (!quiet) logOutro(`${pluralize(configs.length, 'config')} ready`)\n\n try {\n // One config that fails does not stop the others.\n const succeeded = await (watchMode ? watch({ configs: runConfigs, hooks, quiet }) : generate({ configs: runConfigs, hooks }))\n\n // Aborting settles a request in flight at once; the timeout covers a cache read or write on a stalled disk.\n updateCheck.abort()\n await checkForUpdate({ hooks, latestVersion: await withTimeout({ promise: latestVersion, ms: UPDATE_WAIT_MS }) })\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 && !watchMode && succeeded) {\n logTip()\n }\n\n // `exitCode`, not `exit()`, so the payload piped to the telemetry process is flushed first.\n if (!succeeded) {\n process.exitCode = 1\n }\n } catch (error) {\n await Diagnostics.emit(hooks, error)\n process.exit(1)\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;AAKA,MAAM,uBAAuB;;AAG7B,MAAM,0BAA0B;AAKhC,MAAM,YAAY;AAOlB,SAAS,cAAc,OAAsC;CAC3D,MAAM,QAAQ;CACd,OAAO,OAAO,OAAO,YAAY,aAAA,GAAYA,OAAAA,QAAAA,CAAQ,MAAM,OAAO,KAAK,OAAO,MAAM,cAAc;AACpG;AAGA,SAAS,QAAQ,WAA4B;CAC3C,MAAM,MAAM,KAAK,IAAI,IAAI;CACzB,OAAO,OAAO,KAAK,MAAA;AACrB;;AAGA,eAAe,mBAAmB,QAAkD;CAClF,IAAI;EACF,MAAM,MAAM,MAAM,MAAM,sBAAsB,EAAE,QAAQ,YAAY,IAAI,CAAC,QAAQ,YAAY,QAAQ,uBAAuB,CAAC,CAAC,EAAE,CAAC;EACjI,IAAI,CAAC,IAAI,IAAI,OAAO,KAAA;EACpB,MAAM,OAAQ,MAAM,IAAI,KAAK;EAC7B,OAAO,OAAO,KAAK,YAAY,aAAA,GAAYA,OAAAA,QAAAA,CAAQ,KAAK,OAAO,IAAI,KAAK,UAAU,KAAA;CACpF,QAAQ;EACN;CACF;AACF;;;;;;AAOA,eAAsB,iBAAiB,QAAkD;CACvF,IAAIC,wBAAAA,gBAAgB,GAAG,OAAO,KAAA;CAE9B,MAAM,iBAAiB;EACrB,IAAI;GACF,QAAA,GAAOC,WAAAA,YAAAA,CAAY,EAAE,MAAM,QAAQ,CAAC;EACtC,QAAQ;GACN;EACF;CACF,EAAA,CAAG;CACH,MAAM,SAAS,MAAM,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,SAAS;GAAY;GAAO;EAAM,CAAC,IAAI,SAAS;GAAE,SAAS;GAAY;EAAM,CAAC;EAG3H,YAAY,MAAM;EAClB,MAAM,eAAe;GAAE;GAAO,eAAe,MAAM,YAAY;IAAE,SAAS;IAAe,IAAI;GAAe,CAAC;EAAE,CAAC;EAEhH,MAAM,MAAM,SAAS,oBAAoB;EAIzC,IAAI,CAAC,SAAS,CAAC,aAAa,WAC1BU,cAAAA,OAAO;EAIT,IAAI,CAAC,WACH,aAAA,QAAA,WAAmB;CAEvB,SAAS,OAAO;EACd,MAAMf,WAAAA,YAAY,KAAK,OAAO,KAAK;EACnCH,aAAAA,QAAQ,KAAK,CAAC;CAChB;AACF"}
|
|
1
|
+
{"version":3,"file":"run-70QKFTKm.cjs","names":["isValid","isCIEnvironment","kubbStorage","memoryStorage","process","trackRun","Kubb","Diagnostics","delay","isOutdated","version","styleText","pluralize","logStep","formatMs","getInputKind","logWarn","path","trackBuild","diffBuilds","getElapsedMs","logSpacer","logTip","listenForKeys","startWatcher","logInfo","logError","logLevelMap","Hookable","setupReporters","cliReporter","createPlainWriter","logBanner","getConfigs","logIntro","createSpinner","logOutro","jsonReporter","fileReporter","htmlReporter","selectReporters"],"sources":["../src/utils/updateCheck.ts","../src/runners/generate/run.ts"],"sourcesContent":["import { isCIEnvironment } from '@internals/utils'\nimport { kubbStorage } from '@kubb/core'\nimport { isValid } from 'verkit'\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/** How long a stored registry answer stays fresh. */\nexport const UPDATE_CHECK_INTERVAL_MS = 24 * 60 * 60 * 1_000\n\nconst STORE_KEY = 'update-check.json'\n\ntype StoredCheck = {\n version: string\n checkedAt: number\n}\n\nfunction isStoredCheck(value: unknown): value is StoredCheck {\n const check = value as Partial<StoredCheck> | null\n return typeof check?.version === 'string' && isValid(check.version) && typeof check.checkedAt === 'number'\n}\n\n// A timestamp in the future, from a clock set back, counts as stale so it cannot hide updates.\nfunction isFresh(checkedAt: number): boolean {\n const age = Date.now() - checkedAt\n return age >= 0 && age < UPDATE_CHECK_INTERVAL_MS\n}\n\n/** The latest published version, `undefined` when the registry does not answer in time or `signal` aborts. Never rejects. */\nasync function fetchLatestVersion(signal: AbortSignal): Promise<string | undefined> {\n try {\n const res = await fetch(KUBB_NPM_PACKAGE_URL, { signal: AbortSignal.any([signal, AbortSignal.timeout(UPDATE_CHECK_TIMEOUT_MS)]) })\n if (!res.ok) return undefined\n const data = (await res.json()) as { version?: unknown }\n return typeof data.version === 'string' && isValid(data.version) ? data.version : undefined\n } catch {\n return undefined\n }\n}\n\n/**\n * The latest published `@kubb/cli` version for the update notice. Skipped in CI. Asks npm at most once per\n * {@link UPDATE_CHECK_INTERVAL_MS} and keeps the answer in `~/.kubb/cache` (or `KUBB_HOME`).\n * Resolves `undefined` when there is nothing to show. Never rejects.\n */\nexport async function getLatestVersion(signal: AbortSignal): Promise<string | undefined> {\n if (isCIEnvironment()) return undefined\n\n const storage = (() => {\n try {\n return kubbStorage({ base: 'cache' })\n } catch {\n return undefined\n }\n })()\n const stored = await storage?.getItem(STORE_KEY).catch(() => null)\n if (isStoredCheck(stored) && isFresh(stored.checkedAt)) return stored.version\n\n const latest = await fetchLatestVersion(signal)\n if (latest) await storage?.setItem(STORE_KEY, { version: latest, checkedAt: Date.now() }).catch(() => undefined)\n return latest\n}\n","import path from 'node:path'\nimport process from 'node:process'\nimport { setTimeout as delay } from 'node:timers/promises'\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 Diagnostics,\n fileReporter,\n getInputKind,\n htmlReporter,\n jsonReporter,\n Kubb,\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, logWarn } 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 { getLatestVersion } from '../../utils/updateCheck.ts'\nimport { type BuildDiff, type BuildSnapshot, diffBuilds, listenForKeys, startWatcher, trackBuild } from './utils.ts'\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\nfunction toRunConfig({ config, input, dryRun }: { config: Config; input?: string; dryRun: boolean }): Config {\n return {\n ...config,\n input: input ?? config.input,\n // Dry-run never touches disk, regardless of the config's own storage driver.\n storage: dryRun ? memoryStorage() : config.storage,\n // Also keeps core's `hasOutputPasses` false, so dry-run skips the output manifest write too.\n output: dryRun ? { ...config.output, format: false, lint: false, postGenerate: [] } : config.output,\n }\n}\n\ntype GenerateProps = {\n configs: Array<Config>\n hooks: Hookable<KubbHooks>\n}\n\n/**\n * Generates the configs and returns whether every build succeeded.\n */\nexport async function generate({ configs, hooks }: GenerateProps): Promise<boolean> {\n // Not awaited: a detached process sends each request, so it never delays the summary or the exit.\n const untrack = hooks.hook('kubb:generation:end', ({ config, filesCreated = 0, status = 'success', hrStart = process.hrtime() }) => {\n void trackRun({ command: 'generate', hrStart })({\n plugins: 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,\n status,\n })\n })\n let succeeded = true\n try {\n for await (const { success, error } of Kubb.generate(configs, { hooks })) {\n if (error) await Diagnostics.emit(hooks, error)\n succeeded &&= success\n }\n } finally {\n untrack()\n }\n return succeeded\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/** Upper bound in milliseconds for the update check's cache read or write once generation is done. */\nconst UPDATE_WAIT_MS = 1_000\n\n/** `promise`'s value, or `undefined` when it takes longer than `ms`. */\nfunction withTimeout<T>({ promise, ms }: { promise: Promise<T>; ms: number }): Promise<T | undefined> {\n const timer = new AbortController()\n const timeout = delay(ms, undefined, { signal: timer.signal }).catch(() => undefined)\n return Promise.race([promise, timeout]).finally(() => timer.abort())\n}\n\nasync function checkForUpdate({ hooks, latestVersion }: { hooks: Hookable<KubbHooks>; latestVersion: string | undefined }): Promise<void> {\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 * Generates the configs, then again whenever a local `input` file changes. Returns whether the build succeeded when there is no file to watch.\n */\nasync function watch({ configs, hooks, quiet }: GenerateProps & { quiet: boolean }): Promise<boolean> {\n const watchPaths = [...new Set(configs.flatMap(({ input }) => (typeof input === 'string' && getInputKind(input) === 'file' ? [input] : [])))]\n if (!watchPaths.length) {\n if (!quiet) logWarn('Watch mode only follows a local `input` file, so the configs are generated once.')\n return generate({ configs, hooks })\n }\n\n const label = styleText('yellow', `Watching ${watchPaths.map((watchPath) => path.relative(process.cwd(), watchPath)).join(', ')}`)\n const tracker = trackBuild(hooks)\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 // Every config builds again, since an edited spec can change what the configs share.\n const succeeded = await generate({ configs, hooks })\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 a build is queued joins it. One that lands during the build queues one more. Never rejects.\n let queue = Promise.resolve()\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(hooks, error))\n return queue\n }\n const armKeys = quiet\n ? undefined\n : listenForKeys({\n rebuild: () => void rebuild(),\n quit: (code) => void Promise.resolve(hooks.callHook('kubb:lifecycle:end')).finally(() => process.exit(code)),\n })\n\n // The watcher ignores its startup state, so run the first build here. A failing one keeps watching so the user can fix the input.\n await rebuild()\n await startWatcher(watchPaths, rebuild, { info: logInfo, error: logError })\n return true\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 * calls `generate` for each config entry, and prints an update notice when a newer version is known.\n */\nexport async function run({\n input,\n configPath,\n logLevel: logLevelKey,\n watch: watchMode,\n reporters: cliReporters,\n dryRun,\n}: GenerateCommandOptions): Promise<void> {\n // Started first: the notice prints at the end only when the stored answer or the registry is there by then.\n const updateCheck = new AbortController()\n const latestVersion = getLatestVersion(updateCheck.signal)\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 // The run log goes to stderr in `json` mode, so an error with no report entry is never silent and stdout stays one JSON document.\n if (json) setupReporters(hooks, { logLevel, reporters: [cliReporter], writer: createPlainWriter(console.error) })\n\n // The config loads while the banner plays. Once it settles the banner jumps to its last frame, so\n // the build starts right away and no frame lands between log lines.\n const bannerCut = new AbortController()\n const banner = quiet ? undefined : logBanner({ version, signal: bannerCut.signal })\n const loading = getConfigs({\n configPath,\n input,\n watch: watchMode,\n logLevel: logLevelKey as CLIOptions['logLevel'],\n reporters: cliReporters,\n })\n // A rejection is handled below; this also keeps it from counting as unhandled during the banner.\n void loading.then(\n () => bannerCut.abort(),\n () => bannerCut.abort(),\n )\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(hooks, 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 const runConfigs = configs.map((config) => toRunConfig({ config, input, dryRun: dryRun ?? false }))\n\n if (!quiet) logOutro(`${pluralize(configs.length, 'config')} ready`)\n\n try {\n // One config that fails does not stop the others.\n const succeeded = await (watchMode ? watch({ configs: runConfigs, hooks, quiet }) : generate({ configs: runConfigs, hooks }))\n\n // Aborting settles a request in flight at once; the timeout covers a cache read or write on a stalled disk.\n updateCheck.abort()\n await checkForUpdate({ hooks, latestVersion: await withTimeout({ promise: latestVersion, ms: UPDATE_WAIT_MS }) })\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 && !watchMode && succeeded) {\n logTip()\n }\n\n // `exitCode`, not `exit()`, so the payload piped to the telemetry process is flushed first.\n if (!succeeded) {\n process.exitCode = 1\n }\n } catch (error) {\n await Diagnostics.emit(hooks, error)\n process.exit(1)\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;AAKA,MAAM,uBAAuB;;AAG7B,MAAM,0BAA0B;AAKhC,MAAM,YAAY;AAOlB,SAAS,cAAc,OAAsC;CAC3D,MAAM,QAAQ;CACd,OAA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CAChB;AACF"}
|
|
@@ -29,7 +29,7 @@ async function regenerate({ cwd, configPath }) {
|
|
|
29
29
|
try {
|
|
30
30
|
const [{ getConfigs }, { generate }, { default: setupReporters }] = await Promise.all([
|
|
31
31
|
import("./config-BKi_vTvh.js"),
|
|
32
|
-
import("./run-
|
|
32
|
+
import("./run-Cdp4qf86.js"),
|
|
33
33
|
import("./reporters-BDzKLpyo.js")
|
|
34
34
|
]);
|
|
35
35
|
const { configs } = await getConfigs({ configPath });
|
|
@@ -231,4 +231,4 @@ const command = defineWithTypes()({
|
|
|
231
231
|
});
|
|
232
232
|
export { command, run };
|
|
233
233
|
|
|
234
|
-
//# sourceMappingURL=run-
|
|
234
|
+
//# sourceMappingURL=run-B18jS3z1.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"run-DvQUP5ea.js","names":["logLevelMap"],"sources":["../src/runners/update/run.ts"],"sourcesContent":["import path from 'node:path'\nimport process from 'node:process'\nimport { styleText } from 'node:util'\nimport * as clack from '@clack/prompts'\nimport { defineWithTypes } from 'gunshi'\nimport { findConfigFile } from '@internals/shared'\nimport { getErrorMessage, pascalCase } from '@internals/utils'\nimport { type GenerationResult, Hookable, type KubbHooks, logLevel as logLevelMap, readInstalledPackages, type RegistryEntry, type Reporter } from '@kubb/core'\nimport { pluralize } from '../../ui/text.ts'\nimport { dryRunId, type DryRunExtensions, yesArg } from '../../commands/shared.ts'\nimport { isInteractiveRun, logIntro } from '../../ui/intro.ts'\nimport { logBlock, logError, logStep, logWarn } from '../../ui/log.ts'\nimport { createSpinner, withSpinner } from '../../ui/spinner.ts'\nimport { createSummary } from '../../ui/summary.ts'\nimport { formatTable } from '../../ui/table.ts'\nimport { bumpOf, fetchRegistryIndex, incompatibility, installSpec, isOutdated, registryUrl, toRegistryId, toShortId } from '../../utils/registry.ts'\nimport { detectPackageManager } from '../init/utils.ts'\nimport { installWithSpinner } from '../installWithSpinner.ts'\n\nexport type UpdateOptions = {\n /**\n * Registry ids to update. Empty updates every installed extension the registry lists.\n */\n ids: Array<string>\n /**\n * List the updates without installing anything.\n */\n dryRun: boolean\n yes: boolean\n}\n\ntype FileChanges = NonNullable<GenerationResult['fileChanges']>\n\n/**\n * Generates every config in this process, the way `kubb generate` does, and returns the counts of\n * output files it changed. Runs after the install, so the config loads the new versions.\n * `undefined` when the config fails to load or a build fails.\n */\nasync function regenerate({ cwd, configPath }: { cwd: string; configPath: string }): Promise<{ changes: FileChanges; output: string } | undefined> {\n const spinner = createSpinner()\n spinner.start('Generating with the new versions')\n try {\n // Imported here, so the config loader and the generate path never slow down `kubb --help`.\n const [{ getConfigs }, { generate }, { default: setupReporters }] = await Promise.all([\n import('../../config.ts'),\n import('../generate/run.ts'),\n import('../../loggers/reporters.ts'),\n ])\n const { configs } = await getConfigs({ configPath })\n const hooks = new Hookable<KubbHooks>()\n const changes: FileChanges = { added: 0, modified: 0, deleted: 0, linesAdded: 0, linesRemoved: 0 }\n const collect: Reporter = {\n name: 'update',\n report: ({ fileChanges }) => {\n for (const key of Object.keys(changes) as Array<keyof FileChanges>) changes[key] += fileChanges?.[key] ?? 0\n },\n }\n setupReporters(hooks, { logLevel: logLevelMap.info, reporters: [collect], fileChanges: true })\n if (!(await generate({ configs, hooks }))) throw new Error('Generation failed')\n const changed = changes.added + changes.modified + changes.deleted\n spinner.stop(changed ? `Generated: ${pluralize(changed, 'file')} changed` : 'Generated: no files changed')\n return { changes, output: configs.map((config) => path.relative(cwd, path.resolve(config.root ?? cwd, config.output.path)) || '.').join(', ') }\n } catch (error) {\n spinner.error(`Generation failed: ${getErrorMessage(error)}`)\n return undefined\n }\n}\n\n/**\n * Moves installed extensions to the version the registry pins. Shows each version change with its\n * bump, asks which to install with majors left out, installs them, and regenerates to show which\n * files changed. With `dryRun`, only lists the updates and installs nothing.\n */\nexport async function run({ ids, dryRun, yes }: UpdateOptions): Promise<void> {\n const cwd = process.cwd()\n const hrStart = process.hrtime()\n const installedPackages: Array<string> = []\n const summary = createSummary(hrStart)\n logIntro({ title: isInteractiveRun({ yes, dryRun }) ? undefined : styleText('bgCyan', styleText('black', ' Kubb Update ')) })\n\n try {\n const wanted = new Set(ids.map(toRegistryId))\n const [entries, installed] = await withSpinner({\n message: 'Checking the registry',\n promise: Promise.all([fetchRegistryIndex({ registry: registryUrl() }), readInstalledPackages({ root: cwd })]),\n })\n const versions = new Map(installed.map((item) => [item.package, item.version]))\n\n const tracked = entries.filter((entry) => versions.has(entry.artifact.package) && (!wanted.size || wanted.has(entry.id)))\n for (const id of wanted) {\n if (tracked.some((entry) => entry.id === id)) continue\n logWarn(`${id} is not installed, or not in the registry.`)\n // A caller that named it, such as Studio, must not read the run as a successful update.\n process.exitCode = 1\n }\n\n const current = ({ artifact }: RegistryEntry) => versions.get(artifact.package)\n const isMajor = (entry: RegistryEntry) => bumpOf({ installed: current(entry), latest: entry.artifact.version }) === 'major'\n const outdated = tracked.filter((entry) => isOutdated({ installed: current(entry), latest: entry.artifact.version }))\n const proposals = outdated.filter((entry) => {\n const problem = incompatibility(entry.manifest)\n if (problem) {\n logWarn(`Skipped ${entry.id}: ${problem}`)\n // Same as a missing id: Studio would report an update that installed nothing.\n if (wanted.has(entry.id)) process.exitCode = 1\n }\n return !problem\n })\n\n if (!proposals.length) {\n const title = outdated.length ? 'No compatible updates available' : 'Already up to date'\n summary(tracked.length ? title : 'No installed extensions to update', outdated.length ? 'warning' : 'success', [\n ` ${tracked.length - outdated.length} of ${tracked.length} up to date`,\n ...(ids.length ? ['', `No updates for ${ids.join(', ')}.`] : []),\n ])\n return\n }\n\n if (tracked.length) {\n const header = ['Extension', 'Current', 'Latest', '']\n const rows = tracked.map((entry) => {\n if (!outdated.includes(entry)) return [entry.artifact.package, current(entry) ?? '-', 'up to date', '']\n const bump = bumpOf({ installed: current(entry), latest: entry.artifact.version }) ?? ''\n return [entry.artifact.package, current(entry) ?? 'not installed', entry.artifact.version, bump === 'major' ? 'major · breaking' : bump]\n })\n const lines = formatTable([header, ...rows])\n logStep(`Checked ${pluralize(tracked.length, 'extension')} against the registry`)\n logBlock([\n styleText('dim', lines[0]!),\n ...lines.slice(1).map((line, index) => {\n if (!outdated.includes(tracked[index]!)) return styleText('dim', line)\n return line.endsWith('major · breaking') ? styleText('yellow', line) : line\n }),\n ])\n }\n\n if (dryRun) {\n summary('Updates available', 'planned', [`Dry run: nothing was installed. Run kubb update to install ${proposals.length === 1 ? 'it' : 'them'}.`])\n return\n }\n\n // A major can break the generated code, so it is only picked for you when you named it.\n const defaults = proposals.filter((entry) => wanted.has(entry.id) || !isMajor(entry))\n const chosen = yes\n ? defaults.map((entry) => entry.id)\n : await clack.multiselect({\n message: 'Select the updates to install',\n options: proposals.map((entry) => ({\n value: entry.id,\n label: entry.artifact.package,\n hint: `${current(entry) ?? 'not installed'} → ${entry.artifact.version}`,\n })),\n initialValues: defaults.map((entry) => entry.id),\n required: false,\n })\n if (clack.isCancel(chosen)) {\n summary('Update canceled', 'canceled', [' No changes made'])\n return\n }\n const selected = proposals.filter((entry) => chosen.includes(entry.id))\n\n const skipped = proposals\n .filter((entry) => !selected.includes(entry))\n .map((entry) => {\n const kind = pascalCase(entry.manifest.kind)\n return ` ${styleText('dim', 'Skipped')} ${kind} ${entry.artifact.package} ${entry.artifact.version} ${styleText('dim', `run kubb update ${toShortId(entry.id)} later`)}`\n })\n if (!selected.length) {\n summary('No updates installed', 'canceled', [' No updates selected.', ...skipped])\n return\n }\n\n const packageManager = await detectPackageManager(cwd)\n const names = selected.map(({ artifact }) => artifact.package).join(', ')\n await installWithSpinner({\n packages: selected.map(({ artifact }) => installSpec(artifact)),\n names,\n packageManager,\n cwd,\n })\n installedPackages.push(...selected.map((entry) => entry.artifact.package))\n\n // Regenerating rewrites output files, so it is asked for. `--yes` only accepts the install.\n const foundConfig = findConfigFile(cwd)\n const regenerateNow =\n foundConfig && !yes && (await clack.confirm({ message: 'Regenerate now? This rewrites the generated files.', initialValue: true })) === true\n const configPath = regenerateNow ? foundConfig : undefined\n const changed = configPath ? await regenerate({ cwd, configPath }) : undefined\n\n const generationFailed = Boolean(configPath && !changed)\n summary(generationFailed ? 'Extensions updated; generation failed' : 'Update complete', generationFailed ? 'warning' : 'success', [\n ` Packages ${selected.length} installed with ${packageManager.name}${skipped.length ? ` · ${skipped.length} skipped` : ''}`,\n ...skipped,\n ...(changed ? [` Files ${changed.changes.added} added · ${changed.changes.modified} modified · ${changed.changes.deleted} deleted`] : []),\n ...(!configPath ? [' Regeneration not run'] : []),\n ...(generationFailed ? ['', 'Fix the generation error, then run kubb generate.'] : []),\n ])\n } catch (error) {\n logError(getErrorMessage(error))\n summary('Update failed', 'failed', installedPackages.length ? [` Packages ${installedPackages.join(', ')} installed`] : [' No changes made'])\n process.exitCode = 1\n }\n}\n\nexport const command = defineWithTypes<{ extensions: DryRunExtensions }>()({\n name: 'update',\n description: 'Update installed extensions, regenerate, and summarize file changes.',\n examples: ['kubb update', 'kubb update --dry-run', 'kubb update plugin-zod plugin-ts --yes'].join('\\n'),\n args: {\n ids: {\n type: 'positional',\n description: 'Registry ids to update, all installed extensions when omitted',\n multiple: true,\n },\n ...yesArg,\n },\n run: ({ values, extensions }) => run({ ids: values.ids ?? [], dryRun: extensions[dryRunId].enabled, yes: values.yes }),\n})\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;AAsCA,eAAe,WAAW,EAAE,KAAK,cAAkH;CACjJ,MAAM,UAAU,cAAc;CAC9B,QAAQ,MAAM,kCAAkC;CAChD,IAAI;EAEF,MAAM,CAAC,EAAE,cAAc,EAAE,YAAY,EAAE,SAAS,oBAAoB,MAAM,QAAQ,IAAI;GACpF,OAAO;GACP,OAAO;GACP,OAAO;EACT,CAAC;EACD,MAAM,EAAE,YAAY,MAAM,WAAW,EAAE,WAAW,CAAC;EACnD,MAAM,QAAQ,IAAI,SAAoB;EACtC,MAAM,UAAuB;GAAE,OAAO;GAAG,UAAU;GAAG,SAAS;GAAG,YAAY;GAAG,cAAc;EAAE;EAOjG,eAAe,OAAO;G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,eAAe,OAAO,QAAQ,SAAS,MAAM,QAAQ,OAAO,YAAY;GACzH,GAAG;GACH,GAAI,UAAU,CAAC,eAAe,QAAQ,QAAQ,MAAM,WAAW,QAAQ,QAAQ,SAAS,cAAc,QAAQ,QAAQ,QAAQ,SAAS,IAAI,CAAC;GAC5I,GAAI,CAAC,aAAa,CAAC,wBAAwB,IAAI,CAAC;GAChD,GAAI,mBAAmB,CAAC,IAAI,mDAAmD,IAAI,CAAC;EACtF,CAAC;CACH,SAAS,OAAO;EACd,SAAS,gBAAgB,KAAK,CAAC;EAC/B,QAAQ,iBAAiB,UAAU,kBAAkB,SAAS,CAAC,eAAe,kBAAkB,KAAK,IAAI,EAAE,WAAW,IAAI,CAAC,mBAAmB,CAAC;EAC/I,QAAQ,WAAW;CACrB;AACF;AAEA,MAAa,UAAU,gBAAkD,CAAC,CAAC;CACzE,MAAM;CACN,aAAa;CACb,UAAU;EAAC;EAAe;EAAyB;CAAwC,CAAC,CAAC,KAAK,IAAI;CACtG,MAAM;EACJ,KAAK;GACH,MAAM;GACN,aAAa;GACb,UAAU;EACZ;EACA,GAAG;CACL;CACA,MAAM,EAAE,QAAQ,iBAAiB,IAAI;EAAE,KAAK,OAAO,OAAO,CAAC;EAAG,QAAQ,WAAW,SAAS,CAAC;EAAS,KAAK,OAAO;CAAI,CAAC;AACvH,CAAC"}
|
|
1
|
+
{"version":3,"file":"run-B18jS3z1.js","names":["logLevelMap"],"sources":["../src/runners/update/run.ts"],"sourcesContent":["import path from 'node:path'\nimport process from 'node:process'\nimport { styleText } from 'node:util'\nimport * as clack from '@clack/prompts'\nimport { defineWithTypes } from 'gunshi'\nimport { findConfigFile } from '@internals/shared'\nimport { getErrorMessage, pascalCase } from '@internals/utils'\nimport { type GenerationResult, Hookable, type KubbHooks, logLevel as logLevelMap, readInstalledPackages, type RegistryEntry, type Reporter } from '@kubb/core'\nimport { pluralize } from '../../ui/text.ts'\nimport { dryRunId, type DryRunExtensions, yesArg } from '../../commands/shared.ts'\nimport { isInteractiveRun, logIntro } from '../../ui/intro.ts'\nimport { logBlock, logError, logStep, logWarn } from '../../ui/log.ts'\nimport { createSpinner, withSpinner } from '../../ui/spinner.ts'\nimport { createSummary } from '../../ui/summary.ts'\nimport { formatTable } from '../../ui/table.ts'\nimport { bumpOf, fetchRegistryIndex, incompatibility, installSpec, isOutdated, registryUrl, toRegistryId, toShortId } from '../../utils/registry.ts'\nimport { detectPackageManager } from '../init/utils.ts'\nimport { installWithSpinner } from '../installWithSpinner.ts'\n\nexport type UpdateOptions = {\n /**\n * Registry ids to update. Empty updates every installed extension the registry lists.\n */\n ids: Array<string>\n /**\n * List the updates without installing anything.\n */\n dryRun: boolean\n yes: boolean\n}\n\ntype FileChanges = NonNullable<GenerationResult['fileChanges']>\n\n/**\n * Generates every config in this process, the way `kubb generate` does, and returns the counts of\n * output files it changed. Runs after the install, so the config loads the new versions.\n * `undefined` when the config fails to load or a build fails.\n */\nasync function regenerate({ cwd, configPath }: { cwd: string; configPath: string }): Promise<{ changes: FileChanges; output: string } | undefined> {\n const spinner = createSpinner()\n spinner.start('Generating with the new versions')\n try {\n // Imported here, so the config loader and the generate path never slow down `kubb --help`.\n const [{ getConfigs }, { generate }, { default: setupReporters }] = await Promise.all([\n import('../../config.ts'),\n import('../generate/run.ts'),\n import('../../loggers/reporters.ts'),\n ])\n const { configs } = await getConfigs({ configPath })\n const hooks = new Hookable<KubbHooks>()\n const changes: FileChanges = { added: 0, modified: 0, deleted: 0, linesAdded: 0, linesRemoved: 0 }\n const collect: Reporter = {\n name: 'update',\n report: ({ fileChanges }) => {\n for (const key of Object.keys(changes) as Array<keyof FileChanges>) changes[key] += fileChanges?.[key] ?? 0\n },\n }\n setupReporters(hooks, { logLevel: logLevelMap.info, reporters: [collect], fileChanges: true })\n if (!(await generate({ configs, hooks }))) throw new Error('Generation failed')\n const changed = changes.added + changes.modified + changes.deleted\n spinner.stop(changed ? `Generated: ${pluralize(changed, 'file')} changed` : 'Generated: no files changed')\n return { changes, output: configs.map((config) => path.relative(cwd, path.resolve(config.root ?? cwd, config.output.path)) || '.').join(', ') }\n } catch (error) {\n spinner.error(`Generation failed: ${getErrorMessage(error)}`)\n return undefined\n }\n}\n\n/**\n * Moves installed extensions to the version the registry pins. Shows each version change with its\n * bump, asks which to install with majors left out, installs them, and regenerates to show which\n * files changed. With `dryRun`, only lists the updates and installs nothing.\n */\nexport async function run({ ids, dryRun, yes }: UpdateOptions): Promise<void> {\n const cwd = process.cwd()\n const hrStart = process.hrtime()\n const installedPackages: Array<string> = []\n const summary = createSummary(hrStart)\n logIntro({ title: isInteractiveRun({ yes, dryRun }) ? undefined : styleText('bgCyan', styleText('black', ' Kubb Update ')) })\n\n try {\n const wanted = new Set(ids.map(toRegistryId))\n const [entries, installed] = await withSpinner({\n message: 'Checking the registry',\n promise: Promise.all([fetchRegistryIndex({ registry: registryUrl() }), readInstalledPackages({ root: cwd })]),\n })\n const versions = new Map(installed.map((item) => [item.package, item.version]))\n\n const tracked = entries.filter((entry) => versions.has(entry.artifact.package) && (!wanted.size || wanted.has(entry.id)))\n for (const id of wanted) {\n if (tracked.some((entry) => entry.id === id)) continue\n logWarn(`${id} is not installed, or not in the registry.`)\n // A caller that named it, such as Studio, must not read the run as a successful update.\n process.exitCode = 1\n }\n\n const current = ({ artifact }: RegistryEntry) => versions.get(artifact.package)\n const isMajor = (entry: RegistryEntry) => bumpOf({ installed: current(entry), latest: entry.artifact.version }) === 'major'\n const outdated = tracked.filter((entry) => isOutdated({ installed: current(entry), latest: entry.artifact.version }))\n const proposals = outdated.filter((entry) => {\n const problem = incompatibility(entry.manifest)\n if (problem) {\n logWarn(`Skipped ${entry.id}: ${problem}`)\n // Same as a missing id: Studio would report an update that installed nothing.\n if (wanted.has(entry.id)) process.exitCode = 1\n }\n return !problem\n })\n\n if (!proposals.length) {\n const title = outdated.length ? 'No compatible updates available' : 'Already up to date'\n summary(tracked.length ? title : 'No installed extensions to update', outdated.length ? 'warning' : 'success', [\n ` ${tracked.length - outdated.length} of ${tracked.length} up to date`,\n ...(ids.length ? ['', `No updates for ${ids.join(', ')}.`] : []),\n ])\n return\n }\n\n if (tracked.length) {\n const header = ['Extension', 'Current', 'Latest', '']\n const rows = tracked.map((entry) => {\n if (!outdated.includes(entry)) return [entry.artifact.package, current(entry) ?? '-', 'up to date', '']\n const bump = bumpOf({ installed: current(entry), latest: entry.artifact.version }) ?? ''\n return [entry.artifact.package, current(entry) ?? 'not installed', entry.artifact.version, bump === 'major' ? 'major · breaking' : bump]\n })\n const lines = formatTable([header, ...rows])\n logStep(`Checked ${pluralize(tracked.length, 'extension')} against the registry`)\n logBlock([\n styleText('dim', lines[0]!),\n ...lines.slice(1).map((line, index) => {\n if (!outdated.includes(tracked[index]!)) return styleText('dim', line)\n return line.endsWith('major · breaking') ? styleText('yellow', line) : line\n }),\n ])\n }\n\n if (dryRun) {\n summary('Updates available', 'planned', [`Dry run: nothing was installed. Run kubb update to install ${proposals.length === 1 ? 'it' : 'them'}.`])\n return\n }\n\n // A major can break the generated code, so it is only picked for you when you named it.\n const defaults = proposals.filter((entry) => wanted.has(entry.id) || !isMajor(entry))\n const chosen = yes\n ? defaults.map((entry) => entry.id)\n : await clack.multiselect({\n message: 'Select the updates to install',\n options: proposals.map((entry) => ({\n value: entry.id,\n label: entry.artifact.package,\n hint: `${current(entry) ?? 'not installed'} → ${entry.artifact.version}`,\n })),\n initialValues: defaults.map((entry) => entry.id),\n required: false,\n })\n if (clack.isCancel(chosen)) {\n summary('Update canceled', 'canceled', [' No changes made'])\n return\n }\n const selected = proposals.filter((entry) => chosen.includes(entry.id))\n\n const skipped = proposals\n .filter((entry) => !selected.includes(entry))\n .map((entry) => {\n const kind = pascalCase(entry.manifest.kind)\n return ` ${styleText('dim', 'Skipped')} ${kind} ${entry.artifact.package} ${entry.artifact.version} ${styleText('dim', `run kubb update ${toShortId(entry.id)} later`)}`\n })\n if (!selected.length) {\n summary('No updates installed', 'canceled', [' No updates selected.', ...skipped])\n return\n }\n\n const packageManager = await detectPackageManager(cwd)\n const names = selected.map(({ artifact }) => artifact.package).join(', ')\n await installWithSpinner({\n packages: selected.map(({ artifact }) => installSpec(artifact)),\n names,\n packageManager,\n cwd,\n })\n installedPackages.push(...selected.map((entry) => entry.artifact.package))\n\n // Regenerating rewrites output files, so it is asked for. `--yes` only accepts the install.\n const foundConfig = findConfigFile(cwd)\n const regenerateNow =\n foundConfig && !yes && (await clack.confirm({ message: 'Regenerate now? This rewrites the generated files.', initialValue: true })) === true\n const configPath = regenerateNow ? foundConfig : undefined\n const changed = configPath ? await regenerate({ cwd, configPath }) : undefined\n\n const generationFailed = Boolean(configPath && !changed)\n summary(generationFailed ? 'Extensions updated; generation failed' : 'Update complete', generationFailed ? 'warning' : 'success', [\n ` Packages ${selected.length} installed with ${packageManager.name}${skipped.length ? ` · ${skipped.length} skipped` : ''}`,\n ...skipped,\n ...(changed ? [` Files ${changed.changes.added} added · ${changed.changes.modified} modified · ${changed.changes.deleted} deleted`] : []),\n ...(!configPath ? [' Regeneration not run'] : []),\n ...(generationFailed ? ['', 'Fix the generation error, then run kubb generate.'] : []),\n ])\n } catch (error) {\n logError(getErrorMessage(error))\n summary('Update failed', 'failed', installedPackages.length ? [` Packages ${installedPackages.join(', ')} installed`] : [' No changes made'])\n process.exitCode = 1\n }\n}\n\nexport const command = defineWithTypes<{ extensions: DryRunExtensions }>()({\n name: 'update',\n description: 'Update installed extensions, regenerate, and summarize file changes.',\n examples: ['kubb update', 'kubb update --dry-run', 'kubb update plugin-zod plugin-ts --yes'].join('\\n'),\n args: {\n ids: {\n type: 'positional',\n description: 'Registry ids to update, all installed extensions when omitted',\n multiple: true,\n },\n ...yesArg,\n },\n run: ({ values, extensions }) => run({ ids: values.ids ?? [], dryRun: extensions[dryRunId].enabled, yes: values.yes }),\n})\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;AAsCA,eAAe,WAAW,EAAE,KAAK,cAAkH;CACjJ,MAAM,UAAU,cAAc;CAC9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, configPath }) {
|
|
|
33
33
|
try {
|
|
34
34
|
const [{ getConfigs }, { generate }, { default: setupReporters }] = await Promise.all([
|
|
35
35
|
Promise.resolve().then(() => require("./config-CkTrJD0E.cjs")).then((n) => n.config_exports),
|
|
36
|
-
Promise.resolve().then(() => require("./run-
|
|
36
|
+
Promise.resolve().then(() => require("./run-70QKFTKm.cjs")),
|
|
37
37
|
Promise.resolve().then(() => require("./reporters-DLK4D0js.cjs")).then((n) => n.reporters_exports)
|
|
38
38
|
]);
|
|
39
39
|
const { configs } = await getConfigs({ configPath });
|
|
@@ -236,4 +236,4 @@ const command = (0, gunshi.defineWithTypes)()({
|
|
|
236
236
|
exports.command = command;
|
|
237
237
|
exports.run = run;
|
|
238
238
|
|
|
239
|
-
//# sourceMappingURL=run-
|
|
239
|
+
//# sourceMappingURL=run-BW6US_E0.cjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"run-C994a4Y5.cjs","names":["createSpinner","Hookable","logLevelMap","pluralize","path","getErrorMessage","process","createSummary","logIntro","isInteractiveRun","styleText","toRegistryId","withSpinner","fetchRegistryIndex","registryUrl","readInstalledPackages","logWarn","bumpOf","isOutdated","incompatibility","formatTable","logStep","logBlock","clack","pascalCase","toShortId","detectPackageManager","installWithSpinner","installSpec","findConfigFile","logError","defineWithTypes","yesArg","dryRunId"],"sources":["../src/runners/update/run.ts"],"sourcesContent":["import path from 'node:path'\nimport process from 'node:process'\nimport { styleText } from 'node:util'\nimport * as clack from '@clack/prompts'\nimport { defineWithTypes } from 'gunshi'\nimport { findConfigFile } from '@internals/shared'\nimport { getErrorMessage, pascalCase } from '@internals/utils'\nimport { type GenerationResult, Hookable, type KubbHooks, logLevel as logLevelMap, readInstalledPackages, type RegistryEntry, type Reporter } from '@kubb/core'\nimport { pluralize } from '../../ui/text.ts'\nimport { dryRunId, type DryRunExtensions, yesArg } from '../../commands/shared.ts'\nimport { isInteractiveRun, logIntro } from '../../ui/intro.ts'\nimport { logBlock, logError, logStep, logWarn } from '../../ui/log.ts'\nimport { createSpinner, withSpinner } from '../../ui/spinner.ts'\nimport { createSummary } from '../../ui/summary.ts'\nimport { formatTable } from '../../ui/table.ts'\nimport { bumpOf, fetchRegistryIndex, incompatibility, installSpec, isOutdated, registryUrl, toRegistryId, toShortId } from '../../utils/registry.ts'\nimport { detectPackageManager } from '../init/utils.ts'\nimport { installWithSpinner } from '../installWithSpinner.ts'\n\nexport type UpdateOptions = {\n /**\n * Registry ids to update. Empty updates every installed extension the registry lists.\n */\n ids: Array<string>\n /**\n * List the updates without installing anything.\n */\n dryRun: boolean\n yes: boolean\n}\n\ntype FileChanges = NonNullable<GenerationResult['fileChanges']>\n\n/**\n * Generates every config in this process, the way `kubb generate` does, and returns the counts of\n * output files it changed. Runs after the install, so the config loads the new versions.\n * `undefined` when the config fails to load or a build fails.\n */\nasync function regenerate({ cwd, configPath }: { cwd: string; configPath: string }): Promise<{ changes: FileChanges; output: string } | undefined> {\n const spinner = createSpinner()\n spinner.start('Generating with the new versions')\n try {\n // Imported here, so the config loader and the generate path never slow down `kubb --help`.\n const [{ getConfigs }, { generate }, { default: setupReporters }] = await Promise.all([\n import('../../config.ts'),\n import('../generate/run.ts'),\n import('../../loggers/reporters.ts'),\n ])\n const { configs } = await getConfigs({ configPath })\n const hooks = new Hookable<KubbHooks>()\n const changes: FileChanges = { added: 0, modified: 0, deleted: 0, linesAdded: 0, linesRemoved: 0 }\n const collect: Reporter = {\n name: 'update',\n report: ({ fileChanges }) => {\n for (const key of Object.keys(changes) as Array<keyof FileChanges>) changes[key] += fileChanges?.[key] ?? 0\n },\n }\n setupReporters(hooks, { logLevel: logLevelMap.info, reporters: [collect], fileChanges: true })\n if (!(await generate({ configs, hooks }))) throw new Error('Generation failed')\n const changed = changes.added + changes.modified + changes.deleted\n spinner.stop(changed ? `Generated: ${pluralize(changed, 'file')} changed` : 'Generated: no files changed')\n return { changes, output: configs.map((config) => path.relative(cwd, path.resolve(config.root ?? cwd, config.output.path)) || '.').join(', ') }\n } catch (error) {\n spinner.error(`Generation failed: ${getErrorMessage(error)}`)\n return undefined\n }\n}\n\n/**\n * Moves installed extensions to the version the registry pins. Shows each version change with its\n * bump, asks which to install with majors left out, installs them, and regenerates to show which\n * files changed. With `dryRun`, only lists the updates and installs nothing.\n */\nexport async function run({ ids, dryRun, yes }: UpdateOptions): Promise<void> {\n const cwd = process.cwd()\n const hrStart = process.hrtime()\n const installedPackages: Array<string> = []\n const summary = createSummary(hrStart)\n logIntro({ title: isInteractiveRun({ yes, dryRun }) ? undefined : styleText('bgCyan', styleText('black', ' Kubb Update ')) })\n\n try {\n const wanted = new Set(ids.map(toRegistryId))\n const [entries, installed] = await withSpinner({\n message: 'Checking the registry',\n promise: Promise.all([fetchRegistryIndex({ registry: registryUrl() }), readInstalledPackages({ root: cwd })]),\n })\n const versions = new Map(installed.map((item) => [item.package, item.version]))\n\n const tracked = entries.filter((entry) => versions.has(entry.artifact.package) && (!wanted.size || wanted.has(entry.id)))\n for (const id of wanted) {\n if (tracked.some((entry) => entry.id === id)) continue\n logWarn(`${id} is not installed, or not in the registry.`)\n // A caller that named it, such as Studio, must not read the run as a successful update.\n process.exitCode = 1\n }\n\n const current = ({ artifact }: RegistryEntry) => versions.get(artifact.package)\n const isMajor = (entry: RegistryEntry) => bumpOf({ installed: current(entry), latest: entry.artifact.version }) === 'major'\n const outdated = tracked.filter((entry) => isOutdated({ installed: current(entry), latest: entry.artifact.version }))\n const proposals = outdated.filter((entry) => {\n const problem = incompatibility(entry.manifest)\n if (problem) {\n logWarn(`Skipped ${entry.id}: ${problem}`)\n // Same as a missing id: Studio would report an update that installed nothing.\n if (wanted.has(entry.id)) process.exitCode = 1\n }\n return !problem\n })\n\n if (!proposals.length) {\n const title = outdated.length ? 'No compatible updates available' : 'Already up to date'\n summary(tracked.length ? title : 'No installed extensions to update', outdated.length ? 'warning' : 'success', [\n ` ${tracked.length - outdated.length} of ${tracked.length} up to date`,\n ...(ids.length ? ['', `No updates for ${ids.join(', ')}.`] : []),\n ])\n return\n }\n\n if (tracked.length) {\n const header = ['Extension', 'Current', 'Latest', '']\n const rows = tracked.map((entry) => {\n if (!outdated.includes(entry)) return [entry.artifact.package, current(entry) ?? '-', 'up to date', '']\n const bump = bumpOf({ installed: current(entry), latest: entry.artifact.version }) ?? ''\n return [entry.artifact.package, current(entry) ?? 'not installed', entry.artifact.version, bump === 'major' ? 'major · breaking' : bump]\n })\n const lines = formatTable([header, ...rows])\n logStep(`Checked ${pluralize(tracked.length, 'extension')} against the registry`)\n logBlock([\n styleText('dim', lines[0]!),\n ...lines.slice(1).map((line, index) => {\n if (!outdated.includes(tracked[index]!)) return styleText('dim', line)\n return line.endsWith('major · breaking') ? styleText('yellow', line) : line\n }),\n ])\n }\n\n if (dryRun) {\n summary('Updates available', 'planned', [`Dry run: nothing was installed. Run kubb update to install ${proposals.length === 1 ? 'it' : 'them'}.`])\n return\n }\n\n // A major can break the generated code, so it is only picked for you when you named it.\n const defaults = proposals.filter((entry) => wanted.has(entry.id) || !isMajor(entry))\n const chosen = yes\n ? defaults.map((entry) => entry.id)\n : await clack.multiselect({\n message: 'Select the updates to install',\n options: proposals.map((entry) => ({\n value: entry.id,\n label: entry.artifact.package,\n hint: `${current(entry) ?? 'not installed'} → ${entry.artifact.version}`,\n })),\n initialValues: defaults.map((entry) => entry.id),\n required: false,\n })\n if (clack.isCancel(chosen)) {\n summary('Update canceled', 'canceled', [' No changes made'])\n return\n }\n const selected = proposals.filter((entry) => chosen.includes(entry.id))\n\n const skipped = proposals\n .filter((entry) => !selected.includes(entry))\n .map((entry) => {\n const kind = pascalCase(entry.manifest.kind)\n return ` ${styleText('dim', 'Skipped')} ${kind} ${entry.artifact.package} ${entry.artifact.version} ${styleText('dim', `run kubb update ${toShortId(entry.id)} later`)}`\n })\n if (!selected.length) {\n summary('No updates installed', 'canceled', [' No updates selected.', ...skipped])\n return\n }\n\n const packageManager = await detectPackageManager(cwd)\n const names = selected.map(({ artifact }) => artifact.package).join(', ')\n await installWithSpinner({\n packages: selected.map(({ artifact }) => installSpec(artifact)),\n names,\n packageManager,\n cwd,\n })\n installedPackages.push(...selected.map((entry) => entry.artifact.package))\n\n // Regenerating rewrites output files, so it is asked for. `--yes` only accepts the install.\n const foundConfig = findConfigFile(cwd)\n const regenerateNow =\n foundConfig && !yes && (await clack.confirm({ message: 'Regenerate now? This rewrites the generated files.', initialValue: true })) === true\n const configPath = regenerateNow ? foundConfig : undefined\n const changed = configPath ? await regenerate({ cwd, configPath }) : undefined\n\n const generationFailed = Boolean(configPath && !changed)\n summary(generationFailed ? 'Extensions updated; generation failed' : 'Update complete', generationFailed ? 'warning' : 'success', [\n ` Packages ${selected.length} installed with ${packageManager.name}${skipped.length ? ` · ${skipped.length} skipped` : ''}`,\n ...skipped,\n ...(changed ? [` Files ${changed.changes.added} added · ${changed.changes.modified} modified · ${changed.changes.deleted} deleted`] : []),\n ...(!configPath ? [' Regeneration not run'] : []),\n ...(generationFailed ? ['', 'Fix the generation error, then run kubb generate.'] : []),\n ])\n } catch (error) {\n logError(getErrorMessage(error))\n summary('Update failed', 'failed', installedPackages.length ? [` Packages ${installedPackages.join(', ')} installed`] : [' No changes made'])\n process.exitCode = 1\n }\n}\n\nexport const command = defineWithTypes<{ extensions: DryRunExtensions }>()({\n name: 'update',\n description: 'Update installed extensions, regenerate, and summarize file changes.',\n examples: ['kubb update', 'kubb update --dry-run', 'kubb update plugin-zod plugin-ts --yes'].join('\\n'),\n args: {\n ids: {\n type: 'positional',\n description: 'Registry ids to update, all installed extensions when omitted',\n multiple: true,\n },\n ...yesArg,\n },\n run: ({ values, extensions }) => run({ ids: values.ids ?? [], dryRun: extensions[dryRunId].enabled, yes: values.yes }),\n})\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAsCA,eAAe,WAAW,EAAE,KAAK,cAAkH;CACjJ,MAAM,UAAUA,gBAAAA,cAAc;CAC9B,QAAQ,MAAM,kCAAkC;CAChD,IAAI;EAEF,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AmB,CAAC,IAAI,mDAAmD,IAAI,CAAC;EACtF,CAAC;CACH,SAAS,OAAO;EACdO,YAAAA,SAASzB,eAAAA,gBAAgB,KAAK,CAAC;EAC/B,QAAQ,iBAAiB,UAAU,kBAAkB,SAAS,CAAC,eAAe,kBAAkB,KAAK,IAAI,EAAE,WAAW,IAAI,CAAC,mBAAmB,CAAC;EAC/I,aAAA,QAAA,WAAmB;CACrB;AACF;AAEA,MAAa,WAAA,GAAU0B,OAAAA,gBAAAA,CAAkD,CAAC,CAAC;CACzE,MAAM;CACN,aAAa;CACb,UAAU;EAAC;EAAe;EAAyB;CAAwC,CAAC,CAAC,KAAK,IAAI;CACtG,MAAM;EACJ,KAAK;GACH,MAAM;GACN,aAAa;GACb,UAAU;EACZ;EACA,GAAGC,eAAAA;CACL;CACA,MAAM,EAAE,QAAQ,iBAAiB,IAAI;EAAE,KAAK,OAAO,OAAO,CAAC;EAAG,QAAQ,WAAWC,sBAAAA,SAAS,CAAC;EAAS,KAAK,OAAO;CAAI,CAAC;AACvH,CAAC"}
|
|
1
|
+
{"version":3,"file":"run-BW6US_E0.cjs","names":["createSpinner","Hookable","logLevelMap","pluralize","path","getErrorMessage","process","createSummary","logIntro","isInteractiveRun","styleText","toRegistryId","withSpinner","fetchRegistryIndex","registryUrl","readInstalledPackages","logWarn","bumpOf","isOutdated","incompatibility","formatTable","logStep","logBlock","clack","pascalCase","toShortId","detectPackageManager","installWithSpinner","installSpec","findConfigFile","logError","defineWithTypes","yesArg","dryRunId"],"sources":["../src/runners/update/run.ts"],"sourcesContent":["import path from 'node:path'\nimport process from 'node:process'\nimport { styleText } from 'node:util'\nimport * as clack from '@clack/prompts'\nimport { defineWithTypes } from 'gunshi'\nimport { findConfigFile } from '@internals/shared'\nimport { getErrorMessage, pascalCase } from '@internals/utils'\nimport { type GenerationResult, Hookable, type KubbHooks, logLevel as logLevelMap, readInstalledPackages, type RegistryEntry, type Reporter } from '@kubb/core'\nimport { pluralize } from '../../ui/text.ts'\nimport { dryRunId, type DryRunExtensions, yesArg } from '../../commands/shared.ts'\nimport { isInteractiveRun, logIntro } from '../../ui/intro.ts'\nimport { logBlock, logError, logStep, logWarn } from '../../ui/log.ts'\nimport { createSpinner, withSpinner } from '../../ui/spinner.ts'\nimport { createSummary } from '../../ui/summary.ts'\nimport { formatTable } from '../../ui/table.ts'\nimport { bumpOf, fetchRegistryIndex, incompatibility, installSpec, isOutdated, registryUrl, toRegistryId, toShortId } from '../../utils/registry.ts'\nimport { detectPackageManager } from '../init/utils.ts'\nimport { installWithSpinner } from '../installWithSpinner.ts'\n\nexport type UpdateOptions = {\n /**\n * Registry ids to update. Empty updates every installed extension the registry lists.\n */\n ids: Array<string>\n /**\n * List the updates without installing anything.\n */\n dryRun: boolean\n yes: boolean\n}\n\ntype FileChanges = NonNullable<GenerationResult['fileChanges']>\n\n/**\n * Generates every config in this process, the way `kubb generate` does, and returns the counts of\n * output files it changed. Runs after the install, so the config loads the new versions.\n * `undefined` when the config fails to load or a build fails.\n */\nasync function regenerate({ cwd, configPath }: { cwd: string; configPath: string }): Promise<{ changes: FileChanges; output: string } | undefined> {\n const spinner = createSpinner()\n spinner.start('Generating with the new versions')\n try {\n // Imported here, so the config loader and the generate path never slow down `kubb --help`.\n const [{ getConfigs }, { generate }, { default: setupReporters }] = await Promise.all([\n import('../../config.ts'),\n import('../generate/run.ts'),\n import('../../loggers/reporters.ts'),\n ])\n const { configs } = await getConfigs({ configPath })\n const hooks = new Hookable<KubbHooks>()\n const changes: FileChanges = { added: 0, modified: 0, deleted: 0, linesAdded: 0, linesRemoved: 0 }\n const collect: Reporter = {\n name: 'update',\n report: ({ fileChanges }) => {\n for (const key of Object.keys(changes) as Array<keyof FileChanges>) changes[key] += fileChanges?.[key] ?? 0\n },\n }\n setupReporters(hooks, { logLevel: logLevelMap.info, reporters: [collect], fileChanges: true })\n if (!(await generate({ configs, hooks }))) throw new Error('Generation failed')\n const changed = changes.added + changes.modified + changes.deleted\n spinner.stop(changed ? `Generated: ${pluralize(changed, 'file')} changed` : 'Generated: no files changed')\n return { changes, output: configs.map((config) => path.relative(cwd, path.resolve(config.root ?? cwd, config.output.path)) || '.').join(', ') }\n } catch (error) {\n spinner.error(`Generation failed: ${getErrorMessage(error)}`)\n return undefined\n }\n}\n\n/**\n * Moves installed extensions to the version the registry pins. Shows each version change with its\n * bump, asks which to install with majors left out, installs them, and regenerates to show which\n * files changed. With `dryRun`, only lists the updates and installs nothing.\n */\nexport async function run({ ids, dryRun, yes }: UpdateOptions): Promise<void> {\n const cwd = process.cwd()\n const hrStart = process.hrtime()\n const installedPackages: Array<string> = []\n const summary = createSummary(hrStart)\n logIntro({ title: isInteractiveRun({ yes, dryRun }) ? undefined : styleText('bgCyan', styleText('black', ' Kubb Update ')) })\n\n try {\n const wanted = new Set(ids.map(toRegistryId))\n const [entries, installed] = await withSpinner({\n message: 'Checking the registry',\n promise: Promise.all([fetchRegistryIndex({ registry: registryUrl() }), readInstalledPackages({ root: cwd })]),\n })\n const versions = new Map(installed.map((item) => [item.package, item.version]))\n\n const tracked = entries.filter((entry) => versions.has(entry.artifact.package) && (!wanted.size || wanted.has(entry.id)))\n for (const id of wanted) {\n if (tracked.some((entry) => entry.id === id)) continue\n logWarn(`${id} is not installed, or not in the registry.`)\n // A caller that named it, such as Studio, must not read the run as a successful update.\n process.exitCode = 1\n }\n\n const current = ({ artifact }: RegistryEntry) => versions.get(artifact.package)\n const isMajor = (entry: RegistryEntry) => bumpOf({ installed: current(entry), latest: entry.artifact.version }) === 'major'\n const outdated = tracked.filter((entry) => isOutdated({ installed: current(entry), latest: entry.artifact.version }))\n const proposals = outdated.filter((entry) => {\n const problem = incompatibility(entry.manifest)\n if (problem) {\n logWarn(`Skipped ${entry.id}: ${problem}`)\n // Same as a missing id: Studio would report an update that installed nothing.\n if (wanted.has(entry.id)) process.exitCode = 1\n }\n return !problem\n })\n\n if (!proposals.length) {\n const title = outdated.length ? 'No compatible updates available' : 'Already up to date'\n summary(tracked.length ? title : 'No installed extensions to update', outdated.length ? 'warning' : 'success', [\n ` ${tracked.length - outdated.length} of ${tracked.length} up to date`,\n ...(ids.length ? ['', `No updates for ${ids.join(', ')}.`] : []),\n ])\n return\n }\n\n if (tracked.length) {\n const header = ['Extension', 'Current', 'Latest', '']\n const rows = tracked.map((entry) => {\n if (!outdated.includes(entry)) return [entry.artifact.package, current(entry) ?? '-', 'up to date', '']\n const bump = bumpOf({ installed: current(entry), latest: entry.artifact.version }) ?? ''\n return [entry.artifact.package, current(entry) ?? 'not installed', entry.artifact.version, bump === 'major' ? 'major · breaking' : bump]\n })\n const lines = formatTable([header, ...rows])\n logStep(`Checked ${pluralize(tracked.length, 'extension')} against the registry`)\n logBlock([\n styleText('dim', lines[0]!),\n ...lines.slice(1).map((line, index) => {\n if (!outdated.includes(tracked[index]!)) return styleText('dim', line)\n return line.endsWith('major · breaking') ? styleText('yellow', line) : line\n }),\n ])\n }\n\n if (dryRun) {\n summary('Updates available', 'planned', [`Dry run: nothing was installed. Run kubb update to install ${proposals.length === 1 ? 'it' : 'them'}.`])\n return\n }\n\n // A major can break the generated code, so it is only picked for you when you named it.\n const defaults = proposals.filter((entry) => wanted.has(entry.id) || !isMajor(entry))\n const chosen = yes\n ? defaults.map((entry) => entry.id)\n : await clack.multiselect({\n message: 'Select the updates to install',\n options: proposals.map((entry) => ({\n value: entry.id,\n label: entry.artifact.package,\n hint: `${current(entry) ?? 'not installed'} → ${entry.artifact.version}`,\n })),\n initialValues: defaults.map((entry) => entry.id),\n required: false,\n })\n if (clack.isCancel(chosen)) {\n summary('Update canceled', 'canceled', [' No changes made'])\n return\n }\n const selected = proposals.filter((entry) => chosen.includes(entry.id))\n\n const skipped = proposals\n .filter((entry) => !selected.includes(entry))\n .map((entry) => {\n const kind = pascalCase(entry.manifest.kind)\n return ` ${styleText('dim', 'Skipped')} ${kind} ${entry.artifact.package} ${entry.artifact.version} ${styleText('dim', `run kubb update ${toShortId(entry.id)} later`)}`\n })\n if (!selected.length) {\n summary('No updates installed', 'canceled', [' No updates selected.', ...skipped])\n return\n }\n\n const packageManager = await detectPackageManager(cwd)\n const names = selected.map(({ artifact }) => artifact.package).join(', ')\n await installWithSpinner({\n packages: selected.map(({ artifact }) => installSpec(artifact)),\n names,\n packageManager,\n cwd,\n })\n installedPackages.push(...selected.map((entry) => entry.artifact.package))\n\n // Regenerating rewrites output files, so it is asked for. `--yes` only accepts the install.\n const foundConfig = findConfigFile(cwd)\n const regenerateNow =\n foundConfig && !yes && (await clack.confirm({ message: 'Regenerate now? This rewrites the generated files.', initialValue: true })) === true\n const configPath = regenerateNow ? foundConfig : undefined\n const changed = configPath ? await regenerate({ cwd, configPath }) : undefined\n\n const generationFailed = Boolean(configPath && !changed)\n summary(generationFailed ? 'Extensions updated; generation failed' : 'Update complete', generationFailed ? 'warning' : 'success', [\n ` Packages ${selected.length} installed with ${packageManager.name}${skipped.length ? ` · ${skipped.length} skipped` : ''}`,\n ...skipped,\n ...(changed ? [` Files ${changed.changes.added} added · ${changed.changes.modified} modified · ${changed.changes.deleted} deleted`] : []),\n ...(!configPath ? [' Regeneration not run'] : []),\n ...(generationFailed ? ['', 'Fix the generation error, then run kubb generate.'] : []),\n ])\n } catch (error) {\n logError(getErrorMessage(error))\n summary('Update failed', 'failed', installedPackages.length ? [` Packages ${installedPackages.join(', ')} installed`] : [' No changes made'])\n process.exitCode = 1\n }\n}\n\nexport const command = defineWithTypes<{ extensions: DryRunExtensions }>()({\n name: 'update',\n description: 'Update installed extensions, regenerate, and summarize file changes.',\n examples: ['kubb update', 'kubb update --dry-run', 'kubb update plugin-zod plugin-ts --yes'].join('\\n'),\n args: {\n ids: {\n type: 'positional',\n description: 'Registry ids to update, all installed extensions when omitted',\n multiple: true,\n },\n ...yesArg,\n },\n run: ({ values, extensions }) => run({ ids: values.ids ?? [], dryRun: extensions[dryRunId].enabled, yes: values.yes }),\n})\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAsCA,eAAe,WAAW,E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QAAQ,QAAQ,SAAS,IAAI,CAAC;GAC5I,GAAI,CAAC,aAAa,CAAC,wBAAwB,IAAI,CAAC;GAChD,GAAI,mBAAmB,CAAC,IAAI,mDAAmD,IAAI,CAAC;EACtF,CAAC;CACH,SAAS,OAAO;EACdO,YAAAA,SAASzB,eAAAA,gBAAgB,KAAK,CAAC;EAC/B,QAAQ,iBAAiB,UAAU,kBAAkB,SAAS,CAAC,eAAe,kBAAkB,KAAK,IAAI,EAAE,WAAW,IAAI,CAAC,mBAAmB,CAAC;EAC/I,aAAA,QAAA,WAAmB;CACrB;AACF;AAEA,MAAa,WAAA,GAAU0B,OAAAA,gBAAAA,CAAkD,CAAC,CAAC;CACzE,MAAM;CACN,aAAa;CACb,UAAU;EAAC;EAAe;EAAyB;CAAwC,CAAC,CAAC,KAAK,IAAI;CACtG,MAAM;EACJ,KAAK;GACH,MAAM;GACN,aAAa;GACb,UAAU;EACZ;EACA,GAAGC,eAAAA;CACL;CACA,MAAM,EAAE,QAAQ,iBAAiB,IAAI;EAAE,KAAK,OAAO,OAAO,CAAC;EAAG,QAAQ,WAAWC,sBAAAA,SAAS,CAAC;EAAS,KAAK,OAAO;CAAI,CAAC;AACvH,CAAC"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
export { t as connect, a as login, s as resolvePermissions, c as runStudio } from "./run-
|
|
1
|
+
export { t as connect, a as login, s as resolvePermissions, c as runStudio } from "./run-CpPnINxG.js";
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
const require_rolldown_runtime = require("./rolldown-runtime-BV8xUvPy.cjs");
|
|
2
2
|
const require_errors = require("./errors-Bewwe8mY.cjs");
|
|
3
|
-
const require_Telemetry = require("./Telemetry-
|
|
3
|
+
const require_Telemetry = require("./Telemetry-CFa6j6jh.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);
|
|
@@ -29,4 +29,4 @@ async function run() {
|
|
|
29
29
|
}
|
|
30
30
|
exports.run = run;
|
|
31
31
|
|
|
32
|
-
//# sourceMappingURL=run-
|
|
32
|
+
//# sourceMappingURL=run-C4cU9oxc.cjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"run-
|
|
1
|
+
{"version":3,"file":"run-C4cU9oxc.cjs","names":["trackRun","process","styleText","toError"],"sources":["../src/runners/mcp/run.ts"],"sourcesContent":["import process from 'node:process'\nimport { styleText } from 'node:util'\nimport { toError } from '@internals/utils'\nimport type * as McpModule from '@kubb/mcp'\nimport { trackRun } from '../../Telemetry.ts'\n\n/**\n * Starts the `@kubb/mcp` server over stdio and reports the outcome to telemetry.\n */\nexport async function run(): Promise<void> {\n const { run: startMcpServer } = (await import('@kubb/mcp')) as typeof McpModule\n\n const report = trackRun({ command: 'mcp', hrStart: process.hrtime() })\n\n try {\n // The MCP stdio transport owns stdout: anything else written there corrupts the JSON-RPC stream.\n console.error(styleText('cyan', '⏳ Starting MCP server...'))\n console.warn(styleText('yellow', 'This feature is still under development, use with caution'))\n const server = startMcpServer()\n // Report once the client introduces itself, so the event names the client (e.g. `claude-code`, `cursor-vscode`).\n server.on('initialize', ({ clientInfo }) => void report({ status: 'success', mcpClient: clientInfo.name }), { once: true })\n } catch (error) {\n await report({ status: 'failed' })\n console.error(toError(error).message)\n process.exitCode = 1\n }\n}\n"],"mappings":";;;;;;;;;;AASA,eAAsB,MAAqB;CACzC,MAAM,EAAE,KAAK,mBAAoB,MAAM,OAAO;CAE9C,MAAM,SAASA,kBAAAA,SAAS;EAAE,SAAS;EAAO,SAASC,aAAAA,QAAQ,OAAO;CAAE,CAAC;CAErE,IAAI;EAEF,QAAQ,OAAA,GAAMC,UAAAA,UAAAA,CAAU,QAAQ,0BAA0B,CAAC;EAC3D,QAAQ,MAAA,GAAKA,UAAAA,UAAAA,CAAU,UAAU,2DAA2D,CAAC;EAC9E,eAEV,CAAC,CAAC,GAAG,eAAe,EAAE,iBAAiB,KAAK,OAAO;GAAE,QAAQ;GAAW,WAAW,WAAW;EAAK,CAAC,GAAG,EAAE,MAAM,KAAK,CAAC;CAC5H,SAAS,OAAO;EACd,MAAM,OAAO,EAAE,QAAQ,SAAS,CAAC;EACjC,QAAQ,MAAMC,eAAAA,QAAQ,KAAK,CAAC,CAAC,OAAO;EACpC,aAAA,QAAA,WAAmB;CACrB;AACF"}
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import "./rolldown-runtime-BowF1xt-.js";
|
|
2
2
|
import { t as findConfigFile } from "./config-re864UnO.js";
|
|
3
3
|
import { n as toError } from "./errors-CEzFbRvL.js";
|
|
4
|
-
import { n as trackRun } from "./Telemetry-
|
|
4
|
+
import { n as trackRun } from "./Telemetry-B8HIo9K9.js";
|
|
5
5
|
import { t as getConfigs } from "./config-CGcQTdZV.js";
|
|
6
6
|
import { n as pluralize } from "./text-HYWAcipy.js";
|
|
7
7
|
import { n as logCommandSummary } from "./summary-BS-iWuye.js";
|
|
@@ -96,4 +96,4 @@ async function run({ input, configPath }) {
|
|
|
96
96
|
}
|
|
97
97
|
export { run };
|
|
98
98
|
|
|
99
|
-
//# sourceMappingURL=run-
|
|
99
|
+
//# sourceMappingURL=run-C70KILiO.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"run-
|
|
1
|
+
{"version":3,"file":"run-C70KILiO.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, checkoutGitInput, getInputKind } 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, URL, or git input (`git+<repo>#<ref>:<path>`) of 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 = getInputKind(input) === 'file' ? resolve(config.root || process.cwd(), input) : 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 const checkout = getInputKind(target.input) === 'git' ? await checkoutGitInput(target.input) : undefined\n try {\n await target.adapter.validate(checkout?.path ?? target.input, { throwOnError: true })\n } finally {\n await checkout?.dispose()\n }\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,aAAa,KAAK,MAAM,SAAS,QAAQ,OAAO,QAAQ,QAAQ,IAAI,GAAG,KAAK,IAAI;GACjG,OAAO,CAAC,GAAG,OAAO,SAAS,KAAK,IAAI,YAAY;IAAE,SAAS,OAAO;IAAS,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QAAQ;GACR;GACA,OAAO;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"}
|
|
@@ -10,7 +10,7 @@ const require_log = require("./log-BzmBldY6.cjs");
|
|
|
10
10
|
const require_registry = require("./registry-CTVAqQFn.cjs");
|
|
11
11
|
const require_installWithSpinner = require("./installWithSpinner-qjIqjyiW.cjs");
|
|
12
12
|
const require_utils = require("./utils-_hY0r-7x.cjs");
|
|
13
|
-
const require_package = require("./package-
|
|
13
|
+
const require_package = require("./package-BugC4svC.cjs");
|
|
14
14
|
let node_util = require("node:util");
|
|
15
15
|
let gunshi = require("gunshi");
|
|
16
16
|
let node_process = require("node:process");
|
|
@@ -372,4 +372,4 @@ const command = (0, gunshi.defineWithTypes)()({
|
|
|
372
372
|
exports.command = command;
|
|
373
373
|
exports.run = run;
|
|
374
374
|
|
|
375
|
-
//# sourceMappingURL=run-
|
|
375
|
+
//# sourceMappingURL=run-C9PwQp2D.cjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"run-Nh3NdjRM.cjs","names":["clack","process","editConfig","ConfigEditOperation","Diagnostics","KUBB_CONFIG_FILENAME","getConfigs","createKubb","resolveCommand","logIntro","isInteractiveRun","fetchRegistryIndex","registryUrl","incompatibility","exists","path","detectPackageManager","withSpinner","initPackageJson","findSpecFiles","logStep","readSpecInfo","pluralize","initDefaults","findPlugin","parsePluginsFlag","isHttpUrl","styleText","missingPluginDependencies","logWarn","KUBB_PACKAGE_NAME","logBlock","version","installSpec","installPackages","installWithSpinner","write","addGenerateScript","generateScript","formatMs","getElapsedMs","logError","logOutro","defineWithTypes","dryRunId"],"sources":["../../../internals/shared/src/init.ts","../src/runners/init/run.ts"],"sourcesContent":["/** The `kubb.config.ts` `kubb init` writes before `kubb add` puts each plugin in. */\nexport function generateConfigFile({ inputPath, outputPath }: { inputPath: string; outputPath: string }): string {\n return `import { defineConfig } from 'kubb/config'\n\nexport default defineConfig({\n input: '${inputPath}',\n output: {\n path: '${outputPath}',\n clean: true,\n },\n plugins: [],\n})\n`\n}\n","import path from 'node:path'\nimport process from 'node:process'\nimport { styleText } from 'node:util'\nimport * as clack from '@clack/prompts'\nimport type { DryRunExtension } from '@gunshi/plugin-dryrun'\nimport { defineWithTypes } from 'gunshi'\nimport { resolveCommand } from 'package-manager-detector'\nimport { ConfigEditOperation, editConfig, generateConfigFile, initDefaults, KUBB_CONFIG_FILENAME, KUBB_PACKAGE_NAME } from '@internals/shared'\nimport { exists, formatMs, getElapsedMs, write } from '@internals/utils'\nimport { createKubb, Diagnostics, type RegistryEntry } from '@kubb/core'\nimport { dryRunId, type DryRunExtensions } from '../../commands/shared.ts'\nimport { getConfigs } from '../../config.ts'\nimport { isHttpUrl, pluralize } from '../../ui/text.ts'\nimport { isInteractiveRun, logIntro, logOutro } from '../../ui/intro.ts'\nimport { logBlock, logError, logStep, logWarn } from '../../ui/log.ts'\nimport { withSpinner } from '../../ui/spinner.ts'\nimport { fetchRegistryIndex, incompatibility, installSpec, registryUrl } from '../../utils/registry.ts'\nimport { installWithSpinner } from '../installWithSpinner.ts'\nimport {\n addGenerateScript,\n detectPackageManager,\n findPlugin,\n findSpecFiles,\n generateScript,\n initPackageJson,\n installPackages,\n missingPluginDependencies,\n type PackageManagerInfo,\n parsePluginsFlag,\n readSpecInfo,\n} from './utils.ts'\nimport { version } from '../../../package.json'\n\nfunction cancelAndExit(message = 'Operation canceled.'): never {\n clack.cancel(message)\n process.exit(0)\n}\n\nfunction unwrap<T>(value: T): Exclude<T, symbol> {\n if (clack.isCancel(value)) cancelAndExit()\n return value as Exclude<T, symbol>\n}\n\ntype InitOptions = {\n /**\n * When `true`, skips all interactive prompts and uses the detected or default values.\n */\n yes: boolean\n /**\n * Input path flag value from `--input`. When provided, skips the input prompt.\n */\n input?: string\n /**\n * Output directory flag value from `--output`. When provided, skips the output prompt.\n */\n output?: string\n /**\n * Comma-separated plugin list from `--plugins`, e.g. `'plugin-ts,zod'`. When provided, skips the plugin selection prompt.\n */\n plugins?: string\n /**\n * Dry-run extension from `@gunshi/plugin-dryrun`. When enabled, package installation, file\n * writes, and the first run are skipped.\n */\n dryRun: DryRunExtension\n}\n\ntype Choices = {\n inputPath: string\n outputPath: string\n plugins: Array<RegistryEntry>\n}\n\n/** The full `kubb.config.ts` for `choices`, with each plugin added the way `kubb add` adds it. */\nfunction buildConfig({ inputPath, outputPath, plugins }: Choices): string {\n const { source, outcomes } = editConfig({\n source: generateConfigFile({ inputPath, outputPath }),\n edits: plugins.map((entry) => ({ operation: ConfigEditOperation.ADD_PLUGIN, plugin: entry.artifact.package })),\n extensions: new Map(plugins.map(({ artifact, manifest }) => [artifact.package, { package: artifact.package, version: artifact.version, manifest }])),\n })\n const failed = outcomes.find((outcome) => !outcome.applied)\n if (failed && failed.edit.operation === ConfigEditOperation.ADD_PLUGIN)\n throw new Diagnostics.Error({\n code: Diagnostics.code.unknown,\n severity: 'error',\n message: `Could not add ${failed.edit.plugin} to ${KUBB_CONFIG_FILENAME}: ${failed.reason}`,\n help: `Run kubb init without that plugin, then add it with kubb add.`,\n })\n return source\n}\n\n/** Generates from the config at `configPath` without reporters, and returns how many files it wrote. */\nasync function firstRun(configPath: string): Promise<number> {\n const { configs } = await getConfigs({ configPath })\n let files = 0\n for (const config of configs) {\n const result = await createKubb(config).generate()\n if (!result.success) throw new Error(result.diagnostics.flatMap((diagnostic) => (diagnostic.severity === 'error' ? [diagnostic.message] : [])).join('\\n'))\n files += result.files.length\n }\n return files\n}\n\n/** The command that runs `kubb generate`: the `generate` script when it runs Kubb, otherwise `npx kubb generate`. */\nfunction generateCommand({ packageManager, script, watch }: { packageManager: PackageManagerInfo; script: string | undefined; watch: boolean }): string {\n if (script !== 'kubb generate') return `npx kubb generate${watch ? ' --watch' : ''}`\n const { command, args } = resolveCommand(packageManager.agent, 'run', watch ? ['generate', '--watch'] : ['generate'])!\n return [command, ...args].join(' ')\n}\n\n/**\n * Runs the Kubb setup wizard: detects the package manager and specs, asks for the spec, plugins, and\n * output folder, shows the config for review, then installs, writes `kubb.config.ts`, adds a\n * `generate` script, and runs the first generation.\n * Pass `yes: true` to skip all prompts and print one line per step.\n */\nexport async function run({ yes, input: inputFlag, output: outputFlag, plugins: pluginsFlag, dryRun }: InitOptions): Promise<void> {\n const cwd = process.cwd()\n\n if (!yes) logIntro({ title: isInteractiveRun({ yes, dryRun: dryRun.enabled }) ? undefined : 'Set up Kubb' })\n\n try {\n // Start the registry fetch now but await it only at the plugin step, so the first prompt never waits on the network\n const registry = fetchRegistryIndex({ registry: registryUrl() }).then((entries) =>\n entries.filter((entry) => entry.kind === 'plugin' && !incompatibility(entry.manifest)),\n )\n registry.catch(() => {})\n\n if (!(await exists(path.join(cwd, 'package.json')))) {\n if (!yes) {\n const shouldInit = unwrap(await clack.confirm({ message: 'No package.json found. Would you like to create one?', initialValue: true }))\n if (!shouldInit) cancelAndExit()\n }\n\n const packageManager = await detectPackageManager(cwd)\n await withSpinner({\n message: `Initializing package.json with ${packageManager.name}`,\n promise: initPackageJson(cwd, packageManager),\n done: () => `Created package.json with ${packageManager.name}`,\n failed: 'Could not create package.json',\n plain: yes,\n })\n }\n\n const packageManager = await detectPackageManager(cwd)\n const specs = await findSpecFiles(cwd)\n\n if (!yes) {\n logStep(`Package manager ${packageManager.name}`)\n if (specs[0]) {\n const { version: specVersion, operations } = await readSpecInfo(path.join(cwd, specs[0]))\n const details = [\n specs[0].slice(2),\n specVersion ? `${specVersion.startsWith('2') ? 'Swagger' : 'OpenAPI'} ${specVersion}` : undefined,\n operations === undefined ? undefined : pluralize(operations, 'operation'),\n specs.length > 1 ? `+${specs.length - 1} more` : undefined,\n ]\n logStep(`Found ${details.filter(Boolean).join(' · ')}`)\n }\n }\n\n // `--plugins` and `--yes` need the registry before any prompt; the interactive path reads it at the plugin step\n const plugins = pluginsFlag || yes ? await registry : undefined\n const defaultPlugins = (entries: Array<RegistryEntry>) => initDefaults.plugins.flatMap((id) => findPlugin({ plugins: entries, id }) ?? [])\n\n const flagPlugins = pluginsFlag && plugins ? parsePluginsFlag({ plugins, value: pluginsFlag }) : undefined\n\n let choices: Choices = {\n inputPath: inputFlag ?? specs[0] ?? initDefaults.inputPath,\n outputPath: outputFlag ?? initDefaults.outputPath,\n plugins: flagPlugins ?? (plugins ? defaultPlugins(plugins) : []),\n }\n if (yes && !choices.plugins.length) {\n throw new Error('The registry has no default plugin. Pass --plugins to choose one.')\n }\n\n async function askInput(current: string): Promise<string> {\n const choice = specs.length\n ? unwrap(\n await clack.select({\n message: 'Which spec should Kubb read?',\n options: [\n ...specs.map((spec) => ({ value: spec, label: spec, hint: 'found in this repo' })),\n { value: 'url', label: 'A URL' },\n { value: 'file', label: 'Another file' },\n ],\n initialValue: specs.includes(current) ? current : isHttpUrl(current) ? 'url' : 'file',\n }),\n )\n : isHttpUrl(current)\n ? 'url'\n : 'file'\n if (specs.includes(choice)) return choice\n const isUrl = choice === 'url'\n const initial = isUrl === isHttpUrl(current) && !specs.includes(current) ? current : undefined\n return unwrap(\n await clack.text({\n message: isUrl ? 'Spec URL' : 'Spec path',\n placeholder: isUrl ? 'https://example.com/openapi.yaml' : initDefaults.inputPath,\n initialValue: initial,\n defaultValue: isUrl ? undefined : initDefaults.inputPath,\n validate: (value) => {\n if (isUrl && !isHttpUrl(value ?? '')) return 'Enter an http(s) URL'\n },\n }),\n )\n }\n\n async function askPlugins(previous: Array<RegistryEntry>): Promise<Array<RegistryEntry>> {\n const plugins = await registry\n const current = previous.length ? previous : defaultPlugins(plugins)\n const width = Math.max(...plugins.map((entry) => entry.manifest.displayName.length))\n const nameWidth = Math.max(...plugins.map((entry) => entry.manifest.name.length))\n const values = unwrap(\n await clack.multiselect({\n message: 'What should Kubb generate?',\n options: plugins.map(({ id, manifest }) => ({\n value: id,\n label: `${manifest.displayName.padEnd(width)} ${styleText('dim', manifest.name.padEnd(nameWidth))}`.trimEnd(),\n })),\n initialValues: current.map((entry) => entry.id),\n required: true,\n }),\n )\n return plugins.filter((entry) => values.includes(entry.id))\n }\n\n // Flags for all three choices leave nothing to ask or review, as before the review step existed\n const answered = yes || Boolean(inputFlag && outputFlag && pluginsFlag)\n if (!answered) {\n let firstPass = true\n while (true) {\n // The first pass skips the questions a flag answered; \"Change a choice\" asks them all again.\n choices = {\n inputPath: firstPass && inputFlag ? inputFlag : await askInput(choices.inputPath),\n plugins: firstPass && flagPlugins ? flagPlugins : await askPlugins(choices.plugins),\n outputPath:\n firstPass && outputFlag\n ? outputFlag\n : unwrap(await clack.text({ message: 'Output folder', placeholder: choices.outputPath, defaultValue: choices.outputPath })),\n }\n firstPass = false\n const missing = missingPluginDependencies(choices.plugins.map((entry) => entry.manifest))\n if (missing.length) {\n logWarn(`${missing.join('\\n')}\\nAdd the missing plugins.`)\n continue\n }\n const config = buildConfig(choices)\n const packages = [KUBB_PACKAGE_NAME, ...choices.plugins.map((entry) => entry.artifact.package)]\n logStep(`Review ${KUBB_CONFIG_FILENAME}`)\n logBlock([...config.trimEnd().split('\\n'), '', `${styleText('dim', 'Installs')} ${packages.join(' ')} with ${packageManager.name}`])\n const configExists = await exists(path.join(cwd, KUBB_CONFIG_FILENAME))\n const confirmed = unwrap(\n await clack.select({\n message: configExists ? `${KUBB_CONFIG_FILENAME} exists. Overwrite it?` : 'Create it?',\n options: [\n { value: true, label: 'Yes' },\n { value: false, label: 'Change a choice' },\n ],\n }),\n )\n if (confirmed) break\n }\n }\n\n // Check the selection against the plugins' manifests before installing anything\n const missing = missingPluginDependencies(choices.plugins.map((entry) => entry.manifest))\n if (missing.length) {\n throw new Diagnostics.Error({\n code: Diagnostics.code.missingDependency,\n severity: 'error',\n message: `${missing.join('\\n')}\\nAdd the missing plugins and run kubb init again.`,\n })\n }\n\n const configPath = path.join(cwd, KUBB_CONFIG_FILENAME)\n if (answered && !yes && (await exists(configPath))) {\n const overwrite = unwrap(await clack.confirm({ message: `${KUBB_CONFIG_FILENAME} exists. Overwrite it?`, initialValue: false }))\n if (!overwrite) cancelAndExit('Keeping existing configuration.')\n }\n\n // Install `kubb` at the running CLI's version and each plugin at the version the registry pins\n const packagesToInstall = [`${KUBB_PACKAGE_NAME}@${version}`, ...choices.plugins.map((entry) => installSpec(entry.artifact))]\n const packageNames = [KUBB_PACKAGE_NAME, ...choices.plugins.map((entry) => entry.artifact.package)]\n const dry = { message: `install ${packagesToInstall.length} packages with ${packageManager.name}` }\n if (yes) {\n await withSpinner({\n message: '',\n promise: dryRun.run(() => installPackages(packagesToInstall, packageManager, cwd), dry),\n done: () => `Installed ${packageNames.join(' ')} with ${packageManager.name}`,\n plain: true,\n })\n } else {\n await installWithSpinner({\n packages: packagesToInstall,\n names: `${packagesToInstall.length} packages`,\n packageManager,\n cwd,\n install: async (packages, packageManager, cwd, onLine) => void (await dryRun.run(() => installPackages(packages, packageManager, cwd, onLine), dry)),\n })\n }\n\n await withSpinner({\n message: `Writing ${KUBB_CONFIG_FILENAME}`,\n promise: dryRun.run(async () => void (await write(configPath, buildConfig(choices))), { message: `write ${KUBB_CONFIG_FILENAME}` }),\n done: () => `Wrote ${KUBB_CONFIG_FILENAME}`,\n failed: `Could not write ${KUBB_CONFIG_FILENAME}`,\n plain: yes,\n })\n\n const scriptAdded = await dryRun.run(() => addGenerateScript(cwd), {\n message: 'add a generate script to package.json',\n resolve: async () => (await generateScript(cwd)) === undefined,\n })\n if (scriptAdded && !yes) logStep('Added \"generate\": \"kubb generate\" to package.json')\n\n const script = scriptAdded ? 'kubb generate' : await generateScript(cwd)\n const runStart = process.hrtime()\n try {\n await dryRun.run(\n () =>\n withSpinner({\n message: 'Running the first generation',\n promise: firstRun(configPath),\n done: (files) =>\n yes\n ? `Generated ${pluralize(files, 'file')} in ${choices.outputPath}`\n : `First run ${pluralize(files, 'file')} in ${choices.outputPath} · ${formatMs(getElapsedMs(runStart))}`,\n failed: 'First run failed',\n plain: yes,\n }),\n { message: 'run the first generation', resolve: () => 0 },\n )\n } catch (error) {\n logError(error instanceof Error ? error.message : String(error))\n const message = `Kubb is set up, but the first run failed. Fix the error, then run ${generateCommand({ packageManager, script, watch: false })}.`\n if (yes) console.log(message)\n else logOutro(styleText('yellow', message))\n process.exitCode = 1\n return\n }\n\n if (yes) {\n console.log(`Kubb is set up. Run ${generateCommand({ packageManager, script, watch: false })} after changing the spec.`)\n return\n }\n logOutro(`${styleText('green', '✓ Kubb is set up')}\\n ${styleText('dim', 'Next')} ${generateCommand({ packageManager, script, watch: true })}`)\n } catch (error) {\n logError(styleText('red', 'An error occurred during initialization'))\n if (error instanceof Error) {\n logError(error.message)\n }\n process.exit(1)\n }\n}\n\nexport const command = defineWithTypes<{ extensions: DryRunExtensions }>()({\n name: 'init',\n description: 'Set up a config, install plugins, and run the first generation.',\n examples: [\n 'kubb init',\n 'kubb init --yes',\n 'kubb init --input ./openapi.yaml --output ./src/gen --plugins plugin-ts,plugin-zod',\n 'kubb init --yes --input ./openapi.yaml --plugins ts,zod --output src/api',\n 'kubb init --plugins plugin-ts,plugin-axios,plugin-react-query',\n 'kubb init --yes --dry-run',\n ].join('\\n'),\n toKebab: true,\n args: {\n yes: {\n type: 'boolean',\n description: 'Skip prompts and use the detected spec, the default plugin, and the default output folder',\n short: 'y',\n default: false,\n },\n input: {\n type: 'string',\n description: 'Path to the OpenAPI specification',\n short: 'i',\n metavar: 'path',\n },\n output: {\n type: 'string',\n description: 'Output directory for generated files',\n short: 'o',\n metavar: 'path',\n },\n plugins: {\n type: 'string',\n description:\n 'Comma-separated Kubb registry ids of the plugins to add, the same ids `kubb add` takes (plugin-ts, plugin-zod, acme/plugin-x), or short names (ts, zod)',\n metavar: 'plugin-ts,plugin-zod,...',\n },\n },\n run: ({ values, extensions }) => run({ yes: values.yes, input: values.input, output: values.output, plugins: values.plugins, dryRun: extensions[dryRunId] }),\n})\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;AACA,SAAgB,mBAAmB,EAAE,WAAW,cAAiE;CAC/G,OAAO;;;YAGG,UAAU;;aAET,WAAW;;;;;;AAMxB;;ACoBA,SAAS,cAAc,UAAU,uBAA8B;CAC7DA,eAAM,OAAO,OAAO;CACpBC,aAAAA,QAAQ,KAAK,CAAC;AAChB;AAEA,SAAS,OAAU,OAA8B;CAC/C,IAAID,eAAM,SAAS,KAAK,GAAG,cAAc;CACzC,OAAO;AACT;;AAiCA,SAAS,YAAY,EAAE,WAAW,YAAY,WAA4B;CACxE,MAAM,EAAE,QAAQ,aAAaE,mBAAAA,WAAW;EACtC,QAAQ,mBAAmB;GAAE;GAAW;EAAW,CAAC;EACpD,OAAO,QAAQ,KAAK,WAAW;GAAE,WAAWC,mBAAAA,oBAAoB;GAAY,QAAQ,MAAM,SAAS;EAAQ,EAAE;EAC7G,YAAY,IAAI,IAAI,QAAQ,KAAK,EAAE,UAAU,eAAe,CAAC,SAAS,SAAS;GAAE,SAAS,SAAS;GAAS,SAAS,SAAS;GAAS;EAAS,CAAC,CAAC,CAAC;CACrJ,CAAC;CACD,MAAM,SAAS,SAAS,MAAM,YAAY,CAAC,QAAQ,OAAO;CAC1D,IAAI,UAAU,OAAO,KAAK,cAAcA,mBAAAA,oBAAoB,YAC1D,MAAM,IAAIC,WAAAA,YAAY,MAAM;EAC1B,MAAMA,WAAAA,YAAY,KAAK;EACvB,UAAU;EACV,SAAS,iBAAiB,OAAO,KAAK,OAAO,MAAMC,eAAAA,qBAAqB,IAAI,OAAO;EACnF,MAAM;CACR,CAAC;CACH,OAAO;AACT;;AAGA,eAAe,SAAS,YAAqC;CAC3D,MAAM,EAA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N,aAAa;GACb,OAAO;GACP,SAAS;EACX;EACA,SAAS;GACP,MAAM;GACN,aACE;GACF,SAAS;EACX;CACF;CACA,MAAM,EAAE,QAAQ,iBAAiB,IAAI;EAAE,KAAK,OAAO;EAAK,OAAO,OAAO;EAAO,QAAQ,OAAO;EAAQ,SAAS,OAAO;EAAS,QAAQ,WAAWC,sBAAAA;CAAU,CAAC;AAC7J,CAAC"}
|
|
1
|
+
{"version":3,"file":"run-C9PwQp2D.cjs","names":["clack","process","editConfig","ConfigEditOperation","Diagnostics","KUBB_CONFIG_FILENAME","getConfigs","createKubb","resolveCommand","logIntro","isInteractiveRun","fetchRegistryIndex","registryUrl","incompatibility","exists","path","detectPackageManager","withSpinner","initPackageJson","findSpecFiles","logStep","readSpecInfo","pluralize","initDefaults","findPlugin","parsePluginsFlag","isHttpUrl","styleText","missingPluginDependencies","logWarn","KUBB_PACKAGE_NAME","logBlock","version","installSpec","installPackages","installWithSpinner","write","addGenerateScript","generateScript","formatMs","getElapsedMs","logError","logOutro","defineWithTypes","dryRunId"],"sources":["../../../internals/shared/src/init.ts","../src/runners/init/run.ts"],"sourcesContent":["/** The `kubb.config.ts` `kubb init` writes before `kubb add` puts each plugin in. */\nexport function generateConfigFile({ inputPath, outputPath }: { inputPath: string; outputPath: string }): string {\n return `import { defineConfig } from 'kubb/config'\n\nexport default defineConfig({\n input: '${inputPath}',\n output: {\n path: '${outputPath}',\n clean: true,\n },\n plugins: [],\n})\n`\n}\n","import path from 'node:path'\nimport process from 'node:process'\nimport { styleText } from 'node:util'\nimport * as clack from '@clack/prompts'\nimport type { DryRunExtension } from '@gunshi/plugin-dryrun'\nimport { defineWithTypes } from 'gunshi'\nimport { resolveCommand } from 'package-manager-detector'\nimport { ConfigEditOperation, editConfig, generateConfigFile, initDefaults, KUBB_CONFIG_FILENAME, KUBB_PACKAGE_NAME } from '@internals/shared'\nimport { exists, formatMs, getElapsedMs, write } from '@internals/utils'\nimport { createKubb, Diagnostics, type RegistryEntry } from '@kubb/core'\nimport { dryRunId, type DryRunExtensions } from '../../commands/shared.ts'\nimport { getConfigs } from '../../config.ts'\nimport { isHttpUrl, pluralize } from '../../ui/text.ts'\nimport { isInteractiveRun, logIntro, logOutro } from '../../ui/intro.ts'\nimport { logBlock, logError, logStep, logWarn } from '../../ui/log.ts'\nimport { withSpinner } from '../../ui/spinner.ts'\nimport { fetchRegistryIndex, incompatibility, installSpec, registryUrl } from '../../utils/registry.ts'\nimport { installWithSpinner } from '../installWithSpinner.ts'\nimport {\n addGenerateScript,\n detectPackageManager,\n findPlugin,\n findSpecFiles,\n generateScript,\n initPackageJson,\n installPackages,\n missingPluginDependencies,\n type PackageManagerInfo,\n parsePluginsFlag,\n readSpecInfo,\n} from './utils.ts'\nimport { version } from '../../../package.json'\n\nfunction cancelAndExit(message = 'Operation canceled.'): never {\n clack.cancel(message)\n process.exit(0)\n}\n\nfunction unwrap<T>(value: T): Exclude<T, symbol> {\n if (clack.isCancel(value)) cancelAndExit()\n return value as Exclude<T, symbol>\n}\n\ntype InitOptions = {\n /**\n * When `true`, skips all interactive prompts and uses the detected or default values.\n */\n yes: boolean\n /**\n * Input path flag value from `--input`. When provided, skips the input prompt.\n */\n input?: string\n /**\n * Output directory flag value from `--output`. When provided, skips the output prompt.\n */\n output?: string\n /**\n * Comma-separated plugin list from `--plugins`, e.g. `'plugin-ts,zod'`. When provided, skips the plugin selection prompt.\n */\n plugins?: string\n /**\n * Dry-run extension from `@gunshi/plugin-dryrun`. When enabled, package installation, file\n * writes, and the first run are skipped.\n */\n dryRun: DryRunExtension\n}\n\ntype Choices = {\n inputPath: string\n outputPath: string\n plugins: Array<RegistryEntry>\n}\n\n/** The full `kubb.config.ts` for `choices`, with each plugin added the way `kubb add` adds it. */\nfunction buildConfig({ inputPath, outputPath, plugins }: Choices): string {\n const { source, outcomes } = editConfig({\n source: generateConfigFile({ inputPath, outputPath }),\n edits: plugins.map((entry) => ({ operation: ConfigEditOperation.ADD_PLUGIN, plugin: entry.artifact.package })),\n extensions: new Map(plugins.map(({ artifact, manifest }) => [artifact.package, { package: artifact.package, version: artifact.version, manifest }])),\n })\n const failed = outcomes.find((outcome) => !outcome.applied)\n if (failed && failed.edit.operation === ConfigEditOperation.ADD_PLUGIN)\n throw new Diagnostics.Error({\n code: Diagnostics.code.unknown,\n severity: 'error',\n message: `Could not add ${failed.edit.plugin} to ${KUBB_CONFIG_FILENAME}: ${failed.reason}`,\n help: `Run kubb init without that plugin, then add it with kubb add.`,\n })\n return source\n}\n\n/** Generates from the config at `configPath` without reporters, and returns how many files it wrote. */\nasync function firstRun(configPath: string): Promise<number> {\n const { configs } = await getConfigs({ configPath })\n let files = 0\n for (const config of configs) {\n const result = await createKubb(config).generate()\n if (!result.success) throw new Error(result.diagnostics.flatMap((diagnostic) => (diagnostic.severity === 'error' ? [diagnostic.message] : [])).join('\\n'))\n files += result.files.length\n }\n return files\n}\n\n/** The command that runs `kubb generate`: the `generate` script when it runs Kubb, otherwise `npx kubb generate`. */\nfunction generateCommand({ packageManager, script, watch }: { packageManager: PackageManagerInfo; script: string | undefined; watch: boolean }): string {\n if (script !== 'kubb generate') return `npx kubb generate${watch ? ' --watch' : ''}`\n const { command, args } = resolveCommand(packageManager.agent, 'run', watch ? ['generate', '--watch'] : ['generate'])!\n return [command, ...args].join(' ')\n}\n\n/**\n * Runs the Kubb setup wizard: detects the package manager and specs, asks for the spec, plugins, and\n * output folder, shows the config for review, then installs, writes `kubb.config.ts`, adds a\n * `generate` script, and runs the first generation.\n * Pass `yes: true` to skip all prompts and print one line per step.\n */\nexport async function run({ yes, input: inputFlag, output: outputFlag, plugins: pluginsFlag, dryRun }: InitOptions): Promise<void> {\n const cwd = process.cwd()\n\n if (!yes) logIntro({ title: isInteractiveRun({ yes, dryRun: dryRun.enabled }) ? undefined : 'Set up Kubb' })\n\n try {\n // Start the registry fetch now but await it only at the plugin step, so the first prompt never waits on the network\n const registry = fetchRegistryIndex({ registry: registryUrl() }).then((entries) =>\n entries.filter((entry) => entry.kind === 'plugin' && !incompatibility(entry.manifest)),\n )\n registry.catch(() => {})\n\n if (!(await exists(path.join(cwd, 'package.json')))) {\n if (!yes) {\n const shouldInit = unwrap(await clack.confirm({ message: 'No package.json found. Would you like to create one?', initialValue: true }))\n if (!shouldInit) cancelAndExit()\n }\n\n const packageManager = await detectPackageManager(cwd)\n await withSpinner({\n message: `Initializing package.json with ${packageManager.name}`,\n promise: initPackageJson(cwd, packageManager),\n done: () => `Created package.json with ${packageManager.name}`,\n failed: 'Could not create package.json',\n plain: yes,\n })\n }\n\n const packageManager = await detectPackageManager(cwd)\n const specs = await findSpecFiles(cwd)\n\n if (!yes) {\n logStep(`Package manager ${packageManager.name}`)\n if (specs[0]) {\n const { version: specVersion, operations } = await readSpecInfo(path.join(cwd, specs[0]))\n const details = [\n specs[0].slice(2),\n specVersion ? `${specVersion.startsWith('2') ? 'Swagger' : 'OpenAPI'} ${specVersion}` : undefined,\n operations === undefined ? undefined : pluralize(operations, 'operation'),\n specs.length > 1 ? `+${specs.length - 1} more` : undefined,\n ]\n logStep(`Found ${details.filter(Boolean).join(' · ')}`)\n }\n }\n\n // `--plugins` and `--yes` need the registry before any prompt; the interactive path reads it at the plugin step\n const plugins = pluginsFlag || yes ? await registry : undefined\n const defaultPlugins = (entries: Array<RegistryEntry>) => initDefaults.plugins.flatMap((id) => findPlugin({ plugins: entries, id }) ?? [])\n\n const flagPlugins = pluginsFlag && plugins ? parsePluginsFlag({ plugins, value: pluginsFlag }) : undefined\n\n let choices: Choices = {\n inputPath: inputFlag ?? specs[0] ?? initDefaults.inputPath,\n outputPath: outputFlag ?? initDefaults.outputPath,\n plugins: flagPlugins ?? (plugins ? defaultPlugins(plugins) : []),\n }\n if (yes && !choices.plugins.length) {\n throw new Error('The registry has no default plugin. Pass --plugins to choose one.')\n }\n\n async function askInput(current: string): Promise<string> {\n const choice = specs.length\n ? unwrap(\n await clack.select({\n message: 'Which spec should Kubb read?',\n options: [\n ...specs.map((spec) => ({ value: spec, label: spec, hint: 'found in this repo' })),\n { value: 'url', label: 'A URL' },\n { value: 'file', label: 'Another file' },\n ],\n initialValue: specs.includes(current) ? current : isHttpUrl(current) ? 'url' : 'file',\n }),\n )\n : isHttpUrl(current)\n ? 'url'\n : 'file'\n if (specs.includes(choice)) return choice\n const isUrl = choice === 'url'\n const initial = isUrl === isHttpUrl(current) && !specs.includes(current) ? current : undefined\n return unwrap(\n await clack.text({\n message: isUrl ? 'Spec URL' : 'Spec path',\n placeholder: isUrl ? 'https://example.com/openapi.yaml' : initDefaults.inputPath,\n initialValue: initial,\n defaultValue: isUrl ? undefined : initDefaults.inputPath,\n validate: (value) => {\n if (isUrl && !isHttpUrl(value ?? '')) return 'Enter an http(s) URL'\n },\n }),\n )\n }\n\n async function askPlugins(previous: Array<RegistryEntry>): Promise<Array<RegistryEntry>> {\n const plugins = await registry\n const current = previous.length ? previous : defaultPlugins(plugins)\n const width = Math.max(...plugins.map((entry) => entry.manifest.displayName.length))\n const nameWidth = Math.max(...plugins.map((entry) => entry.manifest.name.length))\n const values = unwrap(\n await clack.multiselect({\n message: 'What should Kubb generate?',\n options: plugins.map(({ id, manifest }) => ({\n value: id,\n label: `${manifest.displayName.padEnd(width)} ${styleText('dim', manifest.name.padEnd(nameWidth))}`.trimEnd(),\n })),\n initialValues: current.map((entry) => entry.id),\n required: true,\n }),\n )\n return plugins.filter((entry) => values.includes(entry.id))\n }\n\n // Flags for all three choices leave nothing to ask or review, as before the review step existed\n const answered = yes || Boolean(inputFlag && outputFlag && pluginsFlag)\n if (!answered) {\n let firstPass = true\n while (true) {\n // The first pass skips the questions a flag answered; \"Change a choice\" asks them all again.\n choices = {\n inputPath: firstPass && inputFlag ? inputFlag : await askInput(choices.inputPath),\n plugins: firstPass && flagPlugins ? flagPlugins : await askPlugins(choices.plugins),\n outputPath:\n firstPass && outputFlag\n ? outputFlag\n : unwrap(await clack.text({ message: 'Output folder', placeholder: choices.outputPath, defaultValue: choices.outputPath })),\n }\n firstPass = false\n const missing = missingPluginDependencies(choices.plugins.map((entry) => entry.manifest))\n if (missing.length) {\n logWarn(`${missing.join('\\n')}\\nAdd the missing plugins.`)\n continue\n }\n const config = buildConfig(choices)\n const packages = [KUBB_PACKAGE_NAME, ...choices.plugins.map((entry) => entry.artifact.package)]\n logStep(`Review ${KUBB_CONFIG_FILENAME}`)\n logBlock([...config.trimEnd().split('\\n'), '', `${styleText('dim', 'Installs')} ${packages.join(' ')} with ${packageManager.name}`])\n const configExists = await exists(path.join(cwd, KUBB_CONFIG_FILENAME))\n const confirmed = unwrap(\n await clack.select({\n message: configExists ? `${KUBB_CONFIG_FILENAME} exists. Overwrite it?` : 'Create it?',\n options: [\n { value: true, label: 'Yes' },\n { value: false, label: 'Change a choice' },\n ],\n }),\n )\n if (confirmed) break\n }\n }\n\n // Check the selection against the plugins' manifests before installing anything\n const missing = missingPluginDependencies(choices.plugins.map((entry) => entry.manifest))\n if (missing.length) {\n throw new Diagnostics.Error({\n code: Diagnostics.code.missingDependency,\n severity: 'error',\n message: `${missing.join('\\n')}\\nAdd the missing plugins and run kubb init again.`,\n })\n }\n\n const configPath = path.join(cwd, KUBB_CONFIG_FILENAME)\n if (answered && !yes && (await exists(configPath))) {\n const overwrite = unwrap(await clack.confirm({ message: `${KUBB_CONFIG_FILENAME} exists. Overwrite it?`, initialValue: false }))\n if (!overwrite) cancelAndExit('Keeping existing configuration.')\n }\n\n // Install `kubb` at the running CLI's version and each plugin at the version the registry pins\n const packagesToInstall = [`${KUBB_PACKAGE_NAME}@${version}`, ...choices.plugins.map((entry) => installSpec(entry.artifact))]\n const packageNames = [KUBB_PACKAGE_NAME, ...choices.plugins.map((entry) => entry.artifact.package)]\n const dry = { message: `install ${packagesToInstall.length} packages with ${packageManager.name}` }\n if (yes) {\n await withSpinner({\n message: '',\n promise: dryRun.run(() => installPackages(packagesToInstall, packageManager, cwd), dry),\n done: () => `Installed ${packageNames.join(' ')} with ${packageManager.name}`,\n plain: true,\n })\n } else {\n await installWithSpinner({\n packages: packagesToInstall,\n names: `${packagesToInstall.length} packages`,\n packageManager,\n cwd,\n install: async (packages, packageManager, cwd, onLine) => void (await dryRun.run(() => installPackages(packages, packageManager, cwd, onLine), dry)),\n })\n }\n\n await withSpinner({\n message: `Writing ${KUBB_CONFIG_FILENAME}`,\n promise: dryRun.run(async () => void (await write(configPath, buildConfig(choices))), { message: `write ${KUBB_CONFIG_FILENAME}` }),\n done: () => `Wrote ${KUBB_CONFIG_FILENAME}`,\n failed: `Could not write ${KUBB_CONFIG_FILENAME}`,\n plain: yes,\n })\n\n const scriptAdded = await dryRun.run(() => addGenerateScript(cwd), {\n message: 'add a generate script to package.json',\n resolve: async () => (await generateScript(cwd)) === undefined,\n })\n if (scriptAdded && !yes) logStep('Added \"generate\": \"kubb generate\" to package.json')\n\n const script = scriptAdded ? 'kubb generate' : await generateScript(cwd)\n const runStart = process.hrtime()\n try {\n await dryRun.run(\n () =>\n withSpinner({\n message: 'Running the first generation',\n promise: firstRun(configPath),\n done: (files) =>\n yes\n ? `Generated ${pluralize(files, 'file')} in ${choices.outputPath}`\n : `First run ${pluralize(files, 'file')} in ${choices.outputPath} · ${formatMs(getElapsedMs(runStart))}`,\n failed: 'First run failed',\n plain: yes,\n }),\n { message: 'run the first generation', resolve: () => 0 },\n )\n } catch (error) {\n logError(error instanceof Error ? error.message : String(error))\n const message = `Kubb is set up, but the first run failed. Fix the error, then run ${generateCommand({ packageManager, script, watch: false })}.`\n if (yes) console.log(message)\n else logOutro(styleText('yellow', message))\n process.exitCode = 1\n return\n }\n\n if (yes) {\n console.log(`Kubb is set up. Run ${generateCommand({ packageManager, script, watch: false })} after changing the spec.`)\n return\n }\n logOutro(`${styleText('green', '✓ Kubb is set up')}\\n ${styleText('dim', 'Next')} ${generateCommand({ packageManager, script, watch: true })}`)\n } catch (error) {\n logError(styleText('red', 'An error occurred during initialization'))\n if (error instanceof Error) {\n logError(error.message)\n }\n process.exit(1)\n }\n}\n\nexport const command = defineWithTypes<{ extensions: DryRunExtensions }>()({\n name: 'init',\n description: 'Set up a config, install plugins, and run the first generation.',\n examples: [\n 'kubb init',\n 'kubb init --yes',\n 'kubb init --input ./openapi.yaml --output ./src/gen --plugins plugin-ts,plugin-zod',\n 'kubb init --yes --input ./openapi.yaml --plugins ts,zod --output src/api',\n 'kubb init --plugins plugin-ts,plugin-axios,plugin-react-query',\n 'kubb init --yes --dry-run',\n ].join('\\n'),\n toKebab: true,\n args: {\n yes: {\n type: 'boolean',\n description: 'Skip prompts and use the detected spec, the default plugin, and the default output folder',\n short: 'y',\n default: false,\n },\n input: {\n type: 'string',\n description: 'Path to the OpenAPI specification',\n short: 'i',\n metavar: 'path',\n },\n output: {\n type: 'string',\n description: 'Output directory for generated files',\n short: 'o',\n metavar: 'path',\n },\n plugins: {\n type: 'string',\n description:\n 'Comma-separated Kubb registry ids of the plugins to add, the same ids `kubb add` takes (plugin-ts, plugin-zod, acme/plugin-x), or short names (ts, zod)',\n metavar: 'plugin-ts,plugin-zod,...',\n },\n },\n run: ({ values, extensions }) => run({ yes: values.yes, input: values.input, output: values.output, plugins: values.plugins, dryRun: extensions[dryRunId] }),\n})\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;AACA,SAAgB,mBAAmB,EAAE,WAAW,cAAiE;CAC/G,OAAO;;;YAGG,UAAU;;aAET,WAAW;;;;;;AAMxB;;ACoBA,SAAS,cAAc,UAAU,uBAA8B;CAC7DA,eAAM,OAAO,OAAO;CACpBC,aAAAA,QAAQ,KAAK,CAAC;AAChB;AAEA,SAAS,OAAU,OAA8B;CAC/C,IAAID,eAAM,SAAS,KAAK,GAAG,cAAc;CACzC,OAAO;AACT;;AAiCA,SAAS,YAAY,EAAE,WAAW,YAAY,WAA4B;CACxE,MAAM,EAAE,QAAQ,aAAaE,mBAAAA,WAAW;EACtC,QAAQ,mBAAmB;GAAE;GAAW;EAAW,CAAC;EACpD,OAAO,QAAQ,KAAK,WAAW;GAAE,WAAWC,mBAAAA,oBAAoB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GAAgB;GAAQ,OAAO;EAAK,CAAC,GAAG;CACnJ,SAAS,OAAO;EACdc,YAAAA,UAAAA,GAASd,UAAAA,UAAAA,CAAU,OAAO,yCAAyC,CAAC;EACpE,IAAI,iBAAiB,OACnBc,YAAAA,SAAS,MAAM,OAAO;EAExBxC,aAAAA,QAAQ,KAAK,CAAC;CAChB;AACF;AAEA,MAAa,WAAA,GAAU0C,OAAAA,gBAAAA,CAAkD,CAAC,CAAC;CACzE,MAAM;CACN,aAAa;CACb,UAAU;EACR;EACA;EACA;EACA;EACA;EACA;CACF,CAAC,CAAC,KAAK,IAAI;CACX,SAAS;CACT,MAAM;EACJ,KAAK;GACH,MAAM;GACN,aAAa;GACb,OAAO;GACP,SAAS;EACX;EACA,OAAO;GACL,MAAM;GACN,aAAa;GACb,OAAO;GACP,SAAS;EACX;EACA,QAAQ;GACN,MAAM;GACN,aAAa;GACb,OAAO;GACP,SAAS;EACX;EACA,SAAS;GACP,MAAM;GACN,aACE;GACF,SAAS;EACX;CACF;CACA,MAAM,EAAE,QAAQ,iBAAiB,IAAI;EAAE,KAAK,OAAO;EAAK,OAAO,OAAO;EAAO,QAAQ,OAAO;EAAQ,SAAS,OAAO;EAAS,QAAQ,WAAWC,sBAAAA;CAAU,CAAC;AAC7J,CAAC"}
|
|
@@ -12,7 +12,7 @@ import { n as withSpinner } from "./spinner-D5DgYSS5.js";
|
|
|
12
12
|
import { a as installSpec, i as incompatibility, r as fetchRegistryIndex, s as registryUrl } from "./registry-BBJpMlM9.js";
|
|
13
13
|
import { t as installWithSpinner } from "./installWithSpinner-RJhWCsgh.js";
|
|
14
14
|
import { a as generateScript, c as missingPluginDependencies, i as findSpecFiles, l as parsePluginsFlag, n as detectPackageManager, o as initPackageJson, r as findPlugin, s as installPackages, t as addGenerateScript, u as readSpecInfo } from "./utils-DnmjcKb0.js";
|
|
15
|
-
import { t as version } from "./package-
|
|
15
|
+
import { t as version } from "./package-YxLU4Yha.js";
|
|
16
16
|
import { styleText } from "node:util";
|
|
17
17
|
import { defineWithTypes } from "gunshi";
|
|
18
18
|
import process from "node:process";
|
|
@@ -369,4 +369,4 @@ const command = defineWithTypes()({
|
|
|
369
369
|
});
|
|
370
370
|
export { command, run };
|
|
371
371
|
|
|
372
|
-
//# sourceMappingURL=run-
|
|
372
|
+
//# sourceMappingURL=run-CGEX3q1b.js.map
|