@geek-fun/serverlessinsight 0.9.1 → 0.9.3

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 (124) 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 +4 -8
  4. package/.serverlessinsight/state-insight-poc-app-log-insight-poc-tencent-log.json.backup +3 -8
  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-poc-timer-app-insight-poc-timer.json.backup +132 -0
  8. package/.serverlessinsight/state-insight-volc-app-insight-volc.json.backup +2 -2
  9. package/.serverlessinsight/state-insight-volc-nested-app-insight-volc-nested.json.backup +3 -3
  10. package/.serverlessinsight/state-nested-drift-app-nested-drift-service.json.backup +20 -5
  11. package/.serverlessinsight/state-role-reconcile-test-app-role-reconcile-test-service.json.backup +3 -3
  12. package/AGENTS.md +10 -0
  13. package/CHANGELOG.md +51 -0
  14. package/README.md +103 -13
  15. package/README.zh-CN.md +73 -13
  16. package/codecov +0 -0
  17. package/codecov.SHA256SUM +1 -0
  18. package/codecov.SHA256SUM.sig +16 -0
  19. package/dist/package.json +1 -1
  20. package/dist/src/commands/index.js +92 -24
  21. package/dist/src/commands/local.js +16 -3
  22. package/dist/src/commands/plan.js +31 -4
  23. package/dist/src/commands/schema.js +24 -0
  24. package/dist/src/commands/show.js +64 -10
  25. package/dist/src/commands/validate.js +34 -2
  26. package/dist/src/common/aliyunClient/apigwOperations.js +17 -1
  27. package/dist/src/common/aliyunClient/fc3Operations.js +39 -2
  28. package/dist/src/common/aliyunClient/ossOperations.js +214 -221
  29. package/dist/src/common/bucketPolicy.js +63 -0
  30. package/dist/src/common/constants.js +7 -1
  31. package/dist/src/common/domainUtils.js +4 -1
  32. package/dist/src/common/functionDefinition.js +25 -0
  33. package/dist/src/common/index.js +4 -0
  34. package/dist/src/common/jsonOutput.js +82 -0
  35. package/dist/src/common/logger.js +6 -3
  36. package/dist/src/common/nameBuilder.js +3 -1
  37. package/dist/src/common/noColor.js +9 -0
  38. package/dist/src/common/planCapabilities.js +119 -0
  39. package/dist/src/common/planCompare.js +119 -66
  40. package/dist/src/common/planFormatter.js +34 -20
  41. package/dist/src/common/planRedaction.js +26 -0
  42. package/dist/src/common/refreshPlanner.js +66 -21
  43. package/dist/src/common/siCron.js +415 -0
  44. package/dist/src/common/stateBackend/saasStateBackend.js +5 -4
  45. package/dist/src/common/tencentClient/cosOperations.js +326 -322
  46. package/dist/src/common/tencentClient/scfOperations.js +11 -2
  47. package/dist/src/common/tencentClient/tdsqlcOperations.js +6 -11
  48. package/dist/src/common/triggerMapper.js +16 -1
  49. package/dist/src/common/volcengineClient/apigwOperations.js +82 -0
  50. package/dist/src/common/volcengineClient/iamOperations.js +27 -3
  51. package/dist/src/common/volcengineClient/tosOperations.js +62 -56
  52. package/dist/src/common/volcengineClient/vefaasOperations.js +45 -0
  53. package/dist/src/lang/en.js +70 -3
  54. package/dist/src/lang/index.js +36 -1
  55. package/dist/src/lang/zh-CN.js +70 -3
  56. package/dist/src/parser/eventParser.js +1 -0
  57. package/dist/src/parser/functionParser.js +48 -2
  58. package/dist/src/stack/aliyunStack/apigwExecutor.js +1 -1
  59. package/dist/src/stack/aliyunStack/apigwPlanner.js +103 -23
  60. package/dist/src/stack/aliyunStack/apigwResource.js +4 -3
  61. package/dist/src/stack/aliyunStack/apigwTypes.js +3 -7
  62. package/dist/src/stack/aliyunStack/deployer.js +2 -0
  63. package/dist/src/stack/aliyunStack/esServerlessTypes.js +8 -4
  64. package/dist/src/stack/aliyunStack/fc3Executor.js +7 -3
  65. package/dist/src/stack/aliyunStack/fc3Planner.js +148 -153
  66. package/dist/src/stack/aliyunStack/fc3Resource.js +206 -53
  67. package/dist/src/stack/aliyunStack/fc3Types.js +30 -16
  68. package/dist/src/stack/aliyunStack/ossPlanner.js +15 -1
  69. package/dist/src/stack/aliyunStack/ossResource.js +113 -102
  70. package/dist/src/stack/aliyunStack/ossTypes.js +20 -20
  71. package/dist/src/stack/localStack/aliyunFc.js +1 -6
  72. package/dist/src/stack/localStack/event.js +31 -71
  73. package/dist/src/stack/localStack/function.js +25 -77
  74. package/dist/src/stack/localStack/functionRunner.js +10 -2
  75. package/dist/src/stack/localStack/httpAdapter.js +54 -0
  76. package/dist/src/stack/localStack/httpError.js +5 -0
  77. package/dist/src/stack/localStack/index.js +8 -1
  78. package/dist/src/stack/localStack/legacyLambda.js +26 -0
  79. package/dist/src/stack/localStack/localContext.js +29 -0
  80. package/dist/src/stack/localStack/localRoute.js +12 -0
  81. package/dist/src/stack/localStack/localRuntimes.js +22 -0
  82. package/dist/src/stack/localStack/localServer.js +8 -3
  83. package/dist/src/stack/localStack/requestBody.js +24 -0
  84. package/dist/src/stack/localStack/requestId.js +18 -0
  85. package/dist/src/stack/localStack/tencent.js +147 -0
  86. package/dist/src/stack/localStack/timer.js +183 -0
  87. package/dist/src/stack/localStack/utils.js +19 -1
  88. package/dist/src/stack/localStack/volcengine.js +68 -0
  89. package/dist/src/stack/scfStack/cosPlanner.js +9 -14
  90. package/dist/src/stack/scfStack/cosResource.js +42 -50
  91. package/dist/src/stack/scfStack/cosTypes.js +19 -14
  92. package/dist/src/stack/scfStack/deployer.js +2 -0
  93. package/dist/src/stack/scfStack/scfExecutor.js +7 -3
  94. package/dist/src/stack/scfStack/scfHttpTrigger.js +106 -0
  95. package/dist/src/stack/scfStack/scfPlanner.js +114 -29
  96. package/dist/src/stack/scfStack/scfResource.js +329 -311
  97. package/dist/src/stack/scfStack/scfTypes.js +4 -3
  98. package/dist/src/stack/scfStack/tdsqlcPlanner.js +10 -13
  99. package/dist/src/stack/volcengineStack/apigwDomains.js +64 -0
  100. package/dist/src/stack/volcengineStack/apigwPlanner.js +71 -15
  101. package/dist/src/stack/volcengineStack/apigwResource.js +60 -24
  102. package/dist/src/stack/volcengineStack/apigwTypes.js +5 -1
  103. package/dist/src/stack/volcengineStack/deployer.js +6 -0
  104. package/dist/src/stack/volcengineStack/tosPlanner.js +8 -13
  105. package/dist/src/stack/volcengineStack/tosResource.js +22 -35
  106. package/dist/src/stack/volcengineStack/tosTypes.js +5 -8
  107. package/dist/src/stack/volcengineStack/vefaasPlanner.js +186 -44
  108. package/dist/src/stack/volcengineStack/vefaasResource.js +232 -14
  109. package/dist/src/stack/volcengineStack/vefaasTypes.js +6 -3
  110. package/dist/src/validator/functionSchema.js +25 -2
  111. package/dist/src/validator/iacSchema.js +2 -1
  112. package/dist/src/validator/index.js +4 -1
  113. package/dist/src/validator/rootSchema.js +49 -18
  114. package/dist/src/validator/schemaExport.js +60 -0
  115. package/dist/src/validator/semanticValidation.js +79 -0
  116. package/dist/src/validator/templateRefSchema.js +9 -1
  117. package/dist/tsconfig.tsbuildinfo +1 -1
  118. package/package.json +1 -1
  119. package/release-notes.md +79 -0
  120. package/samples/aliyun-poc-timer.yml +39 -0
  121. package/samples/tencent-local/index.js +13 -0
  122. package/samples/tencent-local/serverlessinsight.yml +23 -0
  123. package/samples/volcengine-local/index.js +13 -0
  124. package/samples/volcengine-local/serverlessinsight.yml +28 -0
@@ -0,0 +1,63 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.normalizeBucketPolicyDefinition = exports.removedBucketPolicy = exports.isOwnedBucketPolicy = exports.serializeBucketPolicy = exports.buildBucketPolicy = void 0;
4
+ /** The exact provider document used by both comparison and write requests. */
5
+ const buildBucketPolicy = (iam, provider) => {
6
+ if (!iam?.resource?.statements?.length)
7
+ return null;
8
+ if (provider === 'tencent') {
9
+ return {
10
+ version: '2.0',
11
+ statement: iam.resource.statements.map((statement) => ({
12
+ effect: statement.effect.toLowerCase(),
13
+ principal: statement.principal,
14
+ action: statement.action,
15
+ resource: statement.resource,
16
+ ...(statement.condition ? { condition: statement.condition } : {}),
17
+ })),
18
+ };
19
+ }
20
+ return {
21
+ ...(provider === 'aliyun' ? { Version: '1' } : {}),
22
+ Statement: iam.resource.statements.map((statement) => ({
23
+ Effect: statement.effect,
24
+ Principal: statement.principal,
25
+ Action: statement.action,
26
+ Resource: statement.resource,
27
+ ...(statement.condition ? { Condition: statement.condition } : {}),
28
+ })),
29
+ };
30
+ };
31
+ exports.buildBucketPolicy = buildBucketPolicy;
32
+ const serializeBucketPolicy = (iam, provider) => {
33
+ const policy = (0, exports.buildBucketPolicy)(iam, provider);
34
+ return policy ? JSON.stringify(policy) : iam?.resource?.statements !== undefined ? 'null' : null;
35
+ };
36
+ exports.serializeBucketPolicy = serializeBucketPolicy;
37
+ /** A policy is ours when state records its instance, or when pre-instance state stored a policy document. */
38
+ const isOwnedBucketPolicy = (policyInstanceType, instances, definition) => (instances ?? []).some((instance) => instance.type === policyInstanceType) ||
39
+ (typeof definition?.policy === 'string' && definition.policy !== 'null');
40
+ exports.isOwnedBucketPolicy = isOwnedBucketPolicy;
41
+ /** A recorded policy the YAML no longer declares (omitted or emptied statements) is removed. */
42
+ const removedBucketPolicy = (policyInstanceType, currentState, desired) => currentState &&
43
+ (0, exports.isOwnedBucketPolicy)(policyInstanceType, currentState.instances, currentState.definition) &&
44
+ (desired.policy === null || desired.policy === 'null')
45
+ ? { policy: currentState.definition.policy ?? null }
46
+ : {};
47
+ exports.removedBucketPolicy = removedBucketPolicy;
48
+ /** Read older saved intent without treating the DSL-to-wire migration as drift. */
49
+ const normalizeBucketPolicyDefinition = (definition, provider) => {
50
+ if (typeof definition.policy !== 'string')
51
+ return definition;
52
+ try {
53
+ const value = JSON.parse(definition.policy);
54
+ if (value?.resource && Array.isArray(value.resource.statements)) {
55
+ return { ...definition, policy: (0, exports.serializeBucketPolicy)(value, provider) };
56
+ }
57
+ }
58
+ catch {
59
+ // Invalid documents are preserved so comparison cannot silently erase them.
60
+ }
61
+ return definition;
62
+ };
63
+ exports.normalizeBucketPolicyDefinition = normalizeBucketPolicyDefinition;
@@ -5,7 +5,13 @@ exports.CODE_ZIP_SIZE_LIMIT = 300 * 1000; // 300 KB - code package size limit fo
5
5
  exports.OSS_DEPLOYMENT_TIMEOUT = 3000; // in seconds
6
6
  exports.SI_BOOTSTRAP_FC_PREFIX = 'si-bootstrap-api';
7
7
  exports.SI_BOOTSTRAP_BUCKET_PREFIX = 'si-bootstrap-artifacts';
8
- exports.SI_LOCALSTACK_SERVER_PORT = 4567;
8
+ // Local dev server port. Under jest, each worker shifts its base port so
9
+ // parallel test files binding the server never collide on one fixed port
10
+ // (pre-existing flake: localServer/index/aliyunFc suites all bind 4567).
11
+ const SI_LOCALSTACK_TEST_WORKER_PORT = process.env.JEST_WORKER_ID && Number.isInteger(Number(process.env.JEST_WORKER_ID))
12
+ ? 4570 + Number(process.env.JEST_WORKER_ID)
13
+ : undefined;
14
+ exports.SI_LOCALSTACK_SERVER_PORT = Number(process.env.SI_LOCALSTACK_SERVER_PORT) || SI_LOCALSTACK_TEST_WORKER_PORT || 4567;
9
15
  exports.ALIYUN_FC3_CONNECT_TIMEOUT_MS = 120000;
10
16
  exports.ALIYUN_FC3_READ_TIMEOUT_MS = 600000;
11
17
  // Query-tier budget for synchronous management-plane RPCs (all non-fc3 aliyun
@@ -1,6 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.deriveWwwDomain = exports.extractHostRecord = exports.extractMainDomain = exports.normalizeDomain = void 0;
3
+ exports.resolveWwwBindingAction = exports.deriveWwwDomain = exports.extractHostRecord = exports.extractMainDomain = exports.normalizeDomain = void 0;
4
4
  const MULTI_LEVEL_TLDS = new Set([
5
5
  // United Kingdom
6
6
  'co.uk',
@@ -144,3 +144,6 @@ const deriveWwwDomain = (domain) => {
144
144
  return `www.${domain}`;
145
145
  };
146
146
  exports.deriveWwwDomain = deriveWwwDomain;
147
+ /** Omission restores the framework default: no www binding. */
148
+ const resolveWwwBindingAction = (declared) => declared === true ? 'ensure' : 'remove';
149
+ exports.resolveWwwBindingAction = resolveWwwBindingAction;
@@ -0,0 +1,25 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.withStoredFunctionIam = exports.withLifecycleIntent = exports.withFunctionLifecycle = void 0;
4
+ const planCompare_1 = require("./planCompare");
5
+ /** Persist lifecycle intent alongside function configuration, using the same shape on every provider. */
6
+ const withFunctionLifecycle = (definition, fn, support = {}) => ({
7
+ ...definition,
8
+ ...(fn?.log !== undefined && !definition.logConfig ? { logEnabled: fn.log } : {}),
9
+ ...(support.http !== false && fn?.triggers?.http ? { http: fn.triggers.http } : {}),
10
+ ...(support.domain !== false && fn?.domain ? { domain: fn.domain } : {}),
11
+ ...(fn?.triggers?.timer !== undefined ? { timers: fn.triggers.timer } : {}),
12
+ });
13
+ exports.withFunctionLifecycle = withFunctionLifecycle;
14
+ /** Lifecycle fields follow the YAML on write: a removed field is dropped, not merged back from stored intent. */
15
+ const withLifecycleIntent = (merged, desired, keys) => ({
16
+ ...Object.fromEntries(Object.entries(merged).filter(([key]) => !keys.includes(key))),
17
+ ...Object.fromEntries(keys.filter((key) => key in desired).map((key) => [key, desired[key]])),
18
+ });
19
+ exports.withLifecycleIntent = withLifecycleIntent;
20
+ /** An omitted IAM block must not revoke a previously managed grant on an unrelated update. */
21
+ const withStoredFunctionIam = (fn, stored = {}) => {
22
+ const iam = (0, planCompare_1.mergeManagedIntent)({ iam: stored.iam }, { iam: fn.iam }).iam;
23
+ return iam ? { ...fn, iam } : fn;
24
+ };
25
+ exports.withStoredFunctionIam = withStoredFunctionIam;
@@ -43,3 +43,7 @@ __exportStar(require("./concurrency"), exports);
43
43
  __exportStar(require("./throttleRetry"), exports);
44
44
  __exportStar(require("./planCompare"), exports);
45
45
  __exportStar(require("./refreshPlanner"), exports);
46
+ __exportStar(require("./planCapabilities"), exports);
47
+ __exportStar(require("./bucketPolicy"), exports);
48
+ __exportStar(require("./functionDefinition"), exports);
49
+ __exportStar(require("./planRedaction"), exports);
@@ -0,0 +1,82 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.buildPlanJson = exports.buildPlanChange = exports.buildPlanSummary = exports.writeJson = exports.isJsonMode = exports.setJsonMode = exports.SHOW_JSON_VERSION = exports.VALIDATE_JSON_VERSION = exports.PLAN_JSON_VERSION = void 0;
4
+ const planRedaction_1 = require("./planRedaction");
5
+ const planFormatter_1 = require("./planFormatter");
6
+ /**
7
+ * Machine-readable output channel (issue #250): the `--json` surface of the CLI.
8
+ *
9
+ * Contract with agents:
10
+ * - logs (pino) go to stderr, JSON results go to stdout — a pipe of stdout is
11
+ * always a single JSON document (jq-parseable);
12
+ * - every envelope carries a version field (`planVersion` / `validateVersion` /
13
+ * `showVersion`) so consumers can pin a shape;
14
+ * - failures emit `{ error: { code, message } }` where `code` is the stable
15
+ * i18n key behind the message — locale changes never change the code.
16
+ */
17
+ exports.PLAN_JSON_VERSION = 1;
18
+ exports.VALIDATE_JSON_VERSION = 1;
19
+ exports.SHOW_JSON_VERSION = 1;
20
+ let jsonMode = false;
21
+ const setJsonMode = (enabled) => {
22
+ jsonMode = enabled;
23
+ };
24
+ exports.setJsonMode = setJsonMode;
25
+ const isJsonMode = () => jsonMode;
26
+ exports.isJsonMode = isJsonMode;
27
+ const writeJson = (payload) => {
28
+ process.stdout.write(`${JSON.stringify(payload, null, 2)}\n`);
29
+ };
30
+ exports.writeJson = writeJson;
31
+ const buildPlanSummary = (items) => items.reduce((summary, item) => {
32
+ if (item.action === 'noop') {
33
+ return { ...summary, unchanged: summary.unchanged + 1 };
34
+ }
35
+ if (item.action === 'create') {
36
+ return (0, planFormatter_1.isRecreate)(item)
37
+ ? { ...summary, recreate: summary.recreate + 1 }
38
+ : { ...summary, create: summary.create + 1 };
39
+ }
40
+ if (item.action === 'update') {
41
+ return { ...summary, update: summary.update + 1 };
42
+ }
43
+ return { ...summary, destroy: summary.destroy + 1 };
44
+ }, { create: 0, update: 0, destroy: 0, recreate: 0, unchanged: 0 });
45
+ exports.buildPlanSummary = buildPlanSummary;
46
+ const toPlanJsonAction = (item) => {
47
+ if (item.action === 'delete')
48
+ return 'destroy';
49
+ if (item.action === 'create' && (0, planFormatter_1.isRecreate)(item))
50
+ return 'recreate';
51
+ return item.action === 'update' ? 'update' : 'create';
52
+ };
53
+ const buildPlanChange = (item) => {
54
+ const attributes = item.changes
55
+ ? (0, planFormatter_1.computeAttributeDiffs)(item.changes.before, item.changes.after).diffs
56
+ : [];
57
+ return {
58
+ logicalId: item.logicalId,
59
+ type: item.resourceType,
60
+ action: toPlanJsonAction(item),
61
+ attributes: (0, planRedaction_1.redactAttributeDiffs)(attributes),
62
+ ...(item.revertKeys?.length ? { revertKeys: item.revertKeys } : {}),
63
+ ...(item.drifted ? { drifted: true } : {}),
64
+ ...(item.driftReasons && item.driftReasons.length > 0
65
+ ? { driftReasons: item.driftReasons }
66
+ : {}),
67
+ };
68
+ };
69
+ exports.buildPlanChange = buildPlanChange;
70
+ const buildPlanJson = (planResult, identity) => {
71
+ const items = planResult.items ?? [];
72
+ return {
73
+ ...(items.some((item) => item.stateUpdate)
74
+ ? { stateUpdates: items.filter((item) => item.stateUpdate).map((item) => item.logicalId) }
75
+ : {}),
76
+ planVersion: exports.PLAN_JSON_VERSION,
77
+ ...identity,
78
+ changes: items.filter((item) => item.action !== 'noop').map(exports.buildPlanChange),
79
+ summary: (0, exports.buildPlanSummary)(items),
80
+ };
81
+ };
82
+ exports.buildPlanJson = buildPlanJson;
@@ -9,6 +9,7 @@ const pino_pretty_1 = __importDefault(require("pino-pretty"));
9
9
  const child_process_1 = require("child_process");
10
10
  const iconv_lite_1 = __importDefault(require("iconv-lite"));
11
11
  const stream_1 = require("stream");
12
+ const noColor_1 = require("./noColor");
12
13
  const CODE_PAGE_TO_ENCODING = {
13
14
  932: 'shift_jis', // Japanese
14
15
  936: 'gbk', // Simplified Chinese
@@ -71,7 +72,7 @@ class EncodingTransformStream extends stream_1.Writable {
71
72
  super();
72
73
  this.encoding = encoding;
73
74
  this.formatLog = pino_pretty_1.default.prettyFactory({
74
- colorize: true,
75
+ colorize: !(0, noColor_1.isNoColorEnabled)(),
75
76
  translateTime: 'HH:MM:ss',
76
77
  ignore: 'pid,hostname',
77
78
  messageFormat: '{msg}',
@@ -81,11 +82,13 @@ class EncodingTransformStream extends stream_1.Writable {
81
82
  try {
82
83
  const stringChunk = typeof chunk === 'string' ? chunk : chunk.toString();
83
84
  const formattedChunk = this.formatLog(stringChunk);
85
+ // Issue #250: logs go to stderr — stdout carries only command result
86
+ // data (--json payloads), so agents can pipe stdout straight to jq.
84
87
  if (this.encoding !== 'utf8' && iconv_lite_1.default.encodingExists(this.encoding)) {
85
- process.stdout.write(iconv_lite_1.default.toEncoding(formattedChunk, 'utf8'));
88
+ process.stderr.write(iconv_lite_1.default.toEncoding(formattedChunk, 'utf8'));
86
89
  }
87
90
  else {
88
- process.stdout.write(formattedChunk);
91
+ process.stderr.write(formattedChunk);
89
92
  }
90
93
  callback();
91
94
  }
@@ -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.buildNasAccessGroupName = exports.buildRolePolicyName = exports.buildFunctionRoleName = exports.CONSTRAINT_NAME_LIMITS = exports.buildConstrainedName = exports.stableHash = exports.DEFAULT_HASH_LENGTH = void 0;
19
+ exports.buildFunctionHttpTriggerName = 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 = {
@@ -101,3 +101,5 @@ exports.buildRolePolicyName = buildRolePolicyName;
101
101
  */
102
102
  const buildNasAccessGroupName = (fnName, stage, mountPath) => `${fnName}-${stage}-nas-access-${mountPath.replace(/\//g, '-').replace(/^-/, '')}`;
103
103
  exports.buildNasAccessGroupName = buildNasAccessGroupName;
104
+ const buildFunctionHttpTriggerName = (functionKey) => `${functionKey}-http-trigger`;
105
+ exports.buildFunctionHttpTriggerName = buildFunctionHttpTriggerName;
@@ -0,0 +1,9 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.isNoColorEnabled = void 0;
4
+ /**
5
+ * no-color.org convention (issue #250): a NO_COLOR environment variable that
6
+ * is present and not an empty string disables ANSI color, regardless of value.
7
+ */
8
+ const isNoColorEnabled = () => process.env.NO_COLOR !== undefined && process.env.NO_COLOR !== '';
9
+ exports.isNoColorEnabled = isNoColorEnabled;
@@ -0,0 +1,119 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.assertSupportedPlanUpdate = exports.assertPlanIdentity = void 0;
4
+ const lang_1 = require("../lang");
5
+ const planCompare_1 = require("./planCompare");
6
+ const UPDATE_FIELDS = {
7
+ VOLCENGINE_VEFAAS: [
8
+ 'codeHash',
9
+ 'runtime',
10
+ 'handler',
11
+ 'memorySize',
12
+ 'timeout',
13
+ 'environment',
14
+ 'description',
15
+ 'role',
16
+ 'iam',
17
+ 'vpcConfig',
18
+ 'tosMountConfig',
19
+ 'logConfig',
20
+ 'logEnabled',
21
+ 'timers',
22
+ ],
23
+ ALIYUN_RDS_SERVERLESS: ['serverlessConfig', 'securityIPList'],
24
+ ALIYUN_ES_SERVERLESS: ['description', 'authentication'],
25
+ TDSQL_C_SERVERLESS: ['minCpu', 'maxCpu', 'autoPause', 'autoPauseDelay'],
26
+ TENCENT_ES_SERVERLESS: ['spaceName', 'kibanaWhiteIpList'],
27
+ ALIYUN_TABLESTORE_TABLE: ['reservedThroughput', 'tableOptions'],
28
+ SCF: [
29
+ 'codeHash',
30
+ 'memorySize',
31
+ 'timeout',
32
+ 'environment',
33
+ 'iam',
34
+ 'logConfig',
35
+ 'logEnabled',
36
+ 'http',
37
+ 'domain',
38
+ 'timers',
39
+ ],
40
+ ALIYUN_OSS_BUCKET: [
41
+ 'acl',
42
+ 'websiteConfiguration',
43
+ 'websiteCodeHash',
44
+ 'domain',
45
+ 'wwwBindApex',
46
+ 'domainCertificateId',
47
+ 'domainCertificateBody',
48
+ 'domainCertificatePrivateKey',
49
+ 'domainProtocol',
50
+ 'policy',
51
+ 'cdnType',
52
+ 'cdnScope',
53
+ 'cdnCacheTtl',
54
+ 'cdnIgnoreQueryString',
55
+ 'cdnOriginProtocol',
56
+ 'cdnCompression',
57
+ 'cdnForceRedirectHttps',
58
+ ],
59
+ COS_BUCKET: [
60
+ 'acl',
61
+ 'websiteConfiguration',
62
+ 'domain',
63
+ 'wwwBindApex',
64
+ 'domainCertificateId',
65
+ 'domainCertificateBody',
66
+ 'domainCertificatePrivateKey',
67
+ 'domainProtocol',
68
+ 'policy',
69
+ ],
70
+ VOLCENGINE_TOS_BUCKET: ['acl', 'websiteConfiguration', 'websiteCodeHash', 'policy'],
71
+ };
72
+ const IDENTITY_FIELDS = {
73
+ ALIYUN_FC3: ['functionName'],
74
+ SCF: ['functionName'],
75
+ VOLCENGINE_VEFAAS: ['functionName'],
76
+ ALIYUN_OSS_BUCKET: ['bucketName'],
77
+ COS_BUCKET: ['bucket', 'region'],
78
+ VOLCENGINE_TOS_BUCKET: ['bucketName'],
79
+ ALIYUN_RDS_SERVERLESS: [],
80
+ ALIYUN_ES_SERVERLESS: ['appName'],
81
+ TDSQL_C_SERVERLESS: [],
82
+ TENCENT_ES_SERVERLESS: [],
83
+ ALIYUN_TABLESTORE_TABLE: ['instanceName', 'tableName'],
84
+ ALIYUN_APIGW: ['groupName'],
85
+ VOLCENGINE_APIGW: ['gatewayName'],
86
+ };
87
+ const assertPlanIdentity = (logicalId, resourceType, stored, desired) => {
88
+ const changed = (IDENTITY_FIELDS[resourceType] ?? []).filter((key) => stored[key] !== undefined &&
89
+ (0, planCompare_1.definitionsDiffer)({ [key]: stored[key] }, { [key]: desired[key] }));
90
+ if (changed.length) {
91
+ throw new Error(lang_1.lang.__('PLAN_REPLACEMENT_REQUIRED', { logicalId, fields: changed.join(', ') }));
92
+ }
93
+ };
94
+ exports.assertPlanIdentity = assertPlanIdentity;
95
+ const assertSupportedPlanUpdate = (logicalId, resourceType, before, desired) => {
96
+ if (resourceType === 'ALIYUN_FC3' &&
97
+ Array.isArray(before.nasStorage) &&
98
+ Array.isArray(desired.nasStorage)) {
99
+ const oldClasses = before.nasStorage.map((entry) => entry.storage_class);
100
+ const newClasses = desired.nasStorage.map((entry) => entry.storage_class);
101
+ if (JSON.stringify(oldClasses) !== JSON.stringify(newClasses)) {
102
+ throw new Error(lang_1.lang.__('PLAN_UPDATE_NOT_SUPPORTED', { logicalId, fields: 'nasStorage.storage_class' }));
103
+ }
104
+ }
105
+ if (resourceType === 'ALIYUN_OSS_BUCKET' &&
106
+ (before.cdnEnabled === true || before.accelerateEnabled === true) &&
107
+ (0, planCompare_1.definitionsDiffer)({ domain: before.domain }, { domain: desired.domain })) {
108
+ throw new Error(lang_1.lang.__('PLAN_UPDATE_NOT_SUPPORTED', { logicalId, fields: 'domain' }));
109
+ }
110
+ const supported = UPDATE_FIELDS[resourceType];
111
+ if (!supported)
112
+ return;
113
+ const changed = Object.keys((0, planCompare_1.managedDefinition)(desired)).filter((key) => !supported.includes(key) &&
114
+ (0, planCompare_1.definitionsDiffer)({ [key]: before[key] }, { [key]: desired[key] }));
115
+ if (changed.length) {
116
+ throw new Error(lang_1.lang.__('PLAN_UPDATE_NOT_SUPPORTED', { logicalId, fields: changed.join(', ') }));
117
+ }
118
+ };
119
+ exports.assertSupportedPlanUpdate = assertSupportedPlanUpdate;
@@ -1,92 +1,145 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.computeRevertKeys = exports.mergeLiveBefore = exports.jsonDocumentDiffers = exports.remoteDiffersFromDesired = void 0;
3
+ exports.mergeManagedIntent = exports.computeRevertKeys = exports.mergeLiveBefore = exports.jsonDocumentDiffers = exports.remoteDiffersFromDesired = exports.definitionsDiffer = exports.managedDefinition = void 0;
4
4
  const hashUtils_1 = require("./hashUtils");
5
- /**
6
- * A desired value "declares" a dimension only when the executor would write it:
7
- * `undefined`/`null` mean unset, and an empty plain object means the executor
8
- * omits the field entirely (e.g. fc3 `environment: {}`, oss
9
- * `websiteConfiguration: {}`) — so cloud-side values in that dimension can
10
- * never be cleared and are not drift. Arrays and empty strings stay declared:
11
- * the executor writes them explicitly.
12
- */
13
- const isDeclared = (value) => {
14
- if (value === undefined || value === null) {
15
- return false;
5
+ const isRecord = (value) => value !== null && typeof value === 'object' && !Array.isArray(value);
6
+ const isDeclared = (value) => value !== undefined && value !== null && (!isRecord(value) || Object.keys(value).length > 0);
7
+ // Membership lists are sets; command arguments, routes and mount sequences are not.
8
+ const SET_FIELDS = new Set([
9
+ 'vSwitchIds',
10
+ 'subnetIds',
11
+ 'securityGroupIds',
12
+ 'subnet_ids',
13
+ 'managed_policies',
14
+ 'kibanaWhiteIpList',
15
+ 'ips',
16
+ 'timers',
17
+ 'methods',
18
+ 'domainProtocol',
19
+ 'statements',
20
+ 'action',
21
+ 'resource',
22
+ 'Service',
23
+ 'AWS',
24
+ 'qcs',
25
+ ]);
26
+ const canonicalValue = (value, key, policyDocument = false) => {
27
+ const policyScope = policyDocument || key === 'policy';
28
+ if (key === 'policy' && (value === null || value === 'null'))
29
+ return 'null';
30
+ if (key === 'policy' && typeof value === 'string') {
31
+ try {
32
+ return canonicalValue(JSON.parse(value), '', true);
33
+ }
34
+ catch {
35
+ return value;
36
+ }
16
37
  }
17
- if (typeof value === 'object' &&
18
- !Array.isArray(value) &&
19
- Object.keys(value).length === 0) {
20
- return false;
38
+ if (Array.isArray(value)) {
39
+ const entries = value.map((entry) => canonicalValue(entry, '', policyScope));
40
+ return policyScope || SET_FIELDS.has(key)
41
+ ? [
42
+ ...new Map(entries.map((entry) => [JSON.stringify(entry) ?? 'null', entry])).values(),
43
+ ].sort((a, b) => (JSON.stringify(a) ?? 'null').localeCompare(JSON.stringify(b) ?? 'null'))
44
+ : entries;
45
+ }
46
+ if (isRecord(value)) {
47
+ return Object.fromEntries(Object.entries(value)
48
+ .sort(([a], [b]) => a.localeCompare(b))
49
+ .map(([name, entry]) => [name, canonicalValue(entry, name, policyScope)]));
21
50
  }
22
- return true;
51
+ return value;
23
52
  };
24
- /**
25
- * One-directional live-drift check (issue #234 Phase 1 contract):
26
- * compares only the attributes a cloud->definition mapper emits (remote) that
27
- * the desired definition actually declares. A desired value with no matching
28
- * cloud value IS drift (the executor sets it on update); a cloud-only extra
29
- * the config never asked for is ignored (the executor may not clear it).
30
- * Unreadable/config-only keys never appear in `remote` — so matching reality
31
- * stays `noop` instead of phantom-drifting every plan.
32
- */
33
- const remoteDiffersFromDesired = (remote, desired) => Object.entries(remote).some(([key]) => {
34
- const desiredValue = desired[key];
35
- if (!isDeclared(desiredValue)) {
36
- return false;
53
+ const projectValue = (actual, desired, key) => {
54
+ if (key === 'policy')
55
+ return canonicalValue(actual, key);
56
+ if (Array.isArray(actual) && Array.isArray(desired) && !SET_FIELDS.has(key)) {
57
+ return actual.map((entry, index) => index < desired.length ? projectValue(entry, desired[index], '') : canonicalValue(entry, ''));
58
+ }
59
+ // An environment declaration replaces the entire map, including removal of
60
+ // cloud-only entries. Structural configs write only their declared members.
61
+ if (isRecord(desired) && isRecord(actual) && key !== 'environment') {
62
+ return Object.fromEntries(Object.entries(desired)
63
+ .filter(([, value]) => isDeclared(value))
64
+ .map(([name, value]) => [name, projectValue(actual[name], value, name)]));
37
65
  }
38
- return !(0, hashUtils_1.attributesEqual)({ [key]: remote[key] }, { [key]: desiredValue });
39
- });
66
+ return canonicalValue(actual, key);
67
+ };
68
+ /** The fields the current configuration actually manages, in comparison form. */
69
+ const managedDefinition = (actual, desired = actual) => Object.fromEntries(Object.entries(desired)
70
+ .filter(([, value]) => isDeclared(value))
71
+ .map(([key, value]) => [key, projectValue(actual[key], value, key)]));
72
+ exports.managedDefinition = managedDefinition;
73
+ const definitionsDiffer = (actual, desired) => !(0, hashUtils_1.attributesEqual)((0, exports.managedDefinition)(actual, desired), (0, exports.managedDefinition)(desired));
74
+ exports.definitionsDiffer = definitionsDiffer;
75
+ /** Only mapper-emitted fields are readable. Explicit null means known absence. */
76
+ const remoteDiffersFromDesired = (remote, desired) => Object.keys(remote).some((key) => remote[key] !== undefined &&
77
+ isDeclared(desired[key]) &&
78
+ !(0, hashUtils_1.attributesEqual)({ value: projectValue(remote[key], desired[key], key) }, { value: projectValue(desired[key], desired[key], key) }));
40
79
  exports.remoteDiffersFromDesired = remoteDiffersFromDesired;
41
- /**
42
- * Canonical JSON document compare (issue #234 phase 3): providers return
43
- * policy documents as parsed objects (or re-serialized strings) whose key
44
- * order and formatting differ from what the config serialized, so byte-level
45
- * string comparison false-drifts. Parses both sides and compares
46
- * key-order-insensitively. Undeclared (null) desired or unreadable cloud
47
- * values are not drift — only a parseable pair with different content is.
48
- */
80
+ /** Undefined is unavailable; null is a successfully read, absent policy. */
49
81
  const jsonDocumentDiffers = (desired, cloud) => {
50
- if (desired === null || cloud === undefined || cloud === null) {
82
+ if (desired === null || cloud === undefined) {
51
83
  return false;
52
84
  }
85
+ if (cloud === null) {
86
+ return desired !== 'null';
87
+ }
53
88
  try {
54
89
  const desiredObj = JSON.parse(desired);
55
90
  const cloudObj = typeof cloud === 'string' ? JSON.parse(cloud) : cloud;
56
- return !(0, hashUtils_1.attributesEqual)({ doc: cloudObj }, { doc: desiredObj });
91
+ return !(0, hashUtils_1.attributesEqual)({ doc: desiredObj }, { doc: cloudObj });
57
92
  }
58
93
  catch {
59
94
  return false;
60
95
  }
61
96
  };
62
97
  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 });
98
+ /** Live values override stored intent only inside currently managed dimensions. */
99
+ const mergeLiveBefore = (stored, live, desired) => {
100
+ const before = {
101
+ ...stored,
102
+ ...Object.fromEntries(Object.entries(live).filter(([, value]) => value !== undefined)),
103
+ };
104
+ return desired ? (0, exports.managedDefinition)(before, desired) : before;
105
+ };
72
106
  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
- */
107
+ const revertPaths = (stored, live, desired, path) => {
108
+ if ((0, hashUtils_1.attributesEqual)({ value: live }, { value: desired })) {
109
+ return [];
110
+ }
111
+ if (isRecord(live) && isRecord(desired)) {
112
+ const saved = isRecord(stored) ? stored : {};
113
+ return [...new Set([...Object.keys(live), ...Object.keys(desired)])].flatMap((key) => revertPaths(saved[key], live[key], desired[key], `${path}.${key}`));
114
+ }
115
+ return (0, hashUtils_1.attributesEqual)({ value: stored }, { value: desired }) ? [path] : [];
116
+ };
80
117
  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.
118
+ const saved = (0, exports.managedDefinition)(stored, desired);
119
+ const current = (0, exports.managedDefinition)(live, desired);
120
+ const target = (0, exports.managedDefinition)(desired);
84
121
  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
- })
122
+ .filter((key) => live[key] !== undefined && isDeclared(desired[key]))
123
+ .flatMap((key) => revertPaths(saved[key], current[key], target[key], key))
90
124
  .sort((a, b) => a.localeCompare(b));
91
125
  };
92
126
  exports.computeRevertKeys = computeRevertKeys;
127
+ const mergeIntentValue = (stored, desired) => {
128
+ if (!isDeclared(desired))
129
+ return stored ?? desired;
130
+ if (!isRecord(desired))
131
+ return desired;
132
+ const previous = isRecord(stored) ? stored : {};
133
+ return Object.fromEntries([...new Set([...Object.keys(previous), ...Object.keys(desired)])].map((key) => [
134
+ key,
135
+ mergeIntentValue(previous[key], desired[key]),
136
+ ]));
137
+ };
138
+ /** Retain unmanaged history so unrelated writes cannot erase dependency configuration. */
139
+ const mergeManagedIntent = (stored, desired) => Object.fromEntries([...new Set([...Object.keys(stored), ...Object.keys(desired)])].map((key) => [
140
+ key,
141
+ key === 'environment' && isDeclared(desired[key])
142
+ ? desired[key]
143
+ : mergeIntentValue(stored[key], desired[key]),
144
+ ]));
145
+ exports.mergeManagedIntent = mergeManagedIntent;