@geek-fun/serverlessinsight 0.9.7 → 0.9.8

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 (86) hide show
  1. package/AGENTS.md +1 -0
  2. package/CHANGELOG.md +68 -6
  3. package/README.md +51 -10
  4. package/README.zh-CN.md +44 -10
  5. package/dist/package.json +2 -1
  6. package/dist/src/commands/deploy.js +3 -1
  7. package/dist/src/commands/destroy.js +3 -1
  8. package/dist/src/commands/forceUnlock.js +2 -2
  9. package/dist/src/commands/index.js +28 -8
  10. package/dist/src/commands/local.js +3 -2
  11. package/dist/src/commands/login.js +120 -37
  12. package/dist/src/commands/logout.js +3 -5
  13. package/dist/src/commands/migrate.js +17 -10
  14. package/dist/src/commands/plan.js +5 -1
  15. package/dist/src/commands/show.js +3 -1
  16. package/dist/src/commands/whoami.js +24 -6
  17. package/dist/src/common/aliyunClient/cdnOperations.js +64 -29
  18. package/dist/src/common/aliyunClient/dnsOperations.js +10 -0
  19. package/dist/src/common/aliyunClient/fc3Operations.js +36 -7
  20. package/dist/src/common/apiClient.js +1 -0
  21. package/dist/src/common/bindingReconcile.js +182 -0
  22. package/dist/src/common/cdnCapabilities.js +80 -0
  23. package/dist/src/common/certUtils.js +44 -5
  24. package/dist/src/common/consoleLines.js +126 -0
  25. package/dist/src/common/constants.js +4 -2
  26. package/dist/src/common/credentialStore.js +136 -39
  27. package/dist/src/common/domainUtils.js +23 -4
  28. package/dist/src/common/functionDefinition.js +4 -1
  29. package/dist/src/common/functionDomainCapabilities.js +28 -0
  30. package/dist/src/common/functionDomainReconcile.js +197 -0
  31. package/dist/src/common/lineContext.js +164 -0
  32. package/dist/src/common/planCapabilities.js +14 -27
  33. package/dist/src/common/planCompare.js +8 -7
  34. package/dist/src/common/planFormatter.js +71 -37
  35. package/dist/src/common/stateBackend/index.js +24 -16
  36. package/dist/src/common/stateBackend/saasStateBackend.js +46 -53
  37. package/dist/src/common/stateBackend/tosStateBackend.js +100 -0
  38. package/dist/src/common/tencentClient/cdnOperations.js +165 -0
  39. package/dist/src/common/tencentClient/cosOperations.js +18 -2
  40. package/dist/src/common/tencentClient/dnspodOperations.js +12 -0
  41. package/dist/src/common/tencentClient/index.js +16 -0
  42. package/dist/src/common/tencentClient/scfOperations.js +23 -1
  43. package/dist/src/common/tencentClient/sslOperations.js +147 -77
  44. package/dist/src/common/volcengineClient/cdnOperations.js +221 -0
  45. package/dist/src/common/volcengineClient/dnsOperations.js +132 -0
  46. package/dist/src/common/volcengineClient/index.js +28 -0
  47. package/dist/src/common/volcengineClient/tosOperations.js +131 -1
  48. package/dist/src/lang/en.js +89 -10
  49. package/dist/src/lang/zh-CN.js +90 -9
  50. package/dist/src/parser/bucketParser.js +22 -79
  51. package/dist/src/parser/functionParser.js +13 -9
  52. package/dist/src/stack/aliyunStack/apigwResource.js +2 -1
  53. package/dist/src/stack/aliyunStack/fc3Planner.js +32 -12
  54. package/dist/src/stack/aliyunStack/fc3Resource.js +169 -121
  55. package/dist/src/stack/aliyunStack/ossPlanner.js +12 -4
  56. package/dist/src/stack/aliyunStack/ossResource.js +484 -501
  57. package/dist/src/stack/aliyunStack/ossTypes.js +21 -67
  58. package/dist/src/stack/localStack/aliyunFc.js +59 -9
  59. package/dist/src/stack/localStack/bucket.js +75 -28
  60. package/dist/src/stack/localStack/event.js +33 -24
  61. package/dist/src/stack/localStack/httpAdapter.js +1 -13
  62. package/dist/src/stack/localStack/index.js +2 -2
  63. package/dist/src/stack/localStack/localServer.js +85 -7
  64. package/dist/src/stack/scfStack/cosPlanner.js +11 -3
  65. package/dist/src/stack/scfStack/cosResource.js +339 -161
  66. package/dist/src/stack/scfStack/cosTypes.js +25 -34
  67. package/dist/src/stack/scfStack/scfPlanner.js +26 -8
  68. package/dist/src/stack/scfStack/scfResource.js +191 -124
  69. package/dist/src/stack/volcengineStack/tosPlanner.js +13 -1
  70. package/dist/src/stack/volcengineStack/tosResource.js +398 -7
  71. package/dist/src/stack/volcengineStack/tosTypes.js +27 -0
  72. package/dist/src/stack/volcengineStack/vefaasTypes.js +1 -1
  73. package/dist/src/types/domains/state.js +6 -0
  74. package/dist/src/validator/bucketSchema.js +35 -113
  75. package/dist/src/validator/cdnSchema.js +30 -0
  76. package/dist/src/validator/eventSchema.js +2 -20
  77. package/dist/src/validator/functionSchema.js +55 -8
  78. package/dist/src/validator/rootSchema.js +3 -3
  79. package/dist/src/validator/semanticValidation.js +504 -1
  80. package/dist/tsconfig.tsbuildinfo +1 -1
  81. package/package.json +2 -1
  82. package/release-notes.md +82 -6
  83. package/samples/aliyun-poc-api-cdn.yml +1 -1
  84. package/samples/aliyun-poc-bucket-cdn.yml +28 -26
  85. package/samples/aliyun-poc-domain.yml +2 -1
  86. package/samples/volcengine-poc-tos-state.yml +36 -0
@@ -3,9 +3,8 @@ Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.parseBucket = void 0;
4
4
  const types_1 = require("../types");
5
5
  const parseUtils_1 = require("./parseUtils");
6
- const logger_1 = require("../common/logger");
7
- const lang_1 = require("../lang");
8
- const isStructuredDomain = (domain) => typeof domain === 'object' && domain !== null && 'domain_name' in domain;
6
+ const domainUtils_1 = require("../common/domainUtils");
7
+ const TEMPLATE_REF_PATTERN = /^\$\{[^}]+\}$/;
9
8
  const parseCdnConfig = (cdn) => {
10
9
  if (cdn == null)
11
10
  return undefined;
@@ -28,84 +27,29 @@ const parseCdnConfig = (cdn) => {
28
27
  parsed.force_redirect_https = String(cdn.force_redirect_https) === 'true';
29
28
  return parsed;
30
29
  };
31
- const parseDomainConfig = (rawDomain, accelerateFromDomain) => {
32
- if (!rawDomain)
33
- return undefined;
34
- return {
35
- domain_name: String(rawDomain.domain_name),
36
- www_bind_apex: (0, parseUtils_1.parseBooleanWithDefault)(rawDomain.www_bind_apex, false),
37
- certificate_id: rawDomain.certificate_id != null ? String(rawDomain.certificate_id) : undefined,
38
- certificate_body: rawDomain.certificate_body != null ? String(rawDomain.certificate_body) : undefined,
39
- certificate_private_key: rawDomain.certificate_private_key != null
40
- ? String(rawDomain.certificate_private_key)
41
- : undefined,
42
- protocol: rawDomain.protocol != null
43
- ? Array.isArray(rawDomain.protocol)
44
- ? rawDomain.protocol.map(String)
45
- : String(rawDomain.protocol)
46
- : undefined,
47
- cdn: parseCdnConfig(rawDomain.cdn),
48
- accelerate: accelerateFromDomain != null ? String(accelerateFromDomain) === 'true' : undefined,
49
- };
50
- };
51
- const parseWebsiteDomain = (domain) => {
52
- if (domain == null) {
53
- return {
54
- domain: undefined,
55
- www_bind_apex: false,
56
- domain_certificate_id: undefined,
57
- domain_certificate_body: undefined,
58
- domain_certificate_private_key: undefined,
59
- domain_protocol: undefined,
60
- };
61
- }
62
- if (!isStructuredDomain(domain)) {
63
- return {
64
- domain: String(domain),
65
- www_bind_apex: false,
66
- domain_certificate_id: undefined,
67
- domain_certificate_body: undefined,
68
- domain_certificate_private_key: undefined,
69
- domain_protocol: undefined,
70
- };
71
- }
72
- const d = domain;
73
- return {
74
- domain: String(d.domain_name),
75
- www_bind_apex: (0, parseUtils_1.parseBooleanWithDefault)(d.www_bind_apex, false),
76
- domain_certificate_id: d.certificate_id != null ? String(d.certificate_id) : undefined,
77
- domain_certificate_body: d.certificate_body != null ? String(d.certificate_body) : undefined,
78
- domain_certificate_private_key: d.certificate_private_key != null ? String(d.certificate_private_key) : undefined,
79
- domain_protocol: d.protocol != null
80
- ? Array.isArray(d.protocol)
81
- ? d.protocol.map(String)
82
- : String(d.protocol)
83
- : undefined,
84
- };
30
+ // NOTE: the bucket-binding `protocol` field was removed in v1 (issue #283) —
31
+ // it was never consumed by any provider. Legacy usage is rejected at schema
32
+ // validation with a migration error (see validateSemantics).
33
+ // Binding identity is the normalized hostname (issue #279). Template refs are
34
+ // preserved verbatim — they resolve at deploy time.
35
+ const parseBindingHostname = (raw) => {
36
+ const value = String(raw);
37
+ return TEMPLATE_REF_PATTERN.test(value) ? value : (0, domainUtils_1.normalizeHostname)(value);
85
38
  };
39
+ const parseDomainBinding = (raw) => ({
40
+ domain_name: parseBindingHostname(raw.domain_name),
41
+ certificate_id: raw.certificate_id != null ? String(raw.certificate_id) : undefined,
42
+ certificate_body: raw.certificate_body != null ? String(raw.certificate_body) : undefined,
43
+ certificate_private_key: raw.certificate_private_key != null ? String(raw.certificate_private_key) : undefined,
44
+ cdn: parseCdnConfig(raw.cdn),
45
+ });
86
46
  /* istanbul ignore next */
87
47
  const parseBucket = (buckets) => {
88
48
  if (!buckets) {
89
49
  return undefined;
90
50
  }
91
51
  return Object.entries(buckets).map(([key, bucket]) => {
92
- let domainParsed = undefined;
93
- // Parse top-level domain (canonical form)
94
- if (bucket.domain) {
95
- const structuredDomain = isStructuredDomain(bucket.domain)
96
- ? bucket.domain
97
- : { domain_name: String(bucket.domain) };
98
- domainParsed = parseDomainConfig(structuredDomain, bucket.domain.accelerate);
99
- }
100
- // Fallback: parse website.domain (deprecated)
101
- if (!domainParsed && bucket.website?.domain) {
102
- logger_1.logger.warn(lang_1.lang.__('BUCKET_DOMAIN_DEPRECATED', { key }));
103
- const structuredDomain = isStructuredDomain(bucket.website.domain)
104
- ? bucket.website.domain
105
- : { domain_name: String(bucket.website.domain) };
106
- domainParsed = parseDomainConfig(structuredDomain, undefined);
107
- }
108
- const websiteDomain = parseWebsiteDomain(bucket.website?.domain);
52
+ const domains = bucket.domains?.map((entry) => parseDomainBinding(entry));
109
53
  // Parse IAM policy statements
110
54
  let iam;
111
55
  if (bucket.iam?.resource?.statements && Array.isArray(bucket.iam.resource.statements)) {
@@ -119,8 +63,8 @@ const parseBucket = (buckets) => {
119
63
  ? resourceRaw.map(String)
120
64
  : [String(resourceRaw)];
121
65
  const principal = {};
122
- for (const [key, val] of Object.entries(stmt.principal || {})) {
123
- principal[key] = val;
66
+ for (const [entryKey, val] of Object.entries(stmt.principal || {})) {
67
+ principal[entryKey] = val;
124
68
  }
125
69
  const parsedStmt = {
126
70
  effect: stmt.effect,
@@ -163,13 +107,12 @@ const parseBucket = (buckets) => {
163
107
  : undefined,
164
108
  }
165
109
  : undefined,
166
- // Parsed top-level domain config
167
- domain: domainParsed,
110
+ accelerate: (0, parseUtils_1.parseBooleanWithDefault)(bucket.accelerate, false),
111
+ domains,
168
112
  iam,
169
113
  website: bucket.website
170
114
  ? {
171
115
  code: String(bucket.website.code),
172
- ...websiteDomain,
173
116
  index: (0, parseUtils_1.parseStringWithDefault)(bucket.website.index, 'index.html'),
174
117
  }
175
118
  : undefined,
@@ -5,6 +5,7 @@ const lodash_1 = require("lodash");
5
5
  const parseUtils_1 = require("./parseUtils");
6
6
  const lang_1 = require("../lang");
7
7
  const siCron_1 = require("../common/siCron");
8
+ const functionDomainReconcile_1 = require("../common/functionDomainReconcile");
8
9
  const parseHttpTrigger = (raw, fnKey) => {
9
10
  if (!raw)
10
11
  return undefined;
@@ -57,14 +58,17 @@ const parseTimerTriggers = (raw, fnKey) => {
57
58
  }
58
59
  return timers;
59
60
  };
60
- const parseDomain = (raw) => {
61
- if (!raw)
61
+ const parseDomainBindings = (raw) => {
62
+ if (!raw || raw.length === 0)
62
63
  return undefined;
63
- return {
64
- domain_name: String(raw.domain_name),
65
- certificate_id: raw.certificate_id ? String(raw.certificate_id) : undefined,
66
- protocol: (0, parseUtils_1.parseStringWithDefault)(raw.protocol, 'HTTPS'),
67
- };
64
+ return raw.map((binding) => ({
65
+ domain_name: String(binding.domain_name),
66
+ path: (0, parseUtils_1.parseStringWithDefault)(binding.path, functionDomainReconcile_1.DEFAULT_FUNCTION_ROUTE_PATH),
67
+ certificate_id: (0, parseUtils_1.parseOptionalString)(binding.certificate_id),
68
+ certificate_body: (0, parseUtils_1.parseOptionalString)(binding.certificate_body),
69
+ certificate_private_key: (0, parseUtils_1.parseOptionalString)(binding.certificate_private_key),
70
+ protocol: (0, functionDomainReconcile_1.normalizeFunctionProtocol)(binding.protocol),
71
+ }));
68
72
  };
69
73
  const parseFunction = (functions) => {
70
74
  if ((0, lodash_1.isEmpty)(functions)) {
@@ -73,7 +77,7 @@ const parseFunction = (functions) => {
73
77
  return Object.entries(functions).map(([key, func]) => {
74
78
  const httpTrigger = parseHttpTrigger(func.triggers?.http, key);
75
79
  const timerTriggers = parseTimerTriggers(func.triggers?.timer, key);
76
- const domain = parseDomain(func.domain);
80
+ const domains = parseDomainBindings(func.domains);
77
81
  return {
78
82
  key,
79
83
  name: func.name,
@@ -146,7 +150,7 @@ const parseFunction = (functions) => {
146
150
  },
147
151
  }
148
152
  : {}),
149
- ...(domain ? { domain } : {}),
153
+ ...(domains ? { domains } : {}),
150
154
  };
151
155
  });
152
156
  };
@@ -7,6 +7,7 @@ const apigwTypes_1 = require("./apigwTypes");
7
7
  const stateManager_1 = require("../../common/stateManager");
8
8
  const common_1 = require("../../common");
9
9
  const certUtils_1 = require("../../common/certUtils");
10
+ const cdnCapabilities_1 = require("../../common/cdnCapabilities");
10
11
  const logger_1 = require("../../common/logger");
11
12
  const lang_1 = require("../../lang");
12
13
  const domainUtils_1 = require("../../common/domainUtils");
@@ -81,7 +82,7 @@ const buildApigwCdnDistributionConfig = (event, domainName, originDomain) => {
81
82
  ...(cdnConfig?.origin_protocol === 'https' ? { port: 443 } : {}),
82
83
  },
83
84
  ],
84
- scope: cdnConfig?.scope ?? 'global',
85
+ scope: (0, cdnCapabilities_1.mapCdnScope)('aliyun', cdnConfig?.scope),
85
86
  };
86
87
  };
87
88
  const createApigwCdnDistribution = async (context, client, event, domainName, originDomain, instances, certificate) => {
@@ -13,6 +13,7 @@ const refreshCache_1 = require("../../common/refreshCache");
13
13
  const planCompare_1 = require("../../common/planCompare");
14
14
  const concurrency_1 = require("../../common/concurrency");
15
15
  const siCron_1 = require("../../common/siCron");
16
+ const functionDomainReconcile_1 = require("../../common/functionDomainReconcile");
16
17
  const fc3Types_2 = require("./fc3Types");
17
18
  const fc3Resource_1 = require("./fc3Resource");
18
19
  const lang_1 = require("../../lang");
@@ -71,17 +72,33 @@ const resolveVpcConfigSecurityGroup = async (context, config) => {
71
72
  const removedFc3Dependents = (fn, currentState) => {
72
73
  const recorded = (type) => currentState?.instances?.find((i) => i.type === type);
73
74
  const recordedTimers = (currentState?.instances ?? []).filter((i) => i.type === 'ALIYUN_FC3_TIMER_TRIGGER');
75
+ // Removed domain bindings surface the stored canonicalized entries; a
76
+ // pre-#286 state (single instance, no definition.domains) reconstructs the
77
+ // legacy `/*` binding so the diff still shows the removal.
78
+ const recordedDomainInstances = (currentState?.instances ?? []).filter((i) => i.type === 'ALIYUN_FC3_CUSTOM_DOMAIN');
79
+ const storedDomains = currentState?.definition?.domains;
74
80
  return {
75
81
  ...(!fn.triggers?.http && recorded('ALIYUN_FC3_HTTP_TRIGGER')
76
82
  ? {
77
83
  http: currentState?.definition?.http ?? recorded('ALIYUN_FC3_HTTP_TRIGGER')?.attributes ?? {},
78
84
  }
79
85
  : {}),
80
- ...(!fn.domain && recorded('ALIYUN_FC3_CUSTOM_DOMAIN')
86
+ ...(!(fn.domains?.length ?? 0) && recordedDomainInstances.length > 0
81
87
  ? {
82
- domain: currentState?.definition?.domain ?? {
83
- domain_name: recorded('ALIYUN_FC3_CUSTOM_DOMAIN')?.id,
84
- },
88
+ domains: (Array.isArray(storedDomains) && storedDomains.length > 0
89
+ ? storedDomains
90
+ : recordedDomainInstances.map((i) => (0, functionDomainReconcile_1.functionDomainDefinitionEntry)({
91
+ domain_name: String(i.id),
92
+ path: i.paths?.[0] ?? '/*',
93
+ ...(typeof i.attributes
94
+ ?.certificate_id === 'string'
95
+ ? {
96
+ certificate_id: i
97
+ .attributes.certificate_id,
98
+ }
99
+ : {}),
100
+ protocol: ['HTTPS'],
101
+ }))),
85
102
  }
86
103
  : {}),
87
104
  ...(!fn.triggers?.timer && recordedTimers.length > 0
@@ -241,13 +258,16 @@ const detectFunctionLifecycleDrift = async (context, client, fn) => {
241
258
  reasons.push('PLAN_DRIFT_HTTP_TRIGGER');
242
259
  }
243
260
  }
244
- if (fn.domain) {
245
- const domain = await (0, refreshCache_1.cachedRefreshRead)(context, `fc3.getCustomDomain:${fn.domain.domain_name}`, () => client.fc3.getCustomDomain(fn.domain.domain_name));
246
- if (!domain ||
247
- (domain.protocol !== undefined && domain.protocol !== fn.domain.protocol) ||
248
- (domain.certConfig?.certificateId !== undefined &&
249
- fn.domain.certificate_id !== undefined &&
250
- domain.certConfig.certificateId !== fn.domain.certificate_id)) {
261
+ // Domain bindings (issue #286): every declared domain must exist with the
262
+ // expected protocol. Route drift is not probed here — the executor converges
263
+ // routes on every apply; certificate changes ride the state's
264
+ // certificate_hash. Template-ref protocol entries default through the same
265
+ // canonicalization the executor uses.
266
+ for (const binding of fn.domains ?? []) {
267
+ const domainName = (0, functionDomainReconcile_1.normalizeFunctionDomainName)(binding.domain_name);
268
+ const domain = await (0, refreshCache_1.cachedRefreshRead)(context, `fc3.getCustomDomain:${domainName}`, () => client.fc3.getCustomDomain(domainName));
269
+ const protocolString = (0, functionDomainReconcile_1.mapFunctionProtocol)('aliyun', binding.protocol);
270
+ if (!domain || (domain.protocol !== undefined && domain.protocol !== protocolString)) {
251
271
  reasons.push('PLAN_DRIFT_FUNCTION_DOMAIN');
252
272
  }
253
273
  }
@@ -404,7 +424,7 @@ const generateFunctionPlan = async (context, state, functions) => {
404
424
  const reasons = [roleReason, ...lifecycleReasons, nestedReason].filter((reason) => reason !== null);
405
425
  const fields = {
406
426
  PLAN_DRIFT_HTTP_TRIGGER: 'http',
407
- PLAN_DRIFT_FUNCTION_DOMAIN: 'domain',
427
+ PLAN_DRIFT_FUNCTION_DOMAIN: 'domains',
408
428
  PLAN_DRIFT_TIMER_TRIGGER: 'timers',
409
429
  };
410
430
  return {
@@ -15,6 +15,8 @@ const common_1 = require("../../common");
15
15
  const constants_1 = require("../../common/constants");
16
16
  const types_1 = require("../../types");
17
17
  const siCron_1 = require("../../common/siCron");
18
+ const certUtils_1 = require("../../common/certUtils");
19
+ const functionDomainReconcile_1 = require("../../common/functionDomainReconcile");
18
20
  const fc3Types_2 = require("./fc3Types");
19
21
  const slsOperations_1 = require("../../common/aliyunClient/slsOperations");
20
22
  const ecsOperations_1 = require("../../common/aliyunClient/ecsOperations");
@@ -25,6 +27,7 @@ const lang_1 = require("../../lang");
25
27
  const ownershipTag_1 = require("../ownershipTag");
26
28
  const alreadyExists_1 = require("../alreadyExists");
27
29
  const sharedLogProject_1 = require("./sharedLogProject");
30
+ const FC3_DOMAIN_INSTANCE_TYPE = 'ALIYUN_FC3_CUSTOM_DOMAIN';
28
31
  const RECOVERY_GET_FUNCTION_DELAY_MS = 1500;
29
32
  const delay = async (ms) => {
30
33
  await new Promise((resolve) => {
@@ -66,6 +69,145 @@ const FC3_ENI_ACTIONS = [
66
69
  ];
67
70
  const buildDefaultRoleName = common_1.buildFunctionRoleName;
68
71
  const buildFc3CertName = (service, stage) => `${service}-${stage}-fc3-domain`;
72
+ /** Resolves a binding's certificate to the inline PEM the FC3 API requires: a CAS reference is fetched, inline PEM is read (file path or literal). */
73
+ const resolveFc3CertMaterial = async (context, client, binding) => {
74
+ if (binding.certificate_id) {
75
+ const detail = await client.cas.getCertificate(binding.certificate_id);
76
+ if (!detail || !detail.cert || !detail.key) {
77
+ throw new Error(lang_1.lang.__('CERT_REFERENCE_NOT_FOUND', { reference: binding.certificate_id }));
78
+ }
79
+ return {
80
+ certName: buildFc3CertName(context.service, context.stage),
81
+ certificate: detail.cert,
82
+ privateKey: detail.key,
83
+ };
84
+ }
85
+ if (binding.certificate_body && binding.certificate_private_key) {
86
+ return {
87
+ certName: buildFc3CertName(context.service, context.stage),
88
+ certificate: (0, certUtils_1.readPemContent)(binding.certificate_body),
89
+ privateKey: (0, certUtils_1.readPemContent)(binding.certificate_private_key),
90
+ };
91
+ }
92
+ return undefined;
93
+ };
94
+ /**
95
+ * Releases a function's routes from a cloud-side domain (issue #286): a
96
+ * pure route subtraction — when the function was the last binding, the
97
+ * domain itself is deleted (per-owner teardown with a live-route check).
98
+ */
99
+ const releaseFc3DomainRoutes = async (client, domainName, own) => {
100
+ const live = await client.fc3.getCustomDomain(domainName);
101
+ if (!live)
102
+ return;
103
+ const liveRoutes = (0, functionDomainReconcile_1.toFunctionDomainRoutes)(live.routeConfig);
104
+ const remaining = (0, functionDomainReconcile_1.mergeDomainRoutes)(liveRoutes, own, 'remove');
105
+ if (remaining.length === 0) {
106
+ logger_1.logger.info(lang_1.lang.__('FUNCTION_DOMAIN_ROUTE_RELEASED', { functionName: own.functionName, domainName }));
107
+ await client.fc3.deleteCustomDomain(domainName);
108
+ logger_1.logger.info(lang_1.lang.__('CUSTOM_DOMAIN_DELETED', { domainName }));
109
+ return;
110
+ }
111
+ if ((0, functionDomainReconcile_1.routesEqual)(liveRoutes, remaining))
112
+ return;
113
+ logger_1.logger.info(lang_1.lang.__('REMOVING_FUNCTION_DOMAIN_ROUTES', { functionName: own.functionName, domainName }));
114
+ await client.fc3.updateCustomDomain(domainName, { routes: remaining });
115
+ };
116
+ const buildFc3DomainBindingInstance = (context, binding, protocolString) => ({
117
+ type: FC3_DOMAIN_INSTANCE_TYPE,
118
+ id: binding.domainName,
119
+ sid: (0, common_1.buildSid)('aliyun', 'fc3-custom-domain', context.stage, binding.domainName),
120
+ paths: binding.paths,
121
+ attributes: {
122
+ protocol: protocolString,
123
+ certificate_id: binding.representative.certificate_id ?? null,
124
+ },
125
+ });
126
+ /**
127
+ * Converges one domain binding: creates the domain (with state-less adoption
128
+ * when a previous partial run already created it — ownership proven by live
129
+ * routes referencing this stack's functions), or updates routes/protocol in
130
+ * place. Certificates redeploy only on content change (certificate_hash in
131
+ * state, issue #283 pattern).
132
+ */
133
+ const applyFc3DomainBinding = async (context, fn, existingState, client, desired, options) => {
134
+ const protocolString = (0, functionDomainReconcile_1.mapFunctionProtocol)('aliyun', desired.representative.protocol);
135
+ const live = await client.fc3.getCustomDomain(desired.domainName);
136
+ const liveRoutes = (0, functionDomainReconcile_1.toFunctionDomainRoutes)(live?.routeConfig);
137
+ const desiredRoutes = (0, functionDomainReconcile_1.mergeDomainRoutes)(liveRoutes, {
138
+ functionName: fn.name,
139
+ paths: desired.paths,
140
+ }, 'apply');
141
+ const desiredCertHash = (0, functionDomainReconcile_1.functionDomainDefinitionEntry)(desired.representative).certificate_hash ?? undefined;
142
+ const storedCertHash = (0, functionDomainReconcile_1.storedFunctionDomainCertHash)(existingState?.definition, desired.domainName);
143
+ const certChanged = storedCertHash !== desiredCertHash || options?.repairDomain === true;
144
+ const certMaterial = certChanged
145
+ ? await resolveFc3CertMaterial(context, client, desired.representative)
146
+ : undefined;
147
+ const converge = async (current) => {
148
+ const currentRoutes = (0, functionDomainReconcile_1.toFunctionDomainRoutes)(current.routeConfig);
149
+ const protocolChanged = current.protocol !== undefined && current.protocol !== protocolString;
150
+ const routesChanged = !(0, functionDomainReconcile_1.routesEqual)(currentRoutes, desiredRoutes);
151
+ if (protocolChanged || routesChanged || certMaterial) {
152
+ logger_1.logger.info(lang_1.lang.__('UPDATING_FUNCTION_DOMAIN_ROUTES', {
153
+ domainName: desired.domainName,
154
+ count: String(desiredRoutes.length),
155
+ }));
156
+ await client.fc3.updateCustomDomain(desired.domainName, {
157
+ protocol: protocolString,
158
+ routes: desiredRoutes,
159
+ ...(certMaterial ? { certConfig: certMaterial } : {}),
160
+ });
161
+ }
162
+ };
163
+ if (!live) {
164
+ const stackFunctionNames = (0, functionDomainReconcile_1.collectStackFunctionNames)(context.iac?.functions, fn.name);
165
+ try {
166
+ logger_1.logger.info(lang_1.lang.__('CREATING_CUSTOM_DOMAIN', { domainName: desired.domainName }));
167
+ await client.fc3.createCustomDomain(desired.domainName, protocolString, desiredRoutes, certMaterial);
168
+ logger_1.logger.info(lang_1.lang.__('CUSTOM_DOMAIN_CREATED', { domainName: desired.domainName }));
169
+ }
170
+ catch (error) {
171
+ if (!(0, alreadyExists_1.isResourceAlreadyExistsError)(error))
172
+ throw error;
173
+ const existing = await client.fc3.getCustomDomain(desired.domainName);
174
+ if (!existing ||
175
+ !(0, functionDomainReconcile_1.routesReferenceStackFunctions)((0, functionDomainReconcile_1.toFunctionDomainRoutes)(existing.routeConfig), stackFunctionNames)) {
176
+ throw new Error(lang_1.lang.__('FUNCTION_DOMAIN_EXISTS_NOT_OWNED', { domainName: desired.domainName }), error instanceof Error ? { cause: error } : undefined);
177
+ }
178
+ logger_1.logger.info(lang_1.lang.__('FUNCTION_DOMAIN_OWNED_ADOPT', { domainName: desired.domainName }));
179
+ await converge(existing);
180
+ }
181
+ }
182
+ else {
183
+ await converge(live);
184
+ }
185
+ return buildFc3DomainBindingInstance(context, desired, protocolString);
186
+ };
187
+ /**
188
+ * Reconciles every domain this function touches: desired bindings converge
189
+ * the shared domain resource (routes merged with other functions' routes),
190
+ * removed bindings are released. Returns the fresh binding instances.
191
+ */
192
+ const reconcileFc3FunctionDomains = async (context, fn, existingInstances, existingState, client, options) => {
193
+ const storedBindings = (0, functionDomainReconcile_1.storedFunctionDomainBindings)(existingInstances, FC3_DOMAIN_INSTANCE_TYPE);
194
+ const desiredBindings = (0, functionDomainReconcile_1.aggregateFunctionDomainBindings)(fn.domains);
195
+ const touched = [...new Set([...storedBindings.keys(), ...desiredBindings.keys()])].sort();
196
+ const instances = [];
197
+ for (const domainName of touched) {
198
+ const desired = desiredBindings.get(domainName);
199
+ if (desired) {
200
+ instances.push(await applyFc3DomainBinding(context, fn, existingState, client, desired, options));
201
+ }
202
+ else {
203
+ await releaseFc3DomainRoutes(client, domainName, {
204
+ functionName: fn.name,
205
+ paths: storedBindings.get(domainName)?.paths ?? [],
206
+ });
207
+ }
208
+ }
209
+ return instances;
210
+ };
69
211
  const collectRolePeers = (state, context, roleId) => {
70
212
  const peers = [];
71
213
  for (const [logicalId, resourceState] of Object.entries((0, common_1.getAllResources)(state))) {
@@ -760,7 +902,7 @@ const createResource = async (context, fn, state) => {
760
902
  lastUpdated: new Date().toISOString(),
761
903
  status: 'tainted',
762
904
  };
763
- const stateAfterDependents = (0, common_1.setResource)(stateWithSharedProject, logicalId, taintedResourceState);
905
+ let stateAfterDependents = (0, common_1.setResource)(stateWithSharedProject, logicalId, taintedResourceState);
764
906
  const client = (0, aliyunClient_1.createAliyunClient)(context);
765
907
  const isTainted = existingResourceState?.status === 'tainted';
766
908
  const existingFunctionOnRetry = isTainted ? await client.fc3.getFunction(fn.name) : null;
@@ -868,30 +1010,19 @@ const createResource = async (context, fn, state) => {
868
1010
  });
869
1011
  }
870
1012
  lifecycleInstances.push(...(await reconcileFc3TimerTriggers(context, fn, [], client)));
871
- if (fn.domain) {
872
- logger_1.logger.info(lang_1.lang.__('CREATING_CUSTOM_DOMAIN', { domainName: fn.domain.domain_name }));
873
- let certConfig;
874
- if (fn.domain.certificate_id) {
875
- const certId = fn.domain.certificate_id;
876
- const detail = await client.cas.getCertificate(certId);
877
- if (!detail || !detail.cert || !detail.key) {
878
- throw new Error(lang_1.lang.__('CERT_REFERENCE_NOT_FOUND', { reference: certId }));
879
- }
880
- certConfig = {
881
- certName: buildFc3CertName(context.service, context.stage),
882
- certificate: detail.cert,
883
- privateKey: detail.key,
884
- };
885
- }
886
- await client.fc3.createCustomDomain(fn.domain.domain_name, fn.domain.protocol, fn.name, certConfig);
887
- logger_1.logger.info(lang_1.lang.__('CUSTOM_DOMAIN_CREATED', { domainName: fn.domain.domain_name }));
888
- lifecycleInstances.push({
889
- type: 'ALIYUN_FC3_CUSTOM_DOMAIN',
890
- id: fn.domain.domain_name,
891
- sid: (0, common_1.buildSid)('aliyun', 'fc3-custom-domain', context.stage, fn.domain.domain_name),
892
- attributes: { protocol: fn.domain.protocol, certificate_id: fn.domain.certificate_id },
1013
+ // Snapshot trigger/timer progress before domain ops so a domain failure
1014
+ // doesn't lose the just-created trigger on retry.
1015
+ if (lifecycleInstances.length > 0) {
1016
+ stateAfterDependents = (0, common_1.setResource)(stateAfterDependents, logicalId, {
1017
+ ...taintedResourceState,
1018
+ instances: [
1019
+ fcInstance,
1020
+ ...lifecycleInstances,
1021
+ ...dependentInstances,
1022
+ ],
893
1023
  });
894
1024
  }
1025
+ lifecycleInstances.push(...(await reconcileFc3FunctionDomains(context, fn, existingDependentInstances, existingResourceState, client)));
895
1026
  }
896
1027
  catch (error) {
897
1028
  throw new types_1.PartialResourceError(stateAfterDependents, error instanceof Error ? error : new Error(String(error)));
@@ -1355,76 +1486,10 @@ const updateResource = async (context, providedFn, state, options) => {
1355
1486
  logger_1.logger.warn(lang_1.lang.__('HTTP_TRIGGER_NOT_FOUND', { triggerName: 'http-trigger' }));
1356
1487
  }
1357
1488
  }
1358
- const existingCustomDomain = existingInstances.find((i) => i.type === 'ALIYUN_FC3_CUSTOM_DOMAIN');
1359
- const desiredDomain = fn.domain;
1360
1489
  const timerInstances = await reconcileFc3TimerTriggers(context, fn, existingInstances, client);
1361
- if (desiredDomain && !existingCustomDomain) {
1362
- logger_1.logger.info(lang_1.lang.__('CREATING_CUSTOM_DOMAIN', { domainName: desiredDomain.domain_name }));
1363
- let certConfig;
1364
- if (desiredDomain.certificate_id) {
1365
- const certId = desiredDomain.certificate_id;
1366
- const detail = await client.cas.getCertificate(certId);
1367
- if (!detail || !detail.cert || !detail.key) {
1368
- throw new Error(lang_1.lang.__('CERT_REFERENCE_NOT_FOUND', { reference: certId }));
1369
- }
1370
- certConfig = {
1371
- certName: buildFc3CertName(context.service, context.stage),
1372
- certificate: detail.cert,
1373
- privateKey: detail.key,
1374
- };
1375
- }
1376
- await client.fc3.createCustomDomain(desiredDomain.domain_name, desiredDomain.protocol, fn.name, certConfig);
1377
- logger_1.logger.info(lang_1.lang.__('CUSTOM_DOMAIN_CREATED', { domainName: desiredDomain.domain_name }));
1378
- }
1379
- else if (!desiredDomain && existingCustomDomain) {
1380
- logger_1.logger.info(lang_1.lang.__('DELETING_CUSTOM_DOMAIN', { domainName: existingCustomDomain.id }));
1381
- try {
1382
- await client.fc3.deleteCustomDomain(existingCustomDomain.id);
1383
- logger_1.logger.info(lang_1.lang.__('CUSTOM_DOMAIN_DELETED', { domainName: existingCustomDomain.id }));
1384
- }
1385
- catch (err) {
1386
- const errorCode = err?.code;
1387
- if (errorCode !== 'CustomDomainNotFound')
1388
- throw err;
1389
- logger_1.logger.warn(lang_1.lang.__('RESOURCE_NOT_FOUND_PROVIDER', {
1390
- resourceType: 'Custom Domain',
1391
- name: existingCustomDomain.id,
1392
- }));
1393
- }
1394
- }
1395
- else if (desiredDomain && existingCustomDomain) {
1396
- const existingProtocol = existingCustomDomain.attributes?.protocol;
1397
- const domainChanged = options?.repairDomain ||
1398
- !(0, common_1.attributesEqual)(existingState?.definition?.domain ?? {}, desiredDomain) ||
1399
- desiredDomain.domain_name !== existingCustomDomain.id ||
1400
- desiredDomain.protocol !== existingProtocol;
1401
- if (domainChanged) {
1402
- logger_1.logger.info(lang_1.lang.__('UPDATING_CUSTOM_DOMAIN', { domainName: desiredDomain.domain_name }));
1403
- let certConfig;
1404
- if (desiredDomain.certificate_id) {
1405
- const certId = desiredDomain.certificate_id;
1406
- const detail = await client.cas.getCertificate(certId);
1407
- if (!detail || !detail.cert || !detail.key) {
1408
- throw new Error(lang_1.lang.__('CERT_REFERENCE_NOT_FOUND', { reference: certId }));
1409
- }
1410
- certConfig = {
1411
- certName: buildFc3CertName(context.service, context.stage),
1412
- certificate: detail.cert,
1413
- privateKey: detail.key,
1414
- };
1415
- }
1416
- try {
1417
- await client.fc3.deleteCustomDomain(existingCustomDomain.id);
1418
- }
1419
- catch (err) {
1420
- const errorCode = err?.code;
1421
- if (errorCode !== 'CustomDomainNotFound')
1422
- throw err;
1423
- }
1424
- await client.fc3.createCustomDomain(desiredDomain.domain_name, desiredDomain.protocol, fn.name, certConfig);
1425
- logger_1.logger.info(lang_1.lang.__('CUSTOM_DOMAIN_CREATED', { domainName: desiredDomain.domain_name }));
1426
- }
1427
- }
1490
+ // Cross-function merged routes (issue #286): this function's bindings
1491
+ // converge the shared domain resources; removed bindings release routes.
1492
+ const domainInstances = await reconcileFc3FunctionDomains(context, fn, existingInstances, existingState, client, { repairDomain: options?.repairDomain });
1428
1493
  const functionInfo = await client.fc3.getFunction(fn.name);
1429
1494
  if (!functionInfo) {
1430
1495
  throw new Error(lang_1.lang.__('REFRESH_STATE_FUNCTION', { name: fn.name }));
@@ -1445,14 +1510,7 @@ const updateResource = async (context, providedFn, state, options) => {
1445
1510
  });
1446
1511
  }
1447
1512
  lifecycleInstances.push(...timerInstances);
1448
- if (fn.domain) {
1449
- lifecycleInstances.push({
1450
- type: 'ALIYUN_FC3_CUSTOM_DOMAIN',
1451
- id: fn.domain.domain_name,
1452
- sid: (0, common_1.buildSid)('aliyun', 'fc3-custom-domain', context.stage, fn.domain.domain_name),
1453
- attributes: { protocol: fn.domain.protocol },
1454
- });
1455
- }
1513
+ lifecycleInstances.push(...domainInstances);
1456
1514
  const existingDependentInstances = existingInstances
1457
1515
  .filter((i) => i.type !== 'ALIYUN_FC3_FUNCTION')
1458
1516
  .filter((i) => i.type !== 'ALIYUN_FC3_HTTP_TRIGGER')
@@ -1482,7 +1540,7 @@ const updateResource = async (context, providedFn, state, options) => {
1482
1540
  const resourceState = {
1483
1541
  mode: 'managed',
1484
1542
  region: context.region,
1485
- definition: (0, functionDefinition_1.withLifecycleIntent)((0, planCompare_1.mergeManagedIntent)(existingState?.definition ?? {}, definition), definition, ['http', 'domain', 'timers']),
1543
+ definition: (0, functionDefinition_1.withLifecycleIntent)((0, planCompare_1.mergeManagedIntent)(existingState?.definition ?? {}, definition), definition, ['http', 'domains', 'timers']),
1486
1544
  instances: [
1487
1545
  fcInstance,
1488
1546
  ...lifecycleInstances,
@@ -1525,6 +1583,16 @@ const deleteResource = async (context, functionName, logicalId, state) => {
1525
1583
  logger_1.logger.warn(lang_1.lang.__('TIMER_TRIGGER_NOT_FOUND', { triggerName: timerInstance.id }));
1526
1584
  }
1527
1585
  }
1586
+ // Domain routes are released before the trigger/function teardown (issue
1587
+ // #286 contract: domain 摘除 → trigger → function). Other functions' routes
1588
+ // survive; the domain itself is deleted only when this was the last binding.
1589
+ const storedDomainBindings = (0, functionDomainReconcile_1.storedFunctionDomainBindings)(existingInstances, FC3_DOMAIN_INSTANCE_TYPE);
1590
+ for (const [domainName, binding] of storedDomainBindings) {
1591
+ await releaseFc3DomainRoutes(client, domainName, {
1592
+ functionName,
1593
+ paths: binding.paths,
1594
+ });
1595
+ }
1528
1596
  const httpTriggerInstance = existingInstances.find((i) => i.type === 'ALIYUN_FC3_HTTP_TRIGGER');
1529
1597
  if (httpTriggerInstance) {
1530
1598
  logger_1.logger.info(lang_1.lang.__('DELETING_HTTP_TRIGGER', { triggerName: httpTriggerInstance.id, functionName }));
@@ -1542,26 +1610,6 @@ const deleteResource = async (context, functionName, logicalId, state) => {
1542
1610
  }
1543
1611
  }
1544
1612
  }
1545
- const customDomainInstance = existingInstances.find((i) => i.type === 'ALIYUN_FC3_CUSTOM_DOMAIN');
1546
- if (customDomainInstance) {
1547
- logger_1.logger.info(lang_1.lang.__('DELETING_CUSTOM_DOMAIN', { domainName: customDomainInstance.id }));
1548
- try {
1549
- await client.fc3.deleteCustomDomain(customDomainInstance.id);
1550
- logger_1.logger.info(lang_1.lang.__('CUSTOM_DOMAIN_DELETED', { domainName: customDomainInstance.id }));
1551
- }
1552
- catch (err) {
1553
- const errorCode = err?.code;
1554
- if (errorCode === 'CustomDomainNotFound') {
1555
- logger_1.logger.warn(lang_1.lang.__('RESOURCE_NOT_FOUND_PROVIDER', {
1556
- resourceType: 'Custom Domain',
1557
- name: customDomainInstance.id,
1558
- }));
1559
- }
1560
- else {
1561
- throw err;
1562
- }
1563
- }
1564
- }
1565
1613
  const hasFcFunction = existingInstances.some((i) => i.type === 'ALIYUN_FC3_FUNCTION');
1566
1614
  if (hasFcFunction) {
1567
1615
  try {