@buddysh/buddy 0.11.2 → 0.11.4
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 +30 -0
- package/dist/bin/cli.js +11 -11
- package/dist/{chunk-ncrq3fvv.js → chunk-28y7eayr.js} +1 -1
- package/dist/{chunk-1c4690h9.js → chunk-4jyw358y.js} +1 -1
- package/dist/{chunk-p8tmms5h.js → chunk-5av2vnvv.js} +1 -1
- package/dist/{chunk-hwxmhkxp.js → chunk-86x1vsjw.js} +1 -1
- package/dist/{chunk-t25apff9.js → chunk-b1w41hfs.js} +1 -1
- package/dist/chunk-bmnx3s41.js +38 -0
- package/dist/{chunk-0eg3kxb5.js → chunk-cs066zt9.js} +1 -1
- package/dist/{chunk-x23a6szw.js → chunk-e0gweha1.js} +1 -1
- package/dist/chunk-e2t5jq26.js +106 -0
- package/dist/{chunk-hbhmns7s.js → chunk-emb5v4wv.js} +1 -1
- package/dist/{chunk-657nbbp7.js → chunk-jz5zs812.js} +1 -1
- package/dist/{chunk-15r904nz.js → chunk-ngh4jbgp.js} +2 -2
- package/dist/{chunk-cwqhxqv7.js → chunk-patms7t8.js} +1 -1
- package/dist/{chunk-929h6hhp.js → chunk-rayxmbcx.js} +1 -1
- package/dist/{chunk-847g7jde.js → chunk-rwggcfgn.js} +1 -1
- package/dist/{chunk-y3dd8v85.js → chunk-s25rb4t2.js} +1 -1
- package/dist/{chunk-bymwaezh.js → chunk-vbeeyhhe.js} +3 -2
- package/dist/{chunk-6bd8ghkz.js → chunk-yr8eta7p.js} +1 -1
- package/dist/src/index.js +1 -1
- package/dist/src/setup.js +1 -1
- package/package.json +7 -7
- package/dist/chunk-dqbk3kcj.js +0 -104
- package/dist/chunk-tws3npt7.js +0 -38
package/dist/chunk-dqbk3kcj.js
DELETED
|
@@ -1,104 +0,0 @@
|
|
|
1
|
-
// @bun
|
|
2
|
-
import{$c as c0}from"./chunk-phfmnnne.js";import{bd as S0,cd as B0,dd as w0,ed as g0}from"./chunk-r763e19p.js";import{fd as l0}from"./chunk-be629jhq.js";import{ld as _0,md as O0,nd as h0}from"./chunk-11hdrnf6.js";import{qd as m0,td as f0}from"./chunk-mkzmjg3f.js";import{ke as e,le as p}from"./chunk-p8tmms5h.js";import{if as y0}from"./chunk-8hjvthz4.js";import{lf as g,mf as k0,nf as H0,of as P0,pf as o}from"./chunk-yngahb11.js";import{$f as Z0,ag as v0,bg as l}from"./chunk-0hc97k0t.js";import{kg as f,og as R0,pg as b0}from"./chunk-3901s7h9.js";import{ph as Y0}from"./chunk-193abzy6.js";import{zh as W0}from"./chunk-e68nf7cm.js";import{Bh as C0,Ch as N0,Dh as x0,Eh as U0}from"./chunk-hfjywbbc.js";import{Wk as V}from"./chunk-q4t568hv.js";import F0 from"fs";import{join as a}from"path";import d from"process";var n0={critical:"\uD83D\uDD34 Critical",high:"\uD83D\uDFE0 High",moderate:"\uD83D\uDFE1 Moderate",low:"\u26AA Low"};class X0{generateDashboard($,X={}){let{showOpenPRs:Q=!0,showDetectedDependencies:K=!0,showDeprecatedDependencies:H=!0,showVulnerableDependencies:Y=!0,includePackageJson:W=!0,includeDependencyFiles:O=!0,includeGitHubActions:j=!0,bodyTemplate:J}=X,_="Dependency Dashboard";if(J)return{title:"Dependency Dashboard",body:this.applyTemplate(J,$)};let Z=this.generateDefaultHeader($);if(Y&&$.vulnerableDependencies&&$.vulnerableDependencies.length>0)Z+=this.generateVulnerableDependenciesSection($.vulnerableDependencies);if(H&&$.deprecatedDependencies&&$.deprecatedDependencies.length>0)Z+=this.generateDeprecatedDependenciesSection($.deprecatedDependencies);if(Q&&$.openPRs.length>0)Z+=this.generateOpenPRsSection($.openPRs);if($.cappedDependencies&&$.cappedDependencies.length>0)Z+=this.generateCappedDependenciesSection($.cappedDependencies);if(K)Z+=this.generateDetectedDependenciesSection({packageJson:W?$.detectedDependencies.packageJson:[],dependencyFiles:O?$.detectedDependencies.dependencyFiles:[],githubActions:j?$.detectedDependencies.githubActions:[]});return Z+=this.generateFooter(),{title:"Dependency Dashboard",body:Z}}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
|
-
|
|
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
|
-
|
|
6
|
-
The following packages are held below their latest version by a range declared elsewhere in the dependency tree. Updating this repository cannot move them \u2014 the constraint has to be widened where it is declared.
|
|
7
|
-
|
|
8
|
-
| Package | Installed | Reachable | Latest | Capped by |
|
|
9
|
-
|---|---|---|---|---|
|
|
10
|
-
`;for(let Q of $){let K=Q.capping.map((H)=>`\`${this.sanitizeReferences(H.by)}\` (\`${H.range}\`)`).join(", ");X+=`| \`${this.sanitizeReferences(Q.name)}\` | \`${Q.installed}\` | \`${Q.reachable}\` | \`${Q.latest}\` | ${K} |
|
|
11
|
-
`}return`${X}
|
|
12
|
-
`}generateOpenPRsSection($){let X=`## Open
|
|
13
|
-
|
|
14
|
-
The following updates have all been created. To force a retry/rebase of any, click on a checkbox below.
|
|
15
|
-
|
|
16
|
-
`;for(let Q of $){let K=this.extractPackageInfo(Q),H=Q.head.replace(/[<>\s]|-->/g,""),Y=this.toRelativePrUrl(Q.url,Q.number)??Q.url,W=this.sanitizeReferences(Q.title);if(X+=` - [ ] <!-- rebase-branch=${H} -->[${W}](${Y})`,K.length>0)X+=` (\`${K.join("`, `")}\`)`;X+=`
|
|
17
|
-
`}return X+=` - [ ] <!-- rebase-all-open-prs -->**Click on this checkbox to rebase all open PRs at once**
|
|
18
|
-
`,X+=`
|
|
19
|
-
`,X}generateDetectedDependenciesSection($){let X=`## Detected dependencies
|
|
20
|
-
|
|
21
|
-
`;if($.packageJson.length>0)X+=this.generatePackageJsonSection($.packageJson);let Q=$.dependencyFiles.filter((W)=>W.path==="composer.json"||W.path.endsWith("/composer.json")),K=Q.filter((W)=>W.path==="composer.json"),H=Q.filter((W)=>W.path!=="composer.json");if(K.length>0)X+=this.generateComposerSection(K);if($.githubActions.length>0)X+=this.generateGitHubActionsSection($.githubActions);let Y=$.dependencyFiles.filter((W)=>!W.path.endsWith("/composer.json")&&W.path!=="composer.json");if(Y.length>0||H.length>0)X+=this.generateDependencyFilesSection([...Y,...H]);return X}generatePackageJsonSection($){let X=`<details><summary>npm</summary>
|
|
22
|
-
<blockquote>
|
|
23
|
-
|
|
24
|
-
`;for(let Q of $){let K=Q.path.split("/").pop()||Q.path;X+=`<details><summary>${K}</summary>
|
|
25
|
-
|
|
26
|
-
`;let H={dependencies:Q.dependencies.filter((Y)=>Y.type==="dependencies"),devDependencies:Q.dependencies.filter((Y)=>Y.type==="devDependencies"),peerDependencies:Q.dependencies.filter((Y)=>Y.type==="peerDependencies"),optionalDependencies:Q.dependencies.filter((Y)=>Y.type==="optionalDependencies")};for(let[Y,W]of Object.entries(H))if(W.length>0)for(let O of W)X+=` - \`${O.name} ${O.currentVersion}\`
|
|
27
|
-
`;X+=`
|
|
28
|
-
</details>
|
|
29
|
-
|
|
30
|
-
`}return X+=`</blockquote>
|
|
31
|
-
</details>
|
|
32
|
-
|
|
33
|
-
`,X}generateGitHubActionsSection($){let X=`<details><summary>github-actions</summary>
|
|
34
|
-
<blockquote>
|
|
35
|
-
|
|
36
|
-
`;for(let Q of $){X+=`<details><summary>${Q.path}</summary>
|
|
37
|
-
|
|
38
|
-
`;let K=new Map;for(let H of Q.dependencies){let Y=`${H.name}@${H.currentVersion}`;if(!K.has(Y))K.set(Y,{name:H.name,currentVersion:H.currentVersion})}for(let H of K.values())X+=` - \`${H.name} ${H.currentVersion}\`
|
|
39
|
-
`;X+=`
|
|
40
|
-
</details>
|
|
41
|
-
|
|
42
|
-
`}return X+=`</blockquote>
|
|
43
|
-
</details>
|
|
44
|
-
|
|
45
|
-
`,X}generateDependencyFilesSection($){let X=`<details><summary>dependency-files</summary>
|
|
46
|
-
<blockquote>
|
|
47
|
-
|
|
48
|
-
`;for(let Q of $){X+=`<details><summary>${Q.path}</summary>
|
|
49
|
-
|
|
50
|
-
`;for(let K of Q.dependencies)X+=` - \`${K.name} ${K.currentVersion}\`
|
|
51
|
-
`;X+=`
|
|
52
|
-
</details>
|
|
53
|
-
|
|
54
|
-
`}return X+=`</blockquote>
|
|
55
|
-
</details>
|
|
56
|
-
|
|
57
|
-
`,X}generateComposerSection($){let X=`<details><summary>composer</summary>
|
|
58
|
-
<blockquote>
|
|
59
|
-
|
|
60
|
-
`;for(let Q of $){let K=Q.path.split("/").pop()||Q.path;X+=`<details><summary>${K}</summary>
|
|
61
|
-
|
|
62
|
-
`;let H={require:Q.dependencies.filter((Y)=>Y.type==="require"),"require-dev":Q.dependencies.filter((Y)=>Y.type==="require-dev")};for(let[Y,W]of Object.entries(H))if(W.length>0)for(let O of W)X+=` - \`${O.name} ${O.currentVersion}\`
|
|
63
|
-
`;X+=`
|
|
64
|
-
</details>
|
|
65
|
-
|
|
66
|
-
`}return X+=`</blockquote>
|
|
67
|
-
</details>
|
|
68
|
-
|
|
69
|
-
`,X}generateVulnerableDependenciesSection($){let X=$.reduce((K,H)=>K+H.advisories.length,0),Q=`> [!CAUTION]
|
|
70
|
-
> ${X} known ${X===1?"vulnerability affects":"vulnerabilities affect"} ${$.length} ${$.length===1?"dependency":"dependencies"} in this repository.
|
|
71
|
-
|
|
72
|
-
| Severity | Package | Current | Advisory | Fixed in |
|
|
73
|
-
|----------|---------|---------|----------|----------|
|
|
74
|
-
`;for(let K of $)for(let H of K.advisories){let Y=n0[H.severity]??H.severity,W=H.url?`[${H.id}](${H.url})`:H.id;Q+=`| ${Y} | \`${K.name}\` | \`${K.currentVersion}\` | ${W} | \`${H.fixedVersion??"n/a"}\` |
|
|
75
|
-
`}return Q+=`
|
|
76
|
-
`,Q}generateDeprecatedDependenciesSection($){let X=`> [!WARNING]
|
|
77
|
-
> These dependencies are deprecated and should be updated to avoid potential security risks and compatibility issues.
|
|
78
|
-
|
|
79
|
-
| Datasource | Name | Replacement PR? |
|
|
80
|
-
|------------|------|-----------------|
|
|
81
|
-
`;for(let Q of $){let K=`\`${Q.name}\``,Y=(Q.replacementAvailable?"available":"unavailable")==="available"?"":"";X+=`| ${Q.datasource} | ${K} | ${Y} |
|
|
82
|
-
`}return X+=`
|
|
83
|
-
`,X}generateFooter(){return`---
|
|
84
|
-
|
|
85
|
-
- [ ] <!-- manual job -->Check this box to trigger a request for Buddy to run again on this repository
|
|
86
|
-
`}extractPackageInfo($){let X=[],Q=[/update.*?dependency\s+(\S+)/i,/update\s+require(?:-dev)?\s+(\S+)\s+to\s+v?\d+/i,/update\s+(\S+)\s+to\s+v?\d+/i,/bump\s+(\S+)\s+from/i,/chore\(deps\):\s*update\s+dependency\s+(\S+)/i];for(let H of Q){let Y=$.title.match(H);if(Y&&Y[1]&&!X.includes(Y[1]))X.push(Y[1])}let K=[{name:"npm",pattern:/### npm Dependencies[\s\S]*?(?=###|\n\n---|z)/i},{name:"pkgx",pattern:/### Launchpad\/pkgx Dependencies[\s\S]*?(?=###|\n\n---|z)/i},{name:"actions",pattern:/### GitHub Actions[\s\S]*?(?=###|\n\n---|z)/i}];for(let H of K){let Y=$.body.match(H.pattern);if(Y){let O=Y[0].match(/\|\s*\[([^\]]+)\]\([^)]+\)\s*\|/g);if(O)for(let j of O){let J=j.match(/\|\s*\[([^\]]+)\]/);if(J&&J[1]){let _=J[1].trim();if(_.includes("`")&&_.includes("->")){let Z=j.match(/\]\(([^)]+)\)/);if(Z&&Z[1]){let L=Z[1].match(/\/diffs\/npm\/([^/]+)\//);if(L&&L[1]){let S=decodeURIComponent(L[1]);if(S&&S.length>1&&!X.includes(S))X.push(S)}}continue}if(!_.includes("://")&&!_.includes("Compare Source")&&!_.includes("badge")&&!_.includes("!")&&!_.startsWith("[![")&&!_.includes("`")&&!_.includes("->")&&!_.includes(" -> ")&&!_.match(/^\d+\.\d+/)&&!_.includes(" ")&&_.length>0&&!X.includes(_))X.push(_)}}}}if(X.length<3){let H=$.body.match(/`([^`]+)`/g);if(H)for(let Y of H){let W=Y.replace(/`/g,"").trim();if(W.includes("->")||W.includes(" -> ")||W.includes("` -> `")||W.match(/^\d+\.\d+/)||W.match(/^v\d+/)||W.match(/[\d.]+\s*->\s*[\d.]+/)||W.match(/^[\d.]+$/)||W.match(/^\d+\.\d+\.\d+/)||W.match(/^\d+\.\d+\.\d+\./)||W.match(/^\^?\d+\.\d+/)||W.match(/^~\d+\.\d+/)||W.includes("://")||W.includes("Compare Source")||W.includes("badge")||W.includes(" "))continue;if(W=W.split(",")[0].trim(),W&&W.length>1&&!X.includes(W)&&(W.startsWith("@")||W.includes("/")||W.match(/^[a-z][a-z0-9.-]*$/i)))X.push(W)}}return X}applyTemplate($,X){return $.replace(/\{\{repository\.owner\}\}/g,X.repository.owner).replace(/\{\{repository\.name\}\}/g,X.repository.name).replace(/\{\{openPRs\.count\}\}/g,X.openPRs.length.toString()).replace(/\{\{lastUpdated\}\}/g,X.lastUpdated.toISOString()).replace(/\{\{detectedDependencies\.packageJson\.count\}\}/g,X.detectedDependencies.packageJson.length.toString()).replace(/\{\{detectedDependencies\.githubActions\.count\}\}/g,X.detectedDependencies.githubActions.length.toString()).replace(/\{\{detectedDependencies\.dependencyFiles\.count\}\}/g,X.detectedDependencies.dependencyFiles.length.toString())}}var d0="buddy/",p0="no-auto-merge";function n($){let X=$.pullRequest?.autoMerge;return{enabled:X?.enabled??!1,strategy:X?.strategy??"squash",conditions:X?.conditions??[],requireGreenCI:X?.requireGreenCI??!0,optOutLabel:X?.optOutLabel??p0,securityLabel:$.security?.label??"security"}}function V0($,X,Q){let K=n(X);if(!K.enabled)return{eligible:!1,reason:"auto-merge is disabled by config"};if(K.conditions.length===0)return{eligible:!1,reason:"no auto-merge conditions configured (set conditions to at least one of patch-only, minor-only, security-only, all)"};if(!$.head.startsWith(d0))return{eligible:!1,reason:`PR #${$.number} is not a buddy PR (branch: ${$.head})`};if($.draft)return{eligible:!1,reason:`PR #${$.number} is a draft`};let H=$.labels??[];if(H.includes(K.optOutLabel))return{eligible:!1,reason:`PR #${$.number} carries the ${K.optOutLabel} label`};if(K.requireGreenCI&&Q===!1)return{eligible:!1,reason:`PR #${$.number} has failing or pending checks`};let Y=f($.body);if(!Y)return{eligible:!1,reason:`PR #${$.number} has no metadata manifest to verify update types against`};if(Y.truncated)return{eligible:!1,reason:`PR #${$.number} has a truncated manifest, so its full update set cannot be verified`};let W=D0(Y,X);if(W)return W;return E0(Y,H,K)}function D0($,X){let Q=[...o(X.packages?.groups),...X.packages?.rules??[]];if(Q.length===0||$.updates.length===0)return null;if(!$.updates.every((Y)=>Y.type&&Y.dependencyType))return null;let H=$.updates.map((Y)=>g(i0(Y),Q));if(H.some((Y)=>Y.autoMerge===!1))return{eligible:!1,reason:"a package rule holds one of these updates back from auto-merge"};if(H.every((Y)=>Y.autoMerge===!0))return{eligible:!0,reason:"every update is covered by a package rule that enables auto-merge"};return null}function i0($){return{name:$.name,currentVersion:$.current,newVersion:$.target,updateType:$.type,file:$.file,dependencyType:$.dependencyType}}function E0($,X,Q){for(let H of Q.conditions)switch(H){case"all":return{eligible:!0,reason:"all updates qualify (condition: all)"};case"patch-only":if($.updates.length>0&&$.updates.every((Y)=>Q0(Y)==="patch"))return{eligible:!0,reason:"every update is a patch"};break;case"minor-only":if($.updates.length>0&&$.updates.every((Y)=>Q0(Y)!=="major"))return{eligible:!0,reason:"every update is minor or patch"};break;case"security-only":if(X.includes(Q.securityLabel))return{eligible:!0,reason:"PR resolves a security advisory"};break}return{eligible:!1,reason:`update types (${[...new Set($.updates.map(Q0))].join(", ")||"none"}) do not satisfy conditions (${Q.conditions.join(", ")})`}}function Q0($){if($.type==="major"||$.type==="minor"||$.type==="patch")return $.type;let X=G0($.current),Q=G0($.target);if(!X||!Q)return"major";if(X[0]!==Q[0])return"major";if(X[1]!==Q[1])return"minor";return"patch"}function G0($){let X=$.trim().match(/(\d+)\.(\d+)\.(\d+)/);if(!X)return null;return[Number(X[1]),Number(X[2]),Number(X[3])]}function I0($,X,Q){let K=n(Q);if(!K.enabled)return{eligible:!1,reason:"auto-merge is disabled by config"};if(K.conditions.length===0)return{eligible:!1,reason:"no auto-merge conditions configured"};if(X.includes(K.optOutLabel))return{eligible:!1,reason:`PR carries the ${K.optOutLabel} label`};let H={schemaVersion:1,updates:$.map((W)=>({name:W.name,current:W.currentVersion,target:W.newVersion,type:W.updateType,file:W.file,dependencyType:W.dependencyType}))},Y=D0(H,Q);if(Y)return Y;return E0(H,X,K)}var A0="https://api.osv.dev",s0=1000,s={low:0,moderate:1,high:2,critical:3};function K0($){switch($){case"dependencies":case"devDependencies":case"peerDependencies":case"optionalDependencies":return"npm";case"require":case"require-dev":return"Packagist";case"python":return"PyPI";case"rust":return"crates.io";case"go":return"Go";case"ruby":return"RubyGems";case"github-actions":return"GitHub Actions";default:return null}}function r0($){let X=$.database_specific?.severity?.toLowerCase();if(X==="low"||X==="moderate"||X==="high"||X==="critical")return X;if(X==="medium")return"moderate";let Q=$.severity?.find((K)=>K.type?.startsWith("CVSS"))?.score;if(Q){let K=t0(Q);if(K!==null){if(K>=9)return"critical";if(K>=7)return"high";if(K>=4)return"moderate";return"low"}}return"moderate"}function t0($){let X=Number($);if(Number.isFinite(X))return X;let Q=$.match(/\/([0-9](?:\.[0-9])?)$/);if(Q){let K=Number(Q[1]);return Number.isFinite(K)?K:null}return null}function a0($,X){for(let Q of $.affected??[]){if(Q.package?.name!==X)continue;for(let K of Q.ranges??[])for(let H of K.events??[])if(H.fixed)return H.fixed}return}class t{logger;concurrency;detailCache=new w0;constructor($,X=8){this.logger=$;this.concurrency=X}async findAdvisories($){let X=new Map;if($.length===0)return X;let Q=await this.queryBatch($),K=[...new Set([...Q.values()].flat())];if(K.length===0)return X;this.logger.debug(`Fetching details for ${K.length} advisory record(s)`);let H=await S0(K,(W)=>this.fetchVulnerability(W),this.concurrency),Y=new Map;for(let W of H)if(W)Y.set(W.id,W);for(let[W,O]of Q){let j=W.slice(W.indexOf(":")+1,W.lastIndexOf("@")),J=[];for(let _ of O){let Z=Y.get(_);if(!Z)continue;J.push({id:Z.id,aliases:Z.aliases??[],summary:Z.summary??Z.details?.split(`
|
|
87
|
-
`)[0]??"No summary provided",severity:r0(Z),url:`https://osv.dev/vulnerability/${Z.id}`,fixedVersion:a0(Z,j)})}if(J.length>0)J.sort((_,Z)=>s[Z.severity]-s[_.severity]),X.set(W,J)}return X}async annotateUpdates($,X="low"){let Q=[],K=[];if($.forEach((O,j)=>{let J=K0(O.dependencyType);if(!J)return;let _=M0(O.currentVersion);if(!_)return;let Z=J==="GitHub Actions"?_.replace(/^v/i,""):_;if(!Z)return;Q.push({name:O.name,version:Z,ecosystem:J}),K.push(j)}),Q.length===0)return $;let H=await this.findAdvisories(Q),Y=s[X],W=0;if(Q.forEach((O,j)=>{let J=H.get(r(O));if(!J?.length)return;let _=$[K[j]],Z=J.filter((z)=>{if(s[z.severity]<Y)return!1;if(!z.fixedVersion)return!1;return e0(M0(_.newVersion),z.fixedVersion)});if(Z.length>0)_.securityAdvisories=Z,W++}),W>0)this.logger.info(`\uD83D\uDD12 ${W} update(s) resolve known security advisories`);return $}async queryBatch($){let X=new Map,Q=B0($,s0);for(let K of Q)try{let H=await W0(`${A0}/v1/querybatch`,{method:"POST",headers:{"Content-Type":"application/json","User-Agent":"buddy"},body:JSON.stringify({queries:K.map((W)=>({package:{name:W.name,ecosystem:W.ecosystem},version:W.version}))}),retryNonIdempotent:!0,onRetry:({delayMs:W,reason:O})=>this.logger.debug(`OSV batch retry in ${Math.round(W/1000)}s (${O})`)});if(!H.ok){this.logger.warn(`OSV advisory lookup failed: HTTP ${H.status}`);continue}(await H.json()).results?.forEach((W,O)=>{let j=W.vulns?.map((J)=>J.id)??[];if(j.length>0)X.set(r(K[O]),j)})}catch(H){this.logger.warn("OSV advisory lookup failed:",H)}return X}async fetchVulnerability($){return this.detailCache.get($,async()=>{try{let X=await W0(`${A0}/v1/vulns/${encodeURIComponent($)}`,{headers:{"User-Agent":"buddy"}});if(!X.ok)return null;return await X.json()}catch(X){return this.logger.debug(`Failed to fetch advisory ${$}:`,X),null}})}}function r($){return`${$.ecosystem}:${$.name}@${$.version}`}function M0($){return $.replace(/^[\^~>=<\s]*v?/,"").trim()}function e0($,X){if(!$||!X)return!1;try{return Bun.semver.order($,X)>=0}catch{return!1}}import $1 from"process";function X1($){if(!$)return null;let X=$.split("/").filter(Boolean);if(X.length<2)return null;return{owner:X.slice(0,-1).join("/"),name:X[X.length-1]}}var Q1=["GITHUB_REPOSITORY","CI_PROJECT_PATH","BITBUCKET_REPO_FULL_NAME"];function W1($){for(let X of Q1){let Q=X1($[X]);if(Q)return Q}return null}function T0($,X=$1.env){if(!$.repository)return{source:"unresolved",overrodeConfig:!1};let Q=$.repository,K=W1(X),H=Boolean(Q.owner&&Q.name);if(!K)return H?{owner:Q.owner,name:Q.name,source:"config",overrodeConfig:!1}:{source:"unresolved",overrodeConfig:!1};if(H&&(Q.owner!==K.owner||Q.name!==K.name)){let O=`Configured repository ${`${Q.owner}/${Q.name}`} does not match the checked-out repository ${K.owner}/${K.name}. Using ${K.owner}/${K.name} \u2014 buddy `+"operates on the checked-out repository. Update repository.owner/repository.name in your buddy config to silence this warning.";if(Q.owner=K.owner,Q.name=K.name,$.dashboard?.issueNumber!==void 0)$.dashboard.issueNumber=void 0;return{owner:K.owner,name:K.name,source:"environment",overrodeConfig:!0,warning:O}}if(!H)return Q.owner||=K.owner,Q.name||=K.name,{owner:K.owner,name:K.name,source:"environment",overrodeConfig:!1};return{owner:Q.owner,name:Q.name,source:"config",overrodeConfig:!1}}class $0{config;projectPath;logger;scanner;registryClient;eventBus=null;dashboardGenerator;constructor($,X=d.cwd()){this.config=$;this.projectPath=X;this.logger=new x0($.verbose??!1,$.logLevel),U0(this.logger),this.resolveRepositoryConfig(),this.scanner=new l0(this.projectPath,this.logger,this.config.packages?.ignorePaths),this.registryClient=new g0(this.projectPath,this.logger,this.config),this.dashboardGenerator=new X0}async analyzeMajors($,X){if(!this.config.ai?.majorUpgrades?.enabled)return{report:"",draft:!1};let{analyzeGroupMajors:Q}=await import("./chunk-vdd1cghr.js"),{createAiClient:K}=await import("./chunk-hsa07n7c.js"),{ReleaseNotesFetcher:H}=await import("./chunk-2wj5xtdn.js"),Y=new H(this.logger),W=await Q({updates:$,config:this.config,workspace:this.projectPath,baseBranch:this.config.repository?.baseBranch||"main",files:X,ai:K(this.config,this.logger),fetchReleases:(O,j,J)=>Y.fetchSpanReleases(O,j,J),logger:this.logger});return{report:W.report,draft:W.draft}}resolveRepositoryConfig(){let $=T0(this.config);if($.warning)this.logger.warn(`\u26A0\uFE0F ${$.warning}`);else if($.source==="environment")this.logger.info(`Auto-detected repository: ${$.owner}/${$.name} from GITHUB_REPOSITORY`)}async scanForUpdates(){let $=Date.now();this.logger.info("Starting dependency update scan...");try{let X=Date.now(),Q=await this.scanner.scanProject();this.logger.info(`\u23F1\uFE0F Package file scan took ${Date.now()-X}ms`);let K=Q.reduce((C,m)=>C+m.dependencies.length,0),H=[],Y=Date.now();if(this.config.packages?.ignore&&this.config.packages.ignore.length>0)H=(await this.registryClient.getOutdatedPackages()).filter((m)=>!this.config.packages.ignore.includes(m.name));else H=await this.registryClient.getOutdatedPackages();this.logger.info(`\u23F1\uFE0F bun outdated check took ${Date.now()-Y}ms (found ${H.length} updates)`);let W=Date.now(),O=await this.checkDependencyFilesForUpdates(Q);this.logger.info(`\u23F1\uFE0F Dependency file checks took ${Date.now()-W}ms (found ${O.length} updates)`);let j=Date.now(),J=await this.checkGitHubActionsForUpdates(Q);this.logger.info(`\u23F1\uFE0F GitHub Actions checks took ${Date.now()-j}ms (found ${J.length} updates)`);let _=Date.now(),Z=await this.checkDockerfilesForUpdates(Q);this.logger.info(`\u23F1\uFE0F Docker image checks took ${Date.now()-_}ms (found ${Z.length} updates)`);let z=Date.now(),L=await this.checkZigForUpdates(Q),S=this.config.packages?.engines===!0?await this.checkEnginesForUpdates(Q):[];this.logger.info(`\u23F1\uFE0F Zig dependency checks took ${Date.now()-z}ms (found ${L.length} updates)`);let{scanCatalogs:B}=await import("./chunk-0paakbpj.js"),E=await B(this.projectPath,(C)=>this.registryClient.getLatestVersion(C),{...this.config.packages?.ignore?{ignore:this.config.packages.ignore}:{},logger:this.logger});if(E.entries.length>0)this.logger.info(`\uD83D\uDCE6 pnpm catalogs: ${E.updates.length} update(s) across ${E.entries.length} entr(ies)`);let U=Date.now(),{scanEcosystems:A}=await import("./chunk-dgfb8k0h.js"),T=await A({dir:this.projectPath,...this.config.packages?.includePrerelease!==void 0?{includePrerelease:this.config.packages.includePrerelease}:{},...this.config.packages?.ignore?{ignore:this.config.packages.ignore}:{},logger:this.logger});if(T.manifests.length>0)this.logger.info(`\u23F1\uFE0F Ecosystem checks took ${Date.now()-U}ms (found ${T.updates.length} updates across ${T.manifests.map((C)=>C.ecosystem).join(", ")})`);let q=[...H,...O,...J,...Z,...L,...S,...T.updates,...E.updates];if(this.config.packages?.ignore&&this.config.packages.ignore.length>0)q=q.filter((C)=>!this.config.packages.ignore.includes(C.name));let N=Date.now();if(this.config.packages?.strategy)q=this.filterUpdatesByStrategy(q,this.config.packages.strategy);this.logger.info(`\u23F1\uFE0F Strategy filtering took ${Date.now()-N}ms`);let b=Date.now();q=await this.filterUpdatesByMinimumReleaseAge(q),this.logger.info(`\u23F1\uFE0F Minimum release age filtering took ${Date.now()-b}ms`),q=this.applyPins(q),q=await this.dropOverriddenUpdates(q,Q),q=this.applyPackageRules(q);let c=Date.now();q=await this.annotateSecurityAdvisories(q),this.logger.info(`\u23F1\uFE0F Security advisory lookup took ${Date.now()-c}ms`);let h=this.config.security?.prioritize??!0,I=Date.now();q=v0(q,{prioritizeSecurity:h}),this.logger.info(`\u23F1\uFE0F Sorting took ${Date.now()-I}ms`);let F=Date.now(),z0=this.config.packages?.groups?this.groupUpdatesByConfig(q):Z0(q,{prioritizeSecurity:h});this.logger.info(`\u23F1\uFE0F Grouping took ${Date.now()-F}ms`);let u=Date.now()-$,y={totalPackages:K,updates:q,groups:z0,scannedAt:new Date,duration:u};return this.logger.success(`Scan completed in ${u}ms. Found ${q.length} updates.`),await this.events.emit("scan.completed",{total:q.length,major:q.filter((C)=>C.updateType==="major").length,minor:q.filter((C)=>C.updateType==="minor").length,patch:q.filter((C)=>C.updateType==="patch").length}),y}catch(X){throw this.logger.error("Failed to scan for updates:",X),X}}prTitleFor($){let X=this.config.pullRequest?.titleFormat;if(!X)return $.title;return _0(X,O0($,{title:$.title},this.config.packages?.strategy))}commitMessageFor($,X){let Q=this.config.pullRequest?.commitMessageFormat,K=Q?_0(Q,O0($,{message:$.title,title:$.title},this.config.packages?.strategy)):$.title;return X?`${K} ${X}`:K}applyPackageRules($){let X=this.config.packages?.rules??[],K=[...o(this.config.packages?.groups),...X];if(K.length===0)return $;let H=k0($,K);if(H.length<$.length)this.logger.info(`\uD83D\uDCCB Package rules dropped ${$.length-H.length} update(s)`);return H.map((Y)=>Y.update)}static mergeUnique($,X){let Q=[...new Set([...$??[],...X])];return Q.length>0?Q:void 0}labelsFor($,X){let Q=$.updates.some((K)=>(K.securityAdvisories?.length??0)>0);return[...new Set([...X.generateLabels($),...Q?[this.config.security?.label??"security"]:[],...this.config.pullRequest?.labels??[],...this.groupEffectsFor($.updates).labels])]}activeRules(){return[...o(this.config.packages?.groups),...this.config.packages?.rules??[]]}groupEffectsFor($){let X=this.activeRules();if(X.length===0)return H0([]);return H0($.map((Q)=>g(Q,X)))}orderGroupsByPriority($){if(this.activeRules().length===0)return $;return $.map((Q,K)=>({group:Q,index:K,priority:this.groupEffectsFor(Q.updates).prPriority})).sort((Q,K)=>K.priority-Q.priority||Q.index-K.index).map((Q)=>Q.group)}async dropOverriddenUpdates($,X){let Q=X.filter((W)=>W.type==="package.json");if(Q.length===0)return $;let{collectResolutionPins:K,pinBlocksUpdate:H}=await import("./chunk-pskqrv5r.js"),Y=new Map;for(let W of Q)try{for(let O of K(JSON.parse(W.content)))Y.set(O.name,{version:O.version,field:O.field})}catch{continue}if(Y.size===0)return $;return $.filter((W)=>{let O=Y.get(W.name);if(!O)return!0;if(!H({name:W.name,version:O.version,field:O.field},W.newVersion))return!0;return this.logger.info(`\uD83D\uDD12 Skipping ${W.name} \u2192 ${W.newVersion}: ${O.field} pins it to ${O.version}, which would win at install time`),!1})}applyPins($){let X=this.config.packages?.pin;if(!X||Object.keys(X).length===0)return $;let Q=[];for(let K of $){let H=X[K.name];if(!H){Q.push(K);continue}if(K.currentVersion===H){this.logger.info(`\uD83D\uDCCC ${K.name} is pinned to ${H}, skipping update to ${K.newVersion}`);continue}this.logger.info(`\uD83D\uDCCC ${K.name} is pinned to ${H}, retargeting update from ${K.newVersion}`),Q.push({...K,newVersion:H,updateType:l(K.currentVersion,H)})}return Q}async annotateSecurityAdvisories($){if(this.config.security?.enabled===!1||$.length===0)return $;try{let Q=await new t(this.logger).annotateUpdates($,this.config.security?.minimumSeverity??"low"),K=Q.filter((H)=>H.securityAdvisories?.length);if(K.length>0)await this.events.emit("security.advisories",{packages:K.map((H)=>({name:H.name,severity:H.securityAdvisories?.[0]?.severity??"unknown"}))});return Q}catch(X){return this.logger.warn("Security advisory lookup failed, continuing without it:",X),$}}async createPullRequests($){let X=Date.now();this.logger.info("Creating pull requests for updates...");try{if(!this.config.repository){this.logger.error("\u274C Repository configuration required for PR creation"),this.logger.info("Configure repository.provider, repository.owner, repository.name in buddy.config.ts");return}if(!this.config.repository.owner||!this.config.repository.name){this.logger.error("\u274C Repository owner and name are required for PR creation"),this.logger.info("Set them in buddy.config.ts or ensure GITHUB_REPOSITORY env var is available");return}let Q=d.env.GITHUB_TOKEN,K=d.env.BUDDY_TOKEN;if(!Q&&!K){this.logger.error("\u274C GITHUB_TOKEN or BUDDY_TOKEN environment variable required for PR creation");return}let H=Q||K,Y=!!K;if(K)this.logger.info("\u2705 BUDDY_TOKEN detected - workflow file permissions enabled");else this.logger.info("\u2139\uFE0F No BUDDY_TOKEN \u2014 workflow file updates will be skipped");let W=await e({provider:this.config.repository.provider,owner:this.config.repository.owner,name:this.config.repository.name,token:H,...K?{workflowToken:K}:{},...this.config.repository.apiUrl?{apiUrl:this.config.repository.apiUrl}:{}},{logger:this.logger}),O=new h0(this.config),j=this.config.maxPRsPerRun??10,J=0,_=this.orderGroupsByPriority($.groups);for(let z of _)try{let L=Date.now();if(this.logger.info(`Creating PR for group: ${z.name} (${z.updates.length} updates)`),z.updates.length>0&&z.updates.every((G)=>G.file.includes(".github/workflows/"))&&!Y){this.logger.warn(`\u26A0\uFE0F Skipping group ${z.name} \u2014 workflow-file updates require BUDDY_TOKEN with the workflow scope`);continue}try{let{spawn:G}=await import("child_process"),w=(M,R)=>{return new Promise((x,v)=>{let P=G(M,R,{stdio:"pipe"});P.on("close",(i)=>i===0?x():v(Error(`Git command failed with code ${i}`))),P.on("error",v)})},D=this.config.repository.baseBranch||"main";await w("git",["checkout",D]),await w("git",["reset","--hard","HEAD"]),await w("git",["clean","-fd"])}catch(G){this.logger.warn("\u26A0\uFE0F Failed to reset to clean state for early file-change check, continuing anyway:",G)}let B=await this.generateAllFileUpdates(z.updates);if(B.length===0){this.logger.info(`\u2139\uFE0F No file changes for group ${z.name}, skipping \u2014 leaving branches untouched`);continue}let E=this.prTitleFor(z),U=Date.now(),A=await O.generateBody(z),T=Date.now()-U;this.logger.info(`\u23F1\uFE0F PR body generation took ${T}ms`);let q=await this.analyzeMajors(z.updates,B.map((G)=>G.path)),N=y0(A,q.report),b=await W.getPullRequests("open"),c=this.generateBranchName(z),h=`buddy/update-${z.name.toLowerCase().replace(/\s+/g,"-")}-`,I=b.find((G)=>(G.head===c||G.title===E||G.head.startsWith(h)||this.isSimilarPRTitle(G.title,E))&&(G.author==="github-actions[bot]"||G.author.includes("buddy")||G.head.startsWith("buddy/"))&&!G.head.includes("renovate/")&&!G.head.includes("dependabot/")&&!G.author.toLowerCase().includes("renovate")&&!G.author.toLowerCase().includes("dependabot"));if(I){if(this.logger.info(`\uD83D\uDD04 Found existing PR #${I.number}: ${I.title}`),this.shouldAutoClosePR(I,z.updates)){this.logger.info(`\uD83D\uDD12 Auto-closing PR #${I.number} due to config change`);try{let D=this.generateCloseReason(I);try{await W.createComment(I.number,D)}catch(M){this.logger.warn(`\u26A0\uFE0F Could not add close reason comment to PR #${I.number}:`,M)}await W.closePullRequest(I.number),await this.events.emit("pr.closed",{number:I.number,title:I.title,reason:"no longer produced by the current configuration"});try{await W.deleteBranch(I.head),this.logger.success(`\u2705 Auto-closed PR #${I.number} and deleted branch ${I.head}`)}catch(M){this.logger.warn(`\u26A0\uFE0F Auto-closed PR #${I.number} but could not delete ${I.head}:`,M)}continue}catch(D){this.logger.error(`\u274C Failed to auto-close PR #${I.number}:`,D)}}if(this.checkIfUpdatesMatch(I.body,z.updates)){this.logger.info("\u2705 Existing PR has the same updates, skipping creation");continue}else{this.logger.info("\uD83D\uDD04 Updates differ, will update existing PR with new content");let D=I.head;try{let{spawn:x}=await import("child_process"),v=(P,i)=>{return new Promise((o0,J0)=>{let L0=x(P,i,{stdio:"pipe"});L0.on("close",(q0)=>{if(q0===0)o0();else J0(Error(`Git command failed with code ${q0}`))}),L0.on("error",J0)})};await v("git",["checkout","main"]),await v("git",["reset","--hard","HEAD"]),await v("git",["clean","-fd"]),this.logger.info(`\uD83E\uDDF9 Reset to clean main state before updating existing PR ${I.number}`)}catch(x){this.logger.warn("\u26A0\uFE0F Failed to reset to clean state, continuing anyway:",x)}let M=await this.generateAllFileUpdates(z.updates);if(M.length===0)this.logger.warn(`\u2139\uFE0F No file changes generated for existing PR ${I.number}, updating metadata only`);else{this.logger.info(`\uD83D\uDCDD Regenerated ${M.length} file changes for existing PR ${I.number}`);try{let{hasBranchDifferences:x}=await import("./chunk-aa277p5r.js");if(!await x(M,D))this.logger.info(`\u2139\uFE0F No content differences for ${D}; recreating from ${this.config.repository.baseBranch||"main"} with same dependency changes to keep branch up-to-date`),await W.commitChanges(D,this.commitMessageFor(z,"(rebased)"),M,this.config.repository.baseBranch||"main"),this.logger.success(`\u2705 Recreated ${D} from ${this.config.repository.baseBranch||"main"} (dependency versions unchanged)`);else await W.commitChanges(D,this.commitMessageFor(z,"(updated)"),M,this.config.repository.baseBranch||"main"),this.logger.success(`\u2705 Recreated branch ${D} with latest dependency versions`)}catch(x){this.logger.warn("\u26A0\uFE0F Failed to compare branch content, proceeding with commit:",x),await W.commitChanges(D,this.commitMessageFor(z,"(updated)"),M,this.config.repository.baseBranch||"main"),this.logger.success(`\u2705 Recreated branch ${D} with latest dependency versions`)}}let R=this.labelsFor(z,O);await W.updatePullRequest(I.number,{title:E,body:N,labels:R,reviewers:this.config.pullRequest?.reviewers,teamReviewers:this.config.pullRequest?.teamReviewers,assignees:this.config.pullRequest?.assignees}),await this.events.emit("pr.updated",{number:I.number,title:E,url:I.url}),this.logger.success(`\u2705 Updated existing PR #${I.number}: ${E}`),this.logger.info(`\uD83D\uDD17 ${I.url}`);continue}}if(J>=j){this.logger.warn(`\u26A0\uFE0F Rate limit reached: already created ${J} PRs this run (max: ${j}). Skipping remaining groups.`);break}let F=this.generateBranchName(z);if(await W.branchExists(F)){this.logger.info(`\uD83D\uDD04 Branch ${F} already exists, checking for associated PR...`);let G=b.find((D)=>D.head===F);if(G){this.logger.info(`\u2705 Found existing PR #${G.number} for branch ${F}, updating it...`);let D=await this.generateAllFileUpdates(z.updates);if(D.length>0)await W.commitChanges(F,this.commitMessageFor(z,"(updated)"),D,this.config.repository.baseBranch||"main");let M=this.labelsFor(z,O);await W.updatePullRequest(G.number,{title:E,body:N,labels:M,reviewers:this.config.pullRequest?.reviewers,teamReviewers:this.config.pullRequest?.teamReviewers,assignees:this.config.pullRequest?.assignees}),await this.events.emit("pr.updated",{number:G.number,title:E,url:G.url}),this.logger.success(`\u2705 Updated existing PR #${G.number}: ${E}`),this.logger.info(`\uD83D\uDD17 ${G.url}`);continue}let w=!1;try{let M=(p(W,"reopenPullRequests","reopenPullRequest")?await W.getPullRequests("closed"):[]).find((R)=>{if(R.head!==F)return!1;if(R.mergedAt)return!1;return Date.now()-(R.updatedAt?.getTime()??0)<86400000});if(M){this.logger.info(`\uD83D\uDD04 Found recently-closed PR #${M.number} for branch ${F}, reopening...`);let R=await this.generateAllFileUpdates(z.updates);if(R.length>0)await W.commitChanges(F,this.commitMessageFor(z,"(reopened)"),R,this.config.repository.baseBranch||"main");await W.reopenPullRequest(M.number);let x=this.labelsFor(z,O);await W.updatePullRequest(M.number,{title:E,body:N,labels:x,reviewers:this.config.pullRequest?.reviewers,teamReviewers:this.config.pullRequest?.teamReviewers,assignees:this.config.pullRequest?.assignees}),await this.events.emit("pr.updated",{number:M.number,title:E,url:M.url}),this.logger.success(`\u2705 Reopened and updated PR #${M.number}: ${E}`),this.logger.info(`\uD83D\uDD17 ${M.url}`),w=!0}}catch(D){this.logger.warn("\u26A0\uFE0F Failed to check/reopen closed PRs:",D)}if(w)continue;this.logger.info(`\uD83E\uDDF9 Branch ${F} exists but has no open PR, cleaning up...`);try{await W.deleteBranch(F)}catch(D){this.logger.warn(`\u26A0\uFE0F Failed to delete orphaned branch ${F}:`,D)}}let u=!1;try{let w=(p(W,"reopenPullRequests","reopenPullRequest")?await W.getPullRequests("closed"):[]).find((D)=>{if(D.head!==F&&!this.isSimilarPRTitle(D.title,E))return!1;if(!D.head.startsWith("buddy/")&&D.author!=="github-actions[bot]")return!1;if(D.mergedAt)return!1;return Date.now()-(D.updatedAt?.getTime()??0)<604800000});if(w){this.logger.info(`\uD83D\uDD04 Found recently-closed PR #${w.number} (branch may have been deleted), recreating branch and reopening...`),await W.createBranch(F,this.config.repository.baseBranch||"main");let D=await this.generateAllFileUpdates(z.updates);if(D.length>0)await W.commitChanges(F,this.commitMessageFor(z,"(reopened)"),D,this.config.repository.baseBranch||"main");await W.reopenPullRequest(w.number);let M=this.labelsFor(z,O);await W.updatePullRequest(w.number,{title:E,body:N,labels:M,reviewers:this.config.pullRequest?.reviewers,teamReviewers:this.config.pullRequest?.teamReviewers,assignees:this.config.pullRequest?.assignees}),await this.events.emit("pr.updated",{number:w.number,title:E,url:w.url}),this.logger.success(`\u2705 Reopened and updated PR #${w.number}: ${E}`),this.logger.info(`\uD83D\uDD17 ${w.url}`),u=!0}}catch(G){this.logger.warn("\u26A0\uFE0F Failed to check/reopen closed PRs:",G)}if(u)continue;await W.createBranch(F,this.config.repository.baseBranch||"main");try{let{spawn:G}=await import("child_process"),w=(D,M)=>{return new Promise((R,x)=>{let v=G(D,M,{stdio:"pipe"});v.on("close",(P)=>{if(P===0)R();else x(Error(`Git command failed with code ${P}`))}),v.on("error",x)})};await w("git",["checkout","main"]),await w("git",["reset","--hard","HEAD"]),await w("git",["clean","-fd"]),this.logger.info(`\uD83E\uDDF9 Reset to clean main state before generating updates for ${z.name}`)}catch(G){this.logger.warn("\u26A0\uFE0F Failed to reset to clean state, continuing anyway:",G)}let y=await this.generateAllFileUpdates(z.updates);if(y.length===0){this.logger.warn(`\u2139\uFE0F No file changes generated for group ${z.name}, skipping PR creation`);continue}let C=!1;for(let G of y)try{let w=await import("fs");if(w.existsSync(G.path)){if(w.readFileSync(G.path,"utf-8")!==G.content){C=!0;break}}else{C=!0;break}}catch{C=!0;break}if(!C){this.logger.warn(`\u2139\uFE0F No actual content changes for group ${z.name}, skipping PR creation`);continue}this.logger.info(`\uD83D\uDCDD Generated ${y.length} file changes for ${z.name}`),await W.commitChanges(F,this.commitMessageFor(z),y,this.config.repository.baseBranch||"main");let m=this.groupEffectsFor(z.updates),j0=this.labelsFor(z,O),k=await W.createPullRequest({title:E,body:N,head:F,base:this.config.repository.baseBranch||"main",draft:q.draft,reviewers:$0.mergeUnique(this.config.pullRequest?.reviewers,m.reviewers),teamReviewers:this.config.pullRequest?.teamReviewers,assignees:$0.mergeUnique(this.config.pullRequest?.assignees,m.assignees),labels:j0});J++,this.logger.success(`\u2705 Created PR #${k.number}: ${k.title} (${J}/${j} this run)`),this.logger.info(`\uD83D\uDD17 ${k.url}`),await this.events.emit("pr.created",{number:k.number,title:k.title,url:k.url,packages:z.updates.map((G)=>G.name)}),await this.queueAutoMerge(W,k,z.updates,j0);let u0=Date.now()-L;this.logger.info(`\u23F1\uFE0F Total group processing took ${u0}ms`)}catch(L){this.logger.error(`\u274C Failed to create PR for group ${z.name}:`,L)}let Z=Date.now()-X;this.logger.success(`\u2705 Completed PR creation for ${$.groups.length} group(s) in ${Z}ms`)}catch(Q){throw this.logger.error("Failed to create pull requests:",Q),Q}}shouldRespectVersion($){if(!(this.config.packages?.respectLatest??!0))return!1;let Q=["latest","*","main","master","develop","dev"],K=$.toLowerCase().trim();return Q.includes(K)}async checkDependencyFilesForUpdates($){let{isDependencyFile:X}=await import("./chunk-19zyq15p.js"),{resolveDependencyFile:Q}=await import("./chunk-05me15qw.js"),K=[],H=$.filter((O)=>X(O.path));this.logger.info(`\u26A1 Checking ${H.length} dependency files in parallel...`);let Y=H.map(async(O)=>{try{this.logger.info(`Checking dependency file: ${O.path}`);let j=await Q(O.path),J=[];for(let _ of j.allDependencies||[]){if(this.shouldRespectVersion(_.constraint)){this.logger.debug(`Skipping ${_.name} - version "${_.constraint}" should be respected`);continue}if(_.constraint!==_.version&&_.version){let Z=_.constraint.replace(/^[\^~>=<]+/,"");if(!this.isNewerVersion(Z,_.version)){this.logger.debug(`Skipping ${_.name} - latest (${_.version}) is not newer than constraint (${Z})`);continue}let z=l(Z,_.version),L=_.version;J.push({name:_.name,currentVersion:_.constraint,newVersion:L,updateType:z,dependencyType:"dependencies",file:O.path,metadata:void 0,releaseNotesUrl:void 0,changelogUrl:void 0,homepage:void 0})}}return J}catch(j){return this.logger.error(`Failed to check dependency file ${O.path}:`,j),[]}}),W=await Promise.all(Y);return K.push(...W.flat()),K}async checkZigForUpdates($){let{isZigManifest:X}=await import("./chunk-zxgkp71x.js"),{fetchLatestZigVersion:Q,fetchZigHash:K,isZigAvailable:H,parseZigSource:Y,zigUrlForVersion:W}=await import("./chunk-1qgr52wx.js"),O=$.filter((Z)=>X(Z.path));if(O.length===0)return[];if(!await H())return this.logger.warn("\u26A0\uFE0F Found Zig manifests but the zig toolchain is not available. "+"Skipping Zig updates: their content-addressed hashes cannot be recomputed without `zig fetch`."),[];let j=d.env.GITHUB_TOKEN||d.env.BUDDY_TOKEN,J=O.flatMap((Z)=>Z.dependencies.filter((z)=>z.type==="zig-dependencies").map((z)=>({file:Z,dep:z})));return this.logger.info(`\u26A1 Checking ${J.length} Zig dependencies...`),(await Promise.all(J.map(async({file:Z,dep:z})=>{let L=z.metadata?.url;if(!L)return this.logger.debug(`Skipping ${z.name}: no URL recorded`),null;let S=Y(L);if(!S)return this.logger.debug(`Skipping ${z.name}: only GitHub-hosted Zig dependencies can be checked`),null;let B=await Q(S,j);if(!B||B===z.currentVersion)return null;let E=W(L,B),U=await K(E);if(!U)return this.logger.warn(`\u26A0\uFE0F Skipping ${z.name} ${z.currentVersion} \u2192 ${B}: could not compute its package hash`),null;return this.logger.info(`\uD83D\uDCE6 ${z.name}: ${z.currentVersion} \u2192 ${B}`),{name:z.name,currentVersion:z.currentVersion,newVersion:B,updateType:l(z.currentVersion,B),dependencyType:"zig-dependencies",file:Z.path,resolved:{url:E,hash:U}}}))).filter((Z)=>Z!==null)}async checkGitHubActionsForUpdates($){let{isGitHubActionsFile:X}=await import("./chunk-sc7emb71.js"),{fetchLatestActionVersion:Q}=await import("./chunk-sc7emb71.js"),K=[],H=$.filter((_)=>X(_.path));this.logger.info(`\uD83D\uDD0D Found ${H.length} GitHub Actions workflow files`);let Y=[];for(let _ of H){let Z=_.dependencies.filter((z)=>z.type==="github-actions");this.logger.info(`Found ${Z.length} GitHub Actions in ${_.path}`),Z.forEach((z)=>Y.push({file:_,dep:z}))}this.logger.info(`\u26A1 Checking ${Y.length} GitHub Actions in parallel...`);let W=Y.map(async({file:_,dep:Z})=>{try{this.logger.info(`Checking action: ${Z.name}@${Z.currentVersion}`);let z=await Q(Z.name);if(z)if(this.logger.info(`Latest version for ${Z.name}: ${z}`),z!==Z.currentVersion){let L=l(Z.currentVersion,z);return this.logger.info(`Update available: ${Z.name} ${Z.currentVersion} \u2192 ${z} (${L})`),{name:Z.name,currentVersion:Z.currentVersion,newVersion:z,updateType:L,dependencyType:"github-actions",file:_.path,metadata:void 0,releaseNotesUrl:`${Y0(this.config)}/${Z.name}/releases`,changelogUrl:void 0,homepage:`${Y0(this.config)}/${Z.name}`}}else this.logger.info(`No update needed for ${Z.name}: already at ${z}`);else this.logger.warn(`Could not fetch latest version for ${Z.name}`);return null}catch(z){return this.logger.warn(`Failed to check version for action ${Z.name}:`,z),null}}),j=(await Promise.all(W)).filter((_)=>_!==null);K.push(...j),this.logger.info(`Generated ${K.length} GitHub Actions updates`);let J=K.reduce((_,Z)=>{if(!_.find((L)=>L.name===Z.name&&L.currentVersion===Z.currentVersion&&L.newVersion===Z.newVersion&&L.file===Z.file))_.push(Z);return _},[]);return this.logger.info(`After deduplication: ${J.length} unique GitHub Actions updates`),J}async checkEnginesForUpdates($){let{bumpEngineConstraint:X,engineUpdateType:Q,resolveEngineVersion:K}=await import("./chunk-pskqrv5r.js"),{fetchLatestActionVersion:H}=await import("./chunk-sc7emb71.js"),Y=$.flatMap((j)=>j.dependencies.filter((J)=>J.type==="engines").map((J)=>({file:j,dep:J})));if(Y.length===0)return[];this.logger.info(`\u26A1 Checking ${Y.length} engine constraint(s)...`);let W={npm:(j)=>this.registryClient.getLatestVersion(j),github:(j)=>H(j)},O=Y.map(async({file:j,dep:J})=>{try{let _=await K(J.name,W);if(!_)return null;let Z=X(J.currentVersion,_);if(!Z)return this.logger.debug(`${J.name} ${J.currentVersion} already admits ${_}`),null;return this.logger.info(`Update available: ${J.name} ${J.currentVersion} \u2192 ${Z}`),{name:J.name,currentVersion:J.currentVersion,newVersion:Z,updateType:Q(J.currentVersion,Z),dependencyType:"engines",file:j.path}}catch(_){return this.logger.warn(`Could not check engine ${J.name}:`,_),null}});return(await Promise.all(O)).filter((j)=>j!==null)}async checkDockerfilesForUpdates($){let{isDockerfile:X}=await import("./chunk-ys1qqcpp.js"),{fetchLatestDockerImageVersion:Q}=await import("./chunk-ys1qqcpp.js"),K=[],H=$.filter((_)=>X(_.path));this.logger.info(`\uD83D\uDD0D Found ${H.length} Dockerfile(s)`);let Y=[];for(let _ of H){let Z=_.dependencies.filter((z)=>z.type==="docker-image");this.logger.info(`Found ${Z.length} Docker images in ${_.path}`),Z.forEach((z)=>Y.push({file:_,dep:z}))}this.logger.info(`\u26A1 Checking ${Y.length} Docker images in parallel...`);let W=Y.map(async({file:_,dep:Z})=>{try{if(this.logger.info(`Checking Docker image: ${Z.name}:${Z.currentVersion}`),this.shouldRespectVersion(Z.currentVersion))return this.logger.debug(`Skipping ${Z.name} - version "${Z.currentVersion}" should be respected`),null;let z=await Q(Z.name,Z.currentVersion,{...this.config.registries?.docker?{registries:this.config.registries.docker}:{},...this.config.packages?.includePrerelease!==void 0?{includePrerelease:this.config.packages.includePrerelease}:{}});if(z)if(this.logger.info(`Latest version for ${Z.name}: ${z}`),z!==Z.currentVersion){let L=l(Z.currentVersion,z);return this.logger.info(`Update available: ${Z.name} ${Z.currentVersion} \u2192 ${z} (${L})`),{name:Z.name,currentVersion:Z.currentVersion,newVersion:z,updateType:L,dependencyType:"docker-image",file:_.path,metadata:void 0,releaseNotesUrl:`https://hub.docker.com/r/${Z.name}/tags`,changelogUrl:void 0,homepage:`https://hub.docker.com/r/${Z.name}`}}else this.logger.info(`No update needed for ${Z.name}: already at ${z}`);else this.logger.warn(`Could not fetch latest version for Docker image ${Z.name}`);return null}catch(z){return this.logger.warn(`Failed to check version for Docker image ${Z.name}:`,z),null}}),j=(await Promise.all(W)).filter((_)=>_!==null);K.push(...j),this.logger.info(`Generated ${K.length} Docker image updates`);let J=K.reduce((_,Z)=>{if(!_.find((L)=>L.name===Z.name&&L.currentVersion===Z.currentVersion&&L.newVersion===Z.newVersion&&L.file===Z.file))_.push(Z);return _},[]);return this.logger.info(`After deduplication: ${J.length} unique Docker image updates`),J}isNewerVersion($,X){try{return Bun.semver.order(X.replace(/^[v^~>=<@]+/,""),$.replace(/^[v^~>=<@]+/,""))>0}catch{return!1}}readDeclaredNpmVersions(){let $=new Map;try{let X=V("fs"),K=V("path").join(this.projectPath,"package.json");if(!X.existsSync(K))return $;let H=JSON.parse(X.readFileSync(K,"utf8"));for(let Y of["dependencies","devDependencies","peerDependencies","optionalDependencies"])for(let[W,O]of Object.entries(H[Y]??{}))if(typeof O==="string"&&!$.has(W))$.set(W,O)}catch(X){this.logger.debug("Could not read declared versions from package.json:",X)}return $}compareVersionsSafe($,X){try{let Q=X.replace(/^[v^~>=<@]+/,""),K=$.replace(/^[v^~>=<@]+/,"");if(!/^\d+\.\d+/.test(Q)||!/^\d+\.\d+/.test(K))return"failed";return Bun.semver.order(Q,K)>0?"behind":"at-or-beyond"}catch{return"failed"}}async generateAllFileUpdates($){let X=[],Q=$.filter((Z)=>Z.file.endsWith("package.json")&&Z.dependencyType!=="engines"&&!Z.file.includes(".yaml")&&!Z.file.includes(".yml")&&!Z.file.includes(".github/workflows/")),K=$.filter((Z)=>Z.dependencyType==="engines");if(K.length>0){let{applyEngineUpdates:Z}=await import("./chunk-pskqrv5r.js"),z=new Map;for(let L of K)z.set(L.file,[...z.get(L.file)??[],L]);for(let[L,S]of z)try{let B=F0.readFileSync(L,"utf-8"),E=Z(B,S);if(E===B){this.logger.warn(`\u26A0\uFE0F No engine changes written to ${L}`);continue}X.push({path:L,content:E,type:"update"})}catch(B){this.logger.warn(`Failed to update engines in ${L}:`,B)}}let H=new Map;for(let Z of Q){if(!H.has(Z.file))H.set(Z.file,[]);H.get(Z.file).push(Z)}for(let[Z,z]of H)try{let L=F0.readFileSync(Z,"utf-8"),S=JSON.parse(L);for(let B of z){let E=!1,U=B.name.replace(/\s*\(dev\)$/,"").replace(/\s*\(peer\)$/,"").replace(/\s*\(optional\)$/,""),A=["dependencies","devDependencies","peerDependencies","optionalDependencies"];for(let T of A)if(S[T]&&S[T][U]){let N=S[T][U].match(/^(\D*)/),b=N?N[1]:"",c=U.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),h=T.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),I=new RegExp(`("${h}"\\s*:\\s*\\{[^}]*?)("${c}"\\s*:\\s*")([^"]+)(")([^}]*?\\})`,"gs"),F=`${b}${B.newVersion}`;L=L.replace(I,`$1$2${F}$4$5`),E=!0;break}if(!E)this.logger.warn(`Package ${U} not found in ${Z}`)}X.push({path:Z,content:L,type:"update"})}catch(L){this.logger.warn(`Failed to update ${Z}:`,L)}let Y=$.filter((Z)=>{let z=Z.file.toLowerCase();return(z.endsWith("deps.yaml")||z.endsWith("deps.yml")||z.endsWith("dependencies.yaml")||z.endsWith("dependencies.yml"))&&!Z.file.includes(".github/workflows/")});if(Y.length>0)try{let{generateDependencyFileUpdates:Z}=await import("./chunk-19zyq15p.js"),z=await Z(Y);X.push(...z)}catch(Z){this.logger.error("Failed to generate dependency file updates:",Z)}let W=$.filter((Z)=>Z.file.endsWith("composer.json")||Z.file.endsWith("composer.lock"));if(W.length>0)try{let{generateComposerUpdates:Z}=await import("./chunk-vqa6vte3.js"),z=await Z(W);X.push(...z)}catch(Z){this.logger.error("Failed to generate Composer updates:",Z)}let O=$.filter((Z)=>Z.file.includes(".github/workflows/"));if(O.length>0)try{let{generateGitHubActionsUpdates:Z}=await import("./chunk-sc7emb71.js"),z=await Z(O);X.push(...z)}catch(Z){this.logger.error("Failed to generate GitHub Actions updates:",Z)}let j=$.filter((Z)=>Z.dependencyType==="docker-image");if(j.length>0)try{let{generateDockerfileUpdates:Z}=await import("./chunk-ys1qqcpp.js"),z=await Z(j,this.config.registries?.docker);X.push(...z)}catch(Z){this.logger.error("Failed to generate Dockerfile updates:",Z)}let J=$.filter((Z)=>Z.dependencyType==="zig-dependencies");if(J.length>0)try{let{generateZigManifestUpdates:Z}=await import("./chunk-zxgkp71x.js"),z=await Z(J);X.push(...z)}catch(Z){this.logger.error("Failed to generate Zig manifest updates:",Z)}let _=$.filter((Z)=>Z.dependencyType==="catalog");if(_.length>0)try{let{applyCatalogUpdates:Z}=await import("./chunk-0paakbpj.js"),z=_[0].file,L=await Bun.file(a(this.projectPath,z)).text(),S=Z(L,_);if(S===L)this.logger.warn(`\u26A0\uFE0F No catalog changes written to ${z}`);else X.push({path:z,content:S,type:"update"})}catch(Z){this.logger.error("Failed to generate pnpm catalog updates:",Z)}return X.push(...await this.generateAdapterFileUpdates($)),X}async generateAdapterFileUpdates($){let{adapterNamed:X}=await import("./chunk-wn6pbyzn.js"),Q=new Map;for(let Y of $){if(!X(Y.dependencyType))continue;let W=Q.get(Y.file);if(W)W.push(Y);else Q.set(Y.file,[Y])}let K=[],H=new Set;for(let[Y,W]of Q){let O=X(W[0].dependencyType);if(!O)continue;H.add(O.name);try{let j=a(this.projectPath,Y),J=await Bun.file(j).text(),_=J;for(let Z of W)_=O.applyUpdate(_,{name:Z.name,currentVersion:Z.currentVersion,newVersion:Z.newVersion,section:Z.dependencyType});if(_===J){this.logger.warn(`\u26A0\uFE0F ${O.name}: no changes written to ${Y}`);continue}K.push({path:Y,content:_,type:"update"})}catch(j){this.logger.error(`Failed to write ${O.name} updates to ${Y}:`,j)}}return[...K,...await this.regenerateAdapterLockfiles(K,[...H])]}async regenerateAdapterLockfiles($,X){if($.length===0||X.length===0)return[];let{regenerateLockfiles:Q}=await import("./chunk-wn6pbyzn.js");try{for(let W of $)await Bun.write(a(this.projectPath,W.path),W.content)}catch(W){return this.logger.warn(`\u26A0\uFE0F Could not stage manifests for lockfile regeneration: ${W}`),[]}let{regenerated:K,notes:H}=await Q(this.projectPath,X);for(let W of H)this.logger.info(`\u2139\uFE0F ${W}`);let Y=[];for(let W of K)try{Y.push({path:W,content:await Bun.file(a(this.projectPath,W)).text(),type:"update"}),this.logger.info(`\uD83D\uDD12 Regenerated ${W}`)}catch(O){this.logger.warn(`\u26A0\uFE0F Could not read the regenerated ${W}: ${O}`)}return Y}async run(){let $=await this.scanForUpdates();if($.updates.length===0)return this.logger.info("No updates available!"),$;if(this.config.pullRequest)await this.createPullRequests($);return $}async checkPackages($){return this.logger.info(`Checking specific packages: ${$.join(", ")}`),this.applyStrategy(await this.registryClient.getUpdatesForPackages($))}async checkPackagesWithPattern($){return this.logger.info(`Checking packages with pattern: ${$}`),this.applyStrategy(await this.registryClient.getUpdatesWithPattern($))}applyStrategy($){let X=this.config.packages?.strategy;return X?this.filterUpdatesByStrategy($,X):$}filterUpdatesByStrategy($,X){if(X==="all")return $;return $.filter((Q)=>P0(X,Q.updateType))}async filterUpdatesByMinimumReleaseAge($){let X=this.config.packages?.minimumReleaseAge??0,Q=this.activeRules(),K=Q.some((j)=>j.minimumReleaseAge!==void 0);if(X===0&&!K)return $;this.logger.info(`Applying minimum release age filter (global ${X} minutes${K?", with per-rule overrides":""}) in parallel...`);let H=$.map(async(j)=>{try{let J=(Q.length>0?g(j,Q).minimumReleaseAge:void 0)??X;if(J===0)return j;if(await this.registryClient.meetsMinimumReleaseAge(j.name,j.newVersion,j.dependencyType,J))return j;else return this.logger.debug(`Filtered out ${j.name}@${j.newVersion} (${j.dependencyType}) \u2014 held for ${J} minutes after publication`),null}catch(J){return this.logger.warn(`Error checking release age for ${j.name}@${j.newVersion} (${j.dependencyType}), including update:`,J),j}}),W=(await Promise.all(H)).filter((j)=>j!==null),O=$.length-W.length;if(O>0)this.logger.info(`Filtered out ${O} updates due to minimum release age requirement`);return W}groupUpdatesByConfig($){let X=[],{grouped:Q,remaining:K}=this.groupByRuleNames($);X.push(...Q);let H=[...K];if(this.config.packages?.groups)for(let Y of this.config.packages.groups){let W=[],{Glob:O}=globalThis.Bun,j=new Set;for(let _ of Y.patterns){let Z;try{Z=new O(_)}catch(z){this.logger.warn(`Invalid group pattern '${_}':`,z);continue}H.forEach((z,L)=>{if(!j.has(L)&&Z.match(z.name))W.push(z),j.add(L)})}if(j.size>0){for(let _=H.length-1;_>=0;_--)if(j.has(_))H.splice(_,1)}let J=W;if(Y.strategy)J=this.filterUpdatesByStrategy(W,Y.strategy);if(J.length>0)X.push({name:Y.name,updates:J,updateType:this.getHighestUpdateType(J),title:`chore(deps): update ${Y.name}`,body:`Update ${J.length} packages in ${Y.name} group`})}if(H.length>0){let Y=Z0(H);X.push(...Y)}return X}groupByRuleNames($){let X=this.config.packages?.rules??[];if(X.length===0)return{grouped:[],remaining:$};let Q=new Map,K=[];for(let Y of $){let W=g(Y,X).groupName;if(!W){K.push(Y);continue}let O=Q.get(W);if(O)O.push(Y);else Q.set(W,[Y])}return{grouped:[...Q.entries()].map(([Y,W])=>({name:Y,updates:W,updateType:this.getHighestUpdateType(W),title:`chore(deps): update ${Y}`,body:`Update ${W.length} packages in ${Y} group`})),remaining:K}}getHighestUpdateType($){if($.some((X)=>X.updateType==="major"))return"major";if($.some((X)=>X.updateType==="minor"))return"minor";return"patch"}generateBranchName($){return`buddy/update-${$.name.toLowerCase().replace(/\s+/g,"-").replace(/[^a-z0-9-]/g,"").replace(/-+/g,"-").replace(/^-|-$/g,"")}`}isSimilarPRTitle($,X){if($.toLowerCase()===X.toLowerCase())return!0;let Q=$.toLowerCase(),K=X.toLowerCase(),H=Q.includes("github actions"),Y=K.includes("github actions");if(H&&Y)return!0;if(H!==Y)return!1;let W=Q.includes("docker image"),O=K.includes("docker image");if(W&&O)return!0;if(W!==O)return!1;let j=[/update all non-major/i,/update \d+ dependenc(y|ies)/i,/update.*\(minor\)/i,/update.*\(patch\)/i,/update.*\(major\)/i],J=j.some((Z)=>Z.test($)),_=j.some((Z)=>Z.test(X));if(J&&_){let Z=Q.includes("(major)")||Q.includes("major update"),z=K.includes("(major)")||K.includes("major update");return Z===z}if(K.includes("update dependency ")){let Z=X.match(/update dependency (\S+)/i),z=$.match(/update dependency (\S+)/i);if(Z&&z)return Z[1]===z[1]}if(J!==_)return!1;if(Q.includes("dependency ")&&K.includes("dependency "))return!1;return!1}checkIfUpdatesMatch($,X){if(!$)return!1;let Q=this.extractPackageUpdatesFromPRBody($),K=new Map;for(let H of Q)K.set(H.name,{from:H.currentVersion,to:H.newVersion});for(let H of X){let Y=K.get(H.name);if(!Y)return!1;let W=Y.to.replace(/^[v^~>=<]+/,""),O=H.newVersion.replace(/^[v^~>=<]+/,"");if(W!==O)return!1}return K.size===X.length}shouldAutoClosePR($,X){if(this.shouldAutoCloseForRespectLatest($))return!0;if(this.shouldAutoCloseForIgnorePaths($))return!0;if(this.shouldAutoCloseForRemovedFiles($))return!0;return!1}shouldAutoCloseForRespectLatest($){if(!(this.config.packages?.respectLatest??!0))return!1;let Q=["latest","*","main","master","develop","dev"],K=this.extractPackageUpdatesFromPRBody($.body);if(K.length===0)return!1;return K.filter((Y)=>{let W=Y.currentVersion.toLowerCase().trim();return Q.includes(W)}).length>0}shouldAutoCloseForIgnorePaths($){let X=this.config.packages?.ignorePaths;if(!X||X.length===0)return!1;let Q=this.extractFilePathsFromPRBody($.body);if(Q.length===0)return!1;let{Glob:K}=globalThis.Bun,H=Q.filter((Y)=>{let W=Y.replace(/^\.\//,"");return X.some((O)=>{try{return new K(O).match(W)}catch(j){return this.logger.debug(`Failed to match path ${W} against pattern ${O}: ${j}`),!1}})});if(H.length>0)return this.logger.debug(`PR #${$.number} contains files now in ignorePaths: ${H.join(", ")}`),!0;return!1}shouldAutoCloseForRemovedFiles($){try{let X=this.extractFilePathsFromPRBody($.body);if(X.length===0)return!1;let Q=V("fs"),K=V("path"),H=X.filter((Y)=>{let W=K.join(this.projectPath,Y);return!Q.existsSync(W)});if(H.length>0){if(this.logger.info(`PR #${$.number} references removed files: ${H.join(", ")}`),this.config.packages?.ignorePaths&&this.config.packages.ignorePaths.length>0){let{Glob:_}=globalThis.Bun;if(H.filter((z)=>{return!this.config.packages.ignorePaths.some((L)=>{try{return new _(L).match(z)}catch(S){return this.logger.warn(`Invalid glob pattern '${L}':`,S),!1}})}).length>0)return this.logger.info(`Some removed files are outside ignored paths - not auto-closing PR #${$.number}`),!1}if(H.some((_)=>_.endsWith("composer.json")))return this.logger.info(`composer.json was removed - PR #${$.number} should be auto-closed`),!0;let W=$.body.toLowerCase(),O=W.includes("composer")||H.some((_)=>_.includes("composer")),j=W.includes("package.json")||H.some((_)=>_.includes("package.json")),J=H.some((_)=>_.endsWith("deps.yaml")||_.endsWith("deps.yml")||_.endsWith("dependencies.yaml")||_.endsWith("dependencies.yml"));if(O||j||J)return this.logger.info(`PR #${$.number} is about removed dependency system - should be auto-closed`),!0}return!1}catch(X){return this.logger.debug(`Failed to check for removed files in PR #${$.number}: ${X}`),!1}}get events(){if(!this.eventBus){this.eventBus=new m0(this.logger);for(let $ of f0(this.config.notifications))this.eventBus.register($)}return this.eventBus}async createGitProvider(){let $=this.config.repository;if(!$?.owner||!$.name)return this.logger.warn("\u26A0\uFE0F Repository owner and name are required for pull request operations"),null;try{return await e({provider:$.provider,owner:$.owner,name:$.name,...$.apiUrl?{apiUrl:$.apiUrl}:{}},{logger:this.logger})}catch(X){return this.logger.warn(`\u26A0\uFE0F ${N0(X)}`),null}}async queueAutoMerge($,X,Q,K){let H=I0(Q,K,this.config);if(!H.eligible){this.logger.debug(`\uD83D\uDD00 PR #${X.number} not auto-merged: ${H.reason}`);return}let{strategy:Y}=n(this.config);if(!p($,"nativeAutoMerge","enableAutoMerge")){this.logger.info(`\uD83D\uDD00 PR #${X.number} qualifies for auto-merge but this provider has no merge queue; update-check will merge it once checks pass`);return}try{if(await $.enableAutoMerge(X.number,Y))this.logger.success(`\uD83D\uDD00 PR #${X.number} queued for auto-merge (${H.reason})`);else this.logger.info(`\uD83D\uDD00 PR #${X.number} qualifies for auto-merge but the repository cannot queue it; update-check will merge it once checks pass`)}catch(W){this.logger.warn(`\u26A0\uFE0F Failed to queue auto-merge for PR #${X.number}: ${W}`)}}async mergeEligiblePullRequests($=!1){let X=n(this.config);if(!X.enabled)return[];let Q=await this.createGitProvider();if(!Q)return[];let K=[],H=await Q.getPullRequests("open");for(let Y of H.filter((W)=>W.head.startsWith("buddy/"))){let W=X.requireGreenCI&&Q.getPullRequestChecksState?await Q.getPullRequestChecksState(Y.number):"none",O=W==="success"||W==="none",j=V0({number:Y.number,title:Y.title,body:Y.body,head:Y.head,labels:Y.labels,draft:Y.draft},this.config,O);if(!j.eligible){this.logger.debug(`\uD83D\uDD00 PR #${Y.number} not merged: ${j.reason}`);continue}if($){this.logger.info(`\uD83D\uDD00 [DRY RUN] Would merge PR #${Y.number} (${j.reason})`),K.push(Y.number);continue}try{await Q.mergePullRequest(Y.number,X.strategy),this.logger.success(`\uD83D\uDD00 Merged PR #${Y.number}: ${j.reason}`),await this.events.emit("pr.merged",{number:Y.number,title:Y.title,strategy:X.strategy}),K.push(Y.number)}catch(J){this.logger.warn(`\u26A0\uFE0F Failed to merge PR #${Y.number}: ${J}`)}}return K}isPlausibleRepoPath($){if(!$||/[\s()[\]!`]|:\/\//.test($))return!1;return/^[\w@.-]+(?:\/[\w@.-]+)*$/.test($)}extractFilePathsFromPRBody($){let X=f($);if(X)return b0(X);let Q=[],K=/\|\s*\[[^\]]+\]\([^)]*\)\s*\|[^|]*\|\s*\*\*([^*]+)\*\*\s*\|/g,H;while((H=K.exec($))!==null){let j=H[1].trim();if(this.isPlausibleRepoPath(j)&&!Q.includes(j))Q.push(j)}let Y=/\*\*([^*]+\.(?:json|yaml|yml|lock))\*\*/g;while((H=Y.exec($))!==null){let j=H[1].trim();if(this.isPlausibleRepoPath(j)&&!Q.includes(j))Q.push(j)}let W=/\|[^|]+\|[^|]+\|([^|]+)\|[^|]*\|/g;while((H=W.exec($))!==null){let j=H[1].trim();if(this.isPlausibleRepoPath(j)&&(j.includes("/")||/\.(?:json|yaml|yml|lock)$/.test(j))&&!Q.includes(j))Q.push(j)}let O=/(?:^|\s)([\w-]+(?:\/[\w.-]+)*\/[\w.-]+\.(?:json|yaml|yml|lock))(?:\s|$)/gm;while((H=O.exec($))!==null){let j=H[1].trim();if(this.isPlausibleRepoPath(j)&&!Q.includes(j))Q.push(j)}return Q}extractPackagesFromPRBody($){let X=f($);if(X)return[...new Set(X.updates.map((Y)=>Y.name))];let Q=[],K=$.match(/\|[^|]*\|[^|]*\|[^|]*\|[^|]*\|/g);if(K)for(let Y of K){let W=Y.match(/\[([^\]]+)\]\([^)]*\)/);if(W)Q.push(W[1])}let H=$.match(/<summary>([^<]+)<\/summary>/g);if(H)for(let Y of H){let W=Y.replace(/<summary>/,"").replace(/<\/summary>/,"").trim();if(W&&!Q.includes(W))Q.push(W)}return Q}extractPackageUpdatesFromPRBody($){let X=f($);if(X)return R0(X);let Q=[],K=new Set,H=/\|\s*\[([^\]]+)\][^|]*\|\s*\[?`?[v^~>=]*([^`|\s]+)`?\s*(?:->|\u2192)\s*`?[v^~>=]*([^`|\s]+)`?\]?/g,Y;while((Y=H.exec($))!==null){let[,W,O,j]=Y;if(!K.has(W))K.add(W),Q.push({name:W,currentVersion:O,newVersion:j})}return Q}getConfig(){return this.config}getProjectPath(){return this.projectPath}async checkAndCloseObsoletePRs($,X=!1){try{this.logger.info("\uD83D\uDD0D Scanning for obsolete PRs due to removed dependency files...");let K=(await $.getPullRequests("open")).filter((Y)=>Y.head.startsWith("buddy/")||Y.author==="github-actions[bot]"&&Y.labels.includes("dependencies"));this.logger.info(`Found ${K.length} dependency-related PRs to check`);let H=0;for(let Y of K)try{if(this.shouldAutoCloseForRemovedFiles(Y))if(this.logger.info(`\uD83D\uDD12 PR #${Y.number} should be auto-closed: ${Y.title}`),X)this.logger.info(`\uD83D\uDD0D [DRY RUN] Would auto-close PR #${Y.number}`),H++;else try{let O=this.generateCloseReason(Y);try{await $.createComment(Y.number,O)}catch(j){this.logger.warn(`\u26A0\uFE0F Could not add close reason comment to PR #${Y.number}:`,j)}if(await $.closePullRequest(Y.number),await this.events.emit("pr.closed",{number:Y.number,title:Y.title,reason:"obsolete \u2014 its dependency files no longer exist"}),Y.head.startsWith("buddy/"))try{await $.deleteBranch(Y.head),this.logger.success(`\u2705 Auto-closed PR #${Y.number} and deleted branch ${Y.head}`)}catch(j){this.logger.warn(`\u26A0\uFE0F Auto-closed PR #${Y.number} but failed to delete branch: ${j}`)}else this.logger.success(`\u2705 Auto-closed PR #${Y.number}`);H++}catch(O){this.logger.error(`\u274C Failed to auto-close PR #${Y.number}:`,O)}}catch(W){this.logger.warn(`\u26A0\uFE0F Error checking PR #${Y.number}:`,W)}if(H>0)this.logger.success(`\u2705 ${X?"Would auto-close":"Auto-closed"} ${H} obsolete PR(s)`);else this.logger.info("\uD83D\uDCCB No obsolete PRs found")}catch(Q){throw this.logger.error("Failed to check for obsolete PRs:",Q),Q}}async checkAndCloseSatisfiedPRs($,X=!1){try{this.logger.info("\uD83D\uDD0D Checking for PRs where dependencies are already at target version...");let K=(await $.getPullRequests("open")).filter((_)=>_.head.startsWith("buddy/")||_.author==="github-actions[bot]"&&_.labels.includes("dependencies"));if(this.logger.info(`Found ${K.length} buddy dependency PRs to validate`),K.length===0){this.logger.info("\uD83D\uDCCB No buddy PRs to check");return}let H=0,Y={...this.config,packages:{...this.config.packages,strategy:"all"}},O=await new $0(Y,this.projectPath).scanForUpdates(),j=new Map;for(let _ of O.updates)j.set(_.name,_);let J=this.readDeclaredNpmVersions();if(O.updates.length===0){this.logger.warn("\u26A0\uFE0F Scan returned 0 updates \u2014 skipping satisfied PR check to avoid false-positive closures");return}for(let _ of K)try{let Z=this.extractPackageUpdatesFromPRBody(_.body);if(Z.length===0){this.logger.debug(`PR #${_.number}: Could not extract package updates, skipping`);continue}let z=_.body.match(/\*\*Total\*\*\s*\|\s*\*\*(\d+)\*\*/),L=z?Number.parseInt(z[1],10):0;if(L>0&&Z.length<L){this.logger.debug(`PR #${_.number}: Extracted ${Z.length}/${L} updates \u2014 incomplete extraction, skipping satisfied check`);continue}let S=0,B=0,E=0;for(let A of Z){let T=j.get(A.name);if(!T){let N=J.get(A.name);if(N){let b=this.compareVersionsSafe(N,A.newVersion);if(b==="at-or-beyond"){this.logger.debug(`PR #${_.number}: ${A.name} declared at ${N}, at or beyond ${A.newVersion}`),S++;continue}if(b==="behind"){this.logger.debug(`PR #${_.number}: ${A.name} declared at ${N}, still behind ${A.newVersion} \u2014 the scan missed it`),B++;continue}}this.logger.debug(`PR #${_.number}: ${A.name} not in current scan and not declared (unverifiable)`),E++;continue}if(T.newVersion===A.newVersion){this.logger.debug(`PR #${_.number}: ${A.name} still needs update to ${A.newVersion}`),B++;continue}let q=this.compareVersionsSafe(T.currentVersion,A.newVersion);if(q==="at-or-beyond")this.logger.debug(`PR #${_.number}: ${A.name} already at or beyond ${A.newVersion}`),S++;else if(q==="behind")this.logger.debug(`PR #${_.number}: ${A.name} still behind ${A.newVersion}`),B++;else this.logger.debug(`PR #${_.number}: ${A.name} version comparison inconclusive`),E++}let U=B===0&&E===0&&S>0;if(this.logger.debug(`PR #${_.number}: verified-satisfied=${S}, still-needed=${B}, unverifiable=${E} \u2192 ${U?"CLOSE":"KEEP"}`),U)if(this.logger.info(`\u2705 PR #${_.number} is satisfied (dependencies at target version): ${_.title}`),X)this.logger.info(`\uD83D\uDD0D [DRY RUN] Would close PR #${_.number}`),H++;else try{let A=Z.filter((q)=>{let b=j.get(q.name)?.currentVersion??J.get(q.name);if(!b)return!1;return this.compareVersionsSafe(b,q.newVersion)==="at-or-beyond"}),T=`\uD83E\uDD16 **Auto-closing satisfied PR**
|
|
88
|
-
|
|
89
|
-
`;if(A.length>0)T+=`The following packages are already at the target version or newer:
|
|
90
|
-
|
|
91
|
-
`,A.forEach((q)=>{T+=`- **${q.name}**: ${q.currentVersion} \u2192 ${q.newVersion}
|
|
92
|
-
`}),T+=`
|
|
93
|
-
`;T+="If this was closed in error, please reopen and add a comment explaining why.";try{await $.createComment(_.number,T)}catch(q){this.logger.warn(`\u26A0\uFE0F Could not add comment to PR #${_.number}:`,q)}if(await $.closePullRequest(_.number),await this.events.emit("pr.closed",{number:_.number,title:_.title,reason:"satisfied \u2014 every package already at or beyond target"}),_.head.startsWith("buddy/"))try{await $.deleteBranch(_.head),this.logger.success(`\u2705 Closed PR #${_.number} and deleted branch ${_.head}`)}catch(q){this.logger.warn(`\u26A0\uFE0F Closed PR #${_.number} but failed to delete branch: ${q}`)}else this.logger.success(`\u2705 Closed PR #${_.number}`);H++}catch(A){this.logger.error(`\u274C Failed to close PR #${_.number}:`,A)}}catch(Z){this.logger.warn(`\u26A0\uFE0F Error validating PR #${_.number}:`,Z)}if(H>0)this.logger.success(`\u2705 ${X?"Would close":"Closed"} ${H} satisfied PR(s)`);else this.logger.info("\uD83D\uDCCB No satisfied PRs found")}catch(Q){throw this.logger.error("Failed to check for satisfied PRs:",Q),Q}}generateCloseReason($){let Q=this.extractFilePathsFromPRBody($.body).filter((O)=>{let j=V("fs"),_=V("path").join(this.projectPath,O);return!j.existsSync(_)}),K=Q.some((O)=>O.includes("composer")),H=Q.some((O)=>O.includes("package.json")),Y=Q.some((O)=>O.endsWith("deps.yaml")||O.endsWith("deps.yml")||O.endsWith("dependencies.yaml")||O.endsWith("dependencies.yml")),W=`\uD83E\uDD16 **Auto-closing obsolete PR**
|
|
94
|
-
|
|
95
|
-
`;if(K)W+="This PR was automatically closed because `composer.json` has been removed from the project, indicating that Composer is no longer used for dependency management.\n\n";else if(H)W+="This PR was automatically closed because `package.json` has been removed from the project, indicating that npm/yarn/pnpm is no longer used for dependency management.\n\n";else if(Y)W+=`This PR was automatically closed because the dependency files it references have been removed from the project.
|
|
96
|
-
|
|
97
|
-
`;else W+=`This PR was automatically closed because the dependency files it references are no longer present in the project.
|
|
98
|
-
|
|
99
|
-
`;if(Q.length>0)W+=`**Removed files:**
|
|
100
|
-
${Q.map((O)=>`- \`${O}\``).join(`
|
|
101
|
-
`)}
|
|
102
|
-
|
|
103
|
-
`;return W+="If this was closed in error, please reopen the PR and update the dependency files accordingly.",W}async createOrUpdateDashboard(){try{if(this.logger.info("Creating or updating dependency dashboard..."),!this.config.repository)throw Error("Repository configuration is required for dashboard");if(this.config.repository.provider!=="github")throw Error("Dashboard is currently only supported for GitHub repositories");if(!this.config.repository.owner||!this.config.repository.name)throw Error("Repository owner and name are required for dashboard. Set them in buddy.config.ts or ensure GITHUB_REPOSITORY env var is available.");let $=await e({provider:this.config.repository.provider,owner:this.config.repository.owner,name:this.config.repository.name,...this.config.repository.token?{token:this.config.repository.token}:{},...this.config.repository.apiUrl?{apiUrl:this.config.repository.apiUrl}:{}},{logger:this.logger}),X=await this.collectDashboardData($),Q=this.config.dashboard||{},{title:K,body:H}=this.dashboardGenerator.generateDashboard(X,{showOpenPRs:Q.showOpenPRs??!0,showDetectedDependencies:Q.showDetectedDependencies??!0,showDeprecatedDependencies:Q.showDeprecatedDependencies??!0,includePackageJson:Q.includePackageJson??!0,includeDependencyFiles:Q.includeDependencyFiles??!0,includeGitHubActions:Q.includeGitHubActions??!0,bodyTemplate:Q.bodyTemplate}),Y={title:Q.title||K,body:H,labels:Q.labels||["dependencies","dashboard"],assignees:Q.assignees},W=await this.findExistingDashboard($,Q.issueNumber),O=null;if(W){if(this.logger.info(`Updating existing dashboard issue #${W.number}`),O=await this.updateDashboardIssue($,W.number,Y),O)this.logger.success(`\u2705 Successfully updated dashboard issue #${O.number}`)}if(!O){this.logger.info("Creating new dashboard issue"),this.logger.info("Performing final check for existing dashboards before creation...");let j=await this.findExistingDashboard($,Q.issueNumber);if(j&&j.number!==W?.number){if(this.logger.info(`Race condition detected! Found existing dashboard #${j.number} during final check`),O=await this.updateDashboardIssue($,j.number,Y),O)this.logger.success(`\u2705 Updated existing dashboard issue #${O.number} (race condition avoided)`)}if(!O)O=await $.createIssue(Y),this.logger.success(`\u2705 Successfully created new dashboard issue #${O.number}`)}if(Q.pin!==void 0)if(!Q.pin)await $.unpinIssue(O.number);else if(p($,"pinIssues","pinIssue"))await $.pinIssue(O.number);else this.logger.debug("\uD83D\uDCCC Provider does not support pinning issues; leaving the dashboard unpinned");return this.logger.success(`\u2705 Dashboard updated: ${O.url}`),await this.events.emit("dashboard.updated",{number:O.number,url:O.url}),O}catch($){throw this.logger.error("Failed to create or update dashboard:",$),$}}async collectDashboardData($){let[X,Q]=await Promise.all([this.scanner.scanProject(),$.getPullRequests("open")]),K=Q.filter((Z)=>Z.labels.includes("dependencies")||Z.labels.includes("dependency")||Z.labels.includes("deps")||Z.title.toLowerCase().includes("update")||Z.title.toLowerCase().includes("chore(deps)")||Z.title.toLowerCase().includes("bump")||Z.title.toLowerCase().includes("upgrade")||Z.title.toLowerCase().includes("renovate")||Z.head.includes("renovate/")||Z.head.includes("dependabot/")||Z.head.includes("buddy/")||Z.head.includes("update-")||Z.head.includes("bump-")),H=X.filter((Z)=>Z.type==="package.json"),Y=X.filter((Z)=>Z.path.includes(".github/workflows/")&&(Z.path.endsWith(".yml")||Z.path.endsWith(".yaml"))),W=X.filter((Z)=>!Z.path.includes(".github/workflows/")&&Z.type!=="package.json"),j=await new c0().checkDeprecatedDependencies(X),J=await this.findVulnerableDependencies(X),_=await this.findCappedDependencies(X);return{openPRs:K,detectedDependencies:{packageJson:H,dependencyFiles:W,githubActions:Y},deprecatedDependencies:j,vulnerableDependencies:J,cappedDependencies:_,repository:{owner:this.config.repository.owner,name:this.config.repository.name,provider:this.config.repository.provider},lastUpdated:new Date}}async findCappedDependencies($){if(this.config.packages?.detectResolutionDrift===!1)return[];try{let{collectDriftInputs:X}=await import("./chunk-yp1tgdh3.js"),{findDrift:Q}=await import("./chunk-3fzbvs2p.js"),K=await X($,this.registryClient,this.projectPath,this.logger),H=Q(K).filter((Y)=>Y.kind==="capped");if(H.length>0)this.logger.info(`\uD83D\uDD17 ${H.length} package(s) capped by a dependant's range`);return H}catch(X){return this.logger.warn("Resolution drift analysis failed, continuing without it:",X),[]}}async findVulnerableDependencies($){if(this.config.security?.enabled===!1)return[];let X=[],Q=new Map;for(let K of $)for(let H of K.dependencies){let Y=K0(H.type);if(!Y)continue;let W=H.currentVersion.replace(/^[\^~>=<\s]*v?/,"").trim();if(!W)continue;let O={name:H.name,version:W,ecosystem:Y},j=r(O);if(Q.has(j))continue;Q.set(j,{name:H.name,currentVersion:H.currentVersion,ecosystem:Y,file:K.path}),X.push(O)}if(X.length===0)return[];try{let H=await new t(this.logger).findAdvisories(X),Y=this.config.security?.minimumSeverity??"low",W={low:0,moderate:1,high:2,critical:3},O=[];for(let[j,J]of H){let _=Q.get(j);if(!_)continue;let Z=J.filter((z)=>W[z.severity]>=W[Y]);if(Z.length>0)O.push({..._,advisories:Z})}return O.sort((j,J)=>W[J.advisories[0].severity]-W[j.advisories[0].severity]),O}catch(K){return this.logger.warn("Vulnerability check failed, dashboard will omit it:",K),[]}}async updateDashboardIssue($,X,Q){try{return await $.updateIssue(X,Q)}catch(K){if(K instanceof C0&&K.isNotFound)return this.logger.warn(`Dashboard issue #${X} no longer exists in ${K.repository} (${K.status}); creating a replacement dashboard instead.`),null;throw K}}async findExistingDashboard($,X){try{if(this.logger.info("Searching for existing dashboard issue..."),X){this.logger.info(`Looking for specific dashboard issue #${X}`);let O=(await $.getIssues("open")).find((j)=>j.number===X);if(O)return this.logger.info(`Found specified dashboard issue #${O.number}: ${O.title}`),O;else return this.logger.warn(`Specified dashboard issue #${X} not found`),null}let Q=await $.getIssues("open");this.logger.info(`Found ${Q.length} open issues to search through`);for(let W of Q){let O=W.labels.includes("dashboard")&&W.labels.includes("dependencies"),j=W.title.toLowerCase().includes("dependency dashboard"),J=W.body.includes("This issue lists Buddy updates and detected dependencies");if(J||O&&j)return this.logger.info(`Found existing dashboard issue #${W.number}: ${W.title}`),this.logger.info(` - Labels: ${W.labels.join(", ")}`),this.logger.info(` - Title matches: ${j}`),this.logger.info(` - Body has marker: ${J}`),W}let K=Q.filter((W)=>W.labels.includes("dashboard")),H=Q.filter((W)=>W.labels.includes("dependencies")),Y=Q.filter((W)=>W.title.toLowerCase().includes("dependency dashboard"));if(this.logger.info("Dashboard search results:"),this.logger.info(` - Issues with 'dashboard' label: ${K.length}`),this.logger.info(` - Issues with 'dependencies' label: ${H.length}`),this.logger.info(` - Issues with 'dependency dashboard' in title: ${Y.length}`),K.length>0){this.logger.info("Issues with 'dashboard' label:");for(let W of K)this.logger.info(` - #${W.number}: ${W.title} (labels: ${W.labels.join(", ")})`)}return this.logger.info("No existing dashboard issue found"),null}catch(Q){throw this.logger.error(`Failed to search for existing dashboard: ${Q}`),Q}}}
|
|
104
|
-
export{K0 as Vc,r0 as Wc,t as Xc,r as Yc,T0 as Zc,$0 as _c};
|
package/dist/chunk-tws3npt7.js
DELETED
|
@@ -1,38 +0,0 @@
|
|
|
1
|
-
// @bun
|
|
2
|
-
import{Kc as T,Lc as v,Mc as y}from"./chunk-8fw0v7bv.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 L}from"./chunk-e68nf7cm.js";import{Bh as A,Ch as C,Fh as F}from"./chunk-hfjywbbc.js";import{Buffer as W}from"buffer";import{spawn as k}from"child_process";import M 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"}}class f{token;owner;repo;hasWorkflowPermissions;workflowToken;apiUrl;cache={pullRequests:new Map,issues:new Map};cacheTTL=120000;logger;constructor(Q,X,Y,Z=!1,$,J,x){this.token=Q;this.owner=X;this.repo=Y;this.hasWorkflowPermissions=Z;this.workflowToken=$;this.apiUrl=J?J.replace(/\/+$/,""):P(),this.logger=x??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}: ${C(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}: ${C(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 K=Bun.file("README.md");if(await K.exists()){let G=`${await K.text()}
|
|
3
|
-
|
|
4
|
-
<!-- Updated by Buddy -->
|
|
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(M.env.NODE_ENV==="test"||M.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(!(M.env.NODE_ENV==="test"||M.env.BUN_ENV==="test")){let V=Y.map((K)=>K.path.replace(/^\.\//,"").replace(/^\/+/,"")),j=y(V);if(j.length>0){this.logger.info(`\uD83D\uDD12 Regenerating lock files for: ${j.join(", ")}`);let K=M.cwd(),q=[];for(let G of j)try{let H=await v(G,K);if(H.success)for(let z of T())try{await this.runCommand("git",["add",z])}catch{}else q.push(`${G}: ${H.message}`)}catch(H){q.push(`${G}: ${H instanceof Error?H.message:String(H)}`)}if(q.length>0){let G=q.map((H)=>` - ${H}`).join(`
|
|
6
|
-
`);throw new I(`Lock file regeneration failed; refusing to open PR with stale lockfiles.
|
|
7
|
-
${G}`)}}}if((await this.runCommand("git",["status","--porcelain"])).trim()){await this.runCommand("git",["commit","-m",X]);let V=$.length>0&&this.hasWorkflowPermissions?this.getEffectiveToken(!0):void 0;await this.runCommand("git",["push","origin",Q,"--force-with-lease"],V),this.logger.info(`\u2705 Successfully recreated ${Q} with fresh changes from ${Z}: ${X}`)}else this.logger.info(`\u2139\uFE0F No file changes after resetting to ${Z} \u2014 skipping push to prevent PR auto-close`)}catch($){throw this.logger.error(`\u274C Failed to commit changes to ${Q} with Git CLI: ${C($)}`),$}}async commitChangesWithAPI(Q,X,Y,Z="main"){try{let $=Y.filter((z)=>z.path.includes(".github/workflows/")),J=Y.filter((z)=>!z.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((z)=>z.path).join(", ")}`),this.logger.warn("\u2139\uFE0F Workflow files will be skipped in this commit. Consider using a GitHub App with workflow permissions for workflow updates."),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, consider using a GitHub App with appropriate permissions.");return}else if($.length>0)this.logger.info(`\u2705 Including ${$.length} workflow file(s) with elevated permissions`);if(Y.some((z)=>z.path.endsWith("package.json")||z.path.endsWith("composer.json")))this.logger.warn("\u26A0\uFE0F Committing manifest files via API \u2014 lock files will not be updated."),this.logger.warn(" Lock file regeneration requires the Git CLI commit path (local filesystem).");this.logger.info(`\uD83D\uDD04 Recreating ${Q} from ${Z} via API (Renovate-style)...`);let V=(await this.apiRequest(`GET /repos/${this.owner}/${this.repo}/git/ref/heads/${Z}`)).object.sha,K=(await this.apiRequest(`GET /repos/${this.owner}/${this.repo}/git/commits/${V}`)).tree.sha;await S(Y,async(z)=>{let U=z.split("/").map((O)=>encodeURIComponent(O)).join("/");try{return await this.apiRequest(`GET /repos/${this.owner}/${this.repo}/contents/${U}?ref=${encodeURIComponent(Z)}`),!0}catch(O){if(O.message?.includes("404"))return!1;throw O}});let q=[];for(let z of Y){let U=R(z.path);if(z.type==="delete")q.push({path:U,mode:"100644",type:"blob",sha:null});else{let O=await this.apiRequest(`POST /repos/${this.owner}/${this.repo}/git/blobs`,{content:W.from(z.content).toString("base64"),encoding:"base64"});q.push({path:U,mode:"100644",type:"blob",sha:O.sha})}}let G=await this.apiRequest(`POST /repos/${this.owner}/${this.repo}/git/trees`,{base_tree:K,tree:q});if(G.sha===K){this.logger.info(`\u2139\uFE0F No file changes relative to ${Z} \u2014 skipping push to prevent PR auto-close`);return}let H=await this.apiRequest(`POST /repos/${this.owner}/${this.repo}/git/commits`,{message:X,tree:G.sha,parents:[V],author:{name:"github-actions[bot]",email:"41898282+github-actions[bot]@users.noreply.github.com"},committer:{name:"github-actions[bot]",email:"41898282+github-actions[bot]@users.noreply.github.com"}});await this.apiRequest(`PATCH /repos/${this.owner}/${this.repo}/git/refs/heads/${Q}`,{sha:H.sha,force:!0}),this.logger.info(`\u2705 Committed changes to ${Q}: ${X}`)}catch($){throw this.logger.error(`\u274C Failed to commit changes to ${Q}: ${C($)}`),$}}async createPullRequest(Q){try{return await this.createPullRequestWithCLI(Q)}catch(X){return this.logger.warn(`\u26A0\uFE0F GitHub CLI failed, falling back to API: ${X}`),await this.createPullRequestWithAPI(Q)}}async createPullRequestWithCLI(Q){try{let X=["pr","create","--title",Q.title,"--body",Q.body,"--head",Q.head,"--base",Q.base];if(Q.draft)X.push("--draft");if(Q.reviewers&&Q.reviewers.length>0)this.logger.info(`\uD83D\uDD0D Adding reviewers via CLI: ${Q.reviewers.join(", ")}`),X.push("--reviewer",Q.reviewers.join(","));if(Q.assignees&&Q.assignees.length>0)X.push("--assignee",Q.assignees.join(","));let Z=(await this.runCommand("gh",X)).match(/https:\/\/github\.com\/[^/]+\/[^/]+\/pull\/(\d+)/);if(!Z)throw Error("Failed to parse PR number from GitHub CLI output");let $=Number.parseInt(Z[1]),J=Z[0];if(this.logger.info(`\u2705 Created PR #${$}: ${Q.title}`),Q.labels&&Q.labels.length>0)try{await this.apiRequest(`POST /repos/${this.owner}/${this.repo}/issues/${$}/labels`,{labels:Q.labels}),this.logger.info(`\u2705 Added labels to PR #${$}: ${Q.labels.join(", ")}`)}catch(x){this.logger.warn(`\u26A0\uFE0F Failed to add labels: ${x}`);for(let _ of Q.labels)try{await this.apiRequest(`POST /repos/${this.owner}/${this.repo}/issues/${$}/labels`,{labels:[_]})}catch(V){this.logger.warn(`\u26A0\uFE0F Failed to add label '${_}': ${V}`)}}return{number:$,title:Q.title,body:Q.body,head:Q.head,base:Q.base,state:"open",url:J,createdAt:new Date,updatedAt:new Date,author:"github-actions[bot]",reviewers:Q.reviewers||[],assignees:Q.assignees||[],labels:Q.labels||[],draft:Q.draft||!1}}catch(X){throw this.logger.error(`\u274C Failed to create PR with GitHub CLI: ${Q.title}: ${C(X)}`),X}}async createPullRequestWithAPI(Q){try{let X=await this.apiRequest(`POST /repos/${this.owner}/${this.repo}/pulls`,{title:Q.title,body:Q.body,head:Q.head,base:Q.base,draft:Q.draft||!1});if(Q.reviewers&&Q.reviewers.length>0)try{this.logger.info(`\uD83D\uDD0D Adding reviewers to PR #${X.number}: ${Q.reviewers.join(", ")}`),await this.apiRequest(`POST /repos/${this.owner}/${this.repo}/pulls/${X.number}/requested_reviewers`,{reviewers:Q.reviewers,team_reviewers:Q.teamReviewers||[]}),this.logger.info(`\u2705 Successfully added reviewers: ${Q.reviewers.join(", ")}`)}catch(Y){this.logger.error(`\u274C Failed to add reviewers: ${Y}`),this.logger.error(` Reviewers: ${Q.reviewers.join(", ")}`),this.logger.error(` Repository: ${this.owner}/${this.repo}`),this.logger.error(` PR: #${X.number}`)}if(Q.assignees&&Q.assignees.length>0)try{await this.apiRequest(`POST /repos/${this.owner}/${this.repo}/issues/${X.number}/assignees`,{assignees:Q.assignees})}catch(Y){this.logger.warn(`\u26A0\uFE0F Failed to add assignees: ${Y}`)}if(Q.labels&&Q.labels.length>0)try{await this.apiRequest(`POST /repos/${this.owner}/${this.repo}/issues/${X.number}/labels`,{labels:Q.labels})}catch(Y){this.logger.warn(`\u26A0\uFE0F Failed to add labels: ${Y}`);for(let Z of Q.labels)try{await this.apiRequest(`POST /repos/${this.owner}/${this.repo}/issues/${X.number}/labels`,{labels:[Z]})}catch($){this.logger.warn(`\u26A0\uFE0F Failed to add label '${Z}': ${$}`)}}return this.logger.info(`\u2705 Created PR #${X.number}: ${Q.title}`),{number:X.number,title:X.title,body:X.body||"",head:X.head.ref,base:X.base.ref,state:X.state,url:X.html_url,createdAt:new Date(X.created_at),updatedAt:new Date(X.updated_at),author:X.user.login,reviewers:Q.reviewers||[],assignees:Q.assignees||[],labels:Q.labels||[],draft:X.draft}}catch(X){throw this.logger.error(`\u274C Failed to create PR with API: ${Q.title}: ${C(X)}`),X}}getEffectiveToken(Q=!1){if(Q&&this.workflowToken)return this.workflowToken;return this.token}async runCommand(Q,X,Y){let Z=Y||this.token;return new Promise(($,J)=>{let x=k(Q,X,{stdio:"pipe",env:{...M.env,GITHUB_TOKEN:Z,GH_TOKEN:Z}}),_="",V="";x.stdout?.on("data",(j)=>{_+=j.toString()}),x.stderr?.on("data",(j)=>{V+=j.toString()}),x.on("close",(j)=>{if(j===0)$(_);else J(Error(`Command failed with code ${j}: ${g(V,Z)}`))}),x.on("error",(j)=>{J(j)})})}async getPullRequests(Q="open"){let X=`${Q}`,Y=this.cache.pullRequests.get(X);if(Y&&this.isCacheValid(Y.timestamp))return this.logger.info(`\uD83D\uDCE6 Using cached PRs (state: ${Q}, ${Y.data.length} PRs)`),Y.data;try{let J=[];for(let _=1;_<=20;_++){let V=await this.apiRequestWithRetry(`GET /repos/${this.owner}/${this.repo}/pulls?state=${Q}&per_page=100&page=${_}`);if(!Array.isArray(V)||V.length===0)break;if(J.push(...V),V.length<100)break}let x=J.map((_)=>({number:_.number,title:_.title,body:_.body??"",head:_.head.ref,base:_.base.ref,state:_.state,url:_.html_url,createdAt:new Date(_.created_at),updatedAt:new Date(_.updated_at),mergedAt:_.merged_at?new Date(_.merged_at):void 0,author:_.user.login,reviewers:_.requested_reviewers?.map((V)=>V.login)??[],assignees:_.assignees?.map((V)=>V.login)??[],labels:_.labels?.map((V)=>V.name)??[],draft:_.draft}));return this.cache.pullRequests.set(X,{data:x,timestamp:Date.now()}),this.logger.info(`\u2705 Fetched and cached ${x.length} PRs (state: ${Q})`),x}catch(Z){throw this.logger.error(`\u274C Failed to get PRs: ${C(Z)}`),Z}}async updatePullRequest(Q,X){this.cache.pullRequests.clear();try{let Y={};if(X.title)Y.title=X.title;if(X.body)Y.body=X.body;if(X.base)Y.base=X.base;if(X.draft!==void 0)Y.draft=X.draft;let Z=await this.apiRequest(`PATCH /repos/${this.owner}/${this.repo}/pulls/${Q}`,Y);if(X.labels&&X.labels.length>0)try{await this.apiRequest(`PUT /repos/${this.owner}/${this.repo}/issues/${Q}/labels`,{labels:X.labels}),this.logger.info(`\u2705 Updated labels for PR #${Q}: ${X.labels.join(", ")}`)}catch($){this.logger.warn(`\u26A0\uFE0F Failed to update labels for PR #${Q}: ${$}`);for(let J of X.labels)try{await this.apiRequest(`POST /repos/${this.owner}/${this.repo}/issues/${Q}/labels`,{labels:[J]})}catch(x){this.logger.warn(`\u26A0\uFE0F Failed to add label '${J}' to PR #${Q}: ${x}`)}}if(X.reviewers&&X.reviewers.length>0)try{this.logger.info(`\uD83D\uDD0D Adding reviewers to existing PR #${Q}: ${X.reviewers.join(", ")}`),await this.apiRequest(`POST /repos/${this.owner}/${this.repo}/pulls/${Q}/requested_reviewers`,{reviewers:X.reviewers,team_reviewers:X.teamReviewers||[]}),this.logger.info(`\u2705 Updated reviewers for PR #${Q}: ${X.reviewers.join(", ")}`)}catch($){this.logger.error(`\u274C Failed to update reviewers for PR #${Q}: ${$}`),this.logger.error(` Reviewers: ${X.reviewers.join(", ")}`),this.logger.error(` Repository: ${this.owner}/${this.repo}`)}if(X.assignees&&X.assignees.length>0)try{await this.runCommand("gh",["issue","edit",Q.toString(),"--add-assignee",X.assignees.join(",")]),this.logger.info(`\u2705 Updated assignees for PR #${Q}: ${X.assignees.join(", ")}`)}catch($){this.logger.warn(`\u26A0\uFE0F Failed to update assignees for PR #${Q}: ${$}`)}return this.logger.info(`\u2705 Updated PR #${Q}`),{number:Z.number,title:Z.title,body:Z.body||"",head:Z.head.ref,base:Z.base.ref,state:Z.state,url:Z.html_url,createdAt:new Date(Z.created_at),updatedAt:new Date(Z.updated_at),author:Z.user.login,reviewers:[],assignees:[],labels:X.labels||[],draft:Z.draft}}catch(Y){throw this.logger.error(`\u274C Failed to update PR #${Q}: ${C(Y)}`),Y}}async closePullRequest(Q){this.cache.pullRequests.clear();try{await this.apiRequest(`PATCH /repos/${this.owner}/${this.repo}/pulls/${Q}`,{state:"closed"}),this.logger.info(`\u2705 Closed PR #${Q}`)}catch(X){throw this.logger.error(`\u274C Failed to close PR #${Q}: ${C(X)}`),X}}async reopenPullRequest(Q){this.cache.pullRequests.clear();try{await this.apiRequest(`PATCH /repos/${this.owner}/${this.repo}/pulls/${Q}`,{state:"open"}),this.logger.info(`\u2705 Reopened PR #${Q}`)}catch(X){throw this.logger.error(`\u274C Failed to reopen PR #${Q}: ${C(X)}`),X}}async createComment(Q,X){try{await this.apiRequest(`POST /repos/${this.owner}/${this.repo}/issues/${Q}/comments`,{body:X}),this.logger.info(`\uD83D\uDCAC Added comment to PR #${Q}`)}catch(Y){throw this.logger.error(`\u274C Failed to add comment to PR #${Q}: ${C(Y)}`),Y}}async mergePullRequest(Q,X="merge"){try{let Y=X==="rebase"?"rebase":X==="squash"?"squash":"merge",$=(await this.apiRequest(`GET /repos/${this.owner}/${this.repo}/pulls/${Q}`)).head.ref;await this.apiRequest(`PUT /repos/${this.owner}/${this.repo}/pulls/${Q}/merge`,{merge_method:Y}),this.logger.info(`\u2705 Merged PR #${Q} using ${X}`);try{await this.deleteBranch($),this.logger.info(`\uD83E\uDDF9 Cleaned up branch ${$} after merge`)}catch(J){this.logger.warn(`\u26A0\uFE0F Failed to clean up branch ${$}:`,J)}}catch(Y){throw this.logger.error(`\u274C Failed to merge PR #${Q}: ${C(Y)}`),Y}}async getPullRequestHeadSha(Q){try{return(await this.apiRequest(`GET /repos/${this.owner}/${this.repo}/pulls/${Q}`))?.head?.sha??""}catch(X){return this.logger.debug(`Could not read head SHA for PR #${Q}: ${C(X)}`),""}}async hasWriteAccess(Q){try{let X=await this.apiRequest(`GET /repos/${this.owner}/${this.repo}/collaborators/${encodeURIComponent(Q)}/permission`);return["write","maintain","admin"].includes(X?.permission)}catch(X){if(X instanceof A&&X.isNotFound)return!1;return this.logger.warn(`\u26A0\uFE0F Could not resolve permissions for @${Q}: ${C(X)}`),!1}}async reactToComment(Q,X){try{await this.apiRequest(`POST /repos/${this.owner}/${this.repo}/issues/comments/${Q}/reactions`,{content:X})}catch(Y){this.logger.debug(`Could not react to comment ${Q}: ${C(Y)}`)}}async getWorkflowRunLogs(Q){try{let X=await L(`${this.apiUrl}/repos/${this.owner}/${this.repo}/actions/runs/${Q}/logs`,{headers:{Authorization:`Bearer ${this.token}`,Accept:"application/vnd.github+json","User-Agent":"buddy"}});if(!X.ok)return this.logger.debug(`Could not fetch logs for run ${Q}: ${X.status}`),null;return W.from(await X.arrayBuffer()).toString("utf-8").replace(/[^\t\n\r\x20-\x7E]+/g," ")}catch(X){return this.logger.debug(`Could not fetch logs for run ${Q}: ${C(X)}`),null}}async listWorkflowRuns(Q,X={}){let Y=new URLSearchParams({branch:Q,per_page:String(X.limit??20)});if(X.status)Y.set("status",X.status);try{return((await this.apiRequest(`GET /repos/${this.owner}/${this.repo}/actions/runs?${Y.toString()}`))?.workflow_runs??[]).map((J)=>({id:Number(J.id),name:String(J.name??""),headSha:String(J.head_sha??""),headBranch:String(J.head_branch??Q),status:E(J.status),conclusion:w(J.conclusion),createdAt:new Date(String(J.created_at??new Date().toISOString()))}))}catch(Z){return this.logger.debug(`Could not list workflow runs for ${Q}: ${C(Z)}`),[]}}async rerunWorkflowRun(Q,X=!0){let Y=X?"rerun-failed-jobs":"rerun";try{let Z=await L(`${this.apiUrl}/repos/${this.owner}/${this.repo}/actions/runs/${Q}/${Y}`,{method:"POST",headers:{Authorization:`Bearer ${this.token}`,Accept:"application/vnd.github+json","User-Agent":"buddy"}});if(!Z.ok)return this.logger.warn(`Could not re-run workflow run ${Q}: ${Z.status} ${Z.statusText}`),!1;return!0}catch(Z){return this.logger.warn(`Could not re-run workflow run ${Q}: ${C(Z)}`),!1}}async createCheckRun(Q,X,Y){try{await this.apiRequest(`POST /repos/${this.owner}/${this.repo}/check-runs`,{name:Q,head_sha:X,status:"completed",conclusion:Y.conclusion,completed_at:new Date().toISOString(),output:{title:Y.title,summary:Y.summary}}),this.logger.info(`\u2705 Reported check run ${Q}: ${Y.conclusion}`)}catch(Z){this.logger.warn(`\u26A0\uFE0F Could not report check run ${Q}: ${C(Z)}`)}}async getFileContent(Q,X){try{let Y=await this.apiRequest(`GET /repos/${this.owner}/${this.repo}/contents/${encodeURIComponent(Q)}?ref=${encodeURIComponent(X)}`);if(!Y?.content)return null;return W.from(Y.content,Y.encoding==="base64"?"base64":"utf-8").toString("utf-8")}catch(Y){if(Y instanceof A&&Y.isNotFound)return null;throw Y}}async getPullRequestDiff(Q){let X=await L(`${this.apiUrl}/repos/${this.owner}/${this.repo}/pulls/${Q}`,{headers:{Authorization:`Bearer ${this.token}`,Accept:"application/vnd.github.v3.diff","User-Agent":"buddy"}});if(!X.ok)throw new A(`Failed to fetch diff for PR #${Q}: ${X.status} ${X.statusText}`,X.status,"GET",`${this.apiUrl}/repos/${this.owner}/${this.repo}/pulls/${Q}`,`${this.owner}/${this.repo}`);return await X.text()}async createReview(Q,X){let Y=`POST /repos/${this.owner}/${this.repo}/pulls/${Q}/reviews`;try{return await this.apiRequest(Y,{body:X.body,event:X.event,...X.comments?.length?{comments:X.comments}:{}}),this.logger.success(`\u2705 Posted review on PR #${Q} (${X.comments?.length??0} inline comment(s))`),{posted:!0,inlineComments:X.comments?.length??0}}catch(Z){if(!X.comments?.length)throw this.logger.error(`\u274C Failed to post review on PR #${Q}: ${C(Z)}`),Z;return this.logger.warn(`\u26A0\uFE0F Review with inline comments was rejected (${C(Z)}); posting the summary alone`),await this.apiRequest(Y,{body:X.body,event:X.event}),{posted:!0,inlineComments:0}}}async enableAutoMerge(Q,X="squash"){let Y=await this.apiRequest(`GET /repos/${this.owner}/${this.repo}/pulls/${Q}`),Z=`mutation($pullRequestId: ID!, $mergeMethod: PullRequestMergeMethod!) {
|
|
8
|
-
enablePullRequestAutoMerge(input: { pullRequestId: $pullRequestId, mergeMethod: $mergeMethod }) {
|
|
9
|
-
pullRequest { number }
|
|
10
|
-
}
|
|
11
|
-
}`,$=await this.graphqlRequest(`mutation($pullRequestId: ID!, $mergeMethod: PullRequestMergeMethod!) {
|
|
12
|
-
enablePullRequestAutoMerge(input: { pullRequestId: $pullRequestId, mergeMethod: $mergeMethod }) {
|
|
13
|
-
pullRequest { number }
|
|
14
|
-
}
|
|
15
|
-
}`,{pullRequestId:Y.node_id,mergeMethod:X.toUpperCase()});if($.errors?.length){let J=$.errors.map((x)=>x.message).join("; ");return this.logger.info(`\u2139\uFE0F GitHub could not queue auto-merge for PR #${Q}: ${J}`),!1}return this.logger.success(`\u2705 Auto-merge queued for PR #${Q} (${X})`),!0}async listReviewThreads(Q){try{let Y=await this.graphqlRequest(`query($owner: String!, $repo: String!, $number: Int!) {
|
|
16
|
-
repository(owner: $owner, name: $repo) {
|
|
17
|
-
pullRequest(number: $number) {
|
|
18
|
-
reviewThreads(first: 100) {
|
|
19
|
-
nodes {
|
|
20
|
-
id
|
|
21
|
-
isResolved
|
|
22
|
-
path
|
|
23
|
-
comments(first: 10) { nodes { author { login } } }
|
|
24
|
-
}
|
|
25
|
-
}
|
|
26
|
-
}
|
|
27
|
-
}
|
|
28
|
-
}`,{owner:this.owner,repo:this.repo,number:Q});if(Y.errors?.length)return this.logger.debug(`Could not read review threads on #${Q}: ${Y.errors.map(($)=>$.message).join("; ")}`),[];return(Y.data?.repository?.pullRequest?.reviewThreads?.nodes??[]).filter(Boolean).map(($)=>({id:String($.id),isResolved:Boolean($.isResolved),...$.path?{path:String($.path)}:{},authorLogins:($.comments?.nodes??[]).map((J)=>J?.author?.login).filter((J)=>typeof J==="string")}))}catch(Y){return this.logger.debug(`Could not read review threads on #${Q}: ${C(Y)}`),[]}}async resolveReviewThread(Q,X){try{let Z=await this.graphqlRequest(`mutation($threadId: ID!) {
|
|
29
|
-
resolveReviewThread(input: { threadId: $threadId }) {
|
|
30
|
-
thread { isResolved }
|
|
31
|
-
}
|
|
32
|
-
}`,{threadId:X});if(Z.errors?.length)return this.logger.warn(`Could not resolve review thread: ${Z.errors.map(($)=>$.message).join("; ")}`),!1;return Boolean(Z.data?.resolveReviewThread?.thread?.isResolved)}catch(Z){return this.logger.warn(`Could not resolve review thread: ${C(Z)}`),!1}}async getPullRequestChecksState(Q){try{let Y=(await this.apiRequest(`GET /repos/${this.owner}/${this.repo}/pulls/${Q}`)).head.sha,[Z,$]=await Promise.all([this.apiRequest(`GET /repos/${this.owner}/${this.repo}/commits/${Y}/status`),this.apiRequest(`GET /repos/${this.owner}/${this.repo}/commits/${Y}/check-runs?per_page=100`)]),J=$?.check_runs??[],x=(Z?.statuses?.length??0)>0;if(J.length===0&&!x)return"none";if(J.some((j)=>j.conclusion!==null&&["failure","cancelled","timed_out","action_required"].includes(j.conclusion))||Z?.state==="failure"||Z?.state==="error")return"failure";if(J.some((j)=>j.status!=="completed")||Z?.state==="pending")return"pending";return"success"}catch(X){return this.logger.warn(`\u26A0\uFE0F Could not read check state for PR #${Q}: ${C(X)}`),"pending"}}async graphqlRequest(Q,X){let Y=await L(`${this.apiUrl}/graphql`,{method:"POST",headers:{Authorization:`Bearer ${this.token}`,"Content-Type":"application/json","User-Agent":"buddy"},body:JSON.stringify({query:Q,variables:X})});if(!Y.ok)throw new A(`GraphQL request failed: ${Y.status} ${Y.statusText}`,Y.status,"POST",`${this.apiUrl}/graphql`,`${this.owner}/${this.repo}`);return await Y.json()}async deleteBranch(Q){try{await this.runCommand("git",["push","origin","--delete",Q]),this.logger.info(`\u2705 Deleted branch ${Q} via git`)}catch(X){try{await this.runCommand("git",["branch","-D",Q])}catch{}if(/remote ref does not exist|unable to delete '[^']*': remote ref/i.test(C(X))){this.logger.info(`\u2139\uFE0F Branch ${Q} was already gone`);return}throw this.logger.warn(`\u26A0\uFE0F Failed to delete remote branch ${Q}: ${C(X)}`),X}}async getBuddyBranches(){try{let Q=await this.runCommand("git",["branch","-r","--format=%(refname:short) %(objectname) %(committerdate:iso8601)"]),X=[];for(let Y of Q.split(`
|
|
33
|
-
`)){let Z=Y.trim();if(!Z)continue;let $=Z.split(" ");if($.length<3)continue;let J=$[0],x=$[1],_=$.slice(2).join(" "),V=J.replace(/^origin\//,"");if(!V.startsWith("buddy/"))continue;try{let j=new Date(_);X.push({name:V,sha:x,lastCommitDate:j})}catch{this.logger.warn(`\u26A0\uFE0F Failed to parse date for branch ${V}: ${_}`),X.push({name:V,sha:x,lastCommitDate:new Date(0)})}}return this.logger.info(`\uD83D\uDD0D Found ${X.length} buddy branches using local git`),X}catch(Q){return this.logger.warn("\u26A0\uFE0F Failed to fetch buddy branches via git, falling back to API:",Q),this.getBuddyBranchesViaAPI()}}async getBuddyBranchesViaAPI(){try{let Q=[],X=1,Y=100;while(!0){let J=await this.apiRequest(`GET /repos/${this.owner}/${this.repo}/branches?per_page=${Y}&page=${X}`);if(!J||J.length===0)break;if(Q=Q.concat(J),J.length<Y)break;X++}this.logger.info(`\uD83D\uDD0D Found ${Q.length} total branches in repository`);let Z=Q.filter((J)=>J.name.startsWith("buddy/"));return this.logger.info(`\uD83E\uDD16 Found ${Z.length} buddy branches`),await Promise.all(Z.map(async(J)=>{try{let x=await this.apiRequest(`GET /repos/${this.owner}/${this.repo}/commits/${J.commit.sha}`);return{name:J.name,sha:J.commit.sha,lastCommitDate:new Date(x.commit.committer.date)}}catch(x){return this.logger.warn(`\u26A0\uFE0F Failed to get commit info for branch ${J.name}: ${C(x)}`),{name:J.name,sha:J.commit.sha,lastCommitDate:new Date(0)}}}))}catch(Q){return this.logger.warn("\u26A0\uFE0F Failed to fetch buddy branches:",Q),[]}}async getOrphanedBuddyBranches(){try{let Q=await this.getBuddyBranches(),X=await this.getOpenPRBranches();return Q.filter((Z)=>!X.has(Z.name))}catch(Q){return this.logger.warn("\u26A0\uFE0F Failed to identify orphaned branches:",Q),[]}}prDetectionSuccessful=!1;async getOpenPRBranches(){this.prDetectionSuccessful=!1;try{let Q=await this.getPullRequests("open"),X=new Set(Q.map((Y)=>Y.head).filter((Y)=>Y.startsWith("buddy/")));return this.logger.info(`\uD83D\uDD0D GitHub API reports ${Q.length} open PR(s); ${X.size} are buddy branches`),this.logger.info(`\uD83D\uDEE1\uFE0F Protecting ${X.size} branches with confirmed open PRs`),this.prDetectionSuccessful=!0,X}catch(Q){this.logger.warn("\u26A0\uFE0F Failed to fetch open PRs via API, falling back to age-based protection:",Q);try{let X=await this.getBuddyBranches(),Y=new Date;Y.setDate(Y.getDate()-30);let Z=new Set;for(let $ of X)if($.lastCommitDate>Y)Z.add($.name);return this.logger.info(`\uD83D\uDEE1\uFE0F Conservative fallback: protecting ${Z.size} branches newer than 30 days`),Z}catch{return this.logger.info("\u26A0\uFE0F Could not enumerate branches for age-based fallback"),new Set}}}async cleanupStaleBranches(Q=7,X=!1){this.logger.info("\uD83D\uDD0D Looking for buddy branches without open PRs...");let Y=await this.getOrphanedBuddyBranches();this.logger.info(`\uD83D\uDD0D Found ${Y.length} orphaned buddy branches (no associated open PRs)`);let Z=Y;if(this.prDetectionSuccessful)this.logger.info(`\uD83C\uDFAF PR detection successful - cleaning up ALL ${Z.length} orphaned branches (any age)`);else{let V=new Date;V.setDate(V.getDate()-Q),Z=Y.filter((j)=>j.lastCommitDate<V),this.logger.info(`\u26A0\uFE0F PR detection failed - only deleting branches older than ${Q} days`),this.logger.info(`\uD83D\uDD0D Found ${Z.length} stale buddy branches (older than ${Q} days)`)}if(Z.length>0){if(this.logger.info("\uD83D\uDCCB Sample of branches to delete:"),Z.slice(0,5).forEach((V)=>{let j=Math.floor((Date.now()-V.lastCommitDate.getTime())/86400000);this.logger.info(` - ${V.name} (${j} days old)`)}),Z.length>5)this.logger.info(` ... and ${Z.length-5} more`)}if(Z.length===0)return this.logger.info("\u2705 No branches to clean up!"),{deleted:[],failed:[]};let $=Z;if(X)return this.logger.info("\uD83D\uDD0D [DRY RUN] Would delete the following branches:"),$.forEach((V)=>{let j=Math.floor((Date.now()-V.lastCommitDate.getTime())/86400000);this.logger.info(` - ${V.name} (${j} days old, last commit: ${V.lastCommitDate.toISOString()})`)}),{deleted:$.map((V)=>V.name),failed:[]};let J=[],x=[];this.logger.info(`\uD83E\uDDF9 Cleaning up ${$.length} stale branches...`);let _=5;for(let V=0;V<$.length;V+=_){let j=$.slice(V,V+_),K=Math.floor(V/_)+1,q=Math.ceil($.length/_);this.logger.info(`\uD83D\uDD04 Processing batch ${K}/${q} (${j.length} branches)`);for(let G of j){try{await this.deleteBranch(G.name),J.push(G.name),this.logger.info(`\u2705 Deleted: ${G.name}`)}catch(H){x.push(G.name),this.logger.warn(`\u274C Failed to delete ${G.name}: ${C(H)}`)}await new Promise((H)=>setTimeout(H,200))}if(V+_<$.length)this.logger.info(`\u23F3 Waiting ${3} seconds before next batch...`),await new Promise((H)=>setTimeout(H,3000))}if(this.logger.info("\uD83C\uDF89 Cleanup complete!"),this.logger.info(` \u2705 Successfully deleted: ${J.length} branches`),this.logger.info(` \u274C Failed to delete: ${x.length} branches`),x.length>0)this.logger.info("\u274C Failed branches:"),x.forEach((V)=>this.logger.info(` - ${V}`));return{deleted:J,failed:x}}async apiRequest(Q,X,Y,Z=0){let[$,J]=Q.split(" "),x=`${this.apiUrl}${J}`,_=Y||this.token,V={method:$,headers:{Authorization:`Bearer ${_}`,Accept:"application/vnd.github.v3+json","Content-Type":"application/json","User-Agent":"buddy"}};if(X&&($==="POST"||$==="PATCH"||$==="PUT"))V.body=JSON.stringify(X);let j=await L(x,{...V,retries:Z,onRetry:({delayMs:K,reason:q})=>this.logger.info(`\u23F3 ${q} on ${$} ${J}, retrying in ${Math.round(K/1000)}s...`)});if(!j.ok){let K=await j.text(),q=_?"token present ([REDACTED])":"NO TOKEN \u2014 ensure GITHUB_TOKEN or BUDDY_TOKEN is set";throw new A(`GitHub API error: ${j.status} ${j.statusText}
|
|
34
|
-
URL: ${$} ${x}
|
|
35
|
-
Auth: ${q}
|
|
36
|
-
Repo: ${this.owner}/${this.repo}
|
|
37
|
-
${K}`,j.status,$,x,`${this.owner}/${this.repo}`,K)}if(j.headers.get("content-type")?.includes("application/json"))return j.json();return j.text()}async apiRequestWithRetry(Q,X,Y=3){return this.apiRequest(Q,X,void 0,Math.max(0,Y-1))}async createIssue(Q){this.cache.issues.clear();try{let X=await this.apiRequestWithRetry(`POST /repos/${this.owner}/${this.repo}/issues`,{title:Q.title,body:Q.body,assignees:Q.assignees||[],labels:Q.labels||[],milestone:Q.milestone});return this.logger.info(`\u2705 Created issue #${X.number}: ${Q.title}`),{number:X.number,title:X.title,body:X.body,state:X.state,url:X.html_url,createdAt:new Date(X.created_at),updatedAt:new Date(X.updated_at),closedAt:X.closed_at?new Date(X.closed_at):void 0,author:X.user.login,assignees:X.assignees?.map((Y)=>Y.login)||[],labels:X.labels?.map((Y)=>typeof Y==="string"?Y:Y.name)||[],pinned:!1}}catch(X){throw this.logger.error(`\u274C Failed to create issue: ${Q.title}: ${C(X)}`),X}}async getIssues(Q="open"){let X=`${Q}`,Y=this.cache.issues.get(X);if(Y&&this.isCacheValid(Y.timestamp))return this.logger.info(`\uD83D\uDCE6 Using cached issues (state: ${Q}, ${Y.data.length} issues)`),Y.data;try{let J=[];for(let _=1;_<=20;_++){let V=await this.apiRequestWithRetry(`GET /repos/${this.owner}/${this.repo}/issues?state=${Q}&sort=updated&direction=desc&per_page=100&page=${_}`);if(!Array.isArray(V)||V.length===0)break;if(J.push(...V),V.length<100)break}let x=J.filter((_)=>!_.pull_request).map((_)=>({number:_.number,title:_.title,body:_.body||"",state:_.state,url:_.html_url,createdAt:new Date(_.created_at),updatedAt:new Date(_.updated_at),closedAt:_.closed_at?new Date(_.closed_at):void 0,author:_.user.login,assignees:_.assignees?.map((V)=>V.login)||[],labels:_.labels?.map((V)=>typeof V==="string"?V:V.name)||[],pinned:!1}));return this.cache.issues.set(X,{data:x,timestamp:Date.now()}),this.logger.info(`\u2705 Fetched and cached ${x.length} issues (state: ${Q})`),x}catch(Z){throw this.logger.error("\u274C Failed to get issues:",Z),Z}}async updateIssue(Q,X){this.cache.issues.clear();try{let Y={};if(X.title!==void 0)Y.title=X.title;if(X.body!==void 0)Y.body=X.body;if(X.assignees!==void 0)Y.assignees=X.assignees;if(X.labels!==void 0)Y.labels=X.labels;if(X.milestone!==void 0)Y.milestone=X.milestone;let Z=await this.apiRequestWithRetry(`PATCH /repos/${this.owner}/${this.repo}/issues/${Q}`,Y);return this.logger.info(`\u2705 Updated issue #${Q}: ${Z.title}`),{number:Z.number,title:Z.title,body:Z.body,state:Z.state,url:Z.html_url,createdAt:new Date(Z.created_at),updatedAt:new Date(Z.updated_at),closedAt:Z.closed_at?new Date(Z.closed_at):void 0,author:Z.user.login,assignees:Z.assignees?.map(($)=>$.login)||[],labels:Z.labels?.map(($)=>typeof $==="string"?$:$.name)||[],pinned:!1}}catch(Y){throw this.logger.error(`\u274C Failed to update issue #${Q}: ${C(Y)}`),Y}}async closeIssue(Q){this.cache.issues.clear();try{await this.apiRequestWithRetry(`PATCH /repos/${this.owner}/${this.repo}/issues/${Q}`,{state:"closed"}),this.logger.info(`\u2705 Closed issue #${Q}`)}catch(X){throw this.logger.error(`\u274C Failed to close issue #${Q}: ${C(X)}`),X}}async pinIssue(Q){return await this.setIssuePinned(Q,!0)}async unpinIssue(Q){return await this.setIssuePinned(Q,!1)}async setIssuePinned(Q,X){let Y=X?"pin":"unpin";try{let Z=await this.apiRequest(`GET /repos/${this.owner}/${this.repo}/issues/${Q}`),$=X?"mutation($issueId: ID!) { pinIssue(input: { issueId: $issueId }) { issue { number } } }":"mutation($issueId: ID!) { unpinIssue(input: { issueId: $issueId }) { issue { number } } }",J=await this.graphqlRequest($,{issueId:Z.node_id});if(J.errors?.length){let x=J.errors.map((_)=>_.message).join("; ");return this.logger.info(`\u26A0\uFE0F Failed to ${Y} issue #${Q}: ${x}`),!1}return this.logger.info(`\uD83D\uDCCC ${X?"Pinned":"Unpinned"} issue #${Q}`),!0}catch(Z){return this.logger.info(`\u26A0\uFE0F Failed to ${Y} issue #${Q}: ${C(Z)}`),!1}}}
|
|
38
|
-
export{f as Jc};
|