@huoye/app-ship 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js ADDED
@@ -0,0 +1,4118 @@
1
+ var __require = /* @__PURE__ */ ((x) => typeof require !== "undefined" ? require : typeof Proxy !== "undefined" ? new Proxy(x, {
2
+ get: (a, b) => (typeof require !== "undefined" ? require : a)[b]
3
+ }) : x)(function(x) {
4
+ if (typeof require !== "undefined") return require.apply(this, arguments);
5
+ throw Error('Dynamic require of "' + x + '" is not supported');
6
+ });
7
+
8
+ // src/utils/logger.ts
9
+ import chalk from "chalk";
10
+ var ConsoleLogger = class {
11
+ info(message) {
12
+ console.log(chalk.blue("\u2139\uFE0F " + message));
13
+ }
14
+ success(message) {
15
+ console.log(chalk.green("\u2705 " + message));
16
+ }
17
+ warn(message) {
18
+ console.log(chalk.yellow("\u26A0\uFE0F " + message));
19
+ }
20
+ error(message) {
21
+ console.log(chalk.red("\u274C " + message));
22
+ }
23
+ title(message) {
24
+ console.log(chalk.bold.cyan("\n" + message + "\n"));
25
+ }
26
+ newLine() {
27
+ console.log("");
28
+ }
29
+ };
30
+ var logger = new ConsoleLogger();
31
+
32
+ // src/validators/env_validator.ts
33
+ var EnvValidator = class {
34
+ /**
35
+ * 验证环境变量
36
+ * @param requiredVars 必需的环境变量列表
37
+ */
38
+ static validate(requiredVars) {
39
+ const missing = requiredVars.filter((v) => !process.env[v]);
40
+ if (missing.length > 0) {
41
+ logger.error(`Missing environment variables: ${missing.join(", ")}`);
42
+ return false;
43
+ }
44
+ return true;
45
+ }
46
+ };
47
+
48
+ // src/validators/config_validator.ts
49
+ import fs from "fs-extra";
50
+ import yaml from "js-yaml";
51
+ var ConfigValidator = class {
52
+ /**
53
+ * 加载并验证配置文件
54
+ * @param filePath 配置文件路径
55
+ */
56
+ static loadAndValidate(filePath) {
57
+ if (!fs.existsSync(filePath)) {
58
+ logger.error(`Config file not found: ${filePath}`);
59
+ return null;
60
+ }
61
+ let content = fs.readFileSync(filePath, "utf8");
62
+ const envRegex = /\$\{([a-zA-Z_][a-zA-Z0-9_]*)\}/g;
63
+ const matches = [...content.matchAll(envRegex)];
64
+ const requiredEnvs = Array.from(new Set(matches.map((m) => m[1])));
65
+ if (!EnvValidator.validate(requiredEnvs)) {
66
+ return null;
67
+ }
68
+ content = content.replace(envRegex, (_, varName) => process.env[varName] || "");
69
+ try {
70
+ const config = yaml.load(content);
71
+ if (!this.validateSchema(config)) {
72
+ return null;
73
+ }
74
+ return config;
75
+ } catch (e) {
76
+ logger.error(`Failed to parse YAML: ${e.message}`);
77
+ return null;
78
+ }
79
+ }
80
+ /**
81
+ * 验证配置 Schema
82
+ * @param config 配置对象
83
+ */
84
+ static validateSchema(config) {
85
+ if (config.publish?.app_store?.enable) {
86
+ const auth = config.publish.app_store.auth;
87
+ if (!auth?.apiKeyId || !auth?.apiIssuerId) {
88
+ logger.error("App Store enabled but missing auth info (apiKeyId, apiIssuerId)");
89
+ return false;
90
+ }
91
+ }
92
+ if (config.publish?.huawei?.enable) {
93
+ const auth = config.publish.huawei.auth;
94
+ if (!auth?.clientId || !auth?.clientSecret) {
95
+ logger.error("Huawei enabled but missing auth info (clientId, clientSecret)");
96
+ return false;
97
+ }
98
+ }
99
+ if (config.publish?.xiaomi?.enable) {
100
+ const auth = config.publish.xiaomi.auth;
101
+ if (!auth?.userName || !auth?.privateKey) {
102
+ logger.error("Xiaomi enabled but missing auth info (userName, privateKey)");
103
+ return false;
104
+ }
105
+ }
106
+ if (config.publish?.oppo?.enable) {
107
+ const auth = config.publish.oppo.auth;
108
+ if (!auth?.clientId || !auth?.clientSecret) {
109
+ logger.error("OPPO enabled but missing auth info (clientId, clientSecret)");
110
+ return false;
111
+ }
112
+ }
113
+ if (config.publish?.vivo?.enable) {
114
+ const auth = config.publish.vivo.auth;
115
+ if (!auth?.accessKey || !auth?.accessSecret) {
116
+ logger.error("vivo enabled but missing auth info (accessKey, accessSecret)");
117
+ return false;
118
+ }
119
+ }
120
+ if (config.publish?.tencent?.enable) {
121
+ const auth = config.publish.tencent.auth;
122
+ if (!auth?.userId || !auth?.appId || !auth?.accessSecret) {
123
+ logger.error("Tencent enabled but missing auth info (userId, appId, accessSecret)");
124
+ return false;
125
+ }
126
+ }
127
+ if (config.publish?.harmony?.enable) {
128
+ const auth = config.publish.harmony.auth;
129
+ if (!auth?.clientId || !auth?.clientSecret) {
130
+ logger.error("Harmony enabled but missing auth info (clientId, clientSecret)");
131
+ return false;
132
+ }
133
+ }
134
+ return true;
135
+ }
136
+ };
137
+
138
+ // src/adapters/pgyer_uploader.ts
139
+ import fs4 from "fs-extra";
140
+ import axios from "axios";
141
+ import FormData from "form-data";
142
+
143
+ // src/utils/retry-strategy.ts
144
+ var ErrorCategory = /* @__PURE__ */ ((ErrorCategory2) => {
145
+ ErrorCategory2["NETWORK_ERROR"] = "NETWORK_ERROR";
146
+ ErrorCategory2["TEMPORARY_ERROR"] = "TEMPORARY_ERROR";
147
+ ErrorCategory2["SERVER_ERROR"] = "SERVER_ERROR";
148
+ ErrorCategory2["AUTH_ERROR"] = "AUTH_ERROR";
149
+ ErrorCategory2["CLIENT_ERROR"] = "CLIENT_ERROR";
150
+ ErrorCategory2["UNKNOWN_ERROR"] = "UNKNOWN_ERROR";
151
+ return ErrorCategory2;
152
+ })(ErrorCategory || {});
153
+ var RetryStrategy = class {
154
+ config;
155
+ constructor(config = {}) {
156
+ this.config = {
157
+ maxRetries: config.maxRetries ?? 3,
158
+ initialDelayMs: config.initialDelayMs ?? 1e3,
159
+ backoffMultiplier: config.backoffMultiplier ?? 2,
160
+ maxDelayMs: config.maxDelayMs ?? 3e4
161
+ };
162
+ }
163
+ /**
164
+ * 根据错误类型判断是否应该重试
165
+ */
166
+ shouldRetry(error, retryCount) {
167
+ if (retryCount >= this.config.maxRetries) {
168
+ return false;
169
+ }
170
+ const category = this.classifyError(error);
171
+ return this.isRetryableCategory(category);
172
+ }
173
+ /**
174
+ * 对错误进行分类
175
+ */
176
+ classifyError(error) {
177
+ const message = error.message.toLowerCase();
178
+ const errorStr = JSON.stringify(error).toLowerCase();
179
+ if (message.includes("econnrefused") || message.includes("enotfound") || message.includes("etimedout") || message.includes("network") || message.includes("socket hang up") || message.includes("socket") || message.includes("econnreset") || message.includes("epipe") || message.includes("hang up")) {
180
+ return "NETWORK_ERROR" /* NETWORK_ERROR */;
181
+ }
182
+ if (message.includes("401") || message.includes("403") || message.includes("unauthorized") || message.includes("forbidden") || message.includes("invalid") || message.includes("token")) {
183
+ return "AUTH_ERROR" /* AUTH_ERROR */;
184
+ }
185
+ if (message.includes("500") || message.includes("502") || message.includes("503") || message.includes("504") || message.includes("server error") || message.includes("\u670D\u52A1\u5668\u7AEF\u5F02\u5E38")) {
186
+ return "SERVER_ERROR" /* SERVER_ERROR */;
187
+ }
188
+ if (message.includes("400") || message.includes("404") || message.includes("bad request") || message.includes("not found")) {
189
+ return "CLIENT_ERROR" /* CLIENT_ERROR */;
190
+ }
191
+ if (message.includes("timeout") || message.includes("rate limit") || message.includes("too many") || message.includes("429")) {
192
+ return "TEMPORARY_ERROR" /* TEMPORARY_ERROR */;
193
+ }
194
+ return "UNKNOWN_ERROR" /* UNKNOWN_ERROR */;
195
+ }
196
+ /**
197
+ * 判断错误类别是否可重试
198
+ */
199
+ isRetryableCategory(category) {
200
+ const retryableCategories = [
201
+ "NETWORK_ERROR" /* NETWORK_ERROR */,
202
+ "TEMPORARY_ERROR" /* TEMPORARY_ERROR */,
203
+ "SERVER_ERROR" /* SERVER_ERROR */
204
+ ];
205
+ return retryableCategories.includes(category);
206
+ }
207
+ /**
208
+ * 计算延迟时间(使用指数退避策略)
209
+ */
210
+ calculateDelay(retryCount) {
211
+ const exponentialDelay = this.config.initialDelayMs * Math.pow(this.config.backoffMultiplier, retryCount);
212
+ const jitter = exponentialDelay * (Math.random() * 0.2);
213
+ const delay = Math.min(exponentialDelay + jitter, this.config.maxDelayMs);
214
+ return Math.round(delay);
215
+ }
216
+ /**
217
+ * 等待指定时间
218
+ */
219
+ async sleep(ms) {
220
+ return new Promise((resolve) => setTimeout(resolve, ms));
221
+ }
222
+ /**
223
+ * 执行带重试的异步函数
224
+ */
225
+ async execute(fn, operationName = "Operation") {
226
+ let lastError;
227
+ let attempt = 0;
228
+ while (attempt <= this.config.maxRetries) {
229
+ attempt++;
230
+ try {
231
+ logger.info(`${operationName} (Attempt ${attempt}/${this.config.maxRetries + 1})`);
232
+ const result = await fn();
233
+ if (attempt > 1) {
234
+ logger.success(`${operationName} succeeded after ${attempt} attempts`);
235
+ }
236
+ return {
237
+ success: true,
238
+ data: result,
239
+ totalAttempts: attempt
240
+ };
241
+ } catch (error) {
242
+ lastError = error;
243
+ const errorMessage = error.message || String(error);
244
+ const category = this.classifyError(error);
245
+ logger.warn(`${operationName} failed (Attempt ${attempt}): ${errorMessage} [${category}]`);
246
+ if (!this.shouldRetry(error, attempt)) {
247
+ logger.error(`${operationName} failed with non-retryable error: ${errorMessage}`);
248
+ return {
249
+ success: false,
250
+ error,
251
+ totalAttempts: attempt,
252
+ lastError: errorMessage
253
+ };
254
+ }
255
+ if (attempt <= this.config.maxRetries) {
256
+ const delayMs = this.calculateDelay(attempt - 1);
257
+ logger.info(
258
+ `Retrying ${operationName} after ${delayMs}ms (${this.config.maxRetries - attempt + 1} retries left)...`
259
+ );
260
+ await this.sleep(delayMs);
261
+ }
262
+ }
263
+ }
264
+ return {
265
+ success: false,
266
+ error: lastError || new Error(`${operationName} failed after all retries`),
267
+ totalAttempts: attempt,
268
+ lastError: lastError?.message
269
+ };
270
+ }
271
+ };
272
+ var DEFAULT_RETRY_CONFIG = {
273
+ maxRetries: 3,
274
+ initialDelayMs: 1e3,
275
+ backoffMultiplier: 2,
276
+ maxDelayMs: 3e4
277
+ };
278
+ function createUploadRetryStrategy(config) {
279
+ return new RetryStrategy({
280
+ ...DEFAULT_RETRY_CONFIG,
281
+ ...config
282
+ });
283
+ }
284
+
285
+ // src/utils/upload-manager.ts
286
+ import path2 from "path";
287
+
288
+ // src/utils/package-parser.ts
289
+ import path from "path";
290
+ import fs2 from "fs";
291
+ import crypto from "crypto";
292
+ async function parsePackageInfo(filePath, options) {
293
+ const ext = path.extname(filePath).toLowerCase();
294
+ try {
295
+ switch (ext) {
296
+ case ".apk":
297
+ return await parseApk(filePath, options);
298
+ case ".ipa":
299
+ return await parseIpa(filePath);
300
+ case ".hap":
301
+ return await parseHap(filePath);
302
+ default:
303
+ logger.warn(`[PackageParser] \u4E0D\u652F\u6301\u7684\u6587\u4EF6\u683C\u5F0F: ${ext}`);
304
+ return null;
305
+ }
306
+ } catch (error) {
307
+ logger.warn(`[PackageParser] \u89E3\u6790\u5931\u8D25: ${error.message}`);
308
+ return null;
309
+ }
310
+ }
311
+ function exec(cmd, args, timeoutMs = 15e3) {
312
+ const { execFile } = __require("child_process");
313
+ return new Promise((resolve, reject) => {
314
+ execFile(
315
+ cmd,
316
+ args,
317
+ { timeout: timeoutMs, maxBuffer: 1024 * 1024 },
318
+ (error, stdout, stderr) => {
319
+ if (error) {
320
+ reject(error);
321
+ } else {
322
+ resolve(stdout);
323
+ }
324
+ }
325
+ );
326
+ });
327
+ }
328
+ async function getAaptPath(options) {
329
+ if (options?.androidSdkPath && fs2.existsSync(options.androidSdkPath)) {
330
+ const buildToolsDir = path.join(options.androidSdkPath, "build-tools");
331
+ if (fs2.existsSync(buildToolsDir)) {
332
+ const tool = findInBuildTools(buildToolsDir);
333
+ if (tool) return tool;
334
+ }
335
+ }
336
+ if (await commandExists("aapt2")) return "aapt2";
337
+ if (await commandExists("aapt")) return "aapt";
338
+ const sdkRoot = process.env.ANDROID_HOME || process.env.ANDROID_SDK_ROOT || path.join(process.env.HOME || "", "Library/Android/sdk");
339
+ if (sdkRoot && fs2.existsSync(sdkRoot)) {
340
+ const buildToolsDir = path.join(sdkRoot, "build-tools");
341
+ if (fs2.existsSync(buildToolsDir)) {
342
+ const tool = findInBuildTools(buildToolsDir);
343
+ if (tool) return tool;
344
+ }
345
+ }
346
+ return null;
347
+ }
348
+ function findInBuildTools(buildToolsDir) {
349
+ const versions = fs2.readdirSync(buildToolsDir).filter((dir) => fs2.lstatSync(path.join(buildToolsDir, dir)).isDirectory()).sort((a, b) => b.localeCompare(a, void 0, { numeric: true }));
350
+ for (const version of versions) {
351
+ const aapt2 = path.join(buildToolsDir, version, "aapt2");
352
+ if (fs2.existsSync(aapt2)) return aapt2;
353
+ const aapt = path.join(buildToolsDir, version, "aapt");
354
+ if (fs2.existsSync(aapt)) return aapt;
355
+ }
356
+ return null;
357
+ }
358
+ async function commandExists(cmd) {
359
+ try {
360
+ await exec("which", [cmd], 3e3);
361
+ return true;
362
+ } catch {
363
+ return false;
364
+ }
365
+ }
366
+ async function parseApk(filePath, options) {
367
+ const tool = await getAaptPath(options);
368
+ if (!tool) {
369
+ logger.warn(
370
+ "[PackageParser] \u26A0\uFE0F aapt2/aapt \u4E0D\u53EF\u7528 (\u8BF7\u68C0\u67E5 ANDROID_HOME \u6216\u52A0\u5165 PATH)\uFF0C\u65E0\u6CD5\u89E3\u6790 APK \u7248\u672C\u4FE1\u606F"
371
+ );
372
+ return null;
373
+ }
374
+ const output = await exec(tool, ["dump", "badging", filePath]);
375
+ const packageMatch = output.match(
376
+ /package:\s+name='([^']*)'.*?versionCode='([^']*)'.*?versionName='([^']*)'/
377
+ );
378
+ if (!packageMatch) {
379
+ logger.warn("[PackageParser] APK badging \u8F93\u51FA\u4E2D\u672A\u627E\u5230\u7248\u672C\u4FE1\u606F");
380
+ return null;
381
+ }
382
+ const info = {
383
+ packageName: packageMatch[1] || void 0,
384
+ versionCode: packageMatch[2] || void 0,
385
+ versionName: packageMatch[3] || void 0
386
+ };
387
+ const nativeCodeMatch = output.match(/native-code:\s+((?:'[^']*'\s*)*)/);
388
+ if (nativeCodeMatch) {
389
+ info.nativeCode = nativeCodeMatch[1].split(/\s+/).filter((s) => s.startsWith("'") && s.endsWith("'")).map((s) => s.slice(1, -1));
390
+ }
391
+ try {
392
+ const fileBuffer = fs2.readFileSync(filePath);
393
+ info.md5 = crypto.createHash("md5").update(fileBuffer).digest("hex").toLowerCase();
394
+ } catch (e) {
395
+ logger.warn(`[PackageParser] \u8BA1\u7B97 MD5 \u5931\u8D25: ${e.message}`);
396
+ }
397
+ logger.info(
398
+ `[PackageParser] APK: ${info.packageName} v${info.versionName}+${info.versionCode} arch:${info.nativeCode?.join(",") || "none"}`
399
+ );
400
+ return info;
401
+ }
402
+ async function parseIpa(filePath) {
403
+ if (!await commandExists("plutil")) {
404
+ logger.warn("[PackageParser] plutil \u4E0D\u53EF\u7528\uFF08\u975E macOS\uFF1F\uFF09\uFF0C\u65E0\u6CD5\u89E3\u6790 IPA");
405
+ return null;
406
+ }
407
+ const listOutput = await exec("unzip", ["-Z1", filePath]);
408
+ const plistPath = listOutput.split("\n").find((line) => /^Payload\/[^/]+\.app\/Info\.plist$/.test(line.trim()));
409
+ if (!plistPath) {
410
+ logger.warn("[PackageParser] IPA \u4E2D\u672A\u627E\u5230 Info.plist");
411
+ return null;
412
+ }
413
+ const plistData = await exec("unzip", ["-p", filePath, plistPath.trim()]);
414
+ const jsonStr = await new Promise((resolve, reject) => {
415
+ const child = __require("child_process").spawn("plutil", ["-convert", "json", "-o", "-", "-"], {
416
+ timeout: 1e4
417
+ });
418
+ let stdout = "";
419
+ let stderr = "";
420
+ child.stdout.on("data", (d) => stdout += d.toString());
421
+ child.stderr.on("data", (d) => stderr += d.toString());
422
+ child.on("close", (code) => {
423
+ if (code === 0) resolve(stdout);
424
+ else reject(new Error(`plutil \u5931\u8D25: ${stderr}`));
425
+ });
426
+ child.stdin.write(plistData);
427
+ child.stdin.end();
428
+ });
429
+ const plist = JSON.parse(jsonStr);
430
+ const info = {
431
+ versionName: plist.CFBundleShortVersionString || void 0,
432
+ versionCode: plist.CFBundleVersion || void 0,
433
+ packageName: plist.CFBundleIdentifier || void 0
434
+ };
435
+ logger.info(`[PackageParser] IPA: ${info.packageName} v${info.versionName}+${info.versionCode}`);
436
+ return info;
437
+ }
438
+ async function parseHap(filePath) {
439
+ let jsonStr = null;
440
+ try {
441
+ jsonStr = await exec("unzip", ["-p", filePath, "module.json"]);
442
+ } catch {
443
+ try {
444
+ jsonStr = await exec("unzip", ["-p", filePath, "config.json"]);
445
+ } catch {
446
+ logger.warn("[PackageParser] HAP \u4E2D\u672A\u627E\u5230 module.json \u6216 config.json");
447
+ return null;
448
+ }
449
+ }
450
+ const config = JSON.parse(jsonStr);
451
+ const app = config.app || {};
452
+ const info = {
453
+ versionName: app.versionName || app.version?.name || void 0,
454
+ versionCode: String(app.versionCode ?? app.version?.code ?? ""),
455
+ packageName: app.bundleName || void 0
456
+ };
457
+ if (!info.versionCode) info.versionCode = void 0;
458
+ logger.info(`[PackageParser] HAP: ${info.packageName} v${info.versionName}+${info.versionCode}`);
459
+ return info;
460
+ }
461
+
462
+ // src/utils/upload-manager.ts
463
+ var UploadManager = class {
464
+ uploaders;
465
+ config;
466
+ constructor(config = {}) {
467
+ this.uploaders = /* @__PURE__ */ new Map();
468
+ this.config = {
469
+ maxConcurrent: config.maxConcurrent ?? 3,
470
+ continueOnError: config.continueOnError ?? true,
471
+ verbose: config.verbose ?? false,
472
+ cancellationToken: config.cancellationToken
473
+ };
474
+ this.registerUploader("pgyer", new PgyerUploader());
475
+ this.registerUploader("huawei", new HuaweiUploader());
476
+ this.registerUploader("xiaomi", new XiaomiUploader());
477
+ this.registerUploader("app_store", new AppleStoreUploader());
478
+ this.registerUploader("testflight", new TestFlightUploader());
479
+ this.registerUploader("adhoc", new AdHocUploader());
480
+ this.registerUploader("harmony", new HarmonyUploader());
481
+ this.registerUploader("oppo", new OppoUploader());
482
+ this.registerUploader("vivo", new VivoUploader());
483
+ this.registerUploader("tencent", new TencentUploader());
484
+ }
485
+ /**
486
+ * 注册上传器
487
+ */
488
+ registerUploader(platform, uploader) {
489
+ this.uploaders.set(platform, uploader);
490
+ }
491
+ /**
492
+ * 获取启用的平台列表(根据配置)
493
+ */
494
+ getEnabledPlatforms(config) {
495
+ const enabled = [];
496
+ if (config?.publish?.pgyer?.enable) enabled.push("pgyer");
497
+ if (config?.publish?.huawei?.enable) enabled.push("huawei");
498
+ if (config?.publish?.xiaomi?.enable) enabled.push("xiaomi");
499
+ if (config?.publish?.oppo?.enable) enabled.push("oppo");
500
+ if (config?.publish?.vivo?.enable) enabled.push("vivo");
501
+ if (config?.publish?.tencent?.enable) enabled.push("tencent");
502
+ if (config?.publish?.app_store?.enable) {
503
+ const mode = config.publish.app_store.mode || "app_store";
504
+ enabled.push(mode);
505
+ }
506
+ return enabled;
507
+ }
508
+ /**
509
+ * 获取可用的平台列表
510
+ */
511
+ getAvailablePlatforms() {
512
+ return Array.from(this.uploaders.keys());
513
+ }
514
+ /**
515
+ * 执行并行上传(支持多文件智能分发)
516
+ */
517
+ async uploadToMultiplePlatforms(filePaths, config, metadata, targetPlatforms) {
518
+ const startTime = Date.now();
519
+ let platforms = targetPlatforms && targetPlatforms.length > 0 ? targetPlatforms : this.getEnabledPlatforms(config);
520
+ if (platforms.length === 0) {
521
+ logger.warn("No platforms enabled for upload");
522
+ return {
523
+ totalUploads: 0,
524
+ successCount: 0,
525
+ failureCount: 0,
526
+ successPlatforms: [],
527
+ failurePlatforms: [],
528
+ results: [],
529
+ totalDurationMs: 0,
530
+ summary: "No platforms configured for upload"
531
+ };
532
+ }
533
+ logger.info(
534
+ `Starting parallel uploads to ${platforms.length} platform(s): ${platforms.join(", ")}`
535
+ );
536
+ const validPlatforms = platforms.filter((platform) => {
537
+ const uploader = this.uploaders.get(platform);
538
+ if (!uploader) {
539
+ logger.warn(`Platform '${platform}' is not supported`);
540
+ return false;
541
+ }
542
+ if (!uploader.validateConfig(config)) {
543
+ logger.warn(`Configuration for '${platform}' is invalid`);
544
+ return false;
545
+ }
546
+ return true;
547
+ });
548
+ if (validPlatforms.length === 0) {
549
+ logger.error("No valid platforms to upload to");
550
+ return {
551
+ totalUploads: platforms.length,
552
+ successCount: 0,
553
+ failureCount: platforms.length,
554
+ successPlatforms: [],
555
+ failurePlatforms: platforms,
556
+ results: [],
557
+ totalDurationMs: Date.now() - startTime,
558
+ summary: "All platforms failed configuration validation"
559
+ };
560
+ }
561
+ const files = Array.isArray(filePaths) ? filePaths : [filePaths];
562
+ logger.info(`Processing ${files.length} file(s) for ${validPlatforms.length} platform(s)`);
563
+ const uploadPromises = validPlatforms.map((platform) => {
564
+ const uploader = this.uploaders.get(platform);
565
+ const targetFile = files.find((f) => uploader.canHandle(f));
566
+ if (!targetFile) {
567
+ logger.warn(`[${platform}] No compatible file found in provided files`);
568
+ return Promise.resolve({
569
+ platform,
570
+ success: false,
571
+ message: `No compatible file found for ${platform}`
572
+ });
573
+ }
574
+ logger.info(`[${platform}] Matched file: ${path2.basename(targetFile)}`);
575
+ return this.uploadToPlatform(platform, targetFile, config, metadata);
576
+ });
577
+ const results = await Promise.all(uploadPromises);
578
+ const report = this.aggregateResults(results, validPlatforms.length, startTime);
579
+ this.printReport(report);
580
+ return report;
581
+ }
582
+ /**
583
+ * 上传到单个平台
584
+ */
585
+ async uploadToPlatform(platform, filePath, config, metadata) {
586
+ if (this.config.cancellationToken?.isCancelled) {
587
+ logger.warn(`[${platform.toUpperCase()}] Upload skipped due to cancellation`);
588
+ return {
589
+ platform,
590
+ success: false,
591
+ message: "Upload cancelled by user"
592
+ };
593
+ }
594
+ const uploader = this.uploaders.get(platform);
595
+ if (!uploader) {
596
+ return {
597
+ platform,
598
+ success: false,
599
+ message: `Platform '${platform}' is not supported`
600
+ };
601
+ }
602
+ try {
603
+ if (this.config.verbose) {
604
+ logger.info(`[${platform.toUpperCase()}] Starting upload...`);
605
+ }
606
+ const pkgInfo = await parsePackageInfo(filePath, {
607
+ androidSdkPath: metadata.globalSettings?.androidSdkPath
608
+ });
609
+ if (pkgInfo) {
610
+ if (pkgInfo.versionName) {
611
+ metadata.version = pkgInfo.versionName;
612
+ }
613
+ if (pkgInfo.versionCode) {
614
+ metadata.buildNumber = pkgInfo.versionCode;
615
+ }
616
+ if (pkgInfo.packageName) {
617
+ ;
618
+ metadata.packageName = pkgInfo.packageName;
619
+ }
620
+ logger.info(
621
+ `[${platform.toUpperCase()}] \u5DF2\u6821\u51C6\u7248\u672C\u4FE1\u606F: v${metadata.version}+${metadata.buildNumber}`
622
+ );
623
+ }
624
+ const result = await uploader.upload(filePath, config, metadata);
625
+ return result;
626
+ } catch (error) {
627
+ const errorMessage = error.message || String(error);
628
+ logger.error(`[${platform.toUpperCase()}] Upload error: ${errorMessage}`);
629
+ return {
630
+ platform,
631
+ success: false,
632
+ message: errorMessage,
633
+ error
634
+ };
635
+ }
636
+ }
637
+ /**
638
+ * 聚合上传结果
639
+ */
640
+ aggregateResults(results, totalPlatforms, startTime) {
641
+ const successResults = results.filter((r) => r.success);
642
+ const failureResults = results.filter((r) => !r.success);
643
+ const successPlatforms = successResults.map((r) => r.platform || "unknown");
644
+ const failurePlatforms = failureResults.map((r) => r.platform || "unknown");
645
+ const totalDurationMs = Date.now() - startTime;
646
+ let summary = "";
647
+ if (successResults.length === totalPlatforms) {
648
+ summary = `\u2705 All ${totalPlatforms} platforms uploaded successfully!`;
649
+ } else if (failureResults.length === totalPlatforms) {
650
+ summary = `\u274C Upload failed on all ${totalPlatforms} platforms`;
651
+ } else {
652
+ summary = `\u26A0\uFE0F Partial success: ${successResults.length} succeeded, ${failureResults.length} failed`;
653
+ }
654
+ return {
655
+ totalUploads: totalPlatforms,
656
+ successCount: successResults.length,
657
+ failureCount: failureResults.length,
658
+ successPlatforms,
659
+ failurePlatforms,
660
+ results,
661
+ totalDurationMs,
662
+ summary
663
+ };
664
+ }
665
+ /**
666
+ * 输出上传报告
667
+ */
668
+ printReport(report) {
669
+ logger.info("");
670
+ logger.info("\u2550".repeat(60));
671
+ logger.info("\u{1F4CA} Upload Report");
672
+ logger.info("\u2550".repeat(60));
673
+ logger.info(`Total Platforms: ${report.totalUploads}`);
674
+ logger.info(`\u2705 Success: ${report.successCount}`);
675
+ logger.info(`\u274C Failure: ${report.failureCount}`);
676
+ if (report.successPlatforms.length > 0) {
677
+ logger.info(`Successful: ${report.successPlatforms.join(", ")}`);
678
+ }
679
+ if (report.failurePlatforms.length > 0) {
680
+ logger.info(`Failed: ${report.failurePlatforms.join(", ")}`);
681
+ }
682
+ logger.info(`Total Duration: ${this.formatDuration(report.totalDurationMs)}`);
683
+ logger.info("");
684
+ logger.info(report.summary);
685
+ logger.info("\u2550".repeat(60));
686
+ logger.info("");
687
+ logger.info("\u{1F4CB} Detailed Results:");
688
+ report.results.forEach((result) => {
689
+ if (result.success) {
690
+ if (this.config.verbose) {
691
+ logger.success(`[${result.platform}] \u2705 ${result.message}`);
692
+ if (result.url) {
693
+ logger.info(` Download: ${result.url}`);
694
+ }
695
+ }
696
+ } else {
697
+ logger.error(`[${result.platform}] \u274C ${result.message}`);
698
+ if (result.error && result.error.stack && this.config.verbose) {
699
+ logger.error(result.error.stack);
700
+ }
701
+ }
702
+ });
703
+ logger.info("");
704
+ }
705
+ /**
706
+ * 格式化持续时间
707
+ */
708
+ formatDuration(ms) {
709
+ if (ms < 1e3) {
710
+ return `${ms}ms`;
711
+ }
712
+ if (ms < 6e4) {
713
+ return `${(ms / 1e3).toFixed(1)}s`;
714
+ }
715
+ return `${(ms / 6e4).toFixed(1)}m`;
716
+ }
717
+ /**
718
+ * 获取可重试的失败平台
719
+ */
720
+ getRetryablePlatforms(report) {
721
+ return report.failurePlatforms;
722
+ }
723
+ /**
724
+ * 重试失败的平台
725
+ */
726
+ async retryFailedPlatforms(failedPlatforms, filePath, config, metadata) {
727
+ if (failedPlatforms.length === 0) {
728
+ logger.info("No platforms to retry");
729
+ return {
730
+ totalUploads: 0,
731
+ successCount: 0,
732
+ failureCount: 0,
733
+ successPlatforms: [],
734
+ failurePlatforms: [],
735
+ results: [],
736
+ totalDurationMs: 0,
737
+ summary: "No platforms to retry"
738
+ };
739
+ }
740
+ logger.info(`Retrying ${failedPlatforms.length} failed platform(s)...`);
741
+ return this.uploadToMultiplePlatforms(filePath, config, metadata, failedPlatforms);
742
+ }
743
+ };
744
+ function createUploadManager(config) {
745
+ return new UploadManager(config);
746
+ }
747
+
748
+ // src/utils/apple-jwt-generator.ts
749
+ import crypto2 from "crypto";
750
+ import fs3 from "fs-extra";
751
+ var AppleJWTGenerator = class _AppleJWTGenerator {
752
+ issuerId;
753
+ keyId;
754
+ privateKey;
755
+ constructor(issuerId, keyId, privateKey) {
756
+ this.issuerId = issuerId;
757
+ this.keyId = keyId;
758
+ this.privateKey = privateKey;
759
+ }
760
+ /**
761
+ * 从文件路径加载私钥内容
762
+ */
763
+ static async fromFile(issuerId, keyId, privateKeyPath) {
764
+ try {
765
+ const privateKey = await fs3.readFile(privateKeyPath, "utf-8");
766
+ return new _AppleJWTGenerator(issuerId, keyId, privateKey);
767
+ } catch (error) {
768
+ throw new Error(`Failed to load Apple private key from ${privateKeyPath}: ${error.message}`);
769
+ }
770
+ }
771
+ /**
772
+ * 从内容字符串创建生成器
773
+ */
774
+ static fromContent(issuerId, keyId, privateKeyContent) {
775
+ return new _AppleJWTGenerator(issuerId, keyId, privateKeyContent);
776
+ }
777
+ /**
778
+ * 生成 JWT 令牌
779
+ * @returns Base64URL 编码的 JWT 字符串
780
+ */
781
+ generate() {
782
+ try {
783
+ const header = this.createHeader();
784
+ const headerEncoded = this.base64urlEncode(JSON.stringify(header));
785
+ const payload = this.createPayload();
786
+ const payloadEncoded = this.base64urlEncode(JSON.stringify(payload));
787
+ const signatureInput = `${headerEncoded}.${payloadEncoded}`;
788
+ const signature = this.sign(signatureInput);
789
+ return `${signatureInput}.${signature}`;
790
+ } catch (error) {
791
+ logger.error(`Failed to generate Apple JWT: ${error.message}`);
792
+ throw error;
793
+ }
794
+ }
795
+ /**
796
+ * 创建 JWT Header
797
+ */
798
+ createHeader() {
799
+ return {
800
+ alg: "ES256",
801
+ kid: this.keyId,
802
+ typ: "JWT"
803
+ };
804
+ }
805
+ /**
806
+ * 创建 JWT Payload
807
+ * 有效期: 20 分钟(1200 秒)
808
+ */
809
+ createPayload() {
810
+ const now = Math.floor(Date.now() / 1e3);
811
+ return {
812
+ iss: this.issuerId,
813
+ aud: "appstoreconnect-v1",
814
+ exp: now + 1200,
815
+ // 20 minutes
816
+ iat: now
817
+ };
818
+ }
819
+ /**
820
+ * 使用 ES256 算法签名
821
+ * ES256 = ECDSA with SHA-256
822
+ */
823
+ sign(data) {
824
+ const sign = crypto2.createSign("SHA256");
825
+ sign.update(data);
826
+ sign.end();
827
+ const signature = sign.sign({
828
+ key: this.privateKey,
829
+ format: "pem"
830
+ });
831
+ const { r, s } = this.parseDERSignature(signature);
832
+ const combined = Buffer.concat([r, s]);
833
+ return this.base64urlEncode(combined);
834
+ }
835
+ /**
836
+ * 解析 DER 格式的签名并提取 r 和 s
837
+ */
838
+ parseDERSignature(derSignature) {
839
+ let offset = 0;
840
+ offset += 2;
841
+ if (derSignature[offset] === 129 || derSignature[offset] === 130) {
842
+ offset += 1;
843
+ } else {
844
+ offset += 1;
845
+ }
846
+ offset += 1;
847
+ const rLength = derSignature[offset];
848
+ offset += 1;
849
+ let r = derSignature.subarray(offset, offset + rLength);
850
+ offset += rLength;
851
+ if (r[0] === 0 && r.length > 32) {
852
+ r = r.subarray(1);
853
+ }
854
+ r = this.padBuffer(r, 32);
855
+ offset += 1;
856
+ const sLength = derSignature[offset];
857
+ offset += 1;
858
+ let s = derSignature.subarray(offset, offset + sLength);
859
+ if (s[0] === 0 && s.length > 32) {
860
+ s = s.subarray(1);
861
+ }
862
+ s = this.padBuffer(s, 32);
863
+ return { r: Buffer.from(r), s: Buffer.from(s) };
864
+ }
865
+ /**
866
+ * 将 Buffer 填充或截断到指定长度
867
+ */
868
+ padBuffer(buf, length) {
869
+ if (buf.length === length) return buf;
870
+ if (buf.length > length) return buf.subarray(buf.length - length);
871
+ const padded = Buffer.alloc(length);
872
+ buf.copy(padded, length - buf.length);
873
+ return padded;
874
+ }
875
+ /**
876
+ * Base64URL 编码 (RFC 4648)
877
+ */
878
+ base64urlEncode(data) {
879
+ const base64 = Buffer.from(data).toString("base64");
880
+ return base64.replace(/\+/g, "-").replace(/\//g, "_").replace(/=/g, "");
881
+ }
882
+ };
883
+
884
+ // src/adapters/pgyer_uploader.ts
885
+ var PgyerUploader = class _PgyerUploader {
886
+ name = "Pgyer";
887
+ static UPLOAD_API = "https://www.pgyer.com/apiv2/app/upload";
888
+ /**
889
+ * 验证配置
890
+ * @param config 配置对象
891
+ */
892
+ validateConfig(config) {
893
+ if (!config?.publish?.pgyer?.enable) {
894
+ return false;
895
+ }
896
+ if (!config.publish.pgyer.apiKey) {
897
+ logger.error("Pgyer apiKey is missing in config");
898
+ return false;
899
+ }
900
+ return true;
901
+ }
902
+ /**
903
+ * 判断是否支持该文件
904
+ * @param filePath 文件路径
905
+ */
906
+ canHandle(filePath) {
907
+ const ext = filePath.split(".").pop()?.toLowerCase();
908
+ return ext === "apk" || ext === "ipa" || ext === "aab";
909
+ }
910
+ /**
911
+ * 上传文件到蒲公英
912
+ * @param filePath 文件路径
913
+ * @param config 配置
914
+ * @param metadata 元数据
915
+ */
916
+ async upload(filePath, config, metadata) {
917
+ const pgyerConfig = config.publish?.pgyer;
918
+ const apiKey = pgyerConfig?.apiKey;
919
+ const desc = metadata.changelog || pgyerConfig?.description || "";
920
+ const retryConfig = config.retry;
921
+ if (!fs4.existsSync(filePath)) {
922
+ return {
923
+ platform: "pgyer",
924
+ success: false,
925
+ message: `File not found: ${filePath}`
926
+ };
927
+ }
928
+ logger.info(`Uploading to Pgyer...`);
929
+ logger.info(`File: ${filePath}`);
930
+ logger.info(`Changelog: ${desc.replace(/\n/g, " ")}`);
931
+ const retryStrategy = createUploadRetryStrategy(retryConfig);
932
+ const result = await retryStrategy.execute(
933
+ () => this.performUpload(filePath, apiKey, desc),
934
+ "Pgyer upload"
935
+ );
936
+ if (result.success) {
937
+ const pgyerData = result.data;
938
+ return {
939
+ platform: "pgyer",
940
+ success: true,
941
+ message: "Upload success",
942
+ url: pgyerData.fullUrl,
943
+ link: pgyerData.fullUrl,
944
+ qrCode: pgyerData.qrCodeUrl,
945
+ data: pgyerData,
946
+ consoleUrl: "https://www.pgyer.com/my"
947
+ };
948
+ } else {
949
+ const lastError = result.lastError;
950
+ const errorMsg = lastError instanceof Error ? lastError.message : String(lastError || "Upload failed");
951
+ return {
952
+ platform: "pgyer",
953
+ success: false,
954
+ message: errorMsg,
955
+ // ✅ 必填且为字符串
956
+ error: result.error
957
+ };
958
+ }
959
+ }
960
+ /**
961
+ * 执行实际上传操作
962
+ * @param filePath 文件路径
963
+ * @param apiKey API Key
964
+ * @param desc 描述
965
+ */
966
+ async performUpload(filePath, apiKey, desc) {
967
+ const form = new FormData();
968
+ form.append("_api_key", apiKey);
969
+ form.append("buildUpdateDescription", desc);
970
+ form.append("file", fs4.createReadStream(filePath));
971
+ const response = await axios.post(_PgyerUploader.UPLOAD_API, form, {
972
+ headers: {
973
+ ...form.getHeaders()
974
+ },
975
+ maxContentLength: Infinity,
976
+ maxBodyLength: Infinity
977
+ });
978
+ const data = response.data;
979
+ if (data.code !== 0) {
980
+ logger.error(`Pgyer API Error: ${data.message}`);
981
+ throw new Error(`Pgyer API Error: ${data.message}`);
982
+ }
983
+ const shortcutUrl = data.data.buildShortcutUrl;
984
+ let qrCodeUrl = data.data.buildQRCodeURL;
985
+ const fullUrl = `https://www.pgyer.com/${shortcutUrl}`;
986
+ if (qrCodeUrl && qrCodeUrl.startsWith("//")) {
987
+ qrCodeUrl = `https:${qrCodeUrl}`;
988
+ } else if (qrCodeUrl && !qrCodeUrl.startsWith("http")) {
989
+ }
990
+ logger.success(`Upload to Pgyer success!`);
991
+ logger.info(`Download URL: ${fullUrl}`);
992
+ return {
993
+ fullUrl,
994
+ qrCodeUrl,
995
+ shortcutUrl
996
+ };
997
+ }
998
+ };
999
+
1000
+ // src/adapters/huawei_uploader.ts
1001
+ import fs5 from "fs-extra";
1002
+ import path3 from "path";
1003
+ import { promisify } from "util";
1004
+ import axios2 from "axios";
1005
+ import FormData2 from "form-data";
1006
+ var HUAWEI_SUPPORTED_SUFFIXES = {
1007
+ image: ["jpg", "jpeg", "png", "bmp"],
1008
+ video: ["mp4", "mov"],
1009
+ package: ["apk", "aab", "rpk"]
1010
+ };
1011
+ var HuaweiUploader = class _HuaweiUploader {
1012
+ name = "Huawei";
1013
+ // 华为上传器默认 API 基础地址
1014
+ static DEFAULT_API_BASE = "https://connect-api.cloud.huawei.com";
1015
+ // 华为上传器获取 Token 路径
1016
+ static TOKEN_PATH = "/api/oauth2/v1/token";
1017
+ // 华为上传器发布 API 根路径
1018
+ static PUBLISH_API_PATH = "/api/publish/v2";
1019
+ /** 获取 API 基础地址 */
1020
+ getApiBase(config) {
1021
+ return config?.publish?.huawei?.apiBaseUrl || _HuaweiUploader.DEFAULT_API_BASE;
1022
+ }
1023
+ /** 获取 Token URL */
1024
+ getTokenUrl(config) {
1025
+ return `${this.getApiBase(config)}${_HuaweiUploader.TOKEN_PATH}`;
1026
+ }
1027
+ /** 获取 Publish API 根路径 */
1028
+ getApiRoot(config) {
1029
+ return `${this.getApiBase(config)}${_HuaweiUploader.PUBLISH_API_PATH}`;
1030
+ }
1031
+ /** 创建 API 请求头(消除 7 处重复) */
1032
+ headers(ctx) {
1033
+ return {
1034
+ Authorization: `Bearer ${ctx.token}`,
1035
+ client_id: ctx.clientId
1036
+ };
1037
+ }
1038
+ /** 检查 API 响应(消除 6 处重复) */
1039
+ checkResponse(res, operation) {
1040
+ const code = res.data.ret?.code ?? res.data.code;
1041
+ if (code !== 0) {
1042
+ throw new Error(`${operation} failed: ${res.data.ret?.msg || res.data.msg}`);
1043
+ }
1044
+ return res.data;
1045
+ }
1046
+ /**
1047
+ * 验证配置
1048
+ * @param config 配置对象
1049
+ * @returns 是否有效
1050
+ */
1051
+ validateConfig(config) {
1052
+ if (!config?.publish?.huawei?.enable) return false;
1053
+ const h = config.publish.huawei;
1054
+ if (!h.auth?.clientId || !h.auth?.clientSecret || !h.appId) {
1055
+ logger.error("Huawei config missing: clientId, clientSecret, or appId");
1056
+ return false;
1057
+ }
1058
+ return true;
1059
+ }
1060
+ /**
1061
+ * 判断是否支持该文件
1062
+ * @param filePath 文件路径
1063
+ * @returns 是否支持
1064
+ */
1065
+ canHandle(filePath) {
1066
+ const ext = filePath.split(".").pop()?.toLowerCase();
1067
+ return ext === "apk" || ext === "aab";
1068
+ }
1069
+ /**
1070
+ * 执行上传
1071
+ * @param filePath 文件路径
1072
+ * @param config 配置
1073
+ * @param metadata 元数据
1074
+ */
1075
+ async upload(filePath, config, metadata) {
1076
+ const hwConfig = config.publish.huawei;
1077
+ const clientId = hwConfig.auth.clientId;
1078
+ const clientSecret = hwConfig.auth.clientSecret;
1079
+ const appId = hwConfig.appId;
1080
+ const releaseType = hwConfig.releaseType || "draft";
1081
+ const suffix = path3.extname(filePath).substring(1);
1082
+ const retryConfig = config.retry;
1083
+ const tokenUrl = this.getTokenUrl(config);
1084
+ const publishApiRoot = this.getApiRoot(config);
1085
+ logger.info("Starting Huawei AppGallery upload...");
1086
+ try {
1087
+ const retryStrategy = createUploadRetryStrategy(retryConfig);
1088
+ logger.info("Authenticating...");
1089
+ const tokenResult = await retryStrategy.execute(
1090
+ () => this.getAccessToken(tokenUrl, clientId, clientSecret),
1091
+ "Huawei authentication"
1092
+ );
1093
+ if (!tokenResult.success || !tokenResult.data) {
1094
+ throw tokenResult.error || new Error("Failed to get access token");
1095
+ }
1096
+ const ctx = {
1097
+ apiRoot: publishApiRoot,
1098
+ token: tokenResult.data,
1099
+ clientId,
1100
+ appId
1101
+ };
1102
+ logger.info("Requesting upload URL...");
1103
+ const uploadInfoResult = await retryStrategy.execute(
1104
+ () => this.getUploadUrl(ctx, suffix),
1105
+ "Huawei get upload URL"
1106
+ );
1107
+ if (!uploadInfoResult.success || !uploadInfoResult.data) {
1108
+ throw uploadInfoResult.error || new Error("Failed to get upload URL");
1109
+ }
1110
+ const uploadInfo = uploadInfoResult.data;
1111
+ logger.info("Uploading file (this may take a while)...");
1112
+ const uploadFileResult = await retryStrategy.execute(
1113
+ () => this.uploadFile(uploadInfo.uploadUrl, uploadInfo.authCode, filePath),
1114
+ "Huawei file upload"
1115
+ );
1116
+ if (!uploadFileResult.success || !uploadFileResult.data) {
1117
+ throw uploadFileResult.error || new Error("File upload failed");
1118
+ }
1119
+ const fileDestUrl = uploadFileResult.data.fileDestUrl;
1120
+ logger.info("Linking file to app...");
1121
+ const updateInfoResult = await retryStrategy.execute(
1122
+ () => this.updateAppFileInfo(ctx, fileDestUrl, filePath),
1123
+ "Huawei update file info"
1124
+ );
1125
+ if (!updateInfoResult.success) {
1126
+ throw updateInfoResult.error || new Error("Failed to update file info");
1127
+ }
1128
+ if (metadata.changelog) {
1129
+ try {
1130
+ logger.info("Updating release notes...");
1131
+ await retryStrategy.execute(
1132
+ () => this.updateReleaseNotes(ctx, metadata.changelog, metadata.version),
1133
+ "Huawei update release notes"
1134
+ );
1135
+ } catch (error) {
1136
+ logger.warn(`Failed to update release notes: ${error.message}. Continuing...`);
1137
+ }
1138
+ }
1139
+ const assets = hwConfig.assets;
1140
+ if (assets) {
1141
+ await this.uploadStoreAssets(ctx, assets, retryStrategy);
1142
+ }
1143
+ if (releaseType === "submit") {
1144
+ try {
1145
+ logger.info("Submitting app for review...");
1146
+ const submitResult = await retryStrategy.execute(
1147
+ () => this.submitForReview(ctx, metadata.version),
1148
+ "Huawei submit for review"
1149
+ );
1150
+ if (!submitResult.success) {
1151
+ throw submitResult.error || new Error("Failed to submit for review");
1152
+ }
1153
+ logger.success("Huawei upload successful and submitted for review!");
1154
+ return {
1155
+ platform: "huawei",
1156
+ success: true,
1157
+ message: "Upload and review submission successful",
1158
+ url: "https://developer.huawei.com/consumer/cn/service/josp/agc/index.html",
1159
+ consoleUrl: "https://developer.huawei.com/consumer/cn/service/josp/agc/index.html"
1160
+ };
1161
+ } catch (error) {
1162
+ logger.warn(
1163
+ `Failed to submit for review: ${error.message}. App uploaded but not submitted.`
1164
+ );
1165
+ return {
1166
+ platform: "huawei",
1167
+ success: true,
1168
+ message: "Upload successful but review submission failed. Please submit manually.",
1169
+ url: "https://developer.huawei.com/consumer/cn/service/josp/agc/index.html",
1170
+ consoleUrl: "https://developer.huawei.com/consumer/cn/service/josp/agc/index.html"
1171
+ };
1172
+ }
1173
+ }
1174
+ logger.success("Huawei upload successful (Draft status).");
1175
+ return {
1176
+ platform: "huawei",
1177
+ success: true,
1178
+ message: "Upload success (Draft)",
1179
+ url: "https://developer.huawei.com/consumer/cn/service/josp/agc/index.html",
1180
+ consoleUrl: "https://developer.huawei.com/consumer/cn/service/josp/agc/index.html"
1181
+ };
1182
+ } catch (error) {
1183
+ logger.error(`Huawei upload failed: ${error.message}`);
1184
+ const safeError = {
1185
+ message: error.message,
1186
+ name: error.name,
1187
+ code: error.code,
1188
+ status: error.response?.status
1189
+ };
1190
+ if (error.response?.data) {
1191
+ safeError.responseData = error.response.data;
1192
+ logger.info(`Error Data: ${JSON.stringify(error.response.data)}`);
1193
+ }
1194
+ return {
1195
+ platform: "huawei",
1196
+ success: false,
1197
+ message: error.message,
1198
+ error: safeError
1199
+ };
1200
+ }
1201
+ }
1202
+ /**
1203
+ * 查询审核状态
1204
+ * @param clientId 客户端 ID
1205
+ * @param clientSecret 客户端密钥
1206
+ * @param appId 应用 ID
1207
+ * @param apiBaseUrl API 基础地址(可选)
1208
+ */
1209
+ async queryReviewStatus(clientId, clientSecret, appId, apiBaseUrl) {
1210
+ const baseUrl = apiBaseUrl || _HuaweiUploader.DEFAULT_API_BASE;
1211
+ const tokenUrl = `${baseUrl}${_HuaweiUploader.TOKEN_PATH}`;
1212
+ const apiRoot = `${baseUrl}${_HuaweiUploader.PUBLISH_API_PATH}`;
1213
+ try {
1214
+ logger.info("Querying review status...");
1215
+ const token = await this.getAccessToken(tokenUrl, clientId, clientSecret);
1216
+ const ctx = { apiRoot, token, clientId, appId };
1217
+ const res = await axios2.get(`${apiRoot}/app-information`, {
1218
+ params: { appId },
1219
+ headers: this.headers(ctx)
1220
+ });
1221
+ this.checkResponse(res, "Query review status");
1222
+ const status = res.data.data?.app?.auditStatus || "unknown";
1223
+ logger.info(`Current review status: ${status}`);
1224
+ return status;
1225
+ } catch (error) {
1226
+ logger.error(`Failed to query review status: ${error.message}`);
1227
+ throw error;
1228
+ }
1229
+ }
1230
+ /**
1231
+ * 获取 Access Token
1232
+ * @param tokenUrl Token URL
1233
+ * @param clientId 客户端 ID
1234
+ * @param clientSecret 客户端密钥
1235
+ */
1236
+ async getAccessToken(tokenUrl, clientId, clientSecret) {
1237
+ const data = {
1238
+ client_id: clientId,
1239
+ client_secret: clientSecret,
1240
+ grant_type: "client_credentials"
1241
+ };
1242
+ logger.info(`[Huawei Auth] Requesting token with clientId: ${clientId}`);
1243
+ try {
1244
+ const res = await axios2.post(tokenUrl, data, {
1245
+ headers: {
1246
+ "Content-Type": "application/json"
1247
+ }
1248
+ });
1249
+ logger.info(
1250
+ `[Huawei Auth] Token response received, keys: ${Object.keys(res.data).join(", ")}`
1251
+ );
1252
+ const token = res.data.access_token || res.data.token;
1253
+ if (!token) {
1254
+ logger.error(
1255
+ `[Huawei Auth] No token in response. Full response: ${JSON.stringify(res.data)}`
1256
+ );
1257
+ throw new Error(`Invalid token response: ${JSON.stringify(res.data)}`);
1258
+ }
1259
+ logger.info(`[Huawei Auth] Token obtained successfully`);
1260
+ return token;
1261
+ } catch (error) {
1262
+ logger.error(`[Huawei Auth] Token request failed: ${error.message}`);
1263
+ if (error.response?.data) {
1264
+ logger.error(`[Huawei Auth] Error response: ${JSON.stringify(error.response.data)}`);
1265
+ }
1266
+ throw error;
1267
+ }
1268
+ }
1269
+ /** 获取上传 URL */
1270
+ async getUploadUrl(ctx, suffix) {
1271
+ logger.info(`[Huawei Upload] Requesting upload URL for appId: ${ctx.appId}, suffix: ${suffix}`);
1272
+ const res = await axios2.get(`${ctx.apiRoot}/upload-url`, {
1273
+ params: { appId: ctx.appId, suffix },
1274
+ headers: this.headers(ctx)
1275
+ });
1276
+ this.checkResponse(res, "Get upload URL");
1277
+ return {
1278
+ uploadUrl: res.data.uploadUrl,
1279
+ authCode: res.data.authCode
1280
+ };
1281
+ }
1282
+ /** 通用文件上传(FormData 方式,无需 API 认证头) */
1283
+ async executeUploadRequest(uploadUrl, authCode, filePath) {
1284
+ const fileName = path3.basename(filePath);
1285
+ const fileSize = fs5.statSync(filePath).size;
1286
+ const form = new FormData2();
1287
+ form.append("file", fs5.createReadStream(filePath), {
1288
+ filename: fileName,
1289
+ contentType: "application/octet-stream",
1290
+ knownLength: fileSize
1291
+ });
1292
+ form.append("authCode", authCode);
1293
+ form.append("fileCount", "1");
1294
+ form.append("parseType", "1");
1295
+ const length = await promisify(form.getLength).bind(form)();
1296
+ logger.info(
1297
+ `[Huawei Upload] Uploading: ${fileName} (${(fileSize / 1024 / 1024).toFixed(2)} MB)`
1298
+ );
1299
+ const res = await axios2.post(uploadUrl, form, {
1300
+ headers: { ...form.getHeaders(), "Content-Length": length },
1301
+ maxContentLength: Infinity,
1302
+ maxBodyLength: Infinity
1303
+ });
1304
+ if (res.data.result?.resultCode !== "0") {
1305
+ throw new Error(`File upload failed: ${JSON.stringify(res.data.result)}`);
1306
+ }
1307
+ const fileInfoList = res.data.result?.UploadFileRsp?.fileInfoList || res.data.result?.uploadFileRsp?.fileInfoList || [];
1308
+ if (fileInfoList.length === 0) {
1309
+ throw new Error("No file info returned from upload");
1310
+ }
1311
+ return fileInfoList.map((f) => ({
1312
+ fileName: f.name || fileName,
1313
+ fileDestUrl: f.fileDestUlr || f.fileDestUrl || authCode
1314
+ }));
1315
+ }
1316
+ /** 上传文件 (APK/AAB) */
1317
+ async uploadFile(uploadUrl, authCode, filePath) {
1318
+ const files = await this.executeUploadRequest(uploadUrl, authCode, filePath);
1319
+ if (files.length > 0 && files[0].fileDestUrl) {
1320
+ logger.info(`[Huawei Upload] App package uploaded, fileDestUrl: ${files[0].fileDestUrl}`);
1321
+ return { fileDestUrl: files[0].fileDestUrl };
1322
+ }
1323
+ throw new Error("Upload succeeded but fileDestUrl not found in response");
1324
+ }
1325
+ /** 更新应用文件信息 */
1326
+ async updateAppFileInfo(ctx, fileDestUrl, filePath) {
1327
+ const fileName = path3.basename(filePath);
1328
+ const fileType = path3.extname(filePath).toLowerCase() === ".aab" ? 7 : 5;
1329
+ const res = await axios2.put(
1330
+ `${ctx.apiRoot}/app-file-info`,
1331
+ {
1332
+ fileType,
1333
+ files: [{ fileName, fileDestUrl }]
1334
+ },
1335
+ {
1336
+ params: { appId: ctx.appId },
1337
+ headers: this.headers(ctx)
1338
+ }
1339
+ );
1340
+ this.checkResponse(res, "Update file info");
1341
+ }
1342
+ /** 更新发布说明(支持多语言) */
1343
+ async updateReleaseNotes(ctx, changelog, version) {
1344
+ const notes = typeof changelog === "string" ? { zh_CN: changelog, en_US: changelog } : changelog;
1345
+ const body = {
1346
+ defaultLanguage: "zh_CN",
1347
+ languages: [
1348
+ {
1349
+ lang: "zh_CN",
1350
+ appName: "",
1351
+ appDesc: "",
1352
+ newFeatures: notes["zh_CN"] || ""
1353
+ },
1354
+ {
1355
+ lang: "en_US",
1356
+ appName: "",
1357
+ appDesc: "",
1358
+ newFeatures: notes["en_US"] || ""
1359
+ }
1360
+ ]
1361
+ };
1362
+ const res = await axios2.put(`${ctx.apiRoot}/app-info`, body, {
1363
+ params: { appId: ctx.appId },
1364
+ headers: this.headers(ctx)
1365
+ });
1366
+ this.checkResponse(res, "Update release notes");
1367
+ logger.info("Release notes updated successfully");
1368
+ }
1369
+ /** 提交审核 */
1370
+ async submitForReview(ctx, version) {
1371
+ const appInfo = await this.getAppInfo(ctx);
1372
+ if (!appInfo?.releaseId) {
1373
+ throw new Error("Could not get release ID for submission");
1374
+ }
1375
+ try {
1376
+ const res = await axios2.post(
1377
+ `${ctx.apiRoot}/app-submit`,
1378
+ {
1379
+ releaseId: appInfo.releaseId,
1380
+ auditDesc: `Version ${version}`
1381
+ },
1382
+ {
1383
+ params: { appId: ctx.appId },
1384
+ headers: this.headers(ctx)
1385
+ }
1386
+ );
1387
+ this.checkResponse(res, "Submit for review");
1388
+ logger.success("App submitted for review successfully");
1389
+ } catch (error) {
1390
+ if (error.response?.status === 404) {
1391
+ logger.warn("Huawei review submission API not yet available. Please submit manually.");
1392
+ } else {
1393
+ throw error;
1394
+ }
1395
+ }
1396
+ }
1397
+ /** 获取应用信息 */
1398
+ async getAppInfo(ctx) {
1399
+ const res = await axios2.get(`${ctx.apiRoot}/app-information`, {
1400
+ params: { appId: ctx.appId },
1401
+ headers: this.headers(ctx)
1402
+ });
1403
+ this.checkResponse(res, "Get app info");
1404
+ return res.data.data;
1405
+ }
1406
+ /** 上传商店素材(图标、截图、视频) */
1407
+ async uploadStoreAssets(ctx, assets, retryStrategy) {
1408
+ const tasks = [];
1409
+ if (assets.icon) {
1410
+ tasks.push({
1411
+ label: "icon",
1412
+ files: [assets.icon],
1413
+ type: 0 /* ICON */
1414
+ });
1415
+ }
1416
+ if (assets.screenshots?.length) {
1417
+ tasks.push({
1418
+ label: `${assets.screenshots.length} screenshot(s)`,
1419
+ files: assets.screenshots,
1420
+ type: 1 /* SCREENSHOT */
1421
+ });
1422
+ }
1423
+ if (assets.video) {
1424
+ tasks.push({
1425
+ label: "preview video",
1426
+ files: [assets.video],
1427
+ type: 2 /* VIDEO */
1428
+ });
1429
+ }
1430
+ for (const task of tasks) {
1431
+ try {
1432
+ logger.info(`Uploading ${task.label}...`);
1433
+ await this.uploadAssetFiles(ctx, task.files, task.type, retryStrategy);
1434
+ logger.success(`${task.label} uploaded successfully`);
1435
+ } catch (error) {
1436
+ logger.warn(`Failed to upload ${task.label}: ${error.message}`);
1437
+ }
1438
+ }
1439
+ }
1440
+ /** 批量上传素材文件 */
1441
+ async uploadAssetFiles(ctx, filePaths, fileType, retryStrategy) {
1442
+ const allFileInfos = [];
1443
+ for (const filePath of filePaths) {
1444
+ if (!await fs5.pathExists(filePath)) {
1445
+ logger.warn(`Asset file not found, skipping: ${filePath}`);
1446
+ continue;
1447
+ }
1448
+ const suffix = path3.extname(filePath).substring(1).toLowerCase();
1449
+ if (!HUAWEI_SUPPORTED_SUFFIXES.image.includes(suffix)) {
1450
+ logger.warn(`Unsupported file type ${suffix}, skipping: ${filePath}`);
1451
+ continue;
1452
+ }
1453
+ const uploadInfoResult = await retryStrategy.execute(
1454
+ () => this.getUploadUrl(ctx, suffix),
1455
+ "Huawei get upload URL for asset"
1456
+ );
1457
+ if (!uploadInfoResult.success || !uploadInfoResult.data) {
1458
+ logger.warn(`Failed to get upload URL for: ${filePath}`);
1459
+ continue;
1460
+ }
1461
+ const uploadInfo = uploadInfoResult.data;
1462
+ const uploadResult = await retryStrategy.execute(
1463
+ () => this.executeUploadRequest(uploadInfo.uploadUrl, uploadInfo.authCode, filePath),
1464
+ "Huawei upload asset"
1465
+ );
1466
+ if (!uploadResult.success || !uploadResult.data) {
1467
+ logger.warn(`Failed to upload: ${filePath}`);
1468
+ continue;
1469
+ }
1470
+ allFileInfos.push(...uploadResult.data);
1471
+ }
1472
+ if (allFileInfos.length === 0) {
1473
+ throw new Error("No assets were uploaded successfully");
1474
+ }
1475
+ await retryStrategy.execute(
1476
+ () => this.updateAssetFileInfo(ctx, allFileInfos, fileType),
1477
+ "Huawei update asset file info"
1478
+ );
1479
+ }
1480
+ /** 更新素材文件信息(关联到应用) */
1481
+ async updateAssetFileInfo(ctx, files, fileType) {
1482
+ const res = await axios2.put(
1483
+ `${ctx.apiRoot}/app-file-info`,
1484
+ {
1485
+ fileType,
1486
+ lang: "zh-CN",
1487
+ files: files.map((f) => ({
1488
+ fileName: f.fileName,
1489
+ fileDestUrl: f.fileDestUrl
1490
+ }))
1491
+ },
1492
+ {
1493
+ params: { appId: ctx.appId },
1494
+ headers: this.headers(ctx)
1495
+ }
1496
+ );
1497
+ this.checkResponse(res, "Update asset file info");
1498
+ }
1499
+ };
1500
+
1501
+ // src/adapters/xiaomi_uploader.ts
1502
+ import fs6 from "fs-extra";
1503
+ import axios3 from "axios";
1504
+ import FormData3 from "form-data";
1505
+ import crypto3 from "crypto";
1506
+ var XiaomiUploader = class _XiaomiUploader {
1507
+ name = "Xiaomi";
1508
+ static API_BASE = "https://api.developer.xiaomi.com/devupload";
1509
+ static PUSH_API = `${_XiaomiUploader.API_BASE}/dev/push`;
1510
+ static QUERY_API = `${_XiaomiUploader.API_BASE}/dev/query`;
1511
+ static CATEGORY_API = `${_XiaomiUploader.API_BASE}/dev/category`;
1512
+ /**
1513
+ * RSA 公钥分段加密 (PKCS1Padding)
1514
+ *
1515
+ * 小米要求: 使用平台分配的 RSA 公钥加密 SIG JSON,
1516
+ * 输出小写十六进制字符串。RSA 1024-bit 密钥单次最多加密 117 字节,
1517
+ * 超出需分段加密后拼接。
1518
+ */
1519
+ rsaEncryptWithPublicKey(data, publicKey) {
1520
+ const buffer = Buffer.from(data, "utf-8");
1521
+ const maxBlock = 117;
1522
+ const chunks = [];
1523
+ for (let offset = 0; offset < buffer.length; offset += maxBlock) {
1524
+ const chunk = buffer.subarray(offset, offset + maxBlock);
1525
+ const encrypted = crypto3.publicEncrypt(
1526
+ {
1527
+ key: publicKey,
1528
+ padding: crypto3.constants.RSA_PKCS1_PADDING
1529
+ },
1530
+ chunk
1531
+ );
1532
+ chunks.push(encrypted);
1533
+ }
1534
+ return Buffer.concat(chunks).toString("hex");
1535
+ }
1536
+ /**
1537
+ * 从 X.509 证书或 PEM 公钥中提取可用于加密的公钥
1538
+ * 优先使用 crypto.X509Certificate,因为它能同时处理 DER 和 PEM 格式的证书
1539
+ */
1540
+ extractPublicKey(buffer) {
1541
+ try {
1542
+ const x509 = new crypto3.X509Certificate(buffer);
1543
+ return x509.publicKey;
1544
+ } catch (e) {
1545
+ try {
1546
+ const content = buffer.toString();
1547
+ if (content.includes("-----BEGIN")) {
1548
+ return crypto3.createPublicKey(content);
1549
+ }
1550
+ return crypto3.createPublicKey(this.normalizePEM(content));
1551
+ } catch (e2) {
1552
+ throw new Error(`\u65E0\u6CD5\u63D0\u53D6\u516C\u94A5: ${e instanceof Error ? e.message : "\u672A\u77E5\u9519\u8BEF"}`);
1553
+ }
1554
+ }
1555
+ }
1556
+ /**
1557
+ * 计算文件 MD5 (小写十六进制)
1558
+ */
1559
+ async calculateFileMD5(filePath) {
1560
+ return new Promise((resolve, reject) => {
1561
+ const hash = crypto3.createHash("md5");
1562
+ const stream = fs6.createReadStream(filePath);
1563
+ stream.on("data", (data) => hash.update(data));
1564
+ stream.on("end", () => resolve(hash.digest("hex")));
1565
+ stream.on("error", reject);
1566
+ });
1567
+ }
1568
+ /**
1569
+ * 计算字符串 MD5 (小写十六进制)
1570
+ */
1571
+ calculateStringMD5(str) {
1572
+ return crypto3.createHash("md5").update(str, "utf-8").digest("hex");
1573
+ }
1574
+ /**
1575
+ * 构建 RequestData JSON
1576
+ */
1577
+ buildRequestData(params) {
1578
+ const { userName, packageName, appName, updateDesc, uploadType } = params;
1579
+ const synchroType = uploadType === "new" ? 0 : 1;
1580
+ const appInfo = {
1581
+ appName,
1582
+ packageName
1583
+ };
1584
+ if (uploadType === "new") {
1585
+ if (params.category != null) appInfo.category = params.category;
1586
+ if (params.keyWords) appInfo.keyWords = params.keyWords;
1587
+ if (params.desc) appInfo.desc = params.desc;
1588
+ if (params.brief) appInfo.brief = params.brief;
1589
+ if (params.privacyUrl) appInfo.privacyUrl = params.privacyUrl;
1590
+ }
1591
+ if (updateDesc) {
1592
+ appInfo.updateDesc = updateDesc;
1593
+ }
1594
+ const requestDataObj = {
1595
+ userName,
1596
+ appInfo,
1597
+ synchroType
1598
+ };
1599
+ const result = JSON.stringify(requestDataObj);
1600
+ logger.info(`[XIAOMI] \u8C03\u8BD5 - RequestData \u5B57\u7B26\u4E32: ${result}`);
1601
+ return result;
1602
+ }
1603
+ /**
1604
+ * 生成只包含 RequestData 的 SIG(用于查询接口)
1605
+ */
1606
+ generateQuerySIG(requestDataMD5, privateKey, publicKey) {
1607
+ const sigObj = {
1608
+ sig: [{ name: "RequestData", hash: requestDataMD5 }],
1609
+ password: privateKey.trim()
1610
+ };
1611
+ const sigJson = JSON.stringify(sigObj);
1612
+ logger.info(`[XIAOMI] \u8C03\u8BD5 - Query SIG \u5F85\u52A0\u5BC6\u5B57\u7B26\u4E32: ${sigJson}`);
1613
+ const encrypted = this.rsaEncryptWithPublicKey(sigJson, publicKey);
1614
+ logger.info(
1615
+ `[XIAOMI] \u8C03\u8BD5 - Query SIG \u52A0\u5BC6\u7ED3\u679C (Hex, \u524D 20\u4F4D): ${encrypted.substring(0, 20)}...`
1616
+ );
1617
+ return encrypted;
1618
+ }
1619
+ /**
1620
+ * 生成包含 RequestData + apk 的加密 SIG 字符串(用于上传接口)
1621
+ */
1622
+ generateUploadSIG(requestDataMD5, apkFileMD5, privateKey, publicKey, extraFiles) {
1623
+ const sigItems = [
1624
+ { name: "RequestData", hash: requestDataMD5 },
1625
+ { name: "apk", hash: apkFileMD5 }
1626
+ ];
1627
+ if (extraFiles) {
1628
+ sigItems.push(...extraFiles);
1629
+ }
1630
+ const sigObj = {
1631
+ sig: sigItems,
1632
+ password: privateKey.trim()
1633
+ };
1634
+ const sigJson = JSON.stringify(sigObj);
1635
+ logger.info(`[XIAOMI] \u8C03\u8BD5 - Upload SIG \u5F85\u52A0\u5BC6\u5B57\u7B26\u4E32: ${sigJson}`);
1636
+ const encrypted = this.rsaEncryptWithPublicKey(sigJson, publicKey);
1637
+ logger.info(
1638
+ `[XIAOMI] \u8C03\u8BD5 - Upload SIG \u52A0\u5BC6\u7ED3\u679C (Hex, \u524D 20\u4F4D): ${encrypted.substring(0, 20)}...`
1639
+ );
1640
+ return encrypted;
1641
+ }
1642
+ /**
1643
+ * 将用户输入的公钥字符串规范化为 PEM 格式
1644
+ */
1645
+ normalizePEM(publicKey) {
1646
+ if (publicKey.includes("-----BEGIN")) {
1647
+ return publicKey.trim();
1648
+ }
1649
+ const clean = publicKey.replace(/[\s\n\r]+/g, "");
1650
+ const lines = clean.match(/.{1,64}/g) || [];
1651
+ return `-----BEGIN PUBLIC KEY-----
1652
+ ${lines.join("\n")}
1653
+ -----END PUBLIC KEY-----`;
1654
+ }
1655
+ validateConfig(config) {
1656
+ if (!config?.publish?.xiaomi?.enable) return false;
1657
+ const x = config.publish.xiaomi;
1658
+ if (!x.auth?.userName || !x.auth?.privateKey) {
1659
+ logger.error("Xiaomi config missing: userName or privateKey");
1660
+ return false;
1661
+ }
1662
+ if (!x.auth?.publicKeyPath) {
1663
+ logger.error("Xiaomi config missing: publicKeyPath");
1664
+ return false;
1665
+ }
1666
+ return true;
1667
+ }
1668
+ canHandle(filePath) {
1669
+ const ext = filePath.split(".").pop()?.toLowerCase();
1670
+ return ext === "apk";
1671
+ }
1672
+ /**
1673
+ * 查询应用状态
1674
+ * 使用 POST /dev/query 接口,需要 SIG 签名认证
1675
+ *
1676
+ * 返回值说明:
1677
+ * - create: true → 需要通过新增方式上传 (synchroType=0)
1678
+ * - updateVersion: true → 可以更新包 (synchroType=1)
1679
+ * - updateInfo: true → 可以仅更新信息 (synchroType=2)
1680
+ */
1681
+ async queryAppStatus(userName, packageName, privateKey, publicKeyObj) {
1682
+ try {
1683
+ const queryData = {
1684
+ packageName,
1685
+ userName
1686
+ };
1687
+ const requestData = JSON.stringify(queryData);
1688
+ logger.info(`Query RequestData: ${requestData}`);
1689
+ const requestDataMD5 = this.calculateStringMD5(requestData);
1690
+ logger.info(`Query RequestData MD5: ${requestDataMD5}`);
1691
+ const sig = this.generateQuerySIG(requestDataMD5, privateKey, publicKeyObj);
1692
+ const params = new URLSearchParams();
1693
+ params.append("RequestData", requestData);
1694
+ params.append("SIG", sig);
1695
+ const response = await axios3.post(_XiaomiUploader.QUERY_API, params.toString(), {
1696
+ headers: {
1697
+ "Content-Type": "application/x-www-form-urlencoded"
1698
+ },
1699
+ timeout: 15e3
1700
+ });
1701
+ const data = response.data;
1702
+ logger.info(`\u67E5\u8BE2\u5E94\u7528\u54CD\u5E94: ${JSON.stringify(data)}`);
1703
+ if (data?.result === -20014) {
1704
+ throw new Error(
1705
+ `\u5C0F\u7C73\u8BA4\u8BC1\u5931\u8D25: \u5BC6\u7801\u9519\u8BEF (result=-20014)\u3002\u8BF7\u68C0\u67E5 publish.xiaomi.auth.privateKey \u662F\u5426\u4E3A\u6700\u65B0\u7684 API \u79C1\u94A5\u3002`
1706
+ );
1707
+ }
1708
+ if (data?.result !== 0) {
1709
+ logger.warn(`\u67E5\u8BE2\u8FD4\u56DE\u975E\u96F6: result=${data?.result}, ${data?.message}`);
1710
+ return { type: "new", queried: false };
1711
+ }
1712
+ const appInfo = data.appInfo || null;
1713
+ if (data.updateVersion === true) {
1714
+ return { type: "update", queried: true, appInfo };
1715
+ }
1716
+ if (data.create === true) {
1717
+ logger.info("\u5E94\u7528\u5DF2\u5728\u540E\u53F0\u521B\u5EFA\u4F46\u5C1A\u672A\u4E0A\u4F20\u8FC7\u5305\uFF0C\u5C06\u8FDB\u5165\u9996\u6B21\u63D0\u5BA1\u6A21\u5F0F");
1718
+ return { type: "new", queried: true, appInfo };
1719
+ }
1720
+ return { type: "update", queried: true, appInfo };
1721
+ } catch (error) {
1722
+ if (error.message.includes("\u5C0F\u7C73\u8BA4\u8BC1\u5931\u8D25")) {
1723
+ throw error;
1724
+ }
1725
+ logger.warn(`\u67E5\u8BE2\u5E94\u7528\u8FDE\u63A5\u5F02\u5E38: ${error.message}\uFF0C\u5C06\u63A8\u6D4B\u4E3A\u65B0\u589E\u5E94\u7528\u6A21\u5F0F`);
1726
+ return { type: "new", queried: false };
1727
+ }
1728
+ }
1729
+ /**
1730
+ * 查询小米应用商店分类列表
1731
+ * POST /dev/category, 无需参数
1732
+ */
1733
+ async queryCategories() {
1734
+ try {
1735
+ const response = await axios3.post(_XiaomiUploader.CATEGORY_API, null, {
1736
+ timeout: 1e4
1737
+ });
1738
+ const data = response.data;
1739
+ if (data?.result === 0 && Array.isArray(data.categories)) {
1740
+ return data.categories;
1741
+ }
1742
+ logger.warn(`\u83B7\u53D6\u5206\u7C7B\u5217\u8868\u5931\u8D25: ${JSON.stringify(data)}`);
1743
+ return null;
1744
+ } catch (error) {
1745
+ logger.warn(`\u83B7\u53D6\u5206\u7C7B\u5217\u8868\u5F02\u5E38: ${error.message}`);
1746
+ return null;
1747
+ }
1748
+ }
1749
+ async upload(filePath, config, metadata) {
1750
+ const xiaomiConfig = config.publish?.xiaomi;
1751
+ const { userName, privateKey, publicKeyPath } = xiaomiConfig.auth;
1752
+ const updateDesc = metadata.changelog || xiaomiConfig?.description || "App Update";
1753
+ const retryConfig = config.retry;
1754
+ if (!fs6.existsSync(filePath)) {
1755
+ return {
1756
+ platform: "xiaomi",
1757
+ success: false,
1758
+ message: `\u6587\u4EF6\u4E0D\u5B58\u5728: ${filePath}`
1759
+ };
1760
+ }
1761
+ const resolvedPublicKey = await this.resolvePublicKey(publicKeyPath);
1762
+ if (!resolvedPublicKey) {
1763
+ return {
1764
+ platform: "xiaomi",
1765
+ success: false,
1766
+ message: "\u65E0\u6CD5\u83B7\u53D6 RSA \u516C\u94A5: publicKeyPath \u672A\u63D0\u4F9B\u6216\u6587\u4EF6\u4E0D\u5B58\u5728"
1767
+ };
1768
+ }
1769
+ const packageName = xiaomiConfig.packageName || this.inferPackageName(filePath);
1770
+ if (!packageName) {
1771
+ return {
1772
+ platform: "xiaomi",
1773
+ success: false,
1774
+ message: "\u7F3A\u5C11 packageName \u914D\u7F6E, \u4E14\u65E0\u6CD5\u4ECE\u6587\u4EF6\u540D\u63A8\u65AD\u5E94\u7528\u5305\u540D"
1775
+ };
1776
+ }
1777
+ const appName = xiaomiConfig.appName || this.inferAppName(packageName);
1778
+ if (!appName) {
1779
+ return {
1780
+ platform: "xiaomi",
1781
+ success: false,
1782
+ message: "\u7F3A\u5C11 appName \u914D\u7F6E, \u4E14\u65E0\u6CD5\u4ECE\u5305\u540D\u63A8\u65AD\u5E94\u7528\u540D\u79F0"
1783
+ };
1784
+ }
1785
+ logger.info("\u5F00\u59CB\u4E0A\u4F20\u5230\u5C0F\u7C73\u5E94\u7528\u5546\u5E97...");
1786
+ logger.info(`\u6587\u4EF6: ${filePath}`);
1787
+ logger.info(`\u5305\u540D: ${packageName}`);
1788
+ logger.info(`\u5E94\u7528\u540D: ${appName}`);
1789
+ const publicKeyObj = this.extractPublicKey(resolvedPublicKey);
1790
+ const configUploadType = xiaomiConfig.uploadType || "auto";
1791
+ let uploadType;
1792
+ let existingAppInfo = null;
1793
+ if (configUploadType === "auto") {
1794
+ logger.info("\u6B63\u5728\u67E5\u8BE2\u5E94\u7528\u4FE1\u606F...");
1795
+ const status = await this.queryAppStatus(userName, packageName, privateKey, publicKeyObj);
1796
+ uploadType = status.type;
1797
+ existingAppInfo = status.appInfo;
1798
+ } else {
1799
+ uploadType = configUploadType;
1800
+ }
1801
+ const uploadTypeDesc = uploadType === "update" ? "\u5E94\u7528\u66F4\u65B0 (synchroType=1)" : "\u65B0\u589E\u5E94\u7528 (synchroType=0)";
1802
+ logger.info(`\u4E0A\u4F20\u7C7B\u578B: ${uploadTypeDesc}`);
1803
+ if (uploadType === "new" && xiaomiConfig.uploadType === "new") {
1804
+ const missing = [];
1805
+ if (xiaomiConfig.category == null) missing.push("category (\u5206\u7C7BID)");
1806
+ if (!xiaomiConfig.desc) missing.push("desc (\u5E94\u7528\u4ECB\u7ECD)");
1807
+ if (missing.length > 0) {
1808
+ return {
1809
+ platform: "xiaomi",
1810
+ success: false,
1811
+ message: `\u9996\u6B21\u63D0\u5BA1\u6A21\u5F0F\u7F3A\u5C11\u5FC5\u586B\u5B57\u6BB5: ${missing.join(", ")}\u3002\u8BF7\u5728\u540E\u53F0\u8865\u5168\u6216\u5728\u914D\u7F6E\u4E2D\u6DFB\u52A0\u3002`
1812
+ };
1813
+ }
1814
+ }
1815
+ try {
1816
+ const retryStrategy = createUploadRetryStrategy(retryConfig);
1817
+ const result = await retryStrategy.execute(
1818
+ () => this.performUpload({
1819
+ filePath,
1820
+ userName,
1821
+ privateKey,
1822
+ publicKey: resolvedPublicKey,
1823
+ packageName,
1824
+ appName,
1825
+ updateDesc,
1826
+ uploadType,
1827
+ category: xiaomiConfig.category || existingAppInfo?.category,
1828
+ keyWords: xiaomiConfig.keyWords || existingAppInfo?.keyWords,
1829
+ desc: xiaomiConfig.desc || existingAppInfo?.desc,
1830
+ brief: xiaomiConfig.brief || existingAppInfo?.brief,
1831
+ privacyUrl: xiaomiConfig.privacyUrl || existingAppInfo?.privacyUrl,
1832
+ assets: xiaomiConfig.assets
1833
+ }),
1834
+ "Xiaomi push upload"
1835
+ );
1836
+ if (!result.success) {
1837
+ throw result.error || new Error("Upload failed");
1838
+ }
1839
+ logger.success("\u4E0A\u4F20\u5230\u5C0F\u7C73\u5E94\u7528\u5546\u5E97\u6210\u529F!");
1840
+ return {
1841
+ platform: "xiaomi",
1842
+ success: true,
1843
+ message: "\u4E0A\u4F20\u6210\u529F, \u7B49\u5F85\u5BA1\u6838",
1844
+ data: result.data,
1845
+ consoleUrl: "https://dev.mi.com/distribute/app/details"
1846
+ };
1847
+ } catch (error) {
1848
+ logger.error(`\u4E0A\u4F20\u5230\u5C0F\u7C73\u5931\u8D25: ${error.message}`);
1849
+ if (error.response?.data) {
1850
+ logger.info(`\u9519\u8BEF\u8BE6\u60C5: ${JSON.stringify(error.response.data)}`);
1851
+ }
1852
+ return {
1853
+ platform: "xiaomi",
1854
+ success: false,
1855
+ message: error.message,
1856
+ error
1857
+ };
1858
+ }
1859
+ }
1860
+ /**
1861
+ * 执行实际的上传操作
1862
+ */
1863
+ async performUpload(params) {
1864
+ const {
1865
+ filePath,
1866
+ userName,
1867
+ privateKey,
1868
+ publicKey,
1869
+ packageName,
1870
+ appName,
1871
+ updateDesc,
1872
+ uploadType,
1873
+ category,
1874
+ keyWords,
1875
+ desc,
1876
+ brief,
1877
+ privacyUrl,
1878
+ assets
1879
+ } = params;
1880
+ const publicKeyObj = this.extractPublicKey(publicKey);
1881
+ const requestData = this.buildRequestData({
1882
+ userName,
1883
+ packageName,
1884
+ appName,
1885
+ updateDesc,
1886
+ uploadType,
1887
+ category,
1888
+ keyWords,
1889
+ desc,
1890
+ brief,
1891
+ privacyUrl
1892
+ });
1893
+ logger.info("RequestData \u5DF2\u6784\u5EFA");
1894
+ logger.info(`RequestData: ${requestData}`);
1895
+ const requestDataMD5 = this.calculateStringMD5(requestData);
1896
+ const apkFileMD5 = await this.calculateFileMD5(filePath);
1897
+ logger.info(`APK MD5: ${apkFileMD5}`);
1898
+ const extraSigItems = [];
1899
+ let iconPath;
1900
+ if (assets?.icon && fs6.existsSync(assets.icon)) {
1901
+ iconPath = assets.icon;
1902
+ const iconMD5 = await this.calculateFileMD5(iconPath);
1903
+ extraSigItems.push({ name: "icon", hash: iconMD5 });
1904
+ }
1905
+ const screenshotPaths = [];
1906
+ if (assets?.screenshots) {
1907
+ for (let i = 0; i < assets.screenshots.length && i < 4; i++) {
1908
+ const ssPath = assets.screenshots[i];
1909
+ if (fs6.existsSync(ssPath)) {
1910
+ screenshotPaths.push(ssPath);
1911
+ const ssMD5 = await this.calculateFileMD5(ssPath);
1912
+ extraSigItems.push({ name: `screenshot_${i + 1}`, hash: ssMD5 });
1913
+ }
1914
+ }
1915
+ }
1916
+ const sig = this.generateUploadSIG(
1917
+ requestDataMD5,
1918
+ apkFileMD5,
1919
+ privateKey,
1920
+ publicKeyObj,
1921
+ extraSigItems.length > 0 ? extraSigItems : void 0
1922
+ );
1923
+ logger.info("SIG \u7B7E\u540D\u5DF2\u751F\u6210");
1924
+ const form = new FormData3();
1925
+ form.append("RequestData", requestData);
1926
+ form.append("SIG", sig);
1927
+ form.append("apk", fs6.createReadStream(filePath));
1928
+ if (iconPath) {
1929
+ form.append("icon", fs6.createReadStream(iconPath));
1930
+ logger.info(`\u9644\u52A0 icon: ${iconPath}`);
1931
+ }
1932
+ for (let i = 0; i < screenshotPaths.length; i++) {
1933
+ form.append(`screenshot_${i + 1}`, fs6.createReadStream(screenshotPaths[i]));
1934
+ logger.info(`\u9644\u52A0 screenshot_${i + 1}: ${screenshotPaths[i]}`);
1935
+ }
1936
+ logger.info(`POST ${_XiaomiUploader.PUSH_API}`);
1937
+ const response = await axios3.post(_XiaomiUploader.PUSH_API, form, {
1938
+ headers: {
1939
+ ...form.getHeaders()
1940
+ },
1941
+ maxContentLength: Infinity,
1942
+ maxBodyLength: Infinity,
1943
+ timeout: 6e4
1944
+ // 60 秒请求超时
1945
+ });
1946
+ const data = response.data;
1947
+ logger.info(`\u5C0F\u7C73 API \u539F\u59CB\u54CD\u5E94: ${JSON.stringify(data)}`);
1948
+ if (data?.result !== 0) {
1949
+ const errMsg = data?.message || data?.msg || JSON.stringify(data);
1950
+ throw new Error(`\u5C0F\u7C73 API \u8FD4\u56DE\u9519\u8BEF (result=${data?.result}): ${errMsg}`);
1951
+ }
1952
+ logger.info(`\u5C0F\u7C73 API \u54CD\u5E94: ${JSON.stringify(data)}`);
1953
+ return data;
1954
+ }
1955
+ /**
1956
+ * 解析公钥: 优先使用内容字段, 其次从文件路径读取
1957
+ */
1958
+ async resolvePublicKey(publicKeyPath) {
1959
+ if (publicKeyPath) {
1960
+ if (!fs6.existsSync(publicKeyPath)) {
1961
+ logger.error(`\u516C\u94A5\u6587\u4EF6\u4E0D\u5B58\u5728: ${publicKeyPath}`);
1962
+ return null;
1963
+ }
1964
+ return await fs6.readFile(publicKeyPath);
1965
+ }
1966
+ return null;
1967
+ }
1968
+ /**
1969
+ * 尝试从文件名推断包名
1970
+ * 例如: com.example.app-release.apk → com.example.app
1971
+ */
1972
+ inferPackageName(filePath) {
1973
+ const fileName = filePath.split("/").pop()?.split("\\").pop() || "";
1974
+ const match = fileName.match(/^([\w.]+?)(?:-(?:release|debug|unsigned))?\.apk$/i);
1975
+ if (match && match[1].includes(".")) {
1976
+ return match[1];
1977
+ }
1978
+ return null;
1979
+ }
1980
+ /**
1981
+ * 从包名推断应用名称
1982
+ * 例如: com.example.app → app 或 com.app → app
1983
+ */
1984
+ inferAppName(packageName) {
1985
+ const parts = packageName.split(".");
1986
+ if (parts.length === 0) return null;
1987
+ const lastPart = parts[parts.length - 1];
1988
+ const humanized = lastPart.replace(/([a-z])([A-Z])/g, "$1 $2").replace(/^./, (c) => c.toUpperCase());
1989
+ return humanized || null;
1990
+ }
1991
+ };
1992
+
1993
+ // src/adapters/apple_store_uploader.ts
1994
+ import fs7 from "fs-extra";
1995
+ import path4 from "path";
1996
+ import { exec as exec2 } from "child_process";
1997
+ import { promisify as promisify2 } from "util";
1998
+ import axios4 from "axios";
1999
+ var execAsync = promisify2(exec2);
2000
+ var APP_STORE_CONNECT_API = "https://api.appstoreconnect.apple.com/v1";
2001
+ var TRANSPORTER_APP_PATH = "/Applications/Transporter.app/Contents/itms/bin/iTMSTransporter";
2002
+ var AppleStoreUploader = class {
2003
+ name = "AppStore";
2004
+ /**
2005
+ * 验证配置是否有效
2006
+ * 至少需要一种认证方式:
2007
+ * - appleId + appPassword(CLI 上传)
2008
+ * - apiKeyId + apiIssuerId + privateKey(API 调用,也可用于 CLI 上传)
2009
+ */
2010
+ validateConfig(config) {
2011
+ if (!config?.publish?.app_store?.enable) return false;
2012
+ const auth = config.publish.app_store?.auth;
2013
+ const hasCliAuth = auth?.appleId && auth?.appPassword;
2014
+ const hasApiAuth = this.hasApiCredentials(auth);
2015
+ if (!hasCliAuth && !hasApiAuth) {
2016
+ logger.error(
2017
+ "Apple \u914D\u7F6E\u7F3A\u5931\uFF1A\u9700\u8981 (appleId + appPassword) \u6216 (apiKeyId + apiIssuerId + privateKey) \u4E2D\u7684\u4E00\u79CD\u3002"
2018
+ );
2019
+ return false;
2020
+ }
2021
+ return true;
2022
+ }
2023
+ /**
2024
+ * 判断是否支持处理该文件
2025
+ */
2026
+ canHandle(filePath) {
2027
+ const ext = filePath.split(".").pop()?.toLowerCase();
2028
+ return ext === "ipa";
2029
+ }
2030
+ /**
2031
+ * 执行上传流程
2032
+ */
2033
+ async upload(filePath, config, metadata) {
2034
+ const appConfig = config.publish.app_store;
2035
+ const auth = appConfig.auth;
2036
+ const retryConfig = config.retry;
2037
+ logger.info("\u5F00\u59CB\u4E0A\u4F20\u5230 App Store...");
2038
+ try {
2039
+ const exists = await fs7.pathExists(filePath);
2040
+ if (!exists) {
2041
+ throw new Error(`IPA \u6587\u4EF6\u672A\u627E\u5230: ${filePath}`);
2042
+ }
2043
+ const fileSize = (await fs7.stat(filePath)).size;
2044
+ logger.info(`IPA \u6587\u4EF6\u5927\u5C0F: ${(fileSize / (1024 * 1024)).toFixed(2)} MB`);
2045
+ const retryStrategy = createUploadRetryStrategy(retryConfig);
2046
+ const uploadResult = await retryStrategy.execute(
2047
+ () => this.uploadWithAvailableTool(filePath, auth),
2048
+ "App Store \u4E0A\u4F20"
2049
+ );
2050
+ if (!uploadResult.success) {
2051
+ throw uploadResult.error || new Error("\u4E0A\u4F20\u5931\u8D25");
2052
+ }
2053
+ logger.success("App Store IPA \u4E0A\u4F20\u6210\u529F\uFF01");
2054
+ if (metadata.changelog && this.hasApiCredentials(auth)) {
2055
+ await this.tryUpdateReleaseNotes(auth, appConfig.appId, metadata.changelog, retryStrategy);
2056
+ } else if (metadata.changelog && !this.hasApiCredentials(auth)) {
2057
+ logger.info(
2058
+ "\u8DF3\u8FC7\u66F4\u65B0\u53D1\u884C\u8BF4\u660E\uFF1A\u672A\u914D\u7F6E API Key \u51ED\u636E\u3002\u5982\u9700\u542F\u7528\uFF0C\u8BF7\u5728\u914D\u7F6E\u4E2D\u6DFB\u52A0 apiKeyId + apiIssuerId + privateKeyPath\u3002"
2059
+ );
2060
+ }
2061
+ return {
2062
+ platform: "app_store",
2063
+ success: true,
2064
+ message: "\u4E0A\u4F20\u6210\u529F\u3002\u8BF7\u524D\u5F80 App Store Connect \u67E5\u770B\u3002",
2065
+ url: "https://appstoreconnect.apple.com/apps",
2066
+ consoleUrl: "https://appstoreconnect.apple.com/apps"
2067
+ };
2068
+ } catch (error) {
2069
+ return {
2070
+ platform: "app_store",
2071
+ success: false,
2072
+ message: error.message,
2073
+ error
2074
+ };
2075
+ }
2076
+ }
2077
+ // ───── CLI 上传 ─────
2078
+ /**
2079
+ * 使用可用的工具上传
2080
+ * 策略: 优先 Transporter → 降级 altool → 都失败
2081
+ */
2082
+ async uploadWithAvailableTool(ipaPath, auth) {
2083
+ const appleId = auth.appleId;
2084
+ const appPassword = auth.appPassword;
2085
+ try {
2086
+ logger.info("\u6B63\u5728\u5C1D\u8BD5\u4F7F\u7528 Transporter CLI...");
2087
+ const transporterTool = await this.resolveToolPath("transporter");
2088
+ if (transporterTool) {
2089
+ await this.uploadViaTransporter(transporterTool, ipaPath, appleId, appPassword);
2090
+ logger.success("\u901A\u8FC7 Transporter \u4E0A\u4F20\u5B8C\u6210");
2091
+ return;
2092
+ }
2093
+ } catch (error) {
2094
+ logger.warn(`Transporter \u8C03\u7528\u5931\u8D25: ${error.message}\u3002\u5C1D\u8BD5\u964D\u7EA7\u5230 altool...`);
2095
+ }
2096
+ let altoolTool = null;
2097
+ try {
2098
+ logger.info("\u6B63\u5728\u5C1D\u8BD5\u4F7F\u7528 xcrun altool...");
2099
+ altoolTool = await this.resolveToolPath("altool");
2100
+ } catch (error) {
2101
+ logger.warn(`altool \u68C0\u6D4B\u5931\u8D25: ${error.message}`);
2102
+ }
2103
+ if (altoolTool) {
2104
+ await this.uploadViaAltool(altoolTool, ipaPath, appleId, appPassword);
2105
+ logger.success("\u901A\u8FC7 altool \u4E0A\u4F20\u5B8C\u6210");
2106
+ return;
2107
+ }
2108
+ throw new Error(this.getToolInstallationGuide());
2109
+ }
2110
+ /**
2111
+ * 解析工具路径结果
2112
+ */
2113
+ async resolveToolPath(tool) {
2114
+ if (tool === "transporter") {
2115
+ try {
2116
+ await execAsync("transporter -version", { timeout: 5e3 });
2117
+ return { command: "transporter", useShell: false };
2118
+ } catch {
2119
+ }
2120
+ if (await fs7.pathExists(TRANSPORTER_APP_PATH)) {
2121
+ return { command: `"${TRANSPORTER_APP_PATH}"`, useShell: false };
2122
+ }
2123
+ } else {
2124
+ const xcrunPath = await fs7.pathExists("/usr/bin/xcrun") ? "/usr/bin/xcrun" : "xcrun";
2125
+ try {
2126
+ await execAsync(`${xcrunPath} altool --version`, {
2127
+ timeout: 1e4
2128
+ });
2129
+ return { command: `${xcrunPath} altool`, useShell: false };
2130
+ } catch (error) {
2131
+ logger.warn(
2132
+ `[AppleStore] Direct altool check failed: ${error.message}. Trying shell mode...`
2133
+ );
2134
+ }
2135
+ try {
2136
+ await execAsync(`bash -l -c "xcrun altool --version"`, {
2137
+ timeout: 1e4
2138
+ });
2139
+ return { command: "xcrun altool", useShell: true };
2140
+ } catch (error) {
2141
+ logger.warn(`[AppleStore] Shell altool check failed: ${error.message}`);
2142
+ }
2143
+ return null;
2144
+ }
2145
+ return null;
2146
+ }
2147
+ /**
2148
+ * 通过 Transporter CLI 上传
2149
+ */
2150
+ async uploadViaTransporter(tool, ipaPath, appleId, appPassword) {
2151
+ const command = [
2152
+ tool.command,
2153
+ "-uploadFile",
2154
+ `"${ipaPath}"`,
2155
+ "-username",
2156
+ appleId,
2157
+ "-password",
2158
+ appPassword,
2159
+ "-showTransferRate"
2160
+ ].join(" ");
2161
+ logger.info(`[Transporter] Uploading: ${path4.basename(ipaPath)}`);
2162
+ try {
2163
+ const { stdout, stderr } = await execAsync(command, {
2164
+ timeout: 30 * 60 * 1e3,
2165
+ // 30 分钟
2166
+ maxBuffer: 10 * 1024 * 1024
2167
+ // 10MB
2168
+ });
2169
+ if (stdout) {
2170
+ logger.info(`[Transporter] ${stdout}`);
2171
+ }
2172
+ if (stderr && (stderr.includes("error") || stderr.includes("failed") || stderr.includes("ERROR"))) {
2173
+ const errorMessage = this.parseAltoolError(stderr);
2174
+ throw new Error(errorMessage);
2175
+ }
2176
+ } catch (error) {
2177
+ throw new Error(`Transporter upload failed: ${error.message}
2178
+ Stderr: ${error.stderr || ""}`);
2179
+ }
2180
+ }
2181
+ /**
2182
+ * 通过 altool 上传
2183
+ */
2184
+ async uploadViaAltool(tool, ipaPath, appleId, appPassword) {
2185
+ const args = [
2186
+ "xcrun altool",
2187
+ // 占位符
2188
+ "--upload-app",
2189
+ "-f",
2190
+ "__IPA_PATH__",
2191
+ // 占位符
2192
+ "-t",
2193
+ "ios",
2194
+ "-u",
2195
+ appleId,
2196
+ "-p",
2197
+ appPassword
2198
+ // '--verbose', // 禁用 verbose
2199
+ ];
2200
+ let command = "";
2201
+ if (tool.useShell) {
2202
+ const innerCommand = args.slice(1).join(" ").replace("__IPA_PATH__", `\\"${ipaPath}\\"`);
2203
+ command = `bash -l -c "${tool.command} ${innerCommand}"`;
2204
+ } else {
2205
+ const innerArgs = args.map((arg) => {
2206
+ if (arg === "xcrun altool") return tool.command;
2207
+ if (arg === "__IPA_PATH__") return `"${ipaPath}"`;
2208
+ return arg;
2209
+ });
2210
+ command = innerArgs.join(" ");
2211
+ }
2212
+ logger.info(`[altool] Uploading: ${path4.basename(ipaPath)}`);
2213
+ logger.info(`[altool] Command prefix: ${tool.command}`);
2214
+ try {
2215
+ const { stdout, stderr } = await execAsync(command, {
2216
+ timeout: 30 * 60 * 1e3,
2217
+ maxBuffer: 10 * 1024 * 1024
2218
+ });
2219
+ if (stdout) {
2220
+ if (stdout.includes("No errors uploading") || stdout.includes("Request UUID")) {
2221
+ logger.info(`[altool] ${stdout}`);
2222
+ }
2223
+ }
2224
+ if (stderr && (stderr.includes("error") || stderr.includes("failed") || stderr.includes("ERROR"))) {
2225
+ const errorMessage = this.parseAltoolError(stderr);
2226
+ throw new Error(errorMessage);
2227
+ }
2228
+ } catch (error) {
2229
+ const errorMsg = this.parseAltoolError(error.stderr || error.message);
2230
+ throw new Error(errorMsg);
2231
+ }
2232
+ }
2233
+ /**
2234
+ * 解析 altool/Transporter 错误信息,翻译为用户友好的语言
2235
+ */
2236
+ parseAltoolError(stderr) {
2237
+ if (!stderr) return "Unknown error";
2238
+ if (stderr.includes("previousBundleVersion") || stderr.includes("ENTITY_ERROR.ATTRIBUTE.INVALID.DUPLICATE") || stderr.includes("Redundant Binary Upload") || stderr.includes("already been used")) {
2239
+ const match = stderr.match(/previously uploaded version: ‘(.*?)’/);
2240
+ const prevVersion = match ? match[1] : "unknown";
2241
+ return `\u7248\u672C\u53F7\u51B2\u7A81 (Version Conflict): \u6784\u5EFA\u7248\u672C ${prevVersion} \u5DF2\u5B58\u5728\u4E8E App Store Connect\u3002
2242
+ \u89E3\u51B3\u65B9\u6848: \u8BF7\u5728 pubspec.yaml \u4E2D\u589E\u52A0 'version: x.y.z+N' \u4E2D\u7684 N (build number)\uFF0C\u7136\u540E\u91CD\u65B0\u6784\u5EFA IPA\u3002`;
2243
+ }
2244
+ if (stderr.includes("Authentication failed") || stderr.includes("password is incorrect") || stderr.includes("NOT_AUTHORIZED")) {
2245
+ return `\u8BA4\u8BC1\u5931\u8D25 (Auth Failed): Apple ID \u6216 App-specific Password \u9519\u8BEF\u3002
2246
+ \u89E3\u51B3\u65B9\u6848: \u8BF7\u68C0\u67E5\u914D\u7F6E\u3002\u6CE8\u610F\u5FC5\u987B\u4F7F\u7528 App \u4E13\u7528\u5BC6\u7801\uFF0C\u4E0D\u80FD\u4F7F\u7528 Apple ID \u767B\u5F55\u5BC6\u7801\u3002`;
2247
+ }
2248
+ if (stderr.includes("Asset validation failed")) {
2249
+ return `\u8D44\u4EA7\u9A8C\u8BC1\u5931\u8D25 (Validation Failed): IPA \u6587\u4EF6\u53EF\u80FD\u4E0D\u7B26\u5408 App Store \u8981\u6C42\u3002
2250
+ \u8BE6\u7EC6\u9519\u8BEF: ${stderr}`;
2251
+ }
2252
+ return `\u4E0A\u4F20\u5DE5\u5177\u62A5\u9519: ${stderr.substring(0, 800)}...`;
2253
+ }
2254
+ // ───── 发行说明 API ─────
2255
+ /**
2256
+ * 检查是否配置了 API Key 凭据
2257
+ */
2258
+ hasApiCredentials(auth) {
2259
+ return !!(auth?.apiKeyId && auth?.apiIssuerId && (auth?.privateKeyPath || auth?.privateKeyContent));
2260
+ }
2261
+ /**
2262
+ * 创建 JWT 生成器
2263
+ */
2264
+ async createJWTGenerator(auth) {
2265
+ if (auth.privateKeyContent) {
2266
+ return AppleJWTGenerator.fromContent(auth.apiIssuerId, auth.apiKeyId, auth.privateKeyContent);
2267
+ }
2268
+ return AppleJWTGenerator.fromFile(auth.apiIssuerId, auth.apiKeyId, auth.privateKeyPath);
2269
+ }
2270
+ /**
2271
+ * 获取 API 请求头
2272
+ */
2273
+ apiHeaders(token) {
2274
+ return {
2275
+ Authorization: `Bearer ${token}`,
2276
+ "Content-Type": "application/json"
2277
+ };
2278
+ }
2279
+ /**
2280
+ * 尝试更新发行说明(失败不影响上传结果)
2281
+ */
2282
+ async tryUpdateReleaseNotes(auth, appId, changelog, retryStrategy) {
2283
+ if (!appId) {
2284
+ logger.info(
2285
+ "\u8DF3\u8FC7\u66F4\u65B0\u53D1\u884C\u8BF4\u660E\uFF1A\u672A\u914D\u7F6E App ID\u3002\u8BF7\u6DFB\u52A0 app_store.appId \u4EE5\u542F\u7528\u81EA\u52A8\u66F4\u65B0\u53D1\u884C\u8BF4\u660E\u3002"
2286
+ );
2287
+ return;
2288
+ }
2289
+ try {
2290
+ logger.info("\u6B63\u5728\u901A\u8FC7 App Store Connect API \u66F4\u65B0\u53D1\u884C\u8BF4\u660E...");
2291
+ const jwtGenerator = await this.createJWTGenerator(auth);
2292
+ const token = jwtGenerator.generate();
2293
+ const version = await this.getPrepareForSubmissionVersion(token, appId);
2294
+ if (!version) {
2295
+ logger.warn(
2296
+ '\u672A\u627E\u5230\u5904\u4E8E"\u51C6\u5907\u63D0\u4EA4 (PREPARE_FOR_SUBMISSION)"\u72B6\u6001\u7684\u7248\u672C\u3002\u5DF2\u8DF3\u8FC7\u66F4\u65B0\u53D1\u884C\u8BF4\u660E\u3002\u8BF7\u5728 App Store Connect \u624B\u52A8\u66F4\u65B0\u3002'
2297
+ );
2298
+ return;
2299
+ }
2300
+ const localizations = await this.getVersionLocalizations(token, version.id);
2301
+ if (localizations.length === 0) {
2302
+ logger.warn("\u8BE5\u7248\u672C\u6CA1\u6709\u627E\u5230\u672C\u5730\u5316\u4FE1\u606F\u3002\u8DF3\u8FC7\u66F4\u65B0\u53D1\u884C\u8BF4\u660E\u3002");
2303
+ return;
2304
+ }
2305
+ for (const loc of localizations) {
2306
+ const locale = loc.attributes?.locale || "unknown";
2307
+ await retryStrategy.execute(
2308
+ () => this.updateLocalizationWhatsNew(token, loc.id, changelog),
2309
+ `\u66F4\u65B0\u53D1\u884C\u8BF4\u660E (${locale})`
2310
+ );
2311
+ logger.info(`\u5DF2\u66F4\u65B0\u53D1\u884C\u8BF4\u660E: ${locale}`);
2312
+ }
2313
+ logger.success("\u6240\u6709\u53D1\u884C\u8BF4\u660E\u66F4\u65B0\u6210\u529F\uFF01");
2314
+ } catch (error) {
2315
+ logger.warn(`\u66F4\u65B0\u53D1\u884C\u8BF4\u660E\u5931\u8D25: ${error.message}\u3002IPA \u4E0A\u4F20\u5DF2\u6210\u529F\u3002\u8BF7\u624B\u52A8\u66F4\u65B0\u53D1\u884C\u8BF4\u660E\u3002`);
2316
+ }
2317
+ }
2318
+ /**
2319
+ * 获取处于"准备提交"状态的版本
2320
+ * 只有此状态下的版本才能修改发行说明
2321
+ */
2322
+ async getPrepareForSubmissionVersion(token, appId) {
2323
+ const res = await axios4.get(`${APP_STORE_CONNECT_API}/apps/${appId}/appStoreVersions`, {
2324
+ params: {
2325
+ "filter[appStoreState]": "PREPARE_FOR_SUBMISSION",
2326
+ limit: 1
2327
+ },
2328
+ headers: this.apiHeaders(token)
2329
+ });
2330
+ const versions = res.data?.data;
2331
+ if (versions && versions.length > 0) {
2332
+ logger.info(
2333
+ `Found version: ${versions[0].attributes?.versionString} (PREPARE_FOR_SUBMISSION)`
2334
+ );
2335
+ return versions[0];
2336
+ }
2337
+ return null;
2338
+ }
2339
+ /**
2340
+ * 获取版本的本地化信息列表
2341
+ */
2342
+ async getVersionLocalizations(token, versionId) {
2343
+ const res = await axios4.get(
2344
+ `${APP_STORE_CONNECT_API}/appStoreVersions/${versionId}/appStoreVersionLocalizations`,
2345
+ {
2346
+ headers: this.apiHeaders(token)
2347
+ }
2348
+ );
2349
+ return res.data?.data || [];
2350
+ }
2351
+ /**
2352
+ * 更新本地化版本的 What's New 内容
2353
+ */
2354
+ async updateLocalizationWhatsNew(token, localizationId, whatsNew) {
2355
+ await axios4.patch(
2356
+ `${APP_STORE_CONNECT_API}/appStoreVersionLocalizations/${localizationId}`,
2357
+ {
2358
+ data: {
2359
+ type: "appStoreVersionLocalizations",
2360
+ id: localizationId,
2361
+ attributes: {
2362
+ whatsNew
2363
+ }
2364
+ }
2365
+ },
2366
+ {
2367
+ headers: this.apiHeaders(token)
2368
+ }
2369
+ );
2370
+ }
2371
+ // ───── 工具安装指引 ─────
2372
+ /**
2373
+ * 获取工具安装指引
2374
+ */
2375
+ getToolInstallationGuide() {
2376
+ return `
2377
+ Neither Transporter nor altool CLI found. Please install one:
2378
+
2379
+ \u3010\u63A8\u8350\u3011 Transporter CLI (\u5B98\u65B9\u63A8\u8350):
2380
+ Mac: https://apps.apple.com/app/transporter/id1450874784
2381
+ Windows: https://www.microsoft.com/store/apps/9NBLGGH52RM5
2382
+
2383
+ \u3010\u5907\u9009\u3011 xcrun altool (Xcode \u81EA\u5E26):
2384
+ Install Xcode Command Line Tools:
2385
+ xcode-select --install
2386
+
2387
+ Note:
2388
+ - \u9700\u8981\u4F7F\u7528 Apple ID \u548C App-specific Password (\u5728 appleid.apple.com \u751F\u6210)
2389
+ - \u4E0D\u80FD\u4F7F\u7528\u666E\u901A Apple ID \u5BC6\u7801
2390
+ `.trim();
2391
+ }
2392
+ };
2393
+
2394
+ // src/adapters/testflight_uploader.ts
2395
+ import fs8 from "fs-extra";
2396
+ import axios5 from "axios";
2397
+ import FormData4 from "form-data";
2398
+ var TestFlightUploader = class _TestFlightUploader {
2399
+ name = "TestFlight";
2400
+ static API_ROOT = "https://api.appstoreconnect.apple.com/v1";
2401
+ static API_TIMEOUT = 3e4;
2402
+ static BUILD_PROCESSING_TIMEOUT = 10 * 60 * 1e3;
2403
+ // 10 minutes
2404
+ static BUILD_POLLING_INTERVAL = 10 * 1e3;
2405
+ // 10 seconds
2406
+ /**
2407
+ * 验证配置
2408
+ * @param config 配置对象
2409
+ */
2410
+ validateConfig(config) {
2411
+ if (!config?.publish?.app_store?.enable) return false;
2412
+ if (config.publish.app_store.mode !== "testflight") return false;
2413
+ const auth = config.publish.app_store.auth;
2414
+ if (!auth?.apiKeyId || !auth?.apiIssuerId) {
2415
+ logger.error("TestFlight config missing: apiKeyId or apiIssuerId");
2416
+ return false;
2417
+ }
2418
+ if (!auth.privateKeyPath && !auth.privateKeyContent) {
2419
+ logger.error("TestFlight config missing: privateKeyPath or privateKeyContent");
2420
+ return false;
2421
+ }
2422
+ return true;
2423
+ }
2424
+ /**
2425
+ * 判断是否支持该文件
2426
+ * @param filePath 文件路径
2427
+ */
2428
+ canHandle(filePath) {
2429
+ const ext = filePath.split(".").pop()?.toLowerCase();
2430
+ return ext === "ipa";
2431
+ }
2432
+ /**
2433
+ * 执行上传到 TestFlight
2434
+ * @param filePath 文件路径
2435
+ * @param config 配置
2436
+ * @param metadata 元数据
2437
+ */
2438
+ async upload(filePath, config, metadata) {
2439
+ const appConfig = config.publish.app_store;
2440
+ const auth = appConfig.auth;
2441
+ const testflightConfig = appConfig.testflight;
2442
+ const retryConfig = config.retry;
2443
+ logger.info("Starting TestFlight upload...");
2444
+ try {
2445
+ const exists = await fs8.pathExists(filePath);
2446
+ if (!exists) {
2447
+ throw new Error(`IPA file not found: ${filePath}`);
2448
+ }
2449
+ const fileSize = (await fs8.stat(filePath)).size;
2450
+ logger.info(`IPA file size: ${(fileSize / (1024 * 1024)).toFixed(2)} MB`);
2451
+ const jwtGenerator = await this.loadJWTGenerator(auth);
2452
+ const retryStrategy = createUploadRetryStrategy(retryConfig);
2453
+ logger.info("Generating JWT token...");
2454
+ const jwt = jwtGenerator.generate();
2455
+ const bundleId = metadata.platform?.includes("ios") ? this.extractBundleId(filePath) : null;
2456
+ if (!bundleId) {
2457
+ throw new Error("Could not determine app bundle ID from IPA");
2458
+ }
2459
+ logger.info(`App bundle ID: ${bundleId}`);
2460
+ logger.info("Creating build record for TestFlight...");
2461
+ const buildResult = await retryStrategy.execute(
2462
+ () => this.createBuild(jwt, bundleId, metadata.version),
2463
+ "TestFlight create build"
2464
+ );
2465
+ if (!buildResult.success || !buildResult.data) {
2466
+ throw buildResult.error || new Error("Failed to create build record");
2467
+ }
2468
+ const buildId = buildResult.data;
2469
+ logger.info(`Build created: ${buildId}`);
2470
+ logger.info("Uploading IPA file to TestFlight (this may take a while)...");
2471
+ const uploadResult = await retryStrategy.execute(
2472
+ () => this.uploadIPAFile(jwt, buildId, filePath),
2473
+ "TestFlight upload file"
2474
+ );
2475
+ if (!uploadResult.success) {
2476
+ throw uploadResult.error || new Error("IPA upload failed");
2477
+ }
2478
+ logger.info("Waiting for build processing (this may take 5-10 minutes)...");
2479
+ await this.waitForBuildProcessing(jwt, buildId, _TestFlightUploader.BUILD_PROCESSING_TIMEOUT);
2480
+ logger.success("Build processing completed");
2481
+ logger.info("Creating Beta Build Version...");
2482
+ const betaBuildResult = await retryStrategy.execute(
2483
+ () => this.createBetaBuildVersion(jwt, buildId),
2484
+ "TestFlight create beta version"
2485
+ );
2486
+ if (!betaBuildResult.success) {
2487
+ logger.warn("Could not create Beta Build Version automatically");
2488
+ }
2489
+ if (testflightConfig?.betaTesters && testflightConfig.betaTesters.length > 0) {
2490
+ logger.info("Adding beta testers...");
2491
+ await this.addBetaTesters(jwt, buildId, testflightConfig.betaTesters, retryStrategy);
2492
+ logger.success("Beta testers added");
2493
+ }
2494
+ if (testflightConfig?.betaBuildLocalization && testflightConfig.betaBuildLocalization.length > 0) {
2495
+ logger.info("Adding beta build localization...");
2496
+ await this.addBetaBuildLocalization(
2497
+ jwt,
2498
+ buildId,
2499
+ testflightConfig.betaBuildLocalization,
2500
+ retryStrategy
2501
+ );
2502
+ logger.success("Beta build localization added");
2503
+ }
2504
+ if (testflightConfig?.autoNotify !== false && testflightConfig?.betaTesters?.length) {
2505
+ logger.info("Notifying beta testers...");
2506
+ await this.notifyBetaTesters(jwt, buildId, metadata.changelog || "New TestFlight build");
2507
+ logger.success("Beta testers notified");
2508
+ }
2509
+ logger.success("TestFlight upload successful!");
2510
+ return {
2511
+ platform: "testflight",
2512
+ success: true,
2513
+ message: "Build uploaded to TestFlight and configured for beta testing",
2514
+ url: `https://appstoreconnect.apple.com/apps/${bundleId}/testflight/builds`
2515
+ };
2516
+ } catch (error) {
2517
+ logger.error(`TestFlight upload failed: ${error.message}`);
2518
+ if (error.response?.data) {
2519
+ logger.info(`Error Data: ${JSON.stringify(error.response.data)}`);
2520
+ }
2521
+ return {
2522
+ platform: "testflight",
2523
+ success: false,
2524
+ message: error.message,
2525
+ error
2526
+ };
2527
+ }
2528
+ }
2529
+ /**
2530
+ * 加载 JWT 生成器
2531
+ * @param auth 认证信息
2532
+ */
2533
+ async loadJWTGenerator(auth) {
2534
+ if (auth.privateKeyContent) {
2535
+ return AppleJWTGenerator.fromContent(auth.apiIssuerId, auth.apiKeyId, auth.privateKeyContent);
2536
+ } else if (auth.privateKeyPath) {
2537
+ return await AppleJWTGenerator.fromFile(auth.apiIssuerId, auth.apiKeyId, auth.privateKeyPath);
2538
+ } else {
2539
+ throw new Error("No Apple private key provided");
2540
+ }
2541
+ }
2542
+ /**
2543
+ * 提取 Bundle ID
2544
+ * @param ipaPath IPA 路径
2545
+ */
2546
+ extractBundleId(ipaPath) {
2547
+ return null;
2548
+ }
2549
+ /**
2550
+ * 创建构建记录
2551
+ * @param jwt JWT
2552
+ * @param bundleId Bundle ID
2553
+ * @param version 版本号
2554
+ */
2555
+ async createBuild(jwt, bundleId, version) {
2556
+ try {
2557
+ const response = await axios5.post(
2558
+ `${_TestFlightUploader.API_ROOT}/builds`,
2559
+ {
2560
+ data: {
2561
+ type: "builds",
2562
+ attributes: {
2563
+ version,
2564
+ uploadedDate: (/* @__PURE__ */ new Date()).toISOString()
2565
+ },
2566
+ relationships: {
2567
+ app: {
2568
+ data: {
2569
+ type: "apps",
2570
+ id: bundleId
2571
+ }
2572
+ }
2573
+ }
2574
+ }
2575
+ },
2576
+ {
2577
+ headers: {
2578
+ Authorization: `Bearer ${jwt}`,
2579
+ "Content-Type": "application/json"
2580
+ },
2581
+ timeout: _TestFlightUploader.API_TIMEOUT
2582
+ }
2583
+ );
2584
+ return response.data.data.id;
2585
+ } catch (error) {
2586
+ if (error.response?.status === 401) {
2587
+ throw new Error("Authentication failed: Invalid JWT or API credentials");
2588
+ }
2589
+ throw error;
2590
+ }
2591
+ }
2592
+ /**
2593
+ * 上传 IPA 文件
2594
+ * @param jwt JWT
2595
+ * @param buildId 构建 ID
2596
+ * @param filePath 文件路径
2597
+ */
2598
+ async uploadIPAFile(jwt, buildId, filePath) {
2599
+ const form = new FormData4();
2600
+ form.append("file", fs8.createReadStream(filePath));
2601
+ try {
2602
+ await axios5.post(
2603
+ `${_TestFlightUploader.API_ROOT}/builds/${buildId}/appStoreVersionExternalTestingBuilds`,
2604
+ form,
2605
+ {
2606
+ headers: {
2607
+ Authorization: `Bearer ${jwt}`,
2608
+ ...form.getHeaders()
2609
+ },
2610
+ timeout: 5 * 60 * 1e3,
2611
+ maxContentLength: Infinity,
2612
+ maxBodyLength: Infinity
2613
+ }
2614
+ );
2615
+ } catch (error) {
2616
+ throw new Error(`Failed to upload IPA: ${error.message}`);
2617
+ }
2618
+ }
2619
+ /**
2620
+ * 等待构建处理
2621
+ * @param jwt JWT
2622
+ * @param buildId 构建 ID
2623
+ * @param timeoutMs 超时时间
2624
+ */
2625
+ async waitForBuildProcessing(jwt, buildId, timeoutMs) {
2626
+ const startTime = Date.now();
2627
+ let lastStatus = "PROCESSING";
2628
+ while (Date.now() - startTime < timeoutMs) {
2629
+ try {
2630
+ const response = await axios5.get(`${_TestFlightUploader.API_ROOT}/builds/${buildId}`, {
2631
+ headers: {
2632
+ Authorization: `Bearer ${jwt}`,
2633
+ "Content-Type": "application/json"
2634
+ },
2635
+ timeout: _TestFlightUploader.API_TIMEOUT
2636
+ });
2637
+ const processingState = response.data.data.attributes.processingState;
2638
+ if (processingState === "READY_FOR_DISTRIBUTION") {
2639
+ logger.success("Build ready for distribution");
2640
+ return;
2641
+ }
2642
+ if (processingState === "FAILED" || processingState === "INVALID") {
2643
+ throw new Error(`Build processing failed with status: ${processingState}`);
2644
+ }
2645
+ if (processingState !== lastStatus) {
2646
+ logger.info(`Build status: ${processingState}`);
2647
+ lastStatus = processingState;
2648
+ }
2649
+ await new Promise(
2650
+ (resolve) => setTimeout(resolve, _TestFlightUploader.BUILD_POLLING_INTERVAL)
2651
+ );
2652
+ } catch (error) {
2653
+ logger.warn(`Error checking build status: ${error.message}`);
2654
+ await new Promise(
2655
+ (resolve) => setTimeout(resolve, _TestFlightUploader.BUILD_POLLING_INTERVAL)
2656
+ );
2657
+ }
2658
+ }
2659
+ throw new Error(`Build processing timeout after ${(timeoutMs / 1e3 / 60).toFixed(1)} minutes.`);
2660
+ }
2661
+ /**
2662
+ * 创建 Beta 版本(使其可测试)
2663
+ * @param jwt JWT
2664
+ * @param buildId 构建 ID
2665
+ */
2666
+ async createBetaBuildVersion(jwt, buildId) {
2667
+ try {
2668
+ const response = await axios5.post(
2669
+ `${_TestFlightUploader.API_ROOT}/betaBuildVersions`,
2670
+ {
2671
+ data: {
2672
+ type: "betaBuildVersions",
2673
+ attributes: {},
2674
+ relationships: {
2675
+ build: {
2676
+ data: {
2677
+ type: "builds",
2678
+ id: buildId
2679
+ }
2680
+ }
2681
+ }
2682
+ }
2683
+ },
2684
+ {
2685
+ headers: {
2686
+ Authorization: `Bearer ${jwt}`,
2687
+ "Content-Type": "application/json"
2688
+ },
2689
+ timeout: _TestFlightUploader.API_TIMEOUT
2690
+ }
2691
+ );
2692
+ return response.data.data.id;
2693
+ } catch (error) {
2694
+ throw new Error(`Failed to create Beta Build Version: ${error.message}`);
2695
+ }
2696
+ }
2697
+ /**
2698
+ * Add beta testers to the build
2699
+ */
2700
+ async addBetaTesters(jwt, buildId, testers, retryStrategy) {
2701
+ for (const testerEmail of testers) {
2702
+ try {
2703
+ await retryStrategy.execute(
2704
+ () => this.addBetaTesterToGroup(jwt, testerEmail, buildId),
2705
+ `TestFlight add tester ${testerEmail}`
2706
+ );
2707
+ logger.info(`\u2713 Added tester: ${testerEmail}`);
2708
+ } catch (error) {
2709
+ logger.warn(`Failed to add tester ${testerEmail}: ${error.message}`);
2710
+ }
2711
+ }
2712
+ }
2713
+ /**
2714
+ * 添加单个测试员到组
2715
+ * @param jwt JWT
2716
+ * @param testerEmail 测试员邮箱
2717
+ * @param buildId 构建 ID
2718
+ */
2719
+ async addBetaTesterToGroup(jwt, testerEmail, buildId) {
2720
+ try {
2721
+ logger.info(`Attempting to add ${testerEmail} to beta testers...`);
2722
+ } catch (error) {
2723
+ throw new Error(`Failed to add beta tester: ${error.message}`);
2724
+ }
2725
+ }
2726
+ /**
2727
+ * Add localization for beta build
2728
+ */
2729
+ async addBetaBuildLocalization(jwt, buildId, localizations, retryStrategy) {
2730
+ for (const localization of localizations) {
2731
+ try {
2732
+ await retryStrategy.execute(
2733
+ () => this.addLocalizationToBuilder(jwt, buildId, localization),
2734
+ `TestFlight add localization ${localization.locale}`
2735
+ );
2736
+ logger.info(`\u2713 Added localization: ${localization.locale}`);
2737
+ } catch (error) {
2738
+ logger.warn(`Failed to add localization ${localization.locale}: ${error.message}`);
2739
+ }
2740
+ }
2741
+ }
2742
+ /**
2743
+ * Add single localization
2744
+ */
2745
+ async addLocalizationToBuilder(jwt, buildId, localization) {
2746
+ try {
2747
+ await axios5.post(
2748
+ `${_TestFlightUploader.API_ROOT}/betaBuildLocalizations`,
2749
+ {
2750
+ data: {
2751
+ type: "betaBuildLocalizations",
2752
+ attributes: {
2753
+ locale: localization.locale,
2754
+ description: localization.description,
2755
+ keywords: localization.keywords?.join(",") || ""
2756
+ },
2757
+ relationships: {
2758
+ build: {
2759
+ data: {
2760
+ type: "betaBuildVersions",
2761
+ id: buildId
2762
+ }
2763
+ }
2764
+ }
2765
+ }
2766
+ },
2767
+ {
2768
+ headers: {
2769
+ Authorization: `Bearer ${jwt}`,
2770
+ "Content-Type": "application/json"
2771
+ },
2772
+ timeout: _TestFlightUploader.API_TIMEOUT
2773
+ }
2774
+ );
2775
+ } catch (error) {
2776
+ throw new Error(`Failed to add localization: ${error.message}`);
2777
+ }
2778
+ }
2779
+ /**
2780
+ * 通知测试员
2781
+ * @param jwt JWT
2782
+ * @param buildId 构建 ID
2783
+ * @param message 消息
2784
+ */
2785
+ async notifyBetaTesters(jwt, buildId, message) {
2786
+ try {
2787
+ logger.info("Sending notification to beta testers...");
2788
+ } catch (error) {
2789
+ logger.warn(`Failed to notify testers: ${error.message}`);
2790
+ }
2791
+ }
2792
+ };
2793
+
2794
+ // src/adapters/adhoc_uploader.ts
2795
+ import fs9 from "fs-extra";
2796
+ import path5 from "path";
2797
+ import { execSync } from "child_process";
2798
+ var AdHocUploader = class {
2799
+ name = "AdHoc";
2800
+ /**
2801
+ * 验证配置
2802
+ * @param config 配置对象
2803
+ * @returns 是否有效
2804
+ */
2805
+ validateConfig(config) {
2806
+ if (!config?.publish?.app_store?.enable) return false;
2807
+ const appConfig = config.publish.app_store;
2808
+ const mode = appConfig?.mode;
2809
+ if (mode !== "adhoc") return false;
2810
+ const adhocConfig = appConfig?.adhoc;
2811
+ if (!adhocConfig) {
2812
+ logger.error("Ad Hoc config missing: adhoc configuration");
2813
+ return false;
2814
+ }
2815
+ return true;
2816
+ }
2817
+ /**
2818
+ * 判断是否支持该文件
2819
+ * @param filePath 文件路径
2820
+ * @returns 是否支持
2821
+ */
2822
+ canHandle(filePath) {
2823
+ const ext = filePath.split(".").pop()?.toLowerCase();
2824
+ return ext === "ipa";
2825
+ }
2826
+ /**
2827
+ * 执行上传(生成 Ad Hoc 分发包)
2828
+ * @param filePath 文件路径
2829
+ * @param config 配置
2830
+ * @param metadata 元数据
2831
+ */
2832
+ async upload(filePath, config, metadata) {
2833
+ const appConfig = config.publish.app_store;
2834
+ const adhocConfig = appConfig.adhoc;
2835
+ const retryConfig = config.retry;
2836
+ logger.info("Starting Ad Hoc distribution setup...");
2837
+ try {
2838
+ const exists = await fs9.pathExists(filePath);
2839
+ if (!exists) {
2840
+ throw new Error(`IPA file not found: ${filePath}`);
2841
+ }
2842
+ const fileSize = (await fs9.stat(filePath)).size;
2843
+ logger.info(`IPA file size: ${(fileSize / (1024 * 1024)).toFixed(2)} MB`);
2844
+ const retryStrategy = createUploadRetryStrategy(retryConfig);
2845
+ const bundleId = this.extractBundleId(filePath);
2846
+ if (!bundleId) {
2847
+ logger.warn("Could not determine app bundle ID from IPA");
2848
+ } else {
2849
+ logger.info(`App bundle ID: ${bundleId}`);
2850
+ }
2851
+ logger.info("Verifying Ad Hoc provisioning profile...");
2852
+ const profileInfo = this.verifyProvisioningProfile(
2853
+ adhocConfig.provisioningProfileSpecifier,
2854
+ adhocConfig.teamId
2855
+ );
2856
+ logger.info("Creating Ad Hoc distribution manifest...");
2857
+ const manifestPath = await this.createManifest(
2858
+ filePath,
2859
+ metadata.version,
2860
+ bundleId,
2861
+ metadata.changelog
2862
+ );
2863
+ logger.info("Setting up distribution directory...");
2864
+ const distributionPath = await this.setupDistributionDirectory(filePath, manifestPath);
2865
+ logger.info("Generating installation links...");
2866
+ const installUrl = this.generateInstallUrl(distributionPath, bundleId);
2867
+ const qrCodePath = await this.generateQRCode(installUrl, distributionPath);
2868
+ this.outputDistributionInfo(installUrl, qrCodePath, distributionPath, profileInfo);
2869
+ logger.success("Ad Hoc distribution setup completed!");
2870
+ return {
2871
+ platform: "adhoc",
2872
+ success: true,
2873
+ message: `Ad Hoc package ready for distribution. Install link and QR code generated.`,
2874
+ url: installUrl
2875
+ };
2876
+ } catch (error) {
2877
+ logger.error(`Ad Hoc setup failed: ${error.message}`);
2878
+ return {
2879
+ platform: "adhoc",
2880
+ success: false,
2881
+ message: error.message,
2882
+ error
2883
+ };
2884
+ }
2885
+ }
2886
+ /**
2887
+ * 从 IPA 提取 Bundle ID
2888
+ * @param ipaPath IPA 路径
2889
+ */
2890
+ extractBundleId(ipaPath) {
2891
+ try {
2892
+ return null;
2893
+ } catch (error) {
2894
+ logger.warn(`Failed to extract bundle ID: ${error.message}`);
2895
+ return null;
2896
+ }
2897
+ }
2898
+ /**
2899
+ * 验证 Provisioning Profile
2900
+ * @param profileSpecifier Profile 名称
2901
+ * @param teamId 团队 ID
2902
+ */
2903
+ verifyProvisioningProfile(profileSpecifier, teamId) {
2904
+ if (!profileSpecifier) {
2905
+ logger.warn("No provisioning profile specified, will use automatic signing");
2906
+ return {
2907
+ name: "Automatic",
2908
+ teamId: teamId || "Unknown",
2909
+ capacity: 100,
2910
+ usedSlots: 0
2911
+ };
2912
+ }
2913
+ logger.info(`Using provisioning profile: ${profileSpecifier}`);
2914
+ return {
2915
+ name: profileSpecifier,
2916
+ teamId: teamId || "Unknown",
2917
+ capacity: 100,
2918
+ usedSlots: 0
2919
+ };
2920
+ }
2921
+ /**
2922
+ * 创建 manifest.plist 文件
2923
+ * @param ipaPath IPA 路径
2924
+ * @param version 版本号
2925
+ * @param bundleId Bundle ID
2926
+ * @param changelog 更新日志
2927
+ */
2928
+ async createManifest(ipaPath, version, bundleId, changelog) {
2929
+ const ipaFileName = path5.basename(ipaPath);
2930
+ const appName = bundleId || path5.parse(ipaFileName).name;
2931
+ const ipaUrl = `itms-services://?action=download-manifest&url=https://your-distribution-server.com/manifests/${ipaFileName}.plist`;
2932
+ const manifestContent = `<?xml version="1.0" encoding="UTF-8"?>
2933
+ <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
2934
+ <plist version="1.0">
2935
+ <dict>
2936
+ <key>items</key>
2937
+ <array>
2938
+ <dict>
2939
+ <key>assets</key>
2940
+ <array>
2941
+ <dict>
2942
+ <key>kind</key>
2943
+ <string>software-package</string>
2944
+ <key>url</key>
2945
+ <string>https://your-distribution-server.com/apps/${ipaFileName}</string>
2946
+ </dict>
2947
+ <dict>
2948
+ <key>kind</key>
2949
+ <string>display-image</string>
2950
+ <key>url</key>
2951
+ <string>https://your-distribution-server.com/icons/app-icon.png</string>
2952
+ </dict>
2953
+ <dict>
2954
+ <key>kind</key>
2955
+ <string>full-size-image</string>
2956
+ <key>url</key>
2957
+ <string>https://your-distribution-server.com/icons/app-icon-large.png</string>
2958
+ </dict>
2959
+ </array>
2960
+ <key>metadata</key>
2961
+ <dict>
2962
+ <key>bundle-identifier</key>
2963
+ <string>${bundleId || "com.example.app"}</string>
2964
+ <key>bundle-version</key>
2965
+ <string>${version}</string>
2966
+ <key>kind</key>
2967
+ <string>software</string>
2968
+ <key>title</key>
2969
+ <string>${appName}</string>
2970
+ <key>subtitle</key>
2971
+ <string>${changelog || "New release"}</string>
2972
+ </dict>
2973
+ </dict>
2974
+ </array>
2975
+ </dict>
2976
+ </plist>`;
2977
+ const manifestPath = `${ipaPath}.plist`;
2978
+ await fs9.writeFile(manifestPath, manifestContent);
2979
+ logger.info(`Manifest created: ${manifestPath}`);
2980
+ return manifestPath;
2981
+ }
2982
+ /**
2983
+ * 设置分发目录结构
2984
+ * @param ipaPath IPA 路径
2985
+ * @param manifestPath Manifest 路径
2986
+ */
2987
+ async setupDistributionDirectory(ipaPath, manifestPath) {
2988
+ const projectRoot = process.cwd();
2989
+ const distributionDir = path5.join(projectRoot, "build", "adhoc-distribution");
2990
+ await fs9.ensureDir(distributionDir);
2991
+ await fs9.ensureDir(path5.join(distributionDir, "apps"));
2992
+ await fs9.ensureDir(path5.join(distributionDir, "manifests"));
2993
+ await fs9.ensureDir(path5.join(distributionDir, "icons"));
2994
+ const ipaFileName = path5.basename(ipaPath);
2995
+ await fs9.copy(ipaPath, path5.join(distributionDir, "apps", ipaFileName));
2996
+ await fs9.copy(manifestPath, path5.join(distributionDir, "manifests", `${ipaFileName}.plist`));
2997
+ logger.info(`Distribution directory: ${distributionDir}`);
2998
+ return distributionDir;
2999
+ }
3000
+ /**
3001
+ * 生成安装链接 (itms-services)
3002
+ * @param distributionPath 分发目录
3003
+ * @param bundleId Bundle ID
3004
+ */
3005
+ generateInstallUrl(distributionPath, bundleId) {
3006
+ const manifestPath = path5.join(distributionPath, "manifests", `*.plist`);
3007
+ return `itms-services://?action=download-manifest&url=file://${manifestPath}`;
3008
+ }
3009
+ /**
3010
+ * 生成二维码
3011
+ * @param url 安装链接
3012
+ * @param distributionPath 分发目录
3013
+ */
3014
+ async generateQRCode(url, distributionPath) {
3015
+ const qrCodePath = path5.join(distributionPath, "install-qrcode.png");
3016
+ try {
3017
+ logger.info(`QR code would be saved to: ${qrCodePath}`);
3018
+ logger.info(`Install URL: ${url}`);
3019
+ return qrCodePath;
3020
+ } catch (error) {
3021
+ logger.warn(`Failed to generate QR code: ${error.message}`);
3022
+ return "";
3023
+ }
3024
+ }
3025
+ /**
3026
+ * 输出分发信息
3027
+ * @param installUrl 安装链接
3028
+ * @param qrCodePath 二维码路径
3029
+ * @param distributionPath 分发目录
3030
+ * @param profileInfo Profile 信息
3031
+ */
3032
+ outputDistributionInfo(installUrl, qrCodePath, distributionPath, profileInfo) {
3033
+ logger.newLine();
3034
+ logger.title("\u{1F4F1} Ad Hoc Distribution Setup Complete");
3035
+ logger.info(`App Name: ${profileInfo.name}`);
3036
+ logger.info(`Team ID: ${profileInfo.teamId}`);
3037
+ logger.info(`Device Capacity: ${profileInfo.capacity}`);
3038
+ logger.info(`Used Slots: ${profileInfo.usedSlots}/${profileInfo.capacity}`);
3039
+ logger.newLine();
3040
+ logger.info("\u{1F4E6} Distribution Files:");
3041
+ logger.info(` Directory: ${distributionPath}`);
3042
+ logger.info(` IPA: ${path5.join(distributionPath, "apps", "*.ipa")}`);
3043
+ logger.info(` Manifest: ${path5.join(distributionPath, "manifests", "*.plist")}`);
3044
+ logger.info(` QR Code: ${qrCodePath}`);
3045
+ logger.newLine();
3046
+ logger.info("\u{1F517} Installation Link:");
3047
+ logger.info(` ${installUrl}`);
3048
+ logger.newLine();
3049
+ logger.info("\u{1F4E4} Distribution Options:");
3050
+ logger.info(" 1. Share via\u84B2\u516C\u82F1: Upload to Pgyer for easy distribution");
3051
+ logger.info(" 2. Share QR code with testers");
3052
+ logger.info(" 3. Host manifest and IPA on your server");
3053
+ logger.info(" 4. Use enterprise distribution service");
3054
+ logger.newLine();
3055
+ logger.info("\u26A0\uFE0F Important:");
3056
+ logger.info(" \u2022 Devices must be registered in your Apple Developer account");
3057
+ logger.info(" \u2022 Maximum 100 devices per app, per year");
3058
+ logger.info(" \u2022 App must be signed with Ad Hoc provisioning profile");
3059
+ logger.info(" \u2022 Cannot be distributed via App Store");
3060
+ }
3061
+ /**
3062
+ * 检查是否安装了 Xcode
3063
+ * @returns 是否安装
3064
+ */
3065
+ checkXcodeInstalled() {
3066
+ try {
3067
+ execSync("xcode-select -p", { stdio: "pipe" });
3068
+ return true;
3069
+ } catch {
3070
+ return false;
3071
+ }
3072
+ }
3073
+ /**
3074
+ * 生成 Ad Hoc 导出选项 (ExportOptions.plist)
3075
+ * @param teamId 团队 ID
3076
+ * @param signingIdentity 签名证书
3077
+ * @param provisioningProfile Profile 名称
3078
+ */
3079
+ generateExportOptions(teamId, signingIdentity, provisioningProfile) {
3080
+ const options = `<?xml version="1.0" encoding="UTF-8"?>
3081
+ <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
3082
+ <plist version="1.0">
3083
+ <dict>
3084
+ <key>method</key>
3085
+ <string>ad-hoc</string>
3086
+ <key>signingStyle</key>
3087
+ <string>automatic</string>
3088
+ <key>stripSwiftSymbols</key>
3089
+ <true/>
3090
+ <key>teamID</key>
3091
+ <string>${teamId || ""}</string>
3092
+ ${signingIdentity ? `<key>signingCertificate</key><string>${signingIdentity}</string>` : ""}
3093
+ ${provisioningProfile ? `<key>provisioningProfileSpecifier</key><string>${provisioningProfile}</string>` : ""}
3094
+ </dict>
3095
+ </plist>`;
3096
+ return options;
3097
+ }
3098
+ };
3099
+
3100
+ // src/adapters/harmony_uploader.ts
3101
+ import fs10 from "fs-extra";
3102
+ import path6 from "path";
3103
+ import axios6 from "axios";
3104
+ import FormData5 from "form-data";
3105
+ var HarmonyUploader = class _HarmonyUploader {
3106
+ name = "HarmonyOS";
3107
+ static TOKEN_URL = "https://connect-api.cloud.huawei.com/api/oauth2/v1/token";
3108
+ static PUBLISH_API_ROOT = "https://connect-api.cloud.huawei.com/api/publish/v2";
3109
+ validateConfig(config) {
3110
+ if (!config?.publish?.harmony?.enable) return false;
3111
+ const h = config.publish.harmony;
3112
+ if (!h.auth?.clientId || !h.auth?.clientSecret || !h.appId) {
3113
+ logger.error("Harmony config missing: clientId, clientSecret, or appId");
3114
+ return false;
3115
+ }
3116
+ return true;
3117
+ }
3118
+ /**
3119
+ * 判断是否支持该文件
3120
+ * @param filePath 文件路径
3121
+ */
3122
+ canHandle(filePath) {
3123
+ const ext = filePath.split(".").pop()?.toLowerCase();
3124
+ return ext === "hap" || ext === "app";
3125
+ }
3126
+ async upload(filePath, config, metadata) {
3127
+ const harmonyConfig = config.publish.harmony;
3128
+ const clientId = harmonyConfig.auth.clientId;
3129
+ const clientSecret = harmonyConfig.auth.clientSecret;
3130
+ const appId = harmonyConfig.appId;
3131
+ const releaseType = harmonyConfig.releaseType || "draft";
3132
+ const suffix = path6.extname(filePath).substring(1);
3133
+ const retryConfig = config.retry;
3134
+ logger.info("Starting HarmonyOS AppGallery upload...");
3135
+ try {
3136
+ const retryStrategy = createUploadRetryStrategy(retryConfig);
3137
+ logger.info("Authenticating...");
3138
+ const tokenResult = await retryStrategy.execute(
3139
+ () => this.getAccessToken(clientId, clientSecret),
3140
+ "Harmony authentication"
3141
+ );
3142
+ if (!tokenResult.success || !tokenResult.data) {
3143
+ throw tokenResult.error || new Error("Failed to get access token");
3144
+ }
3145
+ const token = tokenResult.data;
3146
+ logger.info("Requesting upload URL...");
3147
+ const uploadInfoResult = await retryStrategy.execute(
3148
+ () => this.getUploadUrl(token, appId, suffix),
3149
+ "Harmony get upload URL"
3150
+ );
3151
+ if (!uploadInfoResult.success || !uploadInfoResult.data) {
3152
+ throw uploadInfoResult.error || new Error("Failed to get upload URL");
3153
+ }
3154
+ const uploadInfo = uploadInfoResult.data;
3155
+ logger.info("Uploading HarmonyOS package...");
3156
+ const uploadFileResult = await retryStrategy.execute(
3157
+ () => this.uploadFile(uploadInfo.uploadUrl, uploadInfo.authCode, filePath),
3158
+ "Harmony file upload"
3159
+ );
3160
+ if (!uploadFileResult.success) {
3161
+ throw uploadFileResult.error || new Error("File upload failed");
3162
+ }
3163
+ logger.info("Linking file to app...");
3164
+ const updateInfoResult = await retryStrategy.execute(
3165
+ () => this.updateAppFileInfo(token, appId, uploadInfo.authCode, filePath),
3166
+ "Harmony update file info"
3167
+ );
3168
+ if (!updateInfoResult.success) {
3169
+ throw updateInfoResult.error || new Error("Failed to update file info");
3170
+ }
3171
+ if (releaseType === "submit") {
3172
+ logger.info("Submitting to review...");
3173
+ }
3174
+ logger.success("HarmonyOS upload successful!");
3175
+ return {
3176
+ platform: "harmony",
3177
+ success: true,
3178
+ message: "Upload success",
3179
+ url: "https://developer.huawei.com/consumer/cn/service/josp/agc/index.html"
3180
+ };
3181
+ } catch (error) {
3182
+ logger.error(`HarmonyOS upload failed: ${error.message}`);
3183
+ return {
3184
+ platform: "harmony",
3185
+ success: false,
3186
+ message: error.message,
3187
+ error
3188
+ };
3189
+ }
3190
+ }
3191
+ /**
3192
+ * 获取 Access Token
3193
+ * @param clientId 客户端 ID
3194
+ * @param clientSecret 客户端密钥
3195
+ */
3196
+ async getAccessToken(clientId, clientSecret) {
3197
+ const data = {
3198
+ client_id: clientId,
3199
+ client_secret: clientSecret,
3200
+ grant_type: "client_credentials"
3201
+ };
3202
+ const res = await axios6.post(_HarmonyUploader.TOKEN_URL, data);
3203
+ if (!res.data.access_token) {
3204
+ throw new Error("Failed to get access token");
3205
+ }
3206
+ return res.data.access_token;
3207
+ }
3208
+ /**
3209
+ * 获取上传 URL
3210
+ * @param token Token
3211
+ * @param appId 应用 ID
3212
+ * @param suffix 后缀
3213
+ */
3214
+ async getUploadUrl(token, appId, suffix) {
3215
+ const res = await axios6.get(`${_HarmonyUploader.PUBLISH_API_ROOT}/upload-url`, {
3216
+ params: { appId, suffix },
3217
+ headers: { Authorization: `Bearer ${token}`, client_id: appId }
3218
+ });
3219
+ if (res.data.code != "0") {
3220
+ throw new Error(`Get upload url failed: ${res.data.msg}`);
3221
+ }
3222
+ return {
3223
+ uploadUrl: res.data.uploadUrl,
3224
+ authCode: res.data.authCode
3225
+ };
3226
+ }
3227
+ async uploadFile(uploadUrl, authCode, filePath) {
3228
+ const form = new FormData5();
3229
+ form.append("file", fs10.createReadStream(filePath));
3230
+ form.append("authCode", authCode);
3231
+ form.append("fileCount", "1");
3232
+ const res = await axios6.post(uploadUrl, form, {
3233
+ headers: { ...form.getHeaders() },
3234
+ maxContentLength: Infinity,
3235
+ maxBodyLength: Infinity
3236
+ });
3237
+ if (res.data.result.resultCode != "0") {
3238
+ throw new Error(`File upload failed: ${JSON.stringify(res.data.result)}`);
3239
+ }
3240
+ }
3241
+ /**
3242
+ * 更新应用文件信息
3243
+ * @param token Token
3244
+ * @param appId 应用 ID
3245
+ * @param authCode 授权码
3246
+ * @param filePath 文件路径
3247
+ */
3248
+ async updateAppFileInfo(token, appId, authCode, filePath) {
3249
+ const fileName = path6.basename(filePath);
3250
+ const body = {
3251
+ fileType: 7,
3252
+ // 鸿蒙包的 fileType(需要根据华为最新文档确认)
3253
+ files: [
3254
+ {
3255
+ fileName,
3256
+ fileDestUrl: authCode
3257
+ }
3258
+ ]
3259
+ };
3260
+ const res = await axios6.put(`${_HarmonyUploader.PUBLISH_API_ROOT}/app-file-info`, body, {
3261
+ params: { appId },
3262
+ headers: { Authorization: `Bearer ${token}`, client_id: appId }
3263
+ });
3264
+ if (res.data.ret.code != 0) {
3265
+ throw new Error(`Update file info failed: ${res.data.ret.msg}`);
3266
+ }
3267
+ }
3268
+ };
3269
+
3270
+ // src/adapters/oppo_uploader.ts
3271
+ import fs11 from "fs-extra";
3272
+ import path7 from "path";
3273
+ import axios7 from "axios";
3274
+ import FormData6 from "form-data";
3275
+ import crypto4 from "crypto";
3276
+ var OppoUploader = class _OppoUploader {
3277
+ name = "OPPO";
3278
+ /** OPPO 开放 API 基础地址 */
3279
+ static API_BASE = "https://oop-openapi-cn.heytapmobi.com";
3280
+ /** 获取 token 接口 */
3281
+ static TOKEN_API = `${_OppoUploader.API_BASE}/developer/v1/token`;
3282
+ /** 获取上传 URL 接口 */
3283
+ static UPLOAD_URL_API = `${_OppoUploader.API_BASE}/resource/v1/upload/get-upload-url`;
3284
+ /** 上传完成后提交版本 */
3285
+ static SUBMIT_API = `${_OppoUploader.API_BASE}/resource/v1/app/upd`;
3286
+ /** 查询应详情接口 */
3287
+ static APP_INFO_API = `${_OppoUploader.API_BASE}/resource/v1/app/info`;
3288
+ /**
3289
+ * OPPO API 签名生成
3290
+ * OPPO 使用 HMAC-SHA256 签名机制
3291
+ */
3292
+ generateSign(params, clientSecret) {
3293
+ const sorted = Object.keys(params).sort().filter((key) => params[key] !== void 0 && params[key] !== null).map((key) => `${key}=${params[key]}`).join("&");
3294
+ return crypto4.createHmac("sha256", clientSecret).update(sorted).digest("hex");
3295
+ }
3296
+ validateConfig(config) {
3297
+ if (!config?.publish?.oppo?.enable) return false;
3298
+ const oppo = config.publish.oppo;
3299
+ if (!oppo.auth?.clientId || !oppo.auth?.clientSecret) {
3300
+ logger.error("OPPO config missing: clientId or clientSecret");
3301
+ return false;
3302
+ }
3303
+ return true;
3304
+ }
3305
+ canHandle(filePath) {
3306
+ const ext = filePath.split(".").pop()?.toLowerCase();
3307
+ return ext === "apk";
3308
+ }
3309
+ /**
3310
+ * 尝试从文件名推断包名
3311
+ */
3312
+ inferPackageName(filePath) {
3313
+ const fileName = path7.basename(filePath);
3314
+ const match = fileName.match(/^([\w.]+?)(?:-(?:release|debug|unsigned))?\.apk$/i);
3315
+ if (match && match[1].includes(".")) {
3316
+ return match[1];
3317
+ }
3318
+ return null;
3319
+ }
3320
+ /**
3321
+ * 从包名推断应用名称
3322
+ */
3323
+ inferAppName(packageName) {
3324
+ const parts = packageName.split(".");
3325
+ if (parts.length === 0) return null;
3326
+ const lastPart = parts[parts.length - 1];
3327
+ return lastPart.charAt(0).toUpperCase() + lastPart.slice(1);
3328
+ }
3329
+ async upload(filePath, config, metadata) {
3330
+ const oppoConfig = config.publish.oppo;
3331
+ const clientId = oppoConfig.auth.clientId;
3332
+ const clientSecret = oppoConfig.auth.clientSecret;
3333
+ const packageName = oppoConfig.packageName || this.inferPackageName(filePath);
3334
+ if (!packageName) {
3335
+ return {
3336
+ platform: "oppo",
3337
+ success: false,
3338
+ message: "\u65E0\u6CD5\u83B7\u53D6\u5305\u540D (packageName)\uFF0C\u8BF7\u5728\u914D\u7F6E\u4E2D\u6307\u5B9A\u6216\u786E\u4FDD\u6587\u4EF6\u540D\u5305\u542B\u5305\u540D",
3339
+ consoleUrl: "https://open.oppomobile.com/new/ecology/app"
3340
+ };
3341
+ }
3342
+ const retryConfig = config.retry;
3343
+ const consoleUrl = "https://open.oppomobile.com/new/ecology/app";
3344
+ if (!fs11.existsSync(filePath)) {
3345
+ return {
3346
+ platform: "oppo",
3347
+ success: false,
3348
+ message: `\u6587\u4EF6\u4E0D\u5B58\u5728: ${filePath}`,
3349
+ consoleUrl
3350
+ };
3351
+ }
3352
+ logger.info("\u5F00\u59CB\u4E0A\u4F20\u5230 OPPO \u5E94\u7528\u5546\u5E97...");
3353
+ logger.info(`\u6587\u4EF6: ${filePath}`);
3354
+ try {
3355
+ const retryStrategy = createUploadRetryStrategy(retryConfig);
3356
+ logger.info("\u6B63\u5728\u83B7\u53D6 access_token...");
3357
+ const tokenResult = await retryStrategy.execute(
3358
+ () => this.getAccessToken(clientId, clientSecret),
3359
+ "OPPO authentication"
3360
+ );
3361
+ if (!tokenResult.success || !tokenResult.data) {
3362
+ throw tokenResult.error || new Error("Failed to get access token");
3363
+ }
3364
+ const accessToken = tokenResult.data;
3365
+ logger.info("\u6B63\u5728\u83B7\u53D6\u73B0\u6709\u5E94\u7528\u8BE6\u60C5...");
3366
+ const appInfoResult = await retryStrategy.execute(
3367
+ () => this.getAppInfo(accessToken, clientSecret, packageName),
3368
+ "OPPO get app info"
3369
+ );
3370
+ const onlineAppInfo = appInfoResult.data || {};
3371
+ if (onlineAppInfo) {
3372
+ logger.info(
3373
+ `\u83B7\u53D6\u5230\u7EBF\u4E0A\u4FE1\u606F: ${onlineAppInfo.app_name} (Category: ${onlineAppInfo.second_category_id})`
3374
+ );
3375
+ logger.info(`[OPPO AppInfo Full] ${JSON.stringify(onlineAppInfo)}`);
3376
+ }
3377
+ logger.info("\u6B63\u5728\u83B7\u53D6\u4E0A\u4F20\u5730\u5740...");
3378
+ const uploadUrlResult = await retryStrategy.execute(
3379
+ () => this.getUploadUrl(accessToken, clientSecret),
3380
+ "OPPO get upload URL"
3381
+ );
3382
+ if (!uploadUrlResult.success || !uploadUrlResult.data) {
3383
+ throw uploadUrlResult.error || new Error("Failed to get upload URL");
3384
+ }
3385
+ const { uploadUrl, sign: uploadSign } = uploadUrlResult.data;
3386
+ logger.info("\u6B63\u5728\u4E0A\u4F20 APK \u6587\u4EF6...");
3387
+ const uploadFileResult = await retryStrategy.execute(
3388
+ () => this.uploadFile(uploadUrl, uploadSign, filePath),
3389
+ "OPPO file upload"
3390
+ );
3391
+ if (!uploadFileResult.success || !uploadFileResult.data) {
3392
+ throw uploadFileResult.error || new Error("File upload failed");
3393
+ }
3394
+ const rawUrl = uploadFileResult.data.url;
3395
+ const fileUrl = rawUrl.replace(/^http:\/\//i, "https://").replace("storedl1.nearme.com.cn", "storedl.nearme.com.cn");
3396
+ const md5 = uploadFileResult.data.md5;
3397
+ logger.info("\u6B63\u5728\u63D0\u4EA4\u7248\u672C\u4FE1\u606F...");
3398
+ const submitResult = await retryStrategy.execute(
3399
+ () => this.submitVersion({
3400
+ accessToken,
3401
+ clientSecret,
3402
+ packageName,
3403
+ appName: oppoConfig.appName || metadata.appName || onlineAppInfo.app_name || this.inferAppName(packageName),
3404
+ fileUrl,
3405
+ fileMd5: md5,
3406
+ versionName: metadata.version,
3407
+ versionCode: metadata.buildNumber,
3408
+ updateDesc: metadata.changelog || "App Update",
3409
+ onlineType: oppoConfig.onlineType,
3410
+ // 从配置读取
3411
+ onlineAppInfo
3412
+ // 传入线上信息
3413
+ }),
3414
+ "OPPO submit version"
3415
+ );
3416
+ if (!submitResult.success) {
3417
+ throw submitResult.error || new Error("Submit version failed");
3418
+ }
3419
+ logger.success("\u4E0A\u4F20\u5230 OPPO \u5E94\u7528\u5546\u5E97\u6210\u529F!");
3420
+ return {
3421
+ platform: "oppo",
3422
+ success: true,
3423
+ message: "\u4E0A\u4F20\u6210\u529F, \u8BF7\u524D\u5F80\u540E\u53F0\u786E\u8BA4\u5E76\u63D0\u4EA4\u5BA1\u6838",
3424
+ consoleUrl
3425
+ };
3426
+ } catch (error) {
3427
+ logger.error(`\u4E0A\u4F20\u5230 OPPO \u5931\u8D25: ${error.message}`);
3428
+ return {
3429
+ platform: "oppo",
3430
+ success: false,
3431
+ message: this.formatError(error),
3432
+ error,
3433
+ consoleUrl
3434
+ };
3435
+ }
3436
+ }
3437
+ /**
3438
+ * 获取 access_token
3439
+ * 官方文档: https://open.oppomobile.com/documentation/page/info?id=10998
3440
+ */
3441
+ async getAccessToken(clientId, clientSecret) {
3442
+ const params = {
3443
+ client_id: clientId,
3444
+ client_secret: clientSecret
3445
+ };
3446
+ logger.info(`[OPPO Auth Debug] clientId: ${clientId}`);
3447
+ logger.info(`[OPPO Auth Debug] clientSecret length: ${clientSecret?.length || 0}`);
3448
+ logger.info(`[OPPO Auth Debug] params: ${JSON.stringify(params)}`);
3449
+ const res = await axios7.get(_OppoUploader.TOKEN_API, {
3450
+ params,
3451
+ timeout: 15e3
3452
+ });
3453
+ logger.info(`[OPPO Auth Response] status: ${res.status}, data: ${JSON.stringify(res.data)}`);
3454
+ if (res.data.errno !== 0) {
3455
+ throw new Error(`\u83B7\u53D6 token \u5931\u8D25: ${res.data.data?.message || JSON.stringify(res.data)}`);
3456
+ }
3457
+ return res.data.data.access_token;
3458
+ }
3459
+ /**
3460
+ * 获取应用详情
3461
+ */
3462
+ async getAppInfo(accessToken, clientSecret, packageName) {
3463
+ const timestamp = Math.floor(Date.now() / 1e3);
3464
+ const params = {
3465
+ access_token: accessToken,
3466
+ pkg_name: packageName,
3467
+ timestamp
3468
+ };
3469
+ const apiSign = this.generateSign(params, clientSecret);
3470
+ try {
3471
+ const res = await axios7.get(_OppoUploader.APP_INFO_API, {
3472
+ params: {
3473
+ ...params,
3474
+ api_sign: apiSign
3475
+ },
3476
+ timeout: 15e3
3477
+ });
3478
+ if (res.data.errno !== 0) {
3479
+ logger.warn(`\u83B7\u53D6\u5E94\u7528\u8BE6\u60C5\u5931\u8D25 (\u975E\u81F4\u547D): ${JSON.stringify(res.data)}`);
3480
+ return null;
3481
+ }
3482
+ return res.data.data;
3483
+ } catch (error) {
3484
+ logger.warn(`\u83B7\u53D6\u5E94\u7528\u8BE6\u60C5\u8BF7\u6C42\u5F02\u5E38 (\u975E\u81F4\u547D): ${error.message}`);
3485
+ return null;
3486
+ }
3487
+ }
3488
+ /**
3489
+ * 获取上传地址
3490
+ */
3491
+ async getUploadUrl(accessToken, clientSecret) {
3492
+ const timestamp = Math.floor(Date.now() / 1e3);
3493
+ const params = {
3494
+ access_token: accessToken,
3495
+ timestamp
3496
+ };
3497
+ const apiSign = this.generateSign(params, clientSecret);
3498
+ const res = await axios7.get(_OppoUploader.UPLOAD_URL_API, {
3499
+ params: {
3500
+ ...params,
3501
+ api_sign: apiSign
3502
+ },
3503
+ timeout: 15e3
3504
+ });
3505
+ if (res.data.errno !== 0) {
3506
+ throw new Error(`\u83B7\u53D6\u4E0A\u4F20\u5730\u5740\u5931\u8D25: ${res.data.data?.message || JSON.stringify(res.data)}`);
3507
+ }
3508
+ return {
3509
+ uploadUrl: res.data.data.upload_url,
3510
+ sign: res.data.data.sign
3511
+ };
3512
+ }
3513
+ /**
3514
+ * 上传 APK 文件
3515
+ */
3516
+ async uploadFile(uploadUrl, sign, filePath) {
3517
+ const form = new FormData6();
3518
+ form.append("file", fs11.createReadStream(filePath));
3519
+ form.append("sign", sign);
3520
+ form.append("type", "apk");
3521
+ const res = await axios7.post(uploadUrl, form, {
3522
+ headers: form.getHeaders(),
3523
+ maxContentLength: Infinity,
3524
+ maxBodyLength: Infinity,
3525
+ timeout: 3e5
3526
+ // 5 分钟超时
3527
+ });
3528
+ if (res.data.errno !== 0) {
3529
+ throw new Error(`\u6587\u4EF6\u4E0A\u4F20\u5931\u8D25: ${res.data.data?.message || JSON.stringify(res.data)}`);
3530
+ }
3531
+ return {
3532
+ url: res.data.data.url,
3533
+ md5: res.data.data.md5
3534
+ };
3535
+ }
3536
+ /**
3537
+ * 提交版本信息
3538
+ */
3539
+ async submitVersion(params) {
3540
+ logger.info(`[OPPO Submit Params] ${JSON.stringify(params)}`);
3541
+ const timestamp = Math.floor(Date.now() / 1e3);
3542
+ const online = params.onlineAppInfo || {};
3543
+ let vCode = params.versionCode;
3544
+ if (!vCode || vCode === "0" || vCode === "") {
3545
+ const parts = params.versionName.split("+");
3546
+ if (parts.length > 1) {
3547
+ vCode = parts[1];
3548
+ } else {
3549
+ vCode = "1";
3550
+ }
3551
+ }
3552
+ const signParams = {
3553
+ access_token: params.accessToken,
3554
+ timestamp,
3555
+ // OPPO 官方要求 apk_url 为 JSON 数组格式:[{url, md5, cpu_code}]
3556
+ // cpu_code: 0=通用包, 3=arm64-v8a, 4=armeabi-v7a, 5=x86_64
3557
+ apk_url: JSON.stringify([
3558
+ {
3559
+ url: params.fileUrl,
3560
+ md5: params.fileMd5,
3561
+ cpu_code: 0
3562
+ // 通用包
3563
+ }
3564
+ ]),
3565
+ version_name: params.versionName.split("+")[0],
3566
+ // 仅保留版本名部分
3567
+ version_code: vCode,
3568
+ update_desc: params.updateDesc,
3569
+ pkg_name: params.packageName,
3570
+ app_name: params.appName,
3571
+ // 补充 OPPO 提交审核的必填项 (优先复用线上数据)
3572
+ summary: online.summary || params.updateDesc.slice(0, 15),
3573
+ detail_desc: online.detail_desc || (params.updateDesc.length >= 20 ? params.updateDesc : `${params.updateDesc}, \u6B64\u7248\u672C\u4F18\u5316\u4E86\u7528\u6237\u4F53\u9A8C\u5E76\u4FEE\u590D\u4E86\u5DF2\u77E5\u95EE\u9898\u3002`),
3574
+ privacy_source_url: online.privacy_source_url || `https://open.oppomobile.com/privacy/${params.packageName}`
3575
+ };
3576
+ const mapField = (key, onlineKey) => {
3577
+ const val = online[onlineKey || key];
3578
+ if (val !== void 0 && val !== null && val !== "") {
3579
+ signParams[key] = val;
3580
+ }
3581
+ };
3582
+ mapField("first_category_id");
3583
+ mapField("second_category_id");
3584
+ mapField("third_category_id");
3585
+ if (params.onlineType) {
3586
+ signParams.online_type = params.onlineType;
3587
+ } else {
3588
+ mapField("online_type");
3589
+ }
3590
+ if (!signParams.online_type) {
3591
+ signParams.online_type = "1";
3592
+ }
3593
+ mapField("version_type");
3594
+ mapField("adaptive_equipment");
3595
+ {
3596
+ const val = online["adaptive_type"];
3597
+ if (val !== void 0 && val !== null && val !== "" && String(val) !== "0") {
3598
+ signParams.adaptive_type = val;
3599
+ }
3600
+ }
3601
+ mapField("test_desc");
3602
+ if (!signParams.test_desc) {
3603
+ signParams.test_desc = "\u65E0\u7279\u6B8A\u6D4B\u8BD5\u8BF4\u660E";
3604
+ }
3605
+ mapField("business_username");
3606
+ mapField("business_email");
3607
+ mapField("business_mobile");
3608
+ mapField("customer_contact");
3609
+ if (!signParams.business_username) signParams.business_username = "\u5F00\u53D1\u8D1F\u8D23\u4EBA";
3610
+ if (!signParams.business_email) signParams.business_email = "developer@example.com";
3611
+ if (!signParams.business_mobile) signParams.business_mobile = "13800138000";
3612
+ mapField("copyright_url");
3613
+ mapField("age_level");
3614
+ if (!signParams.age_level) {
3615
+ signParams.age_level = "18";
3616
+ }
3617
+ mapField("icon_url");
3618
+ if (online.pic_url_material && Array.isArray(online.pic_url_material)) {
3619
+ const MAX_SIZE = 1 * 1024 * 1024;
3620
+ const validPicUrls = online.pic_url_material.filter((item) => {
3621
+ return !item.size || Number(item.size) <= MAX_SIZE;
3622
+ }).map((item) => item.url).filter(Boolean);
3623
+ if (validPicUrls.length > 0) {
3624
+ signParams.pic_url = validPicUrls.join(",");
3625
+ } else {
3626
+ mapField("pic_url");
3627
+ }
3628
+ } else {
3629
+ mapField("pic_url");
3630
+ }
3631
+ mapField("is_safe_check");
3632
+ const apiSign = this.generateSign(signParams, params.clientSecret);
3633
+ const data = new URLSearchParams();
3634
+ Object.entries(signParams).forEach(([key, value]) => {
3635
+ data.append(key, String(value));
3636
+ });
3637
+ data.append("api_sign", apiSign);
3638
+ logger.info(`[OPPO Submit Debug] URL: ${_OppoUploader.SUBMIT_API}`);
3639
+ logger.info(`[OPPO Submit Debug] Body: ${data.toString()}`);
3640
+ const res = await axios7.post(_OppoUploader.SUBMIT_API, data.toString(), {
3641
+ headers: {
3642
+ "Content-Type": "application/x-www-form-urlencoded"
3643
+ },
3644
+ timeout: 3e4
3645
+ });
3646
+ logger.info(`[OPPO Submit Response] status: ${res.status}, data: ${JSON.stringify(res.data)}`);
3647
+ if (res.data.errno !== 0) {
3648
+ throw new Error(`\u63D0\u4EA4\u7248\u672C\u5931\u8D25: ${res.data.data?.message || JSON.stringify(res.data)}`);
3649
+ }
3650
+ logger.info("\u7248\u672C\u4FE1\u606F\u5DF2\u63D0\u4EA4");
3651
+ }
3652
+ /**
3653
+ * 格式化错误信息
3654
+ */
3655
+ formatError(error) {
3656
+ if (error.response?.data) {
3657
+ const data = error.response.data;
3658
+ return data.data?.message || data.message || error.message;
3659
+ }
3660
+ return error.message;
3661
+ }
3662
+ };
3663
+
3664
+ // src/adapters/vivo_uploader.ts
3665
+ import fs12 from "fs-extra";
3666
+ import path8 from "path";
3667
+ import axios8 from "axios";
3668
+ import FormData7 from "form-data";
3669
+ import crypto5 from "crypto";
3670
+ var VivoUploader = class _VivoUploader {
3671
+ name = "vivo";
3672
+ /** vivo 开放 API 基础地址 */
3673
+ static API_BASE = "https://developer-api.vivo.com.cn/router/rest";
3674
+ /**
3675
+ * vivo API 签名生成
3676
+ * 规则: 所有参数按 ASCII 码排序后拼接为 key=val&... 字符串,
3677
+ * 以 accessSecret 为密钥进行 HMAC-SHA256 加密,结果转为小写 16 进制字符串
3678
+ */
3679
+ generateSign(params, accessSecret) {
3680
+ const sorted = Object.keys(params).sort().filter((key) => params[key] !== void 0 && params[key] !== null).map((key) => `${key}=${params[key]}`).join("&");
3681
+ const sign = crypto5.createHmac("sha256", accessSecret).update(sorted).digest("hex");
3682
+ logger.info(`[VIVO DEBUG] \u5F85\u7B7E\u540D\u4E32: ${sorted}
3683
+ -> \u7B7E\u540D\u7ED3\u679C: ${sign}`);
3684
+ return sign;
3685
+ }
3686
+ validateConfig(config) {
3687
+ if (!config?.publish?.vivo?.enable) return false;
3688
+ const vivo = config.publish.vivo;
3689
+ if (!vivo.auth?.accessKey || !vivo.auth?.accessSecret) {
3690
+ logger.error("vivo config missing: accessKey or accessSecret");
3691
+ return false;
3692
+ }
3693
+ return true;
3694
+ }
3695
+ canHandle(filePath) {
3696
+ const ext = filePath.split(".").pop()?.toLowerCase();
3697
+ return ext === "apk";
3698
+ }
3699
+ async upload(filePath, config, metadata) {
3700
+ const vivoConfig = config.publish.vivo;
3701
+ const accessKey = vivoConfig.auth.accessKey;
3702
+ const accessSecret = vivoConfig.auth.accessSecret;
3703
+ const retryConfig = config.retry;
3704
+ const consoleUrl = "https://dev.vivo.com.cn/manage/app";
3705
+ if (!fs12.existsSync(filePath)) {
3706
+ return {
3707
+ platform: "vivo",
3708
+ success: false,
3709
+ message: `\u6587\u4EF6\u4E0D\u5B58\u5728: ${filePath}`,
3710
+ consoleUrl
3711
+ };
3712
+ }
3713
+ const fileSize = fs12.statSync(filePath).size;
3714
+ logger.info("\u5F00\u59CB\u4E0A\u4F20\u5230 vivo \u5E94\u7528\u5546\u5E97...");
3715
+ logger.info(`\u6587\u4EF6: ${filePath} (${(fileSize / 1024 / 1024).toFixed(2)} MB)`);
3716
+ try {
3717
+ const retryStrategy = createUploadRetryStrategy(retryConfig);
3718
+ const fileMd5 = await this.calculateFileMD5(filePath);
3719
+ logger.info("\u6B63\u5728\u4E0A\u4F20 APK \u6587\u4EF6...");
3720
+ const packageName = vivoConfig.packageName || "";
3721
+ const uploadFileResult = await retryStrategy.execute(
3722
+ () => this.uploadApk(accessKey, accessSecret, filePath, packageName, fileMd5),
3723
+ "vivo file upload"
3724
+ );
3725
+ if (!uploadFileResult.success || !uploadFileResult.data) {
3726
+ throw uploadFileResult.error || new Error("File upload failed or no serialnumber returned");
3727
+ }
3728
+ const serialnumber = uploadFileResult.data;
3729
+ logger.info("\u6B63\u5728\u63D0\u4EA4\u7248\u672C\u4FE1\u606F...");
3730
+ const submitResult = await retryStrategy.execute(
3731
+ () => this.submitVersion(accessKey, accessSecret, {
3732
+ serialnumber,
3733
+ packageName: vivoConfig.packageName,
3734
+ versionCode: parseInt(metadata.buildNumber) || 1,
3735
+ fileMd5,
3736
+ updateDesc: metadata.changelog || "App Update"
3737
+ }),
3738
+ "vivo submit version"
3739
+ );
3740
+ if (!submitResult.success) {
3741
+ throw submitResult.error || new Error("Submit version failed");
3742
+ }
3743
+ logger.success("\u4E0A\u4F20\u5230 vivo \u5E94\u7528\u5546\u5E97\u6210\u529F!");
3744
+ return {
3745
+ platform: "vivo",
3746
+ success: true,
3747
+ message: "\u4E0A\u4F20\u6210\u529F, \u8BF7\u524D\u5F80\u540E\u53F0\u786E\u8BA4\u5E76\u63D0\u4EA4\u5BA1\u6838",
3748
+ consoleUrl
3749
+ };
3750
+ } catch (error) {
3751
+ logger.error(`\u4E0A\u4F20\u5230 vivo \u5931\u8D25: ${error.message}`);
3752
+ return {
3753
+ platform: "vivo",
3754
+ success: false,
3755
+ message: this.formatError(error),
3756
+ error,
3757
+ consoleUrl
3758
+ };
3759
+ }
3760
+ }
3761
+ /**
3762
+ * 计算文件 MD5
3763
+ */
3764
+ calculateFileMD5(filePath) {
3765
+ return new Promise((resolve, reject) => {
3766
+ const hash = crypto5.createHash("md5");
3767
+ const stream = fs12.createReadStream(filePath);
3768
+ stream.on("data", (data) => hash.update(data));
3769
+ stream.on("end", () => resolve(hash.digest("hex")));
3770
+ stream.on("error", reject);
3771
+ });
3772
+ }
3773
+ /**
3774
+ * 上传 APK 文件并获取流水号
3775
+ * 将公共参数与业务参数放入一个 multipart 请求中直接上传至 API_BASE
3776
+ */
3777
+ async uploadApk(accessKey, accessSecret, filePath, packageName, fileMd5) {
3778
+ const timestamp = String(Date.now());
3779
+ const paramsForSign = {
3780
+ // 公共参数
3781
+ access_key: accessKey,
3782
+ timestamp,
3783
+ format: "json",
3784
+ v: "1.0",
3785
+ sign_method: "hmac",
3786
+ target_app_key: "developer",
3787
+ method: "app.upload.apk.app",
3788
+ // 业务参数
3789
+ packageName,
3790
+ fileMd5
3791
+ };
3792
+ const sign = this.generateSign(paramsForSign, accessSecret);
3793
+ const form = new FormData7();
3794
+ for (const [key, value] of Object.entries(paramsForSign)) {
3795
+ form.append(key, value);
3796
+ }
3797
+ form.append("sign", sign);
3798
+ form.append("file", fs12.createReadStream(filePath), {
3799
+ filename: path8.basename(filePath),
3800
+ contentType: "application/vnd.android.package-archive"
3801
+ });
3802
+ logger.info(
3803
+ `[VIVO DEBUG] \u5F00\u59CB\u4E0A\u4F20 APK (API\u8BF7\u6C42) \u53C2\u6570(\u4E0D\u542B\u6587\u4EF6): ${JSON.stringify({ ...paramsForSign, sign })}`
3804
+ );
3805
+ const res = await axios8.post(_VivoUploader.API_BASE, form, {
3806
+ headers: form.getHeaders(),
3807
+ maxContentLength: Infinity,
3808
+ maxBodyLength: Infinity,
3809
+ timeout: 3e5
3810
+ });
3811
+ logger.info(`[VIVO DEBUG] \u4E0A\u4F20\u54CD\u5E94: ${JSON.stringify(res.data)}`);
3812
+ if (res.data.code !== 0) {
3813
+ throw new Error(`\u6587\u4EF6\u4E0A\u4F20\u5931\u8D25: ${res.data.msg || JSON.stringify(res.data)}`);
3814
+ }
3815
+ const serialnumber = res.data.data?.serialnumber || res.data.data;
3816
+ logger.info(`APK \u6587\u4EF6\u4E0A\u4F20\u5B8C\u6210\uFF0C\u6D41\u6C34\u53F7: ${serialnumber}`);
3817
+ return serialnumber;
3818
+ }
3819
+ /**
3820
+ * 提交版本更新信息
3821
+ */
3822
+ async submitVersion(accessKey, accessSecret, params) {
3823
+ const timestamp = String(Date.now());
3824
+ const reqParams = {
3825
+ access_key: accessKey,
3826
+ timestamp,
3827
+ format: "json",
3828
+ v: "1.0",
3829
+ sign_method: "hmac",
3830
+ target_app_key: "developer",
3831
+ method: "app.sync.update.app",
3832
+ packageName: params.packageName || "",
3833
+ // 文档必填
3834
+ versionCode: String(params.versionCode),
3835
+ // 文档必填 (Integer)
3836
+ apk: params.serialnumber,
3837
+ // 文档中的 apk 字段即为上传接口返回的 serialnumber
3838
+ fileMd5: params.fileMd5,
3839
+ // 文档必填
3840
+ onlineType: "1",
3841
+ // 1:立即上架 2:定时上架 (必填)
3842
+ compatibleDevice: "1",
3843
+ // 1:手机 2:手机和平板 3:平板 (必填)
3844
+ updateDesc: params.updateDesc
3845
+ };
3846
+ reqParams.sign = this.generateSign(reqParams, accessSecret);
3847
+ const formData = new URLSearchParams();
3848
+ for (const [key, value] of Object.entries(reqParams)) {
3849
+ formData.append(key, value);
3850
+ }
3851
+ const res = await axios8.post(_VivoUploader.API_BASE, formData.toString(), {
3852
+ headers: {
3853
+ "Content-Type": "application/x-www-form-urlencoded"
3854
+ },
3855
+ timeout: 3e4
3856
+ });
3857
+ if (res.data.code !== 0) {
3858
+ throw new Error(`\u63D0\u4EA4\u7248\u672C\u5931\u8D25: ${res.data.msg || JSON.stringify(res.data)}`);
3859
+ }
3860
+ logger.info("\u7248\u672C\u4FE1\u606F\u5DF2\u63D0\u4EA4");
3861
+ }
3862
+ /**
3863
+ * 格式化错误信息
3864
+ */
3865
+ formatError(error) {
3866
+ if (error.response?.data) {
3867
+ const data = error.response.data;
3868
+ return data.msg || data.message || error.message;
3869
+ }
3870
+ return error.message;
3871
+ }
3872
+ };
3873
+
3874
+ // src/adapters/tencent_uploader.ts
3875
+ import fs13 from "fs-extra";
3876
+ import path9 from "path";
3877
+ import axios9 from "axios";
3878
+ import crypto6 from "crypto";
3879
+ var TencentUploader = class _TencentUploader {
3880
+ name = "Tencent";
3881
+ /** 腾讯开放平台 API 基础地址 */
3882
+ static API_BASE = "https://p.open.qq.com/open_file/developer_api";
3883
+ /**
3884
+ * 接口签名生成 (HmacSHA256)
3885
+ * 规则: 所有参数按字典序排序拼接为 k1=v1&k2=v2... (不要进行 URL 编码)
3886
+ * 使用 accessSecret 计算 HmacSHA256,转小写 16 进制
3887
+ */
3888
+ generateSign(params, accessSecret) {
3889
+ const sortedKeys = Object.keys(params).sort();
3890
+ const signStr = sortedKeys.filter((key) => params[key] !== void 0 && params[key] !== null).map((key) => `${key}=${params[key]}`).join("&");
3891
+ return crypto6.createHmac("sha256", accessSecret).update(signStr).digest("hex").toLowerCase();
3892
+ }
3893
+ validateConfig(config) {
3894
+ if (!config?.publish?.tencent?.enable) return false;
3895
+ const auth = config.publish.tencent.auth;
3896
+ if (!auth?.userId || !auth?.appId || !auth?.accessSecret) {
3897
+ logger.error("Tencent config missing: userId, appId or accessSecret");
3898
+ return false;
3899
+ }
3900
+ return true;
3901
+ }
3902
+ canHandle(filePath) {
3903
+ return filePath.toLowerCase().endsWith(".apk");
3904
+ }
3905
+ async upload(filePath, config, metadata) {
3906
+ const tencentConfig = config.publish.tencent;
3907
+ const auth = tencentConfig.auth;
3908
+ logger.info(`Tencent \u8FD0\u884C\u65F6\u914D\u7F6E: ${JSON.stringify(tencentConfig)}`);
3909
+ const consoleUrl = "https://app.open.qq.com";
3910
+ if (!fs13.existsSync(filePath)) {
3911
+ return { platform: "tencent", success: false, message: `\u6587\u4EF6\u4E0D\u5B58\u5728: ${filePath}`, consoleUrl };
3912
+ }
3913
+ try {
3914
+ const stats = fs13.statSync(filePath);
3915
+ const fileName = path9.basename(filePath);
3916
+ logger.info("\u6B63\u5728\u83B7\u53D6\u9884\u7B7E\u540D\u4E0A\u4F20\u5730\u5740...");
3917
+ const pkgName = tencentConfig.packageName || "";
3918
+ const uploadInfo = await this.getFileUploadInfo(auth, stats.size, fileName, pkgName);
3919
+ logger.info(`\u83B7\u53D6\u6587\u4EF6\u4E0A\u4F20\u4FE1\u606F\u7ED3\u679C ${JSON.stringify(uploadInfo)}`);
3920
+ logger.info("\u6B63\u5728\u4E0A\u4F20\u6587\u4EF6\u5230\u817E\u8BAF\u4E91 COS (\u7ED5\u8FC7 API \u7F51\u5173\u9650\u5236)...");
3921
+ await this.uploadToCos(uploadInfo.pre_sign_url, filePath, stats.size);
3922
+ logger.info("\u6B63\u5728\u83B7\u53D6\u7EBF\u4E0A\u5E94\u7528\u8BE6\u60C5\u4EE5\u4FDD\u7559\u73B0\u6709\u914D\u7F6E...");
3923
+ const pkgInfo = await parsePackageInfo(filePath, {
3924
+ androidSdkPath: config.globalSettings?.androidSdkPath
3925
+ });
3926
+ const nativeCodes = pkgInfo?.nativeCode || [];
3927
+ const has64Bit = nativeCodes.includes("arm64-v8a") || nativeCodes.includes("x86_64");
3928
+ const has32Bit = nativeCodes.includes("armeabi-v7a") || nativeCodes.includes("armeabi") || nativeCodes.includes("x86");
3929
+ const is64Bit = has64Bit && !has32Bit;
3930
+ const md5 = pkgInfo?.md5;
3931
+ const onlineDetail = await this.queryAppDetail(
3932
+ auth,
3933
+ tencentConfig.packageName || pkgInfo?.packageName || ""
3934
+ );
3935
+ logger.info(`\u83B7\u53D6\u7EBF\u4E0A\u8BE6\u60C5\u6210\u529F: ${onlineDetail.app_name || "\u672A\u547D\u540D"}`);
3936
+ logger.info("\u6B63\u5728\u63D0\u4EA4\u6D41\u6C34\u53F7\u5B8C\u6210\u5BA1\u6838\u7533\u62A5...");
3937
+ const submitResult = await this.submitModifyAppInfo(
3938
+ auth,
3939
+ {
3940
+ ...onlineDetail,
3941
+ // 以前序详情为蓝本
3942
+ pkg_name: tencentConfig.packageName || pkgInfo?.packageName || onlineDetail.pkg_name || "",
3943
+ serial_number: uploadInfo.serial_number,
3944
+ update_desc: metadata.changelog || "\u7248\u672C\u66F4\u65B0",
3945
+ is64Bit,
3946
+ md5
3947
+ },
3948
+ { timeout: tencentConfig.timeout || 6e4 }
3949
+ );
3950
+ logger.info(`\u63D0\u4EA4\u6D41\u6C34\u53F7\u5B8C\u6210\u5BA1\u6838\u7533\u62A5\u7ED3\u679C: ${JSON.stringify(submitResult)}`);
3951
+ logger.success("\u817E\u8BAF\u5E94\u7528\u5B9D\u4E0A\u4F20\u5E76\u63D0\u4EA4\u6210\u529F!");
3952
+ return { platform: "tencent", success: true, message: "\u4E0A\u4F20\u5E76\u63D0\u4EA4\u5BA1\u6838\u6210\u529F", consoleUrl };
3953
+ } catch (error) {
3954
+ logger.error(`\u817E\u8BAF\u4E0A\u4F20\u5931\u8D25: ${JSON.stringify(error)}`);
3955
+ logger.error(`\u817E\u8BAF\u4E0A\u4F20\u5931\u8D25: ${error.stack}`);
3956
+ return { platform: "tencent", success: false, message: error.message, error, consoleUrl };
3957
+ }
3958
+ }
3959
+ /**
3960
+ * 阶段 1: 获取文件上传信息
3961
+ */
3962
+ async getFileUploadInfo(auth, fileSize, fileName, pkgName) {
3963
+ logger.info(`Tencent getFileUploadInfo: ${JSON.stringify(auth)}`);
3964
+ const userId = String(auth.userId || "");
3965
+ const accessSecret = String(auth.accessSecret || "");
3966
+ const signParams = {
3967
+ user_id: userId,
3968
+ timestamp: String(Math.floor(Date.now() / 1e3)),
3969
+ pkg_name: pkgName,
3970
+ app_id: String(auth.appId || ""),
3971
+ file_size: String(fileSize),
3972
+ file_name: fileName,
3973
+ file_type: "apk"
3974
+ };
3975
+ const sign = this.generateSign(signParams, accessSecret);
3976
+ const formParams = {
3977
+ ...signParams,
3978
+ sign
3979
+ };
3980
+ const url = `${_TencentUploader.API_BASE}/get_file_upload_info`;
3981
+ logger.info(`\u6B63\u5728\u8BF7\u6C42 Tencent API: ${url}`);
3982
+ logger.info(`formParams: ${JSON.stringify(formParams)}`);
3983
+ const res = await axios9.post(url, new URLSearchParams(formParams).toString(), {
3984
+ headers: { "Content-Type": "application/x-www-form-urlencoded" }
3985
+ });
3986
+ if (res.data.ret !== 0) {
3987
+ throw new Error(`\u83B7\u53D6\u4E0A\u4F20\u4FE1\u606F\u5931\u8D25: ${res.data.msg} (ret:${res.data.ret})`);
3988
+ }
3989
+ return res.data;
3990
+ }
3991
+ /**
3992
+ * 获取应用详情
3993
+ */
3994
+ async queryAppDetail(auth, pkgName) {
3995
+ const userId = auth.userId || "";
3996
+ const accessSecret = auth.accessSecret || "";
3997
+ const signParams = {
3998
+ user_id: userId,
3999
+ timestamp: String(Math.floor(Date.now() / 1e3)),
4000
+ app_id: String(auth.appId || ""),
4001
+ pkg_name: pkgName
4002
+ };
4003
+ const sign = this.generateSign(signParams, accessSecret);
4004
+ const formParams = { ...signParams, sign };
4005
+ const url = `${_TencentUploader.API_BASE}/query_app_detail`;
4006
+ const res = await axios9.post(url, new URLSearchParams(formParams).toString(), {
4007
+ headers: { "Content-Type": "application/x-www-form-urlencoded" }
4008
+ });
4009
+ if (res.data.ret !== 0) {
4010
+ logger.warn(`\u67E5\u8BE2\u5E94\u7528\u8BE6\u60C5\u5931\u8D25: ${res.data.msg}\uFF0C\u5C06\u4F7F\u7528\u7A7A\u914D\u7F6E\u7EE7\u7EED`);
4011
+ return {};
4012
+ }
4013
+ return res.data;
4014
+ }
4015
+ /**
4016
+ * 阶段 2: 直接上传到 COS (PUT)
4017
+ */
4018
+ async uploadToCos(url, filePath, size) {
4019
+ await axios9.put(url, fs13.createReadStream(filePath), {
4020
+ headers: {
4021
+ "Content-Type": "application/octet-stream",
4022
+ "Content-Length": size
4023
+ },
4024
+ maxContentLength: Infinity,
4025
+ maxBodyLength: Infinity,
4026
+ timeout: 9e5,
4027
+ // 15 分钟
4028
+ onUploadProgress: (p) => {
4029
+ if (p.total) {
4030
+ const percent = Math.round(p.loaded * 100 / p.total);
4031
+ if (percent % 20 === 0) logger.info(`\u4E0A\u4F20\u8FDB\u5EA6: ${percent}%`);
4032
+ }
4033
+ }
4034
+ });
4035
+ }
4036
+ /**
4037
+ * 阶段 3: 提交流水号信息
4038
+ */
4039
+ async submitModifyAppInfo(auth, data, options) {
4040
+ const userId = auth.userId || "";
4041
+ const accessSecret = auth.accessSecret || "";
4042
+ const signParams = {
4043
+ user_id: userId,
4044
+ timestamp: String(Math.floor(Date.now() / 1e3)),
4045
+ app_id: String(auth.appId || ""),
4046
+ pkg_name: String(data.pkg_name || ""),
4047
+ feature: String(data.update_desc || ""),
4048
+ deploy_type: String(data.deploy_type || "1")
4049
+ // 默认审核后立即发布
4050
+ };
4051
+ const skipFields = [
4052
+ "ret",
4053
+ "msg",
4054
+ "user_id",
4055
+ "timestamp",
4056
+ "sign",
4057
+ "app_id",
4058
+ "pkg_name",
4059
+ "feature",
4060
+ "is64Bit",
4061
+ "md5",
4062
+ "serial_number"
4063
+ ];
4064
+ Object.keys(data).forEach((key) => {
4065
+ if (!skipFields.includes(key) && data[key] !== void 0 && data[key] !== null) {
4066
+ signParams[key] = String(data[key]);
4067
+ }
4068
+ });
4069
+ if (data.is64Bit) {
4070
+ signParams.apk64_file_serial_number = String(data.serial_number || "");
4071
+ if (data.md5) signParams.apk64_file_md5 = data.md5;
4072
+ delete signParams.apk32_file_serial_number;
4073
+ delete signParams.apk32_file_md5;
4074
+ } else {
4075
+ signParams.apk32_file_serial_number = String(data.serial_number || "");
4076
+ if (data.md5) signParams.apk32_file_md5 = data.md5;
4077
+ delete signParams.apk64_file_serial_number;
4078
+ delete signParams.apk64_file_md5;
4079
+ }
4080
+ const sign = this.generateSign(signParams, accessSecret);
4081
+ const formParams = {
4082
+ ...signParams,
4083
+ sign
4084
+ };
4085
+ logger.info(`formParams: ${JSON.stringify(formParams)}`);
4086
+ const url = `${_TencentUploader.API_BASE}/update_app`;
4087
+ const res = await axios9.post(url, new URLSearchParams(formParams).toString(), {
4088
+ headers: { "Content-Type": "application/x-www-form-urlencoded" }
4089
+ });
4090
+ if (res.data.ret !== 0) {
4091
+ throw new Error(`\u63D0\u4EA4\u6D41\u6C34\u53F7\u5931\u8D25: ${res.data.msg} (ret:${res.data.ret})`);
4092
+ }
4093
+ return res.data;
4094
+ }
4095
+ };
4096
+ export {
4097
+ AdHocUploader,
4098
+ AppleJWTGenerator,
4099
+ AppleStoreUploader,
4100
+ ConfigValidator,
4101
+ DEFAULT_RETRY_CONFIG,
4102
+ EnvValidator,
4103
+ ErrorCategory,
4104
+ HarmonyUploader,
4105
+ HuaweiUploader,
4106
+ OppoUploader,
4107
+ PgyerUploader,
4108
+ RetryStrategy,
4109
+ TencentUploader,
4110
+ TestFlightUploader,
4111
+ UploadManager,
4112
+ VivoUploader,
4113
+ XiaomiUploader,
4114
+ createUploadManager,
4115
+ createUploadRetryStrategy,
4116
+ parsePackageInfo
4117
+ };
4118
+ //# sourceMappingURL=index.js.map