@kaynooo/cli-check 0.24.1 → 0.25.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,79 +0,0 @@
1
- // @bun
2
- import{outputMode,xdgFolder,takesControlCodes,paint,writeErr,warn,stripAnsi,formatDuration,Exit,fail,UsageError,HelpShown,Completing,completion,heading,OUTPUT_OPTIONS}from"./chunk-ngcnmctk.js";import{readFileSync,realpathSync}from"fs";import{resolve}from"path";import process from"process";function commandLine(){try{return readFileSync("/proc/self/cmdline","utf8").split("\x00").slice(0,-1)}catch{return}}function realPath(word){try{return realpathSync(resolve(word))}catch{return}}function scriptArgs(argv=process.argv.slice(2),cmdline=commandLine(),script=process.argv[1]){let target=script===void 0?void 0:realPath(script)??script,at=cmdline===void 0||target===void 0?-1:cmdline.findIndex((word,index)=>index>0&&(resolve(word)===script||realPath(word)===target)),after=at===-1?[]:cmdline.slice(at+1);return after[0]==="--"&&after.length===argv.length+1&&argv.every((word,index)=>word===after[index+1])?after:argv}import{readFileSync as readFileSync2}from"fs";import{constants}from"os";import process2 from"process";var KILL_GRACE_MS=2000,SIGNALS=["SIGINT","SIGTERM","SIGHUP"],GROUP_SIGNALS=new Set(["SIGINT","SIGHUP"]);function exitCodeOf(code,signal){if(code!==null)return code;if(typeof signal==="number")return 128+signal;return signal===null?129:128+constants.signals[signal]}function groupsOf(pid){try{let stat=readFileSync2(`/proc/${pid}/stat`,"utf8"),fields=stat.slice(stat.lastIndexOf(")")+2).split(" ");return{group:Number(fields[2]),foreground:Number(fields[5])}}catch{return}}function heardTheTerminal(child){if(child.pid===void 0)return!1;let own=groupsOf("self");return own!==void 0&&own.group===own.foreground&&groupsOf(child.pid)?.group===own.group}function holdSignals(cleanup){let received,child,held={get signal(){return received},forward:(to)=>{child=to},release:()=>{for(let signal of SIGNALS)process2.off(signal,onSignal)}};function onSignal(signal){if(received=signal,child!==void 0){if(!GROUP_SIGNALS.has(signal)||!heardTheTerminal(child))child.kill(signal);return}if(cleanup===void 0)return;held.release(),cleanup(signal),process2.kill(process2.pid,signal)}for(let signal of SIGNALS)process2.on(signal,onSignal);return held}async function runCommand(argv,{cwd,env,stdin="ignore",input,timeoutMs,signal,maxBytes=1/0,onChunk,onStart}={}){let chunks=[],grouped=timeoutMs!==void 0||signal!==void 0||onStart!==void 0||onChunk!==void 0,proc=Bun.spawn(argv,{...cwd===void 0?{}:{cwd},...env===void 0?{}:{env},stdin:input===void 0?stdin:new TextEncoder().encode(input),stdout:"pipe",stderr:"pipe",...grouped?{detached:!0}:{}}),state={kept:0,truncated:!1,timedOut:!1,failure:void 0,done:!1},timers=[],killGroup=(killing)=>{if(state.done)return;try{if(grouped)process2.kill(-proc.pid,killing);else proc.kill(killing)}catch{}},stop=()=>{killGroup("SIGTERM"),timers.push(setTimeout(killGroup,KILL_GRACE_MS,"SIGKILL"))},onAbort=()=>stop();if(timeoutMs!==void 0)timers.push(setTimeout(()=>{state.timedOut=!0,stop()},timeoutMs));if(signal?.aborted===!0)onAbort();else signal?.addEventListener("abort",onAbort,{once:!0});onStart?.({kill:(killing)=>killGroup(killing)});let drain=async(stream,name)=>{for await(let data of stream){if(state.failure!==void 0)continue;try{onChunk?.({stream:name,data})}catch(error){state.failure=error,stop();continue}if(state.truncated)continue;let kept=data;if(state.kept+data.length>maxBytes){let cut=maxBytes-state.kept;while(cut>0&&((data[cut]??0)&192)===128)cut--;kept=data.subarray(0,cut),state.truncated=!0}if(state.kept+=kept.length,kept.length>0)chunks.push({stream:name,data:kept})}};try{await Promise.all([drain(proc.stdout,"stdout"),drain(proc.stderr,"stderr")]),await proc.exited}finally{state.done=!0;for(let timer of timers)clearTimeout(timer);signal?.removeEventListener("abort",onAbort)}if(state.failure!==void 0)throw state.failure;let joined=()=>Buffer.concat(chunks.map(({data})=>data)),output,text,stdout;return{code:exitCodeOf(proc.exitCode,proc.signalCode),chunks,timedOut:state.timedOut,truncated:state.truncated,get output(){return output??=joined()},get text(){return text??=(output??=joined()).toString()},get stdout(){return stdout??=Buffer.concat(chunks.filter((chunk)=>chunk.stream==="stdout").map((chunk)=>chunk.data)).toString()}}}import{readFileSync as readFileSync4,realpathSync as realpathSync2}from"fs";import{dirname as dirname2,join as join3}from"path";import process7 from"process";import process3 from"process";var SOCKET_VARIABLE="KAYNOOO_ASKPASS_SOCKET";async function askpassClient(argv){let socketPath=process3.env[SOCKET_VARIABLE];if(socketPath===void 0)return;let request={prompt:argv[0]??"",...process3.env.SSH_ASKPASS_PROMPT==="none"?{notice:!0}:{}},{promise,resolve}=Promise.withResolvers(),received="";try{await Bun.connect({unix:socketPath,socket:{open:(socket)=>void socket.write(`${JSON.stringify(request)}
3
- `),data:(_,chunk)=>{received+=chunk.toString()},close:()=>resolve(received),error:()=>resolve("")}})}catch{return 1}let reply=await promise;if(reply==="")return 1;let{answer}=JSON.parse(reply);if(request.notice===!0)return 0;if(answer===void 0)return 1;return process3.stdout.write(`${answer}
4
- `),0}var COMPLETION_SHELLS=["fish","bash","zsh"];function completionScript(shell,bins,header=`# Generated by \`${bins[0]} --completions ${shell}\``){if(shell==="fish")return`${header}
5
- functions -q __kaynooo_cli_complete; or function __kaynooo_cli_complete --argument-names bin --description 'what a @kaynooo/cli-kit bin offers for the word being typed'
6
- set -l tokens (commandline -xpc 2>/dev/null; or commandline -opc)
7
- set -l current (commandline -ct)
8
- for line in ($bin __complete $tokens[2..-1] $current 2>/dev/null)
9
- if test "$line" = __files__
10
- __fish_complete_path $current
11
- else
12
- echo $line
13
- end
14
- end
15
- end
16
- ${bins.map((bin)=>`complete -c ${bin} -f -a '(__kaynooo_cli_complete ${bin})'
17
- `).join("")}`;if(shell==="bash")return`${header}
18
- __kaynooo_cli_complete() {
19
- local IFS=$'\\n' cur=\${COMP_WORDS[COMP_CWORD]} line words=
20
- local -a lines
21
- COMPREPLY=()
22
- lines=($("\${COMP_WORDS[0]}" __complete "\${COMP_WORDS[@]:1:COMP_CWORD}" 2>/dev/null))
23
- for line in "\${lines[@]}"; do
24
- if [[ $line == __files__ ]]; then
25
- COMPREPLY+=($(compgen -f -- "$cur"))
26
- else
27
- words+="\${line%%$'\\t'*}"$'\\n'
28
- fi
29
- done
30
- COMPREPLY+=($(compgen -W "$words" -- "$cur"))
31
- }
32
- complete -F __kaynooo_cli_complete ${bins.join(" ")}
33
- `;return`${header}
34
- __kaynooo_cli_complete() {
35
- local line
36
- local -a described plain
37
- for line in \${(f)"$("\${words[1]}" __complete "\${(@)words[2,CURRENT]}" 2>/dev/null)"}; do
38
- if [[ $line == __files__ ]]; then
39
- _files
40
- elif [[ $line == *$'\\t'* ]]; then
41
- described+=("\${\${line%%$'\\t'*}//:/\\\\:}:\${line#*$'\\t'}")
42
- else
43
- plain+=("$line")
44
- fi
45
- done
46
- (( \${#described} )) && _describe -V value described
47
- (( \${#plain} )) && compadd -- "\${plain[@]}"
48
- return 0
49
- }
50
- __kaynooo_cli_register() {
51
- add-zsh-hook -d precmd __kaynooo_cli_register
52
- (( $+functions[compdef] )) || { autoload -Uz compinit && compinit }
53
- compdef __kaynooo_cli_complete $__kaynooo_cli_bins
54
- }
55
- autoload -Uz add-zsh-hook
56
- add-zsh-hook precmd __kaynooo_cli_register
57
- typeset -gaU __kaynooo_cli_bins
58
- __kaynooo_cli_bins+=(${bins.join(" ")})
59
- `}var COMPLETE="__complete",FILES="__files__",COMPLETIONS="--completions";async function completingOf(run){completion.active=!0;try{await run([])}catch(error){if(error instanceof Completing)return error}finally{completion.active=!1}return new Completing({})}function candidateLine(candidate){return typeof candidate==="string"?candidate:candidate.join("\t")}function positionalBeingTyped(before,{options,positionals}){let takesValue=(word)=>!word.includes("=")&&Object.entries(options).some(([name,{short,type}])=>type==="string"&&(word===`--${name}`||word===`-${short}`)),typed=[],at=0;while(at<before.length){let word=before[at];if(word==="--"){typed.push(...before.slice(at+1));break}if(!word.startsWith("-"))typed.push(word);else if(takesValue(word))at++;at++}let last=positionals.at(-1);if(typed.length<positionals.length)return{name:positionals[typed.length],typed};return{name:last?.replace("]","").endsWith("...")===!0?last:void 0,typed}}async function leafCandidates(run,words){let completing=await completingOf(run);if((words.at(-1)??"").startsWith("-"))return Object.entries(completing.options).map(([name,option])=>option.description===void 0?`--${name}`:`--${name} ${option.description}`);let flag=words.at(-2),option=flag?.startsWith("-")===!0?Object.entries(completing.options).find(([name,{short}])=>flag===`--${name}`||flag===`-${short}`)?.[1]:void 0,{name,typed}=positionalBeingTyped(words.slice(0,-1),completing);if(option?.type==="string"){let values=option.choices===void 0?await option.candidates?.(typed):option.choices;return values===void 0?[FILES]:values.map(candidateLine)}let values=name===void 0?void 0:await completing.candidates[name]?.(typed);return values===void 0?[FILES]:values.map(candidateLine)}function flagValue([flag="",...rest]){return flag.includes("=")?[flag.slice(flag.indexOf("=")+1),...rest]:rest}function printCompletionScript(name,args,reportError){let shell=COMPLETION_SHELLS.find((each)=>each===args[0]);if(shell===void 0||args.length!==1)return reportError(name,`${COMPLETIONS} takes one of ${COMPLETIONS_SHELLS_LIST()}`,`${name} ${COMPLETIONS} fish`),2;return console.log(completionScript(shell,[name]).trimEnd()),0}function COMPLETIONS_SHELLS_LIST(){return COMPLETION_SHELLS.join(", ")}async function printCandidates(found){for(let line of await found)console.log(line);return 0}import process4 from"process";var NOTIFY_AFTER_MS=1e4,CANCELLED=130;function base64(text){return Buffer.from(text).toString("base64")}function sanitizeOsc(text){return text.replaceAll(/[\x00-\x1F\x7F;]/g," ")}function wrapTmux(codes,env){return codes.map((code)=>env.TMUX===void 0||env.TMUX===""?code:`\x1BPtmux;${code.replaceAll("\x1B","\x1B\x1B")}\x1B\\`).join("")}function notification(title,body,env=process4.env){let program=env.TERM_PROGRAM??"",term=env.TERM??"";if(program==="WezTerm"||term.startsWith("foot")||term.startsWith("rxvt"))return wrapTmux([`\x1B]777;notify;${sanitizeOsc(title)};${sanitizeOsc(body)}\x1B\\`],env);if(program==="iTerm.app"||env.WT_SESSION!==void 0&&env.WT_SESSION!=="")return wrapTmux([`\x1B]9;${sanitizeOsc(title)}: ${sanitizeOsc(body)}\x1B\\`],env);let id=`kit${process4.pid}`,codes=[`\x1B]99;i=${id}:d=0:o=unfocused:e=1;${base64(title)}\x1B\\`,`\x1B]99;i=${id}:p=body:e=1;${base64(body)}\x1B\\`];return wrapTmux(codes,env)}function notifyEnd(command,code,ms,{stream=process4.stderr,env=process4.env}={}){if(ms<NOTIFY_AFTER_MS||code===CANCELLED||outputMode(stream,env)!=="terminal")return;stream.write(notification(command,code===0?`done in ${formatDuration(ms)}`:`failed with exit ${code} after ${formatDuration(ms)}`,env))}import{appendFileSync,mkdirSync,readFileSync as readFileSync3,renameSync,statSync,writeFileSync}from"fs";import{homedir as homedir2}from"os";import{dirname,join as join2}from"path";import process6 from"process";import{lstatSync,openSync}from"fs";import{mkdir,mkdtemp,readdir,rm,stat}from"fs/promises";import{homedir,tmpdir}from"os";import{join}from"path";import process5 from"process";var DAY_MS=86400000,CLI_FOLDER="kaynooo-cli";function isPrivateDirectory(path){try{let info=lstatSync(path,{throwIfNoEntry:!1});return info!==void 0&&info.isDirectory()&&info.uid===(process5.getuid?.()??info.uid)&&(info.mode&63)===0}catch{return!1}}async function privateLogDirectory(name,env=process5.env){let path=join(xdgFolder(env.XDG_RUNTIME_DIR,join(homedir(),".cache")),CLI_FOLDER,name);try{if(await mkdir(path,{recursive:!0,mode:448}),isPrivateDirectory(path))return path}catch{}return mkdtemp(join(tmpdir(),`${name.replaceAll("/","-")}-`))}async function sweepLogs(dir,maxAgeMs=DAY_MS,now=Date.now()){let names;try{names=await readdir(dir)}catch{return}for(let name of names){let path=join(dir,name);try{let info=await stat(path);if(info.isDirectory())await sweepLogs(path,maxAgeMs,now);if(now-info.mtimeMs>maxAgeMs)await rm(path,{force:!0,recursive:info.isDirectory()})}catch{continue}}}var MAX_USAGE_BYTES=2097152,UNKNOWN_OPTION=/unknown option '(--[a-z][a-z0-9-]*)[=']/,FLAG_NAME=/^(?:--[a-z][a-z0-9-]*|-[a-zA-Z])$/,LONGEST_NAME=40,usageError;function noteUsageError(message){usageError=message}function stateHome(env=process6.env){return xdgFolder(env.XDG_STATE_HOME,join2(homedir2(),".local","state"))}function usagePath(env=process6.env){return join2(stateHome(env),CLI_FOLDER,"usage.jsonl")}function usageRecorded(env=process6.env){let off=env.KAYNOOO_CLI_NO_USAGE;return env.NODE_ENV!=="test"&&(off===void 0||off===""||off==="0")}function flagNames(argv){let end=argv.indexOf("--"),names=(end===-1?argv:argv.slice(0,end)).filter((word)=>word.startsWith("-")&&word!=="-").map((word)=>word.includes("=")?word.slice(0,word.indexOf("=")):word);return[...new Set(names)].filter((name)=>name.length<=LONGEST_NAME&&FLAG_NAME.test(name))}function usageEntry(bin,command,argv,code,{ms,mode,now=new Date}={}){let unknown=code===2&&usageError!==void 0?UNKNOWN_OPTION.exec(usageError)?.[1]:void 0;return usageError=void 0,{at:now.toISOString(),bin,...command===void 0?{}:{command},flags:flagNames(argv),code,...unknown===void 0?{}:{unknown},...ms===void 0?{}:{ms:Math.round(ms)},...mode===void 0?{}:{mode}}}function trimUsage(path,maxBytes){let info=statSync(path,{throwIfNoEntry:!1});if(info===void 0||info.size<=maxBytes)return;let lines=readFileSync3(path,"utf8").split(`
60
- `).filter(Boolean),kept=`${lines.slice(Math.floor(lines.length/2)).join(`
61
- `)}
62
- `,temp=`${path}.${process6.pid}.tmp`;writeFileSync(temp,kept,{mode:384}),renameSync(temp,path)}function recordUsage(entry,env=process6.env,maxBytes=MAX_USAGE_BYTES){if(!usageRecorded(env))return;try{let path=usagePath(env);mkdirSync(dirname(path),{recursive:!0,mode:448}),appendFileSync(path,`${JSON.stringify(entry)}
63
- `,{mode:384}),trimUsage(path,maxBytes)}catch{}}var LEVEL_OPTIONS={...OUTPUT_OPTIONS,help:{type:"boolean",short:"h",description:"show this help"}},TOP_OPTIONS={...LEVEL_OPTIONS,version:{type:"boolean",short:"v",description:"print the version"},completions:{type:"string",choices:COMPLETION_SHELLS,description:"print the shell completion script"}};function printError(prefix,message,hint,cause){let colors=paint(process7.stderr),styled=takesControlCodes(process7.stderr),head=styled?`${colors.red.bold("error")} ${colors.dim(`${prefix}:`)}`:`error: ${prefix}:`,under=(label,text,tint)=>text===void 0?"":`
64
- ${styled?tint(label):`${label}:`} ${text}`;writeErr(`${head} ${message}${under("cause",cause,colors.dim)}${under("hint",hint,colors.yellow)}`)}function printJsonError(message,hint,cause,extra){writeErr(JSON.stringify({error:message,...extra?.code===void 0?{}:{code:extra.code},...extra?.command===void 0?{}:{command:extra.command},...hint===void 0?{}:{hint},...cause===void 0?{}:{cause}}))}function wantsJson(argv){let end=argv.indexOf("--");return(end===-1?argv:argv.slice(0,end)).includes("--json")}function reportThrown(prefix,error,redact=(text)=>text,json=!1){if(error instanceof HelpShown)return 0;let code=error instanceof Exit?error.code:1,helpHint=error instanceof UsageError?`run ${prefix} --help for its options`:void 0,named=error instanceof Error&&!(error instanceof Exit)&&error.name!=="Error"?`${error.name}: ${error.message}`:void 0,cause=error instanceof Error&&error.cause instanceof Error?redact(error.cause.message):void 0;if(error instanceof Exit&&error.code===2)noteUsageError(error.message);return(json?(message,hint,causeText)=>printJsonError(message,hint,causeText,{code,command:prefix}):(message,hint,causeText)=>printError(prefix,message,hint,causeText))(redact(named??(error instanceof Error?error.message:String(error))),error instanceof Exit?error.hint??helpHint:void 0,cause),code}function packageVersion(entry=Bun.main){let resolved=entry;try{resolved=realpathSync2(entry)}catch{}for(let dir=dirname2(resolved);;dir=dirname2(dir)){try{let{version}=JSON.parse(readFileSync4(join3(dir,"package.json"),"utf8"));if(typeof version==="string")return version}catch{}if(dirname2(dir)===dir)return"0.0.0"}}async function runMain({name,version,run,redact,usage},argv=scriptArgs()){let answered=await askpassClient(argv);if(answered!==void 0)return answered;if(argv[0]===COMPLETE)return printCandidates(leafCandidates(run,argv.slice(1)));if(argv[0]===COMPLETIONS||argv[0]?.startsWith(`${COMPLETIONS}=`)===!0)return printCompletionScript(name,flagValue(argv),printError);if(argv.length===1&&(argv[0]==="--version"||argv[0]==="-v"))return console.log(version??packageVersion()),0;let code,meta=!1,started=performance.now();heading.bin={name,version:()=>version??packageVersion()};try{code=await run(argv)}catch(error){meta=error instanceof HelpShown,code=reportThrown(name,error,redact,wantsJson(argv))}finally{heading.bin=void 0}if(notifyEnd(name,code,performance.now()-started),usage!==!1&&!meta)try{recordUsage(usageEntry(name,void 0,argv,code,{ms:performance.now()-started,mode:outputMode()}))}catch{}return code}import{existsSync,statSync as statSync2}from"fs";import{homedir as homedir3}from"os";import{basename,dirname as dirname3,join as join4,relative,resolve as resolve2}from"path";import process8 from"process";var SAFE_WORD=/^[\w@%+=:,./-]+$/;var SHELLS=new Set(["sh","bash","zsh","dash","ash","ksh","fish","csh","tcsh","nu","xonsh","elvish","pwsh","powershell"]),SCANNED_PROGRAMS=new Set(["su","runuser","flock"]),COMMAND_STRING_PROGRAMS=new Set([...SHELLS,...SCANNED_PROGRAMS]);function wrapper(short="",long=[],operands=0,runsString=!1){return{short,long,operands,runsString}}var RUNNER={...wrapper(),afterDashes:!0},WRAPPERS=new Map([["command",wrapper()],["builtin",wrapper()],["nohup",wrapper()],["setsid",wrapper()],["busybox",wrapper()],["exec",wrapper("a")],["time",wrapper("fo",["--format","--output"])],["env",wrapper("uCS",["--unset","--chdir","--split-string","--argv0"])],["sudo",wrapper("ughpCTrtUDR",["--user","--group","--host","--prompt","--close-from","--command-timeout","--role","--type","--other-user","--chdir","--chroot"])],["doas",wrapper("uC")],["timeout",wrapper("sk",["--signal","--kill-after"],1)],["nice",wrapper("n",["--adjustment"])],["ionice",wrapper("cnpPu",["--class","--classdata","--pid","--pgid","--uid"])],["stdbuf",wrapper("ioe",["--input","--output","--error"])],["chroot",wrapper("",["--userspec","--groups"],1)],["watch",wrapper("n",["--interval"],0,!0)],["flock",wrapper("wE",["--timeout","--conflict-exit-code"],1)],["parallel",wrapper("jnNSaIPlLdTsC",["--jobs","--max-args","--max-replace-args","--sshlogin","--arg-file","--delimiter","--colsep"],0,!0)],["unbuffer",wrapper()],["systemd-run",wrapper("puEMH",["--property","--unit","--description","--slice","--setenv","--machine","--host","--uid","--gid","--working-directory","--nice","--service-type"])],["xargs",wrapper("IndsEaPL",["--max-args","--max-procs","--max-chars","--delimiter","--arg-file","--eof","--max-lines","--process-slot-var"])],["strace",wrapper("abeEIoOpPsSuUX",["--trace","--output","--attach","--string-limit","--user","--env","--columns","--trace-path","--signal","--status","--summary-sort-by","--summary-columns","--const-print-style","--interruptible","--detach-on"])],["ltrace",wrapper("aeFlnopsuxX",["--output","--user","--library","--config","--align","--indent"])],["taskset",wrapper("",[],1)],["fakeroot",wrapper("lsib",["--lib","--faked"])],["sshpass",wrapper("pfdP")],["coproc",wrapper()],["proxychains",wrapper("f")],["proxychains4",wrapper("f")],["torsocks",wrapper("upaP",["--user","--pass","--address","--port"])],["chrt",wrapper("TPD",["--sched-runtime","--sched-period","--sched-deadline"],1)],["unshare",wrapper("SGRw",["--setuid","--setgid","--root","--wd","--map-user","--map-group","--map-users","--map-groups","--propagation","--setgroups"])],["nsenter",wrapper("tSG",["--target","--setuid","--setgid"])],["out",RUNNER],["slot",RUNNER],["waitfor",RUNNER],["base",RUNNER]]);function shellQuote(word){return SAFE_WORD.test(word)&&!word.startsWith("=")?word:`'${word.replaceAll("'","'\\''")}'`}var COMPOSE_FILES=["compose.yaml","compose.yml","docker-compose.yaml","docker-compose.yml"],OVERRIDE_FILES=["compose.override.yaml","compose.override.yml","docker-compose.override.yaml","docker-compose.override.yml"],PS_TIMEOUT_MS=20000;var VARIABLE=/\$\{(\w+)(?::?-([^${}]*))?\}|\$(\w+)/g,ENV_LINE=/^\s*(?:export\s+)?(\w+)=(.*)$/,QUOTED=/^(['"])(.*)\1$/,TOOL_WORDS={bun:["bun"],bunx:["bun"],node:["node","bun"],npm:["node","bun"],npx:["node","bun"],pnpm:["node","bun"],yarn:["node","bun"],composer:["php"],php:["php"],phpunit:["php"],phpstan:["php"],paratest:["php"],pest:["php"],symfony:["php"],python:["python"],python3:["python"],pytest:["python"],ruff:["python"],uv:["python"],go:["go","golang"],cargo:["rust"],deno:["deno"]};function toolWords(program){let name=basename(program);return TOOL_WORDS[name]??(program.includes("vendor/bin/")?["php"]:[])}async function readFiles(dir,names){for(let name of names){let handle=Bun.file(join4(dir,name));if(await handle.exists())return{name,text:await handle.text()}}return}async function variables(composeDir){let env={},text=(await readFiles(composeDir,[".env"]))?.text??"";for(let line of text.split(`
65
- `)){let match=ENV_LINE.exec(line);if(match!==null&&!line.trimStart().startsWith("#"))env[match[1]??""]=(match[2]??"").trim().replace(QUOTED,"$2")}for(let[key,value]of Object.entries(process8.env))if(value!==void 0)env[key]=value;return env.PWD=composeDir,env}function interpolate(text,env){let current=text;for(let round=0;round<4&&current.includes("$");round++)current=current.replaceAll(VARIABLE,(_,braced,fallback,bare)=>{let value=env[braced??bare??""];return value!==void 0&&value!==""?value:fallback??""});return current}function bindSource(source,composeDir,env){let path=interpolate(source,env);if(path.startsWith("~"))return join4(homedir3(),path.slice(1));if(path.startsWith("/"))return resolve2(path);return path.startsWith(".")?resolve2(composeDir,path):void 0}function mountsOf(volumes,composeDir,env){if(!Array.isArray(volumes))return[];let mounts=[];for(let volume of volumes){let source,target;if(typeof volume==="string")[source,target]=interpolate(volume,env).split(":");else if(typeof volume==="object"&&volume!==null){let object=volume;if(object.type==="bind"&&typeof object.source==="string"&&typeof object.target==="string")({source,target}=object)}let resolved=source===void 0?void 0:bindSource(source,composeDir,env);if(resolved!==void 0&&target?.startsWith("/")===!0)mounts.push({source:resolved,target})}return mounts}function buildText(build){if(typeof build==="string")return build;return typeof build==="object"&&build!==null?Object.values(build).filter((value)=>typeof value==="string").join(" "):""}function parseServices(text,composeDir,env){let services=new Map,parsed=Bun.YAML.parse(text);for(let[name,service]of Object.entries(parsed?.services??{}))if(service!==null&&typeof service==="object")services.set(name,{...service,mounts:mountsOf(service.volumes,composeDir,env)});return services}async function composeFiles(composeDir,env){let listed=env.COMPOSE_FILE;if(listed!==void 0&&listed!==""){let files=[],separator=env.COMPOSE_PATH_SEPARATOR;for(let name of listed.split(separator===void 0||separator===""?":":separator).filter((entry)=>entry!=="")){let file=Bun.file(resolve2(composeDir,name));if(!await file.exists())fail(`COMPOSE_FILE names ${join4(composeDir,name)}, which does not exist`,1,"fix COMPOSE_FILE, or run on the host with --host");files.push({name,text:await file.text()})}return files}let base=await readFiles(composeDir,COMPOSE_FILES);if(base===void 0)return[];let override=await readFiles(composeDir,OVERRIDE_FILES);return override===void 0?[base]:[base,override]}async function readServices(composeDir){let env=await variables(composeDir),files=await composeFiles(composeDir,env);if(files.length===0)return;let services=new Map;for(let file of files){let parsed;try{parsed=parseServices(file.text,composeDir,env)}catch(error){fail(`cannot read ${join4(composeDir,file.name)}: ${error instanceof Error?error.message:String(error)}`,1,"fix the file, or run on the host with --host")}for(let[name,extra]of parsed){let known=services.get(name);services.set(name,known===void 0?extra:{...known,...extra,mounts:[...known.mounts,...extra.mounts],image:extra.image??known.image,build:extra.build??known.build})}}return[...services].map(([name,service])=>({name,mounts:service.mounts,profile:`${name} ${typeof service.image==="string"?service.image:""} ${buildText(service.build)}`.toLowerCase()}))}function climb(dir){let folders=[dir],current=dir;while(!existsSync(join4(current,".git"))&&dirname3(current)!==current)current=dirname3(current),folders.push(current);return existsSync(join4(current,".git"))?folders:[dir]}function containerPath(service,dir){let deepest=service.mounts.filter((mount)=>{let inside=relative(mount.source,dir);return!inside.startsWith("..")&&!inside.startsWith("/")}).toSorted((a,b)=>b.source.length-a.source.length)[0];if(deepest===void 0)return;let inside=relative(deepest.source,dir);return inside===""?deepest.target:join4(deepest.target,inside)}var ORCHESTRATORS=new Set(["make","just","task","mise"]),noticed=new Set;async function place(dir,program,{service,host}={}){if(host===!0||service===void 0&&ORCHESTRATORS.has(basename(program)))return;let found;for(let composeDir of climb(dir)){let services=await readServices(composeDir),mounting=(services??[]).filter((candidate)=>containerPath(candidate,dir)!==void 0);if(services!==void 0&&(mounting.length>0||services.some((candidate)=>candidate.name===service))){found={composeDir,services,mounting};break}}if(found===void 0){if(service!==void 0)fail(`--in ${service}: no compose project mounts ${dir}`);return}if(Bun.which("docker",{PATH:process8.env.PATH??""})===null){if(service!==void 0)fail(`--in ${service}: docker not found`);if(!noticed.has(found.composeDir))noticed.add(found.composeDir),warn(`host, docker not found: the compose project in ${found.composeDir} is not reached`);return}let chosen=choose(found.mounting,found.services,dir,program,service);return{service:chosen.name,composeDir:found.composeDir,workdir:containerPath(chosen,dir)??dir}}function choose(mounting,services,dir,program,service){if(service!==void 0){let named=mounting.find((candidate)=>candidate.name===service);if(named===void 0)fail(`--in ${service}: ${services.some((candidate)=>candidate.name===service)?`the service does not mount ${dir}`:`no such service, found ${services.map((candidate)=>candidate.name).join(", ")}`}`);return named}let[only]=mounting;if(mounting.length===1&&only!==void 0)return only;let words=toolWords(program),fitting=mounting.filter((candidate)=>words.some((word)=>candidate.profile.includes(word))),[fit]=fitting;if(fitting.length!==1||fit===void 0)fail(`${mounting.map((candidate)=>candidate.name).join(", ")} all mount ${dir} and none stands out for ${basename(program)}: pick one with --in <service>, or run on the host with --host`);return fit}function execArgv(placement,argv,env){let variables=Object.entries({NO_COLOR:"1",FORCE_COLOR:"0",...env}).flatMap(([name,value])=>["-e",`${name}=${value}`]);return["docker","compose","exec","-T","-w",placement.workdir,...variables,placement.service,...argv]}function shellIn(placement,command,env={}){return`cd ${shellQuote(placement.composeDir)} && ${execArgv(placement,["sh","-c",command],env).map((word)=>shellQuote(word)).join(" ")}`}function argvIn(placement,argv,env={}){return execArgv(placement,argv,env)}class Stack{answers=new Map;async ask(composeDir){let answer=this.answers.get(composeDir);if(answer===void 0)answer=Stack.running(composeDir),this.answers.set(composeDir,answer);return answer}static async running(composeDir){try{let ran=await runCommand(["docker","compose","ps","--services","--status","running"],{cwd:composeDir,env:process8.env,timeoutMs:PS_TIMEOUT_MS});if(ran.code!==0)return`docker compose ps failed in ${composeDir}: ${ran.text.trim().split(`
66
- `).at(-1)??`exit ${ran.code}`}`;return ran.text.split(`
67
- `).map((line)=>line.trim()).filter((line)=>line!=="")}catch(error){return`cannot run docker compose in ${composeDir}: ${error instanceof Error?error.message:String(error)}`}}async problem(placement){let answer=await this.ask(placement.composeDir);if(typeof answer==="string")return answer;return answer.includes(placement.service)?void 0:`the ${placement.service} service is not running (compose project in ${placement.composeDir}): start it yourself, or run on the host with --host`}}function programOf(command){let end=command.indexOf(" ");return end===-1?command:command.slice(0,end)}async function composeServiceCandidates(){try{return(await readServices(process8.cwd()))?.map((service)=>service.name)??[]}catch{return[]}}var placeOptions={in:{type:"string",description:"run in this compose service instead of the one found mounting the folder",candidates:composeServiceCandidates},host:{type:"boolean",description:"run on the host even when a compose service mounts the folder"}};function placeSettings(values){if(values.in!==void 0&&values.host===!0)fail("--in and --host exclude each other");return{service:values.in,host:values.host}}var BASH_ECHO=/^\$ /,DURATION=/ \[[\d.]+m?s\]$/,BOUNDARY=/^(?:\((?:pass|fail|skip|todo)\) |\S+\.test\.[jt]sx?:$)/,BUN_TEST_SUMMARY=/^\s*\d+ (?:pass|fail|skip|todo)$|^Ran \d+ tests?/,BUN_CHECK_BLOCK=/<error file=[\s\S]*?<\/error>/g,BUN_CHECK_SOURCE=/<source>[\s\S]*?<\/source>\n?/g,BUN_CHECK_ATTRIBUTE=/(\w+)="([^"]*)"/g,BUN_CHECK_SUMMARY=/^Found \d+ errors?/,TSC_ERROR=/\berror TS\d+/,TSC_CONTINUATION=/^\s{2,}\S/,TSC_FRAME=/^\s*[~^|]/,TSC_SUMMARY=/^Found \d+ errors?/,ESLINT_PROBLEM=/^\s+\d+:\d+\s+(?:error|warning)\s/,ESLINT_SUMMARY=/^(?:\u2716 )?\d+ problems? \(/,PHPSTAN_TABLE=/^\s*-{3,} -{3,}/,PHPSTAN_NOISE=/^\s*\[OK\]/,PHP_FAILURES=/^(?:There w(?:as|ere) \d+ (?:failure|error|risky|warning)|\s+(?:FAIL|FAILED)\s+\S|In \S+\.php line \d+:$)/,VITEST_FAIL_LINE=/^ FAIL {2}\S/,PLAYWRIGHT_FAIL_LINE=/^ {2}1\) .+:\d+:\d+ \u203A .+ \u2500+$/,CS_FIXER_LINE=/^\s+\d+\) \S.*\.php(?: \(.+\))?$/,CS_FIXER_TOTAL=/^Found \d+ of \d+ files/,MAX_TESTS=10,MAX_LINES=100,TAIL=30,bunTest=(lines)=>{let seen=new Set,blocks=[];for(let[index,line]of lines.entries()){let name=line.replace(DURATION,"");if(!line.startsWith("(fail) ")||seen.has(name))continue;if(seen.add(name),blocks.length<MAX_TESTS)blocks.push(lines.slice(lines.findLastIndex((text,at)=>at<index&&BOUNDARY.test(text))+1,index+1).join(`
68
- `).trim())}if(blocks.length===0)return;if(seen.size>MAX_TESTS)blocks.push(`and ${seen.size-MAX_TESTS} more failed tests`);return[...blocks.join(`
69
-
70
- `).split(`
71
- `),"",...lines.filter((line)=>BUN_TEST_SUMMARY.test(line)).map((line)=>line.trim())]},bunCheck=(lines)=>{let blocks=lines.join(`
72
- `).match(BUN_CHECK_BLOCK);if(blocks===null)return;return[...blocks.map((block)=>{let{file,line,column,code,message}=bunCheckFields(block);return`${file}:${line}:${column} ${code}: ${message}`}),...lines.filter((line)=>BUN_CHECK_SUMMARY.test(line))]};function bunCheckFields(block){let attributes=Object.fromEntries([...block.slice(0,block.indexOf(`
73
- `)).matchAll(BUN_CHECK_ATTRIBUTE)].map((match)=>[match[1]??"",match[2]??""]));return{file:attributes.file??"",line:attributes.line??"",column:attributes.column??"",code:attributes.code??"",message:block.replace(BUN_CHECK_SOURCE,"").split(`
74
- `).slice(1,-1).join(`
75
- `).trim()}}var tsc=(lines)=>{let kept=[],inError=!1;for(let line of lines)if(TSC_ERROR.test(line))inError=!0,kept.push(line);else if(TSC_SUMMARY.test(line))inError=!1,kept.push(line);else if(inError&&TSC_CONTINUATION.test(line)&&!TSC_FRAME.test(line))kept.push(line);else inError=!1;return kept.some((line)=>TSC_ERROR.test(line))?kept:void 0},eslint=(lines)=>{let kept=[],file="",shown="";for(let line of lines)if(ESLINT_PROBLEM.test(line)){if(file!==shown)kept.push(file),shown=file;kept.push(line)}else if(ESLINT_SUMMARY.test(line))kept.push(line);else if(line.trim()!=="")file=line;return kept.some((line)=>ESLINT_PROBLEM.test(line))?kept:void 0},phpstan=(lines)=>{let start=lines.findIndex((line)=>PHPSTAN_TABLE.test(line));return start===-1?void 0:lines.slice(start).filter((line)=>!PHPSTAN_NOISE.test(line))},php=(lines)=>{let start=lines.findIndex((line)=>PHP_FAILURES.test(line));return start===-1?void 0:lines.slice(start)},vitest=(lines)=>{let start=lines.findIndex((line)=>VITEST_FAIL_LINE.test(line));return start===-1?void 0:lines.slice(start)},playwright=(lines)=>{let start=lines.findIndex((line)=>PLAYWRIGHT_FAIL_LINE.test(line));return start===-1?void 0:lines.slice(start)},phpCsFixer=(lines)=>{let files=lines.filter((line)=>CS_FIXER_LINE.test(line)||CS_FIXER_TOTAL.test(line));return files.some((line)=>CS_FIXER_LINE.test(line))?files:void 0},PARSERS=[bunTest,bunCheck,tsc,eslint,vitest,playwright,phpCsFixer,phpstan,php];function squeeze(lines){let out=[];for(let line of lines.map((text)=>text.trimEnd()))if(line!==""||out.at(-1)!=="")out.push(line);while(out.at(-1)==="")out.pop();return out}function cut(shown){return shown.length>MAX_LINES?[...shown.slice(0,MAX_LINES),`... ${shown.length-MAX_LINES} more lines`].join(`
76
- `):shown.join(`
77
- `)}function recognised(lines,parsers){return parsers.map((parser)=>parser(lines)).find((result)=>result!==void 0&&result.some((line)=>line.trim()!==""))}function failureExcerpt(output){let lines=stripAnsi(output).split(`
78
- `);if(BASH_ECHO.test(lines[0]??""))lines.shift();return cut(squeeze(recognised(lines,PARSERS)??lines.slice(-TAIL)))}var LOG_PATTERNS={BASH_ECHO,DURATION,BOUNDARY,BUN_TEST_SUMMARY,BUN_CHECK_SUMMARY,TSC_CONTINUATION,TSC_FRAME,TSC_SUMMARY,ESLINT_PROBLEM,ESLINT_SUMMARY};var{Glob}=globalThis.Bun;var SESSION_FILES=new Glob("*.json"),ACCOUNT_DIRS=new Glob("*/sessions");import{basename as basename2,dirname as dirname4,join as join5,relative as relative2,sep}from"path";var PARENT=`..${sep}`;var version="0.24.1";
79
- export{exitCodeOf,holdSignals,runCommand,privateLogDirectory,sweepLogs,runMain,shellQuote,place,shellIn,argvIn,Stack,programOf,placeOptions,placeSettings,bunCheckFields,failureExcerpt,LOG_PATTERNS,version};
@@ -1,11 +0,0 @@
1
- // @bun
2
- import{warn,fail,ignoredFolders}from"./chunk-ngcnmctk.js";import{runCommand}from"./chunk-898e3vv3.js";import{existsSync as existsSync2,readdirSync,readFileSync as readFileSync2}from"fs";import{dirname,join as join2,resolve as resolvePath}from"path";import{existsSync,readFileSync}from"fs";import{readdir}from"fs/promises";import{basename,join,relative,resolve as resolve2}from"path";var STEP_NAMES=["check","typecheck","lint","fmt","test"],STEP_SOURCES={fmt:["fmt:check","format:check","fmt-check","format-check"]},TARGET=/^@?([\w-]+)(?:[ \t][^:=\n]*)?:(?!=)/gm,JUSTFILES=["justfile","Justfile",".justfile"],TASKFILES=["Taskfile.yml","taskfile.yml","Taskfile.yaml","taskfile.yaml","Taskfile.dist.yml","taskfile.dist.yml","Taskfile.dist.yaml","taskfile.dist.yaml"],DENO_FILES=["deno.json","deno.jsonc"],MISE_FILES=["mise.toml",".mise.toml",".config/mise.toml"],CHECKRC_FILES=[".checkrc.jsonc",".checkrc.json"],TASK_RUNNERS=new Set(["Justfile","Makefile","Taskfile","mise"]),MAKEFILES=["GNUmakefile","makefile","Makefile"],CS_FIXER_CONFIGS=[".php-cs-fixer.php",".php-cs-fixer.dist.php"],JUST_TIMEOUT_MS=1e4,PHPSTAN_CONFIGS=["phpstan.neon","phpstan.neon.dist","phpstan.dist.neon"],PHPUNIT_CONFIGS=["phpunit.xml","phpunit.xml.dist","phpunit.dist.xml"],RUFF_CONFIGS=["ruff.toml",".ruff.toml"],PYTEST_CONFIGS=["pytest.ini","conftest.py"],MYPY_CONFIGS=["mypy.ini",".mypy.ini"],RUFF_SECTION=/^\[tool\.ruff/m,PYTEST_SECTION=/^\[tool\.pytest/m,MYPY_SECTION=/^\[tool\.mypy/m;async function readFirst(dir,files){for(let file of files){let handle=Bun.file(join(dir,file));if(await handle.exists())return{file,text:await handle.text()}}return}async function read(dir,...files){for(let file of files){let handle=Bun.file(join(dir,file));if(await handle.exists())return handle.text()}return}async function loadCheckConfig(dir){let found=await readFirst(dir,CHECKRC_FILES);if(found===void 0)return;try{let parsed=Bun.JSONC.parse(found.text);if(parsed===null||typeof parsed!=="object"||Array.isArray(parsed))fail(`${found.file} must be a JSON object`);return parsed}catch(error){fail(`${found.file} is not valid JSONC: ${error instanceof Error?error.message:String(error)}`)}}function parseJsonManifest(file,text){try{let parsed=JSON.parse(text);return parsed!==null&&typeof parsed==="object"?parsed:{}}catch{fail(`${file} is not valid JSON`)}}function scriptsOf(manifest){let value=manifest.scripts;return value!==null&&typeof value==="object"?value:{}}function targets(text){return[...text.matchAll(TARGET)].map((match)=>match[1]??"")}async function recipes(dir,file,text){if(Bun.which("just")===null)return targets(text);try{let ran=await runCommand(["just","--justfile",file,"--dump","--dump-format","json"],{cwd:dir,timeoutMs:JUST_TIMEOUT_MS}),dump=JSON.parse(ran.text);if(ran.code!==0)return targets(text);return Object.entries(dump.recipes??{}).filter(([,recipe])=>recipe.private!==!0&&(recipe.parameters??[]).every((parameter)=>parameter.default!==null||parameter.kind==="star")).map(([name])=>name)}catch{return targets(text)}}async function miseTasks(dir){if(Bun.which("mise")===null||!MISE_FILES.some((name)=>existsSync(join(dir,name))))return[];try{let ran=await runCommand(["mise","tasks","ls","--json"],{cwd:dir,timeoutMs:JUST_TIMEOUT_MS});if(ran.code!==0)return[];let root=`${resolve2(dir)}/`;return JSON.parse(ran.text).filter((task)=>!task.hide&&!task.global&&task.source.startsWith(root)).map((task)=>task.name)}catch{return[]}}function callsSelf(value,bin){return typeof value==="string"&&(value===bin||value.startsWith(`${bin} `)||value.startsWith(`${bin} `))}async function candidates(dir,bin,includeNative=!1){let steps=[],packageJson=await read(dir,"package.json"),composerJson=await read(dir,"composer.json"),denoFile=await readFirst(dir,DENO_FILES),justfile=await readFirst(dir,JUSTFILES),makefile=await read(dir,...MAKEFILES),taskfile=await readFirst(dir,TASKFILES),pyprojectText=await read(dir,"pyproject.toml");if(packageJson!==void 0){let manifest=parseJsonManifest("package.json",packageJson),tool=manager(dir,manifest);for(let[name,value]of Object.entries(scriptsOf(manifest)))if(!callsSelf(value,bin))steps.push({name,command:`${tool} run ${name}`,source:"package.json"})}if(composerJson!==void 0){let manifest=parseJsonManifest("composer.json",composerJson);for(let name of Object.keys(scriptsOf(manifest)))steps.push({name,command:`composer run ${name}`,source:"composer.json"})}if(denoFile!==void 0)try{let parsed=Bun.JSONC.parse(denoFile.text);for(let name of Object.keys(parsed?.tasks??{}))steps.push({name,command:`deno task ${name}`,source:denoFile.file})}catch{}if(justfile!==void 0)for(let name of await recipes(dir,justfile.file,justfile.text))steps.push({name,command:`just ${name}`,source:"Justfile"});for(let name of targets(makefile??""))steps.push({name,command:`make ${name}`,source:"Makefile"});if(taskfile!==void 0)try{let parsed=Bun.YAML.parse(taskfile.text);for(let[name,task]of Object.entries(parsed?.tasks??{}))if(!(task!==null&&typeof task==="object"&&task.internal===!0))steps.push({name,command:`task ${name}`,source:"Taskfile"})}catch{}for(let name of await miseTasks(dir))steps.push({name,command:`mise run ${name}`,source:"mise"});if(pyprojectText!==void 0)try{let parsed=Bun.TOML.parse(pyprojectText),runner=existsSync(join(dir,"uv.lock"))?"uv run poe":"poe";for(let name of Object.keys(parsed.tool?.poe?.tasks??{}))if(!name.startsWith("_"))steps.push({name,command:`${runner} ${name}`,source:"pyproject.toml"})}catch{}if(steps.push(...await phpSteps(dir)),includeNative)steps.push(...await nativeSteps(dir,pyprojectText));return steps}async function firstFile(dir,names){for(let name of names)if(await Bun.file(join(dir,name)).exists())return name;return}async function phpSteps(dir){let steps=[],phpstan=await firstFile(dir,PHPSTAN_CONFIGS),csFixer=await firstFile(dir,CS_FIXER_CONFIGS),phpunit=await firstFile(dir,PHPUNIT_CONFIGS);if(phpstan!==void 0)steps.push({name:"typecheck",command:"vendor/bin/phpstan analyse --no-progress --memory-limit=1G",source:phpstan});if(csFixer!==void 0)steps.push({name:"lint",command:"vendor/bin/php-cs-fixer fix --dry-run -v",source:csFixer});if(phpunit!==void 0)steps.push({name:"test",command:"vendor/bin/phpunit",source:phpunit});return steps}async function nativeSteps(dir,pyprojectText){let steps=[];if(existsSync(join(dir,"go.mod")))steps.push({name:"lint",command:"go vet ./...",source:"go.mod"}),steps.push({name:"test",command:"go test ./...",source:"go.mod"});if(existsSync(join(dir,"Cargo.toml")))steps.push({name:"check",command:"cargo check",source:"Cargo.toml"}),steps.push({name:"lint",command:"cargo clippy",source:"Cargo.toml"}),steps.push({name:"fmt:check",command:"cargo fmt -- --check",source:"Cargo.toml"}),steps.push({name:"test",command:"cargo test",source:"Cargo.toml"});let pyPrefix=existsSync(join(dir,"uv.lock"))?"uv run ":"",ruffFile=await firstFile(dir,RUFF_CONFIGS),hasRuff=ruffFile!==void 0||pyprojectText!==void 0&&RUFF_SECTION.test(pyprojectText),hasMypy=await firstFile(dir,MYPY_CONFIGS)!==void 0||pyprojectText!==void 0&&MYPY_SECTION.test(pyprojectText),hasPytest=await firstFile(dir,PYTEST_CONFIGS)!==void 0||pyprojectText!==void 0&&PYTEST_SECTION.test(pyprojectText);if(hasMypy)steps.push({name:"typecheck",command:`${pyPrefix}mypy .`,source:"mypy"});if(hasRuff){let source=ruffFile??"pyproject.toml";steps.push({name:"lint",command:`${pyPrefix}ruff check .`,source}),steps.push({name:"fmt:check",command:`${pyPrefix}ruff format --check .`,source})}if(hasPytest)steps.push({name:"test",command:`${pyPrefix}pytest`,source:"pytest"});return steps}function packageNameOf(dir){let file=join(dir,"package.json");if(!existsSync(file))return;try{let parsed=JSON.parse(readFileSync(file,"utf8"));return typeof parsed.name==="string"?parsed.name:void 0}catch{return}}async function resolveTargets(dir,targets){let known=folders(dir),projects=[],seen=new Set;for(let target of targets){let direct=resolve2(dir,target),matchedDir;if(existsSync(direct))matchedDir=direct;else{let hit=known.find((sub)=>sub===target||basename(sub)===target||packageNameOf(join(dir,sub))===target);if(hit!==void 0)matchedDir=join(dir,hit)}if(matchedDir===void 0)fail(`no path or workspace matching ${target}`);if(seen.has(matchedDir))continue;seen.add(matchedDir);let steps=await discover(matchedDir);if(steps.length===0)fail(`no check steps found in ${target}`);let rel=relative(dir,matchedDir);projects.push({...rel===""?{}:{name:rel},dir:matchedDir,steps})}return projects}async function discoverProjects(dir,targets){if(targets!==void 0&&targets.length>0)return resolveTargets(dir,targets);let own=await discover(dir);if(own.length>0)return[{dir,steps:own}];let projects=[],entries=await readdir(dir,{withFileTypes:!0}),ignored=ignoredFolders(["var","tmp"]),direct=entries.filter((entry)=>entry.isDirectory()&&!entry.name.startsWith(".")&&!ignored.has(entry.name)).map((entry)=>entry.name),subdirs=[...new Set([...direct,...workspaces(dir)])].filter((name)=>name!==".").toSorted((a,b)=>a.localeCompare(b));for(let sub of subdirs){let steps=await discover(join(dir,sub));if(steps.length>0)projects.push({name:sub,dir:join(dir,sub),steps})}return projects}async function discover(dir){let found=await candidates(dir,"check",!0),overrides=(await loadCheckConfig(dir))?.steps??{},runnerCheck=found.find((candidate)=>candidate.name==="check"&&TASK_RUNNERS.has(candidate.source)),base=STEP_NAMES.flatMap((name)=>{if(name in overrides){let custom=overrides[name];return custom===null||custom===void 0?[]:[{name,command:custom,source:".checkrc.json"}]}let step=name==="check"&&runnerCheck!==void 0?runnerCheck:(STEP_SOURCES[name]??[name]).map((each)=>found.find((candidate)=>candidate.name===each)).find((each)=>each!==void 0);return step===void 0?[]:[{...step,name}]});for(let[name,command]of Object.entries(overrides))if(!STEP_NAMES.includes(name)&&typeof command==="string"&&command!=="")base.push({name,command,source:".checkrc.json"});return base}var JUSTFILE=/^\.?justfile$/i,TASKFILES2=["Taskfile.yml","taskfile.yml","Taskfile.yaml","taskfile.yaml","Taskfile.dist.yml","taskfile.dist.yml","Taskfile.dist.yaml","taskfile.dist.yaml"],MISE_FILES2=["mise.toml",".mise.toml","mise.local.toml",".mise.local.toml","mise",".mise","mise-tasks",".mise-tasks",".config/mise.toml",".config/mise"],LOCKFILES=[["bun.lock","bun"],["bun.lockb","bun"],["pnpm-lock.yaml","pnpm"],["yarn.lock","yarn"],["package-lock.json","npm"]],QUALIFIED=/^([a-z]+):(?!:)(.+)$/,BLANKS=/\s+/,TRAILING_SLASHES=/\/+$/,VERSION_SUFFIX=/@.*/,LEADING_HASHES=/^#*/,INCLUDE=/^(?:-|s)?include[ \t]+([^#]+)/,GLOB_CHARS=/[*?[]/,installed=new Map;function has(tool){if(!installed.has(tool))installed.set(tool,Bun.which(tool)!==null);return installed.get(tool)}function list(dir){try{return readdirSync(dir)}catch{return[]}}function locate(dir,here,names){for(let current=dir;;current=join2(current,"..")){let found=names.find((name)=>existsSync2(join2(current,name)));if(found!==void 0)return join2(current,found);let absolute=resolvePath(current);if(!here||existsSync2(join2(current,".git"))||dirname(absolute)===absolute)return}}function children(dir="."){let ignored=ignoredFolders();return readdirSync(dir,{withFileTypes:!0}).filter((child)=>child.isDirectory()&&!child.name.startsWith(".")&&!ignored.has(child.name)).map((child)=>child.name).toSorted()}function build(base,items){return items.map((item)=>({...base,doc:null,parameters:[],...item}))}function text(value){if(typeof value==="string")return value;if(Array.isArray(value)&&value.every((line)=>typeof line==="string"))return value.join(`
3
- `);return Bun.YAML.stringify(value,null,2)??""}function field(value,key){let found=value!==null&&typeof value==="object"?value[key]:void 0;return typeof found==="string"?found:null}function recipes2(tree){return[...Object.values(tree.recipes).filter((recipe)=>!recipe.private),...Object.values(tree.modules).flatMap((module)=>recipes2(module))]}function justFlags(dir,here){if(here)return[];let file=list(dir).find((name)=>JUSTFILE.test(name));return file===void 0?void 0:["--justfile",join2(dir,file)]}function just(dir,here){let flags=justFlags(dir,here);if(flags===void 0||!has("just"))return[];let proc=Bun.spawnSync(["just",...flags,"--dump","--dump-format","json"],{stderr:"pipe"});if(!proc.success)return[];let items=recipes2(JSON.parse(proc.stdout.toString())).map((recipe)=>({name:recipe.namepath,doc:recipe.doc,parameters:recipe.parameters}));return build({kind:"just",tag:"just",runner:["just"],separated:!1,dir},items)}function targets2(source){let found=new Map,pending=null;for(let line of source.split(`
4
- `)){if(line.startsWith("\t"))continue;let[rule="",...rest]=line.split("#"),comment=rest.join("#").replace(LEADING_HASHES,"").trim()||null;if(rule.trim()===""){pending=line.startsWith("##")?comment:null;continue}let colon=rule.indexOf(":"),assignment=rule[colon+1]==="="||rule.slice(colon+1).startsWith(":=")||rule.slice(0,colon).includes("=");if(colon===-1||assignment){pending=null;continue}let doc=comment??pending;for(let name of rule.slice(0,colon).trim().split(BLANKS)){if(name.startsWith(".")||name.includes("%")||name.includes("$"))continue;if(!found.has(name))found.set(name,doc)}pending=null}return[...found].map(([name,doc])=>({name,doc}))}function show(source,target){let lines=source.split(`
5
- `),start=lines.findIndex((line)=>{let hash=line.indexOf("#"),rule=hash===-1?line:line.slice(0,hash),colon=rule.indexOf(":");return colon!==-1&&rule[colon+1]!=="="&&!rule.slice(0,colon).includes("=")&&rule.slice(0,colon).trim().split(BLANKS).includes(target)});if(start===-1)return target;let end=start+1;while(end<lines.length&&(lines[end].startsWith("\t")||lines[end].trim()===""))end++;return lines.slice(start,end).join(`
6
- `).trimEnd()}function withIncludes(source,dir,seen){return source.split(`
7
- `).map((line)=>{let match=INCLUDE.exec(line);if(!match)return line;return match[1].trim().split(BLANKS).flatMap((path)=>GLOB_CHARS.test(path)?[...new Bun.Glob(path).scanSync({cwd:dir})].sort():[path]).map((path)=>resolvePath(dir,path)).filter((file)=>!seen.has(file)&&existsSync2(file)).map((file)=>(seen.add(file),withIncludes(readFileSync2(file,"utf-8"),dir,seen))).join(`
8
- `)}).join(`
9
- `)}function make(dir){let file=MAKEFILES.find((name)=>existsSync2(join2(dir,name)));if(file===void 0)return[];let path=resolvePath(dir,file),source=withIncludes(readFileSync2(path,"utf-8"),dir,new Set([path]));return build({kind:"make",tag:"make",runner:["make"],separated:!1,dir},targets2(source).map((target)=>({...target,body:show(source,target.name)})))}function manager(dir,manifest){let declared=typeof manifest.packageManager==="string"?manifest.packageManager.replace(VERSION_SUFFIX,""):void 0,known=LOCKFILES.find(([,name])=>name===declared);if(known!==void 0)return known[1];for(let current=resolvePath(dir);;current=dirname(current)){let found=LOCKFILES.find(([file])=>existsSync2(join2(current,file)));if(found!==void 0)return found[1];if(dirname(current)===current)return"bun"}}function table(value){return value!==null&&typeof value==="object"?value:{}}function packageScripts(dir,here){let file=locate(dir,here,["package.json"]);if(file===void 0)return[];let manifest=JSON.parse(readFileSync2(file,"utf-8")),tool=manager(dirname(file),manifest),items=Object.entries(table(manifest.scripts)).map(([name,command])=>({name,body:text(command)}));return build({kind:"package",tag:tool,runner:[tool,"run"],separated:tool==="npm",dir:dirname(file)},items)}function composer(dir,here){let file=locate(dir,here,["composer.json"]);if(file===void 0)return[];let manifest=JSON.parse(readFileSync2(file,"utf-8")),descriptions=table(manifest["scripts-descriptions"]),items=Object.entries(table(manifest.scripts)).map(([name,command])=>({name,doc:field(descriptions,name),body:text(command)}));return build({kind:"composer",tag:"composer",runner:["composer","run"],separated:!0,dir:dirname(file)},items)}function deno(dir,here){let file=locate(dir,here,["deno.json","deno.jsonc"]);if(file===void 0)return[];let manifest=Bun.JSONC.parse(readFileSync2(file,"utf-8")),items=Object.entries(table(manifest.tasks)).map(([name,task])=>({name,doc:field(task,"description"),body:field(task,"command")??text(task)}));return build({kind:"deno",tag:"deno",runner:["deno","task"],separated:!1,dir:dirname(file)},items)}function taskfile(dir,here){let file=locate(dir,here,TASKFILES2);if(file===void 0)return[];let tasks=table(Bun.YAML.parse(readFileSync2(file,"utf-8"))?.tasks),items=Object.entries(tasks).filter(([,task])=>!(task!==null&&typeof task==="object"&&task.internal===!0)).map(([name,task])=>({name,doc:field(task,"desc")??field(task,"summary"),body:text(task)}));return build({kind:"task",tag:"task",runner:["task"],separated:!0,dir:dirname(file)},items)}function mise(dir,here){if(!has("mise")||!here&&!MISE_FILES2.some((name)=>existsSync2(join2(dir,name))))return[];let proc=Bun.spawnSync(["mise","tasks","ls","--json"],{cwd:dir,stderr:"pipe"});if(!proc.success)return[];let root=`${resolvePath(dir)}/`,items=JSON.parse(proc.stdout.toString()).filter((task)=>!task.hide&&(here||!task.global&&task.source.startsWith(root))).map((task)=>({name:task.name,doc:task.description||null,body:task.file??task.run.join(`
10
- `)}));return build({kind:"mise",tag:"mise",runner:["mise","run"],separated:!1,dir},items)}function pyproject(dir,here){let file=locate(dir,here,["pyproject.toml"]);if(file===void 0)return[];let manifest=Bun.TOML.parse(readFileSync2(file,"utf-8")),tool=table(manifest.tool),project=table(manifest.project),uv=locate(dirname(file),!0,["uv.lock"])!==void 0,poe=Object.entries(table(table(tool.poe).tasks)).filter(([name])=>!name.startsWith("_")).map(([name,task])=>({name,doc:field(task,"help"),body:field(task,"cmd")??field(task,"shell")??text(task)})),entryPoints=Object.entries(table(project.scripts)).map(([name,target])=>({name,body:text(target)}));return[...build({kind:"poe",tag:"poe",runner:uv?["uv","run","poe"]:["poe"],separated:!1,dir:dirname(file)},poe),...build({kind:"uv",tag:"uv",runner:["uv","run"],separated:!1,dir:dirname(file)},entryPoints)]}var READERS=[just,make,packageScripts,composer,deno,taskfile,mise,pyproject],READER_OF={just,make,package:packageScripts,composer,deno,task:taskfile,mise,poe:pyproject,uv:pyproject},MANIFEST_OF=new Map([[just,"justfile"],[make,"Makefile"],[packageScripts,"package.json"],[composer,"composer.json"],[deno,"deno.json"],[taskfile,"Taskfile.yml"],[mise,"mise.toml"],[pyproject,"pyproject.toml"]]);function readOr(read,fallback){try{return read()}catch{return fallback}}function workspaces(dir="."){let manifest=readOr(()=>JSON.parse(readFileSync2(join2(dir,"package.json"),"utf-8")),{}),declared=Array.isArray(manifest.workspaces)?manifest.workspaces:table(manifest.workspaces).packages,pnpm=readOr(()=>table(Bun.YAML.parse(readFileSync2(join2(dir,"pnpm-workspace.yaml"),"utf-8"))).packages,void 0),patterns=[declared,pnpm].flatMap((value)=>Array.isArray(value)?value.filter((pattern)=>typeof pattern==="string"):[]),excluded=patterns.filter((pattern)=>pattern.startsWith("!")).map((pattern)=>new Bun.Glob(pattern.slice(1)));return patterns.filter((pattern)=>!pattern.startsWith("!")).flatMap((pattern)=>[...new Bun.Glob(`${pattern.replace(TRAILING_SLASHES,"")}/package.json`).scanSync({cwd:dir})].map((file)=>dirname(file))).filter((found)=>!found.split("/").includes("node_modules")&&!excluded.some((glob)=>glob.match(found)))}function folders(dir="."){return[...new Set([...children(dir),...workspaces(dir)])].filter((found)=>found!==".")}function guarded(reader,dir,here,isWarned=!1){try{return reader(dir,here)}catch(error){if(isWarned)warn(`j: skipped ${join2(dir,MANIFEST_OF.get(reader)??"a manifest")}, it does not parse (${error instanceof Error?error.message:String(error)})`);return[]}}function everything(cwd="."){let here=READERS.flatMap((reader)=>guarded(reader,cwd,!0,!0)),below=folders(cwd).flatMap((dir)=>READERS.flatMap((reader)=>guarded(reader,cwd==="."?dir:join2(cwd,dir),!1,!0))),seen=new Set;return[...here,...below].filter((entry)=>{let id=`${entry.kind} ${entry.dir} ${entry.name}`,fresh=!seen.has(id);return seen.add(id),fresh})}function readKind(kind,dir){return guarded(READER_OF[kind],dir,dir===".").filter((entry)=>entry.kind===kind)}function key(entry){return entry.dir==="."?entry.name:`${entry.dir}/${entry.name}`}function id(entry){return`${entry.tag}:${key(entry)}`}function resolve(entries,named){let qualified=QUALIFIED.exec(named),tagged=qualified&&entries.some((entry)=>entry.tag===qualified[1])?qualified:void 0,pool=tagged?entries.filter((entry)=>entry.tag===tagged[1]):entries,rest=tagged?tagged[2]:named,exact=pool.filter((entry)=>key(entry)===rest);return exact.length>0?exact:pool.filter((entry)=>entry.name===rest)}function shortest(entries,entry){let found=resolve(entries,key(entry));return found.length===1&&found[0]===entry?key(entry):id(entry)}function signature(entry){return entry.parameters.map((parameter)=>parameter.default===null&&parameter.kind==="singular"?`<${parameter.name}>`:`[${parameter.name}]`).join(" ")}
11
- export{justFlags,everything,readKind,key,id,resolve,shortest,signature,STEP_NAMES,MAKEFILES,CS_FIXER_CONFIGS,read,loadCheckConfig,candidates,firstFile,discoverProjects};
@@ -1,2 +0,0 @@
1
- // @bun
2
- import{input2}from"./chunk-eg6m1ry1.js";import"./chunk-ngcnmctk.js";export{input2 as input};
package/dist/errs-cli.js DELETED
@@ -1,12 +0,0 @@
1
- #!/bin/sh
2
- // @bun 2>/dev/null; exec bun --no-env-file --config=/dev/null "$0" "$@"
3
- import{paint,warn,role,stripAnsi,printJson,readInput,jsonOption,fail,parse}from"./chunk-ngcnmctk.js";import{holdSignals,runCommand,runMain,place,argvIn,Stack,placeOptions,placeSettings,version}from"./chunk-898e3vv3.js";import{parseErrors,formatError,saveLog}from"./chunk-1rrfsren.js";import process2 from"process";import{relative}from"path";import process from"process";var usage=`errs [options] [log]
4
- errs [options] -- <command> [args...]
5
- errs --in <service> | --host -- <command> [args...]
6
-
7
- Prints one \`file:line:col: message (rule)\` line per error found in a tsc, eslint, bun test, vitest, playwright, phpunit, phpstan, php-cs-fixer, go, cargo, ruff or pytest log, or any \`file:line[:col]: error|warning: message\` line, read from a file, from stdin or from the output of the command run after --.
8
- The lines no format recognised are counted on stderr, never dropped, and a command's full output is saved to a log file whose path is printed with that count.
9
- A command runs inside the running compose service that bind-mounts the current folder and never starts one; --in picks the service, --host forces the host.`,EXITS=[[0,"no error was found and the command, if any, passed"],[1,"errors were found or the command failed"],[2,"a usage error"]],options={...placeOptions,severity:{type:"string",choices:["error","warning"],description:"show only errors or only warnings"},"group-by":{type:"string",choices:["file","rule"],description:"group diagnostics by file or rule"},summary:{type:"boolean",description:"print counts by severity, file and rule instead of every line"},unrecognised:{type:"boolean",short:"u",description:"also print lines no parser recognised"},json:jsonOption("{errors: [{tool, file, line, column, rule, severity, message, test?}], unrecognised, unrecognisedLines?, log?, code?}")};function display(file,cwd){let path=file.startsWith("/")?relative(cwd,file):file;return path.startsWith("..")?file:path}function printGrouped(errors,by,cwd){let groups=new Map;for(let error of errors){let key=by==="file"?display(error.file,cwd):error.rule??"(no rule)",list=groups.get(key)??[];list.push(error),groups.set(key,list)}let head=role(by==="file"?"path":"id",process.stdout),{dim}=paint(process.stdout);for(let[key,list]of[...groups.entries()].toSorted((a,b)=>b[1].length-a[1].length)){console.log(`${head(key)} ${dim(`(${list.length})`)}`);for(let error of list)console.log(` ${formatError(error,cwd)}`)}}function printSummary(errors,cwd){let errCount=errors.filter((e)=>e.severity==="error").length,warnCount=errors.filter((e)=>e.severity==="warning").length,files=new Set(errors.map((e)=>display(e.file,cwd))).size,byRule=new Map;for(let error of errors){let rule=error.rule??error.tool;byRule.set(rule,(byRule.get(rule)??0)+1)}console.log(`${errCount} ${errCount===1?"error":"errors"}, ${warnCount} ${warnCount===1?"warning":"warnings"} across ${files} ${files===1?"file":"files"}`);for(let[rule,count]of[...byRule.entries()].toSorted((a,b)=>b[1]-a[1]).slice(0,10))console.log(` ${String(count).padStart(4)} ${rule}`)}async function readInput2(command,run,settings,cwd){let[path]=command;if(!run&&(settings.service!==void 0||settings.host===!0))fail("--in and --host apply to a command run after --");if(!run&&(path===void 0||path==="-"))return{text:await readInput("-",{noStdin:"give a log, a command after --, or pipe the output on stdin"})};if(!run&&path!==void 0)return{text:await readInput(path),log:path};if(path===void 0)fail("give the command after --");let placement=await place(cwd,path,settings),down=placement===void 0?void 0:await new Stack().problem(placement);if(down!==void 0)fail(down,1);let held=holdSignals(),ran;try{ran=await runCommand(placement===void 0?command:argvIn(placement,command),{...placement===void 0?{}:{cwd:placement.composeDir},env:{...process.env,NO_COLOR:"1",FORCE_COLOR:"0"},onStart:(child)=>held.forward(child)})}catch(error){fail(`cannot run ${command[0]}: ${error instanceof Error?error.message:String(error)}`)}finally{held.release()}return{text:stripAnsi(ran.text),log:await saveLog(ran.output),code:ran.code}}async function errs(args,cwd=process.cwd()){let first=args[0],bare=first!==void 0&&!first.startsWith("-")&&!await Bun.file(first).exists()&&Bun.which(first)!==null,parsed=parse(bare?[]:args,usage,options,{exits:EXITS,rest:!0,replaces:"reading raw tsc, eslint, phpunit, phpstan or playwright logs, or grepping a test summary out of them",examples:[["errs -- bun run check","the type errors of a run"],["bun test 2>&1 | errs","the failed tests from stdin"],["errs -- vendor/bin/phpunit","each failed PHP test with its file and line"]]});if(parsed.positionals.length>1)fail(`give one log, or a command after --
10
-
11
- ${usage}`);let input=await readInput2(bare?args:parsed.rest??parsed.positionals,bare||parsed.rest!==void 0,placeSettings(parsed.values),cwd),{errors:allErrors,unrecognised,unrecognisedLines}=parseErrors(input.text),errors=parsed.values.severity===void 0?allErrors:allErrors.filter((error)=>error.severity===parsed.values.severity);if(parsed.values.json===!0)printJson({errors,unrecognised,...parsed.values.unrecognised===!0?{unrecognisedLines}:{},...input.log===void 0?{}:{log:input.log},...input.code===void 0?{}:{code:input.code}});else{if(parsed.values.summary===!0)printSummary(errors,cwd);else if(parsed.values["group-by"]!==void 0)printGrouped(errors,parsed.values["group-by"],cwd);else for(let error of errors)console.log(formatError(error,cwd));if(parsed.values.unrecognised===!0&&unrecognisedLines.length>0){console.log(`
12
- -- unrecognised (${unrecognisedLines.length}) --`);for(let line of unrecognisedLines)console.log(line)}else if(unrecognised>0)warn(`${unrecognised} ${unrecognised===1?"line":"lines"} not recognised`,input.log===void 0?void 0:`see ${input.log}`);if(errors.length===0&&input.code!==void 0&&input.code!==0)warn(`the command exited ${input.code} with no error recognised`,input.log===void 0?void 0:`see ${input.log}`)}return errors.length>0||(input.code??0)!==0?1:0}process2.exitCode=await runMain({name:"errs",version,run:async(args)=>errs(args)});