@coze/cli 0.1.0-alpha.5276dd → 0.1.0-alpha.f2dd23

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/lib/cli.js CHANGED
@@ -1,12 +1,14 @@
1
1
  #!/usr/bin/env node
2
2
  'use strict';
3
3
 
4
- const index = require('./index-CFBaehnq.js');
4
+ const index = require('./index-SwtgDxQR.js');
5
+ const chalk = require('chalk');
6
+ const node_child_process = require('node:child_process');
5
7
  const fs = require('node:fs/promises');
6
8
  const os = require('node:os');
7
9
  const path = require('node:path');
10
+ const undici = require('undici');
8
11
  const node_fs = require('node:fs');
9
- const chalk = require('chalk');
10
12
  const path$1 = require('path');
11
13
  const promises = require('fs/promises');
12
14
  const require$$0 = require('fs');
@@ -28,7 +30,6 @@ require('tty');
28
30
  require('os');
29
31
  require('zlib');
30
32
  require('events');
31
- require('undici');
32
33
 
33
34
  function _interopNamespaceDefault(e) {
34
35
  const n = Object.create(null);
@@ -121,6 +122,372 @@ const handleCliError = (error, ctx) => {
121
122
  process.exit(cozeError.code);
122
123
  };
123
124
 
125
+ function _nullishCoalesce$l(lhs, rhsFn) { if (lhs != null) { return lhs; } else { return rhsFn(); } }
126
+
127
+
128
+
129
+
130
+
131
+
132
+
133
+
134
+
135
+
136
+
137
+
138
+
139
+
140
+
141
+
142
+
143
+
144
+
145
+
146
+
147
+
148
+
149
+
150
+ const GLOBAL_CONFIG_DIR = path__namespace.join(os__namespace.homedir(), '.coze');
151
+ const GLOBAL_CONFIG_FILE = path__namespace.join(GLOBAL_CONFIG_DIR, 'config.json');
152
+ const LOCAL_CONFIG_FILE = path__namespace.join(process.cwd(), '.cozerc.json');
153
+
154
+ const DEFAULT_CONFIG = {
155
+ apiBaseUrl: 'https://code.coze.cn/',
156
+ openApiBaseUrl: 'https://api.coze.cn',
157
+ integrationApiBaseUrl: 'https://integration.coze.cn',
158
+ clientId: '95438868623436343239609434490626.app.coze',
159
+ defaultOutputFormat: 'json',
160
+ // 当前测试使用,后续会根据环境变量动态切换
161
+ xTTEnv: 'ppe_coze_cli',
162
+ };
163
+
164
+ async function readJsonIfExists(file) {
165
+ try {
166
+ const content = await fs__namespace.readFile(file, 'utf8');
167
+ return JSON.parse(content) ;
168
+ } catch (e) {
169
+ return undefined;
170
+ }
171
+ }
172
+
173
+ /**
174
+ * 从环境变量中获取配置
175
+ * 环境变量的优先级最高,会覆盖配置文件中的设置
176
+ *
177
+ * 支持的环境变量:
178
+ * - COZE_API_TOKEN -> accessToken
179
+ * - COZE_ORG_ID -> organizationId
180
+ * - COZE_ENTERPRISE_ID -> enterpriseId
181
+ * - COZE_SPACE_ID -> spaceId
182
+ * - COZE_CONFIG_SCOPE -> configScope ('global' | 'local')
183
+ */
184
+ function getEnvConfig() {
185
+ const envConfig = {};
186
+ if (process.env.COZE_API_TOKEN) {
187
+ envConfig.accessToken = process.env.COZE_API_TOKEN;
188
+ }
189
+ if (process.env.COZE_ORG_ID) {
190
+ envConfig.organizationId = process.env.COZE_ORG_ID;
191
+ }
192
+ if (process.env.COZE_ENTERPRISE_ID) {
193
+ envConfig.enterpriseId = process.env.COZE_ENTERPRISE_ID;
194
+ }
195
+ if (process.env.COZE_SPACE_ID) {
196
+ envConfig.spaceId = process.env.COZE_SPACE_ID;
197
+ }
198
+ if (
199
+ process.env.COZE_CONFIG_SCOPE === 'global' ||
200
+ process.env.COZE_CONFIG_SCOPE === 'local'
201
+ ) {
202
+ envConfig.configScope = process.env.COZE_CONFIG_SCOPE;
203
+ }
204
+ return envConfig;
205
+ }
206
+
207
+ /**
208
+ * 加载 CLI 配置
209
+ * 配置加载优先级(从高到低):
210
+ * 1. 环境变量 (Environment Variables)
211
+ * 2. 命令行指定的配置文件 (Custom Config)
212
+ * 3. 项目级配置文件 (.cozerc.json)
213
+ * 4. 全局配置文件 (~/.coze/config.json)
214
+ * 5. 默认配置 (DEFAULT_CONFIG)
215
+ *
216
+ * @param configPath 自定义配置文件路径
217
+ */
218
+ async function loadConfig(configPath) {
219
+ const [globalConfig, localConfig, customConfig] = await Promise.all([
220
+ readJsonIfExists(GLOBAL_CONFIG_FILE),
221
+ readJsonIfExists(LOCAL_CONFIG_FILE),
222
+ configPath ? readJsonIfExists(configPath) : undefined,
223
+ ]);
224
+
225
+ const envConfig = getEnvConfig();
226
+
227
+ return {
228
+ ...DEFAULT_CONFIG,
229
+ ...globalConfig,
230
+ ...localConfig,
231
+ ...customConfig,
232
+ ...envConfig,
233
+ };
234
+ }
235
+
236
+ /**
237
+ * 保存配置到文件
238
+ *
239
+ * @param config 要保存的配置项(支持部分更新)
240
+ * @param scope 配置作用域:
241
+ * - 'global': 保存到用户主目录 (~/.coze/config.json)
242
+ * - 'local': 保存到当前工作目录 (.cozerc.json)
243
+ */
244
+ async function saveConfig(
245
+ config,
246
+ scope = _nullishCoalesce$l(getEnvConfig().configScope, () => ( 'global')),
247
+ ) {
248
+ const targetFile =
249
+ scope === 'global' ? GLOBAL_CONFIG_FILE : LOCAL_CONFIG_FILE;
250
+ const targetDir = path__namespace.dirname(targetFile);
251
+
252
+ try {
253
+ await fs__namespace.mkdir(targetDir, { recursive: true });
254
+
255
+ const existingConfig =
256
+ (await readJsonIfExists(targetFile)) || {};
257
+ const newConfig = { ...existingConfig, ...config };
258
+
259
+ await fs__namespace.writeFile(targetFile, JSON.stringify(newConfig, null, 2), 'utf8');
260
+ } catch (error) {
261
+ throw new Error(`Failed to save config to ${targetFile}: ${error}`);
262
+ }
263
+ }
264
+
265
+ /**
266
+ * 删除指定的配置项
267
+ * 优先从 local 删除,如果 local 中没有,则从 global 删除
268
+ *
269
+ * @param key 要删除的配置键
270
+ */
271
+ async function deleteConfig(key) {
272
+ let targetFile = LOCAL_CONFIG_FILE;
273
+ let existingConfig = await readJsonIfExists(targetFile);
274
+
275
+ if (!existingConfig || !(key in existingConfig)) {
276
+ targetFile = GLOBAL_CONFIG_FILE;
277
+ existingConfig = await readJsonIfExists(targetFile);
278
+ }
279
+
280
+ if (!existingConfig || !(key in existingConfig)) {
281
+ return; // Config doesn't exist in local or global, nothing to delete
282
+ }
283
+
284
+ try {
285
+ delete existingConfig[key];
286
+ await fs__namespace.writeFile(
287
+ targetFile,
288
+ JSON.stringify(existingConfig, null, 2),
289
+ 'utf8',
290
+ );
291
+ } catch (error) {
292
+ throw new Error(`Failed to delete config from ${targetFile}: ${error}`);
293
+ }
294
+ }
295
+
296
+
297
+
298
+
299
+
300
+
301
+
302
+ /**
303
+ * 获取所有配置项的详细信息(包含来源)
304
+ */
305
+ async function listConfigs() {
306
+ const [globalConfig, localConfig] = await Promise.all([
307
+ readJsonIfExists(GLOBAL_CONFIG_FILE),
308
+ readJsonIfExists(LOCAL_CONFIG_FILE),
309
+ ]);
310
+
311
+ const envConfig = getEnvConfig();
312
+ const allKeys = new Set([
313
+ ...Object.keys(DEFAULT_CONFIG),
314
+ ...Object.keys(globalConfig || {}),
315
+ ...Object.keys(localConfig || {}),
316
+ ...Object.keys(envConfig),
317
+ ]);
318
+
319
+ const result = [];
320
+
321
+ for (const key of Array.from(allKeys)) {
322
+ const k = key ;
323
+ let value;
324
+ let source = 'default';
325
+
326
+ if (k in envConfig && envConfig[k ] !== undefined) {
327
+ value = envConfig[k ];
328
+ source = 'env';
329
+ } else if (
330
+ localConfig &&
331
+ k in localConfig &&
332
+ localConfig[k] !== undefined
333
+ ) {
334
+ value = String(localConfig[k]);
335
+ source = 'local';
336
+ } else if (
337
+ globalConfig &&
338
+ k in globalConfig &&
339
+ globalConfig[k] !== undefined
340
+ ) {
341
+ value = String(globalConfig[k]);
342
+ source = 'global';
343
+ } else if (k in DEFAULT_CONFIG) {
344
+ value = String(DEFAULT_CONFIG[k ]);
345
+ source = 'default';
346
+ }
347
+
348
+ result.push({ key, value, source });
349
+ }
350
+
351
+ return result;
352
+ }
353
+
354
+ var name = "@coze/cli";
355
+ var version = "0.1.0-alpha.f2dd23";
356
+ const packageJson = {
357
+ name: name,
358
+ version: version};
359
+
360
+ const PACKAGE_NAME = packageJson.name;
361
+ const DEFAULT_REGISTRY = 'https://registry.npmjs.org';
362
+ const HOURS_PER_DAY = 24;
363
+ const MINUTES_PER_HOUR = 60;
364
+ const SECONDS_PER_MINUTE = 60;
365
+ const MS_PER_SECOND = 1000;
366
+ const CHECK_INTERVAL_MS =
367
+ HOURS_PER_DAY * MINUTES_PER_HOUR * SECONDS_PER_MINUTE * MS_PER_SECOND;
368
+
369
+
370
+
371
+
372
+
373
+
374
+
375
+ function getCurrentVersion() {
376
+ return packageJson.version;
377
+ }
378
+
379
+ function compareVersions(current, latest) {
380
+ const parseSemver = (v) => {
381
+ const parts = v.replace(/^v/, '').split('.');
382
+ return {
383
+ major: parseInt(parts[0] || '0', 10),
384
+ minor: parseInt(parts[1] || '0', 10),
385
+ patch: parseInt(parts[2] || '0', 10),
386
+ };
387
+ };
388
+
389
+ const c = parseSemver(current);
390
+ const l = parseSemver(latest);
391
+
392
+ if (l.major !== c.major) {
393
+ return l.major > c.major;
394
+ }
395
+ if (l.minor !== c.minor) {
396
+ return l.minor > c.minor;
397
+ }
398
+ return l.patch > c.patch;
399
+ }
400
+
401
+ function getNpmRegistry() {
402
+ try {
403
+ return node_child_process.execSync('npm config get registry', {
404
+ encoding: 'utf8',
405
+ stdio: ['pipe', 'pipe', 'pipe'],
406
+ })
407
+ .trim()
408
+ .replace(/\/+$/, '');
409
+ } catch (e) {
410
+ return DEFAULT_REGISTRY;
411
+ }
412
+ }
413
+
414
+ async function fetchLatestVersion(
415
+ registryUrl,
416
+ tag = 'latest',
417
+ ) {
418
+ const url = `${registryUrl}/${PACKAGE_NAME}/${tag}`;
419
+ const response = await index.customFetch.fetch(url, {
420
+ headers: { accept: 'application/json' },
421
+ });
422
+
423
+ if (!response.ok) {
424
+ throw new Error(
425
+ `Failed to fetch latest version: ${response.status} ${response.statusText}`,
426
+ );
427
+ }
428
+
429
+ const data = (await response.json()) ;
430
+ return data.version;
431
+ }
432
+
433
+ async function checkForUpdates(
434
+ context,
435
+ forceCheck = false,
436
+ tag = 'latest',
437
+ ) {
438
+ const currentVersion = getCurrentVersion();
439
+ const { config } = context;
440
+
441
+ if (!forceCheck) {
442
+ if (
443
+ config.latestVersion &&
444
+ config.lastCheckTime &&
445
+ Date.now() - config.lastCheckTime < CHECK_INTERVAL_MS
446
+ ) {
447
+ return {
448
+ currentVersion,
449
+ latestVersion: config.latestVersion,
450
+ hasUpdate: compareVersions(currentVersion, config.latestVersion),
451
+ };
452
+ }
453
+ }
454
+
455
+ const registryUrl = getNpmRegistry();
456
+ const latestVersion = await fetchLatestVersion(registryUrl, tag);
457
+
458
+ await saveConfig(
459
+ { latestVersion, lastCheckTime: Date.now() },
460
+ config.configScope,
461
+ );
462
+
463
+ return {
464
+ currentVersion,
465
+ latestVersion,
466
+ hasUpdate: compareVersions(currentVersion, latestVersion),
467
+ };
468
+ }
469
+
470
+ async function updateCheckMiddleware(
471
+ context,
472
+ next,
473
+ ) {
474
+ await next();
475
+
476
+ try {
477
+ const result = await checkForUpdates(context);
478
+
479
+ if (result.hasUpdate) {
480
+ const message =
481
+ `\nUpdate available: ${chalk.gray(result.currentVersion)} → ${chalk.green(result.latestVersion)}` +
482
+ `\nRun ${chalk.cyan('coze upgrade')} to update\n`;
483
+ context.ui.info(message);
484
+ }
485
+ // eslint-disable-next-line @coze-arch/no-empty-catch -- update check failure is non-critical
486
+ } catch (_error) {
487
+ /* noop */
488
+ }
489
+ }
490
+
124
491
  async function requestMiddleware(
125
492
  context,
126
493
  next,
@@ -129,10 +496,18 @@ async function requestMiddleware(
129
496
 
130
497
  index.axiosInstance.defaults.baseURL = context.config.apiBaseUrl;
131
498
  // axiosInstance.defaults.headers.cookie = token || '';
132
- index.axiosInstance.defaults.headers.Authorization = `Bearer ${token}`;
499
+ const tokenInHeader = `Bearer ${token}`;
500
+ index.axiosInstance.defaults.headers.Authorization = tokenInHeader;
501
+ index.customFetch.setHeaders({
502
+ Authorization: tokenInHeader,
503
+ });
133
504
  if (context.config.xTTEnv) {
134
505
  index.axiosInstance.defaults.headers['x-use-ppe'] = '1';
135
506
  index.axiosInstance.defaults.headers['x-tt-env'] = context.config.xTTEnv;
507
+ index.customFetch.setHeaders({
508
+ 'x-use-ppe': '1',
509
+ 'x-tt-env': context.config.xTTEnv,
510
+ });
136
511
  }
137
512
 
138
513
  await next();
@@ -434,8 +809,9 @@ const proxyMiddleware = async (
434
809
  const httpsProxy = process.env.HTTPS_PROXY || process.env.https_proxy;
435
810
 
436
811
  if (httpsProxy || httpProxy) {
812
+ const dispatcher = new undici.EnvHttpProxyAgent();
813
+ index.customFetch.setDispatcher(dispatcher);
437
814
  // 动态导入 ESM 模块
438
-
439
815
  const [{ HttpProxyAgent }, { HttpsProxyAgent }] = await Promise.all([
440
816
  import('http-proxy-agent'),
441
817
  import('https-proxy-agent'),
@@ -458,203 +834,6 @@ const proxyMiddleware = async (
458
834
  await next();
459
835
  };
460
836
 
461
- const GLOBAL_CONFIG_DIR = path__namespace.join(os__namespace.homedir(), '.coze');
462
- const GLOBAL_CONFIG_FILE = path__namespace.join(GLOBAL_CONFIG_DIR, 'config.json');
463
- const LOCAL_CONFIG_FILE = path__namespace.join(process.cwd(), '.cozerc.json');
464
-
465
- const DEFAULT_CONFIG = {
466
- apiBaseUrl: 'https://code.coze.cn/',
467
- openApiBaseUrl: 'https://api.coze.cn',
468
- integrationApiBaseUrl: 'https://integration.coze.cn',
469
- clientId: '95438868623436343239609434490626.app.coze',
470
- defaultOutputFormat: 'json',
471
- // 当前测试使用,后续会根据环境变量动态切换
472
- xTTEnv: 'ppe_coze_cli',
473
- };
474
-
475
- async function readJsonIfExists(file) {
476
- try {
477
- const content = await fs__namespace.readFile(file, 'utf8');
478
- return JSON.parse(content) ;
479
- } catch (e) {
480
- return undefined;
481
- }
482
- }
483
-
484
- /**
485
- * 从环境变量中获取配置
486
- * 环境变量的优先级最高,会覆盖配置文件中的设置
487
- *
488
- * 支持的环境变量:
489
- * - COZE_API_TOKEN -> accessToken
490
- * - COZE_ORG_ID -> organizationId
491
- * - COZE_ENTERPRISE_ID -> enterpriseId
492
- * - COZE_SPACE_ID -> spaceId
493
- */
494
- function getEnvConfig() {
495
- const envConfig = {};
496
- if (process.env.COZE_API_TOKEN) {
497
- envConfig.accessToken = process.env.COZE_API_TOKEN;
498
- }
499
- if (process.env.COZE_ORG_ID) {
500
- envConfig.organizationId = process.env.COZE_ORG_ID;
501
- }
502
- if (process.env.COZE_ENTERPRISE_ID) {
503
- envConfig.enterpriseId = process.env.COZE_ENTERPRISE_ID;
504
- }
505
- if (process.env.COZE_SPACE_ID) {
506
- envConfig.spaceId = process.env.COZE_SPACE_ID;
507
- }
508
- return envConfig;
509
- }
510
-
511
- /**
512
- * 加载 CLI 配置
513
- * 配置加载优先级(从高到低):
514
- * 1. 环境变量 (Environment Variables)
515
- * 2. 命令行指定的配置文件 (Custom Config)
516
- * 3. 项目级配置文件 (.cozerc.json)
517
- * 4. 全局配置文件 (~/.coze/config.json)
518
- * 5. 默认配置 (DEFAULT_CONFIG)
519
- *
520
- * @param configPath 自定义配置文件路径
521
- */
522
- async function loadConfig(configPath) {
523
- const [globalConfig, localConfig, customConfig] = await Promise.all([
524
- readJsonIfExists(GLOBAL_CONFIG_FILE),
525
- readJsonIfExists(LOCAL_CONFIG_FILE),
526
- configPath ? readJsonIfExists(configPath) : undefined,
527
- ]);
528
-
529
- const envConfig = getEnvConfig();
530
-
531
- return {
532
- ...DEFAULT_CONFIG,
533
- ...globalConfig,
534
- ...localConfig,
535
- ...customConfig,
536
- ...envConfig,
537
- };
538
- }
539
-
540
- /**
541
- * 保存配置到文件
542
- *
543
- * @param config 要保存的配置项(支持部分更新)
544
- * @param scope 配置作用域:
545
- * - 'global': 保存到用户主目录 (~/.coze/config.json)
546
- * - 'local': 保存到当前工作目录 (.cozerc.json)
547
- */
548
- async function saveConfig(
549
- config,
550
- scope = 'global',
551
- ) {
552
- const targetFile =
553
- scope === 'global' ? GLOBAL_CONFIG_FILE : LOCAL_CONFIG_FILE;
554
- const targetDir = path__namespace.dirname(targetFile);
555
-
556
- try {
557
- await fs__namespace.mkdir(targetDir, { recursive: true });
558
-
559
- const existingConfig =
560
- (await readJsonIfExists(targetFile)) || {};
561
- const newConfig = { ...existingConfig, ...config };
562
-
563
- await fs__namespace.writeFile(targetFile, JSON.stringify(newConfig, null, 2), 'utf8');
564
- } catch (error) {
565
- throw new Error(`Failed to save config to ${targetFile}: ${error}`);
566
- }
567
- }
568
-
569
- /**
570
- * 删除指定的配置项
571
- * 优先从 local 删除,如果 local 中没有,则从 global 删除
572
- *
573
- * @param key 要删除的配置键
574
- */
575
- async function deleteConfig(key) {
576
- let targetFile = LOCAL_CONFIG_FILE;
577
- let existingConfig = await readJsonIfExists(targetFile);
578
-
579
- if (!existingConfig || !(key in existingConfig)) {
580
- targetFile = GLOBAL_CONFIG_FILE;
581
- existingConfig = await readJsonIfExists(targetFile);
582
- }
583
-
584
- if (!existingConfig || !(key in existingConfig)) {
585
- return; // Config doesn't exist in local or global, nothing to delete
586
- }
587
-
588
- try {
589
- delete existingConfig[key];
590
- await fs__namespace.writeFile(
591
- targetFile,
592
- JSON.stringify(existingConfig, null, 2),
593
- 'utf8',
594
- );
595
- } catch (error) {
596
- throw new Error(`Failed to delete config from ${targetFile}: ${error}`);
597
- }
598
- }
599
-
600
-
601
-
602
-
603
-
604
-
605
-
606
- /**
607
- * 获取所有配置项的详细信息(包含来源)
608
- */
609
- async function listConfigs() {
610
- const [globalConfig, localConfig] = await Promise.all([
611
- readJsonIfExists(GLOBAL_CONFIG_FILE),
612
- readJsonIfExists(LOCAL_CONFIG_FILE),
613
- ]);
614
-
615
- const envConfig = getEnvConfig();
616
- const allKeys = new Set([
617
- ...Object.keys(DEFAULT_CONFIG),
618
- ...Object.keys(globalConfig || {}),
619
- ...Object.keys(localConfig || {}),
620
- ...Object.keys(envConfig),
621
- ]);
622
-
623
- const result = [];
624
-
625
- for (const key of Array.from(allKeys)) {
626
- const k = key ;
627
- let value;
628
- let source = 'default';
629
-
630
- if (k in envConfig && envConfig[k ] !== undefined) {
631
- value = envConfig[k ];
632
- source = 'env';
633
- } else if (
634
- localConfig &&
635
- k in localConfig &&
636
- localConfig[k] !== undefined
637
- ) {
638
- value = String(localConfig[k]);
639
- source = 'local';
640
- } else if (
641
- globalConfig &&
642
- k in globalConfig &&
643
- globalConfig[k] !== undefined
644
- ) {
645
- value = String(globalConfig[k]);
646
- source = 'global';
647
- } else if (k in DEFAULT_CONFIG) {
648
- value = String(DEFAULT_CONFIG[k ]);
649
- source = 'default';
650
- }
651
-
652
- result.push({ key, value, source });
653
- }
654
-
655
- return result;
656
- }
657
-
658
837
  function compose(middlewares) {
659
838
  if (!Array.isArray(middlewares)) {
660
839
  throw new TypeError('Middleware stack must be an array!');
@@ -692,1194 +871,384 @@ function compose(middlewares) {
692
871
  };
693
872
  }
694
873
 
695
- function _nullishCoalesce$k(lhs, rhsFn) { if (lhs != null) { return lhs; } else { return rhsFn(); } } function _optionalChain$J(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = fn(value); } else if (op === 'call' || op === 'optionalCall') { value = fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; }
696
-
874
+ // THIS IS AN AUTOGENERATED FILE. DO NOT EDIT THIS FILE DIRECTLY.
875
+ /* eslint-disable */
876
+ /* tslint:disable */
877
+ // @ts-nocheck
697
878
 
879
+
698
880
 
881
+ var AppAndPATAuthInfoItemType; (function (AppAndPATAuthInfoItemType) {
882
+ const app = 'app'; AppAndPATAuthInfoItemType["app"] = app;
883
+ const pat = 'pat'; AppAndPATAuthInfoItemType["pat"] = pat;
884
+ })(AppAndPATAuthInfoItemType || (AppAndPATAuthInfoItemType = {}));
699
885
 
886
+ var ApplicationForEnterpriseMemberStatus; (function (ApplicationForEnterpriseMemberStatus) {
887
+ const can_apply2 = 'CanApply'; ApplicationForEnterpriseMemberStatus["can_apply2"] = can_apply2;
888
+ const already_applied2 = 'AlreadyApplied'; ApplicationForEnterpriseMemberStatus["already_applied2"] = already_applied2;
889
+ const joined4 = 'Joined'; ApplicationForEnterpriseMemberStatus["joined4"] = joined4;
890
+ const deny3 = 'Deny'; ApplicationForEnterpriseMemberStatus["deny3"] = deny3;
891
+ })(ApplicationForEnterpriseMemberStatus || (ApplicationForEnterpriseMemberStatus = {}));
700
892
 
893
+ var ApplicationStatus; (function (ApplicationStatus) {
894
+ const processing = 'Processing'; ApplicationStatus["processing"] = processing;
895
+ const approved = 'Approved'; ApplicationStatus["approved"] = approved;
896
+ const rejected = 'Rejected'; ApplicationStatus["rejected"] = rejected;
897
+ })(ApplicationStatus || (ApplicationStatus = {}));
701
898
 
899
+ var AppType; (function (AppType) {
900
+ const normal = 'Normal'; AppType["normal"] = normal;
901
+ const connector = 'Connector'; AppType["connector"] = connector;
902
+ const privilege = 'Privilege'; AppType["privilege"] = privilege;
903
+ })(AppType || (AppType = {}));
702
904
 
905
+ var AuthorizationType; (function (AuthorizationType) {
906
+ const auth_app = 'AuthApp'; AuthorizationType["auth_app"] = auth_app;
907
+ const on_behalf_of_user = 'OnBehalfOfUser'; AuthorizationType["on_behalf_of_user"] = on_behalf_of_user;
908
+ })(AuthorizationType || (AuthorizationType = {}));
703
909
 
910
+ var AuthProvider; (function (AuthProvider) {
911
+ const password = 'Password'; AuthProvider["password"] = password;
912
+ const sms = 'Sms'; AuthProvider["sms"] = sms;
913
+ const email = 'Email'; AuthProvider["email"] = email;
914
+ const unknown3 = 'Unknown'; AuthProvider["unknown3"] = unknown3;
915
+ })(AuthProvider || (AuthProvider = {}));
704
916
 
917
+ var AuthStatus; (function (AuthStatus) {
918
+ const authorized = 'authorized'; AuthStatus["authorized"] = authorized;
919
+ const unauthorized = 'unauthorized'; AuthStatus["unauthorized"] = unauthorized;
920
+ const expired4 = 'expired'; AuthStatus["expired4"] = expired4;
921
+ })(AuthStatus || (AuthStatus = {}));
705
922
 
706
- const C = {
707
- reset: '\x1b[0m',
708
- bold: '\x1b[1m',
709
- dim: '\x1b[2m',
710
- red: '\x1b[31m',
711
- green: '\x1b[32m',
712
- yellow: '\x1b[33m',
713
- cyan: '\x1b[36m',
714
- silver: '\x1b[90m',
715
- };
923
+ var AuthType$1; (function (AuthType) {
924
+ const api_key = 'api_key'; AuthType["api_key"] = api_key;
925
+ const wechat_official = 'wechat_official'; AuthType["wechat_official"] = wechat_official;
926
+ const oauth_2 = 'oauth2'; AuthType["oauth_2"] = oauth_2;
927
+ })(AuthType$1 || (AuthType$1 = {}));
716
928
 
717
- const BADGES = {
718
- PROC: '[PROC]',
719
- INFO: '[INFO]',
720
- WARN: '[WARN]',
721
- ERR: '[ERR]',
722
- DONE: '[DONE]',
723
- DBG: '[DBG]',
724
- };
725
- const LEVEL_PRIORITY = {
726
- debug: 0,
727
- verbose: 1,
728
- info: 2,
729
- success: 3,
730
- warn: 4,
731
- error: 5,
732
- };
733
- function badge(text) {
734
- return `${C.dim}${C.bold}${text}${C.reset}`;
735
- }
736
- class UI {
737
-
738
-
739
-
740
-
741
-
929
+ var Certificated; (function (Certificated) {
930
+ const noncertificated = 'Noncertificated'; Certificated["noncertificated"] = noncertificated;
931
+ const certificated = 'Certificated'; Certificated["certificated"] = certificated;
932
+ })(Certificated || (Certificated = {}));
742
933
 
743
- constructor(
744
- log,
745
- format,
746
- level = 'info',
747
- ) {
748
- this.log = log;
749
- this.silent = format === 'json';
750
- this.useColor = this.detectColorSupport();
751
- this.level = level;
752
- this.levelPriority = _nullishCoalesce$k(LEVEL_PRIORITY[level], () => ( 2));
753
- }
934
+ var CertificationType; (function (CertificationType) {
935
+ const uncertified = 'Uncertified'; CertificationType["uncertified"] = uncertified;
936
+ const personal_certification = 'PersonalCertification'; CertificationType["personal_certification"] = personal_certification;
937
+ const enterprise_certification = 'EnterpriseCertification'; CertificationType["enterprise_certification"] = enterprise_certification;
938
+ })(CertificationType || (CertificationType = {}));
754
939
 
755
- detectColorSupport() {
756
- return _optionalChain$J([process, 'access', _ => _.stderr, 'optionalAccess', _2 => _2.isTTY]) === true && process.env.NO_COLOR === undefined;
757
- }
940
+ var ChecklistItemType; (function (ChecklistItemType) {
941
+ const obo = 'Obo'; ChecklistItemType["obo"] = obo;
942
+ const app_auth = 'AppAuth'; ChecklistItemType["app_auth"] = app_auth;
943
+ const personal_access_token = 'PersonalAccessToken'; ChecklistItemType["personal_access_token"] = personal_access_token;
944
+ })(ChecklistItemType || (ChecklistItemType = {}));
758
945
 
759
- paint(code, text) {
760
- return this.useColor ? `${code}${text}${C.reset}` : text;
761
- }
946
+ var ClientType; (function (ClientType) {
947
+ const legacy = 'Legacy'; ClientType["legacy"] = legacy;
948
+ const web_backend = 'WebBackend'; ClientType["web_backend"] = web_backend;
949
+ const single_page_or_native = 'SinglePageOrNative'; ClientType["single_page_or_native"] = single_page_or_native;
950
+ const terminal = 'Terminal'; ClientType["terminal"] = terminal;
951
+ const service = 'Service'; ClientType["service"] = service;
952
+ })(ClientType || (ClientType = {}));
762
953
 
763
- shouldOutput(methodLevel) {
764
- if (this.silent) {
765
- return false;
766
- }
767
- return LEVEL_PRIORITY[methodLevel] >= this.levelPriority;
768
- }
954
+ var CollaboratorType; (function (CollaboratorType) {
955
+ const bot_editor = 'BotEditor'; CollaboratorType["bot_editor"] = bot_editor;
956
+ const bot_developer = 'BotDeveloper'; CollaboratorType["bot_developer"] = bot_developer;
957
+ const bot_operator = 'BotOperator'; CollaboratorType["bot_operator"] = bot_operator;
958
+ })(CollaboratorType || (CollaboratorType = {}));
769
959
 
770
- verbose(msg, ...args) {
771
- this.log.verbose(msg, ...args);
772
- if (!this.shouldOutput('verbose')) {
773
- return;
774
- }
775
- process.stderr.write(`${badge(BADGES.PROC)} ${this.paint(C.cyan, msg)}\n`);
776
- }
960
+ var DeleteOrgResourceType; (function (DeleteOrgResourceType) {
961
+ const workspace = 'Workspace'; DeleteOrgResourceType["workspace"] = workspace;
962
+ const o_auth_app = 'OAuthApp'; DeleteOrgResourceType["o_auth_app"] = o_auth_app;
963
+ const authorized_o_auth_app = 'AuthorizedOAuthApp'; DeleteOrgResourceType["authorized_o_auth_app"] = authorized_o_auth_app;
964
+ const service_access_token = 'ServiceAccessToken'; DeleteOrgResourceType["service_access_token"] = service_access_token;
965
+ const personal_access_token2 = 'PersonalAccessToken'; DeleteOrgResourceType["personal_access_token2"] = personal_access_token2;
966
+ const connector2 = 'Connector'; DeleteOrgResourceType["connector2"] = connector2;
967
+ const normal_api_app = 'NormalApiApp'; DeleteOrgResourceType["normal_api_app"] = normal_api_app;
968
+ const connector_api_app = 'ConnectorApiApp'; DeleteOrgResourceType["connector_api_app"] = connector_api_app;
969
+ })(DeleteOrgResourceType || (DeleteOrgResourceType = {}));
777
970
 
778
- info(msg, ...args) {
779
- this.log.info(msg, ...args);
780
- if (!this.shouldOutput('info')) {
781
- return;
782
- }
783
- process.stderr.write(`${badge(BADGES.INFO)} ${this.paint(C.reset, msg)}\n`);
784
- }
971
+ var DenyType; (function (DenyType) {
972
+ const visitors_prohibited = 'VisitorsProhibited'; DenyType["visitors_prohibited"] = visitors_prohibited;
973
+ const guest_prohibited_by_invited_user_enterprise2 = 'GuestProhibitedByInvitedUserEnterprise'; DenyType["guest_prohibited_by_invited_user_enterprise2"] = guest_prohibited_by_invited_user_enterprise2;
974
+ const prohibited_by_custom_people_management = 'ProhibitedByCustomPeopleManagement'; DenyType["prohibited_by_custom_people_management"] = prohibited_by_custom_people_management;
975
+ })(DenyType || (DenyType = {}));
785
976
 
786
- warn(msg, ...args) {
787
- this.log.warn(msg, ...args);
788
- if (!this.shouldOutput('warn')) {
789
- return;
790
- }
791
- process.stderr.write(
792
- `${badge(BADGES.WARN)} ${this.paint(C.yellow, msg)}\n`,
793
- );
794
- }
977
+ var DeploymentEnv; (function (DeploymentEnv) {
978
+ const dev2 = 'DEV'; DeploymentEnv["dev2"] = dev2;
979
+ const prod2 = 'PROD'; DeploymentEnv["prod2"] = prod2;
980
+ })(DeploymentEnv || (DeploymentEnv = {}));
795
981
 
796
- error(msg, ...args) {
797
- this.log.error(msg, ...args);
798
- if (!this.shouldOutput('error')) {
799
- return;
800
- }
801
- process.stderr.write(`${badge(BADGES.ERR)} ${this.paint(C.red, msg)}\n`);
802
- }
982
+ var DurationDay; (function (DurationDay) {
983
+ const _1 = '1'; DurationDay["_1"] = _1;
984
+ const _30 = '30'; DurationDay["_30"] = _30;
985
+ const _90 = '90'; DurationDay["_90"] = _90;
986
+ const _180 = '180'; DurationDay["_180"] = _180;
987
+ const _365 = '365'; DurationDay["_365"] = _365;
988
+ const customize = 'customize'; DurationDay["customize"] = customize;
989
+ const permanent = 'permanent'; DurationDay["permanent"] = permanent;
990
+ })(DurationDay || (DurationDay = {}));
803
991
 
804
- success(msg, ...args) {
805
- this.log.success(msg, ...args);
806
- if (!this.shouldOutput('success')) {
807
- return;
808
- }
809
- process.stderr.write(`${badge(BADGES.DONE)} ${this.paint(C.green, msg)}\n`);
810
- }
992
+ var DurationDay2; (function (DurationDay2) {
993
+ const _12 = '1'; DurationDay2["_12"] = _12;
994
+ const _302 = '30'; DurationDay2["_302"] = _302;
995
+ const _902 = '90'; DurationDay2["_902"] = _902;
996
+ const _1802 = '180'; DurationDay2["_1802"] = _1802;
997
+ const _3652 = '365'; DurationDay2["_3652"] = _3652;
998
+ const customize2 = 'customize'; DurationDay2["customize2"] = customize2;
999
+ const permanent2 = 'permanent'; DurationDay2["permanent2"] = permanent2;
1000
+ })(DurationDay2 || (DurationDay2 = {}));
811
1001
 
812
- debug(msg, ...args) {
813
- this.log.debug(msg, ...args);
814
- if (!this.shouldOutput('debug')) {
815
- return;
816
- }
817
- process.stderr.write(`${badge(BADGES.DBG)} ${this.paint(C.silver, msg)}\n`);
818
- }
819
- }
1002
+ var EncryptionAlgorithmType; (function (EncryptionAlgorithmType) {
1003
+ const aes_256_gcm = 'AES-256-GCM'; EncryptionAlgorithmType["aes_256_gcm"] = aes_256_gcm;
1004
+ })(EncryptionAlgorithmType || (EncryptionAlgorithmType = {}));
820
1005
 
821
- class JsonFormatter {
822
- format(data) {
823
- const output = JSON.stringify(data, null, 2);
824
- return output.endsWith('\n') ? output : `${output}\n`;
825
- }
1006
+ var EncryptionConfigurationDataType; (function (EncryptionConfigurationDataType) {
1007
+ const conversation = 'Conversation'; EncryptionConfigurationDataType["conversation"] = conversation;
1008
+ const unknown = 'Unknown'; EncryptionConfigurationDataType["unknown"] = unknown;
1009
+ })(EncryptionConfigurationDataType || (EncryptionConfigurationDataType = {}));
826
1010
 
827
- formatError(error) {
828
- const errorObj = {
829
- name: error.name,
830
- message: error.message,
831
- code: error.code,
832
- details: error.details,
833
- };
834
- const output = JSON.stringify(errorObj, null, 2);
835
- return output.endsWith('\n') ? output : `${output}\n`;
836
- }
837
- }
1011
+ var EncryptionKeyStatus; (function (EncryptionKeyStatus) {
1012
+ const active3 = 'Active'; EncryptionKeyStatus["active3"] = active3;
1013
+ const inactive = 'Inactive'; EncryptionKeyStatus["inactive"] = inactive;
1014
+ })(EncryptionKeyStatus || (EncryptionKeyStatus = {}));
838
1015
 
839
- function _nullishCoalesce$j(lhs, rhsFn) { if (lhs != null) { return lhs; } else { return rhsFn(); } } function _optionalChain$I(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = fn(value); } else if (op === 'call' || op === 'optionalCall') { value = fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; }
1016
+ var EncryptionKeyType; (function (EncryptionKeyType) {
1017
+ const cloud_kms = 'CloudKMS'; EncryptionKeyType["cloud_kms"] = cloud_kms;
1018
+ EncryptionKeyType["default"] = 'Default';
1019
+ const unknown2 = 'Unknown'; EncryptionKeyType["unknown2"] = unknown2;
1020
+ })(EncryptionKeyType || (EncryptionKeyType = {}));
840
1021
 
1022
+ var EncryptSecretKeyType; (function (EncryptSecretKeyType) {
1023
+ const user_custom2 = 'user_custom'; EncryptSecretKeyType["user_custom2"] = user_custom2;
1024
+ const consumer3 = 'consumer'; EncryptSecretKeyType["consumer3"] = consumer3;
1025
+ })(EncryptSecretKeyType || (EncryptSecretKeyType = {}));
841
1026
 
1027
+ var EnterpriseRoleType; (function (EnterpriseRoleType) {
1028
+ const super_admin = 'SuperAdmin'; EnterpriseRoleType["super_admin"] = super_admin;
1029
+ const admin = 'Admin'; EnterpriseRoleType["admin"] = admin;
1030
+ const member = 'Member'; EnterpriseRoleType["member"] = member;
1031
+ const guest = 'Guest'; EnterpriseRoleType["guest"] = guest;
1032
+ })(EnterpriseRoleType || (EnterpriseRoleType = {}));
842
1033
 
1034
+ var EnterpriseSettingKey; (function (EnterpriseSettingKey) {
1035
+ const join_enterprise_share_link_expiration_time = 'JoinEnterpriseShareLinkExpirationTime'; EnterpriseSettingKey["join_enterprise_share_link_expiration_time"] = join_enterprise_share_link_expiration_time;
1036
+ const sso = 'SSO'; EnterpriseSettingKey["sso"] = sso;
1037
+ const forbid_guest_join_enterprise = 'ForbidGuestJoinEnterprise'; EnterpriseSettingKey["forbid_guest_join_enterprise"] = forbid_guest_join_enterprise;
1038
+ const forbid_member_join_other_enterprise = 'ForbidMemberJoinOtherEnterprise'; EnterpriseSettingKey["forbid_member_join_other_enterprise"] = forbid_member_join_other_enterprise;
1039
+ const replace_enterprise_logo = 'ReplaceEnterpriseLogo'; EnterpriseSettingKey["replace_enterprise_logo"] = replace_enterprise_logo;
1040
+ const forbid_custom_people_management = 'ForbidCustomPeopleManagement'; EnterpriseSettingKey["forbid_custom_people_management"] = forbid_custom_people_management;
1041
+ const forbid_coze_store_plugin_access = 'ForbidCozeStorePluginAccess'; EnterpriseSettingKey["forbid_coze_store_plugin_access"] = forbid_coze_store_plugin_access;
1042
+ const enterprise_member_listing_skill_coze_store = 'EnterpriseMemberListingSkillCozeStore'; EnterpriseSettingKey["enterprise_member_listing_skill_coze_store"] = enterprise_member_listing_skill_coze_store;
1043
+ const listing_skill_enterprise_store_audit = 'ListingSkillEnterpriseStoreAudit'; EnterpriseSettingKey["listing_skill_enterprise_store_audit"] = listing_skill_enterprise_store_audit;
1044
+ })(EnterpriseSettingKey || (EnterpriseSettingKey = {}));
843
1045
 
1046
+ var EnterpriseSettingValueType; (function (EnterpriseSettingValueType) {
1047
+ const string = 'String'; EnterpriseSettingValueType["string"] = string;
1048
+ const boolean = 'Boolean'; EnterpriseSettingValueType["boolean"] = boolean;
1049
+ const integer = 'Integer'; EnterpriseSettingValueType["integer"] = integer;
1050
+ const string_list = 'StringList'; EnterpriseSettingValueType["string_list"] = string_list;
1051
+ })(EnterpriseSettingValueType || (EnterpriseSettingValueType = {}));
844
1052
 
1053
+ var HandleLevel; (function (HandleLevel) {
1054
+ const must_handle = 'MustHandle'; HandleLevel["must_handle"] = must_handle;
1055
+ const no_need_handle = 'NoNeedHandle'; HandleLevel["no_need_handle"] = no_need_handle;
1056
+ })(HandleLevel || (HandleLevel = {}));
845
1057
 
1058
+ var InstallationStatus; (function (InstallationStatus) {
1059
+ const pending_review_app_auth = 'pending_review_app_auth'; InstallationStatus["pending_review_app_auth"] = pending_review_app_auth;
1060
+ const pending_review_app_obo = 'pending_review_app_obo'; InstallationStatus["pending_review_app_obo"] = pending_review_app_obo;
1061
+ const approved_app_auth = 'approved_app_auth'; InstallationStatus["approved_app_auth"] = approved_app_auth;
1062
+ const approved_app_obo = 'approved_app_obo'; InstallationStatus["approved_app_obo"] = approved_app_obo;
1063
+ })(InstallationStatus || (InstallationStatus = {}));
846
1064
 
1065
+ var InvitationDenyType; (function (InvitationDenyType) {
1066
+ const no_permission = 'NoPermission'; InvitationDenyType["no_permission"] = no_permission;
1067
+ const guest_prohibited_by_enterprise2 = 'GuestProhibitedByEnterprise'; InvitationDenyType["guest_prohibited_by_enterprise2"] = guest_prohibited_by_enterprise2;
1068
+ const guest_prohibited_by_invited_user_enterprise3 = 'GuestProhibitedByInvitedUserEnterprise'; InvitationDenyType["guest_prohibited_by_invited_user_enterprise3"] = guest_prohibited_by_invited_user_enterprise3;
1069
+ const guest_prohibited_by_custom_people_management = 'GuestProhibitedByCustomPeopleManagement'; InvitationDenyType["guest_prohibited_by_custom_people_management"] = guest_prohibited_by_custom_people_management;
1070
+ })(InvitationDenyType || (InvitationDenyType = {}));
847
1071
 
1072
+ var InvitationInfoStatus; (function (InvitationInfoStatus) {
1073
+ const confirming2 = 'Confirming'; InvitationInfoStatus["confirming2"] = confirming2;
1074
+ const joined3 = 'Joined'; InvitationInfoStatus["joined3"] = joined3;
1075
+ const rejected3 = 'Rejected'; InvitationInfoStatus["rejected3"] = rejected3;
1076
+ const revoked2 = 'Revoked'; InvitationInfoStatus["revoked2"] = revoked2;
1077
+ const expired3 = 'Expired'; InvitationInfoStatus["expired3"] = expired3;
1078
+ const deny2 = 'Deny'; InvitationInfoStatus["deny2"] = deny2;
1079
+ })(InvitationInfoStatus || (InvitationInfoStatus = {}));
848
1080
 
1081
+ var InvitationStatus; (function (InvitationStatus) {
1082
+ const confirming = 'Confirming'; InvitationStatus["confirming"] = confirming;
1083
+ const joined2 = 'Joined'; InvitationStatus["joined2"] = joined2;
1084
+ const rejected2 = 'Rejected'; InvitationStatus["rejected2"] = rejected2;
1085
+ const revoked = 'Revoked'; InvitationStatus["revoked"] = revoked;
1086
+ const expired2 = 'Expired'; InvitationStatus["expired2"] = expired2;
1087
+ })(InvitationStatus || (InvitationStatus = {}));
849
1088
 
1089
+ var InvitedUserStatus; (function (InvitedUserStatus) {
1090
+ const can_join = 'CanJoin'; InvitedUserStatus["can_join"] = can_join;
1091
+ const guest_prohibited_by_enterprise = 'GuestProhibitedByEnterprise'; InvitedUserStatus["guest_prohibited_by_enterprise"] = guest_prohibited_by_enterprise;
1092
+ const guest_prohibited_by_invited_user_enterprise = 'GuestProhibitedByInvitedUserEnterprise'; InvitedUserStatus["guest_prohibited_by_invited_user_enterprise"] = guest_prohibited_by_invited_user_enterprise;
1093
+ })(InvitedUserStatus || (InvitedUserStatus = {}));
850
1094
 
1095
+ var InviteLinkStatus$1; (function (InviteLinkStatus) {
1096
+ const can_apply = 'CanApply'; InviteLinkStatus["can_apply"] = can_apply;
1097
+ const already_applied = 'AlreadyApplied'; InviteLinkStatus["already_applied"] = already_applied;
1098
+ const joined = 'Joined'; InviteLinkStatus["joined"] = joined;
1099
+ const expired = 'Expired'; InviteLinkStatus["expired"] = expired;
1100
+ const deny = 'Deny'; InviteLinkStatus["deny"] = deny;
1101
+ })(InviteLinkStatus$1 || (InviteLinkStatus$1 = {}));
851
1102
 
1103
+ var Level; (function (Level) {
1104
+ const free = 'Free'; Level["free"] = free;
1105
+ const premium_lite = 'PremiumLite'; Level["premium_lite"] = premium_lite;
1106
+ const premium = 'Premium'; Level["premium"] = premium;
1107
+ const premium_plus = 'PremiumPlus'; Level["premium_plus"] = premium_plus;
1108
+ const v_1_pro_instance = 'V1ProInstance'; Level["v_1_pro_instance"] = v_1_pro_instance;
1109
+ const pro_personal = 'ProPersonal'; Level["pro_personal"] = pro_personal;
1110
+ const coze_personal_plus = 'CozePersonalPlus'; Level["coze_personal_plus"] = coze_personal_plus;
1111
+ const coze_personal_advanced = 'CozePersonalAdvanced'; Level["coze_personal_advanced"] = coze_personal_advanced;
1112
+ const coze_personal_pro = 'CozePersonalPro'; Level["coze_personal_pro"] = coze_personal_pro;
1113
+ const team = 'Team'; Level["team"] = team;
1114
+ const enterprise_basic = 'EnterpriseBasic'; Level["enterprise_basic"] = enterprise_basic;
1115
+ const enterprise = 'Enterprise'; Level["enterprise"] = enterprise;
1116
+ const enterprise_pro = 'EnterprisePro'; Level["enterprise_pro"] = enterprise_pro;
1117
+ })(Level || (Level = {}));
852
1118
 
1119
+ var ListOption; (function (ListOption) {
1120
+ const user_custom_only = 'user_custom_only'; ListOption["user_custom_only"] = user_custom_only;
1121
+ const all2 = 'all'; ListOption["all2"] = all2;
1122
+ })(ListOption || (ListOption = {}));
853
1123
 
1124
+ var OAuth2ProviderType; (function (OAuth2ProviderType) {
1125
+ const system = 'system'; OAuth2ProviderType["system"] = system;
1126
+ const custom = 'custom'; OAuth2ProviderType["custom"] = custom;
1127
+ })(OAuth2ProviderType || (OAuth2ProviderType = {}));
854
1128
 
1129
+ var OrganizationApplicationDenyType; (function (OrganizationApplicationDenyType) {
1130
+ const not_in_enterprise = 'NotInEnterprise'; OrganizationApplicationDenyType["not_in_enterprise"] = not_in_enterprise;
1131
+ const prohibited_by_custom_people_management2 = 'ProhibitedByCustomPeopleManagement'; OrganizationApplicationDenyType["prohibited_by_custom_people_management2"] = prohibited_by_custom_people_management2;
1132
+ })(OrganizationApplicationDenyType || (OrganizationApplicationDenyType = {}));
855
1133
 
1134
+ var OrganizationApplicationForEnterpriseMemberStatus; (function (OrganizationApplicationForEnterpriseMemberStatus) {
1135
+ const can_apply3 = 'CanApply'; OrganizationApplicationForEnterpriseMemberStatus["can_apply3"] = can_apply3;
1136
+ const already_applied3 = 'AlreadyApplied'; OrganizationApplicationForEnterpriseMemberStatus["already_applied3"] = already_applied3;
1137
+ const joined5 = 'Joined'; OrganizationApplicationForEnterpriseMemberStatus["joined5"] = joined5;
1138
+ const deny4 = 'Deny'; OrganizationApplicationForEnterpriseMemberStatus["deny4"] = deny4;
1139
+ })(OrganizationApplicationForEnterpriseMemberStatus || (OrganizationApplicationForEnterpriseMemberStatus = {}));
856
1140
 
1141
+ var OrganizationRoleType; (function (OrganizationRoleType) {
1142
+ const super_admin2 = 'SuperAdmin'; OrganizationRoleType["super_admin2"] = super_admin2;
1143
+ const admin2 = 'Admin'; OrganizationRoleType["admin2"] = admin2;
1144
+ const member2 = 'Member'; OrganizationRoleType["member2"] = member2;
1145
+ const guest2 = 'Guest'; OrganizationRoleType["guest2"] = guest2;
1146
+ })(OrganizationRoleType || (OrganizationRoleType = {}));
857
1147
 
1148
+ var Ownership; (function (Ownership) {
1149
+ const developer = 'developer'; Ownership["developer"] = developer;
1150
+ const consumer2 = 'consumer'; Ownership["consumer2"] = consumer2;
1151
+ })(Ownership || (Ownership = {}));
858
1152
 
859
- function stripAnsi(input) {
860
- // eslint-disable-next-line no-control-regex
861
- const ansiPattern = /\u001B(?:[@-Z\\-_]|\[[0-?]*[ -/]*[@-~])/g;
862
- return input.replace(ansiPattern, '');
863
- }
1153
+ var PatSearchOption; (function (PatSearchOption) {
1154
+ const all = 'all'; PatSearchOption["all"] = all;
1155
+ const owned = 'owned'; PatSearchOption["owned"] = owned;
1156
+ const others = 'others'; PatSearchOption["others"] = others;
1157
+ })(PatSearchOption || (PatSearchOption = {}));
864
1158
 
865
- function isFullWidthCodePoint(codePoint) {
866
- if (codePoint >= 0x1100 && codePoint <= 0x115f) {
867
- return true;
868
- }
869
- if (codePoint === 0x2329 || codePoint === 0x232a) {
870
- return true;
871
- }
872
- if (codePoint >= 0x2e80 && codePoint <= 0x303e) {
873
- return true;
874
- }
875
- if (codePoint >= 0x3040 && codePoint <= 0xa4cf) {
876
- return true;
877
- }
878
- if (codePoint >= 0xac00 && codePoint <= 0xd7a3) {
879
- return true;
880
- }
881
- if (codePoint >= 0xf900 && codePoint <= 0xfaff) {
882
- return true;
883
- }
884
- if (codePoint >= 0xfe10 && codePoint <= 0xfe19) {
885
- return true;
886
- }
887
- if (codePoint >= 0xfe30 && codePoint <= 0xfe6f) {
888
- return true;
889
- }
890
- if (codePoint >= 0xff00 && codePoint <= 0xff60) {
891
- return true;
892
- }
893
- if (codePoint >= 0xffe0 && codePoint <= 0xffe6) {
894
- return true;
895
- }
896
- if (codePoint >= 0x1f300 && codePoint <= 0x1fa9f) {
897
- return true;
898
- }
899
- if (codePoint >= 0x20000 && codePoint <= 0x3fffd) {
900
- return true;
901
- }
902
- return false;
903
- }
1159
+ var PeopleType; (function (PeopleType) {
1160
+ const enterprise_member = 'EnterpriseMember'; PeopleType["enterprise_member"] = enterprise_member;
1161
+ const enterprise_guest = 'EnterpriseGuest'; PeopleType["enterprise_guest"] = enterprise_guest;
1162
+ })(PeopleType || (PeopleType = {}));
904
1163
 
905
- function stringWidth(input) {
906
- const stripped = stripAnsi(input);
907
- if (!stripped) {
908
- return 0;
909
- }
1164
+ var ProjectAuthIntegrationStatus; (function (ProjectAuthIntegrationStatus) {
1165
+ const not_created = 'NotCreated'; ProjectAuthIntegrationStatus["not_created"] = not_created;
1166
+ const enabled = 'Enabled'; ProjectAuthIntegrationStatus["enabled"] = enabled;
1167
+ const disabled = 'Disabled'; ProjectAuthIntegrationStatus["disabled"] = disabled;
1168
+ })(ProjectAuthIntegrationStatus || (ProjectAuthIntegrationStatus = {}));
910
1169
 
911
- const combiningMarks =
912
- /[\u0300-\u036F\u1AB0-\u1AFF\u1DC0-\u1DFF\u20D0-\u20FF\uFE20-\uFE2F]/u;
1170
+ var ProjectEnvironment; (function (ProjectEnvironment) {
1171
+ const production = 'Production'; ProjectEnvironment["production"] = production;
1172
+ const development = 'Development'; ProjectEnvironment["development"] = development;
1173
+ })(ProjectEnvironment || (ProjectEnvironment = {}));
913
1174
 
914
- let width = 0;
915
- const chars = Array.from(stripped);
916
- for (let i = 0; i < chars.length; i += 1) {
917
- const char = _nullishCoalesce$j(chars[i], () => ( ''));
918
- if (combiningMarks.test(char)) {
919
- continue;
920
- }
921
- const codePoint = char.codePointAt(0);
922
- if (codePoint === undefined) {
923
- continue;
924
- }
925
- width += isFullWidthCodePoint(codePoint) ? 2 : 1;
926
- }
927
- return width;
928
- }
1175
+ var ProjectType$2; (function (ProjectType) {
1176
+ const skill = 'skill'; ProjectType["skill"] = skill;
1177
+ })(ProjectType$2 || (ProjectType$2 = {}));
929
1178
 
930
- function padRightVisible(str, width) {
931
- const current = stringWidth(str);
932
- if (current >= width) {
933
- return str;
934
- }
935
- return `${str}${' '.repeat(width - current)}`;
936
- }
1179
+ var SearchEnv; (function (SearchEnv) {
1180
+ const dev = 'dev'; SearchEnv["dev"] = dev;
1181
+ const prod = 'prod'; SearchEnv["prod"] = prod;
1182
+ })(SearchEnv || (SearchEnv = {}));
937
1183
 
938
- function truncateVisible(str, width) {
939
- if (width <= 0) {
940
- return '';
941
- }
942
- if (stringWidth(str) <= width) {
943
- return str;
944
- }
945
- if (width === 1) {
946
- return '…';
947
- }
1184
+ var SecretKeyType; (function (SecretKeyType) {
1185
+ const user_custom = 'user_custom'; SecretKeyType["user_custom"] = user_custom;
1186
+ const coze_default = 'coze_default'; SecretKeyType["coze_default"] = coze_default;
1187
+ const consumer = 'consumer'; SecretKeyType["consumer"] = consumer;
1188
+ })(SecretKeyType || (SecretKeyType = {}));
948
1189
 
949
- const stripped = stripAnsi(str);
950
- const chars = Array.from(stripped);
951
- const ellipsis = '';
952
- const available = Math.max(0, width - stringWidth(ellipsis));
1190
+ var Status; (function (Status) {
1191
+ const active2 = 'Active'; Status["active2"] = active2;
1192
+ const deactive = 'Deactive'; Status["deactive"] = deactive;
1193
+ })(Status || (Status = {}));
953
1194
 
954
- let out = '';
955
- let used = 0;
956
- for (let i = 0; i < chars.length; i += 1) {
957
- const char = _nullishCoalesce$j(chars[i], () => ( ''));
958
- const w = stringWidth(char);
959
- if (used + w > available) {
960
- break;
961
- }
962
- out += char;
963
- used += w;
964
- }
1195
+ var UserStatus$1; (function (UserStatus) {
1196
+ const active = 'active'; UserStatus["active"] = active;
1197
+ const deactivated = 'deactivated'; UserStatus["deactivated"] = deactivated;
1198
+ const offboarded = 'offboarded'; UserStatus["offboarded"] = offboarded;
1199
+ })(UserStatus$1 || (UserStatus$1 = {}));
965
1200
 
966
- return `${out}${ellipsis}`;
967
- }
1201
+ var VisibilityKey; (function (VisibilityKey) {
1202
+ const studio_space_selector = 'studio_space_selector'; VisibilityKey["studio_space_selector"] = studio_space_selector;
1203
+ const studio_create_project_btn = 'studio_create_project_btn'; VisibilityKey["studio_create_project_btn"] = studio_create_project_btn;
1204
+ const studio_home_page = 'studio_home_page'; VisibilityKey["studio_home_page"] = studio_home_page;
1205
+ const studio_develop = 'studio_develop'; VisibilityKey["studio_develop"] = studio_develop;
1206
+ const studio_library = 'studio_library'; VisibilityKey["studio_library"] = studio_library;
1207
+ const studio_tasks = 'studio_tasks'; VisibilityKey["studio_tasks"] = studio_tasks;
1208
+ const studio_evaluate = 'studio_evaluate'; VisibilityKey["studio_evaluate"] = studio_evaluate;
1209
+ const studio_space_manage = 'studio_space_manage'; VisibilityKey["studio_space_manage"] = studio_space_manage;
1210
+ const studio_templates_store = 'studio_templates_store'; VisibilityKey["studio_templates_store"] = studio_templates_store;
1211
+ const studio_plugins_store = 'studio_plugins_store'; VisibilityKey["studio_plugins_store"] = studio_plugins_store;
1212
+ const studio_agents_store = 'studio_agents_store'; VisibilityKey["studio_agents_store"] = studio_agents_store;
1213
+ const studio_playground = 'studio_playground'; VisibilityKey["studio_playground"] = studio_playground;
1214
+ const studio_docs = 'studio_docs'; VisibilityKey["studio_docs"] = studio_docs;
1215
+ const studio_enterprise_agents_store = 'studio_enterprise_agents_store'; VisibilityKey["studio_enterprise_agents_store"] = studio_enterprise_agents_store;
1216
+ const studio_enterprise_plugins_store = 'studio_enterprise_plugins_store'; VisibilityKey["studio_enterprise_plugins_store"] = studio_enterprise_plugins_store;
1217
+ const studio_organization_manage = 'studio_organization_manage'; VisibilityKey["studio_organization_manage"] = studio_organization_manage;
1218
+ const studio_enterprise_card = 'studio_enterprise_card'; VisibilityKey["studio_enterprise_card"] = studio_enterprise_card;
1219
+ const studio_subscription_card = 'studio_subscription_card'; VisibilityKey["studio_subscription_card"] = studio_subscription_card;
1220
+ const studio_personal_menu = 'studio_personal_menu'; VisibilityKey["studio_personal_menu"] = studio_personal_menu;
1221
+ const studio_more_products = 'studio_more_products'; VisibilityKey["studio_more_products"] = studio_more_products;
1222
+ const studio_notice = 'studio_notice'; VisibilityKey["studio_notice"] = studio_notice;
1223
+ const studio_migration_banner = 'studio_migration_banner'; VisibilityKey["studio_migration_banner"] = studio_migration_banner;
1224
+ const coding_space_selector = 'coding_space_selector'; VisibilityKey["coding_space_selector"] = coding_space_selector;
1225
+ const coding_create_project = 'coding_create_project'; VisibilityKey["coding_create_project"] = coding_create_project;
1226
+ const coding_project_manage = 'coding_project_manage'; VisibilityKey["coding_project_manage"] = coding_project_manage;
1227
+ const coding_integrations = 'coding_integrations'; VisibilityKey["coding_integrations"] = coding_integrations;
1228
+ const coding_library = 'coding_library'; VisibilityKey["coding_library"] = coding_library;
1229
+ const coding_tasks = 'coding_tasks'; VisibilityKey["coding_tasks"] = coding_tasks;
1230
+ const coding_playground = 'coding_playground'; VisibilityKey["coding_playground"] = coding_playground;
1231
+ const coding_evaluate = 'coding_evaluate'; VisibilityKey["coding_evaluate"] = coding_evaluate;
1232
+ const coding_coze_redirect = 'coding_coze_redirect'; VisibilityKey["coding_coze_redirect"] = coding_coze_redirect;
1233
+ const coding_docs = 'coding_docs'; VisibilityKey["coding_docs"] = coding_docs;
1234
+ const coding_community = 'coding_community'; VisibilityKey["coding_community"] = coding_community;
1235
+ const coding_enterprise_card = 'coding_enterprise_card'; VisibilityKey["coding_enterprise_card"] = coding_enterprise_card;
1236
+ const coding_subscription_card = 'coding_subscription_card'; VisibilityKey["coding_subscription_card"] = coding_subscription_card;
1237
+ const coding_personal_menu = 'coding_personal_menu'; VisibilityKey["coding_personal_menu"] = coding_personal_menu;
1238
+ const coding_notice = 'coding_notice'; VisibilityKey["coding_notice"] = coding_notice;
1239
+ const admin_organization_manage = 'admin_organization_manage'; VisibilityKey["admin_organization_manage"] = admin_organization_manage;
1240
+ const admin_member_manage = 'admin_member_manage'; VisibilityKey["admin_member_manage"] = admin_member_manage;
1241
+ const admin_enterprise_config = 'admin_enterprise_config'; VisibilityKey["admin_enterprise_config"] = admin_enterprise_config;
1242
+ })(VisibilityKey || (VisibilityKey = {}));
968
1243
 
969
- function calculateColumnWidths(rows, options) {
970
- if (rows.length === 0) {
971
- return [];
972
- }
1244
+ var VolcanoUserType$2; (function (VolcanoUserType) {
1245
+ const root_user = 'RootUser'; VolcanoUserType["root_user"] = root_user;
1246
+ const basic_user = 'BasicUser'; VolcanoUserType["basic_user"] = basic_user;
1247
+ })(VolcanoUserType$2 || (VolcanoUserType$2 = {}));
973
1248
 
974
- const keySet = new Set();
975
- const orderedKeys = [];
976
1249
 
977
- const seedRow = _nullishCoalesce$j(rows[0], () => ( {}));
978
- for (const key of Object.keys(seedRow)) {
979
- if (!keySet.has(key)) {
980
- keySet.add(key);
981
- orderedKeys.push(key);
982
- }
983
- }
984
1250
 
985
- for (const row of rows) {
986
- for (const key of Object.keys(row)) {
987
- if (!keySet.has(key)) {
988
- keySet.add(key);
989
- orderedKeys.push(key);
990
- }
991
- }
992
- }
993
1251
 
994
- const columns = [];
995
- for (const key of orderedKeys) {
996
- let maxWidth = stringWidth(key);
997
- for (const row of rows) {
998
- const value = row[key];
999
- const valueStr = value === undefined ? '' : String(value);
1000
- maxWidth = Math.max(maxWidth, stringWidth(valueStr));
1001
- }
1002
- columns.push({ key, width: maxWidth });
1003
- }
1004
-
1005
- const gap = _nullishCoalesce$j(options.columnGap, () => ( 2));
1006
- const maxWidth = _nullishCoalesce$j(_nullishCoalesce$j(options.maxWidth, () => ( process.stdout.columns)), () => ( 120));
1007
- const minColWidth = 6;
1008
-
1009
- const dynamicMaxColumns = Math.max(
1010
- 1,
1011
- Math.floor((maxWidth + gap) / (minColWidth + gap)),
1012
- );
1013
- const maxColumns = Math.min(
1014
- _nullishCoalesce$j(options.maxColumns, () => ( dynamicMaxColumns)),
1015
- dynamicMaxColumns,
1016
- );
1017
-
1018
- if (columns.length > maxColumns) {
1019
- columns.splice(maxColumns);
1020
- }
1021
-
1022
- const available = Math.max(
1023
- 0,
1024
- maxWidth - gap * Math.max(0, columns.length - 1),
1025
- );
1026
-
1027
- const sum = () => columns.reduce((acc, col) => acc + col.width, 0);
1028
-
1029
- while (sum() > available) {
1030
- let widestIndex = -1;
1031
- let widestWidth = -1;
1032
- for (let i = 0; i < columns.length; i += 1) {
1033
- const w = _nullishCoalesce$j(_optionalChain$I([columns, 'access', _ => _[i], 'optionalAccess', _2 => _2.width]), () => ( 0));
1034
- if (w > widestWidth) {
1035
- widestWidth = w;
1036
- widestIndex = i;
1037
- }
1038
- }
1039
-
1040
- if (widestIndex === -1) {
1041
- break;
1042
- }
1043
- const current = _nullishCoalesce$j(_optionalChain$I([columns, 'access', _3 => _3[widestIndex], 'optionalAccess', _4 => _4.width]), () => ( 0));
1044
- if (current <= minColWidth) {
1045
- break;
1046
- }
1047
- columns[widestIndex] = { ...columns[widestIndex], width: current - 1 };
1048
- }
1049
-
1050
- for (let i = 0; i < columns.length; i += 1) {
1051
- const col = columns[i];
1052
- if (!col) {
1053
- continue;
1054
- }
1055
- columns[i] = { ...col, width: Math.max(minColWidth, col.width) };
1056
- }
1057
-
1058
- return columns;
1059
- }
1060
-
1061
- function formatTable(rows, options = {}) {
1062
- if (rows.length === 0) {
1063
- return '';
1064
- }
1065
-
1066
- const columns = calculateColumnWidths(rows, options);
1067
- if (columns.length === 0) {
1068
- return '';
1069
- }
1070
-
1071
- const gap = _nullishCoalesce$j(options.columnGap, () => ( 2));
1072
- const gapStr = ' '.repeat(gap);
1073
-
1074
- const header = columns
1075
- .map(col => padRightVisible(truncateVisible(col.key, col.width), col.width))
1076
- .join(gapStr);
1077
- const separator = columns.map(col => '-'.repeat(col.width)).join(gapStr);
1078
-
1079
- const bodyRows = [];
1080
- for (const row of rows) {
1081
- const cells = columns.map(col => {
1082
- const value = row[col.key];
1083
- const valueStr = value === undefined ? '' : String(value);
1084
- const trimmed = truncateVisible(valueStr, col.width);
1085
- return padRightVisible(trimmed, col.width);
1086
- });
1087
- bodyRows.push(cells.join(gapStr));
1088
- }
1089
-
1090
- return `${[header, separator, ...bodyRows].join('\n')}\n`;
1091
- }
1092
-
1093
- function formatKeyValue(
1094
- obj,
1095
- options = {},
1096
- ) {
1097
- const entries = Object.entries(obj);
1098
- if (entries.length === 0) {
1099
- return '';
1100
- }
1101
-
1102
- let maxKeyWidth = 0;
1103
- for (const [key] of entries) {
1104
- maxKeyWidth = Math.max(maxKeyWidth, stringWidth(key));
1105
- }
1106
-
1107
- const maxWidth = _nullishCoalesce$j(_nullishCoalesce$j(options.maxWidth, () => ( process.stdout.columns)), () => ( 120));
1108
- const gap = _nullishCoalesce$j(options.columnGap, () => ( 2));
1109
- const minValueWidth = _nullishCoalesce$j(options.minValueWidth, () => ( 12));
1110
-
1111
- let keyWidth = Math.min(maxKeyWidth, _nullishCoalesce$j(options.keyMaxWidth, () => ( 32)));
1112
- const maxKeyWidthByTotal = Math.max(6, maxWidth - gap - minValueWidth);
1113
- keyWidth = Math.min(keyWidth, maxKeyWidthByTotal);
1114
-
1115
- const valueWidth = Math.max(0, maxWidth - keyWidth - gap);
1116
- const gapStr = ' '.repeat(gap);
1117
-
1118
- const lines = entries.map(([key, value]) => {
1119
- const keyCell = padRightVisible(truncateVisible(key, keyWidth), keyWidth);
1120
- const valueStr =
1121
- value === undefined
1122
- ? 'undefined'
1123
- : value === null
1124
- ? 'null'
1125
- : String(value);
1126
-
1127
- const singleLineValue = valueStr.replace(/\s*\n\s*/g, ' ');
1128
- const valueCell =
1129
- valueWidth > 0 ? truncateVisible(singleLineValue, valueWidth) : '';
1130
-
1131
- return `${keyCell}${gapStr}${valueCell}`;
1132
- });
1133
-
1134
- return `${lines.join('\n')}\n`;
1135
- }
1136
-
1137
- function _nullishCoalesce$i(lhs, rhsFn) { if (lhs != null) { return lhs; } else { return rhsFn(); } }const MAX_DEPTH = 5;
1138
-
1139
-
1140
-
1141
-
1142
-
1143
-
1144
-
1145
- function isObject$1(value) {
1146
- return typeof value === 'object' && value !== null && !Array.isArray(value);
1147
- }
1148
-
1149
- function flattenObject(
1150
- obj,
1151
- prefix = '',
1152
- depth = 0,
1153
- ) {
1154
- const result = {};
1155
-
1156
- if (obj === null || obj === undefined) {
1157
- return result;
1158
- }
1159
-
1160
- if (!isObject$1(obj)) {
1161
- return result;
1162
- }
1163
-
1164
- for (const [key, value] of Object.entries(obj)) {
1165
- const newKey = prefix ? `${prefix}.${key}` : key;
1166
-
1167
- if (value === null || value === undefined) {
1168
- result[newKey] = value ;
1169
- continue;
1170
- }
1171
-
1172
- if (Array.isArray(value)) {
1173
- if (depth >= MAX_DEPTH) {
1174
- result[newKey] = '[Array]';
1175
- } else if (value.length === 0) {
1176
- result[newKey] = '[]';
1177
- } else if (
1178
- value.every(item => typeof item !== 'object' || item === null)
1179
- ) {
1180
- result[newKey] = value.map(v => String(_nullishCoalesce$i(v, () => ( 'null')))).join(', ');
1181
- } else {
1182
- result[newKey] = '[Array]';
1183
- }
1184
- continue;
1185
- }
1186
-
1187
- if (typeof value === 'object') {
1188
- if (depth >= MAX_DEPTH) {
1189
- result[newKey] = '[Object]';
1190
- } else {
1191
- const nested = flattenObject(value, newKey, depth + 1);
1192
- Object.assign(result, nested);
1193
- }
1194
- continue;
1195
- }
1196
-
1197
- result[newKey] = value ;
1198
- }
1199
-
1200
- return result;
1201
- }
1202
-
1203
- function _nullishCoalesce$h(lhs, rhsFn) { if (lhs != null) { return lhs; } else { return rhsFn(); } }
1204
-
1205
- function isObject(value) {
1206
- return typeof value === 'object' && value !== null && !Array.isArray(value);
1207
- }
1208
-
1209
- function isArrayOfObjects(value) {
1210
- return Array.isArray(value) && value.length > 0 && value.every(isObject);
1211
- }
1212
-
1213
- function isPrimitiveArray(
1214
- value,
1215
- ) {
1216
- return (
1217
- Array.isArray(value) &&
1218
- value.length > 0 &&
1219
- value.every(
1220
- item => item === null || item === undefined || typeof item !== 'object',
1221
- )
1222
- );
1223
- }
1224
-
1225
- function formatDetails(details, indent) {
1226
- if (details === undefined || details === null) {
1227
- return '';
1228
- }
1229
-
1230
- if (typeof details === 'string') {
1231
- return `${indent}${details}\n`;
1232
- }
1233
-
1234
- if (Array.isArray(details)) {
1235
- if (details.length === 0) {
1236
- return '';
1237
- }
1238
- const items = details.map(item => {
1239
- if (typeof item === 'object' && item !== null) {
1240
- return formatKeyValue(flattenObject(item));
1241
- }
1242
- return String(item);
1243
- });
1244
- return `${items.map(item => `${indent}- ${item.trim()}`).join('\n')}\n`;
1245
- }
1246
-
1247
- if (isObject(details)) {
1248
- const flattened = flattenObject(details);
1249
- if (Object.keys(flattened).length === 0) {
1250
- return '';
1251
- }
1252
- return `${formatKeyValue(flattened)
1253
- .split('\n')
1254
- .filter(line => line.trim())
1255
- .map(line => `${indent}${line}`)
1256
- .join('\n')}\n`;
1257
- }
1258
-
1259
- return `${indent}${String(details)}\n`;
1260
- }
1261
-
1262
- class TextFormatter {
1263
- format(data) {
1264
- if (data === null) {
1265
- return 'null\n';
1266
- }
1267
-
1268
- if (data === undefined) {
1269
- return 'undefined\n';
1270
- }
1271
-
1272
- if (Array.isArray(data)) {
1273
- if (data.length === 0) {
1274
- return '\n';
1275
- }
1276
-
1277
- if (isArrayOfObjects(data)) {
1278
- const flattenedRows = data.map(row => flattenObject(row));
1279
- return formatTable(flattenedRows);
1280
- }
1281
-
1282
- if (isPrimitiveArray(data)) {
1283
- return `${data.map(item => String(_nullishCoalesce$h(item, () => ( 'null')))).join('\n')}\n`;
1284
- }
1285
-
1286
- return '[Array]\n';
1287
- }
1288
-
1289
- if (isObject(data)) {
1290
- const flattened = flattenObject(data);
1291
- if (Object.keys(flattened).length === 0) {
1292
- return '{}\n';
1293
- }
1294
- return formatKeyValue(flattened);
1295
- }
1296
-
1297
- return `${String(data)}\n`;
1298
- }
1299
-
1300
- formatError(error) {
1301
- const lines = [];
1302
-
1303
- lines.push('✖ [ERROR]');
1304
- lines.push(` Message: ${error.message}`);
1305
- lines.push(` Code: ${error.code}`);
1306
-
1307
- if (error.details !== undefined) {
1308
- lines.push(' Details:');
1309
- const detailsStr = formatDetails(error.details, ' ');
1310
- if (detailsStr) {
1311
- lines.push(detailsStr.trimEnd());
1312
- }
1313
- }
1314
-
1315
- return `${lines.join('\n')}\n`;
1316
- }
1317
- }
1318
-
1319
- function createFormatter(format) {
1320
- switch (format) {
1321
- case 'text':
1322
- return new TextFormatter();
1323
- case 'json':
1324
- default:
1325
- return new JsonFormatter();
1326
- }
1327
- }
1328
-
1329
- class Response {
1330
-
1331
-
1332
- constructor(props) {
1333
- const { format } = props;
1334
- this.formatter = createFormatter(format);
1335
- }
1336
-
1337
- print(data) {
1338
- const output = this.formatter.format(data);
1339
- process.stdout.write(output);
1340
- }
1341
-
1342
- eprint(error) {
1343
- const output = this.formatter.formatError(error);
1344
- process.stdout.write(output);
1345
- }
1346
- }
1347
-
1348
- function _nullishCoalesce$g(lhs, rhsFn) { if (lhs != null) { return lhs; } else { return rhsFn(); } }
1349
-
1350
-
1351
-
1352
-
1353
-
1354
-
1355
-
1356
- const LOG_DIR = path.join(os.homedir(), '.coze', 'logs');
1357
- const MAX_LOG_FILES = 10;
1358
-
1359
- class DiagnosticLogger {
1360
-
1361
-
1362
-
1363
-
1364
-
1365
- __init() {this.fileStream = null;}
1366
- __init2() {this.writeError = false;}
1367
-
1368
- constructor(options = {}) {DiagnosticLogger.prototype.__init.call(this);DiagnosticLogger.prototype.__init2.call(this);
1369
- this.format = _nullishCoalesce$g(options.format, () => ( 'text'));
1370
- this.printToStderr = _nullishCoalesce$g(options.printToStderr, () => ( false));
1371
- this.tags = _nullishCoalesce$g(options.tags, () => ( {}));
1372
- this.startTime = Date.now();
1373
-
1374
- const logFilePath = _nullishCoalesce$g(options.logFile, () => ( this.getDefaultLogPath()));
1375
- this.logFile = logFilePath;
1376
-
1377
- try {
1378
- this.ensureLogDir();
1379
- this.rotateLogFiles();
1380
- this.fileStream = node_fs.createWriteStream(logFilePath, { flags: 'a' });
1381
- this.fileStream.on('error', () => {
1382
- this.fileStream = null;
1383
- });
1384
- } catch (e) {
1385
- this.logFile = null;
1386
- this.fileStream = null;
1387
- }
1388
- }
1389
-
1390
- getDefaultLogPath() {
1391
- const timestamp = new Date().toISOString().replace(/[:.]/g, '-');
1392
- const { pid } = process;
1393
- return path.join(LOG_DIR, `${timestamp}-${pid}.log`);
1394
- }
1395
-
1396
- ensureLogDir() {
1397
- if (!node_fs.existsSync(LOG_DIR)) {
1398
- node_fs.mkdirSync(LOG_DIR, { recursive: true });
1399
- }
1400
- }
1401
-
1402
- rotateLogFiles() {
1403
- try {
1404
- const files = node_fs.readdirSync(LOG_DIR)
1405
- .filter(f => f.endsWith('.log'))
1406
- .map(f => ({
1407
- name: f,
1408
- path: path.join(LOG_DIR, f),
1409
- mtime: node_fs.statSync(path.join(LOG_DIR, f)).mtime.getTime(),
1410
- }))
1411
- .sort((a, b) => b.mtime - a.mtime);
1412
-
1413
- if (files.length >= MAX_LOG_FILES) {
1414
- files.slice(MAX_LOG_FILES - 1).forEach(f => {
1415
- try {
1416
- node_fs.unlinkSync(f.path);
1417
- // eslint-disable-next-line @coze-arch/no-empty-catch
1418
- } catch (e2) {
1419
- // ignore deletion errors
1420
- }
1421
- });
1422
- }
1423
- // eslint-disable-next-line @coze-arch/no-empty-catch
1424
- } catch (e3) {
1425
- // ignore rotation errors
1426
- }
1427
- }
1428
-
1429
- verbose(msg, ...args) {
1430
- this.log('verbose', msg, args);
1431
- }
1432
-
1433
- info(msg, ...args) {
1434
- this.log('info', msg, args);
1435
- }
1436
-
1437
- warn(msg, ...args) {
1438
- this.log('warn', msg, args);
1439
- }
1440
-
1441
- error(msg, ...args) {
1442
- this.log('error', msg, args);
1443
- }
1444
-
1445
- success(msg, ...args) {
1446
- this.log('success', msg, args);
1447
- }
1448
-
1449
- debug(msg, ...args) {
1450
- this.log('debug', msg, args);
1451
- }
1452
-
1453
- log(level, msg, args) {
1454
- const entry = this.formatEntry(level, msg, args);
1455
-
1456
- if (this.fileStream) {
1457
- try {
1458
- this.fileStream.write(`${entry}\n`);
1459
- } catch (e4) {
1460
- if (!this.writeError && this.printToStderr) {
1461
- process.stderr.write('Warning: Log write failed\n');
1462
- this.writeError = true;
1463
- }
1464
- }
1465
- }
1466
-
1467
- if (this.printToStderr) {
1468
- process.stderr.write(`${entry}\n`);
1469
- }
1470
- }
1471
-
1472
- formatEntry(level, msg, args) {
1473
- const timestamp = new Date().toISOString();
1474
- const delta = Date.now() - this.startTime;
1475
-
1476
- if (this.format === 'json') {
1477
- const entry = {
1478
- level,
1479
- timestamp,
1480
- delta,
1481
- ...this.tags,
1482
- message: msg,
1483
- };
1484
- if (args.length > 0) {
1485
- entry.args = args;
1486
- }
1487
- return JSON.stringify(entry);
1488
- }
1489
-
1490
- const tagsStr = Object.entries(this.tags)
1491
- .map(([k, v]) => `${k}=${v}`)
1492
- .join(' ');
1493
- const argsStr = args.length > 0 ? ` ${args.map(String).join(' ')}` : '';
1494
- return `${level.toUpperCase().padEnd(7)} [${timestamp}] +${delta}ms ${tagsStr} ${msg}${argsStr}`;
1495
- }
1496
-
1497
- close() {
1498
- if (this.fileStream) {
1499
- try {
1500
- this.fileStream.end();
1501
- // eslint-disable-next-line @coze-arch/no-empty-catch
1502
- } catch (e5) {
1503
- // ignore close errors
1504
- }
1505
- }
1506
- }
1507
- }
1508
-
1509
- // THIS IS AN AUTOGENERATED FILE. DO NOT EDIT THIS FILE DIRECTLY.
1510
- /* eslint-disable */
1511
- /* tslint:disable */
1512
- // @ts-nocheck
1513
-
1514
-
1515
-
1516
- var AppAndPATAuthInfoItemType; (function (AppAndPATAuthInfoItemType) {
1517
- const app = 'app'; AppAndPATAuthInfoItemType["app"] = app;
1518
- const pat = 'pat'; AppAndPATAuthInfoItemType["pat"] = pat;
1519
- })(AppAndPATAuthInfoItemType || (AppAndPATAuthInfoItemType = {}));
1520
-
1521
- var ApplicationForEnterpriseMemberStatus; (function (ApplicationForEnterpriseMemberStatus) {
1522
- const can_apply2 = 'CanApply'; ApplicationForEnterpriseMemberStatus["can_apply2"] = can_apply2;
1523
- const already_applied2 = 'AlreadyApplied'; ApplicationForEnterpriseMemberStatus["already_applied2"] = already_applied2;
1524
- const joined4 = 'Joined'; ApplicationForEnterpriseMemberStatus["joined4"] = joined4;
1525
- const deny3 = 'Deny'; ApplicationForEnterpriseMemberStatus["deny3"] = deny3;
1526
- })(ApplicationForEnterpriseMemberStatus || (ApplicationForEnterpriseMemberStatus = {}));
1527
-
1528
- var ApplicationStatus; (function (ApplicationStatus) {
1529
- const processing = 'Processing'; ApplicationStatus["processing"] = processing;
1530
- const approved = 'Approved'; ApplicationStatus["approved"] = approved;
1531
- const rejected = 'Rejected'; ApplicationStatus["rejected"] = rejected;
1532
- })(ApplicationStatus || (ApplicationStatus = {}));
1533
-
1534
- var AppType; (function (AppType) {
1535
- const normal = 'Normal'; AppType["normal"] = normal;
1536
- const connector = 'Connector'; AppType["connector"] = connector;
1537
- const privilege = 'Privilege'; AppType["privilege"] = privilege;
1538
- })(AppType || (AppType = {}));
1539
-
1540
- var AuthorizationType; (function (AuthorizationType) {
1541
- const auth_app = 'AuthApp'; AuthorizationType["auth_app"] = auth_app;
1542
- const on_behalf_of_user = 'OnBehalfOfUser'; AuthorizationType["on_behalf_of_user"] = on_behalf_of_user;
1543
- })(AuthorizationType || (AuthorizationType = {}));
1544
-
1545
- var AuthProvider; (function (AuthProvider) {
1546
- const password = 'Password'; AuthProvider["password"] = password;
1547
- const sms = 'Sms'; AuthProvider["sms"] = sms;
1548
- const email = 'Email'; AuthProvider["email"] = email;
1549
- const unknown3 = 'Unknown'; AuthProvider["unknown3"] = unknown3;
1550
- })(AuthProvider || (AuthProvider = {}));
1551
-
1552
- var AuthStatus; (function (AuthStatus) {
1553
- const authorized = 'authorized'; AuthStatus["authorized"] = authorized;
1554
- const unauthorized = 'unauthorized'; AuthStatus["unauthorized"] = unauthorized;
1555
- const expired4 = 'expired'; AuthStatus["expired4"] = expired4;
1556
- })(AuthStatus || (AuthStatus = {}));
1557
-
1558
- var AuthType$1; (function (AuthType) {
1559
- const api_key = 'api_key'; AuthType["api_key"] = api_key;
1560
- const wechat_official = 'wechat_official'; AuthType["wechat_official"] = wechat_official;
1561
- const oauth_2 = 'oauth2'; AuthType["oauth_2"] = oauth_2;
1562
- })(AuthType$1 || (AuthType$1 = {}));
1563
-
1564
- var Certificated; (function (Certificated) {
1565
- const noncertificated = 'Noncertificated'; Certificated["noncertificated"] = noncertificated;
1566
- const certificated = 'Certificated'; Certificated["certificated"] = certificated;
1567
- })(Certificated || (Certificated = {}));
1568
-
1569
- var CertificationType; (function (CertificationType) {
1570
- const uncertified = 'Uncertified'; CertificationType["uncertified"] = uncertified;
1571
- const personal_certification = 'PersonalCertification'; CertificationType["personal_certification"] = personal_certification;
1572
- const enterprise_certification = 'EnterpriseCertification'; CertificationType["enterprise_certification"] = enterprise_certification;
1573
- })(CertificationType || (CertificationType = {}));
1574
-
1575
- var ChecklistItemType; (function (ChecklistItemType) {
1576
- const obo = 'Obo'; ChecklistItemType["obo"] = obo;
1577
- const app_auth = 'AppAuth'; ChecklistItemType["app_auth"] = app_auth;
1578
- const personal_access_token = 'PersonalAccessToken'; ChecklistItemType["personal_access_token"] = personal_access_token;
1579
- })(ChecklistItemType || (ChecklistItemType = {}));
1580
-
1581
- var ClientType; (function (ClientType) {
1582
- const legacy = 'Legacy'; ClientType["legacy"] = legacy;
1583
- const web_backend = 'WebBackend'; ClientType["web_backend"] = web_backend;
1584
- const single_page_or_native = 'SinglePageOrNative'; ClientType["single_page_or_native"] = single_page_or_native;
1585
- const terminal = 'Terminal'; ClientType["terminal"] = terminal;
1586
- const service = 'Service'; ClientType["service"] = service;
1587
- })(ClientType || (ClientType = {}));
1588
-
1589
- var CollaboratorType; (function (CollaboratorType) {
1590
- const bot_editor = 'BotEditor'; CollaboratorType["bot_editor"] = bot_editor;
1591
- const bot_developer = 'BotDeveloper'; CollaboratorType["bot_developer"] = bot_developer;
1592
- const bot_operator = 'BotOperator'; CollaboratorType["bot_operator"] = bot_operator;
1593
- })(CollaboratorType || (CollaboratorType = {}));
1594
-
1595
- var DeleteOrgResourceType; (function (DeleteOrgResourceType) {
1596
- const workspace = 'Workspace'; DeleteOrgResourceType["workspace"] = workspace;
1597
- const o_auth_app = 'OAuthApp'; DeleteOrgResourceType["o_auth_app"] = o_auth_app;
1598
- const authorized_o_auth_app = 'AuthorizedOAuthApp'; DeleteOrgResourceType["authorized_o_auth_app"] = authorized_o_auth_app;
1599
- const service_access_token = 'ServiceAccessToken'; DeleteOrgResourceType["service_access_token"] = service_access_token;
1600
- const personal_access_token2 = 'PersonalAccessToken'; DeleteOrgResourceType["personal_access_token2"] = personal_access_token2;
1601
- const connector2 = 'Connector'; DeleteOrgResourceType["connector2"] = connector2;
1602
- const normal_api_app = 'NormalApiApp'; DeleteOrgResourceType["normal_api_app"] = normal_api_app;
1603
- const connector_api_app = 'ConnectorApiApp'; DeleteOrgResourceType["connector_api_app"] = connector_api_app;
1604
- })(DeleteOrgResourceType || (DeleteOrgResourceType = {}));
1605
-
1606
- var DenyType; (function (DenyType) {
1607
- const visitors_prohibited = 'VisitorsProhibited'; DenyType["visitors_prohibited"] = visitors_prohibited;
1608
- const guest_prohibited_by_invited_user_enterprise2 = 'GuestProhibitedByInvitedUserEnterprise'; DenyType["guest_prohibited_by_invited_user_enterprise2"] = guest_prohibited_by_invited_user_enterprise2;
1609
- const prohibited_by_custom_people_management = 'ProhibitedByCustomPeopleManagement'; DenyType["prohibited_by_custom_people_management"] = prohibited_by_custom_people_management;
1610
- })(DenyType || (DenyType = {}));
1611
-
1612
- var DeploymentEnv; (function (DeploymentEnv) {
1613
- const dev2 = 'DEV'; DeploymentEnv["dev2"] = dev2;
1614
- const prod2 = 'PROD'; DeploymentEnv["prod2"] = prod2;
1615
- })(DeploymentEnv || (DeploymentEnv = {}));
1616
-
1617
- var DurationDay; (function (DurationDay) {
1618
- const _1 = '1'; DurationDay["_1"] = _1;
1619
- const _30 = '30'; DurationDay["_30"] = _30;
1620
- const _90 = '90'; DurationDay["_90"] = _90;
1621
- const _180 = '180'; DurationDay["_180"] = _180;
1622
- const _365 = '365'; DurationDay["_365"] = _365;
1623
- const customize = 'customize'; DurationDay["customize"] = customize;
1624
- const permanent = 'permanent'; DurationDay["permanent"] = permanent;
1625
- })(DurationDay || (DurationDay = {}));
1626
-
1627
- var DurationDay2; (function (DurationDay2) {
1628
- const _12 = '1'; DurationDay2["_12"] = _12;
1629
- const _302 = '30'; DurationDay2["_302"] = _302;
1630
- const _902 = '90'; DurationDay2["_902"] = _902;
1631
- const _1802 = '180'; DurationDay2["_1802"] = _1802;
1632
- const _3652 = '365'; DurationDay2["_3652"] = _3652;
1633
- const customize2 = 'customize'; DurationDay2["customize2"] = customize2;
1634
- const permanent2 = 'permanent'; DurationDay2["permanent2"] = permanent2;
1635
- })(DurationDay2 || (DurationDay2 = {}));
1636
-
1637
- var EncryptionAlgorithmType; (function (EncryptionAlgorithmType) {
1638
- const aes_256_gcm = 'AES-256-GCM'; EncryptionAlgorithmType["aes_256_gcm"] = aes_256_gcm;
1639
- })(EncryptionAlgorithmType || (EncryptionAlgorithmType = {}));
1640
-
1641
- var EncryptionConfigurationDataType; (function (EncryptionConfigurationDataType) {
1642
- const conversation = 'Conversation'; EncryptionConfigurationDataType["conversation"] = conversation;
1643
- const unknown = 'Unknown'; EncryptionConfigurationDataType["unknown"] = unknown;
1644
- })(EncryptionConfigurationDataType || (EncryptionConfigurationDataType = {}));
1645
-
1646
- var EncryptionKeyStatus; (function (EncryptionKeyStatus) {
1647
- const active3 = 'Active'; EncryptionKeyStatus["active3"] = active3;
1648
- const inactive = 'Inactive'; EncryptionKeyStatus["inactive"] = inactive;
1649
- })(EncryptionKeyStatus || (EncryptionKeyStatus = {}));
1650
-
1651
- var EncryptionKeyType; (function (EncryptionKeyType) {
1652
- const cloud_kms = 'CloudKMS'; EncryptionKeyType["cloud_kms"] = cloud_kms;
1653
- EncryptionKeyType["default"] = 'Default';
1654
- const unknown2 = 'Unknown'; EncryptionKeyType["unknown2"] = unknown2;
1655
- })(EncryptionKeyType || (EncryptionKeyType = {}));
1656
-
1657
- var EncryptSecretKeyType; (function (EncryptSecretKeyType) {
1658
- const user_custom2 = 'user_custom'; EncryptSecretKeyType["user_custom2"] = user_custom2;
1659
- const consumer3 = 'consumer'; EncryptSecretKeyType["consumer3"] = consumer3;
1660
- })(EncryptSecretKeyType || (EncryptSecretKeyType = {}));
1661
-
1662
- var EnterpriseRoleType; (function (EnterpriseRoleType) {
1663
- const super_admin = 'SuperAdmin'; EnterpriseRoleType["super_admin"] = super_admin;
1664
- const admin = 'Admin'; EnterpriseRoleType["admin"] = admin;
1665
- const member = 'Member'; EnterpriseRoleType["member"] = member;
1666
- const guest = 'Guest'; EnterpriseRoleType["guest"] = guest;
1667
- })(EnterpriseRoleType || (EnterpriseRoleType = {}));
1668
-
1669
- var EnterpriseSettingKey; (function (EnterpriseSettingKey) {
1670
- const join_enterprise_share_link_expiration_time = 'JoinEnterpriseShareLinkExpirationTime'; EnterpriseSettingKey["join_enterprise_share_link_expiration_time"] = join_enterprise_share_link_expiration_time;
1671
- const sso = 'SSO'; EnterpriseSettingKey["sso"] = sso;
1672
- const forbid_guest_join_enterprise = 'ForbidGuestJoinEnterprise'; EnterpriseSettingKey["forbid_guest_join_enterprise"] = forbid_guest_join_enterprise;
1673
- const forbid_member_join_other_enterprise = 'ForbidMemberJoinOtherEnterprise'; EnterpriseSettingKey["forbid_member_join_other_enterprise"] = forbid_member_join_other_enterprise;
1674
- const replace_enterprise_logo = 'ReplaceEnterpriseLogo'; EnterpriseSettingKey["replace_enterprise_logo"] = replace_enterprise_logo;
1675
- const forbid_custom_people_management = 'ForbidCustomPeopleManagement'; EnterpriseSettingKey["forbid_custom_people_management"] = forbid_custom_people_management;
1676
- const forbid_coze_store_plugin_access = 'ForbidCozeStorePluginAccess'; EnterpriseSettingKey["forbid_coze_store_plugin_access"] = forbid_coze_store_plugin_access;
1677
- const enterprise_member_listing_skill_coze_store = 'EnterpriseMemberListingSkillCozeStore'; EnterpriseSettingKey["enterprise_member_listing_skill_coze_store"] = enterprise_member_listing_skill_coze_store;
1678
- const listing_skill_enterprise_store_audit = 'ListingSkillEnterpriseStoreAudit'; EnterpriseSettingKey["listing_skill_enterprise_store_audit"] = listing_skill_enterprise_store_audit;
1679
- })(EnterpriseSettingKey || (EnterpriseSettingKey = {}));
1680
-
1681
- var EnterpriseSettingValueType; (function (EnterpriseSettingValueType) {
1682
- const string = 'String'; EnterpriseSettingValueType["string"] = string;
1683
- const boolean = 'Boolean'; EnterpriseSettingValueType["boolean"] = boolean;
1684
- const integer = 'Integer'; EnterpriseSettingValueType["integer"] = integer;
1685
- const string_list = 'StringList'; EnterpriseSettingValueType["string_list"] = string_list;
1686
- })(EnterpriseSettingValueType || (EnterpriseSettingValueType = {}));
1687
-
1688
- var HandleLevel; (function (HandleLevel) {
1689
- const must_handle = 'MustHandle'; HandleLevel["must_handle"] = must_handle;
1690
- const no_need_handle = 'NoNeedHandle'; HandleLevel["no_need_handle"] = no_need_handle;
1691
- })(HandleLevel || (HandleLevel = {}));
1692
-
1693
- var InstallationStatus; (function (InstallationStatus) {
1694
- const pending_review_app_auth = 'pending_review_app_auth'; InstallationStatus["pending_review_app_auth"] = pending_review_app_auth;
1695
- const pending_review_app_obo = 'pending_review_app_obo'; InstallationStatus["pending_review_app_obo"] = pending_review_app_obo;
1696
- const approved_app_auth = 'approved_app_auth'; InstallationStatus["approved_app_auth"] = approved_app_auth;
1697
- const approved_app_obo = 'approved_app_obo'; InstallationStatus["approved_app_obo"] = approved_app_obo;
1698
- })(InstallationStatus || (InstallationStatus = {}));
1699
-
1700
- var InvitationDenyType; (function (InvitationDenyType) {
1701
- const no_permission = 'NoPermission'; InvitationDenyType["no_permission"] = no_permission;
1702
- const guest_prohibited_by_enterprise2 = 'GuestProhibitedByEnterprise'; InvitationDenyType["guest_prohibited_by_enterprise2"] = guest_prohibited_by_enterprise2;
1703
- const guest_prohibited_by_invited_user_enterprise3 = 'GuestProhibitedByInvitedUserEnterprise'; InvitationDenyType["guest_prohibited_by_invited_user_enterprise3"] = guest_prohibited_by_invited_user_enterprise3;
1704
- const guest_prohibited_by_custom_people_management = 'GuestProhibitedByCustomPeopleManagement'; InvitationDenyType["guest_prohibited_by_custom_people_management"] = guest_prohibited_by_custom_people_management;
1705
- })(InvitationDenyType || (InvitationDenyType = {}));
1706
-
1707
- var InvitationInfoStatus; (function (InvitationInfoStatus) {
1708
- const confirming2 = 'Confirming'; InvitationInfoStatus["confirming2"] = confirming2;
1709
- const joined3 = 'Joined'; InvitationInfoStatus["joined3"] = joined3;
1710
- const rejected3 = 'Rejected'; InvitationInfoStatus["rejected3"] = rejected3;
1711
- const revoked2 = 'Revoked'; InvitationInfoStatus["revoked2"] = revoked2;
1712
- const expired3 = 'Expired'; InvitationInfoStatus["expired3"] = expired3;
1713
- const deny2 = 'Deny'; InvitationInfoStatus["deny2"] = deny2;
1714
- })(InvitationInfoStatus || (InvitationInfoStatus = {}));
1715
-
1716
- var InvitationStatus; (function (InvitationStatus) {
1717
- const confirming = 'Confirming'; InvitationStatus["confirming"] = confirming;
1718
- const joined2 = 'Joined'; InvitationStatus["joined2"] = joined2;
1719
- const rejected2 = 'Rejected'; InvitationStatus["rejected2"] = rejected2;
1720
- const revoked = 'Revoked'; InvitationStatus["revoked"] = revoked;
1721
- const expired2 = 'Expired'; InvitationStatus["expired2"] = expired2;
1722
- })(InvitationStatus || (InvitationStatus = {}));
1723
-
1724
- var InvitedUserStatus; (function (InvitedUserStatus) {
1725
- const can_join = 'CanJoin'; InvitedUserStatus["can_join"] = can_join;
1726
- const guest_prohibited_by_enterprise = 'GuestProhibitedByEnterprise'; InvitedUserStatus["guest_prohibited_by_enterprise"] = guest_prohibited_by_enterprise;
1727
- const guest_prohibited_by_invited_user_enterprise = 'GuestProhibitedByInvitedUserEnterprise'; InvitedUserStatus["guest_prohibited_by_invited_user_enterprise"] = guest_prohibited_by_invited_user_enterprise;
1728
- })(InvitedUserStatus || (InvitedUserStatus = {}));
1729
-
1730
- var InviteLinkStatus$1; (function (InviteLinkStatus) {
1731
- const can_apply = 'CanApply'; InviteLinkStatus["can_apply"] = can_apply;
1732
- const already_applied = 'AlreadyApplied'; InviteLinkStatus["already_applied"] = already_applied;
1733
- const joined = 'Joined'; InviteLinkStatus["joined"] = joined;
1734
- const expired = 'Expired'; InviteLinkStatus["expired"] = expired;
1735
- const deny = 'Deny'; InviteLinkStatus["deny"] = deny;
1736
- })(InviteLinkStatus$1 || (InviteLinkStatus$1 = {}));
1737
-
1738
- var Level; (function (Level) {
1739
- const free = 'Free'; Level["free"] = free;
1740
- const premium_lite = 'PremiumLite'; Level["premium_lite"] = premium_lite;
1741
- const premium = 'Premium'; Level["premium"] = premium;
1742
- const premium_plus = 'PremiumPlus'; Level["premium_plus"] = premium_plus;
1743
- const v_1_pro_instance = 'V1ProInstance'; Level["v_1_pro_instance"] = v_1_pro_instance;
1744
- const pro_personal = 'ProPersonal'; Level["pro_personal"] = pro_personal;
1745
- const coze_personal_plus = 'CozePersonalPlus'; Level["coze_personal_plus"] = coze_personal_plus;
1746
- const coze_personal_advanced = 'CozePersonalAdvanced'; Level["coze_personal_advanced"] = coze_personal_advanced;
1747
- const coze_personal_pro = 'CozePersonalPro'; Level["coze_personal_pro"] = coze_personal_pro;
1748
- const team = 'Team'; Level["team"] = team;
1749
- const enterprise_basic = 'EnterpriseBasic'; Level["enterprise_basic"] = enterprise_basic;
1750
- const enterprise = 'Enterprise'; Level["enterprise"] = enterprise;
1751
- const enterprise_pro = 'EnterprisePro'; Level["enterprise_pro"] = enterprise_pro;
1752
- })(Level || (Level = {}));
1753
-
1754
- var ListOption; (function (ListOption) {
1755
- const user_custom_only = 'user_custom_only'; ListOption["user_custom_only"] = user_custom_only;
1756
- const all2 = 'all'; ListOption["all2"] = all2;
1757
- })(ListOption || (ListOption = {}));
1758
-
1759
- var OAuth2ProviderType; (function (OAuth2ProviderType) {
1760
- const system = 'system'; OAuth2ProviderType["system"] = system;
1761
- const custom = 'custom'; OAuth2ProviderType["custom"] = custom;
1762
- })(OAuth2ProviderType || (OAuth2ProviderType = {}));
1763
-
1764
- var OrganizationApplicationDenyType; (function (OrganizationApplicationDenyType) {
1765
- const not_in_enterprise = 'NotInEnterprise'; OrganizationApplicationDenyType["not_in_enterprise"] = not_in_enterprise;
1766
- const prohibited_by_custom_people_management2 = 'ProhibitedByCustomPeopleManagement'; OrganizationApplicationDenyType["prohibited_by_custom_people_management2"] = prohibited_by_custom_people_management2;
1767
- })(OrganizationApplicationDenyType || (OrganizationApplicationDenyType = {}));
1768
-
1769
- var OrganizationApplicationForEnterpriseMemberStatus; (function (OrganizationApplicationForEnterpriseMemberStatus) {
1770
- const can_apply3 = 'CanApply'; OrganizationApplicationForEnterpriseMemberStatus["can_apply3"] = can_apply3;
1771
- const already_applied3 = 'AlreadyApplied'; OrganizationApplicationForEnterpriseMemberStatus["already_applied3"] = already_applied3;
1772
- const joined5 = 'Joined'; OrganizationApplicationForEnterpriseMemberStatus["joined5"] = joined5;
1773
- const deny4 = 'Deny'; OrganizationApplicationForEnterpriseMemberStatus["deny4"] = deny4;
1774
- })(OrganizationApplicationForEnterpriseMemberStatus || (OrganizationApplicationForEnterpriseMemberStatus = {}));
1775
-
1776
- var OrganizationRoleType; (function (OrganizationRoleType) {
1777
- const super_admin2 = 'SuperAdmin'; OrganizationRoleType["super_admin2"] = super_admin2;
1778
- const admin2 = 'Admin'; OrganizationRoleType["admin2"] = admin2;
1779
- const member2 = 'Member'; OrganizationRoleType["member2"] = member2;
1780
- const guest2 = 'Guest'; OrganizationRoleType["guest2"] = guest2;
1781
- })(OrganizationRoleType || (OrganizationRoleType = {}));
1782
-
1783
- var Ownership; (function (Ownership) {
1784
- const developer = 'developer'; Ownership["developer"] = developer;
1785
- const consumer2 = 'consumer'; Ownership["consumer2"] = consumer2;
1786
- })(Ownership || (Ownership = {}));
1787
-
1788
- var PatSearchOption; (function (PatSearchOption) {
1789
- const all = 'all'; PatSearchOption["all"] = all;
1790
- const owned = 'owned'; PatSearchOption["owned"] = owned;
1791
- const others = 'others'; PatSearchOption["others"] = others;
1792
- })(PatSearchOption || (PatSearchOption = {}));
1793
-
1794
- var PeopleType; (function (PeopleType) {
1795
- const enterprise_member = 'EnterpriseMember'; PeopleType["enterprise_member"] = enterprise_member;
1796
- const enterprise_guest = 'EnterpriseGuest'; PeopleType["enterprise_guest"] = enterprise_guest;
1797
- })(PeopleType || (PeopleType = {}));
1798
-
1799
- var ProjectAuthIntegrationStatus; (function (ProjectAuthIntegrationStatus) {
1800
- const not_created = 'NotCreated'; ProjectAuthIntegrationStatus["not_created"] = not_created;
1801
- const enabled = 'Enabled'; ProjectAuthIntegrationStatus["enabled"] = enabled;
1802
- const disabled = 'Disabled'; ProjectAuthIntegrationStatus["disabled"] = disabled;
1803
- })(ProjectAuthIntegrationStatus || (ProjectAuthIntegrationStatus = {}));
1804
-
1805
- var ProjectEnvironment; (function (ProjectEnvironment) {
1806
- const production = 'Production'; ProjectEnvironment["production"] = production;
1807
- const development = 'Development'; ProjectEnvironment["development"] = development;
1808
- })(ProjectEnvironment || (ProjectEnvironment = {}));
1809
-
1810
- var ProjectType$2; (function (ProjectType) {
1811
- const skill = 'skill'; ProjectType["skill"] = skill;
1812
- })(ProjectType$2 || (ProjectType$2 = {}));
1813
-
1814
- var SearchEnv; (function (SearchEnv) {
1815
- const dev = 'dev'; SearchEnv["dev"] = dev;
1816
- const prod = 'prod'; SearchEnv["prod"] = prod;
1817
- })(SearchEnv || (SearchEnv = {}));
1818
-
1819
- var SecretKeyType; (function (SecretKeyType) {
1820
- const user_custom = 'user_custom'; SecretKeyType["user_custom"] = user_custom;
1821
- const coze_default = 'coze_default'; SecretKeyType["coze_default"] = coze_default;
1822
- const consumer = 'consumer'; SecretKeyType["consumer"] = consumer;
1823
- })(SecretKeyType || (SecretKeyType = {}));
1824
-
1825
- var Status; (function (Status) {
1826
- const active2 = 'Active'; Status["active2"] = active2;
1827
- const deactive = 'Deactive'; Status["deactive"] = deactive;
1828
- })(Status || (Status = {}));
1829
-
1830
- var UserStatus$1; (function (UserStatus) {
1831
- const active = 'active'; UserStatus["active"] = active;
1832
- const deactivated = 'deactivated'; UserStatus["deactivated"] = deactivated;
1833
- const offboarded = 'offboarded'; UserStatus["offboarded"] = offboarded;
1834
- })(UserStatus$1 || (UserStatus$1 = {}));
1835
-
1836
- var VisibilityKey; (function (VisibilityKey) {
1837
- const studio_space_selector = 'studio_space_selector'; VisibilityKey["studio_space_selector"] = studio_space_selector;
1838
- const studio_create_project_btn = 'studio_create_project_btn'; VisibilityKey["studio_create_project_btn"] = studio_create_project_btn;
1839
- const studio_home_page = 'studio_home_page'; VisibilityKey["studio_home_page"] = studio_home_page;
1840
- const studio_develop = 'studio_develop'; VisibilityKey["studio_develop"] = studio_develop;
1841
- const studio_library = 'studio_library'; VisibilityKey["studio_library"] = studio_library;
1842
- const studio_tasks = 'studio_tasks'; VisibilityKey["studio_tasks"] = studio_tasks;
1843
- const studio_evaluate = 'studio_evaluate'; VisibilityKey["studio_evaluate"] = studio_evaluate;
1844
- const studio_space_manage = 'studio_space_manage'; VisibilityKey["studio_space_manage"] = studio_space_manage;
1845
- const studio_templates_store = 'studio_templates_store'; VisibilityKey["studio_templates_store"] = studio_templates_store;
1846
- const studio_plugins_store = 'studio_plugins_store'; VisibilityKey["studio_plugins_store"] = studio_plugins_store;
1847
- const studio_agents_store = 'studio_agents_store'; VisibilityKey["studio_agents_store"] = studio_agents_store;
1848
- const studio_playground = 'studio_playground'; VisibilityKey["studio_playground"] = studio_playground;
1849
- const studio_docs = 'studio_docs'; VisibilityKey["studio_docs"] = studio_docs;
1850
- const studio_enterprise_agents_store = 'studio_enterprise_agents_store'; VisibilityKey["studio_enterprise_agents_store"] = studio_enterprise_agents_store;
1851
- const studio_enterprise_plugins_store = 'studio_enterprise_plugins_store'; VisibilityKey["studio_enterprise_plugins_store"] = studio_enterprise_plugins_store;
1852
- const studio_organization_manage = 'studio_organization_manage'; VisibilityKey["studio_organization_manage"] = studio_organization_manage;
1853
- const studio_enterprise_card = 'studio_enterprise_card'; VisibilityKey["studio_enterprise_card"] = studio_enterprise_card;
1854
- const studio_subscription_card = 'studio_subscription_card'; VisibilityKey["studio_subscription_card"] = studio_subscription_card;
1855
- const studio_personal_menu = 'studio_personal_menu'; VisibilityKey["studio_personal_menu"] = studio_personal_menu;
1856
- const studio_more_products = 'studio_more_products'; VisibilityKey["studio_more_products"] = studio_more_products;
1857
- const studio_notice = 'studio_notice'; VisibilityKey["studio_notice"] = studio_notice;
1858
- const studio_migration_banner = 'studio_migration_banner'; VisibilityKey["studio_migration_banner"] = studio_migration_banner;
1859
- const coding_space_selector = 'coding_space_selector'; VisibilityKey["coding_space_selector"] = coding_space_selector;
1860
- const coding_create_project = 'coding_create_project'; VisibilityKey["coding_create_project"] = coding_create_project;
1861
- const coding_project_manage = 'coding_project_manage'; VisibilityKey["coding_project_manage"] = coding_project_manage;
1862
- const coding_integrations = 'coding_integrations'; VisibilityKey["coding_integrations"] = coding_integrations;
1863
- const coding_library = 'coding_library'; VisibilityKey["coding_library"] = coding_library;
1864
- const coding_tasks = 'coding_tasks'; VisibilityKey["coding_tasks"] = coding_tasks;
1865
- const coding_playground = 'coding_playground'; VisibilityKey["coding_playground"] = coding_playground;
1866
- const coding_evaluate = 'coding_evaluate'; VisibilityKey["coding_evaluate"] = coding_evaluate;
1867
- const coding_coze_redirect = 'coding_coze_redirect'; VisibilityKey["coding_coze_redirect"] = coding_coze_redirect;
1868
- const coding_docs = 'coding_docs'; VisibilityKey["coding_docs"] = coding_docs;
1869
- const coding_community = 'coding_community'; VisibilityKey["coding_community"] = coding_community;
1870
- const coding_enterprise_card = 'coding_enterprise_card'; VisibilityKey["coding_enterprise_card"] = coding_enterprise_card;
1871
- const coding_subscription_card = 'coding_subscription_card'; VisibilityKey["coding_subscription_card"] = coding_subscription_card;
1872
- const coding_personal_menu = 'coding_personal_menu'; VisibilityKey["coding_personal_menu"] = coding_personal_menu;
1873
- const coding_notice = 'coding_notice'; VisibilityKey["coding_notice"] = coding_notice;
1874
- const admin_organization_manage = 'admin_organization_manage'; VisibilityKey["admin_organization_manage"] = admin_organization_manage;
1875
- const admin_member_manage = 'admin_member_manage'; VisibilityKey["admin_member_manage"] = admin_member_manage;
1876
- const admin_enterprise_config = 'admin_enterprise_config'; VisibilityKey["admin_enterprise_config"] = admin_enterprise_config;
1877
- })(VisibilityKey || (VisibilityKey = {}));
1878
-
1879
- var VolcanoUserType$2; (function (VolcanoUserType) {
1880
- const root_user = 'RootUser'; VolcanoUserType["root_user"] = root_user;
1881
- const basic_user = 'BasicUser'; VolcanoUserType["basic_user"] = basic_user;
1882
- })(VolcanoUserType$2 || (VolcanoUserType$2 = {}));
1883
1252
 
1884
1253
 
1885
1254
 
@@ -2974,15 +2343,11 @@ var VolcanoUserType$2; (function (VolcanoUserType) {
2974
2343
 
2975
2344
 
2976
2345
 
2346
+ /* eslint-enable */
2977
2347
 
2348
+ function _optionalChain$J(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = fn(value); } else if (op === 'call' || op === 'optionalCall') { value = fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; }// THIS IS AN AUTOGENERATED FILE. DO NOT EDIT THIS FILE DIRECTLY.
2978
2349
 
2979
-
2980
-
2981
- /* eslint-enable */
2982
-
2983
- function _optionalChain$H(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = fn(value); } else if (op === 'call' || op === 'optionalCall') { value = fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; }// THIS IS AN AUTOGENERATED FILE. DO NOT EDIT THIS FILE DIRECTLY.
2984
-
2985
-
2350
+
2986
2351
 
2987
2352
 
2988
2353
 
@@ -4363,8 +3728,8 @@ class PermissionApiService {
4363
3728
 
4364
3729
 
4365
3730
  ) {PermissionApiService.prototype.__init.call(this);PermissionApiService.prototype.__init2.call(this);
4366
- this.request = _optionalChain$H([options, 'optionalAccess', _ => _.request]) || this.request;
4367
- this.baseURL = _optionalChain$H([options, 'optionalAccess', _2 => _2.baseURL]) || this.baseURL;
3731
+ this.request = _optionalChain$J([options, 'optionalAccess', _ => _.request]) || this.request;
3732
+ this.baseURL = _optionalChain$J([options, 'optionalAccess', _2 => _2.baseURL]) || this.baseURL;
4368
3733
  }
4369
3734
 
4370
3735
  genBaseURL(path) {
@@ -7141,259 +6506,1073 @@ class PermissionApiService {
7141
6506
  return this.request({ url, method, data }, options);
7142
6507
  }
7143
6508
 
7144
- /**
7145
- * GET /api/permission_api/volcano/get_volcano_login_masked_mobile
7146
- *
7147
- * [jump to BAM](https://cloud.bytedance.net/bam/rd/flow.permission.api/api_doc/show_doc?version=1.0.392&endpoint_id=3880020)
7148
- *
7149
- * get volcano login masked mobile
7150
- *
7151
- * get volcano login masked mobile
7152
- */
7153
- GetVolcanoLoginMaskedMobile(
7154
- req,
7155
- options,
7156
- ) {
7157
- const url = this.genBaseURL(
7158
- '/api/permission_api/volcano/get_volcano_login_masked_mobile',
7159
- );
7160
- const method = 'GET';
7161
- return this.request({ url, method }, options);
6509
+ /**
6510
+ * GET /api/permission_api/volcano/get_volcano_login_masked_mobile
6511
+ *
6512
+ * [jump to BAM](https://cloud.bytedance.net/bam/rd/flow.permission.api/api_doc/show_doc?version=1.0.392&endpoint_id=3880020)
6513
+ *
6514
+ * get volcano login masked mobile
6515
+ *
6516
+ * get volcano login masked mobile
6517
+ */
6518
+ GetVolcanoLoginMaskedMobile(
6519
+ req,
6520
+ options,
6521
+ ) {
6522
+ const url = this.genBaseURL(
6523
+ '/api/permission_api/volcano/get_volcano_login_masked_mobile',
6524
+ );
6525
+ const method = 'GET';
6526
+ return this.request({ url, method }, options);
6527
+ }
6528
+ }
6529
+ const PermissionApi = new PermissionApiService({});
6530
+ /* eslint-enable */
6531
+
6532
+ function _nullishCoalesce$k(lhs, rhsFn) { if (lhs != null) { return lhs; } else { return rhsFn(); } }
6533
+
6534
+
6535
+
6536
+
6537
+
6538
+ class AuthService {
6539
+
6540
+
6541
+ constructor( ctx) {this.ctx = ctx;
6542
+ this.config = ctx.config;
6543
+ }
6544
+
6545
+ getOAuthConfig() {
6546
+ return {
6547
+ baseURL: _nullishCoalesce$k(this.config.openApiBaseUrl, () => ( DEFAULT_CONFIG.openApiBaseUrl)),
6548
+ clientId: _nullishCoalesce$k(this.config.clientId, () => ( DEFAULT_CONFIG.clientId)),
6549
+ };
6550
+ }
6551
+
6552
+ async clearUserContext() {
6553
+ this.config.organizationId = undefined;
6554
+ this.config.enterpriseId = undefined;
6555
+ this.config.spaceId = undefined;
6556
+
6557
+ await saveConfig({
6558
+ organizationId: undefined,
6559
+ enterpriseId: undefined,
6560
+ spaceId: undefined,
6561
+ });
6562
+ }
6563
+
6564
+ async clearAuthData() {
6565
+ this.config.accessToken = undefined;
6566
+ this.config.refreshToken = undefined;
6567
+ this.config.tokenExpiresAt = undefined;
6568
+
6569
+ await saveConfig({
6570
+ accessToken: undefined,
6571
+ refreshToken: undefined,
6572
+ tokenExpiresAt: undefined,
6573
+ });
6574
+ }
6575
+
6576
+ async login(options) {
6577
+ this.ctx.ui.verbose('Initiating login process...');
6578
+
6579
+ if (options.token) {
6580
+ this.ctx.ui.info('Using Personal Access Token (PAT)...');
6581
+ this.config.accessToken = options.token;
6582
+ await saveConfig({
6583
+ accessToken: options.token,
6584
+ refreshToken: undefined,
6585
+ tokenExpiresAt: undefined,
6586
+ });
6587
+ await this.clearUserContext();
6588
+ this.ctx.ui.info('Authentication successful. Credentials saved.');
6589
+ if (this.ctx.format === 'json') {
6590
+ this.ctx.response.print({ success: true, method: 'PAT' });
6591
+ }
6592
+ return;
6593
+ }
6594
+
6595
+ try {
6596
+ this.ctx.ui.info('Starting OAuth flow...');
6597
+ const { baseURL, clientId } = this.getOAuthConfig();
6598
+
6599
+ this.ctx.ui.verbose('Starting OAuth device flow...');
6600
+
6601
+ const deviceCode = await getDeviceCode({
6602
+ baseURL,
6603
+ clientId,
6604
+ });
6605
+
6606
+ const verificationUri = `${deviceCode.verification_uri}?user_code=${deviceCode.user_code}`;
6607
+
6608
+ this.ctx.ui.info(
6609
+ `Please visit ${chalk.underline(verificationUri)} and authorize the application.`,
6610
+ );
6611
+
6612
+ const deviceToken = await getDeviceToken(
6613
+ {
6614
+ baseURL,
6615
+ clientId,
6616
+ deviceCode: deviceCode.device_code,
6617
+ poll: true,
6618
+ },
6619
+ this.ctx,
6620
+ );
6621
+
6622
+ this.ctx.ui.debug(
6623
+ `Polling for device token success: ${JSON.stringify(deviceToken)}`,
6624
+ );
6625
+
6626
+ await this.saveOAuthToken(deviceToken);
6627
+
6628
+ this.ctx.ui.debug('Saving OAuth token successfully.');
6629
+
6630
+ await this.clearUserContext();
6631
+
6632
+ this.ctx.ui.info('Authentication successful. Credentials saved.');
6633
+ if (this.ctx.format === 'json') {
6634
+ this.ctx.response.print({ success: true, method: 'OAuth' });
6635
+ }
6636
+ } catch (oauthError) {
6637
+ this.ctx.ui.error(
6638
+ `OAuth login failed: ${oauthError.message || oauthError}`,
6639
+ );
6640
+ throw oauthError;
6641
+ }
6642
+ }
6643
+
6644
+ async logout() {
6645
+ await this.clearAuthData();
6646
+ await this.clearUserContext();
6647
+ this.ctx.ui.info('You have been logged out. Credentials cleared.');
6648
+ if (this.ctx.format === 'json') {
6649
+ this.ctx.response.print({ success: true, logged_out: true });
6650
+ }
6651
+ }
6652
+
6653
+ async whoami() {
6654
+ const token = await this.getValidAccessToken();
6655
+
6656
+ if (!token) {
6657
+ this.ctx.response.print({ logged_in: false });
6658
+ return;
6659
+ }
6660
+
6661
+ this.ctx.ui.info('Fetching user information...');
6662
+
6663
+ const info = {
6664
+ user: 'mock-user@coze.io',
6665
+ org: 'mock-org',
6666
+ profile: 'default',
6667
+ };
6668
+
6669
+ this.ctx.response.print({
6670
+ logged_in: true,
6671
+ ...info,
6672
+ });
6673
+ }
6674
+
6675
+ async status() {
6676
+ const token = await this.getValidAccessToken();
6677
+
6678
+ this.ctx.ui.info('Checking authentication status...');
6679
+
6680
+ if (!token) {
6681
+ this.ctx.response.print({ logged_in: false });
6682
+ return;
6683
+ }
6684
+
6685
+ const expiresAt = this.config.tokenExpiresAt;
6686
+ const isOAuth = !!this.config.refreshToken;
6687
+
6688
+ const { data: user } = await PermissionApi.GetUserProfile(
6689
+ {},
6690
+ { baseURL: this.config.openApiBaseUrl },
6691
+ );
6692
+
6693
+ const status = {
6694
+ logged_in: true,
6695
+ user,
6696
+ token_expires_at: expiresAt
6697
+ ? new Date(expiresAt).toISOString()
6698
+ : !isOAuth
6699
+ ? 'Never (PAT)'
6700
+ : undefined,
6701
+ };
6702
+
6703
+ this.ctx.response.print(status);
6704
+ }
6705
+
6706
+ async getValidAccessToken() {
6707
+ const { accessToken, refreshToken, tokenExpiresAt } = this.config;
6708
+
6709
+ if (!accessToken) {
6710
+ return undefined;
6711
+ }
6712
+
6713
+ // If there is no refresh token, it means it's a PAT, so it doesn't expire
6714
+ if (!refreshToken) {
6715
+ return accessToken;
6716
+ }
6717
+
6718
+ // If the token is not expired (add 5 minutes buffer), return it
6719
+ const bufferTime = 5 * 60 * 1000;
6720
+ if (tokenExpiresAt && Date.now() < tokenExpiresAt - bufferTime) {
6721
+ return accessToken;
6722
+ }
6723
+
6724
+ // Token is expired or about to expire, let's refresh it
6725
+ this.ctx.ui.verbose(
6726
+ 'Access token is expired or expiring soon, refreshing...',
6727
+ );
6728
+
6729
+ try {
6730
+ const { baseURL, clientId } = this.getOAuthConfig();
6731
+
6732
+ const newToken = await refreshOAuthToken({
6733
+ baseURL,
6734
+ clientId,
6735
+ refreshToken,
6736
+ });
6737
+
6738
+ await this.saveOAuthToken(newToken);
6739
+ this.ctx.ui.verbose('Token refreshed successfully.');
6740
+ return newToken.access_token;
6741
+ } catch (error) {
6742
+ // Clear token config if refresh fails to require re-login
6743
+ this.ctx.ui.error(`Failed to refresh token: ${error.message || error}`);
6744
+ await this.clearAuthData();
6745
+ return undefined;
6746
+ }
6747
+ }
6748
+
6749
+ async saveOAuthToken(token) {
6750
+ const tokenExpiresAt = token.expires_in * 1000;
6751
+
6752
+ // Update local config object so we don't have to reload
6753
+ this.config.accessToken = token.access_token;
6754
+ this.config.refreshToken = token.refresh_token;
6755
+ this.config.tokenExpiresAt = tokenExpiresAt;
6756
+
6757
+ await saveConfig({
6758
+ accessToken: token.access_token,
6759
+ refreshToken: token.refresh_token,
6760
+ tokenExpiresAt,
6761
+ });
6762
+ }
6763
+ }
6764
+
6765
+ function _nullishCoalesce$j(lhs, rhsFn) { if (lhs != null) { return lhs; } else { return rhsFn(); } } function _optionalChain$I(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = fn(value); } else if (op === 'call' || op === 'optionalCall') { value = fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; }
6766
+
6767
+
6768
+
6769
+
6770
+
6771
+
6772
+
6773
+
6774
+
6775
+
6776
+ const C = {
6777
+ reset: '\x1b[0m',
6778
+ bold: '\x1b[1m',
6779
+ dim: '\x1b[2m',
6780
+ red: '\x1b[31m',
6781
+ green: '\x1b[32m',
6782
+ yellow: '\x1b[33m',
6783
+ cyan: '\x1b[36m',
6784
+ silver: '\x1b[90m',
6785
+ };
6786
+
6787
+ const BADGES = {
6788
+ PROC: '[PROC]',
6789
+ INFO: '[INFO]',
6790
+ WARN: '[WARN]',
6791
+ ERR: '[ERR]',
6792
+ DONE: '[DONE]',
6793
+ DBG: '[DBG]',
6794
+ };
6795
+ const LEVEL_PRIORITY = {
6796
+ debug: 0,
6797
+ verbose: 1,
6798
+ info: 2,
6799
+ success: 3,
6800
+ warn: 4,
6801
+ error: 5,
6802
+ };
6803
+ function badge(text) {
6804
+ return `${C.dim}${C.bold}${text}${C.reset}`;
6805
+ }
6806
+ class UI {
6807
+
6808
+
6809
+
6810
+
6811
+
6812
+
6813
+ constructor(
6814
+ log,
6815
+ format,
6816
+ level = 'info',
6817
+ ) {
6818
+ this.log = log;
6819
+ this.silent = format === 'json';
6820
+ this.useColor = this.detectColorSupport();
6821
+ this.level = level;
6822
+ this.levelPriority = _nullishCoalesce$j(LEVEL_PRIORITY[level], () => ( 2));
6823
+ }
6824
+
6825
+ detectColorSupport() {
6826
+ return _optionalChain$I([process, 'access', _ => _.stderr, 'optionalAccess', _2 => _2.isTTY]) === true && process.env.NO_COLOR === undefined;
6827
+ }
6828
+
6829
+ paint(code, text) {
6830
+ return this.useColor ? `${code}${text}${C.reset}` : text;
6831
+ }
6832
+
6833
+ shouldOutput(methodLevel) {
6834
+ if (this.silent) {
6835
+ return false;
6836
+ }
6837
+ return LEVEL_PRIORITY[methodLevel] >= this.levelPriority;
6838
+ }
6839
+
6840
+ verbose(msg, ...args) {
6841
+ this.log.verbose(msg, ...args);
6842
+ if (!this.shouldOutput('verbose')) {
6843
+ return;
6844
+ }
6845
+ process.stderr.write(`${badge(BADGES.PROC)} ${this.paint(C.cyan, msg)}\n`);
6846
+ }
6847
+
6848
+ info(msg, ...args) {
6849
+ this.log.info(msg, ...args);
6850
+ if (!this.shouldOutput('info')) {
6851
+ return;
6852
+ }
6853
+ process.stderr.write(`${badge(BADGES.INFO)} ${this.paint(C.reset, msg)}\n`);
6854
+ }
6855
+
6856
+ warn(msg, ...args) {
6857
+ this.log.warn(msg, ...args);
6858
+ if (!this.shouldOutput('warn')) {
6859
+ return;
6860
+ }
6861
+ process.stderr.write(
6862
+ `${badge(BADGES.WARN)} ${this.paint(C.yellow, msg)}\n`,
6863
+ );
6864
+ }
6865
+
6866
+ error(msg, ...args) {
6867
+ this.log.error(msg, ...args);
6868
+ if (!this.shouldOutput('error')) {
6869
+ return;
6870
+ }
6871
+ process.stderr.write(`${badge(BADGES.ERR)} ${this.paint(C.red, msg)}\n`);
6872
+ }
6873
+
6874
+ success(msg, ...args) {
6875
+ this.log.success(msg, ...args);
6876
+ if (!this.shouldOutput('success')) {
6877
+ return;
6878
+ }
6879
+ process.stderr.write(`${badge(BADGES.DONE)} ${this.paint(C.green, msg)}\n`);
6880
+ }
6881
+
6882
+ debug(msg, ...args) {
6883
+ this.log.debug(msg, ...args);
6884
+ if (!this.shouldOutput('debug')) {
6885
+ return;
6886
+ }
6887
+ process.stderr.write(`${badge(BADGES.DBG)} ${this.paint(C.silver, msg)}\n`);
6888
+ }
6889
+ }
6890
+
6891
+ class JsonFormatter {
6892
+ format(data) {
6893
+ const output = JSON.stringify(data, null, 2);
6894
+ return output.endsWith('\n') ? output : `${output}\n`;
6895
+ }
6896
+
6897
+ formatError(error) {
6898
+ const errorObj = {
6899
+ name: error.name,
6900
+ message: error.message,
6901
+ code: error.code,
6902
+ details: error.details,
6903
+ };
6904
+ const output = JSON.stringify(errorObj, null, 2);
6905
+ return output.endsWith('\n') ? output : `${output}\n`;
6906
+ }
6907
+ }
6908
+
6909
+ function _nullishCoalesce$i(lhs, rhsFn) { if (lhs != null) { return lhs; } else { return rhsFn(); } } function _optionalChain$H(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = fn(value); } else if (op === 'call' || op === 'optionalCall') { value = fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; }
6910
+
6911
+
6912
+
6913
+
6914
+
6915
+
6916
+
6917
+
6918
+
6919
+
6920
+
6921
+
6922
+
6923
+
6924
+
6925
+
6926
+
6927
+
6928
+
6929
+ function stripAnsi(input) {
6930
+ // eslint-disable-next-line no-control-regex
6931
+ const ansiPattern = /\u001B(?:[@-Z\\-_]|\[[0-?]*[ -/]*[@-~])/g;
6932
+ return input.replace(ansiPattern, '');
6933
+ }
6934
+
6935
+ function isFullWidthCodePoint(codePoint) {
6936
+ if (codePoint >= 0x1100 && codePoint <= 0x115f) {
6937
+ return true;
6938
+ }
6939
+ if (codePoint === 0x2329 || codePoint === 0x232a) {
6940
+ return true;
6941
+ }
6942
+ if (codePoint >= 0x2e80 && codePoint <= 0x303e) {
6943
+ return true;
6944
+ }
6945
+ if (codePoint >= 0x3040 && codePoint <= 0xa4cf) {
6946
+ return true;
6947
+ }
6948
+ if (codePoint >= 0xac00 && codePoint <= 0xd7a3) {
6949
+ return true;
6950
+ }
6951
+ if (codePoint >= 0xf900 && codePoint <= 0xfaff) {
6952
+ return true;
6953
+ }
6954
+ if (codePoint >= 0xfe10 && codePoint <= 0xfe19) {
6955
+ return true;
6956
+ }
6957
+ if (codePoint >= 0xfe30 && codePoint <= 0xfe6f) {
6958
+ return true;
6959
+ }
6960
+ if (codePoint >= 0xff00 && codePoint <= 0xff60) {
6961
+ return true;
6962
+ }
6963
+ if (codePoint >= 0xffe0 && codePoint <= 0xffe6) {
6964
+ return true;
6965
+ }
6966
+ if (codePoint >= 0x1f300 && codePoint <= 0x1fa9f) {
6967
+ return true;
6968
+ }
6969
+ if (codePoint >= 0x20000 && codePoint <= 0x3fffd) {
6970
+ return true;
6971
+ }
6972
+ return false;
6973
+ }
6974
+
6975
+ function stringWidth(input) {
6976
+ const stripped = stripAnsi(input);
6977
+ if (!stripped) {
6978
+ return 0;
6979
+ }
6980
+
6981
+ const combiningMarks =
6982
+ /[\u0300-\u036F\u1AB0-\u1AFF\u1DC0-\u1DFF\u20D0-\u20FF\uFE20-\uFE2F]/u;
6983
+
6984
+ let width = 0;
6985
+ const chars = Array.from(stripped);
6986
+ for (let i = 0; i < chars.length; i += 1) {
6987
+ const char = _nullishCoalesce$i(chars[i], () => ( ''));
6988
+ if (combiningMarks.test(char)) {
6989
+ continue;
6990
+ }
6991
+ const codePoint = char.codePointAt(0);
6992
+ if (codePoint === undefined) {
6993
+ continue;
6994
+ }
6995
+ width += isFullWidthCodePoint(codePoint) ? 2 : 1;
6996
+ }
6997
+ return width;
6998
+ }
6999
+
7000
+ function padRightVisible(str, width) {
7001
+ const current = stringWidth(str);
7002
+ if (current >= width) {
7003
+ return str;
7004
+ }
7005
+ return `${str}${' '.repeat(width - current)}`;
7006
+ }
7007
+
7008
+ function truncateVisible(str, width) {
7009
+ if (width <= 0) {
7010
+ return '';
7011
+ }
7012
+ if (stringWidth(str) <= width) {
7013
+ return str;
7014
+ }
7015
+ if (width === 1) {
7016
+ return '…';
7017
+ }
7018
+
7019
+ const stripped = stripAnsi(str);
7020
+ const chars = Array.from(stripped);
7021
+ const ellipsis = '…';
7022
+ const available = Math.max(0, width - stringWidth(ellipsis));
7023
+
7024
+ let out = '';
7025
+ let used = 0;
7026
+ for (let i = 0; i < chars.length; i += 1) {
7027
+ const char = _nullishCoalesce$i(chars[i], () => ( ''));
7028
+ const w = stringWidth(char);
7029
+ if (used + w > available) {
7030
+ break;
7031
+ }
7032
+ out += char;
7033
+ used += w;
7034
+ }
7035
+
7036
+ return `${out}${ellipsis}`;
7037
+ }
7038
+
7039
+ function calculateColumnWidths(rows, options) {
7040
+ if (rows.length === 0) {
7041
+ return [];
7042
+ }
7043
+
7044
+ const keySet = new Set();
7045
+ const orderedKeys = [];
7046
+
7047
+ const seedRow = _nullishCoalesce$i(rows[0], () => ( {}));
7048
+ for (const key of Object.keys(seedRow)) {
7049
+ if (!keySet.has(key)) {
7050
+ keySet.add(key);
7051
+ orderedKeys.push(key);
7052
+ }
7053
+ }
7054
+
7055
+ for (const row of rows) {
7056
+ for (const key of Object.keys(row)) {
7057
+ if (!keySet.has(key)) {
7058
+ keySet.add(key);
7059
+ orderedKeys.push(key);
7060
+ }
7061
+ }
7062
+ }
7063
+
7064
+ const columns = [];
7065
+ for (const key of orderedKeys) {
7066
+ let maxWidth = stringWidth(key);
7067
+ for (const row of rows) {
7068
+ const value = row[key];
7069
+ const valueStr = value === undefined ? '' : String(value);
7070
+ maxWidth = Math.max(maxWidth, stringWidth(valueStr));
7071
+ }
7072
+ columns.push({ key, width: maxWidth });
7073
+ }
7074
+
7075
+ const gap = _nullishCoalesce$i(options.columnGap, () => ( 2));
7076
+ const maxWidth = _nullishCoalesce$i(_nullishCoalesce$i(options.maxWidth, () => ( process.stdout.columns)), () => ( 120));
7077
+ const minColWidth = 6;
7078
+
7079
+ const dynamicMaxColumns = Math.max(
7080
+ 1,
7081
+ Math.floor((maxWidth + gap) / (minColWidth + gap)),
7082
+ );
7083
+ const maxColumns = Math.min(
7084
+ _nullishCoalesce$i(options.maxColumns, () => ( dynamicMaxColumns)),
7085
+ dynamicMaxColumns,
7086
+ );
7087
+
7088
+ if (columns.length > maxColumns) {
7089
+ columns.splice(maxColumns);
7090
+ }
7091
+
7092
+ const available = Math.max(
7093
+ 0,
7094
+ maxWidth - gap * Math.max(0, columns.length - 1),
7095
+ );
7096
+
7097
+ const sum = () => columns.reduce((acc, col) => acc + col.width, 0);
7098
+
7099
+ while (sum() > available) {
7100
+ let widestIndex = -1;
7101
+ let widestWidth = -1;
7102
+ for (let i = 0; i < columns.length; i += 1) {
7103
+ const w = _nullishCoalesce$i(_optionalChain$H([columns, 'access', _ => _[i], 'optionalAccess', _2 => _2.width]), () => ( 0));
7104
+ if (w > widestWidth) {
7105
+ widestWidth = w;
7106
+ widestIndex = i;
7107
+ }
7108
+ }
7109
+
7110
+ if (widestIndex === -1) {
7111
+ break;
7112
+ }
7113
+ const current = _nullishCoalesce$i(_optionalChain$H([columns, 'access', _3 => _3[widestIndex], 'optionalAccess', _4 => _4.width]), () => ( 0));
7114
+ if (current <= minColWidth) {
7115
+ break;
7116
+ }
7117
+ columns[widestIndex] = { ...columns[widestIndex], width: current - 1 };
7118
+ }
7119
+
7120
+ for (let i = 0; i < columns.length; i += 1) {
7121
+ const col = columns[i];
7122
+ if (!col) {
7123
+ continue;
7124
+ }
7125
+ columns[i] = { ...col, width: Math.max(minColWidth, col.width) };
7126
+ }
7127
+
7128
+ return columns;
7129
+ }
7130
+
7131
+ function formatTable(rows, options = {}) {
7132
+ if (rows.length === 0) {
7133
+ return '';
7134
+ }
7135
+
7136
+ const columns = calculateColumnWidths(rows, options);
7137
+ if (columns.length === 0) {
7138
+ return '';
7139
+ }
7140
+
7141
+ const gap = _nullishCoalesce$i(options.columnGap, () => ( 2));
7142
+ const gapStr = ' '.repeat(gap);
7143
+
7144
+ const header = columns
7145
+ .map(col => padRightVisible(truncateVisible(col.key, col.width), col.width))
7146
+ .join(gapStr);
7147
+ const separator = columns.map(col => '-'.repeat(col.width)).join(gapStr);
7148
+
7149
+ const bodyRows = [];
7150
+ for (const row of rows) {
7151
+ const cells = columns.map(col => {
7152
+ const value = row[col.key];
7153
+ const valueStr = value === undefined ? '' : String(value);
7154
+ const trimmed = truncateVisible(valueStr, col.width);
7155
+ return padRightVisible(trimmed, col.width);
7156
+ });
7157
+ bodyRows.push(cells.join(gapStr));
7158
+ }
7159
+
7160
+ return `${[header, separator, ...bodyRows].join('\n')}\n`;
7161
+ }
7162
+
7163
+ function formatKeyValue(
7164
+ obj,
7165
+ options = {},
7166
+ ) {
7167
+ const entries = Object.entries(obj);
7168
+ if (entries.length === 0) {
7169
+ return '';
7170
+ }
7171
+
7172
+ let maxKeyWidth = 0;
7173
+ for (const [key] of entries) {
7174
+ maxKeyWidth = Math.max(maxKeyWidth, stringWidth(key));
7162
7175
  }
7176
+
7177
+ const maxWidth = _nullishCoalesce$i(_nullishCoalesce$i(options.maxWidth, () => ( process.stdout.columns)), () => ( 120));
7178
+ const gap = _nullishCoalesce$i(options.columnGap, () => ( 2));
7179
+ const minValueWidth = _nullishCoalesce$i(options.minValueWidth, () => ( 12));
7180
+
7181
+ let keyWidth = Math.min(maxKeyWidth, _nullishCoalesce$i(options.keyMaxWidth, () => ( 32)));
7182
+ const maxKeyWidthByTotal = Math.max(6, maxWidth - gap - minValueWidth);
7183
+ keyWidth = Math.min(keyWidth, maxKeyWidthByTotal);
7184
+
7185
+ const valueWidth = Math.max(0, maxWidth - keyWidth - gap);
7186
+ const gapStr = ' '.repeat(gap);
7187
+
7188
+ const lines = entries.map(([key, value]) => {
7189
+ const keyCell = padRightVisible(truncateVisible(key, keyWidth), keyWidth);
7190
+ const valueStr =
7191
+ value === undefined
7192
+ ? 'undefined'
7193
+ : value === null
7194
+ ? 'null'
7195
+ : String(value);
7196
+
7197
+ const singleLineValue = valueStr.replace(/\s*\n\s*/g, ' ');
7198
+ const valueCell =
7199
+ valueWidth > 0 ? truncateVisible(singleLineValue, valueWidth) : '';
7200
+
7201
+ return `${keyCell}${gapStr}${valueCell}`;
7202
+ });
7203
+
7204
+ return `${lines.join('\n')}\n`;
7163
7205
  }
7164
- const PermissionApi = new PermissionApiService({});
7165
- /* eslint-enable */
7166
7206
 
7167
- function _nullishCoalesce$f(lhs, rhsFn) { if (lhs != null) { return lhs; } else { return rhsFn(); } }
7207
+ function _nullishCoalesce$h(lhs, rhsFn) { if (lhs != null) { return lhs; } else { return rhsFn(); } }const MAX_DEPTH = 5;
7168
7208
 
7209
+
7169
7210
 
7170
7211
 
7171
7212
 
7172
7213
 
7173
- class AuthService {
7174
-
7175
7214
 
7176
- constructor( ctx) {this.ctx = ctx;
7177
- this.config = ctx.config;
7215
+ function isObject$1(value) {
7216
+ return typeof value === 'object' && value !== null && !Array.isArray(value);
7217
+ }
7218
+
7219
+ function flattenObject(
7220
+ obj,
7221
+ prefix = '',
7222
+ depth = 0,
7223
+ ) {
7224
+ const result = {};
7225
+
7226
+ if (obj === null || obj === undefined) {
7227
+ return result;
7178
7228
  }
7179
7229
 
7180
- getOAuthConfig() {
7181
- return {
7182
- baseURL: _nullishCoalesce$f(this.config.openApiBaseUrl, () => ( DEFAULT_CONFIG.openApiBaseUrl)),
7183
- clientId: _nullishCoalesce$f(this.config.clientId, () => ( DEFAULT_CONFIG.clientId)),
7184
- };
7230
+ if (!isObject$1(obj)) {
7231
+ return result;
7185
7232
  }
7186
7233
 
7187
- async clearUserContext() {
7188
- this.config.organizationId = undefined;
7189
- this.config.enterpriseId = undefined;
7190
- this.config.spaceId = undefined;
7234
+ for (const [key, value] of Object.entries(obj)) {
7235
+ const newKey = prefix ? `${prefix}.${key}` : key;
7191
7236
 
7192
- await saveConfig({
7193
- organizationId: undefined,
7194
- enterpriseId: undefined,
7195
- spaceId: undefined,
7196
- });
7237
+ if (value === null || value === undefined) {
7238
+ result[newKey] = value ;
7239
+ continue;
7240
+ }
7241
+
7242
+ if (Array.isArray(value)) {
7243
+ if (depth >= MAX_DEPTH) {
7244
+ result[newKey] = '[Array]';
7245
+ } else if (value.length === 0) {
7246
+ result[newKey] = '[]';
7247
+ } else if (
7248
+ value.every(item => typeof item !== 'object' || item === null)
7249
+ ) {
7250
+ result[newKey] = value.map(v => String(_nullishCoalesce$h(v, () => ( 'null')))).join(', ');
7251
+ } else {
7252
+ result[newKey] = '[Array]';
7253
+ }
7254
+ continue;
7255
+ }
7256
+
7257
+ if (typeof value === 'object') {
7258
+ if (depth >= MAX_DEPTH) {
7259
+ result[newKey] = '[Object]';
7260
+ } else {
7261
+ const nested = flattenObject(value, newKey, depth + 1);
7262
+ Object.assign(result, nested);
7263
+ }
7264
+ continue;
7265
+ }
7266
+
7267
+ result[newKey] = value ;
7197
7268
  }
7198
7269
 
7199
- async clearAuthData() {
7200
- this.config.accessToken = undefined;
7201
- this.config.refreshToken = undefined;
7202
- this.config.tokenExpiresAt = undefined;
7270
+ return result;
7271
+ }
7203
7272
 
7204
- await saveConfig({
7205
- accessToken: undefined,
7206
- refreshToken: undefined,
7207
- tokenExpiresAt: undefined,
7208
- });
7273
+ function _nullishCoalesce$g(lhs, rhsFn) { if (lhs != null) { return lhs; } else { return rhsFn(); } }
7274
+
7275
+ function isObject(value) {
7276
+ return typeof value === 'object' && value !== null && !Array.isArray(value);
7277
+ }
7278
+
7279
+ function isArrayOfObjects(value) {
7280
+ return Array.isArray(value) && value.length > 0 && value.every(isObject);
7281
+ }
7282
+
7283
+ function isPrimitiveArray(
7284
+ value,
7285
+ ) {
7286
+ return (
7287
+ Array.isArray(value) &&
7288
+ value.length > 0 &&
7289
+ value.every(
7290
+ item => item === null || item === undefined || typeof item !== 'object',
7291
+ )
7292
+ );
7293
+ }
7294
+
7295
+ function formatDetails(details, indent) {
7296
+ if (details === undefined || details === null) {
7297
+ return '';
7209
7298
  }
7210
7299
 
7211
- async login(options) {
7212
- this.ctx.ui.verbose('Initiating login process...');
7300
+ if (typeof details === 'string') {
7301
+ return `${indent}${details}\n`;
7302
+ }
7213
7303
 
7214
- if (options.token) {
7215
- this.ctx.ui.info('Using Personal Access Token (PAT)...');
7216
- this.config.accessToken = options.token;
7217
- await saveConfig({
7218
- accessToken: options.token,
7219
- refreshToken: undefined,
7220
- tokenExpiresAt: undefined,
7221
- });
7222
- await this.clearUserContext();
7223
- this.ctx.ui.info('Authentication successful. Credentials saved.');
7224
- if (this.ctx.format === 'json') {
7225
- this.ctx.response.print({ success: true, method: 'PAT' });
7304
+ if (Array.isArray(details)) {
7305
+ if (details.length === 0) {
7306
+ return '';
7307
+ }
7308
+ const items = details.map(item => {
7309
+ if (typeof item === 'object' && item !== null) {
7310
+ return formatKeyValue(flattenObject(item));
7226
7311
  }
7227
- return;
7312
+ return String(item);
7313
+ });
7314
+ return `${items.map(item => `${indent}- ${item.trim()}`).join('\n')}\n`;
7315
+ }
7316
+
7317
+ if (isObject(details)) {
7318
+ const flattened = flattenObject(details);
7319
+ if (Object.keys(flattened).length === 0) {
7320
+ return '';
7228
7321
  }
7322
+ return `${formatKeyValue(flattened)
7323
+ .split('\n')
7324
+ .filter(line => line.trim())
7325
+ .map(line => `${indent}${line}`)
7326
+ .join('\n')}\n`;
7327
+ }
7229
7328
 
7230
- try {
7231
- this.ctx.ui.info('Starting OAuth flow...');
7232
- const { baseURL, clientId } = this.getOAuthConfig();
7329
+ return `${indent}${String(details)}\n`;
7330
+ }
7233
7331
 
7234
- this.ctx.ui.verbose('Starting OAuth device flow...');
7332
+ class TextFormatter {
7333
+ format(data) {
7334
+ if (data === null) {
7335
+ return 'null\n';
7336
+ }
7235
7337
 
7236
- const deviceCode = await getDeviceCode({
7237
- baseURL,
7238
- clientId,
7239
- });
7338
+ if (data === undefined) {
7339
+ return 'undefined\n';
7340
+ }
7240
7341
 
7241
- const verificationUri = `${deviceCode.verification_uri}?user_code=${deviceCode.user_code}`;
7342
+ if (Array.isArray(data)) {
7343
+ if (data.length === 0) {
7344
+ return '\n';
7345
+ }
7242
7346
 
7243
- this.ctx.ui.info(
7244
- `Please visit ${chalk.underline(verificationUri)} and authorize the application.`,
7245
- );
7347
+ if (isArrayOfObjects(data)) {
7348
+ const flattenedRows = data.map(row => flattenObject(row));
7349
+ return formatTable(flattenedRows);
7350
+ }
7246
7351
 
7247
- const deviceToken = await getDeviceToken(
7248
- {
7249
- baseURL,
7250
- clientId,
7251
- deviceCode: deviceCode.device_code,
7252
- poll: true,
7253
- },
7254
- this.ctx,
7255
- );
7352
+ if (isPrimitiveArray(data)) {
7353
+ return `${data.map(item => String(_nullishCoalesce$g(item, () => ( 'null')))).join('\n')}\n`;
7354
+ }
7256
7355
 
7257
- this.ctx.ui.debug(
7258
- `Polling for device token success: ${JSON.stringify(deviceToken)}`,
7259
- );
7356
+ return '[Array]\n';
7357
+ }
7260
7358
 
7261
- await this.saveOAuthToken(deviceToken);
7359
+ if (isObject(data)) {
7360
+ const flattened = flattenObject(data);
7361
+ if (Object.keys(flattened).length === 0) {
7362
+ return '{}\n';
7363
+ }
7364
+ return formatKeyValue(flattened);
7365
+ }
7262
7366
 
7263
- this.ctx.ui.debug('Saving OAuth token successfully.');
7367
+ return `${String(data)}\n`;
7368
+ }
7264
7369
 
7265
- await this.clearUserContext();
7370
+ formatError(error) {
7371
+ const lines = [];
7266
7372
 
7267
- this.ctx.ui.info('Authentication successful. Credentials saved.');
7268
- if (this.ctx.format === 'json') {
7269
- this.ctx.response.print({ success: true, method: 'OAuth' });
7373
+ lines.push(' [ERROR]');
7374
+ lines.push(` Message: ${error.message}`);
7375
+ lines.push(` Code: ${error.code}`);
7376
+
7377
+ if (error.details !== undefined) {
7378
+ lines.push(' Details:');
7379
+ const detailsStr = formatDetails(error.details, ' ');
7380
+ if (detailsStr) {
7381
+ lines.push(detailsStr.trimEnd());
7270
7382
  }
7271
- } catch (oauthError) {
7272
- this.ctx.ui.error(
7273
- `OAuth login failed: ${oauthError.message || oauthError}`,
7274
- );
7275
- throw oauthError;
7276
7383
  }
7277
- }
7278
7384
 
7279
- async logout() {
7280
- await this.clearAuthData();
7281
- await this.clearUserContext();
7282
- this.ctx.ui.info('You have been logged out. Credentials cleared.');
7283
- if (this.ctx.format === 'json') {
7284
- this.ctx.response.print({ success: true, logged_out: true });
7285
- }
7385
+ return `${lines.join('\n')}\n`;
7286
7386
  }
7387
+ }
7287
7388
 
7288
- async whoami() {
7289
- const token = await this.getValidAccessToken();
7389
+ function createFormatter(format) {
7390
+ switch (format) {
7391
+ case 'text':
7392
+ return new TextFormatter();
7393
+ case 'json':
7394
+ default:
7395
+ return new JsonFormatter();
7396
+ }
7397
+ }
7290
7398
 
7291
- if (!token) {
7292
- this.ctx.response.print({ logged_in: false });
7293
- return;
7294
- }
7399
+ class Response {
7400
+
7295
7401
 
7296
- this.ctx.ui.info('Fetching user information...');
7402
+ constructor(props) {
7403
+ const { format } = props;
7404
+ this.formatter = createFormatter(format);
7405
+ }
7297
7406
 
7298
- const info = {
7299
- user: 'mock-user@coze.io',
7300
- org: 'mock-org',
7301
- profile: 'default',
7302
- };
7407
+ print(data) {
7408
+ const output = this.formatter.format(data);
7409
+ process.stdout.write(output);
7410
+ }
7303
7411
 
7304
- this.ctx.response.print({
7305
- logged_in: true,
7306
- ...info,
7307
- });
7412
+ eprint(error) {
7413
+ const output = this.formatter.formatError(error);
7414
+ process.stdout.write(output);
7308
7415
  }
7416
+ }
7309
7417
 
7310
- async status() {
7311
- const token = await this.getValidAccessToken();
7418
+ function _nullishCoalesce$f(lhs, rhsFn) { if (lhs != null) { return lhs; } else { return rhsFn(); } }
7312
7419
 
7313
- this.ctx.ui.info('Checking authentication status...');
7314
7420
 
7315
- if (!token) {
7316
- this.ctx.response.print({ logged_in: false });
7317
- return;
7318
- }
7319
7421
 
7320
- const expiresAt = this.config.tokenExpiresAt;
7321
- const isOAuth = !!this.config.refreshToken;
7322
7422
 
7323
- const { data: user } = await PermissionApi.GetUserProfile(
7324
- {},
7325
- { baseURL: this.config.openApiBaseUrl },
7326
- );
7327
7423
 
7328
- const status = {
7329
- logged_in: true,
7330
- user,
7331
- token_expires_at: expiresAt
7332
- ? new Date(expiresAt).toISOString()
7333
- : !isOAuth
7334
- ? 'Never (PAT)'
7335
- : undefined,
7336
- };
7337
7424
 
7338
- this.ctx.response.print(status);
7339
- }
7340
7425
 
7341
- async getValidAccessToken() {
7342
- const { accessToken, refreshToken, tokenExpiresAt } = this.config;
7426
+ const LOG_DIR = path.join(os.homedir(), '.coze', 'logs');
7427
+ const MAX_LOG_FILES = 10;
7343
7428
 
7344
- if (!accessToken) {
7345
- return undefined;
7429
+ class DiagnosticLogger {
7430
+
7431
+
7432
+
7433
+
7434
+
7435
+ __init() {this.fileStream = null;}
7436
+ __init2() {this.writeError = false;}
7437
+
7438
+ constructor(options = {}) {DiagnosticLogger.prototype.__init.call(this);DiagnosticLogger.prototype.__init2.call(this);
7439
+ this.format = _nullishCoalesce$f(options.format, () => ( 'text'));
7440
+ this.printToStderr = _nullishCoalesce$f(options.printToStderr, () => ( false));
7441
+ this.tags = _nullishCoalesce$f(options.tags, () => ( {}));
7442
+ this.startTime = Date.now();
7443
+
7444
+ const logFilePath = _nullishCoalesce$f(options.logFile, () => ( this.getDefaultLogPath()));
7445
+ this.logFile = logFilePath;
7446
+
7447
+ try {
7448
+ this.ensureLogDir();
7449
+ this.rotateLogFiles();
7450
+ this.fileStream = node_fs.createWriteStream(logFilePath, { flags: 'a' });
7451
+ this.fileStream.on('error', () => {
7452
+ this.fileStream = null;
7453
+ });
7454
+ } catch (e) {
7455
+ this.logFile = null;
7456
+ this.fileStream = null;
7346
7457
  }
7458
+ }
7347
7459
 
7348
- // If there is no refresh token, it means it's a PAT, so it doesn't expire
7349
- if (!refreshToken) {
7350
- return accessToken;
7460
+ getDefaultLogPath() {
7461
+ const timestamp = new Date().toISOString().replace(/[:.]/g, '-');
7462
+ const { pid } = process;
7463
+ return path.join(LOG_DIR, `${timestamp}-${pid}.log`);
7464
+ }
7465
+
7466
+ ensureLogDir() {
7467
+ if (!node_fs.existsSync(LOG_DIR)) {
7468
+ node_fs.mkdirSync(LOG_DIR, { recursive: true });
7351
7469
  }
7470
+ }
7352
7471
 
7353
- // If the token is not expired (add 5 minutes buffer), return it
7354
- const bufferTime = 5 * 60 * 1000;
7355
- if (tokenExpiresAt && Date.now() < tokenExpiresAt - bufferTime) {
7356
- return accessToken;
7472
+ rotateLogFiles() {
7473
+ try {
7474
+ const files = node_fs.readdirSync(LOG_DIR)
7475
+ .filter(f => f.endsWith('.log'))
7476
+ .map(f => ({
7477
+ name: f,
7478
+ path: path.join(LOG_DIR, f),
7479
+ mtime: node_fs.statSync(path.join(LOG_DIR, f)).mtime.getTime(),
7480
+ }))
7481
+ .sort((a, b) => b.mtime - a.mtime);
7482
+
7483
+ if (files.length >= MAX_LOG_FILES) {
7484
+ files.slice(MAX_LOG_FILES - 1).forEach(f => {
7485
+ try {
7486
+ node_fs.unlinkSync(f.path);
7487
+ // eslint-disable-next-line @coze-arch/no-empty-catch
7488
+ } catch (e2) {
7489
+ // ignore deletion errors
7490
+ }
7491
+ });
7492
+ }
7493
+ // eslint-disable-next-line @coze-arch/no-empty-catch
7494
+ } catch (e3) {
7495
+ // ignore rotation errors
7357
7496
  }
7497
+ }
7358
7498
 
7359
- // Token is expired or about to expire, let's refresh it
7360
- this.ctx.ui.verbose(
7361
- 'Access token is expired or expiring soon, refreshing...',
7362
- );
7499
+ verbose(msg, ...args) {
7500
+ this.log('verbose', msg, args);
7501
+ }
7363
7502
 
7364
- try {
7365
- const { baseURL, clientId } = this.getOAuthConfig();
7503
+ info(msg, ...args) {
7504
+ this.log('info', msg, args);
7505
+ }
7366
7506
 
7367
- const newToken = await refreshOAuthToken({
7368
- baseURL,
7369
- clientId,
7370
- refreshToken,
7371
- });
7507
+ warn(msg, ...args) {
7508
+ this.log('warn', msg, args);
7509
+ }
7372
7510
 
7373
- await this.saveOAuthToken(newToken);
7374
- this.ctx.ui.verbose('Token refreshed successfully.');
7375
- return newToken.access_token;
7376
- } catch (error) {
7377
- // Clear token config if refresh fails to require re-login
7378
- this.ctx.ui.error(`Failed to refresh token: ${error.message || error}`);
7379
- await this.clearAuthData();
7380
- return undefined;
7511
+ error(msg, ...args) {
7512
+ this.log('error', msg, args);
7513
+ }
7514
+
7515
+ success(msg, ...args) {
7516
+ this.log('success', msg, args);
7517
+ }
7518
+
7519
+ debug(msg, ...args) {
7520
+ this.log('debug', msg, args);
7521
+ }
7522
+
7523
+ log(level, msg, args) {
7524
+ const entry = this.formatEntry(level, msg, args);
7525
+
7526
+ if (this.fileStream) {
7527
+ try {
7528
+ this.fileStream.write(`${entry}\n`);
7529
+ } catch (e4) {
7530
+ if (!this.writeError && this.printToStderr) {
7531
+ process.stderr.write('Warning: Log write failed\n');
7532
+ this.writeError = true;
7533
+ }
7534
+ }
7535
+ }
7536
+
7537
+ if (this.printToStderr) {
7538
+ process.stderr.write(`${entry}\n`);
7381
7539
  }
7382
7540
  }
7383
7541
 
7384
- async saveOAuthToken(token) {
7385
- const tokenExpiresAt = token.expires_in * 1000;
7542
+ formatEntry(level, msg, args) {
7543
+ const timestamp = new Date().toISOString();
7544
+ const delta = Date.now() - this.startTime;
7386
7545
 
7387
- // Update local config object so we don't have to reload
7388
- this.config.accessToken = token.access_token;
7389
- this.config.refreshToken = token.refresh_token;
7390
- this.config.tokenExpiresAt = tokenExpiresAt;
7546
+ if (this.format === 'json') {
7547
+ const entry = {
7548
+ level,
7549
+ timestamp,
7550
+ delta,
7551
+ ...this.tags,
7552
+ message: msg,
7553
+ };
7554
+ if (args.length > 0) {
7555
+ entry.args = args;
7556
+ }
7557
+ return JSON.stringify(entry);
7558
+ }
7391
7559
 
7392
- await saveConfig({
7393
- accessToken: token.access_token,
7394
- refreshToken: token.refresh_token,
7395
- tokenExpiresAt,
7396
- });
7560
+ const tagsStr = Object.entries(this.tags)
7561
+ .map(([k, v]) => `${k}=${v}`)
7562
+ .join(' ');
7563
+ const argsStr = args.length > 0 ? ` ${args.map(String).join(' ')}` : '';
7564
+ return `${level.toUpperCase().padEnd(7)} [${timestamp}] +${delta}ms ${tagsStr} ${msg}${argsStr}`;
7565
+ }
7566
+
7567
+ close() {
7568
+ if (this.fileStream) {
7569
+ try {
7570
+ this.fileStream.end();
7571
+ // eslint-disable-next-line @coze-arch/no-empty-catch
7572
+ } catch (e5) {
7573
+ // ignore close errors
7574
+ }
7575
+ }
7397
7576
  }
7398
7577
  }
7399
7578
 
@@ -7482,78 +7661,6 @@ function createContext(options) {
7482
7661
  return context;
7483
7662
  }
7484
7663
 
7485
- function parseArgv(argv) {
7486
- const globalOptions = {};
7487
- let commandName;
7488
- const commandArgs = [];
7489
- let seenCommand = false;
7490
-
7491
- for (let i = 0; i < argv.length; i++) {
7492
- const token = argv[i];
7493
-
7494
- if (token === '--help' || token === '-h') {
7495
- globalOptions.help = true;
7496
- continue;
7497
- }
7498
- if (token === '--version' || token === '-v') {
7499
- globalOptions.version = true;
7500
- continue;
7501
- }
7502
- if (token === '--output') {
7503
- globalOptions.output = argv[++i];
7504
- continue;
7505
- }
7506
- if (token === '--format') {
7507
- const format = argv[++i];
7508
- if (format === 'json' || format === 'text') {
7509
- globalOptions.format = format;
7510
- }
7511
- continue;
7512
- }
7513
- if (token === '--no-color') {
7514
- globalOptions.noColor = true;
7515
- continue;
7516
- }
7517
- if (token === '--config') {
7518
- globalOptions.config = argv[++i];
7519
- continue;
7520
- }
7521
- if (token === '--org-id') {
7522
- globalOptions.orgId = argv[++i];
7523
- continue;
7524
- }
7525
- if (token === '--space-id') {
7526
- globalOptions.spaceId = argv[++i];
7527
- continue;
7528
- }
7529
- if (token === '--verbose') {
7530
- globalOptions.verbose = true;
7531
- continue;
7532
- }
7533
- if (token === '--debug') {
7534
- globalOptions.debug = true;
7535
- continue;
7536
- }
7537
- if (token === '--log-file') {
7538
- globalOptions.logFile = argv[++i];
7539
- continue;
7540
- }
7541
- if (token === '--print-logs') {
7542
- globalOptions.printLogs = true;
7543
- continue;
7544
- }
7545
-
7546
- if (!seenCommand && !token.startsWith('-')) {
7547
- commandName = token;
7548
- seenCommand = true;
7549
- } else {
7550
- commandArgs.push(token);
7551
- }
7552
- }
7553
-
7554
- return { globalOptions, commandName, commandArgs };
7555
- }
7556
-
7557
7664
  async function loggerMiddleware(
7558
7665
  context,
7559
7666
  next,
@@ -16324,7 +16431,7 @@ async function useSpace(spaceId) {
16324
16431
 
16325
16432
  function _optionalChain$D(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = fn(value); } else if (op === 'call' || op === 'optionalCall') { value = fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; }
16326
16433
 
16327
- const registerCommand$a = (program) => {
16434
+ const registerCommand$b = (program) => {
16328
16435
  const space = program
16329
16436
  .command('space')
16330
16437
  .config({
@@ -16484,7 +16591,7 @@ async function useOrganization(orgId)
16484
16591
  function _optionalChain$C(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = fn(value); } else if (op === 'call' || op === 'optionalCall') { value = fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; }/* eslint-disable max-lines-per-function */
16485
16592
 
16486
16593
 
16487
- const registerCommand$9 = (program) => {
16594
+ const registerCommand$a = (program) => {
16488
16595
  const organization = program
16489
16596
  .command('organization')
16490
16597
  .config({
@@ -17094,7 +17201,7 @@ const resolvePollingConfig = (
17094
17201
  };
17095
17202
 
17096
17203
  const downloadToBuffer = async (url) => {
17097
- const resp = await index.customFetch(url);
17204
+ const resp = await index.customFetch.fetch(url);
17098
17205
  if (!resp.ok) {
17099
17206
  throw new index.CozeError(
17100
17207
  `Failed to download generated resource: ${resp.status} ${resp.statusText}`,
@@ -19733,7 +19840,7 @@ const registerGenerateImageCommand = (
19733
19840
 
19734
19841
  let buffer;
19735
19842
  if (responseFormat === 'url') {
19736
- const resp = await index.customFetch(item.url );
19843
+ const resp = await index.customFetch.fetch(item.url );
19737
19844
  if (!resp.ok) {
19738
19845
  throw new index.CozeError(
19739
19846
  `Failed to download generated image: ${resp.status} ${resp.statusText}`,
@@ -20090,18 +20197,9 @@ const registerGenerateAudioCommand = (
20090
20197
 
20091
20198
  const url = new URL('/api/v3/tts/unidirectional', apiBaseUrl);
20092
20199
  url.searchParams.append('is_auth', 'false');
20093
- const headers = {
20094
- Authorization: `Bearer ${accessToken}`,
20095
- 'Content-Type': 'application/json',
20096
- Accept: 'text/event-stream',
20097
- };
20098
- if (_optionalChain$w([ctx, 'optionalAccess', _11 => _11.config, 'access', _12 => _12.xTTEnv])) {
20099
- headers['x-use-ppe'] = '1';
20100
- headers['x-tt-env'] = _optionalChain$w([ctx, 'optionalAccess', _13 => _13.config, 'access', _14 => _14.xTTEnv]);
20101
- }
20102
- const resp = await index.customFetch(url.toString(), {
20200
+
20201
+ const resp = await index.customFetch.fetch(url.toString(), {
20103
20202
  method: 'POST',
20104
- headers,
20105
20203
  body: JSON.stringify(req),
20106
20204
  });
20107
20205
 
@@ -20206,7 +20304,7 @@ const registerGenerateAudioCommand = (
20206
20304
  // - 若未拿到分片但有 final url,则下载落盘
20207
20305
  if (outputPath) {
20208
20306
  const format =
20209
- _nullishCoalesce$8(_optionalChain$w([req, 'access', _15 => _15.req_params, 'optionalAccess', _16 => _16.audio_params, 'optionalAccess', _17 => _17.format]), () => ( DEFAULT_FORMAT));
20307
+ _nullishCoalesce$8(_optionalChain$w([req, 'access', _11 => _11.req_params, 'optionalAccess', _12 => _12.audio_params, 'optionalAccess', _13 => _13.format]), () => ( DEFAULT_FORMAT));
20210
20308
  const ext =
20211
20309
  format === 'pcm'
20212
20310
  ? '.pcm'
@@ -20231,7 +20329,7 @@ const registerGenerateAudioCommand = (
20231
20329
  Buffer.concat(audioChunks),
20232
20330
  );
20233
20331
  } else if (finalAudioUrl) {
20234
- const dlResp = await index.customFetch(finalAudioUrl);
20332
+ const dlResp = await index.customFetch.fetch(finalAudioUrl);
20235
20333
  if (!dlResp.ok) {
20236
20334
  throw new index.CozeError(
20237
20335
  `Failed to download synthesized speech: ${dlResp.status} ${dlResp.statusText}`,
@@ -20258,7 +20356,7 @@ const registerGenerateAudioCommand = (
20258
20356
  );
20259
20357
  }
20260
20358
 
20261
- if (_optionalChain$w([ctx, 'optionalAccess', _18 => _18.format]) === 'json') {
20359
+ if (_optionalChain$w([ctx, 'optionalAccess', _14 => _14.format]) === 'json') {
20262
20360
  writeJsonOutput({
20263
20361
  request: req,
20264
20362
  url: finalAudioUrl,
@@ -20272,7 +20370,7 @@ const registerGenerateAudioCommand = (
20272
20370
  }
20273
20371
 
20274
20372
  // 不保存:默认输出最终 url(若服务端返回)
20275
- if (_optionalChain$w([ctx, 'optionalAccess', _19 => _19.format]) === 'json') {
20373
+ if (_optionalChain$w([ctx, 'optionalAccess', _15 => _15.format]) === 'json') {
20276
20374
  writeJsonOutput({ request: req, url: finalAudioUrl });
20277
20375
  return;
20278
20376
  }
@@ -20287,7 +20385,7 @@ const registerGenerateAudioCommand = (
20287
20385
  );
20288
20386
  } catch (error) {
20289
20387
  if (error instanceof index.CozeError) {
20290
- _optionalChain$w([ctx, 'optionalAccess', _20 => _20.ui, 'optionalAccess', _21 => _21.error, 'call', _22 => _22(error.message)]);
20388
+ _optionalChain$w([ctx, 'optionalAccess', _16 => _16.ui, 'optionalAccess', _17 => _17.error, 'call', _18 => _18(error.message)]);
20291
20389
  process.exit(error.code);
20292
20390
  }
20293
20391
 
@@ -20635,7 +20733,7 @@ const registerListCommand$4 = (configCmd) => {
20635
20733
  });
20636
20734
  };
20637
20735
 
20638
- const registerCommand$8 = (program) => {
20736
+ const registerCommand$9 = (program) => {
20639
20737
  const configCmd = program
20640
20738
  .command('config')
20641
20739
  .description('Manage Coze CLI configuration')
@@ -20661,7 +20759,7 @@ const registerCommand$8 = (program) => {
20661
20759
 
20662
20760
  let completionInstance;
20663
20761
 
20664
- function registerCommand$7(program) {
20762
+ function registerCommand$8(program) {
20665
20763
  completionInstance = omelette('coze');
20666
20764
 
20667
20765
  completionInstance.on('complete', (fragment, data) => {
@@ -20921,8 +21019,10 @@ function pickSkillIds(projectInfo) {
20921
21019
 
20922
21020
  function registerListCommand$3(skill) {
20923
21021
  skill
20924
- .command('list <projectId>')
21022
+ .command('list')
20925
21023
  .description('List skills added to the project')
21024
+ .requiredOption('-p, --project-id <projectId>', 'Project ID')
21025
+ .option('--space-id <spaceId>', 'Space ID (optional, reads from config)')
20926
21026
  .config({
20927
21027
  help: {
20928
21028
  brief: 'List configured skills of the project',
@@ -20931,7 +21031,7 @@ function registerListCommand$3(skill) {
20931
21031
  examples: [
20932
21032
  {
20933
21033
  desc: 'List project skills',
20934
- cmd: 'coze code skill list <projectId>',
21034
+ cmd: 'coze code skill list --project-id <projectId>',
20935
21035
  tags: ['[RECOMMENDED]'],
20936
21036
  },
20937
21037
  ],
@@ -20978,7 +21078,6 @@ function registerListCommand$3(skill) {
20978
21078
  ],
20979
21079
  },
20980
21080
  })
20981
- .option('--space-id <spaceId>', 'Space ID (optional, reads from config)')
20982
21081
  .action(async function (
20983
21082
  projectId,
20984
21083
  options,
@@ -21158,7 +21257,7 @@ function registerAddCommand$2(skill) {
21158
21257
  }
21159
21258
  // end_aigc
21160
21259
 
21161
- const registerCommand$6 = (program) => {
21260
+ const registerCommand$7 = (program) => {
21162
21261
  const skill = program
21163
21262
  .command('skill')
21164
21263
  .config({
@@ -26326,6 +26425,21 @@ const intelligenceTypeToString = (
26326
26425
  type,
26327
26426
  ) => INLLIGENCEIGENCE_TYPE_STRING_MAP[type];
26328
26427
 
26428
+ const VALID_INTELLIGENCE_TYPES = [
26429
+ IntelligenceType.VibeProjectAgent,
26430
+ IntelligenceType.VibeProjectAutomation,
26431
+ IntelligenceType.VibeProjectWebApp,
26432
+ IntelligenceType.VibeProjectApp,
26433
+ IntelligenceType.VibeProjectSkill,
26434
+ IntelligenceType.VibeProjectGeneralWeb,
26435
+ IntelligenceType.VibeProjectWechatMiniProgram,
26436
+ IntelligenceType.VibeProjectAssistantAgent,
26437
+ ];
26438
+
26439
+ const VALID_INTELLIGENCE_TYPES_STRING = VALID_INTELLIGENCE_TYPES.map(
26440
+ intelligenceTypeToString,
26441
+ ).filter(Boolean) ;
26442
+
26329
26443
  function _nullishCoalesce$5(lhs, rhsFn) { if (lhs != null) { return lhs; } else { return rhsFn(); } } function _optionalChain$m(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = fn(value); } else if (op === 'call' || op === 'optionalCall') { value = fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; }/* eslint-disable @coze-arch/max-line-per-function */
26330
26444
 
26331
26445
 
@@ -26394,7 +26508,7 @@ function registerListCommand$2(project) {
26394
26508
  searchScope: {
26395
26509
  type: 'number',
26396
26510
  required: false,
26397
- description: 'Created by',
26511
+ description: 'Created by (All = 0, CreateByMe = 1)',
26398
26512
  },
26399
26513
  folderId: {
26400
26514
  type: 'string',
@@ -26404,7 +26518,7 @@ function registerListCommand$2(project) {
26404
26518
  orderType: {
26405
26519
  type: 'number',
26406
26520
  required: false,
26407
- description: 'Sort type',
26521
+ description: 'Sort type (0 for descending, 1 for ascending)',
26408
26522
  },
26409
26523
  isFavFilter: {
26410
26524
  type: 'boolean',
@@ -26436,6 +26550,20 @@ function registerListCommand$2(project) {
26436
26550
  fix: 'Please use --space-id <spaceId> or run `coze space use <spaceId>` first',
26437
26551
  },
26438
26552
  ],
26553
+ enums: {
26554
+ type: VALID_INTELLIGENCE_TYPES_STRING.reduce((acc, cur) => {
26555
+ acc[cur] = `${cur.toUpperCase()} project`;
26556
+ return acc;
26557
+ }, {}),
26558
+ ['search-scope']: {
26559
+ 0: 'All',
26560
+ 1: 'CreateByMe',
26561
+ },
26562
+ ['order-type']: {
26563
+ 0: 'Descending',
26564
+ 1: 'Ascending',
26565
+ },
26566
+ },
26439
26567
  },
26440
26568
  })
26441
26569
  .option('--size <size>', 'Number of projects to return', parseInt)
@@ -26447,10 +26575,7 @@ function registerListCommand$2(project) {
26447
26575
  [],
26448
26576
  )
26449
26577
  .option('--name <name>', 'Filter by project name')
26450
- .option(
26451
- '--has-published <hasPublished>',
26452
- 'Filter by publish status (true | false)',
26453
- )
26578
+ .option('--has-published', 'Filter by publish status')
26454
26579
  .option(
26455
26580
  '--search-scope <searchScope>',
26456
26581
  'Created by (All = 0, CreateByMe = 1, AllWithCollaborator = 2)',
@@ -26460,10 +26585,7 @@ function registerListCommand$2(project) {
26460
26585
  '--order-type <orderType>',
26461
26586
  'Sort type (0 for descending, 1 for ascending)',
26462
26587
  )
26463
- .option(
26464
- '--is-fav-filter <isFavFilter>',
26465
- 'Filter by favorite status (true | false)',
26466
- )
26588
+ .option('--is-fav-filter', 'Filter by favorite status (true | false)')
26467
26589
  .action(async function (options, cmd) {
26468
26590
  const ctx = cmd.getContext();
26469
26591
  const limit = _nullishCoalesce$5(_optionalChain$m([options, 'optionalAccess', _ => _.size]), () => ( 10));
@@ -26472,11 +26594,11 @@ function registerListCommand$2(project) {
26472
26594
  , 'optionalAccess', _4 => _4.map, 'call', _5 => _5(resolveIntelligenceType)
26473
26595
  , 'access', _6 => _6.filter, 'call', _7 => _7(Boolean)]) ;
26474
26596
  const name = _optionalChain$m([options, 'optionalAccess', _8 => _8.name]);
26475
- const hasPublished = _optionalChain$m([options, 'optionalAccess', _9 => _9.hasPublished]);
26476
- const searchScope = _optionalChain$m([options, 'optionalAccess', _10 => _10.searchScope]);
26597
+ const hasPublished = Boolean(_optionalChain$m([options, 'optionalAccess', _9 => _9.hasPublished]));
26598
+ const searchScope = Number(_nullishCoalesce$5(_optionalChain$m([options, 'optionalAccess', _10 => _10.searchScope]), () => ( 0)));
26477
26599
  const folderId = _optionalChain$m([options, 'optionalAccess', _11 => _11.folderId]);
26478
- const orderType = _optionalChain$m([options, 'optionalAccess', _12 => _12.orderType]);
26479
- const isFavFilter = _optionalChain$m([options, 'optionalAccess', _13 => _13.isFavFilter]);
26600
+ const orderType = Number(_nullishCoalesce$5(_optionalChain$m([options, 'optionalAccess', _12 => _12.orderType]), () => ( 0)));
26601
+ const isFavFilter = Boolean(_optionalChain$m([options, 'optionalAccess', _13 => _13.isFavFilter]));
26480
26602
 
26481
26603
  let projects = [];
26482
26604
  _optionalChain$m([ctx, 'optionalAccess', _14 => _14.ui, 'access', _15 => _15.info, 'call', _16 => _16('Fetching project list...')]);
@@ -26491,6 +26613,11 @@ function registerListCommand$2(project) {
26491
26613
  folder_id: folderId,
26492
26614
  order_type: orderType,
26493
26615
  is_fav_filter: isFavFilter,
26616
+ status: [
26617
+ IntelligenceStatus.Using,
26618
+ IntelligenceStatus.Banned,
26619
+ IntelligenceStatus.MoveFailed,
26620
+ ],
26494
26621
  });
26495
26622
  projects = _optionalChain$m([resp, 'access', _19 => _19.data, 'optionalAccess', _20 => _20.intelligences]) || [];
26496
26623
 
@@ -26973,7 +27100,7 @@ function registerCreateCommand(projectCmd) {
26973
27100
  }
26974
27101
  // end_aigc
26975
27102
 
26976
- const registerCommand$5 = (program) => {
27103
+ const registerCommand$6 = (program) => {
26977
27104
  const project = program
26978
27105
  .command('project')
26979
27106
  .alias('proj')
@@ -38818,7 +38945,7 @@ const deployService = DeployService.getInstance();
38818
38945
  function _optionalChain$f(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = fn(value); } else if (op === 'call' || op === 'optionalCall') { value = fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; }// start_aigc
38819
38946
 
38820
38947
 
38821
- function registerCommand$4(program) {
38948
+ function registerCommand$5(program) {
38822
38949
  program
38823
38950
  .command('preview <projectId>')
38824
38951
  .description('Get deployment preview info for the project')
@@ -39744,7 +39871,7 @@ function registerRemoveCommand$1(envCmd) {
39744
39871
  }
39745
39872
  // end_aigc
39746
39873
 
39747
- const registerCommand$3 = (program) => {
39874
+ const registerCommand$4 = (program) => {
39748
39875
  const env = program
39749
39876
  .command('env')
39750
39877
  .config({
@@ -40009,7 +40136,7 @@ function registerAddCommand(domainCmd) {
40009
40136
  });
40010
40137
  }
40011
40138
 
40012
- const registerCommand$2 = (program) => {
40139
+ const registerCommand$3 = (program) => {
40013
40140
  const domain = program
40014
40141
  .command('domain')
40015
40142
  .config({
@@ -40189,7 +40316,7 @@ function _optionalChain$4(ops) { let lastAccessLHS = undefined; let value = ops[
40189
40316
 
40190
40317
 
40191
40318
 
40192
- function registerCommand$1(program) {
40319
+ function registerCommand$2(program) {
40193
40320
  const deploy = program
40194
40321
  .command('deploy <projectId>')
40195
40322
  .option('--wait', 'Wait for deployment to complete')
@@ -40437,18 +40564,18 @@ function registerAllCommands$1(program) {
40437
40564
  });
40438
40565
 
40439
40566
  registerMessageCommand(code);
40440
- registerCommand$1(code);
40441
- registerCommand$5(code);
40442
- registerCommand$3(code);
40443
40567
  registerCommand$2(code);
40444
40568
  registerCommand$6(code);
40445
40569
  registerCommand$4(code);
40570
+ registerCommand$3(code);
40571
+ registerCommand$7(code);
40572
+ registerCommand$5(code);
40446
40573
  }
40447
40574
 
40448
40575
  function _optionalChain$3(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = fn(value); } else if (op === 'call' || op === 'optionalCall') { value = fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; }/* eslint-disable max-lines-per-function */
40449
40576
 
40450
40577
 
40451
- function registerCommand(program) {
40578
+ function registerCommand$1(program) {
40452
40579
  const auth = program
40453
40580
  .command('auth')
40454
40581
  .description('Manage user authentication and credentials')
@@ -40616,24 +40743,149 @@ function registerCommand(program) {
40616
40743
  });
40617
40744
  }
40618
40745
 
40746
+ function detectPackageManager() {
40747
+ const checks = [
40748
+ { pm: 'npm', cmd: 'npm ls -g @coze/cli --json 2>/dev/null' },
40749
+ { pm: 'pnpm', cmd: 'pnpm ls -g @coze/cli --json 2>/dev/null' },
40750
+ { pm: 'yarn', cmd: 'yarn global list --json 2>/dev/null' },
40751
+ ];
40752
+
40753
+ for (const { pm, cmd } of checks) {
40754
+ try {
40755
+ const output = node_child_process.execSync(cmd, {
40756
+ encoding: 'utf8',
40757
+ stdio: ['pipe', 'pipe', 'pipe'],
40758
+ });
40759
+ if (output.includes('@coze/cli')) {
40760
+ return pm;
40761
+ }
40762
+ // eslint-disable-next-line @coze-arch/no-empty-catch -- package manager detection failure is expected
40763
+ } catch (_error) {
40764
+ /* noop */
40765
+ }
40766
+ }
40767
+
40768
+ return 'npm';
40769
+ }
40770
+
40771
+ function getInstallCommand(
40772
+ packageManager,
40773
+ tag,
40774
+ ) {
40775
+ switch (packageManager) {
40776
+ case 'pnpm':
40777
+ return `pnpm add -g @coze/cli@${tag}`;
40778
+ case 'yarn':
40779
+ return `yarn global add @coze/cli@${tag}`;
40780
+ case 'npm':
40781
+ default:
40782
+ return `npm install -g @coze/cli@${tag}`;
40783
+ }
40784
+ }
40785
+
40786
+ function registerCommand(program) {
40787
+ program
40788
+ .command('upgrade')
40789
+ .description('Upgrade Coze CLI to the latest version')
40790
+ .config({
40791
+ skipAuth: true,
40792
+ skipOrgCheck: true,
40793
+ skipSpaceCheck: true,
40794
+ help: {
40795
+ brief: 'Upgrade CLI to latest version',
40796
+ description:
40797
+ 'Check for the latest version of Coze CLI and upgrade if a newer version is available. Detects the package manager used for the original installation (npm/pnpm/yarn) and runs the appropriate global install command.',
40798
+ examples: [
40799
+ {
40800
+ desc: 'Upgrade to latest version',
40801
+ cmd: 'coze upgrade',
40802
+ tags: ['[RECOMMENDED]'],
40803
+ },
40804
+ {
40805
+ desc: 'Force check and upgrade',
40806
+ cmd: 'coze upgrade --force',
40807
+ },
40808
+ {
40809
+ desc: 'Upgrade to a specific tag',
40810
+ cmd: 'coze upgrade --tag beta',
40811
+ },
40812
+ ],
40813
+ seeAlso: ['coze --version'],
40814
+ },
40815
+ })
40816
+ .option('--force', 'Force upgrade even if already on the latest version')
40817
+ .option('--tag <tag>', 'Specify the dist-tag to upgrade to', 'latest')
40818
+ .action(async (options, cmd) => {
40819
+ const ctx = cmd.getContext();
40820
+ if (!ctx) {
40821
+ process.exit(index.ExitCode.GENERAL_ERROR);
40822
+ }
40823
+
40824
+ ctx.ui.info('Checking for updates...');
40825
+
40826
+ try {
40827
+ const result = await checkForUpdates(ctx, true, options.tag);
40828
+
40829
+ if (!result.hasUpdate && !options.force) {
40830
+ ctx.ui.success(
40831
+ `You are already on the latest version (${result.currentVersion}).`,
40832
+ );
40833
+ return;
40834
+ }
40835
+
40836
+ if (result.hasUpdate) {
40837
+ ctx.ui.info(
40838
+ `New version available: ${chalk.gray(result.currentVersion)} → ${chalk.green(result.latestVersion)}`,
40839
+ );
40840
+ }
40841
+
40842
+ ctx.ui.info('Upgrading Coze CLI...');
40843
+
40844
+ const packageManager = detectPackageManager();
40845
+ const installCmd = getInstallCommand(packageManager, options.tag);
40846
+
40847
+ ctx.ui.verbose(`Using package manager: ${packageManager}`);
40848
+ ctx.ui.verbose(`Running: ${installCmd}`);
40849
+
40850
+ node_child_process.execSync(installCmd, { stdio: 'inherit' });
40851
+
40852
+ const newVersion = getCurrentVersion();
40853
+ ctx.ui.success(
40854
+ `Successfully upgraded Coze CLI to ${result.latestVersion}. (was ${result.currentVersion})`,
40855
+ );
40856
+
40857
+ if (ctx.format === 'json') {
40858
+ ctx.response.print({
40859
+ previousVersion: result.currentVersion,
40860
+ currentVersion: newVersion,
40861
+ latestVersion: result.latestVersion,
40862
+ status: 'upgraded',
40863
+ });
40864
+ }
40865
+ } catch (error) {
40866
+ ctx.ui.error(`Failed to upgrade: ${(error ).message}`);
40867
+ ctx.ui.info(
40868
+ 'You can try upgrading manually with: npm install -g @coze/cli',
40869
+ );
40870
+ process.exit(index.ExitCode.GENERAL_ERROR);
40871
+ }
40872
+ });
40873
+ }
40874
+
40619
40875
  function registerAllCommands(program) {
40620
- registerCommand(program);
40621
- registerCommand$7(program);
40876
+ registerCommand$1(program);
40877
+ registerCommand$8(program);
40622
40878
  registerAllCommands$1(program);
40623
40879
  registerFileCommands(program);
40880
+ registerCommand$b(program);
40624
40881
  registerCommand$a(program);
40625
- registerCommand$9(program);
40626
40882
  registerGenerateCommands(program);
40627
- registerCommand$8(program);
40883
+ registerCommand$9(program);
40884
+ registerCommand(program);
40628
40885
 
40629
- // Initialize auto-completion after all commands are registered
40630
40886
  initCompletion();
40631
40887
  }
40632
40888
 
40633
- var version = "0.1.0-alpha.5276dd";
40634
- const packageJson = {
40635
- version: version};
40636
-
40637
40889
  function _optionalChain$2(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = fn(value); } else if (op === 'call' || op === 'optionalCall') { value = fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; }
40638
40890
 
40639
40891
 
@@ -41289,6 +41541,78 @@ async function buildAndRunProgram(ctx) {
41289
41541
  }
41290
41542
  }
41291
41543
 
41544
+ function parseArgv(argv) {
41545
+ const globalOptions = {};
41546
+ let commandName;
41547
+ const commandArgs = [];
41548
+ let seenCommand = false;
41549
+
41550
+ for (let i = 0; i < argv.length; i++) {
41551
+ const token = argv[i];
41552
+
41553
+ if (token === '--help' || token === '-h') {
41554
+ globalOptions.help = true;
41555
+ continue;
41556
+ }
41557
+ if (token === '--version' || token === '-v') {
41558
+ globalOptions.version = true;
41559
+ continue;
41560
+ }
41561
+ if (token === '--output') {
41562
+ globalOptions.output = argv[++i];
41563
+ continue;
41564
+ }
41565
+ if (token === '--format') {
41566
+ const format = argv[++i];
41567
+ if (format === 'json' || format === 'text') {
41568
+ globalOptions.format = format;
41569
+ }
41570
+ continue;
41571
+ }
41572
+ if (token === '--no-color') {
41573
+ globalOptions.noColor = true;
41574
+ continue;
41575
+ }
41576
+ if (token === '--config') {
41577
+ globalOptions.config = argv[++i];
41578
+ continue;
41579
+ }
41580
+ if (token === '--org-id') {
41581
+ globalOptions.orgId = argv[++i];
41582
+ continue;
41583
+ }
41584
+ if (token === '--space-id') {
41585
+ globalOptions.spaceId = argv[++i];
41586
+ continue;
41587
+ }
41588
+ if (token === '--verbose') {
41589
+ globalOptions.verbose = true;
41590
+ continue;
41591
+ }
41592
+ if (token === '--debug') {
41593
+ globalOptions.debug = true;
41594
+ continue;
41595
+ }
41596
+ if (token === '--log-file') {
41597
+ globalOptions.logFile = argv[++i];
41598
+ continue;
41599
+ }
41600
+ if (token === '--print-logs') {
41601
+ globalOptions.printLogs = true;
41602
+ continue;
41603
+ }
41604
+
41605
+ if (!seenCommand && !token.startsWith('-')) {
41606
+ commandName = token;
41607
+ seenCommand = true;
41608
+ } else {
41609
+ commandArgs.push(token);
41610
+ }
41611
+ }
41612
+
41613
+ return { globalOptions, commandName, commandArgs };
41614
+ }
41615
+
41292
41616
  async function main() {
41293
41617
  const argv = process.argv.slice(2);
41294
41618
  const { globalOptions } = parseArgv(argv);
@@ -41304,7 +41628,11 @@ async function main() {
41304
41628
  await buildAndRunProgram(context);
41305
41629
  };
41306
41630
 
41307
- const composed = compose([proxyMiddleware, requestMiddleware]);
41631
+ const composed = compose([
41632
+ proxyMiddleware,
41633
+ requestMiddleware,
41634
+ updateCheckMiddleware,
41635
+ ]);
41308
41636
  await composed(context, coreHandler);
41309
41637
  }
41310
41638