@supersdk/supercli 0.2.1-staging.19 → 0.2.1-staging.21

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (55) hide show
  1. package/dist/api/consoleClient.js +17 -12
  2. package/dist/api/consoleClient.js.map +1 -1
  3. package/dist/auth/browserAuth.js +42 -44
  4. package/dist/auth/browserAuth.js.map +1 -1
  5. package/dist/auth/tokenAuth.js +46 -0
  6. package/dist/auth/tokenAuth.js.map +1 -0
  7. package/dist/cli.js +66 -6
  8. package/dist/cli.js.map +1 -1
  9. package/dist/commands/accounts.js +89 -31
  10. package/dist/commands/accounts.js.map +1 -1
  11. package/dist/commands/login.js +75 -48
  12. package/dist/commands/login.js.map +1 -1
  13. package/dist/commands/logout.js +20 -25
  14. package/dist/commands/logout.js.map +1 -1
  15. package/dist/commands/publishSite.js +190 -131
  16. package/dist/commands/publishSite.js.map +1 -1
  17. package/dist/commands/switchaccount.js +36 -24
  18. package/dist/commands/switchaccount.js.map +1 -1
  19. package/dist/commands/update.js +8 -6
  20. package/dist/commands/update.js.map +1 -1
  21. package/dist/config/environments.js +17 -1
  22. package/dist/config/environments.js.map +1 -1
  23. package/dist/exit/exitCodes.js +55 -0
  24. package/dist/exit/exitCodes.js.map +1 -0
  25. package/dist/output/envelope.js +104 -0
  26. package/dist/output/envelope.js.map +1 -0
  27. package/dist/output/resultPrinter.js +70 -0
  28. package/dist/output/resultPrinter.js.map +1 -0
  29. package/dist/publish/responseClassifier.js +12 -12
  30. package/dist/publish/responseClassifier.js.map +1 -1
  31. package/dist/publish/siteClient.js +15 -5
  32. package/dist/publish/siteClient.js.map +1 -1
  33. package/dist/publish/siteConfig.js +21 -21
  34. package/dist/publish/siteConfig.js.map +1 -1
  35. package/dist/publish/siteZip.js +8 -8
  36. package/dist/publish/siteZip.js.map +1 -1
  37. package/dist/store/accountStore.js +2 -2
  38. package/dist/store/accountStore.js.map +1 -1
  39. package/dist/store/backends/encryptedFile.js +4 -1
  40. package/dist/store/backends/encryptedFile.js.map +1 -1
  41. package/dist/store/backends/osKeyring.js +4 -8
  42. package/dist/store/backends/osKeyring.js.map +1 -1
  43. package/dist/store/credentialStore.js +22 -0
  44. package/dist/store/credentialStore.js.map +1 -1
  45. package/dist/update/channelResolver.js +3 -3
  46. package/dist/update/channelResolver.js.map +1 -1
  47. package/dist/update/installSafety.js +12 -5
  48. package/dist/update/installSafety.js.map +1 -1
  49. package/dist/util/log.js +10 -1
  50. package/dist/util/log.js.map +1 -1
  51. package/dist/util/prompt.js +25 -0
  52. package/dist/util/prompt.js.map +1 -1
  53. package/package.json +1 -1
  54. package/dist/auth/refresh.js +0 -32
  55. package/dist/auth/refresh.js.map +0 -1
@@ -36,10 +36,10 @@ Object.defineProperty(exports, "__esModule", { value: true });
36
36
  exports.defaultPublishSiteDeps = void 0;
37
37
  exports.runPublishSite = runPublishSite;
38
38
  exports.registerPublishSiteCommand = registerPublishSiteCommand;
39
+ const crypto = __importStar(require("node:crypto"));
39
40
  const fs = __importStar(require("node:fs"));
40
41
  const path = __importStar(require("node:path"));
41
42
  const consoleClient_1 = require("../api/consoleClient");
42
- const refresh_1 = require("../auth/refresh");
43
43
  const siteClient_1 = require("../publish/siteClient");
44
44
  const orgResolve_1 = require("../publish/orgResolve");
45
45
  const responseClassifier_1 = require("../publish/responseClassifier");
@@ -48,23 +48,22 @@ const siteZip_1 = require("../publish/siteZip");
48
48
  const offlineVersion_1 = require("../publish/offlineVersion");
49
49
  const credentialStore_1 = require("../store/credentialStore");
50
50
  const accountStore_1 = require("../store/accountStore");
51
- const log_1 = require("../util/log");
51
+ const environments_1 = require("../config/environments");
52
+ const tokenAuth_1 = require("../auth/tokenAuth");
53
+ const resultPrinter_1 = require("../output/resultPrinter");
52
54
  const prompt_1 = require("../util/prompt");
53
55
  function resolveBackend(account) {
54
56
  return (0, credentialStore_1.backendForAccount)(account.backend, {
55
57
  passphraseProvider: account.backend === 'encrypted-file'
56
- ? () => (0, prompt_1.promptHiddenSync)(`Encryption passphrase for ${account.email}: `)
58
+ ? () => (0, prompt_1.promptHiddenSync)(`Encryption passphrase for ${account.email ?? account.accountKey}: `)
57
59
  : undefined,
58
60
  });
59
61
  }
60
62
  exports.defaultPublishSiteDeps = {
61
63
  getCurrentAccount: accountStore_1.getCurrentAccount,
62
- getAccessToken: (account) => resolveBackend(account).get(account.accountKey)?.accessToken ?? null,
63
- refreshToken: (account) => (0, refresh_1.refreshAccessToken)(new consoleClient_1.ConsoleClient(account.apiOrigin), resolveBackend(account), account.accountKey),
64
+ getStoredToken: (account) => resolveBackend(account).get(account.accountKey)?.token ?? null,
64
65
  markNeedsLogin: accountStore_1.markAccountNeedsLogin,
65
- fetchMe: (apiOrigin, accessToken) => new consoleClient_1.ConsoleClient(apiOrigin).me(accessToken),
66
- // The concrete client is upgraded in the publish layer; this cast preserves
67
- // the command's injectable boundary while those modules evolve independently.
66
+ fetchWhoami: (apiOrigin, token) => new consoleClient_1.ConsoleClient(apiOrigin).whoami(token),
68
67
  createSiteClient: (apiOrigin) => new siteClient_1.SiteClient(apiOrigin),
69
68
  readConfig: siteConfig_1.findConfig,
70
69
  updateConfig: siteConfig_1.updateConfig,
@@ -78,42 +77,45 @@ exports.defaultPublishSiteDeps = {
78
77
  }
79
78
  },
80
79
  };
81
- async function withAuth(account, deps, tokenRef, call) {
82
- let outcome = await call(tokenRef.value);
83
- if (outcome.kind !== 'auth_invalid')
84
- return { kind: 'outcome', outcome };
85
- const refreshed = await deps.refreshToken(account);
86
- if (refreshed.kind === 'needs_login') {
87
- deps.markNeedsLogin(account.accountKey);
88
- return { kind: 'needs_login' };
89
- }
90
- if (refreshed.kind === 'infra_error')
91
- return { kind: 'refresh_failed', message: refreshed.message };
92
- tokenRef.value = refreshed.secret.accessToken;
93
- outcome = await call(tokenRef.value);
80
+ async function withAuth(auth, deps, call) {
81
+ const outcome = await call(auth.token);
94
82
  if (outcome.kind === 'auth_invalid') {
95
- deps.markNeedsLogin(account.accountKey);
83
+ if (auth.accountKey)
84
+ deps.markNeedsLogin(auth.accountKey);
96
85
  return { kind: 'needs_login' };
97
86
  }
98
87
  return { kind: 'outcome', outcome };
99
88
  }
100
- function terminalMessage(result) {
101
- return result.kind === 'needs_login'
102
- ? '凭据已失效,请重新登录:supercli login'
103
- : `无法刷新凭据(网络/服务异常,本地凭据未改动):${result.message}`;
89
+ function terminalResult() {
90
+ return { ok: false, kind: 'needs_login', message: 'credentials are no longer valid — run `supercli login` again' };
91
+ }
92
+ /** Maps an outcome kind (Site or Client) to its failure classification kind. */
93
+ function failureKind(kind) {
94
+ switch (kind) {
95
+ case 'forbidden':
96
+ return 'forbidden';
97
+ case 'rate_limited':
98
+ return 'rate_limited';
99
+ case 'infra_error':
100
+ return 'infra_error';
101
+ case 'auth_invalid':
102
+ return 'auth_invalid';
103
+ default:
104
+ return 'business_error';
105
+ }
104
106
  }
105
107
  function nonSuccessMessage(outcome, context) {
106
108
  switch (outcome.kind) {
107
109
  case 'business_error':
108
110
  return (0, responseClassifier_1.describeSiteError)(outcome.code, outcome.message);
109
111
  case 'forbidden':
110
- return `${outcome.message} — 请核对 --org 或目标 org 的 admin 权限`;
112
+ return `${outcome.message} — check --org, or your admin permission on the target org`;
111
113
  case 'rate_limited':
112
- return `${outcome.message} — 请求过频,请稍后重试`;
114
+ return `${outcome.message} — too many requests; retry later`;
113
115
  case 'infra_error':
114
- return `${context}失败:${outcome.message}`;
116
+ return `${context} failed: ${outcome.message}`;
115
117
  default:
116
- return `${context}失败`;
118
+ return `${context} failed`;
117
119
  }
118
120
  }
119
121
  function valueFromOutcome(outcome) {
@@ -142,7 +144,7 @@ function isSiteForTarget(detail, spid, slug) {
142
144
  Array.isArray(detail.environments));
143
145
  }
144
146
  function isTerminal(value) {
145
- return Boolean(value && typeof value === 'object' && 'kind' in value && (value.kind === 'needs_login' || value.kind === 'refresh_failed'));
147
+ return Boolean(value && typeof value === 'object' && value.kind === 'needs_login');
146
148
  }
147
149
  function listContainsEnvironment(value, env) {
148
150
  if (!Array.isArray(value))
@@ -262,8 +264,8 @@ function reissueCommand(dir, opts, identity) {
262
264
  * `./super_build.sh --build` 过不了的配置,等于把人送进另一个死循环。
263
265
  */
264
266
  function createConfigStep(step, configPath, spid, carryHint) {
265
- const carry = carryHint ?? '`supercli create-app` 生成的工程已自带该文件';
266
- return `${step}) 在 ${quotePath(configPath)} 写入以下内容(${carry}):\n${(0, siteConfig_1.configTemplate)(spid)}`;
267
+ const carry = carryHint ?? 'a project generated by `supercli create-app` already ships this file';
268
+ return `${step}) write the following into ${quotePath(configPath)} (${carry}):\n${(0, siteConfig_1.configTemplate)(spid)}`;
267
269
  }
268
270
  /**
269
271
  * 迁移提示的两条硬规则(两个旧文件共用):
@@ -276,17 +278,17 @@ function createConfigStep(step, configPath, spid, carryHint) {
276
278
  function legacyMigrationMessage(args) {
277
279
  const legacyName = path.basename(args.legacyPath);
278
280
  const lines = [
279
- `检测到已退役的 ${legacyName}(${args.legacyPath}),已保留原文件,未发布任何内容。`,
281
+ `found the retired ${legacyName} (${args.legacyPath}) — the file is left untouched and nothing was published.`,
280
282
  args.headline,
281
283
  ];
282
284
  if (args.existingConfigPath) {
283
- lines.push(`你的 ${quotePath(args.existingConfigPath)} 已就位(schemaVersion ${siteConfig_1.SCHEMA_VERSION}),发布绑定以它为准,无需再写新配置。请按顺序执行:`, `1) 删除旧文件:rm ${quotePath(args.legacyPath)}`, `2) 重新执行:${args.rerun}`);
285
+ lines.push(`your ${quotePath(args.existingConfigPath)} is already in place (schemaVersion ${siteConfig_1.SCHEMA_VERSION}) and publish bindings come from it — there is no new config to write. run these in order:`, `1) delete the retired file: rm ${quotePath(args.legacyPath)}`, `2) re-run: ${args.rerun}`);
284
286
  return lines.join('\n');
285
287
  }
286
- lines.push('请按顺序执行(先写新文件、再删旧文件:旧文件是字段来源,删早了就没得抄了):', createConfigStep(1, args.newConfigPath, args.spid, args.carryHint));
288
+ lines.push('run these in order — write the new file first, delete the old one after: the old file is where these values come from, deleting it early leaves nothing to copy:', createConfigStep(1, args.newConfigPath, args.spid, args.carryHint));
287
289
  if (args.newConfigHint)
288
- lines.push(` (${args.newConfigHint})`);
289
- lines.push(`2) 删除旧文件:rm ${quotePath(args.legacyPath)}`, `3) 重新执行:${args.rerun}`);
290
+ lines.push(` (${args.newConfigHint})`);
291
+ lines.push(`2) delete the retired file: rm ${quotePath(args.legacyPath)}`, `3) re-run: ${args.rerun}`);
290
292
  return lines.join('\n');
291
293
  }
292
294
  /** 发布目录里的旧站点绑定:补齐配置 + 删文件 + 原样重跑,三步一次说完。 */
@@ -296,13 +298,13 @@ function legacySiteYmlMessage(legacyPath, existingConfigPath, spid, rerun) {
296
298
  existingConfigPath,
297
299
  spid,
298
300
  rerun,
299
- headline: `站点绑定已迁移到仓库根的 ${siteConfig_1.CONFIG_FILENAME}(标准 JSON,schemaVersion: 2)。`,
300
- newConfigPath: path.join('<仓库根>', siteConfig_1.CONFIG_FILENAME),
301
- newConfigHint: '发布目录是构建产物,配置放仓库根即可,命令会从发布目录向上查找',
301
+ headline: `site bindings now live in ${siteConfig_1.CONFIG_FILENAME} at the repo root (plain JSON, schemaVersion: 2).`,
302
+ newConfigPath: path.join('<repo-root>', siteConfig_1.CONFIG_FILENAME),
303
+ newConfigHint: 'the publish dir is build output — keep the config at the repo root; the command searches upwards from the publish dir',
302
304
  // super-site.yml 只装站点绑定,从来没有 android/ios/web/version/sdk 这些键 ——
303
305
  // 让人从那里「抄」不存在的字段是把人往沟里带。
304
- carryHint: `把 ${path.basename(legacyPath)} 里的 project.org_id 抄成 orgId、` +
305
- 'site.slug/site.name/environment 抄成 sites[] 的一条;App 侧字段按你的工程实际情况填',
306
+ carryHint: `copy project.org_id from ${path.basename(legacyPath)} into orgId, and ` +
307
+ 'site.slug/site.name/environment into one sites[] entry; fill the App-side fields from your own project',
306
308
  });
307
309
  }
308
310
  /** 仓库根的旧 App 配置:同样 fail-closed,绝不把 YAML 方言「尽力解释」成发布目标。 */
@@ -312,40 +314,56 @@ function legacyAppYamlMessage(legacyPath, existingConfigPath, spid, rerun) {
312
314
  existingConfigPath,
313
315
  spid,
314
316
  rerun,
315
- headline: `SuperSDK 项目配置已改为同目录的 ${siteConfig_1.CONFIG_FILENAME}(标准 JSON,不支持注释)。`,
317
+ headline: `the SuperSDK project config is now ${siteConfig_1.CONFIG_FILENAME} in the same directory (plain JSON, no comments).`,
316
318
  newConfigPath: path.join(path.dirname(legacyPath), siteConfig_1.CONFIG_FILENAME),
317
319
  // 旧的 supersdk.yaml 确实装着这些 App 字段,值得逐个搬。
318
- carryHint: `把 ${path.basename(legacyPath)} 里已有的 name/environment/android/ios/web/version/sdk ` +
319
- '值抄进对应字段,其余保留占位即可',
320
+ carryHint: `copy the name/environment/android/ios/web/version/sdk values you already have in ` +
321
+ `${path.basename(legacyPath)} into the matching fields; leave the rest as placeholders`,
320
322
  });
321
323
  }
322
324
  function absentConfigMessage(dir, read, spid, rerun) {
323
325
  if (read.explicit) {
324
- return `--config 指定的文件不存在:${read.searched[0] ?? ''};不会退回向上查找,也不会猜测发布目标`;
326
+ return `the file given to --config does not exist: ${read.searched[0] ?? ''} — no fallback to the upward search, and no guessing of the publish target`;
325
327
  }
326
328
  const from = read.searched[0] ?? path.resolve(dir);
327
329
  const upTo = read.searched[read.searched.length - 1] ?? from;
328
330
  return [
329
- `未找到 ${siteConfig_1.CONFIG_FILENAME}:已从 ${quotePath(from)} 向上查找至 ${quotePath(upTo)}(到仓库根/家目录/文件系统根为止),未发布任何内容。`,
330
- '发布绑定只从配置文件读取,不会猜测项目、站点或环境。请按顺序执行:',
331
+ `no ${siteConfig_1.CONFIG_FILENAME} found: searched upwards from ${quotePath(from)} to ${quotePath(upTo)} (stopping at the repo root / home directory / filesystem root); nothing was published.`,
332
+ 'publish bindings are read from the config file only — the project, site and environment are never guessed. run these in order:',
331
333
  createConfigStep(1, path.join(upTo, siteConfig_1.CONFIG_FILENAME), spid),
332
- `2) 重新执行:${rerun}`,
333
- ` 或用逃生舱直接指定已有配置:${rerun} --config <path>/${siteConfig_1.CONFIG_FILENAME}`,
334
+ `2) re-run: ${rerun}`,
335
+ ` or point at an existing config directly: ${rerun} --config <path>/${siteConfig_1.CONFIG_FILENAME}`,
334
336
  ].join('\n');
335
337
  }
336
- async function oneEnvironmentRecheck(account, deps, tokenRef, client, context, spid, env) {
337
- const recheck = await withAuth(account, deps, tokenRef, (token) => client.listEnvironments({ ...context, accessToken: token }, spid));
338
+ async function oneEnvironmentRecheck(auth, deps, client, context, spid, env) {
339
+ const recheck = await withAuth(auth, deps, (token) => client.listEnvironments({ ...context, accessToken: token }, spid));
338
340
  if (recheck.kind !== 'outcome')
339
341
  return recheck;
340
342
  return (recheck.outcome.kind === 'success' || recheck.outcome.kind === 'soft_success') && listContainsEnvironment(valueFromOutcome(recheck.outcome), env);
341
343
  }
342
- async function oneSiteRecheck(account, deps, tokenRef, client, context, spid, slug) {
343
- const recheck = await withAuth(account, deps, tokenRef, (token) => client.getSite({ ...context, accessToken: token }, spid, slug));
344
+ async function oneSiteRecheck(auth, deps, client, context, spid, slug) {
345
+ const recheck = await withAuth(auth, deps, (token) => client.getSite({ ...context, accessToken: token }, spid, slug));
344
346
  if (recheck.kind !== 'outcome')
345
347
  return recheck;
346
348
  const detail = siteFrom(valueFromOutcome(recheck.outcome));
347
349
  return isSiteForTarget(detail, spid, slug) ? detail : undefined;
348
350
  }
351
+ /** Resolves the effective token + apiOrigin (env token wins; TC-020/050 clean machine). */
352
+ function resolveAuth(deps) {
353
+ const envToken = (0, tokenAuth_1.resolveEnvToken)();
354
+ if (envToken) {
355
+ return { token: envToken, apiOrigin: (0, environments_1.resolveApiOrigin)().apiOrigin };
356
+ }
357
+ const account = deps.getCurrentAccount();
358
+ if (!account)
359
+ return { ok: false, kind: 'needs_login', message: 'no account is logged in — run `supercli login` first' };
360
+ const stored = deps.getStoredToken(account);
361
+ if (!stored) {
362
+ deps.markNeedsLogin(account.accountKey);
363
+ return { ok: false, kind: 'needs_login', message: 'no valid credential found locally — run `supercli login` again' };
364
+ }
365
+ return { token: stored, apiOrigin: account.apiOrigin, accountKey: account.accountKey };
366
+ }
349
367
  async function runPublishSite(dir, opts, deps = exports.defaultPublishSiteDeps) {
350
368
  // 本地参数校验与目标冲突比对一律先于账号查找、HTTP、配置写入与打包。
351
369
  const explicit = {
@@ -360,20 +378,20 @@ async function runPublishSite(dir, opts, deps = exports.defaultPublishSiteDeps)
360
378
  // 来源」,而是与命令行逐项比对的一致性护栏 —— 目的是让「cd 错目录」这类事故在本地就
361
379
  // 失败,而不是把内容发到另一个站点去。
362
380
  if (!explicit.spid || !explicit.slug || !explicit.env) {
363
- return { ok: false, message: '--spid、--slug、--env 均为必填;不会猜测项目、站点或环境' };
381
+ return { ok: false, message: '--spid, --slug and --env are all required — the project, site and environment are never guessed' };
364
382
  }
365
383
  const spid = explicit.spid;
366
384
  const slug = explicit.slug;
367
385
  const env = explicit.env;
368
386
  if (!isValidSpid(spid))
369
- return { ok: false, message: '--spid 非法:必须为 8 位小写字母或数字' };
387
+ return { ok: false, message: 'invalid --spid: must be 8 lowercase letters or digits' };
370
388
  if (!isValidSlug(slug))
371
- return { ok: false, message: '--slug 非法:必须为 1-32 位小写字母或数字,且不能为 stg' };
389
+ return { ok: false, message: 'invalid --slug: must be 1-32 lowercase letters or digits, and must not be stg' };
372
390
  if (!isValidEnvironment(env))
373
- return { ok: false, message: '--env 非法:必须为 1-10 位小写字母或数字' };
391
+ return { ok: false, message: 'invalid --env: must be 1-10 lowercase letters or digits' };
374
392
  const parsedVersion = (0, offlineVersion_1.parseOfflineVersion)(trimFlag(opts.version));
375
393
  if (!parsedVersion) {
376
- return { ok: false, message: '--version 必填,且必须是最多 64 bytes 的 x.y.z(major ≤ 2147483647,minor/patch ≤ 99;前导零按数值比较)' };
394
+ return { ok: false, message: '--version is required and must be an x.y.z of at most 64 bytes (major <= 2147483647, minor/patch <= 99; leading zeros compare numerically)' };
377
395
  }
378
396
  const version = parsedVersion.raw;
379
397
  // 🔴 发布目录的存在性/类型必须在**任何网络请求之前**判掉。
@@ -382,10 +400,10 @@ async function runPublishSite(dir, opts, deps = exports.defaultPublishSiteDeps)
382
400
  // 留下一个谁也没打算要的空站点。目录检查是 statSync 一次的事,没有理由放在后面。
383
401
  const dirCheck = deps.statDir(dir);
384
402
  if (dirCheck === 'missing') {
385
- return { ok: false, message: `发布目录不存在:${path.resolve(dir)};未发布任何内容` };
403
+ return { ok: false, message: `publish dir does not exist: ${path.resolve(dir)} — nothing was published` };
386
404
  }
387
405
  if (dirCheck === 'not-a-directory') {
388
- return { ok: false, message: `发布目录不是一个目录:${path.resolve(dir)};publish-site 接受的是目录,不是单个文件` };
406
+ return { ok: false, message: `publish dir is not a directory: ${path.resolve(dir)} — publish-site takes a directory, not a single file` };
389
407
  }
390
408
  // 参数先于读盘校验,是为了让迁移/创建提示里能回显用户真正敲过的那条命令。
391
409
  const read = normalizeConfig(deps.readConfig(dir, explicit.config));
@@ -395,17 +413,17 @@ async function runPublishSite(dir, opts, deps = exports.defaultPublishSiteDeps)
395
413
  if (read.kind === 'legacy-app-yaml')
396
414
  return { ok: false, message: legacyAppYamlMessage(read.path, read.existingConfigPath, spid, rerun()) };
397
415
  if (read.kind === 'invalid') {
398
- const where = read.path ? `(${read.path})` : '';
399
- return { ok: false, message: `${siteConfig_1.CONFIG_FILENAME} 非法或不完整${where}:${read.reason ?? '结构不符合 schemaVersion 2'};已保留原文件,请修正后重试` };
416
+ const where = read.path ? ` (${read.path})` : '';
417
+ return { ok: false, message: `${siteConfig_1.CONFIG_FILENAME} is invalid or incomplete${where}: ${read.reason ?? 'the shape does not match schemaVersion 2'} — the file is left untouched; fix it and retry` };
400
418
  }
401
419
  if (read.kind === 'absent')
402
420
  return { ok: false, message: absentConfigMessage(dir, read, spid, rerun()) };
403
421
  const config = read.config;
404
422
  if (config.spid !== spid) {
405
- return { ok: false, message: `--spid ${spid} 与 ${config.path} 记录的 spid ${config.spid} 冲突;不会静默改绑定或覆盖发布目标` };
423
+ return { ok: false, message: `--spid ${spid} conflicts with the spid ${config.spid} recorded in ${config.path} — the binding is never silently rebound, nor the publish target overridden` };
406
424
  }
407
425
  if (explicit.org && config.orgId && explicit.org !== config.orgId) {
408
- return { ok: false, message: `--org ${explicit.org} 与 ${config.path} 记录的 orgId ${config.orgId} 冲突;不会向其他组织发布` };
426
+ return { ok: false, message: `--org ${explicit.org} conflicts with the orgId ${config.orgId} recorded in ${config.path} — refusing to publish to a different org` };
409
427
  }
410
428
  // 🔴 顶层 environment 是 App 自身的 SDK 运行环境,与 sites[].env(站点发到项目的哪个
411
429
  // 环境)是正交的两件事,这里**刻意不做相等断言** —— 用 staging 配置构建却发 prod 站点
@@ -416,59 +434,92 @@ async function runPublishSite(dir, opts, deps = exports.defaultPublishSiteDeps)
416
434
  const siteName = (bound?.name ?? trimFlag(opts.name) ?? slug).trim();
417
435
  const siteNameLength = Array.from(siteName).length;
418
436
  if (siteNameLength < 1 || siteNameLength > 50)
419
- return { ok: false, message: '--name 非法:必须为 1-50 个字符' };
420
- const account = deps.getCurrentAccount();
421
- if (!account)
422
- return { ok: false, message: '当前没有登录账号,请先运行:supercli login' };
423
- const accessToken = deps.getAccessToken(account);
424
- if (!accessToken) {
425
- deps.markNeedsLogin(account.accountKey);
426
- return { ok: false, message: '本地未找到有效凭据,请重新登录:supercli login' };
427
- }
428
- const tokenRef = { value: accessToken };
437
+ return { ok: false, message: 'invalid --name: must be 1-50 characters' };
438
+ // token-wins 鉴权:SUPERCLI_TOKEN 优先于落盘账号;401 = 终态 needs-login,不再 refresh 重试。
439
+ const auth = resolveAuth(deps);
440
+ if ('ok' in auth)
441
+ return auth; // resolveAuth returned a PublishSiteResult failure
442
+ // Resolve the org: explicit --org, else the token's bound org via whoami.
429
443
  let orgId;
430
444
  if (explicit.org) {
431
445
  const resolution = (0, orgResolve_1.resolveOrgId)([], explicit.org);
432
446
  if (resolution.kind !== 'resolved')
433
- return { ok: false, message: '--org 必须为正整数' };
447
+ return { ok: false, message: '--org must be a positive integer' };
434
448
  orgId = resolution.orgId;
435
449
  }
436
450
  else {
437
- const me = await withAuth(account, deps, tokenRef, (token) => deps.fetchMe(account.apiOrigin, token));
438
- if (me.kind !== 'outcome')
439
- return { ok: false, message: terminalMessage(me) };
440
- if (me.outcome.kind !== 'success')
441
- return { ok: false, message: `无法获取当前用户组织:${'message' in me.outcome ? me.outcome.message : me.outcome.kind}` };
442
- const resolution = (0, orgResolve_1.resolveOrgId)(me.outcome.data.orgs ?? undefined);
443
- if (resolution.kind === 'none')
444
- return { ok: false, message: '当前账号未归属任何 org,无法发布' };
445
- if (resolution.kind === 'ambiguous')
446
- return { ok: false, message: `当前账号归属多个 org(${resolution.orgIds.join(', ')}),请通过 --org <id> 指定` };
447
- if (resolution.kind !== 'resolved')
448
- return { ok: false, message: '无法解析当前 org' };
449
- orgId = resolution.orgId;
451
+ // token-scoped identity: the token's bound org comes from /api/open/whoami (org_id).
452
+ const who = await withAuth(auth, deps, (token) => deps.fetchWhoami(auth.apiOrigin, token));
453
+ if (who.kind !== 'outcome')
454
+ return terminalResult();
455
+ if (who.outcome.kind !== 'success') {
456
+ return {
457
+ ok: false,
458
+ kind: failureKind(who.outcome.kind),
459
+ message: `cannot resolve the org bound to the current token: ${'message' in who.outcome ? who.outcome.message : who.outcome.kind}`,
460
+ };
461
+ }
462
+ orgId = String(who.outcome.data.org_id ?? '');
463
+ if (!orgId || orgId === '0')
464
+ return { ok: false, message: 'the current token is not bound to any org — nothing to publish to' };
450
465
  }
451
466
  if (config.orgId && config.orgId !== orgId) {
452
- return { ok: false, message: `当前解析的 org ${orgId} 与 ${config.path} 记录的 orgId ${config.orgId} 冲突;不会向其他组织发布` };
467
+ return { ok: false, message: `the resolved org ${orgId} conflicts with the orgId ${config.orgId} recorded in ${config.path} — refusing to publish to a different org` };
468
+ }
469
+ const client = deps.createSiteClient(auth.apiOrigin);
470
+ const context = { accessToken: auth.token, orgId };
471
+ const idempotencyKey = trimFlag(opts.idempotencyKey) ?? crypto.randomUUID();
472
+ // ---- dry-run (AC-7): read-only checks + server validation, create nothing ----
473
+ if (opts.dryRun) {
474
+ const lookedUp = await withAuth(auth, deps, (token) => client.getSite({ ...context, accessToken: token }, spid, slug));
475
+ if (lookedUp.kind !== 'outcome')
476
+ return terminalResult();
477
+ const existing = siteFrom(valueFromOutcome(lookedUp.outcome));
478
+ const siteExists = isSiteForTarget(existing, spid, slug);
479
+ const expectedSiteId = siteExists ? existing.id : 0;
480
+ let zip;
481
+ try {
482
+ zip = await deps.buildZip(dir);
483
+ }
484
+ catch (error) {
485
+ const message = error instanceof siteZip_1.ZipBuildError ? error.message : error.message;
486
+ return { ok: false, message: `packaging failed: ${message}` };
487
+ }
488
+ const dryDeploy = await withAuth(auth, deps, (token) => client.deploy({ ...context, accessToken: token }, spid, slug, env, {
489
+ zip: zip.buffer,
490
+ version,
491
+ description: opts.description,
492
+ expectedSiteId,
493
+ idempotencyKey,
494
+ dryRun: true,
495
+ }));
496
+ if (dryDeploy.kind !== 'outcome')
497
+ return terminalResult();
498
+ if (dryDeploy.outcome.kind !== 'success' && dryDeploy.outcome.kind !== 'soft_success') {
499
+ return { ok: false, kind: failureKind(dryDeploy.outcome.kind), message: nonSuccessMessage(dryDeploy.outcome, 'deploy validation') };
500
+ }
501
+ return {
502
+ ok: true,
503
+ message: `dry-run validated: ${spid}/${slug}/${env} version=${version} (no deployment created)`,
504
+ result: { dryRun: true, spid, slug, env, version, siteExists, plan: valueFromOutcome(dryDeploy.outcome) },
505
+ };
453
506
  }
454
- const client = deps.createSiteClient(account.apiOrigin);
455
- const context = { accessToken: tokenRef.value, orgId };
456
507
  // env-before-site: unavailable environments never leave a new site behind.
457
- const listed = await withAuth(account, deps, tokenRef, (token) => client.listEnvironments({ ...context, accessToken: token }, spid));
508
+ const listed = await withAuth(auth, deps, (token) => client.listEnvironments({ ...context, accessToken: token }, spid));
458
509
  if (listed.kind !== 'outcome')
459
- return { ok: false, message: terminalMessage(listed) };
510
+ return terminalResult();
460
511
  let environmentAvailable = (listed.outcome.kind === 'success' || listed.outcome.kind === 'soft_success') && listContainsEnvironment(valueFromOutcome(listed.outcome), env);
461
512
  if (!environmentAvailable) {
462
513
  if (listed.outcome.kind !== 'success' && listed.outcome.kind !== 'soft_success') {
463
- return { ok: false, message: nonSuccessMessage(listed.outcome, '查询项目环境') };
514
+ return { ok: false, kind: failureKind(listed.outcome.kind), message: nonSuccessMessage(listed.outcome, 'listing project environments') };
464
515
  }
465
516
  if (env === 'prod')
466
- return { ok: false, message: '项目 prod 环境不存在,请前往控制台检查项目状态' };
517
+ return { ok: false, message: 'the project has no prod environment — check the project state in the Console' };
467
518
  if (!opts.createEnvironment)
468
- return { ok: false, message: `项目环境 "${env}" 不存在;如确认要创建共享环境,请显式传入 --create-environment` };
469
- const created = await withAuth(account, deps, tokenRef, (token) => client.createEnvironment({ ...context, accessToken: token }, spid, { name: env }));
519
+ return { ok: false, message: `project environment "${env}" does not exist — pass --create-environment explicitly to create this shared environment` };
520
+ const created = await withAuth(auth, deps, (token) => client.createEnvironment({ ...context, accessToken: token }, spid, { name: env }));
470
521
  if (created.kind !== 'outcome')
471
- return { ok: false, message: terminalMessage(created) };
522
+ return terminalResult();
472
523
  if (created.outcome.kind === 'success' && asRecord(created.outcome.data)?.name === env) {
473
524
  environmentAvailable = true;
474
525
  }
@@ -476,29 +527,29 @@ async function runPublishSite(dir, opts, deps = exports.defaultPublishSiteDeps)
476
527
  created.outcome.kind === 'soft_success' ||
477
528
  created.outcome.kind === 'infra_error' ||
478
529
  (created.outcome.kind === 'business_error' && created.outcome.code === 'ENV_NAME_DUPLICATE')) {
479
- const rechecked = await oneEnvironmentRecheck(account, deps, tokenRef, client, context, spid, env);
530
+ const rechecked = await oneEnvironmentRecheck(auth, deps, client, context, spid, env);
480
531
  if (typeof rechecked !== 'boolean')
481
- return { ok: false, message: terminalMessage(rechecked) };
532
+ return terminalResult();
482
533
  environmentAvailable = rechecked;
483
534
  }
484
535
  else {
485
- return { ok: false, message: nonSuccessMessage(created.outcome, '创建项目环境') };
536
+ return { ok: false, kind: failureKind(created.outcome.kind), message: nonSuccessMessage(created.outcome, 'creating the project environment') };
486
537
  }
487
538
  if (!environmentAvailable)
488
- return { ok: false, message: `无法确认项目环境 "${env}" 已创建;不会重放写请求,请稍后在控制台核对` };
539
+ return { ok: false, message: `cannot confirm project environment "${env}" was created — the write is never replayed; check the Console shortly` };
489
540
  }
490
541
  let detail;
491
- const lookedUp = await withAuth(account, deps, tokenRef, (token) => client.getSite({ ...context, accessToken: token }, spid, slug));
542
+ const lookedUp = await withAuth(auth, deps, (token) => client.getSite({ ...context, accessToken: token }, spid, slug));
492
543
  if (lookedUp.kind !== 'outcome')
493
- return { ok: false, message: terminalMessage(lookedUp) };
544
+ return terminalResult();
494
545
  const existing = siteFrom(valueFromOutcome(lookedUp.outcome));
495
546
  if (isSiteForTarget(existing, spid, slug)) {
496
547
  detail = existing;
497
548
  }
498
549
  else if (lookedUp.outcome.kind === 'business_error' && lookedUp.outcome.code === 'NOT_FOUND') {
499
- const created = await withAuth(account, deps, tokenRef, (token) => client.createSite({ ...context, accessToken: token }, spid, { name: siteName, slug }));
550
+ const created = await withAuth(auth, deps, (token) => client.createSite({ ...context, accessToken: token }, spid, { name: siteName, slug }));
500
551
  if (created.kind !== 'outcome')
501
- return { ok: false, message: terminalMessage(created) };
552
+ return terminalResult();
502
553
  const createdDetail = siteFrom(valueFromOutcome(created.outcome));
503
554
  if (created.outcome.kind === 'success' && isSiteForTarget(createdDetail, spid, slug)) {
504
555
  detail = createdDetail;
@@ -507,19 +558,19 @@ async function runPublishSite(dir, opts, deps = exports.defaultPublishSiteDeps)
507
558
  created.outcome.kind === 'infra_error' ||
508
559
  (created.outcome.kind === 'business_error' && created.outcome.code === 'SITE_SLUG_DUPLICATE') ||
509
560
  (created.outcome.kind === 'success' && !isSiteForTarget(createdDetail, spid, slug))) {
510
- const rechecked = await oneSiteRecheck(account, deps, tokenRef, client, context, spid, slug);
561
+ const rechecked = await oneSiteRecheck(auth, deps, client, context, spid, slug);
511
562
  if (isTerminal(rechecked))
512
- return { ok: false, message: terminalMessage(rechecked) };
563
+ return terminalResult();
513
564
  detail = rechecked;
514
565
  }
515
566
  else {
516
- return { ok: false, message: nonSuccessMessage(created.outcome, '创建项目站点') };
567
+ return { ok: false, kind: failureKind(created.outcome.kind), message: nonSuccessMessage(created.outcome, 'creating the project site') };
517
568
  }
518
569
  if (!detail)
519
- return { ok: false, message: '无法确认项目站点已创建;不会重放写请求、写绑定或发布,请稍后核对' };
570
+ return { ok: false, message: 'cannot confirm the project site was created — no write is replayed, no binding recorded and nothing published; check again shortly' };
520
571
  }
521
572
  else {
522
- return { ok: false, message: nonSuccessMessage(lookedUp.outcome, '查询项目站点') };
573
+ return { ok: false, kind: failureKind(lookedUp.outcome.kind), message: nonSuccessMessage(lookedUp.outcome, 'looking up the project site') };
523
574
  }
524
575
  // 🔴 打包必须排在写配置之前:它是纯本地校验(根级 index.html、体积/条目上限、符号链接
525
576
  // 等),零网络成本。反过来的顺序会留下一个永远无人纠正的错误记录 —— 首次对一个没有
@@ -531,7 +582,7 @@ async function runPublishSite(dir, opts, deps = exports.defaultPublishSiteDeps)
531
582
  }
532
583
  catch (error) {
533
584
  const message = error instanceof siteZip_1.ZipBuildError ? error.message : error.message;
534
- return { ok: false, message: `打包失败:${message}` };
585
+ return { ok: false, message: `packaging failed: ${message}` };
535
586
  }
536
587
  // 回填只发生在服务端已确认站点身份、且本地打包已经通过之后,且只增不改:sites[] 里没有
537
588
  // 对应条目才 append,orgId 只在缺失时补写。任何一处与既有记录冲突,siteConfig 会抛错而
@@ -545,30 +596,34 @@ async function runPublishSite(dir, opts, deps = exports.defaultPublishSiteDeps)
545
596
  });
546
597
  }
547
598
  catch (error) {
548
- return { ok: false, message: `写入 ${siteConfig_1.CONFIG_FILENAME} 失败,未发布:${error.message}` };
599
+ return { ok: false, message: `writing ${siteConfig_1.CONFIG_FILENAME} failed, nothing published: ${error.message}` };
549
600
  }
550
601
  }
551
- const deployed = await withAuth(account, deps, tokenRef, (token) => client.deploy({ ...context, accessToken: token }, spid, slug, env, {
602
+ const deployed = await withAuth(auth, deps, (token) => client.deploy({ ...context, accessToken: token }, spid, slug, env, {
552
603
  zip: zip.buffer,
553
604
  version,
554
605
  description: opts.description,
555
606
  expectedSiteId: detail.id,
607
+ idempotencyKey,
556
608
  }));
557
609
  if (deployed.kind !== 'outcome')
558
- return { ok: false, message: terminalMessage(deployed) };
610
+ return terminalResult();
559
611
  if (deployed.outcome.kind !== 'success' && deployed.outcome.kind !== 'soft_success') {
560
- return { ok: false, message: nonSuccessMessage(deployed.outcome, '发布') };
612
+ return { ok: false, kind: failureKind(deployed.outcome.kind), message: nonSuccessMessage(deployed.outcome, 'deploy') };
561
613
  }
562
614
  const pending = deployed.outcome.kind === 'soft_success';
563
- // 域名的 zone 是平台部署配置(生产 supersdk.site / staging supersdk.top),CLI 不掌握也不该
564
- // 猜——只用服务端返回的 domain;两处都没有就让用户去 Console 看,绝不编造一个不存在的域名。
565
615
  const domain = domainFromDeploy(valueFromOutcome(deployed.outcome)) ?? domainFromSite(detail, env);
566
- const pendingNote = pending ? '(已受理、同步中,稍后生效)' : '';
616
+ const pendingNote = pending ? ' (accepted; pointer sync in progress, live shortly)' : '';
567
617
  const domainNote = domain
568
- ? `,可访问域名:https://${domain.replace(/^https?:\/\//, '')}`
569
- : ',可访问域名请在 Console 的 Hosting 页查看';
570
- const configNote = wroteConfig ? `,已更新 ${config.path}${mustAppendSite ? ' 的 sites[]' : ' 的 orgId'}` : '';
571
- return { ok: true, message: `发布成功${configNote}${domainNote}${pendingNote}` };
618
+ ? `; reachable at https://${domain.replace(/^https?:\/\//, '')}`
619
+ : '; find the public domain on the Hosting page in the Console';
620
+ const configNote = wroteConfig ? `; updated ${mustAppendSite ? 'sites[]' : 'orgId'} in ${config.path}` : '';
621
+ return {
622
+ ok: true,
623
+ soft: pending,
624
+ message: `published${configNote}${domainNote}${pendingNote}`,
625
+ result: { dryRun: false, spid, slug, env, version, pending, domain, deploy: valueFromOutcome(deployed.outcome) },
626
+ };
572
627
  }
573
628
  function registerPublishSiteCommand(program) {
574
629
  program
@@ -583,14 +638,18 @@ function registerPublishSiteCommand(program) {
583
638
  .option('--create-environment', 'explicitly authorize creating a missing non-prod project environment')
584
639
  .requiredOption('--version <version>', 'required offline package version: x.y.z (major <= 2147483647; minor/patch <= 99)')
585
640
  .option('--description <description>', 'deploy description')
586
- .action(async (dir, options) => {
641
+ .option('--dry-run', 'validate locally + server-side without creating a deployment; print a plan')
642
+ .option('--idempotency-key <key>', 'client idempotency key; replaying the same key returns the first deploy')
643
+ .action(async (dir, options, cmd) => {
644
+ const mode = cmd.optsWithGlobals?.()?.output === 'json' ? 'json' : 'human';
645
+ const printer = new resultPrinter_1.ResultPrinter(mode);
587
646
  const result = await runPublishSite(dir, options);
588
- if (!result.ok) {
589
- log_1.log.error(result.message ?? 'publish-site failed');
590
- process.exitCode = 1;
591
- return;
647
+ if (result.ok) {
648
+ printer.success(result.result ?? {}, { soft: result.soft, humanMessage: result.message });
649
+ }
650
+ else {
651
+ printer.failure(result.kind ?? 'business_error', result.message ?? 'publish-site failed');
592
652
  }
593
- log_1.log.info(result.message ?? 'published');
594
653
  });
595
654
  }
596
655
  //# sourceMappingURL=publishSite.js.map