@kubb/agent 4.24.1 → 4.25.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (24) hide show
  1. package/.output/nitro.json +1 -1
  2. package/.output/server/chunks/nitro/nitro.mjs +710 -381
  3. package/.output/server/chunks/nitro/nitro.mjs.map +1 -1
  4. package/.output/server/chunks/routes/api/health.get.mjs +8 -10
  5. package/.output/server/chunks/routes/api/health.get.mjs.map +1 -1
  6. package/.output/server/index.mjs +5 -5
  7. package/.output/server/node_modules/.nitro/jiti@2.5.1/dist/babel.cjs +246 -0
  8. package/.output/server/node_modules/.nitro/jiti@2.5.1/dist/jiti.cjs +1 -0
  9. package/.output/server/node_modules/.nitro/jiti@2.5.1/lib/jiti.mjs +22 -0
  10. package/.output/server/node_modules/.nitro/jiti@2.5.1/package.json +134 -0
  11. package/.output/server/package.json +2 -2
  12. package/README.md +113 -19
  13. package/package.json +5 -3
  14. package/.output/server/chunks/_/package.mjs +0 -4
  15. package/.output/server/chunks/_/package.mjs.map +0 -1
  16. package/.output/server/chunks/routes/api/generate.options.mjs +0 -31
  17. package/.output/server/chunks/routes/api/generate.options.mjs.map +0 -1
  18. package/.output/server/chunks/routes/api/generate.post.mjs +0 -120
  19. package/.output/server/chunks/routes/api/generate.post.mjs.map +0 -1
  20. package/.output/server/chunks/routes/api/info.get.mjs +0 -63
  21. package/.output/server/chunks/routes/api/info.get.mjs.map +0 -1
  22. /package/.output/server/node_modules/{jiti → .nitro/jiti@2.6.1}/dist/jiti.cjs +0 -0
  23. /package/.output/server/node_modules/{jiti → .nitro/jiti@2.6.1}/lib/jiti.mjs +0 -0
  24. /package/.output/server/node_modules/{jiti → .nitro/jiti@2.6.1}/package.json +0 -0
@@ -1,10 +1,15 @@
1
- import http, { Server as Server$1 } from 'node:http';
1
+ import process from 'node:process';globalThis._importMeta_=globalThis._importMeta_||{url:"file:///_entry.js",env:process.env};import http, { Server as Server$1 } from 'node:http';
2
2
  import https, { Server } from 'node:https';
3
3
  import { EventEmitter } from 'node:events';
4
4
  import { Buffer as Buffer$1 } from 'node:buffer';
5
- import fs$1, { promises, existsSync } from 'node:fs';
5
+ import fs$1, { promises, existsSync, readFileSync, writeFileSync } from 'node:fs';
6
6
  import path$1, { resolve, dirname, join, relative, normalize } from 'node:path';
7
7
  import { createHash } from 'node:crypto';
8
+ import process$1, { version as version$2 } from 'node:process';
9
+ import { orderBy } from 'natural-orderby';
10
+ import { execaCommand, execa } from 'execa';
11
+ import pc from 'picocolors';
12
+ import os from 'node:os';
8
13
  import { performance } from 'node:perf_hooks';
9
14
  import fs from 'fs-extra';
10
15
  import { switcher } from 'js-runtime';
@@ -12,15 +17,10 @@ import mod from 'node:module';
12
17
  import { createFabric } from '@kubb/react-fabric';
13
18
  import { typescriptParser } from '@kubb/react-fabric/parsers';
14
19
  import { fsPlugin } from '@kubb/react-fabric/plugins';
15
- import process$1, { version } from 'node:process';
16
- import os from 'node:os';
17
20
  import { pathToFileURL, fileURLToPath } from 'node:url';
18
21
  import { coerce, satisfies } from 'semver';
19
- import { orderBy } from 'natural-orderby';
20
- import { execaCommand } from 'execa';
21
22
  import { parseArgsStringToArgv } from 'string-argv';
22
23
  import { createJiti } from 'jiti';
23
- import { AsyncLocalStorage } from 'node:async_hooks';
24
24
 
25
25
  const suspectProtoRx = /"(?:_|\\u0{2}5[Ff]){2}(?:p|\\u0{2}70)(?:r|\\u0{2}72)(?:o|\\u0{2}6[Ff])(?:t|\\u0{2}74)(?:o|\\u0{2}6[Ff])(?:_|\\u0{2}5[Ff]){2}"\s*:/;
26
26
  const suspectConstructorRx = /"(?:c|\\u0063)(?:o|\\u006[Ff])(?:n|\\u006[Ee])(?:s|\\u0073)(?:t|\\u0074)(?:r|\\u0072)(?:u|\\u0075)(?:c|\\u0063)(?:t|\\u0074)(?:o|\\u006[Ff])(?:r|\\u0072)"\s*:/;
@@ -4251,9 +4251,9 @@ async function errorHandler(error, event) {
4251
4251
  // H3 will handle fallback
4252
4252
  }
4253
4253
 
4254
- const plugins = [
4255
-
4256
- ];
4254
+ function defineNitroPlugin(def) {
4255
+ return def;
4256
+ }
4257
4257
 
4258
4258
  var __defProp$1 = Object.defineProperty;
4259
4259
  var __name = (target, value) => __defProp$1(target, "name", {
@@ -5281,16 +5281,382 @@ var __typeError$1 = (msg) => {
5281
5281
  var __accessCheck$1 = (obj, member, msg) => member.has(obj) || __typeError$1("Cannot " + msg);
5282
5282
  var __privateGet$1 = (obj, member, getter) => (__accessCheck$1(obj, member, "read from private field"), getter ? getter.call(obj) : member.get(obj));
5283
5283
  var __privateAdd$1 = (obj, member, value) => member.has(obj) ? __typeError$1("Cannot add the same private member more than once") : member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
5284
- var __privateSet = (obj, member, value, setter) => (__accessCheck$1(obj, member, "write to private field"), member.set(obj, value), value);
5285
5284
  var __privateMethod$1 = (obj, member, method) => (__accessCheck$1(obj, member, "access private method"), method);
5286
- var _b$1, _cache, _cwd, _SLASHES, _PackageManager_instances, match_fn;
5285
+ var _items, _FunctionParams_static, _b$1, orderItems_fn, addParams_fn;
5286
+ (_b$1 = class {
5287
+ constructor() {
5288
+ __privateAdd$1(this, _items, []);
5289
+ return this;
5290
+ }
5291
+ get items() {
5292
+ return __privateGet$1(this, _items).flat();
5293
+ }
5294
+ add(item) {
5295
+ if (!item) return this;
5296
+ if (Array.isArray(item)) {
5297
+ item.filter(Boolean).forEach((it) => {
5298
+ __privateGet$1(this, _items).push(it);
5299
+ });
5300
+ return this;
5301
+ }
5302
+ __privateGet$1(this, _items).push(item);
5303
+ return this;
5304
+ }
5305
+ static toObject(items) {
5306
+ var _a2, _b2;
5307
+ let type = [];
5308
+ let name = [];
5309
+ const enabled = items.every((item) => item.enabled) ? (_a2 = items.at(0)) == null ? void 0 : _a2.enabled : true;
5310
+ const required = (_b2 = items.every((item) => item.required)) != null ? _b2 : true;
5311
+ items.forEach((item) => {
5312
+ var _a3, _b3;
5313
+ name = __privateMethod$1(_a3 = _b$1, _FunctionParams_static, addParams_fn).call(_a3, name, {
5314
+ ...item,
5315
+ type: void 0
5316
+ });
5317
+ if (items.some((item$1) => item$1.type)) type = __privateMethod$1(_b3 = _b$1, _FunctionParams_static, addParams_fn).call(_b3, type, item);
5318
+ });
5319
+ return {
5320
+ name: `{ ${name.join(", ")} }`,
5321
+ type: type.length ? `{ ${type.join("; ")} }` : void 0,
5322
+ enabled,
5323
+ required
5324
+ };
5325
+ }
5326
+ toObject() {
5327
+ var _a2;
5328
+ const items = __privateMethod$1(_a2 = _b$1, _FunctionParams_static, orderItems_fn).call(_a2, __privateGet$1(this, _items)).flat();
5329
+ return _b$1.toObject(items);
5330
+ }
5331
+ static toString(items) {
5332
+ var _a2;
5333
+ return __privateMethod$1(_a2 = _b$1, _FunctionParams_static, orderItems_fn).call(_a2, items).reduce((acc, item) => {
5334
+ var _a3, _b2, _c;
5335
+ if (Array.isArray(item)) {
5336
+ if (item.length <= 0) return acc;
5337
+ const subItems = __privateMethod$1(_a3 = _b$1, _FunctionParams_static, orderItems_fn).call(_a3, item);
5338
+ const objectItem = _b$1.toObject(subItems);
5339
+ return __privateMethod$1(_b2 = _b$1, _FunctionParams_static, addParams_fn).call(_b2, acc, objectItem);
5340
+ }
5341
+ return __privateMethod$1(_c = _b$1, _FunctionParams_static, addParams_fn).call(_c, acc, item);
5342
+ }, []).join(", ");
5343
+ }
5344
+ toString() {
5345
+ var _a2;
5346
+ const items = __privateMethod$1(_a2 = _b$1, _FunctionParams_static, orderItems_fn).call(_a2, __privateGet$1(this, _items));
5347
+ return _b$1.toString(items);
5348
+ }
5349
+ }, _items = new WeakMap(), _FunctionParams_static = new WeakSet(), orderItems_fn = function(items) {
5350
+ return orderBy(items.filter(Boolean), [(v) => {
5351
+ if (Array.isArray(v)) return;
5352
+ return !v.default;
5353
+ }, (v) => {
5354
+ var _a2;
5355
+ if (Array.isArray(v)) return;
5356
+ return (_a2 = v.required) != null ? _a2 : true;
5357
+ }], ["desc", "desc"]);
5358
+ }, addParams_fn = function(acc, item) {
5359
+ const { enabled = true, name, type, required = true, ...rest } = item;
5360
+ if (!enabled) return acc;
5361
+ if (!name) {
5362
+ acc.push(`${type}${rest.default ? ` = ${rest.default}` : ""}`);
5363
+ return acc;
5364
+ }
5365
+ const parameterName = name.startsWith("{") ? name : camelCase(name);
5366
+ if (type) if (required) acc.push(`${parameterName}: ${type}${rest.default ? ` = ${rest.default}` : ""}`);
5367
+ else acc.push(`${parameterName}?: ${type}`);
5368
+ else acc.push(`${parameterName}`);
5369
+ return acc;
5370
+ }, __privateAdd$1(_b$1, _FunctionParams_static), _b$1);
5371
+ const formatters = {
5372
+ prettier: {
5373
+ command: "prettier",
5374
+ args: (outputPath) => [
5375
+ "--ignore-unknown",
5376
+ "--write",
5377
+ outputPath
5378
+ ],
5379
+ errorMessage: "Prettier not found"
5380
+ },
5381
+ biome: {
5382
+ command: "biome",
5383
+ args: (outputPath) => [
5384
+ "format",
5385
+ "--write",
5386
+ outputPath
5387
+ ],
5388
+ errorMessage: "Biome not found"
5389
+ },
5390
+ oxfmt: {
5391
+ command: "oxfmt",
5392
+ args: (outputPath) => [outputPath],
5393
+ errorMessage: "Oxfmt not found"
5394
+ }
5395
+ };
5396
+ async function isFormatterAvailable(formatter) {
5397
+ try {
5398
+ await execaCommand(`${formatter} --version`, { stdio: "ignore" });
5399
+ return true;
5400
+ } catch {
5401
+ return false;
5402
+ }
5403
+ }
5404
+ async function detectFormatter() {
5405
+ for (const formatter of [
5406
+ "biome",
5407
+ "oxfmt",
5408
+ "prettier"
5409
+ ]) if (await isFormatterAvailable(formatter)) return formatter;
5410
+ }
5411
+ function isJSONPlugins(plugins) {
5412
+ return !!(plugins == null ? void 0 : plugins.some((plugin) => {
5413
+ return Array.isArray(plugin) && typeof (plugin == null ? void 0 : plugin.at(0)) === "string";
5414
+ }));
5415
+ }
5416
+ function isObjectPlugins(plugins) {
5417
+ return plugins instanceof Object && !Array.isArray(plugins);
5418
+ }
5419
+ function getPlugins(plugins) {
5420
+ if (isObjectPlugins(plugins)) throw new Error("Object plugins are not supported anymore, best to use http://kubb.dev/getting-started/configure#json");
5421
+ if (isJSONPlugins(plugins)) throw new Error("JSON plugins are not supported anymore, best to use http://kubb.dev/getting-started/configure#json");
5422
+ return Promise.resolve(plugins);
5423
+ }
5424
+ function isPromise(result) {
5425
+ return !!result && typeof (result == null ? void 0 : result.then) === "function";
5426
+ }
5427
+ async function getConfigs(config, args) {
5428
+ let kubbUserConfig = Promise.resolve(config);
5429
+ if (typeof config === "function") {
5430
+ const possiblePromise = config(args);
5431
+ if (isPromise(possiblePromise)) kubbUserConfig = possiblePromise;
5432
+ kubbUserConfig = Promise.resolve(possiblePromise);
5433
+ }
5434
+ let JSONConfig = await kubbUserConfig;
5435
+ if (!Array.isArray(JSONConfig)) JSONConfig = [JSONConfig];
5436
+ const results = [];
5437
+ for (const item of JSONConfig) {
5438
+ const plugins = item.plugins ? await getPlugins(item.plugins) : void 0;
5439
+ results.push({
5440
+ ...item,
5441
+ plugins
5442
+ });
5443
+ }
5444
+ return results;
5445
+ }
5446
+ const linters = {
5447
+ eslint: {
5448
+ command: "eslint",
5449
+ args: (outputPath) => [outputPath, "--fix"],
5450
+ errorMessage: "Eslint not found"
5451
+ },
5452
+ biome: {
5453
+ command: "biome",
5454
+ args: (outputPath) => [
5455
+ "lint",
5456
+ "--fix",
5457
+ outputPath
5458
+ ],
5459
+ errorMessage: "Biome not found"
5460
+ },
5461
+ oxlint: {
5462
+ command: "oxlint",
5463
+ args: (outputPath) => ["--fix", outputPath],
5464
+ errorMessage: "Oxlint not found"
5465
+ }
5466
+ };
5467
+ async function isLinterAvailable(linter) {
5468
+ try {
5469
+ await execaCommand(`${linter} --version`, { stdio: "ignore" });
5470
+ return true;
5471
+ } catch {
5472
+ return false;
5473
+ }
5474
+ }
5475
+ async function detectLinter() {
5476
+ for (const linter of [
5477
+ "biome",
5478
+ "oxlint",
5479
+ "eslint"
5480
+ ]) if (await isLinterAvailable(linter)) return linter;
5481
+ }
5482
+ function serializePluginOptions(options) {
5483
+ if (options === null || options === void 0) return {};
5484
+ if (typeof options !== "object") return options;
5485
+ if (Array.isArray(options)) return options.map(serializePluginOptions);
5486
+ const serialized = {};
5487
+ for (const [key, value] of Object.entries(options)) {
5488
+ if (typeof value === "function" || typeof value === "symbol" || value === void 0) continue;
5489
+ if (typeof value === "object" && value !== null) serialized[key] = serializePluginOptions(value);
5490
+ else serialized[key] = value;
5491
+ }
5492
+ return serialized;
5493
+ }
5494
+
5495
+ function isCommandMessage(msg) {
5496
+ return msg.type === "command";
5497
+ }
5498
+
5499
+ const logger = {
5500
+ info(message, details) {
5501
+ const text = details ? `${message} ${pc.dim(details)}` : message;
5502
+ console.info(`${pc.blue("\u2139")} ${text}`);
5503
+ },
5504
+ success(message, details) {
5505
+ const text = details ? `${message} ${pc.dim(details)}` : message;
5506
+ console.log(`${pc.green("\u2713")} ${text}`);
5507
+ },
5508
+ warn(message, details) {
5509
+ const text = details ? `${message} ${pc.dim(details)}` : message;
5510
+ console.warn(`${pc.yellow("\u26A0")} ${text}`);
5511
+ },
5512
+ error(message, details) {
5513
+ const text = details ? `${message} ${pc.dim(details)}` : message;
5514
+ console.error(`${pc.red("\u2717")} ${text}`);
5515
+ }
5516
+ };
5517
+
5518
+ const CONFIG_DIR = path$1.join(os.homedir(), ".kubb");
5519
+ const CONFIG_FILE = path$1.join(CONFIG_DIR, "config.json");
5520
+ function loadAgentConfig() {
5521
+ try {
5522
+ const content = readFileSync(CONFIG_FILE, "utf-8");
5523
+ return JSON.parse(content);
5524
+ } catch (_error) {
5525
+ return { sessions: {} };
5526
+ }
5527
+ }
5528
+ function saveAgentConfig(config) {
5529
+ try {
5530
+ if (!CONFIG_DIR) {
5531
+ return;
5532
+ }
5533
+ try {
5534
+ writeFileSync(CONFIG_FILE, JSON.stringify(config, null, 2), "utf-8");
5535
+ } catch {
5536
+ return;
5537
+ }
5538
+ } catch (_error) {
5539
+ logger.warn("Failed to save agent config");
5540
+ }
5541
+ }
5542
+ function isSessionValid(session) {
5543
+ try {
5544
+ const expiresAt = new Date(session.expiresAt);
5545
+ const now = /* @__PURE__ */ new Date();
5546
+ return now.getTime() < expiresAt.getTime() - 6e4;
5547
+ } catch {
5548
+ return false;
5549
+ }
5550
+ }
5551
+ function getCachedSession(agentToken) {
5552
+ var _a;
5553
+ try {
5554
+ const config = loadAgentConfig();
5555
+ const sessionKey = hashAgentToken(agentToken);
5556
+ const session = (_a = config.sessions) == null ? void 0 : _a[sessionKey];
5557
+ if (!session) {
5558
+ return null;
5559
+ }
5560
+ if (!isSessionValid(session)) {
5561
+ deleteCachedSession(agentToken);
5562
+ return null;
5563
+ }
5564
+ return session;
5565
+ } catch (_error) {
5566
+ logger.warn("Failed to get cached session");
5567
+ return null;
5568
+ }
5569
+ }
5570
+ function cacheSession(agentToken, session) {
5571
+ try {
5572
+ const config = loadAgentConfig();
5573
+ const sessionKey = hashAgentToken(agentToken);
5574
+ if (!config.sessions) {
5575
+ config.sessions = {};
5576
+ }
5577
+ config.sessions[sessionKey] = {
5578
+ ...session,
5579
+ storedAt: (/* @__PURE__ */ new Date()).toISOString()
5580
+ };
5581
+ saveAgentConfig(config);
5582
+ logger.success("Cached agent session");
5583
+ } catch (_error) {
5584
+ logger.warn("Failed to cache session");
5585
+ }
5586
+ }
5587
+ function deleteCachedSession(agentToken) {
5588
+ var _a;
5589
+ try {
5590
+ const config = loadAgentConfig();
5591
+ const sessionKey = hashAgentToken(agentToken);
5592
+ if ((_a = config.sessions) == null ? void 0 : _a[sessionKey]) {
5593
+ delete config.sessions[sessionKey];
5594
+ saveAgentConfig(config);
5595
+ }
5596
+ } catch (_error) {
5597
+ logger.warn("Failed to delete cached session");
5598
+ }
5599
+ }
5600
+ function hashAgentToken(token) {
5601
+ return createHash("sha512").update(token).digest("hex");
5602
+ }
5603
+
5604
+ async function createAgentSession({ token, studioUrl, noCache }) {
5605
+ const cachedSession = !noCache ? getCachedSession(token) : null;
5606
+ if (cachedSession) {
5607
+ logger.success("Using cached agent session");
5608
+ return cachedSession;
5609
+ }
5610
+ const connectUrl = `${studioUrl}/api/agent/session/create`;
5611
+ try {
5612
+ const data = await $fetch(connectUrl, {
5613
+ method: "POST",
5614
+ headers: {
5615
+ Authorization: `Bearer ${token}`
5616
+ }
5617
+ });
5618
+ if (data && !noCache) {
5619
+ cacheSession(token, data);
5620
+ }
5621
+ if (!data) {
5622
+ throw new Error("No data available for agent session");
5623
+ }
5624
+ return data;
5625
+ } catch (error) {
5626
+ throw new Error("Failed to get agent session from Kubb Studio", { cause: error });
5627
+ }
5628
+ }
5629
+ async function disconnect({ sessionToken, token, studioUrl }) {
5630
+ try {
5631
+ const disconnectUrl = `${studioUrl}/api/agent/session/${sessionToken}/disconnect`;
5632
+ await $fetch(disconnectUrl, {
5633
+ method: "POST",
5634
+ headers: {
5635
+ Authorization: `Bearer ${token}`
5636
+ }
5637
+ });
5638
+ logger.success("Sent disconnect notification to Studio on exit");
5639
+ } catch (error) {
5640
+ throw new Error("Failed to notify Studio of disconnection on exit", { cause: error });
5641
+ }
5642
+ }
5643
+
5644
+ var __typeError = (msg) => {
5645
+ throw TypeError(msg);
5646
+ };
5647
+ var __accessCheck = (obj, member, msg) => member.has(obj) || __typeError("Cannot " + msg);
5648
+ var __privateGet = (obj, member, getter) => (__accessCheck(obj, member, "read from private field"), getter ? getter.call(obj) : member.get(obj));
5649
+ var __privateAdd = (obj, member, value) => member.has(obj) ? __typeError("Cannot add the same private member more than once") : member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
5650
+ var __privateSet = (obj, member, value, setter) => (__accessCheck(obj, member, "write to private field"), member.set(obj, value), value);
5651
+ var __privateMethod = (obj, member, method) => (__accessCheck(obj, member, "access private method"), method);
5652
+ var _b, _cache, _cwd, _SLASHES, _PackageManager_instances, match_fn;
5287
5653
  function isInputPath(config) {
5288
5654
  return typeof (config == null ? void 0 : config.input) === "object" && config.input !== null && "path" in config.input;
5289
5655
  }
5290
- var version$1 = "4.24.1";
5656
+ var version$1 = "4.25.1";
5291
5657
  function getDiagnosticInfo() {
5292
5658
  return {
5293
- nodeVersion: version,
5659
+ nodeVersion: version$2,
5294
5660
  KubbVersion: version$1,
5295
5661
  platform: process.platform,
5296
5662
  arch: process.arch,
@@ -5688,11 +6054,11 @@ function findUpSync(name, options = {}) {
5688
6054
  limit: 1
5689
6055
  })[0];
5690
6056
  }
5691
- (_b$1 = class {
6057
+ (_b = class {
5692
6058
  constructor(workspace) {
5693
- __privateAdd$1(this, _PackageManager_instances);
5694
- __privateAdd$1(this, _cwd);
5695
- __privateAdd$1(this, _SLASHES, /* @__PURE__ */ new Set(["/", "\\"]));
6059
+ __privateAdd(this, _PackageManager_instances);
6060
+ __privateAdd(this, _cwd);
6061
+ __privateAdd(this, _SLASHES, /* @__PURE__ */ new Set(["/", "\\"]));
5696
6062
  if (workspace) __privateSet(this, _cwd, workspace);
5697
6063
  return this;
5698
6064
  }
@@ -5700,16 +6066,16 @@ function findUpSync(name, options = {}) {
5700
6066
  __privateSet(this, _cwd, workspace);
5701
6067
  }
5702
6068
  get workspace() {
5703
- return __privateGet$1(this, _cwd);
6069
+ return __privateGet(this, _cwd);
5704
6070
  }
5705
6071
  normalizeDirectory(directory) {
5706
6072
  const lastChar = directory[directory.length - 1];
5707
- if (lastChar && !__privateGet$1(this, _SLASHES).has(lastChar)) return `${directory}/`;
6073
+ if (lastChar && !__privateGet(this, _SLASHES).has(lastChar)) return `${directory}/`;
5708
6074
  return directory;
5709
6075
  }
5710
6076
  getLocation(path$1) {
5711
6077
  let location = path$1;
5712
- if (__privateGet$1(this, _cwd)) location = mod.createRequire(this.normalizeDirectory(__privateGet$1(this, _cwd))).resolve(path$1);
6078
+ if (__privateGet(this, _cwd)) location = mod.createRequire(this.normalizeDirectory(__privateGet(this, _cwd))).resolve(path$1);
5713
6079
  return location;
5714
6080
  }
5715
6081
  async import(path$1) {
@@ -5725,31 +6091,31 @@ function findUpSync(name, options = {}) {
5725
6091
  }
5726
6092
  }
5727
6093
  async getPackageJSON() {
5728
- const pkgPath = await findUp(["package.json"], { cwd: __privateGet$1(this, _cwd) });
6094
+ const pkgPath = await findUp(["package.json"], { cwd: __privateGet(this, _cwd) });
5729
6095
  if (!pkgPath) return;
5730
6096
  const json = await read(pkgPath);
5731
6097
  return JSON.parse(json);
5732
6098
  }
5733
6099
  getPackageJSONSync() {
5734
- const pkgPath = findUpSync(["package.json"], { cwd: __privateGet$1(this, _cwd) });
6100
+ const pkgPath = findUpSync(["package.json"], { cwd: __privateGet(this, _cwd) });
5735
6101
  if (!pkgPath) return;
5736
6102
  const json = readSync(pkgPath);
5737
6103
  return JSON.parse(json);
5738
6104
  }
5739
6105
  static setVersion(dependency, version$2) {
5740
- __privateGet$1(_b$1, _cache)[dependency] = version$2;
6106
+ __privateGet(_b, _cache)[dependency] = version$2;
5741
6107
  }
5742
6108
  async getVersion(dependency) {
5743
- if (typeof dependency === "string" && __privateGet$1(_b$1, _cache)[dependency]) return __privateGet$1(_b$1, _cache)[dependency];
6109
+ if (typeof dependency === "string" && __privateGet(_b, _cache)[dependency]) return __privateGet(_b, _cache)[dependency];
5744
6110
  const packageJSON = await this.getPackageJSON();
5745
6111
  if (!packageJSON) return;
5746
- return __privateMethod$1(this, _PackageManager_instances, match_fn).call(this, packageJSON, dependency);
6112
+ return __privateMethod(this, _PackageManager_instances, match_fn).call(this, packageJSON, dependency);
5747
6113
  }
5748
6114
  getVersionSync(dependency) {
5749
- if (typeof dependency === "string" && __privateGet$1(_b$1, _cache)[dependency]) return __privateGet$1(_b$1, _cache)[dependency];
6115
+ if (typeof dependency === "string" && __privateGet(_b, _cache)[dependency]) return __privateGet(_b, _cache)[dependency];
5750
6116
  const packageJSON = this.getPackageJSONSync();
5751
6117
  if (!packageJSON) return;
5752
- return __privateMethod$1(this, _PackageManager_instances, match_fn).call(this, packageJSON, dependency);
6118
+ return __privateMethod(this, _PackageManager_instances, match_fn).call(this, packageJSON, dependency);
5753
6119
  }
5754
6120
  async isValid(dependency, version$2) {
5755
6121
  const packageVersion = await this.getVersion(dependency);
@@ -5775,160 +6141,7 @@ function findUpSync(name, options = {}) {
5775
6141
  if (typeof dependency === "string" && dependencies[dependency]) return dependencies[dependency];
5776
6142
  const matchedDependency = Object.keys(dependencies).find((dep) => dep.match(dependency));
5777
6143
  return matchedDependency ? dependencies[matchedDependency] : void 0;
5778
- }, __privateAdd$1(_b$1, _cache, {}), _b$1);
5779
- const LogLevel = {
5780
- silent: Number.NEGATIVE_INFINITY,
5781
- error: 0,
5782
- warn: 1,
5783
- info: 3,
5784
- verbose: 4,
5785
- debug: 5
5786
- };
5787
-
5788
- var __typeError = (msg) => {
5789
- throw TypeError(msg);
5790
- };
5791
- var __accessCheck = (obj, member, msg) => member.has(obj) || __typeError("Cannot " + msg);
5792
- var __privateGet = (obj, member, getter) => (__accessCheck(obj, member, "read from private field"), getter ? getter.call(obj) : member.get(obj));
5793
- var __privateAdd = (obj, member, value) => member.has(obj) ? __typeError("Cannot add the same private member more than once") : member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
5794
- var __privateMethod = (obj, member, method) => (__accessCheck(obj, member, "access private method"), method);
5795
- var _items, _FunctionParams_static, _b, orderItems_fn, addParams_fn;
5796
- (_b = class {
5797
- constructor() {
5798
- __privateAdd(this, _items, []);
5799
- return this;
5800
- }
5801
- get items() {
5802
- return __privateGet(this, _items).flat();
5803
- }
5804
- add(item) {
5805
- if (!item) return this;
5806
- if (Array.isArray(item)) {
5807
- item.filter(Boolean).forEach((it) => {
5808
- __privateGet(this, _items).push(it);
5809
- });
5810
- return this;
5811
- }
5812
- __privateGet(this, _items).push(item);
5813
- return this;
5814
- }
5815
- static toObject(items) {
5816
- var _a2, _b2;
5817
- let type = [];
5818
- let name = [];
5819
- const enabled = items.every((item) => item.enabled) ? (_a2 = items.at(0)) == null ? void 0 : _a2.enabled : true;
5820
- const required = (_b2 = items.every((item) => item.required)) != null ? _b2 : true;
5821
- items.forEach((item) => {
5822
- var _a3, _b3;
5823
- name = __privateMethod(_a3 = _b, _FunctionParams_static, addParams_fn).call(_a3, name, {
5824
- ...item,
5825
- type: void 0
5826
- });
5827
- if (items.some((item$1) => item$1.type)) type = __privateMethod(_b3 = _b, _FunctionParams_static, addParams_fn).call(_b3, type, item);
5828
- });
5829
- return {
5830
- name: `{ ${name.join(", ")} }`,
5831
- type: type.length ? `{ ${type.join("; ")} }` : void 0,
5832
- enabled,
5833
- required
5834
- };
5835
- }
5836
- toObject() {
5837
- var _a2;
5838
- const items = __privateMethod(_a2 = _b, _FunctionParams_static, orderItems_fn).call(_a2, __privateGet(this, _items)).flat();
5839
- return _b.toObject(items);
5840
- }
5841
- static toString(items) {
5842
- var _a2;
5843
- return __privateMethod(_a2 = _b, _FunctionParams_static, orderItems_fn).call(_a2, items).reduce((acc, item) => {
5844
- var _a3, _b2, _c;
5845
- if (Array.isArray(item)) {
5846
- if (item.length <= 0) return acc;
5847
- const subItems = __privateMethod(_a3 = _b, _FunctionParams_static, orderItems_fn).call(_a3, item);
5848
- const objectItem = _b.toObject(subItems);
5849
- return __privateMethod(_b2 = _b, _FunctionParams_static, addParams_fn).call(_b2, acc, objectItem);
5850
- }
5851
- return __privateMethod(_c = _b, _FunctionParams_static, addParams_fn).call(_c, acc, item);
5852
- }, []).join(", ");
5853
- }
5854
- toString() {
5855
- var _a2;
5856
- const items = __privateMethod(_a2 = _b, _FunctionParams_static, orderItems_fn).call(_a2, __privateGet(this, _items));
5857
- return _b.toString(items);
5858
- }
5859
- }, _items = new WeakMap(), _FunctionParams_static = new WeakSet(), orderItems_fn = function(items) {
5860
- return orderBy(items.filter(Boolean), [(v) => {
5861
- if (Array.isArray(v)) return;
5862
- return !v.default;
5863
- }, (v) => {
5864
- var _a2;
5865
- if (Array.isArray(v)) return;
5866
- return (_a2 = v.required) != null ? _a2 : true;
5867
- }], ["desc", "desc"]);
5868
- }, addParams_fn = function(acc, item) {
5869
- const { enabled = true, name, type, required = true, ...rest } = item;
5870
- if (!enabled) return acc;
5871
- if (!name) {
5872
- acc.push(`${type}${rest.default ? ` = ${rest.default}` : ""}`);
5873
- return acc;
5874
- }
5875
- const parameterName = name.startsWith("{") ? name : camelCase(name);
5876
- if (type) if (required) acc.push(`${parameterName}: ${type}${rest.default ? ` = ${rest.default}` : ""}`);
5877
- else acc.push(`${parameterName}?: ${type}`);
5878
- else acc.push(`${parameterName}`);
5879
- return acc;
5880
- }, __privateAdd(_b, _FunctionParams_static), _b);
5881
- function isPromise(result) {
5882
- return !!result && typeof (result == null ? void 0 : result.then) === "function";
5883
- }
5884
- function serializePluginOptions(options) {
5885
- if (options === null || options === void 0) return {};
5886
- if (typeof options !== "object") return options;
5887
- if (Array.isArray(options)) return options.map(serializePluginOptions);
5888
- const serialized = {};
5889
- for (const [key, value] of Object.entries(options)) {
5890
- if (typeof value === "function" || typeof value === "symbol" || value === void 0) continue;
5891
- if (typeof value === "object" && value !== null) serialized[key] = serializePluginOptions(value);
5892
- else serialized[key] = value;
5893
- }
5894
- return serialized;
5895
- }
5896
-
5897
- async function isFormatterAvailable(formatter) {
5898
- try {
5899
- await execaCommand(`${formatter} --version`, { stdio: "ignore" });
5900
- return true;
5901
- } catch {
5902
- return false;
5903
- }
5904
- }
5905
- async function detectFormatter() {
5906
- const formatters2 = ["biome", "oxfmt", "prettier"];
5907
- for (const formatter of formatters2) {
5908
- if (await isFormatterAvailable(formatter)) {
5909
- return formatter;
5910
- }
5911
- }
5912
- return void 0;
5913
- }
5914
-
5915
- async function isLinterAvailable(linter) {
5916
- try {
5917
- await execaCommand(`${linter} --version`, { stdio: "ignore" });
5918
- return true;
5919
- } catch {
5920
- return false;
5921
- }
5922
- }
5923
- async function detectLinter() {
5924
- const linters = ["biome", "oxlint", "eslint"];
5925
- for (const linter of linters) {
5926
- if (await isLinterAvailable(linter)) {
5927
- return linter;
5928
- }
5929
- }
5930
- return void 0;
5931
- }
6144
+ }, __privateAdd(_b, _cache, {}), _b);
5932
6145
 
5933
6146
  async function executeHooks({ hooks, events }) {
5934
6147
  const commands = Array.isArray(hooks.done) ? hooks.done : [hooks.done].filter(Boolean);
@@ -5948,39 +6161,7 @@ async function executeHooks({ hooks, events }) {
5948
6161
  }
5949
6162
  }
5950
6163
 
5951
- const formatters = {
5952
- prettier: {
5953
- command: "prettier",
5954
- args: (outputPath) => ["--ignore-unknown", "--write", outputPath],
5955
- errorMessage: "Prettier not found"
5956
- },
5957
- biome: {
5958
- command: "biome",
5959
- args: (outputPath) => ["format", "--write", outputPath],
5960
- errorMessage: "Biome not found"
5961
- },
5962
- oxfmt: {
5963
- command: "oxfmt",
5964
- args: (outputPath) => [outputPath],
5965
- errorMessage: "Oxfmt not found"
5966
- }
5967
- };
5968
-
5969
- async function generate({ config: userConfig, events, logLevel }) {
5970
- const hrStart = process$1.hrtime();
5971
- const config = {
5972
- ...userConfig,
5973
- root: userConfig.root || process$1.cwd(),
5974
- output: {
5975
- write: true,
5976
- barrelType: "named",
5977
- extension: {
5978
- ".ts": ".ts"
5979
- },
5980
- format: "prettier",
5981
- ...userConfig.output
5982
- }
5983
- };
6164
+ async function generate({ config, events }) {
5984
6165
  await events.emit("generation:start", config);
5985
6166
  await events.emit("info", config.name ? `Setup generation ${config.name}` : "Setup generation");
5986
6167
  const { sources, fabric, pluginManager } = await setup({
@@ -5988,7 +6169,7 @@ async function generate({ config: userConfig, events, logLevel }) {
5988
6169
  events
5989
6170
  });
5990
6171
  await events.emit("info", config.name ? `Build generation ${config.name}` : "Build generation");
5991
- const { files, failedPlugins, pluginTimings, error } = await safeBuild(
6172
+ const { files, failedPlugins, error } = await safeBuild(
5992
6173
  {
5993
6174
  config,
5994
6175
  events
@@ -6006,13 +6187,6 @@ async function generate({ config: userConfig, events, logLevel }) {
6006
6187
  events.emit("error", err);
6007
6188
  });
6008
6189
  await events.emit("generation:end", config, files, sources);
6009
- await events.emit("generation:summary", config, {
6010
- failedPlugins,
6011
- filesCreated: files.length,
6012
- status: failedPlugins.size > 0 || error ? "failed" : "success",
6013
- hrStart,
6014
- pluginTimings: void 0
6015
- });
6016
6190
  throw new Error("Generation failed");
6017
6191
  }
6018
6192
  await events.emit("success", "Generation successfully");
@@ -6031,7 +6205,7 @@ async function generate({ config: userConfig, events, logLevel }) {
6031
6205
  }
6032
6206
  if (formatter && formatter !== "auto" && formatter in formatters) {
6033
6207
  const formatterConfig = formatters[formatter];
6034
- const outputPath = path$1.resolve(config.root, config.output.path);
6208
+ const outputPath = path$1.isAbsolute(config.output.path) ? config.output.path : path$1.resolve(process.cwd(), config.root, config.output.path);
6035
6209
  try {
6036
6210
  const hookId = createHash("sha256").update([config.name, formatter].filter(Boolean).join("-")).digest("hex");
6037
6211
  await events.emit("hook:start", {
@@ -6060,70 +6234,26 @@ async function generate({ config: userConfig, events, logLevel }) {
6060
6234
  await events.emit("warn", "No linter found (biome, oxlint, or eslint). Skipping linting.");
6061
6235
  } else {
6062
6236
  linter = detectedLinter;
6063
- await events.emit("info", `Auto-detected linter: ${linter}`);
6064
- }
6065
- }
6066
- if (linter && linter !== "auto") {
6067
- await events.emit("info", `Linting with ${linter}`);
6068
- if (linter === "eslint") {
6069
- try {
6070
- const hookId = createHash("sha256").update([config.name, linter].filter(Boolean).join("-")).digest("hex");
6071
- await events.emit("hook:start", {
6072
- id: hookId,
6073
- command: "eslint",
6074
- args: [path$1.resolve(config.root, config.output.path), "--fix"]
6075
- });
6076
- await events.onOnce("hook:end", async ({ success, error: error2 }) => {
6077
- if (!success) {
6078
- throw error2;
6079
- }
6080
- await events.emit("success", "Linted with eslint successfully");
6081
- });
6082
- } catch (caughtError) {
6083
- const error2 = new Error("Eslint not found");
6084
- error2.cause = caughtError;
6085
- await events.emit("error", error2);
6086
- }
6087
- }
6088
- if (linter === "biome") {
6089
- try {
6090
- const hookId = createHash("sha256").update([config.name, linter].filter(Boolean).join("-")).digest("hex");
6091
- await events.emit("hook:start", {
6092
- id: hookId,
6093
- command: "biome",
6094
- args: ["lint", "--fix", path$1.resolve(config.root, config.output.path)]
6095
- });
6096
- await events.onOnce("hook:end", async ({ success, error: error2 }) => {
6097
- if (!success) {
6098
- throw error2;
6099
- }
6100
- await events.emit("success", "Linted with biome successfully");
6101
- });
6102
- } catch (caughtError) {
6103
- const error2 = new Error("Biome not found");
6104
- error2.cause = caughtError;
6105
- await events.emit("error", error2);
6106
- }
6237
+ await events.emit("info", `Auto-detected linter: ${pc.dim(linter)}`);
6107
6238
  }
6108
- if (linter === "oxlint") {
6109
- try {
6110
- const hookId = createHash("sha256").update([config.name, linter].filter(Boolean).join("-")).digest("hex");
6111
- await events.emit("hook:start", {
6112
- id: hookId,
6113
- command: "oxlint",
6114
- args: ["--fix", path$1.resolve(config.root, config.output.path)]
6115
- });
6116
- await events.onOnce("hook:end", async ({ success, error: error2 }) => {
6117
- if (!success) {
6118
- throw error2;
6119
- }
6120
- await events.emit("success", "Linted with oxlint successfully");
6121
- });
6122
- } catch (caughtError) {
6123
- const error2 = new Error("Oxlint not found");
6124
- error2.cause = caughtError;
6125
- await events.emit("error", error2);
6126
- }
6239
+ }
6240
+ if (linter && linter !== "auto" && linter in linters) {
6241
+ const linterConfig = linters[linter];
6242
+ const outputPath = path$1.isAbsolute(config.output.path) ? config.output.path : path$1.resolve(process.cwd(), config.root, config.output.path);
6243
+ try {
6244
+ const hookId = createHash("sha256").update([config.name, linter].filter(Boolean).join("-")).digest("hex");
6245
+ await events.emit("hook:start", {
6246
+ id: hookId,
6247
+ command: linterConfig.command,
6248
+ args: linterConfig.args(outputPath)
6249
+ });
6250
+ await events.onOnce("hook:end", async ({ success, error: error2 }) => {
6251
+ if (!success) throw error2;
6252
+ });
6253
+ } catch (caughtError) {
6254
+ const error2 = new Error(linterConfig.errorMessage);
6255
+ error2.cause = caughtError;
6256
+ await events.emit("error", error2);
6127
6257
  }
6128
6258
  }
6129
6259
  await events.emit("lint:end");
@@ -6133,52 +6263,10 @@ async function generate({ config: userConfig, events, logLevel }) {
6133
6263
  await executeHooks({ hooks: config.hooks, events });
6134
6264
  await events.emit("hooks:end");
6135
6265
  }
6136
- await events.emit("generation:summary", config, {
6137
- failedPlugins,
6138
- filesCreated: files.length,
6139
- status: failedPlugins.size > 0 || error ? "failed" : "success",
6140
- hrStart,
6141
- pluginTimings
6142
- });
6143
- }
6144
-
6145
- function getPlugins(plugins) {
6146
- if (plugins instanceof Object && !Array.isArray(plugins)) {
6147
- throw new Error("Object plugins are not supported anymore, best to use http://kubb.dev/getting-started/configure#json");
6148
- }
6149
- if (Array.isArray(plugins) && plugins.some((plugin) => Array.isArray(plugin) && typeof (plugin == null ? void 0 : plugin.at(0)) === "string")) {
6150
- throw new Error("JSON plugins are not supported anymore, best to use http://kubb.dev/getting-started/configure#json");
6151
- }
6152
- return Promise.resolve(plugins);
6153
- }
6154
- async function getConfigs(result) {
6155
- const config = result == null ? void 0 : result.config;
6156
- let kubbUserConfig = Promise.resolve(config);
6157
- if (typeof config === "function") {
6158
- const possiblePromise = config({});
6159
- if (isPromise(possiblePromise)) {
6160
- kubbUserConfig = possiblePromise;
6161
- } else {
6162
- kubbUserConfig = Promise.resolve(possiblePromise);
6163
- }
6164
- }
6165
- let JSONConfig = await kubbUserConfig;
6166
- if (!Array.isArray(JSONConfig)) {
6167
- JSONConfig = [JSONConfig];
6168
- }
6169
- const results = [];
6170
- for (const item of JSONConfig) {
6171
- const plugins = item.plugins ? await getPlugins(item.plugins) : void 0;
6172
- results.push({
6173
- ...item,
6174
- plugins
6175
- });
6176
- }
6177
- return results;
6178
6266
  }
6179
6267
 
6180
6268
  const tsLoader = async (configFile) => {
6181
- const jiti = createJiti(configFile, {
6269
+ const jiti = createJiti(globalThis._importMeta_.url, {
6182
6270
  jsx: {
6183
6271
  runtime: "automatic",
6184
6272
  importSource: "@kubb/react-fabric"
@@ -6202,70 +6290,311 @@ async function getCosmiConfig(configPath) {
6202
6290
  }
6203
6291
  }
6204
6292
 
6205
- const contextStorage = new AsyncLocalStorage();
6206
- let globalContext = null;
6207
- function setGlobalContext(context) {
6208
- globalContext = context;
6209
- }
6210
- function useKubbAgentContext() {
6211
- const localContext = contextStorage.getStore();
6212
- if (localContext) {
6213
- return localContext;
6293
+ const WEBSOCKET_READY = 1;
6294
+ const WEBSOCKET_CONNECTING = 0;
6295
+ function createWebsocket(url, options) {
6296
+ const ws = new WebSocket(url, options);
6297
+ setTimeout(() => {
6298
+ if (ws.readyState === WEBSOCKET_CONNECTING) {
6299
+ ws.close(3008, "Connection timeout");
6300
+ }
6301
+ }, 5e3);
6302
+ return ws;
6303
+ }
6304
+ function sendAgentMessage(ws, message) {
6305
+ try {
6306
+ if (ws.readyState !== WEBSOCKET_READY) {
6307
+ return;
6308
+ }
6309
+ ws.send(JSON.stringify(message));
6310
+ } catch (error) {
6311
+ throw new Error("Failed to send message to Kubb Studio", { cause: error });
6214
6312
  }
6215
- if (globalContext) {
6216
- return globalContext;
6313
+ }
6314
+ function setupEventsStream(ws, events) {
6315
+ function sendDataMessage(payload) {
6316
+ sendAgentMessage(ws, {
6317
+ type: "data",
6318
+ payload
6319
+ });
6217
6320
  }
6218
- throw new Error("Kubb agent context not initialized. Make sure KUBB_CONFIG environment variable is set.");
6321
+ events.on("plugin:start", (plugin) => {
6322
+ sendDataMessage({
6323
+ type: "plugin:start",
6324
+ data: [plugin],
6325
+ timestamp: Date.now()
6326
+ });
6327
+ });
6328
+ events.on("plugin:end", (plugin, meta) => {
6329
+ sendDataMessage({
6330
+ type: "plugin:end",
6331
+ data: [plugin, meta],
6332
+ timestamp: Date.now()
6333
+ });
6334
+ });
6335
+ events.on("files:processing:start", (files) => {
6336
+ sendDataMessage({
6337
+ type: "files:processing:start",
6338
+ data: [{ total: files.length }],
6339
+ timestamp: Date.now()
6340
+ });
6341
+ });
6342
+ events.on("file:processing:update", (meta) => {
6343
+ sendDataMessage({
6344
+ type: "file:processing:update",
6345
+ data: [
6346
+ {
6347
+ file: meta.file.path,
6348
+ processed: meta.processed,
6349
+ total: meta.total,
6350
+ percentage: meta.percentage
6351
+ }
6352
+ ],
6353
+ timestamp: Date.now()
6354
+ });
6355
+ });
6356
+ events.on("files:processing:end", (files) => {
6357
+ sendDataMessage({
6358
+ type: "files:processing:end",
6359
+ data: [{ total: files.length }],
6360
+ timestamp: Date.now()
6361
+ });
6362
+ });
6363
+ events.on("info", (message, info) => {
6364
+ sendDataMessage({
6365
+ type: "info",
6366
+ data: [message, info],
6367
+ timestamp: Date.now()
6368
+ });
6369
+ });
6370
+ events.on("success", (message, info) => {
6371
+ sendDataMessage({
6372
+ type: "success",
6373
+ data: [message, info],
6374
+ timestamp: Date.now()
6375
+ });
6376
+ });
6377
+ events.on("warn", (message, info) => {
6378
+ sendDataMessage({
6379
+ type: "warn",
6380
+ data: [message, info],
6381
+ timestamp: Date.now()
6382
+ });
6383
+ });
6384
+ events.on("generation:start", (config) => {
6385
+ var _a;
6386
+ sendDataMessage({
6387
+ type: "generation:start",
6388
+ data: [
6389
+ {
6390
+ name: config.name,
6391
+ plugins: ((_a = config.plugins) == null ? void 0 : _a.length) || 0
6392
+ }
6393
+ ],
6394
+ timestamp: Date.now()
6395
+ });
6396
+ });
6397
+ events.on("generation:end", (config, files, sources) => {
6398
+ const sourcesRecord = {};
6399
+ sources.forEach((value, key) => {
6400
+ sourcesRecord[key] = value;
6401
+ });
6402
+ sendDataMessage({
6403
+ type: "generation:end",
6404
+ data: [config, files, sourcesRecord],
6405
+ timestamp: Date.now()
6406
+ });
6407
+ });
6408
+ events.on("error", (error) => {
6409
+ sendDataMessage({
6410
+ type: "error",
6411
+ data: [
6412
+ {
6413
+ message: error.message,
6414
+ stack: error.stack
6415
+ }
6416
+ ],
6417
+ timestamp: Date.now()
6418
+ });
6419
+ });
6219
6420
  }
6220
6421
 
6221
- let initialized = false;
6222
- const _nKEgeY = defineEventHandler(async () => {
6223
- if (!initialized) {
6224
- initialized = true;
6422
+ var version = "4.25.1";
6423
+
6424
+ const _zcw7I4pYH8OiCfaDcjy_x7I6IH1tLDQR3W_yRZgP6E = defineNitroPlugin(async (nitro) => {
6425
+ const studioUrl = process$1.env.KUBB_STUDIO_URL || "https://studio.kubb.dev";
6426
+ const token = process$1.env.KUBB_AGENT_TOKEN;
6427
+ const configPath = process$1.env.KUBB_CONFIG || "kubb.config.ts";
6428
+ const noCache = process$1.env.KUBB_AGENT_NO_CACHE === "true";
6429
+ const retryInterval = process$1.env.KUBB_RETRY_TIMEOUT ? Number.parseInt(process$1.env.KUBB_RETRY_TIMEOUT, 10) : 3e4;
6430
+ if (!token) {
6431
+ logger.warn("KUBB_AGENT_TOKEN not set", "cannot authenticate with studio");
6432
+ return null;
6433
+ }
6434
+ const result = await getCosmiConfig(configPath);
6435
+ const configs = await getConfigs(result.config, {});
6436
+ if (configs.length === 0) {
6437
+ throw new Error("No configs found");
6438
+ }
6439
+ const config = configs[0];
6440
+ const events = new AsyncEventEmitter();
6441
+ const wsOptions = {
6442
+ headers: {
6443
+ Authorization: `Bearer ${token}`
6444
+ }
6445
+ };
6446
+ const root = process$1.env.KUBB_ROOT || config.root || process$1.cwd();
6447
+ events.on("hook:start", async ({ id, command, args }) => {
6448
+ const commandWithArgs = (args == null ? void 0 : args.length) ? `${command} ${args.join(" ")}` : command;
6449
+ if (!id) {
6450
+ return;
6451
+ }
6225
6452
  try {
6226
- const configPath = process.env.KUBB_CONFIG;
6227
- if (!configPath) {
6228
- throw new Error("KUBB_CONFIG environment variable not set");
6229
- }
6230
- const events = new AsyncEventEmitter();
6231
- const logLevel = LogLevel.info;
6232
- const result = await getCosmiConfig(configPath);
6233
- const configs = await getConfigs(result);
6234
- if (configs.length === 0) {
6235
- throw new Error("No configs found");
6236
- }
6237
- const config = configs[0];
6238
- const onGenerate = async () => {
6239
- await generate({
6240
- config,
6241
- events,
6242
- logLevel
6243
- });
6453
+ const result2 = await execa(command, args, {
6454
+ cwd: root,
6455
+ detached: true,
6456
+ stripFinalNewline: true
6457
+ });
6458
+ console.log(result2.stdout);
6459
+ await events.emit("hook:end", {
6460
+ command,
6461
+ args,
6462
+ id,
6463
+ success: true,
6464
+ error: null
6465
+ });
6466
+ } catch (_err) {
6467
+ const errorMessage = new Error(`Hook execute failed: ${commandWithArgs}`);
6468
+ await events.emit("hook:end", {
6469
+ command,
6470
+ args,
6471
+ id,
6472
+ success: false,
6473
+ error: errorMessage
6474
+ });
6475
+ await events.emit("error", errorMessage);
6476
+ }
6477
+ });
6478
+ async function reconnectToStudio() {
6479
+ logger.info(`Retrying connection in ${formatMs(retryInterval)} to Kubb Studio ...`);
6480
+ setTimeout(async () => {
6481
+ await connectToStudio();
6482
+ }, retryInterval);
6483
+ }
6484
+ async function connectToStudio() {
6485
+ try {
6486
+ const { sessionToken, wsUrl } = await createAgentSession({ noCache, token, studioUrl });
6487
+ const ws = createWebsocket(wsUrl, wsOptions);
6488
+ const onError = async () => {
6489
+ cleanup();
6490
+ logger.error(`Failed to connect to Kubb Studio on "${wsUrl}"`);
6491
+ const cachedSession = !noCache ? getCachedSession(token) : null;
6492
+ if (cachedSession) {
6493
+ deleteCachedSession(token);
6494
+ await reconnectToStudio();
6495
+ }
6244
6496
  };
6245
- const context = {
6246
- config,
6247
- events,
6248
- onGenerate
6497
+ const onOpen = () => {
6498
+ logger.success(`Connected to Kubb Studio on "${wsUrl}"`);
6249
6499
  };
6250
- setGlobalContext(context);
6251
- } catch (error) {
6252
- console.error("Failed to initialize Kubb agent context:", error);
6253
- throw error;
6500
+ const onClose = async () => {
6501
+ cleanup();
6502
+ logger.info("Disconnecting from Studio ...");
6503
+ if (sessionToken) {
6504
+ await disconnect({
6505
+ sessionToken,
6506
+ studioUrl,
6507
+ token
6508
+ }).catch(async () => {
6509
+ deleteCachedSession(token);
6510
+ await reconnectToStudio();
6511
+ });
6512
+ }
6513
+ };
6514
+ const cleanup = () => {
6515
+ ws.removeEventListener("open", onOpen);
6516
+ ws.removeEventListener("close", onClose);
6517
+ ws.removeEventListener("error", onError);
6518
+ };
6519
+ ws.addEventListener("open", onOpen);
6520
+ ws.addEventListener("close", onClose);
6521
+ ws.addEventListener("error", onError);
6522
+ nitro.hooks.hook("close", onClose);
6523
+ setInterval(() => {
6524
+ sendAgentMessage(ws, {
6525
+ type: "ping"
6526
+ });
6527
+ }, 3e4);
6528
+ setupEventsStream(ws, events);
6529
+ ws.addEventListener("message", async (message) => {
6530
+ var _a;
6531
+ const data = JSON.parse(message.data);
6532
+ if (isCommandMessage(data)) {
6533
+ if (data.command === "generate") {
6534
+ await generate({
6535
+ config: {
6536
+ ...config,
6537
+ root
6538
+ },
6539
+ events
6540
+ });
6541
+ logger.success("Generated command success");
6542
+ }
6543
+ if (data.command === "connect") {
6544
+ let specContent;
6545
+ if (config && "path" in config.input) {
6546
+ const specPath = path$1.resolve(process$1.cwd(), config.root, config.input.path);
6547
+ try {
6548
+ specContent = readFileSync(specPath, "utf-8");
6549
+ } catch {
6550
+ }
6551
+ }
6552
+ sendAgentMessage(ws, {
6553
+ type: "connected",
6554
+ payload: {
6555
+ version,
6556
+ configPath: process$1.env.KUBB_CONFIG || "",
6557
+ spec: specContent,
6558
+ config: {
6559
+ name: config.name,
6560
+ root: config.root,
6561
+ input: {
6562
+ path: "path" in config.input ? config.input.path : void 0
6563
+ },
6564
+ output: {
6565
+ path: config.output.path,
6566
+ write: config.output.write,
6567
+ extension: config.output.extension,
6568
+ barrelType: config.output.barrelType
6569
+ },
6570
+ plugins: (_a = config.plugins) == null ? void 0 : _a.map((plugin) => ({
6571
+ name: `@kubb/${plugin.name}`,
6572
+ options: serializePluginOptions(plugin.options)
6573
+ }))
6574
+ }
6575
+ }
6576
+ });
6577
+ }
6578
+ return;
6579
+ }
6580
+ logger.warn(`Unknown message type from Kubb Studio: ${message.data}`);
6581
+ });
6582
+ } catch (_error) {
6583
+ deleteCachedSession(token);
6584
+ await reconnectToStudio();
6254
6585
  }
6255
6586
  }
6587
+ await connectToStudio();
6256
6588
  });
6257
6589
 
6258
- const _lazy_df2682 = () => import('../routes/api/generate.options.mjs');
6259
- const _lazy_nU_FW7 = () => import('../routes/api/generate.post.mjs');
6590
+ const plugins = [
6591
+ _zcw7I4pYH8OiCfaDcjy_x7I6IH1tLDQR3W_yRZgP6E
6592
+ ];
6593
+
6260
6594
  const _lazy_RdtMCE = () => import('../routes/api/health.get.mjs');
6261
- const _lazy_WDQCDr = () => import('../routes/api/info.get.mjs');
6262
6595
 
6263
6596
  const handlers = [
6264
- { route: '', handler: _nKEgeY, lazy: false, middleware: true, method: undefined },
6265
- { route: '/api/generate', handler: _lazy_df2682, lazy: true, middleware: false, method: "options" },
6266
- { route: '/api/generate', handler: _lazy_nU_FW7, lazy: true, middleware: false, method: "post" },
6267
- { route: '/api/health', handler: _lazy_RdtMCE, lazy: true, middleware: false, method: "get" },
6268
- { route: '/api/info', handler: _lazy_WDQCDr, lazy: true, middleware: false, method: "get" }
6597
+ { route: '/api/health', handler: _lazy_RdtMCE, lazy: true, middleware: false, method: "get" }
6269
6598
  ];
6270
6599
 
6271
6600
  function createNitroApp() {
@@ -6681,5 +7010,5 @@ trapUnhandledNodeErrors();
6681
7010
  setupGracefulShutdown(listener, nitroApp);
6682
7011
  const nodeServer = {};
6683
7012
 
6684
- export { serializePluginOptions as a, defineEventHandler as d, nodeServer as n, setHeaders as s, useKubbAgentContext as u };
7013
+ export { defineEventHandler as d, nodeServer as n, version as v };
6685
7014
  //# sourceMappingURL=nitro.mjs.map