@kubb/cli 5.3.8 → 5.3.9

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (98) hide show
  1. package/dist/{Telemetry-CvHQevSK.cjs → Telemetry-B3kc9gFh.cjs} +3 -2
  2. package/dist/Telemetry-B3kc9gFh.cjs.map +1 -0
  3. package/dist/{Telemetry-CJcQkQOT.js → Telemetry-Dw5s6abr.js} +3 -2
  4. package/dist/Telemetry-Dw5s6abr.js.map +1 -0
  5. package/dist/connect-DFd7vS7_.js +11 -0
  6. package/dist/connect-DFd7vS7_.js.map +1 -0
  7. package/dist/connect-bCESn4L8.cjs +11 -0
  8. package/dist/connect-bCESn4L8.cjs.map +1 -0
  9. package/dist/{generate-DGRNFF3n.cjs → generate-Cl5hFNdC.cjs} +5 -18
  10. package/dist/generate-Cl5hFNdC.cjs.map +1 -0
  11. package/dist/{generate-Zldpj9MI.js → generate-Del-D4hj.js} +5 -18
  12. package/dist/generate-Del-D4hj.js.map +1 -0
  13. package/dist/index.cjs +9 -18
  14. package/dist/index.cjs.map +1 -1
  15. package/dist/index.js +9 -18
  16. package/dist/index.js.map +1 -1
  17. package/dist/{init-C2aRtQsn.cjs → init-C5trdwre.cjs} +3 -3
  18. package/dist/{init-C2aRtQsn.cjs.map → init-C5trdwre.cjs.map} +1 -1
  19. package/dist/{init-CqKLyf-D.js → init-CBAmaPkc.js} +3 -3
  20. package/dist/{init-CqKLyf-D.js.map → init-CBAmaPkc.js.map} +1 -1
  21. package/dist/login-5QXmUaQN.cjs +11 -0
  22. package/dist/login-5QXmUaQN.cjs.map +1 -0
  23. package/dist/login-D-1xSRxT.js +11 -0
  24. package/dist/login-D-1xSRxT.js.map +1 -0
  25. package/dist/logout-B2vHFyac.cjs +14 -0
  26. package/dist/logout-B2vHFyac.cjs.map +1 -0
  27. package/dist/logout-XB0v_SY-.js +14 -0
  28. package/dist/logout-XB0v_SY-.js.map +1 -0
  29. package/dist/output-CdnsdD1b.js +342 -0
  30. package/dist/output-CdnsdD1b.js.map +1 -0
  31. package/dist/output-DBBTlqPw.cjs +438 -0
  32. package/dist/output-DBBTlqPw.cjs.map +1 -0
  33. package/dist/{package-BzG32I44.cjs → package-BwIh-jWZ.cjs} +2 -2
  34. package/dist/package-BwIh-jWZ.cjs.map +1 -0
  35. package/dist/package-CDw1YdJ8.js +6 -0
  36. package/dist/package-CDw1YdJ8.js.map +1 -0
  37. package/dist/{run-gQD6xSuC.js → run-Bd-IwEch.js} +48 -301
  38. package/dist/run-Bd-IwEch.js.map +1 -0
  39. package/dist/{run-ByKuuI4i.js → run-C5HkzCUt.js} +27 -23
  40. package/dist/run-C5HkzCUt.js.map +1 -0
  41. package/dist/{run-BaaFaBBx.cjs → run-CIonyF_t.cjs} +99 -299
  42. package/dist/run-CIonyF_t.cjs.map +1 -0
  43. package/dist/{run-BrnQLk3o.js → run-CLhU86LM.js} +3 -3
  44. package/dist/{run-BrnQLk3o.js.map → run-CLhU86LM.js.map} +1 -1
  45. package/dist/{run-kdxqOL8u.js → run-CeTu1eSk.js} +2 -2
  46. package/dist/{run-kdxqOL8u.js.map → run-CeTu1eSk.js.map} +1 -1
  47. package/dist/{run-De_AsR8i.cjs → run-CxglY4u6.cjs} +27 -23
  48. package/dist/run-CxglY4u6.cjs.map +1 -0
  49. package/dist/{run-CqLiqWP1.cjs → run-DPuKGV20.cjs} +3 -3
  50. package/dist/{run-CqLiqWP1.cjs.map → run-DPuKGV20.cjs.map} +1 -1
  51. package/dist/{run-BP7-azAp.js → run-Df4x0iX_.js} +3 -3
  52. package/dist/{run-BP7-azAp.js.map → run-Df4x0iX_.js.map} +1 -1
  53. package/dist/{run-BZiPrq4E.cjs → run-SybIXc6w.cjs} +3 -3
  54. package/dist/{run-BZiPrq4E.cjs.map → run-SybIXc6w.cjs.map} +1 -1
  55. package/dist/{run-VK50TiB7.cjs → run-ZPt0Sw9r.cjs} +2 -2
  56. package/dist/{run-VK50TiB7.cjs.map → run-ZPt0Sw9r.cjs.map} +1 -1
  57. package/dist/shared-C5doIqKD.js +64 -0
  58. package/dist/shared-C5doIqKD.js.map +1 -0
  59. package/dist/shared-CaRlFkWL.cjs +87 -0
  60. package/dist/shared-CaRlFkWL.cjs.map +1 -0
  61. package/dist/snapshot-DWNiluEm.cjs +261 -0
  62. package/dist/snapshot-DWNiluEm.cjs.map +1 -0
  63. package/dist/snapshot-Dhwz_MpL.js +260 -0
  64. package/dist/snapshot-Dhwz_MpL.js.map +1 -0
  65. package/dist/status-Cc3wqN4l.js +11 -0
  66. package/dist/status-Cc3wqN4l.js.map +1 -0
  67. package/dist/status-CxMC5vAa.cjs +11 -0
  68. package/dist/status-CxMC5vAa.cjs.map +1 -0
  69. package/dist/studio-CQ24bwGz.cjs +155 -0
  70. package/dist/studio-CQ24bwGz.cjs.map +1 -0
  71. package/dist/studio-jqKsQP5_.js +155 -0
  72. package/dist/studio-jqKsQP5_.js.map +1 -0
  73. package/dist/{utils-s6yetN6W.js → utils-B1_SWa35.js} +356 -525
  74. package/dist/utils-B1_SWa35.js.map +1 -0
  75. package/dist/{utils-CMU1rLfY.cjs → utils-BP0xq5AK.cjs} +345 -508
  76. package/dist/utils-BP0xq5AK.cjs.map +1 -0
  77. package/package.json +9 -9
  78. package/dist/Telemetry-CJcQkQOT.js.map +0 -1
  79. package/dist/Telemetry-CvHQevSK.cjs.map +0 -1
  80. package/dist/generate-DGRNFF3n.cjs.map +0 -1
  81. package/dist/generate-Zldpj9MI.js.map +0 -1
  82. package/dist/output-DH2Uoy4x.js +0 -118
  83. package/dist/output-DH2Uoy4x.js.map +0 -1
  84. package/dist/output-kmklyYIv.cjs +0 -172
  85. package/dist/output-kmklyYIv.cjs.map +0 -1
  86. package/dist/package-BzG32I44.cjs.map +0 -1
  87. package/dist/package-CRlfmw6k.js +0 -6
  88. package/dist/package-CRlfmw6k.js.map +0 -1
  89. package/dist/run-BaaFaBBx.cjs.map +0 -1
  90. package/dist/run-ByKuuI4i.js.map +0 -1
  91. package/dist/run-De_AsR8i.cjs.map +0 -1
  92. package/dist/run-gQD6xSuC.js.map +0 -1
  93. package/dist/studio-B33RIU3-.cjs +0 -111
  94. package/dist/studio-B33RIU3-.cjs.map +0 -1
  95. package/dist/studio-Cq_th0uM.js +0 -112
  96. package/dist/studio-Cq_th0uM.js.map +0 -1
  97. package/dist/utils-CMU1rLfY.cjs.map +0 -1
  98. package/dist/utils-s6yetN6W.js.map +0 -1
@@ -1,10 +1,10 @@
1
1
  import "./rolldown-runtime-C0LytTxp.js";
2
2
  import { t as toError } from "./errors-C8yNfV7w.js";
3
3
  import { n as isCIEnvironment } from "./agent-3JmkMghp.js";
4
- import { r as sendTelemetry, t as buildTelemetryEvent, u as runtime } from "./Telemetry-CJcQkQOT.js";
5
- import { l as setupReporters, n as getConfigs } from "./utils-s6yetN6W.js";
6
- import { t as version } from "./package-CRlfmw6k.js";
7
- import { a as logIntro, l as canUseTTY, n as logBlock, o as logOutro, t as createSpinner } from "./output-DH2Uoy4x.js";
4
+ import { r as sendTelemetry, t as buildTelemetryEvent, u as runtime } from "./Telemetry-Dw5s6abr.js";
5
+ import { n as getConfigs, u as setupReporters } from "./utils-B1_SWa35.js";
6
+ import { f as startTipRotation, m as canUseTTY, o as logIntro, r as logBlock, s as logOutro, t as createSpinner, u as logTip } from "./output-CdnsdD1b.js";
7
+ import { t as version } from "./package-CDw1YdJ8.js";
8
8
  import { t as KUBB_CONFIG_FILENAME } from "./constants-DHRspBTo.js";
9
9
  import { styleText } from "node:util";
10
10
  import { hash } from "node:crypto";
@@ -12,11 +12,10 @@ import { homedir, hostname } from "node:os";
12
12
  import process from "node:process";
13
13
  import { execFile } from "node:child_process";
14
14
  import { access, mkdir, readFile, rm, writeFile } from "node:fs/promises";
15
- import path, { dirname, join } from "node:path";
16
- import { readFileSync } from "node:fs";
15
+ import path from "node:path";
17
16
  import { cliReporter, logLevel } from "@kubb/core";
18
17
  import * as prompts from "@clack/prompts";
19
- import { PairingCanceledError, createAgent, createClient, createFileStorage, createJob, defaultStudioUrl, machineTokenFrom, pollForPairingToken, runConnection, setStorage, startPairing, waitForJob } from "@kubb/studio";
18
+ import { PairingCanceledError, createFileStorage, defaultStudioUrl, pollForPairingToken, runConnection, setStorage, startPairing } from "@kubb/studio";
20
19
  //#region ../../internals/utils/src/openInBrowser.ts
21
20
  /**
22
21
  * Opens a URL or local file in the default browser, unless running in CI.
@@ -135,250 +134,23 @@ async function clearCredentials() {
135
134
  await clean(getCredentialsPath());
136
135
  }
137
136
  //#endregion
138
- //#region src/runners/studio/ci.ts
139
- function readGithubPullRequestNumber(eventPath) {
140
- if (!eventPath) return;
141
- try {
142
- const event = JSON.parse(readFileSync(eventPath, "utf8"));
143
- return event.pull_request?.number ? String(event.pull_request.number) : void 0;
144
- } catch {
145
- return;
146
- }
147
- }
148
- /**
149
- * Detects the CI provider from its environment variables and derives a stable identity from it.
150
- * The GitHub row reproduces `gh:<repositoryId>:<prNumber>`, the identity `kubb-labs/action` has
151
- * always registered agents under, so an existing repository keeps reusing its agent.
152
- */
153
- function detectCi(env = process.env) {
154
- if (env.GITHUB_ACTIONS) {
155
- const pullRequestNumber = readGithubPullRequestNumber(env.GITHUB_EVENT_PATH);
156
- const repositoryId = env.GITHUB_REPOSITORY_ID ?? env.GITHUB_REPOSITORY ?? "";
157
- const scope = pullRequestNumber ?? env.GITHUB_RUN_ID ?? "";
158
- return {
159
- id: `gh:${repositoryId}:${scope}`,
160
- name: `${env.GITHUB_REPOSITORY ?? "github"}#${scope}`
161
- };
162
- }
163
- if (env.GITLAB_CI) {
164
- const scope = env.CI_MERGE_REQUEST_IID ?? env.CI_COMMIT_REF_SLUG ?? "";
165
- return {
166
- id: `gl:${env.CI_PROJECT_ID ?? ""}:${scope}`,
167
- name: `${env.CI_PROJECT_PATH ?? "gitlab"}#${scope}`
168
- };
169
- }
170
- if (env.BITBUCKET_BUILD_NUMBER) {
171
- const scope = env.BITBUCKET_PR_ID ?? env.BITBUCKET_BRANCH ?? "";
172
- return {
173
- id: `bb:${env.BITBUCKET_REPO_UUID ?? ""}:${scope}`,
174
- name: `${env.BITBUCKET_REPO_FULL_NAME ?? "bitbucket"}#${scope}`
175
- };
176
- }
177
- if (env.CIRCLECI) {
178
- const owner = env.CIRCLE_PROJECT_USERNAME ?? "";
179
- const project = env.CIRCLE_PROJECT_REPONAME ?? "circleci";
180
- const scope = env.CIRCLE_PR_NUMBER ?? env.CIRCLE_BRANCH ?? "";
181
- return {
182
- id: `circle:${owner}:${project}:${scope}`,
183
- name: `${owner ? `${owner}/` : ""}${project}#${scope}`
184
- };
185
- }
186
- return null;
187
- }
188
- //#endregion
189
- //#region src/runners/studio/snapshot.ts
190
- /**
191
- * How long to wait for Studio's `studio:ready` acknowledgement, above the client's own 10s
192
- * handshake-ack timeout.
193
- */
194
- const READY_TIMEOUT_MS = 15e3;
195
- /**
196
- * Longest `--timeout` accepted. Job records expire from Studio's storage after an hour.
197
- */
198
- const MAX_TIMEOUT_SECONDS = 3600;
199
- const LOOPBACK_HOSTS = /* @__PURE__ */ new Set([
200
- "localhost",
201
- "127.0.0.1",
202
- "::1"
203
- ]);
204
- async function findPackageJson(startDirectory) {
205
- let directory = startDirectory;
206
- for (;;) {
207
- const file = join(directory, "package.json");
208
- if (await exists(file)) {
209
- const packageJson = JSON.parse(await read(file));
210
- if (packageJson.name && packageJson.version) return {
211
- name: packageJson.name,
212
- version: packageJson.version
213
- };
214
- }
215
- const parent = dirname(directory);
216
- if (parent === directory) break;
217
- directory = parent;
218
- }
219
- throw new Error(`No package.json with a name and a version found above ${startDirectory}`);
220
- }
221
- /** Reads package.json only for whichever of name/version --name and --version did not supply. */
222
- async function resolvePackageMetadata(options) {
223
- if (options.name && options.packageVersion) return {
224
- name: options.name,
225
- version: options.packageVersion
226
- };
227
- const packageMetadata = await findPackageJson(process.cwd());
228
- return {
229
- name: options.name ?? packageMetadata.name,
230
- version: options.packageVersion ?? packageMetadata.version
231
- };
232
- }
233
- function resolveToken(options) {
234
- const token = options.token ?? process.env.KUBB_TOKEN;
235
- if (!token) throw new Error("An organization CI API key is required. Pass --token or set KUBB_TOKEN.");
236
- return token;
237
- }
238
- function resolveCiIdentity(options) {
239
- const detected = detectCi();
240
- if (options.id) return {
241
- id: options.id,
242
- name: detected?.name ?? options.id
243
- };
244
- if (!detected) throw new Error("Could not detect a supported CI provider (GitHub Actions, GitLab CI, Bitbucket Pipelines, CircleCI). Pass --id.");
245
- return detected;
246
- }
247
- /** Rejects a bad `--timeout` up front instead of letting it reach `waitForJob` as NaN or <= 0. */
248
- function resolveTimeoutMs(options) {
249
- const seconds = options.timeout ?? 600;
250
- if (!Number.isFinite(seconds) || seconds <= 0) throw new Error("--timeout must be a positive number of seconds");
251
- return Math.min(seconds, MAX_TIMEOUT_SECONDS) * 1e3;
252
- }
253
- /** The CI key is a credential, so refuse to send it anywhere but HTTPS or a loopback dev host. */
254
- function assertSecureStudioUrl(studioUrl) {
255
- const url = new URL(studioUrl);
256
- if (url.protocol !== "https:" && !LOOPBACK_HOSTS.has(url.hostname)) throw new Error(`Refusing to send the CI API key to ${studioUrl}. Use an https:// Studio URL, or a loopback host for local development.`);
257
- }
258
- function absoluteUrl(studioUrl, path) {
259
- return new URL(path, `${studioUrl}/`).toString();
260
- }
261
- function toResult(studioUrl, snapshot, agentSlug) {
137
+ //#region src/runners/studio/run.ts
138
+ function createStudioOptions(values) {
262
139
  return {
263
- id: snapshot.id,
264
- name: snapshot.name,
265
- version: snapshot.version,
266
- integrity: snapshot.integrity,
267
- url: absoluteUrl(studioUrl, snapshot.url),
268
- snapshotIdUrl: absoluteUrl(studioUrl, snapshot.snapshotIdUrl),
269
- expiresAt: snapshot.expiresAt,
270
- agentUrl: absoluteUrl(studioUrl, `/agents/${agentSlug}`)
271
- };
272
- }
273
- function printSummary(result) {
274
- logBlock([
275
- `${styleText("dim", "Package".padEnd(10))} ${result.name ?? "(unnamed)"}@${result.version ?? "0.0.0"}`,
276
- `${styleText("dim", "Tarball".padEnd(10))} ${styleText("cyan", result.url)}`,
277
- `${styleText("dim", "Agent".padEnd(10))} ${result.agentUrl}`,
278
- `${styleText("dim", "Expires".padEnd(10))} ${result.expiresAt}`
279
- ]);
280
- }
281
- /**
282
- * Generates a Kubb Studio snapshot from a script: registers or reuses a CI agent, connects it,
283
- * queues a snapshot job, and polls until the tarball is ready. A snapshot job runs generation and
284
- * packs the tarball in one step, so this needs no separate generation run.
285
- */
286
- async function snapshot(options) {
287
- const timeoutMs = resolveTimeoutMs(options);
288
- const token = resolveToken(options);
289
- assertSecureStudioUrl(options.studioUrl);
290
- const { configPath } = await loadConfigs(options);
291
- const ci = resolveCiIdentity(options);
292
- const { name, version: packageVersion } = await resolvePackageMetadata(options);
293
- process.env.KUBB_AGENT_SECRET = ci.id;
294
- const spinner = options.json ? null : createSpinner();
295
- const log = (message) => {
296
- if (options.json) {
297
- console.error(message);
298
- return;
299
- }
300
- spinner?.message(message);
140
+ version,
141
+ configPath: values.config,
142
+ studioUrl: values.url ?? defaultStudioUrl,
143
+ permission: {
144
+ allowRead: values.allowRead,
145
+ allowWrite: values.allowWrite,
146
+ allowConfigEdit: values.allowConfigEdit,
147
+ allowInput: values.allowInput,
148
+ allowExec: values.allowExec
149
+ },
150
+ autoOpen: values.open ?? true,
151
+ logLevel: values.logLevel
301
152
  };
302
- if (options.json) log("Creating Kubb Studio agent");
303
- if (!options.json) spinner?.start("Creating Kubb Studio agent");
304
- const agent = await createAgent({
305
- studioUrl: options.studioUrl,
306
- token,
307
- name: ci.name,
308
- machineToken: machineTokenFrom(ci.id)
309
- });
310
- const { promise: ready, reject: markFailed, resolve: markReady } = Promise.withResolvers();
311
- const client = createClient({
312
- studioUrl: options.studioUrl,
313
- token: agent.token,
314
- configPath,
315
- root: process.cwd(),
316
- version: options.version,
317
- client: { kind: "cli" },
318
- logLevel: logLevel[options.logLevel ?? "info"],
319
- loadConfig: async () => (await loadConfigs(options)).config,
320
- installLogger: (hooks) => {
321
- hooks.hook("studio:connecting", ({ url }) => log(`Connecting to Kubb Studio at ${url}`));
322
- hooks.hook("studio:connected", ({ url }) => log(`Connected to Kubb Studio at ${url}`));
323
- hooks.hook("studio:ready", () => {
324
- log("Kubb Studio connection ready");
325
- markReady();
326
- });
327
- hooks.hook("studio:warn", ({ message }) => log(`Kubb Studio warning: ${message}`));
328
- hooks.hook("studio:error", ({ error }) => markFailed(error));
329
- }
330
- });
331
- await client.connect();
332
- try {
333
- let readyTimeoutHandle;
334
- try {
335
- await Promise.race([ready, new Promise((_, reject) => {
336
- readyTimeoutHandle = setTimeout(() => reject(/* @__PURE__ */ new Error("Timed out waiting for Kubb Studio to confirm the agent was ready")), READY_TIMEOUT_MS);
337
- })]);
338
- } finally {
339
- clearTimeout(readyTimeoutHandle);
340
- }
341
- log("Creating snapshot job");
342
- const job = await createJob({
343
- studioUrl: options.studioUrl,
344
- token,
345
- type: "snapshot",
346
- agentId: agent.id,
347
- name,
348
- version: packageVersion
349
- });
350
- log(`Snapshot job queued: ${job.id}`);
351
- const finished = await waitForJob({
352
- studioUrl: options.studioUrl,
353
- token,
354
- id: job.id,
355
- timeoutMs
356
- });
357
- if (finished.status === "failed") throw new Error(finished.error ?? "Snapshot job failed");
358
- if (!finished.snapshot) throw new Error("Snapshot job succeeded without a snapshot");
359
- const result = toResult(options.studioUrl, finished.snapshot, agent.slug);
360
- if (options.json) log("Snapshot published");
361
- if (!options.json) spinner?.stop("Snapshot published");
362
- if (options.json) console.log(JSON.stringify(result));
363
- if (!options.json) printSummary(result);
364
- } catch (error) {
365
- if (options.json) log("Snapshot failed");
366
- if (!options.json) spinner?.stop("Snapshot failed");
367
- throw error;
368
- } finally {
369
- if (options.json) log("Disconnecting from Kubb Studio");
370
- client.disconnect();
371
- }
372
153
  }
373
- //#endregion
374
- //#region src/runners/studio/run.ts
375
- const ACTIONS = [
376
- "connect",
377
- "login",
378
- "logout",
379
- "status",
380
- "snapshot"
381
- ];
382
154
  /**
383
155
  * Pairs this machine with Studio and stores the resulting token.
384
156
  *
@@ -472,6 +244,7 @@ async function resolvePermissions(options, credentials, configPath = KUBB_CONFIG
472
244
  allowExec: false
473
245
  };
474
246
  const answers = {};
247
+ prompts.updateSettings({ withGuide: true });
475
248
  for (const { key, question } of PERMISSIONS) {
476
249
  if (options.permission[key] || typeof remembered?.[key] === "boolean") {
477
250
  granted[key] = options.permission[key] || remembered?.[key] === true;
@@ -536,7 +309,9 @@ var StudioConnection = class {
536
309
  #processEvents = process;
537
310
  #credentials;
538
311
  #hinted = false;
312
+ #commandActive = false;
539
313
  #hasReauthenticated = false;
314
+ #stopTipRotation;
540
315
  #granted;
541
316
  constructor(options, configPath) {
542
317
  this.#options = options;
@@ -571,6 +346,7 @@ var StudioConnection = class {
571
346
  if (error instanceof PairingCanceledError) return;
572
347
  throw error;
573
348
  } finally {
349
+ this.#stopTipRotation?.();
574
350
  this.#processEvents.off("SIGINT", this.#requestShutdown);
575
351
  this.#processEvents.off("SIGTERM", this.#requestShutdown);
576
352
  }
@@ -624,6 +400,23 @@ var StudioConnection = class {
624
400
  this.#hinted = true;
625
401
  logBlock(styleText("dim", "Press Ctrl+C to disconnect"));
626
402
  });
403
+ hooks.hook("studio:ready", () => {
404
+ logTip();
405
+ this.#stopTipRotation ??= startTipRotation({
406
+ intervalMs: 3e5,
407
+ max: Number.POSITIVE_INFINITY,
408
+ isIdle: () => !this.#commandActive
409
+ });
410
+ });
411
+ hooks.hook("studio:command:start", () => {
412
+ this.#commandActive = true;
413
+ });
414
+ hooks.hook("studio:command:end", () => {
415
+ this.#commandActive = false;
416
+ });
417
+ hooks.hook("studio:error", () => {
418
+ this.#commandActive = false;
419
+ });
627
420
  }
628
421
  };
629
422
  }
@@ -702,9 +495,9 @@ async function status(options) {
702
495
  })) console.log(row);
703
496
  }
704
497
  /**
705
- * Runs a `kubb studio` action and reports the outcome to telemetry.
498
+ * Runs a Studio command with shared setup and telemetry reporting.
706
499
  */
707
- async function run(options) {
500
+ async function run(options, action, { block = false, json = false } = {}) {
708
501
  setStorage(createFileStorage(getProjectKubbHome()));
709
502
  const hrStart = process.hrtime();
710
503
  const report = (status) => sendTelemetry(buildTelemetryEvent({
@@ -714,30 +507,11 @@ async function run(options) {
714
507
  status
715
508
  }));
716
509
  try {
717
- if (options.logLevel !== "silent" && !(options.action === "snapshot" && options.json)) logIntro({
718
- title: `Kubb Studio ${styleText("dim", `v${options.version}`)}`,
510
+ if (options.logLevel !== "silent" && !json) logIntro({
719
511
  warning: styleText("yellow", "This feature is still under development, use with caution"),
720
- block: options.action === "connect"
512
+ block
721
513
  });
722
- switch (options.action) {
723
- case "login":
724
- await login(options);
725
- break;
726
- case "logout":
727
- await clearCredentials();
728
- console.log("Signed out of Kubb Studio.");
729
- break;
730
- case "status":
731
- await status(options);
732
- break;
733
- case "connect":
734
- await connect(options);
735
- break;
736
- case "snapshot":
737
- await snapshot(options);
738
- break;
739
- default: throw new Error(`Unknown action "${options.action}", expected one of ${ACTIONS.join(", ")}`);
740
- }
514
+ await action();
741
515
  await report("success");
742
516
  } catch (error) {
743
517
  await report("failed");
@@ -745,34 +519,7 @@ async function run(options) {
745
519
  process.exitCode = 1;
746
520
  }
747
521
  }
748
- /**
749
- * Maps the parsed `kubb studio` flags onto {@link run}. Loaded on demand by `index.ts`, so the
750
- * Studio client stays out of the process for every other command.
751
- */
752
- const runner = async ({ values }) => {
753
- await run({
754
- action: values.action ?? "connect",
755
- version,
756
- configPath: values.config,
757
- studioUrl: values.url ?? defaultStudioUrl,
758
- permission: {
759
- allowRead: values.allowRead,
760
- allowWrite: values.allowWrite,
761
- allowConfigEdit: values.allowConfigEdit,
762
- allowInput: values.allowInput,
763
- allowExec: values.allowExec
764
- },
765
- autoOpen: values.open,
766
- logLevel: values.logLevel,
767
- token: values.token,
768
- id: values.id,
769
- name: values.name,
770
- packageVersion: values.packageVersion,
771
- timeout: values.timeout,
772
- json: values.json
773
- });
774
- };
775
522
  //#endregion
776
- export { runner };
523
+ export { run as a, exists as c, login as i, read as l, createStudioOptions as n, status as o, loadConfigs as r, clearCredentials as s, connect as t };
777
524
 
778
- //# sourceMappingURL=run-gQD6xSuC.js.map
525
+ //# sourceMappingURL=run-Bd-IwEch.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"run-Bd-IwEch.js","names":["logLevelMap"],"sources":["../../../internals/utils/src/openInBrowser.ts","../../../internals/utils/src/fs.ts","../src/runners/studio/credentials.ts","../src/runners/studio/run.ts"],"sourcesContent":["import { execFile } from 'node:child_process'\nimport process from 'node:process'\nimport { isCIEnvironment } from './isCIEnvironment.ts'\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 execFile('cmd', ['/c', 'start', '', target], () => {})\n } else {\n execFile(process.platform === 'darwin' ? 'open' : 'xdg-open', [target], () => {})\n }\n}\n","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 { hash } from 'node:crypto'\nimport { mkdir, writeFile } from 'node:fs/promises'\nimport { homedir } from 'node:os'\nimport path from 'node:path'\nimport process from 'node:process'\nimport { clean, read } from '@internals/utils'\n\n/**\n * Root for everything the CLI persists between runs: the paired credential, the machine secret,\n * the last Studio config, and the live-session registry. `KUBB_HOME` relocates all of it.\n */\nfunction getKubbHome(): string {\n return process.env.KUBB_HOME ?? path.join(homedir(), '.kubb')\n}\n\n/**\n * Root for the credential and machine identity of the current project.\n *\n * Studio agents are project connections, so two projects on one machine must not share the same\n * persisted token or machine secret.\n */\nexport function getProjectKubbHome(project = process.cwd()): string {\n const projectId = hash('sha256', project)\n return path.join(getKubbHome(), 'projects', projectId)\n}\n\nconst CREDENTIALS_FILENAME = 'credentials.json'\n\n/**\n * Absolute path of the stored credential, so callers can name it in output without rebuilding it.\n */\nexport function getCredentialsPath(): string {\n return path.join(getProjectKubbHome(), CREDENTIALS_FILENAME)\n}\n\nexport type Credentials = {\n /**\n * The Studio instance this machine paired with. A different `--url` means re-pairing.\n */\n studioUrl: string\n /**\n * Bearer token for this machine. Never logged, never printed.\n */\n token: string\n agentId: string\n agentSlug: string\n /**\n * Permissions the user has already granted, keyed by absolute project path, so the CLI asks\n * once per project instead of on every run.\n */\n projects?: Record<string, { allowRead?: boolean; allowWrite?: boolean; allowConfigEdit?: boolean; allowInput?: boolean; allowExec?: boolean }>\n}\n\n/**\n * Reads the stored credential, or null when this machine has not paired yet or the file is\n * unreadable or corrupt. A bad file is treated as \"not paired\" so `kubb studio login` can\n * overwrite it rather than the CLI dying on it.\n */\nexport async function readCredentials(): Promise<Credentials | null> {\n const raw = await read(getCredentialsPath()).catch(() => null)\n if (!raw) {\n return null\n }\n\n try {\n return JSON.parse(raw) as Credentials\n } catch {\n return null\n }\n}\n\n/**\n * Writes the credential with owner-only permissions. The file holds a bearer token, so the mode\n * is set at creation time rather than left to the process umask or fixed up afterward, which\n * would leave the token briefly readable under the umask's default mode.\n */\nexport async function writeCredentials(credentials: Credentials): Promise<void> {\n const file = getCredentialsPath()\n\n await mkdir(path.dirname(file), { recursive: true, mode: 0o700 })\n await writeFile(file, JSON.stringify(credentials, null, 2), { mode: 0o600 })\n}\n\n/**\n * Forgets the stored credential. Succeeds when there was nothing to forget.\n */\nexport async function clearCredentials(): Promise<void> {\n await clean(getCredentialsPath())\n}\n","import { hostname } from 'node:os'\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 { isCIEnvironment, openInBrowser, toError } from '@internals/utils'\nimport type { CLIOptions, Config } from '@kubb/core'\nimport { cliReporter, logLevel as logLevelMap } from '@kubb/core'\nimport {\n createFileStorage,\n type ClientOptions,\n defaultStudioUrl,\n type InvalidAgentTokenError,\n PairingCanceledError,\n pollForPairingToken,\n runConnection,\n setStorage,\n startPairing,\n} from '@kubb/studio'\nimport { buildTelemetryEvent, sendTelemetry } from '../../Telemetry.ts'\nimport setupReporters from '../../loggers/utils.ts'\nimport { createSpinner, logBlock, logIntro, logOutro, logTip, startTipRotation } from '../../loggers/output.ts'\nimport { canUseTTY } from '../../utils/env.ts'\nimport { getConfigs } from '../generate/utils.ts'\nimport { clearCredentials, type Credentials, getCredentialsPath, getProjectKubbHome, readCredentials, writeCredentials } from './credentials.ts'\nimport { version } from '../../../package.json'\n\ntype Permission = 'allowRead' | 'allowWrite' | 'allowConfigEdit' | 'allowInput' | 'allowExec'\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<Permission, 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 = StudioOptions & {\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 /**\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 * Seconds to wait for the job to finish.\n */\n timeout?: number\n /**\n * Print the result as one JSON object instead of a summary.\n */\n json?: boolean\n}\n\ntype StudioValues = {\n config?: string\n url?: string\n allowRead: boolean\n allowWrite: boolean\n allowConfigEdit: boolean\n allowInput: boolean\n allowExec: boolean\n open?: boolean\n logLevel?: CLIOptions['logLevel']\n}\n\nexport function createStudioOptions(values: StudioValues): StudioOptions {\n return {\n version,\n configPath: values.config,\n studioUrl: values.url ?? defaultStudioUrl,\n permission: {\n allowRead: values.allowRead,\n allowWrite: values.allowWrite,\n allowConfigEdit: values.allowConfigEdit,\n allowInput: values.allowInput,\n allowExec: values.allowExec,\n },\n autoOpen: values.open ?? true,\n logLevel: values.logLevel,\n }\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 session = await startPairing({ studioUrl, name: path.basename(process.cwd()), hostname: hostname(), signal })\n\n console.log(`\\nOpen ${styleText('cyan', session.verification_uri)} and approve the code ${styleText('bold', session.user_code)}`)\n\n if (autoOpen) {\n openInBrowser(session.verification_uri_complete)\n }\n\n const spinner = createSpinner()\n spinner.start('Waiting for approval')\n\n try {\n const { token, agent } = await pollForPairingToken({ studioUrl, session, signal })\n spinner.stop(`Paired as ${agent.name}`)\n\n const keepsIdentity = previousCredentials?.studioUrl === studioUrl && previousCredentials.agentId === agent.id\n const credentials: Credentials = {\n studioUrl,\n token,\n agentId: agent.id,\n agentSlug: agent.slug,\n ...(keepsIdentity && previousCredentials?.projects ? { projects: previousCredentials.projects } : {}),\n }\n await writeCredentials(credentials)\n\n console.log(`Credentials stored in ${getCredentialsPath()}`)\n\n return credentials\n } catch (error) {\n spinner.stop(error instanceof PairingCanceledError ? 'Pairing canceled' : 'Pairing failed')\n throw error\n }\n}\n\n/**\n * What each permission is asked as, in the order the questions appear.\n */\nconst PERMISSIONS: ReadonlyArray<{\n key: Permission\n /**\n * Short label for status output and the connect summary.\n */\n label: string\n question: (project: string, configPath: string) => string\n}> = [\n {\n key: 'allowRead',\n label: 'read generated files',\n question: () => 'Let Kubb Studio read the files a generation produced?',\n },\n { key: 'allowWrite', label: 'write generated files', question: (project) => `Let Kubb Studio write generated files into ${project}?` },\n {\n key: 'allowConfigEdit',\n label: 'edit kubb.config.ts',\n question: (_project, configPath) => `Let Kubb Studio change plugin options in ${configPath}?`,\n },\n {\n key: 'allowInput',\n label: 'use a Studio spec',\n question: () => 'Let Kubb Studio generate from an OpenAPI spec it sends, instead of the one on disk?',\n },\n {\n key: 'allowExec',\n label: 'run formatter, linter, postGenerate',\n question: () => 'Let Kubb Studio run the formatter, the linter, and output.postGenerate?',\n },\n]\n\n/**\n * One row per permission, for the connect banner and `kubb studio status`. A list rather than a\n * joined line: four labels this long read as one run-on sentence side by side.\n */\nexport function formatPermissionRows(granted: Record<Permission, boolean>): Array<string> {\n return PERMISSIONS.map(({ key, label }) => `${granted[key] ? styleText('green', '✔') : styleText('red', '✘')} ${label}`)\n}\n\n/**\n * Resolves Studio permissions for the current project.\n * Flags win, saved answers are reused, and new answers are stored unless `persist` is false.\n */\nexport async function resolvePermissions(\n options: StudioOptions,\n credentials: Credentials,\n configPath: string = KUBB_CONFIG_FILENAME,\n /**\n * Stores new answers in `~/.kubb/credentials.json`.\n * Pass `false` for `KUBB_AGENT_TOKEN` sessions so a temporary token is not written back to disk.\n */\n persist = true,\n): Promise<Record<Permission, boolean>> {\n const project = process.cwd()\n const remembered = credentials.projects?.[project]\n const granted: Record<Permission, boolean> = { allowRead: false, allowWrite: false, allowConfigEdit: false, allowInput: false, allowExec: false }\n const answers: Partial<Record<Permission, boolean>> = {}\n prompts.updateSettings({ withGuide: true })\n\n for (const { key, question } of PERMISSIONS) {\n if (options.permission[key] || typeof remembered?.[key] === 'boolean') {\n granted[key] = options.permission[key] || remembered?.[key] === true\n continue\n }\n\n if (isCIEnvironment() || !canUseTTY()) {\n granted[key] = false\n continue\n }\n\n granted[key] = (await prompts.confirm({ message: question(project, configPath), initialValue: false })) === true\n answers[key] = granted[key]\n }\n if (persist && Object.keys(answers).length) {\n await writeCredentials({\n ...credentials,\n projects: { ...credentials.projects, [project]: { ...remembered, ...answers } },\n })\n }\n\n return granted\n}\n\n/**\n * Loads the project's Kubb config the same way `kubb generate` does.\n * Returns the first config.\n */\nexport async function loadConfigs(options: StudioOptions): Promise<{ configPath: string; config: Config }> {\n const { configPath, configs } = await getConfigs({ configPath: options.configPath, logLevel: options.logLevel })\n const [config] = configs\n\n if (!config) {\n throw new Error('Config not defined, create a kubb.config.ts or pass it with --config')\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, config }\n}\n\n/**\n * Why a rejected token could not be recovered automatically: it came from `KUBB_AGENT_TOKEN`, no\n * browser is available to re-pair with, or the token this run already re-paired for was rejected\n * again.\n */\ntype RejectedTokenReason = 'envToken' | 'nonInteractive' | 'reauthExhausted'\n\n/**\n * Explains a rejected token to the operator. Builds the error and nothing else, so each caller\n * decides what happens to the credentials.\n */\nfunction explainRejectedToken(error: InvalidAgentTokenError, reason: RejectedTokenReason): Error {\n if (reason === 'envToken') {\n return new Error(`${error.message} Pair again and update KUBB_AGENT_TOKEN.`)\n }\n\n if (reason === 'reauthExhausted') {\n return new Error(`${error.message} Studio rejected the newly approved token too. Run \\`kubb studio login\\` and try again.`)\n }\n\n return new Error(`${error.message} Run \\`kubb studio login\\` to pair again.`)\n}\n\n/**\n * One `kubb studio` connect run: pairing if needed, connecting, and pairing again whenever Studio\n * rejects the token. Reached through `connect()`, which is what the command runs.\n */\nclass StudioConnection {\n readonly #options: StudioOptions\n readonly #configPath: string\n readonly #shutdown = new AbortController()\n readonly #requestShutdown = (): void => this.#shutdown.abort()\n // `bun-types` narrows `process.on`/`process.off` to its own event union, which omits Node's\n // process signal events, so the listener is installed and removed through the plain emitter API.\n readonly #processEvents = process as unknown as NodeJS.EventEmitter\n\n // Known once `run()` resolves the initial credentials, before anything else reads this field.\n #credentials!: Credentials\n // Whether the \"Press Ctrl+C\" hint already printed, so a reconnect never repeats it.\n #hinted = false\n #commandActive = false\n // One automatic re-pair per run, whether the rejection lands at startup or once the session is\n // live. A token rejected right after a fresh login is a hard failure, not a reason to keep\n // pairing.\n #hasReauthenticated = false\n #stopTipRotation: (() => void) | undefined\n // Resolved by `run()` from the flags and the project's saved answers, before anything reads it.\n #granted!: Record<Permission, boolean>\n\n constructor(options: StudioOptions, configPath: string) {\n this.#options = options\n this.#configPath = configPath\n }\n\n #reportDisconnected(): void {\n if (this.#options.logLevel === 'silent') {\n return\n }\n\n logOutro('Disconnected')\n }\n\n /**\n * Connects and streams generation events until the process is stopped or Studio rejects the\n * token.\n *\n * One `AbortController` covers the whole run: it cancels an in-flight pairing poll on Ctrl+C and\n * ends the wait in `#connectAndWait`. Its signal listeners are armed once here, so a retried\n * pairing cannot leave a duplicate behind.\n */\n async run(): Promise<void> {\n this.#processEvents.once('SIGINT', this.#requestShutdown)\n this.#processEvents.once('SIGTERM', this.#requestShutdown)\n\n try {\n this.#credentials = await this.#resolveInitialCredentials()\n\n this.#granted = await resolvePermissions(this.#options, this.#credentials, this.#configPath, !process.env.KUBB_AGENT_TOKEN)\n\n this.#printBanner()\n\n const outcome = await runConnection({\n credentials: this.#credentials,\n signal: this.#shutdown.signal,\n clientOptions: () => this.#clientOptions(),\n onTokenRejected: ({ error, live }) => this.#handleRejection(error, live),\n })\n\n if (outcome === 'shutdown') {\n this.#reportDisconnected()\n }\n } catch (error) {\n // Canceling the very first pairing (before anything was ever connected) is Ctrl+C working as\n // intended, not a failure to report.\n if (error instanceof PairingCanceledError) {\n return\n }\n\n throw error\n } finally {\n this.#stopTipRotation?.()\n this.#processEvents.off('SIGINT', this.#requestShutdown)\n this.#processEvents.off('SIGTERM', this.#requestShutdown)\n }\n }\n\n async #resolveInitialCredentials(): Promise<Credentials> {\n const envToken = process.env.KUBB_AGENT_TOKEN\n const stored = envToken ? null : await readCredentials()\n\n // A credential is only reused for the Studio it was issued by, so switching `--url` re-pairs\n // instead of sending one instance's token to another.\n const resolved = envToken\n ? { studioUrl: this.#options.studioUrl, token: envToken, agentId: '', agentSlug: '' }\n : stored?.studioUrl === this.#options.studioUrl\n ? stored\n : null\n\n if (resolved) {\n return resolved\n }\n\n if (isCIEnvironment()) {\n throw new Error(`Not paired with ${this.#options.studioUrl}. Set KUBB_AGENT_TOKEN, or run \\`kubb studio login\\` on a machine with a browser.`)\n }\n\n return login(this.#options, { signal: this.#shutdown.signal })\n }\n\n #printBanner(): void {\n if (this.#options.logLevel === 'silent') {\n return\n }\n\n const detail = (label: string, value: string) => `${styleText('dim', label.padEnd(7))} ${value}`\n\n logBlock([\n detail('Studio', styleText('cyan', this.#options.studioUrl)),\n detail('Project', path.basename(process.cwd())),\n detail('Config', path.relative(process.cwd(), this.#configPath) || this.#configPath),\n '',\n styleText('dim', 'Permissions'),\n ...formatPermissionRows(this.#granted),\n ])\n }\n\n /**\n * What every connection attempt opens with. Rebuilt per attempt, so a re-pair that changed the\n * granted permissions takes effect on the next one.\n */\n #clientOptions(): Omit<ClientOptions, 'token' | 'onAuthRequired'> {\n return {\n studioUrl: this.#options.studioUrl,\n configPath: this.#configPath,\n version: this.#options.version,\n // Reloaded on every generate, so an edit to kubb.config.ts is picked up without reconnecting.\n loadConfig: async () => (await loadConfigs(this.#options)).config,\n client: { kind: 'cli' },\n root: process.cwd(),\n permissions: this.#granted,\n logLevel: logLevelMap[this.#options.logLevel ?? 'info'],\n // The loggers `kubb generate` installs, so one place renders the session events and the\n // generations it drives.\n installLogger: async (hooks) => {\n await setupReporters(hooks, { logLevel: logLevelMap[this.#options.logLevel ?? 'info'], reporters: [cliReporter] })\n\n // `client.connect()` resolves once the agent is registered, not once a session is open, so\n // this is the only point that knows the connection is live. Registered after the loggers so\n // it lands under their \"Connected to ...\" line, and once, since every reconnect fires again.\n hooks.hook('studio:connected', () => {\n if (this.#hinted || this.#options.logLevel === 'silent') {\n return\n }\n this.#hinted = true\n\n logBlock(styleText('dim', 'Press Ctrl+C to disconnect'))\n })\n // Show one tip as soon as the session is ready, then replace it every five minutes.\n hooks.hook('studio:ready', () => {\n logTip()\n this.#stopTipRotation ??= startTipRotation({\n intervalMs: 300_000,\n max: Number.POSITIVE_INFINITY,\n isIdle: () => !this.#commandActive,\n })\n })\n hooks.hook('studio:command:start', () => {\n this.#commandActive = true\n })\n hooks.hook('studio:command:end', () => {\n this.#commandActive = false\n })\n hooks.hook('studio:error', () => {\n this.#commandActive = false\n })\n },\n }\n }\n\n /**\n * Throws when a rejected token cannot be replaced by pairing again: this run already paired once\n * and was rejected anyway, or there is no browser to approve a new pairing.\n */\n #assertCanReauthenticate(error: InvalidAgentTokenError): void {\n if (this.#hasReauthenticated) {\n throw explainRejectedToken(error, 'reauthExhausted')\n }\n\n if (isCIEnvironment() || !canUseTTY()) {\n throw explainRejectedToken(error, 'nonInteractive')\n }\n }\n\n /**\n * Studio rejected the token, either before a session ever opened or once one was already live.\n * Keeping a rejected token only produces 401s on every run, so it is forgotten and paired again.\n * Returns the credential to reconnect with, or null when the run is over.\n */\n async #handleRejection(error: InvalidAgentTokenError, live: boolean): Promise<Credentials | null> {\n // An operator-supplied token is never replaced automatically.\n if (process.env.KUBB_AGENT_TOKEN) {\n throw explainRejectedToken(error, 'envToken')\n }\n\n // A token dead at startup is forgotten either way. A live one is only forgotten once this run\n // knows it can pair again, so a CI run keeps the credential it could not replace.\n if (!live) {\n await clearCredentials()\n }\n\n this.#assertCanReauthenticate(error)\n\n console.log(styleText('yellow', live ? `${error.message} Studio needs you to approve access again.` : `${error.message} Pairing again...`))\n\n if (live) {\n await clearCredentials()\n }\n\n const credentials = await this.#reauthenticate()\n\n // Nothing was ever connected at startup, so there is no session to report the end of.\n if (!credentials && live) {\n this.#reportDisconnected()\n }\n\n return credentials\n }\n\n /**\n * Re-pairs and stores the resulting credentials. Returns null when the operator canceled it.\n */\n async #reauthenticate(): Promise<Credentials | null> {\n try {\n this.#credentials = await login(this.#options, { signal: this.#shutdown.signal, previousCredentials: this.#credentials })\n } catch (loginError) {\n if (loginError instanceof PairingCanceledError) {\n return null\n }\n throw loginError\n }\n\n this.#hasReauthenticated = true\n\n // The approved agent may be a different identity, whose saved permissions did not carry\n // forward. Resolving again asks for whatever this credential does not already hold, instead\n // of handing the new agent what the previous one was granted.\n this.#granted = await resolvePermissions(this.#options, this.#credentials, this.#configPath, !process.env.KUBB_AGENT_TOKEN)\n\n return this.#credentials\n }\n}\n\n/**\n * Connects this project to Studio and streams generation events until the process is stopped or\n * Studio rejects the token.\n */\nexport async function connect(options: StudioOptions): Promise<void> {\n // Resolved before any network call to Studio (pairing included), so a project with no config\n // fails fast instead of starting a device-authorization flow it can never use.\n const { configPath } = await loadConfigs(options)\n\n await new StudioConnection(options, configPath).run()\n}\n\n/**\n * Reports the paired agent and any saved permissions for the current project.\n */\nexport async function status(options: StudioOptions): Promise<void> {\n const credentials = await readCredentials()\n\n if (!credentials) {\n console.log('Not paired. Run `kubb studio login`.')\n\n return\n }\n\n console.log(`Paired with ${credentials.studioUrl} as ${styleText('cyan', credentials.agentSlug || credentials.agentId)}`)\n\n if (credentials.studioUrl !== options.studioUrl) {\n console.log(styleText('yellow', `Connecting to ${options.studioUrl} needs pairing again.`))\n }\n\n const remembered = credentials.projects?.[process.cwd()]\n\n if (!remembered) {\n console.log(styleText('dim', 'No saved permissions for this project. Run `kubb studio` to connect and choose.'))\n\n return\n }\n\n console.log(styleText('dim', 'Saved permissions'))\n\n for (const row of formatPermissionRows({\n allowRead: remembered.allowRead === true,\n allowWrite: remembered.allowWrite === true,\n allowConfigEdit: remembered.allowConfigEdit === true,\n allowInput: remembered.allowInput === true,\n allowExec: remembered.allowExec === true,\n })) {\n console.log(row)\n }\n}\n\n/**\n * Runs a Studio command with shared setup and telemetry reporting.\n */\nexport async function run(options: StudioOptions, action: () => Promise<unknown>, { block = false, json = false } = {}): Promise<void> {\n // The machine secret lives here and pairing binds it, so storage is installed before anything\n // reads `getMachineToken()`, which `startPairing` does, before any client exists.\n setStorage(createFileStorage(getProjectKubbHome()))\n\n const hrStart = process.hrtime()\n const report = (status: 'success' | 'failed') => sendTelemetry(buildTelemetryEvent({ command: 'studio', kubbVersion: options.version, hrStart, status }))\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()\n\n await report('success')\n } catch (error) {\n await report('failed')\n console.error(toError(error).message)\n process.exitCode = 1\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;AAOA,SAAgB,cAAc,QAAsB;CAClD,IAAI,gBAAgB,GAAG;CAEvB,IAAI,QAAQ,aAAa,SACvB,SAAS,OAAO;EAAC;EAAM;EAAS;EAAI;CAAM,SAAS,CAAC,CAAC;MAErD,SAAS,QAAQ,aAAa,WAAW,SAAS,YAAY,CAAC,MAAM,SAAS,CAAC,CAAC;AAEpF;;;;;;;;;;;;;;ACAA,eAAsB,OAAO,MAAgC;CAC3D,IAAI,QAAQ,OACV,OAAO,IAAI,KAAK,IAAI,CAAC,CAAC,OAAO;CAE/B,OAAO,OAAO,IAAI,CAAC,CAAC,WACZ,YACA,KACR;AACF;;;;;;;;;;AAWA,eAAsB,KAAK,MAA+B;CACxD,IAAI,QAAQ,OACV,OAAO,IAAI,KAAK,IAAI,CAAC,CAAC,KAAK;CAE7B,OAAO,SAAS,MAAM,EAAE,UAAU,OAAO,CAAC;AAC5C;;;;;;;;;AAsGA,eAAsB,MAAM,MAA6B;CACvD,OAAO,GAAG,MAAM;EAAE,WAAW;EAAM,OAAO;CAAK,CAAC;AAClD;;;;;;;ACpIA,SAAS,cAAsB;CAC7B,OAAO,QAAQ,IAAI,aAAa,KAAK,KAAK,QAAQ,GAAG,OAAO;AAC9D;;;;;;;AAQA,SAAgB,mBAAmB,UAAU,QAAQ,IAAI,GAAW;CAClE,MAAM,YAAY,KAAK,UAAU,OAAO;CACxC,OAAO,KAAK,KAAK,YAAY,GAAG,YAAY,SAAS;AACvD;AAEA,MAAM,uBAAuB;;;;AAK7B,SAAgB,qBAA6B;CAC3C,OAAO,KAAK,KAAK,mBAAmB,GAAG,oBAAoB;AAC7D;;;;;;AAyBA,eAAsB,kBAA+C;CACnE,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YAAY,OAAO,GAAG;CAExH,IAAI,YAAY,cAAc,QAAQ,WACpC,QAAQ,IAAI,UAAU,UAAU,iBAAiB,QAAQ,UAAU,sBAAsB,CAAC;CAG5F,MAAM,aAAa,YAAY,WAAW,QAAQ,IAAI;CAEtD,IAAI,CAAC,YAAY;EACf,QAAQ,IAAI,UAAU,OAAO,iFAAiF,CAAC;EAE/G;CACF;CAEA,QAAQ,IAAI,UAAU,OAAO,mBAAmB,CAAC;CAEjD,KAAK,MAAM,OAAO,qBAAqB;EACrC,WAAW,WAAW,cAAc;EACpC,YAAY,WAAW,eAAe;EACtC,iBAAiB,WAAW,oBAAoB;EAChD,YAAY,WAAW,eAAe;EACtC,WAAW,WAAW,cAAc;CACtC,CAAC,GACC,QAAQ,IAAI,GAAG;AAEnB;;;;AAKA,eAAsB,IAAI,SAAwB,QAAgC,EAAE,QAAQ,OAAO,OAAO,UAAU,CAAC,GAAkB;CAGrI,WAAW,kBAAkB,mBAAmB,CAAC,CAAC;CAElD,MAAM,UAAU,QAAQ,OAAO;CAC/B,MAAM,UAAU,WAAiC,cAAc,oBAAoB;EAAE,SAAS;EAAU,aAAa,QAAQ;EAAS;EAAS;CAAO,CAAC,CAAC;CAExJ,IAAI;EACF,IAAI,QAAQ,aAAa,YAAY,CAAC,MACpC,SAAS;GACP,SAAS,UAAU,UAAU,2DAA2D;GACxF;EACF,CAAC;EAGH,MAAM,OAAO;EAEb,MAAM,OAAO,SAAS;CACxB,SAAS,OAAO;EACd,MAAM,OAAO,QAAQ;EACrB,QAAQ,MAAM,QAAQ,KAAK,CAAC,CAAC,OAAO;EACpC,QAAQ,WAAW;CACrB;AACF"}
@@ -1,9 +1,9 @@
1
1
  import "./rolldown-runtime-C0LytTxp.js";
2
2
  import { t as toError } from "./errors-C8yNfV7w.js";
3
- import { i as KUBB_NPM_PACKAGE_URL, o as UPDATE_CHECK_TIMEOUT_MS, r as sendTelemetry, t as buildTelemetryEvent } from "./Telemetry-CJcQkQOT.js";
4
- import { a as runPostGenerate, c as selectReporters, d as LINTER_PREFERENCE, f as detectTool, i as runHook, l as setupReporters, m as linters, n as getConfigs, o as startUrlWatcher, p as formatters, r as isNewerVersion, s as startWatcher, t as fetchUrlBody, u as FORMATTER_PREFERENCE } from "./utils-s6yetN6W.js";
5
- import { t as version } from "./package-CRlfmw6k.js";
6
- import { i as logInfo, r as logError, s as logStep } from "./output-DH2Uoy4x.js";
3
+ import { i as KUBB_NPM_PACKAGE_URL, o as UPDATE_CHECK_TIMEOUT_MS, r as sendTelemetry, t as buildTelemetryEvent } from "./Telemetry-Dw5s6abr.js";
4
+ import { a as runPostGenerate, c as pluralize, d as FORMATTER_PREFERENCE, f as LINTER_PREFERENCE, h as linters, i as runHook, l as selectReporters, m as formatters, n as getConfigs, o as startUrlWatcher, p as detectTool, r as isNewerVersion, s as startWatcher, t as fetchUrlBody, u as setupReporters } from "./utils-B1_SWa35.js";
5
+ import { a as logInfo, c as logSpacer, f as startTipRotation, i as logError, l as logStep, n as logBanner, o as logIntro, s as logOutro, t as createSpinner, u as logTip } from "./output-CdnsdD1b.js";
6
+ import { t as version } from "./package-CDw1YdJ8.js";
7
7
  import { styleText } from "node:util";
8
8
  import { randomUUID } from "node:crypto";
9
9
  import process from "node:process";
@@ -63,7 +63,6 @@ async function runToolPass({ toolValue, tool, outputPath, logLevel: logLevel$1,
63
63
  async function generate(options) {
64
64
  const { input, hooks, logLevel, dryRun = false } = options;
65
65
  const hrStart = process.hrtime();
66
- const inputPath = input ?? (typeof options.config.input === "string" ? options.config.input : void 0);
67
66
  const config = {
68
67
  ...options.config,
69
68
  input: input ?? options.config.input,
@@ -135,12 +134,6 @@ async function generate(options) {
135
134
  }
136
135
  return outputDiagnostics;
137
136
  };
138
- hooks.hook("kubb:generation:end", ({ status }) => {
139
- if (status === "success") return hooks.callHook("kubb:success", {
140
- message: "Generation succeeded",
141
- info: inputPath
142
- });
143
- });
144
137
  const kubb = createKubb(config, { hooks });
145
138
  const result = await kubb.generate({ processOutput });
146
139
  if (dryRun) await hooks.callHook("kubb:info", {
@@ -192,9 +185,17 @@ async function checkForUpdate(hooks) {
192
185
  async function run({ input, configPath, logLevel: logLevelKey, watch, reporters: cliReporters, dryRun }) {
193
186
  const logLevel$2 = logLevel[logLevelKey] ?? logLevel.info;
194
187
  const hooks = new Hookable();
188
+ const requestedNames = cliReporters?.length ? cliReporters : ["cli"];
189
+ const quiet = logLevel$2 <= logLevel.silent || requestedNames.includes("json");
190
+ if (!quiet) {
191
+ logBanner(version);
192
+ logIntro({ title: "Configuration" });
193
+ }
194
+ const configSpinner = createSpinner();
195
195
  let configs;
196
196
  let resolvedConfigPath;
197
197
  try {
198
+ if (!quiet) configSpinner.start("Loading config");
198
199
  const loaded = await getConfigs({
199
200
  configPath,
200
201
  input,
@@ -203,15 +204,17 @@ async function run({ input, configPath, logLevel: logLevelKey, watch, reporters:
203
204
  });
204
205
  configs = loaded.configs;
205
206
  resolvedConfigPath = loaded.configPath;
207
+ if (!quiet) configSpinner.stop(`Loaded ${styleText("dim", path.relative(process.cwd(), resolvedConfigPath))}`);
206
208
  } catch (error) {
209
+ if (!quiet) configSpinner.error("Config failed loading");
207
210
  await setupReporters(hooks, {
208
211
  logLevel: logLevel$2,
209
212
  reporters: [cliReporter]
210
213
  });
211
214
  await hooks.callHook("kubb:error", { error: toError(error) });
215
+ if (!quiet) logOutro(styleText("red", "✗ Configuration failed"));
212
216
  process.exit(1);
213
217
  }
214
- const requestedNames = cliReporters?.length ? cliReporters : ["cli"];
215
218
  const reporters = selectReporters(configs[0]?.reporters ?? [], requestedNames);
216
219
  await setupReporters(hooks, {
217
220
  logLevel: logLevel$2,
@@ -219,17 +222,10 @@ async function run({ input, configPath, logLevel: logLevelKey, watch, reporters:
219
222
  });
220
223
  await hooks.callHook("kubb:lifecycle:start", { version });
221
224
  await checkForUpdate(hooks);
225
+ if (!quiet) logOutro(`${pluralize(configs.length, "config")} ready`);
222
226
  try {
223
- const relativeConfigPath = path.relative(process.cwd(), resolvedConfigPath);
224
- await hooks.callHook("kubb:info", {
225
- message: "Config loaded",
226
- info: relativeConfigPath
227
- });
228
- await hooks.callHook("kubb:success", {
229
- message: "Config loaded successfully",
230
- info: relativeConfigPath
231
- });
232
227
  let anyFailed = false;
228
+ let tipRotationStarted = false;
233
229
  for (const config of configs) {
234
230
  const effectiveInput = input ?? config.input;
235
231
  const inputKind = typeof effectiveInput === "string" ? getInputKind(effectiveInput) : void 0;
@@ -237,7 +233,7 @@ async function run({ input, configPath, logLevel: logLevelKey, watch, reporters:
237
233
  if (watchPath && watch) {
238
234
  const watchedPaths = [watchPath];
239
235
  const build = async (paths) => {
240
- await generate({
236
+ const succeeded = await generate({
241
237
  input,
242
238
  config,
243
239
  logLevel: logLevel$2,
@@ -245,6 +241,10 @@ async function run({ input, configPath, logLevel: logLevelKey, watch, reporters:
245
241
  dryRun
246
242
  });
247
243
  logStep(styleText("yellow", `Watching for changes in ${paths.join(" and ")}`));
244
+ if (succeeded) {
245
+ logSpacer();
246
+ logTip();
247
+ }
248
248
  };
249
249
  const initialBody = inputKind === "url" ? await fetchUrlBody(watchPath) : void 0;
250
250
  try {
@@ -263,6 +263,10 @@ async function run({ input, configPath, logLevel: logLevelKey, watch, reporters:
263
263
  info: logInfo,
264
264
  error: logError
265
265
  });
266
+ if (!tipRotationStarted) {
267
+ tipRotationStarted = true;
268
+ startTipRotation();
269
+ }
266
270
  } else try {
267
271
  if (!await generate({
268
272
  input,
@@ -286,4 +290,4 @@ async function run({ input, configPath, logLevel: logLevelKey, watch, reporters:
286
290
  //#endregion
287
291
  export { run };
288
292
 
289
- //# sourceMappingURL=run-ByKuuI4i.js.map
293
+ //# sourceMappingURL=run-C5HkzCUt.js.map