@cloudbase/cli 2.12.3-beta.1 → 2.12.3-beta.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (2) hide show
  1. package/dist/standalone/cli.js +653 -929
  2. package/package.json +1 -1
@@ -295574,11 +295574,33 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
295574
295574
  Object.defineProperty(exports, "__esModule", ({ value: true }));
295575
295575
  exports.getPort = void 0;
295576
295576
  const portfinder_1 = __importDefault(__webpack_require__(31323));
295577
- const DEFAULT_PORT = 9012;
295577
+ // 默认端口
295578
+ const LOCAL_DEFAULT_PORT = 9012;
295579
+ const REMOTE_DEFAULT_PORT = 19012;
295580
+ function isRemoteEnvironment() {
295581
+ return Boolean(process.env.SSH_CONNECTION
295582
+ || process.env.SSH_CLIENT
295583
+ || process.env.SSH_TTY
295584
+ || process.env.VSCODE_IPC_HOOK_CLI
295585
+ || process.env.VSCODE_AGENT_FOLDER
295586
+ || process.env.REMOTE_CONTAINERS
295587
+ || process.env.CODESPACES
295588
+ || process.env.GITPOD_WORKSPACE_ID);
295589
+ }
295590
+ function getStartPort() {
295591
+ const customStartPort = Number(process.env.TCB_WEB_LOGIN_START_PORT);
295592
+ if (Number.isInteger(customStartPort) && customStartPort > 0 && customStartPort < 65535) {
295593
+ return customStartPort;
295594
+ }
295595
+ return isRemoteEnvironment() ? REMOTE_DEFAULT_PORT : LOCAL_DEFAULT_PORT;
295596
+ }
295597
+ // 获取本地可用端口
295578
295598
  function getPort() {
295579
295599
  return __awaiter(this, void 0, void 0, function* () {
295600
+ const startPort = getStartPort();
295580
295601
  const port = yield portfinder_1.default.getPortPromise({
295581
- port: DEFAULT_PORT
295602
+ port: startPort,
295603
+ stopPort: 65535
295582
295604
  });
295583
295605
  return port;
295584
295606
  });
@@ -326147,7 +326169,7 @@ module.exports = function generate_pattern(it, $keyword, $ruleType) {
326147
326169
  /***/ ((module) => {
326148
326170
 
326149
326171
  "use strict";
326150
- module.exports = /*#__PURE__*/JSON.parse('{"name":"@cloudbase/cli","version":"2.12.3-beta.1","description":"cli tool for cloudbase","main":"lib/index.js","scripts":{"build":"rimraf lib types && tsc --resolveJsonModule && cpx \\"src/**/*.html\\" lib","watch":"rimraf lib types && tsc -w","dev":"rimraf lib types && cpx \\"src/**/*.html\\" lib && tsc -w","eslint":"eslint \\"./**/*.ts\\"","test":"node --experimental-vm-modules node_modules/jest/bin/jest.js --runInBand --forceExit --detectOpenHandles --coverage --verbose --testTimeout=10000","tsc":"tsc","pkg":"pkg ./bin/cloudbase.js --out-path ./pkg","postinstall":"node ./post-install.js || exit 0 && patch-package","prepublishOnly":"node ./scripts/check-publish-source.js","debug":"bin/tcb.js lowcode watch","build:bundle":"webpack --config build/webpack/cli.cjs && webpack --config build/webpack/ccr.cjs && node build/scripts/copy-figlet-fonts.js","package:darwin-arm64":"OS=darwin ARCH=arm64 VERSION= node -e \\"require(\'child_process\').execSync(\'bash build/scripts/package.sh\',{stdio:\'inherit\'})\\"","package:darwin-x64":"OS=darwin ARCH=x64 VERSION= node -e \\"require(\'child_process\').execSync(\'bash build/scripts/package.sh\',{stdio:\'inherit\'})\\"","package:linux-arm64":"OS=linux ARCH=arm64 VERSION= node -e \\"require(\'child_process\').execSync(\'bash build/scripts/package.sh\',{stdio:\'inherit\'})\\"","package:linux-x64":"OS=linux ARCH=x64 VERSION= node -e \\"require(\'child_process\').execSync(\'bash build/scripts/package.sh\',{stdio:\'inherit\'})\\"","package:all":"bash build/scripts/build-all.sh","node:fetch:one":"node -e \\"require(\'child_process\').execSync(\'bash build/scripts/fetch-node.sh\',{stdio:\'inherit\'})\\"","node:fetch:all":"NODE_VERSION=22.18.0 bash build/scripts/fetch-node.sh --all","node:fetch:win-x64":"OS=windows ARCH=x64 NODE_VERSION=22.18.0 bash build/scripts/fetch-node.sh","node:fetch:win-arm64":"OS=windows ARCH=arm64 NODE_VERSION=22.18.0 bash build/scripts/fetch-node.sh","package:windows-x64":"OS=windows ARCH=x64 VERSION= node -e \\"require(\'child_process\').execSync(\'bash build/scripts/package.sh\',{stdio:\'inherit\'})\\"","package:windows-arm64":"OS=windows ARCH=arm64 VERSION= node -e \\"require(\'child_process\').execSync(\'bash build/scripts/package.sh\',{stdio:\'inherit\'})\\"","package:windows-all":"npm run -s node:fetch:win-x64 && npm run -s node:fetch:win-arm64 && npm run -s package:windows-x64 && npm run -s package:windows-arm64","package:npm":"npm run build && npm run build:bundle && bash build/scripts/prepare-publish.sh","out:prune":"bash build/scripts/prune-out.sh","i18n:scan":"i18next-scanner --config locales/i18next-scanner.config.js && node locales/scripts/generate.js","i18n:sync":"node locales/scripts/sync.js sync","publish":"node ./scripts/publish.js"},"repository":{"type":"git","url":"https://github.com/TencentCloudBase/cloud-base-cli.git"},"bin":{"cloudbase":"bin/cloudbase.js","cloudbase-mcp":"bin/cloudbase-mcp.cjs","tcb":"bin/tcb.js"},"husky":{"hooks":{"pre-commit":"npm run build"}},"author":"cwuyiqing@gmail.com","license":"ISC","dependencies":{"@cloudbase/cloud-api":"^0.5.5","@cloudbase/cloudbase-mcp":"^2.7.3","@cloudbase/framework-core":"^1.9.7","@cloudbase/functions-framework":"1.16.0","@cloudbase/iac-core":"0.0.3-alpha.14","@cloudbase/lowcode-cli":"^0.23.0","@cloudbase/manager-node":"4.10.1","@cloudbase/toolbox":"^0.7.9","@dotenvx/dotenvx":"^1.48.3","@musistudio/claude-code-router":"1.0.36","address":"^1.1.2","camelcase-keys":"^7.0.2","chalk":"^2.4.2","cli-table3":"^0.5.1","commander":"7","del":"^5.1.0","didyoumean":"^1.2.2","enquirer":"^2.3.6","execa":"^4.0.3","figlet":"^1.7.0","fs-extra":"^8.1.0","gradient-string":"^2.0.2","https-proxy-agent":"^5.0.1","i":"^0.3.7","inquirer":"^6.5.0","json-schema-to-typescript":"^14.0.5","lodash":"^4.17.21","log-symbols":"^3.0.0","lowdb":"^1.0.0","make-dir":"^3.0.0","node-fetch":"^2.6.0","nodemon":"^3.1.4","npm":"^11.5.2","open":"^7.0.0","ora":"^4.0.2","os-locale":"5.0.0","patch-package":"^8.0.0","portfinder":"^1.0.28","progress":"^2.0.3","query-string":"^6.8.1","reflect-metadata":"^0.1.13","semver":"^7.3.7","simple-git":"^3.28.0","tar-fs":"^2.0.1","terminal-link":"^2.1.1","toml":"^3.0.0","unzipper":"^0.10.10","update-notifier":"^4.0.0","xdg-basedir":"^4.0.0","yargs":"^16.2.0","yargs-parser":"^21.0.1","zod":"^4.0.13"},"devDependencies":{"@babel/parser":"^7.28.4","@babel/traverse":"^7.28.4","@babel/types":"^7.28.4","@types/fs-extra":"^11.0.4","@types/jest":"^27","@types/koa__router":"^8.0.11","@types/lodash":"^4.14.182","@types/node":"^12.12.38","@types/node-fetch":"^2.5.4","@types/react":"^17.0.37","@types/semver":"^7.3.9","@types/unzipper":"^0.10.11","@types/webpack-dev-server":"^3.11.1","@typescript-eslint/eslint-plugin":"^4.8.1","@typescript-eslint/parser":"^4.8.1","cpx":"^1.5.0","eslint":"^7.14.0","eslint-config-alloy":"^3.8.2","husky":"^3.0.9","i18next-scanner":"^4.6.0","jest":"^27","rimraf":"^3.0.2","ts-jest":"^27","typescript":"^4.7.2","webpack":"^5.92.0","webpack-cli":"^5.1.4"},"packageManager":"yarn@3.6.2+sha512.2c2f8b9615e6659773f65cdec7cf92ef773a98a99e611579601f61c7a91ec94c89c929aac86f1cee819421a9b0db7acfd53ec3ebb95af44f77f77634b08b9557"}');
326172
+ module.exports = /*#__PURE__*/JSON.parse('{"name":"@cloudbase/cli","version":"2.12.3-beta.3","description":"cli tool for cloudbase","main":"lib/index.js","scripts":{"build":"rimraf lib types && tsc --resolveJsonModule && cpx \\"src/**/*.html\\" lib","watch":"rimraf lib types && tsc -w","dev":"rimraf lib types && cpx \\"src/**/*.html\\" lib && tsc -w","eslint":"eslint \\"./**/*.ts\\"","test":"node --experimental-vm-modules node_modules/jest/bin/jest.js --runInBand --forceExit --detectOpenHandles --coverage --verbose --testTimeout=10000","tsc":"tsc","pkg":"pkg ./bin/cloudbase.js --out-path ./pkg","postinstall":"node ./post-install.js || exit 0 && patch-package","prepublishOnly":"node ./scripts/check-publish-source.js","debug":"bin/tcb.js lowcode watch","build:bundle":"webpack --config build/webpack/cli.cjs && webpack --config build/webpack/ccr.cjs && node build/scripts/copy-figlet-fonts.js","package:darwin-arm64":"OS=darwin ARCH=arm64 VERSION= node -e \\"require(\'child_process\').execSync(\'bash build/scripts/package.sh\',{stdio:\'inherit\'})\\"","package:darwin-x64":"OS=darwin ARCH=x64 VERSION= node -e \\"require(\'child_process\').execSync(\'bash build/scripts/package.sh\',{stdio:\'inherit\'})\\"","package:linux-arm64":"OS=linux ARCH=arm64 VERSION= node -e \\"require(\'child_process\').execSync(\'bash build/scripts/package.sh\',{stdio:\'inherit\'})\\"","package:linux-x64":"OS=linux ARCH=x64 VERSION= node -e \\"require(\'child_process\').execSync(\'bash build/scripts/package.sh\',{stdio:\'inherit\'})\\"","package:all":"bash build/scripts/build-all.sh","node:fetch:one":"node -e \\"require(\'child_process\').execSync(\'bash build/scripts/fetch-node.sh\',{stdio:\'inherit\'})\\"","node:fetch:all":"NODE_VERSION=22.18.0 bash build/scripts/fetch-node.sh --all","node:fetch:win-x64":"OS=windows ARCH=x64 NODE_VERSION=22.18.0 bash build/scripts/fetch-node.sh","node:fetch:win-arm64":"OS=windows ARCH=arm64 NODE_VERSION=22.18.0 bash build/scripts/fetch-node.sh","package:windows-x64":"OS=windows ARCH=x64 VERSION= node -e \\"require(\'child_process\').execSync(\'bash build/scripts/package.sh\',{stdio:\'inherit\'})\\"","package:windows-arm64":"OS=windows ARCH=arm64 VERSION= node -e \\"require(\'child_process\').execSync(\'bash build/scripts/package.sh\',{stdio:\'inherit\'})\\"","package:windows-all":"npm run -s node:fetch:win-x64 && npm run -s node:fetch:win-arm64 && npm run -s package:windows-x64 && npm run -s package:windows-arm64","package:npm":"npm run build && npm run build:bundle && bash build/scripts/prepare-publish.sh","out:prune":"bash build/scripts/prune-out.sh","i18n:scan":"i18next-scanner --config locales/i18next-scanner.config.js && node locales/scripts/generate.js","i18n:sync":"node locales/scripts/sync.js sync","publish":"node ./scripts/publish.js"},"repository":{"type":"git","url":"https://github.com/TencentCloudBase/cloud-base-cli.git"},"bin":{"cloudbase":"bin/cloudbase.js","cloudbase-mcp":"bin/cloudbase-mcp.cjs","tcb":"bin/tcb.js"},"husky":{"hooks":{"pre-commit":"npm run build"}},"author":"cwuyiqing@gmail.com","license":"ISC","dependencies":{"@cloudbase/cloud-api":"^0.5.5","@cloudbase/cloudbase-mcp":"^2.7.3","@cloudbase/framework-core":"^1.9.7","@cloudbase/functions-framework":"1.16.0","@cloudbase/iac-core":"0.0.3-alpha.14","@cloudbase/lowcode-cli":"^0.23.0","@cloudbase/manager-node":"4.7.4","@cloudbase/toolbox":"^0.7.16-beta.1","@dotenvx/dotenvx":"^1.48.3","@musistudio/claude-code-router":"1.0.36","address":"^1.1.2","camelcase-keys":"^7.0.2","chalk":"^2.4.2","cli-table3":"^0.5.1","commander":"7","del":"^5.1.0","didyoumean":"^1.2.2","enquirer":"^2.3.6","execa":"^4.0.3","figlet":"^1.7.0","fs-extra":"^8.1.0","gradient-string":"^2.0.2","https-proxy-agent":"^5.0.1","i":"^0.3.7","inquirer":"^6.5.0","json-schema-to-typescript":"^14.0.5","lodash":"^4.17.21","log-symbols":"^3.0.0","lowdb":"^1.0.0","make-dir":"^3.0.0","node-fetch":"^2.6.0","nodemon":"^3.1.4","npm":"^11.5.2","open":"^7.0.0","ora":"^4.0.2","os-locale":"5.0.0","patch-package":"^8.0.0","portfinder":"^1.0.28","progress":"^2.0.3","query-string":"^6.8.1","reflect-metadata":"^0.1.13","semver":"^7.3.7","simple-git":"^3.28.0","tar-fs":"^2.0.1","terminal-link":"^2.1.1","toml":"^3.0.0","unzipper":"^0.10.10","update-notifier":"^4.0.0","xdg-basedir":"^4.0.0","yargs":"^16.2.0","yargs-parser":"^21.0.1","zod":"^4.0.13"},"devDependencies":{"@babel/parser":"^7.28.4","@babel/traverse":"^7.28.4","@babel/types":"^7.28.4","@types/fs-extra":"^11.0.4","@types/jest":"^27","@types/koa__router":"^8.0.11","@types/lodash":"^4.14.182","@types/node":"^12.12.38","@types/node-fetch":"^2.5.4","@types/react":"^17.0.37","@types/semver":"^7.3.9","@types/unzipper":"^0.10.11","@types/webpack-dev-server":"^3.11.1","@typescript-eslint/eslint-plugin":"^4.8.1","@typescript-eslint/parser":"^4.8.1","cpx":"^1.5.0","eslint":"^7.14.0","eslint-config-alloy":"^3.8.2","husky":"^3.0.9","i18next-scanner":"^4.6.0","jest":"^27","rimraf":"^3.0.2","ts-jest":"^27","typescript":"^4.7.2","webpack":"^5.92.0","webpack-cli":"^5.1.4"},"packageManager":"yarn@3.6.2+sha512.2c2f8b9615e6659773f65cdec7cf92ef773a98a99e611579601f61c7a91ec94c89c929aac86f1cee819421a9b0db7acfd53ec3ebb95af44f77f77634b08b9557"}');
326151
326173
 
326152
326174
  /***/ }),
326153
326175
 
@@ -333651,6 +333673,7 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
333651
333673
  Object.defineProperty(exports, "__esModule", ({ value: true }));
333652
333674
  exports.getMacAddress = void 0;
333653
333675
  const address_1 = __importDefault(__webpack_require__(56163));
333676
+ // 获取本机 Mac 地址
333654
333677
  function getMacAddress() {
333655
333678
  return __awaiter(this, void 0, void 0, function* () {
333656
333679
  return new Promise((resolve) => {
@@ -334541,6 +334564,9 @@ const DefaultCloudBaseConfig = {
334541
334564
  functionRoot: './functions',
334542
334565
  functions: []
334543
334566
  };
334567
+ /**
334568
+ * 从配置文件中解析 cloudbase 配置
334569
+ */
334544
334570
  function resolveCloudBaseConfig(options) {
334545
334571
  var _a, _b;
334546
334572
  return __awaiter(this, void 0, void 0, function* () {
@@ -334549,17 +334575,21 @@ function resolveCloudBaseConfig(options) {
334549
334575
  searchFrom,
334550
334576
  moduleName: 'tcb'
334551
334577
  });
334578
+ // 检查旧的配置文件
334552
334579
  if (oldTcbConfig) {
334553
334580
  throw new error_1.CloudBaseError('tcbrc.json 配置文件已废弃,请使用 cloudbaserc 配置文件!');
334554
334581
  }
334582
+ // 可能为 null
334555
334583
  const localCloudBaseConfig = yield (0, cosmiconfig_1.loadConfig)({
334556
334584
  searchFrom,
334557
334585
  configPath
334558
334586
  });
334587
+ // localCloudBaseConfig 不为空,且不存在 envId
334559
334588
  if (localCloudBaseConfig && !localCloudBaseConfig.envId) {
334560
334589
  throw new error_1.CloudBaseError('无效的配置文件,配置文件必须包含环境 Id(envId) 字段');
334561
334590
  }
334562
334591
  const cloudbaseConfig = Object.assign(Object.assign({}, DefaultCloudBaseConfig), localCloudBaseConfig);
334592
+ // 兼容不同形式的配置
334563
334593
  if ((_a = cloudbaseConfig.functions) === null || _a === void 0 ? void 0 : _a.length) {
334564
334594
  cloudbaseConfig.functions = (_b = cloudbaseConfig.functions) === null || _b === void 0 ? void 0 : _b.map((func) => {
334565
334595
  if (func.config) {
@@ -334577,19 +334607,25 @@ function resolveCloudBaseConfig(options) {
334577
334607
  });
334578
334608
  }
334579
334609
  exports.resolveCloudBaseConfig = resolveCloudBaseConfig;
334610
+ /**
334611
+ * 从命令行和配置文件中获取 envId
334612
+ */
334580
334613
  function getEnvId(commandOptions) {
334581
334614
  var _a;
334582
334615
  return __awaiter(this, void 0, void 0, function* () {
334583
334616
  const envId = commandOptions === null || commandOptions === void 0 ? void 0 : commandOptions.envId;
334584
334617
  const configPath = (_a = commandOptions === null || commandOptions === void 0 ? void 0 : commandOptions.parent) === null || _a === void 0 ? void 0 : _a.configFile;
334585
334618
  const cloudbaseConfig = yield resolveCloudBaseConfig(configPath);
334619
+ // 命令行 envId 可以覆盖配置文件 envId
334586
334620
  const assignEnvId = envId || (cloudbaseConfig === null || cloudbaseConfig === void 0 ? void 0 : cloudbaseConfig.envId);
334587
334621
  return assignEnvId;
334588
334622
  });
334589
334623
  }
334590
334624
  exports.getEnvId = getEnvId;
334591
334625
  const renderConfig = (template, view) => {
334626
+ // 渲染时不 escape
334592
334627
  mustache_1.default.escape = (text) => {
334628
+ // 将对象转成 JSON 字符串
334593
334629
  if (typeof text === 'object') {
334594
334630
  try {
334595
334631
  return JSON.stringify(text).replace(/"/g, '\\"');
@@ -334603,6 +334639,7 @@ const renderConfig = (template, view) => {
334603
334639
  return mustache_1.default.render(template, view, ['"{{', '}}"']);
334604
334640
  };
334605
334641
  exports.renderConfig = renderConfig;
334642
+ // cloudbase v2+ 配置文件解析器
334606
334643
  class ConfigParser {
334607
334644
  static get(key, defaultValue, options) {
334608
334645
  return __awaiter(this, void 0, void 0, function* () {
@@ -334620,14 +334657,22 @@ class ConfigParser {
334620
334657
  return this.instance.options(options).update(key, value);
334621
334658
  });
334622
334659
  }
334660
+ // 解析配置
334623
334661
  static parseRawConfig(rawConfig, cwd = process.cwd()) {
334624
334662
  return __awaiter(this, void 0, void 0, function* () {
334625
334663
  let config = lodash_1.default.cloneDeep(rawConfig);
334664
+ // 命令行中指定的 envId,优先级最高
334626
334665
  const envId = yargs_1.default.argv.e || yargs_1.default.argv.envId;
334666
+ // 加载本地 env 文件
334627
334667
  const env = (0, env_1.loadEnvVariables)(cwd);
334668
+ // 转换成字符串
334628
334669
  let configString = JSON.stringify(config);
334629
334670
  const envs = {
334630
- env: Object.assign(Object.assign({ ENV_ID: envId || config.envId }, env), process.env),
334671
+ // 环境变量
334672
+ env: Object.assign(Object.assign({
334673
+ // 注入 ENV_ID,同云端部署保持一致
334674
+ ENV_ID: envId || config.envId }, env), process.env),
334675
+ // 云开发相关的变量
334631
334676
  tcb: {
334632
334677
  envId: envId || config.envId
334633
334678
  },
@@ -334635,14 +334680,17 @@ class ConfigParser {
334635
334680
  uid: (0, uid_1.uuid)(24)
334636
334681
  }
334637
334682
  };
334683
+ // --envId 优先级最高
334638
334684
  if (envId) {
334639
334685
  envs.env.envId = envId;
334640
334686
  envs.env.ENV_ID = envId;
334641
334687
  }
334688
+ // 使用模板渲染
334642
334689
  configString = (0, exports.renderConfig)(configString, envs);
334643
334690
  config = JSON.parse(configString, (key, value) => {
334644
334691
  if (typeof value === 'string') {
334645
334692
  try {
334693
+ // 只解析对象
334646
334694
  const parsed = JSON.parse(value);
334647
334695
  if (typeof parsed === 'object') {
334648
334696
  return parsed;
@@ -334661,6 +334709,7 @@ class ConfigParser {
334661
334709
  constructor(options = {}) {
334662
334710
  this.options(options);
334663
334711
  }
334712
+ // 重写内部配置
334664
334713
  options(options = {}) {
334665
334714
  const { cwd = process.cwd(), cover = true, configPath } = options;
334666
334715
  this.cwd = cwd;
@@ -334668,21 +334717,28 @@ class ConfigParser {
334668
334717
  this.configPath = configPath;
334669
334718
  return this;
334670
334719
  }
334720
+ // get config value by lodash object paths
334721
+ // https://lodash.com/docs/4.17.15#get
334671
334722
  get(key, defaultValue) {
334672
334723
  return __awaiter(this, void 0, void 0, function* () {
334673
334724
  const config = yield this.getConfig();
334725
+ // 不带 key,返回整个配置
334674
334726
  if (!key) {
334675
334727
  return config;
334676
334728
  }
334729
+ // 返回具体字段的值
334677
334730
  return lodash_1.default.get(config, key, defaultValue);
334678
334731
  });
334679
334732
  }
334733
+ // update config value by lodash object paths
334734
+ // https://lodash.com/docs/4.17.15#set
334680
334735
  update(key, value, cover) {
334681
334736
  return __awaiter(this, void 0, void 0, function* () {
334682
334737
  const config = yield resolveCloudBaseConfig({
334683
334738
  configPath: this.configPath
334684
334739
  });
334685
334740
  let unionConfig;
334741
+ // 当 value 为 undefined 且 key 为对象时,直接把 key 作为值更新到 config 中
334686
334742
  if (typeof value === 'undefined' && typeof key === 'object') {
334687
334743
  unionConfig = Object.assign(Object.assign({}, config), key);
334688
334744
  }
@@ -334692,24 +334748,34 @@ class ConfigParser {
334692
334748
  yield this.updateConfig(unionConfig, cover);
334693
334749
  });
334694
334750
  }
334751
+ // 读配置,支持外部直接调用
334695
334752
  getConfig() {
334696
334753
  return __awaiter(this, void 0, void 0, function* () {
334754
+ // 配置文件路径不存在
334697
334755
  if (!this.configPath) {
334756
+ // 搜索配置,获取配置目录
334698
334757
  const result = yield (0, cosmiconfig_1.searchConfig)(this.cwd);
334758
+ // 设置 config 路径
334699
334759
  this.configPath = result === null || result === void 0 ? void 0 : result.filepath;
334700
334760
  }
334761
+ // 读取原配置
334701
334762
  const rawConfig = yield resolveCloudBaseConfig({
334702
334763
  configPath: this.configPath
334703
334764
  });
334704
334765
  return ConfigParser.parseRawConfig(rawConfig, this.cwd);
334705
334766
  });
334706
334767
  }
334768
+ // 写配置
334707
334769
  updateConfig(config, cover = this.cover) {
334708
334770
  return __awaiter(this, void 0, void 0, function* () {
334771
+ // 配置文件路径不存在
334709
334772
  if (!this.configPath) {
334773
+ // 搜索配置,获取配置目录
334710
334774
  const result = yield (0, cosmiconfig_1.searchConfig)(this.cwd);
334775
+ // 设置 config 路径,config 可能不存在
334711
334776
  this.configPath = result === null || result === void 0 ? void 0 : result.filepath;
334712
334777
  }
334778
+ // 原配置
334713
334779
  const baseConfig = yield (0, cosmiconfig_1.loadConfig)({
334714
334780
  searchFrom: this.cwd,
334715
334781
  configPath: this.configPath
@@ -334717,14 +334783,17 @@ class ConfigParser {
334717
334783
  const unionConfig = cover
334718
334784
  ? Object.assign(Object.assign({}, baseConfig), config) : Object.assign(Object.assign({}, config), baseConfig);
334719
334785
  let indent = 2;
334786
+ // 文件存在,检测文件缩进
334720
334787
  if (this.configPath) {
334721
334788
  const fileContent = yield fs_1.default.promises.readFile(this.configPath);
334722
334789
  const detectRet = (0, detect_indent_1.detectIndent)(fileContent === null || fileContent === void 0 ? void 0 : fileContent.toString());
334723
334790
  indent = (detectRet === null || detectRet === void 0 ? void 0 : detectRet.amount) || indent;
334724
334791
  }
334725
334792
  else {
334793
+ // 配置文件可能不存在,设置配置文件路径,直接写内容
334726
334794
  this.configPath = path_1.default.join(this.cwd, 'cloudbaserc.json');
334727
334795
  }
334796
+ // 写入配置到 json 文件中
334728
334797
  jsonfile_1.default.writeFileSync(this.configPath, unionConfig, { spaces: indent });
334729
334798
  });
334730
334799
  }
@@ -378040,11 +378109,17 @@ function indexOf(xs, x) {
378040
378109
 
378041
378110
  Object.defineProperty(exports, "__esModule", ({ value: true }));
378042
378111
  exports.getPropertyByPath = void 0;
378112
+ // Resolves property names or property paths defined with period-delimited
378113
+ // strings or arrays of strings. Property names that are found on the source
378114
+ // object are used directly (even if they include a period).
378115
+ // Nested property names that include periods, within a path, are only
378116
+ // understood in array paths.
378043
378117
  function getPropertyByPath(source, path) {
378044
378118
  if (typeof path === 'string' && Object.prototype.hasOwnProperty.call(source, path)) {
378045
378119
  return source[path];
378046
378120
  }
378047
378121
  const parsedPath = typeof path === 'string' ? path.split('.') : path;
378122
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
378048
378123
  return parsedPath.reduce((previous, key) => {
378049
378124
  if (previous === undefined) {
378050
378125
  return previous;
@@ -383915,7 +383990,6 @@ __exportStar(__webpack_require__(87531), exports);
383915
383990
  __exportStar(__webpack_require__(5476), exports);
383916
383991
  __exportStar(__webpack_require__(74371), exports);
383917
383992
  __exportStar(__webpack_require__(37210), exports);
383918
- __exportStar(__webpack_require__(64180), exports);
383919
383993
  __exportStar(__webpack_require__(22700), exports);
383920
383994
  __exportStar(__webpack_require__(32428), exports);
383921
383995
  __exportStar(__webpack_require__(29561), exports);
@@ -398236,7 +398310,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge
398236
398310
  });
398237
398311
  };
398238
398312
  Object.defineProperty(exports, "__esModule", ({ value: true }));
398239
- exports.AuthSupevisor = void 0;
398313
+ exports.AuthSupevisor = exports.AuthSupervisor = void 0;
398240
398314
  const web_auth_1 = __webpack_require__(76097);
398241
398315
  const common_1 = __webpack_require__(96711);
398242
398316
  const credential_1 = __webpack_require__(99795);
@@ -398244,13 +398318,17 @@ const error_1 = __webpack_require__(64119);
398244
398318
  __exportStar(__webpack_require__(96711), exports);
398245
398319
  __exportStar(__webpack_require__(99795), exports);
398246
398320
  __exportStar(__webpack_require__(76097), exports);
398247
- class AuthSupevisor {
398321
+ class AuthSupervisor {
398322
+ /**
398323
+ * 单例模式,全局缓存
398324
+ * @param options
398325
+ */
398248
398326
  static getInstance(options = {}) {
398249
- if (AuthSupevisor.instance) {
398250
- return AuthSupevisor.instance;
398327
+ if (AuthSupervisor.instance) {
398328
+ return AuthSupervisor.instance;
398251
398329
  }
398252
- const instance = new AuthSupevisor(options);
398253
- AuthSupevisor.instance = instance;
398330
+ const instance = new AuthSupervisor(options);
398331
+ AuthSupervisor.instance = instance;
398254
398332
  return instance;
398255
398333
  }
398256
398334
  constructor(options = {}) {
@@ -398263,11 +398341,15 @@ class AuthSupevisor {
398263
398341
  this.cacheExpiredTime = 0;
398264
398342
  this.throwError = throwError;
398265
398343
  }
398344
+ /**
398345
+ * 获取登录状态信息
398346
+ */
398266
398347
  getLoginState() {
398267
398348
  return __awaiter(this, void 0, void 0, function* () {
398268
398349
  if (this.cacheCredential && this.needCache && !this.isCacheExpire()) {
398269
398350
  return this.cacheCredential;
398270
398351
  }
398352
+ // 获取本地登录状态
398271
398353
  const credential = yield (0, credential_1.checkAndGetCredential)(this.requestConfig);
398272
398354
  if (this.needCache && credential) {
398273
398355
  this.cacheCredential = credential;
@@ -398279,17 +398361,25 @@ class AuthSupevisor {
398279
398361
  return credential;
398280
398362
  });
398281
398363
  }
398364
+ /**
398365
+ * 通过网页授权登录
398366
+ * @returns credential
398367
+ */
398282
398368
  loginByWebAuth(options = {}) {
398283
398369
  return __awaiter(this, void 0, void 0, function* () {
398284
- const { getAuthUrl, throwError } = options;
398370
+ const { getAuthUrl, throwError, noBrowser, callbackTimeout } = options;
398285
398371
  if (this.cacheCredential && this.needCache && !this.isCacheExpire()) {
398286
398372
  return this.cacheCredential;
398287
398373
  }
398374
+ // 校验本地秘钥
398288
398375
  let credential = yield (0, credential_1.checkAndGetCredential)(this.requestConfig);
398289
398376
  if (credential)
398290
398377
  return credential;
398378
+ // 兼容临时秘钥
398291
398379
  credential = yield (0, web_auth_1.getAuthTokenFromWeb)({
398292
- getAuthUrl
398380
+ getAuthUrl,
398381
+ noBrowser,
398382
+ callbackTimeout
398293
398383
  });
398294
398384
  try {
398295
398385
  yield (0, common_1.checkAuth)(credential, this.requestConfig);
@@ -398300,8 +398390,10 @@ class AuthSupevisor {
398300
398390
  }
398301
398391
  return null;
398302
398392
  }
398393
+ // 通过 Web 登录时,本地要存储 tmpSecretId 形式,方式 CLI 登录失效
398303
398394
  const webCredential = (0, common_1.resolveWebCredential)(credential);
398304
398395
  yield credential_1.authStore.set('credential', webCredential);
398396
+ // 缓存处理转换后的 credential
398305
398397
  if (this.needCache && credential) {
398306
398398
  this.cacheCredential = credential;
398307
398399
  const { accessTokenExpired } = credential;
@@ -398312,26 +398404,41 @@ class AuthSupevisor {
398312
398404
  return credential;
398313
398405
  });
398314
398406
  }
398315
- loginByApiSecret(secretId, secretKey, token) {
398407
+ /**
398408
+ * 通过 API Secret 登录,支持临时秘钥
398409
+ * @param secretId
398410
+ * @param secretKey
398411
+ * @param token
398412
+ * @param opts 选项配置,包括强制更新和额外的 Credential 字段
398413
+ * @returns credential
398414
+ */
398415
+ // eslint-disable-next-line max-params
398416
+ loginByApiSecret(secretId, secretKey, token, opts) {
398316
398417
  return __awaiter(this, void 0, void 0, function* () {
398317
- if (this.cacheCredential && this.needCache && !this.isCacheExpire()) {
398418
+ const { forceUpdate = false, storeAsWebCredential = false, additionalCredentialFields } = opts || {};
398419
+ if (this.cacheCredential && this.needCache && !this.isCacheExpire() && !forceUpdate) {
398318
398420
  return this.cacheCredential;
398319
398421
  }
398320
- let credential = yield (0, credential_1.checkAndGetCredential)(this.requestConfig);
398321
- if (credential)
398322
- return credential;
398422
+ // 校验本地秘钥(如果不是强制更新)
398423
+ if (!forceUpdate) {
398424
+ let credential = yield (0, credential_1.checkAndGetCredential)(this.requestConfig);
398425
+ if (credential)
398426
+ return credential;
398427
+ }
398428
+ // 当本地身份信息不存在时,才使用传入参数进行校验
398323
398429
  if (!secretId || !secretKey) {
398324
398430
  throw new error_1.CloudBaseError('secretId 或 secretKey 不能为空');
398325
398431
  }
398326
- credential = {
398327
- secretId,
398432
+ const credential = Object.assign(Object.assign({}, additionalCredentialFields), { secretId,
398328
398433
  secretKey,
398329
- token
398330
- };
398434
+ token });
398331
398435
  try {
398332
398436
  yield (0, common_1.checkAuth)(credential, this.requestConfig);
398333
398437
  }
398334
398438
  catch (e) {
398439
+ // CAM 错误视为登录正常
398440
+ // if (isCamRefused(e)) return credential;
398441
+ // 请求超时
398335
398442
  if (e.type === 'request-timeout') {
398336
398443
  throw new error_1.CloudBaseError('请求超时,请检查你的网络,如果终端无法直接访问公网,请设置终端 HTTP 请求代理!');
398337
398444
  }
@@ -398340,7 +398447,12 @@ class AuthSupevisor {
398340
398447
  }
398341
398448
  return null;
398342
398449
  }
398343
- yield credential_1.authStore.set('credential', credential);
398450
+ // 根据选项决定存储格式
398451
+ const credentialToStore = storeAsWebCredential
398452
+ ? (0, common_1.resolveWebCredential)(credential)
398453
+ : credential;
398454
+ // 存储信息
398455
+ yield credential_1.authStore.set('credential', credentialToStore);
398344
398456
  if (this.needCache && credential) {
398345
398457
  this.cacheCredential = credential;
398346
398458
  this.cacheExpiredTime = Date.now() + 3600 * 1000;
@@ -398353,10 +398465,11 @@ class AuthSupevisor {
398353
398465
  if (this.cacheCredential) {
398354
398466
  this.cacheCredential = null;
398355
398467
  }
398356
- const credentail = yield (0, credential_1.getCredentialWithoutCheck)();
398468
+ const credential = yield (0, credential_1.getCredentialWithoutCheck)();
398357
398469
  try {
398358
- if (credentail === null || credentail === void 0 ? void 0 : credentail.refreshToken) {
398359
- yield (0, credential_1.refreshTmpToken)(Object.assign(Object.assign({}, credentail), { isLogout: true }));
398470
+ // 仅使用 Web 控制台授权登录时才删除 token
398471
+ if (credential === null || credential === void 0 ? void 0 : credential.refreshToken) {
398472
+ yield (0, credential_1.refreshTmpToken)(Object.assign(Object.assign({}, credential), { isLogout: true }));
398360
398473
  }
398361
398474
  yield credential_1.authStore.delete('credential');
398362
398475
  }
@@ -398371,6 +398484,29 @@ class AuthSupevisor {
398371
398484
  return now >= this.cacheExpiredTime;
398372
398485
  }
398373
398486
  }
398487
+ exports.AuthSupervisor = AuthSupervisor;
398488
+ /**
398489
+ * @deprecated Use `AuthSupervisor` instead. This class has a spelling error and will be removed in a future version.
398490
+ */
398491
+ class AuthSupevisor extends AuthSupervisor {
398492
+ /**
398493
+ * @deprecated Use `AuthSupervisor.getInstance` instead
398494
+ */
398495
+ static getInstance(options = {}) {
398496
+ if (AuthSupevisor.instance) {
398497
+ return AuthSupevisor.instance;
398498
+ }
398499
+ const instance = new AuthSupevisor(options);
398500
+ AuthSupevisor.instance = instance;
398501
+ return instance;
398502
+ }
398503
+ /**
398504
+ * @deprecated Use `AuthSupervisor` constructor instead
398505
+ */
398506
+ constructor(options = {}) {
398507
+ super(options);
398508
+ }
398509
+ }
398374
398510
  exports.AuthSupevisor = AuthSupevisor;
398375
398511
 
398376
398512
 
@@ -410150,11 +410286,14 @@ const http_1 = __importDefault(__webpack_require__(58611));
410150
410286
  const system_1 = __webpack_require__(62179);
410151
410287
  const error_1 = __webpack_require__(64119);
410152
410288
  const html_1 = __webpack_require__(74856);
410289
+ const child_process_1 = __webpack_require__(35317);
410290
+ // 创建本地 Web 服务器,接受 Web 控制台传入的信息
410153
410291
  function createLocalServer() {
410154
410292
  return __awaiter(this, void 0, void 0, function* () {
410155
410293
  const server = http_1.default.createServer();
410156
410294
  const port = yield (0, system_1.getPort)();
410157
410295
  return new Promise((resolve, reject) => {
410296
+ // 服务启动异常
410158
410297
  server.on('error', (e) => {
410159
410298
  reject(e);
410160
410299
  });
@@ -410167,6 +410306,7 @@ function createLocalServer() {
410167
410306
  });
410168
410307
  });
410169
410308
  }
410309
+ // 返回 HTML 响应
410170
410310
  function respondWithFile(options) {
410171
410311
  const { req, res, statusCode, filename } = options;
410172
410312
  return new Promise(function (resolve) {
@@ -410180,20 +410320,98 @@ function respondWithFile(options) {
410180
410320
  resolve();
410181
410321
  });
410182
410322
  }
410183
- function getDataFromWeb(getUrl, type) {
410323
+ function isTruthyFlag(value) {
410324
+ if (!value) {
410325
+ return false;
410326
+ }
410327
+ return ['1', 'true', 'yes', 'on'].includes(String(value).trim().toLowerCase());
410328
+ }
410329
+ function isVSCodeEnvironment() {
410330
+ return !!(process.env.VSCODE_PID || process.env.VSCODE_CWD || process.env.TERM_PROGRAM === 'vscode');
410331
+ }
410332
+ function openUrlByVSCode(url) {
410333
+ return __awaiter(this, void 0, void 0, function* () {
410334
+ return new Promise((resolve, reject) => {
410335
+ (0, child_process_1.execFile)('code', ['--open-url', url], (error) => {
410336
+ if (error) {
410337
+ reject(error);
410338
+ return;
410339
+ }
410340
+ resolve();
410341
+ });
410342
+ });
410343
+ });
410344
+ }
410345
+ function hasSystemBrowserOpener() {
410346
+ return __awaiter(this, void 0, void 0, function* () {
410347
+ if (process.platform !== 'linux') {
410348
+ return true;
410349
+ }
410350
+ return new Promise((resolve) => {
410351
+ (0, child_process_1.execFile)('which', ['xdg-open'], (error) => {
410352
+ resolve(!error);
410353
+ });
410354
+ });
410355
+ });
410356
+ }
410357
+ // 从 Web 页面中获取数据
410358
+ function getDataFromWeb(getUrl, type, options = {}) {
410359
+ var _a, _b;
410184
410360
  return __awaiter(this, void 0, void 0, function* () {
410185
410361
  const { server, port } = yield createLocalServer();
410186
- const url = getUrl(port);
410187
- try {
410188
- yield (0, open_1.default)(url, { url: true });
410362
+ const noBrowser = (_a = options.noBrowser) !== null && _a !== void 0 ? _a : isTruthyFlag(process.env.TCB_NO_BROWSER);
410363
+ const callbackTimeout = (_b = options.callbackTimeout) !== null && _b !== void 0 ? _b : 180000;
410364
+ if (!Number.isFinite(callbackTimeout) || callbackTimeout <= 0) {
410365
+ throw new error_1.CloudBaseError('callbackTimeout must be a positive number');
410189
410366
  }
410190
- catch (e) {
410191
- throw new error_1.CloudBaseError('打开浏览器失败,请尝试使用其他登录方式');
410367
+ const url = getUrl(port);
410368
+ console.log('\n\n若链接未自动打开,请手动复制此链接至浏览器,或尝试使用其他登录方式:');
410369
+ console.log(`\n${url}`);
410370
+ if (!noBrowser) {
410371
+ const hasOpener = yield hasSystemBrowserOpener();
410372
+ if (hasOpener) {
410373
+ // 对 url 转码, 避免 wsl 无法正常打开地址
410374
+ // https://www.npmjs.com/package/open#url
410375
+ // https://github.com/sindresorhus/open/blob/master/index.js#L48
410376
+ try {
410377
+ yield (0, open_1.default)(url, { url: true });
410378
+ }
410379
+ catch (e) {
410380
+ const code = (e === null || e === void 0 ? void 0 : e.code) || 'UNKNOWN';
410381
+ console.warn(`自动打开浏览器失败(${code})。`);
410382
+ }
410383
+ }
410384
+ if (isVSCodeEnvironment()) {
410385
+ try {
410386
+ yield openUrlByVSCode(url);
410387
+ }
410388
+ catch (vscodeError) {
410389
+ // ignore error
410390
+ }
410391
+ }
410192
410392
  }
410193
410393
  return new Promise((resolve, reject) => {
410394
+ let finished = false;
410395
+ const timer = setTimeout(() => {
410396
+ if (finished) {
410397
+ return;
410398
+ }
410399
+ finished = true;
410400
+ server.close();
410401
+ reject(new error_1.CloudBaseError(`等待浏览器授权回调超时(${Math.floor(callbackTimeout / 1000)}s)!`));
410402
+ }, callbackTimeout);
410403
+ const finish = (fn) => {
410404
+ if (finished) {
410405
+ return;
410406
+ }
410407
+ finished = true;
410408
+ clearTimeout(timer);
410409
+ fn();
410410
+ };
410194
410411
  server.on('request', (req, res) => {
410195
- const { url } = req;
410412
+ const url = req.url || '/';
410196
410413
  const { query } = query_string_1.default.parseUrl(url);
410414
+ // 响应 HTML 文件
410197
410415
  if (query === null || query === void 0 ? void 0 : query.html) {
410198
410416
  return respondWithFile({
410199
410417
  req,
@@ -410201,25 +410419,33 @@ function getDataFromWeb(getUrl, type) {
410201
410419
  statusCode: 200,
410202
410420
  filename: `${type}Success`
410203
410421
  }).then(() => {
410204
- server.close();
410205
- resolve(query);
410422
+ finish(() => {
410423
+ server.close();
410424
+ resolve(query);
410425
+ });
410206
410426
  }).catch((e) => {
410207
- server.close();
410208
- reject(e);
410427
+ finish(() => {
410428
+ server.close();
410429
+ reject(e);
410430
+ });
410209
410431
  });
410210
410432
  }
410433
+ // CORS 响应普通文本
410211
410434
  res.writeHead(200, {
410212
410435
  'Access-Control-Allow-Origin': '*',
410213
410436
  'Access-Control-Allow-Methods': '*',
410214
410437
  'Access-Control-Allow-Headers': '*',
410215
410438
  'Content-Type': 'text/plain',
410439
+ // 立即关闭 http 连接
410216
410440
  Connection: 'close'
410217
410441
  });
410218
410442
  res.end();
410219
410443
  if (req.method !== 'OPTIONS') {
410220
410444
  server.close();
410221
410445
  }
410222
- resolve(query);
410446
+ finish(() => {
410447
+ resolve(query);
410448
+ });
410223
410449
  });
410224
410450
  });
410225
410451
  });
@@ -442282,6 +442508,7 @@ __exportStar(__webpack_require__(31153), exports);
442282
442508
  __exportStar(__webpack_require__(33283), exports);
442283
442509
  __exportStar(__webpack_require__(79998), exports);
442284
442510
  __exportStar(__webpack_require__(19835), exports);
442511
+ // export types
442285
442512
  __exportStar(__webpack_require__(42612), exports);
442286
442513
 
442287
442514
 
@@ -450306,6 +450533,7 @@ const cloud_api_1 = __webpack_require__(2090);
450306
450533
  const constant_1 = __webpack_require__(53393);
450307
450534
  let commonCredential;
450308
450535
  class CloudApiService {
450536
+ // 单例模式
450309
450537
  static getInstance(service) {
450310
450538
  var _a;
450311
450539
  if ((_a = CloudApiService.serviceCacheMap) === null || _a === void 0 ? void 0 : _a[service]) {
@@ -450316,6 +450544,7 @@ class CloudApiService {
450316
450544
  return apiService;
450317
450545
  }
450318
450546
  constructor(service, baseParams, version = '') {
450547
+ // 初始化 API 实例
450319
450548
  this.apiService = new cloud_api_1.CloudApiService({
450320
450549
  service,
450321
450550
  version,
@@ -450344,6 +450573,7 @@ class CloudApiService {
450344
450573
  }
450345
450574
  }
450346
450575
  exports.CloudApiService = CloudApiService;
450576
+ // 缓存请求实例
450347
450577
  CloudApiService.serviceCacheMap = {};
450348
450578
 
450349
450579
 
@@ -468485,8 +468715,16 @@ const archiver_1 = __importDefault(__webpack_require__(30989));
468485
468715
  exports.decompress = decompress_1.default;
468486
468716
  const unzip = (zipFile, dest) => (0, exports.decompress)(zipFile, dest);
468487
468717
  exports.unzip = unzip;
468718
+ /**
468719
+ * 解压流(使用临时 zip 包)
468720
+ * @param source 可读流
468721
+ * @param dest 解压目标文件夹
468722
+ * @param name 可选的临时 zip 包名
468723
+ */
468488
468724
  const unzipStream = (source, dest, name = 'gape3il5rk8.zip') => __awaiter(void 0, void 0, void 0, function* () {
468725
+ // 确保文件夹存在
468489
468726
  yield (0, fs_2.mkdirAsync)(dest);
468727
+ // 使用一个临时文件下载 zip 包
468490
468728
  const zipPath = path_1.default.join(dest, `${name}.zip`);
468491
468729
  const zip = fs_1.default.createWriteStream(zipPath);
468492
468730
  source.pipe(zip);
@@ -468529,13 +468767,16 @@ function zipFiles(allFilesPath, outputPath, ignore) {
468529
468767
  archive.pipe(output);
468530
468768
  allFilesPath.forEach(filePath => {
468531
468769
  if (fs_1.default.statSync(filePath).isDirectory()) {
468770
+ // append files from a glob pattern
468532
468771
  archive.glob('**/*', {
468772
+ // 目标路径
468533
468773
  cwd: filePath,
468534
468774
  ignore: ignore,
468535
468775
  dot: true
468536
468776
  });
468537
468777
  }
468538
468778
  else {
468779
+ // append file
468539
468780
  archive.file(filePath);
468540
468781
  }
468541
468782
  });
@@ -482194,7 +482435,11 @@ module.exports = arrayMap;
482194
482435
  Object.defineProperty(exports, "__esModule", ({ value: true }));
482195
482436
  exports.AsyncMerge = void 0;
482196
482437
  const cache_1 = __webpack_require__(51995);
482438
+ // 使用 Symbol 值,判断缓存结果时,可以准确判断是否为 Error 类型
482197
482439
  const ERROR_KEY = Symbol('ERROR_KEY');
482440
+ /**
482441
+ * 异步任务合并
482442
+ */
482198
482443
  class AsyncMerge {
482199
482444
  constructor() {
482200
482445
  this.tasks = {};
@@ -482208,7 +482453,10 @@ class AsyncMerge {
482208
482453
  throw new Error('AsyncMerge taskId could not be empty, it will cause unexpected result!');
482209
482454
  }
482210
482455
  return new Promise((resolve, reject) => {
482456
+ // 取缓存
482211
482457
  const cacheRet = cache_1.nilCache.get(taskId);
482458
+ // 校验缓存,缓存结果可能为 null, undefined 等空值
482459
+ // 使用 Symbol 值做判断
482212
482460
  if (maxAge > 0 && cacheRet !== cache_1.Cache.NIL) {
482213
482461
  const e = cacheRet[ERROR_KEY];
482214
482462
  if (e) {
@@ -482230,6 +482478,7 @@ class AsyncMerge {
482230
482478
  }
482231
482479
  });
482232
482480
  }
482481
+ // eslint-disable-next-line
482233
482482
  runTask(fn, taskId, taskOptions, cb) {
482234
482483
  const { tasks } = this;
482235
482484
  const { maxAge = 0, timeout = 60000 } = taskOptions;
@@ -482241,15 +482490,18 @@ class AsyncMerge {
482241
482490
  }
482242
482491
  tasks[taskId].callbacks.push(cb);
482243
482492
  const task = tasks[taskId];
482493
+ // 当前类型的任务没有运行
482244
482494
  if (!task.lock) {
482245
482495
  let timerId = null;
482246
482496
  if (timeout) {
482247
482497
  timerId = setTimeout(() => {
482498
+ // 超时回调
482248
482499
  task.callbacks.forEach((cb) => cb(new Error('TASK_TIMEOUT')));
482249
482500
  task.lock = false;
482250
482501
  delete tasks[taskId];
482251
482502
  }, timeout);
482252
482503
  }
482504
+ // 上锁,标志任务处理开始
482253
482505
  task.lock = true;
482254
482506
  fn()
482255
482507
  .then((res) => {
@@ -482263,6 +482515,7 @@ class AsyncMerge {
482263
482515
  clearTimeout(timerId);
482264
482516
  task.lock = false;
482265
482517
  delete tasks[taskId];
482518
+ // 任务异常,缓存异常值
482266
482519
  maxAge > 0 && cache_1.nilCache.set(taskId, { ERROR_KEY: e }, maxAge);
482267
482520
  task.callbacks.forEach((cb) => cb(e));
482268
482521
  });
@@ -493662,10 +493915,6 @@ let ConfigUpdate = class ConfigUpdate extends common_1.Command {
493662
493915
  {
493663
493916
  flags: '-e, --envId <envId>',
493664
493917
  desc: (0, i18n_1.t)('环境 Id')
493665
- },
493666
- {
493667
- flags: '--yes',
493668
- desc: (0, i18n_1.t)('跳过交互确认,使用默认选项自动执行')
493669
493918
  }
493670
493919
  ],
493671
493920
  desc: (0, i18n_1.t)('更新云函数配置'),
@@ -493675,35 +493924,26 @@ let ConfigUpdate = class ConfigUpdate extends common_1.Command {
493675
493924
  }
493676
493925
  execute(ctx, params, log) {
493677
493926
  return __awaiter(this, void 0, void 0, function* () {
493678
- let { envId, config: { functions }, options } = ctx;
493927
+ let { envId, config: { functions } } = ctx;
493679
493928
  const name = params === null || params === void 0 ? void 0 : params[0];
493680
- const { yes } = options;
493681
493929
  let isBathUpdate = false;
493682
493930
  if (!envId) {
493683
493931
  envId = yield (0, utils_1.selectEnv)({ envTypes: [constant_1.EnvType.BAAS, constant_1.EnvType.WEDA] });
493684
493932
  }
493685
493933
  if (!name) {
493686
- if (yes) {
493687
- log.info((0, i18n_1.t)('🚀 --yes 模式:自动更新配置文件中的全部云函数配置'));
493688
- isBathUpdate = true;
493689
- }
493690
- else {
493691
- const { isBatch } = yield inquirer_1.default.prompt({
493692
- type: 'confirm',
493693
- name: 'isBatch',
493694
- message: (0, i18n_1.t)('无云函数名称,是否需要更新配置文件中的【全部云函数】的配置?'),
493695
- default: false
493696
- });
493697
- isBathUpdate = isBatch;
493698
- }
493934
+ const { isBatch } = yield inquirer_1.default.prompt({
493935
+ type: 'confirm',
493936
+ name: 'isBatch',
493937
+ message: (0, i18n_1.t)('无云函数名称,是否需要更新配置文件中的【全部云函数】的配置?'),
493938
+ default: false
493939
+ });
493940
+ isBathUpdate = isBatch;
493699
493941
  if (!isBathUpdate) {
493700
493942
  throw new error_1.CloudBaseError((0, i18n_1.t)('请指定云函数名称!'));
493701
493943
  }
493702
493944
  }
493703
493945
  if (isBathUpdate) {
493704
- const envVarUpdateMode = hasEnvVariablesConfig(functions)
493705
- ? (yes ? 'overwrite' : yield askEnvVarUpdateMode())
493706
- : undefined;
493946
+ const envVarUpdateMode = hasEnvVariablesConfig(functions) ? yield askEnvVarUpdateMode() : undefined;
493707
493947
  for (const func of functions) {
493708
493948
  const isValid = yield validateFunctionTypeChange(envId, func, log);
493709
493949
  if (!isValid) {
@@ -493727,9 +493967,7 @@ let ConfigUpdate = class ConfigUpdate extends common_1.Command {
493727
493967
  if (!isValid) {
493728
493968
  return;
493729
493969
  }
493730
- const envVarUpdateMode = hasEnvVariablesConfig([functionItem])
493731
- ? (yes ? 'overwrite' : yield askEnvVarUpdateMode())
493732
- : undefined;
493970
+ const envVarUpdateMode = hasEnvVariablesConfig([functionItem]) ? yield askEnvVarUpdateMode() : undefined;
493733
493971
  yield (0, function_1.updateFunctionConfig)({
493734
493972
  envId,
493735
493973
  functionName: name,
@@ -511087,6 +511325,7 @@ Object.defineProperty(exports, "__esModule", ({ value: true }));
511087
511325
  exports.md5Encoding = void 0;
511088
511326
  const crypto_1 = __importDefault(__webpack_require__(76982));
511089
511327
  const error_1 = __webpack_require__(64119);
511328
+ // MD5
511090
511329
  function md5Encoding(str = '') {
511091
511330
  if (typeof str !== 'string')
511092
511331
  throw new error_1.CloudBaseError('参数必须为字符串!');
@@ -512587,9 +512826,13 @@ const FileAsync_1 = __importDefault(__webpack_require__(19778));
512587
512826
  const FileSync_1 = __importDefault(__webpack_require__(29303));
512588
512827
  const fs_1 = __webpack_require__(96185);
512589
512828
  const homeDir = os_1.default.homedir();
512829
+ // 系统配置目录
512590
512830
  const homeAccessible = (0, fs_1.checkFullAccess)(homeDir);
512831
+ // 仅当 home 目录可访问时,才使用 home 目录,否则使用临时目录
512591
512832
  const configDir = homeDir && homeAccessible ? path_1.default.join(homeDir, '.config') : path_1.default.join(os_1.default.tmpdir(), '.config');
512833
+ // cloudbase 配置目录
512592
512834
  exports.cloudbaseConfigDir = path_1.default.join(configDir, '.cloudbase');
512835
+ // 确保目录存在
512593
512836
  make_dir_1.default.sync(exports.cloudbaseConfigDir);
512594
512837
  function getAsyncDB(file) {
512595
512838
  const dbPath = path_1.default.join(exports.cloudbaseConfigDir, `${file}.json`);
@@ -517404,9 +517647,11 @@ function handleTimeout(e) {
517404
517647
  throw new error_1.CloudBaseError('请求超时,请检查你的网络,如果终端无法直接访问公网,请设置终端 HTTP 请求代理!');
517405
517648
  }
517406
517649
  else {
517650
+ // 其他错误,抛出
517407
517651
  throw e;
517408
517652
  }
517409
517653
  }
517654
+ // 使用 fetch + 代理
517410
517655
  function fetch(url, config = {}) {
517411
517656
  return __awaiter(this, void 0, void 0, function* () {
517412
517657
  const proxy = (0, system_1.getProxy)();
@@ -517429,6 +517674,7 @@ function fetch(url, config = {}) {
517429
517674
  });
517430
517675
  }
517431
517676
  exports.fetch = fetch;
517677
+ // 使用 fetch + 代理
517432
517678
  function postFetch(url, data) {
517433
517679
  return __awaiter(this, void 0, void 0, function* () {
517434
517680
  const proxy = (0, system_1.getProxy)();
@@ -517475,6 +517721,7 @@ function fetchStream(url, config = {}) {
517475
517721
  });
517476
517722
  }
517477
517723
  exports.fetchStream = fetchStream;
517724
+ // 使用 fetch + 代理
517478
517725
  function putFetch(url, config = {}) {
517479
517726
  return __awaiter(this, void 0, void 0, function* () {
517480
517727
  const proxy = (0, system_1.getProxy)();
@@ -547181,6 +547428,9 @@ exports.getRegion = exports.getCloudBaseConfig = void 0;
547181
547428
  const yargs_1 = __importDefault(__webpack_require__(72841));
547182
547429
  const path_1 = __importDefault(__webpack_require__(16928));
547183
547430
  const cloudbase_1 = __webpack_require__(10304);
547431
+ /**
547432
+ * 获取当前目录下的 cloudbase 配置
547433
+ */
547184
547434
  const getCloudBaseConfig = (configPath) => __awaiter(void 0, void 0, void 0, function* () {
547185
547435
  let specificConfigPath = configPath || yargs_1.default.argv['config-path'];
547186
547436
  specificConfigPath = specificConfigPath ? path_1.default.resolve(specificConfigPath) : undefined;
@@ -547191,7 +547441,11 @@ const getCloudBaseConfig = (configPath) => __awaiter(void 0, void 0, void 0, fun
547191
547441
  return config;
547192
547442
  });
547193
547443
  exports.getCloudBaseConfig = getCloudBaseConfig;
547444
+ /**
547445
+ * 从命令行参数和配置文件中读取 region
547446
+ */
547194
547447
  const getRegion = (noDefault = false) => __awaiter(void 0, void 0, void 0, function* () {
547448
+ // region 缩写
547195
547449
  const regionMap = {
547196
547450
  gz: 'ap-guangzhou',
547197
547451
  bj: 'ap-beijing',
@@ -547200,16 +547454,19 @@ const getRegion = (noDefault = false) => __awaiter(void 0, void 0, void 0, funct
547200
547454
  cd: 'ap-chengdu',
547201
547455
  cq: 'ap-chongqing'
547202
547456
  };
547457
+ // 命令行中指定的 region
547203
547458
  const argvRegion = (yargs_1.default.argv.r || yargs_1.default.argv.region);
547204
547459
  if (argvRegion && regionMap[argvRegion]) {
547205
547460
  return regionMap[argvRegion];
547206
547461
  }
547207
547462
  if (argvRegion)
547208
547463
  return argvRegion;
547464
+ // 配置文件中的 region
547209
547465
  const config = yield (0, exports.getCloudBaseConfig)();
547210
547466
  if ((config === null || config === void 0 ? void 0 : config.region) && regionMap[config === null || config === void 0 ? void 0 : config.region]) {
547211
547467
  return regionMap[config.region];
547212
547468
  }
547469
+ // 不使用默认值时,不会默认返回 region
547213
547470
  return noDefault ? config === null || config === void 0 ? void 0 : config.region : (config === null || config === void 0 ? void 0 : config.region) || 'ap-shanghai';
547214
547471
  });
547215
547472
  exports.getRegion = getRegion;
@@ -575740,6 +575997,10 @@ Object.defineProperty(exports, "__esModule", ({ value: true }));
575740
575997
  exports.getOSInfo = exports.getPlatformRelease = void 0;
575741
575998
  const os_1 = __importDefault(__webpack_require__(70857));
575742
575999
  const macOSMap = new Map([
576000
+ [24, 'Sequoia'],
576001
+ [23, 'Sonoma'],
576002
+ [22, 'Ventura'],
576003
+ [21, 'Monterey'],
575743
576004
  [20, 'BigSur'],
575744
576005
  [19, 'Catalina'],
575745
576006
  [18, 'Mojave'],
@@ -575755,9 +576016,19 @@ const macOSMap = new Map([
575755
576016
  [8, 'Tiger'],
575756
576017
  [7, 'Panther'],
575757
576018
  [6, 'Jaguar'],
575758
- [5, 'Puma']
576019
+ [5, 'Puma'] // macOS 10.1 Puma (2001)
575759
576020
  ]);
575760
576021
  const winMap = new Map([
576022
+ ['10.0.22000', '11'],
576023
+ ['10.0.19041', '10'],
576024
+ ['10.0.18363', '10'],
576025
+ ['10.0.17763', '10'],
576026
+ ['10.0.17134', '10'],
576027
+ ['10.0.16299', '10'],
576028
+ ['10.0.15063', '10'],
576029
+ ['10.0.14393', '10'],
576030
+ ['10.0.10586', '10'],
576031
+ ['10.0.10240', '10'],
575761
576032
  ['10.0', '10'],
575762
576033
  ['6.3', '8.1'],
575763
576034
  ['6.2', '8'],
@@ -575768,28 +576039,55 @@ const winMap = new Map([
575768
576039
  ['5.0', '2000'],
575769
576040
  ['4.9', 'ME'],
575770
576041
  ['4.1', '98'],
575771
- ['4.0', '95']
576042
+ ['4.0', '95'] // Windows 95 (1995)
575772
576043
  ]);
575773
576044
  function getPlatformRelease(platform, release) {
576045
+ // macOS
575774
576046
  if (platform === 'darwin') {
575775
- const releaseNum = Number(release.split('.')[0]);
575776
- const name = macOSMap.get(releaseNum);
576047
+ const releaseParts = release.split('.');
576048
+ const majorNum = Number(releaseParts[0]);
576049
+ const minorNum = Number(releaseParts[1]) || 0;
576050
+ const name = macOSMap.get(majorNum) || 'macOS';
575777
576051
  let version;
575778
- if (releaseNum >= 20) {
575779
- version = '11.' + (releaseNum - 20);
576052
+ // macOS 11 及以上版本 (majorNum >= 20)
576053
+ if (majorNum >= 20) {
576054
+ // releaseNum 20 -> macOS 11, 21 -> macOS 12, etc.
576055
+ const majorVersion = majorNum - 9;
576056
+ version = `${majorVersion}.${minorNum}`;
576057
+ // macOS 10.x 版本 (majorNum < 20)
575780
576058
  }
575781
576059
  else {
575782
- version = '10.' + (releaseNum - 4);
576060
+ // releaseNum 19 -> 10.15, 18 -> 10.14, etc.
576061
+ const minorVersion = majorNum - 4;
576062
+ version = `10.${minorVersion}`;
575783
576063
  }
575784
576064
  return `${name} ${version}`;
575785
576065
  }
576066
+ // windows
575786
576067
  if (platform === 'win32') {
575787
- const version = (/\d+\.\d/.exec(release) || [])[0];
575788
- return `Windows ${winMap.get(version)}`;
576068
+ // 尝试精确匹配完整版本号
576069
+ let windowsVersion = winMap.get(release);
576070
+ if (!windowsVersion) {
576071
+ // 如果没有精确匹配,尝试匹配主版本号
576072
+ const majorVersion = (/^\d+\.\d+/.exec(release) || [])[0];
576073
+ windowsVersion = winMap.get(majorVersion);
576074
+ }
576075
+ if (!windowsVersion) {
576076
+ // 如果还是没有匹配,尝试只匹配第一部分
576077
+ const firstPart = (/^\d+/.exec(release) || [])[0];
576078
+ if (firstPart === '10') {
576079
+ windowsVersion = '10';
576080
+ }
576081
+ }
576082
+ // 显示完整的版本信息
576083
+ const versionDisplay = windowsVersion || release;
576084
+ return `Windows ${versionDisplay}`;
575789
576085
  }
576086
+ // 其他 Linux
575790
576087
  return 'Linux';
575791
576088
  }
575792
576089
  exports.getPlatformRelease = getPlatformRelease;
576090
+ // 获取 hostname 和平台信息
575793
576091
  function getOSInfo() {
575794
576092
  const hostname = os_1.default.hostname();
575795
576093
  const platform = os_1.default.platform();
@@ -578072,12 +578370,18 @@ function readFile(target) {
578072
578370
  return '';
578073
578371
  }
578074
578372
  }
578373
+ // 从 env 文件中加载环境变量
578374
+ // 参考 https://cli.vuejs.org/zh/guide/mode-and-env.html
578075
578375
  function loadEnvVariables(from = process.cwd()) {
578076
578376
  const mode = yargs_1.default.argv.mode;
578377
+ // .env
578077
578378
  const baseEnv = dotenv_1.default.parse(readFile(path_1.default.join(from, '.env')));
578379
+ // .env.local
578078
578380
  const localEnv = dotenv_1.default.parse(readFile(path_1.default.join(from, '.env.local')));
578381
+ // .env.mode
578079
578382
  const modeEnv = dotenv_1.default.parse(readFile(path_1.default.join(from, `.env.${mode}`)));
578080
578383
  const unionConfig = lodash_1.default.merge({}, baseEnv, localEnv, modeEnv);
578384
+ // 扩展 dotenv 解析模式,支持 functions.xxx=xxx 形式设置对象
578081
578385
  return Object.keys(unionConfig).reduce((prev, key) => {
578082
578386
  return lodash_1.default.set(prev, key, unionConfig[key]);
578083
578387
  }, {});
@@ -581049,28 +581353,46 @@ module.exports = /*#__PURE__*/JSON.parse('{"name":"got","version":"9.6.0","descr
581049
581353
  Object.defineProperty(exports, "__esModule", ({ value: true }));
581050
581354
  exports.nilCache = exports.memoryCache = exports.Cache = void 0;
581051
581355
  class Entry {
581356
+ // eslint-disable-next-line
581052
581357
  constructor(key, value, now, maxAge) {
581053
581358
  this.key = key;
581054
581359
  this.value = value;
581055
581360
  this.now = now;
581056
581361
  this.maxAge = maxAge;
581057
581362
  }
581363
+ // 当前 entry 是否过期
581058
581364
  isExpired() {
581059
581365
  const now = Date.now();
581060
581366
  return this.now + this.maxAge <= now;
581061
581367
  }
581062
581368
  }
581369
+ /**
581370
+ * 缓存模块
581371
+ * 1. 内存缓存
581372
+ * 2. TODO: 本地缓存
581373
+ */
581063
581374
  class Cache {
581064
581375
  constructor(nil) {
581376
+ // use map to cache
581065
581377
  this.store = new Map();
581066
581378
  this.nil = false;
581067
581379
  this.nil = nil;
581068
581380
  }
581381
+ /**
581382
+ * 设置缓存
581383
+ * @param key 缓存 key
581384
+ * @param value 缓存值
581385
+ * @param maxAge 缓存保持时间,单位 ms
581386
+ */
581069
581387
  set(key, value, maxAge = 0) {
581070
581388
  const now = maxAge ? Date.now() : 0;
581071
581389
  const entry = new Entry(key, value, now, maxAge);
581072
581390
  this.store.set(key, entry);
581073
581391
  }
581392
+ /**
581393
+ * 获取缓存结果
581394
+ * @param key 缓存 key
581395
+ */
581074
581396
  get(key) {
581075
581397
  const { nil } = this;
581076
581398
  const entry = this.store.get(key);
@@ -581084,6 +581406,7 @@ class Cache {
581084
581406
  }
581085
581407
  }
581086
581408
  exports.Cache = Cache;
581409
+ // 标志缓存不存在或过期
581087
581410
  Cache.NIL = Symbol('NIL');
581088
581411
  exports.memoryCache = new Cache();
581089
581412
  exports.nilCache = new Cache(true);
@@ -605506,6 +605829,7 @@ class Explorer extends ExplorerBase_1.ExplorerBase {
605506
605829
  return placeResult;
605507
605830
  }
605508
605831
  }
605832
+ // config not found
605509
605833
  return null;
605510
605834
  });
605511
605835
  }
@@ -667635,12 +667959,15 @@ exports.execWithLoading = exports.loadingFactory = void 0;
667635
667959
  const ora_1 = __importDefault(__webpack_require__(4539));
667636
667960
  class Loading {
667637
667961
  constructor() {
667962
+ // @ts-ignore
667638
667963
  process.on('tcbExit', this.stop.bind(this));
667964
+ // @ts-ignore
667639
667965
  process.on('tcbError', this.stop.bind(this));
667640
667966
  this.spinner = (0, ora_1.default)({
667641
667967
  discardStdin: false
667642
667968
  });
667643
667969
  }
667970
+ // eslint-disable-next-line
667644
667971
  set text(text) {
667645
667972
  this.spinner.text = text;
667646
667973
  }
@@ -667667,9 +667994,15 @@ const loadingFactory = () => {
667667
667994
  return new Loading();
667668
667995
  };
667669
667996
  exports.loadingFactory = loadingFactory;
667997
+ /**
667998
+ * 执行异步任务,显示 loading 动画
667999
+ * @param task
668000
+ * @param options
668001
+ */
667670
668002
  const execWithLoading = (task, options = {}) => __awaiter(void 0, void 0, void 0, function* () {
667671
668003
  const { startTip, successTip, failTip } = options;
667672
668004
  const loading = (0, exports.loadingFactory)();
668005
+ // 刷新 loading 提示
667673
668006
  const flush = (text) => {
667674
668007
  loading.text = text;
667675
668008
  };
@@ -673720,20 +674053,15 @@ exports.DefaultFunctionDeployConfig = {
673720
674053
  ignore: ['node_modules', 'node_modules/**/*', '.git']
673721
674054
  };
673722
674055
  exports.RuntimeOptions = [
673723
- { name: 'Node.js 24.11 (公测中)', value: 'Nodejs24.11', handler: 'index.main' },
673724
- { name: 'Node.js 22.21 (公测中)', value: 'Nodejs22.21', handler: 'index.main' },
673725
674056
  { name: 'Node.js 20.19', value: 'Nodejs20.19', handler: 'index.main' },
673726
674057
  { name: 'Node.js 18.15', value: 'Nodejs18.15', handler: 'index.main' },
673727
674058
  { name: 'Node.js 16.13', value: 'Nodejs16.13', handler: 'index.main' },
673728
- { name: 'Python 3.11', value: 'Python3.11', handler: 'index.main' },
673729
- { name: 'Python 3.10', value: 'Python3.10', handler: 'index.main' },
673730
674059
  { name: 'Python 3.9', value: 'Python3.9', handler: 'index.main' },
673731
674060
  { name: 'Python 3.7', value: 'Python3.7', handler: 'index.main' },
673732
674061
  { name: 'PHP 8.0', value: 'Php8.0', handler: 'index.main' },
673733
674062
  { name: 'PHP 7.4', value: 'Php7.4', handler: 'index.main' },
673734
674063
  { name: 'Java 11', value: 'Java11', handler: 'example.Hello::mainHandler' },
673735
- { name: 'Java 8', value: 'Java8', handler: 'example.Hello::mainHandler' },
673736
- { name: 'Golang 1', value: 'Go1', handler: 'main' }
674064
+ { name: 'Java 8', value: 'Java8', handler: 'example.Hello::mainHandler' }
673737
674065
  ];
673738
674066
  exports.DefaultCloudBaseConfig = {
673739
674067
  functionRoot: './functions',
@@ -681806,326 +682134,6 @@ exports.version = version
681806
682134
  exports.defer = defer
681807
682135
 
681808
682136
 
681809
- /***/ }),
681810
-
681811
- /***/ 64180:
681812
- /***/ (function(__unused_webpack_module, exports, __webpack_require__) {
681813
-
681814
- "use strict";
681815
-
681816
- var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
681817
- var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
681818
- if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
681819
- else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
681820
- return c > 3 && r && Object.defineProperty(target, key, r), r;
681821
- };
681822
- var __metadata = (this && this.__metadata) || function (k, v) {
681823
- if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
681824
- };
681825
- var __param = (this && this.__param) || function (paramIndex, decorator) {
681826
- return function (target, key) { decorator(target, key, paramIndex); }
681827
- };
681828
- var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
681829
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
681830
- return new (P || (P = Promise))(function (resolve, reject) {
681831
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
681832
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
681833
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
681834
- step((generator = generator.apply(thisArg, _arguments || [])).next());
681835
- });
681836
- };
681837
- var __importDefault = (this && this.__importDefault) || function (mod) {
681838
- return (mod && mod.__esModule) ? mod : { "default": mod };
681839
- };
681840
- Object.defineProperty(exports, "__esModule", ({ value: true }));
681841
- exports.ConfigPull = void 0;
681842
- const fs_1 = __importDefault(__webpack_require__(79896));
681843
- const path_1 = __importDefault(__webpack_require__(16928));
681844
- const inquirer_1 = __importDefault(__webpack_require__(6403));
681845
- const common_1 = __webpack_require__(48431);
681846
- const error_1 = __webpack_require__(66759);
681847
- const function_1 = __webpack_require__(11686);
681848
- const utils_1 = __webpack_require__(82079);
681849
- const utils_2 = __webpack_require__(75213);
681850
- const decorators_1 = __webpack_require__(93480);
681851
- const i18n_1 = __webpack_require__(69258);
681852
- const constant_1 = __webpack_require__(62977);
681853
- function convertToFunctionConfig(detail, funcDir = '.') {
681854
- var _a, _b, _c, _d, _e, _f, _g;
681855
- const config = {
681856
- name: detail.FunctionName,
681857
- dir: funcDir
681858
- };
681859
- if (detail.Handler) {
681860
- config.handler = detail.Handler;
681861
- }
681862
- if (detail.Timeout) {
681863
- config.timeout = detail.Timeout;
681864
- }
681865
- if (detail.Runtime) {
681866
- config.runtime = detail.Runtime;
681867
- }
681868
- if (detail.MemorySize) {
681869
- config.memorySize = detail.MemorySize;
681870
- }
681871
- if (detail.InstallDependency !== undefined) {
681872
- config.installDependency = detail.InstallDependency === 'TRUE';
681873
- }
681874
- if (((_b = (_a = detail.Environment) === null || _a === void 0 ? void 0 : _a.Variables) === null || _b === void 0 ? void 0 : _b.length) > 0) {
681875
- const envVariables = {};
681876
- for (const item of detail.Environment.Variables) {
681877
- envVariables[item.Key] = item.Value;
681878
- }
681879
- config.envVariables = envVariables;
681880
- }
681881
- if (((_c = detail.VpcConfig) === null || _c === void 0 ? void 0 : _c.VpcId) && ((_d = detail.VpcConfig) === null || _d === void 0 ? void 0 : _d.SubnetId)) {
681882
- config.vpc = {
681883
- vpcId: detail.VpcConfig.VpcId,
681884
- subnetId: detail.VpcConfig.SubnetId
681885
- };
681886
- }
681887
- if (((_e = detail.Triggers) === null || _e === void 0 ? void 0 : _e.length) > 0) {
681888
- config.triggers = detail.Triggers.map((trigger) => ({
681889
- name: trigger.TriggerName,
681890
- type: trigger.Type.toLowerCase(),
681891
- config: trigger.TriggerDesc
681892
- }));
681893
- }
681894
- if (detail.ProtocolType === 'WS') {
681895
- config.protocolType = 'WS';
681896
- if ((_g = (_f = detail.ProtocolParams) === null || _f === void 0 ? void 0 : _f.WsParams) === null || _g === void 0 ? void 0 : _g.IdleTimeOut) {
681897
- config.protocolParams = {
681898
- wsParams: {
681899
- idleTimeOut: detail.ProtocolParams.WsParams.IdleTimeOut
681900
- }
681901
- };
681902
- }
681903
- }
681904
- if (detail.InstanceConcurrencyConfig) {
681905
- const concurrencyConfig = {};
681906
- if (detail.InstanceConcurrencyConfig.MaxConcurrency) {
681907
- concurrencyConfig.maxConcurrency = detail.InstanceConcurrencyConfig.MaxConcurrency;
681908
- }
681909
- if (detail.InstanceConcurrencyConfig.DynamicEnabled !== undefined) {
681910
- concurrencyConfig.dynamicEnabled = detail.InstanceConcurrencyConfig.DynamicEnabled;
681911
- }
681912
- if (Object.keys(concurrencyConfig).length > 0) {
681913
- config.instanceConcurrencyConfig = concurrencyConfig;
681914
- }
681915
- }
681916
- return config;
681917
- }
681918
- function generateCloudbaserc(envId, functionConfig) {
681919
- return {
681920
- envId,
681921
- functionRoot: '.',
681922
- functions: [functionConfig]
681923
- };
681924
- }
681925
- let ConfigPull = class ConfigPull extends common_1.Command {
681926
- get options() {
681927
- return {
681928
- cmd: 'fn',
681929
- childCmd: {
681930
- cmd: 'config',
681931
- desc: (0, i18n_1.t)('函数配置管理')
681932
- },
681933
- childSubCmd: 'pull <name>',
681934
- options: [
681935
- {
681936
- flags: '-e, --envId <envId>',
681937
- desc: (0, i18n_1.t)('环境 Id')
681938
- },
681939
- {
681940
- flags: '-o, --output <output>',
681941
- desc: (0, i18n_1.t)('输出文件路径(默认为当前目录下的 cloudbaserc.json)')
681942
- },
681943
- {
681944
- flags: '--stdout',
681945
- desc: (0, i18n_1.t)('输出到控制台而非文件')
681946
- },
681947
- {
681948
- flags: '--code-secret <codeSecret>',
681949
- desc: (0, i18n_1.t)('代码加密的函数的 CodeSecret')
681950
- },
681951
- {
681952
- flags: '--dir <dir>',
681953
- desc: (0, i18n_1.t)('指定目录用于推测配置(当云函数不存在时)')
681954
- },
681955
- {
681956
- flags: '--yes',
681957
- desc: (0, i18n_1.t)('跳过交互确认,自动覆盖已存在的文件')
681958
- }
681959
- ],
681960
- desc: (0, i18n_1.t)('拉取云函数配置(如云函数不存在则从本地推测)'),
681961
- requiredEnvId: false,
681962
- autoRunLogin: true
681963
- };
681964
- }
681965
- execute(ctx, params, log) {
681966
- return __awaiter(this, void 0, void 0, function* () {
681967
- let { envId, options } = ctx;
681968
- const { output, codeSecret, dir, yes, stdout } = options;
681969
- const name = params === null || params === void 0 ? void 0 : params[0];
681970
- if (!name) {
681971
- throw new error_1.CloudBaseError((0, i18n_1.t)('请指定云函数名称!'));
681972
- }
681973
- if (!envId) {
681974
- envId = yield (0, utils_2.selectEnv)({ envTypes: [constant_1.EnvType.BAAS, constant_1.EnvType.WEDA] });
681975
- }
681976
- const loading = (0, utils_1.loadingFactory)();
681977
- loading.start((0, i18n_1.t)('获取函数配置中...'));
681978
- const functionService = yield (0, function_1.getFunctionService)(envId);
681979
- let config;
681980
- let isInferred = false;
681981
- let selectedEnvId = envId;
681982
- const funcDir = dir || '.';
681983
- try {
681984
- const detail = yield functionService.getFunctionDetail(name, codeSecret);
681985
- loading.stop();
681986
- config = convertToFunctionConfig(detail, funcDir);
681987
- log.info((0, i18n_1.t)('✓ 已从云端拉取函数 [{{name}}] 的配置', { name }));
681988
- }
681989
- catch (e) {
681990
- loading.stop();
681991
- if (e.code === 'ResourceNotFound.Function') {
681992
- log.warn((0, i18n_1.t)('云函数 [{{name}}] 不存在', { name }));
681993
- let shouldCreate = yes;
681994
- if (!shouldCreate) {
681995
- const { confirm } = yield inquirer_1.default.prompt({
681996
- type: 'confirm',
681997
- name: 'confirm',
681998
- message: (0, i18n_1.t)('是否从本地项目推测并创建配置?'),
681999
- default: true
682000
- });
682001
- shouldCreate = confirm;
682002
- }
682003
- if (!shouldCreate) {
682004
- log.info((0, i18n_1.t)('已取消'));
682005
- return;
682006
- }
682007
- const targetDir = dir ? path_1.default.resolve(process.cwd(), dir) : process.cwd();
682008
- const inferResult = (0, function_1.inferFunctionConfig)({ name, targetDir });
682009
- if (inferResult) {
682010
- config = inferResult.config;
682011
- config.dir = funcDir;
682012
- isInferred = true;
682013
- log.info((0, i18n_1.t)('✓ 已从本地推测出配置(来源:{{source}})', { source: inferResult.source }));
682014
- }
682015
- else {
682016
- config = Object.assign({ name, dir: funcDir }, constant_1.DefaultFunctionDeployConfig);
682017
- isInferred = true;
682018
- log.info((0, i18n_1.t)('⚠ 无法从本地推测配置,使用默认配置'));
682019
- }
682020
- }
682021
- else {
682022
- throw e;
682023
- }
682024
- }
682025
- if (stdout) {
682026
- const cloudbaserc = generateCloudbaserc(selectedEnvId, config);
682027
- const stdoutOutput = JSON.stringify(cloudbaserc, null, 2);
682028
- if (isInferred) {
682029
- log.info((0, i18n_1.t)('推测的函数 [{{name}}] 配置:', { name }));
682030
- }
682031
- else {
682032
- log.info((0, i18n_1.t)('云函数 [{{name}}] 配置:', { name }));
682033
- }
682034
- console.log(stdoutOutput);
682035
- log.info('');
682036
- log.info((0, i18n_1.t)('提示:可将上述配置添加到 cloudbaserc.json 的 functions 数组中'));
682037
- return;
682038
- }
682039
- const outputPath = output
682040
- ? path_1.default.resolve(process.cwd(), output)
682041
- : path_1.default.resolve(process.cwd(), 'cloudbaserc.json');
682042
- let finalOutput;
682043
- let isUpdate = false;
682044
- if (fs_1.default.existsSync(outputPath)) {
682045
- try {
682046
- const existingContent = fs_1.default.readFileSync(outputPath, 'utf-8');
682047
- const existingConfig = JSON.parse(existingContent);
682048
- if (!existingConfig.functions) {
682049
- existingConfig.functions = [];
682050
- }
682051
- const existingIndex = existingConfig.functions.findIndex((fn) => fn.name === config.name);
682052
- if (existingIndex >= 0) {
682053
- let shouldUpdate = yes;
682054
- if (!shouldUpdate) {
682055
- const { update } = yield inquirer_1.default.prompt({
682056
- type: 'confirm',
682057
- name: 'update',
682058
- message: (0, i18n_1.t)('函数 [{{name}}] 配置已存在,是否更新?', { name: config.name }),
682059
- default: true
682060
- });
682061
- shouldUpdate = update;
682062
- }
682063
- if (!shouldUpdate) {
682064
- log.info((0, i18n_1.t)('已取消'));
682065
- return;
682066
- }
682067
- existingConfig.functions[existingIndex] = config;
682068
- isUpdate = true;
682069
- }
682070
- else {
682071
- existingConfig.functions.push(config);
682072
- }
682073
- if (!existingConfig.envId) {
682074
- existingConfig.envId = selectedEnvId;
682075
- }
682076
- finalOutput = existingConfig;
682077
- }
682078
- catch (parseError) {
682079
- log.warn((0, i18n_1.t)('现有配置文件解析失败'));
682080
- let shouldOverwrite = yes;
682081
- if (!shouldOverwrite) {
682082
- const { overwrite } = yield inquirer_1.default.prompt({
682083
- type: 'confirm',
682084
- name: 'overwrite',
682085
- message: (0, i18n_1.t)('是否覆盖现有文件?'),
682086
- default: false
682087
- });
682088
- shouldOverwrite = overwrite;
682089
- }
682090
- if (!shouldOverwrite) {
682091
- log.info((0, i18n_1.t)('已取消'));
682092
- return;
682093
- }
682094
- finalOutput = generateCloudbaserc(selectedEnvId, config);
682095
- }
682096
- }
682097
- else {
682098
- finalOutput = generateCloudbaserc(selectedEnvId, config);
682099
- }
682100
- const jsonOutput = JSON.stringify(finalOutput, null, 2);
682101
- fs_1.default.writeFileSync(outputPath, jsonOutput, 'utf-8');
682102
- if (isUpdate) {
682103
- log.success((0, i18n_1.t)('云函数 [{{name}}] 配置已更新到 {{path}}', { name, path: outputPath }));
682104
- }
682105
- else if (fs_1.default.existsSync(outputPath)) {
682106
- log.success((0, i18n_1.t)('云函数 [{{name}}] 配置已追加到 {{path}}', { name, path: outputPath }));
682107
- }
682108
- else {
682109
- log.success((0, i18n_1.t)('云函数 [{{name}}] 配置已保存到 {{path}}', { name, path: outputPath }));
682110
- }
682111
- });
682112
- }
682113
- };
682114
- __decorate([
682115
- (0, decorators_1.InjectParams)(),
682116
- __param(0, (0, decorators_1.CmdContext)()),
682117
- __param(1, (0, decorators_1.ArgsParams)()),
682118
- __param(2, (0, decorators_1.Log)()),
682119
- __metadata("design:type", Function),
682120
- __metadata("design:paramtypes", [Object, Object, decorators_1.Logger]),
682121
- __metadata("design:returntype", Promise)
682122
- ], ConfigPull.prototype, "execute", null);
682123
- ConfigPull = __decorate([
682124
- (0, common_1.ICommand)()
682125
- ], ConfigPull);
682126
- exports.ConfigPull = ConfigPull;
682127
-
682128
-
682129
682137
  /***/ }),
682130
682138
 
682131
682139
  /***/ 64182:
@@ -697294,6 +697302,7 @@ module.exports = ({stream = process.stdout} = {}) => {
697294
697302
 
697295
697303
  Object.defineProperty(exports, "__esModule", ({ value: true }));
697296
697304
  exports.getProxy = void 0;
697305
+ // 解析 Proxy 配置
697297
697306
  function getProxy() {
697298
697307
  const httpProxy = process.env.http_proxy ||
697299
697308
  process.env.HTTP_PROXY ||
@@ -715268,12 +715277,17 @@ const getSearchPlaces = (moduleName) => [
715268
715277
  `${moduleName}rc.js`,
715269
715278
  `${moduleName}.config.js`
715270
715279
  ];
715280
+ /**
715281
+ * 搜索指定配置文件,返回包含路径等信息
715282
+ */
715271
715283
  function searchConfig(dest, moduleName = MODULE_NAME) {
715272
715284
  return __awaiter(this, void 0, void 0, function* () {
715273
715285
  const explorer = (0, explorer_1.cosmiconfig)(moduleName, {
715286
+ // 不向上搜索
715274
715287
  stopDir: process.cwd(),
715275
715288
  searchPlaces: getSearchPlaces(moduleName)
715276
715289
  });
715290
+ // 搜索配置文件
715277
715291
  try {
715278
715292
  return explorer.search(dest || process.cwd());
715279
715293
  }
@@ -715283,14 +715297,21 @@ function searchConfig(dest, moduleName = MODULE_NAME) {
715283
715297
  });
715284
715298
  }
715285
715299
  exports.searchConfig = searchConfig;
715300
+ /**
715301
+ * 搜索或指定配置文件路径
715302
+ * 加载配置文件内容
715303
+ */
715286
715304
  function loadConfig(options = {}) {
715287
715305
  return __awaiter(this, void 0, void 0, function* () {
715288
715306
  const { moduleName = MODULE_NAME, configPath, searchFrom } = options;
715289
715307
  const explorer = (0, explorer_1.cosmiconfig)(moduleName, {
715308
+ // 不向上搜索
715290
715309
  stopDir: process.cwd(),
715291
715310
  searchPlaces: getSearchPlaces(moduleName)
715292
715311
  });
715312
+ // 从指定路径加载配置文件
715293
715313
  if (configPath) {
715314
+ // 校验路径是否存在
715294
715315
  (0, fs_1.checkReadable)(configPath, true);
715295
715316
  try {
715296
715317
  const result = yield explorer.load(configPath);
@@ -715305,6 +715326,7 @@ function loadConfig(options = {}) {
715305
715326
  });
715306
715327
  }
715307
715328
  }
715329
+ // 搜索配置文件
715308
715330
  try {
715309
715331
  const result = yield searchConfig(searchFrom || process.cwd(), moduleName);
715310
715332
  if (!result)
@@ -721024,6 +721046,7 @@ function cosmiconfig(moduleName, options = {}) {
721024
721046
  };
721025
721047
  }
721026
721048
  exports.cosmiconfig = cosmiconfig;
721049
+ // do not allow mutation of default loaders. Make sure it is set inside options
721027
721050
  const defaultLoaders = Object.freeze({
721028
721051
  '.js': loaders_1.loaders.loadJs,
721029
721052
  '.json': loaders_1.loaders.loadJson,
@@ -730446,11 +730469,14 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
730446
730469
  };
730447
730470
  Object.defineProperty(exports, "__esModule", ({ value: true }));
730448
730471
  exports.yaml = exports.yamlStringify = exports.yamlParse = void 0;
730472
+ // https://github.com/nodeca/js-yaml
730449
730473
  const yaml_1 = __importDefault(__webpack_require__(61581));
730474
+ // 解析 YAML 字符串
730450
730475
  const yamlParse = (doc) => {
730451
730476
  return yaml_1.default.parse(doc);
730452
730477
  };
730453
730478
  exports.yamlParse = yamlParse;
730479
+ // 导出为 YAML 字符串
730454
730480
  const yamlStringify = (object) => {
730455
730481
  return yaml_1.default.stringify(object);
730456
730482
  };
@@ -742784,24 +742810,38 @@ const common_1 = __webpack_require__(96711);
742784
742810
  const coding_1 = __webpack_require__(40540);
742785
742811
  const web_1 = __webpack_require__(2240);
742786
742812
  const system_1 = __webpack_require__(62179);
742787
- const CliAuthBaseUrl = 'https://tcb.cloud.tencent.com/dev#/cli-auth';
742813
+ const CliAuthBaseUrl = 'https://tcb.cloud.tencent.com/dev';
742814
+ // 打开云开发控制台,获取授权
742788
742815
  function getAuthTokenFromWeb(options = {}) {
742789
742816
  return __awaiter(this, void 0, void 0, function* () {
742790
- const { getAuthUrl } = options;
742817
+ const { getAuthUrl, noBrowser, callbackTimeout } = options;
742791
742818
  const mac = yield (0, system_1.getMacAddress)();
742792
742819
  const os = (0, system_1.getOSInfo)();
742793
742820
  const macHash = (0, coding_1.md5Encoding)(mac);
742794
742821
  const query = yield (0, web_1.getDataFromWeb)((port) => {
742795
- let cliAuthUrl = `${CliAuthBaseUrl}?port=${port}&hash=${macHash}&mac=${mac}&os=${os}&from=cli`;
742822
+ const callbackUrl = `http://127.0.0.1:${port}`;
742823
+ const encodedQuery = `port=${encodeURIComponent(String(port))}`
742824
+ + `&hash=${encodeURIComponent(macHash)}`
742825
+ + `&mac=${encodeURIComponent(mac)}`
742826
+ + `&os=${encodeURIComponent(os)}`
742827
+ + '&from=cli';
742828
+ const encodedCallbackUrl = encodeURIComponent(callbackUrl);
742829
+ // 授权链接
742830
+ const rawAuthUrl = `${CliAuthBaseUrl}?authCallbackUrl=${encodedCallbackUrl}#/cli-auth?${encodedQuery}`;
742831
+ let cliAuthUrl = rawAuthUrl;
742796
742832
  if (getAuthUrl) {
742797
742833
  try {
742798
- cliAuthUrl = getAuthUrl(`${CliAuthBaseUrl}?port=${port}&hash=${macHash}&mac=${mac}&os=${os}&from=cli`);
742834
+ cliAuthUrl = getAuthUrl(rawAuthUrl);
742799
742835
  }
742800
742836
  catch (error) {
742837
+ // 忽略错误
742801
742838
  }
742802
742839
  }
742803
742840
  return cliAuthUrl;
742804
- }, 'login');
742841
+ }, 'login', {
742842
+ noBrowser,
742843
+ callbackTimeout
742844
+ });
742805
742845
  const credential = (0, common_1.resolveCredential)(query);
742806
742846
  return credential;
742807
742847
  });
@@ -800695,7 +800735,7 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
800695
800735
  return (mod && mod.__esModule) ? mod : { "default": mod };
800696
800736
  };
800697
800737
  Object.defineProperty(exports, "__esModule", ({ value: true }));
800698
- exports.getConfigSourceDescription = exports.inferFunctionConfig = exports.checkAndCreateBootstrap = exports.generateBootstrapContent = void 0;
800738
+ exports.checkAndCreateBootstrap = exports.generateBootstrapContent = void 0;
800699
800739
  const fs_1 = __importDefault(__webpack_require__(79896));
800700
800740
  const path_1 = __importDefault(__webpack_require__(16928));
800701
800741
  const inquirer_1 = __importDefault(__webpack_require__(6403));
@@ -800787,206 +800827,6 @@ function checkAndCreateBootstrap(functionPath, func, options = {}) {
800787
800827
  });
800788
800828
  }
800789
800829
  exports.checkAndCreateBootstrap = checkAndCreateBootstrap;
800790
- function inferFunctionConfig(options = {}) {
800791
- const { name, targetDir = process.cwd(), httpFn } = options;
800792
- const nodeResult = inferNodejsConfig(targetDir, name, httpFn);
800793
- if (nodeResult)
800794
- return nodeResult;
800795
- const pythonResult = inferPythonConfig(targetDir, name, httpFn);
800796
- if (pythonResult)
800797
- return pythonResult;
800798
- const phpResult = inferPhpConfig(targetDir, name, httpFn);
800799
- if (phpResult)
800800
- return phpResult;
800801
- const javaResult = inferJavaConfig(targetDir, name, httpFn);
800802
- if (javaResult)
800803
- return javaResult;
800804
- const goResult = inferGoConfig(targetDir, name, httpFn);
800805
- if (goResult)
800806
- return goResult;
800807
- const fileBasedResult = inferByFileExtension(targetDir, name, httpFn);
800808
- if (fileBasedResult)
800809
- return fileBasedResult;
800810
- return null;
800811
- }
800812
- exports.inferFunctionConfig = inferFunctionConfig;
800813
- function inferNodejsConfig(targetDir, name, httpFn) {
800814
- var _a;
800815
- const packageJsonPath = path_1.default.join(targetDir, 'package.json');
800816
- if (!fs_1.default.existsSync(packageJsonPath)) {
800817
- return null;
800818
- }
800819
- try {
800820
- const packageJson = JSON.parse(fs_1.default.readFileSync(packageJsonPath, 'utf-8'));
800821
- const funcName = name || packageJson.name || path_1.default.basename(targetDir);
800822
- let handler = constant_1.DefaultFunctionDeployConfig.handler;
800823
- if (packageJson.main) {
800824
- const mainFile = path_1.default.basename(packageJson.main).replace(/\.[^.]+$/, '');
800825
- handler = `${mainFile}.main`;
800826
- }
800827
- let runtime = constant_1.DefaultFunctionDeployConfig.runtime;
800828
- if ((_a = packageJson.engines) === null || _a === void 0 ? void 0 : _a.node) {
800829
- const nodeVersion = packageJson.engines.node;
800830
- if (nodeVersion.includes('20')) {
800831
- runtime = 'Nodejs20.19';
800832
- }
800833
- else if (nodeVersion.includes('16')) {
800834
- runtime = 'Nodejs16.13';
800835
- }
800836
- }
800837
- return {
800838
- config: Object.assign(Object.assign(Object.assign({ name: funcName }, constant_1.DefaultFunctionDeployConfig), { runtime,
800839
- handler }), (httpFn ? { type: 'HTTP' } : {})),
800840
- source: (0, i18n_1.t)('Node.js 项目(package.json)')
800841
- };
800842
- }
800843
- catch (e) {
800844
- return null;
800845
- }
800846
- }
800847
- function inferPythonConfig(targetDir, name, httpFn) {
800848
- const pythonFiles = ['requirements.txt', 'setup.py', 'pyproject.toml'];
800849
- const foundFile = pythonFiles.find(file => fs_1.default.existsSync(path_1.default.join(targetDir, file)));
800850
- if (!foundFile) {
800851
- return null;
800852
- }
800853
- const funcName = name || path_1.default.basename(targetDir);
800854
- const entryFiles = ['main.py', 'app.py', 'index.py'];
800855
- let handler = 'index.main';
800856
- for (const file of entryFiles) {
800857
- if (fs_1.default.existsSync(path_1.default.join(targetDir, file))) {
800858
- const filename = path_1.default.basename(file, '.py');
800859
- handler = `${filename}.main`;
800860
- break;
800861
- }
800862
- }
800863
- return {
800864
- config: Object.assign(Object.assign(Object.assign({ name: funcName }, constant_1.DefaultFunctionDeployConfig), { runtime: 'Python3.9', handler }), (httpFn ? { type: 'HTTP' } : {})),
800865
- source: (0, i18n_1.t)('Python 项目({{file}})', { file: foundFile })
800866
- };
800867
- }
800868
- function inferPhpConfig(targetDir, name, httpFn) {
800869
- const composerJsonPath = path_1.default.join(targetDir, 'composer.json');
800870
- let hasPhpFiles = false;
800871
- try {
800872
- hasPhpFiles = fs_1.default.readdirSync(targetDir).some(file => file.endsWith('.php'));
800873
- }
800874
- catch (e) {
800875
- }
800876
- if (!fs_1.default.existsSync(composerJsonPath) && !hasPhpFiles) {
800877
- return null;
800878
- }
800879
- let funcName = name || path_1.default.basename(targetDir);
800880
- let source = (0, i18n_1.t)('PHP 项目(PHP 文件)');
800881
- if (fs_1.default.existsSync(composerJsonPath)) {
800882
- try {
800883
- const composerJson = JSON.parse(fs_1.default.readFileSync(composerJsonPath, 'utf-8'));
800884
- if (!name && composerJson.name) {
800885
- funcName = composerJson.name.split('/').pop() || funcName;
800886
- }
800887
- source = (0, i18n_1.t)('PHP 项目(composer.json)');
800888
- }
800889
- catch (e) {
800890
- }
800891
- }
800892
- let handler = 'index.main';
800893
- if (fs_1.default.existsSync(path_1.default.join(targetDir, 'index.php'))) {
800894
- handler = 'index.main';
800895
- }
800896
- return {
800897
- config: Object.assign(Object.assign(Object.assign({ name: funcName }, constant_1.DefaultFunctionDeployConfig), { runtime: 'Php8.0', handler }), (httpFn ? { type: 'HTTP' } : {})),
800898
- source
800899
- };
800900
- }
800901
- function inferJavaConfig(targetDir, name, httpFn) {
800902
- const javaFiles = ['pom.xml', 'build.gradle', 'build.gradle.kts'];
800903
- const foundFile = javaFiles.find(file => fs_1.default.existsSync(path_1.default.join(targetDir, file)));
800904
- if (!foundFile) {
800905
- return null;
800906
- }
800907
- let funcName = name || path_1.default.basename(targetDir);
800908
- if (!name && foundFile === 'pom.xml') {
800909
- const pomPath = path_1.default.join(targetDir, 'pom.xml');
800910
- try {
800911
- const pomContent = fs_1.default.readFileSync(pomPath, 'utf-8');
800912
- const artifactIdMatch = pomContent.match(/<artifactId>([^<]+)<\/artifactId>/);
800913
- if (artifactIdMatch) {
800914
- funcName = artifactIdMatch[1];
800915
- }
800916
- }
800917
- catch (e) {
800918
- }
800919
- }
800920
- return {
800921
- config: Object.assign(Object.assign(Object.assign({ name: funcName }, constant_1.DefaultFunctionDeployConfig), { runtime: 'Java11', handler: 'example.Hello::mainHandler' }), (httpFn ? { type: 'HTTP' } : {})),
800922
- source: (0, i18n_1.t)('Java 项目({{file}})', { file: foundFile })
800923
- };
800924
- }
800925
- function inferGoConfig(targetDir, name, httpFn) {
800926
- const goFiles = ['go.mod', 'go.sum'];
800927
- const foundFile = goFiles.find(file => fs_1.default.existsSync(path_1.default.join(targetDir, file)));
800928
- if (!foundFile) {
800929
- return null;
800930
- }
800931
- let funcName = name || path_1.default.basename(targetDir);
800932
- if (!name && fs_1.default.existsSync(path_1.default.join(targetDir, 'go.mod'))) {
800933
- try {
800934
- const goModContent = fs_1.default.readFileSync(path_1.default.join(targetDir, 'go.mod'), 'utf-8');
800935
- const moduleMatch = goModContent.match(/^module\s+(.+)$/m);
800936
- if (moduleMatch) {
800937
- funcName = moduleMatch[1].split('/').pop() || funcName;
800938
- }
800939
- }
800940
- catch (e) {
800941
- }
800942
- }
800943
- return {
800944
- config: Object.assign(Object.assign(Object.assign({ name: funcName }, constant_1.DefaultFunctionDeployConfig), { runtime: 'Go1', handler: 'main' }), (httpFn ? { type: 'HTTP' } : {})),
800945
- source: (0, i18n_1.t)('Go 项目({{file}})', { file: foundFile })
800946
- };
800947
- }
800948
- function inferByFileExtension(targetDir, name, httpFn) {
800949
- try {
800950
- const files = fs_1.default.readdirSync(targetDir);
800951
- const fileTypes = {
800952
- js: files.filter(f => f.endsWith('.js')).length,
800953
- ts: files.filter(f => f.endsWith('.ts')).length,
800954
- py: files.filter(f => f.endsWith('.py')).length,
800955
- php: files.filter(f => f.endsWith('.php')).length,
800956
- java: files.filter(f => f.endsWith('.java')).length,
800957
- go: files.filter(f => f.endsWith('.go')).length
800958
- };
800959
- const maxType = Object.entries(fileTypes).reduce((a, b) => (fileTypes[a[0]] || 0) > (fileTypes[b[0]] || 0) ? a : b);
800960
- if (maxType[1] === 0) {
800961
- return null;
800962
- }
800963
- const funcName = name || path_1.default.basename(targetDir);
800964
- const typeConfigMap = {
800965
- js: { runtime: 'Nodejs18.15', handler: 'index.main', source: (0, i18n_1.t)('JavaScript 文件推测') },
800966
- ts: { runtime: 'Nodejs18.15', handler: 'index.main', source: (0, i18n_1.t)('TypeScript 文件推测') },
800967
- py: { runtime: 'Python3.9', handler: 'index.main', source: (0, i18n_1.t)('Python 文件推测') },
800968
- php: { runtime: 'Php8.0', handler: 'index.main', source: (0, i18n_1.t)('PHP 文件推测') },
800969
- java: { runtime: 'Java11', handler: 'example.Hello::mainHandler', source: (0, i18n_1.t)('Java 文件推测') },
800970
- go: { runtime: 'Go1', handler: 'main', source: (0, i18n_1.t)('Go 文件推测') }
800971
- };
800972
- const typeConfig = typeConfigMap[maxType[0]];
800973
- if (!typeConfig) {
800974
- return null;
800975
- }
800976
- return {
800977
- config: Object.assign(Object.assign(Object.assign({ name: funcName }, constant_1.DefaultFunctionDeployConfig), { runtime: typeConfig.runtime, handler: typeConfig.handler }), (httpFn ? { type: 'HTTP' } : {})),
800978
- source: typeConfig.source
800979
- };
800980
- }
800981
- catch (e) {
800982
- return null;
800983
- }
800984
- }
800985
- function getConfigSourceDescription(targetDir) {
800986
- const result = inferFunctionConfig({ targetDir, name: 'temp' });
800987
- return (result === null || result === void 0 ? void 0 : result.source) || (0, i18n_1.t)('默认配置');
800988
- }
800989
- exports.getConfigSourceDescription = getConfigSourceDescription;
800990
800830
 
800991
800831
 
800992
800832
  /***/ }),
@@ -834988,10 +834828,6 @@ let FunctionDeploy = class FunctionDeploy extends common_1.Command {
834988
834828
  {
834989
834829
  flags: '--deployMode <deployMode>',
834990
834830
  desc: (0, i18n_1.t)('代码上传方式:cos(通过 COS 上传)或 zip(直接 ZIP 上传),默认自动选择')
834991
- },
834992
- {
834993
- flags: '--yes',
834994
- desc: (0, i18n_1.t)('跳过交互确认,使用推测或默认配置自动部署')
834995
834831
  }
834996
834832
  ],
834997
834833
  desc: (0, i18n_1.t)('部署云函数'),
@@ -835003,7 +834839,7 @@ let FunctionDeploy = class FunctionDeploy extends common_1.Command {
835003
834839
  return __awaiter(this, void 0, void 0, function* () {
835004
834840
  let { envId, config, options } = ctx;
835005
834841
  const { functions } = config;
835006
- const { force, codeSecret, path: access, all, dir, httpFn, ws, deployMode, yes } = options;
834842
+ const { force, codeSecret, path: access, all, dir, httpFn, ws, deployMode } = options;
835007
834843
  const name = params === null || params === void 0 ? void 0 : params[0];
835008
834844
  this.validateOptions({ deployMode, access }, log);
835009
834845
  const isUnresolvedEnvId = !envId || envId.startsWith('{{');
@@ -835023,12 +834859,12 @@ let FunctionDeploy = class FunctionDeploy extends common_1.Command {
835023
834859
  if (hasConfig) {
835024
834860
  return this.deployWithConfig({
835025
834861
  name, dir, envId, force, codeSecret, access, httpFn, ws, deployMode,
835026
- all, functions, functionRootPath, yes, log
834862
+ all, functions, functionRootPath, log
835027
834863
  });
835028
834864
  }
835029
834865
  else {
835030
834866
  return this.deployWithoutConfig({
835031
- name, dir, envId, force, codeSecret, access, httpFn, ws, deployMode, yes, log
834867
+ name, dir, envId, force, codeSecret, access, httpFn, ws, deployMode, log
835032
834868
  });
835033
834869
  }
835034
834870
  });
@@ -835047,11 +834883,11 @@ let FunctionDeploy = class FunctionDeploy extends common_1.Command {
835047
834883
  }
835048
834884
  deployWithConfig(options) {
835049
834885
  return __awaiter(this, void 0, void 0, function* () {
835050
- const { name, dir, envId, force, codeSecret, access, httpFn, ws, deployMode, all, functions, functionRootPath, yes, log } = options;
834886
+ const { name, dir, envId, force, codeSecret, access, httpFn, ws, deployMode, all, functions, functionRootPath, log } = options;
835051
834887
  if (name) {
835052
834888
  return this.deploySingleWithConfig({
835053
834889
  name, dir, envId, force, codeSecret, access, httpFn, ws, deployMode,
835054
- functions, functionRootPath, yes, log
834890
+ functions, functionRootPath, log
835055
834891
  });
835056
834892
  }
835057
834893
  if (dir) {
@@ -835059,13 +834895,13 @@ let FunctionDeploy = class FunctionDeploy extends common_1.Command {
835059
834895
  }
835060
834896
  return this.deployAllFunction({
835061
834897
  all, envId, force, access, functions, codeSecret,
835062
- functionRootPath, httpFn, ws, deployMode, yes, log
834898
+ functionRootPath, httpFn, ws, deployMode, log
835063
834899
  });
835064
834900
  });
835065
834901
  }
835066
834902
  deploySingleWithConfig(options) {
835067
834903
  return __awaiter(this, void 0, void 0, function* () {
835068
- const { name, dir, envId, force, codeSecret, access, httpFn, ws, deployMode, functions, functionRootPath, yes, log } = options;
834904
+ const { name, dir, envId, force, codeSecret, access, httpFn, ws, deployMode, functions, functionRootPath, log } = options;
835069
834905
  let func = functions === null || functions === void 0 ? void 0 : functions.find((item) => item.name === name);
835070
834906
  let funcPath;
835071
834907
  if (dir) {
@@ -835088,32 +834924,21 @@ let FunctionDeploy = class FunctionDeploy extends common_1.Command {
835088
834924
  }
835089
834925
  if (!func) {
835090
834926
  log.warn((0, i18n_1.t)('配置文件中未找到函数 [{{name}}] 的配置', { name }));
835091
- if (yes) {
835092
- const inferredConfig = this.inferFunctionConfig(httpFn, funcPath);
835093
- const runtime = (inferredConfig === null || inferredConfig === void 0 ? void 0 : inferredConfig.runtime) || (yield this.getDefaultRuntime(funcPath));
835094
- const defaultFunc = Object.assign(Object.assign(Object.assign({ name }, constant_1.DefaultFunctionDeployConfig), { runtime }), (inferredConfig ? { handler: inferredConfig.handler } : {}));
835095
- log.info((0, i18n_1.t)('🚀 --yes 模式:自动使用以下配置部署:'));
835096
- const sourceDesc = inferredConfig ? this.getConfigSourceDescription(funcPath) : (0, i18n_1.t)('默认配置');
835097
- this.printFunctionConfig(defaultFunc, log, sourceDesc);
835098
- func = defaultFunc;
835099
- }
835100
- else {
835101
- const runtime = yield this.selectRuntime();
835102
- const defaultFunc = Object.assign(Object.assign({ name }, constant_1.DefaultFunctionDeployConfig), { runtime });
835103
- log.info((0, i18n_1.t)('将使用以下默认配置:'));
835104
- this.printFunctionConfig(defaultFunc, log, (0, i18n_1.t)('默认配置'));
835105
- const { confirm } = yield inquirer_1.default.prompt({
835106
- type: 'confirm',
835107
- name: 'confirm',
835108
- message: (0, i18n_1.t)('是否使用默认配置继续部署?'),
835109
- default: false
835110
- });
835111
- if (!confirm) {
835112
- log.info((0, i18n_1.t)('已取消部署,请在配置文件中添加函数 [{{name}}] 的配置后重试', { name }));
835113
- return;
835114
- }
835115
- func = defaultFunc;
834927
+ const runtime = yield this.selectRuntime();
834928
+ const defaultFunc = Object.assign(Object.assign({ name }, constant_1.DefaultFunctionDeployConfig), { runtime });
834929
+ log.info((0, i18n_1.t)('将使用以下默认配置:'));
834930
+ this.printFunctionConfig(defaultFunc, log);
834931
+ const { confirm } = yield inquirer_1.default.prompt({
834932
+ type: 'confirm',
834933
+ name: 'confirm',
834934
+ message: (0, i18n_1.t)('是否使用默认配置继续部署?'),
834935
+ default: false
834936
+ });
834937
+ if (!confirm) {
834938
+ log.info((0, i18n_1.t)('已取消部署,请在配置文件中添加函数 [{{name}}] 的配置后重试', { name }));
834939
+ return;
835116
834940
  }
834941
+ func = defaultFunc;
835117
834942
  }
835118
834943
  if (httpFn) {
835119
834944
  func = Object.assign(Object.assign({}, func), { type: 'HTTP' });
@@ -835123,13 +834948,13 @@ let FunctionDeploy = class FunctionDeploy extends common_1.Command {
835123
834948
  }
835124
834949
  return this.doDeploySingleFunction({
835125
834950
  func, envId, force, codeSecret, access, deployMode,
835126
- functionRootPath, functionPath: funcPath, yes, log
834951
+ functionRootPath, functionPath: funcPath, log
835127
834952
  });
835128
834953
  });
835129
834954
  }
835130
834955
  deployWithoutConfig(options) {
835131
834956
  return __awaiter(this, void 0, void 0, function* () {
835132
- const { name, dir, envId, force, codeSecret, access, httpFn, ws, deployMode, yes, log } = options;
834957
+ const { name, dir, envId, force, codeSecret, access, httpFn, ws, deployMode, log } = options;
835133
834958
  let deployDir = process.cwd();
835134
834959
  if (dir) {
835135
834960
  (0, utils_1.checkFullAccess)(dir, true);
@@ -835153,57 +834978,65 @@ let FunctionDeploy = class FunctionDeploy extends common_1.Command {
835153
834978
  if (ws && isInferred) {
835154
834979
  inferredConfig = Object.assign(Object.assign({}, inferredConfig), { type: 'HTTP', protocolType: 'WS' });
835155
834980
  }
835156
- const sourceDesc = isInferred ? this.getConfigSourceDescription(deployDir) : (0, i18n_1.t)('默认配置');
835157
834981
  if (isInferred) {
835158
- log.info((0, i18n_1.t)(' 从项目文件推测出以下配置:'));
834982
+ log.info((0, i18n_1.t)(' package.json 推测出以下配置:'));
835159
834983
  }
835160
834984
  else {
835161
- log.info((0, i18n_1.t)('未推测出配置,将使用默认配置:'));
834985
+ log.info((0, i18n_1.t)('未推测出配置,将使用默认配置:'));
834986
+ }
834987
+ this.printFunctionConfig(inferredConfig, log);
834988
+ const { action } = yield inquirer_1.default.prompt({
834989
+ type: 'list',
834990
+ name: 'action',
834991
+ message: (0, i18n_1.t)('请选择操作'),
834992
+ choices: [
834993
+ { name: (0, i18n_1.t)('使用当前配置部署'), value: 'deploy' },
834994
+ { name: (0, i18n_1.t)('手动输入配置'), value: 'manual' },
834995
+ { name: (0, i18n_1.t)('退出'), value: 'exit' }
834996
+ ]
834997
+ });
834998
+ if (action === 'exit') {
834999
+ log.info((0, i18n_1.t)('已取消部署'));
835000
+ return;
835162
835001
  }
835163
- this.printFunctionConfig(inferredConfig, log, sourceDesc);
835164
835002
  let func;
835165
- if (yes) {
835166
- log.info((0, i18n_1.t)('🚀 --yes 模式:跳过交互,自动部署'));
835167
- func = inferredConfig;
835003
+ if (action === 'manual') {
835004
+ func = yield this.promptFunctionConfig(inferredConfig, httpFn);
835168
835005
  }
835169
835006
  else {
835170
- const { action } = yield inquirer_1.default.prompt({
835171
- type: 'list',
835172
- name: 'action',
835173
- message: (0, i18n_1.t)('请选择操作'),
835174
- choices: [
835175
- { name: (0, i18n_1.t)('使用当前配置部署'), value: 'deploy' },
835176
- { name: (0, i18n_1.t)('手动输入配置'), value: 'manual' },
835177
- { name: (0, i18n_1.t)('退出'), value: 'exit' }
835178
- ]
835179
- });
835180
- if (action === 'exit') {
835181
- log.info((0, i18n_1.t)('已取消部署'));
835182
- return;
835183
- }
835184
- if (action === 'manual') {
835185
- func = yield this.promptFunctionConfig(inferredConfig, httpFn, ws);
835186
- }
835187
- else {
835188
- func = inferredConfig;
835189
- }
835007
+ func = inferredConfig;
835190
835008
  }
835191
835009
  return this.doDeploySingleFunction({
835192
835010
  func, envId, force, codeSecret, access, deployMode,
835193
- functionRootPath: deployDir, functionPath: '.', yes, log
835011
+ functionRootPath: deployDir, functionPath: '.', log
835194
835012
  });
835195
835013
  });
835196
835014
  }
835197
835015
  inferFunctionConfig(httpFn, deployDir) {
835198
835016
  const targetDir = deployDir || process.cwd();
835199
- const result = (0, function_1.inferFunctionConfig)({ targetDir, httpFn });
835200
- return (result === null || result === void 0 ? void 0 : result.config) || null;
835017
+ const packageJsonPath = path_1.default.join(targetDir, 'package.json');
835018
+ if (!fs_1.default.existsSync(packageJsonPath)) {
835019
+ return null;
835020
+ }
835021
+ try {
835022
+ const packageJson = JSON.parse(fs_1.default.readFileSync(packageJsonPath, 'utf-8'));
835023
+ if (!packageJson.name) {
835024
+ return null;
835025
+ }
835026
+ let handler = constant_1.DefaultFunctionDeployConfig.handler;
835027
+ if (packageJson.main) {
835028
+ const mainFile = path_1.default.basename(packageJson.main).replace(/\.[^.]+$/, '');
835029
+ handler = `${mainFile}.main`;
835030
+ }
835031
+ return Object.assign(Object.assign(Object.assign({ name: packageJson.name }, constant_1.DefaultFunctionDeployConfig), { handler }), (httpFn ? { type: 'HTTP' } : {}));
835032
+ }
835033
+ catch (e) {
835034
+ return null;
835035
+ }
835201
835036
  }
835202
- promptFunctionConfig(defaultConfig, httpFn, ws) {
835037
+ promptFunctionConfig(defaultConfig, httpFn) {
835203
835038
  var _a, _b, _c;
835204
835039
  return __awaiter(this, void 0, void 0, function* () {
835205
- const isHttpFnFromCli = httpFn || ws;
835206
- const isWsFromCli = ws;
835207
835040
  const answers = yield inquirer_1.default.prompt([
835208
835041
  {
835209
835042
  type: 'input',
@@ -835232,49 +835065,62 @@ let FunctionDeploy = class FunctionDeploy extends common_1.Command {
835232
835065
  name: 'handler',
835233
835066
  message: (0, i18n_1.t)('入口函数(格式:文件名.函数名)'),
835234
835067
  default: (answers) => {
835235
- if (defaultConfig.handler) {
835236
- return defaultConfig.handler;
835237
- }
835238
835068
  const selectedRuntime = constant_1.RuntimeOptions.find(r => r.value === answers.runtime);
835239
- return (selectedRuntime === null || selectedRuntime === void 0 ? void 0 : selectedRuntime.handler) || constant_1.DefaultFunctionDeployConfig.handler;
835069
+ return (selectedRuntime === null || selectedRuntime === void 0 ? void 0 : selectedRuntime.handler) || defaultConfig.handler;
835240
835070
  }
835241
835071
  },
835242
835072
  {
835243
835073
  type: 'confirm',
835244
835074
  name: 'isHttpFn',
835245
835075
  message: (0, i18n_1.t)('是否为 HTTP 函数'),
835246
- default: isHttpFnFromCli || defaultConfig.type === 'HTTP',
835247
- when: !isHttpFnFromCli
835076
+ default: httpFn || defaultConfig.type === 'HTTP',
835077
+ when: !httpFn
835248
835078
  },
835249
835079
  {
835250
835080
  type: 'confirm',
835251
835081
  name: 'enableWebSocket',
835252
835082
  message: (0, i18n_1.t)('是否支持 WebSocket 协议'),
835253
- default: isWsFromCli || defaultConfig.protocolType === 'WS',
835254
- when: (answers) => !isWsFromCli && (isHttpFnFromCli || answers.isHttpFn)
835083
+ default: defaultConfig.protocolType === 'WS',
835084
+ when: (answers) => httpFn || answers.isHttpFn
835255
835085
  },
835256
835086
  {
835257
835087
  type: 'number',
835258
835088
  name: 'timeout',
835259
835089
  message: (answers) => {
835260
- const isWs = isWsFromCli || answers.enableWebSocket;
835090
+ const isWs = answers.enableWebSocket;
835261
835091
  return isWs ? (0, i18n_1.t)('超时时间(秒,1-7200)') : (0, i18n_1.t)('超时时间(秒,1-900)');
835262
835092
  },
835263
835093
  default: defaultConfig.timeout,
835094
+ validate: (input, answers) => {
835095
+ const num = Number(input);
835096
+ const isWs = answers.enableWebSocket;
835097
+ const maxTimeout = isWs ? 7200 : 900;
835098
+ if (isNaN(num) || num < 1 || num > maxTimeout) {
835099
+ return isWs ? (0, i18n_1.t)('超时时间必须在 1-7200 秒之间') : (0, i18n_1.t)('超时时间必须在 1-900 秒之间');
835100
+ }
835101
+ return true;
835102
+ }
835264
835103
  },
835265
835104
  {
835266
835105
  type: 'number',
835267
835106
  name: 'idleTimeOut',
835268
835107
  message: (0, i18n_1.t)('空闲超时时间(秒,10-7200,默认15)'),
835269
835108
  default: ((_b = (_a = defaultConfig.protocolParams) === null || _a === void 0 ? void 0 : _a.wsParams) === null || _b === void 0 ? void 0 : _b.idleTimeOut) || 15,
835270
- when: (answers) => isWsFromCli || answers.enableWebSocket,
835109
+ when: (answers) => answers.enableWebSocket,
835110
+ validate: (input) => {
835111
+ const num = Number(input);
835112
+ if (isNaN(num) || num < 10 || num > 7200) {
835113
+ return (0, i18n_1.t)('空闲超时时间必须在 10-7200 秒之间');
835114
+ }
835115
+ return true;
835116
+ }
835271
835117
  },
835272
835118
  {
835273
835119
  type: 'confirm',
835274
835120
  name: 'enableInstanceConcurrency',
835275
835121
  message: (0, i18n_1.t)('是否启用多并发'),
835276
835122
  default: !!defaultConfig.instanceConcurrencyConfig,
835277
- when: (answers) => isHttpFnFromCli || answers.isHttpFn
835123
+ when: (answers) => httpFn || answers.isHttpFn
835278
835124
  },
835279
835125
  {
835280
835126
  type: 'number',
@@ -835310,16 +835156,15 @@ let FunctionDeploy = class FunctionDeploy extends common_1.Command {
835310
835156
  default: defaultConfig.installDependency
835311
835157
  }
835312
835158
  ]);
835313
- const enableWs = isWsFromCli || answers.enableWebSocket;
835314
- const protocolType = enableWs ? 'WS' : undefined;
835315
- const protocolParams = (enableWs && answers.idleTimeOut) ? {
835159
+ const protocolType = answers.enableWebSocket ? 'WS' : undefined;
835160
+ const protocolParams = answers.idleTimeOut ? {
835316
835161
  wsParams: { idleTimeOut: answers.idleTimeOut }
835317
835162
  } : undefined;
835318
835163
  const instanceConcurrencyConfig = answers.enableInstanceConcurrency ? {
835319
835164
  dynamicEnabled: 'FALSE',
835320
835165
  maxConcurrency: answers.maxConcurrency
835321
835166
  } : undefined;
835322
- return Object.assign(Object.assign(Object.assign(Object.assign({ name: answers.name.trim(), runtime: answers.runtime, handler: answers.handler, timeout: answers.timeout, memorySize: answers.memorySize, installDependency: answers.installDependency, ignore: defaultConfig.ignore || constant_1.DefaultFunctionDeployConfig.ignore }, (isHttpFnFromCli || answers.isHttpFn ? { type: 'HTTP' } : {})), (protocolType ? { protocolType } : {})), (protocolParams ? { protocolParams } : {})), (instanceConcurrencyConfig ? { instanceConcurrencyConfig } : {}));
835167
+ return Object.assign(Object.assign(Object.assign(Object.assign({ name: answers.name.trim(), runtime: answers.runtime, handler: answers.handler, timeout: answers.timeout, memorySize: answers.memorySize, installDependency: answers.installDependency, ignore: defaultConfig.ignore || constant_1.DefaultFunctionDeployConfig.ignore }, (httpFn || answers.isHttpFn ? { type: 'HTTP' } : {})), (protocolType ? { protocolType } : {})), (protocolParams ? { protocolParams } : {})), (instanceConcurrencyConfig ? { instanceConcurrencyConfig } : {}));
835323
835168
  });
835324
835169
  }
835325
835170
  promptFunctionName() {
@@ -835338,11 +835183,8 @@ let FunctionDeploy = class FunctionDeploy extends common_1.Command {
835338
835183
  return funcName.trim();
835339
835184
  });
835340
835185
  }
835341
- printFunctionConfig(func, log, source) {
835186
+ printFunctionConfig(func, log) {
835342
835187
  var _a, _b;
835343
- if (source) {
835344
- log.info((0, i18n_1.t)('配置来源:{{source}}', { source }));
835345
- }
835346
835188
  log.info((0, i18n_1.t)(' - 函数名称:{{name}}', { name: func.name }));
835347
835189
  log.info((0, i18n_1.t)(' - 运行时:{{runtime}}', { runtime: func.runtime }));
835348
835190
  log.info((0, i18n_1.t)(' - 入口函数:{{handler}}', { handler: func.handler }));
@@ -835365,65 +835207,10 @@ let FunctionDeploy = class FunctionDeploy extends common_1.Command {
835365
835207
  log.info((0, i18n_1.t)(' - 单实例最大并发数:{{num}}', { num: func.instanceConcurrencyConfig.maxConcurrency }));
835366
835208
  }
835367
835209
  }
835368
- else {
835369
- log.info((0, i18n_1.t)(' - 函数类型:Event(事件触发)'));
835370
- }
835371
- if (func.envVariables && Object.keys(func.envVariables).length > 0) {
835372
- log.info((0, i18n_1.t)(' - 环境变量:{{count}} 个', { count: Object.keys(func.envVariables).length }));
835373
- }
835374
- if (func.vpc) {
835375
- log.info((0, i18n_1.t)(' - VPC 配置:已配置'));
835376
- }
835377
- }
835378
- getConfigSourceDescription(targetDir) {
835379
- if (fs_1.default.existsSync(path_1.default.join(targetDir, 'package.json'))) {
835380
- return (0, i18n_1.t)('Node.js 项目(package.json)');
835381
- }
835382
- if (fs_1.default.existsSync(path_1.default.join(targetDir, 'requirements.txt'))) {
835383
- return (0, i18n_1.t)('Python 项目(requirements.txt)');
835384
- }
835385
- if (fs_1.default.existsSync(path_1.default.join(targetDir, 'setup.py'))) {
835386
- return (0, i18n_1.t)('Python 项目(setup.py)');
835387
- }
835388
- if (fs_1.default.existsSync(path_1.default.join(targetDir, 'pyproject.toml'))) {
835389
- return (0, i18n_1.t)('Python 项目(pyproject.toml)');
835390
- }
835391
- if (fs_1.default.existsSync(path_1.default.join(targetDir, 'composer.json'))) {
835392
- return (0, i18n_1.t)('PHP 项目(composer.json)');
835393
- }
835394
- if (fs_1.default.existsSync(path_1.default.join(targetDir, 'pom.xml'))) {
835395
- return (0, i18n_1.t)('Java 项目(pom.xml)');
835396
- }
835397
- if (fs_1.default.existsSync(path_1.default.join(targetDir, 'build.gradle'))) {
835398
- return (0, i18n_1.t)('Java 项目(build.gradle)');
835399
- }
835400
- try {
835401
- const files = fs_1.default.readdirSync(targetDir);
835402
- const fileTypes = {
835403
- js: files.filter(f => f.endsWith('.js')).length,
835404
- ts: files.filter(f => f.endsWith('.ts')).length,
835405
- py: files.filter(f => f.endsWith('.py')).length,
835406
- php: files.filter(f => f.endsWith('.php')).length,
835407
- java: files.filter(f => f.endsWith('.java')).length
835408
- };
835409
- const maxType = Object.entries(fileTypes).reduce((a, b) => fileTypes[a[0]] > fileTypes[b[0]] ? a : b);
835410
- if (maxType[1] > 0) {
835411
- switch (maxType[0]) {
835412
- case 'js': return (0, i18n_1.t)('JavaScript 文件推测');
835413
- case 'ts': return (0, i18n_1.t)('TypeScript 文件推测');
835414
- case 'py': return (0, i18n_1.t)('Python 文件推测');
835415
- case 'php': return (0, i18n_1.t)('PHP 文件推测');
835416
- case 'java': return (0, i18n_1.t)('Java 文件推测');
835417
- }
835418
- }
835419
- }
835420
- catch (e) {
835421
- }
835422
- return (0, i18n_1.t)('默认配置');
835423
835210
  }
835424
835211
  doDeploySingleFunction(options) {
835425
835212
  return __awaiter(this, void 0, void 0, function* () {
835426
- const { func, envId, force, codeSecret, access, deployMode, functionRootPath, functionPath, yes, log } = options;
835213
+ const { func, envId, force, codeSecret, access, deployMode, functionRootPath, functionPath, log } = options;
835427
835214
  if (func.type === 'HTTP') {
835428
835215
  const funcPath = functionPath === '.' ? process.cwd() : (functionPath || path_1.default.join(functionRootPath, func.name));
835429
835216
  const shouldContinue = yield (0, function_1.checkAndCreateBootstrap)(funcPath, func);
@@ -835457,7 +835244,6 @@ let FunctionDeploy = class FunctionDeploy extends common_1.Command {
835457
835244
  func,
835458
835245
  accessPath: access,
835459
835246
  functionPath,
835460
- yes,
835461
835247
  logger: log
835462
835248
  });
835463
835249
  }
@@ -835469,7 +835255,7 @@ let FunctionDeploy = class FunctionDeploy extends common_1.Command {
835469
835255
  }
835470
835256
  deployAllFunction(options) {
835471
835257
  return __awaiter(this, void 0, void 0, function* () {
835472
- let { functions = [], envId, force, codeSecret, functionRootPath, all, access, httpFn, ws, deployMode, yes, log } = options;
835258
+ let { functions = [], envId, force, codeSecret, functionRootPath, all, access, httpFn, ws, deployMode, log } = options;
835473
835259
  if (!functions || functions.length === 0) {
835474
835260
  functions = this.scanFunctionDirectory(functionRootPath, httpFn);
835475
835261
  if (functions.length > 0) {
@@ -835486,7 +835272,7 @@ let FunctionDeploy = class FunctionDeploy extends common_1.Command {
835486
835272
  throw new error_1.CloudBaseError((0, i18n_1.t)('未找到云函数配置,请在 cloudbaserc.json 中配置 functions 字段,或使用 tcb fn deploy <函数名> 指定要部署的函数'));
835487
835273
  }
835488
835274
  let selectedFunctions = functions;
835489
- if (!all && !yes) {
835275
+ if (!all) {
835490
835276
  const choices = functions.map((func) => ({
835491
835277
  name: `${func.name}${func.type === 'HTTP' ? ' (HTTP)' : ''}${func.protocolType === 'WS' ? ' (WS)' : ''}`,
835492
835278
  value: func.name,
@@ -835519,54 +835305,7 @@ let FunctionDeploy = class FunctionDeploy extends common_1.Command {
835519
835305
  throw new error_1.CloudBaseError((0, i18n_1.t)('没有选择任何云函数'));
835520
835306
  }
835521
835307
  }
835522
- else if (yes) {
835523
- log.info((0, i18n_1.t)('🚀 --yes 模式:自动部署全部 {{count}} 个函数', { count: functions.length }));
835524
- }
835525
835308
  const loading = (0, utils_1.loadingFactory)();
835526
- let functionsToOverwrite = new Set();
835527
- if (!force && !yes) {
835528
- loading.start((0, i18n_1.t)('正在检查云函数状态...'));
835529
- const functionService = yield (0, function_2.getFunctionService)(envId);
835530
- const existingFunctions = [];
835531
- const checkTasks = selectedFunctions.map((func) => __awaiter(this, void 0, void 0, function* () {
835532
- try {
835533
- const detail = yield functionService.getFunctionDetail(func.name, codeSecret);
835534
- if (detail) {
835535
- return func.name;
835536
- }
835537
- }
835538
- catch (e) {
835539
- }
835540
- return null;
835541
- }));
835542
- const checkResults = yield Promise.all(checkTasks);
835543
- checkResults.forEach(name => {
835544
- if (name)
835545
- existingFunctions.push(name);
835546
- });
835547
- loading.stop();
835548
- if (existingFunctions.length > 0) {
835549
- log.info((0, i18n_1.t)('发现 {{count}} 个已存在的云函数:', { count: existingFunctions.length }));
835550
- existingFunctions.forEach(name => {
835551
- log.info(` - ${name}`);
835552
- });
835553
- const { toOverwrite } = yield inquirer_1.default.prompt({
835554
- type: 'checkbox',
835555
- name: 'toOverwrite',
835556
- message: (0, i18n_1.t)('请选择要覆盖更新的函数(未选中的将跳过部署)'),
835557
- choices: existingFunctions.map(name => ({
835558
- name,
835559
- value: name,
835560
- checked: true
835561
- }))
835562
- });
835563
- functionsToOverwrite = new Set(toOverwrite);
835564
- const skippedByUser = existingFunctions.filter(name => !functionsToOverwrite.has(name));
835565
- if (skippedByUser.length > 0) {
835566
- log.info((0, i18n_1.t)('以下函数将跳过部署:{{names}}', { names: skippedByUser.join(', ') }));
835567
- }
835568
- }
835569
- }
835570
835309
  const tasks = selectedFunctions.map((func) => () => __awaiter(this, void 0, void 0, function* () {
835571
835310
  let funcWithType = httpFn ? Object.assign(Object.assign({}, func), { type: 'HTTP' }) : func;
835572
835311
  if (ws) {
@@ -835577,13 +835316,13 @@ let FunctionDeploy = class FunctionDeploy extends common_1.Command {
835577
835316
  : path_1.default.join(functionRootPath, func.name);
835578
835317
  if (!fs_1.default.existsSync(funcPath)) {
835579
835318
  log.error((0, i18n_1.t)('未找到函数 [{{name}}] 的目录:{{path}},已跳过', { name: func.name, path: funcPath }));
835580
- return { status: 'skipped', name: func.name };
835319
+ return;
835581
835320
  }
835582
835321
  if (funcWithType.type === 'HTTP') {
835583
835322
  const shouldContinue = yield (0, function_1.checkAndCreateBootstrap)(funcPath, funcWithType);
835584
835323
  if (!shouldContinue) {
835585
835324
  log.warn((0, i18n_1.t)('[{{name}}] 已跳过部署', { name: func.name }));
835586
- return { status: 'skipped', name: func.name };
835325
+ return;
835587
835326
  }
835588
835327
  }
835589
835328
  loading.start((0, i18n_1.t)('云函数部署中'));
@@ -835599,28 +835338,19 @@ let FunctionDeploy = class FunctionDeploy extends common_1.Command {
835599
835338
  deployMode
835600
835339
  });
835601
835340
  loading.succeed((0, i18n_1.t)('[{{name}}] 云函数部署成功', { name: func.name }));
835602
- return { status: 'success', name: func.name };
835603
835341
  }
835604
835342
  catch (e) {
835605
835343
  loading.stop();
835606
- try {
835607
- const result = yield this.handleDeployFail(e, {
835608
- func: funcWithType,
835609
- envId,
835610
- force,
835611
- codeSecret,
835612
- functionRootPath,
835613
- functionPath: func.dir ? funcPath : undefined,
835614
- accessPath: access,
835615
- yes: yes || functionsToOverwrite.has(func.name),
835616
- batchMode: true,
835617
- logger: log
835618
- });
835619
- return { status: result || 'error', name: func.name };
835620
- }
835621
- catch (handleError) {
835622
- return { status: 'error', name: func.name, error: handleError };
835623
- }
835344
+ yield this.handleDeployFail(e, {
835345
+ func: funcWithType,
835346
+ envId,
835347
+ force,
835348
+ codeSecret,
835349
+ functionRootPath,
835350
+ functionPath: func.dir ? funcPath : undefined,
835351
+ accessPath: access,
835352
+ logger: log
835353
+ });
835624
835354
  }
835625
835355
  }));
835626
835356
  if (tasks.length > 5) {
@@ -835628,58 +835358,26 @@ let FunctionDeploy = class FunctionDeploy extends common_1.Command {
835628
835358
  }
835629
835359
  const asyncTaskController = new utils_1.AsyncTaskParallelController(5, 50);
835630
835360
  asyncTaskController.loadTasks(tasks);
835631
- const rawResults = yield asyncTaskController.run();
835632
- const results = rawResults.map((r, index) => {
835633
- var _a;
835634
- if (r instanceof Error) {
835635
- return { status: 'error', name: ((_a = selectedFunctions[index]) === null || _a === void 0 ? void 0 : _a.name) || 'unknown', error: r };
835636
- }
835637
- return r;
835638
- });
835639
- const successCount = results.filter(r => (r === null || r === void 0 ? void 0 : r.status) === 'success').length;
835640
- const skippedCount = results.filter(r => (r === null || r === void 0 ? void 0 : r.status) === 'skipped').length;
835641
- const cancelledCount = results.filter(r => (r === null || r === void 0 ? void 0 : r.status) === 'cancelled').length;
835642
- const errorCount = results.filter(r => (r === null || r === void 0 ? void 0 : r.status) === 'error').length;
835643
- if (successCount > 0) {
835644
- log.success((0, i18n_1.t)('成功部署 {{count}} 个函数', { count: successCount }));
835645
- }
835646
- if (skippedCount > 0) {
835647
- log.warn((0, i18n_1.t)('跳过 {{count}} 个函数', { count: skippedCount }));
835648
- }
835649
- if (cancelledCount > 0) {
835650
- log.info((0, i18n_1.t)('取消部署 {{count}} 个函数', { count: cancelledCount }));
835651
- }
835652
- if (errorCount > 0) {
835653
- log.error((0, i18n_1.t)('{{count}} 个云函数部署失败', { count: errorCount }));
835654
- let envNotFoundError = null;
835655
- results.filter(r => (r === null || r === void 0 ? void 0 : r.status) === 'error').forEach((r) => {
835656
- var _a;
835657
- if ((_a = r === null || r === void 0 ? void 0 : r.error) === null || _a === void 0 ? void 0 : _a.message) {
835658
- log.error(` - [${r.name}] ${r.error.message}`);
835659
- if (r.error.message.includes('Environment') && r.error.message.includes('not found') && !envNotFoundError) {
835660
- envNotFoundError = r.error;
835661
- }
835361
+ const results = yield asyncTaskController.run();
835362
+ const success = results.filter((_) => !_);
835363
+ log.success((0, i18n_1.t)('成功部署 {{count}} 个函数', { count: success === null || success === void 0 ? void 0 : success.length }));
835364
+ const errors = results.filter((_) => _);
835365
+ if (errors === null || errors === void 0 ? void 0 : errors.length) {
835366
+ log.error((0, i18n_1.t)('{{count}} 个云函数部署失败', { count: errors === null || errors === void 0 ? void 0 : errors.length }));
835367
+ errors.forEach((err) => {
835368
+ if (err === null || err === void 0 ? void 0 : err.message) {
835369
+ log.error(` - ${err.message}`);
835662
835370
  }
835663
835371
  });
835664
- if (envNotFoundError) {
835665
- throw envNotFoundError;
835666
- }
835667
- }
835668
- if (successCount === 0 && errorCount === 0 && skippedCount === 0 && cancelledCount === 0) {
835669
- log.info((0, i18n_1.t)('没有函数被部署'));
835670
835372
  }
835671
835373
  });
835672
835374
  }
835673
835375
  handleDeployFail(e, options) {
835674
835376
  return __awaiter(this, void 0, void 0, function* () {
835675
- const { envId, codeSecret, functionRootPath, func: originalFunc, functionPath, accessPath, force: forceOverwrite, yes, batchMode, logger: log } = options;
835377
+ const { envId, codeSecret, functionRootPath, func: originalFunc, functionPath, accessPath, force: forceOverwrite, logger: log } = options;
835676
835378
  let func = originalFunc;
835677
835379
  const loading = (0, utils_1.loadingFactory)();
835678
- const isResourceInUseError = e.code === 'ResourceInUse.FunctionName'
835679
- || e.code === 'ResourceInUse.Function'
835680
- || (e.message && e.message.includes('ResourceInUse.FunctionName'))
835681
- || (e.message && e.message.includes('ResourceInUse.Function'));
835682
- if (isResourceInUseError) {
835380
+ if (e.code === 'ResourceInUse.FunctionName' || e.code === 'ResourceInUse.Function') {
835683
835381
  const functionService = yield (0, function_2.getFunctionService)(envId);
835684
835382
  const existingFunction = yield functionService.getFunctionDetail(func.name, codeSecret);
835685
835383
  const existingType = (existingFunction === null || existingFunction === void 0 ? void 0 : existingFunction.Type) || 'Event';
@@ -835690,7 +835388,7 @@ let FunctionDeploy = class FunctionDeploy extends common_1.Command {
835690
835388
  existingType,
835691
835389
  newType
835692
835390
  }));
835693
- return 'error';
835391
+ return;
835694
835392
  }
835695
835393
  const existingProtocolType = (existingFunction === null || existingFunction === void 0 ? void 0 : existingFunction.ProtocolType) || '';
835696
835394
  const newProtocolType = func.protocolType !== undefined ? func.protocolType : existingProtocolType;
@@ -835700,10 +835398,10 @@ let FunctionDeploy = class FunctionDeploy extends common_1.Command {
835700
835398
  existingProtocolType: existingProtocolType || '无',
835701
835399
  newProtocolType: newProtocolType || '无'
835702
835400
  }));
835703
- return 'error';
835401
+ return;
835704
835402
  }
835705
835403
  func = Object.assign(Object.assign({}, func), { type: newType, protocolType: newProtocolType || undefined });
835706
- let shouldForce = forceOverwrite || yes;
835404
+ let shouldForce = forceOverwrite;
835707
835405
  if (!shouldForce) {
835708
835406
  const answer = yield inquirer_1.default.prompt({
835709
835407
  type: 'confirm',
@@ -835713,8 +835411,9 @@ let FunctionDeploy = class FunctionDeploy extends common_1.Command {
835713
835411
  });
835714
835412
  shouldForce = answer.force;
835715
835413
  }
835414
+ const { triggers } = func;
835716
835415
  if (shouldForce) {
835717
- loading.start(batchMode ? (0, i18n_1.t)('云函数 [{{name}}] 更新部署中...', { name: func.name }) : (0, i18n_1.t)('云函数更新部署中...'));
835416
+ loading.start((0, i18n_1.t)('云函数更新部署中...'));
835718
835417
  try {
835719
835418
  yield (0, function_2.updateFunctionCode)({
835720
835419
  func,
@@ -835725,7 +835424,7 @@ let FunctionDeploy = class FunctionDeploy extends common_1.Command {
835725
835424
  });
835726
835425
  const success = yield this.waitForFunctionReady(envId, func.name, loading);
835727
835426
  if (!success) {
835728
- return 'error';
835427
+ return;
835729
835428
  }
835730
835429
  loading.succeed((0, i18n_1.t)('[{{name}}] 云函数配置更新中...', { name: func.name }));
835731
835430
  yield (0, function_2.updateFunctionConfig)({
@@ -835734,10 +835433,7 @@ let FunctionDeploy = class FunctionDeploy extends common_1.Command {
835734
835433
  config: func
835735
835434
  });
835736
835435
  loading.succeed((0, i18n_1.t)('[{{name}}] 云函数更新成功!', { name: func.name }));
835737
- if (!batchMode) {
835738
- yield this.printSuccessTips(envId);
835739
- }
835740
- return 'success';
835436
+ yield this.printSuccessTips(envId);
835741
835437
  }
835742
835438
  catch (e) {
835743
835439
  loading.stop();
@@ -835745,9 +835441,9 @@ let FunctionDeploy = class FunctionDeploy extends common_1.Command {
835745
835441
  }
835746
835442
  }
835747
835443
  else {
835748
- (log || utils_1.logger).info(batchMode ? (0, i18n_1.t)('[{{name}}] 已跳过部署', { name: func.name }) : (0, i18n_1.t)('已取消部署'));
835749
- return 'cancelled';
835444
+ (log || utils_1.logger).info((0, i18n_1.t)('已取消部署'));
835750
835445
  }
835446
+ return;
835751
835447
  }
835752
835448
  throw e;
835753
835449
  });
@@ -835865,59 +835561,6 @@ let FunctionDeploy = class FunctionDeploy extends common_1.Command {
835865
835561
  return runtime;
835866
835562
  });
835867
835563
  }
835868
- getDefaultRuntime(targetDir) {
835869
- var _a;
835870
- return __awaiter(this, void 0, void 0, function* () {
835871
- const dir = targetDir || process.cwd();
835872
- if (fs_1.default.existsSync(path_1.default.join(dir, 'package.json'))) {
835873
- try {
835874
- const packageJson = JSON.parse(fs_1.default.readFileSync(path_1.default.join(dir, 'package.json'), 'utf-8'));
835875
- if ((_a = packageJson.engines) === null || _a === void 0 ? void 0 : _a.node) {
835876
- const nodeVersion = packageJson.engines.node;
835877
- if (nodeVersion.includes('20'))
835878
- return 'Nodejs20.19';
835879
- if (nodeVersion.includes('16'))
835880
- return 'Nodejs16.13';
835881
- }
835882
- }
835883
- catch (e) {
835884
- }
835885
- return constant_1.DefaultFunctionDeployConfig.runtime;
835886
- }
835887
- const pythonFiles = ['requirements.txt', 'setup.py', 'pyproject.toml'];
835888
- if (pythonFiles.some(file => fs_1.default.existsSync(path_1.default.join(dir, file)))) {
835889
- return 'Python3.9';
835890
- }
835891
- if (fs_1.default.existsSync(path_1.default.join(dir, 'composer.json')) ||
835892
- fs_1.default.readdirSync(dir).some(file => file.endsWith('.php'))) {
835893
- return 'Php8.0';
835894
- }
835895
- const javaFiles = ['pom.xml', 'build.gradle', 'build.gradle.kts'];
835896
- if (javaFiles.some(file => fs_1.default.existsSync(path_1.default.join(dir, file)))) {
835897
- return 'Java11';
835898
- }
835899
- try {
835900
- const files = fs_1.default.readdirSync(dir);
835901
- const fileTypes = {
835902
- js: files.filter(f => f.endsWith('.js')).length,
835903
- ts: files.filter(f => f.endsWith('.ts')).length,
835904
- py: files.filter(f => f.endsWith('.py')).length,
835905
- php: files.filter(f => f.endsWith('.php')).length,
835906
- java: files.filter(f => f.endsWith('.java')).length
835907
- };
835908
- const maxType = Object.entries(fileTypes).reduce((a, b) => fileTypes[a[0]] > fileTypes[b[0]] ? a : b);
835909
- switch (maxType[0]) {
835910
- case 'py': return 'Python3.9';
835911
- case 'php': return 'Php8.0';
835912
- case 'java': return 'Java11';
835913
- default: return constant_1.DefaultFunctionDeployConfig.runtime;
835914
- }
835915
- }
835916
- catch (e) {
835917
- return constant_1.DefaultFunctionDeployConfig.runtime;
835918
- }
835919
- });
835920
- }
835921
835564
  };
835922
835565
  __decorate([
835923
835566
  (0, decorators_1.InjectParams)(),
@@ -864520,6 +864163,7 @@ module.exports = exports
864520
864163
 
864521
864164
  Object.defineProperty(exports, "__esModule", ({ value: true }));
864522
864165
  exports.detectIndent = void 0;
864166
+ // https://github.com/sindresorhus/detect-indent/blob/master/index.js
864523
864167
  const INDENT_REGEX = /^(?:( )+|\t+)/;
864524
864168
  const INDENT_TYPE_SPACE = 'space';
864525
864169
  const INDENT_TYPE_TAB = 'tab';
@@ -864530,6 +864174,7 @@ function makeIndentsMap(string) {
864530
864174
  let key;
864531
864175
  for (const line of string.split(/\n/g)) {
864532
864176
  if (!line) {
864177
+ // Ignore empty lines
864533
864178
  continue;
864534
864179
  }
864535
864180
  let indent;
@@ -864556,16 +864201,19 @@ function makeIndentsMap(string) {
864556
864201
  weight = 0;
864557
864202
  const indentDifference = indent - previousSize;
864558
864203
  previousSize = indent;
864204
+ // Previous line have same indent?
864559
864205
  if (indentDifference === 0) {
864560
864206
  weight++;
864207
+ // We use the key from previous loop
864561
864208
  }
864562
864209
  else {
864563
864210
  const absoluteIndentDifference = indentDifference > 0 ? indentDifference : -indentDifference;
864564
864211
  key = encodeIndentsKey(indentType, absoluteIndentDifference);
864565
864212
  }
864213
+ // Update the stats
864566
864214
  entry = indents.get(key);
864567
864215
  if (entry === undefined) {
864568
- entry = [1, 0];
864216
+ entry = [1, 0]; // Init
864569
864217
  }
864570
864218
  else {
864571
864219
  entry = [++entry[0], entry[1] + weight];
@@ -864575,16 +864223,20 @@ function makeIndentsMap(string) {
864575
864223
  }
864576
864224
  return indents;
864577
864225
  }
864226
+ // Encode the indent type and amount as a string (e.g. 's4') for use as a compound key in the indents Map.
864578
864227
  function encodeIndentsKey(indentType, indentAmount) {
864579
864228
  const typeCharacter = indentType === INDENT_TYPE_SPACE ? 's' : 't';
864580
864229
  return typeCharacter + String(indentAmount);
864581
864230
  }
864231
+ // Extract the indent type and amount from a key of the indents Map.
864582
864232
  function decodeIndentsKey(indentsKey) {
864583
864233
  const keyHasTypeSpace = indentsKey[0] === 's';
864584
864234
  const type = keyHasTypeSpace ? INDENT_TYPE_SPACE : INDENT_TYPE_TAB;
864585
864235
  const amount = Number(indentsKey.slice(1));
864586
864236
  return { type, amount };
864587
864237
  }
864238
+ // Return the key (e.g. 's4') from the indents Map that represents the most common indent,
864239
+ // or return undefined if there are no indents.
864588
864240
  function getMostUsedKey(indents) {
864589
864241
  let result;
864590
864242
  let maxUsed = 0;
@@ -895103,8 +894755,14 @@ const fs_1 = __importDefault(__webpack_require__(79896));
895103
894755
  const del_1 = __importDefault(__webpack_require__(62958));
895104
894756
  const make_dir_1 = __importDefault(__webpack_require__(55589));
895105
894757
  const error_1 = __webpack_require__(64119);
894758
+ /**
894759
+ * 检查路径是否可以访问(读、写)
894760
+ * @param dest 目标路径
894761
+ * @param throwError 无权限时是否抛出异常
894762
+ */
895106
894763
  function checkFullAccess(dest, throwError = false) {
895107
894764
  try {
894765
+ // 可见、可写
895108
894766
  fs_1.default.accessSync(dest, fs_1.default.constants.F_OK);
895109
894767
  fs_1.default.accessSync(dest, fs_1.default.constants.W_OK);
895110
894768
  fs_1.default.accessSync(dest, fs_1.default.constants.R_OK);
@@ -895120,8 +894778,14 @@ function checkFullAccess(dest, throwError = false) {
895120
894778
  }
895121
894779
  }
895122
894780
  exports.checkFullAccess = checkFullAccess;
894781
+ /**
894782
+ * 检查路径是否可以读
894783
+ * @param dest 目标路径
894784
+ * @param throwError 无权限时是否抛出异常
894785
+ */
895123
894786
  function checkWritable(dest, throwError = false) {
895124
894787
  try {
894788
+ // 可见、可写
895125
894789
  fs_1.default.accessSync(dest, fs_1.default.constants.F_OK);
895126
894790
  fs_1.default.accessSync(dest, fs_1.default.constants.W_OK);
895127
894791
  return true;
@@ -895136,8 +894800,14 @@ function checkWritable(dest, throwError = false) {
895136
894800
  }
895137
894801
  }
895138
894802
  exports.checkWritable = checkWritable;
894803
+ /**
894804
+ * 检查路径是否可以写
894805
+ * @param dest 目标路径
894806
+ * @param throwError 无权限或路径不存在时是否抛出异常
894807
+ */
895139
894808
  function checkReadable(dest, throwError = false) {
895140
894809
  try {
894810
+ // 可见、可读
895141
894811
  fs_1.default.accessSync(dest, fs_1.default.constants.F_OK);
895142
894812
  fs_1.default.accessSync(dest, fs_1.default.constants.R_OK);
895143
894813
  return true;
@@ -895152,10 +894822,18 @@ function checkReadable(dest, throwError = false) {
895152
894822
  }
895153
894823
  }
895154
894824
  exports.checkReadable = checkReadable;
894825
+ /**
894826
+ * 检查指定路径是否为文件夹
894827
+ * @param dest 目标路径
894828
+ */
895155
894829
  function isDirectorySync(dest) {
895156
894830
  return fs_1.default.statSync(dest).isDirectory();
895157
894831
  }
895158
894832
  exports.isDirectorySync = isDirectorySync;
894833
+ /**
894834
+ * 检查指定路径是否为文件夹,异步
894835
+ * @param dest 目标路径
894836
+ */
895159
894837
  function isDirectoryAsync(dest) {
895160
894838
  return __awaiter(this, void 0, void 0, function* () {
895161
894839
  const stat = yield fs_1.default.promises.stat(dest);
@@ -895163,6 +894841,12 @@ function isDirectoryAsync(dest) {
895163
894841
  });
895164
894842
  }
895165
894843
  exports.isDirectoryAsync = isDirectoryAsync;
894844
+ /**
894845
+ * 格式化文件大小,保留两位小数
894846
+ * @param size 原数据,单位 Byte
894847
+ * @param unit 目标单位,支持 KB、MB、GB、TB
894848
+ * @param fixed 保留小数位数,默认 2 位
894849
+ */
895166
894850
  function formateFileSize(size, unit, fixed) {
895167
894851
  const numSize = Number(size);
895168
894852
  const unitMap = {
@@ -895174,6 +894858,7 @@ function formateFileSize(size, unit, fixed) {
895174
894858
  return Number(numSize / unitMap[unit]).toFixed(fixed);
895175
894859
  }
895176
894860
  exports.formateFileSize = formateFileSize;
894861
+ // 创建文件夹
895177
894862
  function mkdirSync(dest) {
895178
894863
  make_dir_1.default.sync(dest);
895179
894864
  }
@@ -895184,6 +894869,7 @@ function mkdirAsync(dest) {
895184
894869
  });
895185
894870
  }
895186
894871
  exports.mkdirAsync = mkdirAsync;
894872
+ // 转换 Windows 下的反斜杠路径
895187
894873
  const slash = (input) => {
895188
894874
  const isExtendedLengthPath = /^\\\\\?\\/.test(input);
895189
894875
  if (isExtendedLengthPath) {
@@ -895192,8 +894878,10 @@ const slash = (input) => {
895192
894878
  return input.replace(/\\/g, '/');
895193
894879
  };
895194
894880
  exports.slash = slash;
894881
+ // 删除文件
895195
894882
  function delSync(patterns) {
895196
894883
  let paths;
894884
+ // 不能再使用反斜杠,修复 Windows 下的问题 https://github.com/sindresorhus/del/releases/tag/v5.0.0
895197
894885
  if (Array.isArray(patterns)) {
895198
894886
  paths = patterns.map((item) => (0, exports.slash)(item));
895199
894887
  }
@@ -899076,8 +898764,10 @@ Object.defineProperty(exports, "__esModule", ({ value: true }));
899076
898764
  exports.resolveWebCredential = exports.resolveCredential = exports.checkAuth = void 0;
899077
898765
  const cloud_api_1 = __webpack_require__(2090);
899078
898766
  const config_1 = __webpack_require__(88472);
898767
+ // 调用 env:list 接口,检查密钥是否有效
899079
898768
  function checkAuth(credential, options = {}) {
899080
898769
  return __awaiter(this, void 0, void 0, function* () {
898770
+ // 兼容原临时秘钥
899081
898771
  const { secretId, secretKey, token } = resolveCredential(credential);
899082
898772
  const { proxy, timeout } = options;
899083
898773
  const region = yield (0, config_1.getRegion)();
@@ -899098,8 +898788,10 @@ function checkAuth(credential, options = {}) {
899098
898788
  });
899099
898789
  }
899100
898790
  exports.checkAuth = checkAuth;
898791
+ // 兼容解析旧的登录态
899101
898792
  function resolveCredential(data) {
899102
898793
  let { secretId, secretKey, token, accessTokenExpired, tmpSecretId, tmpSecretKey, tmpToken, tmpExpired, expired, authTime, refreshToken, uin, hash, envId } = data;
898794
+ // 兼容旧的登录态信息
899103
898795
  token = token || tmpToken;
899104
898796
  secretId = secretId || tmpSecretId;
899105
898797
  secretKey = secretKey || tmpSecretKey;
@@ -911166,6 +910858,7 @@ function resolveCredentialFormEnv() {
911166
910858
  token
911167
910859
  };
911168
910860
  }
910861
+ // 获取 credential 数据
911169
910862
  function getCredentialData() {
911170
910863
  return __awaiter(this, void 0, void 0, function* () {
911171
910864
  const localData = (yield exports.authStore.get('credential'));
@@ -911174,6 +910867,7 @@ function getCredentialData() {
911174
910867
  const keys = Object.keys(credential)
911175
910868
  .filter((key) => credential[key])
911176
910869
  .filter((key) => key !== '-');
910870
+ // 检查是否为空对象
911177
910871
  if (!credential || keys.length === 0) {
911178
910872
  return null;
911179
910873
  }
@@ -911181,6 +910875,7 @@ function getCredentialData() {
911181
910875
  });
911182
910876
  }
911183
910877
  exports.getCredentialData = getCredentialData;
910878
+ // 临时密钥过期后,进行续期
911184
910879
  function refreshTmpToken(metaData) {
911185
910880
  return __awaiter(this, void 0, void 0, function* () {
911186
910881
  const mac = yield (0, system_1.getMacAddress)();
@@ -911189,6 +910884,7 @@ function refreshTmpToken(metaData) {
911189
910884
  const credential = (0, common_1.resolveWebCredential)(metaData);
911190
910885
  const res = yield async_1.AsyncMerge.merge(() => (0, cloud_api_1.fetch)(refreshTokenUrl, {
911191
910886
  method: 'POST',
910887
+ // 超时时间:15S
911192
910888
  timeout: 15000,
911193
910889
  body: JSON.stringify(credential),
911194
910890
  headers: { 'Content-Type': 'application/json' }
@@ -911212,6 +910908,7 @@ function refreshTmpToken(metaData) {
911212
910908
  });
911213
910909
  }
911214
910910
  exports.refreshTmpToken = refreshTmpToken;
910911
+ // 是否为 CAM 权限错误
911215
910912
  const isCamRefused = (e) => {
911216
910913
  return (Number(e.code) === 4102 ||
911217
910914
  Number(e.code) === 42 ||
@@ -911219,16 +910916,22 @@ const isCamRefused = (e) => {
911219
910916
  e.code === 'AuthFailure.UnauthorizedOperation');
911220
910917
  };
911221
910918
  exports.isCamRefused = isCamRefused;
910919
+ // 报错返回 null 值
911222
910920
  function wrapCheckAuth(credential, options) {
911223
910921
  return __awaiter(this, void 0, void 0, function* () {
911224
910922
  const { timeout = 15000 } = options;
911225
910923
  try {
910924
+ // 合并请求,避免超过接口限频
911226
910925
  yield async_1.AsyncMerge.merge(() => (0, common_1.checkAuth)(credential, options), 'checkAuth', {
910926
+ // 超时时间不能小于发送请求的超时时间
911227
910927
  timeout: Number(timeout) ? (timeout < 15000 ? 15000 : timeout + 1000) : 15000
911228
910928
  });
911229
910929
  return credential;
911230
910930
  }
911231
910931
  catch (e) {
910932
+ // CAM 错误视为登录正常
910933
+ // if (isCamRefused(e)) return credential;
910934
+ // 请求超时
911232
910935
  if (e.type === 'request-timeout') {
911233
910936
  throw new error_1.CloudBaseError('请求超时,请检查你的网络,如果终端无法直接访问公网,请设置终端 HTTP 请求代理!');
911234
910937
  }
@@ -911236,38 +910939,50 @@ function wrapCheckAuth(credential, options) {
911236
910939
  }
911237
910940
  });
911238
910941
  }
910942
+ // token 将在 n 分钟内过期
911239
910943
  const isTokenExpired = (credential, gap = 120) => credential.accessTokenExpired &&
911240
910944
  Number(credential.accessTokenExpired) < Date.now() + gap * 1000;
910945
+ // 获取身份认证信息并校验、自动刷新
911241
910946
  function checkAndGetCredential(options = {}) {
911242
910947
  return __awaiter(this, void 0, void 0, function* () {
910948
+ // 从本地存储中读取 credential
911243
910949
  const credential = yield getCredentialData();
911244
910950
  if (!credential) {
911245
910951
  return null;
911246
910952
  }
910953
+ // 存在临时密钥信息
911247
910954
  if (credential.refreshToken) {
910955
+ // 临时密钥在 2 小时有效期内,可以直接使用
911248
910956
  if (!isTokenExpired(credential)) {
910957
+ // 检查 credential
911249
910958
  return wrapCheckAuth(credential, options);
911250
910959
  }
911251
910960
  else if (Date.now() < Number(credential.expired)) {
910961
+ // 临时密钥超过两小时有效期,但在 1 个月 refresh 有效期内,刷新临时密钥
911252
910962
  let refreshCredential;
911253
910963
  try {
911254
910964
  refreshCredential = yield refreshTmpToken(credential);
911255
910965
  }
911256
910966
  catch (e) {
910967
+ // 登录态失效
911257
910968
  if (e.code === 'AUTH_FAIL') {
911258
910969
  return null;
911259
910970
  }
911260
910971
  else if (e.code === 'InternalError.GetRoleError') {
910972
+ // 用户未开通服务,视为登录态失效
911261
910973
  return null;
911262
910974
  }
911263
910975
  else {
910976
+ // 异常错误
911264
910977
  throw e;
911265
910978
  }
911266
910979
  }
910980
+ // 存储新的秘钥
911267
910981
  yield exports.authStore.set('credential', refreshCredential || {});
911268
910982
  return wrapCheckAuth((0, common_1.resolveCredential)(refreshCredential), options);
911269
910983
  }
911270
910984
  }
910985
+ // 存在永久密钥
911271
910986
  if (credential.secretId && credential.secretKey) {
911272
910987
  return wrapCheckAuth(credential, options);
911273
910988
  }
@@ -911275,36 +910990,45 @@ function checkAndGetCredential(options = {}) {
911275
910990
  });
911276
910991
  }
911277
910992
  exports.checkAndGetCredential = checkAndGetCredential;
910993
+ // 获取身份认证信息,不校验
911278
910994
  function getCredentialWithoutCheck() {
911279
910995
  return __awaiter(this, void 0, void 0, function* () {
911280
910996
  const credential = yield getCredentialData();
911281
910997
  if (!credential) {
911282
910998
  return null;
911283
910999
  }
911000
+ // 存在临时密钥信息
911284
911001
  if (credential.refreshToken) {
911002
+ // 临时密钥在 2 小时有效期内,可以直接使用
911285
911003
  if (!isTokenExpired(credential)) {
911286
911004
  return credential;
911287
911005
  }
911288
911006
  else if (Date.now() < Number(credential.expired)) {
911007
+ // 临时密钥超过两小时有效期,但在 1 个月 refresh 有效期内,刷新临时密钥
911289
911008
  let refreshCredential;
911290
911009
  try {
911291
911010
  refreshCredential = yield refreshTmpToken(credential);
911292
911011
  }
911293
911012
  catch (e) {
911013
+ // 登录态失效
911294
911014
  if (e.code === 'AUTH_FAIL') {
911295
911015
  return null;
911296
911016
  }
911297
911017
  else if (e.code === 'InternalError.GetRoleError') {
911018
+ // 用户未开通服务,视为登录态失效
911298
911019
  return null;
911299
911020
  }
911300
911021
  else {
911022
+ // 异常错误
911301
911023
  throw e;
911302
911024
  }
911303
911025
  }
911026
+ // 存储新的秘钥
911304
911027
  yield exports.authStore.set('credential', refreshCredential || {});
911305
911028
  return (0, common_1.resolveCredential)(refreshCredential);
911306
911029
  }
911307
911030
  }
911031
+ // 存在永久密钥
911308
911032
  if (credential.secretId && credential.secretKey) {
911309
911033
  return credential;
911310
911034
  }