@coze-arch/cli 0.0.36-alpha.fde2b5 → 0.0.37-alpha.4b3e81

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 (63) hide show
  1. package/README.md +0 -11
  2. package/lib/__templates__/nextjs/package.json +3 -2
  3. package/lib/__templates__/nextjs/pnpm-lock.yaml +259 -206
  4. package/lib/__templates__/nextjs/template.config.js +1 -3
  5. package/lib/__templates__/templates.json +0 -25
  6. package/lib/__templates__/vite/template.config.js +1 -3
  7. package/lib/cli.js +199 -3169
  8. package/package.json +3 -5
  9. package/docs/deploy.md +0 -164
  10. package/lib/__templates__/phaser/.coze +0 -13
  11. package/lib/__templates__/phaser/README.md +0 -37
  12. package/lib/__templates__/phaser/_gitignore +0 -23
  13. package/lib/__templates__/phaser/_npmrc +0 -14
  14. package/lib/__templates__/phaser/assets/image_sequence/coze-game-loading/frame_0001.png +0 -0
  15. package/lib/__templates__/phaser/assets/image_sequence/coze-game-loading/frame_0002.png +0 -0
  16. package/lib/__templates__/phaser/assets/image_sequence/coze-game-loading/frame_0003.png +0 -0
  17. package/lib/__templates__/phaser/assets/image_sequence/coze-game-loading/frame_0004.png +0 -0
  18. package/lib/__templates__/phaser/assets/image_sequence/coze-game-loading/frame_0005.png +0 -0
  19. package/lib/__templates__/phaser/assets/image_sequence/coze-game-loading/frame_0006.png +0 -0
  20. package/lib/__templates__/phaser/assets/image_sequence/coze-game-loading/frame_0007.png +0 -0
  21. package/lib/__templates__/phaser/assets/image_sequence/coze-game-loading/frame_0008.png +0 -0
  22. package/lib/__templates__/phaser/assets/image_sequence/coze-game-loading/frame_0009.png +0 -0
  23. package/lib/__templates__/phaser/assets/image_sequence/coze-game-loading/frame_0010.png +0 -0
  24. package/lib/__templates__/phaser/assets/image_sequence/coze-game-loading/frame_0011.png +0 -0
  25. package/lib/__templates__/phaser/assets/image_sequence/coze-game-loading/frame_0012.png +0 -0
  26. package/lib/__templates__/phaser/assets/image_sequence/coze-game-loading/frame_0013.png +0 -0
  27. package/lib/__templates__/phaser/assets/image_sequence/coze-game-loading/frame_0014.png +0 -0
  28. package/lib/__templates__/phaser/assets/image_sequence/coze-game-loading/frame_0015.png +0 -0
  29. package/lib/__templates__/phaser/assets/image_sequence/coze-game-loading/frame_0016.png +0 -0
  30. package/lib/__templates__/phaser/assets/image_sequence/coze-game-loading/frame_0017.png +0 -0
  31. package/lib/__templates__/phaser/assets/image_sequence/coze-game-loading/frame_0018.png +0 -0
  32. package/lib/__templates__/phaser/assets/image_sequence/coze-game-loading/frame_0019.png +0 -0
  33. package/lib/__templates__/phaser/assets/image_sequence/coze-game-loading/frame_0020.png +0 -0
  34. package/lib/__templates__/phaser/assets/image_sequence/coze-game-loading/frame_0021.png +0 -0
  35. package/lib/__templates__/phaser/assets/image_sequence/coze-game-loading/frame_0022.png +0 -0
  36. package/lib/__templates__/phaser/assets/image_sequence/coze-game-loading/frame_0023.png +0 -0
  37. package/lib/__templates__/phaser/assets/image_sequence/coze-game-loading/frame_0024.png +0 -0
  38. package/lib/__templates__/phaser/assets/image_sequence/coze-game-loading/manifest.json +0 -11
  39. package/lib/__templates__/phaser/debug-runtime/flow-graph.json +0 -20
  40. package/lib/__templates__/phaser/index.html +0 -12
  41. package/lib/__templates__/phaser/package.json +0 -31
  42. package/lib/__templates__/phaser/pnpm-lock.yaml +0 -661
  43. package/lib/__templates__/phaser/scripts/build.sh +0 -8
  44. package/lib/__templates__/phaser/scripts/dev.sh +0 -82
  45. package/lib/__templates__/phaser/scripts/prepare.sh +0 -7
  46. package/lib/__templates__/phaser/scripts/spawn-detached.cjs +0 -29
  47. package/lib/__templates__/phaser/scripts/start.sh +0 -82
  48. package/lib/__templates__/phaser/scripts/validate.sh +0 -7
  49. package/lib/__templates__/phaser/src/assets.ts +0 -15
  50. package/lib/__templates__/phaser/src/global.d.ts +0 -36
  51. package/lib/__templates__/phaser/src/main.ts +0 -28
  52. package/lib/__templates__/phaser/src/scene/BootScene.ts +0 -209
  53. package/lib/__templates__/phaser/src/scene/DevLoadingScene.ts +0 -66
  54. package/lib/__templates__/phaser/src/style.css +0 -28
  55. package/lib/__templates__/phaser/src/types.ts +0 -32
  56. package/lib/__templates__/phaser/src/utils/asset-loader.ts +0 -319
  57. package/lib/__templates__/phaser/src/utils/index.ts +0 -2
  58. package/lib/__templates__/phaser/src/utils/mark-editable.ts +0 -6
  59. package/lib/__templates__/phaser/template.config.js +0 -43
  60. package/lib/__templates__/phaser/tsconfig.json +0 -23
  61. package/lib/__templates__/phaser/vite.config.ts +0 -96
  62. package/lib/deploy/package-project.js +0 -220
  63. package/lib/deploy/package-project.py +0 -165
package/lib/cli.js CHANGED
@@ -14,7 +14,7 @@ var perf_hooks = require('perf_hooks');
14
14
  var fs$1 = require('fs/promises');
15
15
  var os = require('os');
16
16
  var jsYaml = require('js-yaml');
17
- var TOML = require('@iarna/toml');
17
+ var toml = require('@iarna/toml');
18
18
  var crypto = require('crypto');
19
19
  var fastGlob = require('fast-glob');
20
20
  var child_process = require('child_process');
@@ -23,12 +23,6 @@ var Ajv = require('ajv');
23
23
  var minimist = require('minimist');
24
24
  var changeCase = require('change-case');
25
25
  var ejs = require('ejs');
26
- var node_crypto = require('node:crypto');
27
- var node_os = require('node:os');
28
- var promises = require('node:fs/promises');
29
- var node_child_process = require('node:child_process');
30
- var node_util = require('node:util');
31
- var node_stream = require('node:stream');
32
26
 
33
27
  /**
34
28
  * 读取 templates.json 配置
@@ -1634,7 +1628,7 @@ function createNodeTransport() {
1634
1628
  };
1635
1629
  }
1636
1630
 
1637
- function _nullishCoalesce$c(lhs, rhsFn) { if (lhs != null) { return lhs; } else { return rhsFn(); } } function _optionalChain$E(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = fn(value); } else if (op === 'call' || op === 'optionalCall') { value = fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; }/**
1631
+ function _nullishCoalesce$a(lhs, rhsFn) { if (lhs != null) { return lhs; } else { return rhsFn(); } } function _optionalChain$t(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = fn(value); } else if (op === 'call' || op === 'optionalCall') { value = fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; }/**
1638
1632
  * Slardar CLI Reporter 主类
1639
1633
  * 封装 @slardar/base 的初始化和上报逻辑
1640
1634
  */
@@ -1691,7 +1685,7 @@ class SlardarCLIReporter {constructor() { SlardarCLIReporter.prototype.__init.ca
1691
1685
  release: config.release,
1692
1686
  env: config.env,
1693
1687
  name: config.name,
1694
- useLocalConfig: _nullishCoalesce$c(config.useLocalConfig, () => ( false)), // 默认使用服务端配置
1688
+ useLocalConfig: _nullishCoalesce$a(config.useLocalConfig, () => ( false)), // 默认使用服务端配置
1695
1689
  domain: config.domain,
1696
1690
  // 设置本地采样率为 100%,确保事件不被过滤
1697
1691
  sample: {
@@ -1706,7 +1700,7 @@ class SlardarCLIReporter {constructor() { SlardarCLIReporter.prototype.__init.ca
1706
1700
  this.client.on('send', (ev) => {
1707
1701
  log$6(
1708
1702
  'send hook called for event: %s',
1709
- (_optionalChain$E([ev, 'optionalAccess', _ => _.ev_type]) ) || 'unknown',
1703
+ (_optionalChain$t([ev, 'optionalAccess', _ => _.ev_type]) ) || 'unknown',
1710
1704
  );
1711
1705
  });
1712
1706
 
@@ -1764,7 +1758,7 @@ class SlardarCLIReporter {constructor() { SlardarCLIReporter.prototype.__init.ca
1764
1758
  )
1765
1759
  : undefined;
1766
1760
 
1767
- _optionalChain$E([this, 'access', _2 => _2.client, 'access', _3 => _3.sendEvent, 'optionalCall', _4 => _4({
1761
+ _optionalChain$t([this, 'access', _2 => _2.client, 'access', _3 => _3.sendEvent, 'optionalCall', _4 => _4({
1768
1762
  name,
1769
1763
  metrics: cleanMetrics ,
1770
1764
  categories: cleanCategories ,
@@ -1835,7 +1829,7 @@ class SlardarCLIReporter {constructor() { SlardarCLIReporter.prototype.__init.ca
1835
1829
  log$6('Reporting JS error:', {
1836
1830
  name: error.name,
1837
1831
  message: error.message.slice(0, 100),
1838
- stack: _optionalChain$E([error, 'access', _5 => _5.stack, 'optionalAccess', _6 => _6.slice, 'call', _7 => _7(0, 200)]),
1832
+ stack: _optionalChain$t([error, 'access', _5 => _5.stack, 'optionalAccess', _6 => _6.slice, 'call', _7 => _7(0, 200)]),
1839
1833
  extra,
1840
1834
  source,
1841
1835
  });
@@ -1855,7 +1849,7 @@ class SlardarCLIReporter {constructor() { SlardarCLIReporter.prototype.__init.ca
1855
1849
  if (!this.ensureInitialized()) {
1856
1850
  return;
1857
1851
  }
1858
- _optionalChain$E([this, 'access', _8 => _8.client, 'access', _9 => _9.context, 'optionalAccess', _10 => _10.set, 'call', _11 => _11(key, value)]);
1852
+ _optionalChain$t([this, 'access', _8 => _8.client, 'access', _9 => _9.context, 'optionalAccess', _10 => _10.set, 'call', _11 => _11(key, value)]);
1859
1853
  }
1860
1854
 
1861
1855
  /**
@@ -1866,7 +1860,7 @@ class SlardarCLIReporter {constructor() { SlardarCLIReporter.prototype.__init.ca
1866
1860
  return;
1867
1861
  }
1868
1862
  log$6('Merging context:', context);
1869
- _optionalChain$E([this, 'access', _12 => _12.client, 'access', _13 => _13.context, 'optionalAccess', _14 => _14.merge, 'call', _15 => _15(context)]);
1863
+ _optionalChain$t([this, 'access', _12 => _12.client, 'access', _13 => _13.context, 'optionalAccess', _14 => _14.merge, 'call', _15 => _15(context)]);
1870
1864
  }
1871
1865
 
1872
1866
  /**
@@ -1876,7 +1870,7 @@ class SlardarCLIReporter {constructor() { SlardarCLIReporter.prototype.__init.ca
1876
1870
  if (!this.ensureInitialized()) {
1877
1871
  return;
1878
1872
  }
1879
- _optionalChain$E([this, 'access', _16 => _16.client, 'access', _17 => _17.context, 'optionalAccess', _18 => _18.delete, 'call', _19 => _19(key)]);
1873
+ _optionalChain$t([this, 'access', _16 => _16.client, 'access', _17 => _17.context, 'optionalAccess', _18 => _18.delete, 'call', _19 => _19(key)]);
1880
1874
  }
1881
1875
 
1882
1876
  /**
@@ -1886,7 +1880,7 @@ class SlardarCLIReporter {constructor() { SlardarCLIReporter.prototype.__init.ca
1886
1880
  if (!this.ensureInitialized()) {
1887
1881
  return;
1888
1882
  }
1889
- _optionalChain$E([this, 'access', _20 => _20.client, 'access', _21 => _21.context, 'optionalAccess', _22 => _22.clear, 'call', _23 => _23()]);
1883
+ _optionalChain$t([this, 'access', _20 => _20.client, 'access', _21 => _21.context, 'optionalAccess', _22 => _22.clear, 'call', _23 => _23()]);
1890
1884
  }
1891
1885
 
1892
1886
  /**
@@ -1923,7 +1917,7 @@ class SlardarCLIReporter {constructor() { SlardarCLIReporter.prototype.__init.ca
1923
1917
  return;
1924
1918
  }
1925
1919
  log$6('Flushing Slardar data...');
1926
- _optionalChain$E([this, 'access', _24 => _24.client, 'access', _25 => _25.getSender, 'optionalCall', _26 => _26(), 'optionalAccess', _27 => _27.flush, 'call', _28 => _28()]);
1920
+ _optionalChain$t([this, 'access', _24 => _24.client, 'access', _25 => _25.getSender, 'optionalCall', _26 => _26(), 'optionalAccess', _27 => _27.flush, 'call', _28 => _28()]);
1927
1921
  log$6('Waiting %dms for events to be sent...', waitMs);
1928
1922
  await new Promise(resolve => setTimeout(resolve, waitMs));
1929
1923
  log$6('Slardar data flushed');
@@ -1942,7 +1936,7 @@ class SlardarCLIReporter {constructor() { SlardarCLIReporter.prototype.__init.ca
1942
1936
  */
1943
1937
  const reporter = new SlardarCLIReporter();
1944
1938
 
1945
- function _optionalChain$D(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = fn(value); } else if (op === 'call' || op === 'optionalCall') { value = fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; }
1939
+ function _optionalChain$s(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = fn(value); } else if (op === 'call' || op === 'optionalCall') { value = fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; }
1946
1940
 
1947
1941
 
1948
1942
 
@@ -2002,11 +1996,11 @@ const EventBuilder = {
2002
1996
  name: CLI_EVENTS.CLI_COMMAND,
2003
1997
  categories: {
2004
1998
  command,
2005
- args: _optionalChain$D([options, 'optionalAccess', _ => _.args]),
1999
+ args: _optionalChain$s([options, 'optionalAccess', _ => _.args]),
2006
2000
  status: 'running' ,
2007
- ..._optionalChain$D([options, 'optionalAccess', _2 => _2.categories]),
2001
+ ..._optionalChain$s([options, 'optionalAccess', _2 => _2.categories]),
2008
2002
  },
2009
- metrics: _optionalChain$D([options, 'optionalAccess', _3 => _3.metrics]),
2003
+ metrics: _optionalChain$s([options, 'optionalAccess', _3 => _3.metrics]),
2010
2004
  };
2011
2005
  },
2012
2006
 
@@ -2027,13 +2021,13 @@ const EventBuilder = {
2027
2021
  name: CLI_EVENTS.CLI_COMMAND_COMPLETE,
2028
2022
  categories: {
2029
2023
  command,
2030
- args: _optionalChain$D([options, 'optionalAccess', _4 => _4.args]),
2024
+ args: _optionalChain$s([options, 'optionalAccess', _4 => _4.args]),
2031
2025
  status: success ? ('success' ) : ('fail' ),
2032
- ..._optionalChain$D([options, 'optionalAccess', _5 => _5.categories]),
2026
+ ..._optionalChain$s([options, 'optionalAccess', _5 => _5.categories]),
2033
2027
  },
2034
2028
  metrics: {
2035
2029
  duration,
2036
- ...(_optionalChain$D([options, 'optionalAccess', _6 => _6.errorCode]) && { errorCode: options.errorCode }),
2030
+ ...(_optionalChain$s([options, 'optionalAccess', _6 => _6.errorCode]) && { errorCode: options.errorCode }),
2037
2031
  },
2038
2032
  };
2039
2033
  },
@@ -2054,12 +2048,12 @@ const EventBuilder = {
2054
2048
  name: CLI_EVENTS.NETWORK_REQUEST,
2055
2049
  categories: {
2056
2050
  url,
2057
- method: _optionalChain$D([options, 'optionalAccess', _7 => _7.method]) || 'GET',
2058
- statusCode: _optionalChain$D([options, 'optionalAccess', _8 => _8.statusCode, 'optionalAccess', _9 => _9.toString, 'call', _10 => _10()]),
2059
- status: _optionalChain$D([options, 'optionalAccess', _11 => _11.success]) ? ('success' ) : ('fail' ),
2051
+ method: _optionalChain$s([options, 'optionalAccess', _7 => _7.method]) || 'GET',
2052
+ statusCode: _optionalChain$s([options, 'optionalAccess', _8 => _8.statusCode, 'optionalAccess', _9 => _9.toString, 'call', _10 => _10()]),
2053
+ status: _optionalChain$s([options, 'optionalAccess', _11 => _11.success]) ? ('success' ) : ('fail' ),
2060
2054
  },
2061
2055
  metrics: {
2062
- duration: _optionalChain$D([options, 'optionalAccess', _12 => _12.duration]),
2056
+ duration: _optionalChain$s([options, 'optionalAccess', _12 => _12.duration]),
2063
2057
  },
2064
2058
  };
2065
2059
  },
@@ -2081,11 +2075,11 @@ const EventBuilder = {
2081
2075
  categories: {
2082
2076
  operation,
2083
2077
  filePath,
2084
- status: _optionalChain$D([options, 'optionalAccess', _13 => _13.success]) ? ('success' ) : ('fail' ),
2078
+ status: _optionalChain$s([options, 'optionalAccess', _13 => _13.success]) ? ('success' ) : ('fail' ),
2085
2079
  },
2086
2080
  metrics: {
2087
- duration: _optionalChain$D([options, 'optionalAccess', _14 => _14.duration]),
2088
- fileSize: _optionalChain$D([options, 'optionalAccess', _15 => _15.fileSize]),
2081
+ duration: _optionalChain$s([options, 'optionalAccess', _14 => _14.duration]),
2082
+ fileSize: _optionalChain$s([options, 'optionalAccess', _15 => _15.fileSize]),
2089
2083
  },
2090
2084
  };
2091
2085
  },
@@ -2113,7 +2107,7 @@ const EventBuilder = {
2113
2107
  };
2114
2108
 
2115
2109
  var name = "@coze-arch/cli";
2116
- var version = "0.0.36-alpha.fde2b5";
2110
+ var version = "0.0.37-alpha.4b3e81";
2117
2111
  var description = "coze coding devtools cli";
2118
2112
  var license = "MIT";
2119
2113
  var author = "fanwenjie.fe@bytedance.com";
@@ -2125,7 +2119,6 @@ var bin = {
2125
2119
  var files = [
2126
2120
  "lib",
2127
2121
  "bin",
2128
- "docs/deploy.md",
2129
2122
  "lib/**/.npmrc",
2130
2123
  "!**/*.tsbuildinfo",
2131
2124
  "!**/*.map",
@@ -2162,9 +2155,7 @@ var dependencies = {
2162
2155
  "fast-glob": "^3.3.3",
2163
2156
  "js-yaml": "^4.2.0",
2164
2157
  minimist: "^1.2.8",
2165
- pnpm: "9.0.0",
2166
- shelljs: "^0.10.0",
2167
- tar: "^7.5.22"
2158
+ shelljs: "^0.10.0"
2168
2159
  };
2169
2160
  var devDependencies = {
2170
2161
  "@coze-arch/cli-logger": "workspace:*",
@@ -2195,6 +2186,7 @@ var devDependencies = {
2195
2186
  rollup: "^4.60.1",
2196
2187
  sucrase: "^3.35.1",
2197
2188
  tsx: "^4.23.11",
2189
+ "tree-kill": "^1.2.2",
2198
2190
  vitest: "~4.1.10"
2199
2191
  };
2200
2192
  var publishConfig = {
@@ -2223,7 +2215,7 @@ var packageJson = {
2223
2215
  cozePublishConfig: cozePublishConfig
2224
2216
  };
2225
2217
 
2226
- function _optionalChain$C(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = fn(value); } else if (op === 'call' || op === 'optionalCall') { value = fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; }/**
2218
+ function _optionalChain$r(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = fn(value); } else if (op === 'call' || op === 'optionalCall') { value = fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; }/**
2227
2219
  * Slardar 监控初始化和上报
2228
2220
  */
2229
2221
 
@@ -2326,11 +2318,11 @@ const reportCommandComplete = safeRun(
2326
2318
  ,
2327
2319
  ) => {
2328
2320
  const event = EventBuilder.cliCommandComplete(command, success, duration, {
2329
- args: _optionalChain$C([options, 'optionalAccess', _ => _.args]),
2330
- errorCode: _optionalChain$C([options, 'optionalAccess', _2 => _2.errorCode]),
2321
+ args: _optionalChain$r([options, 'optionalAccess', _ => _.args]),
2322
+ errorCode: _optionalChain$r([options, 'optionalAccess', _2 => _2.errorCode]),
2331
2323
  categories: {
2332
- ...(_optionalChain$C([options, 'optionalAccess', _3 => _3.errorMessage]) && { errorMessage: options.errorMessage }),
2333
- ..._optionalChain$C([options, 'optionalAccess', _4 => _4.categories]),
2324
+ ...(_optionalChain$r([options, 'optionalAccess', _3 => _3.errorMessage]) && { errorMessage: options.errorMessage }),
2325
+ ..._optionalChain$r([options, 'optionalAccess', _4 => _4.categories]),
2334
2326
  },
2335
2327
  });
2336
2328
  reporter.sendEvent(event.name, event.metrics, event.categories);
@@ -2389,7 +2381,7 @@ const flushSlardar = safeRun('flushSlardar', async () => {
2389
2381
  await reporter.flush();
2390
2382
  });
2391
2383
 
2392
- function _nullishCoalesce$b(lhs, rhsFn) { if (lhs != null) { return lhs; } else { return rhsFn(); } } function _optionalChain$B(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = fn(value); } else if (op === 'call' || op === 'optionalCall') { value = fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; }var LogLevel; (function (LogLevel) {
2384
+ function _nullishCoalesce$9(lhs, rhsFn) { if (lhs != null) { return lhs; } else { return rhsFn(); } } function _optionalChain$q(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = fn(value); } else if (op === 'call' || op === 'optionalCall') { value = fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; }var LogLevel; (function (LogLevel) {
2393
2385
  const ERROR = 0; LogLevel[LogLevel["ERROR"] = ERROR] = "ERROR";
2394
2386
  const WARN = 1; LogLevel[LogLevel["WARN"] = WARN] = "WARN";
2395
2387
  const SUCCESS = 2; LogLevel[LogLevel["SUCCESS"] = SUCCESS] = "SUCCESS";
@@ -2427,7 +2419,7 @@ class Logger {
2427
2419
 
2428
2420
  constructor(options = {}) {
2429
2421
  this.level = this.parseLogLevel(options.level);
2430
- this.useColor = _nullishCoalesce$b(options.useColor, () => ( this.isColorSupported()));
2422
+ this.useColor = _nullishCoalesce$9(options.useColor, () => ( this.isColorSupported()));
2431
2423
  this.prefix = options.prefix;
2432
2424
  }
2433
2425
 
@@ -2436,7 +2428,7 @@ class Logger {
2436
2428
  return level;
2437
2429
  }
2438
2430
 
2439
- const envLevel = _optionalChain$B([process, 'access', _ => _.env, 'access', _2 => _2.LOG_LEVEL, 'optionalAccess', _3 => _3.toLowerCase, 'call', _4 => _4()]);
2431
+ const envLevel = _optionalChain$q([process, 'access', _ => _.env, 'access', _2 => _2.LOG_LEVEL, 'optionalAccess', _3 => _3.toLowerCase, 'call', _4 => _4()]);
2440
2432
  if (envLevel && envLevel in LOG_LEVEL_MAP) {
2441
2433
  // envLevel 已通过 `in` 检查确认为 LOG_LEVEL_MAP 的键;
2442
2434
  // 显式判空以满足 noUncheckedIndexedAccess,运行时行为不变
@@ -2453,7 +2445,7 @@ class Logger {
2453
2445
  // 简单检测:Node.js 环境且支持 TTY
2454
2446
  return (
2455
2447
  typeof process !== 'undefined' &&
2456
- _optionalChain$B([process, 'access', _5 => _5.stdout, 'optionalAccess', _6 => _6.isTTY]) === true &&
2448
+ _optionalChain$q([process, 'access', _5 => _5.stdout, 'optionalAccess', _6 => _6.isTTY]) === true &&
2457
2449
  process.env.NO_COLOR === undefined
2458
2450
  );
2459
2451
  }
@@ -2478,7 +2470,7 @@ class Logger {
2478
2470
 
2479
2471
  const icon = this.colorize(options.icon, options.color);
2480
2472
  const prefix = this.prefix ? `${icon} ${this.prefix}` : icon;
2481
- console.log(prefix, options.message, ...(_nullishCoalesce$b(options.args, () => ( []))));
2473
+ console.log(prefix, options.message, ...(_nullishCoalesce$9(options.args, () => ( []))));
2482
2474
  }
2483
2475
 
2484
2476
  error(message, ...args) {
@@ -2823,7 +2815,7 @@ const executeWarmup = async (options) => {
2823
2815
  /**
2824
2816
  * 注册 warmup 命令到 program
2825
2817
  */
2826
- const registerCommand$7 = program => {
2818
+ const registerCommand$6 = program => {
2827
2819
  program
2828
2820
  .command('warmup')
2829
2821
  .description('Pre-install dependencies for templates to speed up init')
@@ -2846,9 +2838,9 @@ const COZE_HOME_DIR = '.coze';
2846
2838
 
2847
2839
  /**
2848
2840
  * Logs directory name
2849
- * Default: ~/.coze/logs
2841
+ * Default: .coze-logs
2850
2842
  */
2851
- const LOGS_DIR = 'logs';
2843
+ const LOGS_DIR = '.coze-logs';
2852
2844
 
2853
2845
  /**
2854
2846
  * Get the Coze home directory path
@@ -2863,10 +2855,10 @@ const getCozeHome = () =>
2863
2855
  * Get the logs directory path
2864
2856
  * Can be customized via COZE_LOG_DIR environment variable
2865
2857
  *
2866
- * @returns Absolute path to logs directory (default: ~/.coze/logs)
2858
+ * @returns Absolute path to logs directory (default: ~/.coze-logs)
2867
2859
  */
2868
2860
  const getCozeLogsDir = () =>
2869
- process.env.COZE_LOG_DIR || path.join(getCozeHome(), LOGS_DIR);
2861
+ process.env.COZE_LOG_DIR || path.join(os.homedir(), LOGS_DIR);
2870
2862
 
2871
2863
  /**
2872
2864
  * Get path for a specific file/directory within Coze home
@@ -2897,7 +2889,7 @@ const getCozeFilePath = (relativePath) =>
2897
2889
  * @example
2898
2890
  * ```ts
2899
2891
  * const devLog = getCozeLogPath('dev.log');
2900
- * // Returns: ~/.coze/logs/dev.log
2892
+ * // Returns: ~/.coze-logs/dev.log
2901
2893
  * ```
2902
2894
  */
2903
2895
  const getCozeLogPath = (filename) =>
@@ -3235,7 +3227,7 @@ const executeUpdate = (
3235
3227
  /**
3236
3228
  * 注册 update 命令到 program
3237
3229
  */
3238
- const registerCommand$6 = program => {
3230
+ const registerCommand$5 = program => {
3239
3231
  program
3240
3232
  .command('update <package>')
3241
3233
  .description('Update a package dependency')
@@ -3261,7 +3253,7 @@ const registerCommand$6 = program => {
3261
3253
  });
3262
3254
  };
3263
3255
 
3264
- function _optionalChain$A(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = fn(value); } else if (op === 'call' || op === 'optionalCall') { value = fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; }// Safe JSON parsing utilities with type safety and error handling
3256
+ function _optionalChain$p(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = fn(value); } else if (op === 'call' || op === 'optionalCall') { value = fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; }// Safe JSON parsing utilities with type safety and error handling
3265
3257
  // Provides fallback values, validation, and error monitoring capabilities
3266
3258
 
3267
3259
  /**
@@ -3361,12 +3353,12 @@ function safeJsonParse(
3361
3353
  const parsed = JSON.parse(String(input));
3362
3354
 
3363
3355
  // Optional validation
3364
- if (_optionalChain$A([options, 'optionalAccess', _ => _.validate])) {
3356
+ if (_optionalChain$p([options, 'optionalAccess', _ => _.validate])) {
3365
3357
  if (options.validate(parsed)) {
3366
3358
  return parsed;
3367
3359
  } else {
3368
3360
  const validationError = new Error('JSON validation failed');
3369
- _optionalChain$A([options, 'access', _2 => _2.onError, 'optionalCall', _3 => _3(validationError, input)]);
3361
+ _optionalChain$p([options, 'access', _2 => _2.onError, 'optionalCall', _3 => _3(validationError, input)]);
3370
3362
 
3371
3363
  if (options.throwOnValidationError) {
3372
3364
  throw validationError;
@@ -3378,10 +3370,10 @@ function safeJsonParse(
3378
3370
  return parsed;
3379
3371
  } catch (error) {
3380
3372
  // Re-throw validation errors when throwOnValidationError is true
3381
- if (error instanceof Error && error.message === 'JSON validation failed' && _optionalChain$A([options, 'optionalAccess', _4 => _4.throwOnValidationError])) {
3373
+ if (error instanceof Error && error.message === 'JSON validation failed' && _optionalChain$p([options, 'optionalAccess', _4 => _4.throwOnValidationError])) {
3382
3374
  throw error;
3383
3375
  }
3384
- _optionalChain$A([options, 'optionalAccess', _5 => _5.onError, 'optionalCall', _6 => _6(error , input)]);
3376
+ _optionalChain$p([options, 'optionalAccess', _5 => _5.onError, 'optionalCall', _6 => _6(error , input)]);
3385
3377
  return defaultValue;
3386
3378
  }
3387
3379
  }
@@ -3421,7 +3413,7 @@ function isNode(node) {
3421
3413
  }
3422
3414
  const hasAnchor = (node) => (isScalar(node) || isCollection(node)) && !!node.anchor;
3423
3415
 
3424
- function _optionalChain$z(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = fn(value); } else if (op === 'call' || op === 'optionalCall') { value = fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; }
3416
+ function _optionalChain$o(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = fn(value); } else if (op === 'call' || op === 'optionalCall') { value = fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; }
3425
3417
  const BREAK = Symbol('break visit');
3426
3418
  const SKIP = Symbol('skip children');
3427
3419
  const REMOVE = Symbol('remove node');
@@ -3534,15 +3526,15 @@ function callVisitor(key, node, visitor, path) {
3534
3526
  if (typeof visitor === 'function')
3535
3527
  return visitor(key, node, path);
3536
3528
  if (isMap(node))
3537
- return _optionalChain$z([visitor, 'access', _ => _.Map, 'optionalCall', _2 => _2(key, node, path)]);
3529
+ return _optionalChain$o([visitor, 'access', _ => _.Map, 'optionalCall', _2 => _2(key, node, path)]);
3538
3530
  if (isSeq(node))
3539
- return _optionalChain$z([visitor, 'access', _3 => _3.Seq, 'optionalCall', _4 => _4(key, node, path)]);
3531
+ return _optionalChain$o([visitor, 'access', _3 => _3.Seq, 'optionalCall', _4 => _4(key, node, path)]);
3540
3532
  if (isPair(node))
3541
- return _optionalChain$z([visitor, 'access', _5 => _5.Pair, 'optionalCall', _6 => _6(key, node, path)]);
3533
+ return _optionalChain$o([visitor, 'access', _5 => _5.Pair, 'optionalCall', _6 => _6(key, node, path)]);
3542
3534
  if (isScalar(node))
3543
- return _optionalChain$z([visitor, 'access', _7 => _7.Scalar, 'optionalCall', _8 => _8(key, node, path)]);
3535
+ return _optionalChain$o([visitor, 'access', _7 => _7.Scalar, 'optionalCall', _8 => _8(key, node, path)]);
3544
3536
  if (isAlias(node))
3545
- return _optionalChain$z([visitor, 'access', _9 => _9.Alias, 'optionalCall', _10 => _10(key, node, path)]);
3537
+ return _optionalChain$o([visitor, 'access', _9 => _9.Alias, 'optionalCall', _10 => _10(key, node, path)]);
3546
3538
  return undefined;
3547
3539
  }
3548
3540
  function replaceNode(key, path, node) {
@@ -3633,7 +3625,7 @@ function applyReviver(reviver, obj, key, val) {
3633
3625
  return reviver.call(obj, key, val);
3634
3626
  }
3635
3627
 
3636
- function _optionalChain$y(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = fn(value); } else if (op === 'call' || op === 'optionalCall') { value = fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; }
3628
+ function _optionalChain$n(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = fn(value); } else if (op === 'call' || op === 'optionalCall') { value = fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; }
3637
3629
  /**
3638
3630
  * Recursively convert any node or its contents to native JavaScript
3639
3631
  *
@@ -3663,7 +3655,7 @@ function toJS(value, arg, ctx) {
3663
3655
  ctx.onCreate(res);
3664
3656
  return res;
3665
3657
  }
3666
- if (typeof value === 'bigint' && !_optionalChain$y([ctx, 'optionalAccess', _ => _.keep]))
3658
+ if (typeof value === 'bigint' && !_optionalChain$n([ctx, 'optionalAccess', _ => _.keep]))
3667
3659
  return Number(value);
3668
3660
  return value;
3669
3661
  }
@@ -3701,7 +3693,7 @@ class NodeBase {
3701
3693
  }
3702
3694
  }
3703
3695
 
3704
- function _optionalChain$x(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = fn(value); } else if (op === 'call' || op === 'optionalCall') { value = fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; }
3696
+ function _optionalChain$m(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = fn(value); } else if (op === 'call' || op === 'optionalCall') { value = fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; }
3705
3697
  class Alias extends NodeBase {
3706
3698
  constructor(source) {
3707
3699
  super(ALIAS);
@@ -3717,10 +3709,10 @@ class Alias extends NodeBase {
3717
3709
  * instance of the `source` anchor before this node.
3718
3710
  */
3719
3711
  resolve(doc, ctx) {
3720
- if (_optionalChain$x([ctx, 'optionalAccess', _ => _.maxAliasCount]) === 0)
3712
+ if (_optionalChain$m([ctx, 'optionalAccess', _ => _.maxAliasCount]) === 0)
3721
3713
  throw new ReferenceError('Alias resolution is disabled');
3722
3714
  let nodes;
3723
- if (_optionalChain$x([ctx, 'optionalAccess', _2 => _2.aliasResolveCache])) {
3715
+ if (_optionalChain$m([ctx, 'optionalAccess', _2 => _2.aliasResolveCache])) {
3724
3716
  nodes = ctx.aliasResolveCache;
3725
3717
  }
3726
3718
  else {
@@ -3759,7 +3751,7 @@ class Alias extends NodeBase {
3759
3751
  data = anchors.get(source);
3760
3752
  }
3761
3753
  /* istanbul ignore if */
3762
- if (_optionalChain$x([data, 'optionalAccess', _3 => _3.res]) === undefined) {
3754
+ if (_optionalChain$m([data, 'optionalAccess', _3 => _3.res]) === undefined) {
3763
3755
  const msg = 'This should not happen: Alias anchor was not resolved?';
3764
3756
  throw new ReferenceError(msg);
3765
3757
  }
@@ -3811,7 +3803,7 @@ function getAliasCount(doc, node, anchors) {
3811
3803
  return 1;
3812
3804
  }
3813
3805
 
3814
- function _optionalChain$w(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = fn(value); } else if (op === 'call' || op === 'optionalCall') { value = fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; }
3806
+ function _optionalChain$l(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = fn(value); } else if (op === 'call' || op === 'optionalCall') { value = fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; }
3815
3807
  const isScalarValue = (value) => !value || (typeof value !== 'function' && typeof value !== 'object');
3816
3808
  class Scalar extends NodeBase {
3817
3809
  constructor(value) {
@@ -3819,7 +3811,7 @@ class Scalar extends NodeBase {
3819
3811
  this.value = value;
3820
3812
  }
3821
3813
  toJSON(arg, ctx) {
3822
- return _optionalChain$w([ctx, 'optionalAccess', _ => _.keep]) ? this.value : toJS(this.value, arg, ctx);
3814
+ return _optionalChain$l([ctx, 'optionalAccess', _ => _.keep]) ? this.value : toJS(this.value, arg, ctx);
3823
3815
  }
3824
3816
  toString() {
3825
3817
  return String(this.value);
@@ -3831,17 +3823,17 @@ Scalar.PLAIN = 'PLAIN';
3831
3823
  Scalar.QUOTE_DOUBLE = 'QUOTE_DOUBLE';
3832
3824
  Scalar.QUOTE_SINGLE = 'QUOTE_SINGLE';
3833
3825
 
3834
- function _nullishCoalesce$a(lhs, rhsFn) { if (lhs != null) { return lhs; } else { return rhsFn(); } } function _optionalChain$v(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = fn(value); } else if (op === 'call' || op === 'optionalCall') { value = fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; }
3826
+ function _nullishCoalesce$8(lhs, rhsFn) { if (lhs != null) { return lhs; } else { return rhsFn(); } } function _optionalChain$k(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = fn(value); } else if (op === 'call' || op === 'optionalCall') { value = fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; }
3835
3827
  const defaultTagPrefix = 'tag:yaml.org,2002:';
3836
3828
  function findTagObject(value, tagName, tags) {
3837
3829
  if (tagName) {
3838
3830
  const match = tags.filter(t => t.tag === tagName);
3839
- const tagObj = _nullishCoalesce$a(match.find(t => !t.format), () => ( match[0]));
3831
+ const tagObj = _nullishCoalesce$8(match.find(t => !t.format), () => ( match[0]));
3840
3832
  if (!tagObj)
3841
3833
  throw new Error(`Tag ${tagName} not found`);
3842
3834
  return tagObj;
3843
3835
  }
3844
- return tags.find(t => _optionalChain$v([t, 'access', _ => _.identify, 'optionalCall', _2 => _2(value)]) && !t.format);
3836
+ return tags.find(t => _optionalChain$k([t, 'access', _ => _.identify, 'optionalCall', _2 => _2(value)]) && !t.format);
3845
3837
  }
3846
3838
  function createNode(value, tagName, ctx) {
3847
3839
  if (isDocument(value))
@@ -3849,7 +3841,7 @@ function createNode(value, tagName, ctx) {
3849
3841
  if (isNode(value))
3850
3842
  return value;
3851
3843
  if (isPair(value)) {
3852
- const map = _optionalChain$v([ctx, 'access', _3 => _3.schema, 'access', _4 => _4[MAP], 'access', _5 => _5.createNode, 'optionalCall', _6 => _6(ctx.schema, null, ctx)]);
3844
+ const map = _optionalChain$k([ctx, 'access', _3 => _3.schema, 'access', _4 => _4[MAP], 'access', _5 => _5.createNode, 'optionalCall', _6 => _6(ctx.schema, null, ctx)]);
3853
3845
  map.items.push(value);
3854
3846
  return map;
3855
3847
  }
@@ -3868,7 +3860,7 @@ function createNode(value, tagName, ctx) {
3868
3860
  if (aliasDuplicateObjects && value && typeof value === 'object') {
3869
3861
  ref = sourceObjects.get(value);
3870
3862
  if (ref) {
3871
- _nullishCoalesce$a(ref.anchor, () => ( (ref.anchor = onAnchor(value))));
3863
+ _nullishCoalesce$8(ref.anchor, () => ( (ref.anchor = onAnchor(value))));
3872
3864
  return new Alias(ref.anchor);
3873
3865
  }
3874
3866
  else {
@@ -3876,7 +3868,7 @@ function createNode(value, tagName, ctx) {
3876
3868
  sourceObjects.set(value, ref);
3877
3869
  }
3878
3870
  }
3879
- if (_optionalChain$v([tagName, 'optionalAccess', _7 => _7.startsWith, 'call', _8 => _8('!!')]))
3871
+ if (_optionalChain$k([tagName, 'optionalAccess', _7 => _7.startsWith, 'call', _8 => _8('!!')]))
3880
3872
  tagName = defaultTagPrefix + tagName.slice(2);
3881
3873
  let tagObj = findTagObject(value, tagName, schema.tags);
3882
3874
  if (!tagObj) {
@@ -3901,9 +3893,9 @@ function createNode(value, tagName, ctx) {
3901
3893
  onTagObj(tagObj);
3902
3894
  delete ctx.onTagObj;
3903
3895
  }
3904
- const node = _optionalChain$v([tagObj, 'optionalAccess', _9 => _9.createNode])
3896
+ const node = _optionalChain$k([tagObj, 'optionalAccess', _9 => _9.createNode])
3905
3897
  ? tagObj.createNode(ctx.schema, value, ctx)
3906
- : typeof _optionalChain$v([tagObj, 'optionalAccess', _10 => _10.nodeClass, 'optionalAccess', _11 => _11.from]) === 'function'
3898
+ : typeof _optionalChain$k([tagObj, 'optionalAccess', _10 => _10.nodeClass, 'optionalAccess', _11 => _11.from]) === 'function'
3907
3899
  ? tagObj.nodeClass.from(ctx.schema, value, ctx)
3908
3900
  : new Scalar(value);
3909
3901
  if (tagName)
@@ -4221,7 +4213,7 @@ function consumeMoreIndentedLines(text, i, indent) {
4221
4213
  return end;
4222
4214
  }
4223
4215
 
4224
- function _optionalChain$u(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = fn(value); } else if (op === 'call' || op === 'optionalCall') { value = fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; }
4216
+ function _optionalChain$j(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = fn(value); } else if (op === 'call' || op === 'optionalCall') { value = fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; }
4225
4217
  const getFoldOptions = (ctx, isBlock) => ({
4226
4218
  indentAtStart: isBlock ? ctx.indent.length : ctx.indentAtStart,
4227
4219
  lineWidth: ctx.options.lineWidth,
@@ -4506,9 +4498,9 @@ function plainString(item, ctx, onComment, onChompKeep) {
4506
4498
  // booleans get parsed with those types in v1.2 (e.g. '42', 'true' & '0.9e-3'),
4507
4499
  // and others in v1.1.
4508
4500
  if (actualString) {
4509
- const test = (tag) => tag.default && tag.tag !== 'tag:yaml.org,2002:str' && _optionalChain$u([tag, 'access', _ => _.test, 'optionalAccess', _2 => _2.test, 'call', _3 => _3(str)]);
4501
+ const test = (tag) => tag.default && tag.tag !== 'tag:yaml.org,2002:str' && _optionalChain$j([tag, 'access', _ => _.test, 'optionalAccess', _2 => _2.test, 'call', _3 => _3(str)]);
4510
4502
  const { compat, tags } = ctx.doc.schema;
4511
- if (tags.some(test) || _optionalChain$u([compat, 'optionalAccess', _4 => _4.some, 'call', _5 => _5(test)]))
4503
+ if (tags.some(test) || _optionalChain$j([compat, 'optionalAccess', _4 => _4.some, 'call', _5 => _5(test)]))
4512
4504
  return quotedString(value, ctx);
4513
4505
  }
4514
4506
  return implicitKey
@@ -4554,7 +4546,7 @@ function stringifyString(item, ctx, onComment, onChompKeep) {
4554
4546
  return res;
4555
4547
  }
4556
4548
 
4557
- function _nullishCoalesce$9(lhs, rhsFn) { if (lhs != null) { return lhs; } else { return rhsFn(); } } function _optionalChain$t(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = fn(value); } else if (op === 'call' || op === 'optionalCall') { value = fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; }
4549
+ function _nullishCoalesce$7(lhs, rhsFn) { if (lhs != null) { return lhs; } else { return rhsFn(); } } function _optionalChain$i(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = fn(value); } else if (op === 'call' || op === 'optionalCall') { value = fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; }
4558
4550
  function createStringifyContext(doc, options) {
4559
4551
  const opt = Object.assign({
4560
4552
  blockQuote: true,
@@ -4601,27 +4593,27 @@ function getTagObject(tags, item) {
4601
4593
  if (item.tag) {
4602
4594
  const match = tags.filter(t => t.tag === item.tag);
4603
4595
  if (match.length > 0)
4604
- return _nullishCoalesce$9(match.find(t => t.format === item.format), () => ( match[0]));
4596
+ return _nullishCoalesce$7(match.find(t => t.format === item.format), () => ( match[0]));
4605
4597
  }
4606
4598
  let tagObj = undefined;
4607
4599
  let obj;
4608
4600
  if (isScalar(item)) {
4609
4601
  obj = item.value;
4610
- let match = tags.filter(t => _optionalChain$t([t, 'access', _ => _.identify, 'optionalCall', _2 => _2(obj)]));
4602
+ let match = tags.filter(t => _optionalChain$i([t, 'access', _ => _.identify, 'optionalCall', _2 => _2(obj)]));
4611
4603
  if (match.length > 1) {
4612
4604
  const testMatch = match.filter(t => t.test);
4613
4605
  if (testMatch.length > 0)
4614
4606
  match = testMatch;
4615
4607
  }
4616
4608
  tagObj =
4617
- _nullishCoalesce$9(match.find(t => t.format === item.format), () => ( match.find(t => !t.format)));
4609
+ _nullishCoalesce$7(match.find(t => t.format === item.format), () => ( match.find(t => !t.format)));
4618
4610
  }
4619
4611
  else {
4620
4612
  obj = item;
4621
4613
  tagObj = tags.find(t => t.nodeClass && obj instanceof t.nodeClass);
4622
4614
  }
4623
4615
  if (!tagObj) {
4624
- const name = _nullishCoalesce$9(_optionalChain$t([obj, 'optionalAccess', _3 => _3.constructor, 'optionalAccess', _4 => _4.name]), () => ( (obj === null ? 'null' : typeof obj)));
4616
+ const name = _nullishCoalesce$7(_optionalChain$i([obj, 'optionalAccess', _3 => _3.constructor, 'optionalAccess', _4 => _4.name]), () => ( (obj === null ? 'null' : typeof obj)));
4625
4617
  throw new Error(`Tag not resolved for ${name} value`);
4626
4618
  }
4627
4619
  return tagObj;
@@ -4636,7 +4628,7 @@ function stringifyProps(node, tagObj, { anchors, doc }) {
4636
4628
  anchors.add(anchor);
4637
4629
  props.push(`&${anchor}`);
4638
4630
  }
4639
- const tag = _nullishCoalesce$9(node.tag, () => ( (tagObj.default ? null : tagObj.tag)));
4631
+ const tag = _nullishCoalesce$7(node.tag, () => ( (tagObj.default ? null : tagObj.tag)));
4640
4632
  if (tag)
4641
4633
  props.push(doc.directives.tagString(tag));
4642
4634
  return props.join(' ');
@@ -4647,7 +4639,7 @@ function stringify(item, ctx, onComment, onChompKeep) {
4647
4639
  if (isAlias(item)) {
4648
4640
  if (ctx.doc.directives)
4649
4641
  return item.toString(ctx);
4650
- if (_optionalChain$t([ctx, 'access', _5 => _5.resolvedAliases, 'optionalAccess', _6 => _6.has, 'call', _7 => _7(item)])) {
4642
+ if (_optionalChain$i([ctx, 'access', _5 => _5.resolvedAliases, 'optionalAccess', _6 => _6.has, 'call', _7 => _7(item)])) {
4651
4643
  throw new TypeError(`Cannot stringify circular structure without alias nodes`);
4652
4644
  }
4653
4645
  else {
@@ -4662,10 +4654,10 @@ function stringify(item, ctx, onComment, onChompKeep) {
4662
4654
  const node = isNode(item)
4663
4655
  ? item
4664
4656
  : ctx.doc.createNode(item, { onTagObj: o => (tagObj = o) });
4665
- _nullishCoalesce$9(tagObj, () => ( (tagObj = getTagObject(ctx.doc.schema.tags, node))));
4657
+ _nullishCoalesce$7(tagObj, () => ( (tagObj = getTagObject(ctx.doc.schema.tags, node))));
4666
4658
  const props = stringifyProps(node, tagObj, ctx);
4667
4659
  if (props.length > 0)
4668
- ctx.indentAtStart = (_nullishCoalesce$9(ctx.indentAtStart, () => ( 0))) + props.length + 1;
4660
+ ctx.indentAtStart = (_nullishCoalesce$7(ctx.indentAtStart, () => ( 0))) + props.length + 1;
4669
4661
  const str = typeof tagObj.stringify === 'function'
4670
4662
  ? tagObj.stringify(node, ctx, onComment, onChompKeep)
4671
4663
  : isScalar(node)
@@ -4678,7 +4670,7 @@ function stringify(item, ctx, onComment, onChompKeep) {
4678
4670
  : `${props}\n${ctx.indent}${str}`;
4679
4671
  }
4680
4672
 
4681
- function _nullishCoalesce$8(lhs, rhsFn) { if (lhs != null) { return lhs; } else { return rhsFn(); } }
4673
+ function _nullishCoalesce$6(lhs, rhsFn) { if (lhs != null) { return lhs; } else { return rhsFn(); } }
4682
4674
  function stringifyPair({ key, value }, ctx, onComment, onChompKeep) {
4683
4675
  const { allNullValues, doc, indent, indentStep, options: { commentString, indentSeq, simpleKeys } } = ctx;
4684
4676
  let keyComment = (isNode(key) && key.comment) || null;
@@ -4788,7 +4780,7 @@ function stringifyPair({ key, value }, ctx, onComment, onChompKeep) {
4788
4780
  const vs0 = valueStr[0];
4789
4781
  const nl0 = valueStr.indexOf('\n');
4790
4782
  const hasNewline = nl0 !== -1;
4791
- const flow = _nullishCoalesce$8(_nullishCoalesce$8(ctx.inFlow, () => ( value.flow)), () => ( value.items.length === 0));
4783
+ const flow = _nullishCoalesce$6(_nullishCoalesce$6(ctx.inFlow, () => ( value.flow)), () => ( value.items.length === 0));
4792
4784
  if (hasNewline || !flow) {
4793
4785
  let hasPropsLine = false;
4794
4786
  if (hasNewline && (vs0 === '&' || vs0 === '!')) {
@@ -4829,7 +4821,7 @@ function warn(logLevel, warning) {
4829
4821
  }
4830
4822
  }
4831
4823
 
4832
- function _optionalChain$s(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = fn(value); } else if (op === 'call' || op === 'optionalCall') { value = fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; }
4824
+ function _optionalChain$h(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = fn(value); } else if (op === 'call' || op === 'optionalCall') { value = fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; }
4833
4825
  // If the value associated with a merge key is a single mapping node, each of
4834
4826
  // its key/value pairs is inserted into the current mapping, unless the key
4835
4827
  // already exists in it. If the value associated with the merge key is a
@@ -4853,7 +4845,7 @@ const isMergeKey = (ctx, key) => (merge.identify(key) ||
4853
4845
  (isScalar(key) &&
4854
4846
  (!key.type || key.type === Scalar.PLAIN) &&
4855
4847
  merge.identify(key.value))) &&
4856
- _optionalChain$s([ctx, 'optionalAccess', _ => _.doc, 'access', _2 => _2.schema, 'access', _3 => _3.tags, 'access', _4 => _4.some, 'call', _5 => _5(tag => tag.tag === merge.tag && tag.default)]);
4848
+ _optionalChain$h([ctx, 'optionalAccess', _ => _.doc, 'access', _2 => _2.schema, 'access', _3 => _3.tags, 'access', _4 => _4.some, 'call', _5 => _5(tag => tag.tag === merge.tag && tag.default)]);
4857
4849
  function addMergeToJSMap(ctx, map, value) {
4858
4850
  const source = resolveAliasValue(ctx, value);
4859
4851
  if (isSeq(source))
@@ -4893,7 +4885,7 @@ function resolveAliasValue(ctx, value) {
4893
4885
  return ctx && isAlias(value) ? value.resolve(ctx.doc, ctx) : value;
4894
4886
  }
4895
4887
 
4896
- function _optionalChain$r(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = fn(value); } else if (op === 'call' || op === 'optionalCall') { value = fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; }
4888
+ function _optionalChain$g(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = fn(value); } else if (op === 'call' || op === 'optionalCall') { value = fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; }
4897
4889
  function addPairToJSMap(ctx, map, { key, value }) {
4898
4890
  if (isNode(key) && key.addToJSMap)
4899
4891
  key.addToJSMap(ctx, map, value);
@@ -4930,7 +4922,7 @@ function stringifyKey(key, jsKey, ctx) {
4930
4922
  // eslint-disable-next-line @typescript-eslint/no-base-to-string
4931
4923
  if (typeof jsKey !== 'object')
4932
4924
  return String(jsKey);
4933
- if (isNode(key) && _optionalChain$r([ctx, 'optionalAccess', _ => _.doc])) {
4925
+ if (isNode(key) && _optionalChain$g([ctx, 'optionalAccess', _ => _.doc])) {
4934
4926
  const strCtx = createStringifyContext(ctx.doc, {});
4935
4927
  strCtx.anchors = new Set();
4936
4928
  for (const node of ctx.anchors.keys())
@@ -4950,7 +4942,7 @@ function stringifyKey(key, jsKey, ctx) {
4950
4942
  return JSON.stringify(jsKey);
4951
4943
  }
4952
4944
 
4953
- function _optionalChain$q(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = fn(value); } else if (op === 'call' || op === 'optionalCall') { value = fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; }
4945
+ function _optionalChain$f(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = fn(value); } else if (op === 'call' || op === 'optionalCall') { value = fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; }
4954
4946
  function createPair(key, value, ctx) {
4955
4947
  const k = createNode(key, undefined, ctx);
4956
4948
  const v = createNode(value, undefined, ctx);
@@ -4971,19 +4963,19 @@ class Pair {
4971
4963
  return new Pair(key, value);
4972
4964
  }
4973
4965
  toJSON(_, ctx) {
4974
- const pair = _optionalChain$q([ctx, 'optionalAccess', _2 => _2.mapAsMap]) ? new Map() : {};
4966
+ const pair = _optionalChain$f([ctx, 'optionalAccess', _2 => _2.mapAsMap]) ? new Map() : {};
4975
4967
  return addPairToJSMap(ctx, pair, this);
4976
4968
  }
4977
4969
  toString(ctx, onComment, onChompKeep) {
4978
- return _optionalChain$q([ctx, 'optionalAccess', _3 => _3.doc])
4970
+ return _optionalChain$f([ctx, 'optionalAccess', _3 => _3.doc])
4979
4971
  ? stringifyPair(this, ctx, onComment, onChompKeep)
4980
4972
  : JSON.stringify(this);
4981
4973
  }
4982
4974
  }
4983
4975
 
4984
- function _nullishCoalesce$7(lhs, rhsFn) { if (lhs != null) { return lhs; } else { return rhsFn(); } } function _optionalChain$p(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = fn(value); } else if (op === 'call' || op === 'optionalCall') { value = fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; }
4976
+ function _nullishCoalesce$5(lhs, rhsFn) { if (lhs != null) { return lhs; } else { return rhsFn(); } } function _optionalChain$e(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = fn(value); } else if (op === 'call' || op === 'optionalCall') { value = fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; }
4985
4977
  function stringifyCollection(collection, ctx, options) {
4986
- const flow = _nullishCoalesce$7(ctx.inFlow, () => ( collection.flow));
4978
+ const flow = _nullishCoalesce$5(ctx.inFlow, () => ( collection.flow));
4987
4979
  const stringify = flow ? stringifyFlowCollection : stringifyBlockCollection;
4988
4980
  return stringify(collection, ctx, options);
4989
4981
  }
@@ -5075,7 +5067,7 @@ function stringifyFlowCollection({ items }, ctx, { flowChars, itemIndent }) {
5075
5067
  if (iv.commentBefore)
5076
5068
  reqNewline = true;
5077
5069
  }
5078
- else if (item.value == null && _optionalChain$p([ik, 'optionalAccess', _ => _.comment])) {
5070
+ else if (item.value == null && _optionalChain$e([ik, 'optionalAccess', _ => _.comment])) {
5079
5071
  comment = ik.comment;
5080
5072
  }
5081
5073
  }
@@ -5130,7 +5122,7 @@ function addCommentBefore({ indent, options: { commentString } }, lines, comment
5130
5122
  }
5131
5123
  }
5132
5124
 
5133
- function _nullishCoalesce$6(lhs, rhsFn) { if (lhs != null) { return lhs; } else { return rhsFn(); } } function _optionalChain$o(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = fn(value); } else if (op === 'call' || op === 'optionalCall') { value = fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; }
5125
+ function _nullishCoalesce$4(lhs, rhsFn) { if (lhs != null) { return lhs; } else { return rhsFn(); } } function _optionalChain$d(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = fn(value); } else if (op === 'call' || op === 'optionalCall') { value = fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; }
5134
5126
  function findPair(items, key) {
5135
5127
  const k = isScalar(key) ? key.value : key;
5136
5128
  for (const it of items) {
@@ -5191,12 +5183,12 @@ class YAMLMap extends Collection {
5191
5183
  _pair = pair;
5192
5184
  else if (!pair || typeof pair !== 'object' || !('key' in pair)) {
5193
5185
  // In TypeScript, this never happens.
5194
- _pair = new Pair(pair, _optionalChain$o([pair, 'optionalAccess', _2 => _2.value]));
5186
+ _pair = new Pair(pair, _optionalChain$d([pair, 'optionalAccess', _2 => _2.value]));
5195
5187
  }
5196
5188
  else
5197
5189
  _pair = new Pair(pair.key, pair.value);
5198
5190
  const prev = findPair(this.items, _pair.key);
5199
- const sortEntries = _optionalChain$o([this, 'access', _3 => _3.schema, 'optionalAccess', _4 => _4.sortMapEntries]);
5191
+ const sortEntries = _optionalChain$d([this, 'access', _3 => _3.schema, 'optionalAccess', _4 => _4.sortMapEntries]);
5200
5192
  if (prev) {
5201
5193
  if (!overwrite)
5202
5194
  throw new Error(`Key ${_pair.key} already set`);
@@ -5226,8 +5218,8 @@ class YAMLMap extends Collection {
5226
5218
  }
5227
5219
  get(key, keepScalar) {
5228
5220
  const it = findPair(this.items, key);
5229
- const node = _optionalChain$o([it, 'optionalAccess', _5 => _5.value]);
5230
- return _nullishCoalesce$6((!keepScalar && isScalar(node) ? node.value : node), () => ( undefined));
5221
+ const node = _optionalChain$d([it, 'optionalAccess', _5 => _5.value]);
5222
+ return _nullishCoalesce$4((!keepScalar && isScalar(node) ? node.value : node), () => ( undefined));
5231
5223
  }
5232
5224
  has(key) {
5233
5225
  return !!findPair(this.items, key);
@@ -5241,8 +5233,8 @@ class YAMLMap extends Collection {
5241
5233
  * @returns Instance of Type, Map, or Object
5242
5234
  */
5243
5235
  toJSON(_, ctx, Type) {
5244
- const map = Type ? new Type() : _optionalChain$o([ctx, 'optionalAccess', _6 => _6.mapAsMap]) ? new Map() : {};
5245
- if (_optionalChain$o([ctx, 'optionalAccess', _7 => _7.onCreate]))
5236
+ const map = Type ? new Type() : _optionalChain$d([ctx, 'optionalAccess', _6 => _6.mapAsMap]) ? new Map() : {};
5237
+ if (_optionalChain$d([ctx, 'optionalAccess', _7 => _7.onCreate]))
5246
5238
  ctx.onCreate(map);
5247
5239
  for (const item of this.items)
5248
5240
  addPairToJSMap(ctx, map, item);
@@ -5267,7 +5259,7 @@ class YAMLMap extends Collection {
5267
5259
  }
5268
5260
  }
5269
5261
 
5270
- function _optionalChain$n(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = fn(value); } else if (op === 'call' || op === 'optionalCall') { value = fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; }
5262
+ function _optionalChain$c(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = fn(value); } else if (op === 'call' || op === 'optionalCall') { value = fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; }
5271
5263
  class YAMLSeq extends Collection {
5272
5264
  static get tagName() {
5273
5265
  return 'tag:yaml.org,2002:seq';
@@ -5330,7 +5322,7 @@ class YAMLSeq extends Collection {
5330
5322
  }
5331
5323
  toJSON(_, ctx) {
5332
5324
  const seq = [];
5333
- if (_optionalChain$n([ctx, 'optionalAccess', _2 => _2.onCreate]))
5325
+ if (_optionalChain$c([ctx, 'optionalAccess', _2 => _2.onCreate]))
5334
5326
  ctx.onCreate(seq);
5335
5327
  let i = 0;
5336
5328
  for (const item of this.items)
@@ -5409,7 +5401,7 @@ function createPairs(schema, iterable, ctx) {
5409
5401
  return pairs;
5410
5402
  }
5411
5403
 
5412
- function _optionalChain$m(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = fn(value); } else if (op === 'call' || op === 'optionalCall') { value = fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; }
5404
+ function _optionalChain$b(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = fn(value); } else if (op === 'call' || op === 'optionalCall') { value = fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; }
5413
5405
  class YAMLOMap extends YAMLSeq {
5414
5406
  constructor() {
5415
5407
  super();
@@ -5428,7 +5420,7 @@ class YAMLOMap extends YAMLSeq {
5428
5420
  if (!ctx)
5429
5421
  return super.toJSON(_);
5430
5422
  const map = new Map();
5431
- if (_optionalChain$m([ctx, 'optionalAccess', _2 => _2.onCreate]))
5423
+ if (_optionalChain$b([ctx, 'optionalAccess', _2 => _2.onCreate]))
5432
5424
  ctx.onCreate(map);
5433
5425
  for (const pair of this.items) {
5434
5426
  let key, value;
@@ -5546,7 +5538,7 @@ const isDirExists = async (file) => {
5546
5538
  }
5547
5539
  };
5548
5540
 
5549
- function _optionalChain$l(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = fn(value); } else if (op === 'call' || op === 'optionalCall') { value = fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; }// ABOUTME: Project type detection utility
5541
+ function _optionalChain$a(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = fn(value); } else if (op === 'call' || op === 'optionalCall') { value = fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; }// ABOUTME: Project type detection utility
5550
5542
 
5551
5543
  /**
5552
5544
  * 支持的项目类型枚举
@@ -5648,7 +5640,7 @@ const collectProjectInfo = async (
5648
5640
  }
5649
5641
 
5650
5642
  const scripts = Object.entries(
5651
- (_optionalChain$l([packageJson, 'optionalAccess', _ => _.scripts]) ) || {},
5643
+ (_optionalChain$a([packageJson, 'optionalAccess', _ => _.scripts]) ) || {},
5652
5644
  ).reduce((acc, [name, script]) => {
5653
5645
  if (typeof script === 'string') {
5654
5646
  acc[name] = script;
@@ -5802,7 +5794,7 @@ const detectProjectType = async (
5802
5794
  };
5803
5795
  };
5804
5796
 
5805
- function _optionalChain$k(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = fn(value); } else if (op === 'call' || op === 'optionalCall') { value = fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; }
5797
+ function _optionalChain$9(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = fn(value); } else if (op === 'call' || op === 'optionalCall') { value = fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; }
5806
5798
 
5807
5799
 
5808
5800
  /**
@@ -5814,7 +5806,7 @@ function _optionalChain$k(ops) { let lastAccessLHS = undefined; let value = ops[
5814
5806
  const parseConfigContent = (content) => {
5815
5807
  // 1. 尝试 TOML 格式 (默认)
5816
5808
  try {
5817
- const config = TOML.parse(content);
5809
+ const config = toml.parse(content);
5818
5810
  return config ;
5819
5811
  } catch (error) {
5820
5812
  // TOML 解析失败,继续尝试其他格式
@@ -5848,7 +5840,7 @@ const parseConfigContent = (content) => {
5848
5840
  */
5849
5841
  const parseTomlConfigContent = (content) => {
5850
5842
  try {
5851
- return TOML.parse(content) ;
5843
+ return toml.parse(content) ;
5852
5844
  } catch (e) {
5853
5845
  return null;
5854
5846
  }
@@ -5929,7 +5921,7 @@ const saveTomlCozeConfig = async (
5929
5921
  projectPath,
5930
5922
  `.coze.tmp-${process.pid}-${Date.now()}`,
5931
5923
  );
5932
- const content = TOML.stringify(config );
5924
+ const content = toml.stringify(config );
5933
5925
 
5934
5926
  try {
5935
5927
  await fs$1.writeFile(tempCozeConfigPath, content, 'utf-8');
@@ -5976,16 +5968,16 @@ const getCommandConfig = (
5976
5968
 
5977
5969
  switch (commandName) {
5978
5970
  case 'dev':
5979
- commandConfig = _optionalChain$k([config, 'access', _ => _.dev, 'optionalAccess', _2 => _2.run]);
5971
+ commandConfig = _optionalChain$9([config, 'access', _ => _.dev, 'optionalAccess', _2 => _2.run]);
5980
5972
  break;
5981
5973
  case 'build':
5982
- commandConfig = _optionalChain$k([config, 'access', _3 => _3.deploy, 'optionalAccess', _4 => _4.build]);
5974
+ commandConfig = _optionalChain$9([config, 'access', _3 => _3.deploy, 'optionalAccess', _4 => _4.build]);
5983
5975
  break;
5984
5976
  case 'start':
5985
- commandConfig = _optionalChain$k([config, 'access', _5 => _5.deploy, 'optionalAccess', _6 => _6.run]);
5977
+ commandConfig = _optionalChain$9([config, 'access', _5 => _5.deploy, 'optionalAccess', _6 => _6.run]);
5986
5978
  break;
5987
5979
  case 'validate':
5988
- commandConfig = _optionalChain$k([config, 'access', _7 => _7.dev, 'optionalAccess', _8 => _8.validate]);
5980
+ commandConfig = _optionalChain$9([config, 'access', _7 => _7.dev, 'optionalAccess', _8 => _8.validate]);
5989
5981
  break;
5990
5982
  default:
5991
5983
  throw new Error(`Unknown command: ${commandName}`);
@@ -6136,7 +6128,7 @@ const byFlag = (flag) => {
6136
6128
  return predicate;
6137
6129
  };
6138
6130
 
6139
- function _optionalChain$j(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = fn(value); } else if (op === 'call' || op === 'optionalCall') { value = fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; }
6131
+ function _optionalChain$8(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = fn(value); } else if (op === 'call' || op === 'optionalCall') { value = fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; }
6140
6132
 
6141
6133
 
6142
6134
 
@@ -6167,7 +6159,7 @@ echo "Validate passed!"
6167
6159
  * @returns
6168
6160
  */
6169
6161
  const isCozeValid$3 = (cozeConfig) => {
6170
- if (_optionalChain$j([cozeConfig, 'access', _ => _.dev, 'optionalAccess', _2 => _2.validate])) {
6162
+ if (_optionalChain$8([cozeConfig, 'access', _ => _.dev, 'optionalAccess', _2 => _2.validate])) {
6171
6163
  logger.info('[patch-expo-validate] NOT APPLY: dev.validate exists');
6172
6164
  return false;
6173
6165
  }
@@ -6312,7 +6304,7 @@ const patchExpoValidate = {
6312
6304
  },
6313
6305
  };
6314
6306
 
6315
- function _optionalChain$i(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = fn(value); } else if (op === 'call' || op === 'optionalCall') { value = fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; }
6307
+ function _optionalChain$7(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = fn(value); } else if (op === 'call' || op === 'optionalCall') { value = fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; }
6316
6308
 
6317
6309
 
6318
6310
 
@@ -6345,7 +6337,7 @@ echo "Validate passed!"
6345
6337
  * @returns
6346
6338
  */
6347
6339
  const isCozeValid$2 = (cozeConfig) => {
6348
- if (_optionalChain$i([cozeConfig, 'access', _ => _.dev, 'optionalAccess', _2 => _2.validate])) {
6340
+ if (_optionalChain$7([cozeConfig, 'access', _ => _.dev, 'optionalAccess', _2 => _2.validate])) {
6349
6341
  logger.info('[patch-nextjs-validate] NOT APPLY: dev.validate exists');
6350
6342
  return false;
6351
6343
  }
@@ -6493,7 +6485,7 @@ const patchNextjsValidate = {
6493
6485
  },
6494
6486
  };
6495
6487
 
6496
- function _optionalChain$h(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = fn(value); } else if (op === 'call' || op === 'optionalCall') { value = fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; }
6488
+ function _optionalChain$6(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = fn(value); } else if (op === 'call' || op === 'optionalCall') { value = fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; }
6497
6489
 
6498
6490
  const PATCH_ID$5 = 'nextjs/validate-concurrently@0.0.30';
6499
6491
  const PACKAGE_JSON_FILE$3 = 'package.json';
@@ -6526,7 +6518,7 @@ const readPackageJson = async (projectFolder) => {
6526
6518
  };
6527
6519
 
6528
6520
  const getTargetValidateScript = (packageJson) => {
6529
- const validateScript = _optionalChain$h([packageJson, 'access', _ => _.scripts, 'optionalAccess', _2 => _2.validate]);
6521
+ const validateScript = _optionalChain$6([packageJson, 'access', _ => _.scripts, 'optionalAccess', _2 => _2.validate]);
6530
6522
  if (typeof validateScript !== 'string') {
6531
6523
  return null;
6532
6524
  }
@@ -6543,7 +6535,7 @@ const getTargetValidateScript = (packageJson) => {
6543
6535
 
6544
6536
  const canStackAfterNextjsValidatePatch = async (context, packageJson) => {
6545
6537
  const scripts = packageJson.scripts || {};
6546
- if (typeof scripts.validate !== 'undefined' || typeof scripts['ts-check'] !== 'string' || _optionalChain$h([context, 'access', _3 => _3.cozeConfig, 'access', _4 => _4.dev, 'optionalAccess', _5 => _5.validate])) {
6538
+ if (typeof scripts.validate !== 'undefined' || typeof scripts['ts-check'] !== 'string' || _optionalChain$6([context, 'access', _3 => _3.cozeConfig, 'access', _4 => _4.dev, 'optionalAccess', _5 => _5.validate])) {
6547
6539
  return false;
6548
6540
  }
6549
6541
 
@@ -6612,7 +6604,7 @@ const patchNextjsValidateConcurrently = {
6612
6604
  apply: patchPackageJson$2,
6613
6605
  };
6614
6606
 
6615
- function _optionalChain$g(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = fn(value); } else if (op === 'call' || op === 'optionalCall') { value = fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; }
6607
+ function _optionalChain$5(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = fn(value); } else if (op === 'call' || op === 'optionalCall') { value = fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; }
6616
6608
 
6617
6609
 
6618
6610
 
@@ -6645,7 +6637,7 @@ echo "Validate passed!"
6645
6637
  * @returns
6646
6638
  */
6647
6639
  const isCozeValid$1 = (cozeConfig) => {
6648
- if (_optionalChain$g([cozeConfig, 'access', _ => _.dev, 'optionalAccess', _2 => _2.validate])) {
6640
+ if (_optionalChain$5([cozeConfig, 'access', _ => _.dev, 'optionalAccess', _2 => _2.validate])) {
6649
6641
  logger.info('[patch-vite-validate] NOT APPLY: dev.validate exists');
6650
6642
  return false;
6651
6643
  }
@@ -6790,7 +6782,7 @@ const patchViteValidate = {
6790
6782
  },
6791
6783
  };
6792
6784
 
6793
- function _optionalChain$f(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = fn(value); } else if (op === 'call' || op === 'optionalCall') { value = fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; }
6785
+ function _optionalChain$4(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = fn(value); } else if (op === 'call' || op === 'optionalCall') { value = fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; }
6794
6786
 
6795
6787
 
6796
6788
 
@@ -6827,7 +6819,7 @@ echo "Validate passed!"
6827
6819
  * @returns
6828
6820
  */
6829
6821
  const isCozeValid = (cozeConfig) => {
6830
- if (_optionalChain$f([cozeConfig, 'access', _ => _.dev, 'optionalAccess', _2 => _2.validate])) {
6822
+ if (_optionalChain$4([cozeConfig, 'access', _ => _.dev, 'optionalAccess', _2 => _2.validate])) {
6831
6823
  logger.info('[patch-taro-validate] NOT APPLY: dev.validate exists');
6832
6824
  return false;
6833
6825
  }
@@ -6976,7 +6968,7 @@ const patchTaroValidate = {
6976
6968
  },
6977
6969
  };
6978
6970
 
6979
- function _optionalChain$e(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = fn(value); } else if (op === 'call' || op === 'optionalCall') { value = fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; }
6971
+ function _optionalChain$3(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = fn(value); } else if (op === 'call' || op === 'optionalCall') { value = fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; }
6980
6972
  const PATCH_ID$2 = 'taro/update-pack-script-for-tt-build@0.0.13';
6981
6973
  const PACKAGE_JSON_FILE = 'package.json';
6982
6974
  const PACK_SCRIPT_FILE = '.cozeproj/scripts/pack.sh';
@@ -7055,12 +7047,12 @@ const readPackageScripts = async (
7055
7047
  const packageJsonContent = await fs$1.readFile(packageJsonPath, 'utf-8');
7056
7048
  const packageJson = safeJsonParse(packageJsonContent, null);
7057
7049
 
7058
- return _optionalChain$e([packageJson, 'optionalAccess', _ => _.scripts]) || null;
7050
+ return _optionalChain$3([packageJson, 'optionalAccess', _ => _.scripts]) || null;
7059
7051
  };
7060
7052
 
7061
7053
  const hasBuildTtScript = async (projectFolder) => {
7062
7054
  const scripts = await readPackageScripts(projectFolder);
7063
- return typeof _optionalChain$e([scripts, 'optionalAccess', _2 => _2['build:tt']]) === 'string';
7055
+ return typeof _optionalChain$3([scripts, 'optionalAccess', _2 => _2['build:tt']]) === 'string';
7064
7056
  };
7065
7057
 
7066
7058
  const hasLegacyPackScript = async (projectFolder) => {
@@ -7414,7 +7406,7 @@ const getTemplatePatches = (
7414
7406
  ) =>
7415
7407
  patches.filter(patch => patch.template === template);
7416
7408
 
7417
- function _nullishCoalesce$5(lhs, rhsFn) { if (lhs != null) { return lhs; } else { return rhsFn(); } } function _optionalChain$d(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = fn(value); } else if (op === 'call' || op === 'optionalCall') { value = fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; }
7409
+ function _nullishCoalesce$3(lhs, rhsFn) { if (lhs != null) { return lhs; } else { return rhsFn(); } } function _optionalChain$2(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = fn(value); } else if (op === 'call' || op === 'optionalCall') { value = fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; }
7418
7410
  const DEFAULT_LEGACY_VERSION = 'legacy';
7419
7411
 
7420
7412
  const loadFlagsWithFallback = async () => {
@@ -7520,7 +7512,7 @@ const getNextPatchState = (
7520
7512
 
7521
7513
  ) => ({
7522
7514
  template,
7523
- version: _optionalChain$d([config, 'access', _ => _.project, 'optionalAccess', _2 => _2.version]) || DEFAULT_LEGACY_VERSION,
7515
+ version: _optionalChain$2([config, 'access', _ => _.project, 'optionalAccess', _2 => _2.version]) || DEFAULT_LEGACY_VERSION,
7524
7516
  appliedPatches: [...appliedPatches, patchId],
7525
7517
  });
7526
7518
 
@@ -7544,15 +7536,15 @@ const executePatch = async (
7544
7536
  }
7545
7537
 
7546
7538
  const template =
7547
- _optionalChain$d([config, 'access', _3 => _3.project, 'optionalAccess', _4 => _4.template]) || (await detectTemplateKey(projectFolder));
7539
+ _optionalChain$2([config, 'access', _3 => _3.project, 'optionalAccess', _4 => _4.template]) || (await detectTemplateKey(projectFolder));
7548
7540
 
7549
7541
  if (!template) {
7550
7542
  logger.info('Patch skipped: template not detected');
7551
7543
  return;
7552
7544
  }
7553
7545
 
7554
- const appliedPatches = [...(_optionalChain$d([config, 'access', _5 => _5.project, 'optionalAccess', _6 => _6.appliedPatches]) || [])];
7555
- const projectVersion = _optionalChain$d([config, 'access', _7 => _7.project, 'optionalAccess', _8 => _8.version]);
7546
+ const appliedPatches = [...(_optionalChain$2([config, 'access', _5 => _5.project, 'optionalAccess', _6 => _6.appliedPatches]) || [])];
7547
+ const projectVersion = _optionalChain$2([config, 'access', _7 => _7.project, 'optionalAccess', _8 => _8.version]);
7556
7548
  const flags = await loadFlagsWithFallback();
7557
7549
 
7558
7550
  const context = {
@@ -7597,7 +7589,7 @@ const executePatch = async (
7597
7589
 
7598
7590
  if (options.dryRun) {
7599
7591
  logger.info(`Detected template: ${template}`);
7600
- logger.info(`Current version: ${_nullishCoalesce$5(projectVersion, () => ( DEFAULT_LEGACY_VERSION))}`);
7592
+ logger.info(`Current version: ${_nullishCoalesce$3(projectVersion, () => ( DEFAULT_LEGACY_VERSION))}`);
7601
7593
  logger.info(`Applied patches: ${appliedPatches.join(', ') || '(none)'}`);
7602
7594
  logger.info('Matched patches:');
7603
7595
  matchedPatches.forEach(patch => {
@@ -7638,7 +7630,7 @@ const executePatch = async (
7638
7630
  }
7639
7631
  };
7640
7632
 
7641
- const registerCommand$5 = program => {
7633
+ const registerCommand$4 = program => {
7642
7634
  program
7643
7635
  .command('patch')
7644
7636
  .description('Apply template patches for existing projects')
@@ -7655,14 +7647,14 @@ const registerCommand$5 = program => {
7655
7647
  ) => {
7656
7648
  await executePatch({
7657
7649
  directory,
7658
- dryRun: _optionalChain$d([command, 'optionalAccess', _9 => _9.dryRun]),
7659
- showFlags: _optionalChain$d([command, 'optionalAccess', _10 => _10.showFlags]),
7650
+ dryRun: _optionalChain$2([command, 'optionalAccess', _9 => _9.dryRun]),
7651
+ showFlags: _optionalChain$2([command, 'optionalAccess', _10 => _10.showFlags]),
7660
7652
  });
7661
7653
  },
7662
7654
  );
7663
7655
  };
7664
7656
 
7665
- function _nullishCoalesce$4(lhs, rhsFn) { if (lhs != null) { return lhs; } else { return rhsFn(); } } function _optionalChain$c(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = fn(value); } else if (op === 'call' || op === 'optionalCall') { value = fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; }
7657
+ function _nullishCoalesce$2(lhs, rhsFn) { if (lhs != null) { return lhs; } else { return rhsFn(); } } function _optionalChain$1(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = fn(value); } else if (op === 'call' || op === 'optionalCall') { value = fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; }
7666
7658
  const d$1 = debug('coze-init-cli:run');
7667
7659
 
7668
7660
  /**
@@ -7793,12 +7785,12 @@ const executeRun = async (commandName, options = {}) => {
7793
7785
  }
7794
7786
 
7795
7787
  // 将输出同时写入控制台和日志文件
7796
- _optionalChain$c([childProcess, 'access', _ => _.stdout, 'optionalAccess', _2 => _2.on, 'call', _3 => _3('data', (data) => {
7788
+ _optionalChain$1([childProcess, 'access', _ => _.stdout, 'optionalAccess', _2 => _2.on, 'call', _3 => _3('data', (data) => {
7797
7789
  process.stdout.write(data);
7798
7790
  logStream.write(data);
7799
7791
  })]);
7800
7792
 
7801
- _optionalChain$c([childProcess, 'access', _4 => _4.stderr, 'optionalAccess', _5 => _5.on, 'call', _6 => _6('data', (data) => {
7793
+ _optionalChain$1([childProcess, 'access', _4 => _4.stderr, 'optionalAccess', _5 => _5.on, 'call', _6 => _6('data', (data) => {
7802
7794
  process.stderr.write(data);
7803
7795
  logStream.write(data);
7804
7796
  })]);
@@ -7811,7 +7803,7 @@ const executeRun = async (commandName, options = {}) => {
7811
7803
  const buildDuration = Date.now() - buildStartTime;
7812
7804
 
7813
7805
  if (code !== 0) {
7814
- const errorMessage = `Command exited with code ${_nullishCoalesce$4(code, () => ( 'unknown'))}${signal ? ` and signal ${signal}` : ''}`;
7806
+ const errorMessage = `Command exited with code ${_nullishCoalesce$2(code, () => ( 'unknown'))}${signal ? ` and signal ${signal}` : ''}`;
7815
7807
  logger.error(errorMessage);
7816
7808
  logger.error(`Check log file for details: ${logFilePath}`);
7817
7809
 
@@ -7823,12 +7815,12 @@ const executeRun = async (commandName, options = {}) => {
7823
7815
  categories: {
7824
7816
  fixDuration: String(fixDuration),
7825
7817
  buildDuration: String(buildDuration),
7826
- exitCode: String(_nullishCoalesce$4(code, () => ( 'unknown'))),
7818
+ exitCode: String(_nullishCoalesce$2(code, () => ( 'unknown'))),
7827
7819
  projectType,
7828
7820
  },
7829
7821
  errorContext: {
7830
- exitCode: String(_nullishCoalesce$4(code, () => ( 'unknown'))),
7831
- signal: _nullishCoalesce$4(signal, () => ( 'none')),
7822
+ exitCode: String(_nullishCoalesce$2(code, () => ( 'unknown'))),
7823
+ signal: _nullishCoalesce$2(signal, () => ( 'none')),
7832
7824
  logFile: logFilePath,
7833
7825
  projectType,
7834
7826
  },
@@ -7904,7 +7896,7 @@ const executeRun = async (commandName, options = {}) => {
7904
7896
  /**
7905
7897
  * 注册 dev/build/start 命令到 program
7906
7898
  */
7907
- const registerCommand$4 = program => {
7899
+ const registerCommand$3 = program => {
7908
7900
  // dev 命令
7909
7901
  program
7910
7902
  .command('dev')
@@ -8742,7 +8734,7 @@ const scanRoutesOnce = async (
8742
8734
  }
8743
8735
  };
8744
8736
 
8745
- function _optionalChain$b(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = fn(value); } else if (op === 'call' || op === 'optionalCall') { value = fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; }// Route manifest generation command
8737
+ function _optionalChain(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = fn(value); } else if (op === 'call' || op === 'optionalCall') { value = fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; }// Route manifest generation command
8746
8738
 
8747
8739
 
8748
8740
  const log = debug('coze:routes');
@@ -8830,7 +8822,7 @@ const executeRoutes = async (
8830
8822
  /**
8831
8823
  * Register routes command to program
8832
8824
  */
8833
- const registerCommand$3 = program => {
8825
+ const registerCommand$2 = program => {
8834
8826
  program
8835
8827
  .command('routes')
8836
8828
  .description('Generate routes manifest for the current project')
@@ -8843,11 +8835,11 @@ const registerCommand$3 = program => {
8843
8835
  'Output file path (defaults to ~/.coze/routes.json)',
8844
8836
  )
8845
8837
  .action(async (directory, options) => {
8846
- await executeRoutes({ directory, output: _optionalChain$b([options, 'optionalAccess', _ => _.output]) });
8838
+ await executeRoutes({ directory, output: _optionalChain([options, 'optionalAccess', _ => _.output]) });
8847
8839
  });
8848
8840
  };
8849
8841
 
8850
- function _nullishCoalesce$3(lhs, rhsFn) { if (lhs != null) { return lhs; } else { return rhsFn(); } }
8842
+ function _nullishCoalesce$1(lhs, rhsFn) { if (lhs != null) { return lhs; } else { return rhsFn(); } }
8851
8843
 
8852
8844
 
8853
8845
  const d = debug('coze-init-cli:check-bins');
@@ -8904,7 +8896,7 @@ const checkBins = async (cwd, fix) => {
8904
8896
 
8905
8897
  const bins =
8906
8898
  typeof depPkg.bin === 'string'
8907
- ? { [_nullishCoalesce$3(depName.split('/').pop(), () => ( depName))]: depPkg.bin }
8899
+ ? { [_nullishCoalesce$1(depName.split('/').pop(), () => ( depName))]: depPkg.bin }
8908
8900
  : depPkg.bin;
8909
8901
 
8910
8902
  d('%s declares bins: %o', depName, Object.keys(bins));
@@ -8954,7 +8946,7 @@ const checkBins = async (cwd, fix) => {
8954
8946
  d('pnpm i --force completed');
8955
8947
  };
8956
8948
 
8957
- const registerCommand$2 = program => {
8949
+ const registerCommand$1 = program => {
8958
8950
  program
8959
8951
  .command('check-bins')
8960
8952
  .description(
@@ -9848,7 +9840,7 @@ const execute = async (
9848
9840
  };
9849
9841
  };
9850
9842
 
9851
- function _nullishCoalesce$2(lhs, rhsFn) { if (lhs != null) { return lhs; } else { return rhsFn(); } }
9843
+ function _nullishCoalesce(lhs, rhsFn) { if (lhs != null) { return lhs; } else { return rhsFn(); } }
9852
9844
  /**
9853
9845
  * 运行 pnpm install
9854
9846
  */
@@ -9969,8 +9961,8 @@ const runDev = (projectPath) => {
9969
9961
  // 获取当前 CLI 的可执行文件路径
9970
9962
  // process.argv[0] 是 node,process.argv[1] 是 CLI 入口文件
9971
9963
  // 二者在 CLI 运行时必然存在,兜底空串仅为满足类型收窄,运行时不会命中
9972
- const nodeBin = _nullishCoalesce$2(process.argv[0], () => ( ''));
9973
- const cliPath = _nullishCoalesce$2(process.argv[1], () => ( ''));
9964
+ const nodeBin = _nullishCoalesce(process.argv[0], () => ( ''));
9965
+ const cliPath = _nullishCoalesce(process.argv[1], () => ( ''));
9974
9966
 
9975
9967
  try {
9976
9968
  // 使用通用的后台执行函数启动开发服务器
@@ -10040,7 +10032,7 @@ const executeTemplateEngineStep = async ctx => {
10040
10032
  templateName: ctx.templateName,
10041
10033
  outputPath: ctx.outputPath,
10042
10034
  command: ctx.command,
10043
- force: _nullishCoalesce$2(ctx.options.force, () => ( false)),
10035
+ force: _nullishCoalesce(ctx.options.force, () => ( false)),
10044
10036
  });
10045
10037
 
10046
10038
  // 保存结果到上下文
@@ -10299,7 +10291,7 @@ const executeInit = async (
10299
10291
  /**
10300
10292
  * 注册 init 命令到 program
10301
10293
  */
10302
- const registerCommand$1 = program => {
10294
+ const registerCommand = program => {
10303
10295
  program
10304
10296
  .command('init')
10305
10297
  .description('Initialize a new project from a template')
@@ -10317,3026 +10309,64 @@ const registerCommand$1 = program => {
10317
10309
  .allowUnknownOption() // 允许透传参数
10318
10310
  .action(async (directory, options, command) => {
10319
10311
  // 位置参数优先级高于 --output 选项
10320
- const outputPath = _nullishCoalesce$2(directory, () => ( options.output));
10312
+ const outputPath = _nullishCoalesce(directory, () => ( options.output));
10321
10313
  // Always use force mode - overwrite existing files without conflict check
10322
10314
  const force = true;
10323
10315
  await executeInit({ ...options, output: outputPath, force }, command);
10324
10316
  });
10325
10317
  };
10326
10318
 
10327
- const deployCommands = new WeakSet();
10328
-
10329
- const markDeployCommand = (command) => {
10330
- deployCommands.add(command);
10331
- return command;
10332
- };
10333
-
10334
- const findDeployCommand = (command) => {
10335
- let current = command;
10336
- while (current) {
10337
- if (deployCommands.has(current)) {
10338
- return current;
10339
- }
10340
- current = current.parent;
10341
- }
10342
- throw new Error('Unable to resolve the coze-dev deploy command context.');
10343
- };
10344
-
10345
- class CliError extends Error {
10346
- constructor(
10347
- message,
10348
- code = 'DEPLOY_CLI_ERROR',
10349
- details,
10350
- ) {
10351
- super(message);this.code = code;this.details = details; this.name = 'CliError';
10352
- }
10353
- }
10354
-
10355
- const toErrorPayload = (error) => {
10356
- if (error instanceof CliError) {
10357
- return { code: error.code, message: error.message, details: error.details };
10358
- }
10359
- return {
10360
- code: 'INTERNAL_ERROR',
10361
- message: error instanceof Error ? error.message : String(error),
10362
- };
10363
- };
10364
-
10365
- const APPLICATION_TYPES = new Set([
10366
- 'service',
10367
- 'pages',
10368
- 'mini_program',
10369
- ]);
10370
-
10371
- const PAGES_SERVICE_TYPE = 3;
10372
-
10373
- const inferApplicationTypeFromProjectType = (
10374
- projectType,
10375
- ) => {
10376
- switch (projectType) {
10377
- case 'miniapp':
10378
- case 'miniprogram':
10379
- return 'mini_program';
10380
- case undefined:
10381
- case '':
10382
- return undefined;
10383
- default:
10384
- return 'service';
10385
- }
10386
- };
10387
-
10388
- const parseApplicationType = (
10389
- value,
10390
- ) => {
10391
- if (!value) {
10392
- return undefined;
10393
- }
10394
- if (!APPLICATION_TYPES.has(value )) {
10395
- throw new CliError(
10396
- `Unsupported application type ${value}; expected service, pages, or mini_program.`,
10397
- 'INVALID_APPLICATION_TYPE',
10398
- );
10399
- }
10400
- return value ;
10401
- };
10402
-
10403
- const withRequestedApplicationType = (
10404
- config,
10405
- requestedType,
10406
- hasApplication = false,
10407
- ) => {
10408
- if (!requestedType) {
10409
- return config;
10410
- }
10411
- if (hasApplication && config.application_type !== requestedType) {
10412
- throw new CliError(
10413
- `Application type mismatch: the application is ${config.application_type}, but ${requestedType} was requested.`,
10414
- 'APPLICATION_TYPE_MISMATCH',
10415
- );
10416
- }
10417
- if (requestedType !== 'pages') {
10418
- if (config.application_type !== requestedType) {
10419
- throw new CliError(
10420
- `Application type mismatch: server resolved ${config.application_type}, but ${requestedType} was requested.`,
10421
- 'APPLICATION_TYPE_MISMATCH',
10422
- );
10423
- }
10424
- return config;
10425
- }
10426
- return {
10427
- ...config,
10428
- application_type: 'pages',
10429
- deploy_config: {
10430
- ...config.deploy_config,
10431
- service_type: PAGES_SERVICE_TYPE,
10432
- computer_id: undefined,
10433
- },
10434
- };
10435
- };
10436
-
10437
- function _optionalChain$a(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = fn(value); } else if (op === 'call' || op === 'optionalCall') { value = fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; }
10438
-
10439
- const DEFAULT_CONFIG = {
10440
- apiBaseUrl: 'https://code.coze.cn/',
10441
- openApiBaseUrl: 'https://api.coze.cn',
10442
- clientId: '95438868623436343239609434490626.app.coze',
10443
- };
10444
-
10445
- const getSharedConfigPath = () =>
10446
- node_path.join(node_os.homedir(), '.coze', 'cli', 'config.json');
10447
-
10448
- const getLegacyConfigPath = () => node_path.join(node_os.homedir(), '.coze', 'config.json');
10449
-
10450
- const isRecord$3 = (value) =>
10451
- typeof value === 'object' && value !== null && !Array.isArray(value);
10319
+ const commands = [
10320
+ registerCommand,
10321
+ registerCommand$3,
10322
+ registerCommand$6,
10323
+ registerCommand$4,
10324
+ registerCommand$5,
10325
+ registerCommand$2,
10326
+ registerCommand$1,
10327
+ ];
10452
10328
 
10453
- const readJson = async (path) => {
10454
- try {
10455
- const parsed = safeJsonParse(await promises.readFile(path, 'utf8'), undefined);
10456
- return isRecord$3(parsed) ? parsed : undefined;
10457
- } catch (error) {
10458
- if ((error ).code === 'ENOENT') {
10459
- return undefined;
10460
- }
10461
- throw new CliError(`Unable to read config ${path}: ${String(error)}`, 'CONFIG_INVALID');
10462
- }
10463
- };
10464
-
10465
- const configuredPath = (options) =>
10466
- _optionalChain$a([options, 'optionalAccess', _ => _.config]) || process.env.COZE_CONFIG_FILE;
10467
-
10468
- const loadConfig = async (options = {}) => {
10469
- const customPath = configuredPath(options);
10470
- const globalConfig = customPath
10471
- ? await readJson(node_path.resolve(customPath))
10472
- : (await readJson(getSharedConfigPath())) || (await readJson(getLegacyConfigPath()));
10473
- const environmentAccessToken = process.env.COZE_API_TOKEN;
10474
- const config = {
10475
- ...DEFAULT_CONFIG,
10476
- ...globalConfig,
10477
- ...(environmentAccessToken
10478
- ? {
10479
- accessToken: environmentAccessToken,
10480
- // COZE_API_TOKEN is a fixed runtime credential. Never combine it with
10481
- // refresh metadata left by an earlier OAuth login in config.json.
10482
- refreshToken: undefined,
10483
- tokenExpiresAt: undefined,
10484
- }
10485
- : {}),
10486
- ...(process.env.COZE_ORG_ID ? { organizationId: process.env.COZE_ORG_ID } : {}),
10487
- ...(process.env.COZE_SPACE_ID ? { spaceId: process.env.COZE_SPACE_ID } : {}),
10488
- ...(process.env.COZE_PROJECT_ID ? { projectId: process.env.COZE_PROJECT_ID } : {}),
10489
- ...(options.orgId ? { organizationId: options.orgId } : {}),
10490
- ...(options.spaceId ? { spaceId: options.spaceId } : {}),
10491
- ...(options.apiBaseUrl ? { apiBaseUrl: options.apiBaseUrl } : {}),
10492
- };
10493
- return config;
10494
- };
10329
+ const main = async () => {
10330
+ // 初始化 Slardar 监控
10331
+ initSlardar();
10495
10332
 
10496
- const saveSharedConfig = async (
10497
- patch,
10498
- options = {},
10499
- ) => {
10500
- const target = node_path.resolve(configuredPath(options) || getSharedConfigPath());
10501
- const existing = (await readJson(target)) || {};
10502
- const temp = node_path.join(node_path.dirname(target), `.config-${node_crypto.randomUUID()}.tmp`);
10503
- await promises.mkdir(node_path.dirname(target), { recursive: true });
10504
- try {
10505
- await promises.writeFile(temp, `${JSON.stringify({ ...existing, ...patch }, null, 2)}\n`, {
10506
- encoding: 'utf8',
10507
- mode: 0o600,
10333
+ // 监听未捕获的异常
10334
+ process.on('uncaughtException', async (error) => {
10335
+ reportError(error, {
10336
+ type: 'uncaughtException',
10337
+ context: 'global',
10508
10338
  });
10509
- await promises.rename(temp, target);
10510
- } finally {
10511
- await promises.rm(temp, { force: true });
10512
- }
10513
- };
10514
-
10515
- const FIVE_MINUTES = 5 * 60 * 1000;
10516
-
10517
-
10518
-
10519
-
10520
-
10521
-
10522
-
10523
- const resolveExpiry = (expiresIn) =>
10524
- expiresIn > 946684800 ? expiresIn * 1000 : Date.now() + expiresIn * 1000;
10525
-
10526
- const parseJson = async (response) => {
10527
- const text = await response.text();
10528
- if (!text) {
10529
- return {};
10530
- }
10531
- const parsed = safeJsonParse(text, {});
10532
- return typeof parsed === 'object' && parsed !== null
10533
- ? (parsed )
10534
- : {};
10535
- };
10536
-
10537
- const isRecord$2 = (value) =>
10538
- typeof value === 'object' && value !== null && !Array.isArray(value);
10539
-
10540
- const getCurrentUser = async (
10541
- config,
10542
- options,
10543
- ) => {
10544
- const token = await getAccessToken(config, options);
10545
- const response = await fetch(new URL('/v1/users/me', config.openApiBaseUrl), {
10546
- headers: { authorization: `Bearer ${token}` },
10339
+ await flushSlardar();
10340
+ process.exit(1);
10547
10341
  });
10548
- const payload = await parseJson(response);
10549
- if (!response.ok) {
10550
- throw new CliError(
10551
- typeof payload.msg === 'string'
10552
- ? payload.msg
10553
- : 'Unable to validate the current login. Run `coze-dev deploy auth login` again.',
10554
- response.status === 401 ? 'AUTH_REQUIRED' : 'AUTH_STATUS_FAILED',
10555
- { status: response.status },
10556
- );
10557
- }
10558
- return isRecord$2(payload.data) ? payload.data : payload;
10559
- };
10560
-
10561
- const clearAuthPatch = {
10562
- accessToken: undefined,
10563
- refreshToken: undefined,
10564
- tokenExpiresAt: undefined,
10565
- organizationId: undefined,
10566
- enterpriseId: undefined,
10567
- spaceId: undefined,
10568
- projectId: undefined,
10569
- };
10570
-
10571
- const getAccessToken = async (
10572
- config,
10573
- options,
10574
- ) => {
10575
- if (!config.accessToken) {
10576
- throw new CliError(
10577
- 'No shared login found. Run `coze-dev deploy auth login` first.',
10578
- 'AUTH_REQUIRED',
10579
- );
10580
- }
10581
- if (!config.refreshToken || !config.tokenExpiresAt) {
10582
- return config.accessToken;
10583
- }
10584
- if (Date.now() < config.tokenExpiresAt - FIVE_MINUTES) {
10585
- return config.accessToken;
10586
- }
10587
-
10588
- const response = await fetch(
10589
- new URL('/api/permission/oauth2/token', config.openApiBaseUrl),
10590
- {
10591
- method: 'POST',
10592
- headers: { 'content-type': 'application/json' },
10593
- body: JSON.stringify({
10594
- grant_type: 'refresh_token',
10595
- client_id: config.clientId,
10596
- refresh_token: config.refreshToken,
10597
- }),
10598
- },
10599
- );
10600
- const payload = await parseJson(response);
10601
- if (!response.ok || typeof payload.access_token !== 'string') {
10602
- throw new CliError(
10603
- typeof payload.error_description === 'string'
10604
- ? payload.error_description
10605
- : 'Shared login has expired. Run `coze-dev deploy auth login` again.',
10606
- 'AUTH_REFRESH_FAILED',
10607
- );
10608
- }
10609
- const token = payload ;
10610
- const patch = {
10611
- accessToken: token.access_token,
10612
- refreshToken: token.refresh_token || config.refreshToken,
10613
- tokenExpiresAt: resolveExpiry(token.expires_in),
10614
- };
10615
- Object.assign(config, patch);
10616
- await saveSharedConfig(patch, options);
10617
- return token.access_token;
10618
- };
10619
-
10620
- const saveOAuthToken = async (
10621
- config,
10622
- options,
10623
- token,
10624
- ) => {
10625
- const patch = {
10626
- accessToken: token.access_token,
10627
- refreshToken: token.refresh_token,
10628
- tokenExpiresAt: resolveExpiry(token.expires_in),
10629
- organizationId: undefined,
10630
- enterpriseId: undefined,
10631
- spaceId: undefined,
10632
- projectId: undefined,
10633
- };
10634
- Object.assign(config, patch);
10635
- await saveSharedConfig(patch, options);
10636
- };
10637
-
10638
- const logout = async (
10639
- config,
10640
- options,
10641
- ) => {
10642
- Object.assign(config, clearAuthPatch);
10643
- await saveSharedConfig(clearAuthPatch, options);
10644
- };
10645
-
10646
- const getAuthStatus = async (
10647
- config,
10648
- options,
10649
- ) => {
10650
- if (!config.accessToken) {
10651
- return { logged_in: false };
10652
- }
10653
- const user = await getCurrentUser(config, options);
10654
- return {
10655
- logged_in: true,
10656
- user,
10657
- token_expires_at: config.tokenExpiresAt
10658
- ? new Date(config.tokenExpiresAt).toISOString()
10659
- : 'Never (PAT)',
10660
- };
10661
- };
10662
10342
 
10663
- const DEFAULT_POLL_INTERVAL_MS = 5000;
10664
- const SLOW_DOWN_INCREMENT_MS = 5000;
10665
-
10666
- const isRecord$1 = (value) =>
10667
- typeof value === 'object' && value !== null && !Array.isArray(value);
10668
-
10669
- const readPayload = async (response) => {
10670
- const text = await response.text();
10671
- const payload = safeJsonParse(text, {});
10672
- return isRecord$1(payload) ? payload : {};
10673
- };
10674
-
10675
- const post = async (
10676
- baseUrl,
10677
- path,
10678
- body,
10679
- ) => {
10680
- const response = await fetch(new URL(path, baseUrl), {
10681
- method: 'POST',
10682
- headers: { 'content-type': 'application/json' },
10683
- body: JSON.stringify(body),
10343
+ // 监听未处理的 Promise rejection
10344
+ process.on('unhandledRejection', async (reason) => {
10345
+ const error = reason instanceof Error ? reason : new Error(String(reason));
10346
+ reportError(error, {
10347
+ type: 'unhandledRejection',
10348
+ context: 'global',
10349
+ });
10350
+ await flushSlardar();
10351
+ process.exit(1);
10684
10352
  });
10685
- return { payload: await readPayload(response), response };
10686
- };
10687
-
10688
- const requireString = (
10689
- payload,
10690
- key,
10691
- ) => {
10692
- const value = payload[key];
10693
- if (typeof value !== 'string' || !value) {
10694
- throw new CliError(`OAuth response returned no ${key}.`, 'INVALID_AUTH_RESPONSE');
10695
- }
10696
- return value;
10697
- };
10698
-
10699
- const requireNumber = (
10700
- payload,
10701
- key,
10702
- ) => {
10703
- const value = Number(payload[key]);
10704
- if (!Number.isFinite(value) || value <= 0) {
10705
- throw new CliError(`OAuth response returned no ${key}.`, 'INVALID_AUTH_RESPONSE');
10706
- }
10707
- return value;
10708
- };
10709
-
10710
- const requestDeviceCode = async (config) => {
10711
- const { payload, response } = await post(
10712
- config.openApiBaseUrl,
10713
- '/api/permission/oauth2/device/code',
10714
- { client_id: config.clientId },
10715
- );
10716
- if (!response.ok) {
10717
- throw new CliError(
10718
- typeof payload.error_description === 'string'
10719
- ? payload.error_description
10720
- : 'Unable to start OAuth login.',
10721
- 'AUTH_LOGIN_FAILED',
10722
- { status: response.status },
10723
- );
10724
- }
10725
- return {
10726
- device_code: requireString(payload, 'device_code'),
10727
- user_code: requireString(payload, 'user_code'),
10728
- verification_uri: requireString(payload, 'verification_uri'),
10729
- expires_in: requireNumber(payload, 'expires_in'),
10730
- interval:
10731
- typeof payload.interval === 'number' && payload.interval > 0
10732
- ? payload.interval
10733
- : undefined,
10734
- };
10735
- };
10736
-
10737
- const buildVerificationUrl = (deviceCode) => {
10738
- const url = new URL(deviceCode.verification_uri);
10739
- url.searchParams.set('user_code', deviceCode.user_code);
10740
- return url.toString();
10741
- };
10742
-
10743
- const openBrowser = (url) => {
10744
- const command =
10745
- process.platform === 'darwin'
10746
- ? 'open'
10747
- : process.platform === 'win32'
10748
- ? 'cmd'
10749
- : 'xdg-open';
10750
- const args = process.platform === 'win32' ? ['/c', 'start', '""', url] : [url];
10751
- try {
10752
- const child = node_child_process.spawn(command, args, { detached: true, stdio: 'ignore' });
10753
- child.on('error', () => undefined);
10754
- child.unref();
10755
- } catch (error) {
10756
- }
10757
- };
10758
-
10759
- const sleep = async (milliseconds) =>
10760
- new Promise(resolve => setTimeout(resolve, milliseconds));
10761
-
10762
- const pollToken = async (
10763
- config,
10764
- deviceCode,
10765
- ) => {
10766
- const expiresAt = Date.now() + deviceCode.expires_in * 1000;
10767
- let interval = (deviceCode.interval || DEFAULT_POLL_INTERVAL_MS / 1000) * 1000;
10768
- while (Date.now() < expiresAt) {
10769
- const { payload, response } = await post(
10770
- config.openApiBaseUrl,
10771
- '/api/permission/oauth2/token',
10772
- {
10773
- grant_type: 'urn:ietf:params:oauth:grant-type:device_code',
10774
- client_id: config.clientId,
10775
- device_code: deviceCode.device_code,
10776
- },
10777
- );
10778
- if (response.ok) {
10779
- return {
10780
- access_token: requireString(payload, 'access_token'),
10781
- refresh_token: requireString(payload, 'refresh_token'),
10782
- expires_in: requireNumber(payload, 'expires_in'),
10783
- };
10784
- }
10785
- if (payload.error === 'authorization_pending') {
10786
- await sleep(interval);
10787
- continue;
10788
- }
10789
- if (payload.error === 'slow_down') {
10790
- interval += SLOW_DOWN_INCREMENT_MS;
10791
- await sleep(interval);
10792
- continue;
10793
- }
10794
- throw new CliError(
10795
- typeof payload.error_description === 'string'
10796
- ? payload.error_description
10797
- : 'OAuth authorization failed.',
10798
- 'AUTH_LOGIN_FAILED',
10799
- { oauth_error: payload.error, status: response.status },
10800
- );
10801
- }
10802
- throw new CliError('OAuth authorization expired. Please try again.', 'AUTH_LOGIN_EXPIRED');
10803
- };
10804
-
10805
- const loginWithOAuth = async (
10806
- config,
10807
- options,
10808
- callbacks,
10809
- ) => {
10810
- const deviceCode = await requestDeviceCode(config);
10811
- const verificationUrl = buildVerificationUrl(deviceCode);
10812
- callbacks.onVerification(verificationUrl);
10813
- openBrowser(verificationUrl);
10814
- await saveOAuthToken(config, options, await pollToken(config, deviceCode));
10815
- };
10816
-
10817
- function _optionalChain$9(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = fn(value); } else if (op === 'call' || op === 'optionalCall') { value = fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; }
10818
-
10819
-
10820
-
10821
-
10822
-
10823
-
10824
-
10825
-
10826
10353
 
10354
+ const program = new commander.Command();
10827
10355
 
10356
+ program
10357
+ .name('coze-dev')
10358
+ .description(
10359
+ 'Coze Coding CLI - Project template engine for frontend stacks',
10360
+ )
10361
+ .version(packageJson.version);
10828
10362
 
10363
+ commands.forEach(initCmd => initCmd(program));
10829
10364
 
10830
-
10831
-
10832
-
10833
-
10834
-
10835
-
10836
- const API_PREFIX = '/api/coding/deployment/v2';
10837
- const CREATE_PROJECT_PATH = '/api/ideserver_api/project/create_vibe_project';
10838
- const LIST_SPACES_PATH = '/api/playground_api/space/list';
10839
- const ENCRYPT_PROJECT_SECRET_PATH =
10840
- '/api/permission_api/project_secret/encrypt_project_secret';
10841
- const MAX_MESSAGE_LENGTH = 512;
10842
-
10843
- const isRecord = (value) =>
10844
- typeof value === 'object' && value !== null && !Array.isArray(value);
10845
-
10846
-
10847
-
10848
-
10849
-
10850
-
10851
-
10852
- const parseResponse = async (response) => {
10853
- const text = await response.text();
10854
- if (!text) {
10855
- return { payload: {}, text, validJson: true };
10856
- }
10857
- const invalid = Symbol('invalid-json');
10858
- const parsed = safeJsonParse(text, invalid);
10859
- return parsed === invalid
10860
- ? { payload: undefined, text, validJson: false }
10861
- : { payload: parsed, text, validJson: true };
10862
- };
10863
-
10864
-
10865
-
10866
-
10867
-
10868
-
10869
-
10870
-
10871
-
10872
- const responseExcerpt = (text) => {
10873
- const compact = text.replace(/\s+/gu, ' ').trim();
10874
- return compact ? compact.slice(0, MAX_MESSAGE_LENGTH) : undefined;
10875
- };
10876
-
10877
- const unwrap = (
10878
- payload,
10879
- expectedKey,
10880
- responseMetadata,
10881
- ) => {
10882
- const root = isRecord(payload) ? payload : undefined;
10883
- const first = isRecord(_optionalChain$9([root, 'optionalAccess', _ => _.data])) ? root.data : undefined;
10884
- const second = isRecord(_optionalChain$9([first, 'optionalAccess', _2 => _2.data])) ? first.data : undefined;
10885
- const envelope = [root, first].find(candidate => candidate && 'code' in candidate);
10886
- if (_optionalChain$9([envelope, 'optionalAccess', _3 => _3.code]) !== undefined && Number(envelope.code) !== 0) {
10887
- throw new CliError(
10888
- typeof envelope.msg === 'string'
10889
- ? envelope.msg.slice(0, MAX_MESSAGE_LENGTH)
10890
- : 'The deployment request was rejected.',
10891
- 'API_REJECTED',
10892
- { business_code: envelope.code, ...responseMetadata },
10893
- );
10894
- }
10895
- if (!expectedKey) {
10896
- return (second || first || root || {}) ;
10897
- }
10898
- const matched = [second, first, root].find(
10899
- candidate => candidate && expectedKey in candidate,
10900
- );
10901
- if (!matched) {
10902
- throw new CliError(
10903
- `Deployment API returned no ${expectedKey}.`,
10904
- 'INVALID_RESPONSE',
10905
- );
10906
- }
10907
- return matched ;
10908
- };
10909
-
10910
- class DeployApiClient {
10911
- constructor(
10912
- config,
10913
- globalOptions,
10914
- ) {this.config = config;this.globalOptions = globalOptions;}
10915
-
10916
- debug(message) {
10917
- if (this.globalOptions.debug) {
10918
- process.stderr.write(`[debug] [api] ${message}\n`);
10919
- }
10920
- }
10921
-
10922
- async post(
10923
- path,
10924
- body,
10925
- expectedKey,
10926
- useApiPrefix = true,
10927
- ) {
10928
- const token = await getAccessToken(this.config, this.globalOptions);
10929
- const headers = {
10930
- authorization: `Bearer ${token}`,
10931
- 'content-type': 'application/json',
10932
- 'agw-js-conv': 'str',
10933
- 'x-request-from-coze-cli': '1',
10934
- };
10935
- if (this.config.organizationId) {
10936
- headers['x-coze-account'] = this.config.organizationId;
10937
- }
10938
- const lane = _optionalChain$9([this, 'access', _4 => _4.globalOptions, 'access', _5 => _5.lane, 'optionalAccess', _6 => _6.trim, 'call', _7 => _7()]) || _optionalChain$9([this, 'access', _8 => _8.config, 'access', _9 => _9.xTTEnv, 'optionalAccess', _10 => _10.trim, 'call', _11 => _11()]);
10939
- if (lane) {
10940
- headers['x-use-ppe'] = '1';
10941
- headers['x-tt-env'] = lane;
10942
- }
10943
- const requestUrl = new URL(
10944
- `${useApiPrefix ? API_PREFIX : ''}${path}`,
10945
- this.config.apiBaseUrl,
10946
- );
10947
- this.debug(
10948
- `POST ${requestUrl.toString()}${lane ? ` lane=${lane}` : ''}`,
10949
- );
10950
- const response = await fetch(
10951
- requestUrl,
10952
- { method: 'POST', headers, body: JSON.stringify(body) },
10953
- );
10954
- const responseMetadata = {
10955
- status: response.status,
10956
- status_text: response.statusText,
10957
- log_id: response.headers.get('x-tt-logid') || undefined,
10958
- request_path: requestUrl.pathname,
10959
- content_type: response.headers.get('content-type') || undefined,
10960
- };
10961
- this.debug(
10962
- `${response.status} ${response.statusText} ${requestUrl.pathname}` +
10963
- `${responseMetadata.log_id ? ` log_id=${responseMetadata.log_id}` : ' log_id=unavailable'}`,
10964
- );
10965
- const { payload, text, validJson } = await parseResponse(response);
10966
- if (!response.ok) {
10967
- const root = isRecord(payload) ? payload : undefined;
10968
- throw new CliError(
10969
- typeof _optionalChain$9([root, 'optionalAccess', _12 => _12.msg]) === 'string'
10970
- ? root.msg.slice(0, MAX_MESSAGE_LENGTH)
10971
- : `Deployment API failed: ${response.status} ${response.statusText}` +
10972
- `${validJson ? '' : '; response was not JSON'}`,
10973
- response.status === 401 ? 'AUTH_REQUIRED' : 'HTTP_ERROR',
10974
- {
10975
- ...responseMetadata,
10976
- response_excerpt: responseExcerpt(text),
10977
- },
10978
- );
10979
- }
10980
- if (!validJson) {
10981
- throw new CliError(
10982
- `Deployment API returned invalid JSON (${response.status}).`,
10983
- 'INVALID_RESPONSE',
10984
- {
10985
- ...responseMetadata,
10986
- response_excerpt: responseExcerpt(text),
10987
- },
10988
- );
10989
- }
10990
- return unwrap(payload, expectedKey, responseMetadata);
10991
- }
10992
-
10993
- createDeploymentProject(body) {
10994
- return this.post(
10995
- CREATE_PROJECT_PATH,
10996
- body,
10997
- 'project_id',
10998
- false,
10999
- );
11000
- }
11001
-
11002
- listSpaces(body
11003
-
11004
-
11005
-
11006
-
11007
- ) {
11008
- return this.post(
11009
- LIST_SPACES_PATH,
11010
- body,
11011
- 'bot_space_list',
11012
- false,
11013
- );
11014
- }
11015
-
11016
- encryptProjectSecret(projectId, secrets) {
11017
- return this.post(
11018
- ENCRYPT_PROJECT_SECRET_PATH,
11019
- {
11020
- project_id: projectId,
11021
- encrypt_secrets: {
11022
- secrets,
11023
- cred_providers: [],
11024
- },
11025
- },
11026
- 'sealed_secrets',
11027
- false,
11028
- );
11029
- }
11030
-
11031
- // 列当前登录用户名下的 Application,跨 Project。服务端从登录态取 user_id,
11032
- // 请求体里只有分页参数(deploy_app/list 已去掉 project_id / user_id 两个寻址入参)。
11033
- listApplications(body) {
11034
- return this.post(
11035
- '/deploy_app/list', body, 'items',
11036
- );
11037
- }
11038
-
11039
- getApplication(appId) {
11040
- return this.post('/deploy_app/get', { app_id: appId }, 'app_id');
11041
- }
11042
-
11043
- updateApplication(body) {
11044
- return this.post('/deploy_app/update', body, 'app_id');
11045
- }
11046
-
11047
- // 删除 Application:服务端只接受 **Stopped** 状态,其余状态会带上当前状态报错(先 stop 再 delete)。
11048
- // 已删除的再删一次是幂等成功。
11049
- deleteApplication(appId) {
11050
- return this.post('/deploy_app/delete', { app_id: appId });
11051
- }
11052
-
11053
- getDeployConfig(body
11054
-
11055
-
11056
-
11057
-
11058
-
11059
- ) {
11060
- return this.post('/deploy_config/get', body, 'deploy_config');
11061
- }
11062
-
11063
- createDeployHistory(body) {
11064
- return this.post('/deploy_history/create', body, 'app_id');
11065
- }
11066
-
11067
- preDeployUpload(body
11068
-
11069
-
11070
- ) {
11071
- return this.post('/deploy_history/pre_upload', body, 'upload_url');
11072
- }
11073
-
11074
- getDeployHistory(body) {
11075
- return this.post('/deploy_history/get', body, 'deploy_history_id');
11076
- }
11077
-
11078
- listDeployHistory(body) {
11079
- return this.post
11080
-
11081
-
11082
-
11083
- ('/deploy_history/list', body, 'deploy_history_list');
11084
- }
11085
-
11086
- getOnlineDeployHistory(appId) {
11087
- return this.post(
11088
- '/deploy_history/get_online', { app_id: appId }, 'deploy_history_list',
11089
- );
11090
- }
11091
-
11092
- getOnlineEnvironment(appId) {
11093
- return this.post(
11094
- '/environment/get_online', { app_id: appId }, 'app_id',
11095
- );
11096
- }
11097
-
11098
- checkRollbackDatabase(body) {
11099
- return this.post(
11100
- '/deploy_history/check_rollback_database', body, 'is_rollback_possible',
11101
- );
11102
- }
11103
-
11104
- cancelDeployHistory(body) {
11105
- return this.post('/deploy_history/cancel', body);
11106
- }
11107
-
11108
- rollbackDeployHistory(body
11109
-
11110
-
11111
-
11112
- ) {
11113
- return this.post(
11114
- '/deploy_history/rollback', body, 'new_deploy_history_id',
11115
- );
11116
- }
11117
-
11118
- stopApplication(appId) {
11119
- return this.post('/application/stop', { app_id: appId });
11120
- }
11121
-
11122
- resumeApplication(appId) {
11123
- return this.post('/application/resume', { app_id: appId });
11124
- }
11125
-
11126
- // 暂停是可逆的:只把线上 Unit 从 Ready 改成 Paused,函数留着,可被 resume 推回 Ready。
11127
- // stop 会连函数一起删、落到 Stopped,只能靠重新部署恢复 —— resume 配对的是 pause,不是 stop。
11128
- pauseApplication(appId) {
11129
- return this.post('/application/pause', { app_id: appId });
11130
- }
11131
-
11132
- // PV / UV。入参是 app_id,但服务端反查 project_id 后按 **Project** 聚合 —— 埋点链路只有
11133
- // project 维度,同一 Project 下多个 Application 拿到的是同一份数据。
11134
- getUserAnalyticsMetrics(body) {
11135
- return this.post(
11136
- '/metrics/user_analytics/get', body, 'charts',
11137
- );
11138
- }
11139
-
11140
- getBuildLog(body) {
11141
- return this.post('/deploy_history/log', body, 'log');
11142
- }
11143
-
11144
- searchRuntimeLog(body) {
11145
- return this.post(
11146
- '/runtime_log/search', body, 'logs',
11147
- );
11148
- }
11149
-
11150
- getRuntimeLogCount(appId) {
11151
- return this.post(
11152
- '/runtime_log/count', { app_id: appId }, 'limit',
11153
- );
11154
- }
11155
-
11156
- getDeployCount(appId) {
11157
- return this.post(
11158
- '/deploy_history/get_count', { app_id: appId }, 'success_count',
11159
- );
11160
- }
11161
-
11162
- getApplicationMetrics(body) {
11163
- return this.post(
11164
- '/metrics/get', body, 'charts',
11165
- );
11166
- }
11167
-
11168
- getHostedUsageMonthly(body) {
11169
- return this.post(
11170
- '/hosted_usage/monthly', body, 'summary',
11171
- );
11172
- }
11173
-
11174
- listDomains(appId, unitType) {
11175
- return this.post(
11176
- '/domain/list', {
11177
- app_id: appId,
11178
- ...(unitType === undefined ? {} : { unit_type: unitType }),
11179
- }, 'items',
11180
- );
11181
- }
11182
-
11183
- createDomain(body) {
11184
- return this.post('/domain/create', body, 'domain');
11185
- }
11186
-
11187
- // 改的是系统分配的 <prefix>.coze.site 里的 prefix,不是 createDomain 加进来的自定义域名 ——
11188
- // 那类域名服务端只提供 create/delete,域名串本身不可改。
11189
- updateDefaultDomainPrefix(body) {
11190
- return this.post
11191
-
11192
-
11193
-
11194
-
11195
- ('/domain/update_default_prefix', body, 'new_domain_host_canonical');
11196
- }
11197
-
11198
- getMiniProgramAuthStatus(body) {
11199
- return this.post
11200
-
11201
-
11202
-
11203
-
11204
- ('/api/coding/deployment/auth/status', body, 'is_authorized', false);
11205
- }
11206
-
11207
- bindMiniProgramAuth(body
11208
-
11209
-
11210
-
11211
-
11212
-
11213
- ) {
11214
- return this.post
11215
-
11216
-
11217
-
11218
-
11219
-
11220
-
11221
- ('/api/coding/deployment/auth/bind', body, 'bind_status', false);
11222
- }
11223
-
11224
- submitMiniProgramAuthCode(body
11225
-
11226
-
11227
-
11228
-
11229
-
11230
- ) {
11231
- return this.post(
11232
- '/api/coding/deployment/auth/submit_code', body, undefined, false,
11233
- );
11234
- }
11235
-
11236
- unbindMiniProgramAuth(body) {
11237
- return this.post(
11238
- '/api/coding/deployment/auth/unbind', body, undefined, false,
11239
- );
11240
- }
11241
- }
11242
-
11243
- const textValue = (value) => {
11244
- if (typeof value === 'string') {
11245
- return value;
11246
- }
11247
- return JSON.stringify(value, null, 2);
11248
- };
11249
-
11250
- class Output {
11251
- constructor(
11252
- format,
11253
- debugEnabled = false,
11254
- ) {this.format = format;this.debugEnabled = debugEnabled;}
11255
-
11256
- print(value) {
11257
- process.stdout.write(
11258
- this.format === 'json'
11259
- ? `${JSON.stringify(value, null, 2)}\n`
11260
- : `${textValue(value)}\n`,
11261
- );
11262
- }
11263
-
11264
- info(message) {
11265
- if (this.format === 'text') {
11266
- process.stderr.write(`${message}\n`);
11267
- }
11268
- }
11269
-
11270
- notice(message) {
11271
- process.stderr.write(`${message}\n`);
11272
- }
11273
-
11274
- warn(message) {
11275
- process.stderr.write(`Warning: ${message}\n`);
11276
- }
11277
-
11278
- debug(message) {
11279
- if (this.debugEnabled) {
11280
- process.stderr.write(`[debug] ${message}\n`);
11281
- }
11282
- }
11283
- }
11284
-
11285
- const runtimes = new WeakMap();
11286
-
11287
- const getRuntime = async (command) => {
11288
- const deploy = findDeployCommand(command);
11289
- let runtime = runtimes.get(deploy);
11290
- if (!runtime) {
11291
- runtime = (async () => {
11292
- const options = deploy.opts();
11293
- const config = await loadConfig(options);
11294
- return {
11295
- client: new DeployApiClient(config, options),
11296
- config,
11297
- cwd: process.cwd(),
11298
- globalOptions: options,
11299
- output: new Output(options.format || 'json', options.debug),
11300
- };
11301
- })();
11302
- runtimes.set(deploy, runtime);
11303
- }
11304
- return runtime;
11305
- };
11306
-
11307
- const PRIVACY_POLICY_URL = 'https://docs.coze.cn/guides/privacy';
11308
- const TERMS_OF_SERVICE_URL = 'https://docs.coze.cn/guides/terms-of-service';
11309
-
11310
- const registerAuth = (program) => {
11311
- const auth = program.command('auth').description('Manage deployment CLI authentication');
11312
-
11313
- auth
11314
- .command('login')
11315
- .description('Login with Coze OAuth and save shared credentials')
11316
- .action(async (_options, command) => {
11317
- const runtime = await getRuntime(command);
11318
- await loginWithOAuth(runtime.config, runtime.globalOptions, {
11319
- onVerification: url => {
11320
- runtime.output.notice(
11321
- [
11322
- 'Open this URL to authorize coze-dev deploy:',
11323
- url,
11324
- `Privacy Policy: ${PRIVACY_POLICY_URL}`,
11325
- `Terms of Service: ${TERMS_OF_SERVICE_URL}`,
11326
- ].join('\n'),
11327
- );
11328
- },
11329
- });
11330
- runtime.output.print({ success: true, logged_in: true, method: 'OAuth' });
11331
- });
11332
-
11333
- auth
11334
- .command('status')
11335
- .description('Check and refresh the current shared login')
11336
- .action(async (_options, command) => {
11337
- const runtime = await getRuntime(command);
11338
- runtime.output.print(await getAuthStatus(runtime.config, runtime.globalOptions));
11339
- });
11340
-
11341
- auth
11342
- .command('logout')
11343
- .description('Clear shared credentials and account context')
11344
- .action(async (_options, command) => {
11345
- const runtime = await getRuntime(command);
11346
- await logout(runtime.config, runtime.globalOptions);
11347
- runtime.output.print({ success: true, logged_out: true });
11348
- });
11349
- };
11350
-
11351
- const execFileAsync = node_util.promisify(node_child_process.execFile);
11352
-
11353
- const registerContext = (program) => {
11354
- const context = program.command('context').description('Show or update deployment context');
11355
- context.command('show').action(async (_options, command) => {
11356
- const runtime = await getRuntime(command);
11357
- runtime.output.print({
11358
- organization_id: runtime.config.organizationId,
11359
- space_id: runtime.config.spaceId,
11360
- project_id: runtime.config.projectId,
11361
- lane: runtime.globalOptions.lane || runtime.config.xTTEnv,
11362
- config_path: runtime.globalOptions.config || getSharedConfigPath(),
11363
- });
11364
- });
11365
- context
11366
- .command('use')
11367
- .option('--space-id <spaceId>', 'Default Space ID')
11368
- .option('--project-id <projectId>', 'Default Project ID')
11369
- .action(async (options, command) => {
11370
- const runtime = await getRuntime(command);
11371
- await saveSharedConfig(
11372
- {
11373
- ...(options.spaceId ? { spaceId: options.spaceId } : {}),
11374
- ...(options.projectId ? { projectId: options.projectId } : {}),
11375
- },
11376
- runtime.globalOptions,
11377
- );
11378
- runtime.output.print({
11379
- space_id: options.spaceId || runtime.config.spaceId,
11380
- project_id: options.projectId || runtime.config.projectId,
11381
- });
11382
- });
11383
- };
11384
-
11385
- const registerDoctor = (program) => {
11386
- program
11387
- .command('doctor')
11388
- .description('Check deployment CLI prerequisites and shared login')
11389
- .action(async (_options, command) => {
11390
- const runtime = await getRuntime(command);
11391
- let gitAvailable = true;
11392
- try {
11393
- await execFileAsync('git', ['--version']);
11394
- } catch (e) {
11395
- gitAvailable = false;
11396
- }
11397
- runtime.output.print({
11398
- ok: gitAvailable && Boolean(runtime.config.accessToken),
11399
- git: gitAvailable ? 'ok' : 'missing',
11400
- login: runtime.config.accessToken ? 'reused' : 'missing',
11401
- login_config: runtime.globalOptions.config || getSharedConfigPath(),
11402
- project_id: runtime.config.projectId || 'not configured',
11403
- });
11404
- });
11405
- };
11406
-
11407
- function _optionalChain$8(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = fn(value); } else if (op === 'call' || op === 'optionalCall') { value = fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; }
11408
-
11409
-
11410
-
11411
-
11412
-
11413
-
11414
-
11415
-
11416
-
11417
-
11418
-
11419
-
11420
-
11421
-
11422
-
11423
-
11424
-
11425
-
11426
-
11427
-
11428
-
11429
-
11430
-
11431
-
11432
-
11433
-
11434
-
11435
-
11436
-
11437
- const getDeployParentOptions = (command) =>
11438
- _optionalChain$8([command, 'access', _ => _.parent, 'optionalAccess', _2 => _2.opts, 'call', _3 => _3()]) || {};
11439
-
11440
- const getDeployAppIdOption = (
11441
- options,
11442
- command,
11443
- ) => options.appId || getDeployParentOptions(command).appId;
11444
-
11445
- const getCreateDeployConfig = (config) => ({
11446
- deploy_config: {
11447
- cpu: config.deploy_config.cpu,
11448
- memory_mb: config.deploy_config.memory_mb,
11449
- max_instance: config.deploy_config.max_instance,
11450
- max_concurrency: config.deploy_config.max_concurrency,
11451
- },
11452
- service_type: config.deploy_config.service_type,
11453
- ...(config.deploy_config.computer_id
11454
- ? { computer_id: config.deploy_config.computer_id }
11455
- : {}),
11456
- });
11457
-
11458
- const DEPLOY_STATUS = {
11459
- pending: 1,
11460
- running: 2,
11461
- succeeded: 3,
11462
- failed: 4,
11463
- canceled: 5,
11464
- interrupted: 6,
11465
- preDeploy: 7,
11466
- } ;
11467
-
11468
- const STATUS_NAMES = {
11469
- [DEPLOY_STATUS.pending]: 'Pending',
11470
- [DEPLOY_STATUS.running]: 'Running',
11471
- [DEPLOY_STATUS.succeeded]: 'Succeeded',
11472
- [DEPLOY_STATUS.failed]: 'Failed',
11473
- [DEPLOY_STATUS.canceled]: 'Canceled',
11474
- [DEPLOY_STATUS.interrupted]: 'Interrupted',
11475
- [DEPLOY_STATUS.preDeploy]: 'WaitingForUpload',
11476
- };
11477
-
11478
- const TERMINAL_STATUSES = new Set([
11479
- DEPLOY_STATUS.succeeded,
11480
- DEPLOY_STATUS.failed,
11481
- DEPLOY_STATUS.canceled,
11482
- DEPLOY_STATUS.interrupted,
11483
- ]);
11484
-
11485
- const getDeployStatusText = (status) =>
11486
- status ? STATUS_NAMES[status] || 'Unknown' : 'Unknown';
11487
-
11488
- function _optionalChain$7(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = fn(value); } else if (op === 'call' || op === 'optionalCall') { value = fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; }
11489
-
11490
- const formatDeployDetails = (history) =>
11491
- (_optionalChain$7([history, 'optionalAccess', _ => _.deploy_detail]) || []).map(detail => ({
11492
- target: detail.target,
11493
- status: getDeployStatusText(detail.status),
11494
- deploy_log_key: detail.deploy_log_key,
11495
- deploy_log_url: detail.deploy_log_url,
11496
- }));
11497
-
11498
- const getDeployLogKeys = (history) =>
11499
- [...new Set(
11500
- (history.deploy_detail || [])
11501
- .map(detail => _optionalChain$7([detail, 'access', _2 => _2.deploy_log_key, 'optionalAccess', _3 => _3.trim, 'call', _4 => _4()]))
11502
- .filter((key) => Boolean(key)),
11503
- )];
11504
-
11505
- const normalizePositiveId = (value) => {
11506
- const normalized = value === undefined ? '' : String(value).trim();
11507
- return /^[1-9]\d*$/.test(normalized) ? normalized : undefined;
11508
- };
11509
-
11510
- const resolveDeployHistoryId = (
11511
- deployHistoryId,
11512
- previousDeployHistoryId,
11513
- ) =>
11514
- normalizePositiveId(deployHistoryId) || normalizePositiveId(previousDeployHistoryId);
11515
-
11516
- function _optionalChain$6(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = fn(value); } else if (op === 'call' || op === 'optionalCall') { value = fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; }
11517
-
11518
- const SOURCE_SNAPSHOT_BYTES = 20;
11519
-
11520
- const isId = (value) =>
11521
- typeof value === 'string' && /^\d+$/u.test(value);
11522
-
11523
-
11524
- const resolveAppId = async (cwd, appId) => {
11525
- const explicit = _optionalChain$6([appId, 'optionalAccess', _ => _.trim, 'call', _2 => _2()]);
11526
- if (explicit) {
11527
- return explicit;
11528
- }
11529
- try {
11530
- return (await readProjectMetadata(node_path.resolve(cwd))).appId;
11531
- } catch (error) {
11532
- if ((error ).code === 'COZE_FILE_NOT_FOUND') {
11533
- return undefined;
11534
- }
11535
- throw error;
11536
- }
11537
- };
11538
-
11539
- const requireAppId = async (cwd, appId) => {
11540
- const resolved = await resolveAppId(cwd, appId);
11541
- if (!resolved) {
11542
- throw new CliError(
11543
- 'Application ID is required. Pass --app-id or use a directory whose .coze [project] contains app_id.',
11544
- 'APP_ID_REQUIRED',
11545
- );
11546
- }
11547
- return resolved;
11548
- };
11549
-
11550
- const resolveSourceSnapshot = (sourceRootInput) => {
11551
- const sourceRoot = node_path.resolve(sourceRootInput);
11552
- const commitHash = node_crypto.randomBytes(SOURCE_SNAPSHOT_BYTES).toString('hex');
11553
- return { commitHash, sourceRoot };
11554
- };
11555
-
11556
- const readProjectMetadata = async (
11557
- sourceRoot,
11558
- ) => {
11559
- let cozeFileContent = '';
11560
- try {
11561
- cozeFileContent = await promises.readFile(node_path.join(sourceRoot, '.coze'), 'utf8');
11562
- } catch (error) {
11563
- if ((error ).code === 'ENOENT') {
11564
- throw new CliError(
11565
- `No .coze file found in ${sourceRoot}.`,
11566
- 'COZE_FILE_NOT_FOUND',
11567
- );
11568
- }
11569
- throw error;
11570
- }
11571
- const projectSection = _optionalChain$6([cozeFileContent, 'access', _3 => _3.match, 'call', _4 => _4(
11572
- /^\s*\[project\]\s*(?:#.*)?$([\s\S]*?)(?=^\s*\[[^\]]+\]\s*(?:#.*)?$|(?![\s\S]))/mu,
11573
- ), 'optionalAccess', _5 => _5[1]]);
11574
- const readProjectString = (key) =>
11575
- _optionalChain$6([projectSection
11576
- , 'optionalAccess', _6 => _6.match, 'call', _7 => _7(new RegExp(`^\\s*${key}\\s*=\\s*["']([^"']+)["']`, 'mu')), 'optionalAccess', _8 => _8[1]
11577
- , 'optionalAccess', _9 => _9.trim, 'call', _10 => _10()]);
11578
- const name = readProjectString('name');
11579
- const projectType = readProjectString('project_type');
11580
- const projectId = readProjectString('project_id');
11581
- const appId = readProjectString('app_id');
11582
- const hasUnquotedId = (key) =>
11583
- Boolean(_optionalChain$6([projectSection, 'optionalAccess', _11 => _11.match, 'call', _12 => _12(new RegExp(`^\\s*${key}\\s*=\\s*(?!["'])\\S+`, 'mu'))]));
11584
- if (hasUnquotedId('project_id') || hasUnquotedId('app_id')) {
11585
- throw new CliError(
11586
- '.coze [project].project_id and app_id must be quoted decimal strings.',
11587
- 'INVALID_COZE_FILE',
11588
- );
11589
- }
11590
- if (projectId && !isId(projectId)) {
11591
- throw new CliError('.coze [project].project_id must be a quoted decimal string.', 'INVALID_COZE_FILE');
11592
- }
11593
- if (appId && !isId(appId)) {
11594
- throw new CliError('.coze [project].app_id must be a quoted decimal string.', 'INVALID_COZE_FILE');
11595
- }
11596
- return { name, projectType, projectId, appId, cozeFileContent };
11597
- };
11598
-
11599
- const updateProjectValue = (content, key, value) => {
11600
- const sectionMatch = /^\s*\[project\]\s*(?:#.*)?$/mu.exec(content);
11601
- if (!sectionMatch || sectionMatch.index === undefined) {
11602
- const prefix = `[project]\n${key} = ${JSON.stringify(value)}\n\n`;
11603
- return `${prefix}${content}`;
11604
- }
11605
- const sectionStart = sectionMatch.index + sectionMatch[0].length;
11606
- const following = content.slice(sectionStart);
11607
- const nextSection = /^\s*\[[^\]]+\]\s*(?:#.*)?$/mu.exec(following);
11608
- const sectionEnd = _optionalChain$6([nextSection, 'optionalAccess', _13 => _13.index]) === undefined
11609
- ? content.length
11610
- : sectionStart + nextSection.index;
11611
- const before = content.slice(0, sectionStart);
11612
- let body = content.slice(sectionStart, sectionEnd);
11613
- const keyPattern = new RegExp(`^(\\s*)${key}\\s*=.*$`, 'mu');
11614
- if (keyPattern.test(body)) {
11615
- body = body.replace(keyPattern, `$1${key} = ${JSON.stringify(value)}`);
11616
- } else {
11617
- const separator = body.startsWith('\n') || body.startsWith('\r\n') ? '' : '\n';
11618
- body = `${separator}${body}`;
11619
- const trailingNewline = body.endsWith('\n') ? '' : '\n';
11620
- body = `${body}${trailingNewline}${key} = ${JSON.stringify(value)}\n`;
11621
- }
11622
- return `${before}${body}${content.slice(sectionEnd)}`;
11623
- };
11624
-
11625
- const writeProjectBinding = async (
11626
- sourceRoot,
11627
- binding,
11628
- ) => {
11629
- const path = node_path.join(sourceRoot, '.coze');
11630
- let content = await promises.readFile(path, 'utf8');
11631
- if (binding.projectId) {
11632
- content = updateProjectValue(content, 'project_id', binding.projectId);
11633
- }
11634
- if (binding.appId) {
11635
- content = updateProjectValue(content, 'app_id', binding.appId);
11636
- }
11637
- const tempPath = node_path.join(node_path.dirname(path), `.coze-${node_crypto.randomUUID()}.tmp`);
11638
- try {
11639
- await promises.writeFile(tempPath, content, { encoding: 'utf8', mode: 0o600 });
11640
- await promises.rename(tempPath, path);
11641
- } finally {
11642
- await promises.rm(tempPath, { force: true });
11643
- }
11644
- return readProjectMetadata(sourceRoot);
11645
- };
11646
-
11647
- const ensureProjectMetadata = async (
11648
- sourceRoot,
11649
- options,
11650
- ) => {
11651
- try {
11652
- return await readProjectMetadata(sourceRoot);
11653
- } catch (error) {
11654
- if ((error ).code !== 'COZE_FILE_NOT_FOUND' || !options.allowCreate) {
11655
- throw error;
11656
- }
11657
- }
11658
- const name = _optionalChain$6([options, 'access', _14 => _14.name, 'optionalAccess', _15 => _15.trim, 'call', _16 => _16()]) || 'Pages application';
11659
- const projectType = _optionalChain$6([options, 'access', _17 => _17.projectType, 'optionalAccess', _18 => _18.trim, 'call', _19 => _19()]) || 'web';
11660
- await promises.writeFile(
11661
- node_path.join(sourceRoot, '.coze'),
11662
- `[project]\nname = ${JSON.stringify(name)}\nproject_type = ${JSON.stringify(projectType)}\n`,
11663
- { encoding: 'utf8', mode: 0o600 },
11664
- );
11665
- return readProjectMetadata(sourceRoot);
11666
- };
11667
-
11668
- function _optionalChain$5(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = fn(value); } else if (op === 'call' || op === 'optionalCall') { value = fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; }
11669
- const isFile = async (path) => {
11670
- try {
11671
- return (await promises.stat(path)).isFile();
11672
- } catch (error) {
11673
- if ((error ).code === 'ENOENT') {
11674
- return false;
11675
- }
11676
- throw error;
11677
- }
11678
- };
11679
-
11680
- const validatePagesSource = async (
11681
- sourceRoot,
11682
- cozeFileContent,
11683
- ) => {
11684
- if (await isFile(node_path.join(sourceRoot, 'index.html'))) {
11685
- return;
11686
- }
11687
-
11688
- let config;
11689
- try {
11690
- config = TOML.parse(cozeFileContent);
11691
- } catch (error) {
11692
- throw new CliError(
11693
- `Unable to parse .coze: ${error instanceof Error ? error.message : String(error)}`,
11694
- 'INVALID_COZE_FILE',
11695
- );
11696
- }
11697
- const project = config.project ;
11698
- if (typeof _optionalChain$5([project, 'optionalAccess', _ => _.template]) !== 'string' || project.template.trim().toLowerCase() !== 'nextjs') {
11699
- throw new CliError(
11700
- 'Pages source contains no index.html; .coze project.template must be "nextjs".',
11701
- 'PAGES_BUILD_CONFIG_REQUIRED',
11702
- );
11703
- }
11704
- const deploy = config.deploy ;
11705
- const build = _optionalChain$5([deploy, 'optionalAccess', _2 => _2.build]);
11706
- if (!Array.isArray(build) || build.length === 0 || !build.every(part => typeof part === 'string' && part.length > 0)) {
11707
- throw new CliError(
11708
- 'Pages source contains no index.html; .coze deploy.build must be a non-empty string array.',
11709
- 'PAGES_BUILD_CONFIG_REQUIRED',
11710
- );
11711
- }
11712
- };
11713
-
11714
- const readDeployLocalContext = async (
11715
- sourceRoot,
11716
- requestedApplicationType,
11717
- appId,
11718
- client,
11719
- ) => {
11720
- const sourceSnapshot = resolveSourceSnapshot(sourceRoot);
11721
- let applicationTypeHint = requestedApplicationType;
11722
- let effectiveAppId = appId;
11723
- if (!effectiveAppId) {
11724
- try {
11725
- effectiveAppId = (await ensureProjectMetadata(sourceRoot, { allowCreate: false })).appId;
11726
- } catch (error) {
11727
- if ((error ).code !== 'COZE_FILE_NOT_FOUND') {
11728
- throw error;
11729
- }
11730
- }
11731
- }
11732
- if (!applicationTypeHint && effectiveAppId) {
11733
- applicationTypeHint = (await client.getApplication(effectiveAppId)).application_type;
11734
- }
11735
- const isPagesDeployment = applicationTypeHint === 'pages';
11736
- const metadata = await ensureProjectMetadata(sourceRoot, {
11737
- allowCreate: isPagesDeployment,
11738
- projectType: isPagesDeployment ? 'web' : undefined,
11739
- });
11740
- if (isPagesDeployment) {
11741
- await validatePagesSource(sourceRoot, metadata.cozeFileContent);
11742
- }
11743
- return { ...sourceSnapshot, metadata, isPagesDeployment };
11744
- };
11745
-
11746
- // 服务端 deploy_app/list 的 page_size 上限,超了会被判参数错误。
11747
- // 客户端先拦一道,是为了把错误说在本地(带上上限值),而不是回一句服务端的通用参数错误。
11748
- const APP_LIST_MAX_PAGE_SIZE = 100;
11749
-
11750
- // page_token 是**页码的十进制字符串**(服务端口径,与 deploy_history/list 一致),不是不透明游标。
11751
- // 所以这里能、也应该在本地校验:`--page-token abc` 早报错,比发出去再被拒强。
11752
- const parsePositiveInt = (
11753
- raw,
11754
- option,
11755
- code,
11756
- max,
11757
- ) => {
11758
- const value = Number(raw);
11759
- if (!Number.isSafeInteger(value) || value <= 0) {
11760
- throw new CliError(`${option} must be a positive integer.`, code, { [option]: raw });
11761
- }
11762
- if (max !== undefined && value > max) {
11763
- throw new CliError(`${option} must not exceed ${String(max)}.`, code, { [option]: raw });
11764
- }
11765
- return value;
11766
- };
11767
-
11768
- // ⛔ 别再用 `Number(options.pageSize || 20)`:`--page-size abc` 会算出 NaN,
11769
- // JSON.stringify 把它写成 null 发给服务端,最后表现为「参数没生效」而不是「参数写错了」。
11770
- const parsePageSize = (
11771
- raw,
11772
- fallback,
11773
- max,
11774
- ) => {
11775
- if (raw === undefined || raw === '') {
11776
- return fallback;
11777
- }
11778
- return parsePositiveInt(raw, '--page-size', 'INVALID_PAGE_SIZE', max);
11779
- };
11780
-
11781
- const parsePageToken = (raw) => {
11782
- if (raw === undefined || raw === '') {
11783
- return undefined;
11784
- }
11785
- parsePositiveInt(raw, '--page-token', 'INVALID_PAGE_TOKEN');
11786
- return raw;
11787
- };
11788
-
11789
-
11790
-
11791
-
11792
-
11793
-
11794
-
11795
- // collectAllPages 顺着 next_page_token 把所有页取回来。
11796
- //
11797
- // 服务端从「全量单页」改成真分页之后,`app list` 一次只回一页;想要「我的全部应用」就得翻页。
11798
- // 与其让每个调用方各写一遍循环,不如给一个 --all。
11799
- //
11800
- // ⚠️ 不设页数上限截断:静默截断正是这次要修掉的毛病。只防死循环——服务端如果一直回同一个
11801
- // token(或说 has_more 却不给 token),直接报错,而不是无限翻。
11802
- const collectAllPages = async (
11803
- fetchPage,
11804
- ) => {
11805
- const items = [];
11806
- const seen = new Set();
11807
- let pageToken;
11808
- let pages = 0;
11809
- for (;;) {
11810
- const page = await fetchPage(pageToken);
11811
- items.push(...(page.items || []));
11812
- pages += 1;
11813
- if (!page.has_more) {
11814
- return { items, pages };
11815
- }
11816
- const next = page.next_page_token;
11817
- if (!next || seen.has(next)) {
11818
- throw new CliError(
11819
- 'The server reported more pages but returned no usable next_page_token.',
11820
- 'INVALID_PAGE_TOKEN',
11821
- { next_page_token: next, pages },
11822
- );
11823
- }
11824
- seen.add(next);
11825
- pageToken = next;
11826
- }
11827
- };
11828
-
11829
- async function _asyncOptionalChain(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = await fn(value); } else if (op === 'call' || op === 'optionalCall') { value = await fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; }
11830
-
11831
- const registerDeployReadCommands = (deploy) => {
11832
- deploy
11833
- .command('status')
11834
- .option('--app-id <appId>', 'Application ID')
11835
- .option('--deploy-id <deployId>', 'Deployment history ID')
11836
- .action(async (options, command) => {
11837
- const runtime = await getRuntime(command);
11838
- const appId = await requireAppId(runtime.cwd, getDeployAppIdOption(options, command));
11839
- let deployHistoryId = options.deployId;
11840
- if (!deployHistoryId) {
11841
- deployHistoryId = await _asyncOptionalChain([(
11842
- await runtime.client.listDeployHistory({ app_id: appId, page_size: 1 })
11843
- ), 'access', async _ => _.deploy_history_list, 'optionalAccess', async _2 => _2[0], 'optionalAccess', async _3 => _3.deploy_history_id]);
11844
- }
11845
- if (!deployHistoryId) {
11846
- throw new CliError('No deployment history found.', 'DEPLOYMENT_NOT_FOUND');
11847
- }
11848
- const history = await runtime.client.getDeployHistory({
11849
- app_id: appId,
11850
- deploy_history_id: deployHistoryId,
11851
- });
11852
- runtime.output.print({
11853
- app_id: appId,
11854
- deploy_history_id: deployHistoryId,
11855
- status: getDeployStatusText(history.status),
11856
- commit_hash: history.commit_hash,
11857
- domains: history.domain_list || [],
11858
- error_analysis: history.error_analysis,
11859
- deploy_detail: formatDeployDetails(history),
11860
- connector_data_list: history.connector_data_list || [],
11861
- mobile_artifact_list: history.mobile_artifact_list || [],
11862
- });
11863
- });
11864
-
11865
- deploy
11866
- .command('list')
11867
- .option('--app-id <appId>', 'Application ID')
11868
- .option('--page-size <pageSize>', 'Page size', '10')
11869
- .option('--page-token <pageToken>', 'Page token (page number)')
11870
- .action(async (options, command) => {
11871
- // 先在本地校验:`--page-size abc` 以前算出 NaN 发出去,表现成「参数没生效」。
11872
- const pageSize = parsePageSize(options.pageSize, 10);
11873
- const pageToken = parsePageToken(options.pageToken);
11874
- const runtime = await getRuntime(command);
11875
- const appId = await requireAppId(runtime.cwd, getDeployAppIdOption(options, command));
11876
- const data = await runtime.client.listDeployHistory({
11877
- app_id: appId,
11878
- page_size: pageSize,
11879
- page_token: pageToken,
11880
- });
11881
- runtime.output.print({
11882
- items: (data.deploy_history_list || []).map(item => ({
11883
- deploy_history_id: item.deploy_history_id,
11884
- status: getDeployStatusText(item.status),
11885
- commit_hash: item.commit_hash_short || item.commit_hash,
11886
- created_at: item.created_at,
11887
- can_rollback: item.can_rollback,
11888
- deploy_detail: formatDeployDetails(item),
11889
- connector_data_list: item.connector_data_list || [],
11890
- mobile_artifact_list: item.mobile_artifact_list || [],
11891
- })),
11892
- next_page_token: data.next_page_token,
11893
- has_more: data.has_more,
11894
- });
11895
- });
11896
-
11897
- deploy
11898
- .command('online')
11899
- .description('Show the current online deployment')
11900
- .option('--app-id <appId>', 'Application ID')
11901
- .action(async (options, command) => {
11902
- const runtime = await getRuntime(command);
11903
- const appId = await requireAppId(runtime.cwd, getDeployAppIdOption(options, command));
11904
- const data = await runtime.client.getOnlineDeployHistory(appId);
11905
- runtime.output.print({
11906
- app_id: appId,
11907
- items: (data.deploy_history_list || []).map(item => ({
11908
- deploy_history_id: item.deploy_history_id,
11909
- status: getDeployStatusText(item.status),
11910
- commit_hash: item.commit_hash_short || item.commit_hash,
11911
- created_at: item.created_at,
11912
- deploy_detail: formatDeployDetails(item),
11913
- domains: item.domain_list || [],
11914
- mobile_artifact_list: item.mobile_artifact_list || [],
11915
- })),
11916
- });
11917
- });
11918
-
11919
- deploy
11920
- .command('rollback-check')
11921
- .description('Check whether a deployment supports database rollback')
11922
- .requiredOption('--deploy-id <deployId>', 'Target deployment history ID')
11923
- .option('--app-id <appId>', 'Application ID')
11924
- .action(async (options, command) => {
11925
- const runtime = await getRuntime(command);
11926
- const appId = await requireAppId(runtime.cwd, getDeployAppIdOption(options, command));
11927
- const data = await runtime.client.checkRollbackDatabase({
11928
- app_id: appId,
11929
- deploy_history_id: options.deployId || '',
11930
- });
11931
- runtime.output.print({ app_id: appId, deploy_history_id: options.deployId, ...data });
11932
- });
11933
-
11934
- deploy
11935
- .command('log-count')
11936
- .description('Show runtime log count and limit')
11937
- .option('--app-id <appId>', 'Application ID')
11938
- .action(async (options, command) => {
11939
- const runtime = await getRuntime(command);
11940
- const appId = await requireAppId(runtime.cwd, getDeployAppIdOption(options, command));
11941
- const data = await runtime.client.getRuntimeLogCount(appId);
11942
- runtime.output.print({ app_id: appId, ...data });
11943
- });
11944
-
11945
- deploy
11946
- .command('count')
11947
- .description('Show successful deployment count')
11948
- .option('--app-id <appId>', 'Application ID')
11949
- .action(async (options, command) => {
11950
- const runtime = await getRuntime(command);
11951
- const appId = await requireAppId(runtime.cwd, getDeployAppIdOption(options, command));
11952
- const data = await runtime.client.getDeployCount(appId);
11953
- runtime.output.print({ app_id: appId, ...data });
11954
- });
11955
- };
11956
-
11957
- const registerEnv = (code) => {
11958
- const env = code
11959
- .command('env')
11960
- .description('Inspect the current online environment snapshot');
11961
-
11962
- env
11963
- .command('list')
11964
- .description('List environment variables of the current online deployment')
11965
- .option('--app-id <appId>', 'Application ID')
11966
- .action(async (options, command) => {
11967
- const runtime = await getRuntime(command);
11968
- const appId = await requireAppId(
11969
- runtime.cwd,
11970
- getDeployAppIdOption(options, command),
11971
- );
11972
- runtime.output.print(await runtime.client.getOnlineEnvironment(appId));
11973
- });
11974
- };
11975
-
11976
- function _nullishCoalesce$1(lhs, rhsFn) { if (lhs != null) { return lhs; } else { return rhsFn(); } } function _optionalChain$4(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = fn(value); } else if (op === 'call' || op === 'optionalCall') { value = fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; }
11977
- const CONNECTOR_IDS = {
11978
- wechat: '10000127',
11979
- douyin: '10000126',
11980
- } ;
11981
-
11982
-
11983
-
11984
-
11985
-
11986
-
11987
-
11988
-
11989
-
11990
-
11991
-
11992
-
11993
-
11994
-
11995
- const resolveConnectorId = (platform) => {
11996
- const connectorId = CONNECTOR_IDS[platform ];
11997
- if (!connectorId) {
11998
- throw new CliError(
11999
- `Unsupported Mini-program platform ${String(platform)}; expected wechat or douyin.`,
12000
- 'INVALID_MINIPROGRAM_PLATFORM',
12001
- );
12002
- }
12003
- return connectorId;
12004
- };
12005
-
12006
- const resolveProjectId = async (
12007
- command,
12008
- options,
12009
- ) => {
12010
- if (_optionalChain$4([options, 'access', _ => _.projectId, 'optionalAccess', _2 => _2.trim, 'call', _3 => _3()])) {
12011
- return options.projectId.trim();
12012
- }
12013
- const runtime = await getRuntime(command);
12014
- const sourceRoot = node_path.resolve(runtime.cwd, options.sourceRoot || '.');
12015
- const metadata = await readProjectMetadata(sourceRoot);
12016
- if (!metadata.projectId) {
12017
- throw new CliError(
12018
- 'Project ID is required. Pass --project-id or use a source directory whose .coze [project] contains project_id.',
12019
- 'PROJECT_ID_REQUIRED',
12020
- );
12021
- }
12022
- return metadata.projectId;
12023
- };
12024
-
12025
- const registerMiniProgram = (code) => {
12026
- const miniProgram = code
12027
- .command('mini-program')
12028
- .alias('miniprogram')
12029
- .description('Manage WeChat or Douyin Mini-program authorization');
12030
-
12031
- miniProgram
12032
- .command('status')
12033
- .requiredOption('--platform <platform>', 'wechat or douyin')
12034
- .option('--project-id <projectId>', 'Deployment Project ID')
12035
- .option('--source-root <sourceRoot>', 'Directory containing .coze', '.')
12036
- .action(async (options, command) => {
12037
- const runtime = await getRuntime(command);
12038
- const projectId = await resolveProjectId(command, options);
12039
- const connectorId = resolveConnectorId(options.platform);
12040
- const data = await runtime.client.getMiniProgramAuthStatus({
12041
- project_id: projectId,
12042
- connector_id: connectorId,
12043
- });
12044
- runtime.output.print({ project_id: projectId, platform: options.platform, ...data });
12045
- });
12046
-
12047
- miniProgram
12048
- .command('bind')
12049
- .requiredOption('--platform <platform>', 'wechat or douyin')
12050
- .requiredOption('--mini-app-id <miniAppId>', 'Mini-program AppID')
12051
- .requiredOption('--redirect-url <redirectUrl>', 'OAuth callback URL')
12052
- .option('--project-id <projectId>', 'Deployment Project ID')
12053
- .option('--source-root <sourceRoot>', 'Directory containing .coze', '.')
12054
- .option('--override', 'Move an AppID already bound to another project owned by you')
12055
- .action(async (options, command) => {
12056
- const runtime = await getRuntime(command);
12057
- const projectId = await resolveProjectId(command, options);
12058
- const connectorId = resolveConnectorId(options.platform);
12059
- const data = await runtime.client.bindMiniProgramAuth({
12060
- project_id: projectId,
12061
- connector_id: connectorId,
12062
- redirect_url: options.redirectUrl || '',
12063
- auth_params: { app_id: options.miniAppId || '' },
12064
- override: _nullishCoalesce$1(options.override, () => ( false)),
12065
- });
12066
- runtime.output.print({
12067
- project_id: projectId,
12068
- platform: options.platform,
12069
- mini_app_id: options.miniAppId,
12070
- ...data,
12071
- });
12072
- });
12073
-
12074
- miniProgram
12075
- .command('submit-code')
12076
- .requiredOption('--platform <platform>', 'wechat or douyin')
12077
- .requiredOption('--mini-app-id <miniAppId>', 'Mini-program AppID')
12078
- .requiredOption('--code <code>', 'OAuth authorization code')
12079
- .requiredOption('--verify-state <verifyState>', 'State returned by bind')
12080
- .option('--project-id <projectId>', 'Deployment Project ID')
12081
- .option('--source-root <sourceRoot>', 'Directory containing .coze', '.')
12082
- .action(async (options, command) => {
12083
- const runtime = await getRuntime(command);
12084
- const projectId = await resolveProjectId(command, options);
12085
- await runtime.client.submitMiniProgramAuthCode({
12086
- project_id: projectId,
12087
- connector_id: resolveConnectorId(options.platform),
12088
- code: options.code || '',
12089
- verify_state: options.verifyState || '',
12090
- auth_params: { app_id: options.miniAppId || '' },
12091
- });
12092
- runtime.output.print({ project_id: projectId, platform: options.platform, bound: true });
12093
- });
12094
-
12095
- miniProgram
12096
- .command('unbind')
12097
- .requiredOption('--platform <platform>', 'wechat or douyin')
12098
- .option('--project-id <projectId>', 'Deployment Project ID')
12099
- .option('--source-root <sourceRoot>', 'Directory containing .coze', '.')
12100
- .action(async (options, command) => {
12101
- const runtime = await getRuntime(command);
12102
- const projectId = await resolveProjectId(command, options);
12103
- await runtime.client.unbindMiniProgramAuth({
12104
- project_id: projectId,
12105
- connector_id: resolveConnectorId(options.platform),
12106
- });
12107
- runtime.output.print({ project_id: projectId, platform: options.platform, unbound: true });
12108
- });
12109
- };
12110
-
12111
- function _optionalChain$3(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = fn(value); } else if (op === 'call' || op === 'optionalCall') { value = fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; }
12112
-
12113
- const POLL_INTERVAL_MS = 3000;
12114
- const MAX_CONSECUTIVE_RETRIES = 5;
12115
- const TRANSIENT_RPC_ERROR_CODE = 230000001;
12116
-
12117
- const wait = async () =>
12118
- new Promise(resolve => setTimeout(resolve, POLL_INTERVAL_MS));
12119
-
12120
- const isRetryablePollError = (error) =>
12121
- error instanceof CliError &&
12122
- error.code === 'API_REJECTED' &&
12123
- Number(_optionalChain$3([error, 'access', _ => _.details, 'optionalAccess', _2 => _2.business_code])) === TRANSIENT_RPC_ERROR_CODE;
12124
-
12125
- const pollHistory = async (
12126
- command,
12127
- appId,
12128
- deployHistoryId,
12129
- ) => {
12130
- const runtime = await getRuntime(command);
12131
- const startedAt = Date.now();
12132
- let consecutiveFailures = 0;
12133
- while (true) {
12134
- try {
12135
- const history = await runtime.client.getDeployHistory({
12136
- app_id: appId,
12137
- deploy_history_id: deployHistoryId,
12138
- });
12139
- consecutiveFailures = 0;
12140
- const status = getDeployStatusText(history.status);
12141
- runtime.output.debug(
12142
- `[deploy] History ${deployHistoryId}: ${status} (${String(Math.floor((Date.now() - startedAt) / 1000))}s elapsed)`,
12143
- );
12144
- if (history.status && TERMINAL_STATUSES.has(history.status)) {
12145
- return history;
12146
- }
12147
- } catch (error) {
12148
- if (!isRetryablePollError(error) || consecutiveFailures >= MAX_CONSECUTIVE_RETRIES) {
12149
- throw error;
12150
- }
12151
- consecutiveFailures += 1;
12152
- runtime.output.debug(
12153
- `[deploy] Status check failed transiently; retrying (${String(consecutiveFailures)}/${String(MAX_CONSECUTIVE_RETRIES)}).`,
12154
- );
12155
- }
12156
- await wait();
12157
- }
12158
- };
12159
-
12160
- const GENERAL_PROJECT_TYPE = 9;
12161
-
12162
- /**
12163
- * Map `.coze` `[project].project_type` to the VibeProjectType used when creating the
12164
- * deployment project.
12165
- *
12166
- * The values on the left are the ones the deploy server understands (see `cozefileutil`
12167
- * `ResolveDeployKindByProjectType` / `GeneralProjectTypeByCozeProjectType` in coze-coding);
12168
- * the numbers on the right are `VibeProjectType` (idl/coze.coding.ide/project.thrift).
12169
- *
12170
- * Keeping the two in sync matters beyond project metadata: the created project type decides
12171
- * the project-scoped `COZE_PROJECT_TYPE` secret injected into the runtime, whether a Postgres
12172
- * database is provisioned for the project, and whether the traffic gateway enforces inbound
12173
- * auth. Creating an `agent` project as General(9) therefore deploys successfully but leaves a
12174
- * dead service: the agent template reads `COZE_PROJECT_TYPE` to pick its graph and needs
12175
- * `PGDATABASE_URL` on startup.
12176
- *
12177
- * VibeProjectType WebApp(3) and AssistantAgent(8) are intentionally absent: no `.coze`
12178
- * project_type maps to them.
12179
- */
12180
- const resolveCreationProjectType = (
12181
- projectType,
12182
- ) => {
12183
- switch (projectType) {
12184
- case 'agent':
12185
- return 1;
12186
- case 'workflow':
12187
- case 'automation':
12188
- return 2;
12189
- case 'app':
12190
- return 4;
12191
- case 'skill':
12192
- return 5;
12193
- case 'web':
12194
- case 'backend':
12195
- return 6;
12196
- case 'miniapp':
12197
- case 'miniprogram':
12198
- return 7;
12199
- default:
12200
- return GENERAL_PROJECT_TYPE;
12201
- }
12202
- };
12203
-
12204
- const formatDeployment = (deployment) =>
12205
- typeof deployment === 'object' && deployment
12206
- ? {
12207
- ...(deployment ),
12208
- status: getDeployStatusText(
12209
- Number((deployment ).status),
12210
- ),
12211
- }
12212
- : undefined;
12213
-
12214
- const formatApplication = (application) => ({
12215
- ...application,
12216
- online_deployment: formatDeployment(application.online_deployment),
12217
- latest_deployment: formatDeployment(application.latest_deployment),
12218
- });
12219
-
12220
- // 对应 IDL 的 MetricTimeRange,数值与 V1 保持一致。
12221
- const TIME_RANGES = {
12222
- day: 1,
12223
- week: 2,
12224
- month: 3,
12225
- yesterday: 4,
12226
- 'three-days': 5,
12227
- };
12228
-
12229
- const resolveTimeRange = (value) => {
12230
- const timeRange = TIME_RANGES[value || 'day'];
12231
- if (!timeRange) {
12232
- throw new CliError(
12233
- `Invalid time range; expected one of ${Object.keys(TIME_RANGES).join(', ')}.`,
12234
- 'INVALID_TIME_RANGE',
12235
- { time_range: value },
12236
- );
12237
- }
12238
- return timeRange;
12239
- };
12240
-
12241
- const UNIT_TYPES = { dev: 1, prod: 2 };
12242
-
12243
- // 改 Application 本身的两条写操作,都要显式 --yes 才生效。
12244
- // 单独拎出来是因为它们和 registerApp 里其余只读命令性质不同(会改线上资产),
12245
- // 顺带让 registerApp 保持在 max-line-per-function 之内。
12246
- const registerAppMutations = (app) => {
12247
- app
12248
- .command('rename <name>')
12249
- .description('Rename an application')
12250
- .option('--app-id <appId>', 'Application ID')
12251
- .option('--yes', 'Confirm rename')
12252
- .action(async (name, options, command) => {
12253
- if (!options.yes) {
12254
- throw new CliError('Pass --yes to rename the application.', 'CONFIRMATION_REQUIRED');
12255
- }
12256
- const normalizedName = name.trim();
12257
- if (!normalizedName || normalizedName.length > 255) {
12258
- throw new CliError(
12259
- 'Application name must contain 1 to 255 characters.',
12260
- 'INVALID_APPLICATION_NAME',
12261
- );
12262
- }
12263
- const runtime = await getRuntime(command);
12264
- const appId = await requireAppId(runtime.cwd, options.appId);
12265
- const application = await runtime.client.updateApplication({
12266
- app_id: appId,
12267
- name: normalizedName,
12268
- });
12269
- runtime.output.print(
12270
- formatApplication(application ),
12271
- );
12272
- });
12273
- app
12274
- // 删除是终态、不可撤销,所以和 rename 一样必须显式 --yes。
12275
- //
12276
- // 服务端只接受 **Stopped** 的应用:还在服务的先 `code deploy stop --yes`,否则会拿到一条
12277
- // 带当前状态的报错。这里刻意不替用户先停 —— 停服会真的把线上服务摘掉,那得是用户自己按的。
12278
- .command('delete')
12279
- .description('Delete a stopped application (irreversible)')
12280
- .option('--app-id <appId>', 'Application ID')
12281
- .option('--yes', 'Confirm delete')
12282
- .action(async (options, command) => {
12283
- if (!options.yes) {
12284
- throw new CliError('Pass --yes to delete the application.', 'CONFIRMATION_REQUIRED');
12285
- }
12286
- const runtime = await getRuntime(command);
12287
- const appId = await requireAppId(runtime.cwd, options.appId);
12288
- await runtime.client.deleteApplication(appId);
12289
- // 本地 .coze 里的 app_id 不动(这条命令可能是在别的目录带 --app-id 跑的),但要说清楚:
12290
- // 不清掉它,同目录下一次 deploy 会打到一个已删除的应用上、被服务端拒。
12291
- runtime.output.print({
12292
- app_id: appId,
12293
- deleted: true,
12294
- note: 'Remove app_id from .coze [project] before deploying this directory again.',
12295
- });
12296
- });
12297
- };
12298
-
12299
- const registerApp = (code) => {
12300
- const app = code.command('app').description('Manage deployment applications');
12301
- registerAppMutations(app);
12302
- app
12303
- .command('list')
12304
- // 列的是当前登录用户名下**跨 Project** 的全部 Application。没有 --project-id:
12305
- // V2 的资产归属是 Owner 而不是 Project,同一个 Project 下的应用可以分属不同用户。
12306
- // 也不传 user_id:服务端直接从登录态取,客户端传了也只能传自己。
12307
- //
12308
- // ⚠️ 服务端是真分页(一页最多 100 条),一次调用只回一页。要「我的全部应用」用 --all,
12309
- // 它顺着 next_page_token 翻到底 —— 别再默认第一页就是全部。
12310
- .option('--page-token <pageToken>', 'Pagination token (page number)')
12311
- .option('--page-size <pageSize>', 'Page size', '20')
12312
- .option('--all', 'Fetch every page by following next_page_token')
12313
- .action(async (options, command) => {
12314
- const pageSize = parsePageSize(options.pageSize, 20, APP_LIST_MAX_PAGE_SIZE);
12315
- const pageToken = parsePageToken(options.pageToken);
12316
- if (options.all && pageToken) {
12317
- throw new CliError(
12318
- '--all fetches every page and cannot be combined with --page-token.',
12319
- 'INVALID_PAGE_TOKEN',
12320
- { page_token: options.pageToken },
12321
- );
12322
- }
12323
- const runtime = await getRuntime(command);
12324
- const format = (items) =>
12325
- items.map(item => formatApplication(item ));
12326
- if (options.all) {
12327
- const { items, pages } = await collectAllPages(next =>
12328
- runtime.client.listApplications({ page_token: next, page_size: pageSize }),
12329
- );
12330
- runtime.output.print({ items: format(items), pages, has_more: false });
12331
- return;
12332
- }
12333
- const data = await runtime.client.listApplications({
12334
- page_token: pageToken,
12335
- page_size: pageSize,
12336
- });
12337
- runtime.output.print({
12338
- items: format(data.items),
12339
- next_page_token: data.next_page_token,
12340
- has_more: data.has_more,
12341
- });
12342
- });
12343
- app
12344
- .command('show')
12345
- .requiredOption('--app-id <appId>', 'Application ID')
12346
- .action(async (options, command) => {
12347
- const runtime = await getRuntime(command);
12348
- runtime.output.print(
12349
- formatApplication(
12350
- (await runtime.client.getApplication(options.appId))
12351
-
12352
-
12353
- ,
12354
- ),
12355
- );
12356
- });
12357
- app
12358
- .command('analytics')
12359
- .description('Show PV / UV charts')
12360
- .option('--app-id <appId>', 'Application ID')
12361
- .option(
12362
- '--time-range <timeRange>',
12363
- `Time range: ${Object.keys(TIME_RANGES).join(', ')}`,
12364
- 'day',
12365
- )
12366
- .action(async (options, command) => {
12367
- const timeRange = resolveTimeRange(options.timeRange);
12368
- const runtime = await getRuntime(command);
12369
- const appId = await requireAppId(runtime.cwd, options.appId);
12370
- const data = await runtime.client.getUserAnalyticsMetrics({
12371
- app_id: appId,
12372
- time_range: timeRange,
12373
- });
12374
- runtime.output.print({ app_id: appId, charts: data.charts || [] });
12375
- });
12376
- app
12377
- .command('metrics')
12378
- .description('Show application runtime metrics')
12379
- .option('--app-id <appId>', 'Application ID')
12380
- .option(
12381
- '--time-range <timeRange>',
12382
- `Time range: ${Object.keys(TIME_RANGES).join(', ')}`,
12383
- 'day',
12384
- )
12385
- .action(async (options, command) => {
12386
- const timeRange = resolveTimeRange(options.timeRange);
12387
- const runtime = await getRuntime(command);
12388
- const appId = await requireAppId(runtime.cwd, options.appId);
12389
- const data = await runtime.client.getApplicationMetrics({
12390
- app_id: appId,
12391
- time_range: timeRange,
12392
- });
12393
- runtime.output.print({
12394
- app_id: appId,
12395
- charts: data.charts || [],
12396
- stats: data.stats || [],
12397
- });
12398
- });
12399
- app
12400
- .command('usage')
12401
- .description('Show monthly hosted usage')
12402
- .option('--app-id <appId>', 'Application ID')
12403
- .requiredOption('--bill-month <billMonth>', 'Billing month in YYYY-MM format')
12404
- .action(async (options, command) => {
12405
- const billMonth = options.billMonth || '';
12406
- if (!/^\d{4}-(?:0[1-9]|1[0-2])$/u.test(billMonth)) {
12407
- throw new CliError(
12408
- 'Invalid billing month; expected YYYY-MM.',
12409
- 'INVALID_BILL_MONTH',
12410
- { bill_month: billMonth },
12411
- );
12412
- }
12413
- const runtime = await getRuntime(command);
12414
- const appId = await requireAppId(runtime.cwd, options.appId);
12415
- const data = await runtime.client.getHostedUsageMonthly({
12416
- app_id: appId,
12417
- bill_month: billMonth,
12418
- });
12419
- runtime.output.print({ app_id: appId, summary: data.summary });
12420
- });
12421
- };
12422
-
12423
- const registerDomain = (code) => {
12424
- const domain = code.command('domain').description('Manage application domains');
12425
- domain
12426
- .command('list')
12427
- .option('--app-id <appId>', 'Application ID')
12428
- .option('--unit-type <unitType>', 'Unit type: dev or prod', 'prod')
12429
- .action(async (options, command) => {
12430
- const unitType = UNIT_TYPES[options.unitType || 'prod'];
12431
- if (!unitType) {
12432
- throw new CliError(
12433
- 'Invalid unit type; expected dev or prod.',
12434
- 'INVALID_UNIT_TYPE',
12435
- { unit_type: options.unitType },
12436
- );
12437
- }
12438
- const runtime = await getRuntime(command);
12439
- const appId = await requireAppId(runtime.cwd, options.appId);
12440
- const data = await runtime.client.listDomains(appId, unitType);
12441
- runtime.output.print({
12442
- app_id: appId,
12443
- unit_type: options.unitType || 'prod',
12444
- items: (data.items || []).map(item => ({
12445
- id: item.id,
12446
- domain_host: item.domain_host,
12447
- })),
12448
- });
12449
- });
12450
- domain
12451
- // 改的是系统分配的 <prefix>.coze.site 的 prefix,不是 `domain add` 加进来的自定义域名 ——
12452
- // 那类域名服务端只有 create/delete,域名串本身改不了。
12453
- //
12454
- // 和 rename 一样要 --yes:旧默认域名会立刻停止指向本应用,已经发出去的链接会失效。
12455
- .command('set-prefix <prefix>')
12456
- .description('Change the default domain prefix (<prefix>.coze.site)')
12457
- .option('--app-id <appId>', 'Application ID')
12458
- .option('--yes', 'Confirm prefix change')
12459
- .action(async (prefix, options, command) => {
12460
- if (!options.yes) {
12461
- throw new CliError(
12462
- 'Pass --yes to change the default domain prefix.',
12463
- 'CONFIRMATION_REQUIRED',
12464
- );
12465
- }
12466
- const normalizedPrefix = prefix.trim();
12467
- // 只做形态校验:长度、保留词、占用与权益都由服务端判,客户端不复制第二套规则。
12468
- if (!/^[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/u.test(normalizedPrefix)) {
12469
- throw new CliError(
12470
- 'Invalid prefix; use lowercase letters, digits and hyphens, not starting or ending with a hyphen.',
12471
- 'INVALID_DOMAIN_PREFIX',
12472
- { prefix },
12473
- );
12474
- }
12475
- const runtime = await getRuntime(command);
12476
- const appId = await requireAppId(runtime.cwd, options.appId);
12477
- const data = await runtime.client.updateDefaultDomainPrefix({
12478
- app_id: appId,
12479
- prefix: normalizedPrefix,
12480
- });
12481
- runtime.output.print({
12482
- app_id: appId,
12483
- prefix: normalizedPrefix,
12484
- old_domain_host: data.old_domain_host_canonical,
12485
- new_domain_host: data.new_domain_host_canonical,
12486
- });
12487
- });
12488
- domain
12489
- .command('add <domain>')
12490
- .option('--app-id <appId>', 'Application ID')
12491
- .action(async (domainHost, options, command) => {
12492
- if (!/^[a-zA-Z0-9](?:[a-zA-Z0-9-]*\.)+[a-zA-Z0-9-]+$/u.test(domainHost)) {
12493
- throw new CliError('Invalid domain.', 'INVALID_DOMAIN', { domain: domainHost });
12494
- }
12495
- const runtime = await getRuntime(command);
12496
- const appId = await requireAppId(runtime.cwd, options.appId);
12497
- await runtime.client.createDomain({ app_id: appId, domain: domainHost });
12498
- runtime.output.print({ app_id: appId, domain: domainHost });
12499
- });
12500
- };
12501
-
12502
- function _optionalChain$2(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = fn(value); } else if (op === 'call' || op === 'optionalCall') { value = fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; }
12503
-
12504
- const firstPage = { page: 1, size: 1 };
12505
-
12506
- const listSpaceRequest = (runtime) => ({
12507
- ...(runtime.config.organizationId
12508
- ? { organization_id: runtime.config.organizationId }
12509
- : {}),
12510
- ...(runtime.config.enterpriseId
12511
- ? { enterprise_id: runtime.config.enterpriseId }
12512
- : {}),
12513
- });
12514
-
12515
- const resolveDeploymentSpaceId = async (runtime) => {
12516
- const configuredSpaceId = _optionalChain$2([runtime, 'access', _ => _.config, 'access', _2 => _2.spaceId, 'optionalAccess', _3 => _3.trim, 'call', _4 => _4()]);
12517
- const request = listSpaceRequest(runtime);
12518
- if (configuredSpaceId) {
12519
- const data = await runtime.client.listSpaces(request);
12520
- if (!data.bot_space_list.some(space => space.id === configuredSpaceId)) {
12521
- throw new CliError(
12522
- `Space ID ${configuredSpaceId} is invalid or is not available to the current account.`,
12523
- 'INVALID_SPACE_ID',
12524
- );
12525
- }
12526
- return configuredSpaceId;
12527
- }
12528
-
12529
- const data = await runtime.client.listSpaces({ ...request, ...firstPage });
12530
- const space = data.bot_space_list.find(item => item.id);
12531
- if (!space) {
12532
- throw new CliError(
12533
- 'No available Space was found for the current account. Create or join a Space before deploying.',
12534
- 'SPACE_NOT_FOUND',
12535
- );
12536
- }
12537
-
12538
- runtime.config.spaceId = space.id;
12539
- try {
12540
- await saveSharedConfig({ spaceId: space.id }, runtime.globalOptions);
12541
- } catch (error) {
12542
- runtime.output.warn(`Unable to save the auto-selected Space: ${String(error)}`);
12543
- }
12544
- runtime.output.debug(`Auto-selected Space: ${space.name || space.id} (${space.id})`);
12545
- return space.id;
12546
- };
12547
-
12548
- const PACKAGE_SCRIPT_CANDIDATES = [
12549
- node_path.resolve(__dirname, 'deploy/package-project.js'),
12550
- node_path.resolve(__dirname, '../../../scripts/deploy/package-project.js'),
12551
- ];
12552
-
12553
- const packageCommand = (args) => {
12554
- const packageScript = PACKAGE_SCRIPT_CANDIDATES.find(candidate =>
12555
- node_fs.existsSync(candidate),
12556
- );
12557
- if (!packageScript) {
12558
- throw new CliError(
12559
- 'The deployment packaging script is missing from this coze-dev installation.',
12560
- 'SOURCE_PACKAGE_FAILED',
12561
- );
12562
- }
12563
- return [packageScript, ...args];
12564
- };
12565
-
12566
- const runPackageScript = async (args, debug = false) =>
12567
- new Promise((resolvePromise, reject) => {
12568
- const child = node_child_process.spawn(process.execPath, packageCommand(args), {
12569
- stdio: ['ignore', 'pipe', 'pipe'],
12570
- });
12571
- let errorOutput = '';
12572
- const forward = (chunk) => {
12573
- const text = chunk.toString();
12574
- if (debug) {
12575
- process.stderr.write(text);
12576
- }
12577
- errorOutput = `${errorOutput}${text}`.slice(-65536);
12578
- };
12579
- child.stdout.on('data', forward);
12580
- child.stderr.on('data', forward);
12581
- child.once('error', reject);
12582
- child.once('close', code => {
12583
- if (code === 0) {
12584
- resolvePromise();
12585
- return;
12586
- }
12587
- reject(new Error(
12588
- `Packaging process exited with code ${String(code)}${errorOutput ? `\n${errorOutput.trim()}` : ''}`,
12589
- ));
12590
- });
12591
- });
12592
-
12593
-
12594
-
12595
-
12596
-
12597
-
12598
-
12599
-
12600
-
12601
-
12602
-
12603
-
12604
- const createSourcePackageArchive = async (
12605
- sourceRoot,
12606
- applicationType = 'service',
12607
- debug = false,
12608
- ) => {
12609
- const tempDirectory = await promises.mkdtemp(node_path.join(node_os.tmpdir(), 'coze-deploy-source-'));
12610
- const outputPath = node_path.join(tempDirectory, 'source.tar.gz');
12611
- try {
12612
- await runPackageScript(
12613
- [sourceRoot, outputPath, ...(applicationType === 'pages' ? ['--pages'] : [])],
12614
- debug,
12615
- );
12616
- const info = await promises.stat(outputPath);
12617
- if (info.size === 0) {
12618
- throw new CliError('Source package is empty.', 'SOURCE_PACKAGE_FAILED');
12619
- }
12620
- return {
12621
- path: outputPath,
12622
- sizeBytes: info.size,
12623
- cleanup: () => promises.rm(tempDirectory, { recursive: true, force: true }),
12624
- };
12625
- } catch (error) {
12626
- await promises.rm(tempDirectory, { recursive: true, force: true });
12627
- if (error instanceof CliError) {
12628
- throw error;
12629
- }
12630
- throw new CliError(
12631
- `Unable to package local source: ${error instanceof Error ? error.message : String(error)}`,
12632
- 'SOURCE_PACKAGE_FAILED',
12633
- );
12634
- }
12635
- };
12636
-
12637
- const UPLOAD_SESSION_FILENAME = '.coze-deploy-upload.json';
12638
-
12639
-
12640
-
12641
-
12642
-
12643
-
12644
-
12645
-
12646
-
12647
-
12648
-
12649
- const isUploadSession = (value) => {
12650
- if (!value || typeof value !== 'object') {
12651
- return false;
12652
- }
12653
- const session = value ;
12654
- return typeof session.idempotencyKey === 'string' &&
12655
- typeof session.createdAt === 'number' &&
12656
- typeof session.sourcePackageSizeBytes === 'number' &&
12657
- Boolean(session.request && typeof session.request === 'object');
12658
- };
12659
-
12660
- const readUploadSession = async (sourceRoot) => {
12661
- try {
12662
- const parsed = safeJsonParse(
12663
- await promises.readFile(node_path.join(sourceRoot, UPLOAD_SESSION_FILENAME), 'utf8'),
12664
- undefined,
12665
- );
12666
- return isUploadSession(parsed) ? parsed : undefined;
12667
- } catch (error) {
12668
- if ((error ).code === 'ENOENT') {
12669
- return undefined;
12670
- }
12671
- throw error;
12672
- }
12673
- };
12674
-
12675
- const writeUploadSession = async (sourceRoot, session) => {
12676
- const path = node_path.join(sourceRoot, UPLOAD_SESSION_FILENAME);
12677
- const tempPath = node_path.join(node_path.dirname(path), `.coze-deploy-upload-${node_crypto.randomUUID()}.tmp`);
12678
- await promises.mkdir(node_path.dirname(path), { recursive: true });
12679
- try {
12680
- await promises.writeFile(tempPath, `${JSON.stringify(session, null, 2)}\n`, { encoding: 'utf8', mode: 0o600 });
12681
- await promises.rename(tempPath, path);
12682
- } finally {
12683
- await promises.rm(tempPath, { force: true });
12684
- }
12685
- };
12686
-
12687
- const removeUploadSession = async (sourceRoot) => {
12688
- await promises.rm(node_path.join(sourceRoot, UPLOAD_SESSION_FILENAME), { force: true });
12689
- };
12690
-
12691
- function _optionalChain$1(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = fn(value); } else if (op === 'call' || op === 'optionalCall') { value = fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; }
12692
- const INLINE_SOURCE_PACKAGE_MAX_BYTES = 1024 * 1024;
12693
- const PRE_DEPLOY_SESSION_TTL_MS = 2 * 60 * 60 * 1000;
12694
-
12695
- const uploadFile = async (
12696
- uploadUrl,
12697
- requiredHeaders,
12698
- archive,
12699
- ) => {
12700
- const uploadRequest = {
12701
- method: 'PUT',
12702
- headers: requiredHeaders,
12703
- body: node_stream.Readable.toWeb(node_fs.createReadStream(archive.path)) ,
12704
- duplex: 'half',
12705
- };
12706
- const response = await fetch(uploadUrl, uploadRequest);
12707
- if (!response.ok) {
12708
- throw new CliError(`Direct artifact upload failed: ${response.status} ${response.statusText}`, 'ARTIFACT_UPLOAD_FAILED');
12709
- }
12710
- };
12711
-
12712
- const createDeploymentWithSourcePackage = async (
12713
- client,
12714
- request,
12715
- archive,
12716
- sourceRoot,
12717
- ) => {
12718
- if (archive.sizeBytes <= INLINE_SOURCE_PACKAGE_MAX_BYTES) {
12719
- const content = await promises.readFile(archive.path);
12720
- return {
12721
- uploadMode: 'inline' ,
12722
- result: await client.createDeployHistory({ ...request, source_package_base64: content.toString('base64') }),
12723
- };
12724
- }
12725
-
12726
- const savedSession = await readUploadSession(sourceRoot);
12727
- let retryRequest = request;
12728
- let reconciledSession = savedSession;
12729
- if (_optionalChain$1([savedSession, 'optionalAccess', _ => _.appId]) && savedSession.deployHistoryId) {
12730
- const history = await client.getDeployHistory({
12731
- app_id: savedSession.appId,
12732
- deploy_history_id: savedSession.deployHistoryId,
12733
- });
12734
- switch (history.status) {
12735
- case DEPLOY_STATUS.preDeploy:
12736
- // The server is authoritative for the session lifetime. Reuse the
12737
- // original key even if the local two-hour clock is close to expiry;
12738
- // pre_upload will either refresh the URL or release an expired slot.
12739
- break;
12740
- case DEPLOY_STATUS.pending:
12741
- case DEPLOY_STATUS.running:
12742
- case DEPLOY_STATUS.interrupted:
12743
- case DEPLOY_STATUS.succeeded:
12744
- // The previous create request was accepted but its response may have
12745
- // been lost. Do not upload or create another deployment.
12746
- await removeUploadSession(sourceRoot);
12747
- return {
12748
- uploadMode: 'direct' ,
12749
- result: {
12750
- app_id: savedSession.appId,
12751
- deploy_history_id: savedSession.deployHistoryId,
12752
- status: history.status,
12753
- version: typeof history.version === 'number' ? history.version : undefined,
12754
- },
12755
- };
12756
- case DEPLOY_STATUS.failed:
12757
- case DEPLOY_STATUS.canceled:
12758
- // The reserved history can no longer be claimed. Start a new upload
12759
- // against the Application that pre_upload already created.
12760
- await removeUploadSession(sourceRoot);
12761
- reconciledSession = undefined;
12762
- retryRequest = {
12763
- ...request,
12764
- project_id: undefined,
12765
- app_id: savedSession.appId,
12766
- };
12767
- break;
12768
- default:
12769
- throw new CliError(
12770
- `Unable to reconcile pre-deploy history ${savedSession.deployHistoryId}: unknown status ${String(history.status)}.`,
12771
- 'INVALID_RESPONSE',
12772
- );
12773
- }
12774
- }
12775
- const liveSavedSession = reconciledSession && (
12776
- reconciledSession.appId && reconciledSession.deployHistoryId ||
12777
- Date.now() - reconciledSession.createdAt < PRE_DEPLOY_SESSION_TTL_MS
12778
- )
12779
- ? reconciledSession
12780
- : undefined;
12781
- if (liveSavedSession && liveSavedSession.sourcePackageSizeBytes !== archive.sizeBytes) {
12782
- throw new CliError(
12783
- 'A different source package is waiting for upload. Cancel that deployment or wait for its two-hour session to expire.',
12784
- 'PRE_DEPLOY_SOURCE_CHANGED',
12785
- );
12786
- }
12787
- if (reconciledSession && !liveSavedSession) {
12788
- await removeUploadSession(sourceRoot);
12789
- }
12790
- const resumableSession = liveSavedSession;
12791
- const session = resumableSession || {
12792
- idempotencyKey: node_crypto.randomUUID(),
12793
- createdAt: Date.now(),
12794
- sourcePackageSizeBytes: archive.sizeBytes,
12795
- request: retryRequest,
12796
- };
12797
- // Persist before preDeployUpload: if the server creates PreDeploy but the response is lost,
12798
- // the next CLI run must reuse the same idempotency key.
12799
- await writeUploadSession(sourceRoot, session);
12800
- const preDeploy = await client.preDeployUpload({
12801
- ...session.request,
12802
- source_package_size_bytes: String(archive.sizeBytes),
12803
- idempotency_key: session.idempotencyKey,
12804
- });
12805
- await writeUploadSession(sourceRoot, {
12806
- ...session,
12807
- appId: preDeploy.app_id,
12808
- deployHistoryId: preDeploy.deploy_history_id,
12809
- uploadReceipt: preDeploy.upload_receipt,
12810
- });
12811
- await uploadFile(preDeploy.upload_url, preDeploy.required_headers || {}, archive);
12812
- const result = await client.createDeployHistory({
12813
- ...session.request,
12814
- project_id: undefined,
12815
- app_id: preDeploy.app_id,
12816
- pre_deploy_history_id: preDeploy.deploy_history_id,
12817
- upload_receipt: preDeploy.upload_receipt,
12818
- source_package_size_bytes: String(archive.sizeBytes),
12819
- });
12820
- await removeUploadSession(sourceRoot);
12821
- return { uploadMode: 'direct' , result };
12822
- };
12823
-
12824
- function _nullishCoalesce(lhs, rhsFn) { if (lhs != null) { return lhs; } else { return rhsFn(); } } function _optionalChain(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = fn(value); } else if (op === 'call' || op === 'optionalCall') { value = fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; }
12825
- const SUPPORTED_MINIPROGRAM_CONNECTOR_IDS = new Set(['10000127', '10000126']);
12826
- const collectConnectorId = (value, previous) => [
12827
- ...previous,
12828
- value,
12829
- ];
12830
-
12831
- const getConnectorConfigs = (connectorIds) =>
12832
- (connectorIds || []).map(connectorId => {
12833
- if (!SUPPORTED_MINIPROGRAM_CONNECTOR_IDS.has(connectorId)) {
12834
- throw new CliError(
12835
- `Unsupported connector ID ${connectorId}; expected 10000127 (WeChat) or 10000126 (Douyin).`,
12836
- 'INVALID_CONNECTOR_ID',
12837
- );
12838
- }
12839
- return { connector_id: connectorId };
12840
- });
12841
-
12842
- // Keep deployment option and output contracts together for auditing against the V2 IDL.
12843
- // eslint-disable-next-line @coze-arch/max-line-per-function -- keep V2 deployment contracts together
12844
- const registerDeploy = (code) => {
12845
- const deploy = code
12846
- .command('deploy')
12847
- .description('Deploy an application using deployment V2')
12848
- .option('--source-root <sourceRoot>', 'Local source root', '.')
12849
- .option('--project-id <projectId>', 'Project ID for the first deployment')
12850
- .option('--app-id <appId>', 'Application ID')
12851
- .option(
12852
- '--application-type <type>',
12853
- 'Deployment application type: service, pages, or mini_program',
12854
- )
12855
- .option('-n, --name <name>', 'Application name for the first deployment')
12856
- .option('--message <message>', 'Deployment message')
12857
- .option(
12858
- '--connector-id <connectorId>',
12859
- 'Mini-program channel: 10000127 (WeChat) or 10000126 (Douyin); repeatable',
12860
- collectConnectorId,
12861
- [],
12862
- )
12863
- .option('--wait', 'Wait for deployment completion')
12864
- .option('--yes', 'Confirm deployment')
12865
- // eslint-disable-next-line @coze-arch/max-line-per-function -- deployment orchestration is one auditable flow
12866
- .action(async (options, command) => {
12867
- const runtime = await getRuntime(command);
12868
- const sourceRoot = node_path.resolve(runtime.cwd, options.sourceRoot || '.');
12869
- const requestedApplicationType = parseApplicationType(options.applicationType);
12870
- runtime.output.debug(`[deploy] Reading local project: ${sourceRoot}`);
12871
- const localContext =
12872
- await readDeployLocalContext(
12873
- sourceRoot,
12874
- requestedApplicationType,
12875
- options.appId,
12876
- runtime.client,
12877
- );
12878
- const { commitHash, isPagesDeployment } = localContext;
12879
- let { metadata } = localContext;
12880
- const deploymentName = _nullishCoalesce(options.name, () => ( metadata.name));
12881
- let projectId = options.projectId || metadata.projectId;
12882
- let appId = options.appId || metadata.appId;
12883
- const appIdFromCoze = Boolean(metadata.appId && !options.appId);
12884
- let projectCreated = false;
12885
- let linkedApplicationType;
12886
- if (appId) {
12887
- const linkedApplication = await runtime.client.getApplication(appId);
12888
- linkedApplicationType = linkedApplication.application_type;
12889
- const linkedProjectId = linkedApplication.project_id;
12890
- if (!options.appId && projectId && linkedProjectId && projectId !== linkedProjectId) {
12891
- throw new CliError(
12892
- `Project ${projectId} does not own application ${appId}; it belongs to project ${linkedProjectId}.`,
12893
- 'PROJECT_ID_CONFLICT',
12894
- );
12895
- }
12896
- if (options.appId && linkedProjectId) {
12897
- projectId = linkedProjectId;
12898
- } else {
12899
- projectId ||= linkedProjectId;
12900
- }
12901
- if (!projectId) {
12902
- throw new CliError(
12903
- `Application ${appId} did not return its associated project_id.`,
12904
- 'INVALID_RESPONSE',
12905
- );
12906
- }
12907
- const inferredApplicationType = linkedApplicationType === 'pages'
12908
- ? 'pages'
12909
- : inferApplicationTypeFromProjectType(metadata.projectType);
12910
- const targetApplicationType = requestedApplicationType || inferredApplicationType;
12911
- if (appIdFromCoze && targetApplicationType && linkedApplicationType !== targetApplicationType) {
12912
- runtime.output.warn(
12913
- `The linked application ${appId} is ${linkedApplicationType}, but ${targetApplicationType} is required. A new application will be created and written to .coze.`,
12914
- );
12915
- appId = undefined;
12916
- }
12917
- }
12918
- if (!projectId) {
12919
- runtime.output.debug('[deploy] Creating a dedicated deployment project...');
12920
- const spaceId = await resolveDeploymentSpaceId(runtime);
12921
- const project = await runtime.client.createDeploymentProject({
12922
- space_id: spaceId,
12923
- user_query: deploymentName || 'CLI deployment project',
12924
- project_type: resolveCreationProjectType(metadata.projectType),
12925
- create_source: 'cli',
12926
- project_settings: { project_symbol: 'v3.5' },
12927
- });
12928
- projectId = project.project_id;
12929
- projectCreated = true;
12930
- }
12931
- if (metadata.projectId !== projectId) {
12932
- metadata = await writeProjectBinding(sourceRoot, { projectId });
12933
- }
12934
- runtime.output.debug(`[deploy] Using project ${projectId} from ${projectCreated ? 'new project' : options.projectId ? '--project-id' : appId ? 'application binding' : '.coze'}`);
12935
- const cozeFileContent = metadata.cozeFileContent;
12936
- runtime.output.debug('[deploy] Loading deployment configuration...');
12937
- const serverConfig = await runtime.client.getDeployConfig({
12938
- ...(appId ? { app_id: appId } : { project_id: projectId }),
12939
- commit_hash: commitHash,
12940
- ...(isPagesDeployment ? { application_type: 'pages' } : {}),
12941
- ...(cozeFileContent ? { coze_file_content: cozeFileContent } : {}),
12942
- });
12943
- const config = withRequestedApplicationType(
12944
- serverConfig,
12945
- requestedApplicationType,
12946
- Boolean(appId),
12947
- );
12948
- const applicationType = config.application_type;
12949
- const connectorConfigs = getConnectorConfigs(options.connectorId);
12950
- if (!options.yes) {
12951
- runtime.output.debug('[deploy] Preflight complete; confirmation is required.');
12952
- runtime.output.print({
12953
- confirmation_required: true,
12954
- app_id: appId,
12955
- project_id: projectId,
12956
- application_type: applicationType,
12957
- commit_hash: commitHash,
12958
- source_root: sourceRoot,
12959
- deploy_config: config.deploy_config,
12960
- current_version: config.current_version,
12961
- next_version: config.next_version,
12962
- risks: config.risk_list || [],
12963
- ...(!appId && deploymentName ? { name: deploymentName } : {}),
12964
- message: options.message,
12965
- lane: runtime.globalOptions.lane || runtime.config.xTTEnv,
12966
- });
12967
- return;
12968
- }
12969
- let encryptEnvVariable;
12970
- if (applicationType !== 'pages') {
12971
- runtime.output.debug('[deploy] Loading and encrypting online environment variables...');
12972
- const onlineEnvironment = appId
12973
- ? await runtime.client.getOnlineEnvironment(appId)
12974
- : undefined;
12975
- if (onlineEnvironment && onlineEnvironment.snapshot_status >= 3) {
12976
- throw new CliError(
12977
- onlineEnvironment.status_message ||
12978
- 'The current online environment snapshot is unavailable.',
12979
- 'ONLINE_ENVIRONMENT_UNAVAILABLE',
12980
- );
12981
- }
12982
- const envSecrets = (_optionalChain([onlineEnvironment, 'optionalAccess', _ => _.variables]) || [])
12983
- .filter(variable => variable.source === 'user')
12984
- .map(variable => ({
12985
- secret_id: '',
12986
- secret_key: variable.key,
12987
- secret_val: variable.value,
12988
- secret_type: 'user_custom' ,
12989
- }));
12990
- const encrypted = await runtime.client.encryptProjectSecret(projectId, envSecrets);
12991
- encryptEnvVariable = encrypted.sealed_secrets;
12992
- if (!encryptEnvVariable) {
12993
- throw new CliError(
12994
- 'The project secret encryption API returned no sealed_secrets.',
12995
- 'INVALID_RESPONSE',
12996
- );
12997
- }
12998
- }
12999
- runtime.output.debug(
13000
- `[deploy] Building and packaging ${applicationType} artifact...`,
13001
- );
13002
- const sourcePackage = await createSourcePackageArchive(
13003
- sourceRoot,
13004
- applicationType,
13005
- runtime.globalOptions.debug,
13006
- );
13007
- runtime.output.debug(
13008
- `[deploy] Package ready: ${String(sourcePackage.sizeBytes)} bytes`,
13009
- );
13010
- runtime.output.debug('[deploy] Uploading package and creating deployment...');
13011
- const deploymentRequest = {
13012
- ...(appId ? { app_id: appId } : { project_id: projectId }),
13013
- application_type: applicationType,
13014
- commit_hash: commitHash,
13015
- ...(!appId
13016
- ? { name: deploymentName, source_root: sourceRoot }
13017
- : {}),
13018
- is_sync_db_to_prod: false,
13019
- table_sync_configs: [],
13020
- connector_configs: connectorConfigs,
13021
- ...(cozeFileContent ? { coze_file_content: cozeFileContent } : {}),
13022
- ...(encryptEnvVariable
13023
- ? { encrypt_env_variable: encryptEnvVariable }
13024
- : {}),
13025
- ...getCreateDeployConfig(config),
13026
- };
13027
- let deployment;
13028
- try {
13029
- deployment = await createDeploymentWithSourcePackage(runtime.client, deploymentRequest, sourcePackage, sourceRoot);
13030
- } finally {
13031
- await sourcePackage.cleanup();
13032
- }
13033
- const { result } = deployment;
13034
- const deployHistoryId = resolveDeployHistoryId(
13035
- result.deploy_history_id,
13036
- result.prev_deploy_history_id,
13037
- );
13038
- if (!deployHistoryId) {
13039
- throw new CliError('Deployment response returned no deploy_history_id.', 'INVALID_RESPONSE');
13040
- }
13041
- if (metadata.appId !== result.app_id || metadata.projectId !== projectId) {
13042
- await writeProjectBinding(sourceRoot, {
13043
- projectId,
13044
- appId: result.app_id,
13045
- });
13046
- if (!appId) {
13047
- runtime.output.warn(`Created application ${result.app_id} and saved it to .coze.`);
13048
- }
13049
- }
13050
- if (options.wait) {
13051
- runtime.output.debug('[deploy] Deployment accepted; waiting for completion...');
13052
- } else {
13053
- runtime.output.debug('[deploy] Deployment accepted.');
13054
- }
13055
- const history = options.wait
13056
- ? await pollHistory(command, result.app_id, deployHistoryId)
13057
- : undefined;
13058
- runtime.output.print({
13059
- app_id: result.app_id,
13060
- deploy_history_id: deployHistoryId,
13061
- version: result.version,
13062
- commit_hash: commitHash,
13063
- status: getDeployStatusText(_nullishCoalesce(_optionalChain([history, 'optionalAccess', _2 => _2.status]), () => ( result.status))),
13064
- source_package_size_bytes: sourcePackage.sizeBytes,
13065
- upload_mode: deployment.uploadMode,
13066
- local_link: appId && !projectCreated ? 'unchanged' : 'written',
13067
- mobile_artifact_list: _optionalChain([history, 'optionalAccess', _3 => _3.mobile_artifact_list]) || [],
13068
- });
13069
- });
13070
-
13071
- registerDeployReadCommands(deploy);
13072
-
13073
- deploy
13074
- .command('cancel')
13075
- .requiredOption('--deploy-id <deployId>', 'Deployment history ID')
13076
- .option('--app-id <appId>', 'Application ID')
13077
- .option('--yes', 'Confirm cancellation')
13078
- .action(async (options, command) => {
13079
- const parentOptions = getDeployParentOptions(command);
13080
- if (!options.yes && !parentOptions.yes) {
13081
- throw new CliError('Pass --yes to cancel deployment.', 'CONFIRMATION_REQUIRED');
13082
- }
13083
- const runtime = await getRuntime(command);
13084
- const appId = await requireAppId(runtime.cwd, getDeployAppIdOption(options, command));
13085
- await runtime.client.cancelDeployHistory({
13086
- app_id: appId,
13087
- deploy_history_id: options.deployId || '',
13088
- });
13089
- runtime.output.print({ app_id: appId, canceled: true });
13090
- });
13091
-
13092
- deploy
13093
- .command('rollback')
13094
- .requiredOption('--deploy-id <deployId>', 'Target deployment history ID')
13095
- .option('--app-id <appId>', 'Application ID')
13096
- .option('--rollback-database', 'Rollback database')
13097
- .option('--yes', 'Confirm rollback')
13098
- .action(async (options, command) => {
13099
- const parentOptions = getDeployParentOptions(command);
13100
- if (!options.yes && !parentOptions.yes) {
13101
- throw new CliError('Pass --yes to rollback.', 'CONFIRMATION_REQUIRED');
13102
- }
13103
- const runtime = await getRuntime(command);
13104
- const appId = await requireAppId(runtime.cwd, getDeployAppIdOption(options, command));
13105
- const data = await runtime.client.rollbackDeployHistory({
13106
- app_id: appId,
13107
- target_deploy_history_id: options.deployId || '',
13108
- rollback_database: _nullishCoalesce(options.rollbackDatabase, () => ( false)),
13109
- });
13110
- runtime.output.print({ app_id: appId, ...data });
13111
- });
13112
-
13113
- // stop 不可逆(删函数 → Stopped,只能重新部署),pause 可逆(→ Paused,resume 能推回 Ready)。
13114
- const applicationActions = {
13115
- stop: (client, appId) => client.stopApplication(appId),
13116
- resume: (client, appId) => client.resumeApplication(appId),
13117
- pause: (client, appId) => client.pauseApplication(appId),
13118
- } ;
13119
-
13120
- for (const action of Object.keys(applicationActions) ) {
13121
- deploy
13122
- .command(action)
13123
- .option('--app-id <appId>', 'Application ID')
13124
- .option('--yes', `Confirm ${action}`)
13125
- .action(async (options, command) => {
13126
- const parentOptions = getDeployParentOptions(command);
13127
- if (!options.yes && !parentOptions.yes) {
13128
- throw new CliError(`Pass --yes to ${action}.`, 'CONFIRMATION_REQUIRED');
13129
- }
13130
- const runtime = await getRuntime(command);
13131
- const appId = await requireAppId(runtime.cwd, getDeployAppIdOption(options, command));
13132
- await applicationActions[action](runtime.client, appId);
13133
- runtime.output.print({ app_id: appId, action, success: true });
13134
- });
13135
- }
13136
-
13137
- deploy
13138
- .command('logs')
13139
- .option('--app-id <appId>', 'Application ID')
13140
- .option('--start-time <startTime>', 'Start time in milliseconds')
13141
- .option('--end-time <endTime>', 'End time in milliseconds')
13142
- .option('--limit <limit>', 'Page size')
13143
- .option('--cursor <cursor>', 'Pagination cursor')
13144
- .option('--query <query>', 'Log keyword')
13145
- .option('--level <level>', 'all, info, warn, or error')
13146
- .action(async (options, command) => {
13147
- const runtime = await getRuntime(command);
13148
- const appId = await requireAppId(runtime.cwd, getDeployAppIdOption(options, command));
13149
- runtime.output.print(
13150
- await runtime.client.searchRuntimeLog({
13151
- app_id: appId,
13152
- start_time: options.startTime,
13153
- end_time: options.endTime,
13154
- limit: options.limit,
13155
- cursor: options.cursor,
13156
- query: options.query,
13157
- level: options.level,
13158
- }),
13159
- );
13160
- });
13161
-
13162
- deploy
13163
- .command('build-log')
13164
- .requiredOption('--deploy-id <deployId>', 'Deployment history ID')
13165
- .option('--key <key>', 'Deployment log key; inferred when the deployment has one log')
13166
- .option('--app-id <appId>', 'Application ID')
13167
- .action(async (options, command) => {
13168
- const runtime = await getRuntime(command);
13169
- const appId = await requireAppId(runtime.cwd, getDeployAppIdOption(options, command));
13170
- let key = _optionalChain([options, 'access', _4 => _4.key, 'optionalAccess', _5 => _5.trim, 'call', _6 => _6()]);
13171
- if (!key) {
13172
- const history = await runtime.client.getDeployHistory({
13173
- app_id: appId,
13174
- deploy_history_id: options.deployId || '',
13175
- });
13176
- const keys = getDeployLogKeys(history);
13177
- if (keys.length === 0) {
13178
- throw new CliError(
13179
- 'The deployment has no build log key yet. Retry after deployment stages start.',
13180
- 'BUILD_LOG_NOT_READY',
13181
- );
13182
- }
13183
- if (keys.length > 1) {
13184
- throw new CliError(
13185
- 'The deployment has multiple build logs. Pass --key using deploy status output.',
13186
- 'BUILD_LOG_KEY_REQUIRED',
13187
- { available_keys: keys },
13188
- );
13189
- }
13190
- key = keys[0];
13191
- }
13192
- if (!key) {
13193
- throw new CliError('Deployment log key is empty.', 'BUILD_LOG_NOT_READY');
13194
- }
13195
- runtime.output.print(
13196
- await runtime.client.getBuildLog({
13197
- app_id: appId,
13198
- deploy_history_id: options.deployId || '',
13199
- key,
13200
- }),
13201
- );
13202
- });
13203
-
13204
- deploy
13205
- .command('config')
13206
- .option('--app-id <appId>', 'Application ID')
13207
- .option('--commit-id <commitId>', 'Commit hash')
13208
- .action(async (options, command) => {
13209
- const runtime = await getRuntime(command);
13210
- const appId = await requireAppId(runtime.cwd, getDeployAppIdOption(options, command));
13211
- const application = await runtime.client.getApplication(appId);
13212
- const commitHash = options.commitId || _optionalChain([application, 'access', _7 => _7.latest_deployment, 'optionalAccess', _8 => _8.commit_hash]);
13213
- if (!commitHash) {
13214
- throw new CliError('No deployment commit is available.', 'DEPLOYMENT_NOT_FOUND');
13215
- }
13216
- const applicationType = application.application_type;
13217
- const cozeFileContent = applicationType === 'pages'
13218
- ? undefined
13219
- : (await readProjectMetadata(node_path.resolve(runtime.cwd))).cozeFileContent;
13220
- runtime.output.print(
13221
- await runtime.client.getDeployConfig({
13222
- app_id: appId,
13223
- commit_hash: commitHash,
13224
- ...(applicationType === 'pages' ? { application_type: 'pages' } : {}),
13225
- ...(cozeFileContent ? { coze_file_content: cozeFileContent } : {}),
13226
- }),
13227
- );
13228
- });
13229
- };
13230
-
13231
- const registerCommands = (program) => {
13232
- registerAuth(program);
13233
- registerContext(program);
13234
- registerDoctor(program);
13235
- const code = program.command('code').description('Deployment operations');
13236
- registerApp(code);
13237
- registerDeploy(code);
13238
- registerDomain(code);
13239
- registerEnv(code);
13240
- registerMiniProgram(code);
13241
- };
13242
-
13243
- const configureDeployCommand = (command) => {
13244
- markDeployCommand(command)
13245
- .description('Deploy and manage Coze applications')
13246
- .option('--format <format>', 'Output format: json or text', 'json')
13247
- .option('--config <path>', 'Shared Coze CLI config path')
13248
- .option('--org-id <id>', 'Override organization ID')
13249
- .option('--space-id <id>', 'Override space ID')
13250
- .option('--lane <name>', 'Route API requests to the specified PPE lane')
13251
- .option('--api-base-url <url>', 'Override API base URL')
13252
- .option('--debug', 'Print debug diagnostics')
13253
- .showHelpAfterError()
13254
- .exitOverride();
13255
- registerCommands(command);
13256
- return command;
13257
- };
13258
-
13259
- const registerCommand = (program) => {
13260
- configureDeployCommand(program.command('deploy'));
13261
- };
13262
-
13263
- const readFormat = (argv) => {
13264
- const index = argv.indexOf('--format');
13265
- return index >= 0 && argv[index + 1] === 'text' ? 'text' : 'json';
13266
- };
13267
-
13268
- const handleDeployError = (error, argv = process.argv) => {
13269
- if (
13270
- error instanceof commander.CommanderError &&
13271
- ['commander.helpDisplayed', 'commander.version'].includes(error.code)
13272
- ) {
13273
- return;
13274
- }
13275
- const output = new Output(readFormat(argv), argv.includes('--debug'));
13276
- output.print({ error: toErrorPayload(error) });
13277
- process.exitCode = error instanceof commander.CommanderError ? 4 : 1;
13278
- };
13279
-
13280
- const commands = [
13281
- registerCommand$1,
13282
- registerCommand$4,
13283
- registerCommand$7,
13284
- registerCommand$5,
13285
- registerCommand$6,
13286
- registerCommand$3,
13287
- registerCommand$2,
13288
- registerCommand,
13289
- ];
13290
-
13291
- const main = async () => {
13292
- // 初始化 Slardar 监控
13293
- initSlardar();
13294
-
13295
- // 监听未捕获的异常
13296
- process.on('uncaughtException', async (error) => {
13297
- reportError(error, {
13298
- type: 'uncaughtException',
13299
- context: 'global',
13300
- });
13301
- await flushSlardar();
13302
- process.exit(1);
13303
- });
13304
-
13305
- // 监听未处理的 Promise rejection
13306
- process.on('unhandledRejection', async (reason) => {
13307
- const error = reason instanceof Error ? reason : new Error(String(reason));
13308
- reportError(error, {
13309
- type: 'unhandledRejection',
13310
- context: 'global',
13311
- });
13312
- await flushSlardar();
13313
- process.exit(1);
13314
- });
13315
-
13316
- const program = new commander.Command();
13317
-
13318
- program
13319
- .name('coze-dev')
13320
- .description(
13321
- 'Coze Coding CLI - Project template engine for frontend stacks',
13322
- )
13323
- .version(packageJson.version);
13324
-
13325
- commands.forEach(initCmd => initCmd(program));
13326
-
13327
- // 在 help 输出中添加模板信息
13328
- program.addHelpText('after', generateTemplatesHelpText());
10365
+ // 在 help 输出中添加模板信息
10366
+ program.addHelpText('after', generateTemplatesHelpText());
13329
10367
 
13330
10368
  // 使用 parseAsync 等待命令执行完成
13331
- try {
13332
- await program.parseAsync(process.argv);
13333
- } catch (error) {
13334
- if (process.argv[2] === 'deploy') {
13335
- handleDeployError(error);
13336
- } else {
13337
- throw error;
13338
- }
13339
- }
10369
+ await program.parseAsync(process.argv);
13340
10370
 
13341
10371
  // 统一在命令执行完成后 flush
13342
10372
  // 注意:如果命令中调用了 process.exit(),不会执行到这里