@buddysh/buddy 0.11.0 → 0.11.1
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/CHANGELOG.md +15 -0
- package/dist/bin/cli.js +35 -35
- package/package.json +1 -1
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,20 @@
|
|
|
1
1
|
# Changelog
|
|
2
2
|
|
|
3
|
+
[Compare changes](https://github.com/stacksjs/buddy/compare/v0.11.0...v0.11.1)
|
|
4
|
+
|
|
5
|
+
## ✅ Tests
|
|
6
|
+
|
|
7
|
+
- stop the suite reaching the internet ([8032ff2](https://github.com/stacksjs/buddy/commit/8032ff2)) _(by Chris <chris@stacksjs.com>)_
|
|
8
|
+
|
|
9
|
+
## 🔧 Chores
|
|
10
|
+
|
|
11
|
+
- release v0.11.1 ([e78204a](https://github.com/stacksjs/buddy/commit/e78204a)) _(by Chris <chris@stacksjs.com>)_
|
|
12
|
+
- remove orphaned probe9.ts scratch file ([d15a19f](https://github.com/stacksjs/buddy/commit/d15a19f)) _(by Chris <chris@stacksjs.com>)_
|
|
13
|
+
|
|
14
|
+
## Contributors
|
|
15
|
+
|
|
16
|
+
- _Chris <chris@stacksjs.com>_
|
|
17
|
+
|
|
3
18
|
[Compare changes](https://github.com/stacksjs/buddy/compare/v0.10.5...v0.11.0)
|
|
4
19
|
|
|
5
20
|
## 💥 Breaking Changes
|
package/dist/bin/cli.js
CHANGED
|
@@ -1,46 +1,46 @@
|
|
|
1
1
|
#!/usr/bin/env bun
|
|
2
2
|
// @bun
|
|
3
|
-
import{Cc as
|
|
3
|
+
import{Cc as C1}from"../chunk-1stt2whn.js";import"../chunk-mcrfxphm.js";import{Wc as g}from"../chunk-djntbp7a.js";import"../chunk-1c1gznm9.js";import"../chunk-hw70wbzg.js";import"../chunk-3q6czqs4.js";import"../chunk-vyapg8ca.js";import"../chunk-vagxqhef.js";import"../chunk-xqx460y2.js";import{Od as o1,Pd as z1,Qd as r}from"../chunk-ts35hc5t.js";import{Rd as R1,Zd as e1}from"../chunk-fvpr07dn.js";import"../chunk-56q4pwb5.js";import"../chunk-tb5y0350.js";import"../chunk-16yqbccr.js";import"../chunk-8rc6042h.js";import"../chunk-4efbxdjr.js";import"../chunk-q9n79dd3.js";import"../chunk-6md7qf2g.js";import"../chunk-eagjp0dh.js";import"../chunk-6d9hmjt8.js";import"../chunk-978wtejw.js";import"../chunk-pkkwb0n0.js";import"../chunk-ph1b3vbp.js";import"../chunk-0j7z87kh.js";import"../chunk-naq32yx3.js";import"../chunk-bxfc4g2x.js";import"../chunk-g0w8n555.js";import"../chunk-tzs22es2.js";import"../chunk-9750tenz.js";import{Vi as s1,Zi as t1}from"../chunk-7mgec8kb.js";import{dj as NZ,ej as Z0,fj as $0,gj as J0,hj as Q0,ij as z0,jj as m,kj as f,mj as Y0,nj as X0,oj as j0,pj as q0,qj as G0,sj as K0,tj as H0,uj as U0,vj as V0,wj as W1,xj as W0,yj as F0}from"../chunk-zs3jaj0g.js";import"../chunk-tn8prpny.js";import"../chunk-5k40mwd4.js";import"../chunk-1h3ey7k5.js";import{Oj as t,Pj as M}from"../chunk-akffynkc.js";import"../chunk-x3kragh9.js";import"../chunk-wdwvt7gb.js";import"../chunk-8661pvb8.js";import"../chunk-ctsz0ynx.js";import"../chunk-vkctfqpm.js";import{Dk as PZ,Fk as D}from"../chunk-6g1y9yqh.js";import r1 from"fs";import V from"process";import{existsSync as D0}from"fs";import F1 from"fs/promises";import b1 from"os";import M1 from"path";import a from"process";import{EventEmitter as O0}from"events";import p from"process";import h1 from"process";import T1 from"process";import K1 from"process";import $1 from"process";import _1 from"tty";import YZ,{stdin as rZ,stdout as sZ}from"process";import m1,{stdin as qZ,stdout as GZ}from"process";import KZ from"readline";class u1{configPath;config=null;events=[];retryCount=0;maxRetries=3;retryDelayMs=1000;constructor(){let Z=b1.homedir(),$=M1.join(Z,".config","clapp");this.configPath=M1.join($,"telemetry.json")}async isEnabled(){if(a.env.DO_NOT_TRACK==="1"||a.env.DO_NOT_TRACK==="true")return!1;if(a.env.NO_TELEMETRY==="1"||a.env.NO_TELEMETRY==="true")return!1;return(await this.loadConfig()).enabled}async enable(){let Z=await this.loadConfig();if(Z.enabled=!0,!Z.userId)Z.userId=this.generateUserId();await this.saveConfig(Z)}async disable(){let Z=await this.loadConfig();Z.enabled=!1,await this.saveConfig(Z)}async track(Z,$){if(!await this.isEnabled())return;let Q={event:Z,...$,timestamp:Date.now(),platform:b1.platform(),nodeVersion:a.version};if(this.events.push(Q),this.events.length>=10)await this.send()}async trackCommand(Z,$){await this.track("command",{command:Z,duration:$})}async trackError(Z,$){await this.track("error",{error:Z,command:$})}async send(){if(!await this.isEnabled()||this.events.length===0)return!0;try{this.events=[],this.retryCount=0;let $=await this.loadConfig();return $.lastSent=Date.now(),await this.saveConfig($),!0}catch{if(this.retryCount<this.maxRetries){this.retryCount++;let $=this.retryDelayMs*2**(this.retryCount-1);return await this.sleep($),this.send()}return this.events=[],this.retryCount=0,!1}}async flush(){if(this.events.length===0)return!0;return this.send()}sleep(Z){return new Promise(($)=>setTimeout($,Z))}async status(){let Z=await this.loadConfig();return{enabled:Z.enabled,doNotTrack:a.env.DO_NOT_TRACK==="1"||a.env.DO_NOT_TRACK==="true",eventsQueued:this.events.length,lastSent:Z.lastSent}}async loadConfig(){if(this.config)return this.config;try{if(D0(this.configPath)){let Z=await F1.readFile(this.configPath,"utf-8");return this.config=JSON.parse(Z),this.config}}catch{}return this.config={enabled:!1},this.config}async saveConfig(Z){this.config=Z;try{let $=M1.dirname(this.configPath);await F1.mkdir($,{recursive:!0}),await F1.writeFile(this.configPath,JSON.stringify(Z,null,2),"utf-8")}catch{}}generateUserId(){let Z=Math.random().toString(36).substring(2,15),$=Date.now().toString(36);return`${Z}-${$}`}}var _Z=new u1;function L1(Z){return Z.replace(/[<[].+/,"").trim()}function L0(Z){let $=/<([^>]+)>/g,J=/\[([^\]]+)\]/g,Q=[],z=(j)=>{let q=!1,X=j[1];if(X.startsWith("..."))X=X.slice(3),q=!0;return{required:j[0].startsWith("<"),value:X,variadic:q}},Y;while(Y=$.exec(Z))Q.push(z(Y));let U;while(U=J.exec(Z))Q.push(z(U));return Q}function T0(Z){let $={alias:{},boolean:[]};for(let[J,Q]of Z.entries()){if(Q.names.length>1)$.alias[Q.names[0]]=Q.names.slice(1);if(Q.isBoolean)if(Q.negated){if(!Z.some((Y,U)=>{return U!==J&&Y.names.some((j)=>Q.names.includes(j))&&typeof Y.required==="boolean"}))$.boolean.push(Q.names[0])}else $.boolean.push(Q.names[0])}return $}function y1(Z){return Z.reduce(($,J)=>$.length>=J.length?$:J,"")}function D1(Z,$){return Z.length>=$?Z:`${Z}${" ".repeat($-Z.length)}`}function G1(Z){return Z.replace(/([a-z])-([a-z])/g,($,J,Q)=>{return J+Q.toUpperCase()})}function w0(Z,$,J){let Q=0,z=$.length,Y=Z,U;for(;Q<z;++Q)U=Y[$[Q]],Y=Y[$[Q]]=Q===z-1?J:U!=null?U:!!~$[Q+1].indexOf(".")||!(+$[Q+1]>-1)?{}:[]}function E0(Z,$){for(let J of Object.keys($)){let Q=$[J];if(Q.shouldTransform){if(Z[J]=Array.prototype.concat.call([],Z[J]),typeof Q.transformFunction==="function")Z[J]=Z[J].map(Q.transformFunction)}}}function B0(Z){let $=/([^\\/]+)$/.exec(Z);return $?$[1]:""}function J1(Z){return Z.split(".").map(($,J)=>{return J===0?G1($):$}).join(".")}class Q1 extends Error{exitCode=2;isUsageError=!0;usage;constructor(Z,$){super(Z);if(this.name=this.constructor.name,$!==void 0)this.usage=$;if(typeof Error.captureStackTrace==="function")Error.captureStackTrace(this,this.constructor);else this.stack=Error(Z).stack}format(Z=!1){if(Z&&this.stack)return`${this.message}
|
|
4
4
|
|
|
5
5
|
Stack trace:
|
|
6
|
-
${this.stack}`;return this.message}}function
|
|
6
|
+
${this.stack}`;return this.message}}function I0(Z){if(Z instanceof Q1)return!0;return!!Z&&typeof Z==="object"&&Z.name==="ClappError"&&typeof Z.message==="string"}function P0(){let{env:Z}=h1,{TERM:$,TERM_PROGRAM:J}=Z;if(h1.platform!=="win32")return $!=="linux";return Boolean(Z.WT_SESSION)||Boolean(Z.TERMINUS_SUBLIME)||Z.ConEmuTask==="{cmd::Cmder}"||J==="Terminus-Sublime"||J==="vscode"||$==="xterm-256color"||$==="alacritty"||$==="rxvt-unicode"||$==="rxvt-unicode-256color"||Z.TERMINAL_EMULATOR==="JetBrains-JediTerm"}var V1="\x1B",R=`${V1}[`;var l={to(Z,$){if(!$)return`${R}${Z+1}G`;return`${R}${$+1};${Z+1}H`},move(Z,$){let J="";if(Z<0)J+=`${R}${-Z}D`;else if(Z>0)J+=`${R}${Z}C`;if($<0)J+=`${R}${-$}A`;else if($>0)J+=`${R}${$}B`;return J},up:(Z=1)=>`${R}${Z}A`,down:(Z=1)=>`${R}${Z}B`,forward:(Z=1)=>`${R}${Z}C`,backward:(Z=1)=>`${R}${Z}D`,nextLine:(Z=1)=>`${R}E`.repeat(Z),prevLine:(Z=1)=>`${R}F`.repeat(Z),left:`${R}G`,hide:`${R}?25l`,show:`${R}?25h`,save:`${V1}7`,restore:`${V1}8`};var O1={screen:`${R}2J`,up:(Z=1)=>`${R}1J`.repeat(Z),down:(Z=1)=>`${R}J`.repeat(Z),line:`${R}2K`,lineEnd:`${R}K`,lineStart:`${R}1K`,lines(Z){let $="";for(let J=0;J<Z;J++)$+=this.line+(J<Z-1?l.up():"");if(Z)$+=l.left;return $}},uZ={screen:`${V1}c`};function N0(Z,$){let J=[];for(let Q=0;Q<=$.length;Q++)J[Q]=[Q];for(let Q=0;Q<=Z.length;Q++)J[0][Q]=Q;for(let Q=1;Q<=$.length;Q++)for(let z=1;z<=Z.length;z++)if($.charAt(Q-1)===Z.charAt(z-1))J[Q][z]=J[Q-1][z-1];else J[Q][z]=Math.min(J[Q-1][z-1]+1,J[Q][z-1]+1,J[Q-1][z]+1);return J[$.length][Z.length]}function g1(Z,$,J=2,Q=3){return $.map((z)=>({cmd:z,distance:N0(Z,z)})).filter(({distance:z})=>z<=J).sort((z,Y)=>z.distance-Y.distance).slice(0,Q).map(({cmd:z})=>z)}function A0(Z,$={}){let J={_:[]},Q=$.alias||{},z=new Set($.boolean||[]),Y={};for(let q of Object.keys(Q))for(let X of Q[q])Y[X]=q;for(let q of z)if(Q[q])for(let X of Q[q])z.add(X);function U(q,X){if(q===void 0)return X;if(typeof X==="boolean")return X;return Array.isArray(q)?[...q,X]:[q,X]}function j(q,X){let H=Y[q]||q,G=U(J[H],X);if(J[H]=G,Q[H])for(let K of Q[H])J[K]=G;if(Y[q]&&Q[Y[q]])for(let K of Q[Y[q]])J[K]=G;J[q]=G}for(let q=0;q<Z.length;q++){let X=Z[q];if(X==="--"){J._.push(...Z.slice(q+1));break}if(X.startsWith("--")){let H=X.indexOf("=");if(H!==-1){let G=G1(X.slice(2,H)),K=X.slice(H+1);j(G,K)}else{let G=X.slice(2);if(G.startsWith("no-")){let F=G1(G.slice(3));j(F,!1);continue}let K=G1(G),W=Y[K]||K;if(z.has(W)||z.has(K))j(K,!0);else{let F=Z[q+1];if(F!==void 0&&!F.startsWith("-"))j(K,F),q++;else j(K,!0)}}}else if(X.startsWith("-")&&X.length>1){let H=X.slice(1);for(let G=0;G<H.length;G++){let K=H[G],W=Y[K]||K;if(G===H.length-1&&!z.has(W)&&!z.has(K)){let F=Z[q+1];if(F!==void 0&&!F.startsWith("-"))j(K,F),q++;else j(K,!0)}else j(K,!0)}}else J._.push(X)}return J}class c1{rawName;description;name;names;isBoolean;required;config;negated;constructor(Z,$,J){if(this.rawName=Z,this.description=$,this.config=Object.assign({},J),Z=Z.replace(/\.\*/g,""),this.negated=!1,this.names=L1(Z).split(",").map((Q)=>{let z=Q.trim().replace(/^-{1,2}/,"");if(z.startsWith("no-"))this.negated=!0,z=z.replace(/^no-/,"");return J1(z)}).sort((Q,z)=>Q.length>z.length?1:-1),this.name=this.names[this.names.length-1],this.negated&&this.config.default==null)this.config.default=!0;if(Z.includes("<"))this.required=!0;else if(Z.includes("["))this.required=!1;else this.isBoolean=!0}}var cZ=T1.argv,x0=`${T1.platform}-${T1.arch} bun-v${typeof Bun<"u"?Bun.version:"unknown"}`,v1=K1.argv,R0=`${K1.platform}-${K1.arch} node-${K1.version}`;class w1{rawName;description;config;cli;options;aliasNames;name;namespace;args;commandAction;usageText;versionNumber;examples;helpCallback;globalCommand;beforeHooks;afterHooks;middleware;constructor(Z,$,J,Q){this.rawName=Z,this.description=$,this.config=J,this.cli=Q,this.options=[],this.aliasNames=[],this.name=L1(Z);let z=L1(Z),Y=z.indexOf(":");if(Y>0)this.namespace=z.substring(0,Y),this.name=z.substring(Y+1);if(this.args=L0(Z),this.examples=[],this.beforeHooks=[],this.afterHooks=[],this.middleware=[],!J)this.config={}}usage(Z){return this.usageText=Z,this}allowUnknownOptions(){return this.config.allowUnknownOptions=!0,this}ignoreOptionDefaultValue(){return this.config.ignoreOptionDefaultValue=!0,this}version(Z,$="-v, --version"){return this.versionNumber=Z,this.option($,"Display version number"),this}example(Z){return this.examples.push(Z),this}option(Z,$,J){let Q=new c1(Z,$,J);return this.options.push(Q),this}alias(Z){return this.aliasNames.push(Z),this}action(Z){return this.commandAction=Z,this}before(Z){return this.beforeHooks.push(Z),this}after(Z){return this.afterHooks.push(Z),this}use(Z){return this.middleware.push(Z),this}isMatched(Z){if(this.aliasNames.includes(Z))return!0;if(this.namespace)return`${this.namespace}:${this.name}`===Z;return this.name===Z}get isDefaultCommand(){return this.name===""||this.aliasNames.includes("!")}get isGlobalCommand(){return this instanceof E1}get displayName(){return this.namespace?`${this.namespace}:${this.name}`:this.name}hasOption(Z){let $=J1(Z.split(".")[0]);return!!this.options.find((J)=>{return J.names.some((Q)=>J1(Q)===$)})}outputHelp(){let{name:Z,commands:$}=this.cli,{versionNumber:J,options:Q,helpCallback:z}=this.cli.globalCommand,Y=[{body:`${Z}${J?`/${J}`:""}`}];if(Y.push({title:"Usage",body:` $ ${Z} ${this.usageText||this.rawName}`}),(this.isGlobalCommand||this.isDefaultCommand)&&$.length>0){let X=y1($.map((F)=>F.rawName)),H=new Map,G=[];for(let F of $)if(F.namespace){if(!H.has(F.namespace))H.set(F.namespace,[]);H.get(F.namespace).push(F)}else G.push(F);let K="";if(G.sort((F,L)=>F.rawName<L.rawName?-1:F.rawName>L.rawName?1:0),G.length>0)K+=G.map((F)=>{return` ${D1(F.rawName,X.length)} ${F.description}`}).join(`
|
|
7
7
|
`);let W=Array.from(H.keys()).sort();for(let F of W){let L=H.get(F);if(K.length>0)K+=`
|
|
8
8
|
|
|
9
9
|
`;K+=` ${F}:
|
|
10
|
-
`,K+=L.map((B)=>{return` ${
|
|
11
|
-
`)}Y.push({title:"Commands",body:K}),Y.push({body:`Run \`${Z} <command> --help\` for command details.`})}let j=new Set(this.options.flatMap((X)=>X.names)),q=this.isGlobalCommand?Q:[...this.options,...(Q||[]).filter((X)=>!X.names.some((H)=>j.has(H)))];if(!this.isGlobalCommand&&!this.isDefaultCommand)q=q.filter((X)=>X.name!=="version");if(q.length>0){let X=
|
|
10
|
+
`,K+=L.map((B)=>{return` ${D1(B.rawName,X.length-2)} ${B.description}`}).join(`
|
|
11
|
+
`)}Y.push({title:"Commands",body:K}),Y.push({body:`Run \`${Z} <command> --help\` for command details.`})}let j=new Set(this.options.flatMap((X)=>X.names)),q=this.isGlobalCommand?Q:[...this.options,...(Q||[]).filter((X)=>!X.names.some((H)=>j.has(H)))];if(!this.isGlobalCommand&&!this.isDefaultCommand)q=q.filter((X)=>X.name!=="version");if(q.length>0){let X=y1(q.map((H)=>H.rawName));Y.push({title:"Options",body:q.map((H)=>{return` ${D1(H.rawName,X.length)} ${H.description} ${H.config.default===void 0?"":`(default: ${H.config.default})`}`}).join(`
|
|
12
12
|
`)})}if(this.examples.length>0)Y.push({title:"Examples",body:this.examples.map((X)=>{if(typeof X==="function")return X(Z);return X}).join(`
|
|
13
13
|
`)});if(z)Y=z(Y)||Y;console.log(Y.map((X)=>{return X.title?`${X.title}:
|
|
14
14
|
${X.body}`:X.body}).join(`
|
|
15
15
|
|
|
16
|
-
`))}outputVersion(){let{name:Z}=this.cli,{versionNumber:$}=this.cli.globalCommand;if($)console.log(`${Z}/${$} ${typeof Bun<"u"?
|
|
16
|
+
`))}outputVersion(){let{name:Z}=this.cli,{versionNumber:$}=this.cli.globalCommand;if($)console.log(`${Z}/${$} ${typeof Bun<"u"?x0:R0}`)}get usageLine(){return`$ ${this.cli.name} ${this.usageText||this.rawName}`}checkRequiredArgs(){let Z=this.args.filter(($)=>$.required).length;if(this.cli.args.length<Z){let J=this.args.filter((z)=>z.required).slice(this.cli.args.length),Q=J.map((z)=>`<${z.value}>`).join(" ");throw new Q1(`Missing required argument${J.length>1?"s":""}: ${Q}
|
|
17
17
|
|
|
18
|
-
Run \`${this.cli.name} ${this.rawName} --help\` for usage information.`,this.usageLine)}}checkUnknownOptions(){let{options:Z,globalCommand:$}=this.cli;if(!this.config.allowUnknownOptions){for(let J of Object.keys(Z))if(J!=="--"&&!this.hasOption(J)&&!$.hasOption(J)){let z=[...$.options,...this.options].flatMap((X)=>X.names),Y=
|
|
18
|
+
Run \`${this.cli.name} ${this.rawName} --help\` for usage information.`,this.usageLine)}}checkUnknownOptions(){let{options:Z,globalCommand:$}=this.cli;if(!this.config.allowUnknownOptions){for(let J of Object.keys(Z))if(J!=="--"&&!this.hasOption(J)&&!$.hasOption(J)){let z=[...$.options,...this.options].flatMap((X)=>X.names),Y=J1(J.split(".")[0]),U=J.length>1?`--${J}`:`-${J}`,j=g1(Y,z),q=`Unknown option \`${U}\``;if(j.length>0)q+=`
|
|
19
19
|
|
|
20
20
|
Did you mean one of these?`,j.forEach((X)=>{let H=X.length>1?`--${X}`:`-${X}`;q+=`
|
|
21
21
|
\u2022 ${H}`});throw q+=`
|
|
22
22
|
|
|
23
|
-
Run \`${this.cli.name} ${this.rawName} --help\` to see available options.`,new
|
|
23
|
+
Run \`${this.cli.name} ${this.rawName} --help\` to see available options.`,new Q1(q,this.usageLine)}}}checkOptionValue(){let{options:Z,globalCommand:$}=this.cli,J=[...$.options,...this.options];for(let Q of J){let z=Z[Q.name.split(".")[0]];if(Q.required){let Y=J.some((U)=>U.negated&&U.names.includes(Q.name));if(z===!0||z===!1&&!Y)throw new Q1(`Option \`${Q.rawName}\` requires a value.
|
|
24
24
|
|
|
25
|
-
Example: ${this.cli.name} ${this.rawName} ${Q.rawName} <value>`,this.usageLine)}}}}class
|
|
25
|
+
Example: ${this.cli.name} ${this.rawName} ${Q.rawName} <value>`,this.usageLine)}}}}class E1 extends w1{constructor(Z){super("@@global@@","",{},Z)}}var C0=w1,i={red:["\x1B[31m","\x1B[39m"],green:["\x1B[32m","\x1B[39m"],blue:["\x1B[34m","\x1B[39m"],yellow:["\x1B[33m","\x1B[39m"],cyan:["\x1B[36m","\x1B[39m"],magenta:["\x1B[35m","\x1B[39m"],white:["\x1B[37m","\x1B[39m"],gray:["\x1B[90m","\x1B[39m"],bgRed:["\x1B[41m","\x1B[49m"],bgGreen:["\x1B[42m","\x1B[49m"],bgBlue:["\x1B[44m","\x1B[49m"],bgYellow:["\x1B[43m","\x1B[49m"],bgCyan:["\x1B[46m","\x1B[49m"],bgMagenta:["\x1B[45m","\x1B[49m"],bold:["\x1B[1m","\x1B[22m"],italic:["\x1B[3m","\x1B[23m"],underline:["\x1B[4m","\x1B[24m"],dim:["\x1B[2m","\x1B[22m"],inverse:["\x1B[7m","\x1B[27m"],hidden:["\x1B[8m","\x1B[28m"],strikethrough:["\x1B[9m","\x1B[29m"]};var e={primary:"blue",secondary:"cyan",success:"green",warning:"yellow",error:"red",info:"magenta",muted:"gray"};function S0(){return!0}function k0(){let Z={};Z.supportsColor=S0();function $(Q,z=[]){let Y=Q===""?[]:[...z,Q],U=function(q){if(!Z.supportsColor)return q;let X="",H="";for(let G of Y)if(G in e&&e[G]in i){let K=e[G];X+=i[K][0],H=i[K][1]+H}else if(G in i)X+=i[G][0],H=i[G][1]+H;return X+q+H},j=[...Object.keys(i),...Object.keys(e)];for(let q of j)if(!(q in U))Object.defineProperty(U,q,{get(){return $(q,Y)}});return U}let J=[...Object.keys(i),...Object.keys(e)];for(let Q of J)if(!(Q in Z))Object.defineProperty(Z,Q,{get(){return $(Q)}});return Z}var Z1=k0();class B1 extends O0{name;commands;globalCommand;matchedCommand;matchedCommandName;rawArgs;args;options;showHelpOnExit;showVersionOnExit;enableDidYouMean=!0;signalHandlersSet=!1;isVerbose=!1;isQuiet=!1;isDebug=!1;isNoInteraction=!1;environment;isDryRun=!1;isForce=!1;useEmoji=!0;theme;isNoCache=!1;constructor(Z=""){super();this.name=Z,this.commands=[],this.rawArgs=[],this.args=[],this.options={},this.globalCommand=new E1(this),this.globalCommand.usage("<command> [options]")}handleSignals(Z){if(this.signalHandlersSet)return this;let $=async(J)=>{if(console.log(`
|
|
26
26
|
|
|
27
|
-
Received ${J}, cleaning up...`),Z)try{await Z()}catch(Q){console.error("Error during cleanup:",Q)}p.exit(0)};return p.on("SIGINT",()=>$("SIGINT")),p.on("SIGTERM",()=>$("SIGTERM")),this.signalHandlersSet=!0,this}didYouMean(Z=!0){return this.enableDidYouMean=Z,this}verbose(){return this.globalCommand.option("-v, --verbose","Enable verbose output"),this}quiet(){return this.globalCommand.option("-q, --quiet","Suppress non-essential output"),this}debug(){return this.globalCommand.option("--debug","Enable debug mode with detailed error information"),this}noInteraction(){return this.globalCommand.option("-n, --no-interaction","Do not ask any interactive questions (for CI/CD)"),this}env(){return this.globalCommand.option("--env <environment>","Target environment (e.g., production, staging, local)"),this}dryRun(){return this.globalCommand.option("--dry-run","Preview actions without executing them"),this}force(){return this.globalCommand.option("-f, --force","Skip confirmation prompts"),this}emoji(){return this.globalCommand.option("--no-emoji","Disable emoji in output"),this}themes(){return this.globalCommand.option("--theme <theme>","Color theme (default, dracula, nord, solarized, monokai)"),this}cache(){return this.globalCommand.option("--no-cache","Disable caching"),this}usage(Z){return this.globalCommand.usage(Z),this}command(Z,$,J){if(!J)J={};let Q=new
|
|
27
|
+
Received ${J}, cleaning up...`),Z)try{await Z()}catch(Q){console.error("Error during cleanup:",Q)}p.exit(0)};return p.on("SIGINT",()=>$("SIGINT")),p.on("SIGTERM",()=>$("SIGTERM")),this.signalHandlersSet=!0,this}didYouMean(Z=!0){return this.enableDidYouMean=Z,this}verbose(){return this.globalCommand.option("-v, --verbose","Enable verbose output"),this}quiet(){return this.globalCommand.option("-q, --quiet","Suppress non-essential output"),this}debug(){return this.globalCommand.option("--debug","Enable debug mode with detailed error information"),this}noInteraction(){return this.globalCommand.option("-n, --no-interaction","Do not ask any interactive questions (for CI/CD)"),this}env(){return this.globalCommand.option("--env <environment>","Target environment (e.g., production, staging, local)"),this}dryRun(){return this.globalCommand.option("--dry-run","Preview actions without executing them"),this}force(){return this.globalCommand.option("-f, --force","Skip confirmation prompts"),this}emoji(){return this.globalCommand.option("--no-emoji","Disable emoji in output"),this}themes(){return this.globalCommand.option("--theme <theme>","Color theme (default, dracula, nord, solarized, monokai)"),this}cache(){return this.globalCommand.option("--no-cache","Disable caching"),this}usage(Z){return this.globalCommand.usage(Z),this}command(Z,$,J){if(!J)J={};let Q=new C0(Z,$||"",J,this);return Q.globalCommand=this.globalCommand,this.commands.push(Q),Q}option(Z,$,J){return this.globalCommand.option(Z,$,J),this}help(Z){return this.globalCommand.option("-h, --help","Display this message"),this.globalCommand.helpCallback=Z,this.showHelpOnExit=!0,this}version(Z,$="-v, --version"){return this.globalCommand.version(Z,$),this.showVersionOnExit=!0,this}example(Z){return this.globalCommand.example(Z),this}outputHelp(){if(this.matchedCommand)this.matchedCommand.outputHelp();else this.globalCommand.outputHelp()}outputVersion(){this.globalCommand.outputVersion()}setParsedInfo({args:Z,options:$},J,Q){if(this.args=Z,this.options=$,J)this.matchedCommand=J;if(Q)this.matchedCommandName=Q;return this}unsetMatchedCommand(){this.matchedCommand=void 0,this.matchedCommandName=void 0}showCommandNotFound(Z){if(console.log(Z1.red(`
|
|
28
28
|
\u2717 Command "${Z}" not found.
|
|
29
|
-
`)),this.enableDidYouMean){let $=[];for(let Q of this.commands){if(Q.displayName)$.push(Q.displayName);if(Q.aliasNames)$.push(...Q.aliasNames)}let J=
|
|
29
|
+
`)),this.enableDidYouMean){let $=[];for(let Q of this.commands){if(Q.displayName)$.push(Q.displayName);if(Q.aliasNames)$.push(...Q.aliasNames)}let J=g1(Z,$);if(J.length>0)console.log(Z1.yellow("Did you mean one of these?")),J.forEach((Q)=>console.log(` ${Z1.dim("\u2022")} ${this.name} ${Q}`)),console.log("")}console.log(Z1.dim("Run"),`${this.name} --help`,Z1.dim("to see all available commands")),p.exit(1)}async parse(Z=v1,$={}){let{run:J=!0,exitOnError:Q=!1}=$;if(Q)try{return await this.parse(Z,{run:J})}catch(q){throw this.handleUsageError(q),q}if(this.rawArgs=Z,!this.name)this.name=Z[1]?B0(Z[1]):"cli";let z=!0,Y=Z.slice(2),U=Y[0];if(U&&!U.startsWith("-")){for(let q of this.commands)if(q.isMatched(U)){let X=this.mri(Y,q);z=!1;let H={...X,args:X.args.slice(1)};this.setParsedInfo(H,q,U),this.emit(`command:${U}`,q);break}if(z){let q=Y[1];if(q&&!q.startsWith("-")){let X=`${U}:${q}`;for(let H of this.commands)if(H.isMatched(X)){let G=this.mri(Y,H);z=!1;let K={...G,args:G.args.slice(2)};this.setParsedInfo(K,H,X),this.emit(`command:${X}`,H);break}}}}if(z){for(let q of this.commands)if(q.name===""){z=!1;let X=this.mri(Y,q);this.setParsedInfo(X,q),this.emit("command:!",q);break}}if(z){let q=this.mri(Z.slice(2));this.setParsedInfo(q)}if(this.options.verbose)this.isVerbose=!0;if(this.options.quiet)this.isQuiet=!0;if(this.options.debug)this.isDebug=!0;if(this.options.noInteraction||this.options.interaction===!1)this.isNoInteraction=!0;if(this.options.env)this.environment=String(this.options.env);if(this.options.dryRun)this.isDryRun=!0;if(this.options.force)this.isForce=!0;if(this.options.noEmoji||this.options.emoji===!1)this.useEmoji=!1;if(this.options.theme)this.theme=String(this.options.theme);if(this.options.noCache||this.options.cache===!1)this.isNoCache=!0;if(this.options.help&&this.showHelpOnExit)this.outputHelp(),J=!1,this.unsetMatchedCommand();if(this.options.version&&this.showVersionOnExit&&this.matchedCommandName==null)this.outputVersion(),J=!1,this.unsetMatchedCommand();let j={args:this.args,options:this.options};if(J)await this.runMatchedCommand();if(!this.matchedCommand&&this.args[0]){if(this.emit("command:*"),!(this.listenerCount("command:*")>0))this.showCommandNotFound(this.args[0])}return j}mri(Z,$){let J=[...this.globalCommand.options,...$?$.options:[]],Q=T0(J),z=[],Y=Z.indexOf("--");if(Y>-1)z=Z.slice(Y+1),Z=Z.slice(0,Y);let U=A0(Z,Q),j={_:U._};for(let K of Object.keys(U))if(K!=="_")j[J1(K)]=U[K];let q=j._,X={"--":z},H=$&&$.config.ignoreOptionDefaultValue?$.config.ignoreOptionDefaultValue:this.globalCommand.config.ignoreOptionDefaultValue,G=Object.create(null);for(let K of J){if(!H&&K.config.default!==void 0)for(let W of K.names)X[W]=K.config.default;if(Array.isArray(K.config.type)){if(G[K.name]===void 0)G[K.name]={shouldTransform:!0,transformFunction:K.config.type[0]}}}for(let K of Object.keys(j))if(K!=="_"){let W=K.split(".");w0(X,W,j[K]),E0(X,G)}return{args:q,options:X}}async run(Z=v1){return this.parse(Z,{run:!0,exitOnError:!0})}handleUsageError(Z){if(!I0(Z)||Z.isUsageError===!1)return;let $=Z.message||"command-line error",J=this.name?`${this.name}: `:"",Q=/--help/.test($)?"":Z.usage?`
|
|
30
30
|
Usage: ${Z.usage}`:`
|
|
31
31
|
Run \`${this.name??"cli"} --help\` for usage.`;p.stderr.write(`${J}${$}${Q}
|
|
32
|
-
`),p.exit(Z.exitCode??2)}async runMatchedCommand(){let{args:Z,options:$,matchedCommand:J}=this;if(!J||!J.commandAction)return;J.checkUnknownOptions(),J.checkOptionValue(),J.checkRequiredArgs();let Q=[];J.args.forEach((j,q)=>{if(j.variadic)Q.push(Z.slice(q));else Q.push(Z[q])}),Q.push($);let z={command:J,args:Q,options:$};for(let j of J.beforeHooks)await j(z);let Y,U=async()=>{let j=J.commandAction.apply(this,Q);if(j instanceof Promise)Y=await j;else Y=j;return Y};if(J.middleware.length>0){let j=0,q=async()=>{if(j<J.middleware.length){let X=J.middleware[j++];await X({...z,next:q})}else await U()};await q()}else await U();for(let j of J.afterHooks)await j(z);return Y}removeSignalHandlers(){if(!this.signalHandlersSet)return this;return p.removeAllListeners("SIGINT"),p.removeAllListeners("SIGTERM"),this.signalHandlersSet=!1,this}destroy(){this.removeSignalHandlers(),this.commands=[],this.rawArgs=[],this.args=[],this.options={},this.matchedCommand=void 0,this.matchedCommandName=void 0,this.removeAllListeners()}}class
|
|
32
|
+
`),p.exit(Z.exitCode??2)}async runMatchedCommand(){let{args:Z,options:$,matchedCommand:J}=this;if(!J||!J.commandAction)return;J.checkUnknownOptions(),J.checkOptionValue(),J.checkRequiredArgs();let Q=[];J.args.forEach((j,q)=>{if(j.variadic)Q.push(Z.slice(q));else Q.push(Z[q])}),Q.push($);let z={command:J,args:Q,options:$};for(let j of J.beforeHooks)await j(z);let Y,U=async()=>{let j=J.commandAction.apply(this,Q);if(j instanceof Promise)Y=await j;else Y=j;return Y};if(J.middleware.length>0){let j=0,q=async()=>{if(j<J.middleware.length){let X=J.middleware[j++];await X({...z,next:q})}else await U()};await q()}else await U();for(let j of J.afterHooks)await j(z);return Y}removeSignalHandlers(){if(!this.signalHandlersSet)return this;return p.removeAllListeners("SIGINT"),p.removeAllListeners("SIGTERM"),this.signalHandlersSet=!1,this}destroy(){this.removeSignalHandlers(),this.commands=[],this.rawArgs=[],this.args=[],this.options={},this.matchedCommand=void 0,this.matchedCommandName=void 0,this.removeAllListeners()}}class l1{cache;enabled;cleanupInterval=null;hits=0;misses=0;constructor(){this.cache=new Map,this.enabled=!0,this.startCleanupInterval()}startCleanupInterval(){if(this.cleanupInterval)return;this.cleanupInterval=setInterval(()=>{this.cleanup()},30000),this.cleanupInterval.unref()}stopCleanup(){if(this.cleanupInterval)clearInterval(this.cleanupInterval),this.cleanupInterval=null}isEnabled(){return this.enabled}get(Z){if(!this.enabled){this.misses++;return}let $=this.cache.get(Z);if(!$){this.misses++;return}if(Date.now()-$.timestamp>$.ttl){this.cache.delete(Z),this.misses++;return}return this.hits++,$.value}set(Z,$,J=5000){if(!this.enabled)return;this.cache.set(Z,{value:$,timestamp:Date.now(),ttl:J})}has(Z){if(!this.enabled)return!1;let $=this.cache.get(Z);if(!$)return!1;if(Date.now()-$.timestamp>$.ttl)return this.cache.delete(Z),!1;return!0}delete(Z){this.cache.delete(Z)}clear(){this.cache.clear()}disable(){this.enabled=!1,this.clear()}enable(){this.enabled=!0}stats(){return{size:this.cache.size,enabled:this.enabled,hits:this.hits,misses:this.misses}}resetStats(){this.hits=0,this.misses=0}keys(){return Array.from(this.cache.keys())}cleanup(){let Z=Date.now();for(let[$,J]of this.cache.entries())if(Z-J.timestamp>J.ttl)this.cache.delete($)}destroy(){this.stopCleanup(),this.clear(),this.resetStats()}}var pZ=new l1;function b0(){if("FORCE_COLOR"in $1.env)return $1.env.FORCE_COLOR!=="0";if("NO_COLOR"in $1.env||$1.env.TERM==="dumb")return!1;if($1.platform==="win32")return!0;return _1.isatty(1)&&_1.isatty(2)}var p1=b0();function x(Z,$){if(!p1)return(J)=>J;return(J)=>Z+J+$}var h0=x("\x1B[0m","\x1B[0m"),y0=x("\x1B[31m","\x1B[39m"),v0=x("\x1B[32m","\x1B[39m"),_0=x("\x1B[33m","\x1B[39m"),f0=x("\x1B[34m","\x1B[39m"),m0=x("\x1B[35m","\x1B[39m"),d0=x("\x1B[36m","\x1B[39m"),u0=x("\x1B[37m","\x1B[39m"),g0=x("\x1B[90m","\x1B[39m"),c0=x("\x1B[1m","\x1B[22m"),l0=x("\x1B[3m","\x1B[23m"),p0=x("\x1B[4m","\x1B[24m"),i0=x("\x1B[2m","\x1B[22m"),n0=x("\x1B[7m","\x1B[27m"),a0=x("\x1B[8m","\x1B[28m"),r0=x("\x1B[9m","\x1B[29m"),s0=x("\x1B[41m","\x1B[49m"),t0=x("\x1B[42m","\x1B[49m"),o0=x("\x1B[43m","\x1B[49m"),e0=x("\x1B[44m","\x1B[49m"),ZZ=x("\x1B[45m","\x1B[49m"),$Z=x("\x1B[46m","\x1B[49m"),JZ=x("\x1B[47m","\x1B[49m"),QZ=p1,zZ={reset:h0,red:y0,green:v0,yellow:_0,blue:f0,magenta:m0,cyan:d0,white:u0,gray:g0,bold:c0,italic:l0,underline:p0,dim:i0,inverse:n0,hidden:a0,strikethrough:r0,bgRed:s0,bgGreen:t0,bgYellow:o0,bgBlue:e0,bgMagenta:ZZ,bgCyan:$Z,bgWhite:JZ,isColorSupported:QZ},H1=zZ,XZ=["up","down","left","right","space","enter","cancel"],U1={actions:new Set(XZ),aliases:new Map([["k","up"],["j","down"],["h","left"],["l","right"],["\x03","cancel"],["escape","cancel"]]),messages:{cancel:"Canceled",error:"Something went wrong"}};function i1(Z,$){if(typeof Z==="string")return U1.aliases.get(Z)===$;for(let J of Z){if(J===void 0)continue;if(i1(J,$))return!0}return!1}function jZ(Z,$){if(Z===$)return[];let J=Z.split(`
|
|
33
33
|
`),Q=$.split(`
|
|
34
|
-
`),z=[];for(let Y=0;Y<Math.max(J.length,Q.length);Y++)if(J[Y]!==Q[Y])z.push(Y);return z}var tZ=YZ.platform.startsWith("win"),
|
|
34
|
+
`),z=[];for(let Y=0;Y<Math.max(J.length,Q.length);Y++)if(J[Y]!==Q[Y])z.push(Y);return z}var tZ=YZ.platform.startsWith("win"),f1=Symbol("clapp:cancel");function q1(Z,$){let J=Z;if(J.isTTY)J.setRawMode($)}function HZ(Z){return Z.replace(/\x1b\[[0-9;]*m/g,"")}function UZ(Z){return HZ(Z).length}function d1(Z,$,J){if(!$||$<1)return Z;let Q=J?.hard??!1,z=J?.trim??!0,Y=Z.split(`
|
|
35
35
|
`),U=[];for(let j of Y){if(UZ(j)<=$){U.push(z?j.trimEnd():j);continue}if(Q){let q="",X=0,H=0;while(H<j.length){let G=j.slice(H).match(/^\x1b\[[0-9;]*m/);if(G){q+=G[0],H+=G[0].length;continue}if(X>=$)U.push(z?q.trimEnd():q),q="",X=0;q+=j[H],X++,H++}if(q)U.push(z?q.trimEnd():q)}else U.push(z?j.trimEnd():j)}return U.join(`
|
|
36
|
-
`)}class
|
|
37
|
-
`),
|
|
38
|
-
`).length-1;this.output.write(l.move(-999,Z*-1))}render(){let Z=
|
|
39
|
-
`);this.output.write(Q[J]),this._prevFrame=Z,this.output.write(l.move(0,Q.length-J-1));return}if($&&$?.length>1){let J=$[0];this.output.write(l.move(0,J)),this.output.write(
|
|
36
|
+
`)}class I1{input;output;_abortSignal;rl;opts;_render;_track=!1;_prevFrame="";_subscribers=new Map;_cursor=0;_manualLine="";state="initial";error="";value;userInput="";constructor(Z,$=!0){let{input:J=qZ,output:Q=GZ,render:z,signal:Y,...U}=Z;this.opts=U,this.onKeypress=this.onKeypress.bind(this),this.close=this.close.bind(this),this.render=this.render.bind(this),this._render=z.bind(this),this._track=$,this._abortSignal=Y,this.input=J,this.output=Q}unsubscribe(){this._subscribers.clear()}setSubscriber(Z,$){let J=this._subscribers.get(Z)??[];J.push($),this._subscribers.set(Z,J)}on(Z,$){return this.setSubscriber(Z,{cb:$}),this}once(Z,$){return this.setSubscriber(Z,{cb:$,once:!0}),this}emit(Z,...$){let J=this._subscribers.get(Z)??[],Q=[];for(let z of J)if(z.cb(...$),z.once)Q.push(()=>J.splice(J.indexOf(z),1));for(let z of Q)z();return this}prompt(){return new Promise((Z)=>{if(this._abortSignal){if(this._abortSignal.aborted)return this.state="cancel",this.close(),Z(f1);this._abortSignal.addEventListener("abort",()=>{this.state="cancel",this.close()},{once:!0})}if(this.rl=KZ.createInterface({input:this.input,tabSize:2,prompt:"",escapeCodeTimeout:50,terminal:!0}),this.rl.prompt(),this.opts.initialUserInput!==void 0)this._setUserInput(this.opts.initialUserInput,!0);this.input.on("keypress",this.onKeypress),q1(this.input,!0),this.output.on("resize",this.render),this.render(),this.once("submit",()=>{this.output.write(l.show),this.output.off("resize",this.render),q1(this.input,!1),Z(this.value)}),this.once("cancel",()=>{this.output.write(l.show),this.output.off("resize",this.render),q1(this.input,!1),Z(f1)})})}_isActionKey(Z,$){return Z==="\t"}_setValue(Z){this.value=Z,this.emit("value",this.value)}_setUserInput(Z,$){if(this.userInput=Z??"",this.emit("userInput",this.userInput),$&&this._track&&this.rl)this.rl.write(this.userInput),this._cursor=this.rl.cursor}onKeypress(Z,$){if(this._track&&$.name!=="return"){if($.name&&this._isActionKey(Z,$))this.rl?.write(null,{ctrl:!0,name:"h"});this._cursor=this.rl?.cursor??0;let J=$.name==="tab"||$.name==="escape"||$.name==="backspace"||$.name==="delete"||$.name==="enter"||$.name==="return"||$.name&&["up","down","left","right"].includes($.name);if(Z&&!J&&Z.length===1&&Z>=" ")this._manualLine+=Z;else if($.name==="backspace"&&this._manualLine.length>0)this._manualLine=this._manualLine.slice(0,-1);let Q=this._manualLine.length>=(this.rl?.line?.length||0)?this._manualLine:this.rl?.line;this._setUserInput(Q)}if(this.state==="error")this.state="active",this.error="";if($?.name){if(!this._track&&U1.aliases.has($.name))this.emit("cursor",U1.aliases.get($.name));if(U1.actions.has($.name))this.emit("cursor",$.name)}if(Z&&(Z.toLowerCase()==="y"||Z.toLowerCase()==="n"))this.emit("confirm",Z.toLowerCase()==="y");if(this.emit("key",Z?.toLowerCase(),$),$?.name==="return"){if(this.opts.validate){let J=this.opts.validate(this.value);if(J)this.error=J instanceof Error?J.message:J,this.state="error"}if(this.state!=="error")this.state="submit"}if(i1([Z,$?.name,$?.sequence],"cancel"))this.state="cancel";if(this.state==="submit"||this.state==="cancel")this.emit("finalize");if(this.render(),this.state==="submit"||this.state==="cancel")this.close()}close(){if(this.input.unpipe(),this.input.removeListener("keypress",this.onKeypress),this.output.write(`
|
|
37
|
+
`),q1(this.input,!1),this.rl?.close(),this.rl=void 0,this.emit(`${this.state}`,this.value),this.state==="cancel")setTimeout(()=>{this.unsubscribe()},10);else this.unsubscribe()}restoreCursor(){let Z=d1(this._prevFrame,m1.stdout.columns,{hard:!0,trim:!1}).split(`
|
|
38
|
+
`).length-1;this.output.write(l.move(-999,Z*-1))}render(){let Z=d1(this._render(this)??"",m1.stdout.columns,{hard:!0,trim:!1});if(Z===this._prevFrame)return;if(this.state==="initial")this.output.write(l.hide);else{let $=jZ(this._prevFrame,Z);if(this.restoreCursor(),$&&$?.length===1){let J=$[0];this.output.write(l.move(0,J)),this.output.write(O1.lines(1));let Q=Z.split(`
|
|
39
|
+
`);this.output.write(Q[J]),this._prevFrame=Z,this.output.write(l.move(0,Q.length-J-1));return}if($&&$?.length>1){let J=$[0];this.output.write(l.move(0,J)),this.output.write(O1.down());let z=Z.split(`
|
|
40
40
|
`).slice(J);this.output.write(z.join(`
|
|
41
|
-
`)),this._prevFrame=Z;return}this.output.write(
|
|
41
|
+
`)),this._prevFrame=Z;return}this.output.write(O1.down())}if(this.output.write(Z),this.state==="initial")this.state="active";this._prevFrame=Z}}function VZ(Z,$){if(Z===void 0)return 0;if($.length===0)return 0;let Q=$.findIndex((z)=>z.value===Z);return Q!==-1?Q:0}function WZ(Z,$){return($.label??String($.value)).toLowerCase().includes(Z.toLowerCase())}function FZ(Z,$){if(!$)return;if(Z)return $;return $[0]}class MZ extends I1{filteredOptions;multiple;isNavigating=!1;selectedValues=[];focusedValue;#Z=0;#J="";#Q;#$;get cursor(){return this.#Z}get userInputWithCursor(){if(!this.userInput)return H1.inverse(H1.hidden("_"));if(this._cursor>=this.userInput.length)return`${this.userInput}\u2588`;let Z=this.userInput.slice(0,this._cursor),[$,...J]=this.userInput.slice(this._cursor);return`${Z}${H1.inverse($)}${J.join("")}`}get options(){if(typeof this.#$==="function")return this.#$();return this.#$}constructor(Z){super(Z);this.#$=Z.options;let $=this.options;this.filteredOptions=[...$],this.multiple=Z.multiple===!0,this.#Q=Z.filter??WZ;let J;if(Z.initialValue&&Array.isArray(Z.initialValue))if(this.multiple)J=Z.initialValue;else J=Z.initialValue.slice(0,1);else if(!this.multiple&&this.options.length>0)J=[this.options[0].value];if(J)for(let Q of J){let z=$.findIndex((Y)=>Y.value===Q);if(z!==-1)this.toggleSelected(Q),this.#Z=z}this.focusedValue=this.options[this.#Z]?.value,this.on("key",(Q,z)=>this.#z(Q,z)),this.on("userInput",(Q)=>this.#Y(Q))}_isActionKey(Z,$){return Z==="\t"||this.multiple&&this.isNavigating&&$.name==="space"&&Z!==void 0&&Z!==""}#z(Z,$){let J=$.name==="up",Q=$.name==="down",z=$.name==="return";if(J||Q){if(this.#Z=Math.max(0,Math.min(this.#Z+(J?-1:1),this.filteredOptions.length-1)),this.focusedValue=this.filteredOptions[this.#Z]?.value,!this.multiple)this.selectedValues=[this.focusedValue];this.isNavigating=!0}else if(z)this.value=FZ(this.multiple,this.selectedValues);else if(this.multiple)if(this.focusedValue!==void 0&&($.name==="tab"||this.isNavigating&&$.name==="space"))this.toggleSelected(this.focusedValue);else this.isNavigating=!1;else{if(this.focusedValue)this.selectedValues=[this.focusedValue];this.isNavigating=!1}}deselectAll(){this.selectedValues=[]}toggleSelected(Z){if(this.filteredOptions.length===0)return;if(this.multiple)if(this.selectedValues.includes(Z))this.selectedValues=this.selectedValues.filter(($)=>$!==Z);else this.selectedValues=[...this.selectedValues,Z];else this.selectedValues=[Z]}#Y(Z){if(Z!==this.#J){this.#J=Z;let $=this.options;if(Z)this.filteredOptions=$.filter((J)=>this.#Q(Z,J));else this.filteredOptions=[...$];if(this.#Z=VZ(this.focusedValue,this.filteredOptions),this.focusedValue=this.filteredOptions[this.#Z]?.value,!this.multiple)if(this.focusedValue!==void 0)this.toggleSelected(this.focusedValue);else this.deselectAll()}}}class DZ extends I1{options;cursor=0;#Z;getGroupItems(Z){return this.options.filter(($)=>$.group===Z)}isGroupSelected(Z){let $=this.getGroupItems(Z),J=this.value;if(J===void 0)return!1;return $.every((Q)=>J.includes(Q.value))}toggleValue(){let Z=this.options[this.cursor];if(this.value===void 0)this.value=[];if(Z.group===!0){let $=String(Z.value),J=this.getGroupItems($);if(this.isGroupSelected($))this.value=this.value.filter((Q)=>J.findIndex((z)=>z.value===Q)===-1);else this.value=[...this.value,...J.map((Q)=>Q.value)];this.value=Array.from(new Set(this.value))}else{let $=this.value.includes(Z.value);this.value=$?this.value.filter((J)=>J!==Z.value):[...this.value,Z.value]}}constructor(Z){super(Z,!1);let{options:$}=Z;this.#Z=Z.selectableGroups!==!1,this.options=Object.entries($).flatMap(([J,Q])=>[{value:J,group:!0,label:J},...Q.map((z)=>({...z,group:J}))]),this.value=[...Z.initialValues??[]],this.cursor=Math.max(this.options.findIndex(({value:J})=>J===Z.cursorAt),this.#Z?0:1),this.on("cursor",(J)=>{switch(J){case"left":case"up":{this.cursor=this.cursor===0?this.options.length-1:this.cursor-1;let Q=this.options[this.cursor]?.group===!0;if(!this.#Z&&Q)this.cursor=this.cursor===0?this.options.length-1:this.cursor-1;break}case"down":case"right":{this.cursor=this.cursor===this.options.length-1?0:this.cursor+1;let Q=this.options[this.cursor]?.group===!0;if(!this.#Z&&Q)this.cursor=this.cursor===this.options.length-1?0:this.cursor+1;break}case"space":this.toggleValue();break}})}}var OZ=P0();var A=(Z,$)=>OZ?Z:$,Z$=A("\u25C6","*"),$$=A("\u25A0","x"),J$=A("\u25B2","x"),Q$=A("\u25C7","o"),z$=A("\u250C","T"),LZ=A("\u2502","|"),Y$=A("\u2514","\u2014"),X$=A("\u25CF",">"),j$=A("\u25CB"," "),q$=A("\u25FB","[\u2022]"),G$=A("\u25FC","[+]"),K$=A("\u25FB","[ ]"),H$=A("\u25AA","\u2022"),U$=A("\u2500","-"),V$=A("\u256E","+"),W$=A("\u251C","+"),F$=A("\u256F","+"),M$=A("\u25CF","\u2022"),D$=A("\u25C6","*"),O$=A("\u25B2","!"),L$=A("\u25A0","x");var T$={light:A("\u2500","-"),heavy:A("\u2501","="),block:A("\u2588","#")};function TZ(){return`${H1.gray(LZ)} `}var w$=TZ();var s=PZ(NZ(),1);var P1="0.11.1";var N1=String.raw`^\s*-\s*\[[xX]\]\s*`,EZ=new RegExp(`${N1}<!--\\s*rebase-branch=([^>]*?)\\s*-->`,"gm"),BZ=new RegExp(`${N1}<!--\\s*rebase-all-open-prs\\s*-->`,"m"),IZ=new RegExp(`${N1}<!--\\s*manual job\\s*-->`,"m");function n1(Z){if(!Z)return{rebaseBranches:[],rebaseAll:!1,manualRun:!1};let $=[];for(let J of Z.matchAll(EZ)){let Q=J[1].trim();if(Q&&!$.includes(Q))$.push(Q)}return{rebaseBranches:$,rebaseAll:BZ.test(Z),manualRun:IZ.test(Z)}}function A1(Z){return Z.rebaseBranches.length>0||Z.rebaseAll||Z.manualRun}function a1(Z){return Z.replace(/^(\s*-\s*)\[[xX]\](\s*<!--\s*(?:rebase-branch=[^>]*?|rebase-all-open-prs|manual job)\s*-->)/gm,"$1[ ]$2")}var x1=null;async function C(Z){if(Z)return await C1(Z);if(!x1)x1=await C1();return x1}async function d(Z,$,J){if(!Z.repository?.owner||!Z.repository.name)J.error(`\u274C Repository owner and name are required for ${$}`),J.info("Configure repository.owner and repository.name in buddy.config.ts"),V.exit(1);try{return await o1({provider:Z.repository.provider,owner:Z.repository.owner,name:Z.repository.name,...Z.repository.token?{token:Z.repository.token}:{},...Z.repository.apiUrl?{apiUrl:Z.repository.apiUrl}:{}},{logger:J})}catch(Q){J.error(`\u274C ${t(Q)}`),V.exit(1)}}async function AZ(Z,$,J){let Q=Z.filter((U)=>U.suggestion);if(Q.length===0)return J.info("No committable suggestions in this review"),0;let z=new Map;for(let U of Q){let j=z.get(U.path);if(j)j.push(U);else z.set(U.path,[U])}let Y=0;for(let[U,j]of z){let q=Bun.file(U);if(!await q.exists()){J.warn(`\u26A0\uFE0F Skipping ${U}: not in the working tree`);continue}let X=await q.text();for(let H of[...j].sort((G,K)=>K.line-G.line)){if(!$){if(!(await s.default({type:"confirm",name:"apply",message:`${U}:${H.line} \u2014 ${H.message}
|
|
42
42
|
${H.suggestion}
|
|
43
|
-
Apply?`,initial:!1})).apply)continue}let G=
|
|
43
|
+
Apply?`,initial:!1})).apply)continue}let G=e1(X,H.line,H.suggestion);if(G===null){J.warn(`\u26A0\uFE0F Skipping ${U}:${H.line}: the file changed since the review`);continue}X=G,Y++}await Bun.write(U,X)}return Y}async function xZ(Z,$){try{let{PackageScanner:J}=await import("../chunk-f4nv5x3z.js"),Q=await new J(V.cwd(),$,Z.packages?.ignorePaths).scanProject(),z=new Map;for(let Y of Q)for(let U of Y.dependencies)if(!z.has(U.name))z.set(U.name,U.currentVersion);return[...z].map(([Y,U])=>({name:Y,declaredVersion:U}))}catch(J){return $.debug(`Could not collect dependency context: ${t(J)}`),[]}}var T=new B1("buddy");T.usage(`[command] [options]
|
|
44
44
|
|
|
45
45
|
\uD83D\uDC36 Buddy - AI code review and dependency updates, in one teammate
|
|
46
46
|
|
|
@@ -113,40 +113,40 @@ Migration:
|
|
|
113
113
|
- Converts settings to Buddy format with compatibility report
|
|
114
114
|
- Generates optimized GitHub Actions workflows
|
|
115
115
|
- Provides migration guidance and best practices`);T.command("setup","\uD83D\uDE80 Interactive setup for automated dependency updates (recommended)").option("--verbose, -v","Enable verbose logging").option("--non-interactive","Run setup without prompts (use defaults)").option("--preset <type>","Workflow preset: standard|high-frequency|security|minimal|testing",{default:"standard"}).option("--token-setup <type>","Token setup: existing-secret|new-pat|default-token",{default:"default-token"}).example("buddy setup").example("buddy setup --verbose").example("buddy setup --non-interactive").example("buddy setup --non-interactive --preset testing --verbose").action(async(Z)=>{let $=Z.verbose?M.verbose():M.quiet();try{console.log("\uD83E\uDD16 Welcome to Buddy Setup!"),console.log(`Let's configure automated dependency updates for your project.
|
|
116
|
-
`);let J=
|
|
116
|
+
`);let J=z0(10);f(J),m(J,"Detecting existing configurations"),f(J);let Q=new Z0,z=await Q.detectExistingTools(),Y=[];if(z.length>0&&!Z.nonInteractive){if(console.log(`
|
|
117
117
|
\uD83D\uDD0D Configuration Migration Detection:`),console.log(`Found ${z.length} existing dependency management tool(s):`),z.forEach((O)=>console.log(` \u2022 ${O.name} (${O.configFile})`)),(await s.default({type:"confirm",name:"migrate",message:"Would you like to migrate existing configurations to Buddy?",initial:!0})).migrate){console.log(`
|
|
118
118
|
\uD83D\uDCCB Migrating configurations...`);for(let O of z)try{let w;if(O.name==="renovate")w=await Q.migrateFromRenovate(O.configFile);else if(O.name==="dependabot")w=await Q.migrateFromDependabot(O.configFile);else continue;Y.push(w),console.log(`\u2705 Migrated ${O.name} configuration`)}catch(w){console.log(`\u26A0\uFE0F Failed to migrate ${O.name}: ${w instanceof Error?w.message:"Unknown error"}`)}if(Y.length>0){let O=await Q.generateMigrationReport(Y);console.log(`
|
|
119
119
|
${O}`)}}}else if(z.length>0&&Z.nonInteractive)console.log(`
|
|
120
|
-
\uD83D\uDD0D Found ${z.length} existing tool(s), skipping migration in non-interactive mode`);m(J,"Discovering integrations",!0),f(J);let U=new $
|
|
120
|
+
\uD83D\uDD0D Found ${z.length} existing tool(s), skipping migration in non-interactive mode`);m(J,"Discovering integrations",!0),f(J);let U=new $0,j=await U.discoverPlugins();if(j.length>0&&!Z.nonInteractive){if(console.log(`
|
|
121
121
|
\uD83D\uDD0C Integration Discovery:`),console.log(`Found ${j.length} available integration(s):`),j.forEach((O)=>console.log(` \u2022 ${O.name} v${O.version}`)),(await s.default({type:"confirm",name:"enablePlugins",message:"Would you like to enable these integrations?",initial:!0})).enablePlugins)for(let O of j)await U.loadPlugin(O)}else if(j.length>0&&Z.nonInteractive)console.log(`
|
|
122
|
-
\uD83D\uDD0C Found ${j.length} integration(s), skipping in non-interactive mode`);m(J,"Running pre-flight checks",!0),f(J);let q=await
|
|
123
|
-
\u274C Pre-flight checks failed. Please fix the errors above and try again.`),V.exit(1);m(J,"Analyzing project",!0),f(J);let X=await
|
|
122
|
+
\uD83D\uDD0C Found ${j.length} integration(s), skipping in non-interactive mode`);m(J,"Running pre-flight checks",!0),f(J);let q=await J0();if(W1(q,"\uD83D\uDD0D Pre-flight Validation"),!q.success)console.log(`
|
|
123
|
+
\u274C Pre-flight checks failed. Please fix the errors above and try again.`),V.exit(1);m(J,"Analyzing project",!0),f(J);let X=await Q0();if(console.log(`
|
|
124
124
|
\uD83D\uDD0D Project Analysis:`),console.log(`\uD83D\uDCE6 Project Type: ${X.type}`),console.log(`\u2699\uFE0F Package Manager: ${X.packageManager}`),console.log(`\uD83D\uDD12 Lock File: ${X.hasLockFile?"Found":"Not found"}`),console.log(`\uD83D\uDCC4 Dependency Files: ${X.hasDependencyFiles?"Found":"None"}`),console.log(`\uD83D\uDD04 GitHub Actions: ${X.hasGitHubActions?"Found":"None"}`),console.log(`\uD83D\uDCA1 Recommended Preset: ${X.recommendedPreset}`),X.recommendations.length>0)console.log(`
|
|
125
125
|
\uD83D\uDCCB Recommendations:`),X.recommendations.forEach((P)=>console.log(` \u2022 ${P}`));m(J,"Repository Detection",!0),f(J),console.log(`
|
|
126
|
-
\uD83D\uDCCD Repository Detection`);let H=await
|
|
126
|
+
\uD83D\uDCCD Repository Detection`);let H=await Y0();if(!H)console.log("\u274C Could not detect repository. Please ensure you're in a Git repository."),V.exit(1);console.log(`\u2705 Detected repository: ${H.owner}/${H.name}`),console.log(`\uD83D\uDD17 GitHub URL: https://github.com/${H.owner}/${H.name}`);let G=await V0(H);if(G.warnings.length>0||G.suggestions.length>0)W1(G,"\uD83D\uDD0D Repository Validation");m(J,"GitHub Token Setup",!0),f(J),console.log(`
|
|
127
127
|
\uD83D\uDD11 GitHub Token Setup`),console.log("For full functionality, Buddy needs appropriate GitHub permissions."),console.log(`This enables workflow file updates and advanced GitHub Actions features.
|
|
128
|
-
`);let K;if(Z.nonInteractive)switch(Z.tokenSetup){case"existing-secret":K={hasCustomToken:!0,needsGuide:!1},console.log("\u2705 Using existing organization/repository secrets");break;case"new-pat":K={hasCustomToken:!0,needsGuide:!0},console.log("\u26A0\uFE0F Non-interactive mode: Will use custom token but skip setup guide");break;case"default-token":default:K={hasCustomToken:!1,needsGuide:!1},console.log("\u2705 Using default GITHUB_TOKEN (limited functionality)");break}else if(K=await
|
|
129
|
-
\uD83D\uDD27 Repository Settings`),await
|
|
128
|
+
`);let K;if(Z.nonInteractive)switch(Z.tokenSetup){case"existing-secret":K={hasCustomToken:!0,needsGuide:!1},console.log("\u2705 Using existing organization/repository secrets");break;case"new-pat":K={hasCustomToken:!0,needsGuide:!0},console.log("\u26A0\uFE0F Non-interactive mode: Will use custom token but skip setup guide");break;case"default-token":default:K={hasCustomToken:!1,needsGuide:!1},console.log("\u2705 Using default GITHUB_TOKEN (limited functionality)");break}else if(K=await j0(),K.needsGuide)await X0(H);m(J,"Repository Settings",!0),f(J),console.log(`
|
|
129
|
+
\uD83D\uDD27 Repository Settings`),await q0(H),m(J,"Workflow Configuration",!0),f(J),console.log(`
|
|
130
130
|
\u2699\uFE0F Workflow Configuration`);let W;if(Z.nonInteractive)W={useCase:Z.preset},console.log(`\u2705 Using ${Z.preset} preset for workflow configuration`);else if(W=await s.default([{type:"select",name:"useCase",message:"What type of update schedule would you like?",choices:[{title:"Standard Setup (Recommended)",description:"Dashboard updates 3x/week, dependency updates on schedule",value:"standard"},{title:"High Frequency",description:"Check for updates multiple times per day",value:"high-frequency"},{title:"Security Focused",description:"Frequent patch updates with security-first approach",value:"security"},{title:"Minimal Updates",description:"Weekly checks, lower frequency",value:"minimal"},{title:"Development/Testing",description:"Manual triggers + frequent checks for testing",value:"testing"},{title:"Custom Configuration",description:"Create your own schedule",value:"custom"}]}]),!W.useCase){console.log("Setup cancelled.");return}m(J,"Configuration File",!0),f(J),console.log(`
|
|
131
|
-
\uD83D\uDCDD Configuration File`),await
|
|
132
|
-
\uD83D\uDD04 Workflow Generation`);let F=
|
|
133
|
-
\uD83D\uDD0D Validating Generated Workflows`);let L=[{name:"buddy-dashboard.yml",content:""},{name:"buddy-check.yml",content:""},{name:"buddy-update.yml",content:""}],B=!0;for(let P of L)try{let O=`.github/workflows/${P.name}`;if(
|
|
131
|
+
\uD83D\uDCDD Configuration File`),await G0(H,K.hasCustomToken),m(J,"Workflow Generation",!0),f(J),console.log(`
|
|
132
|
+
\uD83D\uDD04 Workflow Generation`);let F=H0(W.useCase);if(W.useCase==="custom"&&!Z.nonInteractive)await W0(F,$);else console.log(`\u2728 Setting up ${F.name}...`),console.log(`\uD83D\uDCCB ${F.description}`);await K0(F,H,K.hasCustomToken,$),m(J,"Workflow Validation",!0),f(J),console.log(`
|
|
133
|
+
\uD83D\uDD0D Validating Generated Workflows`);let L=[{name:"buddy-dashboard.yml",content:""},{name:"buddy-check.yml",content:""},{name:"buddy-update.yml",content:""}],B=!0;for(let P of L)try{let O=`.github/workflows/${P.name}`;if(r1.existsSync(O)){let w=r1.readFileSync(O,"utf8"),I=await U0(w);if(!I.success)console.log(`\u274C ${P.name} validation failed`),W1(I,`${P.name} Issues`),B=!1;else console.log(`\u2705 ${P.name} validated successfully`)}}catch{console.log(`\u26A0\uFE0F Could not validate ${P.name}`)}if(!B)console.log(`
|
|
134
134
|
\u26A0\uFE0F Some workflows have validation issues. Please review the warnings above.`);if(m(J,"Setup Complete",!0),f(J),console.log(`
|
|
135
|
-
\uD83C\uDF89 Setup Complete!`),await
|
|
135
|
+
\uD83C\uDF89 Setup Complete!`),await F0(H,K.hasCustomToken),j.length>0){console.log(`
|
|
136
136
|
\uD83D\uDD0C Executing integration hooks...`);let P={step:"setup_complete",progress:J,config:Y.length>0?Y[0].migratedSettings:{},repository:H,analysis:X,plugins:j};U.setContext(P),await U.executePluginHooks({event:"setup_complete"})}}catch(J){$.error("Setup failed:",J),V.exit(1)}});T.command("scan","Scan for dependency updates").option("--verbose, -v","Enable verbose logging").option("--packages <names>","Comma-separated list of packages to check").option("--pattern <pattern>","Glob pattern to match packages").option("--strategy <type>","Update strategy: major|minor|patch|all",{default:"all"}).option("--ignore <names>","Comma-separated list of packages to ignore").option("--respect-latest",'Respect "latest", "*", and other dynamic version indicators (default: true)').option("--no-respect-latest",'Allow updating "latest", "*", and other dynamic version indicators').example("buddy scan").example("buddy scan --verbose").example('buddy scan --packages "react,typescript,laravel/framework"').example('buddy scan --pattern "@types/*"').example("buddy scan --strategy minor").example("buddy scan --no-respect-latest").action(async(Z)=>{let $=Z.verbose?M.verbose():M.quiet(),J=await C(Z.config);try{$.info("Loading configuration...");let Q;if(Z.packages)Q=Z.packages.split(",").map((G)=>G.trim());let z;if(Z.ignore)z=Z.ignore.split(",").map((G)=>G.trim());let Y={...J,verbose:Z.verbose??J.verbose,packages:{...J.packages,strategy:Z.strategy??J.packages?.strategy??"all",ignore:z??J.packages?.ignore,respectLatest:Z.respectLatest??J.packages?.respectLatest??!0}},U=new g(Y);if(Q?.length){$.info(`Checking specific packages: ${Q.join(", ")}`);let G=await U.checkPackages(Q);if(G.length===0)$.success("All specified packages are up to date!");else{$.info(`Found ${G.length} updates:`);for(let K of G)$.info(` ${K.name}: ${K.currentVersion} \u2192 ${K.newVersion} (${K.updateType})`)}return}if(Z.pattern){$.info(`Checking packages with pattern: ${Z.pattern}`);let G=await U.checkPackagesWithPattern(Z.pattern);if(G.length===0)$.success("All matching packages are up to date!");else{$.info(`Found ${G.length} updates:`);for(let K of G)$.info(` ${K.name}: ${K.currentVersion} \u2192 ${K.newVersion} (${K.updateType})`)}return}let j=await U.scanForUpdates();if(j.updates.length===0){$.success("All dependencies are up to date!");return}$.info(`
|
|
137
137
|
Scan Results:`),$.info(`\uD83D\uDCE6 Total packages: ${j.totalPackages}`),$.info(`\uD83D\uDD04 Available updates: ${j.updates.length}`),$.info(`\u23F1\uFE0F Scan duration: ${j.duration}ms`);let q=j.updates.filter((G)=>G.updateType==="major"),X=j.updates.filter((G)=>G.updateType==="minor"),H=j.updates.filter((G)=>G.updateType==="patch");if(q.length>0){$.warn(`
|
|
138
138
|
\uD83D\uDEA8 Major updates (${q.length}):`);for(let G of q)$.info(` ${G.name}: ${G.currentVersion} \u2192 ${G.newVersion}`)}if(X.length>0){$.info(`
|
|
139
139
|
\u2728 Minor updates (${X.length}):`);for(let G of X)$.info(` ${G.name}: ${G.currentVersion} \u2192 ${G.newVersion}`)}if(H.length>0){$.info(`
|
|
140
140
|
\uD83D\uDD27 Patch updates (${H.length}):`);for(let G of H)$.info(` ${G.name}: ${G.currentVersion} \u2192 ${G.newVersion}`)}if(j.groups.length>0){$.info(`
|
|
141
|
-
\uD83D\uDCCB Update groups (${j.groups.length}):`);for(let G of j.groups)$.info(` ${G.name}: ${G.updates.length} updates`)}}catch(Q){$.error("Scan failed:",Q),V.exit(1)}});T.command("dashboard","Create or update dependency dashboard issue").option("--verbose, -v","Enable verbose logging").option("--title <title>","Custom dashboard title").option("--issue-number <number>","Update specific issue number").option("--pin","Pin the dashboard issue to the top of the issue list").option("--no-pin","Unpin the dashboard issue").example("buddy dashboard").example('buddy dashboard --title "My Dependencies"').example("buddy dashboard --issue-number 42").example("buddy dashboard --pin").action(async(Z)=>{let $=Z.verbose?M.verbose():M.quiet(),J=await C(Z.config);try{if($.info("Creating or updating dependency dashboard..."),!J.repository)$.error("\u274C Repository configuration required for dashboard"),$.info("Configure repository.provider, repository.owner, repository.name in buddy.config.ts"),V.exit(1);let Q={...J,verbose:Z.verbose??J.verbose,dashboard:{...J.dashboard,enabled:!0,title:Z.title??J.dashboard?.title,issueNumber:Z.issueNumber?Number.parseInt(Z.issueNumber,10):J.dashboard?.issueNumber,pin:Z.pin??J.dashboard?.pin}},Y=await new g(Q).createOrUpdateDashboard();$.success(`\u2705 Dashboard updated: ${Y.url}`),$.info(`\uD83D\uDCCA Issue #${Y.number}: ${Y.title}`)}catch(Q){$.error("Dashboard creation failed:",Q),V.exit(1)}});T.command("update","Update dependencies and create PRs").option("--verbose, -v","Enable verbose logging").option("--strategy <type>","Update strategy: major|minor|patch|all",{default:"all"}).option("--ignore <names>","Comma-separated list of packages to ignore").option("--dry-run","Preview changes without making them").option("--respect-latest",'Respect "latest", "*", and other dynamic version indicators (default: true)').option("--no-respect-latest",'Allow updating "latest", "*", and other dynamic version indicators').example("buddy update").example("buddy update --dry-run").example("buddy update --strategy patch").example("buddy update --verbose").example("buddy update --no-respect-latest").action(async(Z)=>{let $=Z.verbose?M.verbose():M.quiet(),J=await C(Z.config);try{$.info("Starting dependency update process...");let Q;if(Z.ignore)Q=Z.ignore.split(",").map((j)=>j.trim());let z={...J,verbose:Z.verbose??J.verbose,packages:{...J.packages,strategy:Z.strategy??J.packages?.strategy??"all",ignore:Q??J.packages?.ignore,respectLatest:Z.respectLatest??J.packages?.respectLatest??!0}},Y=new g(z),U=await Y.scanForUpdates();if(U.updates.length===0){$.success("All dependencies are up to date!");return}if(Z.dryRun){$.info("\uD83D\uDD0D Dry run mode - no changes will be made"),$.info(`Would create ${U.groups.length} pull request(s):`);for(let j of U.groups)$.info(` \uD83D\uDCDD ${j.title} (${j.updates.length} updates)`);return}await Y.createPullRequests(U),$.success("Update process completed!")}catch(Q){$.error("Update failed:",Q),V.exit(1)}});T.command("rebase <pr-number>","Rebase/retry a pull request by recreating it with latest updates").option("--verbose, -v","Enable verbose logging").option("--force","Force rebase even if PR appears to be up to date").example("buddy rebase 17").example("buddy rebase 17 --verbose").example("buddy rebase 17 --force").action(async(Z,$)=>{let J=$.verbose?M.verbose():M.quiet(),Q=await C($.config);try{if(J.info(`\uD83D\uDD04 Rebasing/retrying PR #${Z}...`),!Q.repository)J.error("\u274C Repository configuration required for PR operations"),J.info("Configure repository.provider, repository.owner, repository.name in buddy.config.ts"),V.exit(1);let z=await d(Q,"PR operations",J),Y=Number.parseInt(Z,10);if(Number.isNaN(Y))J.error("\u274C Invalid PR number provided"),V.exit(1);let j=(await z.getPullRequests("open")).find((O)=>O.number===Y);if(!j)J.error(`\u274C Could not find open PR #${Y}`),V.exit(1);if(!j.head.startsWith("buddy/"))J.error(`\u274C PR #${Y} is not a buddy PR (branch: ${j.head})`),V.exit(1);J.info(`\uD83D\uDCCB Found PR: ${j.title}`),J.info(`\uD83C\uDF3F Branch: ${j.head}`);let q=await RZ(j.body);if(q.length===0)J.error("\u274C Could not extract package updates from PR body"),V.exit(1);if(J.info(`\uD83D\uDCE6 Found ${q.length} packages to update`),!$.force){J.info("\uD83D\uDD0D Checking if rebase is needed...");let I=(await new g(Q).scanForUpdates()).updates.filter((v)=>q.some((b)=>b.name===v.name));if(q.every((v)=>I.some((b)=>b.name===v.name&&b.newVersion===v.newVersion))){J.success("\u2705 PR is already up to date, no rebase needed"),J.info("\uD83D\uDCA1 Use --force to rebase anyway");return}}J.info("\uD83D\uDD04 Updating PR with latest updates...");let X=new g({...Q,verbose:$.verbose??Q.verbose}),H=await X.scanForUpdates();if(H.updates.length===0){J.success("\u2705 All dependencies are now up to date!");return}let G=H.groups.find((O)=>O.updates.length===q.length&&O.updates.every((w)=>q.some((I)=>I.name===w.name))&&q.every((w)=>O.updates.some((I)=>I.name===w.name)));if(!G){J.error("\u274C Could not find matching update group. This likely means the package grouping has changed."),J.info(`\uD83D\uDCCB PR packages: ${q.map((O)=>O.name).join(", ")}`),J.info(`\uD83D\uDCCB Available groups: ${H.groups.map((O)=>`${O.name} (${O.updates.length} packages)`).join(", ")}`),J.info("\uD83D\uDCA1 Close this PR manually and let buddy create new ones with correct grouping");return}let K=await X.generateAllFileUpdates(G.updates);if(K.length===0){J.info(`\u2139\uFE0F No file changes generated for PR #${Y} \u2014 likely a pantry/pkgx-style dep with no JS writer. Skipping commit to avoid an empty force-push.`);let O=j.body||"",w=O.replace(/- \[x\] <!-- rebase-check -->/g,"- [ ] <!-- rebase-check -->");if(w!==O)await z.updatePullRequest(Y,{body:w}),J.info("\u2705 Unticked rebase checkbox to prevent the next update-check run from re-triggering this no-op rebase.");return}let W=Q.repository?.baseBranch||"main";await z.commitChanges(j.head,G.title,K,W),J.info(`\u2705 Recreated branch ${j.head} from ${W} with latest changes`);let{PullRequestGenerator:F}=await import("../chunk-9p1xkmjy.js"),P=(await new F({verbose:$.verbose}).generateBody(G)).replace(/- \[x\] <!-- rebase-check -->/g,"- [ ] <!-- rebase-check -->");await z.updatePullRequest(Y,{title:G.title,body:P}),J.success("\uD83D\uDD04 PR rebase completed! Updated existing PR in place.")}catch(z){J.error("Rebase failed:",z),V.exit(1)}});async function RZ(Z){let $=
|
|
141
|
+
\uD83D\uDCCB Update groups (${j.groups.length}):`);for(let G of j.groups)$.info(` ${G.name}: ${G.updates.length} updates`)}}catch(Q){$.error("Scan failed:",Q),V.exit(1)}});T.command("dashboard","Create or update dependency dashboard issue").option("--verbose, -v","Enable verbose logging").option("--title <title>","Custom dashboard title").option("--issue-number <number>","Update specific issue number").option("--pin","Pin the dashboard issue to the top of the issue list").option("--no-pin","Unpin the dashboard issue").example("buddy dashboard").example('buddy dashboard --title "My Dependencies"').example("buddy dashboard --issue-number 42").example("buddy dashboard --pin").action(async(Z)=>{let $=Z.verbose?M.verbose():M.quiet(),J=await C(Z.config);try{if($.info("Creating or updating dependency dashboard..."),!J.repository)$.error("\u274C Repository configuration required for dashboard"),$.info("Configure repository.provider, repository.owner, repository.name in buddy.config.ts"),V.exit(1);let Q={...J,verbose:Z.verbose??J.verbose,dashboard:{...J.dashboard,enabled:!0,title:Z.title??J.dashboard?.title,issueNumber:Z.issueNumber?Number.parseInt(Z.issueNumber,10):J.dashboard?.issueNumber,pin:Z.pin??J.dashboard?.pin}},Y=await new g(Q).createOrUpdateDashboard();$.success(`\u2705 Dashboard updated: ${Y.url}`),$.info(`\uD83D\uDCCA Issue #${Y.number}: ${Y.title}`)}catch(Q){$.error("Dashboard creation failed:",Q),V.exit(1)}});T.command("update","Update dependencies and create PRs").option("--verbose, -v","Enable verbose logging").option("--strategy <type>","Update strategy: major|minor|patch|all",{default:"all"}).option("--ignore <names>","Comma-separated list of packages to ignore").option("--dry-run","Preview changes without making them").option("--respect-latest",'Respect "latest", "*", and other dynamic version indicators (default: true)').option("--no-respect-latest",'Allow updating "latest", "*", and other dynamic version indicators').example("buddy update").example("buddy update --dry-run").example("buddy update --strategy patch").example("buddy update --verbose").example("buddy update --no-respect-latest").action(async(Z)=>{let $=Z.verbose?M.verbose():M.quiet(),J=await C(Z.config);try{$.info("Starting dependency update process...");let Q;if(Z.ignore)Q=Z.ignore.split(",").map((j)=>j.trim());let z={...J,verbose:Z.verbose??J.verbose,packages:{...J.packages,strategy:Z.strategy??J.packages?.strategy??"all",ignore:Q??J.packages?.ignore,respectLatest:Z.respectLatest??J.packages?.respectLatest??!0}},Y=new g(z),U=await Y.scanForUpdates();if(U.updates.length===0){$.success("All dependencies are up to date!");return}if(Z.dryRun){$.info("\uD83D\uDD0D Dry run mode - no changes will be made"),$.info(`Would create ${U.groups.length} pull request(s):`);for(let j of U.groups)$.info(` \uD83D\uDCDD ${j.title} (${j.updates.length} updates)`);return}await Y.createPullRequests(U),$.success("Update process completed!")}catch(Q){$.error("Update failed:",Q),V.exit(1)}});T.command("rebase <pr-number>","Rebase/retry a pull request by recreating it with latest updates").option("--verbose, -v","Enable verbose logging").option("--force","Force rebase even if PR appears to be up to date").example("buddy rebase 17").example("buddy rebase 17 --verbose").example("buddy rebase 17 --force").action(async(Z,$)=>{let J=$.verbose?M.verbose():M.quiet(),Q=await C($.config);try{if(J.info(`\uD83D\uDD04 Rebasing/retrying PR #${Z}...`),!Q.repository)J.error("\u274C Repository configuration required for PR operations"),J.info("Configure repository.provider, repository.owner, repository.name in buddy.config.ts"),V.exit(1);let z=await d(Q,"PR operations",J),Y=Number.parseInt(Z,10);if(Number.isNaN(Y))J.error("\u274C Invalid PR number provided"),V.exit(1);let j=(await z.getPullRequests("open")).find((O)=>O.number===Y);if(!j)J.error(`\u274C Could not find open PR #${Y}`),V.exit(1);if(!j.head.startsWith("buddy/"))J.error(`\u274C PR #${Y} is not a buddy PR (branch: ${j.head})`),V.exit(1);J.info(`\uD83D\uDCCB Found PR: ${j.title}`),J.info(`\uD83C\uDF3F Branch: ${j.head}`);let q=await RZ(j.body);if(q.length===0)J.error("\u274C Could not extract package updates from PR body"),V.exit(1);if(J.info(`\uD83D\uDCE6 Found ${q.length} packages to update`),!$.force){J.info("\uD83D\uDD0D Checking if rebase is needed...");let I=(await new g(Q).scanForUpdates()).updates.filter((v)=>q.some((b)=>b.name===v.name));if(q.every((v)=>I.some((b)=>b.name===v.name&&b.newVersion===v.newVersion))){J.success("\u2705 PR is already up to date, no rebase needed"),J.info("\uD83D\uDCA1 Use --force to rebase anyway");return}}J.info("\uD83D\uDD04 Updating PR with latest updates...");let X=new g({...Q,verbose:$.verbose??Q.verbose}),H=await X.scanForUpdates();if(H.updates.length===0){J.success("\u2705 All dependencies are now up to date!");return}let G=H.groups.find((O)=>O.updates.length===q.length&&O.updates.every((w)=>q.some((I)=>I.name===w.name))&&q.every((w)=>O.updates.some((I)=>I.name===w.name)));if(!G){J.error("\u274C Could not find matching update group. This likely means the package grouping has changed."),J.info(`\uD83D\uDCCB PR packages: ${q.map((O)=>O.name).join(", ")}`),J.info(`\uD83D\uDCCB Available groups: ${H.groups.map((O)=>`${O.name} (${O.updates.length} packages)`).join(", ")}`),J.info("\uD83D\uDCA1 Close this PR manually and let buddy create new ones with correct grouping");return}let K=await X.generateAllFileUpdates(G.updates);if(K.length===0){J.info(`\u2139\uFE0F No file changes generated for PR #${Y} \u2014 likely a pantry/pkgx-style dep with no JS writer. Skipping commit to avoid an empty force-push.`);let O=j.body||"",w=O.replace(/- \[x\] <!-- rebase-check -->/g,"- [ ] <!-- rebase-check -->");if(w!==O)await z.updatePullRequest(Y,{body:w}),J.info("\u2705 Unticked rebase checkbox to prevent the next update-check run from re-triggering this no-op rebase.");return}let W=Q.repository?.baseBranch||"main";await z.commitChanges(j.head,G.title,K,W),J.info(`\u2705 Recreated branch ${j.head} from ${W} with latest changes`);let{PullRequestGenerator:F}=await import("../chunk-9p1xkmjy.js"),P=(await new F({verbose:$.verbose}).generateBody(G)).replace(/- \[x\] <!-- rebase-check -->/g,"- [ ] <!-- rebase-check -->");await z.updatePullRequest(Y,{title:G.title,body:P}),J.success("\uD83D\uDD04 PR rebase completed! Updated existing PR in place.")}catch(z){J.error("Rebase failed:",z),V.exit(1)}});async function RZ(Z){let $=s1(Z);if($?.truncated)return[];if($)return t1($);let J=[],Q=/\|\s*\[([^\]]+)\][^|]*\|\s*\[?`\^?([^`]+)`\s*->\s*`\^?([^`]+)`\]?/g,z;while((z=Q.exec(Z))!==null){let[,Y,U,j]=z;J.push({name:Y,currentVersion:U,newVersion:j})}return J}T.command("update-check","Check all open buddy PRs for rebase checkbox and auto-rebase if checked").option("--verbose, -v","Enable verbose logging").option("--dry-run","Check but don't actually rebase").example("buddy update-check").example("buddy update-check --verbose").example("buddy update-check --dry-run").action(async(Z)=>{let $=Z.verbose?M.verbose():M.quiet(),J=await C(Z.config);try{if(!J.repository)$.error("\u274C Repository configuration required for PR operations"),$.info("Configure repository.provider, repository.owner, repository.name in buddy.config.ts"),V.exit(1);let Q=await d(J,"PR operations",$),z=await CZ(Q,J,$),Y=n1(z?.body);if(A1(Y))$.info(`\uD83D\uDCCB Dashboard requests: ${Y.rebaseBranches.length} branch(es)${Y.rebaseAll?", rebase all":""}${Y.manualRun?", manual run":""}`);let U=new Set(Y.rebaseBranches);$.info("\uD83D\uDD0D Checking for PRs with rebase checkbox enabled...");let j=0,q=0;try{let K=(await Q.getPullRequests("open")).filter((W)=>W.head.startsWith("buddy/"));$.info(`\uD83D\uDCCB Found ${K.length} buddy PRs to check for rebase requests`);for(let W of K){q++;let F=Y.rebaseAll||U.has(W.head);if(SZ(W.body||"")||F)if($.info(`\uD83D\uDD04 PR #${W.number} has rebase ${F?"requested from the dashboard":"checkbox checked"}`),Z.dryRun)$.info(`\uD83D\uDD0D [DRY RUN] Would rebase PR #${W.number}`),j++;else{$.info(`\uD83D\uDD04 Rebasing PR #${W.number} via rebase command...`);try{let{spawn:B}=await import("child_process"),P=B("bunx",["@buddysh/buddy","rebase",W.number.toString()],{stdio:"inherit",cwd:V.cwd()});await new Promise((O,w)=>{P.on("close",(I)=>{if(I===0)j++,O(I);else w(Error(`Rebase failed with code ${I}`))})}),$.success(`\u2705 Successfully rebased PR #${W.number}`)}catch(B){$.error(`\u274C Failed to rebase PR #${W.number}:`,B)}}}if(j>0)$.success(`\u2705 ${Z.dryRun?"Would rebase":"Successfully rebased"} ${j} PR(s)`);else if(q>0)$.info("\uD83D\uDCCB No PRs have rebase checkbox enabled")}catch(G){$.warn("\u26A0\uFE0F Could not check for rebase requests:",G)}if(A1(Y)&&z){if(Z.dryRun)$.info("\uD83D\uDD0D [DRY RUN] Would clear dashboard checkboxes");else try{await Q.updateIssue(z.number,{body:a1(z.body||"")}),$.success("\u2705 Cleared dashboard checkboxes")}catch(G){$.warn("\u26A0\uFE0F Could not clear dashboard checkboxes:",G)}if(Y.manualRun)if($.info("\uD83D\uDD04 Dashboard requested a full update run..."),Z.dryRun)$.info("\uD83D\uDD0D [DRY RUN] Would run a full scan and create PRs");else try{let G=new g(J),K=await G.scanForUpdates();if(K.updates.length>0)await G.createPullRequests(K);else $.info("\u2705 No updates found during the requested run")}catch(G){$.error("\u274C Requested update run failed:",G)}}$.info(`
|
|
142
142
|
\u2705 Checking for PRs with satisfied dependencies...`);try{let{Buddy:G}=await import("../chunk-0r8zt3d7.js");await new G(J).checkAndCloseSatisfiedPRs(Q,!!Z.dryRun)}catch(G){$.error("\u26A0\uFE0F Could not check for satisfied PRs:",G)}$.info(`
|
|
143
143
|
\uD83D\uDD0D Checking for obsolete PRs due to removed dependency files...`);try{let{Buddy:G}=await import("../chunk-0r8zt3d7.js");await new G(J).checkAndCloseObsoletePRs(Q,!!Z.dryRun)}catch(G){$.error("\u26A0\uFE0F Could not check for obsolete PRs:",G)}let X=0;try{if(X=(await new g(J).mergeEligiblePullRequests(!!Z.dryRun)).length,X>0)$.success(`\uD83D\uDD00 ${Z.dryRun?"Would merge":"Merged"} ${X} PR(s)`)}catch(G){$.warn("\u26A0\uFE0F Could not process auto-merge:",G)}$.info(`
|
|
144
144
|
\uD83E\uDDF9 Running branch cleanup...`),r(Q,"branchHousekeeping","cleanupStaleBranches","branch cleanup");let H=await Q.cleanupStaleBranches(2,!!Z.dryRun);if(Z.dryRun)$.info(`\uD83D\uDD0D [DRY RUN] Would delete ${H.deleted.length} stale branches`);else $.success(`\uD83C\uDF89 Cleanup complete: ${H.deleted.length} branches deleted, ${H.failed.length} failed`);if(j>0||X>0||H.deleted.length>0)$.success(`
|
|
145
145
|
\uD83C\uDF89 Update-check complete: ${j} PR(s) rebased, ${X} merged, ${H.deleted.length} branches cleaned`)}catch(Q){$.error("update-check failed:",Q),V.exit(1)}});async function CZ(Z,$,J){try{let Q=await Z.getIssues("open"),z=$.dashboard?.issueNumber;if(z)return Q.find((U)=>U.number===z)??null;let Y=$.dashboard?.title??"Dependency Dashboard";return Q.find((U)=>U.title===Y)??Q.find((U)=>U.title.includes("Dependency Dashboard"))??null}catch(Q){return J.warn("\u26A0\uFE0F Could not load the dependency dashboard:",Q),null}}function SZ(Z){return/\s*-\s*\[x\]\s*<!--\s*rebase-check\s*-->.*(?:rebase|update)\/retry/i.test(Z)}T.command("fix-ci","Diagnose a failing workflow run and repair it when the fix is clear").option("--verbose, -v","Enable verbose logging").option("--run-id <id>","Workflow run to diagnose").option("--pr <number>","Pull request to comment on").option("--dry-run","Report the diagnosis without acting").example("buddy fix-ci --run-id 12345").action(async(Z)=>{let $=Z.verbose?M.verbose():M.quiet(),J=await C(Z.config);try{let Q=await d(J,"this command",$);r(Q,"ciLogs","getWorkflowRunLogs","reading CI logs");let z=Z.runId?Number.parseInt(Z.runId,10):void 0,Y=z?await Q.getWorkflowRunLogs(z):null;if(!Y){$.warn("\u26A0\uFE0F Could not read the run logs; nothing to diagnose");return}let{attemptFix:U}=await import("../chunk-nsmcjkas.js"),{createAiClient:j}=await import("../chunk-54sc18p8.js"),q=await U({log:Y,workspace:V.cwd(),baseBranch:J.repository?.baseBranch??"main",ai:j(J,$),logger:$,regenerateLockfile:async()=>{let{regenerateLockFile:H,detectRequiredPackageManagers:G}=await import("../chunk-887s0w81.js"),K=G(["package.json","composer.json"]),W=!1;for(let F of K){let L=await H(F,V.cwd());if(L.success)W=!0;else $.warn(`\u26A0\uFE0F ${L.message}`)}return W}});$.info(`
|
|
146
146
|
${q.report}
|
|
147
|
-
`);let X=Z.pr?Number.parseInt(Z.pr,10):void 0;if(X&&!Z.dryRun)await Q.createComment(X,q.report);$.success(`\u2705 ${q.action}${q.fixed?" (fixed)":""}`)}catch(Q){$.error("fix-ci failed:",Q),V.exit(1)}});T.command("handle-comment","Handle an @buddy command from a GitHub event payload").option("--verbose, -v","Enable verbose logging").option("--payload <path>","Path to the event payload (default: GITHUB_EVENT_PATH)").option("--dry-run","Report what would run without acting").example("buddy handle-comment").action(async(Z)=>{let $=Z.verbose?M.verbose():M.quiet(),J=await C(Z.config);try{let Q=Z.payload||V.env.GITHUB_EVENT_PATH;if(!Q)$.error("\u274C No event payload. Pass --payload or run inside GitHub Actions."),V.exit(1);let z=await Bun.file(Q).json(),Y=z.comment,U=z.issue??z.pull_request;if(!Y?.body||!U?.number){$.info("\u2139\uFE0F Event carries no comment; nothing to do");return}let{mentionsBot:j,parseCommand:q}=await import("../chunk-qvn1rtgp.js");if(!j(Y.body)){$.info("\u2139\uFE0F Comment does not mention buddy; nothing to do");return}let X=q(Y.body);if(!X){$.info("\u2139\uFE0F Mention is not a command (quoted or inside code); nothing to do");return}let H=await d(J,"this command",$),G=Y.user?.login??"",K=Y.user?.type==="Bot"||G.endsWith("[bot]"),W={login:G,isBot:K,canWrite:!K&&
|
|
147
|
+
`);let X=Z.pr?Number.parseInt(Z.pr,10):void 0;if(X&&!Z.dryRun)await Q.createComment(X,q.report);$.success(`\u2705 ${q.action}${q.fixed?" (fixed)":""}`)}catch(Q){$.error("fix-ci failed:",Q),V.exit(1)}});T.command("handle-comment","Handle an @buddy command from a GitHub event payload").option("--verbose, -v","Enable verbose logging").option("--payload <path>","Path to the event payload (default: GITHUB_EVENT_PATH)").option("--dry-run","Report what would run without acting").example("buddy handle-comment").action(async(Z)=>{let $=Z.verbose?M.verbose():M.quiet(),J=await C(Z.config);try{let Q=Z.payload||V.env.GITHUB_EVENT_PATH;if(!Q)$.error("\u274C No event payload. Pass --payload or run inside GitHub Actions."),V.exit(1);let z=await Bun.file(Q).json(),Y=z.comment,U=z.issue??z.pull_request;if(!Y?.body||!U?.number){$.info("\u2139\uFE0F Event carries no comment; nothing to do");return}let{mentionsBot:j,parseCommand:q}=await import("../chunk-qvn1rtgp.js");if(!j(Y.body)){$.info("\u2139\uFE0F Comment does not mention buddy; nothing to do");return}let X=q(Y.body);if(!X){$.info("\u2139\uFE0F Mention is not a command (quoted or inside code); nothing to do");return}let H=await d(J,"this command",$),G=Y.user?.login??"",K=Y.user?.type==="Bot"||G.endsWith("[bot]"),W={login:G,isBot:K,canWrite:!K&&z1(H,"permissionLookup","hasWriteAccess")?await H.hasWriteAccess(G):!1},F=Boolean(z.pull_request??z.issue?.pull_request);if($.info(`\uD83E\uDD16 Handling \`${X.name}\` from @${G} on #${U.number}`),Z.dryRun){$.info(`\uD83D\uDD0D [DRY RUN] Would run ${X.name} (canWrite: ${W.canWrite})`);return}if(z1(H,"commentReactions","reactToComment"))await H.reactToComment(Y.id,"eyes");let{createHandlers:L,dispatchCommand:B}=await import("../chunk-qvn1rtgp.js"),{runReviewForPR:P}=await import("../chunk-pkjm2r0a.js"),O=await B({command:X,actor:W,number:U.number,isPullRequest:F,commentId:Y.id,logger:$},L({config:J,provider:H,review:async(w,I)=>await P({config:J,provider:H,prNumber:w,logger:$,...I}),rebase:async(w)=>{let{spawn:I}=await import("child_process");return await new Promise((k,v)=>{I("bunx",["@buddysh/buddy","rebase",String(w)],{stdio:"inherit"}).on("close",(y)=>y===0?k():v(Error(`rebase exited ${y}`)))}),"Rebased."},merge:async()=>await new g(J).mergeEligiblePullRequests(!1),remember:async(w,I)=>{let{addLearning:k,createLearning:v,loadLearnings:b,serializeLearnings:y,DEFAULT_LEARNINGS_FILE:c}=await import("../chunk-54sc18p8.js"),E=J.repository?.baseBranch??"main",h=await b((N,S)=>H.getFileContent(N,S),E,c,$),_=v(w,{source:I.isPullRequest?{pr:I.number}:{issue:I.number}}),u=`buddy/learning-${_.id}`;return await H.commitChanges(u,"chore(buddy): record a learning",[{path:c,content:y(k(h,_)),type:"update"}],E),await H.createPullRequest({title:"chore(buddy): record a learning",body:`Recorded from #${I.number}:
|
|
148
148
|
|
|
149
|
-
> ${w}`,head:u,base:E,draft:!1}),`Noted. I opened a pull request adding it to \`${c}\` so it gets reviewed like any other change.`}}));if(O.reply)await H.createComment(U.number,O.reply);if(
|
|
149
|
+
> ${w}`,head:u,base:E,draft:!1}),`Noted. I opened a pull request adding it to \`${c}\` so it gets reviewed like any other change.`}}));if(O.reply)await H.createComment(U.number,O.reply);if(z1(H,"commentReactions","reactToComment"))await H.reactToComment(Y.id,O.handled?"rocket":"confused");$.success(O.handled?`\u2705 Handled \`${X.name}\``:`\u2139\uFE0F Did not run: ${O.refusal}`)}catch(Q){$.error("handle-comment failed:",Q),V.exit(1)}});T.command("review [pr-number]","Review a pull request, or local changes when no PR is given").option("--verbose, -v","Enable verbose logging").option("--base <branch>","Base branch to diff against for a local review").option("--staged","Review staged changes only").option("--branch","Review this branch against its base, rather than the working tree").option("--light","Analyzers only \u2014 no AI call, fast enough for a pre-commit hook").option("--format <name>","Output format: pretty|json|github|agent",{default:"pretty"}).option("--fix","Apply committable suggestions to the working tree").option("--yes","Apply fixes without confirming each one").option("--fail-on <severity>","Exit non-zero when a finding at or above this severity is found").option("--profile <name>","Review profile: chill|assertive").option("--summary-only","Post only the summary, without inline findings").option("--dry-run","Print the review instead of posting it").example("buddy review 42").example("buddy review --staged --light").example("buddy review --format agent | claude").action(async(Z,$)=>{let J=$.verbose?M.verbose():M.quiet(),Q=await C($.config),z=$.format??"pretty";if(!R1.includes(z))J.error(`\u274C Unknown format '${z}'. Expected one of ${R1.join(", ")}.`),V.exit(1);let Y=z!=="pretty",U=Y?M.silent():J;try{let{createAiClient:j}=await import("../chunk-54sc18p8.js"),q=j(Q,U);if(!q&&(Z||!$.light))J.error("\u274C AI review needs an API key, or use --light for analyzers only. See https://buddy.sh/ai/providers"),V.exit(1);let{composeInstructions:X,loadGuidelines:H,parseReviewState:G,prepareReview:K,reviewDiff:W}=await import("../chunk-p3wsm8kz.js"),{collectLocalDiff:F,formatReview:L,shouldFail:B}=await import("../chunk-63ept76v.js"),{runAnalyzers:P}=await import("../chunk-4hd3rre0.js"),O,w="",I=[],k=null;if(Z){k=await d(Q,"reviewing a pull request",U);let N=Number.parseInt(Z,10);O=await k.getPullRequestDiff(N);let o=(await k.getPullRequests("open")).find((Y1)=>Y1.number===N),n=G(o?.body);I=n?.fingerprints??[],w=n?.reviewedSha??""}else{let N=$.base||Q.repository?.baseBranch||"main",S=$.staged?"staged":$.branch?"branch":"working";U.info(`\uD83D\uDD0D Reviewing ${S} changes${S==="branch"?` against ${N}`:""}...`),O=await F(S,N)}if(!O.trim()){if(!Y)J.success("\u2705 No changes to review");return}let{parseUnifiedDiff:v}=await import("../chunk-mh3x7j6h.js"),b=v(O).files.map((N)=>N.path),y=Q.analysis?.enabled===!1||Z?{findings:[],ran:[],skipped:[]}:await P({files:b,root:V.cwd(),...Q.analysis?.tools?{enabled:Q.analysis.tools}:{},logger:U});if($.light){let N={summary:`Static analysis of ${b.length} changed file(s).`,walkthrough:[],findings:y.findings,effort:1,omittedFiles:y.skipped.map((S)=>`${S.name} (${S.reason})`)};if(V.stdout.write(L(N,z)),$.failOn&&B(N.findings,$.failOn))V.exit(1);return}let c=Q.repository?.baseBranch||$.base||"main",E=k?await H((N,S)=>k.getFileContent(N,S),c,Q.ai?.review?.guidelineFiles,J):"",h=await W(q,{diff:O,profile:$.profile??Q.ai?.review?.profile,summaryOnly:$.summaryOnly??Q.ai?.review?.summaryOnly,instructions:X({global:Q.ai?.review?.instructions,guidelines:E}),pathFilters:Q.ai?.review?.pathFilters,pathInstructions:Q.ai?.review?.pathInstructions,seenFingerprints:I,logger:U}),_={...h,findings:[...y.findings,...h.findings],omittedFiles:[...h.omittedFiles,...y.skipped.map((N)=>`${N.name} (${N.reason})`)]},u=K(_,{headSha:w,requestChangesOn:Q.ai?.review?.requestChangesOn,seenFingerprints:I});if(!Z){if(V.stdout.write(L(_,z)),$.fix){let N=await AZ(_.findings,Boolean($.yes),J);J.success(`\uD83D\uDD27 Applied ${N} suggestion(s)`)}if($.failOn&&B(_.findings,$.failOn))V.exit(1);return}if($.dryRun){J.info(`
|
|
150
150
|
${u.body}
|
|
151
151
|
`);for(let N of u.comments)J.info(`${N.path}:${N.line}
|
|
152
152
|
${N.body}
|
|
@@ -176,13 +176,13 @@ For manual setup, visit:`),$.info("\uD83D\uDD17 Repository settings: https://git
|
|
|
176
176
|
`);V.exit(j.failed?1:0)});T.command("touch <pr-number>","Run a finishing touch ticked on a pull request, as a stacked PR").option("--name <touch>","Run a specific touch rather than reading the checkboxes").option("--test-command <command>","Command that verifies the change").option("--dry-run","Report what would run without acting").option("--verbose, -v","Enable verbose logging").example("buddy touch 42").example("buddy touch 42 --name unit-tests").action(async(Z,$)=>{let J=$.verbose?M.verbose():M.quiet(),Q=await C($.config);try{let z=Number.parseInt(Z,10),Y=await d(Q,"finishing touches",J),j=(await Y.getPullRequests("open")).find((B)=>B.number===z);if(!j)J.error(`\u274C Pull request #${z} is not open`),V.exit(1);let{FINISHING_TOUCHES:q,getFinishingTouch:X,parseTouchSelections:H}=await import("../chunk-7xk28xrv.js"),G=$.name?[$.name]:H(j.body);if(G.length===0){J.info("\u2139\uFE0F No finishing touches are ticked on this pull request");return}let{createAiClient:K}=await import("../chunk-54sc18p8.js"),W=K(Q,J);if(!W)J.error("\u274C Finishing touches need an API key. See https://buddy.sh/ai/providers"),V.exit(1);if($.dryRun){J.info(`\uD83D\uDD0D [DRY RUN] Would run: ${G.join(", ")}`);return}let{runStackedTouch:F}=await import("../chunk-c3fczawt.js");for(let B of G){if(!q[B]){J.warn(`\u26A0\uFE0F Unknown finishing touch '${B}', skipping`);continue}let P=await F({provider:Y,pullRequest:j,touch:X(B),ai:W,workspace:V.cwd(),...$.testCommand?{testCommand:$.testCommand.split(" ")}:{},logger:J});await Y.createComment(z,P.comment),J.success(`\u2705 ${B}: ${P.mode}`)}let L=j.body.replace(/^(\s*-\s*)\[[xX]\](\s*<!--\s*buddy:touch=)/gm,"$1[ ]$2");if(L!==j.body)await Y.updatePullRequest(z,{body:L})}catch(z){J.error("Finishing touch failed:",z),V.exit(1)}});T.command("handle-issue","Post Buddy quick-links on a new issue, or run a ticked action").option("--payload <path>","Path to the event payload (default: GITHUB_EVENT_PATH)").option("--issue <number>","Act on an issue directly rather than reading an event").option("--dry-run","Report what would happen without acting").option("--verbose, -v","Enable verbose logging").example("buddy handle-issue").action(async(Z)=>{let $=Z.verbose?M.verbose():M.quiet(),J=await C(Z.config);if(J.issues?.quickLinks!==!0){$.info("\u2139\uFE0F Issue quick-links are off (set issues.quickLinks to enable)");return}try{let Q=Z.issue?Number.parseInt(Z.issue,10):Number.NaN;if(Number.isNaN(Q)){let F=Z.payload||V.env.GITHUB_EVENT_PATH;if(!F)$.error("\u274C No event payload. Pass --issue or --payload, or run inside CI."),V.exit(1);let L=await Bun.file(F).json();if(Q=Number(L?.issue?.number),Number.isNaN(Q)){$.info("\u2139\uFE0F Event carries no issue; nothing to do");return}}let z=await d(J,"issue quick-links",$),U=(await z.getIssues("open")).find((F)=>F.number===Q);if(!U){$.info(`\u2139\uFE0F Issue #${Q} is not open`);return}let{clearQuickSelection:j,parseQuickSelection:q,QUICK_LINKS_MARKER:X,renderQuickLinks:H}=await import("../chunk-fqj7e6xa.js"),G=q(U.body);if(G.actions.length>0){if($.info(`\uD83E\uDD16 Requested: ${G.actions.join(", ")}`),Z.dryRun)return;let{createAiClient:F}=await import("../chunk-54sc18p8.js"),L=F(J,$);if(!L){await z.createComment(Q,"Buddy needs an AI provider configured to act on this. See https://buddy.sh/ai/providers");return}await z.updateIssue(Q,{body:j(U.body)});for(let B of G.actions){let{getFinishingTouch:P,runAgent:O}=await import("../chunk-2dbkpfy9.js"),w=P(B==="build"?"autofix":"plan"),I=await O(L,{mode:w.mode,task:`${w.buildTask({summary:U.title,files:[]})}
|
|
177
177
|
|
|
178
178
|
Issue:
|
|
179
|
-
${U.body}`,context:{workspace:V.cwd(),baseBranch:J.repository?.baseBranch??"main"},logger:$});await z.createComment(Q,I.output),$.success(`\u2705 Ran ${B}`)}return}if(U.body.includes(X)){$.debug("Quick-links already posted on this issue");return}let K=J.issues?.dependencyContext?await xZ(J,$):[],W=H({body:U.body,packages:K});if(Z.dryRun){$.info(W);return}await z.createComment(Q,W),$.success(`\u2705 Posted quick-links on #${Q}`)}catch(Q){$.error("handle-issue failed:",Q),V.exit(1)}});T.command("gate <pr-number>","Run pre-merge gates on a pull request and publish the result").option("--dry-run","Print the result instead of publishing a check run").option("--verbose, -v","Enable verbose logging").example("buddy gate 42").action(async(Z,$)=>{let J=$.verbose?M.verbose():M.quiet(),Q=await C($.config);try{let z=Number.parseInt(Z,10);if(Number.isNaN(z))J.error("\u274C Invalid PR number"),V.exit(1);let Y=await d(Q,"running gates",J),{findLinkedIssues:U,runAiGates:j,runGates:q,summarizeGates:X}=await import("../chunk-r06ce5g6.js"),{parseManifest:H}=await import("../chunk-frm8zz31.js"),K=(await Y.getPullRequests("open")).find((E)=>E.number===z);if(!K)J.error(`\u274C Pull request #${z} is not open`),V.exit(1);let W=Q.gates??{},F=H(K.body),{manifestUpdates:L}=await import("../chunk-frm8zz31.js"),B=F?await Promise.all(L(F).map(async(E)=>{let h={name:E.name,version:E.newVersion};if(W.dependencyGate?.blockEol===!1)return h;if(F.updates.find((n)=>n.name===E.name)?.dependencyType!=="docker-image")return h;let{checkEol:u,describeEol:N}=await import("../chunk-p1xm1jvz.js"),S=await u(E.name,E.newVersion,{logger:J}),o=N(S);return S?.eol&&o?{...h,eol:o}:h})):[],P=q({title:K.title,body:K.body,manifest:F,dependencies:B},{...W.titleFormat?{titleFormat:W.titleFormat}:{},...W.description?{description:W.description}:{},...W.dependencyGate?{dependencyGate:W.dependencyGate}:{}}),O=U(K.body??""),w=O.length>0?await Y.getIssues("all"):[],I=O.map((E)=>w.find((h)=>h.number===E)).filter((E)=>Boolean(E)).map((E)=>({number:E.number,title:E.title,body:E.body})),{createAiClient:k}=await import("../chunk-54sc18p8.js"),v=await j(k(Q,J),{title:K.title,body:K.body,diff:await Y.getPullRequestDiff(z),linkedIssues:I},{...W.linkedIssue?{linkedIssue:W.linkedIssue}:{},...W.custom?{custom:W.custom}:{}},J),b=[...P,...v],y=X(b);for(let E of b)J.info(`${E.passed?"\u2705":E.mode==="error"?"\u274C":"\u26A0\uFE0F"} ${E.name}: ${E.summary}`);let c=y.conclusion==="failure";if($.dryRun||!
|
|
179
|
+
${U.body}`,context:{workspace:V.cwd(),baseBranch:J.repository?.baseBranch??"main"},logger:$});await z.createComment(Q,I.output),$.success(`\u2705 Ran ${B}`)}return}if(U.body.includes(X)){$.debug("Quick-links already posted on this issue");return}let K=J.issues?.dependencyContext?await xZ(J,$):[],W=H({body:U.body,packages:K});if(Z.dryRun){$.info(W);return}await z.createComment(Q,W),$.success(`\u2705 Posted quick-links on #${Q}`)}catch(Q){$.error("handle-issue failed:",Q),V.exit(1)}});T.command("gate <pr-number>","Run pre-merge gates on a pull request and publish the result").option("--dry-run","Print the result instead of publishing a check run").option("--verbose, -v","Enable verbose logging").example("buddy gate 42").action(async(Z,$)=>{let J=$.verbose?M.verbose():M.quiet(),Q=await C($.config);try{let z=Number.parseInt(Z,10);if(Number.isNaN(z))J.error("\u274C Invalid PR number"),V.exit(1);let Y=await d(Q,"running gates",J),{findLinkedIssues:U,runAiGates:j,runGates:q,summarizeGates:X}=await import("../chunk-r06ce5g6.js"),{parseManifest:H}=await import("../chunk-frm8zz31.js"),K=(await Y.getPullRequests("open")).find((E)=>E.number===z);if(!K)J.error(`\u274C Pull request #${z} is not open`),V.exit(1);let W=Q.gates??{},F=H(K.body),{manifestUpdates:L}=await import("../chunk-frm8zz31.js"),B=F?await Promise.all(L(F).map(async(E)=>{let h={name:E.name,version:E.newVersion};if(W.dependencyGate?.blockEol===!1)return h;if(F.updates.find((n)=>n.name===E.name)?.dependencyType!=="docker-image")return h;let{checkEol:u,describeEol:N}=await import("../chunk-p1xm1jvz.js"),S=await u(E.name,E.newVersion,{logger:J}),o=N(S);return S?.eol&&o?{...h,eol:o}:h})):[],P=q({title:K.title,body:K.body,manifest:F,dependencies:B},{...W.titleFormat?{titleFormat:W.titleFormat}:{},...W.description?{description:W.description}:{},...W.dependencyGate?{dependencyGate:W.dependencyGate}:{}}),O=U(K.body??""),w=O.length>0?await Y.getIssues("all"):[],I=O.map((E)=>w.find((h)=>h.number===E)).filter((E)=>Boolean(E)).map((E)=>({number:E.number,title:E.title,body:E.body})),{createAiClient:k}=await import("../chunk-54sc18p8.js"),v=await j(k(Q,J),{title:K.title,body:K.body,diff:await Y.getPullRequestDiff(z),linkedIssues:I},{...W.linkedIssue?{linkedIssue:W.linkedIssue}:{},...W.custom?{custom:W.custom}:{}},J),b=[...P,...v],y=X(b);for(let E of b)J.info(`${E.passed?"\u2705":E.mode==="error"?"\u274C":"\u26A0\uFE0F"} ${E.name}: ${E.summary}`);let c=y.conclusion==="failure";if($.dryRun||!z1(Y,"checkRuns","createCheckRun")){if(J.info(y.summary),c)V.exit(1);return}if(await Y.createCheckRun("buddy/gates",await Y.getPullRequestHeadSha(z),y),c)V.exit(1)}catch(z){J.error("Gate run failed:",z),V.exit(1)}});T.command("post-merge <pr-number>","Run post-merge actions for a merged pull request").option("--verbose, -v","Enable verbose logging").example("buddy post-merge 42").action(async(Z,$)=>{let J=$.verbose?M.verbose():M.quiet(),Q=await C($.config);try{let z=Number.parseInt(Z,10),Y=await d(Q,"post-merge actions",J),j=(await Y.getPullRequests("all")).find((H)=>H.number===z);if(!j)J.error(`\u274C Pull request #${z} not found`),V.exit(1);if(j.state!=="merged"){J.info(`\u2139\uFE0F PR #${z} was closed without merging; nothing to do`);return}let{runPostMerge:q}=await import("../chunk-r06ce5g6.js"),X=await q(Y,j,Q.gates?.postMerge??{},{baseBranch:Q.repository?.baseBranch??j.base,logger:J});for(let H of X.performed)J.success(`\u2705 ${H}`);for(let H of X.skipped)J.info(`\u23ED\uFE0F ${H.action}: ${H.reason}`)}catch(z){J.error("Post-merge actions failed:",z),V.exit(1)}});T.command("report","Generate a dependency-health and activity report").option("--period <window>","Reporting window: 7d|30d|90d",{default:"30d"}).option("--format <name>","Output format: markdown|json",{default:"markdown"}).option("--prompt <focus>","Focus for the AI narrative, when a provider is configured").option("--publish","Publish to the repository's report issue").option("--verbose, -v","Enable verbose logging").example("buddy report --period 7d").example('buddy report --prompt "focus on security posture" --publish').action(async(Z)=>{let $=Z.format==="json",J=Z.verbose?M.verbose():$?M.silent():M.quiet(),Q=await C(Z.config);try{let{appendHistory:z,computeDeltas:Y,computeMetrics:U,findPrevious:j,HISTORY_PATH:q,loadHistory:X,REPORT_MARKER:H,REPORT_PERIODS:G,renderReport:K,withNarrative:W}=await import("../chunk-czremqk7.js"),F=Z.period??"30d";if(!G.includes(F))J.error(`\u274C Unknown period '${F}'. Expected one of ${G.join(", ")}.`),V.exit(1);let L=await d(Q,"reporting",J),B=new g(Q,V.cwd()),{PackageScanner:P}=await import("../chunk-f4nv5x3z.js"),O=new P(V.cwd(),J,Q.packages?.ignorePaths),[w,I,k]=await Promise.all([B.scanForUpdates(),L.getPullRequests("all"),O.scanProject()]),{ecosystemOf:v}=await import("../chunk-p7zgy37f.js"),b={};for(let X1 of k)for(let j1 of X1.dependencies){let k1=v({name:j1.name,currentVersion:j1.currentVersion,newVersion:j1.currentVersion,updateType:"patch",dependencyType:j1.type,file:X1.path});b[k1]=(b[k1]??0)+1}let{DeprecatedDependenciesChecker:y}=await import("../chunk-6patq6bw.js"),c=await new y().checkDeprecatedDependencies(k).catch(()=>[]),E=U({period:F,now:new Date,pullRequests:I,updates:w.updates,dependenciesByEcosystem:b,deprecated:c.length}),h=Q.repository?.baseBranch||"main",_=await X(L,h,J),u=Y(E,j(_,F));if(Z.format==="json"){V.stdout.write(`${JSON.stringify({metrics:E,deltas:u},null,2)}
|
|
180
180
|
`);return}let{createAiClient:N}=await import("../chunk-54sc18p8.js"),S=await W(K(E,u),E,N(Q,J),Z.prompt??Q.reports?.prompt,J);if(!Z.publish){V.stdout.write(`${S}
|
|
181
|
-
`);return}let n=(await L.getIssues("open")).find((
|
|
181
|
+
`);return}let n=(await L.getIssues("open")).find((X1)=>X1.body.includes(H)),Y1=Q.reports?.title??"Dependency Report",S1=Q.reports?.labels??["dependencies","report"],M0=n?await L.updateIssue(n.number,{title:Y1,body:S,labels:S1}):await L.createIssue({title:Y1,body:S,labels:S1});J.success(`\u2705 Report published: ${M0.url}`),await L.commitChanges(h,"chore(reports): record dependency metrics snapshot",[{path:q,content:z(_,E),type:_.length>0?"update":"create"}],h)}catch(z){J.error("Report failed:",z),V.exit(1)}});T.command("doctor","Diagnose this environment: credentials, git state and analyzer tooling").option("--verbose, -v","Enable verbose logging").example("buddy doctor").action(async(Z)=>{let $=Z.verbose?M.verbose():M.quiet(),J=await C(Z.config).catch((U)=>{return $.warn(`\u26A0\uFE0F Could not load configuration: ${t(U)}`),{}}),{diagnose:Q,renderDoctorReport:z}=await import("../chunk-fdfk918n.js"),Y=await Q(J);if(V.stdout.write(z(Y)),!Y.healthy)V.exit(1)});T.command("run","Run a prompt headlessly, with optional schema-validated output").option("--prompt <text>","The prompt to run").option("--prompt-file <path>","Read the prompt from a file").option("--output-schema <json>","JSON Schema the output must satisfy").option("--output-schema-file <path>","Read the schema from a file").option("--model <name>","Model override").option("--retries <n>","Schema retries before failing",{default:"2"}).option("--verbose, -v","Enable verbose logging").example(`buddy run --prompt "Summarize this week's dependency updates"`).example(`buddy run --prompt-file p.txt --output-schema '{"type":"object"}'`).action(async(Z)=>{let $=Z.verbose?M.verbose():M.silent(),J=await C(Z.config);try{let Q=Z.promptFile?await Bun.file(Z.promptFile).text():Z.prompt;if(!Q?.trim())V.stderr.write(`\u274C Provide --prompt or --prompt-file
|
|
182
182
|
`),V.exit(1);let z=Z.outputSchemaFile?await Bun.file(Z.outputSchemaFile).text():Z.outputSchema,Y;if(z)try{Y=JSON.parse(z)}catch(W){V.stderr.write(`\u274C --output-schema is not valid JSON: ${t(W)}
|
|
183
183
|
`),V.exit(1)}let{createAiClient:U}=await import("../chunk-54sc18p8.js"),j=U(Z.model?{...J,ai:{...J.ai,model:Z.model}}:J,$);if(!j)V.stderr.write(`\u274C No AI provider configured. See https://buddy.sh/ai/providers
|
|
184
184
|
`),V.exit(1);let{publishOutput:q,runHeadless:X}=await import("../chunk-9eqpaxfz.js"),H=await X({prompt:Q,ai:j,...Y?{schema:Y}:{},maxRetries:Number.parseInt(Z.retries??"2",10),logger:$});if(!H.valid)V.stderr.write(`\u274C Output did not satisfy the schema after ${H.attempts} attempt(s):
|
|
185
185
|
${H.error}
|
|
186
186
|
`),V.exit(1);let G=await q(H.result,V.env.GITHUB_OUTPUT),K=typeof H.result==="string"?H.result:JSON.stringify(H.result,null,2);if(V.stdout.write(`${K}
|
|
187
187
|
`),G)$.info("\uD83D\uDCE4 Wrote `result` to $GITHUB_OUTPUT")}catch(Q){V.stderr.write(`\u274C ${t(Q)}
|
|
188
|
-
`),V.exit(1)}});T.command("version","Show the version of Buddy").action(()=>{console.log(
|
|
188
|
+
`),V.exit(1)}});T.command("version","Show the version of Buddy").action(()=>{console.log(P1)});T.option("--config <path>","Path to a buddy config file");T.version(P1);T.help();T.parse();
|
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@buddysh/buddy",
|
|
3
3
|
"type": "module",
|
|
4
|
-
"version": "0.11.
|
|
4
|
+
"version": "0.11.1",
|
|
5
5
|
"description": "AI code review and dependency updates in one bot. Reviews pull requests and local changes, answers @buddy comments, gates merges, repairs failing CI, and keeps dependencies current across npm, Composer, Docker, GitHub Actions and more.",
|
|
6
6
|
"author": "Chris Breuer <chris@stacksjs.org>",
|
|
7
7
|
"license": "MIT",
|