@cloudbase/cloudbase-mcp 2.11.0 → 2.12.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs CHANGED
@@ -106,6 +106,7 @@ const archiver_1 = __importDefault(__webpack_require__(99133));
106
106
  const fs_extra_1 = __webpack_require__(21605);
107
107
  const path_1 = __importDefault(__webpack_require__(39902));
108
108
  const utils_1 = __webpack_require__(62358);
109
+ const type_1 = __webpack_require__(59411);
109
110
  /**
110
111
  * 云托管服务管理类
111
112
  * 提供云托管服务的初始化、下载、列表查询和删除等功能
@@ -195,6 +196,97 @@ class CloudRunService {
195
196
  ServerType: params === null || params === void 0 ? void 0 : params.serverType
196
197
  }));
197
198
  }
199
+ /**
200
+ *
201
+ * @param serverName 云托管服务名
202
+ * @param stablePercent 稳定版本流量比例
203
+ * @param canaryPercent 灰度版本流量比例
204
+ * @returns 灰度发布进度
205
+ */
206
+ async setTraffic(serverName, stablePercent, canaryPercent) {
207
+ // 校验比例之和是否为100%
208
+ if (stablePercent + canaryPercent !== 100) {
209
+ throw new Error('稳定版本流量比例和灰度版本流量比例之和必须等于 100');
210
+ }
211
+ const envConfig = this.environment.lazyEnvironmentConfig;
212
+ const { Task } = await this.tcbrService.request('DescribeServerManageTask', {
213
+ EnvId: envConfig.EnvId,
214
+ ServerName: serverName, // 服务名
215
+ TaskId: 0 // 任务Id
216
+ });
217
+ // 判断是否存在灰度版本
218
+ const isGary = (Task === null || Task === void 0 ? void 0 : Task.ReleaseType) === type_1.ReleaseTypeEnum.GRAY && (Task === null || Task === void 0 ? void 0 : Task.Status) === 'running';
219
+ if (!isGary) {
220
+ throw new Error('不存在灰度中的版本或灰度版本部署未完成');
221
+ }
222
+ // 获取当前版本和灰度版本
223
+ const { ReleaseOrderInfo } = await this.tcbrService.request('DescribeReleaseOrder', {
224
+ EnvId: envConfig.EnvId, // 环境 Id
225
+ ServerName: serverName // 服务名
226
+ });
227
+ const { CurrentVersion, ReleaseVersion } = ReleaseOrderInfo;
228
+ // 设置版本比例
229
+ return await this.tcbrService.request('ReleaseGray', {
230
+ EnvId: envConfig.EnvId, // 环境 Id
231
+ ServerName: serverName, // 服务名
232
+ GrayType: "gray",
233
+ TrafficType: "FLOW",
234
+ GrayFlowRatio: canaryPercent,
235
+ VersionFlowItems: [{
236
+ VersionName: CurrentVersion.VersionName,
237
+ FlowRatio: stablePercent,
238
+ IsDefaultPriority: true,
239
+ Priority: 1,
240
+ }, {
241
+ VersionName: ReleaseVersion.VersionName,
242
+ FlowRatio: canaryPercent,
243
+ IsDefaultPriority: false,
244
+ Priority: 2,
245
+ }]
246
+ });
247
+ }
248
+ /**
249
+ *
250
+ * @param serverName 云托管服务名
251
+ * @returns 发布结果
252
+ */
253
+ async promote(serverName) {
254
+ const envConfig = this.environment.lazyEnvironmentConfig;
255
+ // 获取当前版本和灰度版本
256
+ const { ReleaseOrderInfo } = await this.tcbrService.request('DescribeReleaseOrder', {
257
+ EnvId: envConfig.EnvId, // 环境 Id
258
+ ServerName: serverName // 服务名
259
+ });
260
+ const { ReleaseVersion } = ReleaseOrderInfo;
261
+ return await this.tcbrService.request('ReleaseGray', {
262
+ EnvId: envConfig.EnvId, // 环境 Id
263
+ ServerName: serverName, // 服务名
264
+ GrayType: "gray",
265
+ TrafficType: "FLOW",
266
+ GrayFlowRatio: 100,
267
+ VersionFlowItems: [{ VersionName: ReleaseVersion.VersionName, FlowRatio: 100, Priority: 0, IsDefaultPriority: true }],
268
+ CloseGrayRelease: true,
269
+ });
270
+ }
271
+ /**
272
+ *
273
+ * @param serverName 云托管服务名
274
+ * @returns 回滚结果
275
+ */
276
+ async rollback(serverName) {
277
+ const envConfig = this.environment.lazyEnvironmentConfig;
278
+ const { Task } = await this.tcbrService.request('DescribeServerManageTask', {
279
+ EnvId: envConfig.EnvId,
280
+ ServerName: serverName, // 服务名
281
+ TaskId: 0 // 任务Id
282
+ });
283
+ return await this.tcbrService.request('OperateServerManage', {
284
+ EnvId: envConfig.EnvId, // 环境 Id
285
+ ServerName: serverName,
286
+ TaskId: Task.Id,
287
+ OperateType: 'go_back',
288
+ });
289
+ }
198
290
  /**
199
291
  *查询云托管服务详情
200
292
  * @param {Object} params 查询参数
@@ -203,10 +295,11 @@ class CloudRunService {
203
295
  */
204
296
  async detail(params) {
205
297
  const envConfig = this.environment.lazyEnvironmentConfig;
206
- return this.tcbrService.request('DescribeCloudRunServerDetail', {
298
+ const res = await this.tcbrService.request('DescribeCloudRunServerDetail', {
207
299
  EnvId: envConfig.EnvId,
208
300
  ServerName: params.serverName
209
301
  });
302
+ return res;
210
303
  }
211
304
  /**
212
305
  * 删除指定的云托管服务
@@ -246,6 +339,7 @@ class CloudRunService {
246
339
  * @returns {Promise<IResponseInfo>} 返回部署操作的响应信息
247
340
  */
248
341
  async deploy(params) {
342
+ var _a;
249
343
  const { serverName, targetPath = process.cwd(), serverConfig } = params;
250
344
  /**
251
345
  * 参数校验和默认值设置
@@ -294,7 +388,7 @@ class CloudRunService {
294
388
  RepoLanguage: 'Node.js'
295
389
  };
296
390
  }
297
- deployInfo.ReleaseType = 'FULL';
391
+ deployInfo.ReleaseType = ((_a = params.deployInfo) === null || _a === void 0 ? void 0 : _a.ReleaseType) || "FULL";
298
392
  return this._upsertFunction(false, {
299
393
  name: serverName,
300
394
  deployInfo,
@@ -351,6 +445,7 @@ class CloudRunService {
351
445
  }
352
446
  catch (e) {
353
447
  if (e.code === 'ResourceNotFound' ||
448
+ e.code === 'ResourceNotFound.ServerNotFound' ||
354
449
  // 备注:以下条件当 NotFound 处理(已与 fisheryan 确认过)
355
450
  (e.code === 'InvalidParameter' && e.original.Message === 'service data illegal')) {
356
451
  return false;
@@ -369,6 +464,40 @@ class CloudRunService {
369
464
  Items,
370
465
  });
371
466
  }
467
+ /**
468
+ * 获取部署记录列表,按部署时间倒序(最新在前)
469
+ */
470
+ async getDeployRecords(params) {
471
+ const envConfig = this.environment.lazyEnvironmentConfig;
472
+ const res = await this.tcbrService.request('DescribeCloudRunDeployRecord', {
473
+ EnvId: envConfig.EnvId,
474
+ ServerName: params.serverName,
475
+ });
476
+ res.DeployRecords.sort((a, b) => new Date(b.DeployTime).getTime() - new Date(a.DeployTime).getTime());
477
+ return res;
478
+ }
479
+ async getBuildLog(params) {
480
+ const envConfig = this.environment.lazyEnvironmentConfig;
481
+ let buildId = params.buildId;
482
+ if (!buildId) {
483
+ const sortedRes = await this.getDeployRecords({ serverName: params.serverName });
484
+ buildId = sortedRes.DeployRecords[0].BuildId;
485
+ }
486
+ return this.tcbrService.request('DescribeCloudRunBuildLog', {
487
+ EnvId: envConfig.EnvId,
488
+ ServerName: params.serverName,
489
+ ServerVersion: '',
490
+ BuildId: buildId,
491
+ Offset: 0,
492
+ });
493
+ }
494
+ async getProcessLog(params) {
495
+ const envConfig = this.environment.lazyEnvironmentConfig;
496
+ return this.tcbrService.request('DescribeCloudRunProcessLog', {
497
+ EnvId: envConfig.EnvId,
498
+ RunId: params.RunId,
499
+ });
500
+ }
372
501
  }
373
502
  exports.CloudRunService = CloudRunService;
374
503
  __decorate([
@@ -380,6 +509,15 @@ __decorate([
380
509
  __decorate([
381
510
  (0, utils_1.preLazy)()
382
511
  ], CloudRunService.prototype, "list", null);
512
+ __decorate([
513
+ (0, utils_1.preLazy)()
514
+ ], CloudRunService.prototype, "setTraffic", null);
515
+ __decorate([
516
+ (0, utils_1.preLazy)()
517
+ ], CloudRunService.prototype, "promote", null);
518
+ __decorate([
519
+ (0, utils_1.preLazy)()
520
+ ], CloudRunService.prototype, "rollback", null);
383
521
  __decorate([
384
522
  (0, utils_1.preLazy)()
385
523
  ], CloudRunService.prototype, "detail", null);
@@ -389,6 +527,15 @@ __decorate([
389
527
  __decorate([
390
528
  (0, utils_1.preLazy)()
391
529
  ], CloudRunService.prototype, "deploy", null);
530
+ __decorate([
531
+ (0, utils_1.preLazy)()
532
+ ], CloudRunService.prototype, "getDeployRecords", null);
533
+ __decorate([
534
+ (0, utils_1.preLazy)()
535
+ ], CloudRunService.prototype, "getBuildLog", null);
536
+ __decorate([
537
+ (0, utils_1.preLazy)()
538
+ ], CloudRunService.prototype, "getProcessLog", null);
392
539
  async function codeToZip(cwd, options) {
393
540
  const archive = (0, archiver_1.default)('zip', {
394
541
  zlib: { level: 1 } // 保持与之前相同的压缩级别
@@ -27903,7 +28050,8 @@ const error_1 = __webpack_require__(40430);
27903
28050
  const os = __importStar(__webpack_require__(21820));
27904
28051
  // 10 MB
27905
28052
  exports.BIG_FILE_SIZE = 10485760;
27906
- exports.API_MAX_SIZE = 52428800;
28053
+ // ZipFile 上传最大 1.5MB
28054
+ exports.API_MAX_SIZE = 1.5 * 1024 * 1024;
27907
28055
  var CodeType;
27908
28056
  (function (CodeType) {
27909
28057
  CodeType[CodeType["File"] = 0] = "File";
@@ -27944,6 +28092,7 @@ class FunctionPacker {
27944
28092
  zipOption.pattern = this.incrementalPath;
27945
28093
  }
27946
28094
  await (0, utils_1.compressToZip)(zipOption);
28095
+ return this.zipFilePath;
27947
28096
  }
27948
28097
  // 获取 Java 代码
27949
28098
  getJavaFile() {
@@ -27991,7 +28140,7 @@ class FunctionPacker {
27991
28140
  const fileStats = await promiseStat(this.zipFilePath);
27992
28141
  return fileStats.size > exports.BIG_FILE_SIZE;
27993
28142
  }
27994
- // API 最大 50MB
28143
+ // ZipFile 上传最大 1.5MB
27995
28144
  async isReachMaxSize() {
27996
28145
  if (!this.zipFilePath) {
27997
28146
  await this.build();
@@ -89257,20 +89406,22 @@ exports.TRIGGER_CONFIG_EXAMPLES = exports.SUPPORTED_TRIGGER_TYPES = exports.DEFA
89257
89406
  exports.registerFunctionTools = registerFunctionTools;
89258
89407
  const zod_1 = __webpack_require__(21614);
89259
89408
  const cloudbase_manager_js_1 = __webpack_require__(3431);
89409
+ const logger_js_1 = __webpack_require__(13039);
89260
89410
  const path_1 = __importDefault(__webpack_require__(39902));
89261
89411
  // 支持的 Node.js 运行时列表
89262
89412
  exports.SUPPORTED_NODEJS_RUNTIMES = [
89263
- 'Nodejs18.15',
89264
- 'Nodejs16.13',
89265
- 'Nodejs14.18',
89266
- 'Nodejs12.16',
89267
- 'Nodejs10.15',
89268
- 'Nodejs8.9',
89413
+ "Nodejs20.19",
89414
+ "Nodejs18.15",
89415
+ "Nodejs16.13",
89416
+ "Nodejs14.18",
89417
+ "Nodejs12.16",
89418
+ "Nodejs10.15",
89419
+ "Nodejs8.9",
89269
89420
  ];
89270
- exports.DEFAULT_NODEJS_RUNTIME = 'Nodejs18.15';
89421
+ exports.DEFAULT_NODEJS_RUNTIME = "Nodejs18.15";
89271
89422
  // Supported trigger types
89272
89423
  exports.SUPPORTED_TRIGGER_TYPES = [
89273
- 'timer', // Timer trigger
89424
+ "timer", // Timer trigger
89274
89425
  ];
89275
89426
  // Trigger configuration examples
89276
89427
  exports.TRIGGER_CONFIG_EXAMPLES = {
@@ -89281,8 +89432,8 @@ exports.TRIGGER_CONFIG_EXAMPLES = {
89281
89432
  "0 30 9 * * * *", // Execute at 9:30 AM every day
89282
89433
  "0 0 12 * * * *", // Execute at 12:00 PM every day
89283
89434
  "0 0 0 1 1 * *", // Execute at midnight on January 1st every year
89284
- ]
89285
- }
89435
+ ],
89436
+ },
89286
89437
  };
89287
89438
  /**
89288
89439
  * 处理函数根目录路径,确保不包含函数名
@@ -89313,18 +89464,27 @@ function registerFunctionTools(server) {
89313
89464
  title: "查询云函数列表或详情",
89314
89465
  description: "获取云函数列表或单个函数详情。通过 action 参数区分操作类型:list=获取函数列表(默认,无需额外参数),detail=获取函数详情(需要提供 name 参数指定函数名称)",
89315
89466
  inputSchema: {
89316
- action: zod_1.z.enum(["list", "detail"]).optional().describe("操作类型:list=获取函数列表(默认,无需额外参数),detail=获取函数详情(需要提供 name 参数)"),
89467
+ action: zod_1.z
89468
+ .enum(["list", "detail"])
89469
+ .optional()
89470
+ .describe("操作类型:list=获取函数列表(默认,无需额外参数),detail=获取函数详情(需要提供 name 参数)"),
89317
89471
  limit: zod_1.z.number().optional().describe("范围(list 操作时使用)"),
89318
89472
  offset: zod_1.z.number().optional().describe("偏移(list 操作时使用)"),
89319
- name: zod_1.z.string().optional().describe("要查询的函数名称。当 action='detail' 时,此参数为必填项,必须提供已存在的函数名称。可通过 action='list' 操作获取可用的函数名称列表"),
89320
- codeSecret: zod_1.z.string().optional().describe("代码保护密钥(detail 操作时使用)")
89473
+ name: zod_1.z
89474
+ .string()
89475
+ .optional()
89476
+ .describe("要查询的函数名称。当 action='detail' 时,此参数为必填项,必须提供已存在的函数名称。可通过 action='list' 操作获取可用的函数名称列表"),
89477
+ codeSecret: zod_1.z
89478
+ .string()
89479
+ .optional()
89480
+ .describe("代码保护密钥(detail 操作时使用)"),
89321
89481
  },
89322
89482
  annotations: {
89323
89483
  readOnlyHint: true,
89324
89484
  openWorldHint: true,
89325
- category: "functions"
89326
- }
89327
- }, async ({ action = "list", limit, offset, name, codeSecret }) => {
89485
+ category: "functions",
89486
+ },
89487
+ }, async ({ action = "list", limit, offset, name, codeSecret, }) => {
89328
89488
  // 使用闭包中的 cloudBaseOptions
89329
89489
  const cloudbase = await getManager();
89330
89490
  if (action === "list") {
@@ -89334,9 +89494,9 @@ function registerFunctionTools(server) {
89334
89494
  content: [
89335
89495
  {
89336
89496
  type: "text",
89337
- text: JSON.stringify(result, null, 2)
89338
- }
89339
- ]
89497
+ text: JSON.stringify(result, null, 2),
89498
+ },
89499
+ ],
89340
89500
  };
89341
89501
  }
89342
89502
  else if (action === "detail") {
@@ -89349,9 +89509,9 @@ function registerFunctionTools(server) {
89349
89509
  content: [
89350
89510
  {
89351
89511
  type: "text",
89352
- text: JSON.stringify(result, null, 2)
89353
- }
89354
- ]
89512
+ text: JSON.stringify(result, null, 2),
89513
+ },
89514
+ ],
89355
89515
  };
89356
89516
  }
89357
89517
  else {
@@ -89361,59 +89521,115 @@ function registerFunctionTools(server) {
89361
89521
  // createFunction - 创建云函数 (cloud-incompatible)
89362
89522
  server.registerTool("createFunction", {
89363
89523
  title: "创建云函数",
89364
- description: "创建云函数",
89524
+ description: "创建云函数。云函数分为事件型云函数和 HTTP 云函数,请确认你要创建的函数类型。",
89365
89525
  inputSchema: {
89366
- func: zod_1.z.object({
89526
+ func: zod_1.z
89527
+ .object({
89367
89528
  name: zod_1.z.string().describe("函数名称"),
89529
+ type: zod_1.z
89530
+ .enum(["Event", "HTTP"])
89531
+ .optional()
89532
+ .describe("函数类型,Event 为事件型云函数,HTTP 为 HTTP 云函数"),
89533
+ protocolType: zod_1.z
89534
+ .enum(["HTTP", "WS"])
89535
+ .optional()
89536
+ .describe("HTTP 云函数的协议类型,HTTP 为 HTTP 协议(默认),WS 为 WebSocket 协议,仅当 type 为 HTTP 时有效"),
89537
+ protocolParams: zod_1.z
89538
+ .object({
89539
+ wsParams: zod_1.z
89540
+ .object({
89541
+ idleTimeOut: zod_1.z.number().optional().describe("WebSocket 空闲超时时间(秒),默认 15 秒"),
89542
+ })
89543
+ .optional()
89544
+ .describe("WebSocket 协议参数"),
89545
+ })
89546
+ .optional()
89547
+ .describe("协议参数配置,仅当 protocolType 为 WS 时有效"),
89548
+ instanceConcurrencyConfig: zod_1.z
89549
+ .object({
89550
+ dynamicEnabled: zod_1.z.boolean().optional().describe("是否启用动态并发,默认 false"),
89551
+ maxConcurrency: zod_1.z.number().optional().describe("最大并发数,默认 10"),
89552
+ })
89553
+ .optional()
89554
+ .describe("多并发配置,仅当 type 为 HTTP 时有效"),
89368
89555
  timeout: zod_1.z.number().optional().describe("函数超时时间"),
89369
89556
  envVariables: zod_1.z.record(zod_1.z.string()).optional().describe("环境变量"),
89370
- vpc: zod_1.z.object({
89557
+ vpc: zod_1.z
89558
+ .object({
89371
89559
  vpcId: zod_1.z.string(),
89372
- subnetId: zod_1.z.string()
89373
- }).optional().describe("私有网络配置"),
89374
- runtime: zod_1.z.string().optional().describe("运行时环境,建议指定为 'Nodejs18.15',其他可选值:" + exports.SUPPORTED_NODEJS_RUNTIMES.join(',')),
89375
- triggers: zod_1.z.array(zod_1.z.object({
89560
+ subnetId: zod_1.z.string(),
89561
+ })
89562
+ .optional()
89563
+ .describe("私有网络配置"),
89564
+ runtime: zod_1.z
89565
+ .string()
89566
+ .optional()
89567
+ .describe("运行时环境,建议指定为 'Nodejs18.15',其他可选值:" +
89568
+ exports.SUPPORTED_NODEJS_RUNTIMES.join(",")),
89569
+ triggers: zod_1.z
89570
+ .array(zod_1.z.object({
89376
89571
  name: zod_1.z.string().describe("Trigger name"),
89377
- type: zod_1.z.enum(exports.SUPPORTED_TRIGGER_TYPES).describe("Trigger type, currently only supports 'timer'"),
89378
- config: zod_1.z.string().describe("Trigger configuration. For timer triggers, use cron expression format: second minute hour day month week year. IMPORTANT: Must include exactly 7 fields (second minute hour day month week year). Examples: '0 0 2 1 * * *' (monthly), '0 30 9 * * * *' (daily at 9:30 AM)")
89379
- })).optional().describe("Trigger configuration array"),
89572
+ type: zod_1.z
89573
+ .enum(exports.SUPPORTED_TRIGGER_TYPES)
89574
+ .describe("Trigger type, currently only supports 'timer'"),
89575
+ config: zod_1.z
89576
+ .string()
89577
+ .describe("Trigger configuration. For timer triggers, use cron expression format: second minute hour day month week year. IMPORTANT: Must include exactly 7 fields (second minute hour day month week year). Examples: '0 0 2 1 * * *' (monthly), '0 30 9 * * * *' (daily at 9:30 AM)"),
89578
+ }))
89579
+ .optional()
89580
+ .describe("Trigger configuration array"),
89380
89581
  handler: zod_1.z.string().optional().describe("函数入口"),
89381
- ignore: zod_1.z.union([zod_1.z.string(), zod_1.z.array(zod_1.z.string())]).optional().describe("忽略文件"),
89582
+ ignore: zod_1.z
89583
+ .union([zod_1.z.string(), zod_1.z.array(zod_1.z.string())])
89584
+ .optional()
89585
+ .describe("忽略文件"),
89382
89586
  isWaitInstall: zod_1.z.boolean().optional().describe("是否等待依赖安装"),
89383
- layers: zod_1.z.array(zod_1.z.object({
89587
+ layers: zod_1.z
89588
+ .array(zod_1.z.object({
89384
89589
  name: zod_1.z.string(),
89385
- version: zod_1.z.number()
89386
- })).optional().describe("Layer配置")
89387
- }).describe("函数配置"),
89388
- functionRootPath: zod_1.z.string().optional().describe("函数根目录(云函数目录的父目录),这里需要传操作系统上文件的绝对路径,注意:不要包含函数名本身,例如函数名为 'hello',应传入 '/path/to/cloudfunctions',而不是 '/path/to/cloudfunctions/hello'"),
89389
- force: zod_1.z.boolean().describe("是否覆盖")
89590
+ version: zod_1.z.number(),
89591
+ }))
89592
+ .optional()
89593
+ .describe("Layer配置"),
89594
+ })
89595
+ .describe("函数配置"),
89596
+ functionRootPath: zod_1.z
89597
+ .string()
89598
+ .optional()
89599
+ .describe("函数根目录(云函数目录的父目录),这里需要传操作系统上文件的绝对路径,注意:不要包含函数名本身,例如函数名为 'hello',应传入 '/path/to/cloudfunctions',而不是 '/path/to/cloudfunctions/hello'"),
89600
+ force: zod_1.z.boolean().describe("是否覆盖"),
89390
89601
  },
89391
89602
  annotations: {
89392
89603
  readOnlyHint: false,
89393
89604
  destructiveHint: false,
89394
89605
  idempotentHint: false,
89395
89606
  openWorldHint: true,
89396
- category: "functions"
89397
- }
89398
- }, async ({ func, functionRootPath, force }) => {
89399
- // 自动填充默认 runtime
89400
- if (!func.runtime) {
89401
- func.runtime = exports.DEFAULT_NODEJS_RUNTIME;
89402
- }
89403
- else {
89404
- // 验证 runtime 格式,防止常见的空格问题
89405
- const normalizedRuntime = func.runtime.replace(/\s+/g, '');
89406
- if (exports.SUPPORTED_NODEJS_RUNTIMES.includes(normalizedRuntime)) {
89407
- func.runtime = normalizedRuntime;
89607
+ category: "functions",
89608
+ },
89609
+ }, async ({ func, functionRootPath, force, }) => {
89610
+ (0, logger_js_1.debug)(`[createFunction] name=${func.name}, type=${func.type || "Event"}`);
89611
+ // HTTP 云函数跳过 runtime 验证,Event 云函数进行验证
89612
+ const isHttpFunction = func.type === "HTTP";
89613
+ if (!isHttpFunction) {
89614
+ // 自动填充默认 runtime
89615
+ if (!func.runtime) {
89616
+ func.runtime = exports.DEFAULT_NODEJS_RUNTIME;
89408
89617
  }
89409
- else if (func.runtime.includes(' ')) {
89410
- console.warn(`检测到 runtime 参数包含空格: "${func.runtime}",已自动移除空格`);
89411
- func.runtime = normalizedRuntime;
89618
+ else {
89619
+ // 验证 runtime 格式,防止常见的空格问题
89620
+ const normalizedRuntime = func.runtime.replace(/\s+/g, "");
89621
+ if (exports.SUPPORTED_NODEJS_RUNTIMES.includes(normalizedRuntime)) {
89622
+ func.runtime = normalizedRuntime;
89623
+ }
89624
+ else if (func.runtime.includes(" ")) {
89625
+ console.warn(`检测到 runtime 参数包含空格: "${func.runtime}",已自动移除空格`);
89626
+ func.runtime = normalizedRuntime;
89627
+ }
89628
+ }
89629
+ // 验证 runtime 是否有效
89630
+ if (!exports.SUPPORTED_NODEJS_RUNTIMES.includes(func.runtime)) {
89631
+ throw new Error(`不支持的运行时环境: "${func.runtime}"。支持的值:${exports.SUPPORTED_NODEJS_RUNTIMES.join(", ")}`);
89412
89632
  }
89413
- }
89414
- // 验证 runtime 是否有效
89415
- if (!exports.SUPPORTED_NODEJS_RUNTIMES.includes(func.runtime)) {
89416
- throw new Error(`不支持的运行时环境: "${func.runtime}"。支持的值:${exports.SUPPORTED_NODEJS_RUNTIMES.join(', ')}`);
89417
89633
  }
89418
89634
  // 强制设置 installDependency 为 true(不暴露给AI)
89419
89635
  func.installDependency = true;
@@ -89424,16 +89640,16 @@ function registerFunctionTools(server) {
89424
89640
  const result = await cloudbase.functions.createFunction({
89425
89641
  func,
89426
89642
  functionRootPath: processedRootPath,
89427
- force
89643
+ force,
89428
89644
  });
89429
89645
  (0, cloudbase_manager_js_1.logCloudBaseResult)(server.logger, result);
89430
89646
  return {
89431
89647
  content: [
89432
89648
  {
89433
89649
  type: "text",
89434
- text: JSON.stringify(result, null, 2)
89435
- }
89436
- ]
89650
+ text: JSON.stringify(result, null, 2),
89651
+ },
89652
+ ],
89437
89653
  };
89438
89654
  });
89439
89655
  // updateFunctionCode - 更新函数代码 (cloud-incompatible)
@@ -89442,7 +89658,9 @@ function registerFunctionTools(server) {
89442
89658
  description: "更新已存在函数的代码。注意:此工具仅用于更新代码,不支持修改函数配置(如 runtime)。如果需要修改 runtime,需要删除函数后使用 createFunction 重新创建。",
89443
89659
  inputSchema: {
89444
89660
  name: zod_1.z.string().describe("函数名称"),
89445
- functionRootPath: zod_1.z.string().describe("函数根目录(云函数目录的父目录),这里需要传操作系统上文件的绝对路径"),
89661
+ functionRootPath: zod_1.z
89662
+ .string()
89663
+ .describe("函数根目录(云函数目录的父目录),这里需要传操作系统上文件的绝对路径"),
89446
89664
  // zipFile: z.string().optional().describe("Base64编码的函数包"),
89447
89665
  // handler: z.string().optional().describe("函数入口"),
89448
89666
  // runtime: z.string().optional().describe("运行时(可选值:" + SUPPORTED_NODEJS_RUNTIMES.join(',') + ",默认 Nodejs 18.15)")
@@ -89452,9 +89670,9 @@ function registerFunctionTools(server) {
89452
89670
  destructiveHint: false,
89453
89671
  idempotentHint: false,
89454
89672
  openWorldHint: true,
89455
- category: "functions"
89456
- }
89457
- }, async ({ name, functionRootPath, zipFile, handler }) => {
89673
+ category: "functions",
89674
+ },
89675
+ }, async ({ name, functionRootPath, zipFile, handler, }) => {
89458
89676
  // 处理函数根目录路径,确保不包含函数名
89459
89677
  const processedRootPath = processFunctionRootPath(functionRootPath, name);
89460
89678
  // 构建更新参数,强制设置 installDependency 为 true(不暴露给AI)
@@ -89463,9 +89681,9 @@ function registerFunctionTools(server) {
89463
89681
  func: {
89464
89682
  name,
89465
89683
  installDependency: true,
89466
- ...(handler && { handler })
89684
+ ...(handler && { handler }),
89467
89685
  },
89468
- functionRootPath: processedRootPath
89686
+ functionRootPath: processedRootPath,
89469
89687
  };
89470
89688
  // 如果提供了zipFile,则添加到参数中
89471
89689
  if (zipFile) {
@@ -89479,9 +89697,9 @@ function registerFunctionTools(server) {
89479
89697
  content: [
89480
89698
  {
89481
89699
  type: "text",
89482
- text: JSON.stringify(result, null, 2)
89483
- }
89484
- ]
89700
+ text: JSON.stringify(result, null, 2),
89701
+ },
89702
+ ],
89485
89703
  };
89486
89704
  });
89487
89705
  // updateFunctionConfig - 更新函数配置
@@ -89489,24 +89707,29 @@ function registerFunctionTools(server) {
89489
89707
  title: "更新云函数配置",
89490
89708
  description: "更新云函数配置",
89491
89709
  inputSchema: {
89492
- funcParam: zod_1.z.object({
89710
+ funcParam: zod_1.z
89711
+ .object({
89493
89712
  name: zod_1.z.string().describe("函数名称"),
89494
89713
  timeout: zod_1.z.number().optional().describe("超时时间"),
89495
89714
  envVariables: zod_1.z.record(zod_1.z.string()).optional().describe("环境变量"),
89496
- vpc: zod_1.z.object({
89715
+ vpc: zod_1.z
89716
+ .object({
89497
89717
  vpcId: zod_1.z.string(),
89498
- subnetId: zod_1.z.string()
89499
- }).optional().describe("VPC配置"),
89718
+ subnetId: zod_1.z.string(),
89719
+ })
89720
+ .optional()
89721
+ .describe("VPC配置"),
89500
89722
  // runtime: z.string().optional().describe("运行时(可选值:" + SUPPORTED_NODEJS_RUNTIMES.join(',') + ",默认 Nodejs 18.15)")
89501
- }).describe("函数配置")
89723
+ })
89724
+ .describe("函数配置"),
89502
89725
  },
89503
89726
  annotations: {
89504
89727
  readOnlyHint: false,
89505
89728
  destructiveHint: false,
89506
89729
  idempotentHint: false,
89507
89730
  openWorldHint: true,
89508
- category: "functions"
89509
- }
89731
+ category: "functions",
89732
+ },
89510
89733
  }, async ({ funcParam }) => {
89511
89734
  // 自动填充默认 runtime
89512
89735
  // if (!funcParam.runtime) {
@@ -89516,10 +89739,15 @@ function registerFunctionTools(server) {
89516
89739
  const cloudbase = await getManager();
89517
89740
  const functionDetail = await cloudbase.functions.getFunctionDetail(funcParam.name);
89518
89741
  functionDetail.Environment;
89519
- const vpc = (typeof functionDetail.VpcConfig === 'object' && functionDetail.VpcConfig !== null && functionDetail.VpcConfig.SubnetId && functionDetail.VpcConfig.VpcId) ? {
89520
- subnetId: functionDetail.VpcConfig.SubnetId,
89521
- vpcId: functionDetail.VpcConfig.VpcId
89522
- } : undefined;
89742
+ const vpc = typeof functionDetail.VpcConfig === "object" &&
89743
+ functionDetail.VpcConfig !== null &&
89744
+ functionDetail.VpcConfig.SubnetId &&
89745
+ functionDetail.VpcConfig.VpcId
89746
+ ? {
89747
+ subnetId: functionDetail.VpcConfig.SubnetId,
89748
+ vpcId: functionDetail.VpcConfig.VpcId,
89749
+ }
89750
+ : undefined;
89523
89751
  const result = await cloudbase.functions.updateFunctionConfig({
89524
89752
  name: funcParam.name,
89525
89753
  envVariables: Object.assign({}, functionDetail.Environment.Variables.reduce((acc, curr) => {
@@ -89534,9 +89762,9 @@ function registerFunctionTools(server) {
89534
89762
  content: [
89535
89763
  {
89536
89764
  type: "text",
89537
- text: JSON.stringify(result, null, 2)
89538
- }
89539
- ]
89765
+ text: JSON.stringify(result, null, 2),
89766
+ },
89767
+ ],
89540
89768
  };
89541
89769
  });
89542
89770
  // invokeFunction - 调用函数
@@ -89545,16 +89773,16 @@ function registerFunctionTools(server) {
89545
89773
  description: "调用云函数",
89546
89774
  inputSchema: {
89547
89775
  name: zod_1.z.string().describe("函数名称"),
89548
- params: zod_1.z.record(zod_1.z.any()).optional().describe("调用参数")
89776
+ params: zod_1.z.record(zod_1.z.any()).optional().describe("调用参数"),
89549
89777
  },
89550
89778
  annotations: {
89551
89779
  readOnlyHint: false,
89552
89780
  destructiveHint: false,
89553
89781
  idempotentHint: false,
89554
89782
  openWorldHint: true,
89555
- category: "functions"
89556
- }
89557
- }, async ({ name, params }) => {
89783
+ category: "functions",
89784
+ },
89785
+ }, async ({ name, params, }) => {
89558
89786
  // 使用闭包中的 cloudBaseOptions
89559
89787
  try {
89560
89788
  const cloudbase = await getManager();
@@ -89564,13 +89792,13 @@ function registerFunctionTools(server) {
89564
89792
  content: [
89565
89793
  {
89566
89794
  type: "text",
89567
- text: JSON.stringify(result, null, 2)
89568
- }
89569
- ]
89795
+ text: JSON.stringify(result, null, 2),
89796
+ },
89797
+ ],
89570
89798
  };
89571
89799
  }
89572
89800
  catch (error) {
89573
- const errorMessage = (error instanceof Error ? error.message : String(error));
89801
+ const errorMessage = error instanceof Error ? error.message : String(error);
89574
89802
  if (errorMessage.includes("Function not found") ||
89575
89803
  errorMessage.includes("函数不存在")) {
89576
89804
  throw new Error(`${errorMessage}\n\n` +
@@ -89587,19 +89815,31 @@ function registerFunctionTools(server) {
89587
89815
  description: "获取云函数日志基础信息(LogList),如需日志详情请用 RequestId 调用 getFunctionLogDetail 工具。此接口基于 manger-node 4.4.0+ 的 getFunctionLogsV2 实现,不返回具体日志内容。参数 offset+limit 不得大于 10000,startTime/endTime 间隔不得超过一天。",
89588
89816
  inputSchema: {
89589
89817
  name: zod_1.z.string().describe("函数名称"),
89590
- offset: zod_1.z.number().optional().describe("数据的偏移量,Offset+Limit 不能大于 10000"),
89591
- limit: zod_1.z.number().optional().describe("返回数据的长度,Offset+Limit 不能大于 10000"),
89592
- startTime: zod_1.z.string().optional().describe("查询的具体日期,例如:2017-05-16 20:00:00,只能与 EndTime 相差一天之内"),
89593
- endTime: zod_1.z.string().optional().describe("查询的具体日期,例如:2017-05-16 20:59:59,只能与 StartTime 相差一天之内"),
89818
+ offset: zod_1.z
89819
+ .number()
89820
+ .optional()
89821
+ .describe("数据的偏移量,Offset+Limit 不能大于 10000"),
89822
+ limit: zod_1.z
89823
+ .number()
89824
+ .optional()
89825
+ .describe("返回数据的长度,Offset+Limit 不能大于 10000"),
89826
+ startTime: zod_1.z
89827
+ .string()
89828
+ .optional()
89829
+ .describe("查询的具体日期,例如:2017-05-16 20:00:00,只能与 EndTime 相差一天之内"),
89830
+ endTime: zod_1.z
89831
+ .string()
89832
+ .optional()
89833
+ .describe("查询的具体日期,例如:2017-05-16 20:59:59,只能与 StartTime 相差一天之内"),
89594
89834
  requestId: zod_1.z.string().optional().describe("执行该函数对应的 requestId"),
89595
- qualifier: zod_1.z.string().optional().describe("函数版本,默认为 $LATEST")
89835
+ qualifier: zod_1.z.string().optional().describe("函数版本,默认为 $LATEST"),
89596
89836
  },
89597
89837
  annotations: {
89598
89838
  readOnlyHint: true,
89599
89839
  openWorldHint: true,
89600
- category: "functions"
89601
- }
89602
- }, async ({ name, offset, limit, startTime, endTime, requestId, qualifier }) => {
89840
+ category: "functions",
89841
+ },
89842
+ }, async ({ name, offset, limit, startTime, endTime, requestId, qualifier, }) => {
89603
89843
  if ((offset || 0) + (limit || 0) > 10000) {
89604
89844
  throw new Error("offset+limit 不能大于 10000");
89605
89845
  }
@@ -89611,15 +89851,23 @@ function registerFunctionTools(server) {
89611
89851
  }
89612
89852
  }
89613
89853
  const cloudbase = await getManager();
89614
- const result = await cloudbase.functions.getFunctionLogsV2({ name, offset, limit, startTime, endTime, requestId, qualifier });
89854
+ const result = await cloudbase.functions.getFunctionLogsV2({
89855
+ name,
89856
+ offset,
89857
+ limit,
89858
+ startTime,
89859
+ endTime,
89860
+ requestId,
89861
+ qualifier,
89862
+ });
89615
89863
  (0, cloudbase_manager_js_1.logCloudBaseResult)(server.logger, result);
89616
89864
  return {
89617
89865
  content: [
89618
89866
  {
89619
89867
  type: "text",
89620
- text: JSON.stringify(result, null, 2)
89621
- }
89622
- ]
89868
+ text: JSON.stringify(result, null, 2),
89869
+ },
89870
+ ],
89623
89871
  };
89624
89872
  });
89625
89873
  // getFunctionLogDetail - 查询日志详情(参数直接展开)
@@ -89627,15 +89875,21 @@ function registerFunctionTools(server) {
89627
89875
  title: "获取云函数日志详情",
89628
89876
  description: "根据 getFunctionLogs 返回的 RequestId 查询日志详情。参数 startTime、endTime、requestId,返回日志内容(LogJson 等)。仅支持 manger-node 4.4.0+。",
89629
89877
  inputSchema: {
89630
- startTime: zod_1.z.string().optional().describe("查询的具体日期,例如:2017-05-16 20:00:00,只能与 EndTime 相差一天之内"),
89631
- endTime: zod_1.z.string().optional().describe("查询的具体日期,例如:2017-05-16 20:59:59,只能与 StartTime 相差一天之内"),
89632
- requestId: zod_1.z.string().describe("执行该函数对应的 requestId")
89878
+ startTime: zod_1.z
89879
+ .string()
89880
+ .optional()
89881
+ .describe("查询的具体日期,例如:2017-05-16 20:00:00,只能与 EndTime 相差一天之内"),
89882
+ endTime: zod_1.z
89883
+ .string()
89884
+ .optional()
89885
+ .describe("查询的具体日期,例如:2017-05-16 20:59:59,只能与 StartTime 相差一天之内"),
89886
+ requestId: zod_1.z.string().describe("执行该函数对应的 requestId"),
89633
89887
  },
89634
89888
  annotations: {
89635
89889
  readOnlyHint: true,
89636
89890
  openWorldHint: true,
89637
- category: "functions"
89638
- }
89891
+ category: "functions",
89892
+ },
89639
89893
  }, async ({ startTime, endTime, requestId }) => {
89640
89894
  if (startTime && endTime) {
89641
89895
  const start = new Date(startTime).getTime();
@@ -89648,16 +89902,16 @@ function registerFunctionTools(server) {
89648
89902
  const result = await cloudbase.functions.getFunctionLogDetail({
89649
89903
  startTime,
89650
89904
  endTime,
89651
- logRequestId: requestId
89905
+ logRequestId: requestId,
89652
89906
  });
89653
89907
  (0, cloudbase_manager_js_1.logCloudBaseResult)(server.logger, result);
89654
89908
  return {
89655
89909
  content: [
89656
89910
  {
89657
89911
  type: "text",
89658
- text: JSON.stringify(result, null, 2)
89659
- }
89660
- ]
89912
+ text: JSON.stringify(result, null, 2),
89913
+ },
89914
+ ],
89661
89915
  };
89662
89916
  });
89663
89917
  // manageFunctionTriggers - 管理云函数触发器(创建/删除)
@@ -89665,23 +89919,32 @@ function registerFunctionTools(server) {
89665
89919
  title: "管理云函数触发器",
89666
89920
  description: "创建或删除云函数触发器,通过 action 参数区分操作类型",
89667
89921
  inputSchema: {
89668
- action: zod_1.z.enum(["create", "delete"]).describe("操作类型:create=创建触发器,delete=删除触发器"),
89922
+ action: zod_1.z
89923
+ .enum(["create", "delete"])
89924
+ .describe("操作类型:create=创建触发器,delete=删除触发器"),
89669
89925
  name: zod_1.z.string().describe("函数名"),
89670
- triggers: zod_1.z.array(zod_1.z.object({
89926
+ triggers: zod_1.z
89927
+ .array(zod_1.z.object({
89671
89928
  name: zod_1.z.string().describe("Trigger name"),
89672
- type: zod_1.z.enum(exports.SUPPORTED_TRIGGER_TYPES).describe("Trigger type, currently only supports 'timer'"),
89673
- config: zod_1.z.string().describe("Trigger configuration. For timer triggers, use cron expression format: second minute hour day month week year. IMPORTANT: Must include exactly 7 fields (second minute hour day month week year). Examples: '0 0 2 1 * * *' (monthly), '0 30 9 * * * *' (daily at 9:30 AM)")
89674
- })).optional().describe("触发器配置数组(创建时必需)"),
89675
- triggerName: zod_1.z.string().optional().describe("触发器名称(删除时必需)")
89929
+ type: zod_1.z
89930
+ .enum(exports.SUPPORTED_TRIGGER_TYPES)
89931
+ .describe("Trigger type, currently only supports 'timer'"),
89932
+ config: zod_1.z
89933
+ .string()
89934
+ .describe("Trigger configuration. For timer triggers, use cron expression format: second minute hour day month week year. IMPORTANT: Must include exactly 7 fields (second minute hour day month week year). Examples: '0 0 2 1 * * *' (monthly), '0 30 9 * * * *' (daily at 9:30 AM)"),
89935
+ }))
89936
+ .optional()
89937
+ .describe("触发器配置数组(创建时必需)"),
89938
+ triggerName: zod_1.z.string().optional().describe("触发器名称(删除时必需)"),
89676
89939
  },
89677
89940
  annotations: {
89678
89941
  readOnlyHint: false,
89679
89942
  destructiveHint: false,
89680
89943
  idempotentHint: false,
89681
89944
  openWorldHint: true,
89682
- category: "functions"
89683
- }
89684
- }, async ({ action, name, triggers, triggerName }) => {
89945
+ category: "functions",
89946
+ },
89947
+ }, async ({ action, name, triggers, triggerName, }) => {
89685
89948
  // 使用闭包中的 cloudBaseOptions
89686
89949
  const cloudbase = await getManager();
89687
89950
  if (action === "create") {
@@ -89694,9 +89957,9 @@ function registerFunctionTools(server) {
89694
89957
  content: [
89695
89958
  {
89696
89959
  type: "text",
89697
- text: JSON.stringify(result, null, 2)
89698
- }
89699
- ]
89960
+ text: JSON.stringify(result, null, 2),
89961
+ },
89962
+ ],
89700
89963
  };
89701
89964
  }
89702
89965
  else if (action === "delete") {
@@ -89709,9 +89972,9 @@ function registerFunctionTools(server) {
89709
89972
  content: [
89710
89973
  {
89711
89974
  type: "text",
89712
- text: JSON.stringify(result, null, 2)
89713
- }
89714
- ]
89975
+ text: JSON.stringify(result, null, 2),
89976
+ },
89977
+ ],
89715
89978
  };
89716
89979
  }
89717
89980
  else {
@@ -92398,6 +92661,30 @@ class EnvService {
92398
92661
  EnvId: this.envId
92399
92662
  });
92400
92663
  }
92664
+ /**
92665
+ * 创建环境订单
92666
+ */
92667
+ async createBillingDeal(params) {
92668
+ return this.cloudService.request('CreateBillDeal', Object.assign({}, params));
92669
+ }
92670
+ /**
92671
+ * 取消未支付的订单
92672
+ */
92673
+ async cancelDeal(params) {
92674
+ return this.cloudService.request('CancelDeal', Object.assign({}, params));
92675
+ }
92676
+ /**
92677
+ * 删除已取消的订单
92678
+ */
92679
+ // public async deleteDeal(params: {
92680
+ // TranId: string
92681
+ // UserClientIp: string
92682
+ // WxAppId?: string
92683
+ // }) {
92684
+ // return this.cloudService.request<any>('DeleteDeal', {
92685
+ // ...params
92686
+ // })
92687
+ // }
92401
92688
  // 获取 COS CORS 域名
92402
92689
  async getCOSDomains() {
92403
92690
  const cos = this.getCos();
@@ -125717,7 +126004,7 @@ function registerCapiTools(server) {
125717
126004
  // static credentail = 'credential'
125718
126005
  // }
125719
126006
  Object.defineProperty(exports, "__esModule", ({ value: true }));
125720
- exports.COS_SDK_KEEPALIVE = exports.COS_SDK_PROTOCOL = exports.USE_INTERNAL_ENDPOINT = exports.SCF_STATUS = exports.ROLE_NAME = exports.PUBLIC_RSA_KEY = exports.ERROR = exports.SERVICE_TYPE = exports.ENDPOINT = exports.RUN_ENV = exports.SDK_VERSION = exports.ENV_NAME = void 0;
126007
+ exports.SCF_TEMP_COS = exports.COS_SDK_KEEPALIVE = exports.COS_SDK_PROTOCOL = exports.INTERNAL_ENDPOINT_REGION = exports.USE_INTERNAL_ENDPOINT = exports.SCF_STATUS = exports.ROLE_NAME = exports.PUBLIC_RSA_KEY = exports.ERROR = exports.SERVICE_TYPE = exports.ENDPOINT = exports.RUN_ENV = exports.SDK_VERSION = exports.ENV_NAME = void 0;
125721
126008
  exports.ENV_NAME = {
125722
126009
  ENV_SECRETID: 'TENCENTCLOUD_SECRETID',
125723
126010
  ENV_SECRETKEY: 'TENCENTCLOUD_SECRETKEY',
@@ -125769,8 +126056,22 @@ exports.SCF_STATUS = {
125769
126056
  };
125770
126057
  // 是否使用内网域名
125771
126058
  exports.USE_INTERNAL_ENDPOINT = "USE_INTERNAL_ENDPOINT" in process.env;
126059
+ exports.INTERNAL_ENDPOINT_REGION = process.env.INTERNAL_ENDPOINT_REGION;
125772
126060
  exports.COS_SDK_PROTOCOL = process.env.COS_SDK_PROTOCOL;
125773
126061
  exports.COS_SDK_KEEPALIVE = process.env.COS_SDK_KEEPALIVE;
126062
+ // SCF 临时 COS 配置(用于函数代码上传)
126063
+ exports.SCF_TEMP_COS = {
126064
+ APPID: '1253665819',
126065
+ // 区域前缀映射:region -> bucket 前缀
126066
+ REGION_PREFIX_MAP: {
126067
+ 'ap-shanghai': 'sh',
126068
+ 'ap-guangzhou': 'gz',
126069
+ 'ap-beijing': 'bj',
126070
+ 'ap-singapore': 'sg'
126071
+ },
126072
+ DEFAULT_REGION_PREFIX: 'sh',
126073
+ DEFAULT_REGION: 'ap-shanghai'
126074
+ };
125774
126075
 
125775
126076
 
125776
126077
  /***/ }),
@@ -137208,7 +137509,7 @@ class TelemetryReporter {
137208
137509
  const nodeVersion = process.version; // Node.js版本
137209
137510
  const arch = os_1.default.arch(); // 系统架构
137210
137511
  // 从构建时注入的版本号获取MCP版本信息
137211
- const mcpVersion = process.env.npm_package_version || "2.11.0" || 0;
137512
+ const mcpVersion = process.env.npm_package_version || "2.12.0" || 0;
137212
137513
  return {
137213
137514
  userAgent: `${osType} ${osRelease} ${arch} ${nodeVersion} CloudBase-MCP/${mcpVersion}`,
137214
137515
  deviceId: this.deviceId,
@@ -142107,8 +142408,10 @@ function getJavaScripts(wsPort) {
142107
142408
  }
142108
142409
  }
142109
142410
 
142110
- // WebSocket connection
142111
- const ws = new WebSocket('ws://localhost:${wsPort}');
142411
+ // WebSocket: same host as page so it works in remote VS Code / Cloud IDE (no localhost)
142412
+ const wsScheme = window.location.protocol === 'https:' ? 'wss:' : 'ws:';
142413
+ const wsUrl = wsScheme + '//' + window.location.host;
142414
+ const ws = new WebSocket(wsUrl);
142112
142415
 
142113
142416
  ws.onopen = () => {
142114
142417
  console.log('[env-setup] WebSocket connected');
@@ -157027,7 +157330,7 @@ class HostingService {
157027
157330
  * @param options
157028
157331
  */
157029
157332
  async uploadFiles(options) {
157030
- const { localPath, cloudPath, files = [], onProgress, onFileFinish, parallel = 20, ignore, retryCount, retryInterval } = options;
157333
+ const { localPath, cloudPath, files = [], onProgress, onFileFinish, parallel = 20, ignore = ['.DS_Store'], retryCount, retryInterval } = options;
157031
157334
  const hosting = await this.checkStatus();
157032
157335
  const { Bucket, Regoin } = hosting;
157033
157336
  const storageService = await this.environment.getStorageService();
@@ -176915,6 +177218,39 @@ function validation(yargs, usage, y18n) {
176915
177218
  exports.validation = validation;
176916
177219
 
176917
177220
 
177221
+ /***/ }),
177222
+
177223
+ /***/ 59411:
177224
+ /***/ ((__unused_webpack_module, exports) => {
177225
+
177226
+ "use strict";
177227
+
177228
+ Object.defineProperty(exports, "__esModule", ({ value: true }));
177229
+ exports.ReleaseTypeEnum = exports.CloudrunServerType = void 0;
177230
+ var CloudrunServerType;
177231
+ (function (CloudrunServerType) {
177232
+ /**
177233
+ * 函数型服务
177234
+ */
177235
+ CloudrunServerType["Function"] = "function";
177236
+ /**
177237
+ * 容器型服务
177238
+ */
177239
+ CloudrunServerType["Container"] = "container";
177240
+ })(CloudrunServerType || (exports.CloudrunServerType = CloudrunServerType = {}));
177241
+ var ReleaseTypeEnum;
177242
+ (function (ReleaseTypeEnum) {
177243
+ /**
177244
+ * 灰度发布
177245
+ */
177246
+ ReleaseTypeEnum["GRAY"] = "GRAY";
177247
+ /**
177248
+ * 全量发布
177249
+ */
177250
+ ReleaseTypeEnum["FULL"] = "FULL";
177251
+ })(ReleaseTypeEnum || (exports.ReleaseTypeEnum = ReleaseTypeEnum = {}));
177252
+
177253
+
176918
177254
  /***/ }),
176919
177255
 
176920
177256
  /***/ 59527:
@@ -177053,6 +177389,7 @@ class Environment {
177053
177389
  this.cloudBaseContext = context;
177054
177390
  this.envType = context.envType;
177055
177391
  // 拉取当前环境 的环境信息 todo
177392
+ this.userService = new user_1.UserService(this);
177056
177393
  this.functionService = new function_1.FunctionService(this);
177057
177394
  this.cloudRunService = new cloudrun_1.CloudRunService(this);
177058
177395
  this.agentService = new agent_1.AgentService(this);
@@ -194048,7 +194385,7 @@ Object.defineProperty(exports, "__esModule", ({ value: true }));
194048
194385
  exports.CloudBaseContext = void 0;
194049
194386
  const constant_1 = __webpack_require__(40762);
194050
194387
  class CloudBaseContext {
194051
- constructor({ secretId = '', secretKey = '', token = '', proxy = '', region = '', envType = '', useInternalEndpoint = undefined }) {
194388
+ constructor({ secretId = '', secretKey = '', token = '', proxy = '', region = '', envType = '', useInternalEndpoint = undefined, internalEndpointRegion = undefined }) {
194052
194389
  this.secretId = secretId;
194053
194390
  this.secretKey = secretKey;
194054
194391
  this.token = token;
@@ -194056,10 +194393,14 @@ class CloudBaseContext {
194056
194393
  this.region = region;
194057
194394
  this.envType = envType;
194058
194395
  this.useInternalEndpoint = useInternalEndpoint;
194396
+ this.internalEndpointRegion = internalEndpointRegion;
194059
194397
  }
194060
194398
  isInternalEndpoint() {
194061
194399
  return this.useInternalEndpoint !== undefined ? this.useInternalEndpoint : constant_1.USE_INTERNAL_ENDPOINT;
194062
194400
  }
194401
+ getInternalEndpointRegion() {
194402
+ return this.internalEndpointRegion || constant_1.INTERNAL_ENDPOINT_REGION;
194403
+ }
194063
194404
  }
194064
194405
  exports.CloudBaseContext = CloudBaseContext;
194065
194406
 
@@ -203867,7 +204208,7 @@ ${envIdSection}
203867
204208
  ## 环境信息
203868
204209
  - 操作系统: ${os_1.default.type()} ${os_1.default.release()}
203869
204210
  - Node.js版本: ${process.version}
203870
- - MCP 版本:${process.env.npm_package_version || "2.11.0" || 0}
204211
+ - MCP 版本:${process.env.npm_package_version || "2.12.0" || 0}
203871
204212
  - 系统架构: ${os_1.default.arch()}
203872
204213
  - 时间: ${new Date().toISOString()}
203873
204214
  - 请求ID: ${requestId}
@@ -205377,6 +205718,9 @@ class UserService {
205377
205718
  }]
205378
205719
  });
205379
205720
  }
205721
+ async getTcbAccountInfo() {
205722
+ return this.tcbService.request('DescribeTcbAccountInfo');
205723
+ }
205380
205724
  isValidStr(obj) {
205381
205725
  return typeof obj === 'string' && obj.trim().length > 0;
205382
205726
  }
@@ -218624,7 +218968,7 @@ function registerSetupTools(server) {
218624
218968
  title: "下载项目模板",
218625
218969
  description: `自动下载并部署CloudBase项目模板。⚠️ **MANDATORY FOR NEW PROJECTS** ⚠️
218626
218970
 
218627
- **CRITICAL**: This tool MUST be called FIRST when starting a new project.\n\n支持的模板:\n- react: React + CloudBase 全栈应用模板\n- vue: Vue + CloudBase 全栈应用模板\n- miniprogram: 微信小程序 + 云开发模板 \n- uniapp: UniApp + CloudBase 跨端应用模板\n- rules: 只包含AI编辑器配置文件(包含Cursor、WindSurf、CodeBuddy等所有主流编辑器配置),适合在已有项目中补充AI编辑器配置\n\n支持的IDE类型:\n- all: 下载所有IDE配置\n- cursor: Cursor AI编辑器\n- 其他IDE类型见下方列表\n\n注意:如果未传入 ide 参数且无法从环境变量检测到 IDE,将提示错误并要求传入 ide 参数\n- windsurf: WindSurf AI编辑器\n- codebuddy: CodeBuddy AI编辑器\n- claude-code: Claude Code AI编辑器\n- cline: Cline AI编辑器\n- gemini-cli: Gemini CLI\n- opencode: OpenCode AI编辑器\n- qwen-code: 通义灵码\n- baidu-comate: 百度Comate\n- openai-codex-cli: OpenAI Codex CLI\n- augment-code: Augment Code\n- github-copilot: GitHub Copilot\n- roocode: RooCode AI编辑器\n- tongyi-lingma: 通义灵码\n- trae: Trae AI编辑器\n- qoder: Qoder AI编辑器\n- antigravity: Google Antigravity AI编辑器\n- vscode: Visual Studio Code\n- kiro: Kiro AI编辑器\n- aider: Aider AI编辑器\n\n特别说明:\n- rules 模板会自动包含当前 mcp 版本号信息(版本号:${ true ? "2.11.0" : 0}),便于后续维护和版本追踪\n- 下载 rules 模板时,如果项目中已存在 README.md 文件,系统会自动保护该文件不被覆盖(除非设置 overwrite=true)`,
218971
+ **CRITICAL**: This tool MUST be called FIRST when starting a new project.\n\n支持的模板:\n- react: React + CloudBase 全栈应用模板\n- vue: Vue + CloudBase 全栈应用模板\n- miniprogram: 微信小程序 + 云开发模板 \n- uniapp: UniApp + CloudBase 跨端应用模板\n- rules: 只包含AI编辑器配置文件(包含Cursor、WindSurf、CodeBuddy等所有主流编辑器配置),适合在已有项目中补充AI编辑器配置\n\n支持的IDE类型:\n- all: 下载所有IDE配置\n- cursor: Cursor AI编辑器\n- 其他IDE类型见下方列表\n\n注意:如果未传入 ide 参数且无法从环境变量检测到 IDE,将提示错误并要求传入 ide 参数\n- windsurf: WindSurf AI编辑器\n- codebuddy: CodeBuddy AI编辑器\n- claude-code: Claude Code AI编辑器\n- cline: Cline AI编辑器\n- gemini-cli: Gemini CLI\n- opencode: OpenCode AI编辑器\n- qwen-code: 通义灵码\n- baidu-comate: 百度Comate\n- openai-codex-cli: OpenAI Codex CLI\n- augment-code: Augment Code\n- github-copilot: GitHub Copilot\n- roocode: RooCode AI编辑器\n- tongyi-lingma: 通义灵码\n- trae: Trae AI编辑器\n- qoder: Qoder AI编辑器\n- antigravity: Google Antigravity AI编辑器\n- vscode: Visual Studio Code\n- kiro: Kiro AI编辑器\n- aider: Aider AI编辑器\n\n特别说明:\n- rules 模板会自动包含当前 mcp 版本号信息(版本号:${ true ? "2.12.0" : 0}),便于后续维护和版本追踪\n- 下载 rules 模板时,如果项目中已存在 README.md 文件,系统会自动保护该文件不被覆盖(除非设置 overwrite=true)`,
218628
218972
  inputSchema: {
218629
218973
  template: zod_1.z
218630
218974
  .enum(["react", "vue", "miniprogram", "uniapp", "rules"])
@@ -230171,6 +230515,7 @@ class CloudService {
230171
230515
  }
230172
230516
  get baseUrl() {
230173
230517
  const internalEndpoint = this.cloudBaseContext.isInternalEndpoint();
230518
+ const internalEndpointRegion = this.cloudBaseContext.getInternalEndpointRegion();
230174
230519
  const tcb = process.env.TCB_BASE_URL || 'https://tcb.tencentcloudapi.com';
230175
230520
  const urlMap = {
230176
230521
  tcb,
@@ -230185,6 +230530,9 @@ class CloudService {
230185
230530
  [service]: `https://${service}.internal.tencentcloudapi.com`,
230186
230531
  })).reduce((acc, cur) => (Object.assign(Object.assign({}, acc), cur)), {});
230187
230532
  if (internalEndpoint) {
230533
+ if (internalEndpointRegion) {
230534
+ return `https://${this.service}.${internalEndpointRegion}.tencentcloudapi.woa.com`;
230535
+ }
230188
230536
  return intranetUrlMap[this.service] || `https://${this.service}.internal.tencentcloudapi.com`;
230189
230537
  }
230190
230538
  if (urlMap[this.service]) {
@@ -236962,7 +237310,11 @@ function registerGatewayTools(server) {
236962
237310
  description: "创建云函数的 HTTP 访问",
236963
237311
  inputSchema: {
236964
237312
  name: zod_1.z.string().describe("函数名"),
236965
- path: zod_1.z.string().describe("HTTP 访问路径")
237313
+ path: zod_1.z.string().describe("HTTP 访问路径"),
237314
+ type: zod_1.z
237315
+ .enum(["Event", "HTTP"])
237316
+ .optional()
237317
+ .describe("函数类型,Event 为事件型云函数(默认),HTTP 为 HTTP 云函数")
236966
237318
  },
236967
237319
  annotations: {
236968
237320
  readOnlyHint: false,
@@ -236971,10 +237323,12 @@ function registerGatewayTools(server) {
236971
237323
  openWorldHint: true,
236972
237324
  category: "gateway"
236973
237325
  }
236974
- }, async ({ name, path }) => {
237326
+ }, async ({ name, path, type }) => {
236975
237327
  const cloudbase = await getManager();
237328
+ // Event 云函数 type=1,HTTP 云函数 type=6
237329
+ const accessType = type === "HTTP" ? 6 : 1;
236976
237330
  const result = await cloudbase.access.createAccess({
236977
- type: 1,
237331
+ type: accessType, // HTTP 云函数使用 type=6,需要类型断言
236978
237332
  name,
236979
237333
  path
236980
237334
  });
@@ -256741,10 +257095,15 @@ class InteractiveServer {
256741
257095
  3722, 3723, 3724, 3725, 3726, 3727, 3728, 3729, 3730, 3731, 3732, 3733,
256742
257096
  3734, 3735,
256743
257097
  ];
257098
+ /** Idle timeout for HTTP/WS connections (e.g. long login). Avoids "connection disconnected" after ~1 min. */
257099
+ static SERVER_IDLE_MS = 30 * 60 * 1000; // 30 minutes
257100
+ /** WebSocket ping interval to keep connection alive past proxies/firewalls. */
257101
+ static WS_PING_INTERVAL_MS = 25 * 1000; // 25 seconds
256744
257102
  constructor(mcpServer) {
256745
257103
  this._mcpServer = mcpServer;
256746
257104
  this.app = (0, express_1.default)();
256747
257105
  this.server = http_1.default.createServer(this.app);
257106
+ this.applyServerTimeouts();
256748
257107
  this.wss = new ws_1.WebSocketServer({ server: this.server });
256749
257108
  this.setupExpress();
256750
257109
  this.setupWebSocket();
@@ -256760,6 +257119,16 @@ class InteractiveServer {
256760
257119
  this.isRunning = false;
256761
257120
  }
256762
257121
  }
257122
+ /** Apply timeouts so long-lived login does not cause "connection disconnected". */
257123
+ applyServerTimeouts() {
257124
+ this.server.timeout = 0;
257125
+ if (typeof this.server.keepAliveTimeout === "number") {
257126
+ this.server.keepAliveTimeout = InteractiveServer.SERVER_IDLE_MS;
257127
+ }
257128
+ if (typeof this.server.headersTimeout === "number") {
257129
+ this.server.headersTimeout = Math.max(this.server.headersTimeout || 0, InteractiveServer.SERVER_IDLE_MS);
257130
+ }
257131
+ }
256763
257132
  setupExpress() {
256764
257133
  this.app.use(express_1.default.json());
256765
257134
  this.app.get("/env-setup/:sessionId", (req, res) => {
@@ -256863,6 +257232,16 @@ class InteractiveServer {
256863
257232
  setupWebSocket() {
256864
257233
  this.wss.on("connection", (ws) => {
256865
257234
  (0, logger_js_1.debug)("WebSocket client connected");
257235
+ // Keep connection alive during long login so proxies/firewalls do not close it
257236
+ const pingInterval = setInterval(() => {
257237
+ if (ws.readyState === ws_1.WebSocket.OPEN) {
257238
+ ws.ping();
257239
+ }
257240
+ }, InteractiveServer.WS_PING_INTERVAL_MS);
257241
+ ws.on("close", () => {
257242
+ clearInterval(pingInterval);
257243
+ (0, logger_js_1.debug)("WebSocket client disconnected");
257244
+ });
256866
257245
  ws.on("message", async (message) => {
256867
257246
  try {
256868
257247
  const data = JSON.parse(message.toString());
@@ -256972,9 +257351,6 @@ class InteractiveServer {
256972
257351
  (0, logger_js_1.error)("WebSocket message parsing error", err instanceof Error ? err : new Error(String(err)));
256973
257352
  }
256974
257353
  });
256975
- ws.on("close", () => {
256976
- (0, logger_js_1.debug)("WebSocket client disconnected");
256977
- });
256978
257354
  });
256979
257355
  }
256980
257356
  async start() {
@@ -257016,13 +257392,15 @@ class InteractiveServer {
257016
257392
  reject(err);
257017
257393
  }
257018
257394
  };
257395
+ // Host: default 0.0.0.0 so Cloud IDE / VSCode Remote port-forward can connect; set INTERACTIVE_SERVER_HOST=127.0.0.1 for local-only
257396
+ const host = process.env.INTERACTIVE_SERVER_HOST ?? "0.0.0.0";
257019
257397
  // 设置成功监听处理
257020
257398
  const listeningHandler = () => {
257021
257399
  const address = this.server.address();
257022
257400
  if (address && typeof address === "object") {
257023
257401
  this.port = address.port;
257024
257402
  this.isRunning = true;
257025
- (0, logger_js_1.info)(`Interactive server started successfully on http://localhost:${this.port}`);
257403
+ (0, logger_js_1.info)(`Interactive server started successfully on http://${host}:${this.port}`);
257026
257404
  // 移除临时监听器
257027
257405
  this.server.removeListener("error", errorHandler);
257028
257406
  this.server.removeListener("listening", listeningHandler);
@@ -257037,7 +257415,7 @@ class InteractiveServer {
257037
257415
  this.server.once("error", errorHandler);
257038
257416
  this.server.once("listening", listeningHandler);
257039
257417
  try {
257040
- this.server.listen(portToTry, "127.0.0.1");
257418
+ this.server.listen(portToTry, host);
257041
257419
  }
257042
257420
  catch (err) {
257043
257421
  (0, logger_js_1.error)(`Failed to bind to port ${portToTry}:`, err instanceof Error ? err : new Error(String(err)));
@@ -257078,6 +257456,7 @@ class InteractiveServer {
257078
257456
  this.port = 0;
257079
257457
  // 重新创建整个服务器实例以便下次使用
257080
257458
  this.server = http_1.default.createServer(this.app);
257459
+ this.applyServerTimeouts();
257081
257460
  this.wss = new ws_1.WebSocketServer({ server: this.server });
257082
257461
  this.setupWebSocket();
257083
257462
  (0, logger_js_1.debug)("HTTP and WebSocket servers recreated for next use");
@@ -257168,11 +257547,9 @@ class InteractiveServer {
257168
257547
  (0, logger_js_1.warn)(`Please manually open: ${url}`);
257169
257548
  }
257170
257549
  (0, logger_js_1.info)("Waiting for user selection...");
257171
- // Use shorter timeout for CodeBuddy when notification is sent (2 minutes)
257172
- // This prevents hanging while still giving users enough time to respond
257173
- // Otherwise use the default 10 minutes timeout
257174
- const timeoutDuration = (isCodeBuddy && notificationSent) ? 2 * 60 * 1000 : 10 * 60 * 1000;
257175
- (0, logger_js_1.debug)(`[collectEnvId] Using timeout duration: ${timeoutDuration / 1000} seconds (CodeBuddy: ${isCodeBuddy}, notification sent: ${notificationSent})`);
257550
+ // Use same 10 minutes for all IDEs so long login (re-auth, switch account) does not close the server
257551
+ const timeoutDuration = 10 * 60 * 1000;
257552
+ (0, logger_js_1.debug)(`[collectEnvId] Using timeout duration: ${timeoutDuration / 1000} seconds`);
257176
257553
  return new Promise((resolve) => {
257177
257554
  this.currentResolver = (result) => {
257178
257555
  // 用户选择完成后,关闭服务器
@@ -274430,20 +274807,21 @@ class CloudBase {
274430
274807
  }
274431
274808
  constructor(config = {}) {
274432
274809
  this.cloudBaseConfig = {};
274433
- let { secretId, secretKey, token, envId, proxy, region, envType, useInternalEndpoint } = config;
274810
+ let { secretId, secretKey, token, envId, proxy, region, envType, useInternalEndpoint, internalEndpointRegion } = config;
274434
274811
  // config 中传入的 secretId secretkey 必须同时存在
274435
274812
  if ((secretId && !secretKey) || (!secretId && secretKey)) {
274436
274813
  throw new Error('secretId and secretKey must be a pair');
274437
274814
  }
274438
274815
  this.cloudBaseConfig = {
274439
- secretId,
274440
- secretKey,
274816
+ secretId: secretId ? secretId.trim() : secretId,
274817
+ secretKey: secretKey ? secretKey.trim() : secretKey,
274441
274818
  token,
274442
274819
  envId,
274443
274820
  envType,
274444
274821
  proxy,
274445
274822
  region,
274446
- useInternalEndpoint
274823
+ useInternalEndpoint,
274824
+ internalEndpointRegion,
274447
274825
  };
274448
274826
  // 初始化 context
274449
274827
  this.context = new context_1.CloudBaseContext(this.cloudBaseConfig);
@@ -276620,6 +276998,7 @@ exports.FunctionService = void 0;
276620
276998
  const fs_1 = __importDefault(__webpack_require__(29021));
276621
276999
  const path_1 = __importDefault(__webpack_require__(39902));
276622
277000
  const lodash_1 = __importDefault(__webpack_require__(2543));
277001
+ const cos_nodejs_sdk_v5_1 = __importDefault(__webpack_require__(93625));
276623
277002
  const packer_1 = __webpack_require__(5147);
276624
277003
  const error_1 = __webpack_require__(40430);
276625
277004
  const utils_1 = __webpack_require__(62358);
@@ -276629,9 +277008,33 @@ function isNodeFunction(runtime) {
276629
277008
  // 不严格限制
276630
277009
  return runtime === 'Nodejs10.15' || runtime === 'Nodejs8.9' || (runtime === null || runtime === void 0 ? void 0 : runtime.includes('Nodejs'));
276631
277010
  }
277011
+ /**
277012
+ * 构建镜像配置对象
277013
+ * @param imageConfig 镜像配置
277014
+ * @param options 可选配置
277015
+ * @param options.includeCommandList 是否包含 CommandList/ArgsList(仅 CreateFunction 支持)
277016
+ * @returns 构建好的镜像配置对象
277017
+ */
277018
+ function buildImageConfig(imageConfig, options) {
277019
+ var _a, _b;
277020
+ const { includeCommandList = false } = options || {};
277021
+ const config = Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({ ImageType: imageConfig.imageType || 'enterprise', ImageUri: imageConfig.imageUri }, (imageConfig.registryId && { RegistryId: imageConfig.registryId })), (imageConfig.entryPoint && { EntryPoint: imageConfig.entryPoint })), (imageConfig.command && { Command: imageConfig.command })), (imageConfig.args && { Args: imageConfig.args })), (typeof imageConfig.containerImageAccelerate === 'boolean' && {
277022
+ ContainerImageAccelerate: imageConfig.containerImageAccelerate
277023
+ })), { ImagePort: imageConfig.imagePort || 9000 });
277024
+ // CommandList 和 ArgsList 仅在 CreateFunction 时支持
277025
+ if (includeCommandList) {
277026
+ if ((_a = imageConfig.commandList) === null || _a === void 0 ? void 0 : _a.length) {
277027
+ config.CommandList = imageConfig.commandList;
277028
+ }
277029
+ if ((_b = imageConfig.argsList) === null || _b === void 0 ? void 0 : _b.length) {
277030
+ config.ArgsList = imageConfig.argsList;
277031
+ }
277032
+ }
277033
+ return config;
277034
+ }
276632
277035
  // 解析函数配置,换成请求参数
276633
277036
  function configToParams(options) {
276634
- var _a, _b, _c, _d, _e;
277037
+ var _a, _b, _c, _d, _e, _f, _g;
276635
277038
  const { func, codeSecret, baseParams } = options;
276636
277039
  let installDependency;
276637
277040
  // Node 函数默认安装依赖
@@ -276684,6 +277087,40 @@ function configToParams(options) {
276684
277087
  }));
276685
277088
  params.Layers = transformLayers;
276686
277089
  }
277090
+ // HTTP 云函数类型
277091
+ if ((func === null || func === void 0 ? void 0 : func.type) === 'HTTP') {
277092
+ params.Type = 'HTTP';
277093
+ // WebSocket 协议支持
277094
+ if ((func === null || func === void 0 ? void 0 : func.protocolType) === 'WS') {
277095
+ params.ProtocolType = 'WS';
277096
+ // 协议参数,直接透传或使用默认值
277097
+ // 参考文档:https://cloud.tencent.com/document/api/583/17244#ProtocolParams
277098
+ const idleTimeOut = (_g = (_f = func === null || func === void 0 ? void 0 : func.protocolParams) === null || _f === void 0 ? void 0 : _f.wsParams) === null || _g === void 0 ? void 0 : _g.idleTimeOut;
277099
+ params.ProtocolParams = {
277100
+ WSParams: {
277101
+ IdleTimeOut: typeof idleTimeOut === 'number' ? idleTimeOut : 15
277102
+ }
277103
+ };
277104
+ }
277105
+ // 多并发配置
277106
+ // 参考文档:https://cloud.tencent.com/document/api/583/17244#InstanceConcurrencyConfig
277107
+ if (func === null || func === void 0 ? void 0 : func.instanceConcurrencyConfig) {
277108
+ params.InstanceConcurrencyConfig = {
277109
+ DynamicEnabled: func.instanceConcurrencyConfig.dynamicEnabled || 'FALSE',
277110
+ MaxConcurrency: func.instanceConcurrencyConfig.maxConcurrency || 10
277111
+ };
277112
+ }
277113
+ }
277114
+ // 云函数描述
277115
+ if (func === null || func === void 0 ? void 0 : func.description) {
277116
+ params.Description = func.description;
277117
+ }
277118
+ // 镜像配置(用于镜像部署)
277119
+ if (func === null || func === void 0 ? void 0 : func.imageConfig) {
277120
+ params.Code = {
277121
+ ImageConfig: buildImageConfig(func.imageConfig, { includeCommandList: true })
277122
+ };
277123
+ }
276687
277124
  return params;
276688
277125
  }
276689
277126
  class FunctionService {
@@ -276692,6 +277129,7 @@ class FunctionService {
276692
277129
  this.scfService = new utils_1.CloudService(environment.cloudBaseContext, 'scf', '2018-04-16');
276693
277130
  this.vpcService = new utils_1.CloudService(environment.cloudBaseContext, 'vpc', '2017-03-12');
276694
277131
  this.tcbService = new utils_1.CloudService(environment.cloudBaseContext, 'tcb', '2018-06-08');
277132
+ this.userService = environment.getUserService();
276695
277133
  }
276696
277134
  /**
276697
277135
  * 增量更新函数代码
@@ -276700,11 +277138,12 @@ class FunctionService {
276700
277138
  * @memberof FunctionService
276701
277139
  */
276702
277140
  async updateFunctionIncrementalCode(funcParam) {
276703
- const { namespace } = this.getFunctionConfig();
277141
+ const { env, namespace } = this.getFunctionConfig();
276704
277142
  const { functionRootPath, func, deleteFiles, addFiles } = funcParam;
276705
277143
  const { name, runtime } = func;
276706
277144
  const params = {
276707
277145
  FunctionName: name,
277146
+ EnvId: env,
276708
277147
  Namespace: namespace
276709
277148
  };
276710
277149
  let packer;
@@ -276729,7 +277168,7 @@ class FunctionService {
276729
277168
  }
276730
277169
  params.AddFiles = base64;
276731
277170
  }
276732
- return this.scfService.request('UpdateFunctionIncrementalCode', params);
277171
+ return this.tcbService.request('UpdateFunctionIncrementalCode', params);
276733
277172
  }
276734
277173
  /**
276735
277174
  * 创建云函数
@@ -276737,30 +277176,49 @@ class FunctionService {
276737
277176
  * @returns {(Promise<IResponseInfo | ICreateFunctionRes>)}
276738
277177
  */
276739
277178
  async createFunction(funcParam) {
276740
- const { namespace } = this.getFunctionConfig();
276741
- const { func, functionRootPath, force = false, base64Code, codeSecret, functionPath } = funcParam;
277179
+ var _a;
277180
+ const { env } = this.getFunctionConfig();
277181
+ const { func, functionRootPath, force = false, base64Code, codeSecret, functionPath, deployMode } = funcParam;
276742
277182
  const funcName = func.name;
276743
277183
  const params = configToParams({
276744
277184
  func,
276745
277185
  codeSecret,
276746
277186
  baseParams: {
276747
- Namespace: namespace,
277187
+ EnvId: env,
276748
277188
  Role: 'TCB_QcsRole',
276749
277189
  Stamp: 'MINI_QCBASE'
276750
277190
  }
276751
277191
  });
276752
- params.Code = await this.getCodeParams({
276753
- func,
276754
- base64Code,
276755
- functionPath,
276756
- functionRootPath
276757
- }, params.InstallDependency);
277192
+ // 根据部署方式处理 Code 参数
277193
+ // 优先使用显式指定的 deployMode,如果未指定但存在 imageConfig 则认为是镜像部署
277194
+ const isImageDeploy = deployMode === 'image' || (!deployMode && func.imageConfig);
277195
+ if (isImageDeploy) {
277196
+ // 镜像部署:Code 参数已在 configToParams 中通过 imageConfig 设置
277197
+ if (!((_a = func.imageConfig) === null || _a === void 0 ? void 0 : _a.imageUri)) {
277198
+ throw new error_1.CloudBaseError('镜像部署需要配置 imageConfig.imageUri');
277199
+ }
277200
+ // 镜像部署的特殊配置
277201
+ // 镜像函数不需要 Handler
277202
+ delete params.Handler;
277203
+ // 镜像函数不需要安装依赖
277204
+ delete params.InstallDependency;
277205
+ }
277206
+ else {
277207
+ // 代码部署:通过 getCodeParams 获取代码参数
277208
+ params.Code = await this.getCodeParams({
277209
+ func,
277210
+ base64Code,
277211
+ functionPath,
277212
+ functionRootPath,
277213
+ deployMode
277214
+ }, params.InstallDependency);
277215
+ }
276758
277216
  const { TopicId, LogsetId } = this.getClsServiceConfig();
276759
277217
  params.ClsTopicId = TopicId;
276760
277218
  params.ClsLogsetId = LogsetId;
276761
277219
  try {
276762
277220
  // 创建云函数
276763
- const res = await this.scfService.request('CreateFunction', params);
277221
+ const res = await this.tcbService.request('CreateFunction', params);
276764
277222
  // 等待函数状态正常
276765
277223
  await this.waitFunctionActive(funcName, codeSecret);
276766
277224
  // 创建函数触发器、失败自动重试
@@ -276778,13 +277236,14 @@ class FunctionService {
276778
277236
  const functionExist = e.code === 'ResourceInUse.FunctionName' || e.code === 'ResourceInUse.Function';
276779
277237
  // 已存在同名函数,强制更新
276780
277238
  if (functionExist && force) {
276781
- // 1. 更新函数配置和代码,同名函数可能存在 codeSecret,先修改代码,清除 codeSecret
277239
+ // 1. 更新函数代码(通过 deployMode 区分镜像部署和代码部署)
276782
277240
  const codeRes = await this.updateFunctionCode({
276783
277241
  func,
276784
277242
  base64Code,
276785
277243
  functionPath,
276786
277244
  functionRootPath,
276787
- codeSecret: codeSecret
277245
+ codeSecret: codeSecret,
277246
+ deployMode: isImageDeploy ? 'image' : undefined
276788
277247
  });
276789
277248
  // 等待函数状态正常
276790
277249
  await this.waitFunctionActive(funcName, codeSecret);
@@ -276829,9 +277288,9 @@ class FunctionService {
276829
277288
  */
276830
277289
  async getFunctionList(limit = 20, offset = 0) {
276831
277290
  // 获取Function 环境配置
276832
- const { namespace } = this.getFunctionConfig();
276833
- const res = await this.scfService.request('ListFunctions', {
276834
- Namespace: namespace,
277291
+ const { env } = this.getFunctionConfig();
277292
+ const res = await this.tcbService.request('ListFunctions', {
277293
+ EnvId: env,
276835
277294
  Limit: limit,
276836
277295
  Offset: offset
276837
277296
  });
@@ -276845,9 +277304,9 @@ class FunctionService {
276845
277304
  */
276846
277305
  async listFunctions(limit = 20, offset = 0) {
276847
277306
  // 获取Function 环境配置
276848
- const { namespace } = this.getFunctionConfig();
276849
- const res = await this.scfService.request('ListFunctions', {
276850
- Namespace: namespace,
277307
+ const { env } = this.getFunctionConfig();
277308
+ const res = await this.tcbService.request('ListFunctions', {
277309
+ EnvId: env,
276851
277310
  Limit: limit,
276852
277311
  Offset: offset
276853
277312
  });
@@ -276878,8 +277337,8 @@ class FunctionService {
276878
277337
  const { envId } = options;
276879
277338
  while (true) {
276880
277339
  try {
276881
- const res = await this.scfService.request('ListFunctions', {
276882
- Namespace: envId,
277340
+ const res = await this.tcbService.request('ListFunctions', {
277341
+ EnvId: envId,
276883
277342
  Limit: pageSize,
276884
277343
  Offset: currentOffset
276885
277344
  });
@@ -276962,16 +277421,17 @@ class FunctionService {
276962
277421
  * @returns {Promise<Record<string, string>>}
276963
277422
  */
276964
277423
  async getFunctionDetail(name, codeSecret) {
276965
- const { namespace } = this.getFunctionConfig();
277424
+ const { env } = this.getFunctionConfig();
276966
277425
  const params = {
276967
277426
  FunctionName: name,
276968
- Namespace: namespace,
276969
- ShowCode: 'TRUE'
277427
+ EnvId: env,
277428
+ ShowCode: 'TRUE',
277429
+ Namespace: env
276970
277430
  };
276971
277431
  if (codeSecret) {
276972
277432
  params.CodeSecret = codeSecret;
276973
277433
  }
276974
- const data = await this.scfService.request('GetFunction', params);
277434
+ const data = await this.tcbService.request('GetFunction', params);
276975
277435
  // 解析 VPC 配置
276976
277436
  const { VpcId = '', SubnetId = '' } = data.VpcConfig || {};
276977
277437
  if (VpcId && SubnetId) {
@@ -277148,7 +277608,7 @@ class FunctionService {
277148
277608
  * @returns {Promise<IResponseInfo>}
277149
277609
  */
277150
277610
  async updateFunctionConfig(func) {
277151
- var _a, _b, _c, _d, _e;
277611
+ var _a, _b, _c, _d, _e, _f, _g;
277152
277612
  const { namespace } = this.getFunctionConfig();
277153
277613
  const envVariables = Object.keys(func.envVariables || {}).map(key => ({
277154
277614
  Key: key,
@@ -277161,6 +277621,9 @@ class FunctionService {
277161
277621
  Namespace: namespace,
277162
277622
  L5Enable: l5Enable
277163
277623
  };
277624
+ if (func === null || func === void 0 ? void 0 : func.description) {
277625
+ params.Description = func.description;
277626
+ }
277164
277627
  // 修复参数存在 undefined 字段时,会出现鉴权失败的情况
277165
277628
  // Environment 为覆盖式修改,不保留已有字段
277166
277629
  envVariables.length && (params.Environment = { Variables: envVariables });
@@ -277191,6 +277654,22 @@ class FunctionService {
277191
277654
  }));
277192
277655
  params.Layers = transformLayers;
277193
277656
  }
277657
+ // WebSocket 协议支持(仅 HTTP 函数)
277658
+ if (func === null || func === void 0 ? void 0 : func.protocolParams) {
277659
+ const idleTimeOut = (_g = (_f = func === null || func === void 0 ? void 0 : func.protocolParams) === null || _f === void 0 ? void 0 : _f.wsParams) === null || _g === void 0 ? void 0 : _g.idleTimeOut;
277660
+ params.ProtocolParams = {
277661
+ WSParams: {
277662
+ IdleTimeOut: typeof idleTimeOut === 'number' ? idleTimeOut : 15
277663
+ }
277664
+ };
277665
+ }
277666
+ // 多并发配置(仅 HTTP 函数)
277667
+ if (func === null || func === void 0 ? void 0 : func.instanceConcurrencyConfig) {
277668
+ params.InstanceConcurrencyConfig = {
277669
+ DynamicEnabled: func.instanceConcurrencyConfig.dynamicEnabled || 'FALSE',
277670
+ MaxConcurrency: func.instanceConcurrencyConfig.maxConcurrency || 10
277671
+ };
277672
+ }
277194
277673
  try {
277195
277674
  // 如果函数配置中包含触发器,则更新触发器
277196
277675
  if (func.triggers && func.triggers.length > 0) {
@@ -277206,7 +277685,8 @@ class FunctionService {
277206
277685
  }
277207
277686
  catch (e) {
277208
277687
  throw new error_1.CloudBaseError(`[${func.name}] 更新函数配置失败:${e.message}`, {
277209
- code: e.code
277688
+ code: e.code,
277689
+ requestId: e.requestId
277210
277690
  });
277211
277691
  }
277212
277692
  }
@@ -277217,9 +277697,35 @@ class FunctionService {
277217
277697
  * @memberof FunctionService
277218
277698
  */
277219
277699
  async updateFunctionCode(funcParam) {
277220
- const { func, functionRootPath, base64Code, codeSecret, functionPath } = funcParam;
277700
+ var _a;
277701
+ const { func, functionRootPath, base64Code, codeSecret, functionPath, deployMode } = funcParam;
277221
277702
  const funcName = func.name;
277222
- const { namespace } = this.getFunctionConfig();
277703
+ const { env } = this.getFunctionConfig();
277704
+ // 镜像部署:使用镜像配置更新函数代码
277705
+ if (deployMode === 'image') {
277706
+ if (!((_a = func.imageConfig) === null || _a === void 0 ? void 0 : _a.imageUri)) {
277707
+ throw new error_1.CloudBaseError('镜像部署需要配置 imageConfig.imageUri');
277708
+ }
277709
+ const params = {
277710
+ FunctionName: funcName,
277711
+ EnvId: env,
277712
+ Code: {
277713
+ ImageConfig: buildImageConfig(func.imageConfig)
277714
+ }
277715
+ };
277716
+ try {
277717
+ // 等待函数状态正常
277718
+ await this.waitFunctionActive(funcName, codeSecret);
277719
+ return await this.tcbService.request('UpdateFunctionCode', params);
277720
+ }
277721
+ catch (e) {
277722
+ throw new error_1.CloudBaseError(`[${funcName}] 函数代码更新失败:${e.message}`, {
277723
+ code: e.code,
277724
+ requestId: e.requestId
277725
+ });
277726
+ }
277727
+ }
277728
+ // 代码部署:原有逻辑
277223
277729
  let installDependency;
277224
277730
  // Node 函数默认安装依赖
277225
277731
  installDependency = isNodeFunction(func.runtime) ? 'TRUE' : 'FALSE';
@@ -277231,9 +277737,16 @@ class FunctionService {
277231
277737
  func,
277232
277738
  functionPath,
277233
277739
  functionRootPath,
277234
- base64Code
277740
+ base64Code,
277741
+ deployMode
277235
277742
  }, installDependency);
277236
- const params = Object.assign({ FunctionName: funcName, Namespace: namespace, Handler: func.handler || 'index.main', InstallDependency: installDependency }, codeParams);
277743
+ const params = {
277744
+ FunctionName: funcName,
277745
+ EnvId: env,
277746
+ Handler: func.handler || 'index.main',
277747
+ InstallDependency: installDependency,
277748
+ Code: codeParams
277749
+ };
277237
277750
  if (codeSecret) {
277238
277751
  params.CodeSecret = codeSecret;
277239
277752
  }
@@ -277241,15 +277754,16 @@ class FunctionService {
277241
277754
  // 等待函数状态正常
277242
277755
  await this.waitFunctionActive(funcName, codeSecret);
277243
277756
  // 更新云函数代码
277244
- const res = await this.scfService.request('UpdateFunctionCode', params);
277757
+ const res = await this.tcbService.request('UpdateFunctionCode', params);
277245
277758
  if (installDependency && func.isWaitInstall === true) {
277246
277759
  await this.waitFunctionActive(funcName, codeSecret);
277247
277760
  }
277248
277761
  return res;
277249
277762
  }
277250
277763
  catch (e) {
277251
- throw new error_1.CloudBaseError(`[${funcName}] 函数代码更新失败: ${e.message}`, {
277252
- code: e.code
277764
+ throw new error_1.CloudBaseError(`[${funcName}] 函数代码更新失败:${e.message}`, {
277765
+ code: e.code,
277766
+ requestId: e.requestId
277253
277767
  });
277254
277768
  }
277255
277769
  }
@@ -277274,7 +277788,9 @@ class FunctionService {
277274
277788
  return Object.assign({ RequestId }, Result);
277275
277789
  }
277276
277790
  catch (e) {
277277
- throw new error_1.CloudBaseError(`[${name}] 调用失败:\n${e.message}`);
277791
+ throw new error_1.CloudBaseError(`[${name}] 调用失败:${e.message}`, {
277792
+ requestId: e.requestId
277793
+ });
277278
277794
  }
277279
277795
  }
277280
277796
  /**
@@ -277352,7 +277868,8 @@ class FunctionService {
277352
277868
  catch (e) {
277353
277869
  throw new error_1.CloudBaseError(`[${name}] 创建触发器失败:${e.message}`, {
277354
277870
  action: e.action,
277355
- code: e.code
277871
+ code: e.code,
277872
+ requestId: e.requestId
277356
277873
  });
277357
277874
  }
277358
277875
  }
@@ -277444,7 +277961,9 @@ class FunctionService {
277444
277961
  return { Url, RequestId, CodeSha256 };
277445
277962
  }
277446
277963
  catch (e) {
277447
- throw new error_1.CloudBaseError(`[${functionName}] 获取函数代码下载链接失败:\n${e.message}`);
277964
+ throw new error_1.CloudBaseError(`[${functionName}] 获取函数代码下载链接失败:${e.message}`, {
277965
+ requestId: e.requestId
277966
+ });
277448
277967
  }
277449
277968
  }
277450
277969
  // 函数绑定文件层
@@ -277596,6 +278115,45 @@ class FunctionService {
277596
278115
  LayerVersion: version
277597
278116
  });
277598
278117
  }
278118
+ // 检查函数状态,部分操作在函数更新中时不可进行
278119
+ async waitFunctionActive(funcName, codeSecret) {
278120
+ let ticker;
278121
+ let timer;
278122
+ let resolved;
278123
+ return new Promise((resolve, reject) => {
278124
+ // 超时时间 5 分钟
278125
+ timer = setTimeout(() => {
278126
+ clearInterval(ticker);
278127
+ if (!resolved) {
278128
+ reject(new error_1.CloudBaseError('函数状态异常,检查超时'));
278129
+ }
278130
+ }, 300000);
278131
+ ticker = setInterval(async () => {
278132
+ try {
278133
+ const { Status, StatusDesc, StatusReasons, RequestId } = await this.getFunctionDetail(funcName, codeSecret);
278134
+ // 更新中
278135
+ if (Status === constant_1.SCF_STATUS.CREATING || Status === constant_1.SCF_STATUS.UPDATING)
278136
+ return;
278137
+ // 创建失败
278138
+ if (Status === constant_1.SCF_STATUS.CREATE_FAILED) {
278139
+ const errorDetails = (StatusReasons === null || StatusReasons === void 0 ? void 0 : StatusReasons.map(item => `[${item.ErrorCode}] ${item.ErrorMessage}`).join('\n')) || '';
278140
+ const errorMsg = `云函数创建失败${StatusDesc ? `\n状态描述: ${StatusDesc}` : ''}${errorDetails ? `\n失败信息: ${errorDetails}` : ''}`;
278141
+ throw new error_1.CloudBaseError(errorMsg, { requestId: RequestId });
278142
+ }
278143
+ // 函数状态正常
278144
+ clearInterval(ticker);
278145
+ clearTimeout(timer);
278146
+ resolve();
278147
+ }
278148
+ catch (e) {
278149
+ clearInterval(ticker);
278150
+ clearTimeout(timer);
278151
+ reject(e);
278152
+ }
278153
+ resolved = true;
278154
+ }, 1000);
278155
+ });
278156
+ }
277599
278157
  /**
277600
278158
  * 设置预置并发
277601
278159
  * @private
@@ -277711,6 +278269,116 @@ class FunctionService {
277711
278269
  Namespace: namespace
277712
278270
  });
277713
278271
  }
278272
+ /**
278273
+ * 通过scf COS 上传方式(通过 GetTempCosInfo + COS SDK 上传)
278274
+ * 返回 TempCosObjectName 用于创建/更新函数
278275
+ */
278276
+ async uploadFunctionZipToCosLegacy(options, installDependency) {
278277
+ const { func, functionPath, functionRootPath } = options;
278278
+ const { env } = this.getFunctionConfig();
278279
+ const { CloudAppId } = await this.userService.getTcbAccountInfo();
278280
+ const objectPath = `${CloudAppId}/${env}/${func.name}.zip`;
278281
+ // 1. 生成存放函数包的临时 Cos 目录
278282
+ const { Date: cosDate, Sign } = await this.scfService.request('GetTempCosInfo', {
278283
+ ObjectPath: `${objectPath}`
278284
+ });
278285
+ // 2. 本地压缩
278286
+ const codeType = packer_1.CodeType.File;
278287
+ // 云端安装依赖,自动忽略 node_modules 目录
278288
+ const ignore = installDependency === 'TRUE'
278289
+ ? ['node_modules/**/*', 'node_modules', ...(func.ignore || [])]
278290
+ : [...(func.ignore || [])];
278291
+ const packer = new packer_1.FunctionPacker({
278292
+ ignore,
278293
+ codeType,
278294
+ functionPath,
278295
+ name: func.name,
278296
+ root: functionRootPath
278297
+ });
278298
+ const zipFilePath = await packer.compressFiles();
278299
+ // 3. 初始化 cos 并上传
278300
+ // 根据环境 region 获取对应的 bucket 前缀
278301
+ const region = this.environment.cloudBaseContext.region || constant_1.SCF_TEMP_COS.DEFAULT_REGION;
278302
+ const regionPrefix = constant_1.SCF_TEMP_COS.REGION_PREFIX_MAP[region] || constant_1.SCF_TEMP_COS.DEFAULT_REGION_PREFIX;
278303
+ const tempCosObjectName = `/${cosDate}/${objectPath}`;
278304
+ const uploadParams = {
278305
+ Bucket: `${regionPrefix}tempcos-${constant_1.SCF_TEMP_COS.APPID}`,
278306
+ Key: tempCosObjectName,
278307
+ Region: region,
278308
+ FilePath: zipFilePath,
278309
+ };
278310
+ const cos = new cos_nodejs_sdk_v5_1.default({
278311
+ getAuthorization: function (options, callback) {
278312
+ // 注入上一步获取的临时密钥
278313
+ callback(Sign);
278314
+ }
278315
+ });
278316
+ return new Promise((resolve, reject) => {
278317
+ cos.sliceUploadFile(uploadParams, async (err, data) => {
278318
+ // 清理临时文件
278319
+ await packer.clean();
278320
+ if (err) {
278321
+ reject(new error_1.CloudBaseError(`COS 上传失败: ${err.message || err}`));
278322
+ }
278323
+ else {
278324
+ resolve(data);
278325
+ }
278326
+ });
278327
+ });
278328
+ }
278329
+ /**
278330
+ * 新的 COS 上传方式(通过 DescribeBuildServiceCosInfo + PUT 上传)
278331
+ * 返回 CosTimestamp 用于创建/更新函数
278332
+ */
278333
+ async uploadFunctionZipToCos(options, installDependency) {
278334
+ const { func, functionPath, functionRootPath } = options;
278335
+ const { env } = this.getFunctionConfig();
278336
+ // 1. 生成存放函数包的临时 Cos 目录
278337
+ const { UploadUrl, UnixTimestamp, UploadHeaders } = await this.tcbService.request('DescribeBuildServiceCosInfo', {
278338
+ EnvId: env,
278339
+ ServiceName: func.name,
278340
+ Business: 'scf',
278341
+ Suffix: '.zip'
278342
+ });
278343
+ // 2. 本地压缩
278344
+ const codeType = packer_1.CodeType.File;
278345
+ // 云端安装依赖,自动忽略 node_modules 目录
278346
+ const ignore = installDependency === 'TRUE'
278347
+ ? ['node_modules/**/*', 'node_modules', ...(func.ignore || [])]
278348
+ : [...(func.ignore || [])];
278349
+ const packer = new packer_1.FunctionPacker({
278350
+ ignore,
278351
+ codeType,
278352
+ functionPath,
278353
+ name: func.name,
278354
+ root: functionRootPath
278355
+ });
278356
+ const zipFilePath = await packer.compressFiles();
278357
+ // 3. 通过 UploadUrl 直接上传
278358
+ const fileBuffer = fs_1.default.readFileSync(zipFilePath);
278359
+ // 构建请求头
278360
+ const headers = {
278361
+ 'Content-Type': 'application/zip'
278362
+ };
278363
+ if (UploadHeaders && UploadHeaders.length > 0) {
278364
+ UploadHeaders.forEach(item => {
278365
+ headers[item.Key] = item.Value;
278366
+ });
278367
+ }
278368
+ const response = await fetch(UploadUrl, {
278369
+ method: 'PUT',
278370
+ body: fileBuffer,
278371
+ headers
278372
+ });
278373
+ if (!response.ok) {
278374
+ throw new error_1.CloudBaseError(`上传失败: ${response.status} ${response.statusText}`);
278375
+ }
278376
+ // 清理临时文件
278377
+ await packer.clean();
278378
+ return {
278379
+ UnixTimestamp
278380
+ };
278381
+ }
277714
278382
  async createAccessPath(name, path) {
277715
278383
  const access = this.environment.getAccessService();
277716
278384
  try {
@@ -277735,11 +278403,13 @@ class FunctionService {
277735
278403
  }
277736
278404
  }
277737
278405
  async getCodeParams(options, installDependency) {
277738
- const { func, functionPath, functionRootPath, base64Code } = options;
277739
- // 20MB
277740
- const BIG_LENGTH = 167772160;
277741
- if ((base64Code === null || base64Code === void 0 ? void 0 : base64Code.length) > BIG_LENGTH) {
277742
- throw new error_1.CloudBaseError('base64 不能大于 20 MB');
278406
+ const { func, functionPath, functionRootPath, base64Code, deployMode } = options;
278407
+ // 直接传入 base64Code 的情况,校验大小
278408
+ // ZipFile 上传大小上限 1.5MB,base64 编码后长度约为原始大小的 4/3
278409
+ const MAX_ZIP_SIZE = 1.5 * 1024 * 1024; // 1.5MB
278410
+ const MAX_BASE64_LENGTH = Math.floor(MAX_ZIP_SIZE * 4 / 3); // ≈ 2097152
278411
+ if ((base64Code === null || base64Code === void 0 ? void 0 : base64Code.length) > MAX_BASE64_LENGTH) {
278412
+ throw new error_1.CloudBaseError('ZipFile 上传不能大于 1.5MB,请使用 COS 上传方式');
277743
278413
  }
277744
278414
  if (base64Code === null || base64Code === void 0 ? void 0 : base64Code.length) {
277745
278415
  return {
@@ -277759,17 +278429,29 @@ class FunctionService {
277759
278429
  root: functionRootPath
277760
278430
  });
277761
278431
  await packer.build();
277762
- // 通过云 API 传输的代码大小不能超过 50MB
277763
- const reachMax = await packer.isReachMaxSize();
277764
- if (reachMax) {
277765
- throw new error_1.CloudBaseError('函数代码不能大于 50MB');
277766
- }
277767
- const base64 = await packer.getBase64Code();
277768
- if (!(base64 === null || base64 === void 0 ? void 0 : base64.length)) {
277769
- throw new error_1.CloudBaseError('文件不能为空');
278432
+ // 指定 zip 上传方式:走 ZipFile base64 上传
278433
+ if (deployMode === 'zip') {
278434
+ // 判断是否超过 ZipFile 上传大小限制(1.5MB)
278435
+ const reachMax = await packer.isReachMaxSize();
278436
+ if (reachMax) {
278437
+ throw new error_1.CloudBaseError('ZipFile 上传不能大于 1.5MB,请使用 COS 上传方式(deployMode: "cos")');
278438
+ }
278439
+ const base64 = await packer.getBase64Code();
278440
+ if (!(base64 === null || base64 === void 0 ? void 0 : base64.length)) {
278441
+ throw new error_1.CloudBaseError('文件不能为空');
278442
+ }
278443
+ console.log(`[${func.name}] 部署方式: ZIP base64 上传`);
278444
+ return {
278445
+ ZipFile: base64
278446
+ };
277770
278447
  }
278448
+ // 默认走 COS 上传
278449
+ console.log(`[${func.name}] 部署方式: COS 上传`);
278450
+ const region = this.environment.cloudBaseContext.region || constant_1.SCF_TEMP_COS.DEFAULT_REGION;
278451
+ const legacyResult = await this.uploadFunctionZipToCosLegacy(options, installDependency);
277771
278452
  return {
277772
- ZipFile: base64
278453
+ CosBucketRegion: region,
278454
+ TempCosObjectName: `/${legacyResult.Key}`
277773
278455
  };
277774
278456
  }
277775
278457
  // 获取 COS 临时信息
@@ -277808,10 +278490,11 @@ class FunctionService {
277808
278490
  * @memberof FunctionService
277809
278491
  */
277810
278492
  getFunctionConfig() {
277811
- var _a;
278493
+ var _a, _b, _c, _d;
277812
278494
  const envConfig = this.environment.lazyEnvironmentConfig;
277813
- const namespace = envConfig.Functions[0].Namespace;
277814
- const appId = (_a = envConfig.Storages[0]) === null || _a === void 0 ? void 0 : _a.AppId;
278495
+ // Functions 可能为空
278496
+ const namespace = ((_b = (_a = envConfig.Functions) === null || _a === void 0 ? void 0 : _a[0]) === null || _b === void 0 ? void 0 : _b.Namespace) || '';
278497
+ const appId = (_d = (_c = envConfig.Storages) === null || _c === void 0 ? void 0 : _c[0]) === null || _d === void 0 ? void 0 : _d.AppId;
277815
278498
  const { proxy } = this.environment.cloudBaseContext;
277816
278499
  return {
277817
278500
  proxy,
@@ -277857,45 +278540,6 @@ class FunctionService {
277857
278540
  });
277858
278541
  return SubnetSet;
277859
278542
  }
277860
- // 检查函数状态,部分操作在函数更新中时不可进行
277861
- async waitFunctionActive(funcName, codeSecret) {
277862
- let ticker;
277863
- let timer;
277864
- let resolved;
277865
- return new Promise((resolve, reject) => {
277866
- // 超时时间 5 分钟
277867
- timer = setTimeout(() => {
277868
- clearInterval(ticker);
277869
- if (!resolved) {
277870
- reject(new error_1.CloudBaseError('函数状态异常,检查超时'));
277871
- }
277872
- }, 300000);
277873
- ticker = setInterval(async () => {
277874
- try {
277875
- const { Status, StatusDesc, StatusReasons, RequestId } = await this.getFunctionDetail(funcName, codeSecret);
277876
- // 更新中
277877
- if (Status === constant_1.SCF_STATUS.CREATING || Status === constant_1.SCF_STATUS.UPDATING)
277878
- return;
277879
- // 创建失败
277880
- if (Status === constant_1.SCF_STATUS.CREATE_FAILED) {
277881
- StatusDesc && console.log(`函数状态描述: ${StatusDesc}`);
277882
- const errorDetails = StatusReasons.map(item => `[${item.ErrorCode}] ${item.ErrorMessage}`).join('\n');
277883
- throw new error_1.CloudBaseError(`云函数创建失败\n失败信息: ${errorDetails}\nRequestId: ${RequestId}`);
277884
- }
277885
- // 函数状态正常
277886
- clearInterval(ticker);
277887
- clearTimeout(timer);
277888
- resolve();
277889
- }
277890
- catch (e) {
277891
- clearInterval(ticker);
277892
- clearTimeout(timer);
277893
- reject(e);
277894
- }
277895
- resolved = true;
277896
- }, 1000);
277897
- });
277898
- }
277899
278543
  }
277900
278544
  exports.FunctionService = FunctionService;
277901
278545
  __decorate([
@@ -278006,6 +278650,12 @@ __decorate([
278006
278650
  __decorate([
278007
278651
  (0, utils_1.preLazy)()
278008
278652
  ], FunctionService.prototype, "getFunctionAlias", null);
278653
+ __decorate([
278654
+ (0, utils_1.preLazy)()
278655
+ ], FunctionService.prototype, "uploadFunctionZipToCosLegacy", null);
278656
+ __decorate([
278657
+ (0, utils_1.preLazy)()
278658
+ ], FunctionService.prototype, "uploadFunctionZipToCos", null);
278009
278659
  __decorate([
278010
278660
  (0, utils_1.preLazy)()
278011
278661
  ], FunctionService.prototype, "createAccessPath", null);