@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,15 +3,15 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
3
3
  return (mod && mod.__esModule) ? mod : { "default": mod };
4
4
  };
5
5
  Object.defineProperty(exports, "__esModule", { value: true });
6
- exports.validateApiKeyFormat = exports.resolveApiKey = exports.resolveConsoleUiUrl = exports.getConsoleUrl = exports.resolveConsoleUrl = exports.clearCredentials = exports.deleteCredentials = exports.saveCredentials = exports.loadCredentials = exports.getCredentialsPath = void 0;
6
+ exports.validateApiKeyFormat = exports.parseApiKeyLine = exports.bestEffortConsoleOrigin = exports.resolveApiKey = exports.findProfilesBySlug = exports.loadCredentials = exports.clearCredentials = exports.deleteCredentials = exports.removeActiveProfile = exports.updateProfile = exports.saveProfile = exports.loadCredentialsFile = exports.getCredentialsPath = void 0;
7
7
  const node_fs_1 = __importDefault(require("node:fs"));
8
8
  const node_path_1 = __importDefault(require("node:path"));
9
9
  const node_os_1 = __importDefault(require("node:os"));
10
10
  const logger_1 = require("./logger");
11
11
  const lang_1 = require("../lang");
12
+ const consoleLines_1 = require("./consoleLines");
12
13
  const CREDENTIALS_DIR = '.serverlessinsight';
13
14
  const CREDENTIALS_FILE = 'credentials.json';
14
- const DEFAULT_CONSOLE_URL = 'https://api.console.serverlessinsight.com';
15
15
  const getCredentialsPath = () => {
16
16
  return node_path_1.default.join(node_os_1.default.homedir(), CREDENTIALS_DIR, CREDENTIALS_FILE);
17
17
  };
@@ -22,32 +22,114 @@ const ensureCredentialsDir = () => {
22
22
  node_fs_1.default.mkdirSync(dir, { recursive: true });
23
23
  }
24
24
  };
25
- const loadCredentials = () => {
25
+ const isLegacyShape = (value) => typeof value['apiKey'] === 'string' && typeof value['consoleUrl'] === 'string';
26
+ /** v1 → v2 heal is in-memory only; the file is rewritten on the next save. */
27
+ const healLegacy = (legacy) => {
28
+ const line = (0, consoleLines_1.resolveLineFromOrigin)(legacy.consoleUrl) ?? 'international';
29
+ const key = legacy.orgSlug
30
+ ? (0, consoleLines_1.toProfileKey)(line, legacy.orgSlug)
31
+ : `${line}/legacy-${legacy.orgId.slice(0, 8)}`;
32
+ return {
33
+ active: key,
34
+ profiles: {
35
+ [key]: {
36
+ apiKey: legacy.apiKey,
37
+ orgId: legacy.orgId,
38
+ ...(legacy.orgName ? { orgName: legacy.orgName } : {}),
39
+ ...(legacy.orgSlug ? { orgSlug: legacy.orgSlug } : {}),
40
+ ...(legacy.userEmail ? { userEmail: legacy.userEmail } : {}),
41
+ },
42
+ },
43
+ };
44
+ };
45
+ const loadCredentialsFile = () => {
26
46
  const credPath = (0, exports.getCredentialsPath)();
27
47
  if (!node_fs_1.default.existsSync(credPath)) {
28
48
  return null;
29
49
  }
30
50
  try {
31
- const content = node_fs_1.default.readFileSync(credPath, 'utf-8');
32
- const parsed = JSON.parse(content);
33
- if (!parsed.apiKey || !parsed.consoleUrl || !parsed.orgId) {
34
- return null;
51
+ const parsed = JSON.parse(node_fs_1.default.readFileSync(credPath, 'utf-8'));
52
+ if (isLegacyShape(parsed)) {
53
+ return healLegacy(parsed);
54
+ }
55
+ const profiles = (parsed.profiles ?? {});
56
+ const active = typeof parsed.active === 'string' ? parsed.active : undefined;
57
+ if (active && !profiles[active]) {
58
+ return { profiles };
35
59
  }
36
- return parsed;
60
+ return { ...(active ? { active } : {}), profiles };
37
61
  }
38
62
  catch {
39
63
  logger_1.logger.warn(lang_1.lang.__('CREDENTIAL_CORRUPTED'));
40
64
  return null;
41
65
  }
42
66
  };
43
- exports.loadCredentials = loadCredentials;
44
- const saveCredentials = (creds) => {
67
+ exports.loadCredentialsFile = loadCredentialsFile;
68
+ const writeFile = (file) => {
45
69
  ensureCredentialsDir();
46
70
  const credPath = (0, exports.getCredentialsPath)();
47
- node_fs_1.default.writeFileSync(credPath, JSON.stringify(creds, null, 2), 'utf-8');
71
+ node_fs_1.default.writeFileSync(credPath, JSON.stringify(file, null, 2), 'utf-8');
48
72
  node_fs_1.default.chmodSync(credPath, 0o600);
49
73
  };
50
- exports.saveCredentials = saveCredentials;
74
+ /** Store (or replace) the profile for `line/orgSlug` and optionally make it active. */
75
+ const saveProfile = (line, profile, options) => {
76
+ const file = (0, exports.loadCredentialsFile)() ?? { profiles: {} };
77
+ const key = (0, consoleLines_1.toProfileKey)(line, profile.orgSlug);
78
+ const profiles = { ...file.profiles };
79
+ // Re-key cleanup: one login per org — any other stored entry for the same
80
+ // orgId (e.g. a healed `line/legacy-…` key) is stale once the slug-keyed
81
+ // entry exists.
82
+ for (const existing of Object.keys(profiles)) {
83
+ if (existing !== key && profiles[existing].orgId === profile.orgId) {
84
+ delete profiles[existing];
85
+ }
86
+ }
87
+ profiles[key] = profile;
88
+ const active = options?.activate || !file.active || !profiles[file.active] ? key : file.active;
89
+ writeFile({ active, profiles });
90
+ };
91
+ exports.saveProfile = saveProfile;
92
+ /** Re-key a profile after verifying its slug with the same API key. */
93
+ const updateProfile = (profileKey, apiKey, patch) => {
94
+ const file = (0, exports.loadCredentialsFile)();
95
+ const current = file?.profiles[profileKey];
96
+ const profile = (0, consoleLines_1.splitProfileKey)(profileKey);
97
+ if (!file || !current || current.apiKey !== apiKey || !profile)
98
+ return;
99
+ const resolvedKey = (0, consoleLines_1.toProfileKey)(profile.line, patch.orgSlug);
100
+ if (resolvedKey !== profileKey && file.profiles[resolvedKey])
101
+ return;
102
+ const profiles = { ...file.profiles };
103
+ delete profiles[profileKey];
104
+ profiles[resolvedKey] = { ...current, ...patch };
105
+ writeFile({
106
+ active: file.active === profileKey ? resolvedKey : file.active,
107
+ profiles,
108
+ });
109
+ };
110
+ exports.updateProfile = updateProfile;
111
+ /** Log out: remove the active profile; drop the file entirely when it holds nothing else. */
112
+ const removeActiveProfile = () => {
113
+ const file = (0, exports.loadCredentialsFile)();
114
+ if (!file?.active)
115
+ return null;
116
+ const active = file.active;
117
+ const profile = file.profiles[active];
118
+ const profiles = { ...file.profiles };
119
+ delete profiles[active];
120
+ if (Object.keys(profiles).length === 0) {
121
+ (0, exports.deleteCredentials)();
122
+ }
123
+ else {
124
+ writeFile({ profiles });
125
+ }
126
+ if (!profile)
127
+ return null;
128
+ const split = active.indexOf('/');
129
+ const line = (split > 0 ? active.slice(0, split) : '');
130
+ return { ...profile, line, profileKey: active };
131
+ };
132
+ exports.removeActiveProfile = removeActiveProfile;
51
133
  const deleteCredentials = () => {
52
134
  const credPath = (0, exports.getCredentialsPath)();
53
135
  if (node_fs_1.default.existsSync(credPath)) {
@@ -56,39 +138,54 @@ const deleteCredentials = () => {
56
138
  };
57
139
  exports.deleteCredentials = deleteCredentials;
58
140
  exports.clearCredentials = exports.deleteCredentials;
59
- const resolveConsoleUrl = (creds) => {
60
- return process.env.SI_CONSOLE_URL || creds?.consoleUrl || DEFAULT_CONSOLE_URL;
61
- };
62
- exports.resolveConsoleUrl = resolveConsoleUrl;
63
- const getConsoleUrl = () => {
64
- return process.env.SI_CONSOLE_URL || DEFAULT_CONSOLE_URL;
65
- };
66
- exports.getConsoleUrl = getConsoleUrl;
67
141
  /**
68
- * Resolve the console FRONTEND (UI) URL for browser flows (e.g. /cli/authorize).
69
- * The API URL and the UI URL differ: production uses api./console. subdomains;
70
- * local dev runs the API on :3000 and the Vite dev server on :5173.
142
+ * The active profile, resolved against the store. Legacy files are healed in
143
+ * memory, so callers always see the composite shape. Returns null when no
144
+ * active profile exists.
71
145
  */
72
- const resolveConsoleUiUrl = (creds) => {
73
- if (process.env.SI_CONSOLE_UI_URL) {
74
- return process.env.SI_CONSOLE_UI_URL;
75
- }
76
- const apiUrl = (0, exports.resolveConsoleUrl)(creds);
77
- if (apiUrl.includes('api.')) {
78
- return apiUrl.replace('api.', 'console.');
79
- }
80
- if (apiUrl.includes('localhost:3000')) {
81
- return apiUrl.replace('localhost:3000', 'localhost:5173');
82
- }
83
- return apiUrl;
146
+ const loadCredentials = () => {
147
+ const file = (0, exports.loadCredentialsFile)();
148
+ if (!file?.active)
149
+ return null;
150
+ const profile = file.profiles[file.active];
151
+ if (!profile)
152
+ return null;
153
+ const split = file.active.indexOf('/');
154
+ const line = split > 0
155
+ ? ((0, consoleLines_1.normalizeLineName)(file.active.slice(0, split)) ?? 'international')
156
+ : 'international';
157
+ return { ...profile, line, profileKey: file.active };
84
158
  };
85
- exports.resolveConsoleUiUrl = resolveConsoleUiUrl;
159
+ exports.loadCredentials = loadCredentials;
160
+ /** Find profiles whose org slug matches; used by the yml `org:` resolution step. */
161
+ const findProfilesBySlug = (file, orgSlug) => {
162
+ return Object.entries(file.profiles).flatMap(([key, profile]) => {
163
+ const parsed = (0, consoleLines_1.splitProfileKey)(key);
164
+ return parsed && (profile.orgSlug ?? parsed.orgSlug) === orgSlug ? [key] : [];
165
+ });
166
+ };
167
+ exports.findProfilesBySlug = findProfilesBySlug;
86
168
  const resolveApiKey = (params) => {
87
169
  const { siApiKey, envKey, creds } = params;
88
170
  return siApiKey ?? envKey ?? creds?.apiKey ?? null;
89
171
  };
90
172
  exports.resolveApiKey = resolveApiKey;
91
- const validateApiKeyFormat = (key) => {
92
- return /^si_[A-Za-z0-9_-]{12}_[A-Za-z0-9_-]{32}$/.test(key);
173
+ /** Best-effort console origin for informational messages (force-unlock hint etc.). */
174
+ const bestEffortConsoleOrigin = () => {
175
+ const file = (0, exports.loadCredentialsFile)();
176
+ const active = file?.active;
177
+ if (active) {
178
+ const separator = active.indexOf('/');
179
+ const line = (0, consoleLines_1.normalizeLineName)(separator > 0 ? active.slice(0, separator) : undefined);
180
+ if (line)
181
+ return (0, consoleLines_1.consoleOriginFor)(line);
182
+ }
183
+ // Undocumented internal test/dev hook; never part of the product surface.
184
+ return process.env.SI_CONSOLE_URL || 'https://console.serverlessinsight.com';
93
185
  };
94
- exports.validateApiKeyFormat = validateApiKeyFormat;
186
+ exports.bestEffortConsoleOrigin = bestEffortConsoleOrigin;
187
+ // Re-exports keep the historical import surface working while the format
188
+ // helpers live in consoleLines (ADR-008).
189
+ var consoleLines_2 = require("./consoleLines");
190
+ Object.defineProperty(exports, "parseApiKeyLine", { enumerable: true, get: function () { return consoleLines_2.parseApiKeyLine; } });
191
+ Object.defineProperty(exports, "validateApiKeyFormat", { enumerable: true, get: function () { return consoleLines_2.validateApiKeyFormat; } });
@@ -1,6 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.resolveWwwBindingAction = exports.deriveWwwDomain = exports.extractHostRecord = exports.extractMainDomain = exports.normalizeDomain = void 0;
3
+ exports.deriveWwwDomain = exports.extractHostRecord = exports.extractMainDomain = exports.wildcardCovers = exports.getWildcardSuffix = exports.isWildcardHostname = exports.normalizeHostname = exports.normalizeDomain = void 0;
4
4
  const MULTI_LEVEL_TLDS = new Set([
5
5
  // United Kingdom
6
6
  'co.uk',
@@ -100,6 +100,28 @@ const normalizeDomain = (domain) => {
100
100
  return domain;
101
101
  };
102
102
  exports.normalizeDomain = normalizeDomain;
103
+ /**
104
+ * Binding identity (issue #279): a hostname normalized to lowercase, so
105
+ * `WWW.Example.com` and `www.example.com` are the same binding. Template refs
106
+ * are preserved verbatim by the caller — they resolve later.
107
+ */
108
+ const normalizeHostname = (hostname) => hostname.trim().toLowerCase();
109
+ exports.normalizeHostname = normalizeHostname;
110
+ const isWildcardHostname = (hostname) => hostname.startsWith('*.');
111
+ exports.isWildcardHostname = isWildcardHostname;
112
+ /** Suffix covered by a wildcard hostname (`*.example.com` → `example.com`), or null. */
113
+ const getWildcardSuffix = (hostname) => (0, exports.isWildcardHostname)(hostname) ? hostname.slice(2) : null;
114
+ exports.getWildcardSuffix = getWildcardSuffix;
115
+ /**
116
+ * Whether a wildcard hostname covers an exact hostname for routing purposes:
117
+ * `*.example.com` covers `www.example.com` (any non-empty label list below the
118
+ * suffix) but not the apex `example.com` itself.
119
+ */
120
+ const wildcardCovers = (wildcard, hostname) => {
121
+ const suffix = (0, exports.getWildcardSuffix)(wildcard);
122
+ return suffix != null && hostname.endsWith(`.${suffix}`);
123
+ };
124
+ exports.wildcardCovers = wildcardCovers;
103
125
  const extractMainDomain = (domainName) => {
104
126
  const parts = domainName.split('.');
105
127
  if (parts.length <= 2) {
@@ -144,6 +166,3 @@ const deriveWwwDomain = (domain) => {
144
166
  return `www.${domain}`;
145
167
  };
146
168
  exports.deriveWwwDomain = deriveWwwDomain;
147
- /** Omission restores the framework default: no www binding. */
148
- const resolveWwwBindingAction = (declared) => declared === true ? 'ensure' : 'remove';
149
- exports.resolveWwwBindingAction = resolveWwwBindingAction;
@@ -2,12 +2,15 @@
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.withStoredFunctionIam = exports.withLifecycleIntent = exports.withFunctionLifecycle = void 0;
4
4
  const planCompare_1 = require("./planCompare");
5
+ const functionDomainReconcile_1 = require("./functionDomainReconcile");
5
6
  /** Persist lifecycle intent alongside function configuration, using the same shape on every provider. */
6
7
  const withFunctionLifecycle = (definition, fn, support = {}) => ({
7
8
  ...definition,
8
9
  ...(fn?.log !== undefined && !definition.logConfig ? { logEnabled: fn.log } : {}),
9
10
  ...(support.http !== false && fn?.triggers?.http ? { http: fn.triggers.http } : {}),
10
- ...(support.domain !== false && fn?.domain ? { domain: fn.domain } : {}),
11
+ ...(support.domains !== false && fn?.domains
12
+ ? { domains: (0, functionDomainReconcile_1.canonicalFunctionDomains)(fn.domains) }
13
+ : {}),
11
14
  ...(fn?.triggers?.timer !== undefined ? { timers: fn.triggers.timer } : {}),
12
15
  });
13
16
  exports.withFunctionLifecycle = withFunctionLifecycle;
@@ -0,0 +1,28 @@
1
+ "use strict";
2
+ /**
3
+ * Provider function-domain capability registry (issue #286, #282 fail-fast row).
4
+ *
5
+ * Single source of truth for whether a provider implements direct custom
6
+ * domain binding on functions, and whether wildcard domains (`*.example.com`)
7
+ * are accepted by that provider's domain API. Semantic validation fail-fasts
8
+ * on unsupported combinations; delivering function domains for a provider
9
+ * narrows this registry instead of adding per-executor checks.
10
+ *
11
+ * Deliberately pure (no logger/lang imports) so the validator can import it
12
+ * without dragging runtime state into the validation graph. Only the accessor
13
+ * helper is exported — the registry table itself stays internal.
14
+ */
15
+ Object.defineProperty(exports, "__esModule", { value: true });
16
+ exports.resolveFunctionDomainCapability = void 0;
17
+ // Verified against provider APIs (2026-11):
18
+ // - aliyun FC3: POST /2023-03-30/custom-domains; wildcard domains supported.
19
+ // - tencent SCF: CreateCustomDomain (2018-04-16); docs state 通配符域名不支持.
20
+ // - volcengine veFaaS: no domain API at all (triggers: Timer/APIG/Kafka/... only);
21
+ // the real path is an APIG trigger + APIG domain binding (event-domain model).
22
+ const FUNCTION_DOMAIN_CAPABILITIES = {
23
+ aliyun: { functionDomains: true, wildcardDomains: true },
24
+ tencent: { functionDomains: true, wildcardDomains: false },
25
+ volcengine: { functionDomains: false, wildcardDomains: false },
26
+ };
27
+ const resolveFunctionDomainCapability = (providerName) => FUNCTION_DOMAIN_CAPABILITIES[providerName];
28
+ exports.resolveFunctionDomainCapability = resolveFunctionDomainCapability;
@@ -0,0 +1,197 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.collectStackFunctionNames = exports.routesReferenceStackFunctions = exports.toFunctionDomainRoutes = exports.storedFunctionDomainCertHash = exports.aggregateFunctionDomainBindings = exports.storedFunctionDomainBindings = exports.canonicalFunctionDomains = exports.functionDomainDefinitionEntry = exports.routesEqual = exports.mergeDomainRoutes = exports.isValidFunctionRoutePath = exports.mapFunctionProtocol = exports.normalizeFunctionProtocol = exports.normalizeFunctionDomainName = exports.DEFAULT_FUNCTION_QUALIFIER = exports.DEFAULT_FUNCTION_ROUTE_PATH = void 0;
4
+ const certUtils_1 = require("./certUtils");
5
+ /**
6
+ * Cross-provider core for function custom domains (issue #286).
7
+ *
8
+ * The domain model is binding-per-function, domain-per-cloud: each function
9
+ * declares `domains` bindings; bindings sharing a `domain_name` are merged
10
+ * into ONE cloud-side domain resource whose route list maps paths to the
11
+ * declaring functions. Aliyun FC3 (`routeConfig.routes[]`) and Tencent SCF
12
+ * (`EndpointsConfig[]`) share the same shape, so the route merge, protocol
13
+ * canonicalization and definition canonicalization live here once; provider
14
+ * stacks only supply their cloud operations and instance-type strings.
15
+ */
16
+ exports.DEFAULT_FUNCTION_ROUTE_PATH = '/*';
17
+ exports.DEFAULT_FUNCTION_QUALIFIER = '$DEFAULT';
18
+ const normalizeFunctionDomainName = (domainName) => domainName.trim().toLowerCase();
19
+ exports.normalizeFunctionDomainName = normalizeFunctionDomainName;
20
+ const isFunctionProtocol = (value) => value === 'HTTP' || value === 'HTTPS';
21
+ /**
22
+ * Canonical protocol form: a sorted, de-duplicated subset of HTTP/HTTPS.
23
+ * Accepts the scalar (`HTTPS`) and array (`[HTTP, HTTPS]`) YAML forms; empty
24
+ * input restores the documented default `[HTTPS]` (issue #286).
25
+ */
26
+ const normalizeFunctionProtocol = (raw) => {
27
+ const values = (Array.isArray(raw) ? raw : raw !== undefined ? [raw] : [])
28
+ .map((value) => String(value).trim().toUpperCase())
29
+ .filter(isFunctionProtocol);
30
+ const unique = [...new Set(values)].sort();
31
+ return unique.length > 0 ? unique : ['HTTPS'];
32
+ };
33
+ exports.normalizeFunctionProtocol = normalizeFunctionProtocol;
34
+ /** The single protocol string each provider API expects (`HTTP`, `HTTPS`, or the combined form). */
35
+ const mapFunctionProtocol = (provider, protocols) => {
36
+ if (protocols.length >= 2)
37
+ return provider === 'aliyun' ? 'HTTP,HTTPS' : 'HTTP&HTTPS';
38
+ return protocols[0];
39
+ };
40
+ exports.mapFunctionProtocol = mapFunctionProtocol;
41
+ /**
42
+ * Route-path rules shared by semantic validation and the parser: the path
43
+ * must start with `/`, and `*` may appear at most once and only as the last
44
+ * character (both aliyun and tencent accept exact paths or a trailing
45
+ * wildcard; matching is exact > longest-prefix, never regex).
46
+ */
47
+ const isValidFunctionRoutePath = (path) => {
48
+ if (!path.startsWith('/'))
49
+ return false;
50
+ const wildcardIndex = path.indexOf('*');
51
+ if (wildcardIndex === -1)
52
+ return true;
53
+ return wildcardIndex === path.length - 1 && path.lastIndexOf('*') === wildcardIndex;
54
+ };
55
+ exports.isValidFunctionRoutePath = isValidFunctionRoutePath;
56
+ const routeSortKey = (route) => `${route.path}\u0000${route.functionName}`;
57
+ /**
58
+ * Subtractive-merge reconcile (issue #286): si owns the whole domain resource,
59
+ * but each function reconciles ONLY its own routes. Routes pointing at other
60
+ * functions pass through untouched (preserving their qualifier), the owning
61
+ * function's previous routes are replaced by its desired paths.
62
+ *
63
+ * - `apply`: converge the domain towards (live minus own stale) plus own paths.
64
+ * - `remove`: drop every route of the owning function (function teardown or
65
+ * binding removal) — the caller deletes the domain when the result is empty.
66
+ */
67
+ const mergeDomainRoutes = (live, own, mode) => {
68
+ const others = (live ?? []).filter((route) => route.functionName !== own.functionName);
69
+ if (mode === 'remove')
70
+ return [...others].sort((a, b) => routeSortKey(a).localeCompare(routeSortKey(b)));
71
+ const ownPaths = [...new Set(own.paths)];
72
+ const ownRoutes = ownPaths.map((path) => ({ path, functionName: own.functionName }));
73
+ return [...others, ...ownRoutes].sort((a, b) => routeSortKey(a).localeCompare(routeSortKey(b)));
74
+ };
75
+ exports.mergeDomainRoutes = mergeDomainRoutes;
76
+ /** Whether two normalized route lists describe the same routing table (order-insensitive; qualifier ignored — si routes are always $DEFAULT). */
77
+ const routesEqual = (a, b) => {
78
+ const keyOf = (route) => `${route.path}\u0000${route.functionName}`;
79
+ const aKeys = (a ?? []).map(keyOf).sort();
80
+ const bKeys = (b ?? []).map(keyOf).sort();
81
+ return aKeys.length === bKeys.length && aKeys.every((key, index) => key === bKeys[index]);
82
+ };
83
+ exports.routesEqual = routesEqual;
84
+ /**
85
+ * Canonicalized definition entry for one binding — the exact shape persisted
86
+ * in state and compared by plan/diff. `certificate_hash` records the content
87
+ * hash of inline PEM (or reference id) so cert redeploys only happen on
88
+ * change (issue #283 pattern, applied to function domains by #286).
89
+ */
90
+ const functionDomainDefinitionEntry = (binding) => ({
91
+ domain_name: binding.domain_name,
92
+ path: binding.path,
93
+ certificate_id: binding.certificate_id ?? null,
94
+ certificate_body: binding.certificate_body ?? null,
95
+ certificate_private_key: binding.certificate_private_key ? '(managed)' : null,
96
+ certificate_hash: (0, certUtils_1.resolveBindingCertificateHash)({
97
+ certificate_id: binding.certificate_id,
98
+ certificate_body: binding.certificate_body,
99
+ certificate_private_key: binding.certificate_private_key,
100
+ }) ?? null,
101
+ protocol: binding.protocol,
102
+ });
103
+ exports.functionDomainDefinitionEntry = functionDomainDefinitionEntry;
104
+ /** Bindings sorted by (domain, path) so YAML list reordering never produces a plan change. */
105
+ const canonicalFunctionDomains = (bindings) => (bindings ?? [])
106
+ .map(exports.functionDomainDefinitionEntry)
107
+ .sort((a, b) => `${a.domain_name}\u0000${a.path}`.localeCompare(`${b.domain_name}\u0000${b.path}`));
108
+ exports.canonicalFunctionDomains = canonicalFunctionDomains;
109
+ /**
110
+ * Reads a function's recorded domain bindings from its state instances
111
+ * (identity = the domain name; one instance per domain per function holding
112
+ * that function's `paths`). Instances recorded before #286 carry no `paths`
113
+ * — they routed `/*`, which is the in-place migration default.
114
+ */
115
+ const storedFunctionDomainBindings = (instances, instanceType) => {
116
+ const stored = new Map();
117
+ (instances ?? []).forEach((instance) => {
118
+ if (instance.type !== instanceType)
119
+ return;
120
+ const domainName = (0, exports.normalizeFunctionDomainName)(String(instance.id ?? ''));
121
+ if (!domainName)
122
+ return;
123
+ const rawPaths = Array.isArray(instance.paths)
124
+ ? instance.paths.map(String).filter(Boolean)
125
+ : [];
126
+ const paths = rawPaths.length > 0 ? rawPaths : [exports.DEFAULT_FUNCTION_ROUTE_PATH];
127
+ stored.set(domainName, { domainName, paths });
128
+ });
129
+ return stored;
130
+ };
131
+ exports.storedFunctionDomainBindings = storedFunctionDomainBindings;
132
+ /**
133
+ * Groups a function's `domains` bindings by normalized domain name. A
134
+ * function may bind the same domain with several paths (the cloud route list
135
+ * supports it); the representative binding supplies certificate/protocol,
136
+ * which semantic validation requires to be consistent anyway.
137
+ */
138
+ const aggregateFunctionDomainBindings = (bindings) => {
139
+ const aggregated = new Map();
140
+ (bindings ?? []).forEach((binding) => {
141
+ const domainName = (0, exports.normalizeFunctionDomainName)(binding.domain_name);
142
+ const existing = aggregated.get(domainName);
143
+ aggregated.set(domainName, existing
144
+ ? {
145
+ ...existing,
146
+ paths: existing.paths.includes(binding.path)
147
+ ? existing.paths
148
+ : [...existing.paths, binding.path],
149
+ }
150
+ : { domainName, paths: [binding.path], representative: binding });
151
+ });
152
+ return aggregated;
153
+ };
154
+ exports.aggregateFunctionDomainBindings = aggregateFunctionDomainBindings;
155
+ /**
156
+ * The certificate hash recorded in this function's saved definition for a
157
+ * domain (issue #283 pattern): the canonicalized `domains` entry carries
158
+ * `certificate_hash`; pre-#286 state stored a legacy single-object `domain`
159
+ * whose `certificate_id` derives the same reference hash.
160
+ */
161
+ const storedFunctionDomainCertHash = (definition, domainName) => {
162
+ const target = (0, exports.normalizeFunctionDomainName)(domainName);
163
+ const domains = Array.isArray(definition?.domains)
164
+ ? definition?.domains
165
+ : [];
166
+ const entry = domains.find((candidate) => (0, exports.normalizeFunctionDomainName)(String(candidate.domain_name ?? '')) === target);
167
+ if (entry && typeof entry.certificate_hash === 'string' && entry.certificate_hash) {
168
+ return entry.certificate_hash;
169
+ }
170
+ const legacy = definition?.domain;
171
+ if (legacy &&
172
+ typeof legacy.domain_name === 'string' &&
173
+ (0, exports.normalizeFunctionDomainName)(legacy.domain_name) === target &&
174
+ typeof legacy.certificate_id === 'string' &&
175
+ legacy.certificate_id) {
176
+ return (0, certUtils_1.resolveBindingCertificateHash)({ certificate_id: legacy.certificate_id });
177
+ }
178
+ return undefined;
179
+ };
180
+ exports.storedFunctionDomainCertHash = storedFunctionDomainCertHash;
181
+ /** Normalizes a provider GET route payload into the shared route shape. */
182
+ const toFunctionDomainRoutes = (routeConfig) => (routeConfig?.routes ?? []).map((route) => ({
183
+ path: route.path ?? '',
184
+ functionName: route.functionName ?? '',
185
+ ...(route.qualifier ? { qualifier: route.qualifier } : {}),
186
+ }));
187
+ exports.toFunctionDomainRoutes = toFunctionDomainRoutes;
188
+ /** Whether any live route already points at one of this stack's functions — the ownership heuristic for state-less adoption after a partial failure. */
189
+ const routesReferenceStackFunctions = (live, stackFunctionNames) => live.some((route) => stackFunctionNames.has(route.functionName));
190
+ exports.routesReferenceStackFunctions = routesReferenceStackFunctions;
191
+ /** Every function name in the stack: the parsed config is the authoritative desired set. */
192
+ const collectStackFunctionNames = (iacFunctions, ownFunctionName) => {
193
+ const names = new Set([ownFunctionName]);
194
+ (iacFunctions ?? []).forEach((fn) => names.add(fn.name));
195
+ return names;
196
+ };
197
+ exports.collectStackFunctionNames = collectStackFunctionNames;