@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
@@ -181,8 +181,10 @@ const formatResourceOutput = (logicalId, resource) => {
181
181
  }
182
182
  return [];
183
183
  };
184
- const loadLocalState = (provider, app, service, stage, baseDir) => {
185
- return (0, common_1.loadState)(provider, app, service, stage, baseDir);
184
+ const loadLocalState = async (provider, app, service, stage, baseDir) => {
185
+ const backend = (0, stateBackend_1.createLocalStateBackend)({ provider, app, service, stage, region: (0, common_1.getContext)().region }, { baseDir, markerAction: 'off' });
186
+ const state = await backend.loadState();
187
+ return { state, source: backend.readStateSource() };
186
188
  };
187
189
  const readLocalLock = (app, service, baseDir) => {
188
190
  const statePath = (0, common_1.getStatePath)(app, service, baseDir);
@@ -206,19 +208,22 @@ const show = async (options) => {
206
208
  let stateLocation;
207
209
  let stateLocationDisplay;
208
210
  let usingRemoteBackend = false;
211
+ let stateSource;
209
212
  const backendType = options.iac?.backend?.type;
210
213
  const shouldUseRemoteBackend = backendType === backend_1.StateBackendType.BUCKET_STORE ||
211
214
  backendType === backend_1.StateBackendType.SAAS ||
212
215
  !backendType;
213
216
  if (shouldUseRemoteBackend) {
214
217
  try {
215
- // Read-only command: a migrated state only warns here.
216
218
  const backend = (0, stateBackend_1.createStateBackend)(options.iac.backend, {
217
219
  ...context,
220
+ stage,
218
221
  declaredOrg: options.iac.org,
219
222
  migrationMarker: 'warn',
223
+ mode: 'read-only',
220
224
  });
221
- state = await backend.loadState(context.provider, context.app, context.service, stage);
225
+ state = await backend.loadState();
226
+ stateSource = backend.readStateSource();
222
227
  lockInfo = await backend.readLock();
223
228
  usingRemoteBackend = true;
224
229
  stateLocation =
@@ -233,7 +238,9 @@ const show = async (options) => {
233
238
  else {
234
239
  logger_1.logger.warn(lang_1.lang.__('SHOW_REMOTE_BACKEND_FALLBACK', { error: String(error) }));
235
240
  }
236
- state = loadLocalState(context.provider, context.app, context.service, stage, baseDir);
241
+ const local = await loadLocalState(context.provider, context.app, context.service, stage, baseDir);
242
+ state = local.state;
243
+ stateSource = local.source;
237
244
  // A local copy of a MIGRATED state is stale by definition — showing it
238
245
  // after a remote failure would mislead the user (decision D-3/D-4).
239
246
  if ((0, migrationMarker_1.isMigratedToSaas)(state)) {
@@ -246,7 +253,9 @@ const show = async (options) => {
246
253
  stateLocation === SAAS_STATE_LOCATION ? lang_1.lang.__('SHOW_BACKEND_SAAS') : stateLocation;
247
254
  }
248
255
  else {
249
- state = loadLocalState(context.provider, context.app, context.service, stage, baseDir);
256
+ const local = await loadLocalState(context.provider, context.app, context.service, stage, baseDir);
257
+ state = local.state;
258
+ stateSource = local.source;
250
259
  lockInfo = readLocalLock(context.app, context.service, baseDir);
251
260
  stateLocation = (0, common_1.getStatePath)(context.app, context.service, baseDir);
252
261
  stateLocationDisplay = stateLocation;
@@ -265,11 +274,13 @@ const show = async (options) => {
265
274
  app: state.app,
266
275
  service: state.service,
267
276
  stage,
277
+ region: context.region,
268
278
  ...(state.serial !== undefined ? { serial: state.serial } : {}),
269
279
  ...(state.lineage !== undefined ? { lineage: state.lineage } : {}),
270
280
  ...(state.managedBy !== undefined ? { managedBy: state.managedBy } : {}),
271
281
  stateLocation,
272
282
  backend: backendKind,
283
+ stateSource,
273
284
  locked: !!lockInfo,
274
285
  lock: lockInfo ? { ...lockInfo } : null,
275
286
  resources: resources,
@@ -0,0 +1,185 @@
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.deploymentStateHash = exports.patchAggregateScope = exports.mergeAggregateScope = exports.assertDeploymentState = exports.projectAggregateScope = exports.aggregatePartition = exports.readAggregateDocument = exports.emptyDeploymentState = exports.aggregateStateCorruptError = exports.AGGREGATE_STATE_VERSION = void 0;
7
+ const node_crypto_1 = __importDefault(require("node:crypto"));
8
+ const types_1 = require("../types");
9
+ const lang_1 = require("../lang");
10
+ const stateScope_1 = require("./stateScope");
11
+ const saasProtocol_1 = require("./saasProtocol");
12
+ exports.AGGREGATE_STATE_VERSION = types_1.CURRENT_STATE_VERSION;
13
+ const record = (value) => typeof value === 'object' && value !== null && !Array.isArray(value);
14
+ const aggregateStateCorruptError = (location, cause) => Object.assign(new types_1.StateCorruptError(location, cause), {
15
+ message: lang_1.lang.__('STATE_AGGREGATE_INVALID'),
16
+ });
17
+ exports.aggregateStateCorruptError = aggregateStateCorruptError;
18
+ const corrupt = (location) => {
19
+ throw (0, exports.aggregateStateCorruptError)(location);
20
+ };
21
+ const ownEntry = (values, key) => values && Object.prototype.hasOwnProperty.call(values, key) ? values[key] : undefined;
22
+ const emptyDeploymentState = (scope) => {
23
+ const normalized = (0, stateScope_1.normalizeScope)(scope);
24
+ return {
25
+ version: types_1.CURRENT_STATE_VERSION,
26
+ provider: normalized.provider,
27
+ app: normalized.app,
28
+ service: normalized.service,
29
+ scope: { stage: normalized.stage, region: normalized.region },
30
+ stages: { [normalized.stage]: { resources: {}, shared: {} } },
31
+ resources: {},
32
+ };
33
+ };
34
+ exports.emptyDeploymentState = emptyDeploymentState;
35
+ const readAggregateDocument = (raw, scope, location) => {
36
+ if (!record(raw))
37
+ return corrupt(location);
38
+ if (raw.version !== exports.AGGREGATE_STATE_VERSION) {
39
+ throw new types_1.StateVersionError(String(raw.version ?? ''), exports.AGGREGATE_STATE_VERSION);
40
+ }
41
+ if (raw.app !== scope.app || raw.service !== scope.service) {
42
+ throw Object.assign(new types_1.StateCorruptError(location, undefined), {
43
+ message: lang_1.lang.__('STATE_SCOPED_IDENTITY_MISMATCH'),
44
+ });
45
+ }
46
+ if (!record(raw.stages) || 'provider' in raw || 'resources' in raw)
47
+ return corrupt(location);
48
+ Object.entries(raw.stages).forEach(([stage, entry]) => {
49
+ (0, stateScope_1.validateScopeKeyPart)(stage, 'stage');
50
+ if (!record(entry) || !record(entry.providers))
51
+ return corrupt(location);
52
+ Object.entries(entry.providers).forEach(([provider, providerEntry]) => {
53
+ (0, stateScope_1.validateScopeKeyPart)(provider, 'provider');
54
+ if (!record(providerEntry) || !record(providerEntry.regions))
55
+ return corrupt(location);
56
+ Object.entries(providerEntry.regions).forEach(([region, partition]) => {
57
+ (0, stateScope_1.validateScopeKeyPart)(region, 'region');
58
+ if (region !== region.toLowerCase() ||
59
+ !record(partition) ||
60
+ !record(partition.resources) ||
61
+ (partition.shared !== undefined && !record(partition.shared)) ||
62
+ ['app', 'service', 'provider', 'scope', 'version', 'stages'].some((key) => key in partition) ||
63
+ typeof partition.lineage !== 'string' ||
64
+ partition.lineage.length === 0 ||
65
+ !Number.isInteger(partition.serial) ||
66
+ Number(partition.serial) < 1) {
67
+ return corrupt(location);
68
+ }
69
+ });
70
+ });
71
+ });
72
+ return raw;
73
+ };
74
+ exports.readAggregateDocument = readAggregateDocument;
75
+ const aggregatePartition = (document, scope) => {
76
+ const stage = ownEntry(document?.stages, scope.stage);
77
+ const provider = ownEntry(stage?.providers, scope.provider);
78
+ return ownEntry(provider?.regions, scope.region);
79
+ };
80
+ exports.aggregatePartition = aggregatePartition;
81
+ const projectAggregateScope = (document, scope) => {
82
+ const normalized = (0, stateScope_1.normalizeScope)(scope);
83
+ const partition = (0, exports.aggregatePartition)(document, normalized);
84
+ const empty = (0, exports.emptyDeploymentState)(normalized);
85
+ if (!partition)
86
+ return empty;
87
+ const { resources, shared = {}, ...metadata } = partition;
88
+ return {
89
+ ...empty,
90
+ ...metadata,
91
+ stages: { [normalized.stage]: { resources, shared } },
92
+ resources,
93
+ };
94
+ };
95
+ exports.projectAggregateScope = projectAggregateScope;
96
+ const assertDeploymentState = (state, scope) => {
97
+ const normalized = (0, stateScope_1.normalizeScope)(scope);
98
+ if (state.version !== types_1.CURRENT_STATE_VERSION) {
99
+ throw new types_1.StateVersionError(state.version, types_1.CURRENT_STATE_VERSION);
100
+ }
101
+ if (state.app !== normalized.app ||
102
+ state.service !== normalized.service ||
103
+ state.provider !== normalized.provider ||
104
+ (state.scope &&
105
+ (state.scope.stage !== normalized.stage ||
106
+ state.scope.region.toLowerCase() !== normalized.region))) {
107
+ throw new types_1.StateScopeMismatchError(normalized, {
108
+ app: state.app,
109
+ service: state.service,
110
+ provider: state.provider,
111
+ stage: state.scope?.stage,
112
+ region: state.scope?.region,
113
+ });
114
+ }
115
+ };
116
+ exports.assertDeploymentState = assertDeploymentState;
117
+ const METADATA_KEYS = ['orgId', 'appId', 'serviceId', 'managedBy', 'migration'];
118
+ const mergeAggregateScope = (document, scope, state, options = {}) => {
119
+ const normalized = (0, stateScope_1.normalizeScope)(scope);
120
+ (0, exports.assertDeploymentState)(state, normalized);
121
+ const previous = (0, exports.aggregatePartition)(document, normalized);
122
+ const metadata = Object.fromEntries(METADATA_KEYS.flatMap((key) => {
123
+ const value = previous ? previous[key] : state[key];
124
+ return value === undefined ? [] : [[key, value]];
125
+ }));
126
+ const partition = {
127
+ ...metadata,
128
+ lineage: previous?.lineage ?? state.lineage ?? node_crypto_1.default.randomUUID(),
129
+ serial: options.preserveRevision ? (state.serial ?? 1) : (previous?.serial ?? 0) + 1,
130
+ resources: state.resources,
131
+ shared: state.stages[normalized.stage]?.shared ?? previous?.shared ?? {},
132
+ };
133
+ const stages = document?.stages ?? {};
134
+ const providers = ownEntry(stages, normalized.stage)?.providers ?? {};
135
+ const regions = ownEntry(providers, normalized.provider)?.regions ?? {};
136
+ return {
137
+ ...document,
138
+ version: exports.AGGREGATE_STATE_VERSION,
139
+ app: normalized.app,
140
+ service: normalized.service,
141
+ stages: {
142
+ ...stages,
143
+ [normalized.stage]: {
144
+ providers: {
145
+ ...providers,
146
+ [normalized.provider]: { regions: { ...regions, [normalized.region]: partition } },
147
+ },
148
+ },
149
+ },
150
+ };
151
+ };
152
+ exports.mergeAggregateScope = mergeAggregateScope;
153
+ const patchAggregateScope = (document, selected, patch) => {
154
+ const scope = (0, stateScope_1.normalizeScope)(selected);
155
+ if (Object.keys(patch).some((key) => !METADATA_KEYS.includes(key))) {
156
+ throw new Error(lang_1.lang.__('STATE_PARTITION_PATCH_INVALID'));
157
+ }
158
+ const current = (0, exports.projectAggregateScope)(document, scope);
159
+ const next = (0, exports.mergeAggregateScope)(document, scope, current);
160
+ const partition = (0, exports.aggregatePartition)(next, scope);
161
+ const patched = Object.fromEntries(Object.entries({ ...partition, ...patch }).filter(([, value]) => value !== undefined));
162
+ return {
163
+ ...next,
164
+ stages: {
165
+ ...next.stages,
166
+ [scope.stage]: {
167
+ providers: {
168
+ ...next.stages[scope.stage].providers,
169
+ [scope.provider]: {
170
+ regions: {
171
+ ...next.stages[scope.stage].providers[scope.provider].regions,
172
+ [scope.region]: patched,
173
+ },
174
+ },
175
+ },
176
+ },
177
+ },
178
+ };
179
+ };
180
+ exports.patchAggregateScope = patchAggregateScope;
181
+ const deploymentStateHash = (state) => {
182
+ const { resources: _projection, ...persisted } = state;
183
+ return (0, saasProtocol_1.hashSaasState)(persisted);
184
+ };
185
+ exports.deploymentStateHash = deploymentStateHash;
@@ -0,0 +1,247 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.createAggregateStore = void 0;
4
+ const types_1 = require("../types");
5
+ const lang_1 = require("../lang");
6
+ const aggregateState_1 = require("./aggregateState");
7
+ const stateScope_1 = require("./stateScope");
8
+ const migrationMarker_1 = require("./migrationMarker");
9
+ const constants_1 = require("./constants");
10
+ const regionalMigration_1 = require("./regionalMigration");
11
+ const logger_1 = require("./logger");
12
+ const createAggregateStore = (io, selected, options) => {
13
+ const scope = (0, stateScope_1.normalizeScope)(selected);
14
+ const scopeKey = options.key;
15
+ const markerAction = options.markerAction;
16
+ let source = 'empty';
17
+ let plannedHash;
18
+ let legacyRegionBinding;
19
+ const validateDocument = (raw) => {
20
+ if (typeof raw !== 'object' || raw === null || Array.isArray(raw)) {
21
+ throw (0, aggregateState_1.aggregateStateCorruptError)(options.key);
22
+ }
23
+ const value = raw;
24
+ if (value.app !== scope.app || value.service !== scope.service) {
25
+ throw new types_1.StateScopeMismatchError(scope, {
26
+ app: String(value.app ?? ''),
27
+ service: String(value.service ?? ''),
28
+ provider: typeof value.provider === 'string' ? value.provider : scope.provider,
29
+ stage: scope.stage,
30
+ region: scope.region,
31
+ });
32
+ }
33
+ if (value.version === aggregateState_1.AGGREGATE_STATE_VERSION) {
34
+ return (0, aggregateState_1.readAggregateDocument)(value, scope, options.key);
35
+ }
36
+ if (value.version !== '3.0') {
37
+ throw new types_1.StateVersionError(String(value.version ?? ''), aggregateState_1.AGGREGATE_STATE_VERSION);
38
+ }
39
+ if (typeof value.provider !== 'string' ||
40
+ typeof value.stages !== 'object' ||
41
+ value.stages === null ||
42
+ Array.isArray(value.stages)) {
43
+ throw (0, aggregateState_1.aggregateStateCorruptError)(options.key);
44
+ }
45
+ return value;
46
+ };
47
+ const readStoredDocument = async () => {
48
+ let raw;
49
+ try {
50
+ raw = await io.read(options.key);
51
+ }
52
+ catch (error) {
53
+ if (!(error instanceof SyntaxError))
54
+ throw error;
55
+ const backup = await io.read(`${options.key}.backup`);
56
+ if (backup === null)
57
+ throw (0, aggregateState_1.aggregateStateCorruptError)(options.key, error);
58
+ return validateDocument(backup);
59
+ }
60
+ if (raw === null) {
61
+ const backup = await io.read(`${options.key}.backup`);
62
+ if (backup !== null)
63
+ return validateDocument(backup);
64
+ return null;
65
+ }
66
+ return validateDocument(raw);
67
+ };
68
+ const readDocument = async () => {
69
+ const migration = await io.read(`${options.key}${constants_1.REGIONAL_MIGRATION_SUFFIX}`);
70
+ if (migration !== null) {
71
+ if (typeof migration !== 'object' || !migration || !('phase' in migration))
72
+ throw (0, aggregateState_1.aggregateStateCorruptError)(options.key);
73
+ if (migration.phase !== 'complete') {
74
+ const opId = 'opId' in migration ? String(migration.opId) : options.key;
75
+ throw new Error(lang_1.lang.__('REGIONAL_MIGRATION_PENDING', { opId }));
76
+ }
77
+ }
78
+ const document = await readStoredDocument();
79
+ if (migration && !document)
80
+ throw (0, aggregateState_1.aggregateStateCorruptError)(scopeKey);
81
+ return document;
82
+ };
83
+ const isAggregate = (document) => document.version === aggregateState_1.AGGREGATE_STATE_VERSION;
84
+ const loadState = async (captureBase = true) => {
85
+ const document = await readDocument();
86
+ if (document && !isAggregate(document)) {
87
+ source = 'legacy';
88
+ (0, migrationMarker_1.enforceMigrationMarker)(document, options.markerAction);
89
+ if (document.managedBy === migrationMarker_1.MANAGED_BY_SAAS) {
90
+ return { ...document, resources: document.stages[scope.stage]?.resources ?? {} };
91
+ }
92
+ const empty = (0, aggregateState_1.projectAggregateScope)(null, scope);
93
+ const selected = document.stages[scope.stage];
94
+ const selectRegion = (resources) => Object.fromEntries(Object.entries(resources ?? {}).filter(([, resource]) => {
95
+ const region = resource.region?.trim() || legacyRegionBinding;
96
+ if (!region) {
97
+ throw new Error(lang_1.lang.__('REGIONAL_MIGRATION_UNKNOWN_REGION_REQUIRED'));
98
+ }
99
+ return (0, stateScope_1.canonicalizeRegion)(region) === scope.region;
100
+ }));
101
+ const resources = document.provider === scope.provider ? selectRegion(selected?.resources) : {};
102
+ const shared = document.provider === scope.provider ? selectRegion(selected?.shared) : {};
103
+ const metadata = Object.fromEntries(['orgId', 'appId', 'serviceId', 'managedBy']
104
+ .filter((key) => document[key] !== undefined)
105
+ .map((key) => [key, document[key]]));
106
+ return { ...empty, ...metadata, stages: { [scope.stage]: { resources, shared } }, resources };
107
+ }
108
+ source = (0, aggregateState_1.aggregatePartition)(document, scope) ? 'scoped' : 'empty';
109
+ const state = (0, aggregateState_1.projectAggregateScope)(document, scope);
110
+ (0, migrationMarker_1.enforceMigrationMarker)(state, options.markerAction);
111
+ if (captureBase && plannedHash === undefined)
112
+ plannedHash = (0, aggregateState_1.deploymentStateHash)(state);
113
+ return state;
114
+ };
115
+ const probeWriteReadiness = async () => {
116
+ const document = await readDocument();
117
+ if (document && !isAggregate(document)) {
118
+ source = 'legacy';
119
+ (0, migrationMarker_1.enforceMigrationMarker)(document, options.markerAction);
120
+ return {
121
+ ready: false,
122
+ source,
123
+ reason: lang_1.lang.__('STATE_STORE_UPGRADE_REQUIRED', { location: options.key }),
124
+ };
125
+ }
126
+ source = (0, aggregateState_1.aggregatePartition)(document, scope) ? 'scoped' : 'empty';
127
+ (0, migrationMarker_1.enforceMigrationMarker)((0, aggregateState_1.projectAggregateScope)(document, scope), options.markerAction);
128
+ return { ready: true, source };
129
+ };
130
+ const writableDocument = async () => {
131
+ const document = await readDocument();
132
+ if (document && !isAggregate(document)) {
133
+ throw new Error(lang_1.lang.__('STATE_STORE_UPGRADE_REQUIRED', { location: options.key }));
134
+ }
135
+ return document;
136
+ };
137
+ const writeDocument = async (previous, next) => {
138
+ if (previous && options.backupWrites)
139
+ await io.write(`${options.key}.backup`, previous);
140
+ await io.write(options.key, next);
141
+ source = 'scoped';
142
+ };
143
+ const upgradeLegacyState = async (options = {}) => {
144
+ const binding = options.bindUnknownRegion === undefined
145
+ ? undefined
146
+ : (0, stateScope_1.canonicalizeRegion)(options.bindUnknownRegion);
147
+ legacyRegionBinding = binding;
148
+ const paths = {
149
+ legacyKey: scopeKey,
150
+ backupKey: (opId) => `${scopeKey}.pre-upgrade-${opId}.json`,
151
+ reportKey: (opId) => `${scopeKey}.upgrade-report-${opId}.json`,
152
+ };
153
+ const pending = await (0, regionalMigration_1.readRegionalMigrationJournal)(io, paths);
154
+ if (pending &&
155
+ (!pending.plan ||
156
+ !pending.options ||
157
+ typeof pending.plan.opId !== 'string' ||
158
+ !['applying', 'complete'].includes(pending.phase))) {
159
+ throw (0, aggregateState_1.aggregateStateCorruptError)(scopeKey);
160
+ }
161
+ const document = await readStoredDocument();
162
+ if (pending?.phase === 'complete' && (!document || !isAggregate(document))) {
163
+ throw new Error(lang_1.lang.__('REGIONAL_MIGRATION_SOURCE_CHANGED'));
164
+ }
165
+ if (pending?.phase !== 'applying' && (!document || isAggregate(document)))
166
+ return;
167
+ const legacy = pending?.phase === 'applying'
168
+ ? await io.read(paths.backupKey(pending.plan.opId))
169
+ : document;
170
+ if (!legacy)
171
+ throw new Error(lang_1.lang.__('REGIONAL_MIGRATION_BACKUP_MISSING', { opId: pending?.plan.opId ?? scopeKey }));
172
+ if (isAggregate(legacy))
173
+ throw (0, aggregateState_1.aggregateStateCorruptError)(scopeKey);
174
+ validateDocument(legacy);
175
+ if (legacy.managedBy === migrationMarker_1.MANAGED_BY_SAAS) {
176
+ (0, migrationMarker_1.enforceMigrationMarker)(legacy, markerAction);
177
+ return;
178
+ }
179
+ if (pending &&
180
+ (pending.options.app !== scope.app ||
181
+ pending.options.service !== scope.service ||
182
+ (binding !== undefined && binding !== pending.options.bindUnknownRegion))) {
183
+ throw new Error(lang_1.lang.__('REGIONAL_MIGRATION_PENDING', { opId: pending.plan.opId }));
184
+ }
185
+ const migrationOptions = pending?.options ?? {
186
+ app: scope.app,
187
+ service: scope.service,
188
+ provider: legacy.provider,
189
+ ...(binding ? { bindUnknownRegion: binding } : {}),
190
+ };
191
+ const plan = pending?.plan ?? (0, regionalMigration_1.planRegionalMigration)(legacy, migrationOptions);
192
+ if (plan.unknown.length && !migrationOptions.bindUnknownRegion) {
193
+ plan.unknown.forEach((item) => logger_1.logger.warn(lang_1.lang.__('REGIONAL_MIGRATION_UNKNOWN_ITEM', item)));
194
+ throw new Error(lang_1.lang.__('REGIONAL_MIGRATION_UNKNOWN_REGION_REQUIRED'));
195
+ }
196
+ if (!options.dryRun)
197
+ await (0, regionalMigration_1.applyRegionalMigration)(io, legacy, paths, plan, migrationOptions);
198
+ };
199
+ return {
200
+ upgradeLegacyState,
201
+ loadState,
202
+ probeWriteReadiness,
203
+ readStateSource: () => source,
204
+ clearPlanBase: () => {
205
+ plannedHash = undefined;
206
+ },
207
+ verifyPlanBase: async () => {
208
+ const readiness = await probeWriteReadiness();
209
+ if (!readiness.ready)
210
+ throw new Error(readiness.reason);
211
+ if (plannedHash !== undefined &&
212
+ (0, aggregateState_1.deploymentStateHash)(await loadState(false)) !== plannedHash) {
213
+ throw new Error(lang_1.lang.__('STATE_PLAN_BASE_CHANGED'));
214
+ }
215
+ },
216
+ saveState: async (state) => {
217
+ const document = await writableDocument();
218
+ (0, migrationMarker_1.enforceMigrationMarker)((0, aggregateState_1.projectAggregateScope)(document, scope), options.markerAction);
219
+ await writeDocument(document, (0, aggregateState_1.mergeAggregateScope)(document, scope, state));
220
+ },
221
+ patchPersisted: async (patch) => {
222
+ const existing = await readDocument();
223
+ if (existing &&
224
+ !isAggregate(existing) &&
225
+ markerAction === 'off' &&
226
+ existing.managedBy === migrationMarker_1.MANAGED_BY_SAAS &&
227
+ Object.keys(patch).length === 1 &&
228
+ Object.prototype.hasOwnProperty.call(patch, 'managedBy') &&
229
+ patch.managedBy === undefined) {
230
+ const { managedBy: _owner, ...legacy } = existing;
231
+ if (options.backupWrites)
232
+ await io.write(`${scopeKey}.backup`, existing);
233
+ await io.write(scopeKey, { ...legacy, serial: (legacy.serial ?? 0) + 1 });
234
+ return;
235
+ }
236
+ const document = await writableDocument();
237
+ const current = document ?? {
238
+ version: aggregateState_1.AGGREGATE_STATE_VERSION,
239
+ app: scope.app,
240
+ service: scope.service,
241
+ stages: {},
242
+ };
243
+ await writeDocument(document, (0, aggregateState_1.patchAggregateScope)(current, scope, patch));
244
+ },
245
+ };
246
+ };
247
+ exports.createAggregateStore = createAggregateStore;
@@ -358,6 +358,36 @@ const createApigwOperations = (apigwClient, dnsClient, _context) => {
358
358
  logger_1.logger.error(`\n${separator}\n${lang_1.lang.__('APIGW_VERIFICATION_NEXT_STEPS')}\n${lang_1.lang.__('APIGW_VERIFICATION_STEP1')}\n${lang_1.lang.__('APIGW_VERIFICATION_STEP2')}\n${separator}\n`);
359
359
  };
360
360
  const operations = {
361
+ deleteDomainCertificate: async (groupId, domainName) => {
362
+ try {
363
+ const response = await apigwClient.describeDomain(new cloudapi.DescribeDomainRequest({ groupId, domainName }));
364
+ if (!response.body?.domainName ||
365
+ (!response.body.certificateId && response.body.certificateBody)) {
366
+ throw new Error(lang_1.lang.__('APIGW_DOMAIN_READ_INVALID', { domainId: domainName }));
367
+ }
368
+ if (!response.body.certificateId)
369
+ return;
370
+ await apigwClient.deleteDomainCertificate(new cloudapi.DeleteDomainCertificateRequest({
371
+ groupId,
372
+ domainName,
373
+ certificateId: response.body.certificateId,
374
+ }));
375
+ }
376
+ catch (error) {
377
+ if (!(0, exports.isApigwNotFoundError)(error))
378
+ throw error;
379
+ }
380
+ },
381
+ setDomainCertificate: async (config) => {
382
+ await apigwClient.setDomainCertificate(new cloudapi.SetDomainCertificateRequest({
383
+ groupId: config.groupId,
384
+ domainName: config.domainName,
385
+ certificateName: config.certificateName,
386
+ certificateBody: config.certificateBody,
387
+ certificatePrivateKey: config.certificatePrivateKey,
388
+ }));
389
+ logger_1.logger.info(lang_1.lang.__('APIGW_DOMAIN_CERTIFICATE_UPDATED', { domain: config.domainName }));
390
+ },
361
391
  /**
362
392
  * Create an API Gateway group
363
393
  */
@@ -385,7 +415,7 @@ const createApigwOperations = (apigwClient, dnsClient, _context) => {
385
415
  throw new Error(lang_1.lang.__('APIGW_DOMAIN_READ_INVALID', { domainId: domainName }));
386
416
  return {
387
417
  domainName: response.body.domainName,
388
- certificateBody: response.body.certificateBody ?? null,
418
+ certificateBody: response.body.certificateBody || (response.body.certificateId ? undefined : null),
389
419
  };
390
420
  }
391
421
  catch (error) {
@@ -1008,14 +1038,7 @@ const createApigwOperations = (apigwClient, dnsClient, _context) => {
1008
1038
  });
1009
1039
  const setCertificate = async () => {
1010
1040
  if (config.certificateName && config.certificateBody && config.certificatePrivateKey) {
1011
- const certRequest = new cloudapi.SetDomainCertificateRequest({
1012
- groupId: config.groupId,
1013
- domainName: config.domainName,
1014
- certificateName: config.certificateName,
1015
- certificateBody: config.certificateBody,
1016
- certificatePrivateKey: config.certificatePrivateKey,
1017
- });
1018
- await apigwClient.setDomainCertificate(certRequest);
1041
+ await operations.setDomainCertificate(config);
1019
1042
  }
1020
1043
  };
1021
1044
  try {
@@ -2,6 +2,12 @@
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.validateApiKey = exports.createApiClient = exports.ApiError = void 0;
4
4
  const lang_1 = require("../lang");
5
+ const HTTP_ERROR_KEYS = {
6
+ 401: 'API_ERROR_401',
7
+ 403: 'API_ERROR_403',
8
+ 404: 'API_ERROR_404',
9
+ 409: 'API_ERROR_409',
10
+ };
5
11
  /**
6
12
  * API error carrying the HTTP status so callers can distinguish "not found"
7
13
  * (legitimate empty state on first deploy) from network/5xx failures, which
@@ -9,10 +15,12 @@ const lang_1 = require("../lang");
9
15
  */
10
16
  class ApiError extends Error {
11
17
  status;
18
+ code;
12
19
  constructor(message, status) {
13
20
  super(message);
14
21
  this.name = 'ApiError';
15
22
  this.status = status;
23
+ this.code = HTTP_ERROR_KEYS[status] ?? 'API_ERROR_UNKNOWN';
16
24
  }
17
25
  }
18
26
  exports.ApiError = ApiError;
@@ -40,18 +48,33 @@ const camelizeKeys = (value) => {
40
48
  }
41
49
  return result;
42
50
  };
43
- const handleHttpError = (response) => {
44
- const status = response.status;
45
- if (status === 401)
46
- throw new ApiError(lang_1.lang.__('API_ERROR_401'), 401);
47
- if (status === 403)
48
- throw new ApiError(lang_1.lang.__('API_ERROR_403'), 403);
49
- if (status === 404)
50
- throw new ApiError(lang_1.lang.__('API_ERROR_404'), 404);
51
- if (status === 409) {
52
- throw new ApiError(lang_1.lang.__('API_ERROR_409', { message: `HTTP Error ${status}` }), 409);
51
+ const readErrorMessages = async (response) => {
52
+ try {
53
+ const body = await response.json();
54
+ if (!body || typeof body !== 'object' || !('messages' in body) || !Array.isArray(body.messages))
55
+ return undefined;
56
+ return (body.messages
57
+ .filter((message) => typeof message === 'string' && !!message.trim())
58
+ .map((message) => message.trim())
59
+ .join('\n') || undefined);
60
+ }
61
+ catch {
62
+ return undefined;
63
+ }
64
+ };
65
+ const formatHttpError = (status, details) => {
66
+ const key = HTTP_ERROR_KEYS[status] ?? 'API_ERROR_UNKNOWN';
67
+ const message = details ?? `HTTP Error ${status}`;
68
+ if (key === 'API_ERROR_UNKNOWN') {
69
+ return lang_1.lang.__(key, { status: String(status), message });
53
70
  }
54
- throw new ApiError(lang_1.lang.__('API_ERROR_UNKNOWN', { status: String(status), message: `HTTP Error ${status}` }), status);
71
+ if (key === 'API_ERROR_409')
72
+ return lang_1.lang.__(key, { message });
73
+ return [lang_1.lang.__(key), details].filter(Boolean).join('\n');
74
+ };
75
+ const handleHttpError = async (response) => {
76
+ const details = await readErrorMessages(response);
77
+ throw new ApiError(formatHttpError(response.status, details), response.status);
55
78
  };
56
79
  const buildRequestInit = (method, headers, body) => ({
57
80
  method: method.toUpperCase(),
@@ -88,7 +111,7 @@ const createApiClient = (options) => {
88
111
  throw new Error(lang_1.lang.__('CREDENTIAL_NETWORK_ERROR'));
89
112
  }
90
113
  if (!response.ok) {
91
- handleHttpError(response);
114
+ await handleHttpError(response);
92
115
  }
93
116
  try {
94
117
  return unwrapResponse(await response.json());
@@ -1,6 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.CLS_TOPIC_POLL_MAX_ATTEMPTS = exports.CLS_TOPIC_POLL_INTERVAL_MS = exports.SCF_STATUS_POLL_MAX_ATTEMPTS = exports.SCF_STATUS_POLL_INTERVAL_MS = exports.RAM_ROLE_PROPAGATION_DELAY_MS = exports.APIGW_DNS_PUBLIC_RESOLUTION_DELAY_MS = exports.APIGW_DNS_PUBLIC_RESOLUTION_MAX_ATTEMPTS = exports.APIGW_DOMAIN_BIND_RETRY_DELAY_MS = exports.APIGW_DOMAIN_BIND_MAX_RETRIES = exports.DNS_PROPAGATION_DELAY_MS = exports.DNS_PROPAGATION_MAX_ATTEMPTS = exports.DOMAIN_BIND_RETRY_DELAY_MS = exports.DOMAIN_BIND_MAX_RETRIES = exports.STALE_LOCK_THRESHOLD = exports.DEFAULT_LOCK_RETRY_DELAY = exports.DEFAULT_LOCK_TIMEOUT = exports.LOCK_FILE_SUFFIX = exports.OSS_STATE_REQUEST_TIMEOUT_MS = exports.OSS_STATE_CONNECT_TIMEOUT_MS = exports.FC3_CODE_INLINE_SIZE_LIMIT = exports.ALIYUN_QUERY_READ_TIMEOUT_MS = exports.ALIYUN_QUERY_CONNECT_TIMEOUT_MS = exports.ALIYUN_FC3_READ_TIMEOUT_MS = exports.ALIYUN_FC3_CONNECT_TIMEOUT_MS = exports.SI_LOCALSTACK_SERVER_PORT = exports.SI_BOOTSTRAP_BUCKET_PREFIX = exports.SI_BOOTSTRAP_FC_PREFIX = exports.OSS_DEPLOYMENT_TIMEOUT = exports.CODE_ZIP_SIZE_LIMIT = void 0;
3
+ exports.REGIONAL_MIGRATION_SUFFIX = exports.CLS_TOPIC_POLL_MAX_ATTEMPTS = exports.CLS_TOPIC_POLL_INTERVAL_MS = exports.SCF_STATUS_POLL_MAX_ATTEMPTS = exports.SCF_STATUS_POLL_INTERVAL_MS = exports.RAM_ROLE_PROPAGATION_DELAY_MS = exports.APIGW_DNS_PUBLIC_RESOLUTION_DELAY_MS = exports.APIGW_DNS_PUBLIC_RESOLUTION_MAX_ATTEMPTS = exports.APIGW_DOMAIN_BIND_RETRY_DELAY_MS = exports.APIGW_DOMAIN_BIND_MAX_RETRIES = exports.DNS_PROPAGATION_DELAY_MS = exports.DNS_PROPAGATION_MAX_ATTEMPTS = exports.DOMAIN_BIND_RETRY_DELAY_MS = exports.DOMAIN_BIND_MAX_RETRIES = exports.STALE_LOCK_THRESHOLD = exports.DEFAULT_LOCK_RETRY_DELAY = exports.DEFAULT_LOCK_TIMEOUT = exports.LOCK_FILE_SUFFIX = exports.OSS_STATE_REQUEST_TIMEOUT_MS = exports.OSS_STATE_CONNECT_TIMEOUT_MS = exports.FC3_CODE_INLINE_SIZE_LIMIT = exports.ALIYUN_QUERY_READ_TIMEOUT_MS = exports.ALIYUN_QUERY_CONNECT_TIMEOUT_MS = exports.ALIYUN_FC3_READ_TIMEOUT_MS = exports.ALIYUN_FC3_CONNECT_TIMEOUT_MS = exports.SI_LOCALSTACK_SERVER_PORT = exports.SI_BOOTSTRAP_BUCKET_PREFIX = exports.SI_BOOTSTRAP_FC_PREFIX = exports.OSS_DEPLOYMENT_TIMEOUT = exports.CODE_ZIP_SIZE_LIMIT = void 0;
4
4
  exports.CODE_ZIP_SIZE_LIMIT = 300 * 1000; // 300 KB - code package size limit for inline deployment
5
5
  exports.OSS_DEPLOYMENT_TIMEOUT = 3000; // in seconds
6
6
  exports.SI_BOOTSTRAP_FC_PREFIX = 'si-bootstrap-api';
@@ -49,3 +49,4 @@ exports.SCF_STATUS_POLL_MAX_ATTEMPTS = 20; // up to 60 seconds
49
49
  // queryable via DescribeTopics until the platform finishes provisioning)
50
50
  exports.CLS_TOPIC_POLL_INTERVAL_MS = 3000; // 3 seconds
51
51
  exports.CLS_TOPIC_POLL_MAX_ATTEMPTS = 20; // up to 60 seconds
52
+ exports.REGIONAL_MIGRATION_SUFFIX = '.state-upgrade.json';