@geek-fun/serverlessinsight 0.9.3 → 0.9.5

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 (82) hide show
  1. package/AGENTS.md +5 -2
  2. package/CHANGELOG.md +56 -0
  3. package/README.md +266 -179
  4. package/README.zh-CN.md +264 -147
  5. package/codecov +0 -0
  6. package/codecov.SHA256SUM +1 -1
  7. package/codecov.SHA256SUM.sig +13 -13
  8. package/dist/package.json +22 -19
  9. package/dist/src/commands/deploy.js +7 -2
  10. package/dist/src/commands/destroy.js +6 -3
  11. package/dist/src/commands/forceUnlock.js +16 -21
  12. package/dist/src/commands/index.js +26 -63
  13. package/dist/src/commands/migrate.js +105 -132
  14. package/dist/src/commands/plan.js +27 -3
  15. package/dist/src/commands/show.js +17 -6
  16. package/dist/src/common/aggregateState.js +185 -0
  17. package/dist/src/common/aggregateStore.js +247 -0
  18. package/dist/src/common/aliyunClient/apigwOperations.js +32 -9
  19. package/dist/src/common/apiClient.js +35 -12
  20. package/dist/src/common/constants.js +2 -1
  21. package/dist/src/common/context.js +22 -15
  22. package/dist/src/common/effectiveConfig.js +48 -0
  23. package/dist/src/common/index.js +5 -0
  24. package/dist/src/common/jsonOutput.js +2 -13
  25. package/dist/src/common/migrationMarker.js +0 -7
  26. package/dist/src/common/nameBuilder.js +2 -3
  27. package/dist/src/common/regionalMigration.js +261 -0
  28. package/dist/src/common/saasProtocol.js +41 -0
  29. package/dist/src/common/stateBackend/cosStateBackend.js +88 -8
  30. package/dist/src/common/stateBackend/index.js +42 -18
  31. package/dist/src/common/stateBackend/localStateBackend.js +61 -26
  32. package/dist/src/common/stateBackend/ossStateBackend.js +62 -9
  33. package/dist/src/common/stateBackend/remoteStateBackend.js +94 -94
  34. package/dist/src/common/stateBackend/saasStateBackend.js +327 -92
  35. package/dist/src/common/stateBackend/types.js +9 -0
  36. package/dist/src/common/stateManager.js +38 -11
  37. package/dist/src/common/stateScope.js +34 -0
  38. package/dist/src/common/stateStorageIO.js +31 -0
  39. package/dist/src/lang/en.js +48 -6
  40. package/dist/src/lang/index.js +28 -14
  41. package/dist/src/lang/zh-CN.js +48 -6
  42. package/dist/src/parser/index.js +25 -4
  43. package/dist/src/stack/aliyunStack/apigwDomainPlan.js +82 -0
  44. package/dist/src/stack/aliyunStack/apigwExecutor.js +4 -1
  45. package/dist/src/stack/aliyunStack/apigwPlanner.js +115 -55
  46. package/dist/src/stack/aliyunStack/apigwResource.js +169 -124
  47. package/dist/src/stack/aliyunStack/deployer.js +5 -5
  48. package/dist/src/stack/aliyunStack/destroyer.js +5 -5
  49. package/dist/src/stack/aliyunStack/fc3Planner.js +1 -1
  50. package/dist/src/stack/aliyunStack/fc3Resource.js +2 -2
  51. package/dist/src/stack/aliyunStack/planner.js +1 -1
  52. package/dist/src/stack/aliyunStack/sharedLogProject.js +2 -2
  53. package/dist/src/stack/ownershipTag.js +34 -26
  54. package/dist/src/stack/scfStack/deployer.js +5 -5
  55. package/dist/src/stack/scfStack/destroyer.js +5 -6
  56. package/dist/src/stack/scfStack/planner.js +1 -1
  57. package/dist/src/stack/scfStack/scfResource.js +1 -1
  58. package/dist/src/stack/scfStack/sharedLogset.js +5 -2
  59. package/dist/src/stack/volcengineStack/deployer.js +3 -3
  60. package/dist/src/stack/volcengineStack/destroyer.js +2 -3
  61. package/dist/src/stack/volcengineStack/planner.js +1 -1
  62. package/dist/src/stack/volcengineStack/sharedLogProject.js +4 -4
  63. package/dist/src/stack/volcengineStack/vefaasResource.js +1 -1
  64. package/dist/src/types/domains/state.js +28 -2
  65. package/dist/src/validator/rootSchema.js +8 -0
  66. package/dist/tsconfig.tsbuildinfo +1 -1
  67. package/package.json +22 -19
  68. package/release-notes.md +27 -56
  69. package/samples/README_TENCENT_COS.md +68 -26
  70. package/samples/README_TENCENT_SCF.md +47 -29
  71. package/.serverlessinsight/state-cdn-flow-app-cdn-flow-service.json.backup +0 -14
  72. package/.serverlessinsight/state-iam-test-app-iam-test-service.json.backup +0 -32
  73. package/.serverlessinsight/state-insight-poc-app-insight-poc-tencent.json.backup +0 -90
  74. package/.serverlessinsight/state-insight-poc-app-log-insight-poc-tencent-log.json.backup +0 -118
  75. package/.serverlessinsight/state-insight-poc-deploy-app-insight-poc-deploy.json.backup +0 -215
  76. package/.serverlessinsight/state-insight-poc-destroy-app-insight-poc-destroy.json.backup +0 -14
  77. package/.serverlessinsight/state-insight-poc-timer-app-insight-poc-timer.json.backup +0 -132
  78. package/.serverlessinsight/state-insight-volc-app-insight-volc.json.backup +0 -55
  79. package/.serverlessinsight/state-insight-volc-destroy-app-insight-volc-destroy.json.backup +0 -1
  80. package/.serverlessinsight/state-insight-volc-nested-app-insight-volc-nested.json.backup +0 -93
  81. package/.serverlessinsight/state-nested-drift-app-nested-drift-service.json.backup +0 -163
  82. package/.serverlessinsight/state-role-reconcile-test-app-role-reconcile-test-service.json.backup +0 -148
@@ -3,11 +3,13 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
3
3
  return (mod && mod.__esModule) ? mod : { "default": mod };
4
4
  };
5
5
  Object.defineProperty(exports, "__esModule", { value: true });
6
- exports.getRoleArnFromState = exports.removeSharedResource = exports.setSharedResource = exports.getSharedResource = exports.getAllSharedResources = exports.getAllResources = exports.removeResource = exports.setResource = exports.getResource = exports.saveStateWithLock = exports.patchPersistedState = exports.writeStateFileAtomically = exports.saveState = exports.loadState = exports.toPersistedState = exports.migrateState = exports.clearStateMigrations = exports.registerStateMigration = exports.ensureStateDir = exports.getStatePath = void 0;
6
+ exports.getRoleArnFromState = exports.removeSharedResource = exports.setSharedResource = exports.getSharedResource = exports.getAllSharedResources = exports.getAllResources = exports.removeResource = exports.setResource = exports.getResource = exports.validateScopedDocument = exports.emptyScopedState = exports.saveStateWithLock = exports.patchPersistedState = exports.writeStateFileAtomically = exports.saveState = exports.loadState = exports.toPersistedState = exports.migrateState = exports.clearStateMigrations = exports.registerStateMigration = exports.ensureStateDir = exports.getStatePath = void 0;
7
7
  const node_fs_1 = __importDefault(require("node:fs"));
8
8
  const node_path_1 = __importDefault(require("node:path"));
9
9
  const node_crypto_1 = __importDefault(require("node:crypto"));
10
10
  const types_1 = require("../types");
11
+ const stateScope_1 = require("./stateScope");
12
+ const aggregateState_1 = require("./aggregateState");
11
13
  const lockManager_1 = require("./lockManager");
12
14
  const logger_1 = require("./logger");
13
15
  const STATE_DIR = '.serverlessinsight';
@@ -164,6 +166,9 @@ const saveState = (state, app, service, stage, baseDir = process.cwd()) => {
164
166
  catch {
165
167
  // use default
166
168
  }
169
+ if (parseStateVersion(existing.version) > parseStateVersion(types_1.CURRENT_STATE_VERSION)) {
170
+ throw new types_1.StateVersionError(existing.version, types_1.CURRENT_STATE_VERSION);
171
+ }
167
172
  // Write updated stage resources, preserve all other stages
168
173
  const stateToSave = {
169
174
  ...existing,
@@ -189,11 +194,11 @@ exports.saveState = saveState;
189
194
  * Back up the previous state file, then write tmp + fsync + rename. Shared by
190
195
  * saveState and patchPersistedState.
191
196
  */
192
- const writeStateFileAtomically = (statePath, content) => {
197
+ const writeStateFileAtomically = (statePath, content, options = {}) => {
193
198
  const tmpPath = `${statePath}.tmp`;
194
199
  const backupPath = `${statePath}.backup`;
195
200
  try {
196
- if (node_fs_1.default.existsSync(statePath)) {
201
+ if (options.backup !== false && node_fs_1.default.existsSync(statePath)) {
197
202
  node_fs_1.default.copyFileSync(statePath, backupPath);
198
203
  }
199
204
  const fd = node_fs_1.default.openSync(tmpPath, 'w');
@@ -245,15 +250,10 @@ const patchPersistedState = (app, service, patch, baseDir = process.cwd()) => {
245
250
  catch {
246
251
  // use default
247
252
  }
248
- const patched = { ...existing };
249
- for (const [key, value] of Object.entries(patch)) {
250
- if (value === undefined) {
251
- delete patched[key];
252
- }
253
- else {
254
- patched[key] = value;
255
- }
253
+ if (parseStateVersion(existing.version) > parseStateVersion(types_1.CURRENT_STATE_VERSION)) {
254
+ throw new types_1.StateVersionError(existing.version, types_1.CURRENT_STATE_VERSION);
256
255
  }
256
+ const patched = Object.fromEntries(Object.entries({ ...existing, ...patch }).filter(([, value]) => value !== undefined));
257
257
  const stateToSave = {
258
258
  ...patched,
259
259
  version: types_1.CURRENT_STATE_VERSION,
@@ -274,6 +274,33 @@ const saveStateWithLock = async (state, app, service, stage, operation, baseDir
274
274
  }, options);
275
275
  };
276
276
  exports.saveStateWithLock = saveStateWithLock;
277
+ const emptyScopedState = (scope) => {
278
+ return (0, aggregateState_1.emptyDeploymentState)(scope);
279
+ };
280
+ exports.emptyScopedState = emptyScopedState;
281
+ const validateScopedDocument = (raw, scope) => {
282
+ const normalized = (0, stateScope_1.normalizeScope)(scope);
283
+ if (raw.version && raw.version !== types_1.CURRENT_STATE_VERSION) {
284
+ throw new types_1.StateVersionError(raw.version, types_1.CURRENT_STATE_VERSION);
285
+ }
286
+ const stored = {
287
+ provider: raw.provider,
288
+ app: raw.app,
289
+ service: raw.service,
290
+ stage: raw.scope?.stage,
291
+ region: raw.scope?.region,
292
+ };
293
+ const matches = stored.provider === normalized.provider &&
294
+ stored.app === normalized.app &&
295
+ stored.service === normalized.service &&
296
+ !!raw.scope &&
297
+ raw.scope.stage === normalized.stage &&
298
+ raw.scope.region.toLowerCase() === normalized.region;
299
+ if (!matches) {
300
+ throw new types_1.StateScopeMismatchError(normalized, stored);
301
+ }
302
+ };
303
+ exports.validateScopedDocument = validateScopedDocument;
277
304
  /* istanbul ignore next */
278
305
  const getResource = (state, resourceId) => {
279
306
  return state.resources[resourceId];
@@ -0,0 +1,34 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.stateScopeMatches = exports.normalizeScope = exports.canonicalizeRegion = exports.validateScopeKeyPart = void 0;
4
+ const lang_1 = require("../lang");
5
+ const validateScopeKeyPart = (part, label) => {
6
+ if (!part || part.trim().length === 0) {
7
+ throw new Error(lang_1.lang.__('SCOPE_KEY_PART_REQUIRED', { label }));
8
+ }
9
+ if (part.includes('/') ||
10
+ part.includes('\\') ||
11
+ part.includes('..') ||
12
+ part.trim() !== part ||
13
+ part === '.' ||
14
+ part === '..') {
15
+ throw new Error(lang_1.lang.__('SCOPE_KEY_PART_INVALID', { label, part }));
16
+ }
17
+ return part;
18
+ };
19
+ exports.validateScopeKeyPart = validateScopeKeyPart;
20
+ const canonicalizeRegion = (region) => {
21
+ const canonical = (region ?? '').trim().toLowerCase();
22
+ return (0, exports.validateScopeKeyPart)(canonical, 'region');
23
+ };
24
+ exports.canonicalizeRegion = canonicalizeRegion;
25
+ const normalizeScope = (scope) => ({
26
+ provider: (0, exports.validateScopeKeyPart)(scope.provider, 'provider'),
27
+ app: (0, exports.validateScopeKeyPart)(scope.app, 'app'),
28
+ service: (0, exports.validateScopeKeyPart)(scope.service, 'service'),
29
+ stage: (0, exports.validateScopeKeyPart)(scope.stage, 'stage'),
30
+ region: (0, exports.canonicalizeRegion)(scope.region),
31
+ });
32
+ exports.normalizeScope = normalizeScope;
33
+ const stateScopeMatches = (scope, stage, region) => scope.stage === stage && (0, exports.canonicalizeRegion)(scope.region) === (0, exports.canonicalizeRegion)(region);
34
+ exports.stateScopeMatches = stateScopeMatches;
@@ -0,0 +1,31 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.createLocalStateIO = void 0;
7
+ const node_fs_1 = __importDefault(require("node:fs"));
8
+ const node_path_1 = __importDefault(require("node:path"));
9
+ const stateManager_1 = require("./stateManager");
10
+ const createLocalStateIO = (options = {}) => ({
11
+ read: async (key) => {
12
+ try {
13
+ return JSON.parse(node_fs_1.default.readFileSync(key, 'utf-8'));
14
+ }
15
+ catch (error) {
16
+ if (error.code === 'ENOENT')
17
+ return null;
18
+ throw error;
19
+ }
20
+ },
21
+ write: async (key, data) => {
22
+ node_fs_1.default.mkdirSync(node_path_1.default.dirname(key), { recursive: true });
23
+ if (options.backupWrites === false) {
24
+ (0, stateManager_1.writeStateFileAtomically)(key, JSON.stringify(data, null, 2), { backup: false });
25
+ }
26
+ else {
27
+ (0, stateManager_1.writeStateFileAtomically)(key, JSON.stringify(data, null, 2));
28
+ }
29
+ },
30
+ });
31
+ exports.createLocalStateIO = createLocalStateIO;
@@ -2,9 +2,11 @@
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.en = void 0;
4
4
  exports.en = {
5
+ STATE_STORAGE_PROVIDER_UNSUPPORTED: 'State storage does not support provider {{provider}}. Configure storageProvider as aliyun or tencent.',
5
6
  PLAN_SENSITIVE_VALUE: '(sensitive)',
6
7
  PLAN_NAS_NETWORK_REQUIRED: 'NAS storage on {{logicalId}} needs a declared VPC network or recorded mount targets. Planning stopped before creating any resources.',
7
8
  APIGW_DOMAIN_READ_INVALID: 'Invalid domain response for: {{domainId}}',
9
+ APIGW_DOMAIN_CERTIFICATE_UPDATED: 'Updated gateway certificate for domain: {{domain}}',
8
10
  PLAN_DRIFT_EVENT_DOMAIN: 'Gateway domain or certificate differs from the requested configuration or is missing',
9
11
  PLAN_DRIFT_HTTP_TRIGGER: 'HTTP trigger differs from the requested configuration or is missing',
10
12
  PLAN_DRIFT_FUNCTION_DOMAIN: 'Function domain differs from the requested configuration or is missing',
@@ -234,7 +236,7 @@ exports.en = {
234
236
  FORCE_UNLOCK_CONFIRM: 'Are you absolutely sure? (yes/no): ',
235
237
  FORCE_UNLOCK_CANCELLED: 'Force unlock cancelled',
236
238
  SAAS_FORCE_UNLOCK_NOT_SUPPORTED: 'Force unlock is not supported via CLI for SaaS state. Open {{consoleUrl}} in your browser and unlock the deployment from the Deployments page.',
237
- PLAN_COMMAND_NOT_SUPPORTED: 'Plan command is not supported for this provider',
239
+ PLAN_COMMAND_NOT_SUPPORTED: 'Planning is not supported for this provider',
238
240
  // Lock info formatting
239
241
  LOCK_INFO_HEADER: 'Lock Info:',
240
242
  LOCK_INFO_ID: ' ID: {{id}}',
@@ -863,16 +865,56 @@ exports.en = {
863
865
  MIGRATE_UPLOADED: ' ✓ stage {{stage}} → version {{version}}{{deduped}} (app {{appId}}, service {{serviceId}})',
864
866
  MIGRATE_UPLOADED_DEDUPLICATED: ' (unchanged, deduplicated)',
865
867
  MIGRATE_VERIFY_FAILED: 'Read-back verification FAILED for stage {{stage}} — the migration marker was NOT written. Compare the Console state version with your legacy state, then re-run `si migrate`.',
866
- MIGRATE_CONFLICT: 'The target stage already has Console state. Re-run with --force to adopt it as a new imported version (history is kept).',
867
868
  MIGRATE_MARKER_WRITTEN: 'Migration marker written: the legacy state is now read-only (managedBy=saas).',
868
869
  MIGRATE_MARKER_SKIPPED: 'WARNING: --no-marker was set. The legacy backend stays writable until cutover — complete the YAML cutover immediately.',
869
870
  MIGRATE_ROLLBACK_NO_MARKER: 'No migration marker found on the legacy state — nothing to roll back.',
870
871
  MIGRATE_ROLLBACK_DONE: 'Migration marker cleared. The legacy backend is writable again.',
871
872
  MIGRATE_ROLLBACK_DONE_HINT: 'If you already removed the backend.state_manager block from your YAML, restore it before deploying via the legacy backend.',
872
- MIGRATE_CUTOVER_STEPS: 'Cutover checklist:\n 1. Remove the backend.state_manager block from serverlessinsight.yml, add a top-level org declaration (org: <slug> — see your org settings in Console), and merge\n 2. Run `si plan` — it MUST report no changes (that is the proof of a lossless migration)\n 3. Resume deploys; the Console now owns the deployment timeline',
873
+ MIGRATE_CUTOVER_STEPS: 'Cutover checklist:\n 1. Remove the backend.state_manager block from serverlessinsight.yml, add a top-level org declaration (org: <slug> — see your org settings in Console), and merge\n 2. Run `si diff` — it MUST report no changes and exit 0 (that is the proof of a lossless migration)\n 3. Resume deploys; the Console now owns the deployment timeline',
873
874
  MIGRATION_MARKER_REFUSED: 'This state has been migrated to the ServerlessInsight Console (managedBy=saas) and the legacy backend is closed for changes.\n • To continue with the Console: remove the backend.state_manager block from your YAML, declare a top-level org: <slug>, then deploy again.\n • To deliberately use the legacy backend: run `si migrate --rollback` to clear the marker.',
874
875
  MIGRATION_MARKER_WARN: 'This state has been migrated to the Console (managedBy=saas) — the copy shown here is read-only and may be stale. Do not deploy from this backend.',
875
- // HTTP trigger messages
876
+ SCOPE_KEY_PART_REQUIRED: "'{{label}}' is required and must not be empty",
877
+ SCOPE_KEY_PART_INVALID: "'{{label}}' value '{{part}}' is not path-safe: it must not be empty, contain '/', '\\', '..' or leading/trailing whitespace",
878
+ EFFECTIVE_CONFIG_UNKNOWN_PROVIDER: "Unknown provider '{{provider}}'. Supported providers: aliyun, tencent, volcengine, huawei, aws",
879
+ EFFECTIVE_CONFIG_RESOURCE_UNSUPPORTED: "Provider '{{provider}}' cannot deploy '{{resource}}' from this template. Adjust the template before overriding the provider.",
880
+ EFFECTIVE_CONFIG_REGION_REQUIRED: 'A region is required: pass -r/--region, set provider.region in the YAML, or set the SI_REGION environment variable',
881
+ STATE_AGGREGATE_INVALID: 'The aggregate state document is malformed. Restore a verified backup before continuing.',
882
+ STATE_STORE_UPGRADE_REQUIRED: 'State at {{location}} requires an in-place format upgrade. Deploy, destroy and SaaS handoff prepare it automatically before planning or importing.',
883
+ STATE_PARTITION_PATCH_INVALID: 'Only deployment ownership and migration metadata can be patched.',
884
+ STATE_PLAN_BASE_CHANGED: 'The selected deployment state changed after planning. Generate and approve a new plan before continuing.',
885
+ STATE_SCOPED_VERSION_UNSUPPORTED: 'Unsupported state version {{version}}',
886
+ STATE_SCOPED_IDENTITY_MISMATCH: 'State identity does not match the requested deployment scope',
887
+ STATE_SCOPED_IDENTITY_DETAILS_MISMATCH: 'State identity ({{stored}}) does not match the bound deployment scope ({{requested}})',
888
+ STATE_WRITE_NOT_READY: 'Regional state writes are not ready for this deployment scope',
889
+ STATE_BUCKET_NOT_FOUND: 'The state storage bucket does not exist ({{code}}). Create the bucket or fix the backend.state_manager configuration — the missing bucket is not treated as empty state',
890
+ STATE_BUCKET_ACCESS_DENIED: 'Access to the state storage bucket was denied ({{code}}). Check the storage credentials — an authorization failure is never treated as empty state',
891
+ STATE_STORAGE_CREDENTIALS_MISSING: "State storage needs credentials for {{provider}}. Configure that cloud's credential environment variables. Workload credentials from another provider are never reused.",
892
+ LOCK_CONDITIONAL_CREATE_UNSUPPORTED: 'This state storage does not support exclusive (conditional) create — concurrent first lock acquisition falls back to a verified write and is not guaranteed atomic. Avoid running mutating commands for the same scope in parallel',
893
+ SAAS_REGIONAL_SCOPE_UNSUPPORTED: 'The Console at {{consoleUrl}} does not advertise compatible regional deployment states (scope protocol 2 and state format 4.0). Upgrading the CLI alone cannot isolate regions safely — update the Console, or keep using the previous CLI release for unscoped deployments',
894
+ SAAS_STATE_SCOPE_MISMATCH: 'The Console returned state for stage {{storedStage}} / region {{storedRegion}}, but this command targets stage {{stage}} / region {{region}}. Refusing to mix regional scopes',
895
+ SAAS_READ_ONLY_WRITE_REFUSED: 'This SaaS backend instance was created read-only (diff/show); state writes are refused',
896
+ SAAS_WRITE_BLOCKED_UNSCOPED_STATE: "The current state of stage {{stage}} on the Console has no regional scope recorded (it predates regional isolation). Run the Console-side migration for this service before deploying to region {{region}} — writing here would overwrite another region's state",
897
+ REGIONAL_MIGRATION_UNSUPPORTED_SOURCE: 'Expected a legacy V3.0 state aggregate but found version "{{version}}". No V3 upgrade is needed',
898
+ REGIONAL_MIGRATION_SOURCE_MANAGED_BY_SAAS: 'This legacy state has been migrated to (and is owned by) the ServerlessInsight Console (managedBy=saas). An in-place upgrade would create an unmarked local copy and reopen double-write hazards — refused. Continue on the Console backend, or run `si migrate --rollback` first only if you deliberately want to hand ownership back',
899
+ REGIONAL_MIGRATION_INCOMPLETE_STAGE_COVERAGE: 'The automatic upgrade must preserve every resource in every stage. Source coverage is incomplete; review the source and recovery records before retrying.',
900
+ STATE_ATOMIC_CREATE_REQUIRED: 'This state store cannot atomically reserve ownership or acquire a lock. Mutations are refused.',
901
+ REGIONAL_MIGRATION_PENDING: 'State upgrade {{opId}} is incomplete. Re-run the deploy, destroy or migrate operation to resume with the reviewed region binding.',
902
+ SAAS_STATE_BASE_UNKNOWN: 'Load the regional state before saving or starting a deployment.',
903
+ REGIONAL_LOCK_STALE: 'State is currently locked (stale lock detected).\n{{info}}\nIf you are certain no other operation is running, use:\n si force-unlock {{id}}',
904
+ REGIONAL_LOCK_TIMEOUT: 'Failed to acquire lock after {{seconds}} seconds.\n{{info}}',
905
+ REGIONAL_LOCK_FAILED: 'Failed to acquire lock.\n{{path}}',
906
+ MIGRATE_SOURCE_FORMAT_INVALID: 'The source backend did not provide a valid single-deployment V4 view after automatic preparation. Nothing was imported.',
907
+ MIGRATE_TARGET_REGIONAL_REQUIRED: 'The target service still uses legacy state. Complete its Console-side binding and activation before importing a regional state.',
908
+ MIGRATE_SOURCE_MULTIPLE_SCOPES: 'This regional document contains resources from other stages. Resolve the source ownership before importing; one regional document may own only its selected stage.',
909
+ SAAS_STATE_ACK_INVALID: 'The state server did not confirm a valid regional snapshot and content hash. Refusing to guess the next state revision; upgrade the server to scope protocol 2.',
910
+ REGIONAL_MIGRATION_PROVIDER_MISMATCH: 'The source records provider "{{source}}", while the command selects "{{effective}}". The upgrade preserves the source provider; workload overrides never rewrite historical ownership.',
911
+ REGIONAL_MIGRATION_UNKNOWN_REGION_REQUIRED: 'Some resources carry no region evidence (pre-regional state). Re-run with --bind-unknown-region <region> to bind them explicitly to a region — the CLI never guesses historical regions from YAML or filenames',
912
+ REGIONAL_MIGRATION_SOURCE_CHANGED: 'The source state changed during its format upgrade. Refusing to overwrite it; review the source and retained recovery records before retrying.',
913
+ REGIONAL_MIGRATION_APPLIED: 'State upgraded in place (operation {{opId}}). Stage/provider/region partitions now share the original file or Bucket key. Continuing the requested operation.',
914
+ REGIONAL_MIGRATION_PARTIAL_FAILURE: 'State upgrade interrupted (operation {{opId}}): {{error}}. Keep the source backup and journal; re-run the same operation to resume.',
915
+ REGIONAL_MIGRATION_BACKUP_MISSING: 'Original backup for state upgrade {{opId}} is missing; cannot safely resume. Restore that backup before retrying.',
916
+ REGIONAL_MIGRATION_UNKNOWN_ITEM: ' • [{{stage}}] {{logicalId}} ({{kind}})',
917
+ OPT_BIND_UNKNOWN_REGION: 'explicitly bind resources without region evidence to this region',
876
918
  HTTP_TRIGGER_AUTH_TYPE_REQUIRED: "HTTP trigger '{{functionName}}' requires 'auth_type' (public or iam)",
877
919
  CREATING_HTTP_TRIGGER: "Creating HTTP trigger '{{triggerName}}' for function '{{functionName}}'...",
878
920
  HTTP_TRIGGER_CREATED: "HTTP trigger '{{triggerName}}' created for function '{{functionName}}'",
@@ -1079,8 +1121,8 @@ exports.en = {
1079
1121
  CMD_WHOAMI_DESC: 'show current login status',
1080
1122
  CMD_SHOW_DESC: 'show deployed resources from state',
1081
1123
  CMD_VALIDATE_DESC: 'validate serverless Iac yaml',
1082
- CMD_PLAN_DESC: 'generate and show deployment plan',
1083
- CMD_DIFF_DESC: 'show changes between your config and the live cloud (alias of plan)',
1124
+ CMD_DIFF_DESC: 'show changes between your config and the live cloud',
1125
+ CMD_PLAN_REMOVED: 'the plan command has been removed; use the diff command instead — it accepts the same options and arguments.',
1084
1126
  CMD_DEPLOY_DESC: 'deploy serverless Iac yaml',
1085
1127
  CMD_DESTROY_DESC: 'destroy serverless stack',
1086
1128
  CMD_LOCAL_DESC: 'run Serverless application locally for debugging',
@@ -1,6 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.lang = exports.lookupErrorCode = exports.hasLangKey = void 0;
3
+ exports.getSystemLanguage = exports.lang = exports.lookupErrorCode = exports.hasLangKey = void 0;
4
4
  const child_process_1 = require("child_process");
5
5
  const i18n_1 = require("i18n");
6
6
  const en_1 = require("./en");
@@ -11,24 +11,38 @@ const zh_CN_1 = require("./zh-CN");
11
11
  // eslint-disable-next-line @typescript-eslint/no-require-imports
12
12
  const mustache = require('mustache');
13
13
  mustache.escape = (text) => text;
14
+ const normalizeLocale = (value) => {
15
+ if (!value)
16
+ return null;
17
+ const normalized = value.trim().toLowerCase();
18
+ if (normalized.startsWith('zh'))
19
+ return 'zh-CN';
20
+ if (normalized.startsWith('en'))
21
+ return 'en-US';
22
+ return null;
23
+ };
14
24
  const getSystemLanguage = (defaultLang) => {
15
- const langMatch = (process.env.LANG || process.env.LC_ALL || '').match(/([a-z]{2})[-_]?([A-Z]{2})?/);
16
- if (langMatch) {
17
- return langMatch[0].replace('_', '-');
18
- }
19
- try {
20
- const codePageOutput = (0, child_process_1.execSync)('chcp').toString();
21
- const codePageMatch = codePageOutput.match(/(\d+)\s*$/m);
22
- if (codePageMatch) {
23
- const codePage = parseInt(codePageMatch[1]);
24
- return codePage === 936 ? 'zh-CN' : 'en-US';
25
+ const override = normalizeLocale(process.env.SI_LANG);
26
+ if (override)
27
+ return override;
28
+ const envLocale = [process.env.LC_ALL, process.env.LANG].reduce((found, value) => found ?? normalizeLocale(value), null);
29
+ if (envLocale)
30
+ return envLocale;
31
+ if (process.platform === 'win32') {
32
+ try {
33
+ const codePageOutput = (0, child_process_1.execSync)('chcp').toString();
34
+ const codePageMatch = codePageOutput.match(/(\d+)\s*$/m);
35
+ if (codePageMatch) {
36
+ return parseInt(codePageMatch[1]) === 936 ? 'zh-CN' : 'en-US';
37
+ }
38
+ }
39
+ catch {
40
+ // ignore
25
41
  }
26
- }
27
- catch {
28
- // ignore
29
42
  }
30
43
  return defaultLang;
31
44
  };
45
+ exports.getSystemLanguage = getSystemLanguage;
32
46
  const lang = new i18n_1.I18n({
33
47
  locales: ['en-US', 'zh-CN'],
34
48
  defaultLocale: getSystemLanguage('zh-CN'),
@@ -2,9 +2,11 @@
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.zhCN = void 0;
4
4
  exports.zhCN = {
5
+ STATE_STORAGE_PROVIDER_UNSUPPORTED: 'State 存储不支持云厂商 {{provider}}。请将 storageProvider 配置为 aliyun 或 tencent。',
5
6
  PLAN_SENSITIVE_VALUE: '(敏感值)',
6
7
  PLAN_NAS_NETWORK_REQUIRED: '{{logicalId}} 的 NAS 存储需要声明 VPC 网络或已有挂载目标记录。计划已停止,尚未创建任何资源。',
7
8
  APIGW_DOMAIN_READ_INVALID: '域名 {{domainId}} 的查询响应无效',
9
+ APIGW_DOMAIN_CERTIFICATE_UPDATED: '已更新网关域名证书: {{domain}}',
8
10
  PLAN_DRIFT_EVENT_DOMAIN: '网关域名或证书与配置不一致或不存在',
9
11
  PLAN_DRIFT_HTTP_TRIGGER: 'HTTP 触发器与请求配置不同或已丢失',
10
12
  PLAN_DRIFT_FUNCTION_DOMAIN: '函数域名与请求配置不同或已丢失',
@@ -234,7 +236,7 @@ exports.zhCN = {
234
236
  FORCE_UNLOCK_CONFIRM: '您确定吗?(yes/no): ',
235
237
  FORCE_UNLOCK_CANCELLED: '强制解锁已取消',
236
238
  SAAS_FORCE_UNLOCK_NOT_SUPPORTED: 'SaaS 模式下不支持通过 CLI 强制解锁。请在浏览器中打开 {{consoleUrl}},从部署页面解锁该部署。',
237
- PLAN_COMMAND_NOT_SUPPORTED: '此提供商不支持 Plan 命令',
239
+ PLAN_COMMAND_NOT_SUPPORTED: '此提供商不支持生成部署计划',
238
240
  // Lock info formatting
239
241
  LOCK_INFO_HEADER: '锁信息:',
240
242
  LOCK_INFO_ID: ' ID: {{id}}',
@@ -855,16 +857,56 @@ exports.zhCN = {
855
857
  MIGRATE_UPLOADED: ' ✓ stage {{stage}} → 版本 {{version}}{{deduped}}(app {{appId}},service {{serviceId}})',
856
858
  MIGRATE_UPLOADED_DEDUPLICATED: '(内容未变,已去重)',
857
859
  MIGRATE_VERIFY_FAILED: 'stage {{stage}} 回读校验失败——未写迁移标记。请对比 Console 状态版本与旧状态后重新执行 `si migrate`。',
858
- MIGRATE_CONFLICT: '目标 stage 在 Console 已有状态。如确认覆盖采纳,请加 --force(将作为新版本导入,历史保留)。',
859
860
  MIGRATE_MARKER_WRITTEN: '已写迁移标记:旧状态转为只读(managedBy=saas)。',
860
861
  MIGRATE_MARKER_SKIPPED: '警告:使用了 --no-marker。cutover 完成前旧后端仍可写入——请立即完成 YAML 切换。',
861
862
  MIGRATE_ROLLBACK_NO_MARKER: '旧状态没有迁移标记——无需回滚。',
862
863
  MIGRATE_ROLLBACK_DONE: '已清除迁移标记,旧后端恢复可写。',
863
864
  MIGRATE_ROLLBACK_DONE_HINT: '如果已从 YAML 中删除 backend.state_manager 段,经旧后端部署前请先恢复该段。',
864
- MIGRATE_CUTOVER_STEPS: 'cutover 清单:\n 1. 从 serverlessinsight.yml 删除 backend.state_manager 段,并在顶层添加 org 声明(org: <slug>,slug 见 Console 组织设置)后合并\n 2. 运行 `si plan`——必须显示无变更(这是迁移无损的证明)\n 3. 恢复部署;此后部署时间线由 Console 接管',
865
+ MIGRATE_CUTOVER_STEPS: 'cutover 清单:\n 1. 从 serverlessinsight.yml 删除 backend.state_manager 段,并在顶层添加 org 声明(org: <slug>,slug 见 Console 组织设置)后合并\n 2. 运行 `si diff`——必须显示无变更并退出 0(这是迁移无损的证明)\n 3. 恢复部署;此后部署时间线由 Console 接管',
865
866
  MIGRATION_MARKER_REFUSED: '该状态已迁移至 ServerlessInsight Console(managedBy=saas),旧后端已关闭变更。\n • 继续使用 Console:从 YAML 中删除 backend.state_manager 段并在顶层声明 org: <slug> 后重新部署。\n • 确需经旧后端操作:运行 `si migrate --rollback` 清除标记。',
866
867
  MIGRATION_MARKER_WARN: '该状态已迁移至 Console(managedBy=saas)——此处展示的是只读副本,可能已过期。请勿从该后端部署。',
867
- // HTTP trigger messages
868
+ SCOPE_KEY_PART_REQUIRED: "'{{label}}' 必填且不能为空",
869
+ SCOPE_KEY_PART_INVALID: "'{{label}}' 的值 '{{part}}' 不是路径安全的:不能为空,不能包含 '/'、'\\'、'..' 或首尾空白",
870
+ EFFECTIVE_CONFIG_UNKNOWN_PROVIDER: "未知 provider '{{provider}}'。支持的 provider:aliyun、tencent、volcengine、huawei、aws",
871
+ EFFECTIVE_CONFIG_RESOURCE_UNSUPPORTED: "Provider '{{provider}}' 无法部署当前模板中的 '{{resource}}'。请先调整模板,再覆盖 provider。",
872
+ EFFECTIVE_CONFIG_REGION_REQUIRED: '需要指定 region:通过 -r/--region 传入、在 YAML 的 provider.region 中设置,或设置 SI_REGION 环境变量',
873
+ STATE_AGGREGATE_INVALID: '聚合状态文档格式损坏,请先恢复已验证的备份后再继续。',
874
+ STATE_STORE_UPGRADE_REQUIRED: '状态 {{location}} 需要原位置格式升级。deploy、destroy 和 SaaS 交接会在规划或导入前自动完成升级。',
875
+ STATE_PARTITION_PATCH_INVALID: '仅可修改部署归属和迁移元数据。',
876
+ STATE_PLAN_BASE_CHANGED: '目标部署状态在规划后发生变化,请重新生成并批准计划后再继续。',
877
+ STATE_SCOPED_VERSION_UNSUPPORTED: '不支持的状态版本 {{version}}',
878
+ STATE_SCOPED_IDENTITY_MISMATCH: '状态身份与请求的部署作用域不匹配',
879
+ STATE_SCOPED_IDENTITY_DETAILS_MISMATCH: '状态身份({{stored}})与绑定的部署作用域({{requested}})不匹配',
880
+ STATE_WRITE_NOT_READY: '当前部署范围的状态写入尚未就绪',
881
+ STATE_BUCKET_NOT_FOUND: '状态存储 bucket 不存在({{code}})。请创建 bucket 或修正 backend.state_manager 配置——bucket 缺失不会被当作空状态',
882
+ STATE_BUCKET_ACCESS_DENIED: '状态存储 bucket 访问被拒绝({{code}})。请检查存储凭据——鉴权失败永远不会被当作空状态',
883
+ STATE_STORAGE_CREDENTIALS_MISSING: 'State 存储需要 {{provider}} 的凭证。请配置该云厂商的凭证环境变量,不会复用其他云厂商的业务部署凭证。',
884
+ LOCK_CONDITIONAL_CREATE_UNSUPPORTED: '当前状态存储不支持排他(条件)创建——并发首次加锁将回退为"写入后校验",不保证原子性。请避免对同一 scope 并行执行变更命令',
885
+ SAAS_REGIONAL_SCOPE_UNSUPPORTED: 'Console({{consoleUrl}})尚不支持区域部署状态(缺少 scope protocol 能力)。仅升级 CLI 无法安全隔离区域——请升级 Console,或在未隔离部署场景下继续使用旧版 CLI',
886
+ SAAS_STATE_SCOPE_MISMATCH: 'Console 返回的是 stage {{storedStage}} / region {{storedRegion}} 的状态,但本次命令目标是 stage {{stage}} / region {{region}}。拒绝混用区域 scope',
887
+ SAAS_READ_ONLY_WRITE_REFUSED: '该 SaaS 后端实例以只读模式创建(diff/show),拒绝状态写入',
888
+ SAAS_WRITE_BLOCKED_UNSCOPED_STATE: 'Console 上 stage {{stage}} 的当前状态没有记录区域 scope(早于区域隔离)。请先在 Console 侧完成该服务的迁移,再向 region {{region}} 部署——直接写入会覆盖其他区域的状态',
889
+ REGIONAL_MIGRATION_UNSUPPORTED_SOURCE: '期望旧版 V3.0 状态聚合,但发现版本 "{{version}}"。没有可升级的内容',
890
+ REGIONAL_MIGRATION_SOURCE_MANAGED_BY_SAAS: '该旧版状态已迁移至(并归)ServerlessInsight Console 所有(managedBy=saas)。状态升级会生成无标记的本地副本,重新引入双写风险——已拒绝。请继续使用 Console 后端;或仅在你明确要交还所有权时先运行 `si migrate --rollback`',
891
+ REGIONAL_MIGRATION_INCOMPLETE_STAGE_COVERAGE: '自动升级必须保留所有 stage 中的每个资源。当前源数据覆盖不完整,请核对源状态和恢复记录后再重试。',
892
+ STATE_ATOMIC_CREATE_REQUIRED: '此状态存储无法原子登记所有权或获取锁,已拒绝变更。',
893
+ REGIONAL_MIGRATION_PENDING: 'State 升级 {{opId}} 尚未完成。请使用已审查的区域绑定重新执行 deploy、destroy 或 migrate 以继续。',
894
+ SAAS_STATE_BASE_UNKNOWN: '请先读取区域状态,再保存或开始部署。',
895
+ REGIONAL_LOCK_STALE: '状态已锁定(检测到可能过期的锁)。\n{{info}}\n确认没有其他操作正在运行后,可执行:\n si force-unlock {{id}}',
896
+ REGIONAL_LOCK_TIMEOUT: '等待 {{seconds}} 秒后仍无法获取锁。\n{{info}}',
897
+ REGIONAL_LOCK_FAILED: '无法获取锁。\n{{path}}',
898
+ MIGRATE_SOURCE_FORMAT_INVALID: '源后端在自动准备后未提供有效的单部署 V4 视图,尚未导入任何状态。',
899
+ MIGRATE_TARGET_REGIONAL_REQUIRED: '目标服务仍使用旧版状态。请先完成控制台侧的区域绑定和激活,再导入区域状态。',
900
+ MIGRATE_SOURCE_MULTIPLE_SCOPES: '此区域状态文档还包含其他 stage 的资源。请先核实源状态的归属,再导入;一个区域文档只能管理选定 stage 的资源。',
901
+ SAAS_STATE_ACK_INVALID: '状态服务未确认有效的区域快照和内容哈希。已拒绝推测下一版本,请升级服务端以支持作用域协议 2。',
902
+ REGIONAL_MIGRATION_PROVIDER_MISMATCH: '源状态记录的 provider 为 "{{source}}",命令选择的是 "{{effective}}"。升级保留源 provider,业务部署参数不会重写历史资源归属。',
903
+ REGIONAL_MIGRATION_UNKNOWN_REGION_REQUIRED: '部分资源没有区域证据(早于区域隔离的状态)。请使用 --bind-unknown-region <region> 重新运行以显式绑定区域——CLI 绝不会从 YAML 或文件名猜测历史区域',
904
+ REGIONAL_MIGRATION_SOURCE_CHANGED: '格式升级期间源状态发生了变化。为避免覆盖已有状态,请先核对源状态和保留的恢复记录,再重试原操作。',
905
+ REGIONAL_MIGRATION_APPLIED: 'State 已在原位置升级(操作 {{opId}})。各 stage/provider/region 分区共用原文件或 Bucket key。继续处理当前操作。',
906
+ REGIONAL_MIGRATION_PARTIAL_FAILURE: 'State 升级中断(操作 {{opId}}):{{error}}。请保留源备份和迁移记录,重新运行同一操作以继续。',
907
+ REGIONAL_MIGRATION_BACKUP_MISSING: 'State 升级 {{opId}} 的原始备份缺失,无法安全恢复。请先恢复该备份,再重试原操作。',
908
+ REGIONAL_MIGRATION_UNKNOWN_ITEM: ' • [{{stage}}] {{logicalId}}({{kind}})',
909
+ OPT_BIND_UNKNOWN_REGION: '将没有区域证据的资源显式绑定到该区域',
868
910
  HTTP_TRIGGER_AUTH_TYPE_REQUIRED: "HTTP 触发器 '{{functionName}}' 需要设置 'auth_type'(public 或 iam)",
869
911
  CREATING_HTTP_TRIGGER: "正在为函数 '{{functionName}}' 创建 HTTP 触发器 '{{triggerName}}'...",
870
912
  HTTP_TRIGGER_CREATED: "HTTP 触发器 '{{triggerName}}' 已为函数 '{{functionName}}' 创建成功",
@@ -1071,8 +1113,8 @@ exports.zhCN = {
1071
1113
  CMD_WHOAMI_DESC: '显示当前登录状态',
1072
1114
  CMD_SHOW_DESC: '从状态中显示已部署资源',
1073
1115
  CMD_VALIDATE_DESC: '校验 serverless IaC yaml',
1074
- CMD_PLAN_DESC: '生成并展示部署计划',
1075
- CMD_DIFF_DESC: '展示配置与线上云环境的差异(plan 的别名)',
1116
+ CMD_DIFF_DESC: '展示配置与线上云环境的差异',
1117
+ CMD_PLAN_REMOVED: 'plan 命令已被移除;请改用 diff 命令——两者接受完全相同的选项和参数。迁移方式:将 si plan 替换为 si diff,所有参数保持不变。',
1076
1118
  CMD_DEPLOY_DESC: '部署 serverless IaC yaml',
1077
1119
  CMD_DESTROY_DESC: '销毁 serverless 资源栈',
1078
1120
  CMD_LOCAL_DESC: '本地运行 Serverless 应用进行调试',
@@ -33,6 +33,8 @@ const parseBackend = (raw) => {
33
33
  type: types_1.StateBackendType.BUCKET_STORE,
34
34
  bucket: stateManager.bucket,
35
35
  key: stateManager.key,
36
+ ...(stateManager.storageRegion ? { storageRegion: stateManager.storageRegion } : {}),
37
+ ...(stateManager.storageProvider ? { storageProvider: stateManager.storageProvider } : {}),
36
38
  };
37
39
  }
38
40
  if (type === types_1.StateBackendType.SAAS) {
@@ -77,6 +79,23 @@ const evaluateObject = (obj, ctx, iacVars) => {
77
79
  }
78
80
  return obj;
79
81
  };
82
+ const assertProviderOverrideResources = (iac) => {
83
+ const provider = iac.provider.name;
84
+ const unsupportedSections = provider === 'tencent'
85
+ ? ['events', 'tables']
86
+ : provider === 'volcengine'
87
+ ? ['databases', 'tables']
88
+ : [];
89
+ const unsupportedSection = unsupportedSections.find((section) => Object.keys(iac[section] ?? {}).length > 0);
90
+ const unsupportedDatabase = Object.entries(iac.databases ?? {}).find(([, database]) => provider === 'aliyun'
91
+ ? database.type === 'TDSQL_C_SERVERLESS'
92
+ : provider === 'tencent'
93
+ ? !['TDSQL_C_SERVERLESS', 'ELASTICSEARCH_SERVERLESS'].includes(database.type)
94
+ : false);
95
+ const resource = unsupportedSection ?? (unsupportedDatabase ? `databases.${unsupportedDatabase[0]}` : undefined);
96
+ if (resource)
97
+ throw new Error(lang_1.lang.__('EFFECTIVE_CONFIG_RESOURCE_UNSUPPORTED', { provider, resource }));
98
+ };
80
99
  const revalYaml = (iacLocation, ctx) => {
81
100
  validateExistence(iacLocation);
82
101
  const yamlContent = (0, node_fs_1.readFileSync)(iacLocation, 'utf8');
@@ -86,12 +105,14 @@ const revalYaml = (iacLocation, ctx) => {
86
105
  app: iacJson.app,
87
106
  service: iacJson.service,
88
107
  version: iacJson.version,
89
- provider: { ...iacJson.provider, name: iacJson.provider.name },
108
+ provider: { ...iacJson.provider, name: ctx.provider, region: ctx.region },
90
109
  };
91
- // staticFields are spread in before evaluation (identity fields are not template strings,
92
- // so this is a no-op) and again after to ensure evaluateObject never mangles them.
93
110
  const evaluatedIacJson = evaluateObject({ ...iacJson, ...staticFields }, ctx, iacJson.vars);
94
- const iac = transformYaml({ ...evaluatedIacJson, ...staticFields }, ctx.stage);
111
+ const resolved = { ...evaluatedIacJson, ...staticFields };
112
+ (0, validator_1.validateYaml)(resolved);
113
+ if (iacJson.provider.name !== ctx.provider)
114
+ assertProviderOverrideResources(resolved);
115
+ const iac = transformYaml(resolved, ctx.stage);
95
116
  if (iac.functions) {
96
117
  iac.functions = iac.functions.map((fn) => ({
97
118
  ...fn,
@@ -0,0 +1,82 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.planApigwDomains = void 0;
4
+ const node_crypto_1 = require("node:crypto");
5
+ const certUtils_1 = require("../../common/certUtils");
6
+ const domainUtils_1 = require("../../common/domainUtils");
7
+ const refreshCache_1 = require("../../common/refreshCache");
8
+ const lang_1 = require("../../lang");
9
+ const apigwTypes_1 = require("./apigwTypes");
10
+ const fingerprint = (value) => value ? (0, node_crypto_1.createHash)('sha256').update(value.replace(/\s/g, '')).digest('hex') : null;
11
+ /** Compare readable binding fields without exposing certificate contents or private keys. */
12
+ const planApigwDomains = async (context, client, groupId, domain, summaries, removeCertificate = false) => {
13
+ const primary = String(domain.domain_name);
14
+ const www = domain.www_bind_apex === true ? (0, domainUtils_1.deriveWwwDomain)(primary) : null;
15
+ const names = [primary, ...(www ? [www] : [])];
16
+ const redirect = (0, apigwTypes_1.inferProtocolConfig)(domain.protocol).isHttpRedirectToHttps ??
17
+ false;
18
+ const certificate = domain.certificate_id
19
+ ? (await (0, refreshCache_1.cachedRefreshRead)(context, `cas.getCertificate:${domain.certificate_id}`, () => client.cas.getCertificate(String(domain.certificate_id))))?.cert
20
+ : domain.certificate_body
21
+ ? (0, certUtils_1.readPemContent)(String(domain.certificate_body))
22
+ : undefined;
23
+ if (domain.certificate_id && !certificate)
24
+ throw new Error(lang_1.lang.__('CERT_REFERENCE_NOT_FOUND', { reference: String(domain.certificate_id) }));
25
+ const desiredFingerprint = certificate
26
+ ? fingerprint(certificate)
27
+ : removeCertificate
28
+ ? null
29
+ : undefined;
30
+ const entries = await Promise.all(names.map(async (name) => {
31
+ const summary = summaries?.find((entry) => entry.domainName === name);
32
+ // An omitted summary entry is not proof of absence. Confirm against the detail API.
33
+ const detail = !summary || certificate || removeCertificate
34
+ ? await (0, refreshCache_1.cachedRefreshRead)(context, `apigw.getDomain:${groupId}:${name}`, () => client.apigw.getDomain(groupId, name))
35
+ : undefined;
36
+ const exists = detail === null ? false : detail || summary ? true : undefined;
37
+ const actualFingerprint = detail?.certificateBody !== undefined ? fingerprint(detail.certificateBody) : undefined;
38
+ const before = {
39
+ ...(exists !== undefined ? { exists } : {}),
40
+ ...(summary?.isHttpRedirectToHttps !== undefined && exists !== false
41
+ ? { redirectToHttps: summary.isHttpRedirectToHttps }
42
+ : {}),
43
+ ...(desiredFingerprint !== undefined && actualFingerprint !== undefined
44
+ ? { certificateFingerprint: actualFingerprint }
45
+ : {}),
46
+ };
47
+ const after = {
48
+ ...(exists !== undefined ? { exists: true } : {}),
49
+ ...(summary?.isHttpRedirectToHttps !== undefined || exists === false
50
+ ? { redirectToHttps: redirect }
51
+ : {}),
52
+ ...(desiredFingerprint !== undefined &&
53
+ (actualFingerprint !== undefined || exists === false)
54
+ ? { certificateFingerprint: desiredFingerprint }
55
+ : {}),
56
+ };
57
+ const binding = exists === false ||
58
+ (summary?.isHttpRedirectToHttps !== undefined &&
59
+ summary.isHttpRedirectToHttps !== redirect);
60
+ const certificateChanged = desiredFingerprint !== undefined &&
61
+ (exists === false ||
62
+ (actualFingerprint !== undefined && actualFingerprint !== desiredFingerprint));
63
+ return {
64
+ name,
65
+ before,
66
+ after,
67
+ verified: exists === true &&
68
+ desiredFingerprint !== undefined &&
69
+ actualFingerprint === desiredFingerprint,
70
+ update: binding || certificateChanged
71
+ ? { exists: exists === true, binding, certificate: certificateChanged }
72
+ : undefined,
73
+ };
74
+ }));
75
+ return {
76
+ before: Object.fromEntries(entries.map((entry) => [entry.name, entry.before])),
77
+ after: Object.fromEntries(entries.map((entry) => [entry.name, entry.after])),
78
+ updates: Object.fromEntries(entries.flatMap((entry) => (entry.update ? [[entry.name, entry.update]] : []))),
79
+ certificateVerified: entries.every((entry) => entry.verified),
80
+ };
81
+ };
82
+ exports.planApigwDomains = planApigwDomains;
@@ -28,7 +28,10 @@ const executeSingleItem = async (context, item, eventsMap, serviceName, resolveR
28
28
  throw new Error(lang_1.lang.__('RESOURCE_EVENT_NOT_FOUND', { logicalId: item.logicalId }));
29
29
  }
30
30
  common_1.logger.info(lang_1.lang.__('UPDATING_RESOURCE', { resourceType: 'API Gateway resources', name: event.name }));
31
- const newState = await (0, apigwResource_1.updateApigwResource)(context, event, serviceName, resolveRoleArn, currentState, { repairDomain: item.driftReasons?.includes('PLAN_DRIFT_EVENT_DOMAIN') });
31
+ const newState = await (0, apigwResource_1.updateApigwResource)(context, event, serviceName, resolveRoleArn, currentState, {
32
+ repairDomain: item.driftReasons?.includes('PLAN_DRIFT_EVENT_DOMAIN'),
33
+ scope: item.gatewayUpdate,
34
+ });
32
35
  common_1.logger.info(lang_1.lang.__('RESOURCE_UPDATED', { resourceType: 'API Gateway resources', name: event.name }));
33
36
  return newState;
34
37
  }