@kaynooo/cli-pkg 0.19.0 → 0.20.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.
- package/README.md +2 -2
- package/dist/chunk-1dgxf5yc.js +8 -0
- package/dist/chunk-1er903pe.js +2 -0
- package/dist/{chunk-ar5fvqaa.js → chunk-4ce5gab8.js} +1 -1
- package/dist/chunk-b20mawd6.js +9 -0
- package/dist/chunk-b90pc5k5.js +3 -0
- package/dist/chunk-enwetxvb.js +2 -0
- package/dist/chunk-m4pv8kkb.js +7 -0
- package/dist/{chunk-3h5n8vq4.js → chunk-nvadv55x.js} +1 -1
- package/dist/chunk-q0vmkwhm.js +2 -0
- package/dist/{chunk-gfs0qvpc.js → chunk-q460gr2v.js} +1 -1
- package/dist/chunk-q8pvz0vr.js +69 -0
- package/dist/{chunk-m8t5jkn0.js → chunk-t8dsdj0n.js} +3 -3
- package/dist/chunk-vdcfp18g.js +12 -0
- package/dist/{chunk-hqzyh4eh.js → chunk-ws3phmm3.js} +1 -1
- package/dist/{chunk-p2jx0wx5.js → chunk-wsfa4ft6.js} +1 -1
- package/dist/{chunk-sx5zkre9.js → chunk-wszz9dxa.js} +2 -2
- package/dist/cli.js +1 -1
- package/package.json +2 -2
- package/dist/chunk-0eb0ncqy.js +0 -10
- package/dist/chunk-1g1jb7hz.js +0 -2
- package/dist/chunk-4pzedt0v.js +0 -69
- package/dist/chunk-6eg316z7.js +0 -9
- package/dist/chunk-apxff06c.js +0 -3
- package/dist/chunk-eqa72d87.js +0 -2
- package/dist/chunk-fbz0xjzr.js +0 -2
- package/dist/chunk-jaeg6790.js +0 -7
- package/dist/chunk-mf8nk9vg.js +0 -8
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
// @bun
|
|
2
|
+
import process9 from"process";import{parseArgs}from"util";import process6 from"process";var ct=/[aeiou]y$/;var Ot=/(?:leaf|loaf|thief|wolf|half|calf|elf|sheaf|scarf|dwarf|hoof|wharf)$/,Gt=/(?:knife|life|wife)$/;function G(t,e,{plural:r,zero:n="singular"}={}){if(e===1||e===0&&n==="singular")return t;if(r!==void 0)return r;if(t.endsWith("y")&&!ct.test(t))return`${t.slice(0,-1)}ies`;if(t.endsWith("s")||t.endsWith("x")||t.endsWith("z")||t.endsWith("ch")||t.endsWith("sh"))return`${t}es`;if(Ot.test(t))return`${t.slice(0,-1)}ves`;return Gt.test(t)?`${t.slice(0,-2)}ves`:`${t}s`}function bo(t,e,{zero:r="plural",...n}={}){return`${t} ${G(e,t,{...n,zero:r})}`}var Nt=/\s+\S*$/,Y=/\s/;function Ao(t,e,r="..."){let{suffix:n="...",includeSuffix:s=!1,wordBoundary:o=!1}=typeof r==="string"?{suffix:r}:r;if(t.length<=e)return t;let l=Math.max(0,e),c=t.substring(0,Math.max(0,s?l-n.length:l));if(o&&!Y.test(t[c.length]??" "))c=c.replace(Nt,"")||c;if(o)c=c.trimEnd();return s?(c+n).slice(0,l):c+n}var be=new Map(["\u20AC","","\u201A","\u0192","\u201E","\u2026","\u2020","\u2021","\u02C6","\u2030","\u0160","\u2039","\u0152","","\u017D","","","\u2018","\u2019","\u201C","\u201D","\u2022","\u2013","\u2014","\u02DC","\u2122","\u0161","\u203A","\u0153","","\u017E","\u0178"].map((t,e)=>[t,128+e]).filter(([t])=>t));import process from"process";var MODES=new Set(["terminal","ci","agent","pipe"]),AGENT_VARIABLES=["CLAUDECODE","AI_AGENT","CODEX_SANDBOX","CODEX_CI","CURSOR_AGENT","OPENCODE","GEMINI_CLI","ANTIGRAVITY_AGENT"];function isSet(value){return value!==void 0&&value!==""&&value!=="0"&&value.toLowerCase()!=="false"}function outputMode(stream=process.stdout,env=process.env){let chosen=env.KIT_MODE;if(chosen!==void 0&&MODES.has(chosen))return chosen;if(AGENT_VARIABLES.some((name)=>isSet(env[name])))return"agent";if(stream.isTTY===!0)return"terminal";return isSet(env.CI)?"ci":"pipe"}function isHumanTerminal(stream=process.stdout,env=process.env){return outputMode(stream,env)==="terminal"}function isInteractive(streams=process,env=process.env){return streams.stdin?.isTTY===!0&&isHumanTerminal(streams.stderr??{},env)}import process5 from"process";var G2=/^[a-f0-9]+$/i;function b(r){let e=r.startsWith("#")?r.slice(1):r;if(!G2.test(e))return[0,0,0];if(e.length===3||e.length===4)return[Number.parseInt(e[0]+e[0],16),Number.parseInt(e[1]+e[1],16),Number.parseInt(e[2]+e[2],16)];if(e.length!==6&&e.length!==8)throw Error(`Invalid hex color length: ${e.length}`);return[Number.parseInt(e.slice(0,2),16),Number.parseInt(e.slice(2,4),16),Number.parseInt(e.slice(4,6),16)]}var B={reset:[0,0],bold:[1,22],dim:[2,22],italic:[3,23],underline:[4,24],inverse:[7,27],hidden:[8,28],strikethrough:[9,29],black:[30,39],red:[31,39],green:[32,39],yellow:[33,39],blue:[34,39],magenta:[35,39],cyan:[36,39],white:[37,39],gray:[90,39],grey:[90,39],blackBright:[90,39],redBright:[91,39],greenBright:[92,39],yellowBright:[93,39],blueBright:[94,39],magentaBright:[95,39],cyanBright:[96,39],whiteBright:[97,39],bgBlack:[40,49],bgRed:[41,49],bgGreen:[42,49],bgYellow:[43,49],bgBlue:[44,49],bgMagenta:[45,49],bgCyan:[46,49],bgWhite:[47,49],bgBlackBright:[100,49],bgRedBright:[101,49],bgGreenBright:[102,49],bgYellowBright:[103,49],bgBlueBright:[104,49],bgMagentaBright:[105,49],bgCyanBright:[106,49],bgWhiteBright:[107,49],rgb:(r,e,l,n="fg")=>[`${n==="fg"?38:48};2;${r};${e};${l}`,n==="fg"?39:49],hex:(r,e="fg")=>{let[l,n,c]=b(r);return[`${e==="fg"?38:48};2;${l};${n};${c}`,e==="fg"?39:49]},ansi256:(r,e="fg")=>[`${e==="fg"?38:48};5;${r}`,e==="fg"?39:49]},h=new Set(["","1","2","3","true"]);function C(r,e=globalThis.process?.env??{}){if(e.FORCE_COLOR!==void 0)return h.has(e.FORCE_COLOR);if(e.NO_COLOR!==void 0||e.NODE_DISABLE_COLORS!==void 0||e.TERM==="dumb")return!1;return r?.isTTY===!0}function f(r,e=[]){let l="",n="";for(let t=0,i=e.length;t<i;t++)l+=`\x1B[${e[t][0]}m`,n=`\x1B[${e[t][1]}m${n}`;let c=(t)=>C(r.stream??globalThis.process?.stdout,r.env)?l+t+n:t,g=new Map;return new Proxy(c,{get(t,i){let a=B[i];if(Array.isArray(a)){let s=g.get(i);if(s===void 0)s=f(r,[...e,a]),g.set(i,s);return s}if(typeof a==="function")return(...s)=>{let y=`${i}:${s.join(",")}`,u=g.get(y);if(u===void 0){if(g.size>=64)g.clear();u=f(r,[...e,a(...s)]),g.set(y,u)}return u};throw Error(`Unknown style: ${String(i)}`)}})}function Fe(r={}){return f(r)}var o=Fe();import{existsSync as existsSync3,readFileSync as readFileSync2,statSync as statSync2}from"fs";import{homedir as homedir2}from"os";import{join as join3,resolve as resolve2}from"path";import process4 from"process";import{existsSync}from"fs";import{dirname,join,resolve}from"path";import process2 from"process";function findUp(names,from=process2.cwd(),stop=()=>!1){let wanted=typeof names==="string"?[names]:names;for(let dir=resolve(from);;dir=dirname(dir)){let found=wanted.map((name)=>join(dir,name)).find((path)=>existsSync(path));if(found!==void 0)return found;if(stop(dir)||dirname(dir)===dir)return}}import{existsSync as existsSync2,mkdirSync,readFileSync,statSync,writeFileSync}from"fs";import{homedir}from"os";import{dirname as dirname2,isAbsolute,join as join2}from"path";import process3 from"process";var FILE_CACHE=new Map;function isRecord(value){return typeof value==="object"&&value!==null&&!Array.isArray(value)}function xdgFolder(value,fallback){return value!==void 0&&isAbsolute(value)?value:fallback}function configBase(where={}){let xdg=where.xdg??(where.home===void 0?process3.env.XDG_CONFIG_HOME:void 0);return xdgFolder(xdg,join2(where.home??homedir(),".config"))}function userConfigPath(bin,where={}){return join2(configBase(where),"kaynooo-cli",`${bin}.json`)}function mainConfigPath(where={}){let jsonc=join2(configBase(where),"kaynooo-cli","config.jsonc");return existsSync2(jsonc)?jsonc:userConfigPath("config",where)}function userConfigReadPath(bin,legacy=[],where={}){if(bin==="config")return mainConfigPath(where);let current=userConfigPath(bin,where);if(existsSync2(current))return current;let base=configBase(where);return legacy.map((parts)=>join2(base,...parts)).find((path)=>existsSync2(path))??current}function readCachedObject(path){let stat=statSync(path,{throwIfNoEntry:!1});if(stat===void 0||!stat.isFile())return FILE_CACHE.delete(path),{};let cached=FILE_CACHE.get(path);if(cached!==void 0&&cached.mtimeMs===stat.mtimeMs&&cached.size===stat.size)return cached.data;try{let parsed=Bun.JSONC.parse(readFileSync(path,"utf8")),data=isRecord(parsed)?parsed:{};return FILE_CACHE.set(path,{mtimeMs:stat.mtimeMs,size:stat.size,data}),data}catch{return{}}}function readMainConfig(where={}){return readCachedObject(mainConfigPath(where))}function readUserConfig(bin,where={},legacy=[]){if(bin==="config")return readMainConfig(where);let fileData=readCachedObject(userConfigReadPath(bin,legacy,where)),section=readMainConfig(where)[bin];return isRecord(section)?{...fileData,...section}:fileData}function toLinear(channel){let value=channel/255;return value<=0.04045?value/12.92:((value+0.055)/1.055)**2.4}var fromLinear=(value)=>Math.round(255*Math.min(1,Math.max(0,value<=0.0031308?value*12.92:1.055*value**0.4166666666666667-0.055)));function toOklab(hex){let[r,g,b]=[1,3,5].map((at)=>toLinear(Number.parseInt(hex.slice(at,at+2),16))),l=Math.cbrt(0.4122214708*r+0.5363325363*g+0.0514459929*b),m=Math.cbrt(0.2119034982*r+0.6806995451*g+0.1073969566*b),s=Math.cbrt(0.0883024619*r+0.2817188376*g+0.6299787005*b);return[0.2104542553*l+0.793617785*m-0.0040720468*s,1.9779984951*l-2.428592205*m+0.4505937099*s,0.0259040371*l+0.7827717662*m-0.808675766*s]}function fromOklab([lightness,a,b]){let l=(lightness+0.3963377774*a+0.2158037573*b)**3,m=(lightness-0.1055613458*a-0.0638541728*b)**3,s=(lightness-0.0894841775*a-1.291485548*b)**3;return`#${[4.0767416621*l-3.3077115913*m+0.2309699292*s,-1.2684380046*l+2.6097574011*m-0.3413193965*s,-0.0041960863*l-0.7034186147*m+1.707614701*s].map((channel)=>fromLinear(channel).toString(16).padStart(2,"0")).join("")}`}var ENDS=new Map;function blend(gradient,ratio){let key=gradient.join(),ends=ENDS.get(key);if(ends===void 0)ends=[toOklab(gradient[0]),toOklab(gradient[1])],ENDS.set(key,ends);let at=Math.min(1,Math.max(0,ratio)),[from,to]=ends;return fromOklab(from.map((start,index)=>start+(to[index]-start)*at))}function gradientAt(theme,ratio){return theme.gradient===void 0?void 0:blend(theme.gradient,ratio)}var DEFAULT={colors:{accent:"cyan",id:"yellow",path:"blue",label:"dim",value:"bold",ok:"green",warn:"yellow",problem:"red",note:"dim",plan:"magenta",passed:"green",failed:"red",running:"cyan",queued:"yellow",skipped:"dim"},glyphs:{ok:"\u2713",warn:"\u25B2",problem:"\u2717",note:"\u203A",plan:"\u25C7",passed:"\u2713",failed:"\u2717",running:"\u25CF",queued:"\u25CB",skipped:"-",bar:"\u2501",rule:"\u2500",corner:"\u256D",open:"\u2022",leaf:"\xB7",guide:"\u2502"},accents:["cyan","magenta","green","blue","yellow","redBright"],bins:{},gradient:["#c084fc","#67e8f9"]},BRIGHT={accent:"cyanBright",id:"yellowBright",path:"blueBright",label:"white",value:"bold whiteBright",ok:"greenBright",warn:"yellowBright",problem:"redBright",note:"white",plan:"magentaBright",passed:"greenBright",failed:"redBright",running:"cyanBright",queued:"yellowBright",skipped:"white"},LIGHT={accent:"#0369a1",id:"#b45309",path:"#1d4ed8",label:"#52525b",value:"bold",ok:"#15803d",warn:"#b45309",problem:"#b91c1c",note:"#52525b",plan:"#7e22ce",passed:"#15803d",failed:"#b91c1c",running:"#0369a1",queued:"#b45309",skipped:"#52525b"},MONO={accent:"bold",id:"bold",path:"underline",label:"dim",value:"bold",ok:"bold",warn:"bold",problem:"bold",note:"dim",plan:"dim",passed:"bold",failed:"bold",running:"bold",queued:"dim",skipped:"dim"},ASCII={ok:"+",warn:"!",problem:"x",note:">",plan:"?",passed:"+",failed:"x",running:"*",queued:"o",skipped:"-",bar:"#",rule:"-",corner:"+",open:"*",leaf:"-",guide:"|"},PRESETS={default:{},"high-contrast":{colors:BRIGHT,accents:["cyanBright","magentaBright","greenBright","blueBright","yellowBright","redBright"],gradient:["#d8b4fe","#a5f3fc"]},light:{colors:LIGHT,accents:["#0369a1","#7e22ce","#15803d","#1d4ed8","#b45309","#b91c1c"],gradient:["#7c3aed","#0284c7"]},mono:{colors:MONO,accents:["bold"],gradient:void 0},ascii:{glyphs:ASCII}},STYLES=new Set(["bold","dim","italic","underline","inverse","strikethrough","black","red","green","yellow","blue","magenta","cyan","white","gray","grey","blackBright","redBright","greenBright","yellowBright","blueBright","magentaBright","cyanBright","whiteBright"]),HEX=/^#[0-9a-f]{6}$/i,CONTROL=/\p{Cc}/u,MAX_FILE_BYTES=65536,SPACES=/\s+/;function isColorSpec(spec){if(typeof spec==="number")return Number.isInteger(spec)&&spec>=0&&spec<=255;return typeof spec==="string"&&spec.trim()!==""&&spec.trim().split(SPACES).every((token)=>STYLES.has(token)||HEX.test(token))}var CUBE=[0,95,135,175,215,255];function cubeLevel(channel){return CUBE.reduce((best,value,level)=>Math.abs(value-channel)<Math.abs(CUBE[best]-channel)?level:best,0)}function nearest256(hex){let rgb=[1,3,5].map((at)=>Number.parseInt(hex.slice(at,at+2),16)),levels=rgb.map(cubeLevel),cube=levels.map((level)=>CUBE[level]),grey=Math.min(23,Math.max(0,Math.round((rgb.reduce((sum,channel)=>sum+channel,0)/3-8)/10))),greyValue=8+grey*10,distance=(colour)=>colour.reduce((sum,channel,at)=>sum+(channel-rgb[at])**2,0);return distance([greyValue,greyValue,greyValue])<distance(cube)?232+grey:16+36*levels[0]+6*levels[1]+levels[2]}function hasTrueColor(env){return env.COLORTERM==="truecolor"||env.COLORTERM==="24bit"}function tinted(colors,spec,env=process4.env){if(typeof spec==="number")return colors.ansi256(spec);return spec.trim().split(SPACES).reduce((chain,token)=>{if(HEX.test(token))return hasTrueColor(env)?chain.hex(token):chain.ansi256(nearest256(token));return chain[token]??chain},colors)}function shaded(theme,colors,glyph,cells,width,env=process4.env,{color,gradient}={}){return Array.from({length:cells},(_,index)=>{let at=width<=1?0:index/(width-1),spec=gradient===void 0?color??gradientAt(theme,at)??theme.colors.accent:blend(gradient,at);return tinted(colors,spec,env)(glyph)}).join("")}function isRecord2(value){return typeof value==="object"&&value!==null&&!Array.isArray(value)}function readThemeFile(path,warn){try{let stat=statSync2(path,{throwIfNoEntry:!1});if(stat===void 0)return;if(!stat.isFile()||stat.size>MAX_FILE_BYTES){warn(`${path} is not a regular file under ${MAX_FILE_BYTES/1024} KiB, theme ignored`);return}let parsed=Bun.JSONC.parse(readFileSync2(path,"utf8"));if(isRecord2(parsed))return parsed;warn(`${path} is not a JSON object, theme ignored`)}catch(error){warn(`${path} does not parse (${error instanceof Error?error.message:String(error)}), theme ignored`)}return}function applyPreset(theme,name,warn,where){if(name===void 0)return;if(typeof name!=="string"||!Object.hasOwn(PRESETS,name)){warn(`${where}: no preset ${String(name)}, one of ${Object.keys(PRESETS).join(", ")}`);return}let preset=PRESETS[name];if(Object.assign(theme.colors,preset.colors),Object.assign(theme.glyphs,preset.glyphs),preset.accents!==void 0)theme.accents=[...preset.accents];if(Object.hasOwn(preset,"gradient"))theme.gradient=preset.gradient;return name}function applyFile(theme,file,where,warn){if(isRecord2(file.colors))for(let[key,value]of Object.entries(file.colors))if(!Object.hasOwn(DEFAULT.colors,key))warn(`${where}: no colour ${key}, one of ${Object.keys(DEFAULT.colors).join(", ")}`);else if(!isColorSpec(value))warn(`${where}: colour ${key} is not an ANSI name, \`#rrggbb\` or a number up to 255`);else theme.colors[key]=value;if(isRecord2(file.glyphs))for(let[key,value]of Object.entries(file.glyphs))if(!Object.hasOwn(DEFAULT.glyphs,key))warn(`${where}: no glyph ${key}, one of ${Object.keys(DEFAULT.glyphs).join(", ")}`);else if(typeof value!=="string"||CONTROL.test(value)||Bun.stringWidth(value)!==1)warn(`${where}: glyph ${key} must be one visible character wide, with no control character`);else theme.glyphs[key]=value;if(Array.isArray(file.accents)&&file.accents.length>0&&file.accents.every(isColorSpec))theme.accents=[...file.accents];else if(file.accents!==void 0)warn(`${where}: accents must be a non-empty list of colours`);if(file.gradient===null)theme.gradient=void 0;else if(Array.isArray(file.gradient)&&file.gradient.length===2&&file.gradient.every((end)=>typeof end==="string"&&HEX.test(end)))theme.gradient=[file.gradient[0],file.gradient[1]];else if(file.gradient!==void 0)warn(`${where}: gradient must be two \`#rrggbb\` colours, or null for none`);if(isRecord2(file.bins))for(let[bin,value]of Object.entries(file.bins))if(isColorSpec(value))theme.bins[bin]=value;else warn(`${where}: bin ${bin} has no valid colour`)}function endsWalk(home){return(dir)=>dir===resolve2(home)||existsSync3(join3(dir,".git"))}var warned=new Set;function warnOnce(message){if(warned.has(message))return;warned.add(message),process4.stderr.write(`warning: theme ${message}
|
|
3
|
+
`)}function isPath(chosen){return chosen.includes("/")||chosen.endsWith(".json")}function loadTheme({env=process4.env,from=process4.cwd(),home=homedir2(),warn=warnOnce}={}){let theme={colors:{...DEFAULT.colors},glyphs:{...DEFAULT.glyphs},accents:[...DEFAULT.accents],bins:Object.create(null),gradient:DEFAULT.gradient},sources=[],chosen=env.KIT_THEME??"",wanted=chosen===""?[userConfigPath("theme",{home,xdg:env.XDG_CONFIG_HOME}),findUp(join3(".kaynooo","theme.json"),from,endsWalk(home))]:[];if(isPath(chosen))wanted.push(resolve2(from,chosen));let files=[];if(chosen===""){let mainTheme=readMainConfig({home,xdg:env.XDG_CONFIG_HOME}).theme;if(isRecord2(mainTheme))files.push({path:`${mainConfigPath({home,xdg:env.XDG_CONFIG_HOME})}#theme`,file:mainTheme})}for(let path of wanted){let file=path===void 0?void 0:readThemeFile(path,warn);if(path!==void 0&&file!==void 0)files.push({path,file})}let preset="default";if(chosen!==""&&!isPath(chosen))preset=applyPreset(theme,chosen,warn,"KIT_THEME")??preset;else{let named=files.findLast(({file})=>file.preset!==void 0);if(named!==void 0)preset=applyPreset(theme,named.file.preset,warn,named.path)??preset}for(let{path,file}of files)applyFile(theme,file,path,warn),sources.push(path);return{theme,sources,preset}}var current,currentKey="";function activeTheme(){let key=`${process4.cwd()}\x00${process4.env.KIT_THEME??""}\x00${process4.env.XDG_CONFIG_HOME??""}`;if(current===void 0||key!==currentKey)current=loadTheme(),currentKey=key;return current}var MARK_WORDS={ok:"ok:",warn:"warning:",problem:"error:",note:"note:",plan:"would:"};function takesControlCodes(stream,env=process5.env){return stream.isTTY===!0&&(env.NO_COLOR===void 0||env.NO_COLOR==="")&&env.NODE_DISABLE_COLORS===void 0&&env.TERM!=="dumb"&&outputMode(stream,env)==="terminal"}function paint(stream,env=process5.env){let effective=env.NO_COLOR===""?{...env,NO_COLOR:void 0}:env;return Fe({stream:{isTTY:takesControlCodes(stream,env)},env:effective})}function marked(mark,text,stream,detail,env=process5.env){let colors=paint(stream,env),head=MARK_WORDS[mark];if(takesControlCodes(stream,env)){let{theme}=activeTheme();head=tinted(colors.bold,theme.colors[mark],env)(theme.glyphs[mark])}return`${head} ${text}${detail===void 0?"":` ${colors.dim(detail)}`}`}function writeErr(text=""){process5.stderr.write(`${text}
|
|
4
|
+
`)}function ok(text,detail){console.log(marked("ok",text,process5.stdout,detail))}function note(text,detail){console.log(marked("note",text,process5.stdout,detail))}function warn(text,detail){writeErr(marked("warn",text,process5.stderr,detail))}function problem(text,detail){writeErr(marked("problem",text,process5.stderr,detail))}function role(name,stream,env=process5.env){let colors=paint(stream,env);return takesControlCodes(stream,env)?tinted(colors,activeTheme().theme.colors[name],env):colors}var STATUS_WORDS={passed:["passed","success","succeeded","ok"],failed:["failed","failure","error","errored"],running:["running","in_progress","started","holding"],queued:["queued","waiting","pending","created","blocked","scheduled"],skipped:["skipped","cancelled","canceled","manual"]},STATUS_OF=new Map(Object.entries(STATUS_WORDS).flatMap(([status,words])=>words.map((word)=>[word,status])));var GRAPHEMES=new Intl.Segmenter;function distance(a,b){let left=[...a],right=[...b],before=[],previous=Array.from({length:right.length+1},(_,index)=>index);for(let[i,x]of left.entries()){let current=[i+1];for(let[j,y]of right.entries()){let cost=Math.min((previous[j+1]??0)+1,(current[j]??0)+1,(previous[j]??0)+(x===y?0:1));if(i>0&&j>0&&x===right[j-1]&&left[i-1]===y)cost=Math.min(cost,(before[j-1]??0)+1);current.push(cost)}before=previous,previous=current}return previous[right.length]??0}function closest(name,names){let started=names.find((known)=>known.startsWith(name));if(started!==void 0)return started;let[best]=names.map((known)=>({known,far:distance(name,known)})).sort((a,b)=>a.far-b.far);return best!==void 0&&best.far<=(name.length<4?1:2)?best.known:void 0}var ESC=String.fromCharCode(27),ESCAPE_CODE=new RegExp(`${ESC}(?:\\[[\\x30-\\x3F]*[\\x20-\\x2F]*[\\x40-\\x7E]|\\][^\\u0007${ESC}]*(?:\\u0007|${ESC}\\\\))`,"y"),RESET_STYLE=`${ESC}[0m`,CLOSE_LINK=`${ESC}]8;;${ESC}\\`;function wrapToWidth(text,width){let lines=[],current="";for(let word of text.split(" "))if(current!==""&&Bun.stringWidth(current)+1+Bun.stringWidth(word)>width)lines.push(current),current=word;else current=current===""?word:`${current} ${word}`;return current===""?lines:[...lines,current]}function cutToWidth(line,width,suffix=""){if(Bun.stringWidth(line)<=width)return line;let suffixWidth=suffix===""?0:Bun.stringWidth(suffix),room=Math.max(0,width-suffixWidth),kept="",index=0,styled=!1,linked=!1;while(index<line.length){ESCAPE_CODE.lastIndex=index;let escape=ESCAPE_CODE.exec(line);if(escape!==null){if(kept+=escape[0],escape[0].startsWith(`${ESC}]`))linked=!0;else styled=!0;index=ESCAPE_CODE.lastIndex;continue}let char=String.fromCodePoint(line.codePointAt(index)),columns=Bun.stringWidth(char);if(columns>room)break;kept+=char,room-=columns,index+=char.length}return`${kept}${styled?RESET_STYLE:""}${linked?CLOSE_LINK:""}${suffix}`}var UNITS=[["d",86400],["h",3600],["m",60],["s",1]];function formatSeconds(total){let rest=Math.max(0,Math.round(total)),amounts=UNITS.map(([unit,size])=>{let amount=Math.floor(rest/size);return rest-=amount*size,`${amount}${unit}`}),first=amounts.findIndex((amount)=>!amount.startsWith("0"));if(first===-1)return"0s";let next=amounts[first+1];return next===void 0||next.startsWith("0")?amounts[first]??"0s":`${amounts[first]} ${next}`}function formatDuration(ms){return ms<60000?`${(Math.max(0,ms)/1000).toFixed(1)}s`:formatSeconds(ms/1000)}function formatElapsed(ms){return formatSeconds(Math.floor(Math.max(0,ms)/1000))}function upTo(text,separator){let end=text.indexOf(separator);return end===-1?text:text.slice(0,end)}function formatAge(date,now=Date.now()){let at=typeof date==="number"?date:Date.parse(date);if(Number.isNaN(at))return"-";let seconds=(now-at)/1000;return seconds<60?"just now":`${upTo(formatSeconds(seconds)," ")} ago`}function truncate(text,width){return Ao(text,width,{suffix:"\u2026",includeSuffix:!0})}var LINE_BREAKS=/\s*\n\s*/g;function textWidth(text){return Bun.stringWidth(text)}function table(rows,{cellWidth,header=!1,align=[],fit,stream=process6.stdout,env=process6.env}={}){let cells=cellWidth===void 0?rows:rows.map((row)=>row.map((cell)=>truncate(cell.replaceAll(LINE_BREAKS," "),cellWidth)));if(outputMode(stream,env)==="agent")return cells.map((row)=>row.map((cell)=>Bun.stripANSI(cell).replaceAll(/[\t\r\n]+/g," ")).join("\t")).join(`
|
|
5
|
+
`);let widths=[];for(let row of cells)for(let[index,cell]of row.entries())widths[index]=Math.max(widths[index]??0,textWidth(cell));let shown=fit===void 0?cells:narrow(cells,widths,fit),colors=paint(stream,env),lines=shown.map((row)=>row.map((cell,index)=>{let width=widths[index]??0,gap=" ".repeat(Math.max(0,width-textWidth(cell)));if(align[index]==="right")return`${gap}${cell}`;return index===row.length-1?cell:`${cell}${gap}`}).join(" ").trimEnd()),rule=header&&takesControlCodes(stream,env)&&lines.length>1?[colors.dim(activeTheme().theme.glyphs.rule.repeat(Math.max(...lines.map(textWidth))))]:[];return lines.flatMap((line,index)=>header&&index===0?[colors.bold(line),...rule]:[line]).join(`
|
|
6
|
+
`)}function narrow(rows,widths,limit){let used=()=>widths.reduce((sum,width)=>sum+width,0)+2*Math.max(0,widths.length-1),floor=8;while(used()>limit){let widest=-1;for(let[index,width]of widths.entries())if(width>8&&width>(widths[widest]??0))widest=index;if(widest===-1)break;widths[widest]=Math.max(8,(widths[widest]??0)-(used()-limit))}return rows.map((row)=>row.map((cell,index)=>textWidth(cell)>(widths[index]??0)?cutToWidth(cell,widths[index]??0,"\u2026"):cell))}function jsonText(value,replacer,{stream=process6.stdout,env=process6.env}={}){return JSON.stringify(value,replacer,outputMode(stream,env)==="agent"?void 0:2)}function printJson(value){console.log(jsonText(value))}import process7 from"process";var OPTIONAL=/(?<!\x1B)\[[^\]]+\]/g,USAGE_PREFIX=/^usage:\s*/i,FULL_STOP=/\.$/,PROSE_MARKS=/`([^`\n]+)`|(?<![\w-])(--[a-z][\w-]*|-[a-z](?![\w-]))/gi;function usageLine(usage,colors=paint(process7.stdout),{summary:withSummary=!0}={}){let lines=usage.replace(USAGE_PREFIX,"").split(`
|
|
7
|
+
`),blank=lines.indexOf(""),synopses=blank===-1?lines:lines.slice(0,blank),details=blank===-1?[]:lines.slice(blank+1),colon=synopses[0].indexOf(": "),inline=synopses[0].slice(colon+2),summary=colon===-1?details.shift():`${inline.charAt(0).toUpperCase()}${inline.slice(1)}`;if(colon!==-1)synopses[0]=synopses[0].slice(0,colon);let head=`${colors.bold("Usage:")} ${synopses.map((line)=>line.replaceAll(OPTIONAL,(part)=>colors.dim(part))).join(`
|
|
8
|
+
`)}`,lead=summary===void 0||!withSummary?[]:["",colors.bold(prose(summary,colors))],rest=details.length===0?[]:["",...details.map((line)=>prose(line,colors))];return[head,...lead,...rest].join(`
|
|
9
|
+
`)}function prose(line,colors){if(colors.cyan("x")==="x")return line;return line.replaceAll(PROSE_MARKS,(match,code,flag)=>code===void 0?colors.cyan(flag??match):colors.bold(code))}function helpText(usage,options,colors=paint(process7.stdout),{examples=[],exits=[],bin,columns}={}){let{summary}=description(usage);return[...bin===void 0?[usageLine(usage,colors)]:[`${colors.bold(bin.name)} ${colors.dim(bin.version())}${summary===""?"":` ${summary}`}`,"",usageLine(usage,colors,{summary:!1})],"",colors.bold("Options:"),...optionRows(options,colors,columns),...exitRows(exits,colors),...exampleRows(examples,colors)].join(`
|
|
10
|
+
`)}function exitRows(exits,colors=paint(process7.stdout)){if(exits.length===0)return[];return["",`${colors.bold("Exit codes:")} ${exits.map(([code,meaning])=>`${colors.cyan(String(code))} ${meaning}`).join(", ")}`]}function wantsHelpJson(env=process7.env,argv){if(env.KIT_HELP==="json")return!0;if(argv===void 0)return!1;let end=argv.indexOf("--"),own=end===-1?argv:argv.slice(0,end);if(own.includes("--help=json"))return!0;return(own.includes("--help")||own.includes("-h")||own[0]==="help")&&own.includes("--json")}function description(usage,{examples=[],replaces,exits}={},options){let lines=usage.replace(USAGE_PREFIX,"").split(`
|
|
11
|
+
`),first=lines[0],colon=first.indexOf(": "),prose=lines[lines.indexOf("")+1]??"",fallback=lines.includes("")?`${prose.charAt(0).toLowerCase()}${prose.slice(1)}`.replace(FULL_STOP,""):"";return{synopsis:colon===-1?first:first.slice(0,colon),summary:colon===-1?fallback:first.slice(colon+2),...replaces===void 0?{}:{replaces},examples:examples.map((example)=>typeof example==="string"?{line:example}:{line:example[0],note:example[1]}),...exits===void 0?{}:{exits:exits.map(([code,meaning])=>({code,meaning}))},...options===void 0?{}:{options:Object.entries(options).map(([name,{short,description}])=>({name,...short===void 0?{}:{short},...description===void 0?{}:{description}}))}}}var MAX_AGENT_EXAMPLES=2;function exampleRows(examples,colors=paint(process7.stdout)){if(examples.length===0)return[];let shown=outputMode()==="agent"?examples.slice(0,MAX_AGENT_EXAMPLES):examples;return["",colors.bold("Examples:"),...shown.map((example)=>typeof example==="string"?` ${example}`:` ${example[0]} ${colors.dim(`# ${example[1]}`)}`)]}var MAX_INLINE_CHOICES=24;function optionRows(options,colors=paint(process7.stdout),columns){let rows=Object.entries(options).map(([name,option])=>{let short=option.short===void 0?" ":`${colors.cyan(`-${option.short}`)}, `,choices=option.choices?.join("|"),inline=choices!==void 0&&choices.length<=MAX_INLINE_CHOICES,named=inline?`<${choices}>`:"<value>",placeholder=option.optional===void 0?named:`[${named}]`,value=option.type==="string"?` ${colors.dim(placeholder)}`:"",described=choices===void 0||inline?option.description??"":[option.description,`one of ${option.choices.join(", ")}`].filter(Boolean).join("; ");return{flag:`${short}${colors.cyan(`--${name}`)}${value}`,width:`-x, --${name}`.length+(option.type==="string"?placeholder.length+1:0),description:described}}),width=Math.max(0,...rows.map((row)=>row.width)),indent=2+width+2,room=columns!==void 0&&columns-indent>=20?columns-indent:void 0;return rows.flatMap((row)=>{if(row.description==="")return[` ${row.flag}`];let wrapped=room===void 0?[row.description]:wrapToWidth(row.description,room),[first="",...rest]=wrapped;return[` ${row.flag}${" ".repeat(width-row.width)} ${colors.dim(first)}`,...rest.map((line)=>`${" ".repeat(indent)}${colors.dim(line)}`)]})}import{fstatSync}from"fs";import process8 from"process";var WHOLE=/^\d+$/;function wholeNumber(value,name,fallback,min=1){if(value===void 0)return fallback;let number=Number(value);if(!WHOLE.test(value)||!Number.isSafeInteger(number)||number<min)badUsage(`${name.startsWith("<")?name:`--${name}`} takes a whole number from ${min}, not ${value}`);return number}var BARE_DURATION=/^\d+(?:\.\d+)?$/,DURATION=/^(?:\d+(?:\.\d+)?(?:ms|min|[smhd]))+$/,DURATION_PART=/(\d+(?:\.\d+)?)(ms|min|[smhd])/g,UNIT_MS={ms:1,s:1000,m:60000,min:60000,h:3600000,d:86400000};function durationMs(text,unit){if(BARE_DURATION.test(text))return Number(text)*UNIT_MS[unit];if(!DURATION.test(text))return 0;let ms=0;for(let[,amount,part]of text.matchAll(DURATION_PART))ms+=Number(amount)*UNIT_MS[part];return ms}function duration(value,name,fallback,unit="s"){if(value===void 0)return fallback;let ms=durationMs(value.trim(),unit);if(ms<1)badUsage(`--${name} takes a duration such as 30s, 5m, 1h or 7d, not ${value}`);return ms}function isStdinPiped(){let stat=fstatSync(0);return stat.isFIFO()||stat.isFile()}async function readInput(path,{noStdin="nothing is piped on stdin"}={}){if(path==="-"){if(process8.stdin.isTTY)fail(noStdin);return Bun.stdin.text()}let file=Bun.file(path);if(!await file.exists())fail(`no file ${path}`);return file.text()}var DASHES=/^-+/;function jsonOption(holds){return{type:"boolean",description:holds===void 0?"print JSON":`print JSON: ${holds}`}}var EXIT=Symbol.for("@kaynooo/cli-kit/Exit");class Exit extends Error{code;hint;[EXIT]=!0;constructor(message,code,hint){super(message);this.code=code;this.hint=hint}static[Symbol.hasInstance](value){if(this!==Exit)return Function.prototype[Symbol.hasInstance].call(this,value);return typeof value==="object"&&value!==null&&value[EXIT]===!0}}function fail(message,code=2,hint){throw new Exit(message,code,hint)}class UsageError extends Exit{constructor(message,hint){super(message,2,hint)}}function badUsage(message){throw new UsageError(message)}class HelpShown extends Exit{constructor(){super("help shown",0)}}class Completing{options;positionals;candidates;constructor(options,positionals=[],candidates={}){this.options=options;this.positionals=positionals;this.candidates=candidates}}var completion={active:!1},heading={bin:void 0},OUTPUT_OPTIONS={color:{type:"string",choices:["auto","always","never"],description:"auto (the default) colours on a terminal alone"},plain:{type:"boolean",description:"plain text, no colour or spinner: --color never"}};function applyOutput(color,plain,env=process9.env){let when=plain===!0?"never":color??"auto";if(when==="auto")return;if(when!=="always"&&when!=="never")badUsage(`--color takes auto, always or never, not ${when}`);if(when==="always")env.FORCE_COLOR="1",delete env.NO_COLOR;else env.NO_COLOR="1",delete env.FORCE_COLOR}function parse(args,usage,options,settings={}){let output=Object.fromEntries(Object.entries(OUTPUT_OPTIONS).filter(([name])=>!(name in options))),all={...options,...output,help:{type:"boolean",short:"h",description:"show this help"}},listing=listed(all,settings.allowNegative===!0);if(completion.active)throw new Completing(listing,settings.positionals,settings.candidates);let{own,rest}=settings.trailing===!0?splitTrailing(args,all,settings.positionals?.length??0):splitRest(args,settings.rest===!0),helpJson=wantsHelpJson(process9.env,own),stripHelpJson=(arg)=>{if(arg==="--help=json")return["--help"];return arg==="--json"&&!("json"in options)?[]:[arg]},normalized=helpJson?own.flatMap(stripHelpJson):own,parsed;try{parsed=parseArgs({args:joinDashValues(withBare(withAliases(normalized,all),all),all),options:all,allowPositionals:!0,allowNegative:settings.allowNegative===!0,strict:!0})}catch(error){let message=parseError(error);throw new UsageError(message,nearestOption(message,all,settings.allowNegative===!0))}let values=parsed.values;if(applyOutput("color"in output?values.color:void 0,"plain"in output?values.plain:void 0),values.help===!0){let columns=takesControlCodes(process9.stdout)?process9.stdout.columns:void 0;throw console.log(helpJson?JSON.stringify(description(usage,settings,listing)):helpText(usage,listing,void 0,{...settings,bin:heading.bin,columns})),new HelpShown}if(checkChoices(parsed.values,all),checkConflicts(parsed.values,all),settings.positionals!==void 0)checkPositionals(parsed.positionals,settings.positionals);return{...parsed,values:parsed.values,positionals:parsed.positionals,rest}}function splitRest(args,passes){let separator=passes?args.indexOf("--"):-1;return{own:separator===-1?args:args.slice(0,separator),rest:separator===-1?void 0:args.slice(separator+1)}}function splitTrailing(args,options,count){let takesValue=(word)=>!word.includes("=")&&Object.entries(options).some(([name,{short,type}])=>type==="string"&&(word===`--${name}`||word===`-${short}`)),seen=0;if(count===0)return{own:args,rest:void 0};for(let at=0;at<args.length;at++){let word=args[at];if(word==="--")break;if(word.startsWith("-")){if(takesValue(word))at++;continue}if(seen++,seen===count)return{own:args.slice(0,at+1),rest:args.slice(at+1)}}return{own:args,rest:void 0}}function listed(options,allowNegative){if(!allowNegative)return options;return Object.fromEntries(Object.entries(options).flatMap(([name,option])=>{if(option.type!=="boolean"||option.negative===void 0)return[[name,option]];return[...option.description===void 0?[]:[[name,option]],[`no-${name}`,{type:"boolean",description:option.negative}]]}))}function withAliases(args,options){let named=new Map(Object.entries(options).flatMap(([name,{aliases=[]}])=>aliases.map((alias)=>[`--${alias}`,`--${name}`])));if(named.size===0)return args;let separator=args.indexOf("--");return[...(separator===-1?args:args.slice(0,separator)).map((arg)=>{let at=arg.indexOf("="),current=named.get(at===-1?arg:arg.slice(0,at));return current===void 0?arg:`${current}${at===-1?"":arg.slice(at)}`}),...separator===-1?[]:args.slice(separator)]}function withBare(args,options){let bare=new Map(Object.entries(options).flatMap(([name,{short,optional}])=>optional===void 0?[]:[[`--${name}`,optional],...short===void 0?[]:[[`-${short}`,optional]]]));if(bare.size===0)return args;let separator=args.indexOf("--"),own=separator===-1?args:args.slice(0,separator);return[...own.flatMap((arg,index)=>{let optional=bare.get(arg),next=own[index+1],value=next!==void 0&&(optional?.accepts===void 0?!next.startsWith("-"):optional.accepts.test(next));return optional===void 0||value?[arg]:[arg,optional.bare]}),...separator===-1?[]:args.slice(separator)]}function checkConflicts(values,options){let given=(name)=>values[name]!==void 0&&values[name]!==!1;for(let[name,{conflicts=[]}]of Object.entries(options)){let other=given(name)?conflicts.find(given):void 0;if(other!==void 0)badUsage(`--${name} cannot be used with --${other}`)}}function checkChoices(values,options){for(let[name,option]of Object.entries(options)){if(option.choices===void 0)continue;let given=values[name];for(let value of Array.isArray(given)?given:[given])if(typeof value==="string")oneOf(value,name,option.choices)}}function oneOf(value,name,choices){if(!choices.includes(value))badUsage(`${name.startsWith("<")?name:`--${name}`} takes one of ${choices.join(", ")}, not ${value}`);return value}function checkPositionals(given,names){let variadic=names.at(-1)?.replace("]","").endsWith("...")===!0,required=names.filter((name)=>!name.startsWith("[")).length;if(given.length<required)badUsage(`missing ${names[given.length]}`);if(!variadic&&given.length>names.length)badUsage(`unexpected argument ${given[names.length]}`)}function joinDashValues(args,options){let longOf=new Map(Object.entries(options).flatMap(([name,option])=>option.short===void 0?[[`--${name}`,name]]:[[`--${name}`,name],[`-${option.short}`,name]])),isOption=(arg)=>arg==="--"||longOf.has(arg.includes("=")?arg.slice(0,arg.indexOf("=")):arg),joined=[];for(let i=0;i<args.length;i++){let arg=args[i]??"";if(arg==="--")return[...joined,...args.slice(i)];let name=longOf.get(arg),next=args[i+1];if(name!==void 0&&options[name]?.type==="string"&&next!==void 0&&next.startsWith("-")&&next!=="-"&&!isOption(next))joined.push(`--${name}=${next}`),i++;else joined.push(arg)}return joined}function parseError(error){let message=upTo(error instanceof Error?error.message:String(error),". ");return`${message.charAt(0).toLowerCase()}${message.slice(1)}`}var UNKNOWN_OPTION=/^unknown option '(-[^']+)'/;function nearestOption(message,options,allowNegative){let typed=UNKNOWN_OPTION.exec(message)?.[1];if(typed===void 0)return;let word=typed.replace(DASHES,"");if(word.length<2&&!typed.startsWith("--"))return;let known=Object.entries(options).flatMap(([name,option])=>[...option.short===void 0?[]:[`-${option.short}`],`--${name}`,...allowNegative&&option.type==="boolean"?[`--no-${name}`]:[]]),meant=closest(word,known.map((flag)=>flag.replace(DASHES,"")));return meant===void 0?void 0:`did you mean ${known.find((flag)=>flag.replace(DASHES,"")===meant)}?`}import{homedir as homedir3}from"os";import{join as join4}from"path";import process10 from"process";var SKIPPED_FOLDERS=new Set(["node_modules","vendor","dist","build","target","coverage","venv","__pycache__"]);function ignoredFolders(extra=[],where={}){let configured=readUserConfig("config",where).ignore,names=Array.isArray(configured)?configured.filter((name)=>typeof name==="string"&&name!==""):[];return new Set([...SKIPPED_FOLDERS,...extra,...names])}function cacheFolder({home=homedir3(),env=process10.env}={}){return xdgFolder(env.XDG_CACHE_HOME,join4(home,".cache"))}
|
|
12
|
+
export{bo,outputMode,isInteractive,xdgFolder,userConfigPath,userConfigReadPath,readMainConfig,readUserConfig,tinted,shaded,activeTheme,takesControlCodes,paint,marked,writeErr,ok,note,warn,problem,role,distance,closest,cutToWidth,formatDuration,formatElapsed,formatAge,truncate,textWidth,table,printJson,usageLine,wantsHelpJson,description,exampleRows,optionRows,wholeNumber,duration,isStdinPiped,readInput,jsonOption,Exit,fail,UsageError,badUsage,HelpShown,Completing,completion,OUTPUT_OPTIONS,applyOutput,parse,oneOf,ignoredFolders,cacheFolder};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{printJson,jsonOption,parse,oneOf}from"./chunk-
|
|
2
|
+
import{printJson,jsonOption,parse,oneOf}from"./chunk-vdcfp18g.js";import"./chunk-q8pvz0vr.js";import{ACTIONS,detectManager,commandFor}from"./chunk-32n7yvx5.js";import process from"process";var usage=`pkg manager <install|dev|remove|update|exec>
|
|
3
3
|
|
|
4
4
|
Prints the command the package manager of this folder runs for the action: install is the add or install of a package, dev adds one as a dev dependency, remove drops one, update upgrades them and exec runs a package's bin without installing it. The manager is the one whose lockfile (bun.lock, bun.lockb, yarn.lock, pnpm-lock.yaml, package-lock.json, uv.lock) or composer.json is nearest, here or in a parent folder, bun when none is found.`,EXITS=[[0,"it printed the command"],[2,"a usage error"]],options={json:jsonOption("{manager, action, command}")};function manager(args){let{values,positionals}=parse(args,usage,options,{exits:EXITS,positionals:["<action>"],candidates:{"<action>":()=>[...ACTIONS]},replaces:"telling bun, yarn, pnpm, npm, composer and uv apart by their lockfile before typing an add, remove or dlx",examples:["pkg manager dev",["pkg manager exec","bunx, npx, pnpm dlx... for this folder"]]}),action=oneOf(positionals[0]??"","<action>",ACTIONS),found=detectManager(process.cwd()),command=commandFor(action,found);if(values.json===!0)printJson({manager:found,action,command});else console.log(command);return 0}export{manager};
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{isInteractive,paint,truncate,textWidth,fail,cacheFolder}from"./chunk-
|
|
2
|
+
import{isInteractive,paint,truncate,textWidth,fail,cacheFolder}from"./chunk-vdcfp18g.js";import process2 from"process";import{mkdirSync,readFileSync,writeFileSync}from"fs";import{dirname,join}from"path";var KEPT=50;function answersFile(){return join(cacheFolder(),"kaynooo-cli","answers.json")}function stored(){try{let parsed=JSON.parse(readFileSync(answersFile(),"utf-8"));if(typeof parsed!=="object"||parsed===null)return{};return Object.fromEntries(Object.entries(parsed).filter((entry)=>Array.isArray(entry[1])&&entry[1].every((answer)=>typeof answer==="string")))}catch{return{}}}function earlierAnswers(key){return stored()[key]??[]}function rememberAnswer(key,answer){let all=stored(),file=answersFile();all[key]=[answer,...(all[key]??[]).filter((earlier)=>earlier!==answer)].slice(0,KEPT);try{mkdirSync(dirname(file),{recursive:!0}),writeFileSync(file,JSON.stringify(all))}catch{}}import process from"process";function stopJob(){process.kill(0,"SIGTSTP")}var EDIT_KEYS=new Set(["left","right","wordleft","wordright","linestart","lineend","erase","delete","word","killword","killnext","clear","killend","yank"]),BACKWARD_KILLS=new Set(["word","killword","clear"]),FORWARD_KILLS=new Set(["killnext","killend"]);function isEditKey(key){return EDIT_KEYS.has(key)}function endsKills(key){return typeof key!=="object"&&!isEditKey(key)}var WORD_CHARACTER=/[\p{L}\p{N}_]/u,SPACE=/\s/;function isWord(char){return char!==void 0&&WORD_CHARACTER.test(char)}function wordStart(chars,from){let at=from;while(at>0&&!isWord(chars[at-1]))at--;while(at>0&&isWord(chars[at-1]))at--;return at}function wordEnd(chars,from){let at=from;while(at<chars.length&&!isWord(chars[at]))at++;while(at<chars.length&&isWord(chars[at]))at++;return at}function spacedStart(chars,from){let at=from;while(at>0&&SPACE.test(chars[at-1]??""))at--;while(at>0&&!SPACE.test(chars[at-1]??""))at--;return at}function cut(chars,from,to){return{text:[...chars.slice(0,from),...chars.slice(to)].join(""),caret:from}}function insert(chars,at,text){let typed=[...text];return{text:[...chars.slice(0,at),...typed,...chars.slice(at)].join(""),caret:at+typed.length}}function editLine(line,key){let{killed="",chained=!1}=line,chars=[...line.text],at=Math.min(Math.max(line.caret,0),chars.length),edited=edit(chars,at,key,killed);if(typeof key==="object"||!BACKWARD_KILLS.has(key)&&!FORWARD_KILLS.has(key))return line.killed===void 0?edited:{...edited,killed};let taken=chars.slice(edited.caret,edited.caret+chars.length-[...edited.text].length).join("");if(taken==="")return{...edited,killed,chained};if(!chained)return{...edited,killed:taken,chained:!0};return{...edited,killed:BACKWARD_KILLS.has(key)?taken+killed:killed+taken,chained:!0}}function edit(chars,at,key,killed){let text=chars.join("");if(typeof key==="object")return insert(chars,at,key.text);switch(key){case"left":return{text,caret:Math.max(at-1,0)};case"right":return{text,caret:Math.min(at+1,chars.length)};case"wordleft":return{text,caret:wordStart(chars,at)};case"wordright":return{text,caret:wordEnd(chars,at)};case"linestart":return{text,caret:0};case"lineend":return{text,caret:chars.length};case"erase":return cut(chars,Math.max(at-1,0),at);case"delete":return cut(chars,at,Math.min(at+1,chars.length));case"word":return cut(chars,spacedStart(chars,at),at);case"killword":return cut(chars,wordStart(chars,at),at);case"killnext":return cut(chars,at,wordEnd(chars,at));case"clear":return cut(chars,0,at);case"killend":return cut(chars,at,chars.length);case"yank":return insert(chars,at,killed)}}function visible({text,caret},room){let chars=[...text],at=Math.min(Math.max(caret,0),chars.length),cells=at===chars.length?[...chars," "]:chars,widths=cells.map((char)=>Bun.stringWidth(char)),width=(from,to)=>widths.slice(from,to).reduce((sum,size)=>sum+size,0),fits=(from,to)=>(from>0?1:0)+width(from,to)+(to<cells.length?1:0)<=room,start=at,end=at+1;while(start>0&&fits(start-1,end))start--;while(end<cells.length&&fits(start,end+1))end++;let left=start>0?"\u2026":"",right=end<cells.length?"\u2026":"";return{before:left+chars.slice(start,at).join(""),at:chars[at],after:chars.slice(at+1,end).join("")+right,column:left.length+width(start,at)}}var BOUNDARY_AFTER=new Set([" ","/","-","_",".",":","\\","(","[",",","\t"]),UPPER=/\p{Lu}/u,LOWER=/\p{Ll}/u,NONE=Number.NEGATIVE_INFINITY;function startsWord(text,index){if(index===0)return!0;let before=text[index-1];return BOUNDARY_AFTER.has(before)||LOWER.test(before)&&UPPER.test(text[index])}function fuzzy(query,text){if(query==="")return{score:0,positions:[]};let exact=query!==query.toLowerCase(),needle=exact?query:query.toLowerCase(),haystack=exact?text:text.toLowerCase();if(haystack.length!==text.length||needle.length>haystack.length)return;let width=haystack.length,best=Array.from({length:needle.length},()=>Array(width).fill(NONE)),from=Array.from({length:needle.length},()=>Array(width).fill(-1));for(let j=0;j<needle.length;j++){let run=NONE,runAt=-1;for(let i=j;i<width;i++){if(j>0&&i-2>=j-1){let candidate=best[j-1][i-2]+(i-2)*1;if(candidate>run)run=candidate,runAt=i-2}if(haystack[i]!==needle[j])continue;let here=16+(startsWord(text,i)?10:0)+(i===0?8:0);if(j===0){best[0][i]=here-i*1;continue}let joined=best[j-1][i-1]+12,skipped=run-(i-1)*1;if(joined>NONE&&joined>=skipped)best[j][i]=joined+here,from[j][i]=i-1;else if(skipped>NONE)best[j][i]=skipped+here,from[j][i]=runAt}}let last=best[needle.length-1],end=-1;for(let i=0;i<width;i++)if(last[i]>NONE&&(end===-1||last[i]>last[end]))end=i;if(end===-1)return;let positions=[];for(let j=needle.length-1,i=end;j>=0;j--)positions.unshift(i),i=from[j][i];return{score:last[end],positions}}function rank(query,lines){if(query==="")return lines.map((_,index)=>({index,positions:[]}));let found=[];for(let[index,line]of lines.entries()){let match=fuzzy(query,line);if(match!==void 0)found.push({index,positions:match.positions,score:match.score})}return found.sort((a,b)=>b.score-a.score||lines[a.index].length-lines[b.index].length||a.index-b.index)}var IS_CONTROL=/[\x00-\x1F\x7F-\x9F]/;var PASTE_START="\x1B[200~",PASTE_END="\x1B[201~",KEY_SEQUENCES=/\x1B\[<[0-9;]*[A-Za-z]|\x1B\[[0-9;]*[A-Z~]|\x1BO[A-Z]|\x1B[\s\S]|[\s\S]/gu,MOUSE=/^\x1B\[<(\d+);\d+;\d+[a-z]$/i,WHEEL_LINES=3,KEYS={"\x1B[A":"up","\x1BOA":"up","\x10":"up","\x1B[B":"down","\x1BOB":"down","\x0E":"down","\x1B[5~":"pageup","\x1B[6~":"pagedown","\x1B[H":"home","\x1B[1~":"home","\x1BOH":"home","\x1B[F":"end","\x1B[4~":"end","\x1BOF":"end","\r":"enter","\n":"enter","\x03":"cancel","\x1B":"cancel","\x1B[D":"left","\x1BOD":"left","\x1B[C":"right","\x1BOC":"right","\x1B[1;5D":"wordleft","\x1B[1;3D":"wordleft","\x1Bb":"wordleft","\x1B[1;5C":"wordright","\x1B[1;3C":"wordright","\x1Bf":"wordright","\x01":"linestart","\x05":"lineend","\x7F":"erase","\x1B[3~":"delete","\b":"killword","\x1B\x7F":"killword","\x1B[3;5~":"killnext","\x1Bd":"killnext","\x15":"clear","\v":"killend","\x17":"word","\x19":"yank","\x1A":"suspend","\t":"tab","\x1F":"help","\x1BOP":"help","\x1B[11~":"help"};function repeat(value,count){return Array.from({length:count}).fill(value)}function parseKeys(input,paste={active:!1},ctrls=[]){let codes=new Map(ctrls.map((name)=>[String.fromCharCode(name.codePointAt(name.length-1)-96),name]));return(input.match(KEY_SEQUENCES)??[]).flatMap((sequence)=>{let wheel=MOUSE.exec(sequence)?.[1];if(wheel!==void 0)return repeat(wheel==="64"?"up":"down",wheel==="64"||wheel==="65"?WHEEL_LINES:0);let named=codes.get(sequence),key=named===void 0?KEYS[sequence]:{ctrl:named};if(sequence===PASTE_START||sequence===PASTE_END)return paste.active=sequence===PASTE_START,[];if(paste.active&&(sequence==="\r"||sequence===`
|
|
3
3
|
`))return[];if(key!==void 0)return[key];return IS_CONTROL.test(sequence)||sequence.startsWith("\x1B")?[]:[{text:sequence}]})}var SYNC_START="\x1B[?2026h",SYNC_END="\x1B[?2026l";function overwrite(lines,columns){return lines.map((line)=>textWidth(line)%columns===0?`\x1B[2K${line}`:`${line}\x1B[K`).join(`
|
|
4
4
|
`)}function rowsTaken(lines,columns){return lines.reduce((rows,line)=>rows+Math.max(1,Math.ceil(textWidth(line)/columns)),0)}var MAX_ROWS=10,PROMPT_KEYS=new Set(["up","down","pageup","pagedown","home","end","enter","cancel","suspend","tab"]),MAX_LISTED=12;function readKeys(input,paste={active:!1}){return parseKeys(input,paste).filter((key)=>typeof key==="object"?"text"in key:PROMPT_KEYS.has(key)||isEditKey(key))}function roomAfter(question,columns){return Math.max(columns-textWidth(`? ${question} `)%columns-1,1)}function withCaret(colors,line,room,dim=!1){let{before,at,after}=visible(line,room),tone=dim?colors.dim:(text)=>text;return`${tone(before)}${at===void 0?colors.dim("\u2588"):colors.inverse(at)}${tone(after)}`}function flip(checked,value){let next=new Set(checked);if(!next.delete(value))next.add(value);return next}async function checklist2(question,choices,{initial=new Set,min=0,toggle=flip,...settings}){let list=new List(choices,0),checked=initial,invalid;return await ask(question,settings,(colors,state,rows)=>state==="asking"?[asking(colors,question,list.typed(colors,rows.columns,question),"type to filter, space toggles, enter accepts"),...list.rows(colors,rows,(choice)=>checked.has(choice.value)?`${colors.cyan("\u25C9")} `:`${colors.dim("\u25EF")} `),...invalid===void 0?[]:[` ${colors.red(invalid)}`]]:[answer(colors,question,state,choices.filter((choice)=>checked.has(choice.value)).map((choice)=>choice.label).join(", ")||"none")],(key)=>{if(key==="cancel")return key;if(invalid=void 0,key==="enter")return invalid=checked.size<min?`pick at least ${min}`:void 0,invalid===void 0?"enter":void 0;let current=list.current();if(typeof key==="object"&&key.text===" "){if(current!==void 0)checked=toggle(checked,current.value);return}list.press(key);return})?checked:void 0}async function confirm2(question,{default:fallback,...settings}){let answered=fallback,choices={true:"Y/n",false:"y/N",undefined:"y/n"}[String(fallback)];return await ask(question,settings,(colors,state)=>[state==="asking"?asking(colors,question,"",choices):answer(colors,question,state,answered?"yes":"no")],(key)=>{if(key==="cancel")return"cancel";if(key==="enter")return answered===void 0?void 0:"enter";let letter=typeof key==="object"?key.text.toLowerCase():"";if(letter!=="y"&&letter!=="n")return;return answered=letter==="y","enter"})?answered:void 0}function sharedStart(texts){let[first=[],...rest]=texts.map((text)=>[...text]),length=first.length;for(let chars of rest){let differs=chars.findIndex((char,index)=>char!==first[index]);length=Math.min(length,differs===-1?chars.length:differs)}return first.slice(0,length).join("")}function listed(colors,found,columns){let shared=sharedStart(found),cut=Math.max(shared.lastIndexOf("/"),shared.lastIndexOf(" "))+1,names=found.slice(0,MAX_LISTED).map((each)=>each.slice(cut)),more=found.length>MAX_LISTED?` \u2026 ${found.length-MAX_LISTED} more`:"";return` ${colors.dim(truncate(names.join(" ")+more,Math.max(columns-3,1)))}`}async function input2(question,{default:fallback,mask=!1,validate,history,complete,...settings}){let line={text:"",caret:0},invalid,completions=[],remembered=history===void 0||mask?void 0:history,earlier=remembered===void 0?[]:earlierAnswers(remembered),recalled=-1,draft=line,taken=()=>line.text===""?fallback??"":line.text,shown=()=>mask?"*".repeat([...taken()].length):taken();if(!await ask(question,settings,(colors,state,{columns})=>{if(state!=="asking")return[answer(colors,question,state,shown())];let typed=line.text===""?{text:shown(),caret:[...shown()].length}:{text:shown(),caret:line.caret};return[`${colors.cyan("?")} ${question} ${withCaret(colors,typed,roomAfter(question,columns),line.text==="")}`,...invalid===void 0?[]:[` ${colors.red(invalid)}`],...completions.length>1?[listed(colors,completions,columns)]:[]]},(key)=>{if(key==="cancel")return"cancel";if(invalid=void 0,completions=[],line.chained===!0&&endsKills(key))line={...line,chained:!1};if(key==="tab"){let chars=[...line.text],before=chars.slice(0,line.caret).join(""),found=complete?.(before)??[],filled=sharedStart(found);if([...filled].length>[...before].length)line={...line,text:filled+chars.slice(line.caret).join(""),caret:[...filled].length};else completions=found;return}if(key==="enter")return invalid=validate?.(taken()),invalid===void 0?"enter":void 0;if(key==="up"||key==="down"){let to=Math.min(Math.max(recalled+(key==="up"?1:-1),-1),earlier.length-1);if(recalled===-1)draft=line;recalled=to,line={...to===-1?draft:{text:earlier[to],caret:[...earlier[to]].length},killed:line.killed??""};return}let edit={home:"linestart",end:"lineend"}[key]??key;if(typeof edit==="object"||isEditKey(edit))line=editLine(line,edit);return}))return;if(remembered!==void 0&&taken()!=="")rememberAnswer(remembered,taken());return taken()}class List{choices;line={text:"",caret:0};matches;cursor;top=0;width;searchable;constructor(choices,initial){this.choices=choices;this.matches=choices,this.cursor=Math.min(Math.max(initial,0),choices.length-1),this.width=Math.max(0,...choices.map((choice)=>choice.label.length)),this.searchable=choices.map(({label,hint})=>`${label} ${hint}`.toLowerCase())}current(){return this.matches[this.cursor]}press(key){if(this.line.chained===!0&&endsKills(key))this.line={...this.line,chained:!1};if(key==="up"||key==="down"){if(this.matches.length>0)this.cursor=(this.cursor+(key==="up"?this.matches.length-1:1))%this.matches.length;return}if(key==="home"||key==="end"||key==="pageup"||key==="pagedown"){let last=this.matches.length-1,to={home:0,end:last,pageup:this.cursor-MAX_ROWS,pagedown:this.cursor+MAX_ROWS}[key];this.cursor=Math.max(0,Math.min(last,to));return}if(typeof key!=="object"&&!isEditKey(key))return;let edited=editLine(this.line,key);if(edited.text!==this.line.text)this.filter(edited.text);this.line=edited}typed(colors,columns,question){return this.line.text===""?"":withCaret(colors,this.line,roomAfter(question,columns))}filter(query){let trimmed=query.trim().toLowerCase(),current=this.current();this.matches=trimmed===""?this.choices:rank(trimmed,this.searchable).map(({index})=>this.choices[index]),this.cursor=current===void 0?0:Math.max(this.matches.indexOf(current),0),this.top=0}rows(colors,{columns,rows},marker){if(this.matches.length===0)return[colors.dim(" no match")];let height=Math.max(1,Math.min(MAX_ROWS,rows-3,this.matches.length));this.top=Math.min(Math.max(this.top,this.cursor-height+1),this.cursor);let shown=this.matches.slice(this.top,this.top+height).map((choice,index)=>{let here=this.top+index===this.cursor,mark=marker(choice),head=`${here?"\u276F":" "} ${mark}`,label=choice.label.padEnd(this.width),room=columns-5-(mark===""?0:2)-this.width;return`${here?colors.cyan(head):head}${here?colors.cyan(label):label} ${colors.dim(truncate(choice.hint,Math.max(room,0)))}`}),below=this.matches.length-this.top-height;return[...this.top>0?[colors.dim(` \u2026 ${this.top} more`)]:[],...shown,...below>0?[colors.dim(` \u2026 ${below} more`)]:[]]}}function asking(colors,question,typed,keys){return`${colors.cyan("?")} ${question} ${typed===""?colors.dim(`(${keys})`):typed}`}function answer(colors,question,state,picked){return state==="enter"?`${colors.green("\u2713")} ${question} ${colors.cyan(picked)}`:`${colors.red("\u2717")} ${question} ${colors.dim("cancelled")}`}async function ask(question,{hint,terminal=process2},render,press){let{stdin,stderr}=terminal;if(!isInteractive(terminal))fail(`cannot ask "${question}" off a terminal`,2,hint);let colors=paint(stderr),current="asking",outcome,columns=()=>stderr.columns||80,draw=(state,last=!1)=>{let frame=render(colors,state,{columns:columns(),rows:stderr.rows||24}),rows=rowsTaken(frame,columns());stderr.write(`${SYNC_START}\r${overwrite(frame,columns())}\x1B[0J${last||rows<2?"":`\x1B[${rows-1}A`}${last?"":"\r"}${SYNC_END}`),current=state},redraw=()=>draw(current),paste={active:!1},stop=terminal.stop??(terminal===process2?stopJob:void 0),suspend=()=>{if(stop===void 0)return;stderr.write("\x1B[0J\x1B[?25h\x1B[?2004l"),stdin.setRawMode(!1),stop(),stdin.setRawMode(!0),stderr.write("\x1B[?25l\x1B[?2004h")};try{return stderr.on?.("resize",redraw),stdin.setRawMode(!0),stdin.resume(),stderr.write("\x1B[?25l\x1B[?2004h"),draw("asking"),await new Promise((resolve)=>{function onData(data){for(let key of readKeys(data.toString(),paste)){if(key==="suspend"){suspend();continue}let pressed=press(key);if(pressed!==void 0){settle(pressed);return}}draw("asking")}function onEnd(){settle("cancel")}function settle(settled){outcome=settled,stdin.off("data",onData),stdin.off("end",onEnd),resolve(settled==="enter")}stdin.on("data",onData),stdin.on("end",onEnd)})}finally{stderr.off?.("resize",redraw),draw(outcome??"cancel",!0),stderr.write(`
|
|
5
5
|
\x1B[?25h\x1B[?2004l`),stdin.setRawMode(!1),stdin.pause()}}export{checklist2,confirm2,input2};
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{bo,isInteractive,userConfigPath,ok,note,warn,problem,formatDuration,formatElapsed,wholeNumber,duration,Exit,fail,parse}from"./chunk-
|
|
3
|
-
`)}var usage="pkg bump <name> [version]\n\nWaits until the registry serves the version, vets it as `pkg check` does, then runs `bun add --exact --no-cache` in each folder under --root whose package.json depends on the package, the kind of dependency kept; a version the vetting blocks is refused before any folder is touched, unless --force is given.\nA dependency that is not a registry version (`workspace:`, `link:`, `file:`, git, a URL, `catalog:`), a peer range, a folder already on the version and one whose lockfile pins another manager are left as they are, each said so.\nOn a terminal with no --only or --except, a checklist asks which consumers to bump, then the plan is printed and confirmed.\nWith --all-consumers, a folder with uncommitted changes in its package.json or lockfile is left alone, and each folder whose install went through runs its own `check` and is committed with `gc` only when that passes; nothing is ever pushed.",EXITS=[[0,"every install ran or was left as it is (with --all-consumers, and every check passed and every commit landed)"],[1,"the vetting refuses the version, an install, a check or a commit fails or the registry has no such package"],[2,"the version never shows within the timeout (a registry that cannot be reached is retried until then) or a usage error"]],ROOT_OPTION2={type:"string",description:"the folder holding the repositories (the workspace of the user config or KAYNOOO_WORKSPACE, ~/Workspace by default)"},options={root:ROOT_OPTION2,timeout:{type:"string",short:"t",description:"how long to wait for the registry (10m): 30s, 5m, 1h"},"all-consumers":{type:"boolean",description:"after each install run the folder's check and commit it through gc when it passes"},only:{type:"string",multiple:!0,description:"bump only the folders matching this name or glob, repeatable"},except:{type:"string",multiple:!0,description:"leave the folders matching this name or glob alone, repeatable"},"dry-run":{type:"boolean",description:"print what would run, changing nothing"},yes:{type:"boolean",short:"y",description:"on a terminal, bump every consumer without the checklist and the confirmation"},force:{type:"boolean",description:"bump even when the version is blocked by the vetting"},"min-age":{type:"string",description:"days a version must be old (0: a bump adopts a release on purpose, often one just made)"}},POLL=5000;async function lookup(name,registry,fetcher){try{return{packument:await fetchPackument(name,registry,fetcher)}}catch(error){if(error instanceof Exit&&error.code===2)return{error:error.message};throw error}}async function servedVersion(name,version,settings){if(!isValidName(name))fail(`${name} is not a valid npm package name`);if(version!==void 0&&!EXACT_VERSION.test(version))fail(`bump takes an exact version, not ${version}: leave it out for the latest`);let registry=registryFor(name,settings.configs),host=new URL(registry.url).host,started=Date.now(),region=liveRegion((spinner)=>[`${spinner} waiting for ${host} to serve ${name}@${version??"latest"} ${formatElapsed(Date.now()-started)}`]),lastError="";try{for(;;){let looked=await lookup(name,registry,settings.fetcher);if("error"in looked)lastError=looked.error;else{let latest=looked.packument?.["dist-tags"]?.latest;if(looked.packument===void 0)fail(`${host} has no ${name}`,1);if(version===void 0&&latest===void 0)fail(`${host} has no ${name}`,1);if(version===void 0&&latest!==void 0)return latest;if(version!==void 0&&looked.packument.versions?.[version]!==void 0)return version}if(Date.now()-started>=settings.timeout)fail(`${host} does not serve ${name}@${version??"latest"} after ${formatDuration(settings.timeout)}${lastError===""?"":`, last error: ${lastError}`}`);region.redraw(),await Bun.sleep(settings.poll??POLL)}}finally{region.stop()}}async function vet(name,version,settings){if(settings.isForced===!0)return!0;let report=await checkPackage2(`${name}@${version}`,{configs:settings.configs,fetcher:settings.fetcher,minAgeDays:settings.minAgeDays??0,settings:settings.pkgSettings});if(!report.blocked){for(let warning of report.warnings)warn(`${name}@${version}`,warning);return!0}for(let warning of report.warnings)problem(`${name}@${version} is refused`,warning);return problem(`${name}@${version} is refused`,"no consumer was touched, --force bumps it anyway"),!1}function lockfileOf(dir,root){
|
|
2
|
+
import{bo,isInteractive,userConfigPath,ok,note,warn,problem,formatDuration,formatElapsed,wholeNumber,duration,Exit,fail,parse}from"./chunk-vdcfp18g.js";import{runCommand,liveRegion,stateHome,workspaceRoot}from"./chunk-q8pvz0vr.js";import{checklist2,confirm2}from"./chunk-wsfa4ft6.js";import{LOCKFILES,findConsumers,similarDependencies,isLocal,wantedVersion,RANGE_PREFIX,addCommand}from"./chunk-b90pc5k5.js";import{EXACT_VERSION,isValidName,fetchPackument,registryFor,loadConfigs,loadSettings,nearestFolder}from"./chunk-t8dsdj0n.js";import{checkPackage2}from"./chunk-b20mawd6.js";import{existsSync as existsSync2}from"fs";import{basename,join as join2,relative}from"path";import{existsSync,mkdirSync,readFileSync,writeFileSync}from"fs";import{dirname,join}from"path";function excludedPath(home){let base=home===void 0?stateHome():join(home,".local","state");return join(base,"kaynooo-cli","pkg-excluded.json")}function readExcludedFile(path){try{let raw=Bun.JSONC.parse(readFileSync(path,"utf8"));if(typeof raw!=="object"||raw===null||Array.isArray(raw))return;let excluded={};for(let[name,dirs]of Object.entries(raw))if(Array.isArray(dirs))excluded[name]=dirs.filter((dir)=>typeof dir==="string");return excluded}catch{return}}function loadExcluded(home){let path=excludedPath(home);if(existsSync(path))return readExcludedFile(path);let legacy=userConfigPath("pkg-excluded",{home});return existsSync(legacy)?readExcludedFile(legacy):{}}function saveExcluded(name,dirs,home){let path=excludedPath(home),excluded=loadExcluded(home);if(excluded===void 0)return;if(dirs.length===0)delete excluded[name];else excluded[name]=[...dirs].toSorted();mkdirSync(dirname(path),{recursive:!0}),writeFileSync(path,`${JSON.stringify(excluded,null,2)}
|
|
3
|
+
`)}var usage="pkg bump <name> [version]\n\nWaits until the registry serves the version, vets it as `pkg check` does, then runs `bun add --exact --no-cache` in each folder under --root whose package.json depends on the package, the kind of dependency kept; a version the vetting blocks is refused before any folder is touched, unless --force is given.\nA dependency that is not a registry version (`workspace:`, `link:`, `file:`, git, a URL, `catalog:`), a peer range, a folder already on the version and one whose lockfile pins another manager are left as they are, each said so.\nOn a terminal with no --only or --except, a checklist asks which consumers to bump, then the plan is printed and confirmed.\nWith --all-consumers, a folder with uncommitted changes in its package.json or lockfile is left alone, and each folder whose install went through runs its own `check` and is committed with `gc` only when that passes; nothing is ever pushed.",EXITS=[[0,"every install ran or was left as it is (with --all-consumers, and every check passed and every commit landed)"],[1,"the vetting refuses the version, an install, a check or a commit fails or the registry has no such package"],[2,"the version never shows within the timeout (a registry that cannot be reached is retried until then) or a usage error"]],ROOT_OPTION2={type:"string",description:"the folder holding the repositories (the workspace of the user config or KAYNOOO_WORKSPACE, ~/Workspace by default)"},options={root:ROOT_OPTION2,timeout:{type:"string",short:"t",description:"how long to wait for the registry (10m): 30s, 5m, 1h"},"all-consumers":{type:"boolean",description:"after each install run the folder's check and commit it through gc when it passes"},only:{type:"string",multiple:!0,description:"bump only the folders matching this name or glob, repeatable"},except:{type:"string",multiple:!0,description:"leave the folders matching this name or glob alone, repeatable"},"dry-run":{type:"boolean",description:"print what would run, changing nothing"},yes:{type:"boolean",short:"y",description:"on a terminal, bump every consumer without the checklist and the confirmation"},force:{type:"boolean",description:"bump even when the version is blocked by the vetting"},"min-age":{type:"string",description:"days a version must be old (0: a bump adopts a release on purpose, often one just made)"}},POLL=5000;async function lookup(name,registry,fetcher){try{return{packument:await fetchPackument(name,registry,fetcher)}}catch(error){if(error instanceof Exit&&error.code===2)return{error:error.message};throw error}}async function servedVersion(name,version,settings){if(!isValidName(name))fail(`${name} is not a valid npm package name`);if(version!==void 0&&!EXACT_VERSION.test(version))fail(`bump takes an exact version, not ${version}: leave it out for the latest`);let registry=registryFor(name,settings.configs),host=new URL(registry.url).host,started=Date.now(),region=liveRegion((spinner)=>[`${spinner} waiting for ${host} to serve ${name}@${version??"latest"} ${formatElapsed(Date.now()-started)}`]),lastError="";try{for(;;){let looked=await lookup(name,registry,settings.fetcher);if("error"in looked)lastError=looked.error;else{let latest=looked.packument?.["dist-tags"]?.latest;if(looked.packument===void 0)fail(`${host} has no ${name}`,1);if(version===void 0&&latest===void 0)fail(`${host} has no ${name}`,1);if(version===void 0&&latest!==void 0)return latest;if(version!==void 0&&looked.packument.versions?.[version]!==void 0)return version}if(Date.now()-started>=settings.timeout)fail(`${host} does not serve ${name}@${version??"latest"} after ${formatDuration(settings.timeout)}${lastError===""?"":`, last error: ${lastError}`}`);region.redraw(),await Bun.sleep(settings.poll??POLL)}}finally{region.stop()}}async function vet(name,version,settings){if(settings.isForced===!0)return!0;let report=await checkPackage2(`${name}@${version}`,{configs:settings.configs,fetcher:settings.fetcher,minAgeDays:settings.minAgeDays??0,settings:settings.pkgSettings});if(!report.blocked){for(let warning of report.warnings)warn(`${name}@${version}`,warning);return!0}for(let warning of report.warnings)problem(`${name}@${version} is refused`,warning);return problem(`${name}@${version} is refused`,"no consumer was touched, --force bumps it anyway"),!1}function lockfileOf(dir,root){let at=nearestFolder(dir,(folder)=>LOCKFILES.some(([file])=>existsSync2(join2(folder,file))),root),found=at===void 0?void 0:LOCKFILES.find(([file])=>existsSync2(join2(at,file)))?.[0];return at===void 0||found===void 0?void 0:relative(dir,join2(at,found))}async function hasUncommittedChanges(where,root,run){let lockfile=lockfileOf(where,root),status=await run(["git","status","--porcelain","--","package.json",...lockfile===void 0?[]:[lockfile]],where);return status.code===0&&status.text.trim()!==""}async function checkAndCommit(name,version,where,root,run){let checked=await run(["check"],where);if(checked.code!==0)return`check exited ${checked.code}: ${checked.text.trim().split(`
|
|
4
4
|
`).at(-1)??""}`;let lockfile=lockfileOf(where,root),committed=await run(["gc",`chore(deps): bump ${name} to ${version}`,"--","package.json",...lockfile===void 0?[]:[lockfile]],where);return committed.code===0?void 0:`gc exited ${committed.code}: ${committed.text.trim().split(`
|
|
5
5
|
`).at(-1)??""}`}function matcher(patterns){let globs=patterns.map((pattern)=>new Bun.Glob(pattern));return(dir)=>globs.some((glob)=>glob.match(dir)||glob.match(basename(dir)))}async function bumpConsumers(name,version,settings){let everyone=findConsumers(name,settings.root),isOnly=matcher(settings.only??[]),isExcept=matcher(settings.except??[]),declined=new Set(settings.declined??[]),found=everyone.filter((each)=>(settings.only===void 0||settings.only.length===0||isOnly(each.dir))&&!isExcept(each.dir)&&!declined.has(each.dir)),consumers=found.filter((each)=>!isLocal(each)),left=everyone.length-found.length-declined.size,local=found.length-consumers.length,run=settings.run??(async(argv,cwd)=>runCommand(argv,{cwd})),committed=[],failing=[],skipped=[],isClean=!0;if(everyone.length===0){let similar=similarDependencies(name,settings.root);note(`nothing under ${settings.root} depends on ${name}`,similar.length===0?void 0:`did you mean ${similar.join(", ")}`)}else if(left>0)note(`${bo(left,"folder")} left out by --only or --except`);if(declined.size>0)note(`${bo(declined.size,"folder")} left out by your choice`);if(local>0)note(`${local} non-registry dependenc${local===1?"y":"ies"} (workspace:, file:, git, URL, alias, catalog:)`,"left as they are");for(let consumer of consumers){let argv=addCommand(consumer,name,version),where=join2(settings.root,consumer.dir);if(consumer.kind==="peerDependencies")skipped.push(consumer.dir),note(consumer.dir,`peer range ${consumer.spec}, left as it is`);else if((consumer.alias===void 0?consumer.spec:wantedVersion(consumer).replace(RANGE_PREFIX,""))===version)skipped.push(consumer.dir),note(consumer.dir,`already on ${version}`);else if(settings.isDryRun===!0)note(consumer.dir,`would run ${[argv.join(" "),...settings.isAll===!0?["check",`gc 'chore(deps): bump ${name} to ${version}'`]:[]].join(", then ")}`);else if(settings.isAll===!0&&await hasUncommittedChanges(where,settings.root,run))isClean=!1,failing.push(consumer.dir),problem(consumer.dir,"package.json or its lockfile has uncommitted changes, left alone so that gc does not commit them");else{let ran=await run(argv,where);if(ran.code!==0)isClean=!1,failing.push(consumer.dir),problem(consumer.dir,`${argv.join(" ")} exited ${ran.code}: ${ran.text.trim().split(`
|
|
6
6
|
`).at(-1)??""}`);else if(settings.isAll!==!0)ok(consumer.dir,`${consumer.spec} -> ${version}`);else{let failure=await checkAndCommit(name,version,where,settings.root,run);if(failure===void 0)committed.push(consumer.dir),ok(consumer.dir,`${consumer.spec} -> ${version}, checked and committed`);else isClean=!1,failing.push(consumer.dir),problem(consumer.dir,`${consumer.spec} -> ${version}, left uncommitted: ${failure}`)}}}if(settings.isAll===!0&&settings.isDryRun!==!0)note("summary",`${committed.length} bumped and committed, ${failing.length} bumped and failing${failing.length>0?` (${failing.join(", ")})`:""}, ${skipped.length+local} skipped`);return isClean}function plannedBumps(name,version,settings){return findConsumers(name,settings.root).filter((each)=>!isLocal(each)&&each.kind!=="peerDependencies"&&(each.alias===void 0?each.spec:wantedVersion(each).replace(RANGE_PREFIX,""))!==version).map((each)=>({dir:each.dir,line:`${each.dir} ${each.spec} -> ${version}`}))}var terminalChooser={pick:async(name,plans,excluded)=>checklist2(`bump ${name} in`,plans.map((plan)=>({value:plan.dir,label:plan.line,hint:excluded.has(plan.dir)?"left out last time":""})),{initial:new Set(plans.filter((plan)=>!excluded.has(plan.dir)).map((plan)=>plan.dir)),hint:"pass --yes to bump every consumer"}),confirm:async(question)=>confirm2(question,{default:!0,hint:"pass --yes to skip confirmation"})};async function choosePlan(name,version,settings,chooser=terminalChooser,home){let plans=plannedBumps(name,version,settings);if(plans.length===0)return;let excluded=new Set(loadExcluded(home)?.[name]??[]),picked=await chooser.pick(name,plans,excluded);if(picked===void 0)return{chosen:[],declined:plans.map((plan)=>plan.dir)};let chosen=plans.filter((plan)=>picked.has(plan.dir));for(let plan of chosen)note("plan",plan.line);if(chosen.length===0||await chooser.confirm(`bump ${name} to ${version} in ${bo(chosen.length,"folder")}?`)!==!0)return{chosen:[],declined:plans.map((plan)=>plan.dir)};let declined=plans.filter((plan)=>!picked.has(plan.dir)).map((plan)=>plan.dir);return saveExcluded(name,[...excluded].filter((dir)=>!plans.some((plan)=>plan.dir===dir)).concat(declined),home),{chosen:chosen.map((plan)=>plan.dir),declined}}async function bump2(args){let{values,positionals:[name,asked]}=parse(args,usage,options,{exits:EXITS,positionals:["<name>","[version]"]}),settings={root:workspaceRoot({given:values.root}),configs:await loadConfigs(),timeout:duration(values.timeout,"timeout",600000),isDryRun:values["dry-run"]===!0,isAll:values["all-consumers"]===!0,isForced:values.force===!0,only:values.only,except:values.except,pkgSettings:await loadSettings(),minAgeDays:wholeNumber(values["min-age"],"min-age",0,0)},version=await servedVersion(name,asked,settings);if(!await vet(name,version,settings))return 1;if(settings.isDryRun!==!0&&values.yes!==!0&&isInteractive()&&(settings.only?.length??0)===0&&(settings.except?.length??0)===0){let plan=await choosePlan(name,version,settings);if(plan?.chosen.length===0)return note("nothing to bump","none chosen or not confirmed"),0;settings.declined=plan?.declined}return await bumpConsumers(name,version,settings)?0:1}
|
package/dist/cli.js
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
#!/bin/sh
|
|
2
2
|
// @bun 2>/dev/null; exec bun --no-env-file --config=/dev/null "$0" "$@"
|
|
3
|
-
import"./chunk-
|
|
3
|
+
import"./chunk-vdcfp18g.js";import{runCli}from"./chunk-q8pvz0vr.js";import process from"process";process.exitCode=await runCli({name:"pkg",about:"checks, adds, audits and updates packages safely across bun, pnpm, yarn, npm, composer, cargo and uv",replaces:"bun add on trust, and a bun info and sleep loop then a bun add per consumer",examples:[["pkg zod","the name, the newest version two weeks old, its licence and scripts"],["pkg add zod","vet and install exact safe version with the detected manager"],["pkg update --apply","update dependencies safely across workspaces"]],defaultCommand:"check",commands:{check:{summary:"check packages before they are added (`pkg <name>` alone runs it)",run:async(args)=>(await import("./chunk-enwetxvb.js")).check(args)},add:{summary:"vet packages and install exact safe versions with the detected package manager",run:async(args)=>(await import("./chunk-q460gr2v.js")).add(args)},audit:{summary:"vet lockfiles (bun, pnpm, yarn, npm, composer, cargo, uv) with advisories and direct/via chains",run:async(args)=>(await import("./chunk-1dgxf5yc.js")).audit(args)},update:{summary:"list or --apply safe updates across the folder and its workspaces",run:async(args)=>(await import("./chunk-m4pv8kkb.js")).outdatedCommand(args)},outdated:{summary:"list dependencies that have a newer version safe to take (alias of update)",run:async(args)=>(await import("./chunk-m4pv8kkb.js")).outdatedCommand(args)},bump:{summary:"wait for a release on the registry, then add it in every bun/pnpm/yarn/npm consumer",run:async(args)=>(await import("./chunk-q0vmkwhm.js")).bump(args)},consumers:{summary:"list the folders depending on a package, with the version each asks for",run:async(args)=>(await import("./chunk-nvadv55x.js")).consumers(args)},manager:{summary:"the command this folder's package manager runs to install, remove, update or exec",run:async(args)=>(await import("./chunk-ws3phmm3.js")).manager(args)}}});
|
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@kaynooo/cli-pkg",
|
|
3
3
|
"type": "module",
|
|
4
|
-
"version": "0.
|
|
4
|
+
"version": "0.20.0",
|
|
5
5
|
"description": "pkg: check an npm package before it is added, for a guessed name, a version under two weeks old and install scripts.",
|
|
6
6
|
"author": "Kaynooo <contact@kaynooo.fr>",
|
|
7
7
|
"license": "MIT",
|
|
@@ -41,7 +41,7 @@
|
|
|
41
41
|
"record": "$npm_execpath scripts/record.ts"
|
|
42
42
|
},
|
|
43
43
|
"dependencies": {
|
|
44
|
-
"@kaynooo/cli-kit": "0.
|
|
44
|
+
"@kaynooo/cli-kit": "0.52.0"
|
|
45
45
|
},
|
|
46
46
|
"devDependencies": {
|
|
47
47
|
"@kaynooo/utils": "3.1.0"
|
package/dist/chunk-0eb0ncqy.js
DELETED
|
@@ -1,10 +0,0 @@
|
|
|
1
|
-
// @bun
|
|
2
|
-
import process9 from"process";import{parseArgs}from"util";import process6 from"process";var ct=/[aeiou]y$/;var Ot=/(?:leaf|loaf|thief|wolf|half|calf|elf|sheaf|scarf|dwarf|hoof|wharf)$/,Gt=/(?:knife|life|wife)$/;function G(t,e,{plural:r,zero:n="singular"}={}){if(e===1||e===0&&n==="singular")return t;if(r!==void 0)return r;if(t.endsWith("y")&&!ct.test(t))return`${t.slice(0,-1)}ies`;if(t.endsWith("s")||t.endsWith("x")||t.endsWith("z")||t.endsWith("ch")||t.endsWith("sh"))return`${t}es`;if(Ot.test(t))return`${t.slice(0,-1)}ves`;return Gt.test(t)?`${t.slice(0,-2)}ves`:`${t}s`}function bo(t,e,{zero:r="plural",...n}={}){return`${t} ${G(e,t,{...n,zero:r})}`}var Nt=/\s+\S*$/,Y=/\s/;function Ao(t,e,r="..."){let{suffix:n="...",includeSuffix:s=!1,wordBoundary:o=!1}=typeof r==="string"?{suffix:r}:r;if(t.length<=e)return t;let l=Math.max(0,e),c=t.substring(0,Math.max(0,s?l-n.length:l));if(o&&!Y.test(t[c.length]??" "))c=c.replace(Nt,"")||c;if(o)c=c.trimEnd();return s?(c+n).slice(0,l):c+n}var be=new Map(["\u20AC","","\u201A","\u0192","\u201E","\u2026","\u2020","\u2021","\u02C6","\u2030","\u0160","\u2039","\u0152","","\u017D","","","\u2018","\u2019","\u201C","\u201D","\u2022","\u2013","\u2014","\u02DC","\u2122","\u0161","\u203A","\u0153","","\u017E","\u0178"].map((t,e)=>[t,128+e]).filter(([t])=>t));import process from"process";var MODES=new Set(["terminal","ci","agent","pipe"]),AGENT_VARIABLES=["CLAUDECODE","AI_AGENT","CODEX_SANDBOX","CODEX_CI","CURSOR_AGENT","OPENCODE","GEMINI_CLI","ANTIGRAVITY_AGENT"];function isSet(value){return value!==void 0&&value!==""&&value!=="0"&&value.toLowerCase()!=="false"}function outputMode(stream=process.stdout,env=process.env){let chosen=env.KIT_MODE;if(chosen!==void 0&&MODES.has(chosen))return chosen;if(AGENT_VARIABLES.some((name)=>isSet(env[name])))return"agent";if(stream.isTTY===!0)return"terminal";return isSet(env.CI)?"ci":"pipe"}function isHumanTerminal(stream=process.stdout,env=process.env){return outputMode(stream,env)==="terminal"}function isInteractive(streams=process,env=process.env){return streams.stdin?.isTTY===!0&&isHumanTerminal(streams.stderr??{},env)}import process5 from"process";var G2=/^[a-f0-9]+$/i;function b(r){let e=r.startsWith("#")?r.slice(1):r;if(!G2.test(e))return[0,0,0];if(e.length===3||e.length===4)return[Number.parseInt(e[0]+e[0],16),Number.parseInt(e[1]+e[1],16),Number.parseInt(e[2]+e[2],16)];if(e.length!==6&&e.length!==8)throw Error(`Invalid hex color length: ${e.length}`);return[Number.parseInt(e.slice(0,2),16),Number.parseInt(e.slice(2,4),16),Number.parseInt(e.slice(4,6),16)]}var B={reset:[0,0],bold:[1,22],dim:[2,22],italic:[3,23],underline:[4,24],inverse:[7,27],hidden:[8,28],strikethrough:[9,29],black:[30,39],red:[31,39],green:[32,39],yellow:[33,39],blue:[34,39],magenta:[35,39],cyan:[36,39],white:[37,39],gray:[90,39],grey:[90,39],blackBright:[90,39],redBright:[91,39],greenBright:[92,39],yellowBright:[93,39],blueBright:[94,39],magentaBright:[95,39],cyanBright:[96,39],whiteBright:[97,39],bgBlack:[40,49],bgRed:[41,49],bgGreen:[42,49],bgYellow:[43,49],bgBlue:[44,49],bgMagenta:[45,49],bgCyan:[46,49],bgWhite:[47,49],bgBlackBright:[100,49],bgRedBright:[101,49],bgGreenBright:[102,49],bgYellowBright:[103,49],bgBlueBright:[104,49],bgMagentaBright:[105,49],bgCyanBright:[106,49],bgWhiteBright:[107,49],rgb:(r,e,l,n="fg")=>[`${n==="fg"?38:48};2;${r};${e};${l}`,n==="fg"?39:49],hex:(r,e="fg")=>{let[l,n,c]=b(r);return[`${e==="fg"?38:48};2;${l};${n};${c}`,e==="fg"?39:49]},ansi256:(r,e="fg")=>[`${e==="fg"?38:48};5;${r}`,e==="fg"?39:49]},h=new Set(["","1","2","3","true"]);function C(r,e=globalThis.process?.env??{}){if(e.FORCE_COLOR!==void 0)return h.has(e.FORCE_COLOR);if(e.NO_COLOR!==void 0||e.NODE_DISABLE_COLORS!==void 0||e.TERM==="dumb")return!1;return r?.isTTY===!0}function f(r,e=[]){let l="",n="";for(let t=0,i=e.length;t<i;t++)l+=`\x1B[${e[t][0]}m`,n=`\x1B[${e[t][1]}m${n}`;let c=(t)=>C(r.stream??globalThis.process?.stdout,r.env)?l+t+n:t,g=new Map;return new Proxy(c,{get(t,i){let a=B[i];if(Array.isArray(a)){let s=g.get(i);if(s===void 0)s=f(r,[...e,a]),g.set(i,s);return s}if(typeof a==="function")return(...s)=>{let y=`${i}:${s.join(",")}`,u=g.get(y);if(u===void 0){if(g.size>=64)g.clear();u=f(r,[...e,a(...s)]),g.set(y,u)}return u};throw Error(`Unknown style: ${String(i)}`)}})}function Fe(r={}){return f(r)}var o=Fe();import{existsSync as existsSync3,readFileSync as readFileSync2,statSync as statSync2}from"fs";import{homedir as homedir2}from"os";import{join as join3,resolve as resolve2}from"path";import process4 from"process";import{existsSync}from"fs";import{dirname,join,resolve}from"path";import process2 from"process";function findUp(names,from=process2.cwd(),stop=()=>!1){let wanted=typeof names==="string"?[names]:names;for(let dir=resolve(from);;dir=dirname(dir)){let found=wanted.map((name)=>join(dir,name)).find((path)=>existsSync(path));if(found!==void 0)return found;if(stop(dir)||dirname(dir)===dir)return}}import{existsSync as existsSync2,mkdirSync,readFileSync,statSync,writeFileSync}from"fs";import{homedir}from"os";import{dirname as dirname2,isAbsolute,join as join2}from"path";import process3 from"process";var FILE_CACHE=new Map;function isRecord(value){return typeof value==="object"&&value!==null&&!Array.isArray(value)}function xdgFolder(value,fallback){return value!==void 0&&isAbsolute(value)?value:fallback}function configBase(where={}){let xdg=where.xdg??(where.home===void 0?process3.env.XDG_CONFIG_HOME:void 0);return xdgFolder(xdg,join2(where.home??homedir(),".config"))}function userConfigPath(bin,where={}){return join2(configBase(where),"kaynooo-cli",`${bin}.json`)}function mainConfigPath(where={}){let jsonc=join2(configBase(where),"kaynooo-cli","config.jsonc");return existsSync2(jsonc)?jsonc:userConfigPath("config",where)}function userConfigReadPath(bin,legacy=[],where={}){if(bin==="config")return mainConfigPath(where);let current=userConfigPath(bin,where);if(existsSync2(current))return current;let base=configBase(where);return legacy.map((parts)=>join2(base,...parts)).find((path)=>existsSync2(path))??current}function readCachedObject(path){let stat=statSync(path,{throwIfNoEntry:!1});if(stat===void 0||!stat.isFile())return FILE_CACHE.delete(path),{};let cached=FILE_CACHE.get(path);if(cached!==void 0&&cached.mtimeMs===stat.mtimeMs&&cached.size===stat.size)return cached.data;try{let parsed=Bun.JSONC.parse(readFileSync(path,"utf8")),data=isRecord(parsed)?parsed:{};return FILE_CACHE.set(path,{mtimeMs:stat.mtimeMs,size:stat.size,data}),data}catch{return{}}}function readMainConfig(where={}){return readCachedObject(mainConfigPath(where))}function readUserConfig(bin,where={},legacy=[]){if(bin==="config")return readMainConfig(where);let fileData=readCachedObject(userConfigReadPath(bin,legacy,where)),section=readMainConfig(where)[bin];return isRecord(section)?{...fileData,...section}:fileData}function toLinear(channel){let value=channel/255;return value<=0.04045?value/12.92:((value+0.055)/1.055)**2.4}var fromLinear=(value)=>Math.round(255*Math.min(1,Math.max(0,value<=0.0031308?value*12.92:1.055*value**0.4166666666666667-0.055)));function toOklab(hex){let[r,g,b]=[1,3,5].map((at)=>toLinear(Number.parseInt(hex.slice(at,at+2),16))),l=Math.cbrt(0.4122214708*r+0.5363325363*g+0.0514459929*b),m=Math.cbrt(0.2119034982*r+0.6806995451*g+0.1073969566*b),s=Math.cbrt(0.0883024619*r+0.2817188376*g+0.6299787005*b);return[0.2104542553*l+0.793617785*m-0.0040720468*s,1.9779984951*l-2.428592205*m+0.4505937099*s,0.0259040371*l+0.7827717662*m-0.808675766*s]}function fromOklab([lightness,a,b]){let l=(lightness+0.3963377774*a+0.2158037573*b)**3,m=(lightness-0.1055613458*a-0.0638541728*b)**3,s=(lightness-0.0894841775*a-1.291485548*b)**3;return`#${[4.0767416621*l-3.3077115913*m+0.2309699292*s,-1.2684380046*l+2.6097574011*m-0.3413193965*s,-0.0041960863*l-0.7034186147*m+1.707614701*s].map((channel)=>fromLinear(channel).toString(16).padStart(2,"0")).join("")}`}var ENDS=new Map;function gradientAt(theme,ratio){if(theme.gradient===void 0)return;let key=theme.gradient.join(),ends=ENDS.get(key);if(ends===void 0)ends=[toOklab(theme.gradient[0]),toOklab(theme.gradient[1])],ENDS.set(key,ends);let at=Math.min(1,Math.max(0,ratio)),[from,to]=ends;return fromOklab(from.map((start,index)=>start+(to[index]-start)*at))}var DEFAULT={colors:{accent:"cyan",id:"yellow",path:"blue",label:"dim",value:"bold",ok:"green",warn:"yellow",problem:"red",note:"dim",plan:"magenta",passed:"green",failed:"red",running:"cyan",queued:"yellow",skipped:"dim"},glyphs:{ok:"\u2713",warn:"\u25B2",problem:"\u2717",note:"\u203A",plan:"\u25C7",passed:"\u2713",failed:"\u2717",running:"\u25CF",queued:"\u25CB",skipped:"-",bar:"\u2501",rule:"\u2500",corner:"\u256D",open:"\u2022",leaf:"\xB7",guide:"\u2502"},accents:["cyan","magenta","green","blue","yellow","redBright"],bins:{},gradient:["#c084fc","#67e8f9"]},BRIGHT={accent:"cyanBright",id:"yellowBright",path:"blueBright",label:"white",value:"bold whiteBright",ok:"greenBright",warn:"yellowBright",problem:"redBright",note:"white",plan:"magentaBright",passed:"greenBright",failed:"redBright",running:"cyanBright",queued:"yellowBright",skipped:"white"},LIGHT={accent:"#0369a1",id:"#b45309",path:"#1d4ed8",label:"#52525b",value:"bold",ok:"#15803d",warn:"#b45309",problem:"#b91c1c",note:"#52525b",plan:"#7e22ce",passed:"#15803d",failed:"#b91c1c",running:"#0369a1",queued:"#b45309",skipped:"#52525b"},MONO={accent:"bold",id:"bold",path:"underline",label:"dim",value:"bold",ok:"bold",warn:"bold",problem:"bold",note:"dim",plan:"dim",passed:"bold",failed:"bold",running:"bold",queued:"dim",skipped:"dim"},ASCII={ok:"+",warn:"!",problem:"x",note:">",plan:"?",passed:"+",failed:"x",running:"*",queued:"o",skipped:"-",bar:"#",rule:"-",corner:"+",open:"*",leaf:"-",guide:"|"},PRESETS={default:{},"high-contrast":{colors:BRIGHT,accents:["cyanBright","magentaBright","greenBright","blueBright","yellowBright","redBright"],gradient:["#d8b4fe","#a5f3fc"]},light:{colors:LIGHT,accents:["#0369a1","#7e22ce","#15803d","#1d4ed8","#b45309","#b91c1c"],gradient:["#7c3aed","#0284c7"]},mono:{colors:MONO,accents:["bold"],gradient:void 0},ascii:{glyphs:ASCII}},STYLES=new Set(["bold","dim","italic","underline","inverse","strikethrough","black","red","green","yellow","blue","magenta","cyan","white","gray","grey","blackBright","redBright","greenBright","yellowBright","blueBright","magentaBright","cyanBright","whiteBright"]),HEX=/^#[0-9a-f]{6}$/i,CONTROL=/\p{Cc}/u,MAX_FILE_BYTES=65536,SPACES=/\s+/;function isColorSpec(spec){if(typeof spec==="number")return Number.isInteger(spec)&&spec>=0&&spec<=255;return typeof spec==="string"&&spec.trim()!==""&&spec.trim().split(SPACES).every((token)=>STYLES.has(token)||HEX.test(token))}var CUBE=[0,95,135,175,215,255];function cubeLevel(channel){return CUBE.reduce((best,value,level)=>Math.abs(value-channel)<Math.abs(CUBE[best]-channel)?level:best,0)}function nearest256(hex){let rgb=[1,3,5].map((at)=>Number.parseInt(hex.slice(at,at+2),16)),levels=rgb.map(cubeLevel),cube=levels.map((level)=>CUBE[level]),grey=Math.min(23,Math.max(0,Math.round((rgb.reduce((sum,channel)=>sum+channel,0)/3-8)/10))),greyValue=8+grey*10,distance=(colour)=>colour.reduce((sum,channel,at)=>sum+(channel-rgb[at])**2,0);return distance([greyValue,greyValue,greyValue])<distance(cube)?232+grey:16+36*levels[0]+6*levels[1]+levels[2]}function hasTrueColor(env){return env.COLORTERM==="truecolor"||env.COLORTERM==="24bit"}function tinted(colors,spec,env=process4.env){if(typeof spec==="number")return colors.ansi256(spec);return spec.trim().split(SPACES).reduce((chain,token)=>{if(HEX.test(token))return hasTrueColor(env)?chain.hex(token):chain.ansi256(nearest256(token));return chain[token]??chain},colors)}function shaded(theme,colors,glyph,cells,width,env=process4.env){return Array.from({length:cells},(_,index)=>tinted(colors,gradientAt(theme,width<=1?0:index/(width-1))??theme.colors.accent,env)(glyph)).join("")}function isRecord2(value){return typeof value==="object"&&value!==null&&!Array.isArray(value)}function readThemeFile(path,warn){try{let stat=statSync2(path,{throwIfNoEntry:!1});if(stat===void 0)return;if(!stat.isFile()||stat.size>MAX_FILE_BYTES){warn(`${path} is not a regular file under ${MAX_FILE_BYTES/1024} KiB, theme ignored`);return}let parsed=Bun.JSONC.parse(readFileSync2(path,"utf8"));if(isRecord2(parsed))return parsed;warn(`${path} is not a JSON object, theme ignored`)}catch(error){warn(`${path} does not parse (${error instanceof Error?error.message:String(error)}), theme ignored`)}return}function applyPreset(theme,name,warn,where){if(name===void 0)return;if(typeof name!=="string"||!Object.hasOwn(PRESETS,name)){warn(`${where}: no preset ${String(name)}, one of ${Object.keys(PRESETS).join(", ")}`);return}let preset=PRESETS[name];if(Object.assign(theme.colors,preset.colors),Object.assign(theme.glyphs,preset.glyphs),preset.accents!==void 0)theme.accents=[...preset.accents];if(Object.hasOwn(preset,"gradient"))theme.gradient=preset.gradient;return name}function applyFile(theme,file,where,warn){if(isRecord2(file.colors))for(let[key,value]of Object.entries(file.colors))if(!Object.hasOwn(DEFAULT.colors,key))warn(`${where}: no colour ${key}, one of ${Object.keys(DEFAULT.colors).join(", ")}`);else if(!isColorSpec(value))warn(`${where}: colour ${key} is not an ANSI name, \`#rrggbb\` or a number up to 255`);else theme.colors[key]=value;if(isRecord2(file.glyphs))for(let[key,value]of Object.entries(file.glyphs))if(!Object.hasOwn(DEFAULT.glyphs,key))warn(`${where}: no glyph ${key}, one of ${Object.keys(DEFAULT.glyphs).join(", ")}`);else if(typeof value!=="string"||CONTROL.test(value)||Bun.stringWidth(value)!==1)warn(`${where}: glyph ${key} must be one visible character wide, with no control character`);else theme.glyphs[key]=value;if(Array.isArray(file.accents)&&file.accents.length>0&&file.accents.every(isColorSpec))theme.accents=[...file.accents];else if(file.accents!==void 0)warn(`${where}: accents must be a non-empty list of colours`);if(file.gradient===null)theme.gradient=void 0;else if(Array.isArray(file.gradient)&&file.gradient.length===2&&file.gradient.every((end)=>typeof end==="string"&&HEX.test(end)))theme.gradient=[file.gradient[0],file.gradient[1]];else if(file.gradient!==void 0)warn(`${where}: gradient must be two \`#rrggbb\` colours, or null for none`);if(isRecord2(file.bins))for(let[bin,value]of Object.entries(file.bins))if(isColorSpec(value))theme.bins[bin]=value;else warn(`${where}: bin ${bin} has no valid colour`)}function endsWalk(home){return(dir)=>dir===resolve2(home)||existsSync3(join3(dir,".git"))}var warned=new Set;function warnOnce(message){if(warned.has(message))return;warned.add(message),console.error(`warning: theme ${message}`)}function isPath(chosen){return chosen.includes("/")||chosen.endsWith(".json")}function loadTheme({env=process4.env,from=process4.cwd(),home=homedir2(),warn=warnOnce}={}){let theme={colors:{...DEFAULT.colors},glyphs:{...DEFAULT.glyphs},accents:[...DEFAULT.accents],bins:Object.create(null),gradient:DEFAULT.gradient},sources=[],chosen=env.KIT_THEME??"",wanted=chosen===""?[userConfigPath("theme",{home,xdg:env.XDG_CONFIG_HOME}),findUp(join3(".kaynooo","theme.json"),from,endsWalk(home))]:[];if(isPath(chosen))wanted.push(resolve2(from,chosen));let files=[];if(chosen===""){let mainTheme=readMainConfig({home,xdg:env.XDG_CONFIG_HOME}).theme;if(isRecord2(mainTheme))files.push({path:`${mainConfigPath({home,xdg:env.XDG_CONFIG_HOME})}#theme`,file:mainTheme})}for(let path of wanted){let file=path===void 0?void 0:readThemeFile(path,warn);if(path!==void 0&&file!==void 0)files.push({path,file})}let preset="default";if(chosen!==""&&!isPath(chosen))preset=applyPreset(theme,chosen,warn,"KIT_THEME")??preset;else{let named=files.findLast(({file})=>file.preset!==void 0);if(named!==void 0)preset=applyPreset(theme,named.file.preset,warn,named.path)??preset}for(let{path,file}of files)applyFile(theme,file,path,warn),sources.push(path);return{theme,sources,preset}}var current,currentKey="";function activeTheme(){let key=`${process4.cwd()}\x00${process4.env.KIT_THEME??""}\x00${process4.env.XDG_CONFIG_HOME??""}`;if(current===void 0||key!==currentKey)current=loadTheme(),currentKey=key;return current}var MARK_WORDS={ok:"ok:",warn:"warning:",problem:"error:",note:"note:",plan:"would:"};function takesControlCodes(stream,env=process5.env){return stream.isTTY===!0&&(env.NO_COLOR===void 0||env.NO_COLOR==="")&&env.NODE_DISABLE_COLORS===void 0&&env.TERM!=="dumb"&&outputMode(stream,env)==="terminal"}function paint(stream,env=process5.env){let effective=env.NO_COLOR===""?{...env,NO_COLOR:void 0}:env;return Fe({stream:{isTTY:takesControlCodes(stream,env)},env:effective})}function marked(mark,text,stream,detail,env=process5.env){let colors=paint(stream,env),head=MARK_WORDS[mark];if(takesControlCodes(stream,env)){let{theme}=activeTheme();head=tinted(colors.bold,theme.colors[mark],env)(theme.glyphs[mark])}return`${head} ${text}${detail===void 0?"":` ${colors.dim(detail)}`}`}function ok(text,detail){console.log(marked("ok",text,process5.stdout,detail))}function note(text,detail){console.log(marked("note",text,process5.stdout,detail))}function warn(text,detail){console.error(marked("warn",text,process5.stderr,detail))}function problem(text,detail){console.error(marked("problem",text,process5.stderr,detail))}function role(name,stream,env=process5.env){let colors=paint(stream,env);return takesControlCodes(stream,env)?tinted(colors,activeTheme().theme.colors[name],env):colors}var STATUS_WORDS={passed:["passed","success","succeeded","ok"],failed:["failed","failure","error","errored"],running:["running","in_progress","started","holding"],queued:["queued","waiting","pending","created","blocked","scheduled"],skipped:["skipped","cancelled","canceled","manual"]},STATUS_OF=new Map(Object.entries(STATUS_WORDS).flatMap(([status,words])=>words.map((word)=>[word,status])));function distance(a,b){let left=[...a],right=[...b],before=[],previous=Array.from({length:right.length+1},(_,index)=>index);for(let[i,x]of left.entries()){let current=[i+1];for(let[j,y]of right.entries()){let cost=Math.min((previous[j+1]??0)+1,(current[j]??0)+1,(previous[j]??0)+(x===y?0:1));if(i>0&&j>0&&x===right[j-1]&&left[i-1]===y)cost=Math.min(cost,(before[j-1]??0)+1);current.push(cost)}before=previous,previous=current}return previous[right.length]??0}function closest(name,names){let started=names.find((known)=>known.startsWith(name));if(started!==void 0)return started;let[best]=names.map((known)=>({known,far:distance(name,known)})).sort((a,b)=>a.far-b.far);return best!==void 0&&best.far<=(name.length<4?1:2)?best.known:void 0}var ESC=String.fromCharCode(27),ESCAPE_CODE=new RegExp(`${ESC}(?:\\[[\\x30-\\x3F]*[\\x20-\\x2F]*[\\x40-\\x7E]|\\][^\\u0007${ESC}]*(?:\\u0007|${ESC}\\\\))`,"y"),RESET_STYLE=`${ESC}[0m`,CLOSE_LINK=`${ESC}]8;;${ESC}\\`;function cutToWidth(line,width,suffix=""){if(Bun.stringWidth(line)<=width)return line;let suffixWidth=suffix===""?0:Bun.stringWidth(suffix),room=Math.max(0,width-suffixWidth),kept="",index=0,styled=!1,linked=!1;while(index<line.length){ESCAPE_CODE.lastIndex=index;let escape=ESCAPE_CODE.exec(line);if(escape!==null){if(kept+=escape[0],escape[0].startsWith(`${ESC}]`))linked=!0;else styled=!0;index=ESCAPE_CODE.lastIndex;continue}let char=String.fromCodePoint(line.codePointAt(index)),columns=Bun.stringWidth(char);if(columns>room)break;kept+=char,room-=columns,index+=char.length}return`${kept}${styled?RESET_STYLE:""}${linked?CLOSE_LINK:""}${suffix}`}var UNITS=[["d",86400],["h",3600],["m",60],["s",1]];function formatSeconds(total){let rest=Math.max(0,Math.round(total)),amounts=UNITS.map(([unit,size])=>{let amount=Math.floor(rest/size);return rest-=amount*size,`${amount}${unit}`}),first=amounts.findIndex((amount)=>!amount.startsWith("0"));if(first===-1)return"0s";let next=amounts[first+1];return next===void 0||next.startsWith("0")?amounts[first]??"0s":`${amounts[first]} ${next}`}function formatDuration(ms){return ms<60000?`${(Math.max(0,ms)/1000).toFixed(1)}s`:formatSeconds(ms/1000)}function formatElapsed(ms){return formatSeconds(Math.floor(Math.max(0,ms)/1000))}function upTo(text,separator){let end=text.indexOf(separator);return end===-1?text:text.slice(0,end)}function formatAge(date,now=Date.now()){let at=typeof date==="number"?date:Date.parse(date);if(Number.isNaN(at))return"-";let seconds=(now-at)/1000;return seconds<60?"just now":`${upTo(formatSeconds(seconds)," ")} ago`}function truncate(text,width){return Ao(text,width,{suffix:"\u2026",includeSuffix:!0})}var LINE_BREAKS=/\s*\n\s*/g;function textWidth(text){return Bun.stringWidth(text)}function table(rows,{cellWidth,header=!1,align=[],fit,stream=process6.stdout,env=process6.env}={}){let cells=cellWidth===void 0?rows:rows.map((row)=>row.map((cell)=>truncate(cell.replaceAll(LINE_BREAKS," "),cellWidth)));if(outputMode(stream,env)==="agent")return cells.map((row)=>row.map((cell)=>Bun.stripANSI(cell).replaceAll(/[\t\r\n]+/g," ")).join("\t")).join(`
|
|
3
|
-
`);let widths=[];for(let row of cells)for(let[index,cell]of row.entries())widths[index]=Math.max(widths[index]??0,textWidth(cell));let shown=fit===void 0?cells:narrow(cells,widths,fit),colors=paint(stream,env),lines=shown.map((row)=>row.map((cell,index)=>{let width=widths[index]??0,gap=" ".repeat(Math.max(0,width-textWidth(cell)));if(align[index]==="right")return`${gap}${cell}`;return index===row.length-1?cell:`${cell}${gap}`}).join(" ").trimEnd()),rule=header&&takesControlCodes(stream,env)&&lines.length>1?[colors.dim(activeTheme().theme.glyphs.rule.repeat(Math.max(...lines.map(textWidth))))]:[];return lines.flatMap((line,index)=>header&&index===0?[colors.bold(line),...rule]:[line]).join(`
|
|
4
|
-
`)}function narrow(rows,widths,limit){let used=()=>widths.reduce((sum,width)=>sum+width,0)+2*Math.max(0,widths.length-1),floor=8;while(used()>limit){let widest=-1;for(let[index,width]of widths.entries())if(width>8&&width>(widths[widest]??0))widest=index;if(widest===-1)break;widths[widest]=Math.max(8,(widths[widest]??0)-(used()-limit))}return rows.map((row)=>row.map((cell,index)=>textWidth(cell)>(widths[index]??0)?cutToWidth(cell,widths[index]??0,"\u2026"):cell))}function jsonText(value,replacer,{stream=process6.stdout,env=process6.env}={}){return JSON.stringify(value,replacer,outputMode(stream,env)==="agent"?void 0:2)}function printJson(value){console.log(jsonText(value))}import process7 from"process";var OPTIONAL=/(?<!\x1B)\[[^\]]+\]/g,USAGE_PREFIX=/^usage:\s*/i,FULL_STOP=/\.$/,PROSE_MARKS=/`([^`\n]+)`|(?<![\w-])(--[a-z][\w-]*|-[a-z](?![\w-]))/gi;function usageLine(usage,colors=paint(process7.stdout),{summary:withSummary=!0}={}){let lines=usage.replace(USAGE_PREFIX,"").split(`
|
|
5
|
-
`),blank=lines.indexOf(""),synopses=blank===-1?lines:lines.slice(0,blank),details=blank===-1?[]:lines.slice(blank+1),colon=synopses[0].indexOf(": "),inline=synopses[0].slice(colon+2),summary=colon===-1?details.shift():`${inline.charAt(0).toUpperCase()}${inline.slice(1)}`;if(colon!==-1)synopses[0]=synopses[0].slice(0,colon);let head=`${colors.bold("Usage:")} ${synopses.map((line)=>line.replaceAll(OPTIONAL,(part)=>colors.dim(part))).join(`
|
|
6
|
-
`)}`,lead=summary===void 0||!withSummary?[]:["",colors.bold(prose(summary,colors))],rest=details.length===0?[]:["",...details.map((line)=>prose(line,colors))];return[head,...lead,...rest].join(`
|
|
7
|
-
`)}function prose(line,colors){if(colors.cyan("x")==="x")return line;return line.replaceAll(PROSE_MARKS,(match,code,flag)=>code===void 0?colors.cyan(flag??match):colors.bold(code))}function helpText(usage,options,colors=paint(process7.stdout),{examples=[],exits=[],bin,columns}={}){let{summary}=description(usage);return[...bin===void 0?[usageLine(usage,colors)]:[`${colors.bold(bin.name)} ${colors.dim(bin.version())}${summary===""?"":` ${summary}`}`,"",usageLine(usage,colors,{summary:!1})],"",colors.bold("Options:"),...optionRows(options,colors,columns),...exitRows(exits,colors),...exampleRows(examples,colors)].join(`
|
|
8
|
-
`)}function exitRows(exits,colors=paint(process7.stdout)){if(exits.length===0)return[];return["",`${colors.bold("Exit codes:")} ${exits.map(([code,meaning])=>`${colors.cyan(String(code))} ${meaning}`).join(", ")}`]}function wantsHelpJson(env=process7.env,argv){if(env.KIT_HELP==="json")return!0;if(argv===void 0)return!1;let end=argv.indexOf("--"),own=end===-1?argv:argv.slice(0,end);if(own.includes("--help=json"))return!0;return(own.includes("--help")||own.includes("-h")||own[0]==="help")&&own.includes("--json")}function description(usage,{examples=[],replaces,exits}={},options){let lines=usage.replace(USAGE_PREFIX,"").split(`
|
|
9
|
-
`),first=lines[0],colon=first.indexOf(": "),prose=lines[lines.indexOf("")+1]??"",fallback=lines.includes("")?`${prose.charAt(0).toLowerCase()}${prose.slice(1)}`.replace(FULL_STOP,""):"";return{synopsis:colon===-1?first:first.slice(0,colon),summary:colon===-1?fallback:first.slice(colon+2),...replaces===void 0?{}:{replaces},examples:examples.map((example)=>typeof example==="string"?{line:example}:{line:example[0],note:example[1]}),...exits===void 0?{}:{exits:exits.map(([code,meaning])=>({code,meaning}))},...options===void 0?{}:{options:Object.entries(options).map(([name,{short,description}])=>({name,...short===void 0?{}:{short},...description===void 0?{}:{description}}))}}}var MAX_AGENT_EXAMPLES=2;function exampleRows(examples,colors=paint(process7.stdout)){if(examples.length===0)return[];let shown=outputMode()==="agent"?examples.slice(0,MAX_AGENT_EXAMPLES):examples;return["",colors.bold("Examples:"),...shown.map((example)=>typeof example==="string"?` ${example}`:` ${example[0]} ${colors.dim(`# ${example[1]}`)}`)]}var MAX_INLINE_CHOICES=24;function wrapText(text,limit){if(text.length<=limit)return[text];let lines=[],current="";for(let word of text.split(" "))if(current==="")current=word;else if(current.length+1+word.length<=limit)current=`${current} ${word}`;else lines.push(current),current=word;if(current!=="")lines.push(current);return lines}function optionRows(options,colors=paint(process7.stdout),columns){let rows=Object.entries(options).map(([name,option])=>{let short=option.short===void 0?" ":`${colors.cyan(`-${option.short}`)}, `,choices=option.choices?.join("|"),inline=choices!==void 0&&choices.length<=MAX_INLINE_CHOICES,named=inline?`<${choices}>`:"<value>",placeholder=option.optional===void 0?named:`[${named}]`,value=option.type==="string"?` ${colors.dim(placeholder)}`:"",described=choices===void 0||inline?option.description??"":[option.description,`one of ${option.choices.join(", ")}`].filter(Boolean).join("; ");return{flag:`${short}${colors.cyan(`--${name}`)}${value}`,width:`-x, --${name}`.length+(option.type==="string"?placeholder.length+1:0),description:described}}),width=Math.max(0,...rows.map((row)=>row.width)),indent=2+width+2,room=columns!==void 0&&columns-indent>=20?columns-indent:void 0;return rows.flatMap((row)=>{if(row.description==="")return[` ${row.flag}`];let wrapped=room===void 0?[row.description]:wrapText(row.description,room),[first="",...rest]=wrapped;return[` ${row.flag}${" ".repeat(width-row.width)} ${colors.dim(first)}`,...rest.map((line)=>`${" ".repeat(indent)}${colors.dim(line)}`)]})}import{fstatSync}from"fs";import process8 from"process";var WHOLE=/^\d+$/;function wholeNumber(value,name,fallback,min=1){if(value===void 0)return fallback;let number=Number(value);if(!WHOLE.test(value)||!Number.isSafeInteger(number)||number<min)badUsage(`${name.startsWith("<")?name:`--${name}`} takes a whole number from ${min}, not ${value}`);return number}var BARE_DURATION=/^\d+(?:\.\d+)?$/,DURATION=/^(?:\d+(?:\.\d+)?(?:ms|min|[smhd]))+$/,DURATION_PART=/(\d+(?:\.\d+)?)(ms|min|[smhd])/g,UNIT_MS={ms:1,s:1000,m:60000,min:60000,h:3600000,d:86400000};function durationMs(text,unit){if(BARE_DURATION.test(text))return Number(text)*UNIT_MS[unit];if(!DURATION.test(text))return 0;let ms=0;for(let[,amount,part]of text.matchAll(DURATION_PART))ms+=Number(amount)*UNIT_MS[part];return ms}function duration(value,name,fallback,unit="s"){if(value===void 0)return fallback;let ms=durationMs(value.trim(),unit);if(ms<1)badUsage(`--${name} takes a duration such as 30s, 5m, 1h or 7d, not ${value}`);return ms}function isStdinPiped(){let stat=fstatSync(0);return stat.isFIFO()||stat.isFile()}async function readInput(path,{noStdin="nothing is piped on stdin"}={}){if(path==="-"){if(process8.stdin.isTTY)fail(noStdin);return Bun.stdin.text()}let file=Bun.file(path);if(!await file.exists())fail(`no file ${path}`);return file.text()}var DASHES=/^-+/;function jsonOption(holds){return{type:"boolean",description:holds===void 0?"print JSON":`print JSON: ${holds}`}}var EXIT=Symbol.for("@kaynooo/cli-kit/Exit");class Exit extends Error{code;hint;[EXIT]=!0;constructor(message,code,hint){super(message);this.code=code;this.hint=hint}static[Symbol.hasInstance](value){if(this!==Exit)return Function.prototype[Symbol.hasInstance].call(this,value);return typeof value==="object"&&value!==null&&value[EXIT]===!0}}function fail(message,code=2,hint){throw new Exit(message,code,hint)}class UsageError extends Exit{constructor(message,hint){super(message,2,hint)}}function badUsage(message){throw new UsageError(message)}class HelpShown extends Exit{constructor(){super("help shown",0)}}class Completing{options;positionals;candidates;constructor(options,positionals=[],candidates={}){this.options=options;this.positionals=positionals;this.candidates=candidates}}var completion={active:!1},heading={bin:void 0},OUTPUT_OPTIONS={color:{type:"string",choices:["auto","always","never"],description:"auto (the default) colours on a terminal alone"},plain:{type:"boolean",description:"plain text, no colour or spinner: --color never"}};function applyOutput(color,plain,env=process9.env){let when=plain===!0?"never":color??"auto";if(when==="auto")return;if(when!=="always"&&when!=="never")badUsage(`--color takes auto, always or never, not ${when}`);if(when==="always")env.FORCE_COLOR="1",delete env.NO_COLOR;else env.NO_COLOR="1",delete env.FORCE_COLOR}function parse(args,usage,options,settings={}){let output=Object.fromEntries(Object.entries(OUTPUT_OPTIONS).filter(([name])=>!(name in options))),all={...options,...output,help:{type:"boolean",short:"h",description:"show this help"}},listing=listed(all,settings.allowNegative===!0);if(completion.active)throw new Completing(listing,settings.positionals,settings.candidates);let{own,rest}=settings.trailing===!0?splitTrailing(args,all,settings.positionals?.length??0):splitRest(args,settings.rest===!0),helpJson=wantsHelpJson(process9.env,own),stripHelpJson=(arg)=>{if(arg==="--help=json")return["--help"];return arg==="--json"&&!("json"in options)?[]:[arg]},normalized=helpJson?own.flatMap(stripHelpJson):own,parsed;try{parsed=parseArgs({args:joinDashValues(withBare(withAliases(normalized,all),all),all),options:all,allowPositionals:!0,allowNegative:settings.allowNegative===!0,strict:!0})}catch(error){let message=parseError(error);throw new UsageError(message,nearestOption(message,all,settings.allowNegative===!0))}let values=parsed.values;if(applyOutput("color"in output?values.color:void 0,"plain"in output?values.plain:void 0),values.help===!0){let columns=takesControlCodes(process9.stdout)?process9.stdout.columns:void 0;throw console.log(helpJson?JSON.stringify(description(usage,settings,listing)):helpText(usage,listing,void 0,{...settings,bin:heading.bin,columns})),new HelpShown}if(checkChoices(parsed.values,all),checkConflicts(parsed.values,all),settings.positionals!==void 0)checkPositionals(parsed.positionals,settings.positionals);return{...parsed,values:parsed.values,positionals:parsed.positionals,rest}}function splitRest(args,passes){let separator=passes?args.indexOf("--"):-1;return{own:separator===-1?args:args.slice(0,separator),rest:separator===-1?void 0:args.slice(separator+1)}}function splitTrailing(args,options,count){let takesValue=(word)=>!word.includes("=")&&Object.entries(options).some(([name,{short,type}])=>type==="string"&&(word===`--${name}`||word===`-${short}`)),seen=0;if(count===0)return{own:args,rest:void 0};for(let at=0;at<args.length;at++){let word=args[at];if(word==="--")break;if(word.startsWith("-")){if(takesValue(word))at++;continue}if(seen++,seen===count)return{own:args.slice(0,at+1),rest:args.slice(at+1)}}return{own:args,rest:void 0}}function listed(options,allowNegative){if(!allowNegative)return options;return Object.fromEntries(Object.entries(options).flatMap(([name,option])=>{if(option.type!=="boolean"||option.negative===void 0)return[[name,option]];return[...option.description===void 0?[]:[[name,option]],[`no-${name}`,{type:"boolean",description:option.negative}]]}))}function withAliases(args,options){let named=new Map(Object.entries(options).flatMap(([name,{aliases=[]}])=>aliases.map((alias)=>[`--${alias}`,`--${name}`])));if(named.size===0)return args;let separator=args.indexOf("--");return[...(separator===-1?args:args.slice(0,separator)).map((arg)=>{let at=arg.indexOf("="),current=named.get(at===-1?arg:arg.slice(0,at));return current===void 0?arg:`${current}${at===-1?"":arg.slice(at)}`}),...separator===-1?[]:args.slice(separator)]}function withBare(args,options){let bare=new Map(Object.entries(options).flatMap(([name,{short,optional}])=>optional===void 0?[]:[[`--${name}`,optional],...short===void 0?[]:[[`-${short}`,optional]]]));if(bare.size===0)return args;let separator=args.indexOf("--"),own=separator===-1?args:args.slice(0,separator);return[...own.flatMap((arg,index)=>{let optional=bare.get(arg),next=own[index+1],value=next!==void 0&&(optional?.accepts===void 0?!next.startsWith("-"):optional.accepts.test(next));return optional===void 0||value?[arg]:[arg,optional.bare]}),...separator===-1?[]:args.slice(separator)]}function checkConflicts(values,options){let given=(name)=>values[name]!==void 0&&values[name]!==!1;for(let[name,{conflicts=[]}]of Object.entries(options)){let other=given(name)?conflicts.find(given):void 0;if(other!==void 0)badUsage(`--${name} cannot be used with --${other}`)}}function checkChoices(values,options){for(let[name,option]of Object.entries(options)){if(option.choices===void 0)continue;let given=values[name];for(let value of Array.isArray(given)?given:[given])if(typeof value==="string")oneOf(value,name,option.choices)}}function oneOf(value,name,choices){if(!choices.includes(value))badUsage(`${name.startsWith("<")?name:`--${name}`} takes one of ${choices.join(", ")}, not ${value}`);return value}function checkPositionals(given,names){let variadic=names.at(-1)?.replace("]","").endsWith("...")===!0,required=names.filter((name)=>!name.startsWith("[")).length;if(given.length<required)badUsage(`missing ${names[given.length]}`);if(!variadic&&given.length>names.length)badUsage(`unexpected argument ${given[names.length]}`)}function joinDashValues(args,options){let longOf=new Map(Object.entries(options).flatMap(([name,option])=>option.short===void 0?[[`--${name}`,name]]:[[`--${name}`,name],[`-${option.short}`,name]])),isOption=(arg)=>arg==="--"||longOf.has(arg.includes("=")?arg.slice(0,arg.indexOf("=")):arg),joined=[];for(let i=0;i<args.length;i++){let arg=args[i]??"";if(arg==="--")return[...joined,...args.slice(i)];let name=longOf.get(arg),next=args[i+1];if(name!==void 0&&options[name]?.type==="string"&&next!==void 0&&next.startsWith("-")&&next!=="-"&&!isOption(next))joined.push(`--${name}=${next}`),i++;else joined.push(arg)}return joined}function parseError(error){let message=upTo(error instanceof Error?error.message:String(error),". ");return`${message.charAt(0).toLowerCase()}${message.slice(1)}`}var UNKNOWN_OPTION=/^unknown option '(-[^']+)'/;function nearestOption(message,options,allowNegative){let typed=UNKNOWN_OPTION.exec(message)?.[1];if(typed===void 0)return;let word=typed.replace(DASHES,"");if(word.length<2&&!typed.startsWith("--"))return;let known=Object.entries(options).flatMap(([name,option])=>[...option.short===void 0?[]:[`-${option.short}`],`--${name}`,...allowNegative&&option.type==="boolean"?[`--no-${name}`]:[]]),meant=closest(word,known.map((flag)=>flag.replace(DASHES,"")));return meant===void 0?void 0:`did you mean ${known.find((flag)=>flag.replace(DASHES,"")===meant)}?`}import{homedir as homedir3}from"os";import{join as join4}from"path";import process10 from"process";var SKIPPED_FOLDERS=new Set(["node_modules","vendor","dist","build","target","coverage","venv","__pycache__"]);function ignoredFolders(extra=[],where={}){let configured=readUserConfig("config",where).ignore,names=Array.isArray(configured)?configured.filter((name)=>typeof name==="string"&&name!==""):[];return new Set([...SKIPPED_FOLDERS,...extra,...names])}function cacheFolder({home=homedir3(),env=process10.env}={}){return xdgFolder(env.XDG_CACHE_HOME,join4(home,".cache"))}
|
|
10
|
-
export{bo,outputMode,isInteractive,xdgFolder,userConfigPath,userConfigReadPath,readMainConfig,readUserConfig,tinted,shaded,activeTheme,takesControlCodes,paint,marked,ok,note,warn,problem,role,distance,closest,cutToWidth,formatDuration,formatElapsed,formatAge,truncate,textWidth,table,printJson,usageLine,wantsHelpJson,description,exampleRows,optionRows,wholeNumber,duration,isStdinPiped,readInput,jsonOption,Exit,fail,UsageError,badUsage,HelpShown,Completing,completion,OUTPUT_OPTIONS,applyOutput,parse,oneOf,ignoredFolders,cacheFolder};
|
package/dist/chunk-1g1jb7hz.js
DELETED
package/dist/chunk-4pzedt0v.js
DELETED
|
@@ -1,69 +0,0 @@
|
|
|
1
|
-
// @bun
|
|
2
|
-
import{outputMode,xdgFolder,readUserConfig,tinted,shaded,activeTheme,takesControlCodes,paint,marked,closest,cutToWidth,formatDuration,formatElapsed,usageLine,wantsHelpJson,description,exampleRows,optionRows,wholeNumber,Exit,UsageError,badUsage,HelpShown,Completing,completion,OUTPUT_OPTIONS,applyOutput}from"./chunk-0eb0ncqy.js";var SEVERITIES=["low","moderate","high","critical"];function severityRank(severity){return SEVERITIES.indexOf(severity)}function isIgnored(advisory,ignore){return ignore.includes(advisory.ghsa??"")||ignore.includes(String(advisory.id))}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 process3 from"process";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()}}}var FRAMES=["\u280B","\u2819","\u2839","\u2838","\u283C","\u2834","\u2826","\u2827","\u2807","\u280F"],FRAME_MS=200,BAR_WIDTH=20,CLEAR_BELOW="\r\x1B[J",CTRL_C=3,CONSOLE_METHODS=["log","info","warn","error","debug","dir","dirxml","table","trace","group","groupCollapsed","count","timeEnd","timeLog","assert"];function liveRegion(render,stream=process3.stderr,env=process3.env){if(!takesControlCodes(stream,env))return{redraw:()=>{return},print:(text)=>void stream.write(`${text}
|
|
3
|
-
`),stop:()=>{return},pause:()=>()=>{return}};let write=stream.write.bind(stream),frame=0,drawn=!1,paused=!1,stopped=!1,columns=()=>{let now=stream.getWindowSize?.()[0]??stream.columns;return now===void 0||now===0?80:now},clear=()=>{if(drawn)write(CLEAR_BELOW);drawn=!1},draw=()=>{if(paused)return;let width=columns()-1,height=stream.rows===void 0||stream.rows===0?24:stream.rows,lines=render(FRAMES[frame++%FRAMES.length]).slice(0,Math.max(1,height-1)).map((line)=>cutToWidth(line,width));if(lines.length===0){clear();return}write(`${CLEAR_BELOW}${lines.join(`
|
|
4
|
-
`)}${lines.length>1?`\x1B[${lines.length-1}A`:""}\r`),drawn=!0},timer=setInterval(draw,FRAME_MS);stream.on?.("resize",draw);let restore=interceptOutput(clear),release=swallowInput(),onExit=()=>{clear(),release()},signals=holdSignals(stop);function stop(){stopped=!0,clearInterval(timer),stream.off?.("resize",draw),clear(),restore(),release(),process3.off("exit",onExit),signals.release()}function pause(){if(paused||stopped)return()=>{return};return paused=!0,clearInterval(timer),stream.off?.("resize",draw),clear(),restore(),release(),()=>{if(!paused||stopped)return;paused=!1,timer=setInterval(draw,FRAME_MS),timer.unref(),stream.on?.("resize",draw),restore=interceptOutput(clear),release=swallowInput(),draw()}}return timer.unref(),process3.on("exit",onExit),{redraw:draw,print:(text)=>{clear(),write(`${text}
|
|
5
|
-
`),draw()},stop,pause}}function progressLine(stream=process3.stderr,env=process3.env){let colors=paint(stream,env),write=stream.write.bind(stream),begun=performance.now(),started=begun,current,region=liveRegion((spinner)=>current===void 0?[]:[tintedParts(progressParts(current,spinner,performance.now()-started),colors)],stream,env),end=(line)=>{region.stop(),write(`${line}
|
|
6
|
-
`)};return{update:(progress)=>{let step=current?.step;if(current=progress,progress.step!==step)started=performance.now(),region.redraw()},stop:region.stop,pause:region.pause,done:(text)=>end(marked("ok",text,stream,formatDuration(performance.now()-begun),env)),failed:(text)=>end(marked("problem",text,stream,void 0,env))}}function progressParts({step,done,total,unit},spinner,ms){let{theme}=activeTheme(),parts=[{text:spinner,tint:(colors)=>tinted(colors,theme.colors.accent)},{text:` ${step}`,tint:()=>plain}];if(total!==void 0&&total>0){let counted=Math.min(done??0,total),filled=Math.round(counted/total*BAR_WIDTH);parts.push({text:" ",tint:()=>plain},{text:theme.glyphs.bar.repeat(filled),tint:(colors)=>()=>shaded(theme,colors,theme.glyphs.bar,filled,BAR_WIDTH)},{text:theme.glyphs.bar.repeat(BAR_WIDTH-filled),tint:(colors)=>colors.dim},{text:` ${counted}/${total}${unit===void 0?"":` ${unit}`}`,tint:(colors)=>colors.dim})}return parts.push({text:` ${formatElapsed(ms)}`,tint:(colors)=>colors.dim}),parts}function plain(text){return text}function tintedParts(parts,colors){return parts.map(({text,tint})=>tint(colors)(text)).join("")}function swallowInput(){let input=process3.stdin;if(!input.isTTY)return()=>{return};let onData=(data)=>{if(data.includes(CTRL_C))process3.kill(process3.pid,"SIGINT")};input.setRawMode(!0),input.on("data",onData),input.resume();let released=!1;return()=>{if(released)return;released=!0,input.off("data",onData),input.pause(),input.setRawMode(!1)}}function interceptOutput(clear){let wrapped=[...CONSOLE_METHODS.map((name)=>[console,name]),[process3.stdout,"write"],[process3.stderr,"write"]].map(([target,name])=>{let original=Reflect.get(target,name),wrapper=(...args)=>(clear(),original.apply(target,args));return Reflect.set(target,name,wrapper),{target,name,original,wrapper}});return()=>{for(let{target,name,original,wrapper}of wrapped)if(Reflect.get(target,name)===wrapper)Reflect.set(target,name,original)}}import{readFileSync as readFileSync4,realpathSync as realpathSync2}from"fs";import{dirname as dirname2,join as join2}from"path";import process7 from"process";import process4 from"process";var SOCKET_VARIABLE="KAYNOOO_ASKPASS_SOCKET";async function askpassClient(argv){let socketPath=process4.env[SOCKET_VARIABLE];if(socketPath===void 0)return;let request={prompt:argv[0]??"",...process4.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)}
|
|
7
|
-
`),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 process4.stdout.write(`${answer}
|
|
8
|
-
`),0}var COMPLETION_SHELLS=["fish","bash","zsh"];function completionScript(shell,bins,header=`# Generated by \`${bins[0]} --completions ${shell}\``){if(shell==="fish")return`${header}
|
|
9
|
-
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'
|
|
10
|
-
set -l tokens (commandline -xpc 2>/dev/null; or commandline -opc)
|
|
11
|
-
set -l current (commandline -ct)
|
|
12
|
-
for line in ($bin __complete $tokens[2..-1] $current 2>/dev/null)
|
|
13
|
-
if test "$line" = __files__
|
|
14
|
-
__fish_complete_path $current
|
|
15
|
-
else
|
|
16
|
-
echo $line
|
|
17
|
-
end
|
|
18
|
-
end
|
|
19
|
-
end
|
|
20
|
-
${bins.map((bin)=>`complete -c ${bin} -f -a '(__kaynooo_cli_complete ${bin})'
|
|
21
|
-
`).join("")}`;if(shell==="bash")return`${header}
|
|
22
|
-
__kaynooo_cli_complete() {
|
|
23
|
-
local IFS=$'\\n' cur=\${COMP_WORDS[COMP_CWORD]} line words=
|
|
24
|
-
local -a lines
|
|
25
|
-
COMPREPLY=()
|
|
26
|
-
lines=($("\${COMP_WORDS[0]}" __complete "\${COMP_WORDS[@]:1:COMP_CWORD}" 2>/dev/null))
|
|
27
|
-
for line in "\${lines[@]}"; do
|
|
28
|
-
if [[ $line == __files__ ]]; then
|
|
29
|
-
COMPREPLY+=($(compgen -f -- "$cur"))
|
|
30
|
-
else
|
|
31
|
-
words+="\${line%%$'\\t'*}"$'\\n'
|
|
32
|
-
fi
|
|
33
|
-
done
|
|
34
|
-
COMPREPLY+=($(compgen -W "$words" -- "$cur"))
|
|
35
|
-
}
|
|
36
|
-
complete -F __kaynooo_cli_complete ${bins.join(" ")}
|
|
37
|
-
`;return`${header}
|
|
38
|
-
__kaynooo_cli_complete() {
|
|
39
|
-
local line
|
|
40
|
-
local -a described plain
|
|
41
|
-
for line in \${(f)"$("\${words[1]}" __complete "\${(@)words[2,CURRENT]}" 2>/dev/null)"}; do
|
|
42
|
-
if [[ $line == __files__ ]]; then
|
|
43
|
-
_files
|
|
44
|
-
elif [[ $line == *$'\\t'* ]]; then
|
|
45
|
-
described+=("\${\${line%%$'\\t'*}//:/\\\\:}:\${line#*$'\\t'}")
|
|
46
|
-
else
|
|
47
|
-
plain+=("$line")
|
|
48
|
-
fi
|
|
49
|
-
done
|
|
50
|
-
(( \${#described} )) && _describe -V value described
|
|
51
|
-
(( \${#plain} )) && compadd -- "\${plain[@]}"
|
|
52
|
-
return 0
|
|
53
|
-
}
|
|
54
|
-
__kaynooo_cli_register() {
|
|
55
|
-
add-zsh-hook -d precmd __kaynooo_cli_register
|
|
56
|
-
(( $+functions[compdef] )) || { autoload -Uz compinit && compinit }
|
|
57
|
-
compdef __kaynooo_cli_complete $__kaynooo_cli_bins
|
|
58
|
-
}
|
|
59
|
-
autoload -Uz add-zsh-hook
|
|
60
|
-
add-zsh-hook precmd __kaynooo_cli_register
|
|
61
|
-
typeset -gaU __kaynooo_cli_bins
|
|
62
|
-
__kaynooo_cli_bins+=(${bins.join(" ")})
|
|
63
|
-
`}var COMPLETE="__complete",FILES="__files__",COMPLETIONS="--completions";function shown(commands){return Object.fromEntries(Object.entries(commands).filter(([,{hidden}])=>hidden!==!0))}async function resolveSummary(summary){return typeof summary==="string"?summary:summary()}function lookup({commands,aliases},word){let name=aliases!==void 0&&Object.hasOwn(aliases,word)?aliases[word]??word:word;return Object.hasOwn(commands,name)?commands[name]:void 0}function scopeOf(commands,extra,aliases){return{commands:typeof commands==="function"?{}:commands,lazy:[...typeof commands==="function"?[commands]:[],...extra===void 0?[]:[extra]],aliases}}async function expand(scope,words){if(scope.lazy.length===0)return scope;let commands={...scope.commands};for(let added of await Promise.all(scope.lazy.map(async(lazy)=>lazy(words))))for(let[name,command]of Object.entries(added))commands[name]??=command;return{...scope,commands,lazy:[]}}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({})}async function optionsOf(run){return(await completingOf(run)).options}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)}async function candidates(scope,defaultCommand,words,before=[]){let[word="",...rest]=words,listing=rest.length===0&&!word.startsWith("-"),{commands}=scope,command=lookup(scope,word);if(listing||command===void 0){let expanded=await expand(scope,[...before,...words]);commands=expanded.commands,command=lookup(expanded,word)}if(listing){let own=await Promise.all(Object.entries(shown(commands)).map(async([name,{summary}])=>`${name} ${await resolveSummary(summary)}`)),fallback=defaultCommand===void 0?void 0:commands[defaultCommand],values=fallback!==void 0&&"run"in fallback?await leafCandidates(fallback.run,[word]):[],valueOf=(line)=>line.slice(0,line.includes("\t")?line.indexOf("\t"):void 0);return[...own,...values.filter((line)=>line!==FILES&&!Object.hasOwn(commands,valueOf(line)))]}if(command===void 0){let fallback=defaultCommand===void 0?void 0:commands[defaultCommand];return fallback!==void 0&&"run"in fallback?leafCandidates(fallback.run,words):[]}return"commands"in command?candidates(scopeOf(command.commands,command.extraCommands,command.aliases),void 0,rest,[...before,word]):leafCandidates(command.run,rest)}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 process5 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=process5.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${process5.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=process5.stderr,env=process5.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}from"os";import{dirname,join}from"path";import process6 from"process";var CLI_FOLDER="kaynooo-cli";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,join(homedir(),".local","state"))}function usagePath(env=process6.env){return join(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(`
|
|
64
|
-
`).filter(Boolean),kept=`${lines.slice(Math.floor(lines.length/2)).join(`
|
|
65
|
-
`)}
|
|
66
|
-
`,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)}
|
|
67
|
-
`,{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"}};async function commandRows(all,colors){let commands=shown(all),width=Math.max(0,...Object.keys(commands).map((name)=>name.length)),groups=new Map([["Commands:",[]]]),summaries=await Promise.all(Object.values(commands).map(async({summary})=>resolveSummary(summary)));for(let[index,[name,{group}]]of Object.entries(commands).entries()){let label=group===void 0?"Commands:":`${group}:`,rows=groups.get(label)??[];rows.push(` ${colors.cyan(name.padEnd(width))} ${colors.dim(summaries[index])}`),groups.set(label,rows)}return[...groups].filter(([,rows])=>rows.length>0).flatMap(([label,rows],index)=>[...index===0?[]:[""],colors.bold(label),...rows])}function takeOutputFlags(argv){let index=0;for(;index<argv.length;index++){let word=argv[index];if(word==="--plain")applyOutput(void 0,!0);else if(word.startsWith("--color="))applyOutput(word.slice(8),void 0);else if(word==="--color"&&argv[index+1]!==void 0)applyOutput(argv[++index],void 0);else break}return argv.slice(index)}async function help({path,header,summary:lazySummary,commands,defaultCommand,examples,replaces},stream,json=!1){let colors=paint(stream),prefix=path.join(" "),summary=await resolveSummary(lazySummary);if(json||wantsHelpJson())return JSON.stringify(description(`${prefix} <command> [options]: ${summary}`,{examples,replaces}));let columns=takesControlCodes(stream)?stream.columns:void 0,fallback=defaultCommand===void 0?void 0:commands[defaultCommand],options=fallback!==void 0&&"run"in fallback?await optionsOf(fallback.run):void 0,own=Object.entries(options??{}).filter(([name])=>!(name in TOP_OPTIONS));return[header(colors,summary),"",usageLine(`${prefix} ${defaultCommand===void 0?colors.cyan("<command>"):`[${colors.cyan("<command>")}]`} [options]`,colors),"",...await commandRows(commands,colors),...own.length===0?[]:["",`${colors.bold(`Options of ${defaultCommand}:`)} ${colors.dim("the command run when none is named")}`,...optionRows(Object.fromEntries(own),colors,columns)],"",colors.bold("Options:"),...optionRows(path.length===1?TOP_OPTIONS:LEVEL_OPTIONS,colors,columns),...exampleRows(examples??[],colors),"",`${colors.dim("Run")} ${prefix} ${colors.cyan("<command>")} --help ${colors.dim("for its options.")}`].join(`
|
|
68
|
-
`)}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?"":`
|
|
69
|
-
${styled?tint(label):`${label}:`} ${text}`;console.error(`${head} ${message}${under("cause",cause,colors.dim)}${under("hint",hint,colors.yellow)}`)}function printJsonError(message,hint,cause,extra){console.error(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}async function dispatch(level,typed,{version,redact}){let prefix=level.path.join(" "),argv;try{argv=takeOutputFlags(typed)}catch(error){return{code:reportThrown(prefix,error,redact,wantsJson(typed)),meta:!1}}let[name,...args]=argv,fallback=level.defaultCommand===void 0?void 0:level.commands[level.defaultCommand];if(name===void 0&&level.runBare&&fallback!==void 0&&"run"in fallback)try{return{code:await fallback.run([]),meta:!1}}catch(error){return{code:reportThrown(`${prefix} ${level.defaultCommand}`,error,redact,!1),meta:error instanceof HelpShown}}if(name===void 0&&level.path.length>1)return console.error(await help(await expand(level,[...level.path.slice(1),...argv]),process7.stderr)),{code:2,meta:!0};if(name==="help"&&args.length>0&&args[0]!=="--json")return dispatch(level,[...args,"--help"],{version,redact});if(name===void 0||name==="help"||name==="--help"||name==="-h"||name==="--help=json")return console.log(await help(await expand(level,[...level.path.slice(1),...argv]),process7.stdout,wantsHelpJson(process7.env,argv))),{code:0,meta:!0};if(level.path.length===1&&(name==="--version"||name==="-v"))return console.log(version()),{code:0,meta:!0};let command=lookup(level,name),rest=args,ran=name;if(command===void 0&&level.lazy.length>0)level=await expand(level,[...level.path.slice(1),...argv]),command=lookup(level,name);if(command===void 0&&level.defaultCommand!==void 0)command=level.commands[level.defaultCommand],rest=argv,ran=level.defaultCommand;if(command===void 0){let meant=closest(name,Object.keys(shown(level.commands))),hint=meant===void 0?`run ${prefix} --help for its commands`:`did you mean ${meant}?`;if(wantsJson(argv))printJsonError(`no command ${name}`,hint,void 0,{code:2,command:prefix});else printError(prefix,`no command ${name}`,hint);return{code:2,meta:!1}}if("commands"in command){let{summary}=command;return dispatch({path:[...level.path,name],header:(colors,text)=>`${colors.bold(`${prefix} ${name}`)} ${text}`,summary,...scopeOf(command.commands,command.extraCommands,command.aliases),defaultCommand:command.defaultCommand,runBare:command.runBare===!0,examples:command.examples,replaces:void 0},rest,{version,redact})}try{return{code:await command.run(rest),meta:!1}}catch(error){return{code:reportThrown(`${prefix} ${ran}`,error,redact,wantsJson(rest)),meta:error instanceof HelpShown}}}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(join2(dir,"package.json"),"utf8"));if(typeof version==="string")return version}catch{}if(dirname2(dir)===dir)return"0.0.0"}}async function runCli(cli,argv=scriptArgs()){let answered=await askpassClient(argv);if(answered!==void 0)return answered;if(argv[0]===COMPLETE)return printCandidates(candidates(scopeOf(cli.commands,cli.extraCommands,cli.aliases),cli.defaultCommand,argv.slice(1)));if(argv[0]===COMPLETIONS||argv[0]?.startsWith(`${COMPLETIONS}=`)===!0)return printCompletionScript(cli.name,flagValue(argv),printError);let version=()=>cli.version??packageVersion(),started=performance.now(),{code,meta}=await dispatch({path:[cli.name],header:(colors,about)=>`${colors.bold(cli.name)} ${colors.dim(version())} ${about}`,summary:cli.about,...scopeOf(cli.commands,cli.extraCommands,cli.aliases),defaultCommand:cli.defaultCommand,runBare:cli.runBare===!0,examples:cli.examples,replaces:cli.replaces},argv,{version,redact:cli.redact}),command=commandPath(scopeOf(cli.commands,cli.extraCommands,cli.aliases),argv);if(notifyEnd(command===void 0?cli.name:`${cli.name} ${command}`,code,performance.now()-started),cli.usage!==!1&&!meta)try{recordUsage(usageEntry(cli.name,command,argv,code,{ms:performance.now()-started,mode:outputMode()}))}catch{}return code}function commandPath(scope,argv){let path=[],level=scope;for(let word of argv.filter((each)=>!each.startsWith("-"))){let command=lookup(level,word);if(command===void 0)break;if(path.push(word),!("commands"in command))break;level=scopeOf(command.commands,command.extraCommands,command.aliases)}return path.length===0?void 0:path.join(" ")}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 limitOptions(fallback){return{limit:{type:"string",short:"n",description:`show at most this many rows, the rest counted (${fallback})`},full:{type:"boolean",description:"show every row"}}}function limitOf(values,fallback){if(values.full===!0&&values.limit!==void 0)badUsage("--limit and --full exclude each other");if(values.full===!0||values.json===!0&&values.limit===void 0)return Number.POSITIVE_INFINITY;return wholeNumber(values.limit,"limit",fallback)}function moreFooter(more){return`${more} more, rerun with --full`}function capped(rows,limit){let more=rows.length-limit;return more>0?{shown:rows.slice(0,limit),footer:moreFooter(more)}:{shown:[...rows],footer:void 0}}async function pool(items,limit,task,onDone){let results=Array.from({length:items.length}),next=0,done=0;async function worker(){while(next<items.length){let index=next++;results[index]=await task(items[index]),onDone?.(++done,items.length)}}return await Promise.all(Array.from({length:Math.min(limit,items.length)},worker)),results}var{Glob}=globalThis.Bun;var SESSION_FILES=new Glob("*.json"),ACCOUNT_DIRS=new Glob("*/sessions");import{homedir as homedir2}from"os";import{join as join3,resolve as resolve2}from"path";import process8 from"process";function expandHome(path,home){if(path==="~")return home;return path.startsWith("~/")?join3(home,path.slice(2)):path}function configured(env,home){let folder=readUserConfig("config",{home,xdg:env.XDG_CONFIG_HOME}).workspace;return typeof folder==="string"&&folder!==""?folder:void 0}function workspaceRoot({given,env=process8.env,home=homedir2()}={}){let fromEnv=env.KAYNOOO_WORKSPACE===""?void 0:env.KAYNOOO_WORKSPACE;return resolve2(expandHome(given??fromEnv??configured(env,home)??join3(home,"Workspace"),home))}import{basename,dirname as dirname3,join as join4,relative,sep}from"path";var PARENT=`..${sep}`;export{SEVERITIES,severityRank,isIgnored,runCommand,liveRegion,progressLine,stateHome,runCli,limitOptions,limitOf,capped,pool,workspaceRoot};
|
package/dist/chunk-6eg316z7.js
DELETED
|
@@ -1,9 +0,0 @@
|
|
|
1
|
-
// @bun
|
|
2
|
-
import{role,formatAge,table,printJson,wholeNumber,isStdinPiped,readInput,jsonOption,fail,parse}from"./chunk-0eb0ncqy.js";import{fetchAdvisories,advisoriesFor,filterAdvisories,isPublic,unreachable,fetchPackument,fetchDownloads,DEFAULT_MIN_AGE_DAYS,parseSpec,analyze,registryFor,loadConfigs,DEFAULT_BLOCK_SEVERITY,loadSettings}from"./chunk-m8t5jkn0.js";import{registryDependencies}from"./chunk-apxff06c.js";import{dirname,resolve}from"path";var usage="pkg [check] <name>[@version]... | --from <package.json> | -\n\nChecks npm packages before they are added: the name exists, the newest version at least two weeks old (any age for the `trusted` setting's names, `@kaynooo/*` and `@kayjs/*` by default), downloads, licence, install scripts, a near miss of a popular name, and a changed publisher or lost provenance attestation.\nNames come from the arguments, from a package.json with --from, or from stdin.\nA `.pkgrc.json` with `licenses` refuses a licence outside the list, and `blockSeverity` a version with an advisory at that level or above.",EXITS=[[0,"every package passes"],[1,"one is blocked: missing, the version asked for is under the minimum age or has no date, its licence is outside the allowlist or an advisory reaches the threshold"],[2,"it could not check (the registry unreachable, slow or answering badly, a broken .pkgrc.json, bunfig.toml or .npmrc) or a usage error"]],options={json:jsonOption(),"min-age":{type:"string",description:`days a version must be old (${DEFAULT_MIN_AGE_DAYS}, or the minAge setting)`},from:{type:"string",description:"check the dependencies of this package.json"}},WORDS=/\s+/;async function checkPackage2(text,context){let spec=parseSpec(text),registry=registryFor(spec.name,context.configs),packument=await fetchPackument(spec.name,registry,context.fetcher),downloads=packument!==void 0&&isPublic(registry)?await fetchDownloads(spec.name,context.fetcher):void 0,input={spec,packument,downloads,registry:new URL(registry.url).host,now:context.now,minAgeDays:context.minAgeDays,licenses:context.settings?.licenses,trusted:context.settings?.trusted},report=analyze(input),blockSeverity=context.settings?.blockSeverity??DEFAULT_BLOCK_SEVERITY;if(report.version===void 0)return report;let safe=report.safe?.version,{found,unavailable,isUnsupported}=await fetchAdvisories({[spec.name]:safe===void 0||safe===report.version?[report.version]:[report.version,safe]},registry,context.fetcher);if(unavailable!==void 0&&isUnsupported!==!0)return unreachable(unavailable);let checked=analyze({...input,blockSeverity,advisories:advisoriesFor(found[spec.name],report.version),safeAdvisories:safe===void 0?[]:filterAdvisories(advisoriesFor(found[spec.name],safe),blockSeverity)});if(unavailable!==void 0)checked.warnings.push(`${unavailable}, so its known advisories are not checked`);return checked}function when(release,now){return release?.published===void 0?"":`, published ${formatAge(release.published,now)} (${release.published.slice(0,10)})`}function render2(report,now=Date.now(),stream=process.stdout,env=process.env){let id=role("id",stream,env),warn=role("warn",stream,env);if(!report.exists)return[id(report.name),...report.warnings.map((warning)=>` ${warn("warning:")} ${warning}`)].join(`
|
|
3
|
-
`);let asked=report.requested===void 0?"":` (asked for ${report.requested})`,rows=[["version",report.version===void 0?`none${asked}`:`${report.version}${asked}${when(report,now)}`],["latest",report.latest===void 0?"-":`${report.latest.version}${when(report.latest,now)}`],["safe",report.safe===void 0?"-":`${report.safe.version}${when(report.safe,now)}`],["downloads",report.downloads===void 0?"-":`${report.downloads.toLocaleString("en-US")} last week`],["license",report.license??"-"],["repository",report.repository??"-"],...Object.entries(report.installScripts).map(([name,command])=>[name,command])];return[`${id(report.name)}${report.description===void 0?"":`: ${report.description}`}`,table(rows.map(([key,value])=>[` ${key}`,value??""])),...report.warnings.map((warning)=>` ${warn("warning:")} ${warning}`)].join(`
|
|
4
|
-
`)}async function wanted(positionals,from){let names=positionals.filter((each)=>each!=="-"),fromFile=from===void 0?[]:registryDependencies(await readInput(from)).map(({name,spec})=>`${name}@${spec}`),fromStdin=positionals.includes("-")||names.length===0&&fromFile.length===0&&isStdinPiped()?(await readInput("-")).split(WORDS).filter((each)=>each!==""):[];return[...new Set([...names,...fromFile,...fromStdin])]}async function check2(args){let parsed=parse(args,usage,options,{exits:EXITS}),{values}=parsed,positionals=await wanted(parsed.positionals,values.from);if(positionals.length===0)fail(values.from===void 0?`a package name is needed
|
|
5
|
-
|
|
6
|
-
${usage}`:`${values.from} has no registry dependency to check`);let fromDir=values.from!==void 0&&values.from!=="-"?dirname(resolve(values.from)):void 0,settings=await loadSettings(fromDir),context={configs:await loadConfigs(fromDir),settings,minAgeDays:wholeNumber(values["min-age"],"min-age",settings.minAge??DEFAULT_MIN_AGE_DAYS,0)},reports=await Promise.all(positionals.map(async(text)=>checkPackage2(text,context)));if(values.json===!0)printJson(reports);else console.log(reports.map((report)=>render2(report)).join(`
|
|
7
|
-
|
|
8
|
-
`));return reports.some((report)=>report.blocked)?1:0}
|
|
9
|
-
export{checkPackage2,render2,check2};
|
package/dist/chunk-apxff06c.js
DELETED
|
@@ -1,3 +0,0 @@
|
|
|
1
|
-
// @bun
|
|
2
|
-
import{fail,ignoredFolders}from"./chunk-0eb0ncqy.js";import{existsSync,readdirSync,readFileSync}from"fs";import{dirname,join,relative}from"path";var LOCKFILES=[["bun.lock","bun"],["bun.lockb","bun"],["pnpm-lock.yaml","pnpm"],["yarn.lock","yarn"],["package-lock.json","npm"]],NPM_INSTALLS=["install","i","in","ins","inst","insta","instal","isnt","isnta","isntal","isntall"],NPM_TEST_INSTALLS=["it","install-test","cit","clean-install-test","install-ci-test"],ACTIONS={bun:actions({install:["install","i"],add:["add","a"],remove:["remove","rm"],update:["update"]}),pnpm:actions({install:["install","i"],add:["add"],remove:["remove","rm"],update:["update","up"]}),yarn:new Map([...actions({install:["","install"],add:["add"],remove:["remove"],update:["upgrade"]}),["upgrade-interactive",null],["import",null]]),npm:new Map([...actions({install:NPM_INSTALLS,add:["add"],frozen:["ci","clean-install","ic","install-clean","isntall-clean"],remove:["uninstall","unlink","remove","rm","r","un"],update:["update","u","up","upgrade","udpate"]}),...NPM_TEST_INSTALLS.map((name)=>[name,null])])};var DIR_FLAGS=new Set(["--cwd","-C","--dir","--prefix"]),VALUE_FLAGS=new Set([...DIR_FLAGS,"--filter","-F"]);function actions(byAction){return new Map(Object.entries(byAction).flatMap(([action,names])=>names.map((name)=>[name,action])))}var KINDS=["dependencies","devDependencies","optionalDependencies","peerDependencies"],MAX_DEPTH=5,LOCAL_SPEC=/[:/]/;function packageFiles(dir,depth,found,ignored=ignoredFolders()){let entries;try{entries=readdirSync(dir,{withFileTypes:!0})}catch{return found}for(let entry of entries)if(entry.isFile()&&entry.name==="package.json")found.push(join(dir,entry.name));else if(entry.isDirectory()&&depth<MAX_DEPTH&&!entry.name.startsWith(".")&&!ignored.has(entry.name))packageFiles(join(dir,entry.name),depth+1,found,ignored);return found}function managerFor(dir,root){for(let at=dir;;at=dirname(at)){let lockfile=LOCKFILES.find(([file])=>existsSync(join(at,file)));if(lockfile!==void 0)return lockfile[1];if(at===root||at===dirname(at))return"bun"}}var ALIAS=/^npm:(@[^@/]+\/[^@/]+|[^@/]+)@(.+)$/;function readManifest(path){try{return JSON.parse(readFileSync(path,"utf8"))}catch{return}}function findConsumers(name,root){let consumers=[];for(let path of packageFiles(root,0,[]).sort()){let manifest=readManifest(path);if(manifest===void 0)continue;let seen=new Set;for(let kind of KINDS)for(let[key,spec]of Object.entries(manifest[kind]??{})){let aliased=typeof spec==="string"&&key!==name&&ALIAS.exec(spec)?.[1]===name;if(typeof spec==="string"&&(key===name||aliased)&&!seen.has(key))seen.add(key),consumers.push({dir:relative(root,dirname(path))||".",path,kind,spec,...aliased?{alias:key}:{},manager:managerFor(dirname(path),root)})}}return consumers}var MIN_SIMILAR=3;function similarDependencies(name,root){let base=name.slice(name.lastIndexOf("/")+1).toLowerCase(),found=new Set;for(let path of packageFiles(root,0,[]).sort()){let manifest=readManifest(path);for(let kind of KINDS)for(let[key,spec]of Object.entries(manifest?.[kind]??{})){let target=typeof spec==="string"?ALIAS.exec(spec)?.[1]:void 0;for(let candidate of[key,target]){let last=candidate?.slice(candidate.lastIndexOf("/")+1).toLowerCase();if(candidate!==void 0&&last!==void 0&&candidate!==name&&last.length>=MIN_SIMILAR&&base.length>=MIN_SIMILAR&&(last.includes(base)||base.includes(last)))found.add(candidate)}}}return[...found].toSorted().slice(0,5)}function isLocal(consumer){return consumer.alias===void 0&&LOCAL_SPEC.test(consumer.spec)}function wantedVersion(consumer){return consumer.alias===void 0?consumer.spec:ALIAS.exec(consumer.spec)?.[2]??consumer.spec}var BUN_KIND_FLAGS={dependencies:[],devDependencies:["--dev"],optionalDependencies:["--optional"],peerDependencies:["--peer"]},PNPM_KIND_FLAGS={dependencies:[],devDependencies:["-D"],optionalDependencies:["-O"],peerDependencies:["--save-peer"]},YARN_KIND_FLAGS={dependencies:[],devDependencies:["-D"],optionalDependencies:["-O"],peerDependencies:["-P"]},NPM_KIND_FLAGS={dependencies:[],devDependencies:["--save-dev"],optionalDependencies:["--save-optional"],peerDependencies:["--save-peer"]},RANGE_PREFIX=/^[~^]/;function addCommand(consumer,name,version){let isAlias=consumer.alias!==void 0,prefix=isAlias?RANGE_PREFIX.exec(wantedVersion(consumer))?.[0]??"":"",target=isAlias?`${consumer.alias}@npm:${name}@${prefix}${version}`:`${name}@${version}`,exact=!isAlias||prefix==="";if(consumer.manager==="pnpm")return["pnpm","add",...PNPM_KIND_FLAGS[consumer.kind],...exact?["--save-exact"]:[],target];if(consumer.manager==="yarn")return["yarn","add",...YARN_KIND_FLAGS[consumer.kind],...exact?["--exact"]:[],target];if(consumer.manager==="npm")return["npm","install",...NPM_KIND_FLAGS[consumer.kind],...exact?["--save-exact"]:[],target];return["bun","add",...BUN_KIND_FLAGS[consumer.kind],...exact?["--exact"]:[],"--no-cache",target]}var REGISTRY_KINDS=KINDS.filter((kind)=>kind!=="peerDependencies");function registryDependencies(text){let manifest;try{manifest=JSON.parse(text)}catch{return fail("the package.json is not valid JSON")}return REGISTRY_KINDS.flatMap((kind)=>Object.entries(manifest?.[kind]??{}).flatMap(([name,spec])=>typeof spec==="string"&&!LOCAL_SPEC.test(spec)?[{name,kind,spec}]:[]))}
|
|
3
|
-
export{findConsumers,similarDependencies,isLocal,wantedVersion,RANGE_PREFIX,addCommand,registryDependencies};
|
package/dist/chunk-eqa72d87.js
DELETED
package/dist/chunk-fbz0xjzr.js
DELETED
|
@@ -1,2 +0,0 @@
|
|
|
1
|
-
// @bun
|
|
2
|
-
import{ROOT_OPTION2,bump2}from"./chunk-sx5zkre9.js";import"./chunk-6eg316z7.js";import"./chunk-p2jx0wx5.js";import"./chunk-apxff06c.js";import"./chunk-m8t5jkn0.js";import"./chunk-4pzedt0v.js";import"./chunk-0eb0ncqy.js";export{ROOT_OPTION2 as ROOT_OPTION,bump2 as bump};
|