@iyowei/rim-cli 0.0.0-stage → 0.0.1-stage
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +134 -2
- package/README.zh-CN.md +135 -0
- package/bin/bunfig.toml +5 -0
- package/bin/rim.mjs +433 -0
- package/dist/cli.js +163 -0
- package/dist/manifest.json +7 -0
- package/package.json +62 -4
package/dist/cli.js
ADDED
|
@@ -0,0 +1,163 @@
|
|
|
1
|
+
import{readFileSync as readFileSync16,realpathSync as realpathSync9}from"node:fs";import{dirname as dirname11,join as join18,resolve as resolve14}from"node:path";import{fileURLToPath as fileURLToPath2}from"node:url";import{spawnSync}from"node:child_process";import{existsSync,readFileSync}from"node:fs";import{join as join2,win32 as win322}from"node:path";function readUIntBE(buf,offset,byteLen){if(offset<0||byteLen<1||byteLen>8||offset+byteLen>buf.length)return null;let val=0;for(let i=0;i<byteLen;i+=1)val=val*256+buf[offset+i];return Number.isSafeInteger(val)?val:null}function isValidRefSize(size){return size===1||size===2||size===4||size===8}function parseTrailer(buf){if(buf.length<40)return null;if(Buffer.from(buf.subarray(0,8)).toString("ascii")!=="bplist00")return null;let trailerStart=buf.length-32,offsetIntSize=buf[trailerStart+6],objectRefSize=buf[trailerStart+7];if(!isValidRefSize(offsetIntSize)||!isValidRefSize(objectRefSize))return null;let numObjects=readUIntBE(buf,trailerStart+8,8),topObject=readUIntBE(buf,trailerStart+16,8),offsetTableStart=readUIntBE(buf,trailerStart+24,8);if(numObjects===null||topObject===null||offsetTableStart===null||numObjects<=0||numObjects>16384||topObject>=numObjects||offsetTableStart<8||offsetTableStart+numObjects*offsetIntSize>trailerStart)return null;return{buf,offsetIntSize,objectRefSize,numObjects,topObject,offsetTableStart,trailerStart}}function getObjectOffset(ctx,ref){if(ref<0||ref>=ctx.numObjects)return null;let pos=ctx.offsetTableStart+ref*ctx.offsetIntSize,objOffset=readUIntBE(ctx.buf,pos,ctx.offsetIntSize);if(objOffset===null||objOffset<8||objOffset>=ctx.offsetTableStart)return null;return objOffset}function readCount(buf,pos,lowNibble){if(lowNibble<15)return{count:lowNibble,nextPos:pos};if(pos>=buf.length)return null;let intMarker=buf[pos],intType=Math.floor(intMarker/16),intPow=intMarker%16;if(intType!==1||intPow>3)return null;let byteLen=2**intPow,count=readUIntBE(buf,pos+1,byteLen);if(count===null||count<0)return null;return{count,nextPos:pos+1+byteLen}}function readStringAt(ctx,ref){let offset=getObjectOffset(ctx,ref);if(offset===null)return null;let marker=ctx.buf[offset],kind=Math.floor(marker/16),low=marker%16,lenInfo=readCount(ctx.buf,offset+1,low);if(lenInfo===null)return null;let{count,nextPos}=lenInfo;if(kind===5){if(nextPos+count>ctx.offsetTableStart)return null;return Buffer.from(ctx.buf.subarray(nextPos,nextPos+count)).toString("ascii")}if(kind===6){let byteLen=count*2;if(nextPos+byteLen>ctx.offsetTableStart)return null;return new TextDecoder("utf-16be").decode(ctx.buf.subarray(nextPos,nextPos+byteLen))}return null}function readFirstStringFromArray(ctx,ref){let offset=getObjectOffset(ctx,ref);if(offset===null)return null;let marker=ctx.buf[offset];if(Math.floor(marker/16)!==10)return null;let lenInfo=readCount(ctx.buf,offset+1,marker%16);if(lenInfo===null||lenInfo.count===0)return null;let{count,nextPos}=lenInfo;if(nextPos+count*ctx.objectRefSize>ctx.offsetTableStart)return null;for(let i=0;i<count;i+=1){let elemRef=readUIntBE(ctx.buf,nextPos+i*ctx.objectRefSize,ctx.objectRefSize);if(elemRef===null)continue;let str=readStringAt(ctx,elemRef)?.trim();if(str!==void 0&&str!=="")return str}return null}function extractFromBinaryPlist(buf){let ctx=parseTrailer(buf);if(ctx===null)return null;let topOffset=getObjectOffset(ctx,ctx.topObject);if(topOffset===null)return null;let marker=ctx.buf[topOffset];if(Math.floor(marker/16)!==13)return null;let lenInfo=readCount(ctx.buf,topOffset+1,marker%16);if(lenInfo===null)return null;let{count,nextPos}=lenInfo,refsSpan=count*2*ctx.objectRefSize;if(nextPos+refsSpan>ctx.offsetTableStart)return null;let appleLocaleFallback=null,valStart=nextPos+count*ctx.objectRefSize;for(let i=0;i<count;i+=1){let keyRef=readUIntBE(ctx.buf,nextPos+i*ctx.objectRefSize,ctx.objectRefSize),valRef=readUIntBE(ctx.buf,valStart+i*ctx.objectRefSize,ctx.objectRefSize);if(keyRef===null||valRef===null)continue;let key=readStringAt(ctx,keyRef);if(key==="AppleLanguages"){let primary=readFirstStringFromArray(ctx,valRef);if(primary!==null)return primary}else if(key==="AppleLocale"){let loc=readStringAt(ctx,valRef)?.trim();if(loc!==void 0&&loc!=="")appleLocaleFallback=loc}}return appleLocaleFallback}function extractFromXmlPlist(buf){let head=Buffer.from(buf.subarray(0,Math.min(buf.length,64))).toString("utf8");if(!head.includes("<?xml")&&!head.includes("<plist"))return null;let xml=Buffer.from(buf).toString("utf8"),langMatch=/<key>\s*AppleLanguages\s*<\/key>\s*<array>\s*<string>([^<]+)<\/string>/i.exec(xml);if(langMatch?.[1]!==void 0&&langMatch[1].trim()!=="")return langMatch[1].trim();let localeMatch=/<key>\s*AppleLocale\s*<\/key>\s*<string>([^<]+)<\/string>/i.exec(xml);if(localeMatch?.[1]!==void 0&&localeMatch[1].trim()!=="")return localeMatch[1].trim();return null}function extractMacPreferredLanguage(buf){return extractFromBinaryPlist(buf)??extractFromXmlPlist(buf)}import{randomBytes}from"node:crypto";import{closeSync,lstatSync,mkdirSync,openSync,realpathSync,renameSync,rmSync,writeFileSync}from"node:fs";import{homedir as osHomedir,userInfo}from"node:os";import{dirname,join,posix,resolve,win32}from"node:path";var WIN32_ABS_PATH_RE=/^(?:[A-Za-z]:[/\\]|\\\\(?![?.][/\\])[^\\/]+[/\\][^\\/]+)/,WIN32_DRIVE_REL_RE=/^[A-Za-z]:(?![/\\])/,MACOS_SYS_ROOT_LINKS=new Set(["/var","/tmp","/etc"]);function isAbsoluteForPlatform(p,platform=process.platform){return platform==="win32"?WIN32_ABS_PATH_RE.test(p):p.startsWith("/")}function isAbsoluteAnyPlatform(p){return p.startsWith("/")||WIN32_ABS_PATH_RE.test(p)}function safeOsHomedir(){try{return osHomedir().trim()}catch{return""}}function safeUserInfoHome(){try{return userInfo().homedir.trim()}catch{return""}}function readEnvValue(env,key,platform){let direct=env[key];if(direct!==void 0)return direct.trim();if(platform!=="win32")return"";let lower=key.toLowerCase();for(let[k,v]of Object.entries(env))if(k.toLowerCase()===lower&&v!==void 0)return v.trim();return""}function hasEnvKey(env,key,platform){if(env[key]!==void 0)return!0;if(platform!=="win32")return!1;let lower=key.toLowerCase();return Object.entries(env).some(([k,v])=>k.toLowerCase()===lower&&v!==void 0)}var WIN32_DEVICE_PREFIX_RE=/^[\\/]{2,}[?.][\\/]/;function collectRawChain(rawPath,platform=process.platform){let isWin=platform==="win32",pathMod=isWin?win32:posix,parseInput=isWin?rawPath.replaceAll("/","\\"):rawPath,root=pathMod.parse(parseInput).root,parts=parseInput.slice(root.length).split(isWin?/[\\/]+/:/\/+/).filter(Boolean),lastPart=parts.at(-1),endsWithDotSeg=lastPart==="."||lastPart==="..",effectiveParts=parts.filter((p)=>p!=="."),chain=[],seen=new Set,ancestors=new Set,cursor=root;for(let i=0;i<effectiveParts.length;i+=1){let part=effectiveParts[i];if(part===".."){cursor=pathMod.dirname(cursor);continue}if(cursor=isWin?win32.join(cursor,part):posix.join(cursor,part),i<effectiveParts.length-1)ancestors.add(isWin?cursor.toLowerCase():cursor);if(!seen.has(cursor))seen.add(cursor),chain.push(cursor)}return{chain,ancestors,leaf:cursor,endsWithDotSeg}}function assertSafeLangPath(filePath,platform=process.platform){let trimmed=filePath.trim(),isWin=platform==="win32";if(trimmed===""||WIN32_DEVICE_PREFIX_RE.test(trimmed)||isWin&&WIN32_DRIVE_REL_RE.test(trimmed)||!isAbsoluteForPlatform(trimmed,platform))throw Error(`Refused non-absolute or unsafe language configuration path: "${filePath}"`);let{chain,ancestors,leaf,endsWithDotSeg}=collectRawChain(trimmed,platform);if(endsWithDotSeg||chain.length===0||chain.at(-1)!==leaf)throw Error(`Refused root or non-file language configuration path: "${filePath}"`);for(let segment of chain){let isLeaf=segment===leaf,traversedAsDir=ancestors.has(isWin?segment.toLowerCase():segment);if(!isLeaf&&platform==="darwin"&&MACOS_SYS_ROOT_LINKS.has(segment))continue;let st;try{st=lstatSync(segment)}catch(error){let code=error.code;if(code==="ENOENT"||code==="ENOTDIR")continue;throw error}if(st.isSymbolicLink())throw Error(`Refused symlink in language configuration path: "${segment}"`);if((!isLeaf||traversedAsDir)&&!st.isDirectory())throw Error(`Refused non-directory ancestor in language configuration path: "${segment}"`);if(isLeaf&&!st.isFile())throw Error(`Refused non-regular language configuration file: "${segment}"`)}}function renameWithWinRetry(src,dest){for(let attempt=0;attempt<4;attempt+=1)try{renameSync(src,dest);return}catch(error){let code=error.code;if(process.platform==="win32"&&(code==="EPERM"||code==="EACCES"||code==="EBUSY")&&attempt<3){let sab=new SharedArrayBuffer(4);Atomics.wait(new Int32Array(sab),0,0,40*(attempt+1));continue}throw error}}function resolveSafeLangFilePath(filePath,platform=process.platform){let trimmed=filePath.trim();if(trimmed===""||(platform==="win32"?/[\\/]$/:/\/$/).test(trimmed))throw Error(`Refused root or non-file language configuration path: "${filePath}"`);assertSafeLangPath(trimmed,platform);let ops=platform==="win32"?win32:posix,targetPath=ops.isAbsolute(trimmed)?ops.normalize(trimmed):resolve(trimmed);if(targetPath!==trimmed)assertSafeLangPath(targetPath,platform);return targetPath}function writeLangFileAtomic(filePath,content){let targetPath=resolveSafeLangFilePath(filePath),dir=dirname(targetPath);mkdirSync(dir,{recursive:!0}),assertSafeLangPath(targetPath);let tmp=join(dir,`.lang.${String(process.pid)}.${randomBytes(6).toString("hex")}.tmp`),fd=null;try{fd=openSync(tmp,"wx",384),writeFileSync(fd,content,"utf8"),closeSync(fd),fd=null,renameWithWinRetry(tmp,targetPath)}catch(error){if(fd!==null)try{closeSync(fd)}catch{}try{rmSync(tmp,{force:!0})}catch{}throw error}}var ENCODING_OR_MODIFIER_RE=/[.@].*$/;function parseLangPreference(raw){let cleaned=raw.trim().replace(ENCODING_OR_MODIFIER_RE,"").replaceAll("_","-").toLowerCase();if(cleaned==="system"||cleaned==="auto"||cleaned==="os"||cleaned==="default")return"system";if(cleaned==="en"||cleaned==="english"||cleaned.startsWith("en-"))return"en";if(cleaned==="zh"||cleaned==="chinese"||cleaned==="chs"||cleaned==="cht"||cleaned.startsWith("zh-"))return"zh";return null}function classifyLocaleTag(raw){for(let segment of raw.split(":")){let trimmed=segment.trim();if(trimmed==="")continue;let cleaned=trimmed.replace(ENCODING_OR_MODIFIER_RE,"").replaceAll("_","-").trim().toLowerCase();if(cleaned===""||cleaned==="c"||cleaned==="posix"||cleaned==="utf-8"||cleaned==="utf8")continue;if(cleaned==="zh"||cleaned==="chinese"||cleaned==="chs"||cleaned==="cht"||cleaned.startsWith("zh-"))return"zh";if(/^[a-z]{2,3}(?:-[a-z0-9]+)*$/.test(cleaned))return"en"}return null}function detectFromEnvVars(env){for(let key of["LC_ALL","LC_MESSAGES","LANG","LANGUAGE"]){let val=env[key];if(val===void 0||val.trim()==="")continue;let locale=classifyLocaleTag(val);if(locale!==null)return{locale,rawTag:val.trim(),method:"env"}}return null}function parseLinuxLocaleText(text){let entries=new Map;for(let rawLine of text.split(/\r?\n/)){let line=rawLine.trim();if(line===""||line.startsWith("#"))continue;let m=/^(LC_ALL|LC_MESSAGES|LANG)\s*=\s*["']?([^"'\s#]+)["']?/.exec(line);if(m?.[1]!==void 0&&m[2]!==void 0)entries.set(m[1],m[2])}for(let key of["LC_ALL","LC_MESSAGES","LANG"]){let tag=entries.get(key);if(tag===void 0)continue;let locale=classifyLocaleTag(tag);if(locale!==null)return{locale,rawTag:tag,method:"linux-conf"}}return null}function detectFromLinuxLocaleConf(etcDir="/etc"){for(let file of["locale.conf","default/locale"]){let target=join2(etcDir,file);if(!existsSync(target))continue;try{let found=parseLinuxLocaleText(readFileSync(target,"utf8"));if(found!==null)return found}catch{}}return null}function detectMacOsPlistLocale(trimmedHome){if(!isAbsoluteAnyPlatform(trimmedHome))return null;let plistPath=join2(trimmedHome,"Library/Preferences/.GlobalPreferences.plist");if(!existsSync(plistPath))return null;try{let tag=extractMacPreferredLanguage(readFileSync(plistPath));if(tag===null)return null;let locale=classifyLocaleTag(tag);return locale!==null?{locale,rawTag:tag,method:"macos-prefs"}:null}catch{return null}}function detectMacOsPreferred(home,allowDefaultsFallback){let fromPlist=detectMacOsPlistLocale(home.trim());if(fromPlist!==null)return fromPlist;if(allowDefaultsFallback&&existsSync("/usr/bin/defaults"))try{let res=spawnSync("/usr/bin/defaults",["read","-g","AppleLanguages"],{encoding:"utf8",timeout:400});if(res.status===0&&typeof res.stdout==="string"){let m=/"([^"]+)"|([A-Za-z]{2,3}(?:-[A-Za-z0-9]+)*)/.exec(res.stdout),tag=(m?.[1]??m?.[2]??"").trim(),locale=classifyLocaleTag(tag);if(locale!==null)return{locale,rawTag:tag,method:"macos-prefs"}}}catch{}return null}var WIN32_ABS_ROOT_RE=/^[A-Za-z]:[\\/]/,cachedWindowsSystemLocale;function resolveWindowsRegExe(env=process.env,existsFn=existsSync){let candidates=[env.SystemRoot,env.SYSTEMROOT,env.WINDIR,env.windir],systemRoot="C:\\Windows";for(let raw of candidates){let trimmed=raw?.trim()??"";if(trimmed!==""&&WIN32_ABS_ROOT_RE.test(trimmed)){systemRoot=trimmed;break}}let candidate=win322.join(systemRoot,"System32","reg.exe");return existsFn(candidate)?candidate:null}function parseRegQueryValue(stdout,valueName){let escaped=valueName.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),lineRe=new RegExp(`^\\s*${escaped}\\s+REG_[A-Z_]+(?:\\s+(.+))?$`,"i");for(let line of stdout.split(/\r?\n/)){let match=lineRe.exec(line);if(match===null)continue;let rawField=match[1]?.trim()??"";if(rawField==="")return null;let first=rawField.split("\\0")[0]?.trim()??"";return first!==""?first:null}return null}function detectWindowsUiLanguage(env){if(cachedWindowsSystemLocale!==void 0)return cachedWindowsSystemLocale;let regExe=resolveWindowsRegExe(env);if(regExe===null)return cachedWindowsSystemLocale=null,null;let queries=[["HKCU\\Control Panel\\Desktop","PreferredUILanguages"],["HKCU\\Control Panel\\Desktop\\MuiCached","MachinePreferredUILanguages"],["HKCU\\Control Panel\\International","LocaleName"]];for(let[regKey,valueName]of queries)try{let res=spawnSync(regExe,["query",regKey,"/v",valueName],{encoding:"utf8",timeout:500,windowsHide:!0});if(res.status!==0||typeof res.stdout!=="string")continue;let rawVal=parseRegQueryValue(res.stdout,valueName);if(rawVal===null)continue;let locale=classifyLocaleTag(rawVal);if(locale!==null)return cachedWindowsSystemLocale={locale,rawTag:rawVal,method:"windows-ui"},cachedWindowsSystemLocale}catch{}return cachedWindowsSystemLocale=null,null}function detectFromIntl(){try{let tag=Intl.DateTimeFormat().resolvedOptions().locale,locale=classifyLocaleTag(tag);if(locale!==null)return{locale,rawTag:tag,method:"intl"}}catch{}return null}function detectSystemLocale(options={}){let env=options.env??process.env;if(env.CLIS_TEST_OS_LOCALE!==void 0&&env.CLIS_TEST_OS_LOCALE.trim()!==""){let locale=classifyLocaleTag(env.CLIS_TEST_OS_LOCALE);if(locale!==null)return{locale,rawTag:env.CLIS_TEST_OS_LOCALE.trim(),method:"test-override"}}let hostTestFallback=()=>{if(options.env!==void 0&&"CLIS_TEST_OS_LOCALE"in options.env)return null;let raw=process.env.CLIS_TEST_OS_LOCALE;if(raw===void 0||raw.trim()==="")return null;let locale=classifyLocaleTag(raw);return locale!==null?{locale,rawTag:raw.trim(),method:"test-override"}:null},platform=options.platform??process.platform,allowSubprocess=options.allowSubprocess??options.homedir===void 0,testFallback=hostTestFallback();if(platform==="darwin"){if(options.homedir===void 0&&testFallback!==null)return detectFromEnvVars(env)??testFallback;let realHome=safeOsHomedir(),home=options.homedir??realHome;return detectMacOsPreferred(home,allowSubprocess&&(home===realHome||realHome===""))??detectFromEnvVars(env)??testFallback??detectFromIntl()??{locale:"en",rawTag:"en",method:"fallback"}}if(platform==="win32"){if(testFallback!==null)return detectFromEnvVars(env)??testFallback;return(allowSubprocess?detectWindowsUiLanguage(env):null)??detectFromEnvVars(env)??detectFromIntl()??{locale:"en",rawTag:"en",method:"fallback"}}if(options.etcDir===void 0&&testFallback!==null)return detectFromEnvVars(env)??testFallback;return detectFromEnvVars(env)??detectFromLinuxLocaleConf(options.etcDir)??testFallback??detectFromIntl()??{locale:"en",rawTag:"en",method:"fallback"}}var ESC=String.fromCharCode(27);function isColorAllowedByEnv(env){return!env.NO_COLOR&&env.TERM?.toLowerCase()!=="dumb"}function resolveColorChannels(env,tty){let allowed=isColorAllowedByEnv(env);return{stdout:allowed&&tty.stdout===!0,stderr:allowed&&tty.stderr===!0}}function paintSgr(text,sgr,enabled){if(!enabled||text==="")return text;return`${ESC}[${sgr}m${text}${ESC}[0m`}function detectColorChannels(env=process.env,tty){return resolveColorChannels(env,{stdout:tty?.stdout??process.stdout.isTTY===!0,stderr:tty?.stderr??process.stderr.isTTY===!0})}function supportsStreamColor(stream,env=process.env){return stream.isTTY===!0&&isColorAllowedByEnv(env)}import{createInterface}from"node:readline/promises";function setStreamRef(stream,shouldRef){let candidate=stream,fn=shouldRef?candidate.ref:candidate.unref;if(typeof fn==="function")fn.call(stream)}function isTtyWritable(stream){return stream.isTTY===!0}function isStreamEndedOrDestroyed(input,rl){let s=input,closed=rl!==null&&rl.closed===!0;return s.readableEnded===!0||s.destroyed===!0||closed}var ABSORBED_DESTROYED_STREAMS=new WeakSet,SILENT_ERROR_SINK=()=>{};function createReadlineSession(options={}){let input=options.input??process.stdin,output=options.output??process.stdout,buffered=[],rl=null,ended=!1,aborted=!1,pending=null,processSigintAttached=!1,inputCloseAttached=!1,detachProcessSigint=()=>{if(!processSigintAttached)return;processSigintAttached=!1,process.off("SIGINT",onSigint)},absorbDanglingError=()=>{let state=input;if(state.destroyed!==!0&&state.errored==null)return;if(ABSORBED_DESTROYED_STREAMS.has(input))return;ABSORBED_DESTROYED_STREAMS.add(input),input.on("error",SILENT_ERROR_SINK)},detachInputListeners=()=>{if(absorbDanglingError(),!inputCloseAttached)return;inputCloseAttached=!1,input.off("close",onStreamClosed),input.off("error",onStreamClosed)},noopError=()=>{},finishPendingAsNull=(writeNewline)=>{if(pending===null)return;if(writeNewline&&!aborted&&isTtyWritable(output))output.write(`
|
|
2
|
+
`);let resolve=pending;pending=null,setStreamRef(input,!1),resolve(null)},closeInterfaceSafe=(current)=>{current.off("SIGINT",onSigint),current.on("error",noopError),current.off("error",onStreamClosed),current.close()},onStreamClosed=()=>{if(ended=!0,detachProcessSigint(),detachInputListeners(),rl!==null){let current=rl;rl=null,closeInterfaceSafe(current)}finishPendingAsNull(!0)},onSigint=()=>{if(aborted)return;aborted=!0;let shield=()=>{};if(process.on("SIGINT",shield),setTimeout(()=>process.off("SIGINT",shield),500).unref?.(),detachProcessSigint(),detachInputListeners(),buffered.length=0,isTtyWritable(output))output.write(`
|
|
3
|
+
`);if(rl!==null){let current=rl;rl=null,closeInterfaceSafe(current)}finishPendingAsNull(!1)};function ensure(){if(rl!==null)return rl;let created=createInterface({input,output});if(created.on("line",(line)=>{if(pending===null){buffered.push(line);return}let resolve=pending;pending=null,setStreamRef(input,!1),resolve(line)}),created.on("close",onStreamClosed),created.on("error",onStreamClosed),created.on("SIGINT",onSigint),!inputCloseAttached)inputCloseAttached=!0,input.once("close",onStreamClosed),input.once("error",onStreamClosed);if(input===process.stdin&&!processSigintAttached)processSigintAttached=!0,process.on("SIGINT",onSigint);return rl=created,created}return{ask(prompt){if(pending!==null)return Promise.reject(Error("ReadlineSession.ask() does not support concurrent calls"));if(aborted)return Promise.resolve(null);if(ended||isStreamEndedOrDestroyed(input,null)){ended=!0,detachProcessSigint(),detachInputListeners();let bufferedLine=buffered.shift();if(bufferedLine===void 0)return Promise.resolve(null);return output.write(`${prompt}
|
|
4
|
+
`),Promise.resolve(bufferedLine)}let created=ensure();if(aborted)return Promise.resolve(null);if(ended||rl===null||isStreamEndedOrDestroyed(input,created)){onStreamClosed();let bufferedLine=buffered.shift();if(bufferedLine===void 0)return Promise.resolve(null);return output.write(`${prompt}
|
|
5
|
+
`),Promise.resolve(bufferedLine)}created.setPrompt(prompt),created.prompt();let ready=buffered.shift();if(ready!==void 0)return absorbDanglingError(),output.write(`
|
|
6
|
+
`),Promise.resolve(ready);if(aborted||ended||rl===null||isStreamEndedOrDestroyed(input,created))return onStreamClosed(),Promise.resolve(null);return setStreamRef(input,!0),new Promise((resolve)=>{pending=resolve})},close(){if(ended=!0,buffered.length=0,detachProcessSigint(),detachInputListeners(),rl!==null){let current=rl;rl=null,closeInterfaceSafe(current)}finishPendingAsNull(!1),setStreamRef(input,!1)}}}function parseConfirmAnswer(answer,defaultYes){if(answer===null)return null;let normalized=answer.trim().toLowerCase();if(normalized==="")return defaultYes;return normalized==="y"||normalized==="yes"}async function promptConfirmOnce(question,options={}){let session=createReadlineSession(options);try{let answer=await session.ask(question),parsed=parseConfirmAnswer(answer,!1);if(parsed===null)return"cancelled";return parsed?"yes":"no"}finally{session.close()}}var ESC2=String.fromCharCode(27),BEL=String.fromCharCode(7),C1_CSI=String.fromCharCode(155),C1_ST=String.fromCharCode(156),C1_OSC=String.fromCharCode(157),ANSI_ESCAPE_RE=new RegExp(`${ESC2}(?:\\[[0-?]*[ -/]*[@-~]|\\][^${BEL}${ESC2}${C1_ST}]*(?:${BEL}|${ESC2}\\\\|${C1_ST})|[@-Z\\\\-_])|${C1_CSI}[0-?]*[ -/]*[@-~]|${C1_OSC}[^${BEL}${ESC2}${C1_ST}]*(?:${BEL}|${ESC2}\\\\|${C1_ST})`,"g"),ZERO_WIDTH_UNICODE_RE=/[\p{Mn}\p{Me}\p{Cf}]/u,BREAK_CHARS=new Set([" ","/",","]);function stripAnsi(text){return text.replace(ANSI_ESCAPE_RE,"")}function isZeroWidthCodePoint(ch,code){return code<32||code>=127&&code<=159||code===173||code===8288||code===65279||code>=8203&&code<=8207||code>=65024&&code<=65039||code>=917760&&code<=917999||ZERO_WIDTH_UNICODE_RE.test(ch)}function isFullWidthCodePoint(code){return code===12288||code>=4352&&code<=4447||code>=9001&&code<=9002||code>=11904&&code<=42191||code>=44032&&code<=55203||code>=63744&&code<=64255||code>=65040&&code<=65049||code>=65072&&code<=65135||code>=65281&&code<=65376||code>=65504&&code<=65510||code>=127744&&code<=129791||code>=131072&&code<=196605||code>=196608&&code<=262141}function charWidth(ch){if(ch==="")return 0;let code=ch.codePointAt(0)??0;if(isZeroWidthCodePoint(ch,code))return 0;return isFullWidthCodePoint(code)?2:1}function displayWidth(text){let plain=stripAnsi(text),width=0;for(let ch of plain)width+=charWidth(ch);return width}function truncateDisplay(text,maxWidth,ellipsis="…"){if(maxWidth<=0)return"";if(displayWidth(text)<=maxWidth)return text;let ellipsisWidth=displayWidth(ellipsis);if(maxWidth<=ellipsisWidth)return ellipsisWidth===maxWidth?ellipsis:"";let budget=maxWidth-ellipsisWidth,out="",width=0;for(let ch of text){let cw=charWidth(ch);if(width+cw>budget)break;out+=ch,width+=cw}return`${out}${ellipsis}`}function scanLineSegment(chars,start,maxWidth){let width=0,end=start,lastBreak=-1;while(end<chars.length){let ch=chars[end],cw=charWidth(ch);if(width+cw>maxWidth){if(end===start)end+=1;break}if(width+=cw,BREAK_CHARS.has(ch))lastBreak=end;end+=1}return{end,lastBreak}}function wrapDisplay(text,maxWidth){if(maxWidth<=4)return[truncateDisplay(text,Math.max(1,maxWidth))];if(displayWidth(text)<=maxWidth)return[text];let chars=[...text],lines=[],start=0;while(start<chars.length){let{end,lastBreak}=scanLineSegment(chars,start,maxWidth);if(end>=chars.length){lines.push(chars.slice(start).join("").trimEnd());break}if(lastBreak>start){let slice=chars.slice(start,lastBreak+1).join("").trimEnd();lines.push(slice||chars.slice(start,end).join("")),start=lastBreak+1;while(start<chars.length&&chars[start]===" ")start+=1}else lines.push(chars.slice(start,end).join("")),start=end}return lines.length>0?lines:[""]}var BRAILLE_SPINNER_FRAMES=["⠋","⠙","⠹","⠸","⠼","⠴","⠦","⠧","⠇","⠏"],DEFAULT_SPINNER_INTERVAL_MS=80,ESC3=String.fromCharCode(27),CLEAR_LINE_SEQ=`\r${ESC3}[2K`,DEFAULT_SHIMMER_PALETTE={base:"2",shoulder:"34",peak:"1;94"};function spinnerFrameAt(step,frames=BRAILLE_SPINNER_FRAMES){if(frames.length===0)return"";let idx=(Math.trunc(step)%frames.length+frames.length)%frames.length;return frames[idx]}function formatElapsedMs(elapsedMs){if(elapsedMs===void 0||!Number.isFinite(elapsedMs)||elapsedMs<100)return"";return`${(elapsedMs/1000).toFixed(1)}s`}function renderShimmerText(text,step,enabled,palette=DEFAULT_SHIMMER_PALETTE){if(!enabled||text==="")return text;let chars=Array.from(text),widths=chars.map((ch)=>Math.max(1,displayWidth(ch))),starts=[],totalWidth=0;for(let w of widths)starts.push(totalWidth),totalWidth+=w;let cycle=Math.max(1,totalWidth+6),centerCol=(Math.trunc(step)%cycle+cycle)%cycle-1,pickSgr=(colCenter)=>{let dist=Math.abs(colCenter-centerCol);if(dist<=1.1)return palette.peak;if(dist<=2.6)return palette.shoulder;return palette.base},parts=[],runSgr="",runText="";for(let i=0;i<chars.length;i+=1){let ch=chars[i],colCenter=starts[i]+widths[i]/2,sgr=pickSgr(colCenter);if(sgr===runSgr)runText+=ch;else{if(runText!=="")parts.push(paintSgr(runText,runSgr,!0));runSgr=sgr,runText=ch}}if(runText!=="")parts.push(paintSgr(runText,runSgr,!0));return parts.join("")}function formatSpinnerLine(input){let frame=spinnerFrameAt(input.frameIndex,input.frames),bodyPlain=input.detail!==void 0&&input.detail!==""?`${input.action} · ${input.detail}`:input.action,maxCols=Math.max(12,Math.floor(input.maxCols)),fitted=truncateDisplay(bodyPlain,maxCols-4),splitIdx=fitted.indexOf(" · "),actionPart=splitIdx===-1?fitted:fitted.slice(0,splitIdx),detailPart=splitIdx===-1?"":fitted.slice(splitIdx),styledAction=renderShimmerText(actionPart,input.frameIndex,input.color,input.palette),styledBody=detailPart===""?styledAction:`${styledAction}${paintSgr(detailPart,"2",input.color)}`;return` ${paintSgr(frame,"36",input.color)} ${styledBody}`}function createTtySpinner(options){if(!options.enabled)return{start(){},setText(){},refresh(){},suspend(){},resume(){},stop(){}};let write=options.write??((chunk)=>process.stderr.write(chunk)),columns=options.columns??(()=>process.stderr.columns||80),now=options.now??(()=>Date.now()),setTimer=options.setTimer??((fn,ms)=>setInterval(fn,ms)),clearTimer=options.clearTimer??((handle)=>{clearInterval(handle)}),intervalMs=options.intervalMs??DEFAULT_SPINNER_INTERVAL_MS,frames=options.frames??BRAILLE_SPINNER_FRAMES,{palette,resolveText}=options,active=!1,suspended=!1,visible=!1,frameIndex=0,startedAt=0,currentAction="",currentDetail="",timer,renderFrame=()=>{if(!active||suspended)return;let elapsedMs=now()-startedAt,action,detail;if(resolveText!==void 0){let next=resolveText(elapsedMs);action=next.action,detail=next.detail}else{let elapsed=formatElapsedMs(elapsedMs),parts=[];if(currentDetail!=="")parts.push(currentDetail);if(elapsed!=="")parts.push(elapsed);action=currentAction,detail=parts.length===0?void 0:parts.join(" · ")}let maxCols=Math.max(12,columns()-1),line=formatSpinnerLine({frameIndex,action,detail,maxCols,color:options.color,frames,palette});write(`${CLEAR_LINE_SEQ}${line}`),visible=!0},clearIfVisible=()=>{if(!visible)return;write(CLEAR_LINE_SEQ),visible=!1},startTimer=()=>{if(timer!==void 0)return;timer=setTimer(()=>{frameIndex+=1,renderFrame()},intervalMs),timer.unref?.()},stopTimer=()=>{if(timer===void 0)return;clearTimer(timer),timer=void 0};return{start(action,detail=""){if(action!==void 0){if(currentAction=action,currentDetail=detail,startedAt=now(),!active)active=!0,suspended=!1,frameIndex=0,renderFrame(),startTimer();else{let wasSuspended=suspended;if(suspended=!1,renderFrame(),wasSuspended)startTimer()}return}if(active){if(suspended)suspended=!1,renderFrame(),startTimer();return}active=!0,suspended=!1,startedAt=now(),frameIndex=0,renderFrame(),startTimer()},setText(action,detail=""){if(!active)return;currentAction=action,currentDetail=detail,renderFrame()},refresh(){if(!active)return;renderFrame()},suspend(){if(!active||suspended)return;suspended=!0,stopTimer(),clearIfVisible()},resume(){if(!active||!suspended)return;suspended=!1,renderFrame(),startTimer()},stop(){if(!active)return;active=!1,suspended=!1,stopTimer(),clearIfVisible()}}}import{existsSync as existsSync2,readFileSync as readFileSync2}from"node:fs";function defaultToolLangEnvVar(toolName){return`${toolName.trim().replace(/[^A-Za-z0-9]+/g,"_").replace(/^_+|_+$/g,"").toUpperCase()}_LANG`}function resolveWin32HomeFromEnv(env){if(hasEnvKey(env,"USERPROFILE","win32")){let profile=readEnvValue(env,"USERPROFILE","win32");return profile!==""&&WIN32_ABS_PATH_RE.test(profile)?profile:""}let drive=readEnvValue(env,"HOMEDRIVE","win32"),homePath=readEnvValue(env,"HOMEPATH","win32");if(drive!==""&&homePath!==""){let combined=`${drive}${homePath}`;if(WIN32_ABS_PATH_RE.test(combined))return combined}return""}function normalizeWinCompare(p){return p.replaceAll("\\","/").replace(/\/+$/,"").toLowerCase()}function hasDotDotSegment(p){return p.split(/[\\/]/).includes("..")}function joinRawPosix(base,...parts){let clean=base.replace(/\/+$/,"")||"/";return clean==="/"?`/${parts.join("/")}`:`${clean}/${parts.join("/")}`}function joinRawWin32(base,...parts){return`${base.replace(/[/\\]+$/,"")}\\${parts.join("\\")}`}function resolveSafeHomeDir(options={}){let platform=options.platform??process.platform,env=options.env??process.env;if(options.homedir!==void 0){let explicit=options.homedir.trim();return explicit!==""&&isAbsoluteAnyPlatform(explicit)?explicit:""}if(platform==="win32"){if(hasEnvKey(env,"USERPROFILE","win32")||hasEnvKey(env,"HOMEDRIVE","win32")||hasEnvKey(env,"HOMEPATH","win32"))return resolveWin32HomeFromEnv(env)}else if(hasEnvKey(env,"HOME",platform)){let envHome=readEnvValue(env,"HOME",platform);return envHome!==""&&envHome.startsWith("/")?envHome:""}let isTargetAbs=(p)=>isAbsoluteForPlatform(p,platform),fromOs=safeOsHomedir();if(fromOs!==""&&isTargetAbs(fromOs))return fromOs;let fromPasswd=safeUserInfoHome();if(fromPasswd!==""&&isTargetAbs(fromPasswd))return fromPasswd;return""}function resolveLangConfigPath(options){let platform=options.platform??process.platform,env=options.env??process.env,hasExplicitHome=options.homedir!==void 0,home=resolveSafeHomeDir({homedir:options.homedir,env,platform});if(platform==="win32"){let appData=readEnvValue(env,"APPDATA","win32");if(appData!==""&&WIN32_ABS_PATH_RE.test(appData)&&(!hasExplicitHome||home!==""&&!hasDotDotSegment(appData)&&(normalizeWinCompare(appData)===normalizeWinCompare(home)||normalizeWinCompare(appData).startsWith(`${normalizeWinCompare(home)}/`))))return joinRawWin32(appData,options.toolName,"lang.json");let base=hasExplicitHome?home:resolveWin32HomeFromEnv(env)||home;if(base==="")return"";return joinRawWin32(base,"AppData","Roaming",options.toolName,"lang.json")}let xdgConfig=env.XDG_CONFIG_HOME?.trim(),normPosixHome=home.replace(/\/+$/,"")||"/";if(xdgConfig!==void 0&&xdgConfig!==""&&xdgConfig.startsWith("/")&&(!hasExplicitHome||home!==""&&!hasDotDotSegment(xdgConfig)&&(xdgConfig===normPosixHome||xdgConfig.startsWith(normPosixHome==="/"?"/":`${normPosixHome}/`))))return joinRawPosix(xdgConfig,options.toolName,"lang.json");if(home==="")return"";return joinRawPosix(home,".config",options.toolName,"lang.json")}function readPersistedLang(configPath){let trimmed=configPath.trim();if(trimmed===""||!isAbsoluteForPlatform(trimmed,process.platform))return null;try{let targetPath=resolveSafeLangFilePath(trimmed);if(!existsSync2(targetPath))return null;let raw=readFileSync2(targetPath,"utf8"),parsed=JSON.parse(raw);if(typeof parsed?.lang!=="string")return null;return parseLangPreference(parsed.lang)}catch{return null}}function writePersistedLang(configPath,lang){let trimmed=configPath.trim();writeLangFileAtomic(trimmed,`${JSON.stringify({lang},null,2)}
|
|
7
|
+
`)}function resolveCliLocale(options){let env=options.env??process.env,platform=options.platform??process.platform,home=resolveSafeHomeDir({homedir:options.homedir,env,platform}),envVarName=options.envVarName??defaultToolLangEnvVar(options.toolName),configPath=options.configPath??resolveLangConfigPath({toolName:options.toolName,platform,homedir:options.homedir,env}),system=options.detectSystem?.()??detectSystemLocale({platform,...options.homedir!==void 0?{homedir:options.homedir}:{},env}),finalize=(preference,source)=>({locale:preference==="system"?system.locale:preference,preference,source,envVarName,configPath,system});if(options.flag!==void 0&&options.flag.trim()!==""){let fromFlag=parseLangPreference(options.flag);if(fromFlag!==null)return finalize(fromFlag,"flag")}let toolEnvVal=env[envVarName];if(toolEnvVal!==void 0&&toolEnvVal.trim()!==""){let fromToolEnv=parseLangPreference(toolEnvVal);if(fromToolEnv!==null)return finalize(fromToolEnv,"tool-env")}let suiteEnvVal=env.CLIS_LANG;if(suiteEnvVal!==void 0&&suiteEnvVal.trim()!==""){let fromSuiteEnv=parseLangPreference(suiteEnvVal);if(fromSuiteEnv!==null)return finalize(fromSuiteEnv,"suite-env")}let testRealHome=process.env.CLIS_TEST_REAL_HOME;if(!(testRealHome!==void 0&&testRealHome!==""&&options.configPath===void 0&&options.homedir===void 0&&home===testRealHome)){let persisted=readPersistedLang(configPath);if(persisted!==null)return finalize(persisted,"config")}return finalize("system","default")}function formatInvalidLangError(raw,fallbackLocale){if(raw===null)return fallbackLocale==="zh"?"参数 --lang 缺少取值 (可选值: system | en | zh)":"Option --lang requires a value (expected: system | en | zh)";return fallbackLocale==="zh"?`参数 --lang 不支持 "${raw}" (可选值: system | en | zh)`:`Invalid --lang value "${raw}" (expected: system | en | zh)`}function consumeValueFlagInStrip(argv,i,rest){let val=argv[i+1];if(val==="--lang"){let nextAfterLang=i+2<argv.length?argv[i+2]:void 0,nextLang=nextAfterLang!==void 0?parseLangPreference(nextAfterLang):null;if(nextLang!==null)return rest.push(`--lang=${nextLang}`),{nextIndex:i+2,parsedLang:nextLang};if(nextAfterLang==="--")return rest.push(val,nextAfterLang),{nextIndex:i+2};return rest.push(val),{nextIndex:i+1}}if(val.startsWith("--lang=")){let nextLang=parseLangPreference(val.slice(7));return rest.push(val),{nextIndex:i+1,...nextLang!==null?{parsedLang:nextLang}:{}}}if(val==="--"||!val.startsWith("-"))return rest.push(val),{nextIndex:i+1};return{nextIndex:i}}function stripLangArgs(argv,options={}){let fallbackLocale=options.fallbackLocale??"en",valueFlags=options.valueFlags,rest=[],lang,firstError,afterDash=!1;for(let i=0;i<argv.length;i+=1){let arg=argv[i];if(afterDash){rest.push(arg);continue}if(arg==="--"){afterDash=!0,rest.push(arg);continue}if(arg==="--lang"){let next=argv[i+1];if(next===void 0||next===""||next.startsWith("-")){if(firstError??={raw:null},next==="--")i+=1;continue}let parsed=parseLangPreference(next);if(parsed===null)firstError??={raw:next};else lang=parsed;i+=1;continue}if(arg.startsWith("--lang=")){let raw=arg.slice(7),parsed=raw.trim()===""?null:parseLangPreference(raw);if(parsed===null)firstError??={raw:raw.trim()===""?null:raw};else lang=parsed;continue}if(rest.push(arg),valueFlags?.has(arg)&&i+1<argv.length){let consumed=consumeValueFlagInStrip(argv,i,rest);if(consumed.parsedLang!==void 0)lang=consumed.parsedLang;i=consumed.nextIndex}}if(firstError!==void 0){let errLocale=fallbackLocale;if(lang==="en"||lang==="zh")errLocale=lang;else if(lang==="system"&&options.systemLocale!==void 0)errLocale=options.systemLocale;return{argv:[...argv],...lang!==void 0?{lang}:{},error:formatInvalidLangError(firstError.raw,errLocale)}}return{argv:rest,lang}}function t(locale,zh,en){return locale==="zh"?zh:en}function computeHelpDescColumn(plainLefts,minGap=3){return plainLefts.reduce((max,item)=>Math.max(max,displayWidth(item)),0)+Math.max(2,minGap)}function alignHelpRow(styledLeft,plainLeft,rightText,descCol,indent=" "){let pad=" ".repeat(Math.max(2,descCol-displayWidth(plainLeft)));return`${indent}${styledLeft}${pad}${rightText}`}var HELP_BAR_BLOCK="▍",HELP_RULE_WIDTH=76,HELP_RULE="─".repeat(HELP_RULE_WIDTH);function paintHelp(text,sgr,enabled){return paintSgr(text,sgr,enabled)}function createHelpStyles(color){return{badge:(text)=>paintHelp(text,"1;7",color),section:(text)=>paintHelp(text,"1;34",color),bold:(text)=>paintHelp(text,"1",color),dim:(text)=>paintHelp(text,"2",color),token:(text)=>paintHelp(text,"36",color),green:(text)=>paintHelp(text,"1;32",color),red:(text)=>paintHelp(text,"1;31",color)}}function formatExitAndDocsSection(options){let{locale,color,descCol}=options,s=createHelpStyles(color),exitTitle=options.exitSectionTitle??t(locale,"退出码","Exit Codes"),docsTitle=options.docsSectionTitle??t(locale,"文档与源码","Docs & Source"),lines=[` ${s.section(exitTitle)}`,alignHelpRow(s.green("0"),"0",s.dim(options.exitZeroDesc),descCol),alignHelpRow(s.red("1"),"1",s.dim(options.exitOneDesc),descCol)],rawDocs=options.docsUrl?.trim();if(rawDocs!==void 0&&rawDocs!=="")lines.push("",` ${s.section(docsTitle)}`,` ${s.token(rawDocs)}`);return lines.push(""),lines}var BIDI_ZERO_WIDTH_RE=/[\u200b-\u200f\u202a-\u202e\u2066-\u2069\ufeff]/g;function sanitizeCliText(raw){return stripAnsi(raw).replace(BIDI_ZERO_WIDTH_RE,"").replace(/\p{Cc}/gu," ").replace(/\s+/g," ").trim()}function sanitizeInline(raw){return sanitizeCliText(raw)}function shortenHomePath(filePath,home){let normHome=home.replace(/[\\/]+$/,"");if(normHome!==""&&filePath.startsWith(normHome)&&(filePath[normHome.length]==="/"||filePath[normHome.length]==="\\"))return`~${filePath.slice(normHome.length)}`;return filePath}function formatLangHelp(options){let color=options.color??!1,{locale}=options,safeBin=sanitizeInline(options.binName),safeCfg=sanitizeInline(shortenHomePath(options.configPath,options.homedir??resolveSafeHomeDir())),s=createHelpStyles(color),badge=s.badge(`${HELP_BAR_BLOCK} ${safeBin.toUpperCase()} LANG `),{bold,dim,section,token:cyan}=s,compactCfgForBudget=(maxCfgCols)=>{if(displayWidth(safeCfg)<=maxCfgCols)return safeCfg;let isWinPath=safeCfg.includes("\\"),sep=isWinPath?"\\":"/",segments=safeCfg.split(/[\\/]+/).filter(Boolean),base=segments.at(-1)??safeCfg,parent=segments.at(-2)??"",tail=parent!==""?`${parent}${sep}${base}`:base,compactEnv=isWinPath?`%APPDATA%\\${tail}`:`$XDG_CONFIG_HOME/${tail}`;if(displayWidth(compactEnv)<=maxCfgCols)return compactEnv;let compactTail=`...${sep}${tail}`;if(displayWidth(compactTail)<=maxCfgCols)return compactTail;return`...${sep}${base}`},precedencePrefix=`--lang > ${options.envVarName} > CLIS_LANG > `,suffixCols=locale==="zh"?7:5,singleLineBudget=76-displayWidth(precedencePrefix)-suffixCols,singleLineCfg=compactCfgForBudget(singleLineBudget),wrapPrecedence=4+displayWidth(precedencePrefix)+displayWidth(singleLineCfg)+suffixCols>80,wrappedCfg=wrapPrecedence?compactCfgForBudget(74-suffixCols):singleLineCfg,precedenceLines=(osLabel)=>wrapPrecedence?[` ${cyan("--lang")} > ${cyan(options.envVarName)} > ${cyan("CLIS_LANG")}`,` > ${dim(wrappedCfg)} > ${dim(osLabel)}`]:[` ${cyan("--lang")} > ${cyan(options.envVarName)} > ${cyan("CLIS_LANG")} > ${dim(wrappedCfg)} > ${dim(osLabel)}`],cmdDefault=`${safeBin} lang`,cmdSet=`${safeBin} lang <system|en|zh>`,nonCmdLefts=["system","en","zh","--lang <lang>","-h, --help",...options.supportsJson===!0?["--json"]:[]],maxRightCols=locale==="zh"?38:42,defaultDescCol=computeHelpDescColumn([...nonCmdLefts,cmdDefault]),wideDescCol=computeHelpDescColumn([...nonCmdLefts,cmdDefault,cmdSet]),wrapCmdDefault=4+defaultDescCol+maxRightCols>80,wrapCmdSet=wrapCmdDefault||4+wideDescCol+maxRightCols>80,descCol=wideDescCol;if(wrapCmdDefault)descCol=computeHelpDescColumn(nonCmdLefts);else if(wrapCmdSet)descCol=Math.min(34,defaultDescCol);let row=(styledLeft,plainLeft,desc)=>alignHelpRow(styledLeft,plainLeft,desc,descCol),cmdDefaultRow=(desc)=>wrapCmdDefault?` ${bold(cmdDefault)}
|
|
8
|
+
${" ".repeat(4+descCol)}${dim(desc)}`:row(bold(cmdDefault),cmdDefault,dim(desc)),cmdSetRow=(desc)=>wrapCmdSet?` ${bold(cmdDefault)} ${cyan("<system|en|zh>")}
|
|
9
|
+
${" ".repeat(4+descCol)}${dim(desc)}`:row(`${bold(cmdDefault)} ${cyan("<system|en|zh>")}`,cmdSet,dim(desc)),rule=dim(HELP_RULE),zh=locale==="zh",exitAndDocs=formatExitAndDocsSection({locale,color,descCol,exitZeroDesc:zh?"成功 (含正常执行与 -h/--help)":"Success (command completed or --help)",exitOneDesc:zh?"失败 (参数非法、配置或执行错误)":"Error (invalid arguments or runtime error)",docsUrl:options.docsUrl});if(zh){let zhSubtitle=`查看或切换 ${safeBin} 显示语言 (独立保存, 默认跟随系统)。`,zhSubtitleLines=2+displayWidth(zhSubtitle)<=80?[` ${dim(zhSubtitle)}`]:[` ${dim(`查看或切换 ${safeBin} 显示语言`)}`,` ${dim("(独立保存, 默认跟随系统)。")}`];return["",` ${badge} ${bold("界面语言设置")}`,...zhSubtitleLines,` ${rule}`,"",` ${section("用法")}`,cmdDefaultRow("查看当前生效语言与配置来源"),cmdSetRow("保存该工具的默认显示语言"),"",` ${section("可选值")}`,row(cyan("system"),"system","跟随操作系统首选语言 (默认)"),row(cyan("en"),"en","固定使用英文界面 (即使系统语言为中文)"),row(cyan("zh"),"zh","固定使用简体中文界面"),"",` ${section("选项")}`,...options.supportsJson===!0?[row(cyan("--json"),"--json",dim("以 JSON 格式输出结果"))]:[],row(cyan("--lang <lang>"),"--lang <lang>",dim("单次覆盖语言 (system | en | zh)")),row(cyan("-h, --help"),"-h, --help",dim("显示本帮助")),"",` ${section("优先级")}`,...precedenceLines("系统"),"",...exitAndDocs].join(`
|
|
10
|
+
`)}let enSubtitle=`Inspect or set display language for ${safeBin} (saved per tool).`,enSubtitleLines=2+displayWidth(enSubtitle)<=80?[` ${dim(enSubtitle)}`]:[` ${dim(`Inspect or set display language for ${safeBin}`)}`,` ${dim("(saved per tool).")}`];return["",` ${badge} ${bold("Display Language")}`,...enSubtitleLines,` ${rule}`,"",` ${section("Usage")}`,cmdDefaultRow("Show active language and preference source"),cmdSetRow("Save persistent language preference"),"",` ${section("Values")}`,row(cyan("system"),"system","Follow OS language (default)"),row(cyan("en"),"en","Always display in English"),row(cyan("zh"),"zh","Always display in Simplified Chinese"),"",` ${section("Options")}`,...options.supportsJson===!0?[row(cyan("--json"),"--json",dim("Emit JSON result"))]:[],row(cyan("--lang <lang>"),"--lang <lang>",dim("Override language for this run")),row(cyan("-h, --help"),"-h, --help",dim("Show this help")),"",` ${section("Precedence")}`,...precedenceLines("OS"),"",...exitAndDocs].join(`
|
|
11
|
+
`)}function formatLocaleName(locale){return locale==="zh"?"简体中文 (zh)":"English (en)"}function formatSourceNote(resolved,locale){switch(resolved.source){case"default":return t(locale,"默认跟随系统","default · system");case"config":return resolved.preference==="system"?t(locale,"已保存 · 跟随系统","saved · system"):t(locale,"已保存配置","saved");case"flag":return t(locale,"本次 --lang 覆盖","overridden via --lang");case"tool-env":return t(locale,`环境变量 ${resolved.envVarName} 覆盖`,`overridden via ${resolved.envVarName}`);case"suite-env":return t(locale,"环境变量 CLIS_LANG 覆盖","overridden via CLIS_LANG")}}function resolveDashboardTitle(locale,updatedTo){if(updatedTo===void 0)return t(locale,"语言偏好","Language");if(updatedTo==="system")return t(locale,"已恢复跟随系统语言","Following System Language");return t(locale,"已更新显示语言","Language Updated")}function resolveUpdatedSummary(locale,updatedTo,systemLocale){if(updatedTo==="system")return t(locale,"已保存为默认 system · 自动跟随操作系统语言","Saved default (system) · Follows operating system language");if(updatedTo==="en"&&systemLocale==="zh")return t(locale,"已保存偏好 (en) · 优先于中文系统语言展示","Saved preference (en) · Overrides Chinese system language");if(updatedTo==="zh"&&systemLocale==="en")return t(locale,"已保存偏好 (zh) · 优先于英文系统语言展示","Saved preference (zh) · Overrides English system language");return t(locale,`已保存语言偏好 (${updatedTo})`,`Saved language preference (${updatedTo})`)}function renderLangDashboard(options){let{binName,resolved,updatedTo,color,home}=options,{locale}=resolved,safeBin=sanitizeInline(binName),{badge:makeBadge,bold,dim,token:cyan,green}=createHelpStyles(color),badge=makeBadge(`${HELP_BAR_BLOCK} ${safeBin.toUpperCase()} `),title=resolveDashboardTitle(locale,updatedTo),labelCols=locale==="zh"?12:14,kv=(label,val)=>{let pad=" ".repeat(Math.max(2,labelCols-displayWidth(label)));return` ${dim(label)}${pad}${val}`},sysText=`${sanitizeInline(resolved.system.rawTag)} ${dim("→")} ${resolved.system.locale}`,prefText=`${cyan(resolved.preference)} ${dim(`(${formatSourceNote(resolved,locale)})`)}`,cfgShort=sanitizeInline(shortenHomePath(resolved.configPath,home)),rows=["",` ${badge} ${bold(title)}`,"",kv(t(locale,"当前生效","Active"),bold(formatLocaleName(locale))),kv(t(locale,"自定义项","Preference"),prefText),kv(t(locale,"系统语言","System"),sysText),kv(t(locale,"配置文件","Config"),dim(cfgShort)),""];if(updatedTo!==void 0){let summary=resolveUpdatedSummary(locale,updatedTo,resolved.system.locale);rows.push(` ${green("✓")} ${dim(summary)}`)}else rows.push(` ${dim(t(locale,`切换语言: ${safeBin} lang <system|en|zh>`,`Switch language: ${safeBin} lang <system|en|zh>`))}`);return rows.join(`
|
|
12
|
+
`)}function runLangCommand(options){let env=options.env??process.env,home=resolveSafeHomeDir({homedir:options.homedir,env,platform:options.platform}),colors=options.color??detectColorChannels(env),invalidCode=options.invalidExitCode??1,out=options.out??((line)=>process.stdout.write(`${line}
|
|
13
|
+
`)),err=options.err??((line)=>{let safe=sanitizeInline(line),prefix=colors.stderr?`${paintHelp("✗","1;31",!0)} `:"";process.stderr.write(`${prefix}${safe}
|
|
14
|
+
`)}),current=resolveCliLocale(options),dashIdx=options.argv.indexOf("--"),rawPreDash=dashIdx===-1?options.argv:options.argv.slice(0,dashIdx),postDash=dashIdx===-1?[]:options.argv.slice(dashIdx+1),wantJson=options.json===!0||rawPreDash.includes("--json"),preDash=rawPreDash.filter((tok)=>tok!=="--json"),args=[...preDash,...postDash],emitErr=(code,message)=>{let safe=sanitizeInline(message);if(wantJson){let payload=JSON.stringify({ok:!1,error:{code,message:safe}});if(options.err!==void 0)options.err(payload);else process.stderr.write(`${payload}
|
|
15
|
+
`);return}err(safe)},badOpt=preDash.find((tok)=>tok!=="--help"&&tok!=="-h"&&tok.startsWith("-"));if(badOpt!==void 0)return emitErr("INVALID_ARGUMENT",t(current.locale,`未知选项: ${badOpt}`,`Unknown option: ${badOpt}`)),invalidCode;if(preDash.includes("--help")||preDash.includes("-h")){let extraPos=[...preDash.filter((tok)=>tok!=="--help"&&tok!=="-h"),...postDash];if(extraPos.length>0)return emitErr("INVALID_ARGUMENT",t(current.locale,`多余的参数: ${extraPos[0]} (用 ${options.binName} lang --help 查看用法)`,`Unexpected argument: ${extraPos[0]} (run '${options.binName} lang --help' for usage)`)),invalidCode;let help=formatLangHelp({binName:options.binName,envVarName:current.envVarName,configPath:current.configPath,locale:current.locale,color:wantJson?!1:colors.stdout,homedir:home,supportsJson:options.supportsJson,docsUrl:options.docsUrl});return out(wantJson?JSON.stringify({ok:!0,help},null,2):help),0}if(args.length===0)return out(wantJson?JSON.stringify({ok:!0,tool:options.toolName,...current},null,2):renderLangDashboard({binName:options.binName,resolved:current,color:colors.stdout,home})),0;if(args.length>1)return emitErr("INVALID_ARGUMENT",t(current.locale,`子命令 lang 至多接受 1 个参数 (用法: ${options.binName} lang [system|en|zh])`,`Too many arguments for 'lang' (usage: ${options.binName} lang [system|en|zh])`)),invalidCode;let rawTarget=args[0],target=parseLangPreference(rawTarget);if(target===null)return emitErr("INVALID_ARGUMENT",t(current.locale,`不支持的语言选项 "${rawTarget}" (可选值: system | en | zh)`,`Unsupported language "${rawTarget}" (expected: system | en | zh)`)),invalidCode;try{writePersistedLang(current.configPath,target)}catch(error){let msg=error instanceof Error?error.message:String(error);return emitErr("CONFIG_WRITE_FAILED",t(current.locale,`写入语言配置失败 (${current.configPath}): ${msg}`,`Failed to save language preference (${current.configPath}): ${msg}`)),1}let updated=resolveCliLocale({...options,flag:options.flag,env});return out(wantJson?JSON.stringify({ok:!0,updated:!0,tool:options.toolName,savedPreference:target,...updated},null,2):renderLangDashboard({binName:options.binName,resolved:updated,updatedTo:target,color:colors.stdout,home})),0}import{existsSync as existsSync3,realpathSync as realpathSync3}from"node:fs";import{posix as posix4,win32 as win324}from"node:path";import{posix as posix2}from"node:path";var HOMEBREW_RECEIPT_FILE="INSTALL_RECEIPT.json",HOMEBREW_CELLAR_REASON="命中 Homebrew Cellar 安装目录",SAFE_FORMULA_RE=/^[a-z0-9][a-z0-9@._+-]{0,127}$/i,SAFE_TAP_RE=/^[a-z0-9][a-z0-9._-]{0,63}\/[a-z0-9][a-z0-9._-]{0,63}$/i,RUNTIME_KEG_RE=/^(?:node|bun|nvm|fnm|volta|pnpm|yarn)(?:@[\d.]+)?$/i,CONTROL_CHAR_RE=/[\0\r\n]/;function normalizePosix(raw){return raw.replace(/\/+$/,"")}function isSafeHomebrewPrefix(raw){let norm=normalizePosix(raw.trim());if(norm===""||!norm.startsWith("/")||CONTROL_CHAR_RE.test(norm))return!1;let segs=norm.split("/");if(segs.includes(".")||segs.includes(".."))return!1;if(/(?:^|\/)node_modules(?:\/|$)/i.test(norm))return!1;return!0}function isSafeFormulaName(name){return name!==""&&name!=="."&&name!==".."&&!name.includes("..")&&!CONTROL_CHAR_RE.test(name)&&SAFE_FORMULA_RE.test(name)}function isSafeVersionSegment(version){return version!==""&&version!=="."&&version!==".."&&!version.includes("/")&&!CONTROL_CHAR_RE.test(version)}function parseHomebrewReceiptTap(raw){if(typeof raw!=="string"||raw.trim()==="")return;let parsed;try{parsed=JSON.parse(raw)}catch{return}if(typeof parsed!=="object"||parsed===null||Array.isArray(parsed))return;let source=parsed.source;if(typeof source!=="object"||source===null||Array.isArray(source))return;let tapRaw=source.tap;if(typeof tapRaw!=="string")return;let tap=tapRaw.trim();if(tap===""||tap.includes("..")||CONTROL_CHAR_RE.test(tap)||!SAFE_TAP_RE.test(tap))return;return tap}function matchUnderCellar(normalizedPath,cellarDir,requireLibexecForNodeModules=!1){if(CONTROL_CHAR_RE.test(normalizedPath)||normalizedPath.split("/").includes(".."))return null;let normCellar=normalizePosix(cellarDir);if(normCellar===""||!normCellar.startsWith("/"))return null;if(!normalizedPath.startsWith(`${normCellar}/`))return null;let segments=normalizedPath.slice(normCellar.length+1).split("/"),formula=segments[0]??"",version=segments[1]??"";if(!isSafeFormulaName(formula)||!isSafeVersionSegment(version))return null;if(RUNTIME_KEG_RE.test(formula))return null;let actualCellar=normalizedPath.slice(0,normCellar.length),kegDir=`${actualCellar}/${formula}/${version}`;if(requireLibexecForNodeModules&&normalizedPath.includes("/node_modules/")){if(!normalizedPath.startsWith(`${kegDir}/libexec/lib/node_modules/`))return null}let derivedPrefix=posix2.dirname(actualCellar);if(!isSafeHomebrewPrefix(derivedPrefix))return null;return{prefix:derivedPrefix,cellarDir:actualCellar,formula,kegDir}}function collectConfiguredCellars(env,realpath){let out=[],seen=new Set,add=(cellarDir)=>{let normCellar=normalizePosix(cellarDir);if(!isSafeHomebrewPrefix(normCellar)||!normCellar.endsWith("/Cellar"))return;if(seen.has(normCellar))return;seen.add(normCellar),out.push(normCellar)},envCellar=env.HOMEBREW_CELLAR?.trim();if(envCellar!==void 0&&envCellar!==""){add(envCellar);let resolved=normalizePosix(realpath(envCellar));if(resolved!==normalizePosix(envCellar))add(resolved)}let envPrefix=env.HOMEBREW_PREFIX?.trim();if(envPrefix!==void 0&&envPrefix!==""){let normPref=normalizePosix(envPrefix);if(isSafeHomebrewPrefix(normPref)){add(`${normPref}/Cellar`);let resolvedPref=normalizePosix(realpath(envPrefix));if(resolvedPref!==normPref&&isSafeHomebrewPrefix(resolvedPref))add(`${resolvedPref}/Cellar`)}}return out}var STANDARD_HOMEBREW_CELLARS=["/opt/homebrew/Cellar","/usr/local/Cellar","/home/linuxbrew/.linuxbrew/Cellar"];function extractHomebrewCellarLocation(candidate,env,realpath){let normalized=normalizePosix(candidate);if(!normalized.startsWith("/"))return null;for(let cellarDir of STANDARD_HOMEBREW_CELLARS){let hit=matchUnderCellar(normalized,cellarDir,!0);if(hit!==null)return hit}let linuxbrewMarker="/.linuxbrew/Cellar/",lbIdx=normalized.indexOf(linuxbrewMarker);if(lbIdx>0){let prefix=normalized.slice(0,lbIdx+11),hit=matchUnderCellar(normalized,`${prefix}/Cellar`,!0);if(hit!==null)return hit}for(let cellarDir of collectConfiguredCellars(env,realpath)){let hit=matchUnderCellar(normalized,cellarDir,!0);if(hit!==null)return hit}return null}function resolveHomebrewOrigin(input){let candidates=[],seen=new Set,push=(p,fromRoot)=>{if(typeof p!=="string"||p.trim()==="")return;let norm=normalizePosix(p);if(seen.has(norm))return;seen.add(norm),candidates.push({path:norm,fromRoot})};push(input.normalizedRoot,!0),push(input.rawPackageRoot,!0);for(let raw of input.rawCandidates??[])push(raw,!1);let normRoot=normalizePosix(input.normalizedRoot);for(let{path:cand,fromRoot}of candidates){let match=extractHomebrewCellarLocation(cand,input.env,input.realpath);if(match===null)continue;let formulaOpt=`${match.prefix}/opt/${match.formula}`;if(normRoot.includes("/node_modules/")){if(!(normRoot.startsWith(`${match.kegDir}/libexec/lib/node_modules/`)||normRoot.startsWith(`${formulaOpt}/libexec/lib/node_modules/`)))continue}if(!fromRoot){let insideSameKeg=normRoot===match.kegDir||normRoot.startsWith(`${match.kegDir}/`),insideFormulaOpt=normRoot.startsWith(`${formulaOpt}/`);if(!insideSameKeg&&!insideFormulaOpt)continue;if(insideFormulaOpt&&!insideSameKeg){let realOpt=normalizePosix(input.realpath(formulaOpt)),realKeg=normalizePosix(input.realpath(match.kegDir));if(realOpt===formulaOpt||realOpt!==realKeg)continue}}let receiptRaw=input.readText(input.joinPath(match.kegDir,HOMEBREW_RECEIPT_FILE)),tap=parseHomebrewReceiptTap(receiptRaw),formulaRef=tap!==void 0&&tap.toLowerCase()!=="homebrew/core"?`${tap}/${match.formula}`:match.formula;return{kind:"homebrew",formula:match.formula,...tap!==void 0?{tap}:{},formulaRef,kegDir:match.kegDir,prefix:match.prefix,reason:HOMEBREW_CELLAR_REASON,packageRoot:input.normalizedRoot}}return null}var EPHEMERAL_PATH_RULES=[["npx",["/_npx/"],"位于 npx 临时缓存目录 (_npx)"],["bunx",["/bunx-"],"位于 bunx 临时执行目录"],["pnpm-dlx",["/pnpm/dlx/","/pnpm-cache/dlx/","/pnpm-dlx/"],"位于 pnpm dlx 临时缓存目录"],["deno",["/deno/npm/"],"位于 Deno npm 缓存目录 (/deno/npm/)"]],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 detectEphemeralOrigin(candidates,packageRoot){for(let p of candidates){for(let[runner,markers,reason]of EPHEMERAL_PATH_RULES)if(markers.some((m)=>p.includes(m)))return{kind:"ephemeral",runner,reason,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}}return null}function detectFromStandardPaths(candidates,packageRoot){for(let rawCandidate of candidates){let candidate=rawCandidate.toLowerCase();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 detectProjectPm(projectDir,pathExists,joinPath){if(pathExists(joinPath(projectDir,"bun.lock"))||pathExists(joinPath(projectDir,"bun.lockb")))return"bun";if(pathExists(joinPath(projectDir,"pnpm-lock.yaml")))return"pnpm";if(pathExists(joinPath(projectDir,"yarn.lock")))return"yarn";return"npm"}import{mkdirSync as mkdirSync2,mkdtempSync,readFileSync as readFileSync3,renameSync as renameSync2,rmSync as rmSync2,writeFileSync as writeFileSync2}from"node:fs";import{tmpdir}from"node:os";import{join as join3}from"node: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}function isNewerVersion(current,latest){return compareSemver(current,latest)===-1}import{lstatSync as lstatSync2,readlinkSync,realpathSync as realpathSync2}from"node:fs";import{posix as posix3,resolve as resolve2,win32 as win323}from"node:path";var CONTROL_CHAR_RE2=/[\0\r\n]/,MACOS_SYS_ROOT_LINKS2=new Set(["/var","/tmp","/etc"]),WIN32_RESERVED_DATA_ROOT_RE=/^[a-z]:(?:$|\/(?:windows|program files(?: \(x86\))?|programdata)(?:\/|$)|\/users(?:\/[^/]+)?$|\/[^/]*~\d+(?:\.[^/]+)?(?:\/|$))/,WIN32_RESERVED_BIN_DIR_RE=/^[a-z]:(?:$|\/(?:windows|program files(?: \(x86\))?|programdata)(?:\/|$)|\/users$|\/[^/]*~\d+(?:\.[^/]+)?(?:\/|$))/,POSIX_RESERVED_DATA_ROOTS=new Set(["/","/usr","/bin","/sbin","/etc","/var","/opt","/tmp","/private","/private/etc","/private/tmp","/private/var","/system","/library","/applications","/users","/home","/root"]),POSIX_RESERVED_BIN_DIRS=new Set(["/","/bin","/sbin","/usr","/usr/bin","/usr/sbin","/etc","/var","/private","/private/etc","/private/var","/system","/library","/applications"]);function isAbsoluteAnyFlavor(rawPath){if(CONTROL_CHAR_RE2.test(rawPath))return!1;if(/^[\\/]{2}/.test(rawPath))return!1;if(rawPath.startsWith("/")){if(rawPath.includes("\\")||/\/{2,}/.test(rawPath))return!1;let segs=rawPath.replace(/\/+$/,"").split("/");if(segs.includes(".")||segs.includes(".."))return!1;return posix3.isAbsolute(rawPath)}if(/^[A-Za-z]:[/\\]/.test(rawPath)){let slashNorm=rawPath.replaceAll("\\","/");if(/\/{2,}/.test(slashNorm))return!1;let segs=slashNorm.replace(/\/+$/,"").split("/");if(segs.includes(".")||segs.includes(".."))return!1;if(segs.slice(1).some((seg)=>/[.\s]+$/.test(seg)))return!1;return win323.isAbsolute(rawPath)}return!1}function isWinStylePath(rawPath){return/^(?:[A-Za-z]:[/\\]|\\\\)/.test(rawPath)}function normalizeCanonicalPath(rawPath){let isWin=isWinStylePath(rawPath),resolved=isWin?win323.normalize(rawPath):posix3.normalize(rawPath);return(isWin?resolved.replaceAll("\\","/"):resolved).replace(/\/+$/,"")}function normalizeComparablePath(rawPath){let norm=normalizeCanonicalPath(rawPath);return isWinStylePath(rawPath)?norm.toLowerCase():norm}function hasTraversalSegment(rawPath){return rawPath.replaceAll("\\","/").split("/").includes("..")}function isExpectedBinName(binPath,tool){let norm=normalizeCanonicalPath(binPath),slash=norm.lastIndexOf("/"),rawBase=slash>=0?norm.slice(slash+1):norm;if(isWinStylePath(binPath)){let base=rawBase.toLowerCase(),expected=tool.toLowerCase();return base===expected||base===`${expected}.cmd`||base===`${expected}.bat`||base===`${expected}.exe`}return rawBase===tool}function isSafeStandaloneDataDir(dataDir){let norm=normalizeCanonicalPath(dataDir).toLowerCase();if(norm==="")return!1;if(/^[a-z]:/.test(norm))return!WIN32_RESERVED_DATA_ROOT_RE.test(norm);if(POSIX_RESERVED_DATA_ROOTS.has(norm)||norm.startsWith("/system/")||/^\/(?:users|home)\/[^/]+$/.test(norm))return!1;return!0}function isSafeStandaloneBinDir(binPath){let normBin=normalizeCanonicalPath(binPath).toLowerCase(),slash=normBin.lastIndexOf("/"),binDir=slash<=0?"/":normBin.slice(0,slash);if(/^[a-z]:/.test(normBin))return!WIN32_RESERVED_BIN_DIR_RE.test(binDir);if(POSIX_RESERVED_BIN_DIRS.has(binDir)||binDir.startsWith("/system/"))return!1;return!0}function isSafeStandaloneTopology(dataDir,appDir,runtimeDir,tool){let isWin=isWinStylePath(dataDir);if(isWin!==isWinStylePath(appDir)||isWin!==isWinStylePath(runtimeDir))return!1;let normData=normalizeComparablePath(dataDir),normApp=normalizeComparablePath(appDir),normRuntime=normalizeComparablePath(runtimeDir),tName=isWin?tool.toLowerCase():tool;if(normRuntime!==`${normData}/runtime`)return!1;return normApp===`${normData}/apps/${tName}`||normApp===`${normData}/${tName}`}function isValidStandalonePathLayout(input){return![input.dataDir,input.appDir,input.runtimeDir,input.binPath].some((p)=>!isAbsoluteAnyFlavor(p)||hasTraversalSegment(p))&&isSafeStandaloneDataDir(input.dataDir)&&isSafeStandaloneBinDir(input.binPath)&&isSafeStandaloneTopology(input.dataDir,input.appDir,input.runtimeDir,input.tool)&&isExpectedBinName(input.binPath,input.tool)}function isReservedSystemParentDir(dirPath){let norm=normalizeCanonicalPath(dirPath).toLowerCase();if(norm===""||norm==="/")return!0;if(/^[a-z]:/.test(norm))return WIN32_RESERVED_DATA_ROOT_RE.test(norm);return POSIX_RESERVED_DATA_ROOTS.has(norm)||POSIX_RESERVED_BIN_DIRS.has(norm)||/^\/(?:users|home)\/[^/]+$/.test(norm)||norm.startsWith("/system/")}function stripWinExtendedPrefix(p){if(/^[\\/]{2}[?.][\\/]unc[\\/]/i.test(p))return`\\\\${p.slice(8)}`;return/^[\\/]{2}[?.][\\/]/.test(p)?p.slice(4):p}function probePathSymlink(cur){try{return lstatSync2(cur).isSymbolicLink()?{kind:"link",target:readlinkSync(cur)}:{kind:"none"}}catch(err){let code=err.code;if(code==="ENOENT"||code==="ENOTDIR")return{kind:"none"};return{kind:"error"}}}function splitPathParts(tail,isWin){return tail.split(isWin?/[\\/]+/:/\/+/).filter((s)=>s!=="")}function buildPathFromParts(root,parts,isWin){if(parts.length===0)return root;let sep=isWin?"\\":"/";return`${root.endsWith("/")||root.endsWith("\\")?root:`${root}${sep}`}${parts.join(sep)}`}function resolveRealBestEffortPath(rawPath,resolveRealExact,platform=process.platform){let isWin=platform==="win32",ops=isWin?win323:posix3,isWinDriveRootRel=(v)=>isWin&&(v.startsWith("\\")||v.startsWith("/"))&&!/^[\\/]{2}/.test(v),isAbsForHost=(v)=>isWin?/^(?:[A-Za-z]:[/\\]|[\\/]{2}(?![?.][/\\])[^\\/]+[/\\][^\\/]+)/.test(v):v.startsWith("/"),normalizedInput=isWin?stripWinExtendedPrefix(rawPath):rawPath;if(isWin&&/^[A-Za-z]:(?![/\\])/.test(normalizedInput))return null;let root,queue;if(isAbsForHost(normalizedInput))root=ops.parse(normalizedInput).root,queue=splitPathParts(normalizedInput.slice(root.length),isWin);else if(isWinDriveRootRel(normalizedInput)){let cwd=stripWinExtendedPrefix(resolve2("."));root=win323.parse(cwd).root,queue=splitPathParts(normalizedInput,!0)}else{let cwd=isWin?stripWinExtendedPrefix(resolve2(".")):resolve2(".");root=ops.parse(cwd).root,queue=[...splitPathParts(cwd.slice(root.length),isWin),...splitPathParts(normalizedInput,isWin)]}let resolvedParts=[],hops=0,steps=0;while(queue.length>0){if(steps+=1,steps>4096)return null;let seg=queue.shift();if(seg===""||seg===".")continue;if(seg===".."){resolvedParts.pop();continue}let nextPath=buildPathFromParts(root,[...resolvedParts,seg],isWin),probed=probePathSymlink(nextPath);if(probed.kind==="error")return null;if(probed.kind==="link"){if(hops+=1,hops>40)return null;let linkTarget=isWin?stripWinExtendedPrefix(probed.target):probed.target;if(isAbsForHost(linkTarget))root=ops.parse(linkTarget).root,resolvedParts.length=0,queue=[...splitPathParts(linkTarget.slice(root.length),isWin),...queue];else if(isWinDriveRootRel(linkTarget))resolvedParts.length=0,queue=[...splitPathParts(linkTarget,!0),...queue];else queue=[...splitPathParts(linkTarget,isWin),...queue];continue}resolvedParts.push(seg)}for(let i=resolvedParts.length;i>=0;i-=1){let prefixPath=buildPathFromParts(root,resolvedParts.slice(0,i),isWin),exact=resolveRealExact(prefixPath);if(exact!==null){let rest=resolvedParts.slice(i);if(rest.length===0)return exact;return buildPathFromParts(exact,rest,isWin)}}return buildPathFromParts(root,resolvedParts,isWin)}function resolveRealExactSafe(p){try{return stripWinExtendedPrefix((realpathSync2.native??realpathSync2)(p))}catch{return null}}function normCanonical(p,platform){let norm=(platform==="win32"?p.replaceAll("\\","/"):p).replace(/\/+$/,"");return platform==="win32"||platform==="darwin"?norm.toLowerCase():norm}function isRealPathHomeOrDirectChild(configDir,homeDir,platform=process.platform){if(homeDir===void 0||homeDir.trim()==="")return!1;let realCfg=resolveRealExactSafe(configDir);if(realCfg===null)return!1;let realHome=resolveRealBestEffortPath(homeDir.trim(),resolveRealExactSafe,platform);if(realHome===null)return!0;let normCfg=normCanonical(realCfg,platform),normHome=normCanonical(realHome,platform),cfgParent=(platform==="win32"?win323:posix3).dirname(realCfg);return normCfg===normHome||normCanonical(cfgParent,platform)===normHome||normHome.startsWith(`${normCfg}/`)}function isRealPathHomeOrAncestor(dirPath,homeDir,platform=process.platform){if(homeDir===void 0||homeDir.trim()==="")return!1;let realDir=resolveRealBestEffortPath(dirPath.trim(),resolveRealExactSafe,platform),realHome=resolveRealBestEffortPath(homeDir.trim(),resolveRealExactSafe,platform);if(realDir===null||realHome===null)return!0;let normDir=normCanonical(realDir,platform),normHome=normCanonical(realHome,platform);return normDir===normHome||normHome.startsWith(`${normDir}/`)}function assertPathsNoSymlinkAncestors(targets,isSymlinkFn,platform=process.platform){let checkSym=isSymlinkFn??((p)=>{try{return lstatSync2(p).isSymbolicLink()}catch(err){let code=err.code;if(code==="ENOENT"||code==="ENOTDIR")return!1;throw err}}),isWin=platform==="win32",pathMod=isWin?win323:posix3;for(let target of targets){if(isWin?!/^[A-Za-z]:[/\\]/.test(target):!target.startsWith("/"))throw Error(`Refused uninstall path mismatched with host platform (${platform}): ${target}`);let parseInput=isWin?target.replaceAll("/","\\"):target,{root}=pathMod.parse(parseInput),parts=parseInput.slice(root.length).split(isWin?/[\\/]+/:/\/+/).filter(Boolean),cur=root;for(let i=0;i<parts.length;i+=1){if(cur=isWin?win323.join(cur,parts[i]):posix3.join(cur,parts[i]),i!==parts.length-1&&platform==="darwin"&&MACOS_SYS_ROOT_LINKS2.has(cur))continue;if(checkSym(cur))throw Error(`Refused uninstall through symlink path: ${cur}`)}}}function assertSafeStandaloneCleanupOrigin(origin,isSymlinkFn,platform=process.platform,homeGuard){if(!isValidStandalonePathLayout(origin))throw Error(`Refused unsafe standalone uninstall path layout: ${origin.dataDir}`);if(assertPathsNoSymlinkAncestors([origin.dataDir,origin.appDir,origin.runtimeDir,origin.binPath],isSymlinkFn,platform),typeof homeGuard==="object"&&homeGuard.invalidExplicitHome)throw Error("Refused unsafe standalone uninstall under invalid HOME/USERPROFILE environment");let homeList=[];if(typeof homeGuard==="string"){if(homeGuard.trim()!=="")homeList=[homeGuard]}else if(homeGuard!==void 0)homeList=homeGuard.homeDirs;for(let homeDir of homeList)for(let p of[origin.dataDir,origin.appDir,origin.runtimeDir])if(isRealPathHomeOrAncestor(p,homeDir,platform))throw Error(`Refused unsafe standalone uninstall overlapping home directory: ${p}`)}var STANDALONE_MARKER_FILE=".clis-install.json",SAFE_TOOL_NAME_RE=/^[a-z0-9][a-z0-9-]{0,31}$/,CONTROL_CHAR_RE3=/[\0\r\n]/;function readTextOrNull(path){try{return readFileSync3(path,"utf8")}catch{return null}}function asSafeString(val){if(typeof val!=="string")return null;let trimmed=val.trim();if(trimmed===""||CONTROL_CHAR_RE3.test(trimmed))return null;return trimmed}function asSafePathString(val){if(typeof val!=="string")return null;if(val.trim()===""||CONTROL_CHAR_RE3.test(val))return null;return val}function parseStandaloneInstallMarker(raw){if(typeof raw!=="string"||raw.trim()==="")return null;let parsed;try{parsed=JSON.parse(raw)}catch{return null}if(typeof parsed!=="object"||parsed===null||Array.isArray(parsed))return null;let obj=parsed;if(obj.schemaVersion!==1||obj.method!=="script")return null;let tool=asSafeString(obj.tool),packageName=asSafeString(obj.packageName),dataDir=asSafePathString(obj.dataDir),appDir=asSafePathString(obj.appDir),runtimeDir=asSafePathString(obj.runtimeDir),binPath=asSafePathString(obj.binPath);if(tool===null||!SAFE_TOOL_NAME_RE.test(tool)||packageName===null||!isValidPackageName(packageName)||dataDir===null||appDir===null||runtimeDir===null||binPath===null)return null;if(!isValidStandalonePathLayout({tool,dataDir,appDir,runtimeDir,binPath}))return null;return{schemaVersion:1,method:"script",tool,packageName,dataDir,appDir,runtimeDir,binPath,version:asSafeString(obj.version)??void 0,updatedAt:asSafeString(obj.updatedAt)??void 0}}function resolveStandaloneOrigin(rawPackageRoot,normalizedRoot,readText,joinPath,options){let marker=parseStandaloneInstallMarker(readText(joinPath(rawPackageRoot,STANDALONE_MARKER_FILE)));if(marker===null)return null;let realpathFn=options?.realpath,markerForms=new Set([normalizeComparablePath(stripWinExtendedPrefix(marker.appDir))]),realMarkerApp=realpathFn?.(marker.appDir)??null;if(realMarkerApp!==null&&realMarkerApp!=="")markerForms.add(normalizeComparablePath(stripWinExtendedPrefix(realMarkerApp)));let actualInputs=[normalizedRoot,rawPackageRoot],matched=!1;for(let cand of actualInputs){let norm=normalizeComparablePath(stripWinExtendedPrefix(cand));if(markerForms.has(norm)){matched=!0;break}let realCand=realpathFn?.(cand)??null;if(realCand!==null&&realCand!==""&&markerForms.has(normalizeComparablePath(stripWinExtendedPrefix(realCand)))){matched=!0;break}}if(!matched)return null;return{kind:"standalone",tool:marker.tool,packageName:marker.packageName,dataDir:marker.dataDir,appDir:marker.appDir,runtimeDir:marker.runtimeDir,binPath:marker.binPath,reason:"独立脚本安装 (.clis-install.json)",packageRoot:normalizedRoot}}function readExtractedPackageJson(stagingDir){try{let raw=readFileSync3(join3(stagingDir,"package.json"),"utf8"),parsed=JSON.parse(raw);if(typeof parsed!=="object"||parsed===null)return null;let depsRaw=parsed.dependencies,dependencies;if(typeof depsRaw==="object"&&depsRaw!==null&&!Array.isArray(depsRaw)){let entries=Object.entries(depsRaw).filter((pair)=>typeof pair[1]==="string");if(entries.length>0)dependencies=Object.fromEntries(entries)}return{name:typeof parsed.name==="string"?parsed.name:void 0,version:typeof parsed.version==="string"?parsed.version:void 0,bin:parsed.bin,dependencies}}catch{return null}}function removeDirBestEffort(dir){try{rmSync2(dir,{recursive:!0,force:!0,maxRetries:3,retryDelay:50})}catch{}}function sleepSyncMs(ms){let buf=new SharedArrayBuffer(4);Atomics.wait(new Int32Array(buf),0,0,ms)}var UNTRUSTED_STAGING_CONFIGS=["bunfig.toml",".bunfig.toml",".npmrc",".env","node_modules","bun.lock","bun.lockb","package-lock.json","npm-shrinkwrap.json","yarn.lock","pnpm-lock.yaml"],STRIPPED_STAGING_PKG_FIELDS=["devDependencies","scripts","overrides","resolutions","patchedDependencies","workspaces","optionalDependencies","peerDependencies","peerDependenciesMeta","trustedDependencies","catalog","catalogs","bundledDependencies","bundleDependencies"],SAFE_DEP_NAME_RE=/^(?:@[a-z0-9~_][a-z0-9._~-]*\/)?[a-z0-9~_][a-z0-9._~-]*$/i,SAFE_DEP_VERSION_RE=/^[a-zA-Z0-9._*xX^~<>=|+\-\s]+$/,LOCAL_ARCHIVE_SPEC_RE=/\.(?:tgz|tar\.gz|tar)$/i;function hasDepControlChar(s){for(let i=0;i<s.length;i+=1){let code=s.charCodeAt(i);if(code<=31||code===127)return!0}return!1}function isSafeDepVersionOrTag(v){if(v===""||v.startsWith(".")||v.startsWith("-"))return!1;if(LOCAL_ARCHIVE_SPEC_RE.test(v))return!1;if(v.startsWith("~")&&!/^~(?:\s*[vV]?\d|=)/.test(v))return!1;if(/[/:\\]/.test(v))return!1;if(v.split(/\s+/).some((tok)=>tok.startsWith(".")||LOCAL_ARCHIVE_SPEC_RE.test(tok)))return!1;return SAFE_DEP_VERSION_RE.test(v)}function isSafeRegistryDepSpec(rawSpec){if(typeof rawSpec!=="string")return!1;let spec=rawSpec.trim();if(spec===""||spec.length>256||hasDepControlChar(spec))return!1;if(spec.startsWith("npm:")){let rest=spec.slice(4),atIdx=rest.startsWith("@")?rest.indexOf("@",1):rest.indexOf("@"),aliasPkg=atIdx===-1?rest:rest.slice(0,atIdx),aliasVer=atIdx===-1?"":rest.slice(atIdx+1).trim();if(!SAFE_DEP_NAME_RE.test(aliasPkg)||aliasPkg.split("/").some((seg)=>seg==="."||seg===".."))return!1;return atIdx===-1?!0:isSafeDepVersionOrTag(aliasVer)}return isSafeDepVersionOrTag(spec)}function assertSafeRegistryDependencies(deps){if(deps===void 0||deps===null)return;if(typeof deps!=="object"||Array.isArray(deps))throw Error("package.json dependencies field is invalid");for(let[depName,depSpec]of Object.entries(deps)){if(!SAFE_DEP_NAME_RE.test(depName)||depName.split("/").some((seg)=>seg==="."||seg===".."))throw Error(`Refusing invalid dependency name: ${depName}`);if(!isSafeRegistryDepSpec(depSpec))throw Error(`Refusing non-registry or unsafe dependency specifier: ${depName}@${String(depSpec)}`)}}function sanitizeStagingPackageJson(stagingDir){for(let cfg of UNTRUSTED_STAGING_CONFIGS)try{rmSync2(join3(stagingDir,cfg),{recursive:!0,force:!0})}catch{}let pkgPath=join3(stagingDir,"package.json"),parsed;try{parsed=JSON.parse(readFileSync3(pkgPath,"utf8"))}catch{return}if(typeof parsed!=="object"||parsed===null||Array.isArray(parsed))return;let obj=parsed;if(assertSafeRegistryDependencies(obj.dependencies),!STRIPPED_STAGING_PKG_FIELDS.some((field)=>(field in obj)))return;let prodPkg={...obj};for(let field of STRIPPED_STAGING_PKG_FIELDS)delete prodPkg[field];writeFileSync2(pkgPath,`${JSON.stringify(prodPkg,null,2)}
|
|
16
|
+
`,"utf8")}function createIsolatedDepConfigs(){let cfgDir=mkdtempSync(join3(tmpdir(),"cli-updater-depcfg-"));try{let cleanBunfig=join3(cfgDir,"bunfig.toml"),emptyUserNpmrc=join3(cfgDir,"empty-user.npmrc"),emptyGlobalNpmrc=join3(cfgDir,"empty-global.npmrc"),emptyHome=join3(cfgDir,"empty-home");return mkdirSync2(emptyHome,{recursive:!0}),writeFileSync2(cleanBunfig,`env = false
|
|
17
|
+
preload = []
|
|
18
|
+
`,"utf8"),writeFileSync2(emptyUserNpmrc,"","utf8"),writeFileSync2(emptyGlobalNpmrc,"","utf8"),{cfgDir,cleanBunfig,emptyUserNpmrc,emptyGlobalNpmrc,emptyHome}}catch(err){throw removeDirBestEffort(cfgDir),err}}function buildDepInstallEnv(baseEnv,label,cfg){let scrubbed={};for(let[key,value]of Object.entries(baseEnv)){let low=key.toLowerCase();if(low.startsWith("npm_config_")||low.startsWith("bun_config_")||low==="npm_execpath"||low==="npm_lifecycle_event"||low==="npm_lifecycle_script"||low==="npm_package_json"||low==="init_cwd"||low==="bun_options"||low==="bun_inspect_preload"||low==="node_options"||low==="node_tls_reject_unauthorized")continue;scrubbed[key]=value}let overlay=label==="npm"?{NPM_CONFIG_USERCONFIG:cfg.emptyUserNpmrc,NPM_CONFIG_GLOBALCONFIG:cfg.emptyGlobalNpmrc}:{HOME:cfg.emptyHome,XDG_CONFIG_HOME:cfg.emptyHome,USERPROFILE:cfg.emptyHome},overlayLower=new Set(Object.keys(overlay).map((k)=>k.toLowerCase()));for(let key of Object.keys(scrubbed))if(overlayLower.has(key.toLowerCase()))delete scrubbed[key];return{...scrubbed,...overlay}}function renameWithRetry(src,dest){let lastError;for(let attempt=0;attempt<4;attempt+=1)try{renameSync2(src,dest);return}catch(error){lastError=error;let code=typeof error==="object"&&error!==null&&"code"in error?String(error.code):"";if((code==="EBUSY"||code==="EPERM"||code==="EACCES")&&attempt+1<4){sleepSyncMs(60*(attempt+1));continue}throw error}throw lastError}var SUPPORTED_PACKAGE_MANAGERS=["bun","npm","pnpm","yarn","volta"],LIB_NODE_MODULES_HEURISTIC_REASON="命中标准 <prefix>/lib/node_modules 全局目录";function isWinFlavorPath(path){return/^(?:[A-Za-z]:[/\\]|[\\/]{2}[?.][\\/]|\\\\)/.test(path)}function normalizeSlashes(path){return isWinFlavorPath(path)?path.replaceAll("\\","/").replace(/\/+$/,""):path.replace(/\/+$/,"")}function joinForPath(base,...parts){return isWinFlavorPath(base)?win324.join(base,...parts):posix4.join(base,...parts)}function foldPath(path){return normalizeSlashes(path).toLowerCase()}function isWithinDir(child,parent){let bareDrive=/^[A-Za-z]:(?![/\\])/;if(bareDrive.test(parent)||bareDrive.test(child))return!1;let isWin=isWinFlavorPath(child)||isWinFlavorPath(parent),ops=isWin?win324:posix4,rawP=isWin?stripWinExtendedPrefix(parent):parent,rawC=isWin?stripWinExtendedPrefix(child):child,badWin=(s)=>s===""||bareDrive.test(s)||/^[/\\](?![/\\])/.test(s);if(isWin?badWin(rawP)||badWin(rawC):rawP===""||rawC==="")return!1;let np=isWin?ops.normalize(rawP).toLowerCase():ops.normalize(rawP),nc=isWin?ops.normalize(rawC).toLowerCase():ops.normalize(rawC);if(ops.isAbsolute(np)!==ops.isAbsolute(nc))return!1;let rel=ops.relative(np,nc);return rel===""||rel!==".."&&!rel.startsWith(`..${ops.sep}`)&&!ops.isAbsolute(rel)}function collectRawCandidates(rawPackageRoot,packageRoot,rawPaths){let seen=new Set([isWinFlavorPath(rawPackageRoot)?packageRoot.toLowerCase():packageRoot]),out=[];for(let raw of rawPaths??[]){if(typeof raw!=="string"||raw.trim()==="")continue;let norm=normalizeSlashes(raw),key=isWinFlavorPath(raw)?norm.toLowerCase():norm;if(!seen.has(key))seen.add(key),out.push(norm)}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 buildEnvRootRules(env,realpath,winContext){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?.trim()||env.npm_config_prefix?.trim();if(npmPrefix!==void 0&&npmPrefix!==""){let npmRoots=expandRootVariants(npmPrefix,realpath).flatMap((base)=>{let trimmed=base.trim();if(trimmed==="")return[];let effective=winContext&&/^\/\/[^/]/.test(trimmed)?`\\\\${trimmed.slice(2)}`:trimmed;return[joinForPath(effective,"lib","node_modules"),joinForPath(effective,"node_modules")]});if(npmRoots.length>0)rules.push({pm:"npm",roots:npmRoots,reason:"位于环境变量 NPM_CONFIG_PREFIX 目录内"})}return rules}function detectFromEnvRoots(candidates,env,packageRoot,realpath,winContext){if(candidates.length===0)return null;let rules=buildEnvRootRules(env,realpath,winContext);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}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(rawPackageRoot,packageRoot,pathExists){let libIdx=packageRoot.toLowerCase().lastIndexOf("/lib/node_modules/");if(libIdx<=0)return null;let prefixDir=packageRoot.slice(0,libIdx),probeDir=rawPackageRoot.startsWith("\\\\")&&prefixDir.startsWith("//")?`\\\\${prefixDir.slice(2)}`:prefixDir;if(pathExists(joinForPath(probeDir,"package.json")))return null;return{kind:"global",pm:"npm",reason:LIB_NODE_MODULES_HEURISTIC_REASON,packageRoot}}function detectGlobalForCandidates(rawCandidates,normCandidates,input){if(rawCandidates.length===0&&normCandidates.length===0)return null;return detectFromEnvRoots(rawCandidates,input.env,input.packageRoot,input.realpath,input.winContext)??detectFromStandardPaths(normCandidates,input.packageRoot)??detectFromGlobalRoots(rawCandidates,input.globalRoots,input.packageRoot,input.realpath)}function detectInstallOriginFromPath(input){let env=input.env??process.env,pathExists=input.pathExists??existsSync3,readText=input.readText??readTextOrNull,realpath=input.realpath??safeRealpath,packageRoot=normalizeSlashes(input.packageRoot),foldedRoot=packageRoot.toLowerCase(),rawCandidates=collectRawCandidates(input.packageRoot,packageRoot,input.rawPaths),foldedRawCandidates=rawCandidates.map((c)=>c.toLowerCase());if(!foldedRoot.includes("/node_modules/")&&pathExists(joinForPath(input.packageRoot,"src","cli.ts")))return{kind:"source",reason:"包根目录位于本地源码工作树 (存在 src/cli.ts)",packageRoot};if(!foldedRoot.includes("/node_modules/")){let standalone=resolveStandaloneOrigin(input.packageRoot,packageRoot,readText,joinForPath,{rawCandidates:input.rawPaths,realpath});if(standalone!==null)return standalone}let homebrew=resolveHomebrewOrigin({rawPackageRoot:input.packageRoot,normalizedRoot:packageRoot,rawCandidates:input.rawPaths,env,readText,realpath,joinPath:joinForPath});if(homebrew!==null)return homebrew;let ephemeral=detectEphemeralOrigin([foldedRoot,...foldedRawCandidates],packageRoot);if(ephemeral!==null)return ephemeral;let rawLowPaths=(input.rawPaths??[]).filter((p)=>typeof p==="string"&&p.trim()!==""),globalCtx={env,globalRoots:input.globalRoots,packageRoot,realpath,winContext:isWinFlavorPath(input.packageRoot)},fromGlobal=detectGlobalForCandidates([input.packageRoot],[packageRoot],globalCtx)??detectGlobalForCandidates(rawLowPaths,rawCandidates,globalCtx);if(fromGlobal!==null)return fromGlobal;let fromHeuristic=detectFromLibNodeModulesHeuristic(input.packageRoot,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,hasPkgJson=pathExists(joinForPath(probeDir,"package.json"));if(!hasPkgJson&&/^\/\/[^/]/.test(projectDir)){let uncProbe=`\\\\${projectDir.slice(2)}`;if(pathExists(joinForPath(uncProbe,"package.json")))probeDir=uncProbe,hasPkgJson=!0}if(hasPkgJson)return{kind:"local-project",projectDir,suggestedPm:detectProjectPm(probeDir,pathExists,joinForPath),reason:`位于项目本地 node_modules (${projectDir})`,packageRoot}}return{kind:"unknown",reason:"未匹配已知全局包管理器路径或本地源码工作树",packageRoot}}function safeRealpath(path){try{let fn=realpathSync3.native??realpathSync3;return stripWinExtendedPrefix(fn(path))}catch{return path}}var BIDI_AND_ZERO_WIDTH_RE=/[\u200b-\u200f\u202a-\u202e\u2066-\u2069\ufeff]/g,CONTROL_CHAR_RE4=/\p{Cc}/gu,BAR_BLOCK="▍";function stderrSupportsSpinner(env=process.env){return supportsStreamColor(process.stderr,env)}function sanitizeText(raw){return stripAnsi(raw).replace(BIDI_AND_ZERO_WIDTH_RE,"").replace(CONTROL_CHAR_RE4," ").replace(/\s+/g," ").trim()}function sanitizeMultilineTail(raw,maxLines=12,maxChars=2048){let rawLines=stripAnsi(raw).split(/\r\n|\r|\n/).map((line)=>line.replace(BIDI_AND_ZERO_WIDTH_RE,"").replace(CONTROL_CHAR_RE4," ").replace(/\s+$/g,"")),start=0,end=rawLines.length;while(start<end&&rawLines[start].trim()==="")start+=1;while(end>start&&rawLines[end-1].trim()==="")end-=1;let meaningful=rawLines.slice(start,end);if(meaningful.length===0)return{lines:[],clipped:!1};let clipped=meaningful.length>maxLines,tail=meaningful.slice(-maxLines),kept=[],chars=0;for(let i=tail.length-1;i>=0;i-=1){let line=tail[i];if(chars+line.length+(kept.length>0?1:0)>maxChars&&kept.length>0){clipped=!0;break}let safeLine=line.length>maxChars?`…${line.slice(-(maxChars-1))}`:line;if(safeLine!==line)clipped=!0;kept.push(safeLine),chars+=safeLine.length+(kept.length>1?1:0)}return kept.reverse(),{lines:kept,clipped}}function extractRegistryHost(registry){try{return new URL(registry).host}catch{return""}}var KV_LABEL_COLS=10;function createUpdateUi(color,locale="zh"){let{stdout:out,stderr:err}=color,labelCols=locale==="en"?15:KV_LABEL_COLS;return{header(binName){let badgeText=`${BAR_BLOCK} ${sanitizeText(binName).toUpperCase()} `;return`${paintSgr(badgeText,"1;7",out)} ${paintSgr(t(locale,"自更新","Self-Update"),"1",out)}`},kv(label,value,tone="plain"){let safeLabel=sanitizeText(label),safeValue=sanitizeText(value),pad=" ".repeat(Math.max(2,labelCols-displayWidth(safeLabel))),styledValue=safeValue;if(tone==="bold")styledValue=paintSgr(safeValue,"1",out);else if(tone==="cyan")styledValue=paintSgr(safeValue,"36",out);else if(tone==="dim")styledValue=paintSgr(safeValue,"2",out);return`${paintSgr(safeLabel,"2",out)}${pad}${styledValue}`},body(text){return sanitizeText(text)},hint(text){return paintSgr(sanitizeText(text),"2",out)},warn(text){return paintSgr(sanitizeText(text),"33",out)},success(text,suffix){let tail=suffix!==void 0&&suffix!==""?` ${paintSgr(sanitizeText(suffix),"2",out)}`:"";return`${sanitizeText(text)}${tail} ${paintSgr("✓","1;32",out)}`},foundUpdate(fromVer,toVer,registry){let safeFrom=sanitizeText(fromVer),safeTo=sanitizeText(toVer),safeReg=sanitizeText(registry),arrow=paintSgr("→","2",out),target=paintSgr(`v${safeTo}`,"1;36",out);if(locale==="en"){let src=paintSgr(`(${safeReg})`,"2",out);return`Update available: v${safeFrom} ${arrow} ${target} ${src}`}let src=paintSgr(`(源: ${safeReg})`,"2",out);return`发现新版本: v${safeFrom} ${arrow} ${target} ${src}`},error(text){let safe=sanitizeText(text);return err?`${paintSgr("✗","1;31",!0)} ${safe}`:safe},errorHint(text){let safe=sanitizeText(text);return paintSgr(safe,"2",err)},errorLogLine(line){return`${paintSgr("│","2",err)} ${line}`}}}var UPDATE_VALUE_FLAGS=["--pm","--registry","--lang"],PM_SET=new Set(SUPPORTED_PACKAGE_MANAGERS);function isPackageManager(value){return PM_SET.has(value)}function applyPm(options,value,locale){let normalized=value.trim().toLowerCase(),list=SUPPORTED_PACKAGE_MANAGERS.join(" | ");if(!isPackageManager(normalized))return t(locale,`参数 --pm 不支持 "${value}" (可选值: ${list})`,`Invalid --pm value "${value}" (expected: ${list})`);return options.pm=normalized,null}function applyRegistry(options,value,locale){let trimmed=value.trim();if(!isValidRegistryUrl(trimmed))return t(locale,`参数 --registry 不是合法的 http(s) URL: "${value}"`,`Invalid --registry URL (must be http/https): "${value}"`);return options.registry=trimmed,null}function applyLang(options,value,locale){let parsed=parseLangPreference(value);if(parsed===null)return t(locale,`参数 --lang 不支持 "${value}" (可选值: system | en | zh)`,`Invalid --lang value "${value}" (expected: system | en | zh)`);return options.lang=parsed,null}function nextValueToken(argv,index){let next=argv[index+1];if(next===void 0||next===""||next.startsWith("-"))return null;return next}function parseUpdateArgs(argv,locale="zh",binName){let options={check:!1,force:!1,verbose:!1,help:!1},pmList=SUPPORTED_PACKAGE_MANAGERS.join(" | "),helpCmd=binName!==void 0&&binName.trim()!==""?`${sanitizeText(binName)} update --help`:"update --help",jsonRequested=!1,expectValue=!1;for(let i=0;i<argv.length;i+=1){let token=argv[i];if(expectValue){if(expectValue=!1,token==="--json"){jsonRequested=!0;continue}if(token==="--"||!token.startsWith("-"))continue}if(token==="--")break;if(token==="--json"){jsonRequested=!0;continue}if(token==="--pm"||token==="--registry"||token==="--lang")expectValue=!0}let preLang=stripLangArgs(argv,{fallbackLocale:locale,valueFlags:new Set(UPDATE_VALUE_FLAGS)}).lang,activeLocale=preLang==="en"||preLang==="zh"?preLang:locale,usageError=(message)=>({ok:!1,message:`${message} ${t(activeLocale,`(用 ${helpCmd} 查看用法)`,`(run '${helpCmd}' for usage)`)}`,...jsonRequested?{json:!0}:{}}),afterDashDash=!1;for(let i=0;i<argv.length;i+=1){let arg=argv[i];if(!afterDashDash&&arg==="--"){afterDashDash=!0;continue}if(afterDashDash||!arg.startsWith("-"))return usageError(t(activeLocale,`多余的参数: ${arg}`,`Unexpected argument: ${arg}`));if(arg==="--help"||arg==="-h"){options.help=!0;continue}if(arg==="--json"){options.json=!0;continue}if(arg==="--check"){options.check=!0;continue}if(arg==="--force"){options.force=!0;continue}if(arg==="--verbose"){options.verbose=!0;continue}if(arg==="--pm"){let val=nextValueToken(argv,i);if(val===null)return usageError(t(activeLocale,`参数 --pm 缺少取值 (可选值: ${pmList})`,`Option --pm requires a value (expected: ${pmList})`));let err=applyPm(options,val,activeLocale);if(err!==null)return usageError(err);i+=1;continue}if(arg.startsWith("--pm=")){let val=arg.slice(5);if(val==="")return usageError(t(activeLocale,`参数 --pm 缺少取值 (可选值: ${pmList})`,`Option --pm requires a value (expected: ${pmList})`));let err=applyPm(options,val,activeLocale);if(err!==null)return usageError(err);continue}if(arg==="--registry"){let val=nextValueToken(argv,i);if(val===null)return usageError(t(activeLocale,"参数 --registry 缺少取值","Option --registry requires a URL value"));let err=applyRegistry(options,val,activeLocale);if(err!==null)return usageError(err);i+=1;continue}if(arg.startsWith("--registry=")){let val=arg.slice(11);if(val==="")return usageError(t(activeLocale,"参数 --registry 缺少取值","Option --registry requires a URL value"));let err=applyRegistry(options,val,activeLocale);if(err!==null)return usageError(err);continue}if(arg==="--lang"){let val=nextValueToken(argv,i);if(val===null)return usageError(t(activeLocale,"参数 --lang 缺少取值 (可选值: system | en | zh)","Option --lang requires a value (expected: system | en | zh)"));let err=applyLang(options,val,activeLocale);if(err!==null)return usageError(err);i+=1;continue}if(arg.startsWith("--lang=")){let val=arg.slice(7);if(val==="")return usageError(t(activeLocale,"参数 --lang 缺少取值 (可选值: system | en | zh)","Option --lang requires a value (expected: system | en | zh)"));let err=applyLang(options,val,activeLocale);if(err!==null)return usageError(err);continue}return usageError(t(activeLocale,`子命令 update 不支持参数: ${arg}`,`Unknown option for 'update': ${arg}`))}return{ok:!0,options}}function formatUpdateHelp(binName,packageName,color=!1,locale="zh",docsUrl){let safeBin=sanitizeText(binName),safePkg=sanitizeText(packageName),{badge:makeBadge,bold,dim,section,token}=createHelpStyles(color),badge=makeBadge(`${HELP_BAR_BLOCK} ${safeBin.toUpperCase()} UPDATE `),pmList=SUPPORTED_PACKAGE_MANAGERS.join(" | "),zh=locale!=="en",options=zh?[["--check",void 0,"仅检查最新版本与当前安装方式, 不执行更新"],["--pm","<管理器>",`指定包管理器 (${pmList})`],["--registry","<url>","临时指定本次查询与更新所用的 npm registry"],["--force",void 0,"即使已是最新版本仍强制重新安装"],["--verbose",void 0,"实时显示包管理器原始输出 (默认静默接管)"],["--json",void 0,"以 JSON 格式输出更新检查或升级结果"],["--lang","<语言>","临时指定本次显示语言 (system | en | zh)"]]:[["--check",void 0,"Check latest version and install origin without upgrading"],["--pm","<manager>",`Package manager (${pmList})`],["--registry","<url>","Use a custom npm registry URL for this run"],["--force",void 0,"Reinstall latest version even if already up to date"],["--verbose",void 0,"Stream raw package manager output (default: quiet)"],["--json",void 0,"Emit update status or result as JSON"],["--lang","<lang>","Display language for this run (system | en | zh)"]],metaOptions=[["-h, --help",void 0,zh?"显示本帮助":"Show this help message"]],notes=zh?[["识别依据","按磁盘真实落位路径判定, 不受 bun/node 切换影响"],["安全边界","npx/dlx/本地依赖不覆盖; 源码软链卸载转全局安装"],["环境隔离","更新子进程运行于空临时目录, 隔离 cwd 配置干扰"],["镜像源","读 ~/.bunfig.toml (bun) 或 ~/.npmrc, 缺省官方源"]]:[["Detection","Resolved from package path on disk, runtime-independent"],["Safety","Skips npx/dlx/local; unlinks source links on switch"],["Isolation","Runs in clean temp dir with lifecycle env vars stripped"],["Registry","Reads ~/.bunfig.toml (bun) or ~/.npmrc; default npmjs.org"]],descCol=computeHelpDescColumn([...options.map(([f,a])=>a===void 0?f:`${f} ${a}`),...metaOptions.map(([f,a])=>a===void 0?f:`${f} ${a}`),...notes.map(([k])=>k)]),optLine=([f,a,d])=>{let plain=a===void 0?f:`${f} ${a}`,styled=a===void 0?token(f):`${token(f)} ${dim(a)}`;return alignHelpRow(styled,plain,dim(d),descCol)},exitAndDocs=formatExitAndDocsSection({locale:zh?"zh":"en",color,descCol,exitZeroDesc:zh?"成功 (含 --check 与 -h/--help)":"Success (including --check and --help)",exitOneDesc:zh?"失败 (参数非法、网络或更新出错)":"Error (invalid args, network, or upgrade error)",docsUrl:docsUrl!==void 0?sanitizeText(docsUrl):void 0}),badgePlain=`${HELP_BAR_BLOCK} ${safeBin.toUpperCase()} UPDATE `,titleLabel=zh?"自更新工具":"Self-Update",headerSingle=` ${badgePlain} ${titleLabel} (${safePkg})`;return["",...displayWidth(headerSingle)<=80?[` ${badge} ${bold(titleLabel)} ${dim(`(${safePkg})`)}`]:[` ${badge} ${bold(titleLabel)}`,` ${dim(`(${safePkg})`)}`],` ${dim(zh?"自动识别安装源 (脚本 / Homebrew / bun / npm / pnpm / yarn / volta) 并升级。":"Auto-detects origin (script / Homebrew / bun / npm / pnpm / yarn / volta).")}`,` ${dim(HELP_RULE)}`,"",` ${section(zh?"用法":"Usage")}`,` ${bold(`${safeBin} update`)} ${dim(zh?"[选项]":"[options]")}`,"",` ${section(zh?"选项":"Options")}`,...options.map(optLine),"",...metaOptions.map(optLine),"",` ${section(zh?"说明":"Notes")}`,...notes.map(([k,d])=>alignHelpRow(bold(k),k,dim(d),descCol)),"",...exitAndDocs].join(`
|
|
19
|
+
`)}import{existsSync as existsSync7}from"node:fs";import{accessSync,constants,mkdtempSync as mkdtempSync2,rmSync as rmSync3,statSync}from"node:fs";import{tmpdir as tmpdir2}from"node:os";import{join as join4,posix as posix5,win32 as win326}from"node:path";import{win32 as win325}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"]/,CMD_PERCENT_ESCAPE_HAZARD_RE=/[&|<>^()]/;function wrapDoubleQuotes(segment){return`"${segment.replace(/(\\+)$/,"$1$1")}"`}function escapeBatchPath(batchPath){if(batchPath===""||CMD_FORBIDDEN_RE.test(batchPath))return null;if(batchPath.includes("%")&&CMD_PERCENT_ESCAPE_HAZARD_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.includes("%")&&CMD_PERCENT_ESCAPE_HAZARD_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 allTokens=[batchPath,...pmArgs];if(allTokens.some((tok)=>tok.includes("%"))&&allTokens.some((tok)=>CMD_PERCENT_ESCAPE_HAZARD_RE.test(tok)))return null;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=win325.join(dir,"node.exe");if(isFile(sibling))return sibling;return findNativeNode()}function resolveWindowsBatchDirectJs(pm,batchPath,args,isFile,findNativeNode){let dir=win325.dirname(batchPath),candidates=[];if(pm==="npm")candidates=[win325.join(dir,"node_modules","npm","bin","npm-cli.js")];else if(pm==="pnpm")candidates=[win325.join(dir,"node_modules","pnpm","bin","pnpm.cjs"),win325.join(dir,"node_modules","corepack","dist","pnpm.js")];else if(pm==="yarn")candidates=[win325.join(dir,"yarn.js"),win325.join(dir,"node_modules","yarn","bin","yarn.js"),win325.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}var WIN32_DRIVE_ABS_RE=/^[A-Za-z]:[/\\]/,WIN32_CMD_EXE_RE=/^[A-Za-z]:[/\\].*[/\\]cmd\.exe$/i;function hasWinDotDotSegment(p){return p.split(/[/\\]/).includes("..")}function pickComSpec(env){for(let rawRoot of[env.SystemRoot,env.SYSTEMROOT,env.WINDIR,env.windir])if(typeof rawRoot==="string"){let trimmed=rawRoot.trim();if(WIN32_DRIVE_ABS_RE.test(trimmed)&&!CMD_FORBIDDEN_RE.test(trimmed)&&!hasWinDotDotSegment(trimmed))return win325.join(trimmed,"System32","cmd.exe")}for(let candidate of[env.ComSpec,env.COMSPEC])if(typeof candidate==="string"){let trimmed=candidate.trim();if(WIN32_CMD_EXE_RE.test(trimmed)&&!CMD_FORBIDDEN_RE.test(trimmed)&&!hasWinDotDotSegment(trimmed))return trimmed}return"C:\\Windows\\System32\\cmd.exe"}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:pickComSpec(env),args:["/d","/s","/c",cmdLine],windowsVerbatimArguments:!0}}var WIN32_NATIVE_EXTS=[".exe",".com"],WIN32_BATCH_EXTS=[".cmd",".bat"];function defaultIsExecutable(path){try{if(!statSync(path).isFile())return!1;if(process.platform!=="win32")accessSync(path,constants.X_OK);return!0}catch{return!1}}function firstNonEmptyEnv(...values){for(let val of values)if(typeof val==="string"&&val.trim()!=="")return val;return""}function isLocalNodeModulesBinDir(dir){let folded=dir.replaceAll("\\","/").replace(/\/+$/,"").toLowerCase();return folded.endsWith("/node_modules/.bin")||folded==="node_modules/.bin"}function parseAbsolutePathDirs(env,platform){let raw=platform==="win32"?firstNonEmptyEnv(env.PATH,env.Path):firstNonEmptyEnv(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=defaultIsExecutable){let dirs=parseAbsolutePathDirs(env,platform);if(platform!=="win32"){for(let dir of dirs){let candidate=posix5.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=win326.join(dir,`${name}${ext}`);if(isFile(candidate))return{path:candidate,isBatch:!1}}for(let ext of WIN32_BATCH_EXTS){let candidate=win326.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=defaultIsExecutable){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 isYarnBerryVersion(versionText){if(versionText===null)return!1;let m=/^v?(\d+)\./.exec(versionText.trim());if(m===null)return!1;return Number(m[1])>=2}var STRIPPED_LIFECYCLE_ENV_LOWER=new Set(["npm_execpath","npm_lifecycle_event","npm_lifecycle_script","npm_package_json","init_cwd","bun_options","bun_inspect_preload","node_options","node_tls_reject_unauthorized"]);function buildIsolatedEnv(baseEnv,overlay){let next={...baseEnv};for(let key of Object.keys(next))if(STRIPPED_LIFECYCLE_ENV_LOWER.has(key.toLowerCase()))delete next[key];if(overlay!==void 0){let overlayLower=new Set(Object.keys(overlay).map((k)=>k.toLowerCase()));for(let key of Object.keys(next))if(overlayLower.has(key.toLowerCase()))delete next[key];Object.assign(next,overlay)}return next}function withIsolatedCwd(fn){let dir=mkdtempSync2(join4(tmpdir2(),"cli-update-"));try{return fn(dir)}finally{try{rmSync3(dir,{recursive:!0,force:!0,maxRetries:3,retryDelay:50})}catch{}}}import{spawnSync as spawnSync2}from"node:child_process";import{existsSync as existsSync4,readFileSync as readFileSync4}from"node:fs";import{posix as posix6,win32 as win327}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}var PROBE_ENV_OVERLAY={COREPACK_ENABLE_DOWNLOAD_PROMPT:"0"};function defaultReadText(path){try{return readFileSync4(path,"utf8")}catch{return null}}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=spawnSync2,isFile=defaultIsExecutable){let invocation=resolvePmInvocation("yarn",["--version"],platform,env,isFile);if(invocation===null)return null;try{return withIsolatedCwd((cwd)=>runIsolatedProbe(cwd,invocation,env,spawnFn))}catch{return null}}var joinForPlatform=(p,...parts)=>p==="win32"?win327.join(...parts):posix6.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){if(home==="")return null;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=spawnSync2,options){let roots={},home=resolveSafeHomeDir({homedir:options?.homeDir,env,platform}),readText=options?.readText??defaultReadText,pathExists=options?.pathExists??existsSync4,isFile=options?.isFile??defaultIsExecutable,bunDir=resolveBunGlobalDirFromConfig(home,platform,readText,pathExists);if(bunDir!==null)roots.bun=bunDir;try{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}})}catch{}return roots}import{readFileSync as readFileSync5}from"node:fs";function normalizeRegistryUrl2(url){return normalizeRegistryUrl(url)}function parseRegistryFromBunfig2(content,packageName){return parseRegistryFromBunfig(content,packageName)}function parseRegistryFromNpmrc2(content,packageName){return parseRegistryFromNpmrc(content,packageName)}var DEFAULT_REGISTRY="https://registry.npmjs.org",DEFAULT_FETCH_TIMEOUT_MS=1e4;function defaultReadText2(path){try{return readFileSync5(path,"utf8")}catch{return null}}function deriveToolEnvPrefix(packageName,toolName){return(toolName!==void 0&&toolName.trim()!==""?toolName.trim():packageName.replace(/^@[^/]+\//,"").replace(/-cli$/,"")).toUpperCase().replace(/[^A-Z0-9]+/g,"_")}function resolveRegistry(input){if(input.flagRegistry!==void 0&&isValidRegistryUrl(input.flagRegistry))return normalizeRegistryUrl2(input.flagRegistry);let env=input.env??process.env,toolPrefix=deriveToolEnvPrefix(input.packageName,input.toolName),envCandidates=[toolPrefix!==""?env[`${toolPrefix}_REGISTRY`]:void 0,env.CLIS_REGISTRY,env.NPM_CONFIG_REGISTRY,env.npm_config_registry];for(let cand of envCandidates){let trimmed=cand?.trim();if(trimmed!==void 0&&trimmed!==""&&isValidRegistryUrl(trimmed))return normalizeRegistryUrl2(trimmed)}let home=resolveSafeHomeDir({homedir:input.homeDir,env});if(home==="")return DEFAULT_REGISTRY;let readText=input.readText??defaultReadText2;if(input.pm==="bun"){let bunfig=readText(joinForPath(home,".bunfig.toml"));if(bunfig!==null){let found=parseRegistryFromBunfig2(bunfig,input.packageName);if(found!==null)return normalizeRegistryUrl2(found)}}let npmrc=readText(joinForPath(home,".npmrc"));if(npmrc!==null){let found=parseRegistryFromNpmrc2(npmrc,input.packageName);if(found!==null)return normalizeRegistryUrl2(found)}if(input.pm===void 0){let bunfig=readText(joinForPath(home,".bunfig.toml"));if(bunfig!==null){let found=parseRegistryFromBunfig2(bunfig,input.packageName);if(found!==null)return normalizeRegistryUrl2(found)}}return DEFAULT_REGISTRY}function resolveRegistryAuthToken(input){if(!isValidRegistryUrl(input.registry))return;let env=input.env??process.env,home=resolveSafeHomeDir({homedir:input.homeDir,env});if(home==="")return;let readText=input.readText??defaultReadText2,base=normalizeRegistryUrl2(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}var MAX_SAFE_REDIRECTS=5,REDIRECT_STATUSES=new Set([301,302,303,307,308]);function isAllowedTarballUrl(rawUrl,registryBase){try{let parsed=new URL(rawUrl);if(parsed.protocol!=="https:"&&parsed.protocol!=="http:")return!1;if(registryBase!==void 0){if(new URL(registryBase).protocol==="https:"&&parsed.protocol!=="https:")return!1}return!0}catch{return!1}}async function fetchWithoutHttpsDowngrade(initialUrl,init){let fetchFn=init.fetchFn??fetch,parsedInit=new URL(initialUrl),initialOrigin=parsedInit.origin,requireHttps=parsedInit.protocol==="https:",currentUrl=initialUrl;for(let hop=0;hop<=MAX_SAFE_REDIRECTS;hop+=1){let headers={...init.headers};if(new URL(currentUrl).origin!==initialOrigin){for(let key of Object.keys(headers))if(key.toLowerCase()==="authorization")delete headers[key]}let response=await fetchFn(currentUrl,{headers,redirect:"manual",signal:init.signal});if(requireHttps&&typeof response.url==="string"&&response.url!==""){let finalProto="";try{finalProto=new URL(response.url).protocol}catch{finalProto=""}if(finalProto!==""&&finalProto!=="https:")throw await response.body?.cancel().catch(()=>{}),Error(`Refused HTTPS downgrade redirect (${initialUrl} -> ${response.url})`)}if(!REDIRECT_STATUSES.has(response.status))return response;let location=response.headers.get("location");if(await response.body?.cancel().catch(()=>{}),location===null||location.trim()==="")return response;if(hop===MAX_SAFE_REDIRECTS)throw Error(`Too many redirects (${MAX_SAFE_REDIRECTS})`);let nextUrl;try{nextUrl=new URL(location,currentUrl)}catch{throw Error(`Invalid redirect location: ${location}`)}if(nextUrl.protocol!=="https:"&&nextUrl.protocol!=="http:")throw Error(`Refused redirect to unsupported protocol: ${nextUrl.protocol}`);if(requireHttps&&nextUrl.protocol!=="https:")throw Error(`Refused HTTPS downgrade redirect (${currentUrl} -> ${nextUrl.href})`);if(nextUrl.protocol==="https:")requireHttps=!0;currentUrl=nextUrl.href}throw Error(`Too many redirects (${MAX_SAFE_REDIRECTS})`)}function cleanMessage(raw,secret){let redacted=secret!==void 0&&secret!==""?raw.replaceAll(secret,"[REDACTED]"):raw;return sanitizeCliText(redacted)}async function fetchLatestVersion(input){let locale=input.locale??"zh",tag=input.tag??"latest";if(!isValidPackageName(input.packageName))return{ok:!1,code:"invalid-response",message:t(locale,`非法包名: ${cleanMessage(input.packageName)}`,`Invalid package name: ${cleanMessage(input.packageName)}`)};if(!isValidTargetSpec(tag)||!isValidRegistryUrl(input.registry))return{ok:!1,code:"invalid-response",message:t(locale,"非法的 registry 地址或版本标签","Invalid registry URL or dist-tag")};let base=normalizeRegistryUrl2(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 fetchWithoutHttpsDowngrade(url,{headers,signal:AbortSignal.timeout(timeoutMs),fetchFn})}catch(error){let detail=error instanceof Error?cleanMessage(error.message,authToken):"";return{ok:!1,code:"network",message:detail===""?t(locale,`无法连接包注册表 (${base})`,`Cannot reach registry (${base})`):t(locale,`无法连接包注册表 (${base}): ${detail}`,`Cannot reach registry (${base}): ${detail}`)}}if(response.status===401||response.status===403)return{ok:!1,code:"auth",status:response.status,message:t(locale,`访问包注册表 ${base} 鉴权失败 (HTTP ${response.status}), 请检查 ~/.npmrc / ~/.bunfig.toml 认证凭据或登录状态`,`Authentication failed for ${base} (HTTP ${response.status}); check credentials in ~/.npmrc or ~/.bunfig.toml`)};if(response.status===404)return{ok:!1,code:"not-found",status:404,message:t(locale,`${input.packageName} 尚未在 ${base} 发布 (HTTP 404)`,`${input.packageName} is not published on ${base} (HTTP 404)`)};if(!response.ok)return{ok:!1,code:"http",status:response.status,message:t(locale,`包注册表返回异常状态 HTTP ${response.status} (${base})`,`Registry returned HTTP ${response.status} (${base})`)};let body;try{body=await response.json()}catch{return{ok:!1,code:"invalid-response",message:t(locale,`包注册表返回的内容不是合法 JSON (${base})`,`Registry returned invalid 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:t(locale,`包注册表响应缺少合法 version 字段 (${base})`,`Registry response is missing a valid version field (${base})`)};return{ok:!0,version,registry:base}}function formatUpgradeDisplayCommand(pm,packageName,targetSpec="latest",explicitRegistry){let spec=`${packageName}@${targetSpec}`,reg=explicitRegistry!==void 0?normalizeRegistryUrl2(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 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 locale=input.locale??"zh",targetSpec=input.targetSpec??"latest";if(!isValidPackageName(input.packageName))return{ok:!1,reason:t(locale,`非法包名: ${input.packageName}`,`Invalid package name: ${input.packageName}`)};if(!isValidTargetSpec(targetSpec))return{ok:!1,reason:t(locale,`非法目标版本标签: ${targetSpec}`,`Invalid target version tag: ${targetSpec}`)};if(input.explicitRegistry!==void 0&&!isValidRegistryUrl(input.explicitRegistry))return{ok:!1,reason:t(locale,`非法 registry 地址: ${input.explicitRegistry}`,`Invalid registry URL: ${input.explicitRegistry}`)};let platform=input.platform??process.platform,env=input.env??process.env,isFile=input.isFile??defaultIsExecutable,reg=input.explicitRegistry!==void 0?normalizeRegistryUrl2(input.explicitRegistry):void 0,displayCommand=formatUpgradeDisplayCommand(input.pm,input.packageName,targetSpec,reg);if(input.pm==="yarn"&&isYarnBerryVersion(input.yarnVersion??null))return{ok:!1,reason:t(locale,`当前环境的 Yarn (${input.yarnVersion?.trim()}) 为 v2+ (Berry), 官方已移除 yarn global add 命令, 请改用 --pm bun / --pm npm / --pm pnpm 执行全局更新`,`Yarn (${input.yarnVersion?.trim()}) is v2+ (Berry), which removed 'yarn global add'; rerun with --pm bun, --pm npm, or --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:t(locale,`当前 PATH 中未找到 ${input.pm} 可执行文件, 无法自动执行更新`,`${input.pm} executable was not found in PATH`),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}:{}}}}import{readFileSync as readFileSync7}from"node:fs";import{spawn}from"node:child_process";import{mkdtempSync as mkdtempSync3,rmSync as rmSync4}from"node:fs";import{tmpdir as tmpdir3}from"node:os";import{join as join5}from"node:path";var MAX_CAPTURE_BYTES=65536;class TailByteBuffer{chunks=[];totalBytes=0;truncatedFlag=!1;maxBytes;constructor(maxBytes=MAX_CAPTURE_BYTES){this.maxBytes=Math.max(64,maxBytes)}push(chunk){let buf=typeof chunk==="string"?Buffer.from(chunk,"utf8"):chunk;if(buf.length===0)return;if(buf.length>=this.maxBytes){this.chunks.length=0,this.chunks.push(buf.subarray(buf.length-this.maxBytes)),this.totalBytes=this.maxBytes,this.truncatedFlag=!0;return}this.chunks.push(buf),this.totalBytes+=buf.length;while(this.totalBytes>this.maxBytes&&this.chunks.length>0){this.truncatedFlag=!0;let overflow=this.totalBytes-this.maxBytes,head=this.chunks[0];if(head.length<=overflow)this.chunks.shift(),this.totalBytes-=head.length;else this.chunks[0]=head.subarray(overflow),this.totalBytes-=overflow}}toResult(){if(this.chunks.length===0)return{text:"",truncated:this.truncatedFlag};let merged=Buffer.concat(this.chunks,this.totalBytes);if(this.truncatedFlag){let offset=0;while(offset<merged.length&&offset<4&&merged[offset]>=128&&merged[offset]<192)offset+=1;if(offset>0)merged=merged.subarray(offset)}return{text:merged.toString("utf8"),truncated:this.truncatedFlag}}}async function withIsolatedCwdAsync(fn){let cwd=mkdtempSync3(join5(tmpdir3(),"cli-updater-"));try{return await fn(cwd)}finally{try{rmSync4(cwd,{recursive:!0,force:!0,maxRetries:5,retryDelay:100})}catch{}}}async function executeUpgradePlanAsync(plan,options={}){let env=options.env??process.env,verbose=options.verbose===!0,spawnAsync=options.spawnAsync??spawn,now=options.now??(()=>Date.now()),startedAt=now();try{return await withIsolatedCwdAsync(async(cwd)=>{let tail=new TailByteBuffer(options.maxCaptureBytes);return await new Promise((resolve)=>{let child;try{child=spawnAsync(plan.command,plan.args,{cwd,env:buildIsolatedEnv(env,plan.envOverlay),stdio:verbose?"inherit":["ignore","pipe","pipe"],...plan.windowsVerbatimArguments===!0?{windowsVerbatimArguments:!0}:{}})}catch(err){resolve({status:null,error:err instanceof Error?err:Error(String(err)),durationMs:Math.max(0,now()-startedAt)});return}if(!verbose)child.stdout?.on("data",(chunk)=>tail.push(chunk)),child.stderr?.on("data",(chunk)=>tail.push(chunk));let settled=!1,sawSigInt=!1,sawSigTerm=!1,forwardSigInt=()=>{if(sawSigInt=!0,process.platform==="win32")return;try{child.kill("SIGINT")}catch{}},forwardSigTerm=()=>{sawSigTerm=!0;try{child.kill("SIGTERM")}catch{}},cleanup=()=>{process.off("SIGINT",forwardSigInt),process.off("SIGTERM",forwardSigTerm)},finish=(partial)=>{if(settled)return;if(settled=!0,cleanup(),sawSigInt||partial.signal==="SIGINT"){let shield=()=>{};process.on("SIGINT",shield),setTimeout(()=>process.off("SIGINT",shield),500).unref?.()}let captured=verbose?{text:"",truncated:!1}:tail.toResult(),effectiveSignal=partial.signal??null,effectiveStatus=partial.status;if(effectiveSignal===null&&(sawSigInt||sawSigTerm))effectiveSignal=sawSigInt?"SIGINT":"SIGTERM",effectiveStatus=null;resolve({...partial,status:effectiveStatus,signal:effectiveSignal,capturedOutput:captured.text,truncated:captured.truncated,durationMs:Math.max(0,now()-startedAt)})};process.on("SIGINT",forwardSigInt),process.on("SIGTERM",forwardSigTerm),child.once("error",(error)=>{finish({status:null,error})}),child.once("close",(status,signal)=>{finish({status,signal})})})})}catch(err){return{status:null,error:err instanceof Error?err:Error(String(err)),capturedOutput:"",truncated:!1,durationMs:Math.max(0,now()-startedAt)}}}import{existsSync as existsSync5,readFileSync as readFileSync6}from"node:fs";import{posix as posix7,win32 as win328}from"node:path";function sanitize(raw){return sanitizeText(raw)}function formatVersionLabel(spec){return/^\d/.test(spec)?`v${spec}`:spec}function defaultReadText3(path){try{return readFileSync6(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`}}var ORIGIN_REASON_EN={"命中 Volta 全局工具安装目录":"Volta global directory","命中 Bun 全局安装目录 (~/.bun)":"Bun global directory (~/.bun)","命中 pnpm 全局安装目录":"pnpm global directory","命中 Yarn 全局安装目录":"Yarn global directory","命中 npm 全局安装目录":"npm global directory","命中标准 <prefix>/lib/node_modules 全局目录":"standard <prefix>/lib/node_modules","位于环境变量 VOLTA_HOME 目录内":"VOLTA_HOME directory","位于环境变量 BUN_INSTALL 目录内":"BUN_INSTALL directory","位于环境变量 BUN_INSTALL_GLOBAL_DIR 目录内":"BUN_INSTALL_GLOBAL_DIR directory","位于环境变量 PNPM_HOME 目录内":"PNPM_HOME directory","位于环境变量 NPM_CONFIG_PREFIX 目录内":"NPM_CONFIG_PREFIX directory","位于 npx 临时缓存目录 (_npx)":"npx cache (_npx)","位于 bunx 临时执行目录":"bunx cache","位于 pnpm dlx 临时缓存目录":"pnpm dlx cache","位于 yarn dlx 临时执行目录":"yarn dlx cache","位于 Deno npm 缓存目录 (/deno/npm/)":"Deno npm cache (/deno/npm/)","命中 Homebrew Cellar 安装目录":"Homebrew Cellar directory","包根目录位于本地源码工作树 (存在 src/cli.ts)":"package root is inside a local source tree (src/cli.ts found)",未匹配已知全局包管理器路径或本地源码工作树:"did not match any known global package manager or local source tree"};function translateOriginReason(reason){let mapped=ORIGIN_REASON_EN[reason];if(mapped!==void 0)return mapped;let probed=/^匹配\s+(\S+)\s+实查全局目录\s+\((.+)\)$/.exec(reason);if(probed!==null)return`probed ${probed[1]} global root (${probed[2]})`;let localPkg=/^位于项目本地 node_modules \((.+)\)$/.exec(reason);if(localPkg!==null)return`inside local project node_modules (${localPkg[1]})`;return reason}function describeOrigin(origin,locale="zh",isSourceSymlink=!1){if(locale==="en")switch(origin.kind){case"global":return`${origin.pm} global install (${translateOriginReason(origin.reason)})`;case"standalone":return`standalone script install (${origin.packageRoot})`;case"homebrew":return`Homebrew (${origin.formulaRef})`;case"ephemeral":return`${origin.runner} temporary run (${translateOriginReason(origin.reason)})`;case"source":return isSourceSymlink?`local source symlink (${origin.packageRoot})`:`local source checkout (${origin.packageRoot})`;case"local-project":return`local project dependency (${origin.projectDir})`;case"unknown":return`unrecognized location (${origin.packageRoot})`}switch(origin.kind){case"global":return`${origin.pm} 全局安装 (${origin.reason})`;case"standalone":return`独立脚本安装 (${origin.packageRoot})`;case"homebrew":return`Homebrew 安装 (${origin.formulaRef})`;case"ephemeral":return`${origin.runner} 临时运行 (${origin.reason})`;case"source":return isSourceSymlink?`本地源码软链态 (${origin.packageRoot})`:`本地源码开发态 (${origin.packageRoot})`;case"local-project":return`项目本地依赖 (${origin.projectDir})`;case"unknown":return`未知安装位置 (${origin.packageRoot})`}}function warnCrossPmOverride(origin,targetPm,io,ui=createUpdateUi({stdout:!1,stderr:!1}),locale="zh"){if(origin.kind==="global"&&origin.pm!==targetPm){io.out(ui.warn(t(locale,`注意: 当前命令实际由 ${origin.pm} 全局安装, 改用 ${targetPm} 安装会在磁盘产生双份副本, PATH 靠前的旧副本可能遮蔽新版本!`,`Note: Currently installed globally via ${origin.pm}; installing via ${targetPm} creates a second copy that may be shadowed in PATH.`)));return}if(origin.kind==="standalone"){io.out(ui.warn(t(locale,`注意: 当前运行在独立脚本安装目录 (${sanitize(origin.packageRoot)}), 通过 ${targetPm} 全局安装会产生独立全局副本, 请核对 PATH 优先级避免版本阴影!`,`Note: Currently installed via standalone script (${sanitize(origin.packageRoot)}); installing globally via ${targetPm} creates a separate global copy.`)));return}if(origin.kind==="homebrew"){io.out(ui.warn(t(locale,`注意: 当前命令实际由 Homebrew 安装 (${sanitize(origin.formulaRef)}), 改用 ${targetPm} 全局安装会产生双份副本, PATH 靠前的副本可能遮蔽新版本!`,`Note: Currently installed via Homebrew (${sanitize(origin.formulaRef)}); installing globally via ${targetPm} creates a second copy that may be shadowed in PATH.`)));return}if(origin.kind==="source"){io.out(ui.warn(t(locale,`注意: 当前运行在本地源码工作树 (${sanitize(origin.packageRoot)}), 通过 ${targetPm} 全局安装会另装一份全局副本, 请注意与本地源码运行方式区分避免版本阴影!`,`Note: Running from local source (${sanitize(origin.packageRoot)}); installing globally via ${targetPm} creates a separate global copy.`)));return}if(origin.kind==="local-project")io.out(ui.warn(t(locale,`注意: 当前运行在项目本地依赖 (${sanitize(origin.projectDir)}), 通过 ${targetPm} 全局安装不会更新项目本地依赖, 且可能被本地副本遮蔽!`,`Note: Running from local project dependency (${sanitize(origin.projectDir)}); a global install via ${targetPm} will not update the project dependency.`)))}function resolveOrigin(meta,deps){let env=deps.env??process.env,pathExists=deps.pathExists??existsSync5,platform=deps.platform??process.platform,rawPaths=[...new Set([meta.rawPackageRoot,deps.argvEntry??process.argv[1],env.CLIS_ENTRY_ARGV1].map((p)=>p?.trim()??"").filter((p)=>p!==""))],baseInput={packageRoot:meta.packageRoot,rawPaths,env,pathExists,readText:deps.readText,realpath:deps.realpath},firstPass=detectInstallOriginFromPath(baseInput);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({...baseInput,globalRoots})}return firstPass}function resolveExecutableSkippingLocalBin(binName,platform,env,isFile){let dirs=parseAbsolutePathDirs(env,platform),pathImpl=platform==="win32"?win328:posix7,exts=platform==="win32"?[".exe",".com",".cmd",".bat"]:[""];for(let dir of dirs){if(isLocalNodeModulesBinDir(dir))continue;for(let ext of exts){let candidate=pathImpl.join(dir,`${binName}${ext}`);if(isFile(candidate))return{path:candidate}}}return null}function verifyPostUpgrade(input){let locale=input.locale??"zh",ui=input.ui??createUpdateUi({stdout:!1,stderr:!1},locale),readText=input.readText??defaultReadText3,realpathFn=input.realpath??safeRealpath,unchangedAtOldRoot=!1;if(input.devLinksRemoved!==!0&&input.origin.kind==="global"){let pkgText=readText(joinForPath(input.meta.packageRoot,"package.json"));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(ui.warn(t(locale,`提示: 原安装目录 (${sanitize(input.meta.packageRoot)}) 的版本仍为 ${formatVersionLabel(sanitize(afterVersion))}, 新版本可能安装到了其他位置, 请运行 ${sanitize(input.binName)} --version 核查。`,`Note: Version in ${sanitize(input.meta.packageRoot)} is still ${formatVersionLabel(sanitize(afterVersion))}; verify active binary with '${sanitize(input.binName)} --version'.`)))}catch{}}let normalizeKey=(p)=>{let clean=p.replaceAll("\\","/");return input.platform==="win32"?clean.toLowerCase():clean},postUnlinked=input.postUnlinkedPaths??[],postUnlinkedSet=postUnlinked.length>0?new Set(postUnlinked.map(normalizeKey)):null,baseIsFile=input.isFile??defaultIsExecutable,effectiveIsFile=postUnlinkedSet!==null?(p)=>!postUnlinkedSet.has(normalizeKey(p))&&baseIsFile(p):baseIsFile,resolvedBin=resolveExecutableSkippingLocalBin(input.binName,input.platform,input.env,effectiveIsFile);if(resolvedBin===null){if(input.devLinksRemoved===!0)input.io.out(ui.warn(t(locale,`提示: 源码软链已卸载, 但当前 PATH 中未找到 ${sanitize(input.binName)}, 请确认 ${input.targetPm} 全局 bin 目录已加入 PATH。`,`Note: Source symlink(s) unlinked, but '${sanitize(input.binName)}' was not found in PATH; ensure ${input.targetPm}'s global bin directory is in PATH.`)));return}let resolvedReal=realpathFn(resolvedBin.path),binOrigin=detectInstallOriginFromPath({packageRoot:resolvedReal,rawPaths:[resolvedBin.path],env:input.env,pathExists:input.pathExists??existsSync5}),isSamePmInPlace=input.origin.kind==="global"&&input.origin.pm===input.targetPm,pointsToStaleOldRoot=isWithinDir(resolvedReal,input.meta.packageRoot)&&(!isSamePmInPlace||unchangedAtOldRoot),mismatchPm=binOrigin.kind==="global"&&binOrigin.pm!==input.targetPm,shadowedByOther=binOrigin.kind==="source"||binOrigin.kind==="standalone"||binOrigin.kind==="homebrew";if(pointsToStaleOldRoot||mismatchPm||shadowedByOther||!isSamePmInPlace&&unchangedAtOldRoot){input.io.out(ui.warn(t(locale,`提示: 当前 PATH 中的 ${sanitize(input.binName)} 仍指向旧路径 (${sanitize(resolvedBin.path)}), 可能遮蔽 ${input.targetPm} 新安装的版本, 请检查 PATH 优先级。`,`Note: '${sanitize(input.binName)}' in PATH still resolves to ${sanitize(resolvedBin.path)}, which may shadow the ${input.targetPm} install.`)));return}if(postUnlinked.length>0&&input.platform!=="win32")input.io.out(ui.hint(t(locale,"若当前终端仍缓存旧路径, 请执行 hash -r (bash/zsh) 或 rehash (zsh) 刷新命令缓存。","If your shell still caches the old path, run 'hash -r' or 'rehash'.")))}var SAFE_FORMULA_REF_RE=/^(?:[a-z0-9][a-z0-9._-]{0,63}\/[a-z0-9][a-z0-9._-]{0,63}\/)?[a-z0-9][a-z0-9@._+-]{0,127}$/i;function defaultReadText4(path){try{return readFileSync7(path,"utf8")}catch{return null}}function formatHomebrewUpgradeCommand(formulaRef,reinstall=!1){return reinstall?`brew reinstall ${formulaRef}`:`brew upgrade ${formulaRef}`}function buildHomebrewUpgradePlan(input){let locale=input.locale??"zh",{formulaRef,prefix}=input.origin;if(formulaRef===""||formulaRef.includes("..")||!SAFE_FORMULA_REF_RE.test(formulaRef))return{ok:!1,reason:t(locale,`非法 Homebrew Formula 名称: ${formulaRef}`,`Invalid Homebrew formula reference: ${formulaRef}`)};let platform=input.platform??process.platform,env=input.env??process.env,isFile=input.isFile??defaultIsExecutable,displayCommand=formatHomebrewUpgradeCommand(formulaRef,input.reinstall),prefixBrew=isSafeHomebrewPrefix(prefix)?joinForPath(prefix,"bin","brew"):"",brewCommand=prefixBrew!==""&&isFile(prefixBrew)?prefixBrew:null;if(brewCommand===null){let found=resolveExecutableInPath("brew",platform,env,isFile);brewCommand=found!==null?found.path:null}if(brewCommand===null)return{ok:!1,reason:t(locale,"当前环境未找到 brew 可执行文件, 无法自动执行 Homebrew 更新","brew executable was not found in PATH or Homebrew prefix"),fallbackCommand:displayCommand};return{ok:!0,plan:{command:brewCommand,args:[input.reinstall?"reinstall":"upgrade",formulaRef],displayCommand}}}function readHomebrewOptPackageVersion(origin,packageName,readText=defaultReadText4){let candidates=[joinForPath(origin.prefix,"opt",origin.formula,"libexec","package.json"),joinForPath(origin.prefix,"opt",origin.formula,"libexec","lib","node_modules",packageName,"package.json")];for(let pkgPath of candidates){let raw=readText(pkgPath);if(raw===null)continue;try{let parsed=JSON.parse(raw);if(typeof parsed.version==="string"&&parsed.version.trim()!=="")return parsed.version.trim()}catch{}}return null}function emitHomebrewFailure(input){let{result,displayCommand,verbose,io,ui,locale}=input,manualHint=t(locale,`手动更新命令: ${displayCommand}`,`Run manually: ${displayCommand}`);if(result.error!==void 0)io.err(ui.error(t(locale,`Homebrew 更新启动失败: ${sanitize(result.error.message)}`,`Failed to launch brew: ${sanitize(result.error.message)}`)));else if(result.signal!==void 0&&result.signal!==null)io.err(ui.error(t(locale,`Homebrew 更新被信号中断 (${result.signal})`,`Homebrew upgrade interrupted by signal (${result.signal})`)));else io.err(ui.error(t(locale,`Homebrew 更新失败 (brew 退出码 ${String(result.status??1)})`,`Homebrew upgrade failed (brew exited with code ${String(result.status??1)})`)));if(!verbose&&typeof result.capturedOutput==="string"){let tail=sanitizeMultilineTail(result.capturedOutput);if(tail.lines.length>0){let isClipped=result.truncated===!0||tail.clipped;io.err(ui.errorHint(isClipped?t(locale,"底层输出摘要 (仅显示末尾):","Homebrew output (tail):"):t(locale,"底层输出摘要:","Homebrew output:")));for(let line of tail.lines)io.err(ui.errorLogLine(line))}}return io.err(ui.errorHint(manualHint)),1}function warnIfHomebrewBinShadowed(input){let{binName,origin,platform,env,isFile,realpath,io,ui,locale}=input,dirs=parseAbsolutePathDirs(env,platform),activeBin=null;for(let dir of dirs){if(isLocalNodeModulesBinDir(dir))continue;let candidate=joinForPath(dir,binName);if(isFile(candidate)){activeBin=candidate;break}}if(activeBin===null)return;let brewBinDir=joinForPath(origin.prefix,"bin"),resolved=realpath(activeBin);if(isWithinDir(activeBin,brewBinDir)||isWithinDir(resolved,origin.prefix))return;io.out(ui.warn(t(locale,`提示: 当前 PATH 中的 ${sanitize(binName)} 指向 ${sanitize(activeBin)}, 可能遮蔽 Homebrew 安装目录 (${sanitize(brewBinDir)}), 请检查 PATH 优先级。`,`Note: '${sanitize(binName)}' in PATH resolves to ${sanitize(activeBin)}, which may shadow Homebrew (${sanitize(brewBinDir)}).`)))}async function performHomebrewUpgrade(ctx){let{binName,meta,origin,targetVersion,hasUpdate,opts,io,color,ui,spinner,deps,locale}=ctx,platform=deps.platform??process.platform,env=deps.env??process.env,isFile=deps.isFile??defaultIsExecutable,readText=deps.readText??defaultReadText4,realpathFn=deps.realpath??safeRealpath,reinstall=opts.force&&!hasUpdate&&targetVersion!=="latest",built=buildHomebrewUpgradePlan({origin,reinstall,platform,env,isFile,locale});if(!built.ok){if(io.err(ui.error(t(locale,`无法自动更新: ${built.reason}`,`Cannot upgrade automatically: ${built.reason}`))),built.fallbackCommand!==void 0)io.err(ui.errorHint(t(locale,`手动更新命令: ${built.fallbackCommand}`,`Run manually: ${built.fallbackCommand}`)));return 1}let targetLabel=formatVersionLabel(sanitize(targetVersion));if(opts.verbose)io.out(ui.kv(t(locale,"执行命令","Command"),built.plan.displayCommand,"dim"));else spinner.start(reinstall?t(locale,`正在通过 Homebrew 重装 ${sanitize(origin.formulaRef)}`,`Reinstalling ${sanitize(origin.formulaRef)} via Homebrew`):t(locale,`正在通过 Homebrew 升级 ${sanitize(origin.formulaRef)} 至 ${targetLabel}`,`Upgrading ${sanitize(origin.formulaRef)} to ${targetLabel} via Homebrew`));let result;try{if(deps.execPlanAsync!==void 0)result=await deps.execPlanAsync(built.plan,{env,verbose:opts.verbose,spawnAsync:deps.spawnAsync});else if(deps.execPlan!==void 0)result=await deps.execPlan(built.plan,env,deps.spawnFn);else result=await executeUpgradePlanAsync(built.plan,{env,verbose:opts.verbose,spawnAsync:deps.spawnAsync})}catch(err){result={status:null,error:err instanceof Error?err:Error(String(err))}}finally{spinner.stop()}if(result.error!==void 0||result.signal!==void 0&&result.signal!==null||result.status!==0)return emitHomebrewFailure({result,displayCommand:built.plan.displayCommand,verbose:opts.verbose,io,ui,locale});let afterVersion=readHomebrewOptPackageVersion(origin,meta.name,readText);if(targetVersion!=="latest"&&compareSemver(meta.version,targetVersion)===-1&&afterVersion!==null&&afterVersion===meta.version)return io.out(ui.warn(t(locale,`提示: Homebrew 当前生效版本仍为 ${formatVersionLabel(sanitize(afterVersion))} (Tap 配方可能尚未同步至 ${targetLabel}, 或受 HOMEBREW_NO_AUTO_UPDATE 影响)。`,`Note: Active Homebrew version is still ${formatVersionLabel(sanitize(afterVersion))} (tap formula may not be synced to ${targetLabel} yet, or HOMEBREW_NO_AUTO_UPDATE skipped refresh).`))),io.out(ui.hint(t(locale,`可稍后执行: brew update && ${built.plan.displayCommand}`,`Try later: brew update && ${built.plan.displayCommand}`))),0;let finalLabel=afterVersion!==null?formatVersionLabel(sanitize(afterVersion)):targetLabel,elapsed=formatElapsedMs(result.durationMs),pkgLabel=paintSgr(sanitize(meta.name),"1",color.stdout),verLabel=paintSgr(finalLabel,"1;36",color.stdout);return io.out(ui.success(reinstall?t(locale,`已通过 Homebrew 重装 ${pkgLabel} (${verLabel})`,`Reinstalled ${pkgLabel} (${verLabel}) via Homebrew`):t(locale,`已通过 Homebrew 更新 ${pkgLabel} 至 ${verLabel}`,`Updated ${pkgLabel} to ${verLabel} via Homebrew`),elapsed!==""?`(${elapsed})`:void 0)),warnIfHomebrewBinShadowed({binName,origin,platform,env,isFile,realpath:realpathFn,io,ui,locale}),0}import{posix as posix9,win32 as win3210}from"node:path";import{existsSync as existsSync6,lstatSync as lstatSync3,readlinkSync as readlinkSync2,rmdirSync,symlinkSync,unlinkSync}from"node:fs";import{posix as posix8,win32 as win329}from"node:path";function defaultIsSymlink(path){try{return lstatSync3(path).isSymbolicLink()}catch{return!1}}function defaultReadlink(path){try{return readlinkSync2(path)}catch{return null}}function defaultUnlink(path,platform){if(!defaultIsSymlink(path))throw Error(`Refused to unlink non-symlink path: ${path}`);if(platform!=="win32"){unlinkSync(path);return}try{unlinkSync(path)}catch(err){let code=err.code;if((code==="EPERM"||code==="EISDIR")&&defaultIsSymlink(path)){rmdirSync(path);return}throw err}}function defaultSymlink(target,path,platform,kind){if(platform==="win32"&&kind==="package-dir"){symlinkSync(resolveLinkTarget(path,target,"win32"),path,"junction");return}symlinkSync(target,path)}function resolveLinkTarget(linkPath,rawTarget,platform){let pathImpl=platform==="win32"?win329:posix8;return pathImpl.isAbsolute(rawTarget)?pathImpl.normalize(rawTarget):pathImpl.resolve(pathImpl.dirname(linkPath),rawTarget)}function resolveMultiHopRealpath(targetPath,isSymlink,readlink,platform){let curr=targetPath,seen=new Set;for(let hop=0;hop<16;hop+=1){if(seen.has(curr)||!isSymlink(curr))break;seen.add(curr);let rawTarget=readlink(curr);if(rawTarget===null)break;curr=resolveLinkTarget(curr,rawTarget,platform)}return curr}function readEnv(env,platform,...names){for(let name of names){let val=env[name];if(typeof val==="string"&&val.trim()!=="")return val.trim()}if(platform==="win32"){let targets=new Set(names.map((n)=>n.toLowerCase()));for(let[k,v]of Object.entries(env))if(targets.has(k.toLowerCase())&&typeof v==="string"&&v.trim()!=="")return v.trim()}return""}var WIN32_ABS_HOME_RE=/^(?:[A-Za-z]:[/\\]|\\\\(?![?.][/\\])[^\\/]+[/\\][^\\/]+)/;function hasEnvEntry(env,platform,key){if(env[key]!==void 0)return!0;if(platform!=="win32")return!1;let lower=key.toLowerCase();return Object.entries(env).some(([k,v])=>k.toLowerCase()===lower&&v!==void 0)}function isAbsHomeForPlatform(p,platform){return platform==="win32"?WIN32_ABS_HOME_RE.test(p):p.startsWith("/")}function resolveEnvHomeDir(env,platform,explicitHomeDir){if(explicitHomeDir!==void 0){let trimmed=explicitHomeDir.trim();return trimmed!==""&&isAbsHomeForPlatform(trimmed,platform)?trimmed:""}if(platform==="win32"){if(hasEnvEntry(env,platform,"USERPROFILE")){let userProf=readEnv(env,platform,"USERPROFILE");return userProf!==""&&WIN32_ABS_HOME_RE.test(userProf)?userProf:""}if(hasEnvEntry(env,platform,"HOMEDRIVE")||hasEnvEntry(env,platform,"HOMEPATH")){let drive=readEnv(env,platform,"HOMEDRIVE"),homePath=readEnv(env,platform,"HOMEPATH");if(drive!==""&&homePath!==""){let combined=`${drive}${homePath}`;if(WIN32_ABS_HOME_RE.test(combined))return combined}return""}}else if(hasEnvEntry(env,platform,"HOME")){let envHome=readEnv(env,platform,"HOME");return envHome!==""&&envHome.startsWith("/")?envHome:""}return env===process.env?resolveSafeHomeDir({env,platform}):""}function resolvePmGlobalBinDirs(pm,platform,env,homeDir){let dirs=[];if(pm==="bun"){let bunInstall=readEnv(env,platform,"BUN_INSTALL");if(bunInstall!=="")dirs.push(joinForPath(bunInstall,"bin"));if(homeDir!=="")dirs.push(joinForPath(homeDir,".bun","bin"));return dirs}if(pm==="npm"){let prefix=readEnv(env,platform,"NPM_CONFIG_PREFIX","npm_config_prefix");if(prefix!=="")dirs.push(platform==="win32"?prefix:joinForPath(prefix,"bin"));if(platform==="win32"){let appData=readEnv(env,platform,"APPDATA","AppData");if(appData!=="")dirs.push(joinForPath(appData,"npm"))}return dirs}if(pm==="pnpm"){let pnpmHome=readEnv(env,platform,"PNPM_HOME");if(pnpmHome!=="")dirs.push(pnpmHome);if(homeDir!==""){if(platform==="darwin")dirs.push(joinForPath(homeDir,"Library","pnpm"));else if(platform!=="win32")dirs.push(joinForPath(homeDir,".local","share","pnpm"))}if(platform==="win32"){let localApp=readEnv(env,platform,"LOCALAPPDATA","LocalAppData");if(localApp!=="")dirs.push(joinForPath(localApp,"pnpm"))}return dirs}if(pm==="volta"){let volta=readEnv(env,platform,"VOLTA_HOME");if(volta!=="")dirs.push(joinForPath(volta,"bin"));if(homeDir!=="")dirs.push(joinForPath(homeDir,".volta","bin"));return dirs}if(homeDir!=="")dirs.push(joinForPath(homeDir,".yarn","bin"));return dirs}function createSourceLinkOps(platform,deps){let isSymlink=deps?.isSymlink??defaultIsSymlink,readlink=deps?.readlink??defaultReadlink,realpath=deps?.realpath??((targetPath)=>{let resolved=safeRealpath(targetPath);if(resolved!==targetPath)return resolved;return resolveMultiHopRealpath(targetPath,isSymlink,readlink,platform)});return{isSymlink,readlink,realpath,unlink:deps?.unlink??((p)=>defaultUnlink(p,platform)),symlink:deps?.symlink??((t,p,k)=>defaultSymlink(t,p,platform,k)),pathExists:deps?.pathExists??existsSync6}}function isUnsafeRootOrEmpty(linkPath){let trimmed=linkPath.trim();return trimmed===""||trimmed==="/"||trimmed==="\\"||/^[A-Za-z]:[/\\]?$/.test(trimmed)}function isSafeSourceSymlinkToUnlink(linkPath,ops,shouldUnlink){if(isUnsafeRootOrEmpty(linkPath))return!1;if(!ops.isSymlink(linkPath))return!1;if(shouldUnlink!==void 0&&!shouldUnlink(linkPath))return!1;return!0}function partitionSourceDevLinks(links,targetPmBinDirs=[]){let preInstall=[],postInstall=[];for(let link of links){let inTargetPmBin=targetPmBinDirs.some((dir)=>isWithinDir(link.path,dir));if(link.kind==="package-dir"||link.inferredPm!==void 0||inTargetPmBin)preInstall.push(link);else postInstall.push(link)}return{preInstall,postInstall}}function unlinkSourceDevLinks(links,ops,shouldUnlink){let removed=[];for(let link of links){if(!isSafeSourceSymlinkToUnlink(link.path,ops,shouldUnlink))continue;let target=ops.readlink(link.path);if(target===null)continue;try{ops.unlink(link.path),removed.push({link,target})}catch(err){if(err.code==="ENOENT")continue;return rollbackRemovedDevLinks(removed,ops),{ok:!1,failedPath:link.path,error:err instanceof Error?err:Error(String(err))}}}return{ok:!0,removed}}function rollbackRemovedDevLinks(removed,ops){let failures=[];for(let i=removed.length-1;i>=0;i-=1){let entry=removed[i];if(entry===void 0)continue;try{if(ops.isSymlink(entry.link.path)||ops.pathExists(entry.link.path)){failures.push({path:entry.link.path,reason:"target path already occupied"});continue}ops.symlink(entry.target,entry.link.path,entry.link.kind)}catch(err){failures.push({path:entry.link.path,reason:err instanceof Error?err.message:String(err)})}}return failures}function cleanupPostInstallDevLinks(links,ops,shouldUnlink){let unlinked=[],failed=[];for(let link of links){if(!isSafeSourceSymlinkToUnlink(link.path,ops,shouldUnlink))continue;try{ops.unlink(link.path),unlinked.push(link.path)}catch(err){if(err.code==="ENOENT")continue;failed.push({path:link.path,reason:err instanceof Error?err.message:String(err)})}}return{unlinked,failed}}var DEFAULT_SOURCE_PM_ORDER=["bun","pnpm","npm","yarn","volta"],WIN32_LINK_SUFFIXES=["",".exe",".com",".cmd",".bat",".ps1"];function inferPmForLinkPath(linkPath,intermediateTarget,platform,env,homeDir,globalRoots){let candidates=intermediateTarget!==null&&intermediateTarget!==linkPath?[linkPath,intermediateTarget]:[linkPath];for(let candidate of candidates){let detected=detectInstallOriginFromPath({packageRoot:candidate,rawPaths:[candidate],env,pathExists:()=>!1,globalRoots});if(detected.kind==="global")return detected.pm}for(let pm of DEFAULT_SOURCE_PM_ORDER)for(let binDir of resolvePmGlobalBinDirs(pm,platform,env,homeDir))if(isWithinDir(linkPath,binDir))return pm;return}function extractNodeModulesPackageDir(absTarget,packageName){let folded=normalizeSlashes(absTarget),marker=`/node_modules/${packageName}`,idx=folded.toLowerCase().lastIndexOf(marker.toLowerCase());if(idx<0)return null;let end=idx+marker.length,nextChar=folded.charAt(end);if(nextChar!==""&&nextChar!=="/")return null;return absTarget.slice(0,end)}function collectStandardGlobalPackageDirs(packageName,platform,env,homeDir,globalRoots){let out=[],bunGlobal=readEnv(env,platform,"BUN_INSTALL_GLOBAL_DIR");if(bunGlobal!=="")out.push(joinForPath(bunGlobal,"node_modules",packageName));let bunInstall=readEnv(env,platform,"BUN_INSTALL");if(bunInstall!=="")out.push(joinForPath(bunInstall,"install","global","node_modules",packageName));if(homeDir!=="")out.push(joinForPath(homeDir,".bun","install","global","node_modules",packageName));let npmPrefix=readEnv(env,platform,"NPM_CONFIG_PREFIX","npm_config_prefix");if(npmPrefix!=="")out.push(platform==="win32"?joinForPath(npmPrefix,"node_modules",packageName):joinForPath(npmPrefix,"lib","node_modules",packageName));let pnpmHome=readEnv(env,platform,"PNPM_HOME");if(pnpmHome!=="")out.push(joinForPath(pnpmHome,"global","5","node_modules",packageName));if(homeDir!==""){if(platform==="darwin")out.push(joinForPath(homeDir,"Library","pnpm","global","5","node_modules",packageName));else if(platform!=="win32")out.push(joinForPath(homeDir,".local","share","pnpm","global","5","node_modules",packageName))}if(platform==="win32"){let appData=readEnv(env,platform,"APPDATA","AppData");if(appData!=="")out.push(joinForPath(appData,"npm","node_modules",packageName));let localApp=readEnv(env,platform,"LOCALAPPDATA","LocalAppData");if(localApp!=="")out.push(joinForPath(localApp,"pnpm","global","5","node_modules",packageName))}else out.push(posix9.join("/opt/homebrew/lib/node_modules",packageName)),out.push(posix9.join("/usr/local/lib/node_modules",packageName));if(globalRoots!==void 0)for(let root of Object.values(globalRoots)){if(typeof root!=="string"||root==="")continue;out.push(root.replaceAll("\\","/").toLowerCase().endsWith("/node_modules")?joinForPath(root,packageName):joinForPath(root,"node_modules",packageName))}return out}function findSourceDevSymlinks(input){let{binName,meta,platform,env,globalRoots,ops}=input,pathImpl=platform==="win32"?win3210:posix9,home=resolveEnvHomeDir(env,platform,input.homeDir),resolvedRoot=ops.realpath(meta.packageRoot),found=[],seen=new Set,insideRepo=(p)=>isWithinDir(p,resolvedRoot)||isWithinDir(p,meta.packageRoot),inspectCandidate=(candidate,kind)=>{if(candidate.trim()==="")return null;let parentReal=ops.realpath(pathImpl.dirname(candidate)),canonical=pathImpl.join(parentReal,pathImpl.basename(candidate)),folded=normalizeSlashes(canonical).replace(/\/+$/,""),key=platform==="win32"?folded.toLowerCase():folded;if(seen.has(key))return null;if(insideRepo(candidate)||insideRepo(parentReal)||insideRepo(canonical))return null;if(!ops.isSymlink(candidate))return null;let targetReal=ops.realpath(candidate);if(!insideRepo(targetReal))return null;let intermediate=ops.realpath(ops.readlink(candidate)!==null?resolveLinkTarget(candidate,ops.readlink(candidate),platform):candidate),inferredPm=inferPmForLinkPath(candidate,intermediate,platform,env,home,globalRoots);if(kind==="package-dir"&&inferredPm===void 0)return null;seen.add(key);let entry=inferredPm!==void 0?{path:candidate,kind,inferredPm}:{path:candidate,kind};if(found.push(entry),kind==="bin"){let rawTgt=ops.readlink(candidate),firstHop=rawTgt!==null?resolveLinkTarget(candidate,rawTgt,platform):null,linkedPkgDir=firstHop!==null?extractNodeModulesPackageDir(firstHop,meta.name):null;if(linkedPkgDir!==null)inspectCandidate(linkedPkgDir,"package-dir")}return entry};inspectCandidate(meta.rawPackageRoot,"package-dir");for(let dir of parseAbsolutePathDirs(env,platform)){if(isLocalNodeModulesBinDir(dir))continue;if(platform==="win32")for(let suffix of WIN32_LINK_SUFFIXES)inspectCandidate(win3210.join(dir,`${binName}${suffix}`),"bin");else inspectCandidate(posix9.join(dir,binName),"bin")}if(typeof input.argvEntry==="string"&&input.argvEntry!==""&&!isLocalNodeModulesBinDir(pathImpl.dirname(input.argvEntry)))inspectCandidate(input.argvEntry,"bin");for(let stdDir of collectStandardGlobalPackageDirs(meta.name,platform,env,home,globalRoots))inspectCandidate(stdDir,"package-dir");return found}function findShadowSourceLinksInPath(input){let{binName,platform,env,ops,pathExists}=input,pathImpl=platform==="win32"?win3210:posix9,hits=[];for(let dir of parseAbsolutePathDirs(env,platform)){if(isLocalNodeModulesBinDir(dir))continue;let names=platform==="win32"?WIN32_LINK_SUFFIXES.map((s)=>`${binName}${s}`):[binName];for(let name of names){let cand=pathImpl.join(dir,name);if(!ops.isSymlink(cand))continue;let targetReal=ops.realpath(cand),pkgRoot=pathImpl.dirname(pathImpl.dirname(targetReal));if(!targetReal.replaceAll("\\","/").includes("/node_modules/")&&pathExists(joinForPath(pkgRoot,"src","cli.ts")))hits.push(cand)}}return hits}function cleanupShadowSourceLinksInPath(input){let{shadowLinks,platform,ops,pathExists}=input,pathImpl=platform==="win32"?win3210:posix9,unlinked=[],failed=[];for(let cand of shadowLinks){if(!ops.isSymlink(cand))continue;let targetReal=ops.realpath(cand),pkgRoot=pathImpl.dirname(pathImpl.dirname(targetReal));if(targetReal.replaceAll("\\","/").includes("/node_modules/")||!pathExists(joinForPath(pkgRoot,"src","cli.ts")))continue;try{ops.unlink(cand),unlinked.push(cand)}catch(error){failed.push({path:cand,reason:error instanceof Error?error.message:String(error)})}}return{unlinked,failed}}function isPmAvailableForGlobalInstall(pm,platform,env,deps){let isFile=deps?.isFile??defaultIsExecutable;if(resolveExecutableInPath(pm,platform,env,isFile)===null)return!1;if(pm==="yarn"){let yarnVer=deps?.probeYarn!==void 0?deps.probeYarn():probeYarnVersion(platform,env,deps?.spawnFn,isFile);if(yarnVer===null||isYarnBerryVersion(yarnVer))return!1}return!0}function resolveDefaultPmForSource(input){let{devLinks,platform,env}=input,home=resolveEnvHomeDir(env,platform,input.homeDir),pathDirs=parseAbsolutePathDirs(env,platform),binInPath=(pm)=>resolvePmGlobalBinDirs(pm,platform,env,home).some((b)=>pathDirs.some((d)=>isWithinDir(d,b)&&isWithinDir(b,d))),preferred=[];for(let link of devLinks)if(link.kind==="package-dir"&&link.inferredPm!==void 0){if(!preferred.includes(link.inferredPm))preferred.push(link.inferredPm)}for(let link of devLinks)if(link.kind==="bin"&&link.inferredPm!==void 0){if(!preferred.includes(link.inferredPm))preferred.push(link.inferredPm)}for(let pm of DEFAULT_SOURCE_PM_ORDER)if(binInPath(pm)&&!preferred.includes(pm))preferred.push(pm);for(let pm of DEFAULT_SOURCE_PM_ORDER)if(!preferred.includes(pm))preferred.push(pm);for(let pm of preferred)if(isPmAvailableForGlobalInstall(pm,platform,env,input))return pm;return}function emitUpdateOriginHeader(input){let{meta,origin,devLinks,isSourceSymlink,isCheck=!1,globalPm,explicitPm,targetPm,io,ui,locale}=input;if(io.out(ui.kv(t(locale,"当前版本","Current"),`${meta.name}@${meta.version}`,"bold")),io.out(ui.kv(t(locale,"安装方式","Origin"),describeOrigin(origin,locale,isSourceSymlink))),isSourceSymlink)io.out(ui.kv(t(locale,"源码软链","Source Links"),devLinks.map((l)=>sanitize(l.path)).join(", ")));if(explicitPm!==void 0&&explicitPm!==globalPm){if(io.out(ui.kv(t(locale,"目标安装器","Target PM"),t(locale,`${explicitPm} (经 --pm 手动指定)`,`${explicitPm} (via --pm)`),"cyan")),!isSourceSymlink)warnCrossPmOverride(origin,explicitPm,io,ui,locale)}else if(isSourceSymlink&&targetPm!==void 0)io.out(ui.kv(t(locale,isCheck?"拟用安装器":"目标安装器",isCheck?"Planned PM":"Target PM"),t(locale,`${targetPm} (卸载源码软链后全局安装)`,`${targetPm} (unlink source link & install globally)`),"cyan"))}function emitCheckUpgradeHint(input){let{binName,metaName,origin,targetPm,remoteVersion,explicitRegistry,isSourceSymlink,isOriginTransition,needForce,io,ui,locale}=input,forceSuffix=needForce?" --force":"";if(origin.kind==="standalone"&&targetPm===void 0)return io.out(ui.hint(t(locale,`运行 ${sanitize(binName)} update${forceSuffix} 即可在线升级 (独立脚本安装)`,`Run '${sanitize(binName)} update${forceSuffix}' to upgrade (standalone install)`))),0;if(origin.kind==="homebrew"&&targetPm===void 0){let cmd=formatHomebrewUpgradeCommand(origin.formulaRef,needForce);return io.out(ui.hint(t(locale,`运行 ${sanitize(binName)} update${forceSuffix} 即可${needForce?"强制重装":"升级"} (将执行: ${sanitize(cmd)})`,`Run '${sanitize(binName)} update${forceSuffix}' to ${needForce?"reinstall":"upgrade"} (${sanitize(cmd)})`))),0}if(targetPm!==void 0){let cmd=formatUpgradeDisplayCommand(targetPm,metaName,remoteVersion,explicitRegistry),hintMsg;if(isSourceSymlink)hintMsg=t(locale,`运行 ${sanitize(binName)} update${forceSuffix} 将卸载源码软链并安装全局版 (${sanitize(cmd)})`,`Run '${sanitize(binName)} update${forceSuffix}' to unlink source symlink(s) and install globally (${sanitize(cmd)})`);else if(isOriginTransition)hintMsg=t(locale,`运行命令即可安装全局版: ${sanitize(cmd)}`,`Run to install globally: ${sanitize(cmd)}`);else hintMsg=t(locale,`运行 ${sanitize(binName)} update${forceSuffix} 即可${needForce?"强制重装":"升级"} (将执行: ${sanitize(cmd)})`,`Run '${sanitize(binName)} update${forceSuffix}' to ${needForce?"reinstall":"upgrade"} (${sanitize(cmd)})`);return io.out(ui.hint(hintMsg)),0}return io.out(ui.hint(t(locale,`未能自动识别安装器, 升级请运行: ${sanitize(binName)} update --pm <bun|npm|pnpm|yarn|volta>`,`Package manager could not be auto-detected; upgrade with: ${sanitize(binName)} update --pm <bun|npm|pnpm|yarn|volta>`))),0}async function handleNonGlobalOrigin(ctx){let locale=ctx.locale??"zh",{meta,origin,hasExplicitRegistry,io,fetchVersion,registry}=ctx,ui=ctx.ui??createUpdateUi({stdout:!1,stderr:!1},locale);if(io.out(ui.kv(t(locale,"当前版本","Current"),`${meta.name}@${meta.version}`,"bold")),io.out(ui.kv(t(locale,"安装方式","Origin"),describeOrigin(origin,locale))),meta.isPrivate!==!0||hasExplicitRegistry){ctx.spinner?.start(t(locale,"正在检查最新版本","Checking latest version"),extractRegistryHost(registry));let remote;try{remote=await fetchVersion(registry)}finally{ctx.spinner?.stop()}if(remote.ok){let cmp=compareSemver(meta.version,remote.version),status;if(cmp===-1)status=t(locale,`发现新版本 ${remote.version} (源: ${remote.registry})`,`Update available: ${remote.version} (${remote.registry})`);else if(cmp===null)status=t(locale,`远端版本为 ${remote.version} (无法按 SemVer 比较, 源: ${remote.registry})`,`Remote version ${remote.version} (non-standard SemVer, ${remote.registry})`);else status=t(locale,`远端最新版为 ${remote.version} (源: ${remote.registry})`,`Latest is ${remote.version} (${remote.registry})`);io.out(ui.kv(t(locale,"版本检查","Latest"),status,cmp===-1?"cyan":"plain"))}else if(remote.code!=="not-found")io.out(ui.kv(t(locale,"版本检查","Latest"),t(locale,`暂未获取远端版本 (${sanitize(remote.message)})`,`Could not check remote version (${sanitize(remote.message)})`),"dim"))}let updateLabel=t(locale,"更新方式","How to Update");if(origin.kind==="source")return io.out(ui.kv(updateLabel,t(locale,"当前运行在本地源码工作树, 不通过包管理器覆盖。","Running from local source checkout; skipped global install."))),io.out(ui.hint(t(locale,"请在仓库根目录运行: git pull && bun install && bun run build","Update in repository root: git pull && bun install && bun run build"))),io.out(ui.hint(t(locale,"若要通过包管理器安装全局发布版, 可显式指定 --pm <bun|npm|pnpm|yarn|volta>","To install a global published copy instead, pass --pm <bun|npm|pnpm|yarn|volta>"))),0;if(origin.kind==="ephemeral")return io.out(ui.kv(updateLabel,t(locale,`当前经 ${origin.runner} 临时运行, 无需原地升级。`,`Executed temporarily via ${origin.runner}; no in-place upgrade needed.`))),io.out(ui.hint(t(locale,`下次获取最新版请运行: ${sanitize(ephemeralHintCommand(origin.runner,meta.name))}`,`Run the latest release anytime with: ${sanitize(ephemeralHintCommand(origin.runner,meta.name))}`))),io.out(ui.hint(t(locale,"若希望改为全局安装, 可运行带 --pm <bun|npm|pnpm|yarn|volta> 的 update 或直接全局安装","To install globally, pass --pm <bun|npm|pnpm|yarn|volta>"))),0;return io.out(ui.kv(updateLabel,t(locale,`当前作为项目本地依赖运行 (${sanitize(origin.projectDir)}), 为避免静默改写项目锁文件, 不自动覆盖。`,`Running as a project dependency (${sanitize(origin.projectDir)}); skipped to avoid mutating lockfiles.`))),io.out(ui.hint(t(locale,`请在项目目录执行: ${sanitize(localProjectHintCommand(origin.suggestedPm,meta.name))}`,`Upgrade inside the project directory: ${sanitize(localProjectHintCommand(origin.suggestedPm,meta.name))}`))),0}function handleShadowSourceLinks(ctx){let{binName,shadowLinks,checkOnly,deps,io,ui,locale}=ctx;if(shadowLinks.length===0)return;if(checkOnly){io.out(ui.warn(t(locale,`提示: PATH 中仍检测到源码软链 (${sanitize(shadowLinks.join(", "))}), 运行 ${sanitize(binName)} update 将自动清理。`,`Note: Source symlink(s) still present in PATH (${sanitize(shadowLinks.join(", "))}); run '${sanitize(binName)} update' to clean up automatically.`)));return}let shadowPlatform=deps.platform??process.platform,cleaned=cleanupShadowSourceLinksInPath({shadowLinks,platform:shadowPlatform,ops:createSourceLinkOps(shadowPlatform,deps),pathExists:deps.pathExists??existsSync7});if(cleaned.unlinked.length>0)io.out(ui.success(t(locale,`已自动清理遗留源码软链 (${sanitize(cleaned.unlinked.join(", "))})`,`Cleaned up leftover source symlink(s) (${sanitize(cleaned.unlinked.join(", "))})`)));for(let fail of cleaned.failed)io.out(ui.warn(t(locale,`提示: 遗留源码软链未能自动移除 (${sanitize(fail.path)}: ${sanitize(fail.reason)}), 请手动移除以避免路径干扰。`,`Note: Could not remove leftover source symlink (${sanitize(fail.path)}: ${sanitize(fail.reason)}); remove manually if needed.`)))}import{spawnSync as spawnSync3}from"node:child_process";import{existsSync as existsSync9,mkdirSync as mkdirSync4,mkdtempSync as mkdtempSync4,writeFileSync as writeFileSync4}from"node:fs";import{tmpdir as tmpdir4}from"node:os";import{dirname as dirname3,join as join7}from"node:path";import{createHash as createHash2,timingSafeEqual}from"node:crypto";import{createHash}from"node:crypto";import{chmodSync,existsSync as existsSync8,mkdirSync as mkdirSync3,readFileSync as readFileSync8,writeFileSync as writeFileSync3}from"node:fs";import{dirname as dirname2,join as join6,resolve as resolve3,sep}from"node:path";import{gunzipSync}from"node:zlib";var MAX_TARBALL_COMPRESSED_BYTES=67108864,MAX_TARBALL_UNCOMPRESSED_BYTES=268435456,MAX_TARBALL_ENTRY_COUNT=20000;function readTarString(buf,start,len){let end=start,max=Math.min(buf.length,start+len);while(end<max&&buf[end]!==0)end+=1;return Buffer.from(buf.subarray(start,end)).toString("utf8")}function readTarNumber(buf,start,len){let first=buf[start]??0;if(first>=128){let val=first-128;for(let i=1;i<len;i+=1)val=val*256+(buf[start+i]??0);return val}let raw=readTarString(buf,start,len).trim();if(raw==="")return 0;let parsed=Number.parseInt(raw,8);if(!Number.isFinite(parsed)||parsed<0)throw Error(`Invalid tar octal field: "${raw}"`);return parsed}function verifyHeaderChecksum(header){let expected=readTarNumber(header,148,8),unsignedSum=0;for(let i=0;i<512;i+=1)unsignedSum+=i>=148&&i<156?32:header[i]??0;return unsignedSum===expected}function isZeroBlock(block){for(let i=0;i<block.length;i+=1)if(block[i]!==0)return!1;return!0}function parsePaxRecords(data){let out={},cursor=0;while(cursor<data.length){let spaceIdx=cursor;while(spaceIdx<data.length&&data[spaceIdx]!==32)spaceIdx+=1;if(spaceIdx<=cursor||spaceIdx>=data.length)break;let lenText=Buffer.from(data.subarray(cursor,spaceIdx)).toString("ascii"),recLen=Number.parseInt(lenText,10);if(!Number.isFinite(recLen)||recLen<=spaceIdx-cursor+1)break;let recEnd=Math.min(data.length,cursor+recLen),record=Buffer.from(data.subarray(spaceIdx+1,recEnd)).toString("utf8"),eqIdx=record.indexOf("=");if(eqIdx>0){let key=record.slice(0,eqIdx),val=record.slice(eqIdx+1).replace(/\n$/,"");out[key]=val}cursor+=recLen}return out}function sanitizeArchiveRelativePath(rawName){if(rawName.includes("\x00"))throw Error("Unsafe archive entry contains NUL byte");let slashNorm=rawName.replaceAll("\\","/").replace(/^\.\//,"");if(slashNorm.startsWith("/")||/^[a-zA-Z]:/.test(slashNorm))throw Error(`Unsafe absolute archive path: ${rawName}`);let parts=slashNorm.split("/").filter((seg)=>seg!==""&&seg!==".");if(parts.includes(".."))throw Error(`Unsafe traversal archive path: ${rawName}`);if(parts.length<=1)return null;let rel=parts.slice(1).join("/");return rel===""?null:rel}function hasAnyExecuteBit(mode){let perm=mode%512,ownerExec=Math.floor(perm/64)%2===1,groupExec=Math.floor(perm/8)%2===1,otherExec=perm%2===1;return ownerExec||groupExec||otherExec}function parseNpmTarArchive(tarBytes){if(tarBytes.byteLength>MAX_TARBALL_UNCOMPRESSED_BYTES)throw Error(`Uncompressed tar exceeds safety limit (${tarBytes.byteLength} > ${MAX_TARBALL_UNCOMPRESSED_BYTES} bytes)`);let entries=[],offset=0,totalPayloadBytes=0,nextPax=null,nextLongName=null;while(offset+512<=tarBytes.length){let header=tarBytes.subarray(offset,offset+512);if(isZeroBlock(header))break;if(!verifyHeaderChecksum(header))throw Error(`Corrupt tar header checksum at offset ${offset}`);let typeByte=header[156]??0,typeFlag=typeByte===0?"0":String.fromCharCode(typeByte),mode=readTarNumber(header,100,8),size=readTarNumber(header,124,12),baseName=readTarString(header,0,100),prefix=readTarString(header,345,155),fullName=prefix!==""?`${prefix}/${baseName}`:baseName;if(!(typeFlag==="x"||typeFlag==="g"||typeFlag==="L"||typeFlag==="K")&&nextPax!==null&&typeof nextPax.size==="string"){let paxSize=Number.parseInt(nextPax.size,10);if(Number.isFinite(paxSize)&&paxSize>=0)size=paxSize}offset+=512;let dataEnd=offset+size;if(dataEnd>tarBytes.length)throw Error("Truncated tar entry payload");let payload=tarBytes.subarray(offset,dataEnd),paddedBlocks=Math.ceil(size/512)*512;if(offset+=paddedBlocks,typeFlag==="x"){nextPax=parsePaxRecords(payload);continue}if(typeFlag==="g"||typeFlag==="K")continue;if(typeFlag==="L"){nextLongName=Buffer.from(payload).toString("utf8").replace(/\0+$/,"");continue}if(nextPax!==null){if(typeof nextPax.path==="string"&&nextPax.path!=="")fullName=nextPax.path;nextPax=null}if(nextLongName!==null)fullName=nextLongName,nextLongName=null;if(fullName==="pax_global_header")continue;if(typeFlag!=="0"&&typeFlag!=="5")throw Error(`Unsupported or unsafe tar entry type "${typeFlag}" (${fullName})`);let relPath=sanitizeArchiveRelativePath(fullName);if(relPath===null)continue;if(entries.length>=MAX_TARBALL_ENTRY_COUNT)throw Error(`Archive exceeds maximum entry count (${MAX_TARBALL_ENTRY_COUNT})`);if(typeFlag==="0"){if(totalPayloadBytes+=payload.byteLength,totalPayloadBytes>MAX_TARBALL_UNCOMPRESSED_BYTES)throw Error("Archive extracted payload exceeds safety limit")}entries.push({relPath,type:typeFlag==="5"?"dir":"file",mode:mode%512,data:typeFlag==="0"?payload:new Uint8Array(0)})}return entries}function extractNpmTarball(tgzBytes,destDir){if(tgzBytes.byteLength>MAX_TARBALL_COMPRESSED_BYTES)throw Error(`Compressed tarball exceeds safety limit (${tgzBytes.byteLength} > ${MAX_TARBALL_COMPRESSED_BYTES} bytes)`);let tarBytes=gunzipSync(tgzBytes,{maxOutputLength:MAX_TARBALL_UNCOMPRESSED_BYTES}),entries=parseNpmTarArchive(tarBytes),absRoot=resolve3(destDir);mkdirSync3(absRoot,{recursive:!0});let rootPrefix=absRoot.endsWith(sep)?absRoot:`${absRoot}${sep}`,fileCount=0;for(let entry of entries){let absTarget=resolve3(absRoot,entry.relPath);if(!absTarget.startsWith(rootPrefix))throw Error(`Archive target escapes destination: ${entry.relPath}`);if(entry.type==="dir"){mkdirSync3(absTarget,{recursive:!0});continue}mkdirSync3(dirname2(absTarget),{recursive:!0}),writeFileSync3(absTarget,entry.data);let safeMode=hasAnyExecuteBit(entry.mode)?493:420;try{chmodSync(absTarget,safeMode)}catch{}fileCount+=1}return fileCount}function extractDeclaredBinPaths(binField){if(typeof binField==="string")return[binField];if(typeof binField==="object"&&binField!==null&&!Array.isArray(binField))return Object.values(binField).filter((v)=>typeof v==="string");return[]}function verifyExtractedCliBundle(stagingDir,packageName,binField){let absRoot=resolve3(stagingDir),rootPrefix=absRoot.endsWith(sep)?absRoot:`${absRoot}${sep}`;if(binField!==void 0){let binPaths=extractDeclaredBinPaths(binField);for(let rel of binPaths){let target=resolve3(absRoot,rel);if(!target.startsWith(rootPrefix)||!existsSync8(target))return{ok:!1,reason:`missing bin entrypoint (${rel})`}}}if(!existsSync8(join6(absRoot,"bin","bunfig.toml")))return{ok:!1,reason:"missing bin/bunfig.toml"};let unscoped=packageName.includes("/")?packageName.slice(packageName.indexOf("/")+1):packageName,bundleCandidates=["cli.js",`${unscoped}.js`],matchedBundle;for(let cand of bundleCandidates)if(existsSync8(join6(absRoot,"dist",cand))){matchedBundle=cand;break}if(matchedBundle===void 0)return{ok:!1,reason:`missing dist/cli.js or dist/${unscoped}.js`};let manifestPath=join6(absRoot,"dist","manifest.json");if(!existsSync8(manifestPath))return{ok:!1,reason:"missing dist/manifest.json"};try{let manifest=JSON.parse(readFileSync8(manifestPath,"utf8"));if(manifest.schemaVersion!==1||typeof manifest.cliSha256!=="string")return{ok:!1,reason:"invalid dist/manifest.json schema"};if(createHash("sha256").update(readFileSync8(join6(absRoot,"dist",matchedBundle))).digest("hex")!==manifest.cliSha256)return{ok:!1,reason:`dist/${matchedBundle} SHA-256 mismatch with dist/manifest.json`}}catch{return{ok:!1,reason:"corrupt dist/manifest.json"}}return{ok:!0,bundleRel:`dist/${matchedBundle}`}}var DEFAULT_MAX_TARBALL_BYTES=67108864;function sanitizeToken(token){if(typeof token==="string"&&token.trim()!==""&&!/[\s\p{Cc}]/u.test(token))return token.trim();return}function sameOrigin(urlA,urlB){try{return new URL(urlA).origin===new URL(urlB).origin}catch{return!1}}async function fetchTarballMetadata(input){let locale=input.locale??"zh",spec=input.targetSpec??"latest";if(!isValidPackageName(input.packageName)||!isValidTargetSpec(spec)||!isValidRegistryUrl(input.registry))return{ok:!1,code:"invalid-response",message:t(locale,"非法的包名、目标版本或 registry 地址","Invalid package name, version spec, or registry URL")};let base=normalizeRegistryUrl2(input.registry),url=`${base}/${encodeURIComponent(input.packageName)}/${encodeURIComponent(spec)}`,fetchFn=input.fetchFn??fetch,timeoutMs=input.timeoutMs??DEFAULT_FETCH_TIMEOUT_MS,authToken=sanitizeToken(input.authToken),headers={accept:"application/json"};if(authToken!==void 0)headers.authorization=`Bearer ${authToken}`;let response;try{response=await fetchWithoutHttpsDowngrade(url,{headers,signal:AbortSignal.timeout(timeoutMs),fetchFn})}catch(error){let detail=error instanceof Error?cleanMessage(error.message,authToken):"";return{ok:!1,code:"network",message:detail===""?t(locale,`无法连接源 (${base})`,`Cannot reach registry (${base})`):t(locale,`无法连接源 (${base}): ${detail}`,`Cannot reach registry (${base}): ${detail}`)}}if(response.status===401||response.status===403)return{ok:!1,code:"auth",status:response.status,message:t(locale,`访问源 ${base} 鉴权失败 (HTTP ${response.status})`,`Authentication failed for ${base} (HTTP ${response.status})`)};if(response.status===404)return{ok:!1,code:"not-found",status:404,message:t(locale,`${input.packageName}@${spec} 在 ${base} 不存在 (HTTP 404)`,`${input.packageName}@${spec} not found on ${base} (HTTP 404)`)};if(!response.ok)return{ok:!1,code:"http",status:response.status,message:t(locale,`注册表返回 HTTP ${response.status} (${base})`,`Registry returned HTTP ${response.status} (${base})`)};let body;try{body=await response.json()}catch{return{ok:!1,code:"invalid-response",message:t(locale,`包元数据不是合法 JSON (${base})`,`Package metadata is not valid JSON (${base})`)}}if(typeof body!=="object"||body===null||Array.isArray(body))return{ok:!1,code:"invalid-response",message:t(locale,"包元数据响应格式无效","Invalid package metadata object")};let record=body,version=record.version,tarballUrl=record.dist?.tarball,integrity=typeof record.dist?.integrity==="string"?record.dist.integrity.trim():void 0,shasum=typeof record.dist?.shasum==="string"?record.dist.shasum.trim().toLowerCase():void 0;if(typeof version!=="string"||!isValidTargetSpec(version)||typeof tarballUrl!=="string"||!isAllowedTarballUrl(tarballUrl,base))return{ok:!1,code:"invalid-response",message:t(locale,"包元数据缺少合法 version 或 dist.tarball 地址","Package metadata is missing valid version or dist.tarball URL")};return{ok:!0,version,registry:base,tarballUrl,integrity:integrity===""?void 0:integrity,shasum:shasum===""?void 0:shasum}}function verifyTarballDigest(bytes,integrity,shasum,locale="zh"){if(integrity!==void 0){let tokens=integrity.split(/\s+/).filter(Boolean),supportedCount=0,lastAlgo="";for(let token of tokens){let dashIdx=token.indexOf("-");if(dashIdx<=0)continue;let algo=token.slice(0,dashIdx).toLowerCase(),expectedB64=token.slice(dashIdx+1);if(algo!=="sha512"&&algo!=="sha256")continue;supportedCount+=1,lastAlgo=algo;let expected=Buffer.from(expectedB64,"base64"),actual=createHash2(algo).update(bytes).digest();if(expected.length>0&&expected.length===actual.length&&timingSafeEqual(expected,actual))return{ok:!0}}if(supportedCount>0)return{ok:!1,message:t(locale,`Tarball ${lastAlgo} 完整性校验失败 (可能已损坏或被篡改)`,`Tarball ${lastAlgo} integrity check failed`)}}if(shasum!==void 0&&/^[0-9a-f]{40}$/i.test(shasum)){let expected=Buffer.from(shasum,"hex"),actual=createHash2("sha1").update(bytes).digest();if(expected.length===actual.length&&timingSafeEqual(expected,actual))return{ok:!0};return{ok:!1,message:t(locale,"Tarball sha1 (shasum) 完整性校验失败","Tarball sha1 (shasum) check failed")}}return{ok:!1,message:t(locale,"注册表元数据缺少可验证的 dist.integrity 或 dist.shasum, 已拒绝安装","Missing verifiable dist.integrity or dist.shasum in metadata; aborted")}}async function readResponseWithLimit(response,maxBytes,locale){let overLimit=(size)=>({ok:!1,code:"invalid-response",message:t(locale,`安装包体积超出安全上限 (${size} > ${maxBytes} 字节)`,`Tarball size exceeds limit (${size} > ${maxBytes} bytes)`)}),contentLengthHeader=response.headers.get("content-length");if(contentLengthHeader!==null){let declaredLen=Number.parseInt(contentLengthHeader.trim(),10);if(Number.isFinite(declaredLen)&&declaredLen>maxBytes)return await response.body?.cancel().catch(()=>{}),overLimit(declaredLen)}if(response.body===null||typeof response.body.getReader!=="function"){let rawBuf=Buffer.from(await response.arrayBuffer());return rawBuf.length>maxBytes?overLimit(rawBuf.length):{ok:!0,bytes:rawBuf}}let reader=response.body.getReader(),chunks=[],totalBytes=0;try{while(!0){let{done,value}=await reader.read();if(done)break;if(value===void 0||value.byteLength===0)continue;if(totalBytes+=value.byteLength,totalBytes>maxBytes)return await reader.cancel().catch(()=>{}),overLimit(totalBytes);chunks.push(value)}}finally{reader.releaseLock()}return{ok:!0,bytes:Buffer.concat(chunks,totalBytes)}}async function downloadAndVerifyTarball(input){let locale=input.locale??"zh";if(!isAllowedTarballUrl(input.tarballUrl,input.expectedRegistryBase))return{ok:!1,code:"invalid-response",message:t(locale,"非法的 tarball 下载地址","Invalid tarball URL")};let fetchFn=input.fetchFn??fetch,timeoutMs=input.timeoutMs??DEFAULT_FETCH_TIMEOUT_MS*3,maxBytes=input.maxBytes??DEFAULT_MAX_TARBALL_BYTES,authToken=sanitizeToken(input.authToken),headers={};if(authToken!==void 0&&input.expectedRegistryBase!==void 0&&sameOrigin(input.tarballUrl,input.expectedRegistryBase))headers.authorization=`Bearer ${authToken}`;let networkFail=(error)=>{let detail=error instanceof Error?cleanMessage(error.message,authToken):"";return{ok:!1,code:"network",message:detail===""?t(locale,"下载安装包失败","Failed to download package tarball"):t(locale,`下载安装包失败: ${detail}`,`Failed to download package tarball: ${detail}`)}},response;try{response=await fetchWithoutHttpsDowngrade(input.tarballUrl,{headers,signal:AbortSignal.timeout(timeoutMs),fetchFn})}catch(error){return networkFail(error)}if(response.status===401||response.status===403)return{ok:!1,code:"auth",status:response.status,message:t(locale,`下载安装包鉴权失败 (HTTP ${response.status})`,`Authentication failed downloading tarball (HTTP ${response.status})`)};if(!response.ok)return{ok:!1,code:"http",status:response.status,message:t(locale,`下载安装包返回 HTTP ${response.status}`,`Tarball download returned HTTP ${response.status}`)};let bodyRes;try{bodyRes=await readResponseWithLimit(response,maxBytes,locale)}catch(error){return networkFail(error)}if(!bodyRes.ok)return bodyRes;let rawBuf=bodyRes.bytes,digestCheck=verifyTarballDigest(rawBuf,input.integrity,input.shasum,locale);if(!digestCheck.ok)return{ok:!1,code:"integrity",message:digestCheck.message};return{ok:!0,bytes:rawBuf}}function resolveDependencyInstaller(input){let regFlag=`--registry=${normalizeRegistryUrl2(input.registry)}`,bunArgs=["install",`--config=${input.cleanBunfig}`,"--no-env-file","--production","--ignore-scripts","--no-save","--no-cache",regFlag],bunExe=input.platform==="win32"?"bun.exe":"bun",isolatedBun=joinForPath(input.origin.runtimeDir,bunExe);if(input.isFile(isolatedBun))return{label:"bun",command:isolatedBun,args:bunArgs};let bunInv=resolvePmInvocation("bun",bunArgs,input.platform,input.env,input.isFile);if(bunInv!==null)return{label:"bun",command:bunInv.command,args:bunInv.args,windowsVerbatimArguments:bunInv.windowsVerbatimArguments};let npmInv=resolvePmInvocation("npm",["install",`--userconfig=${input.emptyUserNpmrc}`,`--globalconfig=${input.emptyGlobalNpmrc}`,"--workspaces=false","--global=false","--no-package-lock","--omit=dev","--ignore-scripts","--no-audit","--no-fund",regFlag],input.platform,input.env,input.isFile);if(npmInv!==null)return{label:"npm",command:npmInv.command,args:npmInv.args,windowsVerbatimArguments:npmInv.windowsVerbatimArguments};return null}function installStagingDependencies(input){let platform=input.deps.platform??process.platform,env=input.deps.env??process.env,isFile=input.deps.isFile??defaultIsExecutable,effectiveRegistry=input.opts.registry??input.registry,cfgDir=null;try{let cfg=createIsolatedDepConfigs();cfgDir=cfg.cfgDir;let plan=resolveDependencyInstaller({origin:input.origin,registry:effectiveRegistry,cleanBunfig:cfg.cleanBunfig,emptyUserNpmrc:cfg.emptyUserNpmrc,emptyGlobalNpmrc:cfg.emptyGlobalNpmrc,platform,env,isFile});if(plan===null)return input.io.err(input.ui.error(t(input.locale,"新版本包含运行时依赖, 但未找到隔离 Bun、系统 Bun 或 npm 来安装依赖","The new version declares runtime dependencies, but neither Bun nor npm was found to install them"))),!1;let child=(input.deps.spawnFn??((cmd,args,opts)=>spawnSync3(cmd,args,{...opts,encoding:"utf8"})))(plan.command,plan.args,{cwd:input.stagingDir,env:buildDepInstallEnv(env,plan.label,cfg),encoding:"utf8",stdio:["ignore","pipe","pipe"],timeout:60000,windowsVerbatimArguments:plan.windowsVerbatimArguments});if(child.error!==void 0||child.status!==0){let errMsg=child.error!==void 0?child.error.message:`exit status ${child.status??"unknown"}`;input.io.err(input.ui.error(t(input.locale,`安装新版本运行时依赖失败 (${plan.label}: ${sanitize(errMsg)})`,`Failed to install runtime dependencies (${plan.label}: ${sanitize(errMsg)})`)));let combined=`${child.stdout??""}
|
|
20
|
+
${child.stderr??""}`.trim();if(combined!=="")for(let line of sanitizeMultilineTail(combined).lines)input.io.err(input.ui.errorLogLine(line));return!1}return!0}catch(err){let msg=err instanceof Error?err.message:String(err);return input.io.err(input.ui.error(t(input.locale,`准备依赖安装隔离配置失败: ${sanitize(msg)}`,`Failed to prepare isolated dependency config: ${sanitize(msg)}`))),!1}finally{if(cfgDir!==null)removeDirBestEffort(cfgDir)}}function reportStandaloneError(error,authToken,ctx){let{io,ui,locale,deps}=ctx,raw=error instanceof Error?error.message:String(error),msg=cleanMessage(raw,authToken);if(io.err(ui.error(t(locale,`独立安装更新失败: ${sanitize(msg)}`,`Standalone upgrade failed: ${sanitize(msg)}`))),(deps.platform??process.platform)==="win32")io.err(ui.errorHint(t(locale,`Windows 提示: 若应用目录被其他正在运行的 ${sanitize(ctx.binName)} 终端或安全软件占用 (EBUSY / EPERM), 请关闭其他占用终端后重试或重新运行一键安装脚本。`,`Windows note: If the app directory is locked (EBUSY / EPERM) by another running '${sanitize(ctx.binName)}' process, close active terminals and retry or re-run the install script.`)))}async function performStandaloneUpgrade(ctx){let{meta,origin,targetVersion,registry,opts,io,color,ui,spinner,deps,locale}=ctx,startedAt=Date.now(),targetLabel=formatVersionLabel(sanitize(targetVersion)),regHost=extractRegistryHost(registry),authToken=resolveRegistryAuthToken({packageName:meta.name,registry,env:deps.env,homeDir:deps.homeDir,readText:deps.readText});spinner.start(t(locale,`正在下载 ${sanitize(meta.name)} ${targetLabel}`,`Downloading ${sanitize(meta.name)} ${targetLabel}`),regHost);let stagingShell,stagingDir,backupDir;try{let metaRes=await fetchTarballMetadata({packageName:meta.name,targetSpec:targetVersion,registry,authToken,fetchFn:deps.fetchFn,locale});if(!metaRes.ok)return spinner.stop(),io.err(ui.error(sanitize(metaRes.message))),1;let dlRes=await downloadAndVerifyTarball({tarballUrl:metaRes.tarballUrl,integrity:metaRes.integrity,shasum:metaRes.shasum,authToken,expectedRegistryBase:metaRes.registry,fetchFn:deps.fetchFn,locale});if(!dlRes.ok)return spinner.stop(),io.err(ui.error(sanitize(dlRes.message))),1;let parentDir=dirname3(meta.packageRoot);stagingShell=mkdtempSync4(join7(parentDir,`.clis-staging-${origin.tool}-`)),stagingDir=join7(stagingShell,"node_modules","pkg"),mkdirSync4(stagingDir,{recursive:!0}),extractNpmTarball(dlRes.bytes,stagingDir);let extractedPkg=readExtractedPackageJson(stagingDir),bundleCheck=extractedPkg!==null&&extractedPkg.name===meta.name?verifyExtractedCliBundle(stagingDir,meta.name,extractedPkg.bin):{ok:!1,reason:"package.json name mismatch"};if(!bundleCheck.ok)return spinner.stop(),io.err(ui.error(t(locale,`下载的安装包结构或产物清单校验失败 (${sanitize(bundleCheck.reason)})`,`Downloaded package archive failed verification (${sanitize(bundleCheck.reason)})`))),1;if(sanitizeStagingPackageJson(stagingDir),extractedPkg!==null&&extractedPkg.dependencies!==void 0){if(spinner.update(t(locale,"正在安装运行时依赖","Installing runtime dependencies")),!installStagingDependencies({stagingDir,origin,registry:metaRes.registry,opts,deps,io,ui,locale}))return spinner.stop(),1}let nextMarker={schemaVersion:1,method:"script",tool:origin.tool,packageName:origin.packageName,dataDir:origin.dataDir,appDir:origin.appDir,runtimeDir:origin.runtimeDir,binPath:origin.binPath,version:extractedPkg?.version??metaRes.version,updatedAt:new Date().toISOString()};if(writeFileSync4(join7(stagingDir,STANDALONE_MARKER_FILE),`${JSON.stringify(nextMarker,null,2)}
|
|
21
|
+
`,"utf8"),isWithinDir(process.cwd(),meta.packageRoot))try{process.chdir(tmpdir4())}catch{}backupDir=join7(parentDir,`.clis-backup-${origin.tool}-${process.pid}-${Date.now()}`),renameWithRetry(meta.packageRoot,backupDir);try{renameWithRetry(stagingDir,meta.packageRoot)}catch(swapError){let rollbackOk=!1;try{renameWithRetry(backupDir,meta.packageRoot),rollbackOk=!0}catch{rollbackOk=!1}if(!rollbackOk){let swapMsg=swapError instanceof Error?swapError.message:String(swapError);throw Error(t(locale,`${swapMsg}; 自动回滚亦失败, 旧版本完整备份保留于 ${backupDir}, 请手动移回 ${meta.packageRoot}`,`${swapMsg}; automatic rollback also failed — previous backup is preserved at ${backupDir}, move it back to ${meta.packageRoot}`))}throw swapError}removeDirBestEffort(backupDir),spinner.stop();let finalVer=extractedPkg?.version??metaRes.version,elapsed=formatElapsedMs(Date.now()-startedAt);return io.out(ui.success(t(locale,`升级完成: ${sanitize(meta.name)} 已切换至 ${paintSgr(formatVersionLabel(sanitize(finalVer)),"1;32",color.stdout)} ${paintSgr("(独立脚本安装)","2",color.stdout)}`,`Upgraded ${sanitize(meta.name)} to ${paintSgr(formatVersionLabel(sanitize(finalVer)),"1;32",color.stdout)} ${paintSgr("(standalone)","2",color.stdout)}`),elapsed)),0}catch(error){return spinner.stop(),reportStandaloneError(error,authToken,ctx),1}finally{if(stagingShell!==void 0&&existsSync9(stagingShell))removeDirBestEffort(stagingShell)}}function emitCapturedFailureTail(result,verbose,io,ui,locale){if(verbose||typeof result.capturedOutput!=="string")return;let tail=sanitizeMultilineTail(result.capturedOutput);if(tail.lines.length===0)return;let isClipped=result.truncated===!0||tail.clipped;io.err(ui.errorHint(isClipped?t(locale,"底层输出摘要 (仅显示末尾):","Package manager output (tail):"):t(locale,"底层输出摘要:","Package manager output:")));for(let line of tail.lines)io.err(ui.errorLogLine(line))}function emitUpgradeExecutionFailure(input){let{result,binName,targetPm,platform,displayCommand,verbose,io,ui,locale}=input,manualHint=t(locale,`手动更新命令: ${displayCommand}`,`Run manually: ${displayCommand}`);if(result.error!==void 0)return io.err(ui.error(t(locale,`更新命令启动失败: ${sanitize(result.error.message)}`,`Failed to launch package manager: ${sanitize(result.error.message)}`))),emitCapturedFailureTail(result,verbose,io,ui,locale),io.err(ui.errorHint(manualHint)),1;if(result.signal!==void 0&&result.signal!==null)return io.err(ui.error(t(locale,`更新进程被信号中断 (${result.signal})`,`Upgrade interrupted by signal (${result.signal})`))),emitCapturedFailureTail(result,verbose,io,ui,locale),io.err(ui.errorHint(manualHint)),1;if(io.err(ui.error(t(locale,`更新失败 (${targetPm} 退出码 ${String(result.status??1)})`,`Upgrade failed (${targetPm} exited with code ${String(result.status??1)})`))),emitCapturedFailureTail(result,verbose,io,ui,locale),platform==="win32")io.err(ui.errorHint(t(locale,`Windows 提示: 当前正在运行的 ${sanitize(binName)} 自身可执行/shim 文件可能被系统锁定 (EBUSY / EPERM), 请退出当前命令并关闭其他占用终端后直接执行下方命令:`,`Windows note: The running '${sanitize(binName)}' shim may be locked (EBUSY / EPERM); close active terminals and run manually:`)));if(targetPm==="pnpm")io.err(ui.errorHint(t(locale,"pnpm 提示: 若提示未配置全局 bin 目录, 请检查 PNPM_HOME 环境变量或先运行 pnpm setup。","pnpm note: If global bin directory is unconfigured, check PNPM_HOME or run 'pnpm setup'.")));return io.err(ui.errorHint(manualHint)),1}function handlePostInstallSourceCleanup(input){let{postInstall,preRemoved,shouldUnlink,linkOps,io,ui,locale}=input,postCleanup=postInstall.length>0?cleanupPostInstallDevLinks(postInstall,linkOps,shouldUnlink):{unlinked:[],failed:[]},unlinkedPaths=[...preRemoved.map((r)=>r.link.path),...postCleanup.unlinked];if(unlinkedPaths.length>0)io.out(ui.success(t(locale,`已卸载源码软链 (${sanitize(unlinkedPaths.join(", "))})`,`Unlinked source symlink(s) (${sanitize(unlinkedPaths.join(", "))})`)));for(let fail of postCleanup.failed)io.err(ui.error(t(locale,`源码软链未能自动卸载 (${sanitize(fail.path)}: ${sanitize(fail.reason)}), 请手动移除以避免遮蔽全局版本`,`Could not remove source symlink (${sanitize(fail.path)}: ${sanitize(fail.reason)}); remove it manually to avoid shadowing`)));return{postUnlinked:postCleanup.unlinked,allCleaned:postCleanup.failed.length===0}}function preparePreInstallDevLinks(input){let{devLinks,targetPm,platform,env,deps,linkOps,stillPointsToRepo,displayCommand,io,ui,locale}=input,homeDir=resolveEnvHomeDir(env,platform,deps.homeDir),targetBinDirs=resolvePmGlobalBinDirs(targetPm,platform,env,homeDir),{preInstall,postInstall}=partitionSourceDevLinks(devLinks,targetBinDirs);if(preInstall.length===0)return{ok:!0,preRemoved:[],postInstall};let unlinkedPre=unlinkSourceDevLinks(preInstall,linkOps,stillPointsToRepo);if(!unlinkedPre.ok)return io.err(ui.error(t(locale,`卸载源码软链失败 (${sanitize(unlinkedPre.failedPath)}): ${sanitize(unlinkedPre.error.message)}`,`Failed to unlink source symlink (${sanitize(unlinkedPre.failedPath)}): ${sanitize(unlinkedPre.error.message)}`))),io.err(ui.errorHint(t(locale,`手动更新命令: ${displayCommand}`,`Run manually: ${displayCommand}`))),{ok:!1};return{ok:!0,preRemoved:unlinkedPre.removed,postInstall}}async function performUpgrade(ctx){let{binName,meta,origin,targetPm,targetSpec,devLinks=[],opts,io,color,ui,spinner,deps,locale}=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,deps.isFile);let built=buildUpgradePlan({pm:targetPm,packageName:meta.name,targetSpec,explicitRegistry:opts.registry,platform,env,isFile:deps.isFile,yarnVersion,locale}),manualHint=(cmd)=>t(locale,`手动更新命令: ${cmd}`,`Run manually: ${cmd}`);if(!built.ok){if(io.err(ui.error(t(locale,`无法自动更新: ${built.reason}`,`Cannot upgrade automatically: ${built.reason}`))),built.fallbackCommand!==void 0)io.err(ui.errorHint(manualHint(built.fallbackCommand)));return 1}let linkOps=createSourceLinkOps(platform,deps),resolvedPkgRoot=linkOps.realpath(meta.packageRoot),stillPointsToRepo=(p)=>{let r=linkOps.realpath(p);return isWithinDir(r,resolvedPkgRoot)||isWithinDir(r,meta.packageRoot)},pre=preparePreInstallDevLinks({devLinks,targetPm,meta,platform,env,deps,linkOps,stillPointsToRepo,displayCommand:built.plan.displayCommand,io,ui,locale});if(!pre.ok)return 1;let{preRemoved,postInstall}=pre,targetLabel=formatVersionLabel(sanitize(targetSpec));if(opts.verbose)io.out(ui.kv(t(locale,"执行命令","Command"),built.plan.displayCommand,"dim"));else spinner.start(t(locale,`正在通过 ${targetPm} 升级至 ${targetLabel}`,`Upgrading to ${targetLabel} via ${targetPm}`));let result;try{if(deps.execPlanAsync!==void 0)result=await deps.execPlanAsync(built.plan,{env,verbose:opts.verbose,spawnAsync:deps.spawnAsync});else if(deps.execPlan!==void 0)result=await deps.execPlan(built.plan,env,deps.spawnFn);else result=await executeUpgradePlanAsync(built.plan,{env,verbose:opts.verbose,spawnAsync:deps.spawnAsync})}catch(err){result={status:null,error:err instanceof Error?err:Error(String(err))}}finally{spinner.stop()}if(result.error!==void 0||result.signal!==void 0&&result.signal!==null||result.status!==0){let rollbackFailures=rollbackRemovedDevLinks(preRemoved,linkOps);for(let rbFail of rollbackFailures)io.err(ui.errorHint(t(locale,`警告: 预卸载的源码软链还原失败 (${sanitize(rbFail.path)}: ${sanitize(rbFail.reason)})`,`Warning: Failed to restore source symlink (${sanitize(rbFail.path)}: ${sanitize(rbFail.reason)})`)));return emitUpgradeExecutionFailure({result,binName,targetPm,platform,displayCommand:built.plan.displayCommand,verbose:opts.verbose,io,ui,locale})}let elapsed=formatElapsedMs(result.durationMs),pkgLabel=paintSgr(sanitize(meta.name),"1",color.stdout),verLabel=paintSgr(targetLabel,"1;36",color.stdout);io.out(ui.success(t(locale,`已通过 ${targetPm} 更新 ${pkgLabel} 至 ${verLabel}`,`Updated ${pkgLabel} to ${verLabel} via ${targetPm}`),elapsed!==""?`(${elapsed})`:void 0));let cleanupOutcome=devLinks.length>0?handlePostInstallSourceCleanup({postInstall,preRemoved,shouldUnlink:stillPointsToRepo,linkOps,io,ui,locale}):{postUnlinked:[],allCleaned:!1};return verifyPostUpgrade({binName,meta,origin,targetPm,targetSpec,platform,env,readText:deps.readText,pathExists:deps.pathExists,isFile:deps.isFile,realpath:linkOps.realpath,devLinksRemoved:devLinks.length>0&&cleanupOutcome.allCleaned,postUnlinkedPaths:cleanupOutcome.postUnlinked,io,ui,locale}),0}async function tryForceOfflineUpgrade(ctx){let{meta,origin,targetPm,remote,opts,io,ui,locale}=ctx;if(!opts.force||opts.check||remote.code==="not-found")return null;let warnFetch=()=>{io.err(ui.error(t(locale,`警示: 远端版本查询失败 (${sanitize(remote.message)})`,`Warning: Version check failed (${sanitize(remote.message)})`)))};if(origin.kind==="standalone"&&opts.pm===void 0)return warnFetch(),io.out(ui.body(t(locale,`强制重装模式 (--force): 跳过远端版本校验, 将直接从注册表安装 ${sanitize(meta.name)}@latest (独立脚本安装)`,`Force mode (--force): Skipping version check and installing ${sanitize(meta.name)}@latest (standalone)`))),await performStandaloneUpgrade({...ctx,origin,targetVersion:"latest"});if(origin.kind==="homebrew"&&opts.pm===void 0)return warnFetch(),io.out(ui.body(t(locale,`强制重装模式 (--force): 跳过远端版本校验, 将直接通过 Homebrew 升级 ${sanitize(origin.formulaRef)}`,`Force mode (--force): Skipping version check and upgrading ${sanitize(origin.formulaRef)} via Homebrew`))),await performHomebrewUpgrade({...ctx,origin,targetVersion:"latest",hasUpdate:!0});if(targetPm!==void 0)return warnFetch(),io.out(ui.body(t(locale,`强制重装模式 (--force): 跳过远端版本校验, 将直接通过 ${targetPm} 安装 ${sanitize(meta.name)}@latest`,`Force mode (--force): Skipping version check and installing ${sanitize(meta.name)}@latest via ${targetPm}`))),await performUpgrade({...ctx,targetPm,targetSpec:"latest"});return null}async function handleFetchFailure(ctx){let offlineCode=await tryForceOfflineUpgrade(ctx);if(offlineCode!==null)return offlineCode;let{meta,origin,targetPm,registry,remote,opts,io,ui,locale}=ctx;if(remote.code==="not-found"){let privSuffix=meta.isPrivate?t(locale," (当前包标记为 private)"," (package is marked private)"):"";return io.err(ui.error(t(locale,`${sanitize(meta.name)} 尚未在 ${sanitize(registry)} 发布 (HTTP 404), 无法在线更新${privSuffix}`,`${sanitize(meta.name)} is not published on ${sanitize(registry)} (HTTP 404)${privSuffix}`))),io.err(ui.errorHint(t(locale,"若已发布到私有源, 请加 --registry <url> 后重试","If published to a private registry, pass --registry <url>"))),1}if(io.err(ui.error(t(locale,`检查最新版本失败: ${sanitize(remote.message)}`,`Failed to check latest version: ${sanitize(remote.message)}`))),remote.code==="auth")io.err(ui.errorHint(t(locale,"请先完成源登录或在 ~/.npmrc / ~/.bunfig.toml 配置同源访问 token, 或加 --force 直接委托包管理器安装","Sign in to your registry, configure a token in ~/.npmrc or ~/.bunfig.toml, or pass --force")));let manualCmd;if(origin.kind==="homebrew"&&targetPm===void 0)manualCmd=formatHomebrewUpgradeCommand(origin.formulaRef,!1);else if(targetPm!==void 0)manualCmd=formatUpgradeDisplayCommand(targetPm,meta.name,"latest",opts.registry);if(manualCmd!==void 0)io.err(ui.errorHint(t(locale,`可稍后重试或手动执行: ${manualCmd}`,`Retry later or run manually: ${manualCmd}`)));return 1}function handleVersionComparisonStop(input){let{binName,metaVersion,remote,cmp,force,isOriginTransition,io,color,ui,locale}=input;if(cmp===null&&!force)return io.out(ui.body(t(locale,`版本比较: 当前版本 (${sanitize(metaVersion)}) 与远端版本 (${sanitize(remote.version)}, 源: ${sanitize(remote.registry)}) 无法按标准 SemVer 比较, 未自动覆盖。`,`Version check: Current (${sanitize(metaVersion)}) and remote (${sanitize(remote.version)}, ${sanitize(remote.registry)}) cannot be compared as standard SemVer; skipped.`))),io.out(ui.hint(t(locale,`若确认需要安装远端版本, 请加 --force 重试 (例如: ${sanitize(binName)} update --force)`,`Pass --force to install anyway (e.g. ${sanitize(binName)} update --force)`))),0;if(cmp===1&&!force&&isOriginTransition)return io.out(ui.body(t(locale,`本地版本 (${formatVersionLabel(sanitize(metaVersion))}) 高于远端已发布版本 (${formatVersionLabel(sanitize(remote.version))}, 源: ${sanitize(remote.registry)}), 已跳过降级切换。`,`Local version (${formatVersionLabel(sanitize(metaVersion))}) is ahead of published (${formatVersionLabel(sanitize(remote.version))}, ${sanitize(remote.registry)}); downgrade skipped.`))),io.out(ui.hint(t(locale,`若确认降级切换至全局发布版, 请加 --force 重试 (例如: ${sanitize(binName)} update --force)`,`Pass --force to switch and downgrade anyway (e.g. ${sanitize(binName)} update --force)`))),0;if(cmp!==-1&&!force&&!(cmp===0&&isOriginTransition))return io.out(ui.success(t(locale,`已是最新版本: ${paintSgr(`v${sanitize(metaVersion)}`,"1",color.stdout)}`,`Already up to date: ${paintSgr(`v${sanitize(metaVersion)}`,"1",color.stdout)}`),t(locale,`(远端最新 v${sanitize(remote.version)}, 源: ${sanitize(remote.registry)})`,`(latest v${sanitize(remote.version)} · ${sanitize(remote.registry)})`))),0;return null}async function dispatchRemoteVersion(ctx){let{binName,meta,origin,targetPm,devLinks,remote,opts,io,color,ui,spinner,deps,locale}=ctx,isSourceSymlink=origin.kind==="source"&&(devLinks?.length??0)>0,isOriginTransition=isSourceSymlink||opts.pm!==void 0&&(origin.kind!=="global"||origin.pm!==opts.pm),cmp=compareSemver(meta.version,remote.version),stopCode=handleVersionComparisonStop({binName,metaVersion:meta.version,remote,cmp,force:opts.force,isOriginTransition,io,color,ui,locale});if(stopCode!==null)return stopCode;let hasUpdate=cmp===-1,allowSameVersionTransition=cmp===0&&isOriginTransition;if(hasUpdate)io.out(ui.foundUpdate(meta.version,remote.version,remote.registry));else if(allowSameVersionTransition){let localLabel=paintSgr(formatVersionLabel(sanitize(meta.version)),"1",color.stdout),remoteLabel=paintSgr(formatVersionLabel(sanitize(remote.version)),"1;36",color.stdout);io.out(ui.body(isSourceSymlink?t(locale,`当前为源码软链态 (${localLabel}), 远端最新为 ${remoteLabel} ${paintSgr(`(源: ${sanitize(remote.registry)})`,"2",color.stdout)}`,`Running from source symlink (${localLabel}); latest published is ${remoteLabel} ${paintSgr(`(${sanitize(remote.registry)})`,"2",color.stdout)}`):t(locale,`跨安装器迁移: 将通过 ${targetPm} 安装 ${remoteLabel} ${paintSgr(`(源: ${sanitize(remote.registry)})`,"2",color.stdout)}`,`Origin switch: Installing ${remoteLabel} via ${targetPm} ${paintSgr(`(${sanitize(remote.registry)})`,"2",color.stdout)}`)))}else io.out(ui.body(t(locale,`强制重装模式 (--force): 将重新安装 ${paintSgr(formatVersionLabel(sanitize(remote.version)),"1;36",color.stdout)} ${paintSgr(`(源: ${sanitize(remote.registry)})`,"2",color.stdout)}`,`Force mode (--force): Reinstalling ${paintSgr(formatVersionLabel(sanitize(remote.version)),"1;36",color.stdout)} ${paintSgr(`(${sanitize(remote.registry)})`,"2",color.stdout)}`)));if(opts.check)return emitCheckUpgradeHint({binName,metaName:meta.name,origin,targetPm,remoteVersion:remote.version,explicitRegistry:opts.registry,isSourceSymlink,isOriginTransition,needForce:!hasUpdate&&!allowSameVersionTransition&&opts.force||cmp===1&&opts.force,io,ui,locale});if(origin.kind==="standalone"&&targetPm===void 0)return await performStandaloneUpgrade({binName,meta,origin,targetVersion:remote.version,registry:remote.registry,opts,io,color,ui,spinner,deps,locale});if(origin.kind==="homebrew"&&targetPm===void 0)return await performHomebrewUpgrade({binName,meta,origin,targetVersion:remote.version,hasUpdate,opts,io,color,ui,spinner,deps,locale});if(targetPm===void 0)return io.err(ui.error(isSourceSymlink?t(locale,"未在 PATH 中检测到可用的全局包管理器 (bun / pnpm / npm / yarn v1 / volta), 已中止自动切换","No supported global package manager found in PATH (bun / pnpm / npm / yarn v1 / volta)"):t(locale,"未能自动确认安装本命令的包管理器, 为避免在 PATH 中装出重复版本已停止自动执行","Could not auto-detect the package manager that installed this CLI; aborted to avoid duplicate copies in PATH"))),io.err(ui.errorHint(t(locale,`请使用 --pm 显式指定你的包管理器后重试, 例如: ${sanitize(binName)} update --pm bun`,`Specify your package manager explicitly, e.g.: ${sanitize(binName)} update --pm bun`))),1;return await performUpgrade({binName,meta,origin,targetPm,targetSpec:remote.version,devLinks,opts,io,color,ui,spinner,deps,locale})}function createUpdateSpinner(options){let spinner=createTtySpinner(options);return{start(action,detail=""){spinner.start(action,detail)},update(action,detail=""){spinner.setText(action,detail)},stop(){spinner.stop()}}}import{existsSync as existsSync10,readFileSync as readFileSync9}from"node:fs";import{dirname as dirname4,join as join8}from"node:path";import{fileURLToPath}from"node:url";function readPackageMeta(entryMetaUrl,locale="zh"){let entryPath=fileURLToPath(entryMetaUrl),rawPackageRoot=dirname4(dirname4(entryPath)),packageRoot=safeRealpath(rawPackageRoot),pkgPath=join8(packageRoot,"package.json"),parsed=JSON.parse(readFileSync9(pkgPath,"utf8"));if(typeof parsed.name!=="string"||parsed.name==="")throw Error(t(locale,`无法从 ${pkgPath} 读取合法包名`,`Invalid package name in ${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 resolveUpdateLocale(options,flag){if(flag===void 0&&options.locale!==void 0)return options.locale;let deps=options.deps??{};return resolveCliLocale({toolName:options.toolName??options.binName,flag,platform:deps.platform,homedir:deps.homeDir,env:deps.env}).locale}function loadPackageMetaOrThrow(options,locale){if(options.meta!==void 0)return options.meta;if(options.entryMetaUrl!==void 0)return readPackageMeta(options.entryMetaUrl,locale);throw Error(t(locale,"缺少 entryMetaUrl 或 meta, 无法定位当前包信息","Missing entryMetaUrl or meta for package resolution"))}function resolveUpdateTargetState(input){let{meta,binName,explicitPm,deps}=input,origin=resolveOrigin(meta,deps),platform=deps.platform??process.platform,env=deps.env??process.env,entryArg=deps.argvEntry??(typeof env.CLIS_ENTRY_ARGV1==="string"&&env.CLIS_ENTRY_ARGV1!==""?env.CLIS_ENTRY_ARGV1:process.argv[1]),linkOps=createSourceLinkOps(platform,deps),globalRoots=deps.probeRoots!==void 0?deps.probeRoots():void 0,devLinks=origin.kind==="source"?findSourceDevSymlinks({binName,meta,argvEntry:entryArg,platform,env,homeDir:deps.homeDir,globalRoots,ops:linkOps}):[],shadowLinks=origin.kind==="global"||origin.kind==="homebrew"?findShadowSourceLinksInPath({binName,platform,env,ops:linkOps,pathExists:deps.pathExists??existsSync10}):[],isSourceSymlink=origin.kind==="source"&&devLinks.length>0,globalPm=origin.kind==="global"?origin.pm:void 0,detectedPm=globalPm??(isSourceSymlink?resolveDefaultPmForSource({devLinks,platform,env,homeDir:deps.homeDir,isFile:deps.isFile,probeYarn:deps.probeYarn,spawnFn:deps.spawnFn}):void 0);return{origin,devLinks,shadowLinks,isSourceSymlink,globalPm,targetPm:explicitPm??detectedPm}}function formatSelfUpdateJsonResult(exitCode,ctx){let latestVersion=ctx.latestRemote?.ok===!0?ctx.latestRemote.version:void 0,updateAvailable=latestVersion!==void 0?isNewerVersion(ctx.currentVersion,latestVersion):void 0,resolvedReg=ctx.latestRemote?.ok===!0?ctx.latestRemote.registry:ctx.registry,messages=ctx.capturedOut.map((l)=>l.trim()).filter((l)=>l!==""),errors=ctx.capturedErr.map((l)=>l.trim()).filter((l)=>l!==""),homebrewMeta=ctx.origin.kind==="homebrew"?{homebrewFormula:ctx.origin.formulaRef}:{};if(exitCode!==0)return{channel:"err",payload:JSON.stringify({ok:!1,error:{code:"UPDATE_FAILED",message:errors[0]??"Self-update failed"},checkOnly:ctx.checkOnly,packageName:ctx.packageName,currentVersion:ctx.currentVersion,origin:ctx.origin.kind,...homebrewMeta,packageManager:ctx.targetPm??null,registry:resolvedReg,messages,errors})};return{channel:"out",payload:JSON.stringify({ok:!0,checkOnly:ctx.checkOnly,packageName:ctx.packageName,currentVersion:ctx.currentVersion,...latestVersion!==void 0?{latestVersion}:{},...updateAvailable!==void 0?{updateAvailable}:{},origin:ctx.origin.kind,...homebrewMeta,packageManager:ctx.targetPm??null,isSourceSymlink:ctx.isSourceSymlink,registry:resolvedReg,messages},null,2)}}async function executeUpdateFlow(ctx){let{options,opts:parsed,meta,locale,ui,io,rawIo,color,spinner,jsonMode,capturedOut,capturedErr,deps}=ctx,opts=jsonMode?{...parsed.options,verbose:!1}:parsed.options;io.out(ui.header(options.binName));let{origin,devLinks,shadowLinks,isSourceSymlink,globalPm,targetPm}=resolveUpdateTargetState({meta,binName:options.binName,explicitPm:opts.pm,deps}),registry=resolveRegistry({packageName:meta.name,toolName:options.toolName??options.binName,flagRegistry:opts.registry,pm:targetPm,env:deps.env,homeDir:deps.homeDir,readText:deps.readText}),latestRemote,fetchVersion=async(reg)=>{let res=deps.fetchLatest!==void 0?await deps.fetchLatest(meta.name,reg):await fetchLatestVersion({packageName:meta.name,registry:reg,authToken:resolveRegistryAuthToken({packageName:meta.name,registry:reg,pm:targetPm,env:deps.env,homeDir:deps.homeDir,readText:deps.readText}),locale});return latestRemote=res,res},finalize=(exitCode)=>{if(!jsonMode)return exitCode;let formatted=formatSelfUpdateJsonResult(exitCode,{checkOnly:opts.check,packageName:meta.name,currentVersion:meta.version,origin,targetPm,isSourceSymlink,registry,latestRemote,capturedOut,capturedErr});if(formatted.channel==="err")rawIo.err(formatted.payload);else rawIo.out(formatted.payload);return exitCode},skipSourceUpgradeForPrivate=meta.isPrivate===!0&&opts.registry===void 0;if(opts.pm===void 0&&(origin.kind==="source"&&(!isSourceSymlink||skipSourceUpgradeForPrivate)||origin.kind==="ephemeral"||origin.kind==="local-project"))return finalize(await handleNonGlobalOrigin({meta,origin,hasExplicitRegistry:opts.registry!==void 0,io,ui,spinner,fetchVersion,registry,locale}));emitUpdateOriginHeader({meta,origin,devLinks,isSourceSymlink,isCheck:opts.check,globalPm,explicitPm:opts.pm,targetPm,io,ui,locale}),handleShadowSourceLinks({binName:options.binName,shadowLinks,checkOnly:opts.check,deps,io,ui,locale}),spinner.start(t(locale,"正在检查最新版本","Checking latest version"),extractRegistryHost(registry));let remote;try{remote=await fetchVersion(registry)}finally{spinner.stop()}if(!remote.ok)return finalize(await handleFetchFailure({binName:options.binName,meta,origin,targetPm,devLinks,registry,remote,opts,io,color,ui,spinner,deps,locale}));return finalize(await dispatchRemoteVersion({binName:options.binName,meta,origin,targetPm,devLinks,remote,opts,io,color,ui,spinner,deps,locale}))}async function runSelfUpdate(options){let usingDefaultIo=options.io===void 0,rawIo=options.io??{out:(line)=>process.stdout.write(`${line}
|
|
22
|
+
`),err:(line)=>process.stderr.write(`${line}
|
|
23
|
+
`)},baseLocale=resolveUpdateLocale(options),peeked=stripLangArgs(options.argv,{fallbackLocale:baseLocale,valueFlags:new Set(UPDATE_VALUE_FLAGS)}),preLocale=peeked.lang!==void 0?resolveUpdateLocale(options,peeked.lang):baseLocale,parsed=parseUpdateArgs(options.argv,preLocale,options.binName),jsonMode=options.json===!0||(parsed.ok?parsed.options.json===!0:parsed.json===!0),capturedOut=[],capturedErr=[],io=jsonMode?{out:(line)=>capturedOut.push(stripAnsi(line)),err:(line)=>capturedErr.push(stripAnsi(line))}:rawIo,deps=options.deps??{},color=jsonMode?{stdout:!1,stderr:!1}:options.color??(usingDefaultIo?detectColorChannels(deps.env):{stdout:!1,stderr:!1});if(!parsed.ok){let msg=t(preLocale,`参数错误: ${parsed.message}`,`Invalid argument: ${parsed.message}`);if(jsonMode)return rawIo.err(JSON.stringify({ok:!1,error:{code:"INVALID_ARGUMENT",message:sanitize(msg)}})),1;let errUi=createUpdateUi(color,preLocale);return io.err(errUi.error(msg)),1}let opts=jsonMode?{...parsed.options,verbose:!1}:parsed.options,locale=resolveUpdateLocale(options,opts.lang),ui=createUpdateUi(color,locale),meta;try{meta=loadPackageMetaOrThrow(options,locale)}catch(error){let msg=error instanceof Error?error.message:String(error),errMsg=t(locale,`读取当前包信息失败: ${sanitize(msg)}`,`Failed to read package metadata: ${sanitize(msg)}`);if(jsonMode)return rawIo.err(JSON.stringify({ok:!1,error:{code:"PACKAGE_META_FAILED",message:errMsg}})),1;return io.err(ui.error(errMsg)),1}if(opts.help){let helpStr=formatUpdateHelp(options.binName,meta.name,color.stdout,locale,options.docsUrl);if(jsonMode)return rawIo.out(JSON.stringify({ok:!0,help:helpStr},null,2)),0;for(let line of helpStr.split(`
|
|
24
|
+
`))io.out(line);return 0}let spinner=jsonMode?createUpdateSpinner({enabled:!1,color:!1}):deps.spinner??createUpdateSpinner({enabled:usingDefaultIo&&stderrSupportsSpinner(deps.env),color:color.stderr});return executeUpdateFlow({options,opts:parsed,meta,locale,ui,io,rawIo,color,spinner,jsonMode,capturedOut,capturedErr,deps})}var UNINSTALL_VALUE_FLAGS=["--pm","--lang"],PM_SET2=new Set(SUPPORTED_PACKAGE_MANAGERS);function isPackageManager2(value){return PM_SET2.has(value)}function nextValueToken2(argv,index){let next=argv[index+1];if(next===void 0||next===""||next.startsWith("-"))return null;return next}function hasJsonFlagBeforeDashDash(argv){let expectValue=!1;for(let i=0;i<argv.length;i+=1){let arg=argv[i];if(expectValue){if(expectValue=!1,arg==="--json")return!0;if(arg==="--"||!arg.startsWith("-"))continue}if(arg==="--")break;if(arg==="--json")return!0;if(arg==="--pm"||arg==="--lang")expectValue=!0}return!1}function applyPm2(options,value,locale){let normalized=value.trim().toLowerCase(),list=SUPPORTED_PACKAGE_MANAGERS.join(" | ");if(!isPackageManager2(normalized))return t(locale,`参数 --pm 不支持 "${value}" (可选值: ${list})`,`Invalid --pm value "${value}" (expected: ${list})`);return options.pm=normalized,null}function applyLang2(options,value,locale){let parsed=parseLangPreference(value);if(parsed===null)return t(locale,`参数 --lang 不支持 "${value}" (可选值: system | en | zh)`,`Invalid --lang value "${value}" (expected: system | en | zh)`);return options.lang=parsed,null}function parseUninstallArgs(argv,locale="zh",config={}){let options={yes:!1,dryRun:!1,keepConfig:!1,keptFlags:[],verbose:!1,json:!1,help:!1},customFlagMap=new Map;for(let spec of config.keepFlags??[])customFlagMap.set(spec.flag,spec.key);let wantJson=hasJsonFlagBeforeDashDash(argv),pmList=SUPPORTED_PACKAGE_MANAGERS.join(" | "),helpCmd=config.binName!==void 0&&config.binName.trim()!==""?`${sanitizeText(config.binName)} uninstall --help`:"uninstall --help",preLang=stripLangArgs(argv,{fallbackLocale:locale,valueFlags:new Set(UNINSTALL_VALUE_FLAGS)}).lang,activeLocale=preLang==="en"||preLang==="zh"?preLang:locale,usageError=(message)=>({ok:!1,json:wantJson,message:`${message} ${t(activeLocale,`(用 ${helpCmd} 查看用法)`,`(run '${helpCmd}' for usage)`)}`}),afterDashDash=!1;for(let i=0;i<argv.length;i+=1){let arg=argv[i];if(!afterDashDash&&arg==="--"){afterDashDash=!0;continue}if(afterDashDash||!arg.startsWith("-"))return usageError(t(activeLocale,`多余的参数: ${arg}`,`Unexpected argument: ${arg}`));if(arg==="--help"||arg==="-h"){options.help=!0;continue}if(arg==="--yes"||arg==="-y"){options.yes=!0;continue}if(arg==="--dry-run"){options.dryRun=!0;continue}if(arg==="--keep-config"){options.keepConfig=!0;continue}let customKey=customFlagMap.get(arg);if(customKey!==void 0){if(!options.keptFlags.includes(customKey))options.keptFlags.push(customKey);continue}if(arg==="--verbose"){options.verbose=!0;continue}if(arg==="--json"){options.json=!0;continue}if(arg==="--pm"||arg.startsWith("--pm=")){let val=arg==="--pm"?nextValueToken2(argv,i):arg.slice(5);if(val===null||val==="")return usageError(t(activeLocale,`参数 --pm 缺少取值 (可选值: ${pmList})`,`Option --pm requires a value (expected: ${pmList})`));let err=applyPm2(options,val,activeLocale);if(err!==null)return usageError(err);if(arg==="--pm")i+=1;continue}if(arg==="--lang"||arg.startsWith("--lang=")){let val=arg==="--lang"?nextValueToken2(argv,i):arg.slice(7);if(val===null||val==="")return usageError(t(activeLocale,"参数 --lang 缺少取值 (可选值: system | en | zh)","Option --lang requires a value (expected: system | en | zh)"));let err=applyLang2(options,val,activeLocale);if(err!==null)return usageError(err);if(arg==="--lang")i+=1;continue}return usageError(t(activeLocale,`子命令 uninstall 不支持参数: ${arg}`,`Unknown option for 'uninstall': ${arg}`))}return{ok:!0,options}}function formatUninstallHelp(binName,packageName,color=!1,locale="zh",helpOpts={}){let safeBin=sanitizeText(binName),safePkg=sanitizeText(packageName),{badge:makeBadge,bold,dim,section,token}=createHelpStyles(color),badge=makeBadge(`${HELP_BAR_BLOCK} ${safeBin.toUpperCase()} UNINSTALL `),pmList=SUPPORTED_PACKAGE_MANAGERS.join(" | "),zh=locale!=="en",extraOptionRows=(helpOpts.keepFlags??[]).map((spec)=>[spec.flag,void 0,zh?spec.descZh:spec.descEn]),options=zh?[["--dry-run",void 0,"仅预览将清理的本体、配置与命令, 不执行卸载"],["-y, --yes",void 0,"跳过交互确认 (非 TTY 与 --json 必传)"],["--keep-config",void 0,"保留配置目录 (~/.config/<工具>), 适合重装"],...extraOptionRows,["--pm","<管理器>",`指定全局包管理器 (${pmList})`],["--verbose",void 0,"实时显示包管理器原始输出 (默认静默接管)"],["--json",void 0,"以 JSON 格式输出卸载预览或执行结果"],["--lang","<语言>","临时指定本次显示语言 (system | en | zh)"]]:[["--dry-run",void 0,"Preview uninstall actions without modifying disk"],["-y, --yes",void 0,"Skip confirmation (required in non-TTY / --json)"],["--keep-config",void 0,"Keep user config directory for reinstall"],...extraOptionRows,["--pm","<manager>",`Global package manager (${pmList})`],["--verbose",void 0,"Stream raw package manager output (default quiet)"],["--json",void 0,"Emit uninstall plan or result as JSON"],["--lang","<lang>","Display language for this run (system | en | zh)"]],metaOptions=[["-h, --help",void 0,zh?"显示本帮助":"Show this help message"]],defaultCleanDesc=zh?helpOpts.defaultSummaryZh??"默认卸载本体并清理工具配置目录 (一键脚本末项回收 runtime)":helpOpts.defaultSummaryEn??"Removes CLI, tool config dir, and unused script runtime",notes=zh?[["彻底清理",defaultCleanDesc],["安全护栏","交互先预览再确认; 非 TTY / --json 缺 --yes 拒绝执行"],["来源边界","源码检出、npx/bunx 与本地项目依赖拒绝自卸载"]]:[["Default",defaultCleanDesc],["Safety","Confirms in TTY; non-TTY / --json requires --yes"],["Guard","Refuses source checkouts, npx/bunx, and local deps"]],descCol=computeHelpDescColumn([...options.map(([f,a])=>a===void 0?f:`${f} ${a}`),...metaOptions.map(([f,a])=>a===void 0?f:`${f} ${a}`),...notes.map(([k])=>k)]),optLine=([f,a,d])=>{let plain=a===void 0?f:`${f} ${a}`,styled=a===void 0?token(f):`${token(f)} ${dim(a)}`;return alignHelpRow(styled,plain,dim(d),descCol)},exitAndDocs=formatExitAndDocsSection({locale:zh?"zh":"en",color,descCol,exitZeroDesc:zh?"成功 (含 --dry-run、取消与 -h/--help)":"Success (including --dry-run, cancel, --help)",exitOneDesc:zh?"失败 (参数非法、缺 --yes、受拒来源或卸载出错)":"Error (bad args, missing --yes, or uninstall error)",docsUrl:helpOpts.docsUrl!==void 0?sanitizeText(helpOpts.docsUrl):void 0}),badgePlain=`${HELP_BAR_BLOCK} ${safeBin.toUpperCase()} UNINSTALL `,titleLabel=zh?"彻底卸载工具":"Self-Uninstall",headerSingle=` ${badgePlain} ${titleLabel} (${safePkg})`;return["",...displayWidth(headerSingle)<=80?[` ${badge} ${bold(titleLabel)} ${dim(`(${safePkg})`)}`]:[` ${badge} ${bold(titleLabel)}`,` ${dim(`(${safePkg})`)}`],` ${dim(zh?"自动识别安装源 (脚本 / Homebrew / bun / npm / pnpm / yarn / volta) 并卸载。":"Detects install origin (script / Homebrew / bun / npm / pnpm / yarn / volta).")}`,` ${dim(HELP_RULE)}`,"",` ${section(zh?"用法":"Usage")}`,` ${bold(`${safeBin} uninstall`)} ${dim(zh?"[选项]":"[options]")}`,"",` ${section(zh?"选项":"Options")}`,...options.map(optLine),"",...metaOptions.map(optLine),"",` ${section(zh?"说明":"Notes")}`,...notes.map(([k,d])=>alignHelpRow(bold(k),k,dim(d),descCol)),"",...exitAndDocs].join(`
|
|
25
|
+
`)}import{existsSync as existsSync11,lstatSync as lstatSync4,readdirSync,rmSync as rmSync5,rmdirSync as rmdirSync2}from"node:fs";import{homedir as osHomedir2,userInfo as userInfo2}from"node:os";function hasControlChar(raw){for(let i=0;i<raw.length;i+=1){let code=raw.charCodeAt(i);if(code<=31||code===127)return!0}return!1}function findAllEnvEntries(env,key,caseInsensitive){let out=[];if(!caseInsensitive){if(Object.prototype.hasOwnProperty.call(env,key)&&env[key]!==void 0)out.push(env[key]);return out}let lower=key.toLowerCase();for(let[k,v]of Object.entries(env))if(k.toLowerCase()===lower&&v!==void 0)out.push(v);return out}function isValidTargetHome(raw,platform){if(raw===""||raw!==raw.trim()||hasControlChar(raw))return!1;if(!isAbsoluteAnyFlavor(raw))return!1;return platform==="win32"?/^[A-Za-z]:[/\\]/.test(raw):raw.startsWith("/")}function safePasswdHome(){try{return userInfo2().homedir}catch{return""}}function safeOsHome(){try{return osHomedir2()}catch{return""}}function appendUniqueValid(list,raw,platform){if(raw!==""&&isValidTargetHome(raw,platform)&&!list.includes(raw))list.push(raw)}function resolveUninstallHomeGuard(options){let platform=options.platform??process.platform,homeDirs=[],invalidExplicitHome=!1;if(options.homeDir!==void 0){if(!isValidTargetHome(options.homeDir,platform))return{homeDirs:[],invalidExplicitHome:!0};if(homeDirs.push(options.homeDir),platform===process.platform)appendUniqueValid(homeDirs,safePasswdHome(),platform);return{homeDirs,invalidExplicitHome:!1}}let env=options.env??(platform===process.platform?process.env:{});if(platform==="win32"){let profiles=findAllEnvEntries(env,"USERPROFILE",!0),drives=findAllEnvEntries(env,"HOMEDRIVE",!0),hpaths=findAllEnvEntries(env,"HOMEPATH",!0);if(profiles.length>0){for(let val of profiles)if(isValidTargetHome(val,"win32"))appendUniqueValid(homeDirs,val,"win32");else invalidExplicitHome=!0;if(drives.length>0&&hpaths.length>0)appendUniqueValid(homeDirs,`${drives[0]}${hpaths[0]}`,"win32")}else if(drives.length>0||hpaths.length>0)if(drives.length!==1||hpaths.length!==1)invalidExplicitHome=!0;else{let combined=`${drives[0]}${hpaths[0]}`;if(isValidTargetHome(combined,"win32"))appendUniqueValid(homeDirs,combined,"win32");else invalidExplicitHome=!0}}else{let homes=findAllEnvEntries(env,"HOME",!1);for(let val of homes)if(isValidTargetHome(val,platform))appendUniqueValid(homeDirs,val,platform);else invalidExplicitHome=!0}if(platform===process.platform)appendUniqueValid(homeDirs,safePasswdHome(),platform),appendUniqueValid(homeDirs,safeOsHome(),platform);return{homeDirs,invalidExplicitHome}}function hasRemainingAppsInDir(entries,ignored,isWin){if(entries===null)return!0;for(let entry of entries){if(entry.startsWith("."))continue;let key=isWin?entry.toLowerCase():entry;if(!ignored.has(key))return!0}return!1}import{posix as posix10,win32 as win3211}from"node:path";var SAFE_FORMULA_REF_RE2=/^(?:[a-z0-9][a-z0-9._-]{0,63}\/[a-z0-9][a-z0-9._-]{0,63}\/)?[a-z0-9][a-z0-9@._+-]{0,127}$/i;function resolveToolConfigDir(options){let platform=options.platform??process.platform,langPath=resolveLangConfigPath({toolName:options.toolName,platform,homedir:options.homeDir,env:options.env});if(langPath==="")return"";return platform==="win32"?win3211.dirname(langPath):posix10.dirname(langPath)}function isSafeRemovableConfigDir(configDir,toolName,homeDir){if(/[\0\r\n]/.test(configDir))return!1;let trimmed=configDir.trim();if(trimmed===""||configDir!==trimmed)return!1;if(!isAbsoluteAnyFlavor(trimmed))return!1;let norm=normalizeCanonicalPath(trimmed);if(norm===""||norm==="/"||/^[A-Za-z]:$/i.test(norm))return!1;let lowerNorm=norm.toLowerCase();if(/^\/(?:users|home)\/[^/]+$/.test(lowerNorm)||/^[a-z]:\/users\/[^/]+$/.test(lowerNorm))return!1;let slash=norm.lastIndexOf("/"),parentDir=slash<=0?"/":norm.slice(0,slash),lowerParent=parentDir.toLowerCase();if(homeDir!==void 0&&homeDir.trim()!==""){let normHome=normalizeCanonicalPath(homeDir.trim()).toLowerCase();if(lowerNorm===normHome||lowerParent===normHome||normHome.startsWith(`${lowerNorm}/`))return!1}if(isReservedSystemParentDir(parentDir))return!1;let base=slash>=0?norm.slice(slash+1):"",expected=toolName.trim();return isWinStylePath(trimmed)?base.toLowerCase()===expected.toLowerCase():base===expected}function resolveToolConfigPreview(options){let configDir=resolveToolConfigDir(options);if(configDir==="")return{configDir,configExists:!1};let homeGuard=resolveUninstallHomeGuard({homeDir:options.homeDir,env:options.env,platform:options.platform});if(homeGuard.invalidExplicitHome)return{configDir,configExists:!1};let symlinkSafe=!0;try{assertPathsNoSymlinkAncestors([configDir],options.isSymlink,options.platform)}catch{symlinkSafe=!1}let homeSafe=isSafeRemovableConfigDir(configDir,options.toolName)&&homeGuard.homeDirs.every((h)=>isSafeRemovableConfigDir(configDir,options.toolName,h)&&!isRealPathHomeOrDirectChild(configDir,h,options.platform)),configExists=symlinkSafe&&homeSafe&&options.pathExists(configDir);return{configDir,configExists}}function formatPmUninstallCommand(pm,packageName){switch(pm){case"bun":return`bun remove -g ${packageName}`;case"npm":return`npm uninstall -g ${packageName}`;case"pnpm":return`pnpm remove -g ${packageName}`;case"yarn":return`yarn global remove ${packageName}`;case"volta":return`volta uninstall ${packageName}`}}function buildPmUninstallArgs(pm,packageName){switch(pm){case"bun":return["remove","-g",packageName];case"npm":return["uninstall","-g",packageName];case"pnpm":return["remove","-g",packageName];case"yarn":return["global","remove",packageName];case"volta":return["uninstall",packageName]}}function buildPmUninstallPlan(input){let locale=input.locale??"zh";if(!isValidPackageName(input.packageName))return{ok:!1,reason:t(locale,`非法包名: ${input.packageName}`,`Invalid package name: ${input.packageName}`)};let platform=input.platform??process.platform,env=input.env??process.env,isFile=input.isFile??defaultIsExecutable,displayCommand=formatPmUninstallCommand(input.pm,input.packageName);if(input.pm==="yarn"&&isYarnBerryVersion(input.yarnVersion??null))return{ok:!1,reason:t(locale,`当前环境的 Yarn (${input.yarnVersion?.trim()}) 为 v2+ (Berry), 官方已移除 yarn global remove 命令, 请改用 --pm bun / --pm npm / --pm pnpm`,`Yarn (${input.yarnVersion?.trim()}) is v2+ (Berry), which removed 'yarn global remove'; rerun with --pm bun, --pm npm, or --pm pnpm`)};let pmArgs=buildPmUninstallArgs(input.pm,input.packageName),invocation=resolvePmInvocation(input.pm,pmArgs,platform,env,isFile);if(invocation===null)return{ok:!1,reason:t(locale,`当前 PATH 中未找到 ${input.pm} 可执行文件, 无法自动执行卸载`,`${input.pm} executable was not found in PATH`),fallbackCommand:displayCommand};return{ok:!0,plan:{command:invocation.command,args:invocation.args,displayCommand,...invocation.windowsVerbatimArguments===!0?{windowsVerbatimArguments:!0}:{}}}}function buildHomebrewUninstallPlan(input){let locale=input.locale??"zh",{formulaRef,prefix}=input.origin;if(formulaRef===""||formulaRef.includes("..")||!SAFE_FORMULA_REF_RE2.test(formulaRef))return{ok:!1,reason:t(locale,`非法 Homebrew Formula 名称: ${formulaRef}`,`Invalid Homebrew formula reference: ${formulaRef}`)};let platform=input.platform??process.platform,env=input.env??process.env,isFile=input.isFile??defaultIsExecutable,displayCommand=`brew uninstall ${formulaRef}`,prefixBrew=isSafeHomebrewPrefix(prefix)?joinForPath(prefix,"bin","brew"):"",brewCommand=prefixBrew!==""&&isFile(prefixBrew)?prefixBrew:null;if(brewCommand===null){let found=resolveExecutableInPath("brew",platform,env,isFile);brewCommand=found!==null?found.path:null}if(brewCommand===null)return{ok:!1,reason:t(locale,"当前环境未找到 brew 可执行文件, 无法自动执行 Homebrew 卸载","brew executable was not found in PATH or Homebrew prefix"),fallbackCommand:displayCommand};return{ok:!0,plan:{command:brewCommand,args:["uninstall",formulaRef],displayCommand}}}function dirnameForPath(rawPath){return/^(?:[A-Za-z]:[/\\]|\\\\)/.test(rawPath)?win3211.dirname(rawPath):posix10.dirname(rawPath)}function basenameForPath(rawPath){return/^(?:[A-Za-z]:[/\\]|\\\\)/.test(rawPath)?win3211.basename(rawPath):posix10.basename(rawPath)}function computeStandaloneCleanupTargets(origin,listDir,pathExists){let isWin=isWinStylePath(origin.dataDir),binDir=dirnameForPath(origin.binPath),appsDir=dirnameForPath(origin.appDir),rawSelf=basenameForPath(origin.appDir),selfName=isWin?rawSelf.toLowerCase():rawSelf,normApps=normalizeComparablePath(appsDir),normData=normalizeComparablePath(origin.dataDir),hasOtherApps=!1;if(isWithinDir(appsDir,origin.dataDir)){let entries=listDir(appsDir);if(entries===null)hasOtherApps=!0;else if(normApps===normData){if(hasOtherApps=hasRemainingAppsInDir(entries,new Set([selfName,"runtime","bin","apps"]),isWin),!hasOtherApps){if(entries.some((e)=>(isWin?e.toLowerCase():e)==="apps")){let nested=listDir(joinForPath(origin.dataDir,"apps"));hasOtherApps=hasRemainingAppsInDir(nested,new Set,isWin)}}}else if(hasOtherApps=hasRemainingAppsInDir(entries,new Set([selfName]),isWin),!hasOtherApps){let rootEntries=listDir(origin.dataDir),rootIgnored=rootEntries!==null&&rootEntries.some((e)=>(isWin?e.toLowerCase():e)==="apps")?new Set(["apps","runtime","bin"]):new Set([selfName,"apps","runtime","bin"]);hasOtherApps=hasRemainingAppsInDir(rootEntries,rootIgnored,isWin)}}let willRemoveRuntime=!hasOtherApps&&isWithinDir(origin.runtimeDir,origin.dataDir)&&normalizeComparablePath(origin.runtimeDir)!==normData&&pathExists(origin.runtimeDir);return{binPath:origin.binPath,binDir,appDir:origin.appDir,appsDir,runtimeDir:origin.runtimeDir,dataDir:origin.dataDir,willRemoveRuntime,hasOtherApps}}function findRemainingBinsInPath(input){let platform=input.platform??process.platform,env=input.env??process.env,isFile=input.isFile??defaultIsExecutable,dirs=parseAbsolutePathDirs(env,platform),candidates=platform==="win32"?[`${input.binName}.cmd`,`${input.binName}.exe`,`${input.binName}.ps1`,input.binName]:[input.binName],seen=new Set,found=[];for(let dir of dirs){if(isLocalNodeModulesBinDir(dir))continue;for(let name of candidates){let full=joinForPath(dir,name),key=platform==="win32"?full.toLowerCase():full;if(seen.has(key))continue;if(isFile(full)){seen.add(key),found.push(full);break}}}return found}async function collectUninstallHookInfo(hooks,ctx){let extraItems=[],warnings=[];if(hooks?.inspect!==void 0)try{extraItems=await hooks.inspect({keptFlags:new Set(ctx.keptFlags),keepConfig:ctx.keepConfig,locale:ctx.locale})}catch(error){extraItems=[];let detail=error instanceof Error?error.message:String(error);warnings.push(t(ctx.locale,`工具专属清理项探测失败 (${detail}), 继续卸载仍可能触发附加清理钩子`,`Failed to inspect tool-specific cleanup hooks (${detail}); continuing may still run cleanup hooks`))}let externalNote=null;try{externalNote=hooks?.externalConfigNote?.({configDir:ctx.configDir,locale:ctx.locale})??null}catch{externalNote=null}return{extraItems,externalNote,warnings}}import{spawnSync as spawnSync4}from"node:child_process";import{realpathSync as realpathSync4}from"node:fs";import{win32 as win3212}from"node:path";var SAFE_EXE_PATH_RE=/^[^\0\r\n"&|<>%^!]+$/,WIN32_DELAYED_CLEANUP_SCRIPT=["$ErrorActionPreference = 'SilentlyContinue'","$p = [int]$env:CLIS_CLEANUP_PID","$bp = $env:CLIS_CLEANUP_BIN_PATH","$bd = $env:CLIS_CLEANUP_BIN_DIR","$rt = $env:CLIS_CLEANUP_RUNTIME_DIR","$dd = $env:CLIS_CLEANUP_DATA_DIR","if ($p -gt 0) { Wait-Process -Id $p -Timeout 15 }","if ($bp) { Start-Sleep -Milliseconds 150 }","foreach ($guardRoot in @($dd, $bp)) {"," if (-not $guardRoot) { continue }"," $cur = $guardRoot"," while ($cur) {"," $ci = $null"," try {"," $ci = Get-Item -LiteralPath $cur -Force -ErrorAction Stop"," } catch [System.Management.Automation.ItemNotFoundException] {"," $ci = $null"," } catch {"," exit 0"," }"," if ($null -ne $ci -and ($ci.Attributes -band [IO.FileAttributes]::ReparsePoint)) { exit 0 }"," $parent = Split-Path -Path $cur -Parent"," if (-not $parent -or $parent -eq $cur) { break }"," $cur = $parent"," }","}","for ($i = 0; $i -lt 20; $i++) {"," $pending = $false"," if ($bp -and (Test-Path -LiteralPath $bp -PathType Leaf)) {"," $bi = $null"," try { $bi = Get-Item -LiteralPath $bp -Force -ErrorAction Stop } catch { $bi = $null }"," if ($null -ne $bi -and -not ($bi.Attributes -band [IO.FileAttributes]::ReparsePoint)) {"," Remove-Item -LiteralPath $bp -Force"," if (Test-Path -LiteralPath $bp) { $pending = $true }"," }"," }"," if ($bd -and (Test-Path -LiteralPath $bd -PathType Container)) {"," $bdi = $null"," try { $bdi = Get-Item -LiteralPath $bd -Force -ErrorAction Stop } catch { $bdi = $null }"," if ($null -ne $bdi -and -not ($bdi.Attributes -band [IO.FileAttributes]::ReparsePoint)) {"," if (@(Get-ChildItem -LiteralPath $bd -Force).Count -eq 0) {"," Remove-Item -LiteralPath $bd -Force"," }"," }"," }"," if ($rt -and (Test-Path -LiteralPath $rt)) {"," $ri = $null"," try { $ri = Get-Item -LiteralPath $rt -Force -ErrorAction Stop } catch { $ri = $null }"," $hasReparse = ($null -eq $ri) -or [bool]($ri.Attributes -band [IO.FileAttributes]::ReparsePoint)"," if (-not $hasReparse) {"," $q = New-Object 'System.Collections.Generic.Queue[string]'"," $q.Enqueue($rt)"," while ($q.Count -gt 0 -and -not $hasReparse) {"," $curDir = $q.Dequeue()"," try {"," $children = @(Get-ChildItem -LiteralPath $curDir -Force -ErrorAction Stop)"," } catch {"," $hasReparse = $true"," break"," }"," foreach ($ent in $children) {"," if ($ent.Attributes -band [IO.FileAttributes]::ReparsePoint) {"," $hasReparse = $true"," break"," }"," if ($ent.PSIsContainer) { $q.Enqueue($ent.FullName) }"," }"," }"," }"," if (-not $hasReparse) {"," Remove-Item -LiteralPath $rt -Recurse -Force"," if (Test-Path -LiteralPath $rt) { $pending = $true }"," }"," }"," if (-not $pending) { break }"," Start-Sleep -Milliseconds 250","}","if ($dd -and (Test-Path -LiteralPath $dd -PathType Container)) {"," $di = $null"," try { $di = Get-Item -LiteralPath $dd -Force -ErrorAction Stop } catch { $di = $null }"," if ($null -ne $di -and -not ($di.Attributes -band [IO.FileAttributes]::ReparsePoint)) {"," if (@(Get-ChildItem -LiteralPath $dd -Force).Count -eq 0) {"," Remove-Item -LiteralPath $dd -Force"," }"," }","}"].join(`
|
|
26
|
+
`),WIN32_DELAYED_CLEANUP_ENCODED=Buffer.from(WIN32_DELAYED_CLEANUP_SCRIPT,"utf16le").toString("base64"),WIN32_RESERVED_DATA_ROOT_RE2=/^[a-z]:(?:$|\/(?:windows|program files(?: \(x86\))?|programdata)(?:\/|$)|\/users(?:\/[^/]+)?$)/,WIN32_RESERVED_BIN_DIR_RE2=/^[a-z]:(?:$|\/(?:windows|program files(?: \(x86\))?|programdata)(?:\/|$)|\/users$)/,WIN32_DRIVE_ABS_RE2=/^[A-Za-z]:[/\\]/,WIN32_EXTENDED_OR_UNC_RE=/^(?:\\\\[?.]\\|\\\\|\/\/)/;function canonicalWinPath(p){try{let resolved=(realpathSync4.native??realpathSync4)(p),stripped=stripWinExtendedPrefix(resolved);return normalizeSlashes(stripped).replace(/\/+/g,"/").replace(/\/+$/,"").toLowerCase()}catch{return normalizeSlashes(p).replace(/\/+/g,"/").replace(/\/+$/,"").toLowerCase()}}function hasUnsafeWin32PathForm(raw){if(raw.trim()===""||/[\0\r\n]/.test(raw))return!0;if(WIN32_EXTENDED_OR_UNC_RE.test(raw))return!0;if(!WIN32_DRIVE_ABS_RE2.test(raw))return!0;let slashNorm=normalizeSlashes(raw);if(/\/{2,}/.test(slashNorm))return!0;let segs=slashNorm.replace(/\/+$/,"").split("/");if(segs.includes("..")||segs.includes("."))return!0;if(segs.slice(1).some((seg)=>/[.\s]+$/.test(seg)))return!0;let firstSeg=segs[1]??"";if(/~\d+(?:\.[^/\\]+)?$/.test(firstSeg))return!0;return!1}function isSafeScheduledDataDir(dataDir){if(hasUnsafeWin32PathForm(dataDir))return!1;let normDd=normalizeSlashes(dataDir).replace(/\/+$/,"").toLowerCase();if(normDd===""||normDd==="/"||WIN32_RESERVED_DATA_ROOT_RE2.test(normDd))return!1;let canonDd=canonicalWinPath(dataDir);if(canonDd===""||canonDd==="/"||WIN32_RESERVED_DATA_ROOT_RE2.test(canonDd))return!1;return!0}function isSafeScheduledRuntimeDir(runtimeDir,dataDir){if(!isSafeScheduledDataDir(dataDir)||hasUnsafeWin32PathForm(runtimeDir))return!1;let normRt=normalizeSlashes(runtimeDir).replace(/\/+$/,"").toLowerCase(),normDd=normalizeSlashes(dataDir).replace(/\/+$/,"").toLowerCase(),canonRt=canonicalWinPath(runtimeDir);if(WIN32_RESERVED_DATA_ROOT_RE2.test(canonRt))return!1;return normRt!==normDd&&isWithinDir(runtimeDir,dataDir)&&normRt===`${normDd}/runtime`}function isSafeScheduledBinPath(binPath){if(hasUnsafeWin32PathForm(binPath))return!1;let norm=normalizeSlashes(binPath).replace(/\/+$/,"").toLowerCase(),slash=norm.lastIndexOf("/"),parentDir=slash<=0?norm:norm.slice(0,slash);if(WIN32_RESERVED_BIN_DIR_RE2.test(norm)||WIN32_RESERVED_BIN_DIR_RE2.test(parentDir))return!1;let canon=canonicalWinPath(binPath),canonSlash=canon.lastIndexOf("/"),canonParent=canonSlash<=0?canon:canon.slice(0,canonSlash);if(WIN32_RESERVED_BIN_DIR_RE2.test(canon)||WIN32_RESERVED_BIN_DIR_RE2.test(canonParent))return!1;return/\.(?:cmd|bat)$/i.test(norm)}function isRunningWindowsBatchShim(binPath,env,realpathFn){if(!isSafeScheduledBinPath(binPath))return!1;let entryArgv1=(env.CLIS_ENTRY_ARGV1??"").trim();if(entryArgv1==="")return!1;if(normalizeSlashes(entryArgv1).toLowerCase()===normalizeSlashes(binPath).toLowerCase())return!0;let canon=(p)=>{if(realpathFn!==void 0){let hit=realpathFn(p);return normalizeSlashes(hit??p).toLowerCase()}return canonicalWinPath(p)};return canon(entryArgv1)===canon(binPath)}function scheduleWindowsDelayedRuntimeCleanup(input){let safeDataDir=isSafeScheduledDataDir(input.dataDir)?input.dataDir:"",safeRuntimeDir="";if(input.runtimeDir!==void 0&&input.runtimeDir!==""){if(!isSafeScheduledRuntimeDir(input.runtimeDir,input.dataDir))return!1;safeRuntimeDir=input.runtimeDir}let safeBinPath="";if(input.binPath!==void 0&&input.binPath!==""){if(!isSafeScheduledBinPath(input.binPath))return!1;safeBinPath=input.binPath}if(safeRuntimeDir===""&&safeBinPath==="")return!1;let safeBinDir="";if(safeBinPath!==""&&safeDataDir!==""&&input.binDir!==void 0&&!hasUnsafeWin32PathForm(input.binDir)&&isWithinDir(input.binDir,safeDataDir)&&normalizeSlashes(input.binDir).replace(/\/+$/,"").toLowerCase()!==normalizeSlashes(safeDataDir).replace(/\/+$/,"").toLowerCase())safeBinDir=input.binDir;let hasUnsafeCmdPath=(p)=>/[\r\n\0"]/.test(p)||p.split(/[/\\]/).includes(".."),WIN32_CMD_EXE_RE=/^[A-Za-z]:[/\\].*[/\\]cmd\.exe$/i,sysRootCandidates=[input.env.SystemRoot,input.env.SYSTEMROOT,input.env.WINDIR,input.env.windir],sysRoot="C:\\Windows";for(let raw of sysRootCandidates){let trimmed=raw?.trim()??"";if(WIN32_DRIVE_ABS_RE2.test(trimmed)&&!hasUnsafeCmdPath(trimmed)){sysRoot=trimmed;break}}let cmdCandidate=win3212.join(sysRoot,"System32","cmd.exe"),rawComspec=input.env.ComSpec?.trim()||input.env.COMSPEC?.trim()||"",comspec="";if(input.pathExists(cmdCandidate))comspec=cmdCandidate;else if(WIN32_CMD_EXE_RE.test(rawComspec)&&!hasUnsafeCmdPath(rawComspec)&&input.pathExists(rawComspec))comspec=rawComspec;if(comspec==="")return!1;let psCandidate=win3212.join(sysRoot,"System32","WindowsPowerShell","v1.0","powershell.exe");if(!input.pathExists(psCandidate)||!SAFE_EXE_PATH_RE.test(psCandidate))return!1;let cmdLine=`"start "" /b "${psCandidate}" -NoProfile -NonInteractive -WindowStyle Hidden -EncodedCommand ${WIN32_DELAYED_CLEANUP_ENCODED}"`;try{let res=spawnSync4(comspec,["/d","/s","/c",cmdLine],{stdio:"ignore",windowsHide:!0,windowsVerbatimArguments:!0,timeout:5000,env:{...input.env,CLIS_CLEANUP_PID:String(input.pid),CLIS_CLEANUP_BIN_PATH:safeBinPath,CLIS_CLEANUP_BIN_DIR:safeBinDir,CLIS_CLEANUP_RUNTIME_DIR:safeRuntimeDir,CLIS_CLEANUP_DATA_DIR:safeDataDir}});return res.error===void 0&&res.status===0}catch{return!1}}function createDefaultUninstallFsOps(overrides){return{pathExists:overrides?.pathExists??existsSync11,isSymlink:overrides?.isSymlink??((path)=>{try{return lstatSync4(path).isSymbolicLink()}catch(err){let code=err.code;if(code==="ENOENT"||code==="ENOTDIR")return!1;throw err}}),listDir:overrides?.listDir??((dir)=>{try{return readdirSync(dir)}catch{return null}}),rmFile:overrides?.rmFile??((path)=>{rmSync5(path,{force:!0})}),rmDirRecursive:overrides?.rmDirRecursive??((path)=>{rmSync5(path,{recursive:!0,force:!0})}),rmEmptyDir:overrides?.rmEmptyDir??((path)=>{try{rmdirSync2(path)}catch{}})}}function defaultPromptUninstallConfirm(question){return promptConfirmOnce(question)}var RETRYABLE_FS_CODES=new Set(["EBUSY","EPERM","EACCES","ENOTEMPTY"]);function extractErrnoCode(err){return typeof err==="object"&&err!==null&&"code"in err?String(err.code):""}function executeStandaloneUninstall(origin,fsOps,locale,runtimeCtx){let hostPlatform=runtimeCtx?.platform??process.platform,hostEnv=runtimeCtx?.env??process.env,homeGuard=resolveUninstallHomeGuard({homeDir:runtimeCtx?.homeDir,env:hostEnv,platform:hostPlatform});assertSafeStandaloneCleanupOrigin(origin,fsOps.isSymlink,hostPlatform,homeGuard);let targets=computeStandaloneCleanupTargets(origin,fsOps.listDir,fsOps.pathExists),removedPaths=[],scheduledPaths=[],warnings=[],coreFailures=[],appDirFailed=!1,binPathFailed=!1,deferBinPath=hostPlatform==="win32"&&fsOps.pathExists(targets.binPath)&&isRunningWindowsBatchShim(targets.binPath,hostEnv);if(isWithinDir(targets.appDir,targets.dataDir)&&normalizeComparablePath(targets.appDir)!==normalizeComparablePath(targets.dataDir)&&fsOps.pathExists(targets.appDir))try{fsOps.rmDirRecursive(targets.appDir),removedPaths.push(targets.appDir)}catch(err){let code=extractErrnoCode(err);if(RETRYABLE_FS_CODES.has(code))appDirFailed=!0,coreFailures.push(t(locale,`应用目录正被其他进程占用或无权删除 (${code}): ${targets.appDir}`,`App directory could not be removed (${code}): ${targets.appDir}`));else throw err}if(!appDirFailed&&!deferBinPath&&fsOps.pathExists(targets.binPath))try{if(fsOps.rmFile(targets.binPath),removedPaths.push(targets.binPath),isWithinDir(targets.binDir,targets.dataDir)&&normalizeComparablePath(targets.binDir)!==normalizeComparablePath(targets.dataDir))fsOps.rmEmptyDir(targets.binDir)}catch(err){let code=extractErrnoCode(err);if(RETRYABLE_FS_CODES.has(code))binPathFailed=!0,coreFailures.push(t(locale,`命令入口正被其他进程占用或无权删除 (${code}): ${targets.binPath}`,`Command shim could not be removed (${code}): ${targets.binPath}`));else throw err}let coreOk=!appDirFailed&&!binPathFailed,deferRuntimeDir=!1;if(coreOk&&!targets.hasOtherApps)fsOps.rmEmptyDir(targets.appsDir);if(coreOk&&targets.willRemoveRuntime)try{if(fsOps.rmDirRecursive(targets.runtimeDir),removedPaths.push(targets.runtimeDir),!deferBinPath)fsOps.rmEmptyDir(targets.dataDir)}catch{if(hostPlatform==="win32")deferRuntimeDir=!0;else warnings.push(t(locale,`私有运行时正被当前进程占用, 退出后可手动删除: ${targets.runtimeDir}`,`Private runtime is busy during self-exit; remove manually if desired: ${targets.runtimeDir}`))}else if(coreOk&&!targets.hasOtherApps&&!deferBinPath)fsOps.rmEmptyDir(targets.dataDir);if(coreOk&&(deferBinPath||deferRuntimeDir)){let useDefaultScheduler=runtimeCtx?.scheduleDelayedCleanup===void 0,runtimeAllowed=deferRuntimeDir&&(!useDefaultScheduler||isSafeScheduledRuntimeDir(targets.runtimeDir,targets.dataDir)),scheduler=runtimeCtx?.scheduleDelayedCleanup??scheduleWindowsDelayedRuntimeCleanup,scheduled=deferBinPath||runtimeAllowed?scheduler({...deferBinPath?{binPath:targets.binPath,binDir:targets.binDir}:{},...runtimeAllowed?{runtimeDir:targets.runtimeDir}:{},dataDir:targets.dataDir,pid:runtimeCtx?.pid??process.pid,env:hostEnv,pathExists:fsOps.pathExists}):!1;if(scheduled){if(deferBinPath)scheduledPaths.push(targets.binPath);if(runtimeAllowed)scheduledPaths.push(targets.runtimeDir)}else if(deferBinPath)try{fsOps.rmFile(targets.binPath),removedPaths.push(targets.binPath)}catch{warnings.push(t(locale,`命令入口正被当前终端占用, 退出后可手动删除: ${targets.binPath}`,`Command shim is busy during self-exit; remove manually if desired: ${targets.binPath}`))}if(deferRuntimeDir&&(!scheduled||!runtimeAllowed))warnings.push(t(locale,`私有运行时正被当前进程占用, 退出后可手动删除: ${targets.runtimeDir}`,`Private runtime is busy during self-exit; remove manually if desired: ${targets.runtimeDir}`))}return{removedPaths,scheduledPaths,warnings,coreFailed:coreFailures.length>0,...coreFailures.length>0?{failureMessage:coreFailures.join("; ")}:{}}}function removeToolConfigDir(input){let hostPlatform=input.platform??process.platform,homeGuard=resolveUninstallHomeGuard({homeDir:input.homeDir,env:input.env,platform:hostPlatform});if(homeGuard.invalidExplicitHome)return{removed:!1};if(!isSafeRemovableConfigDir(input.configDir,input.toolName))return{removed:!1};for(let h of homeGuard.homeDirs)if(!isSafeRemovableConfigDir(input.configDir,input.toolName,h))return{removed:!1};if(!input.fsOps.pathExists(input.configDir))return{removed:!1};assertPathsNoSymlinkAncestors([input.configDir],input.fsOps.isSymlink,hostPlatform);for(let h of homeGuard.homeDirs)if(isRealPathHomeOrDirectChild(input.configDir,h,hostPlatform))return{removed:!1};return input.fsOps.rmDirRecursive(input.configDir),{removed:!0}}async function executeUninstallCommand(ctx){let{label,plan,verbose,io,color,ui,spinner,locale,deps}=ctx,startedAt=Date.now(),result,asyncRunner=deps.execPlanAsync??executeUpgradePlanAsync;try{if(deps.execPlan!==void 0){let syncRes=await deps.execPlan(plan);result={status:syncRes.status,signal:syncRes.signal,error:syncRes.error,capturedOutput:syncRes.capturedOutput??"",truncated:syncRes.truncated??!1,durationMs:syncRes.durationMs??Math.max(0,Date.now()-startedAt)}}else if(verbose)io.out(ui.body(t(locale,`正在执行: ${paintSgr(sanitize(plan.displayCommand),"36",color.stdout)}`,`Running: ${paintSgr(sanitize(plan.displayCommand),"36",color.stdout)}`))),result=await asyncRunner(plan,{env:deps.env,verbose:!0,spawnAsync:deps.spawnAsync});else spinner.start(t(locale,`正在通过 ${label} 卸载`,`Uninstalling via ${label}`)),result=await asyncRunner(plan,{env:deps.env,spawnAsync:deps.spawnAsync})}catch(err){result={status:null,error:err instanceof Error?err:Error(String(err))}}finally{spinner.stop()}let elapsedMs=result.durationMs??Math.max(0,Date.now()-startedAt);if(result.error===void 0&&result.signal==null&&result.status===0)return{ok:!0,durationMs:elapsedMs};let reason;if(result.error!==void 0)reason=sanitize(result.error.message);else if(result.signal!=null)reason=t(locale,`卸载进程被信号中止 (${result.signal})`,`Uninstall terminated by signal (${result.signal})`);else reason=t(locale,`${label} 卸载失败 (退出码 ${result.status??"unknown"}, 用时 ${formatElapsedMs(elapsedMs)})`,`${label} uninstall failed (exit code ${result.status??"unknown"}, elapsed ${formatElapsedMs(elapsedMs)})`);io.err(ui.error(reason));let captured=result.capturedOutput??"";if(captured.trim()!==""){let tail=sanitizeMultilineTail(captured);if(tail.lines.length>0){io.err(ui.errorHint(t(locale,"最近输出摘要:","Recent output tail:")));for(let line of tail.lines)io.err(ui.errorLogLine(line))}}return io.err(ui.errorHint(t(locale,`可手动执行: ${sanitize(plan.displayCommand)}`,`Try manually: ${sanitize(plan.displayCommand)}`))),{ok:!1,message:reason}}import{realpathSync as realpathSync5}from"node:fs";function renderUninstallHeader(binName,dryRun,color,locale){let badge=`${BAR_BLOCK} ${sanitize(binName).toUpperCase()} `,title=dryRun?t(locale,"卸载 (预览)","Uninstall (Dry Run)"):t(locale,"卸载","Uninstall");return`${paintSgr(badge,"1;7",color.stdout)} ${paintSgr(title,"1",color.stdout)}`}function describeUnsupportedOrigin(origin,meta,devLinks,locale){if(origin.kind==="source"){let devHint=devLinks.length>0?t(locale,`检测到源码开发软链: ${devLinks.map((d)=>sanitize(d.path)).join(", ")}; 如仅想解除链接请手动移除软链或运行 unlink`,`Detected source dev links: ${devLinks.map((d)=>sanitize(d.path)).join(", ")}; remove them manually if you only want to unlink`):t(locale,"如需卸载其他已安装的全局副本, 请通过对应包管理器卸载或显式传入 --pm","To remove another globally installed copy, use its package manager or pass --pm");return{code:"UNSUPPORTED_ORIGIN",message:t(locale,"当前正从源码仓库直接运行, 为防止误删代码仓, 拒绝执行自卸载","Running directly from a source checkout; refusing to self-uninstall"),hint:devHint}}if(origin.kind==="ephemeral")return{code:"UNSUPPORTED_ORIGIN",message:t(locale,`当前经临时执行器 (${origin.runner}) 运行, 本机未持久化安装, 无需卸载`,`Running via ephemeral runner (${origin.runner}); nothing is persistently installed`)};if(origin.kind==="local-project"){let cmd=origin.suggestedPm==="npm"?`npm uninstall ${meta.name}`:`${origin.suggestedPm} remove ${meta.name}`;return{code:"UNSUPPORTED_ORIGIN",message:t(locale,`当前为项目本地依赖 (${sanitize(origin.projectDir)}), 不执行全局自卸载`,`Installed as a local project dependency (${sanitize(origin.projectDir)}); refusing global uninstall`),hint:t(locale,`请在项目目录执行: ${cmd}`,`Remove inside the project with: ${cmd}`)}}return{code:"UNKNOWN_ORIGIN",message:t(locale,`无法自动识别 ${meta.name} 的安装方式 (${sanitize(origin.reason)})`,`Could not determine how ${meta.name} was installed (${sanitize(translateOriginReason(origin.reason))})`),hint:t(locale,`若为全局安装, 请显式传入 --pm <bun|npm|pnpm|yarn|volta> 或手动执行: ${formatPmUninstallCommand("bun",meta.name)}`,`Pass --pm <bun|npm|pnpm|yarn|volta> or remove manually, e.g. ${formatPmUninstallCommand("bun",meta.name)}`)}}function buildPackageUninstallStep(ctx){let targetPm=ctx.explicitPm??(ctx.origin.kind==="global"?ctx.origin.pm:void 0);if(targetPm!==void 0){let yarnVersion;if(targetPm==="yarn")yarnVersion=ctx.probeYarn!==void 0?ctx.probeYarn():probeYarnVersion(ctx.platform,ctx.env,ctx.spawnFn,ctx.isFile);let outcome=buildPmUninstallPlan({pm:targetPm,packageName:ctx.meta.name,platform:ctx.platform,env:ctx.env,isFile:ctx.isFile,yarnVersion,locale:ctx.locale});if(!outcome.ok)return{ok:!1,code:"UNINSTALL_PLAN_FAILED",message:outcome.reason,hint:outcome.fallbackCommand};return{ok:!0,step:{kind:"global",label:targetPm,pm:targetPm,plan:outcome.plan}}}if(ctx.origin.kind==="homebrew"){let outcome=buildHomebrewUninstallPlan({origin:ctx.origin,platform:ctx.platform,env:ctx.env,isFile:ctx.isFile,locale:ctx.locale});if(!outcome.ok)return{ok:!1,code:"UNINSTALL_PLAN_FAILED",message:outcome.reason,hint:outcome.fallbackCommand};return{ok:!0,step:{kind:"homebrew",label:"Homebrew",formulaRef:ctx.origin.formulaRef,plan:outcome.plan}}}if(ctx.origin.kind==="standalone"){let homeGuard=resolveUninstallHomeGuard({homeDir:ctx.homeDir,env:ctx.env,platform:ctx.platform});try{assertSafeStandaloneCleanupOrigin(ctx.origin,ctx.fsOps.isSymlink,ctx.platform,homeGuard)}catch(err){return{ok:!1,code:"UNINSTALL_PLAN_FAILED",message:err instanceof Error?err.message:String(err)}}return{ok:!0,step:{kind:"standalone",label:t(ctx.locale,"一键脚本安装","One-click script install"),targets:computeStandaloneCleanupTargets(ctx.origin,ctx.fsOps.listDir,ctx.fsOps.pathExists)}}}return{ok:!1,code:"UNSUPPORTED_ORIGIN",message:t(ctx.locale,"不支持的安装来源","Unsupported installation origin")}}function formatOriginLabel(step,locale){if(step.kind==="homebrew")return`Homebrew (${step.formulaRef})`;if(step.kind==="global")return t(locale,`${step.pm} 全局安装`,`${step.pm} global install`);return t(locale,"一键脚本安装","One-click script install")}function emitUninstallPlanSummary(ctx){let{io,ui,color,locale,step,opts,configDir,configExists,externalNote}=ctx;io.out(renderUninstallHeader(ctx.binName,opts.dryRun,color,locale)),io.out(ui.kv(t(locale,"当前版本","Version"),`${ctx.meta.name}@${ctx.meta.version}`,"bold")),io.out(ui.kv(t(locale,"安装方式","Origin"),formatOriginLabel(step,locale))),io.out(""),io.out(ui.body(paintSgr(t(locale,"将清理以下内容:","Items to remove:"),"1",color.stdout)));for(let item of ctx.extraItems){let sudoTag=item.requiresElevation===!0?paintSgr(t(locale," (需 sudo)"," (requires sudo)"),"33",color.stdout):"";io.out(` - ${sanitize(item.label)}${sudoTag}`);for(let p of item.paths??[])io.out(ui.hint(` ${sanitize(p)}`))}if(step.kind==="standalone"){if(io.out(` - ${t(locale,"CLI 本体与入口","CLI package & shim")}: ${sanitize(step.targets.binPath)}`),io.out(ui.hint(` ${sanitize(step.targets.appDir)}`)),step.targets.willRemoveRuntime)io.out(` - ${t(locale,"闲置私有 Bun 运行时","Unused private Bun runtime")}: ${sanitize(step.targets.runtimeDir)}`)}else io.out(` - ${t(locale,"CLI 本体","CLI package")}: ${paintSgr(sanitize(step.plan.displayCommand),"36",color.stdout)}`);if(opts.keepConfig)io.out(ui.hint(` · ${t(locale,`保留配置目录 (--keep-config): ${sanitize(configDir)}`,`Keeping config dir (--keep-config): ${sanitize(configDir)}`)}`));else if(configExists)io.out(` - ${t(locale,"工具配置目录","Tool config directory")}: ${sanitize(configDir)}`);else io.out(ui.hint(` · ${t(locale,`配置目录不存在, 跳过: ${sanitize(configDir)}`,`Config directory absent, skipping: ${sanitize(configDir)}`)}`));if(externalNote!==null)io.out(ui.warn(` ! ${sanitize(externalNote)}`))}function serializePackageAction(step){if(step.kind==="standalone")return{kind:"standalone",binPath:step.targets.binPath,appDir:step.targets.appDir,runtimeDir:step.targets.runtimeDir,willRemoveRuntime:step.targets.willRemoveRuntime};return{kind:step.kind,...step.kind==="homebrew"?{formulaRef:step.formulaRef}:{pm:step.pm},command:step.plan.displayCommand}}function emitDryRunUninstallResult(ctx){if(ctx.jsonMode)return ctx.rawIo.out(JSON.stringify({ok:!0,dryRun:!0,packageName:ctx.meta.name,version:ctx.meta.version,binName:ctx.binName,origin:ctx.originKind,keepConfig:ctx.keepConfig,...ctx.hasDeclaredKeepFlags?{keptFlags:ctx.keptFlags}:{},packageAction:serializePackageAction(ctx.step),extraItems:ctx.extraItems,configDir:ctx.configDir,willRemoveConfig:!ctx.keepConfig&&ctx.configExists,...ctx.externalNote!==null?{externalConfigNote:ctx.externalNote}:{},...ctx.warnings!==void 0&&ctx.warnings.length>0?{warnings:ctx.warnings}:{}},null,2)),0;emitUninstallPlanSummary({binName:ctx.binName,meta:ctx.meta,step:ctx.step,extraItems:ctx.extraItems,configDir:ctx.configDir,configExists:ctx.configExists,opts:{yes:!1,dryRun:!0,keepConfig:ctx.keepConfig,keptFlags:[...ctx.keptFlags],verbose:!1,json:!1,help:!1},externalNote:ctx.externalNote,io:ctx.rawIo,ui:ctx.ui,color:ctx.color,locale:ctx.locale});for(let w of ctx.warnings??[])ctx.rawIo.out(ctx.ui.warn(w));return ctx.rawIo.out(""),ctx.rawIo.out(ctx.ui.hint(t(ctx.locale,"预览模式 (--dry-run): 未执行任何更改。确认无误后去掉 --dry-run 即可卸载。","Dry run (--dry-run): no changes were made. Re-run without --dry-run to uninstall."))),0}function formatErrJson(code,message){return JSON.stringify({ok:!1,error:{code,message:sanitize(message)}})}function buildPartialCleanupNote(locale,removedExtra){if(removedExtra.length===0)return"";return t(locale,` (注意: 以下扩展项已先期清理: ${removedExtra.join(", ")})`,` (Note: pre-cleanup already removed: ${removedExtra.join(", ")})`)}function failUninstallAfterHooks(params){let{message,removedExtra,locale,jsonMode,rawIo,ui,printError}=params,extraNote=buildPartialCleanupNote(locale,removedExtra);if(jsonMode)return rawIo.err(formatErrJson("UNINSTALL_FAILED",`${message}${extraNote}`)),1;if(printError)rawIo.err(ui.error(message));if(extraNote!=="")rawIo.err(ui.warn(sanitize(extraNote.trim())));return 1}async function runCleanupHookPhase(params){if(params.hooks?.cleanup===void 0)return{ok:!0,removedExtra:[]};try{let hookRes=await params.hooks.cleanup({keptFlags:new Set(params.keptFlags),keepConfig:params.keepConfig,json:params.jsonMode,locale:params.locale});if(hookRes.warnings!==void 0)params.warnings.push(...hookRes.warnings);if(!params.jsonMode)for(let item of hookRes.removed)params.rawIo.out(params.ui.success(sanitize(item)));return{ok:!0,removedExtra:hookRes.removed}}catch(err){let msg=err instanceof Error?err.message:String(err);if(params.jsonMode)params.rawIo.err(formatErrJson("UNINSTALL_HOOK_FAILED",msg));else params.rawIo.err(params.ui.error(msg));return{ok:!1}}}function runStandaloneRemovalPhase(ctx){try{let res=executeStandaloneUninstall(ctx.origin,ctx.fsOps,ctx.locale,{platform:ctx.platform,env:ctx.env,homeDir:ctx.homeDir,scheduleDelayedCleanup:ctx.scheduleDelayedCleanup});if(ctx.warnings.push(...res.warnings),res.coreFailed)return failUninstallAfterHooks({message:res.failureMessage??t(ctx.locale,`未能完整清理一键脚本安装的 ${ctx.meta.name}`,`Failed to remove standalone install of ${ctx.meta.name}`),removedExtra:ctx.removedExtra,locale:ctx.locale,jsonMode:ctx.jsonMode,rawIo:ctx.rawIo,ui:ctx.ui,printError:!0}),{ok:!1};if(!ctx.jsonMode){ctx.rawIo.out(ctx.ui.success(t(ctx.locale,`已清理一键脚本安装的 ${ctx.meta.name}`,`Removed standalone install of ${ctx.meta.name}`)));for(let deferred of res.scheduledPaths)ctx.rawIo.out(ctx.ui.body(t(ctx.locale,`已安排退出后自动清理: ${sanitize(deferred)}`,`Scheduled automatic removal on exit: ${sanitize(deferred)}`)))}return{ok:!0,removedPackagePaths:res.removedPaths,scheduledRemovalPaths:res.scheduledPaths}}catch(err){return failUninstallAfterHooks({message:err instanceof Error?err.message:String(err),removedExtra:ctx.removedExtra,locale:ctx.locale,jsonMode:ctx.jsonMode,rawIo:ctx.rawIo,ui:ctx.ui,printError:!0}),{ok:!1}}}function tryRemoveToolConfigDir(ctx){try{if(!removeToolConfigDir({configDir:ctx.configDir,toolName:ctx.toolName,homeDir:ctx.homeDir,env:ctx.env,platform:ctx.platform,fsOps:ctx.fsOps}).removed)return null;if(!ctx.jsonMode)ctx.rawIo.out(ctx.ui.success(t(ctx.locale,`已清理配置目录: ${sanitize(ctx.configDir)}`,`Removed config directory: ${sanitize(ctx.configDir)}`)));return ctx.configDir}catch(error){let detail=error instanceof Error?error.message:String(error);return ctx.warnings.push(t(ctx.locale,`配置目录清理失败 (${sanitize(ctx.configDir)}): ${sanitize(detail)}, 请稍后手动删除`,`Failed to remove config directory (${sanitize(ctx.configDir)}): ${sanitize(detail)}; remove it manually`)),null}}function filterRemainingBins(bins,scheduledRemovalPaths,platform){let norm=(p)=>{let slashed=p.replaceAll("\\","/").replace(/\/+$/,"");return platform==="win32"?slashed.toLowerCase():slashed},canon=(p)=>{try{return norm(stripWinExtendedPrefix((realpathSync5.native??realpathSync5)(p)))}catch{return norm(stripWinExtendedPrefix(p))}},scheduledSet=new Set;for(let p of scheduledRemovalPaths)scheduledSet.add(norm(p)),scheduledSet.add(canon(p));return bins.filter((found)=>!scheduledSet.has(norm(found))&&!scheduledSet.has(canon(found)))}async function executeUninstallSteps(ctx){let{options,opts,meta,origin,step,toolName,configDir,hasDeclaredKeepFlags,jsonMode,locale,color,ui,rawIo,fsOps,platform,env,deps,initialWarnings}=ctx,warnings=[...initialWarnings??[]],hookPhase=await runCleanupHookPhase({hooks:options.hooks,keptFlags:opts.keptFlags,keepConfig:opts.keepConfig,jsonMode,locale,rawIo,ui,warnings});if(!hookPhase.ok)return 1;let{removedExtra}=hookPhase,ioForExec=jsonMode?{out:()=>{},err:()=>{}}:rawIo,spinner=deps.spinner??createUpdateSpinner({enabled:!jsonMode&&!opts.verbose&&options.io===void 0&&stderrSupportsSpinner(env),color:color.stderr}),removedPackagePaths=[],scheduledRemovalPaths=[];if(step.kind==="standalone"){let standaloneRes=runStandaloneRemovalPhase({origin,meta,fsOps,platform,env,homeDir:deps.homeDir,scheduleDelayedCleanup:deps.scheduleDelayedCleanup,jsonMode,locale,rawIo,ui,removedExtra,warnings});if(!standaloneRes.ok)return 1;removedPackagePaths=standaloneRes.removedPackagePaths,scheduledRemovalPaths=standaloneRes.scheduledRemovalPaths}else{let execRes=await executeUninstallCommand({label:step.label,plan:step.plan,verbose:opts.verbose&&!jsonMode,io:ioForExec,color,ui,spinner,locale,deps});if(!execRes.ok)return failUninstallAfterHooks({message:execRes.message,removedExtra,locale,jsonMode,rawIo,ui,printError:!1});if(!jsonMode)rawIo.out(ui.success(t(locale,`已通过 ${step.label} 卸载 ${meta.name}`,`Uninstalled ${meta.name} via ${step.label}`),`(${formatElapsedMs(execRes.durationMs)})`))}let removedConfigDir=opts.keepConfig?null:tryRemoveToolConfigDir({configDir,toolName,homeDir:deps.homeDir,env,platform,fsOps,jsonMode,locale,rawIo,ui,warnings}),remainingBinsInPath=filterRemainingBins(findRemainingBinsInPath({binName:options.binName,platform,env,isFile:deps.isFile}),scheduledRemovalPaths,platform);if(remainingBinsInPath.length>0)warnings.push(t(locale,`检测到 PATH 中仍有其他渠道安装的 ${options.binName}: ${remainingBinsInPath.join(", ")}`,`Another ${options.binName} binary remains in PATH: ${remainingBinsInPath.join(", ")}`));if(jsonMode)return rawIo.out(JSON.stringify({ok:!0,uninstalled:!0,packageName:meta.name,version:meta.version,binName:options.binName,origin:origin.kind,packageAction:serializePackageAction(step),removedPackagePaths,...scheduledRemovalPaths.length>0?{scheduledRemovalPaths}:{},removedExtra,removedConfigDir,keptConfig:opts.keepConfig,...hasDeclaredKeepFlags?{keptFlags:opts.keptFlags}:{},remainingBinsInPath,warnings},null,2)),0;for(let w of warnings)rawIo.out(ui.warn(`! ${sanitize(w)}`));return 0}function formatUninstallErrorJson(code,message){return JSON.stringify({ok:!1,error:{code,message:sanitize(stripAnsi(message)).trim()}})}async function confirmUninstallExecution(ctx){let{binName,yes,jsonMode,interactive,confirmFn,rawIo,ui,locale,printSummary}=ctx;if(!yes&&(jsonMode||!interactive)){let msg=t(locale,`非交互环境或 --json 模式卸载必须显式传入 --yes 确认 (可先用 ${binName} uninstall --dry-run 预览)`,`Non-interactive or --json uninstall requires --yes (preview first with '${binName} uninstall --dry-run')`);if(jsonMode)rawIo.err(formatUninstallErrorJson("CONFIRMATION_REQUIRED",msg));else rawIo.err(ui.error(msg));return"rejected"}if(!jsonMode)printSummary(),rawIo.out("");if(yes)return"proceed";if(await confirmFn(t(locale,"确认彻底卸载以上内容? [y/N]: ","Proceed with uninstall? [y/N]: "))!=="yes")return rawIo.out(ui.warn(t(locale,"已取消卸载, 未作任何更改","Uninstall cancelled; nothing was changed"))),"cancelled";return"proceed"}function emitUninstallFailure(ctx){if(ctx.jsonMode)return ctx.rawIo.err(formatUninstallErrorJson(ctx.code,ctx.message)),1;if(ctx.rawIo.out(renderUninstallHeader(ctx.binName,ctx.dryRun,ctx.color,ctx.locale)),ctx.rawIo.err(ctx.ui.error(ctx.message)),ctx.hint!==void 0){let line=ctx.hintPrefix?t(ctx.locale,`可手动执行: ${sanitize(ctx.hint)}`,`Try manually: ${sanitize(ctx.hint)}`):ctx.hint;ctx.rawIo.err(ctx.ui.errorHint(line))}return 1}function resolvePreUninstallLocale(options){let initLocale=resolveUpdateLocale(options),peeked=stripLangArgs(options.argv,{fallbackLocale:initLocale,valueFlags:new Set(UNINSTALL_VALUE_FLAGS)});return peeked.lang!==void 0?resolveUpdateLocale(options,peeked.lang):initLocale}function formatPackageMetaReadError(err,locale){let msg=err instanceof Error?err.message:String(err);return t(locale,`读取当前包信息失败: ${sanitize(msg)}`,`Failed to read package metadata: ${sanitize(msg)}`)}async function runSelfUninstall(options){let deps=options.deps??{},rawIo=options.io??{out:(line)=>process.stdout.write(`${line}
|
|
27
|
+
`),err:(line)=>process.stderr.write(`${line}
|
|
28
|
+
`)},env=deps.env??process.env,platform=deps.platform??process.platform,color=options.color??(options.io!==void 0?{stdout:!1,stderr:!1}:detectColorChannels(env)),baseLocale=resolvePreUninstallLocale(options),keepFlags=options.hooks?.keepFlags??[],hasDeclaredKeepFlags=keepFlags.length>0,parsed=parseUninstallArgs(options.argv,baseLocale,{binName:options.binName,keepFlags}),jsonMode=options.json===!0||(parsed.ok?parsed.options.json:parsed.json),emitJsonErr=(code,message)=>(rawIo.err(formatUninstallErrorJson(code,message)),1);if(!parsed.ok){if(jsonMode)return emitJsonErr("INVALID_ARGUMENT",parsed.message);return rawIo.err(createUpdateUi(color,baseLocale).error(parsed.message)),1}let opts=parsed.options,locale=resolveUpdateLocale(options,opts.lang),ui=createUpdateUi(color,locale),toolName=options.toolName??options.binName,meta;try{meta=loadPackageMetaOrThrow(options,locale)}catch(err){let errMsg=formatPackageMetaReadError(err,locale);if(jsonMode)return emitJsonErr("PACKAGE_META_FAILED",errMsg);return rawIo.err(ui.error(errMsg)),1}if(opts.help){let help=formatUninstallHelp(options.binName,meta.name,!jsonMode&&color.stdout,locale,{docsUrl:options.docsUrl,...options.hooks});return rawIo.out(jsonMode?JSON.stringify({ok:!0,help},null,2):help),0}let fsOps=createDefaultUninstallFsOps(deps),{origin,devLinks}=resolveUpdateTargetState({meta,binName:options.binName,explicitPm:opts.pm,deps}),sharedFailCtx={binName:options.binName,dryRun:opts.dryRun,jsonMode,rawIo,ui,color,locale};if(opts.pm===void 0&&origin.kind!=="homebrew"&&origin.kind!=="global"&&origin.kind!=="standalone"){let refused=describeUnsupportedOrigin(origin,meta,devLinks,locale);return emitUninstallFailure({...sharedFailCtx,...refused})}let built=buildPackageUninstallStep({origin,meta,explicitPm:opts.pm,fsOps,platform,env,homeDir:deps.homeDir,isFile:deps.isFile,probeYarn:deps.probeYarn,spawnFn:deps.spawnFn,locale});if(!built.ok)return emitUninstallFailure({...sharedFailCtx,code:built.code,message:built.message,hint:built.hint,hintPrefix:!0});let{configDir,configExists}=resolveToolConfigPreview({toolName,homeDir:deps.homeDir,env,platform,pathExists:fsOps.pathExists,isSymlink:fsOps.isSymlink}),hookInfo=await collectUninstallHookInfo(options.hooks,{keptFlags:opts.keptFlags,keepConfig:opts.keepConfig,configDir,locale}),{extraItems,externalNote,warnings:hookWarnings}=hookInfo;if(opts.dryRun)return emitDryRunUninstallResult({binName:options.binName,meta,originKind:origin.kind,step:built.step,extraItems,configDir,configExists,keepConfig:opts.keepConfig,keptFlags:opts.keptFlags,hasDeclaredKeepFlags,externalNote,warnings:hookWarnings,jsonMode,rawIo,ui,color,locale});let interactive=deps.interactive??(process.stdin.isTTY===!0&&process.stdout.isTTY===!0),gate=await confirmUninstallExecution({binName:options.binName,yes:opts.yes,jsonMode,interactive,confirmFn:deps.confirm??defaultPromptUninstallConfirm,rawIo,ui,locale,printSummary:()=>{emitUninstallPlanSummary({binName:options.binName,meta,step:built.step,extraItems,configDir,configExists,opts,externalNote,io:rawIo,ui,color,locale});for(let w of hookWarnings)rawIo.out(ui.warn(w))}});if(gate==="rejected")return 1;if(gate==="cancelled")return 0;return await executeUninstallSteps({options,opts,meta,origin,step:built.step,toolName,configDir,hasDeclaredKeepFlags,jsonMode,locale,color,ui,rawIo,fsOps,platform,env,deps,initialWarnings:hookWarnings})}import{appendFileSync,existsSync as existsSync13,lstatSync as lstatSync5,mkdirSync as mkdirSync5,readFileSync as readFileSync10,readdirSync as readdirSync2,realpathSync as realpathSync6,writeFileSync as writeFileSync5}from"node:fs";import{homedir}from"node:os";import{join as join9,resolve as resolve4}from"node:path";class RimError extends Error{code;details;constructor(code,message,details,cause){super(message,cause!==void 0?{cause}:void 0);if(this.name="RimError",this.code=code,details!==void 0)this.details=details}}function isRimError(error){return error instanceof RimError}function pickLocale(locale){return locale==="en"?"en":"zh"}function rimT(locale,zh,en){return locale==="en"?en:zh}var ESC4=String.fromCharCode(27),CSI_7_RE=new RegExp(`${ESC4}\\[[0-9;?]*[ -/]*[@-~]`,"g"),CSI_8_RE=new RegExp("\\u009b[0-9;?]*[ -/]*[@-~]","g"),OSC_RE=new RegExp(`(?:${ESC4}\\]|\\u009d)[^\\u0007\\u001b\\u009c]*(?:\\u0007|${ESC4}\\\\|\\u009c)?`,"g"),STRING_SEQ_RE=new RegExp(`(?:${ESC4}[PX^_]|[\\u0090\\u0098\\u009e\\u009f])[^\\u001b\\u009c]*(?:${ESC4}\\\\|\\u009c)?`,"g"),ESC_TWO_BYTE_RE=new RegExp(`${ESC4}[ -/]*[0-~]`,"g"),BIDI_RE=/[\u202a-\u202e\u2066-\u2069]/g;function hasControlOrBidi(input){for(let i=0;i<input.length;i+=1){let c=input.charCodeAt(i);if(c<=31||c>=127&&c<=159||c>=8234&&c<=8238||c>=8294&&c<=8297)return!0}return!1}function sanitizeLine(input){if(!hasControlOrBidi(input))return input.trim();return input.replace(OSC_RE,"").replace(STRING_SEQ_RE,"").replace(CSI_7_RE,"").replace(CSI_8_RE,"").replace(ESC_TWO_BYTE_RE,"").replace(BIDI_RE,"").replace(/[\r\n\t]+/g," ").replace(/\p{Cc}/gu,"").trim()}import{accessSync as accessSync2,existsSync as existsSync12,constants as fsConstants,statSync as statSync2}from"node:fs";import{mkdir,writeFile}from"node:fs/promises";import{createServer as createHttpServer}from"node:http";import{createServer as createNetServer}from"node:net";import{dirname as dirname5,isAbsolute,posix as posix11,relative,win32 as win3213}from"node:path";var WIN32_ABS_DIR_RE=/^(?:[A-Za-z]:[/\\]|\\\\(?![?.][/\\])[^\\/]+[/\\][^\\/]+)/,SCHEME_PREFIX_RE=/^[a-zA-Z][a-zA-Z0-9+.-]*:/,PARENT_ESCAPE_RE=/^\.\.(?:[\\/]|$)/;function getBunApis(){let candidate=globalThis.Bun;if(candidate!==null&&typeof candidate==="object")return candidate;return null}function createBunFileResponse(filePath,headers){let bun=getBunApis();return bun!==null?new Response(bun.file(filePath),{status:200,headers}):null}function getRuntimeInfo(){let bunVer=process.versions.bun;if(typeof bunVer==="string"&&bunVer!=="")return{name:"bun",version:bunVer,platform:process.platform,arch:process.arch};return{name:"node",version:process.versions.node??"unknown",platform:process.platform,arch:process.arch}}function sleepMs(ms,signal){if(signal?.aborted===!0)return Promise.reject(new RimError("CANCELLED","Cancelled"));let bun=getBunApis();if(signal===void 0&&bun!==null)return bun.sleep(ms);return new Promise((resolve,reject)=>{let onAbort=()=>{clearTimeout(timer),reject(new RimError("CANCELLED","Cancelled"))},timer=setTimeout(()=>{signal?.removeEventListener("abort",onAbort),resolve()},ms);signal?.addEventListener("abort",onAbort,{once:!0})})}function waitWithTimeout(promise,timeoutMs){return new Promise((resolve)=>{let settled=!1,timer=setTimeout(()=>{if(settled)return;settled=!0,resolve(!1)},timeoutMs);if(typeof timer.unref==="function")timer.unref();promise.then(()=>{if(settled)return;settled=!0,clearTimeout(timer),resolve(!0)},()=>{if(settled)return;settled=!0,clearTimeout(timer),resolve(!0)})})}async function writeTextFile(filePath,content){await mkdir(dirname5(filePath),{recursive:!0});let bun=getBunApis();if(bun!==null){await bun.write(filePath,content);return}await writeFile(filePath,content,"utf8")}function allocateFreePort(){let bun=getBunApis();if(bun!==null){let probe=bun.serve({hostname:"127.0.0.1",port:0,fetch:()=>new Response("")}),port=probe.port??0;if(probe.stop(!0),port>0)return Promise.resolve(port)}return new Promise((resolve,reject)=>{let srv=createNetServer();srv.unref(),srv.once("error",reject),srv.listen(0,"127.0.0.1",()=>{let addr=srv.address(),port=addr!==null&&typeof addr==="object"?addr.port:0;srv.close((closeErr)=>{if(closeErr!==void 0){reject(closeErr);return}if(port<=0){reject(Error("Failed to allocate ephemeral port"));return}resolve(port)})})})}async function readIncomingBody(req){if(req.method==="GET"||req.method==="HEAD")return;let chunks=[];for await(let chunk of req)chunks.push(Buffer.isBuffer(chunk)?chunk:Buffer.from(chunk));if(chunks.length===0)return;return new Uint8Array(Buffer.concat(chunks))}function writeWebResponseToNode(webRes,nodeRes,isHead){let headersObj={};for(let[key,value]of webRes.headers.entries()){let existing=headersObj[key];if(existing===void 0)headersObj[key]=value;else if(Array.isArray(existing))existing.push(value);else headersObj[key]=[existing,value]}if(nodeRes.writeHead(webRes.status,headersObj),isHead||webRes.body===null)return nodeRes.end(),Promise.resolve();return webRes.arrayBuffer().then((buf)=>{nodeRes.end(Buffer.from(buf))})}async function startFetchServer(fetchHandler,hostname="127.0.0.1"){let bun=getBunApis();if(bun!==null){let server=bun.serve({hostname,port:0,fetch:fetchHandler}),port=server.port??0;return{port,url:`http://${hostname}:${port}`,stop:async()=>{server.stop(!0)}}}return await new Promise((resolve,reject)=>{let boundPort=0,server=createHttpServer((req,res)=>{let origin=`http://${hostname}:${String(boundPort)}`,rawReqUrl=req.url??"/",safeRel=rawReqUrl.startsWith("/")?rawReqUrl:`/${rawReqUrl}`,fullUrl;try{fullUrl=new URL(`${origin}${safeRel}`).href}catch{res.writeHead(400,{"Content-Type":"text/plain; charset=utf-8"}),res.end("Bad Request");return}let headers=new Headers;for(let[key,value]of Object.entries(req.headers))if(typeof value==="string")headers.set(key,value);else if(Array.isArray(value))headers.set(key,value.join(", "));let method=req.method??"GET";readIncomingBody(req).then((body)=>fetchHandler(new Request(fullUrl,{method,headers,...body!==void 0?{body:Buffer.from(body)}:{}}))).then((webRes)=>writeWebResponseToNode(webRes,res,method==="HEAD")).catch(()=>{if(!res.headersSent)res.writeHead(500,{"Content-Type":"text/plain; charset=utf-8"});res.end("Internal Server Error")})});server.once("error",reject),server.listen(0,hostname,()=>{let addr=server.address(),port=addr!==null&&typeof addr==="object"?addr.port:0;boundPort=port,resolve({port,url:`http://${hostname}:${port}`,stop:()=>new Promise((resStop)=>{server.close(()=>resStop()),server.closeAllConnections?.()})})})})}function isRegularFile(candidate){try{return statSync2(candidate).isFile()}catch{return!1}}function isExecutableFile(candidate,platform=process.platform){if(!isRegularFile(candidate))return!1;if(platform==="win32")return!0;try{return accessSync2(candidate,fsConstants.X_OK),!0}catch{return!1}}function isPlatformAbsolutePath(filePath,platform=process.platform){return platform==="win32"?WIN32_ABS_DIR_RE.test(filePath):posix11.isAbsolute(filePath)}function isPathWithinRoot(realRoot,realCandidate){let rel=relative(realRoot,realCandidate);return!PARENT_ESCAPE_RE.test(rel)&&!isAbsolute(rel)}function resolveSameOriginUrl(origin,rawPath,locale="zh",fieldLabel="path"){let trimmed=rawPath.trim();if(trimmed===""||trimmed===".")return`${origin}/`;if(SCHEME_PREFIX_RE.test(trimmed)||trimmed.startsWith("//"))throw new RimError("INVALID_ARGUMENT",rimT(locale,`安全拦截: ${fieldLabel} 不可指定外部协议或跨源地址 (${rawPath})`,`Security error: ${fieldLabel} must be same-origin relative (${rawPath})`));let normalized=trimmed.startsWith("/")?trimmed:`/${trimmed}`;if(normalized.startsWith("//"))throw new RimError("INVALID_ARGUMENT",rimT(locale,`安全拦截: ${fieldLabel} 不可使用协议相对路径 (${rawPath})`,`Security error: ${fieldLabel} must not use protocol-relative path (${rawPath})`));let resolved;try{resolved=new URL(normalized,origin)}catch{throw new RimError("INVALID_ARGUMENT",rimT(locale,`非法相对路径 (${fieldLabel}): ${rawPath}`,`Invalid relative path (${fieldLabel}): ${rawPath}`))}if(resolved.origin!==origin)throw new RimError("INVALID_ARGUMENT",rimT(locale,`安全拦截: ${fieldLabel} 解析结果逃出目标源 (${rawPath})`,`Security error: ${fieldLabel} resolved outside target origin (${rawPath})`));return resolved.href}function resolveAbsoluteFromPath(names,options={}){let platform=options.platform??process.platform,env=options.env??process.env,fileProbe=options.fileProbe??((candidate)=>isExecutableFile(candidate,platform)),rawPath=env.PATH?.trim()||(platform==="win32"?env.Path?.trim()||"":"");if(rawPath==="")return null;let sep=platform==="win32"?";":":",exts=platform==="win32"?[".exe",".com",".cmd"]:[""];for(let rawDir of rawPath.split(sep)){let trimmed=rawDir.trim(),dir=trimmed.length>=2&&trimmed.startsWith('"')&&trimmed.endsWith('"')?trimmed.slice(1,-1).trim():trimmed;if(dir==="")continue;if(platform==="win32"?!WIN32_ABS_DIR_RE.test(dir):!dir.startsWith("/"))continue;for(let name of names){let suffixes=/\.[A-Za-z0-9]+$/.test(name)?[""]:exts;for(let ext of suffixes){let candidate=platform==="win32"?win3213.join(dir,`${name}${ext}`):posix11.join(dir,`${name}${ext}`);if(fileProbe(candidate))return candidate}}}return null}function assertSafeHttpUrl(rawUrl,locale="zh"){let parsed;try{parsed=new URL(rawUrl)}catch{throw new RimError("INVALID_ARGUMENT",rimT(locale,`非法目标 URL: ${rawUrl}`,`Invalid target URL: ${rawUrl}`))}if(parsed.protocol!=="http:"&&parsed.protocol!=="https:")throw new RimError("INVALID_ARGUMENT",rimT(locale,`仅支持 http:// 或 https:// 目标地址 (收到协议 ${parsed.protocol})`,`Only http:// and https:// URLs are supported (received ${parsed.protocol})`));return parsed}function isExistingFile(filePath){return existsSync12(filePath)&&isRegularFile(filePath)}import{request as httpRequest}from"node:http";import{request as httpsRequest}from"node:https";import{isIP as isIP2}from"node:net";import{brotliDecompressSync,gunzipSync as gunzipSync2,inflateSync}from"node:zlib";import{createHash as createHash3}from"node:crypto";import{lookup as dnsLookup}from"node:dns/promises";import{isIP}from"node:net";var WINDOWS_RESERVED_NAMES=new Set(["con","prn","aux","nul","com1","com2","com3","com4","com5","com6","com7","com8","com9","lpt1","lpt2","lpt3","lpt4","lpt5","lpt6","lpt7","lpt8","lpt9"]),SCRUBBED_ENV_EXACT=new Set(["BUN_OPTIONS","NODE_OPTIONS","LD_PRELOAD","LD_LIBRARY_PATH","LD_AUDIT","BASH_ENV","ENV","ZDOTDIR"]),SCRUBBED_ENV_PREFIX_RE=/^(?:DYLD_|npm_config_)/i;function buildSanitizedChildEnv(baseEnv=process.env,extra){let clean={};for(let[k,v]of Object.entries(baseEnv)){if(v===void 0)continue;if(SCRUBBED_ENV_EXACT.has(k)||SCRUBBED_ENV_PREFIX_RE.test(k))continue;clean[k]=v}if(extra!==void 0)for(let[k,v]of Object.entries(extra)){if(SCRUBBED_ENV_EXACT.has(k)||SCRUBBED_ENV_PREFIX_RE.test(k))continue;clean[k]=v}return clean}function parseIpv4Octets(ip){let parts=ip.split(".");if(parts.length!==4)return null;let nums=[];for(let part of parts){if(!/^\d{1,3}$/.test(part))return null;let n=Number(part);if(!Number.isInteger(n)||n<0||n>255)return null;nums.push(n)}return[nums[0],nums[1],nums[2],nums[3]]}function classifyIpv4Octets(a,b,c){if(a===127)return"loopback";if(a===0)return"reserved";if(a===10)return"private";if(a===172&&b>=16&&b<=31)return"private";if(a===192&&b===168)return"private";if(a===169&&b===254)return"link-local";if(a===100&&b>=64&&b<=127)return"cgnat";if(a===192&&b===0&&(c===0||c===2))return"reserved";if(a===198&&(b===18||b===19))return"benchmark";if(a===198&&b===51&&c===100)return"reserved";if(a===203&&b===0&&c===113)return"reserved";if(a>=224)return"reserved";return"public"}function expandIpv6Groups(rawIp){let zoneIdx=rawIp.indexOf("%"),ip=(zoneIdx===-1?rawIp:rawIp.slice(0,zoneIdx)).toLowerCase(),working=ip;if(ip.includes(".")){let lastColon=ip.lastIndexOf(":");if(lastColon===-1)return null;let v4=parseIpv4Octets(ip.slice(lastColon+1));if(v4===null)return null;let hi=(v4[0]*256+v4[1]).toString(16),lo=(v4[2]*256+v4[3]).toString(16);working=`${ip.slice(0,lastColon)}:${hi}:${lo}`}let halves=working.split("::");if(halves.length>2)return null;let left=halves[0]===""?[]:halves[0].split(":"),right=halves.length===2&&halves[1]!==""?halves[1].split(":"):[],missing=8-(left.length+right.length);if(halves.length===1&&missing!==0)return null;if(halves.length===2&&missing<0)return null;let full=[...left,...Array.from({length:Math.max(0,missing)},()=>"0"),...right];if(full.length!==8)return null;let out=[];for(let hex of full){if(!/^[0-9a-f]{1,4}$/.test(hex))return null;out.push(Number.parseInt(hex,16))}return out}function classifyEmbeddedIpv4(hiGroup,loGroup){let a=Math.floor(hiGroup/256),b=hiGroup%256,c=Math.floor(loGroup/256);return classifyIpv4Octets(a,b,c)}function classifyIpAddress(rawIp){let trimmed=rawIp.trim().replace(/^\[|\]$/g,""),kind=isIP(trimmed.split("%")[0]??trimmed);if(kind===4){let octets=parseIpv4Octets(trimmed);return octets===null?"invalid":classifyIpv4Octets(octets[0],octets[1],octets[2])}if(kind!==6)return"invalid";let g=expandIpv6Groups(trimmed);if(g===null)return"invalid";let isZeroPrefix=(count)=>{for(let i=0;i<count;i+=1)if(g[i]!==0)return!1;return!0};if(isZeroPrefix(7)&&g[7]===0)return"reserved";if(isZeroPrefix(7)&&g[7]===1)return"loopback";if(isZeroPrefix(5)&&g[5]===65535||isZeroPrefix(4)&&g[4]===65535&&g[5]===0||isZeroPrefix(6))return classifyEmbeddedIpv4(g[6],g[7]);if(g[0]===100&&g[1]===65435&&g[2]===0&&g[3]===0)return classifyEmbeddedIpv4(g[6],g[7]);if(g[0]===100&&g[1]===65435&&g[2]===1)return"private";if(g[0]===8194){let embedded=classifyEmbeddedIpv4(g[1],g[2]);return embedded==="public"?"reserved":embedded}if(g[0]===8193&&g[1]===0)return"reserved";if(g[0]>=64512&&g[0]<=65023)return"private";if(g[0]>=65152&&g[0]<=65215)return"link-local";if(g[0]>=65216&&g[0]<=65279)return"private";if(g[0]>=65280)return"reserved";if(g[0]===8193&&g[1]===3512)return"reserved";return"public"}function isLoopbackIp(ip){return classifyIpAddress(ip)==="loopback"}var INTERNAL_DOMAIN_SUFFIX_RE=/\.(?:local|localhost|internal|lan|home|arpa)$/i;function isLikelyPublicFqdn(host){let lower=host.toLowerCase().replace(/\.$/,"");return lower.includes(".")&&!INTERNAL_DOMAIN_SUFFIX_RE.test(lower)&&lower!=="localhost"}async function resolveAndPinHost(options){let locale=options.locale??"zh",rawHost=options.hostname.trim().replace(/^\[|\]$/g,""),literalKind=isIP(rawHost),records;if(literalKind===4||literalKind===6)records=[{address:rawHost,family:literalKind}];else{let fn=options.lookupFn??((h)=>dnsLookup(h,{all:!0,verbatim:!0}));try{records=await fn(rawHost)}catch(error){throw new RimError("TARGET_UNREACHABLE",rimT(locale,`DNS 解析失败 (${rawHost}): ${sanitizeLine(error instanceof Error?error.message:String(error))}`,`DNS resolution failed (${rawHost}): ${sanitizeLine(error instanceof Error?error.message:String(error))}`),void 0,error)}}if(records.length===0)throw new RimError("TARGET_UNREACHABLE",rimT(locale,`DNS 未返回任何 IP 地址: ${rawHost}`,`DNS returned no addresses for host: ${rawHost}`));let allowFakeIpTunnel=literalKind===0&&isLikelyPublicFqdn(rawHost),allLoopback=!0;for(let rec of records){let cls=classifyIpAddress(rec.address);if(cls!=="loopback")allLoopback=!1;if(cls==="public")continue;if(cls==="loopback"&&options.allowLoopback)continue;if(cls==="benchmark"&&allowFakeIpTunnel)continue;throw new RimError("SSRF_BLOCKED",rimT(locale,`安全拦截 (SSRF): 目标 ${rawHost} 解析到受限地址 ${rec.address} (${cls})`,`Security error (SSRF): host ${rawHost} resolved to blocked address ${rec.address} (${cls})`),{hostname:rawHost,address:rec.address,ipClass:cls})}let chosen=records[0];return{hostname:rawHost,address:chosen.address,family:chosen.family===6?6:4,isLoopback:allLoopback}}async function isLoopbackTarget(rawUrl,lookupFn){let parsed;try{parsed=new URL(rawUrl)}catch{return!1}let host=parsed.hostname.replace(/^\[|\]$/g,""),literal=isIP(host);if(literal===4||literal===6)return isLoopbackIp(host);try{let records=await(lookupFn??((h)=>dnsLookup(h,{all:!0,verbatim:!0})))(host);return records.length>0&&records.every((r)=>isLoopbackIp(r.address))}catch{return!1}}class LifecycleGuard{stack=[];shuttingDown=!1;isShuttingDown(){return this.shuttingDown}assertNotShuttingDown(locale="zh"){if(this.shuttingDown)throw new RimError("CANCELLED",rimT(locale,"正在收尾清理中, 已冻结新子进程启动","Shutdown in progress; new child process launches are frozen"))}register(cleanup){this.stack.push(cleanup);let removed=!1;return()=>{if(removed)return;removed=!0;let idx=this.stack.lastIndexOf(cleanup);if(idx!==-1)this.stack.splice(idx,1)}}async cleanupAll(){this.shuttingDown=!0;while(this.stack.length>0){let fn=this.stack.pop();try{await fn()}catch{}}}}function toSafeHostSlug(hostOrUrl){let raw=hostOrUrl.trim();if(/^https?:\/\//i.test(raw))try{let parsed=new URL(raw);raw=parsed.port!==""?`${parsed.hostname}_${parsed.port}`:parsed.hostname}catch{}else if(/^[a-z0-9.-]+:\d{1,5}$/i.test(raw))raw=raw.replace(":","_");let lowered=raw.toLowerCase(),sanitized=lowered.replace(/[^a-z0-9._-]+/g,"_").replace(/\.{2,}/g,"_").replace(/^[_.-]+|[_.-]+$/g,""),base=sanitized===""?"host":sanitized;if(WINDOWS_RESERVED_NAMES.has(base.split(".")[0]??base))base=`_${base}`;if(base!==lowered||base.length>80){let hash=createHash3("sha256").update(lowered).digest("hex").slice(0,8);return`${base.slice(0,64).replace(/[_.-]+$/,"")||"host"}-${hash}`}return base}var HTML_ESCAPE_RE=/[&<>"'`]/g,HTML_ESCAPE_MAP={"&":"&","<":"<",">":">",'"':""","'":"'","`":"`"};function escapeHtml(input){if(!HTML_ESCAPE_RE.test(input))return input;return HTML_ESCAPE_RE.lastIndex=0,input.replace(HTML_ESCAPE_RE,(ch)=>HTML_ESCAPE_MAP[ch]??ch)}var MAX_DECOMPRESSED_BODY_BYTES=4194304,MAX_WIRE_BODY_BYTES=4194304,MAX_REDIRECT_HOPS=5;function normalizeNodeHeaders(raw){let headers={},linkHeaders=[];for(let[key,val]of Object.entries(raw)){if(val===void 0)continue;let lower=key.toLowerCase();if(Array.isArray(val)){if(headers[lower]=val.join(", "),lower==="link")linkHeaders.push(...val)}else if(headers[lower]=val,lower==="link")linkHeaders.push(val)}return{headers,linkHeaders}}function decompressBodySafe(rawBody,contentEncoding,maxBytes=MAX_DECOMPRESSED_BODY_BYTES){if(rawBody.length===0)return rawBody;let enc=(contentEncoding??"").trim().toLowerCase();try{if(enc==="br")return brotliDecompressSync(rawBody,{maxOutputLength:maxBytes});if(enc==="gzip"||enc==="x-gzip")return gunzipSync2(rawBody,{maxOutputLength:maxBytes});if(enc==="deflate")return inflateSync(rawBody,{maxOutputLength:maxBytes});return rawBody.subarray(0,maxBytes)}catch{return rawBody.subarray(0,maxBytes)}}function resolveUrlPort(parsedUrl,isHttps){if(parsedUrl.port!=="")return Number(parsedUrl.port);return isHttps?443:80}async function singlePinnedRequest(options){let{parsedUrl,pin,method,headers,timeoutMs,readBody,maxWireBytes}=options,isHttps=parsedUrl.protocol==="https:",reqFn=isHttps?httpsRequest:httpRequest,cleanHost=parsedUrl.hostname.replace(/^\[|\]$/g,""),startedAt=performance.now();return await new Promise((resolvePromise,rejectPromise)=>{let settled=!1,finish=(fn)=>{if(settled)return;settled=!0,clearTimeout(timer),options.signal?.removeEventListener("abort",onAbort),fn()},customLookup=(_hostname,optsOrCb,maybeCb)=>{let cb=typeof optsOrCb==="function"?optsOrCb:maybeCb;if(typeof cb!=="function")return;if(typeof optsOrCb==="object"&&optsOrCb!==null&&optsOrCb.all===!0)cb(null,[{address:pin.address,family:pin.family}]);else cb(null,pin.address,pin.family)},req=reqFn({protocol:parsedUrl.protocol,hostname:cleanHost,port:resolveUrlPort(parsedUrl,isHttps),path:`${parsedUrl.pathname}${parsedUrl.search}`,method,headers:{Host:parsedUrl.host,...headers},lookup:customLookup,...isHttps&&isIP2(cleanHost)===0?{servername:cleanHost}:{}},(res)=>{let ttfbMs=Math.max(0,Math.round(performance.now()-startedAt)),{headers:normHeaders,linkHeaders}=normalizeNodeHeaders(res.headers),contentEncoding=normHeaders["content-encoding"]??null,status=res.statusCode??0,isRedirectResp=status>=300&&status<400&&typeof normHeaders.location==="string"&&normHeaders.location.trim()!=="",makeResp=(wireBytes,rawBody)=>({url:parsedUrl.href,finalUrl:parsedUrl.href,redirectChain:[],status,headers:normHeaders,linkHeaders,wireBytes,contentEncoding,ttfbMs,rawBody});if(!readBody||method==="HEAD"||status===304||isRedirectResp){res.resume(),res.once("end",()=>finish(()=>resolvePromise(makeResp(0,Buffer.alloc(0))))),res.once("error",(err)=>finish(()=>rejectPromise(err)));return}let chunks=[],wireBytes=0,storedBytes=0,hardWireAbortBytes=Math.max(maxWireBytes*2,1048576),abortedForSize=!1,concatChunks=()=>chunks.length>0?Buffer.concat(chunks):Buffer.alloc(0);res.on("data",(chunk)=>{if(abortedForSize)return;let buf=Buffer.isBuffer(chunk)?chunk:Buffer.from(chunk);if(wireBytes+=buf.byteLength,storedBytes<maxWireBytes){let room=maxWireBytes-storedBytes;chunks.push(buf.byteLength<=room?buf:buf.subarray(0,room)),storedBytes+=Math.min(buf.byteLength,room)}if(wireBytes>hardWireAbortBytes)abortedForSize=!0,res.destroy(),finish(()=>resolvePromise(makeResp(wireBytes,concatChunks())))}),res.once("end",()=>finish(()=>resolvePromise(makeResp(wireBytes,concatChunks())))),res.once("error",(err)=>{if(!abortedForSize)finish(()=>rejectPromise(err))})}),onAbort=()=>{req.destroy(),finish(()=>rejectPromise(new RimError("CANCELLED",rimT(options.locale,"HTTP 探测已取消","HTTP probe cancelled"))))};if(options.signal?.aborted===!0){onAbort();return}options.signal?.addEventListener("abort",onAbort,{once:!0});let timer=setTimeout(()=>{req.destroy(),finish(()=>rejectPromise(Error(`Request timed out after ${timeoutMs}ms`)))},timeoutMs);req.once("error",(err)=>finish(()=>rejectPromise(err))),req.end()})}async function readCappedFetchBody(res,maxWireBytes){if(res.body===null){let ab=await res.arrayBuffer();return Buffer.from(ab.slice(0,maxWireBytes))}let reader=res.body.getReader(),chunks=[],collected=0;try{while(collected<maxWireBytes){let{done,value}=await reader.read();if(done||value===void 0)break;let room=maxWireBytes-collected;chunks.push(value.byteLength<=room?value:value.subarray(0,room)),collected+=Math.min(value.byteLength,room)}}finally{await reader.cancel().catch(()=>{})}return chunks.length>0?Buffer.concat(chunks):Buffer.alloc(0)}async function singleFetchStubRequest(options){let ctrl=new AbortController,onParent=()=>ctrl.abort();options.signal?.addEventListener("abort",onParent,{once:!0});let timer=setTimeout(()=>ctrl.abort(),options.timeoutMs),started=performance.now();try{let res=await options.fetchFn(options.currentUrl.href,{method:options.method,headers:options.headers,redirect:"manual",signal:ctrl.signal}),ttfbMs=Math.max(0,Math.round(performance.now()-started)),headerMap={},linkHeaders=[];for(let[k,v]of res.headers.entries()){let lk=k.toLowerCase();if(headerMap[lk]=v,lk==="link")linkHeaders.push(v)}let buf=Buffer.alloc(0),isRedir=res.status>=300&&res.status<400&&typeof headerMap.location==="string"&&headerMap.location.trim()!=="";if(options.readBody&&options.method!=="HEAD"&&res.status!==304&&!isRedir)buf=await readCappedFetchBody(res,options.maxWireBytes);else await res.body?.cancel().catch(()=>{});let clHeader=headerMap["content-length"],clNum=clHeader!==void 0?Number(clHeader):Number.NaN,wireBytes=Number.isFinite(clNum)&&clNum>=0?clNum:buf.byteLength;return{url:options.originalUrl,finalUrl:options.currentUrl.href,redirectChain:[...options.redirectChain],status:res.status,headers:headerMap,linkHeaders,wireBytes,contentEncoding:headerMap["content-encoding"]??null,ttfbMs,rawBody:buf}}finally{clearTimeout(timer),options.signal?.removeEventListener("abort",onParent)}}async function ssrfHttpRequest(options){let locale=options.locale??"zh",method=options.method??"GET",headers=options.headers??{},followRedirects=options.followRedirects!==!1,maxRedirects=options.maxRedirects??MAX_REDIRECT_HOPS,timeoutMs=options.timeoutMs??15000,readBody=options.readBody!==!1,maxWireBytes=options.maxWireBytes??MAX_WIRE_BODY_BYTES,initialParsed=assertSafeHttpUrl(options.url,locale),redirectChain=[],currentUrl=initialParsed;for(let hop=0;hop<=maxRedirects;hop+=1){if(options.signal?.aborted===!0)throw new RimError("CANCELLED",rimT(locale,"HTTP 探测已取消","HTTP probe cancelled"));let response;if(options.fetchFn!==void 0)response=await singleFetchStubRequest({fetchFn:options.fetchFn,originalUrl:options.url,currentUrl,redirectChain,method,headers,timeoutMs,readBody,maxWireBytes,signal:options.signal});else{let pin=await resolveAndPinHost({hostname:currentUrl.hostname,allowLoopback:options.allowLoopback,locale,lookupFn:options.lookupFn});response=await singlePinnedRequest({parsedUrl:currentUrl,pin,method,headers,timeoutMs,readBody,maxWireBytes,locale,signal:options.signal})}let isRedirect=response.status>=300&&response.status<400&&typeof response.headers.location==="string"&&response.headers.location.trim()!=="";if(!followRedirects||!isRedirect)return{...response,url:options.url,finalUrl:currentUrl.href,redirectChain:[...redirectChain]};if(hop===maxRedirects)throw new RimError("TARGET_UNREACHABLE",rimT(locale,`超过最大重定向跳数 (${maxRedirects})`,`Maximum redirect hops exceeded (${maxRedirects})`));let nextUrl;try{nextUrl=new URL(response.headers.location,currentUrl)}catch{throw new RimError("SSRF_BLOCKED",rimT(locale,`重定向 Location 非法: ${response.headers.location}`,`Invalid redirect Location: ${response.headers.location}`))}assertSafeHttpUrl(nextUrl.href,locale),redirectChain.push(nextUrl.href),currentUrl=nextUrl}throw new RimError("TARGET_UNREACHABLE",rimT(locale,"超过最大重定向跳数","Maximum redirect hops exceeded"))}function resolveBaselineCacheRoot(options={}){if(options.cacheDir!==void 0&&options.cacheDir.trim()!=="")return resolve4(options.cacheDir.trim());let env=options.env??process.env,xdgCache=env.XDG_CACHE_HOME?.trim()||"";if(xdgCache!=="")return join9(resolve4(xdgCache),"rim");let home=env.HOME?.trim()||env.USERPROFILE?.trim()||homedir();return join9(resolve4(home),".cache","rim")}function resolveSafeHostFile(options){let locale=options.locale??"zh",root=resolveBaselineCacheRoot(options);if(options.createDir===!0)mkdirSync5(root,{recursive:!0});let slug=toSafeHostSlug(options.hostOrUrl),hostDir=join9(root,slug);if(existsSync13(root)){let realRoot=(realpathSync6.native??realpathSync6)(root),hostDirLstat=null;try{hostDirLstat=lstatSync5(hostDir)}catch{hostDirLstat=null}if(hostDirLstat!==null){if(hostDirLstat.isSymbolicLink()&&!existsSync13(hostDir))throw new RimError("BASELINE_ERROR",rimT(locale,`安全拦截: 基线目录为悬空符号链接 (${slug})`,`Security error: baseline directory is a dangling symlink (${slug})`));let realHost=(realpathSync6.native??realpathSync6)(hostDir);if(!isPathWithinRoot(realRoot,realHost))throw new RimError("BASELINE_ERROR",rimT(locale,`安全拦截: 基线目录符号链接逃出缓存根 (${slug})`,`Security error: baseline directory symlink escapes cache root (${slug})`))}else if(options.createDir===!0)mkdirSync5(hostDir,{recursive:!0});let filePath=join9(hostDir,"history.jsonl"),fileLstat=null;try{fileLstat=lstatSync5(filePath)}catch{fileLstat=null}if(fileLstat!==null){if(fileLstat.isSymbolicLink()&&!existsSync13(filePath))throw new RimError("BASELINE_ERROR",rimT(locale,`安全拦截: 基线历史文件为悬空符号链接 (${slug})`,`Security error: baseline history file is a dangling symlink (${slug})`));let realFile=(realpathSync6.native??realpathSync6)(filePath);if(!isPathWithinRoot(realRoot,realFile))throw new RimError("BASELINE_ERROR",rimT(locale,`安全拦截: 基线历史文件符号链接逃出缓存根 (${slug})`,`Security error: baseline history file symlink escapes cache root (${slug})`))}return{root:realRoot,slug,filePath}}return{root,slug,filePath:join9(hostDir,"history.jsonl")}}function parseBaselineJsonl(text){let out=[],len=text.length,pos=0;while(pos<len){let nl=text.indexOf(`
|
|
29
|
+
`,pos);if(nl===-1)nl=len;let trimmed=text.slice(pos,nl).trim();if(pos=nl+1,trimmed==="")continue;try{let parsed=JSON.parse(trimmed);if(parsed!==null&&typeof parsed==="object"&&typeof parsed.timestamp==="string"&&typeof parsed.host==="string"&&parsed.metrics!==void 0&&typeof parsed.metrics==="object")out.push(parsed)}catch{}}return out}function extractBaselineEntry(report,timestamp=new Date().toISOString(),hostOverride){let protoProbe=report.probes.find((p)=>p.id==="proto"),secProbe=report.probes.find((p)=>p.id==="sec"),loadProbe=report.probes.find((p)=>p.id==="load"),mobileSum=report.lighthouse.summaries.find((s)=>s.preset==="mobile"),desktopSum=report.lighthouse.summaries.find((s)=>s.preset==="desktop"),toDev=(s)=>s===void 0?void 0:{performance:s.scores.performance??null,accessibility:s.scores.accessibility??null,bestPractices:s.scores["best-practices"]??null,seo:s.scores.seo??null,longTasks:s.longTasks.length,tbtMs:s.metrics.tbtMs,cls:s.metrics.clsValue},numOrNull=(v)=>typeof v==="number"&&Number.isFinite(v)?v:null,mobile=toDev(mobileSum),desktop=toDev(desktopSum);return{schemaVersion:1,timestamp,targetUrl:report.targetUrl,host:toSafeHostSlug(hostOverride!==void 0&&hostOverride.trim()!==""?hostOverride:report.targetUrl),preset:report.preset,passed:report.passed,metrics:{...protoProbe!==void 0?{htmlBrBytes:numOrNull(protoProbe.metrics.htmlBrBytes),totalCriticalBrBytes:numOrNull(protoProbe.metrics.totalCriticalBrBytes),ttfbMs:numOrNull(protoProbe.metrics.ttfbMs)}:{},...mobile!==void 0?{mobile}:{},...desktop!==void 0?{desktop}:{},...secProbe!==void 0?{secWarnings:numOrNull(secProbe.metrics.warnings)??0,secFailures:numOrNull(secProbe.metrics.failures)??0}:{},...loadProbe!==void 0&&loadProbe.status!=="SKIP"?{loadRps:numOrNull(loadProbe.metrics.rps),loadP95Ms:numOrNull(loadProbe.metrics.p95Ms)}:{}}}}function saveBaselineEntry(entry,options={}){let{filePath}=resolveSafeHostFile({hostOrUrl:entry.host||entry.targetUrl,cacheDir:options.cacheDir,env:options.env,createDir:!0,locale:options.locale});return appendFileSync(filePath,`${JSON.stringify(entry)}
|
|
30
|
+
`,"utf8"),filePath}function loadBaselineHistory(hostOrUrl,options={}){let{filePath}=resolveSafeHostFile({hostOrUrl,cacheDir:options.cacheDir,env:options.env,createDir:!1,locale:options.locale});if(!existsSync13(filePath))return[];return parseBaselineJsonl(readFileSync10(filePath,"utf8"))}function pushDelta(deltas,metric,before,after,unit,higherIsBetter){let b=before??null,a=after??null;if(b===null&&a===null)return;if(b===null||a===null){deltas.push({metric,before:b,after:a,delta:null,unit,direction:"unchanged"});return}let diff=Math.round((a-b)*1000)/1000,direction="unchanged";if(diff!==0)direction=(higherIsBetter?diff>0:diff<0)?"improved":"regressed";deltas.push({metric,before:b,after:a,delta:diff,unit,direction})}function computeBaselineDiff(previous,current){let deltas=[],pm=previous?.metrics,cm=current.metrics;pushDelta(deltas,"htmlBrBytes",pm?.htmlBrBytes,cm.htmlBrBytes,"B",!1),pushDelta(deltas,"totalCriticalBrBytes",pm?.totalCriticalBrBytes,cm.totalCriticalBrBytes,"B",!1),pushDelta(deltas,"ttfbMs",pm?.ttfbMs,cm.ttfbMs,"ms",!1);for(let dev of["mobile","desktop"]){let pd=pm?.[dev],cd=cm[dev];if(pd===void 0&&cd===void 0)continue;pushDelta(deltas,`${dev}.performance`,pd?.performance,cd?.performance,"pts",!0),pushDelta(deltas,`${dev}.accessibility`,pd?.accessibility,cd?.accessibility,"pts",!0),pushDelta(deltas,`${dev}.bestPractices`,pd?.bestPractices,cd?.bestPractices,"pts",!0),pushDelta(deltas,`${dev}.seo`,pd?.seo,cd?.seo,"pts",!0),pushDelta(deltas,`${dev}.longTasks`,pd?.longTasks,cd?.longTasks,"",!1),pushDelta(deltas,`${dev}.tbtMs`,pd?.tbtMs,cd?.tbtMs,"ms",!1),pushDelta(deltas,`${dev}.cls`,pd?.cls,cd?.cls,"",!1)}pushDelta(deltas,"secFailures",pm?.secFailures,cm.secFailures,"",!1),pushDelta(deltas,"secWarnings",pm?.secWarnings,cm.secWarnings,"",!1),pushDelta(deltas,"loadRps",pm?.loadRps,cm.loadRps,"req/s",!0),pushDelta(deltas,"loadP95Ms",pm?.loadP95Ms,cm.loadP95Ms,"ms",!1);let regressedCount=deltas.filter((d)=>d.direction==="regressed").length,improvedCount=deltas.filter((d)=>d.direction==="improved").length;return{host:current.host,previousTimestamp:previous?.timestamp??null,currentTimestamp:current.timestamp,deltas,regressedCount,improvedCount}}function listBaselineHosts(options={}){let root=resolveBaselineCacheRoot(options);if(!existsSync13(root))return[];let realRoot=(realpathSync6.native??realpathSync6)(root),out=[];for(let entry of readdirSync2(realRoot,{withFileTypes:!0})){if(!entry.isDirectory())continue;let histPath=join9(realRoot,entry.name,"history.jsonl");if(!existsSync13(histPath))continue;let realHist=(realpathSync6.native??realpathSync6)(histPath);if(!isPathWithinRoot(realRoot,realHist))continue;let records=parseBaselineJsonl(readFileSync10(realHist,"utf8")),latest=records[records.length-1];out.push({host:entry.name,entries:records.length,latestTimestamp:latest?.timestamp??null,latestTargetUrl:latest?.targetUrl??null,latestPassed:latest?.passed??null})}return out.sort((a,b)=>a.host.localeCompare(b.host))}function pruneBaselineHistory(hostOrUrl,keep=10,options={}){let safeKeep=Math.max(0,Math.round(keep)),{slug,filePath}=resolveSafeHostFile({hostOrUrl,cacheDir:options.cacheDir,env:options.env,createDir:!1,locale:options.locale});if(!existsSync13(filePath))return{host:slug,before:0,after:0};let records=parseBaselineJsonl(readFileSync10(filePath,"utf8")),retained=safeKeep===0?[]:records.slice(-safeKeep),content=retained.length>0?`${retained.map((r)=>JSON.stringify(r)).join(`
|
|
31
|
+
`)}
|
|
32
|
+
`:"";return writeFileSync5(filePath,content,"utf8"),{host:slug,before:records.length,after:retained.length}}import{existsSync as existsSync15,realpathSync as realpathSync8}from"node:fs";import{join as join11,resolve as resolve6}from"node:path";import{pathToFileURL}from"node:url";import{spawn as spawn2}from"node:child_process";import{win32 as win3214}from"node:path";var SHELL_META_RE=/[;&|`$<>()\r\n\0]/,CMD_BATCH_EXT_RE=/\.(?:cmd|bat)$/i,CMD_META_OR_SPACE_RE2=/[\s&|<>^()%!=;,]/,CMD_FORBIDDEN_RE2=/[\r\n\0"]/,CMD_PERCENT_HAZARD_RE=/[&|<>^()]/;function wrapCmdQuotes(segment){return`"${segment.replace(/(\\+)$/,"$1$1")}"`}function escapeWin32BatchToken(token,isPath){if(CMD_FORBIDDEN_RE2.test(token))return null;if(token.includes("%")&&CMD_PERCENT_HAZARD_RE.test(token))return null;if(token==="")return isPath?null:'""';if(!isPath&&!CMD_META_OR_SPACE_RE2.test(token))return token;if(!/[%!]/.test(token))return wrapCmdQuotes(token);let esc=isPath?"^":"^^^",out="",buf="";for(let ch of token)if(ch==="%"||ch==="!"){if(buf!=="")out+=wrapCmdQuotes(buf),buf="";out+=`${esc}${ch}`}else buf+=ch;if(buf!=="")out+=wrapCmdQuotes(buf);return out}function buildSafeSpawnInvocation(binPath,args,options={}){let platform=options.platform??process.platform,env=options.env??process.env,locale=options.locale??"zh";if(platform!=="win32"||!CMD_BATCH_EXT_RE.test(binPath))return{command:binPath,args:[...args]};let all=[binPath,...args];if(all.some((t)=>t.includes("%"))&&all.some((t)=>CMD_PERCENT_HAZARD_RE.test(t)))throw new RimError("INVALID_ARGUMENT",rimT(locale,"安全拦截: Windows 批处理参数禁止同时包含 % 与元字符 (&|<>^())","Security error: Windows batch arguments cannot combine % with shell metacharacters"));let escPath=escapeWin32BatchToken(binPath,!0);if(escPath===null)throw new RimError("INVALID_ARGUMENT",rimT(locale,`安全拦截: 批处理路径包含非法字符 (${binPath})`,`Security error: invalid characters in batch executable path (${binPath})`));let escArgs=[];for(let arg of args){let escaped=escapeWin32BatchToken(arg,!1);if(escaped===null)throw new RimError("INVALID_ARGUMENT",rimT(locale,"安全拦截: Windows 批处理参数包含禁止字符 (双引号或换行)","Security error: Windows batch argument contains forbidden characters (quotes/newlines)"));escArgs.push(escaped)}let rawComSpec=env.ComSpec?.trim()||env.COMSPEC?.trim()||"",comSpec=rawComSpec!==""&&isPlatformAbsolutePath(rawComSpec,"win32")?rawComSpec:win3214.join(env.SystemRoot?.trim()||"C:\\Windows","System32","cmd.exe"),cmdLine=escArgs.length>0?`${escPath} ${escArgs.join(" ")}`:escPath;return{command:comSpec,args:["/d","/s","/c",`"${cmdLine}"`],windowsVerbatimArguments:!0}}function splitSafeCommand(command,locale="zh"){if(SHELL_META_RE.test(command))throw new RimError("INVALID_ARGUMENT",rimT(locale,"命令桥接禁止包含 shell 元字符 (;&|`$<>()), 请使用 argv 数组或纯净命令参数","Command bridge forbids shell metacharacters (;&|`$<>()); pass a clean command or argv array"));let tokens=[],current="",quote="";for(let i=0;i<command.length;i+=1){let ch=command[i];if(quote!==""){if(ch===quote)quote="";else current+=ch;continue}if(ch==='"'||ch==="'"){quote=ch;continue}if(/\s/.test(ch)){if(current!=="")tokens.push(current),current="";continue}current+=ch}if(quote!=="")throw new RimError("INVALID_ARGUMENT",rimT(locale,"命令桥接存在未闭合引号","Unclosed quote in command bridge"));if(current!=="")tokens.push(current);if(tokens.length===0)throw new RimError("INVALID_ARGUMENT",rimT(locale,"命令桥接不能为空","Command bridge cannot be empty"));return tokens}function signalProcessTree(child,sig){let pid=child.pid;if(process.platform!=="win32"&&typeof pid==="number"&&pid>0)try{process.kill(-pid,sig);return}catch{}try{child.kill(sig)}catch{}}async function startCommandBridge(options){let{projectRoot,bridge,entryPath,locale,signal}=options,fetchFn=options.fetchFn??fetch,isAborted=()=>signal?.aborted===!0;if(isAborted())throw new RimError("CANCELLED",rimT(locale,"命令桥接启动已取消","Command bridge startup cancelled"));let argv=[];if(bridge.argv!==void 0&&bridge.argv.length>0)argv=[...bridge.argv];else if(bridge.command!==void 0)argv=splitSafeCommand(bridge.command,locale);if(argv.length===0)throw new RimError("CONFIG_INVALID",rimT(locale,"command 桥接缺少 argv 或 command","Command bridge requires argv or command"));let rawBin=argv[0],resolvedBin=null;if(isPlatformAbsolutePath(rawBin))resolvedBin=isExistingFile(rawBin)?rawBin:null;else resolvedBin=resolveAbsoluteFromPath([rawBin]);if(resolvedBin===null)throw new RimError("BRIDGE_FAILED",rimT(locale,`无法在绝对 PATH 中找到命令桥接可执行文件: ${rawBin}`,`Command bridge executable not found in absolute PATH: ${rawBin}`));let port=typeof options.port==="number"&&Number.isInteger(options.port)&&options.port>0?options.port:await allocateFreePort(),expandedArgs=argv.slice(1).map((arg)=>arg.replaceAll("{{port}}",String(port)).replaceAll("{port}",String(port))),invocation=buildSafeSpawnInvocation(resolvedBin,expandedArgs,{locale}),origin=`http://127.0.0.1:${port}`,entryUrl=resolveSameOriginUrl(origin,entryPath,locale,"path"),readyUrl=resolveSameOriginUrl(origin,bridge.readyPath??entryPath,locale,"readyPath"),readyTimeoutMs=bridge.readyTimeoutMs??15000,child=spawn2(invocation.command,[...invocation.args],{cwd:projectRoot,env:{...buildSanitizedChildEnv(process.env,bridge.env),HOST:"127.0.0.1",PORT:String(port)},stdio:["ignore","ignore","pipe"],detached:process.platform!=="win32",windowsHide:!0,...invocation.windowsVerbatimArguments===!0?{windowsVerbatimArguments:!0}:{}}),exited=!1,exitCode=null,stderrBuf="";child.stderr?.setEncoding("utf8"),child.stderr?.on("data",(chunk)=>{if(stderrBuf.length<2048)stderrBuf+=chunk});let exitPromise=new Promise((res)=>{child.once("exit",(code)=>{exited=!0,exitCode=code,res()}),child.once("error",()=>{exited=!0,res()})}),stopped=!1,stop=async()=>{if(stopped)return;if(stopped=!0,exited)return;if(signalProcessTree(child,"SIGTERM"),await waitWithTimeout(exitPromise,2500),!exited)signalProcessTree(child,"SIGKILL"),await waitWithTimeout(exitPromise,1000)};try{let deadline=Date.now()+readyTimeoutMs;while(Date.now()<deadline){if(isAborted())throw new RimError("CANCELLED",rimT(locale,"命令桥接启动已取消","Command bridge startup cancelled"));if(exited){let detail=sanitizeLine(stderrBuf).slice(0,240);throw new RimError("BRIDGE_FAILED",rimT(locale,`命令桥接在就绪前退出 (exit=${String(exitCode)})${detail!==""?`: ${detail}`:""}`,`Command bridge exited before becoming ready (exit=${String(exitCode)})${detail!==""?`: ${detail}`:""}`))}let remainingMs=deadline-Date.now();if(remainingMs<=0)break;let probeCtrl=new AbortController,onParentAbort=()=>probeCtrl.abort();signal?.addEventListener("abort",onParentAbort,{once:!0});let probeTimer=setTimeout(()=>probeCtrl.abort(),Math.min(remainingMs,1500));try{let resp=await fetchFn(readyUrl,{signal:probeCtrl.signal});if(await resp.body?.cancel().catch(()=>{}),resp.status<500)return{url:entryUrl,origin,mode:"command",detail:argv.join(" "),isLocal:!0,stop}}catch{}finally{clearTimeout(probeTimer),signal?.removeEventListener("abort",onParentAbort)}let sleepBudget=Math.min(40,Math.max(0,deadline-Date.now()));if(sleepBudget>0)await sleepMs(sleepBudget,signal)}throw new RimError("BRIDGE_FAILED",rimT(locale,`命令桥接 ${readyUrl} 未在 ${readyTimeoutMs}ms 内就绪`,`Command bridge ${readyUrl} did not become ready within ${readyTimeoutMs}ms`))}catch(error){throw await stop(),error}}import{existsSync as existsSync14,realpathSync as realpathSync7,statSync as statSync3}from"node:fs";import{readFile}from"node:fs/promises";import{extname,join as join10,posix as posix12,resolve as resolve5}from"node:path";var MIME_TYPES={".html":"text/html; charset=utf-8",".htm":"text/html; charset=utf-8",".js":"text/javascript; charset=utf-8",".mjs":"text/javascript; charset=utf-8",".css":"text/css; charset=utf-8",".json":"application/json; charset=utf-8",".map":"application/json; charset=utf-8",".svg":"image/svg+xml",".wasm":"application/wasm",".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".webp":"image/webp",".avif":"image/avif",".gif":"image/gif",".ico":"image/x-icon",".woff":"font/woff",".woff2":"font/woff2",".txt":"text/plain; charset=utf-8",".xml":"application/xml; charset=utf-8"},STATIC_ASSET_EXT_RE=/\.(?:js|mjs|css|map|json|png|jpe?g|webp|avif|gif|svg|ico|wasm|woff2?|ttf|eot|txt|xml)$/i;function extractPathname(rawUrl){let schemeEnd=rawUrl.indexOf("://"),start=schemeEnd===-1?0:schemeEnd+3,slash=rawUrl.indexOf("/",start),query=rawUrl.indexOf("?",start),hash=rawUrl.indexOf("#",start),delim=-1;if(query!==-1&&hash!==-1)delim=query<hash?query:hash;else if(query!==-1)delim=query;else delim=hash;if(slash===-1||delim!==-1&&delim<slash)return"/";if(delim===-1)return rawUrl.slice(slash);return rawUrl.slice(slash,delim)}var BR_FAST_RE=/(?:^|[,\s])br(?:[,\s]|$)/i,GZ_FAST_RE=/(?:^|[,\s])gzip(?:[,\s]|$)/i;function acceptsEncoding(header,encoding){if(header===null||header===void 0||header==="")return!1;if(!header.includes(";")&&!header.includes("*"))return encoding==="br"?BR_FAST_RE.test(header):GZ_FAST_RE.test(header);let wildcardQ=null;for(let rawPart of header.split(",")){let segments=rawPart.trim().toLowerCase().split(";"),name=(segments[0]??"").trim();if(name==="")continue;let q=1;for(let i=1;i<segments.length;i+=1){let param=segments[i].trim();if(!param.startsWith("q="))continue;let parsed=Number.parseFloat(param.slice(2).trim());q=Number.isFinite(parsed)?parsed:1}if(name===encoding)return q>0;if(name==="*")wildcardQ=q}return wildcardQ!==null&&wildcardQ>0}function normalizeBasePath(raw){if(raw===void 0)return"";let trimmed=raw.trim();if(trimmed===""||trimmed==="/")return"";return(trimmed.startsWith("/")?trimmed:`/${trimmed}`).replace(/\/+$/,"")}function normalizeStaticPath(rawPathname,basePath=""){let decoded;try{decoded=decodeURIComponent(rawPathname)}catch{return null}if(/\p{Cc}/u.test(decoded))return null;if(decoded.includes("\\"))return null;if(decoded.split("/").includes(".."))return null;let normBase=normalizeBasePath(basePath),target=decoded;if(normBase!==""){if(target===normBase||target===`${normBase}/`)target="/";else if(target.startsWith(`${normBase}/`))target=target.slice(normBase.length)}let normalized=posix12.normalize(target.startsWith("/")?target:`/${target}`);if(normalized.split("/").includes("..")||!normalized.startsWith("/"))return null;if(normalized==="/"||normalized.endsWith("/"))return`${normalized}index.html`;return normalized}function isInsideRoot(realRoot,candidatePath){if(!existsSync14(candidatePath))return null;let realCandidate;try{realCandidate=(realpathSync7.native??realpathSync7)(candidatePath)}catch{return null}if(!isPathWithinRoot(realRoot,realCandidate))return null;try{if(!statSync3(realCandidate).isFile())return null}catch{return null}return realCandidate}function buildNotFoundResponse(){return new Response("Not Found",{status:404,headers:{"Content-Type":"text/plain; charset=utf-8","Cache-Control":"no-store","X-Content-Type-Options":"nosniff"}})}function pickCompressedVariant(realRoot,basePath,acceptEncoding){if(acceptsEncoding(acceptEncoding,"br")){let br=isInsideRoot(realRoot,`${basePath}.br`);if(br!==null)return{filePath:br,encoding:"br"}}if(acceptsEncoding(acceptEncoding,"gzip")){let gz=isInsideRoot(realRoot,`${basePath}.gz`);if(gz!==null)return{filePath:gz,encoding:"gzip"}}return{filePath:basePath}}async function createStaticSiteServer(options){let locale=options.locale??"zh",absDir=resolve5(options.dir);if(!existsSync14(absDir))throw new RimError("BRIDGE_FAILED",rimT(locale,`静态站点目录不存在: ${absDir}`,`Static site directory does not exist: ${absDir}`));let realRoot=(realpathSync7.native??realpathSync7)(absDir);if(!statSync3(realRoot).isDirectory())throw new RimError("BRIDGE_FAILED",rimT(locale,`静态站点路径不是目录: ${absDir}`,`Static site path is not a directory: ${absDir}`));let basePath=normalizeBasePath(options.basePath),spaFallback=options.spaFallback!==!1,server=await startFetchServer(async(req)=>{let method=req.method.toUpperCase();if(method!=="GET"&&method!=="HEAD")return new Response("Method Not Allowed",{status:405,headers:{Allow:"GET, HEAD","Content-Type":"text/plain; charset=utf-8","Cache-Control":"no-store","X-Content-Type-Options":"nosniff"}});let rawPath=extractPathname(req.url),relPath=normalizeStaticPath(rawPath,basePath);if(relPath===null)return buildNotFoundResponse();let resolvedRel=relPath,absCandidate=join10(realRoot,relPath.slice(1)),safeFile=isInsideRoot(realRoot,absCandidate);if(safeFile===null){if(!spaFallback||STATIC_ASSET_EXT_RE.test(relPath))return buildNotFoundResponse();if(resolvedRel="/index.html",absCandidate=join10(realRoot,"index.html"),safeFile=isInsideRoot(realRoot,absCandidate),safeFile===null)return buildNotFoundResponse()}let chosen=pickCompressedVariant(realRoot,safeFile,req.headers.get("accept-encoding")),st;try{st=statSync3(chosen.filePath)}catch{return buildNotFoundResponse()}let ext=extname(resolvedRel).toLowerCase(),isHtml=ext===".html"||ext===".htm",contentType=MIME_TYPES[ext]??"application/octet-stream",etag=`"${st.size.toString(16)}-${Math.trunc(st.mtimeMs).toString(16)}-${chosen.encoding??"raw"}"`,headers={"Content-Type":contentType,"Content-Length":String(st.size),"Cache-Control":isHtml?"no-cache, must-revalidate":"public, max-age=3600",Vary:"Accept-Encoding",ETag:etag,"Last-Modified":new Date(st.mtimeMs).toUTCString(),"X-Content-Type-Options":"nosniff","Referrer-Policy":"strict-origin-when-cross-origin","X-Frame-Options":"SAMEORIGIN",...chosen.encoding!==void 0?{"Content-Encoding":chosen.encoding}:{}};if(req.headers.get("if-none-match")===etag)return new Response(null,{status:304,headers});if(method==="HEAD")return new Response(null,{status:200,headers});let bunResponse=createBunFileResponse(chosen.filePath,headers);if(bunResponse!==null)return bunResponse;let bytes=await readFile(chosen.filePath);return new Response(bytes,{status:200,headers})},"127.0.0.1"),rawEntry=options.entryPath?.trim()??"",targetUrl;if(rawEntry===""||rawEntry==="/")targetUrl=basePath!==""?`${server.url}${basePath}/`:`${server.url}/`;else{let safeUrl=resolveSameOriginUrl(server.url,rawEntry,locale,"entryPath"),parsedEntry=new URL(safeUrl),entryPathOnly=parsedEntry.pathname;if(basePath!==""&&entryPathOnly!==basePath&&!entryPathOnly.startsWith(`${basePath}/`))targetUrl=`${server.url}${basePath}${entryPathOnly}${parsedEntry.search}${parsedEntry.hash}`;else targetUrl=safeUrl}return{url:targetUrl,origin:server.url,mode:"static",detail:realRoot,isLocal:!0,stop:server.stop}}var AUTO_STATIC_CANDIDATES=["dist/web","dist","build","out","public","."];function detectDefaultStaticDir(projectRoot){for(let rel of AUTO_STATIC_CANDIDATES){let dirAbs=resolve6(projectRoot,rel);if(existsSync15(join11(dirAbs,"index.html")))return dirAbs}return null}function normalizeEntryPath(rawPath){let trimmed=rawPath?.trim()??"";if(trimmed===""||trimmed==="/")return"/";return trimmed.startsWith("/")?trimmed:`/${trimmed}`}function assertPathWithinProject(projectRoot,targetPath,locale){let realRoot=(realpathSync8.native??realpathSync8)(resolve6(projectRoot)),absTarget=resolve6(projectRoot,targetPath);if(!existsSync15(absTarget))throw new RimError("BRIDGE_FAILED",rimT(locale,`模块桥接入口不存在: ${targetPath}`,`Module bridge entry does not exist: ${targetPath}`));let realTarget=(realpathSync8.native??realpathSync8)(absTarget);if(!isPathWithinRoot(realRoot,realTarget))throw new RimError("BRIDGE_FAILED",rimT(locale,`安全拦截: 模块桥接路径不可逃出项目根目录 (${targetPath})`,`Security error: module bridge path must stay within project root (${targetPath})`));return realTarget}async function resolveModuleServer(mod,bridge,locale){if(bridge.beforeStart!==void 0&&bridge.beforeStart!==""){let hook=mod[bridge.beforeStart];if(typeof hook!=="function")throw new RimError("BRIDGE_FAILED",rimT(locale,`模块桥接缺少 beforeStart 导出函数: ${bridge.beforeStart}`,`Module bridge missing beforeStart export function: ${bridge.beforeStart}`));await hook()}let kind=bridge.exportKind??"auto",rawExport=bridge.export!==void 0&&bridge.export!==""?mod[bridge.export]:mod.startRimServer??mod.fetch??mod.handleRequest??mod.default;if(rawExport===void 0)throw new RimError("BRIDGE_FAILED",rimT(locale,`模块桥接未找到可用导出 (${bridge.export??"startRimServer | fetch | handleRequest | default"})`,`Module bridge did not expose a usable export (${bridge.export??"startRimServer | fetch | handleRequest | default"})`));if(kind==="server"||kind==="auto"&&bridge.export===void 0&&typeof mod.startRimServer==="function"){let started=await rawExport();if(typeof started?.url!=="string")throw new RimError("BRIDGE_FAILED",rimT(locale,"server 桥接未返回有效的 { url } 对象","Server bridge did not return a valid { url } object"));return{customServer:{url:started.url,stop:async()=>{await started.stop?.()}}}}if(kind==="factory"){if(typeof rawExport!=="function")throw new RimError("BRIDGE_FAILED",rimT(locale,"factory 桥接导出必须为函数","Factory bridge export must be a function"));let created=await rawExport();if(typeof created?.fetch!=="function")throw new RimError("BRIDGE_FAILED",rimT(locale,"factory 桥接返回值缺少 fetch 函数","Factory bridge return value is missing a fetch function"));return{fetch:created.fetch}}if(typeof rawExport==="object"&&rawExport!==null&&typeof rawExport.fetch==="function")return{fetch:rawExport.fetch};if(typeof rawExport==="function")return{fetch:rawExport};throw new RimError("BRIDGE_FAILED",rimT(locale,"模块桥接导出形态不受支持","Unsupported module bridge export shape"))}function assertRequiredFilesExist(projectRoot,requireFiles,hint,locale){if(requireFiles===void 0||requireFiles.length===0)return;let realRoot=(realpathSync8.native??realpathSync8)(resolve6(projectRoot));for(let reqFile of requireFiles){let absReq=resolve6(projectRoot,reqFile);if(!isPathWithinRoot(realRoot,absReq))throw new RimError("BRIDGE_FAILED",rimT(locale,`安全拦截: requireFiles 路径不可逃出项目根目录 (${reqFile})`,`Security error: requireFiles path must stay within project root (${reqFile})`));if(!existsSync15(absReq)){let hintText=hint!==void 0&&hint.trim()!==""?hint.trim():rimT(locale,"请先执行项目构建后再运行 rim","build the project before running rim");throw new RimError("BRIDGE_FAILED",rimT(locale,`缺少前置构建产物 ${reqFile}, ${hintText}`,`Missing required build artifact ${reqFile}; ${hintText}`),{requireFile:reqFile,hint:hintText})}let realReq=(realpathSync8.native??realpathSync8)(absReq);if(!isPathWithinRoot(realRoot,realReq))throw new RimError("BRIDGE_FAILED",rimT(locale,`安全拦截: requireFiles 符号链接不可逃出项目根目录 (${reqFile})`,`Security error: requireFiles symlink must stay within project root (${reqFile})`))}}async function startModuleBridge(projectRoot,bridge,entryPath,locale){if(bridge.entry===void 0||bridge.entry.trim()==="")throw new RimError("CONFIG_INVALID",rimT(locale,"module 桥接缺少 entry 文件路径","Module bridge is missing entry file path"));assertRequiredFilesExist(projectRoot,bridge.requireFiles,bridge.requireFilesHint,locale);let safeEntry=assertPathWithinProject(projectRoot,bridge.entry,locale),mod;try{mod=await import(pathToFileURL(safeEntry).href)}catch(error){throw new RimError("BRIDGE_FAILED",rimT(locale,`加载模块桥接失败 (${bridge.entry}): ${sanitizeLine(error instanceof Error?error.message:String(error))}`,`Failed to load module bridge (${bridge.entry}): ${sanitizeLine(error instanceof Error?error.message:String(error))}`),void 0,error)}let resolved=await resolveModuleServer(mod,bridge,locale);if(resolved.customServer!==void 0){let parsed=assertSafeHttpUrl(resolved.customServer.url,locale);return{url:entryPath==="/"?parsed.href:resolveSameOriginUrl(parsed.origin,entryPath,locale,"path"),origin:parsed.origin,mode:"module",detail:`${bridge.entry} (${bridge.export??"startRimServer"})`,isLocal:!0,stop:resolved.customServer.stop}}let server=await startFetchServer(resolved.fetch,"127.0.0.1"),targetUrl;try{targetUrl=resolveSameOriginUrl(server.url,entryPath,locale,"path")}catch(error){throw await server.stop().catch(()=>{}),error}return{url:targetUrl,origin:server.url,mode:"module",detail:`${bridge.entry}${bridge.export!==void 0?`#${bridge.export}`:""}`,isLocal:!0,stop:server.stop}}async function startTargetBridge(options){let{projectRoot,locale,signal,fetchFn}=options,entryPath=normalizeEntryPath(options.path);if(options.localOnly!==!0&&options.url!==void 0&&options.url.trim()!==""){let parsed=assertSafeHttpUrl(options.url.trim(),locale),explicitPath=options.path?.trim(),resolvedUrl=explicitPath!==void 0&&explicitPath!==""?resolveSameOriginUrl(parsed.origin,explicitPath,locale,"path"):parsed.href,isLocalHost=parsed.hostname==="127.0.0.1"||parsed.hostname==="localhost"||parsed.hostname==="::1"||parsed.hostname==="[::1]";return{url:resolvedUrl,origin:parsed.origin,mode:"url",detail:resolvedUrl,isLocal:isLocalHost,stop:async()=>{}}}assertRequiredFilesExist(projectRoot,options.local?.requireFiles,options.local?.requireFilesHint,locale);let effectiveBridge=options.bridge??options.local?.bridge,explicitPort=options.local?.port;if(effectiveBridge===void 0&&options.local?.startCommand!==void 0&&options.local.startCommand.length>0)effectiveBridge={type:"command",argv:options.local.startCommand,readyPath:options.local.healthPath??entryPath,readyTimeoutMs:options.local.startupTimeoutMs??15000,...options.local.env!==void 0?{env:options.local.env}:{}};let bridge=effectiveBridge??{type:"auto"};if(bridge.type==="module")return await startModuleBridge(projectRoot,bridge,entryPath,locale);if(bridge.type==="command")return await startCommandBridge({projectRoot,bridge,port:explicitPort,entryPath,locale,signal,fetchFn});if(bridge.type==="static"){assertRequiredFilesExist(projectRoot,bridge.requireFiles,bridge.requireFilesHint,locale);let dir=resolve6(projectRoot,bridge.dir??"dist");return await createStaticSiteServer({dir,basePath:bridge.basePath,spaFallback:bridge.spaFallback,entryPath,locale})}let autoDir=bridge.dir!==void 0?resolve6(projectRoot,bridge.dir):detectDefaultStaticDir(projectRoot);if(autoDir!==null&&existsSync15(join11(autoDir,"index.html")))return await createStaticSiteServer({dir:autoDir,basePath:bridge.basePath,spaFallback:bridge.spaFallback,entryPath,locale});throw new RimError("TARGET_UNREACHABLE",rimT(locale,"未指定目标 URL, 且当前目录未检测到配置或含 index.html 的构建目录 (dist/web, dist, build, out, public)。请传 URL、--serve-dir <dir> 或先运行 rim init","No target URL provided and no config or static directory with index.html (dist/web, dist, build, out, public) was detected. Pass a URL, --serve-dir <dir>, or run rim init"))}import{existsSync as existsSync16,readFileSync as readFileSync11}from"node:fs";import{join as join12,resolve as resolve7}from"node:path";var SMOKE_ACTIONS=new Set(["viewport","navigate","waitUntil","click","setValue","assert"]),BRIDGE_TYPES=new Set(["auto","static","module","command"]),EXPORT_KINDS=new Set(["auto","fetch","factory","server"]),ENCODING_VALUES=new Set(["br","gzip","any"]),HTTP_METHODS=new Set(["GET","HEAD"]),PROBE_IDS=new Set(["proto","sec","perf","quality","load"]),THRESHOLD_BOUNDS=[["performance",0,100],["accessibility",0,100],["bestPractices",0,100],["seo",0,100],["minPerf",0,100],["minA11y",0,100],["minBp",0,100],["minSeo",0,100],["maxLongTasks",0,1000],["maxTbtMs",0,60000],["maxCls",0,10]];function failCfg(locale,zh,en){throw new RimError("CONFIG_INVALID",rimT(locale,zh,en))}function isPlainObject(value){return value!==null&&typeof value==="object"&&!Array.isArray(value)}function assertObj(value,field,locale){if(!isPlainObject(value))failCfg(locale,`配置字段 ${field} 须为对象`,`Config field ${field} must be an object`);return value}function assertBounded(value,field,min,max,locale){if(typeof value!=="number"||!Number.isFinite(value)||value<min||value>max)failCfg(locale,`配置字段 ${field} 须为 [${min}, ${max}] 范围内的有限数值`,`Config field ${field} must be a finite number within [${min}, ${max}]`);return value}function assertOptBounded(v,field,min,max,locale){if(v!==void 0)assertBounded(v,field,min,max,locale)}function assertOptBool(v,field,locale){if(v!==void 0&&typeof v!=="boolean")failCfg(locale,`配置字段 ${field} 须为布尔值`,`Config field ${field} must be a boolean`)}function assertStr(v,field,locale,required,nonEmpty=!1){if(!required&&v===void 0)return;if(typeof v!=="string"||nonEmpty&&v.trim()==="")failCfg(locale,`配置字段 ${field} 须为${nonEmpty?"非空":""}字符串`,`Config field ${field} must be a${nonEmpty?" non-empty":""} string`)}function assertOptStrArray(v,field,locale){if(v===void 0)return;if(!Array.isArray(v)||v.some((x)=>typeof x!=="string"||x.trim()===""))failCfg(locale,`配置字段 ${field} 须为非空字符串数组`,`Config field ${field} must be an array of non-empty strings`)}function assertOptEnum(v,allowed,field,locale){if(v===void 0)return;if(typeof v!=="string"||!allowed.has(v)){let list=[...allowed].join(" | ");failCfg(locale,`非法 ${field}: ${String(v)} (仅支持 ${list})`,`Invalid ${field}: ${String(v)} (expected ${list})`)}}function validateBridge(raw,locale,prefix="bridge"){if(raw===void 0)return;let obj=assertObj(raw,prefix,locale);if(typeof obj.type!=="string"||!BRIDGE_TYPES.has(obj.type))failCfg(locale,`非法 ${prefix}.type: ${String(obj.type)} (仅支持 auto | static | module | command)`,`Invalid ${prefix}.type: ${String(obj.type)} (expected auto | static | module | command)`);assertOptEnum(obj.exportKind,EXPORT_KINDS,`${prefix}.exportKind`,locale),assertOptBounded(obj.readyTimeoutMs,`${prefix}.readyTimeoutMs`,500,300000,locale),assertOptBool(obj.spaFallback,`${prefix}.spaFallback`,locale);for(let k of["dir","entry","export","beforeStart","command","requireFilesHint"])assertStr(obj[k],`${prefix}.${k}`,locale,!1,!0);for(let k of["basePath","readyPath"])assertStr(obj[k],`${prefix}.${k}`,locale,!1,!1);if(assertOptStrArray(obj.requireFiles,`${prefix}.requireFiles`,locale),assertOptStrArray(obj.argv,`${prefix}.argv`,locale),obj.env!==void 0){let envObj=assertObj(obj.env,`${prefix}.env`,locale);for(let[k,v]of Object.entries(envObj))assertStr(v,`${prefix}.env.${k}`,locale,!0)}return obj}function validateLocalConfig(raw,locale){if(raw===void 0)return;let obj=assertObj(raw,"local",locale);if(assertOptStrArray(obj.requireFiles,"local.requireFiles",locale),assertStr(obj.requireFilesHint,"local.requireFilesHint",locale,!1,!0),assertOptStrArray(obj.startCommand,"local.startCommand",locale),obj.port!==void 0&&obj.port!=="auto")assertBounded(obj.port,"local.port",1,65535,locale);if(assertStr(obj.healthPath,"local.healthPath",locale,!1),assertOptBounded(obj.startupTimeoutMs,"local.startupTimeoutMs",500,300000,locale),obj.env!==void 0){let envObj=assertObj(obj.env,"local.env",locale);for(let[k,v]of Object.entries(envObj))assertStr(v,`local.env.${k}`,locale,!0)}validateBridge(obj.bridge,locale,"local.bridge")}function validateBudgets(raw,locale){if(raw===void 0)return;let obj=assertObj(raw,"budgets",locale);if(assertOptBounded(obj.htmlBrBytes,"budgets.htmlBrBytes",1,1e7,locale),assertOptBounded(obj.totalCriticalBrBytes,"budgets.totalCriticalBrBytes",1,50000000,locale),obj.lighthouse!==void 0){let lh=assertObj(obj.lighthouse,"budgets.lighthouse",locale);for(let[k,min,max]of THRESHOLD_BOUNDS)assertOptBounded(lh[k],`budgets.lighthouse.${k}`,min,max,locale)}}function validateWaivers(raw,locale){if(raw===void 0)return;if(!Array.isArray(raw))failCfg(locale,"配置字段 waivers 须为数组","Config field waivers must be an array");for(let i=0;i<raw.length;i+=1){let w=assertObj(raw[i],`waivers[${i}]`,locale);assertStr(w.ruleId,`waivers[${i}].ruleId`,locale,!0,!0),assertStr(w.reason,`waivers[${i}].reason`,locale,!0,!0),assertOptEnum(w.probe,PROBE_IDS,`waivers[${i}].probe`,locale)}}function validateHttpConfig(raw,locale){if(raw===void 0)return;let obj=assertObj(raw,"http",locale);if(assertOptBool(obj.enabled,"http.enabled",locale),assertOptBounded(obj.maxTtfbMs,"http.maxTtfbMs",1,120000,locale),assertOptEnum(obj.requireEncoding,ENCODING_VALUES,"http.requireEncoding",locale),assertOptStrArray(obj.requireSecurityHeaders,"http.requireSecurityHeaders",locale),assertOptStrArray(obj.warnSecurityHeaders,"http.warnSecurityHeaders",locale),obj.routes===void 0)return;if(!Array.isArray(obj.routes))failCfg(locale,"配置字段 http.routes 须为数组","Config field http.routes must be an array");for(let i=0;i<obj.routes.length;i+=1){let route=obj.routes[i],p=`http.routes[${i}]`;if(!isPlainObject(route)||typeof route.path!=="string")failCfg(locale,`配置字段 ${p} 须为含字符串 path 的对象`,`Config field ${p} must be an object with a string path`);assertOptEnum(route.method,HTTP_METHODS,`${p}.method`,locale),assertOptBounded(route.expectStatus,`${p}.expectStatus`,100,599,locale),assertOptEnum(route.expectEncoding,ENCODING_VALUES,`${p}.expectEncoding`,locale),assertOptStrArray(route.requireHeaders,`${p}.requireHeaders`,locale),assertOptBounded(route.maxTtfbMs,`${p}.maxTtfbMs`,1,120000,locale)}}function validateSmokeStep(step,index,locale){let p=`smoke.steps[${index}]`;if(assertStr(step.label,`${p}.label`,locale,!1),step.action==="viewport")assertBounded(step.width,`${p}.width`,100,7680,locale),assertBounded(step.height,`${p}.height`,100,4320,locale),assertOptBool(step.mobile,`${p}.mobile`,locale),assertOptBounded(step.deviceScaleFactor,`${p}.deviceScaleFactor`,0.5,8,locale);else if(step.action==="navigate")assertStr(step.path,`${p}.path`,locale,!0,!0);else if(step.action==="waitUntil")assertStr(step.expr,`${p}.expr`,locale,!0,!0),assertOptBounded(step.timeoutMs,`${p}.timeoutMs`,100,300000,locale);else if(step.action==="click")assertStr(step.selector,`${p}.selector`,locale,!0,!0);else if(step.action==="setValue"){if(assertStr(step.selector,`${p}.selector`,locale,!0,!0),assertStr(step.value,`${p}.value`,locale,!0),step.event!==void 0&&step.event!=="input"&&step.event!=="change")failCfg(locale,`配置字段 ${p}.event 仅支持 input | change`,`Config field ${p}.event must be input or change`)}else if(step.action==="assert"){assertStr(step.expr,`${p}.expr`,locale,!0,!0);let t=typeof step.expected;if(step.expected!==void 0&&t!=="string"&&t!=="number"&&t!=="boolean")failCfg(locale,`配置字段 ${p}.expected 须为 string / number / boolean`,`Config field ${p}.expected must be a string, number, or boolean`);assertStr(step.includes,`${p}.includes`,locale,!1)}}function validateSmokeConfig(raw,locale){if(raw===void 0)return;let obj=assertObj(raw,"smoke",locale);for(let k of["enabled","failOnConsoleError","failOnPageError","failOnRequestError"])assertOptBool(obj[k],`smoke.${k}`,locale);if(assertOptBounded(obj.waitReadyTimeoutMs,"smoke.waitReadyTimeoutMs",100,300000,locale),assertOptStrArray(obj.ignoreRequestPaths,"smoke.ignoreRequestPaths",locale),assertOptStrArray(obj.argv,"smoke.argv",locale),obj.viewport!==void 0){let vp=assertObj(obj.viewport,"smoke.viewport",locale);assertBounded(vp.width,"smoke.viewport.width",100,7680,locale),assertBounded(vp.height,"smoke.viewport.height",100,4320,locale),assertOptBool(vp.mobile,"smoke.viewport.mobile",locale)}if(obj.steps===void 0)return;if(!Array.isArray(obj.steps))failCfg(locale,"配置字段 smoke.steps 须为数组","Config field smoke.steps must be an array");for(let i=0;i<obj.steps.length;i+=1){let step=obj.steps[i];if(!isPlainObject(step)||typeof step.action!=="string"||!SMOKE_ACTIONS.has(step.action))failCfg(locale,"配置字段 smoke.steps 包含非法 action","Config field smoke.steps contains an invalid action");validateSmokeStep(step,i,locale)}}var FORBIDDEN_KEYS=new Set(["__proto__","constructor","prototype"]),AUDIT_PRESETS=new Set(["quick","ci","full"]),LOAD_RUNNERS=new Set(["builtin","auto","h2load","oha"]);function validateProbeConfigs(raw,locale){if(raw.proto!==void 0){let obj=assertObj(raw.proto,"proto",locale);for(let k of["enabled","check304","checkPreloads","checkH2H3"])assertOptBool(obj[k],`proto.${k}`,locale);assertOptBounded(obj.h2h3TimeoutMs,"proto.h2h3TimeoutMs",1000,120000,locale)}if(raw.sec!==void 0){let obj=assertObj(raw.sec,"sec",locale);for(let k of["enabled","checkCsp","checkTls","runTestssl"])assertOptBool(obj[k],`sec.${k}`,locale);assertOptBounded(obj.tlsMinCertDays,"sec.tlsMinCertDays",7,365,locale),assertOptStrArray(obj.requireHeaders,"sec.requireHeaders",locale),assertOptStrArray(obj.warnHeaders,"sec.warnHeaders",locale),assertOptStrArray(obj.forbidHeaders,"sec.forbidHeaders",locale)}if(raw.quality!==void 0){let obj=assertObj(raw.quality,"quality",locale);for(let k of["enabled","checkLinks","checkExternalLinks","checkAnchors","checkAxe","runAxe","runLychee"])assertOptBool(obj[k],`quality.${k}`,locale);assertOptBounded(obj.maxLinks,"quality.maxLinks",1,200,locale),assertOptBounded(obj.maxExternalLinks,"quality.maxExternalLinks",1,100,locale),assertOptStrArray(obj.axeTags,"quality.axeTags",locale),validateSmokeConfig(obj.smoke,locale)}if(raw.load!==void 0){let obj=assertObj(raw.load,"load",locale);assertOptBool(obj.enabled,"load.enabled",locale),assertOptBounded(obj.concurrency,"load.concurrency",1,20,locale),assertOptBounded(obj.durationMs,"load.durationMs",200,15000,locale),assertOptBounded(obj.maxRequests,"load.maxRequests",1,500,locale),assertOptEnum(obj.runner,LOAD_RUNNERS,"load.runner",locale)}}function assertNoForbiddenKeys(value,locale,depth=0){if(depth>16)failCfg(locale,"配置文件嵌套深度超过安全上限 (16 层)","Configuration nesting depth exceeds safety limit (16)");if(value===null||typeof value!=="object")return;if(Array.isArray(value)){for(let item of value)assertNoForbiddenKeys(item,locale,depth+1);return}for(let key of Object.keys(value)){if(FORBIDDEN_KEYS.has(key))failCfg(locale,`配置文件包含禁止键名: ${key}`,`Configuration contains forbidden key: ${key}`);assertNoForbiddenKeys(value[key],locale,depth+1)}}function validateDevicesArray(raw,field,locale){if(raw===void 0)return;if(!Array.isArray(raw)||raw.length===0)failCfg(locale,`配置字段 ${field} 须为非空数组 (元素仅限 mobile / desktop)`,`Config field ${field} must be a non-empty array of mobile / desktop`);let out=[],seen=new Set;for(let item of raw){if(item!=="mobile"&&item!=="desktop")failCfg(locale,`非法 ${field} 值: ${String(item)} (仅支持 mobile | desktop)`,`Invalid ${field==="presets"?"preset":field} value: ${String(item)} (expected mobile | desktop)`);if(!seen.has(item))seen.add(item),out.push(item)}return out}function validateRimConfig(raw,locale="zh"){if(!isPlainObject(raw))failCfg(locale,"配置根必须是 JSON 对象","Configuration root must be a JSON object");if(assertNoForbiddenKeys(raw,locale),raw.schemaVersion!==void 0&&raw.schemaVersion!==1)failCfg(locale,`不受支持的 schemaVersion: ${String(raw.schemaVersion)} (期望 1)`,`Unsupported schemaVersion: ${String(raw.schemaVersion)} (expected 1)`);assertStr(raw.name,"name",locale,!1,!0),assertStr(raw.baseUrl,"baseUrl",locale,!1,!0),assertStr(raw.url,"url",locale,!1,!0),assertStr(raw.path,"path",locale,!1),assertOptStrArray(raw.routes,"routes",locale),assertOptEnum(raw.preset,AUDIT_PRESETS,"preset",locale);for(let k of["strict","coldGpu","writeReports"])assertOptBool(raw[k],k,locale);let devices=validateDevicesArray(raw.devices,"devices",locale),presets=validateDevicesArray(raw.presets,"presets",locale),bridge=validateBridge(raw.bridge,locale);if(validateLocalConfig(raw.local,locale),validateBudgets(raw.budgets,locale),validateWaivers(raw.waivers,locale),validateHttpConfig(raw.http,locale),validateSmokeConfig(raw.smoke,locale),validateProbeConfigs(raw,locale),raw.thresholds!==void 0){let th=assertObj(raw.thresholds,"thresholds",locale);for(let[k,min,max]of THRESHOLD_BOUNDS)assertOptBounded(th[k],`thresholds.${k}`,min,max,locale)}if(raw.cpuSlowdown!==void 0&&raw.cpuSlowdown!==null)assertBounded(raw.cpuSlowdown,"cpuSlowdown",0.5,20,locale);if(assertOptBounded(raw.timeoutMs,"timeoutMs",1000,600000,locale),raw.outDir!==void 0&&(typeof raw.outDir!=="string"||raw.outDir.trim()===""||/[\0\r\n]/.test(raw.outDir)))failCfg(locale,"配置字段 outDir 无效","Config field outDir is invalid");return assertOptStrArray(raw.strictAllowSkip,"strictAllowSkip",locale),{...raw,...devices!==void 0?{devices}:{},...presets!==void 0?{presets}:{},...bridge!==void 0?{bridge}:{}}}var DEFAULT_CONFIG_FILENAMES=[".rim.json","rim.config.json",".rimrc.json"],DEFAULT_THRESHOLDS=Object.freeze({performance:90,accessibility:90,bestPractices:90,seo:90,maxLongTasks:0});function resolveRimConfigPath(options={}){let cwd=resolve7(options.cwd??process.cwd()),env=options.env??process.env,explicit=options.configPath?.trim();if(explicit!==void 0&&explicit!=="")return{path:resolve7(cwd,explicit),source:"explicit"};let fromEnv=env.RIM_CONFIG?.trim();if(fromEnv!==void 0&&fromEnv!=="")return{path:resolve7(cwd,fromEnv),source:"env"};for(let name of DEFAULT_CONFIG_FILENAMES){let candidate=join12(cwd,name);if(existsSync16(candidate))return{path:candidate,source:"file"}}let pkgPath=join12(cwd,"package.json");if(existsSync16(pkgPath))try{if(JSON.parse(readFileSync11(pkgPath,"utf8")).rim!==void 0)return{path:pkgPath,source:"package-json"}}catch{}return null}function loadRimConfig(options={}){let locale=options.locale??"zh",discovered=resolveRimConfigPath(options);if(discovered===null)return{path:null,config:{}};if(!existsSync16(discovered.path))throw new RimError("CONFIG_NOT_FOUND",rimT(locale,`找不到配置文件: ${discovered.path}`,`Configuration file not found: ${discovered.path}`));let rawText;try{rawText=readFileSync11(discovered.path,"utf8")}catch(error){throw new RimError("CONFIG_INVALID",rimT(locale,`读取配置文件失败 (${discovered.path}): ${sanitizeLine(error instanceof Error?error.message:String(error))}`,`Failed to read configuration file (${discovered.path}): ${sanitizeLine(error instanceof Error?error.message:String(error))}`),void 0,error)}let parsed;try{parsed=JSON.parse(rawText)}catch(error){throw new RimError("CONFIG_INVALID",rimT(locale,`配置文件不是合法 JSON (${discovered.path}): ${sanitizeLine(error instanceof Error?error.message:String(error))}`,`Configuration file is not valid JSON (${discovered.path}): ${sanitizeLine(error instanceof Error?error.message:String(error))}`),void 0,error)}let targetObj=discovered.source==="package-json"?parsed.rim:parsed;return{path:discovered.path,config:validateRimConfig(targetObj,locale)}}import{execFileSync}from"node:child_process";import{existsSync as existsSync20,readdirSync as readdirSync3,statSync as statSync4}from"node:fs";import{dirname as dirname8,resolve as resolve10,win32 as win3216}from"node:path";import{spawn as spawn3}from"node:child_process";import{existsSync as existsSync17,readFileSync as readFileSync12}from"node:fs";import{chmod,mkdtemp,rm}from"node:fs/promises";import{tmpdir as tmpdir5}from"node:os";import{join as join13,win32 as win3215}from"node:path";var DEVTOOLS_LISTENING_RE=/DevTools listening on ws:\/\/[^:\s]+:(\d+)\//;function standardChromeCandidates(platform,env){if(platform==="darwin")return["/Applications/Google Chrome.app/Contents/MacOS/Google Chrome","/Applications/Google Chrome Canary.app/Contents/MacOS/Google Chrome Canary","/Applications/Chromium.app/Contents/MacOS/Chromium","/Applications/Microsoft Edge.app/Contents/MacOS/Microsoft Edge","/Applications/Brave Browser.app/Contents/MacOS/Brave Browser"];if(platform==="win32"){let localAppData=env.LOCALAPPDATA?.trim()||"",programFiles=env.ProgramFiles?.trim()||"C:\\Program Files",programFilesX86=env["ProgramFiles(x86)"]?.trim()||"C:\\Program Files (x86)";return[...localAppData!==""?[win3215.join(localAppData,"Google","Chrome","Application","chrome.exe"),win3215.join(localAppData,"Chromium","Application","chrome.exe")]:[],win3215.join(programFiles,"Google","Chrome","Application","chrome.exe"),win3215.join(programFilesX86,"Google","Chrome","Application","chrome.exe"),win3215.join(programFiles,"Microsoft","Edge","Application","msedge.exe"),win3215.join(programFilesX86,"Microsoft","Edge","Application","msedge.exe")]}return["/usr/bin/google-chrome","/usr/bin/google-chrome-stable","/usr/bin/chromium","/usr/bin/chromium-browser","/snap/bin/chromium","/usr/bin/microsoft-edge","/usr/bin/brave-browser"]}function resolveChromePath(options={}){let platform=options.platform??process.platform,env=options.env??process.env,fileProbe=options.fileProbe??isExistingFile,explicit=options.explicitPath?.trim();if(explicit!==void 0&&explicit!==""){if(isPlatformAbsolutePath(explicit,platform)&&fileProbe(explicit))return{path:explicit,source:"option"};return{path:null,source:"none"}}for(let rawEnv of[env.RIM_CHROME_PATH,env.CHROME_PATH]){let p=rawEnv?.trim()??"";if(p!==""&&isPlatformAbsolutePath(p,platform)&&fileProbe(p))return{path:p,source:"env"}}for(let candidate of standardChromeCandidates(platform,env))if(fileProbe(candidate))return{path:candidate,source:"standard"};let fromPath=resolveAbsoluteFromPath(platform==="win32"?["chrome","msedge"]:["google-chrome","google-chrome-stable","chromium","chromium-browser","microsoft-edge"],{platform,env,fileProbe});if(fromPath!==null)return{path:fromPath,source:"path"};return{path:null,source:"none"}}function buildChromeLaunchFlags(options){let platform=options.platform??process.platform,flags=["--headless=new",`--remote-debugging-port=${options.port}`,`--user-data-dir=${options.profileDir}`,"--no-first-run","--no-default-browser-check","--disable-background-networking","--disable-component-extensions-with-background-pages","--disable-default-apps","--disable-sync","--password-store=basic","--ignore-gpu-blocklist"];if(options.windowSize!==void 0)flags.push(`--window-size=${options.windowSize.width},${options.windowSize.height}`);if(options.coldGpu)flags.push("--disable-gpu-shader-disk-cache");if(platform==="darwin")flags.push("--use-mock-keychain","--use-gl=angle","--use-angle=metal");if(platform==="linux"){if(flags.push("--disable-dev-shm-usage"),process.getuid?.()===0)flags.push("--no-sandbox")}if(options.extraFlags!==void 0&&options.extraFlags.length>0)flags.push(...options.extraFlags);return flags.push("about:blank"),flags}function readDevToolsActivePort(profileDir){let filePath=join13(profileDir,"DevToolsActivePort");if(!existsSync17(filePath))return null;try{let firstLine=readFileSync12(filePath,"utf8").split(/\r?\n/,1)[0]?.trim(),port=Number(firstLine);return Number.isInteger(port)&&port>0&&port<=65535?port:null}catch{return null}}async function launchChrome(options){let locale=options.locale??"zh",timeoutMs=options.timeoutMs??15000;if(options.signal?.aborted===!0)throw new RimError("CANCELLED",rimT(locale,"操作已取消","Operation cancelled"));if(!isPlatformAbsolutePath(options.chromePath)||!isExistingFile(options.chromePath))throw new RimError("CHROME_NOT_FOUND",rimT(locale,`指定的 Chrome 可执行文件不存在: ${options.chromePath}`,`Specified Chrome binary does not exist: ${options.chromePath}`));let profileDir=await mkdtemp(join13(tmpdir5(),"rim-chrome-"));if(process.platform!=="win32")await chmod(profileDir,448).catch(()=>{});let flags=buildChromeLaunchFlags({port:0,profileDir,coldGpu:options.coldGpu,windowSize:options.windowSize,extraFlags:options.extraFlags}),child=spawn3(options.chromePath,flags,{env:buildSanitizedChildEnv(),stdio:["ignore","ignore","pipe"],windowsHide:!0}),exited=!1,exitCode=null,stderrBuf="",detectedPort=null,onPortDetected=null,onEarlyExit=null;child.stderr?.setEncoding("utf8"),child.stderr?.on("data",(chunk)=>{if(stderrBuf.length<4096)stderrBuf+=chunk;if(detectedPort===null){let match=DEVTOOLS_LISTENING_RE.exec(stderrBuf);if(match!==null){let parsed=Number(match[1]);if(Number.isInteger(parsed)&&parsed>0)detectedPort=parsed,onPortDetected?.(parsed)}}});let exitPromise=new Promise((resolve)=>{let markExit=(code)=>{if(exited)return;exited=!0,exitCode=code,onEarlyExit?.(),resolve()};child.once("exit",(code)=>markExit(code)),child.once("error",()=>markExit(null))}),cleaned=!1,cleanup=async()=>{if(cleaned)return;if(cleaned=!0,!exited){try{child.kill("SIGTERM")}catch{}if(await waitWithTimeout(exitPromise,2500),!exited){try{child.kill("SIGKILL")}catch{}await waitWithTimeout(exitPromise,1000)}}await rm(profileDir,{recursive:!0,force:!0,maxRetries:5,retryDelay:80}).catch(()=>{})},boundPort;try{boundPort=await new Promise((resolvePort,rejectPort)=>{if(detectedPort!==null){resolvePort(detectedPort);return}let settled=!1,done=(fn)=>{if(settled)return;settled=!0,clearTimeout(timeoutTimer),clearInterval(filePoll),onPortDetected=null,onEarlyExit=null,options.signal?.removeEventListener("abort",onAbort),fn()},rejectEarlyExit=()=>{let detail=sanitizeLine(stderrBuf).slice(0,240);done(()=>rejectPort(new RimError("CHROME_LAUNCH_FAILED",rimT(locale,`无头 Chrome 在调试端口就绪前提前退出 (exit=${String(exitCode)})${detail!==""?`: ${detail}`:""}`,`Headless Chrome exited before DevTools port became ready (exit=${String(exitCode)})${detail!==""?`: ${detail}`:""}`))))},onAbort=()=>{done(()=>rejectPort(new RimError("CANCELLED",rimT(locale,"操作已取消","Operation cancelled"))))};options.signal?.addEventListener("abort",onAbort,{once:!0}),onPortDetected=(p)=>{done(()=>resolvePort(p))},onEarlyExit=rejectEarlyExit;let timeoutTimer=setTimeout(()=>{done(()=>rejectPort(new RimError("CHROME_LAUNCH_FAILED",rimT(locale,`Chrome 调试端口未在 ${timeoutMs}ms 内就绪`,`Chrome DevTools port did not become ready within ${timeoutMs}ms`))))},timeoutMs),filePoll=setInterval(()=>{let fromFile=readDevToolsActivePort(profileDir);if(fromFile!==null)done(()=>resolvePort(fromFile))},40);if(exited)rejectEarlyExit()})}catch(error){throw await cleanup(),error}return{port:boundPort,chromePath:options.chromePath,cleanup}}import{existsSync as existsSync18,readFileSync as readFileSync13}from"node:fs";import{createRequire}from"node:module";import{dirname as dirname6,join as join14,resolve as resolve8}from"node:path";import{pathToFileURL as pathToFileURL2}from"node:url";function matchWaiver(waivers,ruleId,probe){if(waivers===void 0||waivers.length===0)return;return waivers.find((w)=>w.ruleId===ruleId&&(w.probe===void 0||w.probe===probe))}function applyWaiversToFindings(findings,waivers){if(waivers===void 0||waivers.length===0)return[...findings];return findings.map((f)=>{if(f.status!=="FAIL"&&f.status!=="WARN")return f;let matched=matchWaiver(waivers,f.id,f.probe);if(matched===void 0)return f;return{...f,status:"WAIVED",waiverReason:matched.reason}})}function aggregateProbeStatus(findings,defaultStatus="PASS"){if(findings.length===0)return defaultStatus;let hasFail=!1,hasWarn=!1,hasWaived=!1,hasPass=!1,hasSkip=!1;for(let f of findings)if(f.status==="FAIL")hasFail=!0;else if(f.status==="WARN")hasWarn=!0;else if(f.status==="WAIVED")hasWaived=!0;else if(f.status==="PASS")hasPass=!0;else if(f.status==="SKIP")hasSkip=!0;if(hasFail)return"FAIL";if(hasWarn)return"WARN";if(hasWaived&&!hasPass)return"WAIVED";if(hasPass||hasWaived)return"PASS";return hasSkip?"SKIP":defaultStatus}var LIGHTHOUSE_CATEGORIES=["performance","accessibility","best-practices","seo"];function buildLighthouseConfig(preset,cpuSlowdown){if(preset==="desktop")return{extends:"lighthouse:default",settings:{formFactor:"desktop",screenEmulation:{mobile:!1,width:1350,height:940,deviceScaleFactor:1,disabled:!1},throttling:{rttMs:40,throughputKbps:10240,cpuSlowdownMultiplier:cpuSlowdown??1,requestLatencyMs:0,downloadThroughputKbps:0,uploadThroughputKbps:0}}};return{extends:"lighthouse:default",settings:{formFactor:"mobile",...cpuSlowdown!==null?{throttling:{rttMs:150,throughputKbps:1638.4,cpuSlowdownMultiplier:cpuSlowdown,requestLatencyMs:562.5,downloadThroughputKbps:1474.56,uploadThroughputKbps:675}}:{}}}}function toRouteReportSlug(route){let cleaned=route.trim().replace(/^\/+|\/+$/g,"").replace(/[^a-zA-Z0-9_-]+/g,"-");return cleaned===""?"root":cleaned}function extractLighthouseSummary(input){let{lhr,preset,elapsedMs,htmlPath,jsonPath,waivers}=input,categories=lhr.categories??{},scores={};for(let key of LIGHTHOUSE_CATEGORIES){let rawScore=categories[key]?.score;scores[key]=typeof rawScore==="number"&&Number.isFinite(rawScore)?Math.round(rawScore*100):null}let audits=lhr.audits??{},longTaskAudit=audits["long-tasks"],longTasksAuditPresent=longTaskAudit!==void 0&&longTaskAudit.scoreDisplayMode!=="error"&&longTaskAudit.errorMessage===void 0,rawLongTasks=Array.isArray(longTaskAudit?.details?.items)?longTaskAudit.details.items:[],longTasks=[];for(let item of rawLongTasks)longTasks.push({url:sanitizeLine(String(item.url??"Unattributable")),startMs:Math.round(Number(item.startTime??0)),durationMs:Math.round(Number(item.duration??0))});let mtItems=Array.isArray(audits["mainthread-work-breakdown"]?.details?.items)?audits["mainthread-work-breakdown"].details.items:[],mainThreadTop=[];for(let item of mtItems){let dur=Number(item.duration??0);if(dur<5)continue;if(mainThreadTop.push({groupLabel:sanitizeLine(String(item.groupLabel??"")),durationMs:Math.round(dur)}),mainThreadTop.length>=6)break}let bootItems=Array.isArray(audits["bootup-time"]?.details?.items)?audits["bootup-time"].details.items:[],bootupTop=[],bootLimit=Math.min(5,bootItems.length);for(let i=0;i<bootLimit;i+=1){let item=bootItems[i];bootupTop.push({url:sanitizeLine(String(item.url??"")),totalMs:Math.round(Number(item.total??0)),scriptingMs:Math.round(Number(item.scripting??0))})}let findings=[];for(let id in audits){if(!Object.hasOwn(audits,id))continue;let audit=audits[id];if(audit===void 0)continue;let score=typeof audit.score==="number"?audit.score:null,mode=audit.scoreDisplayMode,isFail=score!==null&&score<1&&mode!=="manual"&&mode!=="notApplicable"&&mode!=="informative",isLongTaskWarn=id==="long-tasks"&&longTasks.length>0;if(isFail||isLongTaskWarn){let matched=matchWaiver(waivers,id,"perf");findings.push({id,title:sanitizeLine(String(audit.title??id)),score,displayValue:sanitizeLine(String(audit.displayValue??"")),...matched!==void 0?{waived:!0,waiverReason:matched.reason}:{}})}}findings.sort((a,b)=>(a.score??1)-(b.score??1));let tbtNum=audits["total-blocking-time"]?.numericValue,clsNum=audits["cumulative-layout-shift"]?.numericValue,ttfbNum=audits["server-response-time"]?.numericValue,rawErr=lhr.runtimeError,runtimeError=rawErr!==void 0&&(typeof rawErr.message==="string"||typeof rawErr.code==="string")&&rawErr.code!=="NO_ERROR"?{...typeof rawErr.code==="string"?{code:rawErr.code}:{},message:sanitizeLine(String(rawErr.message??rawErr.code??"Runtime error"))}:void 0;return{preset,...input.route!==void 0?{route:input.route}:{},...input.url!==void 0?{url:input.url}:{},scores,metrics:{fcp:sanitizeLine(audits["first-contentful-paint"]?.displayValue??"-"),lcp:sanitizeLine(audits["largest-contentful-paint"]?.displayValue??"-"),tbt:sanitizeLine(audits["total-blocking-time"]?.displayValue??"-"),tbtMs:typeof tbtNum==="number"&&Number.isFinite(tbtNum)?Math.round(tbtNum):null,cls:sanitizeLine(audits["cumulative-layout-shift"]?.displayValue??"-"),clsValue:typeof clsNum==="number"&&Number.isFinite(clsNum)?clsNum:null,si:sanitizeLine(audits["speed-index"]?.displayValue??"-"),ttfb:sanitizeLine(audits["server-response-time"]?.displayValue??"-"),ttfbMs:typeof ttfbNum==="number"&&Number.isFinite(ttfbNum)?Math.round(ttfbNum):null},longTasks,longTasksAuditPresent,mainThreadTop,bootupTop,findings,...runtimeError!==void 0?{runtimeError}:{},...htmlPath!==void 0?{htmlPath}:{},...jsonPath!==void 0?{jsonPath}:{},elapsedMs}}var cachedLighthouseFn=null;function probeLighthousePackage(cwd=process.cwd()){let candidates=[()=>createRequire(import.meta.url).resolve("lighthouse/package.json"),()=>createRequire(join14(resolve8(cwd),"package.json")).resolve("lighthouse/package.json")];for(let probe of candidates)try{let pkgPath=probe();if(!existsSync18(pkgPath))continue;let parsed=JSON.parse(readFileSync13(pkgPath,"utf8"));return{available:!0,version:typeof parsed.version==="string"?parsed.version:null,resolvedPath:dirname6(pkgPath)}}catch{}return{available:!1,version:null,resolvedPath:null,error:"lighthouse package could not be resolved"}}async function loadLighthouseFn(cwd,locale){if(cachedLighthouseFn!==null)return cachedLighthouseFn;try{let mod=await import("lighthouse");if(typeof mod.default==="function")return cachedLighthouseFn=mod.default,cachedLighthouseFn}catch{}try{let entryPath=createRequire(join14(resolve8(cwd),"package.json")).resolve("lighthouse"),mod=await import(pathToFileURL2(entryPath).href);if(typeof mod.default==="function")return cachedLighthouseFn=mod.default,cachedLighthouseFn}catch(error){throw new RimError("LIGHTHOUSE_UNAVAILABLE",rimT(locale,`未能加载可编程 lighthouse 依赖包, 请重新安装 @iyowei/rim-cli (${sanitizeLine(error instanceof Error?error.message:String(error))})`,`Failed to load programmatic lighthouse dependency; reinstall @iyowei/rim-cli (${sanitizeLine(error instanceof Error?error.message:String(error))})`),void 0,error)}throw new RimError("LIGHTHOUSE_UNAVAILABLE",rimT(locale,"加载到的 lighthouse 模块缺少默认导出函数","Loaded lighthouse module is missing its default runner export"))}async function defaultLighthouseRunner(input,cwd){let result=await(await loadLighthouseFn(cwd,input.locale))(input.url,{port:input.port,output:input.writeReports?["html","json"]:["json"],logLevel:"error",locale:input.locale,onlyCategories:[...LIGHTHOUSE_CATEGORIES]},buildLighthouseConfig(input.preset,input.cpuSlowdown));if(result===void 0||result.lhr===void 0)throw new RimError("LIGHTHOUSE_FAILED",rimT(input.locale,`Lighthouse (${input.preset}) 未返回有效结果`,`Lighthouse (${input.preset}) did not return a valid result`));let reports=Array.isArray(result.report)?result.report:[result.report];return{lhr:result.lhr,...input.writeReports&&typeof reports[0]==="string"?{htmlReport:reports[0]}:{},...input.writeReports&&typeof reports[1]==="string"?{jsonReport:reports[1]}:{}}}async function raceWithAbort(promise,signal,locale){if(signal===void 0)return await promise;if(signal.aborted)throw new RimError("CANCELLED",rimT(locale,"Lighthouse 审计已取消","Lighthouse audit cancelled"));let onAbort,abortPromise=new Promise((_resolve,reject)=>{onAbort=()=>{reject(new RimError("CANCELLED",rimT(locale,"Lighthouse 审计已取消","Lighthouse audit cancelled")))},signal.addEventListener("abort",onAbort,{once:!0})});try{return await Promise.race([promise,abortPromise])}finally{if(onAbort!==void 0)signal.removeEventListener("abort",onAbort)}}async function runLighthousePresetAudit(options){let startedAt=performance.now(),runInput={url:options.url,port:options.port,preset:options.preset,locale:options.locale,cpuSlowdown:options.cpuSlowdown,writeReports:options.writeReports,signal:options.signal},outPromise=options.runner!==void 0?options.runner(runInput):defaultLighthouseRunner(runInput,options.cwd),out=await raceWithAbort(outPromise,options.signal,options.locale),htmlPath,jsonPath;if(options.writeReports){let absOutDir=resolve8(options.cwd,options.outDir),slugPart=options.multiRoute===!0&&options.route!==void 0&&options.route!=="/"?`${toRouteReportSlug(options.route)}-`:"";if(out.htmlReport!==void 0)htmlPath=join14(absOutDir,`report-${slugPart}${options.preset}.html`),await writeTextFile(htmlPath,out.htmlReport);if(out.jsonReport!==void 0)jsonPath=join14(absOutDir,`report-${slugPart}${options.preset}.json`),await writeTextFile(jsonPath,out.jsonReport)}let elapsedMs=Math.max(0,Math.round(performance.now()-startedAt));return extractLighthouseSummary({lhr:out.lhr,preset:options.preset,route:options.route,url:options.url,elapsedMs,htmlPath,jsonPath,waivers:options.waivers})}import{existsSync as existsSync19,readFileSync as readFileSync14}from"node:fs";import{createRequire as createRequire2}from"node:module";import{dirname as dirname7,join as join15,resolve as resolve9}from"node:path";async function waitForCdpPageWsUrl(options){let locale=options.locale??"zh",timeoutMs=options.timeoutMs??15000,fetchFn=options.fetchFn??fetch,deadline=Date.now()+timeoutMs;while(Date.now()<deadline){if(options.signal?.aborted===!0)throw new RimError("CANCELLED",rimT(locale,"CDP 连接已取消","CDP connection cancelled"));let remainingMs=deadline-Date.now();if(remainingMs<=0)break;let probeCtrl=new AbortController,onParentAbort=()=>probeCtrl.abort();options.signal?.addEventListener("abort",onParentAbort,{once:!0});let probeTimer=setTimeout(()=>probeCtrl.abort(),Math.min(remainingMs,1500));try{let resp=await fetchFn(`http://127.0.0.1:${options.debugPort}/json/list`,{signal:probeCtrl.signal});if(resp.ok){let page=(await resp.json()).find((item)=>item.type==="page"&&typeof item.webSocketDebuggerUrl==="string");if(page?.webSocketDebuggerUrl!==void 0)return page.webSocketDebuggerUrl}else await resp.body?.cancel().catch(()=>{})}catch{}finally{clearTimeout(probeTimer),options.signal?.removeEventListener("abort",onParentAbort)}let sleepBudget=Math.min(30,Math.max(0,deadline-Date.now()));if(sleepBudget>0)await sleepMs(sleepBudget,options.signal)}throw new RimError("CDP_ERROR",rimT(locale,`等待 Chrome CDP 页面目标 (${options.debugPort}) 超时`,`Timed out waiting for Chrome CDP page target on port ${options.debugPort}`))}class CdpClient{ws;nextId=1;closed=!1;pending=new Map;requestUrls=new Map;networkRecords=new Map;consoleErrors=[];pageExceptions=[];failedRequests=[];constructor(ws){this.ws=ws,ws.addEventListener("message",(event)=>{this.handleMessage(String(event.data))}),ws.addEventListener("close",()=>{this.rejectAll(new RimError("CDP_ERROR","CDP WebSocket closed"))}),ws.addEventListener("error",()=>{this.rejectAll(new RimError("CDP_ERROR","CDP WebSocket error"))})}static async connect(wsUrl,timeoutMs=1e4,signal){if(signal?.aborted===!0)throw new RimError("CANCELLED","Cancelled");let ws=new WebSocket(wsUrl);return await new Promise((resolve,reject)=>{let settled=!1,done=(fn)=>{if(settled)return;settled=!0,clearTimeout(timer),signal?.removeEventListener("abort",onAbort),ws.removeEventListener("open",onOpen),ws.removeEventListener("error",onError),ws.removeEventListener("close",onClose),fn()},onOpen=()=>done(resolve),onError=()=>done(()=>reject(new RimError("CDP_ERROR",`CDP WebSocket connection failed: ${wsUrl}`))),onClose=()=>done(()=>reject(new RimError("CDP_ERROR",`CDP WebSocket closed during connect: ${wsUrl}`))),onAbort=()=>{try{ws.close()}catch{}done(()=>reject(new RimError("CANCELLED","Cancelled")))},timer=setTimeout(()=>{try{ws.close()}catch{}done(()=>reject(new RimError("CDP_ERROR",`CDP connect timed out: ${wsUrl}`)))},timeoutMs);signal?.addEventListener("abort",onAbort,{once:!0}),ws.addEventListener("open",onOpen,{once:!0}),ws.addEventListener("error",onError,{once:!0}),ws.addEventListener("close",onClose,{once:!0})}),new CdpClient(ws)}send(method,params={},timeoutMs=15000){if(this.closed)return Promise.reject(new RimError("CDP_ERROR",`CDP already closed (${method})`));let id=this.nextId;return this.nextId+=1,new Promise((resolve,reject)=>{let timer=setTimeout(()=>{this.pending.delete(id),reject(new RimError("CDP_ERROR",`CDP command timed out after ${timeoutMs}ms: ${method}`))},timeoutMs);this.pending.set(id,{resolve,reject,timer});try{this.ws.send(JSON.stringify({id,method,params}))}catch(error){clearTimeout(timer),this.pending.delete(id),reject(new RimError("CDP_ERROR",`CDP send failed (${method}): ${error instanceof Error?error.message:String(error)}`))}})}async evalValue(expression,timeoutMs=15000){let res=await this.send("Runtime.evaluate",{expression,awaitPromise:!0,returnByValue:!0},timeoutMs),exc=res.exceptionDetails;if(exc!==void 0)throw new RimError("CDP_ERROR",`Eval error: ${sanitizeLine(exc.exception?.description||exc.text||"unknown")}`);return res.result?.value}async waitUntil(expression,description,timeoutMs=1e4,signal){let deadline=Date.now()+timeoutMs;while(Date.now()<deadline){if(signal?.aborted===!0)throw new RimError("CANCELLED","Cancelled");let remainingMs=Math.max(100,deadline-Date.now());if(await this.evalValue(`Boolean(${expression})`,remainingMs))return;let sleepBudget=Math.min(45,Math.max(0,deadline-Date.now()));if(sleepBudget>0)await sleepMs(sleepBudget,signal)}throw new RimError("SMOKE_FAILED",`Wait condition timed out (${timeoutMs}ms): ${description}`)}close(){this.rejectAll(new RimError("CDP_ERROR","CDP session closed"));try{this.ws.close()}catch{}}rejectAll(err){this.closed=!0;for(let[,slot]of this.pending)clearTimeout(slot.timer),slot.reject(err);this.pending.clear()}handleMessage(raw){let msg;try{msg=JSON.parse(raw)}catch{return}if(typeof msg.id==="number"){let slot=this.pending.get(msg.id);if(slot===void 0)return;if(this.pending.delete(msg.id),clearTimeout(slot.timer),msg.error!==void 0)slot.reject(new RimError("CDP_ERROR",sanitizeLine(msg.error.message||"CDP command failed")));else slot.resolve(msg.result??{});return}this.handleEvent(msg.method,msg.params)}handleEvent(method,params){if(method==="Runtime.exceptionThrown"){let details=params?.exceptionDetails??{};this.pageExceptions.push(sanitizeLine(details.exception?.description||details.text||"Unknown exception"));return}if(method==="Runtime.consoleAPICalled"){if(String(params?.type??"")!=="error")return;let text=(params?.args??[]).map((arg)=>String(arg.value??arg.description??"")).join(" ");this.consoleErrors.push(sanitizeLine(text));return}if(method==="Network.requestWillBeSent"){let reqId=String(params?.requestId??""),req=params?.request;if(reqId!==""&&typeof req?.url==="string")this.requestUrls.set(reqId,req.url),this.networkRecords.set(reqId,{requestId:reqId,url:req.url,encodedDataLength:0,finished:!1,failed:!1});return}if(method==="Network.responseReceived"){let reqId=String(params?.requestId??""),resp=params?.response;if(reqId!==""&&resp!==void 0){let rec=this.networkRecords.get(reqId);if(rec!==void 0){if(typeof resp.status==="number")rec.status=resp.status;if(typeof resp.protocol==="string")rec.protocol=resp.protocol}}if(typeof resp?.status==="number"&&resp.status>=400&&typeof resp.url==="string")this.failedRequests.push({url:resp.url,status:resp.status,reason:sanitizeLine(resp.statusText||`HTTP ${resp.status}`)});return}if(method==="Network.loadingFinished"){let reqId=String(params?.requestId??"");if(reqId!==""){this.requestUrls.delete(reqId);let rec=this.networkRecords.get(reqId);if(rec!==void 0){if(rec.finished=!0,typeof params?.encodedDataLength==="number")rec.encodedDataLength=params.encodedDataLength}}return}if(method==="Network.loadingFailed"){let reqId=String(params?.requestId??""),url=this.requestUrls.get(reqId)??"unknown";if(reqId!=="")this.requestUrls.delete(reqId);if(params?.canceled===!0)return;let errText=sanitizeLine(String(params?.errorText??"loadingFailed")),rec=this.networkRecords.get(reqId);if(rec!==void 0)rec.failed=!0,rec.errorText=errText;this.failedRequests.push({url,status:0,reason:errText})}}}function appendBuiltinAxeFindings(axe,locale,findings){if(axe.status==="SKIP"){findings.push({id:"quality:axe",probe:"quality",status:"SKIP",title:axe.reason??rimT(locale,"内置 axe-core 无障碍审计已跳过","Bundled axe-core accessibility audit skipped")});return}if(axe.violations.length===0){let ver=axe.axeVersion?` ${axe.axeVersion}`:"";findings.push({id:"quality:axe",probe:"quality",status:"PASS",title:rimT(locale,`内置 axe-core${ver} 无障碍审计通过 (0 项违规, ${axe.passCount} 项规则通过)`,`Bundled axe-core${ver} accessibility audit passed (0 violations, ${axe.passCount} rules passed)`),value:0});return}for(let v of axe.violations){let severe=v.impact==="critical"||v.impact==="serious",targetHint=v.sampleTargets.length>0?`${v.nodeCount} node(s): ${v.sampleTargets.join(", ")}`:void 0;findings.push({id:v.id,probe:"quality",status:severe?"FAIL":"WARN",title:`axe [${v.impact}] ${v.id}: ${v.help}`,...targetHint!==void 0?{detail:targetHint}:{},value:v.nodeCount})}}var cachedAxeSource=null;function probeAxePackage(cwd=process.cwd()){let candidates=[()=>createRequire2(import.meta.url).resolve("axe-core/package.json"),()=>createRequire2(join15(resolve9(cwd),"package.json")).resolve("axe-core/package.json")];for(let probe of candidates)try{let pkgPath=probe();if(!existsSync19(pkgPath))continue;let parsed=JSON.parse(readFileSync14(pkgPath,"utf8"));return{available:!0,version:typeof parsed.version==="string"?parsed.version:null,resolvedPath:dirname7(pkgPath)}}catch{}return{available:!1,version:null,resolvedPath:null,error:"axe-core package could not be resolved"}}function loadAxeSource(cwd,locale){if(cachedAxeSource!==null)return cachedAxeSource;let candidates=[()=>createRequire2(import.meta.url).resolve("axe-core/axe.min.js"),()=>createRequire2(join15(resolve9(cwd),"package.json")).resolve("axe-core/axe.min.js")];for(let probe of candidates)try{let minPath=probe();if(!existsSync19(minPath))continue;return cachedAxeSource=readFileSync14(minPath,"utf8"),cachedAxeSource}catch{}throw new RimError("CDP_ERROR",rimT(locale,"未能加载随包 axe-core/axe.min.js 依赖, 请重新安装 @iyowei/rim-cli","Failed to load bundled axe-core/axe.min.js; reinstall @iyowei/rim-cli"))}function normalizeImpact(raw){if(raw==="critical"||raw==="serious"||raw==="moderate"||raw==="minor")return raw;return"unknown"}function parseAxeRawResult(raw,durationMs){let rawViolations=Array.isArray(raw?.violations)?raw.violations:[],violations=[],hasSevere=!1;for(let item of rawViolations){if(item===null||typeof item!=="object")continue;let rec=item,id=sanitizeLine(String(rec.id??"axe-violation"))||"axe-violation",impact=normalizeImpact(rec.impact);if(impact==="critical"||impact==="serious")hasSevere=!0;let help=sanitizeLine(String(rec.help??rec.description??id)),helpUrl=typeof rec.helpUrl==="string"&&rec.helpUrl.trim()!==""?sanitizeLine(rec.helpUrl):void 0,nodeCount=typeof rec.nodeCount==="number"&&Number.isFinite(rec.nodeCount)?Math.max(0,Math.round(rec.nodeCount)):0,sampleTargets=Array.isArray(rec.sampleTargets)?rec.sampleTargets.map((t)=>sanitizeLine(String(t??""))).filter((t)=>t!=="").slice(0,3):[];violations.push({id,impact,help,...helpUrl!==void 0?{helpUrl}:{},nodeCount,sampleTargets})}let status="PASS";if(hasSevere)status="FAIL";else if(violations.length>0)status="WARN";let incompleteCount=typeof raw?.incompleteCount==="number"&&Number.isFinite(raw.incompleteCount)?Math.max(0,Math.round(raw.incompleteCount)):0,passCount=typeof raw?.passCount==="number"&&Number.isFinite(raw.passCount)?Math.max(0,Math.round(raw.passCount)):0;return{status,engine:"bundled-axe-core",axeVersion:typeof raw?.version==="string"?sanitizeLine(raw.version):null,violationCount:violations.length,incompleteCount,passCount,violations,durationMs:Math.max(0,Math.round(durationMs))}}async function runAxeOnCdpClient(options){let isAborted=()=>options.signal?.aborted===!0;if(isAborted())throw new RimError("CANCELLED",rimT(options.locale,"无障碍审计已取消","Accessibility audit cancelled"));let startedAt=performance.now(),axeSource=loadAxeSource(options.cwd,options.locale),evalTimeout=Math.max(2000,Math.min(options.timeoutMs,25000));if(await options.cdp.send("Runtime.evaluate",{expression:axeSource,silent:!0},evalTimeout),isAborted())throw new RimError("CANCELLED",rimT(options.locale,"无障碍审计已取消","Accessibility audit cancelled"));let runOpts={resultTypes:["violations","incomplete","passes"]};if(options.axeTags!==void 0&&options.axeTags.length>0)runOpts.runOnly={type:"tag",values:[...options.axeTags]};let expr=`(async () => {
|
|
33
|
+
if (typeof window.axe?.run !== 'function') {
|
|
34
|
+
throw new Error('window.axe.run unavailable after injection');
|
|
35
|
+
}
|
|
36
|
+
const r = await window.axe.run(document, ${JSON.stringify(runOpts)});
|
|
37
|
+
return {
|
|
38
|
+
version: typeof window.axe.version === 'string' ? window.axe.version : null,
|
|
39
|
+
incompleteCount: Array.isArray(r.incomplete) ? r.incomplete.length : 0,
|
|
40
|
+
passCount: Array.isArray(r.passes) ? r.passes.length : 0,
|
|
41
|
+
violations: (Array.isArray(r.violations) ? r.violations : []).map((v) => ({
|
|
42
|
+
id: v.id,
|
|
43
|
+
impact: v.impact,
|
|
44
|
+
help: v.help,
|
|
45
|
+
helpUrl: v.helpUrl,
|
|
46
|
+
nodeCount: Array.isArray(v.nodes) ? v.nodes.length : 0,
|
|
47
|
+
sampleTargets: (Array.isArray(v.nodes) ? v.nodes : [])
|
|
48
|
+
.slice(0, 3)
|
|
49
|
+
.map((n) => (Array.isArray(n.target) ? n.target.join(' ') : String(n.target ?? '')))
|
|
50
|
+
.filter(Boolean),
|
|
51
|
+
})),
|
|
52
|
+
};
|
|
53
|
+
})()`,raw=await options.cdp.evalValue(expr,evalTimeout);return parseAxeRawResult(raw,performance.now()-startedAt)}async function runBuiltinAxeAudit(options){let startedAt=performance.now();if(options.axeRunner!==void 0)return await options.axeRunner({targetUrl:options.targetUrl,axeTags:options.axeTags,timeoutMs:options.timeoutMs,locale:options.locale,signal:options.signal});if(options.chromePath===null||options.chromePath==="")return{status:"SKIP",engine:"bundled-axe-core",violationCount:0,incompleteCount:0,passCount:0,violations:[],durationMs:0,reason:rimT(options.locale,"未检测到本机 Chrome, 跳过内置 axe-core 无障碍审计","Chrome not detected; skipping bundled axe-core accessibility audit")};let session=await(options.launchChromeFn??launchChrome)({chromePath:options.chromePath,coldGpu:!1,timeoutMs:options.timeoutMs,locale:options.locale,signal:options.signal}),cdp=null;try{let wsUrl=await waitForCdpPageWsUrl({debugPort:session.port,timeoutMs:options.timeoutMs,locale:options.locale,signal:options.signal});return cdp=await CdpClient.connect(wsUrl,options.timeoutMs,options.signal),await cdp.send("Page.enable"),await cdp.send("Runtime.enable"),await cdp.send("Page.navigate",{url:options.targetUrl}),await cdp.waitUntil("document.readyState === 'complete'",rimT(options.locale,"页面加载完成","document.readyState === complete"),Math.min(options.timeoutMs,15000),options.signal),await runAxeOnCdpClient({cdp,cwd:options.cwd,axeTags:options.axeTags,timeoutMs:options.timeoutMs,locale:options.locale,signal:options.signal})}catch(error){if(isRimError(error)&&error.code==="CANCELLED")throw error;return{status:"SKIP",engine:"bundled-axe-core",violationCount:0,incompleteCount:0,passCount:0,violations:[],durationMs:Math.max(0,Math.round(performance.now()-startedAt)),reason:sanitizeLine(error instanceof Error?error.message:String(error))}}finally{cdp?.close(),await session.cleanup()}}var WIN32_CHROME_VER_DIR_RE=/^(\d+)\.(\d+)\.(\d+)\.(\d+)(?:\.manifest)?$/i;function compareQuadVersions(a,b){for(let i=0;i<4;i+=1){let diff=(a[i]??0)-(b[i]??0);if(diff!==0)return diff}return 0}function probeWin32ChromeVersion(chromePath,readDir=(dir)=>readdirSync3(dir)){let dir=win3216.dirname(chromePath),entries;try{entries=readDir(dir)}catch{return null}let best=null;for(let name of entries){let match=WIN32_CHROME_VER_DIR_RE.exec(name);if(match===null)continue;let tuple=[Number(match[1]),Number(match[2]),Number(match[3]),Number(match[4])],raw=`${match[1]}.${match[2]}.${match[3]}.${match[4]}`;if(best===null||compareQuadVersions(tuple,best.tuple)>0)best={tuple,raw}}if(best===null)return null;let exe=win3216.basename(chromePath).toLowerCase();if(exe==="msedge.exe")return`Microsoft Edge ${best.raw}`;if(exe==="brave.exe")return`Brave ${best.raw}`;return`Google Chrome ${best.raw}`}function defaultProbeBinVersion(binPath,args){try{let inv=buildSafeSpawnInvocation(binPath,args),firstLine=execFileSync(inv.command,[...inv.args],{env:buildSanitizedChildEnv(),encoding:"utf8",stdio:["ignore","pipe","pipe"],timeout:3000,windowsHide:!0,...inv.windowsVerbatimArguments===!0?{windowsVerbatimArguments:!0}:{}}).split(/\r?\n/).map((l)=>sanitizeLine(l)).find((l)=>l!=="");return firstLine?firstLine.slice(0,80):null}catch{return null}}function installHintFor(tool,platform){if(tool==="chrome"){if(platform==="darwin")return"brew install --cask google-chrome";if(platform==="win32")return"winget install Google.Chrome";return"sudo apt install -y chromium || sudo apt install -y google-chrome-stable"}if(tool==="testssl"){if(platform==="darwin")return"brew install testssl";if(platform==="win32")return"scoop install testssl (or WSL: apt install testssl.sh)";return"sudo apt install -y testssl.sh"}if(tool==="h2load"){if(platform==="darwin")return"brew install nghttp2";if(platform==="win32")return"scoop install nghttp2";return"sudo apt install -y nghttp2-client"}if(tool==="oha"){if(platform==="darwin")return"brew install oha";if(platform==="win32")return"winget install hatoo.oha";return"cargo install oha"}if(tool==="lychee"){if(platform==="darwin")return"brew install lychee";if(platform==="win32")return"winget install lycheeverse.lychee";return"cargo install lychee"}return"bun add -g @axe-core/cli # or: npm i -g @axe-core/cli"}function probeOptionalAdapter(options){let path=options.resolveBin(options.binNames),installHint=installHintFor(options.name,options.platform);if(path===null)return{name:options.name,available:!1,path:null,version:null,status:"missing",installHint,builtinFallback:options.builtinFallback};return{name:options.name,available:!0,path,version:options.probeVersion(path,options.versionArgs),status:"ready",installHint,builtinFallback:options.builtinFallback}}function detectDefaultBridgeInfo(input){let{loadedConfig,projectRoot,locale,resolveBin}=input,effectiveBridge=loadedConfig.bridge??loadedConfig.local?.bridge,targetUrlCfg=loadedConfig.url??loadedConfig.baseUrl;if(effectiveBridge?.type==="module"){let entry=effectiveBridge.entry?.trim()??"",entryAbs=entry!==""?resolve10(projectRoot,entry):"",entryFound=entryAbs!==""&&isExistingFile(entryAbs);return{detected:entryFound,mode:"module",detail:entryFound?entry:rimT(locale,`模块桥接入口不存在: ${entry||"(空)"}`,`Module bridge entry not found: ${entry||"(empty)"}`)}}if(effectiveBridge?.type==="command"||(loadedConfig.local?.startCommand?.length??0)>0){let rawBin="";if(effectiveBridge?.argv!==void 0&&effectiveBridge.argv.length>0)rawBin=effectiveBridge.argv[0]??"";else if(loadedConfig.local?.startCommand!==void 0&&loadedConfig.local.startCommand.length>0)rawBin=loadedConfig.local.startCommand[0]??"";else if(effectiveBridge?.command!==void 0)try{rawBin=splitSafeCommand(effectiveBridge.command,locale)[0]??""}catch{rawBin=""}return{detected:rawBin!==""&&(isPlatformAbsolutePath(rawBin)?isExistingFile(rawBin):resolveBin([rawBin])!==null),mode:"command",detail:effectiveBridge?.argv?.join(" ")??loadedConfig.local?.startCommand?.join(" ")??effectiveBridge?.command??"command"}}if(targetUrlCfg!==void 0&&targetUrlCfg.trim()!=="")return{detected:!0,mode:"url",detail:targetUrlCfg};let configuredDir=effectiveBridge?.dir?.trim(),staticDir=configuredDir!==void 0&&configuredDir!==""?resolve10(projectRoot,configuredDir):detectDefaultStaticDir(projectRoot),dirExists=!1;if(staticDir!==null&&existsSync20(staticDir))try{dirExists=statSync4(staticDir).isDirectory()}catch{dirExists=!1}if(staticDir!==null&&dirExists)return{detected:!0,mode:"static",detail:staticDir};if(staticDir!==null)return{detected:!1,mode:"static",detail:rimT(locale,`静态目录不存在: ${staticDir}`,`Static directory does not exist: ${staticDir}`)};return{detected:!1,mode:"none",detail:rimT(locale,"未检测到配置或静态站点构建目录","No config or static build directory detected")}}function diagnoseRim(options={},deps={}){let locale=pickLocale(options.locale),cwd=resolve10(options.cwd??process.cwd()),runtime=getRuntimeInfo(),lhProbe=probeLighthousePackage(cwd),axeProbe=probeAxePackage(cwd),chrome=deps.resolveChrome!==void 0?deps.resolveChrome(options.chromePath):resolveChromePath({explicitPath:options.chromePath}),resolveBin=deps.resolveAdapterBin??((names)=>resolveAbsoluteFromPath(names)),probeVersion=deps.probeBinVersion??defaultProbeBinVersion,chromeVersion=null;if(chrome.path!==null){if(deps.probeBinVersion!==void 0)chromeVersion=deps.probeBinVersion(chrome.path,["--version"]);else if(deps.resolveChrome===void 0)chromeVersion=runtime.platform==="win32"?probeWin32ChromeVersion(chrome.path):defaultProbeBinVersion(chrome.path,["--version"])}let probeExt=(name,binNames,fallbackZh,fallbackEn)=>probeOptionalAdapter({name,binNames,versionArgs:["--version"],builtinFallback:rimT(locale,fallbackZh,fallbackEn),platform:runtime.platform,resolveBin,probeVersion}),axeVer=axeProbe.available&&axeProbe.version?`@${axeProbe.version}`:"",adapters={testssl:probeExt("testssl",["testssl.sh","testssl"],"内置 node:tls","built-in node:tls"),h2load:probeExt("h2load",["h2load"],"内置 node:http2","built-in node:http2"),oha:probeExt("oha",["oha"],"内置 node:http2 + Keep-Alive","built-in node:http2 + keep-alive"),lychee:probeExt("lychee",["lychee"],"内置 SSRF 链接/锚点扫描器","built-in SSRF link/anchor scanner"),axe:probeExt("axe",["axe"],`随包 axe-core${axeVer}`,`bundled axe-core${axeVer}`)},builtins={tls:{engine:"node:tls",available:!0,detail:rimT(locale,"TLS 1.0–1.3 协议矩阵、证书链、有效期、弱密钥/套件与 ALPN (SSRF IP 钉选)","TLS 1.0-1.3 matrix, cert chain/expiry, weak cipher/key & ALPN (SSRF IP-pinned)")},load:{engine:"node:http2+keepalive",available:!0,detail:rimT(locale,"自动协商 HTTP/2 多路复用流与 HTTP/1.1 Keep-Alive 连接池 (SSRF 钉选 + 硬编码护栏)","Auto-negotiated HTTP/2 multiplexed streams & HTTP/1.1 keep-alive pool (SSRF-pinned, capped)")},links:{engine:"builtin-ssrf-scanner",available:!0,detail:rimT(locale,"同源死链、跨页/页内 #anchor、srcset/媒体、重定向链与跨源外链扫描","Same-origin, cross-page/in-page #anchors, srcset/media, redirects & external links")},axe:{engine:"bundled-axe-core",available:axeProbe.available,version:axeProbe.version,detail:axeProbe.available?rimT(locale,`随包锁定 axe-core ${axeProbe.version??""} (经原生 Chrome CDP 注入, 穿透严格 CSP)`,`Bundled axe-core ${axeProbe.version??""} via native Chrome CDP (CSP-safe)`):axeProbe.error??"axe-core unavailable"}},discovered=resolveRimConfigPath({cwd,configPath:options.configPath}),configValid=!0,configError,loadedConfig={};if(discovered!==null)try{loadedConfig=loadRimConfig({cwd,configPath:options.configPath,locale}).config}catch(error){configValid=!1,configError=error instanceof Error?error.message:String(error)}let projectRoot=discovered!==null?dirname8(discovered.path):cwd,defaultBridge=detectDefaultBridgeInfo({loadedConfig,projectRoot,locale,resolveBin});return{runtime,lighthouse:lhProbe,axeCore:axeProbe,builtins,chrome:{available:chrome.path!==null,path:chrome.path,version:chromeVersion,source:chrome.source,...chrome.path===null?{installHint:installHintFor("chrome",runtime.platform)}:{}},adapters,config:{path:discovered?.path??null,valid:configValid,...configError!==void 0?{error:configError}:{}},defaultBridge}}import{dirname as dirname9,resolve as resolve12}from"node:path";import{resolve as resolve11}from"node:path";function statusBadgeClass(status){if(status==="PASS")return"pass";if(status==="WARN")return"warn";if(status==="FAIL")return"fail";if(status==="WAIVED")return"waived";return"skip"}function deltaBadgeClass(direction){if(direction==="improved")return"pass";if(direction==="regressed")return"fail";return"skip"}function safeHref(rawUrl){try{let parsed=new URL(rawUrl);if(parsed.protocol==="http:"||parsed.protocol==="https:")return escapeHtml(parsed.href)}catch{}return"#"}function renderHtmlReport(report,locale="zh"){let title=rimT(locale,`rim 审计报告 - ${report.targetUrl}`,`rim Audit Report - ${report.targetUrl}`),overallLabel=report.passed?rimT(locale,"通过 PASS","PASS"):rimT(locale,"未通过 FAIL","FAIL"),overallClass=report.passed?"pass":"fail",probeRows=report.probes.map((p)=>{let failCnt=p.findings.filter((f)=>f.status==="FAIL").length,warnCnt=p.findings.filter((f)=>f.status==="WARN").length,waivedCnt=p.findings.filter((f)=>f.status==="WAIVED").length;return`<tr>
|
|
54
|
+
<td><code>${escapeHtml(p.id)}</code></td>
|
|
55
|
+
<td><span class="badge ${statusBadgeClass(p.status)}">${escapeHtml(p.status)}</span></td>
|
|
56
|
+
<td>${p.durationMs}ms</td>
|
|
57
|
+
<td>${p.findings.length} (${failCnt} fail / ${warnCnt} warn / ${waivedCnt} waived)</td>
|
|
58
|
+
</tr>`}).join(`
|
|
59
|
+
`),probeSections=report.probes.map((p)=>{let items=p.findings.map((f)=>{let waiver=f.waiverReason!==void 0?`<div class="waiver">WAIVED: ${escapeHtml(f.waiverReason)}</div>`:"",detail=f.detail!==void 0?`<div class="detail">${escapeHtml(f.detail)}</div>`:"";return`<li>
|
|
60
|
+
<span class="badge ${statusBadgeClass(f.status)}">${escapeHtml(f.status)}</span>
|
|
61
|
+
<code>${escapeHtml(f.id)}</code>
|
|
62
|
+
<span>${escapeHtml(f.title)}</span>
|
|
63
|
+
${detail}${waiver}
|
|
64
|
+
</li>`}).join(`
|
|
65
|
+
`);return`<section class="card">
|
|
66
|
+
<h2>${escapeHtml(p.id.toUpperCase())} <span class="badge ${statusBadgeClass(p.status)}">${escapeHtml(p.status)}</span> <small>${p.durationMs}ms</small></h2>
|
|
67
|
+
<ul class="findings">${items||`<li>${escapeHtml(rimT(locale,"无异常条目","No findings"))}</li>`}</ul>
|
|
68
|
+
</section>`}).join(`
|
|
69
|
+
`),lhSection=report.lighthouse.summaries.length>0?`<section class="card">
|
|
70
|
+
<h2>Lighthouse</h2>
|
|
71
|
+
<table>
|
|
72
|
+
<thead><tr><th>Device</th><th>Route</th><th>Perf</th><th>A11y</th><th>BP</th><th>SEO</th><th>FCP</th><th>LCP</th><th>TBT</th><th>CLS</th><th>Long Tasks</th></tr></thead>
|
|
73
|
+
<tbody>
|
|
74
|
+
${report.lighthouse.summaries.map((s)=>`<tr>
|
|
75
|
+
<td>${escapeHtml(s.preset)}</td>
|
|
76
|
+
<td><code>${escapeHtml(s.route??"/")}</code></td>
|
|
77
|
+
<td>${escapeHtml(String(s.scores.performance??"N/A"))}</td>
|
|
78
|
+
<td>${escapeHtml(String(s.scores.accessibility??"N/A"))}</td>
|
|
79
|
+
<td>${escapeHtml(String(s.scores["best-practices"]??"N/A"))}</td>
|
|
80
|
+
<td>${escapeHtml(String(s.scores.seo??"N/A"))}</td>
|
|
81
|
+
<td>${escapeHtml(s.metrics.fcp)}</td>
|
|
82
|
+
<td>${escapeHtml(s.metrics.lcp)}</td>
|
|
83
|
+
<td>${escapeHtml(s.metrics.tbt)}</td>
|
|
84
|
+
<td>${escapeHtml(s.metrics.cls)}</td>
|
|
85
|
+
<td>${s.longTasks.length}</td>
|
|
86
|
+
</tr>`).join(`
|
|
87
|
+
`)}
|
|
88
|
+
</tbody>
|
|
89
|
+
</table>
|
|
90
|
+
</section>`:"",diffSection=report.baselineDiff!==void 0?`<section class="card">
|
|
91
|
+
<h2>${escapeHtml(rimT(locale,"基线对比 Delta","Baseline Diff Delta"))}</h2>
|
|
92
|
+
<p class="meta">${escapeHtml(report.baselineDiff.previousTimestamp??rimT(locale,"首次记录","first run"))} -> ${escapeHtml(report.baselineDiff.currentTimestamp)}</p>
|
|
93
|
+
<table>
|
|
94
|
+
<thead><tr><th>Metric</th><th>Before</th><th>After</th><th>Delta</th><th>Status</th></tr></thead>
|
|
95
|
+
<tbody>
|
|
96
|
+
${report.baselineDiff.deltas.map((d)=>{let sign=d.delta!==null&&d.delta>0?`+${d.delta}`:String(d.delta??"-"),cls=deltaBadgeClass(d.direction);return`<tr>
|
|
97
|
+
<td><code>${escapeHtml(d.metric)}</code></td>
|
|
98
|
+
<td>${escapeHtml(d.before===null?"-":`${d.before}${d.unit}`)}</td>
|
|
99
|
+
<td>${escapeHtml(d.after===null?"-":`${d.after}${d.unit}`)}</td>
|
|
100
|
+
<td>${escapeHtml(`${sign}${d.delta!==null?d.unit:""}`)}</td>
|
|
101
|
+
<td><span class="badge ${cls}">${escapeHtml(d.direction)}</span></td>
|
|
102
|
+
</tr>`}).join(`
|
|
103
|
+
`)}
|
|
104
|
+
</tbody>
|
|
105
|
+
</table>
|
|
106
|
+
</section>`:"";return`<!doctype html>
|
|
107
|
+
<html lang="${locale==="en"?"en":"zh-CN"}">
|
|
108
|
+
<head>
|
|
109
|
+
<meta charset="utf-8">
|
|
110
|
+
<meta name="viewport" content="width=device-width,initial-scale=1">
|
|
111
|
+
<meta http-equiv="Content-Security-Policy" content="default-src 'none'; style-src 'unsafe-inline'; img-src data:;">
|
|
112
|
+
<title>${escapeHtml(title)}</title>
|
|
113
|
+
<style>
|
|
114
|
+
:root { color-scheme: light dark; font-family: ui-sans-serif, system-ui, -apple-system, sans-serif; }
|
|
115
|
+
body { max-width: 1080px; margin: 24px auto; padding: 0 16px; line-height: 1.5; }
|
|
116
|
+
header { display: flex; flex-wrap: wrap; gap: 12px; align-items: baseline; border-bottom: 1px solid #8884; padding-bottom: 12px; margin-bottom: 18px; }
|
|
117
|
+
h1 { margin: 0; font-size: 1.35rem; }
|
|
118
|
+
.meta { color: #888; font-size: 0.9rem; }
|
|
119
|
+
.card { border: 1px solid #8883; border-radius: 10px; padding: 14px 16px; margin-bottom: 16px; }
|
|
120
|
+
.card h2 { margin: 0 0 10px; font-size: 1.05rem; display: flex; align-items: center; gap: 8px; }
|
|
121
|
+
table { width: 100%; border-collapse: collapse; font-size: 0.9rem; }
|
|
122
|
+
th, td { text-align: left; padding: 6px 8px; border-bottom: 1px solid #8882; }
|
|
123
|
+
.findings { list-style: none; padding: 0; margin: 0; display: grid; gap: 6px; }
|
|
124
|
+
.findings li { font-size: 0.92rem; }
|
|
125
|
+
.detail { color: #888; font-size: 0.84rem; margin-left: 16px; }
|
|
126
|
+
.waiver { color: #0b7285; font-size: 0.84rem; margin-left: 16px; }
|
|
127
|
+
.badge { display: inline-block; padding: 1px 7px; border-radius: 999px; font-size: 0.78rem; font-weight: 600; }
|
|
128
|
+
.badge.pass { background: #16a34a22; color: #16a34a; }
|
|
129
|
+
.badge.warn { background: #d9770622; color: #d97706; }
|
|
130
|
+
.badge.fail { background: #dc262622; color: #dc2626; }
|
|
131
|
+
.badge.waived { background: #0891b222; color: #0891b2; }
|
|
132
|
+
.badge.skip { background: #6b728022; color: #6b7280; }
|
|
133
|
+
code { font-family: ui-monospace, SFMono-Regular, Menlo, monospace; font-size: 0.86em; }
|
|
134
|
+
</style>
|
|
135
|
+
</head>
|
|
136
|
+
<body>
|
|
137
|
+
<header>
|
|
138
|
+
<h1>rim</h1>
|
|
139
|
+
<span class="badge ${overallClass}">${escapeHtml(overallLabel)}</span>
|
|
140
|
+
<a href="${safeHref(report.targetUrl)}" rel="noopener noreferrer">${escapeHtml(report.targetUrl)}</a>
|
|
141
|
+
<span class="meta">preset=${escapeHtml(report.preset)} · ${escapeHtml(report.bridge.mode)} · ${escapeHtml(report.runtime.name)} ${escapeHtml(report.runtime.version)} · ${report.elapsedMs}ms</span>
|
|
142
|
+
</header>
|
|
143
|
+
<section class="card">
|
|
144
|
+
<h2>${escapeHtml(rimT(locale,"探针总览","Probe Overview"))}</h2>
|
|
145
|
+
<table>
|
|
146
|
+
<thead><tr><th>Probe</th><th>Status</th><th>Duration</th><th>Findings</th></tr></thead>
|
|
147
|
+
<tbody>${probeRows}</tbody>
|
|
148
|
+
</table>
|
|
149
|
+
</section>
|
|
150
|
+
${lhSection}
|
|
151
|
+
${probeSections}
|
|
152
|
+
${diffSection}
|
|
153
|
+
</body>
|
|
154
|
+
</html>
|
|
155
|
+
`}function resolveStableBaselineHostKey(bridgeMode,configName){if(bridgeMode===void 0||bridgeMode==="url")return;let cleanName=configName?.trim()??"";return cleanName!==""?`local-${cleanName}`:"local"}async function finalizeBaselineAndHtml(input){let{baseReport,bridgeMode,configName,cwd,locale,options}=input,baselineDiff=baseReport.baselineDiff,baselineSavedPath;if(options.diffBaseline===!0||options.saveBaseline===!0){options.onProgress?.({phase:"baseline",detail:rimT(locale,"处理历史水位线基线","Processing baseline history")});let hostKey=resolveStableBaselineHostKey(bridgeMode,configName),entry=extractBaselineEntry(baseReport,void 0,hostKey);if(options.diffBaseline===!0){let history=loadBaselineHistory(entry.host,{cacheDir:options.baselineCacheDir,locale}),prev=history.length>0?history[history.length-1]:null;baselineDiff=computeBaselineDiff(prev,entry)}if(options.saveBaseline===!0)baselineSavedPath=saveBaselineEntry(entry,{cacheDir:options.baselineCacheDir,locale})}let reportWithMeta={...baseReport,...baselineSavedPath!==void 0?{baselineSavedPath}:{},...baselineDiff!==void 0?{baselineDiff}:{}};if(options.htmlReportPath!==void 0&&options.htmlReportPath.trim()!==""){let rawHtmlPath=options.htmlReportPath;for(let i=0;i<rawHtmlPath.length;i+=1){let code=rawHtmlPath.charCodeAt(i);if(code===0||code===10||code===13)throw new RimError("INVALID_ARGUMENT",rimT(locale,"HTML 报告路径包含非法控制字符","HTML report path contains forbidden control characters"))}options.onProgress?.({phase:"html",detail:rimT(locale,"生成自包含 HTML 摘要报告","Writing HTML summary report")});let absHtml=resolve11(cwd,rawHtmlPath.trim()),htmlContent=renderHtmlReport(reportWithMeta,locale);await writeTextFile(absHtml,htmlContent),reportWithMeta={...reportWithMeta,htmlReportPath:absHtml}}return reportWithMeta}import{spawn as spawn4}from"node:child_process";function parseDurationToMs(valStr,unit){let n=Number(valStr);if(!Number.isFinite(n))return 0;let u=unit.toLowerCase();if(u==="us")return Math.round(n/1000*100)/100;if(u==="s")return Math.round(n*1000*100)/100;return Math.round(n*100)/100}function parseH2loadOutput(stdout){let rpsMatch=/([\d.]+)\s+req\/s/i.exec(stdout),reqMatch=/requests:\s*(\d+)\s+total,\s*\d+\s+started,\s*\d+\s+done,\s*(\d+)\s+succeeded,\s*(\d+)\s+failed/i.exec(stdout);if(rpsMatch===null||reqMatch===null)return null;let totalRequests=Number(reqMatch[1]),successCount=Number(reqMatch[2]),errorCount=Math.max(Number(reqMatch[3]),totalRequests-successCount),rps=Math.round(Number(rpsMatch[1])*10)/10,latMatch=/time for request:\s*([\d.]+)(us|ms|s)\s+([\d.]+)(us|ms|s)\s+([\d.]+)(us|ms|s)/i.exec(stdout),minMs=latMatch!==null?parseDurationToMs(latMatch[1],latMatch[2]):0,maxMs=latMatch!==null?parseDurationToMs(latMatch[3],latMatch[4]):0,meanMs=latMatch!==null?parseDurationToMs(latMatch[5],latMatch[6]):0,statusCounts={},scMatch=/status codes:\s*(\d+)\s+2xx,\s*(\d+)\s+3xx,\s*(\d+)\s+4xx,\s*(\d+)\s+5xx/i.exec(stdout);if(scMatch!==null){if(Number(scMatch[1])>0)statusCounts["2xx"]=Number(scMatch[1]);if(Number(scMatch[2])>0)statusCounts["3xx"]=Number(scMatch[2]);if(Number(scMatch[3])>0)statusCounts["4xx"]=Number(scMatch[3]);if(Number(scMatch[4])>0)statusCounts["5xx"]=Number(scMatch[4])}return{totalRequests,successCount,errorCount,rps,latency:{minMs,p50Ms:meanMs,p95Ms:maxMs,p99Ms:maxMs,maxMs},statusCounts}}function parseOhaOutput(stdout){try{let data=JSON.parse(stdout),statusCounts={...data.statusCodeDistribution},total=0,success=0;for(let[k,v]of Object.entries(statusCounts)){total+=v;let s=Number(k);if(s>=200&&s<400)success+=v}let netErrors=0;for(let v of Object.values(data.errorDistribution??{}))if(typeof v==="number"&&Number.isFinite(v)&&v>0)netErrors+=v;if(netErrors>0)total+=netErrors,statusCounts.error=(statusCounts.error??0)+netErrors;let toMs=(sec)=>typeof sec==="number"&&Number.isFinite(sec)?Math.round(sec*1000*100)/100:0;return{totalRequests:total,successCount:success,errorCount:Math.max(0,total-success),rps:Math.round((data.summary?.requestsPerSec??0)*10)/10,latency:{minMs:toMs(data.summary?.fastest),p50Ms:toMs(data.latencyPercentiles?.p50),p95Ms:toMs(data.latencyPercentiles?.p95),p99Ms:toMs(data.latencyPercentiles?.p99),maxMs:toMs(data.summary?.slowest)},statusCounts}}catch{return null}}async function runLoadBinary(options){let inv=buildSafeSpawnInvocation(options.binPath,options.args,{locale:options.locale});return await new Promise((resolvePromise)=>{let child=spawn4(inv.command,[...inv.args],{env:buildSanitizedChildEnv(),stdio:["ignore","pipe","ignore"],windowsHide:!0,...inv.windowsVerbatimArguments===!0?{windowsVerbatimArguments:!0}:{}}),stdout="",exited=!1;child.stdout?.setEncoding("utf8"),child.stdout?.on("data",(c)=>{if(stdout.length<options.maxStdout)stdout+=c});let exitP=new Promise((res)=>{child.once("close",(code)=>{exited=!0,res(code)}),child.once("error",()=>{exited=!0,res(null)})}),onAbort=()=>{try{child.kill("SIGTERM")}catch{}};options.signal?.addEventListener("abort",onAbort,{once:!0}),waitWithTimeout(exitP,options.timeoutMs).then(async(done)=>{if(options.signal?.removeEventListener("abort",onAbort),!done&&!exited){try{child.kill("SIGKILL")}catch{}resolvePromise(null);return}let code=await exitP;resolvePromise(code===0?stdout:null)})})}async function runOhaAdapter(options){let stdout=await runLoadBinary({binPath:options.binPath,args:["-n",String(options.maxRequests),"-c",String(options.concurrency),"--no-tui","--output-format","json",options.targetUrl],maxStdout:256000,timeoutMs:options.timeoutMs,locale:options.locale,signal:options.signal});return stdout!==null?parseOhaOutput(stdout):null}async function runH2loadAdapter(options){let stdout=await runLoadBinary({binPath:options.binPath,args:["-n",String(options.maxRequests),"-c",String(options.concurrency),"-m","1",options.targetUrl],maxStdout:128000,timeoutMs:options.timeoutMs,locale:options.locale,signal:options.signal});return stdout!==null?parseH2loadOutput(stdout):null}import{Agent as HttpAgent,request as httpRequest2}from"node:http";import{Agent as HttpsAgent,request as httpsRequest2}from"node:https";import{isIP as isIP4}from"node:net";import{connect as http2Connect}from"node:http2";import{isIP as isIP3,connect as netConnect}from"node:net";import{connect as tlsConnect}from"node:tls";var MAX_LOAD_WIRE_BYTES=524288;function computeLatencyStats(samplesMs){if(samplesMs.length===0)return{minMs:0,p50Ms:0,p95Ms:0,p99Ms:0,maxMs:0};let sorted=[...samplesMs].sort((a,b)=>a-b),pick=(pct)=>{let idx=Math.min(sorted.length-1,Math.max(0,Math.ceil(pct/100*sorted.length)-1));return Math.round(sorted[idx]*100)/100};return{minMs:Math.round(sorted[0]*100)/100,p50Ms:pick(50),p95Ms:pick(95),p99Ms:pick(99),maxMs:Math.round(sorted[sorted.length-1]*100)/100}}function resolveLoadPort(parsedUrl){if(parsedUrl.port!=="")return Number(parsedUrl.port);return parsedUrl.protocol==="https:"?443:80}async function probeHttpsAlpn(options){if(options.parsedUrl.protocol!=="https:")return null;if(options.signal?.aborted===!0)return null;let cleanHost=options.parsedUrl.hostname.replace(/^\[|\]$/g,""),port=resolveLoadPort(options.parsedUrl);return await new Promise((resolvePromise)=>{let settled=!1,sock=null,finish=(val)=>{if(settled)return;settled=!0,clearTimeout(timer),options.signal?.removeEventListener("abort",onAbort);try{sock?.destroy()}catch{}resolvePromise(val)},onAbort=()=>finish(null);options.signal?.addEventListener("abort",onAbort,{once:!0});let timer=setTimeout(()=>finish(null),Math.min(options.timeoutMs,3000));try{sock=tlsConnect({host:options.pin.address,port,...isIP3(cleanHost)===0?{servername:cleanHost}:{},...options.ca!==void 0?{ca:options.ca}:{},ALPNProtocols:["h2","http/1.1"]},()=>{let alpn=typeof sock?.alpnProtocol==="string"&&sock.alpnProtocol!==""?sock.alpnProtocol:null;finish(alpn)}),sock.once("error",()=>finish(null))}catch{finish(null)}})}function executeH2Stream(options){let startedAt=performance.now();return new Promise((resolvePromise)=>{let settled=!1,status=0,ttfbMs=0,bytes=0,stream=null,finish=(sample)=>{if(settled)return;settled=!0,clearTimeout(timer),options.signal?.removeEventListener("abort",onAbort),resolvePromise(sample)},failNow=()=>{let totalMs=performance.now()-startedAt;try{stream?.close()}catch{}finish({status:0,ok:!1,ttfbMs:ttfbMs>0?ttfbMs:totalMs,totalMs,bytes})},onAbort=()=>failNow();options.signal?.addEventListener("abort",onAbort,{once:!0});let timer=setTimeout(failNow,Math.max(300,options.timeoutMs));try{stream=options.session.request({":method":"GET",":path":options.pathAndQuery,"accept-encoding":"br, gzip"}),stream.on("response",(headers)=>{ttfbMs=performance.now()-startedAt,status=Number(headers[":status"]??0)}),stream.on("data",(chunk)=>{if(bytes+=Buffer.isBuffer(chunk)?chunk.byteLength:Buffer.byteLength(chunk),bytes>MAX_LOAD_WIRE_BYTES){try{stream?.close()}catch{}let totalMs=performance.now()-startedAt;finish({status,ok:status>=200&&status<400,ttfbMs:ttfbMs>0?ttfbMs:totalMs,totalMs,bytes})}}),stream.once("end",()=>{let totalMs=performance.now()-startedAt;finish({status,ok:status>=200&&status<400,ttfbMs:ttfbMs>0?ttfbMs:totalMs,totalMs,bytes})}),stream.once("error",failNow),stream.once("close",()=>{if(!settled)failNow()}),stream.end()}catch{failNow()}})}function openPinnedH2Session(options){if(options.signal?.aborted===!0)return Promise.resolve(null);let isHttps=options.parsedUrl.protocol==="https:",cleanHost=options.parsedUrl.hostname.replace(/^\[|\]$/g,""),port=resolveLoadPort(options.parsedUrl);return new Promise((resolvePromise)=>{let settled=!1,session=null,finish=(s)=>{if(settled)return;settled=!0,clearTimeout(timer),options.signal?.removeEventListener("abort",onAbort),resolvePromise(s)},abortSession=()=>{try{session?.destroy()}catch{}finish(null)},onAbort=()=>abortSession();options.signal?.addEventListener("abort",onAbort,{once:!0});let timer=setTimeout(abortSession,Math.min(options.timeoutMs,4000));try{session=isHttps?http2Connect(options.parsedUrl.origin,{createConnection:()=>tlsConnect({host:options.pin.address,port,...isIP3(cleanHost)===0?{servername:cleanHost}:{},...options.ca!==void 0?{ca:options.ca}:{},ALPNProtocols:["h2"]})}):http2Connect(options.parsedUrl.origin,{createConnection:()=>netConnect({host:options.pin.address,port,family:options.pin.family})}),session.on("error",()=>finish(null)),session.once("connect",()=>finish(session))}catch{finish(null)}})}async function runBuiltinH2Load(options){let sessionCount=Math.max(1,Math.min(options.concurrency,4)),sessions=(await Promise.all(Array.from({length:sessionCount},()=>openPinnedH2Session({parsedUrl:options.parsedUrl,pin:options.pin,ca:options.ca,timeoutMs:options.durationMs+2000,signal:options.signal})))).filter((s)=>s!==null&&!s.closed&&!s.destroyed);if(sessions.length===0)return null;let pathAndQuery=`${options.parsedUrl.pathname}${options.parsedUrl.search}`,startedAt=performance.now(),deadline=Date.now()+options.durationMs,latencies=[],ttfbSamples=[],statusCounts={},issued=0,successCount=0,errorCount=0,totalBytes=0;try{let workers=Array.from({length:options.concurrency},async(_unused,idx)=>{let session=sessions[idx%sessions.length];while(Date.now()<deadline&&issued<options.maxRequests&&options.signal?.aborted!==!0){if(session.closed||session.destroyed)break;issued+=1;let sample=await executeH2Stream({session,pathAndQuery,timeoutMs:Math.min(5000,Math.max(2500,deadline-Date.now())),signal:options.signal});if(latencies.push(sample.totalMs),ttfbSamples.push(sample.ttfbMs),totalBytes+=sample.bytes,sample.status>0){let key=String(sample.status);statusCounts[key]=(statusCounts[key]??0)+1}else statusCounts.error=(statusCounts.error??0)+1;if(sample.ok)successCount+=1;else errorCount+=1}});await Promise.all(workers)}finally{for(let s of sessions)try{s.destroy()}catch{}}if(options.signal?.aborted===!0)throw new RimError("CANCELLED",rimT(options.locale,"压测探针已取消","Load probe cancelled"));let elapsedMs=Math.max(1,Math.round(performance.now()-startedAt)),totalRequests=successCount+errorCount;return{runnerUsed:"builtin-h2",protocol:"h2",totalRequests,successCount,errorCount,elapsedMs,rps:Math.round(totalRequests/(elapsedMs/1000)*10)/10,latency:computeLatencyStats(latencies),ttfbLatency:computeLatencyStats(ttfbSamples),totalBytes,throughputBytesPerSec:Math.round(totalBytes/(elapsedMs/1000)),statusCounts}}function createPinnedLookup(pin){return(_hostname,optsOrCb,maybeCb)=>{let cb=typeof optsOrCb==="function"?optsOrCb:maybeCb;if(cb===void 0)return;if(typeof optsOrCb==="object"&&optsOrCb!==null&&optsOrCb.all===!0)cb(null,[{address:pin.address,family:pin.family}]);else cb(null,pin.address,pin.family)}}function executeH1Request(options){let startedAt=performance.now(),reqFn=options.isHttps?httpsRequest2:httpRequest2;return new Promise((resolvePromise)=>{let settled=!1,ttfbMs=0,bytes=0,finish=(sample)=>{if(settled)return;settled=!0,clearTimeout(timer),options.signal?.removeEventListener("abort",onAbort),resolvePromise(sample)},req=reqFn({protocol:options.parsedUrl.protocol,hostname:options.cleanHost,port:options.port,path:`${options.parsedUrl.pathname}${options.parsedUrl.search}`,method:"GET",agent:options.agent,lookup:options.lookup,headers:{Host:options.parsedUrl.host,"Accept-Encoding":"br, gzip",Connection:"keep-alive"},...options.isHttps&&isIP4(options.cleanHost)===0?{servername:options.cleanHost}:{},...options.isHttps&&options.ca!==void 0?{ca:options.ca}:{}},(res)=>{ttfbMs=performance.now()-startedAt;let status=res.statusCode??0;res.on("data",(chunk)=>{if(bytes+=Buffer.isBuffer(chunk)?chunk.byteLength:Buffer.byteLength(chunk),bytes>MAX_LOAD_WIRE_BYTES){res.destroy();let totalMs=performance.now()-startedAt;finish({status,ok:status>=200&&status<400,ttfbMs,totalMs,bytes})}}),res.once("end",()=>{let totalMs=performance.now()-startedAt;finish({status,ok:status>=200&&status<400,ttfbMs,totalMs,bytes})}),res.once("error",()=>{let totalMs=performance.now()-startedAt;finish({status:0,ok:!1,ttfbMs,totalMs,bytes})}),res.once("close",()=>{if(!settled){let totalMs=performance.now()-startedAt;finish({status:0,ok:!1,ttfbMs,totalMs,bytes})}})}),abortReq=()=>{req.destroy();let totalMs=performance.now()-startedAt;finish({status:0,ok:!1,ttfbMs:ttfbMs>0?ttfbMs:totalMs,totalMs,bytes})},onAbort=()=>abortReq();options.signal?.addEventListener("abort",onAbort,{once:!0});let timer=setTimeout(abortReq,Math.max(300,options.timeoutMs));req.once("error",()=>{let totalMs=performance.now()-startedAt;finish({status:0,ok:!1,ttfbMs:ttfbMs>0?ttfbMs:totalMs,totalMs,bytes})}),req.end()})}async function runBuiltinH1Load(options){let isHttps=options.parsedUrl.protocol==="https:",cleanHost=options.parsedUrl.hostname.replace(/^\[|\]$/g,""),port=resolveLoadPort(options.parsedUrl),lookup=createPinnedLookup(options.pin),agent=isHttps?new HttpsAgent({keepAlive:!0,maxSockets:options.concurrency,maxFreeSockets:options.concurrency,...options.ca!==void 0?{ca:options.ca}:{}}):new HttpAgent({keepAlive:!0,maxSockets:options.concurrency,maxFreeSockets:options.concurrency}),startedAt=performance.now(),deadline=Date.now()+options.durationMs,latencies=[],ttfbSamples=[],statusCounts={},issued=0,successCount=0,errorCount=0,totalBytes=0;try{let workers=Array.from({length:options.concurrency},async()=>{while(Date.now()<deadline&&issued<options.maxRequests&&options.signal?.aborted!==!0){issued+=1;let sample=await executeH1Request({parsedUrl:options.parsedUrl,cleanHost,port,isHttps,agent,lookup,ca:options.ca,timeoutMs:Math.min(5000,Math.max(2500,deadline-Date.now())),signal:options.signal});if(latencies.push(sample.totalMs),ttfbSamples.push(sample.ttfbMs),totalBytes+=sample.bytes,sample.status>0){let key=String(sample.status);statusCounts[key]=(statusCounts[key]??0)+1}else statusCounts.error=(statusCounts.error??0)+1;if(sample.ok)successCount+=1;else errorCount+=1}});await Promise.all(workers)}finally{agent.destroy()}if(options.signal?.aborted===!0)throw new RimError("CANCELLED",rimT(options.locale,"压测探针已取消","Load probe cancelled"));let elapsedMs=Math.max(1,Math.round(performance.now()-startedAt)),totalRequests=successCount+errorCount;return{runnerUsed:"builtin-h1",protocol:"http/1.1",totalRequests,successCount,errorCount,elapsedMs,rps:Math.round(totalRequests/(elapsedMs/1000)*10)/10,latency:computeLatencyStats(latencies),ttfbLatency:computeLatencyStats(ttfbSamples),totalBytes,throughputBytesPerSec:Math.round(totalBytes/(elapsedMs/1000)),statusCounts}}async function runBuiltinPooledLoad(options){let parsedUrl=new URL(options.targetUrl),prefer=options.preferProtocol??"auto";try{let useH2=!1;if(prefer==="h2")useH2=!0;else if(prefer==="auto"&&parsedUrl.protocol==="https:")useH2=await probeHttpsAlpn({pin:options.pin,parsedUrl,ca:options.ca,timeoutMs:Math.min(Math.max(options.durationMs,2000),3000),signal:options.signal})==="h2";if(useH2){let h2Res=await runBuiltinH2Load({parsedUrl,pin:options.pin,concurrency:options.concurrency,durationMs:options.durationMs,maxRequests:options.maxRequests,ca:options.ca,locale:options.locale,signal:options.signal});if(h2Res!==null&&h2Res.totalRequests>0)return h2Res}}catch(error){if(isRimError(error)&&(error.code==="CANCELLED"||error.code==="SSRF_BLOCKED"))throw error}return await runBuiltinH1Load({parsedUrl,pin:options.pin,concurrency:options.concurrency,durationMs:options.durationMs,maxRequests:options.maxRequests,ca:options.ca,locale:options.locale,signal:options.signal})}var MAX_LOAD_CONCURRENCY=20,MAX_LOAD_DURATION_MS=15000,MAX_LOAD_REQUESTS=500;function computeLatencyPercentiles(samplesMs){return computeLatencyStats(samplesMs)}async function runBuiltinLoad(options){let startedAt=performance.now(),deadline=Date.now()+options.durationMs,latencies=[],statusCounts={},issued=0,successCount=0,errorCount=0,workers=Array.from({length:options.concurrency},async()=>{while(Date.now()<deadline&&issued<options.maxRequests&&options.signal?.aborted!==!0){issued+=1;let reqStart=performance.now();try{let res=await ssrfHttpRequest({url:options.targetUrl,method:"GET",headers:{"Accept-Encoding":"br, gzip"},allowLoopback:options.allowLoopback,followRedirects:!1,timeoutMs:Math.min(5000,Math.max(2500,deadline-Date.now())),readBody:!0,maxWireBytes:524288,locale:options.locale,signal:options.signal,fetchFn:options.fetchFn});latencies.push(performance.now()-reqStart);let key=String(res.status);if(statusCounts[key]=(statusCounts[key]??0)+1,res.status>=200&&res.status<400)successCount+=1;else errorCount+=1}catch(error){if(isRimError(error)&&(error.code==="CANCELLED"||error.code==="SSRF_BLOCKED"))throw error;latencies.push(performance.now()-reqStart),errorCount+=1,statusCounts.error=(statusCounts.error??0)+1}}});await Promise.all(workers);let elapsedMs=Math.max(1,Math.round(performance.now()-startedAt)),totalRequests=successCount+errorCount,rps=Math.round(totalRequests/(elapsedMs/1000)*10)/10;return{totalRequests,successCount,errorCount,elapsedMs,rps,latency:computeLatencyPercentiles(latencies),statusCounts}}async function dispatchLoadRunner(options){let resolver=options.resolveAdapterBin??((names)=>resolveAbsoluteFromPath(names)),runnerUsed="builtin",result=null,builtinDetails=null;if(options.fetchFn===void 0&&(options.runnerCfg==="oha"||options.runnerCfg==="auto")){let ohaBin=resolver(["oha"]);if(ohaBin!==null){if(result=await runOhaAdapter({binPath:ohaBin,targetUrl:options.targetUrl,concurrency:options.concurrency,maxRequests:options.maxRequests,timeoutMs:options.extTimeout,locale:options.locale,signal:options.signal}),result!==null)runnerUsed="oha"}}if(result===null&&options.fetchFn===void 0&&(options.runnerCfg==="h2load"||options.runnerCfg==="auto")){let h2loadBin=resolver(["h2load"]);if(h2loadBin!==null){if(result=await runH2loadAdapter({binPath:h2loadBin,targetUrl:options.targetUrl,concurrency:options.concurrency,maxRequests:options.maxRequests,timeoutMs:options.extTimeout,locale:options.locale,signal:options.signal}),result!==null)runnerUsed="h2load"}}if(result===null)if(options.fetchFn===void 0&&options.pinnedHost!==null)builtinDetails=await runBuiltinPooledLoad({targetUrl:options.targetUrl,pin:options.pinnedHost,concurrency:options.concurrency,durationMs:options.durationMs,maxRequests:options.maxRequests,locale:options.locale,signal:options.signal}),result=builtinDetails,runnerUsed=builtinDetails.runnerUsed;else result=await runBuiltinLoad({targetUrl:options.targetUrl,allowLoopback:options.loopback,concurrency:options.concurrency,durationMs:options.durationMs,maxRequests:options.maxRequests,locale:options.locale,signal:options.signal,fetchFn:options.fetchFn});return{runnerUsed,result,builtinDetails}}async function runLoadProbe(options){let startedAt=performance.now(),{targetUrl,allowLoad,locale}=options,cfg=options.loadConfig??{},loopback=await isLoopbackTarget(targetUrl,options.lookupFn);if(!loopback&&!allowLoad){let reason=rimT(locale,"安全护栏: 对非回环公网目标运行 load 压测必须显式传入 --allow-load (已跳过)","Safety guard: running load probe against non-loopback targets requires --allow-load (skipped)");return{id:"load",status:"SKIP",durationMs:Math.max(0,Math.round(performance.now()-startedAt)),metrics:{loopback,allowLoad},findings:[{id:"load:requires-allow-load",probe:"load",status:"SKIP",title:reason}],evidence:{targetUrl,loopback,allowLoad},reason}}let pinnedHost=null;if(options.fetchFn===void 0){let parsedTarget=new URL(targetUrl);pinnedHost=await resolveAndPinHost({hostname:parsedTarget.hostname,allowLoopback:loopback,locale,lookupFn:options.lookupFn})}let concurrency=Math.max(1,Math.min(Math.round(cfg.concurrency??8),MAX_LOAD_CONCURRENCY)),durationMs=Math.max(200,Math.min(Math.round(cfg.durationMs??2000),MAX_LOAD_DURATION_MS)),maxRequests=Math.max(1,Math.min(Math.round(cfg.maxRequests??120),MAX_LOAD_REQUESTS)),{runnerUsed,result,builtinDetails}=await dispatchLoadRunner({targetUrl,loopback,pinnedHost,runnerCfg:cfg.runner,concurrency,durationMs,maxRequests,extTimeout:Math.min(options.timeoutMs,durationMs+5000),locale,signal:options.signal,fetchFn:options.fetchFn,resolveAdapterBin:options.resolveAdapterBin});if(options.signal?.aborted===!0)throw new RimError("CANCELLED",rimT(locale,"压测探针已取消","Load probe cancelled"));let errorRate=result.totalRequests>0?result.errorCount/result.totalRequests:1,findings=[];if(errorRate>0.05)findings.push({id:"load:error-rate",probe:"load",status:"FAIL",title:rimT(locale,`短时压测错误率偏高: ${result.errorCount}/${result.totalRequests} (${Math.round(errorRate*100)}%)`,`Load error rate too high: ${result.errorCount}/${result.totalRequests} (${Math.round(errorRate*100)}%)`),value:Math.round(errorRate*1000)/10,threshold:5});else findings.push({id:"load:summary",probe:"load",status:errorRate>0?"WARN":"PASS",title:rimT(locale,`并发压测 (${runnerUsed}, c=${concurrency}, n=${result.totalRequests}): ${result.rps} RPS | p50 ${result.latency.p50Ms}ms / p95 ${result.latency.p95Ms}ms / p99 ${result.latency.p99Ms}ms`,`Load test (${runnerUsed}, c=${concurrency}, n=${result.totalRequests}): ${result.rps} RPS | p50 ${result.latency.p50Ms}ms / p95 ${result.latency.p95Ms}ms / p99 ${result.latency.p99Ms}ms`),value:result.rps});let finalFindings=applyWaiversToFindings(findings,options.waivers);return{id:"load",status:aggregateProbeStatus(finalFindings,"PASS"),durationMs:Math.max(0,Math.round(performance.now()-startedAt)),metrics:{runner:runnerUsed,...builtinDetails!==null?{protocol:builtinDetails.protocol,ttfbP50Ms:builtinDetails.ttfbLatency.p50Ms,ttfbP95Ms:builtinDetails.ttfbLatency.p95Ms,totalBytes:builtinDetails.totalBytes,throughputBytesPerSec:builtinDetails.throughputBytesPerSec}:{},concurrency,totalRequests:result.totalRequests,successCount:result.successCount,errorCount:result.errorCount,rps:result.rps,minMs:result.latency.minMs,p50Ms:result.latency.p50Ms,p95Ms:result.latency.p95Ms,p99Ms:result.latency.p99Ms,maxMs:result.latency.maxMs},findings:finalFindings,evidence:{targetUrl:sanitizeLine(targetUrl),loopback,runner:runnerUsed,...builtinDetails!==null?{protocol:builtinDetails.protocol,ttfbLatency:builtinDetails.ttfbLatency,totalBytes:builtinDetails.totalBytes,throughputBytesPerSec:builtinDetails.throughputBytesPerSec}:{},caps:{maxConcurrency:MAX_LOAD_CONCURRENCY,maxDurationMs:MAX_LOAD_DURATION_MS,maxRequests:MAX_LOAD_REQUESTS},statusCounts:result.statusCounts}}}var CAT_CHECKS=[{lhrKey:"performance",thresholdKey:"performance"},{lhrKey:"accessibility",thresholdKey:"accessibility"},{lhrKey:"best-practices",thresholdKey:"bestPractices"},{lhrKey:"seo",thresholdKey:"seo"}];function checkAborted(signal,locale){if(signal?.aborted===!0)throw new RimError("CANCELLED",rimT(locale,"性能探针执行已取消","Performance probe cancelled"))}function buildPerfFindings(summaries,thresholds,waivers,locale){let rawFindings=[];for(let s of summaries){if(s.runtimeError!==void 0)rawFindings.push({id:`perf:${s.preset}:runtime`,probe:"perf",status:"FAIL",title:`${s.preset} runtimeError (${s.runtimeError.code??"ERROR"}): ${s.runtimeError.message}`,device:s.preset,route:s.route});for(let cat of CAT_CHECKS){let score=s.scores[cat.lhrKey],minVal=thresholds[cat.thresholdKey];if(score===null||score===void 0||!Number.isFinite(score))rawFindings.push({id:`perf:${s.preset}:${cat.lhrKey}`,probe:"perf",status:"SKIP",title:rimT(locale,`${s.preset} ${cat.lhrKey} 得分缺失 (null)`,`${s.preset} ${cat.lhrKey} score missing (null)`),value:null,threshold:minVal,device:s.preset,route:s.route});else rawFindings.push({id:`perf:${s.preset}:${cat.lhrKey}`,probe:"perf",status:score<minVal?"FAIL":"PASS",title:`${s.preset} ${cat.lhrKey}=${score} ${score<minVal?"<":">="} ${minVal}`,value:score,threshold:minVal,device:s.preset,route:s.route})}if(!s.longTasksAuditPresent)rawFindings.push({id:`perf:${s.preset}:long-tasks`,probe:"perf",status:"SKIP",title:`${s.preset} long-tasks audit missing`,device:s.preset,route:s.route});else{let over=s.longTasks.length>thresholds.maxLongTasks;rawFindings.push({id:`perf:${s.preset}:long-tasks`,probe:"perf",status:over?"FAIL":"PASS",title:`${s.preset} long-tasks=${s.longTasks.length} ${over?">":"<="} ${thresholds.maxLongTasks}`,value:s.longTasks.length,threshold:thresholds.maxLongTasks,device:s.preset,route:s.route})}if(thresholds.maxTbtMs!==void 0)if(s.metrics.tbtMs===null)rawFindings.push({id:`perf:${s.preset}:tbt`,probe:"perf",status:"SKIP",title:`${s.preset} tbtMs is missing`,value:null,threshold:thresholds.maxTbtMs,device:s.preset,route:s.route});else{let over=s.metrics.tbtMs>thresholds.maxTbtMs;rawFindings.push({id:`perf:${s.preset}:tbt`,probe:"perf",status:over?"FAIL":"PASS",title:`${s.preset} tbt=${s.metrics.tbtMs}ms ${over?">":"<="} ${thresholds.maxTbtMs}ms`,value:s.metrics.tbtMs,threshold:thresholds.maxTbtMs,device:s.preset,route:s.route})}if(thresholds.maxCls!==void 0)if(s.metrics.clsValue===null)rawFindings.push({id:`perf:${s.preset}:cls`,probe:"perf",status:"SKIP",title:`${s.preset} cls is missing`,value:null,threshold:thresholds.maxCls,device:s.preset,route:s.route});else{let over=s.metrics.clsValue>thresholds.maxCls;rawFindings.push({id:`perf:${s.preset}:cls`,probe:"perf",status:over?"FAIL":"PASS",title:`${s.preset} cls=${s.metrics.clsValue} ${over?">":"<="} ${thresholds.maxCls}`,value:s.metrics.clsValue,threshold:thresholds.maxCls,device:s.preset,route:s.route})}for(let lf of s.findings)if(lf.waived===!0)rawFindings.push({id:lf.id,probe:"perf",status:"WAIVED",title:`${s.preset} ${lf.id}: ${lf.title}`,waiverReason:lf.waiverReason,device:s.preset,route:s.route})}return applyWaiversToFindings(rawFindings,waivers)}function toLegacyStatus(status){if(status==="FAIL")return"fail";if(status==="WARN")return"warn";return"pass"}async function runPerfProbe(options){let startedAt=performance.now(),{targetUrl,routes,devices,projectRoot,chromePath,coldGpu,cpuSlowdown,outDir,writeReports,thresholds,waivers,timeoutMs,locale,signal,onProgress}=options;if(devices.length===0){let reason=rimT(locale,"未配置任何设备档位 (mobile / desktop)","No device profiles configured (mobile / desktop)");return{probe:{id:"perf",status:"SKIP",durationMs:0,metrics:{},findings:[],evidence:{adapter:options.perfAdapter?.name??"lighthouse"},reason},status:"skip",reason,summaries:[]}}let parsedTarget=new URL(targetUrl),effectiveRoutes=routes.length>0?routes:[`${parsedTarget.pathname}${parsedTarget.search}`||"/"],multiRoute=effectiveRoutes.length>1,launchFn=options.launchChromeFn??launchChrome,summaries=[],lhWarmup=options.perfAdapter===void 0&&options.lighthouseRunner===void 0?loadLighthouseFn(projectRoot,locale).catch(()=>{}):null;for(let route of effectiveRoutes){let routeUrl=effectiveRoutes.length===1&&(route===parsedTarget.pathname||route===`${parsedTarget.pathname}${parsedTarget.search}`)?targetUrl:resolveSameOriginUrl(parsedTarget.origin,route,locale,"route");for(let device of devices){if(checkAborted(signal,locale),onProgress?.({phase:"perf",detail:rimT(locale,`运行 Lighthouse (${device}${multiRoute?` ${route}`:""})`,`Running Lighthouse (${device}${multiRoute?` ${route}`:""})`)}),options.perfAdapter!==void 0){let out=await options.perfAdapter.run({url:routeUrl,route,device,chromePath,coldGpu,cpuSlowdown,outDir,writeReports,timeoutMs,locale,signal});summaries.push(out.summary);continue}let session=await launchFn({chromePath,coldGpu,timeoutMs:Math.min(timeoutMs,25000),locale,signal});try{if(lhWarmup!==null)await lhWarmup;let summary=await runLighthousePresetAudit({url:routeUrl,route,multiRoute,port:session.port,preset:device,cpuSlowdown,outDir,writeReports,cwd:projectRoot,locale,waivers,signal,runner:options.lighthouseRunner});summaries.push(summary)}finally{await session.cleanup()}}}let finalFindings=buildPerfFindings(summaries,thresholds,waivers,locale),probeStatus=aggregateProbeStatus(finalFindings,"PASS"),mobileSummary=summaries.find((s)=>s.preset==="mobile"),desktopSummary=summaries.find((s)=>s.preset==="desktop");return{probe:{id:"perf",status:probeStatus,durationMs:Math.max(0,Math.round(performance.now()-startedAt)),metrics:{runs:summaries.length,...mobileSummary!==void 0?{mobilePerf:mobileSummary.scores.performance,mobileA11y:mobileSummary.scores.accessibility,mobileBp:mobileSummary.scores["best-practices"],mobileSeo:mobileSummary.scores.seo,mobileLongTasks:mobileSummary.longTasks.length,mobileTbtMs:mobileSummary.metrics.tbtMs,mobileCls:mobileSummary.metrics.clsValue}:{},...desktopSummary!==void 0?{desktopPerf:desktopSummary.scores.performance,desktopA11y:desktopSummary.scores.accessibility,desktopBp:desktopSummary.scores["best-practices"],desktopSeo:desktopSummary.scores.seo,desktopLongTasks:desktopSummary.longTasks.length,desktopTbtMs:desktopSummary.metrics.tbtMs,desktopCls:desktopSummary.metrics.clsValue}:{}},findings:finalFindings,evidence:{adapter:options.perfAdapter?.name??"lighthouse",coldGpu,cpuSlowdown,routes:effectiveRoutes,devices}},status:toLegacyStatus(probeStatus),summaries}}function matchesAnyOrigin(rawUrl,allowedOrigins){try{return allowedOrigins.has(new URL(rawUrl).origin)}catch{return!1}}async function runSingleProtocolCapture(options){let launcher=options.launchChromeFn??launchChrome,targetOrigin=new URL(options.targetUrl).origin,startedAt=performance.now(),session=await launcher({chromePath:options.chromePath,coldGpu:!1,timeoutMs:Math.min(options.timeoutMs,15000),locale:options.locale,extraFlags:options.extraFlags,signal:options.signal}),cdp=null;try{let wsUrl=await waitForCdpPageWsUrl({debugPort:session.port,timeoutMs:Math.min(options.timeoutMs,1e4),locale:options.locale,signal:options.signal});cdp=await CdpClient.connect(wsUrl,Math.min(options.timeoutMs,1e4),options.signal),await cdp.send("Page.enable"),await cdp.send("Network.enable"),await cdp.send("Network.setCacheDisabled",{cacheDisabled:!0});let completed=!1,allowedOrigins=new Set([targetOrigin]),navStarted=performance.now();await cdp.send("Page.navigate",{url:options.targetUrl});let deadline=Date.now()+options.timeoutMs;while(Date.now()<deadline){if(options.signal?.aborted===!0)break;let navState=await cdp.evalValue("({ ready: document.readyState === 'complete', href: window.location.href })",2000).catch(()=>({ready:!1,href:"about:blank"}));if(typeof navState?.href==="string"&&(navState.href.startsWith("http://")||navState.href.startsWith("https://")))try{allowedOrigins.add(new URL(navState.href).origin)}catch{}if(navState?.ready===!0&&navState.href!=="about:blank"&&cdp.networkRecords.size>0){if(await sleepMs(250,options.signal).catch(()=>{}),[...cdp.networkRecords.values()].filter((r)=>matchesAnyOrigin(r.url,allowedOrigins)&&!r.finished&&!r.failed).length===0){completed=!0;break}}let step=Math.min(100,Math.max(0,deadline-Date.now()));if(step>0)await sleepMs(step,options.signal).catch(()=>{})}let durationMs=Math.max(0,Math.round(performance.now()-navStarted)),sameOriginRecords=[...cdp.networkRecords.values()].filter((r)=>matchesAnyOrigin(r.url,allowedOrigins)),protocols=new Set,finishedCount=0,failedCount=0,stalledCount=0,totalEncodedBytes=0,mainProtocol=null,failedSamples=[];for(let rec of sameOriginRecords){if(rec.protocol!==void 0&&rec.protocol!==""){if(protocols.add(rec.protocol.toLowerCase()),mainProtocol===null)mainProtocol=rec.protocol.toLowerCase()}if(totalEncodedBytes+=rec.encodedDataLength,rec.failed||rec.status!==void 0&&rec.status>=400){if(failedCount+=1,failedSamples.length<5)failedSamples.push(sanitizeLine(`${rec.url} (${rec.errorText??`HTTP ${String(rec.status)}`})`))}else if(rec.finished)finishedCount+=1;else if(stalledCount+=1,failedSamples.length<5)failedSamples.push(sanitizeLine(`${rec.url} (stalled/in-flight)`))}return{mode:options.mode,completed:completed&&sameOriginRecords.length>0&&failedCount===0&&stalledCount===0,durationMs:durationMs>0?durationMs:Math.round(performance.now()-startedAt),totalRequests:sameOriginRecords.length,finishedCount,failedCount,stalledCount,totalEncodedBytes,protocols:[...protocols].sort(),mainProtocol,failedSamples}}finally{cdp?.close(),await session.cleanup()}}async function runH2H3MtuProbe(options){let{targetUrl,chromePath,locale,signal}=options,parsed;try{parsed=new URL(targetUrl)}catch{return{status:"SKIP",reason:rimT(locale,"目标 URL 无效, 跳过 H2/H3 探针","Invalid URL; skipping H2/H3 probe")}}if(parsed.protocol!=="https:")return{status:"SKIP",reason:rimT(locale,"目标为纯 HTTP 地址 (QUIC/H3 仅适用于 HTTPS), 跳过 H2/H3 对比","Target is plain HTTP (QUIC/H3 requires HTTPS); skipping H2/H3 probe")};if(chromePath===null||chromePath==="")return{status:"SKIP",reason:rimT(locale,"未检测到本机 Chrome, 跳过 CDP H2/H3 对比探针","Chrome not detected; skipping CDP H2/H3 comparison probe")};let hostPort=`${parsed.hostname}:${parsed.port!==""?parsed.port:"443"}`,perRunTimeout=Math.min(options.timeoutMs??15000,20000);try{let h2=await runSingleProtocolCapture({targetUrl,mode:"h2",chromePath,extraFlags:["--disable-quic"],timeoutMs:perRunTimeout,locale,signal,launchChromeFn:options.launchChromeFn});if(signal?.aborted===!0)throw new RimError("CANCELLED",rimT(locale,"H2/H3 探针已取消","H2/H3 probe cancelled"));let h3=await runSingleProtocolCapture({targetUrl,mode:"h3",chromePath,extraFlags:["--enable-quic",`--origin-to-force-quic-on=${hostPort}`],timeoutMs:perRunTimeout,locale,signal,launchChromeFn:options.launchChromeFn}),h3Negotiated=h3.protocols.some((p)=>p.startsWith("h3")),h3HasQuicFailure=h3.totalRequests===0||h3.failedCount>0||h3.stalledCount>0||!h3.completed,h2Healthy=h2.totalRequests>0&&h2.completed&&h2.failedCount===0&&h2.stalledCount===0;if(h2Healthy&&h3HasQuicFailure)return{status:"FAIL",h2,h3,h3Negotiated,mtuBlackholeSuspected:!0,reason:rimT(locale,`疑似 QUIC 路径 MTU 黑洞: H2 完整加载 (${h2.finishedCount}/${h2.totalRequests}, ${h2.durationMs}ms), 但 H3 出现失败/挂起 (${h3.failedCount} 失败, ${h3.stalledCount} 挂起)`,`Suspected QUIC Path MTU blackhole: H2 succeeded (${h2.finishedCount}/${h2.totalRequests}, ${h2.durationMs}ms) while H3 failed/stalled (${h3.failedCount} failed, ${h3.stalledCount} stalled)`)};if(h3HasQuicFailure)return{status:"FAIL",h2,h3,h3Negotiated,mtuBlackholeSuspected:!1,reason:rimT(locale,`H2 与 H3 加载均存在异常: H2 (${h2.failedCount} 失败, ${h2.stalledCount} 挂起), H3 (${h3.failedCount} 失败, ${h3.stalledCount} 挂起)`,`Both H2 and H3 reported load errors: H2 (${h2.failedCount} failed, ${h2.stalledCount} stalled), H3 (${h3.failedCount} failed, ${h3.stalledCount} stalled)`)};if(!h2Healthy)return{status:"WARN",h2,h3,h3Negotiated,mtuBlackholeSuspected:!1,reason:rimT(locale,`H3 加载成功 (${h3.finishedCount}/${h3.totalRequests}), 但 H2 对照组异常 (${h2.failedCount} 失败, ${h2.stalledCount} 挂起)`,`H3 succeeded (${h3.finishedCount}/${h3.totalRequests}), while H2 baseline had errors (${h2.failedCount} failed, ${h2.stalledCount} stalled)`)};if(!h3Negotiated)return{status:"WARN",h2,h3,h3Negotiated:!1,mtuBlackholeSuspected:!1,reason:rimT(locale,`H3/QUIC 未协商生效 (实际协议: ${h3.protocols.join(", ")||"unknown"}; H2 ${h2.durationMs}ms vs H3 ${h3.durationMs}ms)`,`H3/QUIC was not negotiated (observed: ${h3.protocols.join(", ")||"unknown"}; H2 ${h2.durationMs}ms vs H3 ${h3.durationMs}ms)`)};return{status:"PASS",h2,h3,h3Negotiated:!0,mtuBlackholeSuspected:!1,reason:rimT(locale,`H2 (${h2.durationMs}ms) 与 H3 (${h3.durationMs}ms, ${h3.protocols.join(",")}) 全部 ${h3.finishedCount} 个资产完整加载, 无 MTU 黑洞`,`H2 (${h2.durationMs}ms) and H3 (${h3.durationMs}ms, ${h3.protocols.join(",")}) loaded all ${h3.finishedCount} assets with no MTU blackhole`)}}catch(error){if(isRimError(error)&&error.code==="CANCELLED")throw error;return{status:"SKIP",reason:rimT(locale,`H2/H3 探针执行受限已跳过: ${sanitizeLine(error instanceof Error?error.message:String(error))}`,`H2/H3 probe skipped due to runtime limitation: ${sanitizeLine(error instanceof Error?error.message:String(error))}`)}}}var LINK_HEADER_ITEM_RE=/<([^>]+)>([^,]*)/g,LINK_REL_RE=/;\s*rel\s*=\s*"?([^";\s]+)"?/i,LINK_AS_RE=/;\s*as\s*=\s*"?([^";\s]+)"?/i,HTML_COMMENTS_RE=/<!--[\s\S]*?-->/g,STRIP_NON_MARKUP_RE=/<script\b[^>]*>[\s\S]*?<\/script>|<style\b[^>]*>[\s\S]*?<\/style>/gi;function hasUnsafeRootRelChar(value){for(let i=0;i<value.length;i+=1){let c=value.charCodeAt(i);if(c<=32||c===92)return!0}return!1}var TAG_RE=/<([a-zA-Z][a-zA-Z0-9-]*)\s+([^>]+)>/g,ATTR_RE=/([a-zA-Z_:][a-zA-Z0-9_.:-]*)(?:\s*=\s*(?:"([^"]*)"|'([^']*)'|([^\s"'=<>`]+)))?/g,SCRIPT_SRC_TAG_RE=/<script\b([^>]*\bsrc\s*=[^>]*)>/gi,ID_ATTR_FAST_RE=/\bid\s*=\s*(?:"([^"]*)"|'([^']*)'|([^\s"'=<>`]+))/i,NON_HTTP_SCHEME_RE=/^(?:mailto:|tel:|javascript:|data:|blob:|about:)/i,HTML_ATTR_ENTITY_RE=/&(?:amp|quot|apos|lt|gt|#38|#39|#x26|#x27);/gi,HTML_ATTR_ENTITY_MAP={"&":"&","&":"&","&":"&",""":'"',"'":"'","'":"'","'":"'","<":"<",">":">"};function decodeHtmlAttrEntities(value){if(!value.includes("&"))return value;return value.replace(HTML_ATTR_ENTITY_RE,(m)=>HTML_ATTR_ENTITY_MAP[m.toLowerCase()]??m)}var LINK_RESOURCE_RELS=new Set(["icon","shortcut","apple-touch-icon","manifest","canonical"]),RESOURCE_TAGS=new Set(["a","link","img","source","video","audio","iframe","area"]);function parseSrcsetUrls(rawSrcset){let out=[],len=rawSrcset.length,i=0;while(i<len){while(i<len){let c=rawSrcset.charCodeAt(i);if(c>32&&c!==44)break;i+=1}if(i>=len)break;let urlStart=i;while(i<len&&rawSrcset.charCodeAt(i)>32)i+=1;let url=rawSrcset.slice(urlStart,i);if(url.endsWith(",")){while(url.endsWith(","))url=url.slice(0,-1);if(url!=="")out.push(url);continue}if(url!=="")out.push(url);let parenDepth=0;while(i<len){let ch=rawSrcset.charCodeAt(i);if(ch===40)parenDepth+=1;else if(ch===41&&parenDepth>0)parenDepth-=1;else if(ch===44&&parenDepth===0){i+=1;break}i+=1}}return out}function resolveWithParsedBase(rawHref,parsedBase,baseOrigin){let trimmed=rawHref.trim();if(trimmed===""||trimmed.charCodeAt(0)===35)return null;if(trimmed.charCodeAt(0)===47&&trimmed.charCodeAt(1)!==47&&!trimmed.includes("/.")&&!hasUnsafeRootRelChar(trimmed))return`${baseOrigin}${trimmed}`;if(NON_HTTP_SCHEME_RE.test(trimmed))return null;try{let resolved=new URL(trimmed,parsedBase);if(resolved.protocol!=="http:"&&resolved.protocol!=="https:")return null;return resolved.href}catch{return null}}function parseLinkPreloadWithBase(linkHeaders,parsedBase,baseOrigin){if(linkHeaders.length===0)return[];let out=[];for(let i=0;i<linkHeaders.length;i+=1){let header=linkHeaders[i];if(header.trim()==="")continue;LINK_HEADER_ITEM_RE.lastIndex=0;let m;while((m=LINK_HEADER_ITEM_RE.exec(header))!==null){let rawHref=m[1].trim(),params=m[2]??"",rel=LINK_REL_RE.exec(params)?.[1]?.toLowerCase();if(rel!=="preload"&&rel!=="modulepreload")continue;let resolvedUrl=resolveWithParsedBase(rawHref,parsedBase,baseOrigin);if(resolvedUrl===null)continue;let asMatch=LINK_AS_RE.exec(params);out.push({rawHref,resolvedUrl,rel,...asMatch?.[1]!==void 0?{as:asMatch[1].toLowerCase()}:{},source:"header"})}}return out}function extractScriptSrcLinks(html,parsedBase,baseOrigin,links){if(!html.includes("<script")&&!html.includes("<SCRIPT"))return;SCRIPT_SRC_TAG_RE.lastIndex=0;let sm;while((sm=SCRIPT_SRC_TAG_RE.exec(html))!==null){ATTR_RE.lastIndex=0;let am;while((am=ATTR_RE.exec(sm[1]))!==null){if(am[1].toLowerCase()!=="src")continue;let src=decodeHtmlAttrEntities((am[2]??am[3]??am[4]??"").trim());if(src!==""){let resolved=resolveWithParsedBase(src,parsedBase,baseOrigin);if(resolved!==null)links.push({rawHref:src,resolvedUrl:resolved,kind:"script"})}break}}}function scanHtmlResources(html,baseUrl,linkHeaders=[]){let parsedBase;try{parsedBase=new URL(baseUrl)}catch{return{preloads:[],links:[],hashAnchors:[],domIds:new Set}}let baseOrigin=parsedBase.origin,preloads=parseLinkPreloadWithBase(linkHeaders,parsedBase,baseOrigin),links=[],hashAnchors=[],domIds=new Set,withoutComments=html.includes("<!--")?html.replace(HTML_COMMENTS_RE," "):html;extractScriptSrcLinks(withoutComments,parsedBase,baseOrigin,links);let stripped=withoutComments.replace(STRIP_NON_MARKUP_RE," ");TAG_RE.lastIndex=0;let tm;while((tm=TAG_RE.exec(stripped))!==null){let rawAttrs=tm[2];if(rawAttrs===void 0||rawAttrs==="")continue;let tag=tm[1].toLowerCase();if(!RESOURCE_TAGS.has(tag)){if(rawAttrs.includes("id")||rawAttrs.includes("ID")){let idMatch=ID_ATTR_FAST_RE.exec(rawAttrs),idVal=decodeHtmlAttrEntities((idMatch?.[1]??idMatch?.[2]??idMatch?.[3]??"").trim());if(idVal!=="")domIds.add(idVal)}continue}let idVal="",nameVal="",hrefVal="",srcVal="",srcsetVal="",posterVal="",relVal="",asVal="";ATTR_RE.lastIndex=0;let am;while((am=ATTR_RE.exec(rawAttrs))!==null){let k=am[1].toLowerCase(),v=decodeHtmlAttrEntities(am[2]??am[3]??am[4]??"");if(k==="id")idVal=v;else if(k==="href")hrefVal=v;else if(k==="src")srcVal=v;else if(k==="srcset")srcsetVal=v;else if(k==="poster")posterVal=v;else if(k==="rel")relVal=v;else if(k==="as")asVal=v;else if(k==="name")nameVal=v}if(idVal.trim()!=="")domIds.add(idVal.trim());if(tag==="a"||tag==="area"){if(tag==="a"&&nameVal.trim()!=="")domIds.add(nameVal.trim());let href=hrefVal.trim();if(href==="")continue;if(href.charCodeAt(0)===35){let targetId=href.slice(1).trim();if(targetId!==""&&targetId.toLowerCase()!=="top")hashAnchors.push(targetId);continue}let resolved=resolveWithParsedBase(href,parsedBase,baseOrigin);if(resolved!==null){let hashIdx=resolved.indexOf("#"),hash=hashIdx!==-1?resolved.slice(hashIdx+1):void 0;links.push({rawHref:href,resolvedUrl:resolved,kind:"anchor",...hash!==void 0&&hash!==""?{hash}:{}})}continue}if(tag==="link"){let href=hrefVal.trim();if(href===""||relVal==="")continue;let relTokens=relVal.toLowerCase().split(/\s+/).filter(Boolean),isModulePreload=relTokens.includes("modulepreload"),isPreload=!isModulePreload&&relTokens.includes("preload"),isStylesheet=!isModulePreload&&!isPreload&&relTokens.includes("stylesheet"),isOtherResource=!isModulePreload&&!isPreload&&!isStylesheet&&relTokens.some((tok)=>LINK_RESOURCE_RELS.has(tok));if(!isModulePreload&&!isPreload&&!isStylesheet&&!isOtherResource)continue;let resolved=resolveWithParsedBase(href,parsedBase,baseOrigin);if(resolved===null)continue;if(isPreload||isModulePreload){let asLower=asVal.trim().toLowerCase();preloads.push({rawHref:href,resolvedUrl:resolved,rel:isModulePreload?"modulepreload":"preload",...asLower!==""?{as:asLower}:{},source:"html"})}else links.push({rawHref:href,resolvedUrl:resolved,kind:isStylesheet?"stylesheet":"link"});continue}let pushCandidate=(raw,kind)=>{let trimmed=raw.trim();if(trimmed==="")return;let resolved=resolveWithParsedBase(trimmed,parsedBase,baseOrigin);if(resolved!==null)links.push({rawHref:trimmed,resolvedUrl:resolved,kind})};if(tag==="img"){if(pushCandidate(srcVal,"img"),srcsetVal.trim()!=="")for(let candidate of parseSrcsetUrls(srcsetVal))pushCandidate(candidate,"img");continue}if(tag==="iframe"){pushCandidate(srcVal,"iframe");continue}if(pushCandidate(srcVal,"media"),posterVal.trim()!=="")pushCandidate(posterVal,"img");if(srcsetVal.trim()!=="")for(let candidate of parseSrcsetUrls(srcsetVal))pushCandidate(candidate,"media")}return{preloads,links,hashAnchors,domIds}}var QUIC_FIRST_PACKET_BYTES=12288,TCP_IW10_FIRST_PACKET_BYTES=14950,FINGERPRINTED_ASSET_RE=/[.-][a-f0-9]{6,32}\.(?:js|mjs|css|wasm|png|webp|avif|svg|woff2?)$/i;function checkEncodingMatch(actual,expected){if(expected===void 0)return!0;let norm=(actual??"").trim().toLowerCase();if(expected==="any")return norm==="br"||norm==="gzip";return norm===expected}async function safeProtoRequest(options){try{return{ok:!0,res:await ssrfHttpRequest(options)}}catch(error){if(error instanceof Error&&"code"in error&&(error.code==="CANCELLED"||error.code==="SSRF_BLOCKED"))throw error;return{ok:!1,error:sanitizeLine(error instanceof Error?error.message:String(error))}}}function evaluateFirstPacketBudget(options){let{htmlBrBytes,budgets,locale,findings}=options;if(budgets?.htmlBrBytes!==void 0){let ok=htmlBrBytes<=budgets.htmlBrBytes;findings.push({id:"proto:html-br-budget",probe:"proto",status:ok?"PASS":"FAIL",title:ok?rimT(locale,`首屏 HTML 压缩体积 ${htmlBrBytes}B <= 预算 ${budgets.htmlBrBytes}B`,`Entry HTML wire size ${htmlBrBytes}B <= budget ${budgets.htmlBrBytes}B`):rimT(locale,`首屏 HTML 压缩体积 ${htmlBrBytes}B 超出预算 ${budgets.htmlBrBytes}B`,`Entry HTML wire size ${htmlBrBytes}B exceeds budget ${budgets.htmlBrBytes}B`),value:htmlBrBytes,threshold:budgets.htmlBrBytes});return}if(htmlBrBytes>TCP_IW10_FIRST_PACKET_BYTES)findings.push({id:"proto:first-packet-iw10",probe:"proto",status:"WARN",title:rimT(locale,`首屏 HTML (${htmlBrBytes}B) 超出 TCP IW10 (14.6 KB) 与 QUIC (12 KB) 单趟首包预算`,`Entry HTML (${htmlBrBytes}B) exceeds TCP IW10 (14.6 KB) and QUIC (12 KB) initial packet budgets`),value:htmlBrBytes,threshold:TCP_IW10_FIRST_PACKET_BYTES});else if(htmlBrBytes>QUIC_FIRST_PACKET_BYTES)findings.push({id:"proto:first-packet-quic",probe:"proto",status:"WARN",title:rimT(locale,`首屏 HTML (${htmlBrBytes}B) 超出 QUIC 12 KB 首包预算 (仍在 TCP IW10 14.6 KB 内)`,`Entry HTML (${htmlBrBytes}B) exceeds QUIC 12 KB budget (within TCP IW10 14.6 KB)`),value:htmlBrBytes,threshold:QUIC_FIRST_PACKET_BYTES});else findings.push({id:"proto:first-packet-quic",probe:"proto",status:"PASS",title:rimT(locale,`首屏 HTML (${htmlBrBytes}B) 满足 QUIC 12 KB / TCP IW10 首包预算`,`Entry HTML (${htmlBrBytes}B) fits within QUIC 12 KB / TCP IW10 initial window`),value:htmlBrBytes,threshold:QUIC_FIRST_PACKET_BYTES})}async function measurePreloadedAssets(options){let{locale,findings,budgets}=options,scan=scanHtmlResources(options.primaryHtml,options.finalUrl,options.linkHeaders),seenUrls=new Set,sameOriginPreloads=scan.preloads.filter((entry)=>{if(seenUrls.has(entry.resolvedUrl))return!1;try{if(new URL(entry.resolvedUrl).origin!==options.targetOrigin)return!1}catch{return!1}return seenUrls.add(entry.resolvedUrl),!0}),measured=await Promise.all(sameOriginPreloads.slice(0,16).map(async(entry)=>{let res=await safeProtoRequest({url:entry.resolvedUrl,headers:{"Accept-Encoding":"br, gzip"},allowLoopback:options.allowLoopback,timeoutMs:Math.min(options.timeoutMs,1e4),locale,signal:options.signal,fetchFn:options.fetchFn}),pathname=new URL(entry.resolvedUrl).pathname,fingerprinted=FINGERPRINTED_ASSET_RE.test(pathname);if(!res.ok)return{url:entry.resolvedUrl,rawHref:sanitizeLine(entry.rawHref),source:entry.source,status:0,contentEncoding:null,wireBytes:0,cacheControl:null,fingerprinted,immutable:!1};let cc=res.res.headers["cache-control"]!==void 0?sanitizeLine(res.res.headers["cache-control"]):null;return{url:entry.resolvedUrl,rawHref:sanitizeLine(entry.rawHref),source:entry.source,status:res.res.status,contentEncoding:res.res.contentEncoding,wireBytes:res.res.wireBytes,cacheControl:cc,fingerprinted,immutable:cc!==null&&/\bimmutable\b/i.test(cc)}})),totalCriticalBrBytes=0;for(let asset of measured)if(asset.status>=200&&asset.status<300){if(totalCriticalBrBytes+=asset.wireBytes,asset.fingerprinted&&!asset.immutable)findings.push({id:"proto:asset-immutable",probe:"proto",status:"WARN",title:rimT(locale,`指纹静态资产缺少 immutable 强缓存: ${asset.rawHref} (${asset.cacheControl??"missing"})`,`Fingerprinted asset missing immutable Cache-Control: ${asset.rawHref} (${asset.cacheControl??"missing"})`),value:asset.cacheControl??"missing"})}else findings.push({id:"proto:preload-broken",probe:"proto",status:"FAIL",title:rimT(locale,`预加载资源不可用 (${asset.status}): ${asset.rawHref}`,`Preloaded critical asset failed (${asset.status}): ${asset.rawHref}`),value:asset.status});if(budgets?.totalCriticalBrBytes!==void 0){let okCrit=totalCriticalBrBytes<=budgets.totalCriticalBrBytes;findings.push({id:"proto:critical-br-budget",probe:"proto",status:okCrit?"PASS":"FAIL",title:okCrit?rimT(locale,`关键预加载资产合计 ${totalCriticalBrBytes}B <= 预算 ${budgets.totalCriticalBrBytes}B`,`Preloaded critical assets total ${totalCriticalBrBytes}B <= budget ${budgets.totalCriticalBrBytes}B`):rimT(locale,`关键预加载资产合计 ${totalCriticalBrBytes}B 超出预算 ${budgets.totalCriticalBrBytes}B`,`Preloaded critical assets total ${totalCriticalBrBytes}B exceeds budget ${budgets.totalCriticalBrBytes}B`),value:totalCriticalBrBytes,threshold:budgets.totalCriticalBrBytes})}return{assets:measured,totalCriticalBrBytes}}async function probeExtraHttpRoutes(options){let{targetUrl,targetOrigin,locale,findings}=options;return await Promise.all(options.routes.map(async(route)=>{let method=route.method??"GET",resolvedUrl=route.path===""||route.path==="."?targetUrl:resolveSameOriginUrl(targetOrigin,route.path,locale,"HTTP route"),expectStatus=route.expectStatus??200,followRedirects=!(expectStatus>=300&&expectStatus<400),resp=await safeProtoRequest({url:resolvedUrl,method,headers:{"Accept-Encoding":"br, gzip, deflate"},allowLoopback:options.allowLoopback,followRedirects,timeoutMs:options.timeoutMs,readBody:!1,locale,signal:options.signal,fetchFn:options.fetchFn});if(!resp.ok)return findings.push({id:`proto:route:${route.path}`,probe:"proto",status:"FAIL",title:`${method} ${route.path}: ${resp.error}`,route:route.path}),{url:resolvedUrl,path:route.path,method,status:0,ttfbMs:0,contentEncoding:null,headers:{},missingRequiredHeaders:route.requireHeaders??[],missingWarnHeaders:[],passed:!1,failureReason:resp.error};let r=resp.res,reasons=[];if(r.status!==expectStatus)reasons.push(rimT(locale,`期望状态码 ${expectStatus}, 实际 ${r.status}`,`expected HTTP ${expectStatus}, got ${r.status}`));if(route.maxTtfbMs!==void 0&&r.ttfbMs>route.maxTtfbMs)reasons.push(`TTFB ${r.ttfbMs}ms > ${route.maxTtfbMs}ms`);if(!checkEncodingMatch(r.contentEncoding,route.expectEncoding))reasons.push(rimT(locale,`期望压缩编码 ${route.expectEncoding}, 实际 ${r.contentEncoding??"无"}`,`expected encoding ${route.expectEncoding}, got ${r.contentEncoding??"none"}`));let missingHdrs=(route.requireHeaders??[]).map((h)=>h.toLowerCase()).filter((h)=>r.headers[h]===void 0||r.headers[h].trim()==="");if(missingHdrs.length>0)reasons.push(rimT(locale,`缺少必需响应头: ${missingHdrs.join(", ")}`,`missing required headers: ${missingHdrs.join(", ")}`));return findings.push({id:`proto:route:${route.path}`,probe:"proto",status:reasons.length===0?"PASS":"FAIL",title:reasons.length===0?`${method} ${route.path} -> ${r.status} (${r.ttfbMs}ms${r.contentEncoding!==null?`, ${r.contentEncoding}`:""})`:`${method} ${route.path}: ${reasons.join("; ")}`,value:r.status,route:route.path}),{url:resolvedUrl,path:route.path,method,status:r.status,ttfbMs:r.ttfbMs,contentEncoding:r.contentEncoding,headers:r.headers,missingRequiredHeaders:missingHdrs,missingWarnHeaders:[],passed:reasons.length===0,...reasons.length>0?{failureReason:reasons.join("; ")}:{}}}))}function evaluatePrimaryStatusAndCompression(options){let{primary,encodings,httpCfg,pathname,locale,findings}=options,primaryReasons=[];if(primary.status!==200){let msg=rimT(locale,`入口状态码 ${primary.status} (期望 200)`,`Entry HTTP status ${primary.status} (expected 200)`);primaryReasons.push(msg),findings.push({id:"proto:status",probe:"proto",status:"FAIL",title:msg,value:primary.status,threshold:200,route:pathname})}else findings.push({id:"proto:status",probe:"proto",status:"PASS",title:rimT(locale,`HTTP 200 正常响应 (${primary.ttfbMs}ms)`,`HTTP 200 OK (${primary.ttfbMs}ms)`),value:primary.status,route:pathname});if(httpCfg.maxTtfbMs!==void 0&&primary.ttfbMs>httpCfg.maxTtfbMs){let msg=`TTFB ${primary.ttfbMs}ms > ${httpCfg.maxTtfbMs}ms`;primaryReasons.push(msg),findings.push({id:"proto:ttfb",probe:"proto",status:"FAIL",title:msg,value:primary.ttfbMs,threshold:httpCfg.maxTtfbMs,route:pathname})}let effectiveEnc=primary.contentEncoding??encodings.gzip?.contentEncoding??null;if(!checkEncodingMatch(effectiveEnc,httpCfg.requireEncoding)){let msg=rimT(locale,`期望压缩编码 ${httpCfg.requireEncoding}, 实际 ${effectiveEnc??"无"}`,`Expected compression ${httpCfg.requireEncoding}, got ${effectiveEnc??"none"}`);primaryReasons.push(msg),findings.push({id:"proto:encoding-required",probe:"proto",status:"FAIL",title:msg,value:effectiveEnc??"none",threshold:httpCfg.requireEncoding,route:pathname})}else if(primary.contentEncoding==="br")findings.push({id:"proto:compression",probe:"proto",status:"PASS",title:rimT(locale,`压缩协商完整: br ${primary.wireBytes}B / gzip ${encodings.gzip?.wireBytes??"-"}B / raw ${encodings.raw?.wireBytes??"-"}B`,`Compression verified: br ${primary.wireBytes}B / gzip ${encodings.gzip?.wireBytes??"-"}B / raw ${encodings.raw?.wireBytes??"-"}B`),value:primary.wireBytes,route:pathname});else if(encodings.gzip?.contentEncoding==="gzip"&&primary.wireBytes>1024)findings.push({id:"proto:compression-no-br",probe:"proto",status:"WARN",title:rimT(locale,`支持 gzip (${encodings.gzip.wireBytes}B) 但未启用 Brotli (br)`,`gzip supported (${encodings.gzip.wireBytes}B) but Brotli (br) is not enabled`),value:encodings.gzip.wireBytes,route:pathname});else if(primary.wireBytes>1024&&effectiveEnc===null)findings.push({id:"proto:compression-none",probe:"proto",status:"WARN",title:rimT(locale,`响应未压缩 (${primary.wireBytes}B), 建议启用 br / gzip`,`Uncompressed response (${primary.wireBytes}B); enable br / gzip`),value:primary.wireBytes,route:pathname});return{primaryReasons,effectiveEnc}}async function checkCachingAnd304(options){let{primary,locale,findings}=options,h=primary.headers,vary=sanitizeLine(h.vary??""),hasVaryAcceptEncoding=/\baccept-encoding\b/i.test(vary);if(options.effectiveEnc!==null&&!hasVaryAcceptEncoding)findings.push({id:"proto:vary-accept-encoding",probe:"proto",status:"WARN",title:rimT(locale,"压缩响应缺少 Vary: Accept-Encoding 响应头","Compressed response is missing Vary: Accept-Encoding header"),value:vary||"missing"});let etag=h.etag?.trim()??null,lastModified=h["last-modified"]?.trim()??null,revalidation304={tested:!1,status:null,passed:!1};if(options.check304&&etag!==null&&etag!==""){let cond=await safeProtoRequest({url:options.targetUrl,headers:{"Accept-Encoding":primary.contentEncoding??"identity","If-None-Match":etag},allowLoopback:options.allowLoopback,timeoutMs:Math.min(options.timeoutMs,1e4),readBody:!1,locale,signal:options.signal,fetchFn:options.fetchFn});if(cond.ok){let ok304=cond.res.status===304;revalidation304={tested:!0,status:cond.res.status,passed:ok304},findings.push({id:"proto:etag-304",probe:"proto",status:ok304?"PASS":"WARN",title:ok304?rimT(locale,"ETag 条件验证返回 304 Not Modified","ETag revalidation returned 304 Not Modified"):rimT(locale,`带 If-None-Match 返回 HTTP ${cond.res.status} (期望 304)`,`Conditional If-None-Match returned HTTP ${cond.res.status} (expected 304)`),value:cond.res.status,threshold:304})}}else if(etag===null&&lastModified===null)findings.push({id:"proto:validators-missing",probe:"proto",status:"WARN",title:rimT(locale,"响应缺少 ETag 与 Last-Modified 缓存验证器","Response missing ETag and Last-Modified cache validators")});let htmlCacheControl=h["cache-control"]!==void 0?sanitizeLine(h["cache-control"]):null;if(htmlCacheControl!==null&&/\bimmutable\b/i.test(htmlCacheControl))findings.push({id:"proto:html-cache-immutable",probe:"proto",status:"WARN",title:rimT(locale,`HTML 入口不应设置 immutable 强缓存 (${htmlCacheControl})`,`HTML entry should not use immutable caching (${htmlCacheControl})`),value:htmlCacheControl});else if(htmlCacheControl===null)findings.push({id:"proto:html-cache-missing",probe:"proto",status:"WARN",title:rimT(locale,"HTML 入口缺少 Cache-Control 响应头 (推荐 no-cache)","HTML entry is missing Cache-Control header (recommend no-cache)")});return{vary,hasVaryAcceptEncoding,etag,lastModified,htmlCacheControl,revalidation304}}async function runH2H3Stage(options){let{locale,findings}=options,h2h3=await runH2H3MtuProbe({targetUrl:options.targetUrl,chromePath:options.chromePath,timeoutMs:options.timeoutMs,locale,signal:options.signal,launchChromeFn:options.launchChromeFn});if(h2h3.status==="FAIL")findings.push({id:h2h3.mtuBlackholeSuspected===!0?"proto:h3-mtu-blackhole":"proto:h2-h3-failed",probe:"proto",status:"FAIL",title:h2h3.reason??rimT(locale,"检测到 QUIC/H3 路径 MTU 黑洞","QUIC/H3 Path MTU blackhole detected")});else if(h2h3.status==="WARN")findings.push({id:"proto:h3-negotiation",probe:"proto",status:"WARN",title:h2h3.reason??rimT(locale,"HTTP/3 (QUIC) 未协商生效","HTTP/3 (QUIC) not negotiated")});else if(h2h3.status==="PASS")findings.push({id:"proto:h2-h3-mtu",probe:"proto",status:"PASS",title:h2h3.reason??rimT(locale,"H2 与 H3 (QUIC) 加载正常","H2 and H3 (QUIC) verified")});return h2h3}var EDGE_CACHE_HEADERS=["x-edge-cache","x-cache","cf-cache-status","x-vercel-cache","age","via"];function buildUnreachableOutput(input){let{targetUrl,pathname,error,startedAt,waivers,locale,findings}=input;findings.push({id:"proto:unreachable",probe:"proto",status:"FAIL",title:rimT(locale,"目标不可达","Target unreachable"),detail:error,route:pathname});let finalFindings=applyWaiversToFindings(findings,waivers),elapsedMs=Math.max(0,Math.round(performance.now()-startedAt));return{probe:{id:"proto",status:aggregateProbeStatus(finalFindings,"FAIL"),durationMs:elapsedMs,metrics:{status:0},findings:finalFindings,evidence:{targetUrl,error},reason:error},primaryHeaders:{},primaryHtml:"",primaryLinkHeaders:[],routeProbeResults:[{url:targetUrl,path:pathname,method:"GET",status:0,ttfbMs:elapsedMs,contentEncoding:null,headers:{},missingRequiredHeaders:[],missingWarnHeaders:[],passed:!1,failureReason:error}]}}function toEncodingSample(encodingRequested,res){if(!res.ok)return null;return{encodingRequested,contentEncoding:res.res.contentEncoding,status:res.res.status,wireBytes:res.res.wireBytes,ttfbMs:res.res.ttfbMs}}function buildProtoProbeOutput(input){let{targetUrl,primary:{res:primary},primaryHtml,encodings,htmlBrBytes,preloadOut,cacheInfo,altSvc,edgeCache,h2h3,routeProbeResults,findings,waivers,startedAt}=input,finalFindings=applyWaiversToFindings(findings,waivers);return{probe:{id:"proto",status:aggregateProbeStatus(finalFindings,"PASS"),durationMs:Math.max(0,Math.round(performance.now()-startedAt)),metrics:{status:primary.status,ttfbMs:primary.ttfbMs,htmlRawBytes:encodings.raw?.wireBytes??null,htmlGzipBytes:encodings.gzip?.wireBytes??null,htmlBrBytes,totalCriticalBrBytes:preloadOut.totalCriticalBrBytes,totalFirstLoadBrBytes:htmlBrBytes+preloadOut.totalCriticalBrBytes,preloadCount:preloadOut.assets.length,etagPresent:cacheInfo.etag!==null,lastModifiedPresent:cacheInfo.lastModified!==null,varyAcceptEncoding:cacheInfo.hasVaryAcceptEncoding,revalidation304:cacheInfo.revalidation304.tested?cacheInfo.revalidation304.passed:null,altSvcPresent:altSvc!==null,h3Negotiated:h2h3?.h3Negotiated??null,h2DurationMs:h2h3?.h2?.durationMs??null,h3DurationMs:h2h3?.h3?.durationMs??null},findings:finalFindings,evidence:{targetUrl,finalUrl:primary.finalUrl,redirectChain:primary.redirectChain,encodings,vary:cacheInfo.vary||null,etag:cacheInfo.etag,lastModified:cacheInfo.lastModified,cacheControl:cacheInfo.htmlCacheControl,revalidation304:cacheInfo.revalidation304,altSvc,edgeCache,preloads:preloadOut.assets,...h2h3!==void 0?{h2h3}:{}}},primaryHeaders:primary.headers,primaryHtml,primaryLinkHeaders:primary.linkHeaders,routeProbeResults}}async function runProtoProbe(options){let startedAt=performance.now(),{targetUrl,allowLoopback,locale,signal,fetchFn}=options,httpCfg=options.httpConfig??{},protoCfg=options.protoConfig??{},findings=[],parsedTarget=new URL(targetUrl),reqBase={url:targetUrl,allowLoopback,timeoutMs:options.timeoutMs,locale,signal,fetchFn},acceptHtml="text/html,application/xhtml+xml,*/*;q=0.8",[brReq,gzipReq,rawReq]=await Promise.all([safeProtoRequest({...reqBase,headers:{"Accept-Encoding":"br",Accept:"text/html,application/xhtml+xml,*/*;q=0.8"}}),safeProtoRequest({...reqBase,headers:{"Accept-Encoding":"gzip",Accept:"text/html,application/xhtml+xml,*/*;q=0.8"}}),safeProtoRequest({...reqBase,headers:{"Accept-Encoding":"identity",Accept:"text/html,application/xhtml+xml,*/*;q=0.8"}})]);if(!brReq.ok)return buildUnreachableOutput({targetUrl,pathname:parsedTarget.pathname,error:brReq.error,startedAt,waivers:options.waivers,locale,findings});let primary=brReq.res,encodings={br:toEncodingSample("br",brReq),gzip:toEncodingSample("gzip",gzipReq),raw:toEncodingSample("identity",rawReq)},primaryHtml=decompressBodySafe(primary.rawBody,primary.contentEncoding).toString("utf8"),{primaryReasons,effectiveEnc}=evaluatePrimaryStatusAndCompression({primary,encodings,httpCfg,pathname:parsedTarget.pathname,locale,findings}),cacheInfo=await checkCachingAnd304({targetUrl,primary,effectiveEnc,allowLoopback,check304:protoCfg.check304!==!1,timeoutMs:options.timeoutMs,locale,signal,fetchFn,findings}),htmlBrBytes=primary.wireBytes;evaluateFirstPacketBudget({htmlBrBytes,budgets:options.budgets,locale,findings});let preloadOut=protoCfg.checkPreloads!==!1?await measurePreloadedAssets({primaryHtml,finalUrl:primary.finalUrl,targetOrigin:parsedTarget.origin,linkHeaders:primary.linkHeaders,allowLoopback,budgets:options.budgets,timeoutMs:options.timeoutMs,locale,signal,fetchFn,findings}):{assets:[],totalCriticalBrBytes:0},routeProbeResults=[{url:targetUrl,path:parsedTarget.pathname,method:"GET",status:primary.status,ttfbMs:primary.ttfbMs,contentEncoding:primary.contentEncoding,headers:primary.headers,missingRequiredHeaders:[],missingWarnHeaders:[],passed:primaryReasons.length===0,...primaryReasons.length>0?{failureReason:primaryReasons.join("; ")}:{}}];if(httpCfg.routes!==void 0&&httpCfg.routes.length>0){let extra=await probeExtraHttpRoutes({targetUrl,targetOrigin:parsedTarget.origin,routes:httpCfg.routes,allowLoopback,timeoutMs:options.timeoutMs,locale,signal,fetchFn,findings});routeProbeResults.push(...extra)}let altSvc=primary.headers["alt-svc"]??null,edgeCache={};for(let h of EDGE_CACHE_HEADERS)if(primary.headers[h]!==void 0)edgeCache[h]=primary.headers[h];let h2h3;if(protoCfg.checkH2H3!==!1&&(options.runH2H3===!0||protoCfg.checkH2H3===!0))h2h3=await runH2H3Stage({targetUrl,chromePath:options.chromePath??null,timeoutMs:protoCfg.h2h3TimeoutMs??Math.min(options.timeoutMs,15000),locale,signal,launchChromeFn:options.launchChromeFn,findings});return buildProtoProbeOutput({targetUrl,primary:brReq,primaryHtml,encodings,htmlBrBytes,preloadOut,cacheInfo,altSvc,edgeCache,h2h3,routeProbeResults,findings,waivers:options.waivers,startedAt})}async function attachH2H3ToProtoOutput(options){let startedAt=performance.now(),h2h3Findings=[],h2h3=await runH2H3Stage({targetUrl:options.targetUrl,chromePath:options.chromePath,timeoutMs:options.timeoutMs,locale:options.locale,signal:options.signal,launchChromeFn:options.launchChromeFn,findings:h2h3Findings}),waivedH2H3=applyWaiversToFindings(h2h3Findings,options.waivers),mergedFindings=[...options.protoOut.probe.findings,...waivedH2H3],extraMs=Math.max(0,Math.round(performance.now()-startedAt));return{...options.protoOut,probe:{...options.protoOut.probe,status:aggregateProbeStatus(mergedFindings,"PASS"),durationMs:options.protoOut.probe.durationMs+extraMs,metrics:{...options.protoOut.probe.metrics,h3Negotiated:h2h3.h3Negotiated??null,h2DurationMs:h2h3.h2?.durationMs??null,h3DurationMs:h2h3.h3?.durationMs??null},findings:mergedFindings,evidence:{...options.protoOut.probe.evidence,h2h3}}}}import{spawn as spawn5}from"node:child_process";async function runExternalJsonTool(options){let inv=buildSafeSpawnInvocation(options.binPath,options.args,{locale:options.locale});return await new Promise((resolvePromise)=>{let child=spawn5(inv.command,[...inv.args],{env:buildSanitizedChildEnv(),stdio:["ignore","pipe","pipe"],windowsHide:!0,...inv.windowsVerbatimArguments===!0?{windowsVerbatimArguments:!0}:{}}),stdout="",stderr="",exited=!1;child.stdout?.setEncoding("utf8"),child.stderr?.setEncoding("utf8"),child.stdout?.on("data",(c)=>{if(stdout.length<512000)stdout+=c}),child.stderr?.on("data",(c)=>{if(stderr.length<16384)stderr+=c});let exitP=new Promise((res)=>{child.once("close",(code)=>{exited=!0,res(code)}),child.once("error",()=>{exited=!0,res(null)})}),onAbort=()=>{try{child.kill("SIGTERM")}catch{}};options.signal?.addEventListener("abort",onAbort,{once:!0}),waitWithTimeout(exitP,options.timeoutMs).then(async(done)=>{if(options.signal?.removeEventListener("abort",onAbort),!done&&!exited){try{child.kill("SIGKILL")}catch{}resolvePromise({ok:!1,code:null,stdout,stderr:"timed out"});return}let code=await exitP;if(options.signal?.aborted===!0){resolvePromise({ok:!1,code:null,stdout,stderr:"cancelled"});return}resolvePromise({ok:code===0,code,stdout,stderr})})})}async function runExternalAxeCliAdapter(options){let{axeBin,targetUrl,timeoutMs,locale,signal,findings}=options,res=await runExternalJsonTool({binPath:axeBin,args:[targetUrl,"--stdout"],timeoutMs:Math.min(timeoutMs,30000),locale,signal});if(signal?.aborted===!0)throw new RimError("CANCELLED",rimT(locale,"质量探针已取消","Quality probe cancelled"));try{let violations=JSON.parse(res.stdout)?.[0]?.violations??[];if(violations.length===0)findings.push({id:"quality:axe",probe:"quality",status:"PASS",title:rimT(locale,"外部 axe CLI 无障碍审计通过 (0 项违规)","External axe CLI accessibility audit passed (0 violations)"),value:0});let hasSevere=!1;for(let v of violations){let ruleId=String(v.id??"axe-violation"),severe=v.impact==="critical"||v.impact==="serious";if(severe)hasSevere=!0;findings.push({id:ruleId,probe:"quality",status:severe?"FAIL":"WARN",title:`axe [${v.impact??"issue"}] ${ruleId}: ${sanitizeLine(String(v.help??""))}`})}let axeStatus="PASS";if(hasSevere)axeStatus="FAIL";else if(violations.length>0)axeStatus="WARN";return{status:axeStatus,engine:"external-axe",binPath:axeBin,violationCount:violations.length}}catch{return{status:"SKIP",engine:"external-axe",binPath:axeBin,reason:rimT(locale,"axe 输出不可解析已跳过","axe output was not valid JSON; skipped")}}}async function runExternalLycheeAdapter(options){let{lycheeBin,targetUrl,timeoutMs,locale,signal,findings}=options,res=await runExternalJsonTool({binPath:lycheeBin,args:["--format","json","--no-progress",targetUrl],timeoutMs:Math.min(timeoutMs,25000),locale,signal});if(signal?.aborted===!0)throw new RimError("CANCELLED",rimT(locale,"质量探针已取消","Quality probe cancelled"));let failCount;try{let parsed=JSON.parse(res.stdout);if(typeof parsed.errors==="number")failCount=parsed.errors;else if(typeof parsed.fail_count==="number")failCount=parsed.fail_count}catch{}let ok=res.ok&&(failCount===void 0||failCount===0);if(!ok)findings.push({id:"quality:lychee",probe:"quality",status:"WARN",title:rimT(locale,`lychee 外部链接检查检出异常 (${failCount!==void 0?`${failCount} 项失败, `:""}exit=${String(res.code)})`,`lychee link checker reported issues (${failCount!==void 0?`${failCount} failed, `:""}exit=${String(res.code)})`)});return{status:ok?"PASS":"WARN",binPath:lycheeBin,exitCode:res.code,...failCount!==void 0?{failCount}:{}}}async function runOptionalExternalQualityAdapters(options){let{targetUrl,locale,signal,findings}=options,adaptersEvidence={},resolver=options.resolveAdapterBin??((names)=>resolveAbsoluteFromPath(names));if(options.runLychee){let lycheeBin=resolver(["lychee"]);adaptersEvidence.lychee=lycheeBin===null?{status:"SKIP",reason:rimT(locale,"未安装外部 lychee, 已由内置全量链接/外链扫描引擎兜底","External lychee not installed; covered by built-in link scanner")}:await runExternalLycheeAdapter({lycheeBin,targetUrl,timeoutMs:options.timeoutMs,locale,signal,findings})}if(options.runExternalAxeCli){let axeBin=options.resolvedAxeBin!==void 0?options.resolvedAxeBin:resolver(["axe"]);adaptersEvidence.axe=axeBin===null?{status:"SKIP",reason:rimT(locale,"未安装外部 @axe-core/cli (axe), 可启用随包内置 axe-core 引擎","External @axe-core/cli (axe) not installed; bundled axe-core is available")}:await runExternalAxeCliAdapter({axeBin,targetUrl,timeoutMs:options.timeoutMs,locale,signal,findings})}return adaptersEvidence}function hasDomAnchor(domIds,anchor){if(domIds.has(anchor))return!0;try{return domIds.has(decodeURIComponent(anchor))}catch{return!1}}function partitionScannedLinks(options){let{scan,qualityConfig,seenInPageAnchors,brokenAnchors}=options,parsedTarget=new URL(options.targetUrl);parsedTarget.hash="";let{href:targetCleanUrl,origin}=parsedTarget,checkAnchors=qualityConfig.checkAnchors!==!1,maxSameOrigin=Math.min(qualityConfig.maxLinks??40,200),maxExternal=Math.min(qualityConfig.maxExternalLinks??30,100),sameOriginTargets=[],sameOriginMap=new Map,externalTargets=[],seenExternal=new Set;for(let item of scan.links){let cleanUrl=item.resolvedUrl.split("#")[0],parsed;try{parsed=new URL(cleanUrl)}catch{continue}let validHash=checkAnchors&&item.hash!==void 0&&item.hash!==""&&item.hash.toLowerCase()!=="top"?item.hash:null;if(parsed.origin!==origin){if(!seenExternal.has(cleanUrl)&&externalTargets.length<maxExternal)seenExternal.add(cleanUrl),externalTargets.push({url:cleanUrl,kind:item.kind});continue}if(cleanUrl===targetCleanUrl){if(validHash!==null&&!seenInPageAnchors.has(validHash)){if(seenInPageAnchors.add(validHash),!hasDomAnchor(scan.domIds,validHash))brokenAnchors.push(`#${validHash}`)}continue}let existing=sameOriginMap.get(cleanUrl);if(existing!==void 0){if(validHash!==null&&!existing.hashes.includes(validHash))existing.hashes.push(validHash);continue}if(sameOriginTargets.length>=maxSameOrigin)continue;let entry={url:cleanUrl,kind:item.kind,hashes:validHash!==null?[validHash]:[]};sameOriginMap.set(cleanUrl,entry),sameOriginTargets.push(entry)}return{sameOriginTargets,externalTargets}}function appendLinkSummaries(options){let{linkChecks,externalLinkChecks,brokenAnchors,seenInPageAnchorCount,checkedCrossPageAnchorCount=0,locale,findings}=options,totalCheckedAnchors=seenInPageAnchorCount+checkedCrossPageAnchorCount;if(options.checkLinks){let deadLinks=linkChecks.filter((l)=>!l.ok),longRedirects=linkChecks.filter((l)=>l.redirectHops>2);if(deadLinks.length>0)findings.push({id:"quality:dead-links",probe:"quality",status:"FAIL",title:rimT(locale,`检出 ${deadLinks.length} 条死链/不可用同源资源`,`Detected ${deadLinks.length} dead same-origin link(s)/asset(s)`),detail:deadLinks.slice(0,5).map((d)=>`${d.url} (${d.reason??d.status})`).join("; "),value:deadLinks.length});else findings.push({id:"quality:links",probe:"quality",status:"PASS",title:rimT(locale,`同源链接与资源健康 (${linkChecks.length} 项零死链)`,`Same-origin links & assets healthy (${linkChecks.length} checked, 0 dead)`),value:linkChecks.length});if(longRedirects.length>0)findings.push({id:"quality:redirect-chain",probe:"quality",status:"WARN",title:rimT(locale,`发现 ${longRedirects.length} 条过长重定向链 (>2 跳)`,`Detected ${longRedirects.length} long redirect chain(s) (>2 hops)`),value:longRedirects.length})}if(options.checkAnchors){if(brokenAnchors.length>0)findings.push({id:"quality:broken-anchors",probe:"quality",status:"WARN",title:rimT(locale,`发现 ${brokenAnchors.length} 个失效锚点: ${brokenAnchors.slice(0,5).join(", ")}`,`Found ${brokenAnchors.length} broken anchor(s): ${brokenAnchors.slice(0,5).join(", ")}`),value:brokenAnchors.length});else if(totalCheckedAnchors>0)findings.push({id:"quality:anchors",probe:"quality",status:"PASS",title:rimT(locale,`锚点校验通过 (${totalCheckedAnchors} 项)`,`Anchors verified (${totalCheckedAnchors} unique)`),value:totalCheckedAnchors})}if(externalLinkChecks.length>0){let deadExternal=externalLinkChecks.filter((l)=>!l.ok),rateLimitedCount=externalLinkChecks.filter((l)=>l.rateLimited===!0).length;if(deadExternal.length>0)findings.push({id:"quality:external-dead-links",probe:"quality",status:"WARN",title:rimT(locale,`内置外链扫描检出 ${deadExternal.length}/${externalLinkChecks.length} 条异常外链`,`Built-in external link check found ${deadExternal.length}/${externalLinkChecks.length} broken link(s)`),detail:deadExternal.slice(0,5).map((d)=>`${d.url} (${d.reason??d.status})`).join("; "),value:deadExternal.length});else{let rlNote=rateLimitedCount>0?rimT(locale,`, ${rateLimitedCount} 条受反爬/限流保护`,`, ${rateLimitedCount} bot-guarded/rate-limited`):"";findings.push({id:"quality:external-links",probe:"quality",status:"PASS",title:rimT(locale,`内置跨源外链健康 (${externalLinkChecks.length} 项零死链${rlNote})`,`Built-in external links healthy (${externalLinkChecks.length} checked, 0 dead${rlNote})`),value:externalLinkChecks.length})}}}var BOT_GUARD_STATUSES=new Set([403,429,999]);function hostKeyOf(rawUrl){try{return new URL(rawUrl).host.toLowerCase()}catch{return"unknown"}}async function runHostBoundedPool(items,limit,perHostLimit,hostOf,worker){let results=Array.from({length:items.length}),pending=items.map((item,idx)=>({item,idx,host:hostOf(item)})),inFlightByHost=new Map,takeNext=()=>{for(let i=0;i<pending.length;i+=1){let entry=pending[i],active=inFlightByHost.get(entry.host)??0;if(active<perHostLimit)return pending.splice(i,1),inFlightByHost.set(entry.host,active+1),entry}return},waiters=[],notify=()=>{while(waiters.length>0)waiters.shift()?.()},runners=Array.from({length:Math.min(limit,items.length)},async()=>{while(pending.length>0){let next=takeNext();if(next===void 0){await new Promise((res)=>waiters.push(res));continue}try{results[next.idx]=await worker(next.item)}finally{let prev=inFlightByHost.get(next.host)??1;if(prev<=1)inFlightByHost.delete(next.host);else inFlightByHost.set(next.host,prev-1);notify()}}});return await Promise.all(runners),results}function collectMissingCrossPageAnchors(options){let ct=options.contentType.toLowerCase();if(ct!==""&&!ct.includes("html")&&!ct.includes("xml"))return[];let pageHtml=decompressBodySafe(options.rawBody,options.contentEncoding).toString("utf8"),targetScan=scanHtmlResources(pageHtml,options.finalUrl),pathLabel=new URL(options.itemUrl).pathname,missing=[];for(let h of options.hashes)if(!hasDomAnchor(targetScan.domIds,h))missing.push(`${pathLabel}#${h}`);return missing}async function checkSingleUrl(options){let{item,scope,timeoutMs,locale,signal,fetchFn}=options,allowLoopback=scope==="same-origin"?options.allowLoopback:!1,needHtmlForHashes=scope==="same-origin"&&(item.hashes?.length??0)>0,baseHeaders={"Accept-Encoding":"br, gzip","User-Agent":"rim-link-check/0.1"};try{let res=await ssrfHttpRequest({url:item.url,method:needHtmlForHashes?"GET":"HEAD",headers:baseHeaders,allowLoopback,followRedirects:!0,timeoutMs,readBody:needHtmlForHashes,locale,signal,fetchFn});if(!needHtmlForHashes&&(res.status===405||res.status===501||scope==="external"&&res.status===403))res=await ssrfHttpRequest({url:item.url,method:"GET",headers:baseHeaders,allowLoopback,followRedirects:!0,timeoutMs,readBody:!1,locale,signal,fetchFn});let ok=res.status>=200&&res.status<300,rateLimited=scope==="external"&&BOT_GUARD_STATUSES.has(res.status),missingAnchors=ok&&needHtmlForHashes&&item.hashes!==void 0?collectMissingCrossPageAnchors({itemUrl:item.url,finalUrl:res.finalUrl,contentType:res.headers["content-type"]??"",rawBody:res.rawBody,contentEncoding:res.contentEncoding,hashes:item.hashes}):[];return{record:{url:item.url,kind:item.kind,scope,status:res.status,redirectHops:res.redirectChain.length,ok:ok||rateLimited,...rateLimited?{rateLimited:!0,reason:`HTTP ${res.status} (bot-guard/rate-limit)`}:{},...!ok&&!rateLimited?{reason:`HTTP ${res.status}`}:{}},missingAnchors}}catch(error){if(signal?.aborted===!0||isRimError(error)&&error.code==="CANCELLED")throw new RimError("CANCELLED",rimT(locale,"链接扫描已取消","Link scan cancelled"));return{record:{url:item.url,kind:item.kind,scope,status:0,redirectHops:0,ok:!1,reason:sanitizeLine(error instanceof Error?error.message:String(error))},missingAnchors:[]}}}async function scanAndVerifyHtmlLinks(options){let{html,targetUrl,linkHeaders,qualityConfig,locale,findings}=options,linkChecks=[],externalLinkChecks=[],brokenAnchors=[];if(html==="")return{linkChecks,externalLinkChecks,brokenAnchors};let scan=scanHtmlResources(html,targetUrl,linkHeaders),seenInPageAnchors=new Set;if(qualityConfig.checkAnchors!==!1)for(let anchor of scan.hashAnchors){if(seenInPageAnchors.has(anchor))continue;if(seenInPageAnchors.add(anchor),!hasDomAnchor(scan.domIds,anchor))brokenAnchors.push(`#${anchor}`)}let{sameOriginTargets,externalTargets}=partitionScannedLinks({scan,targetUrl,qualityConfig,seenInPageAnchors,brokenAnchors}),checkedCrossPageAnchorCount=0,perReqTimeout=Math.min(options.timeoutMs,8000);if(qualityConfig.checkLinks!==!1){for(let t of sameOriginTargets)checkedCrossPageAnchorCount+=t.hashes.length;let checkedSameOrigin=await runHostBoundedPool(sameOriginTargets,6,6,(item)=>hostKeyOf(item.url),(item)=>checkSingleUrl({item,scope:"same-origin",allowLoopback:options.allowLoopback,timeoutMs:perReqTimeout,locale,signal:options.signal,fetchFn:options.fetchFn}));for(let r of checkedSameOrigin){linkChecks.push(r.record);for(let ma of r.missingAnchors)brokenAnchors.push(ma)}}if(qualityConfig.checkLinks!==!1&&qualityConfig.checkExternalLinks!==!1&&(options.checkExternalLinks===!0||qualityConfig.checkExternalLinks===!0)&&externalTargets.length>0){let checkedExternal=await runHostBoundedPool(externalTargets,6,2,(item)=>hostKeyOf(item.url),(item)=>checkSingleUrl({item,scope:"external",allowLoopback:!1,timeoutMs:perReqTimeout,locale,signal:options.signal,fetchFn:options.fetchFn}));for(let r of checkedExternal)externalLinkChecks.push(r.record)}return appendLinkSummaries({linkChecks,externalLinkChecks,brokenAnchors,seenInPageAnchorCount:seenInPageAnchors.size,checkedCrossPageAnchorCount,checkLinks:qualityConfig.checkLinks!==!1,checkAnchors:qualityConfig.checkAnchors!==!1,locale,findings}),{linkChecks,externalLinkChecks,brokenAnchors}}import{spawn as spawn6}from"node:child_process";function shouldIgnoreRequest(req,targetOrigin,ignorePaths){let parsed;try{parsed=new URL(req.url)}catch{return!1}if(parsed.origin!==targetOrigin)return!0;return ignorePaths.some((p)=>parsed.pathname===p||parsed.pathname.endsWith(p))}async function runSingleSmokeStep(options){let{cdp,step,index,targetOrigin,defaultTimeoutMs,locale,signal}=options;if(signal?.aborted===!0)throw new RimError("CANCELLED",rimT(locale,"冒烟测试已取消","Smoke gate cancelled"));let startedAt=performance.now(),label=step.label??`${step.action} #${index+1}`;try{if(step.action==="viewport")await cdp.send("Emulation.setDeviceMetricsOverride",{width:step.width,height:step.height,deviceScaleFactor:step.deviceScaleFactor??1,mobile:step.mobile===!0});else if(step.action==="navigate"){let resolvedUrl=resolveSameOriginUrl(targetOrigin,step.path,locale,"navigate");await cdp.send("Page.navigate",{url:resolvedUrl})}else if(step.action==="waitUntil")await cdp.waitUntil(step.expr,label,step.timeoutMs??defaultTimeoutMs,signal);else if(step.action==="click"){if(!await cdp.evalValue(`(() => { const el = document.querySelector(${JSON.stringify(step.selector)}); if (!el) return false; el.click(); return true; })()`))throw Error(`Selector not found for click: ${step.selector}`)}else if(step.action==="setValue"){let evt=step.event??"input";if(!await cdp.evalValue(`(() => { const el = document.querySelector(${JSON.stringify(step.selector)}); if (!el) return false; el.value = ${JSON.stringify(step.value)}; el.dispatchEvent(new Event(${JSON.stringify(evt)}, { bubbles: true })); return true; })()`))throw Error(`Selector not found for setValue: ${step.selector}`)}else if(step.action==="assert"){let actual=await cdp.evalValue(step.expr);if(step.expected!==void 0){if(actual!==step.expected)throw Error(`Expected ${JSON.stringify(step.expected)}, got ${JSON.stringify(actual)}`)}else if(step.includes!==void 0){let text=String(actual??"");if(!text.toLowerCase().includes(step.includes.toLowerCase()))throw Error(`Expected "${text}" to include "${step.includes}"`)}else if(!actual)throw Error(`Assertion falsy: ${step.expr}`)}return{index,action:step.action,label,passed:!0,elapsedMs:Math.max(0,Math.round(performance.now()-startedAt))}}catch(error){if(isRimError(error)&&error.code==="CANCELLED")throw error;return{index,action:step.action,label,passed:!1,elapsedMs:Math.max(0,Math.round(performance.now()-startedAt)),error:sanitizeLine(error instanceof Error?error.message:String(error))}}}function killSmokeChild(child,sig){let pid=child.pid;if(process.platform!=="win32"&&typeof pid==="number"&&pid>0)try{process.kill(-pid,sig);return}catch{}try{child.kill(sig)}catch{}}async function runExternalSmokeCommand(options){if(options.signal?.aborted===!0)throw new RimError("CANCELLED",rimT(options.locale,"冒烟测试已取消","Smoke gate cancelled"));let startedAt=performance.now(),rawBin=options.argv[0]??"",binPath=null;if(isPlatformAbsolutePath(rawBin))binPath=isExistingFile(rawBin)?rawBin:null;else binPath=resolveAbsoluteFromPath([rawBin]);if(binPath===null)throw new RimError("SMOKE_FAILED",rimT(options.locale,`无法解析外部冒烟命令可执行文件: ${rawBin}`,`Could not resolve external smoke executable: ${rawBin}`));let invocation=buildSafeSpawnInvocation(binPath,options.argv.slice(1),{locale:options.locale});return await new Promise((resolvePromise,rejectPromise)=>{let child=spawn6(invocation.command,[...invocation.args],{cwd:options.cwd,env:buildSanitizedChildEnv(process.env,{RIM_URL:options.targetUrl}),stdio:["ignore","ignore","pipe"],detached:process.platform!=="win32",windowsHide:!0,...invocation.windowsVerbatimArguments===!0?{windowsVerbatimArguments:!0}:{}}),stderr="",timedOut=!1,settled=!1,killTimer=null;child.stderr?.setEncoding("utf8"),child.stderr?.on("data",(chunk)=>{if(stderr.length<4096)stderr+=chunk});let escalateKill=()=>{if(killSmokeChild(child,"SIGTERM"),killTimer=setTimeout(()=>{killSmokeChild(child,"SIGKILL")},1500),typeof killTimer.unref==="function")killTimer.unref()},cleanupListeners=()=>{if(clearTimeout(timer),killTimer!==null)clearTimeout(killTimer),killTimer=null;options.signal?.removeEventListener("abort",onAbort)},timer=setTimeout(()=>{timedOut=!0,escalateKill()},options.timeoutMs),onAbort=()=>{if(settled)return;settled=!0,escalateKill(),cleanupListeners(),rejectPromise(new RimError("CANCELLED",rimT(options.locale,"冒烟测试已取消","Smoke gate cancelled")))};options.signal?.addEventListener("abort",onAbort,{once:!0}),child.once("error",(err)=>{if(settled)return;settled=!0,cleanupListeners(),rejectPromise(new RimError("SMOKE_FAILED",sanitizeLine(err.message),void 0,err))}),child.once("close",(code)=>{if(settled)return;settled=!0,cleanupListeners();let elapsedMs=Math.max(0,Math.round(performance.now()-startedAt));if(code===0&&!timedOut){resolvePromise({status:"pass",mode:"command",finalUrl:options.targetUrl,pageExceptions:[],consoleErrors:[],failedRequests:[],steps:[],elapsedMs});return}let stderrSuffix=stderr.trim()!==""?`: ${sanitizeLine(stderr).slice(0,240)}`:"",reason=timedOut?rimT(options.locale,`外部冒烟命令超时 (${options.timeoutMs}ms)${stderrSuffix}`,`External smoke command timed out after ${options.timeoutMs}ms${stderrSuffix}`):rimT(options.locale,`外部冒烟命令退出码 ${String(code)}${stderrSuffix}`,`External smoke command exited with code ${String(code)}${stderrSuffix}`);resolvePromise({status:"fail",mode:"command",finalUrl:options.targetUrl,pageExceptions:[],consoleErrors:[],failedRequests:[],steps:[],elapsedMs,reason})})})}async function runSmokeGate(options){let{targetUrl,chromePath,config,timeoutMs,locale,signal}=options;if(config.argv!==void 0&&config.argv.length>0)return await runExternalSmokeCommand({argv:config.argv,targetUrl,cwd:options.cwd??process.cwd(),timeoutMs,locale,signal});let startedAt=performance.now(),viewport=config.viewport??{width:1440,height:900,mobile:!1},targetOrigin=new URL(targetUrl).origin,ignorePaths=config.ignoreRequestPaths??["/favicon.ico"],session=await launchChrome({chromePath,coldGpu:!1,timeoutMs,windowSize:{width:viewport.width,height:viewport.height},locale,signal}),cdp=null,stepResults=[],finalUrl=targetUrl;try{let wsUrl=await waitForCdpPageWsUrl({debugPort:session.port,timeoutMs,locale,signal});cdp=await CdpClient.connect(wsUrl,timeoutMs,signal),await cdp.send("Page.enable"),await cdp.send("Runtime.enable"),await cdp.send("Network.enable"),await cdp.send("Emulation.setDeviceMetricsOverride",{width:viewport.width,height:viewport.height,deviceScaleFactor:1,mobile:viewport.mobile===!0}),await cdp.send("Page.navigate",{url:targetUrl}),await cdp.waitUntil("document.readyState === 'complete'",rimT(locale,"页面加载完成","document.readyState === complete"),config.waitReadyTimeoutMs??Math.min(timeoutMs,15000),signal);let steps=config.steps??[];for(let i=0;i<steps.length;i+=1){let res=await runSingleSmokeStep({cdp,step:steps[i],index:i,targetOrigin,defaultTimeoutMs:Math.min(timeoutMs,15000),locale,signal});if(stepResults.push(res),!res.passed)break}let observedUrl=await cdp.evalValue("window.location.href").catch(()=>targetUrl);if(typeof observedUrl==="string"&&observedUrl!=="")finalUrl=observedUrl;let failedReqs=cdp.failedRequests.filter((req)=>!shouldIgnoreRequest(req,targetOrigin,ignorePaths)),pageExceptions=[...cdp.pageExceptions],consoleErrors=[...cdp.consoleErrors];if(options.afterSmokeHook!==void 0&&signal?.aborted!==!0){if(stepResults.length>0&&finalUrl!==targetUrl)await cdp.send("Page.navigate",{url:targetUrl}),await cdp.waitUntil("document.readyState === 'complete'",rimT(locale,"页面重载完成","document.readyState === complete"),config.waitReadyTimeoutMs??Math.min(timeoutMs,15000),signal);await options.afterSmokeHook(cdp)}let reasons=[],failedStep=stepResults.find((s)=>!s.passed);if(failedStep!==void 0)reasons.push(`${failedStep.label}: ${failedStep.error??"failed"}`);if(config.failOnPageError!==!1&&pageExceptions.length>0)reasons.push(rimT(locale,`未捕获页面异常 (${pageExceptions.length}): ${pageExceptions[0]}`,`uncaught page exceptions (${pageExceptions.length}): ${pageExceptions[0]}`));if(config.failOnConsoleError!==!1&&consoleErrors.length>0)reasons.push(rimT(locale,`控制台错误 (${consoleErrors.length}): ${consoleErrors[0]}`,`console errors (${consoleErrors.length}): ${consoleErrors[0]}`));if(config.failOnRequestError!==!1&&failedReqs.length>0){let first=failedReqs[0];reasons.push(rimT(locale,`同源请求失败 (${failedReqs.length}): ${first.status} ${first.url}`,`failed same-origin requests (${failedReqs.length}): ${first.status} ${first.url}`))}return{status:reasons.length===0?"pass":"fail",mode:"cdp",finalUrl,pageExceptions,consoleErrors,failedRequests:failedReqs,steps:stepResults,elapsedMs:Math.max(0,Math.round(performance.now()-startedAt)),...reasons.length>0?{reason:reasons.join(" | ")}:{}}}finally{cdp?.close(),await session.cleanup()}}async function runSmokeAndBuiltinAxe(options){let{targetUrl,smokeCfg,qCfg,locale,signal,findings}=options,smokeResult={status:"disabled",mode:"disabled",pageExceptions:[],consoleErrors:[],failedRequests:[],steps:[],elapsedMs:0},hasExternalSmokeCmd=(smokeCfg.argv?.length??0)>0,shouldRunSmoke=options.runSmoke!==!1&&smokeCfg.enabled!==!1&&(hasExternalSmokeCmd||options.chromePath!==null&&options.chromePath!==""),reuseSmokeSessionForAxe=shouldRunSmoke&&options.wantBuiltinAxe&&!hasExternalSmokeCmd&&options.runSmokeFn===void 0&&options.axeRunner===void 0&&options.launchChromeFn===void 0,builtinAxeResult;if(shouldRunSmoke){if(options.runSmokeFn!==void 0)smokeResult=await options.runSmokeFn({targetUrl,chromePath:options.chromePath??"",config:smokeCfg,cwd:options.cwd,timeoutMs:options.timeoutMs,locale,signal});else smokeResult=await runSmokeGate({targetUrl,chromePath:options.chromePath??"",config:smokeCfg,cwd:options.cwd,timeoutMs:options.timeoutMs,locale,signal,...reuseSmokeSessionForAxe?{afterSmokeHook:async(cdp)=>{try{builtinAxeResult=await runAxeOnCdpClient({cdp,cwd:options.cwd,axeTags:qCfg.axeTags,timeoutMs:options.timeoutMs,locale,signal})}catch(error){if(isRimError(error)&&error.code==="CANCELLED")throw error;builtinAxeResult={status:"SKIP",engine:"bundled-axe-core",violationCount:0,incompleteCount:0,passCount:0,violations:[],durationMs:0,reason:sanitizeLine(error instanceof Error?error.message:String(error))}}}}:{}});if(smokeResult.status==="fail")findings.push({id:"quality:smoke",probe:"quality",status:"FAIL",title:smokeResult.reason??rimT(locale,"CDP 运行时冒烟未通过","CDP runtime smoke failed")});else if(smokeResult.status==="pass")findings.push({id:"quality:smoke",probe:"quality",status:"PASS",title:rimT(locale,`运行时冒烟通过 (${smokeResult.steps.length} 步, 0 异常, 0 控制台错误)`,`Runtime smoke passed (${smokeResult.steps.length} steps, 0 exceptions, 0 console errors)`)})}else if(options.runSmoke!==!1&&smokeCfg.enabled!==!1&&(options.chromePath===null||options.chromePath==="")){let skipReason=rimT(locale,"未检测到本机 Chrome, 跳过 CDP 运行时冒烟","Chrome not detected; skipping CDP runtime smoke");smokeResult={status:"skip",mode:"cdp",pageExceptions:[],consoleErrors:[],failedRequests:[],steps:[],elapsedMs:0,reason:skipReason},findings.push({id:"quality:smoke",probe:"quality",status:"SKIP",title:skipReason})}if(options.wantBuiltinAxe&&builtinAxeResult===void 0)builtinAxeResult=await runBuiltinAxeAudit({targetUrl,chromePath:options.chromePath,cwd:options.cwd,axeTags:qCfg.axeTags,timeoutMs:options.timeoutMs,locale,signal,launchChromeFn:options.launchChromeFn,axeRunner:options.axeRunner});if(builtinAxeResult!==void 0)appendBuiltinAxeFindings(builtinAxeResult,locale,findings);return{smokeResult,builtinAxeResult}}async function runQualityProbe(options){let startedAt=performance.now(),{targetUrl,allowLoopback,locale,signal,fetchFn}=options,qCfg=options.qualityConfig??{},smokeCfg=qCfg.smoke??options.smokeConfig??{},findings=[],wantExternalAxeCli=qCfg.runAxe===!0||qCfg.checkAxe===!1&&options.runOptionalAdapters===!0,adapterResolver=options.resolveAdapterBin??((names)=>resolveAbsoluteFromPath(names)),resolvedAxeBin=wantExternalAxeCli?adapterResolver(["axe"]):null,wantBuiltinAxe=qCfg.checkAxe!==!1&&(qCfg.checkAxe===!0||resolvedAxeBin===null&&options.checkAxe===!0),{smokeResult,builtinAxeResult}=await runSmokeAndBuiltinAxe({targetUrl,chromePath:options.chromePath,smokeCfg,qCfg,runSmoke:options.runSmoke,wantBuiltinAxe,cwd:options.cwd,timeoutMs:options.timeoutMs,locale,signal,launchChromeFn:options.launchChromeFn,runSmokeFn:options.runSmokeFn,axeRunner:options.axeRunner,findings}),html=options.html??"",linkHeaders=options.linkHeaders??[];if(html===""&&(qCfg.checkLinks!==!1||qCfg.checkAnchors!==!1))try{let resp=await ssrfHttpRequest({url:targetUrl,headers:{"Accept-Encoding":"br, gzip, identity",Accept:"text/html,application/xhtml+xml,*/*;q=0.8"},allowLoopback,timeoutMs:Math.min(options.timeoutMs,1e4),locale,signal,fetchFn});html=decompressBodySafe(resp.rawBody,resp.contentEncoding).toString("utf8"),linkHeaders=resp.linkHeaders}catch(error){if(isRimError(error)&&(error.code==="CANCELLED"||error.code==="SSRF_BLOCKED"))throw error}let{linkChecks,externalLinkChecks,brokenAnchors}=await scanAndVerifyHtmlLinks({html,targetUrl,linkHeaders,allowLoopback,qualityConfig:qCfg,checkExternalLinks:options.checkExternalLinks,timeoutMs:options.timeoutMs,locale,signal,fetchFn,findings}),adaptersEvidence=await runOptionalExternalQualityAdapters({targetUrl,runLychee:qCfg.runLychee===!0||options.runOptionalAdapters===!0,runExternalAxeCli:wantExternalAxeCli,...wantExternalAxeCli?{resolvedAxeBin}:{},timeoutMs:options.timeoutMs,locale,signal,resolveAdapterBin:options.resolveAdapterBin,findings}),finalFindings=applyWaiversToFindings(findings,options.waivers);return{probe:{id:"quality",status:aggregateProbeStatus(finalFindings,"PASS"),durationMs:Math.max(0,Math.round(performance.now()-startedAt)),metrics:{smokeStatus:smokeResult.status,smokeSteps:smokeResult.steps.length,checkedLinks:linkChecks.length,deadLinks:linkChecks.filter((l)=>!l.ok).length,checkedExternalLinks:externalLinkChecks.length,deadExternalLinks:externalLinkChecks.filter((l)=>!l.ok).length,brokenAnchors:brokenAnchors.length,...builtinAxeResult!==void 0&&builtinAxeResult.status!=="SKIP"?{axeViolations:builtinAxeResult.violationCount,axeIncomplete:builtinAxeResult.incompleteCount,axePasses:builtinAxeResult.passCount,axeVersion:builtinAxeResult.axeVersion??null}:{}},findings:finalFindings,evidence:{smokeMode:smokeResult.mode,linkChecks,...externalLinkChecks.length>0?{externalLinkChecks}:{},brokenAnchors,...builtinAxeResult!==void 0?{axe:builtinAxeResult}:{},adapters:adaptersEvidence}},smoke:smokeResult}}var NONCE_OR_HASH_RE=/^'(?:nonce-[A-Za-z0-9+/=_-]+|sha(?:256|384|512)-[A-Za-z0-9+/=_-]+)'$/i;function splitDirectiveValues(rawHeader,start,end){let vals=[],p=start;while(p<end){while(p<end&&rawHeader.charCodeAt(p)<=32)p+=1;if(p>=end)break;let tokEnd=p;while(tokEnd<end&&rawHeader.charCodeAt(tokEnd)>32)tokEnd+=1;vals.push(rawHeader.slice(p,tokEnd)),p=tokEnd}return vals}function parseSinglePolicySlice(rawHeader,sliceStart,sliceEnd){let directives={},i=sliceStart;while(i<sliceEnd){let end=rawHeader.indexOf(";",i);if(end===-1||end>sliceEnd)end=sliceEnd;while(i<end&&rawHeader.charCodeAt(i)<=32)i+=1;if(i<end){let nameEnd=i;while(nameEnd<end&&rawHeader.charCodeAt(nameEnd)>32)nameEnd+=1;let name=rawHeader.slice(i,nameEnd).toLowerCase();if(!Object.hasOwn(directives,name))directives[name]=splitDirectiveValues(rawHeader,nameEnd,end)}i=end+1}return{raw:rawHeader.slice(sliceStart,sliceEnd).trim(),directives}}function parseCspList(rawHeader){let len=rawHeader.length;if(rawHeader.indexOf(",")===-1)return[parseSinglePolicySlice(rawHeader,0,len)];let policies=[],start=0;while(start<len){let comma=rawHeader.indexOf(",",start);if(comma===-1)comma=len;let pol=parseSinglePolicySlice(rawHeader,start,comma);if(Object.keys(pol.directives).length>0)policies.push(pol);start=comma+1}return policies.length>0?policies:[parseSinglePolicySlice(rawHeader,0,len)]}function parseCsp(rawHeader){if(rawHeader.indexOf(",")===-1)return parseSinglePolicySlice(rawHeader,0,rawHeader.length);let list=parseCspList(rawHeader),merged={};for(let pol of list)for(let[k,v]of Object.entries(pol.directives))if(!Object.hasOwn(merged,k))merged[k]=v;return{raw:rawHeader,directives:merged}}function effectiveDirective(csp,name,fallbackToDefault=!0){if(Object.hasOwn(csp.directives,name))return csp.directives[name];if(fallbackToDefault&&Object.hasOwn(csp.directives,"default-src"))return csp.directives["default-src"];return}function inspectScriptTokens(tokens){let hasUnsafeInline=!1,hasUnsafeEval=!1,hasHashOrNonce=!1;for(let i=0;i<tokens.length;i+=1){let tok=tokens[i],lower=tok.toLowerCase();if(lower==="'unsafe-inline'")hasUnsafeInline=!0;else if(lower==="'unsafe-eval'")hasUnsafeEval=!0;else if(NONCE_OR_HASH_RE.test(tok))hasHashOrNonce=!0}return{bareUnsafeInline:hasUnsafeInline&&!hasHashOrNonce,unsafeEval:hasUnsafeEval}}function hasStyleUnsafeInline(tokens){for(let i=0;i<tokens.length;i+=1)if(tokens[i].toLowerCase()==="'unsafe-inline'")return!0;return!1}function auditCspHeader(rawCsp,locale,required){let findings=[];if(rawCsp===void 0||rawCsp.trim()==="")return findings.push({id:"sec:csp-missing",probe:"sec",status:required?"FAIL":"WARN",title:rimT(locale,"缺少 Content-Security-Policy (CSP) 响应头","Missing Content-Security-Policy (CSP) header")}),{parsed:null,findings};let policies=parseCspList(rawCsp),parsed=policies.length===1?policies[0]:parseCsp(rawCsp),anyPolicyConstrainsScript=!1,anyPolicyBlocksBareInline=!1,anyPolicyBlocksEval=!1,anyPolicyAllowsEval=!1,unsafeInlineSample="",unsafeEvalSample="",anyPolicyConstrainsStyle=!1,anyPolicyBlocksStyleInline=!1,styleInlineSample="",hasFrameAncestors=!1,hasBaseUri=!1,hasObjectSrcNone=!1,objectSrcSample="";for(let i=0;i<policies.length;i+=1){let pol=policies[i],scriptSrc=effectiveDirective(pol,"script-src",!0),scriptSrcElem=effectiveDirective(pol,"script-src-elem",!1);if(scriptSrc!==void 0||scriptSrcElem!==void 0){anyPolicyConstrainsScript=!0;let srcCheck=scriptSrc!==void 0?inspectScriptTokens(scriptSrc):{bareUnsafeInline:!1,unsafeEval:!1},elemCheck=scriptSrcElem!==void 0?inspectScriptTokens(scriptSrcElem):{bareUnsafeInline:!1,unsafeEval:!1},policyInlineUnsafe=srcCheck.bareUnsafeInline||elemCheck.bareUnsafeInline,policyEvalUnsafe=srcCheck.unsafeEval||elemCheck.unsafeEval;if(!policyInlineUnsafe&&scriptSrc!==void 0)anyPolicyBlocksBareInline=!0;else if(policyInlineUnsafe&&unsafeInlineSample==="")unsafeInlineSample=sanitizeLine([...scriptSrc??[],...scriptSrcElem??[]].join(" "));if(!policyEvalUnsafe&&scriptSrc!==void 0)anyPolicyBlocksEval=!0;else if(policyEvalUnsafe){if(anyPolicyAllowsEval=!0,unsafeEvalSample==="")unsafeEvalSample=sanitizeLine([...scriptSrc??[],...scriptSrcElem??[]].join(" "))}}let styleSrc=effectiveDirective(pol,"style-src",!0);if(styleSrc!==void 0){if(anyPolicyConstrainsStyle=!0,!hasStyleUnsafeInline(styleSrc))anyPolicyBlocksStyleInline=!0;else if(styleInlineSample==="")styleInlineSample=sanitizeLine(styleSrc.join(" "))}if(effectiveDirective(pol,"frame-ancestors",!1)!==void 0)hasFrameAncestors=!0;if(effectiveDirective(pol,"base-uri",!1)!==void 0)hasBaseUri=!0;let objSrc=effectiveDirective(pol,"object-src",!0);if(objSrc!==void 0){if(objSrc.some((tok)=>tok.toLowerCase()==="'none'"))hasObjectSrcNone=!0;else if(objectSrcSample==="")objectSrcSample=sanitizeLine(objSrc.join(" "))}}if(!anyPolicyConstrainsScript)findings.push({id:"sec:csp-script-src-missing",probe:"sec",status:"WARN",title:rimT(locale,"CSP 缺少 script-src 与 default-src 指令, 无法约束内联脚本与 eval","CSP is missing both script-src and default-src; inline scripts and eval are unrestricted")});else if(!anyPolicyBlocksBareInline)findings.push({id:"sec:csp-script-unsafe-inline",probe:"sec",status:"FAIL",title:rimT(locale,"CSP script-src 包含危险的 'unsafe-inline' 且无 hash/nonce 约束","CSP script-src allows 'unsafe-inline' without hash/nonce"),value:unsafeInlineSample||"unrestricted"});else findings.push({id:"sec:csp-script-inline-safe",probe:"sec",status:"PASS",title:rimT(locale,"CSP script-src 未开放裸 'unsafe-inline'","CSP script-src blocks bare 'unsafe-inline'")});if(anyPolicyAllowsEval&&!anyPolicyBlocksEval)findings.push({id:"sec:csp-script-unsafe-eval",probe:"sec",status:"FAIL",title:rimT(locale,"CSP script-src 包含危险的 JS 'unsafe-eval'","CSP script-src allows dangerous JS 'unsafe-eval'"),value:unsafeEvalSample});if(anyPolicyConstrainsStyle&&!anyPolicyBlocksStyleInline)findings.push({id:"sec:csp-style-unsafe-inline",probe:"sec",status:"WARN",title:rimT(locale,"CSP style-src 使用了 'unsafe-inline' (建议按需收紧为 hash)","CSP style-src uses 'unsafe-inline' (consider tightening to hashes)"),value:styleInlineSample});if(!hasFrameAncestors)findings.push({id:"sec:csp-frame-ancestors",probe:"sec",status:"WARN",title:rimT(locale,"CSP 缺少 frame-ancestors 点击劫持防护指令","CSP is missing frame-ancestors clickjacking directive")});if(!hasBaseUri)findings.push({id:"sec:csp-base-uri",probe:"sec",status:"WARN",title:rimT(locale,"CSP 缺少 base-uri 指令 (推荐 base-uri 'none' 或 'self')","CSP is missing base-uri directive (recommend base-uri 'none' or 'self')")});if(!hasObjectSrcNone)findings.push({id:"sec:csp-object-src",probe:"sec",status:"WARN",title:rimT(locale,"CSP object-src 未锁定为 'none'","CSP object-src is not locked to 'none'"),value:objectSrcSample||"missing"});return{parsed,findings}}import{spawn as spawn7}from"node:child_process";import{existsSync as existsSync21,readFileSync as readFileSync15}from"node:fs";import{mkdtemp as mkdtemp2,rm as rm2}from"node:fs/promises";import{tmpdir as tmpdir6}from"node:os";import{join as join16}from"node:path";function appendTestsslFindings(testssl,locale,findings){if(testssl.status==="FAIL")findings.push({id:"sec:testssl",probe:"sec",status:"FAIL",title:rimT(locale,`testssl.sh 检出高危 TLS 问题 (${testssl.vulnerableItems?.length??0} 项, 证书剩余 ${String(testssl.certDaysRemaining??"?")} 天)`,`testssl.sh detected high-severity TLS issues (${testssl.vulnerableItems?.length??0} items, cert days=${String(testssl.certDaysRemaining??"?")})`),detail:testssl.vulnerableItems?.slice(0,5).join("; ")});else if(testssl.status==="WARN")findings.push({id:"sec:testssl-cert-expiry",probe:"sec",status:"WARN",title:rimT(locale,`TLS 证书即将过期 (剩余 ${String(testssl.certDaysRemaining)} 天)`,`TLS certificate expiring soon (${String(testssl.certDaysRemaining)} days remaining)`),value:testssl.certDaysRemaining});else if(testssl.status==="PASS")findings.push({id:"sec:testssl",probe:"sec",status:"PASS",title:rimT(locale,`testssl.sh TLS 体检通过 (TLS1.2=${String(testssl.tls12)}, TLS1.3=${String(testssl.tls13)}, 证书剩余 ${String(testssl.certDaysRemaining??"?")} 天)`,`testssl.sh TLS audit passed (TLS1.2=${String(testssl.tls12)}, TLS1.3=${String(testssl.tls13)}, cert days=${String(testssl.certDaysRemaining??"?")})`)})}function classifyTestsslStatus(vulnerableCount,certDays){if(vulnerableCount>0||certDays!==null&&certDays<7)return"FAIL";if(certDays!==null&&certDays<30)return"WARN";return"PASS"}async function runOptionalTestssl(options){if(new URL(options.targetUrl).protocol!=="https:")return{status:"SKIP",reason:rimT(options.locale,"非 HTTPS 目标, 跳过 testssl.sh TLS 体检","Non-HTTPS target; skipping testssl.sh TLS check")};let binPath=(options.resolveAdapterBin??((names)=>resolveAbsoluteFromPath(names)))(["testssl.sh","testssl"]);if(binPath===null)return{status:"SKIP",reason:rimT(options.locale,"未安装 testssl.sh, 跳过深度 TLS 体检 (可经 brew install testssl 安装)","testssl.sh not installed; skipping deep TLS audit (install via brew install testssl)")};let tmpDir=await mkdtemp2(join16(tmpdir6(),"rim-testssl-")),jsonOut=join16(tmpDir,"result.json");try{let inv=buildSafeSpawnInvocation(binPath,["--jsonfile",jsonOut,"--quiet","--fast",options.targetUrl],{locale:options.locale}),child=spawn7(inv.command,[...inv.args],{env:buildSanitizedChildEnv(),stdio:["ignore","ignore","pipe"],windowsHide:!0,...inv.windowsVerbatimArguments===!0?{windowsVerbatimArguments:!0}:{}}),stderrBuf="";child.stderr?.setEncoding("utf8"),child.stderr?.on("data",(chunk)=>{if(stderrBuf.length<4096)stderrBuf+=chunk});let exited=!1,exitPromise=new Promise((res)=>{child.once("close",()=>{exited=!0,res()}),child.once("error",()=>{exited=!0,res()})}),onAbort=()=>{try{child.kill("SIGTERM")}catch{}};options.signal?.addEventListener("abort",onAbort,{once:!0});try{if(!await waitWithTimeout(exitPromise,Math.min(options.timeoutMs,45000))&&!exited){try{child.kill("SIGKILL")}catch{}return{status:"SKIP",binPath,reason:rimT(options.locale,"testssl.sh 执行超时已跳过","testssl.sh timed out; skipped")}}}finally{options.signal?.removeEventListener("abort",onAbort)}if(!existsSync21(jsonOut)){let errDetail=sanitizeLine(stderrBuf).slice(0,160);return{status:"SKIP",binPath,reason:rimT(options.locale,`testssl.sh 未生成 JSON 报告${errDetail!==""?`: ${errDetail}`:""}`,`testssl.sh produced no JSON output${errDetail!==""?`: ${errDetail}`:""}`)}}let rawParsed=JSON.parse(readFileSync15(jsonOut,"utf8")),rawItems=[];if(Array.isArray(rawParsed))rawItems=rawParsed;else if(Array.isArray(rawParsed?.scanResult))rawItems=rawParsed.scanResult;let tls12,tls13,earlyData,certDaysRemaining=null,vulnerableItems=[];for(let item of Array.isArray(rawItems)?rawItems:[]){let id=String(item.id??""),sev=String(item.severity??"").toUpperCase(),finding=sanitizeLine(String(item.finding??""));if(id==="TLS1_2")tls12=/offered/i.test(finding)&&!/not offered/i.test(finding);else if(id==="TLS1_3")tls13=/offered/i.test(finding)&&!/not offered/i.test(finding);else if(/early_data|0-rtt/i.test(id))earlyData=finding;else if(id==="cert_notAfter"||id==="cert_expirationStatus"){let daysMatch=/(\d+)\s*days/i.exec(finding);if(daysMatch!==null)certDaysRemaining=Number(daysMatch[1])}if(sev==="CRITICAL"||sev==="HIGH")vulnerableItems.push(`${id}: ${finding}`)}return{status:classifyTestsslStatus(vulnerableItems.length,certDaysRemaining),binPath,tls12,tls13,earlyData,certDaysRemaining,vulnerableItems}}catch(error){return{status:"SKIP",binPath,reason:sanitizeLine(error instanceof Error?error.message:String(error))}}finally{await rm2(tmpDir,{recursive:!0,force:!0}).catch(()=>{})}}import{isIP as isIP5}from"node:net";import{connect as tlsConnect2}from"node:tls";var WEAK_CIPHER_RE=/(?:^|[-_])(?:NULL|EXPORT|EXP|RC4|RC2|DES|3DES|DES-CBC3|MD5|ANON|ADH|AECDH|IDEA|SEED)(?:$|[-_])/i,CLIENT_UNSUPPORTED_RE=/ERR_SSL_NO_PROTOCOLS_AVAILABLE|ERR_TLS_INVALID_PROTOCOL_VERSION|no protocols available/i,SERVER_REJECTED_RE=/TLSV1_ALERT_PROTOCOL_VERSION|UNSUPPORTED_PROTOCOL|unsupported protocol|HANDSHAKE_FAILURE|NO_CIPHERS_AVAILABLE|WRONG_VERSION_NUMBER|ECONNRESET|alert protocol version|handshake failure|socket hang up/i;function isWeakTlsCipher(cipherName){if(cipherName===null||cipherName===void 0)return!1;let trimmed=cipherName.trim();if(trimmed==="")return!1;return WEAK_CIPHER_RE.test(trimmed)}function isWeakTlsKey(keyType,keyBits){if(keyBits===null||!Number.isFinite(keyBits)||keyBits<=0)return!1;if(keyType==="RSA")return keyBits<2048;if(keyType==="EC")return keyBits<224;return!1}function classifyTlsProbeError(err){let rec=err,combined=`${String(rec?.code??"")} ${String(rec?.message??err??"")}`;if(CLIENT_UNSUPPORTED_RE.test(combined))return"client-unsupported";if(SERVER_REJECTED_RE.test(combined))return"rejected";return"error"}function summarizePeerCert(rawCert,authorized,authorizationError,nowMs){if(!rawCert||Object.keys(rawCert).length===0)return;let cert=rawCert,validFrom=typeof cert.valid_from==="string"?cert.valid_from:"",validTo=typeof cert.valid_to==="string"?cert.valid_to:"",fromMs=validFrom!==""?Date.parse(validFrom):Number.NaN,toMs=validTo!==""?Date.parse(validTo):Number.NaN,daysRemaining=Number.isFinite(toMs)?Math.floor((toMs-nowMs)/86400000):null,notYetValid=Number.isFinite(fromMs)&&fromMs>nowMs,curve=null;if(typeof cert.asn1Curve==="string"&&cert.asn1Curve!=="")curve=cert.asn1Curve;else if(typeof cert.nistCurve==="string"&&cert.nistCurve!=="")curve=cert.nistCurve;let keyType=null;if(curve!==null)keyType="EC";else if(typeof cert.modulus==="string"&&cert.modulus!=="")keyType="RSA";let keyBits=typeof cert.bits==="number"&&Number.isFinite(cert.bits)?cert.bits:null,subjectCn=cert.subject?.CN,rawIssuer=cert.issuer?.O??cert.issuer?.CN??"",subject=sanitizeLine(Array.isArray(subjectCn)?subjectCn[0]??"":subjectCn??""),issuer=sanitizeLine(Array.isArray(rawIssuer)?rawIssuer[0]??"":rawIssuer),sanCount=typeof cert.subjectaltname==="string"&&cert.subjectaltname.trim()!==""?cert.subjectaltname.split(",").map((s)=>s.trim()).filter((s)=>s!=="").length:0,chainLength=0,visited=new Set,cursor=cert;while(cursor!==void 0&&Object.keys(cursor).length>0){let fp=cursor.fingerprint256??cursor.fingerprint??`idx-${chainLength}`;if(visited.has(fp))break;if(visited.add(fp),chainLength+=1,chainLength>=12)break;cursor=cursor.issuerCertificate}return{subject,issuer,validFrom:sanitizeLine(validFrom),validTo:sanitizeLine(validTo),daysRemaining,notYetValid,authorized,authorizationError:authorizationError!==null?sanitizeLine(authorizationError):null,keyType,keyBits,curve:curve!==null?sanitizeLine(curve):null,sanCount,fingerprint256:typeof cert.fingerprint256==="string"?sanitizeLine(cert.fingerprint256):null,chainLength}}function evaluateTlsAuditResult(input){let locale=input.locale??"en",warnDays=Math.max(7,input.minCertDays??30),vulnerableItems=[],warnings=[];if(input.tls10==="offered")vulnerableItems.push(rimT(locale,"TLS 1.0 已弃用协议仍在对外提供服务","Deprecated TLS 1.0 protocol is still offered"));if(input.tls11==="offered")vulnerableItems.push(rimT(locale,"TLS 1.1 已弃用协议仍在对外提供服务","Deprecated TLS 1.1 protocol is still offered"));if(input.tls12!=="offered"&&input.tls13!=="offered")vulnerableItems.push(rimT(locale,"未检测到 TLS 1.2 或 TLS 1.3 支持","Neither TLS 1.2 nor TLS 1.3 is offered"));else if(input.tls13!=="offered")warnings.push(rimT(locale,"未启用 TLS 1.3 (仅支持 TLS 1.2)","TLS 1.3 not offered (TLS 1.2 only)"));let weakCipher=isWeakTlsCipher(input.negotiatedCipher);if(weakCipher)vulnerableItems.push(rimT(locale,`协商到弱加密套件: ${sanitizeLine(input.negotiatedCipher??"")}`,`Weak negotiated cipher suite: ${sanitizeLine(input.negotiatedCipher??"")}`));let cert=input.cert,weakKey=cert!==void 0&&isWeakTlsKey(cert.keyType,cert.keyBits);if(weakKey&&cert!==void 0)vulnerableItems.push(rimT(locale,`证书公钥强度不足 (${cert.keyType??"unknown"} ${String(cert.keyBits)} bits)`,`Weak certificate public key (${cert.keyType??"unknown"} ${String(cert.keyBits)} bits)`));if(cert!==void 0){if(!cert.authorized)vulnerableItems.push(rimT(locale,`TLS 证书链或域名校验未通过 (${cert.authorizationError??"unauthorized"})`,`TLS certificate verification failed (${cert.authorizationError??"unauthorized"})`));if(cert.notYetValid)vulnerableItems.push(rimT(locale,`TLS 证书尚未生效 (validFrom=${cert.validFrom})`,`TLS certificate is not yet valid (validFrom=${cert.validFrom})`));if(cert.daysRemaining!==null){if(cert.daysRemaining<0)vulnerableItems.push(rimT(locale,`TLS 证书已过期 (${Math.abs(cert.daysRemaining)} 天前)`,`TLS certificate expired (${Math.abs(cert.daysRemaining)} days ago)`));else if(cert.daysRemaining<7)vulnerableItems.push(rimT(locale,`TLS 证书将在 ${cert.daysRemaining} 天内过期 (< 7 天高危线)`,`TLS certificate expires in ${cert.daysRemaining} day(s) (< 7 day critical threshold)`));else if(cert.daysRemaining<warnDays)warnings.push(rimT(locale,`TLS 证书即将过期 (剩余 ${cert.daysRemaining} 天 < ${warnDays} 天)`,`TLS certificate expiring soon (${cert.daysRemaining} days remaining < ${warnDays} days)`))}}let status="PASS";if(vulnerableItems.length>0)status="FAIL";else if(warnings.length>0)status="WARN";return{status,weakCipher,weakKey,vulnerableItems,warnings}}function appendBuiltinTlsFindings(tls,locale,findings){if(tls.status==="SKIP")return;if(tls.tls10==="offered"||tls.tls11==="offered"){let legacy=[];if(tls.tls10==="offered")legacy.push("TLS 1.0");if(tls.tls11==="offered")legacy.push("TLS 1.1");findings.push({id:"sec:tls-legacy-protocol",probe:"sec",status:"FAIL",title:rimT(locale,`服务端仍提供已弃用协议: ${legacy.join(", ")}`,`Server still offers deprecated protocol(s): ${legacy.join(", ")}`)})}if(tls.weakCipher===!0)findings.push({id:"sec:tls-weak-cipher",probe:"sec",status:"FAIL",title:rimT(locale,`协商到弱 TLS 加密套件: ${tls.negotiatedCipher??"unknown"}`,`Weak TLS cipher suite negotiated: ${tls.negotiatedCipher??"unknown"}`)});if(tls.weakKey===!0)findings.push({id:"sec:tls-weak-key",probe:"sec",status:"FAIL",title:rimT(locale,`TLS 证书公钥强度不足 (${tls.cert?.keyType??"unknown"} ${String(tls.cert?.keyBits??"?")} bits)`,`Weak TLS certificate key (${tls.cert?.keyType??"unknown"} ${String(tls.cert?.keyBits??"?")} bits)`)});if(tls.cert!==void 0&&(!tls.cert.authorized||tls.cert.notYetValid))findings.push({id:"sec:tls-cert-invalid",probe:"sec",status:"FAIL",title:rimT(locale,`TLS 证书校验未通过 (${tls.cert.authorizationError??"invalid"})`,`TLS certificate validation failed (${tls.cert.authorizationError??"invalid"})`)});let days=tls.cert?.daysRemaining??null;if(days!==null&&days<7)findings.push({id:"sec:tls-cert-expiry",probe:"sec",status:"FAIL",title:rimT(locale,days<0?`TLS 证书已过期 (${Math.abs(days)} 天前)`:`TLS 证书即将在 ${days} 天内过期`,days<0?`TLS certificate expired (${Math.abs(days)} days ago)`:`TLS certificate expires in ${days} day(s)`),value:days,threshold:7});else if(days!==null){let expiryWarn=tls.warnings.find((w)=>/expir|过期/i.test(w));if(expiryWarn!==void 0)findings.push({id:"sec:tls-cert-expiry",probe:"sec",status:"WARN",title:expiryWarn,value:days})}if(tls.tls13!=="offered"&&tls.tls12==="offered")findings.push({id:"sec:tls-no-tls13",probe:"sec",status:"WARN",title:rimT(locale,"TLS 1.3 未启用 (仅支持 TLS 1.2)","TLS 1.3 not offered (TLS 1.2 only)")});let addedSpecificFail=findings.some((f)=>f.id.startsWith("sec:tls-")&&f.status==="FAIL");if(tls.status==="FAIL"&&!addedSpecificFail)findings.push({id:"sec:tls",probe:"sec",status:"FAIL",title:rimT(locale,`内置 TLS 体检失败: ${tls.vulnerableItems[0]??tls.reason??"TLS error"}`,`Built-in TLS audit failed: ${tls.vulnerableItems[0]??tls.reason??"TLS error"}`),detail:tls.vulnerableItems.slice(0,4).join("; ")});else if(tls.status==="PASS"){let alpn=tls.alpnProtocol!==null&&tls.alpnProtocol!==void 0?`, ALPN=${tls.alpnProtocol}`:"",daysText=days!==null?`${days}d`:"?";findings.push({id:"sec:tls",probe:"sec",status:"PASS",title:rimT(locale,`内置 TLS 体检通过 (${tls.negotiatedProtocol??"TLS"}, ${tls.negotiatedCipher??"-"}${alpn}, TLS1.3=${tls.tls13}, TLS1.2=${tls.tls12}, 证书剩余 ${daysText})`,`Built-in TLS audit passed (${tls.negotiatedProtocol??"TLS"}, ${tls.negotiatedCipher??"-"}${alpn}, TLS1.3=${tls.tls13}, TLS1.2=${tls.tls12}, cert=${daysText})`),...days!==null?{value:days}:{}})}}async function runSingleTlsHandshake(options){if(options.signal?.aborted===!0)throw new RimError("CANCELLED",rimT(options.locale,"TLS 体检已取消","TLS audit cancelled"));return await new Promise((resolvePromise,reject)=>{let settled=!1,socket=null,finish=(fn)=>{if(settled)return;settled=!0,clearTimeout(timer),options.signal?.removeEventListener("abort",onAbort);try{socket?.destroy()}catch{}fn()},onAbort=()=>{finish(()=>reject(new RimError("CANCELLED",rimT(options.locale,"TLS 体检已取消","TLS audit cancelled"))))};options.signal?.addEventListener("abort",onAbort,{once:!0});let timer=setTimeout(()=>{finish(()=>resolvePromise({ok:!1,errorKind:"error",errorMessage:`TLS handshake timed out after ${options.timeoutMs}ms`}))},options.timeoutMs);try{socket=tlsConnect2({host:options.pin.address,port:options.port,...options.servername!==void 0?{servername:options.servername}:{},...options.version!==void 0?{minVersion:options.version,maxVersion:options.version}:{},...options.ciphers!==void 0?{ciphers:options.ciphers}:{},...options.ca!==void 0?{ca:options.ca}:{},rejectUnauthorized:!1,...options.collectCert?{ALPNProtocols:["h2","http/1.1"]}:{}},()=>{let sock=socket,protocol=sock.getProtocol()??null,cipherInfo=sock.getCipher(),cipher=cipherInfo?.standardName??cipherInfo?.name??null,alpn=typeof sock.alpnProtocol==="string"&&sock.alpnProtocol!==""?sock.alpnProtocol:null,authErr=sock.authorizationError!==null&&sock.authorizationError!==void 0?String(sock.authorizationError):null,cert=options.collectCert?summarizePeerCert(sock.getPeerCertificate(!0),sock.authorized,authErr,Date.now()):void 0;finish(()=>resolvePromise({ok:!0,protocol,cipher,alpn,cert}))}),socket.once("error",(err)=>{let msg=err instanceof Error?err.message:String(err);finish(()=>resolvePromise({ok:!1,errorKind:classifyTlsProbeError(err),errorMessage:sanitizeLine(msg)}))})}catch(err){let msg=err instanceof Error?err.message:String(err);finish(()=>resolvePromise({ok:!1,errorKind:classifyTlsProbeError(err),errorMessage:sanitizeLine(msg)}))}})}async function probeSpecificTlsVersion(options){let first=await runSingleTlsHandshake({...options,collectCert:!1});if(first.ok)return"offered";if(first.errorKind==="client-unsupported"&&(options.version==="TLSv1.1"||options.version==="TLSv1")){let retry=await runSingleTlsHandshake({...options,ciphers:"DEFAULT@SECLEVEL=0",collectCert:!1});if(retry.ok)return"offered";if(retry.errorMessage?.includes("INVALID_COMMAND")===!0)return"client-unsupported";return retry.errorKind??"error"}return first.errorKind??"error"}async function runBuiltinTlsAudit(options){let startedAt=performance.now(),parsed=new URL(options.targetUrl),cleanHost=parsed.hostname.replace(/^\[|\]$/g,""),port=parsed.port!==""?Number(parsed.port):443;if(parsed.protocol!=="https:")return{status:"SKIP",engine:"node:tls",host:cleanHost,port:parsed.port!==""?Number(parsed.port):80,tls13:"error",tls12:"error",tls11:"error",tls10:"error",vulnerableItems:[],warnings:[],durationMs:Math.max(0,Math.round(performance.now()-startedAt)),reason:rimT(options.locale,"非 HTTPS 目标, 跳过内置 TLS 体检","Non-HTTPS target; skipping built-in TLS audit")};let pin=await resolveAndPinHost({hostname:parsed.hostname,allowLoopback:options.allowLoopback,locale:options.locale,lookupFn:options.lookupFn}),servername=isIP5(cleanHost)===0?cleanHost:void 0,handshakeTimeout=Math.max(1000,Math.min(options.timeoutMs,5000));try{let primary=await runSingleTlsHandshake({pin,port,servername,ca:options.ca,collectCert:!0,timeoutMs:handshakeTimeout,locale:options.locale,signal:options.signal});if(!primary.ok){let msg=primary.errorMessage??rimT(options.locale,"TLS 握手失败","TLS handshake failed");return{status:"FAIL",engine:"node:tls",host:cleanHost,port,pinnedIp:pin.address,tls13:"error",tls12:"error",tls11:"error",tls10:"error",vulnerableItems:[msg],warnings:[],durationMs:Math.max(0,Math.round(performance.now()-startedAt)),reason:msg}}let baseProbe={pin,port,servername,ca:options.ca,timeoutMs:handshakeTimeout,locale:options.locale,signal:options.signal},[tls13,tls12,tls11,tls10]=await Promise.all([primary.protocol==="TLSv1.3"?Promise.resolve("offered"):probeSpecificTlsVersion({...baseProbe,version:"TLSv1.3"}),primary.protocol==="TLSv1.2"?Promise.resolve("offered"):probeSpecificTlsVersion({...baseProbe,version:"TLSv1.2"}),primary.protocol==="TLSv1.1"?Promise.resolve("offered"):probeSpecificTlsVersion({...baseProbe,version:"TLSv1.1"}),primary.protocol==="TLSv1"?Promise.resolve("offered"):probeSpecificTlsVersion({...baseProbe,version:"TLSv1"})]),evaluated=evaluateTlsAuditResult({tls13,tls12,tls11,tls10,negotiatedCipher:primary.cipher,cert:primary.cert,minCertDays:options.minCertDays,locale:options.locale});return{status:evaluated.status,engine:"node:tls",host:cleanHost,port,pinnedIp:pin.address,negotiatedProtocol:primary.protocol??null,negotiatedCipher:primary.cipher??null,alpnProtocol:primary.alpn??null,tls13,tls12,tls11,tls10,cert:primary.cert,weakCipher:evaluated.weakCipher,weakKey:evaluated.weakKey,vulnerableItems:evaluated.vulnerableItems,warnings:evaluated.warnings,durationMs:Math.max(0,Math.round(performance.now()-startedAt))}}catch(error){if(isRimError(error)&&(error.code==="CANCELLED"||error.code==="SSRF_BLOCKED"))throw error;let msg=sanitizeLine(error instanceof Error?error.message:String(error));return{status:"FAIL",engine:"node:tls",host:cleanHost,port,pinnedIp:pin.address,tls13:"error",tls12:"error",tls11:"error",tls10:"error",vulnerableItems:[msg],warnings:[],durationMs:Math.max(0,Math.round(performance.now()-startedAt)),reason:msg}}}var EMPTY_STRING_SET=new Set,CHECKED_STD_HEADERS=new Set(["content-security-policy","strict-transport-security","x-content-type-options","x-frame-options","referrer-policy","cross-origin-opener-policy","permissions-policy"]);function auditHstsAndCoreHeaders(options){let{isHttps,headers,parsedCsp,requiredSet,locale,findings}=options;if(isHttps){let hsts=headers["strict-transport-security"]?.trim()??"",maxAgeMatch=/max-age\s*=\s*(\d+)/i.exec(hsts),maxAge=maxAgeMatch!==null?Number(maxAgeMatch[1]):0;if(hsts==="")findings.push({id:"sec:hsts",probe:"sec",status:requiredSet.has("strict-transport-security")?"FAIL":"WARN",title:rimT(locale,"HTTPS 站点缺少 Strict-Transport-Security (HSTS) 响应头","HTTPS site is missing Strict-Transport-Security (HSTS) header")});else if(maxAge<15552000)findings.push({id:"sec:hsts-short",probe:"sec",status:maxAge===0&&requiredSet.has("strict-transport-security")?"FAIL":"WARN",title:rimT(locale,`HSTS max-age 过短 (${maxAge}s < 15552000s / 180 天)`,`HSTS max-age is too short (${maxAge}s < 15552000s / 180 days)`),value:maxAge,threshold:15552000});else findings.push({id:"sec:hsts",probe:"sec",status:"PASS",title:`HSTS ok (max-age=${maxAge})`,value:maxAge})}let xcto=sanitizeLine(headers["x-content-type-options"]?.trim().toLowerCase()??"");findings.push(xcto==="nosniff"?{id:"sec:x-content-type-options",probe:"sec",status:"PASS",title:"X-Content-Type-Options: nosniff"}:{id:"sec:x-content-type-options",probe:"sec",status:requiredSet.has("x-content-type-options")?"FAIL":"WARN",title:rimT(locale,`X-Content-Type-Options 未设为 nosniff (${xcto||"missing"})`,`X-Content-Type-Options is not nosniff (${xcto||"missing"})`),value:xcto||"missing"});let xfo=sanitizeLine(headers["x-frame-options"]?.trim()??""),hasFrameAncestors=parsedCsp!==null&&Object.hasOwn(parsedCsp.directives,"frame-ancestors");if(xfo===""&&!hasFrameAncestors)findings.push({id:"sec:x-frame-options",probe:"sec",status:requiredSet.has("x-frame-options")?"FAIL":"WARN",title:rimT(locale,"缺少 X-Frame-Options 与 CSP frame-ancestors 防点击劫持头","Missing both X-Frame-Options and CSP frame-ancestors")});else if(xfo===""&&requiredSet.has("x-frame-options"))findings.push({id:"sec:x-frame-options",probe:"sec",status:"FAIL",title:rimT(locale,"缺少必需响应头 X-Frame-Options","Missing required header X-Frame-Options")});else findings.push({id:"sec:x-frame-options",probe:"sec",status:"PASS",title:`Clickjacking guard ok (${xfo||"CSP frame-ancestors"})`});let rp=sanitizeLine(headers["referrer-policy"]?.trim()??"");findings.push(rp===""||rp.toLowerCase()==="unsafe-url"?{id:"sec:referrer-policy",probe:"sec",status:requiredSet.has("referrer-policy")?"FAIL":"WARN",title:rimT(locale,`Referrer-Policy 缺失或过于宽松 (${rp||"missing"})`,`Referrer-Policy missing or unsafe (${rp||"missing"})`),value:rp||"missing"}:{id:"sec:referrer-policy",probe:"sec",status:"PASS",title:`Referrer-Policy: ${rp}`});let coop=sanitizeLine(headers["cross-origin-opener-policy"]?.trim()??"");findings.push(coop===""||coop.toLowerCase()==="unsafe-none"?{id:"sec:coop",probe:"sec",status:requiredSet.has("cross-origin-opener-policy")?"FAIL":"WARN",title:rimT(locale,`Cross-Origin-Opener-Policy (COOP) 缺失或为 unsafe-none (${coop||"missing"})`,`Cross-Origin-Opener-Policy (COOP) missing or unsafe-none (${coop||"missing"})`),value:coop||"missing"}:{id:"sec:coop",probe:"sec",status:"PASS",title:`COOP: ${coop}`});let pp=headers["permissions-policy"]?.trim()??"";findings.push(pp===""?{id:"sec:permissions-policy",probe:"sec",status:requiredSet.has("permissions-policy")?"FAIL":"WARN",title:rimT(locale,"缺少 Permissions-Policy 浏览器权限收敛头","Missing Permissions-Policy header")}:{id:"sec:permissions-policy",probe:"sec",status:"PASS",title:"Permissions-Policy present"})}function auditSecurityHeaders(options){let{targetUrl,headers,locale}=options,secCfg=options.secConfig??{},httpCfg=options.httpConfig??{},requiredSet=(httpCfg.requireSecurityHeaders?.length??0)>0||(secCfg.requireHeaders?.length??0)>0?new Set([...(httpCfg.requireSecurityHeaders??[]).map((h)=>h.toLowerCase()),...(secCfg.requireHeaders??[]).map((h)=>h.toLowerCase())]):EMPTY_STRING_SET,forbidSet=(secCfg.forbidHeaders?.length??0)>0?new Set(secCfg.forbidHeaders.map((h)=>h.toLowerCase())):EMPTY_STRING_SET,findings=[],parsedCsp=null;if(secCfg.checkCsp!==!1){let cspAudit=auditCspHeader(headers["content-security-policy"],locale,requiredSet.has("content-security-policy"));parsedCsp=cspAudit.parsed,findings.push(...cspAudit.findings)}auditHstsAndCoreHeaders({isHttps:targetUrl.toLowerCase().startsWith("https://"),headers,parsedCsp,requiredSet,locale,findings});for(let reqH of requiredSet){if(CHECKED_STD_HEADERS.has(reqH))continue;if((headers[reqH]?.trim()??"")==="")findings.push({id:`sec:header:${reqH}`,probe:"sec",status:"FAIL",title:rimT(locale,`缺少必需安全响应头: ${reqH}`,`Missing required security header: ${reqH}`)})}let DEFAULT_FINGERPRINT_HEADERS=new Set(["server","x-powered-by","x-aspnet-version"]),leakedFingerprints=[];for(let fp of DEFAULT_FINGERPRINT_HEADERS){let val=headers[fp]?.trim()??"";if(val!==""){let cleanVal=sanitizeLine(val);leakedFingerprints.push(`${fp}: ${cleanVal}`),findings.push({id:`sec:fingerprint-${fp}`,probe:"sec",status:forbidSet.has(fp)?"FAIL":"WARN",title:rimT(locale,`响应暴露服务端指纹头 ${fp}: ${cleanVal}`,`Response leaks server fingerprint header ${fp}: ${cleanVal}`),value:cleanVal})}}for(let forbidden of forbidSet){if(DEFAULT_FINGERPRINT_HEADERS.has(forbidden))continue;let val=headers[forbidden]?.trim()??"";if(val!==""){let cleanVal=sanitizeLine(val);leakedFingerprints.push(`${forbidden}: ${cleanVal}`),findings.push({id:`sec:forbid-${forbidden}`,probe:"sec",status:"FAIL",title:rimT(locale,`响应包含禁止响应头 ${forbidden}: ${cleanVal}`,`Response contains forbidden header ${forbidden}: ${cleanVal}`),value:cleanVal})}}return{findings,csp:parsedCsp,leakedFingerprints}}async function runSecProbe(options){let startedAt=performance.now(),audited=auditSecurityHeaders({targetUrl:options.targetUrl,headers:options.headers,httpConfig:options.httpConfig,secConfig:options.secConfig,locale:options.locale}),findings=[...audited.findings],tlsAudit;if(options.runTls===!0&&options.secConfig?.checkTls!==!1||options.secConfig?.checkTls===!0){let tlsInput={targetUrl:options.targetUrl,allowLoopback:options.allowLoopback===!0,minCertDays:options.secConfig?.tlsMinCertDays,timeoutMs:options.timeoutMs,locale:options.locale,signal:options.signal};tlsAudit=options.tlsAuditFn!==void 0?await options.tlsAuditFn(tlsInput):await runBuiltinTlsAudit(tlsInput),appendBuiltinTlsFindings(tlsAudit,options.locale,findings)}let testssl;if(options.runTestssl===!0||options.secConfig?.runTestssl===!0)testssl=await runOptionalTestssl({targetUrl:options.targetUrl,timeoutMs:options.timeoutMs,locale:options.locale,signal:options.signal,resolveAdapterBin:options.resolveAdapterBin}),appendTestsslFindings(testssl,options.locale,findings);let certDaysRemaining;if(tlsAudit?.cert?.daysRemaining!==void 0&&tlsAudit.cert.daysRemaining!==null)certDaysRemaining=tlsAudit.cert.daysRemaining;else if(testssl?.certDaysRemaining!==void 0&&testssl.certDaysRemaining!==null)certDaysRemaining=testssl.certDaysRemaining;let finalFindings=applyWaiversToFindings(findings,options.waivers);return{id:"sec",status:aggregateProbeStatus(finalFindings,"PASS"),durationMs:Math.max(0,Math.round(performance.now()-startedAt)),metrics:{hasCsp:audited.csp!==null,hasHsts:Boolean(options.headers["strict-transport-security"]),hasXcto:options.headers["x-content-type-options"]?.toLowerCase()==="nosniff",hasCoop:Boolean(options.headers["cross-origin-opener-policy"]),hasPermissionsPolicy:Boolean(options.headers["permissions-policy"]),leakedFingerprintCount:audited.leakedFingerprints.length,failures:finalFindings.filter((f)=>f.status==="FAIL").length,warnings:finalFindings.filter((f)=>f.status==="WARN").length,...certDaysRemaining!==void 0?{certDaysRemaining}:{},...tlsAudit!==void 0&&tlsAudit.status!=="SKIP"?{tlsProtocol:tlsAudit.negotiatedProtocol??null,tls13:tlsAudit.tls13==="offered",tls12:tlsAudit.tls12==="offered",alpnProtocol:tlsAudit.alpnProtocol??null}:{}},findings:finalFindings,evidence:{cspDirectives:audited.csp?.directives??null,leakedFingerprints:audited.leakedFingerprints,...tlsAudit!==void 0?{tls:tlsAudit}:{},...testssl!==void 0?{testssl}:{}}}}function checkAborted2(signal,locale){if(signal?.aborted===!0)throw new RimError("CANCELLED",rimT(locale,"门禁执行已取消","Rim audit execution cancelled"))}function buildHttpGateResult(protoOut){let routeFailed=protoOut.routeProbeResults.some((r)=>!r.passed),routeWarned=protoOut.routeProbeResults.some((r)=>r.missingWarnHeaders.length>0),status="pass";if(routeFailed)status="fail";else if(routeWarned)status="warn";return{status,routes:protoOut.routeProbeResults,elapsedMs:protoOut.probe.durationMs,...protoOut.probe.reason!==void 0?{reason:protoOut.probe.reason}:{}}}async function runProtoAndPerfStage(input){let{target,preset,enabled,config,options,deps,locale,timeoutMs}=input,allowLoopback=target.isLocal,wantH2H3=config.proto?.checkH2H3!==!1&&(preset!=="quick"&&target.url.toLowerCase().startsWith("https://")||config.proto?.checkH2H3===!0),deferH2H3=wantH2H3&&enabled.has("perf"),protoPromise=enabled.has("proto")?(()=>{options.onProgress?.({phase:"proto",detail:rimT(locale,`执行协议与首包预算探针 (${target.url})`,`Running proto probe (${target.url})`)});let p=runProtoProbe({targetUrl:target.url,allowLoopback,httpConfig:config.http,protoConfig:deferH2H3?{...config.proto,checkH2H3:!1}:config.proto,budgets:config.budgets,waivers:config.waivers,runH2H3:wantH2H3&&!deferH2H3,chromePath:input.chromePath,timeoutMs:Math.min(timeoutMs,20000),locale,signal:options.signal,fetchFn:deps.fetchFn,launchChromeFn:deps.launchChromeFn});return p.catch(()=>{}),p})():null,protoConsumed=!1,protoOut=null,perfProbe=null,lhStatus="disabled",lhReason,lhSummaries=[];try{if(enabled.has("perf")){let perfRoutes=options.url!==void 0&&options.paths===void 0&&options.path===void 0?[new URL(target.url).pathname]:input.routes,perfOut=await runPerfProbe({targetUrl:target.url,routes:perfRoutes,devices:input.devices,projectRoot:input.projectRoot,chromePath:input.chromePath,coldGpu:input.coldGpu,cpuSlowdown:input.cpuSlowdown,outDir:input.outDir,writeReports:input.writeReports,thresholds:input.thresholds,waivers:config.waivers,timeoutMs,locale,signal:options.signal,onProgress:options.onProgress,launchChromeFn:deps.launchChromeFn,lighthouseRunner:deps.lighthouseRunner,perfAdapter:deps.perfAdapter});lhStatus=perfOut.status,lhReason=perfOut.reason,lhSummaries=perfOut.summaries,perfProbe=perfOut.probe}if(protoPromise!==null){if(protoConsumed=!0,protoOut=await protoPromise,deferH2H3&&protoOut.probe.metrics.status!==0)options.onProgress?.({phase:"proto",detail:rimT(locale,"执行 HTTP/2 vs HTTP/3 (QUIC) 路径 MTU 探针","Running HTTP/2 vs HTTP/3 (QUIC) Path MTU probe")}),protoOut=await attachH2H3ToProtoOutput({protoOut,targetUrl:target.url,chromePath:input.chromePath,timeoutMs:config.proto?.h2h3TimeoutMs??Math.min(timeoutMs,15000),waivers:config.waivers,locale,signal:options.signal,launchChromeFn:deps.launchChromeFn})}}finally{if(protoPromise!==null&&!protoConsumed)await protoPromise.catch(()=>{})}return{protoOut,perfProbe,lhStatus,lhReason,lhSummaries}}async function runSecStage(input){let{locale,options,deps,config,timeoutMs}=input;checkAborted2(options.signal,locale),options.onProgress?.({phase:"sec",detail:rimT(locale,"执行安全响应头与 CSP3 探针","Running security headers & CSP3 probe")});let{primaryHeaders,primaryHtml,primaryLinkHeaders}=input;if(!input.hasProtoOutput)try{let res=await ssrfHttpRequest({url:input.targetUrl,headers:{"Accept-Encoding":"br, gzip, identity",Accept:"text/html,application/xhtml+xml,*/*;q=0.8"},allowLoopback:input.allowLoopback,timeoutMs:Math.min(timeoutMs,15000),locale,signal:options.signal,fetchFn:deps.fetchFn});primaryHeaders=res.headers,primaryLinkHeaders=res.linkHeaders,primaryHtml=decompressBodySafe(res.rawBody,res.contentEncoding).toString("utf8")}catch(error){if(isRimError(error)&&(error.code==="CANCELLED"||error.code==="SSRF_BLOCKED"))throw error;let errText=sanitizeLine(error instanceof Error?error.message:String(error));return{probe:{id:"sec",status:"FAIL",durationMs:0,metrics:{reachable:!1,failures:1,warnings:0},findings:[{id:"sec:unreachable",probe:"sec",status:"FAIL",title:rimT(locale,"目标不可达","Target unreachable"),detail:errText}],evidence:{targetUrl:input.targetUrl,error:errText},reason:errText},primaryHeaders,primaryHtml,primaryLinkHeaders}}let wantTls=config.sec?.checkTls!==!1&&(deps.tlsAuditFn!==void 0||deps.fetchFn===void 0)&&(input.preset==="full"||config.sec?.checkTls===!0);return{probe:await runSecProbe({targetUrl:input.targetUrl,allowLoopback:input.allowLoopback,headers:primaryHeaders,httpConfig:config.http,secConfig:config.sec,waivers:config.waivers,runTls:wantTls,runTestssl:config.sec?.runTestssl===!0,timeoutMs,locale,signal:options.signal,resolveAdapterBin:deps.resolveAdapterBin,tlsAuditFn:deps.tlsAuditFn}),primaryHeaders,primaryHtml,primaryLinkHeaders}}async function executeProbePipeline(input){let{target,preset,enabled,config,options,deps,locale,timeoutMs}=input,allowLoopback=target.isLocal;if(target.mode==="url"&&!allowLoopback&&deps.fetchFn===void 0)await resolveAndPinHost({hostname:new URL(target.url).hostname,allowLoopback:!1,locale});let probeResults=[],stage1=await runProtoAndPerfStage(input),httpResult={status:"disabled",routes:[],elapsedMs:0},primaryHeaders={},primaryHtml="",primaryLinkHeaders=[];if(stage1.perfProbe!==null)probeResults.push(stage1.perfProbe);if(stage1.protoOut!==null)primaryHeaders=stage1.protoOut.primaryHeaders,primaryHtml=stage1.protoOut.primaryHtml,primaryLinkHeaders=stage1.protoOut.primaryLinkHeaders,probeResults.push(stage1.protoOut.probe),httpResult=buildHttpGateResult(stage1.protoOut);if(enabled.has("sec")){let secOut=await runSecStage({targetUrl:target.url,allowLoopback,hasProtoOutput:stage1.protoOut!==null,primaryHeaders,primaryHtml,primaryLinkHeaders,preset,config,timeoutMs,locale,options,deps});primaryHeaders=secOut.primaryHeaders,primaryHtml=secOut.primaryHtml,primaryLinkHeaders=secOut.primaryLinkHeaders,probeResults.push(secOut.probe)}let smokeResult={status:"disabled",mode:"disabled",pageExceptions:[],consoleErrors:[],failedRequests:[],steps:[],elapsedMs:0};if(enabled.has("quality")){checkAborted2(options.signal,locale),options.onProgress?.({phase:"quality",detail:rimT(locale,"执行质量探针 (CDP 冒烟 / 死链 / 锚点)","Running quality probe (CDP smoke / links / anchors)")});let qOut=await runQualityProbe({targetUrl:target.url,allowLoopback,html:primaryHtml,linkHeaders:primaryLinkHeaders,chromePath:input.chromePath,smokeConfig:config.smoke,qualityConfig:config.quality,runSmoke:!0,checkExternalLinks:config.quality?.checkExternalLinks!==!1&&(preset==="full"||config.quality?.checkExternalLinks===!0),checkAxe:config.quality?.checkAxe!==!1&&(preset==="full"||config.quality?.checkAxe===!0),runOptionalAdapters:!1,waivers:config.waivers,cwd:input.projectRoot,timeoutMs,locale,signal:options.signal,fetchFn:deps.fetchFn,launchChromeFn:deps.launchChromeFn,runSmokeFn:deps.runSmokeFn,axeRunner:deps.axeRunner,resolveAdapterBin:deps.resolveAdapterBin});smokeResult=qOut.smoke,probeResults.push(qOut.probe)}if(enabled.has("load"))checkAborted2(options.signal,locale),options.onProgress?.({phase:"load",detail:rimT(locale,"执行受控短时并发压测探针","Running bounded load probe")}),probeResults.push(await runLoadProbe({targetUrl:target.url,allowLoad:options.allowLoad===!0,loadConfig:config.load,waivers:config.waivers,timeoutMs,locale,signal:options.signal,fetchFn:deps.fetchFn,resolveAdapterBin:deps.resolveAdapterBin}));return{probeResults,httpResult,lhStatus:stage1.lhStatus,...stage1.lhReason!==void 0?{lhReason:stage1.lhReason}:{},lhSummaries:stage1.lhSummaries,smokeResult}}var CATEGORY_MAP=[{lhrKey:"performance",thresholdKey:"performance",zhLabel:"性能",enLabel:"performance"},{lhrKey:"accessibility",thresholdKey:"accessibility",zhLabel:"无障碍",enLabel:"accessibility"},{lhrKey:"best-practices",thresholdKey:"bestPractices",zhLabel:"最佳实践",enLabel:"best-practices"},{lhrKey:"seo",thresholdKey:"seo",zhLabel:"SEO",enLabel:"seo"}];function evaluateMetricUpperBound(options){let{id,perfId,label,value,limit,unit,missingCode,failCode,waivers,checks}=options;if(value===null){checks.push({id,gate:"lighthouse",status:"skip",code:missingCode,message:`${label} is missing`});return}let waived=matchWaiver(waivers,id,"perf")??matchWaiver(waivers,perfId,"perf");if(value>limit){if(waived!==void 0)checks.push({id,gate:"lighthouse",status:"waived",code:"WAIVED",waiverReason:waived.reason,message:`${label}=${value}${unit} > ${limit}${unit} (WAIVED: ${waived.reason})`});else checks.push({id,gate:"lighthouse",status:"fail",code:failCode,message:`${label}=${value}${unit} > ${limit}${unit}`});return}checks.push({id,gate:"lighthouse",status:"pass",message:`${label}=${value}${unit} <= ${limit}${unit}`})}function evaluateSingleSummary(summary,thresholds,waivers,locale,checks){let p=summary.preset,routeSuffix=summary.route!==void 0&&summary.route!=="/"?`(${summary.route})`:"";if(summary.runtimeError!==void 0)checks.push({id:`lighthouse:${p}:runtime`,gate:"lighthouse",status:"fail",code:"LIGHTHOUSE_RUNTIME_ERROR",message:`${p}${routeSuffix} runtimeError (${summary.runtimeError.code??"ERROR"}): ${summary.runtimeError.message}`});for(let cat of CATEGORY_MAP){let score=summary.scores[cat.lhrKey],minVal=thresholds[cat.thresholdKey],id=`lighthouse:${p}:${cat.lhrKey}`,waived=matchWaiver(waivers,id,"perf")??matchWaiver(waivers,`perf:${p}:${cat.lhrKey}`,"perf");if(score===null||score===void 0||!Number.isFinite(score))checks.push({id,gate:"lighthouse",status:"skip",code:"MISSING_CATEGORY_SCORE",message:rimT(locale,`${p}${routeSuffix} ${cat.zhLabel}得分缺失 (null), 无法通过严格门禁`,`${p}${routeSuffix} ${cat.enLabel} score is missing (null)`)});else if(score<minVal)if(waived!==void 0)checks.push({id,gate:"lighthouse",status:"waived",code:"WAIVED",waiverReason:waived.reason,message:`${p}${routeSuffix} ${cat.lhrKey}=${score} < ${minVal} (WAIVED: ${waived.reason})`});else checks.push({id,gate:"lighthouse",status:"fail",code:"SCORE_BELOW_THRESHOLD",message:`${p}${routeSuffix} ${cat.lhrKey}=${score} < ${minVal}`});else checks.push({id,gate:"lighthouse",status:"pass",message:`${p}${routeSuffix} ${cat.lhrKey}=${score} >= ${minVal}`})}let ltId=`lighthouse:${p}:long-tasks`;if(!summary.longTasksAuditPresent)checks.push({id:ltId,gate:"lighthouse",status:"skip",code:"MISSING_LONG_TASKS_AUDIT",message:rimT(locale,`${p}${routeSuffix} 缺少 long-tasks 审计条目`,`${p}${routeSuffix} long-tasks audit is missing from LHR`)});else evaluateMetricUpperBound({id:ltId,perfId:`perf:${p}:long-tasks`,label:`${p}${routeSuffix} long-tasks`,value:summary.longTasks.length,limit:thresholds.maxLongTasks,unit:"",missingCode:"MISSING_LONG_TASKS_AUDIT",failCode:"LONG_TASKS_EXCEEDED",waivers,checks});if(thresholds.maxTbtMs!==void 0)evaluateMetricUpperBound({id:`lighthouse:${p}:tbt`,perfId:`perf:${p}:tbt`,label:`${p}${routeSuffix} tbt`,value:summary.metrics.tbtMs,limit:thresholds.maxTbtMs,unit:"ms",missingCode:"MISSING_TBT_METRIC",failCode:"TBT_EXCEEDED",waivers,checks});if(thresholds.maxCls!==void 0)evaluateMetricUpperBound({id:`lighthouse:${p}:cls`,perfId:`perf:${p}:cls`,label:`${p}${routeSuffix} cls`,value:summary.metrics.clsValue,limit:thresholds.maxCls,unit:"",missingCode:"MISSING_CLS_METRIC",failCode:"CLS_EXCEEDED",waivers,checks});for(let lf of summary.findings)if(lf.waived===!0)checks.push({id:`lighthouse:${p}:waived:${lf.id}`,gate:"lighthouse",status:"waived",code:"WAIVED",waiverReason:lf.waiverReason,message:`${p}${routeSuffix} ${lf.id}: ${lf.title} (WAIVED: ${lf.waiverReason??""})`})}function evaluateLighthouseChecks(input,checks){let{lighthouseStatus,lighthouseReason,lighthouseSummaries,thresholds,waivers,locale}=input;if(lighthouseStatus==="disabled"){checks.push({id:"lighthouse",gate:"lighthouse",status:"disabled",message:rimT(locale,"Lighthouse 门禁已禁用","Lighthouse gate disabled")});return}if(lighthouseStatus==="skip"||lighthouseSummaries.length===0){checks.push({id:"lighthouse",gate:"lighthouse",status:"skip",code:"LIGHTHOUSE_SKIPPED",message:lighthouseReason??rimT(locale,"Lighthouse 审计未产出有效档位结果","Lighthouse audit produced no preset results")});return}for(let summary of lighthouseSummaries)evaluateSingleSummary(summary,thresholds,waivers,locale,checks)}function probeStatusToCheckStatus(status){if(status==="PASS")return"pass";if(status==="WARN")return"warn";if(status==="FAIL")return"fail";if(status==="WAIVED")return"waived";return"skip"}function formatProbeFindingMessage(f,status){if(status==="waived"&&f.waiverReason!==void 0)return`${f.title} (WAIVED: ${f.waiverReason})`;if(f.detail!==void 0)return`${f.title}: ${f.detail}`;return f.title}function evaluateHttpChecks(http,locale,checks){if(http.status==="disabled"){checks.push({id:"http",gate:"http",status:"disabled",message:rimT(locale,"HTTP 门禁已禁用","HTTP gate disabled")});return}if(http.status==="skip"){checks.push({id:"http",gate:"http",status:"skip",code:"HTTP_SKIPPED",message:http.reason??rimT(locale,"HTTP 门禁被跳过","HTTP gate was skipped")});return}for(let route of http.routes){let id=`http:${route.method}:${route.path}`;if(!route.passed)checks.push({id,gate:"http",status:"fail",code:"HTTP_ROUTE_FAILED",message:`${route.method} ${route.path}: ${route.failureReason??"failed"}`});else if(route.missingWarnHeaders.length>0)checks.push({id,gate:"http",status:"warn",code:"HTTP_SECURITY_HEADER_MISSING",message:rimT(locale,`${route.method} ${route.path} (${route.status}, ${route.ttfbMs}ms) 建议补充安全头: ${route.missingWarnHeaders.join(", ")}`,`${route.method} ${route.path} (${route.status}, ${route.ttfbMs}ms) missing recommended headers: ${route.missingWarnHeaders.join(", ")}`)});else checks.push({id,gate:"http",status:"pass",message:`${route.method} ${route.path} -> ${route.status} (${route.ttfbMs}ms${route.contentEncoding!==null?`, ${route.contentEncoding}`:""})`})}}function evaluateSmokeChecks(smoke,locale,checks){if(smoke.status==="disabled"){checks.push({id:"smoke",gate:"smoke",status:"disabled",message:rimT(locale,"CDP 冒烟门禁已禁用","CDP smoke gate disabled")});return}if(smoke.status==="skip"){checks.push({id:"smoke",gate:"smoke",status:"skip",code:"SMOKE_SKIPPED",message:smoke.reason??rimT(locale,"CDP 冒烟门禁被跳过","CDP smoke gate was skipped")});return}if(smoke.status==="fail"){checks.push({id:"smoke",gate:"smoke",status:"fail",code:"SMOKE_FAILED",message:smoke.reason??rimT(locale,"CDP 冒烟门禁未通过","CDP smoke gate failed")});return}let passMsg=smoke.mode==="command"?rimT(locale,`外部冒烟命令通过 (${smoke.elapsedMs}ms)`,`External smoke command passed (${smoke.elapsedMs}ms)`):rimT(locale,`CDP 冒烟通过 (${smoke.steps.length} 步, ${smoke.pageExceptions.length} 异常, ${smoke.consoleErrors.length} 控制台错误, ${smoke.failedRequests.length} 失败请求)`,`CDP smoke passed (${smoke.steps.length} steps, ${smoke.pageExceptions.length} exceptions, ${smoke.consoleErrors.length} console errors, ${smoke.failedRequests.length} failed requests)`);checks.push({id:"smoke",gate:"smoke",status:"pass",message:passMsg})}function evaluateUnifiedProbes(probes,disabledProbes,input,checks){for(let probe of probes){if(probe.id==="perf"){evaluateLighthouseChecks(input,checks);continue}if(probe.status==="SKIP"&&probe.findings.length===0){checks.push({id:probe.id,gate:probe.id,status:"skip",code:`${probe.id.toUpperCase()}_SKIPPED`,message:probe.reason??rimT(input.locale,`探针 ${probe.id} 被跳过`,`Probe ${probe.id} was skipped`)});continue}if(probe.findings.length===0){checks.push({id:probe.id,gate:probe.id,status:probeStatusToCheckStatus(probe.status),message:`${probe.id}: ${probe.status}`});continue}for(let f of probe.findings){let status=probeStatusToCheckStatus(f.status);checks.push({id:f.id,gate:probe.id,status,...status==="fail"?{code:`${probe.id.toUpperCase()}_FAILED`}:{},...status==="skip"?{code:`${probe.id.toUpperCase()}_SKIPPED`}:{},...status==="waived"?{code:"WAIVED",waiverReason:f.waiverReason}:{},message:formatProbeFindingMessage(f,status)})}}for(let disabledId of disabledProbes??[])checks.push({id:disabledId,gate:disabledId,status:"disabled",message:rimT(input.locale,`探针 ${disabledId} 已禁用`,`Probe ${disabledId} disabled`)})}function evaluateGateVerdict(input){let checks=[];if(input.probes!==void 0)evaluateUnifiedProbes(input.probes,input.disabledProbes,input,checks);else evaluateHttpChecks(input.http,input.locale,checks),evaluateLighthouseChecks(input,checks),evaluateSmokeChecks(input.smoke,input.locale,checks);let allowSkip=new Set(input.strictAllowSkip??[]),failures=[],warnings=[],waived=[],skipped=[],disabled=[],executedCount=0;for(let item of checks){if(item.status==="disabled"){disabled.push(item);continue}if(item.status==="skip"){if(skipped.push(item),input.strict&&!allowSkip.has(item.id)&&!allowSkip.has(item.gate))failures.push({...item,status:"fail",code:"SKIP_IN_STRICT_MODE",message:rimT(input.locale,`严格模式禁止跳过项 [${item.id}]: ${item.message}`,`Strict mode rejects skipped check [${item.id}]: ${item.message}`)});continue}if(executedCount+=1,item.status==="fail")failures.push(item);else if(item.status==="warn")warnings.push(item);else if(item.status==="waived")waived.push(item)}if(input.strict&&executedCount===0)failures.push({id:"gate:zero-checks",gate:"proto",status:"fail",code:"NO_CHECKS_EXECUTED",message:rimT(input.locale,"严格模式拦截空跑: 实际执行检查数为 0","Strict mode rejected empty run: 0 checks were executed")});return{passed:input.strict?failures.length===0:!0,strict:input.strict,checks,failures,warnings,waived,skipped,disabled,executedCount}}var ALL_PROBES=["proto","sec","perf","quality","load"];function expandGateKind(kind){if(kind==="http")return["proto","sec"];if(kind==="lighthouse")return["perf"];if(kind==="smoke")return["quality"];return[kind]}function resolveEnabledProbes(preset,config,only,skip){let active=new Set;if(preset==="quick")active.add("proto"),active.add("sec");else if(preset==="ci"){if(active.add("proto"),active.add("sec"),active.add("perf"),config.quality?.enabled===!0||config.smoke?.enabled===!0||config.quality?.smoke?.enabled===!0||(config.smoke?.steps?.length??0)>0||(config.quality?.smoke?.steps?.length??0)>0||(config.smoke?.argv?.length??0)>0||(config.quality?.smoke?.argv?.length??0)>0)active.add("quality")}else for(let p of ALL_PROBES)active.add(p);if(config.proto?.enabled===!1||config.http?.enabled===!1)active.delete("proto");if(config.sec?.enabled===!1)active.delete("sec");if(config.quality?.enabled===!1)active.delete("quality");else if(config.smoke?.enabled===!1&&preset==="ci"&&config.quality?.enabled!==!0)active.delete("quality");if(config.load?.enabled===!1)active.delete("load");if(only!==void 0&&only.length>0){active.clear();for(let k of only)for(let p of expandGateKind(k))active.add(p)}for(let k of skip??[])for(let p of expandGateKind(k))active.delete(p);let disabled=ALL_PROBES.filter((p)=>!active.has(p));return{enabled:active,disabled}}function mergeThresholds(config,options){let b=config.budgets?.lighthouse,c=config.thresholds;return{performance:options.minPerf??b?.minPerf??b?.performance??c?.performance??DEFAULT_THRESHOLDS.performance,accessibility:options.minA11y??b?.minA11y??b?.accessibility??c?.accessibility??DEFAULT_THRESHOLDS.accessibility,bestPractices:options.minBp??b?.minBp??b?.bestPractices??c?.bestPractices??DEFAULT_THRESHOLDS.bestPractices,seo:options.minSeo??b?.minSeo??b?.seo??c?.seo??DEFAULT_THRESHOLDS.seo,maxLongTasks:options.maxLongTasks??b?.maxLongTasks??c?.maxLongTasks??DEFAULT_THRESHOLDS.maxLongTasks,...options.maxTbtMs!==void 0||b?.maxTbtMs!==void 0||c?.maxTbtMs!==void 0?{maxTbtMs:options.maxTbtMs??b?.maxTbtMs??c?.maxTbtMs}:{},...options.maxCls!==void 0||b?.maxCls!==void 0||c?.maxCls!==void 0?{maxCls:options.maxCls??b?.maxCls??c?.maxCls}:{}}}function resolveBridgeOverride(config,options,cwd){if(options.bridgeModule!==void 0&&options.bridgeModule.trim()!=="")return{type:"module",entry:resolve12(cwd,options.bridgeModule.trim())};if(options.startCommand!==void 0&&options.startCommand.trim()!=="")return{type:"command",command:options.startCommand.trim()};if(options.serveDir!==void 0&&options.serveDir.trim()!=="")return{type:"static",dir:resolve12(cwd,options.serveDir.trim())};return config.bridge}function pickRawRoutes(config,options){if(options.paths!==void 0&&options.paths.length>0)return options.paths;if(options.path!==void 0&&options.path.trim()!=="")return[options.path];if(config.routes!==void 0&&config.routes.length>0)return config.routes;if(config.path!==void 0&&config.path.trim()!=="")return[config.path];return["/"]}function normalizeRoutePath(raw){let trimmed=raw.trim();if(trimmed===""||trimmed==="/")return"/";if(trimmed.startsWith("/"))return trimmed;return`/${trimmed}`}function resolveRoutesList(config,options){let raw=pickRawRoutes(config,options),out=[],seen=new Set;for(let r of raw){let norm=normalizeRoutePath(r);if(!seen.has(norm))seen.add(norm),out.push(norm)}return out}function resolveTargetInputs(config,options,routes){let hasCliBridgeOverride=options.bridgeModule!==void 0&&options.bridgeModule.trim()!==""||options.startCommand!==void 0&&options.startCommand.trim()!==""||options.serveDir!==void 0&&options.serveDir.trim()!=="",hasLocalConfig=options.local===!0||hasCliBridgeOverride||config.bridge!==void 0||config.local!==void 0,effectiveUrl;if(options.url!==void 0&&options.url.trim()!=="")effectiveUrl=options.url;else if(!hasLocalConfig)effectiveUrl=config.url??config.baseUrl;let initialPath;if(options.paths!==void 0&&options.paths.length>0)initialPath=routes[0];else if(options.path!==void 0)initialPath=options.path;else if(effectiveUrl===void 0)initialPath=routes[0];return{hasCliBridgeOverride,effectiveUrl,initialPath}}async function runRim(options={},deps={}){let startedAt=performance.now(),locale=pickLocale(options.locale),cwd=resolve12(options.cwd??process.cwd());checkAborted2(options.signal,locale);let loaded=loadRimConfig({cwd,configPath:options.configPath,locale}),config=loaded.config,projectRoot=loaded.path!==null?dirname9(loaded.path):cwd,preset=options.preset??config.preset??"ci",{enabled,disabled}=resolveEnabledProbes(preset,config,options.only,options.skip),strict=options.strict??config.strict??!1,thresholds=mergeThresholds(config,options),devices=options.devices??options.presets??config.devices??config.presets??["mobile","desktop"],routes=resolveRoutesList(config,options),cpuSlowdown=options.cpuSlowdown??config.cpuSlowdown??null,coldGpu=options.coldGpu??config.coldGpu??!1,outDir=options.outDir!==void 0?resolve12(cwd,options.outDir):config.outDir??"dist/lighthouse",writeReports=options.writeReports??config.writeReports??!0,timeoutMs=options.timeoutMs??config.timeoutMs??60000,strictAllowSkip=options.strictAllowSkip??config.strictAllowSkip,hasExplicitSmokeCommand=(config.quality?.smoke?.argv?.length??config.smoke?.argv?.length??0)>0,chromeRequired=enabled.has("perf"),chromeUseful=chromeRequired||enabled.has("quality")&&!hasExplicitSmokeCommand||enabled.has("proto")&&preset!=="quick",chromePath=null;if(chromeUseful){if(chromePath=(deps.resolveChrome!==void 0?deps.resolveChrome(options.chromePath):resolveChromePath({explicitPath:options.chromePath})).path,chromeRequired&&chromePath===null)throw new RimError("CHROME_NOT_FOUND",rimT(locale,"未检测到本机 Chrome / Chromium / Edge, 请安装浏览器或通过 --chrome-path / RIM_CHROME_PATH / CHROME_PATH 指定绝对路径","No local Chrome / Chromium / Edge binary detected; install a browser or pass --chrome-path / RIM_CHROME_PATH / CHROME_PATH"))}options.onProgress?.({phase:"bridge",detail:rimT(locale,"准备目标站点桥接","Preparing target site bridge")});let{hasCliBridgeOverride,effectiveUrl,initialPath}=resolveTargetInputs(config,options,routes),guard=new LifecycleGuard;guard.assertNotShuttingDown(locale);let target=await startTargetBridge({projectRoot:hasCliBridgeOverride?cwd:projectRoot,url:effectiveUrl,localOnly:options.local===!0,path:initialPath,bridge:resolveBridgeOverride(config,options,cwd),local:config.local,locale,signal:options.signal,fetchFn:deps.fetchFn});guard.register(()=>target.stop());let pipelineOut;try{pipelineOut=await executeProbePipeline({target,preset,enabled,routes,devices,projectRoot,chromePath,coldGpu,cpuSlowdown,outDir,writeReports,thresholds,timeoutMs,locale,config,options,deps})}finally{await guard.cleanupAll()}let orderMap=new Map(ALL_PROBES.map((id,idx)=>[id,idx]));pipelineOut.probeResults.sort((a,b)=>(orderMap.get(a.id)??99)-(orderMap.get(b.id)??99));let verdict=evaluateGateVerdict({strict,strictAllowSkip,thresholds,waivers:config.waivers,probes:pipelineOut.probeResults,disabledProbes:disabled,http:pipelineOut.httpResult,lighthouseStatus:pipelineOut.lhStatus,lighthouseReason:pipelineOut.lhReason,lighthouseSummaries:pipelineOut.lhSummaries,smoke:pipelineOut.smokeResult,locale}),lhStatus=pipelineOut.lhStatus;if(enabled.has("perf")&&lhStatus==="pass"){let lhFailed=verdict.failures.some((item)=>item.gate==="lighthouse"||item.gate==="perf"),lhSkipped=verdict.skipped.some((item)=>item.gate==="lighthouse"||item.gate==="perf");if(lhFailed)lhStatus="fail";else if(lhSkipped)lhStatus="skip"}let effectiveReportRoutes=options.url!==void 0&&options.paths===void 0&&options.path===void 0?[new URL(target.url).pathname]:routes,baseReport={targetUrl:target.url,routes:effectiveReportRoutes,preset,devices,bridge:{mode:target.mode,detail:target.detail},configPath:loaded.path,runtime:getRuntimeInfo(),strict,passed:verdict.passed,thresholds,probes:pipelineOut.probeResults,disabledProbes:disabled,http:pipelineOut.httpResult,lighthouse:{status:lhStatus,summaries:pipelineOut.lhSummaries,...pipelineOut.lhReason!==void 0?{reason:pipelineOut.lhReason}:{}},smoke:pipelineOut.smokeResult,verdict,elapsedMs:Math.max(0,Math.round(performance.now()-startedAt))},finalReport=await finalizeBaselineAndHtml({baseReport,targetUrl:target.url,bridgeMode:target.mode,configName:config.name,cwd,locale,options});return options.onProgress?.({phase:"done",detail:rimT(locale,"门禁检查完成","Rim audit checks completed")}),finalReport}var MAIN_VALUE_FLAGS=["--lang","-c","--config","--url","--path","--serve-dir","--bridge","--start","--preset","--device","--only","--skip","--min-perf","--min-a11y","--min-bp","--min-seo","--max-long-tasks","--cpu-slowdown","--out-dir","--html","--chrome-path","--timeout","--keep"],SHARED_SUBCOMMANDS=new Set(["lang","update","uninstall"]),VALID_PROBES=new Set(["proto","sec","perf","quality","load"]);function resolveRimValueFlags(argv){let i=0;while(i<argv.length){let tok=argv[i];if(tok==="--json"){i+=1;continue}if(tok==="--lang"){let next=argv[i+1];i+=next!==void 0&&!next.startsWith("-")?2:1;continue}if(tok.startsWith("--lang=")){i+=1;continue}break}let head=argv[i];if(head==="update")return new Set([...UPDATE_VALUE_FLAGS,"--lang"]);if(head==="uninstall")return new Set([...UNINSTALL_VALUE_FLAGS,"--lang"]);if(head==="lang")return new Set(["--lang"]);return new Set(MAIN_VALUE_FLAGS)}function detectPreDashJson(argv,valueFlags){let expectValue=!1;for(let i=0;i<argv.length;i+=1){let tok=argv[i];if(expectValue){if(expectValue=!1,tok==="--json")return!0;if(tok==="--"||!tok.startsWith("-"))continue}if(tok==="--")return!1;if(tok==="--json")return!0;if(valueFlags.has(tok))expectValue=!0}return!1}function splitFlagEquals(tok){let eq=tok.indexOf("=");if(eq<=0||!tok.startsWith("--"))return{flag:tok};return{flag:tok.slice(0,eq),inlineVal:tok.slice(eq+1)}}function parseProbeList(raw,flag,locale){let parts=raw.split(",").map((p)=>p.trim().toLowerCase()).filter((p)=>p!=="");if(parts.length===0)return t(locale,`${flag} 不能为空 (可选: proto, sec, perf, quality, load)`,`${flag} cannot be empty (choices: proto, sec, perf, quality, load)`);let out=[],seen=new Set;for(let part of parts){if(!VALID_PROBES.has(part))return t(locale,`${flag} 包含非法探针名: ${part} (可选: proto, sec, perf, quality, load)`,`${flag} contains invalid probe: ${part} (choices: proto, sec, perf, quality, load)`);if(!seen.has(part))seen.add(part),out.push(part)}return out}function parseBoundedNum(raw,flag,min,max,locale){let trimmed=raw.trim(),num=Number(trimmed);if(trimmed===""||!Number.isFinite(num)||num<min||num>max)return t(locale,`${flag} 需要 [${min}, ${max}] 范围内的数值, 收到: ${raw}`,`${flag} requires a number in [${min}, ${max}], received: ${raw}`);return num}function parsePresetValue(raw,locale){let norm=raw.trim().toLowerCase();if(norm==="quick"||norm==="ci"||norm==="full")return norm;return t(locale,`--preset 非法值: ${raw} (仅支持 quick | ci | full; 设备档位请用 --device mobile|desktop|both)`,`Invalid --preset value: ${raw} (expected quick | ci | full; use --device for mobile|desktop|both)`)}function parseDeviceValue(raw,locale){let norm=raw.trim().toLowerCase();if(norm==="mobile")return["mobile"];if(norm==="desktop")return["desktop"];if(norm==="both")return["mobile","desktop"];return t(locale,`--device 非法值: ${raw} (仅支持 mobile | desktop | both)`,`Invalid --device value: ${raw} (expected mobile | desktop | both)`)}function extractSharedSubcommand(argv){let json=!1,i=0;while(i<argv.length&&argv[i]==="--json")json=!0,i+=1;let head=argv[i];if(head===void 0||!SHARED_SUBCOMMANDS.has(head))return null;let sub=head,valueFlags=new Set;if(sub==="update")valueFlags=new Set(UPDATE_VALUE_FLAGS);else if(sub==="uninstall")valueFlags=new Set(UNINSTALL_VALUE_FLAGS);let rest=[],afterDash=!1,expectValue=!1;for(let tok of argv.slice(i+1)){if(afterDash){rest.push(tok);continue}if(expectValue){if(expectValue=!1,tok==="--json"){json=!0,rest.push(tok);continue}if(tok==="--"||!tok.startsWith("-")){rest.push(tok);continue}}if(tok==="--"){afterDash=!0,rest.push(tok);continue}if(tok==="--json"){json=!0;continue}if(valueFlags.has(tok))expectValue=!0;rest.push(tok)}return{command:sub,json,rest}}var BOOL_FLAG_SETTERS={"--json":(s)=>{s.json=!0},"-V":(s)=>{s.version=!0},"--version":(s)=>{s.version=!0},"-h":(s)=>{s.help=!0},"--help":(s)=>{s.help=!0},"--strict":(s)=>{s.strict=!0},"--local":(s)=>{s.local=!0},"--cold-gpu":(s)=>{s.coldGpu=!0},"--no-report":(s)=>{s.writeReports=!1},"--save-baseline":(s)=>{s.saveBaseline=!0},"--diff":(s)=>{s.diffBaseline=!0},"--allow-load":(s)=>{s.allowLoad=!0},"-y":(s)=>{s.yes=!0},"--yes":(s)=>{s.yes=!0},"--force":(s)=>{s.force=!0}};function applyBooleanFlag(flag,inlineVal,state,locale){let setter=BOOL_FLAG_SETTERS[flag];if(setter===void 0)return;if(inlineVal!==void 0)return t(locale,`${flag} 不接受赋值参数`,`${flag} does not accept a value`);return setter(state),null}var STRING_FLAG_MAP={"-c":"configPath","--config":"configPath","--url":"url","--serve-dir":"serveDir","--bridge":"bridgeModule","--start":"startCommand","--out-dir":"outDir","--html":"htmlReportPath","--chrome-path":"chromePath"},NUM_FLAG_SPECS={"--min-perf":{field:"minPerf",min:0,max:100},"--min-a11y":{field:"minA11y",min:0,max:100},"--min-bp":{field:"minBp",min:0,max:100},"--min-seo":{field:"minSeo",min:0,max:100},"--max-long-tasks":{field:"maxLongTasks",min:0,max:1000,transform:(n)=>Math.round(n)},"--cpu-slowdown":{field:"cpuSlowdown",min:0.5,max:20},"--timeout":{field:"timeoutMs",min:1,max:600,transform:(n)=>Math.round(n*1000)},"--keep":{field:"keep",min:0,max:1000,transform:(n)=>Math.round(n)}};function applyValueFlag(options){let{flag,inlineVal,argv,idxRef,state,locale}=options,take=()=>{if(inlineVal!==void 0)return inlineVal.trim()!==""?inlineVal:null;let next=argv[idxRef.i+1];if(next===void 0||next===""||next.startsWith("-"))return null;return idxRef.i+=1,next},missing=()=>t(locale,`选项 ${flag} 缺少参数值`,`Option ${flag} requires a value`);if(flag==="--path"){let val=take();if(val===null)return missing();return state.paths.push(val),null}let strField=STRING_FLAG_MAP[flag];if(strField!==void 0){let val=take();if(val===null)return missing();return state[strField]=val,null}let numSpec=NUM_FLAG_SPECS[flag];if(numSpec!==void 0){let val=take();if(val===null)return missing();let num=parseBoundedNum(val,flag,numSpec.min,numSpec.max,locale);if(typeof num==="string")return num;return state[numSpec.field]=numSpec.transform?numSpec.transform(num):num,null}if(flag==="--preset"){let val=take();if(val===null)return missing();let parsedPreset=parsePresetValue(val,locale);if(parsedPreset!=="quick"&&parsedPreset!=="ci"&&parsedPreset!=="full")return parsedPreset;return state.preset=parsedPreset,null}if(flag==="--device"){let val=take();if(val===null)return missing();let parsedDev=parseDeviceValue(val,locale);if(typeof parsedDev==="string")return parsedDev;return state.devices=parsedDev,null}if(flag==="--only"||flag==="--skip"){let val=take();if(val===null)return missing();let list=parseProbeList(val,flag,locale);if(typeof list==="string")return list;if(flag==="--only")state.only=list;else state.skip=list;return null}return}function parseArgs(argv,locale="zh"){let shared=extractSharedSubcommand(argv);if(shared!==null)return{ok:!0,options:{command:shared.command,version:!1,help:!1,json:shared.json,yes:!1,force:!1,passthroughArgs:shared.rest}};let state={command:"audit",commandExplicit:!1,version:!1,help:!1,json:!1,paths:[],yes:!1,force:!1},afterDash=!1,idxRef={i:0};for(;idxRef.i<argv.length;idxRef.i+=1){let rawTok=argv[idxRef.i];if(!afterDash&&rawTok==="--"){afterDash=!0;continue}if(!afterDash&&rawTok.startsWith("-")){let{flag,inlineVal}=splitFlagEquals(rawTok);if(flag==="--locale")return{ok:!1,message:t(locale,"不支持 --locale, 请使用唯一标准参数 --lang <system|en|zh>","--locale is not supported; use --lang <system|en|zh>")};let boolRes=applyBooleanFlag(flag,inlineVal,state,locale);if(boolRes===null)continue;if(boolRes!==void 0)return{ok:!1,message:boolRes};let valRes=applyValueFlag({flag,inlineVal,argv,idxRef,state,locale});if(valRes===null)continue;if(valRes!==void 0)return{ok:!1,message:valRes};return{ok:!1,message:t(locale,`未知选项: ${rawTok}`,`Unknown option: ${rawTok}`)}}if(!afterDash&&!state.commandExplicit&&state.url===void 0&&(rawTok==="audit"||rawTok==="doctor"||rawTok==="init"||rawTok==="baseline")){state.command=rawTok,state.commandExplicit=!0;continue}if(state.command==="baseline"){if(state.baselineAction===void 0){if(rawTok==="list"||rawTok==="diff"||rawTok==="prune"){state.baselineAction=rawTok;continue}return{ok:!1,message:t(locale,`baseline 子命令无效: ${rawTok} (仅支持 list | diff | prune)`,`Invalid baseline action: ${rawTok} (expected list | diff | prune)`)}}if(state.baselineTarget===void 0){state.baselineTarget=rawTok;continue}}if(state.command==="audit"&&state.url===void 0&&/^https?:\/\//i.test(rawTok)){state.url=rawTok;continue}return{ok:!1,message:t(locale,`未知位置参数: ${rawTok}`,`Unexpected argument: ${rawTok}`)}}let{commandExplicit:_unused,paths,...rest}=state;return{ok:!0,options:{...rest,...paths.length>0?{paths}:{}}}}function emitErr(opts,code,message){if(opts.json)opts.err(JSON.stringify({ok:!1,error:{code,message}}));else opts.err(opts.color?`${paintSgr("✗","1;31",!0)} ${message}`:message);return 1}function paintPassedFlag(passed,color){if(passed===!0)return paintSgr("PASS","1;32",color);if(passed===!1)return paintSgr("FAIL","1;31",color);return"-"}function paintDeltaTag(direction,color){if(direction==="improved")return paintSgr("▲","1;32",color);if(direction==="regressed")return paintSgr("▼","1;31",color);return paintSgr("=","2",color)}function runBaselineCommand(opts){let action=opts.action??"list",{locale,json,color,out}=opts,cacheOpts={cacheDir:opts.cacheDir,locale};if(action==="list"){let hosts=listBaselineHosts({cacheDir:opts.cacheDir});if(json)return out(JSON.stringify({ok:!0,hosts},null,2)),0;if(hosts.length===0)return out(t(locale,"暂无已保存的基线记录 (运行审计时附加 --save-baseline 自动存档)。","No saved baselines yet (pass --save-baseline when running an audit).")),0;let lines=[paintSgr("rim baseline list","1;36",color)];for(let h of hosts){let st=paintPassedFlag(h.latestPassed,color);lines.push(` ${h.host.padEnd(28)} ${String(h.entries).padStart(3)} ${t(locale,"条","runs")} ${st} ${h.latestTimestamp??"-"}`)}return out(lines.join(`
|
|
156
|
+
`)),0}if(action==="diff"){let target=opts.target??listBaselineHosts({cacheDir:opts.cacheDir})[0]?.host;if(target===void 0)return emitErr(opts,"BASELINE_NOT_FOUND",t(locale,"未指定域名且当前无已保存基线记录","No host specified and no saved baselines found"));let history=loadBaselineHistory(target,cacheOpts);if(history.length<2)return emitErr(opts,"BASELINE_INSUFFICIENT",t(locale,`域名 ${target} 仅有 ${history.length} 条基线, 至少需要 2 条才可对比`,`Host ${target} has only ${history.length} baseline entry; need at least 2 to diff`));let previous=history[history.length-2],current=history[history.length-1],diff=computeBaselineDiff(previous,current);if(json)return out(JSON.stringify({ok:!0,diff},null,2)),0;let lines=[paintSgr(`rim baseline diff (${diff.host})`,"1;36",color),` ${diff.previousTimestamp} -> ${diff.currentTimestamp}`];for(let d of diff.deltas){let sign=d.delta!==null&&d.delta>0?`+${d.delta}`:String(d.delta??"-"),tag=paintDeltaTag(d.direction,color);lines.push(` ${tag} ${d.metric.padEnd(24)} ${String(d.before??"-")}${d.unit} -> ${String(d.after??"-")}${d.unit} (${sign}${d.delta!==null?d.unit:""})`)}return out(lines.join(`
|
|
157
|
+
`)),0}let target=opts.target,keep=opts.keep??10;if(target===void 0){let results=listBaselineHosts({cacheDir:opts.cacheDir}).map((h)=>pruneBaselineHistory(h.host,keep,cacheOpts));if(json)return out(JSON.stringify({ok:!0,keep,results},null,2)),0;return out(t(locale,`✓ 已裁剪 ${results.length} 个域名的基线历史 (保留最新 ${keep} 条)`,`✓ Pruned ${results.length} host baseline histories (kept latest ${keep})`)),0}let pruned=pruneBaselineHistory(target,keep,cacheOpts);if(json)return out(JSON.stringify({ok:!0,keep,result:pruned},null,2)),0;return out(t(locale,`✓ ${pruned.host}: 基线记录 ${pruned.before} -> ${pruned.after} 条`,`✓ ${pruned.host}: baseline entries ${pruned.before} -> ${pruned.after}`)),0}async function runWithRimInterrupt(onInterruptStart,task){let controller=new AbortController,interruptedOnce=!1,onSigInt=()=>{if(interruptedOnce)process.exit(130);interruptedOnce=!0,onInterruptStart(),controller.abort()},onSigTerm=()=>{if(interruptedOnce)process.exit(143);interruptedOnce=!0,onInterruptStart(),controller.abort()};process.on("SIGINT",onSigInt),process.on("SIGTERM",onSigTerm);try{return await task(controller.signal)}finally{process.off("SIGINT",onSigInt),process.off("SIGTERM",onSigTerm)}}var CATALOG_ZH={subtitle:"全链路黑盒站点体检与上线门禁",summary:"内置 Lighthouse/axe-core + 协议/H3/TLS + CSP3 + 冒烟/全链扫描 + H2 压测。",sections:{usage:"用法",subcommands:"子命令",options:"选项",examples:"示例",notes:"使用须知",exitCodes:"退出码",docs:"文档与源码"},usageArgs:["[url] [选项]","<子命令> [选项]"],subcommands:[{name:"audit [url]",desc:"运行五大探针站点体检与门禁 (默认命令)"},{name:"doctor",desc:"只读探测运行时、Lighthouse、Chrome 与外部适配器"},{name:"init",desc:"生成极简 .rim.json (--yes / --force)"},{name:"baseline",desc:"管理域名历史水位线 (list | diff | prune)"},{name:"lang",desc:"查看或保存显示语言 (system | en | zh)"},{name:"update",desc:"自动识别安装器升级到最新版 (--check 仅检查)"},{name:"uninstall",desc:"彻底卸载 CLI 与配置 (--dry-run / --keep-config)"}],options:[{flag:"-c, --config",arg:"<path>",desc:"指定配置文件路径"},{flag:"--url",arg:"<url>",desc:"审计目标 URL (仅支持 http/https)"},{flag:"--local",desc:"强制启动本地桥接服务 (跳过 config.baseUrl)"},{flag:"--path",arg:"<route>",desc:"待测子路径 (可重复传入多次)"},{flag:"--serve-dir",arg:"<dir>",desc:"内置静态服务桥接指定目录"},{flag:"--bridge",arg:"<file>",desc:"进程内模块桥接文件"},{flag:"--start",arg:"<cmd>",desc:"外部启动命令桥接 (自动注入 PORT)"},{flag:"--preset",arg:"<mode>",desc:"探针档位: quick | ci | full"},{flag:"--device",arg:"<mode>",desc:"设备档位: mobile | desktop | both"},{flag:"--only",arg:"<list>",desc:"仅跑指定探针 (proto,sec,perf,quality,load)"},{flag:"--skip",arg:"<list>",desc:"跳过指定探针 (显式标记 disabled)"},{flag:"--strict",desc:"CI 严格门禁 (超标、意外 SKIP 或零检查退 1)"},{flag:"--min-perf",arg:"<0-100>",desc:"性能最低分覆盖"},{flag:"--min-a11y",arg:"<0-100>",desc:"无障碍最低分覆盖"},{flag:"--min-bp",arg:"<0-100>",desc:"最佳实践最低分覆盖"},{flag:"--min-seo",arg:"<0-100>",desc:"SEO 最低分覆盖"},{flag:"--max-long-tasks",arg:"<n>",desc:"主线程长任务 (>50ms) 上限"},{flag:"--cpu-slowdown",arg:"<n>",desc:"CPU 节流倍率覆盖 (0.5-20)"},{flag:"--cold-gpu",desc:"禁用 GPU 着色器磁盘缓存 (冷启动基线)"},{flag:"--out-dir",arg:"<dir>",desc:"Lighthouse 报告目录 (默认 dist/lighthouse)"},{flag:"--no-report",desc:"跳过 Lighthouse HTML/JSON 写盘"},{flag:"--html",arg:"<path>",desc:"输出自包含单文件 HTML 摘要报告"},{flag:"--save-baseline",desc:"存档本次指标到 ~/.cache/rim"},{flag:"--diff",desc:"与该域名上一次基线对比输出 delta"},{flag:"--allow-load",desc:"允许对非回环公网目标执行受控短时压测"},{flag:"--keep",arg:"<n>",desc:"baseline prune 保留最新记录数"},{flag:"--chrome-path",arg:"<path>",desc:"显式指定 Chrome 绝对路径"},{flag:"--timeout",arg:"<sec>",desc:"单阶段超时秒数 (1-600)"},{flag:"-y, --yes",desc:"非交互确认 (init / uninstall)"},{flag:"--force",desc:"覆盖已有配置文件 (init)"},{flag:"--json",desc:"输出确定性 JSON 信封 (适配脚本与 AI)"},{flag:"--lang",arg:"<lang>",desc:"单次覆盖输出语言 (system | en | zh)"},{flag:"-V, --version",desc:"输出版本号"},{flag:"-h, --help",desc:"显示本帮助"}],examples:[{cmd:"rim",desc:"自动发现 .rim.json 或静态目录跑 ci 门禁"},{cmd:"rim",tail:[["flag","--preset"],["arg","ci"],["flag","--strict"]],desc:"CI 严格门禁 (proto + sec + perf)"},{cmd:"rim",tail:[["arg","https://example.com"],["flag","--preset"],["arg","quick"]],desc:"零浏览器极速体检协议、压缩与安全头"},{cmd:"rim",tail:[["flag","--only"],["arg","quality"],["flag","--strict"]],desc:"仅跑 CDP 冒烟、死链与页内锚点检查"},{cmd:"rim",tail:[["arg","doctor"],["flag","--json"]],desc:"JSON 只读探测运行时、Chrome 与 5 类适配器"}],notes:[{label:"零前置",desc:"内置 Lighthouse/axe-core/TLS/H2 压测/链接扫描, 装即能用。"},{label:"压测护栏",desc:"公网压测须带 --allow-load 且硬编码并发/时长上限。"},{label:"防假绿",desc:"--strict 将缺失得分、意外 SKIP 或零检查均判失败。"}],exitCodes:[{label:"0",tone:"green",desc:"门禁通过或查询成功"},{label:"1",tone:"red",desc:"参数非法、运行故障或 --strict 门禁未通过"},{label:"130",tone:"amber",desc:"Ctrl+C (SIGINT) 中断并已清理子进程"}]},CATALOG_EN={subtitle:"Full-Stack Website Audit & Release Gate",summary:"Bundled Lighthouse/axe-core + proto/H3/TLS + CSP3 + links + H2 load.",sections:{usage:"Usage",subcommands:"Commands",options:"Options",examples:"Examples",notes:"Notes",exitCodes:"Exit Codes",docs:"Docs & Source"},usageArgs:["[url] [options]","<command> [options]"],subcommands:[{name:"audit [url]",desc:"Run 5-probe website audit & gate (default)"},{name:"doctor",desc:"Inspect runtime, Lighthouse, Chrome & adapters"},{name:"init",desc:"Create starter .rim.json (--yes / --force)"},{name:"baseline",desc:"Manage host baselines (list | diff | prune)"},{name:"lang",desc:"Show or save display language (system | en | zh)"},{name:"update",desc:"Upgrade via detected installer (--check only)"},{name:"uninstall",desc:"Remove CLI and config (--dry-run / --keep-config)"}],options:[{flag:"-c, --config",arg:"<path>",desc:"Path to rim config"},{flag:"--url",arg:"<url>",desc:"Target URL to audit (http/https)"},{flag:"--local",desc:"Force local bridge launch (skip baseUrl)"},{flag:"--path",arg:"<route>",desc:"Route path to audit (repeatable)"},{flag:"--serve-dir",arg:"<dir>",desc:"Serve dir via static bridge"},{flag:"--bridge",arg:"<file>",desc:"In-process module bridge file"},{flag:"--start",arg:"<cmd>",desc:"Command bridge (injects PORT)"},{flag:"--preset",arg:"<mode>",desc:"Probe preset: quick | ci | full"},{flag:"--device",arg:"<mode>",desc:"Device profile: mobile | desktop | both"},{flag:"--only",arg:"<list>",desc:"Run only probes (proto,sec,perf,quality,load)"},{flag:"--skip",arg:"<list>",desc:"Disable selected probes"},{flag:"--strict",desc:"CI strict gate (fail on thresholds / SKIP)"},{flag:"--min-perf",arg:"<0-100>",desc:"Min performance score"},{flag:"--min-a11y",arg:"<0-100>",desc:"Min accessibility score"},{flag:"--min-bp",arg:"<0-100>",desc:"Min best-practices score"},{flag:"--min-seo",arg:"<0-100>",desc:"Min SEO score"},{flag:"--max-long-tasks",arg:"<n>",desc:"Max main-thread long tasks (>50ms)"},{flag:"--cpu-slowdown",arg:"<n>",desc:"CPU slowdown (0.5-20)"},{flag:"--cold-gpu",desc:"Disable GPU shader disk cache"},{flag:"--out-dir",arg:"<dir>",desc:"Lighthouse report output dir"},{flag:"--no-report",desc:"Skip writing Lighthouse HTML/JSON files"},{flag:"--html",arg:"<path>",desc:"Write self-contained HTML summary"},{flag:"--save-baseline",desc:"Save metrics to ~/.cache/rim"},{flag:"--diff",desc:"Diff against previous host baseline"},{flag:"--allow-load",desc:"Allow bounded load probe on public host"},{flag:"--keep",arg:"<n>",desc:"Entries to keep on baseline prune"},{flag:"--chrome-path",arg:"<path>",desc:"Explicit Chrome binary"},{flag:"--timeout",arg:"<sec>",desc:"Per-stage timeout (1-600s)"},{flag:"-y, --yes",desc:"Non-interactive confirm (init / uninstall)"},{flag:"--force",desc:"Overwrite existing config file (init)"},{flag:"--json",desc:"Emit deterministic JSON envelope"},{flag:"--lang",arg:"<lang>",desc:"Override output language (system | en | zh)"},{flag:"-V, --version",desc:"Print version"},{flag:"-h, --help",desc:"Show this help"}],examples:[{cmd:"rim",desc:"Auto-detect .rim.json or static dir"},{cmd:"rim",tail:[["flag","--preset"],["arg","ci"],["flag","--strict"]],desc:"CI strict gate (proto + sec + perf)"},{cmd:"rim",tail:[["arg","https://example.com"],["flag","--preset"],["arg","quick"]],desc:"Zero-browser fast proto + sec audit"},{cmd:"rim",tail:[["flag","--only"],["arg","quality"],["flag","--strict"]],desc:"Run CDP smoke, dead-link & anchor checks only"},{cmd:"rim",tail:[["arg","doctor"],["flag","--json"]],desc:"Read-only JSON check for runtime & adapters"}],notes:[{label:"Bundled",desc:"Ships Lighthouse, axe-core, native TLS, H2 load & link scan."},{label:"Load guard",desc:"Public load requires --allow-load with hardcoded caps."},{label:"Strict",desc:"--strict fails on missing scores, SKIP, or zero checks."}],exitCodes:[{label:"0",tone:"green",desc:"Gate passed or query succeeded"},{label:"1",tone:"red",desc:"Invalid args, runtime error, or strict failure"},{label:"130",tone:"amber",desc:"Cancelled via Ctrl+C (SIGINT)"}]};var GITHUB_URL="https://github.com/iyowei/clis/tree/main/packages/rim-cli",MAX_LINE_COLS=80,LINE_INDENT=" ";function paint(text,code,color){return paintSgr(text,code,color)}function examplePlainParts(item){return[item.cmd,...(item.tail??[]).map(([,val])=>val)]}function computeDescColumn(cat){return computeHelpDescColumn([...cat.subcommands.map((s)=>s.name),...cat.options.map((o)=>o.arg!==void 0?`${o.flag} ${o.arg}`:o.flag),...cat.examples.map((ex)=>examplePlainParts(ex).join(" ")),...cat.notes.map((n)=>n.label),...cat.exitCodes.map((e)=>e.label)])}function formatWrappedRow(styledLeft,plainLeft,desc,descCol,maxRightCols,paintDesc){let wrapped=wrapDisplay(desc,maxRightCols),first=alignHelpRow(styledLeft,plainLeft,paintDesc(wrapped[0]??""),descCol,LINE_INDENT);if(wrapped.length<=1)return[first];let contIndent=" ".repeat(LINE_INDENT.length+descCol);return[first,...wrapped.slice(1).map((ln)=>`${contIndent}${paintDesc(ln)}`)]}function renderExampleLines(item,color,descCol,maxRightCols,dim){let plain=examplePlainParts(item).join(" "),parts=[paint(item.cmd,"1",color)];for(let[kind,val]of item.tail??[])parts.push(paint(val,kind==="arg"?"36":"2",color));return formatWrappedRow(parts.join(" "),plain,item.desc,descCol,maxRightCols,dim)}function helpText(version,color,locale="zh"){let c=locale==="zh"?CATALOG_ZH:CATALOG_EN,s=createHelpStyles(color),descCol=computeDescColumn(c),maxRightCols=Math.max(24,MAX_LINE_COLS-LINE_INDENT.length-descCol),heading=(title)=>` ${s.section(title)}`,lines=[""],badge=s.badge(`${HELP_BAR_BLOCK} RIM `);lines.push(` ${badge} ${s.bold(c.subtitle)} ${s.dim(`v${version}`)}`);for(let summaryLine of wrapDisplay(c.summary,MAX_LINE_COLS-2))lines.push(` ${s.dim(summaryLine)}`);lines.push(` ${s.dim(HELP_RULE)}`),lines.push(""),lines.push(heading(c.sections.usage));for(let u of c.usageArgs)lines.push(` ${s.bold("rim")} ${s.dim(u)}`);lines.push(""),lines.push(heading(c.sections.subcommands));for(let item of c.subcommands)lines.push(...formatWrappedRow(s.token(item.name),item.name,item.desc,descCol,maxRightCols,s.dim));lines.push(""),lines.push(heading(c.sections.options));for(let item of c.options){let plainLeft=item.arg!==void 0?`${item.flag} ${item.arg}`:item.flag,flagStyled=s.token(item.flag),styledLeft=item.arg!==void 0?`${flagStyled} ${s.dim(item.arg)}`:flagStyled;lines.push(...formatWrappedRow(styledLeft,plainLeft,item.desc,descCol,maxRightCols,s.dim))}lines.push(""),lines.push(heading(c.sections.examples));for(let item of c.examples)lines.push(...renderExampleLines(item,color,descCol,maxRightCols,s.dim));lines.push(""),lines.push(heading(c.sections.notes));for(let item of c.notes)lines.push(...formatWrappedRow(paint(item.label,"33",color),item.label,item.desc,descCol,maxRightCols,s.dim));lines.push(""),lines.push(heading(c.sections.exitCodes));for(let item of c.exitCodes){let styledCode=s.red(item.label);if(item.tone==="green")styledCode=s.green(item.label);else if(item.tone==="amber")styledCode=paint(item.label,"1;33",color);lines.push(...formatWrappedRow(styledCode,item.label,item.desc,descCol,maxRightCols,s.dim))}lines.push("");let docsUrl=locale==="zh"?"https://github.com/iyowei/clis/blob/main/packages/rim-cli/README.zh-CN.md":"https://github.com/iyowei/clis/blob/main/packages/rim-cli/README.md";return lines.push(heading(c.sections.docs)),lines.push(` ${s.token(GITHUB_URL)}`),lines.push(` ${s.token(docsUrl)}`),lines.push(""),lines.join(`
|
|
158
|
+
`)}import{existsSync as existsSync22,mkdirSync as mkdirSync6,writeFileSync as writeFileSync6}from"node:fs";import{basename,dirname as dirname10,join as join17,relative as relative2,resolve as resolve13}from"node:path";function buildStarterConfig(options){let{cwd}=options,siteName=basename(resolve13(cwd))||"site",defaultBudgets={lighthouse:{minPerf:DEFAULT_THRESHOLDS.performance,minA11y:DEFAULT_THRESHOLDS.accessibility,minBp:DEFAULT_THRESHOLDS.bestPractices,minSeo:DEFAULT_THRESHOLDS.seo,maxLongTasks:DEFAULT_THRESHOLDS.maxLongTasks}};if(options.url!==void 0)return{schemaVersion:1,name:siteName,baseUrl:options.url,routes:["/"],devices:["mobile","desktop"],budgets:defaultBudgets,outDir:"dist/lighthouse"};if(options.bridgeModule!==void 0)return{schemaVersion:1,name:siteName,routes:["/"],bridge:{type:"module",entry:options.bridgeModule},devices:["mobile","desktop"],budgets:defaultBudgets,outDir:"dist/lighthouse"};if(options.startCommand!==void 0)return{schemaVersion:1,name:siteName,routes:["/"],bridge:{type:"command",command:options.startCommand},devices:["mobile","desktop"],budgets:defaultBudgets,outDir:"dist/lighthouse"};let detectedDir=options.serveDir!==void 0?options.serveDir:(()=>{let found=detectDefaultStaticDir(cwd);return found!==null?relative2(cwd,found).replaceAll("\\","/")||".":void 0})();return{schemaVersion:1,name:siteName,routes:["/"],bridge:detectedDir!==void 0?{type:"static",dir:detectedDir}:{type:"auto"},devices:["mobile","desktop"],budgets:defaultBudgets,outDir:"dist/lighthouse"}}async function runInitCommand(options){let{cwd,locale,json,out,err}=options,targetPath=options.configPath!==void 0?resolve13(cwd,options.configPath):join17(cwd,".rim.json"),existed=existsSync22(targetPath),emitErr=(code,message)=>{if(json)err(JSON.stringify({ok:!1,error:{code,message}}));else err(message);return 1};if(existed&&!options.force)return emitErr("CONFIG_EXISTS",t(locale,`配置文件已存在: ${targetPath} (如需覆盖请附加 --force)`,`Config file already exists: ${targetPath} (pass --force to overwrite)`));if(!options.yes){if(json||!options.interactive)return emitErr("CONFIRMATION_REQUIRED",t(locale,"非交互或 --json 模式下运行 init 须显式传入 --yes 确认写盘","Pass --yes to confirm writing config in non-interactive or --json mode"));if(await promptConfirmOnce(t(locale,`确认写入起步配置文件 ${targetPath}? [y/N]: `,`Write starter config to ${targetPath}? [y/N]: `))!=="yes")return out(t(locale,"已取消初始化, 未写入任何文件。","Cancelled; no files written.")),0}let starter=buildStarterConfig(options);if(mkdirSync6(dirname10(targetPath),{recursive:!0}),writeFileSync6(targetPath,`${JSON.stringify(starter,null,2)}
|
|
159
|
+
`,"utf8"),json)return out(JSON.stringify({ok:!0,configPath:targetPath,created:!existed,overwritten:existed,config:starter},null,2)),0;return out(t(locale,`✓ 已生成配置文件: ${targetPath}`,`✓ Wrote starter config: ${targetPath}`)),0}function p(text,code,color){return paintSgr(text,code,color)}function renderBuiltinLine(label,cap,color){return` ${cap.available?p("✓","1;32",color):p("✗","1;31",color)} ${label.padEnd(10)} ${cap.engine} — ${cap.detail}`}function renderAdapterLine(adapter,locale,color){if(adapter.available){let ver=adapter.version!==null?` (${adapter.version})`:"";return` ${p("✓","1;32",color)} ${adapter.name.padEnd(10)} ${adapter.path}${ver}`}let covered=adapter.builtinFallback?t(locale,`未安装 (已有${adapter.builtinFallback}, 无需手动安装)`,`not installed (covered by ${adapter.builtinFallback})`):t(locale,"未安装 (可选)","missing (optional)");return` ${p("○","2",color)} ${adapter.name.padEnd(10)} ${covered} -> ${adapter.installHint}`}function renderDoctorReport(doctor,options){if(options.json)return JSON.stringify({ok:!0,doctor},null,2);let{color,locale}=options,ok=(yes)=>yes?p("✓","1;32",color):p("✗","1;31",color),chromeDetail=doctor.chrome.available?`${doctor.chrome.path}${doctor.chrome.version?` (${doctor.chrome.version})`:""} [${doctor.chrome.source}]`:`${t(locale,"未检测到 Chrome / Chromium / Edge","Chrome / Chromium / Edge not found")}${doctor.chrome.installHint?` -> ${doctor.chrome.installHint}`:""}`;return[p("rim doctor","1;36",color),` ${ok(!0)} ${t(locale,"运行时","Runtime")}: ${doctor.runtime.name} ${doctor.runtime.version} (${doctor.runtime.platform}/${doctor.runtime.arch})`,` ${ok(doctor.lighthouse.available)} Lighthouse: ${doctor.lighthouse.available?`${doctor.lighthouse.version??"ok"} (${doctor.lighthouse.resolvedPath??""})`:doctor.lighthouse.error??"missing"}`,` ${ok(doctor.axeCore.available)} axe-core: ${doctor.axeCore.available?`${doctor.axeCore.version??"ok"} (${doctor.axeCore.resolvedPath??""})`:doctor.axeCore.error??"missing"}`,` ${ok(doctor.chrome.available)} Chrome: ${chromeDetail}`,` ${ok(doctor.config.valid)} ${t(locale,"配置","Config")}: ${doctor.config.path??t(locale,"未配置 (走零配置默认模式)","none (zero-config defaults)")}${doctor.config.error!==void 0?` — ${doctor.config.error}`:""}`,` ${ok(doctor.defaultBridge.detected)} ${t(locale,"默认桥接","Bridge")}: ${doctor.defaultBridge.mode} (${doctor.defaultBridge.detail})`,"",p(t(locale,"开箱即用内置引擎 (零额外安装):","Built-in / bundled engines (zero extra install):"),"1;36",color),renderBuiltinLine("tls",doctor.builtins.tls,color),renderBuiltinLine("load",doctor.builtins.load,color),renderBuiltinLine("links",doctor.builtins.links,color),renderBuiltinLine("axe",doctor.builtins.axe,color),"",p(t(locale,"可选外部工具覆盖 (均已内置等价引擎, 按需覆盖):","Optional external overrides (already covered by built-ins):"),"1;36",color),renderAdapterLine(doctor.adapters.testssl,locale,color),renderAdapterLine(doctor.adapters.h2load,locale,color),renderAdapterLine(doctor.adapters.oha,locale,color),renderAdapterLine(doctor.adapters.lychee,locale,color),renderAdapterLine(doctor.adapters.axe,locale,color)].join(`
|
|
160
|
+
`)}function formatFindingTag(waived,score,locale){if(waived===!0)return"WAIVED";if(score===null)return t(locale,"提示","info");return String(Math.round(score*100))}function paintDeltaDirection(direction,color){if(direction==="improved")return p2("▲","1;32",color);if(direction==="regressed")return p2("▼","1;31",color);return p2("=","2",color)}function p2(text,code,color){return paintSgr(text,code,color)}function paintStatus(status,color){if(status==="PASS")return p2("PASS ","1;32",color);if(status==="WARN")return p2("WARN ","1;33",color);if(status==="FAIL")return p2("FAIL ","1;31",color);if(status==="WAIVED")return p2("WAIVED","1;36",color);return p2("SKIP ","2",color)}function statusMark(status,color){if(status==="PASS")return p2("✓","1;32",color);if(status==="WARN")return p2("!","1;33",color);if(status==="FAIL")return p2("✗","1;31",color);if(status==="WAIVED")return p2("~","1;36",color);return p2("○","2",color)}function formatScore(val,color){if(val===null||val===void 0)return p2("N/A","1;31",color);if(val>=90)return p2(String(val),"1;32",color);if(val>=50)return p2(String(val),"1;33",color);return p2(String(val),"1;31",color)}function renderProbeSummaryTable(probes,locale,color){if(probes.length===0)return[];let lines=["",p2(t(locale,"=== 探针总览 ===","=== Probe Overview ==="),"1;36",color)];for(let probe of probes){let failCnt=probe.findings.filter((f)=>f.status==="FAIL").length,warnCnt=probe.findings.filter((f)=>f.status==="WARN").length,waivedCnt=probe.findings.filter((f)=>f.status==="WAIVED").length,counts=`${failCnt} fail / ${warnCnt} warn${waivedCnt>0?` / ${waivedCnt} waived`:""}`;lines.push(` ${statusMark(probe.status,color)} ${probe.id.padEnd(8)} ${paintStatus(probe.status,color)} ${String(probe.durationMs).padStart(5)}ms (${counts})`)}return lines}function formatFindingLine(f,color){let w=f.waiverReason!==void 0?` [WAIVED: ${sanitizeCliText(f.waiverReason)}]`:"",detail=f.status!=="PASS"&&f.detail!==void 0&&f.detail.trim()!==""?` — ${sanitizeCliText(f.detail)}`:"";return` ${statusMark(f.status,color)} [${sanitizeCliText(f.id)}] ${sanitizeCliText(f.title)}${detail}${w}`}function renderProtoSection(probe,locale,color){let lines=["",p2(`=== PROTO [${probe.status}] (${probe.durationMs}ms) ===`,"1;36",color)],m=probe.metrics,brB=m.htmlBrBytes??"-",gzB=m.htmlGzipBytes??"-",rawB=m.htmlRawBytes??"-",critB=m.totalCriticalBrBytes??0;lines.push(locale==="en"?` Encodings: br=${String(brB)}B | gzip=${String(gzB)}B | raw=${String(rawB)}B | critical=${String(critB)}B | TTFB=${String(m.ttfbMs??"-")}ms`:` 压缩体积: br=${String(brB)}B | gzip=${String(gzB)}B | raw=${String(rawB)}B | 关键预加载=${String(critB)}B | TTFB=${String(m.ttfbMs??"-")}ms`);let h2h3=probe.evidence.h2h3;if(h2h3!==void 0&&typeof h2h3.reason==="string")lines.push(` H2/H3: [${h2h3.status??"SKIP"}] ${sanitizeCliText(h2h3.reason)}`);for(let f of probe.findings){if(f.status==="PASS")continue;lines.push(formatFindingLine(f,color))}return lines}function renderSecSection(probe,locale,color){let lines=["",p2(`=== SEC [${probe.status}] (${probe.durationMs}ms) ===`,"1;36",color)],interesting=probe.findings.filter((f)=>f.status!=="PASS"),tlsPass=probe.findings.find((f)=>f.id==="sec:tls"&&f.status==="PASS");if(interesting.length===0)lines.push(` ${p2("✓","1;32",color)} ${t(locale,"全部安全响应头与 CSP3 规则通过","All security headers and CSP3 checks passed")}`);else for(let f of interesting)lines.push(formatFindingLine(f,color));if(tlsPass!==void 0)lines.push(` ${p2("✓","1;32",color)} [sec:tls] ${sanitizeCliText(tlsPass.title)}`);let tlsEv=probe.evidence.tls;if(tlsEv!==void 0&&tlsEv.status==="SKIP"&&tlsEv.reason)lines.push(p2(` ○ TLS: ${sanitizeCliText(tlsEv.reason)}`,"2",color));let testssl=probe.evidence.testssl;if(testssl!==void 0&&testssl.status==="SKIP"&&testssl.reason)lines.push(p2(` ○ testssl.sh: ${sanitizeCliText(testssl.reason)}`,"2",color));return lines}function renderLighthouseSection(summary,locale,color){let lines=[],routeTag=summary.route!==void 0&&summary.route!=="/"?` ${summary.route}`:"",label=`${summary.preset.toUpperCase()}${routeTag}`;if(lines.push("",p2(`=== Lighthouse (${label}) [${summary.elapsedMs}ms] ===`,"1;36",color)),summary.runtimeError!==void 0)lines.push(p2(`✗ ${t(locale,"运行期错误","Runtime Error")}: ${summary.runtimeError.message}`,"1;31",color));let sc=summary.scores;lines.push(locale==="en"?`Scores: Perf ${formatScore(sc.performance,color)} | A11y ${formatScore(sc.accessibility,color)} | BP ${formatScore(sc["best-practices"],color)} | SEO ${formatScore(sc.seo,color)}`:`评分: 性能 ${formatScore(sc.performance,color)} | 无障碍 ${formatScore(sc.accessibility,color)} | 最佳实践 ${formatScore(sc["best-practices"],color)} | SEO ${formatScore(sc.seo,color)}`);let m=summary.metrics;if(lines.push(locale==="en"?`Metrics: FCP ${m.fcp} | LCP ${m.lcp} | TBT ${m.tbt} | CLS ${m.cls} | SI ${m.si} | TTFB ${m.ttfb}`:`指标: FCP ${m.fcp} | LCP ${m.lcp} | TBT ${m.tbt} | CLS ${m.cls} | SI ${m.si} | TTFB ${m.ttfb}`),summary.longTasks.length===0)lines.push(p2(`✓ ${t(locale,"主线程长任务 (>50ms): 0 项","Main-thread long tasks (>50ms): 0")}`,"32",color));else{lines.push(p2(`! ${t(locale,`主线程长任务 (>50ms): ${summary.longTasks.length} 项`,`Main-thread long tasks (>50ms): ${summary.longTasks.length}`)}`,"33",color));for(let task of summary.longTasks)lines.push(` - ${task.durationMs}ms @ ${task.startMs}ms | ${task.url}`)}if(summary.mainThreadTop.length>0){let breakdown=summary.mainThreadTop.map((item)=>`${item.groupLabel} ${item.durationMs}ms`).join(" / ");lines.push(`${t(locale,"主线程耗时拆解","Main-thread breakdown")}: ${breakdown}`)}if(summary.bootupTop.length>0){let boot=summary.bootupTop.map((b)=>`${b.url.replace(/^https?:\/\/[^/]+/,"")||b.url} ${b.totalMs}ms (JS ${b.scriptingMs}ms)`).join(" | ");lines.push(`${t(locale,"脚本启动耗时","Script bootup")}: ${boot}`)}if(summary.findings.length===0)lines.push(p2(`✓ ${t(locale,"扣分与警告项: 无","Findings: none")}`,"32",color));else{lines.push(`${t(locale,`扣分与警告项 (${summary.findings.length})`,`Findings (${summary.findings.length})`)}:`);for(let f of summary.findings.slice(0,12)){let tag=formatFindingTag(f.waived,f.score,locale),waiverTail=f.waived===!0&&f.waiverReason!==void 0?` — ${f.waiverReason}`:"";lines.push(` - [${tag}] ${f.id}: ${f.title}${f.displayValue!==""?` (${f.displayValue})`:""}${waiverTail}`)}if(summary.findings.length>12)lines.push(p2(` … ${t(locale,`其余 ${summary.findings.length-12} 项详见完整报告`,`and ${summary.findings.length-12} more in report`)}`,"2",color))}if(summary.htmlPath!==void 0||summary.jsonPath!==void 0){let paths=[summary.htmlPath,summary.jsonPath].filter((item)=>item!==void 0).join(" | ");lines.push(`${t(locale,"报告路径","Reports")}: ${paths}`)}return lines}function renderLoadSection(probe,color){let lines=["",p2(`=== LOAD [${probe.status}] (${probe.durationMs}ms) ===`,"1;36",color)];for(let f of probe.findings){let waiver=f.waiverReason!==void 0?` [WAIVED: ${sanitizeCliText(f.waiverReason)}]`:"",detail=f.status!=="PASS"&&f.detail!==void 0&&f.detail.trim()!==""?` — ${sanitizeCliText(f.detail)}`:"";lines.push(` ${statusMark(f.status,color)} ${sanitizeCliText(f.title)}${detail}${waiver}`)}return lines}function renderBaselineDiffSection(diff,locale,color){let lines=["",p2(`=== ${t(locale,"基线对比 Delta","Baseline Diff Delta")} (${diff.host}) ===`,"1;36",color),` ${diff.previousTimestamp??t(locale,"(首次基线)","(first baseline)")} -> ${diff.currentTimestamp}`];for(let d of diff.deltas){let sign=d.delta!==null&&d.delta>0?`+${d.delta}`:String(d.delta??"-"),tag=paintDeltaDirection(d.direction,color);lines.push(` ${tag} ${d.metric.padEnd(24)} ${String(d.before??"-")}${d.unit} -> ${String(d.after??"-")}${d.unit} (${sign}${d.delta!==null?d.unit:""})`)}return lines}function renderGateReport(report,options){if(options.json){let envelope=report.passed?{ok:!0,report}:{ok:!1,code:"GATE_FAILED",report};return JSON.stringify(envelope,null,2)}let{color,locale}=options,lines=[`${p2("rim","1;36",color)} ${report.targetUrl} (preset=${report.preset} · ${report.bridge.mode} · ${report.runtime.name} ${report.runtime.version} · ${report.elapsedMs}ms)`];lines.push(...renderProbeSummaryTable(report.probes,locale,color));let protoProbe=report.probes.find((pr)=>pr.id==="proto");if(protoProbe!==void 0)lines.push(...renderProtoSection(protoProbe,locale,color));let secProbe=report.probes.find((pr)=>pr.id==="sec");if(secProbe!==void 0)lines.push(...renderSecSection(secProbe,locale,color));for(let summary of report.lighthouse.summaries)lines.push(...renderLighthouseSection(summary,locale,color));let qualityProbe=report.probes.find((pr)=>pr.id==="quality");if(report.smoke.status!=="disabled"){let sMark=p2("✗","1;31",color);if(report.smoke.status==="pass")sMark=p2("✓","1;32",color);else if(report.smoke.status==="skip")sMark=p2("○","2",color);let smokeTitle=report.smoke.mode==="command"?`${t(locale,"外部冒烟命令","External Smoke Command")} (${report.smoke.elapsedMs}ms)`:`${t(locale,"CDP 运行时冒烟","CDP Runtime Smoke")} (${report.smoke.steps.length} ${t(locale,"步","steps")}, ${report.smoke.elapsedMs}ms)`;lines.push("",`${sMark} ${smokeTitle}`);for(let step of report.smoke.steps){let icon=step.passed?"✓":"✗";lines.push(` ${icon} ${step.label} (${step.elapsedMs}ms)${step.error!==void 0?` — ${step.error}`:""}`)}if(report.smoke.reason!==void 0)lines.push(report.smoke.status==="skip"?p2(` ○ ${report.smoke.reason}`,"2",color):p2(` ✗ ${report.smoke.reason}`,"1;31",color))}if(qualityProbe!==void 0){let extraFindings=qualityProbe.findings.filter((f)=>f.id!=="quality:smoke");for(let f of extraFindings)lines.push(formatFindingLine(f,color))}let loadProbe=report.probes.find((pr)=>pr.id==="load");if(loadProbe!==void 0)lines.push(...renderLoadSection(loadProbe,color));if(report.baselineDiff!==void 0)lines.push(...renderBaselineDiffSection(report.baselineDiff,locale,color));if(report.baselineSavedPath!==void 0)lines.push(p2(`✓ ${t(locale,"基线已存档","Baseline saved")}: ${report.baselineSavedPath}`,"32",color));if(report.htmlReportPath!==void 0)lines.push(p2(`✓ ${t(locale,"HTML 摘要报告","HTML summary report")}: ${report.htmlReportPath}`,"32",color));if(report.verdict.waived.length>0)lines.push(p2(`~ ${t(locale,`已豁免 (${report.verdict.waived.length})`,`Waived (${report.verdict.waived.length})`)}: ${report.verdict.waived.map((w)=>w.message).join(" | ")}`,"36",color));if(report.verdict.disabled.length>0)lines.push(p2(`! ${t(locale,"已显式禁用","Explicitly disabled")}: ${report.verdict.disabled.map((d)=>d.id).join(", ")}`,"2",color));if(report.verdict.failures.length>0){let header=report.strict?p2(`✗ ${t(locale,"门禁未通过","Gate failed")} (${report.verdict.failures.length}):`,"1;31",color):p2(`! ${t(locale,`建议模式发现 ${report.verdict.failures.length} 项未达标 (未开启 --strict, 退出码 0; 传 --strict 阻断)`,`Advisory: ${report.verdict.failures.length} check failure(s) (non-strict, exit 0; pass --strict to fail)`)}:`,"1;33",color);lines.push("",header);for(let item of report.verdict.failures)lines.push(` - [${item.code??item.gate}] ${sanitizeCliText(item.message)}`)}else lines.push("",p2(`✓ ${t(locale,`门禁通过 (已执行 ${report.verdict.executedCount} 项检查)`,`Gate passed (${report.verdict.executedCount} checks executed)`)}`,"1;32",color));return lines.join(`
|
|
161
|
+
`)}var TOOL_NAME="rim",BIN_NAME="rim",DOCS_URL="https://github.com/iyowei/clis/tree/main/packages/rim-cli";function readPackageVersion(){try{let raw=readFileSync16(new URL("../package.json",import.meta.url),"utf8"),parsed=JSON.parse(raw);return typeof parsed.version==="string"?parsed.version:"0.0.0"}catch{return"0.0.0"}}function printErr(message,stderrColor,err,json,code){let clean=sanitizeCliText(message);if(json){err(JSON.stringify({ok:!1,error:{code,message:clean}}));return}err(stderrColor?`${paintSgr("✗","1;31",stderrColor)} ${clean}`:clean)}async function executeAuditFlow(input){let{opts,cwd,baselineCacheDir,locale,colors,out,stderrWrite,deps}=input,showProgress=!opts.json&&colors.stderr,wroteProgress=!1,clearProgressLine=()=>{if(!wroteProgress)return;stderrWrite("\r\x1B[2K"),wroteProgress=!1},report=await runWithRimInterrupt(clearProgressLine,(signal)=>runRim({cwd,configPath:opts.configPath,url:opts.url,local:opts.local,paths:opts.paths,serveDir:opts.serveDir,bridgeModule:opts.bridgeModule,startCommand:opts.startCommand,preset:opts.preset,devices:opts.devices,only:opts.only,skip:opts.skip,strict:opts.strict,minPerf:opts.minPerf,minA11y:opts.minA11y,minBp:opts.minBp,minSeo:opts.minSeo,maxLongTasks:opts.maxLongTasks,cpuSlowdown:opts.cpuSlowdown,coldGpu:opts.coldGpu,outDir:opts.outDir,writeReports:opts.writeReports,htmlReportPath:opts.htmlReportPath,saveBaseline:opts.saveBaseline,diffBaseline:opts.diffBaseline,baselineCacheDir,allowLoad:opts.allowLoad,chromePath:opts.chromePath,timeoutMs:opts.timeoutMs,locale,signal,onProgress:showProgress?(evt)=>{wroteProgress=!0,stderrWrite(`\r\x1B[2K${paintSgr("…","36",!0)} ${sanitizeCliText(evt.detail)}`)}:void 0},deps));return clearProgressLine(),out(renderGateReport(report,{color:colors.stdout,json:opts.json,locale})),report.passed?0:1}function resolveRimColorChannels(env=process.env,tty){let colorEnv=env.RIM_NO_COLOR!==void 0&&env.RIM_NO_COLOR!==""?{...env,NO_COLOR:env.RIM_NO_COLOR}:env;return detectColorChannels(colorEnv,tty)}async function runRimCli(rawArgv,hooks={}){let hasCustomIo=hooks.out!==void 0||hooks.err!==void 0,out=hooks.out??((line)=>process.stdout.write(`${line}
|
|
162
|
+
`)),err=hooks.err??((line)=>process.stderr.write(`${line}
|
|
163
|
+
`)),stderrWrite=hooks.stderrWrite??((chunk)=>process.stderr.write(chunk)),colors=hooks.colorChannels?.()??resolveRimColorChannels(),interactive=hooks.isInteractive??(()=>process.stdin.isTTY===!0&&process.stdout.isTTY===!0),version=hooks.version??readPackageVersion(),cwd=hooks.cwd??process.cwd(),scopedValueFlags=resolveRimValueFlags(rawArgv),wantJsonRaw=detectPreDashJson(rawArgv,scopedValueFlags),preLocale=resolveCliLocale({toolName:TOOL_NAME}),stripped=stripLangArgs(rawArgv,{fallbackLocale:preLocale.locale,systemLocale:preLocale.system.locale,valueFlags:scopedValueFlags});if(stripped.error!==void 0)return printErr(stripped.error,colors.stderr,err,wantJsonRaw,"INVALID_ARGUMENT"),1;let locale=resolveCliLocale({toolName:TOOL_NAME,flag:stripped.lang}).locale,parsed=parseArgs(stripped.argv,locale);if(!parsed.ok)return printErr(parsed.message,colors.stderr,err,wantJsonRaw,"INVALID_ARGUMENT"),1;let opts=parsed.options;if(opts.version)return out(opts.json?JSON.stringify({ok:!0,version},null,2):version),0;if(opts.help){let text=helpText(version,opts.json?!1:colors.stdout,locale);return out(opts.json?JSON.stringify({ok:!0,help:text},null,2):text),0}if(opts.command==="lang")return runLangCommand({toolName:TOOL_NAME,binName:BIN_NAME,docsUrl:DOCS_URL,argv:opts.passthroughArgs??[],flag:stripped.lang,supportsJson:!0,json:opts.json,color:colors,...hooks.out!==void 0?{out}:{},...hooks.err!==void 0?{err}:{}});try{if(opts.command==="update")return await runSelfUpdate({binName:BIN_NAME,toolName:TOOL_NAME,docsUrl:DOCS_URL,entryMetaUrl:import.meta.url,argv:opts.passthroughArgs??[],json:opts.json,locale,...hasCustomIo?{io:{out,err}}:{},color:colors});if(opts.command==="uninstall")return await runSelfUninstall({binName:BIN_NAME,toolName:TOOL_NAME,docsUrl:DOCS_URL,entryMetaUrl:import.meta.url,argv:opts.passthroughArgs??[],json:opts.json,locale,...hasCustomIo?{io:{out,err}}:{},color:colors});if(opts.command==="doctor"){let doctor=diagnoseRim({cwd,configPath:opts.configPath,chromePath:opts.chromePath,locale},hooks.deps);return out(renderDoctorReport(doctor,{color:colors.stdout,json:opts.json,locale})),0}if(opts.command==="init")return await runInitCommand({cwd,configPath:opts.configPath,url:opts.url,serveDir:opts.serveDir,bridgeModule:opts.bridgeModule,startCommand:opts.startCommand,yes:opts.yes,force:opts.force,json:opts.json,interactive:interactive(),locale,out,err});if(opts.command==="baseline")return runBaselineCommand({action:opts.baselineAction,target:opts.baselineTarget,keep:opts.keep,json:opts.json,color:colors.stdout,locale,cacheDir:hooks.baselineCacheDir,out,err});return await executeAuditFlow({opts,cwd,baselineCacheDir:hooks.baselineCacheDir,locale,colors,out,stderrWrite,deps:hooks.deps})}catch(error){if(isRimError(error)&&error.code==="CANCELLED"){let msg=t(locale,"已取消站点质量门禁 (Ctrl+C 中断)","Rim audit cancelled (interrupted via Ctrl+C)");return printErr(msg,colors.stderr,err,opts.json,"CANCELLED"),130}let code=isRimError(error)?error.code:"RIM_ERROR",msg=error instanceof Error?error.message:String(error);return printErr(msg,colors.stderr,err,opts.json,code),1}}function stripWin32ExtendedPrefix(p){if(p.startsWith("\\\\?\\UNC\\")||p.startsWith("\\\\?\\unc\\"))return`\\\\${p.slice(8)}`;if(p.startsWith("\\\\?\\"))return p.slice(4);return p}function normalizeEntryPath2(p){let stripped=process.platform==="win32"?stripWin32ExtendedPrefix(p):p,abs=resolve14(stripped);try{abs=(realpathSync9.native??realpathSync9)(abs)}catch{}let clean=process.platform==="win32"?stripWin32ExtendedPrefix(abs):abs;return process.platform==="win32"?clean.toLowerCase():clean}function isRimCliEntry(){let entryArg=process.argv[1];if(typeof entryArg!=="string"||entryArg==="")return!1;let selfPath=fileURLToPath2(import.meta.url,{windows:process.platform==="win32"}),launcherPath=join18(dirname11(dirname11(selfPath)),"bin","rim.mjs"),invoked=normalizeEntryPath2(entryArg);return invoked===normalizeEntryPath2(selfPath)||invoked===normalizeEntryPath2(launcherPath)}if(isRimCliEntry())process.exitCode=await runRimCli(process.argv.slice(2));export{resolveRimColorChannels,runRimCli};
|