connect-api-cli 1.1.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/cli.js ADDED
@@ -0,0 +1,2901 @@
1
+ #!/usr/bin/env node
2
+ "use strict";
3
+ var __create = Object.create;
4
+ var __defProp = Object.defineProperty;
5
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
6
+ var __getOwnPropNames = Object.getOwnPropertyNames;
7
+ var __getProtoOf = Object.getPrototypeOf;
8
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
9
+ var __copyProps = (to, from, except, desc) => {
10
+ if (from && typeof from === "object" || typeof from === "function") {
11
+ for (let key of __getOwnPropNames(from))
12
+ if (!__hasOwnProp.call(to, key) && key !== except)
13
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
14
+ }
15
+ return to;
16
+ };
17
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
18
+ // If the importer is in node compatibility mode or this is not an ESM
19
+ // file that has been converted to a CommonJS file using a Babel-
20
+ // compatible transform (i.e. "__esModule" has not been set), then set
21
+ // "default" to the CommonJS "module.exports" for node compatibility.
22
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
23
+ mod
24
+ ));
25
+
26
+ // src/cli/index.ts
27
+ var import_commander = require("commander");
28
+ var fs7 = __toESM(require("fs"));
29
+ var import_path6 = __toESM(require("path"));
30
+
31
+ // src/services/auth.ts
32
+ var import_axios = __toESM(require("axios"));
33
+ var crypto = __toESM(require("crypto"));
34
+
35
+ // src/config/index.ts
36
+ var dotenv = __toESM(require("dotenv"));
37
+ var import_path = __toESM(require("path"));
38
+ var import_fs = __toESM(require("fs"));
39
+ var envPath = import_path.default.resolve(process.cwd(), ".env");
40
+ if (import_fs.default.existsSync(envPath)) {
41
+ dotenv.config({ path: envPath, quiet: true });
42
+ } else {
43
+ dotenv.config({ quiet: true });
44
+ }
45
+ var DEFAULT_OAUTH = {
46
+ clientId: "117427577",
47
+ authUrl: "https://oauth-login.cloud.huawei.com/oauth2/v3/authorize",
48
+ tokenUrl: "https://connect-api.cloud.huawei.com/api/cag/v1/access-token/generate",
49
+ refreshUrl: "https://connect-api.cloud.huawei.com/api/cag/v1/access-token/refresh",
50
+ redirectUri: "http://localhost:12306",
51
+ scope: "openid profile https://www.huawei.com/auth/agc/publish https://www.huawei.com/auth/agc/develop"
52
+ };
53
+ function loadServiceAccountCredentials(filePath) {
54
+ const abs = import_path.default.isAbsolute(filePath) ? filePath : import_path.default.resolve(process.cwd(), filePath);
55
+ if (!import_fs.default.existsSync(abs)) {
56
+ throw new Error(`Service Account credentials file not found: ${abs}`);
57
+ }
58
+ let raw;
59
+ try {
60
+ raw = JSON.parse(import_fs.default.readFileSync(abs, "utf8"));
61
+ } catch {
62
+ throw new Error(`Invalid Service Account credentials JSON: ${abs}`);
63
+ }
64
+ const creds = raw;
65
+ if (!creds.key_id || !creds.private_key || !creds.sub_account) {
66
+ throw new Error(
67
+ `Service Account credentials missing required fields (key_id, private_key, sub_account): ${abs}`
68
+ );
69
+ }
70
+ return {
71
+ key_id: creds.key_id,
72
+ private_key: creds.private_key,
73
+ sub_account: creds.sub_account,
74
+ project_id: creds.project_id,
75
+ auth_uri: creds.auth_uri,
76
+ token_uri: creds.token_uri,
77
+ auth_provider_cert_uri: creds.auth_provider_cert_uri,
78
+ client_cert_uri: creds.client_cert_uri
79
+ };
80
+ }
81
+ function getConfig() {
82
+ const clientId = process.env.AGC_CLIENT_ID;
83
+ const clientSecret = process.env.AGC_CLIENT_SECRET;
84
+ const authMode = process.env.AGC_AUTH_MODE ?? "client_credentials";
85
+ if (authMode === "client_credentials" && (!clientId || !clientSecret)) {
86
+ throw new Error("Missing AGC credentials. Please set AGC_CLIENT_ID and AGC_CLIENT_SECRET environment variables.");
87
+ }
88
+ if (authMode === "service_account" && !process.env.AGC_SA_CREDENTIALS) {
89
+ throw new Error(
90
+ "Missing Service Account credentials. Please set AGC_SA_CREDENTIALS to the path of your *_private.json file."
91
+ );
92
+ }
93
+ const oauth = {
94
+ clientId: process.env.AGC_OAUTH_CLIENT_ID || DEFAULT_OAUTH.clientId,
95
+ authUrl: process.env.AGC_OAUTH_AUTH_URL || DEFAULT_OAUTH.authUrl,
96
+ tokenUrl: process.env.AGC_OAUTH_TOKEN_URL || DEFAULT_OAUTH.tokenUrl,
97
+ refreshUrl: process.env.AGC_OAUTH_REFRESH_URL || DEFAULT_OAUTH.refreshUrl,
98
+ redirectUri: process.env.AGC_OAUTH_REDIRECT_URI || DEFAULT_OAUTH.redirectUri,
99
+ scope: process.env.AGC_OAUTH_SCOPE || DEFAULT_OAUTH.scope
100
+ };
101
+ let serviceAccount;
102
+ if (authMode === "service_account") {
103
+ const credentialsPath = import_path.default.isAbsolute(process.env.AGC_SA_CREDENTIALS) ? process.env.AGC_SA_CREDENTIALS : import_path.default.resolve(process.cwd(), process.env.AGC_SA_CREDENTIALS);
104
+ serviceAccount = {
105
+ credentialsPath,
106
+ credentials: loadServiceAccountCredentials(credentialsPath)
107
+ };
108
+ }
109
+ const resolvedClientId = authMode === "oauth" ? oauth.clientId : authMode === "service_account" ? serviceAccount.credentials.key_id : clientId || "";
110
+ return {
111
+ clientId: resolvedClientId,
112
+ clientSecret: clientSecret || "",
113
+ domain: process.env.AGC_DOMAIN || "connect-api.cloud.huawei.com",
114
+ authMode,
115
+ oauth,
116
+ teamId: process.env.AGC_TEAM_ID || void 0,
117
+ serviceAccount
118
+ };
119
+ }
120
+
121
+ // src/services/auth.ts
122
+ var SA_AUD = "https://oauth-login.cloud.huawei.com/oauth2/v3/token";
123
+ var SA_JWT_TTL_SEC = 3600;
124
+ var AuthService = class {
125
+ /**
126
+ * 获取访问API的Token(service to service,client_credentials 模式)
127
+ */
128
+ static async getToken() {
129
+ const config2 = getConfig();
130
+ const url = `https://${config2.domain}/api/oauth2/v1/token`;
131
+ const payload = {
132
+ grant_type: "client_credentials",
133
+ client_id: config2.clientId,
134
+ client_secret: config2.clientSecret
135
+ };
136
+ const response = await import_axios.default.post(url, payload, {
137
+ headers: {
138
+ "Content-Type": "application/json"
139
+ }
140
+ });
141
+ return response.data;
142
+ }
143
+ /**
144
+ * 使用 Service Account 凭据本地签发 PS256 JWT(可直接作为 Authorization Bearer)。
145
+ * 参见:获取服务端授权 → Service Account 方式。
146
+ */
147
+ static createServiceAccountJwt(credentials, nowSec = Math.floor(Date.now() / 1e3)) {
148
+ const iat = nowSec;
149
+ const exp = iat + SA_JWT_TTL_SEC;
150
+ const aud = credentials.token_uri || SA_AUD;
151
+ const header = {
152
+ kid: credentials.key_id,
153
+ typ: "JWT",
154
+ alg: "PS256"
155
+ };
156
+ const payload = {
157
+ aud,
158
+ iss: credentials.sub_account,
159
+ exp,
160
+ iat
161
+ };
162
+ const encodedHeader = base64UrlEncode(Buffer.from(JSON.stringify(header), "utf8"));
163
+ const encodedPayload = base64UrlEncode(Buffer.from(JSON.stringify(payload), "utf8"));
164
+ const signingInput = `${encodedHeader}.${encodedPayload}`;
165
+ const privateKey = crypto.createPrivateKey(normalizePem(credentials.private_key));
166
+ const signature = crypto.sign("sha256", Buffer.from(signingInput, "utf8"), {
167
+ key: privateKey,
168
+ padding: crypto.constants.RSA_PKCS1_PSS_PADDING,
169
+ // PS256:saltLength = digest length(与 Java SHA256withRSA/PSS 常见默认一致)
170
+ saltLength: crypto.constants.RSA_PSS_SALTLEN_DIGEST
171
+ });
172
+ const jwt = `${signingInput}.${base64UrlEncode(signature)}`;
173
+ return {
174
+ jwt,
175
+ expiresIn: SA_JWT_TTL_SEC,
176
+ expiresAt: exp * 1e3
177
+ };
178
+ }
179
+ /**
180
+ * 拼装 OAuth 授权 URL(含随机 state 防 CSRF)
181
+ */
182
+ static buildAuthUrl(state) {
183
+ const cfg = getConfig();
184
+ const url = new URL(cfg.oauth.authUrl);
185
+ url.searchParams.set("client_id", cfg.oauth.clientId);
186
+ url.searchParams.set("redirect_uri", cfg.oauth.redirectUri);
187
+ url.searchParams.set("scope", cfg.oauth.scope);
188
+ url.searchParams.set("response_type", "code");
189
+ url.searchParams.set("state", state);
190
+ url.searchParams.set("access_type", "offline");
191
+ return url.toString();
192
+ }
193
+ /**
194
+ * 用授权码换取 OAuth token(与插件 /access-token/generate 对齐)
195
+ */
196
+ static async getOAuthToken(code, redirectUri) {
197
+ const cfg = getConfig();
198
+ const controller = new AbortController();
199
+ const timeoutId = setTimeout(() => controller.abort(), 3e4);
200
+ try {
201
+ const res = await import_axios.default.post(cfg.oauth.tokenUrl, { code, redirectUri }, {
202
+ headers: { "Content-Type": "application/json" },
203
+ signal: controller.signal
204
+ });
205
+ if (!res.data.ret || res.data.ret.code !== 0) {
206
+ throw new Error(res.data.ret?.msg || "Authentication failed");
207
+ }
208
+ return res.data;
209
+ } catch (err) {
210
+ if (err instanceof Error && err.name === "AbortError") {
211
+ throw new Error("\u8BF7\u6C42\u8D85\u65F6\uFF0C\u8BF7\u68C0\u67E5\u7F51\u7EDC\u8FDE\u63A5");
212
+ }
213
+ throw err;
214
+ } finally {
215
+ clearTimeout(timeoutId);
216
+ }
217
+ }
218
+ /**
219
+ * 用 refreshToken 刷新 OAuth token(与插件 /access-token/refresh 对齐)。
220
+ * 刷新接口只返回新的 accessToken,refreshToken 沿用旧值。
221
+ */
222
+ static async refreshOAuthToken(refreshToken) {
223
+ const cfg = getConfig();
224
+ const controller = new AbortController();
225
+ const timeoutId = setTimeout(() => controller.abort(), 3e4);
226
+ try {
227
+ const res = await import_axios.default.post(cfg.oauth.refreshUrl, { refreshToken }, {
228
+ headers: { "Content-Type": "application/json" },
229
+ signal: controller.signal
230
+ });
231
+ if (!res.data.ret || res.data.ret.code !== 0) {
232
+ throw new Error(res.data.ret?.msg || "Refresh failed");
233
+ }
234
+ return res.data;
235
+ } catch (err) {
236
+ if (err instanceof Error && err.name === "AbortError") {
237
+ throw new Error("\u8BF7\u6C42\u8D85\u65F6\uFF0C\u8BF7\u68C0\u67E5\u7F51\u7EDC\u8FDE\u63A5");
238
+ }
239
+ throw err;
240
+ } finally {
241
+ clearTimeout(timeoutId);
242
+ }
243
+ }
244
+ };
245
+ function base64UrlEncode(buf) {
246
+ return buf.toString("base64").replace(/=/g, "").replace(/\+/g, "-").replace(/\//g, "_");
247
+ }
248
+ function normalizePem(privateKey) {
249
+ const trimmed = privateKey.trim();
250
+ if (trimmed.includes("\\n")) {
251
+ return trimmed.replace(/\\n/g, "\n");
252
+ }
253
+ return trimmed;
254
+ }
255
+
256
+ // src/core/oauth-team.ts
257
+ var import_axios2 = __toESM(require("axios"));
258
+ var import_fs2 = __toESM(require("fs"));
259
+ var import_path2 = __toESM(require("path"));
260
+ var import_os = __toESM(require("os"));
261
+ var TOKEN_FILE = import_path2.default.join(import_os.default.homedir(), ".connect-api-cli-token.json");
262
+ var cachedTeamId;
263
+ function readPersistedTeamId() {
264
+ try {
265
+ if (!import_fs2.default.existsSync(TOKEN_FILE)) return void 0;
266
+ const data = JSON.parse(import_fs2.default.readFileSync(TOKEN_FILE, "utf8"));
267
+ return data.teamId || void 0;
268
+ } catch {
269
+ return void 0;
270
+ }
271
+ }
272
+ function writePersistedTeamId(teamId) {
273
+ try {
274
+ if (!import_fs2.default.existsSync(TOKEN_FILE)) return;
275
+ const data = JSON.parse(import_fs2.default.readFileSync(TOKEN_FILE, "utf8"));
276
+ data.teamId = teamId;
277
+ import_fs2.default.writeFileSync(TOKEN_FILE, JSON.stringify(data, null, 2), "utf8");
278
+ } catch {
279
+ }
280
+ }
281
+ async function resolveOAuthTeamId(cfg, accessToken) {
282
+ if (cfg.teamId) {
283
+ return cfg.teamId;
284
+ }
285
+ if (cachedTeamId !== void 0) {
286
+ return cachedTeamId || void 0;
287
+ }
288
+ const persisted = readPersistedTeamId();
289
+ if (persisted) {
290
+ cachedTeamId = persisted;
291
+ return persisted;
292
+ }
293
+ const res = await import_axios2.default.get(
294
+ `https://${cfg.domain}/api/ups/user-permission-service/v1/user-team-list`,
295
+ {
296
+ headers: {
297
+ oauth2Token: accessToken,
298
+ "Content-Type": "application/json"
299
+ },
300
+ timeout: 3e4
301
+ }
302
+ );
303
+ const teams = res.data.teams || [];
304
+ if (res.data.ret && res.data.ret.code !== 0) {
305
+ throw new Error(
306
+ `Failed to list teams for OAuth teamId: ${res.data.ret.msg || JSON.stringify(res.data.ret)}`
307
+ );
308
+ }
309
+ if (teams.length === 0) {
310
+ cachedTeamId = null;
311
+ throw new Error("OAuth account has no teams. Cannot set teamId for API calls.");
312
+ }
313
+ if (teams.length === 1) {
314
+ cachedTeamId = teams[0].id;
315
+ writePersistedTeamId(cachedTeamId);
316
+ return cachedTeamId;
317
+ }
318
+ cachedTeamId = null;
319
+ const preview = teams.slice(0, 8).map((t) => `${t.id}${t.name ? `(${t.name})` : ""}`).join(", ");
320
+ throw new Error(
321
+ `Multiple teams found (${teams.length}). Set AGC_TEAM_ID to one of: ${preview}`
322
+ );
323
+ }
324
+ function getCachedOAuthTeamId() {
325
+ if (cachedTeamId) return cachedTeamId;
326
+ return readPersistedTeamId();
327
+ }
328
+ function clearOAuthTeamIdCache() {
329
+ cachedTeamId = void 0;
330
+ }
331
+
332
+ // src/core/auth-mgr.ts
333
+ var crypto2 = __toESM(require("crypto"));
334
+ var http = __toESM(require("http"));
335
+ var import_child_process = require("child_process");
336
+ var import_fs3 = __toESM(require("fs"));
337
+ var import_path3 = __toESM(require("path"));
338
+ var import_os2 = __toESM(require("os"));
339
+ var AuthManager = class {
340
+ static cacheFile = import_path3.default.join(import_os2.default.homedir(), ".connect-api-cli-token.json");
341
+ /**
342
+ * 获取当前生效的 access token,并具备自动刷新能力:
343
+ * - OAuth 模式:token 过期时优先用 refreshToken 自动刷新,无需重新登录
344
+ * - client_credentials / service_account:过期后重新换取 / 重新签 JWT
345
+ */
346
+ static async getAccessToken() {
347
+ const cfg = getConfig();
348
+ const cache = this.readCache();
349
+ const sameCredential = cache && cache.clientId === cfg.clientId && cache.domain === cfg.domain && cache.authMode === cfg.authMode;
350
+ if (sameCredential && cache.expiresAt > Date.now() + 5 * 60 * 1e3) {
351
+ return cache.accessToken;
352
+ }
353
+ if (cfg.authMode === "oauth" && cache?.refreshToken) {
354
+ try {
355
+ const refreshed = await AuthService.refreshOAuthToken(cache.refreshToken);
356
+ const expiresAt = Date.now() + refreshed.expireTime * 1e3;
357
+ this.writeCache({
358
+ accessToken: refreshed.accessToken,
359
+ expiresAt,
360
+ clientId: cfg.clientId,
361
+ domain: cfg.domain,
362
+ authMode: cfg.authMode,
363
+ refreshToken: cache.refreshToken
364
+ // 刷新接口不返回新 refreshToken,沿用旧值
365
+ });
366
+ return refreshed.accessToken;
367
+ } catch (e) {
368
+ console.error("OAuth token refresh failed, need to re-login:", e instanceof Error ? e.message : String(e));
369
+ this.clearCache();
370
+ }
371
+ }
372
+ return this.acquire();
373
+ }
374
+ /** 登录入口:按当前认证模式获取并缓存 token */
375
+ static async login() {
376
+ clearOAuthTeamIdCache();
377
+ return this.acquire();
378
+ }
379
+ /** 按当前认证模式获取 token(client_credentials / service_account / oauth) */
380
+ static async acquire() {
381
+ const cfg = getConfig();
382
+ if (cfg.authMode === "oauth") {
383
+ return this.loginOAuth();
384
+ }
385
+ if (cfg.authMode === "service_account") {
386
+ if (!cfg.serviceAccount) {
387
+ throw new Error("Service Account credentials not loaded. Set AGC_SA_CREDENTIALS.");
388
+ }
389
+ const { jwt, expiresAt } = AuthService.createServiceAccountJwt(cfg.serviceAccount.credentials);
390
+ this.writeCache({
391
+ accessToken: jwt,
392
+ expiresAt,
393
+ clientId: cfg.clientId,
394
+ domain: cfg.domain,
395
+ authMode: cfg.authMode
396
+ });
397
+ return jwt;
398
+ }
399
+ const res = await AuthService.getToken();
400
+ if (res.access_token && res.expires_in) {
401
+ const expiresAt = Date.now() + res.expires_in * 1e3;
402
+ this.writeCache({
403
+ accessToken: res.access_token,
404
+ expiresAt,
405
+ clientId: cfg.clientId,
406
+ domain: cfg.domain,
407
+ authMode: cfg.authMode
408
+ });
409
+ return res.access_token;
410
+ }
411
+ throw new Error(`Failed to get token: ${JSON.stringify(res.ret)}`);
412
+ }
413
+ /** OAuth 授权码登录:启动本地回调服务器 + 打开浏览器 */
414
+ static loginOAuth() {
415
+ return new Promise((resolve, reject) => {
416
+ const cfg = getConfig();
417
+ const redirectUri = cfg.oauth.redirectUri;
418
+ const port = Number(new URL(redirectUri).port || 80);
419
+ const state = crypto2.randomBytes(32).toString("hex");
420
+ const server = http.createServer(async (req, res) => {
421
+ try {
422
+ const url = new URL(req.url, `http://${req.headers.host}`);
423
+ const code = url.searchParams.get("code");
424
+ const returnedState = url.searchParams.get("state");
425
+ if (!code || returnedState !== state) {
426
+ res.writeHead(400, { "Content-Type": "text/html; charset=utf-8" });
427
+ res.end("<h3>\u65E0\u6548\u7684\u56DE\u8C03\u53C2\u6570</h3>");
428
+ return;
429
+ }
430
+ const token = await AuthService.getOAuthToken(code, redirectUri);
431
+ const expiresAt = Date.now() + token.expireTime * 1e3;
432
+ this.writeCache({
433
+ accessToken: token.accessToken,
434
+ expiresAt,
435
+ clientId: cfg.clientId,
436
+ domain: cfg.domain,
437
+ authMode: cfg.authMode,
438
+ refreshToken: token.refreshToken
439
+ });
440
+ res.writeHead(200, { "Content-Type": "text/html; charset=utf-8" });
441
+ res.end('<!DOCTYPE html><html><body style="font-family:sans-serif;padding:40px;text-align:center"><h2>\u767B\u5F55\u6210\u529F\uFF0C\u53EF\u5173\u95ED\u6B64\u7A97\u53E3</h2></body></html>');
442
+ server.close();
443
+ resolve(token.accessToken);
444
+ } catch (err) {
445
+ server.close();
446
+ reject(err instanceof Error ? err : new Error(String(err)));
447
+ }
448
+ });
449
+ server.on("error", (err) => {
450
+ server.close();
451
+ reject(err);
452
+ });
453
+ server.listen(port, () => {
454
+ const authUrl = AuthService.buildAuthUrl(state);
455
+ console.log("\u8BF7\u5728\u6D4F\u89C8\u5668\u4E2D\u5B8C\u6210\u534E\u4E3A\u8D26\u53F7\u6388\u6743...");
456
+ console.log(`\u82E5\u6D4F\u89C8\u5668\u672A\u81EA\u52A8\u6253\u5F00\uFF0C\u8BF7\u8BBF\u95EE: ${authUrl}`);
457
+ openBrowser(authUrl);
458
+ });
459
+ });
460
+ }
461
+ /** 查询缓存状态(供 status 命令显示) */
462
+ static getStatus() {
463
+ return this.readCache();
464
+ }
465
+ static readCache() {
466
+ try {
467
+ if (import_fs3.default.existsSync(this.cacheFile)) {
468
+ const data = import_fs3.default.readFileSync(this.cacheFile, "utf8");
469
+ return JSON.parse(data);
470
+ }
471
+ } catch (e) {
472
+ }
473
+ return null;
474
+ }
475
+ static writeCache(cache) {
476
+ try {
477
+ import_fs3.default.writeFileSync(this.cacheFile, JSON.stringify(cache, null, 2), "utf8");
478
+ } catch (e) {
479
+ }
480
+ }
481
+ /**
482
+ * 清除缓存的 Token(登出)
483
+ */
484
+ static clearCache() {
485
+ clearOAuthTeamIdCache();
486
+ try {
487
+ if (import_fs3.default.existsSync(this.cacheFile)) {
488
+ import_fs3.default.unlinkSync(this.cacheFile);
489
+ return true;
490
+ }
491
+ return false;
492
+ } catch (e) {
493
+ return false;
494
+ }
495
+ }
496
+ };
497
+ function openBrowser(url) {
498
+ const platform = process.platform;
499
+ const cmd = platform === "darwin" ? "open" : platform === "win32" ? 'start ""' : "xdg-open";
500
+ (0, import_child_process.exec)(`${cmd} "${url}"`, (err) => {
501
+ if (err) {
502
+ console.error("\u65E0\u6CD5\u81EA\u52A8\u6253\u5F00\u6D4F\u89C8\u5668\uFF0C\u8BF7\u624B\u52A8\u590D\u5236\u4E0A\u9762\u7684\u94FE\u63A5\u8BBF\u95EE\u3002");
503
+ }
504
+ });
505
+ }
506
+
507
+ // src/core/http.ts
508
+ var import_axios3 = __toESM(require("axios"));
509
+ var agcClient = import_axios3.default.create();
510
+ function setHeader(headers, name, value) {
511
+ if (typeof headers?.set === "function") {
512
+ headers.set(name, value);
513
+ } else {
514
+ headers[name] = value;
515
+ }
516
+ }
517
+ function deleteHeader(headers, name) {
518
+ if (typeof headers?.delete === "function") {
519
+ headers.delete(name);
520
+ } else {
521
+ delete headers[name];
522
+ }
523
+ }
524
+ function getHeader(headers, name) {
525
+ if (typeof headers?.get === "function") {
526
+ return headers.get(name);
527
+ }
528
+ return headers?.[name] ?? headers?.[name.toLowerCase()];
529
+ }
530
+ function applyAuthHeaders(headers, token, cfg, force = false) {
531
+ if (cfg.authMode === "oauth") {
532
+ deleteHeader(headers, "Authorization");
533
+ deleteHeader(headers, "client_id");
534
+ setHeader(headers, "oauth2Token", token);
535
+ return;
536
+ }
537
+ deleteHeader(headers, "oauth2Token");
538
+ if (force || !getHeader(headers, "Authorization")) {
539
+ setHeader(headers, "Authorization", `Bearer ${token}`);
540
+ }
541
+ if (cfg.authMode !== "service_account" && !getHeader(headers, "client_id")) {
542
+ setHeader(headers, "client_id", cfg.clientId);
543
+ }
544
+ }
545
+ agcClient.interceptors.request.use(async (config2) => {
546
+ const cfg = getConfig();
547
+ if (!config2.baseURL) {
548
+ config2.baseURL = `https://${cfg.domain}`;
549
+ }
550
+ const token = await AuthManager.getAccessToken();
551
+ if (!config2.headers) {
552
+ config2.headers = {};
553
+ }
554
+ applyAuthHeaders(config2.headers, token, cfg);
555
+ if (cfg.authMode === "oauth" && !getHeader(config2.headers, "teamId")) {
556
+ const teamId = await resolveOAuthTeamId(cfg, token);
557
+ if (teamId) {
558
+ setHeader(config2.headers, "teamId", teamId);
559
+ }
560
+ }
561
+ if (config2.data !== void 0 && !getHeader(config2.headers, "Content-Type")) {
562
+ setHeader(config2.headers, "Content-Type", "application/json");
563
+ }
564
+ return config2;
565
+ }, (error) => {
566
+ return Promise.reject(error);
567
+ });
568
+ agcClient.interceptors.response.use(
569
+ (res) => res,
570
+ async (err) => {
571
+ const original = err.config;
572
+ const status = err.response?.status;
573
+ if (status === 401 && original && !original._retry) {
574
+ original._retry = true;
575
+ try {
576
+ const cfg = getConfig();
577
+ const newToken = await AuthManager.getAccessToken();
578
+ if (!original.headers) {
579
+ original.headers = {};
580
+ }
581
+ applyAuthHeaders(original.headers, newToken, cfg, true);
582
+ return agcClient(original);
583
+ } catch (e) {
584
+ return Promise.reject(err);
585
+ }
586
+ }
587
+ if (status === 401 || status === 403) {
588
+ const body = err.response?.data;
589
+ const msg = typeof body === "object" ? JSON.stringify(body, null, 2) : body;
590
+ err.message = err.message + (msg ? `
591
+ API \u54CD\u5E94: ${msg}` : "");
592
+ }
593
+ return Promise.reject(err);
594
+ }
595
+ );
596
+
597
+ // src/services/publish.ts
598
+ function appIdHeaders(appId) {
599
+ return { appId };
600
+ }
601
+ function withOptionalParams(base) {
602
+ const out = {};
603
+ for (const [k, v] of Object.entries(base)) {
604
+ if (v !== void 0) out[k] = v;
605
+ }
606
+ return out;
607
+ }
608
+ var PublishService = class {
609
+ /** 查询应用包名对应的 appid */
610
+ static async getAppIdList(packageName, packageTypes) {
611
+ const response = await agcClient.get("/api/publish/v2/appid-list", {
612
+ params: withOptionalParams({ packageName, packageTypes })
613
+ });
614
+ return response.data;
615
+ }
616
+ /** 创建应用或元服务(projectId 为 query 参数) */
617
+ static async createApp(req) {
618
+ const { projectId, packageName, ...rest } = req;
619
+ const body = { ...rest };
620
+ if (req.installationFree === 0 && packageName) {
621
+ body.packageName = packageName;
622
+ }
623
+ const response = await agcClient.post(
624
+ `/api/publish/v3/app?projectId=${encodeURIComponent(projectId)}`,
625
+ body
626
+ );
627
+ return response.data;
628
+ }
629
+ /** 查询团队账号下的成员角色列表 */
630
+ static async getMembersRoleList(req) {
631
+ const response = await agcClient.get(
632
+ "/api/publish/v3/members-role-list",
633
+ {
634
+ params: {
635
+ fromPage: req.fromPage,
636
+ pageSize: req.pageSize,
637
+ languageCode: req.languageCode
638
+ }
639
+ }
640
+ );
641
+ return response.data;
642
+ }
643
+ /** 查询应用信息 */
644
+ static async getAppInfo(appIdOrReq, lang) {
645
+ const req = typeof appIdOrReq === "string" ? { appId: appIdOrReq, lang } : appIdOrReq;
646
+ const response = await agcClient.get("/api/publish/v3/app-info", {
647
+ params: withOptionalParams({
648
+ appId: req.appId,
649
+ lang: req.lang,
650
+ releaseType: req.releaseType,
651
+ versionId: req.versionId
652
+ })
653
+ });
654
+ return response.data;
655
+ }
656
+ /** 更新应用基本信息 */
657
+ static async updateAppInfo(req) {
658
+ const { appId, releaseType, releasePhase, ...body } = req;
659
+ const response = await agcClient.put(
660
+ "/api/publish/v3/app-info",
661
+ body,
662
+ {
663
+ params: withOptionalParams({ appId, releaseType, releasePhase })
664
+ }
665
+ );
666
+ return response.data;
667
+ }
668
+ /** 更新应用语言信息 */
669
+ static async updateLanguageInfo(req) {
670
+ const { appId, releaseType, releasePhase, ...body } = req;
671
+ const response = await agcClient.put(
672
+ "/api/publish/v3/app-language-info",
673
+ body,
674
+ {
675
+ params: withOptionalParams({ appId, releaseType, releasePhase })
676
+ }
677
+ );
678
+ return response.data;
679
+ }
680
+ /** 删除应用语言信息 */
681
+ static async deleteLanguageInfo(req) {
682
+ const response = await agcClient.delete(
683
+ "/api/publish/v2/app-language-info",
684
+ {
685
+ params: withOptionalParams({
686
+ appId: req.appId,
687
+ lang: req.lang,
688
+ releaseType: req.releaseType
689
+ })
690
+ }
691
+ );
692
+ return response.data;
693
+ }
694
+ /** 更新应用文件信息(图标/截图/视频等) */
695
+ static async updateAppFileInfo(req) {
696
+ const { appId, releaseType, releasePhase, ...body } = req;
697
+ const response = await agcClient.put(
698
+ "/api/publish/v3/app-file-info",
699
+ body,
700
+ {
701
+ params: withOptionalParams({ appId, releaseType, releasePhase })
702
+ }
703
+ );
704
+ return response.data;
705
+ }
706
+ /** 更新应用软件包信息(OBS 上传后上报,AGC 控制台才会出现记录) */
707
+ static async updateAppPackageInfo(req) {
708
+ const { appId, releaseType, releasePhase, fileName, objectId } = req;
709
+ const response = await agcClient.put(
710
+ "/api/publish/v3/app-package-info",
711
+ { fileName, objectId },
712
+ {
713
+ params: withOptionalParams({ appId, releaseType, releasePhase })
714
+ }
715
+ );
716
+ return response.data;
717
+ }
718
+ /** 更新版本上架时间 */
719
+ static async updateReleaseTime(req) {
720
+ const { appId, ...body } = req;
721
+ const response = await agcClient.put(
722
+ "/api/publish/v2/on-shelf-time",
723
+ body,
724
+ { params: { appId } }
725
+ );
726
+ return response.data;
727
+ }
728
+ /** 更新分阶段发布 */
729
+ static async updatePhasedRelease(req) {
730
+ const { appId, ...body } = req;
731
+ const response = await agcClient.put(
732
+ "/api/publish/v2/version/phased-release",
733
+ body,
734
+ { headers: appIdHeaders(appId) }
735
+ );
736
+ return response.data;
737
+ }
738
+ /** 查询应用软件包信息 */
739
+ static async getPackageInfo(req) {
740
+ const response = await agcClient.get(
741
+ "/api/publish/v2/app-package-info",
742
+ {
743
+ params: { packageId: req.packageId },
744
+ headers: appIdHeaders(req.appId)
745
+ }
746
+ );
747
+ return response.data;
748
+ }
749
+ /** 查询软件包编译状态 */
750
+ static async getCompileStatus(req) {
751
+ const response = await agcClient.get(
752
+ "/api/publish/v3/package/compile/status",
753
+ { params: { appId: req.appId, pkgIds: req.pkgIds } }
754
+ );
755
+ return response.data;
756
+ }
757
+ /** 查询应用所有版本类型的版本列表 */
758
+ static async queryBriefInfoList(req) {
759
+ const { appId, ...body } = req;
760
+ const response = await agcClient.post(
761
+ "/api/publish/v3/version/brief-info/list",
762
+ body,
763
+ { headers: appIdHeaders(appId) }
764
+ );
765
+ return response.data;
766
+ }
767
+ /** 查询应用未处理的问题工单 */
768
+ static async queryVersionVoc(req) {
769
+ const { appId, ...body } = req;
770
+ const response = await agcClient.post(
771
+ "/api/publish/v1/app-voc/version-voc",
772
+ body,
773
+ { headers: appIdHeaders(appId) }
774
+ );
775
+ return response.data;
776
+ }
777
+ /** 查询需要上传的资质文件信息 */
778
+ static async queryTagQualDependent() {
779
+ const response = await agcClient.get(
780
+ "/api/publish/v2/tag-qual-dependent"
781
+ );
782
+ return response.data;
783
+ }
784
+ /** 提交资质审核任务 */
785
+ static async submitQualificationReview(req) {
786
+ const { appId, ...body } = req;
787
+ const response = await agcClient.post(
788
+ "/api/publish/v2/qualification-review-task",
789
+ body,
790
+ { headers: appIdHeaders(appId) }
791
+ );
792
+ return response.data;
793
+ }
794
+ /** 查询资质审核任务详情 */
795
+ static async getQualificationReview(req) {
796
+ const response = await agcClient.get(
797
+ "/api/publish/v2/qualification-review-task",
798
+ {
799
+ params: { tagIds: req.tagIds },
800
+ headers: appIdHeaders(req.appId)
801
+ }
802
+ );
803
+ return response.data;
804
+ }
805
+ /** 修改资质审核任务 */
806
+ static async updateQualificationReview(req) {
807
+ const { appId, ...body } = req;
808
+ const response = await agcClient.put(
809
+ "/api/publish/v2/qualification-review-task",
810
+ body,
811
+ { headers: appIdHeaders(appId) }
812
+ );
813
+ return response.data;
814
+ }
815
+ /** 撤销资质审核任务 */
816
+ static async cancelQualificationReview(req) {
817
+ const response = await agcClient.put(
818
+ "/api/publish/v2/qualification-review-task/cancel",
819
+ { taskId: req.taskId },
820
+ { headers: appIdHeaders(req.appId) }
821
+ );
822
+ return response.data;
823
+ }
824
+ /** 删除资质审核任务 */
825
+ static async deleteQualificationReview(req) {
826
+ const response = await agcClient.delete(
827
+ "/api/publish/v2/qualification-review-task",
828
+ {
829
+ data: { tagIds: req.tagIds },
830
+ headers: appIdHeaders(req.appId)
831
+ }
832
+ );
833
+ return response.data;
834
+ }
835
+ /** 新建用户协议 / 隐私政策协议(body.type 区分) */
836
+ static async createAgreement(req) {
837
+ const { appId, ...body } = req;
838
+ const response = await agcClient.post(
839
+ "/api/publish/v2/agreement",
840
+ body,
841
+ { headers: appIdHeaders(appId) }
842
+ );
843
+ return response.data;
844
+ }
845
+ /** 查询用户协议 / 隐私政策协议列表(body.type 区分) */
846
+ static async listAgreements(req) {
847
+ const { appId, ...body } = req;
848
+ const response = await agcClient.post(
849
+ "/api/publish/v2/agreement/list",
850
+ body,
851
+ { headers: appIdHeaders(appId) }
852
+ );
853
+ return response.data;
854
+ }
855
+ /** 更新用户协议 / 隐私政策协议 */
856
+ static async updateAgreement(req) {
857
+ const { appId, ...body } = req;
858
+ const response = await agcClient.put(
859
+ "/api/publish/v2/agreement",
860
+ body,
861
+ { headers: appIdHeaders(appId) }
862
+ );
863
+ return response.data;
864
+ }
865
+ /** 提交隐私政策协议 */
866
+ static async submitPrivacyAgreement(req) {
867
+ const { appId, ...body } = req;
868
+ const response = await agcClient.put(
869
+ "/api/publish/v2/agreement/submit",
870
+ body,
871
+ { headers: appIdHeaders(appId) }
872
+ );
873
+ return response.data;
874
+ }
875
+ /** 申请年龄分级 */
876
+ static async applyAgeRating(req) {
877
+ const { appId, releaseType, releasePhase, ...body } = req;
878
+ const response = await agcClient.post(
879
+ "/api/publish/v2/app-age-rating",
880
+ body,
881
+ {
882
+ params: withOptionalParams({ releaseType, releasePhase }),
883
+ headers: appIdHeaders(appId)
884
+ }
885
+ );
886
+ return response.data;
887
+ }
888
+ /** 提交发布 */
889
+ static async submitApp(req) {
890
+ const { appId, ...body } = req;
891
+ const response = await agcClient.post(
892
+ "/api/publish/v3/app-submit",
893
+ body,
894
+ { headers: appIdHeaders(appId) }
895
+ );
896
+ return response.data;
897
+ }
898
+ /** 撤销审核 */
899
+ static async cancelReview(req) {
900
+ const response = await agcClient.put(
901
+ "/api/publish/v3/version/on-shelf/cancel",
902
+ { versionId: req.versionId },
903
+ { headers: appIdHeaders(req.appId) }
904
+ );
905
+ return response.data;
906
+ }
907
+ /** 下架应用 */
908
+ static async shelfOff(req) {
909
+ const response = await agcClient.post(
910
+ "/api/publish/v2/app-shelf-off",
911
+ null,
912
+ {
913
+ params: withOptionalParams({
914
+ appId: req.appId,
915
+ reason: req.reason,
916
+ releaseType: req.releaseType
917
+ })
918
+ }
919
+ );
920
+ return response.data;
921
+ }
922
+ };
923
+
924
+ // src/services/project.ts
925
+ var ProjectService = class {
926
+ /** 查询团队下的项目列表(Project Management API) */
927
+ static async listProjects() {
928
+ const response = await agcClient.get("/api/project-service/v1/projects");
929
+ return response.data;
930
+ }
931
+ };
932
+
933
+ // src/services/provision.ts
934
+ var ProvisionService = class {
935
+ // ================= Certificates =================
936
+ static async createCert(req) {
937
+ const response = await agcClient.post("/api/publish/v3/cert", req);
938
+ return response.data;
939
+ }
940
+ static async getCertList(req) {
941
+ const response = await agcClient.post("/api/publish/v3/cert/list", req);
942
+ return response.data;
943
+ }
944
+ static async deleteCert(req) {
945
+ const response = await agcClient.post("/api/publish/v2/cert/delete", req);
946
+ return response.data;
947
+ }
948
+ // ================= Devices =================
949
+ static async addDevice(req) {
950
+ const response = await agcClient.post("/api/publish/v2/device", req);
951
+ return response.data;
952
+ }
953
+ static async getDeviceList(req) {
954
+ const params = {};
955
+ if (req.deviceName) params.deviceName = req.deviceName;
956
+ if (req.fromRecCount !== void 0) params.fromRecCount = req.fromRecCount;
957
+ if (req.maxReqCount !== void 0) params.maxReqCount = req.maxReqCount;
958
+ if (req.order !== void 0) params.order = req.order;
959
+ const response = await agcClient.get("/api/publish/v2/device/list", { params });
960
+ return response.data;
961
+ }
962
+ static async deleteDevice(req) {
963
+ const response = await agcClient.post("/api/publish/v2/device/delete", req);
964
+ return response.data;
965
+ }
966
+ // ================= Profile / Provision =================
967
+ static async createProvision(req) {
968
+ const response = await agcClient.post("/api/publish/v3/provision", req);
969
+ return response.data;
970
+ }
971
+ static async getProvisionList(req) {
972
+ const params = {};
973
+ if (req.fromRecCount !== void 0) params.fromRecCount = req.fromRecCount;
974
+ if (req.maxReqCount !== void 0) params.maxReqCount = req.maxReqCount;
975
+ const headers = { appId: req.appId };
976
+ if (req.provisionId) headers.provisionId = req.provisionId;
977
+ const response = await agcClient.get("/api/publish/v3/provision/list", {
978
+ params,
979
+ headers
980
+ });
981
+ return response.data;
982
+ }
983
+ static async updateProvision(req) {
984
+ const response = await agcClient.put("/api/publish/v3/provision", req);
985
+ return response.data;
986
+ }
987
+ static async deleteProvision(req) {
988
+ const response = await agcClient.delete("/api/publish/v2/provision", {
989
+ params: { id: req.id }
990
+ });
991
+ return response.data;
992
+ }
993
+ // ================= Fingerprint =================
994
+ static async addFingerprint(req) {
995
+ const { appId, ...body } = req;
996
+ const response = await agcClient.post(
997
+ "/api/provision/v1/fingerprints",
998
+ body,
999
+ { headers: { appId } }
1000
+ );
1001
+ return response.data;
1002
+ }
1003
+ static async getFingerprintList(req) {
1004
+ const response = await agcClient.get("/api/provision/v1/fingerprints", {
1005
+ headers: { appId: req.appId }
1006
+ });
1007
+ return response.data;
1008
+ }
1009
+ static async deleteFingerprint(req) {
1010
+ const { appId, ...body } = req;
1011
+ const response = await agcClient.delete(
1012
+ "/api/provision/v1/fingerprints",
1013
+ { headers: { appId }, data: body }
1014
+ );
1015
+ return response.data;
1016
+ }
1017
+ // ================= ACL Permission =================
1018
+ /** 查询可申请的 ACL 权限列表 */
1019
+ static async getEligibleACL(req) {
1020
+ const { appId, ...body } = req;
1021
+ const response = await agcClient.post(
1022
+ "/api/provision/v1/user/permission/apply/list",
1023
+ body,
1024
+ { headers: { appId } }
1025
+ );
1026
+ return response.data;
1027
+ }
1028
+ static async applyACL(req) {
1029
+ const { appId, ...body } = req;
1030
+ const response = await agcClient.post(
1031
+ "/api/provision/v1/user/permission/apply",
1032
+ body,
1033
+ { headers: { appId } }
1034
+ );
1035
+ return response.data;
1036
+ }
1037
+ static async getACLStatus(req) {
1038
+ const response = await agcClient.get(
1039
+ "/api/provision/v1/user/permission/apply/status",
1040
+ { headers: { appId: req.appId } }
1041
+ );
1042
+ return response.data;
1043
+ }
1044
+ static async getACLQuery(req) {
1045
+ const response = await agcClient.get("/api/provision/v1/user/permission", {
1046
+ headers: { appId: req.appId }
1047
+ });
1048
+ return response.data;
1049
+ }
1050
+ };
1051
+
1052
+ // src/services/upload.ts
1053
+ var import_axios4 = __toESM(require("axios"));
1054
+ var import_fs4 = __toESM(require("fs"));
1055
+ var import_path4 = __toESM(require("path"));
1056
+ function pickObjectId(res) {
1057
+ return res.urlInfo?.objectId || res.objectId;
1058
+ }
1059
+ var UploadService = class {
1060
+ // ================= Raw APIs =================
1061
+ static async getUploadUrl(req) {
1062
+ const response = await agcClient.get("/api/publish/v2/upload-url/for-obs", {
1063
+ params: req
1064
+ });
1065
+ return response.data;
1066
+ }
1067
+ static async initMultipart(req) {
1068
+ const response = await agcClient.post("/api/publish/v2/upload/multipart/init", null, {
1069
+ params: req
1070
+ });
1071
+ return response.data;
1072
+ }
1073
+ static async getMultipartParts(req) {
1074
+ const { objectId, nspUploadId, parts } = req;
1075
+ const response = await agcClient.post("/api/publish/v2/upload/multipart/parts", parts, {
1076
+ params: { objectId, nspUploadId }
1077
+ });
1078
+ return response.data;
1079
+ }
1080
+ static async composeMultipart(req) {
1081
+ const { objectId, nspUploadId, parts } = req;
1082
+ const response = await agcClient.post("/api/publish/v2/upload/multipart/compose", parts, {
1083
+ params: { objectId, nspUploadId }
1084
+ });
1085
+ return response.data;
1086
+ }
1087
+ // ================= High-level Operations =================
1088
+ /**
1089
+ * 封装好的上传文件核心流程(支持根据文件大小自动单文件或分片上传)
1090
+ * 文件大小 < 5MB 时使用单文件上传,否则使用分片上传。
1091
+ * 仅完成 OBS 落盘;HarmonyOS `.app` 还须调用更新应用软件包信息,AGC 控制台才会有记录。
1092
+ */
1093
+ static async uploadFile(options) {
1094
+ const stat = import_fs4.default.statSync(options.filePath);
1095
+ const fileName = import_path4.default.basename(options.filePath) || "unknown";
1096
+ if (stat.size < 5 * 1024 * 1024) {
1097
+ return this.uploadSingleFile(options, fileName, stat.size);
1098
+ }
1099
+ return this.uploadMultipartFile(options, fileName, stat.size);
1100
+ }
1101
+ /**
1102
+ * OBS 预签名 PUT 头:SignedHeaders 含 content-length / host。
1103
+ * 必须显式带 Content-Length;Host 交给客户端按 URL 设置,勿原样回传。
1104
+ */
1105
+ static buildObsPutHeaders(headers, contentLength) {
1106
+ const out = { ...headers };
1107
+ delete out.Host;
1108
+ delete out.host;
1109
+ out["Content-Length"] = String(contentLength);
1110
+ if (!out["Content-Type"] && !out["content-type"]) {
1111
+ out["Content-Type"] = "application/octet-stream";
1112
+ }
1113
+ return out;
1114
+ }
1115
+ /**
1116
+ * 单文件上传流程
1117
+ */
1118
+ static async uploadSingleFile(options, fileName, contentLength) {
1119
+ const urlRes = await this.getUploadUrl({
1120
+ appId: options.appId,
1121
+ fileName,
1122
+ contentLength,
1123
+ releaseType: options.releaseType,
1124
+ chineseMainlandFlag: options.chineseMainlandFlag
1125
+ });
1126
+ if (!urlRes.urlInfo) {
1127
+ throw new Error(`Failed to get upload URL: ${JSON.stringify(urlRes.ret)}`);
1128
+ }
1129
+ const objectId = pickObjectId(urlRes);
1130
+ if (!objectId) {
1131
+ throw new Error(
1132
+ `Failed to get objectId from upload URL: ${JSON.stringify(urlRes.ret)}`
1133
+ );
1134
+ }
1135
+ const { url, headers } = urlRes.urlInfo;
1136
+ const fileStream = import_fs4.default.createReadStream(options.filePath);
1137
+ await import_axios4.default.put(url, fileStream, {
1138
+ headers: this.buildObsPutHeaders(headers, contentLength),
1139
+ maxBodyLength: Infinity,
1140
+ maxContentLength: Infinity
1141
+ });
1142
+ return { fileName, objectId };
1143
+ }
1144
+ /**
1145
+ * 分片上传流程
1146
+ */
1147
+ static async uploadMultipartFile(options, fileName, fileSize) {
1148
+ const initRes = await this.initMultipart({
1149
+ appId: options.appId,
1150
+ fileName,
1151
+ releaseType: options.releaseType,
1152
+ chineseMainlandFlag: options.chineseMainlandFlag
1153
+ });
1154
+ const { objectId, nspUploadId, nspPartMinSize = 5242880 } = initRes;
1155
+ if (!objectId || !nspUploadId) {
1156
+ throw new Error(`Failed to init multipart upload: ${JSON.stringify(initRes.ret)}`);
1157
+ }
1158
+ const partSize = Number(nspPartMinSize);
1159
+ const partsCount = Math.ceil(fileSize / partSize);
1160
+ const partsReqBody = {};
1161
+ for (let i = 1; i <= partsCount; i++) {
1162
+ const start = (i - 1) * partSize;
1163
+ const end = Math.min(start + partSize, fileSize);
1164
+ partsReqBody[`additionalProp${i}`] = {
1165
+ length: end - start
1166
+ };
1167
+ }
1168
+ const partsRes = await this.getMultipartParts({
1169
+ objectId,
1170
+ nspUploadId,
1171
+ parts: partsReqBody
1172
+ });
1173
+ const uploadInfoMap = partsRes.uploadInfoMap;
1174
+ if (!uploadInfoMap) {
1175
+ throw new Error(`Failed to get parts upload URL: ${JSON.stringify(partsRes.ret)}`);
1176
+ }
1177
+ const fd = import_fs4.default.openSync(options.filePath, "r");
1178
+ const composeReqBody = {};
1179
+ for (let i = 1; i <= partsCount; i++) {
1180
+ const propKey = `additionalProp${i}`;
1181
+ const uploadInfo = uploadInfoMap[propKey];
1182
+ const start = (i - 1) * partSize;
1183
+ const end = Math.min(start + partSize, fileSize);
1184
+ const length = end - start;
1185
+ const buffer = Buffer.alloc(length);
1186
+ import_fs4.default.readSync(fd, buffer, 0, length, start);
1187
+ const res = await import_axios4.default.put(uploadInfo.url, buffer, {
1188
+ headers: this.buildObsPutHeaders(uploadInfo.headers, length),
1189
+ maxBodyLength: Infinity,
1190
+ maxContentLength: Infinity
1191
+ });
1192
+ const etag = res.headers["etag"];
1193
+ composeReqBody[propKey] = {
1194
+ partObjectId: uploadInfo.partObjectId || "",
1195
+ etag
1196
+ };
1197
+ }
1198
+ import_fs4.default.closeSync(fd);
1199
+ await this.composeMultipart({
1200
+ objectId,
1201
+ nspUploadId,
1202
+ parts: composeReqBody
1203
+ });
1204
+ return { fileName, objectId };
1205
+ }
1206
+ };
1207
+
1208
+ // src/services/domain.ts
1209
+ var import_fs5 = __toESM(require("fs"));
1210
+ var DomainService = class {
1211
+ /**
1212
+ * 查询元服务的域名配置信息
1213
+ */
1214
+ static async queryDomain(req) {
1215
+ const response = await agcClient.get(
1216
+ "/api/dms/domain-manage/v1/app/domain",
1217
+ {
1218
+ params: { category: req.category },
1219
+ headers: { appId: req.appId }
1220
+ }
1221
+ );
1222
+ return response.data;
1223
+ }
1224
+ /**
1225
+ * 新增/更新元服务的域名配置信息
1226
+ */
1227
+ static async updateDomain(req) {
1228
+ const response = await agcClient.post(
1229
+ "/api/dms/domain-manage/v1/app/domain",
1230
+ { domains: req.domains },
1231
+ {
1232
+ params: { category: req.category },
1233
+ headers: { appId: req.appId }
1234
+ }
1235
+ );
1236
+ return response.data;
1237
+ }
1238
+ /**
1239
+ * 查询域名修改次数/配置上限
1240
+ */
1241
+ static async queryDomainConfig(req) {
1242
+ const response = await agcClient.get(
1243
+ "/api/dms/domain-manage/v1/app/domain/config",
1244
+ {
1245
+ params: { appId: req.appId }
1246
+ }
1247
+ );
1248
+ return response.data;
1249
+ }
1250
+ /**
1251
+ * 下载域名配置文件
1252
+ */
1253
+ static async verifyFile(req, outputPath) {
1254
+ const response = await agcClient.get(
1255
+ "/api/dms/domain-manage/v1/app/domain/verify-file",
1256
+ {
1257
+ headers: { appId: req.appId },
1258
+ responseType: "stream"
1259
+ }
1260
+ );
1261
+ return new Promise((resolve, reject) => {
1262
+ const writer = import_fs5.default.createWriteStream(outputPath);
1263
+ response.data.pipe(writer);
1264
+ let error = null;
1265
+ writer.on("error", (err) => {
1266
+ error = err;
1267
+ writer.close();
1268
+ reject(err);
1269
+ });
1270
+ writer.on("close", () => {
1271
+ if (!error) {
1272
+ resolve();
1273
+ }
1274
+ });
1275
+ });
1276
+ }
1277
+ /**
1278
+ * 预检查业务域名配置
1279
+ */
1280
+ static async preCheckDomain(req) {
1281
+ const response = await agcClient.post(
1282
+ "/api/dms/domain-manage/v1/app/domain/pre-check",
1283
+ { domain: req.domain },
1284
+ {
1285
+ headers: { appId: req.appId }
1286
+ }
1287
+ );
1288
+ return response.data;
1289
+ }
1290
+ };
1291
+
1292
+ // src/services/sign.ts
1293
+ var import_fs6 = __toESM(require("fs"));
1294
+ var import_path5 = __toESM(require("path"));
1295
+ var import_child_process2 = require("child_process");
1296
+ var import_crypto = __toESM(require("crypto"));
1297
+ var DEFAULT_SIGN_OUT_DIR = ".certs";
1298
+ var SIGN_FILE_PREFIX = {
1299
+ p12: "key_",
1300
+ csr: "key_",
1301
+ cer: "cert_",
1302
+ p7b: "profile_"
1303
+ };
1304
+ var SignService = class {
1305
+ static resolveSignOutputLayout(options) {
1306
+ const rootDir = options.outDir ? import_path5.default.resolve(options.outDir) : import_path5.default.join(process.cwd(), DEFAULT_SIGN_OUT_DIR);
1307
+ const signId = options.filename || this.createSignDefaultId();
1308
+ return {
1309
+ rootDir,
1310
+ bundleDir: import_path5.default.join(rootDir, signId),
1311
+ filename: signId
1312
+ };
1313
+ }
1314
+ static async createSignP12AndCsr(options) {
1315
+ const javaPath = options.javaPath || "java";
1316
+ const sdkPath = options.sdkPath || process.env.HARMONYOS_SDK_PATH;
1317
+ if (!sdkPath) {
1318
+ throw new Error("sdkPath is required. Provide it via --sdk-path or HARMONYOS_SDK_PATH env var.");
1319
+ }
1320
+ const signToolPath = import_path5.default.join(sdkPath, "default", "openharmony", "toolchains", "lib", "hap-sign-tool.jar");
1321
+ if (!import_fs6.default.existsSync(signToolPath)) {
1322
+ throw new Error(`hap-sign-tool.jar not found at ${signToolPath}`);
1323
+ }
1324
+ const { rootDir, bundleDir, filename } = this.resolveSignOutputLayout(options);
1325
+ const createdBundleDir = !import_fs6.default.existsSync(bundleDir);
1326
+ if (!import_fs6.default.existsSync(rootDir)) {
1327
+ import_fs6.default.mkdirSync(rootDir, { recursive: true });
1328
+ }
1329
+ import_fs6.default.mkdirSync(bundleDir, { recursive: true });
1330
+ const p12FilePath = import_path5.default.join(bundleDir, this.signFileName(filename, "p12"));
1331
+ const csrFilePath = import_path5.default.join(bundleDir, this.signFileName(filename, "csr"));
1332
+ const alias = options.alias;
1333
+ const pwd = options.pwd || this.createSignDefaultPassword();
1334
+ try {
1335
+ this.doCreateSignFileP12(javaPath, signToolPath, alias, pwd, p12FilePath);
1336
+ this.doCreateSignFileCsr(javaPath, signToolPath, alias, pwd, p12FilePath, csrFilePath);
1337
+ const csrContent = import_fs6.default.readFileSync(csrFilePath, "utf8");
1338
+ const materialPath = this.placeMaterialBesideStore(bundleDir);
1339
+ return {
1340
+ alias,
1341
+ filename,
1342
+ pwd,
1343
+ p12Path: p12FilePath,
1344
+ csrPath: csrFilePath,
1345
+ csrContent,
1346
+ storePath: bundleDir,
1347
+ cerPath: import_path5.default.join(bundleDir, this.signFileName(filename, "cer")),
1348
+ p7bPath: import_path5.default.join(bundleDir, this.signFileName(filename, "p7b")),
1349
+ ...materialPath ? { materialPath } : {}
1350
+ };
1351
+ } catch (err) {
1352
+ if (createdBundleDir) {
1353
+ import_fs6.default.rmSync(bundleDir, { recursive: true, force: true });
1354
+ }
1355
+ throw err;
1356
+ }
1357
+ }
1358
+ /** 目录名与各文件共用的安全随机数(32 hex) */
1359
+ static createSignDefaultId() {
1360
+ return import_crypto.default.randomBytes(16).toString("hex");
1361
+ }
1362
+ /** `key_<id>.p12` / `cert_<id>.cer` / `profile_<id>.p7b` 等 */
1363
+ static signFileName(id, ext) {
1364
+ return `${SIGN_FILE_PREFIX[ext]}${id}.${ext}`;
1365
+ }
1366
+ /** 密钥库密码:16 字节 CSPRNG → 32 hex(字母+数字,满足 hap-sign-tool 约束) */
1367
+ static createSignDefaultPassword() {
1368
+ return import_crypto.default.randomBytes(16).toString("hex");
1369
+ }
1370
+ /**
1371
+ * hvigor 在 `.p12` 同级目录找 `material/`。把 DevEco 的加密材料放到本套证书目录,
1372
+ * 避免签名文件被拷到工程根目录才能编过。
1373
+ */
1374
+ static placeMaterialBesideStore(bundleDir, configDir) {
1375
+ const dest = import_path5.default.join(bundleDir, "material");
1376
+ if (import_fs6.default.existsSync(dest)) {
1377
+ return dest;
1378
+ }
1379
+ const home = process.env.HOME || process.env.USERPROFILE || "";
1380
+ const src = import_path5.default.resolve(configDir || import_path5.default.join(home, ".ohos", "config"), "material");
1381
+ if (!import_fs6.default.existsSync(src)) {
1382
+ return void 0;
1383
+ }
1384
+ try {
1385
+ import_fs6.default.symlinkSync(src, dest, process.platform === "win32" ? "junction" : "dir");
1386
+ } catch {
1387
+ import_fs6.default.cpSync(src, dest, { recursive: true });
1388
+ }
1389
+ return dest;
1390
+ }
1391
+ /** 需要在日志中遮蔽的敏感参数名 */
1392
+ static SENSITIVE_ARGS = /* @__PURE__ */ new Set(["-keyPwd", "-keystorePwd"]);
1393
+ /** 打印命令行时隐去密码值,避免明文泄露 */
1394
+ static maskArgs(args) {
1395
+ return args.map((arg, i) => i > 0 && this.SENSITIVE_ARGS.has(args[i - 1]) ? "******" : arg).join(" ");
1396
+ }
1397
+ /**
1398
+ * 执行签名工具:命令行与子进程输出统一走 stderr,
1399
+ * 保证 stdout 只有 CLI 的 JSON 结果,便于 jq 等下游解析。
1400
+ */
1401
+ static runSignTool(javaPath, args) {
1402
+ console.error(`Executing: ${javaPath} ${this.maskArgs(args)}`);
1403
+ (0, import_child_process2.execFileSync)(javaPath, args, { stdio: ["ignore", 2, "inherit"] });
1404
+ }
1405
+ static doCreateSignFileP12(javaPath, signToolPath, alias, pwd, outFilePath) {
1406
+ const args = [
1407
+ "-jar",
1408
+ signToolPath,
1409
+ "generate-keypair",
1410
+ "-keyAlias",
1411
+ alias,
1412
+ "-keyPwd",
1413
+ pwd,
1414
+ "-keyAlg",
1415
+ "ECC",
1416
+ "-keySize",
1417
+ "NIST-P-256",
1418
+ "-keystoreFile",
1419
+ outFilePath,
1420
+ "-keystorePwd",
1421
+ pwd
1422
+ ];
1423
+ this.runSignTool(javaPath, args);
1424
+ }
1425
+ static doCreateSignFileCsr(javaPath, signToolPath, alias, pwd, p12Path, outFilePath) {
1426
+ const args = [
1427
+ "-jar",
1428
+ signToolPath,
1429
+ "generate-csr",
1430
+ "-keyAlias",
1431
+ alias,
1432
+ "-keyPwd",
1433
+ pwd,
1434
+ "-subject",
1435
+ "C=CN,O=OpenHarmony,OU=OpenHarmony Community,CN=App Release",
1436
+ "-signAlg",
1437
+ "SHA256withECDSA",
1438
+ "-keystoreFile",
1439
+ p12Path,
1440
+ "-keystorePwd",
1441
+ pwd,
1442
+ "-outFile",
1443
+ outFilePath
1444
+ ];
1445
+ this.runSignTool(javaPath, args);
1446
+ }
1447
+ static COMPONENT = new Int8Array([49, 243, 9, 115, 214, 175, 91, 184, 211, 190, 177, 88, 101, 131, 192, 119]);
1448
+ static readDirBytes(dirPath) {
1449
+ const entries = import_fs6.default.readdirSync(dirPath).filter((f) => f !== ".DS_Store");
1450
+ return new Int8Array(import_fs6.default.readFileSync(import_path5.default.resolve(dirPath, entries[0])));
1451
+ }
1452
+ static readFd(materialPath) {
1453
+ const fdDir = import_path5.default.resolve(materialPath, "fd");
1454
+ return import_fs6.default.readdirSync(fdDir).filter((f) => f !== ".DS_Store").map((e) => this.readDirBytes(import_path5.default.resolve(fdDir, e)));
1455
+ }
1456
+ static xorBuffers(a, b) {
1457
+ const result = new Int8Array(a.byteLength);
1458
+ for (let i = 0; i < a.byteLength; i++) result[i] = a[i] ^ b[i];
1459
+ return result;
1460
+ }
1461
+ static xorAll(components) {
1462
+ let result = this.xorBuffers(components[0], components[1]);
1463
+ for (let i = 2; i < components.length; i++) result = this.xorBuffers(result, components[i]);
1464
+ return Buffer.from(result);
1465
+ }
1466
+ static aesDecrypt(key, data) {
1467
+ const d = Buffer.from(data);
1468
+ const tagLen = (255 & d[0]) << 24 | (255 & d[1]) << 16 | (255 & d[2]) << 8 | 255 & d[3];
1469
+ const ivLen = d.length - 4 - tagLen;
1470
+ const iv = d.subarray(4, 4 + ivLen);
1471
+ const decipher = import_crypto.default.createDecipheriv("aes-128-gcm", key, iv);
1472
+ decipher.setAuthTag(d.subarray(d.length - 16));
1473
+ return Buffer.concat([decipher.update(d.subarray(4 + ivLen, d.length - 16)), decipher.final()]);
1474
+ }
1475
+ static aesEncrypt(key, plaintext) {
1476
+ const iv = import_crypto.default.randomBytes(12);
1477
+ const cipher = import_crypto.default.createCipheriv("aes-128-gcm", key, iv);
1478
+ const enc = Buffer.concat([cipher.update(plaintext, "utf-8"), cipher.final()]);
1479
+ const tag = cipher.getAuthTag();
1480
+ const header = Buffer.alloc(4);
1481
+ header.writeUInt32BE(enc.length + 16, 0);
1482
+ return Buffer.concat([header, iv, enc, tag]).toString("hex").toUpperCase();
1483
+ }
1484
+ static deriveEncryptionKey(configDir) {
1485
+ const materialDir = import_path5.default.resolve(configDir, "material");
1486
+ const fd = this.readFd(materialDir);
1487
+ const salt = this.readDirBytes(import_path5.default.resolve(materialDir, "ac"));
1488
+ const rawKey = new Int8Array(
1489
+ import_crypto.default.pbkdf2Sync(this.xorAll(fd.concat(this.COMPONENT)).toString(), salt, 1e4, 16, "sha256")
1490
+ );
1491
+ return new Int8Array(this.aesDecrypt(rawKey, this.readDirBytes(import_path5.default.resolve(materialDir, "ce"))));
1492
+ }
1493
+ /**
1494
+ * 使用 DevEco Studio 的加密密钥对密码进行 AES-128-GCM 加密,
1495
+ * 生成 build-profile.json5 中 signingConfigs 所需的加密密码。
1496
+ */
1497
+ static encryptPassword(password, configDir) {
1498
+ const dir = configDir || import_path5.default.join(process.env.HOME || "", ".ohos", "config");
1499
+ if (!import_fs6.default.existsSync(import_path5.default.resolve(dir, "material"))) {
1500
+ throw new Error(`\u672A\u627E\u5230\u52A0\u5BC6\u5BC6\u94A5\u76EE\u5F55: ${import_path5.default.resolve(dir, "material")}\u3002\u8BF7\u786E\u8BA4 DevEco Studio \u5DF2\u5B89\u88C5\u5E76\u751F\u6210\u8FC7\u7B7E\u540D\u914D\u7F6E\u3002`);
1501
+ }
1502
+ const key = this.deriveEncryptionKey(dir);
1503
+ return {
1504
+ keyPassword: this.aesEncrypt(key, password),
1505
+ storePassword: this.aesEncrypt(key, password)
1506
+ };
1507
+ }
1508
+ };
1509
+
1510
+ // src/services/testing.ts
1511
+ function appIdHeaders2(appId) {
1512
+ return { appId };
1513
+ }
1514
+ var TestingService = class {
1515
+ // ---- 测试版本 ----
1516
+ /** 新建测试版本 */
1517
+ static async createVersion(req) {
1518
+ const { appId, ...body } = req;
1519
+ const response = await agcClient.post(
1520
+ "/api/publish/v2/test/app/version",
1521
+ {
1522
+ releaseType: body.releaseType ?? 6,
1523
+ testType: body.testType,
1524
+ testDesc: body.testDesc,
1525
+ ...body.onshelfSelfDetect !== void 0 ? { onshelfSelfDetect: body.onshelfSelfDetect } : {}
1526
+ },
1527
+ { params: { appId } }
1528
+ );
1529
+ return response.data;
1530
+ }
1531
+ /** 查询上架自检报告信息 */
1532
+ static async getDetectReport(req) {
1533
+ const response = await agcClient.get(
1534
+ "/api/publish/v2/test/app/version/detect-report",
1535
+ { params: { appId: req.appId, versionId: req.versionId } }
1536
+ );
1537
+ return response.data;
1538
+ }
1539
+ /** 添加软件包到测试版本 */
1540
+ static async addPackage(req) {
1541
+ const { appId, ...body } = req;
1542
+ const response = await agcClient.post(
1543
+ "/api/publish/v2/test/version/pkg",
1544
+ body,
1545
+ { params: { appId } }
1546
+ );
1547
+ return response.data;
1548
+ }
1549
+ /** 更新测试版本(绑包、群组、多语言等) */
1550
+ static async updateVersion(req) {
1551
+ const { appId, ...body } = req;
1552
+ const response = await agcClient.put(
1553
+ "/api/publish/v2/test/app/version",
1554
+ body,
1555
+ { params: { appId } }
1556
+ );
1557
+ return response.data;
1558
+ }
1559
+ /** 更新测试生效版本 */
1560
+ static async releaseVersion(req) {
1561
+ const { appId, ...body } = req;
1562
+ const response = await agcClient.put(
1563
+ "/api/publish/v2/test/version/release",
1564
+ body,
1565
+ { params: { appId } }
1566
+ );
1567
+ return response.data;
1568
+ }
1569
+ /** 更新有效期内的测试版本时间和额度信息 */
1570
+ static async updateOpenTest(req) {
1571
+ const { appId, ...body } = req;
1572
+ const response = await agcClient.put(
1573
+ "/api/publish/v2/test/version/open-test",
1574
+ body,
1575
+ { params: { appId } }
1576
+ );
1577
+ return response.data;
1578
+ }
1579
+ /** 提交测试版本 */
1580
+ static async submitVersion(req) {
1581
+ const response = await agcClient.post(
1582
+ "/api/publish/v2/test/app/version/submit",
1583
+ { versionId: req.versionId },
1584
+ { params: { appId: req.appId } }
1585
+ );
1586
+ return response.data;
1587
+ }
1588
+ /** 停止测试版本 */
1589
+ static async stopVersion(req) {
1590
+ const response = await agcClient.post(
1591
+ "/api/publish/v2/test/version/stop",
1592
+ { versionId: req.versionId },
1593
+ { params: { appId: req.appId } }
1594
+ );
1595
+ return response.data;
1596
+ }
1597
+ /** 删除测试版本 */
1598
+ static async deleteVersion(req) {
1599
+ const response = await agcClient.delete(
1600
+ "/api/publish/v2/test/app/version",
1601
+ { params: { appId: req.appId, versionId: req.versionId } }
1602
+ );
1603
+ return response.data;
1604
+ }
1605
+ // ---- 测试群组 ----
1606
+ /** 新增测试群组 */
1607
+ static async addGroup(req) {
1608
+ const { appId, ...body } = req;
1609
+ const response = await agcClient.post(
1610
+ "/api/app-test/v1/test-group",
1611
+ body,
1612
+ { headers: appIdHeaders2(appId) }
1613
+ );
1614
+ return response.data;
1615
+ }
1616
+ /** 查询测试群组列表 */
1617
+ static async listGroups(req) {
1618
+ const params = {};
1619
+ if (req.groupType !== void 0) params.groupType = req.groupType;
1620
+ if (req.current !== void 0) params.current = req.current;
1621
+ if (req.pageSize !== void 0) params.pageSize = req.pageSize;
1622
+ const response = await agcClient.get(
1623
+ "/api/app-test/v1/test-group/list",
1624
+ { params, headers: appIdHeaders2(req.appId) }
1625
+ );
1626
+ return response.data;
1627
+ }
1628
+ /** 删除测试群组 */
1629
+ static async deleteGroup(req) {
1630
+ const response = await agcClient.delete(
1631
+ "/api/app-test/v1/publish-api/test-group",
1632
+ { params: { groupId: req.groupId }, headers: appIdHeaders2(req.appId) }
1633
+ );
1634
+ return response.data;
1635
+ }
1636
+ /** 修改测试群组 */
1637
+ static async editGroup(req) {
1638
+ const { appId, ...body } = req;
1639
+ const response = await agcClient.put(
1640
+ "/api/app-test/v2/test-group",
1641
+ body,
1642
+ { headers: appIdHeaders2(appId) }
1643
+ );
1644
+ return response.data;
1645
+ }
1646
+ /** 查询测试群组成员 */
1647
+ static async listGroupUsers(req) {
1648
+ const params = {
1649
+ groupId: req.groupId,
1650
+ appId: req.appId
1651
+ };
1652
+ if (req.current !== void 0) params.current = req.current;
1653
+ if (req.pageSize !== void 0) params.pageSize = req.pageSize;
1654
+ const response = await agcClient.get(
1655
+ "/api/app-test/v1/test-user",
1656
+ { params, headers: appIdHeaders2(req.appId) }
1657
+ );
1658
+ return response.data;
1659
+ }
1660
+ /** 新增测试群组成员 */
1661
+ static async addGroupUser(req) {
1662
+ const { appId, ...body } = req;
1663
+ const response = await agcClient.post(
1664
+ "/api/publish/v2/test/user",
1665
+ body,
1666
+ { headers: appIdHeaders2(appId) }
1667
+ );
1668
+ return response.data;
1669
+ }
1670
+ /** 删除测试群组成员 */
1671
+ static async deleteGroupUser(req) {
1672
+ const { appId, ...body } = req;
1673
+ const response = await agcClient.delete(
1674
+ "/api/publish/v2/test/user",
1675
+ { data: body, headers: appIdHeaders2(appId) }
1676
+ );
1677
+ return response.data;
1678
+ }
1679
+ /** 发送邀请测试通知 */
1680
+ static async notifyUsers(req) {
1681
+ const { appId, ...body } = req;
1682
+ const response = await agcClient.post(
1683
+ "/api/publish/v1/test/user/action/notify",
1684
+ body,
1685
+ { headers: appIdHeaders2(appId) }
1686
+ );
1687
+ return response.data;
1688
+ }
1689
+ // ---- 邀请码 ----
1690
+ /** 生成邀请码 */
1691
+ static async createInviteCode(req) {
1692
+ const { appId, ...body } = req;
1693
+ const response = await agcClient.post(
1694
+ "/api/app-test/v1/invitation-code",
1695
+ body,
1696
+ { headers: appIdHeaders2(appId) }
1697
+ );
1698
+ return response.data;
1699
+ }
1700
+ /** 查询测试群组邀请码 */
1701
+ static async getInviteCode(req) {
1702
+ const response = await agcClient.get(
1703
+ "/api/app-test/v1/test-group/invitation-code",
1704
+ { params: { groupId: req.groupId }, headers: appIdHeaders2(req.appId) }
1705
+ );
1706
+ return response.data;
1707
+ }
1708
+ /** 停止邀请码 */
1709
+ static async stopInviteCode(req) {
1710
+ const response = await agcClient.post(
1711
+ "/api/app-test/v1/invitation-code/action/stop",
1712
+ { invitationCodeId: req.invitationCodeId },
1713
+ { headers: appIdHeaders2(req.appId) }
1714
+ );
1715
+ return response.data;
1716
+ }
1717
+ /** 删除邀请码 */
1718
+ static async deleteInviteCode(req) {
1719
+ const response = await agcClient.delete(
1720
+ "/api/app-test/v1/invitation-code",
1721
+ { params: { invitationCodeId: req.invitationCodeId }, headers: appIdHeaders2(req.appId) }
1722
+ );
1723
+ return response.data;
1724
+ }
1725
+ // ---- 公开链接 ----
1726
+ /** 创建公开链接 */
1727
+ static async createPublicLink(req) {
1728
+ const { appId, ...body } = req;
1729
+ const response = await agcClient.post(
1730
+ "/api/app-test/v1/test-group/public-link",
1731
+ body,
1732
+ { headers: appIdHeaders2(appId) }
1733
+ );
1734
+ return response.data;
1735
+ }
1736
+ /** 修改公开链接 */
1737
+ static async editPublicLink(req) {
1738
+ const { appId, ...body } = req;
1739
+ const response = await agcClient.put(
1740
+ "/api/app-test/v1/test-group/public-link",
1741
+ body,
1742
+ { headers: appIdHeaders2(appId) }
1743
+ );
1744
+ return response.data;
1745
+ }
1746
+ /** 查询公开链接 */
1747
+ static async queryPublicLink(req) {
1748
+ const response = await agcClient.get(
1749
+ "/api/app-test/v1/test-group/public-link",
1750
+ { params: { groupId: req.groupId }, headers: appIdHeaders2(req.appId) }
1751
+ );
1752
+ return response.data;
1753
+ }
1754
+ // ---- 问题反馈 ----
1755
+ /** 查询测试问题反馈维度 */
1756
+ static async queryFeedbackDimension(req) {
1757
+ const { appId, ...body } = req;
1758
+ const response = await agcClient.post(
1759
+ "/api/app-test/v1/mgmt/tester-feedback-dimension/action/query",
1760
+ body,
1761
+ { headers: appIdHeaders2(appId) }
1762
+ );
1763
+ return response.data;
1764
+ }
1765
+ /** 查询测试问题反馈 */
1766
+ static async queryFeedback(req) {
1767
+ const { appId, ...body } = req;
1768
+ const response = await agcClient.post(
1769
+ "/api/app-test/v1/mgmt/tester-feedback/action/query",
1770
+ body,
1771
+ { headers: appIdHeaders2(appId) }
1772
+ );
1773
+ return response.data;
1774
+ }
1775
+ /** 删除测试问题反馈 */
1776
+ static async deleteFeedback(req) {
1777
+ const { appId, ...body } = req;
1778
+ const response = await agcClient.delete(
1779
+ "/api/app-test/v1/mgmt/tester-feedback",
1780
+ { data: body, headers: appIdHeaders2(appId) }
1781
+ );
1782
+ return response.data;
1783
+ }
1784
+ };
1785
+
1786
+ // src/cli/project-pick.ts
1787
+ var readline = __toESM(require("readline"));
1788
+ async function resolveProjectId(explicit) {
1789
+ if (explicit) return explicit;
1790
+ const res = await ProjectService.listProjects();
1791
+ if (res.ret?.code !== 0) {
1792
+ console.error(
1793
+ `Failed to list projects: ret.code=${res.ret?.code} msg=${res.ret?.msg ?? "(none)"}`
1794
+ );
1795
+ return void 0;
1796
+ }
1797
+ const list = res.projectList ?? [];
1798
+ if (list.length === 0) {
1799
+ console.error("No projects found. Create a project in AppGallery Connect first.");
1800
+ return void 0;
1801
+ }
1802
+ printProjectChoices(list);
1803
+ if (!process.stdin.isTTY) {
1804
+ console.error(
1805
+ "Non-interactive mode: pass --project-id <id> (from project list)."
1806
+ );
1807
+ return void 0;
1808
+ }
1809
+ const answer = (await promptStderr("Select project by number or paste projectId: ")).trim();
1810
+ if (!answer) {
1811
+ console.error("No project selected.");
1812
+ return void 0;
1813
+ }
1814
+ const byIndex = Number(answer);
1815
+ if (Number.isInteger(byIndex) && byIndex >= 1 && byIndex <= list.length) {
1816
+ const chosen = list[byIndex - 1];
1817
+ console.error(`Using projectId=${chosen.projectId} (${chosen.name ?? ""})`);
1818
+ return chosen.projectId;
1819
+ }
1820
+ const byId = list.find((p) => p.projectId === answer);
1821
+ if (byId) {
1822
+ console.error(`Using projectId=${byId.projectId} (${byId.name ?? ""})`);
1823
+ return byId.projectId;
1824
+ }
1825
+ console.error(`Invalid selection: ${answer}`);
1826
+ return void 0;
1827
+ }
1828
+ function printProjectChoices(list) {
1829
+ console.error("Available projects (use projectId for app-create --project-id):");
1830
+ list.forEach((p, i) => {
1831
+ const name = p.name ? ` ${p.name}` : "";
1832
+ console.error(` [${i + 1}] ${p.projectId}${name}`);
1833
+ });
1834
+ }
1835
+ function promptStderr(question) {
1836
+ const rl = readline.createInterface({ input: process.stdin, output: process.stderr });
1837
+ return new Promise((resolve) => {
1838
+ rl.question(question, (answer) => {
1839
+ rl.close();
1840
+ resolve(answer);
1841
+ });
1842
+ });
1843
+ }
1844
+
1845
+ // src/cli/index.ts
1846
+ var program = new import_commander.Command();
1847
+ function readCliVersion() {
1848
+ if (typeof __CLI_VERSION__ === "string" && __CLI_VERSION__) {
1849
+ return __CLI_VERSION__;
1850
+ }
1851
+ try {
1852
+ const pkgPath = import_path6.default.join(__dirname, "..", "package.json");
1853
+ const pkg = JSON.parse(fs7.readFileSync(pkgPath, "utf8"));
1854
+ if (pkg.version) return pkg.version;
1855
+ } catch {
1856
+ }
1857
+ return "0.0.0";
1858
+ }
1859
+ program.name("connect-api-cli").description("AppGallery Connect API CLI Tool").version(readCliVersion());
1860
+ var authCmd = program.command("auth").description("Authentication management");
1861
+ authCmd.command("login").description("Login and cache token (client_credentials / service_account JWT / OAuth browser)").action(async () => {
1862
+ try {
1863
+ const token = await AuthManager.login();
1864
+ console.log("Successfully logged in. Token generated and cached.");
1865
+ console.log(`Token snippet: ${token.substring(0, 10)}...`);
1866
+ } catch (e) {
1867
+ console.error("Login failed:", e.message);
1868
+ }
1869
+ });
1870
+ authCmd.command("status").description("Show current auth mode and cached token status").action(() => {
1871
+ let cfg;
1872
+ try {
1873
+ cfg = getConfig();
1874
+ } catch (e) {
1875
+ console.error(`Auth status unavailable: ${e.message}`);
1876
+ process.exitCode = 1;
1877
+ return;
1878
+ }
1879
+ const status = AuthManager.getStatus();
1880
+ console.log(`Auth mode: ${cfg.authMode}`);
1881
+ if (cfg.authMode === "service_account") {
1882
+ console.log(`Key ID: ${cfg.clientId}`);
1883
+ if (cfg.serviceAccount) {
1884
+ console.log(`Credentials: ${cfg.serviceAccount.credentialsPath}`);
1885
+ }
1886
+ } else {
1887
+ console.log(`Client ID: ${cfg.clientId}`);
1888
+ }
1889
+ if (cfg.authMode === "oauth") {
1890
+ const teamId = cfg.teamId || getCachedOAuthTeamId();
1891
+ console.log(`Team ID: ${teamId || "(auto on first API call; or set AGC_TEAM_ID)"}`);
1892
+ }
1893
+ if (status) {
1894
+ const remaining = Math.max(0, Math.floor((status.expiresAt - Date.now()) / 1e3));
1895
+ console.log("Token cached: yes");
1896
+ console.log(`Expires in: ${Math.floor(remaining / 60)}m ${remaining % 60}s`);
1897
+ const autoRefresh = cfg.authMode === "oauth" && !!status.refreshToken || cfg.authMode === "service_account" || cfg.authMode === "client_credentials";
1898
+ console.log(`Auto-refresh: ${autoRefresh ? "enabled" : "n/a"}`);
1899
+ } else {
1900
+ console.log("Token cached: no");
1901
+ }
1902
+ });
1903
+ authCmd.command("logout").description("Logout and clear cached access token").action(() => {
1904
+ const cleared = AuthManager.clearCache();
1905
+ if (cleared) {
1906
+ console.log("Successfully logged out. Token cache cleared.");
1907
+ } else {
1908
+ console.log("Already logged out. No token cache found.");
1909
+ }
1910
+ });
1911
+ var publishCmd = program.command("publish").description("Publishing API commands");
1912
+ function readJsonFile(filePath) {
1913
+ return JSON.parse(fs7.readFileSync(filePath, "utf8"));
1914
+ }
1915
+ publishCmd.command("app-id").description("Get App ID by package name").requiredOption("-p, --package-name <packageName>", "Package name (comma-separated, max 50)").option("--package-types <packageTypes>", "Optional package types filter").action(async (options) => {
1916
+ try {
1917
+ const res = await PublishService.getAppIdList(options.packageName, options.packageTypes);
1918
+ console.log(JSON.stringify(res, null, 2));
1919
+ } catch (e) {
1920
+ console.error("Request failed:", e.message);
1921
+ }
1922
+ });
1923
+ publishCmd.command("app-create").description("Create an app or meta-service (omit --project-id to pick from project list)").option("--project-id <projectId>", "AGC project ID (interactive pick if omitted)").requiredOption("--app-name <appName>", "App / meta-service name").option("-p, --package-name <packageName>", "Package name (required for app; omit for meta-service)").requiredOption(
1924
+ "--parent-type <parentType>",
1925
+ "Primary category: 2 game, 13 app"
1926
+ ).requiredOption(
1927
+ "--installation-free <installationFree>",
1928
+ "0 app, 1 meta-service"
1929
+ ).action(async (options) => {
1930
+ try {
1931
+ const parentType = Number(options.parentType);
1932
+ const installationFree = Number(options.installationFree);
1933
+ if (parentType !== 2 && parentType !== 13) {
1934
+ console.error("Invalid --parent-type: must be 2 (game) or 13 (app)");
1935
+ return;
1936
+ }
1937
+ if (installationFree !== 0 && installationFree !== 1) {
1938
+ console.error("Invalid --installation-free: must be 0 (app) or 1 (meta-service)");
1939
+ return;
1940
+ }
1941
+ if (installationFree === 0 && !options.packageName) {
1942
+ console.error("Missing -p/--package-name: required when creating an app (installation-free=0)");
1943
+ return;
1944
+ }
1945
+ const projectId = await resolveProjectId(options.projectId);
1946
+ if (!projectId) {
1947
+ return;
1948
+ }
1949
+ const res = await PublishService.createApp({
1950
+ projectId,
1951
+ appName: options.appName,
1952
+ ...options.packageName ? { packageName: options.packageName } : {},
1953
+ parentType,
1954
+ installationFree
1955
+ });
1956
+ console.log(JSON.stringify(res, null, 2));
1957
+ } catch (e) {
1958
+ console.error("Request failed:", e.message);
1959
+ }
1960
+ });
1961
+ publishCmd.command("members").description("List team members and roles").requiredOption("--from-page <fromPage>", "Start page (>=1)").requiredOption("--page-size <pageSize>", "Page size (1-50)").requiredOption("--lang <languageCode>", "Language code: zh_cn / en_us / ru_ru").action(async (options) => {
1962
+ try {
1963
+ const res = await PublishService.getMembersRoleList({
1964
+ fromPage: Number(options.fromPage),
1965
+ pageSize: Number(options.pageSize),
1966
+ languageCode: options.lang
1967
+ });
1968
+ console.log(JSON.stringify(res, null, 2));
1969
+ } catch (e) {
1970
+ console.error("Request failed:", e.message);
1971
+ }
1972
+ });
1973
+ publishCmd.command("app-info").description("Get App Info by App ID").requiredOption("-a, --app-id <appId>", "App ID").option("-l, --lang <lang>", "Language, e.g. zh-CN").option("-r, --release-type <releaseType>", "1 full, 6 HarmonyOS test").option("-v, --version-id <versionId>", "Version ID (required when releaseType=6)").action(async (options) => {
1974
+ try {
1975
+ const res = await PublishService.getAppInfo({
1976
+ appId: options.appId,
1977
+ lang: options.lang,
1978
+ releaseType: options.releaseType ? Number(options.releaseType) : void 0,
1979
+ versionId: options.versionId
1980
+ });
1981
+ console.log(JSON.stringify(res, null, 2));
1982
+ } catch (e) {
1983
+ console.error("Request failed:", e.message);
1984
+ }
1985
+ });
1986
+ publishCmd.command("app-info-update").description("Update app basic info").requiredOption("-a, --app-id <appId>", "App ID").requiredOption("--body <bodyFile>", "JSON body of app basic fields").option("-r, --release-type <releaseType>", "Release type").option("--release-phase <releasePhase>", "Release phase").action(async (options) => {
1987
+ try {
1988
+ const body = readJsonFile(options.body);
1989
+ const res = await PublishService.updateAppInfo({
1990
+ appId: options.appId,
1991
+ releaseType: options.releaseType ? Number(options.releaseType) : void 0,
1992
+ releasePhase: options.releasePhase ? Number(options.releasePhase) : void 0,
1993
+ ...body
1994
+ });
1995
+ console.log(JSON.stringify(res, null, 2));
1996
+ } catch (e) {
1997
+ console.error("Request failed:", e.message);
1998
+ }
1999
+ });
2000
+ publishCmd.command("language-update").description("Update app language info").requiredOption("-a, --app-id <appId>", "App ID").requiredOption("--body <bodyFile>", "JSON body (must include lang)").option("-r, --release-type <releaseType>", "Release type").option("--release-phase <releasePhase>", "Release phase").action(async (options) => {
2001
+ try {
2002
+ const body = readJsonFile(options.body);
2003
+ const res = await PublishService.updateLanguageInfo({
2004
+ appId: options.appId,
2005
+ releaseType: options.releaseType ? Number(options.releaseType) : void 0,
2006
+ releasePhase: options.releasePhase ? Number(options.releasePhase) : void 0,
2007
+ ...body
2008
+ });
2009
+ console.log(JSON.stringify(res, null, 2));
2010
+ } catch (e) {
2011
+ console.error("Request failed:", e.message);
2012
+ }
2013
+ });
2014
+ publishCmd.command("language-delete").description("Delete app language info").requiredOption("-a, --app-id <appId>", "App ID").requiredOption("-l, --lang <lang>", "Language to delete, e.g. zh-CN").option("-r, --release-type <releaseType>", "Release type").action(async (options) => {
2015
+ try {
2016
+ const res = await PublishService.deleteLanguageInfo({
2017
+ appId: options.appId,
2018
+ lang: options.lang,
2019
+ releaseType: options.releaseType ? Number(options.releaseType) : void 0
2020
+ });
2021
+ console.log(JSON.stringify(res, null, 2));
2022
+ } catch (e) {
2023
+ console.error("Request failed:", e.message);
2024
+ }
2025
+ });
2026
+ publishCmd.command("file-info-update").description("Update app file info (icons/screenshots/videos)").requiredOption("-a, --app-id <appId>", "App ID").requiredOption("--body <bodyFile>", "JSON body of file lists").option("-r, --release-type <releaseType>", "Release type").option("--release-phase <releasePhase>", "Release phase").action(async (options) => {
2027
+ try {
2028
+ const body = readJsonFile(options.body);
2029
+ const res = await PublishService.updateAppFileInfo({
2030
+ appId: options.appId,
2031
+ releaseType: options.releaseType ? Number(options.releaseType) : void 0,
2032
+ releasePhase: options.releasePhase ? Number(options.releasePhase) : void 0,
2033
+ ...body
2034
+ });
2035
+ console.log(JSON.stringify(res, null, 2));
2036
+ } catch (e) {
2037
+ console.error("Request failed:", e.message);
2038
+ }
2039
+ });
2040
+ publishCmd.command("package-update").description("Report uploaded package to AGC (call after OBS upload if upload file used --no-bind)").requiredOption("-a, --app-id <appId>", "App ID").requiredOption("--file-name <fileName>", "Uploaded file name").requiredOption("--object-id <objectId>", "Uploaded object ID").option("-r, --release-type <releaseType>", "Release type").option("--release-phase <releasePhase>", "Release phase").action(async (options) => {
2041
+ try {
2042
+ const res = await PublishService.updateAppPackageInfo({
2043
+ appId: options.appId,
2044
+ fileName: options.fileName,
2045
+ objectId: options.objectId,
2046
+ releaseType: options.releaseType ? Number(options.releaseType) : void 0,
2047
+ releasePhase: options.releasePhase ? Number(options.releasePhase) : void 0
2048
+ });
2049
+ console.log(JSON.stringify(res, null, 2));
2050
+ } catch (e) {
2051
+ console.error("Request failed:", e.message);
2052
+ }
2053
+ });
2054
+ publishCmd.command("release-time").description("Update version on-shelf time").requiredOption("-a, --app-id <appId>", "App ID").requiredOption("--change-type <changeType>", "2 immediate, 3 change scheduled time").option("--release-time <releaseTime>", "UTC time yyyy-MM-ddTHH:mm:ssZZ").option("-r, --release-type <releaseType>", "Release type (default 1)").action(async (options) => {
2055
+ try {
2056
+ const res = await PublishService.updateReleaseTime({
2057
+ appId: options.appId,
2058
+ changeType: Number(options.changeType),
2059
+ releaseTime: options.releaseTime,
2060
+ releaseType: options.releaseType ? Number(options.releaseType) : void 0
2061
+ });
2062
+ console.log(JSON.stringify(res, null, 2));
2063
+ } catch (e) {
2064
+ console.error("Request failed:", e.message);
2065
+ }
2066
+ });
2067
+ publishCmd.command("phased-release").description("Update phased release settings").requiredOption("-a, --app-id <appId>", "App ID").requiredOption("--body <bodyFile>", "JSON body (versionId, releasePhase, state, ...)").action(async (options) => {
2068
+ try {
2069
+ const body = readJsonFile(options.body);
2070
+ const res = await PublishService.updatePhasedRelease({ appId: options.appId, ...body });
2071
+ console.log(JSON.stringify(res, null, 2));
2072
+ } catch (e) {
2073
+ console.error("Request failed:", e.message);
2074
+ }
2075
+ });
2076
+ publishCmd.command("package-info").description("Query package info by package ID").requiredOption("-a, --app-id <appId>", "App ID").requiredOption("--package-id <packageId>", "Package ID").action(async (options) => {
2077
+ try {
2078
+ const res = await PublishService.getPackageInfo({
2079
+ appId: options.appId,
2080
+ packageId: options.packageId
2081
+ });
2082
+ console.log(JSON.stringify(res, null, 2));
2083
+ } catch (e) {
2084
+ console.error("Request failed:", e.message);
2085
+ }
2086
+ });
2087
+ publishCmd.command("compile-status").description("Query package compile/parse status").requiredOption("-a, --app-id <appId>", "App ID").requiredOption("--pkg-ids <pkgIds>", "Comma separated package IDs").action(async (options) => {
2088
+ try {
2089
+ const res = await PublishService.getCompileStatus({
2090
+ appId: options.appId,
2091
+ pkgIds: options.pkgIds
2092
+ });
2093
+ console.log(JSON.stringify(res, null, 2));
2094
+ } catch (e) {
2095
+ console.error("Request failed:", e.message);
2096
+ }
2097
+ });
2098
+ publishCmd.command("version-list").description("Query brief info list of all version types (commercial + test)").requiredOption("-a, --app-id <appId>", "App ID").option("-p, --package-name <packageName>", "Package name").option("--state <state>", "Version state filter (comma-separated)").action(async (options) => {
2099
+ try {
2100
+ const res = await PublishService.queryBriefInfoList({
2101
+ appId: options.appId,
2102
+ packageName: options.packageName,
2103
+ state: options.state
2104
+ });
2105
+ console.log(JSON.stringify(res, null, 2));
2106
+ } catch (e) {
2107
+ console.error("Request failed:", e.message);
2108
+ }
2109
+ });
2110
+ publishCmd.command("version-voc").description("Query unresolved version VOC tickets").requiredOption("-a, --app-id <appId>", "App ID").option("--body <bodyFile>", "Optional JSON filter (vocId/vocDesc/pageNo/pageSize)").action(async (options) => {
2111
+ try {
2112
+ const body = options.body ? readJsonFile(options.body) : {};
2113
+ const res = await PublishService.queryVersionVoc({ appId: options.appId, ...body });
2114
+ console.log(JSON.stringify(res, null, 2));
2115
+ } catch (e) {
2116
+ console.error("Request failed:", e.message);
2117
+ }
2118
+ });
2119
+ publishCmd.command("qual-dependent").description("Query required qualification file definitions").action(async () => {
2120
+ try {
2121
+ const res = await PublishService.queryTagQualDependent();
2122
+ console.log(JSON.stringify(res, null, 2));
2123
+ } catch (e) {
2124
+ console.error("Request failed:", e.message);
2125
+ }
2126
+ });
2127
+ publishCmd.command("qual-submit").description("Submit qualification review task").requiredOption("-a, --app-id <appId>", "App ID").requiredOption("--body <bodyFile>", "JSON body with tagQualInfos").action(async (options) => {
2128
+ try {
2129
+ const body = readJsonFile(options.body);
2130
+ const res = await PublishService.submitQualificationReview({ appId: options.appId, ...body });
2131
+ console.log(JSON.stringify(res, null, 2));
2132
+ } catch (e) {
2133
+ console.error("Request failed:", e.message);
2134
+ }
2135
+ });
2136
+ publishCmd.command("qual-query").description("Query qualification review task details").requiredOption("-a, --app-id <appId>", "App ID").requiredOption("--tag-ids <tagIds>", "Comma separated tag IDs").action(async (options) => {
2137
+ try {
2138
+ const res = await PublishService.getQualificationReview({
2139
+ appId: options.appId,
2140
+ tagIds: options.tagIds
2141
+ });
2142
+ console.log(JSON.stringify(res, null, 2));
2143
+ } catch (e) {
2144
+ console.error("Request failed:", e.message);
2145
+ }
2146
+ });
2147
+ publishCmd.command("qual-update").description("Update qualification review task").requiredOption("-a, --app-id <appId>", "App ID").requiredOption("--body <bodyFile>", "JSON body with tagQualInfos").action(async (options) => {
2148
+ try {
2149
+ const body = readJsonFile(options.body);
2150
+ const res = await PublishService.updateQualificationReview({ appId: options.appId, ...body });
2151
+ console.log(JSON.stringify(res, null, 2));
2152
+ } catch (e) {
2153
+ console.error("Request failed:", e.message);
2154
+ }
2155
+ });
2156
+ publishCmd.command("qual-cancel").description("Cancel qualification review task").requiredOption("-a, --app-id <appId>", "App ID").requiredOption("--task-id <taskId>", "Task ID").action(async (options) => {
2157
+ try {
2158
+ const res = await PublishService.cancelQualificationReview({
2159
+ appId: options.appId,
2160
+ taskId: options.taskId
2161
+ });
2162
+ console.log(JSON.stringify(res, null, 2));
2163
+ } catch (e) {
2164
+ console.error("Request failed:", e.message);
2165
+ }
2166
+ });
2167
+ publishCmd.command("qual-delete").description("Delete qualification review task").requiredOption("-a, --app-id <appId>", "App ID").requiredOption("--tag-ids <tagIds>", "Comma separated tag IDs").action(async (options) => {
2168
+ try {
2169
+ const res = await PublishService.deleteQualificationReview({
2170
+ appId: options.appId,
2171
+ tagIds: options.tagIds.split(",")
2172
+ });
2173
+ console.log(JSON.stringify(res, null, 2));
2174
+ } catch (e) {
2175
+ console.error("Request failed:", e.message);
2176
+ }
2177
+ });
2178
+ publishCmd.command("agreement-create").description("Create user agreement or privacy agreement (type in body)").requiredOption("-a, --app-id <appId>", "App ID").requiredOption("--body <bodyFile>", "JSON body (type: 1 privacy / 2 user agreement, ...)").action(async (options) => {
2179
+ try {
2180
+ const body = readJsonFile(options.body);
2181
+ const res = await PublishService.createAgreement({ appId: options.appId, ...body });
2182
+ console.log(JSON.stringify(res, null, 2));
2183
+ } catch (e) {
2184
+ console.error("Request failed:", e.message);
2185
+ }
2186
+ });
2187
+ publishCmd.command("agreement-list").description("List user/privacy agreements").requiredOption("-a, --app-id <appId>", "App ID").option("--body <bodyFile>", "Optional JSON filter (type/status/name/...)").option("--type <type>", "1 privacy, 2 user agreement").action(async (options) => {
2188
+ try {
2189
+ const body = options.body ? readJsonFile(options.body) : {};
2190
+ if (options.type !== void 0) body.type = Number(options.type);
2191
+ const res = await PublishService.listAgreements({ appId: options.appId, ...body });
2192
+ console.log(JSON.stringify(res, null, 2));
2193
+ } catch (e) {
2194
+ console.error("Request failed:", e.message);
2195
+ }
2196
+ });
2197
+ publishCmd.command("agreement-update").description("Update user/privacy agreement").requiredOption("-a, --app-id <appId>", "App ID").requiredOption("--body <bodyFile>", "JSON body (id, defaultLang, agreementInfos, ...)").action(async (options) => {
2198
+ try {
2199
+ const body = readJsonFile(options.body);
2200
+ const res = await PublishService.updateAgreement({ appId: options.appId, ...body });
2201
+ console.log(JSON.stringify(res, null, 2));
2202
+ } catch (e) {
2203
+ console.error("Request failed:", e.message);
2204
+ }
2205
+ });
2206
+ publishCmd.command("privacy-submit").description("Submit privacy agreement for review").requiredOption("-a, --app-id <appId>", "App ID").requiredOption("--id <agreementId>", "Agreement ID").option("--require-confirm <flag>", "requireConfirm: 0 or 1").action(async (options) => {
2207
+ try {
2208
+ const res = await PublishService.submitPrivacyAgreement({
2209
+ appId: options.appId,
2210
+ id: options.id,
2211
+ requireConfirm: options.requireConfirm !== void 0 ? Number(options.requireConfirm) : void 0
2212
+ });
2213
+ console.log(JSON.stringify(res, null, 2));
2214
+ } catch (e) {
2215
+ console.error("Request failed:", e.message);
2216
+ }
2217
+ });
2218
+ publishCmd.command("age-rating").description("Apply for age rating").requiredOption("-a, --app-id <appId>", "App ID").requiredOption("--body <bodyFile>", "JSON body (feedback/expectedRating/...)").option("-r, --release-type <releaseType>", "Release type").option("--release-phase <releasePhase>", "Release phase").action(async (options) => {
2219
+ try {
2220
+ const body = readJsonFile(options.body);
2221
+ const res = await PublishService.applyAgeRating({
2222
+ appId: options.appId,
2223
+ releaseType: options.releaseType ? Number(options.releaseType) : void 0,
2224
+ releasePhase: options.releasePhase ? Number(options.releasePhase) : void 0,
2225
+ ...body
2226
+ });
2227
+ console.log(JSON.stringify(res, null, 2));
2228
+ } catch (e) {
2229
+ console.error("Request failed:", e.message);
2230
+ }
2231
+ });
2232
+ publishCmd.command("submit").description("Submit app for release review").requiredOption("-a, --app-id <appId>", "App ID").option("--body <bodyFile>", "Optional JSON (releaseTime/remark/releaseType/releasePhase/...)").option("-r, --release-type <releaseType>", "Release type").option("--release-phase <releasePhase>", "Release phase").option("--remark <remark>", "Submit remark").option("--release-time <releaseTime>", "UTC release time").action(async (options) => {
2233
+ try {
2234
+ const body = options.body ? readJsonFile(options.body) : {};
2235
+ if (options.releaseType !== void 0) body.releaseType = Number(options.releaseType);
2236
+ if (options.releasePhase !== void 0) body.releasePhase = Number(options.releasePhase);
2237
+ if (options.remark !== void 0) body.remark = options.remark;
2238
+ if (options.releaseTime !== void 0) body.releaseTime = options.releaseTime;
2239
+ const res = await PublishService.submitApp({ appId: options.appId, ...body });
2240
+ console.log(JSON.stringify(res, null, 2));
2241
+ } catch (e) {
2242
+ console.error("Request failed:", e.message);
2243
+ }
2244
+ });
2245
+ publishCmd.command("cancel-review").description("Cancel an in-review version").requiredOption("-a, --app-id <appId>", "App ID").requiredOption("-v, --version-id <versionId>", "Version ID").action(async (options) => {
2246
+ try {
2247
+ const res = await PublishService.cancelReview({
2248
+ appId: options.appId,
2249
+ versionId: options.versionId
2250
+ });
2251
+ console.log(JSON.stringify(res, null, 2));
2252
+ } catch (e) {
2253
+ console.error("Request failed:", e.message);
2254
+ }
2255
+ });
2256
+ publishCmd.command("shelf-off").description("Take app off shelf").requiredOption("-a, --app-id <appId>", "App ID").requiredOption("--reason <reason>", "Off-shelf reason").option("-r, --release-type <releaseType>", "Release type").action(async (options) => {
2257
+ try {
2258
+ const res = await PublishService.shelfOff({
2259
+ appId: options.appId,
2260
+ reason: options.reason,
2261
+ releaseType: options.releaseType ? Number(options.releaseType) : void 0
2262
+ });
2263
+ console.log(JSON.stringify(res, null, 2));
2264
+ } catch (e) {
2265
+ console.error("Request failed:", e.message);
2266
+ }
2267
+ });
2268
+ var projectCmd = program.command("project").description("Project Management API commands");
2269
+ projectCmd.command("list").description("List AGC projects (projectId for publish app-create)").action(async () => {
2270
+ try {
2271
+ const res = await ProjectService.listProjects();
2272
+ console.log(JSON.stringify(res, null, 2));
2273
+ const list = res.projectList ?? [];
2274
+ if (res.ret?.code === 0 && list.length > 0) {
2275
+ console.error("projectId choices:");
2276
+ for (const p of list) {
2277
+ console.error(` ${p.projectId}${p.name ? ` ${p.name}` : ""}`);
2278
+ }
2279
+ }
2280
+ } catch (e) {
2281
+ console.error("Request failed:", e.message);
2282
+ }
2283
+ });
2284
+ var uploadCmd = program.command("upload").description("Upload Management API commands");
2285
+ uploadCmd.command("file").description("Upload a file (APP, APK, images, etc.); .app is reported to AGC unless --no-bind or -r 6").requiredOption("-a, --app-id <appId>", "App ID").requiredOption("-f, --file-path <filePath>", "Path to the local file to upload").option("-r, --release-type <releaseType>", "Release type: 1 for Full, 6 for HarmonyOS Test").option("-c, --chinese-mainland <flag>", "Chinese mainland flag: 0 or 1").option("--no-bind", "OBS upload only; skip reporting the package so it will not appear in AGC").action(async (options) => {
2286
+ try {
2287
+ console.error(`Uploading file ${options.filePath}...`);
2288
+ const releaseType = options.releaseType ? Number(options.releaseType) : void 0;
2289
+ const uploaded = await UploadService.uploadFile({
2290
+ appId: options.appId,
2291
+ filePath: options.filePath,
2292
+ releaseType,
2293
+ chineseMainlandFlag: options.chineseMainland ? Number(options.chineseMainland) : void 0
2294
+ });
2295
+ const ext = import_path6.default.extname(uploaded.fileName).toLowerCase();
2296
+ const shouldBind = options.bind !== false && ext === ".app" && releaseType !== 6;
2297
+ if (!shouldBind) {
2298
+ console.log(JSON.stringify({
2299
+ ret: { code: 0, msg: "success" },
2300
+ fileName: uploaded.fileName,
2301
+ objectId: uploaded.objectId,
2302
+ bound: false
2303
+ }, null, 2));
2304
+ return;
2305
+ }
2306
+ console.error("Reporting package to AGC...");
2307
+ const bindRes = await PublishService.updateAppPackageInfo({
2308
+ appId: options.appId,
2309
+ fileName: uploaded.fileName,
2310
+ objectId: uploaded.objectId,
2311
+ releaseType
2312
+ });
2313
+ console.log(JSON.stringify({
2314
+ ...bindRes,
2315
+ fileName: uploaded.fileName,
2316
+ objectId: uploaded.objectId,
2317
+ bound: bindRes.ret?.code === 0
2318
+ }, null, 2));
2319
+ if (bindRes.ret?.code !== 0) {
2320
+ console.error(
2321
+ "Package report failed (file is on OBS but AGC has no record):",
2322
+ bindRes.ret?.msg || JSON.stringify(bindRes.ret)
2323
+ );
2324
+ }
2325
+ } catch (e) {
2326
+ console.error("Upload failed:", e.message);
2327
+ }
2328
+ });
2329
+ var provisionCmd = program.command("provision").description("Provisioning API commands");
2330
+ provisionCmd.command("csr-generate").description("Generate a new keypair and CSR file").requiredOption("--alias <alias>", "Key alias").option("--pwd <pwd>", "Key password (default: CSPRNG hex, returned as .pwd; not written to disk)").option("--out-dir <outDir>", "Root output directory (default: ./.certs; each run adds a CSPRNG subdirectory)").option("--filename <filename>", "Shared random id for the cert subdirectory (files get key_/cert_/profile_ prefixes)").option("--sdk-path <sdkPath>", "Path to HarmonyOS SDK (or set HARMONYOS_SDK_PATH env var)").option("--java-path <javaPath>", "Path to java executable (default: java)").action(async (options) => {
2331
+ try {
2332
+ const res = await SignService.createSignP12AndCsr({
2333
+ alias: options.alias,
2334
+ pwd: options.pwd,
2335
+ outDir: options.outDir,
2336
+ filename: options.filename,
2337
+ sdkPath: options.sdkPath,
2338
+ javaPath: options.javaPath
2339
+ });
2340
+ console.error("CSR generation successful.");
2341
+ console.log(JSON.stringify(res, null, 2));
2342
+ } catch (e) {
2343
+ console.error("CSR generation failed:", e.message);
2344
+ }
2345
+ });
2346
+ provisionCmd.command("encrypt-pwd").description("\u52A0\u5BC6 P12 \u5BC6\u7801\uFF0C\u751F\u6210 build-profile.json5 \u6240\u9700\u7684 keyPassword / storePassword").requiredOption("--pwd <password>", "P12 \u5BC6\u7801\u660E\u6587").option("--config-dir <configDir>", "DevEco Studio \u914D\u7F6E\u76EE\u5F55 (\u9ED8\u8BA4 ~/.ohos/config)").action(async (options) => {
2347
+ try {
2348
+ const res = SignService.encryptPassword(options.pwd, options.configDir);
2349
+ console.log(JSON.stringify(res, null, 2));
2350
+ } catch (e) {
2351
+ console.error("\u52A0\u5BC6\u5931\u8D25:", e.message);
2352
+ }
2353
+ });
2354
+ provisionCmd.command("cert-create").description("Create a certificate").requiredOption("--csr <csrFile>", "Path to CSR file").requiredOption("--cert-name <certName>", "Certificate name").requiredOption("--cert-type <certType>", "Certificate type (1: debug, 2: release, 3: in-house, 4: binary)").action(async (options) => {
2355
+ try {
2356
+ const csrContent = fs7.readFileSync(options.csr, "utf8");
2357
+ const res = await ProvisionService.createCert({
2358
+ csr: csrContent,
2359
+ certName: options.certName,
2360
+ certType: Number(options.certType)
2361
+ });
2362
+ console.log(JSON.stringify(res, null, 2));
2363
+ } catch (e) {
2364
+ console.error("Request failed:", e.message);
2365
+ }
2366
+ });
2367
+ provisionCmd.command("cert-list").description("List certificates").option("-t, --cert-type <certType>", "Certificate type").option("--cert-ids <certIds>", "Comma separated certificate IDs").action(async (options) => {
2368
+ try {
2369
+ const req = {};
2370
+ if (options.certType) req.certType = Number(options.certType);
2371
+ if (options.certIds) req.certIds = options.certIds.split(",");
2372
+ const res = await ProvisionService.getCertList(req);
2373
+ console.log(JSON.stringify(res, null, 2));
2374
+ } catch (e) {
2375
+ console.error("Request failed:", e.message);
2376
+ }
2377
+ });
2378
+ provisionCmd.command("cert-delete").description("Delete certificates").requiredOption("--cert-ids <certIds>", "Comma separated certificate IDs to delete").action(async (options) => {
2379
+ try {
2380
+ const res = await ProvisionService.deleteCert({
2381
+ certIds: options.certIds.split(",")
2382
+ });
2383
+ console.log(JSON.stringify(res, null, 2));
2384
+ } catch (e) {
2385
+ console.error("Request failed:", e.message);
2386
+ }
2387
+ });
2388
+ provisionCmd.command("device-add").description("Add new devices").requiredOption("--devices <devicesFile>", 'Path to JSON file containing devices array [{"deviceName":"name","udid":"udid","deviceType":1}]').action(async (options) => {
2389
+ try {
2390
+ const fileContent = fs7.readFileSync(options.devices, "utf8");
2391
+ const deviceList = JSON.parse(fileContent);
2392
+ const res = await ProvisionService.addDevice({ deviceList });
2393
+ console.log(JSON.stringify(res, null, 2));
2394
+ } catch (e) {
2395
+ console.error("Request failed:", e.message);
2396
+ }
2397
+ });
2398
+ provisionCmd.command("device-list").description("List devices").option("--device-name <deviceName>", "Device name to search").option("--from <fromRecCount>", "Starting page").option("--max <maxReqCount>", "Max items per page").option("--order <order>", "1: create time desc, 2: name asc").action(async (options) => {
2399
+ try {
2400
+ const req = {};
2401
+ if (options.deviceName) req.deviceName = options.deviceName;
2402
+ if (options.from) req.fromRecCount = Number(options.from);
2403
+ if (options.max) req.maxReqCount = Number(options.max);
2404
+ if (options.order) req.order = Number(options.order);
2405
+ const res = await ProvisionService.getDeviceList(req);
2406
+ console.log(JSON.stringify(res, null, 2));
2407
+ } catch (e) {
2408
+ console.error("Request failed:", e.message);
2409
+ }
2410
+ });
2411
+ provisionCmd.command("device-delete").description("Delete devices").requiredOption("--device-ids <deviceIdList>", "Comma separated device IDs to delete").action(async (options) => {
2412
+ try {
2413
+ const res = await ProvisionService.deleteDevice({
2414
+ deviceIdList: options.deviceIds.split(",")
2415
+ });
2416
+ console.log(JSON.stringify(res, null, 2));
2417
+ } catch (e) {
2418
+ console.error("Request failed:", e.message);
2419
+ }
2420
+ });
2421
+ provisionCmd.command("profile-create").description("Create a profile").requiredOption("--name <provisionName>", "Profile name").requiredOption("--type <provisionType>", "Profile type (1:debug, 2:release, 3:in-house, 6:specific device)").requiredOption("--cert <certId>", "Certificate ID").requiredOption("-a, --app-id <appId>", "App ID").option("--device-ids <deviceIdList>", "Comma separated device IDs").option("--acls <aclPermissionList>", "Comma separated ACL permissions").action(async (options) => {
2422
+ try {
2423
+ const req = {
2424
+ provisionName: options.name,
2425
+ provisionType: Number(options.type),
2426
+ certId: options.cert,
2427
+ appId: options.appId
2428
+ };
2429
+ if (options.deviceIds) req.deviceIdList = options.deviceIds.split(",");
2430
+ if (options.acls) req.aclPermissionList = options.acls.split(",");
2431
+ const res = await ProvisionService.createProvision(req);
2432
+ console.log(JSON.stringify(res, null, 2));
2433
+ } catch (e) {
2434
+ console.error("Request failed:", e.message);
2435
+ }
2436
+ });
2437
+ provisionCmd.command("profile-list").description("List profiles").requiredOption("-a, --app-id <appId>", "App ID").option("--profile-id <provisionId>", "Profile ID").option("--from <fromRecCount>", "Starting page").option("--max <maxReqCount>", "Max items per page").action(async (options) => {
2438
+ try {
2439
+ const req = { appId: options.appId };
2440
+ if (options.profileId) req.provisionId = options.profileId;
2441
+ if (options.from) req.fromRecCount = Number(options.from);
2442
+ if (options.max) req.maxReqCount = Number(options.max);
2443
+ const res = await ProvisionService.getProvisionList(req);
2444
+ console.log(JSON.stringify(res, null, 2));
2445
+ } catch (e) {
2446
+ console.error("Request failed:", e.message);
2447
+ }
2448
+ });
2449
+ provisionCmd.command("profile-update").description("Update profile devices").requiredOption("--id <provisionId>", "Profile ID").requiredOption("--device-ids <deviceIdList>", "Comma separated device IDs").action(async (options) => {
2450
+ try {
2451
+ const res = await ProvisionService.updateProvision({
2452
+ provisionId: options.id,
2453
+ deviceIdList: options.deviceIds.split(",")
2454
+ });
2455
+ console.log(JSON.stringify(res, null, 2));
2456
+ } catch (e) {
2457
+ console.error("Request failed:", e.message);
2458
+ }
2459
+ });
2460
+ provisionCmd.command("profile-delete").description("Delete a profile").requiredOption("--id <id>", "Profile ID to delete").action(async (options) => {
2461
+ try {
2462
+ const res = await ProvisionService.deleteProvision({ id: options.id });
2463
+ console.log(JSON.stringify(res, null, 2));
2464
+ } catch (e) {
2465
+ console.error("Request failed:", e.message);
2466
+ }
2467
+ });
2468
+ provisionCmd.command("fp-add").description("Add certificate fingerprints").requiredOption("-a, --app-id <appId>", "App ID").requiredOption("--fps <fingerprintList>", "Comma separated fingerprints").action(async (options) => {
2469
+ try {
2470
+ const res = await ProvisionService.addFingerprint({
2471
+ appId: options.appId,
2472
+ fingerprintList: options.fps.split(",")
2473
+ });
2474
+ console.log(JSON.stringify(res, null, 2));
2475
+ } catch (e) {
2476
+ console.error("Request failed:", e.message);
2477
+ }
2478
+ });
2479
+ provisionCmd.command("fp-list").description("List certificate fingerprints").requiredOption("-a, --app-id <appId>", "App ID").action(async (options) => {
2480
+ try {
2481
+ const res = await ProvisionService.getFingerprintList({ appId: options.appId });
2482
+ console.log(JSON.stringify(res, null, 2));
2483
+ } catch (e) {
2484
+ console.error("Request failed:", e.message);
2485
+ }
2486
+ });
2487
+ provisionCmd.command("fp-delete").description("Delete certificate fingerprints").requiredOption("-a, --app-id <appId>", "App ID").requiredOption("--fps <fingerprintList>", "Comma separated fingerprints to delete").action(async (options) => {
2488
+ try {
2489
+ const res = await ProvisionService.deleteFingerprint({
2490
+ appId: options.appId,
2491
+ fingerprintList: options.fps.split(",")
2492
+ });
2493
+ console.log(JSON.stringify(res, null, 2));
2494
+ } catch (e) {
2495
+ console.error("Request failed:", e.message);
2496
+ }
2497
+ });
2498
+ provisionCmd.command("acl-eligible").description("List eligible ACL permissions that can be applied for").requiredOption("-a, --app-id <appId>", "App ID").option("-l, --lang <lang>", "Language: zh / en / ru (default zh)").option("--start <start>", "Start page (default 1)").option("--page-size <pageSize>", "Page size 1-1000 (default 10)").action(async (options) => {
2499
+ try {
2500
+ const res = await ProvisionService.getEligibleACL({
2501
+ appId: options.appId,
2502
+ lang: options.lang,
2503
+ start: options.start ? Number(options.start) : void 0,
2504
+ pageSize: options.pageSize ? Number(options.pageSize) : void 0
2505
+ });
2506
+ console.log(JSON.stringify(res, null, 2));
2507
+ } catch (e) {
2508
+ console.error("Request failed:", e.message);
2509
+ }
2510
+ });
2511
+ provisionCmd.command("acl-apply").description("Apply for restricted ACL permissions").requiredOption("-a, --app-id <appId>", "App ID").requiredOption("--acls <aclsFile>", 'Path to JSON file containing ACL permissions [{"name":"name","reason":"reason"}]').option("--attachment <attachment>", "Attachment object ID").action(async (options) => {
2512
+ try {
2513
+ const fileContent = fs7.readFileSync(options.acls, "utf8");
2514
+ const aclPermissionList = JSON.parse(fileContent);
2515
+ const req = { appId: options.appId, aclPermissionList };
2516
+ if (options.attachment) req.attachment = options.attachment;
2517
+ const res = await ProvisionService.applyACL(req);
2518
+ console.log(JSON.stringify(res, null, 2));
2519
+ } catch (e) {
2520
+ console.error("Request failed:", e.message);
2521
+ }
2522
+ });
2523
+ provisionCmd.command("acl-status").description("Check ACL permission apply status").requiredOption("-a, --app-id <appId>", "App ID").action(async (options) => {
2524
+ try {
2525
+ const res = await ProvisionService.getACLStatus({ appId: options.appId });
2526
+ console.log(JSON.stringify(res, null, 2));
2527
+ } catch (e) {
2528
+ console.error("Request failed:", e.message);
2529
+ }
2530
+ });
2531
+ provisionCmd.command("acl-query").description("Query granted ACL permissions").requiredOption("-a, --app-id <appId>", "App ID").action(async (options) => {
2532
+ try {
2533
+ const res = await ProvisionService.getACLQuery({ appId: options.appId });
2534
+ console.log(JSON.stringify(res, null, 2));
2535
+ } catch (e) {
2536
+ console.error("Request failed:", e.message);
2537
+ }
2538
+ });
2539
+ var domainCmd = program.command("domain").description("Domain Management API commands");
2540
+ domainCmd.command("query").description("Query domain configuration").requiredOption("-a, --app-id <appId>", "App ID").requiredOption("-c, --category <category>", "Category: server or business").action(async (options) => {
2541
+ try {
2542
+ const res = await DomainService.queryDomain({
2543
+ appId: options.appId,
2544
+ category: options.category
2545
+ });
2546
+ console.log(JSON.stringify(res, null, 2));
2547
+ } catch (e) {
2548
+ console.error("Request failed:", e.message);
2549
+ }
2550
+ });
2551
+ domainCmd.command("update").description("Add or update domain configuration").requiredOption("-a, --app-id <appId>", "App ID").requiredOption("-c, --category <category>", "Category: server or business").requiredOption("--domains <domainsFile>", 'Path to JSON file containing domains array [{"type":"httpRequest","value":"https://..."}]').action(async (options) => {
2552
+ try {
2553
+ const fileContent = fs7.readFileSync(options.domains, "utf8");
2554
+ const domains = JSON.parse(fileContent);
2555
+ const res = await DomainService.updateDomain({
2556
+ appId: options.appId,
2557
+ category: options.category,
2558
+ domains
2559
+ });
2560
+ console.log(JSON.stringify(res, null, 2));
2561
+ } catch (e) {
2562
+ console.error("Request failed:", e.message);
2563
+ }
2564
+ });
2565
+ domainCmd.command("config").description("Query domain modification counts and limits").requiredOption("-a, --app-id <appId>", "App ID").action(async (options) => {
2566
+ try {
2567
+ const res = await DomainService.queryDomainConfig({
2568
+ appId: options.appId
2569
+ });
2570
+ console.log(JSON.stringify(res, null, 2));
2571
+ } catch (e) {
2572
+ console.error("Request failed:", e.message);
2573
+ }
2574
+ });
2575
+ domainCmd.command("verify-file").description("Download domain verify file").requiredOption("-a, --app-id <appId>", "App ID").requiredOption("-o, --output <outputPath>", "Output file path").action(async (options) => {
2576
+ try {
2577
+ console.error(`Downloading verify file to ${options.output}...`);
2578
+ await DomainService.verifyFile({
2579
+ appId: options.appId
2580
+ }, options.output);
2581
+ console.log("Download successful.");
2582
+ } catch (e) {
2583
+ console.error("Download failed:", e.message);
2584
+ }
2585
+ });
2586
+ domainCmd.command("pre-check").description("Pre-check business domain configuration").requiredOption("-a, --app-id <appId>", "App ID").requiredOption("--domain <domainFile>", 'Path to JSON file containing domain object {"type":"webView","value":"https://..."}').action(async (options) => {
2587
+ try {
2588
+ const fileContent = fs7.readFileSync(options.domain, "utf8");
2589
+ const domain = JSON.parse(fileContent);
2590
+ const res = await DomainService.preCheckDomain({
2591
+ appId: options.appId,
2592
+ domain
2593
+ });
2594
+ console.log(JSON.stringify(res, null, 2));
2595
+ } catch (e) {
2596
+ console.error("Request failed:", e.message);
2597
+ }
2598
+ });
2599
+ var testCmd = program.command("test").description("Testing API commands (invite/open test versions, groups, invite codes)");
2600
+ testCmd.command("version-create").description("Create a test version").requiredOption("-a, --app-id <appId>", "App ID").requiredOption("--test-type <testType>", "Test type: 3 invite, 4 open").requiredOption("--test-desc <testDesc>", "Test description (max 50 chars)").option("-r, --release-type <releaseType>", "Release type (default 6)").option("--onshelf-self-detect <flag>", "Onshelf self detect: 0 or 1").action(async (options) => {
2601
+ try {
2602
+ const res = await TestingService.createVersion({
2603
+ appId: options.appId,
2604
+ testType: Number(options.testType),
2605
+ testDesc: options.testDesc,
2606
+ releaseType: options.releaseType ? Number(options.releaseType) : void 0,
2607
+ onshelfSelfDetect: options.onshelfSelfDetect !== void 0 ? Number(options.onshelfSelfDetect) : void 0
2608
+ });
2609
+ console.log(JSON.stringify(res, null, 2));
2610
+ } catch (e) {
2611
+ console.error("Request failed:", e.message);
2612
+ }
2613
+ });
2614
+ testCmd.command("version-detect").description("Query onshelf self-detect report").requiredOption("-a, --app-id <appId>", "App ID").requiredOption("-v, --version-id <versionId>", "Test version ID").action(async (options) => {
2615
+ try {
2616
+ const res = await TestingService.getDetectReport({
2617
+ appId: options.appId,
2618
+ versionId: options.versionId
2619
+ });
2620
+ console.log(JSON.stringify(res, null, 2));
2621
+ } catch (e) {
2622
+ console.error("Request failed:", e.message);
2623
+ }
2624
+ });
2625
+ testCmd.command("pkg-add").description("Add package to a test version (objectId from upload)").requiredOption("-a, --app-id <appId>", "App ID").requiredOption("--file-name <fileName>", "Uploaded file name").requiredOption("--object-id <objectId>", "Uploaded object ID").option("--distribute-mode <mode>", "1: test zone, 2: AppGallery").action(async (options) => {
2626
+ try {
2627
+ const res = await TestingService.addPackage({
2628
+ appId: options.appId,
2629
+ distributeMode: options.distributeMode ? Number(options.distributeMode) : void 0,
2630
+ file: { fileName: options.fileName, objectId: options.objectId }
2631
+ });
2632
+ console.log(JSON.stringify(res, null, 2));
2633
+ } catch (e) {
2634
+ console.error("Request failed:", e.message);
2635
+ }
2636
+ });
2637
+ testCmd.command("version-update").description("Update a test version (bind pkg/groups/languages via JSON body)").requiredOption("-a, --app-id <appId>", "App ID").requiredOption("--body <bodyFile>", "JSON body (must include versionId; optional pkgId, openTestInfo, ...)").action(async (options) => {
2638
+ try {
2639
+ const body = readJsonFile(options.body);
2640
+ const res = await TestingService.updateVersion({ appId: options.appId, ...body });
2641
+ console.log(JSON.stringify(res, null, 2));
2642
+ } catch (e) {
2643
+ console.error("Request failed:", e.message);
2644
+ }
2645
+ });
2646
+ testCmd.command("version-release").description("Update effective/release settings of a test version").requiredOption("-a, --app-id <appId>", "App ID").requiredOption("--body <bodyFile>", "JSON body (must include versionId)").action(async (options) => {
2647
+ try {
2648
+ const body = readJsonFile(options.body);
2649
+ const res = await TestingService.releaseVersion({ appId: options.appId, ...body });
2650
+ console.log(JSON.stringify(res, null, 2));
2651
+ } catch (e) {
2652
+ console.error("Request failed:", e.message);
2653
+ }
2654
+ });
2655
+ testCmd.command("version-opentest").description("Update open-test time window / install quota / bind groups").requiredOption("-a, --app-id <appId>", "App ID").requiredOption("--body <bodyFile>", "JSON body (must include versionId)").action(async (options) => {
2656
+ try {
2657
+ const body = readJsonFile(options.body);
2658
+ const res = await TestingService.updateOpenTest({ appId: options.appId, ...body });
2659
+ console.log(JSON.stringify(res, null, 2));
2660
+ } catch (e) {
2661
+ console.error("Request failed:", e.message);
2662
+ }
2663
+ });
2664
+ testCmd.command("version-submit").description("Submit a test version for review").requiredOption("-a, --app-id <appId>", "App ID").requiredOption("-v, --version-id <versionId>", "Test version ID").action(async (options) => {
2665
+ try {
2666
+ const res = await TestingService.submitVersion({
2667
+ appId: options.appId,
2668
+ versionId: options.versionId
2669
+ });
2670
+ console.log(JSON.stringify(res, null, 2));
2671
+ } catch (e) {
2672
+ console.error("Request failed:", e.message);
2673
+ }
2674
+ });
2675
+ testCmd.command("version-stop").description("Stop a test version").requiredOption("-a, --app-id <appId>", "App ID").requiredOption("-v, --version-id <versionId>", "Test version ID").action(async (options) => {
2676
+ try {
2677
+ const res = await TestingService.stopVersion({
2678
+ appId: options.appId,
2679
+ versionId: options.versionId
2680
+ });
2681
+ console.log(JSON.stringify(res, null, 2));
2682
+ } catch (e) {
2683
+ console.error("Request failed:", e.message);
2684
+ }
2685
+ });
2686
+ testCmd.command("version-delete").description("Delete a test version").requiredOption("-a, --app-id <appId>", "App ID").requiredOption("-v, --version-id <versionId>", "Test version ID").action(async (options) => {
2687
+ try {
2688
+ const res = await TestingService.deleteVersion({
2689
+ appId: options.appId,
2690
+ versionId: options.versionId
2691
+ });
2692
+ console.log(JSON.stringify(res, null, 2));
2693
+ } catch (e) {
2694
+ console.error("Request failed:", e.message);
2695
+ }
2696
+ });
2697
+ testCmd.command("group-add").description("Create a test group").requiredOption("-a, --app-id <appId>", "App ID").requiredOption("--name <groupName>", "Group name").option("--type <groupType>", "0 external (default), 1 internal").action(async (options) => {
2698
+ try {
2699
+ const res = await TestingService.addGroup({
2700
+ appId: options.appId,
2701
+ groupName: options.name,
2702
+ groupType: options.type !== void 0 ? Number(options.type) : void 0
2703
+ });
2704
+ console.log(JSON.stringify(res, null, 2));
2705
+ } catch (e) {
2706
+ console.error("Request failed:", e.message);
2707
+ }
2708
+ });
2709
+ testCmd.command("group-list").description("List test groups").requiredOption("-a, --app-id <appId>", "App ID").option("--type <groupType>", "0 external, 1 internal").option("--current <current>", "Page number").option("--page-size <pageSize>", "Page size").action(async (options) => {
2710
+ try {
2711
+ const res = await TestingService.listGroups({
2712
+ appId: options.appId,
2713
+ groupType: options.type !== void 0 ? Number(options.type) : void 0,
2714
+ current: options.current ? Number(options.current) : void 0,
2715
+ pageSize: options.pageSize ? Number(options.pageSize) : void 0
2716
+ });
2717
+ console.log(JSON.stringify(res, null, 2));
2718
+ } catch (e) {
2719
+ console.error("Request failed:", e.message);
2720
+ }
2721
+ });
2722
+ testCmd.command("group-delete").description("Delete a test group").requiredOption("-a, --app-id <appId>", "App ID").requiredOption("-g, --group-id <groupId>", "Group ID").action(async (options) => {
2723
+ try {
2724
+ const res = await TestingService.deleteGroup({
2725
+ appId: options.appId,
2726
+ groupId: options.groupId
2727
+ });
2728
+ console.log(JSON.stringify(res, null, 2));
2729
+ } catch (e) {
2730
+ console.error("Request failed:", e.message);
2731
+ }
2732
+ });
2733
+ testCmd.command("group-edit").description("Rename a test group").requiredOption("-a, --app-id <appId>", "App ID").requiredOption("-g, --group-id <groupId>", "Group ID").requiredOption("--name <groupName>", "New group name").action(async (options) => {
2734
+ try {
2735
+ const res = await TestingService.editGroup({
2736
+ appId: options.appId,
2737
+ groupId: options.groupId,
2738
+ groupName: options.name
2739
+ });
2740
+ console.log(JSON.stringify(res, null, 2));
2741
+ } catch (e) {
2742
+ console.error("Request failed:", e.message);
2743
+ }
2744
+ });
2745
+ testCmd.command("group-user-list").description("List members of a test group").requiredOption("-a, --app-id <appId>", "App ID").requiredOption("-g, --group-id <groupId>", "Group ID").option("--current <current>", "Page number").option("--page-size <pageSize>", "Page size").action(async (options) => {
2746
+ try {
2747
+ const res = await TestingService.listGroupUsers({
2748
+ appId: options.appId,
2749
+ groupId: options.groupId,
2750
+ current: options.current ? Number(options.current) : void 0,
2751
+ pageSize: options.pageSize ? Number(options.pageSize) : void 0
2752
+ });
2753
+ console.log(JSON.stringify(res, null, 2));
2754
+ } catch (e) {
2755
+ console.error("Request failed:", e.message);
2756
+ }
2757
+ });
2758
+ testCmd.command("group-user-add").description("Add a member to a test group").requiredOption("-a, --app-id <appId>", "App ID").requiredOption("--body <bodyFile>", "JSON body: groupId, nickName/hwAccount/uid, ...").action(async (options) => {
2759
+ try {
2760
+ const body = readJsonFile(options.body);
2761
+ const res = await TestingService.addGroupUser({ appId: options.appId, ...body });
2762
+ console.log(JSON.stringify(res, null, 2));
2763
+ } catch (e) {
2764
+ console.error("Request failed:", e.message);
2765
+ }
2766
+ });
2767
+ testCmd.command("group-user-delete").description("Delete members from a test group").requiredOption("-a, --app-id <appId>", "App ID").requiredOption("-g, --group-id <groupId>", "Group ID").requiredOption("--tester-ids <testerIds>", "Comma separated tester IDs").action(async (options) => {
2768
+ try {
2769
+ const res = await TestingService.deleteGroupUser({
2770
+ appId: options.appId,
2771
+ groupId: options.groupId,
2772
+ deleteTesterIds: options.testerIds.split(",")
2773
+ });
2774
+ console.log(JSON.stringify(res, null, 2));
2775
+ } catch (e) {
2776
+ console.error("Request failed:", e.message);
2777
+ }
2778
+ });
2779
+ testCmd.command("group-notify").description("Send invite-test notification to group members").requiredOption("-a, --app-id <appId>", "App ID").requiredOption("-g, --group-id <groupId>", "Group ID").requiredOption("--tester-ids <testerIds>", "Comma separated tester IDs").action(async (options) => {
2780
+ try {
2781
+ const res = await TestingService.notifyUsers({
2782
+ appId: options.appId,
2783
+ groupId: options.groupId,
2784
+ testerIds: options.testerIds.split(",")
2785
+ });
2786
+ console.log(JSON.stringify(res, null, 2));
2787
+ } catch (e) {
2788
+ console.error("Request failed:", e.message);
2789
+ }
2790
+ });
2791
+ testCmd.command("invite-code-create").description("Generate an invitation code for a group").requiredOption("-a, --app-id <appId>", "App ID").requiredOption("-g, --group-id <groupId>", "Group ID").requiredOption("--valid-days <days>", "Valid days (max 30)").requiredOption("--invite-limit <limit>", "Invite limit (max 10000)").action(async (options) => {
2792
+ try {
2793
+ const res = await TestingService.createInviteCode({
2794
+ appId: options.appId,
2795
+ groupId: options.groupId,
2796
+ invitationCodeValidDays: Number(options.validDays),
2797
+ invitationCodeInviteLimit: Number(options.inviteLimit)
2798
+ });
2799
+ console.log(JSON.stringify(res, null, 2));
2800
+ } catch (e) {
2801
+ console.error("Request failed:", e.message);
2802
+ }
2803
+ });
2804
+ testCmd.command("invite-code-list").description("Query invitation codes of a group").requiredOption("-a, --app-id <appId>", "App ID").requiredOption("-g, --group-id <groupId>", "Group ID").action(async (options) => {
2805
+ try {
2806
+ const res = await TestingService.getInviteCode({
2807
+ appId: options.appId,
2808
+ groupId: options.groupId
2809
+ });
2810
+ console.log(JSON.stringify(res, null, 2));
2811
+ } catch (e) {
2812
+ console.error("Request failed:", e.message);
2813
+ }
2814
+ });
2815
+ testCmd.command("invite-code-stop").description("Stop an invitation code").requiredOption("-a, --app-id <appId>", "App ID").requiredOption("--code-id <invitationCodeId>", "Invitation code ID").action(async (options) => {
2816
+ try {
2817
+ const res = await TestingService.stopInviteCode({
2818
+ appId: options.appId,
2819
+ invitationCodeId: options.codeId
2820
+ });
2821
+ console.log(JSON.stringify(res, null, 2));
2822
+ } catch (e) {
2823
+ console.error("Request failed:", e.message);
2824
+ }
2825
+ });
2826
+ testCmd.command("invite-code-delete").description("Delete an invitation code").requiredOption("-a, --app-id <appId>", "App ID").requiredOption("--code-id <invitationCodeId>", "Invitation code ID").action(async (options) => {
2827
+ try {
2828
+ const res = await TestingService.deleteInviteCode({
2829
+ appId: options.appId,
2830
+ invitationCodeId: options.codeId
2831
+ });
2832
+ console.log(JSON.stringify(res, null, 2));
2833
+ } catch (e) {
2834
+ console.error("Request failed:", e.message);
2835
+ }
2836
+ });
2837
+ testCmd.command("public-link-create").description("Create a public test link for a group").requiredOption("-a, --app-id <appId>", "App ID").requiredOption("-g, --group-id <groupId>", "Group ID").requiredOption("--limit <limit>", "Install/limit count").action(async (options) => {
2838
+ try {
2839
+ const res = await TestingService.createPublicLink({
2840
+ appId: options.appId,
2841
+ groupId: options.groupId,
2842
+ limit: Number(options.limit)
2843
+ });
2844
+ console.log(JSON.stringify(res, null, 2));
2845
+ } catch (e) {
2846
+ console.error("Request failed:", e.message);
2847
+ }
2848
+ });
2849
+ testCmd.command("public-link-edit").description("Edit a public test link").requiredOption("-a, --app-id <appId>", "App ID").requiredOption("-g, --group-id <groupId>", "Group ID").option("--limit <limit>", "Install/limit count").option("--status <status>", "Link status").action(async (options) => {
2850
+ try {
2851
+ const res = await TestingService.editPublicLink({
2852
+ appId: options.appId,
2853
+ groupId: options.groupId,
2854
+ limit: options.limit !== void 0 ? Number(options.limit) : void 0,
2855
+ status: options.status !== void 0 ? Number(options.status) : void 0
2856
+ });
2857
+ console.log(JSON.stringify(res, null, 2));
2858
+ } catch (e) {
2859
+ console.error("Request failed:", e.message);
2860
+ }
2861
+ });
2862
+ testCmd.command("public-link-query").description("Query a public test link").requiredOption("-a, --app-id <appId>", "App ID").requiredOption("-g, --group-id <groupId>", "Group ID").action(async (options) => {
2863
+ try {
2864
+ const res = await TestingService.queryPublicLink({
2865
+ appId: options.appId,
2866
+ groupId: options.groupId
2867
+ });
2868
+ console.log(JSON.stringify(res, null, 2));
2869
+ } catch (e) {
2870
+ console.error("Request failed:", e.message);
2871
+ }
2872
+ });
2873
+ testCmd.command("feedback-dimension").description("Query tester feedback dimensions").requiredOption("-a, --app-id <appId>", "App ID").requiredOption("--body <bodyFile>", "JSON filter body (startTime/endTime/...)").action(async (options) => {
2874
+ try {
2875
+ const body = readJsonFile(options.body);
2876
+ const res = await TestingService.queryFeedbackDimension({ appId: options.appId, ...body });
2877
+ console.log(JSON.stringify(res, null, 2));
2878
+ } catch (e) {
2879
+ console.error("Request failed:", e.message);
2880
+ }
2881
+ });
2882
+ testCmd.command("feedback-query").description("Query tester feedback list").requiredOption("-a, --app-id <appId>", "App ID").requiredOption("--body <bodyFile>", "JSON filter body (startTime/endTime/currentPage/...)").action(async (options) => {
2883
+ try {
2884
+ const body = readJsonFile(options.body);
2885
+ const res = await TestingService.queryFeedback({ appId: options.appId, ...body });
2886
+ console.log(JSON.stringify(res, null, 2));
2887
+ } catch (e) {
2888
+ console.error("Request failed:", e.message);
2889
+ }
2890
+ });
2891
+ testCmd.command("feedback-delete").description("Delete tester feedback").requiredOption("-a, --app-id <appId>", "App ID").requiredOption("--body <bodyFile>", "JSON body: delFeedBackInfos, deleteMode").action(async (options) => {
2892
+ try {
2893
+ const body = readJsonFile(options.body);
2894
+ const res = await TestingService.deleteFeedback({ appId: options.appId, ...body });
2895
+ console.log(JSON.stringify(res, null, 2));
2896
+ } catch (e) {
2897
+ console.error("Request failed:", e.message);
2898
+ }
2899
+ });
2900
+ program.parse(process.argv);
2901
+ //# sourceMappingURL=cli.js.map