@kubb/cli 5.19.1 → 5.20.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/{Telemetry-B7SszijK.js → Telemetry-4T6PkdJo.js} +2 -2
- package/dist/{Telemetry-B7SszijK.js.map → Telemetry-4T6PkdJo.js.map} +1 -1
- package/dist/{Telemetry-Cg4O7utx.cjs → Telemetry-q5YqdKmI.cjs} +2 -2
- package/dist/{Telemetry-Cg4O7utx.cjs.map → Telemetry-q5YqdKmI.cjs.map} +1 -1
- package/dist/{background-tkqjTpos.js → background-Bi9AvpqA.js} +1 -1
- package/dist/{background-DY0Mr03A.js → background-Bt-N8p5N.js} +3 -3
- package/dist/{background-DY0Mr03A.js.map → background-Bt-N8p5N.js.map} +1 -1
- package/dist/{background-DqI5F8po.cjs → background-DtI6vVet.cjs} +3 -3
- package/dist/{background-DqI5F8po.cjs.map → background-DtI6vVet.cjs.map} +1 -1
- package/dist/{credentials-Cl3eOa8G.cjs → credentials-9OkKaKAr.cjs} +56 -6
- package/dist/credentials-9OkKaKAr.cjs.map +1 -0
- package/dist/{credentials-LPHovWZe.js → credentials-Bran9lpd.js} +56 -6
- package/dist/credentials-Bran9lpd.js.map +1 -0
- package/dist/{credentials-DznluKkp.js → credentials-XjRyFRWF.js} +1 -1
- package/dist/index.cjs +9 -9
- package/dist/index.js +9 -9
- package/dist/{mcp-VfW5A7Et.js → mcp-C26j2VvJ.js} +2 -2
- package/dist/{mcp-VfW5A7Et.js.map → mcp-C26j2VvJ.js.map} +1 -1
- package/dist/{mcp-BiGBnYH7.cjs → mcp-C5Qb_3i8.cjs} +2 -2
- package/dist/{mcp-BiGBnYH7.cjs.map → mcp-C5Qb_3i8.cjs.map} +1 -1
- package/dist/{package-D5f3ZWB1.cjs → package-CsxsJg57.cjs} +2 -2
- package/dist/package-CsxsJg57.cjs.map +1 -0
- package/dist/package-D1ycB0bA.js +5 -0
- package/dist/package-D1ycB0bA.js.map +1 -0
- package/dist/{run-DBEs_CXd.js → run-6lwgfA_P.js} +2 -2
- package/dist/{run-DBEs_CXd.js.map → run-6lwgfA_P.js.map} +1 -1
- package/dist/{run-Bj7R9x32.js → run-8gqo-bOB.js} +83 -23
- package/dist/run-8gqo-bOB.js.map +1 -0
- package/dist/{run-DM7m4Viy.js → run-B6e2p23o.js} +3 -3
- package/dist/{run-DM7m4Viy.js.map → run-B6e2p23o.js.map} +1 -1
- package/dist/{run-DWWlKSqg.cjs → run-C1JNeHrj.cjs} +2 -2
- package/dist/{run-DWWlKSqg.cjs.map → run-C1JNeHrj.cjs.map} +1 -1
- package/dist/{run-gBNMCysT.cjs → run-CYY1iFD_.cjs} +3 -3
- package/dist/{run-gBNMCysT.cjs.map → run-CYY1iFD_.cjs.map} +1 -1
- package/dist/{run-CnbPIGBg.cjs → run-D5lG3Rv7.cjs} +2 -2
- package/dist/{run-CnbPIGBg.cjs.map → run-D5lG3Rv7.cjs.map} +1 -1
- package/dist/{run--8RWm6ny.js → run-DeevN1it.js} +2 -2
- package/dist/{run--8RWm6ny.js.map → run-DeevN1it.js.map} +1 -1
- package/dist/{run-CvJA7KRW.cjs → run-Dlj-dK7u.cjs} +2 -2
- package/dist/{run-CvJA7KRW.cjs.map → run-Dlj-dK7u.cjs.map} +1 -1
- package/dist/{run-Cp-ddEnQ.cjs → run-Dy3EpGtg.cjs} +82 -22
- package/dist/run-Dy3EpGtg.cjs.map +1 -0
- package/dist/{run-W0EIq66g.js → run-JAYvsn2v.js} +1 -1
- package/dist/{run-DkMqxmXf.js → run-QBGgsQ2B.js} +2 -2
- package/dist/{run-DkMqxmXf.js.map → run-QBGgsQ2B.js.map} +1 -1
- package/dist/{run-DnsSsAj2.cjs → run-q2tnHViw.cjs} +2 -2
- package/dist/{run-DnsSsAj2.cjs.map → run-q2tnHViw.cjs.map} +1 -1
- package/dist/{run-DKTqPtGT.js → run-yNWLKHjJ.js} +2 -2
- package/dist/{run-DKTqPtGT.js.map → run-yNWLKHjJ.js.map} +1 -1
- package/dist/{snapshot-osKgMu9i.cjs → snapshot-CRwqhXnu.cjs} +2 -2
- package/dist/{snapshot-osKgMu9i.cjs.map → snapshot-CRwqhXnu.cjs.map} +1 -1
- package/dist/{snapshot-BH9zjo7V.js → snapshot-fRVniDRs.js} +2 -2
- package/dist/{snapshot-BH9zjo7V.js.map → snapshot-fRVniDRs.js.map} +1 -1
- package/dist/{status-DZceprwS.js → status-DJryj--a.js} +2 -2
- package/dist/{status-DZceprwS.js.map → status-DJryj--a.js.map} +1 -1
- package/dist/{status-Dw2z9CEy.cjs → status-W_mU4q9r.cjs} +2 -2
- package/dist/{status-Dw2z9CEy.cjs.map → status-W_mU4q9r.cjs.map} +1 -1
- package/dist/{studio-igCkMtri.cjs → studio-KJwsS5S9.cjs} +14 -14
- package/dist/{studio-igCkMtri.cjs.map → studio-KJwsS5S9.cjs.map} +1 -1
- package/dist/{studio-CKZ8oF7u.js → studio-ncHwqZbW.js} +14 -14
- package/dist/{studio-CKZ8oF7u.js.map → studio-ncHwqZbW.js.map} +1 -1
- package/dist/studioWorker.js +2 -2
- package/dist/{validate-_a3pddzL.js → validate-DQ9Ls3az.js} +2 -2
- package/dist/{validate-_a3pddzL.js.map → validate-DQ9Ls3az.js.map} +1 -1
- package/dist/{validate-YMI4B_lF.cjs → validate-Dz1Kh4xw.cjs} +2 -2
- package/dist/{validate-YMI4B_lF.cjs.map → validate-Dz1Kh4xw.cjs.map} +1 -1
- package/package.json +7 -7
- package/dist/credentials-Cl3eOa8G.cjs.map +0 -1
- package/dist/credentials-LPHovWZe.js.map +0 -1
- package/dist/package-CdkP7X7O.js +0 -5
- package/dist/package-CdkP7X7O.js.map +0 -1
- package/dist/package-D5f3ZWB1.cjs.map +0 -1
- package/dist/run-Bj7R9x32.js.map +0 -1
- package/dist/run-Cp-ddEnQ.cjs.map +0 -1
|
@@ -3,15 +3,15 @@ const require_text = require("./text-CkCtm5VP.cjs");
|
|
|
3
3
|
const require_config = require("./config-BU9xeaGq.cjs");
|
|
4
4
|
const require_isCIEnvironment = require("./isCIEnvironment-jzKqdVwJ.cjs");
|
|
5
5
|
const require_errors = require("./errors-Bewwe8mY.cjs");
|
|
6
|
-
const require_Telemetry = require("./Telemetry-
|
|
6
|
+
const require_Telemetry = require("./Telemetry-q5YqdKmI.cjs");
|
|
7
7
|
const require_log = require("./log-BzmBldY6.cjs");
|
|
8
8
|
const require_reporters = require("./reporters-DLK4D0js.cjs");
|
|
9
9
|
const require_intro = require("./intro-PFXmY9bD.cjs");
|
|
10
10
|
const require_spinner = require("./spinner-BQgUoe7F.cjs");
|
|
11
11
|
const require_env = require("./env-Bi4GXVdd.cjs");
|
|
12
12
|
const require_config$1 = require("./config-CkTrJD0E.cjs");
|
|
13
|
-
const require_credentials = require("./credentials-
|
|
14
|
-
const require_package = require("./package-
|
|
13
|
+
const require_credentials = require("./credentials-9OkKaKAr.cjs");
|
|
14
|
+
const require_package = require("./package-CsxsJg57.cjs");
|
|
15
15
|
let node_util = require("node:util");
|
|
16
16
|
let node_os = require("node:os");
|
|
17
17
|
let node_process = require("node:process");
|
|
@@ -73,6 +73,7 @@ function openInBrowser(target) {
|
|
|
73
73
|
(0, tinyexec.x)(node_process.default.platform === "darwin" ? "open" : "xdg-open", [target]).then(ignore, ignore);
|
|
74
74
|
}
|
|
75
75
|
// src/runners/studio/run.ts
|
|
76
|
+
const REFRESH_EVERY_MS = 864e5;
|
|
76
77
|
/**
|
|
77
78
|
* Pairs this machine with Studio and stores the resulting token.
|
|
78
79
|
*
|
|
@@ -86,12 +87,14 @@ async function login({ studioUrl, autoOpen }, { signal, previousCredentials } =
|
|
|
86
87
|
let waiting = false;
|
|
87
88
|
let countdown;
|
|
88
89
|
try {
|
|
90
|
+
const privateKey = (0, _kubb_studio.generateAgentKey)();
|
|
89
91
|
const { token, agent } = await (0, _kubb_studio.pairAgent)({
|
|
90
92
|
studioUrl,
|
|
91
93
|
type: "cli",
|
|
92
94
|
name: node_path.default.basename(node_process.default.cwd()),
|
|
93
95
|
hostname: (0, node_os.hostname)(),
|
|
94
96
|
machineId: await require_credentials.getMachineId(),
|
|
97
|
+
privateKey,
|
|
95
98
|
signal,
|
|
96
99
|
onCode: (session) => {
|
|
97
100
|
require_log.logStep([
|
|
@@ -118,16 +121,23 @@ async function login({ studioUrl, autoOpen }, { signal, previousCredentials } =
|
|
|
118
121
|
});
|
|
119
122
|
clearInterval(countdown);
|
|
120
123
|
spinner.stop(`Paired as ${agent.name}${agent.organizationSlug ? ` · org ${agent.organizationSlug}` : ""}`);
|
|
121
|
-
const
|
|
122
|
-
const credentials = {
|
|
124
|
+
const paired = {
|
|
123
125
|
studioUrl,
|
|
124
126
|
token,
|
|
127
|
+
issuedAt: (/* @__PURE__ */ new Date()).toISOString(),
|
|
128
|
+
privateKey,
|
|
125
129
|
agentId: agent.id,
|
|
126
130
|
agentSlug: agent.slug,
|
|
127
|
-
...agent.organizationSlug ? { organizationSlug: agent.organizationSlug } : {}
|
|
128
|
-
...keepsIdentity && previousCredentials?.projects ? { projects: previousCredentials.projects } : {}
|
|
131
|
+
...agent.organizationSlug ? { organizationSlug: agent.organizationSlug } : {}
|
|
129
132
|
};
|
|
130
|
-
await require_credentials.
|
|
133
|
+
const credentials = await require_credentials.updateCredentials((stored) => {
|
|
134
|
+
const previous = stored ?? previousCredentials;
|
|
135
|
+
const keepsIdentity = previous?.studioUrl === studioUrl && previous.agentId === agent.id;
|
|
136
|
+
return {
|
|
137
|
+
...paired,
|
|
138
|
+
...keepsIdentity && previous.projects ? { projects: previous.projects } : {}
|
|
139
|
+
};
|
|
140
|
+
});
|
|
131
141
|
console.log(`Credentials stored in ${require_credentials.getCredentialsPath()}`);
|
|
132
142
|
return credentials;
|
|
133
143
|
} catch (error) {
|
|
@@ -244,15 +254,18 @@ async function resolvePermissions(options, credentials, configPath = require_con
|
|
|
244
254
|
return granted;
|
|
245
255
|
}
|
|
246
256
|
const answers = Object.fromEntries(pending.map(({ key }) => [key, selected.includes(key)]));
|
|
247
|
-
await require_credentials.
|
|
248
|
-
|
|
249
|
-
|
|
250
|
-
...
|
|
251
|
-
|
|
252
|
-
...
|
|
253
|
-
|
|
257
|
+
await require_credentials.updateCredentials((stored) => {
|
|
258
|
+
const current = stored ?? credentials;
|
|
259
|
+
return {
|
|
260
|
+
...current,
|
|
261
|
+
projects: {
|
|
262
|
+
...current.projects,
|
|
263
|
+
[project]: {
|
|
264
|
+
...current.projects?.[project],
|
|
265
|
+
...answers
|
|
266
|
+
}
|
|
254
267
|
}
|
|
255
|
-
}
|
|
268
|
+
};
|
|
256
269
|
});
|
|
257
270
|
return {
|
|
258
271
|
...granted,
|
|
@@ -307,9 +320,10 @@ async function connect(options, context = {}) {
|
|
|
307
320
|
events.once("SIGTERM", stop);
|
|
308
321
|
}
|
|
309
322
|
let unwatch;
|
|
323
|
+
let refreshTimer;
|
|
310
324
|
try {
|
|
311
325
|
if (!context.prepared) {
|
|
312
|
-
const { getWorkerStatus } = await Promise.resolve().then(() => require("./background-
|
|
326
|
+
const { getWorkerStatus } = await Promise.resolve().then(() => require("./background-DtI6vVet.cjs"));
|
|
313
327
|
if ((await getWorkerStatus()).running) throw new _kubb_core.Diagnostics.Error({
|
|
314
328
|
code: _kubb_core.Diagnostics.code.unknown,
|
|
315
329
|
severity: "error",
|
|
@@ -321,6 +335,45 @@ async function connect(options, context = {}) {
|
|
|
321
335
|
const { configPath } = prepared;
|
|
322
336
|
let hinted = false;
|
|
323
337
|
let pairedAgain = false;
|
|
338
|
+
let recovered = false;
|
|
339
|
+
const warn = (message) => options.logLevel !== "silent" && console.log((0, node_util.styleText)("yellow", message));
|
|
340
|
+
const refreshToken = async (force) => {
|
|
341
|
+
if (!force && Date.now() - Date.parse(credentials.issuedAt ?? "") < REFRESH_EVERY_MS) return false;
|
|
342
|
+
const replaced = credentials.token;
|
|
343
|
+
try {
|
|
344
|
+
const token = await (0, _kubb_studio.refreshAgentToken)({
|
|
345
|
+
studioUrl: options.studioUrl,
|
|
346
|
+
token: replaced,
|
|
347
|
+
machineId: await require_credentials.getMachineId(),
|
|
348
|
+
privateKey: credentials.privateKey,
|
|
349
|
+
signal
|
|
350
|
+
});
|
|
351
|
+
if (!token || credentials.token !== replaced) return false;
|
|
352
|
+
const refreshed = {
|
|
353
|
+
token,
|
|
354
|
+
issuedAt: (/* @__PURE__ */ new Date()).toISOString()
|
|
355
|
+
};
|
|
356
|
+
credentials = {
|
|
357
|
+
...credentials,
|
|
358
|
+
...refreshed
|
|
359
|
+
};
|
|
360
|
+
await require_credentials.updateCredentials((stored) => stored?.token === replaced ? {
|
|
361
|
+
...stored,
|
|
362
|
+
...refreshed
|
|
363
|
+
} : void 0).catch((error) => warn(`Could not store the refreshed token: ${require_errors.toError(error).message}`));
|
|
364
|
+
return true;
|
|
365
|
+
} catch (error) {
|
|
366
|
+
if (!signal.aborted && !(error instanceof _kubb_studio.InvalidAgentTokenError)) warn(`Could not refresh the agent token: ${require_errors.toError(error).message}`);
|
|
367
|
+
return false;
|
|
368
|
+
}
|
|
369
|
+
};
|
|
370
|
+
let refreshing;
|
|
371
|
+
const refresh = ({ force = false } = {}) => refreshing ??= refreshToken(force).finally(() => {
|
|
372
|
+
refreshing = void 0;
|
|
373
|
+
});
|
|
374
|
+
await refresh();
|
|
375
|
+
refreshTimer = setInterval(() => void refresh(), REFRESH_EVERY_MS);
|
|
376
|
+
refreshTimer.unref();
|
|
324
377
|
const hooks = new _kubb_core.Hookable();
|
|
325
378
|
require_reporters.setupReporters(hooks, {
|
|
326
379
|
logLevel: _kubb_core.logLevel[options.logLevel ?? "info"],
|
|
@@ -331,6 +384,7 @@ async function connect(options, context = {}) {
|
|
|
331
384
|
let background = false;
|
|
332
385
|
hooks.hook("studio:connected", async () => {
|
|
333
386
|
pairedAgain = false;
|
|
387
|
+
recovered = false;
|
|
334
388
|
await context.onState?.("connected");
|
|
335
389
|
if (listens && !unwatch) unwatch = watchKeys({
|
|
336
390
|
onBackground: () => {
|
|
@@ -345,9 +399,10 @@ async function connect(options, context = {}) {
|
|
|
345
399
|
require_intro.logTip();
|
|
346
400
|
});
|
|
347
401
|
hooks.hook("studio:reconnecting", () => context.onState?.("reconnecting"));
|
|
348
|
-
|
|
402
|
+
while (true) try {
|
|
349
403
|
await (0, _kubb_studio.connectAgent)({
|
|
350
|
-
token: credentials.token,
|
|
404
|
+
token: () => credentials.token,
|
|
405
|
+
privateKey: credentials.privateKey,
|
|
351
406
|
studioUrl: options.studioUrl,
|
|
352
407
|
configPath,
|
|
353
408
|
version: options.version,
|
|
@@ -361,8 +416,12 @@ async function connect(options, context = {}) {
|
|
|
361
416
|
break;
|
|
362
417
|
} catch (error) {
|
|
363
418
|
if (!(error instanceof _kubb_studio.InvalidAgentTokenError)) throw error;
|
|
419
|
+
if (!recovered && !pairedAgain) {
|
|
420
|
+
recovered = true;
|
|
421
|
+
if (await refresh({ force: true })) continue;
|
|
422
|
+
}
|
|
364
423
|
await context.onState?.("authentication required");
|
|
365
|
-
await require_credentials.clearCredentials();
|
|
424
|
+
await require_credentials.clearCredentials(credentials.token);
|
|
366
425
|
if (pairedAgain) throw new Error(`${error.message} Studio rejected the newly approved token too. Run \`kubb studio login\` and try again.`);
|
|
367
426
|
if (context.onState || require_isCIEnvironment.isCIEnvironment() || !require_env.canUseTTY()) throw new Error(`${error.message} Run \`kubb studio login\` to pair again.`);
|
|
368
427
|
unwatch?.();
|
|
@@ -378,7 +437,7 @@ async function connect(options, context = {}) {
|
|
|
378
437
|
await hooks.callHook("kubb:lifecycle:end");
|
|
379
438
|
unwatch?.();
|
|
380
439
|
if (background) {
|
|
381
|
-
const { startWorker } = await Promise.resolve().then(() => require("./background-
|
|
440
|
+
const { startWorker } = await Promise.resolve().then(() => require("./background-DtI6vVet.cjs"));
|
|
382
441
|
await startWorker(options);
|
|
383
442
|
if (options.logLevel !== "silent") require_intro.logOutro("Running in the background · kubb studio stop");
|
|
384
443
|
return;
|
|
@@ -387,6 +446,7 @@ async function connect(options, context = {}) {
|
|
|
387
446
|
} catch (error) {
|
|
388
447
|
if (!(error instanceof _kubb_studio.PairingCanceledError)) throw error;
|
|
389
448
|
} finally {
|
|
449
|
+
clearInterval(refreshTimer);
|
|
390
450
|
unwatch?.();
|
|
391
451
|
events.off("SIGINT", stop);
|
|
392
452
|
events.off("SIGTERM", stop);
|
|
@@ -456,4 +516,4 @@ exports.prepareConnection = prepareConnection;
|
|
|
456
516
|
exports.resolvePermissions = resolvePermissions;
|
|
457
517
|
exports.runStudio = runStudio;
|
|
458
518
|
|
|
459
|
-
//# sourceMappingURL=run-
|
|
519
|
+
//# sourceMappingURL=run-Dy3EpGtg.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"run-Dy3EpGtg.cjs","names":["process","isCIEnvironment","x","isCIEnvironment","process","createSpinner","generateAgentKey","pairAgent","path","process","hostname","getMachineId","styleText","isRichOutput","updateCredentials","getCredentialsPath","PairingCanceledError","AgentPermission","toPermissionFlag","KUBB_CONFIG_FILENAME","isCIEnvironment","canUseTTY","prompts","getConfigs","Diagnostics","readCredentials","refreshAgentToken","toError","InvalidAgentTokenError","Hookable","logLevelMap","cliReporter","plainWriter","connectAgent","clearCredentials","defaultStudioUrl","trackRun"],"sources":["../../../internals/utils/src/copyToClipboard.ts","../../../internals/utils/src/openInBrowser.ts","../src/runners/studio/run.ts"],"sourcesContent":["import process from 'node:process'\nimport { x } from 'tinyexec'\nimport { isCIEnvironment } from './isCIEnvironment.ts'\n\nconst COMMANDS: Partial<Record<NodeJS.Platform, [string, ...Array<string>]>> = {\n darwin: ['pbcopy'],\n win32: ['clip.exe'],\n linux: ['xclip', '-selection', 'clipboard'],\n}\n\n/**\n * Copies text to the system clipboard with the platform's own tool. Resolves `false` in CI, on a\n * platform without a known tool, or when the tool is missing or fails.\n */\nexport async function copyToClipboard(text: string): Promise<boolean> {\n // Wayland sessions have no X selection for xclip to serve, so they use `wl-copy`.\n const command = process.platform === 'linux' && process.env.WAYLAND_DISPLAY ? (['wl-copy'] as const) : COMMANDS[process.platform]\n if (!command || isCIEnvironment()) return false\n\n const [name, ...args] = command\n // stdout and stderr are ignored: xclip and wl-copy stay alive to serve the selection and would hold open pipes until the timeout.\n const run = x(name, args, { timeout: 2_000, nodeOptions: { stdio: ['pipe', 'ignore', 'ignore'] } })\n // A missing tool closes stdin before the write lands; the rejection below reports it.\n run.process?.stdin?.once('error', () => {})\n run.process?.stdin?.end(text)\n\n return run.then(\n ({ exitCode }) => exitCode === 0,\n () => false,\n )\n}\n","import process from 'node:process'\nimport { x } from 'tinyexec'\nimport { isCIEnvironment } from './isCIEnvironment.ts'\n\nconst ignore = () => {}\n\n/**\n * Opens a URL or local file in the default browser, unless running in CI.\n */\nexport function openInBrowser(target: string): void {\n if (isCIEnvironment()) return\n\n if (process.platform === 'win32') {\n x('cmd', ['/c', 'start', '', target]).then(ignore, ignore)\n return\n }\n x(process.platform === 'darwin' ? 'open' : 'xdg-open', [target]).then(ignore, ignore)\n}\n","import { hostname } from 'node:os'\nimport { toPermissionFlag } from '../../ui/text.ts'\nimport path from 'node:path'\nimport process from 'node:process'\nimport { styleText } from 'node:util'\nimport * as prompts from '@clack/prompts'\nimport { KUBB_CONFIG_FILENAME } from '@internals/shared'\nimport { copyToClipboard, isCIEnvironment, openInBrowser, toError } from '@internals/utils'\nimport type { CLIOptions, Config } from '@kubb/core'\nimport { cliReporter, Diagnostics, Hookable, type KubbHooks, logLevel as logLevelMap } from '@kubb/core'\nimport { connectAgent, defaultStudioUrl, generateAgentKey, InvalidAgentTokenError, pairAgent, PairingCanceledError, refreshAgentToken } from '@kubb/studio'\nimport { AgentPermission } from '@kubb/studio/protocol'\nimport { trackRun } from '../../Telemetry.ts'\nimport { plainWriter } from '../../loggers/plainWriter.ts'\nimport setupReporters from '../../loggers/reporters.ts'\nimport { logIntro, logOutro, logTip } from '../../ui/intro.ts'\nimport { logBlock, logStep } from '../../ui/log.ts'\nimport { createSpinner } from '../../ui/spinner.ts'\nimport { canUseTTY, isRichOutput } from '../../utils/env.ts'\nimport { getConfigs } from '../../config.ts'\nimport { clearCredentials, type Credentials, getCredentialsPath, getMachineId, readCredentials, updateCredentials } from './credentials.ts'\nimport { version } from '../../../package.json'\n\nconst REFRESH_EVERY_MS = 24 * 60 * 60 * 1000\n\nexport type StudioOptions = {\n /**\n * Current `@kubb/cli` version, reported to Studio and used for the telemetry payload.\n */\n version: string\n configPath?: string\n /**\n * Base URL of the Studio instance, for a self-hosted deployment. Resolved before it reaches here,\n * since stored credentials are bound to it.\n */\n studioUrl: string\n /**\n * What Studio may do in this project. Each flag grants outright; the rest are asked once per\n * project through {@link resolvePermissions}.\n */\n permission: Record<AgentPermission, boolean>\n /**\n * Whether to open the approval page in a browser during pairing.\n */\n autoOpen: boolean\n logLevel?: CLIOptions['logLevel']\n}\n\nexport type SnapshotOptions = Pick<StudioOptions, 'configPath' | 'studioUrl' | 'logLevel'> & {\n /**\n * Organization CI API key. Falls back to `KUBB_TOKEN`.\n */\n token?: string\n /**\n * Stable identity for the CI agent. Falls back to CI auto-detection.\n */\n id?: string\n /** Identity of another CI agent to also compare with. Falls back to CI auto-detection. */\n baseId?: string\n /**\n * Package name for the generated tarball. Falls back to the nearest package.json.\n */\n name?: string\n /**\n * Package version for the generated tarball. Falls back to the nearest package.json.\n */\n packageVersion?: string\n /**\n * Print the result as one JSON object instead of a summary.\n */\n json?: boolean\n}\n\n/** The flags a `kubb studio` subcommand parsed; each one is optional since a subcommand declares only the flags it uses. */\nexport type StudioValues = {\n config?: string\n url?: string\n allowRead?: boolean\n allowReadAst?: boolean\n allowWrite?: boolean\n allowConfigEdit?: boolean\n allowInstall?: boolean\n allowUpdate?: boolean\n allowRemove?: boolean\n allowSaveInput?: boolean\n allowFileRefs?: boolean\n allowExec?: boolean\n open?: boolean\n logLevel?: CLIOptions['logLevel']\n}\n\ntype LoginOptions = {\n /**\n * Aborting this cancels an in-flight pairing request or poll and rejects with\n * {@link PairingCanceledError}. Wired to `kubb studio`'s shutdown signal, so Ctrl+C during\n * pairing cancels it instead of leaving the poll running.\n */\n signal?: AbortSignal\n /**\n * Credentials from before this login. When the fresh pairing resolves to the same agent on the\n * same Studio, its saved project permissions carry forward instead of being asked again.\n * Left out for an explicitly requested `kubb studio login`, which always starts clean.\n */\n previousCredentials?: Credentials | null\n}\n\n/**\n * Pairs this machine with Studio and stores the resulting token.\n *\n * The CLI holds a code and the browser approves it, rather than the user copying a token out of\n * the UI. The token comes back over the CLI's own HTTPS POST, so it never lands in a URL, a\n * server log, or a `Referer` header.\n */\nexport async function login({ studioUrl, autoOpen }: StudioOptions, { signal, previousCredentials }: LoginOptions = {}): Promise<Credentials> {\n const spinner = createSpinner()\n // A retry notice stays on screen a while before the countdown takes the line back.\n let retryUntil = 0\n // The spinner only starts once a code is shown.\n let waiting = false\n let countdown: NodeJS.Timeout | undefined\n\n try {\n const privateKey = generateAgentKey()\n const { token, agent } = await pairAgent({\n studioUrl,\n type: 'cli',\n name: path.basename(process.cwd()),\n hostname: hostname(),\n machineId: await getMachineId(),\n privateKey,\n signal,\n onCode: (session) => {\n logStep(\n [\n 'Pair this machine',\n `${styleText('dim', 'Open')} ${styleText('cyan', session.verification_uri)}`,\n `${styleText('dim', 'Code')} ${styleText('bold', session.user_code)}`,\n ].join('\\n'),\n )\n\n if (autoOpen) {\n openInBrowser(session.verification_uri_complete)\n }\n\n // Same fallback as the poll in `@kubb/studio`, so the countdown ends when polling does.\n const deadline = Date.now() + (session.expires_in > 0 ? session.expires_in : 600) * 1000\n let copied = false\n const waitingText = () =>\n `Waiting for approval ${styleText('dim', `expires in ${formatCountdown(deadline - Date.now())}${copied ? ' · code copied' : ''} · ctrl+c to cancel`)}`\n clearInterval(countdown)\n spinner.start(waitingText())\n waiting = true\n // Plain output prints every message, so only an animated spinner ticks.\n if (isRichOutput()) countdown = setInterval(() => Date.now() > retryUntil && spinner.message(waitingText()), 1000)\n // Not awaited: the code shows at once, and the spinner picks up the copy when it lands.\n void copyToClipboard(session.user_code).then((done) => {\n copied = done\n })\n },\n onRetry: (error) => {\n retryUntil = Date.now() + 5000\n spinner.message(`Could not reach Kubb Studio, retrying: ${error.message}`)\n },\n })\n clearInterval(countdown)\n spinner.stop(`Paired as ${agent.name}${agent.organizationSlug ? ` · org ${agent.organizationSlug}` : ''}`)\n\n const paired: Credentials = {\n studioUrl,\n token,\n issuedAt: new Date().toISOString(),\n privateKey,\n agentId: agent.id,\n agentSlug: agent.slug,\n ...(agent.organizationSlug ? { organizationSlug: agent.organizationSlug } : {}),\n }\n const credentials = await updateCredentials((stored) => {\n // Read under the lock, so permissions saved while the pairing waited are kept.\n const previous = stored ?? previousCredentials\n const keepsIdentity = previous?.studioUrl === studioUrl && previous.agentId === agent.id\n return { ...paired, ...(keepsIdentity && previous.projects ? { projects: previous.projects } : {}) }\n })\n\n console.log(`Credentials stored in ${getCredentialsPath()}`)\n\n return credentials\n } catch (error) {\n clearInterval(countdown)\n if (waiting) {\n spinner.stop(error instanceof PairingCanceledError ? 'Pairing canceled' : 'Pairing failed')\n }\n throw error\n }\n}\n\n/** Time left on a pairing code as `m:ss`, never below `0:00`. */\nexport function formatCountdown(ms: number): string {\n const seconds = Math.max(0, Math.ceil(ms / 1000))\n\n return `${Math.floor(seconds / 60)}:${String(seconds % 60).padStart(2, '0')}`\n}\n\n/**\n * What each permission is asked as, in the order the list shows them.\n */\nconst PERMISSIONS: ReadonlyArray<{\n key: AgentPermission\n /**\n * Short label for status output and the connect summary.\n */\n label: string\n title: (configPath: string) => string\n hint: string\n}> = [\n { key: AgentPermission.READ, label: 'read source', title: () => 'Read generated files', hint: 'show code in the browser' },\n { key: AgentPermission.READ_AST, label: 'read spec', title: () => 'Read the parsed spec', hint: 'browse schemas and operations' },\n { key: AgentPermission.WRITE, label: 'write files', title: () => 'Write files to disk', hint: 'generate from the browser' },\n { key: AgentPermission.CONFIG_EDIT, label: 'edit config', title: (configPath) => `Change ${configPath}`, hint: 'edit plugin options' },\n { key: AgentPermission.INSTALL, label: 'add plugins', title: () => 'Install extensions from the registry', hint: 'kubb add from the browser' },\n { key: AgentPermission.UPDATE, label: 'update plugins', title: () => 'Update installed extensions', hint: 'kubb update from the browser' },\n { key: AgentPermission.REMOVE, label: 'remove plugins', title: () => 'Remove extensions', hint: 'kubb remove from the browser' },\n {\n key: AgentPermission.SAVE_INPUT,\n label: 'save input',\n title: (configPath) => `Save the spec from Studio as the input in ${configPath}`,\n hint: 'keep a pasted spec, URL, or git file',\n },\n { key: AgentPermission.FILE_REFS, label: 'outside refs', title: () => 'Let a $ref read files outside the project', hint: 'specs that share schemas' },\n { key: AgentPermission.EXEC, label: 'run tools', title: () => 'Run the formatter, linter, and postGenerate', hint: 'after each generation' },\n]\n\n/**\n * Two permissions per row, each marked granted or not, with the flags that grant the missing ones\n * after the last row. For `kubb studio status`.\n */\nexport function formatPermissionRows(granted: Partial<Record<AgentPermission, boolean>>): Array<string> {\n const width = Math.max(...PERMISSIONS.map(({ label }) => label.length))\n const cells = PERMISSIONS.map(({ key, label }) => `${granted[key] ? styleText('green', '✓') : styleText('red', '✖')} ${label.padEnd(width)}`)\n const rows = Array.from({ length: Math.ceil(cells.length / 2) }, (_, index) => cells.slice(index * 2, index * 2 + 2).join(' '))\n const flags = PERMISSIONS.filter(({ key }) => !granted[key])\n .map(({ key }) => toPermissionFlag(key))\n .join(' ')\n\n return flags ? [...rows.slice(0, -1), `${rows.at(-1)} ${styleText('dim', flags)}`] : rows\n}\n\n/**\n * Resolves Studio permissions for the current project.\n * Flags win, saved answers are reused, and the rest are asked in one list whose answers are stored\n * in `~/.kubb/credentials.json`.\n */\nexport async function resolvePermissions(\n options: StudioOptions,\n credentials: Credentials,\n configPath: string = KUBB_CONFIG_FILENAME,\n { edit = false }: { edit?: boolean } = {},\n): Promise<Record<AgentPermission, boolean>> {\n const project = process.cwd()\n const remembered = credentials.projects?.[project]\n const granted = Object.fromEntries(PERMISSIONS.map(({ key }) => [key, options.permission[key] || remembered?.[key] === true])) as Record<\n AgentPermission,\n boolean\n >\n // `edit` asks again for every permission no flag grants, with the saved ones checked.\n const pending = PERMISSIONS.filter(({ key }) => !options.permission[key] && (edit || typeof remembered?.[key] !== 'boolean'))\n\n if (!pending.length || isCIEnvironment() || !canUseTTY()) return granted\n\n prompts.updateSettings({ withGuide: true })\n const selected = await prompts.multiselect({\n message: 'What may Kubb Studio do in this project?',\n options: pending.map(({ key, title, hint }) => ({ value: key, label: title(configPath), hint })),\n ...(edit ? { initialValues: pending.filter(({ key }) => remembered?.[key] === true).map(({ key }) => key) } : {}),\n required: false,\n })\n // A canceled list grants nothing and saves nothing, so the next run asks again.\n if (prompts.isCancel(selected)) {\n if (edit) throw new Error('Canceled. Permissions are unchanged.')\n return granted\n }\n\n const answers = Object.fromEntries(pending.map(({ key }) => [key, selected.includes(key)]))\n // Merged into the stored record, so a token refreshed by a running connection is kept.\n await updateCredentials((stored) => {\n const current = stored ?? credentials\n return { ...current, projects: { ...current.projects, [project]: { ...current.projects?.[project], ...answers } } }\n })\n\n return { ...granted, ...answers }\n}\n\n/**\n * Loads the project's Kubb config the same way `kubb generate` does, one entry per `defineConfig(...)` entry.\n */\nexport async function loadConfigs(options: Pick<StudioOptions, 'configPath' | 'logLevel'>): Promise<{ configPath: string; configs: Array<Config> }> {\n const { configPath, configs } = await getConfigs({ configPath: options.configPath, logLevel: options.logLevel })\n\n if (!configs.length) {\n throw new Diagnostics.Error({\n code: Diagnostics.code.unknown,\n severity: 'error',\n message: 'Config not defined, create a kubb.config.ts or pass it with --config',\n })\n }\n\n // `getConfigs` resolves this to an absolute path. Relativized here, once, so the permission\n // prompt and the path Studio receives over the wire both show the project-relative form instead\n // of leaking the local filesystem layout.\n return { configPath: path.relative(process.cwd(), configPath) || configPath, configs }\n}\n\nexport type PreparedConnection = {\n configPath: string\n credentials: Credentials\n permissions: StudioOptions['permission']\n}\n\n/** Validates the project and resolves pairing and permissions before starting its worker. */\nexport async function prepareConnection(options: StudioOptions, signal?: AbortSignal): Promise<PreparedConnection> {\n const { configPath } = await loadConfigs(options)\n const stored = await readCredentials()\n const credentials = await (async () => {\n if (stored?.studioUrl === options.studioUrl) return stored\n if (isCIEnvironment()) {\n throw new Diagnostics.Error({\n code: Diagnostics.code.unknown,\n severity: 'error',\n message: `Not paired with ${options.studioUrl}. In CI, run \\`kubb studio snapshot\\` instead, or run \\`kubb studio login\\` on a machine with a browser.`,\n })\n }\n return login(options, { signal })\n })()\n const permissions = await resolvePermissions(options, credentials, configPath)\n return { configPath, credentials, permissions }\n}\n\nexport type WorkerState = 'starting' | 'connected' | 'reconnecting' | 'authentication required' | 'stopped'\n\n/** Runs the same project connection in the foreground or in a background worker. */\nexport async function connect(\n options: StudioOptions,\n context: {\n prepared?: PreparedConnection\n signal?: AbortSignal\n onState?: (state: WorkerState) => void | Promise<void>\n } = {},\n): Promise<void> {\n const shutdown = new AbortController()\n const signal = context.signal ?? shutdown.signal\n const stop = () => shutdown.abort()\n const events = process as unknown as NodeJS.EventEmitter\n if (!context.signal) {\n events.once('SIGINT', stop)\n events.once('SIGTERM', stop)\n }\n let unwatch: (() => void) | undefined\n let refreshTimer: NodeJS.Timeout | undefined\n try {\n if (!context.prepared) {\n const { getWorkerStatus } = await import('./background.ts')\n const worker = await getWorkerStatus()\n if (worker.running)\n throw new Diagnostics.Error({\n code: Diagnostics.code.unknown,\n severity: 'error',\n message: 'This project is running in the background. Run `kubb studio stop` first.',\n })\n }\n const prepared = context.prepared ?? (await prepareConnection(options, signal))\n let { credentials, permissions } = prepared\n const { configPath } = prepared\n let hinted = false\n // Set by a fresh pairing until it connects, so a token rejected right after approval fails the run instead of looping.\n let pairedAgain = false\n let recovered = false\n\n const warn = (message: string) => options.logLevel !== 'silent' && console.log(styleText('yellow', message))\n // Resolves whether the token changed; a failure keeps the old one.\n const refreshToken = async (force: boolean): Promise<boolean> => {\n if (!force && Date.now() - Date.parse(credentials.issuedAt ?? '') < REFRESH_EVERY_MS) return false\n const replaced = credentials.token\n try {\n const token = await refreshAgentToken({\n studioUrl: options.studioUrl,\n token: replaced,\n machineId: await getMachineId(),\n privateKey: credentials.privateKey,\n signal,\n })\n // A pairing that finished meanwhile owns the credentials now.\n if (!token || credentials.token !== replaced) return false\n const refreshed = { token, issuedAt: new Date().toISOString() }\n credentials = { ...credentials, ...refreshed }\n // Only the token changes on disk, so permissions saved since this run read the file are kept.\n await updateCredentials((stored) => (stored?.token === replaced ? { ...stored, ...refreshed } : undefined)).catch((error: unknown) =>\n warn(`Could not store the refreshed token: ${toError(error).message}`),\n )\n return true\n } catch (error) {\n if (!signal.aborted && !(error instanceof InvalidAgentTokenError)) warn(`Could not refresh the agent token: ${toError(error).message}`)\n return false\n }\n }\n // The timer and a rejected token share one request: two refreshes of one token cannot both succeed.\n let refreshing: Promise<boolean> | undefined\n const refresh = ({ force = false } = {}): Promise<boolean> =>\n (refreshing ??= refreshToken(force).finally(() => {\n refreshing = undefined\n }))\n await refresh()\n refreshTimer = setInterval(() => void refresh(), REFRESH_EVERY_MS)\n refreshTimer.unref()\n\n // The background worker writes to a log file, so it gets the plain logger rather than the\n // animated one. The logger also covers the `studio:*` events and each generation run.\n const hooks = new Hookable<KubbHooks>()\n setupReporters(hooks, {\n logLevel: logLevelMap[options.logLevel ?? 'info'],\n reporters: [cliReporter],\n ...(context.onState ? { writer: plainWriter } : {}),\n })\n // `b` hands the session to the background worker; only a foreground run in a terminal listens.\n const listens = !context.onState && process.stdin.isTTY === true && canUseTTY()\n let background = false\n hooks.hook('studio:connected', async () => {\n pairedAgain = false\n recovered = false\n await context.onState?.('connected')\n if (listens && !unwatch) {\n unwatch = watchKeys({\n onBackground: () => {\n background = true\n stop()\n },\n onStop: stop,\n })\n }\n if (hinted || context.onState || options.logLevel === 'silent') return\n hinted = true\n logBlock([\n `${styleText('dim', 'Project')} ${path.basename(process.cwd())} ${styleText(\n 'dim',\n PERMISSIONS.filter(({ key }) => permissions[key])\n .map(({ label }) => label)\n .join(' · ') || 'no permissions',\n )}`,\n styleText('dim', listens ? 'Press b to keep running in the background, Ctrl+C to disconnect' : 'Press Ctrl+C to disconnect'),\n ])\n logTip()\n })\n hooks.hook('studio:reconnecting', () => context.onState?.('reconnecting'))\n\n while (true) {\n try {\n await connectAgent({\n token: () => credentials.token,\n privateKey: credentials.privateKey,\n studioUrl: options.studioUrl,\n configPath,\n version: options.version,\n root: process.cwd(),\n agentType: 'cli',\n permissions,\n loadConfigs: async () => (await loadConfigs(options)).configs,\n hooks,\n signal,\n })\n break\n } catch (error) {\n if (!(error instanceof InvalidAgentTokenError)) throw error\n // The answer to an earlier refresh may have been lost, so the token is traded in once more.\n if (!recovered && !pairedAgain) {\n recovered = true\n if (await refresh({ force: true })) continue\n }\n await context.onState?.('authentication required')\n await clearCredentials(credentials.token)\n if (pairedAgain) throw new Error(`${error.message} Studio rejected the newly approved token too. Run \\`kubb studio login\\` and try again.`)\n if (context.onState || isCIEnvironment() || !canUseTTY()) throw new Error(`${error.message} Run \\`kubb studio login\\` to pair again.`)\n\n // The pairing prompts need stdin back.\n unwatch?.()\n unwatch = undefined\n console.log(styleText('yellow', `${error.message} Pairing again...`))\n credentials = await login(options, { signal, previousCredentials: credentials })\n pairedAgain = true\n permissions = await resolvePermissions(options, credentials, configPath)\n }\n }\n // Stops the \"Ready for jobs\" spinner, which would otherwise keep drawing under the closing line.\n await hooks.callHook('kubb:lifecycle:end')\n unwatch?.()\n if (background) {\n const { startWorker } = await import('./background.ts')\n await startWorker(options)\n if (options.logLevel !== 'silent') logOutro('Running in the background · kubb studio stop')\n return\n }\n if (!context.onState && signal.aborted && options.logLevel !== 'silent') logOutro('Disconnected')\n } catch (error) {\n if (!(error instanceof PairingCanceledError)) throw error\n } finally {\n clearInterval(refreshTimer)\n unwatch?.()\n events.off('SIGINT', stop)\n events.off('SIGTERM', stop)\n }\n}\n\n/**\n * Listens for single keys on a TTY stdin. Raw mode turns Ctrl+C into a key instead of SIGINT, so it\n * is handled here too. Returns the function that restores the terminal, safe to call twice.\n */\nexport function watchKeys({ onBackground, onStop }: { onBackground: () => void; onStop: () => void }): () => void {\n const stdin = process.stdin\n const onData = (data: Buffer) => {\n const key = data.toString()\n if (key === 'b' || key === 'B') onBackground()\n if (key === '\\u0003') onStop()\n }\n // A clack spinner reads stdin too and exits the process on Ctrl+C, before the session can close\n // its socket, so its Ctrl+C alias is lifted while these keys are read.\n const cancelAlias = prompts.settings.aliases.get('\\u0003')\n prompts.settings.aliases.delete('\\u0003')\n stdin.setRawMode(true)\n stdin.on('data', onData)\n stdin.resume()\n let restored = false\n\n return () => {\n if (restored) return\n restored = true\n if (cancelAlias) prompts.settings.aliases.set('\\u0003', cancelAlias)\n stdin.off('data', onData)\n stdin.setRawMode(false)\n stdin.pause()\n }\n}\n\n/**\n * Runs a Studio command from its parsed flags: builds the {@link StudioOptions}, prints the intro,\n * and reports the run to telemetry. A failure is printed and sets the exit code instead of throwing.\n */\nexport async function runStudio(\n values: StudioValues,\n action: (options: StudioOptions) => Promise<unknown>,\n { block = false, json = false }: { block?: boolean; json?: boolean } = {},\n): Promise<void> {\n const options: StudioOptions = {\n version,\n configPath: values.config,\n studioUrl: values.url ?? defaultStudioUrl,\n permission: Object.fromEntries(Object.values(AgentPermission).map((key) => [key, values[key] ?? false])) as Record<AgentPermission, boolean>,\n autoOpen: values.open ?? true,\n logLevel: values.logLevel,\n }\n const report = trackRun({ command: 'studio', hrStart: process.hrtime() })\n\n try {\n if (options.logLevel !== 'silent' && !json) {\n logIntro({\n warning: styleText('yellow', 'This feature is still under development, use with caution'),\n block,\n })\n }\n\n await action(options)\n\n await report({ status: 'success' })\n } catch (error) {\n await report({ status: 'failed' })\n console.error(toError(error).message)\n process.exitCode = 1\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;AAIA,MAAM,WAAyE;CAC7E,QAAQ,CAAC,QAAQ;CACjB,OAAO,CAAC,UAAU;CAClB,OAAO;EAAC;EAAS;EAAc;CAAW;AAC5C;;;;;AAMA,eAAsB,gBAAgB,MAAgC;CAEpE,MAAM,U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,IAAI,QAAQ,aAAa,YAAY,CAAC,MACpC,cAAA,SAAS;GACP,UAAA,GAASG,UAAAA,UAAAA,CAAU,UAAU,2DAA2D;GACxF;EACF,CAAC;EAGH,MAAM,OAAO,OAAO;EAEpB,MAAM,OAAO,EAAE,QAAQ,UAAU,CAAC;CACpC,SAAS,OAAO;EACd,MAAM,OAAO,EAAE,QAAQ,SAAS,CAAC;EACjC,QAAQ,MAAMe,eAAAA,QAAQ,KAAK,CAAC,CAAC,OAAO;EACpC,aAAA,QAAA,WAAmB;CACrB;AACF"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
export { t as connect, a as login, s as resolvePermissions, c as runStudio } from "./run-
|
|
1
|
+
export { t as connect, a as login, s as resolvePermissions, c as runStudio } from "./run-8gqo-bOB.js";
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import "./rolldown-runtime-BowF1xt-.js";
|
|
2
2
|
import { n as toError } from "./errors-CEzFbRvL.js";
|
|
3
|
-
import { n as trackRun } from "./Telemetry-
|
|
3
|
+
import { n as trackRun } from "./Telemetry-4T6PkdJo.js";
|
|
4
4
|
import { styleText } from "node:util";
|
|
5
5
|
import process from "node:process";
|
|
6
6
|
// src/runners/mcp/run.ts
|
|
@@ -28,4 +28,4 @@ async function run() {
|
|
|
28
28
|
}
|
|
29
29
|
export { run };
|
|
30
30
|
|
|
31
|
-
//# sourceMappingURL=run-
|
|
31
|
+
//# sourceMappingURL=run-QBGgsQ2B.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"run-
|
|
1
|
+
{"version":3,"file":"run-QBGgsQ2B.js","names":[],"sources":["../src/runners/mcp/run.ts"],"sourcesContent":["import process from 'node:process'\nimport { styleText } from 'node:util'\nimport { toError } from '@internals/utils'\nimport type * as McpModule from '@kubb/mcp'\nimport { trackRun } from '../../Telemetry.ts'\n\n/**\n * Starts the `@kubb/mcp` server over stdio and reports the outcome to telemetry.\n */\nexport async function run(): Promise<void> {\n const { run: startMcpServer } = (await import('@kubb/mcp')) as typeof McpModule\n\n const report = trackRun({ command: 'mcp', hrStart: process.hrtime() })\n\n try {\n // The MCP stdio transport owns stdout: anything else written there corrupts the JSON-RPC stream.\n console.error(styleText('cyan', '⏳ Starting MCP server...'))\n console.warn(styleText('yellow', 'This feature is still under development, use with caution'))\n const server = startMcpServer()\n // Report once the client introduces itself, so the event names the client (e.g. `claude-code`, `cursor-vscode`).\n server.on('initialize', ({ clientInfo }) => void report({ status: 'success', mcpClient: clientInfo.name }), { once: true })\n } catch (error) {\n await report({ status: 'failed' })\n console.error(toError(error).message)\n process.exitCode = 1\n }\n}\n"],"mappings":";;;;;;;;;AASA,eAAsB,MAAqB;CACzC,MAAM,EAAE,KAAK,mBAAoB,MAAM,OAAO;CAE9C,MAAM,SAAS,SAAS;EAAE,SAAS;EAAO,SAAS,QAAQ,OAAO;CAAE,CAAC;CAErE,IAAI;EAEF,QAAQ,MAAM,UAAU,QAAQ,0BAA0B,CAAC;EAC3D,QAAQ,KAAK,UAAU,UAAU,2DAA2D,CAAC;EAG7F,eAAK,CAAC,CAAC,GAAG,eAAe,EAAE,iBAAiB,KAAK,OAAO;GAAE,QAAQ;GAAW,WAAW,WAAW;EAAK,CAAC,GAAG,EAAE,MAAM,KAAK,CAAC;CAC5H,SAAS,OAAO;EACd,MAAM,OAAO,EAAE,QAAQ,SAAS,CAAC;EACjC,QAAQ,MAAM,QAAQ,KAAK,CAAC,CAAC,OAAO;EACpC,QAAQ,WAAW;CACrB;AACF"}
|
|
@@ -10,7 +10,7 @@ const require_log = require("./log-BzmBldY6.cjs");
|
|
|
10
10
|
const require_registry = require("./registry-CTVAqQFn.cjs");
|
|
11
11
|
const require_installWithSpinner = require("./installWithSpinner-qjIqjyiW.cjs");
|
|
12
12
|
const require_utils = require("./utils-_hY0r-7x.cjs");
|
|
13
|
-
const require_package = require("./package-
|
|
13
|
+
const require_package = require("./package-CsxsJg57.cjs");
|
|
14
14
|
let node_util = require("node:util");
|
|
15
15
|
let gunshi = require("gunshi");
|
|
16
16
|
let node_process = require("node:process");
|
|
@@ -372,4 +372,4 @@ const command = (0, gunshi.defineWithTypes)()({
|
|
|
372
372
|
exports.command = command;
|
|
373
373
|
exports.run = run;
|
|
374
374
|
|
|
375
|
-
//# sourceMappingURL=run-
|
|
375
|
+
//# sourceMappingURL=run-q2tnHViw.cjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"run-DnsSsAj2.cjs","names":["clack","editConfig","ConfigEditOperation","Diagnostics","KUBB_CONFIG_FILENAME","getConfigs","createKubb","resolveCommand","process","isInteractiveRun","fetchRegistryIndex","registryUrl","incompatibility","exists","path","detectPackageManager","withSpinner","initPackageJson","findSpecFiles","readSpecInfo","pluralize","initDefaults","findPlugin","parsePluginsFlag","isHttpUrl","styleText","missingPluginDependencies","KUBB_PACKAGE_NAME","version","installSpec","installPackages","installWithSpinner","write","addGenerateScript","generateScript","formatMs","getElapsedMs","defineWithTypes","dryRunId"],"sources":["../../../internals/shared/src/init.ts","../src/runners/init/run.ts"],"sourcesContent":["/** The `kubb.config.ts` `kubb init` writes before `kubb add` puts each plugin in. */\nexport function generateConfigFile({ inputPath, outputPath }: { inputPath: string; outputPath: string }): string {\n return `import { defineConfig } from 'kubb/config'\n\nexport default defineConfig({\n input: '${inputPath}',\n output: {\n path: '${outputPath}',\n clean: true,\n },\n plugins: [],\n})\n`\n}\n","import path from 'node:path'\nimport process from 'node:process'\nimport { styleText } from 'node:util'\nimport * as clack from '@clack/prompts'\nimport type { DryRunExtension } from '@gunshi/plugin-dryrun'\nimport { defineWithTypes } from 'gunshi'\nimport { resolveCommand } from 'package-manager-detector'\nimport { ConfigEditOperation, editConfig, generateConfigFile, initDefaults, KUBB_CONFIG_FILENAME, KUBB_PACKAGE_NAME } from '@internals/shared'\nimport { exists, formatMs, getElapsedMs, write } from '@internals/utils'\nimport { createKubb, Diagnostics, type RegistryEntry } from '@kubb/core'\nimport { dryRunId, type DryRunExtensions } from '../../commands/shared.ts'\nimport { getConfigs } from '../../config.ts'\nimport { isHttpUrl, pluralize } from '../../ui/text.ts'\nimport { isInteractiveRun, logIntro, logOutro } from '../../ui/intro.ts'\nimport { logBlock, logError, logStep, logWarn } from '../../ui/log.ts'\nimport { withSpinner } from '../../ui/spinner.ts'\nimport { fetchRegistryIndex, incompatibility, installSpec, registryUrl } from '../../utils/registry.ts'\nimport { installWithSpinner } from '../installWithSpinner.ts'\nimport {\n addGenerateScript,\n detectPackageManager,\n findPlugin,\n findSpecFiles,\n generateScript,\n initPackageJson,\n installPackages,\n missingPluginDependencies,\n type PackageManagerInfo,\n parsePluginsFlag,\n readSpecInfo,\n} from './utils.ts'\nimport { version } from '../../../package.json'\n\nfunction cancelAndExit(message = 'Operation canceled.'): never {\n clack.cancel(message)\n process.exit(0)\n}\n\nfunction unwrap<T>(value: T): Exclude<T, symbol> {\n if (clack.isCancel(value)) cancelAndExit()\n return value as Exclude<T, symbol>\n}\n\ntype InitOptions = {\n /**\n * When `true`, skips all interactive prompts and uses the detected or default values.\n */\n yes: boolean\n /**\n * Input path flag value from `--input`. When provided, skips the input prompt.\n */\n input?: string\n /**\n * Output directory flag value from `--output`. When provided, skips the output prompt.\n */\n output?: string\n /**\n * Comma-separated plugin list from `--plugins`, e.g. `'plugin-ts,zod'`. When provided, skips the plugin selection prompt.\n */\n plugins?: string\n /**\n * Dry-run extension from `@gunshi/plugin-dryrun`. When enabled, package installation, file\n * writes, and the first run are skipped.\n */\n dryRun: DryRunExtension\n}\n\ntype Choices = {\n inputPath: string\n outputPath: string\n plugins: Array<RegistryEntry>\n}\n\n/** The full `kubb.config.ts` for `choices`, with each plugin added the way `kubb add` adds it. */\nfunction buildConfig({ inputPath, outputPath, plugins }: Choices): string {\n const { source, outcomes } = editConfig({\n source: generateConfigFile({ inputPath, outputPath }),\n edits: plugins.map((entry) => ({ operation: ConfigEditOperation.ADD_PLUGIN, plugin: entry.artifact.package })),\n extensions: new Map(plugins.map(({ artifact, manifest }) => [artifact.package, { package: artifact.package, version: artifact.version, manifest }])),\n })\n const failed = outcomes.find((outcome) => !outcome.applied)\n if (failed && failed.edit.operation === ConfigEditOperation.ADD_PLUGIN)\n throw new Diagnostics.Error({\n code: Diagnostics.code.unknown,\n severity: 'error',\n message: `Could not add ${failed.edit.plugin} to ${KUBB_CONFIG_FILENAME}: ${failed.reason}`,\n help: `Run kubb init without that plugin, then add it with kubb add.`,\n })\n return source\n}\n\n/** Generates from the config at `configPath` without reporters, and returns how many files it wrote. */\nasync function firstRun(configPath: string): Promise<number> {\n const { configs } = await getConfigs({ configPath })\n let files = 0\n for (const config of configs) {\n const result = await createKubb(config).generate()\n if (!result.success) throw new Error(result.diagnostics.flatMap((diagnostic) => (diagnostic.severity === 'error' ? [diagnostic.message] : [])).join('\\n'))\n files += result.files.length\n }\n return files\n}\n\n/** The command that runs `kubb generate`: the `generate` script when it runs Kubb, otherwise `npx kubb generate`. */\nfunction generateCommand({ packageManager, script, watch }: { packageManager: PackageManagerInfo; script: string | undefined; watch: boolean }): string {\n if (script !== 'kubb generate') return `npx kubb generate${watch ? ' --watch' : ''}`\n const { command, args } = resolveCommand(packageManager.agent, 'run', watch ? ['generate', '--watch'] : ['generate'])!\n return [command, ...args].join(' ')\n}\n\n/**\n * Runs the Kubb setup wizard: detects the package manager and specs, asks for the spec, plugins, and\n * output folder, shows the config for review, then installs, writes `kubb.config.ts`, adds a\n * `generate` script, and runs the first generation.\n * Pass `yes: true` to skip all prompts and print one line per step.\n */\nexport async function run({ yes, input: inputFlag, output: outputFlag, plugins: pluginsFlag, dryRun }: InitOptions): Promise<void> {\n const cwd = process.cwd()\n\n if (!yes) logIntro({ title: isInteractiveRun({ yes, dryRun: dryRun.enabled }) ? undefined : 'Set up Kubb' })\n\n try {\n // Start the registry fetch now but await it only at the plugin step, so the first prompt never waits on the network\n const registry = fetchRegistryIndex({ registry: registryUrl() }).then((entries) =>\n entries.filter((entry) => entry.kind === 'plugin' && !incompatibility(entry.manifest)),\n )\n registry.catch(() => {})\n\n if (!(await exists(path.join(cwd, 'package.json')))) {\n if (!yes) {\n const shouldInit = unwrap(await clack.confirm({ message: 'No package.json found. Would you like to create one?', initialValue: true }))\n if (!shouldInit) cancelAndExit()\n }\n\n const packageManager = await detectPackageManager(cwd)\n await withSpinner({\n message: `Initializing package.json with ${packageManager.name}`,\n promise: initPackageJson(cwd, packageManager),\n done: () => `Created package.json with ${packageManager.name}`,\n failed: 'Could not create package.json',\n plain: yes,\n })\n }\n\n const packageManager = await detectPackageManager(cwd)\n const specs = await findSpecFiles(cwd)\n\n if (!yes) {\n logStep(`Package manager ${packageManager.name}`)\n if (specs[0]) {\n const { version: specVersion, operations } = await readSpecInfo(path.join(cwd, specs[0]))\n const details = [\n specs[0].slice(2),\n specVersion ? `${specVersion.startsWith('2') ? 'Swagger' : 'OpenAPI'} ${specVersion}` : undefined,\n operations === undefined ? undefined : pluralize(operations, 'operation'),\n specs.length > 1 ? `+${specs.length - 1} more` : undefined,\n ]\n logStep(`Found ${details.filter(Boolean).join(' · ')}`)\n }\n }\n\n // `--plugins` and `--yes` need the registry before any prompt; the interactive path reads it at the plugin step\n const plugins = pluginsFlag || yes ? await registry : undefined\n const defaultPlugins = (entries: Array<RegistryEntry>) => initDefaults.plugins.flatMap((id) => findPlugin({ plugins: entries, id }) ?? [])\n\n const flagPlugins = pluginsFlag && plugins ? parsePluginsFlag({ plugins, value: pluginsFlag }) : undefined\n\n let choices: Choices = {\n inputPath: inputFlag ?? specs[0] ?? initDefaults.inputPath,\n outputPath: outputFlag ?? initDefaults.outputPath,\n plugins: flagPlugins ?? (plugins ? defaultPlugins(plugins) : []),\n }\n if (yes && !choices.plugins.length) {\n throw new Error('The registry has no default plugin. Pass --plugins to choose one.')\n }\n\n async function askInput(current: string): Promise<string> {\n const choice = specs.length\n ? unwrap(\n await clack.select({\n message: 'Which spec should Kubb read?',\n options: [\n ...specs.map((spec) => ({ value: spec, label: spec, hint: 'found in this repo' })),\n { value: 'url', label: 'A URL' },\n { value: 'file', label: 'Another file' },\n ],\n initialValue: specs.includes(current) ? current : isHttpUrl(current) ? 'url' : 'file',\n }),\n )\n : isHttpUrl(current)\n ? 'url'\n : 'file'\n if (specs.includes(choice)) return choice\n const isUrl = choice === 'url'\n const initial = isUrl === isHttpUrl(current) && !specs.includes(current) ? current : undefined\n return unwrap(\n await clack.text({\n message: isUrl ? 'Spec URL' : 'Spec path',\n placeholder: isUrl ? 'https://example.com/openapi.yaml' : initDefaults.inputPath,\n initialValue: initial,\n defaultValue: isUrl ? undefined : initDefaults.inputPath,\n validate: (value) => {\n if (isUrl && !isHttpUrl(value ?? '')) return 'Enter an http(s) URL'\n },\n }),\n )\n }\n\n async function askPlugins(previous: Array<RegistryEntry>): Promise<Array<RegistryEntry>> {\n const plugins = await registry\n const current = previous.length ? previous : defaultPlugins(plugins)\n const width = Math.max(...plugins.map((entry) => entry.manifest.displayName.length))\n const nameWidth = Math.max(...plugins.map((entry) => entry.manifest.name.length))\n const values = unwrap(\n await clack.multiselect({\n message: 'What should Kubb generate?',\n options: plugins.map(({ id, manifest }) => ({\n value: id,\n label: `${manifest.displayName.padEnd(width)} ${styleText('dim', manifest.name.padEnd(nameWidth))}`.trimEnd(),\n })),\n initialValues: current.map((entry) => entry.id),\n required: true,\n }),\n )\n return plugins.filter((entry) => values.includes(entry.id))\n }\n\n // Flags for all three choices leave nothing to ask or review, as before the review step existed\n const answered = yes || Boolean(inputFlag && outputFlag && pluginsFlag)\n if (!answered) {\n let firstPass = true\n while (true) {\n // The first pass skips the questions a flag answered; \"Change a choice\" asks them all again.\n choices = {\n inputPath: firstPass && inputFlag ? inputFlag : await askInput(choices.inputPath),\n plugins: firstPass && flagPlugins ? flagPlugins : await askPlugins(choices.plugins),\n outputPath:\n firstPass && outputFlag\n ? outputFlag\n : unwrap(await clack.text({ message: 'Output folder', placeholder: choices.outputPath, defaultValue: choices.outputPath })),\n }\n firstPass = false\n const missing = missingPluginDependencies(choices.plugins.map((entry) => entry.manifest))\n if (missing.length) {\n logWarn(`${missing.join('\\n')}\\nAdd the missing plugins.`)\n continue\n }\n const config = buildConfig(choices)\n const packages = [KUBB_PACKAGE_NAME, ...choices.plugins.map((entry) => entry.artifact.package)]\n logStep(`Review ${KUBB_CONFIG_FILENAME}`)\n logBlock([...config.trimEnd().split('\\n'), '', `${styleText('dim', 'Installs')} ${packages.join(' ')} with ${packageManager.name}`])\n const configExists = await exists(path.join(cwd, KUBB_CONFIG_FILENAME))\n const confirmed = unwrap(\n await clack.select({\n message: configExists ? `${KUBB_CONFIG_FILENAME} exists. Overwrite it?` : 'Create it?',\n options: [\n { value: true, label: 'Yes' },\n { value: false, label: 'Change a choice' },\n ],\n }),\n )\n if (confirmed) break\n }\n }\n\n // Check the selection against the plugins' manifests before installing anything\n const missing = missingPluginDependencies(choices.plugins.map((entry) => entry.manifest))\n if (missing.length) {\n throw new Diagnostics.Error({\n code: Diagnostics.code.missingDependency,\n severity: 'error',\n message: `${missing.join('\\n')}\\nAdd the missing plugins and run kubb init again.`,\n })\n }\n\n const configPath = path.join(cwd, KUBB_CONFIG_FILENAME)\n if (answered && !yes && (await exists(configPath))) {\n const overwrite = unwrap(await clack.confirm({ message: `${KUBB_CONFIG_FILENAME} exists. Overwrite it?`, initialValue: false }))\n if (!overwrite) cancelAndExit('Keeping existing configuration.')\n }\n\n // Install `kubb` at the running CLI's version and each plugin at the version the registry pins\n const packagesToInstall = [`${KUBB_PACKAGE_NAME}@${version}`, ...choices.plugins.map((entry) => installSpec(entry.artifact))]\n const packageNames = [KUBB_PACKAGE_NAME, ...choices.plugins.map((entry) => entry.artifact.package)]\n const dry = { message: `install ${packagesToInstall.length} packages with ${packageManager.name}` }\n if (yes) {\n await withSpinner({\n message: '',\n promise: dryRun.run(() => installPackages(packagesToInstall, packageManager, cwd), dry),\n done: () => `Installed ${packageNames.join(' ')} with ${packageManager.name}`,\n plain: true,\n })\n } else {\n await installWithSpinner({\n packages: packagesToInstall,\n names: `${packagesToInstall.length} packages`,\n packageManager,\n cwd,\n install: async (packages, packageManager, cwd, onLine) => void (await dryRun.run(() => installPackages(packages, packageManager, cwd, onLine), dry)),\n })\n }\n\n await withSpinner({\n message: `Writing ${KUBB_CONFIG_FILENAME}`,\n promise: dryRun.run(async () => void (await write(configPath, buildConfig(choices))), { message: `write ${KUBB_CONFIG_FILENAME}` }),\n done: () => `Wrote ${KUBB_CONFIG_FILENAME}`,\n failed: `Could not write ${KUBB_CONFIG_FILENAME}`,\n plain: yes,\n })\n\n const scriptAdded = await dryRun.run(() => addGenerateScript(cwd), {\n message: 'add a generate script to package.json',\n resolve: async () => (await generateScript(cwd)) === undefined,\n })\n if (scriptAdded && !yes) logStep('Added \"generate\": \"kubb generate\" to package.json')\n\n const script = scriptAdded ? 'kubb generate' : await generateScript(cwd)\n const runStart = process.hrtime()\n try {\n await dryRun.run(\n () =>\n withSpinner({\n message: 'Running the first generation',\n promise: firstRun(configPath),\n done: (files) =>\n yes\n ? `Generated ${pluralize(files, 'file')} in ${choices.outputPath}`\n : `First run ${pluralize(files, 'file')} in ${choices.outputPath} · ${formatMs(getElapsedMs(runStart))}`,\n failed: 'First run failed',\n plain: yes,\n }),\n { message: 'run the first generation', resolve: () => 0 },\n )\n } catch (error) {\n logError(error instanceof Error ? error.message : String(error))\n const message = `Kubb is set up, but the first run failed. Fix the error, then run ${generateCommand({ packageManager, script, watch: false })}.`\n if (yes) console.log(message)\n else logOutro(styleText('yellow', message))\n process.exitCode = 1\n return\n }\n\n if (yes) {\n console.log(`Kubb is set up. Run ${generateCommand({ packageManager, script, watch: false })} after changing the spec.`)\n return\n }\n logOutro(`${styleText('green', '✓ Kubb is set up')}\\n ${styleText('dim', 'Next')} ${generateCommand({ packageManager, script, watch: true })}`)\n } catch (error) {\n logError(styleText('red', 'An error occurred during initialization'))\n if (error instanceof Error) {\n logError(error.message)\n }\n process.exit(1)\n }\n}\n\nexport const command = defineWithTypes<{ extensions: DryRunExtensions }>()({\n name: 'init',\n description: 'Set up a config, install plugins, and run the first generation.',\n examples: [\n 'kubb init',\n 'kubb init --yes',\n 'kubb init --input ./openapi.yaml --output ./src/gen --plugins plugin-ts,plugin-zod',\n 'kubb init --yes --input ./openapi.yaml --plugins ts,zod --output src/api',\n 'kubb init --plugins plugin-ts,plugin-axios,plugin-react-query',\n 'kubb init --yes --dry-run',\n ].join('\\n'),\n toKebab: true,\n args: {\n yes: {\n type: 'boolean',\n description: 'Skip prompts and use the detected spec, the default plugin, and the default output folder',\n short: 'y',\n default: false,\n },\n input: {\n type: 'string',\n description: 'Path to the OpenAPI specification',\n short: 'i',\n metavar: 'path',\n },\n output: {\n type: 'string',\n description: 'Output directory for generated files',\n short: 'o',\n metavar: 'path',\n },\n plugins: {\n type: 'string',\n description:\n 'Comma-separated Kubb registry ids of the plugins to add, the same ids `kubb add` takes (plugin-ts, plugin-zod, acme/plugin-x), or short names (ts, zod)',\n metavar: 'plugin-ts,plugin-zod,...',\n },\n },\n run: ({ values, extensions }) => run({ yes: values.yes, input: values.input, output: values.output, plugins: values.plugins, dryRun: extensions[dryRunId] }),\n})\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;AACA,SAAgB,mBAAmB,EAAE,WAAW,cAAiE;CAC/G,OAAO;;;YAGG,UAAU;;aAET,WAAW;;;;;;AAMxB;;ACoBA,SAAS,cAAc,UAAU,uBAA8B;CAC7D,eAAM,OAAO,OAAO;CACpB,aAAA,QAAQ,KAAK,CAAC;AAChB;AAEA,SAAS,OAAU,OAA8B;CAC/C,IAAIA,eAAM,SAAS,KAAK,GAAG,cAAc;CACzC,OAAO;AACT;;AAiCA,SAAS,YAAY,EAAE,WAAW,YAAY,WAA4B;CACxE,MAAM,EAAE,QAAQ,aAAaC,mBAAAA,WAAW;EACtC,QAAQ,mBAAmB;GAAE;GAAW;EAAW,CAAC;EACpD,OAAO,QAAQ,KAAK,WAAW;GAAE,WAAWC,mBAAAA,oBAAoB;GAAY,QAAQ,MAAM,SAAS;EAAQ,EAAE;EAC7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GAASA,UAAAA,UAAAA,CAAU,OAAO,yCAAyC,CAAC;EACpE,IAAI,iBAAiB,OACnB,YAAA,SAAS,MAAM,OAAO;EAExB,aAAA,QAAQ,KAAK,CAAC;CAChB;AACF;AAEA,MAAa,WAAA,GAAUY,OAAAA,gBAAAA,CAAkD,CAAC,CAAC;CACzE,MAAM;CACN,aAAa;CACb,UAAU;EACR;EACA;EACA;EACA;EACA;EACA;CACF,CAAC,CAAC,KAAK,IAAI;CACX,SAAS;CACT,MAAM;EACJ,KAAK;GACH,MAAM;GACN,aAAa;GACb,OAAO;GACP,SAAS;EACX;EACA,OAAO;GACL,MAAM;GACN,aAAa;GACb,OAAO;GACP,SAAS;EACX;EACA,QAAQ;GACN,MAAM;GACN,aAAa;GACb,OAAO;GACP,SAAS;EACX;EACA,SAAS;GACP,MAAM;GACN,aACE;GACF,SAAS;EACX;CACF;CACA,MAAM,EAAE,QAAQ,iBAAiB,IAAI;EAAE,KAAK,OAAO;EAAK,OAAO,OAAO;EAAO,QAAQ,OAAO;EAAQ,SAAS,OAAO;EAAS,QAAQ,WAAWC,sBAAAA;CAAU,CAAC;AAC7J,CAAC"}
|
|
1
|
+
{"version":3,"file":"run-q2tnHViw.cjs","names":["clack","editConfig","ConfigEditOperation","Diagnostics","KUBB_CONFIG_FILENAME","getConfigs","createKubb","resolveCommand","process","isInteractiveRun","fetchRegistryIndex","registryUrl","incompatibility","exists","path","detectPackageManager","withSpinner","initPackageJson","findSpecFiles","readSpecInfo","pluralize","initDefaults","findPlugin","parsePluginsFlag","isHttpUrl","styleText","missingPluginDependencies","KUBB_PACKAGE_NAME","version","installSpec","installPackages","installWithSpinner","write","addGenerateScript","generateScript","formatMs","getElapsedMs","defineWithTypes","dryRunId"],"sources":["../../../internals/shared/src/init.ts","../src/runners/init/run.ts"],"sourcesContent":["/** The `kubb.config.ts` `kubb init` writes before `kubb add` puts each plugin in. */\nexport function generateConfigFile({ inputPath, outputPath }: { inputPath: string; outputPath: string }): string {\n return `import { defineConfig } from 'kubb/config'\n\nexport default defineConfig({\n input: '${inputPath}',\n output: {\n path: '${outputPath}',\n clean: true,\n },\n plugins: [],\n})\n`\n}\n","import path from 'node:path'\nimport process from 'node:process'\nimport { styleText } from 'node:util'\nimport * as clack from '@clack/prompts'\nimport type { DryRunExtension } from '@gunshi/plugin-dryrun'\nimport { defineWithTypes } from 'gunshi'\nimport { resolveCommand } from 'package-manager-detector'\nimport { ConfigEditOperation, editConfig, generateConfigFile, initDefaults, KUBB_CONFIG_FILENAME, KUBB_PACKAGE_NAME } from '@internals/shared'\nimport { exists, formatMs, getElapsedMs, write } from '@internals/utils'\nimport { createKubb, Diagnostics, type RegistryEntry } from '@kubb/core'\nimport { dryRunId, type DryRunExtensions } from '../../commands/shared.ts'\nimport { getConfigs } from '../../config.ts'\nimport { isHttpUrl, pluralize } from '../../ui/text.ts'\nimport { isInteractiveRun, logIntro, logOutro } from '../../ui/intro.ts'\nimport { logBlock, logError, logStep, logWarn } from '../../ui/log.ts'\nimport { withSpinner } from '../../ui/spinner.ts'\nimport { fetchRegistryIndex, incompatibility, installSpec, registryUrl } from '../../utils/registry.ts'\nimport { installWithSpinner } from '../installWithSpinner.ts'\nimport {\n addGenerateScript,\n detectPackageManager,\n findPlugin,\n findSpecFiles,\n generateScript,\n initPackageJson,\n installPackages,\n missingPluginDependencies,\n type PackageManagerInfo,\n parsePluginsFlag,\n readSpecInfo,\n} from './utils.ts'\nimport { version } from '../../../package.json'\n\nfunction cancelAndExit(message = 'Operation canceled.'): never {\n clack.cancel(message)\n process.exit(0)\n}\n\nfunction unwrap<T>(value: T): Exclude<T, symbol> {\n if (clack.isCancel(value)) cancelAndExit()\n return value as Exclude<T, symbol>\n}\n\ntype InitOptions = {\n /**\n * When `true`, skips all interactive prompts and uses the detected or default values.\n */\n yes: boolean\n /**\n * Input path flag value from `--input`. When provided, skips the input prompt.\n */\n input?: string\n /**\n * Output directory flag value from `--output`. When provided, skips the output prompt.\n */\n output?: string\n /**\n * Comma-separated plugin list from `--plugins`, e.g. `'plugin-ts,zod'`. When provided, skips the plugin selection prompt.\n */\n plugins?: string\n /**\n * Dry-run extension from `@gunshi/plugin-dryrun`. When enabled, package installation, file\n * writes, and the first run are skipped.\n */\n dryRun: DryRunExtension\n}\n\ntype Choices = {\n inputPath: string\n outputPath: string\n plugins: Array<RegistryEntry>\n}\n\n/** The full `kubb.config.ts` for `choices`, with each plugin added the way `kubb add` adds it. */\nfunction buildConfig({ inputPath, outputPath, plugins }: Choices): string {\n const { source, outcomes } = editConfig({\n source: generateConfigFile({ inputPath, outputPath }),\n edits: plugins.map((entry) => ({ operation: ConfigEditOperation.ADD_PLUGIN, plugin: entry.artifact.package })),\n extensions: new Map(plugins.map(({ artifact, manifest }) => [artifact.package, { package: artifact.package, version: artifact.version, manifest }])),\n })\n const failed = outcomes.find((outcome) => !outcome.applied)\n if (failed && failed.edit.operation === ConfigEditOperation.ADD_PLUGIN)\n throw new Diagnostics.Error({\n code: Diagnostics.code.unknown,\n severity: 'error',\n message: `Could not add ${failed.edit.plugin} to ${KUBB_CONFIG_FILENAME}: ${failed.reason}`,\n help: `Run kubb init without that plugin, then add it with kubb add.`,\n })\n return source\n}\n\n/** Generates from the config at `configPath` without reporters, and returns how many files it wrote. */\nasync function firstRun(configPath: string): Promise<number> {\n const { configs } = await getConfigs({ configPath })\n let files = 0\n for (const config of configs) {\n const result = await createKubb(config).generate()\n if (!result.success) throw new Error(result.diagnostics.flatMap((diagnostic) => (diagnostic.severity === 'error' ? [diagnostic.message] : [])).join('\\n'))\n files += result.files.length\n }\n return files\n}\n\n/** The command that runs `kubb generate`: the `generate` script when it runs Kubb, otherwise `npx kubb generate`. */\nfunction generateCommand({ packageManager, script, watch }: { packageManager: PackageManagerInfo; script: string | undefined; watch: boolean }): string {\n if (script !== 'kubb generate') return `npx kubb generate${watch ? ' --watch' : ''}`\n const { command, args } = resolveCommand(packageManager.agent, 'run', watch ? ['generate', '--watch'] : ['generate'])!\n return [command, ...args].join(' ')\n}\n\n/**\n * Runs the Kubb setup wizard: detects the package manager and specs, asks for the spec, plugins, and\n * output folder, shows the config for review, then installs, writes `kubb.config.ts`, adds a\n * `generate` script, and runs the first generation.\n * Pass `yes: true` to skip all prompts and print one line per step.\n */\nexport async function run({ yes, input: inputFlag, output: outputFlag, plugins: pluginsFlag, dryRun }: InitOptions): Promise<void> {\n const cwd = process.cwd()\n\n if (!yes) logIntro({ title: isInteractiveRun({ yes, dryRun: dryRun.enabled }) ? undefined : 'Set up Kubb' })\n\n try {\n // Start the registry fetch now but await it only at the plugin step, so the first prompt never waits on the network\n const registry = fetchRegistryIndex({ registry: registryUrl() }).then((entries) =>\n entries.filter((entry) => entry.kind === 'plugin' && !incompatibility(entry.manifest)),\n )\n registry.catch(() => {})\n\n if (!(await exists(path.join(cwd, 'package.json')))) {\n if (!yes) {\n const shouldInit = unwrap(await clack.confirm({ message: 'No package.json found. Would you like to create one?', initialValue: true }))\n if (!shouldInit) cancelAndExit()\n }\n\n const packageManager = await detectPackageManager(cwd)\n await withSpinner({\n message: `Initializing package.json with ${packageManager.name}`,\n promise: initPackageJson(cwd, packageManager),\n done: () => `Created package.json with ${packageManager.name}`,\n failed: 'Could not create package.json',\n plain: yes,\n })\n }\n\n const packageManager = await detectPackageManager(cwd)\n const specs = await findSpecFiles(cwd)\n\n if (!yes) {\n logStep(`Package manager ${packageManager.name}`)\n if (specs[0]) {\n const { version: specVersion, operations } = await readSpecInfo(path.join(cwd, specs[0]))\n const details = [\n specs[0].slice(2),\n specVersion ? `${specVersion.startsWith('2') ? 'Swagger' : 'OpenAPI'} ${specVersion}` : undefined,\n operations === undefined ? undefined : pluralize(operations, 'operation'),\n specs.length > 1 ? `+${specs.length - 1} more` : undefined,\n ]\n logStep(`Found ${details.filter(Boolean).join(' · ')}`)\n }\n }\n\n // `--plugins` and `--yes` need the registry before any prompt; the interactive path reads it at the plugin step\n const plugins = pluginsFlag || yes ? await registry : undefined\n const defaultPlugins = (entries: Array<RegistryEntry>) => initDefaults.plugins.flatMap((id) => findPlugin({ plugins: entries, id }) ?? [])\n\n const flagPlugins = pluginsFlag && plugins ? parsePluginsFlag({ plugins, value: pluginsFlag }) : undefined\n\n let choices: Choices = {\n inputPath: inputFlag ?? specs[0] ?? initDefaults.inputPath,\n outputPath: outputFlag ?? initDefaults.outputPath,\n plugins: flagPlugins ?? (plugins ? defaultPlugins(plugins) : []),\n }\n if (yes && !choices.plugins.length) {\n throw new Error('The registry has no default plugin. Pass --plugins to choose one.')\n }\n\n async function askInput(current: string): Promise<string> {\n const choice = specs.length\n ? unwrap(\n await clack.select({\n message: 'Which spec should Kubb read?',\n options: [\n ...specs.map((spec) => ({ value: spec, label: spec, hint: 'found in this repo' })),\n { value: 'url', label: 'A URL' },\n { value: 'file', label: 'Another file' },\n ],\n initialValue: specs.includes(current) ? current : isHttpUrl(current) ? 'url' : 'file',\n }),\n )\n : isHttpUrl(current)\n ? 'url'\n : 'file'\n if (specs.includes(choice)) return choice\n const isUrl = choice === 'url'\n const initial = isUrl === isHttpUrl(current) && !specs.includes(current) ? current : undefined\n return unwrap(\n await clack.text({\n message: isUrl ? 'Spec URL' : 'Spec path',\n placeholder: isUrl ? 'https://example.com/openapi.yaml' : initDefaults.inputPath,\n initialValue: initial,\n defaultValue: isUrl ? undefined : initDefaults.inputPath,\n validate: (value) => {\n if (isUrl && !isHttpUrl(value ?? '')) return 'Enter an http(s) URL'\n },\n }),\n )\n }\n\n async function askPlugins(previous: Array<RegistryEntry>): Promise<Array<RegistryEntry>> {\n const plugins = await registry\n const current = previous.length ? previous : defaultPlugins(plugins)\n const width = Math.max(...plugins.map((entry) => entry.manifest.displayName.length))\n const nameWidth = Math.max(...plugins.map((entry) => entry.manifest.name.length))\n const values = unwrap(\n await clack.multiselect({\n message: 'What should Kubb generate?',\n options: plugins.map(({ id, manifest }) => ({\n value: id,\n label: `${manifest.displayName.padEnd(width)} ${styleText('dim', manifest.name.padEnd(nameWidth))}`.trimEnd(),\n })),\n initialValues: current.map((entry) => entry.id),\n required: true,\n }),\n )\n return plugins.filter((entry) => values.includes(entry.id))\n }\n\n // Flags for all three choices leave nothing to ask or review, as before the review step existed\n const answered = yes || Boolean(inputFlag && outputFlag && pluginsFlag)\n if (!answered) {\n let firstPass = true\n while (true) {\n // The first pass skips the questions a flag answered; \"Change a choice\" asks them all again.\n choices = {\n inputPath: firstPass && inputFlag ? inputFlag : await askInput(choices.inputPath),\n plugins: firstPass && flagPlugins ? flagPlugins : await askPlugins(choices.plugins),\n outputPath:\n firstPass && outputFlag\n ? outputFlag\n : unwrap(await clack.text({ message: 'Output folder', placeholder: choices.outputPath, defaultValue: choices.outputPath })),\n }\n firstPass = false\n const missing = missingPluginDependencies(choices.plugins.map((entry) => entry.manifest))\n if (missing.length) {\n logWarn(`${missing.join('\\n')}\\nAdd the missing plugins.`)\n continue\n }\n const config = buildConfig(choices)\n const packages = [KUBB_PACKAGE_NAME, ...choices.plugins.map((entry) => entry.artifact.package)]\n logStep(`Review ${KUBB_CONFIG_FILENAME}`)\n logBlock([...config.trimEnd().split('\\n'), '', `${styleText('dim', 'Installs')} ${packages.join(' ')} with ${packageManager.name}`])\n const configExists = await exists(path.join(cwd, KUBB_CONFIG_FILENAME))\n const confirmed = unwrap(\n await clack.select({\n message: configExists ? `${KUBB_CONFIG_FILENAME} exists. Overwrite it?` : 'Create it?',\n options: [\n { value: true, label: 'Yes' },\n { value: false, label: 'Change a choice' },\n ],\n }),\n )\n if (confirmed) break\n }\n }\n\n // Check the selection against the plugins' manifests before installing anything\n const missing = missingPluginDependencies(choices.plugins.map((entry) => entry.manifest))\n if (missing.length) {\n throw new Diagnostics.Error({\n code: Diagnostics.code.missingDependency,\n severity: 'error',\n message: `${missing.join('\\n')}\\nAdd the missing plugins and run kubb init again.`,\n })\n }\n\n const configPath = path.join(cwd, KUBB_CONFIG_FILENAME)\n if (answered && !yes && (await exists(configPath))) {\n const overwrite = unwrap(await clack.confirm({ message: `${KUBB_CONFIG_FILENAME} exists. Overwrite it?`, initialValue: false }))\n if (!overwrite) cancelAndExit('Keeping existing configuration.')\n }\n\n // Install `kubb` at the running CLI's version and each plugin at the version the registry pins\n const packagesToInstall = [`${KUBB_PACKAGE_NAME}@${version}`, ...choices.plugins.map((entry) => installSpec(entry.artifact))]\n const packageNames = [KUBB_PACKAGE_NAME, ...choices.plugins.map((entry) => entry.artifact.package)]\n const dry = { message: `install ${packagesToInstall.length} packages with ${packageManager.name}` }\n if (yes) {\n await withSpinner({\n message: '',\n promise: dryRun.run(() => installPackages(packagesToInstall, packageManager, cwd), dry),\n done: () => `Installed ${packageNames.join(' ')} with ${packageManager.name}`,\n plain: true,\n })\n } else {\n await installWithSpinner({\n packages: packagesToInstall,\n names: `${packagesToInstall.length} packages`,\n packageManager,\n cwd,\n install: async (packages, packageManager, cwd, onLine) => void (await dryRun.run(() => installPackages(packages, packageManager, cwd, onLine), dry)),\n })\n }\n\n await withSpinner({\n message: `Writing ${KUBB_CONFIG_FILENAME}`,\n promise: dryRun.run(async () => void (await write(configPath, buildConfig(choices))), { message: `write ${KUBB_CONFIG_FILENAME}` }),\n done: () => `Wrote ${KUBB_CONFIG_FILENAME}`,\n failed: `Could not write ${KUBB_CONFIG_FILENAME}`,\n plain: yes,\n })\n\n const scriptAdded = await dryRun.run(() => addGenerateScript(cwd), {\n message: 'add a generate script to package.json',\n resolve: async () => (await generateScript(cwd)) === undefined,\n })\n if (scriptAdded && !yes) logStep('Added \"generate\": \"kubb generate\" to package.json')\n\n const script = scriptAdded ? 'kubb generate' : await generateScript(cwd)\n const runStart = process.hrtime()\n try {\n await dryRun.run(\n () =>\n withSpinner({\n message: 'Running the first generation',\n promise: firstRun(configPath),\n done: (files) =>\n yes\n ? `Generated ${pluralize(files, 'file')} in ${choices.outputPath}`\n : `First run ${pluralize(files, 'file')} in ${choices.outputPath} · ${formatMs(getElapsedMs(runStart))}`,\n failed: 'First run failed',\n plain: yes,\n }),\n { message: 'run the first generation', resolve: () => 0 },\n )\n } catch (error) {\n logError(error instanceof Error ? error.message : String(error))\n const message = `Kubb is set up, but the first run failed. Fix the error, then run ${generateCommand({ packageManager, script, watch: false })}.`\n if (yes) console.log(message)\n else logOutro(styleText('yellow', message))\n process.exitCode = 1\n return\n }\n\n if (yes) {\n console.log(`Kubb is set up. Run ${generateCommand({ packageManager, script, watch: false })} after changing the spec.`)\n return\n }\n logOutro(`${styleText('green', '✓ Kubb is set up')}\\n ${styleText('dim', 'Next')} ${generateCommand({ packageManager, script, watch: true })}`)\n } catch (error) {\n logError(styleText('red', 'An error occurred during initialization'))\n if (error instanceof Error) {\n logError(error.message)\n }\n process.exit(1)\n }\n}\n\nexport const command = defineWithTypes<{ extensions: DryRunExtensions }>()({\n name: 'init',\n description: 'Set up a config, install plugins, and run the first generation.',\n examples: [\n 'kubb init',\n 'kubb init --yes',\n 'kubb init --input ./openapi.yaml --output ./src/gen --plugins plugin-ts,plugin-zod',\n 'kubb init --yes --input ./openapi.yaml --plugins ts,zod --output src/api',\n 'kubb init --plugins plugin-ts,plugin-axios,plugin-react-query',\n 'kubb init --yes --dry-run',\n ].join('\\n'),\n toKebab: true,\n args: {\n yes: {\n type: 'boolean',\n description: 'Skip prompts and use the detected spec, the default plugin, and the default output folder',\n short: 'y',\n default: false,\n },\n input: {\n type: 'string',\n description: 'Path to the OpenAPI specification',\n short: 'i',\n metavar: 'path',\n },\n output: {\n type: 'string',\n description: 'Output directory for generated files',\n short: 'o',\n metavar: 'path',\n },\n plugins: {\n type: 'string',\n description:\n 'Comma-separated Kubb registry ids of the plugins to add, the same ids `kubb add` takes (plugin-ts, plugin-zod, acme/plugin-x), or short names (ts, zod)',\n metavar: 'plugin-ts,plugin-zod,...',\n },\n },\n run: ({ values, extensions }) => run({ yes: values.yes, input: values.input, output: values.output, plugins: values.plugins, dryRun: extensions[dryRunId] }),\n})\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;AACA,SAAgB,mBAAmB,EAAE,WAAW,cAAiE;CAC/G,OAAO;;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BowF1xt-.js";
|
|
2
2
|
import { t as findConfigFile } from "./config-re864UnO.js";
|
|
3
3
|
import { n as toError } from "./errors-CEzFbRvL.js";
|
|
4
|
-
import { n as trackRun } from "./Telemetry-
|
|
4
|
+
import { n as trackRun } from "./Telemetry-4T6PkdJo.js";
|
|
5
5
|
import { t as getConfigs } from "./config-CGcQTdZV.js";
|
|
6
6
|
import { n as pluralize } from "./text-HYWAcipy.js";
|
|
7
7
|
import { n as logCommandSummary } from "./summary-BS-iWuye.js";
|
|
@@ -96,4 +96,4 @@ async function run({ input, configPath }) {
|
|
|
96
96
|
}
|
|
97
97
|
export { run };
|
|
98
98
|
|
|
99
|
-
//# sourceMappingURL=run-
|
|
99
|
+
//# sourceMappingURL=run-yNWLKHjJ.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"run-
|
|
1
|
+
{"version":3,"file":"run-yNWLKHjJ.js","names":[],"sources":["../src/runners/validate/run.ts"],"sourcesContent":["import process from 'node:process'\nimport { resolve } from 'node:path'\nimport { styleText } from 'node:util'\nimport { findConfigFile } from '@internals/shared'\nimport { toError } from '@internals/utils'\nimport { type Config, checkoutGitInput, getInputKind } from '@kubb/core'\nimport { trackRun } from '../../Telemetry.ts'\nimport { getConfigs } from '../../config.ts'\nimport { pluralize } from '../../ui/text.ts'\nimport { logCommandSummary } from '../../ui/summary.ts'\n\ntype ValidateOptions = {\n /**\n * Path, URL, or git input (`git+<repo>#<ref>:<path>`) of the specification to validate.\n */\n input: string\n configPath?: string\n}\n\n/**\n * Validates `input` with the configured adapters, falling back to OpenAPI when no config exists.\n * Exits the process with code 1 on validation failure or missing dependency.\n */\nexport async function run({ input, configPath }: ValidateOptions): Promise<void> {\n const hrStart = process.hrtime()\n const report = trackRun({ command: 'validate', hrStart })\n let adapterName: string | undefined\n\n try {\n const configFile = configPath ?? findConfigFile()\n // A config found by search that does not load must not block validating a file; an explicit `--config` still fails.\n const loaded = configFile\n ? await getConfigs({ configPath: configFile, input }).catch((error) => {\n if (configPath) throw error\n })\n : undefined\n const fallback = async () => {\n adapterName = '@kubb/adapter-oas'\n const { adapterOas } = await import('@kubb/adapter-oas')\n return [{ adapter: adapterOas(), input }]\n }\n // An array config often repeats one adapter, so each adapter and input pair is validated once.\n const unique = new Map(\n (loaded?.configs ?? []).map((config) => {\n const resolved = getInputKind(input) === 'file' ? resolve(config.root || process.cwd(), input) : input\n return [`${config.adapter?.name}\\0${resolved}`, { adapter: config.adapter, input: resolved }] as const\n }),\n )\n const targets: Array<{ adapter: Config['adapter']; input: string }> = loaded ? [...unique.values()] : await fallback()\n if (!targets.length) throw new Error('The Kubb config contains no configurations to validate.')\n for (const target of targets) {\n adapterName = target.adapter?.name\n if (!target.adapter) throw new Error('No adapter is configured. Set adapter in your Kubb config to validate this specification.')\n const checkout = getInputKind(target.input) === 'git' ? await checkoutGitInput(target.input) : undefined\n try {\n await target.adapter.validate(checkout?.path ?? target.input, { throwOnError: true })\n } finally {\n await checkout?.dispose()\n }\n }\n const specifications = new Set(targets.map((target) => target.input)).size\n const adapterNames = [...new Set(targets.flatMap((target) => target.adapter?.name ?? []))]\n await report({ status: 'success' })\n\n logCommandSummary({\n title: 'Validation passed',\n status: 'success',\n hrStart,\n lines: [\n ` ${styleText('bold', `${pluralize(specifications, 'specification')} validated`)}`,\n ` ${styleText('dim', 'Input')} ${styleText('cyan', input)}`,\n ` ${styleText('dim', adapterNames.length === 1 ? 'Adapter' : 'Adapters')} ${adapterNames.join(', ')}`,\n ],\n })\n } catch (error) {\n await report({ status: 'failed' })\n const message = toError(error).message\n const missingAdapter = adapterName === '@kubb/adapter-oas' && /(?:Cannot find|Cannot resolve|not found)[\\s\\S]*@kubb\\/adapter-oas/.test(message)\n logCommandSummary({\n title: missingAdapter ? 'Could not validate' : 'Validation failed',\n status: 'failed',\n hrStart,\n lines: [\n ` ${styleText('dim', 'Input')} ${styleText('cyan', input)}`,\n ` ${styleText('dim', 'Adapter')} ${adapterName ?? 'not configured'}${missingAdapter ? ' · not installed' : ''}`,\n '',\n styleText('bold', missingAdapter ? 'Required package' : 'Validation error'),\n ` ${styleText('red', message)}`,\n ...(missingAdapter\n ? ['', 'Install it with:', styleText('cyan', ' npm install @kubb/adapter-oas'), styleText('cyan', ' pnpm add @kubb/adapter-oas')]\n : []),\n ],\n })\n\n process.exit(1)\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;AAuBA,eAAsB,IAAI,EAAE,OAAO,cAA8C;CAC/E,MAAM,UAAU,QAAQ,OAAO;CAC/B,MAAM,SAAS,SAAS;EAAE,SAAS;EAAY;CAAQ,CAAC;CACxD,IAAI;CAEJ,IAAI;EACF,MAAM,aAAa,cAAc,eAAe;EAEhD,MAAM,SAAS,aACX,MAAM,WAAW;GAAE,YAAY;GAAY;EAAM,CAAC,CAAC,CAAC,OAAO,UAAU;GACnE,IAAI,YAAY,MAAM;EACxB,CAAC,IACD,KAAA;EACJ,MAAM,WAAW,YAAY;GAC3B,cAAc;GACd,MAAM,EAAE,eAAe,MAAM,OAAO;GACpC,OAAO,CAAC;IAAE,SAAS,WAAW;IAAG;GAAM,CAAC;EAC1C;EAEA,MAAM,SAAS,IAAI,KAChB,QAAQ,WAAW,CAAC,EAAA,CAAG,KAAK,WAAW;GACtC,MAAM,WAAW,aAAa,KAAK,MAAM,SAAS,QAAQ,OAAO,QAAQ,QAAQ,IAAI,GAAG,KAAK,IAAI;GACjG,OAAO,CAAC,GAAG,OAAO,SAAS,KAAK,IAAI,YAAY;IAAE,SAAS,OAAO;IAAS,OAAO;GAAS,CAAC;EAC9F,CAAC,CACH;EACA,MAAM,UAAgE,SAAS,CAAC,GAAG,OAAO,OAAO,CAAC,IAAI,MAAM,SAAS;EACrH,IAAI,CAAC,QAAQ,QAAQ,MAAM,IAAI,MAAM,yDAAyD;EAC9F,KAAK,MAAM,UAAU,SAAS;GAC5B,cAAc,OAAO,SAAS;GAC9B,IAAI,CAAC,OAAO,SAAS,MAAM,IAAI,MAAM,2FAA2F;GAChI,M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,iCAAiC;KAAG,UAAU,QAAQ,8BAA8B;IAAC,IAChI,CAAC;GACP;EACF,CAAC;EAED,QAAQ,KAAK,CAAC;CAChB;AACF"}
|
|
@@ -4,7 +4,7 @@ const require_spinner = require("./spinner-BQgUoe7F.cjs");
|
|
|
4
4
|
const require_text = require("./text-CkCtm5VP.cjs");
|
|
5
5
|
const require_log = require("./log-BzmBldY6.cjs");
|
|
6
6
|
const require_reporters = require("./reporters-DLK4D0js.cjs");
|
|
7
|
-
const require_run = require("./run-
|
|
7
|
+
const require_run = require("./run-Dy3EpGtg.cjs");
|
|
8
8
|
let node_util = require("node:util");
|
|
9
9
|
let node_process = require("node:process");
|
|
10
10
|
node_process = require_rolldown_runtime.__toESM(node_process, 1);
|
|
@@ -247,4 +247,4 @@ const runner = ({ values }) => require_run.runStudio(values, (options) => snapsh
|
|
|
247
247
|
}), { json: values.json });
|
|
248
248
|
exports.runner = runner;
|
|
249
249
|
|
|
250
|
-
//# sourceMappingURL=snapshot-
|
|
250
|
+
//# sourceMappingURL=snapshot-CRwqhXnu.cjs.map
|