@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
@@ -2,7 +2,9 @@
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.createSaasStateBackend = void 0;
4
4
  const apiClient_1 = require("../apiClient");
5
+ const consoleLines_1 = require("../consoleLines");
5
6
  const credentialStore_1 = require("../credentialStore");
7
+ const lineContext_1 = require("../lineContext");
6
8
  const logger_1 = require("../logger");
7
9
  const stateManager_1 = require("../stateManager");
8
10
  const stateScope_1 = require("../stateScope");
@@ -10,29 +12,29 @@ const eventQueue_1 = require("../eventQueue");
10
12
  const lang_1 = require("../../lang");
11
13
  const saasProtocol_1 = require("../saasProtocol");
12
14
  const types_1 = require("../../types");
13
- const createSaasStateBackend = (context, options) => {
15
+ const createSaasStateBackend = async (context, options) => {
14
16
  const normalized = (0, stateScope_1.normalizeScope)(context.scope);
15
17
  const mode = options?.mode ?? 'mutating';
16
- const creds = options?.apiKey ? null : (0, credentialStore_1.loadCredentials)();
17
- const apiKey = options?.apiKey || creds?.apiKey;
18
- const consoleUrl = (0, credentialStore_1.getConsoleUrl)();
19
- let knownOrgId = creds?.orgId ?? '';
20
- if (!apiKey) {
21
- throw new Error(lang_1.lang.__('SAAS_BACKEND_NO_CREDENTIALS'));
22
- }
23
- // D-6 fast path: when both the yaml declaration and the stored slug are
24
- // known, fail before touching the network at all.
25
- if (context.declaredOrg && creds?.orgSlug && context.declaredOrg !== creds.orgSlug) {
26
- throw new Error(lang_1.lang.__('SAAS_ORG_MISMATCH', {
27
- declared: context.declaredOrg,
28
- actual: creds.orgSlug,
29
- }));
30
- }
31
- if (!context.declaredOrg && creds?.orgName) {
32
- logger_1.logger.info(lang_1.lang.__('SAAS_ORG_FROM_CREDENTIALS', { orgName: creds.orgName }));
18
+ // ADR-008: one resolution entry for line + key + org identity. Throws on
19
+ // ambiguous org slugs, line conflicts, and (non-interactive) unresolved
20
+ // lines before any network call.
21
+ const lineCtx = await (0, lineContext_1.resolveLineContext)({
22
+ siApiKey: options?.apiKey,
23
+ declaredOrg: context.declaredOrg,
24
+ orgFlag: options?.org,
25
+ lineFlag: options?.line,
26
+ operation: 'state access',
27
+ });
28
+ const consoleUrl = lineCtx.consoleUrl;
29
+ let knownOrgId = lineCtx.orgId ?? '';
30
+ const targetOrg = context.declaredOrg ?? options?.org;
31
+ const mustVerifyIdentity = !!targetOrg || (lineCtx.keySource !== 'profile' && !lineCtx.profileKey);
32
+ (0, consoleLines_1.assertOrgMatches)(targetOrg, lineCtx.orgSlug);
33
+ if (!targetOrg && lineCtx.orgName) {
34
+ logger_1.logger.info(lang_1.lang.__('SAAS_ORG_FROM_CREDENTIALS', { orgName: lineCtx.orgName }));
33
35
  }
34
36
  const client = (0, apiClient_1.createApiClient)({
35
- apiKey,
37
+ apiKey: lineCtx.apiKey,
36
38
  baseUrl: consoleUrl,
37
39
  orgId: knownOrgId,
38
40
  });
@@ -108,40 +110,39 @@ const createSaasStateBackend = (context, options) => {
108
110
  flushOnExit: true,
109
111
  });
110
112
  };
111
- /**
112
- * D-6: resolve the API key's org identity (id + slug). Credentials written
113
- * before the slug field existed lack it — fetch it from the validate endpoint
114
- * once, cache it for this backend instance and heal the stored file so later
115
- * commands check locally. Unresolvable (network / version skew) degrades to
116
- * skipping the checks: the key still only ever writes to its own org.
117
- */
113
+ // Cached identity belongs to the effective key. Resolve an override or an
114
+ // older login before it can select or provision a named organization.
118
115
  let resolvedIdentity = null;
119
116
  const resolveKeyOrgIdentity = async () => {
120
- if (resolvedIdentity) {
117
+ if (resolvedIdentity)
121
118
  return resolvedIdentity;
122
- }
123
- const local = {
124
- orgId: creds?.orgId || undefined,
125
- orgSlug: creds?.orgSlug,
126
- };
119
+ const local = { orgId: lineCtx.orgId, orgSlug: lineCtx.orgSlug };
127
120
  if (local.orgId && local.orgSlug) {
128
121
  resolvedIdentity = local;
129
122
  return local;
130
123
  }
124
+ let fetched;
131
125
  try {
132
- const fetched = await client.get('/api/v1/auth/api-keys/validate');
133
- if (fetched.orgSlug && creds) {
134
- (0, credentialStore_1.saveCredentials)({ ...creds, orgSlug: fetched.orgSlug });
135
- }
136
- resolvedIdentity = {
137
- orgId: local.orgId ?? fetched.orgId,
138
- orgSlug: local.orgSlug ?? fetched.orgSlug,
139
- };
140
- knownOrgId = resolvedIdentity.orgId ?? knownOrgId;
126
+ fetched = await client.get('/api/v1/auth/api-keys/validate');
141
127
  }
142
- catch {
128
+ catch (error) {
129
+ if (mustVerifyIdentity)
130
+ throw error;
143
131
  resolvedIdentity = local;
132
+ return local;
133
+ }
134
+ (0, consoleLines_1.assertValidatedRegion)(lineCtx.line, fetched?.region);
135
+ const orgSlug = fetched?.orgSlug ?? local.orgSlug;
136
+ (0, consoleLines_1.assertValidatedOrg)(targetOrg, orgSlug);
137
+ const orgId = fetched?.orgId ?? local.orgId;
138
+ if (fetched?.orgSlug && lineCtx.profileKey) {
139
+ (0, credentialStore_1.updateProfile)(lineCtx.profileKey, lineCtx.apiKey, {
140
+ orgSlug: fetched.orgSlug,
141
+ ...(fetched.orgId ? { orgId: fetched.orgId } : {}),
142
+ });
144
143
  }
144
+ resolvedIdentity = { orgId, orgSlug };
145
+ knownOrgId = orgId ?? knownOrgId;
145
146
  return resolvedIdentity;
146
147
  };
147
148
  const resolveReadOnlyIdentity = async () => {
@@ -155,17 +156,6 @@ const createSaasStateBackend = (context, options) => {
155
156
  return true;
156
157
  };
157
158
  const provision = async (provider, stage) => {
158
- // D-6: the org declaration must match the key's org BEFORE provisioning —
159
- // this POST is what auto-creates app/service, i.e. the wrong-org write.
160
- if (context.declaredOrg) {
161
- const { orgSlug } = await resolveKeyOrgIdentity();
162
- if (orgSlug && orgSlug !== context.declaredOrg) {
163
- throw new Error(lang_1.lang.__('SAAS_ORG_MISMATCH', {
164
- declared: context.declaredOrg,
165
- actual: orgSlug,
166
- }));
167
- }
168
- }
169
159
  const caps = await probeCapabilities();
170
160
  if (!caps.regionalScope) {
171
161
  throw new Error(lang_1.lang.__('SAAS_REGIONAL_SCOPE_UNSUPPORTED', { consoleUrl }));
@@ -198,6 +188,9 @@ const createSaasStateBackend = (context, options) => {
198
188
  if (provisioned) {
199
189
  return;
200
190
  }
191
+ if (mustVerifyIdentity) {
192
+ await resolveKeyOrgIdentity();
193
+ }
201
194
  if (mode === 'read-only') {
202
195
  const exists = await resolveReadOnlyIdentity();
203
196
  if (!exists) {
@@ -0,0 +1,100 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.createTosStateBackend = exports.createTosStorageAdapter = void 0;
4
+ const tos_sdk_1 = require("@volcengine/tos-sdk");
5
+ const remoteStateBackend_1 = require("./remoteStateBackend");
6
+ const constants_1 = require("../constants");
7
+ const lang_1 = require("../../lang");
8
+ const describeFailure = (err) => {
9
+ if (!err || typeof err !== 'object')
10
+ return {};
11
+ const { code, statusCode } = err;
12
+ return {
13
+ ...(typeof code === 'string' ? { code } : {}),
14
+ ...(typeof statusCode === 'number' ? { statusCode } : {}),
15
+ };
16
+ };
17
+ const isMissingBucket = ({ code }) => code === tos_sdk_1.TosServerCode.NoSuchBucket;
18
+ const isAccessDenied = ({ code, statusCode }) => code === tos_sdk_1.TosServerCode.AccessDenied || statusCode === 403;
19
+ /** Only a confirmed missing object is absent state. Other 404s stay errors. */
20
+ const isMissingObject = ({ code }) => code === tos_sdk_1.TosServerCode.NoSuchKey;
21
+ /** A bare 404 is still an idempotent deletion, but never an empty state read. */
22
+ const isMissingObjectDeletion = ({ code, statusCode }) => code === tos_sdk_1.TosServerCode.NoSuchKey || (code === undefined && statusCode === 404);
23
+ const assertNotFatalAbsence = (err) => {
24
+ const failure = describeFailure(err);
25
+ if (isMissingBucket(failure)) {
26
+ throw new Error(lang_1.lang.__('STATE_BUCKET_NOT_FOUND', { code: failure.code ?? tos_sdk_1.TosServerCode.NoSuchBucket }));
27
+ }
28
+ if (isAccessDenied(failure)) {
29
+ throw new Error(lang_1.lang.__('STATE_BUCKET_ACCESS_DENIED', {
30
+ code: failure.code ?? tos_sdk_1.TosServerCode.AccessDenied,
31
+ }));
32
+ }
33
+ };
34
+ const createTosStorageAdapter = (config) => {
35
+ const tosClient = new tos_sdk_1.TosClient({
36
+ accessKeyId: config.accessKeyId,
37
+ accessKeySecret: config.accessKeySecret,
38
+ stsToken: config.securityToken,
39
+ region: config.region,
40
+ endpoint: `tos-${config.region}.volces.com`,
41
+ secure: true,
42
+ requestTimeout: constants_1.TOS_STATE_REQUEST_TIMEOUT_MS,
43
+ connectionTimeout: constants_1.TOS_STATE_CONNECT_TIMEOUT_MS,
44
+ });
45
+ return {
46
+ read: async (key) => {
47
+ try {
48
+ const response = await tosClient.getObjectV2({
49
+ bucket: config.bucket,
50
+ key,
51
+ dataType: 'buffer',
52
+ });
53
+ return JSON.parse(response.data.content.toString('utf-8'));
54
+ }
55
+ catch (err) {
56
+ assertNotFatalAbsence(err);
57
+ if (isMissingObject(describeFailure(err)))
58
+ return null;
59
+ throw err;
60
+ }
61
+ },
62
+ write: async (key, data) => {
63
+ await tosClient.putObject({
64
+ bucket: config.bucket,
65
+ key,
66
+ body: Buffer.from(JSON.stringify(data, null, 2), 'utf-8'),
67
+ contentType: 'application/json',
68
+ });
69
+ },
70
+ delete: async (key) => {
71
+ try {
72
+ await tosClient.deleteObject({ bucket: config.bucket, key });
73
+ }
74
+ catch (err) {
75
+ assertNotFatalAbsence(err);
76
+ if (isMissingObjectDeletion(describeFailure(err)))
77
+ return;
78
+ throw err;
79
+ }
80
+ },
81
+ lockPath: config.lockPath,
82
+ };
83
+ };
84
+ exports.createTosStorageAdapter = createTosStorageAdapter;
85
+ const createTosStateBackend = (config) => {
86
+ const adapter = (0, exports.createTosStorageAdapter)({
87
+ bucket: config.bucket,
88
+ region: config.region,
89
+ accessKeyId: config.accessKeyId,
90
+ accessKeySecret: config.accessKeySecret,
91
+ securityToken: config.securityToken,
92
+ lockPath: `tos://${config.bucket}/${config.key}`,
93
+ });
94
+ return (0, remoteStateBackend_1.createRemoteStateBackend)(adapter, {
95
+ scope: config.scope,
96
+ key: config.key,
97
+ markerAction: config.markerAction,
98
+ });
99
+ };
100
+ exports.createTosStateBackend = createTosStateBackend;
@@ -0,0 +1,165 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
15
+ }) : function(o, v) {
16
+ o["default"] = v;
17
+ });
18
+ var __importStar = (this && this.__importStar) || (function () {
19
+ var ownKeys = function(o) {
20
+ ownKeys = Object.getOwnPropertyNames || function (o) {
21
+ var ar = [];
22
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
23
+ return ar;
24
+ };
25
+ return ownKeys(o);
26
+ };
27
+ return function (mod) {
28
+ if (mod && mod.__esModule) return mod;
29
+ var result = {};
30
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
31
+ __setModuleDefault(result, mod);
32
+ return result;
33
+ };
34
+ })();
35
+ Object.defineProperty(exports, "__esModule", { value: true });
36
+ exports.CdnClient = exports.createTencentCdnOperations = void 0;
37
+ const tencentcloud = __importStar(require("tencentcloud-sdk-nodejs-cdn"));
38
+ const lang_1 = require("../../lang");
39
+ const logger_1 = require("../logger");
40
+ const CdnClient = tencentcloud.cdn.v20180606.Client;
41
+ exports.CdnClient = CdnClient;
42
+ const toOrigin = (origin) => ({
43
+ OriginType: origin.originType,
44
+ Origins: origin.origins,
45
+ ...(origin.serverName ? { ServerName: origin.serverName } : {}),
46
+ ...(origin.cosPrivateAccess ? { CosPrivateAccess: origin.cosPrivateAccess } : {}),
47
+ ...(origin.originPullProtocol ? { OriginPullProtocol: origin.originPullProtocol } : {}),
48
+ });
49
+ const addCdnDomain = (cdnClient) => async (config) => {
50
+ await cdnClient.AddCdnDomain({
51
+ Domain: config.domainName,
52
+ ServiceType: config.serviceType,
53
+ Area: config.area,
54
+ Origin: toOrigin(config.origin),
55
+ });
56
+ };
57
+ const describeCdnDomain = (cdnClient) => async (domainName) => {
58
+ try {
59
+ const response = await cdnClient.DescribeDomains({
60
+ Filters: [{ Name: 'domain', Value: [domainName] }],
61
+ Limit: 1,
62
+ });
63
+ const info = response.Domains?.[0];
64
+ if (!info || !info.Domain)
65
+ return null;
66
+ return {
67
+ domainName: info.Domain,
68
+ cname: info.Cname,
69
+ status: info.Status,
70
+ serviceType: info.ServiceType,
71
+ origin: info.Origin
72
+ ? {
73
+ originType: info.Origin.OriginType,
74
+ origins: info.Origin.Origins ?? undefined,
75
+ serverName: info.Origin.ServerName,
76
+ }
77
+ : undefined,
78
+ };
79
+ }
80
+ catch {
81
+ return null;
82
+ }
83
+ };
84
+ const deleteCdnDomain = (cdnClient) => async (domainName) => {
85
+ try {
86
+ await cdnClient.DeleteCdnDomain({ Domain: domainName });
87
+ }
88
+ catch (error) {
89
+ const code = error?.code ?? '';
90
+ if (code.includes('NotFound') || code.includes('NotExist')) {
91
+ logger_1.logger.warn(lang_1.lang.__('RESOURCE_NOT_FOUND_PROVIDER', { resourceType: 'CDN domain', name: domainName }));
92
+ return;
93
+ }
94
+ throw error;
95
+ }
96
+ };
97
+ const updateCdnDelivery = (cdnClient) => async (domainName, update) => {
98
+ const request = { Domain: domainName };
99
+ if (update.serviceType != null)
100
+ request.ServiceType = update.serviceType;
101
+ if (update.area != null)
102
+ request.Area = update.area;
103
+ if (update.origin)
104
+ request.Origin = toOrigin(update.origin);
105
+ await cdnClient.UpdateDomainConfig(request);
106
+ };
107
+ const applyCacheConfig = (cdnClient) => async (domainName, cacheTtl, ignoreQueryString) => {
108
+ const request = { Domain: domainName };
109
+ // cache_ttl is expressed in seconds across si (issue #283); Tencent's
110
+ // SimpleCache CacheTime is seconds-based. `null` renders the provider
111
+ // default (FollowOrigin on, query string in the key) so a dropped si
112
+ // option converges the cloud instead of leaving the previous override
113
+ // behind — same contract on aliyun/volcengine.
114
+ request.Cache = {
115
+ SimpleCache: {
116
+ // CacheRules is required by the API shape; FollowOrigin on makes the
117
+ // empty rule list mean "no override, follow the origin headers".
118
+ CacheRules: cacheTtl != null
119
+ ? [{ CacheType: 'all', CacheContents: ['all'], CacheTime: cacheTtl }]
120
+ : [],
121
+ FollowOrigin: cacheTtl != null ? 'off' : 'on',
122
+ IgnoreCacheControl: 'off',
123
+ IgnoreSetCookie: 'off',
124
+ CompareMaxAge: 'off',
125
+ },
126
+ };
127
+ request.CacheKey = { FullUrlCache: ignoreQueryString ? 'off' : 'on' };
128
+ await cdnClient.UpdateDomainConfig(request);
129
+ };
130
+ const applyCompression = (cdnClient) => async (domainName, enabled) => {
131
+ if (enabled == null)
132
+ return;
133
+ await cdnClient.UpdateDomainConfig({
134
+ Domain: domainName,
135
+ Compression: { Switch: enabled ? 'on' : 'off' },
136
+ });
137
+ };
138
+ const applyHttpsRedirect = (cdnClient) => async (domainName, enabled) => {
139
+ if (enabled == null)
140
+ return;
141
+ await cdnClient.UpdateDomainConfig({
142
+ Domain: domainName,
143
+ ForceRedirect: {
144
+ Switch: enabled ? 'on' : 'off',
145
+ ...(enabled ? { RedirectType: 'https', RedirectStatusCode: 301 } : {}),
146
+ },
147
+ });
148
+ };
149
+ const enableHttps = (cdnClient) => async (domainName) => {
150
+ await cdnClient.UpdateDomainConfig({
151
+ Domain: domainName,
152
+ Https: { Switch: 'on', Http2: 'on' },
153
+ });
154
+ };
155
+ const createTencentCdnOperations = (cdnClient) => ({
156
+ addCdnDomain: addCdnDomain(cdnClient),
157
+ describeCdnDomain: describeCdnDomain(cdnClient),
158
+ deleteCdnDomain: deleteCdnDomain(cdnClient),
159
+ updateCdnDelivery: updateCdnDelivery(cdnClient),
160
+ applyCacheConfig: applyCacheConfig(cdnClient),
161
+ applyCompression: applyCompression(cdnClient),
162
+ applyHttpsRedirect: applyHttpsRedirect(cdnClient),
163
+ enableHttps: enableHttps(cdnClient),
164
+ });
165
+ exports.createTencentCdnOperations = createTencentCdnOperations;
@@ -129,21 +129,32 @@ const createCosOperations = (cosClient, region, dnsOps) => {
129
129
  logger_1.logger.warn(lang_1.lang.__('COS_CORS_RULE_REMOVE_FAILED', { domain, error: String(error) }));
130
130
  }
131
131
  };
132
- const bindCustomDomain = async (bucketName, domain) => {
132
+ const bindCustomDomain = async (bucketName, domain, options) => {
133
133
  const mainDomain = (0, domainUtils_1.extractMainDomain)(domain);
134
134
  const hostRecord = (0, domainUtils_1.extractHostRecord)(domain, mainDomain);
135
135
  const cosEndpoint = getCosEndpoint(bucketName);
136
136
  let bucketDomainBound = false;
137
137
  try {
138
+ const existingRules = await new Promise((resolve, reject) => {
139
+ cosClient.getBucketDomain({ Bucket: bucketName, Region: region }, (err, data) => {
140
+ if (err && err.statusCode !== 404)
141
+ reject(err);
142
+ else
143
+ resolve(data?.DomainRule ?? []);
144
+ });
145
+ });
146
+ const existingRule = existingRules.find((rule) => rule.Name.toLowerCase() === domain);
138
147
  await new Promise((resolve, reject) => {
139
148
  cosClient.putBucketDomain({
140
149
  Bucket: bucketName,
141
150
  Region: region,
142
151
  DomainRule: [
152
+ ...existingRules.filter((rule) => rule.Name.toLowerCase() !== domain),
143
153
  {
154
+ ...existingRule,
144
155
  Status: 'ENABLED',
145
156
  Name: domain,
146
- Type: 'REST',
157
+ Type: existingRule?.Type ?? 'REST',
147
158
  },
148
159
  ],
149
160
  }, (err) => {
@@ -162,6 +173,11 @@ const createCosOperations = (cosClient, region, dnsOps) => {
162
173
  logger_1.logger.warn(lang_1.lang.__('COS_BUCKET_DOMAIN_BIND_FAILED', { error: String(error) }));
163
174
  }
164
175
  await addCorsRuleForDomain(bucketName, domain);
176
+ if (options?.skipDns) {
177
+ // CDN delivery manages its own CNAME (pointing at the CDN domain); a
178
+ // bucket-side record would compete for the same RR name.
179
+ return { domain, cname: cosEndpoint, bucketDomainBound };
180
+ }
165
181
  if (!dnsOps) {
166
182
  logger_1.logger.warn(lang_1.lang.__('COS_DNS_MANUAL_CONFIG_REQUIRED', { domain, cname: cosEndpoint }));
167
183
  return { domain, cname: cosEndpoint, bucketDomainBound };
@@ -47,6 +47,17 @@ const addDomainRecord = (dnsClient) => async (config) => {
47
47
  });
48
48
  return String(response.RecordId);
49
49
  };
50
+ const updateDomainRecord = (dnsClient) => async (domainName, recordId, config) => {
51
+ await dnsClient.ModifyRecord({
52
+ Domain: domainName,
53
+ RecordId: parseInt(recordId, 10),
54
+ SubDomain: config.rr,
55
+ RecordType: config.type,
56
+ Value: config.value,
57
+ RecordLine: '默认',
58
+ TTL: config.ttl || 600,
59
+ });
60
+ };
50
61
  const deleteDomainRecord = (dnsClient) => async (domainName, recordId) => {
51
62
  await dnsClient.DeleteRecord({
52
63
  Domain: domainName,
@@ -83,6 +94,7 @@ const createDnsOperations = (dnsClient) => {
83
94
  return {
84
95
  addDomainRecord: addDomainRecord(dnsClient),
85
96
  deleteDomainRecord: deleteDomainRecord(dnsClient),
97
+ updateDomainRecord: updateDomainRecord(dnsClient),
86
98
  describeDomainRecords: describe,
87
99
  checkDomainRecordExists: checkDomainRecordExists(describe),
88
100
  };
@@ -47,6 +47,7 @@ const tencentEs = __importStar(require("tencentcloud-sdk-nodejs-es"));
47
47
  const tencentSsl = __importStar(require("tencentcloud-sdk-nodejs-ssl"));
48
48
  const tencentTag = __importStar(require("tencentcloud-sdk-nodejs-tag"));
49
49
  const tencentCls = __importStar(require("tencentcloud-sdk-nodejs-cls"));
50
+ const cdnOperations_1 = require("./cdnOperations");
50
51
  const cos_nodejs_sdk_v5_1 = __importDefault(require("cos-nodejs-sdk-v5"));
51
52
  const scfOperations_1 = require("./scfOperations");
52
53
  const cosOperations_1 = require("./cosOperations");
@@ -56,6 +57,7 @@ const esOperations_1 = require("./esOperations");
56
57
  const dnspodOperations_1 = require("./dnspodOperations");
57
58
  const sslOperations_1 = require("./sslOperations");
58
59
  const clsOperations_1 = require("./clsOperations");
60
+ const cdnOperations_2 = require("./cdnOperations");
59
61
  __exportStar(require("./types"), exports);
60
62
  var clsOperations_2 = require("./clsOperations");
61
63
  Object.defineProperty(exports, "createClsOperations", { enumerable: true, get: function () { return clsOperations_2.createClsOperations; } });
@@ -163,6 +165,18 @@ const initializeSdkClients = (context) => {
163
165
  },
164
166
  };
165
167
  const clsClient = new ClsClient(clsClientConfig);
168
+ const cdnClient = new cdnOperations_1.CdnClient({
169
+ credential: {
170
+ secretId: context.accessKeyId,
171
+ secretKey: context.accessKeySecret,
172
+ },
173
+ region: context.region,
174
+ profile: {
175
+ httpProfile: {
176
+ endpoint: 'cdn.tencentcloudapi.com',
177
+ },
178
+ },
179
+ });
166
180
  return {
167
181
  scf: scfClient,
168
182
  cos: cosClient,
@@ -173,6 +187,7 @@ const initializeSdkClients = (context) => {
173
187
  cam: camClient,
174
188
  tag: tagClient,
175
189
  cls: clsClient,
190
+ cdn: cdnClient,
176
191
  };
177
192
  };
178
193
  const createTencentClient = (context) => {
@@ -192,6 +207,7 @@ const createTencentClient = (context) => {
192
207
  ssl: (0, sslOperations_1.createSslOperations)(sdkClients.ssl),
193
208
  cls: (0, clsOperations_1.createClsOperations)(sdkClients.cls),
194
209
  dns: dnsOps,
210
+ cdn: (0, cdnOperations_2.createTencentCdnOperations)(sdkClients.cdn),
195
211
  };
196
212
  };
197
213
  exports.createTencentClient = createTencentClient;
@@ -237,6 +237,23 @@ const createScfOperations = (scfClient, deps) => {
237
237
  ...(params.CertConfig ? { CertConfig: params.CertConfig } : {}),
238
238
  });
239
239
  },
240
+ updateCustomDomain: async (params) => {
241
+ await scfClient.UpdateCustomDomain({
242
+ Domain: params.Domain,
243
+ ...(params.Protocol !== undefined ? { Protocol: params.Protocol } : {}),
244
+ ...(params.EndpointsConfig
245
+ ? {
246
+ EndpointsConfig: params.EndpointsConfig.map((ep) => ({
247
+ Namespace: ep.Namespace,
248
+ FunctionName: ep.FunctionName,
249
+ Qualifier: ep.Qualifier,
250
+ PathMatch: ep.PathMatch,
251
+ })),
252
+ }
253
+ : {}),
254
+ ...(params.CertConfig ? { CertConfig: params.CertConfig } : {}),
255
+ });
256
+ },
240
257
  getCustomDomain: async (domain) => {
241
258
  try {
242
259
  const response = await scfClient.GetCustomDomain({ Domain: domain });
@@ -245,7 +262,11 @@ const createScfOperations = (scfClient, deps) => {
245
262
  return {
246
263
  Domain: response.Domain,
247
264
  Protocol: response.Protocol,
265
+ ...(response.CertConfig?.CertificateId
266
+ ? { CertificateId: response.CertConfig.CertificateId }
267
+ : {}),
248
268
  EndpointsConfig: response.EndpointsConfig?.map((ep) => ({
269
+ Namespace: ep.Namespace,
249
270
  FunctionName: ep.FunctionName,
250
271
  Qualifier: ep.Qualifier,
251
272
  PathMatch: ep.PathMatch,
@@ -256,7 +277,8 @@ const createScfOperations = (scfClient, deps) => {
256
277
  if (error &&
257
278
  typeof error === 'object' &&
258
279
  'code' in error &&
259
- error.code === 'ResourceNotFound') {
280
+ (error.code === 'ResourceNotFound' ||
281
+ String(error.code ?? '').startsWith('ResourceNotFound'))) {
260
282
  return null;
261
283
  }
262
284
  throw error;