create-clis 1.0.0 → 1.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (88) hide show
  1. package/README.md +22 -14
  2. package/README.zh-CN.md +22 -14
  3. package/assets/manifest.json +7 -2
  4. package/assets/template/.github/ISSUE_TEMPLATE/bug_report.yml +15 -29
  5. package/assets/template/.github/ISSUE_TEMPLATE/feature_request.yml +6 -12
  6. package/assets/template/.github/PULL_REQUEST_TEMPLATE.md +3 -3
  7. package/assets/template/.github/workflows/ci.yml +69 -7
  8. package/assets/template/.github/workflows/release.yml +23 -23
  9. package/assets/template/.gitignorerc.json +1 -8
  10. package/assets/template/.oxlintrc.json +1 -6
  11. package/assets/template/.prettierignore +0 -1
  12. package/assets/template/.releaserc.json +6 -1
  13. package/assets/template/.vscode/launch.json +1 -1
  14. package/assets/template/.vscode/settings.json +1 -0
  15. package/assets/template/.vscode/tasks.json +45 -0
  16. package/assets/template/AGENTS.md +4 -4
  17. package/assets/template/CONTRIBUTING.md +6 -4
  18. package/assets/template/CONTRIBUTING.zh-CN.md +6 -4
  19. package/assets/template/_gitignore +7 -405
  20. package/assets/template/bunfig.toml +2 -11
  21. package/assets/template/docs/README.md +6 -6
  22. package/assets/template/docs/adrs/README.md +4 -2
  23. package/assets/template/docs/development.md +15 -9
  24. package/assets/template/lefthook.yml +20 -30
  25. package/assets/template/package.json +5 -6
  26. package/assets/template/packages/{{NAME}}/README.md +4 -4
  27. package/assets/template/packages/{{NAME}}/README.zh-CN.md +2 -2
  28. package/assets/template/packages/{{NAME}}/package.json +3 -1
  29. package/assets/template/packages/{{NAME}}/scripts/build.ts +50 -14
  30. package/assets/template/packages/{{NAME}}/scripts/verify-release.test.ts +140 -15
  31. package/assets/template/packages/{{NAME}}/scripts/verify-release.ts +27 -14
  32. package/assets/template/packages/{{NAME}}/tsconfig.build.json +1 -1
  33. package/assets/template/packages/{{NAME}}-cli/README.md +9 -6
  34. package/assets/template/packages/{{NAME}}-cli/README.zh-CN.md +6 -3
  35. package/assets/template/packages/{{NAME}}-cli/bin/bunfig.toml +3 -0
  36. package/assets/template/packages/{{NAME}}-cli/bin/{{BIN_NAME}} +43 -21
  37. package/assets/template/packages/{{NAME}}-cli/bin/{{BIN_NAME}}.cmd +8 -17
  38. package/assets/template/packages/{{NAME}}-cli/bin/{{BIN_NAME}}.d.mts +6 -3
  39. package/assets/template/packages/{{NAME}}-cli/bin/{{BIN_NAME}}.mjs +189 -107
  40. package/assets/template/packages/{{NAME}}-cli/package.json +3 -2
  41. package/assets/template/packages/{{NAME}}-cli/scripts/release-artifact.ts +24 -73
  42. package/assets/template/packages/{{NAME}}-cli/scripts/release.fixtures.ts +8 -3
  43. package/assets/template/packages/{{NAME}}-cli/scripts/verify-release.test.ts +16 -10
  44. package/assets/template/packages/{{NAME}}-cli/scripts/verify-release.ts +8 -52
  45. package/assets/template/packages/{{NAME}}-cli/scripts/write-dist-manifest.test.ts +3 -3
  46. package/assets/template/packages/{{NAME}}-cli/scripts/write-dist-manifest.ts +8 -68
  47. package/assets/template/packages/{{NAME}}-cli/src/cli.ts +51 -11
  48. package/assets/template/scripts/ci.ts +285 -64
  49. package/assets/template/scripts/install-git-hooks.mjs +10 -0
  50. package/assets/template/scripts/install-git-hooks.test.ts +1 -1
  51. package/assets/template/scripts/lib/npm-trust-parse.ts +169 -0
  52. package/assets/template/scripts/lib/release-cli.ts +299 -0
  53. package/assets/template/scripts/lib/release-verify.ts +148 -15
  54. package/assets/template/scripts/lib/workspace.test.ts +63 -1
  55. package/assets/template/scripts/lib/workspace.ts +132 -42
  56. package/assets/template/scripts/lint-dependency-direction.test.ts +131 -0
  57. package/assets/template/scripts/lint-dependency-direction.ts +130 -0
  58. package/assets/template/scripts/lint-doc-examples.test.ts +45 -9
  59. package/assets/template/scripts/lint-doc-examples.ts +227 -50
  60. package/assets/template/scripts/lint-doc-references.test.ts +36 -0
  61. package/assets/template/scripts/lint-doc-references.ts +142 -57
  62. package/assets/template/scripts/lint-doc-shared.ts +26 -23
  63. package/assets/template/scripts/lint-stray-backups.test.ts +3 -1
  64. package/assets/template/scripts/lint-stray-backups.ts +7 -3
  65. package/assets/template/scripts/npm-trust-guard.test.ts +56 -8
  66. package/assets/template/scripts/npm-trust-guard.ts +116 -200
  67. package/assets/template/scripts/safe-install.ts +28 -23
  68. package/assets/template/scripts/transcription/api-harness.ts +28 -206
  69. package/assets/template/scripts/transcription/compare.test.ts +84 -0
  70. package/assets/template/scripts/transcription/compare.ts +4 -4
  71. package/assets/template/scripts/transcription/corpus.ts +9 -3
  72. package/assets/template/scripts/transcription/fixture.ts +2 -4
  73. package/assets/template/scripts/transcription/make-mutants.ts +116 -37
  74. package/assets/template/scripts/transcription/run-conformance.ts +57 -34
  75. package/assets/template/scripts/transcription/validate-coverage.test.ts +11 -14
  76. package/assets/template/scripts/transcription/validate-coverage.ts +8 -10
  77. package/assets/template/scripts/transcription/validate.ts +18 -3
  78. package/assets/template/tsconfig.json +2 -20
  79. package/assets/template/turbo.jsonc +7 -52
  80. package/bin/bunfig.toml +3 -0
  81. package/bin/create-clis.mjs +165 -104
  82. package/dist/create-clis.js +48 -87681
  83. package/dist/manifest.json +3 -3
  84. package/package.json +9 -5
  85. package/assets/template/packages/{{NAME}}/docs/README.md +0 -21
  86. package/assets/template/packages/{{NAME}}-cli/docs/README.md +0 -21
  87. package/bin/create-clis +0 -35
  88. package/bin/create-clis.cmd +0 -32
@@ -1,60 +1,15 @@
1
1
  {
2
- // 用 .jsonc 而非 .json: 缓存键的输入面需要就地注释说明口径 (turbo 官方支持的注释载体, 见
3
- // https://turborepo.dev/docs/reference/configuration 「Use turbo.jsonc to add comments」)。
4
2
  "$schema": "https://turbo.build/schema.json",
5
3
  "tasks": {
6
4
  "build": {
7
5
  "dependsOn": ["^build"],
8
- "outputs": ["dist/**", "assets/**"],
9
- // 缓存键输入面: 生成器包 (create-clis) 的构建会从仓库根读骨架源来产出模板资产, 而 turbo
10
- // 默认只把「包目录内」的文件算进缓存键, 根级文件的改动不进键; 曾实测出双向事故: 改根级
11
- // 骨架源命中缓存不重算 (陈旧资产被当最新), 以及根构建把缓存里的旧资产还原回磁盘、覆盖掉
12
- // 刚修好的版本。故显式补根级输入面, 范围取「宁大勿漏」。
13
- // 口径: $TURBO_DEFAULT$ 保住包目录默认面 (含 .gitignore 语义; 显式写 inputs 会丢掉默认面,
14
- // 官方文档明示); 其余条目是模板构建会读的根级源, 与 .gitignore 无关的保守超集。
15
- // 注意: 显式 glob 不再享 .gitignore 过滤, 所以对 packages/ 这类会落构建产物的目录必须显式
16
- // 排除 (dist / .turbo / node_modules / assets), 否则产物进缓存键, 每次构建自我失效、缓存恒
17
- // 不命中, 或根级源变更后凭空多一轮重算。assets 只排除生成器包自己那份 (那是本任务的构建
18
- // 产物); 不写成通用的 `packages/**/assets/**`, 防将来某包把真源放 assets 被误排除在外。
19
- // 同步义务: 骨架清单的唯一权威是 packages/create-clis/scripts/template-manifest.ts; 新增
20
- // 根级骨架源时先登记那份清单, 再照本条补一条 glob, 两处不互为来源。
21
- "inputs": [
22
- "$TURBO_DEFAULT$",
23
- "$TURBO_ROOT$/.editorconfig",
24
- "$TURBO_ROOT$/.gitattributes",
25
- "$TURBO_ROOT$/.gitignore",
26
- "$TURBO_ROOT$/.gitignorerc.json",
27
- "$TURBO_ROOT$/.mailmap",
28
- "$TURBO_ROOT$/.npmrc",
29
- "$TURBO_ROOT$/.nvmrc",
30
- "$TURBO_ROOT$/.oxlintrc.json",
31
- "$TURBO_ROOT$/.prettierignore",
32
- "$TURBO_ROOT$/.prettierrc",
33
- "$TURBO_ROOT$/.releaserc.json",
34
- "$TURBO_ROOT$/.github/**",
35
- "$TURBO_ROOT$/.vscode/**",
36
- "$TURBO_ROOT$/AGENTS.md",
37
- "$TURBO_ROOT$/CODE_OF_CONDUCT.md",
38
- "$TURBO_ROOT$/CONTRIBUTING.md",
39
- "$TURBO_ROOT$/CONTRIBUTING.zh-CN.md",
40
- "$TURBO_ROOT$/LICENSE",
41
- "$TURBO_ROOT$/README.md",
42
- "$TURBO_ROOT$/README.zh-CN.md",
43
- "$TURBO_ROOT$/SECURITY.md",
44
- "$TURBO_ROOT$/bunfig.toml",
45
- "$TURBO_ROOT$/docs/**",
46
- "$TURBO_ROOT$/lefthook.yml",
47
- "$TURBO_ROOT$/package.json",
48
- "$TURBO_ROOT$/packages/**",
49
- "!$TURBO_ROOT$/packages/**/dist/**",
50
- "!$TURBO_ROOT$/packages/**/.turbo/**",
51
- "!$TURBO_ROOT$/packages/**/node_modules/**",
52
- "!$TURBO_ROOT$/packages/create-clis/assets/**",
53
- "$TURBO_ROOT$/scripts/**",
54
- "$TURBO_ROOT$/tsconfig.json",
55
- ],
6
+ "outputs": ["dist/**"],
7
+ },
8
+ "typecheck": {
9
+ "dependsOn": ["^build"],
10
+ },
11
+ "test": {
12
+ "dependsOn": ["^build"],
56
13
  },
57
- "typecheck": {},
58
- "test": {},
59
14
  },
60
15
  }
@@ -0,0 +1,3 @@
1
+ # CLI 启动器隔离配置: 禁止自动加载当前工作目录的 bunfig.toml (防 preload 劫持与坏配置崩溃) 与 .env
2
+ preload = []
3
+ env = false
@@ -1,95 +1,81 @@
1
1
  #!/usr/bin/env node
2
2
  /**
3
- * npm 安装场景的启动器: 挑选运行时 (Bun 优先, 其次 Node) 后启动真实入口。
4
- * 与 bin/create-clis (sh) / bin/create-clis.cmd (cmd) 职责同逻辑 (挑选运行时: Bun 优先, Node
5
- * 回退), 差异在本文件是 npm 的 bin 目标: 本文件同时承担 Unix 与 Windows 的 npm shim 目标
6
- * (shebang 必须是 node, 否则 npm 的 cmd-shim 会按 shebang 解释器生成 Windows 上不存在的调用)。
3
+ * npm 安装场景的启动器: 挑选运行时 (Bun 优先, 其次 Node >= 22.18.0) 后启动真实入口 (只认构建产物)。
7
4
  *
8
- * 只认产物 (与既有 CLI 包启动器的一处刻意差异): 生成器无源码回退: 入口恒为
9
- * dist/create-clis.js, 产物缺失即报错退出。生成器随包发售的是产物 + 模板资产 (assets/),
10
- * 二者缺一不可; 「开发态回退直跑 src/cli.ts」会把发行面缺陷藏起来 (源码在包内并不存在),
11
- * 仓库开发态请先跑构建 (bun run build)。
12
- *
13
- * 运行时解析防劫持 (与 @iyowei/sweep-node-modules-cli 启动器同款处理): Windows 上裸名执行会
14
- * 先搜当前工作目录 (CreateProcessW 的搜索序里「parent 的当前目录」居第 2 位; 本文件走的 Node
15
- * spawn 亦然: libuv 的 search_path 以 NeedCurrentDirectoryForExePathW 门控先试 cwd 再扫
16
- * PATH), 而生成器的调用现场恰是「在用户自己的目录里跑」, 目录内放一个同名 bun.exe / bun.com
17
- * 即可顶替真实运行时进入执行链。故 win32 下先按 PATH 解析出绝对路径 (空条目与相对条目都会把
18
- * 解析引回当前目录, 一并跳过) 再探测与执行, 解析面与执行面都不再触发任何搜索序; POSIX 侧同法
19
- * 收紧 (空与相对条目在 POSIX 下同样意为当前目录), 并保持 execvp「首候选不可执行时继续搜索」的
20
- * 语义 (逐候选探测)。该逻辑与 sweep-nm 启动器逐行同源, 三个函数带可注入接缝导出 (platform /
21
- * pathEnv / fileProbe / probe), 由 scripts/launcher.runtime-resolution.test.mjs 注入复现;
22
- * 测试写成 .mjs 而非 .ts: 被测对象是纯 JS 分发入口 (node 直跑, 不进 tsc 编译面), 用 .ts 就得给
23
- * bin/ 配类型投影 (bin/create-clis.d.mts), 而 files 白名单整目录收 bin/, 投影会多出一份发行面
24
- * 文件 (白名单契约是 bin 三件)。
25
- *
26
- * 产物自证 (发行面 dist/create-clis.js 与源码和提交无身份绑定的运行时防线): 决定跑
27
- * dist/create-clis.js 之前必须与随附的 dist/manifest.json 对账 (形状版本受支持, 且清单记的
28
- * cliSha256 必须等于实测摘要), 清单缺失 / 损坏 / 版本不支持 / 摘要不符一律拒收产物并给出指引,
29
- * 不静默执行 (静默执行会把产物漂移藏起来)。工作树脏净不进本判定 (开发态常脏), 那是发布闸门
30
- * scripts/verify-release.ts 的职责; 清单字段契约见 scripts/release-artifact.ts (包内无法
31
- * 跨语言复用该模块, 两边口径由 scripts/write-dist-manifest.test.ts 的钉住用例与两侧注释对齐)。
32
- *
33
- * 退出码原样透传; 两个运行时都缺席时给出可操作提示并非零退出。
5
+ * 安全与进程模型防线:
6
+ * 1. 运行时解析防劫持: win32 严格按盘符/UNC 绝对路径正则过滤 PATH (拦截 /usr/bin 盘根相对路径与 cwd 劫持),
7
+ * 返回全部候选数组逐一 probe; POSIX 仅按 `/` 开头绝对 PATH 解析;
8
+ * 2. Bun 工作目录配置隔离: 选中 Bun 时强制附加 --config=<pkg>/bin/bunfig.toml 与
9
+ * --no-env-file (缺失隔离配置即拒绝); 经壳启动器透传 CLIS_BUN_ISOLATED=1 且当前已是 Bun 时同进程 import;
10
+ * 3. 纯 Node 同进程零套娃: 无可用 Bun 且当前 Node >= 22.18.0 时直接同进程 import, 跨运行时切换时异步 spawn
11
+ * 并隔离父进程 SIGINT 防孤儿进程, 信号终止按 POSIX 语义自杀回传;
12
+ * 4. 产物自证: 执行 dist/create-clis.js 前必先与 dist/manifest.json 校验 SHA-256。
34
13
  */
35
- import { spawnSync } from 'node:child_process';
14
+ import { spawn, spawnSync } from 'node:child_process';
36
15
  import { createHash } from 'node:crypto';
37
16
  import { existsSync, readFileSync, realpathSync, statSync } from 'node:fs';
38
- import { dirname, join, posix, win32 } from 'node:path';
39
- import { fileURLToPath } from 'node:url';
17
+ import { basename, dirname, join, posix, win32 } from 'node:path';
18
+ import { fileURLToPath, pathToFileURL } from 'node:url';
40
19
 
41
- /** 产物与清单的文件名 (与 scripts/release-artifact.ts 的 CLI_FILE / MANIFEST_FILE 同值) */
42
20
  const CLI_FILE = 'create-clis.js';
43
21
  const MANIFEST_FILE = 'manifest.json';
44
-
45
- /**
46
- * win32 的候选可执行扩展名, 顺序与 Node 实际走的 libuv 搜索一致 (.com 先于 .exe)。
47
- * 不展开 PATHEXT: .bat / .cmd 无法被 Node 无 shell 直接执行, 展开只会把不可执行的命中当成功;
48
- * 保持该面与 libuv 等价也意味着本次收紧不改动 win32 上「哪些安装形态能命中」的既有行为。
49
- */
50
22
  const WIN32_EXEC_EXTS = ['.com', '.exe'];
23
+ const WIN32_ABS_DIR_RE = /^(?:[A-Za-z]:[/\\]|\\\\[^\\]+\\[^\\]+)/;
24
+ const MIN_NODE_MAJOR = 22;
25
+ const MIN_NODE_MINOR = 18;
51
26
 
52
- /** 探测命令是否可执行 (以 --version 的实际退出码为准, 不依赖 shell 内建) */
53
- const available = (command) =>
54
- spawnSync(command, ['--version'], { stdio: 'ignore' }).status === 0;
27
+ /** 校验 Node.js 版本是否满足 >= 22.18.0 下限 */
28
+ export const isSupportedNodeVersion = (rawVersion) => {
29
+ if (typeof rawVersion !== 'string') return false;
30
+ const match = /^v?(\d+)\.(\d+)/.exec(rawVersion.trim());
31
+ if (!match) return false;
32
+ const major = Number(match[1]);
33
+ const minor = Number(match[2]);
34
+ return (
35
+ major > MIN_NODE_MAJOR ||
36
+ (major === MIN_NODE_MAJOR && minor >= MIN_NODE_MINOR)
37
+ );
38
+ };
39
+
40
+ const isBunRuntime = (runtime) => {
41
+ const name = basename(runtime).toLowerCase();
42
+ return name === 'bun' || name === 'bun.exe' || name === 'bun.com';
43
+ };
44
+
45
+ const available = (command) => {
46
+ const res = spawnSync(command, ['--version'], {
47
+ encoding: 'utf8',
48
+ stdio: ['ignore', 'pipe', 'ignore'],
49
+ });
50
+ if (res.status !== 0) return false;
51
+ if (isBunRuntime(command)) return true;
52
+ return isSupportedNodeVersion(res.stdout);
53
+ };
55
54
 
56
- /** 路径处是否为普通文件 (探针读不到即 false, 不抛; 目录名撞上候选名时不得当选) */
57
- const isFileAt = (path) => {
55
+ const isFileAt = (filePath) => {
58
56
  try {
59
- return statSync(path).isFile();
57
+ return statSync(filePath).isFile();
60
58
  } catch {
61
59
  return false;
62
60
  }
63
61
  };
64
62
 
65
- /**
66
- * 在 PATH 中解析命令的绝对路径 (win32 语义), 找不到返回 null。
67
- * 只供 win32 分支调用: CreateProcessW 与 libuv 的裸名搜索序都会先搜当前目录, 本函数把
68
- * 「当前目录」从解析面整个摘掉: 空条目 (Windows 上表示当前目录) 与相对条目 (同样按当前
69
- * 目录解析) 一律跳过, 只认绝对目录; 条目两侧的引号按 libuv 同款剥掉 (Windows PATH 允许
70
- * 引号包裹含空格的目录)。注入 pathEnv / fileProbe 供测试在非 win32 宿主上覆盖本函数。
71
- */
72
- export const resolveWin32Executable = (name, pathEnv, fileProbe) => {
63
+ export const resolveWin32Executables = (name, pathEnv, fileProbe) => {
64
+ const found = [];
73
65
  for (const raw of pathEnv.split(';')) {
74
66
  const dir =
75
67
  raw.length > 1 && raw.startsWith('"') && raw.endsWith('"')
76
68
  ? raw.slice(1, -1)
77
69
  : raw;
78
- if (dir === '' || !win32.isAbsolute(dir)) continue;
70
+ if (dir === '' || !WIN32_ABS_DIR_RE.test(dir)) continue;
79
71
  for (const ext of WIN32_EXEC_EXTS) {
80
72
  const candidate = win32.join(dir, name + ext);
81
- if (fileProbe(candidate)) return candidate;
73
+ if (fileProbe(candidate)) found.push(candidate);
82
74
  }
83
75
  }
84
- return null;
76
+ return found;
85
77
  };
86
78
 
87
- /**
88
- * 在 PATH 中解析命令的全部候选绝对路径 (POSIX 语义, 保持 PATH 顺序), 跳过空条目与相对
89
- * 条目 (两者在 POSIX 下都按当前目录解析, 属本工具要摘掉的解析面; 与 win32 分支同一理由)。
90
- * 返回数组而非首命中: 同名文件可能不可执行, execvp 在该情形会继续搜索, 候选交由调用方逐个
91
- * 探测以保持同一语义。注入 pathEnv / fileProbe 供测试覆盖本函数。
92
- */
93
79
  export const resolvePosixExecutables = (name, pathEnv, fileProbe) => {
94
80
  const found = [];
95
81
  for (const dir of pathEnv.split(':')) {
@@ -100,36 +86,25 @@ export const resolvePosixExecutables = (name, pathEnv, fileProbe) => {
100
86
  return found;
101
87
  };
102
88
 
103
- /**
104
- * 挑选运行时: Bun 优先, 其次 Node; 皆无则 null (由调用处报错退出)。
105
- * 两个平台都先按 PATH 解析绝对路径再探测 (理由见文件头「运行时解析防劫持」): win32 取
106
- * 首个解析命中, POSIX 按 PATH 顺序逐个候选探测 (保持 execvp 的继续搜索语义)。
107
- * 各参数显式传入供测试注入, 生产调用不传。
108
- */
109
89
  export const pickRuntime = ({
110
90
  platform = process.platform,
111
- pathEnv = process.env.PATH ?? '',
91
+ pathEnv = process.env.PATH ?? process.env.Path ?? '',
112
92
  fileProbe = isFileAt,
113
93
  probe = available,
94
+ names = ['bun', 'node'],
114
95
  } = {}) => {
115
- for (const name of ['bun', 'node']) {
116
- if (platform === 'win32') {
117
- const resolved = resolveWin32Executable(name, pathEnv, fileProbe);
118
- if (resolved !== null && probe(resolved)) return resolved;
119
- continue;
120
- }
121
- for (const candidate of resolvePosixExecutables(name, pathEnv, fileProbe)) {
96
+ for (const name of names) {
97
+ const candidates =
98
+ platform === 'win32'
99
+ ? resolveWin32Executables(name, pathEnv, fileProbe)
100
+ : resolvePosixExecutables(name, pathEnv, fileProbe);
101
+ for (const candidate of candidates) {
122
102
  if (probe(candidate)) return candidate;
123
103
  }
124
104
  }
125
105
  return null;
126
106
  };
127
107
 
128
- /**
129
- * 产物自证: 核对 dist/create-clis.js 与 dist/manifest.json 的摘要是否同源。
130
- * 通过返回 null, 否则返回人话原因; 原因串全是本文件固定措辞, 不回显清单内容 (清单是外部
131
- * 文件, 其文本不受控, 不落进输出面)。
132
- */
133
108
  const artifactProblem = (distDir) => {
134
109
  const manifestPath = join(distDir, MANIFEST_FILE);
135
110
  if (!existsSync(manifestPath)) return `缺少产物清单 (dist/${MANIFEST_FILE})`;
@@ -139,8 +114,6 @@ const artifactProblem = (distDir) => {
139
114
  } catch {
140
115
  return `产物清单 (dist/${MANIFEST_FILE}) 损坏, 不是合法 JSON`;
141
116
  }
142
- // 形状版本先对: 异版本的字段语义无保证, 宁可拒收 (字面量 1 与 scripts/release-artifact.ts 的
143
- // MANIFEST_SCHEMA_VERSION 同值, 改动须两处同步; 启动器随包分发, 包内无法 import 该模块)
144
117
  if (manifest?.schemaVersion !== 1) {
145
118
  return `产物清单 (dist/${MANIFEST_FILE}) 的 schemaVersion 不是受支持的版本 (期望 1)`;
146
119
  }
@@ -156,34 +129,66 @@ const artifactProblem = (distDir) => {
156
129
  } catch {
157
130
  return `产物 (dist/${CLI_FILE}) 读不出来, 摘要算不出`;
158
131
  }
159
- if (recorded !== actual)
132
+ if (recorded !== actual) {
160
133
  return `产物 (dist/${CLI_FILE}) 的摘要与清单记录不符`;
134
+ }
161
135
  return null;
162
136
  };
163
137
 
164
- /**
165
- * 本文件是否作为入口被直接执行。
166
- * 经 realpath 比对而非字面路径: npm 在 Unix 上以符号链接 (或经 shim) 落 bin, 此时 argv[1] 是
167
- * 链接路径而 import.meta.url 是解析后的真实路径。main 守卫只为让「被 import 时不跑主流程」,
168
- * 判定失配的后果是入口静默不跑, 故除字面相等外只在 realpath 成功时采信。
169
- */
170
138
  const isEntry = () => {
171
139
  const entry = process.argv[1];
172
140
  if (typeof entry !== 'string' || entry === '') return false;
173
141
  const self = fileURLToPath(import.meta.url);
174
- if (entry === self) return true;
142
+ const norm = (value) =>
143
+ process.platform === 'win32' ? value.toLowerCase() : value;
144
+ if (norm(entry) === norm(self)) return true;
175
145
  try {
176
- return realpathSync(entry) === self;
146
+ const realpath = realpathSync.native ?? realpathSync;
147
+ const realSelf = realpath(self);
148
+ return norm(realpath(entry)) === norm(realSelf);
177
149
  } catch {
178
150
  return false;
179
151
  }
180
152
  };
181
153
 
182
- const main = () => {
154
+ /** 跨运行时异步派生并隔离父进程 SIGINT, 防止 Ctrl+C 先杀父进程留下孤儿进程 */
155
+ const runChild = (command, args, extraEnv) =>
156
+ new Promise((resolveExit) => {
157
+ const onSigint = () => {};
158
+ process.on('SIGINT', onSigint);
159
+ const child = spawn(command, args, {
160
+ stdio: 'inherit',
161
+ env: extraEnv ? { ...process.env, ...extraEnv } : process.env,
162
+ });
163
+ child.on('error', (error) => {
164
+ process.off('SIGINT', onSigint);
165
+ process.stderr.write(`create-clis: 启动运行时失败 (${error.message})\n`);
166
+ resolveExit({ status: 1, signal: null });
167
+ });
168
+ child.on('close', (code, signal) => {
169
+ process.off('SIGINT', onSigint);
170
+ resolveExit({ status: code, signal });
171
+ });
172
+ });
173
+
174
+ const finishChild = (result) => {
175
+ if (result.signal) {
176
+ try {
177
+ process.kill(process.pid, result.signal);
178
+ } catch {
179
+ process.exit(1);
180
+ }
181
+ return;
182
+ }
183
+ process.exit(result.status ?? 1);
184
+ };
185
+
186
+ const main = async () => {
183
187
  const root = dirname(dirname(fileURLToPath(import.meta.url)));
184
188
  const distDir = join(root, 'dist');
185
189
  const entry = join(distDir, CLI_FILE);
186
- // 生成器只认产物 (无源码回退): 产物缺失即拒, 退出码与「无运行时」同一档: 1
190
+ const isolatedBunfig = join(root, 'bin', 'bunfig.toml');
191
+
187
192
  if (!existsSync(entry)) {
188
193
  process.stderr.write(
189
194
  `create-clis: 缺少产物 (dist/${CLI_FILE} 不存在), 本入口只认构建产物, 无源码回退。\n` +
@@ -192,7 +197,6 @@ const main = () => {
192
197
  );
193
198
  process.exit(1);
194
199
  }
195
- // 有产物就得先自证 (与随附清单对账); 不通过即拒收
196
200
  const problem = artifactProblem(distDir);
197
201
  if (problem !== null) {
198
202
  process.stderr.write(
@@ -202,18 +206,75 @@ const main = () => {
202
206
  );
203
207
  process.exit(1);
204
208
  }
205
- const runtime = pickRuntime();
206
209
 
207
- if (runtime === null) {
208
- process.stderr.write('create-clis: 未找到 bun 或 node, 请至少安装其一\n');
210
+ const ensureIsolatedBunfig = () => {
211
+ if (existsSync(isolatedBunfig)) return;
212
+ process.stderr.write(
213
+ 'create-clis: 缺少启动器隔离配置 (bin/bunfig.toml), 为防工作目录 bunfig.toml 劫持已拒绝执行。\n',
214
+ );
209
215
  process.exit(1);
216
+ };
217
+
218
+ // 当前已是 Bun: 隔离态直接同进程 import, 非隔离态直接用 process.execPath 重派隔离态 Bun (不扫 PATH)
219
+ if (typeof process.versions.bun === 'string') {
220
+ ensureIsolatedBunfig();
221
+ if (process.env.CLIS_BUN_ISOLATED === '1') {
222
+ await import(pathToFileURL(entry).href);
223
+ return;
224
+ }
225
+ const result = await runChild(
226
+ process.execPath,
227
+ [
228
+ `--config=${isolatedBunfig}`,
229
+ '--no-env-file',
230
+ entry,
231
+ ...process.argv.slice(2),
232
+ ],
233
+ { CLIS_BUN_ISOLATED: '1' },
234
+ );
235
+ finishChild(result);
236
+ return;
210
237
  }
211
238
 
212
- const { status } = spawnSync(runtime, [entry, ...process.argv.slice(2)], {
213
- stdio: 'inherit',
214
- });
239
+ const bunRuntime = pickRuntime({ names: ['bun'] });
240
+ if (bunRuntime !== null) {
241
+ ensureIsolatedBunfig();
242
+ const result = await runChild(
243
+ bunRuntime,
244
+ [
245
+ `--config=${isolatedBunfig}`,
246
+ '--no-env-file',
247
+ entry,
248
+ ...process.argv.slice(2),
249
+ ],
250
+ { CLIS_BUN_ISOLATED: '1' },
251
+ );
252
+ finishChild(result);
253
+ return;
254
+ }
255
+
256
+ // 无 Bun 时: 若当前 Node 满足 >= 22.18.0 则同进程加载产物 (消除 3 进程套娃并保留原始 argv)
257
+ if (isSupportedNodeVersion(process.versions.node)) {
258
+ await import(pathToFileURL(entry).href);
259
+ return;
260
+ }
261
+
262
+ const nodeRuntime = pickRuntime({ names: ['node'] });
263
+ if (nodeRuntime !== null) {
264
+ const result = await runChild(nodeRuntime, [
265
+ entry,
266
+ ...process.argv.slice(2),
267
+ ]);
268
+ finishChild(result);
269
+ return;
270
+ }
215
271
 
216
- process.exit(status ?? 1);
272
+ process.stderr.write(
273
+ `create-clis: 未找到可用的 bun 或 node (>= ${MIN_NODE_MAJOR}.${MIN_NODE_MINOR}.0; 当前 node 为 ${process.versions.node ?? '未知'})\n`,
274
+ );
275
+ process.exit(1);
217
276
  };
218
277
 
219
- if (isEntry()) main();
278
+ if (isEntry()) {
279
+ await main();
280
+ }