@kubb/cli 5.8.3 → 5.8.4
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-BOCR2q1g.js → Telemetry-Ci7sRy6A.js} +2 -2
- package/dist/{Telemetry-BOCR2q1g.js.map → Telemetry-Ci7sRy6A.js.map} +1 -1
- package/dist/{Telemetry-D1M0d8PT.cjs → Telemetry-DKccmt8g.cjs} +2 -2
- package/dist/{Telemetry-D1M0d8PT.cjs.map → Telemetry-DKccmt8g.cjs.map} +1 -1
- package/dist/{background-1fPYMKIh.cjs → background-B7VAPM7b.cjs} +2 -2
- package/dist/{background-1fPYMKIh.cjs.map → background-B7VAPM7b.cjs.map} +1 -1
- package/dist/background-CATamspG.js +1 -0
- package/dist/{background-lBbQYvN7.js → background-CnSPyAn7.js} +2 -2
- package/dist/{background-lBbQYvN7.js.map → background-CnSPyAn7.js.map} +1 -1
- package/dist/{commands-VS9f9all.cjs → commands-CLUcjHHU.cjs} +3 -3
- package/dist/{commands-VS9f9all.cjs.map → commands-CLUcjHHU.cjs.map} +1 -1
- package/dist/{commands-DCwzlFGA.js → commands-Cgmj9PsM.js} +3 -3
- package/dist/{commands-DCwzlFGA.js.map → commands-Cgmj9PsM.js.map} +1 -1
- package/dist/index.cjs +15 -15
- package/dist/index.js +15 -15
- package/dist/{registry-DjGepXb0.js → registry-B7BvdrGE.js} +6 -2
- package/dist/registry-B7BvdrGE.js.map +1 -0
- package/dist/{registry-CCKUL3ps.cjs → registry-DER9aRyg.cjs} +11 -1
- package/dist/registry-DER9aRyg.cjs.map +1 -0
- package/dist/{run-CNiUPnC7.js → run-99Go42ib.js} +2 -2
- package/dist/{run-CNiUPnC7.js.map → run-99Go42ib.js.map} +1 -1
- package/dist/{run-mIZ7hJVc.js → run-9oIapU5y.js} +3 -3
- package/dist/{run-mIZ7hJVc.js.map → run-9oIapU5y.js.map} +1 -1
- package/dist/{run-CkIxVyjD.js → run-BSQJrncc.js} +2 -2
- package/dist/{run-CkIxVyjD.js.map → run-BSQJrncc.js.map} +1 -1
- package/dist/{run-DrUd6OfI.cjs → run-BnCdDjXH.cjs} +3 -3
- package/dist/{run-DrUd6OfI.cjs.map → run-BnCdDjXH.cjs.map} +1 -1
- package/dist/{run-C4IHvWT_.cjs → run-C5P5_H0R.cjs} +3 -3
- package/dist/run-C5P5_H0R.cjs.map +1 -0
- package/dist/{run-BKkuOyne.cjs → run-CMkKa1rU.cjs} +2 -2
- package/dist/{run-BKkuOyne.cjs.map → run-CMkKa1rU.cjs.map} +1 -1
- package/dist/{run-C31KZ8zp.cjs → run-CQKXIa2D.cjs} +2 -2
- package/dist/{run-C31KZ8zp.cjs.map → run-CQKXIa2D.cjs.map} +1 -1
- package/dist/{run-BF_nhSiJ.cjs → run-ClLBHOpl.cjs} +2 -2
- package/dist/{run-BF_nhSiJ.cjs.map → run-ClLBHOpl.cjs.map} +1 -1
- package/dist/{run-BaFyksnF.cjs → run-CnBJroZW.cjs} +2 -2
- package/dist/{run-BaFyksnF.cjs.map → run-CnBJroZW.cjs.map} +1 -1
- package/dist/{run-B9wWJSSx.js → run-DRR30f0e.js} +3 -3
- package/dist/run-DRR30f0e.js.map +1 -0
- package/dist/{run-CDS3EWEN.js → run-Ey756UCd.js} +2 -2
- package/dist/{run-CDS3EWEN.js.map → run-Ey756UCd.js.map} +1 -1
- package/dist/{run-DjINtbfD.js → run-IkpyXtut.js} +2 -2
- package/dist/{run-DjINtbfD.js.map → run-IkpyXtut.js.map} +1 -1
- package/dist/{run-DVIqUt1x.cjs → run-VAkf24Cw.cjs} +3 -3
- package/dist/run-VAkf24Cw.cjs.map +1 -0
- package/dist/{run-BURZ4hDs.js → run-yb2R1vt0.js} +3 -3
- package/dist/run-yb2R1vt0.js.map +1 -0
- package/dist/{snapshot-DgsBHsOb.js → snapshot-2q9d9Dqg.js} +3 -3
- package/dist/{snapshot-DgsBHsOb.js.map → snapshot-2q9d9Dqg.js.map} +1 -1
- package/dist/{snapshot-CQcQ5L6B.cjs → snapshot-CXplfGXC.cjs} +3 -3
- package/dist/{snapshot-CQcQ5L6B.cjs.map → snapshot-CXplfGXC.cjs.map} +1 -1
- package/dist/studioWorker.js +2 -2
- package/package.json +7 -7
- package/dist/background-BreCsKLJ.js +0 -1
- package/dist/registry-CCKUL3ps.cjs.map +0 -1
- package/dist/registry-DjGepXb0.js.map +0 -1
- package/dist/run-B9wWJSSx.js.map +0 -1
- package/dist/run-BURZ4hDs.js.map +0 -1
- package/dist/run-C4IHvWT_.cjs.map +0 -1
- package/dist/run-DVIqUt1x.cjs.map +0 -1
|
@@ -2,7 +2,7 @@ import "./rolldown-runtime-CRm0XQPb.js";
|
|
|
2
2
|
import { t as getErrorMessage } from "./errors-DmC83ALX.js";
|
|
3
3
|
import { t as findConfigFile } from "./config-DAdYwK_D.js";
|
|
4
4
|
import { a as logInfo, d as logWarn, i as logError, l as logStep, o as logIntro, r as logBlock, s as logOutro } from "./output-B9Yw7vL0.js";
|
|
5
|
-
import {
|
|
5
|
+
import { i as installSpec, o as registryUrl, r as incompatibility, s as toRegistryId, t as fetchRegistryDetail } from "./registry-B7BvdrGE.js";
|
|
6
6
|
import { i as installPackages, t as detectPackageManager } from "./utils-Dhx5PMpD.js";
|
|
7
7
|
import { styleText } from "node:util";
|
|
8
8
|
import process from "node:process";
|
|
@@ -62,7 +62,7 @@ async function run({ id: input, configPath, yes, install }) {
|
|
|
62
62
|
const { artifact, manifest } = detail;
|
|
63
63
|
const problem = incompatibility(manifest);
|
|
64
64
|
if (problem) throw new Error(problem);
|
|
65
|
-
const spec =
|
|
65
|
+
const spec = installSpec(artifact);
|
|
66
66
|
const configFile = manifest.kind === "plugin" ? configPath ? path.resolve(configPath) : findConfigFile(cwd) : void 0;
|
|
67
67
|
if (manifest.kind === "plugin" && !configFile) throw new Error("No kubb.config.ts found. Run `kubb init` first, or pass --config.");
|
|
68
68
|
logInfo(`${styleText("cyan", manifest.displayName)} (${manifest.kind}): ${manifest.description}`);
|
|
@@ -103,4 +103,4 @@ async function run({ id: input, configPath, yes, install }) {
|
|
|
103
103
|
//#endregion
|
|
104
104
|
export { run };
|
|
105
105
|
|
|
106
|
-
//# sourceMappingURL=run-
|
|
106
|
+
//# sourceMappingURL=run-yb2R1vt0.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"run-yb2R1vt0.js","names":[],"sources":["../src/runners/add/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 { getErrorMessage } from '@internals/utils'\nimport type { ExtensionManifest, RegistryDetail } from '@kubb/core'\nimport { findConfigFile } from '../../config.ts'\nimport { logBlock, logError, logInfo, logIntro, logOutro, logStep, logWarn } from '../../loggers/output.ts'\nimport { fetchRegistryDetail, incompatibility, installSpec, registryUrl, toRegistryId } from '../../utils/registry.ts'\nimport { detectPackageManager, installPackages } from '../init/utils.ts'\n\nexport type AddOptions = {\n /**\n * `owner/slug`, or a bare `slug` for an official extension.\n */\n id: string\n configPath?: string\n yes: boolean\n install: boolean\n}\n\n/** The import and the `defineConfig` property to merge into `kubb.config.ts` by hand. */\nexport function toSnippet({ artifact, manifest }: Pick<RegistryDetail, 'artifact' | 'manifest'>): string {\n const call = `${manifest.export}()`\n const property: Record<ExtensionManifest['kind'], string> = {\n plugin: `plugins: [..., ${call}],`,\n adapter: `adapter: ${call},`,\n parser: `parsers: [..., ${call}],`,\n }\n return [`import { ${manifest.export} } from '${artifact.package}'`, '', property[manifest.kind]].join('\\n')\n}\n\n/** Adds the plugin call and its import to the config file. Returns why it could not, or `undefined`. */\nasync function addToConfig({ detail, configFile }: { detail: RegistryDetail; configFile: string }): Promise<string | undefined> {\n const { artifact, manifest } = detail\n try {\n const { writeConfigEdits } = await import('@kubb/studio')\n const { outcomes } = await writeConfigEdits({\n filePath: configFile,\n edits: [{ operation: 'add-plugin', plugin: artifact.package, importName: manifest.export }],\n extensions: new Map([[artifact.package, { package: artifact.package, version: artifact.version, manifest }]]),\n })\n return outcomes[0]?.applied ? undefined : (outcomes[0]?.reason ?? 'the config file was not changed')\n } catch (error) {\n return getErrorMessage(error)\n }\n}\n\n/**\n * Installs an extension from the Kubb registry at its reviewed version and, for a plugin, adds it to\n * `kubb.config.ts`. Refuses when the running Kubb or Node.js version is outside its compatibility.\n */\nexport async function run({ id: input, configPath, yes, install }: AddOptions): Promise<void> {\n const cwd = process.cwd()\n logIntro({ title: styleText('bgCyan', styleText('black', ' Kubb Add ')) })\n\n try {\n const registry = registryUrl()\n const detail = await fetchRegistryDetail({ id: toRegistryId(input), registry })\n const { artifact, manifest } = detail\n\n const problem = incompatibility(manifest)\n if (problem) throw new Error(problem)\n\n const spec = installSpec(artifact)\n const configFile = manifest.kind === 'plugin' ? (configPath ? path.resolve(configPath) : findConfigFile(cwd)) : undefined\n if (manifest.kind === 'plugin' && !configFile) throw new Error('No kubb.config.ts found. Run `kubb init` first, or pass --config.')\n\n logInfo(`${styleText('cyan', manifest.displayName)} (${manifest.kind}): ${manifest.description}`)\n logBlock([\n install ? `Install ${styleText('cyan', spec)} as a dev dependency` : `Skip installing ${spec}`,\n configFile\n ? `Add ${styleText('cyan', `${manifest.export}()`)} to ${path.relative(cwd, configFile) || configFile}`\n : `Print the ${manifest.kind} snippet to add`,\n ])\n\n const confirmed = yes || (await clack.confirm({ message: 'Continue?', initialValue: true }))\n if (clack.isCancel(confirmed) || !confirmed) {\n clack.cancel('Operation canceled.')\n return\n }\n\n if (install) {\n const packageManager = detectPackageManager(cwd)\n logStep(`Installing ${spec} with ${packageManager.name}`)\n await installPackages([spec], packageManager, cwd)\n }\n\n const reason = configFile ? await addToConfig({ detail, configFile }) : `add the ${manifest.kind} to your config`\n if (!reason) {\n logOutro(styleText('green', install ? `Added ${spec}` : `Added ${manifest.export}() to the config. Install ${spec} to use it.`))\n return\n }\n\n if (configFile) logWarn(`Could not edit ${configFile}: ${reason}`)\n logBlock(['Add the import to your Kubb config and merge the property into its defineConfig call:', '', toSnippet(detail)])\n logOutro(styleText('green', install ? `Installed ${spec}. Add it with the snippet above.` : `Install ${spec} and add the snippet above.`))\n } catch (error) {\n logError(getErrorMessage(error))\n process.exitCode = 1\n }\n}\n"],"mappings":";;;;;;;;;;;;AAsBA,SAAgB,UAAU,EAAE,UAAU,YAAmE;CACvG,MAAM,OAAO,GAAG,SAAS,OAAO;CAChC,MAAM,WAAsD;EAC1D,QAAQ,kBAAkB,KAAK;EAC/B,SAAS,YAAY,KAAK;EAC1B,QAAQ,kBAAkB,KAAK;CACjC;CACA,OAAO;EAAC,YAAY,SAAS,OAAO,WAAW,SAAS,QAAQ;EAAI;EAAI,SAAS,SAAS;CAAK,CAAC,CAAC,KAAK,IAAI;AAC5G;;AAGA,eAAe,YAAY,EAAE,QAAQ,cAA2F;CAC9H,MAAM,EAAE,UAAU,aAAa;CAC/B,IAAI;EACF,MAAM,EAAE,qBAAqB,MAAM,OAAO;EAC1C,MAAM,EAAE,aAAa,MAAM,iBAAiB;GAC1C,UAAU;GACV,OAAO,CAAC;IAAE,WAAW;IAAc,QAAQ,SAAS;IAAS,YAAY,SAAS;GAAO,CAAC;GAC1F,4BAAY,IAAI,IAAI,CAAC,CAAC,SAAS,SAAS;IAAE,SAAS,SAAS;IAAS,SAAS,SAAS;IAAS;GAAS,CAAC,CAAC,CAAC;EAC9G,CAAC;EACD,OAAO,SAAS,EAAE,EAAE,UAAU,KAAA,IAAa,SAAS,EAAE,EAAE,UAAU;CACpE,SAAS,OAAO;EACd,OAAO,gBAAgB,KAAK;CAC9B;AACF;;;;;AAMA,eAAsB,IAAI,EAAE,IAAI,OAAO,YAAY,KAAK,WAAsC;CAC5F,MAAM,MAAM,QAAQ,IAAI;CACxB,SAAS,EAAE,OAAO,UAAU,UAAU,UAAU,SAAS,YAAY,CAAC,EAAE,CAAC;CAEzE,IAAI;EACF,MAAM,WAAW,YAAY;EAC7B,MAAM,SAAS,MAAM,oBAAoB;GAAE,IA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yF;GAAI,UAAU,MAAM;EAAC,CAAC;EACzH,SAAS,UAAU,SAAS,UAAU,aAAa,KAAK,oCAAoC,WAAW,KAAK,4BAA4B,CAAC;CAC3I,SAAS,OAAO;EACd,SAAS,gBAAgB,KAAK,CAAC;EAC/B,QAAQ,WAAW;CACrB;AACF"}
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import "./rolldown-runtime-CRm0XQPb.js";
|
|
2
|
-
import { i as loadConfigs, s as run } from "./run-
|
|
3
|
-
import { i as runtime } from "./Telemetry-
|
|
2
|
+
import { i as loadConfigs, s as run } from "./run-9oIapU5y.js";
|
|
3
|
+
import { i as runtime } from "./Telemetry-Ci7sRy6A.js";
|
|
4
4
|
import { h as createPlainLogger, r as logBlock } from "./output-B9Yw7vL0.js";
|
|
5
5
|
import { n as setupReporters } from "./reporters-CNZQUlXY.js";
|
|
6
6
|
import { styleText } from "node:util";
|
|
@@ -256,4 +256,4 @@ const runner = async ({ values }) => {
|
|
|
256
256
|
//#endregion
|
|
257
257
|
export { runner };
|
|
258
258
|
|
|
259
|
-
//# sourceMappingURL=snapshot-
|
|
259
|
+
//# sourceMappingURL=snapshot-2q9d9Dqg.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"snapshot-DgsBHsOb.js","names":["logLevel","logLevelMap"],"sources":["../../../internals/utils/src/fs.ts","../src/runners/studio/ci.ts","../src/runners/studio/snapshot.ts"],"sourcesContent":["import { access, mkdir, readFile, rm, writeFile } from 'node:fs/promises'\nimport { dirname, isAbsolute, relative, resolve } from 'node:path'\nimport { runtime } from './runtime.ts'\n\n/**\n * Resolves to `true` when the file or directory at `path` exists.\n * Uses `Bun.file().exists()` when running under Bun, `fs.access` otherwise.\n *\n * @example\n * ```ts\n * if (await exists('./kubb.config.ts')) {\n * const content = await read('./kubb.config.ts')\n * }\n * ```\n */\nexport async function exists(path: string): Promise<boolean> {\n if (runtime.isBun) {\n return Bun.file(path).exists()\n }\n return access(path).then(\n () => true,\n () => false,\n )\n}\n\n/**\n * Reads the file at `path` as a UTF-8 string.\n * Uses `Bun.file().text()` when running under Bun, `fs.readFile` otherwise.\n *\n * @example\n * ```ts\n * const source = await read('./src/Pet.ts')\n * ```\n */\nexport async function read(path: string): Promise<string> {\n if (runtime.isBun) {\n return Bun.file(path).text()\n }\n return readFile(path, { encoding: 'utf8' })\n}\n\ntype WriteOptions = {\n /**\n * Previously read content, or `null` when the file does not exist.\n * Omitting this value reads the file before writing.\n */\n stored?: string | null\n /**\n * When `true`, re-reads the file immediately after writing and throws if the\n * content does not match — useful for catching write failures on unreliable file systems.\n */\n sanity?: boolean\n}\n\n/**\n * Whether `stored` already holds `source`, comparing on the trimmed text rather than the exact\n * bytes. Surrounding whitespace is what a formatter adds and what editors strip, and neither is a\n * reason to rewrite the file.\n *\n * Both sides are trimmed, so a storage that keeps bytes verbatim settles on the same answer as one\n * that normalizes what it stores. Trimming only `stored` would leave a source with leading\n * whitespace rewritten on every build, since the stored copy keeps the whitespace the comparison\n * has already dropped.\n */\nexport function matchesStored({ stored, source }: { stored: string; source: string }): boolean {\n return stored.trim() === source.trim()\n}\n\n/**\n * Writes `data` to `path`, trimming surrounding whitespace and ending the file with a single newline\n * the way prettier, biome, and oxfmt all do.\n * Skips the write when the trimmed content is empty, or when the file already holds that content.\n * Creates any missing parent directories automatically.\n * When `sanity` is `true`, re-reads the file after writing and throws if the content does not match.\n *\n * @example\n * ```ts\n * await write('./src/Pet.ts', source) // writes and returns the trimmed content plus a newline\n * await write('./src/Pet.ts', source) // null — file unchanged\n * await write('./src/Pet.ts', ' ') // null — empty content skipped\n * ```\n */\nexport async function write(path: string, data: string, options: WriteOptions = {}): Promise<string | null> {\n const trimmed = data.trim()\n if (trimmed === '') return null\n\n const content = `${trimmed}\\n`\n const resolved = resolve(path)\n let stored = options.stored\n\n if (stored === undefined) {\n if (runtime.isBun) {\n const file = Bun.file(resolved)\n stored = (await file.exists()) ? await file.text() : null\n } else {\n try {\n stored = await readFile(resolved, { encoding: 'utf-8' })\n } catch {\n /* file doesn't exist yet */\n stored = null\n }\n }\n }\n if (matchesStored({ stored: stored ?? '', source: trimmed })) return null\n\n if (runtime.isBun) {\n await Bun.write(resolved, content)\n return content\n }\n\n // Creating the directory up front costs a syscall per file, and every file after the first in a\n // directory pays it for nothing. Write first and only fall back when the directory is missing,\n // which also stays correct when something removed it mid-run.\n try {\n await writeFile(resolved, content, { encoding: 'utf-8' })\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error\n\n await mkdir(dirname(resolved), { recursive: true })\n await writeFile(resolved, content, { encoding: 'utf-8' })\n }\n\n if (options.sanity) {\n const savedData = await readFile(resolved, { encoding: 'utf-8' })\n if (savedData !== content) {\n throw new Error(`Sanity check failed for ${path}\\n\\nData[${data.length}]:\\n${data}\\n\\nSaved[${savedData.length}]:\\n${savedData}\\n`)\n }\n return savedData\n }\n\n return content\n}\n\n/**\n * Recursively removes `path`. Silently succeeds when `path` does not exist.\n *\n * @example\n * ```ts\n * await clean('./dist')\n * ```\n */\nexport async function clean(path: string): Promise<void> {\n return rm(path, { recursive: true, force: true })\n}\n\n/**\n * Converts a filesystem path to use POSIX (`/`) separators.\n *\n * Most of the codebase compares and composes paths as strings (prefix matching, joining for\n * import specifiers, splitting on `/`). On POSIX `path.resolve` already returns `/`-separated\n * paths, but on Windows it returns `\\`-separated paths, which breaks every such comparison.\n *\n * Routing every path that crosses a module boundary through `toPosixPath` keeps the rest of the\n * code platform-agnostic. The conversion runs unconditionally so Windows-specific behavior is\n * exercisable from POSIX CI.\n *\n * @example\n * toPosixPath('C:\\\\repo\\\\src\\\\pet.ts') // 'C:/repo/src/pet.ts'\n */\nexport function toPosixPath(filePath: string): string {\n return filePath.replaceAll('\\\\', '/')\n}\n\n/**\n * Strips the file extension from a path or file name.\n * Only removes the last `.ext` segment when the dot is not part of a directory name.\n *\n * @example\n * trimExtName('petStore.ts') // 'petStore'\n * trimExtName('/src/models/pet.ts') // '/src/models/pet'\n * trimExtName('/project.v2/gen/pet.ts') // '/project.v2/gen/pet'\n * trimExtName('noExtension') // 'noExtension'\n */\nexport function trimExtName(text: string): string {\n const dotIndex = text.lastIndexOf('.')\n if (dotIndex > 0 && !text.includes('/', dotIndex)) {\n return text.slice(0, dotIndex)\n }\n return text\n}\n\n/**\n * Resolves to `true` when `path` is `parent` itself or nested inside it. Both sides are resolved\n * to absolute paths first, so relative and `..`-containing inputs compare correctly.\n *\n * Guards a destructive or an out-of-tree operation: before wiping an output directory, check that\n * it does not contain the project root, and before loading a path a caller supplied, check that it\n * did not escape the directory it is allowed to read from.\n *\n * @example\n * isPathInside('./src/gen', '.') // true — nested inside the root\n * isPathInside('.', '.') // true — the same directory counts as inside\n * isPathInside('.', './src/gen') // false — the root is not inside its own output\n * isPathInside('../other', '.') // false — escapes the root\n */\nexport function isPathInside(path: string, parent: string): boolean {\n const resolvedPath = resolve(path)\n const resolvedParent = resolve(parent)\n if (resolvedPath === resolvedParent) {\n return true\n }\n\n const rel = relative(resolvedParent, resolvedPath)\n\n return rel !== '' && !rel.startsWith('..') && !isAbsolute(rel)\n}\n","import { readFileSync } from 'node:fs'\nimport process from 'node:process'\n\n/**\n * Stable identity for the CI agent a snapshot run registers or reuses.\n */\nexport type CiContext = {\n /**\n * Fed into the machine token, so the same merge or pull request reuses one agent.\n */\n id: string\n /**\n * Agent display name shown in Studio.\n */\n name: string\n /** The commit this run builds, so the next snapshot can diff against it. */\n commit?: string\n /** The branch a pull request merges into, and the `id` runs on that branch register under. */\n base?: { branch: string; id: string }\n}\n\ntype GithubPullRequest = { number: number; head?: { sha?: string }; base?: { ref?: string } }\n\nfunction readGithubPullRequest(eventPath: string | undefined): GithubPullRequest | undefined {\n if (!eventPath) {\n return undefined\n }\n\n try {\n const event = JSON.parse(readFileSync(eventPath, 'utf8')) as { pull_request?: GithubPullRequest }\n return event.pull_request?.number ? event.pull_request : undefined\n } catch {\n return undefined\n }\n}\n\n/** Reproduces GitLab's `CI_COMMIT_REF_SLUG` for a branch it gives no slug of, like a merge request's target. */\nexport function gitlabRefSlug(ref: string): string {\n return ref\n .toLowerCase()\n .replace(/[^a-z0-9]/gu, '-')\n .slice(0, 63)\n .replace(/^-+|-+$/g, '')\n}\n\n/**\n * Detects the CI provider from its environment variables and derives a stable identity from it.\n * The GitHub row reproduces `gh:<repositoryId>:<prNumber>`, the identity `kubb-labs/action` has\n * always registered agents under, so an existing repository keeps reusing its agent.\n */\nexport function detectCi(env: Record<string, string | undefined> = process.env): CiContext | null {\n if (env.GITHUB_ACTIONS) {\n const pullRequest = readGithubPullRequest(env.GITHUB_EVENT_PATH)\n const repositoryId = env.GITHUB_REPOSITORY_ID ?? env.GITHUB_REPOSITORY ?? ''\n const branch = env.GITHUB_REF?.startsWith('refs/heads/') ? env.GITHUB_REF.slice('refs/heads/'.length) : undefined\n // A branch run is scoped by its ref, which a pull request number never collides with.\n const scope = pullRequest?.number ?? (branch ? `refs/heads/${branch}` : env.GITHUB_RUN_ID) ?? ''\n const baseBranch = pullRequest?.base?.ref\n\n return {\n id: `gh:${repositoryId}:${scope}`,\n name: `${env.GITHUB_REPOSITORY ?? 'github'}#${pullRequest?.number ?? branch ?? scope}`,\n // The head commit, not the merge commit a pull request run checks out.\n commit: pullRequest?.head?.sha ?? env.GITHUB_SHA,\n base: baseBranch ? { branch: baseBranch, id: `gh:${repositoryId}:refs/heads/${baseBranch}` } : undefined,\n }\n }\n\n if (env.GITLAB_CI) {\n const scope = env.CI_MERGE_REQUEST_IID ?? env.CI_COMMIT_REF_SLUG ?? ''\n const baseBranch = env.CI_MERGE_REQUEST_TARGET_BRANCH_NAME\n\n return {\n id: `gl:${env.CI_PROJECT_ID ?? ''}:${scope}`,\n name: `${env.CI_PROJECT_PATH ?? 'gitlab'}#${scope}`,\n commit: env.CI_MERGE_REQUEST_SOURCE_BRANCH_SHA || env.CI_COMMIT_SHA,\n base: baseBranch ? { branch: baseBranch, id: `gl:${env.CI_PROJECT_ID ?? ''}:${gitlabRefSlug(baseBranch)}` } : undefined,\n }\n }\n\n if (env.BITBUCKET_BUILD_NUMBER) {\n const scope = env.BITBUCKET_PR_ID ?? env.BITBUCKET_BRANCH ?? ''\n\n return { id: `bb:${env.BITBUCKET_REPO_UUID ?? ''}:${scope}`, name: `${env.BITBUCKET_REPO_FULL_NAME ?? 'bitbucket'}#${scope}`, commit: env.BITBUCKET_COMMIT }\n }\n\n if (env.CIRCLECI) {\n // Owner-qualified: two projects with the same name under different CircleCI orgs must not\n // collide on one agent, since registering it purges the other project's live sessions.\n const owner = env.CIRCLE_PROJECT_USERNAME ?? ''\n const project = env.CIRCLE_PROJECT_REPONAME ?? 'circleci'\n const scope = env.CIRCLE_PR_NUMBER ?? env.CIRCLE_BRANCH ?? ''\n\n return { id: `circle:${owner}:${project}:${scope}`, name: `${owner ? `${owner}/` : ''}${project}#${scope}`, commit: env.CIRCLE_SHA1 }\n }\n\n return null\n}\n","import { dirname, join } from 'node:path'\nimport process from 'node:process'\nimport { styleText } from 'node:util'\nimport { read } from '@internals/utils'\nimport { cliReporter, Hookable, type KubbHooks, logLevel as logLevelMap } from '@kubb/core'\nimport { createSnapshot, defaultStudioUrl } from '@kubb/studio'\nimport type { BranchSnapshotChanges, PublishedSnapshot, SnapshotChanges } from '@kubb/studio/protocol'\nimport { logBlock } from '../../loggers/output.ts'\nimport { createPlainLogger } from '../../loggers/plainLogger.ts'\nimport setupReporters from '../../loggers/reporters.ts'\nimport { type CiContext, detectCi } from './ci.ts'\nimport { loadConfigs, run, type SnapshotOptions } from './run.ts'\nimport type { command } from '../../commands/studio/snapshot.ts'\nimport type { CommandRunner } from 'gunshi'\n\n/**\n * Walks up from `directory` to the first package.json with a name and a version.\n */\nasync function findPackageJson(directory: string): Promise<{ name: string; version: string }> {\n const packageJson = JSON.parse(await read(join(directory, 'package.json')).catch(() => '{}')) as Partial<{ name: string; version: string }>\n if (packageJson.name && packageJson.version) return { name: packageJson.name, version: packageJson.version }\n\n const parent = dirname(directory)\n if (parent === directory) throw new Error(`No package.json with a name and a version found above ${process.cwd()}`)\n\n return findPackageJson(parent)\n}\n\n/** Reads package.json only for whichever of name/version --name and --version did not supply. */\nasync function resolvePackageMetadata(options: SnapshotOptions): Promise<{ name: string; version: string }> {\n if (options.name && options.packageVersion) return { name: options.name, version: options.packageVersion }\n\n const found = await findPackageJson(process.cwd())\n return { name: options.name ?? found.name, version: options.packageVersion ?? found.version }\n}\n\nfunction resolveToken(options: SnapshotOptions): string {\n const token = options.token ?? process.env.KUBB_TOKEN\n\n if (!token) {\n throw new Error('An organization CI API key is required. Pass --token or set KUBB_TOKEN.')\n }\n\n return token\n}\n\nfunction resolveCiIdentity(options: SnapshotOptions): CiContext {\n const detected = detectCi()\n // A custom --id drops the detected base, since runs on that branch may use a custom id too.\n const ci = options.id ? { id: options.id, name: detected?.name ?? options.id, commit: detected?.commit } : detected\n\n if (!ci) {\n throw new Error('Could not detect a supported CI provider (GitHub Actions, GitLab CI, Bitbucket Pipelines, CircleCI). Pass --id.')\n }\n\n // An explicit --base-id may not name a branch, so it labels the comparison itself.\n const base = options.baseId ? { branch: options.baseId, id: options.baseId } : ci.base\n\n return { ...ci, base: base?.id === ci.id ? undefined : base }\n}\n\nfunction absoluteUrl(studioUrl: string, path: string): string {\n return new URL(path, `${studioUrl}/`).toString()\n}\n\ntype SnapshotResult = {\n id: string\n name: string | null\n version: string | null\n integrity: string | null\n url: string\n snapshotIdUrl: string\n expiresAt: string\n agentUrl: string\n /** What changed since the previous snapshot of this package on this agent. */\n changes?: SnapshotChanges\n /** What differs from the latest snapshot of the base branch, named by `branch`. */\n branchChanges?: BranchSnapshotChanges & { branch: string }\n}\n\nfunction toResult({ studioUrl, snapshot, ci }: { studioUrl: string; snapshot: PublishedSnapshot; ci: CiContext }): SnapshotResult {\n return {\n id: snapshot.id,\n name: snapshot.name,\n version: snapshot.version,\n integrity: snapshot.integrity,\n url: absoluteUrl(studioUrl, snapshot.url),\n snapshotIdUrl: absoluteUrl(studioUrl, snapshot.snapshotIdUrl),\n expiresAt: snapshot.expiresAt,\n agentUrl: absoluteUrl(studioUrl, `/agents/${snapshot.agent.slug ?? snapshot.agent.id}`),\n changes: snapshot.changes,\n branchChanges: snapshot.branchChanges && ci.base ? { ...snapshot.branchChanges, branch: ci.base.branch } : undefined,\n }\n}\n\n/** How many files differ, `against` what. */\nfunction describeChanges(changes: SnapshotChanges, against: string): string {\n const { added, changed, removed } = changes\n\n return added.length + changed.length + removed.length\n ? `${added.length} added, ${changed.length} changed, ${removed.length} removed ${against}`\n : `No changes ${against}`\n}\n\n/** One summary line: how many files changed, and since which run. */\nexport function formatChanges(changes: SnapshotChanges): string {\n if (!changes.base) {\n return 'First snapshot'\n }\n\n return describeChanges(changes, `since ${changes.base.commit?.slice(0, 7) ?? changes.base.createdAt}`)\n}\n\n/** One summary line: how the snapshot differs from the base branch's latest one. */\nexport function formatBranchChanges(changes: BranchSnapshotChanges & { branch: string }): string {\n if (changes.base) return describeChanges(changes, `against ${changes.branch}`)\n\n return changes.baseFound ? `No snapshot of ${changes.branch} for this package yet` : `No snapshot of ${changes.branch} to compare with`\n}\n\nfunction printSummary(result: SnapshotResult): void {\n logBlock([\n `${styleText('dim', 'Package'.padEnd(10))} ${result.name ?? '(unnamed)'}@${result.version ?? '0.0.0'}`,\n `${styleText('dim', 'Tarball'.padEnd(10))} ${styleText('cyan', result.url)}`,\n `${styleText('dim', 'Agent'.padEnd(10))} ${result.agentUrl}`,\n ...(result.branchChanges ? [`${styleText('dim', 'Branch'.padEnd(10))} ${formatBranchChanges(result.branchChanges)}`] : []),\n ...(result.changes ? [`${styleText('dim', 'Changes'.padEnd(10))} ${formatChanges(result.changes)}`] : []),\n `${styleText('dim', 'Expires'.padEnd(10))} ${result.expiresAt}`,\n ])\n}\n\n/**\n * Generates the project, packs it, and publishes it to Kubb Studio in one request, under the CI\n * agent the run's identity names.\n */\nexport async function snapshot(options: SnapshotOptions): Promise<void> {\n const token = resolveToken(options)\n const { config } = await loadConfigs(options)\n const ci = resolveCiIdentity(options)\n const { name, version: packageVersion } = await resolvePackageMetadata(options)\n const logLevel = logLevelMap[options.logLevel ?? 'info']\n\n const write = options.json ? (line: string) => console.error(line) : (line: string) => console.log(line)\n const hooks = new Hookable<KubbHooks>()\n setupReporters(hooks, { logLevel, reporters: [cliReporter], logger: createPlainLogger(write) })\n const step = (message: string) => {\n if (logLevel > logLevelMap.silent) {\n write(message)\n }\n }\n\n step('Generating the snapshot')\n\n try {\n const published = await createSnapshot({\n studioUrl: options.studioUrl,\n apiKey: token,\n config,\n hooks,\n id: ci.id,\n name: ci.name,\n packageName: name,\n version: packageVersion,\n commit: ci.commit,\n baseId: ci.base?.id,\n })\n const result = toResult({ studioUrl: options.studioUrl, snapshot: published, ci })\n\n step('Snapshot published')\n\n if (options.json) {\n console.log(JSON.stringify(result))\n }\n if (!options.json) {\n printSummary(result)\n }\n } catch (error) {\n step('Snapshot failed')\n throw error\n }\n}\n\nexport const runner: CommandRunner<{ args: typeof command.args; extensions: {} }> = async ({ values }) => {\n const options: SnapshotOptions = {\n configPath: values.config,\n studioUrl: values.url ?? defaultStudioUrl,\n logLevel: values.logLevel,\n token: values.token,\n id: values.id,\n baseId: values.baseId,\n name: values.name,\n packageVersion: values.packageVersion,\n json: values.json,\n }\n await run({ options, action: () => snapshot(options), json: options.json })\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;AAkCA,eAAsB,KAAK,MAA+B;CACxD,IAAI,QAAQ,OACV,OAAO,IAAI,KAAK,IAAI,CAAC,CAAC,KAAK;CAE7B,OAAO,SAAS,MAAM,EAAE,UAAU,OAAO,CAAC;AAC5C;;;AChBA,SAAS,sBAAsB,WAA8D;CAC3F,IAAI,CAAC,WACH;CAGF,IAAI;EACF,MAAM,QAAQ,KAAK,MAAM,aAAa,WAAW,MAAM,CAAC;EACxD,OAAO,MAAM,cAAc,SAAS,MAAM,eAAe,KAAA;CAC3D,QAAQ;EACN;CACF;AACF;;AAGA,SAAgB,cA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,IAAID,aAAWC,SAAY,QACzB,MAAM,OAAO;CAEjB;CAEA,KAAK,yBAAyB;CAE9B,IAAI;EACF,MAAM,YAAY,MAAM,eAAe;GACrC,WAAW,QAAQ;GACnB,QAAQ;GACR;GACA;GACA,IAAI,GAAG;GACP,MAAM,GAAG;GACT,aAAa;GACb,SAAS;GACT,QAAQ,GAAG;GACX,QAAQ,GAAG,MAAM;EACnB,CAAC;EACD,MAAM,SAAS,SAAS;GAAE,WAAW,QAAQ;GAAW,UAAU;GAAW;EAAG,CAAC;EAEjF,KAAK,oBAAoB;EAEzB,IAAI,QAAQ,MACV,QAAQ,IAAI,KAAK,UAAU,MAAM,CAAC;EAEpC,IAAI,CAAC,QAAQ,MACX,aAAa,MAAM;CAEvB,SAAS,OAAO;EACd,KAAK,iBAAiB;EACtB,MAAM;CACR;AACF;AAEA,MAAa,SAAuE,OAAO,EAAE,aAAa;CACxG,MAAM,UAA2B;EAC/B,YAAY,OAAO;EACnB,WAAW,OAAO,OAAO;EACzB,UAAU,OAAO;EACjB,OAAO,OAAO;EACd,IAAI,OAAO;EACX,QAAQ,OAAO;EACf,MAAM,OAAO;EACb,gBAAgB,OAAO;EACvB,MAAM,OAAO;CACf;CACA,MAAM,IAAI;EAAE;EAAS,cAAc,SAAS,OAAO;EAAG,MAAM,QAAQ;CAAK,CAAC;AAC5E"}
|
|
1
|
+
{"version":3,"file":"snapshot-2q9d9Dqg.js","names":["logLevel","logLevelMap"],"sources":["../../../internals/utils/src/fs.ts","../src/runners/studio/ci.ts","../src/runners/studio/snapshot.ts"],"sourcesContent":["import { access, mkdir, readFile, rm, writeFile } from 'node:fs/promises'\nimport { dirname, isAbsolute, relative, resolve } from 'node:path'\nimport { runtime } from './runtime.ts'\n\n/**\n * Resolves to `true` when the file or directory at `path` exists.\n * Uses `Bun.file().exists()` when running under Bun, `fs.access` otherwise.\n *\n * @example\n * ```ts\n * if (await exists('./kubb.config.ts')) {\n * const content = await read('./kubb.config.ts')\n * }\n * ```\n */\nexport async function exists(path: string): Promise<boolean> {\n if (runtime.isBun) {\n return Bun.file(path).exists()\n }\n return access(path).then(\n () => true,\n () => false,\n )\n}\n\n/**\n * Reads the file at `path` as a UTF-8 string.\n * Uses `Bun.file().text()` when running under Bun, `fs.readFile` otherwise.\n *\n * @example\n * ```ts\n * const source = await read('./src/Pet.ts')\n * ```\n */\nexport async function read(path: string): Promise<string> {\n if (runtime.isBun) {\n return Bun.file(path).text()\n }\n return readFile(path, { encoding: 'utf8' })\n}\n\ntype WriteOptions = {\n /**\n * Previously read content, or `null` when the file does not exist.\n * Omitting this value reads the file before writing.\n */\n stored?: string | null\n /**\n * When `true`, re-reads the file immediately after writing and throws if the\n * content does not match — useful for catching write failures on unreliable file systems.\n */\n sanity?: boolean\n}\n\n/**\n * Whether `stored` already holds `source`, comparing on the trimmed text rather than the exact\n * bytes. Surrounding whitespace is what a formatter adds and what editors strip, and neither is a\n * reason to rewrite the file.\n *\n * Both sides are trimmed, so a storage that keeps bytes verbatim settles on the same answer as one\n * that normalizes what it stores. Trimming only `stored` would leave a source with leading\n * whitespace rewritten on every build, since the stored copy keeps the whitespace the comparison\n * has already dropped.\n */\nexport function matchesStored({ stored, source }: { stored: string; source: string }): boolean {\n return stored.trim() === source.trim()\n}\n\n/**\n * Writes `data` to `path`, trimming surrounding whitespace and ending the file with a single newline\n * the way prettier, biome, and oxfmt all do.\n * Skips the write when the trimmed content is empty, or when the file already holds that content.\n * Creates any missing parent directories automatically.\n * When `sanity` is `true`, re-reads the file after writing and throws if the content does not match.\n *\n * @example\n * ```ts\n * await write('./src/Pet.ts', source) // writes and returns the trimmed content plus a newline\n * await write('./src/Pet.ts', source) // null — file unchanged\n * await write('./src/Pet.ts', ' ') // null — empty content skipped\n * ```\n */\nexport async function write(path: string, data: string, options: WriteOptions = {}): Promise<string | null> {\n const trimmed = data.trim()\n if (trimmed === '') return null\n\n const content = `${trimmed}\\n`\n const resolved = resolve(path)\n let stored = options.stored\n\n if (stored === undefined) {\n if (runtime.isBun) {\n const file = Bun.file(resolved)\n stored = (await file.exists()) ? await file.text() : null\n } else {\n try {\n stored = await readFile(resolved, { encoding: 'utf-8' })\n } catch {\n /* file doesn't exist yet */\n stored = null\n }\n }\n }\n if (matchesStored({ stored: stored ?? '', source: trimmed })) return null\n\n if (runtime.isBun) {\n await Bun.write(resolved, content)\n return content\n }\n\n // Creating the directory up front costs a syscall per file, and every file after the first in a\n // directory pays it for nothing. Write first and only fall back when the directory is missing,\n // which also stays correct when something removed it mid-run.\n try {\n await writeFile(resolved, content, { encoding: 'utf-8' })\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error\n\n await mkdir(dirname(resolved), { recursive: true })\n await writeFile(resolved, content, { encoding: 'utf-8' })\n }\n\n if (options.sanity) {\n const savedData = await readFile(resolved, { encoding: 'utf-8' })\n if (savedData !== content) {\n throw new Error(`Sanity check failed for ${path}\\n\\nData[${data.length}]:\\n${data}\\n\\nSaved[${savedData.length}]:\\n${savedData}\\n`)\n }\n return savedData\n }\n\n return content\n}\n\n/**\n * Recursively removes `path`. Silently succeeds when `path` does not exist.\n *\n * @example\n * ```ts\n * await clean('./dist')\n * ```\n */\nexport async function clean(path: string): Promise<void> {\n return rm(path, { recursive: true, force: true })\n}\n\n/**\n * Converts a filesystem path to use POSIX (`/`) separators.\n *\n * Most of the codebase compares and composes paths as strings (prefix matching, joining for\n * import specifiers, splitting on `/`). On POSIX `path.resolve` already returns `/`-separated\n * paths, but on Windows it returns `\\`-separated paths, which breaks every such comparison.\n *\n * Routing every path that crosses a module boundary through `toPosixPath` keeps the rest of the\n * code platform-agnostic. The conversion runs unconditionally so Windows-specific behavior is\n * exercisable from POSIX CI.\n *\n * @example\n * toPosixPath('C:\\\\repo\\\\src\\\\pet.ts') // 'C:/repo/src/pet.ts'\n */\nexport function toPosixPath(filePath: string): string {\n return filePath.replaceAll('\\\\', '/')\n}\n\n/**\n * Strips the file extension from a path or file name.\n * Only removes the last `.ext` segment when the dot is not part of a directory name.\n *\n * @example\n * trimExtName('petStore.ts') // 'petStore'\n * trimExtName('/src/models/pet.ts') // '/src/models/pet'\n * trimExtName('/project.v2/gen/pet.ts') // '/project.v2/gen/pet'\n * trimExtName('noExtension') // 'noExtension'\n */\nexport function trimExtName(text: string): string {\n const dotIndex = text.lastIndexOf('.')\n if (dotIndex > 0 && !text.includes('/', dotIndex)) {\n return text.slice(0, dotIndex)\n }\n return text\n}\n\n/**\n * Resolves to `true` when `path` is `parent` itself or nested inside it. Both sides are resolved\n * to absolute paths first, so relative and `..`-containing inputs compare correctly.\n *\n * Guards a destructive or an out-of-tree operation: before wiping an output directory, check that\n * it does not contain the project root, and before loading a path a caller supplied, check that it\n * did not escape the directory it is allowed to read from.\n *\n * @example\n * isPathInside('./src/gen', '.') // true — nested inside the root\n * isPathInside('.', '.') // true — the same directory counts as inside\n * isPathInside('.', './src/gen') // false — the root is not inside its own output\n * isPathInside('../other', '.') // false — escapes the root\n */\nexport function isPathInside(path: string, parent: string): boolean {\n const resolvedPath = resolve(path)\n const resolvedParent = resolve(parent)\n if (resolvedPath === resolvedParent) {\n return true\n }\n\n const rel = relative(resolvedParent, resolvedPath)\n\n return rel !== '' && !rel.startsWith('..') && !isAbsolute(rel)\n}\n","import { readFileSync } from 'node:fs'\nimport process from 'node:process'\n\n/**\n * Stable identity for the CI agent a snapshot run registers or reuses.\n */\nexport type CiContext = {\n /**\n * Fed into the machine token, so the same merge or pull request reuses one agent.\n */\n id: string\n /**\n * Agent display name shown in Studio.\n */\n name: string\n /** The commit this run builds, so the next snapshot can diff against it. */\n commit?: string\n /** The branch a pull request merges into, and the `id` runs on that branch register under. */\n base?: { branch: string; id: string }\n}\n\ntype GithubPullRequest = { number: number; head?: { sha?: string }; base?: { ref?: string } }\n\nfunction readGithubPullRequest(eventPath: string | undefined): GithubPullRequest | undefined {\n if (!eventPath) {\n return undefined\n }\n\n try {\n const event = JSON.parse(readFileSync(eventPath, 'utf8')) as { pull_request?: GithubPullRequest }\n return event.pull_request?.number ? event.pull_request : undefined\n } catch {\n return undefined\n }\n}\n\n/** Reproduces GitLab's `CI_COMMIT_REF_SLUG` for a branch it gives no slug of, like a merge request's target. */\nexport function gitlabRefSlug(ref: string): string {\n return ref\n .toLowerCase()\n .replace(/[^a-z0-9]/gu, '-')\n .slice(0, 63)\n .replace(/^-+|-+$/g, '')\n}\n\n/**\n * Detects the CI provider from its environment variables and derives a stable identity from it.\n * The GitHub row reproduces `gh:<repositoryId>:<prNumber>`, the identity `kubb-labs/action` has\n * always registered agents under, so an existing repository keeps reusing its agent.\n */\nexport function detectCi(env: Record<string, string | undefined> = process.env): CiContext | null {\n if (env.GITHUB_ACTIONS) {\n const pullRequest = readGithubPullRequest(env.GITHUB_EVENT_PATH)\n const repositoryId = env.GITHUB_REPOSITORY_ID ?? env.GITHUB_REPOSITORY ?? ''\n const branch = env.GITHUB_REF?.startsWith('refs/heads/') ? env.GITHUB_REF.slice('refs/heads/'.length) : undefined\n // A branch run is scoped by its ref, which a pull request number never collides with.\n const scope = pullRequest?.number ?? (branch ? `refs/heads/${branch}` : env.GITHUB_RUN_ID) ?? ''\n const baseBranch = pullRequest?.base?.ref\n\n return {\n id: `gh:${repositoryId}:${scope}`,\n name: `${env.GITHUB_REPOSITORY ?? 'github'}#${pullRequest?.number ?? branch ?? scope}`,\n // The head commit, not the merge commit a pull request run checks out.\n commit: pullRequest?.head?.sha ?? env.GITHUB_SHA,\n base: baseBranch ? { branch: baseBranch, id: `gh:${repositoryId}:refs/heads/${baseBranch}` } : undefined,\n }\n }\n\n if (env.GITLAB_CI) {\n const scope = env.CI_MERGE_REQUEST_IID ?? env.CI_COMMIT_REF_SLUG ?? ''\n const baseBranch = env.CI_MERGE_REQUEST_TARGET_BRANCH_NAME\n\n return {\n id: `gl:${env.CI_PROJECT_ID ?? ''}:${scope}`,\n name: `${env.CI_PROJECT_PATH ?? 'gitlab'}#${scope}`,\n commit: env.CI_MERGE_REQUEST_SOURCE_BRANCH_SHA || env.CI_COMMIT_SHA,\n base: baseBranch ? { branch: baseBranch, id: `gl:${env.CI_PROJECT_ID ?? ''}:${gitlabRefSlug(baseBranch)}` } : undefined,\n }\n }\n\n if (env.BITBUCKET_BUILD_NUMBER) {\n const scope = env.BITBUCKET_PR_ID ?? env.BITBUCKET_BRANCH ?? ''\n\n return { id: `bb:${env.BITBUCKET_REPO_UUID ?? ''}:${scope}`, name: `${env.BITBUCKET_REPO_FULL_NAME ?? 'bitbucket'}#${scope}`, commit: env.BITBUCKET_COMMIT }\n }\n\n if (env.CIRCLECI) {\n // Owner-qualified: two projects with the same name under different CircleCI orgs must not\n // collide on one agent, since registering it purges the other project's live sessions.\n const owner = env.CIRCLE_PROJECT_USERNAME ?? ''\n const project = env.CIRCLE_PROJECT_REPONAME ?? 'circleci'\n const scope = env.CIRCLE_PR_NUMBER ?? env.CIRCLE_BRANCH ?? ''\n\n return { id: `circle:${owner}:${project}:${scope}`, name: `${owner ? `${owner}/` : ''}${project}#${scope}`, commit: env.CIRCLE_SHA1 }\n }\n\n return null\n}\n","import { dirname, join } from 'node:path'\nimport process from 'node:process'\nimport { styleText } from 'node:util'\nimport { read } from '@internals/utils'\nimport { cliReporter, Hookable, type KubbHooks, logLevel as logLevelMap } from '@kubb/core'\nimport { createSnapshot, defaultStudioUrl } from '@kubb/studio'\nimport type { BranchSnapshotChanges, PublishedSnapshot, SnapshotChanges } from '@kubb/studio/protocol'\nimport { logBlock } from '../../loggers/output.ts'\nimport { createPlainLogger } from '../../loggers/plainLogger.ts'\nimport setupReporters from '../../loggers/reporters.ts'\nimport { type CiContext, detectCi } from './ci.ts'\nimport { loadConfigs, run, type SnapshotOptions } from './run.ts'\nimport type { command } from '../../commands/studio/snapshot.ts'\nimport type { CommandRunner } from 'gunshi'\n\n/**\n * Walks up from `directory` to the first package.json with a name and a version.\n */\nasync function findPackageJson(directory: string): Promise<{ name: string; version: string }> {\n const packageJson = JSON.parse(await read(join(directory, 'package.json')).catch(() => '{}')) as Partial<{ name: string; version: string }>\n if (packageJson.name && packageJson.version) return { name: packageJson.name, version: packageJson.version }\n\n const parent = dirname(directory)\n if (parent === directory) throw new Error(`No package.json with a name and a version found above ${process.cwd()}`)\n\n return findPackageJson(parent)\n}\n\n/** Reads package.json only for whichever of name/version --name and --version did not supply. */\nasync function resolvePackageMetadata(options: SnapshotOptions): Promise<{ name: string; version: string }> {\n if (options.name && options.packageVersion) return { name: options.name, version: options.packageVersion }\n\n const found = await findPackageJson(process.cwd())\n return { name: options.name ?? found.name, version: options.packageVersion ?? found.version }\n}\n\nfunction resolveToken(options: SnapshotOptions): string {\n const token = options.token ?? process.env.KUBB_TOKEN\n\n if (!token) {\n throw new Error('An organization CI API key is required. Pass --token or set KUBB_TOKEN.')\n }\n\n return token\n}\n\nfunction resolveCiIdentity(options: SnapshotOptions): CiContext {\n const detected = detectCi()\n // A custom --id drops the detected base, since runs on that branch may use a custom id too.\n const ci = options.id ? { id: options.id, name: detected?.name ?? options.id, commit: detected?.commit } : detected\n\n if (!ci) {\n throw new Error('Could not detect a supported CI provider (GitHub Actions, GitLab CI, Bitbucket Pipelines, CircleCI). Pass --id.')\n }\n\n // An explicit --base-id may not name a branch, so it labels the comparison itself.\n const base = options.baseId ? { branch: options.baseId, id: options.baseId } : ci.base\n\n return { ...ci, base: base?.id === ci.id ? undefined : base }\n}\n\nfunction absoluteUrl(studioUrl: string, path: string): string {\n return new URL(path, `${studioUrl}/`).toString()\n}\n\ntype SnapshotResult = {\n id: string\n name: string | null\n version: string | null\n integrity: string | null\n url: string\n snapshotIdUrl: string\n expiresAt: string\n agentUrl: string\n /** What changed since the previous snapshot of this package on this agent. */\n changes?: SnapshotChanges\n /** What differs from the latest snapshot of the base branch, named by `branch`. */\n branchChanges?: BranchSnapshotChanges & { branch: string }\n}\n\nfunction toResult({ studioUrl, snapshot, ci }: { studioUrl: string; snapshot: PublishedSnapshot; ci: CiContext }): SnapshotResult {\n return {\n id: snapshot.id,\n name: snapshot.name,\n version: snapshot.version,\n integrity: snapshot.integrity,\n url: absoluteUrl(studioUrl, snapshot.url),\n snapshotIdUrl: absoluteUrl(studioUrl, snapshot.snapshotIdUrl),\n expiresAt: snapshot.expiresAt,\n agentUrl: absoluteUrl(studioUrl, `/agents/${snapshot.agent.slug ?? snapshot.agent.id}`),\n changes: snapshot.changes,\n branchChanges: snapshot.branchChanges && ci.base ? { ...snapshot.branchChanges, branch: ci.base.branch } : undefined,\n }\n}\n\n/** How many files differ, `against` what. */\nfunction describeChanges(changes: SnapshotChanges, against: string): string {\n const { added, changed, removed } = changes\n\n return added.length + changed.length + removed.length\n ? `${added.length} added, ${changed.length} changed, ${removed.length} removed ${against}`\n : `No changes ${against}`\n}\n\n/** One summary line: how many files changed, and since which run. */\nexport function formatChanges(changes: SnapshotChanges): string {\n if (!changes.base) {\n return 'First snapshot'\n }\n\n return describeChanges(changes, `since ${changes.base.commit?.slice(0, 7) ?? changes.base.createdAt}`)\n}\n\n/** One summary line: how the snapshot differs from the base branch's latest one. */\nexport function formatBranchChanges(changes: BranchSnapshotChanges & { branch: string }): string {\n if (changes.base) return describeChanges(changes, `against ${changes.branch}`)\n\n return changes.baseFound ? `No snapshot of ${changes.branch} for this package yet` : `No snapshot of ${changes.branch} to compare with`\n}\n\nfunction printSummary(result: SnapshotResult): void {\n logBlock([\n `${styleText('dim', 'Package'.padEnd(10))} ${result.name ?? '(unnamed)'}@${result.version ?? '0.0.0'}`,\n `${styleText('dim', 'Tarball'.padEnd(10))} ${styleText('cyan', result.url)}`,\n `${styleText('dim', 'Agent'.padEnd(10))} ${result.agentUrl}`,\n ...(result.branchChanges ? [`${styleText('dim', 'Branch'.padEnd(10))} ${formatBranchChanges(result.branchChanges)}`] : []),\n ...(result.changes ? [`${styleText('dim', 'Changes'.padEnd(10))} ${formatChanges(result.changes)}`] : []),\n `${styleText('dim', 'Expires'.padEnd(10))} ${result.expiresAt}`,\n ])\n}\n\n/**\n * Generates the project, packs it, and publishes it to Kubb Studio in one request, under the CI\n * agent the run's identity names.\n */\nexport async function snapshot(options: SnapshotOptions): Promise<void> {\n const token = resolveToken(options)\n const { config } = await loadConfigs(options)\n const ci = resolveCiIdentity(options)\n const { name, version: packageVersion } = await resolvePackageMetadata(options)\n const logLevel = logLevelMap[options.logLevel ?? 'info']\n\n const write = options.json ? (line: string) => console.error(line) : (line: string) => console.log(line)\n const hooks = new Hookable<KubbHooks>()\n setupReporters(hooks, { logLevel, reporters: [cliReporter], logger: createPlainLogger(write) })\n const step = (message: string) => {\n if (logLevel > logLevelMap.silent) {\n write(message)\n }\n }\n\n step('Generating the snapshot')\n\n try {\n const published = await createSnapshot({\n studioUrl: options.studioUrl,\n apiKey: token,\n config,\n hooks,\n id: ci.id,\n name: ci.name,\n packageName: name,\n version: packageVersion,\n commit: ci.commit,\n baseId: ci.base?.id,\n })\n const result = toResult({ studioUrl: options.studioUrl, snapshot: published, ci })\n\n step('Snapshot published')\n\n if (options.json) {\n console.log(JSON.stringify(result))\n }\n if (!options.json) {\n printSummary(result)\n }\n } catch (error) {\n step('Snapshot failed')\n throw error\n }\n}\n\nexport const runner: CommandRunner<{ args: typeof command.args; extensions: {} }> = async ({ values }) => {\n const options: SnapshotOptions = {\n configPath: values.config,\n studioUrl: values.url ?? defaultStudioUrl,\n logLevel: values.logLevel,\n token: values.token,\n id: values.id,\n baseId: values.baseId,\n name: values.name,\n packageVersion: values.packageVersion,\n json: values.json,\n }\n await run({ options, action: () => snapshot(options), json: options.json })\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;AAkCA,eAAsB,KAAK,MAA+B;CACxD,IAAI,QAAQ,OACV,OAAO,IAAI,KAAK,IAAI,CAAC,CAAC,KAAK;CAE7B,OAAO,SAAS,MAAM,EAAE,UAAU,OAAO,CAAC;AAC5C;;;AChBA,SAAS,sBAAsB,WAA8D;CAC3F,IAAI,CAAC,WACH;CAGF,IAAI;EACF,MAAM,QAAQ,KAAK,MAAM,aAAa,WAAW,MAAM,CAAC;EACxD,OAAO,M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C,WAAW;EAAG,QAAQ,kBAAkB,KAAK;CAAE,CAAC;CAC9F,MAAM,QAAQ,YAAoB;EAChC,IAAID,aAAWC,SAAY,QACzB,MAAM,OAAO;CAEjB;CAEA,KAAK,yBAAyB;CAE9B,IAAI;EACF,MAAM,YAAY,MAAM,eAAe;GACrC,WAAW,QAAQ;GACnB,QAAQ;GACR;GACA;GACA,IAAI,GAAG;GACP,MAAM,GAAG;GACT,aAAa;GACb,SAAS;GACT,QAAQ,GAAG;GACX,QAAQ,GAAG,MAAM;EACnB,CAAC;EACD,MAAM,SAAS,SAAS;GAAE,WAAW,QAAQ;GAAW,UAAU;GAAW;EAAG,CAAC;EAEjF,KAAK,oBAAoB;EAEzB,IAAI,QAAQ,MACV,QAAQ,IAAI,KAAK,UAAU,MAAM,CAAC;EAEpC,IAAI,CAAC,QAAQ,MACX,aAAa,MAAM;CAEvB,SAAS,OAAO;EACd,KAAK,iBAAiB;EACtB,MAAM;CACR;AACF;AAEA,MAAa,SAAuE,OAAO,EAAE,aAAa;CACxG,MAAM,UAA2B;EAC/B,YAAY,OAAO;EACnB,WAAW,OAAO,OAAO;EACzB,UAAU,OAAO;EACjB,OAAO,OAAO;EACd,IAAI,OAAO;EACX,QAAQ,OAAO;EACf,MAAM,OAAO;EACb,gBAAgB,OAAO;EACvB,MAAM,OAAO;CACf;CACA,MAAM,IAAI;EAAE;EAAS,cAAc,SAAS,OAAO;EAAG,MAAM,QAAQ;CAAK,CAAC;AAC5E"}
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
const require_agent = require("./agent-DElUuYuy.cjs");
|
|
2
|
-
const require_run = require("./run-
|
|
3
|
-
const require_Telemetry = require("./Telemetry-
|
|
2
|
+
const require_run = require("./run-BnCdDjXH.cjs");
|
|
3
|
+
const require_Telemetry = require("./Telemetry-DKccmt8g.cjs");
|
|
4
4
|
const require_output = require("./output-CWupdozw.cjs");
|
|
5
5
|
const require_reporters = require("./reporters-C5HAypFq.cjs");
|
|
6
6
|
let node_util = require("node:util");
|
|
@@ -257,4 +257,4 @@ const runner = async ({ values }) => {
|
|
|
257
257
|
//#endregion
|
|
258
258
|
exports.runner = runner;
|
|
259
259
|
|
|
260
|
-
//# sourceMappingURL=snapshot-
|
|
260
|
+
//# sourceMappingURL=snapshot-CXplfGXC.cjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"snapshot-CQcQ5L6B.cjs","names":["runtime","readFile","readFileSync","process","join","dirname","process","styleText","loadConfigs","logLevelMap","Hookable","cliReporter","createPlainLogger","createSnapshot","defaultStudioUrl","run"],"sources":["../../../internals/utils/src/fs.ts","../src/runners/studio/ci.ts","../src/runners/studio/snapshot.ts"],"sourcesContent":["import { access, mkdir, readFile, rm, writeFile } from 'node:fs/promises'\nimport { dirname, isAbsolute, relative, resolve } from 'node:path'\nimport { runtime } from './runtime.ts'\n\n/**\n * Resolves to `true` when the file or directory at `path` exists.\n * Uses `Bun.file().exists()` when running under Bun, `fs.access` otherwise.\n *\n * @example\n * ```ts\n * if (await exists('./kubb.config.ts')) {\n * const content = await read('./kubb.config.ts')\n * }\n * ```\n */\nexport async function exists(path: string): Promise<boolean> {\n if (runtime.isBun) {\n return Bun.file(path).exists()\n }\n return access(path).then(\n () => true,\n () => false,\n )\n}\n\n/**\n * Reads the file at `path` as a UTF-8 string.\n * Uses `Bun.file().text()` when running under Bun, `fs.readFile` otherwise.\n *\n * @example\n * ```ts\n * const source = await read('./src/Pet.ts')\n * ```\n */\nexport async function read(path: string): Promise<string> {\n if (runtime.isBun) {\n return Bun.file(path).text()\n }\n return readFile(path, { encoding: 'utf8' })\n}\n\ntype WriteOptions = {\n /**\n * Previously read content, or `null` when the file does not exist.\n * Omitting this value reads the file before writing.\n */\n stored?: string | null\n /**\n * When `true`, re-reads the file immediately after writing and throws if the\n * content does not match — useful for catching write failures on unreliable file systems.\n */\n sanity?: boolean\n}\n\n/**\n * Whether `stored` already holds `source`, comparing on the trimmed text rather than the exact\n * bytes. Surrounding whitespace is what a formatter adds and what editors strip, and neither is a\n * reason to rewrite the file.\n *\n * Both sides are trimmed, so a storage that keeps bytes verbatim settles on the same answer as one\n * that normalizes what it stores. Trimming only `stored` would leave a source with leading\n * whitespace rewritten on every build, since the stored copy keeps the whitespace the comparison\n * has already dropped.\n */\nexport function matchesStored({ stored, source }: { stored: string; source: string }): boolean {\n return stored.trim() === source.trim()\n}\n\n/**\n * Writes `data` to `path`, trimming surrounding whitespace and ending the file with a single newline\n * the way prettier, biome, and oxfmt all do.\n * Skips the write when the trimmed content is empty, or when the file already holds that content.\n * Creates any missing parent directories automatically.\n * When `sanity` is `true`, re-reads the file after writing and throws if the content does not match.\n *\n * @example\n * ```ts\n * await write('./src/Pet.ts', source) // writes and returns the trimmed content plus a newline\n * await write('./src/Pet.ts', source) // null — file unchanged\n * await write('./src/Pet.ts', ' ') // null — empty content skipped\n * ```\n */\nexport async function write(path: string, data: string, options: WriteOptions = {}): Promise<string | null> {\n const trimmed = data.trim()\n if (trimmed === '') return null\n\n const content = `${trimmed}\\n`\n const resolved = resolve(path)\n let stored = options.stored\n\n if (stored === undefined) {\n if (runtime.isBun) {\n const file = Bun.file(resolved)\n stored = (await file.exists()) ? await file.text() : null\n } else {\n try {\n stored = await readFile(resolved, { encoding: 'utf-8' })\n } catch {\n /* file doesn't exist yet */\n stored = null\n }\n }\n }\n if (matchesStored({ stored: stored ?? '', source: trimmed })) return null\n\n if (runtime.isBun) {\n await Bun.write(resolved, content)\n return content\n }\n\n // Creating the directory up front costs a syscall per file, and every file after the first in a\n // directory pays it for nothing. Write first and only fall back when the directory is missing,\n // which also stays correct when something removed it mid-run.\n try {\n await writeFile(resolved, content, { encoding: 'utf-8' })\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error\n\n await mkdir(dirname(resolved), { recursive: true })\n await writeFile(resolved, content, { encoding: 'utf-8' })\n }\n\n if (options.sanity) {\n const savedData = await readFile(resolved, { encoding: 'utf-8' })\n if (savedData !== content) {\n throw new Error(`Sanity check failed for ${path}\\n\\nData[${data.length}]:\\n${data}\\n\\nSaved[${savedData.length}]:\\n${savedData}\\n`)\n }\n return savedData\n }\n\n return content\n}\n\n/**\n * Recursively removes `path`. Silently succeeds when `path` does not exist.\n *\n * @example\n * ```ts\n * await clean('./dist')\n * ```\n */\nexport async function clean(path: string): Promise<void> {\n return rm(path, { recursive: true, force: true })\n}\n\n/**\n * Converts a filesystem path to use POSIX (`/`) separators.\n *\n * Most of the codebase compares and composes paths as strings (prefix matching, joining for\n * import specifiers, splitting on `/`). On POSIX `path.resolve` already returns `/`-separated\n * paths, but on Windows it returns `\\`-separated paths, which breaks every such comparison.\n *\n * Routing every path that crosses a module boundary through `toPosixPath` keeps the rest of the\n * code platform-agnostic. The conversion runs unconditionally so Windows-specific behavior is\n * exercisable from POSIX CI.\n *\n * @example\n * toPosixPath('C:\\\\repo\\\\src\\\\pet.ts') // 'C:/repo/src/pet.ts'\n */\nexport function toPosixPath(filePath: string): string {\n return filePath.replaceAll('\\\\', '/')\n}\n\n/**\n * Strips the file extension from a path or file name.\n * Only removes the last `.ext` segment when the dot is not part of a directory name.\n *\n * @example\n * trimExtName('petStore.ts') // 'petStore'\n * trimExtName('/src/models/pet.ts') // '/src/models/pet'\n * trimExtName('/project.v2/gen/pet.ts') // '/project.v2/gen/pet'\n * trimExtName('noExtension') // 'noExtension'\n */\nexport function trimExtName(text: string): string {\n const dotIndex = text.lastIndexOf('.')\n if (dotIndex > 0 && !text.includes('/', dotIndex)) {\n return text.slice(0, dotIndex)\n }\n return text\n}\n\n/**\n * Resolves to `true` when `path` is `parent` itself or nested inside it. Both sides are resolved\n * to absolute paths first, so relative and `..`-containing inputs compare correctly.\n *\n * Guards a destructive or an out-of-tree operation: before wiping an output directory, check that\n * it does not contain the project root, and before loading a path a caller supplied, check that it\n * did not escape the directory it is allowed to read from.\n *\n * @example\n * isPathInside('./src/gen', '.') // true — nested inside the root\n * isPathInside('.', '.') // true — the same directory counts as inside\n * isPathInside('.', './src/gen') // false — the root is not inside its own output\n * isPathInside('../other', '.') // false — escapes the root\n */\nexport function isPathInside(path: string, parent: string): boolean {\n const resolvedPath = resolve(path)\n const resolvedParent = resolve(parent)\n if (resolvedPath === resolvedParent) {\n return true\n }\n\n const rel = relative(resolvedParent, resolvedPath)\n\n return rel !== '' && !rel.startsWith('..') && !isAbsolute(rel)\n}\n","import { readFileSync } from 'node:fs'\nimport process from 'node:process'\n\n/**\n * Stable identity for the CI agent a snapshot run registers or reuses.\n */\nexport type CiContext = {\n /**\n * Fed into the machine token, so the same merge or pull request reuses one agent.\n */\n id: string\n /**\n * Agent display name shown in Studio.\n */\n name: string\n /** The commit this run builds, so the next snapshot can diff against it. */\n commit?: string\n /** The branch a pull request merges into, and the `id` runs on that branch register under. */\n base?: { branch: string; id: string }\n}\n\ntype GithubPullRequest = { number: number; head?: { sha?: string }; base?: { ref?: string } }\n\nfunction readGithubPullRequest(eventPath: string | undefined): GithubPullRequest | undefined {\n if (!eventPath) {\n return undefined\n }\n\n try {\n const event = JSON.parse(readFileSync(eventPath, 'utf8')) as { pull_request?: GithubPullRequest }\n return event.pull_request?.number ? event.pull_request : undefined\n } catch {\n return undefined\n }\n}\n\n/** Reproduces GitLab's `CI_COMMIT_REF_SLUG` for a branch it gives no slug of, like a merge request's target. */\nexport function gitlabRefSlug(ref: string): string {\n return ref\n .toLowerCase()\n .replace(/[^a-z0-9]/gu, '-')\n .slice(0, 63)\n .replace(/^-+|-+$/g, '')\n}\n\n/**\n * Detects the CI provider from its environment variables and derives a stable identity from it.\n * The GitHub row reproduces `gh:<repositoryId>:<prNumber>`, the identity `kubb-labs/action` has\n * always registered agents under, so an existing repository keeps reusing its agent.\n */\nexport function detectCi(env: Record<string, string | undefined> = process.env): CiContext | null {\n if (env.GITHUB_ACTIONS) {\n const pullRequest = readGithubPullRequest(env.GITHUB_EVENT_PATH)\n const repositoryId = env.GITHUB_REPOSITORY_ID ?? env.GITHUB_REPOSITORY ?? ''\n const branch = env.GITHUB_REF?.startsWith('refs/heads/') ? env.GITHUB_REF.slice('refs/heads/'.length) : undefined\n // A branch run is scoped by its ref, which a pull request number never collides with.\n const scope = pullRequest?.number ?? (branch ? `refs/heads/${branch}` : env.GITHUB_RUN_ID) ?? ''\n const baseBranch = pullRequest?.base?.ref\n\n return {\n id: `gh:${repositoryId}:${scope}`,\n name: `${env.GITHUB_REPOSITORY ?? 'github'}#${pullRequest?.number ?? branch ?? scope}`,\n // The head commit, not the merge commit a pull request run checks out.\n commit: pullRequest?.head?.sha ?? env.GITHUB_SHA,\n base: baseBranch ? { branch: baseBranch, id: `gh:${repositoryId}:refs/heads/${baseBranch}` } : undefined,\n }\n }\n\n if (env.GITLAB_CI) {\n const scope = env.CI_MERGE_REQUEST_IID ?? env.CI_COMMIT_REF_SLUG ?? ''\n const baseBranch = env.CI_MERGE_REQUEST_TARGET_BRANCH_NAME\n\n return {\n id: `gl:${env.CI_PROJECT_ID ?? ''}:${scope}`,\n name: `${env.CI_PROJECT_PATH ?? 'gitlab'}#${scope}`,\n commit: env.CI_MERGE_REQUEST_SOURCE_BRANCH_SHA || env.CI_COMMIT_SHA,\n base: baseBranch ? { branch: baseBranch, id: `gl:${env.CI_PROJECT_ID ?? ''}:${gitlabRefSlug(baseBranch)}` } : undefined,\n }\n }\n\n if (env.BITBUCKET_BUILD_NUMBER) {\n const scope = env.BITBUCKET_PR_ID ?? env.BITBUCKET_BRANCH ?? ''\n\n return { id: `bb:${env.BITBUCKET_REPO_UUID ?? ''}:${scope}`, name: `${env.BITBUCKET_REPO_FULL_NAME ?? 'bitbucket'}#${scope}`, commit: env.BITBUCKET_COMMIT }\n }\n\n if (env.CIRCLECI) {\n // Owner-qualified: two projects with the same name under different CircleCI orgs must not\n // collide on one agent, since registering it purges the other project's live sessions.\n const owner = env.CIRCLE_PROJECT_USERNAME ?? ''\n const project = env.CIRCLE_PROJECT_REPONAME ?? 'circleci'\n const scope = env.CIRCLE_PR_NUMBER ?? env.CIRCLE_BRANCH ?? ''\n\n return { id: `circle:${owner}:${project}:${scope}`, name: `${owner ? `${owner}/` : ''}${project}#${scope}`, commit: env.CIRCLE_SHA1 }\n }\n\n return null\n}\n","import { dirname, join } from 'node:path'\nimport process from 'node:process'\nimport { styleText } from 'node:util'\nimport { read } from '@internals/utils'\nimport { cliReporter, Hookable, type KubbHooks, logLevel as logLevelMap } from '@kubb/core'\nimport { createSnapshot, defaultStudioUrl } from '@kubb/studio'\nimport type { BranchSnapshotChanges, PublishedSnapshot, SnapshotChanges } from '@kubb/studio/protocol'\nimport { logBlock } from '../../loggers/output.ts'\nimport { createPlainLogger } from '../../loggers/plainLogger.ts'\nimport setupReporters from '../../loggers/reporters.ts'\nimport { type CiContext, detectCi } from './ci.ts'\nimport { loadConfigs, run, type SnapshotOptions } from './run.ts'\nimport type { command } from '../../commands/studio/snapshot.ts'\nimport type { CommandRunner } from 'gunshi'\n\n/**\n * Walks up from `directory` to the first package.json with a name and a version.\n */\nasync function findPackageJson(directory: string): Promise<{ name: string; version: string }> {\n const packageJson = JSON.parse(await read(join(directory, 'package.json')).catch(() => '{}')) as Partial<{ name: string; version: string }>\n if (packageJson.name && packageJson.version) return { name: packageJson.name, version: packageJson.version }\n\n const parent = dirname(directory)\n if (parent === directory) throw new Error(`No package.json with a name and a version found above ${process.cwd()}`)\n\n return findPackageJson(parent)\n}\n\n/** Reads package.json only for whichever of name/version --name and --version did not supply. */\nasync function resolvePackageMetadata(options: SnapshotOptions): Promise<{ name: string; version: string }> {\n if (options.name && options.packageVersion) return { name: options.name, version: options.packageVersion }\n\n const found = await findPackageJson(process.cwd())\n return { name: options.name ?? found.name, version: options.packageVersion ?? found.version }\n}\n\nfunction resolveToken(options: SnapshotOptions): string {\n const token = options.token ?? process.env.KUBB_TOKEN\n\n if (!token) {\n throw new Error('An organization CI API key is required. Pass --token or set KUBB_TOKEN.')\n }\n\n return token\n}\n\nfunction resolveCiIdentity(options: SnapshotOptions): CiContext {\n const detected = detectCi()\n // A custom --id drops the detected base, since runs on that branch may use a custom id too.\n const ci = options.id ? { id: options.id, name: detected?.name ?? options.id, commit: detected?.commit } : detected\n\n if (!ci) {\n throw new Error('Could not detect a supported CI provider (GitHub Actions, GitLab CI, Bitbucket Pipelines, CircleCI). Pass --id.')\n }\n\n // An explicit --base-id may not name a branch, so it labels the comparison itself.\n const base = options.baseId ? { branch: options.baseId, id: options.baseId } : ci.base\n\n return { ...ci, base: base?.id === ci.id ? undefined : base }\n}\n\nfunction absoluteUrl(studioUrl: string, path: string): string {\n return new URL(path, `${studioUrl}/`).toString()\n}\n\ntype SnapshotResult = {\n id: string\n name: string | null\n version: string | null\n integrity: string | null\n url: string\n snapshotIdUrl: string\n expiresAt: string\n agentUrl: string\n /** What changed since the previous snapshot of this package on this agent. */\n changes?: SnapshotChanges\n /** What differs from the latest snapshot of the base branch, named by `branch`. */\n branchChanges?: BranchSnapshotChanges & { branch: string }\n}\n\nfunction toResult({ studioUrl, snapshot, ci }: { studioUrl: string; snapshot: PublishedSnapshot; ci: CiContext }): SnapshotResult {\n return {\n id: snapshot.id,\n name: snapshot.name,\n version: snapshot.version,\n integrity: snapshot.integrity,\n url: absoluteUrl(studioUrl, snapshot.url),\n snapshotIdUrl: absoluteUrl(studioUrl, snapshot.snapshotIdUrl),\n expiresAt: snapshot.expiresAt,\n agentUrl: absoluteUrl(studioUrl, `/agents/${snapshot.agent.slug ?? snapshot.agent.id}`),\n changes: snapshot.changes,\n branchChanges: snapshot.branchChanges && ci.base ? { ...snapshot.branchChanges, branch: ci.base.branch } : undefined,\n }\n}\n\n/** How many files differ, `against` what. */\nfunction describeChanges(changes: SnapshotChanges, against: string): string {\n const { added, changed, removed } = changes\n\n return added.length + changed.length + removed.length\n ? `${added.length} added, ${changed.length} changed, ${removed.length} removed ${against}`\n : `No changes ${against}`\n}\n\n/** One summary line: how many files changed, and since which run. */\nexport function formatChanges(changes: SnapshotChanges): string {\n if (!changes.base) {\n return 'First snapshot'\n }\n\n return describeChanges(changes, `since ${changes.base.commit?.slice(0, 7) ?? changes.base.createdAt}`)\n}\n\n/** One summary line: how the snapshot differs from the base branch's latest one. */\nexport function formatBranchChanges(changes: BranchSnapshotChanges & { branch: string }): string {\n if (changes.base) return describeChanges(changes, `against ${changes.branch}`)\n\n return changes.baseFound ? `No snapshot of ${changes.branch} for this package yet` : `No snapshot of ${changes.branch} to compare with`\n}\n\nfunction printSummary(result: SnapshotResult): void {\n logBlock([\n `${styleText('dim', 'Package'.padEnd(10))} ${result.name ?? '(unnamed)'}@${result.version ?? '0.0.0'}`,\n `${styleText('dim', 'Tarball'.padEnd(10))} ${styleText('cyan', result.url)}`,\n `${styleText('dim', 'Agent'.padEnd(10))} ${result.agentUrl}`,\n ...(result.branchChanges ? [`${styleText('dim', 'Branch'.padEnd(10))} ${formatBranchChanges(result.branchChanges)}`] : []),\n ...(result.changes ? [`${styleText('dim', 'Changes'.padEnd(10))} ${formatChanges(result.changes)}`] : []),\n `${styleText('dim', 'Expires'.padEnd(10))} ${result.expiresAt}`,\n ])\n}\n\n/**\n * Generates the project, packs it, and publishes it to Kubb Studio in one request, under the CI\n * agent the run's identity names.\n */\nexport async function snapshot(options: SnapshotOptions): Promise<void> {\n const token = resolveToken(options)\n const { config } = await loadConfigs(options)\n const ci = resolveCiIdentity(options)\n const { name, version: packageVersion } = await resolvePackageMetadata(options)\n const logLevel = logLevelMap[options.logLevel ?? 'info']\n\n const write = options.json ? (line: string) => console.error(line) : (line: string) => console.log(line)\n const hooks = new Hookable<KubbHooks>()\n setupReporters(hooks, { logLevel, reporters: [cliReporter], logger: createPlainLogger(write) })\n const step = (message: string) => {\n if (logLevel > logLevelMap.silent) {\n write(message)\n }\n }\n\n step('Generating the snapshot')\n\n try {\n const published = await createSnapshot({\n studioUrl: options.studioUrl,\n apiKey: token,\n config,\n hooks,\n id: ci.id,\n name: ci.name,\n packageName: name,\n version: packageVersion,\n commit: ci.commit,\n baseId: ci.base?.id,\n })\n const result = toResult({ studioUrl: options.studioUrl, snapshot: published, ci })\n\n step('Snapshot published')\n\n if (options.json) {\n console.log(JSON.stringify(result))\n }\n if (!options.json) {\n printSummary(result)\n }\n } catch (error) {\n step('Snapshot failed')\n throw error\n }\n}\n\nexport const runner: CommandRunner<{ args: typeof command.args; extensions: {} }> = async ({ values }) => {\n const options: SnapshotOptions = {\n configPath: values.config,\n studioUrl: values.url ?? defaultStudioUrl,\n logLevel: values.logLevel,\n token: values.token,\n id: values.id,\n baseId: values.baseId,\n name: values.name,\n packageVersion: values.packageVersion,\n json: values.json,\n }\n await run({ options, action: () => snapshot(options), json: options.json })\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;AAkCA,eAAsB,KAAK,MAA+B;CACxD,IAAIA,kBAAAA,QAAQ,OACV,OAAO,IAAI,KAAK,IAAI,CAAC,CAAC,KAAK;CAE7B,QAAA,GAAOC,iBAAAA,SAAAA,CAAS,MAAM,EAAE,UAAU,OAAO,CAAC;AAC5C;;;AChBA,SAAS,sBAAsB,WAA8D;CAC3F,IAAI,CAAC,WACH;CAGF,IAAI;EACF,MAAM,QAAQ,KAAK,OAAA,GAAMC,QAAAA,aAAAA,CAAa,WAAW,MAAM,CAAC;EACxD,OAAO,MAAM,cAAc,SAAS,MAAM,eAAe,KAAA;CAC3D,QAAQ;EACN;CACF;AACF;;AAGA,SAAgB,cAAc,KAAqB;CACjD,OAAO,IACJ,YAAY,CAAC,CACb,QAAQ,eAAe,GAAG,CAAC,CAC3B,MAAM,GAAG,EAAE,CAAC,CACZ,QAAQ,YAAY,EAAE;AAC3B;;;;;;AAOA,SAAgB,SAAS,MAA0CC,aAAAA,QAAQ,KAAuB;CAChG,IAAI,IAAI,gBAAgB;EACtB,MAAM,cAAc,sBAAsB,IAAI,iBAAiB;EAC/D,MAAM,eAAe,IAAI,wBAAwB,IAAI,qBAAqB;EAC1E,MAAM,SAAS,IAAI,YAAY,WAAW,aAAa,IAAI,IAAI,WAAW,MAAM,EAAoB,IAAI,KAAA;EAExG,MAA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CAAe;GACrC,WAAW,QAAQ;GACnB,QAAQ;GACR;GACA;GACA,IAAI,GAAG;GACP,MAAM,GAAG;GACT,aAAa;GACb,SAAS;GACT,QAAQ,GAAG;GACX,QAAQ,GAAG,MAAM;EACnB,CAAC;EACD,MAAM,SAAS,SAAS;GAAE,WAAW,QAAQ;GAAW,UAAU;GAAW;EAAG,CAAC;EAEjF,KAAK,oBAAoB;EAEzB,IAAI,QAAQ,MACV,QAAQ,IAAI,KAAK,UAAU,MAAM,CAAC;EAEpC,IAAI,CAAC,QAAQ,MACX,aAAa,MAAM;CAEvB,SAAS,OAAO;EACd,KAAK,iBAAiB;EACtB,MAAM;CACR;AACF;AAEA,MAAa,SAAuE,OAAO,EAAE,aAAa;CACxG,MAAM,UAA2B;EAC/B,YAAY,OAAO;EACnB,WAAW,OAAO,OAAOC,aAAAA;EACzB,UAAU,OAAO;EACjB,OAAO,OAAO;EACd,IAAI,OAAO;EACX,QAAQ,OAAO;EACf,MAAM,OAAO;EACb,gBAAgB,OAAO;EACvB,MAAM,OAAO;CACf;CACA,MAAMC,YAAAA,IAAI;EAAE;EAAS,cAAc,SAAS,OAAO;EAAG,MAAM,QAAQ;CAAK,CAAC;AAC5E"}
|
|
1
|
+
{"version":3,"file":"snapshot-CXplfGXC.cjs","names":["runtime","readFile","readFileSync","process","join","dirname","process","styleText","loadConfigs","logLevelMap","Hookable","cliReporter","createPlainLogger","createSnapshot","defaultStudioUrl","run"],"sources":["../../../internals/utils/src/fs.ts","../src/runners/studio/ci.ts","../src/runners/studio/snapshot.ts"],"sourcesContent":["import { access, mkdir, readFile, rm, writeFile } from 'node:fs/promises'\nimport { dirname, isAbsolute, relative, resolve } from 'node:path'\nimport { runtime } from './runtime.ts'\n\n/**\n * Resolves to `true` when the file or directory at `path` exists.\n * Uses `Bun.file().exists()` when running under Bun, `fs.access` otherwise.\n *\n * @example\n * ```ts\n * if (await exists('./kubb.config.ts')) {\n * const content = await read('./kubb.config.ts')\n * }\n * ```\n */\nexport async function exists(path: string): Promise<boolean> {\n if (runtime.isBun) {\n return Bun.file(path).exists()\n }\n return access(path).then(\n () => true,\n () => false,\n )\n}\n\n/**\n * Reads the file at `path` as a UTF-8 string.\n * Uses `Bun.file().text()` when running under Bun, `fs.readFile` otherwise.\n *\n * @example\n * ```ts\n * const source = await read('./src/Pet.ts')\n * ```\n */\nexport async function read(path: string): Promise<string> {\n if (runtime.isBun) {\n return Bun.file(path).text()\n }\n return readFile(path, { encoding: 'utf8' })\n}\n\ntype WriteOptions = {\n /**\n * Previously read content, or `null` when the file does not exist.\n * Omitting this value reads the file before writing.\n */\n stored?: string | null\n /**\n * When `true`, re-reads the file immediately after writing and throws if the\n * content does not match — useful for catching write failures on unreliable file systems.\n */\n sanity?: boolean\n}\n\n/**\n * Whether `stored` already holds `source`, comparing on the trimmed text rather than the exact\n * bytes. Surrounding whitespace is what a formatter adds and what editors strip, and neither is a\n * reason to rewrite the file.\n *\n * Both sides are trimmed, so a storage that keeps bytes verbatim settles on the same answer as one\n * that normalizes what it stores. Trimming only `stored` would leave a source with leading\n * whitespace rewritten on every build, since the stored copy keeps the whitespace the comparison\n * has already dropped.\n */\nexport function matchesStored({ stored, source }: { stored: string; source: string }): boolean {\n return stored.trim() === source.trim()\n}\n\n/**\n * Writes `data` to `path`, trimming surrounding whitespace and ending the file with a single newline\n * the way prettier, biome, and oxfmt all do.\n * Skips the write when the trimmed content is empty, or when the file already holds that content.\n * Creates any missing parent directories automatically.\n * When `sanity` is `true`, re-reads the file after writing and throws if the content does not match.\n *\n * @example\n * ```ts\n * await write('./src/Pet.ts', source) // writes and returns the trimmed content plus a newline\n * await write('./src/Pet.ts', source) // null — file unchanged\n * await write('./src/Pet.ts', ' ') // null — empty content skipped\n * ```\n */\nexport async function write(path: string, data: string, options: WriteOptions = {}): Promise<string | null> {\n const trimmed = data.trim()\n if (trimmed === '') return null\n\n const content = `${trimmed}\\n`\n const resolved = resolve(path)\n let stored = options.stored\n\n if (stored === undefined) {\n if (runtime.isBun) {\n const file = Bun.file(resolved)\n stored = (await file.exists()) ? await file.text() : null\n } else {\n try {\n stored = await readFile(resolved, { encoding: 'utf-8' })\n } catch {\n /* file doesn't exist yet */\n stored = null\n }\n }\n }\n if (matchesStored({ stored: stored ?? '', source: trimmed })) return null\n\n if (runtime.isBun) {\n await Bun.write(resolved, content)\n return content\n }\n\n // Creating the directory up front costs a syscall per file, and every file after the first in a\n // directory pays it for nothing. Write first and only fall back when the directory is missing,\n // which also stays correct when something removed it mid-run.\n try {\n await writeFile(resolved, content, { encoding: 'utf-8' })\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error\n\n await mkdir(dirname(resolved), { recursive: true })\n await writeFile(resolved, content, { encoding: 'utf-8' })\n }\n\n if (options.sanity) {\n const savedData = await readFile(resolved, { encoding: 'utf-8' })\n if (savedData !== content) {\n throw new Error(`Sanity check failed for ${path}\\n\\nData[${data.length}]:\\n${data}\\n\\nSaved[${savedData.length}]:\\n${savedData}\\n`)\n }\n return savedData\n }\n\n return content\n}\n\n/**\n * Recursively removes `path`. Silently succeeds when `path` does not exist.\n *\n * @example\n * ```ts\n * await clean('./dist')\n * ```\n */\nexport async function clean(path: string): Promise<void> {\n return rm(path, { recursive: true, force: true })\n}\n\n/**\n * Converts a filesystem path to use POSIX (`/`) separators.\n *\n * Most of the codebase compares and composes paths as strings (prefix matching, joining for\n * import specifiers, splitting on `/`). On POSIX `path.resolve` already returns `/`-separated\n * paths, but on Windows it returns `\\`-separated paths, which breaks every such comparison.\n *\n * Routing every path that crosses a module boundary through `toPosixPath` keeps the rest of the\n * code platform-agnostic. The conversion runs unconditionally so Windows-specific behavior is\n * exercisable from POSIX CI.\n *\n * @example\n * toPosixPath('C:\\\\repo\\\\src\\\\pet.ts') // 'C:/repo/src/pet.ts'\n */\nexport function toPosixPath(filePath: string): string {\n return filePath.replaceAll('\\\\', '/')\n}\n\n/**\n * Strips the file extension from a path or file name.\n * Only removes the last `.ext` segment when the dot is not part of a directory name.\n *\n * @example\n * trimExtName('petStore.ts') // 'petStore'\n * trimExtName('/src/models/pet.ts') // '/src/models/pet'\n * trimExtName('/project.v2/gen/pet.ts') // '/project.v2/gen/pet'\n * trimExtName('noExtension') // 'noExtension'\n */\nexport function trimExtName(text: string): string {\n const dotIndex = text.lastIndexOf('.')\n if (dotIndex > 0 && !text.includes('/', dotIndex)) {\n return text.slice(0, dotIndex)\n }\n return text\n}\n\n/**\n * Resolves to `true` when `path` is `parent` itself or nested inside it. Both sides are resolved\n * to absolute paths first, so relative and `..`-containing inputs compare correctly.\n *\n * Guards a destructive or an out-of-tree operation: before wiping an output directory, check that\n * it does not contain the project root, and before loading a path a caller supplied, check that it\n * did not escape the directory it is allowed to read from.\n *\n * @example\n * isPathInside('./src/gen', '.') // true — nested inside the root\n * isPathInside('.', '.') // true — the same directory counts as inside\n * isPathInside('.', './src/gen') // false — the root is not inside its own output\n * isPathInside('../other', '.') // false — escapes the root\n */\nexport function isPathInside(path: string, parent: string): boolean {\n const resolvedPath = resolve(path)\n const resolvedParent = resolve(parent)\n if (resolvedPath === resolvedParent) {\n return true\n }\n\n const rel = relative(resolvedParent, resolvedPath)\n\n return rel !== '' && !rel.startsWith('..') && !isAbsolute(rel)\n}\n","import { readFileSync } from 'node:fs'\nimport process from 'node:process'\n\n/**\n * Stable identity for the CI agent a snapshot run registers or reuses.\n */\nexport type CiContext = {\n /**\n * Fed into the machine token, so the same merge or pull request reuses one agent.\n */\n id: string\n /**\n * Agent display name shown in Studio.\n */\n name: string\n /** The commit this run builds, so the next snapshot can diff against it. */\n commit?: string\n /** The branch a pull request merges into, and the `id` runs on that branch register under. */\n base?: { branch: string; id: string }\n}\n\ntype GithubPullRequest = { number: number; head?: { sha?: string }; base?: { ref?: string } }\n\nfunction readGithubPullRequest(eventPath: string | undefined): GithubPullRequest | undefined {\n if (!eventPath) {\n return undefined\n }\n\n try {\n const event = JSON.parse(readFileSync(eventPath, 'utf8')) as { pull_request?: GithubPullRequest }\n return event.pull_request?.number ? event.pull_request : undefined\n } catch {\n return undefined\n }\n}\n\n/** Reproduces GitLab's `CI_COMMIT_REF_SLUG` for a branch it gives no slug of, like a merge request's target. */\nexport function gitlabRefSlug(ref: string): string {\n return ref\n .toLowerCase()\n .replace(/[^a-z0-9]/gu, '-')\n .slice(0, 63)\n .replace(/^-+|-+$/g, '')\n}\n\n/**\n * Detects the CI provider from its environment variables and derives a stable identity from it.\n * The GitHub row reproduces `gh:<repositoryId>:<prNumber>`, the identity `kubb-labs/action` has\n * always registered agents under, so an existing repository keeps reusing its agent.\n */\nexport function detectCi(env: Record<string, string | undefined> = process.env): CiContext | null {\n if (env.GITHUB_ACTIONS) {\n const pullRequest = readGithubPullRequest(env.GITHUB_EVENT_PATH)\n const repositoryId = env.GITHUB_REPOSITORY_ID ?? env.GITHUB_REPOSITORY ?? ''\n const branch = env.GITHUB_REF?.startsWith('refs/heads/') ? env.GITHUB_REF.slice('refs/heads/'.length) : undefined\n // A branch run is scoped by its ref, which a pull request number never collides with.\n const scope = pullRequest?.number ?? (branch ? `refs/heads/${branch}` : env.GITHUB_RUN_ID) ?? ''\n const baseBranch = pullRequest?.base?.ref\n\n return {\n id: `gh:${repositoryId}:${scope}`,\n name: `${env.GITHUB_REPOSITORY ?? 'github'}#${pullRequest?.number ?? branch ?? scope}`,\n // The head commit, not the merge commit a pull request run checks out.\n commit: pullRequest?.head?.sha ?? env.GITHUB_SHA,\n base: baseBranch ? { branch: baseBranch, id: `gh:${repositoryId}:refs/heads/${baseBranch}` } : undefined,\n }\n }\n\n if (env.GITLAB_CI) {\n const scope = env.CI_MERGE_REQUEST_IID ?? env.CI_COMMIT_REF_SLUG ?? ''\n const baseBranch = env.CI_MERGE_REQUEST_TARGET_BRANCH_NAME\n\n return {\n id: `gl:${env.CI_PROJECT_ID ?? ''}:${scope}`,\n name: `${env.CI_PROJECT_PATH ?? 'gitlab'}#${scope}`,\n commit: env.CI_MERGE_REQUEST_SOURCE_BRANCH_SHA || env.CI_COMMIT_SHA,\n base: baseBranch ? { branch: baseBranch, id: `gl:${env.CI_PROJECT_ID ?? ''}:${gitlabRefSlug(baseBranch)}` } : undefined,\n }\n }\n\n if (env.BITBUCKET_BUILD_NUMBER) {\n const scope = env.BITBUCKET_PR_ID ?? env.BITBUCKET_BRANCH ?? ''\n\n return { id: `bb:${env.BITBUCKET_REPO_UUID ?? ''}:${scope}`, name: `${env.BITBUCKET_REPO_FULL_NAME ?? 'bitbucket'}#${scope}`, commit: env.BITBUCKET_COMMIT }\n }\n\n if (env.CIRCLECI) {\n // Owner-qualified: two projects with the same name under different CircleCI orgs must not\n // collide on one agent, since registering it purges the other project's live sessions.\n const owner = env.CIRCLE_PROJECT_USERNAME ?? ''\n const project = env.CIRCLE_PROJECT_REPONAME ?? 'circleci'\n const scope = env.CIRCLE_PR_NUMBER ?? env.CIRCLE_BRANCH ?? ''\n\n return { id: `circle:${owner}:${project}:${scope}`, name: `${owner ? `${owner}/` : ''}${project}#${scope}`, commit: env.CIRCLE_SHA1 }\n }\n\n return null\n}\n","import { dirname, join } from 'node:path'\nimport process from 'node:process'\nimport { styleText } from 'node:util'\nimport { read } from '@internals/utils'\nimport { cliReporter, Hookable, type KubbHooks, logLevel as logLevelMap } from '@kubb/core'\nimport { createSnapshot, defaultStudioUrl } from '@kubb/studio'\nimport type { BranchSnapshotChanges, PublishedSnapshot, SnapshotChanges } from '@kubb/studio/protocol'\nimport { logBlock } from '../../loggers/output.ts'\nimport { createPlainLogger } from '../../loggers/plainLogger.ts'\nimport setupReporters from '../../loggers/reporters.ts'\nimport { type CiContext, detectCi } from './ci.ts'\nimport { loadConfigs, run, type SnapshotOptions } from './run.ts'\nimport type { command } from '../../commands/studio/snapshot.ts'\nimport type { CommandRunner } from 'gunshi'\n\n/**\n * Walks up from `directory` to the first package.json with a name and a version.\n */\nasync function findPackageJson(directory: string): Promise<{ name: string; version: string }> {\n const packageJson = JSON.parse(await read(join(directory, 'package.json')).catch(() => '{}')) as Partial<{ name: string; version: string }>\n if (packageJson.name && packageJson.version) return { name: packageJson.name, version: packageJson.version }\n\n const parent = dirname(directory)\n if (parent === directory) throw new Error(`No package.json with a name and a version found above ${process.cwd()}`)\n\n return findPackageJson(parent)\n}\n\n/** Reads package.json only for whichever of name/version --name and --version did not supply. */\nasync function resolvePackageMetadata(options: SnapshotOptions): Promise<{ name: string; version: string }> {\n if (options.name && options.packageVersion) return { name: options.name, version: options.packageVersion }\n\n const found = await findPackageJson(process.cwd())\n return { name: options.name ?? found.name, version: options.packageVersion ?? found.version }\n}\n\nfunction resolveToken(options: SnapshotOptions): string {\n const token = options.token ?? process.env.KUBB_TOKEN\n\n if (!token) {\n throw new Error('An organization CI API key is required. Pass --token or set KUBB_TOKEN.')\n }\n\n return token\n}\n\nfunction resolveCiIdentity(options: SnapshotOptions): CiContext {\n const detected = detectCi()\n // A custom --id drops the detected base, since runs on that branch may use a custom id too.\n const ci = options.id ? { id: options.id, name: detected?.name ?? options.id, commit: detected?.commit } : detected\n\n if (!ci) {\n throw new Error('Could not detect a supported CI provider (GitHub Actions, GitLab CI, Bitbucket Pipelines, CircleCI). Pass --id.')\n }\n\n // An explicit --base-id may not name a branch, so it labels the comparison itself.\n const base = options.baseId ? { branch: options.baseId, id: options.baseId } : ci.base\n\n return { ...ci, base: base?.id === ci.id ? undefined : base }\n}\n\nfunction absoluteUrl(studioUrl: string, path: string): string {\n return new URL(path, `${studioUrl}/`).toString()\n}\n\ntype SnapshotResult = {\n id: string\n name: string | null\n version: string | null\n integrity: string | null\n url: string\n snapshotIdUrl: string\n expiresAt: string\n agentUrl: string\n /** What changed since the previous snapshot of this package on this agent. */\n changes?: SnapshotChanges\n /** What differs from the latest snapshot of the base branch, named by `branch`. */\n branchChanges?: BranchSnapshotChanges & { branch: string }\n}\n\nfunction toResult({ studioUrl, snapshot, ci }: { studioUrl: string; snapshot: PublishedSnapshot; ci: CiContext }): SnapshotResult {\n return {\n id: snapshot.id,\n name: snapshot.name,\n version: snapshot.version,\n integrity: snapshot.integrity,\n url: absoluteUrl(studioUrl, snapshot.url),\n snapshotIdUrl: absoluteUrl(studioUrl, snapshot.snapshotIdUrl),\n expiresAt: snapshot.expiresAt,\n agentUrl: absoluteUrl(studioUrl, `/agents/${snapshot.agent.slug ?? snapshot.agent.id}`),\n changes: snapshot.changes,\n branchChanges: snapshot.branchChanges && ci.base ? { ...snapshot.branchChanges, branch: ci.base.branch } : undefined,\n }\n}\n\n/** How many files differ, `against` what. */\nfunction describeChanges(changes: SnapshotChanges, against: string): string {\n const { added, changed, removed } = changes\n\n return added.length + changed.length + removed.length\n ? `${added.length} added, ${changed.length} changed, ${removed.length} removed ${against}`\n : `No changes ${against}`\n}\n\n/** One summary line: how many files changed, and since which run. */\nexport function formatChanges(changes: SnapshotChanges): string {\n if (!changes.base) {\n return 'First snapshot'\n }\n\n return describeChanges(changes, `since ${changes.base.commit?.slice(0, 7) ?? changes.base.createdAt}`)\n}\n\n/** One summary line: how the snapshot differs from the base branch's latest one. */\nexport function formatBranchChanges(changes: BranchSnapshotChanges & { branch: string }): string {\n if (changes.base) return describeChanges(changes, `against ${changes.branch}`)\n\n return changes.baseFound ? `No snapshot of ${changes.branch} for this package yet` : `No snapshot of ${changes.branch} to compare with`\n}\n\nfunction printSummary(result: SnapshotResult): void {\n logBlock([\n `${styleText('dim', 'Package'.padEnd(10))} ${result.name ?? '(unnamed)'}@${result.version ?? '0.0.0'}`,\n `${styleText('dim', 'Tarball'.padEnd(10))} ${styleText('cyan', result.url)}`,\n `${styleText('dim', 'Agent'.padEnd(10))} ${result.agentUrl}`,\n ...(result.branchChanges ? [`${styleText('dim', 'Branch'.padEnd(10))} ${formatBranchChanges(result.branchChanges)}`] : []),\n ...(result.changes ? [`${styleText('dim', 'Changes'.padEnd(10))} ${formatChanges(result.changes)}`] : []),\n `${styleText('dim', 'Expires'.padEnd(10))} ${result.expiresAt}`,\n ])\n}\n\n/**\n * Generates the project, packs it, and publishes it to Kubb Studio in one request, under the CI\n * agent the run's identity names.\n */\nexport async function snapshot(options: SnapshotOptions): Promise<void> {\n const token = resolveToken(options)\n const { config } = await loadConfigs(options)\n const ci = resolveCiIdentity(options)\n const { name, version: packageVersion } = await resolvePackageMetadata(options)\n const logLevel = logLevelMap[options.logLevel ?? 'info']\n\n const write = options.json ? (line: string) => console.error(line) : (line: string) => console.log(line)\n const hooks = new Hookable<KubbHooks>()\n setupReporters(hooks, { logLevel, reporters: [cliReporter], logger: createPlainLogger(write) })\n const step = (message: string) => {\n if (logLevel > logLevelMap.silent) {\n write(message)\n }\n }\n\n step('Generating the snapshot')\n\n try {\n const published = await createSnapshot({\n studioUrl: options.studioUrl,\n apiKey: token,\n config,\n hooks,\n id: ci.id,\n name: ci.name,\n packageName: name,\n version: packageVersion,\n commit: ci.commit,\n baseId: ci.base?.id,\n })\n const result = toResult({ studioUrl: options.studioUrl, snapshot: published, ci })\n\n step('Snapshot published')\n\n if (options.json) {\n console.log(JSON.stringify(result))\n }\n if (!options.json) {\n printSummary(result)\n }\n } catch (error) {\n step('Snapshot failed')\n throw error\n }\n}\n\nexport const runner: CommandRunner<{ args: typeof command.args; extensions: {} }> = async ({ values }) => {\n const options: SnapshotOptions = {\n configPath: values.config,\n studioUrl: values.url ?? defaultStudioUrl,\n logLevel: values.logLevel,\n token: values.token,\n id: values.id,\n baseId: values.baseId,\n name: values.name,\n packageVersion: values.packageVersion,\n json: values.json,\n }\n await run({ options, action: () => snapshot(options), json: options.json })\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;AAkCA,eAAsB,KAAK,MAA+B;CACxD,IAAIA,kBAAAA,QAAQ,OACV,OAAO,IAAI,KAAK,IAAI,CAAC,CAAC,KAAK;CAE7B,QAAA,GAAOC,iBAAAA,SAAAA,CAAS,MAAM,EAAE,UAAU,OAAO,CAAC;AAC5C;;;AChBA,SAAS,sBAAsB,WAA8D;CAC3F,IAAI,CAAC,WACH;CAGF,IAAI;EACF,MAAM,QAAQ,KAAK,OAAA,GAAMC,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,SAAS,OAAO;EAAG,MAAM,QAAQ;CAAK,CAAC;AAC5E"}
|
package/dist/studioWorker.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import "./rolldown-runtime-CRm0XQPb.js";
|
|
2
|
-
import { t as connect } from "./run-
|
|
3
|
-
import { r as serveWorker, t as getWorkerLogPath } from "./background-
|
|
2
|
+
import { t as connect } from "./run-9oIapU5y.js";
|
|
3
|
+
import { r as serveWorker, t as getWorkerLogPath } from "./background-CnSPyAn7.js";
|
|
4
4
|
import { format } from "node:util";
|
|
5
5
|
import { appendFileSync, statSync, writeFileSync } from "node:fs";
|
|
6
6
|
//#region src/runners/studio/worker.ts
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@kubb/cli",
|
|
3
|
-
"version": "5.8.
|
|
3
|
+
"version": "5.8.4",
|
|
4
4
|
"description": "Official CLI for Kubb. Run kubb generate, kubb init, kubb validate, kubb studio, and kubb mcp to manage the full code generation lifecycle.",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"cli",
|
|
@@ -63,7 +63,7 @@
|
|
|
63
63
|
"dependencies": {
|
|
64
64
|
"@clack/prompts": "^1.8.1",
|
|
65
65
|
"@gunshi/plugin-dryrun": "^0.37.3",
|
|
66
|
-
"@kubb/core": "5.8.
|
|
66
|
+
"@kubb/core": "5.8.4",
|
|
67
67
|
"chokidar": "^5.0.0",
|
|
68
68
|
"gunshi": "^0.37.3",
|
|
69
69
|
"jiti": "^2.7.0",
|
|
@@ -74,13 +74,13 @@
|
|
|
74
74
|
"devDependencies": {
|
|
75
75
|
"@internals/shared": "0.0.1",
|
|
76
76
|
"@internals/utils": "0.0.1",
|
|
77
|
-
"@kubb/adapter-oas": "5.8.
|
|
78
|
-
"@kubb/studio": "5.8.
|
|
77
|
+
"@kubb/adapter-oas": "5.8.4",
|
|
78
|
+
"@kubb/studio": "5.8.4"
|
|
79
79
|
},
|
|
80
80
|
"peerDependencies": {
|
|
81
|
-
"@kubb/adapter-oas": "5.8.
|
|
82
|
-
"@kubb/mcp": "5.8.
|
|
83
|
-
"@kubb/studio": "5.8.
|
|
81
|
+
"@kubb/adapter-oas": "5.8.4",
|
|
82
|
+
"@kubb/mcp": "5.8.4",
|
|
83
|
+
"@kubb/studio": "5.8.4"
|
|
84
84
|
},
|
|
85
85
|
"peerDependenciesMeta": {
|
|
86
86
|
"@kubb/adapter-oas": {
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
export { n as getWorkerStatus } from "./background-lBbQYvN7.js";
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"registry-CCKUL3ps.cjs","names":["process","getErrorMessage","isRegistryEntry","isValid","isLessThan"],"sources":["../src/utils/registry.ts"],"sourcesContent":["import process from 'node:process'\nimport { getErrorMessage } from '@internals/utils'\nimport { checkCompatibility, type ExtensionManifest, isRegistryEntry, type RegistryDetail, type RegistryEntry } from '@kubb/core'\nimport { isLessThan, isValid } from 'verkit'\n\nexport const DEFAULT_REGISTRY = 'https://kubb.dev/registry'\n\nconst SLUG = '[a-z0-9]+(?:-[a-z0-9]+)*'\nconst ID = new RegExp(`^${SLUG}(\\\\/${SLUG})?$`)\n\n/** The registry base URL: `KUBB_REGISTRY`, or kubb.dev. */\nexport function registryUrl(): string {\n const url = process.env.KUBB_REGISTRY || DEFAULT_REGISTRY\n if (!/^https?:\\/\\//.test(url)) throw new Error(`KUBB_REGISTRY must be an http(s) URL, got \"${url}\".`)\n return url.replace(/\\/+$/, '')\n}\n\n/**\n * Turns `owner/slug`, or a bare `slug` meaning `kubb-labs/<slug>`, into a registry id.\n *\n * @throws when the id has another shape, so it never reaches a URL unchecked.\n */\nexport function toRegistryId(input: string): string {\n if (!ID.test(input)) throw new Error(`\"${input}\" is not a registry id. Use owner/slug, such as kubb-labs/plugin-zod, or a slug, such as plugin-zod.`)\n return input.includes('/') ? input : `kubb-labs/${input}`\n}\n\n/** GETs `url` as JSON. A non-2xx answer returns only its status; a network error throws with the URL. */\nasync function fetchJSON(url: string): Promise<{ status: number; body?: unknown }> {\n try {\n const response = await globalThis.fetch(url, { headers: { accept: 'application/json' } })\n if (!response.ok) return { status: response.status }\n return { status: response.status, body: (await response.json()) as unknown }\n } catch (cause) {\n throw new Error(`Could not read ${url}: ${getErrorMessage(cause)}`, { cause })\n }\n}\n\n/** Fetches one extension's detail document. */\nexport async function fetchRegistryDetail({ id, registry }: { id: string; registry: string }): Promise<RegistryDetail> {\n const { status, body } = await fetchJSON(`${registry}/${id}.json`)\n if (status === 404) throw new Error(`\"${id}\" is not in the registry at ${registry}.`)\n if (status !== 200 || !isRegistryEntry(body) || body.id !== id)\n throw new Error(`The registry at ${registry} sent an invalid entry for \"${id}\" (HTTP ${status}).`)\n\n const { overview } = body as { overview?: unknown }\n return { ...body, overview: typeof overview === 'string' ? overview : null }\n}\n\n/** Fetches the registry index, leaving out entries that fail validation. */\nexport async function fetchRegistryIndex({ registry }: { registry: string }): Promise<Array<RegistryEntry>> {\n const { status, body } = await fetchJSON(`${registry}/index.json`)\n const index = body as { version?: unknown; extensions?: unknown } | null | undefined\n if (status !== 200 || index?.version !== 1 || !Array.isArray(index.extensions)) {\n throw new Error(`The registry at ${registry} sent an invalid index (HTTP ${status}).`)\n }\n return index.extensions.filter(isRegistryEntry)\n}\n\n/** Why the running Kubb or Node.js version cannot use this extension, or `undefined` when it can. */\nexport function incompatibility(manifest: ExtensionManifest): string | undefined {\n try {\n checkCompatibility({ name: manifest.name, compatibility: manifest.compatibility })\n return undefined\n } catch (error) {\n return getErrorMessage(error)\n }\n}\n\n/**\n * Whether `latest` is newer than `installed`. An unknown installed version counts as outdated, and an\n * invalid `latest` never does.\n */\nexport function isOutdated({ installed, latest }: { installed: string | undefined; latest: string }): boolean {\n if (!isValid(latest)) return false\n return !installed || !isValid(installed) || isLessThan(installed, latest)\n}\n"],"mappings":";;;;;;AAOA,MAAM,OAAO;AACb,MAAM,KAAK,IAAI,OAAO,IAAI,KA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AAE,YAAiE;CAC1G,MAAM,EAAE,QAAQ,SAAS,MAAM,UAAU,GAAG,SAAS,YAAY;CACjE,MAAM,QAAQ;CACd,IAAI,WAAW,OAAO,OAAO,YAAY,KAAK,CAAC,MAAM,QAAQ,MAAM,UAAU,GAC3E,MAAM,IAAI,MAAM,mBAAmB,SAAS,+BAA+B,OAAO,GAAG;CAEvF,OAAO,MAAM,WAAW,OAAOA,WAAAA,eAAe;AAChD;;AAGA,SAAgB,gBAAgB,UAAiD;CAC/E,IAAI;EACF,CAAA,GAAA,WAAA,mBAAA,CAAmB;GAAE,MAAM,SAAS;GAAM,eAAe,SAAS;EAAc,CAAC;EACjF;CACF,SAAS,OAAO;EACd,OAAOD,eAAAA,gBAAgB,KAAK;CAC9B;AACF;;;;;AAMA,SAAgB,WAAW,EAAE,WAAW,UAAsE;CAC5G,IAAI,EAAA,GAACE,OAAAA,QAAAA,CAAQ,MAAM,GAAG,OAAO;CAC7B,OAAO,CAAC,aAAa,EAAA,GAACA,OAAAA,QAAAA,CAAQ,SAAS,MAAA,GAAKC,OAAAA,WAAAA,CAAW,WAAW,MAAM;AAC1E"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"registry-DjGepXb0.js","names":[],"sources":["../src/utils/registry.ts"],"sourcesContent":["import process from 'node:process'\nimport { getErrorMessage } from '@internals/utils'\nimport { checkCompatibility, type ExtensionManifest, isRegistryEntry, type RegistryDetail, type RegistryEntry } from '@kubb/core'\nimport { isLessThan, isValid } from 'verkit'\n\nexport const DEFAULT_REGISTRY = 'https://kubb.dev/registry'\n\nconst SLUG = '[a-z0-9]+(?:-[a-z0-9]+)*'\nconst ID = new RegExp(`^${SLUG}(\\\\/${SLUG})?$`)\n\n/** The registry base URL: `KUBB_REGISTRY`, or kubb.dev. */\nexport function registryUrl(): string {\n const url = process.env.KUBB_REGISTRY || DEFAULT_REGISTRY\n if (!/^https?:\\/\\//.test(url)) throw new Error(`KUBB_REGISTRY must be an http(s) URL, got \"${url}\".`)\n return url.replace(/\\/+$/, '')\n}\n\n/**\n * Turns `owner/slug`, or a bare `slug` meaning `kubb-labs/<slug>`, into a registry id.\n *\n * @throws when the id has another shape, so it never reaches a URL unchecked.\n */\nexport function toRegistryId(input: string): string {\n if (!ID.test(input)) throw new Error(`\"${input}\" is not a registry id. Use owner/slug, such as kubb-labs/plugin-zod, or a slug, such as plugin-zod.`)\n return input.includes('/') ? input : `kubb-labs/${input}`\n}\n\n/** GETs `url` as JSON. A non-2xx answer returns only its status; a network error throws with the URL. */\nasync function fetchJSON(url: string): Promise<{ status: number; body?: unknown }> {\n try {\n const response = await globalThis.fetch(url, { headers: { accept: 'application/json' } })\n if (!response.ok) return { status: response.status }\n return { status: response.status, body: (await response.json()) as unknown }\n } catch (cause) {\n throw new Error(`Could not read ${url}: ${getErrorMessage(cause)}`, { cause })\n }\n}\n\n/** Fetches one extension's detail document. */\nexport async function fetchRegistryDetail({ id, registry }: { id: string; registry: string }): Promise<RegistryDetail> {\n const { status, body } = await fetchJSON(`${registry}/${id}.json`)\n if (status === 404) throw new Error(`\"${id}\" is not in the registry at ${registry}.`)\n if (status !== 200 || !isRegistryEntry(body) || body.id !== id)\n throw new Error(`The registry at ${registry} sent an invalid entry for \"${id}\" (HTTP ${status}).`)\n\n const { overview } = body as { overview?: unknown }\n return { ...body, overview: typeof overview === 'string' ? overview : null }\n}\n\n/** Fetches the registry index, leaving out entries that fail validation. */\nexport async function fetchRegistryIndex({ registry }: { registry: string }): Promise<Array<RegistryEntry>> {\n const { status, body } = await fetchJSON(`${registry}/index.json`)\n const index = body as { version?: unknown; extensions?: unknown } | null | undefined\n if (status !== 200 || index?.version !== 1 || !Array.isArray(index.extensions)) {\n throw new Error(`The registry at ${registry} sent an invalid index (HTTP ${status}).`)\n }\n return index.extensions.filter(isRegistryEntry)\n}\n\n/** Why the running Kubb or Node.js version cannot use this extension, or `undefined` when it can. */\nexport function incompatibility(manifest: ExtensionManifest): string | undefined {\n try {\n checkCompatibility({ name: manifest.name, compatibility: manifest.compatibility })\n return undefined\n } catch (error) {\n return getErrorMessage(error)\n }\n}\n\n/**\n * Whether `latest` is newer than `installed`. An unknown installed version counts as outdated, and an\n * invalid `latest` never does.\n */\nexport function isOutdated({ installed, latest }: { installed: string | undefined; latest: string }): boolean {\n if (!isValid(latest)) return false\n return !installed || !isValid(installed) || isLessThan(installed, latest)\n}\n"],"mappings":";;;;;AAOA,MAAM,OAAO;AACb,MAAM,KAAK,IAAI,OAAO,IAAI,KAAK,MAAM,KAAK,IAAI;;AAG9C,SAAgB,cAAsB;CACpC,MAAM,MAAM,QAAQ,IAAI,iBAAA;CACxB,IAAI,CAAC,eAAe,KAAK,GAAG,GAAG,MAAM,IAAI,MAAM,8CAA8C,IAAI,GAAG;CACpG,OAAO,IAAI,QAAQ,QAAQ,EAAE;AAC/B;;;;;;AAOA,SAAgB,aAAa,OAAuB;CAClD,IAAI,CAAC,GAAG,KAAK,KAAK,GAAG,MAAM,IAAI,MAAM,IAAI,MAAM,qGAAqG;CACpJ,OAAO,MAAM,SAAS,GAAG,IAAI,QAAQ,aAAa;AACpD;;AAGA,eAAe,UAAU,KAA0D;CACjF,IAAI;EACF,MAAM,WAAW,MAAM,WAAW,MAAM,KAAK,EAAE,SAAS,EAAE,QAAQ,mBAAmB,EAAE,CAAC;EACxF,IAAI,CAAC,SAAS,IAAI,OAAO,EAAE,QAAQ,SAAS,OAAO;EACnD,OAAO;GAAE,QAAQ,SAAS;GAAQ,MAAO,MAAM,SAAS,KAAK;EAAc;CAC7E,SAAS,OAAO;EACd,MAAM,IAAI,MAAM,kBAAkB,IAAI,IAAI,gBAAgB,KAAK,KAAK,EAAE,MAAM,CAAC;CAC/E;AACF;;AAGA,eAAsB,oBAAoB,EAAE,IAAI,YAAuE;CACrH,MAAM,EAAE,QAAQ,SAAS,MAAM,UAAU,GAAG,SAAS,GAAG,GAAG,MAAM;CACjE,IAAI,WAAW,KAAK,MAAM,IAAI,MAAM,IAAI,GAAG,8BAA8B,SAAS,EAAE;CACpF,IAAI,WAAW,OAAO,CAAC,gBAAgB,IAAI,KAAK,KAAK,OAAO,IAC1D,MAAM,IAAI,MAAM,mBAAmB,SAAS,8BAA8B,GAAG,UAAU,OAAO,GAAG;CAEnG,MAAM,EAAE,aAAa;CACrB,OAAO;EAAE,GAAG;EAAM,UAAU,OAAO,aAAa,WAAW,WAAW;CAAK;AAC7E;;AAGA,eAAsB,mBAAmB,EAAE,YAAiE;CAC1G,MAAM,EAAE,QAAQ,SAAS,MAAM,UAAU,GAAG,SAAS,YAAY;CACjE,MAAM,QAAQ;CACd,IAAI,WAAW,OAAO,OAAO,YAAY,KAAK,CAAC,MAAM,QAAQ,MAAM,UAAU,GAC3E,MAAM,IAAI,MAAM,mBAAmB,SAAS,+BAA+B,OAAO,GAAG;CAEvF,OAAO,MAAM,WAAW,OAAO,eAAe;AAChD;;AAGA,SAAgB,gBAAgB,UAAiD;CAC/E,IAAI;EACF,mBAAmB;GAAE,MAAM,SAAS;GAAM,eAAe,SAAS;EAAc,CAAC;EACjF;CACF,SAAS,OAAO;EACd,OAAO,gBAAgB,KAAK;CAC9B;AACF;;;;;AAMA,SAAgB,WAAW,EAAE,WAAW,UAAsE;CAC5G,IAAI,CAAC,QAAQ,MAAM,GAAG,OAAO;CAC7B,OAAO,CAAC,aAAa,CAAC,QAAQ,SAAS,KAAK,WAAW,WAAW,MAAM;AAC1E"}
|
package/dist/run-B9wWJSSx.js.map
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"run-B9wWJSSx.js","names":[],"sources":["../src/runners/update/run.ts"],"sourcesContent":["import process from 'node:process'\nimport { styleText } from 'node:util'\nimport * as clack from '@clack/prompts'\nimport { getErrorMessage } from '@internals/utils'\nimport { readInstalledPackages } from '@kubb/core'\nimport { logBlock, logError, logInfo, logIntro, logOutro, logStep, logWarn } from '../../loggers/output.ts'\nimport { fetchRegistryIndex, incompatibility, isOutdated, registryUrl, toRegistryId } from '../../utils/registry.ts'\nimport { detectPackageManager, installPackages } from '../init/utils.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 check: boolean\n yes: boolean\n}\n\n/**\n * Moves installed extensions to the version the registry pins. Lists the proposals, asks, then\n * installs them. With `check`, only lists them.\n */\nexport async function run({ ids, check, yes }: UpdateOptions): Promise<void> {\n const cwd = process.cwd()\n logIntro({ title: styleText('bgCyan', styleText('black', ' Kubb Update ')) })\n\n try {\n const wanted = new Set(ids.map(toRegistryId))\n const [entries, installed] = await Promise.all([fetchRegistryIndex({ registry: registryUrl() }), readInstalledPackages({ root: cwd })])\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)) logWarn(`${id} is not installed, or not in the registry.`)\n }\n\n const proposals = tracked.filter((entry) => {\n if (!isOutdated({ installed: versions.get(entry.artifact.package), latest: entry.artifact.version })) return false\n const problem = incompatibility(entry.manifest)\n if (problem) logWarn(`Skipped ${entry.id}: ${problem}`)\n return !problem\n })\n\n if (!proposals.length) {\n logOutro(ids.length ? `No updates for ${ids.join(', ')}.` : 'Every installed extension is up to date.')\n return\n }\n\n const plural = proposals.length === 1 ? '' : 's'\n logBlock(\n proposals.map(({ artifact }) => `${artifact.package} ${versions.get(artifact.package) ?? 'not installed'} -> ${styleText('green', artifact.version)}`),\n )\n\n if (check) {\n logOutro(`${proposals.length} update${plural} available. Run \\`kubb update\\` to install.`)\n return\n }\n\n const confirmed = yes || (await clack.confirm({ message: `Install ${proposals.length} update${plural}?`, initialValue: true }))\n if (clack.isCancel(confirmed) || !confirmed) {\n clack.cancel('Operation canceled.')\n return\n }\n\n const packageManager = detectPackageManager(cwd)\n const specs = proposals.map(({ artifact }) => `${artifact.package}@${artifact.version}`)\n logStep(`Installing ${specs.join(', ')} with ${packageManager.name}`)\n await installPackages(specs, packageManager, cwd)\n\n logInfo(`Updated ${specs.length} extension${plural}`)\n logOutro(styleText('green', 'Done'))\n } catch (error) {\n logError(getErrorMessage(error))\n process.exitCode = 1\n }\n}\n"],"mappings":";;;;;;;;;;;;;;AAsBA,eAAsB,IAAI,EAAE,KAAK,OAAO,OAAqC;CAC3E,MAAM,MAAM,QAAQ,IAAI;CACxB,SAAS,EAAE,OAAO,UAAU,UAAU,UAAU,SAAS,eAAe,CAAC,EAAE,CAAC;CAE5E,IAAI;EACF,MAAM,SAAS,IAAI,IAAI,IAAI,IAAI,YAAY,CAAC;EAC5C,MAAM,CAAC,SAAS,aAAa,MAAM,QAAQ,IAAI,CAAC,mBAAmB,EAAE,UAAU,YAAY,EAAE,CAAC,GAAG,sBAAsB,EAAE,MAAM,IAAI,CAAC,CAAC,CAAC;EACtI,MAAM,WAAW,IAAI,IAAI,UAAU,KAAK,SAAS,CAAC,KAAK,SAAS,KAAK,OAAO,CAAC,CAAC;EAE9E,MAAM,UAAU,QAAQ,QAAQ,UAAU,SAAS,IAAI,MAAM,SAAS,OAAO,MAAM,CAAC,OAAO,QAAQ,OAAO,IAAI,MAAM,EAAE,EAAE;EACxH,KAAK,MAAM,MAAM,QACf,IAAI,CAAC,QAAQ,MAAM,UAAU,MAAM,OAAO,EAAE,GAAG,QAAQ,GAAG,GAAG,2CAA2C;EAG1G,MAAM,YAAY,QAAQ,QAAQ,UAAU;GAC1C,IAAI,CAAC,WAAW;IAAE,WAAW,SAAS,IAAI,MAAM,SAAS,OAAO;IAAG,QAAQ,MAAM,SAAS;GAAQ,CAAC,GAAG,OAAO;GAC7G,MAAM,UAAU,gBAAgB,MAAM,QAAQ;GAC9C,IAAI,SAAS,QAAQ,WAAW,MAAM,GAAG,IAAI,SAAS;GACtD,OAAO,CAAC;EACV,CAAC;EAED,IAAI,CAAC,UAAU,QAAQ;GACrB,SAAS,IAAI,SAAS,kBAAkB,IAAI,KAAK,IAAI,EAAE,KAAK,0CAA0C;GACtG;EACF;EAEA,MAAM,SAAS,UAAU,WAAW,IAAI,KAAK;EAC7C,SACE,UAAU,KAAK,EAAE,eAAe,GAAG,SAAS,QAAQ,IAAI,SAAS,IAAI,SAAS,OAAO,KAAK,gBAAgB,MAAM,UAAU,SAAS,SAAS,OAAO,GAAG,CACxJ;EAEA,IAAI,OAAO;GACT,SAAS,GAAG,UAAU,OAAO,SAAS,OAAO,4CAA4C;GACzF;EACF;EAEA,MAAM,YAAY,OAAQ,MAAM,MAAM,QAAQ;GAAE,SAAS,WAAW,UAAU,OAAO,SAAS,OAAO;GAAI,cAAc;EAAK,CAAC;EAC7H,IAAI,MAAM,SAAS,SAAS,KAAK,CAAC,WAAW;GAC3C,MAAM,OAAO,qBAAqB;GAClC;EACF;EAEA,MAAM,iBAAiB,qBAAqB,GAAG;EAC/C,MAAM,QAAQ,UAAU,KAAK,EAAE,eAAe,GAAG,SAAS,QAAQ,GAAG,SAAS,SAAS;EACvF,QAAQ,cAAc,MAAM,KAAK,IAAI,EAAE,QAAQ,eAAe,MAAM;EACpE,MAAM,gBAAgB,OAAO,gBAAgB,GAAG;EAEhD,QAAQ,WAAW,MAAM,OAAO,YAAY,QAAQ;EACpD,SAAS,UAAU,SAAS,MAAM,CAAC;CACrC,SAAS,OAAO;EACd,SAAS,gBAAgB,KAAK,CAAC;EAC/B,QAAQ,WAAW;CACrB;AACF"}
|
package/dist/run-BURZ4hDs.js.map
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"run-BURZ4hDs.js","names":[],"sources":["../src/runners/add/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 { getErrorMessage } from '@internals/utils'\nimport type { ExtensionManifest, RegistryDetail } from '@kubb/core'\nimport { findConfigFile } from '../../config.ts'\nimport { logBlock, logError, logInfo, logIntro, logOutro, logStep, logWarn } from '../../loggers/output.ts'\nimport { fetchRegistryDetail, incompatibility, registryUrl, toRegistryId } from '../../utils/registry.ts'\nimport { detectPackageManager, installPackages } from '../init/utils.ts'\n\nexport type AddOptions = {\n /**\n * `owner/slug`, or a bare `slug` for an official extension.\n */\n id: string\n configPath?: string\n yes: boolean\n install: boolean\n}\n\n/** The import and the `defineConfig` property to merge into `kubb.config.ts` by hand. */\nexport function toSnippet({ artifact, manifest }: Pick<RegistryDetail, 'artifact' | 'manifest'>): string {\n const call = `${manifest.export}()`\n const property: Record<ExtensionManifest['kind'], string> = {\n plugin: `plugins: [..., ${call}],`,\n adapter: `adapter: ${call},`,\n parser: `parsers: [..., ${call}],`,\n }\n return [`import { ${manifest.export} } from '${artifact.package}'`, '', property[manifest.kind]].join('\\n')\n}\n\n/** Adds the plugin call and its import to the config file. Returns why it could not, or `undefined`. */\nasync function addToConfig({ detail, configFile }: { detail: RegistryDetail; configFile: string }): Promise<string | undefined> {\n const { artifact, manifest } = detail\n try {\n const { writeConfigEdits } = await import('@kubb/studio')\n const { outcomes } = await writeConfigEdits({\n filePath: configFile,\n edits: [{ operation: 'add-plugin', plugin: artifact.package, importName: manifest.export }],\n extensions: new Map([[artifact.package, { package: artifact.package, version: artifact.version, manifest }]]),\n })\n return outcomes[0]?.applied ? undefined : (outcomes[0]?.reason ?? 'the config file was not changed')\n } catch (error) {\n return getErrorMessage(error)\n }\n}\n\n/**\n * Installs an extension from the Kubb registry at its reviewed version and, for a plugin, adds it to\n * `kubb.config.ts`. Refuses when the running Kubb or Node.js version is outside its compatibility.\n */\nexport async function run({ id: input, configPath, yes, install }: AddOptions): Promise<void> {\n const cwd = process.cwd()\n logIntro({ title: styleText('bgCyan', styleText('black', ' Kubb Add ')) })\n\n try {\n const registry = registryUrl()\n const detail = await fetchRegistryDetail({ id: toRegistryId(input), registry })\n const { artifact, manifest } = detail\n\n const problem = incompatibility(manifest)\n if (problem) throw new Error(problem)\n\n const spec = `${artifact.package}@${artifact.version}`\n const configFile = manifest.kind === 'plugin' ? (configPath ? path.resolve(configPath) : findConfigFile(cwd)) : undefined\n if (manifest.kind === 'plugin' && !configFile) throw new Error('No kubb.config.ts found. Run `kubb init` first, or pass --config.')\n\n logInfo(`${styleText('cyan', manifest.displayName)} (${manifest.kind}): ${manifest.description}`)\n logBlock([\n install ? `Install ${styleText('cyan', spec)} as a dev dependency` : `Skip installing ${spec}`,\n configFile\n ? `Add ${styleText('cyan', `${manifest.export}()`)} to ${path.relative(cwd, configFile) || configFile}`\n : `Print the ${manifest.kind} snippet to add`,\n ])\n\n const confirmed = yes || (await clack.confirm({ message: 'Continue?', initialValue: true }))\n if (clack.isCancel(confirmed) || !confirmed) {\n clack.cancel('Operation canceled.')\n return\n }\n\n if (install) {\n const packageManager = detectPackageManager(cwd)\n logStep(`Installing ${spec} with ${packageManager.name}`)\n await installPackages([spec], packageManager, cwd)\n }\n\n const reason = configFile ? await addToConfig({ detail, configFile }) : `add the ${manifest.kind} to your config`\n if (!reason) {\n logOutro(styleText('green', install ? `Added ${spec}` : `Added ${manifest.export}() to the config. Install ${spec} to use it.`))\n return\n }\n\n if (configFile) logWarn(`Could not edit ${configFile}: ${reason}`)\n logBlock(['Add the import to your Kubb config and merge the property into its defineConfig call:', '', toSnippet(detail)])\n logOutro(styleText('green', install ? `Installed ${spec}. Add it with the snippet above.` : `Install ${spec} and add the snippet above.`))\n } catch (error) {\n logError(getErrorMessage(error))\n process.exitCode = 1\n }\n}\n"],"mappings":";;;;;;;;;;;;AAsBA,SAAgB,UAAU,EAAE,UAAU,YAAmE;CACvG,MAAM,OAAO,GAAG,SAAS,OAAO;CAChC,MAAM,WAAsD;EAC1D,QAAQ,kBAAkB,KAAK;EAC/B,SAAS,YAAY,KAAK;EAC1B,QAAQ,kBAAkB,KAAK;CACjC;CACA,OAAO;EAAC,YAAY,SAAS,OAAO,WAAW,SAAS,QAAQ;EAAI;EAAI,SAAS,SAAS;CAAK,CAAC,CAAC,KAAK,IAAI;AAC5G;;AAGA,eAAe,YAAY,EAAE,QAAQ,cAA2F;CAC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OAAO,UAAU,QAAQ,GAAG,SAAS,OAAO,GAAG,EAAE,MAAM,KAAK,SAAS,KAAK,UAAU,KAAK,eACzF,aAAa,SAAS,KAAK,gBACjC,CAAC;EAED,MAAM,YAAY,OAAQ,MAAM,MAAM,QAAQ;GAAE,SAAS;GAAa,cAAc;EAAK,CAAC;EAC1F,IAAI,MAAM,SAAS,SAAS,KAAK,CAAC,WAAW;GAC3C,MAAM,OAAO,qBAAqB;GAClC;EACF;EAEA,IAAI,SAAS;GACX,MAAM,iBAAiB,qBAAqB,GAAG;GAC/C,QAAQ,cAAc,KAAK,QAAQ,eAAe,MAAM;GACxD,MAAM,gBAAgB,CAAC,IAAI,GAAG,gBAAgB,GAAG;EACnD;EAEA,MAAM,SAAS,aAAa,MAAM,YAAY;GAAE;GAAQ;EAAW,CAAC,IAAI,WAAW,SAAS,KAAK;EACjG,IAAI,CAAC,QAAQ;GACX,SAAS,UAAU,SAAS,UAAU,SAAS,SAAS,SAAS,SAAS,OAAO,4BAA4B,KAAK,YAAY,CAAC;GAC/H;EACF;EAEA,IAAI,YAAY,QAAQ,kBAAkB,WAAW,IAAI,QAAQ;EACjE,SAAS;GAAC;GAAyF;GAAI,UAAU,MAAM;EAAC,CAAC;EACzH,SAAS,UAAU,SAAS,UAAU,aAAa,KAAK,oCAAoC,WAAW,KAAK,4BAA4B,CAAC;CAC3I,SAAS,OAAO;EACd,SAAS,gBAAgB,KAAK,CAAC;EAC/B,QAAQ,WAAW;CACrB;AACF"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"run-C4IHvWT_.cjs","names":["getErrorMessage","process","styleText","registryUrl","fetchRegistryDetail","toRegistryId","incompatibility","path","findConfigFile","clack","detectPackageManager","installPackages"],"sources":["../src/runners/add/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 { getErrorMessage } from '@internals/utils'\nimport type { ExtensionManifest, RegistryDetail } from '@kubb/core'\nimport { findConfigFile } from '../../config.ts'\nimport { logBlock, logError, logInfo, logIntro, logOutro, logStep, logWarn } from '../../loggers/output.ts'\nimport { fetchRegistryDetail, incompatibility, registryUrl, toRegistryId } from '../../utils/registry.ts'\nimport { detectPackageManager, installPackages } from '../init/utils.ts'\n\nexport type AddOptions = {\n /**\n * `owner/slug`, or a bare `slug` for an official extension.\n */\n id: string\n configPath?: string\n yes: boolean\n install: boolean\n}\n\n/** The import and the `defineConfig` property to merge into `kubb.config.ts` by hand. */\nexport function toSnippet({ artifact, manifest }: Pick<RegistryDetail, 'artifact' | 'manifest'>): string {\n const call = `${manifest.export}()`\n const property: Record<ExtensionManifest['kind'], string> = {\n plugin: `plugins: [..., ${call}],`,\n adapter: `adapter: ${call},`,\n parser: `parsers: [..., ${call}],`,\n }\n return [`import { ${manifest.export} } from '${artifact.package}'`, '', property[manifest.kind]].join('\\n')\n}\n\n/** Adds the plugin call and its import to the config file. Returns why it could not, or `undefined`. */\nasync function addToConfig({ detail, configFile }: { detail: RegistryDetail; configFile: string }): Promise<string | undefined> {\n const { artifact, manifest } = detail\n try {\n const { writeConfigEdits } = await import('@kubb/studio')\n const { outcomes } = await writeConfigEdits({\n filePath: configFile,\n edits: [{ operation: 'add-plugin', plugin: artifact.package, importName: manifest.export }],\n extensions: new Map([[artifact.package, { package: artifact.package, version: artifact.version, manifest }]]),\n })\n return outcomes[0]?.applied ? undefined : (outcomes[0]?.reason ?? 'the config file was not changed')\n } catch (error) {\n return getErrorMessage(error)\n }\n}\n\n/**\n * Installs an extension from the Kubb registry at its reviewed version and, for a plugin, adds it to\n * `kubb.config.ts`. Refuses when the running Kubb or Node.js version is outside its compatibility.\n */\nexport async function run({ id: input, configPath, yes, install }: AddOptions): Promise<void> {\n const cwd = process.cwd()\n logIntro({ title: styleText('bgCyan', styleText('black', ' Kubb Add ')) })\n\n try {\n const registry = registryUrl()\n const detail = await fetchRegistryDetail({ id: toRegistryId(input), registry })\n const { artifact, manifest } = detail\n\n const problem = incompatibility(manifest)\n if (problem) throw new Error(problem)\n\n const spec = `${artifact.package}@${artifact.version}`\n const configFile = manifest.kind === 'plugin' ? (configPath ? path.resolve(configPath) : findConfigFile(cwd)) : undefined\n if (manifest.kind === 'plugin' && !configFile) throw new Error('No kubb.config.ts found. Run `kubb init` first, or pass --config.')\n\n logInfo(`${styleText('cyan', manifest.displayName)} (${manifest.kind}): ${manifest.description}`)\n logBlock([\n install ? `Install ${styleText('cyan', spec)} as a dev dependency` : `Skip installing ${spec}`,\n configFile\n ? `Add ${styleText('cyan', `${manifest.export}()`)} to ${path.relative(cwd, configFile) || configFile}`\n : `Print the ${manifest.kind} snippet to add`,\n ])\n\n const confirmed = yes || (await clack.confirm({ message: 'Continue?', initialValue: true }))\n if (clack.isCancel(confirmed) || !confirmed) {\n clack.cancel('Operation canceled.')\n return\n }\n\n if (install) {\n const packageManager = detectPackageManager(cwd)\n logStep(`Installing ${spec} with ${packageManager.name}`)\n await installPackages([spec], packageManager, cwd)\n }\n\n const reason = configFile ? await addToConfig({ detail, configFile }) : `add the ${manifest.kind} to your config`\n if (!reason) {\n logOutro(styleText('green', install ? `Added ${spec}` : `Added ${manifest.export}() to the config. Install ${spec} to use it.`))\n return\n }\n\n if (configFile) logWarn(`Could not edit ${configFile}: ${reason}`)\n logBlock(['Add the import to your Kubb config and merge the property into its defineConfig call:', '', toSnippet(detail)])\n logOutro(styleText('green', install ? `Installed ${spec}. Add it with the snippet above.` : `Install ${spec} and add the snippet above.`))\n } catch (error) {\n logError(getErrorMessage(error))\n process.exitCode = 1\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;AAsBA,SAAgB,UAAU,EAAE,UAAU,YAAmE;CACvG,MAAM,OAAO,GAAG,SAAS,OAAO;CAChC,MAAM,WAAsD;EAC1D,QAAQ,kBAAkB,KAAK;EAC/B,SAAS,YAAY,KAAK;EAC1B,QAAQ,kBAAkB,KAAK;CACjC;CACA,OAAO;EAAC,YAAY,SAAS,OAAO,W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WAAW,KAAK,4BAA4B,CAAC;CAC3I,SAAS,OAAO;EACd,eAAA,SAASF,eAAAA,gBAAgB,KAAK,CAAC;EAC/B,aAAA,QAAA,WAAmB;CACrB;AACF"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"run-DVIqUt1x.cjs","names":["process","styleText","toRegistryId","fetchRegistryIndex","registryUrl","readInstalledPackages","isOutdated","incompatibility","clack","detectPackageManager","installPackages","getErrorMessage"],"sources":["../src/runners/update/run.ts"],"sourcesContent":["import process from 'node:process'\nimport { styleText } from 'node:util'\nimport * as clack from '@clack/prompts'\nimport { getErrorMessage } from '@internals/utils'\nimport { readInstalledPackages } from '@kubb/core'\nimport { logBlock, logError, logInfo, logIntro, logOutro, logStep, logWarn } from '../../loggers/output.ts'\nimport { fetchRegistryIndex, incompatibility, isOutdated, registryUrl, toRegistryId } from '../../utils/registry.ts'\nimport { detectPackageManager, installPackages } from '../init/utils.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 check: boolean\n yes: boolean\n}\n\n/**\n * Moves installed extensions to the version the registry pins. Lists the proposals, asks, then\n * installs them. With `check`, only lists them.\n */\nexport async function run({ ids, check, yes }: UpdateOptions): Promise<void> {\n const cwd = process.cwd()\n logIntro({ title: styleText('bgCyan', styleText('black', ' Kubb Update ')) })\n\n try {\n const wanted = new Set(ids.map(toRegistryId))\n const [entries, installed] = await Promise.all([fetchRegistryIndex({ registry: registryUrl() }), readInstalledPackages({ root: cwd })])\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)) logWarn(`${id} is not installed, or not in the registry.`)\n }\n\n const proposals = tracked.filter((entry) => {\n if (!isOutdated({ installed: versions.get(entry.artifact.package), latest: entry.artifact.version })) return false\n const problem = incompatibility(entry.manifest)\n if (problem) logWarn(`Skipped ${entry.id}: ${problem}`)\n return !problem\n })\n\n if (!proposals.length) {\n logOutro(ids.length ? `No updates for ${ids.join(', ')}.` : 'Every installed extension is up to date.')\n return\n }\n\n const plural = proposals.length === 1 ? '' : 's'\n logBlock(\n proposals.map(({ artifact }) => `${artifact.package} ${versions.get(artifact.package) ?? 'not installed'} -> ${styleText('green', artifact.version)}`),\n )\n\n if (check) {\n logOutro(`${proposals.length} update${plural} available. Run \\`kubb update\\` to install.`)\n return\n }\n\n const confirmed = yes || (await clack.confirm({ message: `Install ${proposals.length} update${plural}?`, initialValue: true }))\n if (clack.isCancel(confirmed) || !confirmed) {\n clack.cancel('Operation canceled.')\n return\n }\n\n const packageManager = detectPackageManager(cwd)\n const specs = proposals.map(({ artifact }) => `${artifact.package}@${artifact.version}`)\n logStep(`Installing ${specs.join(', ')} with ${packageManager.name}`)\n await installPackages(specs, packageManager, cwd)\n\n logInfo(`Updated ${specs.length} extension${plural}`)\n logOutro(styleText('green', 'Done'))\n } catch (error) {\n logError(getErrorMessage(error))\n process.exitCode = 1\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;AAsBA,eAAsB,IAAI,EAAE,KAAK,OAAO,OAAqC;CAC3E,MAAM,MAAMA,aAAAA,QAAQ,IAAI;CACxB,eAAA,SAAS,EAAE,QAAA,GAAOC,UAAAA,UAAAA,CAAU,WAAA,GAAUA,UAAAA,UAAAA,CAAU,SAAS,eAAe,CAAC,EAAE,CAAC;CAE5E,IAAI;EACF,MAAM,SAAS,IAAI,IAAI,IAAI,IAAIC,iBAAAA,YAAY,CAAC;EAC5C,MAAM,CAAC,SAAS,aAAa,MAAM,QAAQ,IAAI,CAACC,iBAAAA,mBAAmB,EAAE,UAAUC,iBAAAA,YAAY,EAAE,CAAC,IAAA,GAAGC,WAAAA,sBAAAA,CAAsB,EAAE,MAAM,IAAI,CAAC,CAAC,CAAC;EACtI,MAAM,WAAW,IAAI,IAAI,UAAU,KAAK,SAAS,CAAC,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