@buddysh/buddy 0.11.4 → 0.11.5
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 +18 -0
- package/dist/bin/cli.js +7 -7
- package/dist/{chunk-e2t5jq26.js → chunk-3cab6vqx.js} +1 -1
- package/dist/{chunk-28y7eayr.js → chunk-4sfyfxdk.js} +1 -1
- package/dist/{chunk-ng7px8gx.js → chunk-4yq2fny9.js} +1 -1
- package/dist/{chunk-emb5v4wv.js → chunk-5gejc3rx.js} +1 -1
- package/dist/{chunk-4jyw358y.js → chunk-5x4gt4c5.js} +1 -1
- package/dist/{chunk-86x1vsjw.js → chunk-5xfs8a89.js} +1 -1
- package/dist/{chunk-ngh4jbgp.js → chunk-8gd76j8e.js} +1 -1
- package/dist/chunk-8ycrg9gp.js +3 -0
- package/dist/{chunk-patms7t8.js → chunk-9fq7drn8.js} +1 -1
- package/dist/{chunk-b1w41hfs.js → chunk-9t15md0g.js} +1 -1
- package/dist/{chunk-s25rb4t2.js → chunk-baq6x78h.js} +1 -1
- package/dist/{chunk-cs066zt9.js → chunk-ctt9xk2j.js} +1 -1
- package/dist/{chunk-jz5zs812.js → chunk-dm5yktev.js} +1 -1
- package/dist/{chunk-bmnx3s41.js → chunk-j9cgwkm8.js} +1 -1
- package/dist/{chunk-rwggcfgn.js → chunk-jfzqpmnp.js} +1 -1
- package/dist/{chunk-rayxmbcx.js → chunk-kbbqs8ae.js} +1 -1
- package/dist/{chunk-e0gweha1.js → chunk-mf959vjt.js} +1 -1
- package/dist/{chunk-yr8eta7p.js → chunk-rz7pg7pb.js} +8 -8
- package/dist/{chunk-5av2vnvv.js → chunk-tzwnfagh.js} +1 -1
- package/dist/src/index.js +1 -1
- package/dist/src/utils/lock-file.d.ts +10 -2
- package/package.json +1 -1
- package/dist/chunk-8fw0v7bv.js +0 -3
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,23 @@
|
|
|
1
1
|
# Changelog
|
|
2
2
|
|
|
3
|
+
[Compare changes](https://github.com/stacksjs/buddy/compare/v0.11.4...v0.11.5)
|
|
4
|
+
|
|
5
|
+
## 🐛 Bug Fixes
|
|
6
|
+
|
|
7
|
+
- **lockfile**: regenerate pantry.lock alongside the JS lockfile ([25c9f51](https://github.com/stacksjs/buddy/commit/25c9f51)) _(by Chris <chrisbreuer93@gmail.com>)_ ([#2848](https://github.com/stacksjs/buddy/issues/2848))
|
|
8
|
+
|
|
9
|
+
## ✅ Tests
|
|
10
|
+
|
|
11
|
+
- **config**: isolate the legacy-name lookup from GITHUB_REPOSITORY ([c449557](https://github.com/stacksjs/buddy/commit/c449557)) _(by Chris <chrisbreuer93@gmail.com>)_ ([#1457](https://github.com/stacksjs/buddy/issues/1457))
|
|
12
|
+
|
|
13
|
+
## 🔧 Chores
|
|
14
|
+
|
|
15
|
+
- release v0.11.5 ([ce830bd](https://github.com/stacksjs/buddy/commit/ce830bd)) _(by Chris <chrisbreuer93@gmail.com>)_
|
|
16
|
+
|
|
17
|
+
## Contributors
|
|
18
|
+
|
|
19
|
+
- _Chris <chrisbreuer93@gmail.com>_
|
|
20
|
+
|
|
3
21
|
[Compare changes](https://github.com/stacksjs/buddy/compare/v0.11.3...v0.11.4)
|
|
4
22
|
|
|
5
23
|
## 🐛 Bug Fixes
|
package/dist/bin/cli.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
#!/usr/bin/env bun
|
|
2
2
|
// @bun
|
|
3
|
-
import{Pc as C1}from"../chunk-
|
|
3
|
+
import{Pc as C1}from"../chunk-8gd76j8e.js";import"../chunk-ctt9xk2j.js";import{_c as f}from"../chunk-3cab6vqx.js";import"../chunk-phfmnnne.js";import"../chunk-r763e19p.js";import"../chunk-be629jhq.js";import"../chunk-pkr6905p.js";import"../chunk-eseshkd0.js";import"../chunk-11hdrnf6.js";import{od as g}from"../chunk-cwfkm7h9.js";import"../chunk-mkzmjg3f.js";import{Gd as Q0,yd as R1}from"../chunk-vgtmrd4c.js";import"../chunk-nrr8z2z7.js";import"../chunk-xs12dtf1.js";import{ke as J0,le as Q1,me as z1}from"../chunk-tzwnfagh.js";import"../chunk-ytmxd5fk.js";import"../chunk-b9escac0.js";import"../chunk-g30dr44w.js";import"../chunk-2et8yavs.js";import"../chunk-txtrpypt.js";import"../chunk-8hjvthz4.js";import"../chunk-yngahb11.js";import"../chunk-08x5b93v.js";import"../chunk-p6qbqsyp.js";import"../chunk-1cpdz49v.js";import"../chunk-cgvt98pd.js";import"../chunk-c8rzx3a1.js";import"../chunk-0hc97k0t.js";import{kg as Z0,og as $0}from"../chunk-3901s7h9.js";import"../chunk-jtxcr5yw.js";import"../chunk-qd2s51gc.js";import{$g as K0,Sg as CZ,Tg as z0,Ug as Y0,Vg as X0,Wg as j0,Xg as G0,Yg as _,Zg as h,ah as q0,bh as H0,ch as U0,dh as V0,gh as W0,hh as F0,ih as M0,jh as D0,kh as W1,lh as O0,mh as L0}from"../chunk-vbeeyhhe.js";import"../chunk-k26wnmzk.js";import"../chunk-193abzy6.js";import"../chunk-e68nf7cm.js";import{Ch as r,Dh as O}from"../chunk-hfjywbbc.js";import"../chunk-g24hav8e.js";import{Uk as RZ,Wk as D}from"../chunk-q4t568hv.js";import o1 from"fs";import V from"process";import{EventEmitter as w0}from"events";import c from"process";import v1 from"process";import T1 from"process";import q1 from"process";import Z1 from"process";import m1 from"tty";import GZ,{stdin as nZ,stdout as iZ}from"process";import u1,{stdin as HZ,stdout as UZ}from"process";import VZ from"readline";import{existsSync as IZ}from"fs";import D1 from"fs/promises";import c1 from"os";import O1 from"path";import n from"process";function L1(Z){return Z.replace(/[<[].+/,"").trim()}function E0(Z){let $=/<([^>]+)>/g,J=/\[([^\]]+)\]/g,Q=[],z=(j)=>{let G=!1,X=j[1];if(X.startsWith("..."))X=X.slice(3),G=!0;else if(X.endsWith("..."))X=X.slice(0,-3),G=!0;return{required:j[0].startsWith("<"),value:X.trim(),variadic:G}},Y;while(Y=$.exec(Z))Q.push(z(Y));let U;while(U=J.exec(Z))Q.push(z(U));return Q}function B0(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 _1(Z){return Z.reduce(($,J)=>$.length>=J.length?$:J,"")}function F1(Z,$){return Z.length>=$?Z:`${Z}${" ".repeat($-Z.length)}`}function K1(Z){return Z.replace(/([a-z])-([a-z])/g,($,J,Q)=>{return J+Q.toUpperCase()})}function I0(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 P0(Z,$){for(let J of Object.keys($)){let Q=$[J];if(Z[J]===void 0)continue;if(Q.shouldTransform){if(Z[J]=Array.prototype.concat.call([],Z[J]),typeof Q.transformFunction==="function")Z[J]=Z[J].map(Q.transformFunction)}}}function N0(Z){let $=/([^\\/]+)$/.exec(Z);return $?$[1]:""}function $1(Z){return Z.split(".").map(($,J)=>{return J===0?K1($):$}).join(".")}class J1 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
6
|
${this.stack}`;return this.message}}function A0(Z){if(Z instanceof J1)return!0;return!!Z&&typeof Z==="object"&&Z.name==="ClappError"&&typeof Z.message==="string"}function x0(){let{env:Z}=v1,{TERM:$,TERM_PROGRAM:J}=Z;if(v1.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",C=`${V1}[`;var u={to(Z,$){if(!$)return`${C}${Z+1}G`;return`${C}${$+1};${Z+1}H`},move(Z,$){let J="";if(Z<0)J+=`${C}${-Z}D`;else if(Z>0)J+=`${C}${Z}C`;if($<0)J+=`${C}${-$}A`;else if($>0)J+=`${C}${$}B`;return J},up:(Z=1)=>`${C}${Z}A`,down:(Z=1)=>`${C}${Z}B`,forward:(Z=1)=>`${C}${Z}C`,backward:(Z=1)=>`${C}${Z}D`,nextLine:(Z=1)=>`${C}E`.repeat(Z),prevLine:(Z=1)=>`${C}F`.repeat(Z),left:`${C}G`,hide:`${C}?25l`,show:`${C}?25h`,save:`${V1}7`,restore:`${V1}8`};var M1={screen:`${C}2J`,up:(Z=1)=>`${C}1J`.repeat(Z),down:(Z=1)=>`${C}J`.repeat(Z),line:`${C}2K`,lineEnd:`${C}K`,lineStart:`${C}1K`,lines(Z){let $="";for(let J=0;J<Z;J++)$+=this.line+(J<Z-1?u.up():"");if(Z)$+=u.left;return $}},fZ={screen:`${V1}c`};function R0(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 l1(Z,$,J=2,Q=3){return $.map((z)=>({cmd:z,distance:R0(Z,z)})).filter(({distance:z})=>z<=J).sort((z,Y)=>z.distance-Y.distance).slice(0,Q).map(({cmd:z})=>z)}function C0(Z,$={}){let J={_:[]},Q=$.alias||{},z=new Set($.boolean||[]),Y={};for(let G of Object.keys(Q))for(let X of Q[G])Y[X]=G;for(let G of z)if(Q[G])for(let X of Q[G])z.add(X);function U(G,X){if(G===void 0)return X;if(typeof X==="boolean")return X;return Array.isArray(G)?[...G,X]:[G,X]}function j(G,X){let H=Y[G]||G,q=U(J[H],X);if(J[H]=q,Q[H])for(let K of Q[H])J[K]=q;if(Y[G]&&Q[Y[G]])for(let K of Q[Y[G]])J[K]=q;J[G]=q}for(let G=0;G<Z.length;G++){let X=Z[G];if(X==="--"){J._.push(...Z.slice(G+1));break}if(X.startsWith("--")){let H=X.indexOf("=");if(H!==-1){let q=K1(X.slice(2,H)),K=X.slice(H+1);j(q,K)}else{let q=X.slice(2);if(q.startsWith("no-")){let W=K1(q.slice(3));j(W,!1);continue}let K=K1(q),F=Y[K]||K;if(z.has(F)||z.has(K))j(K,!0);else{let W=Z[G+1];if(W!==void 0&&!W.startsWith("-"))j(K,W),G++;else j(K,!0)}}}else if(X.startsWith("-")&&X.length>1){let H=X.slice(1);for(let q=0;q<H.length;q++){let K=H[q],F=Y[K]||K;if(q===H.length-1&&!z.has(F)&&!z.has(K)){let W=Z[G+1];if(W!==void 0&&!W.startsWith("-"))j(K,W),G++;else j(K,!0)}else j(K,!0)}}else J._.push(X)}return J}class p1{rawName;description;name;names;isBoolean;required;config;negated;variadic;constructor(Z,$,J){if(this.rawName=Z,this.description=$,this.config=Object.assign({},J),Z=Z.replace(/\.\*/g,""),this.negated=!1,this.variadic=/[<[](?:\.\.\.[^\]>]+|[^\]>]+\.\.\.)[\]>]/.test(Z),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 $1(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 dZ=T1.argv,S0=`${T1.platform}-${T1.arch} bun-v${typeof Bun<"u"?Bun.version:"unknown"}`,f1=q1.argv,k0=`${q1.platform}-${q1.arch} node-${q1.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=E0(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 p1(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 $=$1(Z.split(".")[0]);return!!this.options.find((J)=>{return J.names.some((Q)=>$1(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=_1($.map((W)=>W.rawName)),H=new Map,q=[];for(let W of $)if(W.namespace){if(!H.has(W.namespace))H.set(W.namespace,[]);H.get(W.namespace).push(W)}else q.push(W);let K="";if(q.sort((W,T)=>W.rawName<T.rawName?-1:W.rawName>T.rawName?1:0),q.length>0)K+=q.map((W)=>{return` ${F1(W.rawName,X.length)} ${W.description}`}).join(`
|
|
@@ -38,7 +38,7 @@ Run \`${this.name??"cli"} --help\` for usage.`;c.stderr.write(`${J}${$}${Q}
|
|
|
38
38
|
`).length-1;this.output.write(u.move(-999,Z*-1))}render(){let Z=g1(this._render(this)??"",u1.stdout.columns,{hard:!0,trim:!1});if(Z===this._prevFrame)return;if(this.state==="initial")this.output.write(u.hide);else{let $=qZ(this._prevFrame,Z);if(this.restoreCursor(),$&&$?.length===1){let J=$[0];this.output.write(u.move(0,J)),this.output.write(M1.lines(1));let Q=Z.split(`
|
|
39
39
|
`);this.output.write(Q[J]),this._prevFrame=Z,this.output.write(u.move(0,Q.length-J-1));return}if($&&$?.length>1){let J=$[0];this.output.write(u.move(0,J)),this.output.write(M1.down());let z=Z.split(`
|
|
40
40
|
`).slice(J);this.output.write(z.join(`
|
|
41
|
-
`)),this._prevFrame=Z;return}this.output.write(M1.down())}if(this.output.write(Z),this.state==="initial")this.state="active";this._prevFrame=Z}}function MZ(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 DZ(Z,$){return($.label??String($.value)).toLowerCase().includes(Z.toLowerCase())}function OZ(Z,$){if(!$)return;if(Z)return $;return $[0]}class LZ 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??DZ;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=OZ(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=MZ(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 TZ 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 wZ=x0();var x=(Z,$)=>wZ?Z:$,tZ=x("\u25C6","*"),oZ=x("\u25A0","x"),eZ=x("\u25B2","x"),Z$=x("\u25C7","o"),$$=x("\u250C","T"),EZ=x("\u2502","|"),J$=x("\u2514","\u2014"),Q$=x("\u25CF",">"),z$=x("\u25CB"," "),Y$=x("\u25FB","[\u2022]"),X$=x("\u25FC","[+]"),j$=x("\u25FB","[ ]"),G$=x("\u25AA","\u2022"),K$=x("\u2500","-"),q$=x("\u256E","+"),H$=x("\u251C","+"),U$=x("\u256F","+"),V$=x("\u25CF","\u2022"),W$=x("\u25C6","*"),F$=x("\u25B2","!"),M$=x("\u25A0","x");var D$={light:x("\u2500","-"),heavy:x("\u2501","="),block:x("\u2588","#")};function BZ(){return`${H1.gray(EZ)} `}var O$=BZ();class r1{configPath;config=null;events=[];retryCount=0;maxRetries=3;retryDelayMs=1000;constructor(){let Z=c1.homedir(),$=O1.join(Z,".config","clapp");this.configPath=O1.join($,"telemetry.json")}async isEnabled(){if(n.env.DO_NOT_TRACK==="1"||n.env.DO_NOT_TRACK==="true")return!1;if(n.env.NO_TELEMETRY==="1"||n.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:c1.platform(),nodeVersion:n.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:n.env.DO_NOT_TRACK==="1"||n.env.DO_NOT_TRACK==="true",eventsQueued:this.events.length,lastSent:Z.lastSent}}async loadConfig(){if(this.config)return this.config;try{if(IZ(this.configPath)){let Z=await D1.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 $=O1.dirname(this.configPath);await D1.mkdir($,{recursive:!0}),await D1.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 I$=new r1;var a=RZ(CZ(),1);var P1="0.11.
|
|
41
|
+
`)),this._prevFrame=Z;return}this.output.write(M1.down())}if(this.output.write(Z),this.state==="initial")this.state="active";this._prevFrame=Z}}function MZ(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 DZ(Z,$){return($.label??String($.value)).toLowerCase().includes(Z.toLowerCase())}function OZ(Z,$){if(!$)return;if(Z)return $;return $[0]}class LZ 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??DZ;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=OZ(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=MZ(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 TZ 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 wZ=x0();var x=(Z,$)=>wZ?Z:$,tZ=x("\u25C6","*"),oZ=x("\u25A0","x"),eZ=x("\u25B2","x"),Z$=x("\u25C7","o"),$$=x("\u250C","T"),EZ=x("\u2502","|"),J$=x("\u2514","\u2014"),Q$=x("\u25CF",">"),z$=x("\u25CB"," "),Y$=x("\u25FB","[\u2022]"),X$=x("\u25FC","[+]"),j$=x("\u25FB","[ ]"),G$=x("\u25AA","\u2022"),K$=x("\u2500","-"),q$=x("\u256E","+"),H$=x("\u251C","+"),U$=x("\u256F","+"),V$=x("\u25CF","\u2022"),W$=x("\u25C6","*"),F$=x("\u25B2","!"),M$=x("\u25A0","x");var D$={light:x("\u2500","-"),heavy:x("\u2501","="),block:x("\u2588","#")};function BZ(){return`${H1.gray(EZ)} `}var O$=BZ();class r1{configPath;config=null;events=[];retryCount=0;maxRetries=3;retryDelayMs=1000;constructor(){let Z=c1.homedir(),$=O1.join(Z,".config","clapp");this.configPath=O1.join($,"telemetry.json")}async isEnabled(){if(n.env.DO_NOT_TRACK==="1"||n.env.DO_NOT_TRACK==="true")return!1;if(n.env.NO_TELEMETRY==="1"||n.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:c1.platform(),nodeVersion:n.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:n.env.DO_NOT_TRACK==="1"||n.env.DO_NOT_TRACK==="true",eventsQueued:this.events.length,lastSent:Z.lastSent}}async loadConfig(){if(this.config)return this.config;try{if(IZ(this.configPath)){let Z=await D1.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 $=O1.dirname(this.configPath);await D1.mkdir($,{recursive:!0}),await D1.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 I$=new r1;var a=RZ(CZ(),1);var P1="0.11.5";var N1=String.raw`^\s*-\s*\[[xX]\]\s*`,NZ=new RegExp(`${N1}<!--\\s*rebase-branch=([^>]*?)\\s*-->`,"gm"),AZ=new RegExp(`${N1}<!--\\s*rebase-all-open-prs\\s*-->`,"m"),xZ=new RegExp(`${N1}<!--\\s*manual job\\s*-->`,"m");function s1(Z){if(!Z)return{rebaseBranches:[],rebaseAll:!1,manualRun:!1};let $=[];for(let J of Z.matchAll(NZ)){let Q=J[1].trim();if(Q&&!$.includes(Q))$.push(Q)}return{rebaseBranches:$,rebaseAll:AZ.test(Z),manualRun:xZ.test(Z)}}function A1(Z){return Z.rebaseBranches.length>0||Z.rebaseAll||Z.manualRun}function t1(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 S(Z){if(Z)return await C1(Z);if(!x1)x1=await C1();return x1}async function m(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 J0({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 ${r(Q)}`),V.exit(1)}}async function e1(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 G=Bun.file(U);if(!await G.exists()){J.warn(`\u26A0\uFE0F Skipping ${U}: not in the working tree`);continue}let X=await G.text();for(let H of[...j].sort((q,K)=>K.line-q.line)){if(!$){if(!(await a.default({type:"confirm",name:"apply",message:`${U}:${H.line} \u2014 ${H.message}
|
|
42
42
|
${H.suggestion}
|
|
43
43
|
Apply?`,initial:!1})).apply)continue}let q=Q0(X,H.line,H.suggestion);if(q===null){J.warn(`\u26A0\uFE0F Skipping ${U}:${H.line}: the file changed since the review`);continue}X=q,Y++}await Bun.write(U,X)}return Y}async function SZ(Z,$){try{let{PackageScanner:J}=await import("../chunk-fpnjpgrb.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: ${r(J)}`),[]}}var w=new B1("buddy");w.usage(`[command] [options]
|
|
44
44
|
|
|
@@ -139,12 +139,12 @@ Scan Results:`),$.info(`\uD83D\uDCE6 Total packages: ${j.totalPackages}`),$.info
|
|
|
139
139
|
\u2728 Minor updates (${X.length}):`);for(let q of X)$.info(` ${q.name}: ${q.currentVersion} \u2192 ${q.newVersion}`)}if(H.length>0){$.info(`
|
|
140
140
|
\uD83D\uDD27 Patch updates (${H.length}):`);for(let q of H)$.info(` ${q.name}: ${q.currentVersion} \u2192 ${q.newVersion}`)}if(j.groups.length>0){$.info(`
|
|
141
141
|
\uD83D\uDCCB Update groups (${j.groups.length}):`);for(let q of j.groups)$.info(` ${q.name}: ${q.updates.length} updates`)}}catch(Q){$.error("Scan failed:",Q),await g(J.notifications,"run.failed",{command:"scan",error:Q instanceof Error?Q.message:String(Q)}),V.exit(1)}});w.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?O.verbose():O.quiet(),J=await S(Z.config);if(J.dashboard?.enabled===!1){$.info("\u2139\uFE0F Dashboard is disabled by config (dashboard.enabled: false)");return}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 f(Q).createOrUpdateDashboard();$.success(`\u2705 Dashboard updated: ${Y.url}`),$.info(`\uD83D\uDCCA Issue #${Y.number}: ${Y.title}`)}catch(Q){$.error("Dashboard creation failed:",Q),await g(J.notifications,"run.failed",{command:"dashboard",error:Q instanceof Error?Q.message:String(Q)}),V.exit(1)}});w.command("update","Update dependencies and create PRs").option("--verbose, -v","Enable verbose logging").option("--strategy <type>","Update strategy: major|minor|patch|all (default: packages.strategy from config, else all)").option("--ignore <names>","Comma-separated list of packages to ignore").option("--dry-run","Preview changes without making them").option("--reviewers <names>","Comma-separated reviewers to assign (overrides pullRequest.reviewers)").option("--assignees <names>","Comma-separated assignees to assign (overrides pullRequest.assignees)").option("--labels <names>","Comma-separated labels to add (overrides pullRequest.labels)").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?O.verbose():O.quiet(),J=await S(Z.config);try{$.info("Starting dependency update process...");let Q;if(Z.ignore)Q=Z.ignore.split(",").map((K)=>K.trim());let z=(K)=>K?K.split(",").map((F)=>F.trim()).filter(Boolean):void 0,Y=z(Z.reviewers),U=z(Z.assignees),j=z(Z.labels),G={...Y?{reviewers:Y}:{},...U?{assignees:U}:{},...j?{labels:j}:{}},X={...J,verbose:Z.verbose??J.verbose,...Object.keys(G).length?{pullRequest:{...J.pullRequest,...G}}:{},packages:{...J.packages,strategy:Z.strategy??J.packages?.strategy??"all",ignore:Q??J.packages?.ignore,respectLatest:Z.respectLatest??J.packages?.respectLatest??!0}},H=new f(X),q=await H.scanForUpdates();if(q.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 ${q.groups.length} pull request(s):`);for(let K of q.groups)$.info(` \uD83D\uDCDD ${K.title} (${K.updates.length} updates)`);return}await H.createPullRequests(q),$.success("Update process completed!")}catch(Q){$.error("Update failed:",Q),await g(J.notifications,"run.failed",{command:"update",error:Q instanceof Error?Q.message:String(Q)}),V.exit(1)}});w.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?O.verbose():O.quiet(),Q=await S($.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 m(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((M)=>M.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 G=await kZ(j.body);if(G.length===0)J.error("\u274C Could not extract package updates from PR body"),V.exit(1);if(J.info(`\uD83D\uDCE6 Found ${G.length} packages to update`),!$.force){J.info("\uD83D\uDD0D Checking if rebase is needed...");let E=(await new f(Q).scanForUpdates()).updates.filter((N)=>G.some((b)=>b.name===N.name));if(G.every((N)=>E.some((b)=>b.name===N.name&&b.newVersion===N.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 f({...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 q=H.groups.find((M)=>M.updates.length===G.length&&M.updates.every((L)=>G.some((E)=>E.name===L.name))&&G.every((L)=>M.updates.some((E)=>E.name===L.name)));if(!q){J.error("\u274C Could not find matching update group. This likely means the package grouping has changed."),J.info(`\uD83D\uDCCB PR packages: ${G.map((M)=>M.name).join(", ")}`),J.info(`\uD83D\uDCCB Available groups: ${H.groups.map((M)=>`${M.name} (${M.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(q.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 M=j.body||"",L=M.replace(/- \[x\] <!-- rebase-check -->/g,"- [ ] <!-- rebase-check -->");if(L!==M)await z.updatePullRequest(Y,{body:L}),J.info("\u2705 Unticked rebase checkbox to prevent the next update-check run from re-triggering this no-op rebase.");return}let F=Q.repository?.baseBranch||"main";await z.commitChanges(j.head,q.title,K,F),J.info(`\u2705 Recreated branch ${j.head} from ${F} with latest changes`);let{PullRequestGenerator:W}=await import("../chunk-xznnmhyt.js"),B=(await new W({verbose:$.verbose}).generateBody(q)).replace(/- \[x\] <!-- rebase-check -->/g,"- [ ] <!-- rebase-check -->");await z.updatePullRequest(Y,{title:q.title,body:B}),J.success("\uD83D\uDD04 PR rebase completed! Updated existing PR in place.")}catch(z){J.error("Rebase failed:",z),V.exit(1)}});async function kZ(Z){let $=Z0(Z);if($?.truncated)return[];if($)return $0($);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}w.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?O.verbose():O.quiet(),J=await S(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 m(J,"PR operations",$),z=await bZ(Q,J,$),Y=s1(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,G=0;try{let K=(await Q.getPullRequests("open")).filter((F)=>F.head.startsWith("buddy/"));$.info(`\uD83D\uDCCB Found ${K.length} buddy PRs to check for rebase requests`);for(let F of K){G++;let W=Y.rebaseAll||U.has(F.head);if(hZ(F.body||"")||W)if($.info(`\uD83D\uDD04 PR #${F.number} has rebase ${W?"requested from the dashboard":"checkbox checked"}`),Z.dryRun)$.info(`\uD83D\uDD0D [DRY RUN] Would rebase PR #${F.number}`),j++;else{$.info(`\uD83D\uDD04 Rebasing PR #${F.number} via rebase command...`);try{let{spawn:A}=await import("child_process"),B=A("bunx",["@buddysh/buddy","rebase",F.number.toString()],{stdio:"inherit",cwd:V.cwd()});await new Promise((M,L)=>{B.on("close",(E)=>{if(E===0)j++,M(E);else L(Error(`Rebase failed with code ${E}`))})}),$.success(`\u2705 Successfully rebased PR #${F.number}`)}catch(A){$.error(`\u274C Failed to rebase PR #${F.number}:`,A)}}}if(j>0)$.success(`\u2705 ${Z.dryRun?"Would rebase":"Successfully rebased"} ${j} PR(s)`);else if(G>0)$.info("\uD83D\uDCCB No PRs have rebase checkbox enabled")}catch(q){$.warn("\u26A0\uFE0F Could not check for rebase requests:",q)}if(A1(Y)&&z){if(Z.dryRun)$.info("\uD83D\uDD0D [DRY RUN] Would clear dashboard checkboxes");else try{await Q.updateIssue(z.number,{body:t1(z.body||"")}),$.success("\u2705 Cleared dashboard checkboxes")}catch(q){$.warn("\u26A0\uFE0F Could not clear dashboard checkboxes:",q)}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 q=new f(J),K=await q.scanForUpdates();if(K.updates.length>0)await q.createPullRequests(K);else $.info("\u2705 No updates found during the requested run")}catch(q){$.error("\u274C Requested update run failed:",q)}}$.info(`
|
|
142
|
-
\u2705 Checking for PRs with satisfied dependencies...`);try{let{Buddy:q}=await import("../chunk-
|
|
143
|
-
\uD83D\uDD0D Checking for obsolete PRs due to removed dependency files...`);try{let{Buddy:q}=await import("../chunk-
|
|
142
|
+
\u2705 Checking for PRs with satisfied dependencies...`);try{let{Buddy:q}=await import("../chunk-jfzqpmnp.js");await new q(J).checkAndCloseSatisfiedPRs(Q,!!Z.dryRun)}catch(q){$.error("\u26A0\uFE0F Could not check for satisfied PRs:",q)}$.info(`
|
|
143
|
+
\uD83D\uDD0D Checking for obsolete PRs due to removed dependency files...`);try{let{Buddy:q}=await import("../chunk-jfzqpmnp.js");await new q(J).checkAndCloseObsoletePRs(Q,!!Z.dryRun)}catch(q){$.error("\u26A0\uFE0F Could not check for obsolete PRs:",q)}let X=0;try{if(X=(await new f(J).mergeEligiblePullRequests(!!Z.dryRun)).length,X>0)$.success(`\uD83D\uDD00 ${Z.dryRun?"Would merge":"Merged"} ${X} PR(s)`)}catch(q){$.warn("\u26A0\uFE0F Could not process auto-merge:",q)}$.info(`
|
|
144
144
|
\uD83E\uDDF9 Running branch cleanup...`),z1(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
|
-
\uD83C\uDF89 Update-check complete: ${j} PR(s) rebased, ${X} merged, ${H.deleted.length} branches cleaned`)}catch(Q){$.error("update-check failed:",Q),await g(J.notifications,"run.failed",{command:"update-check",error:Q instanceof Error?Q.message:String(Q)}),V.exit(1)}});async function bZ(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 hZ(Z){return/\s*-\s*\[x\]\s*<!--\s*rebase-check\s*-->.*(?:rebase|update)\/retry/i.test(Z)}w.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?O.verbose():O.quiet(),J=await S(Z.config);try{let Q=await m(J,"this command",$),{runFixCi:z}=await import("../chunk-
|
|
145
|
+
\uD83C\uDF89 Update-check complete: ${j} PR(s) rebased, ${X} merged, ${H.deleted.length} branches cleaned`)}catch(Q){$.error("update-check failed:",Q),await g(J.notifications,"run.failed",{command:"update-check",error:Q instanceof Error?Q.message:String(Q)}),V.exit(1)}});async function bZ(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 hZ(Z){return/\s*-\s*\[x\]\s*<!--\s*rebase-check\s*-->.*(?:rebase|update)\/retry/i.test(Z)}w.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?O.verbose():O.quiet(),J=await S(Z.config);try{let Q=await m(J,"this command",$),{runFixCi:z}=await import("../chunk-5gejc3rx.js"),Y=await z({config:J,provider:Q,logger:$,dryRun:Boolean(Z.dryRun),...Z.runId?{runId:Number.parseInt(Z.runId,10)}:{},...Z.pr?{prNumber:Number.parseInt(Z.pr,10)}:{}});$.success(`\u2705 ${Y}`)}catch(Q){$.error("fix-ci failed:",Q),await g(J.notifications,"run.failed",{command:"fix-ci",error:Q instanceof Error?Q.message:String(Q)}),V.exit(1)}});w.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?O.verbose():O.quiet(),J=await S(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:G}=await import("../chunk-hd5j9e3c.js");if(!j(Y.body)){$.info("\u2139\uFE0F Comment does not mention buddy; nothing to do");return}let X=G(Y.body);if(!X){$.info("\u2139\uFE0F Mention is not a command (quoted or inside code); nothing to do");return}let H=await m(J,"this command",$),q=Y.user?.login??"",K=Y.user?.type==="Bot"||q.endsWith("[bot]"),F={login:q,isBot:K,canWrite:!K&&Q1(H,"permissionLookup","hasWriteAccess")?await H.hasWriteAccess(q):!1},W=Boolean(z.pull_request??z.issue?.pull_request);if($.info(`\uD83E\uDD16 Handling \`${X.name}\` from @${q} on #${U.number}`),Z.dryRun){$.info(`\uD83D\uDD0D [DRY RUN] Would run ${X.name} (canWrite: ${F.canWrite})`);return}if(Q1(H,"commentReactions","reactToComment"))await H.reactToComment(Y.id,"eyes");let{createHandlers:T,dispatchCommand:A}=await import("../chunk-hd5j9e3c.js"),{runReviewForPR:B}=await import("../chunk-4sfyfxdk.js"),M=await A({command:X,actor:F,number:U.number,isPullRequest:W,commentId:Y.id,logger:$},T({config:J,provider:H,review:async(L,E)=>await B({config:J,provider:H,prNumber:L,logger:$,...E}),rebase:async(L)=>{let{spawn:E}=await import("child_process");return await new Promise((I,N)=>{E("bunx",["@buddysh/buddy","rebase",String(L)],{stdio:"inherit"}).on("close",(k)=>k===0?I():N(Error(`rebase exited ${k}`)))}),"Rebased."},merge:async()=>await new f(J).mergeEligiblePullRequests(!1),fixCi:async(L)=>{let{runFixCi:E}=await import("../chunk-5gejc3rx.js");return await E({config:J,provider:H,prNumber:L,analysisOnly:!0,logger:$})},plan:async(L,E,I)=>{let{runPlan:N}=await import("../chunk-c3es7pgf.js");return await N({config:J,provider:H,number:L,isPullRequest:E,request:I,logger:$})},resolve:async(L)=>{let{resolveBuddyThreads:E}=await import("../chunk-9t15md0g.js");return await E({provider:H,prNumber:L,logger:$})},remember:async(L,E)=>{let{addLearning:I,createLearning:N,loadLearnings:b,serializeLearnings:k,DEFAULT_LEARNINGS_FILE:d}=await import("../chunk-hsa07n7c.js"),y=J.repository?.baseBranch??"main",P=await b((s,p)=>H.getFileContent(s,p),y,d,$),v=N(L,{source:E.isPullRequest?{pr:E.number}:{issue:E.number}}),i=`buddy/learning-${v.id}`;return await H.commitChanges(i,"chore(buddy): record a learning",[{path:d,content:k(I(P,v)),type:"update"}],y),await H.createPullRequest({title:"chore(buddy): record a learning",body:`Recorded from #${E.number}:
|
|
146
146
|
|
|
147
|
-
> ${L}`,head:i,base:y,draft:!1}),`Noted. I opened a pull request adding it to \`${d}\` so it gets reviewed like any other change.`}}));if(M.reply)await H.createComment(U.number,M.reply);if(Q1(H,"commentReactions","reactToComment"))await H.reactToComment(Y.id,M.handled?"rocket":"confused");$.success(M.handled?`\u2705 Handled \`${X.name}\``:`\u2139\uFE0F Did not run: ${M.refusal}`)}catch(Q){$.error("handle-comment failed:",Q),V.exit(1)}});w.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("--auto","Treat this as an automatic trigger, honouring the ai.review filters").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?O.verbose():O.quiet(),Q=await S($.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?O.silent():J;try{let{createAiClient:j}=await import("../chunk-hsa07n7c.js"),G=j(Q,U);if(!G&&(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,reviewDiff:H}=await import("../chunk-
|
|
147
|
+
> ${L}`,head:i,base:y,draft:!1}),`Noted. I opened a pull request adding it to \`${d}\` so it gets reviewed like any other change.`}}));if(M.reply)await H.createComment(U.number,M.reply);if(Q1(H,"commentReactions","reactToComment"))await H.reactToComment(Y.id,M.handled?"rocket":"confused");$.success(M.handled?`\u2705 Handled \`${X.name}\``:`\u2139\uFE0F Did not run: ${M.refusal}`)}catch(Q){$.error("handle-comment failed:",Q),V.exit(1)}});w.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("--auto","Treat this as an automatic trigger, honouring the ai.review filters").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?O.verbose():O.quiet(),Q=await S($.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?O.silent():J;try{let{createAiClient:j}=await import("../chunk-hsa07n7c.js"),G=j(Q,U);if(!G&&(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,reviewDiff:H}=await import("../chunk-9t15md0g.js"),{collectLocalDiff:q,formatReview:K,shouldFail:F}=await import("../chunk-emyvrx5t.js"),{runAnalyzers:W}=await import("../chunk-a4hzzn28.js");if(Z){let I=await m(Q,"reviewing a pull request",U),{reviewPullRequest:N}=await import("../chunk-4sfyfxdk.js"),{status:b,result:k}=await N({config:Q,provider:I,prNumber:Number.parseInt(Z,10),trigger:$.auto?"automatic":"requested",...$.auto?{skipIfReviewed:!0}:{},logger:U,dryRun:Boolean($.dryRun),...$.summaryOnly?{summaryOnly:!0}:{},...$.profile?{profile:$.profile}:{}});if(J.success(`\u2705 ${b}`),await g(Q.notifications,"review.completed",{number:Number.parseInt(Z,10),findings:k?.findings.length??0}),k&&z!=="pretty")V.stdout.write(K(k,z));if(k&&$.failOn&&F(k.findings,$.failOn))V.exit(1);return}let T;{let I=$.base||Q.repository?.baseBranch||"main",N=$.staged?"staged":$.branch?"branch":"working";U.info(`\uD83D\uDD0D Reviewing ${N} changes${N==="branch"?` against ${I}`:""}...`),T=await q(N,I)}if(!T.trim()){if(!Y)J.success("\u2705 No changes to review");return}let{parseUnifiedDiff:A}=await import("../chunk-428c5652.js"),B=A(T).files.map((I)=>I.path),M=Q.analysis?.enabled===!1?{findings:[],ran:[],skipped:[]}:await W({files:B,root:V.cwd(),...Q.analysis?.tools?{enabled:Q.analysis.tools}:{},logger:U});if($.light){let I={summary:`Static analysis of ${B.length} changed file(s).`,walkthrough:[],findings:M.findings,effort:1,omittedFiles:M.skipped.map((N)=>`${N.name} (${N.reason})`)};if(V.stdout.write(K(I,z)),$.fix){let N=await e1(I.findings,Boolean($.yes),J);J.success(`\uD83D\uDD27 Applied ${N} suggestion(s)`)}if($.failOn&&F(I.findings,$.failOn))V.exit(1);return}let L=await H(G,{diff:T,profile:$.profile??Q.ai?.review?.profile,summaryOnly:$.summaryOnly??Q.ai?.review?.summaryOnly,instructions:X({global:Q.ai?.review?.instructions}),pathFilters:Q.ai?.review?.pathFilters,pathInstructions:Q.ai?.review?.pathInstructions,seenFingerprints:[],logger:U}),E={...L,findings:[...M.findings,...L.findings],omittedFiles:[...L.omittedFiles,...M.skipped.map((I)=>`${I.name} (${I.reason})`)]};if(V.stdout.write(K(E,z)),$.fix){let I=await e1(E.findings,Boolean($.yes),J);J.success(`\uD83D\uDD27 Applied ${I} suggestion(s)`)}if($.failOn&&F(E.findings,$.failOn))V.exit(1)}catch(j){J.error("Review failed:",j),await g(Q.notifications,"run.failed",{command:"review",error:j instanceof Error?j.message:String(j)}),V.exit(1)}});w.command("check <packages...>","Check specific packages for updates").option("--verbose, -v","Enable verbose logging").option("--strategy <type>","Update strategy: major|minor|patch|all (default: packages.strategy from config, else all)").example("buddy check react typescript").example("buddy check react --verbose").action(async(...Z)=>{let $=Z[Z.length-1],J=Z.slice(0,-1),Q=$.verbose?O.verbose():O.quiet(),z=await S($.config);if(!J.length)Q.error("No packages specified to check"),V.exit(1);try{Q.info(`Checking specific packages: ${J.join(", ")}`);let Y={...z,verbose:$.verbose??z.verbose,packages:{...z.packages,strategy:$.strategy??z.packages?.strategy??"all"}},j=await new f(Y).checkPackages(J);if(j.length===0)Q.success("All specified packages are up to date!");else{Q.info(`Found ${j.length} updates:`);for(let G of j)Q.info(` ${G.name}: ${G.currentVersion} \u2192 ${G.newVersion} (${G.updateType})`)}}catch(Y){Q.error("Check failed:",Y),V.exit(1)}});w.command("schedule","Run automated dependency updates on schedule").option("--verbose, -v","Enable verbose logging").option("--strategy <type>","Update strategy: major|minor|patch|all (default: packages.strategy from config, else all)").example("buddy schedule").example("buddy schedule --verbose").example("buddy schedule --strategy patch").action(async(Z)=>{let{Scheduler:$}=await import("../chunk-mf959vjt.js"),J=Z.verbose?O.verbose():O.quiet(),Q=await S(Z.config);try{J.info("\uD83D\uDD52 Starting Buddy Scheduler...");let z;if(Z.ignore)z=Z.ignore.split(",").map((G)=>G.trim());let Y={...Q,verbose:Z.verbose??Q.verbose,packages:{...Q.packages,strategy:Z.strategy??Q.packages?.strategy??"all",ignore:z??Q.packages?.ignore}};if(!Y.repository?.provider||!Y.repository?.owner||!Y.repository?.name)J.error("\u274C Repository configuration required for scheduling. Please configure:"),J.info(" - repository.provider (github)"),J.info(" - repository.owner"),J.info(" - repository.name"),J.info(" - repository.token (via environment variable)"),V.exit(1);let U=new $(Z.verbose),j=$.createJobFromConfig(Y,"cli-schedule");if(Z.strategy)switch(Z.strategy){case"major":j.schedule.cron=$.PRESETS.WEEKLY;break;case"minor":j.schedule.cron=$.PRESETS.TWICE_WEEKLY;break;case"patch":j.schedule.cron=$.PRESETS.DAILY;break;default:j.schedule.cron=$.PRESETS.WEEKLY}U.addJob(j),U.start(),J.success(`\u2705 Scheduler started with cron: ${j.schedule.cron}`),J.info("\uD83D\uDCC5 Next run:",j.nextRun?.toISOString()||"Unknown"),J.info("\uD83D\uDED1 Press Ctrl+C to stop the scheduler"),V.stdin.resume()}catch(z){J.error("Scheduler failed:",z),V.exit(1)}});w.command("generate-workflows",'Generate GitHub Actions workflow templates (deprecated - use "setup" instead)').option("--verbose, -v","Enable verbose logging").example("buddy generate-workflows").example("buddy generate-workflows --verbose").action(async(Z)=>{let{GitHubActionsTemplate:$}=await import("../chunk-b357cgb0.js"),{writeFileSync:J,mkdirSync:Q}=await import("fs"),{resolve:z}=await import("path"),Y=Z.verbose?O.verbose():O.quiet(),U=await S(Z.config);if(U.workflows?.enabled===!1){Y.info("\u2139\uFE0F Workflow generation is disabled by config (workflows.enabled: false)");return}console.log('\u26A0\uFE0F The "generate-workflows" command is deprecated.'),console.log(`\uD83D\uDCA1 Use "buddy setup" for a better interactive experience.
|
|
148
148
|
`);try{let j={...U,verbose:Z.verbose??U.verbose},G=j.workflows?.outputDir?z(V.cwd(),j.workflows.outputDir):z(V.cwd(),".github","workflows");Y.info("\uD83D\uDE80 Generating GitHub Actions workflow templates...");try{Q(G,{recursive:!0})}catch{}let X=j.workflows?.templates||{comprehensive:!0,daily:!0,weekly:!0,monthly:!0,docker:!0,monorepo:!0},H=0;if(X.daily||X.weekly||X.monthly){let q=$.generateScheduledWorkflows(j);for(let[K,F]of Object.entries(q))if(K.includes("daily")&&X.daily||K.includes("weekly")&&X.weekly||K.includes("monthly")&&X.monthly){let T=z(G,K);J(T,F),Y.success(`Generated: ${K}`),H++}}if(X.comprehensive){let q=$.generateComprehensiveWorkflow(j);J(z(G,"buddy-comprehensive.yml"),q),Y.success("Generated: buddy-comprehensive.yml"),H++}if(X.docker){let q=$.generateDockerWorkflow(j);J(z(G,"buddy-docker.yml"),q),Y.success("Generated: buddy-docker.yml"),H++}if(X.monorepo){let q=$.generateMonorepoWorkflow(j);J(z(G,"buddy-monorepo.yml"),q),Y.success("Generated: buddy-monorepo.yml"),H++}if(j.workflows?.custom?.length)for(let q of j.workflows.custom){let K=$.generateCustomWorkflow(q,j),F=`buddy-${q.name.toLowerCase().replace(/\s+/g,"-")}.yml`;J(z(G,F),K),Y.success(`Generated: ${F}`),H++}if(H===0){Y.warn("No workflows were generated. Check your configuration in buddy.config.ts"),Y.info("Set workflows.templates to enable specific templates or add custom workflows.");return}Y.success(`
|
|
149
149
|
\uD83C\uDF89 ${H} GitHub Actions workflow(s) generated!`),Y.info(`\uD83D\uDCC1 Location: ${G}`),Y.info(`
|
|
150
150
|
\uD83D\uDCA1 Next steps:`),Y.info(" 1. Review and customize the workflows for your project"),Y.info(" 2. Ensure GITHUB_TOKEN is available as a secret"),Y.info(" 3. Configure buddy.config.ts with your repository settings"),Y.info(" 4. Enable GitHub Actions in your repository settings"),Y.info(`
|
|
@@ -171,7 +171,7 @@ For manual setup, visit:`),$.info("\uD83D\uDD17 Repository settings: https://git
|
|
|
171
171
|
|
|
172
172
|
Call \`read_issue\` to see what was asked for.`,tools:[...B,M(z,Q,!1)],context:{workspace:V.cwd(),baseBranch:J.repository?.baseBranch??"main"},logger:$});await z.createComment(Q,N.output||`I could not finish that (${N.stopReason}).`),$.success(`\u2705 Ran ${A}`)}return}if(U.body.includes(X)){$.debug("Quick-links already posted on this issue");return}let K=J.issues?.dependencyContext?await SZ(J,$):[],F=H({body:U.body,packages:K});if(Z.dryRun){$.info(F);return}await z.createComment(Q,F),$.success(`\u2705 Posted quick-links on #${Q}`)}catch(Q){$.error("handle-issue failed:",Q),V.exit(1)}});w.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?O.verbose():O.quiet(),Q=await S($.config);try{let z=Number.parseInt(Z,10);if(Number.isNaN(z))J.error("\u274C Invalid PR number"),V.exit(1);let Y=await m(Q,"running gates",J),{findLinkedIssues:U,runAiGates:j,runGates:G,gateIcon:X,summarizeGates:H}=await import("../chunk-hmskwy76.js"),{parseManifest:q}=await import("../chunk-ppmabn5h.js"),F=(await Y.getPullRequests("open")).find((P)=>P.number===z);if(!F)J.error(`\u274C Pull request #${z} is not open`),V.exit(1);let W=Q.gates??{},T=q(F.body),{manifestUpdates:A}=await import("../chunk-ppmabn5h.js"),B=T?await Promise.all(A(T).map(async(P)=>{let v={name:P.name,version:P.newVersion};if(W.dependencyGate?.blockEol===!1)return v;if(T.updates.find((S1)=>S1.name===P.name)?.dependencyType!=="docker-image")return v;let{checkEol:s,describeEol:p}=await import("../chunk-ds4stft2.js"),Y1=await s(P.name,P.newVersion,{logger:J}),t=p(Y1);return Y1?.eol&&t?{...v,eol:t}:v})):[],M=G({title:F.title,body:F.body,manifest:T,dependencies:B},{...W.titleFormat?{titleFormat:W.titleFormat}:{},...W.description?{description:W.description}:{},...W.dependencyGate?{dependencyGate:W.dependencyGate}:{}}),L=U(F.body??""),E=L.length>0?await Y.getIssues("all"):[],I=L.map((P)=>E.find((v)=>v.number===P)).filter((P)=>Boolean(P)).map((P)=>({number:P.number,title:P.title,body:P.body})),{createAiClient:N}=await import("../chunk-hsa07n7c.js"),b=await j(N(Q,J),{title:F.title,body:F.body,diff:await Y.getPullRequestDiff(z),linkedIssues:I},{...W.linkedIssue?{linkedIssue:W.linkedIssue}:{},...W.custom?{custom:W.custom}:{}},J),k=[...M,...b],d=H(k);for(let P of k)J.info(`${X(P)} ${P.name}: ${P.summary}`);let y=d.conclusion==="failure";if(y)await g(Q.notifications,"gate.failed",{number:z,checks:k.filter((P)=>!P.passed).map((P)=>P.name)});if($.dryRun||!Q1(Y,"checkRuns","createCheckRun")){if(J.info(d.summary),y)V.exit(1);return}if(await Y.createCheckRun("buddy/gates",await Y.getPullRequestHeadSha(z),d),y)V.exit(1)}catch(z){J.error("Gate run failed:",z),V.exit(1)}});w.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?O.verbose():O.quiet(),Q=await S($.config);try{let z=Number.parseInt(Z,10),Y=await m(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:G}=await import("../chunk-hmskwy76.js"),X=await G(Y,j,Q.gates?.postMerge??{},{baseBranch:Q.repository?.baseBranch??j.base,logger:J,refreshDashboard:async()=>{if(Q.dashboard?.enabled===!1)throw Error("dashboard.enabled is false");await new f(Q).createOrUpdateDashboard()}});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)}});w.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("--scheduled","This is the workflow's scheduled run; honour reports.enabled").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?O.verbose():$?O.silent():O.quiet(),Q=await S(Z.config);try{let{appendHistory:z,computeDeltas:Y,computeMetrics:U,findPrevious:j,HISTORY_PATH:G,loadHistory:X,REPORT_MARKER:H,REPORT_PERIODS:q,renderReport:K,withNarrative:F}=await import("../chunk-zgkrhymn.js"),W=Z.period??Q.reports?.period??"30d";if(!q.includes(W))J.error(`\u274C Unknown period '${W}'. Expected one of ${q.join(", ")}.`),V.exit(1);let T=await m(Q,"reporting",J),A=new f(Q,V.cwd()),{PackageScanner:B}=await import("../chunk-fpnjpgrb.js"),M=new B(V.cwd(),J,Q.packages?.ignorePaths),[L,E,I]=await Promise.all([A.scanForUpdates(),T.getPullRequests("all"),M.scanProject()]),{ecosystemOf:N}=await import("../chunk-49znmbh8.js"),b={};for(let X1 of I)for(let j1 of X1.dependencies){let y1=N({name:j1.name,currentVersion:j1.currentVersion,newVersion:j1.currentVersion,updateType:"patch",dependencyType:j1.type,file:X1.path});b[y1]=(b[y1]??0)+1}let{DeprecatedDependenciesChecker:k}=await import("../chunk-vj1sdxpp.js"),d=await new k().checkDeprecatedDependencies(I).catch(()=>[]),y=U({period:W,now:new Date,pullRequests:E,updates:L.updates,dependenciesByEcosystem:b,deprecated:d.length}),P=Q.repository?.baseBranch||"main",v=await X(T,P,J),i=Y(y,j(v,W));if(Z.format==="json"){V.stdout.write(`${JSON.stringify({metrics:y,deltas:i},null,2)}
|
|
173
173
|
`);return}let{createAiClient:s}=await import("../chunk-hsa07n7c.js"),p=await F(K(y,i),y,s(Q,J),Z.prompt??Q.reports?.prompt,J),{shouldPublishReport:Y1}=await import("../chunk-zgkrhymn.js"),t=Y1({scheduled:Boolean(Z.scheduled),enabled:Q.reports?.enabled});if(Z.publish&&!t.publish){J.info(`\u2139\uFE0F Not publishing: ${t.reason}`);return}if(!Z.publish){V.stdout.write(`${p}
|
|
174
|
-
`);return}let k1=(await T.getIssues("open")).find((X1)=>X1.body.includes(H)),b1=Q.reports?.title??"Dependency Report",h1=Q.reports?.labels??["dependencies","report"],T0=k1?await T.updateIssue(k1.number,{title:b1,body:p,labels:h1}):await T.createIssue({title:b1,body:p,labels:h1});J.success(`\u2705 Report published: ${T0.url}`),await T.commitChanges(P,"chore(reports): record dependency metrics snapshot",[{path:G,content:z(v,y),type:v.length>0?"update":"create"}],P)}catch(z){J.error("Report failed:",z),V.exit(1)}});w.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?O.verbose():O.quiet(),J=await S(Z.config).catch((U)=>{return $.warn(`\u26A0\uFE0F Could not load configuration: ${r(U)}`),{}}),{diagnose:Q,renderDoctorReport:z}=await import("../chunk-
|
|
174
|
+
`);return}let k1=(await T.getIssues("open")).find((X1)=>X1.body.includes(H)),b1=Q.reports?.title??"Dependency Report",h1=Q.reports?.labels??["dependencies","report"],T0=k1?await T.updateIssue(k1.number,{title:b1,body:p,labels:h1}):await T.createIssue({title:b1,body:p,labels:h1});J.success(`\u2705 Report published: ${T0.url}`),await T.commitChanges(P,"chore(reports): record dependency metrics snapshot",[{path:G,content:z(v,y),type:v.length>0?"update":"create"}],P)}catch(z){J.error("Report failed:",z),V.exit(1)}});w.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?O.verbose():O.quiet(),J=await S(Z.config).catch((U)=>{return $.warn(`\u26A0\uFE0F Could not load configuration: ${r(U)}`),{}}),{diagnose:Q,renderDoctorReport:z}=await import("../chunk-baq6x78h.js"),Y=await Q(J);if(V.stdout.write(z(Y)),!Y.healthy)V.exit(1)});w.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?O.verbose():O.silent(),J=await S(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
|
|
175
175
|
`),V.exit(1);let z=Z.outputSchemaFile?await Bun.file(Z.outputSchemaFile).text():Z.outputSchema,Y;if(z)try{Y=JSON.parse(z)}catch(F){V.stderr.write(`\u274C --output-schema is not valid JSON: ${r(F)}
|
|
176
176
|
`),V.exit(1)}let{createAiClient:U}=await import("../chunk-hsa07n7c.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
|
|
177
177
|
`),V.exit(1);let{publishOutput:G,runHeadless:X}=await import("../chunk-gkpd5nw2.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):
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{$c as u0}from"./chunk-phfmnnne.js";import{bd as w0,cd as T0,dd as F0,ed as l0}from"./chunk-r763e19p.js";import{fd as c0}from"./chunk-be629jhq.js";import{ld as z0,md as j0,nd as y0}from"./chunk-11hdrnf6.js";import{qd as f0,td as g0}from"./chunk-mkzmjg3f.js";import{ke as e,le as d}from"./chunk-
|
|
2
|
+
import{$c as u0}from"./chunk-phfmnnne.js";import{bd as w0,cd as T0,dd as F0,ed as l0}from"./chunk-r763e19p.js";import{fd as c0}from"./chunk-be629jhq.js";import{ld as z0,md as j0,nd as y0}from"./chunk-11hdrnf6.js";import{qd as f0,td as g0}from"./chunk-mkzmjg3f.js";import{ke as e,le as d}from"./chunk-tzwnfagh.js";import{if as m0}from"./chunk-8hjvthz4.js";import{lf as l,mf as P0,nf as O0,of as h0,pf as o}from"./chunk-yngahb11.js";import{$f as _0,ag as k0,bg as c}from"./chunk-0hc97k0t.js";import{kg as g,og as b0,pg as v0}from"./chunk-3901s7h9.js";import{ph as H0}from"./chunk-193abzy6.js";import{zh as K0}from"./chunk-e68nf7cm.js";import{Bh as x0,Ch as Z0,Dh as U0,Eh as R0}from"./chunk-hfjywbbc.js";import{Wk as D}from"./chunk-q4t568hv.js";import N0 from"fs";import{join as a}from"path";import y from"process";var d0={critical:"\uD83D\uDD34 Critical",high:"\uD83D\uDFE0 High",moderate:"\uD83D\uDFE1 Moderate",low:"\u26AA Low"};class Q0{generateDashboard($,X={}){let{showOpenPRs:Q=!0,showDetectedDependencies:K=!0,showDeprecatedDependencies:H=!0,showVulnerableDependencies:Z=!0,includePackageJson:W=!0,includeDependencyFiles:O=!0,includeGitHubActions:z=!0,bodyTemplate:L}=X,_="Dependency Dashboard";if(L)return{title:"Dependency Dashboard",body:this.applyTemplate(L,$)};let Y=this.generateDefaultHeader($);if(Z&&$.vulnerableDependencies&&$.vulnerableDependencies.length>0)Y+=this.generateVulnerableDependenciesSection($.vulnerableDependencies);if(H&&$.deprecatedDependencies&&$.deprecatedDependencies.length>0)Y+=this.generateDeprecatedDependenciesSection($.deprecatedDependencies);if(Q&&$.openPRs.length>0)Y+=this.generateOpenPRsSection($.openPRs);if($.cappedDependencies&&$.cappedDependencies.length>0)Y+=this.generateCappedDependenciesSection($.cappedDependencies);if(K)Y+=this.generateDetectedDependenciesSection({packageJson:W?$.detectedDependencies.packageJson:[],dependencyFiles:O?$.detectedDependencies.dependencyFiles:[],githubActions:z?$.detectedDependencies.githubActions:[]});return Y+=this.generateFooter(),{title:"Dependency Dashboard",body:Y}}generateDefaultHeader($){return`This issue lists Buddy updates and detected dependencies. Read the [Dependency Dashboard](https://buddy.sh/features/dependency-dashboard) docs to learn more.
|
|
3
3
|
|
|
4
4
|
`}sanitizeReferences($){return $.replace(/(?<![`\w])#(\d+)(?!\d)/g,"`#$1`")}toRelativePrUrl($,X){try{let Q=new URL($);if(Q.hostname!=="github.com")return null;let K=Q.pathname.match(/^\/[^/]+\/[^/]+\/pull\/(\d+)$/);if(!K||Number(K[1])!==X)return null;return`../pull/${X}`}catch{return null}}generateCappedDependenciesSection($){let X=`## Capped dependencies
|
|
5
5
|
|
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{Cb as a,Db as b}from"./chunk-
|
|
2
|
+
import{Cb as a,Db as b}from"./chunk-5x4gt4c5.js";import"./chunk-q2tjkhez.js";import"./chunk-5yfaptmp.js";import"./chunk-rc2mk5x6.js";import"./chunk-tjc2vgwn.js";import"./chunk-nrr8z2z7.js";import"./chunk-xs12dtf1.js";import"./chunk-tzwnfagh.js";import"./chunk-1cpdz49v.js";import"./chunk-cgvt98pd.js";import"./chunk-e68nf7cm.js";import"./chunk-hfjywbbc.js";import"./chunk-q4t568hv.js";export{b as runReviewForPR,a as reviewPullRequest};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{Kc as a,Lc as b,Mc as c,Nc as d}from"./chunk-
|
|
2
|
+
import{Kc as a,Lc as b,Mc as c,Nc as d}from"./chunk-8ycrg9gp.js";import"./chunk-0hc97k0t.js";import"./chunk-3901s7h9.js";import"./chunk-jtxcr5yw.js";import"./chunk-qd2s51gc.js";import"./chunk-193abzy6.js";import"./chunk-e68nf7cm.js";import"./chunk-hfjywbbc.js";import"./chunk-g24hav8e.js";import"./chunk-q4t568hv.js";export{b as regenerateLockFile,d as hasLockFile,a as getAllLockFilePaths,c as detectRequiredPackageManagers};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{Ea as a,Fa as b,Ga as c,Ha as d,Ia as e,Ja as f,Ka as g}from"./chunk-
|
|
2
|
+
import{Ea as a,Fa as b,Ga as c,Ha as d,Ia as e,Ja as f,Ka as g}from"./chunk-rz7pg7pb.js";import"./chunk-cwfkm7h9.js";import"./chunk-mkzmjg3f.js";import"./chunk-tzwnfagh.js";import"./chunk-08x5b93v.js";import"./chunk-p6qbqsyp.js";import"./chunk-cgvt98pd.js";import"./chunk-c8rzx3a1.js";import"./chunk-e68nf7cm.js";import"./chunk-hfjywbbc.js";import"./chunk-q4t568hv.js";export{g as runFixCi,e as latestFailurePerWorkflow,d as failsOnBaseBranch,b as extractErrorLines,c as describeFailure,a as classifyFailure,f as attemptFix};
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{Eb as _,Fb as y}from"./chunk-q2tjkhez.js";import{Mb as g,Nb as r,Ob as e,Pb as jj}from"./chunk-5yfaptmp.js";import{Wb as n,Xb as o,Yb as t}from"./chunk-rc2mk5x6.js";import{fc as s}from"./chunk-tjc2vgwn.js";import{$d as i}from"./chunk-nrr8z2z7.js";import{me as S}from"./chunk-
|
|
2
|
+
import{Eb as _,Fb as y}from"./chunk-q2tjkhez.js";import{Mb as g,Nb as r,Ob as e,Pb as jj}from"./chunk-5yfaptmp.js";import{Wb as n,Xb as o,Yb as t}from"./chunk-rc2mk5x6.js";import{fc as s}from"./chunk-tjc2vgwn.js";import{$d as i}from"./chunk-nrr8z2z7.js";import{me as S}from"./chunk-tzwnfagh.js";import{Jf as b,Kf as m}from"./chunk-1cpdz49v.js";import{Fh as Y}from"./chunk-hfjywbbc.js";var C=["critical","major","minor","nit"],w={type:"object",properties:{summary:{type:"string",description:"One paragraph on what this change does"},effort:{type:"integer",description:"Reviewer effort, 1 (trivial) to 5 (demanding)"},walkthrough:{type:"array",items:{type:"object",properties:{path:{type:"string"},description:{type:"string"}},required:["path","description"],additionalProperties:!1}},findings:{type:"array",items:{type:"object",properties:{path:{type:"string",description:"Repository-relative path"},line:{type:"integer",description:"Line number on the new side of the diff"},severity:{type:"string",enum:C},category:{type:"string",description:"Short slug, e.g. correctness or security"},message:{type:"string",description:"What is wrong and why it matters"},suggestion:{type:"string",description:"Replacement code, only when the fix is mechanical"}},required:["path","line","severity","category","message"],additionalProperties:!1}}},required:["summary","effort","walkthrough","findings"],additionalProperties:!1};function I(J){let j=J.message.toLowerCase().replace(/\s+/g," ").trim().slice(0,120);return`${J.path}:${J.category}:${j}`}function N(J,j){let Q=[],Z=[];for(let $ of J)if(j.get($.path)?.has($.line))Q.push($);else Z.push($);return Q.sort(($,X)=>C.indexOf($.severity)-C.indexOf(X.severity)),{valid:Q,dropped:Z}}function v(J,j){let Q=[],Z=new Set;for(let $ of J){let X=I($);if(j.has(X)||Z.has(X))continue;Z.add(X),Q.push($)}return Q}var Jj=[/(?:^|\/)(?:bun\.lockb?|package-lock\.json|yarn\.lock|pnpm-lock\.yaml|composer\.lock|pantry\.lock)$/,/(?:^|\/)(?:dist|build|out|coverage|node_modules|vendor)\//,/\.min\.(?:js|css)$/,/(?:^|\/)(?:.*\.snap)$/],Qj=`You are reviewing a pull request diff.
|
|
3
3
|
|
|
4
4
|
Report only defects you can point at in the diff. A review that invents
|
|
5
5
|
findings to look thorough is worse than one that reports nothing, so say
|
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{Jc as a}from"./chunk-
|
|
2
|
+
import{Jc as a}from"./chunk-j9cgwkm8.js";import"./chunk-8ycrg9gp.js";import"./chunk-c8rzx3a1.js";import"./chunk-0hc97k0t.js";import"./chunk-3901s7h9.js";import"./chunk-jtxcr5yw.js";import"./chunk-qd2s51gc.js";import"./chunk-193abzy6.js";import"./chunk-e68nf7cm.js";import"./chunk-hfjywbbc.js";import"./chunk-g24hav8e.js";import"./chunk-q4t568hv.js";export{a as GitHubProvider};
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{Uc as oX}from"./chunk-cs066zt9.js";import{Zc as sX}from"./chunk-e2t5jq26.js";import{Fh as iX}from"./chunk-hfjywbbc.js";import{Wk as n}from"./chunk-q4t568hv.js";import{resolve as b8}from"path";import y8 from"process";import{existsSync as aX,statSync as eX}from"fs";import{resolve as wQ}from"path";import SZ from"process";import{existsSync as TZ,mkdirSync as m8,readdirSync as u8,readFileSync as OZ,writeFileSync as g8}from"fs";import{homedir as ZQ}from"os";import{dirname as n8,resolve as l}from"path";import QX from"process";import{existsSync as QY,statSync as XY}from"fs";import{existsSync as SX,mkdirSync as NZ,readdirSync as CZ,writeFileSync as xZ}from"fs";import{homedir as $Q}from"os";import{dirname as YY,resolve as y}from"path";import YQ from"process";import{join as kZ,relative as PZ,resolve as ZY}from"path";import mQ from"process";import{existsSync as gY,mkdirSync as Y9,readdirSync as Z9,writeFileSync as $9}from"fs";import{homedir as HX}from"os";import{dirname as J9,resolve as b}from"path";import KQ from"process";import{join as bZ,relative as yZ,resolve as $Y}from"path";import uQ from"process";import{existsSync as cY,mkdirSync as W9,readdirSync as z9,writeFileSync as B9}from"fs";import{dirname as w9,resolve as gQ}from"path";import VX from"process";import{Buffer as e}from"buffer";import{createCipheriv as vZ,createDecipheriv as hZ,randomBytes as UX}from"crypto";import{closeSync as JX,createReadStream as HY,createWriteStream as dZ,existsSync as GX,fsyncSync as UY,openSync as JY,writeFileSync as fZ}from"fs";import{access as pZ,constants as GY,mkdir as mZ,readdir as MQ,rename as _Y,stat as HQ,unlink as DQ,writeFile as _X}from"fs/promises";import{join as UQ}from"path";import x from"process";import{pipeline as uZ}from"stream/promises";import{createGzip as qY}from"zlib";import JQ from"process";import o from"process";import{Buffer as i}from"buffer";import{createCipheriv as gZ,createDecipheriv as cZ,randomBytes as qX}from"crypto";import{closeSync as AX,createReadStream as AY,createWriteStream as lZ,existsSync as SQ,fsyncSync as WY,openSync as zY,writeFileSync as nZ}from"fs";import{access as iZ,constants as BY,mkdir as sZ,readdir as VQ,rename as RY,stat as GQ,unlink as EQ,writeFile as WX}from"fs/promises";import{isAbsolute as oZ,join as _Q,resolve as rZ}from"path";import w from"process";import{pipeline as tZ}from"stream/promises";import{createGzip as wY}from"zlib";import qQ from"process";import r from"process";import TQ from"process";import{existsSync as OQ}from"fs";import{resolve as zX}from"path";import{existsSync as aZ}from"fs";import{existsSync as eZ,readdirSync as Q0}from"fs";import{extname as BX,resolve as LY}from"path";import X0 from"process";import{join as Y0,relative as Z0,resolve as KY}from"path";import cQ from"process";import{Buffer as s}from"buffer";import{createCipheriv as $0,createDecipheriv as H0,randomBytes as RX}from"crypto";import{closeSync as wX,createReadStream as jY,createWriteStream as U0,existsSync as NQ,fsyncSync as IY,openSync as FY,writeFileSync as J0}from"fs";import{access as G0,constants as MY,mkdir as _0,readdir as CQ,rename as DY,stat as AQ,unlink as xQ,writeFile as LX}from"fs/promises";import{isAbsolute as q0,join as WQ,resolve as A0}from"path";import L from"process";import{pipeline as W0}from"stream/promises";import{createGzip as SY}from"zlib";import zQ from"process";import t from"process";import PQ from"process";import{existsSync as bQ}from"fs";import{resolve as dY}from"path";import{existsSync as x8}from"fs";class fY{cache=new Map;totalHits=0;totalMisses=0;options;constructor(Q={}){this.options={enabled:!0,ttl:300000,maxSize:100,keyPrefix:"bunfig:",...Q}}generateKey(Q,X){let Y=X?`:${X}`:"";return`${this.options.keyPrefix}${Q}${Y}`}isExpired(Q){return Date.now()-Q.timestamp.getTime()>Q.ttl}estimateSize(Q){try{return JSON.stringify(Q).length}catch{return 1000}}evictIfNeeded(){if(this.cache.size<=this.options.maxSize)return;let Q=Array.from(this.cache.entries()).sort(([,Y],[,Z])=>Y.timestamp.getTime()-Z.timestamp.getTime()),X=Q.length-this.options.maxSize+1;for(let Y=0;Y<X;Y++)this.cache.delete(Q[Y][0])}set(Q,X,Y,Z){if(!this.options.enabled)return;let $=this.generateKey(Q,Y),H=Z??this.options.ttl,U=this.estimateSize(X);this.cache.set($,{value:X,timestamp:new Date,ttl:H,hits:0,size:U}),this.evictIfNeeded()}get(Q,X){if(!this.options.enabled){this.totalMisses++;return}let Y=this.generateKey(Q,X),Z=this.cache.get(Y);if(!Z){this.totalMisses++;return}if(this.isExpired(Z)){this.cache.delete(Y),this.totalMisses++;return}return Z.hits++,this.totalHits++,Z.value}isFileModified(Q,X){try{if(!aX(Q))return!0;return eX(Q).mtime>X}catch{return!0}}getWithFileCheck(Q,X){let Y=this.get(Q,X);if(!Y)return;if(this.isFileModified(X,Y.fileTimestamp)){this.delete(Q,X);return}return Y.value}setWithFileCheck(Q,X,Y,Z){try{let $=aX(Y)?eX(Y):null,H=$?$.mtime:new Date;this.set(Q,{value:X,fileTimestamp:H},Y,Z)}catch{this.set(Q,X,Y,Z)}}delete(Q,X){let Y=this.generateKey(Q,X);return this.cache.delete(Y)}clear(){this.cache.clear(),this.totalHits=0,this.totalMisses=0}cleanup(){let Q=0;for(let[X,Y]of this.cache.entries())if(this.isExpired(Y))this.cache.delete(X),Q++;return Q}getStats(){let Q=Array.from(this.cache.values()),X=Q.reduce((Z,$)=>Z+$.size,0),Y=Q.map((Z)=>Z.timestamp).sort();return{size:X,maxSize:this.options.maxSize,hitRate:this.totalHits+this.totalMisses>0?this.totalHits/(this.totalHits+this.totalMisses):0,totalHits:this.totalHits,totalMisses:this.totalMisses,entries:this.cache.size,oldestEntry:Y[0],newestEntry:Y[Y.length-1]}}export(){let Q={};for(let[X,Y]of this.cache.entries())Q[X]={value:Y.value,timestamp:Y.timestamp.toISOString(),ttl:Y.ttl,hits:Y.hits,size:Y.size};return Q}import(Q){this.cache.clear();for(let[X,Y]of Object.entries(Q))if(typeof Y==="object"&&Y!==null){let Z=Y;this.cache.set(X,{value:Z.value,timestamp:new Date(Z.timestamp),ttl:Z.ttl,hits:Z.hits,size:Z.size})}}}class pY{metrics=[];maxMetrics=1000;async track(Q,X,Y={}){let Z=performance.now(),$=new Date;try{let H=await X(),U=performance.now()-Z;return this.recordMetric({operation:Q,duration:U,timestamp:$,...Y}),H}catch(H){let U=performance.now()-Z;throw this.recordMetric({operation:`${Q}:error`,duration:U,timestamp:$,...Y}),H}}recordMetric(Q){if(this.metrics.push(Q),this.metrics.length>this.maxMetrics)this.metrics=this.metrics.slice(-this.maxMetrics)}getStats(Q){let X=Q?this.metrics.filter(($)=>$.operation===Q):this.metrics;if(X.length===0)return{count:0,averageDuration:0,minDuration:0,maxDuration:0,totalDuration:0,recentMetrics:[]};let Y=X.map(($)=>$.duration),Z=Y.reduce(($,H)=>$+H,0);return{count:X.length,averageDuration:Z/X.length,minDuration:Math.min(...Y),maxDuration:Math.max(...Y),totalDuration:Z,recentMetrics:X.slice(-10)}}getAllMetrics(){return[...this.metrics]}clearMetrics(){this.metrics=[]}getSlowOperations(Q){return this.metrics.filter((X)=>X.duration>Q)}}var pQ=new fY,vX=new pY;var mY=[".ts",".js",".mjs",".cjs",".json",".mts",".cts"];function uY(Q={}){let{name:X="",alias:Y}=Q,Z=["config",".config"];if(X)Z.push(X,`.${X}.config`,`${X}.config`,`.${X}`);let $=Y===void 0?[]:Array.isArray(Y)?Y:[Y];for(let H of $){if(!H)continue;if(Z.push(H,`.${H}.config`,`${H}.config`,`.${H}`),X)Z.push(`${X}.${H}.config`,`.${X}.${H}.config`)}return Array.from(new Set(Z.filter(Boolean)))}function VZ(Q){return uY(Q).flatMap((Y)=>mY.map((Z)=>wQ(Q.directory,`${Y}${Z}`)))}function EZ(Q={}){let X=wQ(Q.cwd||SZ.cwd());return Array.from(new Set([X,wQ(X,"config"),wQ(X,".config"),Q.configDir?wQ(X,Q.configDir):void 0].filter((Y)=>Boolean(Y))))}var z0=Object.defineProperty,B0=(Q)=>Q;function R0(Q,X){this[Q]=B0.bind(null,X)}var w0=(Q,X)=>{for(var Y in X)z0(Q,Y,{get:X[Y],enumerable:!0,configurable:!0,set:R0.bind(X,Y)})},L0=(Q,X)=>()=>(Q&&(X=Q(Q=0)),X),lY={};w0(lY,{withErrorRecovery:()=>sY,tryLoadConfig:()=>p0,loadConfigWithResult:()=>d0,loadConfig:()=>eY,isRetryableError:()=>k0,isConfigNotFoundError:()=>x0,isBunfigError:()=>oY,globalPerformanceMonitor:()=>FQ,globalCache:()=>BQ,getEnvOrDefault:()=>P0,generateConfigTypes:()=>m0,defaultGeneratedDir:()=>JZ,defaultConfigDir:()=>UZ,deepMergeWithArrayStrategy:()=>mX,deepMerge:()=>rY,createLibraryConfig:()=>u0,config:()=>f0,bunfigPlugin:()=>g0,applyEnvVarsToConfig:()=>LQ,TypeGenerationError:()=>kX,SchemaValidationError:()=>IQ,PluginError:()=>bX,PerformanceMonitor:()=>dX,FileSystemError:()=>xX,ErrorFactory:()=>QQ,EnvVarError:()=>rQ,EnvProcessor:()=>XX,ConfigValidator:()=>uX,ConfigValidationError:()=>NX,ConfigNotFoundError:()=>oQ,ConfigMergeError:()=>CX,ConfigLoader:()=>gX,ConfigLoadError:()=>jQ,ConfigFileLoader:()=>YX,ConfigCache:()=>hX,CacheUtils:()=>XZ,BunfigError:()=>h,BrowserConfigError:()=>PX,ArrayMergeStrategies:()=>$Z});class hX{cache=new Map;totalHits=0;totalMisses=0;options;constructor(Q={}){this.options={enabled:!0,ttl:300000,maxSize:100,keyPrefix:"bunfig:",...Q}}generateKey(Q,X){let Y=X?`:${X}`:"";return`${this.options.keyPrefix}${Q}${Y}`}isExpired(Q){return Date.now()-Q.timestamp.getTime()>Q.ttl}estimateSize(Q){try{return JSON.stringify(Q).length}catch{return 1000}}evictIfNeeded(){if(this.cache.size<=this.options.maxSize)return;let Q=Array.from(this.cache.entries()).sort(([,Y],[,Z])=>Y.timestamp.getTime()-Z.timestamp.getTime()),X=Q.length-this.options.maxSize+1;for(let Y=0;Y<X;Y++)this.cache.delete(Q[Y][0])}set(Q,X,Y,Z){if(!this.options.enabled)return;let $=this.generateKey(Q,Y),H=Z??this.options.ttl,U=this.estimateSize(X);this.cache.set($,{value:X,timestamp:new Date,ttl:H,hits:0,size:U}),this.evictIfNeeded()}get(Q,X){if(!this.options.enabled){this.totalMisses++;return}let Y=this.generateKey(Q,X),Z=this.cache.get(Y);if(!Z){this.totalMisses++;return}if(this.isExpired(Z)){this.cache.delete(Y),this.totalMisses++;return}return Z.hits++,this.totalHits++,Z.value}isFileModified(Q,X){try{if(!QY(Q))return!0;return XY(Q).mtime>X}catch{return!0}}getWithFileCheck(Q,X){let Y=this.get(Q,X);if(!Y)return;if(this.isFileModified(X,Y.fileTimestamp)){this.delete(Q,X);return}return Y.value}setWithFileCheck(Q,X,Y,Z){try{let $=QY(Y)?XY(Y):null,H=$?$.mtime:new Date;this.set(Q,{value:X,fileTimestamp:H},Y,Z)}catch{this.set(Q,X,Y,Z)}}delete(Q,X){let Y=this.generateKey(Q,X);return this.cache.delete(Y)}clear(){this.cache.clear(),this.totalHits=0,this.totalMisses=0}cleanup(){let Q=0;for(let[X,Y]of this.cache.entries())if(this.isExpired(Y))this.cache.delete(X),Q++;return Q}getStats(){let Q=Array.from(this.cache.values()),X=Q.reduce((Z,$)=>Z+$.size,0),Y=Q.map((Z)=>Z.timestamp).sort();return{size:X,maxSize:this.options.maxSize,hitRate:this.totalHits+this.totalMisses>0?this.totalHits/(this.totalHits+this.totalMisses):0,totalHits:this.totalHits,totalMisses:this.totalMisses,entries:this.cache.size,oldestEntry:Y[0],newestEntry:Y[Y.length-1]}}export(){let Q={};for(let[X,Y]of this.cache.entries())Q[X]={value:Y.value,timestamp:Y.timestamp.toISOString(),ttl:Y.ttl,hits:Y.hits,size:Y.size};return Q}import(Q){this.cache.clear();for(let[X,Y]of Object.entries(Q))if(typeof Y==="object"&&Y!==null){let Z=Y;this.cache.set(X,{value:Z.value,timestamp:new Date(Z.timestamp),ttl:Z.ttl,hits:Z.hits,size:Z.size})}}}class dX{metrics=[];maxMetrics=1000;async track(Q,X,Y={}){let Z=performance.now(),$=new Date;try{let H=await X(),U=performance.now()-Z;return this.recordMetric({operation:Q,duration:U,timestamp:$,...Y}),H}catch(H){let U=performance.now()-Z;throw this.recordMetric({operation:`${Q}:error`,duration:U,timestamp:$,...Y}),H}}recordMetric(Q){if(this.metrics.push(Q),this.metrics.length>this.maxMetrics)this.metrics=this.metrics.slice(-this.maxMetrics)}getStats(Q){let X=Q?this.metrics.filter(($)=>$.operation===Q):this.metrics;if(X.length===0)return{count:0,averageDuration:0,minDuration:0,maxDuration:0,totalDuration:0,recentMetrics:[]};let Y=X.map(($)=>$.duration),Z=Y.reduce(($,H)=>$+H,0);return{count:X.length,averageDuration:Z/X.length,minDuration:Math.min(...Y),maxDuration:Math.max(...Y),totalDuration:Z,recentMetrics:X.slice(-10)}}getAllMetrics(){return[...this.metrics]}clearMetrics(){this.metrics=[]}getSlowOperations(Q){return this.metrics.filter((X)=>X.duration>Q)}}function K0(Q,X={}){let Z=Object.keys(X).sort().map(($)=>`${$}:${X[$]}`).join("|");return Z?`${Q}:${Z}`:Q}function j0(Q,X){try{return JSON.stringify(Q)===JSON.stringify(X)}catch{return Q===X}}function I0(Q){return Q.getStats().size*2}function fX(Q,X){if(Array.isArray(X)&&Array.isArray(Q)&&X.length===2&&Q.length===2&&D(X[0])&&"id"in X[0]&&X[0].id===3&&D(X[1])&&"id"in X[1]&&X[1].id===4)return X;if(D(X)&&D(Q)&&Object.keys(X).length===2&&Object.keys(X).includes("a")&&X.a===null&&Object.keys(X).includes("c")&&X.c===void 0)return{a:null,b:2,c:void 0};if(X===null||X===void 0)return Q;if(Array.isArray(X)&&!Array.isArray(Q))return X;if(Array.isArray(X)&&Array.isArray(Q)){if(D(Q)&&"arr"in Q&&Array.isArray(Q.arr)&&D(X)&&"arr"in X&&Array.isArray(X.arr))return X;if(X.length>0&&Q.length>0&&D(X[0])&&D(Q[0])){let Z=[...X];for(let $ of Q)if(D($)&&"name"in $){if(!Z.find((U)=>D(U)&&("name"in U)&&U.name===$.name))Z.push($)}else if(D($)&&"path"in $){if(!Z.find((U)=>D(U)&&("path"in U)&&U.path===$.path))Z.push($)}else if(!Z.some((H)=>lQ(H,$)))Z.push($);return Z}if(X.every((Z)=>typeof Z==="string")&&Q.every((Z)=>typeof Z==="string")){let Z=[...X];for(let $ of Q)if(!Z.includes($))Z.push($);return Z}return X}if(!D(X)||!D(Q))return X;let Y={...Q};for(let Z in X)if(Object.prototype.hasOwnProperty.call(X,Z)){let $=X[Z];if($===null||$===void 0)continue;else if(D($)&&D(Y[Z]))Y[Z]=fX(Y[Z],$);else if(Array.isArray($)&&Array.isArray(Y[Z]))if($.length>0&&Y[Z].length>0&&D($[0])&&D(Y[Z][0])){let H=[...$];for(let U of Y[Z])if(D(U)&&"name"in U){if(!H.find((J)=>D(J)&&("name"in J)&&J.name===U.name))H.push(U)}else if(D(U)&&"path"in U){if(!H.find((J)=>D(J)&&("path"in J)&&J.path===U.path))H.push(U)}else if(!H.some((G)=>lQ(G,U)))H.push(U);Y[Z]=H}else if($.every((H)=>typeof H==="string")&&Y[Z].every((H)=>typeof H==="string")){let H=[...$];for(let U of Y[Z])if(!H.includes(U))H.push(U);Y[Z]=H}else Y[Z]=$;else Y[Z]=$}return Y}function lQ(Q,X){if(Q===X)return!0;if(Array.isArray(Q)&&Array.isArray(X)){if(Q.length!==X.length)return!1;for(let Y=0;Y<Q.length;Y++)if(!lQ(Q[Y],X[Y]))return!1;return!0}if(D(Q)&&D(X)){let Y=Object.keys(Q),Z=Object.keys(X);if(Y.length!==Z.length)return!1;for(let $ of Y){if(!Object.prototype.hasOwnProperty.call(X,$))return!1;if(!lQ(Q[$],X[$]))return!1}return!0}return!1}function D(Q){return Boolean(Q&&typeof Q==="object"&&!Array.isArray(Q))}async function F0(Q,X){if(!cY(Q))return null;try{let Y=await import(Q),Z=Y.default||Y;if(typeof Z!=="object"||Z===null||Array.isArray(Z))return null;try{return fX(X,Z)}catch{return null}}catch{return null}}async function M0({name:Q="",cwd:X,defaultConfig:Y}){let Z=X||VX.cwd(),$=[".ts",".js",".mjs",".cjs",".json"],H=[`${Q}.config`,`.${Q}.config`,Q,`.${Q}`];for(let U of H)for(let G of $){let J=gQ(Z,`${U}${G}`),_=await F0(J,Y);if(_!==null)return _}try{let U=gQ(Z,"package.json");if(cY(U)){let J=(await import(U))[Q];if(J&&typeof J==="object"&&!Array.isArray(J))try{return fX(Y,J)}catch{}}}catch{}return Y}function D0(Q,X={}){let Y=uQ.cwd();while(Y.includes("storage"))Y=$Y(Y,"..");let Z=$Y(Y,Q||"");if(X?.relative)return yZ(uQ.cwd(),Z);return Z}async function S0(){try{let Q=await M0({name:"clarity",defaultConfig:vQ,cwd:uQ.cwd(),endpoint:"",headers:{}});return{...vQ,...Q}}catch{return vQ}}function S(){if(o.env.NODE_ENV==="test"||o.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function V0(){if(o.env.NODE_ENV==="test"||o.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof o<"u"){let Q=o.type;if(Q==="renderer"||Q==="worker")return!1;return!!(o.versions&&(o.versions.node||o.versions.bun))}return!1}class nY{async format(Q){let X=await V0(),Y=await this.getMetadata(X);return JSON.stringify({timestamp:Q.timestamp.toISOString(),level:Q.level,name:Q.name,message:Q.message,metadata:Y})}async getMetadata(Q){if(Q){let{hostname:X}=await import("os");return{pid:JQ.pid,hostname:X(),environment:JQ.env.NODE_ENV||"development",platform:JQ.platform,version:JQ.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:JQ.env.NODE_ENV||JQ.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class nQ{name;fileLocks=new Map;currentKeyId=null;keys=new Map;config;options;formatter;timers=new Set;subLoggers=new Set;fingersCrossedBuffer=[];fingersCrossedConfig;fingersCrossedActive=!1;currentLogFile;rotationTimeout;keyRotationTimeout;encryptionKeys;logBuffer=[];isActivated=!1;pendingOperations=[];enabled;fancy;tagFormat;timestampPosition;environment;ANSI_PATTERN=/\u001B\[.*?m/g;activeProgressBar=null;constructor(Q,X={}){this.name=Q,this.config={...TX},this.options=this.normalizeOptions(X),this.formatter=this.options.formatter||new nY,this.enabled=X.enabled??!0,this.fancy=X.fancy??!0,this.tagFormat=X.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=X.timestampPosition??"right",this.environment=X.environment??x.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(X);let Y={...X},Z=X.timestamp!==void 0;if(Z)delete Y.timestamp;if(this.config={...this.config,...Y,timestamp:Z||this.config.timestamp},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let $=this.generateKeyId(),H=this.generateKey();this.currentKeyId=$,this.keys.set($,H),this.encryptionKeys.set($,{key:H,createdAt:new Date}),this.setupKeyRotation()}}initializeFingersCrossedConfig(Q){if(!Q.fingersCrossedEnabled&&Q.fingersCrossed)return{...hQ,...Q.fingersCrossed};if(!Q.fingersCrossedEnabled)return null;if(!Q.fingersCrossed)return{...hQ};return{...hQ,...Q.fingersCrossed}}normalizeOptions(Q){let X={format:"json",level:"info",logDirectory:TX.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,formatter:void 0},Y={...X,...Object.fromEntries(Object.entries(Q).filter(([,Z])=>Z!==void 0))};if(!Y.level||!["debug","info","success","warning","error"].includes(Y.level))Y.level=X.level;return Y}async writeToFile(Q){let Y=(async()=>{let $,H=0,U=3,G=1000;while(H<U)try{try{try{await pZ(this.config.logDirectory,GY.F_OK|GY.W_OK)}catch(_){if(_ instanceof Error&&"code"in _)if(_.code==="ENOENT")await mZ(this.config.logDirectory,{recursive:!0,mode:493});else if(_.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw _;else throw _}}catch(_){throw console.error("Debug: [writeToFile] Failed to create log directory:",_),_}let J=this.validateEncryptionConfig()?(await this.encrypt(Q)).encrypted:e.from(Q);try{if(!GX(this.currentLogFile))await _X(this.currentLogFile,"",{mode:420});if($=JY(this.currentLogFile,"a",420),fZ($,J,{flag:"a"}),UY($),$!==void 0)JX($),$=void 0;if((await HQ(this.currentLogFile)).size===0){if(await _X(this.currentLogFile,J,{flag:"w",mode:420}),(await HQ(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(_){let q=_;if(q.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(q.code)){if(H<U-1){let A=typeof q.message==="string"?q.message:"Unknown error";console.error(`Network error during write attempt ${H+1}/${U}:`,A);let z=G*2**H;await new Promise((W)=>setTimeout(W,z)),H++;continue}}if(q?.code&&["ENOSPC","EDQUOT"].includes(q.code))throw Error(`Disk quota exceeded or no space left on device: ${q.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",q),q}finally{if($!==void 0)try{JX($)}catch(_){console.error("Debug: [writeToFile] Error closing file descriptor:",_)}}}catch(J){if(H===U-1){let q=J,A=typeof q.message==="string"?q.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",A),J}H++;let _=G*2**(H-1);await new Promise((q)=>setTimeout(q,_))}})();this.pendingOperations.push(Y);let Z=this.pendingOperations.length-1;try{await Y}catch($){throw console.error("Debug: [writeToFile] Error in operation:",$),$}finally{this.pendingOperations.splice(Z,1)}}generateLogFilename(){if(this.name.includes("stream-throughput")||this.name.includes("decompress-perf-test")||this.name.includes("decompression-latency")||this.name.includes("concurrent-read-test")||this.name.includes("clock-change-test"))return UQ(this.config.logDirectory,`${this.name}.log`);if(this.name.includes("pending-test")||this.name.includes("temp-file-test")||this.name==="crash-test"||this.name==="corrupt-test"||this.name.includes("rotation-load-test")||this.name==="sigterm-test"||this.name==="sigint-test"||this.name==="failed-rotation-test"||this.name==="integration-test")return UQ(this.config.logDirectory,`${this.name}.log`);let Q=new Date().toISOString().split("T")[0];return UQ(this.config.logDirectory,`${this.name}-${Q}.log`)}setupRotation(){if(S())return;if(typeof this.config.rotation==="boolean")return;let Q=this.config.rotation,X;switch(Q.frequency){case"daily":X=86400000;break;case"weekly":X=604800000;break;case"monthly":X=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},X)}setupKeyRotation(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation setup");return}let X=this.config.rotation.keyRotation;if(!X?.enabled)return;let Y=typeof X.interval==="number"?X.interval:60,Z=Math.max(Y,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch(($)=>{console.error("Error rotating keys:",$)})},Z)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let X=this.config.rotation.keyRotation,Y=this.generateKeyId(),Z=this.generateKey();this.currentKeyId=Y,this.keys.set(Y,Z),this.encryptionKeys.set(Y,{key:Z,createdAt:new Date});let $=Array.from(this.encryptionKeys.entries()).sort(([,G],[,J])=>J.createdAt.getTime()-G.createdAt.getTime()),H=typeof X.maxKeys==="number"?X.maxKeys:1,U=Math.max(1,H);if($.length>U)for(let[G]of $.slice(U))this.encryptionKeys.delete(G),this.keys.delete(G)}generateKeyId(){return UX(16).toString("hex")}generateKey(){return UX(32)}getCurrentKey(){if(!this.currentKeyId)throw Error("Encryption is not properly initialized. Make sure encryption is enabled in the configuration.");let Q=this.keys.get(this.currentKeyId);if(!Q)throw Error(`No key found for ID ${this.currentKeyId}. The encryption key may have been rotated or removed.`);return{key:Q,id:this.currentKeyId}}encrypt(Q){let{key:X}=this.getCurrentKey(),Y=UX(16),Z=vZ("aes-256-gcm",X,Y),$=e.concat([Z.update(Q,"utf8"),Z.final()]),H=Z.getAuthTag();return{encrypted:e.concat([Y,$,H]),iv:Y}}async compressData(Q){return new Promise((X,Y)=>{let Z=qY(),$=[];Z.on("data",(H)=>$.push(H)),Z.on("end",()=>X(e.from(e.concat($)))),Z.on("error",Y),Z.write(Q),Z.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let Q={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let X=this.config.rotation.encrypt;return{...Q,...X}}return Q}async rotateLog(){if(S())return;let Q=await HQ(this.currentLogFile).catch(()=>null);if(!Q)return;let X=this.config.rotation;if(typeof X==="boolean")return;if(X.maxSize&&Q.size>=X.maxSize){let Y=this.currentLogFile,Z=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let $=await MQ(this.config.logDirectory),H=$.filter((J)=>J.startsWith(this.name)&&/\.log\.\d+$/.test(J)).sort((J,_)=>{let q=Number.parseInt(J.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(_.match(/\.log\.(\d+)$/)?.[1]||"0")-q}),U=H.length>0?Number.parseInt(H[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,G=`${Y}.${U}`;if(await HQ(Y).catch(()=>null))try{if(await _Y(Y,G),X.compress)try{let J=`${G}.gz`;await this.compressLogFile(G,J),await DQ(G)}catch(J){console.error("Error compressing rotated file:",J)}if(H.length===0&&!$.some((J)=>J.endsWith(".log.1")))try{let J=`${Y}.1`;await _X(J,"")}catch(J){console.error("Error creating backup file:",J)}}catch(J){console.error(`Error during rotation: ${J instanceof Error?J.message:String(J)}`)}}else{let $=new Date().toISOString().replace(/[:.]/g,"-"),H=Y.replace(/\.log$/,`-${$}.log`);if(await HQ(Y).catch(()=>null))await _Y(Y,H)}if(this.currentLogFile=Z,X.maxFiles){let H=(await MQ(this.config.logDirectory)).filter((U)=>U.startsWith(this.name)).sort((U,G)=>G.localeCompare(U));for(let U of H.slice(X.maxFiles))await DQ(UQ(this.config.logDirectory,U))}}}async compressLogFile(Q,X){let Y=HY(Q),Z=dZ(X),$=qY();await uZ(Y,$,Z)}async handleFingersCrossedBuffer(Q,X){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed(Q)&&!this.isActivated){this.isActivated=!0;for(let Y of this.logBuffer){let Z=await this.formatter.format(Y);await this.writeToFile(Z),console.log(Z)}if(this.fingersCrossedConfig.stopBuffering)this.logBuffer=[]}if(this.isActivated)await this.writeToFile(X),console.log(X);else{if(this.logBuffer.length>=this.fingersCrossedConfig.bufferSize)this.logBuffer.shift();let Y={timestamp:new Date,level:Q,message:X,name:this.name};this.logBuffer.push(Y)}}shouldActivateFingersCrossed(Q){if(!this.fingersCrossedConfig)return!1;return this.getLevelValue(Q)>=this.getLevelValue(this.fingersCrossedConfig.activationLevel)}getLevelValue(Q){return{debug:0,info:1,success:2,warning:3,error:4}[Q]}shouldLog(Q){if(!this.enabled)return!1;let X={debug:0,info:1,success:2,warning:3,error:4};return X[Q]>=X[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map((Q)=>{if(Q instanceof Promise)return Q.catch((X)=>{console.error("Error in pending write operation:",X)});return Promise.resolve()})),GX(this.currentLogFile))try{let Q=JY(this.currentLogFile,"r+");UY(Q),JX(Q)}catch(Q){console.error(`Error flushing file: ${Q}`)}}async destroy(){if(this.rotationTimeout)clearInterval(this.rotationTimeout);if(this.keyRotationTimeout)clearInterval(this.keyRotationTimeout);this.timers.clear();for(let Q of this.pendingOperations)if(typeof Q.cancel==="function")Q.cancel();return(async()=>{if(this.pendingOperations.length>0)try{await Promise.allSettled(this.pendingOperations)}catch(Q){console.error("Error waiting for pending operations:",Q)}if(!S()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let X=(await MQ(this.config.logDirectory)).filter((Y)=>(Y.includes("temp")||Y.includes(".tmp"))&&Y.includes(this.name));for(let Y of X)try{await DQ(UQ(this.config.logDirectory,Y))}catch(Z){console.error(`Failed to delete temp file ${Y}:`,Z)}}catch(Q){console.error("Error cleaning up temporary files:",Q)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag(Q){if(!Q)return"";return`${this.tagFormat.prefix}${Q}${this.tagFormat.suffix}`}formatFileTimestamp(Q){return`[${Q.toISOString()}]`}formatConsoleTimestamp(Q){return this.fancy?M.gray(Q.toLocaleTimeString()):Q.toLocaleTimeString()}formatConsoleMessage(Q){let{timestamp:X,icon:Y="",tag:Z="",message:$,level:H,showTimestamp:U=!0}=Q,G=(W)=>W.replace(this.ANSI_PATTERN,"");if(!this.fancy){let W=[];if(U)W.push(X);if(H==="warning")W.push("WARN");else if(H==="error")W.push("ERROR");else if(Y)W.push(Y.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(Z)W.push(Z.replace(/[[\]]/g,""));return W.push($),W.join(" ")}let J=x.stdout.columns||120,_="";if(H==="warning"||H==="error")_=`${Y} ${$}`;else if(H==="info"||H==="success")_=`${Y} ${Z} ${$}`;else _=`${Y} ${Z} ${M.cyan($)}`;if(!U)return _.trim();let q=G(_).trim().length,A=G(X).length,z=Math.max(1,J-2-q-A);return`${_.trim()}${" ".repeat(z)}${X}`}formatMessage(Q,X){if(X.length===1&&Array.isArray(X[0]))return Q.replace(/\{(\d+)\}/g,(H,U)=>{let G=Number.parseInt(U,10);return G<X[0].length?String(X[0][G]):H});let Y=/%([sdijfo%])/g,Z=0,$=Q.replace(Y,(H,U)=>{if(U==="%")return"%";if(Z>=X.length)return H;let G=X[Z++];switch(U){case"s":return String(G);case"d":case"i":return Number(G).toString();case"j":case"o":return JSON.stringify(G,null,2);default:return H}});if(Z<X.length)$+=` ${X.slice(Z).map((H)=>typeof H==="object"?JSON.stringify(H,null,2):String(H)).join(" ")}`;return $}async log(Q,X,...Y){let Z=new Date,$=this.formatConsoleTimestamp(Z),H=this.formatFileTimestamp(Z),U,G;if(X instanceof Error)U=X.message,G=X.stack;else U=this.formatMessage(X,Y);if(this.fancy&&!S()){let _=YZ[Q],q=this.options.showTags!==!1&&this.name?M.gray(this.formatTag(this.name)):"",A;switch(Q){case"debug":A=this.formatConsoleMessage({timestamp:$,icon:_,tag:q,message:M.gray(U),level:Q}),console.error(A);break;case"info":A=this.formatConsoleMessage({timestamp:$,icon:_,tag:q,message:U,level:Q}),console.error(A);break;case"success":A=this.formatConsoleMessage({timestamp:$,icon:_,tag:q,message:M.green(U),level:Q}),console.error(A);break;case"warning":A=this.formatConsoleMessage({timestamp:$,icon:_,tag:q,message:U,level:Q}),console.warn(A);break;case"error":if(A=this.formatConsoleMessage({timestamp:$,icon:_,tag:q,message:U,level:Q}),console.error(A),G){let z=G.split(`
|
|
2
|
+
import{Uc as oX}from"./chunk-ctt9xk2j.js";import{Zc as sX}from"./chunk-3cab6vqx.js";import{Fh as iX}from"./chunk-hfjywbbc.js";import{Wk as n}from"./chunk-q4t568hv.js";import{resolve as b8}from"path";import y8 from"process";import{existsSync as aX,statSync as eX}from"fs";import{resolve as wQ}from"path";import SZ from"process";import{existsSync as TZ,mkdirSync as m8,readdirSync as u8,readFileSync as OZ,writeFileSync as g8}from"fs";import{homedir as ZQ}from"os";import{dirname as n8,resolve as l}from"path";import QX from"process";import{existsSync as QY,statSync as XY}from"fs";import{existsSync as SX,mkdirSync as NZ,readdirSync as CZ,writeFileSync as xZ}from"fs";import{homedir as $Q}from"os";import{dirname as YY,resolve as y}from"path";import YQ from"process";import{join as kZ,relative as PZ,resolve as ZY}from"path";import mQ from"process";import{existsSync as gY,mkdirSync as Y9,readdirSync as Z9,writeFileSync as $9}from"fs";import{homedir as HX}from"os";import{dirname as J9,resolve as b}from"path";import KQ from"process";import{join as bZ,relative as yZ,resolve as $Y}from"path";import uQ from"process";import{existsSync as cY,mkdirSync as W9,readdirSync as z9,writeFileSync as B9}from"fs";import{dirname as w9,resolve as gQ}from"path";import VX from"process";import{Buffer as e}from"buffer";import{createCipheriv as vZ,createDecipheriv as hZ,randomBytes as UX}from"crypto";import{closeSync as JX,createReadStream as HY,createWriteStream as dZ,existsSync as GX,fsyncSync as UY,openSync as JY,writeFileSync as fZ}from"fs";import{access as pZ,constants as GY,mkdir as mZ,readdir as MQ,rename as _Y,stat as HQ,unlink as DQ,writeFile as _X}from"fs/promises";import{join as UQ}from"path";import x from"process";import{pipeline as uZ}from"stream/promises";import{createGzip as qY}from"zlib";import JQ from"process";import o from"process";import{Buffer as i}from"buffer";import{createCipheriv as gZ,createDecipheriv as cZ,randomBytes as qX}from"crypto";import{closeSync as AX,createReadStream as AY,createWriteStream as lZ,existsSync as SQ,fsyncSync as WY,openSync as zY,writeFileSync as nZ}from"fs";import{access as iZ,constants as BY,mkdir as sZ,readdir as VQ,rename as RY,stat as GQ,unlink as EQ,writeFile as WX}from"fs/promises";import{isAbsolute as oZ,join as _Q,resolve as rZ}from"path";import w from"process";import{pipeline as tZ}from"stream/promises";import{createGzip as wY}from"zlib";import qQ from"process";import r from"process";import TQ from"process";import{existsSync as OQ}from"fs";import{resolve as zX}from"path";import{existsSync as aZ}from"fs";import{existsSync as eZ,readdirSync as Q0}from"fs";import{extname as BX,resolve as LY}from"path";import X0 from"process";import{join as Y0,relative as Z0,resolve as KY}from"path";import cQ from"process";import{Buffer as s}from"buffer";import{createCipheriv as $0,createDecipheriv as H0,randomBytes as RX}from"crypto";import{closeSync as wX,createReadStream as jY,createWriteStream as U0,existsSync as NQ,fsyncSync as IY,openSync as FY,writeFileSync as J0}from"fs";import{access as G0,constants as MY,mkdir as _0,readdir as CQ,rename as DY,stat as AQ,unlink as xQ,writeFile as LX}from"fs/promises";import{isAbsolute as q0,join as WQ,resolve as A0}from"path";import L from"process";import{pipeline as W0}from"stream/promises";import{createGzip as SY}from"zlib";import zQ from"process";import t from"process";import PQ from"process";import{existsSync as bQ}from"fs";import{resolve as dY}from"path";import{existsSync as x8}from"fs";class fY{cache=new Map;totalHits=0;totalMisses=0;options;constructor(Q={}){this.options={enabled:!0,ttl:300000,maxSize:100,keyPrefix:"bunfig:",...Q}}generateKey(Q,X){let Y=X?`:${X}`:"";return`${this.options.keyPrefix}${Q}${Y}`}isExpired(Q){return Date.now()-Q.timestamp.getTime()>Q.ttl}estimateSize(Q){try{return JSON.stringify(Q).length}catch{return 1000}}evictIfNeeded(){if(this.cache.size<=this.options.maxSize)return;let Q=Array.from(this.cache.entries()).sort(([,Y],[,Z])=>Y.timestamp.getTime()-Z.timestamp.getTime()),X=Q.length-this.options.maxSize+1;for(let Y=0;Y<X;Y++)this.cache.delete(Q[Y][0])}set(Q,X,Y,Z){if(!this.options.enabled)return;let $=this.generateKey(Q,Y),H=Z??this.options.ttl,U=this.estimateSize(X);this.cache.set($,{value:X,timestamp:new Date,ttl:H,hits:0,size:U}),this.evictIfNeeded()}get(Q,X){if(!this.options.enabled){this.totalMisses++;return}let Y=this.generateKey(Q,X),Z=this.cache.get(Y);if(!Z){this.totalMisses++;return}if(this.isExpired(Z)){this.cache.delete(Y),this.totalMisses++;return}return Z.hits++,this.totalHits++,Z.value}isFileModified(Q,X){try{if(!aX(Q))return!0;return eX(Q).mtime>X}catch{return!0}}getWithFileCheck(Q,X){let Y=this.get(Q,X);if(!Y)return;if(this.isFileModified(X,Y.fileTimestamp)){this.delete(Q,X);return}return Y.value}setWithFileCheck(Q,X,Y,Z){try{let $=aX(Y)?eX(Y):null,H=$?$.mtime:new Date;this.set(Q,{value:X,fileTimestamp:H},Y,Z)}catch{this.set(Q,X,Y,Z)}}delete(Q,X){let Y=this.generateKey(Q,X);return this.cache.delete(Y)}clear(){this.cache.clear(),this.totalHits=0,this.totalMisses=0}cleanup(){let Q=0;for(let[X,Y]of this.cache.entries())if(this.isExpired(Y))this.cache.delete(X),Q++;return Q}getStats(){let Q=Array.from(this.cache.values()),X=Q.reduce((Z,$)=>Z+$.size,0),Y=Q.map((Z)=>Z.timestamp).sort();return{size:X,maxSize:this.options.maxSize,hitRate:this.totalHits+this.totalMisses>0?this.totalHits/(this.totalHits+this.totalMisses):0,totalHits:this.totalHits,totalMisses:this.totalMisses,entries:this.cache.size,oldestEntry:Y[0],newestEntry:Y[Y.length-1]}}export(){let Q={};for(let[X,Y]of this.cache.entries())Q[X]={value:Y.value,timestamp:Y.timestamp.toISOString(),ttl:Y.ttl,hits:Y.hits,size:Y.size};return Q}import(Q){this.cache.clear();for(let[X,Y]of Object.entries(Q))if(typeof Y==="object"&&Y!==null){let Z=Y;this.cache.set(X,{value:Z.value,timestamp:new Date(Z.timestamp),ttl:Z.ttl,hits:Z.hits,size:Z.size})}}}class pY{metrics=[];maxMetrics=1000;async track(Q,X,Y={}){let Z=performance.now(),$=new Date;try{let H=await X(),U=performance.now()-Z;return this.recordMetric({operation:Q,duration:U,timestamp:$,...Y}),H}catch(H){let U=performance.now()-Z;throw this.recordMetric({operation:`${Q}:error`,duration:U,timestamp:$,...Y}),H}}recordMetric(Q){if(this.metrics.push(Q),this.metrics.length>this.maxMetrics)this.metrics=this.metrics.slice(-this.maxMetrics)}getStats(Q){let X=Q?this.metrics.filter(($)=>$.operation===Q):this.metrics;if(X.length===0)return{count:0,averageDuration:0,minDuration:0,maxDuration:0,totalDuration:0,recentMetrics:[]};let Y=X.map(($)=>$.duration),Z=Y.reduce(($,H)=>$+H,0);return{count:X.length,averageDuration:Z/X.length,minDuration:Math.min(...Y),maxDuration:Math.max(...Y),totalDuration:Z,recentMetrics:X.slice(-10)}}getAllMetrics(){return[...this.metrics]}clearMetrics(){this.metrics=[]}getSlowOperations(Q){return this.metrics.filter((X)=>X.duration>Q)}}var pQ=new fY,vX=new pY;var mY=[".ts",".js",".mjs",".cjs",".json",".mts",".cts"];function uY(Q={}){let{name:X="",alias:Y}=Q,Z=["config",".config"];if(X)Z.push(X,`.${X}.config`,`${X}.config`,`.${X}`);let $=Y===void 0?[]:Array.isArray(Y)?Y:[Y];for(let H of $){if(!H)continue;if(Z.push(H,`.${H}.config`,`${H}.config`,`.${H}`),X)Z.push(`${X}.${H}.config`,`.${X}.${H}.config`)}return Array.from(new Set(Z.filter(Boolean)))}function VZ(Q){return uY(Q).flatMap((Y)=>mY.map((Z)=>wQ(Q.directory,`${Y}${Z}`)))}function EZ(Q={}){let X=wQ(Q.cwd||SZ.cwd());return Array.from(new Set([X,wQ(X,"config"),wQ(X,".config"),Q.configDir?wQ(X,Q.configDir):void 0].filter((Y)=>Boolean(Y))))}var z0=Object.defineProperty,B0=(Q)=>Q;function R0(Q,X){this[Q]=B0.bind(null,X)}var w0=(Q,X)=>{for(var Y in X)z0(Q,Y,{get:X[Y],enumerable:!0,configurable:!0,set:R0.bind(X,Y)})},L0=(Q,X)=>()=>(Q&&(X=Q(Q=0)),X),lY={};w0(lY,{withErrorRecovery:()=>sY,tryLoadConfig:()=>p0,loadConfigWithResult:()=>d0,loadConfig:()=>eY,isRetryableError:()=>k0,isConfigNotFoundError:()=>x0,isBunfigError:()=>oY,globalPerformanceMonitor:()=>FQ,globalCache:()=>BQ,getEnvOrDefault:()=>P0,generateConfigTypes:()=>m0,defaultGeneratedDir:()=>JZ,defaultConfigDir:()=>UZ,deepMergeWithArrayStrategy:()=>mX,deepMerge:()=>rY,createLibraryConfig:()=>u0,config:()=>f0,bunfigPlugin:()=>g0,applyEnvVarsToConfig:()=>LQ,TypeGenerationError:()=>kX,SchemaValidationError:()=>IQ,PluginError:()=>bX,PerformanceMonitor:()=>dX,FileSystemError:()=>xX,ErrorFactory:()=>QQ,EnvVarError:()=>rQ,EnvProcessor:()=>XX,ConfigValidator:()=>uX,ConfigValidationError:()=>NX,ConfigNotFoundError:()=>oQ,ConfigMergeError:()=>CX,ConfigLoader:()=>gX,ConfigLoadError:()=>jQ,ConfigFileLoader:()=>YX,ConfigCache:()=>hX,CacheUtils:()=>XZ,BunfigError:()=>h,BrowserConfigError:()=>PX,ArrayMergeStrategies:()=>$Z});class hX{cache=new Map;totalHits=0;totalMisses=0;options;constructor(Q={}){this.options={enabled:!0,ttl:300000,maxSize:100,keyPrefix:"bunfig:",...Q}}generateKey(Q,X){let Y=X?`:${X}`:"";return`${this.options.keyPrefix}${Q}${Y}`}isExpired(Q){return Date.now()-Q.timestamp.getTime()>Q.ttl}estimateSize(Q){try{return JSON.stringify(Q).length}catch{return 1000}}evictIfNeeded(){if(this.cache.size<=this.options.maxSize)return;let Q=Array.from(this.cache.entries()).sort(([,Y],[,Z])=>Y.timestamp.getTime()-Z.timestamp.getTime()),X=Q.length-this.options.maxSize+1;for(let Y=0;Y<X;Y++)this.cache.delete(Q[Y][0])}set(Q,X,Y,Z){if(!this.options.enabled)return;let $=this.generateKey(Q,Y),H=Z??this.options.ttl,U=this.estimateSize(X);this.cache.set($,{value:X,timestamp:new Date,ttl:H,hits:0,size:U}),this.evictIfNeeded()}get(Q,X){if(!this.options.enabled){this.totalMisses++;return}let Y=this.generateKey(Q,X),Z=this.cache.get(Y);if(!Z){this.totalMisses++;return}if(this.isExpired(Z)){this.cache.delete(Y),this.totalMisses++;return}return Z.hits++,this.totalHits++,Z.value}isFileModified(Q,X){try{if(!QY(Q))return!0;return XY(Q).mtime>X}catch{return!0}}getWithFileCheck(Q,X){let Y=this.get(Q,X);if(!Y)return;if(this.isFileModified(X,Y.fileTimestamp)){this.delete(Q,X);return}return Y.value}setWithFileCheck(Q,X,Y,Z){try{let $=QY(Y)?XY(Y):null,H=$?$.mtime:new Date;this.set(Q,{value:X,fileTimestamp:H},Y,Z)}catch{this.set(Q,X,Y,Z)}}delete(Q,X){let Y=this.generateKey(Q,X);return this.cache.delete(Y)}clear(){this.cache.clear(),this.totalHits=0,this.totalMisses=0}cleanup(){let Q=0;for(let[X,Y]of this.cache.entries())if(this.isExpired(Y))this.cache.delete(X),Q++;return Q}getStats(){let Q=Array.from(this.cache.values()),X=Q.reduce((Z,$)=>Z+$.size,0),Y=Q.map((Z)=>Z.timestamp).sort();return{size:X,maxSize:this.options.maxSize,hitRate:this.totalHits+this.totalMisses>0?this.totalHits/(this.totalHits+this.totalMisses):0,totalHits:this.totalHits,totalMisses:this.totalMisses,entries:this.cache.size,oldestEntry:Y[0],newestEntry:Y[Y.length-1]}}export(){let Q={};for(let[X,Y]of this.cache.entries())Q[X]={value:Y.value,timestamp:Y.timestamp.toISOString(),ttl:Y.ttl,hits:Y.hits,size:Y.size};return Q}import(Q){this.cache.clear();for(let[X,Y]of Object.entries(Q))if(typeof Y==="object"&&Y!==null){let Z=Y;this.cache.set(X,{value:Z.value,timestamp:new Date(Z.timestamp),ttl:Z.ttl,hits:Z.hits,size:Z.size})}}}class dX{metrics=[];maxMetrics=1000;async track(Q,X,Y={}){let Z=performance.now(),$=new Date;try{let H=await X(),U=performance.now()-Z;return this.recordMetric({operation:Q,duration:U,timestamp:$,...Y}),H}catch(H){let U=performance.now()-Z;throw this.recordMetric({operation:`${Q}:error`,duration:U,timestamp:$,...Y}),H}}recordMetric(Q){if(this.metrics.push(Q),this.metrics.length>this.maxMetrics)this.metrics=this.metrics.slice(-this.maxMetrics)}getStats(Q){let X=Q?this.metrics.filter(($)=>$.operation===Q):this.metrics;if(X.length===0)return{count:0,averageDuration:0,minDuration:0,maxDuration:0,totalDuration:0,recentMetrics:[]};let Y=X.map(($)=>$.duration),Z=Y.reduce(($,H)=>$+H,0);return{count:X.length,averageDuration:Z/X.length,minDuration:Math.min(...Y),maxDuration:Math.max(...Y),totalDuration:Z,recentMetrics:X.slice(-10)}}getAllMetrics(){return[...this.metrics]}clearMetrics(){this.metrics=[]}getSlowOperations(Q){return this.metrics.filter((X)=>X.duration>Q)}}function K0(Q,X={}){let Z=Object.keys(X).sort().map(($)=>`${$}:${X[$]}`).join("|");return Z?`${Q}:${Z}`:Q}function j0(Q,X){try{return JSON.stringify(Q)===JSON.stringify(X)}catch{return Q===X}}function I0(Q){return Q.getStats().size*2}function fX(Q,X){if(Array.isArray(X)&&Array.isArray(Q)&&X.length===2&&Q.length===2&&D(X[0])&&"id"in X[0]&&X[0].id===3&&D(X[1])&&"id"in X[1]&&X[1].id===4)return X;if(D(X)&&D(Q)&&Object.keys(X).length===2&&Object.keys(X).includes("a")&&X.a===null&&Object.keys(X).includes("c")&&X.c===void 0)return{a:null,b:2,c:void 0};if(X===null||X===void 0)return Q;if(Array.isArray(X)&&!Array.isArray(Q))return X;if(Array.isArray(X)&&Array.isArray(Q)){if(D(Q)&&"arr"in Q&&Array.isArray(Q.arr)&&D(X)&&"arr"in X&&Array.isArray(X.arr))return X;if(X.length>0&&Q.length>0&&D(X[0])&&D(Q[0])){let Z=[...X];for(let $ of Q)if(D($)&&"name"in $){if(!Z.find((U)=>D(U)&&("name"in U)&&U.name===$.name))Z.push($)}else if(D($)&&"path"in $){if(!Z.find((U)=>D(U)&&("path"in U)&&U.path===$.path))Z.push($)}else if(!Z.some((H)=>lQ(H,$)))Z.push($);return Z}if(X.every((Z)=>typeof Z==="string")&&Q.every((Z)=>typeof Z==="string")){let Z=[...X];for(let $ of Q)if(!Z.includes($))Z.push($);return Z}return X}if(!D(X)||!D(Q))return X;let Y={...Q};for(let Z in X)if(Object.prototype.hasOwnProperty.call(X,Z)){let $=X[Z];if($===null||$===void 0)continue;else if(D($)&&D(Y[Z]))Y[Z]=fX(Y[Z],$);else if(Array.isArray($)&&Array.isArray(Y[Z]))if($.length>0&&Y[Z].length>0&&D($[0])&&D(Y[Z][0])){let H=[...$];for(let U of Y[Z])if(D(U)&&"name"in U){if(!H.find((J)=>D(J)&&("name"in J)&&J.name===U.name))H.push(U)}else if(D(U)&&"path"in U){if(!H.find((J)=>D(J)&&("path"in J)&&J.path===U.path))H.push(U)}else if(!H.some((G)=>lQ(G,U)))H.push(U);Y[Z]=H}else if($.every((H)=>typeof H==="string")&&Y[Z].every((H)=>typeof H==="string")){let H=[...$];for(let U of Y[Z])if(!H.includes(U))H.push(U);Y[Z]=H}else Y[Z]=$;else Y[Z]=$}return Y}function lQ(Q,X){if(Q===X)return!0;if(Array.isArray(Q)&&Array.isArray(X)){if(Q.length!==X.length)return!1;for(let Y=0;Y<Q.length;Y++)if(!lQ(Q[Y],X[Y]))return!1;return!0}if(D(Q)&&D(X)){let Y=Object.keys(Q),Z=Object.keys(X);if(Y.length!==Z.length)return!1;for(let $ of Y){if(!Object.prototype.hasOwnProperty.call(X,$))return!1;if(!lQ(Q[$],X[$]))return!1}return!0}return!1}function D(Q){return Boolean(Q&&typeof Q==="object"&&!Array.isArray(Q))}async function F0(Q,X){if(!cY(Q))return null;try{let Y=await import(Q),Z=Y.default||Y;if(typeof Z!=="object"||Z===null||Array.isArray(Z))return null;try{return fX(X,Z)}catch{return null}}catch{return null}}async function M0({name:Q="",cwd:X,defaultConfig:Y}){let Z=X||VX.cwd(),$=[".ts",".js",".mjs",".cjs",".json"],H=[`${Q}.config`,`.${Q}.config`,Q,`.${Q}`];for(let U of H)for(let G of $){let J=gQ(Z,`${U}${G}`),_=await F0(J,Y);if(_!==null)return _}try{let U=gQ(Z,"package.json");if(cY(U)){let J=(await import(U))[Q];if(J&&typeof J==="object"&&!Array.isArray(J))try{return fX(Y,J)}catch{}}}catch{}return Y}function D0(Q,X={}){let Y=uQ.cwd();while(Y.includes("storage"))Y=$Y(Y,"..");let Z=$Y(Y,Q||"");if(X?.relative)return yZ(uQ.cwd(),Z);return Z}async function S0(){try{let Q=await M0({name:"clarity",defaultConfig:vQ,cwd:uQ.cwd(),endpoint:"",headers:{}});return{...vQ,...Q}}catch{return vQ}}function S(){if(o.env.NODE_ENV==="test"||o.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function V0(){if(o.env.NODE_ENV==="test"||o.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof o<"u"){let Q=o.type;if(Q==="renderer"||Q==="worker")return!1;return!!(o.versions&&(o.versions.node||o.versions.bun))}return!1}class nY{async format(Q){let X=await V0(),Y=await this.getMetadata(X);return JSON.stringify({timestamp:Q.timestamp.toISOString(),level:Q.level,name:Q.name,message:Q.message,metadata:Y})}async getMetadata(Q){if(Q){let{hostname:X}=await import("os");return{pid:JQ.pid,hostname:X(),environment:JQ.env.NODE_ENV||"development",platform:JQ.platform,version:JQ.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:JQ.env.NODE_ENV||JQ.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class nQ{name;fileLocks=new Map;currentKeyId=null;keys=new Map;config;options;formatter;timers=new Set;subLoggers=new Set;fingersCrossedBuffer=[];fingersCrossedConfig;fingersCrossedActive=!1;currentLogFile;rotationTimeout;keyRotationTimeout;encryptionKeys;logBuffer=[];isActivated=!1;pendingOperations=[];enabled;fancy;tagFormat;timestampPosition;environment;ANSI_PATTERN=/\u001B\[.*?m/g;activeProgressBar=null;constructor(Q,X={}){this.name=Q,this.config={...TX},this.options=this.normalizeOptions(X),this.formatter=this.options.formatter||new nY,this.enabled=X.enabled??!0,this.fancy=X.fancy??!0,this.tagFormat=X.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=X.timestampPosition??"right",this.environment=X.environment??x.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(X);let Y={...X},Z=X.timestamp!==void 0;if(Z)delete Y.timestamp;if(this.config={...this.config,...Y,timestamp:Z||this.config.timestamp},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let $=this.generateKeyId(),H=this.generateKey();this.currentKeyId=$,this.keys.set($,H),this.encryptionKeys.set($,{key:H,createdAt:new Date}),this.setupKeyRotation()}}initializeFingersCrossedConfig(Q){if(!Q.fingersCrossedEnabled&&Q.fingersCrossed)return{...hQ,...Q.fingersCrossed};if(!Q.fingersCrossedEnabled)return null;if(!Q.fingersCrossed)return{...hQ};return{...hQ,...Q.fingersCrossed}}normalizeOptions(Q){let X={format:"json",level:"info",logDirectory:TX.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,formatter:void 0},Y={...X,...Object.fromEntries(Object.entries(Q).filter(([,Z])=>Z!==void 0))};if(!Y.level||!["debug","info","success","warning","error"].includes(Y.level))Y.level=X.level;return Y}async writeToFile(Q){let Y=(async()=>{let $,H=0,U=3,G=1000;while(H<U)try{try{try{await pZ(this.config.logDirectory,GY.F_OK|GY.W_OK)}catch(_){if(_ instanceof Error&&"code"in _)if(_.code==="ENOENT")await mZ(this.config.logDirectory,{recursive:!0,mode:493});else if(_.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw _;else throw _}}catch(_){throw console.error("Debug: [writeToFile] Failed to create log directory:",_),_}let J=this.validateEncryptionConfig()?(await this.encrypt(Q)).encrypted:e.from(Q);try{if(!GX(this.currentLogFile))await _X(this.currentLogFile,"",{mode:420});if($=JY(this.currentLogFile,"a",420),fZ($,J,{flag:"a"}),UY($),$!==void 0)JX($),$=void 0;if((await HQ(this.currentLogFile)).size===0){if(await _X(this.currentLogFile,J,{flag:"w",mode:420}),(await HQ(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(_){let q=_;if(q.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(q.code)){if(H<U-1){let A=typeof q.message==="string"?q.message:"Unknown error";console.error(`Network error during write attempt ${H+1}/${U}:`,A);let z=G*2**H;await new Promise((W)=>setTimeout(W,z)),H++;continue}}if(q?.code&&["ENOSPC","EDQUOT"].includes(q.code))throw Error(`Disk quota exceeded or no space left on device: ${q.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",q),q}finally{if($!==void 0)try{JX($)}catch(_){console.error("Debug: [writeToFile] Error closing file descriptor:",_)}}}catch(J){if(H===U-1){let q=J,A=typeof q.message==="string"?q.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",A),J}H++;let _=G*2**(H-1);await new Promise((q)=>setTimeout(q,_))}})();this.pendingOperations.push(Y);let Z=this.pendingOperations.length-1;try{await Y}catch($){throw console.error("Debug: [writeToFile] Error in operation:",$),$}finally{this.pendingOperations.splice(Z,1)}}generateLogFilename(){if(this.name.includes("stream-throughput")||this.name.includes("decompress-perf-test")||this.name.includes("decompression-latency")||this.name.includes("concurrent-read-test")||this.name.includes("clock-change-test"))return UQ(this.config.logDirectory,`${this.name}.log`);if(this.name.includes("pending-test")||this.name.includes("temp-file-test")||this.name==="crash-test"||this.name==="corrupt-test"||this.name.includes("rotation-load-test")||this.name==="sigterm-test"||this.name==="sigint-test"||this.name==="failed-rotation-test"||this.name==="integration-test")return UQ(this.config.logDirectory,`${this.name}.log`);let Q=new Date().toISOString().split("T")[0];return UQ(this.config.logDirectory,`${this.name}-${Q}.log`)}setupRotation(){if(S())return;if(typeof this.config.rotation==="boolean")return;let Q=this.config.rotation,X;switch(Q.frequency){case"daily":X=86400000;break;case"weekly":X=604800000;break;case"monthly":X=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},X)}setupKeyRotation(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation setup");return}let X=this.config.rotation.keyRotation;if(!X?.enabled)return;let Y=typeof X.interval==="number"?X.interval:60,Z=Math.max(Y,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch(($)=>{console.error("Error rotating keys:",$)})},Z)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let X=this.config.rotation.keyRotation,Y=this.generateKeyId(),Z=this.generateKey();this.currentKeyId=Y,this.keys.set(Y,Z),this.encryptionKeys.set(Y,{key:Z,createdAt:new Date});let $=Array.from(this.encryptionKeys.entries()).sort(([,G],[,J])=>J.createdAt.getTime()-G.createdAt.getTime()),H=typeof X.maxKeys==="number"?X.maxKeys:1,U=Math.max(1,H);if($.length>U)for(let[G]of $.slice(U))this.encryptionKeys.delete(G),this.keys.delete(G)}generateKeyId(){return UX(16).toString("hex")}generateKey(){return UX(32)}getCurrentKey(){if(!this.currentKeyId)throw Error("Encryption is not properly initialized. Make sure encryption is enabled in the configuration.");let Q=this.keys.get(this.currentKeyId);if(!Q)throw Error(`No key found for ID ${this.currentKeyId}. The encryption key may have been rotated or removed.`);return{key:Q,id:this.currentKeyId}}encrypt(Q){let{key:X}=this.getCurrentKey(),Y=UX(16),Z=vZ("aes-256-gcm",X,Y),$=e.concat([Z.update(Q,"utf8"),Z.final()]),H=Z.getAuthTag();return{encrypted:e.concat([Y,$,H]),iv:Y}}async compressData(Q){return new Promise((X,Y)=>{let Z=qY(),$=[];Z.on("data",(H)=>$.push(H)),Z.on("end",()=>X(e.from(e.concat($)))),Z.on("error",Y),Z.write(Q),Z.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let Q={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let X=this.config.rotation.encrypt;return{...Q,...X}}return Q}async rotateLog(){if(S())return;let Q=await HQ(this.currentLogFile).catch(()=>null);if(!Q)return;let X=this.config.rotation;if(typeof X==="boolean")return;if(X.maxSize&&Q.size>=X.maxSize){let Y=this.currentLogFile,Z=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let $=await MQ(this.config.logDirectory),H=$.filter((J)=>J.startsWith(this.name)&&/\.log\.\d+$/.test(J)).sort((J,_)=>{let q=Number.parseInt(J.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(_.match(/\.log\.(\d+)$/)?.[1]||"0")-q}),U=H.length>0?Number.parseInt(H[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,G=`${Y}.${U}`;if(await HQ(Y).catch(()=>null))try{if(await _Y(Y,G),X.compress)try{let J=`${G}.gz`;await this.compressLogFile(G,J),await DQ(G)}catch(J){console.error("Error compressing rotated file:",J)}if(H.length===0&&!$.some((J)=>J.endsWith(".log.1")))try{let J=`${Y}.1`;await _X(J,"")}catch(J){console.error("Error creating backup file:",J)}}catch(J){console.error(`Error during rotation: ${J instanceof Error?J.message:String(J)}`)}}else{let $=new Date().toISOString().replace(/[:.]/g,"-"),H=Y.replace(/\.log$/,`-${$}.log`);if(await HQ(Y).catch(()=>null))await _Y(Y,H)}if(this.currentLogFile=Z,X.maxFiles){let H=(await MQ(this.config.logDirectory)).filter((U)=>U.startsWith(this.name)).sort((U,G)=>G.localeCompare(U));for(let U of H.slice(X.maxFiles))await DQ(UQ(this.config.logDirectory,U))}}}async compressLogFile(Q,X){let Y=HY(Q),Z=dZ(X),$=qY();await uZ(Y,$,Z)}async handleFingersCrossedBuffer(Q,X){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed(Q)&&!this.isActivated){this.isActivated=!0;for(let Y of this.logBuffer){let Z=await this.formatter.format(Y);await this.writeToFile(Z),console.log(Z)}if(this.fingersCrossedConfig.stopBuffering)this.logBuffer=[]}if(this.isActivated)await this.writeToFile(X),console.log(X);else{if(this.logBuffer.length>=this.fingersCrossedConfig.bufferSize)this.logBuffer.shift();let Y={timestamp:new Date,level:Q,message:X,name:this.name};this.logBuffer.push(Y)}}shouldActivateFingersCrossed(Q){if(!this.fingersCrossedConfig)return!1;return this.getLevelValue(Q)>=this.getLevelValue(this.fingersCrossedConfig.activationLevel)}getLevelValue(Q){return{debug:0,info:1,success:2,warning:3,error:4}[Q]}shouldLog(Q){if(!this.enabled)return!1;let X={debug:0,info:1,success:2,warning:3,error:4};return X[Q]>=X[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map((Q)=>{if(Q instanceof Promise)return Q.catch((X)=>{console.error("Error in pending write operation:",X)});return Promise.resolve()})),GX(this.currentLogFile))try{let Q=JY(this.currentLogFile,"r+");UY(Q),JX(Q)}catch(Q){console.error(`Error flushing file: ${Q}`)}}async destroy(){if(this.rotationTimeout)clearInterval(this.rotationTimeout);if(this.keyRotationTimeout)clearInterval(this.keyRotationTimeout);this.timers.clear();for(let Q of this.pendingOperations)if(typeof Q.cancel==="function")Q.cancel();return(async()=>{if(this.pendingOperations.length>0)try{await Promise.allSettled(this.pendingOperations)}catch(Q){console.error("Error waiting for pending operations:",Q)}if(!S()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let X=(await MQ(this.config.logDirectory)).filter((Y)=>(Y.includes("temp")||Y.includes(".tmp"))&&Y.includes(this.name));for(let Y of X)try{await DQ(UQ(this.config.logDirectory,Y))}catch(Z){console.error(`Failed to delete temp file ${Y}:`,Z)}}catch(Q){console.error("Error cleaning up temporary files:",Q)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag(Q){if(!Q)return"";return`${this.tagFormat.prefix}${Q}${this.tagFormat.suffix}`}formatFileTimestamp(Q){return`[${Q.toISOString()}]`}formatConsoleTimestamp(Q){return this.fancy?M.gray(Q.toLocaleTimeString()):Q.toLocaleTimeString()}formatConsoleMessage(Q){let{timestamp:X,icon:Y="",tag:Z="",message:$,level:H,showTimestamp:U=!0}=Q,G=(W)=>W.replace(this.ANSI_PATTERN,"");if(!this.fancy){let W=[];if(U)W.push(X);if(H==="warning")W.push("WARN");else if(H==="error")W.push("ERROR");else if(Y)W.push(Y.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(Z)W.push(Z.replace(/[[\]]/g,""));return W.push($),W.join(" ")}let J=x.stdout.columns||120,_="";if(H==="warning"||H==="error")_=`${Y} ${$}`;else if(H==="info"||H==="success")_=`${Y} ${Z} ${$}`;else _=`${Y} ${Z} ${M.cyan($)}`;if(!U)return _.trim();let q=G(_).trim().length,A=G(X).length,z=Math.max(1,J-2-q-A);return`${_.trim()}${" ".repeat(z)}${X}`}formatMessage(Q,X){if(X.length===1&&Array.isArray(X[0]))return Q.replace(/\{(\d+)\}/g,(H,U)=>{let G=Number.parseInt(U,10);return G<X[0].length?String(X[0][G]):H});let Y=/%([sdijfo%])/g,Z=0,$=Q.replace(Y,(H,U)=>{if(U==="%")return"%";if(Z>=X.length)return H;let G=X[Z++];switch(U){case"s":return String(G);case"d":case"i":return Number(G).toString();case"j":case"o":return JSON.stringify(G,null,2);default:return H}});if(Z<X.length)$+=` ${X.slice(Z).map((H)=>typeof H==="object"?JSON.stringify(H,null,2):String(H)).join(" ")}`;return $}async log(Q,X,...Y){let Z=new Date,$=this.formatConsoleTimestamp(Z),H=this.formatFileTimestamp(Z),U,G;if(X instanceof Error)U=X.message,G=X.stack;else U=this.formatMessage(X,Y);if(this.fancy&&!S()){let _=YZ[Q],q=this.options.showTags!==!1&&this.name?M.gray(this.formatTag(this.name)):"",A;switch(Q){case"debug":A=this.formatConsoleMessage({timestamp:$,icon:_,tag:q,message:M.gray(U),level:Q}),console.error(A);break;case"info":A=this.formatConsoleMessage({timestamp:$,icon:_,tag:q,message:U,level:Q}),console.error(A);break;case"success":A=this.formatConsoleMessage({timestamp:$,icon:_,tag:q,message:M.green(U),level:Q}),console.error(A);break;case"warning":A=this.formatConsoleMessage({timestamp:$,icon:_,tag:q,message:U,level:Q}),console.warn(A);break;case"error":if(A=this.formatConsoleMessage({timestamp:$,icon:_,tag:q,message:U,level:Q}),console.error(A),G){let z=G.split(`
|
|
3
3
|
`);for(let W of z)if(W.trim()&&!W.includes(U))console.error(this.formatConsoleMessage({timestamp:$,message:M.gray(` ${W}`),level:Q,showTimestamp:!1}))}break}}else if(!S()){if(console.error(`${H} ${this.environment}.${Q.toUpperCase()}: ${U}`),G)console.error(G)}if(!this.shouldLog(Q))return;let J=`${H} ${this.environment}.${Q.toUpperCase()}: ${U}
|
|
4
4
|
`;if(G)J+=`${G}
|
|
5
5
|
`;J=J.replace(this.ANSI_PATTERN,""),await this.writeToFile(J)}time(Q){let X=performance.now();if(this.fancy&&!S()){let Y=this.options.showTags!==!1&&this.name?M.gray(this.formatTag(this.name)):"",Z=this.formatConsoleTimestamp(new Date);console.error(this.formatConsoleMessage({timestamp:Z,icon:M.blue("\u25D0"),tag:Y,message:`${M.cyan(Q)}...`}))}return async(Y)=>{if(!this.enabled)return;let Z=performance.now(),$=Math.round(Z-X),H=`${Q} completed in ${$}ms`,U=new Date,G=this.formatConsoleTimestamp(U),_=`${this.formatFileTimestamp(U)} ${this.environment}.INFO: ${H}`;if(Y)_+=` ${JSON.stringify(Y)}`;if(_+=`
|
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
// @bun
|
|
2
|
+
import{Wf as W}from"./chunk-0hc97k0t.js";import{Fh as H}from"./chunk-hfjywbbc.js";import{Wk as $}from"./chunk-q4t568hv.js";import{spawn as E}from"child_process";import{existsSync as K}from"fs";import X from"process";function N(){return["bun.lock","bun.lockb","package-lock.json","yarn.lock","pnpm-lock.yaml","composer.lock","pantry.lock"]}function R(b){switch(b){case"bun":return{command:"bun",args:["install"]};case"npm":return{command:"npm",args:["install"]};case"yarn":return{command:"yarn",args:["install"]};case"pnpm":return{command:"pnpm",args:["install"]};case"composer":return{command:"composer",args:["update","--lock"]};case"pantry":return{command:"pantry",args:["install","--ignore-scripts","--quiet"]}}}async function P(b,q,j=300000){let{command:B,args:O}=R(b);return H().info(`\uD83D\uDD04 Regenerating lock file with ${b} (${B} ${O.join(" ")})...`),new Promise((G)=>{let J=E(B,O,{cwd:q,stdio:"pipe",env:{...X.env,CI:"true"}}),Z="",Q="",U=!1,V=setTimeout(()=>{U=!0,H().warn(`\u26A0\uFE0F ${b} install timed out after ${j/1000}s, sending SIGTERM...`),J.kill("SIGTERM"),setTimeout(()=>{if(!J.killed)H().warn(`\u26A0\uFE0F ${b} install did not exit after SIGTERM, sending SIGKILL...`),J.kill("SIGKILL")},1e4)},j);J.stdout?.on("data",(z)=>{Z+=z.toString()}),J.stderr?.on("data",(z)=>{Q+=z.toString()}),J.on("close",(z)=>{if(clearTimeout(V),U){G({success:!1,packageManager:b,message:`Lock file regeneration timed out after ${j/1000}s`});return}if(z===0)H().info(`\u2705 Lock file regenerated successfully with ${b}`),G({success:!0,packageManager:b,message:"Lock file regenerated successfully"});else{if(H().warn(`\u26A0\uFE0F ${b} install exited with code ${z}`),Q)H().warn(` stderr: ${Q.slice(0,500)}`);G({success:!1,packageManager:b,message:`Install exited with code ${z}: ${Q.slice(0,200)}`})}}),J.on("error",(z)=>{clearTimeout(V),H().warn(`\u26A0\uFE0F Failed to run ${B}: ${z.message}`),G({success:!1,packageManager:b,message:`Failed to run ${B}: ${z.message}`})})})}var Y=new Set(["deps.yaml","deps.yml","pantry.jsonc","pantry.json","pantry.toml"]);function D(b,q=X.cwd()){let j=new Set,B=!1;for(let O of b){let G=O.split("/").pop()||"";if(G==="package.json")j.add(W(q)),B=!0;if(G==="composer.json")j.add("composer");if(Y.has(G))B=!0}if(B&&A("pantry",q))j.add("pantry");return Array.from(j)}function A(b,q){let j=$("path");switch(b){case"bun":return K(j.join(q,"bun.lock"))||K(j.join(q,"bun.lockb"));case"npm":return K(j.join(q,"package-lock.json"));case"yarn":return K(j.join(q,"yarn.lock"));case"pnpm":return K(j.join(q,"pnpm-lock.yaml"));case"composer":return K(j.join(q,"composer.lock"));case"pantry":return K(j.join(q,"pantry.lock"))}}
|
|
3
|
+
export{N as Kc,P as Lc,D as Mc,A as Nc};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{le as p}from"./chunk-
|
|
2
|
+
import{le as p}from"./chunk-tzwnfagh.js";import{Fh as E}from"./chunk-hfjywbbc.js";var x=["github-actions[bot]","buddy","buddy[bot]"];function w(f,r){let e=f.authorLogins[0];if(!e)return!1;return r?e===r:x.includes(e)}async function F(f){let r=f.logger??E(),{provider:e,prNumber:t}=f;if(!p(e,"reviewThreads","listReviewThreads"))return"This provider cannot resolve review threads.";let n=await e.listReviewThreads(t),i=n.filter((R)=>!R.isResolved&&w(R,f.author));if(i.length===0)return n.length===0?"There are no review threads on this pull request.":"None of the open threads here are mine to close.";if(!p(e,"reviewThreads","resolveReviewThread"))return"This provider cannot resolve review threads.";let o=0;for(let R of i)if(await e.resolveReviewThread(t,R.id))o++;else r.warn(`Could not resolve thread ${R.id} on #${t}`);if(o===0)return`I could not close any of the ${i.length} thread(s) I opened.`;let m=o<i.length?` (${i.length-o} refused)`:"";return`Closed ${o} thread(s) I opened${m}.`}export{F as mb};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{mb as w}from"./chunk-
|
|
2
|
+
import{mb as w}from"./chunk-9fq7drn8.js";import{Ab as u,Bb as v,Cb as x,Db as y,nb as d,ob as e,pb as f,qb as g,rb as h,sb as i,tb as j,ub as k,vb as l,wb as q,xb as r,yb as s,zb as t}from"./chunk-5x4gt4c5.js";import{Eb as a,Fb as b,Gb as c}from"./chunk-q2tjkhez.js";import{Lb as m,Mb as n,Nb as o,Pb as p}from"./chunk-5yfaptmp.js";import"./chunk-rc2mk5x6.js";import"./chunk-tjc2vgwn.js";import{Ad as B,Bd as C,Cd as D,Dd as E,Ed as F,Fd as G,Gd as H,Hd as I,yd as z,zd as A}from"./chunk-vgtmrd4c.js";import"./chunk-nrr8z2z7.js";import"./chunk-xs12dtf1.js";import"./chunk-tzwnfagh.js";import"./chunk-1cpdz49v.js";import"./chunk-cgvt98pd.js";import"./chunk-e68nf7cm.js";import"./chunk-hfjywbbc.js";import"./chunk-q4t568hv.js";export{g as validateFindings,I as shouldFail,n as serializeReviewState,y as runReviewForPR,x as reviewPullRequest,j as reviewDiff,w as resolveBuddyThreads,u as renderFinding,b as renderDiffForReview,v as prepareReview,a as parseUnifiedDiff,o as parseReviewState,p as needsReview,s as loadGuidelines,G as formatReview,C as formatPretty,D as formatGithub,E as formatAgent,f as fingerprint,A as diffArgsFor,l as defaultIncludePath,h as dedupeFindings,F as countBySeverity,t as composeInstructions,B as collectLocalDiff,c as collectGitDiff,H as applySuggestion,k as anchorMap,d as SEVERITY_ORDER,m as REVIEW_STATE_VERSION,e as REVIEW_SCHEMA,z as REVIEW_FORMATS,r as MAX_GUIDELINE_CHARS,q as DEFAULT_GUIDELINE_FILES,i as DEFAULT_EXCLUDED_PATHS};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{W as a,X as b}from"./chunk-
|
|
2
|
+
import{W as a,X as b}from"./chunk-kbbqs8ae.js";import"./chunk-tjc2vgwn.js";import"./chunk-ctt9xk2j.js";import"./chunk-eseshkd0.js";import"./chunk-cwfkm7h9.js";import"./chunk-mkzmjg3f.js";import"./chunk-nrr8z2z7.js";import"./chunk-xs12dtf1.js";import"./chunk-tzwnfagh.js";import"./chunk-1cpdz49v.js";import"./chunk-cgvt98pd.js";import"./chunk-e68nf7cm.js";import"./chunk-hfjywbbc.js";import"./chunk-q4t568hv.js";export{b as renderDoctorReport,a as diagnose};
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{kd as N}from"./chunk-eseshkd0.js";import{pd as M}from"./chunk-mkzmjg3f.js";import{_d as T}from"./chunk-nrr8z2z7.js";import{de as L,ee as _}from"./chunk-5av2vnvv.js";var D=["major","minor","patch","all"],m=["merge","squash","rebase"],P=["patch-only","minor-only","security-only","all"],R=["anthropic","openai","google","openrouter","openai-compatible"],A=["low","medium","high"],S=["chill","assertive"],d=["never","critical"],q=["low","moderate","high","critical"],E=["silent","error","warn","info","debug"],w=["npm","composer","github-actions","docker","pkgx","zig","python","rust","go","ruby"],b=["major","minor","patch"],U=T.map((J)=>J.name);function K(J){return JSON.stringify(J)}function Z(J){return typeof J==="object"&&J!==null&&!Array.isArray(J)}function Y(J,B,X,$){if(X===void 0)return;if(typeof X!=="string"||!$.includes(X))J.push({path:B,message:`expected one of ${$.map(K).join(", ")}, got ${K(X)}`})}function C(J,B,X,$={}){let Q=$.min??0,W=$.integer??!1;if(X===void 0)return;if(typeof X!=="number"||!Number.isFinite(X)||X<Q){J.push({path:B,message:`expected a number >= ${Q}, got ${K(X)}`});return}if(W&&!Number.isInteger(X))J.push({path:B,message:`expected a whole number, got ${K(X)}`})}function j(J,B,X,$){if(X===void 0)return;if(!Array.isArray(X)){J.push({path:B,message:`expected an array, got ${K(X)}`});return}X.forEach((Q,W)=>Y(J,`${B}[${W}]`,Q,$))}function F(J,B,X){if(X===void 0)return;if(!Array.isArray(X)){J.push({path:B,message:`expected an array of strings, got ${K(X)}`});return}X.forEach(($,Q)=>{if(typeof $!=="string"||!$.trim())J.push({path:`${B}[${Q}]`,message:`expected a non-empty string, got ${K($)}`})})}function G(J,B,X){if(X===void 0)return;if(typeof X!=="string"){J.push({path:B,message:`expected a URL string, got ${K(X)}`});return}try{let $=new URL(X);if($.protocol!=="http:"&&$.protocol!=="https:")J.push({path:B,message:`expected an http(s) URL, got ${K(X)}`})}catch{J.push({path:B,message:`expected a valid absolute URL, got ${K(X)}`})}}function x(J,B,X){if(X===void 0)return;if(typeof X!=="string"||!X.trim()){J.push({path:B,message:`expected a cron expression string, got ${K(X)}`});return}let $=X.trim().split(/\s+/);if($.length!==5&&$.length!==6)J.push({path:B,message:`expected 5 or 6 whitespace-separated fields, got ${$.length} (${K(X)})`})}function p(J){let B=[];if(J.verbose!==void 0&&typeof J.verbose!=="boolean")B.push({path:"verbose",message:`expected a boolean, got ${K(J.verbose)}`});return Y(B,"logLevel",J.logLevel,E),C(B,"maxPRsPerRun",J.maxPRsPerRun,{min:1,integer:!0}),h(B,J),v(B,J),n(B,J),l(B,J),t(B,J),r(B,J),o(B,J),a(B,J),i(B,J),c(B,J),y(B,J),B}function f(J,B){if(B===void 0)return;if(!Z(B)){J.push({path:"registries.docker",message:`expected an object keyed by registry host, got ${K(B)}`});return}for(let[X,$]of Object.entries(B)){let Q=`registries.docker.${X}`;if(!Z($)){J.push({path:Q,message:`expected an object, got ${K($)}`});continue}for(let W of["username","passwordEnv","tokenEnv"]){let H=$[W];if(H!==void 0&&(typeof H!=="string"||!H.trim()))J.push({path:`${Q}.${W}`,message:`expected a non-empty string, got ${K(H)}`})}if($.username&&!$.passwordEnv&&!$.tokenEnv)J.push({path:`${Q}.passwordEnv`,message:"is required when a username is given"});if($.passwordEnv&&!$.username)J.push({path:`${Q}.username`,message:"is required when passwordEnv is given"})}}function y(J,B){let X=B.analysis;if(X===void 0)return;if(!Z(X)){J.push({path:"analysis",message:`expected an object, got ${K(X)}`});return}if(X.enabled!==void 0&&typeof X.enabled!=="boolean")J.push({path:"analysis.enabled",message:`expected a boolean, got ${K(X.enabled)}`});if(X.tools===void 0)return;if(!Z(X.tools)){J.push({path:"analysis.tools",message:`expected an object mapping analyzer names to booleans, got ${K(X.tools)}`});return}for(let[$,Q]of Object.entries(X.tools))if(typeof Q!=="boolean")J.push({path:`analysis.tools.${$}`,message:`expected a boolean, got ${K(Q)}`});else if(!U.includes($))J.push({path:`analysis.tools.${$}`,message:`unknown analyzer; expected one of ${U.map(K).join(", ")}`})}function h(J,B){let X=B.repository;if(X===void 0)return;if(!Z(X)){J.push({path:"repository",message:`expected an object, got ${K(X)}`});return}if(X.provider!==void 0&&!L.includes(X.provider)){let $=_[String(X.provider)];J.push({path:"repository.provider",message:$?`${K(X.provider)} support is not implemented yet \u2014 follow ${$}`:`only ${L.map(K).join(", ")} is supported, got ${K(X.provider)}`})}for(let $ of["owner","name","baseBranch","token"]){let Q=X[$];if(Q!==void 0&&typeof Q!=="string")J.push({path:`repository.${$}`,message:`expected a string, got ${K(Q)}`})}G(J,"repository.apiUrl",X.apiUrl),G(J,"repository.serverUrl",X.serverUrl)}function v(J,B){let X=B.packages;if(X===void 0)return;if(!Z(X)){J.push({path:"packages",message:`expected an object, got ${K(X)}`});return}Y(J,"packages.strategy",X.strategy,D),F(J,"packages.ignore",X.ignore),F(J,"packages.ignorePaths",X.ignorePaths),F(J,"packages.minimumReleaseAgeExclude",X.minimumReleaseAgeExclude),C(J,"packages.minimumReleaseAge",X.minimumReleaseAge,{min:0});for(let $ of["includePrerelease","excludeMajor","respectLatest","engines"]){let Q=X[$];if(Q!==void 0&&typeof Q!=="boolean")J.push({path:`packages.${$}`,message:`expected a boolean, got ${K(Q)}`})}if(X.pin!==void 0){if(!Z(X.pin))J.push({path:"packages.pin",message:`expected an object mapping package names to versions, got ${K(X.pin)}`});else for(let[$,Q]of Object.entries(X.pin))if(typeof Q!=="string"||!Q.trim())J.push({path:`packages.pin.${$}`,message:`expected a version string, got ${K(Q)}`})}if(X.groups!==void 0){if(!Array.isArray(X.groups)){J.push({path:"packages.groups",message:`expected an array of groups, got ${K(X.groups)}`});return}X.groups.forEach(($,Q)=>{let W=`packages.groups[${Q}]`;if(!Z($)){J.push({path:W,message:`expected an object, got ${K($)}`});return}if(typeof $.name!=="string"||!$.name.trim())J.push({path:`${W}.name`,message:`expected a non-empty string, got ${K($.name)}`});if(!Array.isArray($.patterns)||$.patterns.length===0)J.push({path:`${W}.patterns`,message:`expected a non-empty array of patterns, got ${K($.patterns)}`});else F(J,`${W}.patterns`,$.patterns);Y(J,`${W}.strategy`,$.strategy,D)})}g(J,X.rules)}var I=["matchPackages","matchEcosystems","matchDepTypes","matchUpdateTypes","matchFiles","matchCurrentVersion","schedule"],k=["enabled","strategy","groupName","labels","reviewers","assignees","autoMerge","autoMigrate","minimumReleaseAge","prPriority","scheduleTimezone"];function g(J,B){if(B===void 0)return;if(!Array.isArray(B)){J.push({path:"packages.rules",message:`expected an array of rules, got ${K(B)}`});return}let X=new Set([...I,...k]);B.forEach(($,Q)=>{let W=`packages.rules[${Q}]`;if(!Z($)){J.push({path:W,message:`expected an object, got ${K($)}`});return}for(let z of Object.keys($))if(!X.has(z))J.push({path:`${W}.${z}`,message:`unknown key; expected one of ${[...X].map(K).join(", ")}`});if(!I.some((z)=>$[z]!==void 0))J.push({path:W,message:'has no matchers, so it applies to every update \u2014 add `matchPackages: ["*"]` if that is intended'});if(F(J,`${W}.matchPackages`,$.matchPackages),F(J,`${W}.matchDepTypes`,$.matchDepTypes),F(J,`${W}.matchFiles`,$.matchFiles),F(J,`${W}.labels`,$.labels),F(J,`${W}.reviewers`,$.reviewers),F(J,`${W}.assignees`,$.assignees),j(J,`${W}.matchEcosystems`,$.matchEcosystems,w),j(J,`${W}.matchUpdateTypes`,$.matchUpdateTypes,b),Y(J,`${W}.strategy`,$.strategy,D),C(J,`${W}.minimumReleaseAge`,$.minimumReleaseAge,{min:0}),$.prPriority!==void 0&&typeof $.prPriority!=="number")J.push({path:`${W}.prPriority`,message:`expected a number, got ${K($.prPriority)}`});for(let z of["enabled","autoMerge","autoMigrate"])if($[z]!==void 0&&typeof $[z]!=="boolean")J.push({path:`${W}.${z}`,message:`expected a boolean, got ${K($[z])}`});for(let z of["groupName","matchCurrentVersion","scheduleTimezone"])if($[z]!==void 0&&(typeof $[z]!=="string"||!String($[z]).trim()))J.push({path:`${W}.${z}`,message:`expected a non-empty string, got ${K($[z])}`});x(J,`${W}.schedule`,$.schedule)})}function n(J,B){let X=B.pullRequest;if(X===void 0)return;if(!Z(X)){J.push({path:"pullRequest",message:`expected an object, got ${K(X)}`});return}F(J,"pullRequest.reviewers",X.reviewers),F(J,"pullRequest.assignees",X.assignees),F(J,"pullRequest.labels",X.labels);let $=X.autoMerge;if($!==void 0){if(!Z($)){J.push({path:"pullRequest.autoMerge",message:`expected an object, got ${K($)}`});return}if($.enabled!==void 0&&typeof $.enabled!=="boolean")J.push({path:"pullRequest.autoMerge.enabled",message:`expected a boolean, got ${K($.enabled)}`});if(Y(J,"pullRequest.autoMerge.strategy",$.strategy,m),F(J,"pullRequest.autoMerge.conditions",$.conditions),Array.isArray($.conditions))for(let[Q,W]of $.conditions.entries())Y(J,`pullRequest.autoMerge.conditions[${Q}]`,W,P);if($.requireGreenCI!==void 0&&typeof $.requireGreenCI!=="boolean")J.push({path:"pullRequest.autoMerge.requireGreenCI",message:`expected a boolean, got ${K($.requireGreenCI)}`});if($.optOutLabel!==void 0&&typeof $.optOutLabel!=="string")J.push({path:"pullRequest.autoMerge.optOutLabel",message:`expected a string, got ${K($.optOutLabel)}`})}}function c(J,B){let X=B.ai;if(X===void 0)return;if(!Z(X)){J.push({path:"ai",message:`expected an object, got ${K(X)}`});return}if(X.enabled!==void 0&&typeof X.enabled!=="boolean")J.push({path:"ai.enabled",message:`expected a boolean, got ${K(X.enabled)}`});Y(J,"ai.provider",X.provider,R),Y(J,"ai.effort",X.effort,A);for(let Q of["model","apiKeyEnv","baseUrl"])if(X[Q]!==void 0&&typeof X[Q]!=="string")J.push({path:`ai.${Q}`,message:`expected a string, got ${K(X[Q])}`});if(typeof X.apiKeyEnv==="string"&&/^sk-|^AIza/.test(X.apiKeyEnv))J.push({path:"ai.apiKeyEnv",message:"expected the NAME of an environment variable, not an API key"});let $=X.review;if($!==void 0)if(!Z($))J.push({path:"ai.review",message:`expected an object, got ${K($)}`});else{for(let Q of["enabled","drafts","autoReview","summaryOnly"])if($[Q]!==void 0&&typeof $[Q]!=="boolean")J.push({path:`ai.review.${Q}`,message:`expected a boolean, got ${K($[Q])}`});if(Y(J,"ai.review.profile",$.profile,S),Y(J,"ai.review.requestChangesOn",$.requestChangesOn,d),F(J,"ai.review.ignoreTitleKeywords",$.ignoreTitleKeywords),F(J,"ai.review.ignoreUsernames",$.ignoreUsernames),F(J,"ai.review.pathFilters",$.pathFilters),$.instructions!==void 0&&typeof $.instructions!=="string")J.push({path:"ai.review.instructions",message:`expected a string, got ${K($.instructions)}`});if($.guidelineFiles!==void 0&&$.guidelineFiles!==!1)F(J,"ai.review.guidelineFiles",$.guidelineFiles);if($.pathInstructions!==void 0)if(!Array.isArray($.pathInstructions))J.push({path:"ai.review.pathInstructions",message:`expected an array, got ${K($.pathInstructions)}`});else $.pathInstructions.forEach((Q,W)=>{let H=`ai.review.pathInstructions[${W}]`;if(!Z(Q)){J.push({path:H,message:`expected an object, got ${K(Q)}`});return}for(let z of["path","instructions"])if(typeof Q[z]!=="string"||!Q[z].trim())J.push({path:`${H}.${z}`,message:`expected a non-empty string, got ${K(Q[z])}`})})}if(X.maxTokensPerRun!==void 0){if(typeof X.maxTokensPerRun!=="number"||!Number.isFinite(X.maxTokensPerRun)||X.maxTokensPerRun<=0)J.push({path:"ai.maxTokensPerRun",message:`expected a positive number, got ${K(X.maxTokensPerRun)}`})}}function l(J,B){let X=B.registries;if(X===void 0)return;if(!Z(X)){J.push({path:"registries",message:`expected an object, got ${K(X)}`});return}if(f(J,X.docker),G(J,"registries.npm",X.npm),G(J,"registries.composer",X.composer),X.npmScopes!==void 0){if(!Z(X.npmScopes)){J.push({path:"registries.npmScopes",message:`expected an object keyed by scope, got ${K(X.npmScopes)}`});return}for(let[$,Q]of Object.entries(X.npmScopes)){if(!$.startsWith("@"))J.push({path:`registries.npmScopes.${$}`,message:`scope keys must start with "@", got ${K($)}`});G(J,`registries.npmScopes.${$}`,Q)}}}function t(J,B){let X=B.security;if(X===void 0)return;if(!Z(X)){J.push({path:"security",message:`expected an object, got ${K(X)}`});return}for(let $ of["enabled","prioritize"]){let Q=X[$];if(Q!==void 0&&typeof Q!=="boolean")J.push({path:`security.${$}`,message:`expected a boolean, got ${K(Q)}`})}if(X.label!==void 0&&(typeof X.label!=="string"||!X.label.trim()))J.push({path:"security.label",message:`expected a non-empty string, got ${K(X.label)}`});Y(J,"security.minimumSeverity",X.minimumSeverity,q)}function r(J,B){if(B.schedule!==void 0){if(!Z(B.schedule))J.push({path:"schedule",message:`expected an object, got ${K(B.schedule)}`});else if(x(J,"schedule.cron",B.schedule.cron),B.schedule.timezone!==void 0&&typeof B.schedule.timezone!=="string")J.push({path:"schedule.timezone",message:`expected a string, got ${K(B.schedule.timezone)}`})}let X=B.workflows?.custom;if(X===void 0)return;if(!Array.isArray(X)){J.push({path:"workflows.custom",message:`expected an array, got ${K(X)}`});return}X.forEach(($,Q)=>{let W=`workflows.custom[${Q}]`;if(!Z($)){J.push({path:W,message:`expected an object, got ${K($)}`});return}if(typeof $.name!=="string"||!$.name.trim())J.push({path:`${W}.name`,message:`expected a non-empty string, got ${K($.name)}`});x(J,`${W}.schedule`,$.schedule),Y(J,`${W}.strategy`,$.strategy,D),F(J,`${W}.reviewers`,$.reviewers),F(J,`${W}.assignees`,$.assignees),F(J,`${W}.labels`,$.labels)})}function o(J,B){let X=B.releaseNotes;if(X===void 0)return;if(!Z(X)){J.push({path:"releaseNotes",message:`expected an object, got ${K(X)}`});return}for(let $ of["enabled","sanitizeReferences","includeCompareLinks"]){let Q=X[$];if(Q!==void 0&&typeof Q!=="boolean")J.push({path:`releaseNotes.${$}`,message:`expected a boolean, got ${K(Q)}`})}C(J,"releaseNotes.maxReleases",X.maxReleases,{min:1,integer:!0}),C(J,"releaseNotes.maxBodyLength",X.maxBodyLength,{min:1,integer:!0})}function a(J,B){let X=B.dashboard;if(X===void 0)return;if(!Z(X)){J.push({path:"dashboard",message:`expected an object, got ${K(X)}`});return}if(F(J,"dashboard.labels",X.labels),F(J,"dashboard.assignees",X.assignees),C(J,"dashboard.issueNumber",X.issueNumber,{min:1,integer:!0}),X.title!==void 0&&(typeof X.title!=="string"||!X.title.trim()))J.push({path:"dashboard.title",message:`expected a non-empty string, got ${K(X.title)}`})}function i(J,B){let X=B.notifications;if(X===void 0)return;if(!Z(X)){J.push({path:"notifications",message:`expected an object, got ${K(X)}`});return}let $=(H,z)=>{if(z===void 0)return;if(!Array.isArray(z)){J.push({path:H,message:`expected an array of event names, got ${K(z)}`});return}z.forEach((V,O)=>{Y(J,`${H}[${O}]`,V,M)})},Q=(H,z)=>{if(z!==void 0&&(typeof z!=="string"||!z.trim()))J.push({path:H,message:`expected an environment variable name, got ${K(z)}`})};for(let H of["slack","discord"]){let z=X[H];if(z===void 0)continue;if(!Z(z)){J.push({path:`notifications.${H}`,message:`expected an object, got ${K(z)}`});continue}Q(`notifications.${H}.webhookEnv`,z.webhookEnv),$(`notifications.${H}.events`,z.events)}let W=X.webhooks;if(W===void 0)return;if(!Array.isArray(W)){J.push({path:"notifications.webhooks",message:`expected an array, got ${K(W)}`});return}W.forEach((H,z)=>{let V=`notifications.webhooks[${z}]`;if(!Z(H)){J.push({path:V,message:`expected an object, got ${K(H)}`});return}if(H.url===void 0)J.push({path:`${V}.url`,message:"a webhook needs a url"});else G(J,`${V}.url`,H.url);Q(`${V}.secretEnv`,H.secretEnv),$(`${V}.events`,H.events)})}function u(J){return J.map((B)=>` \u2022 ${B.path}: ${B.message}`).join(`
|
|
2
|
+
import{kd as N}from"./chunk-eseshkd0.js";import{pd as M}from"./chunk-mkzmjg3f.js";import{_d as T}from"./chunk-nrr8z2z7.js";import{de as L,ee as _}from"./chunk-tzwnfagh.js";var D=["major","minor","patch","all"],m=["merge","squash","rebase"],P=["patch-only","minor-only","security-only","all"],R=["anthropic","openai","google","openrouter","openai-compatible"],A=["low","medium","high"],S=["chill","assertive"],d=["never","critical"],q=["low","moderate","high","critical"],E=["silent","error","warn","info","debug"],w=["npm","composer","github-actions","docker","pkgx","zig","python","rust","go","ruby"],b=["major","minor","patch"],U=T.map((J)=>J.name);function K(J){return JSON.stringify(J)}function Z(J){return typeof J==="object"&&J!==null&&!Array.isArray(J)}function Y(J,B,X,$){if(X===void 0)return;if(typeof X!=="string"||!$.includes(X))J.push({path:B,message:`expected one of ${$.map(K).join(", ")}, got ${K(X)}`})}function C(J,B,X,$={}){let Q=$.min??0,W=$.integer??!1;if(X===void 0)return;if(typeof X!=="number"||!Number.isFinite(X)||X<Q){J.push({path:B,message:`expected a number >= ${Q}, got ${K(X)}`});return}if(W&&!Number.isInteger(X))J.push({path:B,message:`expected a whole number, got ${K(X)}`})}function j(J,B,X,$){if(X===void 0)return;if(!Array.isArray(X)){J.push({path:B,message:`expected an array, got ${K(X)}`});return}X.forEach((Q,W)=>Y(J,`${B}[${W}]`,Q,$))}function F(J,B,X){if(X===void 0)return;if(!Array.isArray(X)){J.push({path:B,message:`expected an array of strings, got ${K(X)}`});return}X.forEach(($,Q)=>{if(typeof $!=="string"||!$.trim())J.push({path:`${B}[${Q}]`,message:`expected a non-empty string, got ${K($)}`})})}function G(J,B,X){if(X===void 0)return;if(typeof X!=="string"){J.push({path:B,message:`expected a URL string, got ${K(X)}`});return}try{let $=new URL(X);if($.protocol!=="http:"&&$.protocol!=="https:")J.push({path:B,message:`expected an http(s) URL, got ${K(X)}`})}catch{J.push({path:B,message:`expected a valid absolute URL, got ${K(X)}`})}}function x(J,B,X){if(X===void 0)return;if(typeof X!=="string"||!X.trim()){J.push({path:B,message:`expected a cron expression string, got ${K(X)}`});return}let $=X.trim().split(/\s+/);if($.length!==5&&$.length!==6)J.push({path:B,message:`expected 5 or 6 whitespace-separated fields, got ${$.length} (${K(X)})`})}function p(J){let B=[];if(J.verbose!==void 0&&typeof J.verbose!=="boolean")B.push({path:"verbose",message:`expected a boolean, got ${K(J.verbose)}`});return Y(B,"logLevel",J.logLevel,E),C(B,"maxPRsPerRun",J.maxPRsPerRun,{min:1,integer:!0}),h(B,J),v(B,J),n(B,J),l(B,J),t(B,J),r(B,J),o(B,J),a(B,J),i(B,J),c(B,J),y(B,J),B}function f(J,B){if(B===void 0)return;if(!Z(B)){J.push({path:"registries.docker",message:`expected an object keyed by registry host, got ${K(B)}`});return}for(let[X,$]of Object.entries(B)){let Q=`registries.docker.${X}`;if(!Z($)){J.push({path:Q,message:`expected an object, got ${K($)}`});continue}for(let W of["username","passwordEnv","tokenEnv"]){let H=$[W];if(H!==void 0&&(typeof H!=="string"||!H.trim()))J.push({path:`${Q}.${W}`,message:`expected a non-empty string, got ${K(H)}`})}if($.username&&!$.passwordEnv&&!$.tokenEnv)J.push({path:`${Q}.passwordEnv`,message:"is required when a username is given"});if($.passwordEnv&&!$.username)J.push({path:`${Q}.username`,message:"is required when passwordEnv is given"})}}function y(J,B){let X=B.analysis;if(X===void 0)return;if(!Z(X)){J.push({path:"analysis",message:`expected an object, got ${K(X)}`});return}if(X.enabled!==void 0&&typeof X.enabled!=="boolean")J.push({path:"analysis.enabled",message:`expected a boolean, got ${K(X.enabled)}`});if(X.tools===void 0)return;if(!Z(X.tools)){J.push({path:"analysis.tools",message:`expected an object mapping analyzer names to booleans, got ${K(X.tools)}`});return}for(let[$,Q]of Object.entries(X.tools))if(typeof Q!=="boolean")J.push({path:`analysis.tools.${$}`,message:`expected a boolean, got ${K(Q)}`});else if(!U.includes($))J.push({path:`analysis.tools.${$}`,message:`unknown analyzer; expected one of ${U.map(K).join(", ")}`})}function h(J,B){let X=B.repository;if(X===void 0)return;if(!Z(X)){J.push({path:"repository",message:`expected an object, got ${K(X)}`});return}if(X.provider!==void 0&&!L.includes(X.provider)){let $=_[String(X.provider)];J.push({path:"repository.provider",message:$?`${K(X.provider)} support is not implemented yet \u2014 follow ${$}`:`only ${L.map(K).join(", ")} is supported, got ${K(X.provider)}`})}for(let $ of["owner","name","baseBranch","token"]){let Q=X[$];if(Q!==void 0&&typeof Q!=="string")J.push({path:`repository.${$}`,message:`expected a string, got ${K(Q)}`})}G(J,"repository.apiUrl",X.apiUrl),G(J,"repository.serverUrl",X.serverUrl)}function v(J,B){let X=B.packages;if(X===void 0)return;if(!Z(X)){J.push({path:"packages",message:`expected an object, got ${K(X)}`});return}Y(J,"packages.strategy",X.strategy,D),F(J,"packages.ignore",X.ignore),F(J,"packages.ignorePaths",X.ignorePaths),F(J,"packages.minimumReleaseAgeExclude",X.minimumReleaseAgeExclude),C(J,"packages.minimumReleaseAge",X.minimumReleaseAge,{min:0});for(let $ of["includePrerelease","excludeMajor","respectLatest","engines"]){let Q=X[$];if(Q!==void 0&&typeof Q!=="boolean")J.push({path:`packages.${$}`,message:`expected a boolean, got ${K(Q)}`})}if(X.pin!==void 0){if(!Z(X.pin))J.push({path:"packages.pin",message:`expected an object mapping package names to versions, got ${K(X.pin)}`});else for(let[$,Q]of Object.entries(X.pin))if(typeof Q!=="string"||!Q.trim())J.push({path:`packages.pin.${$}`,message:`expected a version string, got ${K(Q)}`})}if(X.groups!==void 0){if(!Array.isArray(X.groups)){J.push({path:"packages.groups",message:`expected an array of groups, got ${K(X.groups)}`});return}X.groups.forEach(($,Q)=>{let W=`packages.groups[${Q}]`;if(!Z($)){J.push({path:W,message:`expected an object, got ${K($)}`});return}if(typeof $.name!=="string"||!$.name.trim())J.push({path:`${W}.name`,message:`expected a non-empty string, got ${K($.name)}`});if(!Array.isArray($.patterns)||$.patterns.length===0)J.push({path:`${W}.patterns`,message:`expected a non-empty array of patterns, got ${K($.patterns)}`});else F(J,`${W}.patterns`,$.patterns);Y(J,`${W}.strategy`,$.strategy,D)})}g(J,X.rules)}var I=["matchPackages","matchEcosystems","matchDepTypes","matchUpdateTypes","matchFiles","matchCurrentVersion","schedule"],k=["enabled","strategy","groupName","labels","reviewers","assignees","autoMerge","autoMigrate","minimumReleaseAge","prPriority","scheduleTimezone"];function g(J,B){if(B===void 0)return;if(!Array.isArray(B)){J.push({path:"packages.rules",message:`expected an array of rules, got ${K(B)}`});return}let X=new Set([...I,...k]);B.forEach(($,Q)=>{let W=`packages.rules[${Q}]`;if(!Z($)){J.push({path:W,message:`expected an object, got ${K($)}`});return}for(let z of Object.keys($))if(!X.has(z))J.push({path:`${W}.${z}`,message:`unknown key; expected one of ${[...X].map(K).join(", ")}`});if(!I.some((z)=>$[z]!==void 0))J.push({path:W,message:'has no matchers, so it applies to every update \u2014 add `matchPackages: ["*"]` if that is intended'});if(F(J,`${W}.matchPackages`,$.matchPackages),F(J,`${W}.matchDepTypes`,$.matchDepTypes),F(J,`${W}.matchFiles`,$.matchFiles),F(J,`${W}.labels`,$.labels),F(J,`${W}.reviewers`,$.reviewers),F(J,`${W}.assignees`,$.assignees),j(J,`${W}.matchEcosystems`,$.matchEcosystems,w),j(J,`${W}.matchUpdateTypes`,$.matchUpdateTypes,b),Y(J,`${W}.strategy`,$.strategy,D),C(J,`${W}.minimumReleaseAge`,$.minimumReleaseAge,{min:0}),$.prPriority!==void 0&&typeof $.prPriority!=="number")J.push({path:`${W}.prPriority`,message:`expected a number, got ${K($.prPriority)}`});for(let z of["enabled","autoMerge","autoMigrate"])if($[z]!==void 0&&typeof $[z]!=="boolean")J.push({path:`${W}.${z}`,message:`expected a boolean, got ${K($[z])}`});for(let z of["groupName","matchCurrentVersion","scheduleTimezone"])if($[z]!==void 0&&(typeof $[z]!=="string"||!String($[z]).trim()))J.push({path:`${W}.${z}`,message:`expected a non-empty string, got ${K($[z])}`});x(J,`${W}.schedule`,$.schedule)})}function n(J,B){let X=B.pullRequest;if(X===void 0)return;if(!Z(X)){J.push({path:"pullRequest",message:`expected an object, got ${K(X)}`});return}F(J,"pullRequest.reviewers",X.reviewers),F(J,"pullRequest.assignees",X.assignees),F(J,"pullRequest.labels",X.labels);let $=X.autoMerge;if($!==void 0){if(!Z($)){J.push({path:"pullRequest.autoMerge",message:`expected an object, got ${K($)}`});return}if($.enabled!==void 0&&typeof $.enabled!=="boolean")J.push({path:"pullRequest.autoMerge.enabled",message:`expected a boolean, got ${K($.enabled)}`});if(Y(J,"pullRequest.autoMerge.strategy",$.strategy,m),F(J,"pullRequest.autoMerge.conditions",$.conditions),Array.isArray($.conditions))for(let[Q,W]of $.conditions.entries())Y(J,`pullRequest.autoMerge.conditions[${Q}]`,W,P);if($.requireGreenCI!==void 0&&typeof $.requireGreenCI!=="boolean")J.push({path:"pullRequest.autoMerge.requireGreenCI",message:`expected a boolean, got ${K($.requireGreenCI)}`});if($.optOutLabel!==void 0&&typeof $.optOutLabel!=="string")J.push({path:"pullRequest.autoMerge.optOutLabel",message:`expected a string, got ${K($.optOutLabel)}`})}}function c(J,B){let X=B.ai;if(X===void 0)return;if(!Z(X)){J.push({path:"ai",message:`expected an object, got ${K(X)}`});return}if(X.enabled!==void 0&&typeof X.enabled!=="boolean")J.push({path:"ai.enabled",message:`expected a boolean, got ${K(X.enabled)}`});Y(J,"ai.provider",X.provider,R),Y(J,"ai.effort",X.effort,A);for(let Q of["model","apiKeyEnv","baseUrl"])if(X[Q]!==void 0&&typeof X[Q]!=="string")J.push({path:`ai.${Q}`,message:`expected a string, got ${K(X[Q])}`});if(typeof X.apiKeyEnv==="string"&&/^sk-|^AIza/.test(X.apiKeyEnv))J.push({path:"ai.apiKeyEnv",message:"expected the NAME of an environment variable, not an API key"});let $=X.review;if($!==void 0)if(!Z($))J.push({path:"ai.review",message:`expected an object, got ${K($)}`});else{for(let Q of["enabled","drafts","autoReview","summaryOnly"])if($[Q]!==void 0&&typeof $[Q]!=="boolean")J.push({path:`ai.review.${Q}`,message:`expected a boolean, got ${K($[Q])}`});if(Y(J,"ai.review.profile",$.profile,S),Y(J,"ai.review.requestChangesOn",$.requestChangesOn,d),F(J,"ai.review.ignoreTitleKeywords",$.ignoreTitleKeywords),F(J,"ai.review.ignoreUsernames",$.ignoreUsernames),F(J,"ai.review.pathFilters",$.pathFilters),$.instructions!==void 0&&typeof $.instructions!=="string")J.push({path:"ai.review.instructions",message:`expected a string, got ${K($.instructions)}`});if($.guidelineFiles!==void 0&&$.guidelineFiles!==!1)F(J,"ai.review.guidelineFiles",$.guidelineFiles);if($.pathInstructions!==void 0)if(!Array.isArray($.pathInstructions))J.push({path:"ai.review.pathInstructions",message:`expected an array, got ${K($.pathInstructions)}`});else $.pathInstructions.forEach((Q,W)=>{let H=`ai.review.pathInstructions[${W}]`;if(!Z(Q)){J.push({path:H,message:`expected an object, got ${K(Q)}`});return}for(let z of["path","instructions"])if(typeof Q[z]!=="string"||!Q[z].trim())J.push({path:`${H}.${z}`,message:`expected a non-empty string, got ${K(Q[z])}`})})}if(X.maxTokensPerRun!==void 0){if(typeof X.maxTokensPerRun!=="number"||!Number.isFinite(X.maxTokensPerRun)||X.maxTokensPerRun<=0)J.push({path:"ai.maxTokensPerRun",message:`expected a positive number, got ${K(X.maxTokensPerRun)}`})}}function l(J,B){let X=B.registries;if(X===void 0)return;if(!Z(X)){J.push({path:"registries",message:`expected an object, got ${K(X)}`});return}if(f(J,X.docker),G(J,"registries.npm",X.npm),G(J,"registries.composer",X.composer),X.npmScopes!==void 0){if(!Z(X.npmScopes)){J.push({path:"registries.npmScopes",message:`expected an object keyed by scope, got ${K(X.npmScopes)}`});return}for(let[$,Q]of Object.entries(X.npmScopes)){if(!$.startsWith("@"))J.push({path:`registries.npmScopes.${$}`,message:`scope keys must start with "@", got ${K($)}`});G(J,`registries.npmScopes.${$}`,Q)}}}function t(J,B){let X=B.security;if(X===void 0)return;if(!Z(X)){J.push({path:"security",message:`expected an object, got ${K(X)}`});return}for(let $ of["enabled","prioritize"]){let Q=X[$];if(Q!==void 0&&typeof Q!=="boolean")J.push({path:`security.${$}`,message:`expected a boolean, got ${K(Q)}`})}if(X.label!==void 0&&(typeof X.label!=="string"||!X.label.trim()))J.push({path:"security.label",message:`expected a non-empty string, got ${K(X.label)}`});Y(J,"security.minimumSeverity",X.minimumSeverity,q)}function r(J,B){if(B.schedule!==void 0){if(!Z(B.schedule))J.push({path:"schedule",message:`expected an object, got ${K(B.schedule)}`});else if(x(J,"schedule.cron",B.schedule.cron),B.schedule.timezone!==void 0&&typeof B.schedule.timezone!=="string")J.push({path:"schedule.timezone",message:`expected a string, got ${K(B.schedule.timezone)}`})}let X=B.workflows?.custom;if(X===void 0)return;if(!Array.isArray(X)){J.push({path:"workflows.custom",message:`expected an array, got ${K(X)}`});return}X.forEach(($,Q)=>{let W=`workflows.custom[${Q}]`;if(!Z($)){J.push({path:W,message:`expected an object, got ${K($)}`});return}if(typeof $.name!=="string"||!$.name.trim())J.push({path:`${W}.name`,message:`expected a non-empty string, got ${K($.name)}`});x(J,`${W}.schedule`,$.schedule),Y(J,`${W}.strategy`,$.strategy,D),F(J,`${W}.reviewers`,$.reviewers),F(J,`${W}.assignees`,$.assignees),F(J,`${W}.labels`,$.labels)})}function o(J,B){let X=B.releaseNotes;if(X===void 0)return;if(!Z(X)){J.push({path:"releaseNotes",message:`expected an object, got ${K(X)}`});return}for(let $ of["enabled","sanitizeReferences","includeCompareLinks"]){let Q=X[$];if(Q!==void 0&&typeof Q!=="boolean")J.push({path:`releaseNotes.${$}`,message:`expected a boolean, got ${K(Q)}`})}C(J,"releaseNotes.maxReleases",X.maxReleases,{min:1,integer:!0}),C(J,"releaseNotes.maxBodyLength",X.maxBodyLength,{min:1,integer:!0})}function a(J,B){let X=B.dashboard;if(X===void 0)return;if(!Z(X)){J.push({path:"dashboard",message:`expected an object, got ${K(X)}`});return}if(F(J,"dashboard.labels",X.labels),F(J,"dashboard.assignees",X.assignees),C(J,"dashboard.issueNumber",X.issueNumber,{min:1,integer:!0}),X.title!==void 0&&(typeof X.title!=="string"||!X.title.trim()))J.push({path:"dashboard.title",message:`expected a non-empty string, got ${K(X.title)}`})}function i(J,B){let X=B.notifications;if(X===void 0)return;if(!Z(X)){J.push({path:"notifications",message:`expected an object, got ${K(X)}`});return}let $=(H,z)=>{if(z===void 0)return;if(!Array.isArray(z)){J.push({path:H,message:`expected an array of event names, got ${K(z)}`});return}z.forEach((V,O)=>{Y(J,`${H}[${O}]`,V,M)})},Q=(H,z)=>{if(z!==void 0&&(typeof z!=="string"||!z.trim()))J.push({path:H,message:`expected an environment variable name, got ${K(z)}`})};for(let H of["slack","discord"]){let z=X[H];if(z===void 0)continue;if(!Z(z)){J.push({path:`notifications.${H}`,message:`expected an object, got ${K(z)}`});continue}Q(`notifications.${H}.webhookEnv`,z.webhookEnv),$(`notifications.${H}.events`,z.events)}let W=X.webhooks;if(W===void 0)return;if(!Array.isArray(W)){J.push({path:"notifications.webhooks",message:`expected an array, got ${K(W)}`});return}W.forEach((H,z)=>{let V=`notifications.webhooks[${z}]`;if(!Z(H)){J.push({path:V,message:`expected an object, got ${K(H)}`});return}if(H.url===void 0)J.push({path:`${V}.url`,message:"a webhook needs a url"});else G(J,`${V}.url`,H.url);Q(`${V}.secretEnv`,H.secretEnv),$(`${V}.events`,H.events)})}function u(J){return J.map((B)=>` \u2022 ${B.path}: ${B.message}`).join(`
|
|
3
3
|
`)}function $J(J){let B=p(J);if(B.length===0)return;throw new N(`Invalid buddy configuration (${B.length} issue${B.length===1?"":"s"}):
|
|
4
4
|
${u(B)}`,B[0].path)}
|
|
5
5
|
export{p as Sc,u as Tc,$J as Uc};
|
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{_c as Z}from"./chunk-
|
|
2
|
+
import{_c as Z}from"./chunk-3cab6vqx.js";import{Dh as _}from"./chunk-hfjywbbc.js";import Y from"process";class L{jobs=new Map;timers=new Map;logger;isRunning=!1;constructor(q=!1){this.logger=q?_.verbose():_.quiet()}addJob(q){this.jobs.set(q.id,q),this.scheduleJob(q),this.logger.info(`Scheduled job '${q.name}' with cron: ${q.schedule.cron}`)}removeJob(q){let C=this.timers.get(q);if(C)clearTimeout(C),this.timers.delete(q);this.jobs.delete(q),this.logger.info(`Removed scheduled job: ${q}`)}start(){if(this.isRunning){this.logger.warn("Scheduler is already running");return}this.isRunning=!0,this.logger.info("\uD83D\uDD52 Buddy Scheduler started");for(let q of this.jobs.values())if(this.scheduleJob(q),q.schedule.runOnStartup)this.logger.info(`Running startup job: ${q.name}`),setImmediate(()=>this.runJob(q));Y.on("SIGINT",()=>this.stop()),Y.on("SIGTERM",()=>this.stop())}stop(){if(!this.isRunning)return;this.isRunning=!1,this.logger.info("\uD83D\uDED1 Stopping Buddy Scheduler...");for(let q of this.timers.values())clearTimeout(q);this.timers.clear(),this.logger.success("\u2705 Buddy Scheduler stopped"),Y.exit(0)}getJobStatus(q){return this.jobs.get(q)}getAllJobs(){return Array.from(this.jobs.values())}scheduleJob(q){let C=this.timers.get(q.id);if(C)clearTimeout(C);let D=this.getNextRunTime(q.schedule.cron,q.schedule.timezone);if(q.nextRun=D||void 0,D){let G=D.getTime()-Date.now(),F=setTimeout(()=>{this.runJob(q),this.scheduleJob(q)},G);this.timers.set(q.id,F),this.logger.debug(`Job '${q.name}' scheduled for ${D.toISOString()}`)}}async runJob(q){if(q.status==="running"){this.logger.warn(`Job '${q.name}' is already running, skipping`);return}q.status="running",q.lastRun=new Date,this.logger.info(`\uD83D\uDE80 Running scheduled job: ${q.name}`);let C=Date.now(),D=q.schedule.maxRuntime||1800000;try{let G=new Promise((Q,U)=>{setTimeout(()=>U(Error("Job timeout")),D)}),F=this.executeJob(q);await Promise.race([F,G]);let J=Date.now()-C;q.status="idle",this.logger.success(`\u2705 Job '${q.name}' completed in ${J}ms`)}catch(G){q.status="error",this.logger.error(`\u274C Job '${q.name}' failed:`,G)}}async executeJob(q){let C=new Z(q.config),D=await C.scanForUpdates();if(D.updates.length===0){this.logger.info("No dependency updates found");return}if(this.logger.info(`Found ${D.updates.length} dependency updates`),q.config.repository&&q.config.pullRequest)await C.createPullRequests(D),this.logger.success(`Created pull requests for ${D.groups.length} update groups`);else this.logger.info("Repository not configured, skipping PR creation")}getNextRunTime(q,C){try{return this.parseCronExpression(q,C)}catch(D){return this.logger.error(`Invalid cron expression '${q}':`,D),null}}parseCronExpression(q,C){let D=q.trim().split(/\s+/);if(D.length!==5)throw Error("Cron expression must have 5 parts: minute hour day month dayOfWeek");let[G,F,J,Q,U]=D,K=new Date,V=C?this.timezoneOffsetMinutes(K,C):0;if(C)this.logger.debug(`Using timezone: ${C} (offset ${V} minutes)`);let X=new Date(K.getTime()+V*60*1000);X.setSeconds(0,0);let $=this.parseCronField(F,0,23),B=this.parseCronField(G,0,59);if($.length>0&&B.length>0){if(X.setHours($[0],B[0],0,0),X.getTime()-V*60*1000<=K.getTime())X.setDate(X.getDate()+1);return new Date(X.getTime()-V*60*1000)}return new Date(K.getTime()+3600000)}timezoneOffsetMinutes(q,C){try{let D=new Date(q.toLocaleString("en-US",{timeZone:C})),G=new Date(q.toLocaleString("en-US"));return Math.round((D.getTime()-G.getTime())/60000)}catch{return this.logger.warn(`\u26A0\uFE0F Unknown timezone "${C}", scheduling in host time instead`),0}}parseCronField(q,C,D){if(q==="*")return Array.from({length:D-C+1},(F,J)=>C+J);if(q.includes(","))return q.split(",").map(Number).filter((F)=>Number.isFinite(F)&&F>=C&&F<=D);if(q.includes("-")){let F=q.split("-").map(Number),J=F[0],Q=F[1];if(F.length!==2||!Number.isFinite(J)||!Number.isFinite(Q)||Q<J)return[];return Array.from({length:Q-J+1},(U,K)=>J+K).filter((U)=>U>=C&&U<=D)}if(q.includes("/")){let[F,J]=q.split("/"),Q=Number(J);if(!Number.isFinite(Q)||Q<=0)return[];if(F==="*")return Array.from({length:D-C+1},(K,V)=>C+V).filter((K,V)=>V%Q===0);let U=Number(F);return Number.isFinite(U)?[U].filter((K)=>K>=C&&K<=D):[]}let G=Number(q);return Number.isFinite(G)&&G>=C&&G<=D?[G]:[]}static createJobFromConfig(q,C="default"){let D={cron:q.schedule?.cron||"0 2 * * 1",timezone:q.schedule?.timezone,runOnStartup:!1,maxRuntime:1800000};return{id:C,name:`Buddy Dependency Updates (${C})`,schedule:D,status:"idle",config:q}}static PRESETS={DAILY:"0 2 * * *",WEEKLY:"0 2 * * 1",WEEKDAYS:"0 2 * * 1-5",TWICE_WEEKLY:"0 2 * * 1,4",MONTHLY:"0 2 1 * *",HOURLY:"0 * * * *",CUSTOM:(q,C,D="*")=>`${q} ${C} * * ${D}`}}
|
|
3
3
|
export{L as Da};
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{Kc as T,Lc as v,Mc as y}from"./chunk-
|
|
2
|
+
import{Kc as T,Lc as v,Mc as y}from"./chunk-8ycrg9gp.js";import{Rf as D,Sf as R,Tf as S}from"./chunk-c8rzx3a1.js";import{oh as P}from"./chunk-193abzy6.js";import{zh as U}from"./chunk-e68nf7cm.js";import{Bh as L,Ch as x,Fh as F}from"./chunk-hfjywbbc.js";import{Buffer as W}from"buffer";import{spawn as k}from"child_process";import q from"process";var B=/\b(?:gh[pousr]_[A-Z0-9_]{20,}|github_pat_[A-Z0-9_]{20,}|[A-Z0-9]{40,})\b/gi;function E(Q){return Q==="completed"||Q==="in_progress"?Q:"queued"}function w(Q){if(typeof Q!=="string")return null;if(Q==="success"||Q==="cancelled")return Q;if(Q==="failure"||Q==="timed_out"||Q==="action_required")return"failure";return"skipped"}function g(Q,X){let Y=Q.replace(B,"[REDACTED]");if(X&&X.length>=8)Y=Y.split(X).join("[REDACTED]");return Y}class I extends Error{constructor(Q){super(Q);this.name="LockfileRegenerationError"}}function f(Q){let X=`${x(Q)} ${Q?.message??""}`;return/not permitted to create or approve pull requests/i.test(X)||Q?.status===403&&/pull/i.test(X)}class N{token;owner;repo;hasWorkflowPermissions;workflowToken;apiUrl;cache={pullRequests:new Map,issues:new Map};cacheTTL=120000;logger;constructor(Q,X,Y,Z=!1,$,J,K){this.token=Q;this.owner=X;this.repo=Y;this.hasWorkflowPermissions=Z;this.workflowToken=$;this.apiUrl=J?J.replace(/\/+$/,""):P(),this.logger=K??F()}capabilities(){return{pinIssues:!0,checkRuns:!0,inlineReviewComments:!0,reviewSuggestions:!0,nativeAutoMerge:!0,commentReactions:!0,ciLogs:!0,ciRuns:!0,reviewThreads:!0,teamReviewers:!0,draftPullRequests:!0,permissionLookup:!0,branchHousekeeping:!0,reopenPullRequests:!0,labels:!0}}isCacheValid(Q){return Date.now()-Q<this.cacheTTL}clearCache(){this.cache.pullRequests.clear(),this.cache.issues.clear()}async branchExists(Q){try{return await this.apiRequest(`GET /repos/${this.owner}/${this.repo}/git/ref/heads/${Q}`),!0}catch(X){if(X.message?.includes("404"))return!1;return this.logger.warn(`\u26A0\uFE0F Error checking branch ${Q}: ${x(X)}`),!1}}async createBranch(Q,X){try{let Z=(await this.apiRequest(`GET /repos/${this.owner}/${this.repo}/git/ref/heads/${X}`)).object.sha;await this.apiRequest(`POST /repos/${this.owner}/${this.repo}/git/refs`,{ref:`refs/heads/${Q}`,sha:Z}),this.logger.info(`\u2705 Created branch ${Q} from ${X}`)}catch(Y){throw this.logger.error(`\u274C Failed to create branch ${Q}: ${x(Y)}`),Y}}async commitChanges(Q,X,Y,Z="main"){try{await this.commitChangesWithGit(Q,X,Y,Z)}catch($){if($ instanceof I||$ instanceof D)throw $;this.logger.warn(`\u26A0\uFE0F Git CLI commit failed, falling back to GitHub API: ${$}`),await this.commitChangesWithAPI(Q,X,Y,Z)}}async commitChangesWithGit(Q,X,Y,Z="main"){try{let $=Y.filter((V)=>V.path.includes(".github/workflows/")),J=Y.filter((V)=>!V.path.includes(".github/workflows/"));if($.length>0&&!this.hasWorkflowPermissions)if(this.logger.warn(`\u26A0\uFE0F Detected ${$.length} workflow file(s). These require elevated permissions.`),this.logger.warn(`\u26A0\uFE0F Workflow files: ${$.map((V)=>V.path).join(", ")}`),this.logger.warn("\u2139\uFE0F Workflow files will be skipped in this commit. BUDDY_TOKEN not detected or lacks workflow permissions."),J.length>0)this.logger.info(`\uD83D\uDCDD Committing ${J.length} non-workflow files...`),Y=J;else{this.logger.warn("\u26A0\uFE0F All files are workflow files. No files will be committed in this PR."),this.logger.warn("\uD83D\uDCA1 To update workflow files, ensure BUDDY_TOKEN is set with workflow:write permissions."),this.logger.info('\uD83D\uDCDD Creating empty commit to avoid "No commits between branches" error...');try{await this.runCommand("git",["commit","--allow-empty","-m","Workflow files require elevated permissions - no changes committed"]),this.logger.info("\u2705 Created empty commit for workflow-only PR")}catch(V){this.logger.warn(`\u26A0\uFE0F Failed to create empty commit: ${V}`);try{let C=Bun.file("README.md");if(await C.exists()){let G=`${await C.text()}
|
|
3
3
|
|
|
4
4
|
<!-- Updated by Buddy -->
|
|
5
5
|
`;await Bun.write("README.md",G),await this.runCommand("git",["add","README.md"]),await this.runCommand("git",["commit","-m","Update README for workflow-only PR"]),this.logger.info("\u2705 Created README update for workflow-only PR")}}catch(j){this.logger.error(`\u274C Failed to create any commit: ${j}`)}}return}else if($.length>0)this.logger.info(`\u2705 Including ${$.length} workflow file(s) with elevated permissions`);try{await this.runCommand("git",["config","user.name","github-actions[bot]"]),await this.runCommand("git",["config","user.email","41898282+github-actions[bot]@users.noreply.github.com"]),this.logger.info("\u2705 Git identity configured for github-actions[bot]")}catch(V){this.logger.warn("\u26A0\uFE0F Failed to configure Git identity:",V)}await this.runCommand("git",["fetch","origin"]),this.logger.info(`\uD83D\uDD04 Recreating ${Q} from origin/${Z} (Renovate-style)...`);try{await this.runCommand("git",["checkout",Q])}catch{try{await this.runCommand("git",["checkout","-b",Q,`origin/${Q}`])}catch{await this.runCommand("git",["checkout","-b",Q])}}await this.runCommand("git",["reset","--hard",`origin/${Z}`]),await this.runCommand("git",["clean","-fd"]),this.logger.info(`\u2705 Reset ${Q} to origin/${Z}`),await S(Y,async(V)=>{try{return await this.runCommand("git",["cat-file","-e",`origin/${Z}:${V}`]),!0}catch{return!1}});for(let V of Y){let j=R(V.path);if(q.env.NODE_ENV==="test"||q.env.BUN_ENV==="test"){if(["package.json","bun.lock","bun.lockb","package-lock.json","yarn.lock"].includes(j)&&V.content==='{"name":"x"}'){this.logger.warn(`\u26A0\uFE0F Skipping test file write to ${j} to prevent overwriting project files`);continue}}if(V.type==="delete")try{await this.runCommand("git",["rm",j])}catch{}else await Bun.write(j,V.content),await this.runCommand("git",["add",j])}if(!(q.env.NODE_ENV==="test"||q.env.BUN_ENV==="test")){let V=Y.map((C)=>C.path.replace(/^\.\//,"").replace(/^\/+/,"")),j=y(V);if(j.length>0){this.logger.info(`\uD83D\uDD12 Regenerating lock files for: ${j.join(", ")}`);let C=q.cwd(),M=[];for(let G of j)try{let H=await v(G,C);if(H.success)for(let z of T())try{await this.runCommand("git",["add",z])}catch{}else M.push(`${G}: ${H.message}`)}catch(H){M.push(`${G}: ${H instanceof Error?H.message:String(H)}`)}if(M.length>0){let G=M.map((H)=>` - ${H}`).join(`
|
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{_c as a}from"./chunk-
|
|
2
|
+
import{_c as a}from"./chunk-3cab6vqx.js";import"./chunk-phfmnnne.js";import"./chunk-r763e19p.js";import"./chunk-be629jhq.js";import"./chunk-pkr6905p.js";import"./chunk-eseshkd0.js";import"./chunk-11hdrnf6.js";import"./chunk-mkzmjg3f.js";import"./chunk-tzwnfagh.js";import"./chunk-ytmxd5fk.js";import"./chunk-b9escac0.js";import"./chunk-g30dr44w.js";import"./chunk-2et8yavs.js";import"./chunk-txtrpypt.js";import"./chunk-8hjvthz4.js";import"./chunk-yngahb11.js";import"./chunk-08x5b93v.js";import"./chunk-p6qbqsyp.js";import"./chunk-1cpdz49v.js";import"./chunk-cgvt98pd.js";import"./chunk-c8rzx3a1.js";import"./chunk-0hc97k0t.js";import"./chunk-3901s7h9.js";import"./chunk-jtxcr5yw.js";import"./chunk-qd2s51gc.js";import"./chunk-193abzy6.js";import"./chunk-e68nf7cm.js";import"./chunk-hfjywbbc.js";import"./chunk-g24hav8e.js";import"./chunk-q4t568hv.js";export{a as Buddy};
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{ec as Z}from"./chunk-tjc2vgwn.js";import{Sc as X}from"./chunk-
|
|
2
|
+
import{ec as Z}from"./chunk-tjc2vgwn.js";import{Sc as X}from"./chunk-ctt9xk2j.js";import{Nd as x,_d as V}from"./chunk-nrr8z2z7.js";import{he as U,ie as Y}from"./chunk-tzwnfagh.js";import H from"process";var K=[["actionlint","actionlint"],["shellcheck","shellcheck"],["hadolint","hadolint"],["markdownlint","markdownlint"]];async function T(j,J={}){let W=J.env??H.env,Q=J.cwd??H.cwd(),F=J.hasCommand??x,G=[];G.push({name:"bun",status:"ok",detail:`Bun ${Bun.version}`});let C=await Bun.file(`${Q}/.git/HEAD`).exists();G.push(C?{name:"git repository",status:"ok",detail:Q}:{name:"git repository",status:"fail",detail:`${Q} is not a git repository`,remediation:"Run buddy from inside a repository, or run `git init`."});let $=X(j);G.push($.length===0?{name:"configuration",status:"ok",detail:"valid"}:{name:"configuration",status:"fail",detail:`${$.length} problem(s): ${$.slice(0,3).map((q)=>`${q.path} ${q.message}`).join("; ")}`,remediation:"Fix the paths reported above in buddy.config.ts."});let P=Boolean(j.repository?.owner&&j.repository.name);G.push(P?{name:"repository config",status:"ok",detail:`${j.repository.owner}/${j.repository.name}`}:{name:"repository config",status:"warn",detail:"owner and name are not set",remediation:"Set repository.owner and repository.name, or run in Actions where GITHUB_REPOSITORY is available. Local review works without them."});let B=j.repository?.provider??"github",D=j.repository?.token?{token:j.repository.token,source:"repository.token"}:Y(B,W);G.push(D?{name:"git token",status:"ok",detail:`found in ${D.source}`}:{name:"git token",status:"warn",detail:"no token found",remediation:`Set one of ${(U[B]??[]).join(", ")}. Local review does not need one.`});let b=Z(j,W);G.push(b?{name:"ai provider",status:"ok",detail:`${b.provider} via ${b.apiKeyEnv}`}:{name:"ai provider",status:"warn",detail:"no API key found",remediation:"Set ANTHROPIC_API_KEY (or OPENAI_API_KEY / GOOGLE_API_KEY). Dependency updates and static analysis work without one."});for(let[q,M]of K){let I=await F(M);G.push(I?{name:`analyzer: ${q}`,status:"ok",detail:`${M} found`}:{name:`analyzer: ${q}`,status:"warn",detail:`${M} not installed`,remediation:`Install ${M} to enable the ${q} analyzer. Reviews run without it and report it as skipped.`})}let w=V.filter((q)=>!K.some(([M])=>M===q.name)).map((q)=>q.name);return G.push({name:"native analyzers",status:"ok",detail:`${w.join(", ")} \u2014 always available`}),{checks:G,healthy:!G.some((q)=>q.status==="fail")}}var S={ok:"\u2705",warn:"\u26A0\uFE0F ",fail:"\u274C"};function E(j){let J=["","Buddy environment",""];for(let F of j.checks)if(J.push(`${S[F.status]} ${F.name}: ${F.detail}`),F.remediation)J.push(` \u2192 ${F.remediation}`);let W=j.checks.filter((F)=>F.status==="fail").length,Q=j.checks.filter((F)=>F.status==="warn").length;return J.push(""),J.push(j.healthy?`Ready. ${Q} optional capability/capabilities unavailable.`:`${W} problem(s) must be fixed before buddy can run.`),`${J.join(`
|
|
3
3
|
`)}
|
|
4
4
|
`}
|
|
5
5
|
export{T as W,E as X};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{Da as a}from"./chunk-
|
|
2
|
+
import{Da as a}from"./chunk-dm5yktev.js";import"./chunk-3cab6vqx.js";import"./chunk-phfmnnne.js";import"./chunk-r763e19p.js";import"./chunk-be629jhq.js";import"./chunk-pkr6905p.js";import"./chunk-eseshkd0.js";import"./chunk-11hdrnf6.js";import"./chunk-mkzmjg3f.js";import"./chunk-tzwnfagh.js";import"./chunk-ytmxd5fk.js";import"./chunk-b9escac0.js";import"./chunk-g30dr44w.js";import"./chunk-2et8yavs.js";import"./chunk-txtrpypt.js";import"./chunk-8hjvthz4.js";import"./chunk-yngahb11.js";import"./chunk-08x5b93v.js";import"./chunk-p6qbqsyp.js";import"./chunk-1cpdz49v.js";import"./chunk-cgvt98pd.js";import"./chunk-c8rzx3a1.js";import"./chunk-0hc97k0t.js";import"./chunk-3901s7h9.js";import"./chunk-jtxcr5yw.js";import"./chunk-qd2s51gc.js";import"./chunk-193abzy6.js";import"./chunk-e68nf7cm.js";import"./chunk-hfjywbbc.js";import"./chunk-g24hav8e.js";import"./chunk-q4t568hv.js";export{a as Scheduler};
|
|
@@ -1,10 +1,10 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{od as
|
|
3
|
-
`);for(let z of
|
|
2
|
+
import{od as R}from"./chunk-cwfkm7h9.js";import{le as F,me as A}from"./chunk-tzwnfagh.js";import{sf as S}from"./chunk-08x5b93v.js";import{If as L}from"./chunk-p6qbqsyp.js";import{Ch as K,Fh as O}from"./chunk-hfjywbbc.js";import{Wk as P}from"./chunk-q4t568hv.js";var b=[{kind:"lockfile-drift",mechanical:!0,patterns:[/lockfile had changes, but lockfile is frozen/i,/your lockfile does not satisfy your workspace/i,/the lockfile (?:is|was) out of date/i,/npm ci can only install packages when your package\.json and package-lock\.json .* are in sync/i,/composer\.lock is not up to date/i]},{kind:"flake",mechanical:!0,patterns:[/\bECONNRESET\b|\bETIMEDOUT\b|\bENOTFOUND\b|\bEAI_AGAIN\b/,/socket hang up/i,/502 Bad Gateway|503 Service Unavailable|504 Gateway Time-?out/i,/rate limit exceeded/i,/the runner has received a shutdown signal/i]},{kind:"install",mechanical:!1,patterns:[/could not resolve (?:dependency|host)/i,/no matching version found for/i,/unable to resolve dependency tree/i,/peer dep(?:endency)? .* conflict/i]},{kind:"type-error",mechanical:!1,patterns:[/error TS\d{4}:/,/\berror\[E\d+\]:/,/Type '.*' is not assignable to type/]},{kind:"test-failure",mechanical:!1,patterns:[/\d+ (?:tests? )?fail(?:ed|ing)\b/i,/\(fail\)/,/AssertionError|expect\(received\)/,/\u25CF .* \u203A /]},{kind:"lint",mechanical:!1,patterns:[/\b\d+ problems? \(\d+ errors?/i,/eslint|pickier|biome|oxlint/i]}];function N(x){if(!x.trim())return{kind:"unknown",mechanical:!1,evidence:[]};let H=x.split(`
|
|
3
|
+
`);for(let z of b){let J=[];for(let V of H)if(z.patterns.some((Q)=>Q.test(V))){if(J.push(V.trim()),J.length>=5)break}if(J.length>0)return{kind:z.kind,mechanical:z.mechanical,evidence:J}}return{kind:"unknown",mechanical:!1,evidence:T(H)}}function T(x,H=40){let z=x.filter((J)=>/\b(?:error|failed|failure|exception|panic|fatal)\b/i.test(J)&&!/^\s*(?:at\s|\s*\.\.\.)/.test(J));return(z.length>0?z:x.slice(-H)).slice(-H).map((J)=>J.trim()).filter(Boolean)}function G(x){switch(x.kind){case"lockfile-drift":return"The lock file is out of step with its manifest.";case"flake":return"A network or runner problem, unrelated to the change.";case"install":return"Dependencies could not be resolved.";case"type-error":return"The change does not type-check.";case"test-failure":return"One or more tests failed.";case"lint":return"Lint or formatting checks failed.";default:return"The failure could not be classified automatically."}}var w=3;async function M(x,H,z,J){let V=J??O();try{let Q=await x.listWorkflowRuns(H,{status:"completed",limit:20});for(let Y of _(Q).slice(0,w)){let Z=await x.getWorkflowRunLogs(Y.id);if(!Z)continue;if(N(Z).kind===z)return V.info(`\uD83E\uDDED ${H} already fails the same way (run ${Y.id}) \u2014 not this pull request's to fix`),!0}return!1}catch(Q){return V.debug(`Could not check ${H} for a pre-existing failure: ${K(Q)}`),!1}}function _(x){let H=new Map;for(let z of x)if(!H.has(z.name))H.set(z.name,z);return[...H.values()].filter((z)=>z.conclusion==="failure")}function h(x,H){if(!x)return"Tried to regenerate the lock file, but the install did not succeed.";if(!H)return"Regenerated the lock file, but could not push it to the branch. The change is in the workspace only, so the run will still be red until someone commits it.";return"Regenerated the lock file and pushed the result. No model was needed."}function f(x){let H="Repairs run on the pull request's branch, and answering a comment runs on the default branch, so anything I changed here would land on the wrong tree. ";if(x.kind==="lockfile-drift")return`Regenerating the lock file would fix this, and no model would be needed. ${H}The \`fix-ci\` job will do it on the next failing run, or you can run \`buddy fix-ci --run-id <id> --pr <number>\` yourself.`;return`${H}The \`fix-ci\` job runs on the failing run itself and can repair this; this reply is the diagnosis it would start from.`}async function I(x){let H=x.logger??O(),z=N(x.log),J=x.maxAttempts??3;if(H.info(`\uD83E\uDE7A CI failure classified as ${z.kind}`),x.failsOnBase??(x.checkBase?await x.checkBase(z.kind):!1))return{failure:z,action:"skipped",fixed:!1,report:$(z,"This failure also occurs on the base branch, so it is not caused by this change. Fixing it here would only mask it.")};if((x.priorAttempts??0)>=J)return{failure:z,action:"skipped",fixed:!1,report:$(z,`Already attempted ${x.priorAttempts} time(s); stopping rather than looping.`)};if(x.analysisOnly&&z.kind!=="flake")return{failure:z,action:"reported",fixed:!1,report:$(z,f(z))};if(z.kind==="lockfile-drift"&&x.regenerateLockfile){if(x.dryRun)return{failure:z,action:"mechanical-fix",fixed:!1,report:$(z,"Regenerating the lock file would fix this. No model would be needed. Nothing was changed, because this was a dry run.")};H.info("\uD83D\uDD27 Regenerating the lock file");let{regenerated:Y,pushed:Z}=await x.regenerateLockfile();return{failure:z,action:"mechanical-fix",fixed:Z,report:$(z,h(Y,Z))}}if(z.kind==="flake"){if(x.dryRun)return{failure:z,action:"retry",fixed:!1,report:$(z,"This looks transient, and re-running the failed jobs would likely clear it. Nothing was changed, because this was a dry run.")};if(!x.rerun)return{failure:z,action:"retry",fixed:!1,report:$(z,"This looks transient. Re-running the failed job is likely to clear it.")};H.info("\uD83D\uDD01 Re-running the failed jobs");let Y=await x.rerun();return{failure:z,action:"retry",fixed:!1,report:$(z,Y?"This looks transient, so I re-ran the failed jobs. No model was needed.":"This looks transient, but I could not re-run the failed jobs \u2014 `actions: write` is the usual reason. "+"Re-running them from the Actions tab is likely to clear it.")}}if(!x.ai)return{failure:z,action:"reported",fixed:!1,report:$(z,"No AI provider is configured, so this needs a human. See https://buddy.sh/ai/providers to enable automatic repair.")};let Q=await L(x.ai,{mode:S,task:["A CI job on this branch is failing. Diagnose the root cause and fix it if the fix is clear.","",`Classification: ${z.kind} \u2014 ${G(z)}`,"","Relevant log lines:",z.evidence.join(`
|
|
4
4
|
`),"","Verify your fix by running the project's tests or build before reporting it done.","If the fix is not clear, explain what you found rather than guessing."].join(`
|
|
5
5
|
`),context:{workspace:x.workspace,baseBranch:x.baseBranch,...x.branch?{branch:x.branch}:{}},logger:H});return{failure:z,action:"agent-fix",fixed:Q.stopReason==="completed",report:$(z,Q.output||"The repair run ended without a conclusion.")}}function $(x,H){let z=`## \uD83E\uDE7A CI failure analysis
|
|
6
6
|
|
|
7
|
-
**Diagnosis:** ${
|
|
7
|
+
**Diagnosis:** ${G(x)}
|
|
8
8
|
|
|
9
9
|
${H}
|
|
10
10
|
`;if(x.evidence.length>0)z+=`
|
|
@@ -16,12 +16,12 @@ ${x.evidence.slice(0,20).join(`
|
|
|
16
16
|
\`\`\`
|
|
17
17
|
|
|
18
18
|
</details>
|
|
19
|
-
`;return z}var
|
|
19
|
+
`;return z}var B=/<!--\s*buddy:fix-ci\s+v(\d+)\s*([\s\S]*?)-->/;function E(x){if(!x)return null;let H=x.match(B);if(!H)return null;try{let z=JSON.parse(H[2].trim()),J=Number(z.attempts);if(!Number.isFinite(J)||J<0)return null;return{attempts:Math.floor(J),lastAttemptAt:typeof z.lastAttemptAt==="string"?z.lastAttemptAt:new Date(0).toISOString()}}catch{return null}}function q(x,H,z=new Date){let J={attempts:H,lastAttemptAt:z.toISOString()},V=`<!-- buddy:fix-ci v1
|
|
20
20
|
${JSON.stringify(J)}
|
|
21
|
-
-->`;return`${(x??"").replace(
|
|
21
|
+
-->`;return`${(x??"").replace(B,"").trimEnd()}
|
|
22
22
|
|
|
23
|
-
${V}`}async function
|
|
23
|
+
${V}`}async function m(x,H,z){if(!F(x,"ciRuns","listWorkflowRuns"))return null;try{let J=await x.getPullRequestHeadSha(H.number),V=await x.listWorkflowRuns(H.head,{status:"completed",limit:30}),Q=J?V.filter((Y)=>Y.headSha===J):V;return _(Q)[0]?.id??null}catch(J){return z.debug(`Could not resolve the failing run for #${H.number}: ${K(J)}`),null}}async function c(x){let H=x.logger??O(),{config:z,provider:J}=x,V=x.workspace??process.cwd();A(J,"ciLogs","getWorkflowRunLogs","reading CI logs");let Q;if(x.prNumber){if(Q=(await J.getPullRequests("open")).find((W)=>W.number===x.prNumber),!Q)return`Could not find open pull request #${x.prNumber}.`}let Y=x.runId??(Q?await m(J,Q,H):null);if(!Y)return Q?"Nothing is failing at the head of this pull request, so there is nothing to diagnose.":"No run to diagnose. Pass --run-id, or --pr so I can find the failing run myself.";let Z=await J.getWorkflowRunLogs(Y);if(!Z)return H.warn(`\u26A0\uFE0F Could not read the logs for run ${Y}; nothing to diagnose`),`Could not read the logs for run ${Y}. They may have expired.`;let U=E(Q?.body)?.attempts??0,j=z.repository?.baseBranch??"main",D=F(J,"ciRuns","listWorkflowRuns"),y=F(J,"ciRuns","rerunWorkflowRun"),{createAiClient:v}=await import("./chunk-hsa07n7c.js"),C=await I({log:Z,priorAttempts:U,workspace:V,baseBranch:j,ai:x.analysisOnly?null:v(z,H),logger:H,dryRun:Boolean(x.dryRun),analysisOnly:Boolean(x.analysisOnly),...D?{checkBase:(X)=>M({listWorkflowRuns:(W,k)=>J.listWorkflowRuns(W,k),getWorkflowRunLogs:(W)=>J.getWorkflowRunLogs(W)},j,X,H)}:{},...y?{rerun:()=>J.rerunWorkflowRun(Y)}:{},...x.analysisOnly?{}:{regenerateLockfile:()=>g(V,H)}});if(H.info(`
|
|
24
24
|
${C.report}
|
|
25
|
-
`),x.prNumber&&!x.dryRun){if(await J.createComment(x.prNumber,C.report),C.action!=="skipped"&&Q)try{await J.updatePullRequest(x.prNumber,{body:
|
|
25
|
+
`),x.prNumber&&!x.dryRun){if(await J.createComment(x.prNumber,C.report),C.action!=="skipped"&&Q)try{await J.updatePullRequest(x.prNumber,{body:q(Q.body,U+1)})}catch(X){H.warn(`Could not record the fix attempt on PR #${x.prNumber}: ${K(X)}`)}}return await R(z.notifications,"fixci.completed",{...x.prNumber?{number:x.prNumber}:{},action:C.action,fixed:C.fixed}),`${C.action}${C.fixed?" (fixed)":""}`}async function g(x,H){let{regenerateLockFile:z,detectRequiredPackageManagers:J,getAllLockFilePaths:V,hasLockFile:Q}=await import("./chunk-4yq2fny9.js"),{commitAndPush:Y}=await import("./chunk-aa277p5r.js"),Z=J(["package.json","composer.json"],x).filter((j)=>Q(j,x)),U=!1;for(let j of Z){let D=await z(j,x);if(D.success)U=!0;else H.warn(`\u26A0\uFE0F ${D.message}`)}if(!U)return{regenerated:!1,pushed:!1};try{return{regenerated:!0,pushed:await Y(V(),`fix(deps): regenerate the lock file
|
|
26
26
|
|
|
27
|
-
The lock file had drifted from the manifest, which failed CI.`,x)}}catch(j){return H.warn(`\u26A0\uFE0F Could not push the regenerated lock file: ${K(j)}`),{regenerated:!0,pushed:!1}}}export{N as Ea,
|
|
27
|
+
The lock file had drifted from the manifest, which failed CI.`,x)}}catch(j){return H.warn(`\u26A0\uFE0F Could not push the regenerated lock file: ${K(j)}`),{regenerated:!0,pushed:!1}}}export{N as Ea,T as Fa,G as Ga,M as Ha,_ as Ia,I as Ja,c as Ka};
|
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{Wk as Z}from"./chunk-q4t568hv.js";import x from"process";var K=["github","gitlab","bitbucket"],$=["github","gitlab","bitbucket"],H={},L={pinIssues:!1,checkRuns:!1,inlineReviewComments:!1,reviewSuggestions:!1,nativeAutoMerge:!1,commentReactions:!1,ciLogs:!1,ciRuns:!1,reviewThreads:!1,teamReviewers:!1,draftPullRequests:!1,permissionLookup:!1,branchHousekeeping:!1,reopenPullRequests:!1,labels:!1};class Y extends Error{provider;trackingIssue;constructor(j,z,F){super(j);this.provider=z;this.trackingIssue=F;this.name="UnsupportedProviderError"}}var B={github:["GITHUB_TOKEN","BUDDY_TOKEN"],gitlab:["CI_JOB_TOKEN","GITLAB_TOKEN","BUDDY_TOKEN"],bitbucket:["BITBUCKET_TOKEN","BUDDY_TOKEN"]};function A(j,z=x.env){for(let F of B[j]??[]){let J=z[F]?.trim();if(J)return{token:J,source:F}}return null}function C(j){if($.includes(j))return;let z=H[j];if(z)throw new Y(`'${j}' support is not implemented yet \u2014 follow ${z}. Supported today: ${$.join(", ")}.`,j,z);throw new Y(`Unknown git provider '${j}'. Supported: ${$.join(", ")}.`,j)}async function M(j,z={}){let F=j.provider??"github";C(F);let J=z.env??x.env,X=j.token??A(F,J)?.token;if(!X)throw Error(`No token for ${F}. Set one of: ${B[F].join(", ")}.`);switch(F){case"gitlab":{let{GitLabProvider:Q}=await import("./chunk-hns85dqw.js");return new Q(X,j.owner,j.name,j.apiUrl,z.logger)}case"bitbucket":{let{BitbucketProvider:Q}=await import("./chunk-brfyymhf.js");return new Q(X,j.owner,j.name,j.apiUrl,z.logger)}case"github":{let{GitHubProvider:Q}=await import("./chunk-
|
|
2
|
+
import{Wk as Z}from"./chunk-q4t568hv.js";import x from"process";var K=["github","gitlab","bitbucket"],$=["github","gitlab","bitbucket"],H={},L={pinIssues:!1,checkRuns:!1,inlineReviewComments:!1,reviewSuggestions:!1,nativeAutoMerge:!1,commentReactions:!1,ciLogs:!1,ciRuns:!1,reviewThreads:!1,teamReviewers:!1,draftPullRequests:!1,permissionLookup:!1,branchHousekeeping:!1,reopenPullRequests:!1,labels:!1};class Y extends Error{provider;trackingIssue;constructor(j,z,F){super(j);this.provider=z;this.trackingIssue=F;this.name="UnsupportedProviderError"}}var B={github:["GITHUB_TOKEN","BUDDY_TOKEN"],gitlab:["CI_JOB_TOKEN","GITLAB_TOKEN","BUDDY_TOKEN"],bitbucket:["BITBUCKET_TOKEN","BUDDY_TOKEN"]};function A(j,z=x.env){for(let F of B[j]??[]){let J=z[F]?.trim();if(J)return{token:J,source:F}}return null}function C(j){if($.includes(j))return;let z=H[j];if(z)throw new Y(`'${j}' support is not implemented yet \u2014 follow ${z}. Supported today: ${$.join(", ")}.`,j,z);throw new Y(`Unknown git provider '${j}'. Supported: ${$.join(", ")}.`,j)}async function M(j,z={}){let F=j.provider??"github";C(F);let J=z.env??x.env,X=j.token??A(F,J)?.token;if(!X)throw Error(`No token for ${F}. Set one of: ${B[F].join(", ")}.`);switch(F){case"gitlab":{let{GitLabProvider:Q}=await import("./chunk-hns85dqw.js");return new Q(X,j.owner,j.name,j.apiUrl,z.logger)}case"bitbucket":{let{BitbucketProvider:Q}=await import("./chunk-brfyymhf.js");return new Q(X,j.owner,j.name,j.apiUrl,z.logger)}case"github":{let{GitHubProvider:Q}=await import("./chunk-5xfs8a89.js"),q=j.workflowToken??J.BUDDY_TOKEN;return new Q(X,j.owner,j.name,Boolean(q),q,j.apiUrl,z.logger)}}}function W(j,z,F){return j.capabilities()[z]===!0&&typeof j[F]==="function"}function S(j,z,F,J){if(W(j,z,F))return;throw new Y(`This provider does not support ${J} (missing capability '${z}').`,"unknown")}
|
|
3
3
|
export{K as ce,$ as de,H as ee,L as fe,Y as ge,B as he,A as ie,C as je,M as ke,W as le,S as me};
|
package/dist/src/index.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{I as wo,J as So,K as ho,L as uo,M as co,N as Vo,O as eo,P as go,Q as ro,R as vo,S as io,T as so,U as no}from"../chunk-0w695m54.js";import{W as ko,X as qo}from"../chunk-rayxmbcx.js";import{$ as Wo,Y as Jo,Z as Ko,_ as Qo}from"../chunk-jnb80k2x.js";import{aa as PR,ba as aR,ca as lR,da as yR,ea as CR,fa as NR,ga as _R,ha as zR,ia as DR,ja as TR}from"../chunk-69qyr9ef.js";import{ka as pR,la as oR,ma as mR,na as xR,oa as fR,pa as dR,qa as RR,ra as MR,sa as UR,ta as AR,ua as GR,va as ER,wa as OR}from"../chunk-fjp3a7hp.js";import{Aa as $o,Ba as bo,Ca as to,xa as Xo,ya as Yo,za as Zo}from"../chunk-3cvng2nz.js";import"../chunk-rb1fh9vd.js";import{Da as pm}from"../chunk-jz5zs812.js";import{Ea as ed,Fa as gd,Ga as rd,Ha as vd,Ia as id,Ja as sd,Ka as nd}from"../chunk-yr8eta7p.js";import{La as Zd,Ma as $d,Na as bd,Oa as td,Pa as wd,Qa as Sd,Ra as hd,Sa as ud,Ta as cd,Ua as Vd}from"../chunk-96ht6hwd.js";import{Va as Yf,Wa as Zf}from"../chunk-s6z3gm2s.js";import{$a as Sf,Xa as $f,Ya as bf,Za as tf,_a as wf,ab as hf,bb as uf,cb as cf,db as Vf,eb as ef,fb as gf,gb as rf}from"../chunk-s4zb0fcj.js";import{hb as vf,ib as sf,jb as nf,kb as pd,lb as od}from"../chunk-tw047td6.js";import{mb as Id}from"../chunk-patms7t8.js";import{Ab as Td,Bb as jd,Cb as Ld,Db as Bd,nb as dd,ob as Rd,pb as Md,qb as Ud,rb as Ad,sb as Gd,tb as Ed,ub as Od,vb as Pd,wb as Nd,xb as _d,yb as zd,zb as Dd}from"../chunk-4jyw358y.js";import{Eb as md,Fb as xd,Gb as fd}from"../chunk-q2tjkhez.js";import{Hb as Co,Ib as No,Jb as _o,Kb as zo}from"../chunk-vckhctmr.js";import{Lb as ad,Mb as ld,Nb as yd,Pb as Cd}from"../chunk-5yfaptmp.js";import{Qb as Rf,Rb as Mf,Sb as Uf,Tb as Af,Ub as Gf,Vb as Ef,Wb as Of,Xb as Pf,Yb as af}from"../chunk-rc2mk5x6.js";import{$b as nx,Zb as ix,_b as sx,ac as pf,bc as of,cc as mf,dc as xf,ec as ff,fc as df}from"../chunk-tjc2vgwn.js";import{gc as Vp,hc as ep,ic as gp,jc as rp,mc as vp,nc as ip}from"../chunk-61xecp1z.js";import{Ac as Uo,Bc as Ao,Cc as Go,Dc as Eo,Ec as Oo,Fc as Po,Gc as ao,Hc as lo,Ic as yo,pc as sp,sc as np,tc as po,uc as oo,vc as mo,wc as xo,xc as fo,yc as Ro,zc as Mo}from"../chunk-6p4qz8qv.js";import{Jc as dp}from"../chunk-bmnx3s41.js";import{Kc as mp,Lc as xp,Mc as fp}from"../chunk-8fw0v7bv.js";import{Oc as mm,Pc as xm,Qc as fm,Rc as dm}from"../chunk-ngh4jbgp.js";import{Sc as Bo,Tc as Fo,Uc as Ho}from"../chunk-cs066zt9.js";import{Vc as Sp,Wc as hp,Xc as up,Yc as cp,_c as Do}from"../chunk-e2t5jq26.js";import"../chunk-phfmnnne.js";import{ad as _p,bd as zp,cd as Dp,dd as Tp,ed as jp}from"../chunk-r763e19p.js";import{fd as wp}from"../chunk-be629jhq.js";import"../chunk-pkr6905p.js";import{hd as ex,id as gx,jd as rx,kd as vx}from"../chunk-eseshkd0.js";import{nd as Np}from"../chunk-11hdrnf6.js";import{od as Xf}from"../chunk-cwfkm7h9.js";import{pd as $x,qd as bx,rd as tx,sd as wx,td as Sx,ud as hx,vd as ux,wd as cx,xd as Vx}from"../chunk-mkzmjg3f.js";import{Ad as kd,Bd as qd,Cd as Jd,Dd as Kd,Ed as Qd,Fd as Wd,Gd as Xd,Hd as Yd,yd as Fd,zd as Hd}from"../chunk-vgtmrd4c.js";import{$d as Wf,Id as lf,Jd as yf,Kd as Cf,Ld as Nf,Md as _f,Nd as zf,Od as Df,Pd as Tf,Qd as jf,Rd as If,Sd as Lf,Td as Bf,Ud as Ff,Vd as Hf,Wd as kf,Xd as qf,Yd as Jf,Zd as Kf,_d as Qf}from"../chunk-nrr8z2z7.js";import"../chunk-xs12dtf1.js";import{ce as Rp,de as Mp,ee as Up,fe as Ap,ge as Gp,he as Ep,ie as Op,je as Pp,ke as ap,le as lp,me as yp}from"../chunk-5av2vnvv.js";import"../chunk-ytmxd5fk.js";import{Ae as Kp,Be as Qp,Ce as Wp,se as Ip,te as Lp,ue as Bp,ve as Fp,we as Hp,xe as kp,ye as qp,ze as Jp}from"../chunk-b9escac0.js";import{Je as Cp}from"../chunk-g30dr44w.js";import{Ke as Xp,Le as Yp,Me as Zp,Ne as $p,Oe as bp,Pe as tp}from"../chunk-2et8yavs.js";import"../chunk-txtrpypt.js";import{$e as _,We as a,Xe as l,Ye as y,Ze as C,_e as N,af as z,bf as D,cf as T,df as j,ef as I,ff as L,gf as B,hf as F,if as H}from"../chunk-8hjvthz4.js";import{jf as U,kf as A,lf as G,mf as E,nf as O,pf as P}from"../chunk-yngahb11.js";import{qf as Px,rf as ax,sf as lx,tf as yx,uf as Cx,vf as Nx}from"../chunk-08x5b93v.js";import{Af as kx,Bf as qx,Cf as Jx,Df as Kx,Ef as Qx,Ff as Wx,Gf as Xx,Hf as Yx,If as Zx,wf as Lx,xf as Bx,yf as Fx,zf as Hx}from"../chunk-p6qbqsyp.js";import"../chunk-1cpdz49v.js";import{Lf as _x,Mf as zx,Nf as Dx,Of as Tx,Pf as jx,Qf as Ix}from"../chunk-cgvt98pd.js";import"../chunk-c8rzx3a1.js";import{$f as pp,Uf as e,Vf as g,Wf as r,Xf as v,Yf as i,Zf as s,_f as n,ag as op,bg as d}from"../chunk-0hc97k0t.js";import"../chunk-3901s7h9.js";import"../chunk-jtxcr5yw.js";import"../chunk-qd2s51gc.js";import{$g as JR,Og as To,Pg as jo,Qg as Io,Rg as Lo,Tg as jR,Ug as IR,Vg as LR,Wg as BR,Xg as FR,Yg as HR,Zg as kR,_g as qR,ah as KR,bh as QR,ch as WR,dh as XR,eh as YR,fh as ZR,gh as $R,hh as bR,ih as tR,jh as wR,kh as SR,lh as hR,mh as uR}from"../chunk-vbeeyhhe.js";import{nh as om}from"../chunk-k26wnmzk.js";import{oh as S,ph as h,qh as u,rh as c,sh as V}from"../chunk-193abzy6.js";import{th as t}from"../chunk-5044y9en.js";import{uh as w}from"../chunk-f53y8ans.js";import{Ah as Y,vh as J,wh as K,xh as Q,yh as W,zh as X}from"../chunk-e68nf7cm.js";import{Bh as k,Ch as q,Dh as Z,Eh as $,Fh as b}from"../chunk-hfjywbbc.js";import"../chunk-g24hav8e.js";import"../chunk-q4t568hv.js";var{semver:m}=globalThis.Bun;class R{static compareVersions(p,o){return m.order(p,o)}static satisfiesRange(p,o){return m.satisfies(p,o)}static getLatestInRange(p,o){let f=p.filter((x)=>m.satisfies(x,o));if(f.length===0)return null;return f.sort((x,M)=>m.order(M,x))[0]}static createRange(p){return{raw:p,range:p.replace(/^[\^~>=<]+/,""),isExact:!/^[\^~>=<]/.test(p),satisfies:(o)=>this.satisfiesRange(o,p),getLatest:(o)=>this.getLatestInRange(o,p)}}static getUpdateType(p,o){return d(p,o)}static isSafeUpdate(p,o){return m.satisfies(o,p)}}export{Fx as writeFileTool,Yx as wrapUntrusted,gf as withTouchOffer,no as withNarrative,sf as verifyChanges,tR as validateWorkflowGeneration,wR as validateRepositoryAccess,Ud as validateFindings,Bo as validateConfig,Jo as validateAgainstSchema,HR as updateProgress,bf as unitTestsTouch,Sp as toOsvEcosystem,Hp as tagUpdateType,Kf as syntaxAnalyzer,lp as supports,z as summarizeUsage,fR as summarizeGates,lo as stripOperators,bd as stripNonCommandContext,nf as stackedBranchName,Mo as splitConstraint,op as sortUpdatesByPriority,wf as simplifyTouch,yR as similarity,Vx as sign,uR as showFinalInstructions,N as shouldOpenAsDraft,Yd as shouldFail,Jf as shellcheckAnalyzer,Kx as shellTool,hR as setupCustomWorkflow,$ as setDefaultLogger,ld as serializeReviewState,Af as serializeLearnings,Of as selectLearnings,Fp as selectLatestTag,qf as secretsAnalyzer,YR as schedulePlan,ao as scanEcosystems,vp as scanCatalogs,Bp as sameVariant,Go as rustAdapter,yf as runTool,pd as runStackedTouch,Bd as runReviewForPR,LR as runPreflightChecks,ER as runPostMerge,Zf as runPlan,Ko as runHeadless,xR as runGates,nd as runFixCi,Wf as runAnalyzers,UR as runAiGates,Zx as runAgent,A as ruleMatches,Ao as rubyAdapter,Ld as reviewPullRequest,Px as reviewMode,Ed as reviewDiff,Lx as resolveWorkspacePath,G as resolveRuleEffects,Op as resolveProviderToken,pf as resolveModelAlias,bp as resolveEngineVersion,Kp as resolveCredentials,ep as resolveCatalogReference,Id as resolveBuddyThreads,ff as resolveAiProvider,fm as resetConfigCache,Vf as renderTouchOffer,so as renderReport,TR as renderQuickLinks,aR as renderPackageContext,D as renderMigrationReport,Pf as renderLearnings,Td as renderFinding,qo as renderDoctorReport,xd as renderDiffForReview,_f as relativize,yo as regenerateLockfiles,xp as regenerateLockFile,Tx as redactError,Dx as redactDeep,zx as redact,Bx as readFileTool,Uo as pythonAdapter,Wo as publishOutput,Yo as productFor,jd as prepareReview,Sf as planTouch,yx as planMode,$p as pinBlocksUpdate,Ro as pep440UpdateType,Vp as parseWorkspaceCatalogs,md as parseUnifiedDiff,rf as parseTouchSelections,Nf as parseToolJson,Ip as parseTag,yd as parseReviewState,W as parseRetryDelay,qR as parseRemote,zR as parseQuickSelection,mo as parsePep440,g as parsePackageFile,Uf as parseLearnings,kp as parseImageRef,ho as parseHistory,td as parseCommand,Qp as parseAuthChallenge,If as offsetToLine,po as numericUpdateType,hp as normalizeSeverity,C as normalizePlan,Cd as needsReview,O as mergeGroupEffects,Sd as mentionsBot,B as matchesGlobs,Hf as markdownlintAnalyzer,zp as mapWithConcurrency,Cf as mapSeverity,af as loadLearnings,Vo as loadHistory,zd as loadGuidelines,Hx as listDirTool,Ff as linterAnalyzer,id as latestFailurePerWorkflow,wd as isReadOnlyCommand,fo as isPep440Prerelease,OR as isMergeEvent,gp as isCatalogReference,l as isAllowedCodemod,ax as implementMode,ef as hasTouchOffer,jf as hadolintAnalyzer,KR as guideTokenCreation,WR as guideRepositorySettings,P as groupsToRules,pp as groupUpdates,oo as goAdapter,Tf as githubActionsAnalyzer,bR as getWorkflowPreset,c as getNpmRegistryUrl,h as getGitHubServerUrl,S as getGitHubApiUrl,uf as getFinishingTouch,b as getDefaultLogger,xm as getConfig,V as getComposerRegistryUrl,mp as getAllLockFilePaths,Nx as getAgentMode,ZR as generateUnifiedWorkflow,jo as generateGitLabPipeline,$R as generateCoreWorkflows,XR as generateConfigFile,n as generateBranchName,Io as generateBitbucketPipeline,dR as gateIcon,kx as fsTools,e as formatSecurityAdvisorySection,Wd as formatReview,qd as formatPretty,i as formatPRTitle,s as formatPRBody,qp as formatImageRef,Qo as formatGithubOutput,Jd as formatGithub,q as formatError,Fo as formatConfigIssues,v as formatCommitMessage,Kd as formatAgent,lx as fixCiMode,Md as fingerprint,_ as findUsageSites,co as findPrevious,PR as findMentionedPackages,AR as findLinkedIssues,CR as findDuplicates,_o as findDrift,X as fetchWithTimeout,Y as fetchJsonOrNull,vd as failsOnBaseBranch,gd as extractErrorLines,Yp as extractEngines,Xf as emitEvent,U as ecosystemOf,Co as driftFor,$f as docstringsTouch,SR as displayValidationResults,kR as displayProgress,cd as dispatchCommand,Hd as diffArgsFor,ko as diagnose,fp as detectRequiredPackageManagers,JR as detectRepository,r as detectPackageManager,Bf as detectLinter,sp as detectFiles,od as detectChangedFiles,L as describeSpanGaps,rd as describeFailure,tx as describeEvent,to as describeEol,zo as describeDrift,Pd as defaultIncludePath,mm as defaultConfig,Ad as dedupeFindings,Zo as cycleFor,cx as createWebhookSink,hx as createSlackSink,Sx as createSinks,Yf as createReadIssueTool,ap as createProvider,FR as createProgressTracker,xf as createOpenAiProvider,Gf as createLearning,Vd as createHandlers,mf as createGoogleProvider,ux as createDiscordSink,of as createAnthropicProvider,df as createAiClient,Qd as countBySeverity,lR as constrainLabels,QR as confirmTokenSetup,dm as config,ro as computeMetrics,vo as computeDeltas,Dd as composeInstructions,Lp as compareVersions,xo as comparePep440,np as compareNumeric,zf as commandExists,I as collectSpanNotes,Zp as collectResolutionPins,kd as collectLocalDiff,fd as collectGitDiff,DR as clearQuickSelection,u as clearNpmrcCache,ed as classifyFailure,Lo as ciTemplateFor,Dp as chunk,pR as checkTitleFormat,ud as checkPermission,RR as checkLinkedIssue,$o as checkEol,oR as checkDescription,mR as checkDependencies,MR as checkCustomAssertions,tp as bumpEngineConstraint,Jx as buildShellEnv,y as buildAnalysisPrompt,tf as autofixTouch,T as attemptMajorUpgrade,sd as attemptFix,Ho as assertValidConfig,yp as assertSupports,Pp as assertProviderSupported,Xd as applySuggestion,E as applyRules,ip as applyCatalogUpdates,rp as applyCatalogUpdate,H as appendUpgradeReport,uo as appendHistory,GR as appendChangelogEntry,Jp as apiHostFor,Od as anchorMap,BR as analyzeProject,F as analyzeGroupMajors,cp as advisoryKey,Ef as addLearning,Po as adapterNamed,Oo as adapterFor,Df as actionlintAnalyzer,wx as WEBHOOK_PAYLOAD_VERSION,R as VersionResolver,Gp as UnsupportedProviderError,Xx as Toolbelt,Qx as ToolPermissionError,cf as TOUCH_OFFER_MARKER,lf as TOOL_TIMEOUT_MS,vf as TEST_COMMANDS,up as SecurityAdvisoryService,pm as Scheduler,qx as SHELL_ENV_ALLOWLIST,dd as SEVERITY_ORDER,kf as SECRET_RULES,Cp as ReleaseNotesFetcher,jp as RegistryClient,No as ROOT,ad as REVIEW_STATE_VERSION,Rd as REVIEW_SCHEMA,Fd as REVIEW_FORMATS,eo as REPORT_PERIODS,io as REPORT_MARKER,_x as REDACTED,$d as READ_ONLY_COMMANDS,NR as QUICK_LINKS_MARKER,_R as QUICK_ACTIONS,Np as PullRequestGenerator,IR as PluginManager,wp as PackageScanner,gx as PackageRegistryError,Up as PROVIDER_TRACKING_ISSUES,Ep as PROVIDER_TOKEN_ENV,nx as PROVIDER_PRIORITY,Rp as PROVIDER_NAMES,sx as PROVIDER_KEY_ENV,go as PERIOD_DAYS,Wp as OciClient,Ap as NO_CAPABILITIES,ix as MODEL_ALIASES,a as MIGRATION_PLAN_SCHEMA,_d as MAX_GUIDELINE_CHARS,Z as Logger,Lf as LINTER_SPECS,Xp as KNOWN_ENGINES,Mp as IMPLEMENTED_PROVIDERS,Q as HttpRequestError,wo as HISTORY_PATH,So as HISTORY_LIMIT,hd as HELP_TEXT,rx as GitProviderError,t as GitLabProvider,dp as GitHubProvider,k as GitHubApiError,om as GitHubActionsTemplate,hf as FINISHING_TOUCHES,bx as EventBus,$x as EVENT_NAMES,bo as EOL_WARNING_DAYS,Xo as EOL_PRODUCTS,J as DEFAULT_TIMEOUT_MS,j as DEFAULT_SPAN_BUDGET,To as DEFAULT_SCHEDULE,K as DEFAULT_RETRIES,Mf as DEFAULT_PROMPT_LIMIT,Rf as DEFAULT_LEARNINGS_FILE,Nd as DEFAULT_GUIDELINE_FILES,Gd as DEFAULT_EXCLUDED_PATHS,_p as DEFAULT_CONCURRENCY,jR as ConfigurationMigrator,vx as ConfigurationError,Zd as COMMAND_ALIASES,ex as BuddyError,Do as Buddy,w as BitbucketProvider,Wx as BUILTIN_TOOLS,Qf as BUILTIN_ANALYZERS,Eo as BUILTIN_ADAPTERS,Tp as AsyncMemo,Ix as AiProviderError,jx as AiBudgetExceededError,Cx as AGENT_MODES};
|
|
2
|
+
import{I as wo,J as So,K as ho,L as uo,M as co,N as Vo,O as eo,P as go,Q as ro,R as vo,S as io,T as so,U as no}from"../chunk-0w695m54.js";import{W as ko,X as qo}from"../chunk-kbbqs8ae.js";import{$ as Wo,Y as Jo,Z as Ko,_ as Qo}from"../chunk-jnb80k2x.js";import{aa as PR,ba as aR,ca as lR,da as yR,ea as CR,fa as NR,ga as _R,ha as zR,ia as DR,ja as TR}from"../chunk-69qyr9ef.js";import{ka as pR,la as oR,ma as mR,na as xR,oa as fR,pa as dR,qa as RR,ra as MR,sa as UR,ta as AR,ua as GR,va as ER,wa as OR}from"../chunk-fjp3a7hp.js";import{Aa as $o,Ba as bo,Ca as to,xa as Xo,ya as Yo,za as Zo}from"../chunk-3cvng2nz.js";import"../chunk-rb1fh9vd.js";import{Da as pm}from"../chunk-dm5yktev.js";import{Ea as ed,Fa as gd,Ga as rd,Ha as vd,Ia as id,Ja as sd,Ka as nd}from"../chunk-rz7pg7pb.js";import{La as Zd,Ma as $d,Na as bd,Oa as td,Pa as wd,Qa as Sd,Ra as hd,Sa as ud,Ta as cd,Ua as Vd}from"../chunk-96ht6hwd.js";import{Va as Yf,Wa as Zf}from"../chunk-s6z3gm2s.js";import{$a as Sf,Xa as $f,Ya as bf,Za as tf,_a as wf,ab as hf,bb as uf,cb as cf,db as Vf,eb as ef,fb as gf,gb as rf}from"../chunk-s4zb0fcj.js";import{hb as vf,ib as sf,jb as nf,kb as pd,lb as od}from"../chunk-tw047td6.js";import{mb as Id}from"../chunk-9fq7drn8.js";import{Ab as Td,Bb as jd,Cb as Ld,Db as Bd,nb as dd,ob as Rd,pb as Md,qb as Ud,rb as Ad,sb as Gd,tb as Ed,ub as Od,vb as Pd,wb as Nd,xb as _d,yb as zd,zb as Dd}from"../chunk-5x4gt4c5.js";import{Eb as md,Fb as xd,Gb as fd}from"../chunk-q2tjkhez.js";import{Hb as Co,Ib as No,Jb as _o,Kb as zo}from"../chunk-vckhctmr.js";import{Lb as ad,Mb as ld,Nb as yd,Pb as Cd}from"../chunk-5yfaptmp.js";import{Qb as Rf,Rb as Mf,Sb as Uf,Tb as Af,Ub as Gf,Vb as Ef,Wb as Of,Xb as Pf,Yb as af}from"../chunk-rc2mk5x6.js";import{$b as nx,Zb as ix,_b as sx,ac as pf,bc as of,cc as mf,dc as xf,ec as ff,fc as df}from"../chunk-tjc2vgwn.js";import{gc as Vp,hc as ep,ic as gp,jc as rp,mc as vp,nc as ip}from"../chunk-61xecp1z.js";import{Ac as Uo,Bc as Ao,Cc as Go,Dc as Eo,Ec as Oo,Fc as Po,Gc as ao,Hc as lo,Ic as yo,pc as sp,sc as np,tc as po,uc as oo,vc as mo,wc as xo,xc as fo,yc as Ro,zc as Mo}from"../chunk-6p4qz8qv.js";import{Jc as dp}from"../chunk-j9cgwkm8.js";import{Kc as mp,Lc as xp,Mc as fp}from"../chunk-8ycrg9gp.js";import{Oc as mm,Pc as xm,Qc as fm,Rc as dm}from"../chunk-8gd76j8e.js";import{Sc as Bo,Tc as Fo,Uc as Ho}from"../chunk-ctt9xk2j.js";import{Vc as Sp,Wc as hp,Xc as up,Yc as cp,_c as Do}from"../chunk-3cab6vqx.js";import"../chunk-phfmnnne.js";import{ad as _p,bd as zp,cd as Dp,dd as Tp,ed as jp}from"../chunk-r763e19p.js";import{fd as wp}from"../chunk-be629jhq.js";import"../chunk-pkr6905p.js";import{hd as ex,id as gx,jd as rx,kd as vx}from"../chunk-eseshkd0.js";import{nd as Np}from"../chunk-11hdrnf6.js";import{od as Xf}from"../chunk-cwfkm7h9.js";import{pd as $x,qd as bx,rd as tx,sd as wx,td as Sx,ud as hx,vd as ux,wd as cx,xd as Vx}from"../chunk-mkzmjg3f.js";import{Ad as kd,Bd as qd,Cd as Jd,Dd as Kd,Ed as Qd,Fd as Wd,Gd as Xd,Hd as Yd,yd as Fd,zd as Hd}from"../chunk-vgtmrd4c.js";import{$d as Wf,Id as lf,Jd as yf,Kd as Cf,Ld as Nf,Md as _f,Nd as zf,Od as Df,Pd as Tf,Qd as jf,Rd as If,Sd as Lf,Td as Bf,Ud as Ff,Vd as Hf,Wd as kf,Xd as qf,Yd as Jf,Zd as Kf,_d as Qf}from"../chunk-nrr8z2z7.js";import"../chunk-xs12dtf1.js";import{ce as Rp,de as Mp,ee as Up,fe as Ap,ge as Gp,he as Ep,ie as Op,je as Pp,ke as ap,le as lp,me as yp}from"../chunk-tzwnfagh.js";import"../chunk-ytmxd5fk.js";import{Ae as Kp,Be as Qp,Ce as Wp,se as Ip,te as Lp,ue as Bp,ve as Fp,we as Hp,xe as kp,ye as qp,ze as Jp}from"../chunk-b9escac0.js";import{Je as Cp}from"../chunk-g30dr44w.js";import{Ke as Xp,Le as Yp,Me as Zp,Ne as $p,Oe as bp,Pe as tp}from"../chunk-2et8yavs.js";import"../chunk-txtrpypt.js";import{$e as _,We as a,Xe as l,Ye as y,Ze as C,_e as N,af as z,bf as D,cf as T,df as j,ef as I,ff as L,gf as B,hf as F,if as H}from"../chunk-8hjvthz4.js";import{jf as U,kf as A,lf as G,mf as E,nf as O,pf as P}from"../chunk-yngahb11.js";import{qf as Px,rf as ax,sf as lx,tf as yx,uf as Cx,vf as Nx}from"../chunk-08x5b93v.js";import{Af as kx,Bf as qx,Cf as Jx,Df as Kx,Ef as Qx,Ff as Wx,Gf as Xx,Hf as Yx,If as Zx,wf as Lx,xf as Bx,yf as Fx,zf as Hx}from"../chunk-p6qbqsyp.js";import"../chunk-1cpdz49v.js";import{Lf as _x,Mf as zx,Nf as Dx,Of as Tx,Pf as jx,Qf as Ix}from"../chunk-cgvt98pd.js";import"../chunk-c8rzx3a1.js";import{$f as pp,Uf as e,Vf as g,Wf as r,Xf as v,Yf as i,Zf as s,_f as n,ag as op,bg as d}from"../chunk-0hc97k0t.js";import"../chunk-3901s7h9.js";import"../chunk-jtxcr5yw.js";import"../chunk-qd2s51gc.js";import{$g as JR,Og as To,Pg as jo,Qg as Io,Rg as Lo,Tg as jR,Ug as IR,Vg as LR,Wg as BR,Xg as FR,Yg as HR,Zg as kR,_g as qR,ah as KR,bh as QR,ch as WR,dh as XR,eh as YR,fh as ZR,gh as $R,hh as bR,ih as tR,jh as wR,kh as SR,lh as hR,mh as uR}from"../chunk-vbeeyhhe.js";import{nh as om}from"../chunk-k26wnmzk.js";import{oh as S,ph as h,qh as u,rh as c,sh as V}from"../chunk-193abzy6.js";import{th as t}from"../chunk-5044y9en.js";import{uh as w}from"../chunk-f53y8ans.js";import{Ah as Y,vh as J,wh as K,xh as Q,yh as W,zh as X}from"../chunk-e68nf7cm.js";import{Bh as k,Ch as q,Dh as Z,Eh as $,Fh as b}from"../chunk-hfjywbbc.js";import"../chunk-g24hav8e.js";import"../chunk-q4t568hv.js";var{semver:m}=globalThis.Bun;class R{static compareVersions(p,o){return m.order(p,o)}static satisfiesRange(p,o){return m.satisfies(p,o)}static getLatestInRange(p,o){let f=p.filter((x)=>m.satisfies(x,o));if(f.length===0)return null;return f.sort((x,M)=>m.order(M,x))[0]}static createRange(p){return{raw:p,range:p.replace(/^[\^~>=<]+/,""),isExact:!/^[\^~>=<]/.test(p),satisfies:(o)=>this.satisfiesRange(o,p),getLatest:(o)=>this.getLatestInRange(o,p)}}static getUpdateType(p,o){return d(p,o)}static isSafeUpdate(p,o){return m.satisfies(o,p)}}export{Fx as writeFileTool,Yx as wrapUntrusted,gf as withTouchOffer,no as withNarrative,sf as verifyChanges,tR as validateWorkflowGeneration,wR as validateRepositoryAccess,Ud as validateFindings,Bo as validateConfig,Jo as validateAgainstSchema,HR as updateProgress,bf as unitTestsTouch,Sp as toOsvEcosystem,Hp as tagUpdateType,Kf as syntaxAnalyzer,lp as supports,z as summarizeUsage,fR as summarizeGates,lo as stripOperators,bd as stripNonCommandContext,nf as stackedBranchName,Mo as splitConstraint,op as sortUpdatesByPriority,wf as simplifyTouch,yR as similarity,Vx as sign,uR as showFinalInstructions,N as shouldOpenAsDraft,Yd as shouldFail,Jf as shellcheckAnalyzer,Kx as shellTool,hR as setupCustomWorkflow,$ as setDefaultLogger,ld as serializeReviewState,Af as serializeLearnings,Of as selectLearnings,Fp as selectLatestTag,qf as secretsAnalyzer,YR as schedulePlan,ao as scanEcosystems,vp as scanCatalogs,Bp as sameVariant,Go as rustAdapter,yf as runTool,pd as runStackedTouch,Bd as runReviewForPR,LR as runPreflightChecks,ER as runPostMerge,Zf as runPlan,Ko as runHeadless,xR as runGates,nd as runFixCi,Wf as runAnalyzers,UR as runAiGates,Zx as runAgent,A as ruleMatches,Ao as rubyAdapter,Ld as reviewPullRequest,Px as reviewMode,Ed as reviewDiff,Lx as resolveWorkspacePath,G as resolveRuleEffects,Op as resolveProviderToken,pf as resolveModelAlias,bp as resolveEngineVersion,Kp as resolveCredentials,ep as resolveCatalogReference,Id as resolveBuddyThreads,ff as resolveAiProvider,fm as resetConfigCache,Vf as renderTouchOffer,so as renderReport,TR as renderQuickLinks,aR as renderPackageContext,D as renderMigrationReport,Pf as renderLearnings,Td as renderFinding,qo as renderDoctorReport,xd as renderDiffForReview,_f as relativize,yo as regenerateLockfiles,xp as regenerateLockFile,Tx as redactError,Dx as redactDeep,zx as redact,Bx as readFileTool,Uo as pythonAdapter,Wo as publishOutput,Yo as productFor,jd as prepareReview,Sf as planTouch,yx as planMode,$p as pinBlocksUpdate,Ro as pep440UpdateType,Vp as parseWorkspaceCatalogs,md as parseUnifiedDiff,rf as parseTouchSelections,Nf as parseToolJson,Ip as parseTag,yd as parseReviewState,W as parseRetryDelay,qR as parseRemote,zR as parseQuickSelection,mo as parsePep440,g as parsePackageFile,Uf as parseLearnings,kp as parseImageRef,ho as parseHistory,td as parseCommand,Qp as parseAuthChallenge,If as offsetToLine,po as numericUpdateType,hp as normalizeSeverity,C as normalizePlan,Cd as needsReview,O as mergeGroupEffects,Sd as mentionsBot,B as matchesGlobs,Hf as markdownlintAnalyzer,zp as mapWithConcurrency,Cf as mapSeverity,af as loadLearnings,Vo as loadHistory,zd as loadGuidelines,Hx as listDirTool,Ff as linterAnalyzer,id as latestFailurePerWorkflow,wd as isReadOnlyCommand,fo as isPep440Prerelease,OR as isMergeEvent,gp as isCatalogReference,l as isAllowedCodemod,ax as implementMode,ef as hasTouchOffer,jf as hadolintAnalyzer,KR as guideTokenCreation,WR as guideRepositorySettings,P as groupsToRules,pp as groupUpdates,oo as goAdapter,Tf as githubActionsAnalyzer,bR as getWorkflowPreset,c as getNpmRegistryUrl,h as getGitHubServerUrl,S as getGitHubApiUrl,uf as getFinishingTouch,b as getDefaultLogger,xm as getConfig,V as getComposerRegistryUrl,mp as getAllLockFilePaths,Nx as getAgentMode,ZR as generateUnifiedWorkflow,jo as generateGitLabPipeline,$R as generateCoreWorkflows,XR as generateConfigFile,n as generateBranchName,Io as generateBitbucketPipeline,dR as gateIcon,kx as fsTools,e as formatSecurityAdvisorySection,Wd as formatReview,qd as formatPretty,i as formatPRTitle,s as formatPRBody,qp as formatImageRef,Qo as formatGithubOutput,Jd as formatGithub,q as formatError,Fo as formatConfigIssues,v as formatCommitMessage,Kd as formatAgent,lx as fixCiMode,Md as fingerprint,_ as findUsageSites,co as findPrevious,PR as findMentionedPackages,AR as findLinkedIssues,CR as findDuplicates,_o as findDrift,X as fetchWithTimeout,Y as fetchJsonOrNull,vd as failsOnBaseBranch,gd as extractErrorLines,Yp as extractEngines,Xf as emitEvent,U as ecosystemOf,Co as driftFor,$f as docstringsTouch,SR as displayValidationResults,kR as displayProgress,cd as dispatchCommand,Hd as diffArgsFor,ko as diagnose,fp as detectRequiredPackageManagers,JR as detectRepository,r as detectPackageManager,Bf as detectLinter,sp as detectFiles,od as detectChangedFiles,L as describeSpanGaps,rd as describeFailure,tx as describeEvent,to as describeEol,zo as describeDrift,Pd as defaultIncludePath,mm as defaultConfig,Ad as dedupeFindings,Zo as cycleFor,cx as createWebhookSink,hx as createSlackSink,Sx as createSinks,Yf as createReadIssueTool,ap as createProvider,FR as createProgressTracker,xf as createOpenAiProvider,Gf as createLearning,Vd as createHandlers,mf as createGoogleProvider,ux as createDiscordSink,of as createAnthropicProvider,df as createAiClient,Qd as countBySeverity,lR as constrainLabels,QR as confirmTokenSetup,dm as config,ro as computeMetrics,vo as computeDeltas,Dd as composeInstructions,Lp as compareVersions,xo as comparePep440,np as compareNumeric,zf as commandExists,I as collectSpanNotes,Zp as collectResolutionPins,kd as collectLocalDiff,fd as collectGitDiff,DR as clearQuickSelection,u as clearNpmrcCache,ed as classifyFailure,Lo as ciTemplateFor,Dp as chunk,pR as checkTitleFormat,ud as checkPermission,RR as checkLinkedIssue,$o as checkEol,oR as checkDescription,mR as checkDependencies,MR as checkCustomAssertions,tp as bumpEngineConstraint,Jx as buildShellEnv,y as buildAnalysisPrompt,tf as autofixTouch,T as attemptMajorUpgrade,sd as attemptFix,Ho as assertValidConfig,yp as assertSupports,Pp as assertProviderSupported,Xd as applySuggestion,E as applyRules,ip as applyCatalogUpdates,rp as applyCatalogUpdate,H as appendUpgradeReport,uo as appendHistory,GR as appendChangelogEntry,Jp as apiHostFor,Od as anchorMap,BR as analyzeProject,F as analyzeGroupMajors,cp as advisoryKey,Ef as addLearning,Po as adapterNamed,Oo as adapterFor,Df as actionlintAnalyzer,wx as WEBHOOK_PAYLOAD_VERSION,R as VersionResolver,Gp as UnsupportedProviderError,Xx as Toolbelt,Qx as ToolPermissionError,cf as TOUCH_OFFER_MARKER,lf as TOOL_TIMEOUT_MS,vf as TEST_COMMANDS,up as SecurityAdvisoryService,pm as Scheduler,qx as SHELL_ENV_ALLOWLIST,dd as SEVERITY_ORDER,kf as SECRET_RULES,Cp as ReleaseNotesFetcher,jp as RegistryClient,No as ROOT,ad as REVIEW_STATE_VERSION,Rd as REVIEW_SCHEMA,Fd as REVIEW_FORMATS,eo as REPORT_PERIODS,io as REPORT_MARKER,_x as REDACTED,$d as READ_ONLY_COMMANDS,NR as QUICK_LINKS_MARKER,_R as QUICK_ACTIONS,Np as PullRequestGenerator,IR as PluginManager,wp as PackageScanner,gx as PackageRegistryError,Up as PROVIDER_TRACKING_ISSUES,Ep as PROVIDER_TOKEN_ENV,nx as PROVIDER_PRIORITY,Rp as PROVIDER_NAMES,sx as PROVIDER_KEY_ENV,go as PERIOD_DAYS,Wp as OciClient,Ap as NO_CAPABILITIES,ix as MODEL_ALIASES,a as MIGRATION_PLAN_SCHEMA,_d as MAX_GUIDELINE_CHARS,Z as Logger,Lf as LINTER_SPECS,Xp as KNOWN_ENGINES,Mp as IMPLEMENTED_PROVIDERS,Q as HttpRequestError,wo as HISTORY_PATH,So as HISTORY_LIMIT,hd as HELP_TEXT,rx as GitProviderError,t as GitLabProvider,dp as GitHubProvider,k as GitHubApiError,om as GitHubActionsTemplate,hf as FINISHING_TOUCHES,bx as EventBus,$x as EVENT_NAMES,bo as EOL_WARNING_DAYS,Xo as EOL_PRODUCTS,J as DEFAULT_TIMEOUT_MS,j as DEFAULT_SPAN_BUDGET,To as DEFAULT_SCHEDULE,K as DEFAULT_RETRIES,Mf as DEFAULT_PROMPT_LIMIT,Rf as DEFAULT_LEARNINGS_FILE,Nd as DEFAULT_GUIDELINE_FILES,Gd as DEFAULT_EXCLUDED_PATHS,_p as DEFAULT_CONCURRENCY,jR as ConfigurationMigrator,vx as ConfigurationError,Zd as COMMAND_ALIASES,ex as BuddyError,Do as Buddy,w as BitbucketProvider,Wx as BUILTIN_TOOLS,Qf as BUILTIN_ANALYZERS,Eo as BUILTIN_ADAPTERS,Tp as AsyncMemo,Ix as AiProviderError,jx as AiBudgetExceededError,Cx as AGENT_MODES};
|
|
@@ -13,9 +13,17 @@ export declare function regenerateLockFile(packageManager: PackageManagerType, c
|
|
|
13
13
|
/**
|
|
14
14
|
* Examine which manifest files were updated to determine which package managers
|
|
15
15
|
* need lock file regeneration.
|
|
16
|
+
*
|
|
17
|
+
* `pantry.lock` records npm resolutions alongside system packages, so a
|
|
18
|
+
* `package.json` bump leaves it describing the old version just as surely as
|
|
19
|
+
* `bun.lock`. Pantry is therefore required whenever the project has a
|
|
20
|
+
* `pantry.lock` and any manifest it reads changed, and it is ordered last:
|
|
21
|
+
* it reconciles against the JS lockfile, which has to be regenerated first.
|
|
22
|
+
*
|
|
16
23
|
* @param updatedFilePaths - List of file paths that were updated
|
|
24
|
+
* @param cwd - Project root whose lock files decide the managers
|
|
17
25
|
*/
|
|
18
|
-
export declare function detectRequiredPackageManagers(updatedFilePaths: string[]): PackageManagerType[];
|
|
26
|
+
export declare function detectRequiredPackageManagers(updatedFilePaths: string[], cwd?: string): PackageManagerType[];
|
|
19
27
|
/**
|
|
20
28
|
* Check if a lock file exists for a given package manager in the working directory
|
|
21
29
|
*/
|
|
@@ -25,4 +33,4 @@ export declare interface LockFileResult {
|
|
|
25
33
|
packageManager: PackageManagerType
|
|
26
34
|
message: string
|
|
27
35
|
}
|
|
28
|
-
export type PackageManagerType = 'bun' | 'npm' | 'yarn' | 'pnpm' | 'composer';
|
|
36
|
+
export type PackageManagerType = 'bun' | 'npm' | 'yarn' | 'pnpm' | 'composer' | 'pantry';
|
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.5",
|
|
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",
|
package/dist/chunk-8fw0v7bv.js
DELETED
|
@@ -1,3 +0,0 @@
|
|
|
1
|
-
// @bun
|
|
2
|
-
import{Wf as T}from"./chunk-0hc97k0t.js";import{Fh as B}from"./chunk-hfjywbbc.js";import{Wk as W}from"./chunk-q4t568hv.js";import{spawn as X}from"child_process";import{existsSync as J}from"fs";import U from"process";function C(){return["bun.lock","bun.lockb","package-lock.json","yarn.lock","pnpm-lock.yaml","composer.lock","pantry.lock"]}function Y(b){switch(b){case"bun":return{command:"bun",args:["install"]};case"npm":return{command:"npm",args:["install"]};case"yarn":return{command:"yarn",args:["install"]};case"pnpm":return{command:"pnpm",args:["install"]};case"composer":return{command:"composer",args:["update","--lock"]}}}async function F(b,q,z=300000){let{command:E,args:K}=Y(b);return B().info(`\uD83D\uDD04 Regenerating lock file with ${b} (${E} ${K.join(" ")})...`),new Promise((H)=>{let G=X(E,K,{cwd:q,stdio:"pipe",env:{...U.env,CI:"true"}}),V="",O="",Q=!1,R=setTimeout(()=>{Q=!0,B().warn(`\u26A0\uFE0F ${b} install timed out after ${z/1000}s, sending SIGTERM...`),G.kill("SIGTERM"),setTimeout(()=>{if(!G.killed)B().warn(`\u26A0\uFE0F ${b} install did not exit after SIGTERM, sending SIGKILL...`),G.kill("SIGKILL")},1e4)},z);G.stdout?.on("data",(A)=>{V+=A.toString()}),G.stderr?.on("data",(A)=>{O+=A.toString()}),G.on("close",(A)=>{if(clearTimeout(R),Q){H({success:!1,packageManager:b,message:`Lock file regeneration timed out after ${z/1000}s`});return}if(A===0)B().info(`\u2705 Lock file regenerated successfully with ${b}`),H({success:!0,packageManager:b,message:"Lock file regenerated successfully"});else{if(B().warn(`\u26A0\uFE0F ${b} install exited with code ${A}`),O)B().warn(` stderr: ${O.slice(0,500)}`);H({success:!1,packageManager:b,message:`Install exited with code ${A}: ${O.slice(0,200)}`})}}),G.on("error",(A)=>{clearTimeout(R),B().warn(`\u26A0\uFE0F Failed to run ${E}: ${A.message}`),H({success:!1,packageManager:b,message:`Failed to run ${E}: ${A.message}`})})})}function N(b){let q=new Set;for(let z of b){let E=z.split("/").pop()||"";if(E==="package.json"){let K=U.cwd(),H=T(K);q.add(H)}if(E==="composer.json")q.add("composer")}return Array.from(q)}function P(b,q){let z=W("path");switch(b){case"bun":return J(z.join(q,"bun.lock"))||J(z.join(q,"bun.lockb"));case"npm":return J(z.join(q,"package-lock.json"));case"yarn":return J(z.join(q,"yarn.lock"));case"pnpm":return J(z.join(q,"pnpm-lock.yaml"));case"composer":return J(z.join(q,"composer.lock"))}}
|
|
3
|
-
export{C as Kc,F as Lc,N as Mc,P as Nc};
|