@supersdk/supercli 0.1.1-staging.2 → 0.1.1-staging.4

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 (34) hide show
  1. package/dist/commands/createApp.js +14 -58
  2. package/dist/commands/createApp.js.map +1 -1
  3. package/dist/commands/publishSite.js +286 -209
  4. package/dist/commands/publishSite.js.map +1 -1
  5. package/dist/createApp/copyTemplate.js +38 -53
  6. package/dist/createApp/copyTemplate.js.map +1 -1
  7. package/dist/publish/offlineVersion.js +33 -0
  8. package/dist/publish/offlineVersion.js.map +1 -0
  9. package/dist/publish/orgResolve.js +16 -17
  10. package/dist/publish/orgResolve.js.map +1 -1
  11. package/dist/publish/responseClassifier.js +17 -7
  12. package/dist/publish/responseClassifier.js.map +1 -1
  13. package/dist/publish/siteClient.js +19 -10
  14. package/dist/publish/siteClient.js.map +1 -1
  15. package/dist/publish/siteConfig.js +166 -124
  16. package/dist/publish/siteConfig.js.map +1 -1
  17. package/dist/template/README.md +11 -1
  18. package/dist/template/android/app/build.gradle.kts +6 -3
  19. package/dist/template/android/app/src/main/java/com/supersdk/simple/SimpleApplication.java +1 -1
  20. package/dist/template/android/gradle/supersdk-config-reader.gradle +2 -1
  21. package/dist/template/android/supersdk-default.config.json +3 -2
  22. package/dist/template/ios/MockSuperSDKPackage/Sources/SuperSDK/SuperSDK.swift +20 -4
  23. package/dist/template/ios/Sources/App/AppDelegate.swift +5 -1
  24. package/dist/template/ios/Sources/App/SimpleSDKBootstrap.swift +6 -2
  25. package/dist/template/ios/Sources/App/SimpleSDKProbe.swift +7 -4
  26. package/dist/template/ios/Tests/SimpleAppTests/SimpleSDKInitializationTests.swift +2 -1
  27. package/dist/template/scripts/build_ios.sh +13 -9
  28. package/dist/template/scripts/supersdk_template.py +15 -8
  29. package/dist/template/supersdk.yaml +3 -2
  30. package/dist/template/web/src/index.html +6 -2
  31. package/dist/template/web/src/js/app.js +6 -3
  32. package/dist/template/web/src/js/supersdk.js +229 -91
  33. package/dist/template/web/src/js/supersdk.provenance.json +3 -3
  34. package/package.json +1 -1
@@ -34,30 +34,21 @@ var __importStar = (this && this.__importStar) || (function () {
34
34
  })();
35
35
  Object.defineProperty(exports, "__esModule", { value: true });
36
36
  exports.defaultPublishSiteDeps = void 0;
37
- exports.isValidEnvName = isValidEnvName;
38
37
  exports.runPublishSite = runPublishSite;
39
38
  exports.registerPublishSiteCommand = registerPublishSiteCommand;
40
39
  const path = __importStar(require("node:path"));
41
40
  const consoleClient_1 = require("../api/consoleClient");
42
- const accountStore_1 = require("../store/accountStore");
43
- const credentialStore_1 = require("../store/credentialStore");
44
41
  const refresh_1 = require("../auth/refresh");
45
- const log_1 = require("../util/log");
46
- const prompt_1 = require("../util/prompt");
47
42
  const siteClient_1 = require("../publish/siteClient");
48
- const responseClassifier_1 = require("../publish/responseClassifier");
49
43
  const orgResolve_1 = require("../publish/orgResolve");
44
+ const responseClassifier_1 = require("../publish/responseClassifier");
50
45
  const siteConfig_1 = require("../publish/siteConfig");
51
46
  const siteZip_1 = require("../publish/siteZip");
52
- /**
53
- * Mirrors the backend `validate_environment_name` (service.rs): a non-empty name
54
- * of at most 10 characters, all ASCII lowercase letters or digits. Kept as a
55
- * local fail-fast so an invalid --env never reaches an irreversible create call.
56
- */
57
- const ENV_NAME_PATTERN = /^[a-z0-9]{1,10}$/;
58
- function isValidEnvName(env) {
59
- return ENV_NAME_PATTERN.test(env);
60
- }
47
+ const offlineVersion_1 = require("../publish/offlineVersion");
48
+ const credentialStore_1 = require("../store/credentialStore");
49
+ const accountStore_1 = require("../store/accountStore");
50
+ const log_1 = require("../util/log");
51
+ const prompt_1 = require("../util/prompt");
61
52
  function resolveBackend(account) {
62
53
  return (0, credentialStore_1.backendForAccount)(account.backend, {
63
54
  passphraseProvider: account.backend === 'encrypted-file'
@@ -66,30 +57,29 @@ function resolveBackend(account) {
66
57
  });
67
58
  }
68
59
  exports.defaultPublishSiteDeps = {
69
- getCurrentAccount: () => (0, accountStore_1.getCurrentAccount)(),
60
+ getCurrentAccount: accountStore_1.getCurrentAccount,
70
61
  getAccessToken: (account) => resolveBackend(account).get(account.accountKey)?.accessToken ?? null,
71
62
  refreshToken: (account) => (0, refresh_1.refreshAccessToken)(new consoleClient_1.ConsoleClient(account.apiOrigin), resolveBackend(account), account.accountKey),
72
- markNeedsLogin: (accountKey) => (0, accountStore_1.markAccountNeedsLogin)(accountKey),
63
+ markNeedsLogin: accountStore_1.markAccountNeedsLogin,
73
64
  fetchMe: (apiOrigin, accessToken) => new consoleClient_1.ConsoleClient(apiOrigin).me(accessToken),
65
+ // The concrete client is upgraded in the publish layer; this cast preserves
66
+ // the command's injectable boundary while those modules evolve independently.
74
67
  createSiteClient: (apiOrigin) => new siteClient_1.SiteClient(apiOrigin),
75
68
  readSiteConfig: siteConfig_1.readSiteConfig,
76
69
  writeSiteConfig: siteConfig_1.writeSiteConfig,
77
- buildZip: (dir) => (0, siteZip_1.buildSiteZip)(dir),
70
+ buildZip: siteZip_1.buildSiteZip,
78
71
  };
79
72
  async function withAuth(account, deps, tokenRef, call) {
80
73
  let outcome = await call(tokenRef.value);
81
74
  if (outcome.kind !== 'auth_invalid')
82
75
  return { kind: 'outcome', outcome };
83
- // 401 → refresh exactly once, then retry exactly once.
84
76
  const refreshed = await deps.refreshToken(account);
85
77
  if (refreshed.kind === 'needs_login') {
86
78
  deps.markNeedsLogin(account.accountKey);
87
79
  return { kind: 'needs_login' };
88
80
  }
89
- if (refreshed.kind === 'infra_error') {
90
- // Refresh itself failed on network/5xx — NOT a credential-invalid signal.
81
+ if (refreshed.kind === 'infra_error')
91
82
  return { kind: 'refresh_failed', message: refreshed.message };
92
- }
93
83
  tokenRef.value = refreshed.secret.accessToken;
94
84
  outcome = await call(tokenRef.value);
95
85
  if (outcome.kind === 'auth_invalid') {
@@ -98,17 +88,17 @@ async function withAuth(account, deps, tokenRef, call) {
98
88
  }
99
89
  return { kind: 'outcome', outcome };
100
90
  }
101
- function terminalMessage(t) {
102
- if (t.kind === 'needs_login')
103
- return '凭据已失效,请重新登录:supercli login';
104
- return `无法刷新凭据(网络/服务异常,本地凭据未改动):${t.message}`;
91
+ function terminalMessage(result) {
92
+ return result.kind === 'needs_login'
93
+ ? '凭据已失效,请重新登录:supercli login'
94
+ : `无法刷新凭据(网络/服务异常,本地凭据未改动):${result.message}`;
105
95
  }
106
96
  function nonSuccessMessage(outcome, context) {
107
97
  switch (outcome.kind) {
108
98
  case 'business_error':
109
99
  return (0, responseClassifier_1.describeSiteError)(outcome.code, outcome.message);
110
100
  case 'forbidden':
111
- return `${outcome.message} — 需要目标 org 的 admin 权限`;
101
+ return `${outcome.message} — 请核对 --org 或目标 org 的 admin 权限`;
112
102
  case 'rate_limited':
113
103
  return `${outcome.message} — 请求过频,请稍后重试`;
114
104
  case 'infra_error':
@@ -117,239 +107,326 @@ function nonSuccessMessage(outcome, context) {
117
107
  return `${context}失败`;
118
108
  }
119
109
  }
120
- function detailFromOutcome(outcome) {
110
+ function valueFromOutcome(outcome) {
121
111
  if (outcome.kind === 'success')
122
112
  return outcome.data;
123
113
  if (outcome.kind === 'soft_success')
124
114
  return outcome.resource;
125
115
  return undefined;
126
116
  }
127
- function toSiteConfig(detail, fallbackSlug) {
128
- const slug = detail?.slug !== undefined ? String(detail.slug) : fallbackSlug;
129
- return {
130
- id: detail?.id !== undefined && detail?.id !== null ? String(detail.id) : '',
131
- slug,
132
- name: detail?.name !== undefined && detail?.name !== null ? String(detail.name) : slug,
133
- };
117
+ function asRecord(value) {
118
+ return value !== null && typeof value === 'object' ? value : undefined;
119
+ }
120
+ function siteFrom(value) {
121
+ const record = asRecord(value);
122
+ return record ? record : undefined;
123
+ }
124
+ function isSiteForTarget(detail, spid, slug) {
125
+ return Boolean(detail &&
126
+ typeof detail.id === 'number' &&
127
+ Number.isSafeInteger(detail.id) &&
128
+ detail.id > 0 &&
129
+ detail.spid === spid &&
130
+ detail.slug === slug &&
131
+ typeof detail.name === 'string' &&
132
+ detail.name.length > 0 &&
133
+ Array.isArray(detail.environments));
134
+ }
135
+ function isTerminal(value) {
136
+ return Boolean(value && typeof value === 'object' && 'kind' in value && (value.kind === 'needs_login' || value.kind === 'refresh_failed'));
134
137
  }
135
- function envNames(detail) {
136
- if (!detail?.environments)
137
- return [];
138
- return detail.environments
139
- .map((e) => (typeof e.name === 'string' ? e.name : undefined))
140
- .filter((v) => v !== undefined);
138
+ function listContainsEnvironment(value, env) {
139
+ if (!Array.isArray(value))
140
+ return false;
141
+ return value.some((item) => asRecord(item)?.name === env);
141
142
  }
142
- function domainForEnv(detail, env) {
143
- const match = detail?.environments?.find((e) => e.name === env);
144
- return match && typeof match.domain === 'string' ? match.domain : undefined;
143
+ function environmentViews(detail) {
144
+ return Array.isArray(detail.environments) ? detail.environments.filter((item) => Boolean(asRecord(item))) : [];
145
+ }
146
+ function domainFromSite(detail, env) {
147
+ const found = environmentViews(detail).find((item) => item.env === env);
148
+ return typeof found?.domain === 'string' && found.domain.length > 0 ? found.domain : undefined;
149
+ }
150
+ function domainFromDeploy(value) {
151
+ const record = asRecord(value);
152
+ return typeof record?.domain === 'string' && record.domain.length > 0 ? record.domain : undefined;
153
+ }
154
+ function isValidSpid(value) {
155
+ return /^[a-z0-9]{8}$/.test(value);
156
+ }
157
+ function isValidSlug(value) {
158
+ return /^[a-z0-9]{1,32}$/.test(value) && value !== 'stg';
159
+ }
160
+ function isValidEnvironment(value) {
161
+ return /^[a-z0-9]{1,10}$/.test(value);
162
+ }
163
+ function trimFlag(value) {
164
+ const trimmed = value?.trim();
165
+ return trimmed ? trimmed : undefined;
166
+ }
167
+ function normalizeBinding(value) {
168
+ if (value === null || value === undefined)
169
+ return { kind: 'absent' };
170
+ const record = asRecord(value);
171
+ if (!record || typeof record.kind !== 'string')
172
+ return { kind: 'invalid' };
173
+ if (record.kind === 'absent')
174
+ return { kind: 'absent' };
175
+ if (record.kind === 'legacy-v1') {
176
+ const site = asRecord(record.site);
177
+ return typeof site?.slug === 'string' && typeof site.name === 'string'
178
+ ? { kind: 'legacy-v1', site: { slug: site.slug, name: site.name } }
179
+ : { kind: 'legacy-v1' };
180
+ }
181
+ if (record.kind !== 'valid-v2')
182
+ return { kind: 'invalid' };
183
+ const config = asRecord(record.config);
184
+ const project = asRecord(config?.project);
185
+ const site = asRecord(config?.site);
186
+ if (typeof config?.schemaVersion !== 'number' ||
187
+ config.schemaVersion !== 2 ||
188
+ typeof project?.spid !== 'string' ||
189
+ typeof project.orgId !== 'string' ||
190
+ typeof site?.slug !== 'string' ||
191
+ typeof site.name !== 'string' ||
192
+ typeof config.environment !== 'string') {
193
+ return { kind: 'invalid' };
194
+ }
195
+ return { kind: 'valid-v2', config: config };
196
+ }
197
+ function legacyMigrationMessage(dir, site) {
198
+ const quotedDir = path.resolve(dir);
199
+ const slug = site?.slug && isValidSlug(site.slug) ? site.slug : '<slug>';
200
+ const name = site?.name?.trim();
201
+ const nameFlag = name ? ` --name ${JSON.stringify(name)}` : '';
202
+ return ('检测到已退役 schema v1 super-site.yml,已保留原文件。请从 Console 获取项目身份后重新发布:' +
203
+ ` supercli publish-site ${JSON.stringify(quotedDir)} --spid <spid> --slug ${slug} --env <env> --org <org>${nameFlag}`);
204
+ }
205
+ function fallbackDomain(spid, slug, env) {
206
+ return env === 'prod' ? `${slug}-${spid}.supersdk.site` : `${slug}-${env}-${spid}.supersdk.site`;
207
+ }
208
+ async function oneEnvironmentRecheck(account, deps, tokenRef, client, context, spid, env) {
209
+ const recheck = await withAuth(account, deps, tokenRef, (token) => client.listEnvironments({ ...context, accessToken: token }, spid));
210
+ if (recheck.kind !== 'outcome')
211
+ return recheck;
212
+ return (recheck.outcome.kind === 'success' || recheck.outcome.kind === 'soft_success') && listContainsEnvironment(valueFromOutcome(recheck.outcome), env);
213
+ }
214
+ async function oneSiteRecheck(account, deps, tokenRef, client, context, spid, slug) {
215
+ const recheck = await withAuth(account, deps, tokenRef, (token) => client.getSite({ ...context, accessToken: token }, spid, slug));
216
+ if (recheck.kind !== 'outcome')
217
+ return recheck;
218
+ const detail = siteFrom(valueFromOutcome(recheck.outcome));
219
+ return isSiteForTarget(detail, spid, slug) ? detail : undefined;
145
220
  }
146
221
  async function runPublishSite(dir, opts, deps = exports.defaultPublishSiteDeps) {
147
- // --env is REQUIRED and has NO default; it never touches super-site.yml. Fail
148
- // before any HTTP call (and without persisting anything) when it is missing.
149
- const env = opts.env?.trim();
150
- if (!env) {
151
- return { ok: false, message: '必须通过 --env 指定站点环境(如 --env prod),该值无默认值' };
222
+ // Local parse and target conflict checks deliberately precede account lookup,
223
+ // HTTP, config writes and zip construction.
224
+ const binding = normalizeBinding(deps.readSiteConfig(dir));
225
+ if (binding.kind === 'legacy-v1')
226
+ return { ok: false, message: legacyMigrationMessage(dir, binding.site) };
227
+ if (binding.kind === 'invalid')
228
+ return { ok: false, message: 'super-site.yml 非法或不完整;已保留原文件,请修正或按迁移命令重新建立 schema v2 绑定' };
229
+ const explicit = {
230
+ spid: trimFlag(opts.spid),
231
+ slug: trimFlag(opts.slug),
232
+ env: trimFlag(opts.env),
233
+ org: trimFlag(opts.org),
234
+ };
235
+ let spid;
236
+ let slug;
237
+ let env;
238
+ let boundOrgId;
239
+ let siteName;
240
+ let mustWriteBinding = false;
241
+ if (binding.kind === 'absent') {
242
+ if (!explicit.spid || !explicit.slug || !explicit.env) {
243
+ return { ok: false, message: '首次发布必须同时提供合法的 --spid、--slug、--env;不会猜测项目、站点或环境' };
244
+ }
245
+ spid = explicit.spid;
246
+ slug = explicit.slug;
247
+ env = explicit.env;
248
+ siteName = trimFlag(opts.name) ?? slug;
249
+ mustWriteBinding = true;
152
250
  }
153
- // Validate --env LOCALLY (mirrors backend service.rs validate_environment_name:
154
- // 1-10 lowercase letters/digits) BEFORE any HTTP. A typo like "Staging" would
155
- // otherwise sail past create-site + super-site.yml write and only fail at the
156
- // create-env call with INVALID_ENV_NAME — after an irreversible side effect.
157
- if (!isValidEnvName(env)) {
158
- return {
159
- ok: false,
160
- message: `--env "${env}" 非法:需为 1-10 位小写字母或数字(如 prod、stg1),不能含大写/连字符/其他字符`,
161
- };
251
+ else {
252
+ const config = binding.config;
253
+ if ((explicit.spid && explicit.spid !== config.project.spid) ||
254
+ (explicit.slug && explicit.slug !== config.site.slug) ||
255
+ (explicit.env && explicit.env !== config.environment) ||
256
+ (explicit.org && explicit.org !== config.project.orgId)) {
257
+ return { ok: false, message: '显式发布参数与 schema v2 super-site.yml 绑定冲突;不会静默覆盖目标' };
258
+ }
259
+ spid = config.project.spid;
260
+ slug = config.site.slug;
261
+ env = config.environment;
262
+ boundOrgId = config.project.orgId;
263
+ siteName = config.site.name;
264
+ }
265
+ if (!isValidSpid(spid))
266
+ return { ok: false, message: '--spid 非法:必须为 8 位小写字母或数字' };
267
+ if (!isValidSlug(slug))
268
+ return { ok: false, message: '--slug 非法:必须为 1-32 位小写字母或数字,且不能为 stg' };
269
+ if (!isValidEnvironment(env))
270
+ return { ok: false, message: '--env 非法:必须为 1-10 位小写字母或数字' };
271
+ siteName = siteName.trim();
272
+ const siteNameLength = Array.from(siteName).length;
273
+ if (siteNameLength < 1 || siteNameLength > 50)
274
+ return { ok: false, message: '--name 非法:必须为 1-50 个字符' };
275
+ const parsedVersion = (0, offlineVersion_1.parseOfflineVersion)(trimFlag(opts.version));
276
+ if (!parsedVersion) {
277
+ return { ok: false, message: '--version 必填,且必须是最多 64 bytes 的 x.y.z(major ≤ 2147483647,minor/patch ≤ 99;前导零按数值比较)' };
162
278
  }
279
+ const version = parsedVersion.raw;
163
280
  const account = deps.getCurrentAccount();
164
- if (!account) {
281
+ if (!account)
165
282
  return { ok: false, message: '当前没有登录账号,请先运行:supercli login' };
166
- }
167
283
  const accessToken = deps.getAccessToken(account);
168
284
  if (!accessToken) {
169
285
  deps.markNeedsLogin(account.accountKey);
170
286
  return { ok: false, message: '本地未找到有效凭据,请重新登录:supercli login' };
171
287
  }
172
288
  const tokenRef = { value: accessToken };
173
- const apiOrigin = account.apiOrigin;
174
- const siteClient = deps.createSiteClient(apiOrigin);
175
- // ---- determine slug + mode LOCALLY, before any HTTP (TC-S27) ----
176
- // super-site.yml read + default-slug derivation are pure/local, so an invalid
177
- // default slug (uppercase/underscore/reserved dir name) fails before /me.
178
- const bound = deps.readSiteConfig(dir);
179
- let mode;
180
- if (bound) {
181
- mode = { kind: 'bound', slug: bound.slug };
182
- }
183
- else if (opts.slug && opts.slug.trim().length > 0) {
184
- mode = { kind: 'explicit', slug: opts.slug.trim() };
289
+ let orgId;
290
+ if (explicit.org) {
291
+ const resolution = (0, orgResolve_1.resolveOrgId)([], explicit.org);
292
+ if (resolution.kind !== 'resolved')
293
+ return { ok: false, message: '--org 必须为正整数' };
294
+ orgId = resolution.orgId;
185
295
  }
186
296
  else {
187
- const derived = (0, siteConfig_1.deriveDefaultSlug)(path.basename(path.resolve(dir)));
188
- if (!derived) {
189
- return {
190
- ok: false,
191
- message: '无法从目录名派生出合法 slug(需 1-40 位小写字母/数字/内部连字符、非保留字),请显式传入 --slug',
192
- };
193
- }
194
- mode = { kind: 'create', slug: derived, name: opts.name && opts.name.trim().length > 0 ? opts.name.trim() : derived };
297
+ const me = await withAuth(account, deps, tokenRef, (token) => deps.fetchMe(account.apiOrigin, token));
298
+ if (me.kind !== 'outcome')
299
+ return { ok: false, message: terminalMessage(me) };
300
+ if (me.outcome.kind !== 'success')
301
+ return { ok: false, message: `无法获取当前用户组织:${'message' in me.outcome ? me.outcome.message : me.outcome.kind}` };
302
+ const resolution = (0, orgResolve_1.resolveOrgId)(me.outcome.data.orgs ?? undefined);
303
+ if (resolution.kind === 'none')
304
+ return { ok: false, message: '当前账号未归属任何 org,无法发布' };
305
+ if (resolution.kind === 'ambiguous')
306
+ return { ok: false, message: `当前账号归属多个 org(${resolution.orgIds.join(', ')}),请通过 --org <id> 指定` };
307
+ if (resolution.kind !== 'resolved')
308
+ return { ok: false, message: '无法解析当前 org' };
309
+ orgId = resolution.orgId;
195
310
  }
196
- // ---- resolve org (X-Org-Id) ----
197
- let orgId;
198
- if (opts.org && opts.org.trim().length > 0) {
199
- orgId = opts.org.trim();
311
+ if (boundOrgId && boundOrgId !== orgId) {
312
+ return { ok: false, message: '当前解析的 org 与 schema v2 绑定冲突;不会向其他组织发布' };
200
313
  }
201
- else {
202
- const meAttempt = await withAuth(account, deps, tokenRef, (token) => deps.fetchMe(apiOrigin, token));
203
- if (meAttempt.kind !== 'outcome') {
204
- return { ok: false, message: terminalMessage(meAttempt) };
314
+ const client = deps.createSiteClient(account.apiOrigin);
315
+ const context = { accessToken: tokenRef.value, orgId };
316
+ // env-before-site: unavailable environments never leave a new site behind.
317
+ const listed = await withAuth(account, deps, tokenRef, (token) => client.listEnvironments({ ...context, accessToken: token }, spid));
318
+ if (listed.kind !== 'outcome')
319
+ return { ok: false, message: terminalMessage(listed) };
320
+ let environmentAvailable = (listed.outcome.kind === 'success' || listed.outcome.kind === 'soft_success') && listContainsEnvironment(valueFromOutcome(listed.outcome), env);
321
+ if (!environmentAvailable) {
322
+ if (listed.outcome.kind !== 'success' && listed.outcome.kind !== 'soft_success') {
323
+ return { ok: false, message: nonSuccessMessage(listed.outcome, '查询项目环境') };
205
324
  }
206
- const me = meAttempt.outcome;
207
- if (me.kind !== 'success') {
208
- return { ok: false, message: `无法获取当前用户信息:${'message' in me ? me.message : me.kind}` };
325
+ if (env === 'prod')
326
+ return { ok: false, message: '项目 prod 环境不存在,请前往控制台检查项目状态' };
327
+ if (!opts.createEnvironment)
328
+ return { ok: false, message: `项目环境 "${env}" 不存在;如确认要创建共享环境,请显式传入 --create-environment` };
329
+ const created = await withAuth(account, deps, tokenRef, (token) => client.createEnvironment({ ...context, accessToken: token }, spid, { name: env }));
330
+ if (created.kind !== 'outcome')
331
+ return { ok: false, message: terminalMessage(created) };
332
+ if (created.outcome.kind === 'success' && asRecord(created.outcome.data)?.name === env) {
333
+ environmentAvailable = true;
209
334
  }
210
- // opts.org is already known empty in this branch (the non-empty case is
211
- // handled above), so it is intentionally NOT forwarded here.
212
- const resolution = (0, orgResolve_1.resolveOrgId)(me.data.orgs ?? undefined);
213
- if (resolution.kind === 'none') {
214
- return { ok: false, message: '当前账号未归属任何 org,无法发布' };
335
+ else if (created.outcome.kind === 'success' ||
336
+ created.outcome.kind === 'soft_success' ||
337
+ created.outcome.kind === 'infra_error' ||
338
+ (created.outcome.kind === 'business_error' && created.outcome.code === 'ENV_NAME_DUPLICATE')) {
339
+ const rechecked = await oneEnvironmentRecheck(account, deps, tokenRef, client, context, spid, env);
340
+ if (typeof rechecked !== 'boolean')
341
+ return { ok: false, message: terminalMessage(rechecked) };
342
+ environmentAvailable = rechecked;
215
343
  }
216
- if (resolution.kind === 'ambiguous') {
217
- return {
218
- ok: false,
219
- message: `当前账号归属多个 org(${resolution.orgIds.join(', ')}),请通过 --org <id> 指定`,
220
- };
344
+ else {
345
+ return { ok: false, message: nonSuccessMessage(created.outcome, '创建项目环境') };
221
346
  }
222
- orgId = resolution.orgId;
347
+ if (!environmentAvailable)
348
+ return { ok: false, message: `无法确认项目环境 "${env}" 已创建;不会重放写请求,请稍后在控制台核对` };
223
349
  }
224
- // ---- resolve site detail per mode ----
225
- const slug = mode.slug;
226
350
  let detail;
227
- let wroteConfig = false;
228
- if (mode.kind === 'bound') {
229
- // AC-S1: bound yml → use its slug, GET detail (single detail fetch), publish.
230
- const attempt = await withAuth(account, deps, tokenRef, (t) => siteClient.getSite({ accessToken: t, orgId }, slug));
231
- if (attempt.kind !== 'outcome')
232
- return { ok: false, message: terminalMessage(attempt) };
233
- const outcome = attempt.outcome;
234
- if (outcome.kind !== 'success' && outcome.kind !== 'soft_success') {
235
- if (outcome.kind === 'business_error' && outcome.code === 'NOT_FOUND') {
236
- return { ok: false, message: `已绑定的 slug "${slug}" 不存在或不属当前 org,请核对 super-site.yml/--org` };
237
- }
238
- return { ok: false, message: nonSuccessMessage(outcome, '查询站点详情') };
239
- }
240
- detail = detailFromOutcome(outcome);
351
+ const lookedUp = await withAuth(account, deps, tokenRef, (token) => client.getSite({ ...context, accessToken: token }, spid, slug));
352
+ if (lookedUp.kind !== 'outcome')
353
+ return { ok: false, message: terminalMessage(lookedUp) };
354
+ const existing = siteFrom(valueFromOutcome(lookedUp.outcome));
355
+ if (isSiteForTarget(existing, spid, slug)) {
356
+ detail = existing;
241
357
  }
242
- else if (mode.kind === 'explicit') {
243
- // AC-S9: no yml but explicit --slug → GET; NOT_FOUND is a hard error (backend
244
- // org-filters, so "not found" and "owned by another org" are indistinguishable
245
- // — never auto-create here).
246
- const attempt = await withAuth(account, deps, tokenRef, (t) => siteClient.getSite({ accessToken: t, orgId }, slug));
247
- if (attempt.kind !== 'outcome')
248
- return { ok: false, message: terminalMessage(attempt) };
249
- const outcome = attempt.outcome;
250
- if (outcome.kind === 'business_error' && outcome.code === 'NOT_FOUND') {
251
- return { ok: false, message: `slug "${slug}" 不存在或不属当前 org,请核对 --slug/--org` };
358
+ else if (lookedUp.outcome.kind === 'business_error' && lookedUp.outcome.code === 'NOT_FOUND') {
359
+ const created = await withAuth(account, deps, tokenRef, (token) => client.createSite({ ...context, accessToken: token }, spid, { name: siteName, slug }));
360
+ if (created.kind !== 'outcome')
361
+ return { ok: false, message: terminalMessage(created) };
362
+ const createdDetail = siteFrom(valueFromOutcome(created.outcome));
363
+ if (created.outcome.kind === 'success' && isSiteForTarget(createdDetail, spid, slug)) {
364
+ detail = createdDetail;
252
365
  }
253
- if (outcome.kind !== 'success' && outcome.kind !== 'soft_success') {
254
- return { ok: false, message: nonSuccessMessage(outcome, '查询站点详情') };
366
+ else if (created.outcome.kind === 'soft_success' ||
367
+ created.outcome.kind === 'infra_error' ||
368
+ (created.outcome.kind === 'business_error' && created.outcome.code === 'SITE_SLUG_DUPLICATE') ||
369
+ (created.outcome.kind === 'success' && !isSiteForTarget(createdDetail, spid, slug))) {
370
+ const rechecked = await oneSiteRecheck(account, deps, tokenRef, client, context, spid, slug);
371
+ if (isTerminal(rechecked))
372
+ return { ok: false, message: terminalMessage(rechecked) };
373
+ detail = rechecked;
374
+ }
375
+ else {
376
+ return { ok: false, message: nonSuccessMessage(created.outcome, '创建项目站点') };
255
377
  }
256
- detail = detailFromOutcome(outcome);
257
- deps.writeSiteConfig(dir, toSiteConfig(detail, slug));
258
- wroteConfig = true;
378
+ if (!detail)
379
+ return { ok: false, message: '无法确认项目站点已创建;不会重放写请求、写绑定或发布,请稍后核对' };
259
380
  }
260
381
  else {
261
- // AC-S2: no yml, no --slug → the ONLY auto-create entry point.
262
- const attempt = await withAuth(account, deps, tokenRef, (t) => siteClient.createSite({ accessToken: t, orgId }, { name: mode.name, slug }));
263
- if (attempt.kind !== 'outcome')
264
- return { ok: false, message: terminalMessage(attempt) };
265
- const outcome = attempt.outcome;
266
- if (outcome.kind === 'soft_success') {
267
- log_1.log.warn('建站已提交,边缘指针同步进行中(软成功)', { slug, org: orgId });
268
- }
269
- else if (outcome.kind !== 'success') {
270
- return { ok: false, message: nonSuccessMessage(outcome, '建站') };
271
- }
272
- detail = detailFromOutcome(outcome);
273
- deps.writeSiteConfig(dir, toSiteConfig(detail, slug));
274
- wroteConfig = true;
382
+ return { ok: false, message: nonSuccessMessage(lookedUp.outcome, '查询项目站点') };
275
383
  }
276
- // ---- ensure target env exists (reuse the detail already fetched) ----
277
- let envJustCreated = false;
278
- if (!envNames(detail).includes(env)) {
279
- if (env === 'prod') {
280
- return { ok: false, message: `站点 "${slug}" 的 prod 环境不存在,请前往控制台检查` };
281
- }
282
- const attempt = await withAuth(account, deps, tokenRef, (t) => siteClient.createEnv({ accessToken: t, orgId }, slug, { name: env }));
283
- if (attempt.kind !== 'outcome')
284
- return { ok: false, message: terminalMessage(attempt) };
285
- const outcome = attempt.outcome;
286
- if (outcome.kind === 'soft_success') {
287
- log_1.log.warn('环境创建已提交,边缘指针同步进行中(软成功)', { slug, env, org: orgId });
288
- }
289
- else if (outcome.kind !== 'success') {
290
- return { ok: false, message: nonSuccessMessage(outcome, '创建环境') };
291
- }
292
- envJustCreated = true;
384
+ if (mustWriteBinding) {
385
+ deps.writeSiteConfig(dir, {
386
+ schemaVersion: 2,
387
+ project: { spid, orgId },
388
+ site: { slug, name: detail.name },
389
+ environment: env,
390
+ });
293
391
  }
294
- // ---- package the directory (local prechecks; no upload on failure) ----
295
392
  let zip;
296
393
  try {
297
394
  zip = await deps.buildZip(dir);
298
395
  }
299
- catch (err) {
300
- if (err instanceof siteZip_1.ZipBuildError) {
301
- return { ok: false, message: `打包失败:${err.message}` };
302
- }
303
- log_1.log.error('publishSite.buildZip error: ' + err.message, { slug, env });
304
- return { ok: false, message: `打包失败:${err.message}` };
396
+ catch (error) {
397
+ const message = error instanceof siteZip_1.ZipBuildError ? error.message : error.message;
398
+ return { ok: false, message: `打包失败:${message}` };
305
399
  }
306
- // ---- deploy (multipart) ----
307
- const deployAttempt = await withAuth(account, deps, tokenRef, (t) => siteClient.deploy({ accessToken: t, orgId }, slug, env, {
400
+ const deployed = await withAuth(account, deps, tokenRef, (token) => client.deploy({ ...context, accessToken: token }, spid, slug, env, {
308
401
  zip: zip.buffer,
309
- version: opts.version,
402
+ version,
310
403
  description: opts.description,
404
+ expectedSiteId: detail.id,
311
405
  }));
312
- if (deployAttempt.kind !== 'outcome')
313
- return { ok: false, message: terminalMessage(deployAttempt) };
314
- const deployOutcome = deployAttempt.outcome;
315
- let pending = false;
316
- if (deployOutcome.kind === 'soft_success') {
317
- pending = true;
318
- log_1.log.warn('发布已提交,边缘同步进行中(软成功)', { slug, env, org: orgId });
319
- }
320
- else if (deployOutcome.kind !== 'success') {
321
- return { ok: false, message: nonSuccessMessage(deployOutcome, '发布') };
322
- }
323
- // ---- resolve access domain (re-GET only if a new env was just created) ----
324
- if (envJustCreated) {
325
- const attempt = await withAuth(account, deps, tokenRef, (t) => siteClient.getSite({ accessToken: t, orgId }, slug));
326
- if (attempt.kind === 'outcome' && (attempt.outcome.kind === 'success' || attempt.outcome.kind === 'soft_success')) {
327
- detail = detailFromOutcome(attempt.outcome) ?? detail;
328
- }
329
- else {
330
- log_1.log.warn('无法刷新站点详情以获取新环境域名', { slug, env });
331
- }
406
+ if (deployed.kind !== 'outcome')
407
+ return { ok: false, message: terminalMessage(deployed) };
408
+ if (deployed.outcome.kind !== 'success' && deployed.outcome.kind !== 'soft_success') {
409
+ return { ok: false, message: nonSuccessMessage(deployed.outcome, '发布') };
332
410
  }
333
- const domain = domainForEnv(detail, env);
334
- const pendingNote = pending ? '(边缘同步进行中,稍后生效)' : '';
335
- const configNote = wroteConfig ? ',已写入 super-site.yml' : '';
336
- const message = domain
337
- ? `发布成功${configNote},可访问域名:https://${domain.replace(/^https?:\/\//, '')}${pendingNote}`
338
- : `发布成功${configNote}${pendingNote}(未获取到环境域名)`;
339
- return { ok: true, message };
411
+ const pending = deployed.outcome.kind === 'soft_success';
412
+ const domain = domainFromDeploy(valueFromOutcome(deployed.outcome)) ?? domainFromSite(detail, env) ?? fallbackDomain(spid, slug, env);
413
+ const pendingNote = pending ? '(已受理、同步中,稍后生效)' : '';
414
+ return { ok: true, message: `发布成功${mustWriteBinding ? ',已写入 super-site.yml' : ''},可访问域名:https://${domain.replace(/^https?:\/\//, '')}${pendingNote}` };
340
415
  }
341
416
  function registerPublishSiteCommand(program) {
342
417
  program
343
418
  .command('publish-site <dir>')
344
- .description('Package a directory and publish it as a SuperSite deploy.')
345
- .option('--env <env>', 'target site environment (e.g. prod); REQUIRED, no default')
346
- .option('--slug <slug>', 'site slug to bind/publish to')
347
- .option('--name <name>', 'display name used when creating a new site')
348
- .option('--org <id>', 'organization id (required when the account has multiple orgs)')
349
- .option('--version <version>', 'deploy version label')
419
+ .description('Publish a project-scoped SuperSite deploy.')
420
+ .option('--spid <spid>', 'project spid (required for a first publish)')
421
+ .option('--slug <slug>', 'site slug (required for a first publish)')
422
+ .option('--env <env>', 'project environment (required for a first publish)')
423
+ .option('--org <id>', 'organization id; required when the account has multiple orgs')
424
+ .option('--name <name>', 'display name used only when creating a new site')
425
+ .option('--create-environment', 'explicitly authorize creating a missing non-prod project environment')
426
+ .requiredOption('--version <version>', 'required offline package version: x.y.z (major <= 2147483647; minor/patch <= 99)')
350
427
  .option('--description <description>', 'deploy description')
351
- .action(async (dir, opts) => {
352
- const result = await runPublishSite(dir, opts);
428
+ .action(async (dir, options) => {
429
+ const result = await runPublishSite(dir, options);
353
430
  if (!result.ok) {
354
431
  log_1.log.error(result.message ?? 'publish-site failed');
355
432
  process.exitCode = 1;