@zrhsh/wukong-cli 0.4.8 → 0.4.10

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/cli.js CHANGED
@@ -3,12 +3,6 @@ var __defProp = Object.defineProperty;
3
3
  var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
4
  var __getOwnPropNames = Object.getOwnPropertyNames;
5
5
  var __hasOwnProp = Object.prototype.hasOwnProperty;
6
- var __require = /* @__PURE__ */ ((x) => typeof require !== "undefined" ? require : typeof Proxy !== "undefined" ? new Proxy(x, {
7
- get: (a, b) => (typeof require !== "undefined" ? require : a)[b]
8
- }) : x)(function(x) {
9
- if (typeof require !== "undefined") return require.apply(this, arguments);
10
- throw Error('Dynamic require of "' + x + '" is not supported');
11
- });
12
6
  var __esm = (fn, res) => function __init() {
13
7
  return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res;
14
8
  };
@@ -95,194 +89,6 @@ var init_debug = __esm({
95
89
  }
96
90
  });
97
91
 
98
- // src/utils/version/cache.ts
99
- var VersionCache;
100
- var init_cache = __esm({
101
- "src/utils/version/cache.ts"() {
102
- "use strict";
103
- init_esm_shims();
104
- VersionCache = class {
105
- lastCheckTime = 0;
106
- cachedVersion = null;
107
- checkInterval;
108
- /**
109
- * Constructor
110
- * @param checkInterval - Check interval in milliseconds (default: 24 hours)
111
- */
112
- constructor(checkInterval = 24 * 60 * 60 * 1e3) {
113
- this.checkInterval = checkInterval;
114
- }
115
- /**
116
- * Check if a new version check should be performed
117
- */
118
- shouldCheck() {
119
- const now = Date.now();
120
- return now - this.lastCheckTime >= this.checkInterval;
121
- }
122
- /**
123
- * Get cached version
124
- */
125
- get() {
126
- return this.cachedVersion;
127
- }
128
- /**
129
- * Set cached version with timestamp
130
- */
131
- set(version) {
132
- this.cachedVersion = version;
133
- this.lastCheckTime = Date.now();
134
- }
135
- /**
136
- * Clear cache
137
- */
138
- clear() {
139
- this.lastCheckTime = 0;
140
- this.cachedVersion = null;
141
- }
142
- /**
143
- * Get time since last check
144
- */
145
- getTimeSinceLastCheck() {
146
- if (this.lastCheckTime === 0) {
147
- return 0;
148
- }
149
- return Date.now() - this.lastCheckTime;
150
- }
151
- };
152
- }
153
- });
154
-
155
- // src/utils/version/provider.ts
156
- var provider_exports = {};
157
- __export(provider_exports, {
158
- NpmVersionProvider: () => NpmVersionProvider
159
- });
160
- var NpmVersionProvider;
161
- var init_provider = __esm({
162
- "src/utils/version/provider.ts"() {
163
- "use strict";
164
- init_esm_shims();
165
- NpmVersionProvider = class {
166
- constructor(packageName, registryUrl) {
167
- this.packageName = packageName;
168
- this.registryUrl = registryUrl;
169
- this.timeout = 5e3;
170
- }
171
- timeout;
172
- /**
173
- * Get latest version from npm
174
- */
175
- async getLatestVersion() {
176
- try {
177
- const controller = new AbortController();
178
- const timeoutId = setTimeout(() => controller.abort(), this.timeout);
179
- const response = await fetch(`${this.registryUrl}/${this.packageName}`, {
180
- signal: controller.signal
181
- });
182
- clearTimeout(timeoutId);
183
- if (!response.ok) {
184
- return null;
185
- }
186
- const data = await response.json();
187
- return data["dist-tags"]?.latest || null;
188
- } catch (error) {
189
- return null;
190
- }
191
- }
192
- };
193
- }
194
- });
195
-
196
- // src/utils/version/checker.ts
197
- var checker_exports = {};
198
- __export(checker_exports, {
199
- VersionChecker: () => VersionChecker
200
- });
201
- var VersionChecker;
202
- var init_checker = __esm({
203
- "src/utils/version/checker.ts"() {
204
- "use strict";
205
- init_esm_shims();
206
- init_cache();
207
- VersionChecker = class {
208
- constructor(provider, currentVersion, cache) {
209
- this.provider = provider;
210
- this.currentVersion = currentVersion;
211
- this.cache = cache || new VersionCache();
212
- }
213
- cache;
214
- /**
215
- * Compare two version strings
216
- * Returns: 1 if v1 > v2, -1 if v1 < v2, 0 if equal
217
- */
218
- compareVersions(v1, v2) {
219
- const parts1 = v1.split(".").map(Number);
220
- const parts2 = v2.split(".").map(Number);
221
- for (let i = 0; i < Math.max(parts1.length, parts2.length); i++) {
222
- const part1 = parts1[i] || 0;
223
- const part2 = parts2[i] || 0;
224
- if (part1 > part2) return 1;
225
- if (part1 < part2) return -1;
226
- }
227
- return 0;
228
- }
229
- /**
230
- * Check for update (cached or fresh)
231
- */
232
- async checkForUpdate() {
233
- if (!this.cache.shouldCheck()) {
234
- const cached = this.cache.get();
235
- if (cached) {
236
- return {
237
- hasUpdate: this.compareVersions(cached, this.currentVersion) > 0,
238
- currentVersion: this.currentVersion,
239
- latestVersion: cached
240
- };
241
- }
242
- }
243
- const latestVersion = await this.provider.getLatestVersion();
244
- if (!latestVersion) {
245
- return {
246
- hasUpdate: false,
247
- currentVersion: this.currentVersion,
248
- latestVersion: null
249
- };
250
- }
251
- this.cache.set(latestVersion);
252
- return {
253
- hasUpdate: this.compareVersions(latestVersion, this.currentVersion) > 0,
254
- currentVersion: this.currentVersion,
255
- latestVersion
256
- };
257
- }
258
- /**
259
- * Check in background (for async execution)
260
- */
261
- async checkInBackground() {
262
- try {
263
- await this.checkForUpdate();
264
- } catch (error) {
265
- }
266
- }
267
- /**
268
- * Clear cached data
269
- */
270
- clearCache() {
271
- this.cache.clear();
272
- }
273
- /**
274
- * Get current cache info
275
- */
276
- getCacheInfo() {
277
- return {
278
- lastCheckTime: this.cache.lastCheckTime,
279
- cachedVersion: this.cache.cachedVersion
280
- };
281
- }
282
- };
283
- }
284
- });
285
-
286
92
  // src/config/errors/config-file-error.ts
287
93
  var ConfigFileError;
288
94
  var init_config_file_error = __esm({
@@ -394,16 +200,16 @@ var init_environments = __esm({
394
200
  });
395
201
 
396
202
  // src/config/config-loader.ts
397
- import { readFileSync, writeFileSync, existsSync, mkdirSync } from "fs";
398
- import { join, dirname } from "path";
399
- import { homedir } from "os";
203
+ import { readFileSync as readFileSync2, writeFileSync as writeFileSync2, existsSync, mkdirSync as mkdirSync2 } from "fs";
204
+ import { join as join2, dirname as dirname2 } from "path";
205
+ import { homedir as homedir2 } from "os";
400
206
  import { fileURLToPath as fileURLToPath2 } from "url";
401
207
  function getUserConfigPath() {
402
208
  return CONFIG_FILE_PATH;
403
209
  }
404
210
  function ensureConfigDir() {
405
211
  if (!existsSync(CONFIG_DIR)) {
406
- mkdirSync(CONFIG_DIR, { recursive: true });
212
+ mkdirSync2(CONFIG_DIR, { recursive: true });
407
213
  }
408
214
  }
409
215
  function createDefaultConfig() {
@@ -412,25 +218,25 @@ function createDefaultConfig() {
412
218
  return;
413
219
  }
414
220
  try {
415
- const templatePath = join(getProjectRoot(), "wukong-cli.json.template");
221
+ const templatePath = join2(getProjectRoot(), "wukong-cli.json.template");
416
222
  if (!existsSync(templatePath)) {
417
223
  console.warn(`Warning: Template config not found: ${templatePath}`);
418
224
  return;
419
225
  }
420
- const templateContent = readFileSync(templatePath, "utf-8");
226
+ const templateContent = readFileSync2(templatePath, "utf-8");
421
227
  const defaultConfig = JSON.parse(templateContent);
422
228
  ensureConfigDir();
423
- writeFileSync(configPath, JSON.stringify(defaultConfig, null, 2), "utf-8");
229
+ writeFileSync2(configPath, JSON.stringify(defaultConfig, null, 2), "utf-8");
424
230
  } catch (error) {
425
231
  }
426
232
  }
427
233
  function getProjectRoot() {
428
- let currentDir = dirname(fileURLToPath2(import.meta.url));
429
- while (currentDir !== dirname(currentDir)) {
430
- if (existsSync(join(currentDir, "package.json"))) {
234
+ let currentDir = dirname2(fileURLToPath2(import.meta.url));
235
+ while (currentDir !== dirname2(currentDir)) {
236
+ if (existsSync(join2(currentDir, "package.json"))) {
431
237
  return currentDir;
432
238
  }
433
- currentDir = dirname(currentDir);
239
+ currentDir = dirname2(currentDir);
434
240
  }
435
241
  return process.cwd();
436
242
  }
@@ -448,7 +254,7 @@ function loadConfig() {
448
254
  return {};
449
255
  }
450
256
  try {
451
- const content = readFileSync(configPath, "utf-8");
257
+ const content = readFileSync2(configPath, "utf-8");
452
258
  const config = JSON.parse(content);
453
259
  return config;
454
260
  } catch (error) {
@@ -525,8 +331,8 @@ var init_config_loader = __esm({
525
331
  init_esm_shims();
526
332
  init_environments();
527
333
  init_config_file_error();
528
- CONFIG_DIR = join(homedir(), ".wukong-cli");
529
- CONFIG_FILE_PATH = join(CONFIG_DIR, "wukong-cli.json");
334
+ CONFIG_DIR = join2(homedir2(), ".wukong-cli");
335
+ CONFIG_FILE_PATH = join2(CONFIG_DIR, "wukong-cli.json");
530
336
  }
531
337
  });
532
338
 
@@ -777,9 +583,9 @@ var init_keytar_adapter = __esm({
777
583
  });
778
584
 
779
585
  // src/providers/file-credential-store.ts
780
- import { writeFileSync as writeFileSync2, readFileSync as readFileSync2, unlinkSync, existsSync as existsSync2, mkdirSync as mkdirSync2 } from "fs";
781
- import { join as join2 } from "path";
782
- import { homedir as homedir2 } from "os";
586
+ import { writeFileSync as writeFileSync3, readFileSync as readFileSync3, unlinkSync, existsSync as existsSync2, mkdirSync as mkdirSync3 } from "fs";
587
+ import { join as join3 } from "path";
588
+ import { homedir as homedir3 } from "os";
783
589
  var FileCredentialStore;
784
590
  var init_file_credential_store = __esm({
785
591
  "src/providers/file-credential-store.ts"() {
@@ -788,21 +594,21 @@ var init_file_credential_store = __esm({
788
594
  FileCredentialStore = class {
789
595
  configDir;
790
596
  constructor() {
791
- this.configDir = join2(homedir2(), ".wukong-cli");
597
+ this.configDir = join3(homedir3(), ".wukong-cli");
792
598
  this.ensureConfigDir();
793
599
  }
794
600
  ensureConfigDir() {
795
601
  if (!existsSync2(this.configDir)) {
796
- mkdirSync2(this.configDir, { recursive: true, mode: 448 });
602
+ mkdirSync3(this.configDir, { recursive: true, mode: 448 });
797
603
  }
798
604
  }
799
605
  getTokenPath(service, account) {
800
606
  const filename = `${service}_${account}.token`;
801
- return join2(this.configDir, filename);
607
+ return join3(this.configDir, filename);
802
608
  }
803
609
  async setPassword(service, account, password) {
804
610
  const filePath = this.getTokenPath(service, account);
805
- writeFileSync2(filePath, password, { mode: 384 });
611
+ writeFileSync3(filePath, password, { mode: 384 });
806
612
  }
807
613
  async getPassword(service, account) {
808
614
  const filePath = this.getTokenPath(service, account);
@@ -810,7 +616,7 @@ var init_file_credential_store = __esm({
810
616
  return null;
811
617
  }
812
618
  try {
813
- return readFileSync2(filePath, "utf-8");
619
+ return readFileSync3(filePath, "utf-8");
814
620
  } catch {
815
621
  return null;
816
622
  }
@@ -934,8 +740,8 @@ var init_token_cache = __esm({
934
740
  return this.refreshToken;
935
741
  }
936
742
  setTokens(accessToken, refreshToken) {
937
- this.accessToken = accessToken;
938
- this.refreshToken = refreshToken;
743
+ if (accessToken !== null) this.accessToken = accessToken;
744
+ if (refreshToken !== null) this.refreshToken = refreshToken;
939
745
  }
940
746
  clear() {
941
747
  this.accessToken = null;
@@ -955,42 +761,280 @@ var init_token_cache = __esm({
955
761
  // src/cli.ts
956
762
  init_esm_shims();
957
763
  init_debug();
958
- import { Command as Command4 } from "commander";
764
+ import { Command as Command5 } from "commander";
959
765
 
960
766
  // src/utils/version/index.ts
961
767
  init_esm_shims();
962
- init_cache();
963
- init_provider();
964
- init_checker();
965
- var versionCheckerInstance = null;
966
- function getVersionChecker() {
967
- if (!versionCheckerInstance) {
968
- const { createRequire: createRequire2 } = __require("module");
969
- const nodeRequire = createRequire2(import.meta.url);
970
- const packageJson = nodeRequire("../../package.json");
971
- const { NpmVersionProvider: NpmVersionProvider2 } = (init_provider(), __toCommonJS(provider_exports));
972
- const { VersionChecker: VersionChecker2 } = (init_checker(), __toCommonJS(checker_exports));
973
- const provider = new NpmVersionProvider2(
974
- "@zrhsh/wukong-cli",
975
- "https://registry.npmjs.org"
976
- );
977
- versionCheckerInstance = new VersionChecker2(
978
- provider,
979
- packageJson.version
980
- );
768
+
769
+ // src/utils/version/checker.ts
770
+ init_esm_shims();
771
+
772
+ // src/utils/version/cache.ts
773
+ init_esm_shims();
774
+ var VersionCache = class {
775
+ lastCheckTime = 0;
776
+ cachedVersion = null;
777
+ checkInterval;
778
+ /**
779
+ * Constructor
780
+ * @param checkInterval - Check interval in milliseconds (default: 24 hours)
781
+ */
782
+ constructor(checkInterval = 24 * 60 * 60 * 1e3) {
783
+ this.checkInterval = checkInterval;
784
+ }
785
+ /**
786
+ * Check if a new version check should be performed
787
+ */
788
+ shouldCheck() {
789
+ const now = Date.now();
790
+ return now - this.lastCheckTime >= this.checkInterval;
791
+ }
792
+ /**
793
+ * Get cached version
794
+ */
795
+ get() {
796
+ return this.cachedVersion;
797
+ }
798
+ /**
799
+ * Set cached version with timestamp
800
+ */
801
+ set(version) {
802
+ this.cachedVersion = version;
803
+ this.lastCheckTime = Date.now();
804
+ }
805
+ /**
806
+ * Clear cache
807
+ */
808
+ clear() {
809
+ this.lastCheckTime = 0;
810
+ this.cachedVersion = null;
811
+ }
812
+ /**
813
+ * Get time since last check
814
+ */
815
+ getTimeSinceLastCheck() {
816
+ if (this.lastCheckTime === 0) {
817
+ return 0;
818
+ }
819
+ return Date.now() - this.lastCheckTime;
820
+ }
821
+ /** Last check timestamp */
822
+ get lastCheck() {
823
+ return this.lastCheckTime;
824
+ }
825
+ /** Cached version string */
826
+ get version() {
827
+ return this.cachedVersion;
981
828
  }
982
- return versionCheckerInstance;
829
+ };
830
+
831
+ // src/utils/version/compare.ts
832
+ init_esm_shims();
833
+ function compareVersions(v1, v2) {
834
+ const parts1 = v1.split(".").map(Number);
835
+ const parts2 = v2.split(".").map(Number);
836
+ for (let i = 0; i < Math.max(parts1.length, parts2.length); i++) {
837
+ const part1 = parts1[i] || 0;
838
+ const part2 = parts2[i] || 0;
839
+ if (part1 > part2) return 1;
840
+ if (part1 < part2) return -1;
841
+ }
842
+ return 0;
843
+ }
844
+ function describeVersionComparison(currentVersion, latestVersion) {
845
+ const comparison = compareVersions(currentVersion, latestVersion);
846
+ if (comparison > 0) {
847
+ return "current version is newer than latest";
848
+ }
849
+ if (comparison < 0) {
850
+ return "latest version is newer";
851
+ }
852
+ return "current version is equal to latest";
853
+ }
854
+
855
+ // src/utils/version/checker.ts
856
+ var VersionChecker = class {
857
+ constructor(provider, currentVersion, cache) {
858
+ this.provider = provider;
859
+ this.currentVersion = currentVersion;
860
+ this.cache = cache || new VersionCache();
861
+ }
862
+ cache;
863
+ /**
864
+ * Check for update (cached or fresh)
865
+ */
866
+ async checkForUpdate() {
867
+ if (!this.cache.shouldCheck()) {
868
+ const cached = this.cache.get();
869
+ if (cached) {
870
+ return {
871
+ hasUpdate: compareVersions(cached, this.currentVersion) > 0,
872
+ currentVersion: this.currentVersion,
873
+ latestVersion: cached
874
+ };
875
+ }
876
+ }
877
+ const latestVersion = await this.provider.getLatestVersion();
878
+ if (!latestVersion) {
879
+ return {
880
+ hasUpdate: false,
881
+ currentVersion: this.currentVersion,
882
+ latestVersion: null
883
+ };
884
+ }
885
+ this.cache.set(latestVersion);
886
+ return {
887
+ hasUpdate: compareVersions(latestVersion, this.currentVersion) > 0,
888
+ currentVersion: this.currentVersion,
889
+ latestVersion
890
+ };
891
+ }
892
+ /**
893
+ * Check in background (for async execution)
894
+ */
895
+ async checkInBackground(notifier) {
896
+ try {
897
+ const result = await this.checkForUpdate();
898
+ if (result.hasUpdate && notifier && result.latestVersion) {
899
+ notifier.notify(result.currentVersion, result.latestVersion);
900
+ }
901
+ } catch (error) {
902
+ }
903
+ }
904
+ /**
905
+ * Clear cached data
906
+ */
907
+ clearCache() {
908
+ this.cache.clear();
909
+ }
910
+ /**
911
+ * Get current cache info
912
+ */
913
+ getCacheInfo() {
914
+ return {
915
+ lastCheckTime: this.cache.lastCheck,
916
+ cachedVersion: this.cache.version
917
+ };
918
+ }
919
+ };
920
+
921
+ // src/utils/version/provider.ts
922
+ init_esm_shims();
923
+ var NpmVersionProvider = class {
924
+ constructor(packageName, registryUrl) {
925
+ this.packageName = packageName;
926
+ this.registryUrl = registryUrl;
927
+ this.timeout = 5e3;
928
+ }
929
+ timeout;
930
+ /**
931
+ * Get latest version from npm
932
+ */
933
+ async getLatestVersion() {
934
+ try {
935
+ const controller = new AbortController();
936
+ const timeoutId = setTimeout(() => controller.abort(), this.timeout);
937
+ const response = await fetch(`${this.registryUrl}/${this.packageName}`, {
938
+ signal: controller.signal
939
+ });
940
+ clearTimeout(timeoutId);
941
+ if (!response.ok) {
942
+ return null;
943
+ }
944
+ const data = await response.json();
945
+ return data["dist-tags"]?.latest || null;
946
+ } catch (error) {
947
+ return null;
948
+ }
949
+ }
950
+ };
951
+
952
+ // src/utils/version/persistent-cache.ts
953
+ init_esm_shims();
954
+ import { readFileSync, writeFileSync, mkdirSync } from "fs";
955
+ import { dirname } from "path";
956
+ var PersistentVersionCache = class extends VersionCache {
957
+ cacheFilePath;
958
+ constructor(cacheFilePath, checkInterval) {
959
+ super(checkInterval);
960
+ this.cacheFilePath = cacheFilePath;
961
+ this.loadFromFile();
962
+ }
963
+ loadFromFile() {
964
+ try {
965
+ const content = readFileSync(this.cacheFilePath, "utf-8");
966
+ const data = JSON.parse(content);
967
+ if (typeof data.lastCheckTime === "number" && typeof data.version === "string") {
968
+ this.lastCheckTime = data.lastCheckTime;
969
+ this.cachedVersion = data.version;
970
+ }
971
+ } catch {
972
+ }
973
+ }
974
+ saveToFile() {
975
+ try {
976
+ mkdirSync(dirname(this.cacheFilePath), { recursive: true });
977
+ const data = {
978
+ lastCheckTime: this.lastCheckTime,
979
+ version: this.cachedVersion ?? ""
980
+ };
981
+ writeFileSync(this.cacheFilePath, JSON.stringify(data), "utf-8");
982
+ } catch {
983
+ }
984
+ }
985
+ set(version) {
986
+ super.set(version);
987
+ this.saveToFile();
988
+ }
989
+ clear() {
990
+ super.clear();
991
+ this.saveToFile();
992
+ }
993
+ };
994
+
995
+ // src/utils/version/index.ts
996
+ import { homedir } from "os";
997
+ import { join } from "path";
998
+
999
+ // src/utils/version/notifier.ts
1000
+ init_esm_shims();
1001
+ import chalk2 from "chalk";
1002
+ var ConsoleNotifier = class {
1003
+ notify(currentVersion, latestVersion) {
1004
+ const message = `New version available: ${currentVersion} \u2192 ${latestVersion}, run 'wukong-cli update' to update.`;
1005
+ console.log(chalk2.yellow(message));
1006
+ }
1007
+ };
1008
+
1009
+ // src/utils/version/index.ts
1010
+ var versionCheckerInstance = null;
1011
+ function getVersionChecker(currentVersion) {
1012
+ if (versionCheckerInstance) {
1013
+ return versionCheckerInstance;
1014
+ }
1015
+ const cacheFilePath = join(homedir(), ".wukong-cli", "version-cache.json");
1016
+ const provider = new NpmVersionProvider(
1017
+ "@zrhsh/wukong-cli",
1018
+ "https://registry.npmjs.org"
1019
+ );
1020
+ const instance = new VersionChecker(
1021
+ provider,
1022
+ currentVersion,
1023
+ new PersistentVersionCache(cacheFilePath)
1024
+ );
1025
+ versionCheckerInstance = instance;
1026
+ return instance;
983
1027
  }
984
1028
 
985
1029
  // src/commands/auth.ts
986
1030
  init_esm_shims();
987
1031
  import { Command } from "commander";
988
- import chalk4 from "chalk";
1032
+ import chalk5 from "chalk";
989
1033
  import ora3 from "ora";
990
1034
 
991
1035
  // src/utils/environment.ts
992
1036
  init_esm_shims();
993
- import chalk2 from "chalk";
1037
+ import chalk3 from "chalk";
994
1038
  function formatEnvironmentDisplay(env, displayName) {
995
1039
  if (env === "prod") {
996
1040
  return "";
@@ -1000,7 +1044,7 @@ function formatEnvironmentDisplay(env, displayName) {
1000
1044
  function printEnvironmentInfo(env, displayName) {
1001
1045
  const display = formatEnvironmentDisplay(env, displayName);
1002
1046
  if (display) {
1003
- console.log(chalk2.dim(`Environment: ${chalk2.cyan(display)}`));
1047
+ console.log(chalk3.dim(`Environment: ${chalk3.cyan(display)}`));
1004
1048
  }
1005
1049
  }
1006
1050
 
@@ -1338,7 +1382,7 @@ init_esm_shims();
1338
1382
 
1339
1383
  // src/core/http/api-error-handler.ts
1340
1384
  init_esm_shims();
1341
- import chalk3 from "chalk";
1385
+ import chalk4 from "chalk";
1342
1386
  var ApiError = class extends Error {
1343
1387
  constructor(code, message, retryable = false) {
1344
1388
  super(message);
@@ -1359,17 +1403,31 @@ var ApiErrorHandler = class {
1359
1403
  this.register(9913, (response) => {
1360
1404
  const error = new ApiError(
1361
1405
  response.code,
1362
- response.message || "Token expired or invalid",
1406
+ response.msg || response.errorMsg || response.message || "Token expired or invalid",
1363
1407
  true
1364
1408
  // 可重试
1365
1409
  );
1366
1410
  throw error;
1367
1411
  });
1412
+ this.register(9909, (response) => {
1413
+ throw new ApiError(
1414
+ response.code,
1415
+ response.msg || response.errorMsg || response.message || "Access denied",
1416
+ false
1417
+ );
1418
+ });
1419
+ this.register(9914, (response) => {
1420
+ throw new ApiError(
1421
+ response.code,
1422
+ response.msg || response.errorMsg || response.message || "Session expired, please login again",
1423
+ false
1424
+ );
1425
+ });
1368
1426
  [401, 403].forEach((code) => {
1369
1427
  this.register(code, (response) => {
1370
1428
  throw new ApiError(
1371
1429
  response.code,
1372
- response.message || "Authentication failed",
1430
+ response.msg || response.errorMsg || response.message || "Authentication failed",
1373
1431
  code === 401
1374
1432
  // 401 可以尝试刷新 token
1375
1433
  );
@@ -1397,7 +1455,7 @@ var ApiErrorHandler = class {
1397
1455
  }
1398
1456
  throw new ApiError(
1399
1457
  response.code,
1400
- response.message || "Unknown API error"
1458
+ response.msg || response.errorMsg || response.message || "Unknown API error"
1401
1459
  );
1402
1460
  }
1403
1461
  }
@@ -1418,12 +1476,12 @@ var ApiErrorHandler = class {
1418
1476
  async tryRecover(error, recoverFunction) {
1419
1477
  if (error instanceof ApiError && error.retryable) {
1420
1478
  console.log("");
1421
- console.log(chalk3.yellow("\u26A0 Token expired, attempting refresh..."));
1479
+ console.log(chalk4.yellow("\u26A0 Token expired, attempting refresh..."));
1422
1480
  try {
1423
1481
  return await recoverFunction();
1424
1482
  } catch (refreshError) {
1425
1483
  console.log("");
1426
- console.log(chalk3.yellow("\u26A0 Auto-refresh failed:"), chalk3.dim(refreshError.message));
1484
+ console.log(chalk4.yellow("\u26A0 Auto-refresh failed:"), chalk4.dim(refreshError.message));
1427
1485
  throw new ApiError(
1428
1486
  error.code,
1429
1487
  `${error.message} (Auto-refresh failed)`
@@ -1445,33 +1503,11 @@ function getApiErrorHandler() {
1445
1503
  init_esm_shims();
1446
1504
  init_oceanet();
1447
1505
  import { createRetoken } from "ts-retoken";
1448
- function createFetchWithTimeout(timeoutMs) {
1449
- return async (url, options = {}) => {
1450
- const controller = new AbortController();
1451
- const timeoutId = setTimeout(() => controller.abort(), timeoutMs);
1452
- try {
1453
- const response = await fetch(url, {
1454
- ...options,
1455
- signal: controller.signal
1456
- });
1457
- clearTimeout(timeoutId);
1458
- return response;
1459
- } catch (error) {
1460
- clearTimeout(timeoutId);
1461
- if (error.name === "AbortError") {
1462
- throw new Error(`Request timeout after ${timeoutMs}ms`);
1463
- }
1464
- throw error;
1465
- }
1466
- };
1467
- }
1468
1506
  function createRetokenInstance(credentialStore, tokenCache) {
1469
1507
  const config = getOceanetConfig();
1470
1508
  const store = credentialStore || (init_credential_store(), __toCommonJS(credential_store_exports)).getCredentialStore();
1471
1509
  const cache = tokenCache || (init_token_cache(), __toCommonJS(token_cache_exports)).getGlobalTokenCache();
1472
1510
  return createRetoken({
1473
- // 使用带超时的 fetch(10秒超时)
1474
- fetch: createFetchWithTimeout(1e4),
1475
1511
  refreshEndpoint: {
1476
1512
  url: `${config.AUTH_BASE_URL}${config.AUTH_ENDPOINTS.REFRESH_TOKEN}`,
1477
1513
  method: "POST",
@@ -1524,8 +1560,8 @@ function createRetokenInstance(credentialStore, tokenCache) {
1524
1560
  },
1525
1561
  // 保存 token 到持久化存储和缓存
1526
1562
  setTokens: (tokens) => {
1527
- const accessToken = tokens?.accessToken || tokens?.access_token;
1528
- const refreshToken = tokens?.refreshToken || tokens?.refresh_token;
1563
+ const accessToken = tokens?.accessToken;
1564
+ const refreshToken = tokens?.refreshToken;
1529
1565
  if (!accessToken || !refreshToken) {
1530
1566
  throw new Error("Invalid tokens: missing access_token or refresh_token");
1531
1567
  }
@@ -1882,63 +1918,63 @@ authCommands.command("login").description("Login using Device Authorization Flow
1882
1918
  const config = getOceanetConfig();
1883
1919
  const envConfig = allEnvs[env];
1884
1920
  console.log("");
1885
- console.log(chalk4.bgBlue.white.bold(" Wukong CLI Login "));
1921
+ console.log(chalk5.bgBlue.white.bold(" Wukong CLI Login "));
1886
1922
  console.log("");
1887
1923
  printEnvironmentInfo(env, envConfig.displayName);
1888
1924
  console.log("");
1889
1925
  const adapter = createCliDeviceFlowAdapter();
1890
1926
  const { verificationUri, deviceCode, expiresIn, interval } = await adapter.getDeviceCode();
1891
1927
  console.log("");
1892
- console.log(chalk4.bold("=".repeat(50)));
1893
- console.log(chalk4.bold(" Please complete authorization"));
1894
- console.log(chalk4.bold("=".repeat(50)));
1928
+ console.log(chalk5.bold("=".repeat(50)));
1929
+ console.log(chalk5.bold(" Please complete authorization"));
1930
+ console.log(chalk5.bold("=".repeat(50)));
1895
1931
  console.log("");
1896
- console.log(chalk4.green(" Authorization URL:"));
1932
+ console.log(chalk5.green(" Authorization URL:"));
1897
1933
  console.log("");
1898
- console.log(chalk4.cyan(` ${verificationUri}`));
1934
+ console.log(chalk5.cyan(` ${verificationUri}`));
1899
1935
  console.log("");
1900
- console.error(chalk4.yellow.bold(">>> Please open this link in your browser <<<"));
1901
- console.error(chalk4.cyan(verificationUri));
1936
+ console.error(chalk5.yellow.bold(">>> Please open this link in your browser <<<"));
1937
+ console.error(chalk5.cyan(verificationUri));
1902
1938
  console.error("");
1903
1939
  const open = await import("open").catch(() => null);
1904
1940
  if (open) {
1905
1941
  try {
1906
1942
  await open.default(verificationUri);
1907
- console.log(chalk4.dim(" Browser opened automatically"));
1943
+ console.log(chalk5.dim(" Browser opened automatically"));
1908
1944
  } catch {
1909
- console.log(chalk4.dim(" Please copy link to browser"));
1945
+ console.log(chalk5.dim(" Please copy link to browser"));
1910
1946
  }
1911
1947
  } else {
1912
- console.log(chalk4.dim(" Please copy link to browser"));
1948
+ console.log(chalk5.dim(" Please copy link to browser"));
1913
1949
  }
1914
1950
  console.log("");
1915
- console.log(chalk4.dim("\u2550".repeat(50)));
1916
- console.log(chalk4.dim(` Device Code: ${deviceCode}`));
1917
- console.log(chalk4.dim(` Expires in: ${expiresIn} seconds`));
1918
- console.log(chalk4.dim("\u2550".repeat(50)));
1951
+ console.log(chalk5.dim("\u2550".repeat(50)));
1952
+ console.log(chalk5.dim(` Device Code: ${deviceCode}`));
1953
+ console.log(chalk5.dim(` Expires in: ${expiresIn} seconds`));
1954
+ console.log(chalk5.dim("\u2550".repeat(50)));
1919
1955
  console.log("");
1920
1956
  const tokens = await adapter.pollToken(deviceCode);
1921
1957
  await saveToken(tokens.accessToken, tokens.refreshToken);
1922
1958
  console.log("");
1923
- console.log(chalk4.bgGreen.black.bold(" [OK] Login Successful "));
1959
+ console.log(chalk5.bgGreen.black.bold(" [OK] Login Successful "));
1924
1960
  console.log("");
1925
- console.log(chalk4.green("[OK] Tokens saved securely"));
1961
+ console.log(chalk5.green("[OK] Tokens saved securely"));
1926
1962
  printEnvironmentInfo(env, envConfig.displayName);
1927
- console.log(chalk4.dim(`Access Token expires in: ${Math.floor(tokens.expiresIn / 60)} minutes`));
1963
+ console.log(chalk5.dim(`Access Token expires in: ${Math.floor(tokens.expiresIn / 60)} minutes`));
1928
1964
  console.log("");
1929
- console.log(chalk4.dim("Next:"), chalk4.cyan("wukong-cli auth status"));
1965
+ console.log(chalk5.dim("Next:"), chalk5.cyan("wukong-cli auth status"));
1930
1966
  console.log("");
1931
1967
  } catch (error) {
1932
1968
  if (error instanceof ConfigFileError) {
1933
1969
  console.log("");
1934
- console.log(chalk4.red(`[ERROR] Configuration Error`));
1970
+ console.log(chalk5.red(`[ERROR] Configuration Error`));
1935
1971
  console.log("");
1936
- console.log(chalk4.red(error.toUserMessage()));
1972
+ console.log(chalk5.red(error.toUserMessage()));
1937
1973
  console.log("");
1938
1974
  return;
1939
1975
  }
1940
1976
  console.log("");
1941
- console.log(chalk4.red(`[ERROR] ${error instanceof Error ? error.message : "Unknown error"}`));
1977
+ console.log(chalk5.red(`[ERROR] ${error instanceof Error ? error.message : "Unknown error"}`));
1942
1978
  console.log("");
1943
1979
  }
1944
1980
  });
@@ -1953,11 +1989,11 @@ authCommands.command("logout").description("Logout and clear saved tokens").acti
1953
1989
  await logout(accessToken);
1954
1990
  }
1955
1991
  console.log("");
1956
- console.log(chalk4.green(`[OK] Logged out from ${env}`), chalk4.dim(`(${envConfig.displayName})`));
1992
+ console.log(chalk5.green(`[OK] Logged out from ${env}`), chalk5.dim(`(${envConfig.displayName})`));
1957
1993
  console.log("");
1958
1994
  } catch {
1959
1995
  console.log("");
1960
- console.log(chalk4.yellow(`\u25CB Already logged out from ${env}`), chalk4.dim(`(${envConfig.displayName})`));
1996
+ console.log(chalk5.yellow(`\u25CB Already logged out from ${env}`), chalk5.dim(`(${envConfig.displayName})`));
1961
1997
  console.log("");
1962
1998
  }
1963
1999
  });
@@ -1970,10 +2006,10 @@ authCommands.command("refresh").description("Manually refresh access token").act
1970
2006
  const accessToken = await getAccessToken();
1971
2007
  if (!accessToken) {
1972
2008
  console.log("");
1973
- console.log(chalk4.yellow("[ERROR] Not authenticated"));
2009
+ console.log(chalk5.yellow("[ERROR] Not authenticated"));
1974
2010
  printEnvironmentInfo(env, envConfig.displayName);
1975
2011
  console.log("");
1976
- console.log(chalk4.dim(`Run: wukong-cli auth login`));
2012
+ console.log(chalk5.dim(`Run: wukong-cli auth login`));
1977
2013
  console.log("");
1978
2014
  return;
1979
2015
  }
@@ -1984,7 +2020,7 @@ authCommands.command("refresh").description("Manually refresh access token").act
1984
2020
  spinner.succeed("Token refreshed successfully!");
1985
2021
  console.log("");
1986
2022
  printEnvironmentInfo(env, envConfig.displayName);
1987
- console.log(chalk4.dim("New tokens saved securely"));
2023
+ console.log(chalk5.dim("New tokens saved securely"));
1988
2024
  console.log("");
1989
2025
  } catch (error) {
1990
2026
  spinner.fail("Token refresh failed");
@@ -1993,18 +2029,18 @@ authCommands.command("refresh").description("Manually refresh access token").act
1993
2029
  } catch (error) {
1994
2030
  if (error instanceof ConfigFileError) {
1995
2031
  console.log("");
1996
- console.log(chalk4.red(`[ERROR] Configuration Error`));
2032
+ console.log(chalk5.red(`[ERROR] Configuration Error`));
1997
2033
  console.log("");
1998
- console.log(chalk4.red(error.toUserMessage()));
2034
+ console.log(chalk5.red(error.toUserMessage()));
1999
2035
  console.log("");
2000
2036
  return;
2001
2037
  }
2002
2038
  console.log("");
2003
- console.log(chalk4.red(`[ERROR] ${error instanceof Error ? error.message : "Unknown error"}`));
2039
+ console.log(chalk5.red(`[ERROR] ${error instanceof Error ? error.message : "Unknown error"}`));
2004
2040
  console.log("");
2005
2041
  printEnvironmentInfo(env, envConfig.displayName);
2006
- console.log(chalk4.dim(`Your session may have expired. Please run:`));
2007
- console.log(chalk4.dim(` wukong-cli auth login`));
2042
+ console.log(chalk5.dim(`Your session may have expired. Please run:`));
2043
+ console.log(chalk5.dim(` wukong-cli auth login`));
2008
2044
  console.log("");
2009
2045
  }
2010
2046
  });
@@ -2018,10 +2054,10 @@ authCommands.command("status").description("Show authentication status").action(
2018
2054
  const config = getOceanetConfig();
2019
2055
  const accessToken = await getAccessToken();
2020
2056
  if (!accessToken) {
2021
- console.log(chalk4.yellow(`[ERROR] Not authenticated`));
2057
+ console.log(chalk5.yellow(`[ERROR] Not authenticated`));
2022
2058
  console.log("");
2023
2059
  printEnvironmentInfo(env, envConfig.displayName);
2024
- console.log(chalk4.dim(`Run: wukong-cli auth login`));
2060
+ console.log(chalk5.dim(`Run: wukong-cli auth login`));
2025
2061
  console.log("");
2026
2062
  return;
2027
2063
  }
@@ -2029,37 +2065,37 @@ authCommands.command("status").description("Show authentication status").action(
2029
2065
  const client = getClient();
2030
2066
  const userInfoUrl = `${config.AUTH_BASE_URL}/oceanet-auth/web/userInfo`;
2031
2067
  const userInfo = await client.get(userInfoUrl);
2032
- console.log(chalk4.green("[OK] Authenticated"));
2068
+ console.log(chalk5.green("[OK] Authenticated"));
2033
2069
  console.log("");
2034
2070
  const displayUser = userInfo.firstName ? `${userInfo.firstName} (${userInfo.username})` : userInfo.username || "N/A";
2035
2071
  printEnvironmentInfo(env, envConfig.displayName);
2036
- console.log(chalk4.dim("User:"), chalk4.cyan(displayUser));
2037
- console.log(chalk4.dim("Email:"), chalk4.cyan(userInfo.email || "N/A"));
2038
- console.log(chalk4.dim("OrgCode:"), chalk4.cyan(userInfo.ouCode || "N/A"));
2039
- console.log(chalk4.dim("OrgName:"), chalk4.cyan(userInfo.ouName || "N/A"));
2072
+ console.log(chalk5.dim("User:"), chalk5.cyan(displayUser));
2073
+ console.log(chalk5.dim("Email:"), chalk5.cyan(userInfo.email || "N/A"));
2074
+ console.log(chalk5.dim("OrgCode:"), chalk5.cyan(userInfo.ouCode || "N/A"));
2075
+ console.log(chalk5.dim("OrgName:"), chalk5.cyan(userInfo.ouName || "N/A"));
2040
2076
  console.log("");
2041
2077
  } catch (error) {
2042
2078
  const errorMsg = error instanceof Error ? error.message : String(error);
2043
- console.log(chalk4.yellow(`[ERROR] Not authenticated`));
2079
+ console.log(chalk5.yellow(`[ERROR] Not authenticated`));
2044
2080
  console.log("");
2045
- console.log(chalk4.red("Error:"), chalk4.dim(errorMsg));
2081
+ console.log(chalk5.red("Error:"), chalk5.dim(errorMsg));
2046
2082
  console.log("");
2047
2083
  printEnvironmentInfo(env, envConfig.displayName);
2048
- console.log(chalk4.dim(`Run: wukong-cli auth login`));
2084
+ console.log(chalk5.dim(`Run: wukong-cli auth login`));
2049
2085
  console.log("");
2050
2086
  }
2051
2087
  } catch (error) {
2052
2088
  if (error instanceof ConfigFileError) {
2053
- console.log(chalk4.red(`[ERROR] Configuration Error`));
2089
+ console.log(chalk5.red(`[ERROR] Configuration Error`));
2054
2090
  console.log("");
2055
- console.log(chalk4.red(error.toUserMessage()));
2091
+ console.log(chalk5.red(error.toUserMessage()));
2056
2092
  console.log("");
2057
2093
  return;
2058
2094
  }
2059
- console.log(chalk4.yellow(`\u2717 Not authenticated`));
2095
+ console.log(chalk5.yellow(`\u2717 Not authenticated`));
2060
2096
  console.log("");
2061
2097
  printEnvironmentInfo(env, envConfig.displayName);
2062
- console.log(chalk4.dim(`Run: wukong-cli auth login`));
2098
+ console.log(chalk5.dim(`Run: wukong-cli auth login`));
2063
2099
  console.log("");
2064
2100
  }
2065
2101
  });
@@ -2068,7 +2104,7 @@ authCommands.command("status").description("Show authentication status").action(
2068
2104
  init_esm_shims();
2069
2105
  import { Command as Command2 } from "commander";
2070
2106
  import ora4 from "ora";
2071
- import chalk5 from "chalk";
2107
+ import chalk6 from "chalk";
2072
2108
  init_oceanet();
2073
2109
  init_config_file_error();
2074
2110
  function fixGitBashPath(url) {
@@ -2117,14 +2153,14 @@ async function executeRequest(method, url, options) {
2117
2153
  const accessToken = await getAccessToken();
2118
2154
  if (!accessToken) {
2119
2155
  spinner.fail("Not authenticated");
2120
- console.error(chalk5.red("Please run: wukong-cli auth login"));
2156
+ console.error(chalk6.red("Please run: wukong-cli auth login"));
2121
2157
  process.exit(1);
2122
2158
  }
2123
2159
  const fullUrl = buildUrl2(url, options.baseUrl);
2124
2160
  const customHeaders = parseHeaders(options.headers);
2125
2161
  const client = getClient();
2126
2162
  const requestData = options.data ? JSON.parse(options.data) : void 0;
2127
- spinner.text = `${method} ${chalk5.cyan(fullUrl)}`;
2163
+ spinner.text = `${method} ${chalk6.cyan(fullUrl)}`;
2128
2164
  const startTime = Date.now();
2129
2165
  let data;
2130
2166
  switch (method.toUpperCase()) {
@@ -2150,22 +2186,29 @@ async function executeRequest(method, url, options) {
2150
2186
  const duration = Date.now() - startTime;
2151
2187
  spinner.succeed("Response received");
2152
2188
  console.log("");
2153
- console.log(chalk5.dim("Status:"), "200 OK");
2189
+ console.log(chalk6.dim("Status:"), "200 OK");
2154
2190
  console.log("");
2155
- console.log(chalk5.dim("Response:"));
2191
+ console.log(chalk6.dim("Response:"));
2156
2192
  console.log(JSON.stringify(data, null, 2));
2157
2193
  } catch (error) {
2158
2194
  spinner.fail("Request failed");
2159
2195
  if (error instanceof ConfigFileError) {
2160
2196
  console.log("");
2161
- console.log(chalk5.red(`[ERROR] Configuration Error`));
2197
+ console.log(chalk6.red(`[ERROR] Configuration Error`));
2162
2198
  console.log("");
2163
- console.log(chalk5.red(error.toUserMessage()));
2199
+ console.log(chalk6.red(error.toUserMessage()));
2200
+ console.log("");
2201
+ process.exit(1);
2202
+ }
2203
+ if (error instanceof ApiError) {
2204
+ console.log("");
2205
+ console.log(chalk6.red(`API Error (code: ${error.code})`));
2206
+ console.log(chalk6.red(error.message));
2164
2207
  console.log("");
2165
2208
  process.exit(1);
2166
2209
  }
2167
2210
  if (error instanceof Error) {
2168
- console.error(chalk5.red(error.message));
2211
+ console.error(chalk6.red(error.message));
2169
2212
  }
2170
2213
  process.exit(1);
2171
2214
  }
@@ -2191,58 +2234,58 @@ httpCommand.command("delete <url>").description("Send DELETE request").option("-
2191
2234
  // src/commands/init.ts
2192
2235
  init_esm_shims();
2193
2236
  import { Command as Command3 } from "commander";
2194
- import { writeFileSync as writeFileSync3, existsSync as existsSync3, readFileSync as readFileSync3, mkdirSync as mkdirSync3 } from "fs";
2195
- import { join as join3, dirname as dirname3 } from "path";
2196
- import { homedir as homedir3 } from "os";
2237
+ import { writeFileSync as writeFileSync4, existsSync as existsSync3, readFileSync as readFileSync4, mkdirSync as mkdirSync4 } from "fs";
2238
+ import { join as join4, dirname as dirname4 } from "path";
2239
+ import { homedir as homedir4 } from "os";
2197
2240
  import { fileURLToPath as fileURLToPath3 } from "url";
2198
- import chalk6 from "chalk";
2199
- var CONFIG_DIR2 = join3(homedir3(), ".wukong-cli");
2200
- var CONFIG_FILE_PATH2 = join3(CONFIG_DIR2, "wukong-cli.json");
2241
+ import chalk7 from "chalk";
2242
+ var CONFIG_DIR2 = join4(homedir4(), ".wukong-cli");
2243
+ var CONFIG_FILE_PATH2 = join4(CONFIG_DIR2, "wukong-cli.json");
2201
2244
  function getProjectRoot2() {
2202
- let currentDir = dirname3(fileURLToPath3(import.meta.url));
2203
- while (currentDir !== dirname3(currentDir)) {
2204
- if (existsSync3(join3(currentDir, "package.json"))) {
2245
+ let currentDir = dirname4(fileURLToPath3(import.meta.url));
2246
+ while (currentDir !== dirname4(currentDir)) {
2247
+ if (existsSync3(join4(currentDir, "package.json"))) {
2205
2248
  return currentDir;
2206
2249
  }
2207
- currentDir = dirname3(currentDir);
2250
+ currentDir = dirname4(currentDir);
2208
2251
  }
2209
2252
  return process.cwd();
2210
2253
  }
2211
2254
  function ensureConfigDir2() {
2212
2255
  if (!existsSync3(CONFIG_DIR2)) {
2213
- mkdirSync3(CONFIG_DIR2, { recursive: true });
2256
+ mkdirSync4(CONFIG_DIR2, { recursive: true });
2214
2257
  }
2215
2258
  }
2216
2259
  async function executeInit() {
2217
- const templatePath = join3(getProjectRoot2(), "wukong-cli.json.template");
2260
+ const templatePath = join4(getProjectRoot2(), "wukong-cli.json.template");
2218
2261
  if (!existsSync3(templatePath)) {
2219
- console.error(chalk6.red("\u274C Template configuration file not found"));
2220
- console.error(chalk6.yellow(`Expected location: ${templatePath}`));
2262
+ console.error(chalk7.red("\u274C Template configuration file not found"));
2263
+ console.error(chalk7.yellow(`Expected location: ${templatePath}`));
2221
2264
  process.exit(1);
2222
2265
  }
2223
2266
  try {
2224
2267
  ensureConfigDir2();
2225
- const templateContent = readFileSync3(templatePath, "utf-8");
2268
+ const templateContent = readFileSync4(templatePath, "utf-8");
2226
2269
  const configExists = existsSync3(CONFIG_FILE_PATH2);
2227
2270
  if (configExists) {
2228
- console.log(chalk6.yellow("\u26A0\uFE0F Existing configuration file will be overwritten"));
2271
+ console.log(chalk7.yellow("\u26A0\uFE0F Existing configuration file will be overwritten"));
2229
2272
  }
2230
- writeFileSync3(CONFIG_FILE_PATH2, templateContent, "utf-8");
2231
- console.log(chalk6.green("\u2705 Configuration file created successfully"));
2232
- console.log(chalk6.gray(`Location: ${CONFIG_FILE_PATH2}`));
2273
+ writeFileSync4(CONFIG_FILE_PATH2, templateContent, "utf-8");
2274
+ console.log(chalk7.green("\u2705 Configuration file created successfully"));
2275
+ console.log(chalk7.gray(`Location: ${CONFIG_FILE_PATH2}`));
2233
2276
  if (configExists) {
2234
- console.log(chalk6.yellow("Previous configuration has been overwritten"));
2277
+ console.log(chalk7.yellow("Previous configuration has been overwritten"));
2235
2278
  }
2236
2279
  try {
2237
2280
  const config = JSON.parse(templateContent);
2238
- console.log(chalk6.gray("\nConfiguration preview:"));
2239
- console.log(chalk6.gray(` Default Environment: ${config.defaultEnv}`));
2240
- console.log(chalk6.gray(` Configured Environments: ${Object.keys(config.environments).join(", ")}`));
2281
+ console.log(chalk7.gray("\nConfiguration preview:"));
2282
+ console.log(chalk7.gray(` Default Environment: ${config.defaultEnv}`));
2283
+ console.log(chalk7.gray(` Configured Environments: ${Object.keys(config.environments).join(", ")}`));
2241
2284
  } catch (parseError) {
2242
2285
  }
2243
2286
  } catch (error) {
2244
- console.error(chalk6.red("\u274C Failed to create configuration file"));
2245
- console.error(chalk6.yellow(`Error: ${error}`));
2287
+ console.error(chalk7.red("\u274C Failed to create configuration file"));
2288
+ console.error(chalk7.yellow(`Error: ${error}`));
2246
2289
  process.exit(1);
2247
2290
  }
2248
2291
  }
@@ -2250,9 +2293,116 @@ var initCommand = new Command3("init").description("Initialize configuration fil
2250
2293
  await executeInit();
2251
2294
  });
2252
2295
 
2296
+ // src/commands/update.ts
2297
+ init_esm_shims();
2298
+ import { Command as Command4 } from "commander";
2299
+
2300
+ // src/core/update/npm-updater.ts
2301
+ init_esm_shims();
2302
+ import { spawn } from "child_process";
2303
+ var UpdateExecutionError = class extends Error {
2304
+ constructor(message, exitCode = null) {
2305
+ super(message);
2306
+ this.exitCode = exitCode;
2307
+ this.name = "UpdateExecutionError";
2308
+ }
2309
+ };
2310
+ var NpmUpdater = class {
2311
+ constructor(spawnFn = spawn) {
2312
+ this.spawnFn = spawnFn;
2313
+ }
2314
+ updateToLatest() {
2315
+ return new Promise((resolve, reject) => {
2316
+ const child = this.spawnFn(
2317
+ "npm",
2318
+ ["install", "-g", "@zrhsh/wukong-cli@latest"],
2319
+ { stdio: ["ignore", "pipe", "pipe"] }
2320
+ );
2321
+ child.stdout?.pipe(process.stdout);
2322
+ child.stderr?.pipe(process.stderr);
2323
+ child.on("error", (error) => {
2324
+ reject(
2325
+ new UpdateExecutionError(
2326
+ `Failed to start npm: ${error.message}`,
2327
+ null
2328
+ )
2329
+ );
2330
+ });
2331
+ child.on("close", (code) => {
2332
+ if (code === 0) {
2333
+ resolve();
2334
+ return;
2335
+ }
2336
+ reject(
2337
+ new UpdateExecutionError(
2338
+ `npm install failed with exit code ${code}`,
2339
+ code
2340
+ )
2341
+ );
2342
+ });
2343
+ });
2344
+ }
2345
+ };
2346
+
2347
+ // src/commands/update.ts
2348
+ var MANUAL_UPDATE_COMMAND = "npm install -g @zrhsh/wukong-cli@latest";
2349
+ async function runUpdateCommand({
2350
+ currentVersion,
2351
+ versionProvider,
2352
+ updater,
2353
+ output
2354
+ }) {
2355
+ const latestVersion = await versionProvider.getLatestVersion();
2356
+ if (!latestVersion) {
2357
+ output.error("Unable to fetch latest version from npm registry.");
2358
+ output.error(`Manual update: ${MANUAL_UPDATE_COMMAND}`);
2359
+ return 1;
2360
+ }
2361
+ output.log(`Current version: ${currentVersion}`);
2362
+ output.log(`Latest version: ${latestVersion}`);
2363
+ output.log(
2364
+ `Compare result: ${describeVersionComparison(currentVersion, latestVersion)}`
2365
+ );
2366
+ const comparison = compareVersions(currentVersion, latestVersion);
2367
+ if (comparison === 0) {
2368
+ output.log("Already up to date.");
2369
+ return 0;
2370
+ }
2371
+ if (comparison > 0) {
2372
+ output.log("Skip update.");
2373
+ return 0;
2374
+ }
2375
+ output.log("Updating with npm...");
2376
+ try {
2377
+ await updater.updateToLatest();
2378
+ output.log("Update completed.");
2379
+ output.log("Run: wukong-cli --version");
2380
+ return 0;
2381
+ } catch (error) {
2382
+ const message = error instanceof Error ? error.message : String(error);
2383
+ output.error(`Update failed: ${message}`);
2384
+ output.error(`Manual update: ${MANUAL_UPDATE_COMMAND}`);
2385
+ return 1;
2386
+ }
2387
+ }
2388
+ var updateCommand = new Command4("update").description("Update wukong-cli to the latest npm version").action(async () => {
2389
+ const exitCode = await runUpdateCommand({
2390
+ currentVersion: "0.4.10",
2391
+ versionProvider: new NpmVersionProvider(
2392
+ "@zrhsh/wukong-cli",
2393
+ "https://registry.npmjs.org"
2394
+ ),
2395
+ updater: new NpmUpdater(),
2396
+ output: console
2397
+ });
2398
+ if (exitCode !== 0) {
2399
+ process.exitCode = exitCode;
2400
+ }
2401
+ });
2402
+
2253
2403
  // src/cli.ts
2254
- var program = new Command4();
2255
- program.name("wukong-cli").description("Wukong CLI - TypeScript implementation").version("0.4.8").option("--debug", "Enable debug mode (show HTTP requests)").hook("preAction", (thisCommand) => {
2404
+ var program = new Command5();
2405
+ program.name("wukong-cli").description("Wukong CLI - TypeScript implementation").version("0.4.10").option("--debug", "Enable debug mode (show HTTP requests)").hook("preAction", (thisCommand) => {
2256
2406
  const options = thisCommand.opts();
2257
2407
  if (options.debug === true) {
2258
2408
  setDebugMode(true, true);
@@ -2263,14 +2413,16 @@ program.name("wukong-cli").description("Wukong CLI - TypeScript implementation")
2263
2413
  program.addCommand(authCommands);
2264
2414
  program.addCommand(httpCommand);
2265
2415
  program.addCommand(initCommand);
2416
+ program.addCommand(updateCommand);
2266
2417
  if (process.argv.length === 2) {
2267
2418
  program.help();
2268
2419
  }
2269
2420
  program.parse();
2270
2421
  setImmediate(() => {
2271
2422
  try {
2272
- const versionChecker = getVersionChecker();
2273
- versionChecker.checkInBackground().catch(() => {
2423
+ const versionChecker = getVersionChecker("0.4.10");
2424
+ const notifier = new ConsoleNotifier();
2425
+ versionChecker.checkInBackground(notifier).catch(() => {
2274
2426
  });
2275
2427
  } catch {
2276
2428
  }