@geek-fun/serverlessinsight 0.8.8 → 0.9.0

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 (52) hide show
  1. package/.serverlessinsight/state-cdn-flow-app-cdn-flow-service.json.backup +1 -1
  2. package/.serverlessinsight/state-iam-test-app-iam-test-service.json.backup +2 -2
  3. package/.serverlessinsight/state-insight-poc-app-insight-poc-tencent.json.backup +2 -2
  4. package/.serverlessinsight/state-insight-poc-app-log-insight-poc-tencent-log.json.backup +123 -0
  5. package/.serverlessinsight/state-insight-poc-deploy-app-insight-poc-deploy.json.backup +4 -4
  6. package/.serverlessinsight/state-insight-poc-destroy-app-insight-poc-destroy.json.backup +1 -1
  7. package/.serverlessinsight/state-insight-volc-app-insight-volc.json.backup +2 -2
  8. package/.serverlessinsight/state-insight-volc-nested-app-insight-volc-nested.json.backup +93 -0
  9. package/.serverlessinsight/state-nested-drift-app-nested-drift-service.json.backup +148 -0
  10. package/.serverlessinsight/state-role-reconcile-test-app-role-reconcile-test-service.json.backup +3 -3
  11. package/CHANGELOG.md +29 -0
  12. package/dist/package.json +1 -1
  13. package/dist/src/commands/deploy.js +3 -1
  14. package/dist/src/commands/index.js +25 -0
  15. package/dist/src/common/aliyunClient/fc3Operations.js +5 -0
  16. package/dist/src/common/aliyunClient/index.js +44 -35
  17. package/dist/src/common/constants.js +5 -1
  18. package/dist/src/common/imsClient.js +2 -2
  19. package/dist/src/common/nameBuilder.js +13 -1
  20. package/dist/src/common/planCompare.js +31 -1
  21. package/dist/src/common/planFormatter.js +69 -54
  22. package/dist/src/common/refreshPlanner.js +31 -8
  23. package/dist/src/lang/en.js +20 -6
  24. package/dist/src/lang/zh-CN.js +20 -6
  25. package/dist/src/stack/aliyunStack/apigwPlanner.js +26 -5
  26. package/dist/src/stack/aliyunStack/databasePlanner.js +6 -1
  27. package/dist/src/stack/aliyunStack/databaseResource.js +10 -2
  28. package/dist/src/stack/aliyunStack/deployer.js +30 -13
  29. package/dist/src/stack/aliyunStack/fc3Planner.js +46 -25
  30. package/dist/src/stack/aliyunStack/fc3Resource.js +137 -87
  31. package/dist/src/stack/aliyunStack/ossPlanner.js +6 -1
  32. package/dist/src/stack/aliyunStack/ossResource.js +9 -2
  33. package/dist/src/stack/aliyunStack/tablestorePlanner.js +2 -1
  34. package/dist/src/stack/aliyunStack/tablestoreResource.js +2 -1
  35. package/dist/src/stack/deploy.js +10 -4
  36. package/dist/src/stack/scfStack/cosPlanner.js +6 -1
  37. package/dist/src/stack/scfStack/cosResource.js +6 -2
  38. package/dist/src/stack/scfStack/deployer.js +21 -6
  39. package/dist/src/stack/scfStack/esServerlessPlanner.js +6 -1
  40. package/dist/src/stack/scfStack/esServerlessResource.js +5 -1
  41. package/dist/src/stack/scfStack/scfPlanner.js +26 -27
  42. package/dist/src/stack/scfStack/scfResource.js +6 -2
  43. package/dist/src/stack/scfStack/tdsqlcPlanner.js +6 -1
  44. package/dist/src/stack/scfStack/tdsqlcResource.js +5 -1
  45. package/dist/src/stack/volcengineStack/apigwPlanner.js +5 -1
  46. package/dist/src/stack/volcengineStack/deployer.js +15 -4
  47. package/dist/src/stack/volcengineStack/tosPlanner.js +6 -1
  48. package/dist/src/stack/volcengineStack/tosResource.js +10 -3
  49. package/dist/src/stack/volcengineStack/vefaasPlanner.js +39 -11
  50. package/dist/src/stack/volcengineStack/vefaasResource.js +5 -1
  51. package/dist/src/validator/semanticValidation.js +24 -0
  52. package/package.json +1 -1
@@ -76,6 +76,15 @@ __exportStar(require("./tablestoreOperations"), exports);
76
76
  __exportStar(require("./dnsOperations"), exports);
77
77
  __exportStar(require("./casOperations"), exports);
78
78
  __exportStar(require("./cdnOperations"), exports);
79
+ // Non-fc3 aliyun clients are synchronous management-plane RPCs — they share
80
+ // the short query-tier timeout budget (issue #234: sls ran on the SDK default
81
+ // 3s read timeout and a cold read aborted whole deploys; the deploy-tier
82
+ // budget would instead let a hung call stall a deploy for minutes).
83
+ const applyAliyunQueryTimeouts = (config) => {
84
+ config.connectTimeout = constants_1.ALIYUN_QUERY_CONNECT_TIMEOUT_MS;
85
+ config.readTimeout = constants_1.ALIYUN_QUERY_READ_TIMEOUT_MS;
86
+ return config;
87
+ };
79
88
  const initializeSdkClients = (context) => {
80
89
  const baseConfig = {
81
90
  accessKeyId: context.accessKeyId,
@@ -83,47 +92,47 @@ const initializeSdkClients = (context) => {
83
92
  regionId: context.region,
84
93
  securityToken: context.securityToken,
85
94
  };
86
- const fc3Config = new $OpenApi.Config(baseConfig);
87
- fc3Config.endpoint = `${context.accountId}.${context.region}.fc.aliyuncs.com`;
88
- fc3Config.connectTimeout = constants_1.ALIYUN_FC3_CONNECT_TIMEOUT_MS;
89
- fc3Config.readTimeout = constants_1.ALIYUN_FC3_READ_TIMEOUT_MS;
90
- const fc3Client = new fc20230330_1.default(fc3Config);
91
- const slsConfig = new $OpenApi.Config(baseConfig);
92
- slsConfig.endpoint = `${context.region}.log.aliyuncs.com`;
93
- const slsClient = new sls20201230_1.default(slsConfig);
94
- const ramConfig = new $OpenApi.Config(baseConfig);
95
- ramConfig.endpoint = 'ram.aliyuncs.com';
96
- const ramClient = new ram20150501_1.default(ramConfig);
97
- const ecsConfig = new $OpenApi.Config(baseConfig);
98
- ecsConfig.endpoint = `ecs.${context.region}.aliyuncs.com`;
99
- const ecsClient = new ecs20140526_1.default(ecsConfig);
100
- const nasConfig = new $OpenApi.Config(baseConfig);
101
- nasConfig.endpoint = `nas.${context.region}.aliyuncs.com`;
102
- const nasClient = new nas20170626_1.default(nasConfig);
95
+ const fc3Client = new fc20230330_1.default(Object.assign(new $OpenApi.Config(baseConfig), {
96
+ endpoint: `${context.accountId}.${context.region}.fc.aliyuncs.com`,
97
+ connectTimeout: constants_1.ALIYUN_FC3_CONNECT_TIMEOUT_MS,
98
+ readTimeout: constants_1.ALIYUN_FC3_READ_TIMEOUT_MS,
99
+ }));
100
+ const slsClient = new sls20201230_1.default(applyAliyunQueryTimeouts(Object.assign(new $OpenApi.Config(baseConfig), {
101
+ endpoint: `${context.region}.log.aliyuncs.com`,
102
+ })));
103
+ const ramClient = new ram20150501_1.default(applyAliyunQueryTimeouts(Object.assign(new $OpenApi.Config(baseConfig), {
104
+ endpoint: 'ram.aliyuncs.com',
105
+ })));
106
+ const ecsClient = new ecs20140526_1.default(applyAliyunQueryTimeouts(Object.assign(new $OpenApi.Config(baseConfig), {
107
+ endpoint: `ecs.${context.region}.aliyuncs.com`,
108
+ })));
109
+ const nasClient = new nas20170626_1.default(applyAliyunQueryTimeouts(Object.assign(new $OpenApi.Config(baseConfig), {
110
+ endpoint: `nas.${context.region}.aliyuncs.com`,
111
+ })));
103
112
  const ossClient = new ali_oss_1.default({
104
113
  accessKeyId: context.accessKeyId,
105
114
  accessKeySecret: context.accessKeySecret,
106
115
  region: `oss-${context.region}`,
107
116
  stsToken: context.securityToken,
108
117
  });
109
- const apigwConfig = new $OpenApi.Config(baseConfig);
110
- apigwConfig.endpoint = `apigateway.${context.region}.aliyuncs.com`;
111
- const apigwClient = new cloudapi20160714_1.default(apigwConfig);
112
- const rdsConfig = new $OpenApi.Config(baseConfig);
113
- rdsConfig.endpoint = `rds.aliyuncs.com`;
114
- const rdsClient = new rds20140815_1.default(rdsConfig);
115
- const esConfig = new $OpenApi.Config(baseConfig);
116
- esConfig.endpoint = `elasticsearch-serverless.${context.region}.aliyuncs.com`;
117
- const esClient = new es_serverless20230627_1.default(esConfig);
118
- const dnsConfig = new $OpenApi.Config(baseConfig);
119
- dnsConfig.endpoint = `alidns.aliyuncs.com`;
120
- const dnsClient = new alidns20150109_1.default(dnsConfig);
121
- const casConfig = new $OpenApi.Config(baseConfig);
122
- casConfig.endpoint = `cas.aliyuncs.com`;
123
- const casClient = new cas20200407_1.default(casConfig);
124
- const cdnConfig = new $OpenApi.Config(baseConfig);
125
- cdnConfig.endpoint = `cdn.aliyuncs.com`;
126
- const cdnClient = new cdn20180510_1.default(cdnConfig);
118
+ const apigwClient = new cloudapi20160714_1.default(applyAliyunQueryTimeouts(Object.assign(new $OpenApi.Config(baseConfig), {
119
+ endpoint: `apigateway.${context.region}.aliyuncs.com`,
120
+ })));
121
+ const rdsClient = new rds20140815_1.default(applyAliyunQueryTimeouts(Object.assign(new $OpenApi.Config(baseConfig), {
122
+ endpoint: `rds.aliyuncs.com`,
123
+ })));
124
+ const esClient = new es_serverless20230627_1.default(applyAliyunQueryTimeouts(Object.assign(new $OpenApi.Config(baseConfig), {
125
+ endpoint: `elasticsearch-serverless.${context.region}.aliyuncs.com`,
126
+ })));
127
+ const dnsClient = new alidns20150109_1.default(applyAliyunQueryTimeouts(Object.assign(new $OpenApi.Config(baseConfig), {
128
+ endpoint: `alidns.aliyuncs.com`,
129
+ })));
130
+ const casClient = new cas20200407_1.default(applyAliyunQueryTimeouts(Object.assign(new $OpenApi.Config(baseConfig), {
131
+ endpoint: `cas.aliyuncs.com`,
132
+ })));
133
+ const cdnClient = new cdn20180510_1.default(applyAliyunQueryTimeouts(Object.assign(new $OpenApi.Config(baseConfig), {
134
+ endpoint: `cdn.aliyuncs.com`,
135
+ })));
127
136
  return {
128
137
  fc3: fc3Client,
129
138
  sls: slsClient,
@@ -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_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.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';
@@ -8,6 +8,10 @@ exports.SI_BOOTSTRAP_BUCKET_PREFIX = 'si-bootstrap-artifacts';
8
8
  exports.SI_LOCALSTACK_SERVER_PORT = 4567;
9
9
  exports.ALIYUN_FC3_CONNECT_TIMEOUT_MS = 120000;
10
10
  exports.ALIYUN_FC3_READ_TIMEOUT_MS = 600000;
11
+ // Query-tier budget for synchronous management-plane RPCs (all non-fc3 aliyun
12
+ // clients): fast fail beats long hang — long waits are polling loops, not calls.
13
+ exports.ALIYUN_QUERY_CONNECT_TIMEOUT_MS = 10000; // 10 seconds
14
+ exports.ALIYUN_QUERY_READ_TIMEOUT_MS = 30000; // 30 seconds
11
15
  exports.FC3_CODE_INLINE_SIZE_LIMIT = 70 * 1024 * 1024; // 70MB threshold for OSS upload
12
16
  // OSS state backend timeouts
13
17
  exports.OSS_STATE_CONNECT_TIMEOUT_MS = 10000; // 10 seconds
@@ -48,8 +48,8 @@ const getIamInfo = async (context) => {
48
48
  regionId: context.region,
49
49
  endpoint: 'ims.aliyuncs.com',
50
50
  });
51
- imsConfig.connectTimeout = constants_1.ALIYUN_FC3_CONNECT_TIMEOUT_MS;
52
- imsConfig.readTimeout = constants_1.ALIYUN_FC3_READ_TIMEOUT_MS;
51
+ imsConfig.connectTimeout = constants_1.ALIYUN_QUERY_CONNECT_TIMEOUT_MS;
52
+ imsConfig.readTimeout = constants_1.ALIYUN_QUERY_READ_TIMEOUT_MS;
53
53
  const imsClient = new ims20190815_1.default(imsConfig);
54
54
  const { body } = await imsClient.getUser(new ims20190815.GetUserRequest({ userAccessKeyId: context.accessKeyId }));
55
55
  return body?.user
@@ -16,7 +16,7 @@
16
16
  * deploy set are additionally rejected up-front by semantic validation.
17
17
  */
18
18
  Object.defineProperty(exports, "__esModule", { value: true });
19
- exports.buildRolePolicyName = exports.buildFunctionRoleName = exports.CONSTRAINT_NAME_LIMITS = exports.buildConstrainedName = exports.stableHash = exports.DEFAULT_HASH_LENGTH = void 0;
19
+ exports.buildNasAccessGroupName = exports.buildRolePolicyName = exports.buildFunctionRoleName = exports.CONSTRAINT_NAME_LIMITS = exports.buildConstrainedName = exports.stableHash = exports.DEFAULT_HASH_LENGTH = void 0;
20
20
  const FNV_OFFSET_BASIS = 0x811c9dc5;
21
21
  const FNV_PRIME = 0x01000193;
22
22
  const SANITISERS = {
@@ -89,3 +89,15 @@ exports.buildFunctionRoleName = buildFunctionRoleName;
89
89
  /** Single source of truth for the execution policy name attached to a role. */
90
90
  const buildRolePolicyName = (roleName) => `${roleName}-policy`;
91
91
  exports.buildRolePolicyName = buildRolePolicyName;
92
+ /**
93
+ * Single source of truth for function-owned NAS access-group names. The raw
94
+ * mount path is flattened (slashes folded, leading dash trimmed) so every
95
+ * derivation site — create and update/repair alike — produces the identical
96
+ * group for the same config; deriving it inline is what caused the recreated
97
+ * target to bind to a never-created group (issue #234 M4).
98
+ *
99
+ * Deliberately not routed through buildConstrainedName: existing deployments
100
+ * must keep byte-identical names (stored-first on rename).
101
+ */
102
+ const buildNasAccessGroupName = (fnName, stage, mountPath) => `${fnName}-${stage}-nas-access-${mountPath.replace(/\//g, '-').replace(/^-/, '')}`;
103
+ exports.buildNasAccessGroupName = buildNasAccessGroupName;
@@ -1,6 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.jsonDocumentDiffers = exports.remoteDiffersFromDesired = void 0;
3
+ exports.computeRevertKeys = exports.mergeLiveBefore = exports.jsonDocumentDiffers = exports.remoteDiffersFromDesired = void 0;
4
4
  const hashUtils_1 = require("./hashUtils");
5
5
  /**
6
6
  * A desired value "declares" a dimension only when the executor would write it:
@@ -60,3 +60,33 @@ const jsonDocumentDiffers = (desired, cloud) => {
60
60
  }
61
61
  };
62
62
  exports.jsonDocumentDiffers = jsonDocumentDiffers;
63
+ /**
64
+ * Best-known "current live" display baseline (issue #246): the plan diff's
65
+ * `before` must always be cloud reality, not the stored intent. Live mapper
66
+ * output covers only the attributes the cloud API exposes, so stored
67
+ * definition keys the mapper never emits (codeHash, iam, ...) are carried
68
+ * over from the stored definition — live values win where readable, stored
69
+ * values fill the unreadable rest.
70
+ */
71
+ const mergeLiveBefore = (stored, live) => ({ ...stored, ...live });
72
+ exports.mergeLiveBefore = mergeLiveBefore;
73
+ /**
74
+ * Field-level drift signature (issue #246): top-level keys where the stored
75
+ * definition already matches the desired one while the live value does not —
76
+ * i.e. the difference on that key is entirely a cloud-side edit the config
77
+ * never asked for. All three sides should be passed through the same
78
+ * normalization the display uses, so keys line up with the rendered diff.
79
+ */
80
+ const computeRevertKeys = (stored, live, desired) => {
81
+ // Only keys the live read actually carries can claim a cloud-side edit —
82
+ // a desired-declared key the mapper never emits (codeHash, iam, ...) is an
83
+ // unreadable dimension, not a revert.
84
+ return Object.keys(live)
85
+ .filter((key) => {
86
+ const storedMatchesDesired = (0, hashUtils_1.attributesEqual)({ [key]: stored[key] }, { [key]: desired[key] });
87
+ const liveMatchesDesired = (0, hashUtils_1.attributesEqual)({ [key]: live[key] }, { [key]: desired[key] });
88
+ return storedMatchesDesired && !liveMatchesDesired;
89
+ })
90
+ .sort((a, b) => a.localeCompare(b));
91
+ };
92
+ exports.computeRevertKeys = computeRevertKeys;
@@ -28,8 +28,6 @@ const DEFAULT_CONFIG = {
28
28
  colorize: true,
29
29
  indentSize: 4,
30
30
  keyAlignWidth: 12,
31
- showUnchangedAttributes: false,
32
- maxUnchangedHidden: 5,
33
31
  };
34
32
  const isObject = (val) => typeof val === 'object' && val !== null && !Array.isArray(val);
35
33
  const isSimpleObject = (val) => {
@@ -142,9 +140,17 @@ const computeMaxKeyWidth = (diffs, baseIndent) => diffs.reduce((maxWidth, diff)
142
140
  : 0;
143
141
  return Math.max(maxWidth, keyWidth, childWidth);
144
142
  }, 0);
145
- const formatAttributeLines = (diff, indent, config, keyWidth) => {
143
+ const formatAttributeLines = (diff, indent, config, keyWidth, revertKeys) => {
146
144
  const spaces = ' '.repeat(indent);
147
145
  const alignedKey = (diff.key + ':').padEnd(keyWidth);
146
+ // Issue #246: a field whose stored value already matched the config while
147
+ // the cloud diverged is annotated at the line level — the resource block
148
+ // stays in place, only this line explains why it appears. Only leaf lines
149
+ // reach suffix (parent cases early-return on children), so a revert key
150
+ // with nested children never carries the annotation.
151
+ const suffix = (line) => revertKeys?.has(diff.key)
152
+ ? `${line} ${colorize(lang_1.lang.__('PLAN_REVERT_ANNOTATION'), 'CYAN', config.colorize)}`
153
+ : line;
148
154
  switch (diff.action) {
149
155
  case 'add': {
150
156
  if (diff.children && diff.children.length > 0) {
@@ -157,7 +163,7 @@ const formatAttributeLines = (diff, indent, config, keyWidth) => {
157
163
  const value = diff.isComputed
158
164
  ? colorize(lang_1.lang.__('PLAN_COMPUTED_VALUE'), 'CYAN', config.colorize)
159
165
  : formatValue(diff.after);
160
- return [colorize(`${spaces}${alignedKey} ${value}`, 'GREEN', config.colorize)];
166
+ return [suffix(colorize(`${spaces}${alignedKey} ${value}`, 'GREEN', config.colorize))];
161
167
  }
162
168
  case 'remove': {
163
169
  if (diff.children && diff.children.length > 0) {
@@ -168,7 +174,7 @@ const formatAttributeLines = (diff, indent, config, keyWidth) => {
168
174
  ];
169
175
  }
170
176
  return [
171
- colorize(`${spaces}${alignedKey} ${formatValue(diff.before)}`, 'RED', config.colorize),
177
+ suffix(colorize(`${spaces}${alignedKey} ${formatValue(diff.before)}`, 'RED', config.colorize)),
172
178
  ];
173
179
  }
174
180
  case 'change': {
@@ -182,7 +188,7 @@ const formatAttributeLines = (diff, indent, config, keyWidth) => {
182
188
  const beforeStr = formatValue(diff.before);
183
189
  const afterStr = formatValue(diff.after);
184
190
  return [
185
- colorize(`${spaces}${alignedKey} ${beforeStr} -> ${afterStr}`, 'YELLOW', config.colorize),
191
+ suffix(colorize(`${spaces}${alignedKey} ${beforeStr} -> ${afterStr}`, 'YELLOW', config.colorize)),
186
192
  ];
187
193
  }
188
194
  }
@@ -192,49 +198,68 @@ const ACTION_DESC = {
192
198
  update: 'PLAN_WILL_UPDATE',
193
199
  delete: 'PLAN_WILL_DESTROY',
194
200
  noop: 'PLAN_NO_CHANGES',
195
- refresh: 'PLAN_WILL_REFRESH',
196
201
  };
197
202
  const ACTION_SYMBOL = {
198
203
  create: '+',
199
204
  update: '~',
200
205
  delete: '-',
201
- refresh: '↻',
202
206
  };
203
207
  const ACTION_COLOR = {
204
208
  create: 'GREEN',
205
209
  update: 'YELLOW',
206
210
  delete: 'RED',
207
- refresh: 'CYAN',
208
211
  };
212
+ /**
213
+ * A create plan for a resource that also has a recorded `before` is a
214
+ * recreation (the cloud copy disappeared or was tainted) — rendered as a
215
+ * single `-/+` block showing the old→new fields, never as two separate
216
+ * add/remove blocks (issue #246 resource-paradigm invariant).
217
+ */
218
+ const isRecreate = (item) => item.action === 'create' && !!item.changes?.before;
209
219
  /* istanbul ignore next */
210
220
  const formatPlanItem = (item, config = DEFAULT_CONFIG) => {
211
- const descKey = ACTION_DESC[item.action] ?? 'PLAN_NO_CHANGES';
212
- const headerLine = ` # ${item.logicalId} ${lang_1.lang.__(descKey)}`;
213
221
  if (item.action === 'noop') {
214
- return headerLine;
222
+ // Unchanged resources are not rendered as blocks — they only surface in
223
+ // the plan summary count (issue #246 display spec).
224
+ return '';
215
225
  }
216
- const symbol = ACTION_SYMBOL[item.action] ?? ' ';
217
- const symbolColor = ACTION_COLOR[item.action] ?? 'RESET';
226
+ const recreate = isRecreate(item);
227
+ const descKey = recreate ? 'PLAN_WILL_RECREATE' : (ACTION_DESC[item.action] ?? 'PLAN_NO_CHANGES');
228
+ const headerLine = ` # ${item.logicalId} ${lang_1.lang.__(descKey)}`;
229
+ const symbol = recreate ? '-/+' : (ACTION_SYMBOL[item.action] ?? ' ');
230
+ const symbolColor = recreate ? 'YELLOW' : (ACTION_COLOR[item.action] ?? 'RESET');
218
231
  const resourceLine = colorize(` ${symbol} ${item.logicalId}:`, symbolColor, config.colorize);
219
- // A drifted update is caused by an out-of-config cloud edit — surface that
220
- // so it doesn't read like an ordinary config change.
221
- const driftedLine = item.drifted && item.action !== 'delete'
222
- ? [colorize(` # ${lang_1.lang.__('PLAN_DRIFTED_MARKER')}`, 'CYAN', config.colorize)]
223
- : [];
232
+ // Probe-level drift (role policy, logstore, ...) has no attribute-level
233
+ // diff to show — each reason becomes its own explanatory line.
234
+ const reasonLines = (item.driftReasons ?? []).map((reason) => colorize(` # ${lang_1.lang.__(reason)}`, 'CYAN', config.colorize));
224
235
  if (!item.changes) {
225
- return [headerLine, resourceLine, ...driftedLine].join('\n');
236
+ // No changes payload at all: the drift marker is the only explanation
237
+ // available (fallback — planners normally attach changes or reasons).
238
+ const driftedLine = item.drifted && reasonLines.length === 0
239
+ ? [colorize(` # ${lang_1.lang.__('PLAN_DRIFTED_MARKER')}`, 'CYAN', config.colorize)]
240
+ : [];
241
+ return [headerLine, resourceLine, ...reasonLines, ...driftedLine].join('\n');
226
242
  }
227
243
  const { diffs, unchangedCount } = (0, exports.computeAttributeDiffs)(item.changes.before, item.changes.after);
228
244
  const keyWidth = Math.max(config.keyAlignWidth, computeMaxKeyWidth(diffs, config.indentSize));
245
+ const revertKeys = new Set(item.revertKeys ?? []);
229
246
  const attrLines = diffs.length > 0
230
- ? diffs.flatMap((diff) => formatAttributeLines(diff, config.indentSize, config, keyWidth))
247
+ ? diffs.flatMap((diff) => formatAttributeLines(diff, config.indentSize, config, keyWidth, revertKeys))
231
248
  : [];
232
- const hiddenLine = unchangedCount > 0 && !config.showUnchangedAttributes
249
+ const hiddenLine = unchangedCount > 0
233
250
  ? [
234
251
  colorize(` # ${lang_1.lang.__('PLAN_UNCHANGED_ATTRS', { count: String(unchangedCount) })}`, 'DIM', config.colorize),
235
252
  ]
236
253
  : [];
237
- return [headerLine, resourceLine, ...driftedLine, ...attrLines, ...hiddenLine].join('\n');
254
+ // Invariant backstop (issue #246): a drifted item must always explain
255
+ // itself — attribute lines, reasons, or as a last resort the generic
256
+ // marker. Planners attach at least one of these for every drifted item.
257
+ const driftedFallback = item.drifted && attrLines.length === 0 && reasonLines.length === 0
258
+ ? [colorize(` # ${lang_1.lang.__('PLAN_DRIFTED_MARKER')}`, 'CYAN', config.colorize)]
259
+ : [];
260
+ return [headerLine, resourceLine, ...reasonLines, ...attrLines, ...hiddenLine, ...driftedFallback]
261
+ .filter((line) => line.length > 0)
262
+ .join('\n');
238
263
  };
239
264
  exports.formatPlanItem = formatPlanItem;
240
265
  /* istanbul ignore next */
@@ -242,39 +267,29 @@ const formatPlan = (items, config = DEFAULT_CONFIG) => {
242
267
  if (items.length === 0) {
243
268
  return lang_1.lang.__('NO_CHANGES_INFRASTRUCTURE_UP_TO_DATE');
244
269
  }
245
- const createItems = items.filter((i) => i.action === 'create');
246
- const updateItems = items.filter((i) => i.action === 'update');
247
- const deleteItems = items.filter((i) => i.action === 'delete');
248
- const refreshItems = items.filter((i) => i.action === 'refresh');
249
- const noopItems = items.filter((i) => i.action === 'noop');
250
- const actionItems = [
251
- ...createItems,
252
- ...updateItems,
253
- ...deleteItems,
254
- ...refreshItems,
255
- ...noopItems,
256
- ];
257
- const header = [
258
- `${lang_1.lang.__('PLAN_HEADER')}\n`,
259
- colorize(lang_1.lang.__('PLAN_LEGEND_CREATE'), 'GREEN', config.colorize),
260
- colorize(lang_1.lang.__('PLAN_LEGEND_UPDATE'), 'YELLOW', config.colorize),
261
- colorize(lang_1.lang.__('PLAN_LEGEND_DESTROY'), 'RED', config.colorize),
262
- '',
263
- ];
264
- const itemLines = actionItems.flatMap((item) => [(0, exports.formatPlanItem)(item, config), '']);
265
- const driftedCount = items.filter((i) => i.drifted && i.action !== 'delete').length;
266
- const driftedSummary = driftedCount > 0
267
- ? [
268
- colorize(lang_1.lang.__('PLAN_DRIFTED_SUMMARY', { driftedCount: String(driftedCount) }), 'CYAN', config.colorize),
269
- '',
270
- ]
271
- : [];
270
+ // Resource paradigm (issue #246): render blocks in the planner's domain
271
+ // order, one block per resource, never regrouped by action. Unchanged
272
+ // resources only surface in the summary count.
273
+ const unchangedCount = items.filter((i) => i.action === 'noop').length;
274
+ const itemLines = items
275
+ .filter((i) => i.action !== 'noop')
276
+ .flatMap((item) => {
277
+ const block = (0, exports.formatPlanItem)(item, config);
278
+ return block ? [block, ''] : [];
279
+ });
280
+ const recreateCount = items.filter(isRecreate).length;
281
+ const addCount = items.filter((i) => i.action === 'create' && !isRecreate(i)).length;
282
+ const modifyCount = items.filter((i) => i.action === 'update').length;
283
+ const removeCount = items.filter((i) => i.action === 'delete').length;
284
+ const header = [`${lang_1.lang.__('PLAN_HEADER')}\n`];
272
285
  const summary = lang_1.lang.__('PLAN_SUMMARY', {
273
- createCount: String(createItems.length),
274
- updateCount: String(updateItems.length),
275
- deleteCount: String(deleteItems.length),
286
+ addCount: String(addCount),
287
+ modifyCount: String(modifyCount),
288
+ removeCount: String(removeCount),
289
+ recreateCount: String(recreateCount),
290
+ unchangedCount: String(unchangedCount),
276
291
  });
277
- return [...header, ...itemLines, ...driftedSummary, summary].join('\n');
292
+ return [...header, ...itemLines, summary].join('\n');
278
293
  };
279
294
  exports.formatPlan = formatPlan;
280
295
  /* istanbul ignore next */
@@ -3,6 +3,8 @@ Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.planRefreshedResource = exports.decideRefreshedExistsAction = void 0;
4
4
  const hashUtils_1 = require("./hashUtils");
5
5
  const planCompare_1 = require("./planCompare");
6
+ const logger_1 = require("./logger");
7
+ const lang_1 = require("../lang");
6
8
  const decideRefreshedExistsAction = async (args) => {
7
9
  const remote = await args.read();
8
10
  if (!remote) {
@@ -14,11 +16,16 @@ const decideRefreshedExistsAction = async (args) => {
14
16
  }
15
17
  const remoteDiffers = (0, planCompare_1.remoteDiffersFromDesired)(attributes, args.desiredDefinition);
16
18
  if (args.definitionChanged || remoteDiffers) {
17
- return { action: 'update', drifted: true };
19
+ return { action: 'update', drifted: true, liveAttributes: attributes };
18
20
  }
19
21
  const extra = await args.extraUpdate?.();
20
22
  if (extra?.update) {
21
- return { action: 'update', drifted: extra.drifted };
23
+ return {
24
+ action: 'update',
25
+ drifted: extra.drifted,
26
+ liveAttributes: attributes,
27
+ ...(extra.reason ? { driftReasons: [extra.reason] } : {}),
28
+ };
22
29
  }
23
30
  return { action: 'noop' };
24
31
  };
@@ -28,8 +35,12 @@ exports.decideRefreshedExistsAction = decideRefreshedExistsAction;
28
35
  * no-state-probe / exists-refresh decision chain of the simple planners
29
36
  * (buckets, tables, databases). Function and gateway planners keep their
30
37
  * custom flows (role probes, trigger reconciliation, config normalization).
31
- * Read failures on the exists path degrade to a create plan — the pre-existing
32
- * planner behavior, preserved verbatim.
38
+ *
39
+ * Issue #246 display contract: a drift/intent update's `changes.before` is
40
+ * always cloud reality — live attributes merged over the stored definition
41
+ * (stored fills the keys the cloud mapper never emits) — so every update
42
+ * renders a complete live→desired field diff, and `revertKeys` marks the
43
+ * fields whose difference is purely an out-of-config cloud edit.
33
44
  */
34
45
  const planRefreshedResource = async (args) => {
35
46
  const { logicalId, resourceType, currentState, desiredDefinition } = args;
@@ -81,24 +92,36 @@ const planRefreshedResource = async (args) => {
81
92
  logicalId,
82
93
  action: 'create',
83
94
  resourceType,
84
- changes: { before: normalize(currentDefinition), after: desiredDefinition },
95
+ changes: { before: normalizedCurrent, after: desiredDefinition },
85
96
  drifted: true,
86
97
  };
87
98
  }
99
+ const normalizedLive = normalize(decision.liveAttributes);
100
+ const revertKeys = (0, planCompare_1.computeRevertKeys)(normalizedCurrent, normalizedLive, normalizedDesired);
88
101
  return {
89
102
  logicalId,
90
103
  action: 'update',
91
104
  resourceType,
92
- changes: { before: normalizedCurrent, after: normalizedDesired },
105
+ changes: {
106
+ before: normalize((0, planCompare_1.mergeLiveBefore)(currentDefinition, normalizedLive)),
107
+ after: normalizedDesired,
108
+ },
93
109
  ...(decision.drifted ? { drifted: true } : {}),
110
+ ...(revertKeys.length ? { revertKeys } : {}),
111
+ ...(decision.driftReasons?.length ? { driftReasons: decision.driftReasons } : {}),
94
112
  };
95
113
  }
96
- catch {
114
+ catch (error) {
115
+ logger_1.logger.warn(lang_1.lang.__('PLAN_LIVE_READ_FAILED', {
116
+ logicalId,
117
+ error: error instanceof Error ? error.message : String(error),
118
+ }));
97
119
  return {
98
120
  logicalId,
99
121
  action: 'create',
100
122
  resourceType,
101
- changes: { before: normalize(currentDefinition), after: desiredDefinition },
123
+ changes: { before: normalizedCurrent, after: normalizedDesired },
124
+ drifted: true,
102
125
  };
103
126
  }
104
127
  };
@@ -109,17 +109,29 @@ exports.en = {
109
109
  PLAN_WILL_CREATE: 'will be created',
110
110
  PLAN_WILL_UPDATE: 'will be updated in-place',
111
111
  PLAN_WILL_DESTROY: 'will be destroyed',
112
- PLAN_WILL_REFRESH: 'will be refreshed',
112
+ PLAN_WILL_RECREATE: 'will be recreated',
113
113
  PLAN_NO_CHANGES: 'no changes',
114
114
  PLAN_HEADER: 'ServerlessInsight will perform the following actions:',
115
- PLAN_LEGEND_CREATE: ' + create',
116
- PLAN_LEGEND_UPDATE: ' ~ update in-place',
117
- PLAN_LEGEND_DESTROY: ' - destroy',
118
- PLAN_SUMMARY: 'Plan: {{createCount}} to add, {{updateCount}} to change, {{deleteCount}} to destroy.',
115
+ PLAN_SUMMARY: 'Plan: {{addCount}} add, {{modifyCount}} modify, {{removeCount}} remove, {{recreateCount}} recreate, {{unchangedCount}} unchanged.',
119
116
  PLAN_UNCHANGED_ATTRS: '({{count}} unchanged attributes hidden)',
120
117
  PLAN_COMPUTED_VALUE: '(known after deploy)',
118
+ PLAN_REVERT_ANNOTATION: '(changed in the cloud, will be restored to config)',
121
119
  PLAN_DRIFTED_MARKER: '(drifted — cloud changed outside of this config, will be reconciled)',
122
- PLAN_DRIFTED_SUMMARY: 'Drift: {{driftedCount}} resource(s) changed in the cloud outside of this config.',
120
+ PLAN_LIVE_READ_FAILED: 'Failed to read live state for {{logicalId}}; planning a create instead: {{error}}',
121
+ PLAN_DRIFT_ROLE_MISSING: 'IAM role missing in the cloud',
122
+ PLAN_DRIFT_ROLE_POLICY: 'IAM role policy changed in the cloud',
123
+ PLAN_DRIFT_LOGSTORE: 'function log resources changed in the cloud',
124
+ PLAN_DRIFT_SG_RULES: 'security group rules changed in the cloud',
125
+ PLAN_DRIFT_NAS_MOUNT: 'NAS mount target deleted in the cloud',
126
+ PLAN_DRIFT_TLS_TOPIC: 'log topic configuration changed in the cloud',
127
+ PLAN_DRIFT_CLS_TOPIC: 'log topic configuration changed in the cloud',
128
+ PLAN_DRIFT_TRIGGERS: 'API triggers changed in the cloud',
129
+ RESOURCE_EXISTS_NOT_OWNED: '{{resourceType}} {{resourceName}} already exists in provider but is not owned by this stack (missing {{tagKey}} tag). Refusing to create — resolve manually.',
130
+ RESOURCE_EXISTS_NOT_OWNED_ADOPT: '{{resourceType}} {{resourceName}} already exists in provider but is not owned by this stack (missing {{tagKey}} tag). Refusing to adopt — resolve manually.',
131
+ TABLESTORE_EXISTS_UNVERIFIABLE: 'Table {{tableName}} already exists in provider but ownership cannot be verified (Tablestore does not support table-level tags). Refusing to adopt — resolve manually.',
132
+ TABLESTORE_EXISTS_UNVERIFIABLE_PROBE: 'Table {{tableName}} already exists in provider but ownership cannot be verified (no table-level tags). Refusing to adopt — resolve manually.',
133
+ TAINTED_RECOVERY_SKIP_CREATE: '{{resourceType}} {{resourceName}} already exists in provider (tainted recovery), skipping create and refreshing state',
134
+ OWNERSHIP_VERIFYING: '{{resourceType}} {{resourceName}} already exists in provider, verifying ownership tag before adopting',
123
135
  // TDSQL-C database messages
124
136
  TDSQL_CLUSTER_CREATION_INITIATED: 'TDSQL-C cluster creation initiated',
125
137
  TDSQL_CLUSTER_CREATION_FAILED: 'Failed to create TDSQL-C cluster',
@@ -426,6 +438,8 @@ exports.en = {
426
438
  // Pre-deploy semantic validation (issue #222)
427
439
  PARSE_BACKEND_BUCKET_STORE_FIELDS_REQUIRED: 'Backend type BUCKET_STORE requires both "bucket" and "key" fields',
428
440
  SEMANTIC_DUPLICATE_TRIGGER: 'Duplicate trigger in event "{{eventKey}}": {{method}} {{path}} is defined more than once',
441
+ SEMANTIC_CONTAINER_CODE_CONFLICT: 'Function "{{fnKey}}" cannot define both "container" and "code" — they are mutually exclusive sources',
442
+ SEMANTIC_FUNCTION_SOURCE_REQUIRED: 'Function "{{fnKey}}" must define either "code" or "container"',
429
443
  SEMANTIC_DUPLICATE_GENERATED_API_NAME: 'Generated API Gateway apiName "{{apiName}}" collides between "{{firstPath}}" and "{{secondPath}}" in this deployment; shorten the event name or differentiate trigger method/path',
430
444
  SEMANTIC_DUPLICATE_ROUTE_NAME: 'Generated API Gateway route name "{{routeName}}" collides between "{{firstPath}}" and "{{secondPath}}" in this deployment; shorten the event name or differentiate trigger method/path',
431
445
  SEMANTIC_UNRESOLVED_FUNCTION_BACKEND: 'Trigger backend "{{reference}}" in event "{{eventKey}}" does not match any function definition in the configuration',
@@ -109,17 +109,29 @@ exports.zhCN = {
109
109
  PLAN_WILL_CREATE: '将被创建',
110
110
  PLAN_WILL_UPDATE: '将就地更新',
111
111
  PLAN_WILL_DESTROY: '将被销毁',
112
- PLAN_WILL_REFRESH: '将被刷新',
112
+ PLAN_WILL_RECREATE: '将被重建',
113
113
  PLAN_NO_CHANGES: '无变更',
114
114
  PLAN_HEADER: 'ServerlessInsight 将执行以下操作:',
115
- PLAN_LEGEND_CREATE: ' + 创建',
116
- PLAN_LEGEND_UPDATE: ' ~ 就地更新',
117
- PLAN_LEGEND_DESTROY: ' - 销毁',
118
- PLAN_SUMMARY: '计划: 新增 {{createCount}} 个,变更 {{updateCount}} 个,销毁 {{deleteCount}} 个。',
115
+ PLAN_SUMMARY: '计划: 新增 {{addCount}},变更 {{modifyCount}},移除 {{removeCount}},重建 {{recreateCount}},无变更 {{unchangedCount}}。',
119
116
  PLAN_UNCHANGED_ATTRS: '({{count}} 个未变更属性已隐藏)',
120
117
  PLAN_COMPUTED_VALUE: '(部署后可知)',
118
+ PLAN_REVERT_ANNOTATION: '(云端已改,将按配置恢复)',
121
119
  PLAN_DRIFTED_MARKER: '(云端已漂移——与本配置不一致,将按配置纠正)',
122
- PLAN_DRIFTED_SUMMARY: '漂移: {{driftedCount}} 个资源在云端被本配置之外的变更修改。',
120
+ PLAN_LIVE_READ_FAILED: '读取 {{logicalId}} 云端状态失败,降级为创建计划: {{error}}',
121
+ PLAN_DRIFT_ROLE_MISSING: '云端 IAM 角色缺失',
122
+ PLAN_DRIFT_ROLE_POLICY: '云端 IAM 角色策略被修改',
123
+ PLAN_DRIFT_LOGSTORE: '云端函数日志资源被修改',
124
+ PLAN_DRIFT_SG_RULES: '云端安全组规则被修改',
125
+ PLAN_DRIFT_NAS_MOUNT: '云端 NAS 挂载点被删除',
126
+ PLAN_DRIFT_TLS_TOPIC: '云端日志主题配置被修改',
127
+ PLAN_DRIFT_CLS_TOPIC: '云端日志主题配置被修改',
128
+ PLAN_DRIFT_TRIGGERS: '云端 API 触发器被修改',
129
+ RESOURCE_EXISTS_NOT_OWNED: '{{resourceType}} {{resourceName}} 已存在于云端但归属本 stack(缺少 {{tagKey}} 标签),拒绝创建——请手动处理。',
130
+ RESOURCE_EXISTS_NOT_OWNED_ADOPT: '{{resourceType}} {{resourceName}} 已存在于云端但归属本 stack(缺少 {{tagKey}} 标签),拒绝收养——请手动处理。',
131
+ TABLESTORE_EXISTS_UNVERIFIABLE: '表 {{tableName}} 已存在于云端但无法校验归属(Tablestore 不支持表级标签),拒绝收养——请手动处理。',
132
+ TABLESTORE_EXISTS_UNVERIFIABLE_PROBE: '表 {{tableName}} 已存在于云端但无法校验归属(无表级标签),拒绝收养——请手动处理。',
133
+ TAINTED_RECOVERY_SKIP_CREATE: '{{resourceType}} {{resourceName}} 已存在(tainted 恢复),跳过创建并刷新状态',
134
+ OWNERSHIP_VERIFYING: '{{resourceType}} {{resourceName}} 已存在,正在校验归属标签后收养',
123
135
  // TDSQL-C 数据库消息
124
136
  TDSQL_CLUSTER_CREATION_INITIATED: 'TDSQL-C 集群创建已启动',
125
137
  TDSQL_CLUSTER_CREATION_FAILED: '创建 TDSQL-C 集群失败',
@@ -423,6 +435,8 @@ exports.zhCN = {
423
435
  // Pre-deploy semantic validation (issue #222)
424
436
  PARSE_BACKEND_BUCKET_STORE_FIELDS_REQUIRED: '后端类型 BUCKET_STORE 需要同时提供 "bucket" 和 "key" 字段',
425
437
  SEMANTIC_DUPLICATE_TRIGGER: '事件 "{{eventKey}}" 中存在重复触发器: {{method}} {{path}} 定义了不止一次',
438
+ SEMANTIC_CONTAINER_CODE_CONFLICT: '函数 "{{fnKey}}" 不能同时定义 "container" 与 "code"——两者互斥',
439
+ SEMANTIC_FUNCTION_SOURCE_REQUIRED: '函数 "{{fnKey}}" 必须定义 "code" 或 "container" 之一',
426
440
  SEMANTIC_DUPLICATE_GENERATED_API_NAME: '生成的 API Gateway apiName "{{apiName}}" 在 "{{firstPath}}" 与 "{{secondPath}}" 之间发生冲突;请缩短事件名称或区分触发器的 method/path',
427
441
  SEMANTIC_DUPLICATE_ROUTE_NAME: '生成的 API Gateway route name "{{routeName}}" 在 "{{firstPath}}" 与 "{{secondPath}}" 之间发生冲突;请缩短事件名称或区分触发器的 method/path',
428
442
  SEMANTIC_UNRESOLVED_FUNCTION_BACKEND: '事件 "{{eventKey}}" 的触发器后端 "{{reference}}" 未匹配到配置中的任何函数定义',