@kubb/agent 4.29.0 → 4.31.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.
Files changed (61) hide show
  1. package/.output/nitro.json +1 -1
  2. package/.output/server/chunks/nitro/nitro.mjs +509 -345
  3. package/.output/server/chunks/nitro/nitro.mjs.map +1 -1
  4. package/.output/server/chunks/routes/api/health.get.mjs +3 -1
  5. package/.output/server/chunks/routes/api/health.get.mjs.map +1 -1
  6. package/.output/server/index.mjs +3 -1
  7. package/.output/server/index.mjs.map +1 -1
  8. package/.output/server/node_modules/@kubb/fabric-core/dist/index.js +6 -3
  9. package/.output/server/node_modules/@kubb/fabric-core/dist/{onProcessExit-CF200hsz.js → onProcessExit-B0rJqX4s.js} +7 -1
  10. package/.output/server/node_modules/@kubb/fabric-core/dist/plugins.js +1 -1
  11. package/.output/server/node_modules/@kubb/fabric-core/package.json +1 -1
  12. package/.output/server/node_modules/@kubb/react-fabric/dist/index.js +1 -1
  13. package/.output/server/node_modules/@kubb/react-fabric/dist/plugins.js +1 -1
  14. package/.output/server/node_modules/@kubb/react-fabric/dist/{reactPlugin-BkDkx1cs.js → reactPlugin-tE73eBS_.js} +5 -1
  15. package/.output/server/node_modules/@kubb/react-fabric/package.json +2 -2
  16. package/.output/server/node_modules/@logtail/core/dist/cjs/base.js +339 -0
  17. package/.output/server/node_modules/@logtail/core/dist/cjs/index.js +9 -0
  18. package/.output/server/node_modules/@logtail/core/package.json +45 -0
  19. package/.output/server/node_modules/@logtail/node/dist/cjs/context.js +93 -0
  20. package/.output/server/node_modules/@logtail/node/dist/cjs/index.js +6 -0
  21. package/.output/server/node_modules/@logtail/node/dist/cjs/node.js +106 -0
  22. package/.output/server/node_modules/@logtail/node/package.json +53 -0
  23. package/.output/server/node_modules/@logtail/tools/dist/cjs/batch.js +122 -0
  24. package/.output/server/node_modules/@logtail/tools/dist/cjs/burstProtection.js +50 -0
  25. package/.output/server/node_modules/@logtail/tools/dist/cjs/encode.js +12 -0
  26. package/.output/server/node_modules/@logtail/tools/dist/cjs/index.js +41 -0
  27. package/.output/server/node_modules/@logtail/tools/dist/cjs/queue.js +41 -0
  28. package/.output/server/node_modules/@logtail/tools/dist/cjs/throttle.js +67 -0
  29. package/.output/server/node_modules/@logtail/tools/package.json +39 -0
  30. package/.output/server/node_modules/@logtail/types/dist/cjs/types.js +21 -0
  31. package/.output/server/node_modules/@logtail/types/package.json +45 -0
  32. package/.output/server/node_modules/@msgpack/msgpack/dist/CachedKeyDecoder.js +63 -0
  33. package/.output/server/node_modules/@msgpack/msgpack/dist/DecodeError.js +18 -0
  34. package/.output/server/node_modules/@msgpack/msgpack/dist/Decoder.js +583 -0
  35. package/.output/server/node_modules/@msgpack/msgpack/dist/Encoder.js +408 -0
  36. package/.output/server/node_modules/@msgpack/msgpack/dist/ExtData.js +14 -0
  37. package/.output/server/node_modules/@msgpack/msgpack/dist/ExtensionCodec.js +72 -0
  38. package/.output/server/node_modules/@msgpack/msgpack/dist/decode.js +32 -0
  39. package/.output/server/node_modules/@msgpack/msgpack/dist/decodeAsync.js +44 -0
  40. package/.output/server/node_modules/@msgpack/msgpack/dist/encode.js +17 -0
  41. package/.output/server/node_modules/@msgpack/msgpack/dist/index.js +34 -0
  42. package/.output/server/node_modules/@msgpack/msgpack/dist/timestamp.js +104 -0
  43. package/.output/server/node_modules/@msgpack/msgpack/dist/utils/int.js +34 -0
  44. package/.output/server/node_modules/@msgpack/msgpack/dist/utils/prettyByte.js +8 -0
  45. package/.output/server/node_modules/@msgpack/msgpack/dist/utils/stream.js +40 -0
  46. package/.output/server/node_modules/@msgpack/msgpack/dist/utils/typedArrays.js +28 -0
  47. package/.output/server/node_modules/@msgpack/msgpack/dist/utils/utf8.js +167 -0
  48. package/.output/server/node_modules/@msgpack/msgpack/package.json +100 -0
  49. package/.output/server/node_modules/consola/dist/chunks/prompt.mjs +280 -0
  50. package/.output/server/node_modules/consola/dist/core.mjs +512 -0
  51. package/.output/server/node_modules/consola/dist/index.mjs +651 -0
  52. package/.output/server/node_modules/consola/dist/shared/consola.DRwqZj3T.mjs +72 -0
  53. package/.output/server/node_modules/consola/dist/shared/consola.DXBYu-KD.mjs +288 -0
  54. package/.output/server/node_modules/consola/package.json +136 -0
  55. package/.output/server/node_modules/serialize-error/index.js +154 -0
  56. package/.output/server/node_modules/serialize-error/package.json +41 -0
  57. package/.output/server/node_modules/stack-trace/lib/stack-trace.js +136 -0
  58. package/.output/server/node_modules/stack-trace/package.json +21 -0
  59. package/.output/server/package.json +11 -3
  60. package/README.md +3 -3
  61. package/package.json +23 -18
@@ -6,14 +6,15 @@ import http, { Server as Server$2 } from 'node:http';
6
6
  import https, { Server as Server$1 } from 'node:https';
7
7
  import { EventEmitter } from 'node:events';
8
8
  import { Buffer as Buffer$1 } from 'node:buffer';
9
- import fs$1, { promises, existsSync, readFileSync, writeFileSync } from 'node:fs';
9
+ import fs$1, { promises, existsSync, readFileSync } from 'node:fs';
10
10
  import path$2, { resolve, dirname, relative, join, normalize } from 'node:path';
11
11
  import anymatch from 'anymatch';
12
12
  import { createHash, randomBytes } from 'node:crypto';
13
13
  import process$1, { version as version$2 } from 'node:process';
14
+ import { Logtail } from '@logtail/node';
15
+ import { consola } from 'consola';
14
16
  import { sortBy, mergeDeep, isPlainObject as isPlainObject$1, uniqueWith, isDeepEqual, isNumber, isFunction, difference } from 'remeda';
15
17
  import { x } from 'tinyexec';
16
- import os$1 from 'node:os';
17
18
  import { styleText } from 'node:util';
18
19
  import { access, rm, readFile as readFile$1, mkdir, writeFile as writeFile$1 } from 'node:fs/promises';
19
20
  import { performance as performance$1 } from 'node:perf_hooks';
@@ -21,6 +22,7 @@ import mod, { createRequire } from 'node:module';
21
22
  import { createFabric, createReactFabric, App, File, Function as Function$1, Const, FunctionParams, Type as Type$1, useApp } from '@kubb/react-fabric';
22
23
  import { typescriptParser } from '@kubb/react-fabric/parsers';
23
24
  import { fsPlugin } from '@kubb/react-fabric/plugins';
25
+ import os$1 from 'node:os';
24
26
  import { pathToFileURL, fileURLToPath } from 'node:url';
25
27
  import * as pkg from 'empathic/package';
26
28
  import { coerce, satisfies } from 'semver';
@@ -4387,28 +4389,217 @@ function defineNitroPlugin(def) {
4387
4389
  return def;
4388
4390
  }
4389
4391
 
4390
- const logger = {
4391
- info(message, details) {
4392
- const text = details ? `${message} ${styleText("dim", details)}` : message;
4393
- console.info(`${styleText("blue", "\u2139")} ${text}`);
4394
- },
4395
- success(message, details) {
4396
- const text = details ? `${message} ${styleText("dim", details)}` : message;
4397
- console.log(`${styleText("green", "\u2713")} ${text}`);
4398
- },
4399
- warn(message, details) {
4400
- const text = details ? `${message} ${styleText("dim", details)}` : message;
4401
- console.warn(`${styleText("yellow", "\u26A0")} ${text}`);
4402
- },
4403
- error(message, details) {
4404
- const text = details ? `${message} ${styleText("dim", details)}` : message;
4405
- console.error(`${styleText("red", "\u2717")} ${text}`);
4392
+ let logtail = null;
4393
+ function getLogtail() {
4394
+ if (logtail) {
4395
+ return logtail;
4396
+ }
4397
+ const token = process.env.OTLP_TOKEN;
4398
+ if (!token) {
4399
+ return null;
4400
+ }
4401
+ try {
4402
+ logtail = new Logtail(token, {
4403
+ endpoint: process.env.OTEL_EXPORTER_OTLP_ENDPOINT
4404
+ });
4405
+ return logtail;
4406
+ } catch {
4407
+ return null;
4408
+ }
4409
+ }
4410
+ function toBetterStackContext(ctx) {
4411
+ if (!ctx) return void 0;
4412
+ const filtered = Object.fromEntries(Object.entries(ctx).filter(([, v]) => v !== void 0 && v !== null));
4413
+ return Object.keys(filtered).length ? filtered : void 0;
4414
+ }
4415
+ function sendToBetterStack(level, tag, message, ctx) {
4416
+ const client = getLogtail();
4417
+ if (!client) {
4418
+ return;
4419
+ }
4420
+ try {
4421
+ const fullMessage = message !== void 0 ? `[${tag}] ${message}` : tag;
4422
+ const context = toBetterStackContext(ctx);
4423
+ if (level === "error") {
4424
+ client.error(fullMessage, context).then(() => client.flush());
4425
+ } else if (level === "warn") {
4426
+ client.warn(fullMessage, context).then(() => client.flush());
4427
+ } else {
4428
+ client.info(fullMessage, context).then(() => client.flush());
4429
+ }
4430
+ } catch (_e) {
4406
4431
  }
4432
+ }
4433
+ function log(level, tag, message, ctx) {
4434
+ const displayMessage = message !== void 0 ? `[${tag}] ${message}` : tag;
4435
+ consola[level](displayMessage);
4436
+ if (ctx) {
4437
+ const filtered = Object.fromEntries(Object.entries(ctx).filter(([, v]) => v !== void 0 && v !== null));
4438
+ if (Object.keys(filtered).length) {
4439
+ console.table(filtered);
4440
+ }
4441
+ }
4442
+ if (process.env.OTEL_EXPORTER_OTLP_ENDPOINT && process.env.OTLP_TOKEN) {
4443
+ sendToBetterStack(level, tag, message, ctx);
4444
+ }
4445
+ }
4446
+ const logger = {
4447
+ info: (tag, message, ctx) => log("info", tag, message, ctx),
4448
+ success: (tag, message, ctx) => log("success", tag, message, ctx),
4449
+ warn: (tag, message, ctx) => log("warn", tag, message, ctx),
4450
+ error: (tag, message, ctx) => log("error", tag, message, ctx)
4407
4451
  };
4408
4452
 
4409
4453
  const _KZ9YuROWp70nNn4X1C4BxF_W0D7H9EWgBo03XvMd7w0 = defineNitroPlugin(() => {
4410
4454
  });
4411
4455
 
4456
+ function maskedString(value, start = 8, end = 4) {
4457
+ if (value.length <= start + end) return value;
4458
+ return `${value.slice(0, start)}\u2026${value.slice(-end)}`;
4459
+ }
4460
+
4461
+ const HEARTBEAT_INTERVAL_MS = 5 * 60 * 1e3;
4462
+ const _a2VEEUGb5K4b1gyM9hOmO1Xz0hUJSFuGyIT3cHsvE = defineNitroPlugin((nitro) => {
4463
+ const heartbeatUrl = process$1.env.KUBB_AGENT_HEARTBEAT_URL;
4464
+ if (!heartbeatUrl) {
4465
+ return;
4466
+ }
4467
+ const maskedUrl = maskedString(heartbeatUrl);
4468
+ const timer = setInterval(async () => {
4469
+ try {
4470
+ await $fetch(heartbeatUrl, { method: "GET" });
4471
+ logger.info(`Heartbeat sent to ${maskedUrl}`);
4472
+ } catch (error) {
4473
+ logger.warn(`Failed to send heartbeat to ${maskedUrl}`, error == null ? void 0 : error.message);
4474
+ }
4475
+ }, HEARTBEAT_INTERVAL_MS);
4476
+ nitro.hooks.hook("close", () => {
4477
+ clearInterval(timer);
4478
+ });
4479
+ });
4480
+
4481
+ function getStorage() {
4482
+ return useStorage("kubb");
4483
+ }
4484
+ function isSessionValid(session) {
4485
+ try {
4486
+ const expiresAt = new Date(session.expiresAt);
4487
+ const now = /* @__PURE__ */ new Date();
4488
+ return now.getTime() < expiresAt.getTime() - 6e4;
4489
+ } catch {
4490
+ return false;
4491
+ }
4492
+ }
4493
+ function getSessionKey(token) {
4494
+ return `sessions:${createHash("sha512").update(token).digest("hex")}`;
4495
+ }
4496
+ async function getCachedSession(sessionKey) {
4497
+ const storage = getStorage();
4498
+ const agentSession = await storage.getItem(sessionKey);
4499
+ if (!agentSession) {
4500
+ return null;
4501
+ }
4502
+ if (!isSessionValid(agentSession)) {
4503
+ return null;
4504
+ }
4505
+ return agentSession;
4506
+ }
4507
+ async function cacheSession({ sessionKey, session }) {
4508
+ const storage = getStorage();
4509
+ await storage.setItem(sessionKey, { ...session, storedAt: (/* @__PURE__ */ new Date()).toISOString(), configs: [] });
4510
+ }
4511
+ async function removeCachedSession(sessionKey) {
4512
+ const storage = getStorage();
4513
+ const maskedSessionKey = maskedString(sessionKey.replace("sessions:", ""));
4514
+ logger.info(`[${maskedSessionKey}] Removing expired agent session from cache...`);
4515
+ await storage.removeItem(sessionKey);
4516
+ logger.success(`[${maskedSessionKey}] Removed expired agent session from cache`);
4517
+ }
4518
+ async function saveStudioConfigToStorage({ sessionKey, config }) {
4519
+ const storage = getStorage();
4520
+ const agentSession = await getCachedSession(sessionKey);
4521
+ if (!agentSession) {
4522
+ throw new Error("No valid session found for retrieving previous configs");
4523
+ }
4524
+ await storage.setItem(sessionKey, { ...agentSession, configs: [...agentSession.configs, { config, storedAt: (/* @__PURE__ */ new Date()).toISOString() }] });
4525
+ }
4526
+
4527
+ function generateToken() {
4528
+ return randomBytes(32).toString("hex");
4529
+ }
4530
+ function generateMachineToken() {
4531
+ return process.env.KUBB_AGENT_SECRET ? process.env.KUBB_AGENT_SECRET : createHash("sha256").update(generateToken()).digest("hex");
4532
+ }
4533
+
4534
+ async function createAgentSession({ token, studioUrl, noCache, cacheKey }) {
4535
+ const machineToken = generateMachineToken();
4536
+ const sessionKey = cacheKey != null ? cacheKey : getSessionKey(token);
4537
+ const maskedSessionKey = maskedString(sessionKey.replace("sessions:", ""));
4538
+ const connectUrl = `${studioUrl}/api/agent/session/create`;
4539
+ const canCache = !noCache;
4540
+ if (canCache) {
4541
+ const cachedSession = await getCachedSession(sessionKey);
4542
+ if (cachedSession) {
4543
+ logger.success(`[${maskedSessionKey}] Using cached agent session`);
4544
+ return cachedSession;
4545
+ }
4546
+ await removeCachedSession(sessionKey);
4547
+ }
4548
+ try {
4549
+ logger.info(`[${maskedSessionKey}] Creating agent session with Studio...`);
4550
+ const data = await $fetch(connectUrl, {
4551
+ method: "POST",
4552
+ headers: { Authorization: `Bearer ${token}` },
4553
+ body: { machineToken }
4554
+ });
4555
+ if (!data) {
4556
+ throw new Error("No data available for agent session");
4557
+ }
4558
+ if (canCache) {
4559
+ await cacheSession({ sessionKey, session: { ...data, storedAt: (/* @__PURE__ */ new Date()).toISOString(), configs: [] } });
4560
+ logger.success(`[${maskedSessionKey}] Saved agent session to cache`);
4561
+ }
4562
+ logger.info(`[${maskedSessionKey}] Created agent session with Studio`);
4563
+ return data;
4564
+ } catch (error) {
4565
+ throw new Error("Failed to get agent session from Kubb Studio", { cause: error });
4566
+ }
4567
+ }
4568
+ async function registerAgent({ token, studioUrl, poolSize }) {
4569
+ var _a, _b;
4570
+ const machineToken = generateMachineToken();
4571
+ const registerUrl = `${studioUrl}/api/agent/register`;
4572
+ try {
4573
+ logger.info("Registering agent with Studio...");
4574
+ await $fetch(registerUrl, {
4575
+ method: "POST",
4576
+ headers: {
4577
+ Authorization: `Bearer ${token}`
4578
+ },
4579
+ body: { machineToken, poolSize }
4580
+ });
4581
+ logger.success(`Agent registered with Studio with token ${maskedString(token)}`);
4582
+ } catch (error) {
4583
+ logger.error("Failed to register agent with Studio", (_b = (_a = error == null ? void 0 : error.cause) == null ? void 0 : _a.message) != null ? _b : error == null ? void 0 : error.message);
4584
+ }
4585
+ }
4586
+ async function disconnect({ sessionId, token, studioUrl }) {
4587
+ const disconnectUrl = `${studioUrl}/api/agent/session/${sessionId}/disconnect`;
4588
+ const maskedSessionKey = maskedString(sessionId);
4589
+ try {
4590
+ logger.info(`[${maskedSessionKey}] Disconnecting from Studio...`);
4591
+ await $fetch(disconnectUrl, {
4592
+ method: "POST",
4593
+ headers: {
4594
+ Authorization: `Bearer ${token}`
4595
+ }
4596
+ });
4597
+ logger.success(`[${maskedSessionKey}] Disconnected from Studio`);
4598
+ } catch (error) {
4599
+ throw new Error("Failed to notify Studio of disconnection on exit", { cause: error });
4600
+ }
4601
+ }
4602
+
4412
4603
  async function clean(path) {
4413
4604
  return rm(path, {
4414
4605
  recursive: true,
@@ -5882,121 +6073,16 @@ function tokenize(command) {
5882
6073
  return args;
5883
6074
  }
5884
6075
 
6076
+ var version = "4.31.0";
6077
+
5885
6078
  function isCommandMessage(msg) {
5886
6079
  return msg.type === "command";
5887
6080
  }
5888
6081
  function isPongMessage(msg) {
5889
6082
  return msg.type === "pong";
5890
6083
  }
5891
-
5892
- function getSessionKey(token) {
5893
- return `sessions:${createHash("sha512").update(token).digest("hex")}`;
5894
- }
5895
-
5896
- function isSessionValid(session) {
5897
- try {
5898
- const expiresAt = new Date(session.expiresAt);
5899
- const now = /* @__PURE__ */ new Date();
5900
- return now.getTime() < expiresAt.getTime() - 6e4;
5901
- } catch {
5902
- return false;
5903
- }
5904
- }
5905
-
5906
- function generateToken() {
5907
- return randomBytes(32).toString("hex");
5908
- }
5909
- function generateSecureToken(id = generateToken()) {
5910
- return createHash("sha256").update(id).digest("hex");
5911
- }
5912
- function generateMachineToken() {
5913
- if (process.env.KUBB_AGENT_SECRET) {
5914
- return generateSecureToken(process.env.KUBB_AGENT_SECRET);
5915
- }
5916
- const interfaces = os$1.networkInterfaces();
5917
- const macs = [];
5918
- for (const name in interfaces) {
5919
- for (const iface of interfaces[name]) {
5920
- if (!iface.internal && iface.mac !== "00:00:00:00:00:00") {
5921
- macs.push(iface.mac);
5922
- }
5923
- }
5924
- }
5925
- const hostname = os$1.hostname();
5926
- const rawId = macs.join(",") + hostname;
5927
- return generateSecureToken(rawId);
5928
- }
5929
-
5930
- async function createAgentSession({ token, studioUrl, noCache }) {
5931
- const storage = useStorage("kubb");
5932
- if (!noCache) {
5933
- const sessionKey = getSessionKey(token);
5934
- const stored = await storage.getItem(sessionKey);
5935
- if (stored && isSessionValid(stored)) {
5936
- logger.success("Using cached agent session");
5937
- return stored;
5938
- }
5939
- if (stored) {
5940
- await storage.removeItem(sessionKey);
5941
- }
5942
- }
5943
- const connectUrl = `${studioUrl}/api/agent/session/create`;
5944
- try {
5945
- const machineToken = generateMachineToken();
5946
- const data = await $fetch(connectUrl, {
5947
- method: "POST",
5948
- headers: {
5949
- Authorization: `Bearer ${token}`
5950
- },
5951
- body: { machineToken }
5952
- });
5953
- if (!data) {
5954
- throw new Error("No data available for agent session");
5955
- }
5956
- if (!noCache) {
5957
- const sessionKey = getSessionKey(token);
5958
- await storage.setItem(sessionKey, {
5959
- ...data,
5960
- storedAt: (/* @__PURE__ */ new Date()).toISOString()
5961
- });
5962
- logger.success("Cached agent session");
5963
- }
5964
- logger.success("Agent session created");
5965
- return data;
5966
- } catch (error) {
5967
- throw new Error("Failed to get agent session from Kubb Studio", { cause: error });
5968
- }
5969
- }
5970
- async function registerAgent({ token, studioUrl }) {
5971
- var _a, _b;
5972
- const machineToken = generateMachineToken();
5973
- const registerUrl = `${studioUrl}/api/agent/register`;
5974
- try {
5975
- await $fetch(registerUrl, {
5976
- method: "POST",
5977
- headers: {
5978
- Authorization: `Bearer ${token}`
5979
- },
5980
- body: { machineToken }
5981
- });
5982
- logger.success("Agent registered with Studio");
5983
- } catch (error) {
5984
- logger.warn("Failed to register agent with Studio", (_b = (_a = error == null ? void 0 : error.cause) == null ? void 0 : _a.message) != null ? _b : error == null ? void 0 : error.message);
5985
- }
5986
- }
5987
- async function disconnect({ sessionToken, token, studioUrl }) {
5988
- try {
5989
- const disconnectUrl = `${studioUrl}/api/agent/session/${sessionToken}/disconnect`;
5990
- await $fetch(disconnectUrl, {
5991
- method: "POST",
5992
- headers: {
5993
- Authorization: `Bearer ${token}`
5994
- }
5995
- });
5996
- logger.success("Sent disconnect notification to Studio on exit");
5997
- } catch (error) {
5998
- throw new Error("Failed to notify Studio of disconnection on exit", { cause: error });
5999
- }
6084
+ function isDisconnectMessage(msg) {
6085
+ return msg.type === "disconnect";
6000
6086
  }
6001
6087
 
6002
6088
  var __typeError$3 = (msg) => {
@@ -6032,7 +6118,7 @@ var BaseGenerator = (_a$3 = class {
6032
6118
  function isInputPath(config) {
6033
6119
  return typeof (config == null ? void 0 : config.input) === "object" && config.input !== null && "path" in config.input;
6034
6120
  }
6035
- var version$1 = "4.29.0";
6121
+ var version$1 = "4.31.0";
6036
6122
  function getDiagnosticInfo() {
6037
6123
  return {
6038
6124
  nodeVersion: version$2,
@@ -6510,6 +6596,15 @@ async function getCosmiConfig(configPath) {
6510
6596
  }
6511
6597
  }
6512
6598
 
6599
+ async function loadConfig(resolvedConfigPath) {
6600
+ const result = await getCosmiConfig(resolvedConfigPath);
6601
+ const configs = await getConfigs(result.config, {});
6602
+ if (configs.length === 0) {
6603
+ throw new Error("No configs found");
6604
+ }
6605
+ return configs[0];
6606
+ }
6607
+
6513
6608
  var __defProp$8 = Object.defineProperty;
6514
6609
  var __name$5 = (target, value) => __defProp$8(target, "name", {
6515
6610
  value,
@@ -11469,6 +11564,7 @@ async function buildOperations(operations, { config, fabric, plugin, generator,
11469
11564
  })
11470
11565
  }));
11471
11566
  await fabric.context.fileManager.upsert(...fabricChild.files);
11567
+ fabricChild.unmount();
11472
11568
  }
11473
11569
  async function buildOperation(operation, { config, fabric, plugin, generator, Component }) {
11474
11570
  if (!Component) return;
@@ -11489,6 +11585,7 @@ async function buildOperation(operation, { config, fabric, plugin, generator, Co
11489
11585
  })
11490
11586
  }));
11491
11587
  await fabric.context.fileManager.upsert(...fabricChild.files);
11588
+ fabricChild.unmount();
11492
11589
  }
11493
11590
  async function buildSchema(schema, { config, fabric, plugin, Component, generator }) {
11494
11591
  if (!Component) return;
@@ -11509,6 +11606,7 @@ async function buildSchema(schema, { config, fabric, plugin, Component, generato
11509
11606
  })
11510
11607
  }));
11511
11608
  await fabric.context.fileManager.upsert(...fabricChild.files);
11609
+ fabricChild.unmount();
11512
11610
  }
11513
11611
  var SchemaGenerator = (_b = class extends BaseGenerator {
11514
11612
  constructor() {
@@ -11786,6 +11884,16 @@ getRefAlias_fn = function(schemaObject, name) {
11786
11884
  }
11787
11885
  }];
11788
11886
  }
11887
+ if ($ref.startsWith("#") && !$ref.startsWith("#/components/")) try {
11888
+ const inlineSchema = this.context.oas.get($ref);
11889
+ if (inlineSchema && !isReference(inlineSchema)) return this.parse({
11890
+ schema: inlineSchema,
11891
+ name,
11892
+ parentName: null,
11893
+ rootName: null
11894
+ });
11895
+ } catch {
11896
+ }
11789
11897
  __privateMethod$1(this, _SchemaGenerator_instances, ensureNameMapping_fn).call(this);
11790
11898
  const originalName = $ref.replace(/.+\//, "");
11791
11899
  const resolvedName = __privateGet(this, _schemaNameMapping).get($ref) || originalName;
@@ -12239,7 +12347,7 @@ parseSchemaObject_fn = function({ schema: _schemaObject, name, parentName, rootN
12239
12347
  }
12240
12348
  if (schemaObject.format) {
12241
12349
  if (schemaObject.type === "integer" && schemaObject.format === "int64") {
12242
- baseItems.unshift({ keyword: options.integerType === "number" ? schemaKeywords.integer : schemaKeywords.bigint });
12350
+ baseItems.unshift({ keyword: options.integerType === "bigint" ? schemaKeywords.bigint : schemaKeywords.integer });
12243
12351
  return baseItems;
12244
12352
  }
12245
12353
  if (schemaObject.type === "integer" && schemaObject.format === "int32") {
@@ -213216,7 +213324,7 @@ const pluginTs = definePlugin((options) => {
213216
213324
  const { output = {
213217
213325
  path: "types",
213218
213326
  barrelType: "named"
213219
- }, group, exclude = [], include, override = [], enumType = "asConst", enumKeyCasing = "none", enumSuffix = "enum", dateType = "string", integerType = "bigint", unknownType = "any", optionalType = "questionToken", arrayType = "array", emptySchemaType = unknownType, syntaxType = "type", transformers: transformers2 = {}, mapper = {}, paramsCasing, generators = [typeGenerator].filter(Boolean), contentType, UNSTABLE_NAMING } = options;
213327
+ }, group, exclude = [], include, override = [], enumType = "asConst", enumKeyCasing = "none", enumSuffix = "enum", dateType = "string", integerType = "number", unknownType = "any", optionalType = "questionToken", arrayType = "array", emptySchemaType = unknownType, syntaxType = "type", transformers: transformers2 = {}, mapper = {}, paramsCasing, generators = [typeGenerator].filter(Boolean), contentType, UNSTABLE_NAMING } = options;
213220
213328
  return {
213221
213329
  name: pluginTsName,
213222
213330
  options: {
@@ -213576,7 +213684,7 @@ const pluginZod = definePlugin((options) => {
213576
213684
  const { output = {
213577
213685
  path: "zod",
213578
213686
  barrelType: "named"
213579
- }, group, exclude = [], include, override = [], transformers = {}, dateType = "string", unknownType = "any", emptySchemaType = unknownType, typed = false, mapper = {}, operations = false, mini = false, version = mini ? "4" : new PackageManager().isValidSync("zod", ">=4") ? "4" : "3", guidType = "uuid", importPath = mini ? "zod/mini" : version === "4" ? "zod/v4" : "zod", coercion = false, inferred = false, generators = [zodGenerator, operations ? operationsGenerator$1 : void 0].filter(Boolean), wrapOutput = void 0, contentType } = options;
213687
+ }, group, exclude = [], include, override = [], transformers = {}, dateType = "string", unknownType = "any", emptySchemaType = unknownType, integerType = "number", typed = false, mapper = {}, operations = false, mini = false, version = mini ? "4" : new PackageManager().isValidSync("zod", ">=4") ? "4" : "3", guidType = "uuid", importPath = mini ? "zod/mini" : version === "4" ? "zod/v4" : "zod", coercion = false, inferred = false, generators = [zodGenerator, operations ? operationsGenerator$1 : void 0].filter(Boolean), wrapOutput = void 0, contentType } = options;
213580
213688
  return {
213581
213689
  name: pluginZodName,
213582
213690
  options: {
@@ -213589,6 +213697,7 @@ const pluginZod = definePlugin((options) => {
213589
213697
  dateType,
213590
213698
  unknownType,
213591
213699
  emptySchemaType,
213700
+ integerType,
213592
213701
  mapper,
213593
213702
  importPath,
213594
213703
  coercion,
@@ -215192,7 +215301,7 @@ const pluginFaker = definePlugin((options) => {
215192
215301
  const { output = {
215193
215302
  path: "mocks",
215194
215303
  barrelType: "named"
215195
- }, seed, group, exclude = [], include, override = [], transformers = {}, mapper = {}, unknownType = "any", emptySchemaType = unknownType, dateType = "string", dateParser = "faker", generators = [fakerGenerator].filter(Boolean), regexGenerator = "faker", paramsCasing, contentType } = options;
215304
+ }, seed, group, exclude = [], include, override = [], transformers = {}, mapper = {}, unknownType = "any", emptySchemaType = unknownType, dateType = "string", integerType = "number", dateParser = "faker", generators = [fakerGenerator].filter(Boolean), regexGenerator = "faker", paramsCasing, contentType } = options;
215196
215305
  return {
215197
215306
  name: pluginFakerName,
215198
215307
  options: {
@@ -215200,6 +215309,7 @@ const pluginFaker = definePlugin((options) => {
215200
215309
  transformers,
215201
215310
  seed,
215202
215311
  dateType,
215312
+ integerType,
215203
215313
  unknownType,
215204
215314
  emptySchemaType,
215205
215315
  dateParser,
@@ -217750,7 +217860,7 @@ const infiniteQueryGenerator$1 = createReactGenerator({
217750
217860
  path: zod.file.path
217751
217861
  }),
217752
217862
  options.client.importPath ? /* @__PURE__ */ jsxs(Fragment, { children: [
217753
- /* @__PURE__ */ jsx(File.Import, {
217863
+ !shouldUseClientPlugin && /* @__PURE__ */ jsx(File.Import, {
217754
217864
  name: "fetch",
217755
217865
  path: options.client.importPath
217756
217866
  }),
@@ -217769,7 +217879,7 @@ const infiniteQueryGenerator$1 = createReactGenerator({
217769
217879
  isTypeOnly: true
217770
217880
  })
217771
217881
  ] }) : /* @__PURE__ */ jsxs(Fragment, { children: [
217772
- /* @__PURE__ */ jsx(File.Import, {
217882
+ !shouldUseClientPlugin && /* @__PURE__ */ jsx(File.Import, {
217773
217883
  name: ["fetch"],
217774
217884
  root: query.file.path,
217775
217885
  path: path$2.resolve(config.root, config.output.path, ".kubb/fetch.ts")
@@ -217976,7 +218086,7 @@ const mutationGenerator$4 = createReactGenerator({
217976
218086
  path: zod.file.path
217977
218087
  }),
217978
218088
  options.client.importPath ? /* @__PURE__ */ jsxs(Fragment, { children: [
217979
- /* @__PURE__ */ jsx(File.Import, {
218089
+ !shouldUseClientPlugin && /* @__PURE__ */ jsx(File.Import, {
217980
218090
  name: "fetch",
217981
218091
  path: options.client.importPath
217982
218092
  }),
@@ -217995,7 +218105,7 @@ const mutationGenerator$4 = createReactGenerator({
217995
218105
  isTypeOnly: true
217996
218106
  })
217997
218107
  ] }) : /* @__PURE__ */ jsxs(Fragment, { children: [
217998
- /* @__PURE__ */ jsx(File.Import, {
218108
+ !shouldUseClientPlugin && /* @__PURE__ */ jsx(File.Import, {
217999
218109
  name: ["fetch"],
218000
218110
  root: mutation.file.path,
218001
218111
  path: path$2.resolve(config.root, config.output.path, ".kubb/fetch.ts")
@@ -218186,7 +218296,7 @@ const queryGenerator$4 = createReactGenerator({
218186
218296
  path: zod.file.path
218187
218297
  }),
218188
218298
  options.client.importPath ? /* @__PURE__ */ jsxs(Fragment, { children: [
218189
- /* @__PURE__ */ jsx(File.Import, {
218299
+ !shouldUseClientPlugin && /* @__PURE__ */ jsx(File.Import, {
218190
218300
  name: "fetch",
218191
218301
  path: options.client.importPath
218192
218302
  }),
@@ -218205,7 +218315,7 @@ const queryGenerator$4 = createReactGenerator({
218205
218315
  isTypeOnly: true
218206
218316
  })
218207
218317
  ] }) : /* @__PURE__ */ jsxs(Fragment, { children: [
218208
- /* @__PURE__ */ jsx(File.Import, {
218318
+ !shouldUseClientPlugin && /* @__PURE__ */ jsx(File.Import, {
218209
218319
  name: ["fetch"],
218210
218320
  root: query.file.path,
218211
218321
  path: path$2.resolve(config.root, config.output.path, ".kubb/fetch.ts")
@@ -218408,7 +218518,7 @@ const suspenseInfiniteQueryGenerator = createReactGenerator({
218408
218518
  path: zod.file.path
218409
218519
  }),
218410
218520
  options.client.importPath ? /* @__PURE__ */ jsxs(Fragment, { children: [
218411
- /* @__PURE__ */ jsx(File.Import, {
218521
+ !shouldUseClientPlugin && /* @__PURE__ */ jsx(File.Import, {
218412
218522
  name: "fetch",
218413
218523
  path: options.client.importPath
218414
218524
  }),
@@ -218427,7 +218537,7 @@ const suspenseInfiniteQueryGenerator = createReactGenerator({
218427
218537
  isTypeOnly: true
218428
218538
  })
218429
218539
  ] }) : /* @__PURE__ */ jsxs(Fragment, { children: [
218430
- /* @__PURE__ */ jsx(File.Import, {
218540
+ !shouldUseClientPlugin && /* @__PURE__ */ jsx(File.Import, {
218431
218541
  name: ["fetch"],
218432
218542
  root: query.file.path,
218433
218543
  path: path$2.resolve(config.root, config.output.path, ".kubb/fetch.ts")
@@ -218642,7 +218752,7 @@ const suspenseQueryGenerator = createReactGenerator({
218642
218752
  path: zod.file.path
218643
218753
  }),
218644
218754
  options.client.importPath ? /* @__PURE__ */ jsxs(Fragment, { children: [
218645
- /* @__PURE__ */ jsx(File.Import, {
218755
+ !shouldUseClientPlugin && /* @__PURE__ */ jsx(File.Import, {
218646
218756
  name: "fetch",
218647
218757
  path: options.client.importPath
218648
218758
  }),
@@ -218661,7 +218771,7 @@ const suspenseQueryGenerator = createReactGenerator({
218661
218771
  isTypeOnly: true
218662
218772
  })
218663
218773
  ] }) : /* @__PURE__ */ jsxs(Fragment, { children: [
218664
- /* @__PURE__ */ jsx(File.Import, {
218774
+ !shouldUseClientPlugin && /* @__PURE__ */ jsx(File.Import, {
218665
218775
  name: ["fetch"],
218666
218776
  root: query.file.path,
218667
218777
  path: path$2.resolve(config.root, config.output.path, ".kubb/fetch.ts")
@@ -219541,7 +219651,7 @@ const mutationGenerator$3 = createReactGenerator({
219541
219651
  path: zod.file.path
219542
219652
  }),
219543
219653
  options.client.importPath ? /* @__PURE__ */ jsxs(Fragment, { children: [
219544
- /* @__PURE__ */ jsx(File.Import, {
219654
+ !shouldUseClientPlugin && /* @__PURE__ */ jsx(File.Import, {
219545
219655
  name: "fetch",
219546
219656
  path: options.client.importPath
219547
219657
  }),
@@ -219560,7 +219670,7 @@ const mutationGenerator$3 = createReactGenerator({
219560
219670
  isTypeOnly: true
219561
219671
  })
219562
219672
  ] }) : /* @__PURE__ */ jsxs(Fragment, { children: [
219563
- /* @__PURE__ */ jsx(File.Import, {
219673
+ !shouldUseClientPlugin && /* @__PURE__ */ jsx(File.Import, {
219564
219674
  name: ["fetch"],
219565
219675
  root: mutation.file.path,
219566
219676
  path: path$2.resolve(config.root, config.output.path, ".kubb/fetch.ts")
@@ -219734,7 +219844,7 @@ const queryGenerator$3 = createReactGenerator({
219734
219844
  path: zod.file.path
219735
219845
  }),
219736
219846
  options.client.importPath ? /* @__PURE__ */ jsxs(Fragment, { children: [
219737
- /* @__PURE__ */ jsx(File.Import, {
219847
+ !shouldUseClientPlugin && /* @__PURE__ */ jsx(File.Import, {
219738
219848
  name: "fetch",
219739
219849
  path: options.client.importPath
219740
219850
  }),
@@ -219753,7 +219863,7 @@ const queryGenerator$3 = createReactGenerator({
219753
219863
  isTypeOnly: true
219754
219864
  })
219755
219865
  ] }) : /* @__PURE__ */ jsxs(Fragment, { children: [
219756
- /* @__PURE__ */ jsx(File.Import, {
219866
+ !shouldUseClientPlugin && /* @__PURE__ */ jsx(File.Import, {
219757
219867
  name: ["fetch"],
219758
219868
  root: query.file.path,
219759
219869
  path: path$2.resolve(config.root, config.output.path, ".kubb/fetch.ts")
@@ -220555,7 +220665,7 @@ const mutationGenerator$2 = createReactGenerator({
220555
220665
  path: zod.file.path
220556
220666
  }),
220557
220667
  options.client.importPath ? /* @__PURE__ */ jsxs(Fragment, { children: [
220558
- /* @__PURE__ */ jsx(File.Import, {
220668
+ !shouldUseClientPlugin && /* @__PURE__ */ jsx(File.Import, {
220559
220669
  name: "fetch",
220560
220670
  path: options.client.importPath
220561
220671
  }),
@@ -220574,7 +220684,7 @@ const mutationGenerator$2 = createReactGenerator({
220574
220684
  isTypeOnly: true
220575
220685
  })
220576
220686
  ] }) : /* @__PURE__ */ jsxs(Fragment, { children: [
220577
- /* @__PURE__ */ jsx(File.Import, {
220687
+ !shouldUseClientPlugin && /* @__PURE__ */ jsx(File.Import, {
220578
220688
  name: ["fetch"],
220579
220689
  root: mutation.file.path,
220580
220690
  path: path$2.resolve(config.root, config.output.path, ".kubb/fetch.ts")
@@ -220747,7 +220857,7 @@ const queryGenerator$2 = createReactGenerator({
220747
220857
  path: zod.file.path
220748
220858
  }),
220749
220859
  options.client.importPath ? /* @__PURE__ */ jsxs(Fragment, { children: [
220750
- /* @__PURE__ */ jsx(File.Import, {
220860
+ !shouldUseClientPlugin && /* @__PURE__ */ jsx(File.Import, {
220751
220861
  name: "fetch",
220752
220862
  path: options.client.importPath
220753
220863
  }),
@@ -220766,7 +220876,7 @@ const queryGenerator$2 = createReactGenerator({
220766
220876
  isTypeOnly: true
220767
220877
  })
220768
220878
  ] }) : /* @__PURE__ */ jsxs(Fragment, { children: [
220769
- /* @__PURE__ */ jsx(File.Import, {
220879
+ !shouldUseClientPlugin && /* @__PURE__ */ jsx(File.Import, {
220770
220880
  name: ["fetch"],
220771
220881
  root: query.file.path,
220772
220882
  path: path$2.resolve(config.root, config.output.path, ".kubb/fetch.ts")
@@ -221606,7 +221716,7 @@ const mutationGenerator$1 = createReactGenerator({
221606
221716
  path: zod.file.path
221607
221717
  }),
221608
221718
  options.client.importPath ? /* @__PURE__ */ jsxs(Fragment, { children: [
221609
- /* @__PURE__ */ jsx(File.Import, {
221719
+ !shouldUseClientPlugin && /* @__PURE__ */ jsx(File.Import, {
221610
221720
  name: "fetch",
221611
221721
  path: options.client.importPath
221612
221722
  }),
@@ -221625,7 +221735,7 @@ const mutationGenerator$1 = createReactGenerator({
221625
221735
  isTypeOnly: true
221626
221736
  })
221627
221737
  ] }) : /* @__PURE__ */ jsxs(Fragment, { children: [
221628
- /* @__PURE__ */ jsx(File.Import, {
221738
+ !shouldUseClientPlugin && /* @__PURE__ */ jsx(File.Import, {
221629
221739
  name: ["fetch"],
221630
221740
  root: mutation.file.path,
221631
221741
  path: path$2.resolve(config.root, config.output.path, ".kubb/fetch.ts")
@@ -221794,7 +221904,7 @@ const queryGenerator$1 = createReactGenerator({
221794
221904
  path: zod.file.path
221795
221905
  }),
221796
221906
  options.client.importPath ? /* @__PURE__ */ jsxs(Fragment, { children: [
221797
- /* @__PURE__ */ jsx(File.Import, {
221907
+ !shouldUseClientPlugin && /* @__PURE__ */ jsx(File.Import, {
221798
221908
  name: "fetch",
221799
221909
  path: options.client.importPath
221800
221910
  }),
@@ -221813,7 +221923,7 @@ const queryGenerator$1 = createReactGenerator({
221813
221923
  isTypeOnly: true
221814
221924
  })
221815
221925
  ] }) : /* @__PURE__ */ jsxs(Fragment, { children: [
221816
- /* @__PURE__ */ jsx(File.Import, {
221926
+ !shouldUseClientPlugin && /* @__PURE__ */ jsx(File.Import, {
221817
221927
  name: ["fetch"],
221818
221928
  root: query.file.path,
221819
221929
  path: path$2.resolve(config.root, config.output.path, ".kubb/fetch.ts")
@@ -222968,7 +223078,7 @@ const infiniteQueryGenerator = createReactGenerator({
222968
223078
  path: zod.file.path
222969
223079
  }),
222970
223080
  options.client.importPath ? /* @__PURE__ */ jsxs(Fragment, { children: [
222971
- /* @__PURE__ */ jsx(File.Import, {
223081
+ !shouldUseClientPlugin && /* @__PURE__ */ jsx(File.Import, {
222972
223082
  name: "fetch",
222973
223083
  path: options.client.importPath
222974
223084
  }),
@@ -222987,7 +223097,7 @@ const infiniteQueryGenerator = createReactGenerator({
222987
223097
  isTypeOnly: true
222988
223098
  })
222989
223099
  ] }) : /* @__PURE__ */ jsxs(Fragment, { children: [
222990
- /* @__PURE__ */ jsx(File.Import, {
223100
+ !shouldUseClientPlugin && /* @__PURE__ */ jsx(File.Import, {
222991
223101
  name: ["fetch"],
222992
223102
  root: query.file.path,
222993
223103
  path: path$2.resolve(config.root, config.output.path, ".kubb/fetch.ts")
@@ -223192,7 +223302,7 @@ const mutationGenerator = createReactGenerator({
223192
223302
  path: zod.file.path
223193
223303
  }),
223194
223304
  options.client.importPath ? /* @__PURE__ */ jsxs(Fragment, { children: [
223195
- /* @__PURE__ */ jsx(File.Import, {
223305
+ !shouldUseClientPlugin && /* @__PURE__ */ jsx(File.Import, {
223196
223306
  name: "fetch",
223197
223307
  path: options.client.importPath
223198
223308
  }),
@@ -223211,7 +223321,7 @@ const mutationGenerator = createReactGenerator({
223211
223321
  isTypeOnly: true
223212
223322
  })
223213
223323
  ] }) : /* @__PURE__ */ jsxs(Fragment, { children: [
223214
- /* @__PURE__ */ jsx(File.Import, {
223324
+ !shouldUseClientPlugin && /* @__PURE__ */ jsx(File.Import, {
223215
223325
  name: ["fetch"],
223216
223326
  root: mutation.file.path,
223217
223327
  path: path$2.resolve(config.root, config.output.path, ".kubb/fetch.ts")
@@ -223385,7 +223495,7 @@ const queryGenerator = createReactGenerator({
223385
223495
  path: zod.file.path
223386
223496
  }),
223387
223497
  options.client.importPath ? /* @__PURE__ */ jsxs(Fragment, { children: [
223388
- /* @__PURE__ */ jsx(File.Import, {
223498
+ !shouldUseClientPlugin && /* @__PURE__ */ jsx(File.Import, {
223389
223499
  name: "fetch",
223390
223500
  path: options.client.importPath
223391
223501
  }),
@@ -223404,7 +223514,7 @@ const queryGenerator = createReactGenerator({
223404
223514
  isTypeOnly: true
223405
223515
  })
223406
223516
  ] }) : /* @__PURE__ */ jsxs(Fragment, { children: [
223407
- /* @__PURE__ */ jsx(File.Import, {
223517
+ !shouldUseClientPlugin && /* @__PURE__ */ jsx(File.Import, {
223408
223518
  name: ["fetch"],
223409
223519
  root: query.file.path,
223410
223520
  path: path$2.resolve(config.root, config.output.path, ".kubb/fetch.ts")
@@ -223693,20 +223803,41 @@ function resolvePlugins(plugins) {
223693
223803
  });
223694
223804
  }
223695
223805
 
223696
- function readStudioConfig(configPath) {
223697
- const studioConfigPath = path$2.join(path$2.dirname(configPath), "kubb.config.studio.json");
223698
- if (!existsSync(studioConfigPath)) {
223699
- return null;
223700
- }
223701
- try {
223702
- return JSON.parse(readFileSync(studioConfigPath, "utf-8"));
223703
- } catch {
223704
- return null;
223705
- }
223806
+ function mergePlugins(diskPlugins, studioPlugins) {
223807
+ if (!diskPlugins && !studioPlugins) return void 0;
223808
+ if (!studioPlugins) return diskPlugins;
223809
+ const resolvedStudio = resolvePlugins(studioPlugins);
223810
+ if (!diskPlugins) return resolvedStudio;
223811
+ const studioByName = new Map(resolvedStudio.map((p) => [p.name, p]));
223812
+ const diskNames = new Set(diskPlugins.map((p) => p.name));
223813
+ const mergedDisk = diskPlugins.map((diskPlugin) => {
223814
+ const studioPlugin = studioByName.get(diskPlugin.name);
223815
+ if (!studioPlugin) return diskPlugin;
223816
+ return { ...diskPlugin, options: mergeDeep(diskPlugin.options, studioPlugin.options) };
223817
+ });
223818
+ const studioOnly = resolvedStudio.filter((p) => !diskNames.has(p.name));
223819
+ return [...mergedDisk, ...studioOnly];
223706
223820
  }
223707
- function writeStudioConfig(configPath, config) {
223708
- const studioConfigPath = path$2.join(path$2.dirname(configPath), "kubb.config.studio.json");
223709
- writeFileSync(studioConfigPath, JSON.stringify(config, null, 2), "utf-8");
223821
+
223822
+ function setupHookListener(events, root) {
223823
+ events.on("hook:start", async ({ id, command, args }) => {
223824
+ if (!id) {
223825
+ return;
223826
+ }
223827
+ const commandWithArgs = (args == null ? void 0 : args.length) ? `${command} ${args.join(" ")}` : command;
223828
+ try {
223829
+ const result = await x(command, [...args != null ? args : []], {
223830
+ nodeOptions: { cwd: root, detached: true },
223831
+ throwOnError: true
223832
+ });
223833
+ console.log(result.stdout.trimEnd());
223834
+ await events.emit("hook:end", { command, args, id, success: true, error: null });
223835
+ } catch (_err) {
223836
+ const errorMessage = new Error(`Hook execute failed: ${commandWithArgs}`);
223837
+ await events.emit("hook:end", { command, args, id, success: false, error: errorMessage });
223838
+ await events.emit("error", errorMessage);
223839
+ }
223840
+ });
223710
223841
  }
223711
223842
 
223712
223843
  const WEBSOCKET_READY = 1;
@@ -223838,7 +223969,165 @@ function setupEventsStream(ws, events) {
223838
223969
  });
223839
223970
  }
223840
223971
 
223841
- var version = "4.29.0";
223972
+ async function connectToStudio(options) {
223973
+ var _a;
223974
+ const {
223975
+ token,
223976
+ studioUrl,
223977
+ configPath,
223978
+ resolvedConfigPath,
223979
+ noCache,
223980
+ allowAll,
223981
+ allowWrite,
223982
+ root,
223983
+ retryInterval,
223984
+ heartbeatInterval = 3e4,
223985
+ initialSession,
223986
+ sessionKey,
223987
+ nitro
223988
+ } = options;
223989
+ const events = new AsyncEventEmitter();
223990
+ const maskedSessionKey = maskedString(sessionKey.replace("sessions:", ""));
223991
+ async function removeSession() {
223992
+ if (!noCache) {
223993
+ await removeCachedSession(sessionKey);
223994
+ }
223995
+ }
223996
+ async function reconnect() {
223997
+ logger.info(`[${maskedSessionKey}] Retrying connection in ${formatMs(retryInterval)} to Kubb Studio ...`);
223998
+ await removeSession();
223999
+ setTimeout(() => connectToStudio({ ...options, initialSession: void 0 }), retryInterval);
224000
+ }
224001
+ try {
224002
+ setupHookListener(events, root);
224003
+ const { sessionId, wsUrl, isSandbox } = initialSession != null ? initialSession : await createAgentSession({ noCache, token, studioUrl, cacheKey: sessionKey });
224004
+ const ws = createWebsocket(wsUrl, { headers: { Authorization: `Bearer ${token}` } });
224005
+ const maskedWsUrl = maskedString(wsUrl);
224006
+ const effectiveAllowAll = isSandbox ? false : allowAll;
224007
+ const effectiveWrite = isSandbox ? false : allowWrite;
224008
+ let serverDisconnected = false;
224009
+ let heartbeatTimer;
224010
+ async function cleanup(reason = "cleanup") {
224011
+ try {
224012
+ clearInterval(heartbeatTimer);
224013
+ heartbeatTimer = void 0;
224014
+ events.removeAll();
224015
+ ws.close(1e3, reason);
224016
+ ws.removeEventListener("open", onOpen);
224017
+ ws.removeEventListener("close", onClose);
224018
+ ws.removeEventListener("error", onError);
224019
+ } catch (_error) {
224020
+ }
224021
+ }
224022
+ const onOpen = () => {
224023
+ logger.success(`[${maskedSessionKey}] Connected to Kubb Studio on "${maskedWsUrl}"`);
224024
+ };
224025
+ const onClose = async () => {
224026
+ if (serverDisconnected) {
224027
+ return;
224028
+ }
224029
+ serverDisconnected = true;
224030
+ await cleanup();
224031
+ await disconnect({ sessionId, studioUrl, token }).catch(() => {
224032
+ });
224033
+ await reconnect();
224034
+ };
224035
+ const onError = async () => {
224036
+ logger.error(`[${maskedSessionKey}] Failed to connect to Kubb Studio on "${maskedWsUrl}"`);
224037
+ await cleanup();
224038
+ await reconnect();
224039
+ };
224040
+ ws.addEventListener("open", onOpen);
224041
+ ws.addEventListener("close", onClose);
224042
+ ws.addEventListener("error", onError);
224043
+ nitro.hooks.hook("close", async () => {
224044
+ await cleanup();
224045
+ await disconnect({ sessionId, studioUrl, token }).catch(() => {
224046
+ });
224047
+ });
224048
+ heartbeatTimer = setInterval(() => sendAgentMessage(ws, { type: "ping" }), heartbeatInterval);
224049
+ setupEventsStream(ws, events);
224050
+ ws.addEventListener("message", async (message) => {
224051
+ var _a2, _b, _c;
224052
+ try {
224053
+ const data = JSON.parse(message.data);
224054
+ logger.info(`[${maskedSessionKey}] Received "${data.type}" from Studio`);
224055
+ if (isPongMessage(data)) {
224056
+ return;
224057
+ }
224058
+ if (isDisconnectMessage(data)) {
224059
+ logger.warn(`[${maskedSessionKey}] Agent session disconnected by Studio with reason: ${data.reason}`);
224060
+ if (data.reason === "revoked") {
224061
+ await cleanup(`session_${data.reason}`);
224062
+ await removeSession();
224063
+ return;
224064
+ }
224065
+ if (data.reason === "expired") {
224066
+ await cleanup();
224067
+ await reconnect();
224068
+ return;
224069
+ }
224070
+ return;
224071
+ }
224072
+ if (isCommandMessage(data)) {
224073
+ if (data.command === "generate") {
224074
+ const config = await loadConfig(resolvedConfigPath);
224075
+ const patch = data.payload;
224076
+ const plugins = mergePlugins(config.plugins, patch == null ? void 0 : patch.plugins);
224077
+ const inputOverride = isSandbox ? { data: (_a2 = patch == null ? void 0 : patch.input) != null ? _a2 : "" } : void 0;
224078
+ if (allowWrite && isSandbox) {
224079
+ logger.warn(`[${maskedSessionKey}] Agent is running in a sandbox environment, write will be disabled`);
224080
+ }
224081
+ if ((patch == null ? void 0 : patch.input) && !isSandbox) {
224082
+ logger.warn(`[${maskedSessionKey}] Input override via payload is only supported in sandbox mode and will be ignored`);
224083
+ }
224084
+ if (data.payload && effectiveWrite) {
224085
+ await saveStudioConfigToStorage({ sessionKey, config: data.payload }).catch((err) => {
224086
+ logger.warn(`[${maskedSessionKey}] Failed to save studio config: ${err == null ? void 0 : err.message}`);
224087
+ });
224088
+ }
224089
+ await generate({
224090
+ config: {
224091
+ ...config,
224092
+ root,
224093
+ input: inputOverride != null ? inputOverride : config.input,
224094
+ output: { ...config.output, write: effectiveWrite },
224095
+ plugins
224096
+ },
224097
+ events
224098
+ });
224099
+ logger.success(`[${maskedSessionKey}] Completed "${data.type}" from Studio`);
224100
+ return;
224101
+ }
224102
+ if (data.command === "connect") {
224103
+ const config = await loadConfig(resolvedConfigPath);
224104
+ sendAgentMessage(ws, {
224105
+ type: "connected",
224106
+ payload: {
224107
+ version,
224108
+ configPath,
224109
+ permissions: { allowAll: effectiveAllowAll, allowWrite: effectiveWrite },
224110
+ config: {
224111
+ plugins: (_b = config.plugins) == null ? void 0 : _b.map((plugin) => ({
224112
+ name: `@kubb/${plugin.name}`,
224113
+ options: serializePluginOptions(plugin.options)
224114
+ }))
224115
+ }
224116
+ }
224117
+ });
224118
+ logger.success(`[${maskedSessionKey}] Completed "${data.type}" from Studio`);
224119
+ return;
224120
+ }
224121
+ }
224122
+ logger.warn(`[${maskedSessionKey}] Unknown message type from Kubb Studio: ${message.data}`);
224123
+ } catch (error) {
224124
+ logger.error(`[${maskedSessionKey}] [unhandledRejection] ${(_c = error == null ? void 0 : error.message) != null ? _c : error}`);
224125
+ }
224126
+ });
224127
+ } catch (error) {
224128
+ throw new Error(`[unhandledRejection] ${(_a = error == null ? void 0 : error.message) != null ? _a : error}`, { cause: error });
224129
+ }
224130
+ }
223842
224131
 
223843
224132
  const _zcw7I4pYH8OiCfaDcjy_x7I6IH1tLDQR3W_yRZgP6E = defineNitroPlugin(async (nitro) => {
223844
224133
  const studioUrl = process$1.env.KUBB_STUDIO_URL || "https://studio.kubb.dev";
@@ -223846,195 +224135,70 @@ const _zcw7I4pYH8OiCfaDcjy_x7I6IH1tLDQR3W_yRZgP6E = defineNitroPlugin(async (nit
223846
224135
  const configPath = process$1.env.KUBB_AGENT_CONFIG || "kubb.config.ts";
223847
224136
  const noCache = process$1.env.KUBB_AGENT_NO_CACHE === "true";
223848
224137
  const retryInterval = process$1.env.KUBB_AGENT_RETRY_TIMEOUT ? Number.parseInt(process$1.env.KUBB_AGENT_RETRY_TIMEOUT, 10) : 3e4;
224138
+ const heartbeatInterval = process$1.env.KUBB_AGENT_HEARTBEAT_INTERVAL ? Number.parseInt(process$1.env.KUBB_AGENT_HEARTBEAT_INTERVAL, 10) : 3e4;
223849
224139
  const root = process$1.env.KUBB_AGENT_ROOT || process$1.cwd();
223850
224140
  const allowAll = process$1.env.KUBB_AGENT_ALLOW_ALL === "true";
223851
224141
  const allowWrite = allowAll || process$1.env.KUBB_AGENT_ALLOW_WRITE === "true";
224142
+ const poolSize = process$1.env.KUBB_AGENT_POOL_SIZE ? Number.parseInt(process$1.env.KUBB_AGENT_POOL_SIZE, 10) : 1;
223852
224143
  if (!token) {
223853
224144
  logger.warn("KUBB_AGENT_TOKEN not set", "cannot authenticate with studio");
223854
224145
  return null;
223855
224146
  }
224147
+ if (!process$1.env.KUBB_AGENT_SECRET) {
224148
+ logger.warn("KUBB_AGENT_SECRET not set", "secret should be set");
224149
+ }
223856
224150
  const resolvedConfigPath = path$2.isAbsolute(configPath) ? configPath : path$2.resolve(root, configPath);
223857
- const events = new AsyncEventEmitter();
223858
224151
  const storage = useStorage("kubb");
223859
- async function loadConfig() {
223860
- const result = await getCosmiConfig(resolvedConfigPath);
223861
- const configs = await getConfigs(result.config, {});
223862
- if (configs.length === 0) {
223863
- throw new Error("No configs found");
223864
- }
223865
- return configs[0];
223866
- }
223867
- const wsOptions = {
223868
- headers: {
223869
- Authorization: `Bearer ${token}`
223870
- }
223871
- };
223872
- events.on("hook:start", async ({ id, command, args }) => {
223873
- const commandWithArgs = (args == null ? void 0 : args.length) ? `${command} ${args.join(" ")}` : command;
223874
- if (!id) {
223875
- return;
223876
- }
223877
- try {
223878
- const result = await x(command, [...args != null ? args : []], {
223879
- nodeOptions: { cwd: root, detached: true },
223880
- throwOnError: true
223881
- });
223882
- console.log(result.stdout.trimEnd());
223883
- await events.emit("hook:end", {
223884
- command,
223885
- args,
223886
- id,
223887
- success: true,
223888
- error: null
223889
- });
223890
- } catch (_err) {
223891
- const errorMessage = new Error(`Hook execute failed: ${commandWithArgs}`);
223892
- await events.emit("hook:end", {
223893
- command,
223894
- args,
223895
- id,
223896
- success: false,
223897
- error: errorMessage
224152
+ const sessionKey = getSessionKey(token);
224153
+ const maskedSessionKey = maskedString(sessionKey.replace("sessions:", ""));
224154
+ try {
224155
+ await registerAgent({ token, studioUrl, poolSize });
224156
+ const baseOptions = {
224157
+ token,
224158
+ studioUrl,
224159
+ configPath,
224160
+ resolvedConfigPath,
224161
+ noCache,
224162
+ allowAll,
224163
+ allowWrite,
224164
+ root,
224165
+ retryInterval,
224166
+ heartbeatInterval,
224167
+ storage,
224168
+ sessionKey,
224169
+ nitro
224170
+ };
224171
+ logger.info(`[${maskedSessionKey}] Starting session pool of ${poolSize} connection(s)`);
224172
+ const sessions = /* @__PURE__ */ new Map();
224173
+ for (const index2 of Array.from({ length: poolSize }, (_, i) => i)) {
224174
+ const cacheKey = `${sessionKey}-${index2}`;
224175
+ const maskedSessionKey2 = maskedString(cacheKey);
224176
+ const session = await createAgentSession({ noCache, token, studioUrl, cacheKey }).catch((err) => {
224177
+ logger.warn(`[${maskedSessionKey2}] Failed to pre-create pool session:`, err == null ? void 0 : err.message);
224178
+ return null;
223898
224179
  });
223899
- await events.emit("error", errorMessage);
224180
+ sessions.set(cacheKey, session);
223900
224181
  }
223901
- });
223902
- async function reconnectToStudio() {
223903
- logger.info(`Retrying connection in ${formatMs(retryInterval)} to Kubb Studio ...`);
223904
- setTimeout(async () => {
223905
- await connectToStudio();
223906
- }, retryInterval);
223907
- }
223908
- async function connectToStudio() {
223909
- try {
223910
- const { sessionToken, wsUrl, isSandbox } = await createAgentSession({
223911
- noCache,
223912
- token,
223913
- studioUrl
223914
- });
223915
- const ws = createWebsocket(wsUrl, wsOptions);
223916
- const onError = async () => {
223917
- cleanup();
223918
- logger.error(`Failed to connect to Kubb Studio on "${wsUrl}"`);
223919
- if (!noCache) {
223920
- const sessionKey = getSessionKey(token);
223921
- const stored = await storage.getItem(sessionKey);
223922
- if (stored && isSessionValid(stored)) {
223923
- await storage.removeItem(sessionKey);
223924
- await reconnectToStudio();
223925
- }
223926
- }
223927
- };
223928
- const onOpen = () => {
223929
- logger.success(`Connected to Kubb Studio on "${wsUrl}"`);
223930
- };
223931
- const onClose = async () => {
223932
- cleanup();
223933
- logger.info("Disconnecting from Studio ...");
223934
- if (sessionToken) {
223935
- await disconnect({
223936
- sessionToken,
223937
- studioUrl,
223938
- token
223939
- }).catch(async () => {
223940
- await storage.removeItem(getSessionKey(token));
223941
- await reconnectToStudio();
223942
- });
223943
- }
223944
- };
223945
- const cleanup = () => {
223946
- ws.removeEventListener("open", onOpen);
223947
- ws.removeEventListener("close", onClose);
223948
- ws.removeEventListener("error", onError);
223949
- };
223950
- ws.addEventListener("open", onOpen);
223951
- ws.addEventListener("close", onClose);
223952
- ws.addEventListener("error", onError);
223953
- nitro.hooks.hook("close", onClose);
223954
- setInterval(() => {
223955
- sendAgentMessage(ws, {
223956
- type: "ping"
223957
- });
223958
- }, 3e4);
223959
- setupEventsStream(ws, events);
223960
- ws.addEventListener("message", async (message) => {
223961
- var _a, _b, _c, _d;
223962
- try {
223963
- const data = JSON.parse(message.data);
223964
- if (isPongMessage(data)) {
223965
- logger.info("Received pong from Studio");
223966
- return;
223967
- }
223968
- if (isCommandMessage(data)) {
223969
- if (data.command === "generate") {
223970
- const config = await loadConfig();
223971
- const studioConfig = readStudioConfig(resolvedConfigPath);
223972
- const patch = (_a = data.payload) != null ? _a : studioConfig;
223973
- const resolvedPlugins = (patch == null ? void 0 : patch.plugins) ? resolvePlugins(patch.plugins) : void 0;
223974
- if (allowWrite && isSandbox) {
223975
- logger.warn("Agent is running in a sandbox environment, write will be disabled");
223976
- }
223977
- if ((patch == null ? void 0 : patch.input) && !isSandbox) {
223978
- logger.warn("Input override via payload is only supported in sandbox mode and will be ignored");
223979
- }
223980
- const inputOverride = isSandbox ? { data: (_b = patch.input) != null ? _b : "" } : void 0;
223981
- await generate({
223982
- config: {
223983
- ...config,
223984
- input: inputOverride != null ? inputOverride : config.input,
223985
- plugins: resolvedPlugins != null ? resolvedPlugins : config.plugins,
223986
- root,
223987
- output: {
223988
- ...config.output,
223989
- write: isSandbox ? false : allowWrite
223990
- }
223991
- },
223992
- events
223993
- });
223994
- if (allowWrite) {
223995
- writeStudioConfig(resolvedConfigPath, data.payload);
223996
- }
223997
- logger.success("Generated command success");
223998
- }
223999
- if (data.command === "connect") {
224000
- const config = await loadConfig();
224001
- sendAgentMessage(ws, {
224002
- type: "connected",
224003
- payload: {
224004
- version,
224005
- configPath,
224006
- permissions: {
224007
- allowAll: isSandbox ? false : allowWrite,
224008
- allowWrite: isSandbox ? false : allowWrite
224009
- },
224010
- config: {
224011
- plugins: (_c = config.plugins) == null ? void 0 : _c.map((plugin) => ({
224012
- name: `@kubb/${plugin.name}`,
224013
- options: serializePluginOptions(plugin.options)
224014
- }))
224015
- }
224016
- }
224017
- });
224018
- }
224019
- return;
224020
- }
224021
- logger.warn(`Unknown message type from Kubb Studio: ${message.data}`);
224022
- } catch (error) {
224023
- logger.error(`[unhandledRejection] ${(_d = error == null ? void 0 : error.message) != null ? _d : error}`);
224024
- }
224182
+ let index = 0;
224183
+ for (const [cacheKey, session] of sessions) {
224184
+ index++;
224185
+ if (!session) {
224186
+ continue;
224187
+ }
224188
+ const maskedSessionKey2 = maskedString(session.sessionId);
224189
+ logger.info(`[${maskedSessionKey2}] Connecting session ${index}/${sessions.size}`);
224190
+ await connectToStudio({ ...baseOptions, initialSession: session, sessionKey: cacheKey }).catch((err) => {
224191
+ logger.warn(`[${maskedSessionKey2}] Session ${index} failed to connect:`, err == null ? void 0 : err.message);
224025
224192
  });
224026
- } catch (error) {
224027
- await storage.removeItem(getSessionKey(token));
224028
- logger.error(`Something went wrong ${error}`);
224029
- await reconnectToStudio();
224030
224193
  }
224194
+ } catch (error) {
224195
+ logger.error("Failed to connect to Kubb Studio\n", error == null ? void 0 : error.message);
224031
224196
  }
224032
- await registerAgent({ token, studioUrl });
224033
- await connectToStudio();
224034
224197
  });
224035
224198
 
224036
224199
  const plugins = [
224037
224200
  _KZ9YuROWp70nNn4X1C4BxF_W0D7H9EWgBo03XvMd7w0,
224201
+ _a2VEEUGb5K4b1gyM9hOmO1Xz0hUJSFuGyIT3cHsvE,
224038
224202
  _zcw7I4pYH8OiCfaDcjy_x7I6IH1tLDQR3W_yRZgP6E
224039
224203
  ];
224040
224204