ccjk 12.0.6 → 12.0.7

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (62) hide show
  1. package/README.md +14 -0
  2. package/README.zh-CN.md +13 -0
  3. package/dist/chunks/api-cli.mjs +1 -1
  4. package/dist/chunks/ccjk-agents.mjs +3 -2
  5. package/dist/chunks/ccjk-all.mjs +129 -1764
  6. package/dist/chunks/ccjk-hooks.mjs +5 -4
  7. package/dist/chunks/ccjk-mcp.mjs +7 -6
  8. package/dist/chunks/ccjk-setup.mjs +3 -2
  9. package/dist/chunks/ccjk-skills.mjs +6 -5
  10. package/dist/chunks/ccr.mjs +6 -5
  11. package/dist/chunks/check-updates.mjs +8 -8
  12. package/dist/chunks/claude-code-config-manager.mjs +1 -1
  13. package/dist/chunks/claude-code-incremental-manager.mjs +2 -2
  14. package/dist/chunks/codex-config-switch.mjs +1 -1
  15. package/dist/chunks/codex-provider-manager.mjs +1 -1
  16. package/dist/chunks/config-switch.mjs +1 -1
  17. package/dist/chunks/config.mjs +1 -1
  18. package/dist/chunks/config2.mjs +1 -1
  19. package/dist/chunks/config3.mjs +1 -1
  20. package/dist/chunks/constants.mjs +33 -2
  21. package/dist/chunks/dashboard.mjs +115 -3
  22. package/dist/chunks/features.mjs +3 -3
  23. package/dist/chunks/init.mjs +108 -4
  24. package/dist/chunks/installer2.mjs +7 -7
  25. package/dist/chunks/manager.mjs +1048 -0
  26. package/dist/chunks/mcp-cli.mjs +1 -1
  27. package/dist/chunks/mcp.mjs +1 -1
  28. package/dist/chunks/menu.mjs +22 -1
  29. package/dist/chunks/notification.mjs +5 -2
  30. package/dist/chunks/package.mjs +1 -1
  31. package/dist/chunks/quick-provider.mjs +1 -269
  32. package/dist/chunks/quick-setup.mjs +10 -10
  33. package/dist/chunks/remote.mjs +4 -1
  34. package/dist/chunks/simple-config.mjs +1 -1
  35. package/dist/chunks/skill.mjs +117 -9003
  36. package/dist/chunks/skill2.mjs +9003 -0
  37. package/dist/chunks/skills-sync.mjs +536 -55
  38. package/dist/chunks/skills.mjs +7 -1156
  39. package/dist/chunks/smart-defaults.mjs +87 -9
  40. package/dist/chunks/status.mjs +1 -1
  41. package/dist/chunks/uninstall.mjs +1 -1
  42. package/dist/chunks/update.mjs +2 -2
  43. package/dist/chunks/zero-config.mjs +6 -2
  44. package/dist/cli.mjs +3 -1
  45. package/dist/i18n/locales/en/cloud.json +40 -0
  46. package/dist/i18n/locales/zh-CN/cloud.json +40 -0
  47. package/dist/index.d.mts +2586 -2
  48. package/dist/index.d.ts +2586 -2
  49. package/dist/index.mjs +1340 -7
  50. package/dist/shared/ccjk.B364Fu0N.mjs +1819 -0
  51. package/dist/shared/ccjk.BtB1e5jm.mjs +171 -0
  52. package/dist/shared/{ccjk.BnpWvs9V.mjs → ccjk.BwfbSKN2.mjs} +1 -1
  53. package/dist/shared/{ccjk.AqnXPAzw.mjs → ccjk.C2jHOZVP.mjs} +1 -1
  54. package/dist/shared/{ccjk.BSYWk9ML.mjs → ccjk.Cjj8SVrn.mjs} +1 -1
  55. package/dist/shared/ccjk.D6ycHbak.mjs +270 -0
  56. package/dist/shared/ccjk.D8ZLYSZZ.mjs +299 -0
  57. package/dist/shared/{ccjk.s7OCVzdd.mjs → ccjk.DS7UESmF.mjs} +2 -1483
  58. package/dist/shared/{ccjk.BiCrMV5O.mjs → ccjk.DXRAZcix.mjs} +0 -28
  59. package/dist/shared/ccjk.UIvifqNE.mjs +1486 -0
  60. package/dist/shared/{ccjk.BDKUdmLk.mjs → ccjk.c-ETfBZ_.mjs} +208 -86
  61. package/package.json +5 -1
  62. package/templates/claude-code/common/settings.json +3 -1
@@ -1,23 +1,27 @@
1
1
  import a from './index2.mjs';
2
- import { c as consola, o as ofetch, a as analyzeProject } from '../shared/ccjk.s7OCVzdd.mjs';
3
- import fs__default, { readFileSync, promises } from 'node:fs';
4
- import path__default, { dirname, join } from 'node:path';
5
- import { fileURLToPath } from 'node:url';
6
- import { randomUUID, createHash } from 'node:crypto';
2
+ import { c as consola } from '../shared/ccjk.UIvifqNE.mjs';
3
+ import { c as createCompleteCloudClient } from '../shared/ccjk.B364Fu0N.mjs';
7
4
  import { i18n, ensureI18nInitialized } from './index5.mjs';
5
+ import { createHash } from 'node:crypto';
6
+ import { promises, readFileSync } from 'node:fs';
7
+ import { join } from 'node:path';
8
+ import { a as analyzeProject } from '../shared/ccjk.DS7UESmF.mjs';
9
+ import { c as createDefaultGateway } from '../shared/ccjk.BtB1e5jm.mjs';
8
10
  import { ccjkAgents } from './ccjk-agents.mjs';
9
11
  import { ccjkHooks } from './ccjk-hooks.mjs';
10
12
  import { ccjkMcp } from './ccjk-mcp.mjs';
11
13
  import { ccjkSkills } from './ccjk-skills.mjs';
12
- import { a as extractString } from '../shared/ccjk.AqnXPAzw.mjs';
14
+ import { e as extractString } from '../shared/ccjk.C2jHOZVP.mjs';
13
15
  import '../shared/ccjk.BAGoDD49.mjs';
14
- import './index8.mjs';
16
+ import 'node:url';
17
+ import 'node:process';
15
18
  import '../shared/ccjk.bQ7Dh1g4.mjs';
19
+ import './index8.mjs';
16
20
  import 'tinyglobby';
17
21
  import '../shared/ccjk.BBtCGd_g.mjs';
18
- import 'node:process';
19
22
  import './constants.mjs';
20
23
  import 'node:os';
24
+ import '../shared/ccjk.D6ycHbak.mjs';
21
25
  import '../shared/ccjk.CfKKcvWy.mjs';
22
26
  import 'node:perf_hooks';
23
27
  import './index3.mjs';
@@ -44,1714 +48,14 @@ import 'module';
44
48
  import 'node:stream';
45
49
  import '../shared/ccjk.DsYaCCx4.mjs';
46
50
 
47
- const defaults = Object.freeze({
48
- ignoreUnknown: false,
49
- respectType: false,
50
- respectFunctionNames: false,
51
- respectFunctionProperties: false,
52
- unorderedObjects: true,
53
- unorderedArrays: false,
54
- unorderedSets: false,
55
- excludeKeys: void 0,
56
- excludeValues: void 0,
57
- replacer: void 0
58
- });
59
- function objectHash(object, options) {
60
- if (options) {
61
- options = { ...defaults, ...options };
62
- } else {
63
- options = defaults;
64
- }
65
- const hasher = createHasher(options);
66
- hasher.dispatch(object);
67
- return hasher.toString();
68
- }
69
- const defaultPrototypesKeys = Object.freeze([
70
- "prototype",
71
- "__proto__",
72
- "constructor"
73
- ]);
74
- function createHasher(options) {
75
- let buff = "";
76
- let context = /* @__PURE__ */ new Map();
77
- const write = (str) => {
78
- buff += str;
79
- };
80
- return {
81
- toString() {
82
- return buff;
83
- },
84
- getContext() {
85
- return context;
86
- },
87
- dispatch(value) {
88
- if (options.replacer) {
89
- value = options.replacer(value);
90
- }
91
- const type = value === null ? "null" : typeof value;
92
- return this[type](value);
93
- },
94
- object(object) {
95
- if (object && typeof object.toJSON === "function") {
96
- return this.object(object.toJSON());
97
- }
98
- const objString = Object.prototype.toString.call(object);
99
- let objType = "";
100
- const objectLength = objString.length;
101
- if (objectLength < 10) {
102
- objType = "unknown:[" + objString + "]";
103
- } else {
104
- objType = objString.slice(8, objectLength - 1);
105
- }
106
- objType = objType.toLowerCase();
107
- let objectNumber = null;
108
- if ((objectNumber = context.get(object)) === void 0) {
109
- context.set(object, context.size);
110
- } else {
111
- return this.dispatch("[CIRCULAR:" + objectNumber + "]");
112
- }
113
- if (typeof Buffer !== "undefined" && Buffer.isBuffer && Buffer.isBuffer(object)) {
114
- write("buffer:");
115
- return write(object.toString("utf8"));
116
- }
117
- if (objType !== "object" && objType !== "function" && objType !== "asyncfunction") {
118
- if (this[objType]) {
119
- this[objType](object);
120
- } else if (!options.ignoreUnknown) {
121
- this.unkown(object, objType);
122
- }
123
- } else {
124
- let keys = Object.keys(object);
125
- if (options.unorderedObjects) {
126
- keys = keys.sort();
127
- }
128
- let extraKeys = [];
129
- if (options.respectType !== false && !isNativeFunction(object)) {
130
- extraKeys = defaultPrototypesKeys;
131
- }
132
- if (options.excludeKeys) {
133
- keys = keys.filter((key) => {
134
- return !options.excludeKeys(key);
135
- });
136
- extraKeys = extraKeys.filter((key) => {
137
- return !options.excludeKeys(key);
138
- });
139
- }
140
- write("object:" + (keys.length + extraKeys.length) + ":");
141
- const dispatchForKey = (key) => {
142
- this.dispatch(key);
143
- write(":");
144
- if (!options.excludeValues) {
145
- this.dispatch(object[key]);
146
- }
147
- write(",");
148
- };
149
- for (const key of keys) {
150
- dispatchForKey(key);
151
- }
152
- for (const key of extraKeys) {
153
- dispatchForKey(key);
154
- }
155
- }
156
- },
157
- array(arr, unordered) {
158
- unordered = unordered === void 0 ? options.unorderedArrays !== false : unordered;
159
- write("array:" + arr.length + ":");
160
- if (!unordered || arr.length <= 1) {
161
- for (const entry of arr) {
162
- this.dispatch(entry);
163
- }
164
- return;
165
- }
166
- const contextAdditions = /* @__PURE__ */ new Map();
167
- const entries = arr.map((entry) => {
168
- const hasher = createHasher(options);
169
- hasher.dispatch(entry);
170
- for (const [key, value] of hasher.getContext()) {
171
- contextAdditions.set(key, value);
172
- }
173
- return hasher.toString();
174
- });
175
- context = contextAdditions;
176
- entries.sort();
177
- return this.array(entries, false);
178
- },
179
- date(date) {
180
- return write("date:" + date.toJSON());
181
- },
182
- symbol(sym) {
183
- return write("symbol:" + sym.toString());
184
- },
185
- unkown(value, type) {
186
- write(type);
187
- if (!value) {
188
- return;
189
- }
190
- write(":");
191
- if (value && typeof value.entries === "function") {
192
- return this.array(
193
- Array.from(value.entries()),
194
- true
195
- /* ordered */
196
- );
197
- }
198
- },
199
- error(err) {
200
- return write("error:" + err.toString());
201
- },
202
- boolean(bool) {
203
- return write("bool:" + bool);
204
- },
205
- string(string) {
206
- write("string:" + string.length + ":");
207
- write(string);
208
- },
209
- function(fn) {
210
- write("fn:");
211
- if (isNativeFunction(fn)) {
212
- this.dispatch("[native]");
213
- } else {
214
- this.dispatch(fn.toString());
215
- }
216
- if (options.respectFunctionNames !== false) {
217
- this.dispatch("function-name:" + String(fn.name));
218
- }
219
- if (options.respectFunctionProperties) {
220
- this.object(fn);
221
- }
222
- },
223
- number(number) {
224
- return write("number:" + number);
225
- },
226
- xml(xml) {
227
- return write("xml:" + xml.toString());
228
- },
229
- null() {
230
- return write("Null");
231
- },
232
- undefined() {
233
- return write("Undefined");
234
- },
235
- regexp(regex) {
236
- return write("regex:" + regex.toString());
237
- },
238
- uint8array(arr) {
239
- write("uint8array:");
240
- return this.dispatch(Array.prototype.slice.call(arr));
241
- },
242
- uint8clampedarray(arr) {
243
- write("uint8clampedarray:");
244
- return this.dispatch(Array.prototype.slice.call(arr));
245
- },
246
- int8array(arr) {
247
- write("int8array:");
248
- return this.dispatch(Array.prototype.slice.call(arr));
249
- },
250
- uint16array(arr) {
251
- write("uint16array:");
252
- return this.dispatch(Array.prototype.slice.call(arr));
253
- },
254
- int16array(arr) {
255
- write("int16array:");
256
- return this.dispatch(Array.prototype.slice.call(arr));
257
- },
258
- uint32array(arr) {
259
- write("uint32array:");
260
- return this.dispatch(Array.prototype.slice.call(arr));
261
- },
262
- int32array(arr) {
263
- write("int32array:");
264
- return this.dispatch(Array.prototype.slice.call(arr));
265
- },
266
- float32array(arr) {
267
- write("float32array:");
268
- return this.dispatch(Array.prototype.slice.call(arr));
269
- },
270
- float64array(arr) {
271
- write("float64array:");
272
- return this.dispatch(Array.prototype.slice.call(arr));
273
- },
274
- arraybuffer(arr) {
275
- write("arraybuffer:");
276
- return this.dispatch(new Uint8Array(arr));
277
- },
278
- url(url) {
279
- return write("url:" + url.toString());
280
- },
281
- map(map) {
282
- write("map:");
283
- const arr = [...map];
284
- return this.array(arr, options.unorderedSets !== false);
285
- },
286
- set(set) {
287
- write("set:");
288
- const arr = [...set];
289
- return this.array(arr, options.unorderedSets !== false);
290
- },
291
- file(file) {
292
- write("file:");
293
- return this.dispatch([file.name, file.size, file.type, file.lastModfied]);
294
- },
295
- blob() {
296
- if (options.ignoreUnknown) {
297
- return write("[blob]");
298
- }
299
- throw new Error(
300
- 'Hashing Blob objects is currently not supported\nUse "options.replacer" or "options.ignoreUnknown"\n'
301
- );
302
- },
303
- domwindow() {
304
- return write("domwindow");
305
- },
306
- bigint(number) {
307
- return write("bigint:" + number.toString());
308
- },
309
- /* Node.js standard native objects */
310
- process() {
311
- return write("process");
312
- },
313
- timer() {
314
- return write("timer");
315
- },
316
- pipe() {
317
- return write("pipe");
318
- },
319
- tcp() {
320
- return write("tcp");
321
- },
322
- udp() {
323
- return write("udp");
324
- },
325
- tty() {
326
- return write("tty");
327
- },
328
- statwatcher() {
329
- return write("statwatcher");
330
- },
331
- securecontext() {
332
- return write("securecontext");
333
- },
334
- connection() {
335
- return write("connection");
336
- },
337
- zlib() {
338
- return write("zlib");
339
- },
340
- context() {
341
- return write("context");
342
- },
343
- nodescript() {
344
- return write("nodescript");
345
- },
346
- httpparser() {
347
- return write("httpparser");
348
- },
349
- dataview() {
350
- return write("dataview");
351
- },
352
- signal() {
353
- return write("signal");
354
- },
355
- fsevent() {
356
- return write("fsevent");
357
- },
358
- tlswrap() {
359
- return write("tlswrap");
360
- }
361
- };
362
- }
363
- const nativeFunc = "[native code] }";
364
- const nativeFuncLength = nativeFunc.length;
365
- function isNativeFunction(f) {
366
- if (typeof f !== "function") {
367
- return false;
368
- }
369
- return Function.prototype.toString.call(f).slice(-nativeFuncLength) === nativeFunc;
370
- }
371
-
372
- class WordArray {
373
- words;
374
- sigBytes;
375
- constructor(words, sigBytes) {
376
- words = this.words = words || [];
377
- this.sigBytes = sigBytes === void 0 ? words.length * 4 : sigBytes;
378
- }
379
- toString(encoder) {
380
- return (encoder || Hex).stringify(this);
381
- }
382
- concat(wordArray) {
383
- this.clamp();
384
- if (this.sigBytes % 4) {
385
- for (let i = 0; i < wordArray.sigBytes; i++) {
386
- const thatByte = wordArray.words[i >>> 2] >>> 24 - i % 4 * 8 & 255;
387
- this.words[this.sigBytes + i >>> 2] |= thatByte << 24 - (this.sigBytes + i) % 4 * 8;
388
- }
389
- } else {
390
- for (let j = 0; j < wordArray.sigBytes; j += 4) {
391
- this.words[this.sigBytes + j >>> 2] = wordArray.words[j >>> 2];
392
- }
393
- }
394
- this.sigBytes += wordArray.sigBytes;
395
- return this;
396
- }
397
- clamp() {
398
- this.words[this.sigBytes >>> 2] &= 4294967295 << 32 - this.sigBytes % 4 * 8;
399
- this.words.length = Math.ceil(this.sigBytes / 4);
400
- }
401
- clone() {
402
- return new WordArray([...this.words]);
403
- }
404
- }
405
- const Hex = {
406
- stringify(wordArray) {
407
- const hexChars = [];
408
- for (let i = 0; i < wordArray.sigBytes; i++) {
409
- const bite = wordArray.words[i >>> 2] >>> 24 - i % 4 * 8 & 255;
410
- hexChars.push((bite >>> 4).toString(16), (bite & 15).toString(16));
411
- }
412
- return hexChars.join("");
413
- }
414
- };
415
- const Base64 = {
416
- stringify(wordArray) {
417
- const keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
418
- const base64Chars = [];
419
- for (let i = 0; i < wordArray.sigBytes; i += 3) {
420
- const byte1 = wordArray.words[i >>> 2] >>> 24 - i % 4 * 8 & 255;
421
- const byte2 = wordArray.words[i + 1 >>> 2] >>> 24 - (i + 1) % 4 * 8 & 255;
422
- const byte3 = wordArray.words[i + 2 >>> 2] >>> 24 - (i + 2) % 4 * 8 & 255;
423
- const triplet = byte1 << 16 | byte2 << 8 | byte3;
424
- for (let j = 0; j < 4 && i * 8 + j * 6 < wordArray.sigBytes * 8; j++) {
425
- base64Chars.push(keyStr.charAt(triplet >>> 6 * (3 - j) & 63));
426
- }
427
- }
428
- return base64Chars.join("");
429
- }
430
- };
431
- const Latin1 = {
432
- parse(latin1Str) {
433
- const latin1StrLength = latin1Str.length;
434
- const words = [];
435
- for (let i = 0; i < latin1StrLength; i++) {
436
- words[i >>> 2] |= (latin1Str.charCodeAt(i) & 255) << 24 - i % 4 * 8;
437
- }
438
- return new WordArray(words, latin1StrLength);
439
- }
440
- };
441
- const Utf8 = {
442
- parse(utf8Str) {
443
- return Latin1.parse(unescape(encodeURIComponent(utf8Str)));
444
- }
445
- };
446
- class BufferedBlockAlgorithm {
447
- _data = new WordArray();
448
- _nDataBytes = 0;
449
- _minBufferSize = 0;
450
- blockSize = 512 / 32;
451
- reset() {
452
- this._data = new WordArray();
453
- this._nDataBytes = 0;
454
- }
455
- _append(data) {
456
- if (typeof data === "string") {
457
- data = Utf8.parse(data);
458
- }
459
- this._data.concat(data);
460
- this._nDataBytes += data.sigBytes;
461
- }
462
- _doProcessBlock(_dataWords, _offset) {
463
- }
464
- _process(doFlush) {
465
- let processedWords;
466
- let nBlocksReady = this._data.sigBytes / (this.blockSize * 4);
467
- if (doFlush) {
468
- nBlocksReady = Math.ceil(nBlocksReady);
469
- } else {
470
- nBlocksReady = Math.max((nBlocksReady | 0) - this._minBufferSize, 0);
471
- }
472
- const nWordsReady = nBlocksReady * this.blockSize;
473
- const nBytesReady = Math.min(nWordsReady * 4, this._data.sigBytes);
474
- if (nWordsReady) {
475
- for (let offset = 0; offset < nWordsReady; offset += this.blockSize) {
476
- this._doProcessBlock(this._data.words, offset);
477
- }
478
- processedWords = this._data.words.splice(0, nWordsReady);
479
- this._data.sigBytes -= nBytesReady;
480
- }
481
- return new WordArray(processedWords, nBytesReady);
482
- }
483
- }
484
- class Hasher extends BufferedBlockAlgorithm {
485
- update(messageUpdate) {
486
- this._append(messageUpdate);
487
- this._process();
488
- return this;
489
- }
490
- finalize(messageUpdate) {
491
- if (messageUpdate) {
492
- this._append(messageUpdate);
493
- }
494
- }
495
- }
496
-
497
- const H = [
498
- 1779033703,
499
- -1150833019,
500
- 1013904242,
501
- -1521486534,
502
- 1359893119,
503
- -1694144372,
504
- 528734635,
505
- 1541459225
506
- ];
507
- const K = [
508
- 1116352408,
509
- 1899447441,
510
- -1245643825,
511
- -373957723,
512
- 961987163,
513
- 1508970993,
514
- -1841331548,
515
- -1424204075,
516
- -670586216,
517
- 310598401,
518
- 607225278,
519
- 1426881987,
520
- 1925078388,
521
- -2132889090,
522
- -1680079193,
523
- -1046744716,
524
- -459576895,
525
- -272742522,
526
- 264347078,
527
- 604807628,
528
- 770255983,
529
- 1249150122,
530
- 1555081692,
531
- 1996064986,
532
- -1740746414,
533
- -1473132947,
534
- -1341970488,
535
- -1084653625,
536
- -958395405,
537
- -710438585,
538
- 113926993,
539
- 338241895,
540
- 666307205,
541
- 773529912,
542
- 1294757372,
543
- 1396182291,
544
- 1695183700,
545
- 1986661051,
546
- -2117940946,
547
- -1838011259,
548
- -1564481375,
549
- -1474664885,
550
- -1035236496,
551
- -949202525,
552
- -778901479,
553
- -694614492,
554
- -200395387,
555
- 275423344,
556
- 430227734,
557
- 506948616,
558
- 659060556,
559
- 883997877,
560
- 958139571,
561
- 1322822218,
562
- 1537002063,
563
- 1747873779,
564
- 1955562222,
565
- 2024104815,
566
- -2067236844,
567
- -1933114872,
568
- -1866530822,
569
- -1538233109,
570
- -1090935817,
571
- -965641998
572
- ];
573
- const W = [];
574
- class SHA256 extends Hasher {
575
- _hash = new WordArray([...H]);
576
- /**
577
- * Resets the internal state of the hash object to initial values.
578
- */
579
- reset() {
580
- super.reset();
581
- this._hash = new WordArray([...H]);
582
- }
583
- _doProcessBlock(M, offset) {
584
- const H2 = this._hash.words;
585
- let a = H2[0];
586
- let b = H2[1];
587
- let c = H2[2];
588
- let d = H2[3];
589
- let e = H2[4];
590
- let f = H2[5];
591
- let g = H2[6];
592
- let h = H2[7];
593
- for (let i = 0; i < 64; i++) {
594
- if (i < 16) {
595
- W[i] = M[offset + i] | 0;
596
- } else {
597
- const gamma0x = W[i - 15];
598
- const gamma0 = (gamma0x << 25 | gamma0x >>> 7) ^ (gamma0x << 14 | gamma0x >>> 18) ^ gamma0x >>> 3;
599
- const gamma1x = W[i - 2];
600
- const gamma1 = (gamma1x << 15 | gamma1x >>> 17) ^ (gamma1x << 13 | gamma1x >>> 19) ^ gamma1x >>> 10;
601
- W[i] = gamma0 + W[i - 7] + gamma1 + W[i - 16];
602
- }
603
- const ch = e & f ^ ~e & g;
604
- const maj = a & b ^ a & c ^ b & c;
605
- const sigma0 = (a << 30 | a >>> 2) ^ (a << 19 | a >>> 13) ^ (a << 10 | a >>> 22);
606
- const sigma1 = (e << 26 | e >>> 6) ^ (e << 21 | e >>> 11) ^ (e << 7 | e >>> 25);
607
- const t1 = h + sigma1 + ch + K[i] + W[i];
608
- const t2 = sigma0 + maj;
609
- h = g;
610
- g = f;
611
- f = e;
612
- e = d + t1 | 0;
613
- d = c;
614
- c = b;
615
- b = a;
616
- a = t1 + t2 | 0;
617
- }
618
- H2[0] = H2[0] + a | 0;
619
- H2[1] = H2[1] + b | 0;
620
- H2[2] = H2[2] + c | 0;
621
- H2[3] = H2[3] + d | 0;
622
- H2[4] = H2[4] + e | 0;
623
- H2[5] = H2[5] + f | 0;
624
- H2[6] = H2[6] + g | 0;
625
- H2[7] = H2[7] + h | 0;
626
- }
627
- /**
628
- * Finishes the hash calculation and returns the hash as a WordArray.
629
- *
630
- * @param {string} messageUpdate - Additional message content to include in the hash.
631
- * @returns {WordArray} The finalised hash as a WordArray.
632
- */
633
- finalize(messageUpdate) {
634
- super.finalize(messageUpdate);
635
- const nBitsTotal = this._nDataBytes * 8;
636
- const nBitsLeft = this._data.sigBytes * 8;
637
- this._data.words[nBitsLeft >>> 5] |= 128 << 24 - nBitsLeft % 32;
638
- this._data.words[(nBitsLeft + 64 >>> 9 << 4) + 14] = Math.floor(
639
- nBitsTotal / 4294967296
640
- );
641
- this._data.words[(nBitsLeft + 64 >>> 9 << 4) + 15] = nBitsTotal;
642
- this._data.sigBytes = this._data.words.length * 4;
643
- this._process();
644
- return this._hash;
645
- }
646
- }
647
- function sha256base64(message) {
648
- return new SHA256().finalize(message).toString(Base64);
649
- }
650
-
651
- function hash(object, options = {}) {
652
- const hashed = typeof object === "string" ? object : objectHash(object, options);
653
- return sha256base64(hashed).slice(0, 10);
654
- }
655
-
656
- class CloudCache {
657
- memoryCache;
658
- cacheDir;
659
- enabled;
660
- constructor(config) {
661
- this.memoryCache = /* @__PURE__ */ new Map();
662
- this.enabled = config.enableCache !== false;
663
- this.cacheDir = config.cacheDir || path__default.join(process.cwd(), ".ccjk-cache");
664
- if (this.enabled) {
665
- this.ensureCacheDir();
666
- this.loadCacheFromDisk();
667
- }
668
- }
669
- /**
670
- * Ensure cache directory exists
671
- */
672
- ensureCacheDir() {
673
- try {
674
- if (!fs__default.existsSync(this.cacheDir)) {
675
- fs__default.mkdirSync(this.cacheDir, { recursive: true });
676
- consola.debug("Created cache directory:", this.cacheDir);
677
- }
678
- } catch (error) {
679
- consola.warn("Failed to create cache directory, disabling cache:", error);
680
- this.enabled = false;
681
- }
682
- }
683
- /**
684
- * Load cache from disk
685
- */
686
- loadCacheFromDisk() {
687
- try {
688
- const cacheFile = path__default.join(this.cacheDir, "cache.json");
689
- if (fs__default.existsSync(cacheFile)) {
690
- const data = fs__default.readFileSync(cacheFile, "utf-8");
691
- const entries = JSON.parse(data);
692
- const now = Date.now();
693
- for (const [key, entry] of Object.entries(entries)) {
694
- if (entry.expiresAt > now) {
695
- this.memoryCache.set(key, entry);
696
- }
697
- }
698
- consola.debug(`Loaded ${this.memoryCache.size} cache entries from disk`);
699
- }
700
- } catch (error) {
701
- consola.warn("Failed to load cache from disk:", error);
702
- }
703
- }
704
- /**
705
- * Save cache to disk
706
- */
707
- saveCacheToDisk() {
708
- try {
709
- const cacheFile = path__default.join(this.cacheDir, "cache.json");
710
- const entries = Object.fromEntries(this.memoryCache);
711
- fs__default.writeFileSync(cacheFile, JSON.stringify(entries, null, 2));
712
- } catch (error) {
713
- consola.warn("Failed to save cache to disk:", error);
714
- }
715
- }
716
- /**
717
- * Generate cache key from parameters
718
- */
719
- generateKey(prefix, params) {
720
- const hashValue = hash(params);
721
- return `${prefix}:${hashValue}`;
722
- }
723
- /**
724
- * Get cached value
725
- *
726
- * @param key - Cache key
727
- * @returns Cached value or undefined if not found/expired
728
- */
729
- get(key) {
730
- if (!this.enabled) {
731
- return void 0;
732
- }
733
- const entry = this.memoryCache.get(key);
734
- if (!entry) {
735
- return void 0;
736
- }
737
- if (Date.now() > entry.expiresAt) {
738
- this.memoryCache.delete(key);
739
- this.saveCacheToDisk();
740
- return void 0;
741
- }
742
- consola.debug(`Cache hit: ${key}`);
743
- return entry.data;
744
- }
745
- /**
746
- * Set cached value with TTL
747
- *
748
- * @param key - Cache key
749
- * @param value - Value to cache
750
- * @param ttlSeconds - Time to live in seconds
751
- */
752
- set(key, value, ttlSeconds) {
753
- if (!this.enabled) {
754
- return;
755
- }
756
- const entry = {
757
- data: value,
758
- expiresAt: Date.now() + ttlSeconds * 1e3,
759
- key
760
- };
761
- this.memoryCache.set(key, entry);
762
- this.saveCacheToDisk();
763
- consola.debug(`Cache set: ${key} (TTL: ${ttlSeconds}s)`);
764
- }
765
- /**
766
- * Delete cache entry
767
- *
768
- * @param key - Cache key
769
- */
770
- delete(key) {
771
- this.memoryCache.delete(key);
772
- this.saveCacheToDisk();
773
- consola.debug(`Cache deleted: ${key}`);
774
- }
775
- /**
776
- * Clear all cache entries
777
- */
778
- clear() {
779
- this.memoryCache.clear();
780
- this.saveCacheToDisk();
781
- consola.debug("Cache cleared");
782
- }
783
- /**
784
- * Clean expired entries
785
- */
786
- cleanExpired() {
787
- const now = Date.now();
788
- let cleaned = 0;
789
- for (const [key, entry] of this.memoryCache.entries()) {
790
- if (now > entry.expiresAt) {
791
- this.memoryCache.delete(key);
792
- cleaned++;
793
- }
794
- }
795
- if (cleaned > 0) {
796
- this.saveCacheToDisk();
797
- consola.debug(`Cleaned ${cleaned} expired cache entries`);
798
- }
799
- }
800
- /**
801
- * Get cache statistics
802
- */
803
- getStats() {
804
- return {
805
- size: this.memoryCache.size,
806
- keys: Array.from(this.memoryCache.keys())
807
- };
808
- }
809
- }
810
- class CachedCloudClient {
811
- client;
812
- cache;
813
- constructor(client, cache) {
814
- this.client = client;
815
- this.cache = cache;
816
- }
817
- /**
818
- * Analyze project with caching (7-day TTL)
819
- */
820
- async analyzeProject(request) {
821
- const cacheKey = this.cache.generateKey("analyze", request);
822
- const cached = this.cache.get(cacheKey);
823
- if (cached) {
824
- return cached;
825
- }
826
- const result = await this.client.analyzeProject(request);
827
- this.cache.set(cacheKey, result, 7 * 24 * 60 * 60);
828
- return result;
829
- }
830
- /**
831
- * Get template with caching (30-day TTL)
832
- */
833
- async getTemplate(id, language) {
834
- const cacheKey = this.cache.generateKey("template", { id, language });
835
- const cached = this.cache.get(cacheKey);
836
- if (cached) {
837
- return cached;
838
- }
839
- const result = await this.client.getTemplate(id, language);
840
- this.cache.set(cacheKey, result, 30 * 24 * 60 * 60);
841
- return result;
842
- }
843
- /**
844
- * Get batch templates with caching (30-day TTL)
845
- */
846
- async getBatchTemplates(request) {
847
- const cacheKey = this.cache.generateKey("batch", request);
848
- const cached = this.cache.get(cacheKey);
849
- if (cached) {
850
- return cached;
851
- }
852
- const result = await this.client.getBatchTemplates(request);
853
- this.cache.set(cacheKey, result, 30 * 24 * 60 * 60);
854
- return result;
855
- }
856
- /**
857
- * Report usage (no caching)
858
- */
859
- async reportUsage(report) {
860
- return this.client.reportUsage(report);
861
- }
862
- /**
863
- * Health check with caching (5-minute TTL)
864
- */
865
- async healthCheck() {
866
- const cacheKey = "health:check";
867
- const cached = this.cache.get(cacheKey);
868
- if (cached) {
869
- return cached;
870
- }
871
- const result = await this.client.healthCheck();
872
- this.cache.set(cacheKey, result, 5 * 60);
873
- return result;
874
- }
875
- /**
876
- * Clear cache
877
- */
878
- clearCache() {
879
- this.cache.clear();
880
- }
881
- /**
882
- * Clean expired cache entries
883
- */
884
- cleanCache() {
885
- this.cache.cleanExpired();
886
- }
887
- /**
888
- * Get cache statistics
889
- */
890
- getCacheStats() {
891
- return this.cache.getStats();
892
- }
893
- /**
894
- * Get underlying client
895
- */
896
- getClient() {
897
- return this.client;
898
- }
899
- }
900
-
901
- class CloudClientError extends Error {
902
- /** Error type */
903
- type;
904
- /** HTTP status code if applicable */
905
- statusCode;
906
- /** Original error */
907
- originalError;
908
- constructor(type, message, statusCode, originalError) {
909
- super(message);
910
- this.name = "CloudClientError";
911
- this.type = type;
912
- this.statusCode = statusCode;
913
- this.originalError = originalError;
914
- }
915
- /**
916
- * Create error from HTTP response
917
- */
918
- static fromResponse(statusCode, message) {
919
- let type;
920
- if (statusCode === 401)
921
- type = "AUTH_ERROR";
922
- else if (statusCode === 429)
923
- type = "RATE_LIMIT_ERROR";
924
- else if (statusCode >= 500)
925
- type = "SERVER_ERROR";
926
- else if (statusCode >= 400)
927
- type = "API_ERROR";
928
- else type = "UNKNOWN_ERROR";
929
- return new CloudClientError(type, message, statusCode);
930
- }
931
- /**
932
- * Create network error
933
- */
934
- static network(error) {
935
- return new CloudClientError(
936
- "NETWORK_ERROR",
937
- error instanceof Error ? error.message : "Network connection failed",
938
- void 0,
939
- error
940
- );
941
- }
942
- /**
943
- * Create timeout error
944
- */
945
- static timeout(timeout) {
946
- return new CloudClientError(
947
- "TIMEOUT_ERROR",
948
- `Request timeout after ${timeout}ms`
949
- );
950
- }
951
- /**
952
- * Create validation error
953
- */
954
- static validation(message) {
955
- return new CloudClientError("VALIDATION_ERROR", message);
956
- }
957
- }
958
-
959
- const __dirname = dirname(fileURLToPath(import.meta.url));
960
- let CCJK_VERSION$1 = "9.0.0";
961
- try {
962
- const packageJson = JSON.parse(readFileSync(join(__dirname, "../../package.json"), "utf-8"));
963
- CCJK_VERSION$1 = packageJson.version;
964
- } catch {
965
- }
966
- const API_PREFIX = "/api/v1";
967
- class CloudClient {
968
- fetch;
969
- config;
970
- constructor(config) {
971
- this.config = {
972
- timeout: 1e4,
973
- enableRetry: true,
974
- maxRetries: 3,
975
- enableTelemetry: true,
976
- ...config
977
- };
978
- this.fetch = ofetch.create({
979
- baseURL: this.config.baseURL,
980
- timeout: this.config.timeout,
981
- headers: {
982
- "User-Agent": `CCJK/${this.config.version || CCJK_VERSION$1}`,
983
- ...this.config.apiKey && { Authorization: `Bearer ${this.config.apiKey}` }
984
- },
985
- retry: this.config.enableRetry ? this.config.maxRetries : 0,
986
- retryDelay: (context) => this.calculateRetryDelay(context.options.retry || 0)
987
- });
988
- }
989
- /**
990
- * Calculate retry delay with exponential backoff
991
- */
992
- calculateRetryDelay(attempt) {
993
- const delays = [100, 200, 400, 800];
994
- return delays[Math.min(attempt, delays.length - 1)];
995
- }
996
- /**
997
- * Handle fetch errors and convert to CloudClientError
998
- */
999
- handleError(error, context) {
1000
- if (error instanceof CloudClientError) {
1001
- throw error;
1002
- }
1003
- if (error instanceof Error) {
1004
- const errorMessage = error.message || "";
1005
- if (errorMessage.includes("timeout") || errorMessage.includes("timed out")) {
1006
- throw CloudClientError.timeout(this.config.timeout || 1e4);
1007
- }
1008
- if (errorMessage.includes("ECONNREFUSED") || errorMessage.includes("ENOTFOUND")) {
1009
- throw CloudClientError.network(error);
1010
- }
1011
- const statusMatch = errorMessage.match(/(\d{3})\s+/);
1012
- const statusCode = statusMatch ? Number.parseInt(statusMatch[1]) : void 0;
1013
- let responseDetails = errorMessage;
1014
- try {
1015
- if (errorMessage.includes(":")) {
1016
- const parts = errorMessage.split(":");
1017
- if (parts.length > 1) {
1018
- responseDetails = parts.slice(1).join(":").trim();
1019
- }
1020
- }
1021
- } catch {
1022
- }
1023
- consola.warn(`Cloud API error in ${context}:`, {
1024
- statusCode,
1025
- message: responseDetails,
1026
- originalError: error
1027
- });
1028
- if (statusCode) {
1029
- throw CloudClientError.fromResponse(statusCode, responseDetails);
1030
- }
1031
- throw new CloudClientError(
1032
- "UNKNOWN_ERROR",
1033
- `Unexpected error during ${context}: ${responseDetails}`,
1034
- void 0,
1035
- error
1036
- );
1037
- }
1038
- consola.warn(`Cloud API error in ${context}:`, error);
1039
- throw new CloudClientError(
1040
- "UNKNOWN_ERROR",
1041
- `Unexpected error during ${context}`,
1042
- void 0,
1043
- error
1044
- );
1045
- }
1046
- /**
1047
- * Analyze project and get recommendations
1048
- *
1049
- * POST /api/v1/analysis/projects
1050
- *
1051
- * @param request - Project analysis request
1052
- * @returns Project analysis response with recommendations
1053
- */
1054
- async analyzeProject(request) {
1055
- try {
1056
- consola.debug("Analyzing project:", request.projectRoot);
1057
- const response = await this.fetch(`${API_PREFIX}/analysis/projects`, {
1058
- method: "POST",
1059
- body: request
1060
- });
1061
- consola.debug(`Received ${response.recommendations.length} recommendations`);
1062
- return response;
1063
- } catch (error) {
1064
- this.handleError(error, "project analysis");
1065
- }
1066
- }
1067
- /**
1068
- * Get a single template by ID
1069
- *
1070
- * GET /api/v1/templates/:id
1071
- *
1072
- * @param id - Template identifier
1073
- * @param language - Language for translations (optional)
1074
- * @returns Template response
1075
- */
1076
- async getTemplate(id, language) {
1077
- try {
1078
- consola.debug("Fetching template:", id);
1079
- const response = await this.fetch(`${API_PREFIX}/templates/${encodeURIComponent(id)}`, {
1080
- method: "GET",
1081
- params: language ? { language } : void 0
1082
- });
1083
- consola.debug(`Template ${id} fetched successfully`);
1084
- return response;
1085
- } catch (error) {
1086
- this.handleError(error, `template fetch: ${id}`);
1087
- }
1088
- }
1089
- /**
1090
- * Get multiple templates in batch
1091
- *
1092
- * POST /api/v1/templates/batch
1093
- *
1094
- * @param request - Batch template request
1095
- * @returns Batch template response
1096
- */
1097
- async getBatchTemplates(request) {
1098
- try {
1099
- consola.debug("Fetching batch templates:", request.ids.length);
1100
- const response = await this.fetch(`${API_PREFIX}/templates/batch`, {
1101
- method: "POST",
1102
- body: request
1103
- });
1104
- consola.debug(`Fetched ${Object.keys(response.templates).length} templates`);
1105
- return response;
1106
- } catch (error) {
1107
- this.handleError(error, "batch template fetch");
1108
- }
1109
- }
1110
- /**
1111
- * Report usage metrics
1112
- *
1113
- * POST /api/v1/telemetry/installation
1114
- *
1115
- * @param report - Usage report payload
1116
- * @returns Usage report response
1117
- */
1118
- async reportUsage(report) {
1119
- try {
1120
- consola.debug("Reporting usage:", report.metricType);
1121
- const response = await this.fetch(`${API_PREFIX}/telemetry/installation`, {
1122
- method: "POST",
1123
- body: report
1124
- });
1125
- consola.debug("Usage report accepted");
1126
- return response;
1127
- } catch (error) {
1128
- consola.warn("Failed to report usage:", error);
1129
- return {
1130
- success: false,
1131
- requestId: "",
1132
- message: error instanceof Error ? error.message : "Unknown error"
1133
- };
1134
- }
1135
- }
1136
- /**
1137
- * Check API health status
1138
- *
1139
- * GET /api/v1/health
1140
- *
1141
- * @returns Health check response
1142
- */
1143
- async healthCheck() {
1144
- try {
1145
- consola.debug("Checking API health");
1146
- const response = await this.fetch(`${API_PREFIX}/health`, {
1147
- method: "GET"
1148
- });
1149
- consola.debug(`API health: ${response.status}`);
1150
- return response;
1151
- } catch (error) {
1152
- this.handleError(error, "health check");
1153
- }
1154
- }
1155
- /**
1156
- * Update client configuration
1157
- *
1158
- * @param config - Partial configuration to update
1159
- */
1160
- updateConfig(config) {
1161
- this.config = { ...this.config, ...config };
1162
- if (config.baseURL || config.timeout || config.apiKey) {
1163
- this.fetch = ofetch.create({
1164
- baseURL: this.config.baseURL,
1165
- timeout: this.config.timeout,
1166
- headers: {
1167
- "User-Agent": `CCJK/${this.config.version || CCJK_VERSION$1}`,
1168
- ...this.config.apiKey && { Authorization: `Bearer ${this.config.apiKey}` }
1169
- },
1170
- retry: this.config.enableRetry ? this.config.maxRetries : 0,
1171
- retryDelay: (context) => this.calculateRetryDelay(context.options.retry || 0)
1172
- });
1173
- }
1174
- }
1175
- /**
1176
- * Get current configuration
1177
- */
1178
- getConfig() {
1179
- return { ...this.config };
1180
- }
1181
- }
1182
- function createCloudClient(config) {
1183
- return new CloudClient({
1184
- baseURL: "https://api.claudehome.cn",
1185
- timeout: 1e4,
1186
- version: CCJK_VERSION$1,
1187
- enableCache: true,
1188
- enableRetry: true,
1189
- maxRetries: 3,
1190
- enableTelemetry: true,
1191
- ...config
1192
- });
1193
- }
1194
-
1195
- const DEFAULT_RETRY_CONFIG = {
1196
- maxAttempts: 3,
1197
- initialDelay: 100,
1198
- multiplier: 2,
1199
- maxDelay: 800,
1200
- retryableStatusCodes: [500, 502, 503, 504, 408, 429]
1201
- };
1202
- async function withRetry(fn, config = {}) {
1203
- const retryConfig = { ...DEFAULT_RETRY_CONFIG, ...config };
1204
- let lastError;
1205
- for (let attempt = 0; attempt < retryConfig.maxAttempts; attempt++) {
1206
- try {
1207
- return await fn();
1208
- } catch (error) {
1209
- lastError = error;
1210
- if (!shouldRetry(error, retryConfig, attempt)) {
1211
- throw error;
1212
- }
1213
- const delay = Math.min(
1214
- retryConfig.initialDelay * retryConfig.multiplier ** attempt,
1215
- retryConfig.maxDelay
1216
- );
1217
- consola.warn(
1218
- `Request failed (attempt ${attempt + 1}/${retryConfig.maxAttempts}), retrying in ${delay}ms:`,
1219
- error instanceof Error ? error.message : error
1220
- );
1221
- await sleep(delay);
1222
- }
1223
- }
1224
- throw lastError;
1225
- }
1226
- function shouldRetry(error, config, attempt) {
1227
- if (attempt >= config.maxAttempts - 1) {
1228
- return false;
1229
- }
1230
- if (error instanceof CloudClientError) {
1231
- if (error.type === "VALIDATION_ERROR" || error.type === "AUTH_ERROR") {
1232
- return false;
1233
- }
1234
- if (error.type === "NETWORK_ERROR" || error.type === "TIMEOUT_ERROR") {
1235
- return true;
1236
- }
1237
- if (error.statusCode && config.retryableStatusCodes.includes(error.statusCode)) {
1238
- return true;
1239
- }
1240
- }
1241
- if (error instanceof Error) {
1242
- const message = error.message.toLowerCase();
1243
- if (message.includes("network") || message.includes("connection") || message.includes("timeout") || message.includes("econnrefused") || message.includes("enotfound")) {
1244
- return true;
1245
- }
1246
- }
1247
- return false;
1248
- }
1249
- function sleep(ms) {
1250
- return new Promise((resolve) => setTimeout(resolve, ms));
1251
- }
1252
- class RetryableCloudClient {
1253
- client;
1254
- retryConfig;
1255
- constructor(client, retryConfig = {}) {
1256
- this.client = client;
1257
- this.retryConfig = retryConfig;
1258
- }
1259
- /**
1260
- * Analyze project with retry
1261
- */
1262
- analyzeProject = async (request) => {
1263
- return withRetry(
1264
- () => this.client.analyzeProject(request),
1265
- this.retryConfig
1266
- );
1267
- };
1268
- /**
1269
- * Get template with retry
1270
- */
1271
- getTemplate = async (id, language) => {
1272
- return withRetry(
1273
- () => this.client.getTemplate(id, language),
1274
- this.retryConfig
1275
- );
1276
- };
1277
- /**
1278
- * Get batch templates with retry
1279
- */
1280
- getBatchTemplates = async (request) => {
1281
- return withRetry(
1282
- () => this.client.getBatchTemplates(request),
1283
- this.retryConfig
1284
- );
1285
- };
1286
- /**
1287
- * Report usage (no retry)
1288
- */
1289
- reportUsage = async (report) => {
1290
- return this.client.reportUsage(report);
1291
- };
1292
- /**
1293
- * Health check (no retry)
1294
- */
1295
- healthCheck = async () => {
1296
- return withRetry(
1297
- () => this.client.healthCheck(),
1298
- this.retryConfig
1299
- );
1300
- };
1301
- /**
1302
- * Get underlying client
1303
- */
1304
- getClient() {
1305
- return this.client;
1306
- }
1307
- }
1308
-
1309
- const DEFAULT_TELEMETRY_CONFIG = {
1310
- enabled: true,
1311
- batchSize: 10,
1312
- flushInterval: 3e4
1313
- // 30 seconds
1314
- };
1315
- class TelemetryReporter {
1316
- client;
1317
- config;
1318
- events = [];
1319
- flushTimer;
1320
- userId;
1321
- constructor(client, config = {}) {
1322
- this.client = client;
1323
- this.config = { ...DEFAULT_TELEMETRY_CONFIG, ...config };
1324
- this.userId = this.config.userId || this.generateUserId();
1325
- if (this.config.enabled) {
1326
- this.startFlushTimer();
1327
- }
1328
- }
1329
- /**
1330
- * Generate or load anonymous user ID
1331
- */
1332
- generateUserId() {
1333
- const envUserId = process.env.CCJK_TELEMETRY_USER_ID;
1334
- if (envUserId) {
1335
- return envUserId;
1336
- }
1337
- return randomUUID();
1338
- }
1339
- /**
1340
- * Start periodic flush timer
1341
- */
1342
- startFlushTimer() {
1343
- this.flushTimer = setInterval(() => {
1344
- if (this.events.length > 0) {
1345
- this.flush().catch((error) => {
1346
- consola.warn("Failed to flush telemetry events:", error);
1347
- });
1348
- }
1349
- }, this.config.flushInterval);
1350
- this.flushTimer.unref();
1351
- }
1352
- /**
1353
- * Stop flush timer
1354
- */
1355
- stopFlushTimer() {
1356
- if (this.flushTimer) {
1357
- clearInterval(this.flushTimer);
1358
- this.flushTimer = void 0;
1359
- }
1360
- }
1361
- /**
1362
- * Check if telemetry is enabled
1363
- */
1364
- isEnabled() {
1365
- if (process.env.CCJK_TELEMETRY === "false") {
1366
- return false;
1367
- }
1368
- return this.config.enabled;
1369
- }
1370
- /**
1371
- * Track an event
1372
- *
1373
- * @param type - Event type
1374
- * @param data - Additional event data
1375
- */
1376
- track(type, data) {
1377
- if (!this.isEnabled()) {
1378
- return;
1379
- }
1380
- const event = {
1381
- type,
1382
- data: {
1383
- ...data,
1384
- userId: this.userId
1385
- },
1386
- timestamp: (/* @__PURE__ */ new Date()).toISOString()
1387
- };
1388
- this.events.push(event);
1389
- consola.debug(`Telemetry event tracked: ${type}`, data);
1390
- if (this.events.length >= this.config.batchSize) {
1391
- this.flush().catch((error) => {
1392
- consola.warn("Failed to flush telemetry events:", error);
1393
- });
1394
- }
1395
- }
1396
- /**
1397
- * Track template download
1398
- */
1399
- trackTemplateDownload(templateId, templateType) {
1400
- this.track("template_download", {
1401
- templateId,
1402
- templateType,
1403
- timestamp: Date.now()
1404
- });
1405
- }
1406
- /**
1407
- * Track recommendation shown
1408
- */
1409
- trackRecommendationShown(recommendationId, category) {
1410
- this.track("recommendation_shown", {
1411
- recommendationId,
1412
- category,
1413
- timestamp: Date.now()
1414
- });
1415
- }
1416
- /**
1417
- * Track recommendation accepted
1418
- */
1419
- trackRecommendationAccepted(recommendationId, category) {
1420
- this.track("recommendation_accepted", {
1421
- recommendationId,
1422
- category,
1423
- timestamp: Date.now()
1424
- });
1425
- }
1426
- /**
1427
- * Track analysis completed
1428
- */
1429
- trackAnalysisCompleted(projectType, frameworks) {
1430
- this.track("analysis_completed", {
1431
- projectType,
1432
- frameworks,
1433
- recommendationCount: frameworks?.length || 0,
1434
- timestamp: Date.now()
1435
- });
1436
- }
1437
- /**
1438
- * Track error occurred
1439
- */
1440
- trackError(errorType, errorMessage, context) {
1441
- this.track("error_occurred", {
1442
- errorType,
1443
- errorMessage,
1444
- context,
1445
- timestamp: Date.now()
1446
- });
1447
- }
1448
- /**
1449
- * Flush pending events to server
1450
- */
1451
- async flush() {
1452
- if (!this.isEnabled() || this.events.length === 0) {
1453
- return;
1454
- }
1455
- const eventsToSend = [...this.events];
1456
- this.events = [];
1457
- try {
1458
- consola.debug(`Flushing ${eventsToSend.length} telemetry events`);
1459
- const batchSize = 100;
1460
- for (let i = 0; i < eventsToSend.length; i += batchSize) {
1461
- const batch = eventsToSend.slice(i, i + batchSize);
1462
- await this.sendBatch(batch);
1463
- }
1464
- consola.debug("Telemetry events flushed successfully");
1465
- } catch (error) {
1466
- this.events.unshift(...eventsToSend);
1467
- throw error;
1468
- }
1469
- }
1470
- /**
1471
- * Send a batch of events
1472
- */
1473
- async sendBatch(events) {
1474
- const report = {
1475
- reportId: randomUUID(),
1476
- metricType: "analysis_completed",
1477
- // Batch metric type
1478
- timestamp: (/* @__PURE__ */ new Date()).toISOString(),
1479
- ccjkVersion: process.env.npm_package_version || "8.0.0",
1480
- nodeVersion: process.version,
1481
- platform: process.platform,
1482
- data: {
1483
- events,
1484
- batchSize: events.length,
1485
- userId: this.userId
1486
- }
1487
- };
1488
- await this.client.reportUsage(report);
1489
- }
1490
- /**
1491
- * Stop telemetry and flush remaining events
1492
- */
1493
- async stop() {
1494
- this.stopFlushTimer();
1495
- if (this.events.length > 0) {
1496
- await this.flush();
1497
- }
1498
- }
1499
- /**
1500
- * Get current queue size
1501
- */
1502
- getQueueSize() {
1503
- return this.events.length;
1504
- }
1505
- /**
1506
- * Get telemetry status
1507
- */
1508
- getStatus() {
1509
- return {
1510
- enabled: this.isEnabled(),
1511
- queueSize: this.getQueueSize(),
1512
- userId: this.userId
1513
- };
1514
- }
1515
- }
1516
- let globalTelemetry;
1517
- function initializeTelemetry(client, config) {
1518
- if (globalTelemetry) {
1519
- globalTelemetry.stop().catch(() => {
1520
- });
1521
- }
1522
- globalTelemetry = new TelemetryReporter(client, config);
1523
- return globalTelemetry;
1524
- }
1525
-
1526
- class FallbackCloudClient {
1527
- client;
1528
- fallbackEnabled;
1529
- constructor(client, fallbackEnabled = true) {
1530
- this.client = client;
1531
- this.fallbackEnabled = fallbackEnabled;
1532
- }
1533
- /**
1534
- * Analyze project with fallback
1535
- */
1536
- async analyzeProject(request) {
1537
- try {
1538
- return await this.client.analyzeProject(request);
1539
- } catch (error) {
1540
- if (this.fallbackEnabled) {
1541
- consola.warn("Cloud API unavailable, using local recommendations");
1542
- return this.getLocalRecommendations(request);
1543
- }
1544
- throw error;
1545
- }
1546
- }
1547
- /**
1548
- * Get template with fallback
1549
- */
1550
- async getTemplate(id, language) {
1551
- try {
1552
- return await this.client.getTemplate(id, language);
1553
- } catch (error) {
1554
- if (this.fallbackEnabled) {
1555
- consola.warn("Cloud API unavailable, using local template");
1556
- return this.getLocalTemplate(id, language);
1557
- }
1558
- throw error;
1559
- }
1560
- }
1561
- /**
1562
- * Get batch templates with fallback
1563
- */
1564
- async getBatchTemplates(request) {
1565
- try {
1566
- return await this.client.getBatchTemplates(request);
1567
- } catch (error) {
1568
- if (this.fallbackEnabled) {
1569
- consola.warn("Cloud API unavailable, using local templates");
1570
- return this.getLocalBatchTemplates(request);
1571
- }
1572
- throw error;
1573
- }
1574
- }
1575
- /**
1576
- * Report usage (no fallback)
1577
- */
1578
- async reportUsage(report) {
1579
- return this.client.reportUsage(report);
1580
- }
1581
- /**
1582
- * Health check (no fallback)
1583
- */
1584
- async healthCheck() {
1585
- return this.client.healthCheck();
1586
- }
1587
- /**
1588
- * Get local fallback recommendations
1589
- */
1590
- getLocalRecommendations(request) {
1591
- const recommendations = [];
1592
- if (request.devDependencies?.typescript || request.devDependencies?.tslib) {
1593
- recommendations.push({
1594
- id: "typescript-workflow",
1595
- name: { "en": "TypeScript Workflow", "zh-CN": "TypeScript \u5DE5\u4F5C\u6D41" },
1596
- description: { "en": "Enhanced TypeScript support", "zh-CN": "\u589E\u5F3A\u7684 TypeScript \u652F\u6301" },
1597
- category: "skill",
1598
- relevanceScore: 0.9,
1599
- installCommand: "ccjk config switch typescript",
1600
- tags: ["typescript", "type-checking"]
1601
- });
1602
- }
1603
- if (request.dependencies?.react || request.dependencies?.["react-dom"]) {
1604
- recommendations.push({
1605
- id: "react-workflow",
1606
- name: { "en": "React Workflow", "zh-CN": "React \u5DE5\u4F5C\u6D41" },
1607
- description: { "en": "React development tools", "zh-CN": "React \u5F00\u53D1\u5DE5\u5177" },
1608
- category: "skill",
1609
- relevanceScore: 0.95,
1610
- installCommand: "ccjk config switch react",
1611
- tags: ["react", "jsx", "frontend"]
1612
- });
1613
- }
1614
- if (request.dependencies?.express || request.dependencies?.fastify) {
1615
- recommendations.push({
1616
- id: "nodejs-workflow",
1617
- name: { "en": "Node.js Workflow", "zh-CN": "Node.js \u5DE5\u4F5C\u6D41" },
1618
- description: { "en": "Node.js development tools", "zh-CN": "Node.js \u5F00\u53D1\u5DE5\u5177" },
1619
- category: "skill",
1620
- relevanceScore: 0.9,
1621
- installCommand: "ccjk config switch nodejs",
1622
- tags: ["nodejs", "backend", "server"]
1623
- });
1624
- }
1625
- if (request.gitRemote) {
1626
- recommendations.push({
1627
- id: "git-workflow",
1628
- name: { "en": "Git Workflow", "zh-CN": "Git \u5DE5\u4F5C\u6D41" },
1629
- description: { "en": "Git best practices", "zh-CN": "Git \u6700\u4F73\u5B9E\u8DF5" },
1630
- category: "skill",
1631
- relevanceScore: 0.8,
1632
- installCommand: "ccjk config switch git",
1633
- tags: ["git", "vcs"]
1634
- });
1635
- }
1636
- return {
1637
- requestId: "local-fallback",
1638
- recommendations,
1639
- projectType: this.detectProjectType(request),
1640
- frameworks: this.detectFrameworks(request)
1641
- };
1642
- }
1643
- /**
1644
- * Get local fallback template
1645
- */
1646
- getLocalTemplate(id, _language) {
1647
- const templates = {
1648
- "basic-workflow": {
1649
- id: "basic-workflow",
1650
- type: "workflow",
1651
- name: { "en": "Basic Workflow", "zh-CN": "\u57FA\u7840\u5DE5\u4F5C\u6D41" },
1652
- description: { "en": "Basic development workflow", "zh-CN": "\u57FA\u7840\u5F00\u53D1\u5DE5\u4F5C\u6D41" },
1653
- content: JSON.stringify({
1654
- name: "basic",
1655
- steps: ["init", "test", "build", "deploy"]
1656
- }, null, 2),
1657
- version: "1.0.0",
1658
- createdAt: (/* @__PURE__ */ new Date()).toISOString(),
1659
- updatedAt: (/* @__PURE__ */ new Date()).toISOString()
1660
- }
1661
- };
1662
- return templates[id] || {
1663
- id,
1664
- type: "workflow",
1665
- name: { "en": "Unknown Template", "zh-CN": "\u672A\u77E5\u6A21\u677F" },
1666
- description: { "en": "Template not found", "zh-CN": "\u6A21\u677F\u672A\u627E\u5230" },
1667
- content: "{}",
1668
- version: "1.0.0",
1669
- createdAt: (/* @__PURE__ */ new Date()).toISOString(),
1670
- updatedAt: (/* @__PURE__ */ new Date()).toISOString()
1671
- };
1672
- }
1673
- /**
1674
- * Get local fallback batch templates
1675
- */
1676
- getLocalBatchTemplates(request) {
1677
- const templates = {};
1678
- const notFound = [];
1679
- for (const id of request.ids) {
1680
- try {
1681
- templates[id] = this.getLocalTemplate(id, request.language);
1682
- } catch {
1683
- notFound.push(id);
1684
- }
1685
- }
1686
- return {
1687
- requestId: "local-fallback",
1688
- templates,
1689
- notFound
1690
- };
1691
- }
1692
- /**
1693
- * Detect project type
1694
- */
1695
- detectProjectType(request) {
1696
- if (request.dependencies?.react)
1697
- return "react";
1698
- if (request.dependencies?.vue)
1699
- return "vue";
1700
- if (request.dependencies?.express)
1701
- return "nodejs";
1702
- if (request.devDependencies?.typescript)
1703
- return "typescript";
1704
- return "generic";
1705
- }
1706
- /**
1707
- * Detect frameworks
1708
- */
1709
- detectFrameworks(request) {
1710
- const frameworks = [];
1711
- const deps = { ...request.dependencies, ...request.devDependencies };
1712
- if (deps.react)
1713
- frameworks.push("react");
1714
- if (deps.vue)
1715
- frameworks.push("vue");
1716
- if (deps.angular)
1717
- frameworks.push("angular");
1718
- if (deps.svelte)
1719
- frameworks.push("svelte");
1720
- if (deps.express)
1721
- frameworks.push("express");
1722
- if (deps.fastify)
1723
- frameworks.push("fastify");
1724
- if (deps.typescript)
1725
- frameworks.push("typescript");
1726
- if (deps.webpack)
1727
- frameworks.push("webpack");
1728
- if (deps.vite)
1729
- frameworks.push("vite");
1730
- return frameworks;
1731
- }
1732
- }
1733
- function createCompleteCloudClient(config) {
1734
- const baseClient = createCloudClient(config);
1735
- const retryClient = new RetryableCloudClient(baseClient);
1736
- const cache = new CloudCache(baseClient.getConfig());
1737
- const cachedClient = new CachedCloudClient(retryClient.getClient(), cache);
1738
- const fallbackClient = new FallbackCloudClient(cachedClient.getClient());
1739
- initializeTelemetry(baseClient);
1740
- return fallbackClient;
1741
- }
1742
-
1743
51
  const packageJson = JSON.parse(readFileSync(join(process.cwd(), "package.json"), "utf-8"));
1744
52
  const CCJK_VERSION = packageJson.version;
1745
53
  class CloudSetupOrchestrator {
1746
- cloudClient;
54
+ gateway;
1747
55
  logger = consola.withTag("cloud-setup");
1748
56
  startTime = Date.now();
1749
57
  constructor(options = {}) {
1750
- this.cloudClient = createCompleteCloudClient({
1751
- baseURL: options.cloudEndpoint || "https://api.ccjk.dev",
1752
- enableCache: options.cacheStrategy !== "disabled",
1753
- version: CCJK_VERSION
1754
- });
58
+ this.gateway = createDefaultGateway();
1755
59
  }
1756
60
  /**
1757
61
  * Execute cloud-powered setup
@@ -1779,7 +83,8 @@ class CloudSetupOrchestrator {
1779
83
  const templates = await this.downloadTemplates(recommendations, options);
1780
84
  const result = await this.executeInstallation(recommendations, templates, options);
1781
85
  if (options.submitTelemetry !== false) {
1782
- await this.uploadTelemetry(result);
86
+ this.uploadTelemetry(result).catch(() => {
87
+ });
1783
88
  }
1784
89
  if (options.generateReport) {
1785
90
  result.reportPath = await this.generateReport(result, recommendations, options);
@@ -1871,16 +176,29 @@ class CloudSetupOrchestrator {
1871
176
  }
1872
177
  }
1873
178
  try {
1874
- const response = await this.cloudClient.analyzeProject(request);
179
+ const response = await this.gateway.request(
180
+ "analysis.projects",
181
+ {
182
+ method: "POST",
183
+ body: request,
184
+ timeout: 1e4
185
+ // 10s timeout for cloud analysis
186
+ }
187
+ );
188
+ if (!response.success || !response.data) {
189
+ this.logger.warn("Cloud API returned error:", response.error);
190
+ return this.getLocalRecommendations(analysis);
191
+ }
192
+ const data = response.data;
1875
193
  const fingerprint = this.generateProjectFingerprint(analysis);
1876
194
  const recommendations = {
1877
- skills: response.recommendations.filter((r) => r.category === "skill"),
1878
- mcpServices: response.recommendations.filter((r) => r.category === "mcp"),
1879
- agents: response.recommendations.filter((r) => r.category === "agent"),
1880
- hooks: response.recommendations.filter((r) => r.category === "hook"),
1881
- confidence: this.calculateConfidence(response.recommendations),
195
+ skills: data.recommendations.filter((r) => r.category === "skill"),
196
+ mcpServices: data.recommendations.filter((r) => r.category === "mcp"),
197
+ agents: data.recommendations.filter((r) => r.category === "agent"),
198
+ hooks: data.recommendations.filter((r) => r.category === "hook"),
199
+ confidence: this.calculateConfidence(data.recommendations),
1882
200
  fingerprint,
1883
- insights: this.extractInsights(response)
201
+ insights: this.extractInsights(data)
1884
202
  };
1885
203
  return recommendations;
1886
204
  } catch (_error) {
@@ -2164,14 +482,26 @@ class CloudSetupOrchestrator {
2164
482
  ];
2165
483
  const templateIds = allRecommendations.map((r) => r.id);
2166
484
  try {
2167
- const response = await this.cloudClient.getBatchTemplates({
2168
- ids: templateIds,
2169
- language: options.lang
2170
- });
485
+ const response = await this.gateway.request(
486
+ "templates.batch",
487
+ {
488
+ method: "POST",
489
+ body: {
490
+ ids: templateIds,
491
+ language: options.lang
492
+ },
493
+ timeout: 15e3
494
+ // 15s timeout for template download
495
+ }
496
+ );
497
+ if (!response.success || !response.data) {
498
+ throw new Error(response.error || "Template download failed");
499
+ }
500
+ const templates = response.data;
2171
501
  if (options.interactive !== false) {
2172
- console.log(` ${a.green("\u2713")} ${i18n.t("cloud-setup:templatesDownloaded", { count: Object.keys(response.templates).length })}`);
502
+ console.log(` ${a.green("\u2713")} ${i18n.t("cloud-setup:templatesDownloaded", { count: Object.keys(templates.templates).length })}`);
2173
503
  }
2174
- return response;
504
+ return templates;
2175
505
  } catch (error) {
2176
506
  this.logger.error("Failed to download templates:", error);
2177
507
  throw error;
@@ -2344,49 +674,84 @@ class CloudSetupOrchestrator {
2344
674
  }
2345
675
  }
2346
676
  /**
2347
- * Upload telemetry
677
+ * Upload telemetry (non-blocking with retry budget)
678
+ * Fire-and-forget: does not block setup completion
2348
679
  */
2349
680
  async uploadTelemetry(result) {
2350
- try {
2351
- const telemetry = {
2352
- requestId: result.requestId,
2353
- installation: {
2354
- timestamp: Date.now(),
2355
- duration: result.duration,
2356
- selectedResources: [
2357
- ...result.installed.skills.map((id) => ({ id, type: "skill", version: "1.0.0" })),
2358
- ...result.installed.mcpServices.map((id) => ({ id, type: "mcp", version: "1.0.0" })),
2359
- ...result.installed.agents.map((id) => ({ id, type: "agent", version: "1.0.0" })),
2360
- ...result.installed.hooks.map((id) => ({ id, type: "hook", version: "1.0.0" }))
2361
- ],
2362
- skippedResources: [
2363
- ...result.skipped.skills,
2364
- ...result.skipped.mcpServices,
2365
- ...result.skipped.agents,
2366
- ...result.skipped.hooks
2367
- ],
2368
- failedResources: [
2369
- ...result.failed.skills,
2370
- ...result.failed.mcpServices,
2371
- ...result.failed.agents,
2372
- ...result.failed.hooks
2373
- ]
2374
- },
2375
- clientInfo: {
2376
- ccjkVersion: CCJK_VERSION,
2377
- os: process.platform,
2378
- nodeVersion: process.version
2379
- },
2380
- performance: {
2381
- networkLatency: 0,
2382
- cacheHit: false,
2383
- retryCount: 0
681
+ const telemetry = {
682
+ requestId: result.requestId,
683
+ installation: {
684
+ timestamp: Date.now(),
685
+ duration: result.duration,
686
+ selectedResources: [
687
+ ...result.installed.skills.map((id) => ({ id, type: "skill", version: "1.0.0" })),
688
+ ...result.installed.mcpServices.map((id) => ({ id, type: "mcp", version: "1.0.0" })),
689
+ ...result.installed.agents.map((id) => ({ id, type: "agent", version: "1.0.0" })),
690
+ ...result.installed.hooks.map((id) => ({ id, type: "hook", version: "1.0.0" }))
691
+ ],
692
+ skippedResources: [
693
+ ...result.skipped.skills,
694
+ ...result.skipped.mcpServices,
695
+ ...result.skipped.agents,
696
+ ...result.skipped.hooks
697
+ ],
698
+ failedResources: [
699
+ ...result.failed.skills,
700
+ ...result.failed.mcpServices,
701
+ ...result.failed.agents,
702
+ ...result.failed.hooks
703
+ ]
704
+ },
705
+ clientInfo: {
706
+ ccjkVersion: CCJK_VERSION,
707
+ os: process.platform,
708
+ nodeVersion: process.version
709
+ },
710
+ performance: {
711
+ networkLatency: 0,
712
+ cacheHit: false,
713
+ retryCount: 0
714
+ }
715
+ };
716
+ this.sendTelemetryWithRetry(telemetry, 3, 5e3).catch((error) => {
717
+ this.logger.debug("Telemetry upload failed after retries (non-blocking):", error);
718
+ });
719
+ }
720
+ /**
721
+ * Send telemetry with retry budget
722
+ * Private helper for non-blocking telemetry submission
723
+ */
724
+ async sendTelemetryWithRetry(telemetry, maxAttempts, timeout) {
725
+ for (let attempt = 1; attempt <= maxAttempts; attempt++) {
726
+ try {
727
+ const timeoutPromise = new Promise((_, reject) => {
728
+ setTimeout(() => reject(new Error("Telemetry timeout")), timeout);
729
+ });
730
+ const response = await Promise.race([
731
+ this.gateway.request("telemetry.installation", {
732
+ method: "POST",
733
+ body: telemetry,
734
+ timeout
735
+ }),
736
+ timeoutPromise
737
+ ]);
738
+ if (response.success) {
739
+ this.logger.debug(`Telemetry uploaded successfully (attempt ${attempt}/${maxAttempts})`);
740
+ return;
2384
741
  }
2385
- };
2386
- await this.cloudClient.reportUsage(telemetry);
2387
- this.logger.info("Telemetry uploaded successfully");
2388
- } catch (error) {
2389
- this.logger.warn("Failed to upload telemetry:", error);
742
+ throw new Error(response.error || "Unknown telemetry error");
743
+ } catch (error) {
744
+ this.logger.debug(
745
+ `Telemetry attempt ${attempt}/${maxAttempts} failed:`,
746
+ error instanceof Error ? error.message : error
747
+ );
748
+ if (attempt === maxAttempts) {
749
+ this.logger.debug("Telemetry failed after all retry attempts - giving up silently");
750
+ return;
751
+ }
752
+ const delay = 100 * 2 ** (attempt - 1);
753
+ await new Promise((resolve) => setTimeout(resolve, delay));
754
+ }
2390
755
  }
2391
756
  }
2392
757
  /**