create-clis 1.1.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.
|
@@ -4,32 +4,72 @@
|
|
|
4
4
|
* 生成后的项目应把它替换为自己的命令实现 (打包与发布自证见 package.json 与 scripts/)。
|
|
5
5
|
* 退出码: 0 成功; 值解析与命令分发按需要扩展。
|
|
6
6
|
*/
|
|
7
|
+
import { readFileSync } from 'node:fs';
|
|
8
|
+
|
|
7
9
|
import { greet } from '{{SCOPE}}/{{NAME}}';
|
|
8
10
|
|
|
9
11
|
const HELP_TEXT = [
|
|
10
12
|
'{{BIN_NAME}}: 示例命令行工具 (模板骨架)',
|
|
11
13
|
'',
|
|
12
|
-
'用法: {{BIN_NAME}} [--name <名字>] [--help]',
|
|
14
|
+
'用法: {{BIN_NAME}} [--name <名字>] [--version] [--help]',
|
|
13
15
|
'',
|
|
14
16
|
'选项:',
|
|
15
|
-
' --name <名字>
|
|
16
|
-
' --
|
|
17
|
+
' --name <名字> 要问候的名字 (缺省 world)',
|
|
18
|
+
' -V, --version 打印当前版本号',
|
|
19
|
+
' -h, --help 打印本帮助',
|
|
17
20
|
].join('\n');
|
|
18
21
|
|
|
19
|
-
/**
|
|
20
|
-
const
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
22
|
+
/** 读取当前 CLI 包版本号 (源码态 src/cli.ts 与打包态 dist/cli.js 同位于包根下一级) */
|
|
23
|
+
const readCliVersion = (): string => {
|
|
24
|
+
try {
|
|
25
|
+
const raw = readFileSync(
|
|
26
|
+
new URL('../package.json', import.meta.url),
|
|
27
|
+
'utf8',
|
|
28
|
+
);
|
|
29
|
+
const parsed = JSON.parse(raw) as { version?: unknown };
|
|
30
|
+
return typeof parsed.version === 'string' ? parsed.version : 'unknown';
|
|
31
|
+
} catch {
|
|
32
|
+
return 'unknown';
|
|
33
|
+
}
|
|
34
|
+
};
|
|
35
|
+
|
|
36
|
+
/** 解析最小示例参数: 支持 --version / -V、--help / -h 与 --name <名字> (演示最小解析, 替换时按需扩展) */
|
|
37
|
+
const parseArgs = (
|
|
38
|
+
argv: readonly string[],
|
|
39
|
+
): { help: boolean; version: boolean; who: string } => {
|
|
40
|
+
let help = false;
|
|
41
|
+
let version = false;
|
|
42
|
+
let who = 'world';
|
|
43
|
+
for (let i = 0; i < argv.length; i += 1) {
|
|
44
|
+
const arg = argv[i];
|
|
45
|
+
if (arg === '--') break;
|
|
46
|
+
if (arg === '--version' || arg === '-V') version = true;
|
|
47
|
+
else if (arg === '--help' || arg === '-h') help = true;
|
|
48
|
+
else if (arg === '--name') {
|
|
49
|
+
const next = argv[i + 1];
|
|
50
|
+
if (next !== undefined) {
|
|
51
|
+
who = next;
|
|
52
|
+
i += 1;
|
|
53
|
+
}
|
|
54
|
+
} else if (arg?.startsWith('--name=')) {
|
|
55
|
+
const value = arg.slice('--name='.length);
|
|
56
|
+
if (value.length > 0) who = value;
|
|
57
|
+
}
|
|
58
|
+
}
|
|
59
|
+
return { help, version, who };
|
|
24
60
|
};
|
|
25
61
|
|
|
26
62
|
const main = (): number => {
|
|
27
|
-
const
|
|
28
|
-
if (
|
|
63
|
+
const { help, version, who } = parseArgs(process.argv.slice(2));
|
|
64
|
+
if (version) {
|
|
65
|
+
process.stdout.write(`${readCliVersion()}\n`);
|
|
66
|
+
return 0;
|
|
67
|
+
}
|
|
68
|
+
if (help) {
|
|
29
69
|
process.stdout.write(`${HELP_TEXT}\n`);
|
|
30
70
|
return 0;
|
|
31
71
|
}
|
|
32
|
-
process.stdout.write(`${greet({ who
|
|
72
|
+
process.stdout.write(`${greet({ who })}\n`);
|
|
33
73
|
return 0;
|
|
34
74
|
};
|
|
35
75
|
|
package/dist/create-clis.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{existsSync as existsSync6}from"node:fs";import{resolve as resolve2}from"node:path";import{readFileSync as readFileSync4}from"node:fs";import{dirname,join as join2}from"node:path";import{fileURLToPath}from"node:url";import{existsSync,realpathSync}from"node:fs";import{posix,win32}from"node:path";var SUPPORTED_PACKAGE_MANAGERS=["bun","npm","pnpm","yarn","volta"],LIB_NODE_MODULES_HEURISTIC_REASON="命中标准 <prefix>/lib/node_modules 全局目录";function normalizeSlashes(path){return path.replaceAll("\\","/").replace(/\/+$/,"")}function joinForPath(base,...parts){return/^(?:[A-Za-z]:[/\\]|\\\\)/.test(base)||base.includes("\\")?win32.join(base,...parts):posix.join(base,...parts)}function foldPath(path){return normalizeSlashes(path).toLowerCase()}function isWithinDir(child,parent){let normParent=foldPath(parent);if(normParent==="")return!1;let normChild=foldPath(child);return normChild===normParent||normChild.startsWith(`${normParent}/`)}function collectRawFoldedCandidates(foldedRoot,rawPaths){let seen=new Set([foldedRoot]),out=[];for(let raw of rawPaths??[]){if(typeof raw!=="string"||raw.trim()==="")continue;let folded=foldPath(raw);if(!seen.has(folded))seen.add(folded),out.push(folded)}return out}function expandRootVariants(root,realpath){let trimmed=root.trim();if(trimmed==="")return[];let out=[trimmed],resolved=realpath(trimmed);if(foldPath(resolved)!==foldPath(trimmed))out.push(resolved);return out}function detectEphemeral(candidates,packageRoot){for(let p of candidates){if(p.includes("/_npx/"))return{kind:"ephemeral",runner:"npx",reason:"位于 npx 临时缓存目录 (_npx)",packageRoot};if(p.includes("/bunx-"))return{kind:"ephemeral",runner:"bunx",reason:"位于 bunx 临时执行目录",packageRoot};if(p.includes("/pnpm/dlx/")||p.includes("/pnpm-cache/dlx/")||p.includes("/pnpm-dlx/"))return{kind:"ephemeral",runner:"pnpm-dlx",reason:"位于 pnpm dlx 临时缓存目录",packageRoot};if(p.includes("/xfs-")&&p.includes("/dlx-")||p.includes("/berry/cache/")&&p.includes("/dlx"))return{kind:"ephemeral",runner:"yarn-dlx",reason:"位于 yarn dlx 临时执行目录",packageRoot};if(p.includes("/deno/npm/"))return{kind:"ephemeral",runner:"deno",reason:"位于 Deno npm 缓存目录 (/deno/npm/)",packageRoot}}return null}function buildEnvRootRules(env,realpath){let rules=[],directSpecs=[["volta",env.VOLTA_HOME,"位于环境变量 VOLTA_HOME 目录内"],["bun",env.BUN_INSTALL,"位于环境变量 BUN_INSTALL 目录内"],["bun",env.BUN_INSTALL_GLOBAL_DIR,"位于环境变量 BUN_INSTALL_GLOBAL_DIR 目录内"],["pnpm",env.PNPM_HOME,"位于环境变量 PNPM_HOME 目录内"]];for(let[pm,rawRoot,reason]of directSpecs){if(rawRoot===void 0||rawRoot.trim()==="")continue;let roots=expandRootVariants(rawRoot,realpath);if(roots.length>0)rules.push({pm,roots,reason})}let npmPrefix=env.NPM_CONFIG_PREFIX??env.npm_config_prefix;if(npmPrefix!==void 0&&npmPrefix.trim()!==""){let npmRoots=[];for(let base of expandRootVariants(npmPrefix,realpath)){let norm=normalizeSlashes(base);if(norm==="")continue;npmRoots.push(`${norm}/lib/node_modules`,`${norm}/node_modules`)}if(npmRoots.length>0)rules.push({pm:"npm",roots:npmRoots,reason:"位于环境变量 NPM_CONFIG_PREFIX 目录内"})}return rules}function detectFromEnvRoots(candidates,env,packageRoot,realpath){if(candidates.length===0)return null;let rules=buildEnvRootRules(env,realpath);for(let candidate of candidates)for(let rule of rules)if(rule.roots.some((root)=>isWithinDir(candidate,root)))return{kind:"global",pm:rule.pm,reason:rule.reason,packageRoot};return null}var GLOBAL_PATH_SIGNATURES=[["volta",["/.volta/tools/","/volta/tools/","/.volta/bin/","/volta/bin/"],"命中 Volta 全局工具安装目录"],["bun",["/.bun/install/global/","/.bun/bin/"],"命中 Bun 全局安装目录 (~/.bun)"],["pnpm",["/pnpm/global/","/library/pnpm/global/","/.local/share/pnpm/global/","/appdata/local/pnpm/global/","/pnpm-global/"],"命中 pnpm 全局安装目录"],["yarn",["/.config/yarn/global/","/yarn/data/global/","/yarn/config/global/","/yarn/global/","/.yarn/global/"],"命中 Yarn 全局安装目录"],["npm",["/appdata/roaming/npm/node_modules/","/usr/local/lib/node_modules/","/usr/lib/node_modules/","/opt/homebrew/lib/node_modules/","/.nvm/versions/node/","/nvm4w/","/fnm/node-versions/","/.fnm/node-versions/","/fnm_multishells/","/.asdf/installs/nodejs/","/.local/share/mise/installs/node/","/.mise/installs/node/","/mise/installs/node/","/.nodenv/versions/","/.n/lib/node_modules/","/program files/nodejs/node_modules/","/scoop/apps/nodejs/"],"命中 npm 全局安装目录"]];function detectFromStandardPaths(candidates,packageRoot){for(let candidate of candidates)for(let[pm,markers,reason]of GLOBAL_PATH_SIGNATURES)if(markers.some((marker)=>candidate.includes(marker)))return{kind:"global",pm,reason,packageRoot};return null}function detectFromGlobalRoots(candidates,globalRoots,packageRoot,realpath){if(globalRoots===void 0||candidates.length===0)return null;for(let candidate of candidates)for(let pm of SUPPORTED_PACKAGE_MANAGERS){let root=globalRoots[pm];if(root===void 0||root.trim()==="")continue;if(expandRootVariants(root,realpath).some((v)=>isWithinDir(candidate,v)))return{kind:"global",pm,reason:`匹配 ${pm} 实查全局目录 (${root})`,packageRoot}}return null}function detectFromLibNodeModulesHeuristic(packageRoot,pathExists){let libIdx=packageRoot.toLowerCase().lastIndexOf("/lib/node_modules/");if(libIdx<=0)return null;let prefixDir=packageRoot.slice(0,libIdx);if(pathExists(joinForPath(prefixDir,"package.json")))return null;return{kind:"global",pm:"npm",reason:LIB_NODE_MODULES_HEURISTIC_REASON,packageRoot}}function detectProjectPm(projectDir,pathExists){if(pathExists(joinForPath(projectDir,"bun.lock"))||pathExists(joinForPath(projectDir,"bun.lockb")))return"bun";if(pathExists(joinForPath(projectDir,"pnpm-lock.yaml")))return"pnpm";if(pathExists(joinForPath(projectDir,"yarn.lock")))return"yarn";return"npm"}function detectGlobalForCandidates(candidates,input){if(candidates.length===0)return null;return detectFromEnvRoots(candidates,input.env,input.packageRoot,input.realpath)??detectFromStandardPaths(candidates,input.packageRoot)??detectFromGlobalRoots(candidates,input.globalRoots,input.packageRoot,input.realpath)}function detectInstallOriginFromPath(input){let env=input.env??process.env,pathExists=input.pathExists??existsSync,realpath=input.realpath??safeRealpath,packageRoot=normalizeSlashes(input.packageRoot),foldedRoot=packageRoot.toLowerCase(),rawCandidates=collectRawFoldedCandidates(foldedRoot,input.rawPaths);if(!foldedRoot.includes("/node_modules/")&&pathExists(joinForPath(input.packageRoot,"src","cli.ts")))return{kind:"source",reason:"包根目录位于本地源码工作树 (存在 src/cli.ts)",packageRoot};let ephemeral=detectEphemeral([foldedRoot,...rawCandidates],packageRoot);if(ephemeral!==null)return ephemeral;let fromRoot=detectGlobalForCandidates([foldedRoot],{env,globalRoots:input.globalRoots,packageRoot,realpath});if(fromRoot!==null)return fromRoot;let fromRaw=detectGlobalForCandidates(rawCandidates,{env,globalRoots:input.globalRoots,packageRoot,realpath});if(fromRaw!==null)return fromRaw;let fromHeuristic=detectFromLibNodeModulesHeuristic(packageRoot,pathExists);if(fromHeuristic!==null)return fromHeuristic;let nmIdx=foldedRoot.indexOf("/node_modules/");if(nmIdx>0){let projectDir=packageRoot.slice(0,nmIdx),probeDir=input.packageRoot.startsWith("\\\\")?`\\\\${projectDir.slice(2)}`:projectDir;if(pathExists(joinForPath(probeDir,"package.json")))return{kind:"local-project",projectDir,suggestedPm:detectProjectPm(probeDir,pathExists),reason:`位于项目本地 node_modules (${projectDir})`,packageRoot}}return{kind:"unknown",reason:"未匹配已知全局包管理器路径或本地源码工作树",packageRoot}}function safeRealpath(path){try{return(realpathSync.native??realpathSync)(path)}catch{return path}}var PACKAGE_NAME_RE=/^(?:@[a-z0-9][a-z0-9._-]*\/)?[a-z0-9][a-z0-9._-]*$/,SEMVER_RE=/^v?(\d+)\.(\d+)\.(\d+)(?:-([0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*))?(?:\+[0-9A-Za-z.-]+)?$/,TARGET_SPEC_RE=/^[A-Za-z0-9][A-Za-z0-9._+-]{0,127}$/;function isValidPackageName(name){return name.length>0&&name.length<=214&&PACKAGE_NAME_RE.test(name)}function isValidTargetSpec(spec){return TARGET_SPEC_RE.test(spec)}function isValidRegistryUrl(raw){if(raw.length===0||/[\s"'`$|;&<>\\?#\p{Cc}]/u.test(raw))return!1;try{let parsed=new URL(raw);if(parsed.protocol!=="https:"&&parsed.protocol!=="http:")return!1;if(parsed.username!==""||parsed.password!==""||parsed.search!==""||parsed.hash!=="")return!1;return parsed.hostname.length>0}catch{return!1}}function parseSemver(raw){let match=SEMVER_RE.exec(raw.trim());if(match===null)return null;let major=Number(match[1]),minor=Number(match[2]),patch=Number(match[3]);if(!Number.isSafeInteger(major)||!Number.isSafeInteger(minor)||!Number.isSafeInteger(patch))return null;let prerelease=match[4]===void 0?[]:match[4].split(".");return{major,minor,patch,prerelease}}function comparePrereleaseId(a,b){let aNum=/^\d+$/.test(a),bNum=/^\d+$/.test(b);if(aNum&&bNum)return Math.sign(Number(a)-Number(b));if(aNum&&!bNum)return-1;if(!aNum&&bNum)return 1;if(a===b)return 0;return a<b?-1:1}function compareSemver(a,b){let left=parseSemver(a),right=parseSemver(b);if(left===null||right===null)return null;if(left.major!==right.major)return left.major<right.major?-1:1;if(left.minor!==right.minor)return left.minor<right.minor?-1:1;if(left.patch!==right.patch)return left.patch<right.patch?-1:1;let lPre=left.prerelease,rPre=right.prerelease;if(lPre.length===0&&rPre.length===0)return 0;if(lPre.length===0)return 1;if(rPre.length===0)return-1;let limit=Math.min(lPre.length,rPre.length);for(let i=0;i<limit;i+=1){let diff=comparePrereleaseId(lPre[i],rPre[i]);if(diff!==0)return diff<0?-1:1}if(lPre.length===rPre.length)return 0;return lPre.length<rPre.length?-1:1}var PM_SET=new Set(SUPPORTED_PACKAGE_MANAGERS);function isPackageManager(value){return PM_SET.has(value)}function applyPm(options,value){let normalized=value.trim().toLowerCase();if(!isPackageManager(normalized))return`参数 --pm 不支持 "${value}" (可选值: ${SUPPORTED_PACKAGE_MANAGERS.join(" | ")})`;return options.pm=normalized,null}function applyRegistry(options,value){let trimmed=value.trim();if(!isValidRegistryUrl(trimmed))return`参数 --registry 不是合法的 http(s) URL: "${value}"`;return options.registry=trimmed,null}function nextValueToken(argv,index){let next=argv[index+1];if(next===void 0||next===""||next.startsWith("-"))return null;return next}function parseUpdateArgs(argv){let options={check:!1,force:!1,help:!1};for(let i=0;i<argv.length;i+=1){let arg=argv[i];if(arg==="--help"||arg==="-h"){options.help=!0;continue}if(arg==="--check"){options.check=!0;continue}if(arg==="--force"){options.force=!0;continue}if(arg==="--pm"){let val=nextValueToken(argv,i);if(val===null)return{ok:!1,message:`参数 --pm 缺少取值 (可选值: ${SUPPORTED_PACKAGE_MANAGERS.join(" | ")})`};let err=applyPm(options,val);if(err!==null)return{ok:!1,message:err};i+=1;continue}if(arg.startsWith("--pm=")){let val=arg.slice(5);if(val==="")return{ok:!1,message:`参数 --pm 缺少取值 (可选值: ${SUPPORTED_PACKAGE_MANAGERS.join(" | ")})`};let err=applyPm(options,val);if(err!==null)return{ok:!1,message:err};continue}if(arg==="--registry"){let val=nextValueToken(argv,i);if(val===null)return{ok:!1,message:"参数 --registry 缺少取值"};let err=applyRegistry(options,val);if(err!==null)return{ok:!1,message:err};i+=1;continue}if(arg.startsWith("--registry=")){let val=arg.slice(11);if(val==="")return{ok:!1,message:"参数 --registry 缺少取值"};let err=applyRegistry(options,val);if(err!==null)return{ok:!1,message:err};continue}return{ok:!1,message:`子命令 update 不支持参数: ${arg} (用 update --help 查看用法)`}}return{ok:!0,options}}function formatUpdateHelp(binName,packageName){return[`${binName} update: 自动识别当前安装方式 (bun / npm / pnpm / yarn / volta) 并更新 ${packageName}`,"",`用法: ${binName} update [选项]`,"","选项:"," --check 仅检查最新版本与当前安装方式, 不执行更新",` --pm <管理器> 手动指定更新所用的包管理器 (${SUPPORTED_PACKAGE_MANAGERS.join(" | ")})`," --registry <url> 临时指定本次查询与更新所用的 npm registry"," --force 即使已是最新版本仍强制重新安装"," -h, --help 显示本帮助","","说明:"," • 安装方式按当前包在磁盘上的真实落位路径判定, 不受运行时的 bun/node 切换影响"," • 通过 npx / bunx / pnpm dlx / yarn dlx 临时运行, 或处于本地源码开发态时不会盲目覆盖全局"," • 更新子进程在独立临时空目录执行, 隔绝当前工作目录的 .npmrc / bunfig.toml / package.json 干扰"].join(`
|
|
1
|
+
import{existsSync as existsSync6}from"node:fs";import{resolve as resolve2}from"node:path";import{readFileSync as readFileSync4}from"node:fs";import{dirname,join as join2}from"node:path";import{fileURLToPath}from"node:url";import{existsSync,realpathSync}from"node:fs";import{posix,win32}from"node:path";var SUPPORTED_PACKAGE_MANAGERS=["bun","npm","pnpm","yarn","volta"],LIB_NODE_MODULES_HEURISTIC_REASON="命中标准 <prefix>/lib/node_modules 全局目录";function normalizeSlashes(path){return path.replaceAll("\\","/").replace(/\/+$/,"")}function joinForPath(base,...parts){return/^(?:[A-Za-z]:[/\\]|\\\\)/.test(base)||base.includes("\\")?win32.join(base,...parts):posix.join(base,...parts)}function foldPath(path){return normalizeSlashes(path).toLowerCase()}function isWithinDir(child,parent){let normParent=foldPath(parent);if(normParent==="")return!1;let normChild=foldPath(child);return normChild===normParent||normChild.startsWith(`${normParent}/`)}function collectRawFoldedCandidates(foldedRoot,rawPaths){let seen=new Set([foldedRoot]),out=[];for(let raw of rawPaths??[]){if(typeof raw!=="string"||raw.trim()==="")continue;let folded=foldPath(raw);if(!seen.has(folded))seen.add(folded),out.push(folded)}return out}function expandRootVariants(root,realpath){let trimmed=root.trim();if(trimmed==="")return[];let out=[trimmed],resolved=realpath(trimmed);if(foldPath(resolved)!==foldPath(trimmed))out.push(resolved);return out}function detectEphemeral(candidates,packageRoot){for(let p of candidates){if(p.includes("/_npx/"))return{kind:"ephemeral",runner:"npx",reason:"位于 npx 临时缓存目录 (_npx)",packageRoot};if(p.includes("/bunx-"))return{kind:"ephemeral",runner:"bunx",reason:"位于 bunx 临时执行目录",packageRoot};if(p.includes("/pnpm/dlx/")||p.includes("/pnpm-cache/dlx/")||p.includes("/pnpm-dlx/"))return{kind:"ephemeral",runner:"pnpm-dlx",reason:"位于 pnpm dlx 临时缓存目录",packageRoot};if(p.includes("/xfs-")&&p.includes("/dlx-")||p.includes("/berry/cache/")&&p.includes("/dlx"))return{kind:"ephemeral",runner:"yarn-dlx",reason:"位于 yarn dlx 临时执行目录",packageRoot};if(p.includes("/deno/npm/"))return{kind:"ephemeral",runner:"deno",reason:"位于 Deno npm 缓存目录 (/deno/npm/)",packageRoot}}return null}function buildEnvRootRules(env,realpath){let rules=[],directSpecs=[["volta",env.VOLTA_HOME,"位于环境变量 VOLTA_HOME 目录内"],["bun",env.BUN_INSTALL,"位于环境变量 BUN_INSTALL 目录内"],["bun",env.BUN_INSTALL_GLOBAL_DIR,"位于环境变量 BUN_INSTALL_GLOBAL_DIR 目录内"],["pnpm",env.PNPM_HOME,"位于环境变量 PNPM_HOME 目录内"]];for(let[pm,rawRoot,reason]of directSpecs){if(rawRoot===void 0||rawRoot.trim()==="")continue;let roots=expandRootVariants(rawRoot,realpath);if(roots.length>0)rules.push({pm,roots,reason})}let npmPrefix=env.NPM_CONFIG_PREFIX??env.npm_config_prefix;if(npmPrefix!==void 0&&npmPrefix.trim()!==""){let npmRoots=[];for(let base of expandRootVariants(npmPrefix,realpath)){let norm=normalizeSlashes(base);if(norm==="")continue;npmRoots.push(`${norm}/lib/node_modules`,`${norm}/node_modules`)}if(npmRoots.length>0)rules.push({pm:"npm",roots:npmRoots,reason:"位于环境变量 NPM_CONFIG_PREFIX 目录内"})}return rules}function detectFromEnvRoots(candidates,env,packageRoot,realpath){if(candidates.length===0)return null;let rules=buildEnvRootRules(env,realpath);for(let candidate of candidates)for(let rule of rules)if(rule.roots.some((root)=>isWithinDir(candidate,root)))return{kind:"global",pm:rule.pm,reason:rule.reason,packageRoot};return null}var GLOBAL_PATH_SIGNATURES=[["volta",["/.volta/tools/","/volta/tools/","/.volta/bin/","/volta/bin/"],"命中 Volta 全局工具安装目录"],["bun",["/.bun/install/global/","/.bun/bin/"],"命中 Bun 全局安装目录 (~/.bun)"],["pnpm",["/pnpm/global/","/library/pnpm/global/","/.local/share/pnpm/global/","/appdata/local/pnpm/global/","/pnpm-global/"],"命中 pnpm 全局安装目录"],["yarn",["/.config/yarn/global/","/yarn/data/global/","/yarn/config/global/","/yarn/global/","/.yarn/global/"],"命中 Yarn 全局安装目录"],["npm",["/appdata/roaming/npm/node_modules/","/usr/local/lib/node_modules/","/usr/lib/node_modules/","/opt/homebrew/lib/node_modules/","/.nvm/versions/node/","/nvm4w/","/fnm/node-versions/","/.fnm/node-versions/","/fnm_multishells/","/.asdf/installs/nodejs/","/.local/share/mise/installs/node/","/.mise/installs/node/","/mise/installs/node/","/.nodenv/versions/","/.n/lib/node_modules/","/program files/nodejs/node_modules/","/scoop/apps/nodejs/"],"命中 npm 全局安装目录"]];function detectFromStandardPaths(candidates,packageRoot){for(let candidate of candidates)for(let[pm,markers,reason]of GLOBAL_PATH_SIGNATURES)if(markers.some((marker)=>candidate.includes(marker)))return{kind:"global",pm,reason,packageRoot};return null}function detectFromGlobalRoots(candidates,globalRoots,packageRoot,realpath){if(globalRoots===void 0||candidates.length===0)return null;for(let candidate of candidates)for(let pm of SUPPORTED_PACKAGE_MANAGERS){let root=globalRoots[pm];if(root===void 0||root.trim()==="")continue;if(expandRootVariants(root,realpath).some((v)=>isWithinDir(candidate,v)))return{kind:"global",pm,reason:`匹配 ${pm} 实查全局目录 (${root})`,packageRoot}}return null}function detectFromLibNodeModulesHeuristic(packageRoot,pathExists){let libIdx=packageRoot.toLowerCase().lastIndexOf("/lib/node_modules/");if(libIdx<=0)return null;let prefixDir=packageRoot.slice(0,libIdx);if(pathExists(joinForPath(prefixDir,"package.json")))return null;return{kind:"global",pm:"npm",reason:LIB_NODE_MODULES_HEURISTIC_REASON,packageRoot}}function detectProjectPm(projectDir,pathExists){if(pathExists(joinForPath(projectDir,"bun.lock"))||pathExists(joinForPath(projectDir,"bun.lockb")))return"bun";if(pathExists(joinForPath(projectDir,"pnpm-lock.yaml")))return"pnpm";if(pathExists(joinForPath(projectDir,"yarn.lock")))return"yarn";return"npm"}function detectGlobalForCandidates(candidates,input){if(candidates.length===0)return null;return detectFromEnvRoots(candidates,input.env,input.packageRoot,input.realpath)??detectFromStandardPaths(candidates,input.packageRoot)??detectFromGlobalRoots(candidates,input.globalRoots,input.packageRoot,input.realpath)}function detectInstallOriginFromPath(input){let env=input.env??process.env,pathExists=input.pathExists??existsSync,realpath=input.realpath??safeRealpath,packageRoot=normalizeSlashes(input.packageRoot),foldedRoot=packageRoot.toLowerCase(),rawCandidates=collectRawFoldedCandidates(foldedRoot,input.rawPaths);if(!foldedRoot.includes("/node_modules/")&&pathExists(joinForPath(input.packageRoot,"src","cli.ts")))return{kind:"source",reason:"包根目录位于本地源码工作树 (存在 src/cli.ts)",packageRoot};let ephemeral=detectEphemeral([foldedRoot,...rawCandidates],packageRoot);if(ephemeral!==null)return ephemeral;let fromRoot=detectGlobalForCandidates([foldedRoot],{env,globalRoots:input.globalRoots,packageRoot,realpath});if(fromRoot!==null)return fromRoot;let fromRaw=detectGlobalForCandidates(rawCandidates,{env,globalRoots:input.globalRoots,packageRoot,realpath});if(fromRaw!==null)return fromRaw;let fromHeuristic=detectFromLibNodeModulesHeuristic(packageRoot,pathExists);if(fromHeuristic!==null)return fromHeuristic;let nmIdx=foldedRoot.indexOf("/node_modules/");if(nmIdx>0){let projectDir=packageRoot.slice(0,nmIdx),probeDir=input.packageRoot.startsWith("\\\\")?`\\\\${projectDir.slice(2)}`:projectDir;if(pathExists(joinForPath(probeDir,"package.json")))return{kind:"local-project",projectDir,suggestedPm:detectProjectPm(probeDir,pathExists),reason:`位于项目本地 node_modules (${projectDir})`,packageRoot}}return{kind:"unknown",reason:"未匹配已知全局包管理器路径或本地源码工作树",packageRoot}}function safeRealpath(path){try{return(realpathSync.native??realpathSync)(path)}catch{return path}}var PACKAGE_NAME_RE=/^(?:@[a-z0-9][a-z0-9._-]*\/)?[a-z0-9][a-z0-9._-]*$/,SEMVER_RE=/^v?(\d+)\.(\d+)\.(\d+)(?:-([0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*))?(?:\+[0-9A-Za-z.-]+)?$/,TARGET_SPEC_RE=/^[A-Za-z0-9][A-Za-z0-9._+-]{0,127}$/;function isValidPackageName(name){return name.length>0&&name.length<=214&&PACKAGE_NAME_RE.test(name)}function isValidTargetSpec(spec){return TARGET_SPEC_RE.test(spec)}function isValidRegistryUrl(raw){if(raw.length===0||/[\s"'`$|;&<>\\?#\p{Cc}]/u.test(raw))return!1;try{let parsed=new URL(raw);if(parsed.protocol!=="https:"&&parsed.protocol!=="http:")return!1;if(parsed.username!==""||parsed.password!==""||parsed.search!==""||parsed.hash!=="")return!1;return parsed.hostname.length>0}catch{return!1}}function parseSemver(raw){let match=SEMVER_RE.exec(raw.trim());if(match===null)return null;let major=Number(match[1]),minor=Number(match[2]),patch=Number(match[3]);if(!Number.isSafeInteger(major)||!Number.isSafeInteger(minor)||!Number.isSafeInteger(patch))return null;let prerelease=match[4]===void 0?[]:match[4].split(".");return{major,minor,patch,prerelease}}function comparePrereleaseId(a,b){let aNum=/^\d+$/.test(a),bNum=/^\d+$/.test(b);if(aNum&&bNum)return Math.sign(Number(a)-Number(b));if(aNum&&!bNum)return-1;if(!aNum&&bNum)return 1;if(a===b)return 0;return a<b?-1:1}function compareSemver(a,b){let left=parseSemver(a),right=parseSemver(b);if(left===null||right===null)return null;if(left.major!==right.major)return left.major<right.major?-1:1;if(left.minor!==right.minor)return left.minor<right.minor?-1:1;if(left.patch!==right.patch)return left.patch<right.patch?-1:1;let lPre=left.prerelease,rPre=right.prerelease;if(lPre.length===0&&rPre.length===0)return 0;if(lPre.length===0)return 1;if(rPre.length===0)return-1;let limit=Math.min(lPre.length,rPre.length);for(let i=0;i<limit;i+=1){let diff=comparePrereleaseId(lPre[i],rPre[i]);if(diff!==0)return diff<0?-1:1}if(lPre.length===rPre.length)return 0;return lPre.length<rPre.length?-1:1}var PM_SET=new Set(SUPPORTED_PACKAGE_MANAGERS);function isPackageManager(value){return PM_SET.has(value)}function applyPm(options,value){let normalized=value.trim().toLowerCase();if(!isPackageManager(normalized))return`参数 --pm 不支持 "${value}" (可选值: ${SUPPORTED_PACKAGE_MANAGERS.join(" | ")})`;return options.pm=normalized,null}function applyRegistry(options,value){let trimmed=value.trim();if(!isValidRegistryUrl(trimmed))return`参数 --registry 不是合法的 http(s) URL: "${value}"`;return options.registry=trimmed,null}function nextValueToken(argv,index){let next=argv[index+1];if(next===void 0||next===""||next.startsWith("-"))return null;return next}function parseUpdateArgs(argv){let options={check:!1,force:!1,help:!1};for(let i=0;i<argv.length;i+=1){let arg=argv[i];if(arg==="--help"||arg==="-h"){options.help=!0;continue}if(arg==="--check"){options.check=!0;continue}if(arg==="--force"){options.force=!0;continue}if(arg==="--pm"){let val=nextValueToken(argv,i);if(val===null)return{ok:!1,message:`参数 --pm 缺少取值 (可选值: ${SUPPORTED_PACKAGE_MANAGERS.join(" | ")})`};let err=applyPm(options,val);if(err!==null)return{ok:!1,message:err};i+=1;continue}if(arg.startsWith("--pm=")){let val=arg.slice(5);if(val==="")return{ok:!1,message:`参数 --pm 缺少取值 (可选值: ${SUPPORTED_PACKAGE_MANAGERS.join(" | ")})`};let err=applyPm(options,val);if(err!==null)return{ok:!1,message:err};continue}if(arg==="--registry"){let val=nextValueToken(argv,i);if(val===null)return{ok:!1,message:"参数 --registry 缺少取值"};let err=applyRegistry(options,val);if(err!==null)return{ok:!1,message:err};i+=1;continue}if(arg.startsWith("--registry=")){let val=arg.slice(11);if(val==="")return{ok:!1,message:"参数 --registry 缺少取值"};let err=applyRegistry(options,val);if(err!==null)return{ok:!1,message:err};continue}return{ok:!1,message:`子命令 update 不支持参数: ${arg} (用 update --help 查看用法)`}}return{ok:!0,options}}function formatUpdateHelp(binName,packageName){return["",` ${binName} update 自更新工具 (${packageName})`," 自动识别当前安装器 (bun / npm / pnpm / yarn / volta) 并原地升级。"," ────────────────────────────────────────────────────────────────────────────",""," 用法",` ${binName} update [选项]`,""," 选项"," --check 仅检查最新版本与当前安装方式, 不执行更新",` --pm <管理器> 手动指定更新所用的包管理器 (${SUPPORTED_PACKAGE_MANAGERS.join(" | ")})`," --registry <url> 临时指定本次查询与更新所用的 npm registry"," --force 即使已是最新版本仍强制重新安装",""," -h, --help 显示本帮助",""," 说明"," 识别依据 按当前包在磁盘上的真实落位路径判定, 不受 bun / node 运行时切换影响"," 安全边界 npx / bunx / dlx 临时运行或本地源码态不盲目覆盖全局安装"," 环境隔离 更新子进程在独立临时空目录执行, 隔绝 cwd 配置干扰"," 镜像源 默认走官方源 registry.npmjs.org, 自动遵循本机 ~/.bunfig.toml 或 ~/.npmrc",""].join(`
|
|
2
2
|
`)}import{spawnSync}from"node:child_process";import{existsSync as existsSync2,mkdtempSync,readFileSync as readFileSync2,rmSync,statSync}from"node:fs";import{homedir as homedir2,tmpdir}from"node:os";import{join,posix as posix2,win32 as win323}from"node:path";function normalizeRegistryUrl(url){return url.trim().replace(/\/+$/,"")}function extractScope(packageName){if(!packageName.startsWith("@"))return null;let slash=packageName.indexOf("/");return slash>1?packageName.slice(0,slash):null}function unquotePair(raw){let trimmed=raw.trim();if(trimmed.length>=2&&(trimmed.startsWith('"')&&trimmed.endsWith('"')||trimmed.startsWith("'")&&trimmed.endsWith("'")))return trimmed.slice(1,-1);return trimmed}function stripTomlComment(line){let inDouble=!1,inSingle=!1,escaped=!1;for(let i=0;i<line.length;i+=1){let ch=line[i];if(inDouble){if(escaped)escaped=!1;else if(ch==="\\")escaped=!0;else if(ch==='"')inDouble=!1;continue}if(inSingle){if(ch==="'")inSingle=!1;continue}if(ch==="#")return line.slice(0,i).trim();if(ch==='"')inDouble=!0;else if(ch==="'")inSingle=!0}return line.trim()}function parseTomlString(raw){let trimmed=raw.trim();if(trimmed.length<2)return null;let quote=trimmed[0];if(quote!=='"'&"e!=="'")return null;if(quote==="'"){let end=trimmed.indexOf("'",1);return end===trimmed.length-1?trimmed.slice(1,end):null}let out="",escaped=!1;for(let i=1;i<trimmed.length;i+=1){let ch=trimmed[i];if(escaped){out+=ch,escaped=!1;continue}if(ch==="\\"){escaped=!0;continue}if(ch==='"')return i===trimmed.length-1?out:null;out+=ch}return null}function extractInlineField(body,fieldName){let m=new RegExp(`(?:^|[,{])\\s*${fieldName}\\s*=\\s*("[^"\\\\]*(?:\\\\.[^"\\\\]*)*"|'[^']*')`).exec(body);return m===null?null:parseTomlString(m[1])}function normalizeUrlPath(pathname){let trimmed=pathname.replace(/\/+$/,"");return trimmed===""?"/":`${trimmed}/`}function expandEnvToken(raw,env,allowBareDollar){let missing=!1,expanded=raw.replace(/\$\{([A-Za-z_][A-Za-z0-9_]*)\}/g,(_m,name)=>{let val=env[name];if(typeof val!=="string"||val==="")return missing=!0,"";return val});if(missing||expanded.includes("${"))return null;if(allowBareDollar){if(expanded=expanded.replace(/\$([A-Za-z_][A-Za-z0-9_]*)/g,(_m,name)=>{let val=env[name];if(typeof val!=="string"||val==="")return missing=!0,"";return val}),missing)return null}let trimmed=expanded.trim();if(trimmed===""||/[\s\p{Cc}]/u.test(trimmed))return null;return trimmed}function parseRegistryFromNpmrc(content,packageName){let scope=extractScope(packageName),globalReg=null,scopedReg=null;for(let rawLine of content.split(/\r?\n/)){let line=rawLine.trim();if(line===""||line.startsWith("#")||line.startsWith(";"))continue;let eq=line.indexOf("=");if(eq<=0)continue;let key=line.slice(0,eq).trim(),value=unquotePair(line.slice(eq+1));if(!isValidRegistryUrl(value))continue;if(scope!==null&&key===`${scope}:registry`)scopedReg=value;else if(key==="registry")globalReg=value}return scopedReg??globalReg}function parseAuthTokenFromNpmrc(content,registryUrl,env=process.env){let target;try{target=new URL(normalizeRegistryUrl(registryUrl))}catch{return null}let targetHost=target.host.toLowerCase(),targetPath=normalizeUrlPath(target.pathname),matched=null;for(let rawLine of content.split(/\r?\n/)){let line=rawLine.trim();if(line===""||line.startsWith("#")||line.startsWith(";"))continue;let eq=line.indexOf("=");if(eq<=0)continue;let key=line.slice(0,eq).trim();if(!key.startsWith("//")||!key.endsWith(":_authToken"))continue;let hostPath=key.slice(2,-11);if(hostPath==="")continue;let entry;try{entry=new URL(`https://${hostPath}`)}catch{continue}if(entry.host.toLowerCase()!==targetHost||normalizeUrlPath(entry.pathname)!==targetPath)continue;let token=expandEnvToken(unquotePair(line.slice(eq+1)),env,!1);if(token!==null)matched=token}return matched}function parseScopedSubtableHeader(section){let m=/^install\.scopes\.(?:"([^"]+)"|'([^']+)'|([^\s.\]]+))$/.exec(section);if(m===null)return null;let scopeName=(m[1]??m[2]??m[3]??"").trim();return scopeName.startsWith("@")?scopeName:null}function applyBunfigKeyValue(target,key,rhs){let str=parseTomlString(rhs);if(str===null)return;if(key==="url"&&isValidRegistryUrl(str))target.url=str;else if(key==="token"&&str.trim()!=="")target.token=str}function applyBunfigRegistryRhs(target,rhs){let str=parseTomlString(rhs);if(str!==null){if(isValidRegistryUrl(str))target.url=str;return}if(!rhs.startsWith("{")||!rhs.endsWith("}"))return;let url=extractInlineField(rhs,"url");if(url!==null&&isValidRegistryUrl(url))target.url=url;let token=extractInlineField(rhs,"token");if(token!==null&&token.trim()!=="")target.token=token}function parseBunfigInstall(content){let result={globalEntry:{},scopes:new Map,globalDir:null},section="",getScopeEntry=(scopeName)=>{let existing=result.scopes.get(scopeName);if(existing!==void 0)return existing;let created={};return result.scopes.set(scopeName,created),created};for(let rawLine of content.split(/\r?\n/)){let line=stripTomlComment(rawLine);if(line==="")continue;let secMatch=/^\[([^\]]+)\]$/.exec(line);if(secMatch!==null){section=secMatch[1].trim();continue}let eq=line.indexOf("=");if(eq<=0)continue;let rawKey=line.slice(0,eq).trim(),rhs=line.slice(eq+1).trim();if(section==="install"){if(rawKey==="registry")applyBunfigRegistryRhs(result.globalEntry,rhs);else if(rawKey==="globalDir"){let dir=parseTomlString(rhs);if(dir!==null&&dir.trim()!=="")result.globalDir=dir.trim()}continue}if(section==="install.registry"){applyBunfigKeyValue(result.globalEntry,rawKey,rhs);continue}if(section==="install.scopes"){let scopeName=unquotePair(rawKey);if(scopeName.startsWith("@"))applyBunfigRegistryRhs(getScopeEntry(scopeName),rhs);continue}let subScope=parseScopedSubtableHeader(section);if(subScope!==null)applyBunfigKeyValue(getScopeEntry(subScope),rawKey,rhs)}return result}function parseRegistryFromBunfig(content,packageName){let parsed=parseBunfigInstall(content),scope=extractScope(packageName);return(scope!==null?parsed.scopes.get(scope)?.url:void 0)??parsed.globalEntry.url??null}function matchesRegistryOriginAndPath(targetUrl,entryUrl){try{let a=new URL(normalizeRegistryUrl(targetUrl)),b=new URL(normalizeRegistryUrl(entryUrl));return a.protocol===b.protocol&&a.host.toLowerCase()===b.host.toLowerCase()&&normalizeUrlPath(a.pathname)===normalizeUrlPath(b.pathname)}catch{return!1}}function parseAuthTokenFromBunfig(content,registryUrl,packageName,env=process.env){let parsed=parseBunfigInstall(content),scope=extractScope(packageName),ordered=[];if(scope!==null){let scoped=parsed.scopes.get(scope);if(scoped!==void 0)ordered.push(scoped)}ordered.push(parsed.globalEntry);for(let[k,entry]of parsed.scopes.entries())if(k!==scope)ordered.push(entry);for(let entry of ordered){if(entry.url===void 0||entry.token===void 0)continue;if(!matchesRegistryOriginAndPath(registryUrl,entry.url))continue;let expanded=expandEnvToken(entry.token,env,!0);if(expanded!==null)return expanded}return null}function parseGlobalDirFromBunfig(content){return parseBunfigInstall(content).globalDir}import{readFileSync}from"node:fs";import{homedir}from"node:os";var DEFAULT_REGISTRY="https://registry.npmjs.org",DEFAULT_FETCH_TIMEOUT_MS=1e4;function defaultReadText(path){try{return readFileSync(path,"utf8")}catch{return null}}function resolveRegistry(input){if(input.flagRegistry!==void 0&&isValidRegistryUrl(input.flagRegistry))return normalizeRegistryUrl(input.flagRegistry);let env=input.env??process.env,envReg=env.NPM_CONFIG_REGISTRY??env.npm_config_registry;if(typeof envReg==="string"&&isValidRegistryUrl(envReg))return normalizeRegistryUrl(envReg);let home=input.homeDir??homedir(),readText=input.readText??defaultReadText;if(input.pm==="bun"){let bunfig=readText(joinForPath(home,".bunfig.toml"));if(bunfig!==null){let found=parseRegistryFromBunfig(bunfig,input.packageName);if(found!==null)return normalizeRegistryUrl(found)}}let npmrc=readText(joinForPath(home,".npmrc"));if(npmrc!==null){let found=parseRegistryFromNpmrc(npmrc,input.packageName);if(found!==null)return normalizeRegistryUrl(found)}if(input.pm===void 0){let bunfig=readText(joinForPath(home,".bunfig.toml"));if(bunfig!==null){let found=parseRegistryFromBunfig(bunfig,input.packageName);if(found!==null)return normalizeRegistryUrl(found)}}return DEFAULT_REGISTRY}function resolveRegistryAuthToken(input){if(!isValidRegistryUrl(input.registry))return;let env=input.env??process.env,home=input.homeDir??homedir(),readText=input.readText??defaultReadText,base=normalizeRegistryUrl(input.registry);if(input.pm==="bun"){let bunfig=readText(joinForPath(home,".bunfig.toml"));if(bunfig!==null){let token=parseAuthTokenFromBunfig(bunfig,base,input.packageName,env);if(token!==null)return token}}let npmrc=readText(joinForPath(home,".npmrc"));if(npmrc!==null){let token=parseAuthTokenFromNpmrc(npmrc,base,env);if(token!==null)return token}if(input.pm===void 0){let bunfig=readText(joinForPath(home,".bunfig.toml"));if(bunfig!==null){let token=parseAuthTokenFromBunfig(bunfig,base,input.packageName,env);if(token!==null)return token}}return}function cleanMessage(raw,secret){return(secret!==void 0&&secret!==""?raw.replaceAll(secret,"[REDACTED]"):raw).replace(/\p{Cc}/gu," ").replace(/\s+/g," ").trim()}async function fetchLatestVersion(input){let tag=input.tag??"latest";if(!isValidPackageName(input.packageName))return{ok:!1,code:"invalid-response",message:`非法包名: ${cleanMessage(input.packageName)}`};if(!isValidTargetSpec(tag)||!isValidRegistryUrl(input.registry))return{ok:!1,code:"invalid-response",message:"非法的 registry 地址或版本标签"};let base=normalizeRegistryUrl(input.registry),url=`${base}/${encodeURIComponent(input.packageName)}/${encodeURIComponent(tag)}`,fetchFn=input.fetchFn??fetch,timeoutMs=input.timeoutMs??DEFAULT_FETCH_TIMEOUT_MS,authToken=typeof input.authToken==="string"&&input.authToken.trim()!==""&&!/[\s\p{Cc}]/u.test(input.authToken)?input.authToken.trim():void 0,headers={accept:"application/vnd.npm.install-v1+json, application/json"};if(authToken!==void 0)headers.authorization=`Bearer ${authToken}`;let response;try{response=await fetchFn(url,{headers,signal:AbortSignal.timeout(timeoutMs)})}catch(error){let detail=error instanceof Error?cleanMessage(error.message,authToken):"";return{ok:!1,code:"network",message:detail===""?`无法连接包注册表 (${base})`:`无法连接包注册表 (${base}): ${detail}`}}if(response.status===401||response.status===403)return{ok:!1,code:"auth",status:response.status,message:`访问包注册表 ${base} 鉴权失败 (HTTP ${response.status}), 请检查 ~/.npmrc / ~/.bunfig.toml 认证凭据或登录状态`};if(response.status===404)return{ok:!1,code:"not-found",status:404,message:`${input.packageName} 尚未在 ${base} 发布 (HTTP 404)`};if(!response.ok)return{ok:!1,code:"http",status:response.status,message:`包注册表返回异常状态 HTTP ${response.status} (${base})`};let body;try{body=await response.json()}catch{return{ok:!1,code:"invalid-response",message:`包注册表返回的内容不是合法 JSON (${base})`}}let version=typeof body==="object"&&body!==null&&!Array.isArray(body)?body.version:void 0;if(typeof version!=="string"||!isValidTargetSpec(version))return{ok:!1,code:"invalid-response",message:`包注册表响应缺少合法 version 字段 (${base})`};return{ok:!0,version,registry:base}}import{win32 as win322}from"node:path";function isWin32AbsolutePath(dir){return/^(?:[A-Za-z]:[/\\]|\\\\[^\\]+\\[^\\]+)/.test(dir)}var CMD_META_OR_SPACE_RE=/[\s&|<>^()%!]/,CMD_FORBIDDEN_RE=/[\r\n\0"]/;function wrapDoubleQuotes(segment){return`"${segment.replace(/(\\+)$/,"$1$1")}"`}function escapeBatchPath(batchPath){if(batchPath===""||CMD_FORBIDDEN_RE.test(batchPath))return null;if(!/[%!]/.test(batchPath))return wrapDoubleQuotes(batchPath);let out="",buf="";for(let ch of batchPath)if(ch==="%"||ch==="!"){if(buf!=="")out+=wrapDoubleQuotes(buf),buf="";out+=`^${ch}`}else buf+=ch;if(buf!=="")out+=wrapDoubleQuotes(buf);return out}function escapeBatchArg(arg){if(CMD_FORBIDDEN_RE.test(arg))return null;if(arg==="")return'""';if(!CMD_META_OR_SPACE_RE.test(arg))return arg;if(!/[%!]/.test(arg))return wrapDoubleQuotes(arg);let out="",buf="";for(let ch of arg)if(ch==="%"||ch==="!"){if(buf!=="")out+=wrapDoubleQuotes(buf),buf="";out+=`^^^${ch}`}else buf+=ch;if(buf!=="")out+=wrapDoubleQuotes(buf);return out}function buildWindowsBatchCommandLine(batchPath,pmArgs){let escapedPath=escapeBatchPath(batchPath);if(escapedPath===null)return null;let escapedArgs=[];for(let arg of pmArgs){let escaped=escapeBatchArg(arg);if(escaped===null)return null;escapedArgs.push(escaped)}return`"${escapedArgs.length===0?escapedPath:`${escapedPath} ${escapedArgs.join(" ")}`}"`}function resolveNodeExeForDir(dir,isFile,findNativeNode){let sibling=win322.join(dir,"node.exe");if(isFile(sibling))return sibling;return findNativeNode()}function resolveWindowsBatchDirectJs(pm,batchPath,args,isFile,findNativeNode){let dir=win322.dirname(batchPath),candidates=[];if(pm==="npm")candidates=[win322.join(dir,"node_modules","npm","bin","npm-cli.js")];else if(pm==="pnpm")candidates=[win322.join(dir,"node_modules","pnpm","bin","pnpm.cjs"),win322.join(dir,"node_modules","corepack","dist","pnpm.js")];else if(pm==="yarn")candidates=[win322.join(dir,"yarn.js"),win322.join(dir,"node_modules","yarn","bin","yarn.js"),win322.join(dir,"node_modules","corepack","dist","yarn.js")];else return null;for(let entryJs of candidates){if(!isFile(entryJs))continue;let nodeExe=resolveNodeExeForDir(dir,isFile,findNativeNode);if(nodeExe!==null)return{command:nodeExe,args:[entryJs,...args]}}return null}function resolveWindowsBatchInvocation(pm,batchPath,pmArgs,env,isFile,findNativeNode){let directJs=resolveWindowsBatchDirectJs(pm,batchPath,pmArgs,isFile,findNativeNode);if(directJs!==null)return directJs;let cmdLine=buildWindowsBatchCommandLine(batchPath,pmArgs);if(cmdLine===null)return null;return{command:env.ComSpec??env.COMSPEC??"cmd.exe",args:["/d","/s","/c",cmdLine],windowsVerbatimArguments:!0}}var WIN32_NATIVE_EXTS=[".exe",".com"],WIN32_BATCH_EXTS=[".cmd",".bat"],PROBE_ENV_OVERLAY={COREPACK_ENABLE_DOWNLOAD_PROMPT:"0"};function defaultIsFile(path){try{return statSync(path).isFile()}catch{return!1}}function defaultReadText2(path){try{return readFileSync2(path,"utf8")}catch{return null}}function parseAbsolutePathDirs(env,platform){let raw=platform==="win32"?env.PATH??env.Path??"":env.PATH??"",sep=platform==="win32"?";":":",out=[];for(let item of raw.split(sep)){let trimmed=item.trim(),cleaned=trimmed.length>1&&trimmed.startsWith('"')&&trimmed.endsWith('"')?trimmed.slice(1,-1):trimmed;if(cleaned==="")continue;if(platform==="win32"?isWin32AbsolutePath(cleaned):cleaned.startsWith("/"))out.push(cleaned)}return out}function resolveExecutableInPath(name,platform=process.platform,env=process.env,isFile=defaultIsFile){let dirs=parseAbsolutePathDirs(env,platform);if(platform!=="win32"){for(let dir of dirs){let candidate=posix2.join(dir,name);if(isFile(candidate))return{path:candidate,isBatch:!1}}return null}for(let dir of dirs){for(let ext of WIN32_NATIVE_EXTS){let candidate=win323.join(dir,`${name}${ext}`);if(isFile(candidate))return{path:candidate,isBatch:!1}}for(let ext of WIN32_BATCH_EXTS){let candidate=win323.join(dir,`${name}${ext}`);if(isFile(candidate))return{path:candidate,isBatch:!0}}}return null}function resolvePmInvocation(pm,pmArgs,platform=process.platform,env=process.env,isFile=defaultIsFile){let found=resolveExecutableInPath(pm,platform,env,isFile);if(found===null)return null;if(platform==="win32"&&found.isBatch){let findNativeNode=()=>{let nodeFound=resolveExecutableInPath("node","win32",env,isFile);return nodeFound!==null&&!nodeFound.isBatch?nodeFound.path:null};return resolveWindowsBatchInvocation(pm,found.path,pmArgs,env,isFile,findNativeNode)}return{command:found.path,args:[...pmArgs]}}function formatUpgradeDisplayCommand(pm,packageName,targetSpec="latest",explicitRegistry){let spec=`${packageName}@${targetSpec}`,reg=explicitRegistry!==void 0?normalizeRegistryUrl(explicitRegistry):void 0;switch(pm){case"bun":return reg===void 0?`bun add -g ${spec}`:`bun add -g ${spec} --registry=${reg}`;case"npm":return reg===void 0?`npm install -g ${spec}`:`npm install -g ${spec} --registry=${reg}`;case"pnpm":return reg===void 0?`pnpm add -g ${spec}`:`pnpm add -g ${spec} --registry=${reg}`;case"yarn":return reg===void 0?`yarn global add ${spec}`:`yarn global add ${spec} --registry ${reg}`;case"volta":return reg===void 0?`volta install ${spec}`:`NPM_CONFIG_REGISTRY=${reg} volta install ${spec}`}}function isYarnBerryVersion(versionText){if(versionText===null)return!1;let m=/^v?(\d+)\./.exec(versionText.trim());if(m===null)return!1;return Number(m[1])>=2}function buildPmUpgradeArgs(pm,spec,reg){if(pm==="volta")return["install",spec];if(pm==="yarn")return reg===void 0?["global","add",spec]:["global","add",spec,"--registry",reg];let base=pm==="npm"?["install","-g",spec]:["add","-g",spec];return reg===void 0?base:[...base,`--registry=${reg}`]}function buildUpgradePlan(input){let targetSpec=input.targetSpec??"latest";if(!isValidPackageName(input.packageName))return{ok:!1,reason:`非法包名: ${input.packageName}`};if(!isValidTargetSpec(targetSpec))return{ok:!1,reason:`非法目标版本标签: ${targetSpec}`};if(input.explicitRegistry!==void 0&&!isValidRegistryUrl(input.explicitRegistry))return{ok:!1,reason:`非法 registry 地址: ${input.explicitRegistry}`};let platform=input.platform??process.platform,env=input.env??process.env,isFile=input.isFile??defaultIsFile,reg=input.explicitRegistry!==void 0?normalizeRegistryUrl(input.explicitRegistry):void 0,displayCommand=formatUpgradeDisplayCommand(input.pm,input.packageName,targetSpec,reg);if(input.pm==="yarn"&&isYarnBerryVersion(input.yarnVersion??null))return{ok:!1,reason:`当前环境的 Yarn (${input.yarnVersion?.trim()}) 为 v2+ (Berry), 官方已移除 yarn global add 命令, `+"请改用 --pm bun / --pm npm / --pm pnpm 执行全局更新"};let spec=`${input.packageName}@${targetSpec}`,pmArgs=buildPmUpgradeArgs(input.pm,spec,reg),invocation=resolvePmInvocation(input.pm,pmArgs,platform,env,isFile);if(invocation===null)return{ok:!1,reason:`当前 PATH 中未找到 ${input.pm} 可执行文件, 无法自动执行更新`,fallbackCommand:displayCommand};let envOverlay=reg===void 0?void 0:{npm_config_registry:reg,NPM_CONFIG_REGISTRY:reg};return{ok:!0,plan:{command:invocation.command,args:invocation.args,displayCommand,envOverlay,...invocation.windowsVerbatimArguments===!0?{windowsVerbatimArguments:!0}:{}}}}function buildIsolatedEnv(baseEnv,overlay){let next={...baseEnv};if(delete next.npm_execpath,delete next.npm_lifecycle_event,delete next.npm_lifecycle_script,delete next.npm_package_json,delete next.INIT_CWD,overlay!==void 0)Object.assign(next,overlay);return next}function withIsolatedCwd(fn){let dir=mkdtempSync(join(tmpdir(),"cli-update-"));try{return fn(dir)}finally{try{rmSync(dir,{recursive:!0,force:!0,maxRetries:3,retryDelay:50})}catch{}}}function runIsolatedProbe(cwd,invocation,env,spawnFn){let res=spawnFn(invocation.command,invocation.args,{cwd,env:buildIsolatedEnv(env,PROBE_ENV_OVERLAY),encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:3000,...invocation.windowsVerbatimArguments===!0?{windowsVerbatimArguments:!0}:{}});if(res.status!==0||typeof res.stdout!=="string")return null;let text=res.stdout.trim();return text===""?null:text}function probeYarnVersion(platform=process.platform,env=process.env,spawnFn=spawnSync){let invocation=resolvePmInvocation("yarn",["--version"],platform,env);if(invocation===null)return null;return withIsolatedCwd((cwd)=>runIsolatedProbe(cwd,invocation,env,spawnFn))}var joinForPlatform=(p,...parts)=>p==="win32"?win323.join(...parts):posix2.join(...parts);function expandHomeDir(raw,home,p){if(raw==="~")return home;if(raw.startsWith("~/")||raw.startsWith("~\\"))return joinForPlatform(p,home,raw.slice(2));return raw}function resolveBunGlobalDirFromConfig(home,platform,readText,pathExists){let bunfig=readText(joinForPlatform(platform,home,".bunfig.toml"));if(bunfig===null)return null;let rawDir=parseGlobalDirFromBunfig(bunfig);if(rawDir===null)return null;let expanded=expandHomeDir(rawDir,home,platform);return pathExists(expanded)?safeRealpath(expanded):null}function probeGlobalRoots(platform=process.platform,env=process.env,spawnFn=spawnSync,options){let roots={},home=options?.homeDir??homedir2(),readText=options?.readText??defaultReadText2,pathExists=options?.pathExists??existsSync2,isFile=options?.isFile??defaultIsFile,bunDir=resolveBunGlobalDirFromConfig(home,platform,readText,pathExists);if(bunDir!==null)roots.bun=bunDir;return withIsolatedCwd((cwd)=>{let probeDir=(pm,args)=>{let invocation=resolvePmInvocation(pm,args,platform,env,isFile);if(invocation===null)return null;let stdout=runIsolatedProbe(cwd,invocation,env,spawnFn);if(stdout===null)return null;let line=stdout.split(/\r?\n/)[0]?.trim()??"";if(line===""||!pathExists(line))return null;return safeRealpath(line)},pnpmRoot=probeDir("pnpm",["root","-g"]);if(pnpmRoot!==null)roots.pnpm=pnpmRoot;let npmRoot=probeDir("npm",["root","-g"]);if(npmRoot!==null)roots.npm=npmRoot;let yarnVerInv=resolvePmInvocation("yarn",["--version"],platform,env,isFile),yarnVer=yarnVerInv!==null?runIsolatedProbe(cwd,yarnVerInv,env,spawnFn):null;if(yarnVer!==null&&!isYarnBerryVersion(yarnVer)){let yarnDir=probeDir("yarn",["global","dir"]);if(yarnDir!==null)roots.yarn=yarnDir}}),roots}function executeUpgradePlan(plan,env=process.env,spawnFn=spawnSync){return withIsolatedCwd((cwd)=>{let res=spawnFn(plan.command,plan.args,{cwd,env:buildIsolatedEnv(env,plan.envOverlay),stdio:"inherit",...plan.windowsVerbatimArguments===!0?{windowsVerbatimArguments:!0}:{}});return{status:res.status,signal:res.signal,error:res.error}})}import{existsSync as existsSync3,readFileSync as readFileSync3}from"node:fs";function sanitize(raw){return raw.replace(/\p{Cc}/gu," ").replace(/\s+/g," ").trim()}function formatVersionLabel(spec){return/^\d/.test(spec)?`v${spec}`:spec}function defaultReadText3(path){try{return readFileSync3(path,"utf8")}catch{return null}}function ephemeralHintCommand(runner,packageName){switch(runner){case"bunx":return`bunx ${packageName}@latest`;case"npx":return`npx ${packageName}@latest`;case"pnpm-dlx":return`pnpm dlx ${packageName}@latest`;case"yarn-dlx":return`yarn dlx ${packageName}@latest`;case"deno":return`deno run -A npm:${packageName}@latest`}}function localProjectHintCommand(pm,packageName){switch(pm){case"bun":return`bun add -D ${packageName}@latest`;case"pnpm":return`pnpm add -D ${packageName}@latest`;case"yarn":return`yarn add -D ${packageName}@latest`;case"npm":return`npm install -D ${packageName}@latest`}}function describeOrigin(origin){switch(origin.kind){case"global":return`${origin.pm} 全局安装 (${origin.reason})`;case"ephemeral":return`${origin.runner} 临时运行 (${origin.reason})`;case"source":return`本地源码开发态 (${origin.packageRoot})`;case"local-project":return`项目本地依赖 (${origin.projectDir})`;case"unknown":return`未知安装位置 (${origin.packageRoot})`}}function warnCrossPmOverride(origin,targetPm,io){if(origin.kind==="global"&&origin.pm!==targetPm){io.out(`注意: 当前命令实际由 ${origin.pm} 全局安装, 改用 ${targetPm} 安装会在磁盘产生双份副本, PATH 靠前的旧副本可能遮蔽新版本!`);return}if(origin.kind==="source"){io.out(`注意: 当前运行在本地源码工作树 (${origin.packageRoot}), 通过 ${targetPm} 全局安装会产生独立全局副本, 请核对 PATH 优先级避免版本阴影!`);return}if(origin.kind==="local-project")io.out(`注意: 当前运行在项目本地依赖 (${origin.projectDir}), 通过 ${targetPm} 全局安装不会更新项目本地依赖, 且可能被本地副本遮蔽!`)}function resolveOrigin(meta,deps){let env=deps.env??process.env,pathExists=deps.pathExists??existsSync3,platform=deps.platform??process.platform,rawPaths=[meta.rawPackageRoot],entryArg=deps.argvEntry??process.argv[1];if(typeof entryArg==="string"&&entryArg!=="")rawPaths.push(entryArg);let firstPass=detectInstallOriginFromPath({packageRoot:meta.packageRoot,rawPaths,env,pathExists});if(!(firstPass.kind==="unknown"||firstPass.kind==="local-project"||firstPass.kind==="global"&&firstPass.reason===LIB_NODE_MODULES_HEURISTIC_REASON))return firstPass;if(meta.packageRoot.replaceAll("\\","/").toLowerCase().includes("/node_modules/")){let globalRoots=deps.probeRoots!==void 0?deps.probeRoots():probeGlobalRoots(platform,env,deps.spawnFn,{homeDir:deps.homeDir,readText:deps.readText,pathExists,isFile:deps.isFile});if(Object.keys(globalRoots).length>0)return detectInstallOriginFromPath({packageRoot:meta.packageRoot,rawPaths,env,pathExists,globalRoots})}return firstPass}function verifyPostUpgrade(input){let pkgText=(input.readText??defaultReadText3)(joinForPath(input.meta.packageRoot,"package.json")),unchangedAtOldRoot=!1;if(pkgText!==null)try{let parsed=JSON.parse(pkgText),afterVersion=typeof parsed.version==="string"?parsed.version:void 0;if(input.targetSpec!=="latest"&&compareSemver(input.meta.version,input.targetSpec)===-1&&afterVersion!==void 0&&afterVersion===input.meta.version)unchangedAtOldRoot=!0,input.io.out(`提示: 原安装目录 (${input.meta.packageRoot}) 的版本仍为 ${formatVersionLabel(afterVersion)}, 新版本可能安装到了其他位置, 请运行 ${input.binName} --version 核查。`)}catch{}let resolvedBin=resolveExecutableInPath(input.binName,input.platform,input.env,input.isFile);if(resolvedBin===null)return;let resolvedReal=safeRealpath(resolvedBin.path),oldGlobalPm=input.origin.kind==="global"&&input.origin.pm!==input.targetPm?input.origin.pm:null,isCrossGlobal=oldGlobalPm!==null,pointsToOldRoot=isWithinDir(resolvedReal,input.meta.packageRoot),pointsToOldPm=!1;if(oldGlobalPm!==null){let binOrigin=detectInstallOriginFromPath({packageRoot:resolvedReal,rawPaths:[resolvedBin.path],env:input.env,pathExists:()=>!1});pointsToOldPm=binOrigin.kind==="global"&&binOrigin.pm===oldGlobalPm}if(pointsToOldPm||pointsToOldRoot&&(isCrossGlobal||input.origin.kind==="source"||unchangedAtOldRoot))input.io.out(`提示: 当前 PATH 中的 ${input.binName} 仍指向旧路径 (${resolvedBin.path}), 可能遮蔽 ${input.targetPm} 新安装的版本, 请检查 PATH 优先级。`)}async function handleNonGlobalOrigin(ctx){let{meta,origin,hasExplicitRegistry,io,fetchVersion,registry}=ctx;if(io.out(`当前版本: ${meta.name}@${meta.version}`),io.out(`安装方式: ${describeOrigin(origin)}`),meta.isPrivate!==!0||hasExplicitRegistry){let remote=await fetchVersion(registry);if(remote.ok){let cmp=compareSemver(meta.version,remote.version),status;if(cmp===-1)status=`发现新版本 ${remote.version} (源: ${remote.registry})`;else if(cmp===null)status=`远端版本为 ${remote.version} (无法按 SemVer 比较, 源: ${remote.registry})`;else status=`远端最新版为 ${remote.version} (源: ${remote.registry})`;io.out(`版本检查: ${status}`)}else if(remote.code!=="not-found")io.out(`版本检查: 暂未获取远端版本 (${sanitize(remote.message)})`)}if(origin.kind==="source")return io.out("更新方式: 当前运行在本地源码工作树, 不通过包管理器覆盖。"),io.out(" 请在仓库根目录运行: git pull && bun install && bun run build"),io.out(" 若要通过包管理器安装全局发布版, 可显式指定 --pm <bun|npm|pnpm|yarn|volta>"),0;if(origin.kind==="ephemeral")return io.out(`更新方式: 当前经 ${origin.runner} 临时运行, 无需原地升级。`),io.out(` 下次获取最新版请运行: ${ephemeralHintCommand(origin.runner,meta.name)}`),io.out(" 若希望改为全局安装, 可运行带 --pm <bun|npm|pnpm|yarn|volta> 的 update 或直接全局安装"),0;return io.out(`更新方式: 当前作为项目本地依赖运行 (${origin.projectDir}), 为避免静默改写项目锁文件, 不自动覆盖。`),io.out(` 请在项目目录执行: ${localProjectHintCommand(origin.suggestedPm,meta.name)}`),0}function readPackageMeta(entryMetaUrl){let entryPath=fileURLToPath(entryMetaUrl),rawPackageRoot=dirname(dirname(entryPath)),packageRoot=safeRealpath(rawPackageRoot),pkgPath=join2(packageRoot,"package.json"),parsed=JSON.parse(readFileSync4(pkgPath,"utf8"));if(typeof parsed.name!=="string"||parsed.name==="")throw Error(`无法从 ${pkgPath} 读取合法包名`);let version=typeof parsed.version==="string"&&parsed.version!==""?parsed.version:"0.0.0";return{name:parsed.name,version,isPrivate:parsed.private===!0,rawPackageRoot,packageRoot}}function performUpgrade(ctx){let{binName,meta,origin,targetPm,targetSpec,opts,io,deps}=ctx,platform=deps.platform??process.platform,env=deps.env??process.env,yarnVersion=null;if(targetPm==="yarn")yarnVersion=deps.probeYarn!==void 0?deps.probeYarn():probeYarnVersion(platform,env,deps.spawnFn);let built=buildUpgradePlan({pm:targetPm,packageName:meta.name,targetSpec,explicitRegistry:opts.registry,platform,env,isFile:deps.isFile,yarnVersion});if(!built.ok){if(io.err(`无法自动更新: ${built.reason}`),built.fallbackCommand!==void 0)io.err(` 手动更新命令: ${built.fallbackCommand}`);return 1}io.out(`即将执行: ${built.plan.displayCommand}`);let result=(deps.execPlan??executeUpgradePlan)(built.plan,env,deps.spawnFn);if(result.error!==void 0)return io.err(`更新命令启动失败: ${sanitize(result.error.message)}`),io.err(` 手动更新命令: ${built.plan.displayCommand}`),1;if(result.signal!==void 0&&result.signal!==null)return io.err(`更新进程被信号中断 (${result.signal})`),io.err(` 手动更新命令: ${built.plan.displayCommand}`),1;if(result.status!==0){if(io.err(`更新失败 (${targetPm} 退出码 ${String(result.status??1)})`),platform==="win32")io.err(` Windows 提示: 当前正在运行的 ${binName} 自身可执行/shim 文件可能被系统锁定 (EBUSY / EPERM), 请退出当前命令并关闭其他占用终端后直接执行下方命令:`);if(targetPm==="pnpm")io.err(" pnpm 提示: 若提示未配置全局 bin 目录, 请检查 PNPM_HOME 环境变量或先运行 pnpm setup。");return io.err(` 手动更新命令: ${built.plan.displayCommand}`),1}return io.out(`已通过 ${targetPm} 更新 ${meta.name} 至 ${formatVersionLabel(targetSpec)} ✓`),verifyPostUpgrade({binName,meta,origin,targetPm,targetSpec,platform,env,readText:deps.readText,isFile:deps.isFile,io}),0}function handleFetchFailure(ctx){let{binName,meta,origin,targetPm,registry,remote,opts,io,deps}=ctx;if(opts.force&&!opts.check&&targetPm!==void 0)return io.err(`警示: 远端版本查询失败 (${sanitize(remote.message)})`),io.out(`强制重装模式 (--force): 跳过远端版本校验, 将直接通过 ${targetPm} 安装 ${meta.name}@latest`),performUpgrade({binName,meta,origin,targetPm,targetSpec:"latest",opts,io,deps});if(remote.code==="not-found")return io.err(`${meta.name} 尚未在 ${registry} 发布 (HTTP 404), 无法在线更新`+(meta.isPrivate?" (当前包标记为 private)":"")),io.err(" 若已发布到私有源, 请加 --registry <url> 后重试"),1;if(remote.code==="auth")io.err(`检查最新版本失败: ${sanitize(remote.message)}`),io.err(" 请先完成源登录或在 ~/.npmrc / ~/.bunfig.toml 配置同源访问 token, 或加 --force 直接委托包管理器安装");else io.err(`检查最新版本失败: ${sanitize(remote.message)}`);if(targetPm!==void 0){let cmd=formatUpgradeDisplayCommand(targetPm,meta.name,"latest",opts.registry);io.err(` 可稍后重试或手动执行: ${cmd}`)}return 1}async function runSelfUpdate(options){let io=options.io??{out:(line)=>process.stdout.write(`${line}
|
|
3
3
|
`),err:(line)=>process.stderr.write(`${line}
|
|
4
4
|
`)},deps=options.deps??{},parsed=parseUpdateArgs(options.argv);if(!parsed.ok)return io.err(`参数错误: ${parsed.message}`),1;let opts=parsed.options,meta;try{if(options.meta!==void 0)meta=options.meta;else if(options.entryMetaUrl!==void 0)meta=readPackageMeta(options.entryMetaUrl);else throw Error("缺少 entryMetaUrl 或 meta, 无法定位当前包信息")}catch(error){let msg=error instanceof Error?error.message:String(error);return io.err(`读取当前包信息失败: ${sanitize(msg)}`),1}if(opts.help){for(let line of formatUpdateHelp(options.binName,meta.name).split(`
|
|
@@ -30,13 +30,13 @@ import{existsSync as existsSync6}from"node:fs";import{resolve as resolve2}from"n
|
|
|
30
30
|
`)end+=1;let start=expandOverLeadingDocComment(out,lazyDecl.index),withoutBlock=out.slice(0,start)+out.slice(end);if(!withoutBlock.includes("resolveConformanceCliSrc")){let withoutImport=withoutBlock.replace(LAZY_CONFORMANCE_IMPORT,"");out=withoutImport.includes("resolveProductPairs")?withoutBlock:withoutImport}}return out}function assertStepSurgery(source,pruned,steps,entries){let expected=[...entries.keys()].filter((name)=>!steps.includes(name)),actual=[...locateStepEntries(pruned).keys()];if(actual.length!==expected.length||expected.some((name)=>!actual.includes(name)))throw Error(`步骤手术自检未过: STEPS 表期望 [${expected.join(", ")}], 实得 [${actual.join(", ")}]`);for(let name of steps)if(pruned.includes(`'${name}'`))throw Error(`步骤手术自检未过: '${name}' 仍残留在 ${CI_SCRIPT}`);assertBracketsBalanced(pruned),assertBracketsBalanced(source)}function assertBracketsBalanced(source){let closers={"(":")","[":"]","{":"}"},stack=[];for(let{char}of codeChars(source))if(char in closers)stack.push(closers[char]);else if(char===")"||char==="]"||char==="}"){if(stack.pop()!==char)throw Error(`括号配平自检未过: ${CI_SCRIPT} 出现未配对闭合符 ${char}`)}if(stack.length>0)throw Error(`括号配平自检未过: ${CI_SCRIPT} 有 ${stack.length} 个未闭合的 ${stack.join("")}`)}function findMatchingBrace(source,openIndex){let depth=0;for(let{char,index}of codeChars(source,openIndex))if(char==="{")depth+=1;else if(char==="}"){if(depth-=1,depth===0)return index}throw Error(`${CI_SCRIPT} 形态预期不符: 第 ${openIndex} 字符起的 \`{\` 未闭合`)}class TargetRejectedError extends Error{}function assertTargetAvailable(targetDir){if(!existsSync5(targetDir))return;if(!statSync2(targetDir).isDirectory())throw new TargetRejectedError(`目标路径已存在且不是目录: ${targetDir}`);if(readdirSync2(targetDir).length>0)throw new TargetRejectedError(`目标目录已存在且非空: ${targetDir} (不覆盖已有目录; 请换一个目录或先清空)`)}function substituteVocabulary(targetDir,vocabulary){for(let rel of listTemplateFiles(targetDir)){let srcPath=join5(targetDir,rel),{mode}=statSync2(srcPath),next=renderTemplate(rel,vocabulary,TEMPLATE_VOCABULARY),source=readFileSync6(srcPath,"utf8"),rendered=renderTemplate(source,vocabulary,TEMPLATE_VOCABULARY);if(next===rel){if(rendered!==source)writeFileSync2(srcPath,rendered,{mode});continue}let destination=join5(targetDir,next);if(mkdirSync(dirname2(destination),{recursive:!0}),writeFileSync2(destination,rendered,{mode}),process.platform!=="win32")chmodSync(destination,mode);rmSync3(srcPath)}for(let rel of listTemplateDirs(targetDir).sort((left,right)=>right.length-left.length)){let full=join5(targetDir,rel);if(existsSync5(full)&&readdirSync2(full).length===0)rmdirSync(full)}}function restoreCarrierNames(targetDir){for(let rel of listTemplateFiles(targetDir)){let restored=fromCarrierPath(rel);if(restored===rel)continue;renameSync(join5(targetDir,rel),join5(targetDir,restored))}}async function formatTree(root){let configPath=join5(root,".prettierrc");if(!existsSync5(configPath))throw Error("模板缺少 .prettierrc: 无可用的格式化收口配置 (模板形态预期不符)");let prettier=await import("prettier"),prettierPlugin=createRequire(import.meta.url).resolve("@trivago/prettier-plugin-sort-imports"),options={...JSON.parse(readFileSync6(configPath,"utf8")),plugins:[prettierPlugin]},ignorePath=join5(root,".prettierignore"),fileInfoOptions={plugins:[prettierPlugin],resolveConfig:!1};if(existsSync5(ignorePath))fileInfoOptions.ignorePath=ignorePath;for(let rel of listTemplateFiles(root)){let filePath=join5(root,rel),info=await prettier.getFileInfo(filePath,fileInfoOptions);if(info.ignored||info.inferredParser===null)continue;let source=readFileSync6(filePath,"utf8"),output;try{output=await prettier.format(source,{...options,filepath:filePath})}catch(error){throw Error(`格式化收口失败于 ${rel}: ${error instanceof Error?error.message:String(error)}`)}if(output!==source)writeFileSync2(filePath,output)}}function assertNoResidual(targetDir,vocabulary,original){let placeholderLiterals=Object.values(TEMPLATE_VOCABULARY).filter((value)=>typeof value==="string"&&value.length>0),leftovers=[];for(let rel of listTemplateFiles(targetDir)){let text=readFileSync6(join5(targetDir,rel),"utf8");if(containsResidual(rel,TEMPLATE_VOCABULARY)||containsResidual(text,TEMPLATE_VOCABULARY)||placeholderLiterals.some((literal)=>rel.includes(literal)||text.includes(literal)))leftovers.push(`${rel} (模板占位形态残留)`);if(containsResidual(rel,original,vocabulary)||containsResidual(text,original,vocabulary))leftovers.push(`${rel} (原项目词汇残留)`)}if(leftovers.length>0)throw Error(`二道自检未过, 生成物仍含未替换形态:
|
|
31
31
|
${leftovers.join(`
|
|
32
32
|
`)}`)}async function runHooks(hooks,targetDir){let executed=[];if(hooks.gitInit!==void 0)await hooks.gitInit(targetDir),executed.push("git init");if(hooks.install!==void 0)await hooks.install(targetDir),executed.push("依赖安装");return executed}async function generateProject(options){let{templateDir,targetDir,vocabulary,tier,original}=options;return assertTargetAvailable(targetDir),cpSync(templateDir,targetDir,{recursive:!0}),restoreCarrierNames(targetDir),pruneTemplate(targetDir,removeRulesFor(tier)),substituteVocabulary(targetDir,vocabulary),await formatTree(targetDir),assertNoResidual(targetDir,vocabulary,original),{executed:await runHooks(options.hooks??{},targetDir)}}var WIN32_ABS_DIR_RE=/^(?:[A-Za-z]:[/\\]|\\\\[^\\]+\\[^\\]+)/,WIN32_HOOK_EXTS=[".exe",".com",".cmd"],isFileAt=(filePath)=>{try{return statSync2(filePath).isFile()}catch{return!1}};function cleanInstallEnv(sourceEnv=process.env){let env={};for(let[key,value]of Object.entries(sourceEnv)){if(value===void 0)continue;let lower=key.toLowerCase();if(lower==="npm_execpath"||lower.startsWith("npm_lifecycle_"))continue;env[key]=value}return env}var CMD_META_OR_SPACE_RE2=/[\s&|<>^()%!]/,CMD_FORBIDDEN_RE2=/[\r\n\0"]/;function wrapDoubleQuotes2(segment){return`"${segment.replace(/(\\+)$/,"$1$1")}"`}function escapePercentAndBang(value,prefix){let out="",buf="";for(let ch of value)if(ch==="%"||ch==="!"){if(buf!=="")out+=wrapDoubleQuotes2(buf),buf="";out+=`${prefix}${ch}`}else buf+=ch;if(buf!=="")out+=wrapDoubleQuotes2(buf);return out}function escapeBatchPath2(batchPath){if(batchPath===""||CMD_FORBIDDEN_RE2.test(batchPath))throw Error("Windows 批处理路径包含非法控制字符或双引号, 拒绝经 cmd.exe 执行");if(!/[%!]/.test(batchPath))return wrapDoubleQuotes2(batchPath);return escapePercentAndBang(batchPath,"^")}function escapeBatchArg2(arg){if(CMD_FORBIDDEN_RE2.test(arg))throw Error("Windows 批处理参数包含非法控制字符或双引号, 拒绝经 cmd.exe 执行");if(arg==="")return'""';if(!CMD_META_OR_SPACE_RE2.test(arg))return arg;if(!/[%!]/.test(arg))return wrapDoubleQuotes2(arg);return escapePercentAndBang(arg,"^^^")}function buildBatchInvocation(batchPath,args,env={}){let escapedPath=escapeBatchPath2(batchPath),escapedArgs=args.map((arg)=>escapeBatchArg2(arg)),inner=escapedArgs.length===0?escapedPath:`${escapedPath} ${escapedArgs.join(" ")}`;return{command:env.ComSpec?.trim()||env.COMSPEC?.trim()||"cmd.exe",args:["/d","/s","/c",`"${inner}"`],windowsVerbatimArguments:!0}}function resolveHookCommand(name,options={}){if((options.platform??process.platform)!=="win32")return{command:name,isBatch:!1};let pathEnv=options.pathEnv??process.env.PATH??process.env.Path??"",fileProbe=options.fileProbe??isFileAt;for(let raw of pathEnv.split(";")){let dir=raw.length>1&&raw.startsWith('"')&&raw.endsWith('"')?raw.slice(1,-1):raw;if(dir===""||!WIN32_ABS_DIR_RE.test(dir))continue;for(let ext of WIN32_HOOK_EXTS){let candidate=win324.join(dir,`${name}${ext}`);if(fileProbe(candidate))return{command:candidate,isBatch:ext===".cmd"}}}return{command:name,isBatch:!1}}var defaultSpawner=(command,args,options)=>spawnSync2(command,args,options);function createGitInitHook(spawner=defaultSpawner){return(targetDir)=>{let env=cleanGitEnv(),resolved=resolveHookCommand("git",{pathEnv:env.PATH??env.Path??""}),invocation=resolved.isBatch?buildBatchInvocation(resolved.command,["init","--quiet"],env):{command:resolved.command,args:["init","--quiet"],windowsVerbatimArguments:!1},result=spawner(invocation.command,invocation.args,{cwd:targetDir,encoding:"utf8",env,windowsVerbatimArguments:invocation.windowsVerbatimArguments});if(result.error!==void 0){if(result.error.code==="ENOENT")throw Error("git init 失败: 未找到 git 可执行文件 (请先安装 git, 或使用 --no-git 跳过)");throw Error(`git init 启动失败: ${result.error.message}`)}if(result.status!==0){let rawStderr=result.stderr,stderr=(typeof rawStderr==="string"?rawStderr:rawStderr?.toString("utf8")??"").trim(),detail=stderr.length>0?`: ${stderr}`:"";throw Error(`git init 失败 (退出码 ${String(result.status??result.signal)})${detail}`)}}}function createInstallHook(spawner=defaultSpawner){return(targetDir)=>{process.stdout.write(` 安装依赖 (bun install) ...
|
|
33
|
-
`);let env=cleanInstallEnv(),resolved=resolveHookCommand("bun",{pathEnv:env.PATH??env.Path??""}),invocation=resolved.isBatch?buildBatchInvocation(resolved.command,["install"],env):{command:resolved.command,args:["install"],windowsVerbatimArguments:!1},result=spawner(invocation.command,invocation.args,{cwd:targetDir,stdio:"inherit",env,windowsVerbatimArguments:invocation.windowsVerbatimArguments});if(result.error!==void 0){if(result.error.code==="ENOENT")throw Error("依赖安装失败: 未找到 bun 可执行文件 (生成物为 bun 工程, 请先安装 bun: https://bun.sh, "+`或使用 --no-install 跳过后进入 ${targetDir} 手动安装)`);throw Error(`依赖安装启动失败: ${result.error.message}; 产物已生成完整, 可进入 ${targetDir} 重跑 bun install`)}if(result.status!==0)throw Error(`依赖安装失败 (退出码 ${String(result.status??result.signal)}); 产物已生成完整, `+`可进入 ${targetDir} 重跑 bun install`)}}
|
|
34
|
-
`)},
|
|
35
|
-
`);function buildHooks(options){let hooks={};if(options.git)hooks.gitInit=createGitInitHook();if(options.install)hooks.install=createInstallHook();return hooks}function nextSteps(targetDir,installed,tier,projectName){let lines=["","下一步:",` cd ${targetDir}`];if(!installed)lines.push(" bun install # 安装依赖");if(tier==="full")lines.push(` # full 档: 转写契约套件只带机制, 契约与语料需自填 (packages/${projectName}/docs/protocol/);`),lines.push(" # 填好前 bun run ci 的 lint:coverage 与 conformance 步骤会红");return lines.push(" bun run ci # 验证全绿"),lines.push(" 然后从 docs/README.md (文档总索引) 读起, 开始改造。"),lines.join(`
|
|
33
|
+
`);let env=cleanInstallEnv(),resolved=resolveHookCommand("bun",{pathEnv:env.PATH??env.Path??""}),invocation=resolved.isBatch?buildBatchInvocation(resolved.command,["install"],env):{command:resolved.command,args:["install"],windowsVerbatimArguments:!1},result=spawner(invocation.command,invocation.args,{cwd:targetDir,stdio:"inherit",env,windowsVerbatimArguments:invocation.windowsVerbatimArguments});if(result.error!==void 0){if(result.error.code==="ENOENT")throw Error("依赖安装失败: 未找到 bun 可执行文件 (生成物为 bun 工程, 请先安装 bun: https://bun.sh, "+`或使用 --no-install 跳过后进入 ${targetDir} 手动安装)`);throw Error(`依赖安装启动失败: ${result.error.message}; 产物已生成完整, 可进入 ${targetDir} 重跑 bun install`)}if(result.status!==0)throw Error(`依赖安装失败 (退出码 ${String(result.status??result.signal)}); 产物已生成完整, `+`可进入 ${targetDir} 重跑 bun install`)}}var WHITE=["255;255;255","255"],DARK_PALETTE={primary:["245;245;247","255"],secondary:["161;161;166","248"],tertiary:["110;110;115","242"],separator:["56;56;58","238"],blue:["10;132;255","39"],cyan:["100;210;255","81"]},LIGHT_PALETTE={primary:["29;29;31","234"],secondary:["110;110;115","242"],tertiary:["142;142;147","246"],separator:["210;210;215","252"],blue:["0;122;255","27"],cyan:["0;102;204","26"]},TRUECOLOR_TERMS=["iterm","vscode","ghostty","warp","wezterm"];function supportsTrueColor(){if(process.env.WT_SESSION)return!0;let ct=(process.env.COLORTERM??"").toLowerCase();if(ct.includes("truecolor")||ct.includes("24bit"))return!0;let termProg=(process.env.TERM_PROGRAM??"").toLowerCase();return TRUECOLOR_TERMS.some((term)=>termProg.includes(term))}function isLightTerminal(){let fgbg=process.env.COLORFGBG;if(!fgbg)return!1;let parts=fgbg.split(";"),bg=Number(parts[parts.length-1]);return Number.isFinite(bg)&&bg>=7&&bg!==8}function stdoutSupportsColor(){return process.stdout.isTTY===!0&&!process.env.NO_COLOR&&process.env.TERM?.toLowerCase()!=="dumb"}function createStyler(color){let theme=isLightTerminal()?LIGHT_PALETTE:DARK_PALETTE,trueColor=color&&supportsTrueColor(),fg=(tok,text,bold=!1)=>{if(!color)return text;let b=bold?"1;":"";return trueColor?`\x1B[${b}38;2;${tok[0]}m${text}\x1B[0m`:`\x1B[${b}38;5;${tok[1]}m${text}\x1B[0m`};return{badge:(text)=>{let label=` ${text} `;if(!color)return label;return trueColor?`\x1B[1;38;2;${WHITE[0]};48;2;${theme.blue[0]}m${label}\x1B[0m`:`\x1B[1;38;5;${WHITE[1]};48;5;${theme.blue[1]}m${label}\x1B[0m`},title:(t)=>fg(theme.primary,t,!0),primary:(t)=>fg(theme.primary,t,!1),muted:(t)=>fg(theme.secondary,t,!1),dim:(t)=>fg(theme.tertiary,t,!1),rule:(t)=>fg(theme.separator,t,!1),section:(t)=>fg(theme.blue,t,!0),token:(t)=>fg(theme.cyan,t,!1)}}var VARIABLE_OPTIONS=[{flag:"--name",arg:"<名>",desc:"项目名 (kebab-case; 缺省取目录 basename)"},{flag:"--scope",arg:"<@scope>",desc:"npm scope (缺省无 scope, 裸包名)"},{flag:"--bin",arg:"<名>",desc:"主命令名 (缺省由项目名派生短形态)"},{flag:"--owner",arg:"<名>",desc:"仓库所有者 (缺省取 git 全局 user.name)"},{flag:"--repo",arg:"<url>",desc:"仓库地址 (缺省 https://github.com/<owner>/<name>)"}],CONTROL_OPTIONS=[{flag:"--tier",arg:"<档>",desc:"装备档位: core | standard | full (缺省 standard)"},{flag:"--no-git",desc:"跳过 git init (默认执行)"},{flag:"--no-install",desc:"跳过依赖安装 (默认执行)"},{flag:"--yes",desc:"全部取默认值, 零交互"}],META_OPTIONS=[{flag:"-V, --version",desc:"显示当前版本号"},{flag:"-h, --help",desc:"显示本帮助"}],LEFT_COL=20,RULE_WIDTH=76;function displayWidth(text){let width=0;for(let ch of text){let code=ch.codePointAt(0)??0,wide=code>=11904&&code<=42191||code>=63744&&code<=64255||code>=65280&&code<=65376;width+=wide?2:1}return width}function formatOptionRow(row,s){let plain=row.arg===void 0?row.flag:`${row.flag} ${row.arg}`,pad=" ".repeat(Math.max(2,LEFT_COL-displayWidth(plain)));return` ${row.arg===void 0?s.token(row.flag):`${s.token(row.flag)} ${s.dim(row.arg)}`}${pad}${s.muted(row.desc)}`}function formatHelpText(color){let s=createStyler(color),varRows=VARIABLE_OPTIONS.map((row)=>formatOptionRow(row,s)),ctrlRows=CONTROL_OPTIONS.map((row)=>formatOptionRow(row,s)),metaRows=META_OPTIONS.map((row)=>formatOptionRow(row,s));return["",` ${s.badge("CREATE-CLIS")} ${s.title("clis 集合仓脚手架")}`,` ${s.muted("从 clis 集合仓骨架快照生成独立的新双包集合仓, 带能力档位与全绿 CI。")}`,` ${s.rule("─".repeat(RULE_WIDTH))}`,"",` ${s.section("用法")}`,` ${s.title("create-clis")} ${s.dim("[目录] [选项]")}`,` ${s.title("create-clis")} ${s.dim("<子命令> [选项]")}`,"",` ${s.section("子命令")}`,` ${s.title("update")}${" ".repeat(LEFT_COL-6)}${s.muted("自动识别安装器升级到最新版 (--check 仅检查)")}`,"",` ${s.section("模板变量")}`,...varRows,"",` ${s.section("生成选项")}`,...ctrlRows,"",...metaRows,"",` ${s.section("说明")}`,` ${s.primary("目标目录")} ${s.muted("缺省为当前目录下以项目名命名的子目录; 非空目录直接拒绝 (不覆盖)")}`,` ${s.primary("调用约定")} ${s.muted("经 npm create 调用时旗标写在 -- 之后 (npm create clis -- --tier core)")}`,""].join(`
|
|
34
|
+
`)}import{createInterface}from"node:readline/promises";import{spawnSync as spawnSync3}from"node:child_process";import{basename,resolve}from"node:path";var DEFAULT_TIER="standard",KEBAB_NAME=/^[a-z0-9]+(-[a-z0-9]+)*$/,SLUG_LIKE=/^[a-zA-Z0-9](?:[a-zA-Z0-9._-]*[a-zA-Z0-9])?$/,SCOPE=/^@[a-z0-9][a-z0-9._-]*$/,REPO_URL=/^[a-z][a-z0-9+.-]*:\/\/[^\s/]+\/[^\s]+$/i;function validateName(name){if(name.length===0)return"项目名不能为空";if(!KEBAB_NAME.test(name))return`项目名 ${JSON.stringify(name)} 不是 kebab-case (只允许小写字母 / 数字, 以 - 分隔, 如 my-tool)`;return null}function validateBinName(bin){if(bin.length===0)return"bin 名不能为空";if(!SLUG_LIKE.test(bin))return`bin 名 ${JSON.stringify(bin)} 不可用作命令 (需字母 / 数字起止, 中间可含 . _ -, 不得含空白 / 路径分隔符 / shell 元字符)`;return null}function validateScope(scope){if(scope.length===0)return null;if(!SCOPE.test(scope))return`scope ${JSON.stringify(scope)} 不是合法 npm scope (需 @ 开头的小写名, 如 @me)`;return null}function validateOwner(owner){if(owner.length===0)return"owner 不能为空";if(!SLUG_LIKE.test(owner))return`owner ${JSON.stringify(owner)} 含不可用于仓库地址的字符 (只接受字母 / 数字 / . _ -)`;return null}function validateRepoUrl(url){if(url.length===0)return"仓库地址不能为空";if(!REPO_URL.test(url))return`仓库地址 ${JSON.stringify(url)} 不是合法 URL (需 scheme://host/path, 如 https://github.com/me/my-tool)`;return null}function provided(value){return value!==void 0&&value.length>0?value:void 0}function deriveBinName(name){let segments=name.split("-").filter((segment)=>segment.length>0);if(segments.length<=2)return name;let head=segments[0],initials=segments.slice(1).map((segment)=>segment.charAt(0)).join("");return`${head}-${initials}`}var VALUE_FLAGS={"--name":"name","--scope":"scope","--bin":"bin","--owner":"owner","--repo":"repo"},TIERS=new Set(["core","standard","full"]);function isTier(value){return TIERS.has(value)}function valueTokenAt(argv,index){let next=argv[index+1];if(next===void 0||next.startsWith("-"))return;return next}function parseFlags(argv){let options={git:!0,install:!0,yes:!1},afterDashDash=!1;for(let index=0;index<argv.length;index+=1){let token=argv[index];if(!afterDashDash&&token==="--"){afterDashDash=!0;continue}if(afterDashDash||!token.startsWith("-")){if(options.dir!==void 0)return{error:`只接受一个目标目录位置参数, 多余的: ${JSON.stringify(token)}`};options.dir=token;continue}if(token==="-h")return options.help=!0,options;if(token==="-V")return options.version=!0,options;if(!token.startsWith("--"))return{error:`未知旗标 ${JSON.stringify(token)}`};let inlineIndex=token.indexOf("="),flag=inlineIndex===-1?token:token.slice(0,inlineIndex),inline=inlineIndex===-1?void 0:token.slice(inlineIndex+1);if(flag==="--help"||flag==="--version"){if(inline!==void 0)return{error:`开关旗标 ${flag} 不接受值`};if(flag==="--help")options.help=!0;else options.version=!0;return options}if(flag==="--yes"||flag==="--no-git"||flag==="--no-install"){if(inline!==void 0)return{error:`开关旗标 ${flag} 不接受值`};if(flag==="--yes")options.yes=!0;else if(flag==="--no-git")options.git=!1;else options.install=!1;continue}if(flag==="--tier"){let value=inline??valueTokenAt(argv,index);if(value===void 0)return{error:"旗标 --tier 缺少值 (core | standard | full)"};if(inline===void 0)index+=1;if(!isTier(value))return{error:`旗标 --tier 只接受 core / standard / full, 收到 ${JSON.stringify(value)}`};options.tier=value;continue}let target=VALUE_FLAGS[flag];if(target===void 0)return{error:`未知旗标 ${JSON.stringify(flag)}`};let value=inline??valueTokenAt(argv,index);if(value===void 0)return{error:`旗标 ${flag} 缺少值`};if(inline===void 0)index+=1;options[target]=value}if(options.name===void 0&&options.dir!==void 0){let derived=basename(options.dir),fallback=derived==="."||derived===".."?basename(resolve(options.dir)):derived;if(fallback.length>0)options.suggestedName=fallback}return options}function resolveVocabulary(opts,env){let name=provided(opts.name)??provided(opts.suggestedName);if(name===void 0)return{error:"缺少项目名: 用位置参数或 --name 提供 (kebab-case, 如 my-tool)"};let nameError=validateName(name);if(nameError!==null)return{error:nameError};let scope=provided(opts.scope)??"",scopeError=validateScope(scope);if(scopeError!==null)return{error:scopeError};let binName=provided(opts.bin)??deriveBinName(name),binError=validateBinName(binName);if(binError!==null)return{error:binError};let owner=provided(opts.owner)??provided(env.gitUserName??void 0);if(owner===void 0)return{error:"缺少仓库所有者: --owner 未给出, 且读不到 git 全局 user.name"};let ownerError=validateOwner(owner);if(ownerError!==null)return{error:ownerError};let repoUrl=provided(opts.repo)??`https://github.com/${owner}/${name}`,repoError=validateRepoUrl(repoUrl);if(repoError!==null)return{error:repoError};return{name,scope,binName,owner,repoUrl}}function readGitUserName(){let result=spawnSync3("git",["config","--global","user.name"],{encoding:"utf8"});if(result.status!==0)return null;let value=result.stdout.trim();return value.length>0?value:null}function collected(result){return"error"in result?{state:"error",error:result.error}:{state:"collected",vocabulary:result}}async function askValidated(io,question,hint,fallback,validate){for(;;){let answer=await io.ask(question,hint);if(answer===null)return null;let trimmed=answer.trim(),value=trimmed.length>0?trimmed:fallback;if(value===void 0){io.print(` ✗ ${question} 必填, 不能留空`);continue}let error=validate(value);if(error===null)return value;io.print(` ✗ ${error}`)}}async function askAll(io,env,seed={git:!0,install:!0,yes:!1}){try{if(seed.yes)return collected(resolveVocabulary(seed,env));let seedName=provided(seed.name),rawSuggested=provided(seed.suggestedName),seedScope=provided(seed.scope),seedBin=provided(seed.bin),seedOwner=provided(seed.owner),seedRepo=provided(seed.repo),seededChecks=[[seedName,validateName],[seedScope,validateScope],[seedBin,validateBinName],[seedOwner,validateOwner],[seedRepo,validateRepoUrl]];for(let[value,validate]of seededChecks){if(value===void 0)continue;let error=validate(value);if(error!==null)return{state:"error",error}}let usableSuggested=rawSuggested!==void 0&&validateName(rawSuggested)===null?rawSuggested:void 0;io.print("create-clis: 依次回答以下问题 (方括号内为默认值, 回车采用)");let name=seedName??usableSuggested;if(name===void 0){let answer=await askValidated(io,"项目名","必填, kebab-case, 如 my-tool",void 0,validateName);if(answer===null)return{state:"cancelled"};name=answer}let scope=seedScope;if(scope===void 0){let answer=await askValidated(io,"scope","回车跳过 (裸包名; 带 scope 时以 @ 开头, 如 @me)","",validateScope);if(answer===null)return{state:"cancelled"};scope=answer}let bin=seedBin;if(bin===void 0){let fallback=deriveBinName(name),answer=await askValidated(io,"bin 名",`默认: ${fallback}`,fallback,validateBinName);if(answer===null)return{state:"cancelled"};bin=answer}let owner=seedOwner;if(owner===void 0){let gitDefault=env.gitUserName!==null&&validateOwner(env.gitUserName)===null?env.gitUserName:void 0,answer=await askValidated(io,"owner",gitDefault===void 0?"必填 (读不到可用的 git 全局 user.name)":`默认: ${gitDefault}`,gitDefault,validateOwner);if(answer===null)return{state:"cancelled"};owner=answer}let repo=seedRepo;if(repo===void 0){let fallback=`https://github.com/${owner}/${name}`,answer=await askValidated(io,"仓库地址",`默认: ${fallback}`,fallback,validateRepoUrl);if(answer===null)return{state:"cancelled"};repo=answer}return collected(resolveVocabulary({...seed,name,scope,bin,owner,repo},env))}finally{io.close?.()}}function createPromptIO(){let buffered=[],rl=null,ended=!1,pending=null;function setStdinRef(shouldRef){let fn=shouldRef?process.stdin.ref:process.stdin.unref;if(typeof fn==="function")fn.call(process.stdin)}function ensure(){if(rl!==null)return rl;let created=createInterface({input:process.stdin,output:process.stdout});return created.on("line",(line)=>{if(pending===null){buffered.push(line);return}let resolve=pending;pending=null,setStdinRef(!1),resolve(line)}),created.on("close",()=>{if(ended=!0,pending===null)return;let resolve=pending;pending=null,setStdinRef(!1),resolve(null)}),created.on("SIGINT",()=>created.close()),rl=created,created}function readLine(prompt){if(ended){let bufferedLine=buffered.shift();if(bufferedLine===void 0)return Promise.resolve(null);return process.stdout.write(prompt),Promise.resolve(bufferedLine)}let created=ensure();created.setPrompt(prompt),created.prompt();let ready=buffered.shift();if(ready!==void 0)return Promise.resolve(ready);return setStdinRef(!0),new Promise((resolve)=>{pending=resolve})}return{ask(question,hint){let prompt=hint===void 0?` ${question} `:` ${question} [${hint}] `;return readLine(prompt)},print(line){process.stdout.write(`${line}
|
|
35
|
+
`)},close(){if(ended=!0,buffered.length=0,rl!==null){let current=rl;rl=null,current.close()}setStdinRef(!1)}}}function buildHooks(options){let hooks={};if(options.git)hooks.gitInit=createGitInitHook();if(options.install)hooks.install=createInstallHook();return hooks}function nextSteps(targetDir,installed,tier,projectName){let lines=["","下一步:",` cd ${targetDir}`];if(!installed)lines.push(" bun install # 安装依赖");if(tier==="full")lines.push(` # full 档: 转写契约套件只带机制, 契约与语料需自填 (packages/${projectName}/docs/protocol/);`),lines.push(" # 填好前 bun run ci 的 lint:coverage 与 conformance 步骤会红");return lines.push(" bun run ci # 验证全绿"),lines.push(" 然后从 docs/README.md (文档总索引) 读起, 开始改造。"),lines.join(`
|
|
36
36
|
`)}async function main(){let argv=process.argv.slice(2);if(argv[0]==="update")try{return await runSelfUpdate({binName:"create-clis",entryMetaUrl:import.meta.url,argv:argv.slice(1)})}catch(error){let message=error instanceof Error?error.message:String(error);return process.stderr.write(`更新失败: ${message}
|
|
37
37
|
`),1}let parsed=parseFlags(argv);if("error"in parsed)return process.stderr.write(`参数错误: ${parsed.error}
|
|
38
38
|
`),1;if(parsed.version)return process.stdout.write(`${readPackageMeta(import.meta.url).version}
|
|
39
|
-
`),0;if(parsed.help)return process.stdout.write(`${
|
|
39
|
+
`),0;if(parsed.help)return process.stdout.write(`${formatHelpText(stdoutSupportsColor())}
|
|
40
40
|
`),0;if(parsed.dir!==void 0){let precheckDir=resolve2(process.cwd(),parsed.dir);try{assertTargetAvailable(precheckDir)}catch(error){let message=error instanceof Error?error.message:String(error);return process.stderr.write(`生成失败: ${message}
|
|
41
41
|
`),1}}let env={gitUserName:readGitUserName()},outcome=await askAll(createPromptIO(),env,parsed);if(outcome.state==="cancelled")return process.stdout.write(`已取消
|
|
42
42
|
`),1;if(outcome.state==="error")return process.stderr.write(`${outcome.error}
|
package/dist/manifest.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"schemaVersion": 1,
|
|
3
|
-
"commit": "
|
|
3
|
+
"commit": "374f00a96c05abe244d0c35b76cff38e99e549a1",
|
|
4
4
|
"dirty": false,
|
|
5
|
-
"cliSha256": "
|
|
6
|
-
"builtAt": "2026-11-20T04:
|
|
5
|
+
"cliSha256": "560d58fa6081f0d3d86baec7a1d6e94f279e5e51424d7ac7d6af386e3fbe14af",
|
|
6
|
+
"builtAt": "2026-11-20T04:37:32.415Z"
|
|
7
7
|
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "create-clis",
|
|
3
|
-
"version": "1.
|
|
3
|
+
"version": "1.2.0",
|
|
4
4
|
"description": "Scaffold a standalone clis collection repository from the clis skeleton snapshot: capability tiers, generic vocabulary, green CI out of the box. clis 集合仓生成器。",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"cli",
|